Datasets:
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 |
Dataset card for ArtifactAI/arxiv_cplusplus_research_code
Dataset Description
https://huggingface.co/datasets/AlgorithmicResearchGroup/arxiv_cplusplus_research_code
Dataset Summary
ArtifactAI/arxiv_python_research_code contains over 10.6GB of source code files referenced strictly in ArXiv papers. The dataset serves as a curated dataset for Code LLMs.
How to use it
from datasets import load_dataset
# full dataset (10.6GB of data)
ds = load_dataset("AlgorithmicResearchGroup/arxiv_cplusplus_research_code", split="train")
# dataset streaming (will only download the data as needed)
ds = load_dataset("AlgorithmicResearchGroup/arxiv_cplusplus_research_code", streaming=True, split="train")
for sample in iter(ds): print(sample["code"])
Dataset Structure
Data Instances
Each data instance corresponds to one file. The content of the file is in the code
feature, and other features (repo
, file
, etc.) provide some metadata.
Data Fields
repo
(string): code repository name.file
(string): file path in the repository.code
(string): code within the file.file_length
: (integer): number of characters in the file.avg_line_length
: (float): the average line-length of the file.max_line_length
: (integer): the maximum line-length of the file.extension_type
: (string): file extension.
Data Splits
The dataset has no splits and all data is loaded as train split by default.
Dataset Creation
Source Data
Initial Data Collection and Normalization
34,099 active GitHub repository names were extracted from ArXiv papers from its inception through July 21st, 2023 totaling 773G of compressed github repositories.
These repositories were then filtered, and the code from each of "cpp", "cxx", "cc", "h", "hpp", "hxx" file extension was extracted into 1.4 million files.
Who are the source language producers?
The source (code) language producers are users of GitHub that created unique repository
Personal and Sensitive Information
The released dataset may contain sensitive information such as emails, IP addresses, and API/ssh keys that have previously been published to public repositories on GitHub.
Additional Information
Dataset Curators
Matthew Kenney, AlgorithmicResearchGroup, matt@algorithmicresearchgroup.com
Citation Information
@misc{arxiv_cplusplus_research_code,
title={arxiv_cplusplus_research_code},
author={Matthew Kenney},
year={2023}
}
- Downloads last month
- 1,213