repo
stringlengths
1
152
file
stringlengths
15
205
code
stringlengths
0
41.6M
file_length
int64
0
41.6M
avg_line_length
float64
0
1.81M
max_line_length
int64
0
12.7M
extension_type
stringclasses
90 values
psutil
psutil-master/psutil/_psutil_common.h
/* * Copyright (c) 2009, Giampaolo Rodola'. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include <Python.h> // ==================================================================== // --- Global vars / constants // ==================================================================== extern int PSUTIL_DEBUG; // a signaler for connections without an actual status static const int PSUTIL_CONN_NONE = 128; // strncpy() variant which appends a null terminator. #define PSUTIL_STRNCPY(dst, src, n) \ strncpy(dst, src, n - 1); \ dst[n - 1] = '\0' // ==================================================================== // --- Backward compatibility with missing Python.h APIs // ==================================================================== #if PY_MAJOR_VERSION < 3 // On Python 2 we just return a plain byte string, which is never // supposed to raise decoding errors, see: // https://github.com/giampaolo/psutil/issues/1040 #define PyUnicode_DecodeFSDefault PyString_FromString #define PyUnicode_DecodeFSDefaultAndSize PyString_FromStringAndSize #endif #if defined(PSUTIL_WINDOWS) && \ defined(PYPY_VERSION) && \ !defined(PyErr_SetFromWindowsErrWithFilename) PyObject *PyErr_SetFromWindowsErrWithFilename(int ierr, const char *filename); #endif // --- _Py_PARSE_PID // SIZEOF_INT|LONG is missing on Linux + PyPy (only?). // SIZEOF_PID_T is missing on Windows + Python2. // In this case we guess it from setup.py. It's not 100% bullet proof, // If wrong we'll probably get compiler warnings. // FWIW on all UNIX platforms I've seen pid_t is defined as an int. // _getpid() on Windows also returns an int. #if !defined(SIZEOF_INT) #define SIZEOF_INT 4 #endif #if !defined(SIZEOF_LONG) #define SIZEOF_LONG 8 #endif #if !defined(SIZEOF_PID_T) #define SIZEOF_PID_T PSUTIL_SIZEOF_PID_T // set as a macro in setup.py #endif // _Py_PARSE_PID is Python 3 only, but since it's private make sure it's // always present. #ifndef _Py_PARSE_PID #if SIZEOF_PID_T == SIZEOF_INT #define _Py_PARSE_PID "i" #elif SIZEOF_PID_T == SIZEOF_LONG #define _Py_PARSE_PID "l" #elif defined(SIZEOF_LONG_LONG) && SIZEOF_PID_T == SIZEOF_LONG_LONG #define _Py_PARSE_PID "L" #else #error "_Py_PARSE_PID: sizeof(pid_t) is neither sizeof(int), " "sizeof(long) or sizeof(long long)" #endif #endif // Python 2 or PyPy on Windows #ifndef PyLong_FromPid #if ((SIZEOF_PID_T == SIZEOF_INT) || (SIZEOF_PID_T == SIZEOF_LONG)) #if PY_MAJOR_VERSION >= 3 #define PyLong_FromPid PyLong_FromLong #else #define PyLong_FromPid PyInt_FromLong #endif #elif defined(SIZEOF_LONG_LONG) && SIZEOF_PID_T == SIZEOF_LONG_LONG #define PyLong_FromPid PyLong_FromLongLong #else #error "PyLong_FromPid: sizeof(pid_t) is neither sizeof(int), " "sizeof(long) or sizeof(long long)" #endif #endif // ==================================================================== // --- Custom exceptions // ==================================================================== PyObject* AccessDenied(const char *msg); PyObject* NoSuchProcess(const char *msg); PyObject* PyErr_SetFromOSErrnoWithSyscall(const char *syscall); // ==================================================================== // --- Global utils // ==================================================================== PyObject* psutil_check_pid_range(PyObject *self, PyObject *args); PyObject* psutil_set_debug(PyObject *self, PyObject *args); int psutil_setup(void); // Print a debug message on stderr. #define psutil_debug(...) do { \ if (! PSUTIL_DEBUG) \ break; \ fprintf(stderr, "psutil-debug [%s:%d]> ", __FILE__, __LINE__); \ fprintf(stderr, __VA_ARGS__); \ fprintf(stderr, "\n");} while(0) // ==================================================================== // --- BSD // ==================================================================== void convert_kvm_err(const char *syscall, char *errbuf); // ==================================================================== // --- macOS // ==================================================================== #ifdef PSUTIL_OSX #include <mach/mach_time.h> extern struct mach_timebase_info PSUTIL_MACH_TIMEBASE_INFO; #endif // ==================================================================== // --- Windows // ==================================================================== #ifdef PSUTIL_WINDOWS #include <windows.h> // make it available to any file which includes this module #include "arch/windows/ntextapi.h" extern int PSUTIL_WINVER; extern SYSTEM_INFO PSUTIL_SYSTEM_INFO; extern CRITICAL_SECTION PSUTIL_CRITICAL_SECTION; #define PSUTIL_WINDOWS_VISTA 60 #define PSUTIL_WINDOWS_7 61 #define PSUTIL_WINDOWS_8 62 #define PSUTIL_WINDOWS_8_1 63 #define PSUTIL_WINDOWS_10 100 #define PSUTIL_WINDOWS_NEW MAXLONG #define MALLOC(x) HeapAlloc(GetProcessHeap(), 0, (x)) #define MALLOC_ZERO(x) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, (x)) #define FREE(x) HeapFree(GetProcessHeap(), 0, (x)) #define _NT_FACILITY_MASK 0xfff #define _NT_FACILITY_SHIFT 16 #define _NT_FACILITY(status) \ ((((ULONG)(status)) >> _NT_FACILITY_SHIFT) & _NT_FACILITY_MASK) #define NT_NTWIN32(status) (_NT_FACILITY(status) == FACILITY_WIN32) #define WIN32_FROM_NTSTATUS(status) (((ULONG)(status)) & 0xffff) #define LO_T 1e-7 #define HI_T 429.4967296 #ifndef AF_INET6 #define AF_INET6 23 #endif PVOID psutil_GetProcAddress(LPCSTR libname, LPCSTR procname); PVOID psutil_GetProcAddressFromLib(LPCSTR libname, LPCSTR procname); PVOID psutil_SetFromNTStatusErr(NTSTATUS Status, const char *syscall); double psutil_FiletimeToUnixTime(FILETIME ft); double psutil_LargeIntegerToUnixTime(LARGE_INTEGER li); #endif
6,118
33.570621
77
h
psutil
psutil-master/psutil/_psutil_posix.h
/* * Copyright (c) 2009, Giampaolo Rodola'. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ long psutil_getpagesize(void); int psutil_pid_exists(pid_t pid); void psutil_raise_for_pid(pid_t pid, char *msg);
289
28
73
h
psutil
psutil-master/psutil/arch/aix/common.h
/* * Copyright (c) 2017, Arnon Yaari * All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #ifndef __PSUTIL_AIX_COMMON_H__ #define __PSUTIL_AIX_COMMON_H__ #include <sys/core.h> #define PROCINFO_INCR (256) #define PROCSIZE (sizeof(struct procentry64)) #define FDSINFOSIZE (sizeof(struct fdsinfo64)) #define KMEM "/dev/kmem" typedef u_longlong_t KA_T; /* psutil_kread() - read from kernel memory */ int psutil_kread(int Kd, /* kernel memory file descriptor */ KA_T addr, /* kernel memory address */ char *buf, /* buffer to receive data */ size_t len); /* length to read */ struct procentry64 * psutil_read_process_table( int * num /* out - number of processes read */ ); #endif /* __PSUTIL_AIX_COMMON_H__ */
894
26.96875
73
h
psutil
psutil-master/psutil/arch/aix/ifaddrs.h
/* * Copyright (c) 2017, Arnon Yaari * All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ /*! Based on code from https://lists.samba.org/archive/samba-technical/2009-February/063079.html !*/ #ifndef GENERIC_AIX_IFADDRS_H #define GENERIC_AIX_IFADDRS_H #include <sys/socket.h> #include <net/if.h> #undef ifa_dstaddr #undef ifa_broadaddr #define ifa_broadaddr ifa_dstaddr struct ifaddrs { struct ifaddrs *ifa_next; char *ifa_name; unsigned int ifa_flags; struct sockaddr *ifa_addr; struct sockaddr *ifa_netmask; struct sockaddr *ifa_dstaddr; }; extern int getifaddrs(struct ifaddrs **); extern void freeifaddrs(struct ifaddrs *); #endif
767
20.942857
77
h
psutil
psutil-master/psutil/arch/aix/net_connections.h
/* * Copyright (c) 2017, Arnon Yaari * All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #ifndef __NET_CONNECTIONS_H__ #define __NET_CONNECTIONS_H__ #include <Python.h> PyObject* psutil_net_connections(PyObject *self, PyObject *args); #endif /* __NET_CONNECTIONS_H__ */
356
21.3125
73
h
psutil
psutil-master/psutil/arch/aix/net_kernel_structs.h
/* * Copyright (c) 2017, Arnon Yaari * All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ /* The kernel is always 64 bit but Python is usually compiled as a 32 bit * process. We're reading the kernel memory to get the network connections, * so we need the structs we read to be defined with 64 bit "pointers". * Here are the partial definitions of the structs we use, taken from the * header files, with data type sizes converted to their 64 bit counterparts, * and unused data truncated. */ #ifdef __64BIT__ /* In case we're in a 64 bit process after all */ #include <sys/socketvar.h> #include <sys/protosw.h> #include <sys/unpcb.h> #include <sys/mbuf_base.h> #include <sys/mbuf_macro.h> #include <netinet/ip_var.h> #include <netinet/tcp.h> #include <netinet/tcpip.h> #include <netinet/tcp_timer.h> #include <netinet/tcp_var.h> #define file64 file #define socket64 socket #define protosw64 protosw #define inpcb64 inpcb #define tcpcb64 tcpcb #define unpcb64 unpcb #define mbuf64 mbuf #else /* __64BIT__ */ struct file64 { int f_flag; int f_count; int f_options; int f_type; u_longlong_t f_data; }; struct socket64 { short so_type; /* generic type, see socket.h */ short so_options; /* from socket call, see socket.h */ ushort so_linger; /* time to linger while closing */ short so_state; /* internal state flags SS_*, below */ u_longlong_t so_pcb; /* protocol control block */ u_longlong_t so_proto; /* protocol handle */ }; struct protosw64 { short pr_type; /* socket type used for */ u_longlong_t pr_domain; /* domain protocol a member of */ short pr_protocol; /* protocol number */ short pr_flags; /* see below */ }; struct inpcb64 { u_longlong_t inp_next,inp_prev; /* pointers to other pcb's */ u_longlong_t inp_head; /* pointer back to chain of inpcb's for this protocol */ u_int32_t inp_iflowinfo; /* input flow label */ u_short inp_fport; /* foreign port */ u_int16_t inp_fatype; /* foreign address type */ union in_addr_6 inp_faddr_6; /* foreign host table entry */ u_int32_t inp_oflowinfo; /* output flow label */ u_short inp_lport; /* local port */ u_int16_t inp_latype; /* local address type */ union in_addr_6 inp_laddr_6; /* local host table entry */ u_longlong_t inp_socket; /* back pointer to socket */ u_longlong_t inp_ppcb; /* pointer to per-protocol pcb */ u_longlong_t space_rt; struct sockaddr_in6 spare_dst; u_longlong_t inp_ifa; /* interface address to use */ int inp_flags; /* generic IP/datagram flags */ }; struct tcpcb64 { u_longlong_t seg__next; u_longlong_t seg__prev; short t_state; /* state of this connection */ }; struct unpcb64 { u_longlong_t unp_socket; /* pointer back to socket */ u_longlong_t unp_vnode; /* if associated with file */ ino_t unp_vno; /* fake vnode number */ u_longlong_t unp_conn; /* control block of connected socket */ u_longlong_t unp_refs; /* referencing socket linked list */ u_longlong_t unp_nextref; /* link in unp_refs list */ u_longlong_t unp_addr; /* bound address of socket */ }; struct m_hdr64 { u_longlong_t mh_next; /* next buffer in chain */ u_longlong_t mh_nextpkt; /* next chain in queue/record */ long mh_len; /* amount of data in this mbuf */ u_longlong_t mh_data; /* location of data */ }; struct mbuf64 { struct m_hdr64 m_hdr; }; #define m_len m_hdr.mh_len #endif /* __64BIT__ */
4,060
35.258929
77
h
psutil
psutil-master/psutil/arch/bsd/cpu.h
/* * Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include <Python.h> PyObject *psutil_cpu_count_logical(PyObject *self, PyObject *args); PyObject *psutil_cpu_times(PyObject *self, PyObject *args);
335
29.545455
73
h
psutil
psutil-master/psutil/arch/bsd/disk.h
/* * Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include <Python.h> PyObject *psutil_disk_partitions(PyObject *self, PyObject *args);
273
26.4
73
h
psutil
psutil-master/psutil/arch/bsd/net.h
/* * Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include <Python.h> PyObject *psutil_net_io_counters(PyObject *self, PyObject *args);
273
26.4
73
h
psutil
psutil-master/psutil/arch/bsd/proc.h
/* * Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include <Python.h> PyObject *psutil_pids(PyObject *self, PyObject *args); PyObject *psutil_proc_environ(PyObject *self, PyObject *args); PyObject *psutil_proc_name(PyObject *self, PyObject *args); PyObject *psutil_proc_oneshot_info(PyObject *self, PyObject *args); PyObject *psutil_proc_open_files(PyObject *self, PyObject *args);
519
36.142857
73
h
psutil
psutil-master/psutil/arch/bsd/sys.h
/* * Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include <Python.h> PyObject *psutil_boot_time(PyObject *self, PyObject *args); PyObject *psutil_users(PyObject *self, PyObject *args);
323
28.454545
73
h
psutil
psutil-master/psutil/arch/freebsd/cpu.h
/* * Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include <Python.h> PyObject *psutil_cpu_freq(PyObject* self, PyObject* args); PyObject *psutil_cpu_stats(PyObject* self, PyObject* args); PyObject *psutil_cpu_topology(PyObject* self, PyObject* args); PyObject *psutil_per_cpu_times(PyObject *self, PyObject *args);
453
33.923077
73
h
psutil
psutil-master/psutil/arch/freebsd/disk.h
/* * Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include <Python.h> PyObject *psutil_disk_io_counters(PyObject* self, PyObject* args);
274
26.5
73
h
psutil
psutil-master/psutil/arch/freebsd/mem.h
/* * Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include <Python.h> PyObject *psutil_swap_mem(PyObject* self, PyObject* args); PyObject *psutil_virtual_mem(PyObject* self, PyObject* args);
328
28.909091
73
h
psutil
psutil-master/psutil/arch/freebsd/proc.h
/* * Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include <Python.h> typedef struct kinfo_proc kinfo_proc; int psutil_get_proc_list(struct kinfo_proc **procList, size_t *procCount); int psutil_kinfo_proc(const pid_t pid, struct kinfo_proc *proc); PyObject* psutil_proc_cmdline(PyObject* self, PyObject* args); PyObject* psutil_proc_cpu_affinity_get(PyObject* self, PyObject* args); PyObject* psutil_proc_cpu_affinity_set(PyObject* self, PyObject* args); PyObject* psutil_proc_cwd(PyObject* self, PyObject* args); PyObject* psutil_proc_exe(PyObject* self, PyObject* args); PyObject* psutil_proc_getrlimit(PyObject* self, PyObject* args); PyObject* psutil_proc_memory_maps(PyObject* self, PyObject* args); PyObject* psutil_proc_num_fds(PyObject* self, PyObject* args); PyObject* psutil_proc_num_threads(PyObject* self, PyObject* args); PyObject* psutil_proc_setrlimit(PyObject* self, PyObject* args); PyObject* psutil_proc_threads(PyObject* self, PyObject* args);
1,102
43.12
74
h
psutil
psutil-master/psutil/arch/freebsd/proc_socks.h
/* * Copyright (c) 2009, Giampaolo Rodola'. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include <Python.h> PyObject* psutil_proc_connections(PyObject* self, PyObject* args);
263
25.4
73
h
psutil
psutil-master/psutil/arch/freebsd/sensors.h
/* * Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include <Python.h> PyObject* psutil_sensors_battery(PyObject* self, PyObject* args); PyObject* psutil_sensors_cpu_temperature(PyObject* self, PyObject* args);
347
30.636364
73
h
psutil
psutil-master/psutil/arch/freebsd/sys_socks.h
/* * Copyright (c) 2009, Giampaolo Rodola'. * All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include <Python.h> PyObject* psutil_net_connections(PyObject* self, PyObject* args);
265
23.181818
73
h
psutil
psutil-master/psutil/arch/netbsd/cpu.h
/* * Copyright (c) 2009, Giampaolo Rodola', Landry Breuil. * All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include <Python.h> PyObject *psutil_cpu_stats(PyObject *self, PyObject *args); PyObject *psutil_per_cpu_times(PyObject *self, PyObject *args);
338
27.25
73
h
psutil
psutil-master/psutil/arch/netbsd/disk.h
/* * Copyright (c) 2009, Giampaolo Rodola', Landry Breuil. * All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include <Python.h> PyObject *psutil_disk_io_counters(PyObject *self, PyObject *args);
281
24.636364
73
h
psutil
psutil-master/psutil/arch/netbsd/mem.h
/* * Copyright (c) 2009, Giampaolo Rodola', Landry Breuil. * All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include <Python.h> PyObject *psutil_virtual_mem(PyObject *self, PyObject *args); PyObject *psutil_swap_mem(PyObject *self, PyObject *args);
335
27
73
h
psutil
psutil-master/psutil/arch/netbsd/proc.h
/* * Copyright (c) 2009, Giampaolo Rodola', Landry Breuil. * All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include <Python.h> typedef struct kinfo_proc2 kinfo_proc; int psutil_kinfo_proc(pid_t pid, kinfo_proc *proc); struct kinfo_file * kinfo_getfile(pid_t pid, int* cnt); int psutil_get_proc_list(kinfo_proc **procList, size_t *procCount); char *psutil_get_cmd_args(pid_t pid, size_t *argsize); PyObject *psutil_proc_cmdline(PyObject *self, PyObject *args); PyObject *psutil_proc_connections(PyObject *self, PyObject *args); PyObject *psutil_proc_cwd(PyObject *self, PyObject *args); PyObject *psutil_proc_num_fds(PyObject *self, PyObject *args); PyObject *psutil_proc_threads(PyObject *self, PyObject *args); PyObject* psutil_proc_exe(PyObject* self, PyObject* args); PyObject* psutil_proc_num_threads(PyObject* self, PyObject* args);
927
37.666667
73
h
psutil
psutil-master/psutil/arch/netbsd/socks.h
/* * Copyright (c) 2009, Giampaolo Rodola'. * Copyright (c) 2015, Ryo ONODERA. * All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ PyObject *psutil_proc_connections(PyObject *, PyObject *); PyObject *psutil_net_connections(PyObject *, PyObject *);
331
29.181818
73
h
psutil
psutil-master/psutil/arch/openbsd/cpu.h
/* * Copyright (c) 2009, Giampaolo Rodola', Landry Breuil. * All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include <Python.h> PyObject *psutil_cpu_freq(PyObject* self, PyObject* args); PyObject *psutil_cpu_stats(PyObject* self, PyObject* args); PyObject *psutil_per_cpu_times(PyObject *self, PyObject *args);
397
29.615385
73
h
psutil
psutil-master/psutil/arch/openbsd/disk.h
/* * Copyright (c) 2009, Giampaolo Rodola', Landry Breuil. * All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include <Python.h> PyObject *psutil_disk_io_counters(PyObject* self, PyObject* args);
281
24.636364
73
h
psutil
psutil-master/psutil/arch/openbsd/mem.h
/* * Copyright (c) 2009, Giampaolo Rodola', Landry Breuil. * All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include <Python.h> PyObject *psutil_virtual_mem(PyObject *self, PyObject *args); PyObject *psutil_swap_mem(PyObject *self, PyObject *args);
335
27
73
h
psutil
psutil-master/psutil/arch/openbsd/proc.h
/* * Copyright (c) 2009, Giampaolo Rodola', Landry Breuil. * All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include <Python.h> typedef struct kinfo_proc kinfo_proc; int psutil_kinfo_proc(pid_t pid, struct kinfo_proc *proc); struct kinfo_file * kinfo_getfile(pid_t pid, int* cnt); int psutil_get_proc_list(struct kinfo_proc **procList, size_t *procCount); char **_psutil_get_argv(pid_t pid); PyObject *psutil_proc_cmdline(PyObject *self, PyObject *args); PyObject *psutil_proc_threads(PyObject *self, PyObject *args); PyObject *psutil_proc_num_fds(PyObject *self, PyObject *args); PyObject *psutil_proc_cwd(PyObject *self, PyObject *args);
728
33.714286
74
h
psutil
psutil-master/psutil/arch/openbsd/socks.h
/* * Copyright (c) 2009, Giampaolo Rodola'. * All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ PyObject *psutil_net_connections(PyObject* self, PyObject* args);
244
26.222222
73
h
psutil
psutil-master/psutil/arch/osx/cpu.h
/* * Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include <Python.h> PyObject *psutil_cpu_count_cores(PyObject *self, PyObject *args); PyObject *psutil_cpu_count_logical(PyObject *self, PyObject *args); PyObject *psutil_cpu_freq(PyObject *self, PyObject *args); PyObject *psutil_cpu_stats(PyObject *self, PyObject *args); PyObject *psutil_cpu_times(PyObject *self, PyObject *args); PyObject *psutil_per_cpu_times(PyObject *self, PyObject *args);
584
38
73
h
psutil
psutil-master/psutil/arch/osx/disk.h
/* * Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include <Python.h> PyObject *psutil_disk_io_counters(PyObject *self, PyObject *args); PyObject *psutil_disk_partitions(PyObject *self, PyObject *args); PyObject *psutil_disk_usage_used(PyObject *self, PyObject *args);
406
32.916667
73
h
psutil
psutil-master/psutil/arch/osx/mem.h
/* * Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include <Python.h> PyObject *psutil_swap_mem(PyObject *self, PyObject *args); PyObject *psutil_virtual_mem(PyObject *self, PyObject *args);
328
28.909091
73
h
psutil
psutil-master/psutil/arch/osx/net.h
/* * Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include <Python.h> PyObject *psutil_net_io_counters(PyObject *self, PyObject *args);
273
26.4
73
h
psutil
psutil-master/psutil/arch/osx/proc.h
/* * Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include <Python.h> PyObject *psutil_pids(PyObject *self, PyObject *args); PyObject *psutil_proc_cmdline(PyObject *self, PyObject *args); PyObject *psutil_proc_connections(PyObject *self, PyObject *args); PyObject *psutil_proc_cwd(PyObject *self, PyObject *args); PyObject *psutil_proc_environ(PyObject *self, PyObject *args); PyObject *psutil_proc_exe(PyObject *self, PyObject *args); PyObject *psutil_proc_kinfo_oneshot(PyObject *self, PyObject *args); PyObject *psutil_proc_memory_uss(PyObject *self, PyObject *args); PyObject *psutil_proc_name(PyObject *self, PyObject *args); PyObject *psutil_proc_num_fds(PyObject *self, PyObject *args); PyObject *psutil_proc_open_files(PyObject *self, PyObject *args); PyObject *psutil_proc_pidtaskinfo_oneshot(PyObject *self, PyObject *args); PyObject *psutil_proc_threads(PyObject *self, PyObject *args);
1,035
46.090909
74
h
psutil
psutil-master/psutil/arch/osx/sensors.h
/* * Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include <Python.h> PyObject *psutil_sensors_battery(PyObject *self, PyObject *args);
273
26.4
73
h
psutil
psutil-master/psutil/arch/osx/sys.h
/* * Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include <Python.h> PyObject *psutil_boot_time(PyObject *self, PyObject *args); PyObject *psutil_users(PyObject *self, PyObject *args);
323
28.454545
73
h
psutil
psutil-master/psutil/arch/solaris/environ.h
/* * Copyright (c) 2009, Giampaolo Rodola', Oleksii Shevchuk. * All rights reserved. Use of this source code is governed by a BSD-style * license that can be found in the LICENSE file. */ #ifndef PROCESS_AS_UTILS_H #define PROCESS_AS_UTILS_H char ** psutil_read_raw_args(psinfo_t info, const char *procfs_path, size_t *count); char ** psutil_read_raw_env(psinfo_t info, const char *procfs_path, ssize_t *count); void psutil_free_cstrings_array(char **array, size_t count); #endif // PROCESS_AS_UTILS_H
511
24.6
76
h
psutil
psutil-master/psutil/arch/solaris/v10/ifaddrs.h
/* Reference: https://lists.samba.org/archive/samba-technical/2009-February/063079.html */ #ifndef __IFADDRS_H__ #define __IFADDRS_H__ #include <sys/socket.h> #include <net/if.h> #undef ifa_dstaddr #undef ifa_broadaddr #define ifa_broadaddr ifa_dstaddr struct ifaddrs { struct ifaddrs *ifa_next; char *ifa_name; unsigned int ifa_flags; struct sockaddr *ifa_addr; struct sockaddr *ifa_netmask; struct sockaddr *ifa_dstaddr; }; extern int getifaddrs(struct ifaddrs **); extern void freeifaddrs(struct ifaddrs *); #endif
567
20.037037
90
h
psutil
psutil-master/psutil/arch/windows/cpu.h
/* * Copyright (c) 2009, Giampaolo Rodola'. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include <Python.h> PyObject *psutil_cpu_count_logical(PyObject *self, PyObject *args); PyObject *psutil_cpu_count_cores(PyObject *self, PyObject *args); PyObject *psutil_cpu_freq(PyObject *self, PyObject *args); PyObject *psutil_cpu_stats(PyObject *self, PyObject *args); PyObject *psutil_cpu_times(PyObject *self, PyObject *args); PyObject *psutil_per_cpu_times(PyObject *self, PyObject *args);
573
37.266667
73
h
psutil
psutil-master/psutil/arch/windows/disk.h
/* * Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include <Python.h> PyObject *psutil_disk_io_counters(PyObject *self, PyObject *args); PyObject *psutil_disk_partitions(PyObject *self, PyObject *args); PyObject *psutil_disk_usage(PyObject *self, PyObject *args); PyObject *psutil_QueryDosDevice(PyObject *self, PyObject *args);
466
34.923077
73
h
psutil
psutil-master/psutil/arch/windows/mem.h
/* * Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include <Python.h> PyObject *psutil_getpagesize(PyObject *self, PyObject *args); PyObject *psutil_virtual_mem(PyObject *self, PyObject *args); PyObject *psutil_swap_percent(PyObject *self, PyObject *args);
394
31.916667
73
h
psutil
psutil-master/psutil/arch/windows/net.h
/* * Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include <Python.h> PyObject *psutil_net_if_addrs(PyObject *self, PyObject *args); PyObject *psutil_net_if_stats(PyObject *self, PyObject *args); PyObject *psutil_net_io_counters(PyObject *self, PyObject *args);
399
32.333333
73
h
psutil
psutil-master/psutil/arch/windows/ntextapi.h
/* * Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. * Define Windows structs and constants which are considered private. */ #if !defined(__NTEXTAPI_H__) #define __NTEXTAPI_H__ #include <winternl.h> #include <iphlpapi.h> typedef LONG NTSTATUS; // https://github.com/ajkhoury/TestDll/blob/master/nt_ddk.h #define STATUS_INFO_LENGTH_MISMATCH ((NTSTATUS)0xC0000004L) #define STATUS_BUFFER_TOO_SMALL ((NTSTATUS)0xC0000023L) #define STATUS_ACCESS_DENIED ((NTSTATUS)0xC0000022L) #define STATUS_NOT_FOUND ((NTSTATUS)0xC0000225L) #define STATUS_BUFFER_OVERFLOW ((NTSTATUS)0x80000005L) // WtsApi32.h #define WTS_CURRENT_SERVER_HANDLE ((HANDLE)NULL) #define WINSTATIONNAME_LENGTH 32 #define DOMAIN_LENGTH 17 #define USERNAME_LENGTH 20 // ================================================================ // Enums // ================================================================ #undef SystemExtendedHandleInformation #define SystemExtendedHandleInformation 64 #undef MemoryWorkingSetInformation #define MemoryWorkingSetInformation 0x1 #undef ObjectNameInformation #define ObjectNameInformation 1 #undef ProcessIoPriority #define ProcessIoPriority 33 #undef ProcessWow64Information #define ProcessWow64Information 26 #undef SystemProcessIdInformation #define SystemProcessIdInformation 88 // process suspend() / resume() typedef enum _KTHREAD_STATE { Initialized, Ready, Running, Standby, Terminated, Waiting, Transition, DeferredReady, GateWait, MaximumThreadState } KTHREAD_STATE, *PKTHREAD_STATE; typedef enum _KWAIT_REASON { Executive, FreePage, PageIn, PoolAllocation, DelayExecution, Suspended, UserRequest, WrExecutive, WrFreePage, WrPageIn, WrPoolAllocation, WrDelayExecution, WrSuspended, WrUserRequest, WrEventPair, WrQueue, WrLpcReceive, WrLpcReply, WrVirtualMemory, WrPageOut, WrRendezvous, WrKeyedEvent, WrTerminated, WrProcessInSwap, WrCpuRateControl, WrCalloutStack, WrKernel, WrResource, WrPushLock, WrMutex, WrQuantumEnd, WrDispatchInt, WrPreempted, WrYieldExecution, WrFastMutex, WrGuardedMutex, WrRundown, WrAlertByThreadId, WrDeferredPreempt, MaximumWaitReason } KWAIT_REASON, *PKWAIT_REASON; // users() typedef enum _WTS_INFO_CLASS { WTSInitialProgram, WTSApplicationName, WTSWorkingDirectory, WTSOEMId, WTSSessionId, WTSUserName, WTSWinStationName, WTSDomainName, WTSConnectState, WTSClientBuildNumber, WTSClientName, WTSClientDirectory, WTSClientProductId, WTSClientHardwareId, WTSClientAddress, WTSClientDisplay, WTSClientProtocolType, WTSIdleTime, WTSLogonTime, WTSIncomingBytes, WTSOutgoingBytes, WTSIncomingFrames, WTSOutgoingFrames, WTSClientInfo, WTSSessionInfo, WTSSessionInfoEx, WTSConfigInfo, WTSValidationInfo, // Info Class value used to fetch Validation Information through the WTSQuerySessionInformation WTSSessionAddressV4, WTSIsRemoteSession } WTS_INFO_CLASS; typedef enum _WTS_CONNECTSTATE_CLASS { WTSActive, // User logged on to WinStation WTSConnected, // WinStation connected to client WTSConnectQuery, // In the process of connecting to client WTSShadow, // Shadowing another WinStation WTSDisconnected, // WinStation logged on without client WTSIdle, // Waiting for client to connect WTSListen, // WinStation is listening for connection WTSReset, // WinStation is being reset WTSDown, // WinStation is down due to error WTSInit, // WinStation in initialization } WTS_CONNECTSTATE_CLASS; // ================================================================ // Structs. // ================================================================ // cpu_stats(), per_cpu_times() typedef struct { LARGE_INTEGER IdleTime; LARGE_INTEGER KernelTime; LARGE_INTEGER UserTime; LARGE_INTEGER DpcTime; LARGE_INTEGER InterruptTime; ULONG InterruptCount; } _SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION; // cpu_stats() typedef struct { LARGE_INTEGER IdleProcessTime; LARGE_INTEGER IoReadTransferCount; LARGE_INTEGER IoWriteTransferCount; LARGE_INTEGER IoOtherTransferCount; ULONG IoReadOperationCount; ULONG IoWriteOperationCount; ULONG IoOtherOperationCount; ULONG AvailablePages; ULONG CommittedPages; ULONG CommitLimit; ULONG PeakCommitment; ULONG PageFaultCount; ULONG CopyOnWriteCount; ULONG TransitionCount; ULONG CacheTransitionCount; ULONG DemandZeroCount; ULONG PageReadCount; ULONG PageReadIoCount; ULONG CacheReadCount; ULONG CacheIoCount; ULONG DirtyPagesWriteCount; ULONG DirtyWriteIoCount; ULONG MappedPagesWriteCount; ULONG MappedWriteIoCount; ULONG PagedPoolPages; ULONG NonPagedPoolPages; ULONG PagedPoolAllocs; ULONG PagedPoolFrees; ULONG NonPagedPoolAllocs; ULONG NonPagedPoolFrees; ULONG FreeSystemPtes; ULONG ResidentSystemCodePage; ULONG TotalSystemDriverPages; ULONG TotalSystemCodePages; ULONG NonPagedPoolLookasideHits; ULONG PagedPoolLookasideHits; ULONG AvailablePagedPoolPages; ULONG ResidentSystemCachePage; ULONG ResidentPagedPoolPage; ULONG ResidentSystemDriverPage; ULONG CcFastReadNoWait; ULONG CcFastReadWait; ULONG CcFastReadResourceMiss; ULONG CcFastReadNotPossible; ULONG CcFastMdlReadNoWait; ULONG CcFastMdlReadWait; ULONG CcFastMdlReadResourceMiss; ULONG CcFastMdlReadNotPossible; ULONG CcMapDataNoWait; ULONG CcMapDataWait; ULONG CcMapDataNoWaitMiss; ULONG CcMapDataWaitMiss; ULONG CcPinMappedDataCount; ULONG CcPinReadNoWait; ULONG CcPinReadWait; ULONG CcPinReadNoWaitMiss; ULONG CcPinReadWaitMiss; ULONG CcCopyReadNoWait; ULONG CcCopyReadWait; ULONG CcCopyReadNoWaitMiss; ULONG CcCopyReadWaitMiss; ULONG CcMdlReadNoWait; ULONG CcMdlReadWait; ULONG CcMdlReadNoWaitMiss; ULONG CcMdlReadWaitMiss; ULONG CcReadAheadIos; ULONG CcLazyWriteIos; ULONG CcLazyWritePages; ULONG CcDataFlushes; ULONG CcDataPages; ULONG ContextSwitches; ULONG FirstLevelTbFills; ULONG SecondLevelTbFills; ULONG SystemCalls; } _SYSTEM_PERFORMANCE_INFORMATION; // cpu_stats() typedef struct { ULONG ContextSwitches; ULONG DpcCount; ULONG DpcRate; ULONG TimeIncrement; ULONG DpcBypassCount; ULONG ApcBypassCount; } _SYSTEM_INTERRUPT_INFORMATION; typedef struct _SYSTEM_HANDLE_TABLE_ENTRY_INFO_EX { PVOID Object; HANDLE UniqueProcessId; HANDLE HandleValue; ULONG GrantedAccess; USHORT CreatorBackTraceIndex; USHORT ObjectTypeIndex; ULONG HandleAttributes; ULONG Reserved; } SYSTEM_HANDLE_TABLE_ENTRY_INFO_EX, *PSYSTEM_HANDLE_TABLE_ENTRY_INFO_EX; typedef struct _SYSTEM_HANDLE_INFORMATION_EX { ULONG_PTR NumberOfHandles; ULONG_PTR Reserved; SYSTEM_HANDLE_TABLE_ENTRY_INFO_EX Handles[1]; } SYSTEM_HANDLE_INFORMATION_EX, *PSYSTEM_HANDLE_INFORMATION_EX; typedef struct _CLIENT_ID2 { HANDLE UniqueProcess; HANDLE UniqueThread; } CLIENT_ID2, *PCLIENT_ID2; #define CLIENT_ID CLIENT_ID2 #define PCLIENT_ID PCLIENT_ID2 typedef struct _SYSTEM_THREAD_INFORMATION2 { LARGE_INTEGER KernelTime; LARGE_INTEGER UserTime; LARGE_INTEGER CreateTime; ULONG WaitTime; PVOID StartAddress; CLIENT_ID ClientId; LONG Priority; LONG BasePriority; ULONG ContextSwitches; ULONG ThreadState; KWAIT_REASON WaitReason; } SYSTEM_THREAD_INFORMATION2, *PSYSTEM_THREAD_INFORMATION2; #define SYSTEM_THREAD_INFORMATION SYSTEM_THREAD_INFORMATION2 #define PSYSTEM_THREAD_INFORMATION PSYSTEM_THREAD_INFORMATION2 typedef struct _SYSTEM_PROCESS_INFORMATION2 { ULONG NextEntryOffset; ULONG NumberOfThreads; LARGE_INTEGER SpareLi1; LARGE_INTEGER SpareLi2; LARGE_INTEGER SpareLi3; LARGE_INTEGER CreateTime; LARGE_INTEGER UserTime; LARGE_INTEGER KernelTime; UNICODE_STRING ImageName; LONG BasePriority; HANDLE UniqueProcessId; HANDLE InheritedFromUniqueProcessId; ULONG HandleCount; ULONG SessionId; ULONG_PTR PageDirectoryBase; SIZE_T PeakVirtualSize; SIZE_T VirtualSize; DWORD PageFaultCount; SIZE_T PeakWorkingSetSize; SIZE_T WorkingSetSize; SIZE_T QuotaPeakPagedPoolUsage; SIZE_T QuotaPagedPoolUsage; SIZE_T QuotaPeakNonPagedPoolUsage; SIZE_T QuotaNonPagedPoolUsage; SIZE_T PagefileUsage; SIZE_T PeakPagefileUsage; SIZE_T PrivatePageCount; LARGE_INTEGER ReadOperationCount; LARGE_INTEGER WriteOperationCount; LARGE_INTEGER OtherOperationCount; LARGE_INTEGER ReadTransferCount; LARGE_INTEGER WriteTransferCount; LARGE_INTEGER OtherTransferCount; SYSTEM_THREAD_INFORMATION Threads[1]; } SYSTEM_PROCESS_INFORMATION2, *PSYSTEM_PROCESS_INFORMATION2; #define SYSTEM_PROCESS_INFORMATION SYSTEM_PROCESS_INFORMATION2 #define PSYSTEM_PROCESS_INFORMATION PSYSTEM_PROCESS_INFORMATION2 // cpu_freq() typedef struct _PROCESSOR_POWER_INFORMATION { ULONG Number; ULONG MaxMhz; ULONG CurrentMhz; ULONG MhzLimit; ULONG MaxIdleState; ULONG CurrentIdleState; } PROCESSOR_POWER_INFORMATION, *PPROCESSOR_POWER_INFORMATION; #ifndef __IPHLPAPI_H__ typedef struct in6_addr { union { UCHAR Byte[16]; USHORT Word[8]; } u; } IN6_ADDR, *PIN6_ADDR, FAR *LPIN6_ADDR; #endif // PEB / cmdline(), cwd(), environ() typedef struct { BYTE Reserved1[16]; PVOID Reserved2[5]; UNICODE_STRING CurrentDirectoryPath; PVOID CurrentDirectoryHandle; UNICODE_STRING DllPath; UNICODE_STRING ImagePathName; UNICODE_STRING CommandLine; LPCWSTR env; } RTL_USER_PROCESS_PARAMETERS_, *PRTL_USER_PROCESS_PARAMETERS_; // users() typedef struct _WTS_SESSION_INFOW { DWORD SessionId; // session id LPWSTR pWinStationName; // name of WinStation this session is // connected to WTS_CONNECTSTATE_CLASS State; // connection state (see enum) } WTS_SESSION_INFOW, * PWTS_SESSION_INFOW; #define PWTS_SESSION_INFO PWTS_SESSION_INFOW typedef struct _WTS_CLIENT_ADDRESS { DWORD AddressFamily; // AF_INET, AF_INET6, AF_IPX, AF_NETBIOS, AF_UNSPEC BYTE Address[20]; // client network address } WTS_CLIENT_ADDRESS, * PWTS_CLIENT_ADDRESS; typedef struct _WTSINFOW { WTS_CONNECTSTATE_CLASS State; // connection state (see enum) DWORD SessionId; // session id DWORD IncomingBytes; DWORD OutgoingBytes; DWORD IncomingFrames; DWORD OutgoingFrames; DWORD IncomingCompressedBytes; DWORD OutgoingCompressedBytes; WCHAR WinStationName[WINSTATIONNAME_LENGTH]; WCHAR Domain[DOMAIN_LENGTH]; WCHAR UserName[USERNAME_LENGTH + 1];// name of WinStation this session is // connected to LARGE_INTEGER ConnectTime; LARGE_INTEGER DisconnectTime; LARGE_INTEGER LastInputTime; LARGE_INTEGER LogonTime; LARGE_INTEGER CurrentTime; } WTSINFOW, * PWTSINFOW; #define PWTSINFO PWTSINFOW // cpu_count_cores() #if (_WIN32_WINNT < 0x0601) // Windows < 7 (Vista and XP) typedef struct _SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX { LOGICAL_PROCESSOR_RELATIONSHIP Relationship; DWORD Size; _ANONYMOUS_UNION union { PROCESSOR_RELATIONSHIP Processor; NUMA_NODE_RELATIONSHIP NumaNode; CACHE_RELATIONSHIP Cache; GROUP_RELATIONSHIP Group; } DUMMYUNIONNAME; } SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX, \ *PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX; #endif // memory_uss() typedef struct _MEMORY_WORKING_SET_BLOCK { ULONG_PTR Protection : 5; ULONG_PTR ShareCount : 3; ULONG_PTR Shared : 1; ULONG_PTR Node : 3; #ifdef _WIN64 ULONG_PTR VirtualPage : 52; #else ULONG VirtualPage : 20; #endif } MEMORY_WORKING_SET_BLOCK, *PMEMORY_WORKING_SET_BLOCK; // memory_uss() typedef struct _MEMORY_WORKING_SET_INFORMATION { ULONG_PTR NumberOfEntries; MEMORY_WORKING_SET_BLOCK WorkingSetInfo[1]; } MEMORY_WORKING_SET_INFORMATION, *PMEMORY_WORKING_SET_INFORMATION; // memory_uss() typedef struct _PSUTIL_PROCESS_WS_COUNTERS { SIZE_T NumberOfPages; SIZE_T NumberOfPrivatePages; SIZE_T NumberOfSharedPages; SIZE_T NumberOfShareablePages; } PSUTIL_PROCESS_WS_COUNTERS, *PPSUTIL_PROCESS_WS_COUNTERS; // exe() typedef struct _SYSTEM_PROCESS_ID_INFORMATION { HANDLE ProcessId; UNICODE_STRING ImageName; } SYSTEM_PROCESS_ID_INFORMATION, *PSYSTEM_PROCESS_ID_INFORMATION; // ==================================================================== // PEB structs for cmdline(), cwd(), environ() // ==================================================================== #ifdef _WIN64 typedef struct { BYTE Reserved1[2]; BYTE BeingDebugged; BYTE Reserved2[21]; PVOID LoaderData; PRTL_USER_PROCESS_PARAMETERS_ ProcessParameters; // more fields... } PEB_; // When we are a 64 bit process accessing a 32 bit (WoW64) // process we need to use the 32 bit structure layout. typedef struct { USHORT Length; USHORT MaxLength; DWORD Buffer; } UNICODE_STRING32; typedef struct { BYTE Reserved1[16]; DWORD Reserved2[5]; UNICODE_STRING32 CurrentDirectoryPath; DWORD CurrentDirectoryHandle; UNICODE_STRING32 DllPath; UNICODE_STRING32 ImagePathName; UNICODE_STRING32 CommandLine; DWORD env; } RTL_USER_PROCESS_PARAMETERS32; typedef struct { BYTE Reserved1[2]; BYTE BeingDebugged; BYTE Reserved2[1]; DWORD Reserved3[2]; DWORD Ldr; DWORD ProcessParameters; // more fields... } PEB32; #else // ! _WIN64 typedef struct { BYTE Reserved1[2]; BYTE BeingDebugged; BYTE Reserved2[1]; PVOID Reserved3[2]; PVOID Ldr; PRTL_USER_PROCESS_PARAMETERS_ ProcessParameters; // more fields... } PEB_; // When we are a 32 bit (WoW64) process accessing a 64 bit process // we need to use the 64 bit structure layout and a special function // to read its memory. typedef NTSTATUS (NTAPI *_NtWow64ReadVirtualMemory64)( HANDLE ProcessHandle, PVOID64 BaseAddress, PVOID Buffer, ULONG64 Size, PULONG64 NumberOfBytesRead); typedef struct { PVOID Reserved1[2]; PVOID64 PebBaseAddress; PVOID Reserved2[4]; PVOID UniqueProcessId[2]; PVOID Reserved3[2]; } PROCESS_BASIC_INFORMATION64; typedef struct { USHORT Length; USHORT MaxLength; PVOID64 Buffer; } UNICODE_STRING64; typedef struct { BYTE Reserved1[16]; PVOID64 Reserved2[5]; UNICODE_STRING64 CurrentDirectoryPath; PVOID64 CurrentDirectoryHandle; UNICODE_STRING64 DllPath; UNICODE_STRING64 ImagePathName; UNICODE_STRING64 CommandLine; PVOID64 env; } RTL_USER_PROCESS_PARAMETERS64; typedef struct { BYTE Reserved1[2]; BYTE BeingDebugged; BYTE Reserved2[21]; PVOID64 LoaderData; PVOID64 ProcessParameters; // more fields... } PEB64; #endif // _WIN64 // ================================================================ // Type defs for modules loaded at runtime. // ================================================================ BOOL (WINAPI *_GetLogicalProcessorInformationEx) ( LOGICAL_PROCESSOR_RELATIONSHIP relationship, PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX Buffer, PDWORD ReturnLength); #define GetLogicalProcessorInformationEx _GetLogicalProcessorInformationEx BOOLEAN (WINAPI * _WinStationQueryInformationW) ( HANDLE ServerHandle, ULONG SessionId, WINSTATIONINFOCLASS WinStationInformationClass, PVOID pWinStationInformation, ULONG WinStationInformationLength, PULONG pReturnLength); #define WinStationQueryInformationW _WinStationQueryInformationW NTSTATUS (NTAPI *_NtQueryInformationProcess) ( HANDLE ProcessHandle, DWORD ProcessInformationClass, PVOID ProcessInformation, DWORD ProcessInformationLength, PDWORD ReturnLength); #define NtQueryInformationProcess _NtQueryInformationProcess NTSTATUS (NTAPI *_NtQuerySystemInformation) ( ULONG SystemInformationClass, PVOID SystemInformation, ULONG SystemInformationLength, PULONG ReturnLength); #define NtQuerySystemInformation _NtQuerySystemInformation NTSTATUS (NTAPI *_NtSetInformationProcess) ( HANDLE ProcessHandle, DWORD ProcessInformationClass, PVOID ProcessInformation, DWORD ProcessInformationLength); #define NtSetInformationProcess _NtSetInformationProcess PSTR (NTAPI * _RtlIpv4AddressToStringA) ( struct in_addr *Addr, PSTR S); #define RtlIpv4AddressToStringA _RtlIpv4AddressToStringA PSTR (NTAPI * _RtlIpv6AddressToStringA) ( struct in6_addr *Addr, PSTR P); #define RtlIpv6AddressToStringA _RtlIpv6AddressToStringA DWORD (WINAPI * _GetExtendedTcpTable) ( PVOID pTcpTable, PDWORD pdwSize, BOOL bOrder, ULONG ulAf, TCP_TABLE_CLASS TableClass, ULONG Reserved); #define GetExtendedTcpTable _GetExtendedTcpTable DWORD (WINAPI * _GetExtendedUdpTable) ( PVOID pUdpTable, PDWORD pdwSize, BOOL bOrder, ULONG ulAf, UDP_TABLE_CLASS TableClass, ULONG Reserved); #define GetExtendedUdpTable _GetExtendedUdpTable DWORD (CALLBACK *_GetActiveProcessorCount) ( WORD GroupNumber); #define GetActiveProcessorCount _GetActiveProcessorCount BOOL(CALLBACK *_WTSQuerySessionInformationW) ( HANDLE hServer, DWORD SessionId, WTS_INFO_CLASS WTSInfoClass, LPWSTR* ppBuffer, DWORD* pBytesReturned ); #define WTSQuerySessionInformationW _WTSQuerySessionInformationW BOOL(CALLBACK *_WTSEnumerateSessionsW)( HANDLE hServer, DWORD Reserved, DWORD Version, PWTS_SESSION_INFO* ppSessionInfo, DWORD* pCount ); #define WTSEnumerateSessionsW _WTSEnumerateSessionsW VOID(CALLBACK *_WTSFreeMemory)( IN PVOID pMemory ); #define WTSFreeMemory _WTSFreeMemory ULONGLONG (CALLBACK *_GetTickCount64) ( void); #define GetTickCount64 _GetTickCount64 NTSTATUS (NTAPI *_NtQueryObject) ( HANDLE Handle, OBJECT_INFORMATION_CLASS ObjectInformationClass, PVOID ObjectInformation, ULONG ObjectInformationLength, PULONG ReturnLength); #define NtQueryObject _NtQueryObject NTSTATUS (WINAPI *_RtlGetVersion) ( PRTL_OSVERSIONINFOW lpVersionInformation ); #define RtlGetVersion _RtlGetVersion NTSTATUS (WINAPI *_NtResumeProcess) ( HANDLE hProcess ); #define NtResumeProcess _NtResumeProcess NTSTATUS (WINAPI *_NtSuspendProcess) ( HANDLE hProcess ); #define NtSuspendProcess _NtSuspendProcess NTSTATUS (NTAPI *_NtQueryVirtualMemory) ( HANDLE ProcessHandle, PVOID BaseAddress, int MemoryInformationClass, PVOID MemoryInformation, SIZE_T MemoryInformationLength, PSIZE_T ReturnLength ); #define NtQueryVirtualMemory _NtQueryVirtualMemory ULONG (WINAPI *_RtlNtStatusToDosErrorNoTeb) ( NTSTATUS status ); #define RtlNtStatusToDosErrorNoTeb _RtlNtStatusToDosErrorNoTeb #endif // __NTEXTAPI_H__
19,323
26.293785
120
h
psutil
psutil-master/psutil/arch/windows/proc.h
/* * Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include <Python.h> PyObject *TimeoutExpired; PyObject *TimeoutAbandoned; PyObject *psutil_pid_exists(PyObject *self, PyObject *args); PyObject *psutil_pids(PyObject *self, PyObject *args); PyObject *psutil_ppid_map(PyObject *self, PyObject *args); PyObject *psutil_proc_cpu_affinity_get(PyObject *self, PyObject *args); PyObject *psutil_proc_cpu_affinity_set(PyObject *self, PyObject *args); PyObject *psutil_proc_exe(PyObject *self, PyObject *args); PyObject *psutil_proc_io_counters(PyObject *self, PyObject *args); PyObject *psutil_proc_io_priority_get(PyObject *self, PyObject *args); PyObject *psutil_proc_io_priority_set(PyObject *self, PyObject *args); PyObject *psutil_proc_is_suspended(PyObject *self, PyObject *args); PyObject *psutil_proc_kill(PyObject *self, PyObject *args); PyObject *psutil_proc_memory_info(PyObject *self, PyObject *args); PyObject *psutil_proc_memory_maps(PyObject *self, PyObject *args); PyObject *psutil_proc_memory_uss(PyObject *self, PyObject *args); PyObject *psutil_proc_num_handles(PyObject *self, PyObject *args); PyObject *psutil_proc_open_files(PyObject *self, PyObject *args); PyObject *psutil_proc_priority_get(PyObject *self, PyObject *args); PyObject *psutil_proc_priority_set(PyObject *self, PyObject *args); PyObject *psutil_proc_suspend_or_resume(PyObject *self, PyObject *args); PyObject *psutil_proc_threads(PyObject *self, PyObject *args); PyObject *psutil_proc_times(PyObject *self, PyObject *args); PyObject *psutil_proc_username(PyObject *self, PyObject *args); PyObject *psutil_proc_wait(PyObject *self, PyObject *args);
1,767
49.514286
73
h
psutil
psutil-master/psutil/arch/windows/proc_handles.h
/* * Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include <Python.h> #include <windows.h> PyObject* psutil_get_open_files(DWORD pid, HANDLE hProcess);
289
25.363636
73
h
psutil
psutil-master/psutil/arch/windows/proc_info.h
/* * Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include <Python.h> #include <windows.h> #include "ntextapi.h" #define PSUTIL_FIRST_PROCESS(Processes) ( \ (PSYSTEM_PROCESS_INFORMATION)(Processes)) #define PSUTIL_NEXT_PROCESS(Process) ( \ ((PSYSTEM_PROCESS_INFORMATION)(Process))->NextEntryOffset ? \ (PSYSTEM_PROCESS_INFORMATION)((PCHAR)(Process) + \ ((PSYSTEM_PROCESS_INFORMATION)(Process))->NextEntryOffset) : NULL) int psutil_get_proc_info(DWORD pid, PSYSTEM_PROCESS_INFORMATION *retProcess, PVOID *retBuffer); PyObject* psutil_proc_cmdline(PyObject *self, PyObject *args, PyObject *kwdict); PyObject* psutil_proc_cwd(PyObject *self, PyObject *args); PyObject* psutil_proc_environ(PyObject *self, PyObject *args); PyObject* psutil_proc_info(PyObject *self, PyObject *args);
961
37.48
80
h
psutil
psutil-master/psutil/arch/windows/proc_utils.h
/* * Copyright (c) 2009, Giampaolo Rodola'. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ DWORD* psutil_get_pids(DWORD *numberOfReturnedPIDs); HANDLE psutil_handle_from_pid(DWORD pid, DWORD dwDesiredAccess); HANDLE psutil_check_phandle(HANDLE hProcess, DWORD pid, int check_exit_code); int psutil_pid_is_running(DWORD pid); int psutil_assert_pid_exists(DWORD pid, char *err); int psutil_assert_pid_not_exists(DWORD pid, char *err);
517
38.846154
77
h
psutil
psutil-master/psutil/arch/windows/security.h
/* * Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. * * Security related functions for Windows platform (Set privileges such as * SeDebug), as well as security helper functions. */ #include <windows.h> int psutil_set_se_debug();
365
25.142857
74
h
psutil
psutil-master/psutil/arch/windows/sensors.h
/* * Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include <Python.h> PyObject *psutil_sensors_battery(PyObject *self, PyObject *args);
273
26.4
73
h
psutil
psutil-master/psutil/arch/windows/services.h
/* * Copyright (c) 2009, Giampaolo Rodola'. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include <Python.h> #include <Winsvc.h> SC_HANDLE psutil_get_service_handle( char service_name, DWORD scm_access, DWORD access); PyObject *psutil_winservice_enumerate(PyObject *self, PyObject *args); PyObject *psutil_winservice_query_config(PyObject *self, PyObject *args); PyObject *psutil_winservice_query_status(PyObject *self, PyObject *args); PyObject *psutil_winservice_query_descr(PyObject *self, PyObject *args); PyObject *psutil_winservice_start(PyObject *self, PyObject *args); PyObject *psutil_winservice_stop(PyObject *self, PyObject *args);
734
39.833333
73
h
psutil
psutil-master/psutil/arch/windows/socks.h
/* * Copyright (c) 2009, Giampaolo Rodola', Jeff Tang. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include <Python.h> PyObject *psutil_net_connections(PyObject *self, PyObject *args);
273
26.4
73
h
psutil
psutil-master/psutil/arch/windows/sys.h
/* * Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include <Python.h> PyObject *psutil_boot_time(PyObject *self, PyObject *args); PyObject *psutil_users(PyObject *self, PyObject *args);
323
28.454545
73
h
psutil
psutil-master/psutil/arch/windows/wmi.h
/* * Copyright (c) 2009 Giampaolo Rodola'. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include <Python.h> PyObject* psutil_init_loadavg_counter(); PyObject* psutil_get_loadavg();
268
23.454545
73
h
ffhq-features-dataset
ffhq-features-dataset-master/extract_features.sh
mkdir ffhq for i in {00000..69999}; do date; echo "$i"; curl -H "Ocp-Apim-Subscription-Key: <Your-Key-Here>" "<Your-Microsoft-Cognitive-Server-Here>/face/v1.0/detect?returnFaceId=true&returnFaceLandmarks=false&returnFaceAttributes=age,gender,headPose,smile,facialHair,glasses,emotion,hair,makeup,occlusion,accessories,blur,exposure,noise" -H "Content-Type: application/json" --data-ascii "{\"url\":\"<Server-With-FFHQ-images>/ffhq/thumbnails128x128/${i}.png\"}" -o ffhq/${i}.json; #sudo zip -ur ffhq_info_small.zip ffhq; done
535
66
426
sh
FIt-SNE
FIt-SNE-master/src/annoylib.h
// Copyright (c) 2013 Spotify AB // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. #ifndef ANNOYLIB_H #define ANNOYLIB_H #include <stdio.h> #include <sys/stat.h> #ifndef _MSC_VER #include <unistd.h> #endif #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <fcntl.h> #include <stddef.h> #if defined(_MSC_VER) && _MSC_VER == 1500 typedef unsigned char uint8_t; typedef signed __int32 int32_t; typedef unsigned __int64 uint64_t; #else #include <stdint.h> #endif #if defined(_MSC_VER) || defined(__MINGW32__) #ifndef NOMINMAX #define NOMINMAX #endif #include "winlibs/mman.h" #include <windows.h> #else #include <sys/mman.h> #endif #include <cerrno> #include <string.h> #include <math.h> #include <vector> #include <algorithm> #include <queue> #include <limits> #ifdef _MSC_VER // Needed for Visual Studio to disable runtime checks for mempcy #pragma runtime_checks("s", off) #endif // This allows others to supply their own logger / error printer without // requiring Annoy to import their headers. See RcppAnnoy for a use case. #ifndef __ERROR_PRINTER_OVERRIDE__ #define showUpdate(...) { fprintf(stderr, __VA_ARGS__ ); } #else #define showUpdate(...) { __ERROR_PRINTER_OVERRIDE__( __VA_ARGS__ ); } #endif #ifndef _MSC_VER #define popcount __builtin_popcountll #else // See #293, #358 #define isnan(x) _isnan(x) #define popcount cole_popcount #endif #if !defined(NO_MANUAL_VECTORIZATION) && defined(__GNUC__) && (__GNUC__ >6) && defined(__AVX512F__) // See #402 #pragma message "Using 512-bit AVX instructions" #define USE_AVX512 #elif !defined(NO_MANUAL_VECTORIZATION) && defined(__AVX__) && defined (__SSE__) && defined(__SSE2__) && defined(__SSE3__) #pragma message "Using 128-bit AVX instructions" #define USE_AVX #else #pragma message "Using no AVX instructions" #endif #if defined(USE_AVX) || defined(USE_AVX512) #if defined(_MSC_VER) #include <intrin.h> #elif defined(__GNUC__) #include <x86intrin.h> #endif #endif #ifndef ANNOY_NODE_ATTRIBUTE #ifndef _MSC_VER #define ANNOY_NODE_ATTRIBUTE __attribute__((__packed__)) // TODO: this is turned on by default, but may not work for all architectures! Need to investigate. #else #define ANNOY_NODE_ATTRIBUTE #endif #endif using std::vector; using std::pair; using std::numeric_limits; using std::make_pair; inline void* remap_memory(void* _ptr, int _fd, size_t old_size, size_t new_size) { #ifdef __linux__ _ptr = mremap(_ptr, old_size, new_size, MREMAP_MAYMOVE); #else munmap(_ptr, old_size); #ifdef MAP_POPULATE _ptr = mmap(_ptr, new_size, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_POPULATE, _fd, 0); #else _ptr = mmap(_ptr, new_size, PROT_READ | PROT_WRITE, MAP_SHARED, _fd, 0); #endif #endif return _ptr; } namespace { template<typename S, typename Node> inline Node* get_node_ptr(const void* _nodes, const size_t _s, const S i) { return (Node*)((uint8_t *)_nodes + (_s * i)); } template<typename T> inline T dot(const T* x, const T* y, int f) { T s = 0; for (int z = 0; z < f; z++) { s += (*x) * (*y); x++; y++; } return s; } template<typename T> inline T manhattan_distance(const T* x, const T* y, int f) { T d = 0.0; for (int i = 0; i < f; i++) d += fabs(x[i] - y[i]); return d; } template<typename T> inline T euclidean_distance(const T* x, const T* y, int f) { // Don't use dot-product: avoid catastrophic cancellation in #314. T d = 0.0; for (int i = 0; i < f; ++i) { const T tmp=*x - *y; d += tmp * tmp; ++x; ++y; } return d; } #ifdef USE_AVX // Horizontal single sum of 256bit vector. inline float hsum256_ps_avx(__m256 v) { const __m128 x128 = _mm_add_ps(_mm256_extractf128_ps(v, 1), _mm256_castps256_ps128(v)); const __m128 x64 = _mm_add_ps(x128, _mm_movehl_ps(x128, x128)); const __m128 x32 = _mm_add_ss(x64, _mm_shuffle_ps(x64, x64, 0x55)); return _mm_cvtss_f32(x32); } template<> inline float dot<float>(const float* x, const float *y, int f) { float result = 0; if (f > 7) { __m256 d = _mm256_setzero_ps(); for (; f > 7; f -= 8) { d = _mm256_add_ps(d, _mm256_mul_ps(_mm256_loadu_ps(x), _mm256_loadu_ps(y))); x += 8; y += 8; } // Sum all floats in dot register. result += hsum256_ps_avx(d); } // Don't forget the remaining values. for (; f > 0; f--) { result += *x * *y; x++; y++; } return result; } template<> inline float manhattan_distance<float>(const float* x, const float* y, int f) { float result = 0; int i = f; if (f > 7) { __m256 manhattan = _mm256_setzero_ps(); __m256 minus_zero = _mm256_set1_ps(-0.0f); for (; i > 7; i -= 8) { const __m256 x_minus_y = _mm256_sub_ps(_mm256_loadu_ps(x), _mm256_loadu_ps(y)); const __m256 distance = _mm256_andnot_ps(minus_zero, x_minus_y); // Absolute value of x_minus_y (forces sign bit to zero) manhattan = _mm256_add_ps(manhattan, distance); x += 8; y += 8; } // Sum all floats in manhattan register. result = hsum256_ps_avx(manhattan); } // Don't forget the remaining values. for (; i > 0; i--) { result += fabsf(*x - *y); x++; y++; } return result; } template<> inline float euclidean_distance<float>(const float* x, const float* y, int f) { float result=0; if (f > 7) { __m256 d = _mm256_setzero_ps(); for (; f > 7; f -= 8) { const __m256 diff = _mm256_sub_ps(_mm256_loadu_ps(x), _mm256_loadu_ps(y)); d = _mm256_add_ps(d, _mm256_mul_ps(diff, diff)); // no support for fmadd in AVX... x += 8; y += 8; } // Sum all floats in dot register. result = hsum256_ps_avx(d); } // Don't forget the remaining values. for (; f > 0; f--) { float tmp = *x - *y; result += tmp * tmp; x++; y++; } return result; } #endif #ifdef USE_AVX512 template<> inline float dot<float>(const float* x, const float *y, int f) { float result = 0; if (f > 15) { __m512 d = _mm512_setzero_ps(); for (; f > 15; f -= 16) { //AVX512F includes FMA d = _mm512_fmadd_ps(_mm512_loadu_ps(x), _mm512_loadu_ps(y), d); x += 16; y += 16; } // Sum all floats in dot register. result += _mm512_reduce_add_ps(d); } // Don't forget the remaining values. for (; f > 0; f--) { result += *x * *y; x++; y++; } return result; } template<> inline float manhattan_distance<float>(const float* x, const float* y, int f) { float result = 0; int i = f; if (f > 15) { __m512 manhattan = _mm512_setzero_ps(); for (; i > 15; i -= 16) { const __m512 x_minus_y = _mm512_sub_ps(_mm512_loadu_ps(x), _mm512_loadu_ps(y)); manhattan = _mm512_add_ps(manhattan, _mm512_abs_ps(x_minus_y)); x += 16; y += 16; } // Sum all floats in manhattan register. result = _mm512_reduce_add_ps(manhattan); } // Don't forget the remaining values. for (; i > 0; i--) { result += fabsf(*x - *y); x++; y++; } return result; } template<> inline float euclidean_distance<float>(const float* x, const float* y, int f) { float result=0; if (f > 15) { __m512 d = _mm512_setzero_ps(); for (; f > 15; f -= 16) { const __m512 diff = _mm512_sub_ps(_mm512_loadu_ps(x), _mm512_loadu_ps(y)); d = _mm512_fmadd_ps(diff, diff, d); x += 16; y += 16; } // Sum all floats in dot register. result = _mm512_reduce_add_ps(d); } // Don't forget the remaining values. for (; f > 0; f--) { float tmp = *x - *y; result += tmp * tmp; x++; y++; } return result; } #endif template<typename T> inline T get_norm(T* v, int f) { return sqrt(dot(v, v, f)); } template<typename T, typename Random, typename Distance, typename Node> inline void two_means(const vector<Node*>& nodes, int f, Random& random, bool cosine, Node* p, Node* q) { /* This algorithm is a huge heuristic. Empirically it works really well, but I can't motivate it well. The basic idea is to keep two centroids and assign points to either one of them. We weight each centroid by the number of points assigned to it, so to balance it. */ static int iteration_steps = 200; size_t count = nodes.size(); size_t i = random.index(count); size_t j = random.index(count-1); j += (j >= i); // ensure that i != j Distance::template copy_node<T, Node>(p, nodes[i], f); Distance::template copy_node<T, Node>(q, nodes[j], f); if (cosine) { Distance::template normalize<T, Node>(p, f); Distance::template normalize<T, Node>(q, f); } Distance::init_node(p, f); Distance::init_node(q, f); int ic = 1, jc = 1; for (int l = 0; l < iteration_steps; l++) { size_t k = random.index(count); T di = ic * Distance::distance(p, nodes[k], f), dj = jc * Distance::distance(q, nodes[k], f); T norm = cosine ? get_norm(nodes[k]->v, f) : 1.0; if (!(norm > T(0))) { continue; } if (di < dj) { for (int z = 0; z < f; z++) p->v[z] = (p->v[z] * ic + nodes[k]->v[z] / norm) / (ic + 1); Distance::init_node(p, f); ic++; } else if (dj < di) { for (int z = 0; z < f; z++) q->v[z] = (q->v[z] * jc + nodes[k]->v[z] / norm) / (jc + 1); Distance::init_node(q, f); jc++; } } } } // namespace struct Base { template<typename T, typename S, typename Node> static inline void preprocess(void* nodes, size_t _s, const S node_count, const int f) { // Override this in specific metric structs below if you need to do any pre-processing // on the entire set of nodes passed into this index. } template<typename Node> static inline void zero_value(Node* dest) { // Initialize any fields that require sane defaults within this node. } template<typename T, typename Node> static inline void copy_node(Node* dest, const Node* source, const int f) { memcpy(dest->v, source->v, f * sizeof(T)); } template<typename T, typename Node> static inline void normalize(Node* node, int f) { T norm = get_norm(node->v, f); if (norm > 0) { for (int z = 0; z < f; z++) node->v[z] /= norm; } } }; struct Angular : Base { template<typename S, typename T> struct ANNOY_NODE_ATTRIBUTE Node { /* * We store a binary tree where each node has two things * - A vector associated with it * - Two children * All nodes occupy the same amount of memory * All nodes with n_descendants == 1 are leaf nodes. * A memory optimization is that for nodes with 2 <= n_descendants <= K, * we skip the vector. Instead we store a list of all descendants. K is * determined by the number of items that fits in the space of the vector. * For nodes with n_descendants == 1 the vector is a data point. * For nodes with n_descendants > K the vector is the normal of the split plane. * Note that we can't really do sizeof(node<T>) because we cheat and allocate * more memory to be able to fit the vector outside */ S n_descendants; union { S children[2]; // Will possibly store more than 2 T norm; }; T v[1]; // We let this one overflow intentionally. Need to allocate at least 1 to make GCC happy }; template<typename S, typename T> static inline T distance(const Node<S, T>* x, const Node<S, T>* y, int f) { // want to calculate (a/|a| - b/|b|)^2 // = a^2 / a^2 + b^2 / b^2 - 2ab/|a||b| // = 2 - 2cos T pp = x->norm ? x->norm : dot(x->v, x->v, f); // For backwards compatibility reasons, we need to fall back and compute the norm here T qq = y->norm ? y->norm : dot(y->v, y->v, f); T pq = dot(x->v, y->v, f); T ppqq = pp * qq; if (ppqq > 0) return 2.0 - 2.0 * pq / sqrt(ppqq); else return 2.0; // cos is 0 } template<typename S, typename T> static inline T margin(const Node<S, T>* n, const T* y, int f) { return dot(n->v, y, f); } template<typename S, typename T, typename Random> static inline bool side(const Node<S, T>* n, const T* y, int f, Random& random) { T dot = margin(n, y, f); if (dot != 0) return (dot > 0); else return random.flip(); } template<typename S, typename T, typename Random> static inline void create_split(const vector<Node<S, T>*>& nodes, int f, size_t s, Random& random, Node<S, T>* n) { Node<S, T>* p = (Node<S, T>*)alloca(s); Node<S, T>* q = (Node<S, T>*)alloca(s); two_means<T, Random, Angular, Node<S, T> >(nodes, f, random, true, p, q); for (int z = 0; z < f; z++) n->v[z] = p->v[z] - q->v[z]; Base::normalize<T, Node<S, T> >(n, f); } template<typename T> static inline T normalized_distance(T distance) { // Used when requesting distances from Python layer // Turns out sometimes the squared distance is -0.0 // so we have to make sure it's a positive number. return sqrt(std::max(distance, T(0))); } template<typename T> static inline T pq_distance(T distance, T margin, int child_nr) { if (child_nr == 0) margin = -margin; return std::min(distance, margin); } template<typename T> static inline T pq_initial_value() { return numeric_limits<T>::infinity(); } template<typename S, typename T> static inline void init_node(Node<S, T>* n, int f) { n->norm = dot(n->v, n->v, f); } static const char* name() { return "angular"; } }; struct DotProduct : Angular { template<typename S, typename T> struct ANNOY_NODE_ATTRIBUTE Node { /* * This is an extension of the Angular node with an extra attribute for the scaled norm. */ S n_descendants; S children[2]; // Will possibly store more than 2 T dot_factor; T v[1]; // We let this one overflow intentionally. Need to allocate at least 1 to make GCC happy }; static const char* name() { return "dot"; } template<typename S, typename T> static inline T distance(const Node<S, T>* x, const Node<S, T>* y, int f) { return -dot(x->v, y->v, f); } template<typename Node> static inline void zero_value(Node* dest) { dest->dot_factor = 0; } template<typename S, typename T> static inline void init_node(Node<S, T>* n, int f) { } template<typename T, typename Node> static inline void copy_node(Node* dest, const Node* source, const int f) { memcpy(dest->v, source->v, f * sizeof(T)); dest->dot_factor = source->dot_factor; } template<typename S, typename T, typename Random> static inline void create_split(const vector<Node<S, T>*>& nodes, int f, size_t s, Random& random, Node<S, T>* n) { Node<S, T>* p = (Node<S, T>*)alloca(s); Node<S, T>* q = (Node<S, T>*)alloca(s); DotProduct::zero_value(p); DotProduct::zero_value(q); two_means<T, Random, DotProduct, Node<S, T> >(nodes, f, random, true, p, q); for (int z = 0; z < f; z++) n->v[z] = p->v[z] - q->v[z]; n->dot_factor = p->dot_factor - q->dot_factor; DotProduct::normalize<T, Node<S, T> >(n, f); } template<typename T, typename Node> static inline void normalize(Node* node, int f) { T norm = sqrt(dot(node->v, node->v, f) + pow(node->dot_factor, 2)); if (norm > 0) { for (int z = 0; z < f; z++) node->v[z] /= norm; node->dot_factor /= norm; } } template<typename S, typename T> static inline T margin(const Node<S, T>* n, const T* y, int f) { return dot(n->v, y, f) + (n->dot_factor * n->dot_factor); } template<typename S, typename T, typename Random> static inline bool side(const Node<S, T>* n, const T* y, int f, Random& random) { T dot = margin(n, y, f); if (dot != 0) return (dot > 0); else return random.flip(); } template<typename T> static inline T normalized_distance(T distance) { return -distance; } template<typename T, typename S, typename Node> static inline void preprocess(void* nodes, size_t _s, const S node_count, const int f) { // This uses a method from Microsoft Research for transforming inner product spaces to cosine/angular-compatible spaces. // (Bachrach et al., 2014, see https://www.microsoft.com/en-us/research/wp-content/uploads/2016/02/XboxInnerProduct.pdf) // Step one: compute the norm of each vector and store that in its extra dimension (f-1) for (S i = 0; i < node_count; i++) { Node* node = get_node_ptr<S, Node>(nodes, _s, i); T norm = sqrt(dot(node->v, node->v, f)); if (isnan(norm)) norm = 0; node->dot_factor = norm; } // Step two: find the maximum norm T max_norm = 0; for (S i = 0; i < node_count; i++) { Node* node = get_node_ptr<S, Node>(nodes, _s, i); if (node->dot_factor > max_norm) { max_norm = node->dot_factor; } } // Step three: set each vector's extra dimension to sqrt(max_norm^2 - norm^2) for (S i = 0; i < node_count; i++) { Node* node = get_node_ptr<S, Node>(nodes, _s, i); T node_norm = node->dot_factor; T dot_factor = sqrt(pow(max_norm, static_cast<T>(2.0)) - pow(node_norm, static_cast<T>(2.0))); if (isnan(dot_factor)) dot_factor = 0; node->dot_factor = dot_factor; } } }; struct Hamming : Base { template<typename S, typename T> struct ANNOY_NODE_ATTRIBUTE Node { S n_descendants; S children[2]; T v[1]; }; static const size_t max_iterations = 20; template<typename T> static inline T pq_distance(T distance, T margin, int child_nr) { return distance - (margin != (unsigned int) child_nr); } template<typename T> static inline T pq_initial_value() { return numeric_limits<T>::max(); } template<typename T> static inline int cole_popcount(T v) { // Note: Only used with MSVC 9, which lacks intrinsics and fails to // calculate std::bitset::count for v > 32bit. Uses the generalized // approach by Eric Cole. // See https://graphics.stanford.edu/~seander/bithacks.html#CountBitsSet64 v = v - ((v >> 1) & (T)~(T)0/3); v = (v & (T)~(T)0/15*3) + ((v >> 2) & (T)~(T)0/15*3); v = (v + (v >> 4)) & (T)~(T)0/255*15; return (T)(v * ((T)~(T)0/255)) >> (sizeof(T) - 1) * 8; } template<typename S, typename T> static inline T distance(const Node<S, T>* x, const Node<S, T>* y, int f) { size_t dist = 0; for (int i = 0; i < f; i++) { dist += popcount(x->v[i] ^ y->v[i]); } return dist; } template<typename S, typename T> static inline bool margin(const Node<S, T>* n, const T* y, int f) { static const size_t n_bits = sizeof(T) * 8; T chunk = n->v[0] / n_bits; return (y[chunk] & (static_cast<T>(1) << (n_bits - 1 - (n->v[0] % n_bits)))) != 0; } template<typename S, typename T, typename Random> static inline bool side(const Node<S, T>* n, const T* y, int f, Random& random) { return margin(n, y, f); } template<typename S, typename T, typename Random> static inline void create_split(const vector<Node<S, T>*>& nodes, int f, size_t s, Random& random, Node<S, T>* n) { size_t cur_size = 0; size_t i = 0; int dim = f * 8 * sizeof(T); for (; i < max_iterations; i++) { // choose random position to split at n->v[0] = random.index(dim); cur_size = 0; for (typename vector<Node<S, T>*>::const_iterator it = nodes.begin(); it != nodes.end(); ++it) { if (margin(n, (*it)->v, f)) { cur_size++; } } if (cur_size > 0 && cur_size < nodes.size()) { break; } } // brute-force search for splitting coordinate if (i == max_iterations) { int j = 0; for (; j < dim; j++) { n->v[0] = j; cur_size = 0; for (typename vector<Node<S, T>*>::const_iterator it = nodes.begin(); it != nodes.end(); ++it) { if (margin(n, (*it)->v, f)) { cur_size++; } } if (cur_size > 0 && cur_size < nodes.size()) { break; } } } } template<typename T> static inline T normalized_distance(T distance) { return distance; } template<typename S, typename T> static inline void init_node(Node<S, T>* n, int f) { } static const char* name() { return "hamming"; } }; struct Minkowski : Base { template<typename S, typename T> struct ANNOY_NODE_ATTRIBUTE Node { S n_descendants; T a; // need an extra constant term to determine the offset of the plane S children[2]; T v[1]; }; template<typename S, typename T> static inline T margin(const Node<S, T>* n, const T* y, int f) { return n->a + dot(n->v, y, f); } template<typename S, typename T, typename Random> static inline bool side(const Node<S, T>* n, const T* y, int f, Random& random) { T dot = margin(n, y, f); if (dot != 0) return (dot > 0); else return random.flip(); } template<typename T> static inline T pq_distance(T distance, T margin, int child_nr) { if (child_nr == 0) margin = -margin; return std::min(distance, margin); } template<typename T> static inline T pq_initial_value() { return numeric_limits<T>::infinity(); } }; struct Euclidean : Minkowski { template<typename S, typename T> static inline T distance(const Node<S, T>* x, const Node<S, T>* y, int f) { return euclidean_distance(x->v, y->v, f); } template<typename S, typename T, typename Random> static inline void create_split(const vector<Node<S, T>*>& nodes, int f, size_t s, Random& random, Node<S, T>* n) { Node<S, T>* p = (Node<S, T>*)alloca(s); Node<S, T>* q = (Node<S, T>*)alloca(s); two_means<T, Random, Euclidean, Node<S, T> >(nodes, f, random, false, p, q); for (int z = 0; z < f; z++) n->v[z] = p->v[z] - q->v[z]; Base::normalize<T, Node<S, T> >(n, f); n->a = 0.0; for (int z = 0; z < f; z++) n->a += -n->v[z] * (p->v[z] + q->v[z]) / 2; } template<typename T> static inline T normalized_distance(T distance) { return sqrt(std::max(distance, T(0))); } template<typename S, typename T> static inline void init_node(Node<S, T>* n, int f) { } static const char* name() { return "euclidean"; } }; struct Manhattan : Minkowski { template<typename S, typename T> static inline T distance(const Node<S, T>* x, const Node<S, T>* y, int f) { return manhattan_distance(x->v, y->v, f); } template<typename S, typename T, typename Random> static inline void create_split(const vector<Node<S, T>*>& nodes, int f, size_t s, Random& random, Node<S, T>* n) { Node<S, T>* p = (Node<S, T>*)alloca(s); Node<S, T>* q = (Node<S, T>*)alloca(s); two_means<T, Random, Manhattan, Node<S, T> >(nodes, f, random, false, p, q); for (int z = 0; z < f; z++) n->v[z] = p->v[z] - q->v[z]; Base::normalize<T, Node<S, T> >(n, f); n->a = 0.0; for (int z = 0; z < f; z++) n->a += -n->v[z] * (p->v[z] + q->v[z]) / 2; } template<typename T> static inline T normalized_distance(T distance) { return std::max(distance, T(0)); } template<typename S, typename T> static inline void init_node(Node<S, T>* n, int f) { } static const char* name() { return "manhattan"; } }; template<typename S, typename T> class AnnoyIndexInterface { public: virtual ~AnnoyIndexInterface() {}; virtual bool add_item(S item, const T* w, char** error=NULL) = 0; virtual bool build(int q, char** error=NULL) = 0; virtual bool unbuild(char** error=NULL) = 0; virtual bool save(const char* filename, bool prefault=false, char** error=NULL) = 0; virtual void unload() = 0; virtual bool load(const char* filename, bool prefault=false, char** error=NULL) = 0; virtual T get_distance(S i, S j) const = 0; virtual void get_nns_by_item(S item, size_t n, size_t search_k, vector<S>* result, vector<T>* distances) const = 0; virtual void get_nns_by_vector(const T* w, size_t n, size_t search_k, vector<S>* result, vector<T>* distances) const = 0; virtual S get_n_items() const = 0; virtual S get_n_trees() const = 0; virtual void verbose(bool v) = 0; virtual void get_item(S item, T* v) const = 0; virtual void set_seed(int q) = 0; virtual bool on_disk_build(const char* filename, char** error=NULL) = 0; }; template<typename S, typename T, typename Distance, typename Random> class AnnoyIndex : public AnnoyIndexInterface<S, T> { /* * We use random projection to build a forest of binary trees of all items. * Basically just split the hyperspace into two sides by a hyperplane, * then recursively split each of those subtrees etc. * We create a tree like this q times. The default q is determined automatically * in such a way that we at most use 2x as much memory as the vectors take. */ public: typedef Distance D; typedef typename D::template Node<S, T> Node; protected: const int _f; size_t _s; S _n_items; Random _random; void* _nodes; // Could either be mmapped, or point to a memory buffer that we reallocate S _n_nodes; S _nodes_size; vector<S> _roots; S _K; bool _loaded; bool _verbose; int _fd; bool _on_disk; bool _built; public: AnnoyIndex(int f) : _f(f), _random() { _s = offsetof(Node, v) + _f * sizeof(T); // Size of each node _verbose = false; _built = false; _K = (S) (((size_t) (_s - offsetof(Node, children))) / sizeof(S)); // Max number of descendants to fit into node reinitialize(); // Reset everything } ~AnnoyIndex() { unload(); } int get_f() const { return _f; } bool add_item(S item, const T* w, char** error=NULL) { return add_item_impl(item, w, error); } template<typename W> bool add_item_impl(S item, const W& w, char** error=NULL) { if (_loaded) { showUpdate("You can't add an item to a loaded index\n"); if (error) *error = (char *)"You can't add an item to a loaded index"; return false; } _allocate_size(item + 1); Node* n = _get(item); D::zero_value(n); n->children[0] = 0; n->children[1] = 0; n->n_descendants = 1; for (int z = 0; z < _f; z++) n->v[z] = w[z]; D::init_node(n, _f); if (item >= _n_items) _n_items = item + 1; return true; } bool on_disk_build(const char* file, char** error=NULL) { _on_disk = true; #ifdef _WIN32 _fd = _open(file, O_RDWR | O_CREAT | O_TRUNC, (int)0600); #else _fd = open(file, O_RDWR | O_CREAT | O_TRUNC, (int)0600); #endif if (_fd == -1) { showUpdate("Error: file descriptor is -1\n"); if (error) *error = strerror(errno); _fd = 0; return false; } _nodes_size = 1; if (ftruncate(_fd, _s * _nodes_size) == -1) { showUpdate("Error truncating file: %s\n", strerror(errno)); if (error) *error = strerror(errno); return false; } #ifdef MAP_POPULATE _nodes = (Node*) mmap(0, _s * _nodes_size, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_POPULATE, _fd, 0); #else _nodes = (Node*) mmap(0, _s * _nodes_size, PROT_READ | PROT_WRITE, MAP_SHARED, _fd, 0); #endif return true; } bool build(int q, char** error=NULL) { if (_loaded) { showUpdate("You can't build a loaded index\n"); if (error) *error = (char *)"You can't build a loaded index"; return false; } if (_built) { showUpdate("You can't build a built index\n"); if (error) *error = (char *)"You can't build a built index"; return false; } D::template preprocess<T, S, Node>(_nodes, _s, _n_items, _f); _n_nodes = _n_items; while (1) { if (q == -1 && _n_nodes >= _n_items * 2) break; if (q != -1 && _roots.size() >= (size_t)q) break; if (_verbose) showUpdate("pass %zd...\n", _roots.size()); vector<S> indices; for (S i = 0; i < _n_items; i++) { if (_get(i)->n_descendants >= 1) // Issue #223 indices.push_back(i); } _roots.push_back(_make_tree(indices, true)); } // Also, copy the roots into the last segment of the array // This way we can load them faster without reading the whole file _allocate_size(_n_nodes + (S)_roots.size()); for (size_t i = 0; i < _roots.size(); i++) memcpy(_get(_n_nodes + (S)i), _get(_roots[i]), _s); _n_nodes += _roots.size(); if (_verbose) showUpdate("has %d nodes\n", _n_nodes); if (_on_disk) { _nodes = remap_memory(_nodes, _fd, _s * _nodes_size, _s * _n_nodes); if (ftruncate(_fd, _s * _n_nodes)) { // TODO: this probably creates an index in a corrupt state... not sure what to do showUpdate("Error truncating file: %s\n", strerror(errno)); if (error) *error = strerror(errno); return false; } _nodes_size = _n_nodes; } _built = true; return true; } bool unbuild(char** error=NULL) { if (_loaded) { showUpdate("You can't unbuild a loaded index\n"); if (error) *error = (char *)"You can't unbuild a loaded index"; return false; } _roots.clear(); _n_nodes = _n_items; _built = false; return true; } bool save(const char* filename, bool prefault=false, char** error=NULL) { if (!_built) { showUpdate("You can't save an index that hasn't been built\n"); if (error) *error = (char *)"You can't save an index that hasn't been built"; return false; } if (_on_disk) { return true; } else { // Delete file if it already exists (See issue #335) #ifdef _WIN32 _unlink(filename); #else unlink(filename); #endif printf("path: %s\n", filename); FILE *f = fopen(filename, "wb"); if (f == NULL) { showUpdate("Unable to open: %s\n", strerror(errno)); if (error) *error = strerror(errno); return false; } if (fwrite(_nodes, _s, _n_nodes, f) != (size_t) _n_nodes) { showUpdate("Unable to write: %s\n", strerror(errno)); if (error) *error = strerror(errno); return false; } if (fclose(f) == EOF) { showUpdate("Unable to close: %s\n", strerror(errno)); if (error) *error = strerror(errno); return false; } unload(); return load(filename, prefault, error); } } void reinitialize() { _fd = 0; _nodes = NULL; _loaded = false; _n_items = 0; _n_nodes = 0; _nodes_size = 0; _on_disk = false; _roots.clear(); } void unload() { if (_on_disk && _fd) { #ifdef _WIN32 _close(_fd); #else close(_fd); #endif munmap(_nodes, _s * _nodes_size); } else { if (_fd) { // we have mmapped data #ifdef _WIN32 _close(_fd); #else close(_fd); #endif munmap(_nodes, _n_nodes * _s); } else if (_nodes) { // We have heap allocated data free(_nodes); } } reinitialize(); if (_verbose) showUpdate("unloaded\n"); } bool load(const char* filename, bool prefault=false, char** error=NULL) { #ifdef _WIN32 _fd = _open(filename, O_RDONLY, (int)0400); #else _fd = open(filename, O_RDONLY, (int)0400); #endif if (_fd == -1) { showUpdate("Error: file descriptor is -1\n"); if (error) *error = strerror(errno); _fd = 0; return false; } #ifdef _WIN32 off_t size = _lseek(_fd, 0, SEEK_END); #else off_t size = lseek(_fd, 0, SEEK_END); #endif if (size == -1) { showUpdate("lseek returned -1\n"); if (error) *error = strerror(errno); return false; } else if (size == 0) { showUpdate("Size of file is zero\n"); if (error) *error = (char *)"Size of file is zero"; return false; } else if (size % _s) { // Something is fishy with this index! showUpdate("Error: index size %zu is not a multiple of vector size %zu\n", (size_t)size, _s); if (error) *error = (char *)"Index size is not a multiple of vector size"; return false; } int flags = MAP_SHARED; if (prefault) { #ifdef MAP_POPULATE flags |= MAP_POPULATE; #else showUpdate("prefault is set to true, but MAP_POPULATE is not defined on this platform"); #endif } _nodes = (Node*)mmap(0, size, PROT_READ, flags, _fd, 0); _n_nodes = (S)(size / _s); // Find the roots by scanning the end of the file and taking the nodes with most descendants _roots.clear(); S m = -1; for (S i = _n_nodes - 1; i >= 0; i--) { S k = _get(i)->n_descendants; if (m == -1 || k == m) { _roots.push_back(i); m = k; } else { break; } } // hacky fix: since the last root precedes the copy of all roots, delete it if (_roots.size() > 1 && _get(_roots.front())->children[0] == _get(_roots.back())->children[0]) _roots.pop_back(); _loaded = true; _built = true; _n_items = m; if (_verbose) showUpdate("found %lu roots with degree %d\n", _roots.size(), m); return true; } T get_distance(S i, S j) const { return D::normalized_distance(D::distance(_get(i), _get(j), _f)); } void get_nns_by_item(S item, size_t n, size_t search_k, vector<S>* result, vector<T>* distances) const { // TODO: handle OOB const Node* m = _get(item); _get_all_nns(m->v, n, search_k, result, distances); } void get_nns_by_vector(const T* w, size_t n, size_t search_k, vector<S>* result, vector<T>* distances) const { _get_all_nns(w, n, search_k, result, distances); } S get_n_items() const { return _n_items; } S get_n_trees() const { return _roots.size(); } void verbose(bool v) { _verbose = v; } void get_item(S item, T* v) const { // TODO: handle OOB Node* m = _get(item); memcpy(v, m->v, (_f) * sizeof(T)); } void set_seed(int seed) { _random.set_seed(seed); } protected: void _allocate_size(S n) { if (n > _nodes_size) { const double reallocation_factor = 1.3; S new_nodes_size = std::max(n, (S) ((_nodes_size + 1) * reallocation_factor)); void *old = _nodes; if (_on_disk) { int rc = ftruncate(_fd, _s * new_nodes_size); if (_verbose && rc) showUpdate("File truncation error\n"); _nodes = remap_memory(_nodes, _fd, _s * _nodes_size, _s * new_nodes_size); } else { _nodes = realloc(_nodes, _s * new_nodes_size); memset((char *) _nodes + (_nodes_size * _s) / sizeof(char), 0, (new_nodes_size - _nodes_size) * _s); } _nodes_size = new_nodes_size; if (_verbose) showUpdate("Reallocating to %d nodes: old_address=%p, new_address=%p\n", new_nodes_size, old, _nodes); } } inline Node* _get(const S i) const { return get_node_ptr<S, Node>(_nodes, _s, i); } S _make_tree(const vector<S >& indices, bool is_root) { // The basic rule is that if we have <= _K items, then it's a leaf node, otherwise it's a split node. // There's some regrettable complications caused by the problem that root nodes have to be "special": // 1. We identify root nodes by the arguable logic that _n_items == n->n_descendants, regardless of how many descendants they actually have // 2. Root nodes with only 1 child need to be a "dummy" parent // 3. Due to the _n_items "hack", we need to be careful with the cases where _n_items <= _K or _n_items > _K if (indices.size() == 1 && !is_root) return indices[0]; if (indices.size() <= (size_t)_K && (!is_root || (size_t)_n_items <= (size_t)_K || indices.size() == 1)) { _allocate_size(_n_nodes + 1); S item = _n_nodes++; Node* m = _get(item); m->n_descendants = is_root ? _n_items : (S)indices.size(); // Using std::copy instead of a loop seems to resolve issues #3 and #13, // probably because gcc 4.8 goes overboard with optimizations. // Using memcpy instead of std::copy for MSVC compatibility. #235 // Only copy when necessary to avoid crash in MSVC 9. #293 if (!indices.empty()) memcpy(m->children, &indices[0], indices.size() * sizeof(S)); return item; } vector<Node*> children; for (size_t i = 0; i < indices.size(); i++) { S j = indices[i]; Node* n = _get(j); if (n) children.push_back(n); } vector<S> children_indices[2]; Node* m = (Node*)alloca(_s); D::create_split(children, _f, _s, _random, m); for (size_t i = 0; i < indices.size(); i++) { S j = indices[i]; Node* n = _get(j); if (n) { bool side = D::side(m, n->v, _f, _random); children_indices[side].push_back(j); } else { showUpdate("No node for index %d?\n", j); } } // If we didn't find a hyperplane, just randomize sides as a last option while (children_indices[0].size() == 0 || children_indices[1].size() == 0) { if (_verbose) showUpdate("\tNo hyperplane found (left has %ld children, right has %ld children)\n", children_indices[0].size(), children_indices[1].size()); if (_verbose && indices.size() > 100000) showUpdate("Failed splitting %lu items\n", indices.size()); children_indices[0].clear(); children_indices[1].clear(); // Set the vector to 0.0 for (int z = 0; z < _f; z++) m->v[z] = 0.0; for (size_t i = 0; i < indices.size(); i++) { S j = indices[i]; // Just randomize... children_indices[_random.flip()].push_back(j); } } int flip = (children_indices[0].size() > children_indices[1].size()); m->n_descendants = is_root ? _n_items : (S)indices.size(); for (int side = 0; side < 2; side++) { // run _make_tree for the smallest child first (for cache locality) m->children[side^flip] = _make_tree(children_indices[side^flip], false); } _allocate_size(_n_nodes + 1); S item = _n_nodes++; memcpy(_get(item), m, _s); return item; } void _get_all_nns(const T* v, size_t n, size_t search_k, vector<S>* result, vector<T>* distances) const { Node* v_node = (Node *)alloca(_s); D::template zero_value<Node>(v_node); memcpy(v_node->v, v, sizeof(T) * _f); D::init_node(v_node, _f); std::priority_queue<pair<T, S> > q; if (search_k == (size_t)-1) { search_k = n * _roots.size(); } for (size_t i = 0; i < _roots.size(); i++) { q.push(make_pair(Distance::template pq_initial_value<T>(), _roots[i])); } std::vector<S> nns; while (nns.size() < search_k && !q.empty()) { const pair<T, S>& top = q.top(); T d = top.first; S i = top.second; Node* nd = _get(i); q.pop(); if (nd->n_descendants == 1 && i < _n_items) { nns.push_back(i); } else if (nd->n_descendants <= _K) { const S* dst = nd->children; nns.insert(nns.end(), dst, &dst[nd->n_descendants]); } else { T margin = D::margin(nd, v, _f); q.push(make_pair(D::pq_distance(d, margin, 1), static_cast<S>(nd->children[1]))); q.push(make_pair(D::pq_distance(d, margin, 0), static_cast<S>(nd->children[0]))); } } // Get distances for all items // To avoid calculating distance multiple times for any items, sort by id std::sort(nns.begin(), nns.end()); vector<pair<T, S> > nns_dist; S last = -1; for (size_t i = 0; i < nns.size(); i++) { S j = nns[i]; if (j == last) continue; last = j; if (_get(j)->n_descendants == 1) // This is only to guard a really obscure case, #284 nns_dist.push_back(make_pair(D::distance(v_node, _get(j), _f), j)); } size_t m = nns_dist.size(); size_t p = n < m ? n : m; // Return this many items std::partial_sort(nns_dist.begin(), nns_dist.begin() + p, nns_dist.end()); for (size_t i = 0; i < p; i++) { if (distances) distances->push_back(D::normalized_distance(nns_dist[i].first)); result->push_back(nns_dist[i].second); } } }; #endif // vim: tabstop=2 shiftwidth=2
40,303
29.303759
143
h
FIt-SNE
FIt-SNE-master/src/kissrandom.h
#ifndef KISSRANDOM_H #define KISSRANDOM_H #if defined(_MSC_VER) && _MSC_VER == 1500 typedef unsigned __int32 uint32_t; typedef unsigned __int64 uint64_t; #else #include <stdint.h> #endif // KISS = "keep it simple, stupid", but high quality random number generator // http://www0.cs.ucl.ac.uk/staff/d.jones/GoodPracticeRNG.pdf -> "Use a good RNG and build it into your code" // http://mathforum.org/kb/message.jspa?messageID=6627731 // https://de.wikipedia.org/wiki/KISS_(Zufallszahlengenerator) // 32 bit KISS struct Kiss32Random { uint32_t x; uint32_t y; uint32_t z; uint32_t c; // seed must be != 0 Kiss32Random(uint32_t seed = 123456789) { x = seed; y = 362436000; z = 521288629; c = 7654321; } uint32_t kiss() { // Linear congruence generator x = 69069 * x + 12345; // Xor shift y ^= y << 13; y ^= y >> 17; y ^= y << 5; // Multiply-with-carry uint64_t t = 698769069ULL * z + c; c = t >> 32; z = (uint32_t) t; return x + y + z; } inline int flip() { // Draw random 0 or 1 return kiss() & 1; } inline size_t index(size_t n) { // Draw random integer between 0 and n-1 where n is at most the number of data points you have return kiss() % n; } inline void set_seed(uint32_t seed) { x = seed; } }; // 64 bit KISS. Use this if you have more than about 2^24 data points ("big data" ;) ) struct Kiss64Random { uint64_t x; uint64_t y; uint64_t z; uint64_t c; // seed must be != 0 Kiss64Random(uint64_t seed = 1234567890987654321ULL) { x = seed; y = 362436362436362436ULL; z = 1066149217761810ULL; c = 123456123456123456ULL; } uint64_t kiss() { // Linear congruence generator z = 6906969069LL*z+1234567; // Xor shift y ^= (y<<13); y ^= (y>>17); y ^= (y<<43); // Multiply-with-carry (uint128_t t = (2^58 + 1) * x + c; c = t >> 64; x = (uint64_t) t) uint64_t t = (x<<58)+c; c = (x>>6); x += t; c += (x<t); return x + y + z; } inline int flip() { // Draw random 0 or 1 return kiss() & 1; } inline size_t index(size_t n) { // Draw random integer between 0 and n-1 where n is at most the number of data points you have return kiss() % n; } inline void set_seed(uint32_t seed) { x = seed; } }; #endif // vim: tabstop=2 shiftwidth=2
2,365
21.11215
109
h
FIt-SNE
FIt-SNE-master/src/nbodyfft.cpp
#include "winlibs/stdafx.h" #include "parallel_for.h" #include "time_code.h" #include "nbodyfft.h" void precompute_2d(double x_max, double x_min, double y_max, double y_min, int n_boxes, int n_interpolation_points, kernel_type_2d kernel, double *box_lower_bounds, double *box_upper_bounds, double *y_tilde_spacings, double *y_tilde, double *x_tilde, complex<double> *fft_kernel_tilde, double df ) { /* * Set up the boxes */ int n_total_boxes = n_boxes * n_boxes; double box_width = (x_max - x_min) / (double) n_boxes; // Left and right bounds of each box, first the lower bounds in the x direction, then in the y direction for (int i = 0; i < n_boxes; i++) { for (int j = 0; j < n_boxes; j++) { box_lower_bounds[i * n_boxes + j] = j * box_width + x_min; box_upper_bounds[i * n_boxes + j] = (j + 1) * box_width + x_min; box_lower_bounds[n_total_boxes + i * n_boxes + j] = i * box_width + y_min; box_upper_bounds[n_total_boxes + i * n_boxes + j] = (i + 1) * box_width + y_min; } } // Coordinates of each (equispaced) interpolation node for a single box double h = 1 / (double) n_interpolation_points; y_tilde_spacings[0] = h / 2; for (int i = 1; i < n_interpolation_points; i++) { y_tilde_spacings[i] = y_tilde_spacings[i - 1] + h; } // Coordinates of all the equispaced interpolation points int n_interpolation_points_1d = n_interpolation_points * n_boxes; int n_fft_coeffs = 2 * n_interpolation_points_1d; h = h * box_width; x_tilde[0] = x_min + h / 2; y_tilde[0] = y_min + h / 2; for (int i = 1; i < n_interpolation_points_1d; i++) { x_tilde[i] = x_tilde[i - 1] + h; y_tilde[i] = y_tilde[i - 1] + h; } /* * Evaluate the kernel at the interpolation nodes and form the embedded generating kernel vector for a circulant * matrix */ auto *kernel_tilde = new double[n_fft_coeffs * n_fft_coeffs](); for (int i = 0; i < n_interpolation_points_1d; i++) { for (int j = 0; j < n_interpolation_points_1d; j++) { double tmp = kernel(y_tilde[0], x_tilde[0], y_tilde[i], x_tilde[j],df ); kernel_tilde[(n_interpolation_points_1d + i) * n_fft_coeffs + (n_interpolation_points_1d + j)] = tmp; kernel_tilde[(n_interpolation_points_1d - i) * n_fft_coeffs + (n_interpolation_points_1d + j)] = tmp; kernel_tilde[(n_interpolation_points_1d + i) * n_fft_coeffs + (n_interpolation_points_1d - j)] = tmp; kernel_tilde[(n_interpolation_points_1d - i) * n_fft_coeffs + (n_interpolation_points_1d - j)] = tmp; } } // Precompute the FFT of the kernel generating matrix fftw_plan p = fftw_plan_dft_r2c_2d(n_fft_coeffs, n_fft_coeffs, kernel_tilde, reinterpret_cast<fftw_complex *>(fft_kernel_tilde), FFTW_ESTIMATE); fftw_execute(p); fftw_destroy_plan(p); delete[] kernel_tilde; } void n_body_fft_2d(int N, int n_terms, double *xs, double *ys, double *chargesQij, int n_boxes, int n_interpolation_points, double *box_lower_bounds, double *box_upper_bounds, double *y_tilde_spacings, complex<double> *fft_kernel_tilde, double *potentialQij, unsigned int nthreads) { int n_total_boxes = n_boxes * n_boxes; int total_interpolation_points = n_total_boxes * n_interpolation_points * n_interpolation_points; double coord_min = box_lower_bounds[0]; double box_width = box_upper_bounds[0] - box_lower_bounds[0]; auto *point_box_idx = new int[N]; // Determine which box each point belongs to for (int i = 0; i < N; i++) { auto x_idx = static_cast<int>((xs[i] - coord_min) / box_width); auto y_idx = static_cast<int>((ys[i] - coord_min) / box_width); // TODO: Figure out how on earth x_idx can be less than zero... // It's probably something to do with the fact that we use the single lowest coord for both dims? Probably not // this, more likely negative 0 if rounding errors if (x_idx >= n_boxes) { x_idx = n_boxes - 1; } else if (x_idx < 0) { x_idx = 0; } if (y_idx >= n_boxes) { y_idx = n_boxes - 1; } else if (y_idx < 0) { y_idx = 0; } point_box_idx[i] = y_idx * n_boxes + x_idx; } // Compute the relative position of each point in its box in the interval [0, 1] auto *x_in_box = new double[N]; auto *y_in_box = new double[N]; for (int i = 0; i < N; i++) { int box_idx = point_box_idx[i]; double x_min = box_lower_bounds[box_idx]; double y_min = box_lower_bounds[n_total_boxes + box_idx]; x_in_box[i] = (xs[i] - x_min) / box_width; y_in_box[i] = (ys[i] - y_min) / box_width; } INITIALIZE_TIME START_TIME /* * Step 1: Interpolate kernel using Lagrange polynomials and compute the w coefficients */ // Compute the interpolated values at each real point with each Lagrange polynomial in the `x` direction auto *x_interpolated_values = new double[N * n_interpolation_points]; interpolate(n_interpolation_points, N, x_in_box, y_tilde_spacings, x_interpolated_values); // Compute the interpolated values at each real point with each Lagrange polynomial in the `y` direction auto *y_interpolated_values = new double[N * n_interpolation_points]; interpolate(n_interpolation_points, N, y_in_box, y_tilde_spacings, y_interpolated_values); auto *w_coefficients = new double[total_interpolation_points * n_terms](); for (int i = 0; i < N; i++) { int box_idx = point_box_idx[i]; int box_j = box_idx / n_boxes; int box_i = box_idx % n_boxes; for (int interp_i = 0; interp_i < n_interpolation_points; interp_i++) { for (int interp_j = 0; interp_j < n_interpolation_points; interp_j++) { // Compute the index of the point in the interpolation grid of points int idx = (box_i * n_interpolation_points + interp_i) * (n_boxes * n_interpolation_points) + (box_j * n_interpolation_points) + interp_j; for (int d = 0; d < n_terms; d++) { w_coefficients[idx * n_terms + d] += y_interpolated_values[interp_j * N + i] * x_interpolated_values[interp_i * N + i] * chargesQij[i * n_terms + d]; } } } } END_TIME("Step 1"); START_TIME; /* * Step 2: Compute the values v_{m, n} at the equispaced nodes, multiply the kernel matrix with the coefficients w */ auto *y_tilde_values = new double[total_interpolation_points * n_terms](); int n_fft_coeffs_half = n_interpolation_points * n_boxes; int n_fft_coeffs = 2 * n_interpolation_points * n_boxes; auto *mpol_sort = new double[total_interpolation_points]; // FFT of fft_input auto *fft_input = new double[n_fft_coeffs * n_fft_coeffs](); auto *fft_w_coefficients = new complex<double>[n_fft_coeffs * (n_fft_coeffs / 2 + 1)]; auto *fft_output = new double[n_fft_coeffs * n_fft_coeffs](); fftw_plan plan_dft, plan_idft; plan_dft = fftw_plan_dft_r2c_2d(n_fft_coeffs, n_fft_coeffs, fft_input, reinterpret_cast<fftw_complex *>(fft_w_coefficients), FFTW_ESTIMATE); plan_idft = fftw_plan_dft_c2r_2d(n_fft_coeffs, n_fft_coeffs, reinterpret_cast<fftw_complex *>(fft_w_coefficients), fft_output, FFTW_ESTIMATE); for (int d = 0; d < n_terms; d++) { for (int i = 0; i < total_interpolation_points; i++) { mpol_sort[i] = w_coefficients[i * n_terms + d]; } for (int i = 0; i < n_fft_coeffs_half; i++) { for (int j = 0; j < n_fft_coeffs_half; j++) { fft_input[i * n_fft_coeffs + j] = mpol_sort[i * n_fft_coeffs_half + j]; } } fftw_execute(plan_dft); // Take the Hadamard product of two complex vectors for (int i = 0; i < n_fft_coeffs * (n_fft_coeffs / 2 + 1); i++) { double x_ = fft_w_coefficients[i].real(); double y_ = fft_w_coefficients[i].imag(); double u_ = fft_kernel_tilde[i].real(); double v_ = fft_kernel_tilde[i].imag(); fft_w_coefficients[i].real(x_ * u_ - y_ * v_); fft_w_coefficients[i].imag(x_ * v_ + y_ * u_); } // Invert the computed values at the interpolated nodes fftw_execute(plan_idft); for (int i = 0; i < n_fft_coeffs_half; i++) { for (int j = 0; j < n_fft_coeffs_half; j++) { int row = n_fft_coeffs_half + i; int col = n_fft_coeffs_half + j; // FFTW doesn't perform IDFT normalization, so we have to do it ourselves. This is done by dividing // the result with the number of points in the input mpol_sort[i * n_fft_coeffs_half + j] = fft_output[row * n_fft_coeffs + col] / (double) (n_fft_coeffs * n_fft_coeffs); } } for (int i = 0; i < n_fft_coeffs_half * n_fft_coeffs_half; i++) { y_tilde_values[i * n_terms + d] = mpol_sort[i]; } } fftw_destroy_plan(plan_dft); fftw_destroy_plan(plan_idft); delete[] fft_w_coefficients; delete[] fft_input; delete[] fft_output; delete[] mpol_sort; END_TIME("FFT"); START_TIME /* * Step 3: Compute the potentials \tilde{\phi} */ PARALLEL_FOR(nthreads,N, { int box_idx = point_box_idx[loop_i]; int box_i = box_idx % n_boxes; int box_j = box_idx / n_boxes; for (int interp_i = 0; interp_i < n_interpolation_points; interp_i++) { for (int interp_j = 0; interp_j < n_interpolation_points; interp_j++) { for (int d = 0; d < n_terms; d++) { // Compute the index of the point in the interpolation grid of points int idx = (box_i * n_interpolation_points + interp_i) * (n_boxes * n_interpolation_points) + (box_j * n_interpolation_points) + interp_j; potentialQij[loop_i * n_terms + d] += x_interpolated_values[interp_i * N + loop_i] * y_interpolated_values[interp_j * N + loop_i] * y_tilde_values[idx * n_terms + d]; } } } }); END_TIME("Step 3"); delete[] point_box_idx; delete[] x_interpolated_values; delete[] y_interpolated_values; delete[] w_coefficients; delete[] y_tilde_values; delete[] x_in_box; delete[] y_in_box; } void precompute(double y_min, double y_max, int n_boxes, int n_interpolation_points, kernel_type kernel, double *box_lower_bounds, double *box_upper_bounds, double *y_tilde_spacing, double *y_tilde, complex<double> *fft_kernel_vector, double df) { /* * Set up the boxes */ double box_width = (y_max - y_min) / (double) n_boxes; // Compute the left and right bounds of each box for (int box_idx = 0; box_idx < n_boxes; box_idx++) { box_lower_bounds[box_idx] = box_idx * box_width + y_min; box_upper_bounds[box_idx] = (box_idx + 1) * box_width + y_min; } int total_interpolation_points = n_interpolation_points * n_boxes; // Coordinates of each equispaced interpolation point for a single box. This equally spaces them between [0, 1] // with equal space between the points and half that space between the boundary point and the closest boundary point // e.g. [0.1, 0.3, 0.5, 0.7, 0.9] with spacings [0.1, 0.2, 0.2, 0.2, 0.2, 0.1], respectively. This ensures that the // nodes will still be equispaced across box boundaries double h = 1 / (double) n_interpolation_points; y_tilde_spacing[0] = h / 2; for (int i = 1; i < n_interpolation_points; i++) { y_tilde_spacing[i] = y_tilde_spacing[i - 1] + h; } // Coordinates of all the equispaced interpolation points h = h * box_width; y_tilde[0] = y_min + h / 2; for (int i = 1; i < total_interpolation_points; i++) { y_tilde[i] = y_tilde[i - 1] + h; } /* * Evaluate the kernel at the interpolation nodes and form the embedded generating kernel vector for a circulant * matrix */ auto *kernel_vector = new complex<double>[2 * total_interpolation_points](); // Compute the generating vector x between points K(y_i, y_j) where i = 0, j = 0:N-1 // [0 0 0 0 0 5 4 3 2 1] for linear kernel // This evaluates the Cauchy kernel centered on y_tilde[0] to all the other points for (int i = 0; i < total_interpolation_points; i++) { kernel_vector[total_interpolation_points + i].real(kernel(y_tilde[0], y_tilde[i], df)); } // This part symmetrizes the vector, this embeds the Toeplitz generating vector into the circulant generating vector // but also has the nice property of symmetrizing the Cauchy kernel, which is probably planned // [0 1 2 3 4 5 4 3 2 1] for linear kernel for (int i = 1; i < total_interpolation_points; i++) { kernel_vector[i].real(kernel_vector[2 * total_interpolation_points - i].real()); } // Precompute the FFT of the kernel generating vector fftw_plan p = fftw_plan_dft_1d(2 * total_interpolation_points, reinterpret_cast<fftw_complex *>(kernel_vector), reinterpret_cast<fftw_complex *>(fft_kernel_vector), FFTW_FORWARD, FFTW_ESTIMATE); fftw_execute(p); fftw_destroy_plan(p); delete[] kernel_vector; } void interpolate(int n_interpolation_points, int N, const double *y_in_box, const double *y_tilde_spacings, double *interpolated_values) { // The denominators are the same across the interpolants, so we only need to compute them once auto *denominator = new double[n_interpolation_points]; for (int i = 0; i < n_interpolation_points; i++) { denominator[i] = 1; for (int j = 0; j < n_interpolation_points; j++) { if (i != j) { denominator[i] *= y_tilde_spacings[i] - y_tilde_spacings[j]; } } } // Compute the numerators and the interpolant value for (int i = 0; i < N; i++) { for (int j = 0; j < n_interpolation_points; j++) { interpolated_values[j * N + i] = 1; for (int k = 0; k < n_interpolation_points; k++) { if (j != k) { interpolated_values[j * N + i] *= y_in_box[i] - y_tilde_spacings[k]; } } interpolated_values[j * N + i] /= denominator[j]; } } delete[] denominator; } void nbodyfft(int N, int n_terms, double *Y, double *chargesQij, int n_boxes, int n_interpolation_points, double *box_lower_bounds, double *box_upper_bounds, double *y_tilde_spacings, double *y_tilde, complex<double> *fft_kernel_vector, double *potentialsQij) { int total_interpolation_points = n_interpolation_points * n_boxes; double coord_min = box_lower_bounds[0]; double box_width = box_upper_bounds[0] - box_lower_bounds[0]; // Determine which box each point belongs to auto *point_box_idx = new int[N]; for (int i = 0; i < N; i++) { auto box_idx = static_cast<int>((Y[i] - coord_min) / box_width); // The right most point maps directly into `n_boxes`, while it should belong to the last box if (box_idx >= n_boxes) { box_idx = n_boxes - 1; } point_box_idx[i] = box_idx; } // Compute the relative position of each point in its box in the interval [0, 1] auto *y_in_box = new double[N]; for (int i = 0; i < N; i++) { int box_idx = point_box_idx[i]; double box_min = box_lower_bounds[box_idx]; y_in_box[i] = (Y[i] - box_min) / box_width; } /* * Step 1: Interpolate kernel using Lagrange polynomials and compute the w coefficients */ // Compute the interpolated values at each real point with each Lagrange polynomial auto *interpolated_values = new double[n_interpolation_points * N]; interpolate(n_interpolation_points, N, y_in_box, y_tilde_spacings, interpolated_values); auto *w_coefficients = new double[total_interpolation_points * n_terms](); for (int i = 0; i < N; i++) { int box_idx = point_box_idx[i] * n_interpolation_points; for (int interp_idx = 0; interp_idx < n_interpolation_points; interp_idx++) { for (int d = 0; d < n_terms; d++) { w_coefficients[(box_idx + interp_idx) * n_terms + d] += interpolated_values[interp_idx * N + i] * chargesQij[i * n_terms + d]; } } } // `embedded_w_coefficients` is just a vector of zeros prepended to `w_coefficients`, this (probably) matches the // dimensions of the kernel matrix K and since we embedded the generating vector by prepending values, we have to do // the same here auto *embedded_w_coefficients = new double[2 * total_interpolation_points * n_terms](); for (int i = 0; i < total_interpolation_points; i++) { for (int d = 0; d < n_terms; d++) { embedded_w_coefficients[(total_interpolation_points + i) * n_terms + d] = w_coefficients[i * n_terms + d]; } } /* * Step 2: Compute the values v_{m, n} at the equispaced nodes, multiply the kernel matrix with the coefficients w */ auto *fft_w_coefficients = new complex<double>[2 * total_interpolation_points]; auto *y_tilde_values = new double[total_interpolation_points * n_terms](); fftw_plan plan_dft, plan_idft; plan_dft = fftw_plan_dft_1d(2 * total_interpolation_points, reinterpret_cast<fftw_complex *>(fft_w_coefficients), reinterpret_cast<fftw_complex *>(fft_w_coefficients), FFTW_FORWARD, FFTW_ESTIMATE); plan_idft = fftw_plan_dft_1d(2 * total_interpolation_points, reinterpret_cast<fftw_complex *>(fft_w_coefficients), reinterpret_cast<fftw_complex *>(fft_w_coefficients), FFTW_BACKWARD, FFTW_ESTIMATE); for (int d = 0; d < n_terms; d++) { for (int i = 0; i < 2 * total_interpolation_points; i++) { fft_w_coefficients[i].real(embedded_w_coefficients[i * n_terms + d]); } fftw_execute(plan_dft); // Take the Hadamard product of two complex vectors for (int i = 0; i < 2 * total_interpolation_points; i++) { double x_ = fft_w_coefficients[i].real(); double y_ = fft_w_coefficients[i].imag(); double u_ = fft_kernel_vector[i].real(); double v_ = fft_kernel_vector[i].imag(); fft_w_coefficients[i].real(x_ * u_ - y_ * v_); fft_w_coefficients[i].imag(x_ * v_ + y_ * u_); } // Invert the computed values at the interpolated nodes, unfortunate naming but it's better to do IDFT inplace fftw_execute(plan_idft); for (int i = 0; i < total_interpolation_points; i++) { // FFTW doesn't perform IDFT normalization, so we have to do it ourselves. This is done by multiplying the // result with the number of points in the input y_tilde_values[i * n_terms + d] = fft_w_coefficients[i].real() / (total_interpolation_points * 2.0); } } fftw_destroy_plan(plan_dft); fftw_destroy_plan(plan_idft); delete[] fft_w_coefficients; /* * Step 3: Compute the potentials \tilde{\phi} */ for (int i = 0; i < N; i++) { int box_idx = point_box_idx[i] * n_interpolation_points; for (int j = 0; j < n_interpolation_points; j++) { for (int d = 0; d < n_terms; d++) { potentialsQij[i * n_terms + d] += interpolated_values[j * N + i] * y_tilde_values[(box_idx + j) * n_terms + d]; } } } delete[] point_box_idx; delete[] y_in_box; delete[] interpolated_values; delete[] w_coefficients; delete[] y_tilde_values; delete[] embedded_w_coefficients; }
20,456
43.861842
126
cpp
FIt-SNE
FIt-SNE-master/src/nbodyfft.h
#ifndef NBODYFFT_H #define NBODYFFT_H #ifdef _WIN32 #include "winlibs/fftw3.h" #else #include <fftw3.h> #endif #include <complex> using namespace std; typedef double (*kernel_type)(double, double, double); typedef double (*kernel_type_2d)(double, double, double, double, double); void precompute_2d(double x_max, double x_min, double y_max, double y_min, int n_boxes, int n_interpolation_points, kernel_type_2d kernel, double *box_lower_bounds, double *box_upper_bounds, double *y_tilde_spacings, double *y_tilde, double *x_tilde, complex<double> *fft_kernel_tilde, double df); void n_body_fft_2d(int N, int n_terms, double *xs, double *ys, double *chargesQij, int n_boxes, int n_interpolation_points, double *box_lower_bounds, double *box_upper_bounds, double *y_tilde_spacings, complex<double> *fft_kernel_tilde, double *potentialQij, unsigned int nthreads); void precompute(double y_min, double y_max, int n_boxes, int n_interpolation_points, kernel_type kernel, double *box_lower_bounds, double *box_upper_bounds, double *y_tilde_spacing, double *y_tilde, complex<double> *fft_kernel_vector, double df); void nbodyfft(int N, int n_terms, double *Y, double *chargesQij, int n_boxes, int n_interpolation_points, double *box_lower_bounds, double *box_upper_bounds, double *y_tilde_spacings, double *y_tilde, complex<double> *fft_kernel_vector, double *potentialsQij); void interpolate(int n_interpolation_points, int N, const double *y_in_box, const double *y_tilde_spacings, double *interpolated_values); #endif
1,677
44.351351
125
h
FIt-SNE
FIt-SNE-master/src/parallel_for.h
#ifndef PARALLEL_FOR_H #define PARALLEL_FOR_H #include<algorithm> #include <functional> #include <thread> #include <vector> #if defined(_OPENMP) #pragma message "Using OpenMP threading." #define PARALLEL_FOR(nthreads,LOOP_END,O) { \ if (nthreads >1 ) { \ _Pragma("omp parallel num_threads(nthreads)") \ { \ _Pragma("omp for") \ for (int loop_i=0; loop_i<LOOP_END; loop_i++) { \ O; \ } \ } \ }else{ \ for (int loop_i=0; loop_i<LOOP_END; loop_i++) { \ O; \ } \ } \ } #else #define PARALLEL_FOR(nthreads,LOOP_END,O) { \ if (nthreads >1 ) { \ std::vector<std::thread> threads(nthreads); \ for (int t = 0; t < nthreads; t++) { \ threads[t] = std::thread(std::bind( \ [&](const int bi, const int ei, const int t) { \ for(int loop_i = bi;loop_i<ei;loop_i++) { O; } \ },t*LOOP_END/nthreads,(t+1)==nthreads?LOOP_END:(t+1)*LOOP_END/nthreads,t)); \ } \ std::for_each(threads.begin(),threads.end(),[](std::thread& x){x.join();});\ }else{ \ for (int loop_i=0; loop_i<LOOP_END; loop_i++) { \ O; \ } \ } \ } #endif #endif
1,222
26.177778
83
h
FIt-SNE
FIt-SNE-master/src/sptree.cpp
/* * * Copyright (c) 2014, Laurens van der Maaten (Delft University of Technology) * 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. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the Delft University of Technology. * 4. Neither the name of the Delft University of Technology 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 LAURENS VAN DER MAATEN ''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 LAURENS VAN DER MAATEN 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 "winlibs/stdafx.h" #include <math.h> #include <float.h> #include <stdlib.h> #include <stdio.h> #include <cmath> #include "sptree.h" #include "parallel_for.h" // Constructs cell Cell::Cell(unsigned int inp_dimension) { dimension = inp_dimension; corner = (double *) malloc(dimension * sizeof(double)); width = (double *) malloc(dimension * sizeof(double)); } Cell::Cell(unsigned int inp_dimension, double *inp_corner, double *inp_width) { dimension = inp_dimension; corner = (double *) malloc(dimension * sizeof(double)); width = (double *) malloc(dimension * sizeof(double)); for (int d = 0; d < dimension; d++) setCorner(d, inp_corner[d]); for (int d = 0; d < dimension; d++) setWidth(d, inp_width[d]); } // Destructs cell Cell::~Cell() { free(corner); free(width); } double Cell::getCorner(unsigned int d) { return corner[d]; } double Cell::getWidth(unsigned int d) { return width[d]; } void Cell::setCorner(unsigned int d, double val) { corner[d] = val; } void Cell::setWidth(unsigned int d, double val) { width[d] = val; } // Checks whether a point lies in a cell bool Cell::containsPoint(double point[]) { for (int d = 0; d < dimension; d++) { if (corner[d] - width[d] > point[d]) return false; if (corner[d] + width[d] < point[d]) return false; } return true; } // Default constructor for SPTree -- build tree, too! SPTree::SPTree(unsigned int D, double *inp_data, unsigned int N) { // Compute mean, width, and height of current map (boundaries of SPTree) int nD = 0; double *mean_Y = (double *) calloc(D, sizeof(double)); double *min_Y = (double *) malloc(D * sizeof(double)); for (unsigned int d = 0; d < D; d++) min_Y[d] = DBL_MAX; double *max_Y = (double *) malloc(D * sizeof(double)); for (unsigned int d = 0; d < D; d++) max_Y[d] = -DBL_MAX; for (unsigned int n = 0; n < N; n++) { for (unsigned int d = 0; d < D; d++) { mean_Y[d] += inp_data[n * D + d]; if (inp_data[nD + d] < min_Y[d]) min_Y[d] = inp_data[nD + d]; if (inp_data[nD + d] > max_Y[d]) max_Y[d] = inp_data[nD + d]; } nD += D; } for (int d = 0; d < D; d++) mean_Y[d] /= (double) N; // Construct SPTree double *width = (double *) malloc(D * sizeof(double)); for (int d = 0; d < D; d++) width[d] = fmax(max_Y[d] - mean_Y[d], mean_Y[d] - min_Y[d]) + 1e-5; init(NULL, D, inp_data, mean_Y, width); fill(N); // Clean up memory free(mean_Y); free(max_Y); free(min_Y); free(width); } // Constructor for SPTree with particular size and parent -- build the tree, too! SPTree::SPTree(unsigned int D, double *inp_data, unsigned int N, double *inp_corner, double *inp_width) { init(NULL, D, inp_data, inp_corner, inp_width); fill(N); } // Constructor for SPTree with particular size (do not fill the tree) SPTree::SPTree(unsigned int D, double *inp_data, double *inp_corner, double *inp_width) { init(NULL, D, inp_data, inp_corner, inp_width); } // Constructor for SPTree with particular size and parent (do not fill tree) SPTree::SPTree(SPTree *inp_parent, unsigned int D, double *inp_data, double *inp_corner, double *inp_width) { init(inp_parent, D, inp_data, inp_corner, inp_width); } // Constructor for SPTree with particular size and parent -- build the tree, too! SPTree::SPTree(SPTree *inp_parent, unsigned int D, double *inp_data, unsigned int N, double *inp_corner, double *inp_width) { init(inp_parent, D, inp_data, inp_corner, inp_width); fill(N); } // Main initialization function void SPTree::init(SPTree *inp_parent, unsigned int D, double *inp_data, double *inp_corner, double *inp_width) { parent = inp_parent; dimension = D; no_children = 2; for (unsigned int d = 1; d < D; d++) no_children *= 2; data = inp_data; is_leaf = true; size = 0; cum_size = 0; boundary = new Cell(dimension); for (unsigned int d = 0; d < D; d++) boundary->setCorner(d, inp_corner[d]); for (unsigned int d = 0; d < D; d++) boundary->setWidth(d, inp_width[d]); children = (SPTree **) malloc(no_children * sizeof(SPTree *)); for (unsigned int i = 0; i < no_children; i++) children[i] = NULL; center_of_mass = (double *) malloc(D * sizeof(double)); for (unsigned int d = 0; d < D; d++) center_of_mass[d] = .0; } // Destructor for SPTree SPTree::~SPTree() { for (unsigned int i = 0; i < no_children; i++) { if (children[i] != NULL) delete children[i]; } free(children); free(center_of_mass); delete boundary; } // Update the data underlying this tree void SPTree::setData(double *inp_data) { data = inp_data; } // Get the parent of the current tree SPTree *SPTree::getParent() { return parent; } // Insert a point into the SPTree bool SPTree::insert(unsigned int new_index) { // Ignore objects which do not belong in this quad tree double *point = data + new_index * dimension; if (!boundary->containsPoint(point)) return false; // Online update of cumulative size and center-of-mass cum_size++; double mult1 = (double) (cum_size - 1) / (double) cum_size; double mult2 = 1.0 / (double) cum_size; for (unsigned int d = 0; d < dimension; d++) center_of_mass[d] *= mult1; for (unsigned int d = 0; d < dimension; d++) center_of_mass[d] += mult2 * point[d]; // If there is space in this quad tree and it is a leaf, add the object here if (is_leaf && size < QT_NODE_CAPACITY) { index[size] = new_index; size++; return true; } // Don't add duplicates for now (this is not very nice) bool any_duplicate = false; for (unsigned int n = 0; n < size; n++) { bool duplicate = true; for (unsigned int d = 0; d < dimension; d++) { if (point[d] != data[index[n] * dimension + d]) { duplicate = false; break; } } any_duplicate = any_duplicate | duplicate; } if (any_duplicate) return true; // Otherwise, we need to subdivide the current cell if (is_leaf) subdivide(); // Find out where the point can be inserted for (unsigned int i = 0; i < no_children; i++) { if (children[i]->insert(new_index)) return true; } // Otherwise, the point cannot be inserted (this should never happen) return false; } // Create four children which fully divide this cell into four quads of equal area void SPTree::subdivide() { // Create new children double *new_corner = (double *) malloc(dimension * sizeof(double)); double *new_width = (double *) malloc(dimension * sizeof(double)); for (unsigned int i = 0; i < no_children; i++) { unsigned int div = 1; for (unsigned int d = 0; d < dimension; d++) { new_width[d] = .5 * boundary->getWidth(d); if ((i / div) % 2 == 1) new_corner[d] = boundary->getCorner(d) - .5 * boundary->getWidth(d); else new_corner[d] = boundary->getCorner(d) + .5 * boundary->getWidth(d); div *= 2; } children[i] = new SPTree(this, dimension, data, new_corner, new_width); } free(new_corner); free(new_width); // Move existing points to correct children for (unsigned int i = 0; i < size; i++) { bool success = false; for (unsigned int j = 0; j < no_children; j++) { if (!success) success = children[j]->insert(index[i]); } index[i] = -1; } // Empty parent node size = 0; is_leaf = false; } // Build SPTree on dataset void SPTree::fill(unsigned int N) { for (unsigned int i = 0; i < N; i++) insert(i); } // Checks whether the specified tree is correct bool SPTree::isCorrect() { for (unsigned int n = 0; n < size; n++) { double *point = data + index[n] * dimension; if (!boundary->containsPoint(point)) return false; } if (!is_leaf) { bool correct = true; for (int i = 0; i < no_children; i++) correct = correct && children[i]->isCorrect(); return correct; } else return true; } // Build a list of all indices in SPTree void SPTree::getAllIndices(unsigned int *indices) { getAllIndices(indices, 0); } // Build a list of all indices in SPTree unsigned int SPTree::getAllIndices(unsigned int *indices, unsigned int loc) { // Gather indices in current quadrant for (unsigned int i = 0; i < size; i++) indices[loc + i] = index[i]; loc += size; // Gather indices in children if (!is_leaf) { for (int i = 0; i < no_children; i++) loc = children[i]->getAllIndices(indices, loc); } return loc; } unsigned int SPTree::getDepth() { if (is_leaf) return 1; int depth = 0; for (unsigned int i = 0; i < no_children; i++) depth = fmax(depth, children[i]->getDepth()); return 1 + depth; } // Compute non-edge forces using Barnes-Hut algorithm void SPTree::computeNonEdgeForces(unsigned int point_index, double theta, double neg_f[], double *sum_Q) { // Make sure that we spend no time on empty nodes or self-interactions if (cum_size == 0 || (is_leaf && size == 1 && index[0] == point_index)) return; // Compute distance between point and center-of-mass double D = .0; unsigned int ind = point_index * dimension; for (unsigned int d = 0; d < dimension; d++) D += (data[ind + d] - center_of_mass[d]) * (data[ind + d] - center_of_mass[d]); // Check whether we can use this node as a "summary" double max_width = 0.0; double cur_width; for (unsigned int d = 0; d < dimension; d++) { cur_width = boundary->getWidth(d); max_width = (max_width > cur_width) ? max_width : cur_width; } if (is_leaf || max_width / sqrt(D) < theta) { // Compute and add t-SNE force between point and current node D = 1.0 / (1.0 + D); double mult = cum_size * D; *sum_Q += mult; mult *= D; for (unsigned int d = 0; d < dimension; d++) neg_f[d] += mult * (data[ind + d] - center_of_mass[d]); } else { // Recursively apply Barnes-Hut to children for (unsigned int i = 0; i < no_children; i++) children[i]->computeNonEdgeForces(point_index, theta, neg_f, sum_Q); } } // Computes edge forces void SPTree::computeEdgeForces(unsigned int *row_P, unsigned int *col_P, double *val_P, int N, double *pos_f, unsigned int nthreads) { // Loop over all edges in the graph PARALLEL_FOR(nthreads, N, { unsigned int ind1 = loop_i * dimension; for (unsigned int i = row_P[loop_i]; i < row_P[loop_i + 1]; i++) { // Compute pairwise distance and Q-value double D = 1.0; unsigned int ind2 = col_P[i] * dimension; for (unsigned int d = 0; d < dimension; d++) D += (data[ind1 + d] - data[ind2 + d]) * (data[ind1 + d] - data[ind2 + d]); D = val_P[i] / D; // Sum positive force for (unsigned int d = 0; d < dimension; d++) pos_f[ind1 + d] += D * (data[ind1 + d] - data[ind2 + d]); } }); } // Print out tree void SPTree::print() { if (cum_size == 0) { printf("Empty node\n"); return; } if (is_leaf) { printf("Leaf node; data = ["); for (int i = 0; i < size; i++) { double *point = data + index[i] * dimension; for (int d = 0; d < dimension; d++) printf("%f, ", point[d]); printf(" (index = %d)", index[i]); if (i < size - 1) printf("\n"); else printf("]\n"); } } else { printf("Intersection node with center-of-mass = ["); for (int d = 0; d < dimension; d++) printf("%f, ", center_of_mass[d]); printf("]; children are:\n"); for (int i = 0; i < no_children; i++) children[i]->print(); } }
13,754
33.216418
134
cpp
FIt-SNE
FIt-SNE-master/src/sptree.h
/* * * Copyright (c) 2014, Laurens van der Maaten (Delft University of Technology) * 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. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the Delft University of Technology. * 4. Neither the name of the Delft University of Technology 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 LAURENS VAN DER MAATEN ''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 LAURENS VAN DER MAATEN 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. * */ #ifndef SPTREE_H #define SPTREE_H using namespace std; class Cell { unsigned int dimension; double *corner; double *width; public: Cell(unsigned int inp_dimension); Cell(unsigned int inp_dimension, double *inp_corner, double *inp_width); ~Cell(); double getCorner(unsigned int d); double getWidth(unsigned int d); void setCorner(unsigned int d, double val); void setWidth(unsigned int d, double val); bool containsPoint(double point[]); }; class SPTree { // Fixed constants static const unsigned int QT_NODE_CAPACITY = 1; // A buffer we use when doing force computations double *buff; // Properties of this node in the tree SPTree *parent; unsigned int dimension; bool is_leaf; unsigned int size; unsigned int cum_size; // Axis-aligned bounding box stored as a center with half-dimensions to represent the boundaries of this quad tree Cell *boundary; // Indices in this space-partitioning tree node, corresponding center-of-mass, and list of all children double *data; double *center_of_mass; unsigned int index[QT_NODE_CAPACITY]; // Children SPTree **children; unsigned int no_children; public: SPTree(unsigned int D, double *inp_data, unsigned int N); SPTree(unsigned int D, double *inp_data, double *inp_corner, double *inp_width); SPTree(unsigned int D, double *inp_data, unsigned int N, double *inp_corner, double *inp_width); SPTree(SPTree *inp_parent, unsigned int D, double *inp_data, unsigned int N, double *inp_corner, double *inp_width); SPTree(SPTree *inp_parent, unsigned int D, double *inp_data, double *inp_corner, double *inp_width); ~SPTree(); void setData(double *inp_data); SPTree *getParent(); void construct(Cell boundary); bool insert(unsigned int new_index); void subdivide(); bool isCorrect(); void rebuildTree(); void getAllIndices(unsigned int *indices); unsigned int getDepth(); void computeNonEdgeForces(unsigned int point_index, double theta, double neg_f[], double *sum_Q); void computeEdgeForces(unsigned int *row_P, unsigned int *col_P, double *val_P, int N, double *pos_f, unsigned int nthreads); void print(); private: void init(SPTree *inp_parent, unsigned int D, double *inp_data, double *inp_corner, double *inp_width); void fill(unsigned int N); unsigned int getAllIndices(unsigned int *indices, unsigned int loc); bool isChild(unsigned int test_index, unsigned int start, unsigned int end); }; #endif
4,413
30.304965
129
h
FIt-SNE
FIt-SNE-master/src/time_code.h
#ifndef TIME_CODE_H #define TIME_CODE_H #include <chrono> #if defined(TIME_CODE) #pragma message "Timing code" #define INITIALIZE_TIME std::chrono::steady_clock::time_point STARTVAR; #define START_TIME \ STARTVAR = std::chrono::steady_clock::now(); #define END_TIME(LABEL) { \ std::chrono::steady_clock::time_point ENDVAR = std::chrono::steady_clock::now(); \ printf("%s: %ld ms\n",LABEL, std::chrono::duration_cast<std::chrono::milliseconds>(ENDVAR-STARTVAR).count()); \ } #else #define INITIALIZE_TIME #define START_TIME #define END_TIME(LABEL) {} #endif #endif
950
44.285714
133
h
FIt-SNE
FIt-SNE-master/src/tsne.cpp
/* * * Copyright (c) 2014, Laurens van der Maaten (Delft University of Technology) * 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. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the Delft University of Technology. * 4. Neither the name of the Delft University of Technology 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 LAURENS VAN DER MAATEN ''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 LAURENS VAN DER MAATEN 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 "winlibs/stdafx.h" #ifdef _WIN32 #define _CRT_SECURE_NO_DEPRECATE #endif #include <iostream> #include <fstream> #include "nbodyfft.h" #include <math.h> #include "annoylib.h" #include "kissrandom.h" #include <thread> #include <float.h> #include <cstring> #include "vptree.h" #include "sptree.h" #include "tsne.h" #include "progress_bar/ProgressBar.hpp" #include "parallel_for.h" #include "time_code.h" using namespace std::chrono; #ifdef _WIN32 #include "winlibs/unistd.h" #else #include <unistd.h> #endif #include <functional> #define _CRT_SECURE_NO_WARNINGS int itTest = 0; bool measure_accuracy = false; double squared_cauchy(double x, double y, double df) { return pow(1.0 + pow(x - y, 2), -2); } double general_kernel(double x, double y, double df) { return pow(1.0 + ((x - y)*(x-y) )/df, -(df)); } double squared_general_kernel(double x, double y, double df) { return pow(1.0 + ((x - y)*(x-y) )/df, -(df+1.0)); } double squared_cauchy_2d(double x1, double x2, double y1, double y2,double df) { return pow(1.0 + pow(x1 - y1, 2) + pow(x2 - y2, 2), -2); } double general_kernel_2d(double x1, double x2, double y1, double y2, double df) { return pow(1.0 + ((x1 - y1)*(x1-y1) + (x2 - y2)*(x2-y2))/df, -(df)); } double squared_general_kernel_2d(double x1, double x2, double y1, double y2, double df) { return pow(1.0 + ((x1 - y1)*(x1-y1) + (x2 - y2)*(x2-y2))/df, -(df+1.0)); } using namespace std; //Helper function for printing Y at each iteration. Useful for debugging void print_progress(int iter, double *Y, int N, int no_dims) { ofstream myfile; std::ostringstream stringStream; stringStream << "dat/intermediate" << iter << ".txt"; std::string copyOfStr = stringStream.str(); myfile.open(stringStream.str().c_str()); for (int j = 0; j < N; j++) { for (int i = 0; i < no_dims; i++) { myfile << Y[j * no_dims + i] << " "; } myfile << "\n"; } myfile.close(); } // Perform t-SNE int TSNE::run(double *X, int N, int D, double *Y, int no_dims, double perplexity, double theta, int rand_seed, bool skip_random_init, int max_iter, int stop_lying_iter, int mom_switch_iter, double momentum, double final_momentum, double learning_rate, int K, double sigma, int nbody_algorithm, int knn_algo, double early_exag_coeff, double *costs, bool no_momentum_during_exag, int start_late_exag_iter, double late_exag_coeff, int n_trees, int search_k, int nterms, double intervals_per_integer, int min_num_intervals, unsigned int nthreads, int load_affinities, int perplexity_list_length, double *perplexity_list, double df, double max_step_norm) { // Some logging messages if (N - 1 < 3 * perplexity) { printf("Perplexity too large for the number of data points!\n"); exit(1); } if (no_momentum_during_exag) { printf("No momentum during the exaggeration phase.\n"); } else { printf("Will use momentum during exaggeration phase\n"); } // Determine whether we are using an exact algorithm bool exact = theta == .0; // Allocate some memory auto *dY = (double *) malloc(N * no_dims * sizeof(double)); auto *uY = (double *) malloc(N * no_dims * sizeof(double)); auto *gains = (double *) malloc(N * no_dims * sizeof(double)); if (dY == nullptr || uY == nullptr || gains == nullptr) throw std::bad_alloc(); // Initialize gradient to zeros and gains to ones. for (int i = 0; i < N * no_dims; i++) uY[i] = .0; for (int i = 0; i < N * no_dims; i++) gains[i] = 1.0; printf("Computing input similarities...\n"); zeroMean(X, N, D); if (perplexity > 0 || perplexity_list_length > 0) { printf("Using perplexity, so normalizing input data (to prevent numerical problems)\n"); double max_X = .0; for (unsigned long i = 0; i < N * D; i++) { if (fabs(X[i]) > max_X) max_X = fabs(X[i]); } for (unsigned long i = 0; i < N * D; i++) X[i] /= max_X; } else { printf("Not using perplexity, so data are left un-normalized.\n"); } // Compute input similarities for exact t-SNE double *P = nullptr; unsigned int *row_P = nullptr; unsigned int *col_P = nullptr; double *val_P = nullptr; if (exact) { // Loading input similarities if load_affinities == 1 if (load_affinities == 1) { printf("Loading exact input similarities from file...\n"); P = (double *) malloc(N * N * sizeof(double)); if (P == NULL) { printf("Memory allocation failed!\n"); exit(1); } FILE *h; size_t result; if ((h = fopen("P.dat", "rb")) == NULL) { printf("Error: could not open data file.\n"); return -2; } result = fread(P, sizeof(double), N * N, h); fclose(h); } else { // Compute similarities printf("Theta set to 0, so running exact algorithm\n"); P = (double *) malloc(N * N * sizeof(double)); if (P == NULL) { printf("Memory allocation failed!\n"); exit(1); } computeGaussianPerplexity(X, N, D, P, perplexity, sigma, perplexity_list_length, perplexity_list); // Symmetrize input similarities printf("Symmetrizing...\n"); int nN = 0; for (int n = 0; n < N; n++) { int mN = (n + 1) * N; for (int m = n + 1; m < N; m++) { P[nN + m] += P[mN + n]; P[mN + n] = P[nN + m]; mN += N; } nN += N; } double sum_P = .0; for (int i = 0; i < N * N; i++) sum_P += P[i]; for (int i = 0; i < N * N; i++) P[i] /= sum_P; //sum_P is just a cute way of writing 2N printf("Finished exact calculation of the P. Sum_p: %lf \n", sum_P); } // Saving input similarities if load_affinities == 2 if (load_affinities == 2) { printf("Saving exact input similarities to file...\n"); FILE *h; if ((h = fopen("P.dat", "w+b")) == NULL) { printf("Error: could not open data file.\n"); return -2; } fwrite(P, sizeof(double), N * N, h); fclose(h); } } // Compute input similarities for approximate t-SNE else { // Loading input similarities if load_affinities == 1 if (load_affinities == 1) { printf("Loading approximate input similarities from files...\n"); row_P = (unsigned int *) malloc((N + 1) * sizeof(unsigned int)); if (row_P == NULL) { printf("Memory allocation failed!\n"); exit(1); } FILE *h; size_t result; if ((h = fopen("P_row.dat", "rb")) == NULL) { printf("Error: could not open data file.\n"); return -2; } result = fread(row_P, sizeof(unsigned int), N + 1, h); fclose(h); int numel = row_P[N]; col_P = (unsigned int *) calloc(numel, sizeof(unsigned int)); val_P = (double *) calloc(numel, sizeof(double)); if (col_P == NULL || val_P == NULL) { printf("Memory allocation failed!\n"); exit(1); } if ((h = fopen("P_val.dat", "rb")) == NULL) { printf("Error: could not open data file.\n"); return -2; } result = fread(val_P, sizeof(double), numel, h); fclose(h); if ((h = fopen("P_col.dat", "rb")) == NULL) { printf("Error: could not open data file.\n"); return -2; } result = fread(col_P, sizeof(unsigned int), numel, h); fclose(h); printf(" val_P: %f %f %f ... %f %f %f\n", val_P[0], val_P[1], val_P[2], val_P[numel - 3], val_P[numel - 2], val_P[numel - 1]); printf(" col_P: %d %d %d ... %d %d %d\n", col_P[0], col_P[1], col_P[2], col_P[numel - 3], col_P[numel - 2], col_P[numel - 1]); printf(" row_P: %d %d %d ... %d %d %d\n", row_P[0], row_P[1], row_P[2], row_P[N - 2], row_P[N - 1], row_P[N]); } else { // Compute asymmetric pairwise input similarities int K_to_use; double sigma_to_use; if (perplexity < 0) { printf("Using manually set kernel width\n"); K_to_use = K; sigma_to_use = sigma; } else { printf("Using perplexity, not the manually set kernel width. K (number of nearest neighbors) and sigma (bandwidth) parameters are going to be ignored.\n"); if (perplexity > 0) { K_to_use = (int) 3 * perplexity; } else { K_to_use = (int) 3 * perplexity_list[0]; for (int pp = 1; pp < perplexity_list_length; pp++) { if ((int) 3* perplexity_list[pp] > K_to_use) { K_to_use = (int) 3 * perplexity_list[pp]; } } } sigma_to_use = -1; } if (knn_algo == 1) { printf("Using ANNOY for knn search, with parameters: n_trees %d and search_k %d\n", n_trees, search_k); int error_code = 0; error_code = computeGaussianPerplexity(X, N, D, &row_P, &col_P, &val_P, perplexity, K_to_use, sigma_to_use, n_trees, search_k, nthreads, perplexity_list_length, perplexity_list, rand_seed); if (error_code < 0) return error_code; } else if (knn_algo == 2) { printf("Using VP trees for nearest neighbor search\n"); computeGaussianPerplexity(X, N, D, &row_P, &col_P, &val_P, perplexity, K_to_use, sigma_to_use, nthreads, perplexity_list_length, perplexity_list); } else { printf("Invalid knn_algo param\n"); free(dY); free(uY); free(gains); exit(1); } // Symmetrize input similarities printf("Symmetrizing...\n"); symmetrizeMatrix(&row_P, &col_P, &val_P, N); double sum_P = .0; for (int i = 0; i < row_P[N]; i++) sum_P += val_P[i]; for (int i = 0; i < row_P[N]; i++) val_P[i] /= sum_P; } // Saving input similarities if load_affinities == 2 if (load_affinities == 2) { printf("Saving approximate input similarities to files...\n"); int numel = row_P[N]; FILE *h; if ((h = fopen("P_val.dat", "w+b")) == NULL) { printf("Error: could not open data file.\n"); return -2; } fwrite(val_P, sizeof(double), numel, h); fclose(h); if ((h = fopen("P_col.dat", "w+b")) == NULL) { printf("Error: could not open data file.\n"); return -2; } fwrite(col_P, sizeof(unsigned int), numel, h); fclose(h); if ((h = fopen("P_row.dat", "w+b")) == NULL) { printf("Error: could not open data file.\n"); return -2; } fwrite(row_P, sizeof(unsigned int), N + 1, h); fclose(h); printf(" val_P: %f %f %f ... %f %f %f\n", val_P[0], val_P[1], val_P[2], val_P[numel - 3], val_P[numel - 2], val_P[numel - 1]); printf(" col_P: %d %d %d ... %d %d %d\n", col_P[0], col_P[1], col_P[2], col_P[numel - 3], col_P[numel - 2], col_P[numel - 1]); printf(" row_P: %d %d %d ... %d %d %d\n", row_P[0], row_P[1], row_P[2], row_P[N - 2], row_P[N - 1], row_P[N]); } } // Set random seed if (skip_random_init != true) { if (rand_seed >= 0) { printf("Using random seed: %d\n", rand_seed); srand((unsigned int) rand_seed); } else { printf("Using current time as random seed...\n"); srand(time(NULL)); } } // Initialize solution (randomly) if (skip_random_init != true) { printf("Randomly initializing the solution.\n"); for (int i = 0; i < N * no_dims; i++) Y[i] = randn() * .0001; printf("Y[0] = %lf\n", Y[0]); } else { printf("Using the given initialization.\n"); } // If we are doing early exaggeration, we pre-multiply all the P by the coefficient of early exaggeration double max_sum_cols = 0; // Compute maximum possible exaggeration coefficient, if user requests if (early_exag_coeff == 0) { for (int n = 0; n < N; n++) { double running_sum = 0; for (int i = row_P[n]; i < row_P[n + 1]; i++) { running_sum += val_P[i]; } if (running_sum > max_sum_cols) max_sum_cols = running_sum; } early_exag_coeff = (1.0 / (learning_rate * max_sum_cols)); printf("Max of the val_Ps is: %lf\n", max_sum_cols); } printf("Exaggerating Ps by %f\n", early_exag_coeff); if (exact) { for (int i = 0; i < N * N; i++) { P[i] *= early_exag_coeff; } } else { for (int i = 0; i < row_P[N]; i++) val_P[i] *= early_exag_coeff; } print_progress(0, Y, N, no_dims); // Perform main training loop if (exact) { printf("Input similarities computed \nLearning embedding...\n"); } else { printf("Input similarities computed (sparsity = %f)!\nLearning embedding...\n", (double) row_P[N] / ((double) N * (double) N)); } std::chrono::steady_clock::time_point start_time = std::chrono::steady_clock::now(); if (!exact) { if (nbody_algorithm == 2) { printf("Using FIt-SNE approximation.\n"); } else if (nbody_algorithm == 1) { printf("Using the Barnes-Hut approximation.\n"); } else { printf("Error: Undefined algorithm"); exit(2); } } for (int iter = 0; iter < max_iter; iter++) { itTest = iter; if (exact) { // Compute the exact gradient using full P matrix computeExactGradient(P, Y, N, no_dims, dY,df); } else { if (nbody_algorithm == 2) { // Use FFT accelerated interpolation based negative gradients if (no_dims == 1) { if (df ==1.0) { computeFftGradientOneD(P, row_P, col_P, val_P, Y, N, no_dims, dY, nterms, intervals_per_integer, min_num_intervals, nthreads); }else { computeFftGradientOneDVariableDf(P, row_P, col_P, val_P, Y, N, no_dims, dY, nterms, intervals_per_integer, min_num_intervals, nthreads,df ); } } else { if (df ==1.0) { computeFftGradient(P, row_P, col_P, val_P, Y, N, no_dims, dY, nterms, intervals_per_integer, min_num_intervals, nthreads); }else { computeFftGradientVariableDf(P, row_P, col_P, val_P, Y, N, no_dims, dY, nterms, intervals_per_integer, min_num_intervals, nthreads,df ); } } } else if (nbody_algorithm == 1) { // Otherwise, compute the negative gradient using the Barnes-Hut approximation computeGradient(P, row_P, col_P, val_P, Y, N, no_dims, dY, theta, nthreads); } } if (measure_accuracy) { computeGradient(P, row_P, col_P, val_P, Y, N, no_dims, dY, theta, nthreads); computeFftGradient(P, row_P, col_P, val_P, Y, N, no_dims, dY, nterms, intervals_per_integer, min_num_intervals, nthreads); computeExactGradientTest(Y, N, no_dims,df); } // We can turn off momentum/gains until after the early exaggeration phase is completed if (no_momentum_during_exag) { if (iter > stop_lying_iter) { for (int i = 0; i < N * no_dims; i++) gains[i] = (sign(dY[i]) != sign(uY[i])) ? (gains[i] + .2) : (gains[i] * .8); for (int i = 0; i < N * no_dims; i++) if (gains[i] < .01) gains[i] = .01; for (int i = 0; i < N * no_dims; i++) uY[i] = momentum * uY[i] - learning_rate * gains[i] * dY[i]; for (int i = 0; i < N * no_dims; i++) Y[i] = Y[i] + uY[i]; } else { // During early exaggeration or compression, no trickery (i.e. no momentum, or gains). Just good old // fashion gradient descent for (int i = 0; i < N * no_dims; i++) Y[i] = Y[i] - dY[i]; } } else { for (int i = 0; i < N * no_dims; i++) gains[i] = (sign(dY[i]) != sign(uY[i])) ? (gains[i] + .2) : (gains[i] * .8); for (int i = 0; i < N * no_dims; i++) if (gains[i] < .01) gains[i] = .01; for (int i = 0; i < N * no_dims; i++) uY[i] = momentum * uY[i] - learning_rate * gains[i] * dY[i]; // Clip the step sizes if max_step_norm is provided if (max_step_norm > 0) { for (int i=0; i<N; i++) { double step = 0; for (int j=0; j<no_dims; j++) { step += uY[i*no_dims + j] * uY[i*no_dims + j]; } step = sqrt(step); if (step > max_step_norm) { for (int j=0; j<no_dims; j++) { uY[i*no_dims + j] *= (max_step_norm/step); } } } } for (int i = 0; i < N * no_dims; i++) Y[i] = Y[i] + uY[i]; } /* // Print step norms (for debugging) double maxstepnorm = 0; for (int i=0; i<N; i++) { double step = 0; for (int j=0; j<no_dims; j++) { step += uY[i*no_dims + j] * uY[i*no_dims + j]; } step = sqrt(step); if (step > maxstepnorm) { maxstepnorm = step; } } printf("%d: %f\n", iter, maxstepnorm); */ // Make solution zero-mean zeroMean(Y, N, no_dims); // Switch off early exaggeration if (iter == stop_lying_iter) { printf("Unexaggerating Ps by %f\n", early_exag_coeff); if (exact) { for (int i = 0; i < N * N; i++) P[i] /= early_exag_coeff; } else { for (int i = 0; i < row_P[N]; i++) val_P[i] /= early_exag_coeff; } } if (iter == start_late_exag_iter) { printf("Exaggerating Ps by %f\n", late_exag_coeff); if (exact) { for (int i = 0; i < N * N; i++) P[i] *= late_exag_coeff; } else { for (int i = 0; i < row_P[N]; i++) val_P[i] *= late_exag_coeff; } } if (iter == mom_switch_iter) momentum = final_momentum; // Print out progress if ((iter+1) % 50 == 0 || iter == max_iter - 1) { INITIALIZE_TIME; START_TIME; double C = .0; if (exact) { C = evaluateError(P, Y, N, no_dims,df); }else{ if (nbody_algorithm == 2) { C = evaluateErrorFft(row_P, col_P, val_P, Y, N, no_dims,nthreads,df); }else { C = evaluateError(row_P, col_P, val_P, Y, N, no_dims,theta, nthreads); } } // Adjusting the KL divergence if exaggeration is currently turned on // See https://github.com/pavlin-policar/fastTSNE/blob/master/notes/notes.pdf, Section 3.2 if (iter < stop_lying_iter && stop_lying_iter != -1) { C = C/early_exag_coeff - log(early_exag_coeff); } if (iter >= start_late_exag_iter && start_late_exag_iter != -1) { C = C/late_exag_coeff - log(late_exag_coeff); } costs[iter] = C; END_TIME("Computing Error"); std::chrono::steady_clock::time_point now = std::chrono::steady_clock::now(); printf("Iteration %d (50 iterations in %.2f seconds), cost %f\n", iter+1, std::chrono::duration_cast<std::chrono::milliseconds>(now-start_time).count()/(float)1000.0, C); start_time = std::chrono::steady_clock::now(); } } // Clean up memory free(dY); free(uY); free(gains); if (exact) { free(P); } else { free(row_P); free(col_P); free(val_P); } return 0; } // Compute gradient of the t-SNE cost function (using Barnes-Hut algorithm) void TSNE::computeGradient(double *P, unsigned int *inp_row_P, unsigned int *inp_col_P, double *inp_val_P, double *Y, int N, int D, double *dC, double theta, unsigned int nthreads) { // Construct space-partitioning tree on current map SPTree *tree = new SPTree(D, Y, N); // Compute all terms required for t-SNE gradient unsigned long SIZE = (unsigned long) N * (unsigned long) D; double sum_Q = .0; double *pos_f = (double *) calloc(SIZE, sizeof(double)); double *neg_f = (double *) calloc(SIZE, sizeof(double)); double *Q = (double *) calloc(N, sizeof(double)); if (pos_f == NULL || neg_f == NULL || Q == NULL) { printf("Memory allocation failed!\n"); exit(1); } tree->computeEdgeForces(inp_row_P, inp_col_P, inp_val_P, N, pos_f, nthreads); PARALLEL_FOR(nthreads, N, { tree->computeNonEdgeForces(loop_i, theta, neg_f + loop_i * D, Q + loop_i); }); for (int i=0; i<N; i++) { sum_Q += Q[i]; } // Compute final t-SNE gradient FILE *fp = nullptr; if (measure_accuracy) { char buffer[500]; sprintf(buffer, "temp/bh_gradient%d.txt", itTest); fp = fopen(buffer, "w"); // Open file for writing } for (unsigned long i = 0; i < N * D; i++) { dC[i] = pos_f[i] - (neg_f[i] / sum_Q); if (measure_accuracy) { if (i < N) { fprintf(fp, "%d, %.12e, %.12e, %.12e,%.12e,%.12e %.12e\n", i, dC[i * 2], dC[i * 2 + 1], pos_f[i * 2], pos_f[i * 2 + 1], neg_f[i * 2] / sum_Q, neg_f[i * 2 + 1] / sum_Q); } } } if (measure_accuracy) { fclose(fp); } free(pos_f); free(neg_f); delete tree; } // Compute the gradient of the t-SNE cost function using the FFT interpolation based approximation for for one // dimensional Ys void TSNE::computeFftGradientOneDVariableDf(double *P, unsigned int *inp_row_P, unsigned int *inp_col_P, double *inp_val_P, double *Y, int N, int D, double *dC, int n_interpolation_points, double intervals_per_integer, int min_num_intervals, unsigned int nthreads, double df) { // Zero out the gradient for (unsigned long i = 0; i < N * D; i++) dC[i] = 0.0; // Push all the points at which we will evaluate // Y is stored row major, with a row corresponding to a single point // Find the min and max values of Ys double y_min = INFINITY; double y_max = -INFINITY; for (unsigned long i = 0; i < N; i++) { if (Y[i] < y_min) y_min = Y[i]; if (Y[i] > y_max) y_max = Y[i]; } auto n_boxes = static_cast<int>(fmax(min_num_intervals, (y_max - y_min) / intervals_per_integer)); int squared_n_terms = 2; auto *SquaredChargesQij = new double[N * squared_n_terms]; auto *SquaredPotentialsQij = new double[N * squared_n_terms](); for (unsigned long j = 0; j < N; j++) { SquaredChargesQij[j * squared_n_terms + 0] = Y[j]; SquaredChargesQij[j * squared_n_terms + 1] = 1; } auto *box_lower_bounds = new double[n_boxes]; auto *box_upper_bounds = new double[n_boxes]; auto *y_tilde_spacings = new double[n_interpolation_points]; auto *y_tilde = new double[n_interpolation_points * n_boxes](); auto *fft_kernel_vector = new complex<double>[2 * n_interpolation_points * n_boxes]; precompute(y_min, y_max, n_boxes, n_interpolation_points, &squared_general_kernel, box_lower_bounds, box_upper_bounds, y_tilde_spacings, y_tilde, fft_kernel_vector, df); nbodyfft(N, squared_n_terms, Y, SquaredChargesQij, n_boxes, n_interpolation_points, box_lower_bounds, box_upper_bounds, y_tilde_spacings, y_tilde, fft_kernel_vector, SquaredPotentialsQij); int not_squared_n_terms = 1; auto *NotSquaredChargesQij = new double[N * not_squared_n_terms]; auto *NotSquaredPotentialsQij = new double[N * not_squared_n_terms](); for (unsigned long j = 0; j < N; j++) { NotSquaredChargesQij[j * not_squared_n_terms + 0] = 1; } precompute(y_min, y_max, n_boxes, n_interpolation_points, &general_kernel, box_lower_bounds, box_upper_bounds, y_tilde_spacings, y_tilde, fft_kernel_vector, df); nbodyfft(N, not_squared_n_terms, Y, NotSquaredChargesQij, n_boxes, n_interpolation_points, box_lower_bounds, box_upper_bounds, y_tilde_spacings, y_tilde, fft_kernel_vector, NotSquaredPotentialsQij); // Compute the normalization constant Z or sum of q_{ij}. double sum_Q = 0; for (unsigned long i = 0; i < N; i++) { double h1 = NotSquaredPotentialsQij[i * not_squared_n_terms+ 0]; sum_Q += h1; } sum_Q -= N; this->current_sum_Q = sum_Q; // Now, figure out the Gaussian component of the gradient. This corresponds to the "attraction" term of the // gradient. It was calculated using a fast KNN approach, so here we just use the results that were passed to this // function // unsigned int ind2 = 0; double *pos_f = new double[N]; PARALLEL_FOR(nthreads, N, { double dim1 = 0; for (unsigned int i = inp_row_P[loop_i]; i < inp_row_P[loop_i + 1]; i++) { // Compute pairwise distance and Q-value unsigned int ind3 = inp_col_P[i]; double d_ij = Y[loop_i] - Y[ind3]; double q_ij = 1 / (1 + (d_ij * d_ij)/df); dim1 += inp_val_P[i] * q_ij * d_ij; } pos_f[loop_i] = dim1; }); double *neg_f = new double[N * 2]; for (unsigned int i = 0; i < N; i++) { double h2 = SquaredPotentialsQij[i * squared_n_terms]; double h4 = SquaredPotentialsQij[i * squared_n_terms + 1]; neg_f[i] = ( Y[i] *h4 - h2 ) / sum_Q; dC[i ] = (pos_f[i] - neg_f[i ]); } delete[] SquaredChargesQij; delete[] SquaredPotentialsQij; delete[] NotSquaredChargesQij; delete[] NotSquaredPotentialsQij; delete[] pos_f; delete[] neg_f; delete[] box_lower_bounds; delete[] box_upper_bounds; delete[] y_tilde_spacings; delete[] y_tilde; delete[] fft_kernel_vector; } // Compute the gradient of the t-SNE cost function using the FFT interpolation based approximation for for one // dimensional Ys void TSNE::computeFftGradientOneD(double *P, unsigned int *inp_row_P, unsigned int *inp_col_P, double *inp_val_P, double *Y, int N, int D, double *dC, int n_interpolation_points, double intervals_per_integer, int min_num_intervals, unsigned int nthreads) { // Zero out the gradient for (unsigned long i = 0; i < N * D; i++) dC[i] = 0.0; // Push all the points at which we will evaluate // Y is stored row major, with a row corresponding to a single point // Find the min and max values of Ys double y_min = INFINITY; double y_max = -INFINITY; for (unsigned long i = 0; i < N; i++) { if (Y[i] < y_min) y_min = Y[i]; if (Y[i] > y_max) y_max = Y[i]; } auto n_boxes = static_cast<int>(fmax(min_num_intervals, (y_max - y_min) / intervals_per_integer)); // The number of "charges" or s+2 sums i.e. number of kernel sums int n_terms = 3; auto *chargesQij = new double[N * n_terms]; auto *potentialsQij = new double[N * n_terms](); // Prepare the terms that we'll use to compute the sum i.e. the repulsive forces for (unsigned long j = 0; j < N; j++) { chargesQij[j * n_terms + 0] = 1; chargesQij[j * n_terms + 1] = Y[j]; chargesQij[j * n_terms + 2] = Y[j] * Y[j]; } auto *box_lower_bounds = new double[n_boxes]; auto *box_upper_bounds = new double[n_boxes]; auto *y_tilde_spacings = new double[n_interpolation_points]; auto *y_tilde = new double[n_interpolation_points * n_boxes](); auto *fft_kernel_vector = new complex<double>[2 * n_interpolation_points * n_boxes]; precompute(y_min, y_max, n_boxes, n_interpolation_points, &squared_cauchy, box_lower_bounds, box_upper_bounds, y_tilde_spacings, y_tilde, fft_kernel_vector, 1.0); nbodyfft(N, n_terms, Y, chargesQij, n_boxes, n_interpolation_points, box_lower_bounds, box_upper_bounds, y_tilde_spacings, y_tilde, fft_kernel_vector, potentialsQij); delete[] box_lower_bounds; delete[] box_upper_bounds; delete[] y_tilde_spacings; delete[] y_tilde; delete[] fft_kernel_vector; // Compute the normalization constant Z or sum of q_{ij}. This expression is different from the one in the original // paper, but equivalent. This is done so we need only use a single kernel (K_2 in the paper) instead of two // different ones. We subtract N at the end because the following sums over all i, j, whereas Z contains i \neq j double sum_Q = 0; for (unsigned long i = 0; i < N; i++) { double phi1 = potentialsQij[i * n_terms + 0]; double phi2 = potentialsQij[i * n_terms + 1]; double phi3 = potentialsQij[i * n_terms + 2]; sum_Q += (1 + Y[i] * Y[i]) * phi1 - 2 * (Y[i] * phi2) + phi3; } sum_Q -= N; this->current_sum_Q = sum_Q; // Now, figure out the Gaussian component of the gradient. This corresponds to the "attraction" term of the // gradient. It was calculated using a fast KNN approach, so here we just use the results that were passed to this // function // unsigned int ind2 = 0; double *pos_f = new double[N]; PARALLEL_FOR(nthreads, N, { double dim1 = 0; for (unsigned int i = inp_row_P[loop_i]; i < inp_row_P[loop_i + 1]; i++) { // Compute pairwise distance and Q-value unsigned int ind3 = inp_col_P[i]; double d_ij = Y[loop_i] - Y[ind3]; double q_ij = 1 / (1 + d_ij * d_ij); dim1 += inp_val_P[i] * q_ij * d_ij; } pos_f[loop_i] = dim1; }); // Make the negative term, or F_rep in the equation 3 of the paper double *neg_f = new double[N]; for (unsigned int n = 0; n < N; n++) { neg_f[n] = (Y[n] * potentialsQij[n * n_terms] - potentialsQij[n * n_terms + 1]) / sum_Q; dC[n] = pos_f[n] - neg_f[n]; } delete[] chargesQij; delete[] potentialsQij; delete[] pos_f; delete[] neg_f; } // Compute the gradient of the t-SNE cost function using the FFT interpolation // based approximation, with variable degree of freedom df void TSNE::computeFftGradientVariableDf(double *P, unsigned int *inp_row_P, unsigned int *inp_col_P, double *inp_val_P, double *Y, int N, int D, double *dC, int n_interpolation_points, double intervals_per_integer, int min_num_intervals, unsigned int nthreads, double df) { // Zero out the gradient for (unsigned long i = 0; i < N * D; i++) dC[i] = 0.0; // For convenience, split the x and y coordinate values auto *xs = new double[N]; auto *ys = new double[N]; double min_coord = INFINITY; double max_coord = -INFINITY; // Find the min/max values of the x and y coordinates for (unsigned long i = 0; i < N; i++) { xs[i] = Y[i * 2 + 0]; ys[i] = Y[i * 2 + 1]; if (xs[i] > max_coord) max_coord = xs[i]; else if (xs[i] < min_coord) min_coord = xs[i]; if (ys[i] > max_coord) max_coord = ys[i]; else if (ys[i] < min_coord) min_coord = ys[i]; } // Compute the number of boxes in a single dimension and the total number of boxes in 2d auto n_boxes_per_dim = static_cast<int>(fmax(min_num_intervals, (max_coord - min_coord) / intervals_per_integer)); //printf("min_coord: %lf, max_coord: %lf, n_boxes_per_dim: %d, (max_coord - min_coord) / intervals_per_integer) %d\n", min_coord, max_coord, n_boxes_per_dim, static_cast<int>( (max_coord - min_coord) / intervals_per_integer)); // FFTW works faster on numbers that can be written as 2^a 3^b 5^c 7^d // 11^e 13^f, where e+f is either 0 or 1, and the other exponents are // arbitrary int allowed_n_boxes_per_dim[20] = {25,36, 50, 55, 60, 65, 70, 75, 80, 85, 90, 96, 100, 110, 120, 130, 140,150, 175, 200}; if ( n_boxes_per_dim < allowed_n_boxes_per_dim[19] ) { //Round up to nearest grid point int chosen_i; for (chosen_i =0; allowed_n_boxes_per_dim[chosen_i]< n_boxes_per_dim; chosen_i++); n_boxes_per_dim = allowed_n_boxes_per_dim[chosen_i]; } //printf(" n_boxes_per_dim: %d\n", n_boxes_per_dim ); // The number of "charges" or s+2 sums i.e. number of kernel sums int squared_n_terms = 3; auto *SquaredChargesQij = new double[N * squared_n_terms]; auto *SquaredPotentialsQij = new double[N * squared_n_terms](); // Prepare the terms that we'll use to compute the sum i.e. the repulsive forces for (unsigned long j = 0; j < N; j++) { SquaredChargesQij[j * squared_n_terms + 0] = xs[j]; SquaredChargesQij[j * squared_n_terms + 1] = ys[j]; SquaredChargesQij[j * squared_n_terms + 2] = 1; } // Compute the number of boxes in a single dimension and the total number of boxes in 2d int n_boxes = n_boxes_per_dim * n_boxes_per_dim; auto *box_lower_bounds = new double[2 * n_boxes]; auto *box_upper_bounds = new double[2 * n_boxes]; auto *y_tilde_spacings = new double[n_interpolation_points]; int n_interpolation_points_1d = n_interpolation_points * n_boxes_per_dim; auto *x_tilde = new double[n_interpolation_points_1d](); auto *y_tilde = new double[n_interpolation_points_1d](); auto *fft_kernel_tilde = new complex<double>[2 * n_interpolation_points_1d * 2 * n_interpolation_points_1d]; INITIALIZE_TIME; START_TIME; precompute_2d(max_coord, min_coord, max_coord, min_coord, n_boxes_per_dim, n_interpolation_points, &squared_general_kernel_2d, box_lower_bounds, box_upper_bounds, y_tilde_spacings, x_tilde, y_tilde, fft_kernel_tilde, df); n_body_fft_2d(N, squared_n_terms, xs, ys, SquaredChargesQij, n_boxes_per_dim, n_interpolation_points, box_lower_bounds, box_upper_bounds, y_tilde_spacings, fft_kernel_tilde, SquaredPotentialsQij, nthreads); int not_squared_n_terms = 1; auto *NotSquaredChargesQij = new double[N * not_squared_n_terms]; auto *NotSquaredPotentialsQij = new double[N * not_squared_n_terms](); // Prepare the terms that we'll use to compute the sum i.e. the repulsive forces for (unsigned long j = 0; j < N; j++) { NotSquaredChargesQij[j * not_squared_n_terms + 0] = 1; } precompute_2d(max_coord, min_coord, max_coord, min_coord, n_boxes_per_dim, n_interpolation_points, &general_kernel_2d, box_lower_bounds, box_upper_bounds, y_tilde_spacings, x_tilde, y_tilde, fft_kernel_tilde,df); n_body_fft_2d(N, not_squared_n_terms, xs, ys, NotSquaredChargesQij, n_boxes_per_dim, n_interpolation_points, box_lower_bounds, box_upper_bounds, y_tilde_spacings, fft_kernel_tilde, NotSquaredPotentialsQij, nthreads); // Compute the normalization constant Z or sum of q_{ij}. double sum_Q = 0; for (unsigned long i = 0; i < N; i++) { double h1 = NotSquaredPotentialsQij[i * not_squared_n_terms+ 0]; sum_Q += h1; } sum_Q -= N; // Now, figure out the Gaussian component of the gradient. This corresponds to the "attraction" term of the // gradient. It was calculated using a fast KNN approach, so here we just use the results that were passed to this // function unsigned int ind2 = 0; double *pos_f = new double[N * 2]; END_TIME("Total Interpolation"); START_TIME; // Loop over all edges in the graph PARALLEL_FOR(nthreads, N, { double dim1 = 0; double dim2 = 0; for (unsigned int i = inp_row_P[loop_i]; i < inp_row_P[loop_i + 1]; i++) { // Compute pairwise distance and Q-value unsigned int ind3 = inp_col_P[i]; double d_ij = (xs[loop_i] - xs[ind3]) * (xs[loop_i] - xs[ind3]) + (ys[loop_i] - ys[ind3]) * (ys[loop_i] - ys[ind3]); double q_ij = 1 / (1 + d_ij/df); dim1 += inp_val_P[i] * q_ij * (xs[loop_i] - xs[ind3]); dim2 += inp_val_P[i] * q_ij * (ys[loop_i] - ys[ind3]); } pos_f[loop_i * 2 + 0] = dim1; pos_f[loop_i * 2 + 1] = dim2; }); // Make the negative term, or F_rep in the equation 3 of the paper END_TIME("Attractive Forces"); double *neg_f = new double[N * 2]; for (unsigned int i = 0; i < N; i++) { double h2 = SquaredPotentialsQij[i * squared_n_terms]; double h3 = SquaredPotentialsQij[i * squared_n_terms + 1]; double h4 = SquaredPotentialsQij[i * squared_n_terms + 2]; neg_f[i * 2 + 0] = ( xs[i] *h4 - h2 ) / sum_Q; neg_f[i * 2 + 1] = (ys[i] *h4 - h3 ) / sum_Q; dC[i * 2 + 0] = (pos_f[i * 2] - neg_f[i * 2]); dC[i * 2 + 1] = (pos_f[i * 2 + 1] - neg_f[i * 2 + 1]); } this->current_sum_Q = sum_Q; /* FILE *fp = nullptr; char buffer[500]; sprintf(buffer, "temp/fft_gradient%d.txt", itTest); fp = fopen(buffer, "w"); // Open file for writing for (int i = 0; i < N; i++) { fprintf(fp, "%d,%.12e,%.12e\n", i, neg_f[i * 2] , neg_f[i * 2 + 1]); } fclose(fp);*/ delete[] pos_f; delete[] neg_f; delete[] SquaredPotentialsQij; delete[] NotSquaredPotentialsQij; delete[] SquaredChargesQij; delete[] NotSquaredChargesQij; delete[] xs; delete[] ys; delete[] box_lower_bounds; delete[] box_upper_bounds; delete[] y_tilde_spacings; delete[] y_tilde; delete[] x_tilde; delete[] fft_kernel_tilde; } // Compute the gradient of the t-SNE cost function using the FFT interpolation based approximation void TSNE::computeFftGradient(double *P, unsigned int *inp_row_P, unsigned int *inp_col_P, double *inp_val_P, double *Y, int N, int D, double *dC, int n_interpolation_points, double intervals_per_integer, int min_num_intervals, unsigned int nthreads) { // Zero out the gradient for (unsigned long i = 0; i < N * D; i++) dC[i] = 0.0; // For convenience, split the x and y coordinate values auto *xs = new double[N]; auto *ys = new double[N]; double min_coord = INFINITY; double max_coord = -INFINITY; // Find the min/max values of the x and y coordinates for (unsigned long i = 0; i < N; i++) { xs[i] = Y[i * 2 + 0]; ys[i] = Y[i * 2 + 1]; if (xs[i] > max_coord) max_coord = xs[i]; else if (xs[i] < min_coord) min_coord = xs[i]; if (ys[i] > max_coord) max_coord = ys[i]; else if (ys[i] < min_coord) min_coord = ys[i]; } // The number of "charges" or s+2 sums i.e. number of kernel sums int n_terms = 4; auto *chargesQij = new double[N * n_terms]; auto *potentialsQij = new double[N * n_terms](); // Prepare the terms that we'll use to compute the sum i.e. the repulsive forces for (unsigned long j = 0; j < N; j++) { chargesQij[j * n_terms + 0] = 1; chargesQij[j * n_terms + 1] = xs[j]; chargesQij[j * n_terms + 2] = ys[j]; chargesQij[j * n_terms + 3] = xs[j] * xs[j] + ys[j] * ys[j]; } // Compute the number of boxes in a single dimension and the total number of boxes in 2d auto n_boxes_per_dim = static_cast<int>(fmax(min_num_intervals, (max_coord - min_coord) / intervals_per_integer)); // FFTW works faster on numbers that can be written as 2^a 3^b 5^c 7^d // 11^e 13^f, where e+f is either 0 or 1, and the other exponents are // arbitrary int allowed_n_boxes_per_dim[20] = {25,36, 50, 55, 60, 65, 70, 75, 80, 85, 90, 96, 100, 110, 120, 130, 140,150, 175, 200}; if ( n_boxes_per_dim < allowed_n_boxes_per_dim[19] ) { //Round up to nearest grid point int chosen_i; for (chosen_i =0; allowed_n_boxes_per_dim[chosen_i]< n_boxes_per_dim; chosen_i++); n_boxes_per_dim = allowed_n_boxes_per_dim[chosen_i]; } int n_boxes = n_boxes_per_dim * n_boxes_per_dim; auto *box_lower_bounds = new double[2 * n_boxes]; auto *box_upper_bounds = new double[2 * n_boxes]; auto *y_tilde_spacings = new double[n_interpolation_points]; int n_interpolation_points_1d = n_interpolation_points * n_boxes_per_dim; auto *x_tilde = new double[n_interpolation_points_1d](); auto *y_tilde = new double[n_interpolation_points_1d](); auto *fft_kernel_tilde = new complex<double>[2 * n_interpolation_points_1d * 2 * n_interpolation_points_1d]; INITIALIZE_TIME; START_TIME; precompute_2d(max_coord, min_coord, max_coord, min_coord, n_boxes_per_dim, n_interpolation_points, &squared_cauchy_2d, box_lower_bounds, box_upper_bounds, y_tilde_spacings, x_tilde, y_tilde, fft_kernel_tilde,1.0); n_body_fft_2d(N, n_terms, xs, ys, chargesQij, n_boxes_per_dim, n_interpolation_points, box_lower_bounds, box_upper_bounds, y_tilde_spacings, fft_kernel_tilde, potentialsQij,nthreads); // Compute the normalization constant Z or sum of q_{ij}. This expression is different from the one in the original // paper, but equivalent. This is done so we need only use a single kernel (K_2 in the paper) instead of two // different ones. We subtract N at the end because the following sums over all i, j, whereas Z contains i \neq j double sum_Q = 0; for (unsigned long i = 0; i < N; i++) { double phi1 = potentialsQij[i * n_terms + 0]; double phi2 = potentialsQij[i * n_terms + 1]; double phi3 = potentialsQij[i * n_terms + 2]; double phi4 = potentialsQij[i * n_terms + 3]; sum_Q += (1 + xs[i] * xs[i] + ys[i] * ys[i]) * phi1 - 2 * (xs[i] * phi2 + ys[i] * phi3) + phi4; } sum_Q -= N; this->current_sum_Q = sum_Q; double *pos_f = new double[N * 2]; END_TIME("Total Interpolation"); START_TIME; // Now, figure out the Gaussian component of the gradient. This corresponds to the "attraction" term of the // gradient. It was calculated using a fast KNN approach, so here we just use the results that were passed to this // function PARALLEL_FOR(nthreads, N, { double dim1 = 0; double dim2 = 0; for (unsigned int i = inp_row_P[loop_i]; i < inp_row_P[loop_i + 1]; i++) { // Compute pairwise distance and Q-value unsigned int ind3 = inp_col_P[i]; double d_ij = (xs[loop_i] - xs[ind3]) * (xs[loop_i] - xs[ind3]) + (ys[loop_i] - ys[ind3]) * (ys[loop_i] - ys[ind3]); double q_ij = 1 / (1 + d_ij); dim1 += inp_val_P[i] * q_ij * (xs[loop_i] - xs[ind3]); dim2 += inp_val_P[i] * q_ij * (ys[loop_i] - ys[ind3]); } pos_f[loop_i * 2 + 0] = dim1; pos_f[loop_i * 2 + 1] = dim2; }); END_TIME("Attractive Forces"); //printf("Attractive forces took %lf\n", (diff(start20,end20))/(double)1E6); // Make the negative term, or F_rep in the equation 3 of the paper double *neg_f = new double[N * 2]; for (unsigned int i = 0; i < N; i++) { neg_f[i * 2 + 0] = (xs[i] * potentialsQij[i * n_terms] - potentialsQij[i * n_terms + 1]) / sum_Q; neg_f[i * 2 + 1] = (ys[i] * potentialsQij[i * n_terms] - potentialsQij[i * n_terms + 2]) / sum_Q; dC[i * 2 + 0] = pos_f[i * 2] - neg_f[i * 2]; dC[i * 2 + 1] = pos_f[i * 2 + 1] - neg_f[i * 2 + 1]; } delete[] pos_f; delete[] neg_f; delete[] potentialsQij; delete[] chargesQij; delete[] xs; delete[] ys; delete[] box_lower_bounds; delete[] box_upper_bounds; delete[] y_tilde_spacings; delete[] y_tilde; delete[] x_tilde; delete[] fft_kernel_tilde; } void TSNE::computeExactGradientTest(double *Y, int N, int D, double df ) { // Compute the squared Euclidean distance matrix double *DD = (double *) malloc(N * N * sizeof(double)); if (DD == NULL) { printf("Memory allocation failed!\n"); exit(1); } computeSquaredEuclideanDistance(Y, N, D, DD); // Compute Q-matrix and normalization sum double *Q = (double *) malloc(N * N * sizeof(double)); if (Q == NULL) { printf("Memory allocation failed!\n"); exit(1); } double sum_Q = .0; int nN = 0; for (int n = 0; n < N; n++) { for (int m = 0; m < N; m++) { if (n != m) { Q[nN + m] = 1.0 / pow(1.0 + DD[nN + m]/(double)df, (df)); sum_Q += Q[nN + m]; } } nN += N; } // Perform the computation of the gradient char buffer[500]; sprintf(buffer, "temp/exact_gradient%d.txt", itTest); FILE *fp = fopen(buffer, "w"); // Open file for writing nN = 0; int nD = 0; for (int n = 0; n < N; n++) { double testQij = 0; double testPos = 0; double testNeg1 = 0; double testNeg2 = 0; double testdC = 0; int mD = 0; for (int m = 0; m < N; m++) { if (n != m) { testNeg1 += pow(Q[nN + m],(df +1.0)/df) * (Y[nD + 0] - Y[mD + 0]) / sum_Q; testNeg2 += pow(Q[nN + m],(df +1.0)/df) * (Y[nD + 1] - Y[mD + 1]) / sum_Q; } mD += D; } fprintf(fp, "%d, %.12e, %.12e\n", n, testNeg1,testNeg2); nN += N; nD += D; } fclose(fp); free(DD); free(Q); } // Compute the exact gradient of the t-SNE cost function void TSNE::computeExactGradient(double *P, double *Y, int N, int D, double *dC, double df) { // Make sure the current gradient contains zeros for (unsigned long i = 0; i < N * D; i++) dC[i] = 0.0; // Compute the squared Euclidean distance matrix auto *DD = (double *) malloc(N * N * sizeof(double)); if (DD == nullptr) throw std::bad_alloc(); computeSquaredEuclideanDistance(Y, N, D, DD); // Compute Q-matrix and normalization sum auto *Q = (double *) malloc(N * N * sizeof(double)); if (Q == nullptr) throw std::bad_alloc(); auto *Qpow = (double *) malloc(N * N * sizeof(double)); if (Qpow == nullptr) throw std::bad_alloc(); double sum_Q = .0; int nN = 0; for (int n = 0; n < N; n++) { for (int m = 0; m < N; m++) { if (n != m) { //Q[nN + m] = 1.0 / pow(1.0 + DD[nN + m]/(double)df, df); Q[nN + m] = 1.0 / (1.0 + DD[nN + m]/(double)df); Qpow[nN + m] = pow(Q[nN + m], df); sum_Q += Qpow[nN + m]; } } nN += N; } // Perform the computation of the gradient nN = 0; int nD = 0; for (int n = 0; n < N; n++) { int mD = 0; for (int m = 0; m < N; m++) { if (n != m) { double mult = (P[nN + m] - (Qpow[nN + m] / sum_Q)) * (Q[nN + m]); for (int d = 0; d < D; d++) { dC[nD + d] += (Y[nD + d] - Y[mD + d]) * mult; } } mD += D; } nN += N; nD += D; } free(Q); free(Qpow); free(DD); } // Evaluate t-SNE cost function (exactly) double TSNE::evaluateError(double *P, double *Y, int N, int D, double df) { // Compute the squared Euclidean distance matrix double *DD = (double *) malloc(N * N * sizeof(double)); double *Q = (double *) malloc(N * N * sizeof(double)); if (DD == NULL || Q == NULL) { printf("Memory allocation failed!\n"); exit(1); } computeSquaredEuclideanDistance(Y, N, D, DD); // Compute Q-matrix and normalization sum int nN = 0; double sum_Q = DBL_MIN; for (int n = 0; n < N; n++) { for (int m = 0; m < N; m++) { if (n != m) { //Q[nN + m] = 1.0 / pow(1.0 + DD[nN + m]/(double)df, df); Q[nN + m] = 1.0 / (1.0 + DD[nN + m]/(double)df); Q[nN +m ] = pow(Q[nN +m ], df); sum_Q += Q[nN + m]; } else Q[nN + m] = DBL_MIN; } nN += N; } //printf("sum_Q: %e", sum_Q); for (int i = 0; i < N * N; i++) Q[i] /= sum_Q; // for (int i = 0; i < N; i++) printf("Q[%d]: %e\n", i, Q[i]); //printf("Q[N*N/2+1]: %e, Q[N*N-1]: %e\n", Q[N*N/2+1], Q[N*N/2+2]); // Sum t-SNE error double C = .0; for (int n = 0; n < N * N; n++) { C += P[n] * log((P[n] + FLT_MIN) / (Q[n] + FLT_MIN)); } // Clean up memory free(DD); free(Q); return C; } // Evaluate t-SNE cost function (approximately) using FFT double TSNE::evaluateErrorFft(unsigned int *row_P, unsigned int *col_P, double *val_P, double *Y, int N, int D,unsigned int nthreads, double df) { // Get estimate of normalization term double sum_Q = this->current_sum_Q; // Loop over all edges to compute t-SNE error double C = .0; PARALLEL_FOR(nthreads,N,{ double *buff = (double *) calloc(D, sizeof(double)); int ind1 = loop_i * D; double temp = 0; for (int i = row_P[loop_i]; i < row_P[loop_i + 1]; i++) { double Q = .0; int ind2 = col_P[i] * D; for (int d = 0; d < D; d++) buff[d] = Y[ind1 + d]; for (int d = 0; d < D; d++) buff[d] -= Y[ind2 + d]; for (int d = 0; d < D; d++) Q += buff[d] * buff[d]; Q = pow(1.0 / (1.0 + Q/df), df) / sum_Q; temp += val_P[i] * log((val_P[i] + FLT_MIN) / (Q + FLT_MIN)); } C += temp; free(buff); }); // Clean up memory return C; } // Evaluate t-SNE cost function (approximately) double TSNE::evaluateError(unsigned int *row_P, unsigned int *col_P, double *val_P, double *Y, int N, int D, double theta, unsigned int nthreads) { // Get estimate of normalization term SPTree *tree = new SPTree(D, Y, N); double *buff = (double *) calloc(D, sizeof(double)); double sum_Q = .0; for (int n = 0; n < N; n++) tree->computeNonEdgeForces(n, theta, buff, &sum_Q); double C = .0; PARALLEL_FOR(nthreads,N,{ double *buff = (double *) calloc(D, sizeof(double)); int ind1 = loop_i * D; double temp = 0; for (int i = row_P[loop_i]; i < row_P[loop_i + 1]; i++) { double Q = .0; int ind2 = col_P[i] * D; for (int d = 0; d < D; d++) buff[d] = Y[ind1 + d]; for (int d = 0; d < D; d++) buff[d] -= Y[ind2 + d]; for (int d = 0; d < D; d++) Q += buff[d] * buff[d]; Q = (1.0 / (1.0 + Q)) / sum_Q; temp += val_P[i] * log((val_P[i] + FLT_MIN) / (Q + FLT_MIN)); } C += temp; free(buff); }); // Clean up memory free(buff); delete tree; return C; } // Converts an array of [squared] Euclidean distances into similarities aka affinities // using a specified perplexity value (or a specified kernel width) double TSNE::distances2similarities(double *D, double *P, int N, int n, double perplexity, double sigma, bool ifSquared) { /* D - a pointer to the array of distances P - a pointer to the array of similarities N - length of D and P n - index of the point that should have D = 0 perplexity - target perplexity sigma - kernel width if perplexity == -1 ifSquared - if D contains squared distances (TRUE) or not (FALSE) */ double sum_P; double beta; if (perplexity > 0) { // Using binary search to find the appropriate kernel width double min_beta = -DBL_MAX; double max_beta = DBL_MAX; double tol = 1e-5; int max_iter = 200; int iter = 0; bool found = false; beta = 1.0; // Iterate until we found a good kernel width while(!found && iter < max_iter) { // Apply Gaussian kernel for(int m = 0; m < N; m++) P[m] = exp(-beta * (ifSquared ? D[m] : D[m]*D[m])); if (n>=0) P[n] = DBL_MIN; // Compute entropy sum_P = DBL_MIN; for(int m = 0; m < N; m++) sum_P += P[m]; double H = 0.0; for(int m = 0; m < N; m++) H += beta * ((ifSquared ? D[m] : D[m]*D[m]) * P[m]); H = (H / sum_P) + log(sum_P); // Evaluate whether the entropy is within the tolerance level double Hdiff = H - log(perplexity); if(Hdiff < tol && -Hdiff < tol) { found = true; } else { if(Hdiff > 0) { min_beta = beta; if(max_beta == DBL_MAX || max_beta == -DBL_MAX) beta *= 2.0; else beta = (beta + max_beta) / 2.0; } else { max_beta = beta; if(min_beta == -DBL_MAX || min_beta == DBL_MAX) beta /= 2.0; else beta = (beta + min_beta) / 2.0; } } // Update iteration counter iter++; } }else{ // Using fixed kernel width: no iterations needed beta = 1/(2*sigma*sigma); for(int m = 0; m < N; m++) P[m] = exp(-beta * (ifSquared ? D[m] : D[m]*D[m])); if (n >= 0) P[n] = DBL_MIN; sum_P = DBL_MIN; for(int m = 0; m < N; m++) sum_P += P[m]; } // Normalize for(int m = 0; m < N; m++) P[m] /= sum_P; return beta; } // Converts an array of [squared] Euclidean distances into similarities aka affinities // using a list of perplexities double TSNE::distances2similarities(double *D, double *P, int N, int n, double perplexity, double sigma, bool ifSquared, int perplexity_list_length, double *perplexity_list) { // if perplexity != 0 then defaulting to using this perplexity (or fixed sigma) if (perplexity != 0) { double beta = distances2similarities(D, P, N, n, perplexity, sigma, true); return beta; } // otherwise averaging similarities using all perplexities in perplexity_list double *tmp = (double*) malloc(N * sizeof(double)); if(tmp == NULL) { printf("Memory allocation failed!\n"); exit(1); } double beta = distances2similarities(D, P, N, n, perplexity_list[0], sigma, true); for (int m=1; m < perplexity_list_length; m++){ beta = distances2similarities(D, tmp, N, n, perplexity_list[m], sigma, true); for (int i=0; i<N; i++){ P[i] += tmp[i]; } } for (int i=0; i<N; i++){ P[i] /= perplexity_list_length; } return beta; } // Compute input similarities using exact algorithm void TSNE::computeGaussianPerplexity(double *X, int N, int D, double *P, double perplexity, double sigma, int perplexity_list_length, double *perplexity_list) { if (perplexity < 0) { printf("Using manually set kernel width\n"); } else { printf("Using perplexity, not the manually set kernel width\n"); } // Compute the squared Euclidean distance matrix double *DD = (double *) malloc(N * N * sizeof(double)); if (DD == NULL) { printf("Memory allocation failed!\n"); exit(1); } computeSquaredEuclideanDistance(X, N, D, DD); // Convert distances to similarities using Gaussian kernel row by row int nN = 0; double beta; for (int n = 0; n < N; n++) { beta = distances2similarities(&DD[nN], &P[nN], N, n, perplexity, sigma, true, perplexity_list_length, perplexity_list); nN += N; } // Clean up memory free(DD); } // Compute input similarities using ANNOY int TSNE::computeGaussianPerplexity(double *X, int N, int D, unsigned int **_row_P, unsigned int **_col_P, double **_val_P, double perplexity, int K, double sigma, int num_trees, int search_k, unsigned int nthreads, int perplexity_list_length, double *perplexity_list, int rand_seed) { if(perplexity > K) printf("Perplexity should be lower than K!\n"); // Allocate the memory we need printf("Going to allocate memory. N: %d, K: %d, N*K = %d\n", N, K, N*K); *_row_P = (unsigned int*) malloc((N + 1) * sizeof(unsigned int)); *_col_P = (unsigned int*) calloc(N * K, sizeof(unsigned int)); *_val_P = (double*) calloc(N * K, sizeof(double)); if(*_row_P == NULL || *_col_P == NULL || *_val_P == NULL) { printf("Memory allocation failed!\n"); exit(1); } unsigned int* row_P = *_row_P; unsigned int* col_P = *_col_P; double* val_P = *_val_P; row_P[0] = 0; for(int n = 0; n < N; n++) row_P[n + 1] = row_P[n] + (unsigned int) K; printf("Building Annoy tree...\n"); AnnoyIndex<int, double, Euclidean, Kiss32Random> tree = AnnoyIndex<int, double, Euclidean, Kiss32Random>(D); if (rand_seed > 0) { tree.set_seed(rand_seed); } for(unsigned long i=0; i<N; ++i){ double *vec = (double *) malloc( D * sizeof(double) ); for(unsigned long z=0; z<D; ++z){ vec[z] = X[i*D+z]; } tree.add_item(i, vec); } tree.build(num_trees); //Check if it returns enough neighbors std::vector<int> closest; std::vector<double> closest_distances; for (int n = 0; n < 100; n++){ tree.get_nns_by_item(n, K+1, search_k, &closest, &closest_distances); unsigned int neighbors_count = closest.size(); if (neighbors_count < K+1 ) { printf("Requesting perplexity*3=%d neighbors, but ANNOY is only giving us %u. Please increase search_k\n", K, neighbors_count); return -1; } } printf("Done building tree. Beginning nearest neighbor search... \n"); ProgressBar bar(N,60); //const size_t nthreads = 1; { // Pre loop std::cout << "parallel (" << nthreads << " threads):" << std::endl; std::vector<std::thread> threads(nthreads); for (int t = 0; t < nthreads; t++) { threads[t] = std::thread(std::bind( [&](const int bi, const int ei, const int t) { // loop over all items for(int n = bi;n<ei;n++) { // inner loop { // Find nearest neighbors std::vector<int> closest; std::vector<double> closest_distances; tree.get_nns_by_item(n, K+1, search_k, &closest, &closest_distances); double* cur_P = (double*) malloc((N - 1) * sizeof(double)); if(cur_P == NULL) { printf("Memory allocation failed!\n"); exit(1); } double beta = distances2similarities(&closest_distances[1], cur_P, K, -1, perplexity, sigma, false, perplexity_list_length, perplexity_list); ++bar; if(t == 0 && n % 100 == 0) { bar.display(); // if (perplexity >= 0) { // printf(" - point %d of %d, most recent beta calculated is %lf \n", n, N, beta); // } else { // printf(" - point %d of %d, beta is set to %lf \n", n, N, 1/sigma); // } } // Store current row of P in matrix for(unsigned int m = 0; m < K; m++) { col_P[row_P[n] + m] = (unsigned int) closest[m + 1]; val_P[row_P[n] + m] = cur_P[m]; } free(cur_P); closest.clear(); closest_distances.clear(); } } },t*N/nthreads,(t+1)==nthreads?N:(t+1)*N/nthreads,t)); } std::for_each(threads.begin(),threads.end(),[](std::thread& x){x.join();}); // Post loop } bar.display(); printf("\n"); return 0; } // Compute input similarities with a fixed perplexity using ball trees (this function allocates memory another function should free) void TSNE::computeGaussianPerplexity(double *X, int N, int D, unsigned int **_row_P, unsigned int **_col_P, double **_val_P, double perplexity, int K, double sigma, unsigned int nthreads, int perplexity_list_length, double *perplexity_list) { if(perplexity > K) printf("Perplexity should be lower than K!\n"); // Allocate the memory we need printf("Going to allocate memory. N: %d, K: %d, N*K = %d\n", N, K, N*K); *_row_P = (unsigned int*) malloc((N + 1) * sizeof(unsigned int)); *_col_P = (unsigned int*) calloc(N * K, sizeof(unsigned int)); *_val_P = (double*) calloc(N * K, sizeof(double)); if(*_row_P == NULL || *_col_P == NULL || *_val_P == NULL) { printf("Memory allocation failed!\n"); exit(1); } unsigned int* row_P = *_row_P; unsigned int* col_P = *_col_P; double* val_P = *_val_P; row_P[0] = 0; for(int n = 0; n < N; n++) row_P[n + 1] = row_P[n] + (unsigned int) K; // Build ball tree on data set printf("Building VP tree...\n"); VpTree<DataPoint, euclidean_distance> *tree = new VpTree<DataPoint, euclidean_distance>(); vector<DataPoint> obj_X(N, DataPoint(D, -1, X)); for (int n = 0; n < N; n++) obj_X[n] = DataPoint(D, n, X + n * D); tree->create(obj_X); printf("Done building tree. Beginning nearest neighbor search... \n"); ProgressBar bar(N,60); //const size_t nthreads = 1; { // Pre loop std::cout << "parallel (" << nthreads << " threads):" << std::endl; std::vector<std::thread> threads(nthreads); for (int t = 0; t < nthreads; t++) { threads[t] = std::thread(std::bind( [&](const int bi, const int ei, const int t) { // loop over all items for(int n = bi;n<ei;n++) { // inner loop { // Find nearest neighbors std::vector<double> cur_P(K); vector<DataPoint> indices; vector<double> distances; tree->search(obj_X[n], K + 1, &indices, &distances); double beta = distances2similarities(&distances[1], &cur_P[0], K, -1, perplexity, sigma, false, perplexity_list_length, perplexity_list); ++bar; if(t == 0 && n % 100 == 0) { bar.display(); // if (perplexity >= 0) { // printf(" - point %d of %d, most recent beta calculated is %lf \n", n, N, beta); // } else { // printf(" - point %d of %d, beta is set to %lf \n", n, N, 1/sigma); // } } for(unsigned int m = 0; m < K; m++) { col_P[row_P[n] + m] = (unsigned int) indices[m + 1].index(); val_P[row_P[n] + m] = cur_P[m]; } indices.clear(); distances.clear(); cur_P.clear(); } } },t*N/nthreads,(t+1)==nthreads?N:(t+1)*N/nthreads,t)); } std::for_each(threads.begin(),threads.end(),[](std::thread& x){x.join();}); // Post loop } bar.display(); printf("\n"); // Clean up memory obj_X.clear(); delete tree; } // Symmetrizes a sparse matrix void TSNE::symmetrizeMatrix(unsigned int **_row_P, unsigned int **_col_P, double **_val_P, int N) { // Get sparse matrix unsigned int *row_P = *_row_P; unsigned int *col_P = *_col_P; double *val_P = *_val_P; // Count number of elements and row counts of symmetric matrix int *row_counts = (int *) calloc(N, sizeof(int)); if (row_counts == NULL) { printf("Memory allocation failed!\n"); exit(1); } for (int n = 0; n < N; n++) { for (int i = row_P[n]; i < row_P[n + 1]; i++) { // Check whether element (col_P[i], n) is present bool present = false; for (int m = row_P[col_P[i]]; m < row_P[col_P[i] + 1]; m++) { if (col_P[m] == n) present = true; } if (present) row_counts[n]++; else { row_counts[n]++; row_counts[col_P[i]]++; } } } int no_elem = 0; for (int n = 0; n < N; n++) no_elem += row_counts[n]; // Allocate memory for symmetrized matrix unsigned int *sym_row_P = (unsigned int *) malloc((N + 1) * sizeof(unsigned int)); unsigned int *sym_col_P = (unsigned int *) malloc(no_elem * sizeof(unsigned int)); double *sym_val_P = (double *) malloc(no_elem * sizeof(double)); if (sym_row_P == NULL || sym_col_P == NULL || sym_val_P == NULL) { printf("Memory allocation failed!\n"); exit(1); } // Construct new row indices for symmetric matrix sym_row_P[0] = 0; for (int n = 0; n < N; n++) sym_row_P[n + 1] = sym_row_P[n] + (unsigned int) row_counts[n]; // Fill the result matrix int *offset = (int *) calloc(N, sizeof(int)); if (offset == NULL) { printf("Memory allocation failed!\n"); exit(1); } for (int n = 0; n < N; n++) { for (unsigned int i = row_P[n]; i < row_P[n + 1]; i++) { // considering element(n, col_P[i]) // Check whether element (col_P[i], n) is present bool present = false; for (unsigned int m = row_P[col_P[i]]; m < row_P[col_P[i] + 1]; m++) { if (col_P[m] == n) { present = true; if (n <= col_P[i]) { // make sure we do not add elements twice sym_col_P[sym_row_P[n] + offset[n]] = col_P[i]; sym_col_P[sym_row_P[col_P[i]] + offset[col_P[i]]] = n; sym_val_P[sym_row_P[n] + offset[n]] = val_P[i] + val_P[m]; sym_val_P[sym_row_P[col_P[i]] + offset[col_P[i]]] = val_P[i] + val_P[m]; } } } // If (col_P[i], n) is not present, there is no addition involved if (!present) { sym_col_P[sym_row_P[n] + offset[n]] = col_P[i]; sym_col_P[sym_row_P[col_P[i]] + offset[col_P[i]]] = n; sym_val_P[sym_row_P[n] + offset[n]] = val_P[i]; sym_val_P[sym_row_P[col_P[i]] + offset[col_P[i]]] = val_P[i]; } // Update offsets if (!present || (n <= col_P[i])) { offset[n]++; if (col_P[i] != n) offset[col_P[i]]++; } } } // Divide the result by two for (int i = 0; i < no_elem; i++) sym_val_P[i] /= 2.0; // Return symmetrized matrices free(*_row_P); *_row_P = sym_row_P; free(*_col_P); *_col_P = sym_col_P; free(*_val_P); *_val_P = sym_val_P; // Free up some memory free(offset); free(row_counts); } // Compute squared Euclidean distance matrix void TSNE::computeSquaredEuclideanDistance(double *X, int N, int D, double *DD) { const double *XnD = X; for (int n = 0; n < N; ++n, XnD += D) { const double *XmD = XnD + D; double *curr_elem = &DD[n * N + n]; *curr_elem = 0.0; double *curr_elem_sym = curr_elem + N; for (int m = n + 1; m < N; ++m, XmD += D, curr_elem_sym += N) { *(++curr_elem) = 0.0; for (int d = 0; d < D; ++d) { *curr_elem += (XnD[d] - XmD[d]) * (XnD[d] - XmD[d]); } *curr_elem_sym = *curr_elem; } } } // Makes data zero-mean void TSNE::zeroMean(double *X, int N, int D) { // Compute data mean double *mean = (double *) calloc(D, sizeof(double)); if (mean == NULL) throw std::bad_alloc(); unsigned long nD = 0; for (int n = 0; n < N; n++) { for (int d = 0; d < D; d++) { mean[d] += X[nD + d]; } nD += D; } for (int d = 0; d < D; d++) { mean[d] /= (double) N; } // Subtract data mean nD = 0; for (int n = 0; n < N; n++) { for (int d = 0; d < D; d++) { X[nD + d] -= mean[d]; } nD += D; } free(mean); } // Generates a Gaussian random number double TSNE::randn() { double x, y, radius; do { x = 2 * (rand() / ((double) RAND_MAX + 1)) - 1; y = 2 * (rand() / ((double) RAND_MAX + 1)) - 1; radius = (x * x) + (y * y); } while ((radius >= 1.0) || (radius == 0.0)); radius = sqrt(-2 * log(radius) / radius); x *= radius; return x; } // Function that loads data from a t-SNE file // Note: this function does a malloc that should be freed elsewhere bool TSNE::load_data(const char *data_path, double **data, double **Y, int *n, int *d, int *no_dims, double *theta, double *perplexity, int *rand_seed, int *max_iter, int *stop_lying_iter, int *mom_switch_iter, double* momentum, double* final_momentum, double* learning_rate, int *K, double *sigma, int *nbody_algo, int *knn_algo, double *early_exag_coeff, int *no_momentum_during_exag, int *n_trees, int *search_k, int *start_late_exag_iter, double *late_exag_coeff, int *nterms, double *intervals_per_integer, int *min_num_intervals, bool *skip_random_init, int *load_affinities, int *perplexity_list_length, double **perplexity_list, double * df, double *max_step_norm) { FILE *h; if((h = fopen(data_path, "r+b")) == NULL) { printf("Error: could not open data file.\n"); return false; } size_t result; // need this to get rid of warnings that otherwise appear result = fread(n, sizeof(int), 1, h); // number of datapoints result = fread(d, sizeof(int), 1, h); // original dimensionality result = fread(theta, sizeof(double), 1, h); // gradient accuracy result = fread(perplexity, sizeof(double), 1, h); // perplexity // if perplexity == 0, then what follows is the number of perplexities // to combine and then the list of these perpexities if (*perplexity == 0) { result = fread(perplexity_list_length, sizeof(int), 1, h); *perplexity_list = (double*) malloc(*perplexity_list_length * sizeof(double)); if(*perplexity_list == NULL) { printf("Memory allocation failed!\n"); exit(1); } result = fread(*perplexity_list, sizeof(double), *perplexity_list_length, h); } else { perplexity_list_length = 0; perplexity_list = NULL; } result = fread(no_dims, sizeof(int), 1, h); // output dimensionality result = fread(max_iter, sizeof(int),1,h); // maximum number of iterations result = fread(stop_lying_iter, sizeof(int),1,h); // when to stop early exaggeration result = fread(mom_switch_iter, sizeof(int),1,h); // when to switch the momentum value result = fread(momentum, sizeof(double),1,h); // initial momentum result = fread(final_momentum, sizeof(double),1,h); // final momentum result = fread(learning_rate, sizeof(double),1,h); // learning rate result = fread(max_step_norm, sizeof(double),1,h); // max step norm result = fread(K, sizeof(int),1,h); // number of neighbours to compute result = fread(sigma, sizeof(double),1,h); // input kernel width result = fread(nbody_algo, sizeof(int),1,h); // Barnes-Hut or FFT result = fread(knn_algo, sizeof(int),1,h); // VP-trees or Annoy result = fread(early_exag_coeff, sizeof(double),1,h); // early exaggeration result = fread(no_momentum_during_exag, sizeof(int),1,h); // if to use momentum during early exagg result = fread(n_trees, sizeof(int),1,h); // number of trees for Annoy result = fread(search_k, sizeof(int),1,h); // search_k for Annoy result = fread(start_late_exag_iter, sizeof(int),1,h); // when to start late exaggeration result = fread(late_exag_coeff, sizeof(double),1,h); // late exaggeration result = fread(nterms, sizeof(int),1,h); // FFT parameter result = fread(intervals_per_integer, sizeof(double),1,h); // FFT parameter result = fread(min_num_intervals, sizeof(int),1,h); // FFT parameter if((*nbody_algo == 2) && (*no_dims > 2)){ printf("FFT interpolation scheme supports only 1 or 2 output dimensions, not %d\n", *no_dims); exit(1); } *data = (double*) malloc((unsigned long)*d * (unsigned long) *n * sizeof(double)); if(*data == NULL) { printf("Memory allocation failed!\n"); exit(1); } result = fread(*data, sizeof(double), (unsigned long) *n * (unsigned long) *d, h); // the data if(!feof(h)) { result = fread(rand_seed, sizeof(int), 1, h); // random seed } if(!feof(h)) { result = fread(df, sizeof(double),1,h); // Number of degrees of freedom of the kernel } if(!feof(h)) { result = fread(load_affinities, sizeof(int), 1, h); // to load or to save affinities } // allocating space for the t-sne solution *Y = (double*) malloc(*n * *no_dims * sizeof(double)); if(*Y == NULL) { printf("Memory allocation failed!\n"); exit(1); } // if the file has not ended, the remaining part is the initialization if(!feof(h)){ result = fread(*Y, sizeof(double), *n * *no_dims, h); if(result < *n * *no_dims){ *skip_random_init = false; }else{ *skip_random_init = true; } } else{ *skip_random_init = false; } fclose(h); printf("Read the following parameters:\n\t n %d by d %d dataset, theta %lf,\n" "\t perplexity %lf, no_dims %d, max_iter %d,\n" "\t stop_lying_iter %d, mom_switch_iter %d,\n" "\t momentum %lf, final_momentum %lf,\n" "\t learning_rate %lf, max_step_norm %lf,\n" "\t K %d, sigma %lf, nbody_algo %d,\n" "\t knn_algo %d, early_exag_coeff %lf,\n" "\t no_momentum_during_exag %d, n_trees %d, search_k %d,\n" "\t start_late_exag_iter %d, late_exag_coeff %lf\n" "\t nterms %d, interval_per_integer %lf, min_num_intervals %d, t-dist df %lf\n", *n, *d, *theta, *perplexity, *no_dims, *max_iter,*stop_lying_iter, *mom_switch_iter, *momentum, *final_momentum, *learning_rate, *max_step_norm, *K, *sigma, *nbody_algo, *knn_algo, *early_exag_coeff, *no_momentum_during_exag, *n_trees, *search_k, *start_late_exag_iter, *late_exag_coeff, *nterms, *intervals_per_integer, *min_num_intervals, *df); printf("Read the %i x %i data matrix successfully. X[0,0] = %lf\n", *n, *d, *data[0]); if(*perplexity == 0){ printf("Read the list of perplexities: "); for (int m=0; m<*perplexity_list_length; m++){ printf("%f ", (*perplexity_list)[m]); } printf("\n"); } if(*skip_random_init){ printf("Read the initialization successfully.\n"); } return true; } // Function that saves map to a t-SNE file void TSNE::save_data(const char *result_path, double* data, double* costs, int n, int d, int max_iter) { // Open file, write first 2 integers and then the data FILE *h; if((h = fopen(result_path, "w+b")) == NULL) { printf("Error: could not open data file.\n"); return; } fwrite(&n, sizeof(int), 1, h); fwrite(&d, sizeof(int), 1, h); fwrite(data, sizeof(double), n * d, h); fwrite(&max_iter, sizeof(int), 1, h); fwrite(costs, sizeof(double), max_iter, h); fclose(h); printf("Wrote the %i x %i data matrix successfully.\n", n, d); } int main(int argc, char *argv[]) { const char version_number[] = "1.2.1"; printf("=============== t-SNE v%s ===============\n", version_number); // Define some variables int N, D, no_dims, max_iter, stop_lying_iter; int K, nbody_algo, knn_algo, no_momentum_during_exag; int mom_switch_iter; double momentum, final_momentum, learning_rate, max_step_norm; int n_trees, search_k, start_late_exag_iter; double sigma, early_exag_coeff, late_exag_coeff; double perplexity, theta, *data, *initial_data; int nterms, min_num_intervals; double intervals_per_integer; int rand_seed = 0; int load_affinities = 0; const char *data_path, *result_path; unsigned int nthreads; TSNE* tsne = new TSNE(); double *Y; bool skip_random_init; double *perplexity_list; int perplexity_list_length; double df; data_path = "data.dat"; result_path = "result.dat"; nthreads = 0; if (argc >=2 ) { if ( strcmp(argv[1],version_number)) { std::cout<<"Wrapper passed wrong version number: "<< argv[1] <<std::endl; exit(-1); } }else{ std::cout<<"Please pass version number as first argument." <<std::endl; exit(-1); } if(argc >= 3) { data_path = argv[2]; } if(argc >= 4) { result_path = argv[3]; } if(argc >= 5) { nthreads = (unsigned int)strtoul(argv[4], (char **)NULL, 10); } if (nthreads == 0) { nthreads = std::thread::hardware_concurrency(); } std::cout<<"fast_tsne data_path: "<< data_path <<std::endl; std::cout<<"fast_tsne result_path: "<< result_path <<std::endl; std::cout<<"fast_tsne nthreads: "<< nthreads <<std::endl; // Read the parameters and the dataset if(tsne->load_data(data_path, &data, &Y, &N, &D, &no_dims, &theta, &perplexity, &rand_seed, &max_iter, &stop_lying_iter, &mom_switch_iter, &momentum, &final_momentum, &learning_rate, &K, &sigma, &nbody_algo, &knn_algo, &early_exag_coeff, &no_momentum_during_exag, &n_trees, &search_k, &start_late_exag_iter, &late_exag_coeff, &nterms, &intervals_per_integer, &min_num_intervals, &skip_random_init, &load_affinities, &perplexity_list_length, &perplexity_list, &df, &max_step_norm)) { bool no_momentum_during_exag_bool = true; if (no_momentum_during_exag == 0) no_momentum_during_exag_bool = false; // Now fire up the SNE implementation double* costs = (double*) calloc(max_iter, sizeof(double)); if(costs == NULL) { printf("Memory allocation failed!\n"); exit(1); } int error_code = 0; error_code = tsne->run(data, N, D, Y, no_dims, perplexity, theta, rand_seed, skip_random_init, max_iter, stop_lying_iter, mom_switch_iter, momentum, final_momentum, learning_rate, K, sigma, nbody_algo, knn_algo, early_exag_coeff, costs, no_momentum_during_exag_bool, start_late_exag_iter, late_exag_coeff, n_trees,search_k, nterms, intervals_per_integer, min_num_intervals, nthreads, load_affinities, perplexity_list_length, perplexity_list, df, max_step_norm); if (error_code < 0) { exit(error_code); } // Save the results tsne->save_data(result_path, Y, costs, N, no_dims, max_iter); // Clean up the memory free(data); data = NULL; free(Y); Y = NULL; free(costs); costs = NULL; } delete(tsne); printf("Done.\n\n"); }
82,871
37.779598
231
cpp
FIt-SNE
FIt-SNE-master/src/tsne.h
/* * * Copyright (c) 2014, Laurens van der Maaten (Delft University of Technology) * 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. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the Delft University of Technology. * 4. Neither the name of the Delft University of Technology 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 LAURENS VAN DER MAATEN ''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 LAURENS VAN DER MAATEN 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. * */ #ifndef TSNE_H #define TSNE_H static inline double sign(double x) { return (x == .0 ? .0 : (x < .0 ? -1.0 : 1.0)); } class TSNE { public: int run(double *X, int N, int D, double *Y, int no_dims, double perplexity, double theta, int rand_seed, bool skip_random_init, int max_iter, int stop_lying_iter, int mom_switch_iter, double momentum, double final_momentum, double learning_rate, int K, double sigma, int nbody_algorithm, int knn_algo, double early_exag_coeff, double *costs, bool no_momentum_during_exag, int start_late_exag_iter, double late_exag_coeff, int n_trees, int search_k, int nterms, double intervals_per_integer, int min_num_intervals, unsigned int nthreads, int load_affinities, int perplexity_list_length, double *perplexity_list, double df, double max_step_norm); bool load_data(const char *data_path, double **data, double **Y, int *n, int *d, int *no_dims, double *theta, double *perplexity, int *rand_seed, int *max_iter, int *stop_lying_iter, int *mom_switch_iter, double* momentum, double* final_momentum, double* learning_rate, int *K, double *sigma, int *nbody_algo, int *knn_algo, double* early_exag_coeff, int *no_momentum_during_exag, int *n_trees, int *search_k, int *start_late_exag_iter, double *late_exag_coeff, int *nterms, double *intervals_per_integer, int *min_num_intervals, bool *skip_random_init, int *load_affinities, int *perplexity_list_length, double **perplexity_list, double *df, double *max_step_norm); void save_data(const char *result_path, double *data, double *costs, int n, int d, int max_iter); void symmetrizeMatrix(unsigned int **row_P, unsigned int **col_P, double **val_P, int N); // should be static! private: double current_sum_Q; void computeGradient(double *P, unsigned int *inp_row_P, unsigned int *inp_col_P, double *inp_val_P, double *Y, int N, int D, double *dC, double theta, unsigned int nthreads); void computeFftGradientVariableDf(double *P, unsigned int *inp_row_P, unsigned int *inp_col_P, double *inp_val_P, double *Y, int N, int D, double *dC, int n_interpolation_points, double intervals_per_integer, int min_num_intervals, unsigned int nthreads, double df); void computeFftGradient(double *P, unsigned int *inp_row_P, unsigned int *inp_col_P, double *inp_val_P, double *Y, int N, int D, double *dC, int n_interpolation_points, double intervals_per_integer, int min_num_intervals, unsigned int nthreads); void computeFftGradientOneDVariableDf(double *P, unsigned int *inp_row_P, unsigned int *inp_col_P, double *inp_val_P, double *Y, int N, int D, double *dC, int n_interpolation_points, double intervals_per_integer, int min_num_intervals, unsigned int nthreads, double df); void computeFftGradientOneD(double *P, unsigned int *inp_row_P, unsigned int *inp_col_P, double *inp_val_P, double *Y, int N, int D, double *dC, int n_interpolation_points, double intervals_per_integer, int min_num_intervals, unsigned int nthreads); void computeExactGradient(double *P, double *Y, int N, int D, double *dC, double df); void computeExactGradientTest(double *Y, int N, int D, double df); double evaluateError(double *P, double *Y, int N, int D, double df); double evaluateError(unsigned int *row_P, unsigned int *col_P, double *val_P, double *Y, int N, int D, double theta, unsigned int nthreads); double evaluateErrorFft(unsigned int *row_P, unsigned int *col_P, double *val_P, double *Y, int N, int D, unsigned int nthreads, double df); void zeroMean(double *X, int N, int D); double distances2similarities(double *D, double *P, int N, int n, double perplexity, double sigma, bool ifSquared); double distances2similarities(double *D, double *P, int N, int n, double perplexity, double sigma, bool ifSquared, int perplexity_list_length, double *perplexity_list); void computeGaussianPerplexity(double *X, int N, int D, double *P, double perplexity, double sigma, int perplexity_list_length, double *perplexity_list); void computeGaussianPerplexity(double *X, int N, int D, unsigned int **_row_P, unsigned int **_col_P, double **_val_P, double perplexity, int K, double sigma, unsigned int nthreads, int perplexity_list_length, double *perplexity_list); int computeGaussianPerplexity(double *X, int N, int D, unsigned int **_row_P, unsigned int **_col_P, double **_val_P, double perplexity, int K, double sigma, int num_trees, int search_k, unsigned int nthreads, int perplexity_list_length, double *perplexity_list, int rand_seed); void computeSquaredEuclideanDistance(double *X, int N, int D, double *DD); double randn(); }; #endif
7,140
59.516949
144
h
FIt-SNE
FIt-SNE-master/src/vptree.h
/* * * Copyright (c) 2014, Laurens van der Maaten (Delft University of Technology) * 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. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the Delft University of Technology. * 4. Neither the name of the Delft University of Technology 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 LAURENS VAN DER MAATEN ''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 LAURENS VAN DER MAATEN 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. * */ /* This code was adopted with minor modifications from Steve Hanov's great tutorial at http://stevehanov.ca/blog/index.php?id=130 */ #include <stdlib.h> #include <algorithm> #include <vector> #include <stdio.h> #include <queue> #include <limits> #include <cmath> #ifndef VPTREE_H #define VPTREE_H class DataPoint { int _ind; public: double *_x; int _D; DataPoint() { _D = 1; _ind = -1; _x = NULL; } DataPoint(int D, int ind, double *x) { _D = D; _ind = ind; _x = (double *) malloc(_D * sizeof(double)); for (int d = 0; d < _D; d++) _x[d] = x[d]; } DataPoint(const DataPoint &other) { // this makes a deep copy -- should not free anything if (this != &other) { _D = other.dimensionality(); _ind = other.index(); _x = (double *) malloc(_D * sizeof(double)); for (int d = 0; d < _D; d++) _x[d] = other.x(d); } } ~DataPoint() { if (_x != NULL) free(_x); } DataPoint &operator=(const DataPoint &other) { // asignment should free old object if (this != &other) { if (_x != NULL) free(_x); _D = other.dimensionality(); _ind = other.index(); _x = (double *) malloc(_D * sizeof(double)); for (int d = 0; d < _D; d++) _x[d] = other.x(d); } return *this; } int index() const { return _ind; } int dimensionality() const { return _D; } double x(int d) const { return _x[d]; } }; double euclidean_distance(const DataPoint &t1, const DataPoint &t2) { double dd = .0; double *x1 = t1._x; double *x2 = t2._x; double diff; for (int d = 0; d < t1._D; d++) { diff = (x1[d] - x2[d]); dd += diff * diff; } return sqrt(dd); } template<typename T, double (*distance)(const T &, const T &)> class VpTree { public: // Default constructor VpTree() : _root(0) {} // Destructor ~VpTree() { delete _root; } // Function to create a new VpTree from data void create(const std::vector <T> &items) { delete _root; _items = items; _root = buildFromPoints(0, items.size()); } // Function that uses the tree to find the k nearest neighbors of target void search(const T &target, int k, std::vector <T> *results, std::vector<double> *distances) { // Use a priority queue to store intermediate results on std::priority_queue <HeapItem> heap; // Variable that tracks the distance to the farthest point in our results // Perform the search double _tau = DBL_MAX; search(_root, target, k, heap, _tau); // Gather final results results->clear(); distances->clear(); while (!heap.empty()) { results->push_back(_items[heap.top().index]); distances->push_back(heap.top().dist); heap.pop(); } // Results are in reverse order std::reverse(results->begin(), results->end()); std::reverse(distances->begin(), distances->end()); } private: std::vector <T> _items; // Single node of a VP tree (has a point and radius; left children are closer to point than the radius) struct Node { int index; // index of point in node double threshold; // radius(?) Node *left; // points closer by than threshold Node *right; // points farther away than threshold Node() : index(0), threshold(0.), left(0), right(0) {} ~Node() { // destructor delete left; delete right; } } *_root; // An item on the intermediate result queue struct HeapItem { HeapItem(int index, double dist) : index(index), dist(dist) {} int index; double dist; bool operator<(const HeapItem &o) const { return dist < o.dist; } }; // Distance comparator for use in std::nth_element struct DistanceComparator { const T &item; DistanceComparator(const T &item) : item(item) {} bool operator()(const T &a, const T &b) { return distance(item, a) < distance(item, b); } }; // Function that (recursively) fills the tree Node *buildFromPoints(int lower, int upper) { if (upper == lower) { // indicates that we're done here! return NULL; } // Lower index is center of current node Node *node = new Node(); node->index = lower; if (upper - lower > 1) { // if we did not arrive at leaf yet // Choose an arbitrary point and move it to the start int i = (int) ((double) rand() / RAND_MAX * (upper - lower - 1)) + lower; std::swap(_items[lower], _items[i]); // Partition around the median distance int median = (upper + lower) / 2; std::nth_element(_items.begin() + lower + 1, _items.begin() + median, _items.begin() + upper, DistanceComparator(_items[lower])); // Threshold of the new node will be the distance to the median node->threshold = distance(_items[lower], _items[median]); // Recursively build tree node->index = lower; node->left = buildFromPoints(lower + 1, median); node->right = buildFromPoints(median, upper); } // Return result return node; } // Helper function that searches the tree void search(Node *node, const T &target, int k, std::priority_queue <HeapItem> &heap, double &_tau) { if (node == NULL) return; // indicates that we're done here // Compute distance between target and current node double dist = distance(_items[node->index], target); // If current node within radius tau if (dist < _tau) { if (heap.size() == k) heap.pop(); // remove furthest node from result list (if we already have k results) heap.push(HeapItem(node->index, dist)); // add current node to result list if (heap.size() == k) _tau = heap.top().dist; // update value of tau (farthest point in result list) } // Return if we arrived at a leaf if (node->left == NULL && node->right == NULL) { return; } // If the target lies within the radius of ball if (dist < node->threshold) { if (dist - _tau <= node->threshold) { // if there can still be neighbors inside the ball, recursively search left child first search(node->left, target, k, heap, _tau); } if (dist + _tau >= node->threshold) { // if there can still be neighbors outside the ball, recursively search right child search(node->right, target, k, heap, _tau); } // If the target lies outsize the radius of the ball } else { if (dist + _tau >= node->threshold) { // if there can still be neighbors outside the ball, recursively search right child first search(node->right, target, k, heap, _tau); } if (dist - _tau <= node->threshold) { // if there can still be neighbors inside the ball, recursively search left child search(node->left, target, k, heap, _tau); } } } }; #endif
9,593
32.90106
132
h
FIt-SNE
FIt-SNE-master/src/progress_bar/ProgressBar.hpp
#ifndef PROGRESSBAR_PROGRESSBAR_HPP #define PROGRESSBAR_PROGRESSBAR_HPP #include <chrono> #include <iostream> class ProgressBar { private: unsigned int ticks = 0; const unsigned int total_ticks; const unsigned int bar_width; const char complete_char = '='; const char incomplete_char = ' '; const std::chrono::steady_clock::time_point start_time = std::chrono::steady_clock::now(); public: ProgressBar(unsigned int total, unsigned int width, char complete, char incomplete) : total_ticks {total}, bar_width {width}, complete_char {complete}, incomplete_char {incomplete} {} ProgressBar(unsigned int total, unsigned int width) : total_ticks {total}, bar_width {width} {} unsigned int operator++() { return ++ticks; } void display() const { float progress = (float) ticks / total_ticks; int pos = (int) (bar_width * progress); std::chrono::steady_clock::time_point now = std::chrono::steady_clock::now(); auto time_elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(now-start_time).count(); std::cout << "["; for (int i = 0; i < bar_width; ++i) { if (i < pos) std::cout << complete_char; else if (i == pos) std::cout << ">"; else std::cout << incomplete_char; } std::cout << "] " << int(progress * 100.0) << "% " << float(time_elapsed) / 1000.0 << "s\r"; std::cout.flush(); } void done() const { display(); std::cout << std::endl; } }; #endif //PROGRESSBAR_PROGRESSBAR_HPP
1,610
29.396226
109
hpp
FIt-SNE
FIt-SNE-master/src/winlibs/fftw3.h
/* * Copyright (c) 2003, 2007-14 Matteo Frigo * Copyright (c) 2003, 2007-14 Massachusetts Institute of Technology * * The following statement of license applies *only* to this header file, * and *not* to the other files distributed with FFTW or derived therefrom: * * 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 ``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 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. */ /***************************** NOTE TO USERS ********************************* * * THIS IS A HEADER FILE, NOT A MANUAL * * If you want to know how to use FFTW, please read the manual, * online at http://www.fftw.org/doc/ and also included with FFTW. * For a quick start, see the manual's tutorial section. * * (Reading header files to learn how to use a library is a habit * stemming from code lacking a proper manual. Arguably, it's a * *bad* habit in most cases, because header files can contain * interfaces that are not part of the public, stable API.) * ****************************************************************************/ #ifndef FFTW3_H #define FFTW3_H #include <stdio.h> #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* If <complex.h> is included, use the C99 complex type. Otherwise define a type bit-compatible with C99 complex */ #if !defined(FFTW_NO_Complex) && defined(_Complex_I) && defined(complex) && defined(I) # define FFTW_DEFINE_COMPLEX(R, C) typedef R _Complex C #else # define FFTW_DEFINE_COMPLEX(R, C) typedef R C[2] #endif #define FFTW_CONCAT(prefix, name) prefix ## name #define FFTW_MANGLE_DOUBLE(name) FFTW_CONCAT(fftw_, name) #define FFTW_MANGLE_FLOAT(name) FFTW_CONCAT(fftwf_, name) #define FFTW_MANGLE_LONG_DOUBLE(name) FFTW_CONCAT(fftwl_, name) #define FFTW_MANGLE_QUAD(name) FFTW_CONCAT(fftwq_, name) /* IMPORTANT: for Windows compilers, you should add a line */ #define FFTW_DLL /* here and in kernel/ifftw.h if you are compiling/using FFTW as a DLL, in order to do the proper importing/exporting, or alternatively compile with -DFFTW_DLL or the equivalent command-line flag. This is not necessary under MinGW/Cygwin, where libtool does the imports/exports automatically. */ #if defined(FFTW_DLL) && (defined(_WIN32) || defined(__WIN32__)) /* annoying Windows syntax for shared-library declarations */ # if defined(COMPILING_FFTW) /* defined in api.h when compiling FFTW */ # define FFTW_EXTERN extern __declspec(dllexport) # else /* user is calling FFTW; import symbol */ # define FFTW_EXTERN extern __declspec(dllimport) # endif #else # define FFTW_EXTERN extern #endif enum fftw_r2r_kind_do_not_use_me { FFTW_R2HC=0, FFTW_HC2R=1, FFTW_DHT=2, FFTW_REDFT00=3, FFTW_REDFT01=4, FFTW_REDFT10=5, FFTW_REDFT11=6, FFTW_RODFT00=7, FFTW_RODFT01=8, FFTW_RODFT10=9, FFTW_RODFT11=10 }; struct fftw_iodim_do_not_use_me { int n; /* dimension size */ int is; /* input stride */ int os; /* output stride */ }; #include <stddef.h> /* for ptrdiff_t */ struct fftw_iodim64_do_not_use_me { ptrdiff_t n; /* dimension size */ ptrdiff_t is; /* input stride */ ptrdiff_t os; /* output stride */ }; typedef void (*fftw_write_char_func_do_not_use_me)(char c, void *); typedef int (*fftw_read_char_func_do_not_use_me)(void *); /* huge second-order macro that defines prototypes for all API functions. We expand this macro for each supported precision X: name-mangling macro R: real data type C: complex data type */ #define FFTW_DEFINE_API(X, R, C) \ \ FFTW_DEFINE_COMPLEX(R, C); \ \ typedef struct X(plan_s) *X(plan); \ \ typedef struct fftw_iodim_do_not_use_me X(iodim); \ typedef struct fftw_iodim64_do_not_use_me X(iodim64); \ \ typedef enum fftw_r2r_kind_do_not_use_me X(r2r_kind); \ \ typedef fftw_write_char_func_do_not_use_me X(write_char_func); \ typedef fftw_read_char_func_do_not_use_me X(read_char_func); \ \ FFTW_EXTERN void X(execute)(const X(plan) p); \ \ FFTW_EXTERN X(plan) X(plan_dft)(int rank, const int *n, \ C *in, C *out, int sign, unsigned flags); \ \ FFTW_EXTERN X(plan) X(plan_dft_1d)(int n, C *in, C *out, int sign, \ unsigned flags); \ FFTW_EXTERN X(plan) X(plan_dft_2d)(int n0, int n1, \ C *in, C *out, int sign, unsigned flags); \ FFTW_EXTERN X(plan) X(plan_dft_3d)(int n0, int n1, int n2, \ C *in, C *out, int sign, unsigned flags); \ \ FFTW_EXTERN X(plan) X(plan_many_dft)(int rank, const int *n, \ int howmany, \ C *in, const int *inembed, \ int istride, int idist, \ C *out, const int *onembed, \ int ostride, int odist, \ int sign, unsigned flags); \ \ FFTW_EXTERN X(plan) X(plan_guru_dft)(int rank, const X(iodim) *dims, \ int howmany_rank, \ const X(iodim) *howmany_dims, \ C *in, C *out, \ int sign, unsigned flags); \ FFTW_EXTERN X(plan) X(plan_guru_split_dft)(int rank, const X(iodim) *dims, \ int howmany_rank, \ const X(iodim) *howmany_dims, \ R *ri, R *ii, R *ro, R *io, \ unsigned flags); \ \ FFTW_EXTERN X(plan) X(plan_guru64_dft)(int rank, \ const X(iodim64) *dims, \ int howmany_rank, \ const X(iodim64) *howmany_dims, \ C *in, C *out, \ int sign, unsigned flags); \ FFTW_EXTERN X(plan) X(plan_guru64_split_dft)(int rank, \ const X(iodim64) *dims, \ int howmany_rank, \ const X(iodim64) *howmany_dims, \ R *ri, R *ii, R *ro, R *io, \ unsigned flags); \ \ FFTW_EXTERN void X(execute_dft)(const X(plan) p, C *in, C *out); \ FFTW_EXTERN void X(execute_split_dft)(const X(plan) p, R *ri, R *ii, \ R *ro, R *io); \ \ FFTW_EXTERN X(plan) X(plan_many_dft_r2c)(int rank, const int *n, \ int howmany, \ R *in, const int *inembed, \ int istride, int idist, \ C *out, const int *onembed, \ int ostride, int odist, \ unsigned flags); \ \ FFTW_EXTERN X(plan) X(plan_dft_r2c)(int rank, const int *n, \ R *in, C *out, unsigned flags); \ \ FFTW_EXTERN X(plan) X(plan_dft_r2c_1d)(int n,R *in,C *out,unsigned flags); \ FFTW_EXTERN X(plan) X(plan_dft_r2c_2d)(int n0, int n1, \ R *in, C *out, unsigned flags); \ FFTW_EXTERN X(plan) X(plan_dft_r2c_3d)(int n0, int n1, \ int n2, \ R *in, C *out, unsigned flags); \ \ \ FFTW_EXTERN X(plan) X(plan_many_dft_c2r)(int rank, const int *n, \ int howmany, \ C *in, const int *inembed, \ int istride, int idist, \ R *out, const int *onembed, \ int ostride, int odist, \ unsigned flags); \ \ FFTW_EXTERN X(plan) X(plan_dft_c2r)(int rank, const int *n, \ C *in, R *out, unsigned flags); \ \ FFTW_EXTERN X(plan) X(plan_dft_c2r_1d)(int n,C *in,R *out,unsigned flags); \ FFTW_EXTERN X(plan) X(plan_dft_c2r_2d)(int n0, int n1, \ C *in, R *out, unsigned flags); \ FFTW_EXTERN X(plan) X(plan_dft_c2r_3d)(int n0, int n1, \ int n2, \ C *in, R *out, unsigned flags); \ \ FFTW_EXTERN X(plan) X(plan_guru_dft_r2c)(int rank, const X(iodim) *dims, \ int howmany_rank, \ const X(iodim) *howmany_dims, \ R *in, C *out, \ unsigned flags); \ FFTW_EXTERN X(plan) X(plan_guru_dft_c2r)(int rank, const X(iodim) *dims, \ int howmany_rank, \ const X(iodim) *howmany_dims, \ C *in, R *out, \ unsigned flags); \ \ FFTW_EXTERN X(plan) X(plan_guru_split_dft_r2c)( \ int rank, const X(iodim) *dims, \ int howmany_rank, \ const X(iodim) *howmany_dims, \ R *in, R *ro, R *io, \ unsigned flags); \ FFTW_EXTERN X(plan) X(plan_guru_split_dft_c2r)( \ int rank, const X(iodim) *dims, \ int howmany_rank, \ const X(iodim) *howmany_dims, \ R *ri, R *ii, R *out, \ unsigned flags); \ \ FFTW_EXTERN X(plan) X(plan_guru64_dft_r2c)(int rank, \ const X(iodim64) *dims, \ int howmany_rank, \ const X(iodim64) *howmany_dims, \ R *in, C *out, \ unsigned flags); \ FFTW_EXTERN X(plan) X(plan_guru64_dft_c2r)(int rank, \ const X(iodim64) *dims, \ int howmany_rank, \ const X(iodim64) *howmany_dims, \ C *in, R *out, \ unsigned flags); \ \ FFTW_EXTERN X(plan) X(plan_guru64_split_dft_r2c)( \ int rank, const X(iodim64) *dims, \ int howmany_rank, \ const X(iodim64) *howmany_dims, \ R *in, R *ro, R *io, \ unsigned flags); \ FFTW_EXTERN X(plan) X(plan_guru64_split_dft_c2r)( \ int rank, const X(iodim64) *dims, \ int howmany_rank, \ const X(iodim64) *howmany_dims, \ R *ri, R *ii, R *out, \ unsigned flags); \ \ FFTW_EXTERN void X(execute_dft_r2c)(const X(plan) p, R *in, C *out); \ FFTW_EXTERN void X(execute_dft_c2r)(const X(plan) p, C *in, R *out); \ \ FFTW_EXTERN void X(execute_split_dft_r2c)(const X(plan) p, \ R *in, R *ro, R *io); \ FFTW_EXTERN void X(execute_split_dft_c2r)(const X(plan) p, \ R *ri, R *ii, R *out); \ \ FFTW_EXTERN X(plan) X(plan_many_r2r)(int rank, const int *n, \ int howmany, \ R *in, const int *inembed, \ int istride, int idist, \ R *out, const int *onembed, \ int ostride, int odist, \ const X(r2r_kind) *kind, unsigned flags); \ \ FFTW_EXTERN X(plan) X(plan_r2r)(int rank, const int *n, R *in, R *out, \ const X(r2r_kind) *kind, unsigned flags); \ \ FFTW_EXTERN X(plan) X(plan_r2r_1d)(int n, R *in, R *out, \ X(r2r_kind) kind, unsigned flags); \ FFTW_EXTERN X(plan) X(plan_r2r_2d)(int n0, int n1, R *in, R *out, \ X(r2r_kind) kind0, X(r2r_kind) kind1, \ unsigned flags); \ FFTW_EXTERN X(plan) X(plan_r2r_3d)(int n0, int n1, int n2, \ R *in, R *out, X(r2r_kind) kind0, \ X(r2r_kind) kind1, X(r2r_kind) kind2, \ unsigned flags); \ \ FFTW_EXTERN X(plan) X(plan_guru_r2r)(int rank, const X(iodim) *dims, \ int howmany_rank, \ const X(iodim) *howmany_dims, \ R *in, R *out, \ const X(r2r_kind) *kind, unsigned flags); \ \ FFTW_EXTERN X(plan) X(plan_guru64_r2r)(int rank, const X(iodim64) *dims, \ int howmany_rank, \ const X(iodim64) *howmany_dims, \ R *in, R *out, \ const X(r2r_kind) *kind, unsigned flags); \ \ FFTW_EXTERN void X(execute_r2r)(const X(plan) p, R *in, R *out); \ \ FFTW_EXTERN void X(destroy_plan)(X(plan) p); \ FFTW_EXTERN void X(forget_wisdom)(void); \ FFTW_EXTERN void X(cleanup)(void); \ \ FFTW_EXTERN void X(set_timelimit)(double t); \ \ FFTW_EXTERN void X(plan_with_nthreads)(int nthreads); \ FFTW_EXTERN int X(init_threads)(void); \ FFTW_EXTERN void X(cleanup_threads)(void); \ FFTW_EXTERN void X(make_planner_thread_safe)(void); \ \ FFTW_EXTERN int X(export_wisdom_to_filename)(const char *filename); \ FFTW_EXTERN void X(export_wisdom_to_file)(FILE *output_file); \ FFTW_EXTERN char *X(export_wisdom_to_string)(void); \ FFTW_EXTERN void X(export_wisdom)(X(write_char_func) write_char, \ void *data); \ FFTW_EXTERN int X(import_system_wisdom)(void); \ FFTW_EXTERN int X(import_wisdom_from_filename)(const char *filename); \ FFTW_EXTERN int X(import_wisdom_from_file)(FILE *input_file); \ FFTW_EXTERN int X(import_wisdom_from_string)(const char *input_string); \ FFTW_EXTERN int X(import_wisdom)(X(read_char_func) read_char, void *data); \ \ FFTW_EXTERN void X(fprint_plan)(const X(plan) p, FILE *output_file); \ FFTW_EXTERN void X(print_plan)(const X(plan) p); \ FFTW_EXTERN char *X(sprint_plan)(const X(plan) p); \ \ FFTW_EXTERN void *X(malloc)(size_t n); \ FFTW_EXTERN R *X(alloc_real)(size_t n); \ FFTW_EXTERN C *X(alloc_complex)(size_t n); \ FFTW_EXTERN void X(free)(void *p); \ \ FFTW_EXTERN void X(flops)(const X(plan) p, \ double *add, double *mul, double *fmas); \ FFTW_EXTERN double X(estimate_cost)(const X(plan) p); \ FFTW_EXTERN double X(cost)(const X(plan) p); \ \ FFTW_EXTERN int X(alignment_of)(R *p); \ FFTW_EXTERN const char X(version)[]; \ FFTW_EXTERN const char X(cc)[]; \ FFTW_EXTERN const char X(codelet_optim)[]; /* end of FFTW_DEFINE_API macro */ FFTW_DEFINE_API(FFTW_MANGLE_DOUBLE, double, fftw_complex) FFTW_DEFINE_API(FFTW_MANGLE_FLOAT, float, fftwf_complex) FFTW_DEFINE_API(FFTW_MANGLE_LONG_DOUBLE, long double, fftwl_complex) /* __float128 (quad precision) is a gcc extension on i386, x86_64, and ia64 for gcc >= 4.6 (compiled in FFTW with --enable-quad-precision) */ #if (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)) \ && !(defined(__ICC) || defined(__INTEL_COMPILER) || defined(__CUDACC__) || defined(__PGI)) \ && (defined(__i386__) || defined(__x86_64__) || defined(__ia64__)) # if !defined(FFTW_NO_Complex) && defined(_Complex_I) && defined(complex) && defined(I) /* note: __float128 is a typedef, which is not supported with the _Complex keyword in gcc, so instead we use this ugly __attribute__ version. However, we can't simply pass the __attribute__ version to FFTW_DEFINE_API because the __attribute__ confuses gcc in pointer types. Hence redefining FFTW_DEFINE_COMPLEX. Ugh. */ # undef FFTW_DEFINE_COMPLEX # define FFTW_DEFINE_COMPLEX(R, C) typedef _Complex float __attribute__((mode(TC))) C # endif FFTW_DEFINE_API(FFTW_MANGLE_QUAD, __float128, fftwq_complex) #endif #define FFTW_FORWARD (-1) #define FFTW_BACKWARD (+1) #define FFTW_NO_TIMELIMIT (-1.0) /* documented flags */ #define FFTW_MEASURE (0U) #define FFTW_DESTROY_INPUT (1U << 0) #define FFTW_UNALIGNED (1U << 1) #define FFTW_CONSERVE_MEMORY (1U << 2) #define FFTW_EXHAUSTIVE (1U << 3) /* NO_EXHAUSTIVE is default */ #define FFTW_PRESERVE_INPUT (1U << 4) /* cancels FFTW_DESTROY_INPUT */ #define FFTW_PATIENT (1U << 5) /* IMPATIENT is default */ #define FFTW_ESTIMATE (1U << 6) #define FFTW_WISDOM_ONLY (1U << 21) /* undocumented beyond-guru flags */ #define FFTW_ESTIMATE_PATIENT (1U << 7) #define FFTW_BELIEVE_PCOST (1U << 8) #define FFTW_NO_DFT_R2HC (1U << 9) #define FFTW_NO_NONTHREADED (1U << 10) #define FFTW_NO_BUFFERING (1U << 11) #define FFTW_NO_INDIRECT_OP (1U << 12) #define FFTW_ALLOW_LARGE_GENERIC (1U << 13) /* NO_LARGE_GENERIC is default */ #define FFTW_NO_RANK_SPLITS (1U << 14) #define FFTW_NO_VRANK_SPLITS (1U << 15) #define FFTW_NO_VRECURSE (1U << 16) #define FFTW_NO_SIMD (1U << 17) #define FFTW_NO_SLOW (1U << 18) #define FFTW_NO_FIXED_RADIX_LARGE_N (1U << 19) #define FFTW_ALLOW_PRUNING (1U << 20) #ifdef __cplusplus } /* extern "C" */ #endif /* __cplusplus */ #endif /* FFTW3_H */
18,102
42.516827
93
h
FIt-SNE
FIt-SNE-master/src/winlibs/mman.h
/* * sys/mman.h * mman-win32 */ #ifndef _SYS_MMAN_H_ #define _SYS_MMAN_H_ #ifndef _WIN32_WINNT // Allow use of features specific to Windows XP or later. #define _WIN32_WINNT 0x0501 // Change this to the appropriate value to target other versions of Windows. #endif /* All the headers include this file. */ #ifndef _MSC_VER #include <_mingw.h> #endif #if defined(MMAN_LIBRARY_DLL) /* Windows shared libraries (DLL) must be declared export when building the lib and import when building the application which links against the library. */ #if defined(MMAN_LIBRARY) #define MMANSHARED_EXPORT __declspec(dllexport) #else #define MMANSHARED_EXPORT __declspec(dllimport) #endif /* MMAN_LIBRARY */ #else /* Static libraries do not require a __declspec attribute.*/ #define MMANSHARED_EXPORT #endif /* MMAN_LIBRARY_DLL */ /* Determine offset type */ #include <stdint.h> #if defined(_WIN64) typedef int64_t OffsetType; #else typedef uint32_t OffsetType; #endif #include <sys/types.h> #ifdef __cplusplus extern "C" { #endif #define PROT_NONE 0 #define PROT_READ 1 #define PROT_WRITE 2 #define PROT_EXEC 4 #define MAP_FILE 0 #define MAP_SHARED 1 #define MAP_PRIVATE 2 #define MAP_TYPE 0xf #define MAP_FIXED 0x10 #define MAP_ANONYMOUS 0x20 #define MAP_ANON MAP_ANONYMOUS #define MAP_FAILED ((void *)-1) /* Flags for msync. */ #define MS_ASYNC 1 #define MS_SYNC 2 #define MS_INVALIDATE 4 MMANSHARED_EXPORT void* mmap(void *addr, size_t len, int prot, int flags, int fildes, OffsetType off); MMANSHARED_EXPORT int munmap(void *addr, size_t len); MMANSHARED_EXPORT int _mprotect(void *addr, size_t len, int prot); MMANSHARED_EXPORT int msync(void *addr, size_t len, int flags); MMANSHARED_EXPORT int mlock(const void *addr, size_t len); MMANSHARED_EXPORT int munlock(const void *addr, size_t len); #if !defined(__MINGW32__) MMANSHARED_EXPORT int ftruncate(int fd, unsigned int size); #endif #ifdef __cplusplus } #endif #endif /* _SYS_MMAN_H_ */
2,083
24.108434
109
h
FIt-SNE
FIt-SNE-master/src/winlibs/stdafx.cpp
// stdafx.cpp : source file that includes just the standard includes // FItSNE.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h" // TODO: reference any additional headers you need in STDAFX.H // and not in this file
285
30.777778
68
cpp
FIt-SNE
FIt-SNE-master/src/winlibs/stdafx.h
// stdafx.h : include file for standard system include files, // or project specific include files that are used frequently, but // are changed infrequently // #pragma once #ifdef _WIN32 #define _CRT_SECURE_NO_WARNINGS #define _CRT_SECURE_NO_DEPRECATE #include "targetver.h" #include <stdio.h> #include <tchar.h> #endif
327
15.4
66
h
FIt-SNE
FIt-SNE-master/src/winlibs/targetver.h
#pragma once // Including SDKDDKVer.h defines the highest available Windows platform. // If you wish to build your application for a previous Windows platform, include WinSDKVer.h and // set the _WIN32_WINNT macro to the platform you wish to support before including SDKDDKVer.h. #include <SDKDDKVer.h>
306
33.111111
97
h
FIt-SNE
FIt-SNE-master/src/winlibs/unistd.h
#ifndef _UNISTD_H #define _UNISTD_H 1 /* This is intended as a drop-in replacement for unistd.h on Windows. * Please add functionality as neeeded. * https://stackoverflow.com/a/826027/1202830 */ #include <stdlib.h> #include <io.h> //#include <getopt.h> /* getopt at: https://gist.github.com/ashelly/7776712 */ #include <process.h> /* for getpid() and the exec..() family */ #include <direct.h> /* for _getcwd() and _chdir() */ #define srandom srand #define random rand /* Values for the second argument to access. These may be OR'd together. */ #define R_OK 4 /* Test for read permission. */ #define W_OK 2 /* Test for write permission. */ //#define X_OK 1 /* execute permission - unsupported in windows*/ #define F_OK 0 /* Test for existence. */ #define access _access #define dup2 _dup2 #define execve _execve #define ftruncate _chsize #define unlink _unlink #define fileno _fileno #define getcwd _getcwd #define chdir _chdir #define isatty _isatty #define lseek _lseek /* read, write, and close are NOT being #defined here, because while there are file handle specific versions for Windows, they probably don't work for sockets. You need to look at your app and consider whether to call e.g. closesocket(). */ #ifdef _WIN64 #define ssize_t __int64 #else #define ssize_t long #endif #define STDIN_FILENO 0 #define STDOUT_FILENO 1 #define STDERR_FILENO 2 /* should be in some equivalent to <sys/types.h> */ //typedef __int8 int8_t; //typedef __int16 int16_t; //typedef __int32 int32_t; //typedef __int64 int64_t; //typedef unsigned __int8 uint8_t; //typedef unsigned __int16 uint16_t; //typedef unsigned __int32 uint32_t; //typedef unsigned __int64 uint64_t; #endif /* unistd.h */
1,788
30.946429
240
h
FIt-SNE
FIt-SNE-master/src/winlibs/fftw/fftw3.h
/* * Copyright (c) 2003, 2007-14 Matteo Frigo * Copyright (c) 2003, 2007-14 Massachusetts Institute of Technology * * The following statement of license applies *only* to this header file, * and *not* to the other files distributed with FFTW or derived therefrom: * * 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 ``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 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. */ /***************************** NOTE TO USERS ********************************* * * THIS IS A HEADER FILE, NOT A MANUAL * * If you want to know how to use FFTW, please read the manual, * online at http://www.fftw.org/doc/ and also included with FFTW. * For a quick start, see the manual's tutorial section. * * (Reading header files to learn how to use a library is a habit * stemming from code lacking a proper manual. Arguably, it's a * *bad* habit in most cases, because header files can contain * interfaces that are not part of the public, stable API.) * ****************************************************************************/ #ifndef FFTW3_H #define FFTW3_H #include <stdio.h> #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* If <complex.h> is included, use the C99 complex type. Otherwise define a type bit-compatible with C99 complex */ #if !defined(FFTW_NO_Complex) && defined(_Complex_I) && defined(complex) && defined(I) # define FFTW_DEFINE_COMPLEX(R, C) typedef R _Complex C #else # define FFTW_DEFINE_COMPLEX(R, C) typedef R C[2] #endif #define FFTW_CONCAT(prefix, name) prefix ## name #define FFTW_MANGLE_DOUBLE(name) FFTW_CONCAT(fftw_, name) #define FFTW_MANGLE_FLOAT(name) FFTW_CONCAT(fftwf_, name) #define FFTW_MANGLE_LONG_DOUBLE(name) FFTW_CONCAT(fftwl_, name) #define FFTW_MANGLE_QUAD(name) FFTW_CONCAT(fftwq_, name) /* IMPORTANT: for Windows compilers, you should add a line */ #define FFTW_DLL /* here and in kernel/ifftw.h if you are compiling/using FFTW as a DLL, in order to do the proper importing/exporting, or alternatively compile with -DFFTW_DLL or the equivalent command-line flag. This is not necessary under MinGW/Cygwin, where libtool does the imports/exports automatically. */ #if defined(FFTW_DLL) && (defined(_WIN32) || defined(__WIN32__)) /* annoying Windows syntax for shared-library declarations */ # if defined(COMPILING_FFTW) /* defined in api.h when compiling FFTW */ # define FFTW_EXTERN extern __declspec(dllexport) # else /* user is calling FFTW; import symbol */ # define FFTW_EXTERN extern __declspec(dllimport) # endif #else # define FFTW_EXTERN extern #endif enum fftw_r2r_kind_do_not_use_me { FFTW_R2HC=0, FFTW_HC2R=1, FFTW_DHT=2, FFTW_REDFT00=3, FFTW_REDFT01=4, FFTW_REDFT10=5, FFTW_REDFT11=6, FFTW_RODFT00=7, FFTW_RODFT01=8, FFTW_RODFT10=9, FFTW_RODFT11=10 }; struct fftw_iodim_do_not_use_me { int n; /* dimension size */ int is; /* input stride */ int os; /* output stride */ }; #include <stddef.h> /* for ptrdiff_t */ struct fftw_iodim64_do_not_use_me { ptrdiff_t n; /* dimension size */ ptrdiff_t is; /* input stride */ ptrdiff_t os; /* output stride */ }; typedef void (*fftw_write_char_func_do_not_use_me)(char c, void *); typedef int (*fftw_read_char_func_do_not_use_me)(void *); /* huge second-order macro that defines prototypes for all API functions. We expand this macro for each supported precision X: name-mangling macro R: real data type C: complex data type */ #define FFTW_DEFINE_API(X, R, C) \ \ FFTW_DEFINE_COMPLEX(R, C); \ \ typedef struct X(plan_s) *X(plan); \ \ typedef struct fftw_iodim_do_not_use_me X(iodim); \ typedef struct fftw_iodim64_do_not_use_me X(iodim64); \ \ typedef enum fftw_r2r_kind_do_not_use_me X(r2r_kind); \ \ typedef fftw_write_char_func_do_not_use_me X(write_char_func); \ typedef fftw_read_char_func_do_not_use_me X(read_char_func); \ \ FFTW_EXTERN void X(execute)(const X(plan) p); \ \ FFTW_EXTERN X(plan) X(plan_dft)(int rank, const int *n, \ C *in, C *out, int sign, unsigned flags); \ \ FFTW_EXTERN X(plan) X(plan_dft_1d)(int n, C *in, C *out, int sign, \ unsigned flags); \ FFTW_EXTERN X(plan) X(plan_dft_2d)(int n0, int n1, \ C *in, C *out, int sign, unsigned flags); \ FFTW_EXTERN X(plan) X(plan_dft_3d)(int n0, int n1, int n2, \ C *in, C *out, int sign, unsigned flags); \ \ FFTW_EXTERN X(plan) X(plan_many_dft)(int rank, const int *n, \ int howmany, \ C *in, const int *inembed, \ int istride, int idist, \ C *out, const int *onembed, \ int ostride, int odist, \ int sign, unsigned flags); \ \ FFTW_EXTERN X(plan) X(plan_guru_dft)(int rank, const X(iodim) *dims, \ int howmany_rank, \ const X(iodim) *howmany_dims, \ C *in, C *out, \ int sign, unsigned flags); \ FFTW_EXTERN X(plan) X(plan_guru_split_dft)(int rank, const X(iodim) *dims, \ int howmany_rank, \ const X(iodim) *howmany_dims, \ R *ri, R *ii, R *ro, R *io, \ unsigned flags); \ \ FFTW_EXTERN X(plan) X(plan_guru64_dft)(int rank, \ const X(iodim64) *dims, \ int howmany_rank, \ const X(iodim64) *howmany_dims, \ C *in, C *out, \ int sign, unsigned flags); \ FFTW_EXTERN X(plan) X(plan_guru64_split_dft)(int rank, \ const X(iodim64) *dims, \ int howmany_rank, \ const X(iodim64) *howmany_dims, \ R *ri, R *ii, R *ro, R *io, \ unsigned flags); \ \ FFTW_EXTERN void X(execute_dft)(const X(plan) p, C *in, C *out); \ FFTW_EXTERN void X(execute_split_dft)(const X(plan) p, R *ri, R *ii, \ R *ro, R *io); \ \ FFTW_EXTERN X(plan) X(plan_many_dft_r2c)(int rank, const int *n, \ int howmany, \ R *in, const int *inembed, \ int istride, int idist, \ C *out, const int *onembed, \ int ostride, int odist, \ unsigned flags); \ \ FFTW_EXTERN X(plan) X(plan_dft_r2c)(int rank, const int *n, \ R *in, C *out, unsigned flags); \ \ FFTW_EXTERN X(plan) X(plan_dft_r2c_1d)(int n,R *in,C *out,unsigned flags); \ FFTW_EXTERN X(plan) X(plan_dft_r2c_2d)(int n0, int n1, \ R *in, C *out, unsigned flags); \ FFTW_EXTERN X(plan) X(plan_dft_r2c_3d)(int n0, int n1, \ int n2, \ R *in, C *out, unsigned flags); \ \ \ FFTW_EXTERN X(plan) X(plan_many_dft_c2r)(int rank, const int *n, \ int howmany, \ C *in, const int *inembed, \ int istride, int idist, \ R *out, const int *onembed, \ int ostride, int odist, \ unsigned flags); \ \ FFTW_EXTERN X(plan) X(plan_dft_c2r)(int rank, const int *n, \ C *in, R *out, unsigned flags); \ \ FFTW_EXTERN X(plan) X(plan_dft_c2r_1d)(int n,C *in,R *out,unsigned flags); \ FFTW_EXTERN X(plan) X(plan_dft_c2r_2d)(int n0, int n1, \ C *in, R *out, unsigned flags); \ FFTW_EXTERN X(plan) X(plan_dft_c2r_3d)(int n0, int n1, \ int n2, \ C *in, R *out, unsigned flags); \ \ FFTW_EXTERN X(plan) X(plan_guru_dft_r2c)(int rank, const X(iodim) *dims, \ int howmany_rank, \ const X(iodim) *howmany_dims, \ R *in, C *out, \ unsigned flags); \ FFTW_EXTERN X(plan) X(plan_guru_dft_c2r)(int rank, const X(iodim) *dims, \ int howmany_rank, \ const X(iodim) *howmany_dims, \ C *in, R *out, \ unsigned flags); \ \ FFTW_EXTERN X(plan) X(plan_guru_split_dft_r2c)( \ int rank, const X(iodim) *dims, \ int howmany_rank, \ const X(iodim) *howmany_dims, \ R *in, R *ro, R *io, \ unsigned flags); \ FFTW_EXTERN X(plan) X(plan_guru_split_dft_c2r)( \ int rank, const X(iodim) *dims, \ int howmany_rank, \ const X(iodim) *howmany_dims, \ R *ri, R *ii, R *out, \ unsigned flags); \ \ FFTW_EXTERN X(plan) X(plan_guru64_dft_r2c)(int rank, \ const X(iodim64) *dims, \ int howmany_rank, \ const X(iodim64) *howmany_dims, \ R *in, C *out, \ unsigned flags); \ FFTW_EXTERN X(plan) X(plan_guru64_dft_c2r)(int rank, \ const X(iodim64) *dims, \ int howmany_rank, \ const X(iodim64) *howmany_dims, \ C *in, R *out, \ unsigned flags); \ \ FFTW_EXTERN X(plan) X(plan_guru64_split_dft_r2c)( \ int rank, const X(iodim64) *dims, \ int howmany_rank, \ const X(iodim64) *howmany_dims, \ R *in, R *ro, R *io, \ unsigned flags); \ FFTW_EXTERN X(plan) X(plan_guru64_split_dft_c2r)( \ int rank, const X(iodim64) *dims, \ int howmany_rank, \ const X(iodim64) *howmany_dims, \ R *ri, R *ii, R *out, \ unsigned flags); \ \ FFTW_EXTERN void X(execute_dft_r2c)(const X(plan) p, R *in, C *out); \ FFTW_EXTERN void X(execute_dft_c2r)(const X(plan) p, C *in, R *out); \ \ FFTW_EXTERN void X(execute_split_dft_r2c)(const X(plan) p, \ R *in, R *ro, R *io); \ FFTW_EXTERN void X(execute_split_dft_c2r)(const X(plan) p, \ R *ri, R *ii, R *out); \ \ FFTW_EXTERN X(plan) X(plan_many_r2r)(int rank, const int *n, \ int howmany, \ R *in, const int *inembed, \ int istride, int idist, \ R *out, const int *onembed, \ int ostride, int odist, \ const X(r2r_kind) *kind, unsigned flags); \ \ FFTW_EXTERN X(plan) X(plan_r2r)(int rank, const int *n, R *in, R *out, \ const X(r2r_kind) *kind, unsigned flags); \ \ FFTW_EXTERN X(plan) X(plan_r2r_1d)(int n, R *in, R *out, \ X(r2r_kind) kind, unsigned flags); \ FFTW_EXTERN X(plan) X(plan_r2r_2d)(int n0, int n1, R *in, R *out, \ X(r2r_kind) kind0, X(r2r_kind) kind1, \ unsigned flags); \ FFTW_EXTERN X(plan) X(plan_r2r_3d)(int n0, int n1, int n2, \ R *in, R *out, X(r2r_kind) kind0, \ X(r2r_kind) kind1, X(r2r_kind) kind2, \ unsigned flags); \ \ FFTW_EXTERN X(plan) X(plan_guru_r2r)(int rank, const X(iodim) *dims, \ int howmany_rank, \ const X(iodim) *howmany_dims, \ R *in, R *out, \ const X(r2r_kind) *kind, unsigned flags); \ \ FFTW_EXTERN X(plan) X(plan_guru64_r2r)(int rank, const X(iodim64) *dims, \ int howmany_rank, \ const X(iodim64) *howmany_dims, \ R *in, R *out, \ const X(r2r_kind) *kind, unsigned flags); \ \ FFTW_EXTERN void X(execute_r2r)(const X(plan) p, R *in, R *out); \ \ FFTW_EXTERN void X(destroy_plan)(X(plan) p); \ FFTW_EXTERN void X(forget_wisdom)(void); \ FFTW_EXTERN void X(cleanup)(void); \ \ FFTW_EXTERN void X(set_timelimit)(double t); \ \ FFTW_EXTERN void X(plan_with_nthreads)(int nthreads); \ FFTW_EXTERN int X(init_threads)(void); \ FFTW_EXTERN void X(cleanup_threads)(void); \ FFTW_EXTERN void X(make_planner_thread_safe)(void); \ \ FFTW_EXTERN int X(export_wisdom_to_filename)(const char *filename); \ FFTW_EXTERN void X(export_wisdom_to_file)(FILE *output_file); \ FFTW_EXTERN char *X(export_wisdom_to_string)(void); \ FFTW_EXTERN void X(export_wisdom)(X(write_char_func) write_char, \ void *data); \ FFTW_EXTERN int X(import_system_wisdom)(void); \ FFTW_EXTERN int X(import_wisdom_from_filename)(const char *filename); \ FFTW_EXTERN int X(import_wisdom_from_file)(FILE *input_file); \ FFTW_EXTERN int X(import_wisdom_from_string)(const char *input_string); \ FFTW_EXTERN int X(import_wisdom)(X(read_char_func) read_char, void *data); \ \ FFTW_EXTERN void X(fprint_plan)(const X(plan) p, FILE *output_file); \ FFTW_EXTERN void X(print_plan)(const X(plan) p); \ FFTW_EXTERN char *X(sprint_plan)(const X(plan) p); \ \ FFTW_EXTERN void *X(malloc)(size_t n); \ FFTW_EXTERN R *X(alloc_real)(size_t n); \ FFTW_EXTERN C *X(alloc_complex)(size_t n); \ FFTW_EXTERN void X(free)(void *p); \ \ FFTW_EXTERN void X(flops)(const X(plan) p, \ double *add, double *mul, double *fmas); \ FFTW_EXTERN double X(estimate_cost)(const X(plan) p); \ FFTW_EXTERN double X(cost)(const X(plan) p); \ \ FFTW_EXTERN int X(alignment_of)(R *p); \ FFTW_EXTERN const char X(version)[]; \ FFTW_EXTERN const char X(cc)[]; \ FFTW_EXTERN const char X(codelet_optim)[]; /* end of FFTW_DEFINE_API macro */ FFTW_DEFINE_API(FFTW_MANGLE_DOUBLE, double, fftw_complex) FFTW_DEFINE_API(FFTW_MANGLE_FLOAT, float, fftwf_complex) FFTW_DEFINE_API(FFTW_MANGLE_LONG_DOUBLE, long double, fftwl_complex) /* __float128 (quad precision) is a gcc extension on i386, x86_64, and ia64 for gcc >= 4.6 (compiled in FFTW with --enable-quad-precision) */ #if (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)) \ && !(defined(__ICC) || defined(__INTEL_COMPILER) || defined(__CUDACC__) || defined(__PGI)) \ && (defined(__i386__) || defined(__x86_64__) || defined(__ia64__)) # if !defined(FFTW_NO_Complex) && defined(_Complex_I) && defined(complex) && defined(I) /* note: __float128 is a typedef, which is not supported with the _Complex keyword in gcc, so instead we use this ugly __attribute__ version. However, we can't simply pass the __attribute__ version to FFTW_DEFINE_API because the __attribute__ confuses gcc in pointer types. Hence redefining FFTW_DEFINE_COMPLEX. Ugh. */ # undef FFTW_DEFINE_COMPLEX # define FFTW_DEFINE_COMPLEX(R, C) typedef _Complex float __attribute__((mode(TC))) C # endif FFTW_DEFINE_API(FFTW_MANGLE_QUAD, __float128, fftwq_complex) #endif #define FFTW_FORWARD (-1) #define FFTW_BACKWARD (+1) #define FFTW_NO_TIMELIMIT (-1.0) /* documented flags */ #define FFTW_MEASURE (0U) #define FFTW_DESTROY_INPUT (1U << 0) #define FFTW_UNALIGNED (1U << 1) #define FFTW_CONSERVE_MEMORY (1U << 2) #define FFTW_EXHAUSTIVE (1U << 3) /* NO_EXHAUSTIVE is default */ #define FFTW_PRESERVE_INPUT (1U << 4) /* cancels FFTW_DESTROY_INPUT */ #define FFTW_PATIENT (1U << 5) /* IMPATIENT is default */ #define FFTW_ESTIMATE (1U << 6) #define FFTW_WISDOM_ONLY (1U << 21) /* undocumented beyond-guru flags */ #define FFTW_ESTIMATE_PATIENT (1U << 7) #define FFTW_BELIEVE_PCOST (1U << 8) #define FFTW_NO_DFT_R2HC (1U << 9) #define FFTW_NO_NONTHREADED (1U << 10) #define FFTW_NO_BUFFERING (1U << 11) #define FFTW_NO_INDIRECT_OP (1U << 12) #define FFTW_ALLOW_LARGE_GENERIC (1U << 13) /* NO_LARGE_GENERIC is default */ #define FFTW_NO_RANK_SPLITS (1U << 14) #define FFTW_NO_VRANK_SPLITS (1U << 15) #define FFTW_NO_VRECURSE (1U << 16) #define FFTW_NO_SIMD (1U << 17) #define FFTW_NO_SLOW (1U << 18) #define FFTW_NO_FIXED_RADIX_LARGE_N (1U << 19) #define FFTW_ALLOW_PRUNING (1U << 20) #ifdef __cplusplus } /* extern "C" */ #endif /* __cplusplus */ #endif /* FFTW3_H */
18,102
42.516827
93
h
FIt-SNE
FIt-SNE-master/src/winlibs/fftw/ffwt_license-and-copyright.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <!-- This manual is for FFTW (version 3.3.8, 24 May 2018). Copyright (C) 2003 Matteo Frigo. Copyright (C) 2003 Massachusetts Institute of Technology. Permission is granted to make and distribute verbatim copies of this manual provided the copyright notice and this permission notice are preserved on all copies. Permission is granted to copy and distribute modified versions of this manual under the conditions for verbatim copying, provided that the entire resulting derived work is distributed under the terms of a permission notice identical to this one. Permission is granted to copy and distribute translations of this manual into another language, under the above conditions for modified versions, except that this permission notice may be stated in a translation approved by the Free Software Foundation. --> <!-- Created by GNU Texinfo 6.3, http://www.gnu.org/software/texinfo/ --> <head> <title>FFTW 3.3.8: License and Copyright</title> <meta name="description" content="FFTW 3.3.8: License and Copyright"> <meta name="keywords" content="FFTW 3.3.8: License and Copyright"> <meta name="resource-type" content="document"> <meta name="distribution" content="global"> <meta name="Generator" content="makeinfo"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <link href="index.html#Top" rel="start" title="Top"> <link href="Concept-Index.html#Concept-Index" rel="index" title="Concept Index"> <link href="index.html#SEC_Contents" rel="contents" title="Table of Contents"> <link href="index.html#Top" rel="up" title="Top"> <link href="Concept-Index.html#Concept-Index" rel="next" title="Concept Index"> <link href="Acknowledgments.html#Acknowledgments" rel="prev" title="Acknowledgments"> <style type="text/css"> <!-- a.summary-letter {text-decoration: none} blockquote.indentedblock {margin-right: 0em} blockquote.smallindentedblock {margin-right: 0em; font-size: smaller} blockquote.smallquotation {font-size: smaller} div.display {margin-left: 3.2em} div.example {margin-left: 3.2em} div.lisp {margin-left: 3.2em} div.smalldisplay {margin-left: 3.2em} div.smallexample {margin-left: 3.2em} div.smalllisp {margin-left: 3.2em} kbd {font-style: oblique} pre.display {font-family: inherit} pre.format {font-family: inherit} pre.menu-comment {font-family: serif} pre.menu-preformatted {font-family: serif} pre.smalldisplay {font-family: inherit; font-size: smaller} pre.smallexample {font-size: smaller} pre.smallformat {font-family: inherit; font-size: smaller} pre.smalllisp {font-size: smaller} span.nolinebreak {white-space: nowrap} span.roman {font-family: initial; font-weight: normal} span.sansserif {font-family: sans-serif; font-weight: normal} ul.no-bullet {list-style: none} --> </style> </head> <body lang="en"> <a name="License-and-Copyright"></a> <div class="header"> <p> Next: <a href="Concept-Index.html#Concept-Index" accesskey="n" rel="next">Concept Index</a>, Previous: <a href="Acknowledgments.html#Acknowledgments" accesskey="p" rel="prev">Acknowledgments</a>, Up: <a href="index.html#Top" accesskey="u" rel="up">Top</a> &nbsp; [<a href="index.html#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="Concept-Index.html#Concept-Index" title="Index" rel="index">Index</a>]</p> </div> <hr> <a name="License-and-Copyright-1"></a> <h2 class="chapter">12 License and Copyright</h2> <p>FFTW is Copyright &copy; 2003, 2007-11 Matteo Frigo, Copyright &copy; 2003, 2007-11 Massachusetts Institute of Technology. </p> <p>FFTW 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 2 of the License, or (at your option) any later version. </p> <p>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. </p> <p>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 You can also find the <a href="http://www.gnu.org/licenses/gpl-2.0.html">GPL on the GNU web site</a>. </p> <p>In addition, we kindly ask you to acknowledge FFTW and its authors in any program or publication in which you use FFTW. (You are not <em>required</em> to do so; it is up to your common sense to decide whether you want to comply with this request or not.) For general publications, we suggest referencing: Matteo Frigo and Steven G. Johnson, &ldquo;The design and implementation of FFTW3,&rdquo; <i>Proc. IEEE</i> <b>93</b> (2), 216&ndash;231 (2005). </p> <p>Non-free versions of FFTW are available under terms different from those of the General Public License. (e.g. they do not require you to accompany any object code using FFTW with the corresponding source code.) For these alternative terms you must purchase a license from MIT&rsquo;s Technology Licensing Office. Users interested in such a license should contact us (<a href="mailto:[email protected]">[email protected]</a>) for more information. </p> <hr> <div class="header"> <p> Next: <a href="Concept-Index.html#Concept-Index" accesskey="n" rel="next">Concept Index</a>, Previous: <a href="Acknowledgments.html#Acknowledgments" accesskey="p" rel="prev">Acknowledgments</a>, Up: <a href="index.html#Top" accesskey="u" rel="up">Top</a> &nbsp; [<a href="index.html#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="Concept-Index.html#Concept-Index" title="Index" rel="index">Index</a>]</p> </div> </body> </html>
5,796
45.376
436
html
octomap
octomap-master/dynamicEDT3D/doxygen.h
/** * \namespace dynamicEDT3D Namespace of the dynamicEDT3D library * */ /** \mainpage dynamicEDT3D \section intro_sec Introduction The <a href="http://octomap.sourceforge.net/">dynamicEDT3D library</a> implements an inrementally updatable Euclidean distance transform (EDT) in 3D. It comes with a wrapper to use the OctoMap 3D representation and hooks into the change detection of the OctoMap library to propagate changes to the EDT. \section install_sec Installation <p>See the file README.txt in the main folder. </p> \section gettingstarted_sec Getting Started <p>There are two example programs in the src/examples directory that show the basic functionality of the library.</p> \section changelog_sec Changelog <p>See the file CHANGELOG.txt in the main folder or the <a href="http://octomap.svn.sourceforge.net/viewvc/octomap/trunk/dynamicEDT3D/CHANGELOG.txt">latest version online</a> </p> \section using_sec Using dynamicEDT3D? <p> Please let us know if you are using dynamicEDT3D, as we are curious to find out how it enables other people's work or research. Additionally, please cite our paper if you use dynamicEDT3D in your research: </p> <p>B. Lau, C. Sprunk, and W. Burgard, <strong>"Efficient Grid-based Spatial Representations for Robot Navigation in Dynamic Environments"</strong> in <em>Robotics and Autonomous Systems</em>, 2012. Accepted for publication. Software available at <a href="http://octomap.sf.net/">http://octomap.sf.net/</a>. </p> <p>BibTeX:</p> <pre>@@article{lau12ras, author = {Boris Lau and Christoph Sprunk and Wolfram Burgard}, title = {Efficient Grid-based Spatial Representations for Robot Navigation in Dynamic Environments}, journal = {Robotics and Autonomous Systems (RAS)}, year = {2012}, url = {http://octomap.sf.net/}, note = {Accepted for publication. Software available at \url{http://octomap.sf.net/}} }</pre> **/
1,923
39.083333
304
h
octomap
octomap-master/dynamicEDT3D/include/dynamicEDT3D/bucketedqueue.h
/** * dynamicEDT3D: * A library for incrementally updatable Euclidean distance transforms in 3D. * @author C. Sprunk, B. Lau, W. Burgard, University of Freiburg, Copyright (C) 2011. * @see http://octomap.sourceforge.net/ * License: New BSD License */ /* * Copyright (c) 2011-2012, C. Sprunk, B. Lau, W. Burgard, University of Freiburg * 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 University of Freiburg 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. */ #ifndef _PRIORITYQUEUE2_H_ #define _PRIORITYQUEUE2_H_ #include <vector> #include <set> #include <queue> #include <assert.h> #include "point.h" #include <map> //! Priority queue for integer coordinates with squared distances as priority. /** A priority queue that uses buckets to group elements with the same priority. * The individual buckets are unsorted, which increases efficiency if these groups are large. * The elements are assumed to be integer coordinates, and the priorities are assumed * to be squared euclidean distances (integers). */ template <typename T> class BucketPrioQueue { public: //! Standard constructor /** Standard constructor. When called for the first time it creates a look up table * that maps square distanes to bucket numbers, which might take some time... */ BucketPrioQueue(); void clear() { buckets.clear(); } //! Checks whether the Queue is empty bool empty(); //! push an element void push(int prio, T t); //! return and pop the element with the lowest squared distance */ T pop(); int size() { return count; } int getNumBuckets() { return buckets.size(); } private: int count; typedef std::map< int, std::queue<T> > BucketType; BucketType buckets; typename BucketType::iterator nextPop; }; #include "bucketedqueue.hxx" #endif
3,237
34.582418
94
h
octomap
octomap-master/dynamicEDT3D/include/dynamicEDT3D/bucketedqueue.hxx
/** * dynamicEDT3D: * A library for incrementally updatable Euclidean distance transforms in 3D. * @author C. Sprunk, B. Lau, W. Burgard, University of Freiburg, Copyright (C) 2011. * @see http://octomap.sourceforge.net/ * License: New BSD License */ /* * Copyright (c) 2011-2012, C. Sprunk, B. Lau, W. Burgard, University of Freiburg * 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 University of Freiburg 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. */ #include "bucketedqueue.h" #include "limits.h" template <class T> BucketPrioQueue<T>::BucketPrioQueue() { nextPop = buckets.end(); count = 0; } template <class T> bool BucketPrioQueue<T>::empty() { return (count==0); } template <class T> void BucketPrioQueue<T>::push(int prio, T t) { buckets[prio].push(t); if (nextPop == buckets.end() || prio < nextPop->first) nextPop = buckets.find(prio); count++; } template <class T> T BucketPrioQueue<T>::pop() { while (nextPop!=buckets.end() && nextPop->second.empty()) ++nextPop; T p = nextPop->second.front(); nextPop->second.pop(); if (nextPop->second.empty()) { typename BucketType::iterator it = nextPop; nextPop++; buckets.erase(it); } count--; return p; }
2,656
33.960526
86
hxx
octomap
octomap-master/dynamicEDT3D/include/dynamicEDT3D/dynamicEDT3D.h
/** * dynamicEDT3D: * A library for incrementally updatable Euclidean distance transforms in 3D. * @author C. Sprunk, B. Lau, W. Burgard, University of Freiburg, Copyright (C) 2011. * @see http://octomap.sourceforge.net/ * License: New BSD License */ /* * Copyright (c) 2011-2012, C. Sprunk, B. Lau, W. Burgard, University of Freiburg * 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 University of Freiburg 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. */ #ifndef _DYNAMICEDT3D_H_ #define _DYNAMICEDT3D_H_ #include <limits.h> #include <queue> #include "bucketedqueue.h" //! A DynamicEDT3D object computes and updates a 3D distance map. class DynamicEDT3D { public: DynamicEDT3D(int _maxdist_squared); ~DynamicEDT3D(); //! Initialization with an empty map void initializeEmpty(int _sizeX, int _sizeY, int sizeZ, bool initGridMap=true); //! Initialization with a given binary map (false==free, true==occupied) void initializeMap(int _sizeX, int _sizeY, int sizeZ, bool*** _gridMap); //! add an obstacle at the specified cell coordinate void occupyCell(int x, int y, int z); //! remove an obstacle at the specified cell coordinate void clearCell(int x, int y, int z); //! remove old dynamic obstacles and add the new ones void exchangeObstacles(std::vector<INTPOINT3D> newObstacles); //! update distance map to reflect the changes virtual void update(bool updateRealDist=true); //! returns the obstacle distance at the specified location float getDistance( int x, int y, int z ) const; //! gets the closest occupied cell for that location INTPOINT3D getClosestObstacle( int x, int y, int z ) const; //! returns the squared obstacle distance in cell units at the specified location int getSQCellDistance( int x, int y, int z ) const; //! checks whether the specficied location is occupied bool isOccupied(int x, int y, int z) const; //! returns the x size of the workspace/map unsigned int getSizeX() const {return sizeX;} //! returns the y size of the workspace/map unsigned int getSizeY() const {return sizeY;} //! returns the z size of the workspace/map unsigned int getSizeZ() const {return sizeZ;} typedef enum {invalidObstData = INT_MAX} ObstDataState; ///distance value returned when requesting distance for a cell outside the map static float distanceValue_Error; ///distance value returned when requesting distance in cell units for a cell outside the map static int distanceInCellsValue_Error; protected: struct dataCell { float dist; int obstX; int obstY; int obstZ; int sqdist; char queueing; bool needsRaise; }; typedef enum {free=0, occupied=1} State; typedef enum {fwNotQueued=1, fwQueued=2, fwProcessed=3, bwQueued=4, bwProcessed=1} QueueingState; // methods inline void raiseCell(INTPOINT3D &p, dataCell &c, bool updateRealDist); inline void propagateCell(INTPOINT3D &p, dataCell &c, bool updateRealDist); inline void inspectCellRaise(int &nx, int &ny, int &nz, bool updateRealDist); inline void inspectCellPropagate(int &nx, int &ny, int &nz, dataCell &c, bool updateRealDist); void setObstacle(int x, int y, int z); void removeObstacle(int x, int y, int z); private: void commitAndColorize(bool updateRealDist=true); inline bool isOccupied(int &x, int &y, int &z, dataCell &c); // queues BucketPrioQueue<INTPOINT3D> open; std::vector<INTPOINT3D> removeList; std::vector<INTPOINT3D> addList; std::vector<INTPOINT3D> lastObstacles; // maps protected: int sizeX; int sizeY; int sizeZ; int sizeXm1; int sizeYm1; int sizeZm1; dataCell*** data; bool*** gridMap; // parameters int padding; double doubleThreshold; double sqrt2; double maxDist; int maxDist_squared; }; #endif
5,228
33.401316
99
h
octomap
octomap-master/dynamicEDT3D/include/dynamicEDT3D/dynamicEDTOctomap.h
/** * dynamicEDT3D: * A library for incrementally updatable Euclidean distance transforms in 3D. * @author C. Sprunk, B. Lau, W. Burgard, University of Freiburg, Copyright (C) 2011. * @see http://octomap.sourceforge.net/ * License: New BSD License */ /* * Copyright (c) 2011-2012, C. Sprunk, B. Lau, W. Burgard, University of Freiburg * 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 University of Freiburg 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. */ #ifndef DYNAMICEDTOCTOMAP_H_ #define DYNAMICEDTOCTOMAP_H_ #include "dynamicEDT3D.h" #include <octomap/OcTree.h> #include <octomap/OcTreeStamped.h> /// A DynamicEDTOctomapBase object connects a DynamicEDT3D object to an octomap. template <class TREE> class DynamicEDTOctomapBase: private DynamicEDT3D { public: /** Create a DynamicEDTOctomapBase object that maintains a distance transform in the bounding box given by bbxMin, bbxMax and clamps distances at maxdist. * treatUnknownAsOccupied configures the treatment of unknown cells in the distance computation. * * The constructor copies occupancy data but does not yet compute the distance map. You need to call udpate to do this. * * The distance map is maintained in a full three-dimensional array, i.e., there exists a float field in memory for every voxel inside the bounding box given by bbxMin and bbxMax. Consider this when computing distance maps for large octomaps, they will use much more memory than the octomap itself! */ DynamicEDTOctomapBase(float maxdist, TREE* _octree, octomap::point3d bbxMin, octomap::point3d bbxMax, bool treatUnknownAsOccupied); virtual ~DynamicEDTOctomapBase(); ///trigger updating of the distance map. This will query the octomap for the set of changes since the last update. ///If you set updateRealDist to false, computations will be faster (square root will be omitted), but you can only retrieve squared distances virtual void update(bool updateRealDist=true); ///retrieves distance and closestObstacle (closestObstacle is to be discarded if distance is maximum distance, the method does not write closestObstacle in this case). ///Returns DynamicEDTOctomapBase::distanceValue_Error if point is outside the map. void getDistanceAndClosestObstacle(const octomap::point3d& p, float &distance, octomap::point3d& closestObstacle) const; ///retrieves distance at point. Returns DynamicEDTOctomapBase::distanceValue_Error if point is outside the map. float getDistance(const octomap::point3d& p) const; ///retrieves distance at key. Returns DynamicEDTOctomapBase::distanceValue_Error if key is outside the map. float getDistance(const octomap::OcTreeKey& k) const; ///retrieves squared distance in cells at point. Returns DynamicEDTOctomapBase::distanceInCellsValue_Error if point is outside the map. int getSquaredDistanceInCells(const octomap::point3d& p) const; //variant of getDistanceAndClosestObstacle that ommits the check whether p is inside the area of the distance map. Use only if you are certain that p is covered by the distance map and if you need to save the time of the check. void getDistanceAndClosestObstacle_unsafe(const octomap::point3d& p, float &distance, octomap::point3d& closestObstacle) const; //variant of getDistance that ommits the check whether p is inside the area of the distance map. Use only if you are certain that p is covered by the distance map and if you need to save the time of the check. float getDistance_unsafe(const octomap::point3d& p) const; //variant of getDistance that ommits the check whether p is inside the area of the distance map. Use only if you are certain that p is covered by the distance map and if you need to save the time of the check. float getDistance_unsafe(const octomap::OcTreeKey& k) const; //variant of getSquaredDistanceInCells that ommits the check whether p is inside the area of the distance map. Use only if you are certain that p is covered by the distance map and if you need to save the time of the check. int getSquaredDistanceInCells_unsafe(const octomap::point3d& p) const; ///retrieve maximum distance value float getMaxDist() const { return maxDist*octree->getResolution(); } ///retrieve squared maximum distance value in grid cells int getSquaredMaxDistCells() const { return maxDist_squared; } ///Brute force method used for debug purposes. Checks occupancy state consistency between octomap and internal representation. bool checkConsistency() const; ///distance value returned when requesting distance for a cell outside the map static float distanceValue_Error; ///distance value returned when requesting distance in cell units for a cell outside the map static int distanceInCellsValue_Error; private: void initializeOcTree(octomap::point3d bbxMin, octomap::point3d bbxMax); void insertMaxDepthLeafAtInitialize(octomap::OcTreeKey key); void updateMaxDepthLeaf(octomap::OcTreeKey& key, bool occupied); void worldToMap(const octomap::point3d &p, int &x, int &y, int &z) const; void mapToWorld(int x, int y, int z, octomap::point3d &p) const; void mapToWorld(int x, int y, int z, octomap::OcTreeKey &key) const; TREE* octree; bool unknownOccupied; int treeDepth; double treeResolution; octomap::OcTreeKey boundingBoxMinKey; octomap::OcTreeKey boundingBoxMaxKey; int offsetX, offsetY, offsetZ; }; typedef DynamicEDTOctomapBase<octomap::OcTree> DynamicEDTOctomap; typedef DynamicEDTOctomapBase<octomap::OcTreeStamped> DynamicEDTOctomapStamped; #include "dynamicEDTOctomap.hxx" #endif /* DYNAMICEDTOCTOMAP_H_ */
7,002
52.458015
303
h
octomap
octomap-master/dynamicEDT3D/include/dynamicEDT3D/dynamicEDTOctomap.hxx
/** * dynamicEDT3D: * A library for incrementally updatable Euclidean distance transforms in 3D. * @author C. Sprunk, B. Lau, W. Burgard, University of Freiburg, Copyright (C) 2011. * @see http://octomap.sourceforge.net/ * License: New BSD License */ /* * Copyright (c) 2011-2012, C. Sprunk, B. Lau, W. Burgard, University of Freiburg * 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 University of Freiburg 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. */ template <class TREE> float DynamicEDTOctomapBase<TREE>::distanceValue_Error = -1.0; template <class TREE> int DynamicEDTOctomapBase<TREE>::distanceInCellsValue_Error = -1; template <class TREE> DynamicEDTOctomapBase<TREE>::DynamicEDTOctomapBase(float maxdist, TREE* _octree, octomap::point3d bbxMin, octomap::point3d bbxMax, bool treatUnknownAsOccupied) : DynamicEDT3D(((int) (maxdist/_octree->getResolution()+1)*((int) (maxdist/_octree->getResolution()+1)))), octree(_octree), unknownOccupied(treatUnknownAsOccupied) { treeDepth = octree->getTreeDepth(); treeResolution = octree->getResolution(); initializeOcTree(bbxMin, bbxMax); octree->enableChangeDetection(true); } template <class TREE> DynamicEDTOctomapBase<TREE>::~DynamicEDTOctomapBase() { } template <class TREE> void DynamicEDTOctomapBase<TREE>::update(bool updateRealDist){ for(octomap::KeyBoolMap::const_iterator it = octree->changedKeysBegin(), end=octree->changedKeysEnd(); it!=end; ++it){ //the keys in this list all go down to the lowest level! octomap::OcTreeKey key = it->first; //ignore changes outside of bounding box if(key[0] < boundingBoxMinKey[0] || key[1] < boundingBoxMinKey[1] || key[2] < boundingBoxMinKey[2]) continue; if(key[0] > boundingBoxMaxKey[0] || key[1] > boundingBoxMaxKey[1] || key[2] > boundingBoxMaxKey[2]) continue; typename TREE::NodeType* node = octree->search(key); assert(node); //"node" is not necessarily at lowest level, BUT: the occupancy value of this node //has to be the same as of the node indexed by the key *it updateMaxDepthLeaf(key, octree->isNodeOccupied(node)); } octree->resetChangeDetection(); DynamicEDT3D::update(updateRealDist); } template <class TREE> void DynamicEDTOctomapBase<TREE>::initializeOcTree(octomap::point3d bbxMin, octomap::point3d bbxMax){ boundingBoxMinKey = octree->coordToKey(bbxMin); boundingBoxMaxKey = octree->coordToKey(bbxMax); offsetX = -boundingBoxMinKey[0]; offsetY = -boundingBoxMinKey[1]; offsetZ = -boundingBoxMinKey[2]; int _sizeX = boundingBoxMaxKey[0] - boundingBoxMinKey[0] + 1; int _sizeY = boundingBoxMaxKey[1] - boundingBoxMinKey[1] + 1; int _sizeZ = boundingBoxMaxKey[2] - boundingBoxMinKey[2] + 1; initializeEmpty(_sizeX, _sizeY, _sizeZ, false); if(unknownOccupied == false){ for(typename TREE::leaf_bbx_iterator it = octree->begin_leafs_bbx(bbxMin,bbxMax), end=octree->end_leafs_bbx(); it!= end; ++it){ if(octree->isNodeOccupied(*it)){ int nodeDepth = it.getDepth(); if( nodeDepth == treeDepth){ insertMaxDepthLeafAtInitialize(it.getKey()); } else { int cubeSize = 1 << (treeDepth - nodeDepth); octomap::OcTreeKey key=it.getIndexKey(); for(int dx = 0; dx < cubeSize; dx++) for(int dy = 0; dy < cubeSize; dy++) for(int dz = 0; dz < cubeSize; dz++){ unsigned short int tmpx = key[0]+dx; unsigned short int tmpy = key[1]+dy; unsigned short int tmpz = key[2]+dz; if(boundingBoxMinKey[0] > tmpx || boundingBoxMinKey[1] > tmpy || boundingBoxMinKey[2] > tmpz) continue; if(boundingBoxMaxKey[0] < tmpx || boundingBoxMaxKey[1] < tmpy || boundingBoxMaxKey[2] < tmpz) continue; insertMaxDepthLeafAtInitialize(octomap::OcTreeKey(tmpx, tmpy, tmpz)); } } } } } else { octomap::OcTreeKey key; for(int dx=0; dx<sizeX; dx++){ key[0] = boundingBoxMinKey[0] + dx; for(int dy=0; dy<sizeY; dy++){ key[1] = boundingBoxMinKey[1] + dy; for(int dz=0; dz<sizeZ; dz++){ key[2] = boundingBoxMinKey[2] + dz; typename TREE::NodeType* node = octree->search(key); if(!node || octree->isNodeOccupied(node)){ insertMaxDepthLeafAtInitialize(key); } } } } } } template <class TREE> void DynamicEDTOctomapBase<TREE>::insertMaxDepthLeafAtInitialize(octomap::OcTreeKey key){ bool isSurrounded = true; for(int dx=-1; dx<=1; dx++) for(int dy=-1; dy<=1; dy++) for(int dz=-1; dz<=1; dz++){ if(dx==0 && dy==0 && dz==0) continue; typename TREE::NodeType* node = octree->search(octomap::OcTreeKey(key[0]+dx, key[1]+dy, key[2]+dz)); if((!unknownOccupied && node==NULL) || ((node!=NULL) && (octree->isNodeOccupied(node)==false))){ isSurrounded = false; break; } } if(isSurrounded){ //obstacles that are surrounded by obstacles do not need to be put in the queues, //hence this initialization dataCell c; int x = key[0]+offsetX; int y = key[1]+offsetY; int z = key[2]+offsetZ; c.obstX = x; c.obstY = y; c.obstZ = z; c.sqdist = 0; c.dist = 0.0; c.queueing = fwProcessed; c.needsRaise = false; data[x][y][z] = c; } else { setObstacle(key[0]+offsetX, key[1]+offsetY, key[2]+offsetZ); } } template <class TREE> void DynamicEDTOctomapBase<TREE>::updateMaxDepthLeaf(octomap::OcTreeKey& key, bool occupied){ if(occupied) setObstacle(key[0]+offsetX, key[1]+offsetY, key[2]+offsetZ); else removeObstacle(key[0]+offsetX, key[1]+offsetY, key[2]+offsetZ); } template <class TREE> void DynamicEDTOctomapBase<TREE>::worldToMap(const octomap::point3d &p, int &x, int &y, int &z) const { octomap::OcTreeKey key = octree->coordToKey(p); x = key[0] + offsetX; y = key[1] + offsetY; z = key[2] + offsetZ; } template <class TREE> void DynamicEDTOctomapBase<TREE>::mapToWorld(int x, int y, int z, octomap::point3d &p) const { p = octree->keyToCoord(octomap::OcTreeKey(x-offsetX, y-offsetY, z-offsetZ)); } template <class TREE> void DynamicEDTOctomapBase<TREE>::mapToWorld(int x, int y, int z, octomap::OcTreeKey &key) const { key = octomap::OcTreeKey(x-offsetX, y-offsetY, z-offsetZ); } template <class TREE> void DynamicEDTOctomapBase<TREE>::getDistanceAndClosestObstacle(const octomap::point3d& p, float &distance, octomap::point3d& closestObstacle) const { int x,y,z; worldToMap(p, x, y, z); if(x>=0 && x<sizeX && y>=0 && y<sizeY && z>=0 && z<sizeZ){ dataCell c= data[x][y][z]; distance = c.dist*treeResolution; if(c.obstX != invalidObstData){ mapToWorld(c.obstX, c.obstY, c.obstZ, closestObstacle); } else { //If we are at maxDist, it can very well be that there is no valid closest obstacle data for this cell, this is not an error. } } else { distance = distanceValue_Error; } } template <class TREE> void DynamicEDTOctomapBase<TREE>::getDistanceAndClosestObstacle_unsafe(const octomap::point3d& p, float &distance, octomap::point3d& closestObstacle) const { int x,y,z; worldToMap(p, x, y, z); dataCell c= data[x][y][z]; distance = c.dist*treeResolution; if(c.obstX != invalidObstData){ mapToWorld(c.obstX, c.obstY, c.obstZ, closestObstacle); } else { //If we are at maxDist, it can very well be that there is no valid closest obstacle data for this cell, this is not an error. } } template <class TREE> float DynamicEDTOctomapBase<TREE>::getDistance(const octomap::point3d& p) const { int x,y,z; worldToMap(p, x, y, z); if(x>=0 && x<sizeX && y>=0 && y<sizeY && z>=0 && z<sizeZ){ return data[x][y][z].dist*treeResolution; } else { return distanceValue_Error; } } template <class TREE> float DynamicEDTOctomapBase<TREE>::getDistance_unsafe(const octomap::point3d& p) const { int x,y,z; worldToMap(p, x, y, z); return data[x][y][z].dist*treeResolution; } template <class TREE> float DynamicEDTOctomapBase<TREE>::getDistance(const octomap::OcTreeKey& k) const { int x = k[0] + offsetX; int y = k[1] + offsetY; int z = k[2] + offsetZ; if(x>=0 && x<sizeX && y>=0 && y<sizeY && z>=0 && z<sizeZ){ return data[x][y][z].dist*treeResolution; } else { return distanceValue_Error; } } template <class TREE> float DynamicEDTOctomapBase<TREE>::getDistance_unsafe(const octomap::OcTreeKey& k) const { int x = k[0] + offsetX; int y = k[1] + offsetY; int z = k[2] + offsetZ; return data[x][y][z].dist*treeResolution; } template <class TREE> int DynamicEDTOctomapBase<TREE>::getSquaredDistanceInCells(const octomap::point3d& p) const { int x,y,z; worldToMap(p, x, y, z); if(x>=0 && x<sizeX && y>=0 && y<sizeY && z>=0 && z<sizeZ){ return data[x][y][z].sqdist; } else { return distanceInCellsValue_Error; } } template <class TREE> int DynamicEDTOctomapBase<TREE>::getSquaredDistanceInCells_unsafe(const octomap::point3d& p) const { int x,y,z; worldToMap(p, x, y, z); return data[x][y][z].sqdist; } template <class TREE> bool DynamicEDTOctomapBase<TREE>::checkConsistency() const { for(octomap::KeyBoolMap::const_iterator it = octree->changedKeysBegin(), end=octree->changedKeysEnd(); it!=end; ++it){ //std::cerr<<"Cannot check consistency, you must execute the update() method first."<<std::endl; return false; } for(int x=0; x<sizeX; x++){ for(int y=0; y<sizeY; y++){ for(int z=0; z<sizeZ; z++){ octomap::point3d point; mapToWorld(x,y,z,point); typename TREE::NodeType* node = octree->search(point); bool mapOccupied = isOccupied(x,y,z); bool treeOccupied = false; if(node){ treeOccupied = octree->isNodeOccupied(node); } else { if(unknownOccupied) treeOccupied = true; } if(mapOccupied != treeOccupied){ //std::cerr<<"OCCUPANCY MISMATCH BETWEEN TREE AND MAP at "<<x<<","<<y<<","<<z<<std::endl; //std::cerr<<"Tree "<<treeOccupied<<std::endl; //std::cerr<<"Map "<<mapOccupied<<std::endl; return false; } } } } return true; }
11,291
32.309735
163
hxx
octomap
octomap-master/dynamicEDT3D/include/dynamicEDT3D/point.h
/** * dynamicEDT3D: * A library for incrementally updatable Euclidean distance transforms in 3D. * @author C. Sprunk, B. Lau, W. Burgard, University of Freiburg, Copyright (C) 2011. * @see http://octomap.sourceforge.net/ * License: New BSD License */ /* * Copyright (c) 2011-2012, C. Sprunk, B. Lau, W. Burgard, University of Freiburg * 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 University of Freiburg 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. */ #ifndef _VOROPOINT_H_ #define _VOROPOINT_H_ #define INTPOINT IntPoint #define INTPOINT3D IntPoint3D /*! A light-weight integer point with fields x,y */ class IntPoint { public: IntPoint() : x(0), y(0) {} IntPoint(int _x, int _y) : x(_x), y(_y) {} int x,y; }; /*! A light-weight integer point with fields x,y,z */ class IntPoint3D { public: IntPoint3D() : x(0), y(0), z(0) {} IntPoint3D(int _x, int _y, int _z) : x(_x), y(_y), z(_z) {} int x,y,z; }; #endif
2,379
37.387097
84
h
octomap
octomap-master/dynamicEDT3D/src/dynamicEDT3D.cpp
/** * dynamicEDT3D: * A library for incrementally updatable Euclidean distance transforms in 3D. * @author C. Sprunk, B. Lau, W. Burgard, University of Freiburg, Copyright (C) 2011. * @see http://octomap.sourceforge.net/ * License: New BSD License */ /* * Copyright (c) 2011-2012, C. Sprunk, B. Lau, W. Burgard, University of Freiburg * 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 University of Freiburg 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. */ #include <dynamicEDT3D/dynamicEDT3D.h> #include <math.h> #include <stdlib.h> #define FOR_EACH_NEIGHBOR_WITH_CHECK(function, p, ...) \ int x=p.x;\ int y=p.y;\ int z=p.z;\ int xp1 = x+1;\ int xm1 = x-1;\ int yp1 = y+1;\ int ym1 = y-1;\ int zp1 = z+1;\ int zm1 = z-1;\ \ if(z<sizeZm1) function(x, y, zp1, ##__VA_ARGS__);\ if(z>0) function(x, y, zm1, ##__VA_ARGS__);\ \ if(y<sizeYm1){\ function(x, yp1, z, ##__VA_ARGS__);\ if(z<sizeZm1) function(x, yp1, zp1, ##__VA_ARGS__);\ if(z>0) function(x, yp1, zm1, ##__VA_ARGS__);\ }\ \ if(y>0){\ function(x, ym1, z, ##__VA_ARGS__);\ if(z<sizeZm1) function(x, ym1, zp1, ##__VA_ARGS__);\ if(z>0) function(x, ym1, zm1, ##__VA_ARGS__);\ }\ \ \ if(x<sizeXm1){\ function(xp1, y, z, ##__VA_ARGS__);\ if(z<sizeZm1) function(xp1, y, zp1, ##__VA_ARGS__);\ if(z>0) function(xp1, y, zm1, ##__VA_ARGS__);\ \ if(y<sizeYm1){\ function(xp1, yp1, z, ##__VA_ARGS__);\ if(z<sizeZm1) function(xp1, yp1, zp1, ##__VA_ARGS__);\ if(z>0) function(xp1, yp1, zm1, ##__VA_ARGS__);\ }\ \ if(y>0){\ function(xp1, ym1, z, ##__VA_ARGS__);\ if(z<sizeZm1) function(xp1, ym1, zp1, ##__VA_ARGS__);\ if(z>0) function(xp1, ym1, zm1, ##__VA_ARGS__);\ }\ }\ \ if(x>0){\ function(xm1, y, z, ##__VA_ARGS__);\ if(z<sizeZm1) function(xm1, y, zp1, ##__VA_ARGS__);\ if(z>0) function(xm1, y, zm1, ##__VA_ARGS__);\ \ if(y<sizeYm1){\ function(xm1, yp1, z, ##__VA_ARGS__);\ if(z<sizeZm1) function(xm1, yp1, zp1, ##__VA_ARGS__);\ if(z>0) function(xm1, yp1, zm1, ##__VA_ARGS__);\ }\ \ if(y>0){\ function(xm1, ym1, z, ##__VA_ARGS__);\ if(z<sizeZm1) function(xm1, ym1, zp1, ##__VA_ARGS__);\ if(z>0) function(xm1, ym1, zm1, ##__VA_ARGS__);\ }\ } float DynamicEDT3D::distanceValue_Error = -1.0; int DynamicEDT3D::distanceInCellsValue_Error = -1; DynamicEDT3D::DynamicEDT3D(int _maxdist_squared) { sqrt2 = sqrt(2.0); maxDist_squared = _maxdist_squared; maxDist = sqrt((double) maxDist_squared); data = NULL; gridMap = NULL; } DynamicEDT3D::~DynamicEDT3D() { if (data) { for (int x=0; x<sizeX; x++){ for (int y=0; y<sizeY; y++) delete[] data[x][y]; delete[] data[x]; } delete[] data; } if (gridMap) { for (int x=0; x<sizeX; x++){ for (int y=0; y<sizeY; y++) delete[] gridMap[x][y]; delete[] gridMap[x]; } delete[] gridMap; } } void DynamicEDT3D::initializeEmpty(int _sizeX, int _sizeY, int _sizeZ, bool initGridMap) { sizeX = _sizeX; sizeY = _sizeY; sizeZ = _sizeZ; sizeXm1 = sizeX-1; sizeYm1 = sizeY-1; sizeZm1 = sizeZ-1; if (data) { for (int x=0; x<sizeX; x++){ for (int y=0; y<sizeY; y++) delete[] data[x][y]; delete[] data[x]; } delete[] data; } data = new dataCell**[sizeX]; for (int x=0; x<sizeX; x++){ data[x] = new dataCell*[sizeY]; for(int y=0; y<sizeY; y++) data[x][y] = new dataCell[sizeZ]; } if (initGridMap) { if (gridMap) { for (int x=0; x<sizeX; x++){ for (int y=0; y<sizeY; y++) delete[] gridMap[x][y]; delete[] gridMap[x]; } delete[] gridMap; } gridMap = new bool**[sizeX]; for (int x=0; x<sizeX; x++){ gridMap[x] = new bool*[sizeY]; for (int y=0; y<sizeY; y++) gridMap[x][y] = new bool[sizeZ]; } } dataCell c; c.dist = maxDist; c.sqdist = maxDist_squared; c.obstX = invalidObstData; c.obstY = invalidObstData; c.obstZ = invalidObstData; c.queueing = fwNotQueued; c.needsRaise = false; for (int x=0; x<sizeX; x++){ for (int y=0; y<sizeY; y++){ for (int z=0; z<sizeZ; z++){ data[x][y][z] = c; } } } if (initGridMap) { for (int x=0; x<sizeX; x++) for (int y=0; y<sizeY; y++) for (int z=0; z<sizeZ; z++) gridMap[x][y][z] = 0; } } void DynamicEDT3D::initializeMap(int _sizeX, int _sizeY, int _sizeZ, bool*** _gridMap) { gridMap = _gridMap; initializeEmpty(_sizeX, _sizeY, _sizeZ, false); for (int x=0; x<sizeX; x++) { for (int y=0; y<sizeY; y++) { for (int z=0; z<sizeZ; z++) { if (gridMap[x][y][z]) { dataCell c = data[x][y][z]; if (!isOccupied(x,y,z,c)) { bool isSurrounded = true; for (int dx=-1; dx<=1; dx++) { int nx = x+dx; if (nx<0 || nx>sizeX-1) continue; for (int dy=-1; dy<=1; dy++) { int ny = y+dy; if (ny<0 || ny>sizeY-1) continue; for (int dz=-1; dz<=1; dz++) { if (dx==0 && dy==0 && dz==0) continue; int nz = z+dz; if (nz<0 || nz>sizeZ-1) continue; if (!gridMap[nx][ny][nz]) { isSurrounded = false; break; } } } } if (isSurrounded) { c.obstX = x; c.obstY = y; c.obstZ = z; c.sqdist = 0; c.dist = 0; c.queueing = fwProcessed; data[x][y][z] = c; } else setObstacle(x,y,z); } } } } } } void DynamicEDT3D::occupyCell(int x, int y, int z) { gridMap[x][y][z] = 1; setObstacle(x,y,z); } void DynamicEDT3D::clearCell(int x, int y, int z) { gridMap[x][y][z] = 0; removeObstacle(x,y,z); } void DynamicEDT3D::setObstacle(int x, int y, int z) { dataCell c = data[x][y][z]; if(isOccupied(x,y,z,c)) return; addList.push_back(INTPOINT3D(x,y,z)); c.obstX = x; c.obstY = y; c.obstZ = z; data[x][y][z] = c; } void DynamicEDT3D::removeObstacle(int x, int y, int z) { dataCell c = data[x][y][z]; if(isOccupied(x,y,z,c) == false) return; removeList.push_back(INTPOINT3D(x,y,z)); c.obstX = invalidObstData; c.obstY = invalidObstData; c.obstZ = invalidObstData; c.queueing = bwQueued; data[x][y][z] = c; } void DynamicEDT3D::exchangeObstacles(std::vector<INTPOINT3D> points) { for (unsigned int i=0; i<lastObstacles.size(); i++) { int x = lastObstacles[i].x; int y = lastObstacles[i].y; int z = lastObstacles[i].z; bool v = gridMap[x][y][z]; if (v) continue; removeObstacle(x,y,z); } lastObstacles.clear(); for (unsigned int i=0; i<points.size(); i++) { int x = points[i].x; int y = points[i].y; int z = points[i].z; bool v = gridMap[x][y][z]; if (v) continue; setObstacle(x,y,z); lastObstacles.push_back(points[i]); } } void DynamicEDT3D::update(bool updateRealDist) { commitAndColorize(updateRealDist); while (!open.empty()) { INTPOINT3D p = open.pop(); int x = p.x; int y = p.y; int z = p.z; dataCell c = data[x][y][z]; if(c.queueing==fwProcessed) continue; if (c.needsRaise) { // RAISE raiseCell(p, c, updateRealDist); data[x][y][z] = c; } else if (c.obstX != invalidObstData && isOccupied(c.obstX,c.obstY,c.obstZ,data[c.obstX][c.obstY][c.obstZ])) { // LOWER propagateCell(p, c, updateRealDist); data[x][y][z] = c; } } } void DynamicEDT3D::raiseCell(INTPOINT3D &p, dataCell &c, bool updateRealDist){ /* for (int dx=-1; dx<=1; dx++) { int nx = p.x+dx; if (nx<0 || nx>sizeX-1) continue; for (int dy=-1; dy<=1; dy++) { int ny = p.y+dy; if (ny<0 || ny>sizeY-1) continue; for (int dz=-1; dz<=1; dz++) { if (dx==0 && dy==0 && dz==0) continue; int nz = p.z+dz; if (nz<0 || nz>sizeZ-1) continue; inspectCellRaise(nx,ny,nz, updateRealDist); } } } */ FOR_EACH_NEIGHBOR_WITH_CHECK(inspectCellRaise,p, updateRealDist) c.needsRaise = false; c.queueing = bwProcessed; } void DynamicEDT3D::inspectCellRaise(int &nx, int &ny, int &nz, bool updateRealDist){ dataCell nc = data[nx][ny][nz]; if (nc.obstX!=invalidObstData && !nc.needsRaise) { if(!isOccupied(nc.obstX,nc.obstY,nc.obstZ,data[nc.obstX][nc.obstY][nc.obstZ])) { open.push(nc.sqdist, INTPOINT3D(nx,ny,nz)); nc.queueing = fwQueued; nc.needsRaise = true; nc.obstX = invalidObstData; nc.obstY = invalidObstData; nc.obstZ = invalidObstData; if (updateRealDist) nc.dist = maxDist; nc.sqdist = maxDist_squared; data[nx][ny][nz] = nc; } else { if(nc.queueing != fwQueued){ open.push(nc.sqdist, INTPOINT3D(nx,ny,nz)); nc.queueing = fwQueued; data[nx][ny][nz] = nc; } } } } void DynamicEDT3D::propagateCell(INTPOINT3D &p, dataCell &c, bool updateRealDist){ c.queueing = fwProcessed; /* for (int dx=-1; dx<=1; dx++) { int nx = p.x+dx; if (nx<0 || nx>sizeX-1) continue; for (int dy=-1; dy<=1; dy++) { int ny = p.y+dy; if (ny<0 || ny>sizeY-1) continue; for (int dz=-1; dz<=1; dz++) { if (dx==0 && dy==0 && dz==0) continue; int nz = p.z+dz; if (nz<0 || nz>sizeZ-1) continue; inspectCellPropagate(nx, ny, nz, c, updateRealDist); } } } */ if(c.sqdist==0){ FOR_EACH_NEIGHBOR_WITH_CHECK(inspectCellPropagate, p, c, updateRealDist) } else { int x=p.x; int y=p.y; int z=p.z; int xp1 = x+1; int xm1 = x-1; int yp1 = y+1; int ym1 = y-1; int zp1 = z+1; int zm1 = z-1; int dpx = (x - c.obstX); int dpy = (y - c.obstY); int dpz = (z - c.obstZ); // dpy=0; // dpz=0; if(dpz >=0 && z<sizeZm1) inspectCellPropagate(x, y, zp1, c, updateRealDist); if(dpz <=0 && z>0) inspectCellPropagate(x, y, zm1, c, updateRealDist); if(dpy>=0 && y<sizeYm1){ inspectCellPropagate(x, yp1, z, c, updateRealDist); if(dpz >=0 && z<sizeZm1) inspectCellPropagate(x, yp1, zp1, c, updateRealDist); if(dpz <=0 && z>0) inspectCellPropagate(x, yp1, zm1, c, updateRealDist); } if(dpy<=0 && y>0){ inspectCellPropagate(x, ym1, z, c, updateRealDist); if(dpz >=0 && z<sizeZm1) inspectCellPropagate(x, ym1, zp1, c, updateRealDist); if(dpz <=0 && z>0) inspectCellPropagate(x, ym1, zm1, c, updateRealDist); } if(dpx>=0 && x<sizeXm1){ inspectCellPropagate(xp1, y, z, c, updateRealDist); if(dpz >=0 && z<sizeZm1) inspectCellPropagate(xp1, y, zp1, c, updateRealDist); if(dpz <=0 && z>0) inspectCellPropagate(xp1, y, zm1, c, updateRealDist); if(dpy>=0 && y<sizeYm1){ inspectCellPropagate(xp1, yp1, z, c, updateRealDist); if(dpz >=0 && z<sizeZm1) inspectCellPropagate(xp1, yp1, zp1, c, updateRealDist); if(dpz <=0 && z>0) inspectCellPropagate(xp1, yp1, zm1, c, updateRealDist); } if(dpy<=0 && y>0){ inspectCellPropagate(xp1, ym1, z, c, updateRealDist); if(dpz >=0 && z<sizeZm1) inspectCellPropagate(xp1, ym1, zp1, c, updateRealDist); if(dpz <=0 && z>0) inspectCellPropagate(xp1, ym1, zm1, c, updateRealDist); } } if(dpx<=0 && x>0){ inspectCellPropagate(xm1, y, z, c, updateRealDist); if(dpz >=0 && z<sizeZm1) inspectCellPropagate(xm1, y, zp1, c, updateRealDist); if(dpz <=0 && z>0) inspectCellPropagate(xm1, y, zm1, c, updateRealDist); if(dpy>=0 && y<sizeYm1){ inspectCellPropagate(xm1, yp1, z, c, updateRealDist); if(dpz >=0 && z<sizeZm1) inspectCellPropagate(xm1, yp1, zp1, c, updateRealDist); if(dpz <=0 && z>0) inspectCellPropagate(xm1, yp1, zm1, c, updateRealDist); } if(dpy<=0 && y>0){ inspectCellPropagate(xm1, ym1, z, c, updateRealDist); if(dpz >=0 && z<sizeZm1) inspectCellPropagate(xm1, ym1, zp1, c, updateRealDist); if(dpz <=0 && z>0) inspectCellPropagate(xm1, ym1, zm1, c, updateRealDist); } } } } void DynamicEDT3D::inspectCellPropagate(int &nx, int &ny, int &nz, dataCell &c, bool updateRealDist){ dataCell nc = data[nx][ny][nz]; if(!nc.needsRaise) { int distx = nx-c.obstX; int disty = ny-c.obstY; int distz = nz-c.obstZ; int newSqDistance = distx*distx + disty*disty + distz*distz; if(newSqDistance > maxDist_squared) newSqDistance = maxDist_squared; bool overwrite = (newSqDistance < nc.sqdist); if(!overwrite && newSqDistance==nc.sqdist) { //the neighbor cell is marked to be raised, has no valid source obstacle if (nc.obstX == invalidObstData){ overwrite = true; } else { //the neighbor has no valid source obstacle but the raise wave has not yet reached it dataCell tmp = data[nc.obstX][nc.obstY][nc.obstZ]; if((tmp.obstX==nc.obstX && tmp.obstY==nc.obstY && tmp.obstZ==nc.obstZ)==false) overwrite = true; } } if (overwrite) { if(newSqDistance < maxDist_squared){ open.push(newSqDistance, INTPOINT3D(nx,ny,nz)); nc.queueing = fwQueued; } if (updateRealDist) { nc.dist = sqrt((double) newSqDistance); } nc.sqdist = newSqDistance; nc.obstX = c.obstX; nc.obstY = c.obstY; nc.obstZ = c.obstZ; } data[nx][ny][nz] = nc; } } float DynamicEDT3D::getDistance( int x, int y, int z ) const { if( (x>=0) && (x<sizeX) && (y>=0) && (y<sizeY) && (z>=0) && (z<sizeZ)){ return data[x][y][z].dist; } else return distanceValue_Error; } INTPOINT3D DynamicEDT3D::getClosestObstacle( int x, int y, int z ) const { if( (x>=0) && (x<sizeX) && (y>=0) && (y<sizeY) && (z>=0) && (z<sizeZ)){ dataCell c = data[x][y][z]; return INTPOINT3D(c.obstX, c.obstY, c.obstZ); } else return INTPOINT3D(invalidObstData, invalidObstData, invalidObstData); } int DynamicEDT3D::getSQCellDistance( int x, int y, int z ) const { if( (x>=0) && (x<sizeX) && (y>=0) && (y<sizeY) && (z>=0) && (z<sizeZ)){ return data[x][y][z].sqdist; } else return distanceInCellsValue_Error; } void DynamicEDT3D::commitAndColorize(bool updateRealDist) { // ADD NEW OBSTACLES for (unsigned int i=0; i<addList.size(); i++) { INTPOINT3D p = addList[i]; int x = p.x; int y = p.y; int z = p.z; dataCell c = data[x][y][z]; if(c.queueing != fwQueued){ if (updateRealDist) c.dist = 0; c.sqdist = 0; c.obstX = x; c.obstY = y; c.obstZ = z; c.queueing = fwQueued; data[x][y][z] = c; open.push(0, INTPOINT3D(x,y,z)); } } // REMOVE OLD OBSTACLES for (unsigned int i=0; i<removeList.size(); i++) { INTPOINT3D p = removeList[i]; int x = p.x; int y = p.y; int z = p.z; dataCell c = data[x][y][z]; if (isOccupied(x,y,z,c)==true) continue; // obstacle was removed and reinserted open.push(0, INTPOINT3D(x,y,z)); if (updateRealDist) c.dist = maxDist; c.sqdist = maxDist_squared; c.needsRaise = true; data[x][y][z] = c; } removeList.clear(); addList.clear(); } bool DynamicEDT3D::isOccupied(int x, int y, int z) const { dataCell c = data[x][y][z]; return (c.obstX==x && c.obstY==y && c.obstZ==z); } bool DynamicEDT3D::isOccupied(int &x, int &y, int &z, dataCell &c) { return (c.obstX==x && c.obstY==y && c.obstZ==z); }
16,104
26.204392
112
cpp
octomap
octomap-master/dynamicEDT3D/src/examples/exampleEDT3D.cpp
/** * dynamicEDT3D: * A library for incrementally updatable Euclidean distance transforms in 3D. * @author C. Sprunk, B. Lau, W. Burgard, University of Freiburg, Copyright (C) 2011. * @see http://octomap.sourceforge.net/ * License: New BSD License */ /* * Copyright (c) 2011-2012, C. Sprunk, B. Lau, W. Burgard, University of Freiburg * 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 University of Freiburg 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. */ #include <dynamicEDT3D/dynamicEDT3D.h> #include <iostream> #include <stdlib.h> int main( int , char** ) { //we build a sample map int sizeX, sizeY, sizeZ; sizeX=100; sizeY=100; sizeZ=100; bool*** map; map = new bool**[sizeX]; for(int x=0; x<sizeX; x++){ map[x] = new bool*[sizeY]; for(int y=0; y<sizeY; y++){ map[x][y] = new bool[sizeZ]; for(int z=0; z<sizeZ; z++){ if(x<2 || x > sizeX-3 || y < 2 || y > sizeY-3 || z<2 || z > sizeZ-3) map[x][y][z] = 1; else map[x][y][z] = 0; } } } map[51][45][67] = 1; map[50][50][68] = 1; // create the EDT object and initialize it with the map int maxDistInCells = 20; DynamicEDT3D distmap(maxDistInCells*maxDistInCells); distmap.initializeMap(sizeX, sizeY, sizeZ, map); //compute the distance map distmap.update(); // now perform some updates with random obstacles int numPoints = 20; for (int frame=1; frame<=10; frame++) { std::cout<<"\n\nthis is frame #"<<frame<<std::endl; std::vector<IntPoint3D> newObstacles; for (int i=0; i<numPoints; i++) { double x = 2+rand()/(double)RAND_MAX*(sizeX-4); double y = 2+rand()/(double)RAND_MAX*(sizeY-4); double z = 2+rand()/(double)RAND_MAX*(sizeZ-4); newObstacles.push_back(IntPoint3D(x,y,z)); } // register the new obstacles (old ones will be removed) distmap.exchangeObstacles(newObstacles); //update the distance map distmap.update(); //retrieve distance at a point float dist = distmap.getDistance(30,67,33); int distSquared = distmap.getSQCellDistance(30,67,33); std::cout<<"distance at 30,67,33: "<< dist << " squared: "<< distSquared << std::endl; if(distSquared == maxDistInCells*maxDistInCells) std::cout<<"we hit a cell with d = dmax, distance value is clamped."<<std::endl; //retrieve closest occupied cell at a point IntPoint3D closest = distmap.getClosestObstacle(30,67,33); if(closest.x == DynamicEDT3D::invalidObstData) std::cout<<"we hit a cell with d = dmax, no information about closest occupied cell."<<std::endl; else std::cout<<"closest occupied cell to 30,67,33: "<< closest.x<<","<<closest.y<<","<<closest.z<<std::endl; } std::cout<<"\n\nthis is the last frame"<<std::endl; // now remove all random obstacles again. std::vector<IntPoint3D> empty; distmap.exchangeObstacles(empty); distmap.update(); //retrieve distance at a point float dist = distmap.getDistance(30,67,33); int distSquared = distmap.getSQCellDistance(30,67,33); std::cout<<"distance at 30,67,33: "<< dist << " squared: "<< distSquared << std::endl; if(distSquared == maxDistInCells*maxDistInCells) std::cout<<"we hit a cell with d = dmax, distance value is clamped."<<std::endl; //retrieve closest occupied cell at a point IntPoint3D closest = distmap.getClosestObstacle(30,67,33); if(closest.x == DynamicEDT3D::invalidObstData) std::cout<<"we hit a cell with d = dmax, no information about closest occupied cell."<<std::endl; else std::cout<<"closest occupied cell to 30,67,33: "<< closest.x<<","<<closest.y<<","<<closest.z<<std::endl; return 0; }
5,086
36.404412
108
cpp
octomap
octomap-master/dynamicEDT3D/src/examples/exampleEDTOctomap.cpp
/** * dynamicEDT3D: * A library for incrementally updatable Euclidean distance transforms in 3D. * @author C. Sprunk, B. Lau, W. Burgard, University of Freiburg, Copyright (C) 2011. * @see http://octomap.sourceforge.net/ * License: New BSD License */ /* * Copyright (c) 2011-2012, C. Sprunk, B. Lau, W. Burgard, University of Freiburg * 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 University of Freiburg 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. */ #include <dynamicEDT3D/dynamicEDTOctomap.h> #include <iostream> int main( int argc, char *argv[] ) { if(argc<=1){ std::cout<<"usage: "<<argv[0]<<" <octoMap.bt>"<<std::endl; exit(0); } octomap::OcTree *tree = NULL; tree = new octomap::OcTree(0.05); //read in octotree tree->readBinary(argv[1]); std::cout<<"read in tree, "<<tree->getNumLeafNodes()<<" leaves "<<std::endl; double x,y,z; tree->getMetricMin(x,y,z); octomap::point3d min(x,y,z); //std::cout<<"Metric min: "<<x<<","<<y<<","<<z<<std::endl; tree->getMetricMax(x,y,z); octomap::point3d max(x,y,z); //std::cout<<"Metric max: "<<x<<","<<y<<","<<z<<std::endl; bool unknownAsOccupied = true; unknownAsOccupied = false; float maxDist = 1.0; //- the first argument ist the max distance at which distance computations are clamped //- the second argument is the octomap //- arguments 3 and 4 can be used to restrict the distance map to a subarea //- argument 5 defines whether unknown space is treated as occupied or free //The constructor copies data but does not yet compute the distance map DynamicEDTOctomap distmap(maxDist, tree, min, max, unknownAsOccupied); //This computes the distance map distmap.update(); //This is how you can query the map octomap::point3d p(5.0,5.0,0.6); //As we don't know what the dimension of the loaded map are, we modify this point p.x() = min.x() + 0.3 * (max.x() - min.x()); p.y() = min.y() + 0.6 * (max.y() - min.y()); p.z() = min.z() + 0.5 * (max.z() - min.z()); octomap::point3d closestObst; float distance; distmap.getDistanceAndClosestObstacle(p, distance, closestObst); std::cout<<"\n\ndistance at point "<<p.x()<<","<<p.y()<<","<<p.z()<<" is "<<distance<<std::endl; if(distance < distmap.getMaxDist()) std::cout<<"closest obstacle to "<<p.x()<<","<<p.y()<<","<<p.z()<<" is at "<<closestObst.x()<<","<<closestObst.y()<<","<<closestObst.z()<<std::endl; //if you modify the octree via tree->insertScan() or tree->updateNode() //just call distmap.update() again to adapt the distance map to the changes made delete tree; return 0; }
4,039
38.607843
152
cpp
octomap
octomap-master/dynamicEDT3D/src/examples/exampleEDTOctomapStamped.cpp
/** * dynamicEDT3D: * A library for incrementally updatable Euclidean distance transforms in 3D. * @author C. Sprunk, B. Lau, W. Burgard, University of Freiburg, Copyright (C) 2011. * @see http://octomap.sourceforge.net/ * License: New BSD License */ /* * Copyright (c) 2011-2012, C. Sprunk, B. Lau, W. Burgard, University of Freiburg * 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 University of Freiburg 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. */ #include <dynamicEDT3D/dynamicEDTOctomap.h> #include <iostream> int main( int argc, char *argv[] ) { if(argc<=1){ std::cout<<"usage: "<<argv[0]<<" <octoMap.bt>"<<std::endl; exit(0); } typedef octomap::OcTreeStamped OcTreeType; OcTreeType *tree = NULL; tree = new OcTreeType(0.05); //read in octotree tree->readBinary(argv[1]); std::cout<<"read in tree, "<<tree->getNumLeafNodes()<<" leaves "<<std::endl; double x,y,z; tree->getMetricMin(x,y,z); octomap::point3d min(x,y,z); //std::cout<<"Metric min: "<<x<<","<<y<<","<<z<<std::endl; tree->getMetricMax(x,y,z); octomap::point3d max(x,y,z); //std::cout<<"Metric max: "<<x<<","<<y<<","<<z<<std::endl; bool unknownAsOccupied = true; unknownAsOccupied = false; float maxDist = 1.0; //- the first argument is the max distance at which distance computations are clamped //- the second argument is the octomap //- arguments 3 and 4 can be used to restrict the distance map to a subarea //- argument 5 defines whether unknown space is treated as occupied or free //The constructor copies data but does not yet compute the distance map DynamicEDTOctomapStamped distmap(maxDist, tree, min, max, unknownAsOccupied); //This computes the distance map distmap.update(); //This is how you can query the map octomap::point3d p(5.0,5.0,0.6); //As we don't know what the dimension of the loaded map are, we modify this point p.x() = min.x() + 0.3 * (max.x() - min.x()); p.y() = min.y() + 0.6 * (max.y() - min.y()); p.z() = min.z() + 0.5 * (max.z() - min.z()); octomap::point3d closestObst; float distance; distmap.getDistanceAndClosestObstacle(p, distance, closestObst); std::cout<<"\n\ndistance at point "<<p.x()<<","<<p.y()<<","<<p.z()<<" is "<<distance<<std::endl; if(distance < distmap.getMaxDist()) std::cout<<"closest obstacle to "<<p.x()<<","<<p.y()<<","<<p.z()<<" is at "<<closestObst.x()<<","<<closestObst.y()<<","<<closestObst.z()<<std::endl; //if you modify the octree via tree->insertScan() or tree->updateNode() //just call distmap.update() again to adapt the distance map to the changes made delete tree; return 0; }
4,080
38.621359
152
cpp
octomap
octomap-master/octomap/doxygen.h
/** * \namespace octomath Namespace of the math library in OctoMap * */ /** * \namespace octomap Namespace the OctoMap library and visualization tools * */ /** \mainpage OctoMap \section intro_sec Introduction The <a href="https://octomap.github.io/">OctoMap library</a> implements a 3D occupancy grid mapping approach. It provides data structures and mapping algorithms. The map is implemented using an \ref octomap::OcTree "Octree". It is designed to meet the following requirements: </p> <ul> <li> <b>Full 3D model.</b> The map is able to model arbitrary environments without prior assumptions about it. The representation models occupied areas as well as free space. If no information is available about an area (commonly denoted as <i>unknown areas</i>), this information is encoded as well. While the distinction between free and occupied space is essential for safe robot navigation, information about unknown areas is important, e.g., for autonomous exploration of an environment. </li> <li> <b>Updatable.</b> It is possible to add new information or sensor readings at any time. Modeling and updating is done in a <i>probabilistic</i> fashion. This accounts for sensor noise or measurements which result from dynamic changes in the environment, e.g., because of dynamic objects. Furthermore, multiple robots are able to contribute to the same map and a previously recorded map is extendable when new areas are explored. </li> <li> <b>Flexible.</b> The extent of the map does not have to be known in advance. Instead, the map is dynamically expanded as needed. The map is multi-resolution so that, for instance, a high-level planner is able to use a coarse map, while a local planner may operate using a fine resolution. This also allows for efficient visualizations which scale from coarse overviews to detailed close-up views. </li> <li> <b>Compact.</b> The is stored efficiently, both in memory and on disk. It is possible to generate compressed files for later usage or convenient exchange between robots even under bandwidth constraints. </li> </ul> <p> Octomap was developed by <a href="http://www.informatik.uni-freiburg.de/~wurm">Kai M. Wurm</a> and <a href="http://www.arminhornung.de">Armin Hornung</a>, and is currently maintained by Armin Hornung. A tracker for bug reports and feature requests is available available <a href="https://github.com/OctoMap/octomap/issues">on GitHub</a>. You can find an overview at https://octomap.github.io/ and the code repository at https://github.com/OctoMap/octomap.</p> \section install_sec Installation <p>See the file README.txt in the main folder. </p> \section changelog_sec Changelog <p>See the file CHANGELOG.txt in the main folder or the <a href="https://raw.github.com/OctoMap/octomap/master/octomap/CHANGELOG.txt">latest version online</a>. </p> \section gettingstarted_sec Getting Started <p> Jump right in and have a look at the main class \ref octomap::OcTree OcTree and the examples in src/octomap/simple_example.cpp. To integrate single measurements into the 3D map have a look at \ref octomap::OcTree::insertRay "OcTree::insertRay(...)", to insert full 3D scans (pointclouds) please have a look at \ref octomap::OcTree::insertPointCloud "OcTree::insertPointCloud(...)". Queries can be performed e.g. with \ref octomap::OcTree::search "OcTree::search(...)" or \ref octomap::OcTree::castRay "OcTree::castRay(...)". The preferred way to batch-access or process nodes in an Octree is with the iterators \ref leaf_iterator "leaf_iterator", \ref tree_iterator "tree_iterator", or \ref leaf_bbx_iterator "leaf_bbx_iterator".</p> \image html uml_overview.png <p>The \ref octomap::OcTree "OcTree" class is derived from \ref octomap::OccupancyOcTreeBase "OccupancyOcTreeBase", with most functionality in the parent class. Also derive from OccupancyOcTreeBase if you you want to implement your own Octree and node classes. You can have a look at the classes \ref octomap::OcTreeStamped "OcTreeStamped" and \ref octomap::OcTreeNodeStamped "OcTreeNodeStamped" as examples. </p> <p> Start the 3D visualization with: <b>bin/octovis</b> </p> <p> You will find an example 3D scan (please bunzip2 first) and an example OctoMap .bt file in the directory <b>share/data</b> to try. More data sets are available at http://ais.informatik.uni-freiburg.de/projects/datasets/octomap/. </p> **/
4,441
38.309735
228
h
octomap
octomap-master/octomap/include/octomap/AbstractOcTree.h
/* * OctoMap - An Efficient Probabilistic 3D Mapping Framework Based on Octrees * https://octomap.github.io/ * * Copyright (c) 2009-2013, K.M. Wurm and A. Hornung, University of Freiburg * All rights reserved. * License: New BSD * * 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 Freiburg 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. */ #ifndef OCTOMAP_ABSTRACT_OCTREE_H #define OCTOMAP_ABSTRACT_OCTREE_H #include <cstddef> #include <fstream> #include <string> #include <iostream> #include <map> namespace octomap { /** * This abstract class is an interface to all octrees and provides a * factory design pattern for readin and writing all kinds of OcTrees * to files (see read()). */ class AbstractOcTree { friend class StaticMapInit; public: AbstractOcTree(); virtual ~AbstractOcTree() {}; /// virtual constructor: creates a new object of same type virtual AbstractOcTree* create() const = 0; /// returns actual class name as string for identification virtual std::string getTreeType() const = 0; virtual double getResolution() const = 0; virtual void setResolution(double res) = 0; virtual size_t size() const = 0; virtual size_t memoryUsage() const = 0; virtual size_t memoryUsageNode() const = 0; virtual void getMetricMin(double& x, double& y, double& z) = 0; virtual void getMetricMin(double& x, double& y, double& z) const = 0; virtual void getMetricMax(double& x, double& y, double& z) = 0; virtual void getMetricMax(double& x, double& y, double& z) const = 0; virtual void getMetricSize(double& x, double& y, double& z) = 0; virtual void prune() = 0; virtual void expand() = 0; virtual void clear() = 0; //-- Iterator tree access // default iterator is leaf_iterator // class leaf_iterator; // class tree_iterator; // class leaf_bbx_iterator; // typedef leaf_iterator iterator; class iterator_base; // /// @return beginning of the tree as leaf iterator //virtual iterator_base begin(unsigned char maxDepth=0) const = 0; // /// @return end of the tree as leaf iterator // virtual const iterator end() const = 0; // /// @return beginning of the tree as leaf iterator // virtual leaf_iterator begin_leafs(unsigned char maxDepth=0) const = 0; // /// @return end of the tree as leaf iterator // virtual const leaf_iterator end_leafs() const = 0; // /// @return beginning of the tree as leaf iterator in a bounding box // virtual leaf_bbx_iterator begin_leafs_bbx(const OcTreeKey& min, const OcTreeKey& max, unsigned char maxDepth=0) const = 0; // /// @return beginning of the tree as leaf iterator in a bounding box // virtual leaf_bbx_iterator begin_leafs_bbx(const point3d& min, const point3d& max, unsigned char maxDepth=0) const = 0; // /// @return end of the tree as leaf iterator in a bounding box // virtual const leaf_bbx_iterator end_leafs_bbx() const = 0; // /// @return beginning of the tree as iterator to all nodes (incl. inner) // virtual tree_iterator begin_tree(unsigned char maxDepth=0) const = 0; // /// @return end of the tree as iterator to all nodes (incl. inner) // const tree_iterator end_tree() const = 0; /// Write file header and complete tree to file (serialization) bool write(const std::string& filename) const; /// Write file header and complete tree to stream (serialization) bool write(std::ostream& s) const; /** * Creates a certain OcTree (factory pattern) * * @param id unique ID of OcTree * @param res resolution of OcTree * @return pointer to newly created OcTree (empty). NULL if the ID is unknown! */ static AbstractOcTree* createTree(const std::string id, double res); /** * Read the file header, create the appropriate class and deserialize. * This creates a new octree which you need to delete yourself. If you * expect or requre a specific kind of octree, use dynamic_cast afterwards: * @code * AbstractOcTree* tree = AbstractOcTree::read("filename.ot"); * OcTree* octree = dynamic_cast<OcTree*>(tree); * * @endcode */ static AbstractOcTree* read(const std::string& filename); /// Read the file header, create the appropriate class and deserialize. /// This creates a new octree which you need to delete yourself. static AbstractOcTree* read(std::istream &s); /** * Read all nodes from the input stream (without file header), * for this the tree needs to be already created. * For general file IO, you * should probably use AbstractOcTree::read() instead. */ virtual std::istream& readData(std::istream &s) = 0; /// Write complete state of tree to stream (without file header) unmodified. /// Pruning the tree first produces smaller files (lossless compression) virtual std::ostream& writeData(std::ostream &s) const = 0; private: /// create private store, Construct on first use static std::map<std::string, AbstractOcTree*>& classIDMapping(); protected: static bool readHeader(std::istream &s, std::string& id, unsigned& size, double& res); static void registerTreeType(AbstractOcTree* tree); static const std::string fileHeader; }; } // end namespace #endif
6,748
39.90303
128
h
octomap
octomap-master/octomap/include/octomap/AbstractOccupancyOcTree.h
/* * OctoMap - An Efficient Probabilistic 3D Mapping Framework Based on Octrees * https://octomap.github.io/ * * Copyright (c) 2009-2013, K.M. Wurm and A. Hornung, University of Freiburg * All rights reserved. * License: New BSD * * 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 Freiburg 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. */ #ifndef OCTOMAP_ABSTRACT_OCCUPANCY_OCTREE_H #define OCTOMAP_ABSTRACT_OCCUPANCY_OCTREE_H #include "AbstractOcTree.h" #include "octomap_utils.h" #include "OcTreeNode.h" #include "OcTreeKey.h" #include <cassert> #include <fstream> namespace octomap { /** * Interface class for all octree types that store occupancy. This serves * as a common base class e.g. for polymorphism and contains common code * for reading and writing binary trees. */ class AbstractOccupancyOcTree : public AbstractOcTree { public: AbstractOccupancyOcTree(); virtual ~AbstractOccupancyOcTree() {}; //-- IO /** * Writes OcTree to a binary file using writeBinary(). * The OcTree is first converted to the maximum likelihood estimate and pruned. * @return success of operation */ bool writeBinary(const std::string& filename); /** * Writes compressed maximum likelihood OcTree to a binary stream. * The OcTree is first converted to the maximum likelihood estimate and pruned * for maximum compression. * @return success of operation */ bool writeBinary(std::ostream &s); /** * Writes OcTree to a binary file using writeBinaryConst(). * The OcTree is not changed, in particular not pruned first. * Files will be smaller when the tree is pruned first or by using * writeBinary() instead. * @return success of operation */ bool writeBinaryConst(const std::string& filename) const; /** * Writes the maximum likelihood OcTree to a binary stream (const variant). * Files will be smaller when the tree is pruned first or by using * writeBinary() instead. * @return success of operation */ bool writeBinaryConst(std::ostream &s) const; /// Writes the actual data, implemented in OccupancyOcTreeBase::writeBinaryData() virtual std::ostream& writeBinaryData(std::ostream &s) const = 0; /** * Reads an OcTree from an input stream. * Existing nodes of the tree are deleted before the tree is read. * @return success of operation */ bool readBinary(std::istream &s); /** * Reads OcTree from a binary file. * Existing nodes of the tree are deleted before the tree is read. * @return success of operation */ bool readBinary(const std::string& filename); /// Reads the actual data, implemented in OccupancyOcTreeBase::readBinaryData() virtual std::istream& readBinaryData(std::istream &s) = 0; // -- occupancy queries /// queries whether a node is occupied according to the tree's parameter for "occupancy" inline bool isNodeOccupied(const OcTreeNode* occupancyNode) const{ return (occupancyNode->getLogOdds() >= this->occ_prob_thres_log); } /// queries whether a node is occupied according to the tree's parameter for "occupancy" inline bool isNodeOccupied(const OcTreeNode& occupancyNode) const{ return (occupancyNode.getLogOdds() >= this->occ_prob_thres_log); } /// queries whether a node is at the clamping threshold according to the tree's parameter inline bool isNodeAtThreshold(const OcTreeNode* occupancyNode) const{ return (occupancyNode->getLogOdds() >= this->clamping_thres_max || occupancyNode->getLogOdds() <= this->clamping_thres_min); } /// queries whether a node is at the clamping threshold according to the tree's parameter inline bool isNodeAtThreshold(const OcTreeNode& occupancyNode) const{ return (occupancyNode.getLogOdds() >= this->clamping_thres_max || occupancyNode.getLogOdds() <= this->clamping_thres_min); } // - update functions /** * Manipulate log_odds value of voxel directly * * @param key of the NODE that is to be updated * @param log_odds_update value to be added (+) to log_odds value of node * @param lazy_eval whether update of inner nodes is omitted after the update (default: false). * This speeds up the insertion, but you need to call updateInnerOccupancy() when done. * @return pointer to the updated NODE */ virtual OcTreeNode* updateNode(const OcTreeKey& key, float log_odds_update, bool lazy_eval = false) = 0; /** * Manipulate log_odds value of voxel directly. * Looks up the OcTreeKey corresponding to the coordinate and then calls udpateNode() with it. * * @param value 3d coordinate of the NODE that is to be updated * @param log_odds_update value to be added (+) to log_odds value of node * @param lazy_eval whether update of inner nodes is omitted after the update (default: false). * This speeds up the insertion, but you need to call updateInnerOccupancy() when done. * @return pointer to the updated NODE */ virtual OcTreeNode* updateNode(const point3d& value, float log_odds_update, bool lazy_eval = false) = 0; /** * Integrate occupancy measurement. * * @param key of the NODE that is to be updated * @param occupied true if the node was measured occupied, else false * @param lazy_eval whether update of inner nodes is omitted after the update (default: false). * This speeds up the insertion, but you need to call updateInnerOccupancy() when done. * @return pointer to the updated NODE */ virtual OcTreeNode* updateNode(const OcTreeKey& key, bool occupied, bool lazy_eval = false) = 0; /** * Integrate occupancy measurement. * Looks up the OcTreeKey corresponding to the coordinate and then calls udpateNode() with it. * * @param value 3d coordinate of the NODE that is to be updated * @param occupied true if the node was measured occupied, else false * @param lazy_eval whether update of inner nodes is omitted after the update (default: false). * This speeds up the insertion, but you need to call updateInnerOccupancy() when done. * @return pointer to the updated NODE */ virtual OcTreeNode* updateNode(const point3d& value, bool occupied, bool lazy_eval = false) = 0; virtual void toMaxLikelihood() = 0; //-- parameters for occupancy and sensor model: /// sets the threshold for occupancy (sensor model) void setOccupancyThres(double prob){occ_prob_thres_log = logodds(prob); } /// sets the probability for a "hit" (will be converted to logodds) - sensor model void setProbHit(double prob){prob_hit_log = logodds(prob); assert(prob_hit_log >= 0.0);} /// sets the probability for a "miss" (will be converted to logodds) - sensor model void setProbMiss(double prob){prob_miss_log = logodds(prob); assert(prob_miss_log <= 0.0);} /// sets the minimum threshold for occupancy clamping (sensor model) void setClampingThresMin(double thresProb){clamping_thres_min = logodds(thresProb); } /// sets the maximum threshold for occupancy clamping (sensor model) void setClampingThresMax(double thresProb){clamping_thres_max = logodds(thresProb); } /// @return threshold (probability) for occupancy - sensor model double getOccupancyThres() const {return probability(occ_prob_thres_log); } /// @return threshold (logodds) for occupancy - sensor model float getOccupancyThresLog() const {return occ_prob_thres_log; } /// @return probability for a "hit" in the sensor model (probability) double getProbHit() const {return probability(prob_hit_log); } /// @return probability for a "hit" in the sensor model (logodds) float getProbHitLog() const {return prob_hit_log; } /// @return probability for a "miss" in the sensor model (probability) double getProbMiss() const {return probability(prob_miss_log); } /// @return probability for a "miss" in the sensor model (logodds) float getProbMissLog() const {return prob_miss_log; } /// @return minimum threshold for occupancy clamping in the sensor model (probability) double getClampingThresMin() const {return probability(clamping_thres_min); } /// @return minimum threshold for occupancy clamping in the sensor model (logodds) float getClampingThresMinLog() const {return clamping_thres_min; } /// @return maximum threshold for occupancy clamping in the sensor model (probability) double getClampingThresMax() const {return probability(clamping_thres_max); } /// @return maximum threshold for occupancy clamping in the sensor model (logodds) float getClampingThresMaxLog() const {return clamping_thres_max; } protected: /// Try to read the old binary format for conversion, will be removed in the future bool readBinaryLegacyHeader(std::istream &s, unsigned int& size, double& res); // occupancy parameters of tree, stored in logodds: float clamping_thres_min; float clamping_thres_max; float prob_hit_log; float prob_miss_log; float occ_prob_thres_log; static const std::string binaryFileHeader; }; } // end namespace #endif
10,721
43.305785
108
h
octomap
octomap-master/octomap/include/octomap/ColorOcTree.h
/* * OctoMap - An Efficient Probabilistic 3D Mapping Framework Based on Octrees * https://octomap.github.io/ * * Copyright (c) 2009-2013, K.M. Wurm and A. Hornung, University of Freiburg * All rights reserved. * License: New BSD * * 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 Freiburg 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. */ #ifndef OCTOMAP_COLOR_OCTREE_H #define OCTOMAP_COLOR_OCTREE_H #include <iostream> #include <octomap/OcTreeNode.h> #include <octomap/OccupancyOcTreeBase.h> namespace octomap { // forward declaraton for "friend" class ColorOcTree; // node definition class ColorOcTreeNode : public OcTreeNode { public: friend class ColorOcTree; // needs access to node children (inherited) class Color { public: Color() : r(255), g(255), b(255) {} Color(uint8_t _r, uint8_t _g, uint8_t _b) : r(_r), g(_g), b(_b) {} inline bool operator== (const Color &other) const { return (r==other.r && g==other.g && b==other.b); } inline bool operator!= (const Color &other) const { return (r!=other.r || g!=other.g || b!=other.b); } uint8_t r, g, b; }; public: ColorOcTreeNode() : OcTreeNode() {} ColorOcTreeNode(const ColorOcTreeNode& rhs) : OcTreeNode(rhs), color(rhs.color) {} bool operator==(const ColorOcTreeNode& rhs) const{ return (rhs.value == value && rhs.color == color); } void copyData(const ColorOcTreeNode& from){ OcTreeNode::copyData(from); this->color = from.getColor(); } inline Color getColor() const { return color; } inline void setColor(Color c) {this->color = c; } inline void setColor(uint8_t r, uint8_t g, uint8_t b) { this->color = Color(r,g,b); } Color& getColor() { return color; } // has any color been integrated? (pure white is very unlikely...) inline bool isColorSet() const { return ((color.r != 255) || (color.g != 255) || (color.b != 255)); } void updateColorChildren(); ColorOcTreeNode::Color getAverageChildColor() const; // file I/O std::istream& readData(std::istream &s); std::ostream& writeData(std::ostream &s) const; protected: Color color; }; // tree definition class ColorOcTree : public OccupancyOcTreeBase <ColorOcTreeNode> { public: /// Default constructor, sets resolution of leafs ColorOcTree(double resolution); /// virtual constructor: creates a new object of same type /// (Covariant return type requires an up-to-date compiler) ColorOcTree* create() const {return new ColorOcTree(resolution); } std::string getTreeType() const {return "ColorOcTree";} /** * Prunes a node when it is collapsible. This overloaded * version only considers the node occupancy for pruning, * different colors of child nodes are ignored. * @return true if pruning was successful */ virtual bool pruneNode(ColorOcTreeNode* node); virtual bool isNodeCollapsible(const ColorOcTreeNode* node) const; // set node color at given key or coordinate. Replaces previous color. ColorOcTreeNode* setNodeColor(const OcTreeKey& key, uint8_t r, uint8_t g, uint8_t b); ColorOcTreeNode* setNodeColor(float x, float y, float z, uint8_t r, uint8_t g, uint8_t b) { OcTreeKey key; if (!this->coordToKeyChecked(point3d(x,y,z), key)) return NULL; return setNodeColor(key,r,g,b); } // integrate color measurement at given key or coordinate. Average with previous color ColorOcTreeNode* averageNodeColor(const OcTreeKey& key, uint8_t r, uint8_t g, uint8_t b); ColorOcTreeNode* averageNodeColor(float x, float y, float z, uint8_t r, uint8_t g, uint8_t b) { OcTreeKey key; if (!this->coordToKeyChecked(point3d(x,y,z), key)) return NULL; return averageNodeColor(key,r,g,b); } // integrate color measurement at given key or coordinate. Average with previous color ColorOcTreeNode* integrateNodeColor(const OcTreeKey& key, uint8_t r, uint8_t g, uint8_t b); ColorOcTreeNode* integrateNodeColor(float x, float y, float z, uint8_t r, uint8_t g, uint8_t b) { OcTreeKey key; if (!this->coordToKeyChecked(point3d(x,y,z), key)) return NULL; return integrateNodeColor(key,r,g,b); } // update inner nodes, sets color to average child color void updateInnerOccupancy(); // uses gnuplot to plot a RGB histogram in EPS format void writeColorHistogram(std::string filename); protected: void updateInnerOccupancyRecurs(ColorOcTreeNode* node, unsigned int depth); /** * Static member object which ensures that this OcTree's prototype * ends up in the classIDMapping only once. You need this as a * static member in any derived octree class in order to read .ot * files through the AbstractOcTree factory. You should also call * ensureLinking() once from the constructor. */ class StaticMemberInitializer{ public: StaticMemberInitializer() { ColorOcTree* tree = new ColorOcTree(0.1); tree->clearKeyRays(); AbstractOcTree::registerTreeType(tree); } /** * Dummy function to ensure that MSVC does not drop the * StaticMemberInitializer, causing this tree failing to register. * Needs to be called from the constructor of this octree. */ void ensureLinking() {}; }; /// static member to ensure static initialization (only once) static StaticMemberInitializer colorOcTreeMemberInit; }; //! user friendly output in format (r g b) std::ostream& operator<<(std::ostream& out, ColorOcTreeNode::Color const& c); } // end namespace #endif
7,563
35.365385
90
h
octomap
octomap-master/octomap/include/octomap/CountingOcTree.h
/* * OctoMap - An Efficient Probabilistic 3D Mapping Framework Based on Octrees * https://octomap.github.io/ * * Copyright (c) 2009-2013, K.M. Wurm and A. Hornung, University of Freiburg * All rights reserved. * License: New BSD * * 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 Freiburg 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. */ #ifndef OCTOMAP_COUNTING_OCTREE_HH #define OCTOMAP_COUNTING_OCTREE_HH #include <stdio.h> #include "OcTreeBase.h" #include "OcTreeDataNode.h" namespace octomap { /** * An Octree-node which stores an internal counter per node / volume. * * Count is recursive, parent nodes have the summed count of their * children. * * \note In our mapping system this data structure is used in * CountingOcTree in the sensor model only */ class CountingOcTreeNode : public OcTreeDataNode<unsigned int> { public: CountingOcTreeNode(); ~CountingOcTreeNode(); inline unsigned int getCount() const { return getValue(); } inline void increaseCount() { value++; } inline void setCount(unsigned c) {this->setValue(c); } }; /** * An AbstractOcTree which stores an internal counter per node / volume. * * Count is recursive, parent nodes have the summed count of their * children. * * \note Was only used internally, not used anymore */ class CountingOcTree : public OcTreeBase <CountingOcTreeNode> { public: /// Default constructor, sets resolution of leafs CountingOcTree(double resolution); virtual CountingOcTreeNode* updateNode(const point3d& value); CountingOcTreeNode* updateNode(const OcTreeKey& k); void getCentersMinHits(point3d_list& node_centers, unsigned int min_hits) const; protected: void getCentersMinHitsRecurs( point3d_list& node_centers, unsigned int& min_hits, unsigned int max_depth, CountingOcTreeNode* node, unsigned int depth, const OcTreeKey& parent_key) const; /** * Static member object which ensures that this OcTree's prototype * ends up in the classIDMapping only once. You need this as a * static member in any derived octree class in order to read .ot * files through the AbstractOcTree factory. You should also call * ensureLinking() once from the constructor. */ class StaticMemberInitializer{ public: StaticMemberInitializer() { CountingOcTree* tree = new CountingOcTree(0.1); tree->clearKeyRays(); AbstractOcTree::registerTreeType(tree); } /** * Dummy function to ensure that MSVC does not drop the * StaticMemberInitializer, causing this tree failing to register. * Needs to be called from the constructor of this octree. */ void ensureLinking() {}; }; /// static member to ensure static initialization (only once) static StaticMemberInitializer countingOcTreeMemberInit; }; } #endif
4,512
35.395161
84
h
octomap
octomap-master/octomap/include/octomap/MCTables.h
/* * OctoMap - An Efficient Probabilistic 3D Mapping Framework Based on Octrees * https://octomap.github.io/ * * Copyright (c) 2013, F-M. De Rainville, P. Bourke * All rights reserved. * License: New BSD * * 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 Freiburg 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. */ #ifndef OCTOMAP_MCTABLES_H #define OCTOMAP_MCTABLES_H /** * Tables used by the Marching Cubes Algorithm * The tables are from Paul Bourke's web page * http://paulbourke.net/geometry/polygonise/ * Used with permission here under BSD license. */ namespace octomap { static const int edgeTable[256]={ 0x0 , 0x109, 0x203, 0x30a, 0x406, 0x50f, 0x605, 0x70c, 0x80c, 0x905, 0xa0f, 0xb06, 0xc0a, 0xd03, 0xe09, 0xf00, 0x190, 0x99 , 0x393, 0x29a, 0x596, 0x49f, 0x795, 0x69c, 0x99c, 0x895, 0xb9f, 0xa96, 0xd9a, 0xc93, 0xf99, 0xe90, 0x230, 0x339, 0x33 , 0x13a, 0x636, 0x73f, 0x435, 0x53c, 0xa3c, 0xb35, 0x83f, 0x936, 0xe3a, 0xf33, 0xc39, 0xd30, 0x3a0, 0x2a9, 0x1a3, 0xaa , 0x7a6, 0x6af, 0x5a5, 0x4ac, 0xbac, 0xaa5, 0x9af, 0x8a6, 0xfaa, 0xea3, 0xda9, 0xca0, 0x460, 0x569, 0x663, 0x76a, 0x66 , 0x16f, 0x265, 0x36c, 0xc6c, 0xd65, 0xe6f, 0xf66, 0x86a, 0x963, 0xa69, 0xb60, 0x5f0, 0x4f9, 0x7f3, 0x6fa, 0x1f6, 0xff , 0x3f5, 0x2fc, 0xdfc, 0xcf5, 0xfff, 0xef6, 0x9fa, 0x8f3, 0xbf9, 0xaf0, 0x650, 0x759, 0x453, 0x55a, 0x256, 0x35f, 0x55 , 0x15c, 0xe5c, 0xf55, 0xc5f, 0xd56, 0xa5a, 0xb53, 0x859, 0x950, 0x7c0, 0x6c9, 0x5c3, 0x4ca, 0x3c6, 0x2cf, 0x1c5, 0xcc , 0xfcc, 0xec5, 0xdcf, 0xcc6, 0xbca, 0xac3, 0x9c9, 0x8c0, 0x8c0, 0x9c9, 0xac3, 0xbca, 0xcc6, 0xdcf, 0xec5, 0xfcc, 0xcc , 0x1c5, 0x2cf, 0x3c6, 0x4ca, 0x5c3, 0x6c9, 0x7c0, 0x950, 0x859, 0xb53, 0xa5a, 0xd56, 0xc5f, 0xf55, 0xe5c, 0x15c, 0x55 , 0x35f, 0x256, 0x55a, 0x453, 0x759, 0x650, 0xaf0, 0xbf9, 0x8f3, 0x9fa, 0xef6, 0xfff, 0xcf5, 0xdfc, 0x2fc, 0x3f5, 0xff , 0x1f6, 0x6fa, 0x7f3, 0x4f9, 0x5f0, 0xb60, 0xa69, 0x963, 0x86a, 0xf66, 0xe6f, 0xd65, 0xc6c, 0x36c, 0x265, 0x16f, 0x66 , 0x76a, 0x663, 0x569, 0x460, 0xca0, 0xda9, 0xea3, 0xfaa, 0x8a6, 0x9af, 0xaa5, 0xbac, 0x4ac, 0x5a5, 0x6af, 0x7a6, 0xaa , 0x1a3, 0x2a9, 0x3a0, 0xd30, 0xc39, 0xf33, 0xe3a, 0x936, 0x83f, 0xb35, 0xa3c, 0x53c, 0x435, 0x73f, 0x636, 0x13a, 0x33 , 0x339, 0x230, 0xe90, 0xf99, 0xc93, 0xd9a, 0xa96, 0xb9f, 0x895, 0x99c, 0x69c, 0x795, 0x49f, 0x596, 0x29a, 0x393, 0x99 , 0x190, 0xf00, 0xe09, 0xd03, 0xc0a, 0xb06, 0xa0f, 0x905, 0x80c, 0x70c, 0x605, 0x50f, 0x406, 0x30a, 0x203, 0x109, 0x0 }; static const int triTable[256][16] = {{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 8, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 1, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {1, 8, 3, 9, 8, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {1, 2, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 8, 3, 1, 2, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {9, 2, 10, 0, 2, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {2, 8, 3, 2, 10, 8, 10, 9, 8, -1, -1, -1, -1, -1, -1, -1}, {3, 11, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 11, 2, 8, 11, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {1, 9, 0, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {1, 11, 2, 1, 9, 11, 9, 8, 11, -1, -1, -1, -1, -1, -1, -1}, {3, 10, 1, 11, 10, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 10, 1, 0, 8, 10, 8, 11, 10, -1, -1, -1, -1, -1, -1, -1}, {3, 9, 0, 3, 11, 9, 11, 10, 9, -1, -1, -1, -1, -1, -1, -1}, {9, 8, 10, 10, 8, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {4, 7, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {4, 3, 0, 7, 3, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 1, 9, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {4, 1, 9, 4, 7, 1, 7, 3, 1, -1, -1, -1, -1, -1, -1, -1}, {1, 2, 10, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {3, 4, 7, 3, 0, 4, 1, 2, 10, -1, -1, -1, -1, -1, -1, -1}, {9, 2, 10, 9, 0, 2, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1}, {2, 10, 9, 2, 9, 7, 2, 7, 3, 7, 9, 4, -1, -1, -1, -1}, {8, 4, 7, 3, 11, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {11, 4, 7, 11, 2, 4, 2, 0, 4, -1, -1, -1, -1, -1, -1, -1}, {9, 0, 1, 8, 4, 7, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1}, {4, 7, 11, 9, 4, 11, 9, 11, 2, 9, 2, 1, -1, -1, -1, -1}, {3, 10, 1, 3, 11, 10, 7, 8, 4, -1, -1, -1, -1, -1, -1, -1}, {1, 11, 10, 1, 4, 11, 1, 0, 4, 7, 11, 4, -1, -1, -1, -1}, {4, 7, 8, 9, 0, 11, 9, 11, 10, 11, 0, 3, -1, -1, -1, -1}, {4, 7, 11, 4, 11, 9, 9, 11, 10, -1, -1, -1, -1, -1, -1, -1}, {9, 5, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {9, 5, 4, 0, 8, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 5, 4, 1, 5, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {8, 5, 4, 8, 3, 5, 3, 1, 5, -1, -1, -1, -1, -1, -1, -1}, {1, 2, 10, 9, 5, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {3, 0, 8, 1, 2, 10, 4, 9, 5, -1, -1, -1, -1, -1, -1, -1}, {5, 2, 10, 5, 4, 2, 4, 0, 2, -1, -1, -1, -1, -1, -1, -1}, {2, 10, 5, 3, 2, 5, 3, 5, 4, 3, 4, 8, -1, -1, -1, -1}, {9, 5, 4, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 11, 2, 0, 8, 11, 4, 9, 5, -1, -1, -1, -1, -1, -1, -1}, {0, 5, 4, 0, 1, 5, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1}, {2, 1, 5, 2, 5, 8, 2, 8, 11, 4, 8, 5, -1, -1, -1, -1}, {10, 3, 11, 10, 1, 3, 9, 5, 4, -1, -1, -1, -1, -1, -1, -1}, {4, 9, 5, 0, 8, 1, 8, 10, 1, 8, 11, 10, -1, -1, -1, -1}, {5, 4, 0, 5, 0, 11, 5, 11, 10, 11, 0, 3, -1, -1, -1, -1}, {5, 4, 8, 5, 8, 10, 10, 8, 11, -1, -1, -1, -1, -1, -1, -1}, {9, 7, 8, 5, 7, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {9, 3, 0, 9, 5, 3, 5, 7, 3, -1, -1, -1, -1, -1, -1, -1}, {0, 7, 8, 0, 1, 7, 1, 5, 7, -1, -1, -1, -1, -1, -1, -1}, {1, 5, 3, 3, 5, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {9, 7, 8, 9, 5, 7, 10, 1, 2, -1, -1, -1, -1, -1, -1, -1}, {10, 1, 2, 9, 5, 0, 5, 3, 0, 5, 7, 3, -1, -1, -1, -1}, {8, 0, 2, 8, 2, 5, 8, 5, 7, 10, 5, 2, -1, -1, -1, -1}, {2, 10, 5, 2, 5, 3, 3, 5, 7, -1, -1, -1, -1, -1, -1, -1}, {7, 9, 5, 7, 8, 9, 3, 11, 2, -1, -1, -1, -1, -1, -1, -1}, {9, 5, 7, 9, 7, 2, 9, 2, 0, 2, 7, 11, -1, -1, -1, -1}, {2, 3, 11, 0, 1, 8, 1, 7, 8, 1, 5, 7, -1, -1, -1, -1}, {11, 2, 1, 11, 1, 7, 7, 1, 5, -1, -1, -1, -1, -1, -1, -1}, {9, 5, 8, 8, 5, 7, 10, 1, 3, 10, 3, 11, -1, -1, -1, -1}, {5, 7, 0, 5, 0, 9, 7, 11, 0, 1, 0, 10, 11, 10, 0, -1}, {11, 10, 0, 11, 0, 3, 10, 5, 0, 8, 0, 7, 5, 7, 0, -1}, {11, 10, 5, 7, 11, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {10, 6, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 8, 3, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {9, 0, 1, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {1, 8, 3, 1, 9, 8, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1}, {1, 6, 5, 2, 6, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {1, 6, 5, 1, 2, 6, 3, 0, 8, -1, -1, -1, -1, -1, -1, -1}, {9, 6, 5, 9, 0, 6, 0, 2, 6, -1, -1, -1, -1, -1, -1, -1}, {5, 9, 8, 5, 8, 2, 5, 2, 6, 3, 2, 8, -1, -1, -1, -1}, {2, 3, 11, 10, 6, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {11, 0, 8, 11, 2, 0, 10, 6, 5, -1, -1, -1, -1, -1, -1, -1}, {0, 1, 9, 2, 3, 11, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1}, {5, 10, 6, 1, 9, 2, 9, 11, 2, 9, 8, 11, -1, -1, -1, -1}, {6, 3, 11, 6, 5, 3, 5, 1, 3, -1, -1, -1, -1, -1, -1, -1}, {0, 8, 11, 0, 11, 5, 0, 5, 1, 5, 11, 6, -1, -1, -1, -1}, {3, 11, 6, 0, 3, 6, 0, 6, 5, 0, 5, 9, -1, -1, -1, -1}, {6, 5, 9, 6, 9, 11, 11, 9, 8, -1, -1, -1, -1, -1, -1, -1}, {5, 10, 6, 4, 7, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {4, 3, 0, 4, 7, 3, 6, 5, 10, -1, -1, -1, -1, -1, -1, -1}, {1, 9, 0, 5, 10, 6, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1}, {10, 6, 5, 1, 9, 7, 1, 7, 3, 7, 9, 4, -1, -1, -1, -1}, {6, 1, 2, 6, 5, 1, 4, 7, 8, -1, -1, -1, -1, -1, -1, -1}, {1, 2, 5, 5, 2, 6, 3, 0, 4, 3, 4, 7, -1, -1, -1, -1}, {8, 4, 7, 9, 0, 5, 0, 6, 5, 0, 2, 6, -1, -1, -1, -1}, {7, 3, 9, 7, 9, 4, 3, 2, 9, 5, 9, 6, 2, 6, 9, -1}, {3, 11, 2, 7, 8, 4, 10, 6, 5, -1, -1, -1, -1, -1, -1, -1}, {5, 10, 6, 4, 7, 2, 4, 2, 0, 2, 7, 11, -1, -1, -1, -1}, {0, 1, 9, 4, 7, 8, 2, 3, 11, 5, 10, 6, -1, -1, -1, -1}, {9, 2, 1, 9, 11, 2, 9, 4, 11, 7, 11, 4, 5, 10, 6, -1}, {8, 4, 7, 3, 11, 5, 3, 5, 1, 5, 11, 6, -1, -1, -1, -1}, {5, 1, 11, 5, 11, 6, 1, 0, 11, 7, 11, 4, 0, 4, 11, -1}, {0, 5, 9, 0, 6, 5, 0, 3, 6, 11, 6, 3, 8, 4, 7, -1}, {6, 5, 9, 6, 9, 11, 4, 7, 9, 7, 11, 9, -1, -1, -1, -1}, {10, 4, 9, 6, 4, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {4, 10, 6, 4, 9, 10, 0, 8, 3, -1, -1, -1, -1, -1, -1, -1}, {10, 0, 1, 10, 6, 0, 6, 4, 0, -1, -1, -1, -1, -1, -1, -1}, {8, 3, 1, 8, 1, 6, 8, 6, 4, 6, 1, 10, -1, -1, -1, -1}, {1, 4, 9, 1, 2, 4, 2, 6, 4, -1, -1, -1, -1, -1, -1, -1}, {3, 0, 8, 1, 2, 9, 2, 4, 9, 2, 6, 4, -1, -1, -1, -1}, {0, 2, 4, 4, 2, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {8, 3, 2, 8, 2, 4, 4, 2, 6, -1, -1, -1, -1, -1, -1, -1}, {10, 4, 9, 10, 6, 4, 11, 2, 3, -1, -1, -1, -1, -1, -1, -1}, {0, 8, 2, 2, 8, 11, 4, 9, 10, 4, 10, 6, -1, -1, -1, -1}, {3, 11, 2, 0, 1, 6, 0, 6, 4, 6, 1, 10, -1, -1, -1, -1}, {6, 4, 1, 6, 1, 10, 4, 8, 1, 2, 1, 11, 8, 11, 1, -1}, {9, 6, 4, 9, 3, 6, 9, 1, 3, 11, 6, 3, -1, -1, -1, -1}, {8, 11, 1, 8, 1, 0, 11, 6, 1, 9, 1, 4, 6, 4, 1, -1}, {3, 11, 6, 3, 6, 0, 0, 6, 4, -1, -1, -1, -1, -1, -1, -1}, {6, 4, 8, 11, 6, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {7, 10, 6, 7, 8, 10, 8, 9, 10, -1, -1, -1, -1, -1, -1, -1}, {0, 7, 3, 0, 10, 7, 0, 9, 10, 6, 7, 10, -1, -1, -1, -1}, {10, 6, 7, 1, 10, 7, 1, 7, 8, 1, 8, 0, -1, -1, -1, -1}, {10, 6, 7, 10, 7, 1, 1, 7, 3, -1, -1, -1, -1, -1, -1, -1}, {1, 2, 6, 1, 6, 8, 1, 8, 9, 8, 6, 7, -1, -1, -1, -1}, {2, 6, 9, 2, 9, 1, 6, 7, 9, 0, 9, 3, 7, 3, 9, -1}, {7, 8, 0, 7, 0, 6, 6, 0, 2, -1, -1, -1, -1, -1, -1, -1}, {7, 3, 2, 6, 7, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {2, 3, 11, 10, 6, 8, 10, 8, 9, 8, 6, 7, -1, -1, -1, -1}, {2, 0, 7, 2, 7, 11, 0, 9, 7, 6, 7, 10, 9, 10, 7, -1}, {1, 8, 0, 1, 7, 8, 1, 10, 7, 6, 7, 10, 2, 3, 11, -1}, {11, 2, 1, 11, 1, 7, 10, 6, 1, 6, 7, 1, -1, -1, -1, -1}, {8, 9, 6, 8, 6, 7, 9, 1, 6, 11, 6, 3, 1, 3, 6, -1}, {0, 9, 1, 11, 6, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {7, 8, 0, 7, 0, 6, 3, 11, 0, 11, 6, 0, -1, -1, -1, -1}, {7, 11, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {7, 6, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {3, 0, 8, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 1, 9, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {8, 1, 9, 8, 3, 1, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1}, {10, 1, 2, 6, 11, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {1, 2, 10, 3, 0, 8, 6, 11, 7, -1, -1, -1, -1, -1, -1, -1}, {2, 9, 0, 2, 10, 9, 6, 11, 7, -1, -1, -1, -1, -1, -1, -1}, {6, 11, 7, 2, 10, 3, 10, 8, 3, 10, 9, 8, -1, -1, -1, -1}, {7, 2, 3, 6, 2, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {7, 0, 8, 7, 6, 0, 6, 2, 0, -1, -1, -1, -1, -1, -1, -1}, {2, 7, 6, 2, 3, 7, 0, 1, 9, -1, -1, -1, -1, -1, -1, -1}, {1, 6, 2, 1, 8, 6, 1, 9, 8, 8, 7, 6, -1, -1, -1, -1}, {10, 7, 6, 10, 1, 7, 1, 3, 7, -1, -1, -1, -1, -1, -1, -1}, {10, 7, 6, 1, 7, 10, 1, 8, 7, 1, 0, 8, -1, -1, -1, -1}, {0, 3, 7, 0, 7, 10, 0, 10, 9, 6, 10, 7, -1, -1, -1, -1}, {7, 6, 10, 7, 10, 8, 8, 10, 9, -1, -1, -1, -1, -1, -1, -1}, {6, 8, 4, 11, 8, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {3, 6, 11, 3, 0, 6, 0, 4, 6, -1, -1, -1, -1, -1, -1, -1}, {8, 6, 11, 8, 4, 6, 9, 0, 1, -1, -1, -1, -1, -1, -1, -1}, {9, 4, 6, 9, 6, 3, 9, 3, 1, 11, 3, 6, -1, -1, -1, -1}, {6, 8, 4, 6, 11, 8, 2, 10, 1, -1, -1, -1, -1, -1, -1, -1}, {1, 2, 10, 3, 0, 11, 0, 6, 11, 0, 4, 6, -1, -1, -1, -1}, {4, 11, 8, 4, 6, 11, 0, 2, 9, 2, 10, 9, -1, -1, -1, -1}, {10, 9, 3, 10, 3, 2, 9, 4, 3, 11, 3, 6, 4, 6, 3, -1}, {8, 2, 3, 8, 4, 2, 4, 6, 2, -1, -1, -1, -1, -1, -1, -1}, {0, 4, 2, 4, 6, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {1, 9, 0, 2, 3, 4, 2, 4, 6, 4, 3, 8, -1, -1, -1, -1}, {1, 9, 4, 1, 4, 2, 2, 4, 6, -1, -1, -1, -1, -1, -1, -1}, {8, 1, 3, 8, 6, 1, 8, 4, 6, 6, 10, 1, -1, -1, -1, -1}, {10, 1, 0, 10, 0, 6, 6, 0, 4, -1, -1, -1, -1, -1, -1, -1}, {4, 6, 3, 4, 3, 8, 6, 10, 3, 0, 3, 9, 10, 9, 3, -1}, {10, 9, 4, 6, 10, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {4, 9, 5, 7, 6, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 8, 3, 4, 9, 5, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1}, {5, 0, 1, 5, 4, 0, 7, 6, 11, -1, -1, -1, -1, -1, -1, -1}, {11, 7, 6, 8, 3, 4, 3, 5, 4, 3, 1, 5, -1, -1, -1, -1}, {9, 5, 4, 10, 1, 2, 7, 6, 11, -1, -1, -1, -1, -1, -1, -1}, {6, 11, 7, 1, 2, 10, 0, 8, 3, 4, 9, 5, -1, -1, -1, -1}, {7, 6, 11, 5, 4, 10, 4, 2, 10, 4, 0, 2, -1, -1, -1, -1}, {3, 4, 8, 3, 5, 4, 3, 2, 5, 10, 5, 2, 11, 7, 6, -1}, {7, 2, 3, 7, 6, 2, 5, 4, 9, -1, -1, -1, -1, -1, -1, -1}, {9, 5, 4, 0, 8, 6, 0, 6, 2, 6, 8, 7, -1, -1, -1, -1}, {3, 6, 2, 3, 7, 6, 1, 5, 0, 5, 4, 0, -1, -1, -1, -1}, {6, 2, 8, 6, 8, 7, 2, 1, 8, 4, 8, 5, 1, 5, 8, -1}, {9, 5, 4, 10, 1, 6, 1, 7, 6, 1, 3, 7, -1, -1, -1, -1}, {1, 6, 10, 1, 7, 6, 1, 0, 7, 8, 7, 0, 9, 5, 4, -1}, {4, 0, 10, 4, 10, 5, 0, 3, 10, 6, 10, 7, 3, 7, 10, -1}, {7, 6, 10, 7, 10, 8, 5, 4, 10, 4, 8, 10, -1, -1, -1, -1}, {6, 9, 5, 6, 11, 9, 11, 8, 9, -1, -1, -1, -1, -1, -1, -1}, {3, 6, 11, 0, 6, 3, 0, 5, 6, 0, 9, 5, -1, -1, -1, -1}, {0, 11, 8, 0, 5, 11, 0, 1, 5, 5, 6, 11, -1, -1, -1, -1}, {6, 11, 3, 6, 3, 5, 5, 3, 1, -1, -1, -1, -1, -1, -1, -1}, {1, 2, 10, 9, 5, 11, 9, 11, 8, 11, 5, 6, -1, -1, -1, -1}, {0, 11, 3, 0, 6, 11, 0, 9, 6, 5, 6, 9, 1, 2, 10, -1}, {11, 8, 5, 11, 5, 6, 8, 0, 5, 10, 5, 2, 0, 2, 5, -1}, {6, 11, 3, 6, 3, 5, 2, 10, 3, 10, 5, 3, -1, -1, -1, -1}, {5, 8, 9, 5, 2, 8, 5, 6, 2, 3, 8, 2, -1, -1, -1, -1}, {9, 5, 6, 9, 6, 0, 0, 6, 2, -1, -1, -1, -1, -1, -1, -1}, {1, 5, 8, 1, 8, 0, 5, 6, 8, 3, 8, 2, 6, 2, 8, -1}, {1, 5, 6, 2, 1, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {1, 3, 6, 1, 6, 10, 3, 8, 6, 5, 6, 9, 8, 9, 6, -1}, {10, 1, 0, 10, 0, 6, 9, 5, 0, 5, 6, 0, -1, -1, -1, -1}, {0, 3, 8, 5, 6, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {10, 5, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {11, 5, 10, 7, 5, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {11, 5, 10, 11, 7, 5, 8, 3, 0, -1, -1, -1, -1, -1, -1, -1}, {5, 11, 7, 5, 10, 11, 1, 9, 0, -1, -1, -1, -1, -1, -1, -1}, {10, 7, 5, 10, 11, 7, 9, 8, 1, 8, 3, 1, -1, -1, -1, -1}, {11, 1, 2, 11, 7, 1, 7, 5, 1, -1, -1, -1, -1, -1, -1, -1}, {0, 8, 3, 1, 2, 7, 1, 7, 5, 7, 2, 11, -1, -1, -1, -1}, {9, 7, 5, 9, 2, 7, 9, 0, 2, 2, 11, 7, -1, -1, -1, -1}, {7, 5, 2, 7, 2, 11, 5, 9, 2, 3, 2, 8, 9, 8, 2, -1}, {2, 5, 10, 2, 3, 5, 3, 7, 5, -1, -1, -1, -1, -1, -1, -1}, {8, 2, 0, 8, 5, 2, 8, 7, 5, 10, 2, 5, -1, -1, -1, -1}, {9, 0, 1, 5, 10, 3, 5, 3, 7, 3, 10, 2, -1, -1, -1, -1}, {9, 8, 2, 9, 2, 1, 8, 7, 2, 10, 2, 5, 7, 5, 2, -1}, {1, 3, 5, 3, 7, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 8, 7, 0, 7, 1, 1, 7, 5, -1, -1, -1, -1, -1, -1, -1}, {9, 0, 3, 9, 3, 5, 5, 3, 7, -1, -1, -1, -1, -1, -1, -1}, {9, 8, 7, 5, 9, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {5, 8, 4, 5, 10, 8, 10, 11, 8, -1, -1, -1, -1, -1, -1, -1}, {5, 0, 4, 5, 11, 0, 5, 10, 11, 11, 3, 0, -1, -1, -1, -1}, {0, 1, 9, 8, 4, 10, 8, 10, 11, 10, 4, 5, -1, -1, -1, -1}, {10, 11, 4, 10, 4, 5, 11, 3, 4, 9, 4, 1, 3, 1, 4, -1}, {2, 5, 1, 2, 8, 5, 2, 11, 8, 4, 5, 8, -1, -1, -1, -1}, {0, 4, 11, 0, 11, 3, 4, 5, 11, 2, 11, 1, 5, 1, 11, -1}, {0, 2, 5, 0, 5, 9, 2, 11, 5, 4, 5, 8, 11, 8, 5, -1}, {9, 4, 5, 2, 11, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {2, 5, 10, 3, 5, 2, 3, 4, 5, 3, 8, 4, -1, -1, -1, -1}, {5, 10, 2, 5, 2, 4, 4, 2, 0, -1, -1, -1, -1, -1, -1, -1}, {3, 10, 2, 3, 5, 10, 3, 8, 5, 4, 5, 8, 0, 1, 9, -1}, {5, 10, 2, 5, 2, 4, 1, 9, 2, 9, 4, 2, -1, -1, -1, -1}, {8, 4, 5, 8, 5, 3, 3, 5, 1, -1, -1, -1, -1, -1, -1, -1}, {0, 4, 5, 1, 0, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {8, 4, 5, 8, 5, 3, 9, 0, 5, 0, 3, 5, -1, -1, -1, -1}, {9, 4, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {4, 11, 7, 4, 9, 11, 9, 10, 11, -1, -1, -1, -1, -1, -1, -1}, {0, 8, 3, 4, 9, 7, 9, 11, 7, 9, 10, 11, -1, -1, -1, -1}, {1, 10, 11, 1, 11, 4, 1, 4, 0, 7, 4, 11, -1, -1, -1, -1}, {3, 1, 4, 3, 4, 8, 1, 10, 4, 7, 4, 11, 10, 11, 4, -1}, {4, 11, 7, 9, 11, 4, 9, 2, 11, 9, 1, 2, -1, -1, -1, -1}, {9, 7, 4, 9, 11, 7, 9, 1, 11, 2, 11, 1, 0, 8, 3, -1}, {11, 7, 4, 11, 4, 2, 2, 4, 0, -1, -1, -1, -1, -1, -1, -1}, {11, 7, 4, 11, 4, 2, 8, 3, 4, 3, 2, 4, -1, -1, -1, -1}, {2, 9, 10, 2, 7, 9, 2, 3, 7, 7, 4, 9, -1, -1, -1, -1}, {9, 10, 7, 9, 7, 4, 10, 2, 7, 8, 7, 0, 2, 0, 7, -1}, {3, 7, 10, 3, 10, 2, 7, 4, 10, 1, 10, 0, 4, 0, 10, -1}, {1, 10, 2, 8, 7, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {4, 9, 1, 4, 1, 7, 7, 1, 3, -1, -1, -1, -1, -1, -1, -1}, {4, 9, 1, 4, 1, 7, 0, 8, 1, 8, 7, 1, -1, -1, -1, -1}, {4, 0, 3, 7, 4, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {4, 8, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {9, 10, 8, 10, 11, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {3, 0, 9, 3, 9, 11, 11, 9, 10, -1, -1, -1, -1, -1, -1, -1}, {0, 1, 10, 0, 10, 8, 8, 10, 11, -1, -1, -1, -1, -1, -1, -1}, {3, 1, 10, 11, 3, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {1, 2, 11, 1, 11, 9, 9, 11, 8, -1, -1, -1, -1, -1, -1, -1}, {3, 0, 9, 3, 9, 11, 1, 2, 9, 2, 11, 9, -1, -1, -1, -1}, {0, 2, 11, 8, 0, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {3, 2, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {2, 3, 8, 2, 8, 10, 10, 8, 9, -1, -1, -1, -1, -1, -1, -1}, {9, 10, 2, 0, 9, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {2, 3, 8, 2, 8, 10, 0, 1, 8, 1, 10, 8, -1, -1, -1, -1}, {1, 10, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {1, 3, 8, 9, 1, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 9, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 3, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}}; static const point3d vertexList[12] = { point3d(1, 0, -1), point3d(0, -1, -1), point3d(-1, 0, -1), point3d(0, 1, -1), point3d(1, 0, 1), point3d(0, -1, 1), point3d(-1, 0, 1), point3d(0, 1, 1), point3d(1, 1, 0), point3d(1, -1, 0), point3d(-1, -1, 0), point3d(-1, 1, 0), }; } #endif
19,345
53.342697
78
h
octomap
octomap-master/octomap/include/octomap/MapCollection.h
/* * OctoMap - An Efficient Probabilistic 3D Mapping Framework Based on Octrees * https://octomap.github.io/ * * Copyright (c) 2009-2013, K.M. Wurm and A. Hornung, University of Freiburg * All rights reserved. * License: New BSD * * 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 Freiburg 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. */ #ifndef OCTOMAP_MAP_COLLECTION_H #define OCTOMAP_MAP_COLLECTION_H #include <vector> #include <octomap/MapNode.h> namespace octomap { template <class MAPNODE> class MapCollection { public: MapCollection(); MapCollection(std::string filename); ~MapCollection(); void addNode( MAPNODE* node); MAPNODE* addNode(const Pointcloud& cloud, point3d sensor_origin); bool removeNode(const MAPNODE* n); MAPNODE* queryNode(const point3d& p); bool isOccupied(const point3d& p) const; bool isOccupied(float x, float y, float z) const; double getOccupancy(const point3d& p); bool castRay(const point3d& origin, const point3d& direction, point3d& end, bool ignoreUnknownCells=false, double maxRange=-1.0) const; bool writePointcloud(std::string filename); bool write(std::string filename); // TODO void insertScan(const Pointcloud& scan, const octomap::point3d& sensor_origin, double maxrange=-1., bool pruning=true, bool lazy_eval = false); // TODO MAPNODE* queryNode(std::string id); typedef typename std::vector<MAPNODE*>::iterator iterator; typedef typename std::vector<MAPNODE*>::const_iterator const_iterator; iterator begin() { return nodes.begin(); } iterator end() { return nodes.end(); } const_iterator begin() const { return nodes.begin(); } const_iterator end() const { return nodes.end(); } size_t size() const { return nodes.size(); } protected: void clear(); bool read(std::string filename); // TODO std::vector<Pointcloud*> segment(const Pointcloud& scan) const; // TODO MAPNODE* associate(const Pointcloud& scan); static void splitPathAndFilename(std::string &filenamefullpath, std::string* path, std::string *filename); static std::string combinePathAndFilename(std::string path, std::string filename); static bool readTagValue(std::string tag, std::ifstream &infile, std::string* value); protected: std::vector<MAPNODE*> nodes; }; } // end namespace #include "octomap/MapCollection.hxx" #endif
3,897
36.480769
110
h
octomap
octomap-master/octomap/include/octomap/MapCollection.hxx
/* * OctoMap - An Efficient Probabilistic 3D Mapping Framework Based on Octrees * https://octomap.github.io/ * * Copyright (c) 2009-2013, K.M. Wurm and A. Hornung, University of Freiburg * All rights reserved. * License: New BSD * * 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 Freiburg 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. */ #include <stdio.h> #include <sstream> #include <fstream> namespace octomap { template <class MAPNODE> MapCollection<MAPNODE>::MapCollection() { } template <class MAPNODE> MapCollection<MAPNODE>::MapCollection(std::string filename) { this->read(filename); } template <class MAPNODE> MapCollection<MAPNODE>::~MapCollection() { this->clear(); } template <class MAPNODE> void MapCollection<MAPNODE>::clear() { // FIXME: memory leak, else we run into double frees in, e.g., the viewer... // for(typename std::vector<MAPNODE*>::iterator it= nodes.begin(); it != nodes.end(); ++it) // delete *it; nodes.clear(); } template <class MAPNODE> bool MapCollection<MAPNODE>::read(std::string filenamefullpath) { std::string path; std::string filename; splitPathAndFilename(filenamefullpath, &path, &filename); std::ifstream infile; infile.open(filenamefullpath.c_str(), std::ifstream::in); if(!infile.is_open()){ OCTOMAP_ERROR_STR("Could not open "<< filenamefullpath << ". MapCollection not loaded."); return false; } bool ok = true; while(ok){ std::string nodeID; ok = readTagValue("MAPNODEID", infile, &nodeID); if(!ok){ //do not throw error, you could be at the end of the file break; } std::string mapNodeFilename; ok = readTagValue("MAPNODEFILENAME", infile, &mapNodeFilename); if(!ok){ OCTOMAP_ERROR_STR("Could not read MAPNODEFILENAME."); break; } std::string poseStr; ok = readTagValue("MAPNODEPOSE", infile, &poseStr); std::istringstream poseStream(poseStr); float x,y,z; poseStream >> x >> y >> z; double roll,pitch,yaw; poseStream >> roll >> pitch >> yaw; ok = ok && !poseStream.fail(); if(!ok){ OCTOMAP_ERROR_STR("Could not read MAPNODEPOSE."); break; } octomap::pose6d origin(x, y, z, roll, pitch, yaw); MAPNODE* node = new MAPNODE(combinePathAndFilename(path,mapNodeFilename), origin); node->setId(nodeID); if(!ok){ for(unsigned int i=0; i<nodes.size(); i++){ delete nodes[i]; } infile.close(); return false; } else { nodes.push_back(node); } } infile.close(); return true; } template <class MAPNODE> void MapCollection<MAPNODE>::addNode( MAPNODE* node){ nodes.push_back(node); } template <class MAPNODE> MAPNODE* MapCollection<MAPNODE>::addNode(const Pointcloud& cloud, point3d sensor_origin) { // TODO... return 0; } template <class MAPNODE> bool MapCollection<MAPNODE>::removeNode(const MAPNODE* n) { // TODO... return false; } template <class MAPNODE> MAPNODE* MapCollection<MAPNODE>::queryNode(const point3d& p) { for (const_iterator it = this->begin(); it != this->end(); ++it) { point3d ptrans = (*it)->getOrigin().inv().transform(p); typename MAPNODE::TreeType::NodeType* n = (*it)->getMap()->search(ptrans); if (!n) continue; if ((*it)->getMap()->isNodeOccupied(n)) return (*it); } return 0; } template <class MAPNODE> bool MapCollection<MAPNODE>::isOccupied(const point3d& p) const { for (const_iterator it = this->begin(); it != this->end(); ++it) { point3d ptrans = (*it)->getOrigin().inv().transform(p); typename MAPNODE::TreeType::NodeType* n = (*it)->getMap()->search(ptrans); if (!n) continue; if ((*it)->getMap()->isNodeOccupied(n)) return true; } return false; } template <class MAPNODE> bool MapCollection<MAPNODE>::isOccupied(float x, float y, float z) const { point3d q(x,y,z); return this->isOccupied(q); } template <class MAPNODE> double MapCollection<MAPNODE>::getOccupancy(const point3d& p) { double max_occ_val = 0; bool is_unknown = true; for (const_iterator it = this->begin(); it != this->end(); ++it) { point3d ptrans = (*it)->getOrigin().inv().transform(p); typename MAPNODE::TreeType::NodeType* n = (*it)->getMap()->search(ptrans); if (n) { double occ = n->getOccupancy(); if (occ > max_occ_val) max_occ_val = occ; is_unknown = false; } } if (is_unknown) return 0.5; return max_occ_val; } template <class MAPNODE> bool MapCollection<MAPNODE>::castRay(const point3d& origin, const point3d& direction, point3d& end, bool ignoreUnknownCells, double maxRange) const { bool hit_obstacle = false; double min_dist = 1e6; // SPEEDUP: use openMP to do raycasting in parallel // SPEEDUP: use bounding boxes to determine submaps for (const_iterator it = this->begin(); it != this->end(); ++it) { point3d origin_trans = (*it)->getOrigin().inv().transform(origin); point3d direction_trans = (*it)->getOrigin().inv().rot().rotate(direction); printf("ray from %.2f,%.2f,%.2f in dir %.2f,%.2f,%.2f in node %s\n", origin_trans.x(), origin_trans.y(), origin_trans.z(), direction_trans.x(), direction_trans.y(), direction_trans.z(), (*it)->getId().c_str()); point3d temp_endpoint; if ((*it)->getMap()->castRay(origin_trans, direction_trans, temp_endpoint, ignoreUnknownCells, maxRange)) { printf("hit obstacle in node %s\n", (*it)->getId().c_str()); double current_dist = origin_trans.distance(temp_endpoint); if (current_dist < min_dist) { min_dist = current_dist; end = (*it)->getOrigin().transform(temp_endpoint); } hit_obstacle = true; } // end if hit obst } // end for return hit_obstacle; } template <class MAPNODE> bool MapCollection<MAPNODE>::writePointcloud(std::string filename) { Pointcloud pc; for(typename std::vector<MAPNODE* >::iterator it = nodes.begin(); it != nodes.end(); ++it){ Pointcloud tmp = (*it)->generatePointcloud(); pc.push_back(tmp); } pc.writeVrml(filename); return true; } template <class MAPNODE> bool MapCollection<MAPNODE>::write(std::string filename) { bool ok = true; std::ofstream outfile(filename.c_str()); outfile << "#This file was generated by the write-method of MapCollection\n"; for(typename std::vector<MAPNODE* >::iterator it = nodes.begin(); it != nodes.end(); ++it){ std::string id = (*it)->getId(); pose6d origin = (*it)->getOrigin(); std::string nodemapFilename = "nodemap_"; nodemapFilename.append(id); nodemapFilename.append(".bt"); outfile << "MAPNODEID " << id << "\n"; outfile << "MAPNODEFILENAME "<< nodemapFilename << "\n"; outfile << "MAPNODEPOSE " << origin.x() << " " << origin.y() << " " << origin.z() << " " << origin.roll() << " " << origin.pitch() << " " << origin.yaw() << std::endl; ok = ok && (*it)->writeMap(nodemapFilename); } outfile.close(); return ok; } // TODO template <class MAPNODE> void MapCollection<MAPNODE>::insertScan(const Pointcloud& scan, const octomap::point3d& sensor_origin, double maxrange, bool pruning, bool lazy_eval) { fprintf(stderr, "ERROR: MapCollection::insertScan is not implemented yet.\n"); } template <class MAPNODE> MAPNODE* MapCollection<MAPNODE>::queryNode(std::string id) { for (const_iterator it = this->begin(); it != this->end(); ++it) { if ((*it)->getId() == id) return *(it); } return 0; } // TODO template <class MAPNODE> std::vector<Pointcloud*> MapCollection<MAPNODE>::segment(const Pointcloud& scan) const { std::vector<Pointcloud*> result; fprintf(stderr, "ERROR: MapCollection::segment is not implemented yet.\n"); return result; } // TODO template <class MAPNODE> MAPNODE* MapCollection<MAPNODE>::associate(const Pointcloud& scan) { fprintf(stderr, "ERROR: MapCollection::associate is not implemented yet.\n"); return 0; } template <class MAPNODE> void MapCollection<MAPNODE>::splitPathAndFilename(std::string &filenamefullpath, std::string* path, std::string *filename) { #ifdef WIN32 std::string::size_type lastSlash = filenamefullpath.find_last_of('\\'); #else std::string::size_type lastSlash = filenamefullpath.find_last_of('/'); #endif if (lastSlash != std::string::npos){ *filename = filenamefullpath.substr(lastSlash + 1); *path = filenamefullpath.substr(0, lastSlash); } else { *filename = filenamefullpath; *path = ""; } } template <class MAPNODE> std::string MapCollection<MAPNODE>::combinePathAndFilename(std::string path, std::string filename) { std::string result = path; if(path != ""){ #ifdef WIN32 result.append("\\"); #else result.append("/"); #endif } result.append(filename); return result; } template <class MAPNODE> bool MapCollection<MAPNODE>::readTagValue(std::string /*tag*/, std::ifstream& infile, std::string* value) { std::string line; while( getline(infile, line) ){ if(line.length() != 0 && line[0] != '#') break; } *value = ""; std::string::size_type firstSpace = line.find(' '); if(firstSpace != std::string::npos && firstSpace != line.size()-1){ *value = line.substr(firstSpace + 1); return true; } else return false; } } // namespace
11,272
33.057402
113
hxx
octomap
octomap-master/octomap/include/octomap/MapNode.h
/* * OctoMap - An Efficient Probabilistic 3D Mapping Framework Based on Octrees * https://octomap.github.io/ * * Copyright (c) 2009-2013, K.M. Wurm and A. Hornung, University of Freiburg * All rights reserved. * License: New BSD * * 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 Freiburg 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. */ #ifndef OCTOMAP_MAP_NODE_H #define OCTOMAP_MAP_NODE_H #include <string> #include <octomap/OcTree.h> namespace octomap { template <class TREETYPE> class MapNode { public: MapNode(); MapNode(TREETYPE* node_map, pose6d origin); MapNode(std::string filename, pose6d origin); MapNode(const Pointcloud& cloud, pose6d origin); ~MapNode(); typedef TREETYPE TreeType; TREETYPE* getMap() { return node_map; } void updateMap(const Pointcloud& cloud, point3d sensor_origin); inline std::string getId() { return id; } inline void setId(std::string newid) { id = newid; } inline pose6d getOrigin() { return origin; } // returns cloud of voxel centers in global reference frame Pointcloud generatePointcloud(); bool writeMap(std::string filename); protected: TREETYPE* node_map; // occupancy grid map pose6d origin; // origin and orientation relative to parent std::string id; void clear(); bool readMap(std::string filename); }; } // end namespace #include "octomap/MapNode.hxx" #endif
2,880
33.710843
78
h
octomap
octomap-master/octomap/include/octomap/MapNode.hxx
/* * OctoMap - An Efficient Probabilistic 3D Mapping Framework Based on Octrees * https://octomap.github.io/ * * Copyright (c) 2009-2013, K.M. Wurm and A. Hornung, University of Freiburg * All rights reserved. * License: New BSD * * 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 Freiburg 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. */ namespace octomap { template <class TREETYPE> MapNode<TREETYPE>::MapNode(): node_map(0) { } template <class TREETYPE> MapNode<TREETYPE>::MapNode(TREETYPE* in_node_map, pose6d in_origin) { this->node_map = in_node_map; this->origin = in_origin; } template <class TREETYPE> MapNode<TREETYPE>::MapNode(const Pointcloud& in_cloud, pose6d in_origin): node_map(0) { } template <class TREETYPE> MapNode<TREETYPE>::MapNode(std::string filename, pose6d in_origin): node_map(0){ readMap(filename); this->origin = in_origin; id = filename; } template <class TREETYPE> MapNode<TREETYPE>::~MapNode() { clear(); } template <class TREETYPE> void MapNode<TREETYPE>::updateMap(const Pointcloud& cloud, point3d sensor_origin) { } template <class TREETYPE> Pointcloud MapNode<TREETYPE>::generatePointcloud() { Pointcloud pc; point3d_list occs; node_map->getOccupied(occs); for(point3d_list::iterator it = occs.begin(); it != occs.end(); ++it){ pc.push_back(*it); } return pc; } template <class TREETYPE> void MapNode<TREETYPE>::clear(){ if(node_map != 0){ delete node_map; node_map = 0; id = ""; origin = pose6d(0.0,0.0,0.0,0.0,0.0,0.0); } } template <class TREETYPE> bool MapNode<TREETYPE>::readMap(std::string filename){ if(node_map != 0) delete node_map; node_map = new TREETYPE(0.05); return node_map->readBinary(filename); } template <class TREETYPE> bool MapNode<TREETYPE>::writeMap(std::string filename){ return node_map->writeBinary(filename); } } // namespace
3,389
32.235294
89
hxx
octomap
octomap-master/octomap/include/octomap/OcTree.h
/* * OctoMap - An Efficient Probabilistic 3D Mapping Framework Based on Octrees * https://octomap.github.io/ * * Copyright (c) 2009-2013, K.M. Wurm and A. Hornung, University of Freiburg * All rights reserved. * License: New BSD * * 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 Freiburg 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. */ #ifndef OCTOMAP_OCTREE_H #define OCTOMAP_OCTREE_H #include "OccupancyOcTreeBase.h" #include "OcTreeNode.h" #include "ScanGraph.h" namespace octomap { /** * octomap main map data structure, stores 3D occupancy grid map in an OcTree. * Basic functionality is implemented in OcTreeBase. * */ class OcTree : public OccupancyOcTreeBase <OcTreeNode> { public: /// Default constructor, sets resolution of leafs OcTree(double resolution); /** * Reads an OcTree from a binary file * @param _filename * */ OcTree(std::string _filename); virtual ~OcTree(){}; /// virtual constructor: creates a new object of same type /// (Covariant return type requires an up-to-date compiler) OcTree* create() const {return new OcTree(resolution); } std::string getTreeType() const {return "OcTree";} protected: /** * Static member object which ensures that this OcTree's prototype * ends up in the classIDMapping only once. You need this as a * static member in any derived octree class in order to read .ot * files through the AbstractOcTree factory. You should also call * ensureLinking() once from the constructor. */ class StaticMemberInitializer{ public: StaticMemberInitializer() { OcTree* tree = new OcTree(0.1); tree->clearKeyRays(); AbstractOcTree::registerTreeType(tree); } /** * Dummy function to ensure that MSVC does not drop the * StaticMemberInitializer, causing this tree failing to register. * Needs to be called from the constructor of this octree. */ void ensureLinking() {}; }; /// to ensure static initialization (only once) static StaticMemberInitializer ocTreeMemberInit; }; } // end namespace #endif
3,597
34.27451
80
h
octomap
octomap-master/octomap/include/octomap/OcTreeBase.h
/* * OctoMap - An Efficient Probabilistic 3D Mapping Framework Based on Octrees * https://octomap.github.io/ * * Copyright (c) 2009-2013, K.M. Wurm and A. Hornung, University of Freiburg * All rights reserved. * License: New BSD * * 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 Freiburg 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. */ #ifndef OCTOMAP_OCTREE_BASE_H #define OCTOMAP_OCTREE_BASE_H #include "OcTreeBaseImpl.h" #include "AbstractOcTree.h" namespace octomap { template <class NODE> class OcTreeBase : public OcTreeBaseImpl<NODE,AbstractOcTree> { public: OcTreeBase<NODE>(double res) : OcTreeBaseImpl<NODE,AbstractOcTree>(res) {}; /// virtual constructor: creates a new object of same type /// (Covariant return type requires an up-to-date compiler) OcTreeBase<NODE>* create() const {return new OcTreeBase<NODE>(this->resolution); } std::string getTreeType() const {return "OcTreeBase";} }; } #endif
2,391
40.241379
86
h
octomap
octomap-master/octomap/include/octomap/OcTreeBaseImpl.h
/* * OctoMap - An Efficient Probabilistic 3D Mapping Framework Based on Octrees * https://octomap.github.io/ * * Copyright (c) 2009-2013, K.M. Wurm and A. Hornung, University of Freiburg * All rights reserved. * License: New BSD * * 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 Freiburg 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. */ #ifndef OCTOMAP_OCTREE_BASE_IMPL_H #define OCTOMAP_OCTREE_BASE_IMPL_H #include <list> #include <limits> #include <iterator> #include <stack> #include <bitset> #include "octomap_types.h" #include "OcTreeKey.h" #include "ScanGraph.h" namespace octomap { // forward declaration for NODE children array class AbstractOcTreeNode; /** * OcTree base class, to be used with with any kind of OcTreeDataNode. * * This tree implementation currently has a maximum depth of 16 * nodes. For this reason, coordinates values have to be, e.g., * below +/- 327.68 meters (2^15) at a maximum resolution of 0.01m. * * This limitation enables the use of an efficient key generation * method which uses the binary representation of the data point * coordinates. * * \note You should probably not use this class directly, but * OcTreeBase or OccupancyOcTreeBase instead * * \tparam NODE Node class to be used in tree (usually derived from * OcTreeDataNode) * \tparam INTERFACE Interface to be derived from, should be either * AbstractOcTree or AbstractOccupancyOcTree */ template <class NODE,class INTERFACE> class OcTreeBaseImpl : public INTERFACE { public: /// Make the templated NODE type available from the outside typedef NODE NodeType; // the actual iterator implementation is included here // as a member from this file #include <octomap/OcTreeIterator.hxx> OcTreeBaseImpl(double resolution); virtual ~OcTreeBaseImpl(); /// Deep copy constructor OcTreeBaseImpl(const OcTreeBaseImpl<NODE,INTERFACE>& rhs); /** * Swap contents of two octrees, i.e., only the underlying * pointer / tree structure. You have to ensure yourself that the * metadata (resolution etc) matches. No memory is cleared * in this function */ void swapContent(OcTreeBaseImpl<NODE,INTERFACE>& rhs); /// Comparison between two octrees, all meta data, all /// nodes, and the structure must be identical bool operator== (const OcTreeBaseImpl<NODE,INTERFACE>& rhs) const; std::string getTreeType() const {return "OcTreeBaseImpl";} /// Change the resolution of the octree, scaling all voxels. /// This will not preserve the (metric) scale! void setResolution(double r); inline double getResolution() const { return resolution; } inline unsigned int getTreeDepth () const { return tree_depth; } inline double getNodeSize(unsigned depth) const {assert(depth <= tree_depth); return sizeLookupTable[depth];} /** * Clear KeyRay vector to minimize unneeded memory. This is only * useful for the StaticMemberInitializer classes, don't call it for * an octree that is actually used. */ void clearKeyRays(){ keyrays.clear(); } // -- Tree structure operations formerly contained in the nodes --- /// Creates (allocates) the i-th child of the node. @return ptr to newly create NODE NODE* createNodeChild(NODE* node, unsigned int childIdx); /// Deletes the i-th child of the node void deleteNodeChild(NODE* node, unsigned int childIdx); /// @return ptr to child number childIdx of node NODE* getNodeChild(NODE* node, unsigned int childIdx) const; /// @return const ptr to child number childIdx of node const NODE* getNodeChild(const NODE* node, unsigned int childIdx) const; /// A node is collapsible if all children exist, don't have children of their own /// and have the same occupancy value virtual bool isNodeCollapsible(const NODE* node) const; /** * Safe test if node has a child at index childIdx. * First tests if there are any children. Replaces node->childExists(...) * \return true if the child at childIdx exists */ bool nodeChildExists(const NODE* node, unsigned int childIdx) const; /** * Safe test if node has any children. Replaces node->hasChildren(...) * \return true if node has at least one child */ bool nodeHasChildren(const NODE* node) const; /** * Expands a node (reverse of pruning): All children are created and * their occupancy probability is set to the node's value. * * You need to verify that this is indeed a pruned node (i.e. not a * leaf at the lowest level) * */ virtual void expandNode(NODE* node); /** * Prunes a node when it is collapsible * @return true if pruning was successful */ virtual bool pruneNode(NODE* node); // -------- /** * \return Pointer to the root node of the tree. This pointer * should not be modified or deleted externally, the OcTree * manages its memory itself. In an empty tree, root is NULL. */ inline NODE* getRoot() const { return root; } /** * Search node at specified depth given a 3d point (depth=0: search full tree depth). * You need to check if the returned node is NULL, since it can be in unknown space. * @return pointer to node if found, NULL otherwise */ NODE* search(double x, double y, double z, unsigned int depth = 0) const; /** * Search node at specified depth given a 3d point (depth=0: search full tree depth) * You need to check if the returned node is NULL, since it can be in unknown space. * @return pointer to node if found, NULL otherwise */ NODE* search(const point3d& value, unsigned int depth = 0) const; /** * Search a node at specified depth given an addressing key (depth=0: search full tree depth) * You need to check if the returned node is NULL, since it can be in unknown space. * @return pointer to node if found, NULL otherwise */ NODE* search(const OcTreeKey& key, unsigned int depth = 0) const; /** * Delete a node (if exists) given a 3d point. Will always * delete at the lowest level unless depth !=0, and expand pruned inner nodes as needed. * Pruned nodes at level "depth" will directly be deleted as a whole. */ bool deleteNode(double x, double y, double z, unsigned int depth = 0); /** * Delete a node (if exists) given a 3d point. Will always * delete at the lowest level unless depth !=0, and expand pruned inner nodes as needed. * Pruned nodes at level "depth" will directly be deleted as a whole. */ bool deleteNode(const point3d& value, unsigned int depth = 0); /** * Delete a node (if exists) given an addressing key. Will always * delete at the lowest level unless depth !=0, and expand pruned inner nodes as needed. * Pruned nodes at level "depth" will directly be deleted as a whole. */ bool deleteNode(const OcTreeKey& key, unsigned int depth = 0); /// Deletes the complete tree structure void clear(); /** * Lossless compression of the octree: A node will replace all of its eight * children if they have identical values. You usually don't have to call * prune() after a regular occupancy update, updateNode() incrementally * prunes all affected nodes. */ virtual void prune(); /// Expands all pruned nodes (reverse of prune()) /// \note This is an expensive operation, especially when the tree is nearly empty! virtual void expand(); // -- statistics ---------------------- /// \return The number of nodes in the tree virtual inline size_t size() const { return tree_size; } /// \return Memory usage of the complete octree in bytes (may vary between architectures) virtual size_t memoryUsage() const; /// \return Memory usage of a single octree node virtual inline size_t memoryUsageNode() const {return sizeof(NODE); }; /// \return Memory usage of a full grid of the same size as the OcTree in bytes (for comparison) /// \note this can be larger than the adressable memory - size_t may not be enough to hold it! unsigned long long memoryFullGrid() const; double volume(); /// Size of OcTree (all known space) in meters for x, y and z dimension virtual void getMetricSize(double& x, double& y, double& z); /// Size of OcTree (all known space) in meters for x, y and z dimension virtual void getMetricSize(double& x, double& y, double& z) const; /// minimum value of the bounding box of all known space in x, y, z virtual void getMetricMin(double& x, double& y, double& z); /// minimum value of the bounding box of all known space in x, y, z void getMetricMin(double& x, double& y, double& z) const; /// maximum value of the bounding box of all known space in x, y, z virtual void getMetricMax(double& x, double& y, double& z); /// maximum value of the bounding box of all known space in x, y, z void getMetricMax(double& x, double& y, double& z) const; /// Traverses the tree to calculate the total number of nodes size_t calcNumNodes() const; /// Traverses the tree to calculate the total number of leaf nodes size_t getNumLeafNodes() const; // -- access tree nodes ------------------ /// return centers of leafs that do NOT exist (but could) in a given bounding box void getUnknownLeafCenters(point3d_list& node_centers, point3d pmin, point3d pmax, unsigned int depth = 0) const; // -- raytracing ----------------------- /** * Traces a ray from origin to end (excluding), returning an * OcTreeKey of all nodes traversed by the beam. You still need to check * if a node at that coordinate exists (e.g. with search()). * * @param origin start coordinate of ray * @param end end coordinate of ray * @param ray KeyRay structure that holds the keys of all nodes traversed by the ray, excluding "end" * @return Success of operation. Returning false usually means that one of the coordinates is out of the OcTree's range */ bool computeRayKeys(const point3d& origin, const point3d& end, KeyRay& ray) const; /** * Traces a ray from origin to end (excluding), returning the * coordinates of all nodes traversed by the beam. You still need to check * if a node at that coordinate exists (e.g. with search()). * @note: use the faster computeRayKeys method if possible. * * @param origin start coordinate of ray * @param end end coordinate of ray * @param ray KeyRay structure that holds the keys of all nodes traversed by the ray, excluding "end" * @return Success of operation. Returning false usually means that one of the coordinates is out of the OcTree's range */ bool computeRay(const point3d& origin, const point3d& end, std::vector<point3d>& ray); // file IO /** * Read all nodes from the input stream (without file header), * for this the tree needs to be already created. * For general file IO, you * should probably use AbstractOcTree::read() instead. */ std::istream& readData(std::istream &s); /// Write complete state of tree to stream (without file header) unmodified. /// Pruning the tree first produces smaller files (lossless compression) std::ostream& writeData(std::ostream &s) const; typedef leaf_iterator iterator; /// @return beginning of the tree as leaf iterator iterator begin(unsigned char maxDepth=0) const {return iterator(this, maxDepth);}; /// @return end of the tree as leaf iterator const iterator end() const {return leaf_iterator_end;}; // TODO: RVE? /// @return beginning of the tree as leaf iterator leaf_iterator begin_leafs(unsigned char maxDepth=0) const {return leaf_iterator(this, maxDepth);}; /// @return end of the tree as leaf iterator const leaf_iterator end_leafs() const {return leaf_iterator_end;} /// @return beginning of the tree as leaf iterator in a bounding box leaf_bbx_iterator begin_leafs_bbx(const OcTreeKey& min, const OcTreeKey& max, unsigned char maxDepth=0) const { return leaf_bbx_iterator(this, min, max, maxDepth); } /// @return beginning of the tree as leaf iterator in a bounding box leaf_bbx_iterator begin_leafs_bbx(const point3d& min, const point3d& max, unsigned char maxDepth=0) const { return leaf_bbx_iterator(this, min, max, maxDepth); } /// @return end of the tree as leaf iterator in a bounding box const leaf_bbx_iterator end_leafs_bbx() const {return leaf_iterator_bbx_end;} /// @return beginning of the tree as iterator to all nodes (incl. inner) tree_iterator begin_tree(unsigned char maxDepth=0) const {return tree_iterator(this, maxDepth);} /// @return end of the tree as iterator to all nodes (incl. inner) const tree_iterator end_tree() const {return tree_iterator_end;} // // Key / coordinate conversion functions // /// Converts from a single coordinate into a discrete key inline key_type coordToKey(double coordinate) const{ return ((int) floor(resolution_factor * coordinate)) + tree_max_val; } /// Converts from a single coordinate into a discrete key at a given depth key_type coordToKey(double coordinate, unsigned depth) const; /// Converts from a 3D coordinate into a 3D addressing key inline OcTreeKey coordToKey(const point3d& coord) const{ return OcTreeKey(coordToKey(coord(0)), coordToKey(coord(1)), coordToKey(coord(2))); } /// Converts from a 3D coordinate into a 3D addressing key inline OcTreeKey coordToKey(double x, double y, double z) const{ return OcTreeKey(coordToKey(x), coordToKey(y), coordToKey(z)); } /// Converts from a 3D coordinate into a 3D addressing key at a given depth inline OcTreeKey coordToKey(const point3d& coord, unsigned depth) const{ if (depth == tree_depth) return coordToKey(coord); else return OcTreeKey(coordToKey(coord(0), depth), coordToKey(coord(1), depth), coordToKey(coord(2), depth)); } /// Converts from a 3D coordinate into a 3D addressing key at a given depth inline OcTreeKey coordToKey(double x, double y, double z, unsigned depth) const{ if (depth == tree_depth) return coordToKey(x,y,z); else return OcTreeKey(coordToKey(x, depth), coordToKey(y, depth), coordToKey(z, depth)); } /** * Adjusts a 3D key from the lowest level to correspond to a higher depth (by * shifting the key values) * * @param key Input key, at the lowest tree level * @param depth Target depth level for the new key * @return Key for the new depth level */ inline OcTreeKey adjustKeyAtDepth(const OcTreeKey& key, unsigned int depth) const{ if (depth == tree_depth) return key; assert(depth <= tree_depth); return OcTreeKey(adjustKeyAtDepth(key[0], depth), adjustKeyAtDepth(key[1], depth), adjustKeyAtDepth(key[2], depth)); } /** * Adjusts a single key value from the lowest level to correspond to a higher depth (by * shifting the key value) * * @param key Input key, at the lowest tree level * @param depth Target depth level for the new key * @return Key for the new depth level */ key_type adjustKeyAtDepth(key_type key, unsigned int depth) const; /** * Converts a 3D coordinate into a 3D OcTreeKey, with boundary checking. * * @param coord 3d coordinate of a point * @param key values that will be computed, an array of fixed size 3. * @return true if point is within the octree (valid), false otherwise */ bool coordToKeyChecked(const point3d& coord, OcTreeKey& key) const; /** * Converts a 3D coordinate into a 3D OcTreeKey at a certain depth, with boundary checking. * * @param coord 3d coordinate of a point * @param depth level of the key from the top * @param key values that will be computed, an array of fixed size 3. * @return true if point is within the octree (valid), false otherwise */ bool coordToKeyChecked(const point3d& coord, unsigned depth, OcTreeKey& key) const; /** * Converts a 3D coordinate into a 3D OcTreeKey, with boundary checking. * * @param x * @param y * @param z * @param key values that will be computed, an array of fixed size 3. * @return true if point is within the octree (valid), false otherwise */ bool coordToKeyChecked(double x, double y, double z, OcTreeKey& key) const; /** * Converts a 3D coordinate into a 3D OcTreeKey at a certain depth, with boundary checking. * * @param x * @param y * @param z * @param depth level of the key from the top * @param key values that will be computed, an array of fixed size 3. * @return true if point is within the octree (valid), false otherwise */ bool coordToKeyChecked(double x, double y, double z, unsigned depth, OcTreeKey& key) const; /** * Converts a single coordinate into a discrete addressing key, with boundary checking. * * @param coordinate 3d coordinate of a point * @param key discrete 16 bit adressing key, result * @return true if coordinate is within the octree bounds (valid), false otherwise */ bool coordToKeyChecked(double coordinate, key_type& key) const; /** * Converts a single coordinate into a discrete addressing key, with boundary checking. * * @param coordinate 3d coordinate of a point * @param depth level of the key from the top * @param key discrete 16 bit adressing key, result * @return true if coordinate is within the octree bounds (valid), false otherwise */ bool coordToKeyChecked(double coordinate, unsigned depth, key_type& key) const; /// converts from a discrete key at a given depth into a coordinate /// corresponding to the key's center double keyToCoord(key_type key, unsigned depth) const; /// converts from a discrete key at the lowest tree level into a coordinate /// corresponding to the key's center inline double keyToCoord(key_type key) const{ return (double( (int) key - (int) this->tree_max_val ) +0.5) * this->resolution; } /// converts from an addressing key at the lowest tree level into a coordinate /// corresponding to the key's center inline point3d keyToCoord(const OcTreeKey& key) const{ return point3d(float(keyToCoord(key[0])), float(keyToCoord(key[1])), float(keyToCoord(key[2]))); } /// converts from an addressing key at a given depth into a coordinate /// corresponding to the key's center inline point3d keyToCoord(const OcTreeKey& key, unsigned depth) const{ return point3d(float(keyToCoord(key[0], depth)), float(keyToCoord(key[1], depth)), float(keyToCoord(key[2], depth))); } protected: /// Constructor to enable derived classes to change tree constants. /// This usually requires a re-implementation of some core tree-traversal functions as well! OcTreeBaseImpl(double resolution, unsigned int tree_depth, unsigned int tree_max_val); /// initialize non-trivial members, helper for constructors void init(); /// recalculates min and max in x, y, z. Does nothing when tree size didn't change. void calcMinMax(); void calcNumNodesRecurs(NODE* node, size_t& num_nodes) const; /// recursive call of readData() std::istream& readNodesRecurs(NODE*, std::istream &s); /// recursive call of writeData() std::ostream& writeNodesRecurs(const NODE*, std::ostream &s) const; /// Recursively delete a node and all children. Deallocates memory /// but does NOT set the node ptr to NULL nor updates tree size. void deleteNodeRecurs(NODE* node); /// recursive call of deleteNode() bool deleteNodeRecurs(NODE* node, unsigned int depth, unsigned int max_depth, const OcTreeKey& key); /// recursive call of prune() void pruneRecurs(NODE* node, unsigned int depth, unsigned int max_depth, unsigned int& num_pruned); /// recursive call of expand() void expandRecurs(NODE* node, unsigned int depth, unsigned int max_depth); size_t getNumLeafNodesRecurs(const NODE* parent) const; private: /// Assignment operator is private: don't (re-)assign octrees /// (const-parameters can't be changed) - use the copy constructor instead. OcTreeBaseImpl<NODE,INTERFACE>& operator=(const OcTreeBaseImpl<NODE,INTERFACE>&); protected: void allocNodeChildren(NODE* node); NODE* root; ///< Pointer to the root NODE, NULL for empty tree // constants of the tree const unsigned int tree_depth; ///< Maximum tree depth is fixed to 16 currently const unsigned int tree_max_val; double resolution; ///< in meters double resolution_factor; ///< = 1. / resolution size_t tree_size; ///< number of nodes in tree /// flag to denote whether the octree extent changed (for lazy min/max eval) bool size_changed; point3d tree_center; // coordinate offset of tree double max_value[3]; ///< max in x, y, z double min_value[3]; ///< min in x, y, z /// contains the size of a voxel at level i (0: root node). tree_depth+1 levels (incl. 0) std::vector<double> sizeLookupTable; /// data structure for ray casting, array for multithreading std::vector<KeyRay> keyrays; const leaf_iterator leaf_iterator_end; const leaf_bbx_iterator leaf_iterator_bbx_end; const tree_iterator tree_iterator_end; }; } #include <octomap/OcTreeBaseImpl.hxx> #endif
23,307
39.465278
123
h
octomap
octomap-master/octomap/include/octomap/OcTreeBaseImpl.hxx
/* * OctoMap - An Efficient Probabilistic 3D Mapping Framework Based on Octrees * https://octomap.github.io/ * * Copyright (c) 2009-2013, K.M. Wurm and A. Hornung, University of Freiburg * All rights reserved. * License: New BSD * * 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 Freiburg 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. */ #undef max #undef min #include <limits> #ifdef _OPENMP #include <omp.h> #endif namespace octomap { template <class NODE,class I> OcTreeBaseImpl<NODE,I>::OcTreeBaseImpl(double in_resolution) : I(), root(NULL), tree_depth(16), tree_max_val(32768), resolution(in_resolution), tree_size(0) { init(); // no longer create an empty root node - only on demand } template <class NODE,class I> OcTreeBaseImpl<NODE,I>::OcTreeBaseImpl(double in_resolution, unsigned int in_tree_depth, unsigned int in_tree_max_val) : I(), root(NULL), tree_depth(in_tree_depth), tree_max_val(in_tree_max_val), resolution(in_resolution), tree_size(0) { init(); // no longer create an empty root node - only on demand } template <class NODE,class I> OcTreeBaseImpl<NODE,I>::~OcTreeBaseImpl(){ clear(); } template <class NODE,class I> OcTreeBaseImpl<NODE,I>::OcTreeBaseImpl(const OcTreeBaseImpl<NODE,I>& rhs) : root(NULL), tree_depth(rhs.tree_depth), tree_max_val(rhs.tree_max_val), resolution(rhs.resolution), tree_size(rhs.tree_size) { init(); // copy nodes recursively: if (rhs.root) root = new NODE(*(rhs.root)); } template <class NODE,class I> void OcTreeBaseImpl<NODE,I>::init(){ this->setResolution(this->resolution); for (unsigned i = 0; i< 3; i++){ max_value[i] = -(std::numeric_limits<double>::max( )); min_value[i] = std::numeric_limits<double>::max( ); } size_changed = true; // create as many KeyRays as there are OMP_THREADS defined, // one buffer for each thread #ifdef _OPENMP #pragma omp parallel #pragma omp critical { if (omp_get_thread_num() == 0){ this->keyrays.resize(omp_get_num_threads()); } } #else this->keyrays.resize(1); #endif } template <class NODE,class I> void OcTreeBaseImpl<NODE,I>::swapContent(OcTreeBaseImpl<NODE,I>& other){ NODE* this_root = root; root = other.root; other.root = this_root; size_t this_size = this->tree_size; this->tree_size = other.tree_size; other.tree_size = this_size; } template <class NODE,class I> bool OcTreeBaseImpl<NODE,I>::operator== (const OcTreeBaseImpl<NODE,I>& other) const{ if (tree_depth != other.tree_depth || tree_max_val != other.tree_max_val || resolution != other.resolution || tree_size != other.tree_size){ return false; } // traverse all nodes, check if structure the same typename OcTreeBaseImpl<NODE,I>::tree_iterator it = this->begin_tree(); typename OcTreeBaseImpl<NODE,I>::tree_iterator end = this->end_tree(); typename OcTreeBaseImpl<NODE,I>::tree_iterator other_it = other.begin_tree(); typename OcTreeBaseImpl<NODE,I>::tree_iterator other_end = other.end_tree(); for (; it != end; ++it, ++other_it){ if (other_it == other_end) return false; if (it.getDepth() != other_it.getDepth() || it.getKey() != other_it.getKey() || !(*it == *other_it)) { return false; } } if (other_it != other_end) return false; return true; } template <class NODE,class I> void OcTreeBaseImpl<NODE,I>::setResolution(double r) { resolution = r; resolution_factor = 1. / resolution; tree_center(0) = tree_center(1) = tree_center(2) = (float) (((double) tree_max_val) / resolution_factor); // init node size lookup table: sizeLookupTable.resize(tree_depth+1); for(unsigned i = 0; i <= tree_depth; ++i){ sizeLookupTable[i] = resolution * double(1 << (tree_depth - i)); } size_changed = true; } template <class NODE,class I> NODE* OcTreeBaseImpl<NODE,I>::createNodeChild(NODE* node, unsigned int childIdx){ assert(childIdx < 8); if (node->children == NULL) { allocNodeChildren(node); } assert (node->children[childIdx] == NULL); NODE* newNode = new NODE(); node->children[childIdx] = static_cast<AbstractOcTreeNode*>(newNode); tree_size++; size_changed = true; return newNode; } template <class NODE,class I> void OcTreeBaseImpl<NODE,I>::deleteNodeChild(NODE* node, unsigned int childIdx){ assert((childIdx < 8) && (node->children != NULL)); assert(node->children[childIdx] != NULL); delete static_cast<NODE*>(node->children[childIdx]); // TODO delete check if empty node->children[childIdx] = NULL; tree_size--; size_changed = true; } template <class NODE,class I> NODE* OcTreeBaseImpl<NODE,I>::getNodeChild(NODE* node, unsigned int childIdx) const{ assert((childIdx < 8) && (node->children != NULL)); assert(node->children[childIdx] != NULL); return static_cast<NODE*>(node->children[childIdx]); } template <class NODE,class I> const NODE* OcTreeBaseImpl<NODE,I>::getNodeChild(const NODE* node, unsigned int childIdx) const{ assert((childIdx < 8) && (node->children != NULL)); assert(node->children[childIdx] != NULL); return static_cast<const NODE*>(node->children[childIdx]); } template <class NODE,class I> bool OcTreeBaseImpl<NODE,I>::isNodeCollapsible(const NODE* node) const{ // all children must exist, must not have children of // their own and have the same occupancy probability if (!nodeChildExists(node, 0)) return false; const NODE* firstChild = getNodeChild(node, 0); if (nodeHasChildren(firstChild)) return false; for (unsigned int i = 1; i<8; i++) { // comparison via getChild so that casts of derived classes ensure // that the right == operator gets called if (!nodeChildExists(node, i) || nodeHasChildren(getNodeChild(node, i)) || !(*(getNodeChild(node, i)) == *(firstChild))) return false; } return true; } template <class NODE,class I> bool OcTreeBaseImpl<NODE,I>::nodeChildExists(const NODE* node, unsigned int childIdx) const{ assert(childIdx < 8); if ((node->children != NULL) && (node->children[childIdx] != NULL)) return true; else return false; } template <class NODE,class I> bool OcTreeBaseImpl<NODE,I>::nodeHasChildren(const NODE* node) const { if (node->children == NULL) return false; for (unsigned int i = 0; i<8; i++){ if (node->children[i] != NULL) return true; } return false; } template <class NODE,class I> void OcTreeBaseImpl<NODE,I>::expandNode(NODE* node){ assert(!nodeHasChildren(node)); for (unsigned int k=0; k<8; k++) { NODE* newNode = createNodeChild(node, k); newNode->copyData(*node); } } template <class NODE,class I> bool OcTreeBaseImpl<NODE,I>::pruneNode(NODE* node){ if (!isNodeCollapsible(node)) return false; // set value to children's values (all assumed equal) node->copyData(*(getNodeChild(node, 0))); // delete children (known to be leafs at this point!) for (unsigned int i=0;i<8;i++) { deleteNodeChild(node, i); } delete[] node->children; node->children = NULL; return true; } template <class NODE,class I> void OcTreeBaseImpl<NODE,I>::allocNodeChildren(NODE* node){ // TODO NODE* node->children = new AbstractOcTreeNode*[8]; for (unsigned int i=0; i<8; i++) { node->children[i] = NULL; } } template <class NODE,class I> inline key_type OcTreeBaseImpl<NODE,I>::coordToKey(double coordinate, unsigned depth) const{ assert (depth <= tree_depth); int keyval = ((int) floor(resolution_factor * coordinate)); unsigned int diff = tree_depth - depth; if(!diff) // same as coordToKey without depth return keyval + tree_max_val; else // shift right and left => erase last bits. Then add offset. return ((keyval >> diff) << diff) + (1 << (diff-1)) + tree_max_val; } template <class NODE,class I> bool OcTreeBaseImpl<NODE,I>::coordToKeyChecked(double coordinate, key_type& keyval) const { // scale to resolution and shift center for tree_max_val int scaled_coord = ((int) floor(resolution_factor * coordinate)) + tree_max_val; // keyval within range of tree? if (( scaled_coord >= 0) && (((unsigned int) scaled_coord) < (2*tree_max_val))) { keyval = scaled_coord; return true; } return false; } template <class NODE,class I> bool OcTreeBaseImpl<NODE,I>::coordToKeyChecked(double coordinate, unsigned depth, key_type& keyval) const { // scale to resolution and shift center for tree_max_val int scaled_coord = ((int) floor(resolution_factor * coordinate)) + tree_max_val; // keyval within range of tree? if (( scaled_coord >= 0) && (((unsigned int) scaled_coord) < (2*tree_max_val))) { keyval = scaled_coord; keyval = adjustKeyAtDepth(keyval, depth); return true; } return false; } template <class NODE,class I> bool OcTreeBaseImpl<NODE,I>::coordToKeyChecked(const point3d& point, OcTreeKey& key) const{ for (unsigned int i=0;i<3;i++) { if (!coordToKeyChecked( point(i), key[i])) return false; } return true; } template <class NODE,class I> bool OcTreeBaseImpl<NODE,I>::coordToKeyChecked(const point3d& point, unsigned depth, OcTreeKey& key) const{ for (unsigned int i=0;i<3;i++) { if (!coordToKeyChecked( point(i), depth, key[i])) return false; } return true; } template <class NODE,class I> bool OcTreeBaseImpl<NODE,I>::coordToKeyChecked(double x, double y, double z, OcTreeKey& key) const{ if (!(coordToKeyChecked(x, key[0]) && coordToKeyChecked(y, key[1]) && coordToKeyChecked(z, key[2]))) { return false; } else { return true; } } template <class NODE,class I> bool OcTreeBaseImpl<NODE,I>::coordToKeyChecked(double x, double y, double z, unsigned depth, OcTreeKey& key) const{ if (!(coordToKeyChecked(x, depth, key[0]) && coordToKeyChecked(y, depth, key[1]) && coordToKeyChecked(z, depth, key[2]))) { return false; } else { return true; } } template <class NODE,class I> key_type OcTreeBaseImpl<NODE,I>::adjustKeyAtDepth(key_type key, unsigned int depth) const{ unsigned int diff = tree_depth - depth; if(diff == 0) return key; else return (((key-tree_max_val) >> diff) << diff) + (1 << (diff-1)) + tree_max_val; } template <class NODE,class I> double OcTreeBaseImpl<NODE,I>::keyToCoord(key_type key, unsigned depth) const{ assert(depth <= tree_depth); // root is centered on 0 = 0.0 if (depth == 0) { return 0.0; } else if (depth == tree_depth) { return keyToCoord(key); } else { return (floor( (double(key)-double(this->tree_max_val)) /double(1 << (tree_depth - depth)) ) + 0.5 ) * this->getNodeSize(depth); } } template <class NODE,class I> NODE* OcTreeBaseImpl<NODE,I>::search(const point3d& value, unsigned int depth) const { OcTreeKey key; if (!coordToKeyChecked(value, key)){ OCTOMAP_ERROR_STR("Error in search: ["<< value <<"] is out of OcTree bounds!"); return NULL; } else { return this->search(key, depth); } } template <class NODE,class I> NODE* OcTreeBaseImpl<NODE,I>::search(double x, double y, double z, unsigned int depth) const { OcTreeKey key; if (!coordToKeyChecked(x, y, z, key)){ OCTOMAP_ERROR_STR("Error in search: ["<< x <<" "<< y << " " << z << "] is out of OcTree bounds!"); return NULL; } else { return this->search(key, depth); } } template <class NODE,class I> NODE* OcTreeBaseImpl<NODE,I>::search (const OcTreeKey& key, unsigned int depth) const { assert(depth <= tree_depth); if (root == NULL) return NULL; if (depth == 0) depth = tree_depth; // generate appropriate key_at_depth for queried depth OcTreeKey key_at_depth = key; if (depth != tree_depth) key_at_depth = adjustKeyAtDepth(key, depth); NODE* curNode (root); int diff = tree_depth - depth; // follow nodes down to requested level (for diff = 0 it's the last level) for (int i=(tree_depth-1); i>=diff; --i) { unsigned int pos = computeChildIdx(key_at_depth, i); if (nodeChildExists(curNode, pos)) { // cast needed: (nodes need to ensure it's the right pointer) curNode = getNodeChild(curNode, pos); } else { // we expected a child but did not get it // is the current node a leaf already? if (!nodeHasChildren(curNode)) { // TODO similar check to nodeChildExists? return curNode; } else { // it is not, search failed return NULL; } } } // end for return curNode; } template <class NODE,class I> bool OcTreeBaseImpl<NODE,I>::deleteNode(const point3d& value, unsigned int depth) { OcTreeKey key; if (!coordToKeyChecked(value, key)){ OCTOMAP_ERROR_STR("Error in deleteNode: ["<< value <<"] is out of OcTree bounds!"); return false; } else { return this->deleteNode(key, depth); } } template <class NODE,class I> bool OcTreeBaseImpl<NODE,I>::deleteNode(double x, double y, double z, unsigned int depth) { OcTreeKey key; if (!coordToKeyChecked(x, y, z, key)){ OCTOMAP_ERROR_STR("Error in deleteNode: ["<< x <<" "<< y << " " << z << "] is out of OcTree bounds!"); return false; } else { return this->deleteNode(key, depth); } } template <class NODE,class I> bool OcTreeBaseImpl<NODE,I>::deleteNode(const OcTreeKey& key, unsigned int depth) { if (root == NULL) return true; if (depth == 0) depth = tree_depth; return deleteNodeRecurs(root, 0, depth, key); } template <class NODE,class I> void OcTreeBaseImpl<NODE,I>::clear() { if (this->root){ deleteNodeRecurs(root); this->tree_size = 0; this->root = NULL; // max extent of tree changed: this->size_changed = true; } } template <class NODE,class I> void OcTreeBaseImpl<NODE,I>::prune() { if (root == NULL) return; for (unsigned int depth=tree_depth-1; depth > 0; --depth) { unsigned int num_pruned = 0; pruneRecurs(this->root, 0, depth, num_pruned); if (num_pruned == 0) break; } } template <class NODE,class I> void OcTreeBaseImpl<NODE,I>::expand() { if (root) expandRecurs(root,0, tree_depth); } template <class NODE,class I> bool OcTreeBaseImpl<NODE,I>::computeRayKeys(const point3d& origin, const point3d& end, KeyRay& ray) const { // see "A Faster Voxel Traversal Algorithm for Ray Tracing" by Amanatides & Woo // basically: DDA in 3D ray.reset(); OcTreeKey key_origin, key_end; if ( !OcTreeBaseImpl<NODE,I>::coordToKeyChecked(origin, key_origin) || !OcTreeBaseImpl<NODE,I>::coordToKeyChecked(end, key_end) ) { OCTOMAP_WARNING_STR("coordinates ( " << origin << " -> " << end << ") out of bounds in computeRayKeys"); return false; } if (key_origin == key_end) return true; // same tree cell, we're done. ray.addKey(key_origin); // Initialization phase ------------------------------------------------------- point3d direction = (end - origin); float length = (float) direction.norm(); direction /= length; // normalize vector int step[3]; double tMax[3]; double tDelta[3]; OcTreeKey current_key = key_origin; for(unsigned int i=0; i < 3; ++i) { // compute step direction if (direction(i) > 0.0) step[i] = 1; else if (direction(i) < 0.0) step[i] = -1; else step[i] = 0; // compute tMax, tDelta if (step[i] != 0) { // corner point of voxel (in direction of ray) double voxelBorder = this->keyToCoord(current_key[i]); voxelBorder += (float) (step[i] * this->resolution * 0.5); tMax[i] = ( voxelBorder - origin(i) ) / direction(i); tDelta[i] = this->resolution / fabs( direction(i) ); } else { tMax[i] = std::numeric_limits<double>::max( ); tDelta[i] = std::numeric_limits<double>::max( ); } } // Incremental phase --------------------------------------------------------- bool done = false; while (!done) { unsigned int dim; // find minimum tMax: if (tMax[0] < tMax[1]){ if (tMax[0] < tMax[2]) dim = 0; else dim = 2; } else { if (tMax[1] < tMax[2]) dim = 1; else dim = 2; } // advance in direction "dim" current_key[dim] += step[dim]; tMax[dim] += tDelta[dim]; assert (current_key[dim] < 2*this->tree_max_val); // reached endpoint, key equv? if (current_key == key_end) { done = true; break; } else { // reached endpoint world coords? // dist_from_origin now contains the length of the ray when traveled until the border of the current voxel double dist_from_origin = std::min(std::min(tMax[0], tMax[1]), tMax[2]); // if this is longer than the expected ray length, we should have already hit the voxel containing the end point with the code above (key_end). // However, we did not hit it due to accumulating discretization errors, so this is the point here to stop the ray as we would never reach the voxel key_end if (dist_from_origin > length) { done = true; break; } else { // continue to add freespace cells ray.addKey(current_key); } } assert ( ray.size() < ray.sizeMax() - 1); } // end while return true; } template <class NODE,class I> bool OcTreeBaseImpl<NODE,I>::computeRay(const point3d& origin, const point3d& end, std::vector<point3d>& _ray) { _ray.clear(); if (!computeRayKeys(origin, end, keyrays.at(0))) return false; for (KeyRay::const_iterator it = keyrays[0].begin(); it != keyrays[0].end(); ++it) { _ray.push_back(keyToCoord(*it)); } return true; } template <class NODE,class I> void OcTreeBaseImpl<NODE,I>::deleteNodeRecurs(NODE* node){ assert(node); // TODO: maintain tree size? if (node->children != NULL) { for (unsigned int i=0; i<8; i++) { if (node->children[i] != NULL){ this->deleteNodeRecurs(static_cast<NODE*>(node->children[i])); } } delete[] node->children; node->children = NULL; } // else: node has no children delete node; } template <class NODE,class I> bool OcTreeBaseImpl<NODE,I>::deleteNodeRecurs(NODE* node, unsigned int depth, unsigned int max_depth, const OcTreeKey& key){ if (depth >= max_depth) // on last level: delete child when going up return true; assert(node); unsigned int pos = computeChildIdx(key, this->tree_depth-1-depth); if (!nodeChildExists(node, pos)) { // child does not exist, but maybe it's a pruned node? if ((!nodeHasChildren(node)) && (node != this->root)) { // TODO double check for exists / root exception? // current node does not have children AND it's not the root node // -> expand pruned node expandNode(node); // tree_size and size_changed adjusted in createNodeChild(...) } else { // no branch here, node does not exist return false; } } // follow down further, fix inner nodes on way back up bool deleteChild = deleteNodeRecurs(getNodeChild(node, pos), depth+1, max_depth, key); if (deleteChild){ // TODO: lazy eval? // TODO delete check depth, what happens to inner nodes with children? this->deleteNodeChild(node, pos); if (!nodeHasChildren(node)) return true; else{ node->updateOccupancyChildren(); // TODO: occupancy? } } // node did not lose a child, or still has other children return false; } template <class NODE,class I> void OcTreeBaseImpl<NODE,I>::pruneRecurs(NODE* node, unsigned int depth, unsigned int max_depth, unsigned int& num_pruned) { assert(node); if (depth < max_depth) { for (unsigned int i=0; i<8; i++) { if (nodeChildExists(node, i)) { pruneRecurs(getNodeChild(node, i), depth+1, max_depth, num_pruned); } } } // end if depth else { // max level reached if (pruneNode(node)) { num_pruned++; } } } template <class NODE,class I> void OcTreeBaseImpl<NODE,I>::expandRecurs(NODE* node, unsigned int depth, unsigned int max_depth) { if (depth >= max_depth) return; assert(node); // current node has no children => can be expanded if (!nodeHasChildren(node)){ expandNode(node); } // recursively expand children for (unsigned int i=0; i<8; i++) { if (nodeChildExists(node, i)) { // TODO double check (node != NULL) expandRecurs(getNodeChild(node, i), depth+1, max_depth); } } } template <class NODE,class I> std::ostream& OcTreeBaseImpl<NODE,I>::writeData(std::ostream &s) const{ if (root) writeNodesRecurs(root, s); return s; } template <class NODE,class I> std::ostream& OcTreeBaseImpl<NODE,I>::writeNodesRecurs(const NODE* node, std::ostream &s) const{ node->writeData(s); // 1 bit for each children; 0: empty, 1: allocated std::bitset<8> children; for (unsigned int i=0; i<8; i++) { if (nodeChildExists(node, i)) children[i] = 1; else children[i] = 0; } char children_char = (char) children.to_ulong(); s.write((char*)&children_char, sizeof(char)); // std::cout << "wrote: " << value << " " // << children.to_string<char,std::char_traits<char>,std::allocator<char> >() // << std::endl; // recursively write children for (unsigned int i=0; i<8; i++) { if (children[i] == 1) { this->writeNodesRecurs(getNodeChild(node, i), s); } } return s; } template <class NODE,class I> std::istream& OcTreeBaseImpl<NODE,I>::readData(std::istream &s) { if (!s.good()){ OCTOMAP_WARNING_STR(__FILE__ << ":" << __LINE__ << "Warning: Input filestream not \"good\""); } this->tree_size = 0; size_changed = true; // tree needs to be newly created or cleared externally if (root) { OCTOMAP_ERROR_STR("Trying to read into an existing tree."); return s; } root = new NODE(); readNodesRecurs(root, s); tree_size = calcNumNodes(); // compute number of nodes return s; } template <class NODE,class I> std::istream& OcTreeBaseImpl<NODE,I>::readNodesRecurs(NODE* node, std::istream &s) { node->readData(s); char children_char; s.read((char*)&children_char, sizeof(char)); std::bitset<8> children ((unsigned long long) children_char); //std::cout << "read: " << node->getValue() << " " // << children.to_string<char,std::char_traits<char>,std::allocator<char> >() // << std::endl; for (unsigned int i=0; i<8; i++) { if (children[i] == 1){ NODE* newNode = createNodeChild(node, i); readNodesRecurs(newNode, s); } } return s; } template <class NODE,class I> unsigned long long OcTreeBaseImpl<NODE,I>::memoryFullGrid() const{ if (root == NULL) return 0; double size_x, size_y, size_z; this->getMetricSize(size_x, size_y,size_z); // assuming best case (one big array and efficient addressing) // we can avoid "ceil" since size already accounts for voxels // Note: this can be larger than the adressable memory // - size_t may not be enough to hold it! return (unsigned long long)((size_x/resolution) * (size_y/resolution) * (size_z/resolution) * sizeof(root->getValue())); } // non-const versions, // change min/max/size_changed members template <class NODE,class I> void OcTreeBaseImpl<NODE,I>::getMetricSize(double& x, double& y, double& z){ double minX, minY, minZ; double maxX, maxY, maxZ; getMetricMax(maxX, maxY, maxZ); getMetricMin(minX, minY, minZ); x = maxX - minX; y = maxY - minY; z = maxZ - minZ; } template <class NODE,class I> void OcTreeBaseImpl<NODE,I>::getMetricSize(double& x, double& y, double& z) const{ double minX, minY, minZ; double maxX, maxY, maxZ; getMetricMax(maxX, maxY, maxZ); getMetricMin(minX, minY, minZ); x = maxX - minX; y = maxY - minY; z = maxZ - minZ; } template <class NODE,class I> void OcTreeBaseImpl<NODE,I>::calcMinMax() { if (!size_changed) return; // empty tree if (root == NULL){ min_value[0] = min_value[1] = min_value[2] = 0.0; max_value[0] = max_value[1] = max_value[2] = 0.0; size_changed = false; return; } for (unsigned i = 0; i< 3; i++){ max_value[i] = -std::numeric_limits<double>::max(); min_value[i] = std::numeric_limits<double>::max(); } for(typename OcTreeBaseImpl<NODE,I>::leaf_iterator it = this->begin(), end=this->end(); it!= end; ++it) { double size = it.getSize(); double halfSize = size/2.0; double x = it.getX() - halfSize; double y = it.getY() - halfSize; double z = it.getZ() - halfSize; if (x < min_value[0]) min_value[0] = x; if (y < min_value[1]) min_value[1] = y; if (z < min_value[2]) min_value[2] = z; x += size; y += size; z += size; if (x > max_value[0]) max_value[0] = x; if (y > max_value[1]) max_value[1] = y; if (z > max_value[2]) max_value[2] = z; } size_changed = false; } template <class NODE,class I> void OcTreeBaseImpl<NODE,I>::getMetricMin(double& x, double& y, double& z){ calcMinMax(); x = min_value[0]; y = min_value[1]; z = min_value[2]; } template <class NODE,class I> void OcTreeBaseImpl<NODE,I>::getMetricMax(double& x, double& y, double& z){ calcMinMax(); x = max_value[0]; y = max_value[1]; z = max_value[2]; } // const versions template <class NODE,class I> void OcTreeBaseImpl<NODE,I>::getMetricMin(double& mx, double& my, double& mz) const { mx = my = mz = std::numeric_limits<double>::max( ); if (size_changed) { // empty tree if (root == NULL){ mx = my = mz = 0.0; return; } for(typename OcTreeBaseImpl<NODE,I>::leaf_iterator it = this->begin(), end=this->end(); it!= end; ++it) { double halfSize = it.getSize()/2.0; double x = it.getX() - halfSize; double y = it.getY() - halfSize; double z = it.getZ() - halfSize; if (x < mx) mx = x; if (y < my) my = y; if (z < mz) mz = z; } } // end if size changed else { mx = min_value[0]; my = min_value[1]; mz = min_value[2]; } } template <class NODE,class I> void OcTreeBaseImpl<NODE,I>::getMetricMax(double& mx, double& my, double& mz) const { mx = my = mz = -std::numeric_limits<double>::max( ); if (size_changed) { // empty tree if (root == NULL){ mx = my = mz = 0.0; return; } for(typename OcTreeBaseImpl<NODE,I>::leaf_iterator it = this->begin(), end=this->end(); it!= end; ++it) { double halfSize = it.getSize()/2.0; double x = it.getX() + halfSize; double y = it.getY() + halfSize; double z = it.getZ() + halfSize; if (x > mx) mx = x; if (y > my) my = y; if (z > mz) mz = z; } } else { mx = max_value[0]; my = max_value[1]; mz = max_value[2]; } } template <class NODE,class I> size_t OcTreeBaseImpl<NODE,I>::calcNumNodes() const { size_t retval = 0; // root node if (root){ retval++; calcNumNodesRecurs(root, retval); } return retval; } template <class NODE,class I> void OcTreeBaseImpl<NODE,I>::calcNumNodesRecurs(NODE* node, size_t& num_nodes) const { assert (node); if (nodeHasChildren(node)) { for (unsigned int i=0; i<8; ++i) { if (nodeChildExists(node, i)) { num_nodes++; calcNumNodesRecurs(getNodeChild(node, i), num_nodes); } } } } template <class NODE,class I> size_t OcTreeBaseImpl<NODE,I>::memoryUsage() const{ size_t num_leaf_nodes = this->getNumLeafNodes(); size_t num_inner_nodes = tree_size - num_leaf_nodes; return (sizeof(OcTreeBaseImpl<NODE,I>) + memoryUsageNode() * tree_size + num_inner_nodes * sizeof(NODE*[8])); } template <class NODE,class I> void OcTreeBaseImpl<NODE,I>::getUnknownLeafCenters(point3d_list& node_centers, point3d pmin, point3d pmax, unsigned int depth) const { assert(depth <= tree_depth); if (depth == 0) depth = tree_depth; point3d pmin_clamped = this->keyToCoord(this->coordToKey(pmin, depth), depth); point3d pmax_clamped = this->keyToCoord(this->coordToKey(pmax, depth), depth); float diff[3]; unsigned int steps[3]; float step_size = this->resolution * pow(2, tree_depth-depth); for (int i=0;i<3;++i) { diff[i] = pmax_clamped(i) - pmin_clamped(i); steps[i] = static_cast<unsigned int>(floor(diff[i] / step_size)); // std::cout << "bbx " << i << " size: " << diff[i] << " " << steps[i] << " steps\n"; } point3d p = pmin_clamped; NODE* res; for (unsigned int x=0; x<steps[0]; ++x) { p.x() += step_size; for (unsigned int y=0; y<steps[1]; ++y) { p.y() += step_size; for (unsigned int z=0; z<steps[2]; ++z) { // std::cout << "querying p=" << p << std::endl; p.z() += step_size; res = this->search(p,depth); if (res == NULL) { node_centers.push_back(p); } } p.z() = pmin_clamped.z(); } p.y() = pmin_clamped.y(); } } template <class NODE,class I> size_t OcTreeBaseImpl<NODE,I>::getNumLeafNodes() const { if (root == NULL) return 0; return getNumLeafNodesRecurs(root); } template <class NODE,class I> size_t OcTreeBaseImpl<NODE,I>::getNumLeafNodesRecurs(const NODE* parent) const { assert(parent); if (!nodeHasChildren(parent)) // this is a leaf -> terminate return 1; size_t sum_leafs_children = 0; for (unsigned int i=0; i<8; ++i) { if (nodeChildExists(parent, i)) { sum_leafs_children += getNumLeafNodesRecurs(getNodeChild(parent, i)); } } return sum_leafs_children; } template <class NODE,class I> double OcTreeBaseImpl<NODE,I>::volume() { double x, y, z; getMetricSize(x, y, z); return x*y*z; } }
32,739
28.232143
164
hxx
octomap
octomap-master/octomap/include/octomap/OcTreeDataNode.h
/* * OctoMap - An Efficient Probabilistic 3D Mapping Framework Based on Octrees * https://octomap.github.io/ * * Copyright (c) 2009-2013, K.M. Wurm and A. Hornung, University of Freiburg * All rights reserved. * License: New BSD * * 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 Freiburg 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. */ #ifndef OCTOMAP_OCTREE_DATA_NODE_H #define OCTOMAP_OCTREE_DATA_NODE_H #include "octomap_types.h" #include "assert.h" namespace octomap { class AbstractOcTreeNode { }; // forward declaration for friend in OcTreeDataNode template<typename NODE,typename I> class OcTreeBaseImpl; /** * Basic node in the OcTree that can hold arbitrary data of type T in value. * This is the base class for nodes used in an OcTree. The used implementation * for occupancy mapping is in OcTreeNode.# * \tparam T data to be stored in the node (e.g. a float for probabilities) * * Note: If you derive a class (directly or indirectly) from OcTreeDataNode, * you have to implement (at least) the following functions to avoid slicing * errors and memory-related bugs: * createChild(), getChild(), getChild() const, expandNode() * See ColorOcTreeNode in ColorOcTree.h for an example. */ template<typename T> class OcTreeDataNode: public AbstractOcTreeNode { template<typename NODE, typename I> friend class OcTreeBaseImpl; public: OcTreeDataNode(); OcTreeDataNode(T initVal); /// Copy constructor, performs a recursive deep-copy of all children /// including node data in "value" OcTreeDataNode(const OcTreeDataNode& rhs); /// Delete only own members. /// OcTree maintains tree structure and must have deleted children already ~OcTreeDataNode(); /// Copy the payload (data in "value") from rhs into this node /// Opposed to copy ctor, this does not clone the children as well void copyData(const OcTreeDataNode& from); /// Equals operator, compares if the stored value is identical bool operator==(const OcTreeDataNode& rhs) const; // -- children ---------------------------------- /// Test whether the i-th child exists. /// @deprecated Replaced by tree->nodeChildExists(...) /// \return true if the i-th child exists OCTOMAP_DEPRECATED(bool childExists(unsigned int i) const); /// @deprecated Replaced by tree->nodeHasChildren(...) /// \return true if the node has at least one child OCTOMAP_DEPRECATED(bool hasChildren() const); /// @return value stored in the node T getValue() const{return value;}; /// sets value to be stored in the node void setValue(T v) {value = v;}; // file IO: /// Read node payload (data only) from binary stream std::istream& readData(std::istream &s); /// Write node payload (data only) to binary stream std::ostream& writeData(std::ostream &s) const; /// Make the templated data type available from the outside typedef T DataType; protected: void allocChildren(); /// pointer to array of children, may be NULL /// @note The tree class manages this pointer, the array, and the memory for it! /// The children of a node are always enforced to be the same type as the node AbstractOcTreeNode** children; /// stored data (payload) T value; }; } // end namespace #include "octomap/OcTreeDataNode.hxx" #endif
4,866
34.268116
84
h
octomap
octomap-master/octomap/include/octomap/OcTreeDataNode.hxx
/* * OctoMap - An Efficient Probabilistic 3D Mapping Framework Based on Octrees * https://octomap.github.io/ * * Copyright (c) 2009-2013, K.M. Wurm and A. Hornung, University of Freiburg * All rights reserved. * License: New BSD * * 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 Freiburg 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. */ namespace octomap { template <typename T> OcTreeDataNode<T>::OcTreeDataNode() : children(NULL) { } template <typename T> OcTreeDataNode<T>::OcTreeDataNode(T initVal) : children(NULL), value(initVal) { } template <typename T> OcTreeDataNode<T>::OcTreeDataNode(const OcTreeDataNode<T>& rhs) : children(NULL), value(rhs.value) { if (rhs.children != NULL){ allocChildren(); for (unsigned i = 0; i<8; ++i){ if (rhs.children[i] != NULL) children[i] = new OcTreeDataNode<T>(*(static_cast<OcTreeDataNode<T>*>(rhs.children[i]))); } } } template <typename T> OcTreeDataNode<T>::~OcTreeDataNode() { // Delete only own members. OcTree maintains tree structure and must have deleted // children already assert(children == NULL); } template <typename T> void OcTreeDataNode<T>::copyData(const OcTreeDataNode<T>& from){ value = from.value; } template <typename T> bool OcTreeDataNode<T>::operator== (const OcTreeDataNode<T>& rhs) const{ return rhs.value == value; } // ============================================================ // = children ======================================= // ============================================================ template <typename T> bool OcTreeDataNode<T>::childExists(unsigned int i) const { assert(i < 8); if ((children != NULL) && (children[i] != NULL)) return true; else return false; } template <typename T> bool OcTreeDataNode<T>::hasChildren() const { if (children == NULL) return false; for (unsigned int i = 0; i<8; i++){ // fast check, we know children != NULL if (children[i] != NULL) return true; } return false; } // ============================================================ // = File IO ======================================= // ============================================================ template <typename T> std::istream& OcTreeDataNode<T>::readData(std::istream &s) { s.read((char*) &value, sizeof(value)); return s; } template <typename T> std::ostream& OcTreeDataNode<T>::writeData(std::ostream &s) const{ s.write((const char*) &value, sizeof(value)); return s; } // ============================================================ // = private methodes ======================================= // ============================================================ template <typename T> void OcTreeDataNode<T>::allocChildren() { children = new AbstractOcTreeNode*[8]; for (unsigned int i=0; i<8; i++) { children[i] = NULL; } } } // end namespace
4,485
30.815603
99
hxx