source
stringlengths 3
92
| c
stringlengths 26
2.25M
|
|---|---|
3d25pt.lbpar.c
|
#include <omp.h>
#include <math.h>
#define ceild(n,d) ceil(((double)(n))/((double)(d)))
#define floord(n,d) floor(((double)(n))/((double)(d)))
#define max(x,y) ((x) > (y)? (x) : (y))
#define min(x,y) ((x) < (y)? (x) : (y))
/*
* Order-2, 3D 25 point stencil
* Adapted from PLUTO and Pochoir test bench
*
* Tareq Malas
*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#ifdef LIKWID_PERFMON
#include <likwid.h>
#endif
#include "print_utils.h"
#define TESTS 2
#define MAX(a,b) ((a) > (b) ? a : b)
#define MIN(a,b) ((a) < (b) ? a : b)
#ifndef min
#define min(x,y) ((x) < (y)? (x) : (y))
#endif
/* Subtract the `struct timeval' values X and Y,
* storing the result in RESULT.
*
* Return 1 if the difference is negative, otherwise 0.
*/
int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y)
{
/* Perform the carry for the later subtraction by updating y. */
if (x->tv_usec < y->tv_usec)
{
int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1;
y->tv_usec -= 1000000 * nsec;
y->tv_sec += nsec;
}
if (x->tv_usec - y->tv_usec > 1000000)
{
int nsec = (x->tv_usec - y->tv_usec) / 1000000;
y->tv_usec += 1000000 * nsec;
y->tv_sec -= nsec;
}
/* Compute the time remaining to wait.
* tv_usec is certainly positive.
*/
result->tv_sec = x->tv_sec - y->tv_sec;
result->tv_usec = x->tv_usec - y->tv_usec;
/* Return 1 if result is negative. */
return x->tv_sec < y->tv_sec;
}
int main(int argc, char *argv[])
{
int t, i, j, k, test;
int Nx, Ny, Nz, Nt;
if (argc > 3) {
Nx = atoi(argv[1])+8;
Ny = atoi(argv[2])+8;
Nz = atoi(argv[3])+8;
}
if (argc > 4)
Nt = atoi(argv[4]);
double ****A = (double ****) malloc(sizeof(double***)*2);
double ***roc2 = (double ***) malloc(sizeof(double**));
A[0] = (double ***) malloc(sizeof(double**)*Nz);
A[1] = (double ***) malloc(sizeof(double**)*Nz);
roc2 = (double ***) malloc(sizeof(double**)*Nz);
for(i=0; i<Nz; i++){
A[0][i] = (double**) malloc(sizeof(double*)*Ny);
A[1][i] = (double**) malloc(sizeof(double*)*Ny);
roc2[i] = (double**) malloc(sizeof(double*)*Ny);
for(j=0;j<Ny;j++){
A[0][i][j] = (double*) malloc(sizeof(double)*Nx);
A[1][i][j] = (double*) malloc(sizeof(double)*Nx);
roc2[i][j] = (double*) malloc(sizeof(double)*Nx);
}
}
// tile size information, including extra element to decide the list length
int *tile_size = (int*) malloc(sizeof(int));
tile_size[0] = -1;
// The list is modified here before source-to-source transformations
tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5);
tile_size[0] = 24;
tile_size[1] = 24;
tile_size[2] = 16;
tile_size[3] = 512;
tile_size[4] = -1;
// for timekeeping
int ts_return = -1;
struct timeval start, end, result;
double tdiff = 0.0, min_tdiff=1.e100;
const int BASE = 1024;
// initialize variables
//
srand(42);
for (i = 1; i < Nz; i++) {
for (j = 1; j < Ny; j++) {
for (k = 1; k < Nx; k++) {
A[0][i][j][k] = 1.0 * (rand() % BASE);
roc2[i][j][k] = 2.0 * (rand() % BASE);
}
}
}
#ifdef LIKWID_PERFMON
LIKWID_MARKER_INIT;
#pragma omp parallel
{
LIKWID_MARKER_THREADINIT;
#pragma omp barrier
LIKWID_MARKER_START("calc");
}
#endif
int num_threads = 1;
#if defined(_OPENMP)
num_threads = omp_get_max_threads();
#endif
const double coef0 = -0.28472;
const double coef1 = 0.16000;
const double coef2 = -0.02000;
const double coef3 = 0.00254;
const double coef4 = -0.00018;
for(test=0; test<TESTS; test++){
gettimeofday(&start, 0);
// serial execution - Addition: 6 && Multiplication: 2
/* Copyright (C) 1991-2014 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
/* This header is separate from features.h so that the compiler can
include it implicitly at the start of every compilation. It must
not itself include <features.h> or any other header that includes
<features.h> because the implicit include comes before any feature
test macros that may be defined in a source file before it first
explicitly includes a system header. GCC knows the name of this
header in order to preinclude it. */
/* glibc's intent is to support the IEC 559 math functionality, real
and complex. If the GCC (4.9 and later) predefined macros
specifying compiler intent are available, use them to determine
whether the overall intent is to support these features; otherwise,
presume an older compiler has intent to support these features and
define these macros by default. */
/* wchar_t uses ISO/IEC 10646 (2nd ed., published 2011-03-15) /
Unicode 6.0. */
/* We do not support C11 <threads.h>. */
int t1, t2, t3, t4, t5, t6, t7, t8;
int lb, ub, lbp, ubp, lb2, ub2;
register int lbv, ubv;
/* Start of CLooG code */
if ((Nt >= 1) && (Nx >= 9) && (Ny >= 9) && (Nz >= 9)) {
for (t1=-1;t1<=floord(Nt-1,3);t1++) {
lbp=max(ceild(t1,2),ceild(6*t1-Nt+2,6));
ubp=min(floord(4*Nt+Nz-9,24),floord(12*t1+Nz+6,24));
#pragma omp parallel for private(lbv,ubv,t3,t4,t5,t6,t7,t8)
for (t2=lbp;t2<=ubp;t2++) {
for (t3=max(max(max(0,ceild(3*t1-3*t2,2)),ceild(3*t1-2,4)),ceild(24*t2-Nz-3,16));t3<=min(min(min(floord(4*Nt+Ny-9,16),floord(12*t1+Ny+15,16)),floord(24*t2+Ny+11,16)),floord(24*t1-24*t2+Nz+Ny+13,16));t3++) {
for (t4=max(max(max(max(0,ceild(3*t1-3*t2-62,64)),ceild(3*t1-126,128)),ceild(24*t2-Nz-499,512)),ceild(16*t3-Ny-499,512));t4<=min(min(min(min(floord(4*Nt+Nx-9,512),floord(12*t1+Nx+15,512)),floord(24*t2+Nx+11,512)),floord(16*t3+Nx+3,512)),floord(24*t1-24*t2+Nz+Nx+13,512));t4++) {
for (t5=max(max(max(max(max(0,ceild(24*t2-Nz+5,4)),ceild(16*t3-Ny+5,4)),ceild(512*t4-Nx+5,4)),3*t1),6*t1-6*t2+1);t5<=min(min(min(min(min(floord(24*t1-24*t2+Nz+18,4),Nt-1),3*t1+5),6*t2+4),4*t3+2),128*t4+126);t5++) {
for (t6=max(max(24*t2,4*t5+4),-24*t1+24*t2+8*t5-23);t6<=min(min(24*t2+23,-24*t1+24*t2+8*t5),4*t5+Nz-5);t6++) {
for (t7=max(16*t3,4*t5+4);t7<=min(16*t3+15,4*t5+Ny-5);t7++) {
lbv=max(512*t4,4*t5+4);
ubv=min(512*t4+511,4*t5+Nx-5);
#pragma ivdep
#pragma vector always
for (t8=lbv;t8<=ubv;t8++) {
A[( t5 + 1) % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] = (((2.0 * A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)]) - A[( t5 + 1) % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)]) + (roc2[ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (((((coef0 * A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)]) + (coef1 * (((((A[ t5 % 2][ (-4*t5+t6) - 1][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 1][ (-4*t5+t7)][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 1][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 1][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 1]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 1]))) + (coef2 * (((((A[ t5 % 2][ (-4*t5+t6) - 2][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 2][ (-4*t5+t7)][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 2][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 2][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 2]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 2]))) + (coef3 * (((((A[ t5 % 2][ (-4*t5+t6) - 3][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 3][ (-4*t5+t7)][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 3][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 3][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 3]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 3]))) + (coef4 * (((((A[ t5 % 2][ (-4*t5+t6) - 4][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 4][ (-4*t5+t7)][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 4][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 4][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 4]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 4])))));;
}
}
}
}
}
}
}
}
}
/* End of CLooG code */
gettimeofday(&end, 0);
ts_return = timeval_subtract(&result, &end, &start);
tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6);
min_tdiff = MIN(min_tdiff, tdiff);
printf("Rank 0 TEST# %d time: %f\n", test, tdiff);
}
PRINT_RESULTS(4, "constant")
#ifdef LIKWID_PERFMON
#pragma omp parallel
{
LIKWID_MARKER_STOP("calc");
}
LIKWID_MARKER_CLOSE;
#endif
// Free allocated arrays
for(i=0; i<Nz; i++){
for(j=0;j<Ny;j++){
free(A[0][i][j]);
free(A[1][i][j]);
free(roc2[i][j]);
}
free(A[0][i]);
free(A[1][i]);
free(roc2[i]);
}
free(A[0]);
free(A[1]);
free(roc2);
return 0;
}
|
irbuilder_for_unsigned_runtime.c
|
// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py UTC_ARGS: --function-signature --include-generated-funcs
// RUN: %clang_cc1 -fopenmp-enable-irbuilder -verify -fopenmp -fopenmp-version=45 -x c++ -triple x86_64-unknown-unknown -emit-llvm %s -o - | FileCheck %s
// expected-no-diagnostics
#ifndef HEADER
#define HEADER
// CHECK-LABEL: define {{.*}}@workshareloop_unsigned_runtime(
// CHECK-NEXT: [[ENTRY:.*]]:
// CHECK-NEXT: %[[A_ADDR:.+]] = alloca float*, align 8
// CHECK-NEXT: %[[B_ADDR:.+]] = alloca float*, align 8
// CHECK-NEXT: %[[C_ADDR:.+]] = alloca float*, align 8
// CHECK-NEXT: %[[D_ADDR:.+]] = alloca float*, align 8
// CHECK-NEXT: %[[I:.+]] = alloca i32, align 4
// CHECK-NEXT: %[[AGG_CAPTURED:.+]] = alloca %struct.anon, align 8
// CHECK-NEXT: %[[AGG_CAPTURED1:.+]] = alloca %struct.anon.0, align 4
// CHECK-NEXT: %[[DOTCOUNT_ADDR:.+]] = alloca i32, align 4
// CHECK-NEXT: %[[P_LASTITER:.+]] = alloca i32, align 4
// CHECK-NEXT: %[[P_LOWERBOUND:.+]] = alloca i32, align 4
// CHECK-NEXT: %[[P_UPPERBOUND:.+]] = alloca i32, align 4
// CHECK-NEXT: %[[P_STRIDE:.+]] = alloca i32, align 4
// CHECK-NEXT: store float* %[[A:.+]], float** %[[A_ADDR]], align 8
// CHECK-NEXT: store float* %[[B:.+]], float** %[[B_ADDR]], align 8
// CHECK-NEXT: store float* %[[C:.+]], float** %[[C_ADDR]], align 8
// CHECK-NEXT: store float* %[[D:.+]], float** %[[D_ADDR]], align 8
// CHECK-NEXT: store i32 33, i32* %[[I]], align 4
// CHECK-NEXT: %[[TMP0:.+]] = getelementptr inbounds %struct.anon, %struct.anon* %[[AGG_CAPTURED]], i32 0, i32 0
// CHECK-NEXT: store i32* %[[I]], i32** %[[TMP0]], align 8
// CHECK-NEXT: %[[TMP1:.+]] = getelementptr inbounds %struct.anon.0, %struct.anon.0* %[[AGG_CAPTURED1]], i32 0, i32 0
// CHECK-NEXT: %[[TMP2:.+]] = load i32, i32* %[[I]], align 4
// CHECK-NEXT: store i32 %[[TMP2]], i32* %[[TMP1]], align 4
// CHECK-NEXT: call void @__captured_stmt(i32* %[[DOTCOUNT_ADDR]], %struct.anon* %[[AGG_CAPTURED]])
// CHECK-NEXT: %[[DOTCOUNT:.+]] = load i32, i32* %[[DOTCOUNT_ADDR]], align 4
// CHECK-NEXT: br label %[[OMP_LOOP_PREHEADER:.+]]
// CHECK-EMPTY:
// CHECK-NEXT: [[OMP_LOOP_PREHEADER]]:
// CHECK-NEXT: store i32 1, i32* %[[P_LOWERBOUND]], align 4
// CHECK-NEXT: store i32 %[[DOTCOUNT]], i32* %[[P_UPPERBOUND]], align 4
// CHECK-NEXT: store i32 1, i32* %[[P_STRIDE]], align 4
// CHECK-NEXT: %[[OMP_GLOBAL_THREAD_NUM:.+]] = call i32 @__kmpc_global_thread_num(%struct.ident_t* @1)
// CHECK-NEXT: call void @__kmpc_dispatch_init_4u(%struct.ident_t* @1, i32 %[[OMP_GLOBAL_THREAD_NUM]], i32 37, i32 1, i32 %[[DOTCOUNT]], i32 1, i32 1)
// CHECK-NEXT: br label %[[OMP_LOOP_PREHEADER_OUTER_COND:.+]]
// CHECK-EMPTY:
// CHECK-NEXT: [[OMP_LOOP_HEADER:.*]]:
// CHECK-NEXT: %[[OMP_LOOP_IV:.+]] = phi i32 [ %[[LB:.+]], %[[OMP_LOOP_PREHEADER_OUTER_COND]] ], [ %[[OMP_LOOP_NEXT:.+]], %[[OMP_LOOP_INC:.+]] ]
// CHECK-NEXT: br label %[[OMP_LOOP_COND:.+]]
// CHECK-EMPTY:
// CHECK-NEXT: [[OMP_LOOP_COND]]:
// CHECK-NEXT: %[[UB:.+]] = load i32, i32* %[[P_UPPERBOUND]], align 4
// CHECK-NEXT: %[[OMP_LOOP_CMP:.+]] = icmp ult i32 %[[OMP_LOOP_IV]], %[[UB]]
// CHECK-NEXT: br i1 %[[OMP_LOOP_CMP]], label %[[OMP_LOOP_BODY:.+]], label %[[OMP_LOOP_PREHEADER_OUTER_COND]]
// CHECK-EMPTY:
// CHECK-NEXT: [[OMP_LOOP_BODY]]:
// CHECK-NEXT: call void @__captured_stmt.1(i32* %[[I]], i32 %[[OMP_LOOP_IV]], %struct.anon.0* %[[AGG_CAPTURED1]])
// CHECK-NEXT: %[[TMP3:.+]] = load float*, float** %[[B_ADDR]], align 8
// CHECK-NEXT: %[[TMP4:.+]] = load i32, i32* %[[I]], align 4
// CHECK-NEXT: %[[IDXPROM:.+]] = zext i32 %[[TMP4]] to i64
// CHECK-NEXT: %[[ARRAYIDX:.+]] = getelementptr inbounds float, float* %[[TMP3]], i64 %[[IDXPROM]]
// CHECK-NEXT: %[[TMP5:.+]] = load float, float* %[[ARRAYIDX]], align 4
// CHECK-NEXT: %[[TMP6:.+]] = load float*, float** %[[C_ADDR]], align 8
// CHECK-NEXT: %[[TMP7:.+]] = load i32, i32* %[[I]], align 4
// CHECK-NEXT: %[[IDXPROM2:.+]] = zext i32 %[[TMP7]] to i64
// CHECK-NEXT: %[[ARRAYIDX3:.+]] = getelementptr inbounds float, float* %[[TMP6]], i64 %[[IDXPROM2]]
// CHECK-NEXT: %[[TMP8:.+]] = load float, float* %[[ARRAYIDX3]], align 4
// CHECK-NEXT: %[[MUL:.+]] = fmul float %[[TMP5]], %[[TMP8]]
// CHECK-NEXT: %[[TMP9:.+]] = load float*, float** %[[D_ADDR]], align 8
// CHECK-NEXT: %[[TMP10:.+]] = load i32, i32* %[[I]], align 4
// CHECK-NEXT: %[[IDXPROM4:.+]] = zext i32 %[[TMP10]] to i64
// CHECK-NEXT: %[[ARRAYIDX5:.+]] = getelementptr inbounds float, float* %[[TMP9]], i64 %[[IDXPROM4]]
// CHECK-NEXT: %[[TMP11:.+]] = load float, float* %[[ARRAYIDX5]], align 4
// CHECK-NEXT: %[[MUL6:.+]] = fmul float %[[MUL]], %[[TMP11]]
// CHECK-NEXT: %[[TMP12:.+]] = load float*, float** %[[A_ADDR]], align 8
// CHECK-NEXT: %[[TMP13:.+]] = load i32, i32* %[[I]], align 4
// CHECK-NEXT: %[[IDXPROM7:.+]] = zext i32 %[[TMP13]] to i64
// CHECK-NEXT: %[[ARRAYIDX8:.+]] = getelementptr inbounds float, float* %[[TMP12]], i64 %[[IDXPROM7]]
// CHECK-NEXT: store float %[[MUL6]], float* %[[ARRAYIDX8]], align 4
// CHECK-NEXT: br label %[[OMP_LOOP_INC]]
// CHECK-EMPTY:
// CHECK-NEXT: [[OMP_LOOP_INC]]:
// CHECK-NEXT: %[[OMP_LOOP_NEXT]] = add nuw i32 %[[OMP_LOOP_IV]], 1
// CHECK-NEXT: br label %[[OMP_LOOP_HEADER]]
// CHECK-EMPTY:
// CHECK-NEXT: [[OMP_LOOP_EXIT:.*]]:
// CHECK-NEXT: %[[OMP_GLOBAL_THREAD_NUM9:.+]] = call i32 @__kmpc_global_thread_num(%struct.ident_t* @1)
// CHECK-NEXT: call void @__kmpc_barrier(%struct.ident_t* @2, i32 %[[OMP_GLOBAL_THREAD_NUM9]])
// CHECK-NEXT: br label %[[OMP_LOOP_AFTER:.+]]
// CHECK-EMPTY:
// CHECK-NEXT: [[OMP_LOOP_AFTER]]:
// CHECK-NEXT: ret void
// CHECK-EMPTY:
// CHECK-NEXT: [[OMP_LOOP_PREHEADER_OUTER_COND]]:
// CHECK-NEXT: %[[TMP14:.+]] = call i32 @__kmpc_dispatch_next_4u(%struct.ident_t* @1, i32 %[[OMP_GLOBAL_THREAD_NUM]], i32* %[[P_LASTITER]], i32* %[[P_LOWERBOUND]], i32* %[[P_UPPERBOUND]], i32* %[[P_STRIDE]])
// CHECK-NEXT: %[[TMP15:.+]] = icmp ne i32 %[[TMP14]], 0
// CHECK-NEXT: %[[TMP16:.+]] = load i32, i32* %[[P_LOWERBOUND]], align 4
// CHECK-NEXT: %[[LB]] = sub i32 %[[TMP16]], 1
// CHECK-NEXT: br i1 %[[TMP15]], label %[[OMP_LOOP_HEADER]], label %[[OMP_LOOP_EXIT]]
// CHECK-NEXT: }
extern "C" void workshareloop_unsigned_runtime(float *a, float *b, float *c, float *d) {
#pragma omp for schedule(runtime)
for (unsigned i = 33; i < 32000000; i += 7) {
a[i] = b[i] * c[i] * d[i];
}
}
#endif // HEADER
// CHECK-LABEL: define {{.*}}@__captured_stmt(
// CHECK-NEXT: [[ENTRY:.*]]:
// CHECK-NEXT: %[[DISTANCE_ADDR:.+]] = alloca i32*, align 8
// CHECK-NEXT: %[[__CONTEXT_ADDR:.+]] = alloca %struct.anon*, align 8
// CHECK-NEXT: %[[DOTSTART:.+]] = alloca i32, align 4
// CHECK-NEXT: %[[DOTSTOP:.+]] = alloca i32, align 4
// CHECK-NEXT: %[[DOTSTEP:.+]] = alloca i32, align 4
// CHECK-NEXT: store i32* %[[DISTANCE:.+]], i32** %[[DISTANCE_ADDR]], align 8
// CHECK-NEXT: store %struct.anon* %[[__CONTEXT:.+]], %struct.anon** %[[__CONTEXT_ADDR]], align 8
// CHECK-NEXT: %[[TMP0:.+]] = load %struct.anon*, %struct.anon** %[[__CONTEXT_ADDR]], align 8
// CHECK-NEXT: %[[TMP1:.+]] = getelementptr inbounds %struct.anon, %struct.anon* %[[TMP0]], i32 0, i32 0
// CHECK-NEXT: %[[TMP2:.+]] = load i32*, i32** %[[TMP1]], align 8
// CHECK-NEXT: %[[TMP3:.+]] = load i32, i32* %[[TMP2]], align 4
// CHECK-NEXT: store i32 %[[TMP3]], i32* %[[DOTSTART]], align 4
// CHECK-NEXT: store i32 32000000, i32* %[[DOTSTOP]], align 4
// CHECK-NEXT: store i32 7, i32* %[[DOTSTEP]], align 4
// CHECK-NEXT: %[[TMP4:.+]] = load i32, i32* %[[DOTSTART]], align 4
// CHECK-NEXT: %[[TMP5:.+]] = load i32, i32* %[[DOTSTOP]], align 4
// CHECK-NEXT: %[[CMP:.+]] = icmp ult i32 %[[TMP4]], %[[TMP5]]
// CHECK-NEXT: br i1 %[[CMP]], label %[[COND_TRUE:.+]], label %[[COND_FALSE:.+]]
// CHECK-EMPTY:
// CHECK-NEXT: [[COND_TRUE]]:
// CHECK-NEXT: %[[TMP6:.+]] = load i32, i32* %[[DOTSTOP]], align 4
// CHECK-NEXT: %[[TMP7:.+]] = load i32, i32* %[[DOTSTART]], align 4
// CHECK-NEXT: %[[SUB:.+]] = sub i32 %[[TMP6]], %[[TMP7]]
// CHECK-NEXT: %[[TMP8:.+]] = load i32, i32* %[[DOTSTEP]], align 4
// CHECK-NEXT: %[[SUB1:.+]] = sub i32 %[[TMP8]], 1
// CHECK-NEXT: %[[ADD:.+]] = add i32 %[[SUB]], %[[SUB1]]
// CHECK-NEXT: %[[TMP9:.+]] = load i32, i32* %[[DOTSTEP]], align 4
// CHECK-NEXT: %[[DIV:.+]] = udiv i32 %[[ADD]], %[[TMP9]]
// CHECK-NEXT: br label %[[COND_END:.+]]
// CHECK-EMPTY:
// CHECK-NEXT: [[COND_FALSE]]:
// CHECK-NEXT: br label %[[COND_END]]
// CHECK-EMPTY:
// CHECK-NEXT: [[COND_END]]:
// CHECK-NEXT: %[[COND:.+]] = phi i32 [ %[[DIV]], %[[COND_TRUE]] ], [ 0, %[[COND_FALSE]] ]
// CHECK-NEXT: %[[TMP10:.+]] = load i32*, i32** %[[DISTANCE_ADDR]], align 8
// CHECK-NEXT: store i32 %[[COND]], i32* %[[TMP10]], align 4
// CHECK-NEXT: ret void
// CHECK-NEXT: }
// CHECK-LABEL: define {{.*}}@__captured_stmt.1(
// CHECK-NEXT: [[ENTRY:.*]]:
// CHECK-NEXT: %[[LOOPVAR_ADDR:.+]] = alloca i32*, align 8
// CHECK-NEXT: %[[LOGICAL_ADDR:.+]] = alloca i32, align 4
// CHECK-NEXT: %[[__CONTEXT_ADDR:.+]] = alloca %struct.anon.0*, align 8
// CHECK-NEXT: store i32* %[[LOOPVAR:.+]], i32** %[[LOOPVAR_ADDR]], align 8
// CHECK-NEXT: store i32 %[[LOGICAL:.+]], i32* %[[LOGICAL_ADDR]], align 4
// CHECK-NEXT: store %struct.anon.0* %[[__CONTEXT:.+]], %struct.anon.0** %[[__CONTEXT_ADDR]], align 8
// CHECK-NEXT: %[[TMP0:.+]] = load %struct.anon.0*, %struct.anon.0** %[[__CONTEXT_ADDR]], align 8
// CHECK-NEXT: %[[TMP1:.+]] = getelementptr inbounds %struct.anon.0, %struct.anon.0* %[[TMP0]], i32 0, i32 0
// CHECK-NEXT: %[[TMP2:.+]] = load i32, i32* %[[TMP1]], align 4
// CHECK-NEXT: %[[TMP3:.+]] = load i32, i32* %[[LOGICAL_ADDR]], align 4
// CHECK-NEXT: %[[MUL:.+]] = mul i32 7, %[[TMP3]]
// CHECK-NEXT: %[[ADD:.+]] = add i32 %[[TMP2]], %[[MUL]]
// CHECK-NEXT: %[[TMP4:.+]] = load i32*, i32** %[[LOOPVAR_ADDR]], align 8
// CHECK-NEXT: store i32 %[[ADD]], i32* %[[TMP4]], align 4
// CHECK-NEXT: ret void
// CHECK-NEXT: }
// CHECK: ![[META0:[0-9]+]] = !{i32 1, !"wchar_size", i32 4}
// CHECK: ![[META1:[0-9]+]] = !{i32 7, !"openmp", i32 45}
// CHECK: ![[META2:[0-9]+]] =
|
queue.h
|
// -*- C++ -*-
// Copyright (C) 2007-2018 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library is free
// software; you can redistribute it and/or modify it under the terms
// of the GNU General Public License as published by the Free Software
// Foundation; either version 3, or (at your option) any later
// version.
// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
// Under Section 7 of GPL version 3, you are granted additional
// permissions described in the GCC Runtime Library Exception, version
// 3.1, as published by the Free Software Foundation.
// You should have received a copy of the GNU General Public License and
// a copy of the GCC Runtime Library Exception along with this program;
// see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
// <http://www.gnu.org/licenses/>.
/** @file parallel/queue.h
* @brief Lock-free double-ended queue.
* This file is a GNU parallel extension to the Standard C++ Library.
*/
// Written by Johannes Singler.
#ifndef _GLIBCXX_PARALLEL_QUEUE_H
#define _GLIBCXX_PARALLEL_QUEUE_H 1
#include <parallel/types.h>
#include <parallel/base.h>
#include <parallel/compatibility.h>
/** @brief Decide whether to declare certain variable volatile in this file. */
#define _GLIBCXX_VOLATILE volatile
namespace __gnu_parallel
{
/**@brief Double-ended queue of bounded size, allowing lock-free
* atomic access. push_front() and pop_front() must not be called
* concurrently to each other, while pop_back() can be called
* concurrently at all times.
* @c empty(), @c size(), and @c top() are intentionally not provided.
* Calling them would not make sense in a concurrent setting.
* @param _Tp Contained element type. */
template<typename _Tp>
class _RestrictedBoundedConcurrentQueue
{
private:
/** @brief Array of elements, seen as cyclic buffer. */
_Tp* _M_base;
/** @brief Maximal number of elements contained at the same time. */
_SequenceIndex _M_max_size;
/** @brief Cyclic __begin and __end pointers contained in one
atomically changeable value. */
_GLIBCXX_VOLATILE _CASable _M_borders;
public:
/** @brief Constructor. Not to be called concurrent, of course.
* @param __max_size Maximal number of elements to be contained. */
_RestrictedBoundedConcurrentQueue(_SequenceIndex __max_size)
{
_M_max_size = __max_size;
_M_base = new _Tp[__max_size];
_M_borders = __encode2(0, 0);
#pragma omp flush
}
/** @brief Destructor. Not to be called concurrent, of course. */
~_RestrictedBoundedConcurrentQueue()
{ delete[] _M_base; }
/** @brief Pushes one element into the queue at the front end.
* Must not be called concurrently with pop_front(). */
void
push_front(const _Tp& __t)
{
_CASable __former_borders = _M_borders;
int __former_front, __former_back;
__decode2(__former_borders, __former_front, __former_back);
*(_M_base + __former_front % _M_max_size) = __t;
#if _GLIBCXX_PARALLEL_ASSERTIONS
// Otherwise: front - back > _M_max_size eventually.
_GLIBCXX_PARALLEL_ASSERT(((__former_front + 1) - __former_back)
<= _M_max_size);
#endif
__fetch_and_add(&_M_borders, __encode2(1, 0));
}
/** @brief Pops one element from the queue at the front end.
* Must not be called concurrently with pop_front(). */
bool
pop_front(_Tp& __t)
{
int __former_front, __former_back;
#pragma omp flush
__decode2(_M_borders, __former_front, __former_back);
while (__former_front > __former_back)
{
// Chance.
_CASable __former_borders = __encode2(__former_front,
__former_back);
_CASable __new_borders = __encode2(__former_front - 1,
__former_back);
if (__compare_and_swap(&_M_borders, __former_borders,
__new_borders))
{
__t = *(_M_base + (__former_front - 1) % _M_max_size);
return true;
}
#pragma omp flush
__decode2(_M_borders, __former_front, __former_back);
}
return false;
}
/** @brief Pops one element from the queue at the front end.
* Must not be called concurrently with pop_front(). */
bool
pop_back(_Tp& __t) //queue behavior
{
int __former_front, __former_back;
#pragma omp flush
__decode2(_M_borders, __former_front, __former_back);
while (__former_front > __former_back)
{
// Chance.
_CASable __former_borders = __encode2(__former_front,
__former_back);
_CASable __new_borders = __encode2(__former_front,
__former_back + 1);
if (__compare_and_swap(&_M_borders, __former_borders,
__new_borders))
{
__t = *(_M_base + __former_back % _M_max_size);
return true;
}
#pragma omp flush
__decode2(_M_borders, __former_front, __former_back);
}
return false;
}
};
} //namespace __gnu_parallel
#undef _GLIBCXX_VOLATILE
#endif /* _GLIBCXX_PARALLEL_QUEUE_H */
|
asaxpy.c
|
/**
* @file asaxpy.c
* @brief Function definition for performing the \c saxpy operation on accelerator.
*
* This source file contains function definition for the \c saxpy operation,
* which is defined as:
*
* y := a * x + y
*
* where:
*
* - a is a scalar.
* - x and y are single-precision vectors each with n elements.
*
* @author Xin Wu (PC²)
* @date 05.04.2020
* @copyright CC BY-SA 2.0
*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <omp.h>
#include <hip/hip_runtime.h>
#include <hipblas.h>
#include "wtcalc.h"
#include "asaxpy.h"
void asaxpy(const int n,
const float a,
const float *x,
float *y,
const int ial)
{
hipblasHandle_t handle;
float alfa = a,
*x_dev = NULL,
*y_dev = NULL;
struct timespec rt[2];
int m = (n >> 4);
switch (ial) {
case 0:
/*
* - <<<2^7 , 2^7 >>>, auto scheduling
*/
#pragma omp target data device(0) map(to:a, n, x[0:n]) map(tofrom:y[0:n])
{
clock_gettime(CLOCK_REALTIME, rt + 0);
#pragma omp target teams distribute parallel for device(0) \
num_teams(128) num_threads(128) dist_schedule(static, 128) shared(a, n, x, y)
for (int i = 0; i < n; ++i) {
y[i] = a * x[i] + y[i];
}
clock_gettime(CLOCK_REALTIME, rt + 1);
}
break;
case 1:
/*
* - <<<2^16, 2^10>>>, manual scheduling
*/
#pragma omp target data device(0) \
map(to:a, n, x[0:n]) map(tofrom:y[0:n])
{
clock_gettime(CLOCK_REALTIME, rt + 0);
#pragma omp target teams distribute parallel for device(0) \
num_teams(65536) num_threads(1024) dist_schedule(static, 1024) shared(a, n, x, y)
for (int i = 0; i < n; ++i) {
y[i] = a * x[i] + y[i];
}
clock_gettime(CLOCK_REALTIME, rt + 1);
}
break;
case 2:
/*
* - <<<2^15, 2^7 >>>, manual scheduling, 16x loop unrolling (2^15*2^7*16==2^26)
*/
#pragma omp target data device(0) \
map(to:a, m, x[0:n]) map(tofrom:y[0:n])
{
clock_gettime(CLOCK_REALTIME, rt + 0);
#pragma omp target teams distribute parallel for device(0) \
num_teams(65536/2) num_threads(128) dist_schedule(static, 128) shared(a, m, x, y)
for (int i = 0; i < m; ++i) {
y[i ] = a * x[i ] + y[i ];
y[i + m] = a * x[i + m] + y[i + m];
y[i + 0x2 * m] = a * x[i + 0x2 * m] + y[i + 0x2 * m];
y[i + 0x3 * m] = a * x[i + 0x3 * m] + y[i + 0x3 * m];
y[i + 0x4 * m] = a * x[i + 0x4 * m] + y[i + 0x4 * m];
y[i + 0x5 * m] = a * x[i + 0x5 * m] + y[i + 0x5 * m];
y[i + 0x6 * m] = a * x[i + 0x6 * m] + y[i + 0x6 * m];
y[i + 0x7 * m] = a * x[i + 0x7 * m] + y[i + 0x7 * m];
y[i + 0x8 * m] = a * x[i + 0x8 * m] + y[i + 0x8 * m];
y[i + 0x9 * m] = a * x[i + 0x9 * m] + y[i + 0x9 * m];
y[i + 0xa * m] = a * x[i + 0xa * m] + y[i + 0xa * m];
y[i + 0xb * m] = a * x[i + 0xb * m] + y[i + 0xb * m];
y[i + 0xc * m] = a * x[i + 0xc * m] + y[i + 0xc * m];
y[i + 0xd * m] = a * x[i + 0xd * m] + y[i + 0xd * m];
y[i + 0xe * m] = a * x[i + 0xe * m] + y[i + 0xe * m];
y[i + 0xf * m] = a * x[i + 0xf * m] + y[i + 0xf * m];
}
clock_gettime(CLOCK_REALTIME, rt + 1);
}
break;
case 3:
/*
* - <<<2^12, 2^7 >>>, auto scheduling, 16x loop unrolling
*/
#pragma omp target data device(0) \
map(to:a, m, x[0:n]) map(tofrom:y[0:n])
{
clock_gettime(CLOCK_REALTIME, rt + 0);
#pragma omp target teams distribute parallel for device(0) \
num_teams(4096) num_threads(128) dist_schedule(static, 128) shared(a, m, x, y)
for (int i = 0; i < m; ++i) {
y[i ] = a * x[i ] + y[i ];
y[i + m] = a * x[i + m] + y[i + m];
y[i + 0x2 * m] = a * x[i + 0x2 * m] + y[i + 0x2 * m];
y[i + 0x3 * m] = a * x[i + 0x3 * m] + y[i + 0x3 * m];
y[i + 0x4 * m] = a * x[i + 0x4 * m] + y[i + 0x4 * m];
y[i + 0x5 * m] = a * x[i + 0x5 * m] + y[i + 0x5 * m];
y[i + 0x6 * m] = a * x[i + 0x6 * m] + y[i + 0x6 * m];
y[i + 0x7 * m] = a * x[i + 0x7 * m] + y[i + 0x7 * m];
y[i + 0x8 * m] = a * x[i + 0x8 * m] + y[i + 0x8 * m];
y[i + 0x9 * m] = a * x[i + 0x9 * m] + y[i + 0x9 * m];
y[i + 0xa * m] = a * x[i + 0xa * m] + y[i + 0xa * m];
y[i + 0xb * m] = a * x[i + 0xb * m] + y[i + 0xb * m];
y[i + 0xc * m] = a * x[i + 0xc * m] + y[i + 0xc * m];
y[i + 0xd * m] = a * x[i + 0xd * m] + y[i + 0xd * m];
y[i + 0xe * m] = a * x[i + 0xe * m] + y[i + 0xe * m];
y[i + 0xf * m] = a * x[i + 0xf * m] + y[i + 0xf * m];
}
clock_gettime(CLOCK_REALTIME, rt + 1);
}
break;
case 4:
/*
* - <<<2^16, 2^9>>>:
* * de-linearize the vector (convert the vector to matrix)
* * collapse the ji-loop
* * 2x i-loop unrolling
*/
#pragma omp target data device(0) \
map(to:a, x[0:n]) map(tofrom:y[0:n])
{
clock_gettime(CLOCK_REALTIME, rt + 0);
#pragma omp target teams distribute parallel for device(0) \
num_teams(65536) num_threads(512) dist_schedule(static, 512) \
collapse(2) shared(a, x, y)
for (int j = 0; j < 65536; ++j) {
for (int i = 0; i < 512; ++i) { /* 2x i-loop unrolling */
y[j * 1024 + i ] += a * x[j * 1024 + i ];
y[j * 1024 + i + 512] += a * x[j * 1024 + i + 512];
}
}
clock_gettime(CLOCK_REALTIME, rt + 1);
}
break;
default:
/*
* hipblasSaxpy in HIPBLAS
*/
if (HIPBLAS_STATUS_SUCCESS != hipblasCreate(&handle)) {
printf("error: initialization (HIPBLAS)\n");
hipblasDestroy(handle);
exit(EXIT_FAILURE);
}
if (hipSuccess != hipMalloc((void **) &x_dev, sizeof(*x) * n) ||
hipSuccess != hipMalloc((void **) &y_dev, sizeof(*y) * n)) {
printf("error: memory allocation (HIP)\n");
hipFree(x_dev); hipFree(y_dev);
hipblasDestroy(handle);
exit(EXIT_FAILURE);
}
if (HIPBLAS_STATUS_SUCCESS != hipblasSetVector(n, sizeof(*x), x, 1, x_dev, 1) ||
HIPBLAS_STATUS_SUCCESS != hipblasSetVector(n, sizeof(*y), y, 1, y_dev, 1)) {
printf("error: host --> accl (HIPBLAS)\n");
hipFree(x_dev); hipFree(y_dev);
hipblasDestroy(handle);
exit(EXIT_FAILURE);
}
clock_gettime(CLOCK_REALTIME, rt + 0);
if (HIPBLAS_STATUS_SUCCESS != hipblasSaxpy(handle, n, &alfa, x_dev, 1, y_dev, 1)) {
printf("error: hipblasSaxpy (HIPBLAS)\n");
hipFree(x_dev); hipFree(y_dev);
hipblasDestroy(handle);
exit(EXIT_FAILURE);
}
if (hipSuccess != hipDeviceSynchronize()) {
printf("error: device synchronization (HIP)\n");
hipFree(x_dev); hipFree(y_dev);
hipblasDestroy(handle);
exit(EXIT_FAILURE);
}
clock_gettime(CLOCK_REALTIME, rt + 1);
if (HIPBLAS_STATUS_SUCCESS != hipblasGetVector(n, sizeof(*y), y_dev, 1, y, 1)) {
printf("error: accl --> host (HIPBLAS)\n");
hipFree(x_dev); hipFree(y_dev);
hipblasDestroy(handle);
exit(EXIT_FAILURE);
}
hipFree(x_dev); hipFree(y_dev);
hipblasDestroy(handle);
break;
} /* end switch (ial) */
if (wtcalc >= 0.0) {
wtcalc += (rt[1].tv_sec - rt[0].tv_sec) + 1.0e-9 * (rt[1].tv_nsec - rt[0].tv_nsec);
}
}
|
modifier_view.h
|
// ==========================================================================
// SeqAn - The Library for Sequence Analysis
// ==========================================================================
// Copyright (c) 2006-2015, Knut Reinert, FU Berlin
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of Knut Reinert or the FU Berlin nor the names of
// its contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL KNUT REINERT OR THE FU BERLIN 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.
//
// ==========================================================================
// Author: David Weese <[email protected]>
// Author: Manuel Holtgrewe <[email protected]>
// ==========================================================================
// TODO(holtgrew): Split into modified_string_mod_view.h and modified_iterator_mod_view.h.
// TODO(holtgrew): Move out convert()
#ifndef SEQAN_MODIFIER_MODIFIER_VIEW_H_
#define SEQAN_MODIFIER_MODIFIER_VIEW_H_
namespace seqan
{
// ==========================================================================
// Forwards
// ==========================================================================
// ==========================================================================
// Classes
// ==========================================================================
// --------------------------------------------------------------------------
// Class ModView
// --------------------------------------------------------------------------
/*!
* @class ModViewModifiedIterator
* @extends ModifiedIterator
* @headerfile <seqan/modifier.h>
*
* @brief Transforms the character of a host using a custom functor.
*
* @signature template <typename THost, typename TFunctor>
* class ModifiedIterator<THost, ModView<TFunctor> >;
*
* @tparam THost The host iterator.
* @tparam TFunctor A unary functor type.
*/
/*!
* @class ModViewModifiedString
* @extends ModifiedString
* @headerfile <seqan/modifier.h>
*
* @brief Transforms the character of a host using a custom functor.
*
* @signature template <typename THost, typename TFunctor>
* class ModifiedString<THost, ModView<TFunctor> >;
*
* @tparam THost The host iterator.
* @tparam TFunctor A unary functor type.
*/
template <typename TFunctor>
struct ModView {};
template <typename TFunctor>
struct ModViewCargo
{
TFunctor func;
ModViewCargo() : func()
{}
};
template <typename THost, typename TFunctor>
class ModifiedIterator<THost, ModView<TFunctor> >
{
public:
typedef typename Cargo<ModifiedIterator>::Type TCargo_;
THost _host;
TCargo_ _cargo;
mutable typename Value<ModifiedIterator>::Type tmp_value;
ModifiedIterator() : _host(), tmp_value()
{}
template <typename TOtherHost>
ModifiedIterator(ModifiedIterator<TOtherHost, ModView<TFunctor> > & origin) :
_host(origin._host), _cargo(origin._cargo), tmp_value()
{}
explicit
ModifiedIterator(THost const & host) :
_host(host), tmp_value()
{}
ModifiedIterator(THost const & host, TFunctor const & functor):
_host(host), tmp_value()
{
cargo(*this).func = functor;
}
};
// --------------------------------------------------------------------------
// Class ModifiedString
// --------------------------------------------------------------------------
template <typename THost, typename TFunctor>
class ModifiedString<THost, ModView<TFunctor> >
{
public:
typedef typename Pointer_<THost>::Type THostPointer_;
typedef typename Cargo<ModifiedString>::Type TCargo_;
mutable THostPointer_ _host;
TCargo_ _cargo;
mutable typename Value<ModifiedString>::Type tmp_value;
// Default constructor.
ModifiedString() : _host(), tmp_value()
{}
// Construct with the actual host.
explicit
ModifiedString(typename Parameter_<THost>::Type host):
_host(_toPointer(host)), tmp_value()
{}
// Construct with the functor.
explicit
ModifiedString(TFunctor const & functor):
_host(), tmp_value()
{
cargo(*this).func = functor;
}
// Constructor for creating a ModifiedString with const host from a non-const host.
template <typename THost_>
explicit
ModifiedString(THost_ & host,
SEQAN_CTOR_ENABLE_IF(IsConstructible<THost, THost_>)) :
_host(_toPointer(host)), tmp_value()
{
ignoreUnusedVariableWarning(dummy);
}
// Construct with the actual host; variant with functor.
ModifiedString(typename Parameter_<THost>::Type host, TFunctor const & functor) :
_host(_toPointer(host)), tmp_value()
{
cargo(*this).func = functor;
}
// Constructor for creating a ModifiedString with const host with a non-const host; variant with functor.
template <typename THost_>
explicit
ModifiedString(THost_ & host,
TFunctor const & functor,
SEQAN_CTOR_ENABLE_IF(IsConstructible<THost, THost_>)) :
_host(_toPointer(host)), tmp_value()
{
ignoreUnusedVariableWarning(dummy);
cargo(*this).func = functor;
}
#ifdef SEQAN_CXX11_STANDARD
// Constructor for innermost type; hand down to _host which is a ModifiedString itself.
template <typename THost_>
explicit
ModifiedString(THost_ && host,
SEQAN_CTOR_ENABLE_IF(IsAnInnerHost<
typename RemoveReference<THost>::Type,
typename RemoveReference<THost_>::Type >)) :
_host(std::forward<THost_>(host)), tmp_value()
{
ignoreUnusedVariableWarning(dummy);
}
// Constructor for innermost type; hand down to _host which is a ModifiedString itself. Variant with functor.
template <typename THost_>
explicit
ModifiedString(THost_ && host,
TFunctor const & functor,
SEQAN_CTOR_ENABLE_IF(IsAnInnerHost<
typename RemoveReference<THost>::Type,
typename RemoveReference<THost_>::Type >)) :
_host(std::forward<THost_>(host)), tmp_value()
{
ignoreUnusedVariableWarning(dummy);
cargo(*this).func = functor;
}
#else
// Constructor for innermost type; hand down to _host which is a ModifiedString itself. Non-const variant.
template <typename THost_>
explicit
ModifiedString(THost_ & host,
SEQAN_CTOR_ENABLE_IF(IsAnInnerHost<THost, THost_>)) :
_host(host), tmp_value()
{
ignoreUnusedVariableWarning(dummy);
}
// Constructor for innermost type; hand down to _host which is a ModifiedString itself. Non-const variant.
template <typename THost_>
explicit
ModifiedString(THost_ const & host,
SEQAN_CTOR_ENABLE_IF(IsAnInnerHost<THost, THost_ const>)) :
_host(host), tmp_value()
{
ignoreUnusedVariableWarning(dummy);
}
// Constructor for innermost type; hand down to _host which is a ModifiedString itself. Non-const variant with
// functor.
template <typename THost_>
explicit
ModifiedString(THost_ & host,
TFunctor const & functor,
SEQAN_CTOR_ENABLE_IF(IsAnInnerHost<THost, THost_>)) :
_host(host), tmp_value()
{
ignoreUnusedVariableWarning(dummy);
cargo(*this).func = functor;
}
// Constructor for innermost type; hand down to _host which is a ModifiedString itself. Non-const variant with
// functor.
template <typename THost_>
explicit
ModifiedString(THost_ const & host,
TFunctor const & functor,
SEQAN_CTOR_ENABLE_IF(IsAnInnerHost<THost, THost_ const>)) :
_host(host), tmp_value()
{
ignoreUnusedVariableWarning(dummy);
cargo(*this).func = functor;
}
#endif
template <typename TPos>
inline typename Reference<ModifiedString>::Type
operator[](TPos pos)
{
return value(*this, pos);
}
template <typename TPos>
inline typename Reference<ModifiedString const>::Type
operator[](TPos pos) const
{
return value(*this, pos);
}
};
// ==========================================================================
// Metafunctions
// ==========================================================================
// --------------------------------------------------------------------------
// Metafunction Cargo [ModifiedIterator]
// --------------------------------------------------------------------------
template <typename THost, typename TFunctor>
struct Cargo<ModifiedIterator<THost, ModView<TFunctor> > >
{
typedef ModViewCargo<TFunctor> Type;
};
// --------------------------------------------------------------------------
// Metafunction Value [ModifiedIterator]
// --------------------------------------------------------------------------
template <typename THost, typename TFunctor>
struct Value<ModifiedIterator<THost, ModView<TFunctor> > >
{
typedef typename TFunctor::result_type TResult_;
typedef typename RemoveConst_<TResult_>::Type Type;
};
template <typename THost, typename TFunctor>
struct Value<ModifiedIterator<THost, ModView<TFunctor> > const> :
Value<ModifiedIterator<THost, ModView<TFunctor> > >
{};
// --------------------------------------------------------------------------
// Metafunction GetValue [ModifiedIterator]
// --------------------------------------------------------------------------
template <typename THost, typename TFunctor>
struct GetValue<ModifiedIterator<THost, ModView<TFunctor> > > :
Value<ModifiedIterator<THost, ModView<TFunctor> > >
{};
template <typename THost, typename TFunctor>
struct GetValue<ModifiedIterator<THost, ModView<TFunctor> > const> :
Value<ModifiedIterator<THost, ModView<TFunctor> > >
{};
// --------------------------------------------------------------------------
// Metafunction Reference [ModifiedIterator]
// --------------------------------------------------------------------------
template <typename THost, typename TFunctor>
struct Reference<ModifiedIterator<THost, ModView<TFunctor> > > :
Value<ModifiedIterator<THost, ModView<TFunctor> > >
{};
template <typename THost, typename TFunctor>
struct Reference<ModifiedIterator<THost, ModView<TFunctor> > const> :
Value<ModifiedIterator<THost, ModView<TFunctor> > >
{};
// NOTE(h-2): ModView element access is always by copy never by reference
// This is a workaround for dangling references to the stack when
// combining infixes and modified views, more precisely:
// if you iterate over an infix of a modview then value() on the iterator
// will return reference to the tmp_value inside the moditerator
// which might have been destructed.
// This is a more general problem that stems from the fact that
// "virtual strings" of the same type (infixes, modstrings) can be
// automatically compacted into one layer, but combinations cannot.
// This workaround happens in ModView, because it is used less frequently
// then Infixes.
// --------------------------------------------------------------------------
// Metafunction Cargo [ModifiedString]
// --------------------------------------------------------------------------
template <typename THost, typename TFunctor>
struct Cargo< ModifiedString<THost, ModView<TFunctor> > >
{
typedef ModViewCargo<TFunctor> Type;
};
// ==========================================================================
// Functions
// ==========================================================================
// --------------------------------------------------------------------------
// Function getValue() [ModifiedIterator]
// --------------------------------------------------------------------------
template <typename THost, typename TFunctor>
inline typename GetValue<ModifiedIterator<THost, ModView<TFunctor> > >::Type
getValue(ModifiedIterator<THost, ModView<TFunctor> > & me)
{
return cargo(me).func(getValue(host(me)));
}
template <typename THost, typename TFunctor>
inline typename GetValue<ModifiedIterator<THost, ModView<TFunctor> > const>::Type
getValue(ModifiedIterator<THost, ModView<TFunctor> > const & me)
{
return cargo(me).func(getValue(host(me)));
}
// --------------------------------------------------------------------------
// Function value() [ModifiedIterator]
// --------------------------------------------------------------------------
template <typename THost, typename TFunctor>
inline typename GetValue<ModifiedIterator<THost, ModView<TFunctor> > >::Type
value(ModifiedIterator<THost, ModView<TFunctor> > & me)
{
return getValue(me);
}
template <typename THost, typename TFunctor>
inline typename GetValue<ModifiedIterator<THost, ModView<TFunctor> > const>::Type
value(ModifiedIterator<THost, ModView<TFunctor> > const & me)
{
return getValue(me);
}
// --------------------------------------------------------------------------
// Function getValue() [ModifiedString]
// --------------------------------------------------------------------------
template <typename THost, typename TFunctor, typename TPos>
inline typename GetValue<ModifiedString<THost, ModView<TFunctor> > >::Type
getValue(ModifiedString<THost, ModView<TFunctor> > & me, TPos pos)
{
return cargo(me).func(getValue(host(me), pos));
}
template <typename THost, typename TFunctor, typename TPos>
inline typename GetValue<ModifiedString<THost, ModView<TFunctor> > const>::Type
getValue(ModifiedString<THost, ModView<TFunctor> > const & me, TPos pos)
{
return cargo(me).func(getValue(host(me), pos));
}
// --------------------------------------------------------------------------
// Function value() [ModifiedString]
// --------------------------------------------------------------------------
template <typename THost, typename TFunctor, typename TPos>
inline typename GetValue<ModifiedString<THost, ModView<TFunctor> > >::Type
value(ModifiedString<THost, ModView<TFunctor> > & me, TPos pos)
{
return getValue(me, pos);
}
template <typename THost, typename TFunctor, typename TPos>
inline typename GetValue<ModifiedString<THost, ModView<TFunctor> > const>::Type
value(ModifiedString<THost, ModView<TFunctor> > const & me, TPos pos)
{
return getValue(me, pos);
}
// --------------------------------------------------------------------------
// Function assignModViewFunctor()
// --------------------------------------------------------------------------
template <typename THost, typename TFunctor>
inline void
assignModViewFunctor(ModifiedString<THost, ModView<TFunctor> > & me, TFunctor const & functor)
{
cargo(me).func = functor;
}
// --------------------------------------------------------------------------
// Function convert()
// --------------------------------------------------------------------------
template < typename TSequence, typename TFunctor >
inline void
convert(TSequence & sequence, TFunctor const &F)
{
#if defined (_OPENMP) && defined (SEQAN_PARALLEL)
// OpenMP does not support for loop with iterators. Therefore use index variables.
typedef typename Position<TSequence>::Type TPos;
typedef typename MakeSigned_<TPos>::Type TSignedPos;
#pragma omp parallel for if(length(sequence) > 1000000)
for(TSignedPos p = 0; p < (TSignedPos)length(sequence); ++p)
sequence[p] = F(sequence[p]);
#else
typedef typename Iterator<TSequence, Standard>::Type TIter;
TIter it = begin(sequence, Standard());
TIter itEnd = end(sequence, Standard());
for(; it != itEnd; ++it)
*it = F(*it);
#endif
}
template < typename TSequence, typename TFunctor >
inline void
convert(TSequence const & sequence, TFunctor const &F)
{
#if defined (_OPENMP) && defined (SEQAN_PARALLEL)
// OpenMP does not support for loop with iterators. Therefore use index variables.
typedef typename Position<TSequence>::Type TPos;
typedef typename MakeSigned_<TPos>::Type TSignedPos;
#pragma omp parallel for if(length(sequence) > 1000000)
for(TSignedPos p = 0; p < (TSignedPos)length(sequence); ++p)
sequence[p] = F(sequence[p]);
#else
typedef typename Iterator<TSequence const, Standard>::Type TIter;
TIter it = begin(sequence, Standard());
TIter itEnd = end(sequence, Standard());
for(; it != itEnd; ++it)
*it = F(*it);
#endif
}
} // namespace seqan
#endif // SEQAN_MODIFIER_MODIFIER_VIEW_H_
|
resample.c
|
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% RRRR EEEEE SSSSS AAA M M PPPP L EEEEE %
% R R E SS A A MM MM P P L E %
% RRRR EEE SSS AAAAA M M M PPPP L EEE %
% R R E SS A A M M P L E %
% R R EEEEE SSSSS A A M M P LLLLL EEEEE %
% %
% %
% MagickCore Pixel Resampling Methods %
% %
% Software Design %
% Cristy %
% Anthony Thyssen %
% August 2007 %
% %
% %
% Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% http://www.imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "MagickCore/studio.h"
#include "MagickCore/artifact.h"
#include "MagickCore/color-private.h"
#include "MagickCore/cache.h"
#include "MagickCore/draw.h"
#include "MagickCore/exception-private.h"
#include "MagickCore/gem.h"
#include "MagickCore/image.h"
#include "MagickCore/image-private.h"
#include "MagickCore/log.h"
#include "MagickCore/magick.h"
#include "MagickCore/memory_.h"
#include "MagickCore/pixel.h"
#include "MagickCore/pixel-accessor.h"
#include "MagickCore/quantum.h"
#include "MagickCore/random_.h"
#include "MagickCore/resample.h"
#include "MagickCore/resize.h"
#include "MagickCore/resize-private.h"
#include "MagickCore/resource_.h"
#include "MagickCore/token.h"
#include "MagickCore/transform.h"
#include "MagickCore/signature-private.h"
#include "MagickCore/utility.h"
#include "MagickCore/utility-private.h"
#include "MagickCore/option.h"
/*
EWA Resampling Options
*/
/* select ONE resampling method */
#define EWA 1 /* Normal EWA handling - raw or clamped */
/* if 0 then use "High Quality EWA" */
#define EWA_CLAMP 1 /* EWA Clamping from Nicolas Robidoux */
#define FILTER_LUT 1 /* Use a LUT rather then direct filter calls */
/* output debugging information */
#define DEBUG_ELLIPSE 0 /* output ellipse info for debug */
#define DEBUG_HIT_MISS 0 /* output hit/miss pixels (as gnuplot commands) */
#define DEBUG_NO_PIXEL_HIT 0 /* Make pixels that fail to hit anything - RED */
#if ! FILTER_DIRECT
#define WLUT_WIDTH 1024 /* size of the filter cache */
#endif
/*
Typedef declarations.
*/
struct _ResampleFilter
{
CacheView
*view;
Image
*image;
ExceptionInfo
*exception;
MagickBooleanType
debug;
/* Information about image being resampled */
ssize_t
image_area;
PixelInterpolateMethod
interpolate;
VirtualPixelMethod
virtual_pixel;
FilterType
filter;
/* processing settings needed */
MagickBooleanType
limit_reached,
do_interpolate,
average_defined;
PixelInfo
average_pixel;
/* current ellipitical area being resampled around center point */
double
A, B, C,
Vlimit, Ulimit, Uwidth, slope;
#if FILTER_LUT
/* LUT of weights for filtered average in elliptical area */
double
filter_lut[WLUT_WIDTH];
#else
/* Use a Direct call to the filter functions */
ResizeFilter
*filter_def;
double
F;
#endif
/* the practical working support of the filter */
double
support;
size_t
signature;
};
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% A c q u i r e R e s a m p l e I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AcquireResampleFilter() initializes the information resample needs do to a
% scaled lookup of a color from an image, using area sampling.
%
% The algorithm is based on a Elliptical Weighted Average, where the pixels
% found in a large elliptical area is averaged together according to a
% weighting (filter) function. For more details see "Fundamentals of Texture
% Mapping and Image Warping" a master's thesis by Paul.S.Heckbert, June 17,
% 1989. Available for free from, http://www.cs.cmu.edu/~ph/
%
% As EWA resampling (or any sort of resampling) can require a lot of
% calculations to produce a distorted scaling of the source image for each
% output pixel, the ResampleFilter structure generated holds that information
% between individual image resampling.
%
% This function will make the appropriate AcquireCacheView() calls
% to view the image, calling functions do not need to open a cache view.
%
% Usage Example...
% resample_filter=AcquireResampleFilter(image,exception);
% SetResampleFilter(resample_filter, GaussianFilter);
% for (y=0; y < (ssize_t) image->rows; y++) {
% for (x=0; x < (ssize_t) image->columns; x++) {
% u= ....; v= ....;
% ScaleResampleFilter(resample_filter, ... scaling vectors ...);
% (void) ResamplePixelColor(resample_filter,u,v,&pixel);
% ... assign resampled pixel value ...
% }
% }
% DestroyResampleFilter(resample_filter);
%
% The format of the AcquireResampleFilter method is:
%
% ResampleFilter *AcquireResampleFilter(const Image *image,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport ResampleFilter *AcquireResampleFilter(const Image *image,
ExceptionInfo *exception)
{
register ResampleFilter
*resample_filter;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
resample_filter=(ResampleFilter *) AcquireMagickMemory(sizeof(
*resample_filter));
if (resample_filter == (ResampleFilter *) NULL)
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
(void) ResetMagickMemory(resample_filter,0,sizeof(*resample_filter));
resample_filter->exception=exception;
resample_filter->image=ReferenceImage((Image *) image);
resample_filter->view=AcquireVirtualCacheView(resample_filter->image,
exception);
resample_filter->debug=IsEventLogging();
resample_filter->image_area=(ssize_t) (image->columns*image->rows);
resample_filter->average_defined=MagickFalse;
resample_filter->signature=MagickCoreSignature;
SetResampleFilter(resample_filter,image->filter);
(void) SetResampleFilterInterpolateMethod(resample_filter,image->interpolate);
(void) SetResampleFilterVirtualPixelMethod(resample_filter,
GetImageVirtualPixelMethod(image));
return(resample_filter);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D e s t r o y R e s a m p l e I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DestroyResampleFilter() finalizes and cleans up the resampling
% resample_filter as returned by AcquireResampleFilter(), freeing any memory
% or other information as needed.
%
% The format of the DestroyResampleFilter method is:
%
% ResampleFilter *DestroyResampleFilter(ResampleFilter *resample_filter)
%
% A description of each parameter follows:
%
% o resample_filter: resampling information structure
%
*/
MagickExport ResampleFilter *DestroyResampleFilter(
ResampleFilter *resample_filter)
{
assert(resample_filter != (ResampleFilter *) NULL);
assert(resample_filter->signature == MagickCoreSignature);
assert(resample_filter->image != (Image *) NULL);
if (resample_filter->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
resample_filter->image->filename);
resample_filter->view=DestroyCacheView(resample_filter->view);
resample_filter->image=DestroyImage(resample_filter->image);
#if ! FILTER_LUT
resample_filter->filter_def=DestroyResizeFilter(resample_filter->filter_def);
#endif
resample_filter->signature=(~MagickCoreSignature);
resample_filter=(ResampleFilter *) RelinquishMagickMemory(resample_filter);
return(resample_filter);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e s a m p l e P i x e l C o l o r %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ResamplePixelColor() samples the pixel values surrounding the location
% given using an elliptical weighted average, at the scale previously
% calculated, and in the most efficent manner possible for the
% VirtualPixelMethod setting.
%
% The format of the ResamplePixelColor method is:
%
% MagickBooleanType ResamplePixelColor(ResampleFilter *resample_filter,
% const double u0,const double v0,PixelInfo *pixel,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o resample_filter: the resample filter.
%
% o u0,v0: A double representing the center of the area to resample,
% The distortion transformed transformed x,y coordinate.
%
% o pixel: the resampled pixel is returned here.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType ResamplePixelColor(
ResampleFilter *resample_filter,const double u0,const double v0,
PixelInfo *pixel,ExceptionInfo *exception)
{
MagickBooleanType
status;
ssize_t u,v, v1, v2, uw, hit;
double u1;
double U,V,Q,DQ,DDQ;
double divisor_c,divisor_m;
register double weight;
register const Quantum *pixels;
assert(resample_filter != (ResampleFilter *) NULL);
assert(resample_filter->signature == MagickCoreSignature);
status=MagickTrue;
/* GetPixelInfo(resample_filter->image,pixel); */
if ( resample_filter->do_interpolate ) {
status=InterpolatePixelInfo(resample_filter->image,resample_filter->view,
resample_filter->interpolate,u0,v0,pixel,resample_filter->exception);
return(status);
}
#if DEBUG_ELLIPSE
(void) FormatLocaleFile(stderr, "u0=%lf; v0=%lf;\n", u0, v0);
#endif
/*
Does resample area Miss the image Proper?
If and that area a simple solid color - then simply return that color!
This saves a lot of calculation when resampling outside the bounds of
the source image.
However it probably should be expanded to image bounds plus the filters
scaled support size.
*/
hit = 0;
switch ( resample_filter->virtual_pixel ) {
case BackgroundVirtualPixelMethod:
case TransparentVirtualPixelMethod:
case BlackVirtualPixelMethod:
case GrayVirtualPixelMethod:
case WhiteVirtualPixelMethod:
case MaskVirtualPixelMethod:
if ( resample_filter->limit_reached
|| u0 + resample_filter->Ulimit < 0.0
|| u0 - resample_filter->Ulimit > (double) resample_filter->image->columns-1.0
|| v0 + resample_filter->Vlimit < 0.0
|| v0 - resample_filter->Vlimit > (double) resample_filter->image->rows-1.0
)
hit++;
break;
case UndefinedVirtualPixelMethod:
case EdgeVirtualPixelMethod:
if ( ( u0 + resample_filter->Ulimit < 0.0 && v0 + resample_filter->Vlimit < 0.0 )
|| ( u0 + resample_filter->Ulimit < 0.0
&& v0 - resample_filter->Vlimit > (double) resample_filter->image->rows-1.0 )
|| ( u0 - resample_filter->Ulimit > (double) resample_filter->image->columns-1.0
&& v0 + resample_filter->Vlimit < 0.0 )
|| ( u0 - resample_filter->Ulimit > (double) resample_filter->image->columns-1.0
&& v0 - resample_filter->Vlimit > (double) resample_filter->image->rows-1.0 )
)
hit++;
break;
case HorizontalTileVirtualPixelMethod:
if ( v0 + resample_filter->Vlimit < 0.0
|| v0 - resample_filter->Vlimit > (double) resample_filter->image->rows-1.0
)
hit++; /* outside the horizontally tiled images. */
break;
case VerticalTileVirtualPixelMethod:
if ( u0 + resample_filter->Ulimit < 0.0
|| u0 - resample_filter->Ulimit > (double) resample_filter->image->columns-1.0
)
hit++; /* outside the vertically tiled images. */
break;
case DitherVirtualPixelMethod:
if ( ( u0 + resample_filter->Ulimit < -32.0 && v0 + resample_filter->Vlimit < -32.0 )
|| ( u0 + resample_filter->Ulimit < -32.0
&& v0 - resample_filter->Vlimit > (double) resample_filter->image->rows+31.0 )
|| ( u0 - resample_filter->Ulimit > (double) resample_filter->image->columns+31.0
&& v0 + resample_filter->Vlimit < -32.0 )
|| ( u0 - resample_filter->Ulimit > (double) resample_filter->image->columns+31.0
&& v0 - resample_filter->Vlimit > (double) resample_filter->image->rows+31.0 )
)
hit++;
break;
case TileVirtualPixelMethod:
case MirrorVirtualPixelMethod:
case RandomVirtualPixelMethod:
case HorizontalTileEdgeVirtualPixelMethod:
case VerticalTileEdgeVirtualPixelMethod:
case CheckerTileVirtualPixelMethod:
/* resampling of area is always needed - no VP limits */
break;
}
if ( hit ) {
/* The area being resampled is simply a solid color
* just return a single lookup color.
*
* Should this return the users requested interpolated color?
*/
status=InterpolatePixelInfo(resample_filter->image,resample_filter->view,
IntegerInterpolatePixel,u0,v0,pixel,resample_filter->exception);
return(status);
}
/*
When Scaling limits reached, return an 'averaged' result.
*/
if ( resample_filter->limit_reached ) {
switch ( resample_filter->virtual_pixel ) {
/* This is always handled by the above, so no need.
case BackgroundVirtualPixelMethod:
case ConstantVirtualPixelMethod:
case TransparentVirtualPixelMethod:
case GrayVirtualPixelMethod,
case WhiteVirtualPixelMethod
case MaskVirtualPixelMethod:
*/
case UndefinedVirtualPixelMethod:
case EdgeVirtualPixelMethod:
case DitherVirtualPixelMethod:
case HorizontalTileEdgeVirtualPixelMethod:
case VerticalTileEdgeVirtualPixelMethod:
/* We need an average edge pixel, from the correct edge!
How should I calculate an average edge color?
Just returning an averaged neighbourhood,
works well in general, but falls down for TileEdge methods.
This needs to be done properly!!!!!!
*/
status=InterpolatePixelInfo(resample_filter->image,
resample_filter->view,AverageInterpolatePixel,u0,v0,pixel,
resample_filter->exception);
break;
case HorizontalTileVirtualPixelMethod:
case VerticalTileVirtualPixelMethod:
/* just return the background pixel - Is there more direct way? */
status=InterpolatePixelInfo(resample_filter->image,
resample_filter->view,IntegerInterpolatePixel,-1.0,-1.0,pixel,
resample_filter->exception);
break;
case TileVirtualPixelMethod:
case MirrorVirtualPixelMethod:
case RandomVirtualPixelMethod:
case CheckerTileVirtualPixelMethod:
default:
/* generate a average color of the WHOLE image */
if ( resample_filter->average_defined == MagickFalse ) {
Image
*average_image;
CacheView
*average_view;
GetPixelInfo(resample_filter->image,(PixelInfo *)
&resample_filter->average_pixel);
resample_filter->average_defined=MagickTrue;
/* Try to get an averaged pixel color of whole image */
average_image=ResizeImage(resample_filter->image,1,1,BoxFilter,
resample_filter->exception);
if (average_image == (Image *) NULL)
{
*pixel=resample_filter->average_pixel; /* FAILED */
break;
}
average_view=AcquireVirtualCacheView(average_image,exception);
pixels=GetCacheViewVirtualPixels(average_view,0,0,1,1,
resample_filter->exception);
if (pixels == (const Quantum *) NULL) {
average_view=DestroyCacheView(average_view);
average_image=DestroyImage(average_image);
*pixel=resample_filter->average_pixel; /* FAILED */
break;
}
GetPixelInfoPixel(resample_filter->image,pixels,
&(resample_filter->average_pixel));
average_view=DestroyCacheView(average_view);
average_image=DestroyImage(average_image);
if ( resample_filter->virtual_pixel == CheckerTileVirtualPixelMethod )
{
/* CheckerTile is a alpha blend of the image's average pixel
color and the current background color */
/* image's average pixel color */
weight = QuantumScale*((double)
resample_filter->average_pixel.alpha);
resample_filter->average_pixel.red *= weight;
resample_filter->average_pixel.green *= weight;
resample_filter->average_pixel.blue *= weight;
divisor_c = weight;
/* background color */
weight = QuantumScale*((double)
resample_filter->image->background_color.alpha);
resample_filter->average_pixel.red +=
weight*resample_filter->image->background_color.red;
resample_filter->average_pixel.green +=
weight*resample_filter->image->background_color.green;
resample_filter->average_pixel.blue +=
weight*resample_filter->image->background_color.blue;
resample_filter->average_pixel.alpha +=
resample_filter->image->background_color.alpha;
divisor_c += weight;
/* alpha blend */
resample_filter->average_pixel.red /= divisor_c;
resample_filter->average_pixel.green /= divisor_c;
resample_filter->average_pixel.blue /= divisor_c;
resample_filter->average_pixel.alpha /= 2; /* 50% blend */
}
}
*pixel=resample_filter->average_pixel;
break;
}
return(status);
}
/*
Initialize weighted average data collection
*/
hit = 0;
divisor_c = 0.0;
divisor_m = 0.0;
pixel->red = pixel->green = pixel->blue = 0.0;
if (pixel->colorspace == CMYKColorspace)
pixel->black = 0.0;
if (pixel->alpha_trait != UndefinedPixelTrait)
pixel->alpha = 0.0;
/*
Determine the parellelogram bounding box fitted to the ellipse
centered at u0,v0. This area is bounding by the lines...
*/
v1 = (ssize_t)ceil(v0 - resample_filter->Vlimit); /* range of scan lines */
v2 = (ssize_t)floor(v0 + resample_filter->Vlimit);
/* scan line start and width accross the parallelogram */
u1 = u0 + (v1-v0)*resample_filter->slope - resample_filter->Uwidth;
uw = (ssize_t)(2.0*resample_filter->Uwidth)+1;
#if DEBUG_ELLIPSE
(void) FormatLocaleFile(stderr, "v1=%ld; v2=%ld\n", (long)v1, (long)v2);
(void) FormatLocaleFile(stderr, "u1=%ld; uw=%ld\n", (long)u1, (long)uw);
#else
# define DEBUG_HIT_MISS 0 /* only valid if DEBUG_ELLIPSE is enabled */
#endif
/*
Do weighted resampling of all pixels, within the scaled ellipse,
bound by a Parellelogram fitted to the ellipse.
*/
DDQ = 2*resample_filter->A;
for( v=v1; v<=v2; v++ ) {
#if DEBUG_HIT_MISS
long uu = ceil(u1); /* actual pixel location (for debug only) */
(void) FormatLocaleFile(stderr, "# scan line from pixel %ld, %ld\n", (long)uu, (long)v);
#endif
u = (ssize_t)ceil(u1); /* first pixel in scanline */
u1 += resample_filter->slope; /* start of next scan line */
/* location of this first pixel, relative to u0,v0 */
U = (double)u-u0;
V = (double)v-v0;
/* Q = ellipse quotent ( if Q<F then pixel is inside ellipse) */
Q = (resample_filter->A*U + resample_filter->B*V)*U + resample_filter->C*V*V;
DQ = resample_filter->A*(2.0*U+1) + resample_filter->B*V;
/* get the scanline of pixels for this v */
pixels=GetCacheViewVirtualPixels(resample_filter->view,u,v,(size_t) uw,
1,resample_filter->exception);
if (pixels == (const Quantum *) NULL)
return(MagickFalse);
/* count up the weighted pixel colors */
for( u=0; u<uw; u++ ) {
#if FILTER_LUT
/* Note that the ellipse has been pre-scaled so F = WLUT_WIDTH */
if ( Q < (double)WLUT_WIDTH ) {
weight = resample_filter->filter_lut[(int)Q];
#else
/* Note that the ellipse has been pre-scaled so F = support^2 */
if ( Q < (double)resample_filter->F ) {
weight = GetResizeFilterWeight(resample_filter->filter_def,
sqrt(Q)); /* a SquareRoot! Arrggghhhhh... */
#endif
pixel->alpha += weight*GetPixelAlpha(resample_filter->image,pixels);
divisor_m += weight;
if (pixel->alpha_trait != UndefinedPixelTrait)
weight *= QuantumScale*((double) GetPixelAlpha(resample_filter->image,pixels));
pixel->red += weight*GetPixelRed(resample_filter->image,pixels);
pixel->green += weight*GetPixelGreen(resample_filter->image,pixels);
pixel->blue += weight*GetPixelBlue(resample_filter->image,pixels);
if (pixel->colorspace == CMYKColorspace)
pixel->black += weight*GetPixelBlack(resample_filter->image,pixels);
divisor_c += weight;
hit++;
#if DEBUG_HIT_MISS
/* mark the pixel according to hit/miss of the ellipse */
(void) FormatLocaleFile(stderr, "set arrow from %lf,%lf to %lf,%lf nohead ls 3\n",
(long)uu-.1,(double)v-.1,(long)uu+.1,(long)v+.1);
(void) FormatLocaleFile(stderr, "set arrow from %lf,%lf to %lf,%lf nohead ls 3\n",
(long)uu+.1,(double)v-.1,(long)uu-.1,(long)v+.1);
} else {
(void) FormatLocaleFile(stderr, "set arrow from %lf,%lf to %lf,%lf nohead ls 1\n",
(long)uu-.1,(double)v-.1,(long)uu+.1,(long)v+.1);
(void) FormatLocaleFile(stderr, "set arrow from %lf,%lf to %lf,%lf nohead ls 1\n",
(long)uu+.1,(double)v-.1,(long)uu-.1,(long)v+.1);
}
uu++;
#else
}
#endif
pixels+=GetPixelChannels(resample_filter->image);
Q += DQ;
DQ += DDQ;
}
}
#if DEBUG_ELLIPSE
(void) FormatLocaleFile(stderr, "Hit=%ld; Total=%ld;\n", (long)hit, (long)uw*(v2-v1) );
#endif
/*
Result sanity check -- this should NOT happen
*/
if ( hit == 0 || divisor_m <= MagickEpsilon || divisor_c <= MagickEpsilon ) {
/* not enough pixels, or bad weighting in resampling,
resort to direct interpolation */
#if DEBUG_NO_PIXEL_HIT
pixel->alpha = pixel->red = pixel->green = pixel->blue = 0;
pixel->red = QuantumRange; /* show pixels for which EWA fails */
#else
status=InterpolatePixelInfo(resample_filter->image,
resample_filter->view,resample_filter->interpolate,u0,v0,pixel,
resample_filter->exception);
#endif
return status;
}
/*
Finialize results of resampling
*/
divisor_m = 1.0/divisor_m;
if (pixel->alpha_trait != UndefinedPixelTrait)
pixel->alpha = (double) ClampToQuantum(divisor_m*pixel->alpha);
divisor_c = 1.0/divisor_c;
pixel->red = (double) ClampToQuantum(divisor_c*pixel->red);
pixel->green = (double) ClampToQuantum(divisor_c*pixel->green);
pixel->blue = (double) ClampToQuantum(divisor_c*pixel->blue);
if (pixel->colorspace == CMYKColorspace)
pixel->black = (double) ClampToQuantum(divisor_c*pixel->black);
return(MagickTrue);
}
#if EWA && EWA_CLAMP
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
- C l a m p U p A x e s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ClampUpAxes() function converts the input vectors into a major and
% minor axis unit vectors, and their magnitude. This allows us to
% ensure that the ellipse generated is never smaller than the unit
% circle and thus never too small for use in EWA resampling.
%
% This purely mathematical 'magic' was provided by Professor Nicolas
% Robidoux and his Masters student Chantal Racette.
%
% Reference: "We Recommend Singular Value Decomposition", David Austin
% http://www.ams.org/samplings/feature-column/fcarc-svd
%
% By generating major and minor axis vectors, we can actually use the
% ellipse in its "canonical form", by remapping the dx,dy of the
% sampled point into distances along the major and minor axis unit
% vectors.
%
% Reference: http://en.wikipedia.org/wiki/Ellipse#Canonical_form
*/
static inline void ClampUpAxes(const double dux,
const double dvx,
const double duy,
const double dvy,
double *major_mag,
double *minor_mag,
double *major_unit_x,
double *major_unit_y,
double *minor_unit_x,
double *minor_unit_y)
{
/*
* ClampUpAxes takes an input 2x2 matrix
*
* [ a b ] = [ dux duy ]
* [ c d ] = [ dvx dvy ]
*
* and computes from it the major and minor axis vectors [major_x,
* major_y] and [minor_x,minor_y] of the smallest ellipse containing
* both the unit disk and the ellipse which is the image of the unit
* disk by the linear transformation
*
* [ dux duy ] [S] = [s]
* [ dvx dvy ] [T] = [t]
*
* (The vector [S,T] is the difference between a position in output
* space and [X,Y]; the vector [s,t] is the difference between a
* position in input space and [x,y].)
*/
/*
* Output:
*
* major_mag is the half-length of the major axis of the "new"
* ellipse.
*
* minor_mag is the half-length of the minor axis of the "new"
* ellipse.
*
* major_unit_x is the x-coordinate of the major axis direction vector
* of both the "old" and "new" ellipses.
*
* major_unit_y is the y-coordinate of the major axis direction vector.
*
* minor_unit_x is the x-coordinate of the minor axis direction vector.
*
* minor_unit_y is the y-coordinate of the minor axis direction vector.
*
* Unit vectors are useful for computing projections, in particular,
* to compute the distance between a point in output space and the
* center of a unit disk in output space, using the position of the
* corresponding point [s,t] in input space. Following the clamping,
* the square of this distance is
*
* ( ( s * major_unit_x + t * major_unit_y ) / major_mag )^2
* +
* ( ( s * minor_unit_x + t * minor_unit_y ) / minor_mag )^2
*
* If such distances will be computed for many [s,t]'s, it makes
* sense to actually compute the reciprocal of major_mag and
* minor_mag and multiply them by the above unit lengths.
*
* Now, if you want to modify the input pair of tangent vectors so
* that it defines the modified ellipse, all you have to do is set
*
* newdux = major_mag * major_unit_x
* newdvx = major_mag * major_unit_y
* newduy = minor_mag * minor_unit_x = minor_mag * -major_unit_y
* newdvy = minor_mag * minor_unit_y = minor_mag * major_unit_x
*
* and use these tangent vectors as if they were the original ones.
* Usually, this is a drastic change in the tangent vectors even if
* the singular values are not clamped; for example, the minor axis
* vector always points in a direction which is 90 degrees
* counterclockwise from the direction of the major axis vector.
*/
/*
* Discussion:
*
* GOAL: Fix things so that the pullback, in input space, of a disk
* of radius r in output space is an ellipse which contains, at
* least, a disc of radius r. (Make this hold for any r>0.)
*
* ESSENCE OF THE METHOD: Compute the product of the first two
* factors of an SVD of the linear transformation defining the
* ellipse and make sure that both its columns have norm at least 1.
* Because rotations and reflexions map disks to themselves, it is
* not necessary to compute the third (rightmost) factor of the SVD.
*
* DETAILS: Find the singular values and (unit) left singular
* vectors of Jinv, clampling up the singular values to 1, and
* multiply the unit left singular vectors by the new singular
* values in order to get the minor and major ellipse axis vectors.
*
* Image resampling context:
*
* The Jacobian matrix of the transformation at the output point
* under consideration is defined as follows:
*
* Consider the transformation (x,y) -> (X,Y) from input locations
* to output locations. (Anthony Thyssen, elsewhere in resample.c,
* uses the notation (u,v) -> (x,y).)
*
* The Jacobian matrix of the transformation at (x,y) is equal to
*
* J = [ A, B ] = [ dX/dx, dX/dy ]
* [ C, D ] [ dY/dx, dY/dy ]
*
* that is, the vector [A,C] is the tangent vector corresponding to
* input changes in the horizontal direction, and the vector [B,D]
* is the tangent vector corresponding to input changes in the
* vertical direction.
*
* In the context of resampling, it is natural to use the inverse
* Jacobian matrix Jinv because resampling is generally performed by
* pulling pixel locations in the output image back to locations in
* the input image. Jinv is
*
* Jinv = [ a, b ] = [ dx/dX, dx/dY ]
* [ c, d ] [ dy/dX, dy/dY ]
*
* Note: Jinv can be computed from J with the following matrix
* formula:
*
* Jinv = 1/(A*D-B*C) [ D, -B ]
* [ -C, A ]
*
* What we do is modify Jinv so that it generates an ellipse which
* is as close as possible to the original but which contains the
* unit disk. This can be accomplished as follows:
*
* Let
*
* Jinv = U Sigma V^T
*
* be an SVD decomposition of Jinv. (The SVD is not unique, but the
* final ellipse does not depend on the particular SVD.)
*
* We could clamp up the entries of the diagonal matrix Sigma so
* that they are at least 1, and then set
*
* Jinv = U newSigma V^T.
*
* However, we do not need to compute V for the following reason:
* V^T is an orthogonal matrix (that is, it represents a combination
* of rotations and reflexions) so that it maps the unit circle to
* itself. For this reason, the exact value of V does not affect the
* final ellipse, and we can choose V to be the identity
* matrix. This gives
*
* Jinv = U newSigma.
*
* In the end, we return the two diagonal entries of newSigma
* together with the two columns of U.
*/
/*
* ClampUpAxes was written by Nicolas Robidoux and Chantal Racette
* of Laurentian University with insightful suggestions from Anthony
* Thyssen and funding from the National Science and Engineering
* Research Council of Canada. It is distinguished from its
* predecessors by its efficient handling of degenerate cases.
*
* The idea of clamping up the EWA ellipse's major and minor axes so
* that the result contains the reconstruction kernel filter support
* is taken from Andreas Gustaffson's Masters thesis "Interactive
* Image Warping", Helsinki University of Technology, Faculty of
* Information Technology, 59 pages, 1993 (see Section 3.6).
*
* The use of the SVD to clamp up the singular values of the
* Jacobian matrix of the pullback transformation for EWA resampling
* is taken from the astrophysicist Craig DeForest. It is
* implemented in his PDL::Transform code (PDL = Perl Data
* Language).
*/
const double a = dux;
const double b = duy;
const double c = dvx;
const double d = dvy;
/*
* n is the matrix Jinv * transpose(Jinv). Eigenvalues of n are the
* squares of the singular values of Jinv.
*/
const double aa = a*a;
const double bb = b*b;
const double cc = c*c;
const double dd = d*d;
/*
* Eigenvectors of n are left singular vectors of Jinv.
*/
const double n11 = aa+bb;
const double n12 = a*c+b*d;
const double n21 = n12;
const double n22 = cc+dd;
const double det = a*d-b*c;
const double twice_det = det+det;
const double frobenius_squared = n11+n22;
const double discriminant =
(frobenius_squared+twice_det)*(frobenius_squared-twice_det);
/*
* In exact arithmetic, discriminant can't be negative. In floating
* point, it can, because of the bad conditioning of SVD
* decompositions done through the associated normal matrix.
*/
const double sqrt_discriminant =
sqrt(discriminant > 0.0 ? discriminant : 0.0);
/*
* s1 is the largest singular value of the inverse Jacobian
* matrix. In other words, its reciprocal is the smallest singular
* value of the Jacobian matrix itself.
* If s1 = 0, both singular values are 0, and any orthogonal pair of
* left and right factors produces a singular decomposition of Jinv.
*/
/*
* Initially, we only compute the squares of the singular values.
*/
const double s1s1 = 0.5*(frobenius_squared+sqrt_discriminant);
/*
* s2 the smallest singular value of the inverse Jacobian
* matrix. Its reciprocal is the largest singular value of the
* Jacobian matrix itself.
*/
const double s2s2 = 0.5*(frobenius_squared-sqrt_discriminant);
const double s1s1minusn11 = s1s1-n11;
const double s1s1minusn22 = s1s1-n22;
/*
* u1, the first column of the U factor of a singular decomposition
* of Jinv, is a (non-normalized) left singular vector corresponding
* to s1. It has entries u11 and u21. We compute u1 from the fact
* that it is an eigenvector of n corresponding to the eigenvalue
* s1^2.
*/
const double s1s1minusn11_squared = s1s1minusn11*s1s1minusn11;
const double s1s1minusn22_squared = s1s1minusn22*s1s1minusn22;
/*
* The following selects the largest row of n-s1^2 I as the one
* which is used to find the eigenvector. If both s1^2-n11 and
* s1^2-n22 are zero, n-s1^2 I is the zero matrix. In that case,
* any vector is an eigenvector; in addition, norm below is equal to
* zero, and, in exact arithmetic, this is the only case in which
* norm = 0. So, setting u1 to the simple but arbitrary vector [1,0]
* if norm = 0 safely takes care of all cases.
*/
const double temp_u11 =
( (s1s1minusn11_squared>=s1s1minusn22_squared) ? n12 : s1s1minusn22 );
const double temp_u21 =
( (s1s1minusn11_squared>=s1s1minusn22_squared) ? s1s1minusn11 : n21 );
const double norm = sqrt(temp_u11*temp_u11+temp_u21*temp_u21);
/*
* Finalize the entries of first left singular vector (associated
* with the largest singular value).
*/
const double u11 = ( (norm>0.0) ? temp_u11/norm : 1.0 );
const double u21 = ( (norm>0.0) ? temp_u21/norm : 0.0 );
/*
* Clamp the singular values up to 1.
*/
*major_mag = ( (s1s1<=1.0) ? 1.0 : sqrt(s1s1) );
*minor_mag = ( (s2s2<=1.0) ? 1.0 : sqrt(s2s2) );
/*
* Return the unit major and minor axis direction vectors.
*/
*major_unit_x = u11;
*major_unit_y = u21;
*minor_unit_x = -u21;
*minor_unit_y = u11;
}
#endif
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S c a l e R e s a m p l e F i l t e r %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ScaleResampleFilter() does all the calculations needed to resample an image
% at a specific scale, defined by two scaling vectors. This not using
% a orthogonal scaling, but two distorted scaling vectors, to allow the
% generation of a angled ellipse.
%
% As only two deritive scaling vectors are used the center of the ellipse
% must be the center of the lookup. That is any curvature that the
% distortion may produce is discounted.
%
% The input vectors are produced by either finding the derivitives of the
% distortion function, or the partial derivitives from a distortion mapping.
% They do not need to be the orthogonal dx,dy scaling vectors, but can be
% calculated from other derivatives. For example you could use dr,da/r
% polar coordinate vector scaling vectors
%
% If u,v = DistortEquation(x,y) OR u = Fu(x,y); v = Fv(x,y)
% Then the scaling vectors are determined from the deritives...
% du/dx, dv/dx and du/dy, dv/dy
% If the resulting scaling vectors is othogonally aligned then...
% dv/dx = 0 and du/dy = 0
% Producing an othogonally alligned ellipse in source space for the area to
% be resampled.
%
% Note that scaling vectors are different to argument order. Argument order
% is the general order the deritives are extracted from the distortion
% equations, and not the scaling vectors. As such the middle two vaules
% may be swapped from what you expect. Caution is advised.
%
% WARNING: It is assumed that any SetResampleFilter() method call will
% always be performed before the ScaleResampleFilter() method, so that the
% size of the ellipse will match the support for the resampling filter being
% used.
%
% The format of the ScaleResampleFilter method is:
%
% void ScaleResampleFilter(const ResampleFilter *resample_filter,
% const double dux,const double duy,const double dvx,const double dvy)
%
% A description of each parameter follows:
%
% o resample_filter: the resampling resample_filterrmation defining the
% image being resampled
%
% o dux,duy,dvx,dvy:
% The deritives or scaling vectors defining the EWA ellipse.
% NOTE: watch the order, which is based on the order deritives
% are usally determined from distortion equations (see above).
% The middle two values may need to be swapped if you are thinking
% in terms of scaling vectors.
%
*/
MagickExport void ScaleResampleFilter(ResampleFilter *resample_filter,
const double dux,const double duy,const double dvx,const double dvy)
{
double A,B,C,F;
assert(resample_filter != (ResampleFilter *) NULL);
assert(resample_filter->signature == MagickCoreSignature);
resample_filter->limit_reached = MagickFalse;
/* A 'point' filter forces use of interpolation instead of area sampling */
if ( resample_filter->filter == PointFilter )
return; /* EWA turned off - nothing to do */
#if DEBUG_ELLIPSE
(void) FormatLocaleFile(stderr, "# -----\n" );
(void) FormatLocaleFile(stderr, "dux=%lf; dvx=%lf; duy=%lf; dvy=%lf;\n",
dux, dvx, duy, dvy);
#endif
/* Find Ellipse Coefficents such that
A*u^2 + B*u*v + C*v^2 = F
With u,v relative to point around which we are resampling.
And the given scaling dx,dy vectors in u,v space
du/dx,dv/dx and du/dy,dv/dy
*/
#if EWA
/* Direct conversion of derivatives into elliptical coefficients
However when magnifying images, the scaling vectors will be small
resulting in a ellipse that is too small to sample properly.
As such we need to clamp the major/minor axis to a minumum of 1.0
to prevent it getting too small.
*/
#if EWA_CLAMP
{ double major_mag,
minor_mag,
major_x,
major_y,
minor_x,
minor_y;
ClampUpAxes(dux,dvx,duy,dvy, &major_mag, &minor_mag,
&major_x, &major_y, &minor_x, &minor_y);
major_x *= major_mag; major_y *= major_mag;
minor_x *= minor_mag; minor_y *= minor_mag;
#if DEBUG_ELLIPSE
(void) FormatLocaleFile(stderr, "major_x=%lf; major_y=%lf; minor_x=%lf; minor_y=%lf;\n",
major_x, major_y, minor_x, minor_y);
#endif
A = major_y*major_y+minor_y*minor_y;
B = -2.0*(major_x*major_y+minor_x*minor_y);
C = major_x*major_x+minor_x*minor_x;
F = major_mag*minor_mag;
F *= F; /* square it */
}
#else /* raw unclamped EWA */
A = dvx*dvx+dvy*dvy;
B = -2.0*(dux*dvx+duy*dvy);
C = dux*dux+duy*duy;
F = dux*dvy-duy*dvx;
F *= F; /* square it */
#endif /* EWA_CLAMP */
#else /* HQ_EWA */
/*
This Paul Heckbert's "Higher Quality EWA" formula, from page 60 in his
thesis, which adds a unit circle to the elliptical area so as to do both
Reconstruction and Prefiltering of the pixels in the resampling. It also
means it is always likely to have at least 4 pixels within the area of the
ellipse, for weighted averaging. No scaling will result with F == 4.0 and
a circle of radius 2.0, and F smaller than this means magnification is
being used.
NOTE: This method produces a very blury result at near unity scale while
producing perfect results for strong minitification and magnifications.
However filter support is fixed to 2.0 (no good for Windowed Sinc filters)
*/
A = dvx*dvx+dvy*dvy+1;
B = -2.0*(dux*dvx+duy*dvy);
C = dux*dux+duy*duy+1;
F = A*C - B*B/4;
#endif
#if DEBUG_ELLIPSE
(void) FormatLocaleFile(stderr, "A=%lf; B=%lf; C=%lf; F=%lf\n", A,B,C,F);
/* Figure out the various information directly about the ellipse.
This information currently not needed at this time, but may be
needed later for better limit determination.
It is also good to have as a record for future debugging
*/
{ double alpha, beta, gamma, Major, Minor;
double Eccentricity, Ellipse_Area, Ellipse_Angle;
alpha = A+C;
beta = A-C;
gamma = sqrt(beta*beta + B*B );
if ( alpha - gamma <= MagickEpsilon )
Major=MagickMaximumValue;
else
Major=sqrt(2*F/(alpha - gamma));
Minor = sqrt(2*F/(alpha + gamma));
(void) FormatLocaleFile(stderr, "# Major=%lf; Minor=%lf\n", Major, Minor );
/* other information about ellipse include... */
Eccentricity = Major/Minor;
Ellipse_Area = MagickPI*Major*Minor;
Ellipse_Angle = atan2(B, A-C);
(void) FormatLocaleFile(stderr, "# Angle=%lf Area=%lf\n",
(double) RadiansToDegrees(Ellipse_Angle), Ellipse_Area);
}
#endif
/* If one or both of the scaling vectors is impossibly large
(producing a very large raw F value), we may as well not bother
doing any form of resampling since resampled area is very large.
In this case some alternative means of pixel sampling, such as
the average of the whole image is needed to get a reasonable
result. Calculate only as needed.
*/
if ( (4*A*C - B*B) > MagickMaximumValue ) {
resample_filter->limit_reached = MagickTrue;
return;
}
/* Scale ellipse to match the filters support
(that is, multiply F by the square of the support)
Simplier to just multiply it by the support twice!
*/
F *= resample_filter->support;
F *= resample_filter->support;
/* Orthogonal bounds of the ellipse */
resample_filter->Ulimit = sqrt(C*F/(A*C-0.25*B*B));
resample_filter->Vlimit = sqrt(A*F/(A*C-0.25*B*B));
/* Horizontally aligned parallelogram fitted to Ellipse */
resample_filter->Uwidth = sqrt(F/A); /* Half of the parallelogram width */
resample_filter->slope = -B/(2.0*A); /* Reciprocal slope of the parallelogram */
#if DEBUG_ELLIPSE
(void) FormatLocaleFile(stderr, "Ulimit=%lf; Vlimit=%lf; UWidth=%lf; Slope=%lf;\n",
resample_filter->Ulimit, resample_filter->Vlimit,
resample_filter->Uwidth, resample_filter->slope );
#endif
/* Check the absolute area of the parallelogram involved.
* This limit needs more work, as it is too slow for larger images
* with tiled views of the horizon.
*/
if ( (resample_filter->Uwidth * resample_filter->Vlimit)
> (4.0*resample_filter->image_area)) {
resample_filter->limit_reached = MagickTrue;
return;
}
/* Scale ellipse formula to directly index the Filter Lookup Table */
{ register double scale;
#if FILTER_LUT
/* scale so that F = WLUT_WIDTH; -- hardcoded */
scale = (double)WLUT_WIDTH/F;
#else
/* scale so that F = resample_filter->F (support^2) */
scale = resample_filter->F/F;
#endif
resample_filter->A = A*scale;
resample_filter->B = B*scale;
resample_filter->C = C*scale;
}
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t R e s a m p l e F i l t e r %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetResampleFilter() set the resampling filter lookup table based on a
% specific filter. Note that the filter is used as a radial filter not as a
% two pass othogonally aligned resampling filter.
%
% The format of the SetResampleFilter method is:
%
% void SetResampleFilter(ResampleFilter *resample_filter,
% const FilterType filter)
%
% A description of each parameter follows:
%
% o resample_filter: resampling resample_filterrmation structure
%
% o filter: the resize filter for elliptical weighting LUT
%
*/
MagickExport void SetResampleFilter(ResampleFilter *resample_filter,
const FilterType filter)
{
ResizeFilter
*resize_filter;
assert(resample_filter != (ResampleFilter *) NULL);
assert(resample_filter->signature == MagickCoreSignature);
resample_filter->do_interpolate = MagickFalse;
resample_filter->filter = filter;
/* Default cylindrical filter is a Cubic Keys filter */
if ( filter == UndefinedFilter )
resample_filter->filter = RobidouxFilter;
if ( resample_filter->filter == PointFilter ) {
resample_filter->do_interpolate = MagickTrue;
return; /* EWA turned off - nothing more to do */
}
resize_filter = AcquireResizeFilter(resample_filter->image,
resample_filter->filter,MagickTrue,resample_filter->exception);
if (resize_filter == (ResizeFilter *) NULL) {
(void) ThrowMagickException(resample_filter->exception,GetMagickModule(),
ModuleError, "UnableToSetFilteringValue",
"Fall back to Interpolated 'Point' filter");
resample_filter->filter = PointFilter;
resample_filter->do_interpolate = MagickTrue;
return; /* EWA turned off - nothing more to do */
}
/* Get the practical working support for the filter,
* after any API call blur factors have been accoded for.
*/
#if EWA
resample_filter->support = GetResizeFilterSupport(resize_filter);
#else
resample_filter->support = 2.0; /* fixed support size for HQ-EWA */
#endif
#if FILTER_LUT
/* Fill the LUT with the weights from the selected filter function */
{ register int
Q;
double
r_scale;
/* Scale radius so the filter LUT covers the full support range */
r_scale = resample_filter->support*sqrt(1.0/(double)WLUT_WIDTH);
for(Q=0; Q<WLUT_WIDTH; Q++)
resample_filter->filter_lut[Q] = (double)
GetResizeFilterWeight(resize_filter,sqrt((double)Q)*r_scale);
/* finished with the resize filter */
resize_filter = DestroyResizeFilter(resize_filter);
}
#else
/* save the filter and the scaled ellipse bounds needed for filter */
resample_filter->filter_def = resize_filter;
resample_filter->F = resample_filter->support*resample_filter->support;
#endif
/*
Adjust the scaling of the default unit circle
This assumes that any real scaling changes will always
take place AFTER the filter method has been initialized.
*/
ScaleResampleFilter(resample_filter, 1.0, 0.0, 0.0, 1.0);
#if 0
/*
This is old code kept as a reference only. Basically it generates
a Gaussian bell curve, with sigma = 0.5 if the support is 2.0
Create Normal Gaussian 2D Filter Weighted Lookup Table.
A normal EWA guassual lookup would use exp(Q*ALPHA)
where Q = distance squared from 0.0 (center) to 1.0 (edge)
and ALPHA = -4.0*ln(2.0) ==> -2.77258872223978123767
The table is of length 1024, and equates to support radius of 2.0
thus needs to be scaled by ALPHA*4/1024 and any blur factor squared
The it comes from reference code provided by Fred Weinhaus.
*/
r_scale = -2.77258872223978123767/(WLUT_WIDTH*blur*blur);
for(Q=0; Q<WLUT_WIDTH; Q++)
resample_filter->filter_lut[Q] = exp((double)Q*r_scale);
resample_filter->support = WLUT_WIDTH;
#endif
#if FILTER_LUT
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp single
#endif
{
if (IsStringTrue(GetImageArtifact(resample_filter->image,
"resample:verbose")) != MagickFalse)
{
register int
Q;
double
r_scale;
/* Debug output of the filter weighting LUT
Gnuplot the LUT data, the x scale index has been adjusted
plot [0:2][-.2:1] "lut.dat" with lines
The filter values should be normalized for comparision
*/
printf("#\n");
printf("# Resampling Filter LUT (%d values) for '%s' filter\n",
WLUT_WIDTH, CommandOptionToMnemonic(MagickFilterOptions,
resample_filter->filter) );
printf("#\n");
printf("# Note: values in table are using a squared radius lookup.\n");
printf("# As such its distribution is not uniform.\n");
printf("#\n");
printf("# The X value is the support distance for the Y weight\n");
printf("# so you can use gnuplot to plot this cylindrical filter\n");
printf("# plot [0:2][-.2:1] \"lut.dat\" with lines\n");
printf("#\n");
/* Scale radius so the filter LUT covers the full support range */
r_scale = resample_filter->support*sqrt(1.0/(double)WLUT_WIDTH);
for(Q=0; Q<WLUT_WIDTH; Q++)
printf("%8.*g %.*g\n",
GetMagickPrecision(),sqrt((double)Q)*r_scale,
GetMagickPrecision(),resample_filter->filter_lut[Q] );
printf("\n\n"); /* generate a 'break' in gnuplot if multiple outputs */
}
/* Output the above once only for each image, and each setting
(void) DeleteImageArtifact(resample_filter->image,"resample:verbose");
*/
}
#endif /* FILTER_LUT */
return;
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t R e s a m p l e F i l t e r I n t e r p o l a t e M e t h o d %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetResampleFilterInterpolateMethod() sets the resample filter interpolation
% method.
%
% The format of the SetResampleFilterInterpolateMethod method is:
%
% MagickBooleanType SetResampleFilterInterpolateMethod(
% ResampleFilter *resample_filter,const InterpolateMethod method)
%
% A description of each parameter follows:
%
% o resample_filter: the resample filter.
%
% o method: the interpolation method.
%
*/
MagickExport MagickBooleanType SetResampleFilterInterpolateMethod(
ResampleFilter *resample_filter,const PixelInterpolateMethod method)
{
assert(resample_filter != (ResampleFilter *) NULL);
assert(resample_filter->signature == MagickCoreSignature);
assert(resample_filter->image != (Image *) NULL);
if (resample_filter->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
resample_filter->image->filename);
resample_filter->interpolate=method;
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t R e s a m p l e F i l t e r V i r t u a l P i x e l M e t h o d %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetResampleFilterVirtualPixelMethod() changes the virtual pixel method
% associated with the specified resample filter.
%
% The format of the SetResampleFilterVirtualPixelMethod method is:
%
% MagickBooleanType SetResampleFilterVirtualPixelMethod(
% ResampleFilter *resample_filter,const VirtualPixelMethod method)
%
% A description of each parameter follows:
%
% o resample_filter: the resample filter.
%
% o method: the virtual pixel method.
%
*/
MagickExport MagickBooleanType SetResampleFilterVirtualPixelMethod(
ResampleFilter *resample_filter,const VirtualPixelMethod method)
{
assert(resample_filter != (ResampleFilter *) NULL);
assert(resample_filter->signature == MagickCoreSignature);
assert(resample_filter->image != (Image *) NULL);
if (resample_filter->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
resample_filter->image->filename);
resample_filter->virtual_pixel=method;
if (method != UndefinedVirtualPixelMethod)
(void) SetCacheViewVirtualPixelMethod(resample_filter->view,method);
return(MagickTrue);
}
|
GB_unop__tanh_fc32_fc32.c
|
//------------------------------------------------------------------------------
// GB_unop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated/ folder, do not edit it (auto-generated).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_atomics.h"
#include "GB_unop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB (_unop_apply__tanh_fc32_fc32)
// op(A') function: GB (_unop_tran__tanh_fc32_fc32)
// C type: GxB_FC32_t
// A type: GxB_FC32_t
// cast: GxB_FC32_t cij = aij
// unaryop: cij = ctanhf (aij)
#define GB_ATYPE \
GxB_FC32_t
#define GB_CTYPE \
GxB_FC32_t
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
GxB_FC32_t aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = ctanhf (x) ;
// casting
#define GB_CAST(z, aij) \
GxB_FC32_t z = aij ;
// cij = op (aij)
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
GxB_FC32_t aij = Ax [pA] ; \
/* Cx [pC] = op (cast (aij)) */ \
GxB_FC32_t z = aij ; \
Cx [pC] = ctanhf (z) ; \
}
// true if operator is the identity op with no typecasting
#define GB_OP_IS_IDENTITY_WITH_NO_TYPECAST \
0
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_TANH || GxB_NO_FC32)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_apply__tanh_fc32_fc32)
(
GxB_FC32_t *Cx, // Cx and Ax may be aliased
const GxB_FC32_t *Ax,
const int8_t *restrict Ab, // A->b if A is bitmap
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
// TODO: if OP is ONE and uniform-valued matrices are exploited, then
// do this in O(1) time
if (Ab == NULL)
{
#if ( GB_OP_IS_IDENTITY_WITH_NO_TYPECAST )
GB_memcpy (Cx, Ax, anz * sizeof (GxB_FC32_t), nthreads) ;
#else
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
GxB_FC32_t aij = Ax [p] ;
GxB_FC32_t z = aij ;
Cx [p] = ctanhf (z) ;
}
#endif
}
else
{
// bitmap case, no transpose; A->b already memcpy'd into C->b
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!Ab [p]) continue ;
GxB_FC32_t aij = Ax [p] ;
GxB_FC32_t z = aij ;
Cx [p] = ctanhf (z) ;
}
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_tran__tanh_fc32_fc32)
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
GB_binop__bclr_int16.c
|
//------------------------------------------------------------------------------
// GB_binop: hard-coded functions for each built-in binary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated2/ folder, do not edit it
// (it is auto-generated from Generator/*).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_emult.h"
#include "GB_control.h"
#include "GB_ek_slice.h"
#include "GB_dense.h"
#include "GB_atomics.h"
#include "GB_bitmap_assign_methods.h"
#include "GB_binop__include.h"
// C=binop(A,B) is defined by the following types and operators:
// A+B function (eWiseAdd): GB (_AaddB__bclr_int16)
// A.*B function (eWiseMult): GB (_AemultB_01__bclr_int16)
// A.*B function (eWiseMult): GB (_AemultB_02__bclr_int16)
// A.*B function (eWiseMult): GB (_AemultB_03__bclr_int16)
// A.*B function (eWiseMult): GB (_AemultB_bitmap__bclr_int16)
// A*D function (colscale): GB ((none))
// D*A function (rowscale): GB ((none))
// C+=B function (dense accum): GB (_Cdense_accumB__bclr_int16)
// C+=b function (dense accum): GB (_Cdense_accumb__bclr_int16)
// C+=A+B function (dense ewise3): GB ((none))
// C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__bclr_int16)
// C=scalar+B GB (_bind1st__bclr_int16)
// C=scalar+B' GB (_bind1st_tran__bclr_int16)
// C=A+scalar GB (_bind2nd__bclr_int16)
// C=A'+scalar GB (_bind2nd_tran__bclr_int16)
// C type: int16_t
// A type: int16_t
// B,b type: int16_t
// BinaryOp: cij = GB_BITCLR (aij, bij, int16_t, 16)
#define GB_ATYPE \
int16_t
#define GB_BTYPE \
int16_t
#define GB_CTYPE \
int16_t
// true if the types of A and B are identical
#define GB_ATYPE_IS_BTYPE \
1
// true if the types of C and A are identical
#define GB_CTYPE_IS_ATYPE \
1
// true if the types of C and B are identical
#define GB_CTYPE_IS_BTYPE \
1
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA,A_iso) \
int16_t aij = GBX (Ax, pA, A_iso)
// bij = Bx [pB]
#define GB_GETB(bij,Bx,pB,B_iso) \
int16_t bij = GBX (Bx, pB, B_iso)
// declare scalar of the same type as C
#define GB_CTYPE_SCALAR(t) \
int16_t t
// cij = Ax [pA]
#define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \
cij = GBX (Ax, pA, A_iso)
// cij = Bx [pB]
#define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \
cij = GBX (Bx, pB, B_iso)
#define GB_CX(p) Cx [p]
// binary operator
#define GB_BINOP(z,x,y,i,j) \
z = GB_BITCLR (x, y, int16_t, 16) ;
// true if the binop must be flipped
#define GB_BINOP_FLIP \
1
// op is second
#define GB_OP_IS_SECOND \
0
// do the numerical phases of GB_add and GB_emult
#define GB_PHASE_2_OF_2
// hard-coded loops can be vectorized
#define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_BCLR || GxB_NO_INT16 || GxB_NO_BCLR_INT16)
//------------------------------------------------------------------------------
// C += A+B, all 3 matrices dense
//------------------------------------------------------------------------------
#if 0
// The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV.
void GB ((none))
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#include "GB_dense_ewise3_accum_template.c"
}
#endif
//------------------------------------------------------------------------------
// C = A+B, all 3 matrices dense
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_ewise3_noaccum__bclr_int16)
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_dense_ewise3_noaccum_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C += B, accumulate a sparse matrix into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_accumB__bclr_int16)
(
GrB_Matrix C,
const GrB_Matrix B,
const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
{
#include "GB_dense_subassign_23_template.c"
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C += b, accumulate a scalar into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_accumb__bclr_int16)
(
GrB_Matrix C,
const GB_void *p_bwork,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
{
// get the scalar b for C += b, of type int16_t
int16_t bwork = (*((int16_t *) p_bwork)) ;
#include "GB_dense_subassign_22_template.c"
return (GrB_SUCCESS) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = A*D, column scale with diagonal D matrix
//------------------------------------------------------------------------------
#if 0
GrB_Info GB ((none))
(
GrB_Matrix C,
const GrB_Matrix A, bool A_is_pattern,
const GrB_Matrix D, bool D_is_pattern,
const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int16_t *restrict Cx = (int16_t *) C->x ;
#include "GB_AxB_colscale_template.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
//------------------------------------------------------------------------------
// C = D*B, row scale with diagonal D matrix
//------------------------------------------------------------------------------
#if 0
GrB_Info GB ((none))
(
GrB_Matrix C,
const GrB_Matrix D, bool D_is_pattern,
const GrB_Matrix B, bool B_is_pattern,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int16_t *restrict Cx = (int16_t *) C->x ;
#include "GB_AxB_rowscale_template.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
//------------------------------------------------------------------------------
// eWiseAdd: C = A+B or C<M> = A+B
//------------------------------------------------------------------------------
GrB_Info GB (_AaddB__bclr_int16)
(
GrB_Matrix C,
const int C_sparsity,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const bool Ch_is_Mh,
const int64_t *restrict C_to_M,
const int64_t *restrict C_to_A,
const int64_t *restrict C_to_B,
const GB_task_struct *restrict TaskList,
const int C_ntasks,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
GB_WERK_DECLARE (M_ek_slicing, int64_t) ;
GB_WERK_DECLARE (A_ek_slicing, int64_t) ;
GB_WERK_DECLARE (B_ek_slicing, int64_t) ;
#include "GB_add_template.c"
GB_FREE_WORK ;
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C = A.*B or C<M> = A.*B
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_01__bclr_int16)
(
GrB_Matrix C,
const int C_sparsity,
const int ewise_method,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *restrict C_to_M,
const int64_t *restrict C_to_A,
const int64_t *restrict C_to_B,
const GB_task_struct *restrict TaskList,
const int C_ntasks,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_emult_01_meta.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_02__bclr_int16)
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const bool flipxy,
const int64_t *restrict Cp_kfirst,
const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#if GB_BINOP_FLIP
// The operator is not commutative, and does not have a flipped
// variant. For example z=atan2(y,x).
if (flipxy)
{
// use fmult(y,x)
#undef GB_FLIPPED
#define GB_FLIPPED 1
#include "GB_emult_02_template.c"
}
else
{
// use fmult(x,y)
#undef GB_FLIPPED
#define GB_FLIPPED 0
#include "GB_emult_02_template.c"
}
#else
// No need to handle the flip: the operator is either commutative, or
// has been handled by changing z=div(y,x) to z=rdiv(x,y) for example.
#undef GB_FLIPPED
#define GB_FLIPPED 0
#include "GB_emult_02_template.c"
#endif
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_03__bclr_int16)
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *restrict Cp_kfirst,
const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_emult_03_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_bitmap__bclr_int16)
(
GrB_Matrix C,
const int ewise_method,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_bitmap_emult_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st
//------------------------------------------------------------------------------
GrB_Info GB (_bind1st__bclr_int16)
(
GB_void *Cx_output, // Cx and Bx may be aliased
const GB_void *x_input,
const GB_void *Bx_input,
const int8_t *restrict Bb,
int64_t bnz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int16_t *Cx = (int16_t *) Cx_output ;
int16_t x = (*((int16_t *) x_input)) ;
int16_t *Bx = (int16_t *) Bx_input ;
int64_t p ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < bnz ; p++)
{
if (!GBB (Bb, p)) continue ;
int16_t bij = GBX (Bx, p, false) ;
Cx [p] = GB_BITCLR (x, bij, int16_t, 16) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd
//------------------------------------------------------------------------------
GrB_Info GB (_bind2nd__bclr_int16)
(
GB_void *Cx_output, // Cx and Ax may be aliased
const GB_void *Ax_input,
const GB_void *y_input,
const int8_t *restrict Ab,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
int16_t *Cx = (int16_t *) Cx_output ;
int16_t *Ax = (int16_t *) Ax_input ;
int16_t y = (*((int16_t *) y_input)) ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!GBB (Ab, p)) continue ;
int16_t aij = GBX (Ax, p, false) ;
Cx [p] = GB_BITCLR (aij, y, int16_t, 16) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (x, A'): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (x, aij), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
int16_t aij = GBX (Ax, pA, false) ; \
Cx [pC] = GB_BITCLR (x, aij, int16_t, 16) ; \
}
GrB_Info GB (_bind1st_tran__bclr_int16)
(
GrB_Matrix C,
const GB_void *x_input,
const GrB_Matrix A,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
// GB_unop_transpose.c uses GB_ATYPE, but A is
// the 2nd input to binary operator z=f(x,y).
#undef GB_ATYPE
#define GB_ATYPE \
int16_t
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int16_t x = (*((const int16_t *) x_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
#undef GB_ATYPE
#define GB_ATYPE \
int16_t
}
//------------------------------------------------------------------------------
// C = op (A', y): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (aij, y), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
int16_t aij = GBX (Ax, pA, false) ; \
Cx [pC] = GB_BITCLR (aij, y, int16_t, 16) ; \
}
GrB_Info GB (_bind2nd_tran__bclr_int16)
(
GrB_Matrix C,
const GrB_Matrix A,
const GB_void *y_input,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int16_t y = (*((const int16_t *) y_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
mput_ispc.c
|
#include "hmap_struct_isp.h"
// #include "hmap_aux.h"
// #include "hmap_get.h"
// #include "fasthash.h"
static inline void *
set_key(
void **keys,
uint32 i,
void *alt_keys,
uint32 key_len
)
{
void *key_i;
if ( keys != NULL ) {
key_i = keys[i];
}
else {
key_i = (void *)((int8 *)alt_keys + (i*key_len));
}
return key_i;
}
//--------------------------------
static inline void *
set_val(
void **vals,
uint32 i,
void *alt_vals,
uint32 val_len
)
{
void *val_i;
if ( vals != NULL ) {
val_i = vals[i];
}
else {
val_i = (void *)((int8 *)alt_vals + (i*val_len));
}
return val_i;
}
//--------------------------------
static inline uint16
set_key_len(
uint16 *key_lens,
uint32 i,
uint32 key_len
)
{
uint16 key_len_i;
if ( key_lens != NULL ) {
key_len_i = key_lens[i];
}
else {
key_len_i = key_len;
}
return key_len_i;
}
//--------------------------------
export void
hmap_mput(
uniform hmap_t * uniform ptr_hmap,
uniform hmap_multi_t * uniform M,
uniform void ** uniform keys, // [nkeys]
uint16 key_lens[], // [nkeys]
void *alt_keys, // either keys or alt_keys but not both
uint32 key_len,
uint32 nkeys,
void **vals, // [nkeys]
void *alt_vals, // either keys or alt_keys but not both
uint32 val_len
)
{
int status = 0;
if ( nkeys == 0 ) { goto BYE; }
//-------------------------------------------------
if ( keys == NULL ) {
if ( key_lens != NULL ) { go_BYE(-1); }
if ( alt_keys == NULL ) { go_BYE(-1); }
if ( key_len == 0 ) { go_BYE(-1); }
}
else {
if ( key_lens == NULL ) { go_BYE(-1); }
if ( alt_keys != NULL ) { go_BYE(-1); }
if ( key_len != 0 ) { go_BYE(-1); }
}
//-------------------------------------------------
if ( vals == NULL ) {
if ( alt_vals == NULL ) { go_BYE(-1); }
if ( val_len == 0 ) { go_BYE(-1); }
}
else {
if ( alt_vals != NULL ) { go_BYE(-1); }
if ( val_len != 0 ) { go_BYE(-1); }
}
//-------------------------------------------------
uint32 *idxs = M->idxs;
uint32 *hashes = M->hashes;
uint32 *locs = M->locs;
int8_t *tids = M->tids;
bool *exists = M->exists;
uint16 *m_key_len = M->m_key_len;
void **m_key = M->m_key;
int nP = M->num_procs;
#ifdef SEQUENTIAL
nP = 1;
#else
if ( nP <= 0 ) {
nP = omp_get_num_procs();
}
#endif
// fprintf(stderr, "Using %d cores \n", nP);
uint64 proc_divinfo = fast_div32_init(nP);
uint32 lb = 0, ub;
register uint64 hashkey = ptr_hmap->hashkey;
register uint64 divinfo = ptr_hmap->divinfo;
for ( int iter = 0; ; iter++ ) {
ub = lb + M->num_at_once;
if ( ub > nkeys ) { ub = nkeys; }
uint32 niters = ub - lb;
int num_per_core = 16; // so that no false sharing on write
bool do_sequential_loop = false;
#pragma omp parallel for num_threads(nP) schedule(static, 1)
for ( uint32 j = 0; j < niters; j += num_per_core ) {
uint32 i = j + lb;
//--------------------------------
m_key[j] = set_key(keys, i, alt_keys, key_len);
m_key_len[j] = set_key_len(key_lens, i, key_len);
dbg_t dbg;
idxs[j] = UINT_MAX; // bad value
// hashes[j] = murmurhash3(m_key[j], m_key_len[j], hashkey);
// hashes[j] = fasthash32(m_key[j], m_key_len[j], hashkey);
locs[j] = fast_rem32(hashes[j], ptr_hmap->size, divinfo);
dbg.hash = hashes[j]; dbg.probe_loc = locs[j];
int lstatus = hmap_get(ptr_hmap, m_key[j], m_key_len[j], NULL,
exists+j, idxs+j, &dbg);
// do not exist if bad status, this is an omp loop
if ( lstatus != 0 ) { if ( status == 0 ) { status = lstatus; } }
if ( !exists[j] ) { // new key=> insert in sequential loop
tids[j] = -1; // assigned to nobody, done in sequential loop
if ( do_sequential_loop == false ) {
do_sequential_loop = true;
}
}
else {
tids[j] = fast_rem32(hashes[j], nP, proc_divinfo);
}
}
cBYE(status);
if ( ub >= nkeys ) { break; }
lb += M->num_at_once;
}
BYE:
return status;
}
|
rose_pointers.c
|
// x1 and x2 may alias to each other. If no-aliasing assumed, the loop can be parallelized.
#include <omp.h>
void foo(double *x,int jp,int begin,int end,double rh1)
{
double *x1;
double *x2;
x1 = x;
x2 = x1 + jp;
#pragma omp parallel for firstprivate (end,rh1)
for (int i = begin; i <= end - 1; i += 1) {
x1[i] += rh1;
x2[i] -= rh1;
}
}
|
FEMTree.h
|
/*
Copyright (c) 2006, Michael Kazhdan and Matthew Bolitho
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list of
conditions and the following disclaimer. Redistributions in binary form must reproduce
the above copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the distribution.
Neither the name of the Johns Hopkins University nor the names of its contributors
may be used to endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
DAMAGE.
*/
// -- [TODO] Make as many of the functions (related to the solver) const as possible.
// -- [TODO] Move the point interpolation constraint scaling by 1<<maxDepth
// -- [TODO] Add support for staggered-grid test functions
// -- [TODO] Store signatures with constraints/systems/restriction-prolongations
// -- [TODO] Make a virtual evaluation that only needs to know the degree
// -- [TODO] Modify (public) functions so that template parameters don't need to be passed when they are called
// -- [TODO] Confirm that whenever _isValidFEM*Node is called, the flags have already been set.
// -- [TODO] Make weight evaluation more efficient in _getSamplesPerNode by reducing the number of calls to getNeighbors
// -- [TODO] For point evaluation:
// 1. Have the evaluator store stencils for all depths [DONE]
// 2. When testing centers/corners, don't use generic evaluation
#ifndef FEM_TREE_INCLUDED
#define FEM_TREE_INCLUDED
#define VERSION "10.02"
#define MEMORY_ALLOCATOR_BLOCK_SIZE 1<<12
#define NEW_CODE
// SOR=0.125 sorPower=6
#include <atomic>
#include "MyMiscellany.h"
#include "BSplineData.h"
#include "Geometry.h"
#include "PointStream.h"
#include "RegularTree.h"
#include "SparseMatrix.h"
#include <functional>
template< unsigned int Dim , class Real > class FEMTree;
enum
{
SHOW_GLOBAL_RESIDUAL_NONE ,
SHOW_GLOBAL_RESIDUAL_LAST ,
SHOW_GLOBAL_RESIDUAL_ALL ,
SHOW_GLOBAL_RESIDUAL_COUNT
};
const char* ShowGlobalResidualNames[] = { "show none" , "show last" , "show all" };
class FEMTreeNodeData
{
public:
enum
{
SPACE_FLAG = 1 ,
FEM_FLAG_1 = 2 ,
FEM_FLAG_2 = 4 ,
REFINABLE_FLAG = 8 ,
GHOST_FLAG = 1<<7
};
int nodeIndex;
mutable char flags;
void setGhostFlag( bool f ) const { if( f ) flags |= GHOST_FLAG ; else flags &= ~GHOST_FLAG; }
bool getGhostFlag( void ) const { return ( flags & GHOST_FLAG )!=0; }
FEMTreeNodeData( void );
~FEMTreeNodeData( void );
};
template< unsigned int Dim >
class SortedTreeNodes
{
typedef RegularTreeNode< Dim , FEMTreeNodeData > TreeNode;
protected:
Pointer( Pointer( int ) ) _sliceStart;
int _levels;
public:
Pointer( TreeNode* ) treeNodes;
int begin( int depth ) const { return _sliceStart[depth][0]; }
int end( int depth ) const { return _sliceStart[depth][(size_t)1<<depth]; }
int begin( int depth , int slice ) const { return _sliceStart[depth][ slice<0 ? 0 : ( slice>(1<<depth) ? (1<<depth) : slice ) ]; }
int end( int depth , int slice ) const { return begin( depth , slice+1 ); }
int size( void ) const { return _sliceStart[_levels-1][(size_t)1<<(_levels-1)]; }
int size( int depth ) const { if(depth<0||depth>=_levels) printf( "uhoh\n" ); return _sliceStart[depth][(size_t)1<<depth] - _sliceStart[depth][0]; }
int size( int depth , int slice ) const { return end( depth , slice ) - begin( depth , slice ); }
int levels( void ) const { return _levels; }
SortedTreeNodes( void );
~SortedTreeNodes( void );
void set( TreeNode& root , std::vector< int >* map );
size_t set( TreeNode& root );
};
template< typename T > struct DotFunctor{};
template< > struct DotFunctor< float >
{
double operator()( float v1 , float v2 ){ return v1*v2; }
unsigned int dimension( void ) const { return 1; }
};
template< > struct DotFunctor< double >
{
double operator()( double v1 , double v2 ){ return v1*v2; }
unsigned int dimension( void ) const { return 1; }
};
template< class Real , unsigned int Dim > struct DotFunctor< Point< Real , Dim > >
{
double operator()( Point< Real , Dim > v1 , Point< Real , Dim > v2 ){ return Point< Real , Dim >::Dot( v1 , v2 ); }
unsigned int dimension( void ) const { return Dim; }
};
template< typename Pack > struct SupportKey{ };
template< unsigned int ... Degrees >
struct SupportKey< UIntPack< Degrees ... > > : public RegularTreeNode< sizeof...(Degrees) , FEMTreeNodeData >::template NeighborKey< UIntPack< (-BSplineSupportSizes< Degrees >::SupportStart) ... > , UIntPack< BSplineSupportSizes< Degrees >::SupportEnd ... > >
{
typedef UIntPack< (-BSplineSupportSizes< Degrees >::SupportStart ) ... > LeftRadii;
typedef UIntPack< ( BSplineSupportSizes< Degrees >::SupportEnd ) ... > RightRadii;
typedef UIntPack< ( BSplineSupportSizes< Degrees >::SupportSize ) ... > Sizes;
};
template< typename Pack > struct ConstSupportKey{ };
template< unsigned int ... Degrees >
struct ConstSupportKey< UIntPack< Degrees ... > > : public RegularTreeNode< sizeof...(Degrees) , FEMTreeNodeData >::template ConstNeighborKey< UIntPack< (-BSplineSupportSizes< Degrees >::SupportStart ) ... > , UIntPack< BSplineSupportSizes< Degrees >::SupportEnd ... > >
{
typedef UIntPack< (-BSplineSupportSizes< Degrees >::SupportStart ) ... > LeftRadii;
typedef UIntPack< ( BSplineSupportSizes< Degrees >::SupportEnd ) ... > RightRadii;
typedef UIntPack< ( BSplineSupportSizes< Degrees >::SupportSize ) ... > Sizes;
};
template< typename Pack > struct OverlapKey{ };
template< unsigned int ... Degrees >
struct OverlapKey< UIntPack< Degrees ... > > : public RegularTreeNode< sizeof...(Degrees) , FEMTreeNodeData >::template NeighborKey< UIntPack< (-BSplineOverlapSizes< Degrees , Degrees >::OverlapStart ) ... > , UIntPack< BSplineOverlapSizes< Degrees , Degrees >::OverlapEnd ... > >
{
typedef UIntPack< (-BSplineOverlapSizes< Degrees , Degrees >::OverlapStart ) ... > LeftRadii;
typedef UIntPack< ( BSplineOverlapSizes< Degrees , Degrees >::OverlapEnd ) ... > RightRadii;
typedef UIntPack< ( BSplineOverlapSizes< Degrees , Degrees >::OverlapSize ) ... > Sizes;
};
template< typename Pack > struct ConstOverlapKey{ };
template< unsigned int ... Degrees >
struct ConstOverlapKey< UIntPack< Degrees ... > > : public RegularTreeNode< sizeof...(Degrees) , FEMTreeNodeData >::template ConstNeighborKey< UIntPack< (-BSplineOverlapSizes< Degrees , Degrees >::OverlapStart ) ... > , UIntPack< BSplineOverlapSizes< Degrees , Degrees >::OverlapEnd ... > >
{
typedef UIntPack< (-BSplineOverlapSizes< Degrees , Degrees >::OverlapStart ) ... > LeftRadii;
typedef UIntPack< ( BSplineOverlapSizes< Degrees , Degrees >::OverlapEnd ) ... > RightRadii;
typedef UIntPack< ( BSplineOverlapSizes< Degrees , Degrees >::OverlapSize ) ... > Sizes;
};
template< typename Pack > struct PointSupportKey{ };
template< unsigned int ... Degrees >
struct PointSupportKey< UIntPack< Degrees ... > > : public RegularTreeNode< sizeof...(Degrees) , FEMTreeNodeData >::template NeighborKey< UIntPack< BSplineSupportSizes< Degrees >::SupportEnd ... > , UIntPack< (-BSplineSupportSizes< Degrees >::SupportStart ) ... > >
{
typedef UIntPack< ( BSplineSupportSizes< Degrees >::SupportEnd ) ... > LeftRadii;
typedef UIntPack< (-BSplineSupportSizes< Degrees >::SupportStart ) ... > RightRadii;
typedef UIntPack< ( BSplineSupportSizes< Degrees >::SupportEnd - BSplineSupportSizes< Degrees >::SupportStart + 1 ) ... > Sizes;
};
template< typename Pack > struct ConstPointSupportKey{ };
template< unsigned int ... Degrees >
struct ConstPointSupportKey< UIntPack< Degrees ... > > : public RegularTreeNode< sizeof...(Degrees) , FEMTreeNodeData >::template ConstNeighborKey< UIntPack< BSplineSupportSizes< Degrees >::SupportEnd ... > , UIntPack< (-BSplineSupportSizes< Degrees >::SupportStart ) ... > >
{
typedef UIntPack< ( BSplineSupportSizes< Degrees >::SupportEnd ) ... > LeftRadii;
typedef UIntPack< (-BSplineSupportSizes< Degrees >::SupportStart ) ... > RightRadii;
typedef UIntPack< ( BSplineSupportSizes< Degrees >::SupportEnd - BSplineSupportSizes< Degrees >::SupportStart + 1 ) ... > Sizes;
};
template< typename Pack > struct CornerSupportKey{ };
template< unsigned int ... Degrees >
struct CornerSupportKey< UIntPack< Degrees ... > > : public RegularTreeNode< sizeof...(Degrees) , FEMTreeNodeData >::template NeighborKey< UIntPack< BSplineSupportSizes< Degrees >::BCornerEnd ... > , UIntPack< ( -BSplineSupportSizes< Degrees >::BCornerStart + 1 ) ... > >
{
typedef UIntPack< ( BSplineSupportSizes< Degrees >::BCornerEnd ) ... > LeftRadii;
typedef UIntPack< (-BSplineSupportSizes< Degrees >::BCornerStart + 1 ) ... > RightRadii;
typedef UIntPack< ( BSplineSupportSizes< Degrees >::BCornerSize + 1 ) ... > Sizes;
};
template< typename Pack > struct ConstCornerSupportKey{ };
template< unsigned int ... Degrees >
struct ConstCornerSupportKey< UIntPack< Degrees ... > > : public RegularTreeNode< sizeof...(Degrees) , FEMTreeNodeData >::template ConstNeighborKey< UIntPack< BSplineSupportSizes< Degrees >::BCornerEnd ... > , UIntPack< ( -BSplineSupportSizes< Degrees >::BCornerStart + 1 ) ... > >
{
typedef UIntPack< ( BSplineSupportSizes< Degrees >::BCornerEnd ) ... > LeftRadii;
typedef UIntPack< (-BSplineSupportSizes< Degrees >::BCornerStart + 1 ) ... > RightRadii;
typedef UIntPack< ( BSplineSupportSizes< Degrees >::BCornerSize + 1 ) ... > Sizes;
};
// This represents a vector that can only grow in size.
// It has the property that once a reference to an element is returned, that reference remains valid until the vector is destroyed.
template< typename T , unsigned int LogBlockSize=10 , unsigned InitialBlocks=10 , unsigned int AllocationMultiplier=2 >
struct BlockedVector
{
BlockedVector( T defaultValue=T() ) : _defaultValue( defaultValue )
{
_reservedBlocks = InitialBlocks;
_blocks = NewPointer< Pointer( T ) >( _reservedBlocks );
for( size_t i=0 ; i<_reservedBlocks ; i++ ) _blocks[i] = NullPointer( Pointer( T ) );
_allocatedBlocks = _size = 0;
}
~BlockedVector( void )
{
for( size_t i=0 ; i<_allocatedBlocks ; i++ ) DeletePointer( _blocks[i] );
DeletePointer( _blocks );
}
BlockedVector( const BlockedVector& v )
{
_reservedBlocks = v._reservedBlocks , _allocatedBlocks = v._allocatedBlocks , _size = v._size , _defaultValue = v._defaultValue;
_blocks = NewPointer< Pointer( T ) >( _reservedBlocks );
for( size_t i=0 ; i<_allocatedBlocks ; i++ )
{
_blocks[i] = NewPointer< T >( _BlockSize );
memcpy( _blocks[i] , v._blocks[i] , sizeof(T)*_BlockSize );
}
for( size_t i=_allocatedBlocks ; i<_reservedBlocks ; i++ ) _blocks[i] = NullPointer( Pointer ( T ) );
}
BlockedVector& operator = ( const BlockedVector& v )
{
for( size_t i=0 ; i<_allocatedBlocks ; i++ ) DeletePointer( _blocks[i] );
DeletePointer( _blocks );
_reservedBlocks = v._reservedBlocks , _blocks = v._blocks , _allocatedBlocks = v._allocatedBlocks , _size = v._size , _defaultValue = v._defaultValue;
_blocks = NewPointer< Pointer( T ) >( _reservedBlocks );
for( size_t i=0 ; i<_allocatedBlocks ; i++ )
{
_blocks[i] = NewPointer< T >( _BlockSize );
memcpy( _blocks[i] , v._blocks[i] , sizeof(T)*_BlockSize );
}
for( size_t i=_allocatedBlocks ; i<_reservedBlocks ; i++ ) _blocks[i] = NullPointer( Pointer ( T ) );
return *this;
}
BlockedVector( BlockedVector&& v )
{
_reservedBlocks = v._reservedBlocks , _allocatedBlocks = v._allocatedBlocks , _size = v._size , _defaultValue = v._defaultValue , _blocks = v._blocks;
v._reservedBlocks = v._allocatedBlocks = v._size = 0 , v._blocks = NullPointer( Pointer( T ) );
}
BlockedVector& operator = ( BlockedVector&& v )
{
for( size_t i=0 ; i<_allocatedBlocks ; i++ ) DeletePointer( _blocks[i] );
DeletePointer( _blocks );
_reservedBlocks = v._reservedBlocks , _allocatedBlocks = v._allocatedBlocks , _size = v._size , _defaultValue = v._defaultValue , _blocks = v._blocks;
v._reservedBlocks = v._allocatedBlocks = v._size = 0 , v._blocks = NullPointer( Pointer( T ) );
return *this;
}
size_t size( void ) const { return _size; }
const T& operator[]( size_t idx ) const { return _blocks[idx>>LogBlockSize][idx&_Mask]; }
T& operator[]( size_t idx ){ return _blocks[idx>>LogBlockSize][idx&_Mask]; }
size_t resize( size_t size ){ return resize( size , _defaultValue ); }
size_t resize( size_t size , const T& defaultValue )
{
if( size<=_size )
{
#ifdef _MSC_VER
fprintf( stderr , "[WARNING] BlockedVector::resize: new size must be greater than old size: %llu > %llu\n" , size , _size );
#else // !MSC_VER
fprintf( stderr , "[WARNING] BlockedVector::resize: new size must be greater than old size: %lu > %lu\n" , size , _size );
#endif // _MSC_VER
return _size;
}
size_t index = size-1;
size_t block = index >> LogBlockSize;
size_t blockIndex = index & _Mask;
// If there are insufficiently many blocks
if( block>=_reservedBlocks )
{
size_t newReservedSize = std::max< size_t >( _reservedBlocks * AllocationMultiplier , block+1 );
Pointer( Pointer( T ) ) __blocks = NewPointer< Pointer( T ) >( newReservedSize );
memcpy( __blocks , _blocks , sizeof( Pointer( T ) ) * _reservedBlocks );
for( size_t i=_reservedBlocks ; i<newReservedSize ; i++ ) __blocks[i] = NullPointer( Pointer( T ) );
Pointer( Pointer( T ) ) _oldBlocks = _blocks;
_blocks = __blocks;
_reservedBlocks = newReservedSize;
DeletePointer( _oldBlocks );
}
// If the block hasn't been allocated
if( block>=_allocatedBlocks )
{
for( size_t b=_allocatedBlocks ; b<=block ; b++ )
{
_blocks[b] = NewPointer< T >( _BlockSize );
for( size_t i=0 ; i<_BlockSize ; i++ ) _blocks[b][i] = defaultValue;
}
_allocatedBlocks = block+1;
}
_size = index+1;
return index;
}
size_t push( void ){ return resize( _size+1 ); }
protected:
static const size_t _BlockSize = 1<<LogBlockSize;
static const size_t _Mask = (1<<LogBlockSize)-1;
T _defaultValue;
size_t _allocatedBlocks , _reservedBlocks;
size_t _size;
Pointer( Pointer( T ) ) _blocks;
};
template< class Data , typename Pack > struct _SparseOrDenseNodeData{};
template< class Data , unsigned int ... FEMSigs >
struct _SparseOrDenseNodeData< Data , UIntPack< FEMSigs ... > >
{
static const unsigned int Dim = sizeof ... ( FEMSigs );
typedef UIntPack< FEMSigs ... > FEMSignatures;
typedef Data data_type;
virtual size_t size( void ) const = 0;
virtual const Data& operator[] ( int idx ) const = 0;
virtual Data& operator[] ( int idx ) = 0;
virtual Data& operator[]( const RegularTreeNode< Dim , FEMTreeNodeData >* node ) = 0;
virtual Data* operator()( const RegularTreeNode< Dim , FEMTreeNodeData >* node ) = 0;
virtual const Data* operator()( const RegularTreeNode< Dim , FEMTreeNodeData >* node ) const = 0;
};
template< class Data , typename Pack > struct SparseNodeData{};
template< class Data , unsigned int ... FEMSigs >
struct SparseNodeData< Data , UIntPack< FEMSigs ... > > : public _SparseOrDenseNodeData< Data , UIntPack< FEMSigs ... > >
{
static const unsigned int Dim = sizeof ... ( FEMSigs );
size_t size( void ) const { return _data.size(); }
const Data& operator[] ( int idx ) const { return _data[idx]; }
Data& operator[] ( int idx ) { return _data[idx]; }
void reserve( size_t sz ){ if( sz>_indices.size() ) _indices.resize( sz , -1 ); }
Data* operator()( const RegularTreeNode< Dim , FEMTreeNodeData >* node ){ return ( node->nodeData.nodeIndex<0 || node->nodeData.nodeIndex>=(int)_indices.size() || _indices[ node->nodeData.nodeIndex ]<0 ) ? NULL : &_data[ _indices[ node->nodeData.nodeIndex ] ]; }
const Data* operator()( const RegularTreeNode< Dim , FEMTreeNodeData >* node ) const { return ( node->nodeData.nodeIndex<0 || node->nodeData.nodeIndex>=(int)_indices.size() || _indices[ node->nodeData.nodeIndex ]<0 ) ? NULL : &_data[ _indices[ node->nodeData.nodeIndex ] ]; }
Data& operator[]( const RegularTreeNode< Dim , FEMTreeNodeData >* node )
{
// If the node hasn't been indexed yet
if( node->nodeData.nodeIndex>=(int)_indices.size() )
#pragma omp critical( SparseNodeData__operator )
if( node->nodeData.nodeIndex>=(int)_indices.size() ) _indices.resize( node->nodeData.nodeIndex+1 , -1 );
// If the node hasn't been allocated yet
if( _indices[ node->nodeData.nodeIndex ]==-1 )
#pragma omp critical( SparseNodeData__operator )
if( _indices[ node->nodeData.nodeIndex ]==-1 ) _indices[ node->nodeData.nodeIndex ] = (int)_data.push();
return _data[ _indices[ node->nodeData.nodeIndex ] ];
}
int index( const RegularTreeNode< Dim , FEMTreeNodeData >* node ) const
{
if( !node || node->nodeData.nodeIndex<0 || node->nodeData.nodeIndex>=(int)_indices.size() ) return -1;
else return _indices[ node->nodeData.nodeIndex ];
}
protected:
template< unsigned int _Dim , class _Real > friend class FEMTree;
// Map should be the size of the old number of entries and map[i] should give the new index of the old i-th node
void _remapIndices( const int* newNodeIndices , unsigned int newNodeCount )
{
BlockedVector< int > newIndices;
newIndices.resize( newNodeCount );
for( int i=0 ; i<(int)newNodeCount ; i++ ) newIndices[i] = -1;
for( size_t i=0 ; i<(int)_indices.size() ; i++ ) if( newNodeIndices[i]>=0 && newNodeIndices[i]<(int)newNodeCount ) newIndices[ newNodeIndices[i] ] = _indices[i];
_indices = newIndices;
}
BlockedVector< int > _indices;
BlockedVector< Data > _data;
};
template< class Data , typename Pack > struct DenseNodeData{};
template< class Data , unsigned int ... FEMSigs >
struct DenseNodeData< Data , UIntPack< FEMSigs ... > > : public _SparseOrDenseNodeData< Data , UIntPack< FEMSigs ... > >
{
static const unsigned int Dim = sizeof ... ( FEMSigs );
DenseNodeData( void ) { _data = NullPointer( Data ) ; _sz = 0; }
DenseNodeData( size_t sz ){ _sz = sz ; if( sz ) _data = NewPointer< Data >( sz ) ; else _data = NullPointer( Data ); }
DenseNodeData( const DenseNodeData& d ) : DenseNodeData() { _resize( d._sz ) ; if( _sz ) memcpy( _data , d._data , sizeof(Data) * _sz ); }
DenseNodeData( DenseNodeData&& d ){ _data = d._data , _sz = d._sz ; d._data = NullPointer( Data ) , d._sz = 0; }
DenseNodeData& operator = ( const DenseNodeData& d ){ _resize( d._sz ) ; if( _sz ) memcpy( _data , d._data , sizeof(Data) * _sz ) ; return *this; }
DenseNodeData& operator = ( DenseNodeData&& d ){ size_t __sz = _sz ; Pointer( Data ) __data = _data ; _data = d._data , _sz = d._sz ; d._data = __data , d._sz = __sz ; return *this; }
~DenseNodeData( void ){ DeletePointer( _data ) ; _sz = 0; }
static void WriteSignatures( FILE* fp )
{
unsigned int dim = sizeof ... ( FEMSigs );
fwrite( &dim , sizeof(unsigned int) , 1 , fp );
unsigned int femSigs[] = { FEMSigs ... };
fwrite( femSigs , sizeof(unsigned int) , dim , fp );
}
void write( FILE* fp ) const { fwrite( &_sz , sizeof(size_t) , 1 , fp ) ; fwrite( _data , sizeof(Data) , _sz , fp ); }
void read ( FILE* fp )
{
if( fread( &_sz , sizeof(size_t) , 1 , fp )!=1 ) fprintf( stderr , "[ERROR] DenseNodeData::read: Failed to read size\n" ) , exit( 0 );
_data = NewPointer< Data >( _sz );
if( fread ( _data , sizeof(Data) , _sz , fp )!=_sz ) fprintf( stderr , "[ERROR] DenseNodeData::read failed to read data\n" ) , exit( 0 );
}
Data& operator[] ( int idx ) { return _data[idx]; }
const Data& operator[] ( int idx ) const { return _data[idx]; }
size_t size( void ) const { return _sz; }
Data& operator[]( const RegularTreeNode< Dim , FEMTreeNodeData >* node ) { return _data[ node->nodeData.nodeIndex ]; }
Data* operator()( const RegularTreeNode< Dim , FEMTreeNodeData >* node ) { return ( node==NULL || node->nodeData.nodeIndex>=(int)_sz ) ? NULL : &_data[ node->nodeData.nodeIndex ]; }
const Data* operator()( const RegularTreeNode< Dim , FEMTreeNodeData >* node ) const { return ( node==NULL || node->nodeData.nodeIndex>=(int)_sz ) ? NULL : &_data[ node->nodeData.nodeIndex ]; }
int index( const RegularTreeNode< Dim , FEMTreeNodeData >* node ) const { return ( !node || node->nodeData.nodeIndex<0 || node->nodeData.nodeIndex>=(int)this->_data.size() ) ? -1 : node->nodeData.nodeIndex; }
Pointer( Data ) operator()( void ) { return _data; }
ConstPointer( Data ) operator()( void ) const { return ( ConstPointer( Data ) )_data; }
protected:
template< unsigned int _Dim , class _Real > friend class FEMTree;
// Map should be the size of the old number of entries and map[i] should give the new index of the old i-th node
void _remapIndices( const int* newNodeIndices , size_t newNodeCount )
{
Pointer( Data ) newData = NewPointer< Data >( newNodeCount );
memset( newData , 0 , sizeof(Data)*newNodeCount );
for( size_t i=0 ; i<_sz ; i++ ) if( newNodeIndices[i]>=0 && newNodeIndices[i]<newNodeCount ) newData[ newNodeIndices[i] ] = _data[i];
DeletePointer( _data );
_data = newData;
_sz = newNodeCount;
}
size_t _sz;
void _resize( size_t sz ){ DeletePointer( _data ) ; if( sz ) _data = NewPointer< Data >( sz ) ; else _data = NullPointer( Data ) ; _sz = sz; }
Pointer( Data ) _data;
};
enum FEMTreeRealType
{
FEM_TREE_REAL_FLOAT ,
FEM_TREE_REAL_DOUBLE ,
FEM_TREE_REAL_COUNT
};
const char* FEMTreeRealNames[] = { "float" , "double" };
void ReadFEMTreeParameter( FILE* fp , FEMTreeRealType& realType , int &dimension )
{
if( fread( &realType , sizeof(FEMTreeRealType) , 1 , fp )!=1 ) fprintf( stderr , "[ERROR] ReadFEMTreeParameter: Failed to read real type\n" ) , exit( 0 );
if( fread( &dimension , sizeof(int) , 1 , fp )!=1 ) fprintf( stderr , "[ERROR] ReadFEMTreeParameter: Failed to read dimension\n" ) , exit( 0 );
}
unsigned int* ReadDenseNodeDataSignatures( FILE* fp , unsigned int& dim )
{
if( fread( &dim , sizeof(int) , 1 , fp )!=1 ) fprintf( stderr , "[ERROR] ReadDenseNodeDataSignatures: Failed to read dimension\n" ) , exit( 0 );
unsigned int* femSigs = new unsigned int[dim];
if( fread( femSigs , sizeof(unsigned int) , dim , fp )!=dim ) fprintf( stderr , "[ERROR] ReadDenseNodeDataSignatures: Failed to read signatures\n" ) , exit( 0 );
return femSigs;
}
// The Derivative method needs static members:
// Dim: the dimensionality of the space in which derivatives are evaluated
// Size: the total number of derivatives
// and static methods:
// Index: takes the number of partials along each dimension and returns the index
// Factor: takes an index and sets the number of partials along each dimension
template< typename T > struct TensorDerivatives{ };
template< class Real , typename T > struct TensorDerivativeValues{ };
// Specify the derivatives for each dimension separately
template< unsigned int D , unsigned int ... Ds >
struct TensorDerivatives< UIntPack< D , Ds ... > >
{
typedef TensorDerivatives< UIntPack< Ds ... > > _TensorDerivatives;
static const int LastDerivative = UIntPack< D , Ds ... >::template Get< sizeof ... (Ds) >();
static const int Dim = _TensorDerivatives::Dim + 1;
static const unsigned int Size = _TensorDerivatives::Size * ( D+1 );
static void Factor( unsigned int idx , unsigned int derivatives[Dim] ){ derivatives[0] = idx / _TensorDerivatives::Size ; _TensorDerivatives::Factor( idx % _TensorDerivatives::Size , derivatives+1 ); }
static unsigned int Index( const unsigned int derivatives[Dim] ){ return _TensorDerivatives::Index( derivatives + 1 ) + _TensorDerivatives::Size * derivatives[0]; }
};
template< unsigned int D >
struct TensorDerivatives< UIntPack< D > >
{
static const int LastDerivative = D;
static const int Dim = 1;
static const unsigned int Size = D+1;
static void Factor( unsigned int idx , unsigned int derivatives[1] ){ derivatives[0] = idx; }
static unsigned int Index( const unsigned int derivatives[1] ){ return derivatives[0]; }
};
template< class Real , unsigned int ... Ds > struct TensorDerivativeValues< Real , UIntPack< Ds ... > > : public Point< Real , TensorDerivatives< UIntPack< Ds ... > >::Size >{ };
// Specify the sum of the derivatives
template< unsigned int Dim , unsigned int D >
struct CumulativeDerivatives
{
typedef CumulativeDerivatives< Dim , D-1 > _CumulativeDerivatives;
static const int LastDerivative = D;
static const unsigned int Size = _CumulativeDerivatives::Size * Dim + 1;
static void Factor( unsigned int idx , unsigned int d[Dim] )
{
if( idx<_CumulativeDerivatives::Size ) return _CumulativeDerivatives::Factor( idx , d );
else _Factor( idx - _CumulativeDerivatives::Size , d );
}
static unsigned int Index( const unsigned int derivatives[Dim] )
{
int dCount = 0;
for( int d=0 ; d<Dim ; d++ ) dCount += derivatives[d];
if( dCount>=D ) fprintf( stderr , "[ERROR] CumulativeDerivatives::Index: more derivatives than allowed\n" ) , exit( 0 );
else if( dCount<D ) return _CumulativeDerivatives::Index( derivatives );
else return _CumulativeDerivatives::Size + _Index( derivatives );
}
protected:
static const unsigned int _Size = _CumulativeDerivatives::_Size * Dim;
static void _Factor( unsigned int idx , unsigned int d[Dim] )
{
_CumulativeDerivatives::_Factor( idx % _CumulativeDerivatives::_Size , d );
d[ idx / _CumulativeDerivatives::_Size ]++;
}
static unsigned int _Index( const unsigned int d[Dim] )
{
unsigned int _d[Dim];
memcpy( _d , d , sizeof(_d) );
for( int i=0 ; i<Dim ; i++ ) if( _d[i] )
{
_d[i]--;
return _CumulativeDerivatives::Index( _d ) * Dim + i;
}
fprintf( stderr , "[ERROR] CumulativeDerivatives::_Index: no derivatives specified\n" ) , exit( 0 );
return -1;
}
friend CumulativeDerivatives< Dim , D+1 >;
};
template< unsigned int Dim >
struct CumulativeDerivatives< Dim , 0 >
{
static const int LastDerivative = 0;
static const unsigned int Size = 1;
static void Factor( unsigned int idx , unsigned int d[Dim] ){ memset( d , 0 , sizeof(unsigned int)*Dim ); }
static unsigned int Index( const unsigned int derivatives[Dim] ){ return 0; }
protected:
static const unsigned int _Size = 1;
static void _Factor( unsigned int idx , unsigned int d[Dim] ){ memset( d , 0 , sizeof(unsigned int)*Dim ); }
friend CumulativeDerivatives< Dim , 1 >;
};
template< typename Real , unsigned int Dim , unsigned int D > using CumulativeDerivativeValues = Point< Real , CumulativeDerivatives< Dim , D >::Size >;
template< unsigned int Dim , class Real , unsigned int D >
CumulativeDerivativeValues< Real , Dim , D > Evaluate( const double dValues[Dim][D+1] )
{
CumulativeDerivativeValues< Real , Dim , D > v;
unsigned int _d[Dim];
for( int d=0 ; d<CumulativeDerivatives< Dim , D >::Size ; d++ )
{
CumulativeDerivatives< Dim , D >::Factor( d , _d );
double value = dValues[0][ _d[0] ];
for( int dd=1 ; dd<Dim ; dd++ ) value *= dValues[dd][ _d[dd] ];
v[d] = (Real)value;
}
return v;
}
template< unsigned int Dim , class Real , typename T , unsigned int D >
struct DualPointInfo
{
Point< Real , Dim > position;
Real weight;
CumulativeDerivativeValues< T , Dim , D > dualValues;
DualPointInfo operator + ( const DualPointInfo& p ) const { return DualPointInfo( position + p.position , dualValues + p.dualValues , weight + p.weight ); }
DualPointInfo& operator += ( const DualPointInfo& p ){ position += p.position ; weight += p.weight , dualValues += p.dualValues ; return *this; }
DualPointInfo operator * ( Real s ) const { return DualPointInfo( position*s , weight*s , dualValues*s ); }
DualPointInfo& operator *= ( Real s ){ position *= s , weight *= s , dualValues *= s ; return *this; }
DualPointInfo operator / ( Real s ) const { return DualPointInfo( position/s , weight/s , dualValues/s ); }
DualPointInfo& operator /= ( Real s ){ position /= s , weight /= s , dualValues /= s ; return *this; }
DualPointInfo( void ) : weight(0) { }
DualPointInfo( Point< Real , Dim > p , CumulativeDerivativeValues< T , Dim , D > c , Real w ) { position = p , dualValues = c , weight = w; }
};
template< unsigned int Dim , class Real , typename Data , typename T , unsigned int D >
struct DualPointAndDataInfo
{
DualPointInfo< Dim , Real , T , D > pointInfo;
Data data;
DualPointAndDataInfo operator + ( const DualPointAndDataInfo& p ) const { return DualPointAndDataInfo( pointInfo + p.pointInfo , data + p.data ); }
DualPointAndDataInfo operator * ( Real s ) const { return DualPointAndDataInfo( pointInfo * s , data * s ); }
DualPointAndDataInfo operator / ( Real s ) const { return DualPointAndDataInfo( pointInfo / s , data / s ); }
DualPointAndDataInfo& operator += ( const DualPointAndDataInfo& p ){ pointInfo += p.pointInfo ; data += p.data ; return *this; }
DualPointAndDataInfo& operator *= ( Real s ) { pointInfo *= s , data *= s ; return *this; }
DualPointAndDataInfo& operator /= ( Real s ) { pointInfo /= s , data /= s ; return *this; }
DualPointAndDataInfo( void ){ }
DualPointAndDataInfo( DualPointInfo< Dim , Real , T , D > p , Data d ) { pointInfo = p , data = d; }
};
template< unsigned int Dim , class Real , typename T , unsigned int D >
struct DualPointInfoBrood
{
DualPointInfo< Dim , Real , T , D >& operator[]( size_t idx ){ return _dpInfo[idx]; }
const DualPointInfo< Dim , Real , T , D >& operator[]( size_t idx ) const { return _dpInfo[idx]; }
void finalize( void ){ _size = 0 ; for( int i=0 ; i<(1<<Dim) ; i++ ) if( _dpInfo[i].weight>0 ) _dpInfo[_size++] = _dpInfo[i]; }
unsigned int size( void ) const { return _size; }
DualPointInfoBrood operator + ( const DualPointInfoBrood& p ) const { DualPointInfoBrood d ; for( int i=0 ; i<(1<<Dim) ; i++ ) d._dpInfo[i] = _dpInfo[i] + p._dpInfo[i] ; return d; }
DualPointInfoBrood operator * ( Real s ) const { DualPointInfoBrood d ; for( int i=0 ; i<(1<<Dim) ; i++ ) d._dpInfo[i] = _dpInfo[i] * s ; return d; }
DualPointInfoBrood operator / ( Real s ) const { DualPointInfoBrood d ; for( int i=0 ; i<(1<<Dim) ; i++ ) d._dpInfo[i] = _dpInfo[i] / s ; return d; }
DualPointInfoBrood& operator += ( const DualPointInfoBrood& p ){ for( int i=0 ; i<(1<<Dim) ; i++ ) _dpInfo[i] += p._dpInfo[i] ; return *this; }
DualPointInfoBrood& operator *= ( Real s ) { for( int i=0 ; i<(1<<Dim) ; i++ ) _dpInfo[i] *= s ; return *this; }
DualPointInfoBrood& operator /= ( Real s ) { for( int i=0 ; i<(1<<Dim) ; i++ ) _dpInfo[i] /= s ; return *this; }
protected:
DualPointInfo< Dim , Real , T , D > _dpInfo[1<<Dim];
unsigned int _size;
};
template< unsigned int Dim , class Real , typename Data , typename T , unsigned int D >
struct DualPointAndDataInfoBrood
{
DualPointAndDataInfo< Dim , Real , Data , T , D >& operator[]( size_t idx ){ return _dpInfo[idx]; }
const DualPointAndDataInfo< Dim , Real , Data , T , D >& operator[]( size_t idx ) const { return _dpInfo[idx]; }
void finalize( void ){ _size = 0 ; for( int i=0 ; i<(1<<Dim) ; i++ ) if( _dpInfo[i].pointInfo.weight>0 ) _dpInfo[_size++] = _dpInfo[i]; }
unsigned int size( void ) const { return _size; }
DualPointAndDataInfoBrood operator + ( const DualPointAndDataInfoBrood& p ) const { DualPointAndDataInfoBrood d ; for( int i=0 ; i<(1<<Dim) ; i++ ) d._dpInfo[i] = _dpInfo[i] + p._dpInfo[i] ; return d; }
DualPointAndDataInfoBrood operator * ( Real s ) const { DualPointAndDataInfoBrood d ; for( int i=0 ; i<(1<<Dim) ; i++ ) d._dpInfo[i] = _dpInfo[i] * s ; return d; }
DualPointAndDataInfoBrood operator / ( Real s ) const { DualPointAndDataInfoBrood d ; for( int i=0 ; i<(1<<Dim) ; i++ ) d._dpInfo[i] = _dpInfo[i] / s ; return d; }
DualPointAndDataInfoBrood& operator += ( const DualPointAndDataInfoBrood& p ){ for( int i=0 ; i<(1<<Dim) ; i++ ) _dpInfo[i] += p._dpInfo[i] ; return *this; }
DualPointAndDataInfoBrood& operator *= ( Real s ) { for( int i=0 ; i<(1<<Dim) ; i++ ) _dpInfo[i] *= s ; return *this; }
DualPointAndDataInfoBrood& operator /= ( Real s ) { for( int i=0 ; i<(1<<Dim) ; i++ ) _dpInfo[i] /= s ; return *this; }
protected:
DualPointAndDataInfo< Dim , Real , Data , T , D > _dpInfo[1<<Dim];
unsigned int _size;
};
////////////////////////////
// The virtual integrator //
////////////////////////////
struct BaseFEMIntegrator
{
template< typename TDegreePack > struct System{};
template< typename TDegreePack > struct RestrictionProlongation{};
template< typename TDegreePack , typename CDegreePack , unsigned int CDim > struct Constraint{};
template< typename TDegreePack > struct SystemConstraint{};
template< typename TDegreePack > struct PointEvaluator{};
protected:
template< unsigned int Degree , unsigned int ... Degrees >
static typename std::enable_if< sizeof ... ( Degrees )==0 , bool >::type _IsInteriorlySupported( UIntPack< Degree , Degrees ... > , unsigned int depth , const int off[] )
{
int begin , end;
BSplineSupportSizes< Degree >::InteriorSupportedSpan( depth , begin , end );
return off[0]>=begin && off[0]<end;
}
template< unsigned int Degree , unsigned int ... Degrees >
static typename std::enable_if< sizeof ... ( Degrees )!=0 , bool >::type _IsInteriorlySupported( UIntPack< Degree , Degrees ... > , unsigned int depth , const int off[] )
{
int begin , end;
BSplineSupportSizes< Degree >::InteriorSupportedSpan( depth , begin , end );
return ( off[0]>=begin && off[0]<end ) && _IsInteriorlySupported( UIntPack< Degrees ... >() , depth , off+1 );
}
template< unsigned int Degree , unsigned int ... Degrees >
static typename std::enable_if< sizeof ... ( Degrees )==0 , bool >::type _IsInteriorlySupported( UIntPack< Degree , Degrees ... > , unsigned int depth , const int off[] , const double begin[] , const double end[] )
{
int res = 1<<depth;
double b = ( 0. + off[0] + BSplineSupportSizes< Degree >::SupportStart ) / res;
double e = ( 1. + off[0] + BSplineSupportSizes< Degree >::SupportEnd ) / res;
return b>=begin[0] && e<=end[0];
}
template< unsigned int Degree , unsigned int ... Degrees >
static typename std::enable_if< sizeof ... ( Degrees )!=0 , bool >::type _IsInteriorlySupported( UIntPack< Degree , Degrees ... > , unsigned int depth , const int off[] , const double begin[] , const double end[] )
{
int res = 1<<depth;
double b = ( 0. + off[0] + BSplineSupportSizes< Degree >::SupportStart ) / res;
double e = ( 1. + off[0] + BSplineSupportSizes< Degree >::SupportEnd ) / res;
return b>=begin[0] && e<=end[0] && _IsInteriorlySupported( UIntPack< Degrees ... >() , depth , off+1 , begin+1 , end+1 );
}
template< unsigned int Degree1 , unsigned int ... Degrees1 , unsigned int Degree2 , unsigned int ... Degrees2 >
static typename std::enable_if< sizeof ... ( Degrees1 )==0 >::type _InteriorOverlappedSpan( UIntPack< Degree1 , Degrees1 ... > , UIntPack< Degree2 , Degrees2 ... > , int depth , int begin[] , int end[] )
{
BSplineIntegrationData< FEMDegreeAndBType< Degree1 , BOUNDARY_NEUMANN >::Signature , FEMDegreeAndBType< Degree2 , BOUNDARY_NEUMANN >::Signature >::InteriorOverlappedSpan( depth , begin[0] , end[0] );
}
template< unsigned int Degree1 , unsigned int ... Degrees1 , unsigned int Degree2 , unsigned int ... Degrees2 >
static typename std::enable_if< sizeof ... ( Degrees1 )!=0 >::type _InteriorOverlappedSpan( UIntPack< Degree1 , Degrees1 ... > , UIntPack< Degree2 , Degrees2 ... > , int depth , int begin[] , int end[] )
{
BSplineIntegrationData< FEMDegreeAndBType< Degree1 , BOUNDARY_NEUMANN >::Signature , FEMDegreeAndBType< Degree2 , BOUNDARY_NEUMANN >::Signature >::InteriorOverlappedSpan( depth , begin[0] , end[0] );
_InteriorOverlappedSpan( UIntPack< Degrees1 ... >() , UIntPack< Degrees2 ... >() , depth , begin+1 , end+1 );
}
template< unsigned int Degree1 , unsigned int ... Degrees1 , unsigned int Degree2 , unsigned int ... Degrees2 >
static typename std::enable_if< sizeof ... ( Degrees1 )==0 , bool >::type _IsInteriorlyOverlapped( UIntPack< Degree1 , Degrees1 ... > , UIntPack< Degree2 , Degrees2 ... > , unsigned int depth , const int off[] )
{
int begin , end;
BSplineIntegrationData< FEMDegreeAndBType< Degree1 , BOUNDARY_NEUMANN >::Signature , FEMDegreeAndBType< Degree2 , BOUNDARY_NEUMANN >::Signature >::InteriorOverlappedSpan( depth , begin , end );
return off[0]>= begin && off[0]<end;
}
template< unsigned int Degree1 , unsigned int ... Degrees1 , unsigned int Degree2 , unsigned int ... Degrees2 >
static typename std::enable_if< sizeof ... ( Degrees1 )!=0 , bool >::type _IsInteriorlyOverlapped( UIntPack< Degree1 , Degrees1 ... > , UIntPack< Degree2 , Degrees2 ... > , unsigned int depth , const int off[] )
{
int begin , end;
BSplineIntegrationData< FEMDegreeAndBType< Degree1 , BOUNDARY_NEUMANN >::Signature , FEMDegreeAndBType< Degree2 , BOUNDARY_NEUMANN >::Signature >::InteriorOverlappedSpan( depth , begin , end );
return ( off[0]>= begin && off[0]<end ) && _IsInteriorlyOverlapped( UIntPack< Degrees1 ... >() , UIntPack< Degrees2 ... >() , depth , off+1 );
}
template< unsigned int Degree1 , unsigned int ... Degrees1 , unsigned int Degree2 , unsigned int ... Degrees2 >
static typename std::enable_if< sizeof ... ( Degrees1 )==0 >::type _ParentOverlapBounds( UIntPack< Degree1 , Degrees1 ... > , UIntPack< Degree2 , Degrees2 ... > , unsigned int depth , const int off[] , int start[] , int end[] )
{
const int OverlapStart = BSplineOverlapSizes< Degree1 , Degree2 >::OverlapStart;
start[0] = BSplineOverlapSizes< Degree1 , Degree2 >::ParentOverlapStart[ off[0] & 1 ] - OverlapStart;
end [0] = BSplineOverlapSizes< Degree1 , Degree2 >::ParentOverlapEnd [ off[0] & 1 ] - OverlapStart + 1;
}
template< unsigned int Degree1 , unsigned int ... Degrees1 , unsigned int Degree2 , unsigned int ... Degrees2 >
static typename std::enable_if< sizeof ... ( Degrees1 )!=0 >::type _ParentOverlapBounds( UIntPack< Degree1 , Degrees1 ... > , UIntPack< Degree2 , Degrees2 ... > , unsigned int depth , const int off[] , int start[] , int end[] )
{
const int OverlapStart = BSplineOverlapSizes< Degree1 , Degree2 >::OverlapStart;
start[0] = BSplineOverlapSizes< Degree1 , Degree2 >::ParentOverlapStart[ off[0] & 1 ] - OverlapStart;
end [0] = BSplineOverlapSizes< Degree1 , Degree2 >::ParentOverlapEnd [ off[0] & 1 ] - OverlapStart + 1;
_ParentOverlapBounds( UIntPack< Degrees1 ... >() , UIntPack< Degrees2 ... >() , depth , off+1 , start+1 , end+1 );
}
template< unsigned int Degree1 , unsigned int ... Degrees1 , unsigned int Degree2 , unsigned int ... Degrees2 >
static typename std::enable_if< sizeof ... ( Degrees1 )==0 >::type _ParentOverlapBounds( UIntPack< Degree1 , Degrees1 ... > , UIntPack< Degree2 , Degrees2 ... > , int corner , int start[] , int end[] )
{
const int OverlapStart = BSplineOverlapSizes< Degree1 , Degree2 >::OverlapStart;
start[0] = BSplineOverlapSizes< Degree1 , Degree2 >::ParentOverlapStart[ corner & 1 ] - OverlapStart;
end [0] = BSplineOverlapSizes< Degree1 , Degree2 >::ParentOverlapEnd [ corner & 1 ] - OverlapStart + 1;
}
template< unsigned int Degree1 , unsigned int ... Degrees1 , unsigned int Degree2 , unsigned int ... Degrees2 >
static typename std::enable_if< sizeof ... ( Degrees1 )!=0 >::type _ParentOverlapBounds( UIntPack< Degree1 , Degrees1 ... > , UIntPack< Degree2 , Degrees2 ... > , int corner , int start[] , int end[] )
{
const int OverlapStart = BSplineOverlapSizes< Degree1 , Degree2 >::OverlapStart;
start[0] = BSplineOverlapSizes< Degree1 , Degree2 >::ParentOverlapStart[ corner & 1 ] - OverlapStart;
end [0] = BSplineOverlapSizes< Degree1 , Degree2 >::ParentOverlapEnd [ corner & 1 ] - OverlapStart + 1;
_ParentOverlapBounds( UIntPack< Degrees1 ... >() , UIntPack< Degrees2 ... >() , corner>>1 , start+1 , end+1 );
}
public:
template< unsigned int ... Degrees >
static bool IsInteriorlySupported( UIntPack< Degrees ... > , int depth , const int offset[] ){ return depth>=0 && _IsInteriorlySupported( UIntPack< Degrees ... >() , depth , offset ); }
template< unsigned int ... Degrees >
static bool IsInteriorlySupported( UIntPack< Degrees ... > , int depth , const int offset[] , const double begin[] , const double end[] ){ return depth>=0 && _IsInteriorlySupported( UIntPack< Degrees ... >() , depth , offset , begin , end ); }
template< unsigned int ... Degrees1 , unsigned int ... Degrees2 >
static void InteriorOverlappedSpan( UIntPack< Degrees1 ... > , UIntPack< Degrees2 ... > , int depth , int begin[] , int end[] )
{
static_assert( sizeof ... ( Degrees1 ) == sizeof ... ( Degrees2 ) , "[ERROR] Dimensions don't match" );
_InteriorOverlappedSpan( UIntPack< Degrees1 ... >() , UIntPack< Degrees2 ... >() , depth , begin , end );
}
template< unsigned int ... Degrees1 , unsigned int ... Degrees2 >
static bool IsInteriorlyOverlapped( UIntPack< Degrees1 ... > , UIntPack< Degrees2 ... > , int depth , const int offset[] )
{
static_assert( sizeof ... ( Degrees1 ) == sizeof ... ( Degrees2 ) , "[ERROR] Dimensions don't match" );
return depth>=0 && _IsInteriorlyOverlapped( UIntPack< Degrees1 ... >() , UIntPack< Degrees2 ... >() , depth , offset );
}
template< unsigned int ... Degrees1 , unsigned int ... Degrees2 >
static void ParentOverlapBounds( UIntPack< Degrees1 ... > , UIntPack< Degrees2 ... > , int depth , const int offset[] , int start[] , int end[] )
{
static_assert( sizeof ... ( Degrees1 ) == sizeof ... ( Degrees2 ) , "[ERROR] Dimensions don't match" );
if( depth>0 ) _ParentOverlapBounds( UIntPack< Degrees1 ... >() , UIntPack< Degrees2 ... >() , depth , offset , start , end );
}
template< unsigned int ... Degrees1 , unsigned int ... Degrees2 >
static void ParentOverlapBounds( UIntPack< Degrees1 ... > , UIntPack< Degrees2 ... > , int corner , int start[] , int end[] )
{
static_assert( sizeof ... ( Degrees1 ) == sizeof ... ( Degrees2 ) , "[ERROR] Dimensions don't match" );
_ParentOverlapBounds( UIntPack< Degrees1 ... >() , UIntPack< Degrees2 ... >() , corner , start , end );
}
template< unsigned int Dim >
struct PointEvaluatorState
{
virtual double value( const int offset[] , const unsigned int d[] ) const = 0;
virtual double subValue( const int offset[] , const unsigned int d[] ) const = 0;
template< class Real , typename DerivativeType >
Point< Real , DerivativeType::Size > dValues( const int offset[] ) const
{
Point< Real , DerivativeType::Size > v;
unsigned int _d[Dim];
for( int d=0 ; d<DerivativeType::Size ; d++ )
{
DerivativeType::Factor( d , _d );
v[d] = (Real)value( offset , _d );
}
return v;
}
template< class Real , typename DerivativeType >
Point< Real , DerivativeType::LastDerivative+1 > partialDotDValues( Point< Real , DerivativeType::Size > v , const int offset[] ) const
{
Point< Real , DerivativeType::LastDerivative+1 > dot;
unsigned int _d[Dim];
for( int d=0 ; d<DerivativeType::Size ; d++ )
{
DerivativeType::Factor( d , _d );
dot[ _d[Dim-1] ] += (Real)( subValue( offset , _d ) * v[d] );
}
return dot;
}
};
template< unsigned int ... TDegrees >
struct PointEvaluator< UIntPack< TDegrees ... > >
{
static const unsigned int Dim = sizeof ... ( TDegrees );
};
template< unsigned int ... TDegrees >
struct RestrictionProlongation< UIntPack< TDegrees ... > >
{
virtual void init( void ){ }
virtual double upSampleCoefficient( const int pOff[] , const int cOff[] ) const = 0;
typedef DynamicWindow< double , UIntPack< ( - BSplineSupportSizes< TDegrees >::DownSample0Start + BSplineSupportSizes< TDegrees >::DownSample1End + 1 ) ... > > DownSampleStencil;
struct UpSampleStencil : public DynamicWindow< double , UIntPack< BSplineSupportSizes< TDegrees >::UpSampleSize ... > > { };
struct DownSampleStencils : public DynamicWindow< DownSampleStencil , IsotropicUIntPack< sizeof ... ( TDegrees ) , 2 > > { };
void init( int highDepth ){ _highDepth = highDepth ; init(); }
void setStencil ( UpSampleStencil & stencil ) const;
void setStencils( DownSampleStencils& stencils ) const;
int highDepth( void ) const { return _highDepth; }
protected:
int _highDepth;
};
template< unsigned int ... TDegrees >
struct System< UIntPack< TDegrees ... > >
{
virtual void init( void ){ }
virtual double ccIntegrate( const int off1[] , const int off2[] ) const = 0;
virtual double pcIntegrate( const int off1[] , const int off2[] ) const = 0;
virtual bool vanishesOnConstants( void ) const { return false; }
virtual RestrictionProlongation< UIntPack< TDegrees ... > >& restrictionProlongation( void ) = 0;
struct CCStencil : public DynamicWindow< double , UIntPack< BSplineOverlapSizes< TDegrees , TDegrees >::OverlapSize ... > >{ };
#ifdef SHOW_WARNINGS
#pragma message ( "[WARNING] Why are the parent/child stencils so big?" )
#endif // SHOW_WARNINGS
struct PCStencils : public DynamicWindow< CCStencil , IsotropicUIntPack< sizeof ... ( TDegrees ) , 2 > >{ };
void init( int highDepth ){ _highDepth = highDepth ; init(); }
template< bool IterateFirst > void setStencil ( CCStencil & stencil ) const;
template< bool IterateFirst > void setStencils( PCStencils& stencils ) const;
int highDepth( void ) const { return _highDepth; }
protected:
int _highDepth;
};
template< unsigned int ... TDegrees , unsigned int ... CDegrees , unsigned int CDim >
struct Constraint< UIntPack< TDegrees ... > , UIntPack< CDegrees ... > , CDim >
{
static_assert( sizeof...(TDegrees)==sizeof...(CDegrees) , "[ERROR] BaseFEMIntegrator::Constraint: Test and constraint dimensions don't match" );
virtual void init( void ){ ; }
virtual Point< double , CDim > ccIntegrate( const int off1[] , const int off2[] ) const = 0;
virtual Point< double , CDim > pcIntegrate( const int off1[] , const int off2[] ) const = 0;
virtual Point< double , CDim > cpIntegrate( const int off1[] , const int off2[] ) const = 0;
virtual RestrictionProlongation< UIntPack< TDegrees ... > >& tRestrictionProlongation( void ) = 0;
virtual RestrictionProlongation< UIntPack< CDegrees ... > >& cRestrictionProlongation( void ) = 0;
struct CCStencil : public DynamicWindow< Point< double , CDim > , UIntPack< BSplineOverlapSizes< TDegrees , CDegrees >::OverlapSize ... > >{ };
#ifdef SHOW_WARNINGS
#pragma message ( "[WARNING] Why are the parent/child stencils so big?" )
#endif // SHOW_WARNINGS
struct PCStencils : public DynamicWindow< CCStencil , IsotropicUIntPack< sizeof ... ( TDegrees ) , 2 > >{ };
struct CPStencils : public DynamicWindow< CCStencil , IsotropicUIntPack< sizeof ... ( TDegrees ) , 2 > >{ };
void init( int highDepth ){ _highDepth = highDepth ; init(); }
template< bool IterateFirst > void setStencil ( CCStencil & stencil ) const;
template< bool IterateFirst > void setStencils( PCStencils& stencils ) const;
template< bool IterateFirst > void setStencils( CPStencils& stencils ) const;
int highDepth( void ) const { return _highDepth; }
protected:
int _highDepth;
};
template< unsigned int ... TDegrees >
struct SystemConstraint< UIntPack< TDegrees ... > > : public Constraint< UIntPack< TDegrees ... > , UIntPack< TDegrees ... > , 1 >
{
typedef Constraint< UIntPack< TDegrees ... > , UIntPack< TDegrees ... > , 1 > Base;
SystemConstraint( System< UIntPack< TDegrees ... > >& sys ) : _sys( sys ){;}
void init( void ){ _sys.init( Base::highDepth() ) ; _sys.init(); }
Point< double , 1 > ccIntegrate( const int off1[] , const int off2[] ) const{ return Point< double , 1 >( _sys.ccIntegrate( off1 , off2 ) ); }
Point< double , 1 > pcIntegrate( const int off1[] , const int off2[] ) const{ return Point< double , 1 >( _sys.pcIntegrate( off1 , off2 ) ); }
Point< double , 1 > cpIntegrate( const int off1[] , const int off2[] ) const{ return Point< double , 1 >( _sys.pcIntegrate( off2 , off1 ) ); }
RestrictionProlongation< UIntPack< TDegrees ... > >& tRestrictionProlongation( void ){ return _sys.restrictionProlongation(); }
RestrictionProlongation< UIntPack< TDegrees ... > >& cRestrictionProlongation( void ){ return _sys.restrictionProlongation(); }
protected:
System< UIntPack< TDegrees ... > >& _sys;
};
};
/////////////////////////////////////////////////
// An implementation of the virtual integrator //
/////////////////////////////////////////////////
struct FEMIntegrator
{
protected:
template< unsigned int FEMSig , unsigned int ... FEMSigs >
static typename std::enable_if< sizeof ... ( FEMSigs )==0 , bool >::type _IsValidFEMNode( UIntPack< FEMSig , FEMSigs ... > , unsigned int depth , const int offset[] )
{
return !BSplineEvaluationData< FEMSig >::OutOfBounds( depth , offset[0] );
}
template< unsigned int FEMSig , unsigned int ... FEMSigs >
static typename std::enable_if< sizeof ... ( FEMSigs )!=0 , bool >::type _IsValidFEMNode( UIntPack< FEMSig , FEMSigs ... > , unsigned int depth , const int offset[] )
{
return !BSplineEvaluationData< FEMSig >::OutOfBounds( depth , offset[0] ) && _IsValidFEMNode( UIntPack< FEMSigs ... >() , depth , offset+1 );
}
template< unsigned int FEMSig , unsigned ... FEMSigs >
static typename std::enable_if< sizeof ... ( FEMSigs )==0 , bool >::type _IsOutOfBounds( UIntPack< FEMSig , FEMSigs ... > , unsigned int depth , const int offset[] )
{
return BSplineEvaluationData< FEMSig >::OutOfBounds( depth , offset[0] );
}
template< unsigned int FEMSig , unsigned ... FEMSigs >
static typename std::enable_if< sizeof ... ( FEMSigs )!=0 , bool >::type _IsOutOfBounds( UIntPack< FEMSig , FEMSigs ... > , unsigned int depth , const int offset[] )
{
return BSplineEvaluationData< FEMSig >::OutOfBounds( depth , offset[0] ) || _IsOutOfBounds( UIntPack< FEMSigs ... >() , depth , offset+1 );
}
template< unsigned int FEMSig , unsigned int ... FEMSigs >
static typename std::enable_if< sizeof ... ( FEMSigs )==0 >::type _BSplineBegin( UIntPack< FEMSig , FEMSigs ... > , unsigned int depth , int begin[] )
{
begin[0] = BSplineEvaluationData< FEMSig >::Begin( depth );
}
template< unsigned int FEMSig , unsigned int ... FEMSigs >
static typename std::enable_if< sizeof ... ( FEMSigs )!=0 >::type _BSplineBegin( UIntPack< FEMSig , FEMSigs ... > , unsigned int depth , int begin[] )
{
begin[0] = BSplineEvaluationData< FEMSig >::Begin( depth ) ; _BSplineBegin( UIntPack< FEMSigs ... >() , depth , begin+1 );
}
template< unsigned int FEMSig , unsigned int ... FEMSigs >
static typename std::enable_if< sizeof ... ( FEMSigs )==0 >::type _BSplineEnd( UIntPack< FEMSig , FEMSigs ... > , unsigned int depth , int end[] )
{
end[0] = BSplineEvaluationData< FEMSig >::End( depth );
}
template< unsigned int FEMSig , unsigned int ... FEMSigs >
static typename std::enable_if< sizeof ... ( FEMSigs )!=0 >::type _BSplineEnd( UIntPack< FEMSig , FEMSigs ... > , unsigned int depth , int end[] )
{
end[0] = BSplineEvaluationData< FEMSig >::End( depth ) ; _BSplineEnd( UIntPack< FEMSigs ... >() , depth , end+1 );
}
template< unsigned int FEMSig , unsigned int ... FEMSigs >
static typename std::enable_if< sizeof ... ( FEMSigs )==0 , double >::type _Integral( UIntPack< FEMSig , FEMSigs ... > , unsigned int depth , const int offset[] , const double begin[] , const double end[] )
{
return BSplineEvaluationData< FEMSig >::Integral( depth , offset[0] , begin[0] , end[0] , 0 );
}
template< unsigned int FEMSig , unsigned int ... FEMSigs >
static typename std::enable_if< sizeof ... ( FEMSigs )!=0 , double >::type _Integral( UIntPack< FEMSig , FEMSigs ... > , unsigned int depth , const int offset[] , const double begin[] , const double end[] )
{
return BSplineEvaluationData< FEMSig >::Integral( depth , offset[0] , begin[0] , end[0] , 0 ) * _Integral( UIntPack< FEMSigs ... >() , depth , offset+1 , begin+1 , end+1 );
}
public:
template< unsigned int ... FEMSigs >
static double Integral( UIntPack< FEMSigs ... > , int depth , const int offset[] , const double begin[] , const double end[] )
{
if( depth<0 ) return 0;
else return _Integral( UIntPack< FEMSigs ... >() , depth , offset , begin , end );
}
template< unsigned int ... FEMSigs > static bool IsValidFEMNode( UIntPack< FEMSigs ... > , int depth , const int offset[] ){ return _IsValidFEMNode( UIntPack< FEMSigs ... >() , depth , offset ); }
template< unsigned int ... FEMSigs > static bool IsOutOfBounds( UIntPack< FEMSigs ... > , int depth , const int offset[] ){ return depth<0 || _IsOutOfBounds( UIntPack< FEMSigs ... >() , depth , offset ); }
template< unsigned int ... FEMSigs > static void BSplineBegin( UIntPack< FEMSigs ... > , int depth , int begin[] ){ if( depth>=0 ) _BSplineBegin( UIntPack< FEMSigs ... >() , depth , begin ); }
template< unsigned int ... FEMSigs > static void BSplineEnd ( UIntPack< FEMSigs ... > , int depth , int end [] ){ if( depth>=0 ) _BSplineEnd ( UIntPack< FEMSigs ... >() , depth , end ); }
template< typename TSignatures , typename TDerivatives > struct System{};
template< typename TSignatures , typename TDerivatives , typename CSignatures , typename CDerivatives , unsigned int CDim > struct Constraint{};
template< typename TSignatures , typename TDerivatives , typename CSignatures , typename CDerivatives > struct ScalarConstraint{};
template< typename TSignatures > struct RestrictionProlongation{};
template< typename TSignatures , typename TDerivatives > struct PointEvaluator{};
template< typename TSignatures , typename TDerivatives > struct PointEvaluatorState{};
template< unsigned int ... TSignatures , unsigned int ... TDs >
struct PointEvaluatorState< UIntPack< TSignatures ... > , UIntPack< TDs ... > > : public BaseFEMIntegrator::template PointEvaluatorState< sizeof ... ( TSignatures ) >
{
static_assert( sizeof...(TSignatures)==sizeof...(TDs) , "[ERROR] Degree and derivative dimensions don't match" );
static_assert( UIntPack< FEMSignature< TSignatures >::Degree ... >::template Compare< UIntPack< TDs ... > >::GreaterThanOrEqual , "[ERROR] PointEvaluatorState: More derivatives than degrees" );
static const unsigned int Dim = sizeof...(TSignatures);
double value ( const int offset[] , const unsigned int derivatives[] ) const { return _value< Dim >( offset , derivatives ); }
double subValue( const int offset[] , const unsigned int derivatives[] ) const { return _value< Dim-1 >( offset , derivatives ); }
// Bypassing the "auto" keyword
template< unsigned int _Dim >
const double (*(values)( void ) const )[ UIntPack< TDs ... >::template Get< _Dim >()+1 ] { return std::template get< _Dim >( _oneDValues ).values; }
protected:
int _pointOffset[Dim];
template< unsigned int Degree , unsigned int D > struct _OneDValues
{
double values[ BSplineSupportSizes< Degree >::SupportSize ][ D+1 ];
double value( int dOff , unsigned int d ) const
{
if( dOff>=-BSplineSupportSizes< Degree >::SupportEnd && dOff<=-BSplineSupportSizes< Degree >::SupportStart && d<=D ) return values[ dOff+BSplineSupportSizes< Degree >::SupportEnd][d];
else return 0;
}
};
std::tuple< _OneDValues< FEMSignature< TSignatures >::Degree , TDs > ... > _oneDValues;
template< unsigned int MaxDim=Dim , unsigned int I=0 > typename std::enable_if< I==MaxDim , double >::type _value( const int off[] , const unsigned int d[] ) const { return 1.; }
template< unsigned int MaxDim=Dim , unsigned int I=0 > typename std::enable_if< I!=MaxDim , double >::type _value( const int off[] , const unsigned int d[] ) const { return std::get< I >( _oneDValues ).value( off[I]-_pointOffset[I] , d[I] ) * _value< MaxDim , I+1 >( off , d ); }
template< typename T1 , typename T2 > friend struct PointEvaluator;
};
template< unsigned int ... TSignatures , unsigned int ... TDs >
struct PointEvaluator< UIntPack< TSignatures ... > , UIntPack< TDs ... > > : public BaseFEMIntegrator::template PointEvaluator< UIntPack< FEMSignature< TSignatures >::Degree ... > >
{
static_assert( sizeof...(TSignatures)==sizeof...(TDs) , "[ERROR] PointEvaluator: Degree and derivative dimensions don't match" );
static_assert( UIntPack< FEMSignature< TSignatures >::Degree ... >::template Compare< UIntPack< TDs ... > >::GreaterThanOrEqual , "[ERROR] PointEvaluator: More derivatives than degrees" );
static const unsigned int Dim = sizeof ... ( TSignatures );
typedef typename BaseFEMIntegrator::template PointEvaluator< UIntPack< FEMSignature< TSignatures >::Degree ... > > Base;
PointEvaluator( unsigned int maxDepth ) : _maxDepth( maxDepth ) { _init(); }
template< unsigned int ... EDs >
void initEvaluationState( Point< double , Dim > p , unsigned int depth , PointEvaluatorState< UIntPack< TSignatures ... > , UIntPack< EDs ... > >& state ) const
{
unsigned int res = 1<<depth;
for( int d=0 ; d<Dim ; d++ ) state._pointOffset[d] = (int)( p[d] * res );
initEvaluationState( p , depth , state._pointOffset , state );
}
template< unsigned int ... EDs >
void initEvaluationState( Point< double , Dim > p , unsigned int depth , const int* offset , PointEvaluatorState< UIntPack< TSignatures ... > , UIntPack< EDs ... > >& state ) const
{
static_assert( UIntPack< TDs ... >::template Compare< UIntPack< EDs ... > >::GreaterThanOrEqual , "[ERROR] PointEvaluator::init: More evaluation derivatives than stored derivatives" );
for( int d=0 ; d<Dim ; d++ ) state._pointOffset[d] = (int)offset[d];
_initEvaluationState( UIntPack< TSignatures ... >() , UIntPack< EDs ... >() , &p[0] , depth , state );
}
protected:
unsigned int _maxDepth;
std::tuple< BSplineData< TSignatures , TDs > ... > _bSplineData;
template< unsigned int I=0 > typename std::enable_if< I==Dim >::type _init( void ){}
template< unsigned int I=0 > typename std::enable_if< I< Dim >::type _init( void ){ std::get< I >( _bSplineData ).reset( _maxDepth ) ; _init< I+1 >( ); }
template< unsigned int I , unsigned int TSig , unsigned int D , typename State >
void _setEvaluationState( const double* p , unsigned int depth , State& state ) const
{
static const int LeftSupportRadius = -BSplineSupportSizes< FEMSignature< TSig >::Degree >::SupportStart;
static const int LeftPointSupportRadius = BSplineSupportSizes< FEMSignature< TSig >::Degree >::SupportEnd ;
static const int RightSupportRadius = BSplineSupportSizes< FEMSignature< TSig >::Degree >::SupportEnd ;
static const int RightPointSupportRadius = -BSplineSupportSizes< FEMSignature< TSig >::Degree >::SupportStart;
for( int s=-LeftPointSupportRadius ; s<=RightPointSupportRadius ; s++ )
{
int pIdx = state._pointOffset[I];
int fIdx = state._pointOffset[I]+s;
double _p = p[I];
const Polynomial< FEMSignature< TSig >::Degree >* components = std::get< I >( _bSplineData )[depth].polynomialsAndOffset( _p , pIdx , fIdx );
for( int d=0 ; d<=D ; d++ ) std::get< I >( state._oneDValues ).values[ s+LeftPointSupportRadius ][d] = components[d]( _p );
}
}
template< typename State , unsigned int TSig , unsigned int ... TSigs , unsigned int D , unsigned int ... Ds >
typename std::enable_if< sizeof...(TSigs)==0 >::type _initEvaluationState( UIntPack< TSig , TSigs ... > , UIntPack< D , Ds ... > , const double* p , unsigned int depth , State& state ) const
{
_setEvaluationState< Dim-1 , TSig , D >( p , depth , state );
}
template< typename State , unsigned int TSig , unsigned int ... TSigs , unsigned int D , unsigned int ... Ds >
typename std::enable_if< sizeof...(TSigs)!=0 >::type _initEvaluationState( UIntPack< TSig , TSigs ... > , UIntPack< D , Ds ... > , const double* p , unsigned int depth , State& state ) const
{
_setEvaluationState< Dim-1-sizeof...(TSigs) , TSig , D >( p , depth , state );
_initEvaluationState( UIntPack< TSigs ... >() , UIntPack< Ds ... >() , p , depth , state );
}
};
template< unsigned int ... TSignatures >
struct RestrictionProlongation< UIntPack< TSignatures ... > > : public BaseFEMIntegrator::template RestrictionProlongation< UIntPack< FEMSignature< TSignatures >::Degree ... > >
{
static const unsigned int Dim = sizeof ... ( TSignatures );
typedef typename BaseFEMIntegrator::template RestrictionProlongation< UIntPack< FEMSignature< TSignatures >::Degree ... > > Base;
double upSampleCoefficient( const int pOff[] , const int cOff[] ) const { return _coefficient( pOff , cOff ); }
void init( unsigned int depth ){ Base::init( depth ); }
void init( void ){ _init( Base::highDepth() ); }
protected:
std::tuple< typename BSplineEvaluationData< TSignatures >::UpSampleEvaluator ... > _upSamplers;
template< unsigned int D=0 > typename std::enable_if< D==Dim >::type _init( int highDepth ){ }
template< unsigned int D=0 > typename std::enable_if< D< Dim >::type _init( int highDepth ){ std::get< D >( _upSamplers ).set( highDepth-1 ) ; _init< D+1 >( highDepth ); }
template< unsigned int D=0 > typename std::enable_if< D==Dim , double >::type _coefficient( const int pOff[] , const int cOff[] ) const { return 1.; }
template< unsigned int D=0 > typename std::enable_if< D< Dim , double >::type _coefficient( const int pOff[] , const int cOff[] ) const { return _coefficient< D+1 >( pOff , cOff ) * std::get< D >( _upSamplers ).value( pOff[D] , cOff[D] ); }
};
template< unsigned int ... TSignatures , unsigned int ... TDerivatives , unsigned int ... CSignatures , unsigned int ... CDerivatives , unsigned int CDim >
struct Constraint< UIntPack< TSignatures ... > , UIntPack< TDerivatives ... > , UIntPack< CSignatures ... > , UIntPack< CDerivatives ... > , CDim > : public BaseFEMIntegrator::template Constraint< UIntPack< FEMSignature< TSignatures >::Degree ... > , UIntPack< FEMSignature< CSignatures >::Degree ... > , CDim >
{
static_assert( sizeof ... ( TSignatures ) == sizeof ... ( CSignatures ) , "[ERROR] Test signatures and contraint signatures must have the same dimension" );
static_assert( sizeof ... ( TSignatures ) == sizeof ... ( TDerivatives ) , "[ERROR] Test signatures and derivatives must have the same dimension" );
static_assert( sizeof ... ( CSignatures ) == sizeof ... ( CDerivatives ) , "[ERROR] Constraint signatures and derivatives must have the same dimension" );
static_assert( UIntPack< FEMSignature< TSignatures >::Degree ... >::template Compare< UIntPack< TDerivatives ... > >::GreaterThanOrEqual , "[ERROR] Test functions cannot have more derivatives than the degree" );
static_assert( UIntPack< FEMSignature< CSignatures >::Degree ... >::template Compare< UIntPack< CDerivatives ... > >::GreaterThanOrEqual , "[ERROR] Test functions cannot have more derivatives than the degree" );
static const unsigned int Dim = sizeof ... ( TSignatures );
typedef typename BaseFEMIntegrator::template Constraint< UIntPack< FEMSignature< TSignatures >::Degree ... > , UIntPack< FEMSignature< CSignatures >::Degree ... > , CDim > Base;
static const unsigned int TDerivativeSize = TensorDerivatives< UIntPack< TDerivatives ... > >::Size;
static const unsigned int CDerivativeSize = TensorDerivatives< UIntPack< CDerivatives ... > >::Size;
static inline void TFactorDerivatives( unsigned int idx , unsigned int d[ Dim ] ){ TensorDerivatives< UIntPack< TDerivatives ... > >::Factor( idx , d ); }
static inline void CFactorDerivatives( unsigned int idx , unsigned int d[ Dim ] ){ TensorDerivatives< UIntPack< CDerivatives ... > >::Factor( idx , d ); }
static inline unsigned int TDerivativeIndex( const unsigned int d[ Dim ] ){ return TensorDerivatives< UIntPack< TDerivatives ... > >::Index( d ); }
static inline unsigned int CDerivativeIndex( const unsigned int d[ Dim ] ){ return TensorDerivatives< UIntPack< CDerivatives ... > >::Index( d ); }
Matrix< double , TDerivativeSize , CDerivativeSize > weights[CDim];
Point< double , CDim > ccIntegrate( const int off1[] , const int off2[] ) const { return _integrate( INTEGRATE_CHILD_CHILD , off1 , off2 ); }
Point< double , CDim > pcIntegrate( const int off1[] , const int off2[] ) const { return _integrate( INTEGRATE_PARENT_CHILD , off1 , off2 ); }
Point< double , CDim > cpIntegrate( const int off1[] , const int off2[] ) const { return _integrate( INTEGRATE_CHILD_PARENT , off1 , off2 ); }
void init( unsigned int depth ){ Base::init( depth ); }
void init( void )
{
_init( Base::highDepth() );
_weightedIndices.resize(0);
for( unsigned int d1=0 ; d1<TDerivativeSize ; d1++ ) for( unsigned int d2=0 ; d2<CDerivativeSize ; d2++ )
{
_WeightedIndices w(d1,d2);
for( unsigned int c=0 ; c<CDim ; c++ ) if( weights[c](d1,d2)>0 ) w.indices.push_back( std::pair< unsigned int , double >( c , weights[c](d1,d2) ) );
if( w.indices.size() ) _weightedIndices.push_back(w);
}
}
typename BaseFEMIntegrator::template RestrictionProlongation< UIntPack< FEMSignature< TSignatures >::Degree ... > >& tRestrictionProlongation( void ){ return _tRestrictionProlongation; }
typename BaseFEMIntegrator::template RestrictionProlongation< UIntPack< FEMSignature< CSignatures >::Degree ... > >& cRestrictionProlongation( void ){ return _cRestrictionProlongation; }
protected:
RestrictionProlongation< UIntPack< TSignatures ... > > _tRestrictionProlongation;
RestrictionProlongation< UIntPack< CSignatures ... > > _cRestrictionProlongation;
struct _WeightedIndices
{
_WeightedIndices( unsigned int _d1=0 , unsigned int _d2=0 ) : d1(_d1) , d2(_d2) { ; }
unsigned int d1 , d2;
std::vector< std::pair< unsigned int , double > > indices;
};
std::vector< _WeightedIndices > _weightedIndices;
enum IntegrationType
{
INTEGRATE_CHILD_CHILD ,
INTEGRATE_PARENT_CHILD ,
INTEGRATE_CHILD_PARENT
};
template< unsigned int _TSig , unsigned int _TDerivatives , unsigned int _CSig , unsigned int _CDerivatives >
struct _Integrators
{
typename BSplineIntegrationData< _TSig , _CSig >::FunctionIntegrator::template Integrator< _TDerivatives , _CDerivatives > ccIntegrator;
typename BSplineIntegrationData< _TSig , _CSig >::FunctionIntegrator::template ChildIntegrator< _TDerivatives , _CDerivatives > pcIntegrator;
typename BSplineIntegrationData< _CSig , _TSig >::FunctionIntegrator::template ChildIntegrator< _CDerivatives , _TDerivatives > cpIntegrator;
};
std::tuple< _Integrators< TSignatures , TDerivatives , CSignatures , CDerivatives > ... > _integrators;
template< unsigned int D=0 >
typename std::enable_if< D==Dim >::type _init( int depth ){ ; }
template< unsigned int D=0 >
typename std::enable_if< D< Dim >::type _init( int depth )
{
std::get< D >( _integrators ).ccIntegrator.set( depth );
if( depth ) std::get< D >( _integrators ).pcIntegrator.set( depth-1 ) , std::get< D >( _integrators ).cpIntegrator.set( depth-1 );
_init< D+1 >( depth );
}
template< unsigned int D=0 >
typename std::enable_if< D==Dim , double >::type _integral( IntegrationType iType , const int off1[] , const int off2[] , const unsigned int d1[] , const unsigned int d2[] ) const { return 1.; }
template< unsigned int D=0 >
typename std::enable_if< D< Dim , double >::type _integral( IntegrationType iType , const int off1[] , const int off2[] , const unsigned int d1[] , const unsigned int d2[] ) const
{
double remainingIntegral = _integral< D+1 >( iType , off1 , off2 , d1 , d2 );
switch( iType )
{
case INTEGRATE_CHILD_CHILD: return std::get< D >( _integrators ).ccIntegrator.dot( off1[D] , off2[D] , d1[D] , d2[D] ) * remainingIntegral;
case INTEGRATE_PARENT_CHILD: return std::get< D >( _integrators ).pcIntegrator.dot( off1[D] , off2[D] , d1[D] , d2[D] ) * remainingIntegral;
case INTEGRATE_CHILD_PARENT: return std::get< D >( _integrators ).cpIntegrator.dot( off2[D] , off1[D] , d2[D] , d1[D] ) * remainingIntegral;
default: fprintf( stderr , "[ERORR] FEMIntegrator::Test::Constraint::_integral: Undefined integration type\n" ) , exit( 0 );
}
}
Point< double , CDim > _integrate( IntegrationType iType , const int off1[] , const int off[] ) const;
};
template< unsigned int ... TSignatures , unsigned int ... TDerivatives , unsigned int ... CSignatures , unsigned int ... CDerivatives >
struct ScalarConstraint< UIntPack< TSignatures ... > , UIntPack< TDerivatives ... > , UIntPack< CSignatures ... > , UIntPack< CDerivatives ... > > : public Constraint< UIntPack< TSignatures ... > , UIntPack< TDerivatives ... > , UIntPack< CSignatures ... > , UIntPack< CDerivatives ... > , 1 >
{
static const unsigned int Dim = sizeof ... ( TSignatures );
typedef typename BaseFEMIntegrator::template Constraint< UIntPack< FEMSignature< TSignatures >::Degree ... > , UIntPack< FEMSignature< CSignatures >::Degree ... > , 1 > Base;
typedef Constraint< UIntPack< TSignatures ... > , UIntPack< TDerivatives ... > , UIntPack< CSignatures ... > , UIntPack< CDerivatives ... > , 1 > FullConstraint;
using FullConstraint::weights;
// [NOTE] We define the constructor using a recursive function call to take into account multiplicity (e.g. so that d^2/dxdy and d^2/dydx each contribute)
ScalarConstraint( const std::initializer_list< double >& w )
{
std::function< void ( unsigned int[] , const double[] , unsigned int ) > SetDerivativeWeights = [&]( unsigned int derivatives[Dim] , const double w[] , unsigned int d )
{
unsigned int idx1 = FullConstraint::TDerivativeIndex( derivatives ) , idx2 = FullConstraint::CDerivativeIndex( derivatives );
weights[0][idx1][idx2] += w[0];
if( d>0 ) for( int dd=0 ; dd<Dim ; dd++ ){ derivatives[dd]++ ; SetDerivativeWeights( derivatives , w+1 , d-1 ) ; derivatives[dd]--; }
};
static const unsigned int DMax = std::min< unsigned int >( UIntPack< TDerivatives ... >::Min() , UIntPack< CDerivatives ... >::Min() );
unsigned int derivatives[Dim];
double _w[DMax+1];
memset( _w , 0 , sizeof(_w) );
{
unsigned int dd=0;
for( typename std::initializer_list< double >::const_iterator iter=w.begin() ; iter!=w.end() && dd<=DMax ; dd++ , iter++ ) _w[dd] = *iter;
}
for( int d=0 ; d<Dim ; d++ ) derivatives[d] = 0;
if( w.size() ) SetDerivativeWeights( derivatives , _w , std::min< unsigned int >( DMax+1 , (unsigned int)w.size() )-1 );
}
};
template< unsigned int ... TSignatures , unsigned int ... TDerivatives >
struct System< UIntPack< TSignatures ... > , UIntPack< TDerivatives ... > > : public BaseFEMIntegrator::template System< UIntPack< FEMSignature< TSignatures >::Degree... > >
{
static_assert( sizeof ... ( TSignatures ) == sizeof ... ( TDerivatives ) , "[ERROR] Test signatures and derivatives must have the same dimension" );
static const unsigned int Dim = sizeof ... ( TSignatures );
typedef typename BaseFEMIntegrator::template System< UIntPack< FEMSignature< TSignatures >::Degree... > > Base;
System( const std::initializer_list< double >& w ) : _sc( w ){ ; }
void init( unsigned int depth ){ Base::init( depth ); }
void init( void ){ ( (BaseFEMIntegrator::template Constraint< UIntPack< FEMSignature< TSignatures >::Degree ... > , UIntPack< FEMSignature< TSignatures >::Degree ... > , 1 >&)_sc ).init( BaseFEMIntegrator::template System< UIntPack< FEMSignature< TSignatures >::Degree... > >::_highDepth ); }
double ccIntegrate( const int off1[] , const int off2[] ) const { return _sc.ccIntegrate( off1 , off2 )[0]; }
double pcIntegrate( const int off1[] , const int off2[] ) const { return _sc.pcIntegrate( off1 , off2 )[0]; }
bool vanishesOnConstants( void ) const { return _sc.weights[0][0][0]==0; }
typename BaseFEMIntegrator::template RestrictionProlongation< UIntPack< FEMSignature< TSignatures >::Degree ... > >& restrictionProlongation( void ){ return _sc.tRestrictionProlongation(); }
protected:
ScalarConstraint< UIntPack< TSignatures ... > , UIntPack< TDerivatives ... > , UIntPack< TSignatures ... > , UIntPack< TDerivatives ... > > _sc;
};
};
//////////////////////////////////////////
template< unsigned int Dim > inline void SetGhostFlag( RegularTreeNode< Dim , FEMTreeNodeData >* node , bool flag ){ if( node && node->parent ) node->parent->nodeData.setGhostFlag( flag ); }
template< unsigned int Dim > inline bool GetGhostFlag( const RegularTreeNode< Dim , FEMTreeNodeData >* node ){ return node==NULL || node->parent==NULL || node->parent->nodeData.getGhostFlag( ); }
template< unsigned int Dim > inline bool IsActiveNode( const RegularTreeNode< Dim , FEMTreeNodeData >* node ){ return !GetGhostFlag< Dim >( node ); }
template< unsigned int Dim , class Real , class Vertex > struct IsoSurfaceExtractor;
template< unsigned int Dim , class Data >
struct NodeSample
{
RegularTreeNode< Dim , FEMTreeNodeData >* node;
Data data;
};
template< unsigned int Dim , class Real >
struct NodeAndPointSample
{
RegularTreeNode< Dim , FEMTreeNodeData >* node;
ProjectiveData< Point< Real , Dim > , Real > sample;
};
template< unsigned int Dim , class Real > using NodeSimplices = NodeSample< Dim , std::vector< Simplex< Real , Dim , Dim-1 > > >;
template< typename T > struct WindowLoopData{ };
template< unsigned int ... Sizes >
struct WindowLoopData< UIntPack< Sizes ... > >
{
static const int Dim = sizeof ... ( Sizes );
unsigned int size[1<<Dim];
unsigned int indices[1<<Dim][ WindowSize< UIntPack< Sizes ... > >::Size ];
WindowLoopData( std::function< void ( int c , int* , int* ) > boundsFunction )
{
int start[Dim] , end[Dim];
for( int c=0 ; c<(1<<Dim) ; c++ )
{
size[c] = 0;
boundsFunction( c , start , end );
unsigned int idx[Dim];
WindowLoop< Dim >::Run
(
start , end ,
[&]( int d , int i ){ idx[d] = i; } ,
[&]( void ){ indices[c][ size[c]++ ] = GetWindowIndex( UIntPack< Sizes ... >() , idx ); }
);
}
}
};
template< class Data >
void AddAtomic( Data& a , const Data& b )
{
#pragma omp critical
a += b;
}
template< class Real , unsigned int Dim >
void AddAtomic( Point< Real , Dim >& a , const Point< Real , Dim >& b )
{
for( int d=0 ; d<Dim ; d++ ) AddAtomic( a[d] , b[d] );
}
void AddAtomic( float& a , const float& b )
{
#pragma omp atomic
a += b;
}
void AddAtomic( double& a , const double& b )
{
#pragma omp atomic
a += b;
}
template< class Data >
bool IsZero( const Data& data ){ return false; }
template< class Real , unsigned int Dim >
bool IsZero( const Point< Real , Dim >& d )
{
bool zero = true;
for( int i=0 ; i<Dim ; i++ ) zero &= (d[i]==0);
return zero;
}
bool IsZero( const float& f ){ return f==0.f; }
bool IsZero( const double& f ){ return f==0.; }
template< unsigned int Dim , class Real >
class FEMTree
{
public:
typedef RegularTreeNode< Dim , FEMTreeNodeData > FEMTreeNode;
Allocator< FEMTreeNode >* nodeAllocator;
protected:
template< unsigned int _Dim , class _Real , class Vertex > friend struct IsoSurfaceExtractor;
std::atomic< int > _nodeCount;
void _nodeInitializer( FEMTreeNode& node ){ node.nodeData.nodeIndex = _nodeCount++; }
struct _NodeInitializer
{
FEMTree& femTree;
_NodeInitializer( FEMTree& f ) : femTree(f){;}
void operator() ( FEMTreeNode& node ){ femTree._nodeInitializer( node ); }
};
public:
typedef int LocalDepth;
typedef int LocalOffset[Dim];
int nodeCount( void ) const { return _nodeCount; }
typedef NodeAndPointSample< Dim , Real > PointSample;
typedef typename FEMTreeNode::template NeighborKey< IsotropicUIntPack< Dim , 1 > , IsotropicUIntPack< Dim , 1 > > OneRingNeighborKey;
typedef typename FEMTreeNode::template ConstNeighborKey< IsotropicUIntPack< Dim , 1 > , IsotropicUIntPack< Dim , 1 > > ConstOneRingNeighborKey;
typedef typename FEMTreeNode::template Neighbors< IsotropicUIntPack< Dim , 3 > > OneRingNeighbors;
typedef typename FEMTreeNode::template ConstNeighbors< IsotropicUIntPack< Dim , 3 > > ConstOneRingNeighbors;
template< typename FEMDegreePack > using BaseSystem = typename BaseFEMIntegrator::template System< FEMDegreePack >;
template< typename FEMSigPack , typename DerivativePack > using PointEvaluator = typename FEMIntegrator::template PointEvaluator< FEMSigPack , DerivativePack >;
template< typename FEMSigPack , typename DerivativePack > using PointEvaluatorState = typename FEMIntegrator::template PointEvaluatorState< FEMSigPack , DerivativePack >;
template< typename FEMDegreePack > using CCStencil = typename BaseSystem< FEMDegreePack >::CCStencil;
template< typename FEMDegreePack > using PCStencils = typename BaseSystem< FEMDegreePack >::PCStencils;
template< unsigned int ... FEMSigs > bool isValidFEMNode( UIntPack< FEMSigs ... > , const FEMTreeNode* node ) const;
bool isValidSpaceNode( const FEMTreeNode* node ) const;
const FEMTreeNode* leaf( Point< Real , Dim > p ) const;
FEMTreeNode* leaf( Point< Real , Dim > p , LocalDepth maxDepth=-1 );
// [NOTE] In the case that T != double, we require both operators() for computing the system dual
template< typename T , unsigned int PointD >
struct InterpolationInfo
{
virtual void range( const FEMTreeNode* node , size_t& begin , size_t& end ) const = 0;
virtual Point< T , CumulativeDerivatives< Dim , PointD >::Size > operator() ( size_t pointIdx ) const = 0;
virtual Point< T , CumulativeDerivatives< Dim , PointD >::Size > operator() ( size_t pointIdx , const Point< T , CumulativeDerivatives< Dim , PointD >::Size >& dValues ) const = 0;
virtual Point< double , CumulativeDerivatives< Dim , PointD >::Size > operator() ( size_t pointIdx , const Point< double , CumulativeDerivatives< Dim , PointD >::Size >& dValues ) const = 0;
virtual const DualPointInfo< Dim , Real , T , PointD >& operator[]( size_t pointIdx ) const = 0;
virtual bool constrainsDCTerm( void ) const = 0;
virtual ~InterpolationInfo( void ){}
DualPointInfo< Dim , Real , T , PointD >& operator[]( size_t pointIndex ){ return const_cast< DualPointInfo< Dim , Real , T , PointD >& >( ( ( const InterpolationInfo* )this )->operator[]( pointIndex ) ); }
};
template< unsigned int PointD >
struct InterpolationInfo< double , PointD >
{
virtual void range( const FEMTreeNode* node , size_t& begin , size_t& end ) const = 0;
virtual Point< double , CumulativeDerivatives< Dim , PointD >::Size > operator() ( size_t pointIdx ) const = 0;
virtual Point< double , CumulativeDerivatives< Dim , PointD >::Size > operator() ( size_t pointIdx , const Point< double , CumulativeDerivatives< Dim , PointD >::Size >& dValues ) const = 0;
virtual const DualPointInfo< Dim , Real , double , PointD >& operator[]( size_t pointIdx ) const = 0;
virtual bool constrainsDCTerm( void ) const = 0;
virtual ~InterpolationInfo( void ){}
DualPointInfo< Dim , Real , double , PointD >& operator[]( size_t pointIndex ){ return const_cast< DualPointInfo< Dim , Real , double , PointD >& >( ( ( const InterpolationInfo* )this )->operator[]( pointIndex ) ); }
};
template< typename T , unsigned int PointD , typename ConstraintDual , typename SystemDual >
struct ApproximatePointInterpolationInfo : public InterpolationInfo< T , PointD >
{
void range( const FEMTreeNode* node , size_t& begin , size_t& end ) const
{
int idx = _iData.index( node );
if( idx<0 ) begin = end = 0;
else begin = idx , end = idx+1;
}
bool constrainsDCTerm( void ) const { return _constrainsDCTerm; }
const DualPointInfo< Dim , Real , T , PointD >& operator[]( size_t pointIdx ) const { return _iData[ (int)pointIdx ]; }
Point< T , CumulativeDerivatives< Dim , PointD >::Size > operator() ( size_t pointIdx ) const { return _constraintDual( _iData[ (int)pointIdx ].position ); }
Point< T , CumulativeDerivatives< Dim , PointD >::Size > operator() ( size_t pointIdx , const Point< T , CumulativeDerivatives< Dim , PointD >::Size >& dValues ) const { return _systemDual( _iData[ (int)pointIdx ].position , dValues ); }
Point< double , CumulativeDerivatives< Dim , PointD >::Size > operator() ( size_t pointIdx , const Point< double , CumulativeDerivatives< Dim , PointD >::Size >& dValues ) const { return _systemDual( _iData[ (int)pointIdx ].position , dValues ); }
ApproximatePointInterpolationInfo( ConstraintDual constraintDual , SystemDual systemDual , bool constrainsDCTerm ) : _constraintDual( constraintDual ) , _systemDual( systemDual ) , _constrainsDCTerm( constrainsDCTerm ) { }
protected:
SparseNodeData< DualPointInfo< Dim , Real , T , PointD > , ZeroUIntPack< Dim > > _iData;
bool _constrainsDCTerm;
ConstraintDual _constraintDual;
SystemDual _systemDual;
friend class FEMTree< Dim , Real >;
};
template< unsigned int PointD , typename ConstraintDual , typename SystemDual >
struct ApproximatePointInterpolationInfo< double , PointD , ConstraintDual , SystemDual > : public InterpolationInfo< double , PointD >
{
typedef double T;
void range( const FEMTreeNode* node , size_t& begin , size_t& end ) const
{
int idx = _iData.index( node );
if( idx<0 ) begin = end = 0;
else begin = idx , end = idx+1;
}
bool constrainsDCTerm( void ) const { return _constrainsDCTerm; }
const DualPointInfo< Dim , Real , T , PointD >& operator[]( size_t pointIdx ) const { return _iData[ (int)pointIdx ]; }
Point< T , CumulativeDerivatives< Dim , PointD >::Size > operator() ( size_t pointIdx ) const { return _constraintDual( _iData[ (int)pointIdx ].position ); }
Point< T , CumulativeDerivatives< Dim , PointD >::Size > operator() ( size_t pointIdx , const Point< T , CumulativeDerivatives< Dim , PointD >::Size >& dValues ) const { return _systemDual( _iData[ (int)pointIdx ].position , dValues ); }
ApproximatePointInterpolationInfo( ConstraintDual constraintDual , SystemDual systemDual , bool constrainsDCTerm ) : _constraintDual( constraintDual ) , _systemDual( systemDual ) , _constrainsDCTerm( constrainsDCTerm ) { }
protected:
SparseNodeData< DualPointInfo< Dim , Real , T , PointD > , ZeroUIntPack< Dim > > _iData;
bool _constrainsDCTerm;
ConstraintDual _constraintDual;
SystemDual _systemDual;
friend class FEMTree< Dim , Real >;
};
template< typename T , typename Data , unsigned int PointD , typename ConstraintDual , typename SystemDual >
struct ApproximatePointAndDataInterpolationInfo : public InterpolationInfo< T , PointD >
{
void range( const FEMTreeNode* node , size_t& begin , size_t& end ) const
{
int idx = _iData.index( node );
if( idx<0 ) begin = end = 0;
else begin = idx , end = idx+1;
}
bool constrainsDCTerm( void ) const { return _constrainsDCTerm; }
const DualPointInfo< Dim , Real , T , PointD >& operator[]( size_t pointIdx ) const { return _iData[ (int)pointIdx ].pointInfo; }
Point< T , CumulativeDerivatives< Dim , PointD >::Size > operator() ( size_t pointIdx ) const { return _constraintDual( _iData[ (int)pointIdx ].pointInfo.position , _iData[ (int)pointIdx ].data ); }
Point< T , CumulativeDerivatives< Dim , PointD >::Size > operator() ( size_t pointIdx , const Point< T , CumulativeDerivatives< Dim , PointD >::Size >& dValues ) const { return _systemDual( _iData[ (int)pointIdx ].pointInfo.position , _iData[ (int)pointIdx ].data , dValues ); }
Point< double , CumulativeDerivatives< Dim , PointD >::Size > operator() ( size_t pointIdx , const Point< double , CumulativeDerivatives< Dim , PointD >::Size >& dValues ) const { return _systemDual( _iData[ (int)pointIdx ].pointInfo.position , _iData[ (int)pointIdx ].data , dValues ); }
ApproximatePointAndDataInterpolationInfo( ConstraintDual constraintDual , SystemDual systemDual , bool constrainsDCTerm ) : _constraintDual( constraintDual ) , _systemDual( systemDual ) , _constrainsDCTerm( constrainsDCTerm ) { }
protected:
SparseNodeData< DualPointAndDataInfo< Dim , Real , Data , T , PointD > , ZeroUIntPack< Dim > > _iData;
bool _constrainsDCTerm;
ConstraintDual _constraintDual;
SystemDual _systemDual;
friend class FEMTree< Dim , Real >;
};
template< typename Data , unsigned int PointD , typename ConstraintDual , typename SystemDual >
struct ApproximatePointAndDataInterpolationInfo< double , Data , PointD , ConstraintDual , SystemDual > : public InterpolationInfo< double , PointD >
{
typedef double T;
void range( const FEMTreeNode* node , size_t& begin , size_t& end ) const
{
int idx = _iData.index( node );
if( idx<0 ) begin = end = 0;
else begin = idx , end = idx+1;
}
bool constrainsDCTerm( void ) const { return _constrainsDCTerm; }
const DualPointInfo< Dim , Real , T , PointD >& operator[]( size_t pointIdx ) const { return _iData[ (int)pointIdx ].pointInfo; }
Point< T , CumulativeDerivatives< Dim , PointD >::Size > operator() ( size_t pointIdx ) const { return _constraintDual( _iData[ (int)pointIdx ].pointInfo.position , _iData[ (int)pointIdx ].data ); }
Point< T , CumulativeDerivatives< Dim , PointD >::Size > operator() ( size_t pointIdx , const Point< T , CumulativeDerivatives< Dim , PointD >::Size >& dValues ) const { return _systemDual( _iData[ (int)pointIdx ].pointInfo.position , _iData[ (int)pointIdx ].data , dValues ); }
ApproximatePointAndDataInterpolationInfo( ConstraintDual constraintDual , SystemDual systemDual , bool constrainsDCTerm ) : _constraintDual( constraintDual ) , _systemDual( systemDual ) , _constrainsDCTerm( constrainsDCTerm ) { }
protected:
SparseNodeData< DualPointAndDataInfo< Dim , Real , Data , T , PointD > , ZeroUIntPack< Dim > > _iData;
bool _constrainsDCTerm;
ConstraintDual _constraintDual;
SystemDual _systemDual;
friend class FEMTree< Dim , Real >;
};
template< typename T , unsigned int PointD , typename ConstraintDual , typename SystemDual >
struct ApproximateChildPointInterpolationInfo : public InterpolationInfo< T , PointD >
{
void range( const FEMTreeNode* node , size_t& begin , size_t& end ) const
{
int idx = _iData.index( node );
if( idx<0 ) begin = end = 0;
else begin = (idx<<Dim) , end = (idx<<Dim) | _iData[idx].size();
}
bool constrainsDCTerm( void ) const { return _constrainsDCTerm; }
const DualPointInfo< Dim , Real , T , PointD >& operator[]( size_t pointIdx ) const { return __iData(pointIdx); }
Point< T , CumulativeDerivatives< Dim , PointD >::Size > operator() ( size_t pointIdx ) const { return _constraintDual( __iData(pointIdx).position ); }
Point< T , CumulativeDerivatives< Dim , PointD >::Size > operator() ( size_t pointIdx , const Point< T , CumulativeDerivatives< Dim , PointD >::Size >& dValues ) const { return _systemDual( __iData(pointIdx).position , dValues ); }
Point< double , CumulativeDerivatives< Dim , PointD >::Size > operator() ( size_t pointIdx , const Point< double , CumulativeDerivatives< Dim , PointD >::Size >& dValues ) const { return _systemDual( __iData(pointIdx).position , dValues ); }
ApproximateChildPointInterpolationInfo( ConstraintDual constraintDual , SystemDual systemDual , bool constrainsDCTerm ) : _constraintDual( constraintDual ) , _systemDual( systemDual ) , _constrainsDCTerm( constrainsDCTerm ) { }
protected:
static const unsigned int _Mask = (1<<Dim)-1;
SparseNodeData< DualPointInfoBrood< Dim , Real , T , PointD > , ZeroUIntPack< Dim > > _iData;
DualPointInfo< Dim , Real , T , PointD >& __iData( size_t pointIdx ){ return _iData[ (int)(pointIdx>>Dim) ][ pointIdx & _Mask ]; }
const DualPointInfo< Dim , Real , T , PointD >& __iData( size_t pointIdx ) const { return _iData[ (int)(pointIdx>>Dim) ][ pointIdx & _Mask ]; }
bool _constrainsDCTerm;
ConstraintDual _constraintDual;
SystemDual _systemDual;
friend class FEMTree< Dim , Real >;
};
template< unsigned int PointD , typename ConstraintDual , typename SystemDual >
struct ApproximateChildPointInterpolationInfo< double , PointD , ConstraintDual , SystemDual > : public InterpolationInfo< double , PointD >
{
typedef double T;
void range( const FEMTreeNode* node , size_t& begin , size_t& end ) const
{
int idx = _iData.index( node );
if( idx<0 ) begin = end = 0;
else begin = (idx<<Dim) , end = (idx<<Dim) | _iData[idx].size();
}
bool constrainsDCTerm( void ) const { return _constrainsDCTerm; }
const DualPointInfo< Dim , Real , T , PointD >& operator[]( size_t pointIdx ) const { return __iData(pointIdx); }
Point< T , CumulativeDerivatives< Dim , PointD >::Size > operator() ( size_t pointIdx ) const { return _constraintDual( __iData(pointIdx).position ); }
Point< T , CumulativeDerivatives< Dim , PointD >::Size > operator() ( size_t pointIdx , const Point< T , CumulativeDerivatives< Dim , PointD >::Size >& dValues ) const { return _systemDual( __iData(pointIdx).position , dValues ); }
ApproximateChildPointInterpolationInfo( ConstraintDual constraintDual , SystemDual systemDual , bool constrainsDCTerm ) : _constraintDual( constraintDual ) , _systemDual( systemDual ) , _constrainsDCTerm( constrainsDCTerm ) { }
protected:
static const unsigned int _Mask = (1<<Dim)-1;
SparseNodeData< DualPointInfoBrood< Dim , Real , T , PointD > , ZeroUIntPack< Dim > > _iData;
DualPointInfo< Dim , Real , T , PointD >& __iData( size_t pointIdx ){ return _iData[ (int)(pointIdx>>Dim) ][ pointIdx & _Mask ]; }
const DualPointInfo< Dim , Real , T , PointD >& __iData( size_t pointIdx ) const { return _iData[ (int)(pointIdx>>Dim) ][ pointIdx & _Mask ]; }
bool _constrainsDCTerm;
ConstraintDual _constraintDual;
SystemDual _systemDual;
friend class FEMTree< Dim , Real >;
};
template< typename T , typename Data , unsigned int PointD , typename ConstraintDual , typename SystemDual >
struct ApproximateChildPointAndDataInterpolationInfo : public InterpolationInfo< T , PointD >
{
void range( const FEMTreeNode* node , size_t& begin , size_t& end ) const
{
int idx = _iData.index( node );
if( idx<0 ) begin = end = 0;
else begin = (idx<<Dim) , end = (idx<<Dim) | _iData[idx].size();
}
bool constrainsDCTerm( void ) const { return _constrainsDCTerm; }
const DualPointInfo< Dim , Real , T , PointD >& operator[]( size_t pointIdx ) const { return __iData(pointIdx).pointInfo; }
Point< T , CumulativeDerivatives< Dim , PointD >::Size > operator() ( size_t pointIdx ) const { return _constraintDual( __iData(pointIdx).pointInfo.position , __iData(pointIdx).data ); }
Point< T , CumulativeDerivatives< Dim , PointD >::Size > operator() ( size_t pointIdx , const Point< T , CumulativeDerivatives< Dim , PointD >::Size >& dValues ) const { return _systemDual( __iData(pointIdx).pointInfo.position , __iData(pointIdx).data , dValues ); }
Point< double , CumulativeDerivatives< Dim , PointD >::Size > operator() ( size_t pointIdx , const Point< double , CumulativeDerivatives< Dim , PointD >::Size >& dValues ) const { return _systemDual( __iData(pointIdx).pointInfo.position , __iData(pointIdx).data , dValues ); }
ApproximateChildPointAndDataInterpolationInfo( ConstraintDual constraintDual , SystemDual systemDual , bool constrainsDCTerm ) : _constraintDual( constraintDual ) , _systemDual( systemDual ) , _constrainsDCTerm( constrainsDCTerm ) { }
protected:
static const unsigned int _Mask = (1<<Dim)-1;
SparseNodeData< DualPointAndDataInfoBrood< Dim , Real , Data , T , PointD > , ZeroUIntPack< Dim > > _iData;
DualPointAndDataInfo< Dim , Real , Data , T , PointD >& __iData( size_t pointIdx ){ return _iData[ (int)(pointIdx>>Dim) ][ pointIdx & _Mask ]; }
const DualPointAndDataInfo< Dim , Real , Data , T , PointD >& __iData( size_t pointIdx ) const { return _iData[ (int)(pointIdx>>Dim) ][ pointIdx & _Mask ]; }
bool _constrainsDCTerm;
ConstraintDual _constraintDual;
SystemDual _systemDual;
friend class FEMTree< Dim , Real >;
};
template< typename Data , unsigned int PointD , typename ConstraintDual , typename SystemDual >
struct ApproximateChildPointAndDataInterpolationInfo< double , Data , PointD , ConstraintDual , SystemDual > : public InterpolationInfo< double , PointD >
{
typedef double T;
void range( const FEMTreeNode* node , size_t& begin , size_t& end ) const
{
int idx = _iData.index( node );
if( idx<0 ) begin = end = 0;
else begin = (idx<<Dim) , end = (idx<<Dim) | _iData[idx].size();
}
bool constrainsDCTerm( void ) const { return _constrainsDCTerm; }
const DualPointInfo< Dim , Real , T , PointD >& operator[]( size_t pointIdx ) const { return __iData(pointIdx).pointInfo; }
Point< T , CumulativeDerivatives< Dim , PointD >::Size > operator() ( size_t pointIdx ) const { return _constraintDual( __iData(pointIdx).pointInfo.position , __iData(pointIdx).data ); }
Point< T , CumulativeDerivatives< Dim , PointD >::Size > operator() ( size_t pointIdx , const Point< T , CumulativeDerivatives< Dim , PointD >::Size >& dValues ) const { return _systemDual( __iData(pointIdx).pointInfo.position , __iData(pointIdx).data , dValues ); }
ApproximateChildPointAndDataInterpolationInfo( ConstraintDual constraintDual , SystemDual systemDual , bool constrainsDCTerm ) : _constraintDual( constraintDual ) , _systemDual( systemDual ) , _constrainsDCTerm( constrainsDCTerm ) { }
protected:
static const unsigned int _Mask = (1<<Dim)-1;
SparseNodeData< DualPointAndDataInfoBrood< Dim , Real , Data , T , PointD > , ZeroUIntPack< Dim > > _iData;
DualPointAndDataInfo< Dim , Real , Data , T , PointD >& __iData( size_t pointIdx ){ return _iData[ (int)(pointIdx>>Dim) ][ pointIdx & _Mask ]; }
const DualPointAndDataInfo< Dim , Real , Data , T , PointD >& __iData( size_t pointIdx ) const { return _iData[ (int)(pointIdx>>Dim) ][ pointIdx & _Mask ]; }
bool _constrainsDCTerm;
ConstraintDual _constraintDual;
SystemDual _systemDual;
friend class FEMTree< Dim , Real >;
};
template< typename T , unsigned int PointD , typename ConstraintDual , typename SystemDual >
struct ExactPointInterpolationInfo : public InterpolationInfo< T , PointD >
{
void range( const FEMTreeNode* node , size_t& begin , size_t& end ) const { begin = _sampleSpan[ node->nodeData.nodeIndex ].first , end = _sampleSpan[ node->nodeData.nodeIndex ].second; }
bool constrainsDCTerm( void ) const { return _constrainsDCTerm; }
const DualPointInfo< Dim , Real , T , PointD >& operator[]( size_t pointIdx ) const { return _iData[ (int)pointIdx ]; }
Point< T , CumulativeDerivatives< Dim , PointD >::Size > operator() ( size_t pointIdx ) const { return _constraintDual( _iData[ (int)pointIdx ].position ); }
Point< T , CumulativeDerivatives< Dim , PointD >::Size > operator() ( size_t pointIdx , const Point< T , CumulativeDerivatives< Dim , PointD >::Size >& dValues ) const { return _systemDual( _iData[ (int)pointIdx ].position , dValues ); }
Point< double , CumulativeDerivatives< Dim , PointD >::Size > operator() ( size_t pointIdx , const Point< double , CumulativeDerivatives< Dim , PointD >::Size >& dValues ) const { return _systemDual( _iData[ (int)pointIdx ].position , dValues ); }
ExactPointInterpolationInfo( ConstraintDual constraintDual , SystemDual systemDual , bool constrainsDCTerm ) : _constraintDual( constraintDual ) , _systemDual( systemDual ) , _constrainsDCTerm( constrainsDCTerm ) { }
protected:
void _init( const class FEMTree< Dim , Real >& tree , const std::vector< PointSample >& samples , bool noRescale );
std::vector< std::pair< int , int > > _sampleSpan;
std::vector< DualPointInfo< Dim , Real , T , PointD > > _iData;
bool _constrainsDCTerm;
ConstraintDual _constraintDual;
SystemDual _systemDual;
friend class FEMTree< Dim , Real >;
};
template< unsigned int PointD , typename ConstraintDual , typename SystemDual >
struct ExactPointInterpolationInfo< double , PointD , ConstraintDual , SystemDual > : public InterpolationInfo< double , PointD >
{
typedef double T;
void range( const FEMTreeNode* node , size_t& begin , size_t& end ) const { begin = _sampleSpan[ node->nodeData.nodeIndex ].first , end = _sampleSpan[ node->nodeData.nodeIndex ].second; }
bool constrainsDCTerm( void ) const { return _constrainsDCTerm; }
const DualPointInfo< Dim , Real , T , PointD >& operator[]( size_t pointIdx ) const { return _iData[ (int)pointIdx ]; }
Point< T , CumulativeDerivatives< Dim , PointD >::Size > operator() ( size_t pointIdx ) const { return _constraintDual( _iData[ (int)pointIdx ].position ); }
Point< T , CumulativeDerivatives< Dim , PointD >::Size > operator() ( size_t pointIdx , const Point< T , CumulativeDerivatives< Dim , PointD >::Size >& dValues ) const { return _systemDual( _iData[ (int)pointIdx ].position , dValues ); }
ExactPointInterpolationInfo( ConstraintDual constraintDual , SystemDual systemDual , bool constrainsDCTerm ) : _constraintDual( constraintDual ) , _systemDual( systemDual ) , _constrainsDCTerm( constrainsDCTerm ) { }
protected:
void _init( const class FEMTree< Dim , Real >& tree , const std::vector< PointSample >& samples , bool noRescale );
std::vector< std::pair< int , int > > _sampleSpan;
std::vector< DualPointInfo< Dim , Real , T , PointD > > _iData;
bool _constrainsDCTerm;
ConstraintDual _constraintDual;
SystemDual _systemDual;
friend class FEMTree< Dim , Real >;
};
template< typename T , typename Data , unsigned int PointD , typename ConstraintDual , typename SystemDual >
struct _ExactPointAndDataInterpolationInfo : public InterpolationInfo< T , PointD >
{
_ExactPointAndDataInterpolationInfo( ConstraintDual constraintDual , SystemDual systemDual , bool constrainsDCTerm ) : _constraintDual( constraintDual ) , _systemDual( systemDual ) , _constrainsDCTerm( constrainsDCTerm ) { }
protected:
void _init( const class FEMTree< Dim , Real >& tree , const std::vector< PointSample >& samples , ConstPointer( Data ) sampleData , bool noRescale );
std::vector< std::pair< int , int > > _sampleSpan;
std::vector< DualPointAndDataInfo< Dim , Real , Data , T , PointD > > _iData;
bool _constrainsDCTerm;
ConstraintDual _constraintDual;
SystemDual _systemDual;
friend class FEMTree< Dim , Real >;
};
template< typename T , typename Data , unsigned int PointD , typename ConstraintDual , typename SystemDual >
struct ExactPointAndDataInterpolationInfo : public _ExactPointAndDataInterpolationInfo< T , Data , PointD , ConstraintDual , SystemDual >
{
using _ExactPointAndDataInterpolationInfo< T , Data , PointD , ConstraintDual , SystemDual >::_sampleSpan;
using _ExactPointAndDataInterpolationInfo< T , Data , PointD , ConstraintDual , SystemDual >::_constrainsDCTerm;
using _ExactPointAndDataInterpolationInfo< T , Data , PointD , ConstraintDual , SystemDual >::_iData;
using _ExactPointAndDataInterpolationInfo< T , Data , PointD , ConstraintDual , SystemDual >::_constraintDual;
using _ExactPointAndDataInterpolationInfo< T , Data , PointD , ConstraintDual , SystemDual >::_systemDual;
void range( const FEMTreeNode* node , size_t& begin , size_t& end ) const { begin = _sampleSpan[ node->nodeData.nodeIndex ].first , end = _sampleSpan[ node->nodeData.nodeIndex ].second; }
bool constrainsDCTerm( void ) const { return _constrainsDCTerm; }
const DualPointInfo< Dim , Real , T , PointD >& operator[]( size_t pointIdx ) const { return _iData[ (int)pointIdx ].pointInfo; }
Point< T , CumulativeDerivatives< Dim , PointD >::Size > operator() ( size_t pointIdx ) const { return _constraintDual( _iData[ pointIdx ].pointInfo.position , _iData[ (int)pointIdx ].data ); }
Point< T , CumulativeDerivatives< Dim , PointD >::Size > operator() ( size_t pointIdx , const Point< T , CumulativeDerivatives< Dim , PointD >::Size >& dValues ) const { return _systemDual( _iData[ (int)pointIdx ].pointInfo.position , _iData[ (int)pointIdx ].data , dValues ); }
Point< double , CumulativeDerivatives< Dim , PointD >::Size > operator() ( size_t pointIdx , const Point< double , CumulativeDerivatives< Dim , PointD >::Size >& dValues ) const { return _systemDual( _iData[ (int)pointIdx ].pointInfo.position , _iData[ (int)pointIdx ].data , dValues ); }
ExactPointAndDataInterpolationInfo( ConstraintDual constraintDual , SystemDual systemDual , bool constrainsDCTerm ) : _ExactPointAndDataInterpolationInfo< T , Data , PointD , ConstraintDual , SystemDual >( constraintDual , systemDual , constrainsDCTerm ) { }
};
template< typename Data , unsigned int PointD , typename ConstraintDual , typename SystemDual >
struct ExactPointAndDataInterpolationInfo< double , Data , PointD , ConstraintDual , SystemDual > : public _ExactPointAndDataInterpolationInfo< double , Data , PointD , ConstraintDual , SystemDual >
{
using _ExactPointAndDataInterpolationInfo< double , Data , PointD , ConstraintDual , SystemDual >::_sampleSpan;
using _ExactPointAndDataInterpolationInfo< double , Data , PointD , ConstraintDual , SystemDual >::_constrainsDCTerm;
using _ExactPointAndDataInterpolationInfo< double , Data , PointD , ConstraintDual , SystemDual >::_iData;
void range( const FEMTreeNode* node , size_t& begin , size_t& end ) const { begin = _sampleSpan[ node->nodeData.nodeIndex ].first , end = _sampleSpan[ node->nodeData.nodeIndex ].second; }
bool constrainsDCTerm( void ) const { return _constrainsDCTerm; }
const DualPointInfo< Dim , Real , double , PointD >& operator[]( size_t pointIdx ) const { return _iData[ (int)pointIdx ].pointInfo; }
Point< double , CumulativeDerivatives< Dim , PointD >::Size > operator() ( size_t pointIdx ) const { return _constraintDual( _iData[ pointIdx ].pointInfo.position , _iData[ (int)pointIdx ].data ); }
Point< double , CumulativeDerivatives< Dim , PointD >::Size > operator() ( size_t pointIdx , const Point< double , CumulativeDerivatives< Dim , PointD >::Size >& dValues ) const { return _systemDual( _iData[ (int)pointIdx ].pointInfo.position , _iData[ (int)pointIdx ].data , dValues ); }
ExactPointAndDataInterpolationInfo( ConstraintDual constraintDual , SystemDual systemDual , bool constrainsDCTerm ) : _ExactPointAndDataInterpolationInfo< double , Data , PointD , ConstraintDual , SystemDual >( constraintDual , systemDual , constrainsDCTerm ) { }
};
template< typename T , unsigned int PointD , typename ConstraintDual , typename SystemDual >
static ApproximatePointInterpolationInfo< T , PointD , ConstraintDual , SystemDual >* InitializeApproximatePointInterpolationInfo( const class FEMTree< Dim , Real >& tree , const std::vector< PointSample >& samples , ConstraintDual constraintDual , SystemDual systemDual , bool constrainsDCTerm , int adaptiveExponent )
{
ApproximatePointInterpolationInfo< T , PointD , ConstraintDual , SystemDual >* a = new ApproximatePointInterpolationInfo< T , PointD , ConstraintDual , SystemDual >( constraintDual , systemDual , constrainsDCTerm );
a->_iData = tree._densifyInterpolationInfoAndSetDualConstraints< T , PointD >( samples , constraintDual , adaptiveExponent );
return a;
}
template< typename T , typename Data , unsigned int PointD , typename ConstraintDual , typename SystemDual >
static ApproximatePointAndDataInterpolationInfo< T , Data , PointD , ConstraintDual , SystemDual >* InitializeApproximatePointAndDataInterpolationInfo( const class FEMTree< Dim , Real >& tree , const std::vector< PointSample >& samples , ConstPointer( Data ) sampleData , ConstraintDual constraintDual , SystemDual systemDual , bool constrainsDCTerm , int adaptiveExponent )
{
ApproximatePointAndDataInterpolationInfo< T , Data , PointD , ConstraintDual , SystemDual >* a = new ApproximatePointAndDataInterpolationInfo< T , Data , PointD , ConstraintDual , SystemDual >( constraintDual , systemDual , constrainsDCTerm );
a->_iData = tree._densifyInterpolationInfoAndSetDualConstraints< T , Data , PointD >( samples , sampleData , constraintDual , adaptiveExponent );
return a;
}
template< typename T , unsigned int PointD , typename ConstraintDual , typename SystemDual >
static ApproximateChildPointInterpolationInfo< T , PointD , ConstraintDual , SystemDual >* InitializeApproximateChildPointInterpolationInfo( const class FEMTree< Dim , Real >& tree , const std::vector< PointSample >& samples , ConstraintDual constraintDual , SystemDual systemDual , bool constrainsDCTerm , bool noRescale )
{
ApproximateChildPointInterpolationInfo< T , PointD , ConstraintDual , SystemDual >* a = new ApproximateChildPointInterpolationInfo< T , PointD , ConstraintDual , SystemDual >( constraintDual , systemDual , constrainsDCTerm );
a->_iData = tree._densifyChildInterpolationInfoAndSetDualConstraints< T , PointD >( samples , constraintDual , noRescale );
return a;
}
template< typename T , typename Data , unsigned int PointD , typename ConstraintDual , typename SystemDual >
static ApproximateChildPointAndDataInterpolationInfo< T , Data , PointD , ConstraintDual , SystemDual >* InitializeApproximateChildPointAndDataInterpolationInfo( const class FEMTree< Dim , Real >& tree , const std::vector< PointSample >& samples , ConstPointer( Data ) sampleData , ConstraintDual constraintDual , SystemDual systemDual , bool constrainsDCTerm , bool noRescale )
{
ApproximateChildPointAndDataInterpolationInfo< T , Data , PointD , ConstraintDual , SystemDual >* a = new ApproximateChildPointAndDataInterpolationInfo< T , Data , PointD , ConstraintDual , SystemDual >( constraintDual , systemDual , constrainsDCTerm );
a->_iData = tree._densifyChildInterpolationInfoAndSetDualConstraints< T , Data , PointD >( samples , sampleData , constraintDual , noRescale );
return a;
}
template< typename T , unsigned int PointD , typename ConstraintDual , typename SystemDual >
static ExactPointInterpolationInfo< T , PointD , ConstraintDual , SystemDual >* InitializeExactPointInterpolationInfo( const class FEMTree< Dim , Real >& tree , const std::vector< PointSample >& samples , ConstraintDual constraintDual , SystemDual systemDual , bool constrainsDCTerm , bool noRescale )
{
ExactPointInterpolationInfo< T , PointD , ConstraintDual , SystemDual >* e = new ExactPointInterpolationInfo< T , PointD , ConstraintDual , SystemDual >( constraintDual , systemDual , constrainsDCTerm );
e->_init( tree , samples , noRescale );
return e;
}
template< typename T , typename Data , unsigned int PointD , typename ConstraintDual , typename SystemDual >
static ExactPointAndDataInterpolationInfo< T , Data , PointD , ConstraintDual , SystemDual >* InitializeExactPointAndDataInterpolationInfo( const class FEMTree< Dim , Real >& tree , const std::vector< PointSample >& samples , ConstPointer( Data ) sampleData , ConstraintDual constraintDual , SystemDual systemDual , bool constrainsDCTerm , bool noRescale )
{
ExactPointAndDataInterpolationInfo< T , Data , PointD , ConstraintDual , SystemDual >* e = new ExactPointAndDataInterpolationInfo< T , Data , PointD , ConstraintDual , SystemDual >( constraintDual , systemDual , constrainsDCTerm );
e->_init( tree , samples , sampleData , noRescale );
return e;
}
template< typename T , unsigned int PointD , typename ConstraintDual , typename SystemDual > friend struct ExactPointInterpolationInfo;
template< typename T , typename Data , unsigned int PointD , typename ConstraintDual , typename SystemDual > friend struct ExactPointAndDataInterpolationInfo;
template< typename T , unsigned int PointD , unsigned int ... PointDs >
static bool ConstrainsDCTerm( const InterpolationInfo< T , PointD >* iInfo , const InterpolationInfo< T , PointDs >* ... iInfos ){ return ConstrainsDCTerm( iInfo ) || ConstrainsDCTerm( iInfos... ); }
template< typename T , unsigned int PointD >
static bool ConstrainsDCTerm( const InterpolationInfo< T , PointD >* iInfo ){ return iInfo && iInfo->constrainsDCTerm(); }
static bool ConstrainsDCTerm( void ){ return false; }
#ifdef SHOW_WARNINGS
#pragma message( "[WARNING] This should not be isotropic" )
#endif // SHOW_WARNINGS
template< unsigned int DensityDegree > struct DensityEstimator : public SparseNodeData< Real , IsotropicUIntPack< Dim , FEMDegreeAndBType< DensityDegree >::Signature > >
{
DensityEstimator( int kernelDepth , int coDimension ) : _kernelDepth( kernelDepth ) , _coDimension( coDimension ){ ; }
int coDimension( void ) const { return _coDimension; }
int kernelDepth( void ) const { return _kernelDepth; }
protected:
int _kernelDepth , _coDimension;
};
protected:
bool _isValidSpaceNode( const FEMTreeNode* node ) const { return !GetGhostFlag< Dim >( node ) && ( node->nodeData.flags & FEMTreeNodeData::SPACE_FLAG ); }
bool _isValidFEM1Node ( const FEMTreeNode* node ) const { return !GetGhostFlag< Dim >( node ) && ( node->nodeData.flags & FEMTreeNodeData::FEM_FLAG_1 ); }
bool _isValidFEM2Node ( const FEMTreeNode* node ) const { return !GetGhostFlag< Dim >( node ) && ( node->nodeData.flags & FEMTreeNodeData::FEM_FLAG_2 ); }
bool _isRefinableNode ( const FEMTreeNode* node ) const { return !GetGhostFlag< Dim >( node ) && ( node->nodeData.flags & FEMTreeNodeData::REFINABLE_FLAG ); }
FEMTreeNode* _tree;
FEMTreeNode* _spaceRoot;
SortedTreeNodes< Dim > _sNodes;
LocalDepth _maxDepth;
int _depthOffset;
mutable unsigned int _femSigs1[ Dim ];
mutable unsigned int _femSigs2[ Dim ];
mutable unsigned int _refinableSigs[ Dim ];
static bool _InBounds( Point< Real , Dim > p );
int _localToGlobal( LocalDepth d ) const { return d + _depthOffset; }
LocalDepth _localDepth( const FEMTreeNode* node ) const { return node->depth() - _depthOffset; }
int _localInset( LocalDepth d ) const { return _depthOffset<=1 ? 0 : 1<<( d + _depthOffset - 1 ); }
void _localDepthAndOffset( const FEMTreeNode* node , LocalDepth& d , LocalOffset& off ) const
{
node->depthAndOffset( d , off ) ; d -= _depthOffset;
int inset = _localInset( d );
for( int d=0 ; d<Dim ; d++ ) off[d] -= inset;
}
template< unsigned int FEMSig > static int _BSplineBegin( LocalDepth depth ){ return BSplineEvaluationData< FEMSig >::Begin( depth ); }
template< unsigned int FEMSig > static int _BSplineEnd ( LocalDepth depth ){ return BSplineEvaluationData< FEMSig >::End ( depth ); }
template< unsigned int ... FEMSigs >
bool _outOfBounds( UIntPack< FEMSigs ... > , const FEMTreeNode* node ) const
{
if( !node ) return true;
LocalDepth d ; LocalOffset off ; _localDepthAndOffset( node , d , off );
return FEMIntegrator::IsOutOfBounds( UIntPack< FEMSigs ... >() , d , off );
}
int _sNodesBegin( LocalDepth d ) const { return _sNodes.begin( _localToGlobal( d ) ); }
int _sNodesEnd ( LocalDepth d ) const { return _sNodes.end ( _localToGlobal( d ) ); }
int _sNodesSize ( LocalDepth d ) const { return _sNodes.size ( _localToGlobal( d ) ); }
int _sNodesBeginSlice( LocalDepth d ) const { return _localInset(d); }
int _sNodesEndSlice( LocalDepth d ) const{ return ( 1<<_localToGlobal(d) ) - _localInset(d) - 1; }
int _sNodesBegin( LocalDepth d , int slice ) const { return _sNodes.begin( _localToGlobal( d ) , slice + _localInset( d ) ); }
int _sNodesEnd ( LocalDepth d , int slice ) const { return _sNodes.end ( _localToGlobal( d ) , slice + _localInset( d ) ); }
int _sNodesSize ( LocalDepth d , int slice ) const { return _sNodes.size ( _localToGlobal( d ) , slice + _localInset( d ) ); }
template< unsigned int FEMDegree > static bool _IsInteriorlySupported( LocalDepth depth , const LocalOffset off )
{
if( depth>=0 )
{
int begin , end;
BSplineSupportSizes< FEMDegree >::InteriorSupportedSpan( depth , begin , end );
bool interior = true;
for( int dd=0 ; dd<Dim ; dd++ ) interior &= off[dd]>=begin && off[dd]<end;
return interior;
}
else return false;
}
template< unsigned int FEMDegree > bool _isInteriorlySupported( const FEMTreeNode* node ) const
{
if( !node ) return false;
LocalDepth d ; LocalOffset off;
_localDepthAndOffset( node , d , off );
return _IsInteriorlySupported< FEMDegree >( d , off );
}
template< unsigned int ... FEMDegrees > static bool _IsInteriorlySupported( UIntPack< FEMDegrees ... > , LocalDepth depth , const LocalOffset off ){ return BaseFEMIntegrator::IsInteriorlySupported( UIntPack< FEMDegrees ... >() , depth , off ); }
template< unsigned int ... FEMDegrees > bool _isInteriorlySupported( UIntPack< FEMDegrees ... > , const FEMTreeNode* node ) const
{
if( !node ) return false;
LocalDepth d ; LocalOffset off ; _localDepthAndOffset( node , d , off );
return _IsInteriorlySupported< FEMDegrees ... >( UIntPack< FEMDegrees ... >() , d , off );
}
template< unsigned int FEMDegree1 , unsigned int FEMDegree2 > static bool _IsInteriorlyOverlapped( LocalDepth depth , const LocalOffset off )
{
if( depth>=0 )
{
int begin , end;
BSplineIntegrationData< FEMDegreeAndBType< FEMDegree1 , BOUNDARY_NEUMANN >::Signature , FEMDegreeAndBType< FEMDegree2 , BOUNDARY_NEUMANN >::Signature >::InteriorOverlappedSpan( depth , begin , end );
bool interior = true;
for( int dd=0 ; dd<Dim ; dd++ ) interior &= off[dd]>=begin && off[dd]<end;
return interior;
}
else return false;
}
template< unsigned int FEMDegree1 , unsigned int FEMDegree2 > bool _isInteriorlyOverlapped( const FEMTreeNode* node ) const
{
if( !node ) return false;
LocalDepth d ; LocalOffset off;
_localDepthAndOffset( node , d , off );
return _IsInteriorlyOverlapped< FEMDegree1 , FEMDegree2 >( d , off );
}
template< unsigned int ... FEMDegrees1 , unsigned int ... FEMDegrees2 > static bool _IsInteriorlyOverlapped( UIntPack< FEMDegrees1 ... > , UIntPack< FEMDegrees2 ... > , LocalDepth depth , const LocalOffset off ){ return BaseFEMIntegrator::IsInteriorlyOverlapped( UIntPack< FEMDegrees1 ... >() , UIntPack< FEMDegrees2 ... >() , depth , off ); }
template< unsigned int ... FEMDegrees1 , unsigned int ... FEMDegrees2 > bool _isInteriorlyOverlapped( UIntPack< FEMDegrees1 ... > , UIntPack< FEMDegrees2 ... > , const FEMTreeNode* node ) const
{
if( !node ) return false;
LocalDepth d ; LocalOffset off ; _localDepthAndOffset( node , d , off );
return _IsInteriorlyOverlapped( UIntPack< FEMDegrees1 ... >() , UIntPack< FEMDegrees2 ... >() , d , off );
}
void _startAndWidth( const FEMTreeNode* node , Point< Real , Dim >& start , Real& width ) const
{
LocalDepth d ; LocalOffset off;
_localDepthAndOffset( node , d , off );
if( d>=0 ) width = Real( 1.0 / (1<< d ) );
else width = Real( 1.0 * (1<<(-d)) );
for( int dd=0 ; dd<Dim ; dd++ ) start[dd] = Real( off[dd] ) * width;
}
void _centerAndWidth( const FEMTreeNode* node , Point< Real , Dim >& center , Real& width ) const
{
int d , off[Dim];
_localDepthAndOffset( node , d , off );
width = Real( 1.0 / (1<<d) );
for( int dd=0 ; dd<Dim ; dd++ ) center[dd] = Real( off[dd] + 0.5 ) * width;
}
int _childIndex( const FEMTreeNode* node , Point< Real , Dim > p ) const
{
Point< Real , Dim > c ; Real w;
_centerAndWidth( node , c , w );
int cIdx = 0;
for( int d=0 ; d<Dim ; d++ ) if( p[d]>=c[d] ) cIdx |= (1<<d);
return cIdx;
}
template< unsigned int ... Degrees > void _setFullDepth( UIntPack< Degrees ... > , FEMTreeNode* node , LocalDepth depth );
template< unsigned int ... Degrees > void _setFullDepth( UIntPack< Degrees ... > , LocalDepth depth );
template< unsigned int ... Degrees > LocalDepth _getFullDepth( UIntPack< Degrees ... > , const FEMTreeNode* node ) const;
public:
template< unsigned int ... Degrees > LocalDepth getFullDepth( UIntPack< Degrees ... > ) const;
LocalDepth depth( const FEMTreeNode* node ) const { return _localDepth( node ); }
void depthAndOffset( const FEMTreeNode* node , LocalDepth& depth , LocalOffset& offset ) const { _localDepthAndOffset( node , depth , offset ); }
int nodesSize ( void ) const { return _sNodes.size( ); }
int nodesBegin( LocalDepth d ) const { return _sNodes.begin( _localToGlobal( d ) ); }
int nodesEnd ( LocalDepth d ) const { return _sNodes.end ( _localToGlobal( d ) ); }
int nodesSize ( LocalDepth d ) const { return _sNodes.size ( _localToGlobal( d ) ); }
int nodesBegin( LocalDepth d , int slice ) const { return _sNodes.begin( _localToGlobal( d ) , slice + _localInset( d ) ); }
int nodesEnd ( LocalDepth d , int slice ) const { return _sNodes.end ( _localToGlobal( d ) , slice + _localInset( d ) ); }
int nodesSize ( LocalDepth d , int slice ) const { return _sNodes.size ( _localToGlobal( d ) , slice + _localInset( d ) ); }
const FEMTreeNode* node( int idx ) const { return _sNodes.treeNodes[idx]; }
void centerAndWidth( int idx , Point< Real , Dim >& center , Real& width ) const { _centerAndWidth( _sNodes.treeNodes[idx] , center , width ); }
void startAndWidth( int idx , Point< Real , Dim >& center , Real& width ) const { _startAndWidth( _sNodes.treeNodes[idx] , center , width ); }
protected:
/////////////////////////////////////
// System construction code //
// MultiGridFEMTreeData.System.inl //
/////////////////////////////////////
public:
template< unsigned int ... FEMSigs > void setMultiColorIndices( UIntPack< FEMSigs ... > , int depth , std::vector< std::vector< int > >& indices ) const;
protected:
template< unsigned int ... FEMSigs > void _setMultiColorIndices( UIntPack< FEMSigs ... > , int start , int end , std::vector< std::vector< int > >& indices ) const;
struct _SolverStats
{
double constraintUpdateTime , systemTime , solveTime;
double bNorm2 , inRNorm2 , outRNorm2;
};
template< unsigned int ... FEMSigs , typename T , unsigned int PointD , unsigned int ... PointDs >
typename std::enable_if< (sizeof...(PointDs)!=0) >::type _addPointValues( UIntPack< FEMSigs ... > , StaticWindow< Real , UIntPack< BSplineOverlapSizes< FEMSignature< FEMSigs >::Degree >::OverlapSize ... > >& pointValues , const typename FEMTreeNode::template ConstNeighbors< UIntPack< BSplineOverlapSizes< FEMSignature< FEMSigs >::Degree >::OverlapSize ... > >& neighbors , const PointEvaluator< UIntPack< FEMSigs ... > , UIntPack< FEMSignature< FEMSigs >::Degree ... > >& bsData , const InterpolationInfo< T , PointD >* iInfo , const InterpolationInfo< T , PointDs >* ... iInfos ) const
{
_addPointValues( UIntPack< FEMSigs ... >() , pointValues , neighbors , bsData , iInfo ) , _addPointValues( UIntPack< FEMSigs ... >() , pointValues , neighbors , bsData , iInfos... );
}
template< unsigned int ... FEMSigs >
void _addPointValues( UIntPack< FEMSigs ... > , StaticWindow< Real , UIntPack< BSplineOverlapSizes< FEMSignature< FEMSigs >::Degree >::OverlapSize ... > >& pointValues , const typename FEMTreeNode::template ConstNeighbors< UIntPack< BSplineOverlapSizes< FEMSignature< FEMSigs >::Degree >::OverlapSize ... > >& neighbors , const PointEvaluator< UIntPack< FEMSigs ... > , UIntPack< FEMSignature< FEMSigs >::Degree ... > >& bsData ) const { }
template< unsigned int ... FEMSigs , typename T , unsigned int PointD >
void _addPointValues( UIntPack< FEMSigs ... > , StaticWindow< Real , UIntPack< BSplineOverlapSizes< FEMSignature< FEMSigs >::Degree >::OverlapSize ... > >& pointValues , const typename FEMTreeNode::template ConstNeighbors< UIntPack< BSplineOverlapSizes< FEMSignature< FEMSigs >::Degree >::OverlapSize ... > >& neighbors , const PointEvaluator< UIntPack< FEMSigs ... > , UIntPack< FEMSignature< FEMSigs >::Degree ... > >& bsData , const InterpolationInfo< T , PointD >* interpolationInfo ) const;
template< unsigned int ... FEMSigs , typename T , unsigned int PointD , unsigned int ... PointDs >
typename std::enable_if< (sizeof...(PointDs)>1) >::type _addProlongedPointValues( UIntPack< FEMSigs ... > , WindowSlice< Real , UIntPack< BSplineOverlapSizes< FEMSignature< FEMSigs >::Degree >::OverlapSize ... > > pointValues , const typename FEMTreeNode::template ConstNeighbors< UIntPack< BSplineOverlapSizes< FEMSignature< FEMSigs >::Degree >::OverlapSize ... > >& neighbors , const typename FEMTreeNode::template ConstNeighbors< UIntPack< BSplineOverlapSizes< FEMSignature< FEMSigs >::Degree >::OverlapSize ... > >& pNeighbors , const PointEvaluator< UIntPack< FEMSigs ... > , UIntPack< FEMSignature< FEMSigs >::Degree ... > >& bsData , const InterpolationInfo< T , PointD >* iInfo , const InterpolationInfo< T , PointDs >* ... iInfos ) const
{
_addProlongedPointValues( UIntPack< FEMSigs ... >() , pointValues , neighbors , pNeighbors , bsData , iInfo ) , _addProlongedPointValues( UIntPack< FEMSigs ... >() , pointValues , neighbors , pNeighbors , bsData , iInfos... );
}
template< unsigned int ... FEMSigs > void _addProlongedPointValues( UIntPack< FEMSigs ... > , WindowSlice< Real , UIntPack< BSplineOverlapSizes< FEMSignature< FEMSigs >::Degree >::OverlapSize ... > > pointValues , const typename FEMTreeNode::template ConstNeighbors< UIntPack< BSplineOverlapSizes< FEMSignature< FEMSigs >::Degree >::OverlapSize ... > >& neighbors , const typename FEMTreeNode::template ConstNeighbors< UIntPack< BSplineOverlapSizes< FEMSignature< FEMSigs >::Degree >::OverlapSize ... > >& pNeighbors , const PointEvaluator< UIntPack< FEMSigs ... > , UIntPack< FEMSignature< FEMSigs >::Degree ... > >& bsData ) const { }
template< unsigned int ... FEMSigs , typename T , unsigned int PointD >
void _addProlongedPointValues( UIntPack< FEMSigs ... > , WindowSlice< Real , UIntPack< BSplineOverlapSizes< FEMSignature< FEMSigs >::Degree >::OverlapSize ... > > pointValues , const typename FEMTreeNode::template ConstNeighbors< UIntPack< BSplineOverlapSizes< FEMSignature< FEMSigs >::Degree >::OverlapSize ... > >& neighbors , const typename FEMTreeNode::template ConstNeighbors< UIntPack< BSplineOverlapSizes< FEMSignature< FEMSigs >::Degree >::OverlapSize ... > >& pNeighbors , const PointEvaluator< UIntPack< FEMSigs ... > , UIntPack< FEMSignature< FEMSigs >::Degree ... > >& bsData , const InterpolationInfo< T , PointD >* iInfo ) const;
template< unsigned int ... FEMSigs , typename T , unsigned int PointD , unsigned int ... PointDs >
typename std::enable_if< (sizeof...(PointDs)!=0) >::type _setPointValuesFromProlongedSolution( LocalDepth highDepth , const PointEvaluator< UIntPack< FEMSigs ... > , UIntPack< FEMSignature< FEMSigs >::Degree ... > >& bsData , ConstPointer( T ) prolongedSolution , InterpolationInfo< T , PointD >* iInfo , InterpolationInfo< T , PointDs >* ... iInfos ) const
{
_setPointValuesFromProlongedSolution( highDepth , bsData , prolongedSolution , iInfo ) , _setPointValuesFromProlongedSolution( highDepth , bsData , prolongedSolution , iInfos... );
}
template< unsigned int ... FEMSigs , typename T > void _setPointValuesFromProlongedSolution( LocalDepth highDepth , const PointEvaluator< UIntPack< FEMSigs ... > , UIntPack< FEMSignature< FEMSigs >::Degree ... > >& bsData , ConstPointer( T ) prolongedSolution ) const { }
template< unsigned int ... FEMSigs , typename T , unsigned int PointD >
void _setPointValuesFromProlongedSolution( LocalDepth highDepth , const PointEvaluator< UIntPack< FEMSigs ... > , UIntPack< FEMSignature< FEMSigs >::Degree ... > >& bsData , ConstPointer( T ) prolongedSolution , InterpolationInfo< T , PointD >* interpolationInfo ) const;
template< unsigned int ... FEMSigs , typename T , unsigned int PointD , unsigned int ... PointDs >
typename std::enable_if< (sizeof...(PointDs)!=0) , T >::type _getInterpolationConstraintFromProlongedSolution( const typename FEMTreeNode::template ConstNeighbors< UIntPack< BSplineOverlapSizes< FEMSignature< FEMSigs >::Degree >::OverlapSize ... > >& neighbors , const FEMTreeNode* node , ConstPointer( T ) prolongedSolution , const PointEvaluator< UIntPack< FEMSigs ... > , UIntPack< FEMSignature< FEMSigs >::Degree ... > >& bsData , const InterpolationInfo< T , PointD >* iInfo , const InterpolationInfo< T , PointDs >* ... iInfos ) const
{
return _getInterpolationConstraintFromProlongedSolution( neighbors , node , prolongedSolution , bsData , iInfo ) + _getInterpolationConstraintFromProlongedSolution( neighbors , node , prolongedSolution , bsData , iInfos... );
}
template< unsigned int ... FEMSigs , typename T > T _getInterpolationConstraintFromProlongedSolution( const typename FEMTreeNode::template ConstNeighbors< UIntPack< BSplineOverlapSizes< FEMSignature< FEMSigs >::Degree >::OverlapSize ... > >& neighbors , const FEMTreeNode* node , ConstPointer( T ) prolongedSolution , const PointEvaluator< UIntPack< FEMSigs ... > , UIntPack< FEMSignature< FEMSigs >::Degree ... > >& bsData ) const { return T(); }
template< unsigned int ... FEMSigs , typename T , unsigned int PointD >
T _getInterpolationConstraintFromProlongedSolution( const typename FEMTreeNode::template ConstNeighbors< UIntPack< BSplineOverlapSizes< FEMSignature< FEMSigs >::Degree >::OverlapSize ... > >& neighbors , const FEMTreeNode* node , ConstPointer( T ) prolongedSolution , const PointEvaluator< UIntPack< FEMSigs ... > , UIntPack< FEMSignature< FEMSigs >::Degree ... > >& bsData , const InterpolationInfo< T , PointD >* iInfo ) const;
template< unsigned int ... FEMSigs , typename T , unsigned int PointD , unsigned int ... PointDs >
typename std::enable_if< (sizeof...(PointDs)!=0) >::type _updateRestrictedInterpolationConstraints( const PointEvaluator< UIntPack< FEMSigs ... > , UIntPack< FEMSignature< FEMSigs >::Degree ... > >& bsData , LocalDepth highDepth , ConstPointer( T ) solution , Pointer( T ) cumulativeConstraints , const InterpolationInfo< T , PointD >* iInfo , const InterpolationInfo< T , PointDs >* ... iInfos ) const
{
_updateRestrictedInterpolationConstraints( bsData , highDepth , solution , cumulativeConstraints , iInfo ) , _updateRestrictedInterpolationConstraints( bsData , highDepth , solution , cumulativeConstraints , iInfos... );
}
template< unsigned int ... FEMSigs , typename T > void _updateRestrictedInterpolationConstraints( PointEvaluator< UIntPack< FEMSigs ... > , UIntPack< FEMSignature< FEMSigs >::Degree ... > >& bsData , LocalDepth highDepth , ConstPointer( T ) solution , Pointer( T ) cumulativeConstraints ) const { ; }
template< unsigned int ... FEMSigs , typename T , unsigned int PointD >
void _updateRestrictedInterpolationConstraints( const PointEvaluator< UIntPack< FEMSigs ... > , UIntPack< FEMSignature< FEMSigs >::Degree ... > >& bsData , LocalDepth highDepth , ConstPointer( T ) solution , Pointer( T ) cumulativeConstraints , const InterpolationInfo< T , PointD >* interpolationInfo ) const;
template< unsigned int FEMDegree1 , unsigned int FEMDegree2 > static void _SetParentOverlapBounds( const FEMTreeNode* node , int start[Dim] , int end[Dim] );
template< unsigned int FEMDegree1 , unsigned int FEMDegree2 > static void _SetParentOverlapBounds( int cIdx , int start[Dim] , int end[Dim] );
template< unsigned int ... FEMDegrees1 , unsigned int ... FEMDegrees2 > static void _SetParentOverlapBounds( UIntPack< FEMDegrees1 ... > , UIntPack< FEMDegrees2 ... > , const FEMTreeNode* node , int start[Dim] , int end[Dim] )
{
if( node )
{
int d , off[Dim] ; node->depthAndOffset( d , off );
BaseFEMIntegrator::template ParentOverlapBounds( UIntPack< FEMDegrees1 ... >() , UIntPack< FEMDegrees2 ... >() , d , off , start , end );
}
}
template< unsigned int ... FEMDegrees1 , unsigned int ... FEMDegrees2 > static void _SetParentOverlapBounds( UIntPack< FEMDegrees1 ... > , UIntPack< FEMDegrees2 ... > , int cIdx , int start[Dim] , int end[Dim] )
{
BaseFEMIntegrator::template ParentOverlapBounds( UIntPack< FEMDegrees1 ... >() , UIntPack< FEMDegrees2 ... >() , cIdx , start , end );
}
template< unsigned int ... FEMSigs >
int _getProlongedMatrixRowSize( const FEMTreeNode* node , const typename FEMTreeNode::template ConstNeighbors< UIntPack< BSplineOverlapSizes< FEMSignature< FEMSigs >::Degree >::OverlapSize ... > >& pNeighbors ) const;
template< unsigned int ... FEMSigs >
int _getMatrixRowSize( const typename FEMTreeNode::template ConstNeighbors< UIntPack< BSplineOverlapSizes< FEMSignature< FEMSigs >::Degree >::OverlapSize ... > >& neighbors ) const;
template< typename T , unsigned int ... PointDs , unsigned int ... FEMSigs >
T _setMatrixRowAndGetConstraintFromProlongation( UIntPack< FEMSigs ... > , const BaseSystem< UIntPack< FEMSignature< FEMSigs >::Degree ... > >& F , const typename FEMTreeNode::template ConstNeighbors< UIntPack< BSplineOverlapSizes< FEMSignature< FEMSigs >::Degree >::OverlapSize ... > >& pNeighbors , const typename FEMTreeNode::template ConstNeighbors< UIntPack< BSplineOverlapSizes< FEMSignature< FEMSigs >::Degree >::OverlapSize ... > >& neighbors , Pointer( MatrixEntry< Real > ) row , int offset , const PCStencils< UIntPack< FEMSignature< FEMSigs >::Degree ... > >& pcStencils , const CCStencil< UIntPack< FEMSignature< FEMSigs >::Degree ... > >& ccStencil , const PointEvaluator< UIntPack< FEMSigs ... > , UIntPack< FEMSignature< FEMSigs >::Degree ... > >& bsData , ConstPointer( T ) prolongedSolution , const InterpolationInfo< T , PointDs >* ... interpolationInfo ) const;
template< typename T , unsigned int ... PointDs , unsigned int ... FEMSigs >
int _setProlongedMatrixRow( const typename BaseFEMIntegrator::System< UIntPack< FEMSignature< FEMSigs >::Degree ... > >& F , const typename FEMTreeNode::template ConstNeighbors< UIntPack< BSplineOverlapSizes< FEMSignature< FEMSigs >::Degree >::OverlapSize ... > >& neighbors , const typename FEMTreeNode::template ConstNeighbors< UIntPack< BSplineOverlapSizes< FEMSignature< FEMSigs >::Degree >::OverlapSize ... > >& pNeighbors , Pointer( MatrixEntry< Real > ) row , int offset , const DynamicWindow< double , UIntPack< BSplineOverlapSizes< FEMSignature< FEMSigs >::Degree >::OverlapSize ... > >& stencil , const PointEvaluator< UIntPack< FEMSigs ... > , UIntPack< FEMSignature< FEMSigs >::Degree ... > >& bsData , const InterpolationInfo< T , PointDs >* ... interpolationInfo ) const;
// Updates the constraints @(depth) based on the solution coefficients @(depth-1)
template< unsigned int ... FEMSigs , typename T , unsigned int ... PointDs >
T _getConstraintFromProlongedSolution( UIntPack< FEMSigs ... > , const BaseSystem< UIntPack< FEMSignature< FEMSigs >::Degree ... > >& F , const typename FEMTreeNode::template ConstNeighbors< UIntPack< BSplineOverlapSizes< FEMSignature< FEMSigs >::Degree >::OverlapSize ... > >& neighbors , const typename FEMTreeNode::template ConstNeighbors< UIntPack< BSplineOverlapSizes< FEMSignature< FEMSigs >::Degree >::OverlapSize ... > >& pNeighbors , const FEMTreeNode* node , ConstPointer( T ) prolongedSolution , const DynamicWindow< double , UIntPack< BSplineOverlapSizes< FEMSignature< FEMSigs >::Degree >::OverlapSize ... > >& stencil , const PointEvaluator< UIntPack< FEMSigs ... > , UIntPack< FEMSignature< FEMSigs >::Degree ... > >& bsData , const InterpolationInfo< T , PointDs >* ... interpolationInfo ) const;
template< unsigned int ... FEMSigs , typename T , typename TDotT , typename SORWeights , unsigned int ... PointDs >
int _solveFullSystemGS( UIntPack< FEMSigs ... > , const typename BaseFEMIntegrator::System< UIntPack< FEMSignature< FEMSigs >::Degree ... > >& F , const PointEvaluator< UIntPack< FEMSigs ... > , UIntPack< FEMSignature< FEMSigs >::Degree ... > >& bsData , LocalDepth depth , Pointer( T ) solution , ConstPointer( T ) prolongedSolution , ConstPointer( T ) constraints , TDotT Dot , int iters , bool coarseToFine , SORWeights sorWeights , _SolverStats& stats , bool computeNorms , const InterpolationInfo< T , PointDs >* ... interpolationInfo ) const;
template< unsigned int ... FEMSigs , typename T , typename TDotT , typename SORWeights , unsigned int ... PointDs >
int _solveSlicedSystemGS( UIntPack< FEMSigs ... > , const typename BaseFEMIntegrator::System< UIntPack< FEMSignature< FEMSigs >::Degree ... > >& F , const PointEvaluator< UIntPack< FEMSigs ... > , UIntPack< FEMSignature< FEMSigs >::Degree ... > >& bsData , LocalDepth depth , Pointer( T ) solution , ConstPointer( T ) prolongedSolution , ConstPointer( T ) constraints , TDotT Dot , int iters , bool coarseToFine , unsigned int sliceBlockSize , SORWeights sorWeights , _SolverStats& stats , bool computeNorms , const InterpolationInfo< T , PointDs >* ... interpolationInfo ) const;
template< unsigned int ... FEMSigs , typename T , typename TDotT , typename SORWeights , unsigned int ... PointDs >
int _solveSystemGS( UIntPack< FEMSigs ... > , bool sliced , const typename BaseFEMIntegrator::System< UIntPack< FEMSignature< FEMSigs >::Degree ... > >& F , const PointEvaluator< UIntPack< FEMSigs ... > , UIntPack< FEMSignature< FEMSigs >::Degree ... > >& bsData , LocalDepth depth , Pointer( T ) solution , ConstPointer( T ) prolongedSolution , ConstPointer( T ) constraints , TDotT Dot , int iters , bool coarseToFine , unsigned int sliceBlockSize , SORWeights sorWeights , _SolverStats& stats , bool computeNorms , const InterpolationInfo< T , PointDs >* ... interpolationInfo ) const
{
if( sliced ) return _solveSlicedSystemGS( UIntPack< FEMSigs ... >() , F , bsData , depth , solution , prolongedSolution , constraints , Dot , iters , coarseToFine , sliceBlockSize , sorWeights , stats , computeNorms , interpolationInfo ... );
else return _solveFullSystemGS ( UIntPack< FEMSigs ... >() , F , bsData , depth , solution , prolongedSolution , constraints , Dot , iters , coarseToFine , sorWeights , stats , computeNorms , interpolationInfo ... );
}
template< unsigned int ... FEMSigs , typename T , typename TDotT , unsigned int ... PointDs >
int _solveSystemCG( UIntPack< FEMSigs ... > , const typename BaseFEMIntegrator::System< UIntPack< FEMSignature< FEMSigs >::Degree ... > >& F , const PointEvaluator< UIntPack< FEMSigs ... > , UIntPack< FEMSignature< FEMSigs >::Degree ... > >& bsData , LocalDepth depth , Pointer( T ) solution , ConstPointer( T ) prolongedSolution , ConstPointer( T ) constraints , TDotT Dot , int iters , bool coarseToFine , _SolverStats& stats , bool computeNorms , double cgAccuracy , const InterpolationInfo< T , PointDs >* ... interpolationInfo ) const;
template< unsigned int ... FEMSigs , typename T , typename TDotT , unsigned int ... PointDs >
void _solveRegularMG( UIntPack< FEMSigs ... > , typename BaseFEMIntegrator::System< UIntPack< FEMSignature< FEMSigs >::Degree ... > >& F , const PointEvaluator< UIntPack< FEMSigs ... > , UIntPack< FEMSignature< FEMSigs >::Degree ... > >& bsData , LocalDepth depth , Pointer( T ) solution , ConstPointer( T ) constraints , TDotT Dot , int vCycles , int iters , _SolverStats& stats , bool computeNorms , double cgAccuracy , const InterpolationInfo< T , PointDs >* ... interpolationInfo ) const;
// Updates the cumulative integral constraints @(depth-1) based on the change in solution coefficients @(depth)
template< unsigned int ... FEMSigs , typename T >
void _updateRestrictedIntegralConstraints( UIntPack< FEMSigs ... > , const typename BaseFEMIntegrator::System< UIntPack< FEMSignature< FEMSigs >::Degree ... > >& F , LocalDepth highDepth , ConstPointer( T ) solution , Pointer( T ) cumulativeConstraints ) const;
template< unsigned int PointD , typename T , unsigned int ... FEMSigs >
CumulativeDerivativeValues< T , Dim , PointD > _coarserFunctionValues( UIntPack< FEMSigs ... > , Point< Real , Dim > p , const ConstPointSupportKey< UIntPack< FEMSignature< FEMSigs >::Degree ... > >& neighborKey , const FEMTreeNode* node , const PointEvaluator< UIntPack< FEMSigs ... > , UIntPack< FEMSignature< FEMSigs >::Degree ... > >& bsData , ConstPointer( T ) coefficients ) const;
template< unsigned int PointD , typename T , unsigned int ... FEMSigs >
CumulativeDerivativeValues< T , Dim , PointD > _finerFunctionValues( UIntPack< FEMSigs ... > , Point< Real , Dim > p , const ConstPointSupportKey< UIntPack< FEMSignature< FEMSigs >::Degree ... > >& neighborKey , const FEMTreeNode* node , const PointEvaluator< UIntPack< FEMSigs ... > , UIntPack< FEMSignature< FEMSigs >::Degree ... > >& bsData , ConstPointer( T ) coefficients ) const;
template< unsigned int ... FEMSigs , typename T , unsigned int ... PointDs >
int _getSliceMatrixAndProlongationConstraints( UIntPack< FEMSigs ... > , const BaseSystem< UIntPack< FEMSignature< FEMSigs >::Degree ... > >& F , SparseMatrix< Real >& matrix , Pointer( Real ) diagonalR , const PointEvaluator< UIntPack< FEMSigs ... > , UIntPack< FEMSignature< FEMSigs >::Degree ... > >& bsData , LocalDepth depth , int nBegin , int nEnd , ConstPointer( T ) prolongedSolution , Pointer( T ) constraints , const CCStencil < UIntPack< FEMSignature< FEMSigs >::Degree ... > >& ccStencil , const PCStencils< UIntPack< FEMSignature< FEMSigs >::Degree ... > >& pcStencils , const InterpolationInfo< T , PointDs >* ... interpolationInfo ) const;
// Down samples constraints @(depth) to constraints @(depth-1)
template< class C , unsigned ... Degrees , unsigned int ... FEMSigs > void _downSample( UIntPack< FEMSigs ... > , typename BaseFEMIntegrator::template RestrictionProlongation< UIntPack< Degrees ... > >& RP , LocalDepth highDepth , Pointer( C ) constraints ) const;
// Up samples coefficients @(depth-1) to coefficients @(depth)
template< class C , unsigned ... Degrees , unsigned int ... FEMSigs > void _upSample( UIntPack< FEMSigs ... > , typename BaseFEMIntegrator::template RestrictionProlongation< UIntPack< Degrees ... > >& RP , LocalDepth highDepth , Pointer( C ) coefficients ) const;
template< bool XMajor , class C , unsigned int ... FEMSigs > static void _RegularGridUpSample( UIntPack< FEMSigs ... > , LocalDepth highDepth , ConstPointer( C ) lowCoefficients , Pointer( C ) highCoefficients );
template< bool XMajor , class C , unsigned int ... FEMSigs > static void _RegularGridUpSample( UIntPack< FEMSigs ... > , const int lowBegin[] , const int lowEnd[] , const int highBegin[] , const int highEnd[] , LocalDepth highDepth , ConstPointer( C ) lowCoefficients , Pointer( C ) highCoefficients );
public:
template< class C , unsigned int ... FEMSigs > DenseNodeData< C , UIntPack< FEMSigs ... > > coarseCoefficients( const DenseNodeData< C , UIntPack< FEMSigs ... > >& coefficients ) const;
template< class C , unsigned int ... FEMSigs > DenseNodeData< C , UIntPack< FEMSigs ... > > coarseCoefficients( const SparseNodeData< C , UIntPack< FEMSigs ... > >& coefficients ) const;
// For each (valid) fem node, compute the ratio of the sum of active prolongation weights to the sum of total prolongation weights
// If the prolongToChildren flag is set, then these weights are pushed to the children by computing the ratio of the prolongation of the above weights to the prolongation of unity weights
template< unsigned int ... FEMSigs > DenseNodeData< Real , UIntPack< FEMSigs ... > > prolongationWeights( UIntPack< FEMSigs ... > , bool prolongToChildren ) const;
// For each (valid) fem node, compute the integral of the basis function over the valid space nodes over the integral of the basis function
template< unsigned int ... FEMSigs > DenseNodeData< Real , UIntPack< FEMSigs ... > > supportWeights( UIntPack< FEMSigs ... > ) const;
protected:
//////////////////////////////////////////////
// Code for splatting point-sample data //
// MultiGridFEMTreeData.WeightedSamples.inl //
//////////////////////////////////////////////
template< unsigned int WeightDegree >
void _addWeightContribution( DensityEstimator< WeightDegree >& densityWeights , FEMTreeNode* node , Point< Real , Dim > position , PointSupportKey< IsotropicUIntPack< Dim , WeightDegree > >& weightKey , Real weight=Real(1.0) );
template< unsigned int WeightDegree , class PointSupportKey >
Real _getSamplesPerNode( const DensityEstimator< WeightDegree >& densityWeights , const FEMTreeNode* node , Point< Real , Dim > position , PointSupportKey& weightKey ) const;
template< unsigned int WeightDegree , class WeightKey >
void _getSampleDepthAndWeight( const DensityEstimator< WeightDegree >& densityWeights , const FEMTreeNode* node , Point< Real , Dim > position , WeightKey& weightKey , Real& depth , Real& weight ) const;
template< unsigned int WeightDegree , class WeightKey >
void _getSampleDepthAndWeight( const DensityEstimator< WeightDegree >& densityWeights , Point< Real , Dim > position , WeightKey& weightKey , Real& depth , Real& weight ) const;
template< bool CreateNodes , class V , unsigned int ... DataSigs > void _splatPointData( FEMTreeNode* node , Point< Real , Dim > point , V v , SparseNodeData< V , UIntPack< DataSigs ... > >& data , PointSupportKey< UIntPack< FEMSignature< DataSigs >::Degree ... > >& dataKey );
template< bool CreateNodes , unsigned int WeightDegree , class V , unsigned int ... DataSigs > Real _splatPointData( const DensityEstimator< WeightDegree >& densityWeights , Point< Real , Dim > point , V v , SparseNodeData< V , UIntPack< DataSigs ... > >& data , PointSupportKey< IsotropicUIntPack< Dim , WeightDegree > >& weightKey , PointSupportKey< UIntPack< FEMSignature< DataSigs >::Degree ... > >& dataKey , LocalDepth minDepth , LocalDepth maxDepth , int dim , Real depthBias );
template< bool CreateNodes , unsigned int WeightDegree , class V , unsigned int ... DataSigs > Real _multiSplatPointData( const DensityEstimator< WeightDegree >* densityWeights , FEMTreeNode* node , Point< Real , Dim > point , V v , SparseNodeData< V , UIntPack< DataSigs ... > >& data , PointSupportKey< IsotropicUIntPack< Dim , WeightDegree > >& weightKey , PointSupportKey< UIntPack< FEMSignature< DataSigs >::Degree ... > >& dataKey , int dim );
template< unsigned int WeightDegree , class V , unsigned int ... DataSigs > Real _nearestMultiSplatPointData( const DensityEstimator< WeightDegree >* densityWeights , FEMTreeNode* node , Point< Real , Dim > point , V v , SparseNodeData< V , UIntPack< DataSigs ... > >& data , PointSupportKey< IsotropicUIntPack< Dim , WeightDegree > >& weightKey , int dim=Dim );
template< class V , class Coefficients , unsigned int D , unsigned int ... DataSigs > V _evaluate( const Coefficients& coefficients , Point< Real , Dim > p , const PointEvaluator< UIntPack< DataSigs ... > , IsotropicUIntPack< Dim , D > >& pointEvaluator , const ConstPointSupportKey< UIntPack< FEMSignature< DataSigs >::Degree ... > >& dataKey ) const;
public:
template< bool XMajor , class V , unsigned int ... DataSigs > Pointer( V ) regularGridEvaluate( const DenseNodeData< V , UIntPack< DataSigs ... > >& coefficients , int& res , LocalDepth depth=-1 , bool primal=false ) const;
template< bool XMajor , class V , unsigned int ... DataSigs > Pointer( V ) regularGridUpSample( const DenseNodeData< V , UIntPack< DataSigs ... > >& coefficients , LocalDepth depth=-1 ) const;
template< bool XMajor , class V , unsigned int ... DataSigs > Pointer( V ) regularGridUpSample( const DenseNodeData< V , UIntPack< DataSigs ... > >& coefficients , const int begin[Dim] , const int end[Dim] , LocalDepth depth=-1 ) const;
template< class V , unsigned int ... DataSigs > V average( const DenseNodeData< V , UIntPack< DataSigs ... > >& coefficients ) const;
template< class V , unsigned int ... DataSigs > V average( const DenseNodeData< V , UIntPack< DataSigs ... > >& coefficients , const Real begin[Dim] , const Real end[Dim] ) const;
template< typename T > struct HasNormalDataFunctor{};
template< unsigned int ... NormalSigs >
struct HasNormalDataFunctor< UIntPack< NormalSigs ... > >
{
const SparseNodeData< Point< Real , Dim > , UIntPack< NormalSigs ... > >& normalInfo;
HasNormalDataFunctor( const SparseNodeData< Point< Real , Dim > , UIntPack< NormalSigs ... > >& ni ) : normalInfo( ni ){ ; }
bool operator() ( const FEMTreeNode* node ) const
{
const Point< Real , Dim >* n = normalInfo( node );
if( n )
{
const Point< Real , Dim >& normal = *n;
for( int d=0 ; d<Dim ; d++ ) if( normal[d]!=0 ) return true;
}
if( node->children ) for( int c=0 ; c<(1<<Dim) ; c++ ) if( (*this)( node->children + c ) ) return true;
return false;
}
};
struct TrivialHasDataFunctor{ bool operator() ( const FEMTreeNode* node ) const { return true; } };
protected:
// [NOTE] The input/output for this method is pre-scaled by weight
template< typename T > bool _setInterpolationInfoFromChildren( FEMTreeNode* node , SparseNodeData< T , IsotropicUIntPack< Dim , FEMTrivialSignature > >& iInfo ) const;
template< typename T , unsigned int PointD , typename ConstraintDual > SparseNodeData< DualPointInfo < Dim , Real , T , PointD > , IsotropicUIntPack< Dim , FEMTrivialSignature > > _densifyInterpolationInfoAndSetDualConstraints( const std::vector< PointSample >& samples , ConstraintDual constraintDual , int adaptiveExponent ) const;
template< typename T , typename Data , unsigned int PointD , typename ConstraintDual > SparseNodeData< DualPointAndDataInfo< Dim , Real , Data , T , PointD > , IsotropicUIntPack< Dim , FEMTrivialSignature > > _densifyInterpolationInfoAndSetDualConstraints( const std::vector< PointSample >& samples , ConstPointer( Data ) sampleData , ConstraintDual constraintDual , int adaptiveExponent ) const;
template< typename T , unsigned int PointD , typename ConstraintDual > SparseNodeData< DualPointInfoBrood < Dim , Real , T , PointD > , IsotropicUIntPack< Dim , FEMTrivialSignature > > _densifyChildInterpolationInfoAndSetDualConstraints( const std::vector< PointSample >& samples , ConstraintDual constraintDual , bool noRescale ) const;
template< typename T , typename Data , unsigned int PointD , typename ConstraintDual > SparseNodeData< DualPointAndDataInfoBrood< Dim , Real , Data , T , PointD > , IsotropicUIntPack< Dim , FEMTrivialSignature > > _densifyChildInterpolationInfoAndSetDualConstraints( const std::vector< PointSample >& samples , ConstPointer( Data ) sampleData , ConstraintDual constraintDual , bool noRescale ) const;
void _setSpaceValidityFlags( void ) const;
template< unsigned int ... FEMSigs1 > void _setFEM1ValidityFlags( UIntPack< FEMSigs1 ... > ) const;
template< unsigned int ... FEMSigs2 > void _setFEM2ValidityFlags( UIntPack< FEMSigs2 ... > ) const;
template< unsigned int ... FEMSigs > void _setRefinabilityFlags( UIntPack< FEMSigs ... > ) const;
template< class HasDataFunctor > void _clipTree( const HasDataFunctor& f , LocalDepth fullDepth );
public:
template< unsigned int PointD , unsigned int ... FEMSigs > SparseNodeData< CumulativeDerivativeValues< Real , Dim , PointD > , IsotropicUIntPack< Dim , FEMTrivialSignature > > leafValues( const DenseNodeData< Real , UIntPack< FEMSigs ... > >& coefficients , int maxDepth=-1 ) const;
protected:
/////////////////////////////////////
// Evaluation Methods //
// MultiGridFEMTreeData.Evaluation //
/////////////////////////////////////
static const unsigned int CHILDREN = 1<<Dim;
template< typename Pack , unsigned int PointD > struct _Evaluator{ };
template< unsigned int ... FEMSigs , unsigned int PointD >
struct _Evaluator< UIntPack< FEMSigs ... > , PointD >
{
static_assert( Dim == sizeof...(FEMSigs) , "[ERROR] Number of signatures doesn't match dimension" );
typedef DynamicWindow< CumulativeDerivativeValues< double , Dim , PointD > , UIntPack< BSplineSupportSizes< FEMSignature< FEMSigs >::Degree >::SupportSize ... > > CenterStencil;
typedef DynamicWindow< CumulativeDerivativeValues< double , Dim , PointD > , UIntPack< BSplineSupportSizes< FEMSignature< FEMSigs >::Degree >::SupportSize ... > > CornerStencil;
typedef DynamicWindow< CumulativeDerivativeValues< double , Dim , PointD > , UIntPack< ( BSplineSupportSizes< FEMSignature< FEMSigs >::Degree >::BCornerSize + 1 ) ... > > BCornerStencil;
typedef std::tuple< typename BSplineEvaluationData< FEMSigs >::template Evaluator< PointD > ... > Evaluators;
typedef std::tuple< typename BSplineEvaluationData< FEMSigs >::template ChildEvaluator< PointD > ... > ChildEvaluators;
struct StencilData
{
CenterStencil ccCenterStencil , pcCenterStencils[CHILDREN];
CornerStencil ccCornerStencil[CHILDREN] , pcCornerStencils[CHILDREN][CHILDREN];
BCornerStencil ccBCornerStencil[CHILDREN] , pcBCornerStencils[CHILDREN][CHILDREN];
};
Pointer( StencilData ) stencilData;
Pointer( Evaluators ) evaluators;
Pointer( ChildEvaluators ) childEvaluators;
void set( LocalDepth depth );
_Evaluator( void ){ _pointEvaluator = NULL ; stencilData = NullPointer( StencilData ) , evaluators = NullPointer( Evaluators ) , childEvaluators = NullPointer( ChildEvaluators ); }
~_Evaluator( void ){ if( _pointEvaluator ) delete _pointEvaluator , _pointEvaluator = NULL ; if( stencilData ) DeletePointer( stencilData ) ; if( evaluators ) DeletePointer( evaluators ) ; if( childEvaluators ) DeletePointer( childEvaluators ); }
protected:
enum _CenterOffset{ CENTER=-1 , BACK=0 , FRONT=1 };
template< unsigned int _PointD=PointD > CumulativeDerivativeValues< double , Dim , _PointD > _values( unsigned int d , const int fIdx[Dim] , const int idx[Dim] , const _CenterOffset off[Dim] , bool parentChild ) const;
template< unsigned int _PointD=PointD > CumulativeDerivativeValues< double , Dim , _PointD > _centerValues( unsigned int d , const int fIdx[Dim] , const int idx[Dim] , bool parentChild ) const;
template< unsigned int _PointD=PointD > CumulativeDerivativeValues< double , Dim , _PointD > _cornerValues( unsigned int d , const int fIdx[Dim] , const int idx[Dim] , int corner , bool parentChild ) const;
template< unsigned int _PointD=PointD , unsigned int I=0 > typename std::enable_if< I==Dim >::type _setDValues( unsigned int d , const int fIdx[] , const int cIdx[] , const _CenterOffset off[] , bool pc , double dValues[][_PointD+1] ) const{ }
template< unsigned int _PointD=PointD , unsigned int I=0 > typename std::enable_if< I< Dim >::type _setDValues( unsigned int d , const int fIdx[] , const int cIdx[] , const _CenterOffset off[] , bool pc , double dValues[][_PointD+1] ) const
{
if( pc ) for( int dd=0 ; dd<=_PointD ; dd++ ) dValues[I][dd] = off[I]==CENTER ? std::get< I >( childEvaluators[d] ).centerValue( fIdx[I] , cIdx[I] , dd ) : std::get< I >( childEvaluators[d] ).cornerValue( fIdx[I] , cIdx[I]+off[I] , dd );
else for( int dd=0 ; dd<=_PointD ; dd++ ) dValues[I][dd] = off[I]==CENTER ? std::get< I >( evaluators[d] ).centerValue( fIdx[I] , cIdx[I] , dd ) : std::get< I >( evaluators[d] ).cornerValue( fIdx[I] , cIdx[I]+off[I] , dd );
_setDValues< _PointD , I+1 >( d , fIdx , cIdx , off , pc , dValues );
}
template< unsigned int I=0 > typename std::enable_if< I==Dim >::type _setEvaluators( unsigned int maxDepth ){ }
template< unsigned int I=0 > typename std::enable_if< I< Dim >::type _setEvaluators( unsigned int maxDepth )
{
static const unsigned int FEMSig = UIntPack< FEMSigs ... >::template Get< I >();
for( unsigned int d=0 ; d<=maxDepth ; d++ ) BSplineEvaluationData< FEMSig >:: SetEvaluator( std::template get< I >( evaluators[d] ) , d );
for( unsigned int d=1 ; d<=maxDepth ; d++ ) BSplineEvaluationData< FEMSig >::SetChildEvaluator( std::template get< I >( childEvaluators[d] ) , d-1 );
_setEvaluators< I+1 >( maxDepth );
}
typename FEMIntegrator::template PointEvaluator< UIntPack< FEMSigs ... > , IsotropicUIntPack< Dim , PointD > >* _pointEvaluator;
friend FEMTree;
};
template< class V , unsigned int _PointD , unsigned int ... FEMSigs , unsigned int PointD >
CumulativeDerivativeValues< V , Dim , _PointD > _getCenterValues( const ConstPointSupportKey< UIntPack< FEMSignature< FEMSigs >::Degree ... > >& neighborKey , const FEMTreeNode* node , ConstPointer( V ) solution , ConstPointer( V ) coarseSolution , const _Evaluator< UIntPack< FEMSigs ... > , PointD >& evaluator , int maxDepth , bool isInterior ) const;
template< class V , unsigned int _PointD , unsigned int ... FEMSigs , unsigned int PointD >
CumulativeDerivativeValues< V , Dim , _PointD > _getCornerValues( const ConstPointSupportKey< UIntPack< FEMSignature< FEMSigs >::Degree ... > >& neighborKey , const FEMTreeNode* node , int corner , ConstPointer( V ) solution , ConstPointer( V ) coarseSolution , const _Evaluator< UIntPack< FEMSigs ... > , PointD >& evaluator , int maxDepth , bool isInterior ) const;
template< class V , unsigned int _PointD , unsigned int ... FEMSigs , unsigned int PointD >
CumulativeDerivativeValues< V , Dim , _PointD > _getValues ( const ConstPointSupportKey< UIntPack< FEMSignature< FEMSigs >::Degree ... > >& neighborKey , const FEMTreeNode* node , Point< Real , Dim > p , ConstPointer( V ) solution , ConstPointer( V ) coarseSolution , const _Evaluator< UIntPack< FEMSigs ... > , PointD >& evaluator , int maxDepth ) const;
template< class V , unsigned int _PointD , unsigned int ... FEMSigs , unsigned int PointD >
CumulativeDerivativeValues< V , Dim , _PointD > _getCornerValues( const ConstCornerSupportKey< UIntPack< FEMSignature< FEMSigs >::Degree ... > >& neighborKey , const FEMTreeNode* node , int corner , ConstPointer( V ) solution , ConstPointer( V ) coarseSolution , const _Evaluator< UIntPack< FEMSigs ... > , PointD >& evaluator , int maxDepth , bool isInterior ) const;
template< unsigned int ... SupportSizes >
struct CornerLoopData
{
typedef UIntPack< SupportSizes ... > _SupportSizes;
// static const unsigned int supportSizes[] = { SupportSizes ... };
static const unsigned int supportSizes[];
unsigned int ccSize[1<<Dim] , pcSize[1<<Dim][1<<Dim];
unsigned int ccIndices[1<<Dim] [ WindowSize< _SupportSizes >::Size ];
unsigned int pcIndices[1<<Dim][1<<Dim][ WindowSize< _SupportSizes >::Size ];
CornerLoopData( void )
{
int start[Dim] , end[Dim] , _start[Dim] , _end[Dim];
for( int c=0 ; c<(1<<Dim) ; c++ )
{
ccSize[c] = 0;
for( int dd=0 ; dd<Dim ; dd++ )
{
start[dd] = 0 , end[dd] = supportSizes[dd];
if( (c>>dd) & 1 ) start[dd]++;
else end [dd]--;
}
unsigned int idx[Dim];
WindowLoop< Dim >::Run
(
start , end ,
[&]( int d , int i ){ idx[d] = i; } ,
[&]( void ){ ccIndices[c][ ccSize[c]++ ] = GetWindowIndex( _SupportSizes() , idx ); }
);
for( int _c=0 ; _c<(1<<Dim) ; _c++ )
{
pcSize[c][_c] = 0;
for( int dd=0 ; dd<Dim ; dd++ )
{
if( ( (_c>>dd) & 1 ) != ( (c>>dd) & 1 ) ) _start[dd] = 0 , _end[dd] = supportSizes[dd];
else _start[dd] = start[dd] , _end[dd] = end[dd];
}
unsigned int idx[Dim];
WindowLoop< Dim >::Run
(
_start , _end ,
[&]( int d , int i ){ idx[d] = i; } ,
[&]( void ){ pcIndices[c][_c][ pcSize[c][_c]++ ] = GetWindowIndex( _SupportSizes() , idx ); }
);
}
}
}
};
public:
template< typename Pack , unsigned int PointD , typename T > struct _MultiThreadedEvaluator{ };
template< unsigned int ... FEMSigs , unsigned int PointD , typename T >
struct _MultiThreadedEvaluator< UIntPack< FEMSigs ... > , PointD , T >
{
typedef UIntPack< FEMSigs ... > FEMSignatures;
typedef UIntPack< FEMSignature< FEMSigs >::Degree ... > FEMDegrees;
const FEMTree* _tree;
int _threads;
std::vector< ConstPointSupportKey< FEMDegrees > > _pointNeighborKeys;
std::vector< ConstCornerSupportKey< FEMDegrees > > _cornerNeighborKeys;
_Evaluator< FEMSignatures , PointD > _evaluator;
const DenseNodeData< T , FEMSignatures >& _coefficients;
DenseNodeData< T , FEMSignatures > _coarseCoefficients;
public:
_MultiThreadedEvaluator( const FEMTree* tree , const DenseNodeData< T , FEMSignatures >& coefficients , int threads=omp_get_max_threads() );
template< unsigned int _PointD=PointD > CumulativeDerivativeValues< T , Dim , _PointD > values( Point< Real , Dim > p , int thread=0 , const FEMTreeNode* node=NULL );
template< unsigned int _PointD=PointD > CumulativeDerivativeValues< T , Dim , _PointD > centerValues( const FEMTreeNode* node , int thread=0 );
template< unsigned int _PointD=PointD > CumulativeDerivativeValues< T , Dim , _PointD > cornerValues( const FEMTreeNode* node , int corner , int thread=0 );
};
template< typename Pack , unsigned int PointD , typename T=Real > using MultiThreadedEvaluator = _MultiThreadedEvaluator< Pack , PointD , T >;
template< unsigned int DensityDegree >
struct MultiThreadedWeightEvaluator
{
const FEMTree* _tree;
int _threads;
std::vector< ConstPointSupportKey< IsotropicUIntPack< Dim , DensityDegree > > > _neighborKeys;
const DensityEstimator< DensityDegree >& _density;
public:
MultiThreadedWeightEvaluator( const FEMTree* tree , const DensityEstimator< DensityDegree >& density , int threads=omp_get_max_threads() );
Real weight( Point< Real , Dim > p , int thread=0 );
};
static double _MaxMemoryUsage , _LocalMemoryUsage;
void _reorderDenseOrSparseNodeData( const int* , size_t ){ ; }
template< class Data , unsigned int ... FEMSigs , class ... DenseOrSparseNodeData >
void _reorderDenseOrSparseNodeData( const int* map , size_t sz , SparseNodeData< Data , UIntPack< FEMSigs ... > >* sData , DenseOrSparseNodeData* ... data )
{
if( sData ) sData->_remapIndices( map , (int)sz );
_reorderDenseOrSparseNodeData( map , sz , data ... );
}
template< class Data , unsigned int ... FEMSigs , class ... DenseOrSparseNodeData >
void _reorderDenseOrSparseNodeData( const int* map , size_t sz , DenseNodeData< Data , UIntPack< FEMSigs ... > >* dData , DenseOrSparseNodeData* ... data )
{
if( dData ) dData->_remapIndices( map , sz );
_reorderDenseOrSparseNodeData( map , sz , data ... );
}
public:
static double MaxMemoryUsage( void ){ return _MaxMemoryUsage; }
static double LocalMemoryUsage( void ){ return _LocalMemoryUsage; }
static void ResetLocalMemoryUsage( void ){ _LocalMemoryUsage = 0; }
static double MemoryUsage( void );
FEMTree( int blockSize );
FEMTree( FILE* fp , int blockSize );
~FEMTree( void )
{
if( _tree ) for( int c=0 ; c<(1<<Dim) ; c++ ) _tree[c].cleanChildren( nodeAllocator );
if( nodeAllocator ) delete nodeAllocator;
}
void write( FILE* fp ) const;
static void WriteParameter( FILE* fp )
{
FEMTreeRealType realType;
if ( typeid( Real )==typeid( float ) ) realType=FEM_TREE_REAL_FLOAT;
else if( typeid( Real )==typeid( double ) ) realType=FEM_TREE_REAL_DOUBLE;
else fprintf( stderr , "[ERROR] FEMTree::WriteParameter: Unrecognized real type\n" ) , exit( 0 );
fwrite( &realType , sizeof(FEMTreeRealType) , 1 , fp );
int dim = Dim;
fwrite( &dim , sizeof(int) , 1 , fp );
}
template< unsigned int LeftRadius , unsigned int RightRadius , class ... DenseOrSparseNodeData > void thicken( FEMTreeNode** nodes , size_t nodeCount , DenseOrSparseNodeData* ... data );
template< unsigned int LeftRadius , unsigned int RightRadius , class IsThickenNode , class ... DenseOrSparseNodeData > void thicken( IsThickenNode F , DenseOrSparseNodeData* ... data );
template< unsigned int Radius , class ... DenseOrSparseNodeData > void thicken( FEMTreeNode** nodes , size_t nodeCount , DenseOrSparseNodeData* ... data ){ thicken< Radius , Radius >( nodes , nodeCount , data ... ); }
template< unsigned int Radius , class IsThickenNode , class ... DenseOrSparseNodeData > void thicken( IsThickenNode F , DenseOrSparseNodeData* ... data ){ thicken< Radius , Radius >( F , data ... ); }
template< unsigned int DensityDegree >
typename FEMTree::template DensityEstimator< DensityDegree >* setDensityEstimator( const std::vector< PointSample >& samples , LocalDepth splatDepth , Real samplesPerNode , int coDimension );
template< unsigned int ... NormalSigs , unsigned int DensityDegree , class Data >
#if defined(_WIN32) || defined(_WIN64)
SparseNodeData< Point< Real , Dim > , UIntPack< NormalSigs ... > > setNormalField( UIntPack< NormalSigs ... > , const std::vector< PointSample >& samples , const std::vector< Data >& normalData , const DensityEstimator< DensityDegree >* density , Real& pointWeightSum , std::function< Real ( Real ) > BiasFunction = []( Real ){ return 0.f; } );
#else // !_WIN32 && !_WIN64
SparseNodeData< Point< Real , Dim > , UIntPack< NormalSigs ... > > setNormalField( UIntPack< NormalSigs ... > , const std::vector< PointSample >& samples , const std::vector< Data >& normalData , const DensityEstimator< DensityDegree >* density , Real& pointWeightSum , std::function< Real ( Real ) > BiasFunction = []( Real ){ return (Real)0; } );
#endif // _WIN32 || _WIN64
template< unsigned int DataSig , bool CreateNodes , unsigned int DensityDegree , class Data >
SparseNodeData< Data , IsotropicUIntPack< Dim , DataSig > > setSingleDepthDataField( const std::vector< PointSample >& samples , const std::vector< Data >& sampleData , const DensityEstimator< DensityDegree >* density );
template< unsigned int DataSig , bool CreateNodes , unsigned int DensityDegree , class Data >
SparseNodeData< ProjectiveData< Data , Real > , IsotropicUIntPack< Dim , DataSig > > setDataField( const std::vector< PointSample >& samples , std::vector< Data >& sampleData , const DensityEstimator< DensityDegree >* density , bool nearest=false );
template< unsigned int MaxDegree , class HasDataFunctor , class ... DenseOrSparseNodeData > void finalizeForMultigrid( LocalDepth fullDepth , const HasDataFunctor F , DenseOrSparseNodeData* ... data );
template< unsigned int ... FEMSigs > DenseNodeData< Real , UIntPack< FEMSigs ... > > initDenseNodeData( UIntPack< FEMSigs ... > ) const;
template< class Data , unsigned int ... FEMSigs > DenseNodeData< Data , UIntPack< FEMSigs ... > > initDenseNodeData( UIntPack< FEMSigs ... > ) const;
// Add multiple-dimensions -> one-dimension constraints
template< typename T , unsigned int ... FEMDegrees , unsigned int ... FEMSigs , unsigned int ... CDegrees , unsigned int ... CSigs , unsigned int CDim >
void addFEMConstraints( typename BaseFEMIntegrator::template Constraint< UIntPack< FEMDegrees ... > , UIntPack< CDegrees ... > , CDim >& F , const _SparseOrDenseNodeData< Point< T , CDim > , UIntPack< CSigs ... > >& coefficients , DenseNodeData< T , UIntPack< FEMSigs ... > >& constraints , LocalDepth maxDepth ) const
{
typedef SparseNodeData< Point< T , CDim > , UIntPack< CSigs ... > > SparseType;
typedef DenseNodeData< Point< T , CDim > , UIntPack< CSigs ... > > DenseType;
static_assert( sizeof...( FEMDegrees )==Dim && sizeof...( FEMSigs )==Dim && sizeof...( CDegrees )==Dim && sizeof...( CSigs )==Dim , "[ERROR] Dimensions don't match" );
static_assert( UIntPack< FEMDegrees ... >::template Compare< UIntPack< FEMSignature< FEMSigs >::Degree ... > >::Equal , "[ERROR] FEM signature and degrees don't match" );
static_assert( UIntPack< CDegrees ... >::template Compare< UIntPack< FEMSignature< CSigs >::Degree ... > >::Equal , "[ERROR] Constraint signature and degrees don't match" );
if ( typeid(coefficients)==typeid(SparseType) ) return _addFEMConstraints< T >( UIntPack< FEMSigs ... >() , UIntPack< CSigs ... >() , F , static_cast< const SparseType& >( coefficients ) , constraints() , maxDepth );
else if( typeid(coefficients)==typeid( DenseType) ) return _addFEMConstraints< T >( UIntPack< FEMSigs ... >() , UIntPack< CSigs ... >() , F , static_cast< const DenseType& >( coefficients ) , constraints() , maxDepth );
else return _addFEMConstraints< T >( UIntPack< FEMSigs ... >() , UIntPack< CSigs ... >() , F , coefficients , constraints() , maxDepth );
}
// Add one-dimensions -> one-dimension constraints (with distinct signatures)
template< typename T , unsigned int ... FEMDegrees , unsigned int ... FEMSigs , unsigned int ... CDegrees , unsigned int ... CSigs >
void addFEMConstraints( typename BaseFEMIntegrator::template Constraint< UIntPack< FEMDegrees ... > , UIntPack< CDegrees ... > , 1 >& F , const _SparseOrDenseNodeData< T , UIntPack< CSigs ... > >& coefficients , DenseNodeData< T , UIntPack< FEMSigs ... > >& constraints , LocalDepth maxDepth ) const
{
typedef SparseNodeData< T , UIntPack< CSigs ... > > SparseType;
typedef DenseNodeData< T , UIntPack< CSigs ... > > DenseType;
static_assert( sizeof...( FEMDegrees )==Dim && sizeof...( FEMSigs )==Dim && sizeof...( CDegrees )==Dim && sizeof...( CSigs )==Dim , "[ERROR] Dimensions don't match" );
static_assert( UIntPack< FEMDegrees ... >::template Compare< UIntPack< FEMSignature< FEMSigs >::Degree ... > >::Equal , "[ERROR] FEM signature and degrees don't match" );
static_assert( UIntPack< CDegrees ... >::template Compare< UIntPack< FEMSignature< CSigs >::Degree ... > >::Equal , "[ERROR] Constaint signature and degrees don't match" );
if ( typeid(coefficients)==typeid(SparseType) ) return _addFEMConstraints< T >( UIntPack< FEMSigs ... >() , UIntPack< CSigs ... >() , F , static_cast< const SparseType& >( coefficients ) , constraints() , maxDepth );
else if( typeid(coefficients)==typeid( DenseType) ) return _addFEMConstraints< T >( UIntPack< FEMSigs ... >() , UIntPack< CSigs ... >() , F , static_cast< const DenseType& >( coefficients ) , constraints() , maxDepth );
else return _addFEMConstraints< T >( UIntPack< FEMSigs ... >() , UIntPack< CSigs ... >() , F , coefficients , constraints() , maxDepth );
}
// Add one-dimensions -> one-dimension constraints (with the same signatures)
template< typename T , unsigned int ... FEMDegrees , unsigned int ... FEMSigs >
// void addFEMConstraints( typename BaseFEMIntegrator::template System< UIntPack< FEMDegrees ... > >& F , const SparseNodeData< T , UIntPack< FEMSigs ... > >& coefficients , _SparseOrDenseNodeData< T , UIntPack< FEMSigs ... > >& constraints , LocalDepth maxDepth ) const
void addFEMConstraints( typename BaseFEMIntegrator::template System< UIntPack< FEMDegrees ... > >& F , const _SparseOrDenseNodeData< T , UIntPack< FEMSigs ... > >& coefficients , DenseNodeData< T , UIntPack< FEMSigs ... > >& constraints , LocalDepth maxDepth ) const
{
typedef SparseNodeData< T , UIntPack< FEMSigs ... > > SparseType;
typedef DenseNodeData< T , UIntPack< FEMSigs ... > > DenseType;
static_assert( sizeof...( FEMDegrees )==Dim && sizeof...( FEMSigs )==Dim , "[ERROR] Dimensions don't match" );
static_assert( UIntPack< FEMDegrees ... >::template Compare< UIntPack< FEMSignature< FEMSigs >::Degree ... > >::Equal , "[ERROR] FEM signatures and degrees don't match" );
typename BaseFEMIntegrator::template SystemConstraint< UIntPack< FEMDegrees ... > > _F( F );
if ( typeid(coefficients)==typeid(SparseType) ) return _addFEMConstraints< T >( UIntPack< FEMSigs ... >() , UIntPack< FEMSigs ... >() , _F , static_cast< const SparseType& >( coefficients ) , constraints() , maxDepth );
else if( typeid(coefficients)==typeid( DenseType) ) return _addFEMConstraints< T >( UIntPack< FEMSigs ... >() , UIntPack< FEMSigs ... >() , _F , static_cast< const DenseType& >( coefficients ) , constraints() , maxDepth );
else return _addFEMConstraints< T >( UIntPack< FEMSigs ... >() , UIntPack< FEMSigs ... >() , _F , coefficients , constraints() , maxDepth );
}
// Add interpolation constraints
template< typename T , unsigned int ... FEMSigs , unsigned int PointD , unsigned int ... PointDs >
typename std::enable_if< (sizeof...(PointDs)!=0) >::type addInterpolationConstraints( DenseNodeData< T , UIntPack< FEMSigs ... > >& constraints , LocalDepth maxDepth , const InterpolationInfo< T , PointD >& iInfo , const InterpolationInfo< T , PointDs >& ... iInfos ) const
{
addInterpolationConstraints< T , FEMSigs ... >( constraints , maxDepth , iInfo );
addInterpolationConstraints< T , FEMSigs ... >( constraints , maxDepth , iInfos ... );
}
template< typename T , unsigned int ... FEMSigs , unsigned int PointD > void addInterpolationConstraints( DenseNodeData< T , UIntPack< FEMSigs ... > >& constraints , LocalDepth maxDepth , const InterpolationInfo< T , PointD >& interpolationInfo ) const;
// Real
template< unsigned int ... FEMDegrees1 , unsigned int ... FEMSigs1 , unsigned int ... FEMDegrees2 , unsigned int ... FEMSigs2 >
double dot( typename BaseFEMIntegrator::Constraint< UIntPack< FEMDegrees1 ... > , UIntPack< FEMDegrees2 ... > , 1 >& F , const _SparseOrDenseNodeData< Real , UIntPack< FEMSigs1 ... > >& coefficients1 , const _SparseOrDenseNodeData< Real , UIntPack< FEMSigs2 ... > >& coefficients2 ) const
{
typedef SparseNodeData< Real , UIntPack< FEMSigs1 ... > > SparseType1;
typedef DenseNodeData< Real , UIntPack< FEMSigs1 ... > > DenseType1;
typedef SparseNodeData< Real , UIntPack< FEMSigs2 ... > > SparseType2;
typedef DenseNodeData< Real , UIntPack< FEMSigs2 ... > > DenseType2;
static_assert( sizeof...( FEMDegrees1 )==Dim && sizeof...( FEMSigs1 )==Dim && sizeof...( FEMDegrees2 )==Dim && sizeof...( FEMSigs2 )==Dim , "[ERROR] Dimensions don't match" );
static_assert( UIntPack< FEMDegrees1 ... >::template Compare< UIntPack< FEMSignature< FEMSigs1 >::Degree ... > >::Equal , "[ERROR] FEM signature and degrees don't match" );
static_assert( UIntPack< FEMDegrees2 ... >::template Compare< UIntPack< FEMSignature< FEMSigs2 >::Degree ... > >::Equal , "[ERROR] FEM signature and degrees don't match" );
if ( typeid(coefficients1)==typeid(SparseType1) && typeid(coefficients2)==typeid(SparseType2) ) return _dot< Real >( UIntPack< FEMSigs1 ... >() , UIntPack< FEMSigs2 ... >() , F , static_cast< const SparseType1& >( coefficients1 ) , static_cast< const SparseType2& >( coefficients2 ) , []( Real v , Real w ){ return v*w; } );
else if( typeid(coefficients1)==typeid(SparseType1) && typeid(coefficients2)==typeid( DenseType2) ) return _dot< Real >( UIntPack< FEMSigs1 ... >() , UIntPack< FEMSigs2 ... >() , F , static_cast< const SparseType1& >( coefficients1 ) , static_cast< const DenseType2& >( coefficients2 ) , []( Real v , Real w ){ return v*w; } );
else if( typeid(coefficients1)==typeid( DenseType1) && typeid(coefficients2)==typeid( DenseType2) ) return _dot< Real >( UIntPack< FEMSigs1 ... >() , UIntPack< FEMSigs2 ... >() , F , static_cast< const DenseType1& >( coefficients1 ) , static_cast< const DenseType2& >( coefficients2 ) , []( Real v , Real w ){ return v*w; } );
else if( typeid(coefficients1)==typeid( DenseType1) && typeid(coefficients2)==typeid(SparseType2) ) return _dot< Real >( UIntPack< FEMSigs1 ... >() , UIntPack< FEMSigs2 ... >() , F , static_cast< const DenseType1& >( coefficients1 ) , static_cast< const SparseType2& >( coefficients2 ) , []( Real v , Real w ){ return v*w; } );
else return _dot< Real >( UIntPack< FEMSigs1 ... >() , UIntPack< FEMSigs2 ... >() , F , coefficients1 , coefficients2 , []( Real v , Real w ){ return v*w; } );
}
template< unsigned int ... FEMDegrees , unsigned int ... FEMSigs >
double dot( typename BaseFEMIntegrator::System< UIntPack< FEMDegrees ... > >& F , const _SparseOrDenseNodeData< Real , UIntPack< FEMSigs ... > >& coefficients1 , const _SparseOrDenseNodeData< Real , UIntPack< FEMSigs ... > >& coefficients2 ) const
{
typedef SparseNodeData< Real , UIntPack< FEMSigs ... > > SparseType;
typedef DenseNodeData< Real , UIntPack< FEMSigs ... > > DenseType;
static_assert( sizeof...( FEMDegrees )==Dim && sizeof...( FEMSigs )==Dim , "[ERROR] Dimensions don't match" );
static_assert( UIntPack< FEMDegrees ... >::template Compare< UIntPack< FEMSignature< FEMSigs >::Degree ... > >::Equal , "[ERROR] FEM signatures and degrees don't match" );
typename BaseFEMIntegrator::template SystemConstraint< UIntPack< FEMDegrees ... > > _F( F );
if ( typeid(coefficients1)==typeid(SparseType) && typeid(coefficients2)==typeid(SparseType) ) return _dot< Real >( UIntPack< FEMSigs ... >() , UIntPack< FEMSigs ... >() , _F , static_cast< const SparseType& >( coefficients1 ) , static_cast< const SparseType& >( coefficients2 ) , []( Real v , Real w ){ return v*w; } );
else if( typeid(coefficients1)==typeid(SparseType) && typeid(coefficients2)==typeid( DenseType) ) return _dot< Real >( UIntPack< FEMSigs ... >() , UIntPack< FEMSigs ... >() , _F , static_cast< const SparseType& >( coefficients1 ) , static_cast< const DenseType& >( coefficients2 ) , []( Real v , Real w ){ return v*w; } );
else if( typeid(coefficients1)==typeid( DenseType) && typeid(coefficients2)==typeid( DenseType) ) return _dot< Real >( UIntPack< FEMSigs ... >() , UIntPack< FEMSigs ... >() , _F , static_cast< const DenseType& >( coefficients1 ) , static_cast< const DenseType& >( coefficients2 ) , []( Real v , Real w ){ return v*w; } );
else if( typeid(coefficients1)==typeid( DenseType) && typeid(coefficients2)==typeid(SparseType) ) return _dot< Real >( UIntPack< FEMSigs ... >() , UIntPack< FEMSigs ... >() , _F , static_cast< const DenseType& >( coefficients1 ) , static_cast< const SparseType& >( coefficients2 ) , []( Real v , Real w ){ return v*w; } );
else return _dot< Real >( UIntPack< FEMSigs ... >() , UIntPack< FEMSigs ... >() , _F , coefficients1 , coefficients2 , []( Real v , Real w ){ return v*w; } );
}
template< unsigned int ... FEMDegrees , unsigned int ... FEMSigs >
double squareNorm( typename BaseFEMIntegrator::template System< UIntPack< FEMDegrees ... > >& F , const _SparseOrDenseNodeData< Real , UIntPack< FEMSigs ... > >& coefficients ) const
{
typedef SparseNodeData< Real , UIntPack< FEMSigs ... > > SparseType;
typedef DenseNodeData< Real , UIntPack< FEMSigs ... > > DenseType;
typename BaseFEMIntegrator::template SystemConstraint< UIntPack< FEMDegrees ... > > _F( F );
if ( typeid(coefficients)==typeid(SparseType) ) return _dot< Real >( UIntPack< FEMSigs ... >() , UIntPack< FEMSigs ... >() , _F , static_cast< const SparseType& >( coefficients ) , static_cast< const SparseType& >( coefficients ) , []( Real v , Real w ){ return v*w; } );
else if( typeid(coefficients)==typeid( DenseType) ) return _dot< Real >( UIntPack< FEMSigs ... >() , UIntPack< FEMSigs ... >() , _F , static_cast< const DenseType& >( coefficients ) , static_cast< const DenseType& >( coefficients ) , []( Real v , Real w ){ return v*w; } );
else return _dot< Real >( UIntPack< FEMSigs ... >() , UIntPack< FEMSigs ... >() , _F , coefficients , coefficients , []( Real v , Real w ){ return v*w; } );
}
template< unsigned int ... FEMSigs1 , unsigned int ... FEMSigs2 , unsigned int ... PointDs >
double interpolationDot( const DenseNodeData< Real , UIntPack< FEMSigs1 ... > >& coefficients1 , const DenseNodeData< Real , UIntPack< FEMSigs2 ... > >& coefficients2 , const InterpolationInfo< Real , PointDs >* ... iInfos ) const
{
static_assert( sizeof...( FEMSigs1 )==Dim && sizeof...( FEMSigs2 )==Dim , "[ERROR] Dimensions don't match" );
return _inteprolationDot( UIntPack< FEMSigs1 ... >() , UIntPack< FEMSigs2 ... >() , coefficients1 , coefficients2 , []( Real v , Real w ){ return v*w; } , iInfos... );
}
template< unsigned int ... FEMSigs , unsigned int ... PointDs >
double interpolationSquareNorm( const DenseNodeData< Real , UIntPack< FEMSigs ... > >& coefficients , const InterpolationInfo< Real , PointDs >* ... iInfos ) const
{
static_assert( sizeof...( FEMSigs )==Dim , "[ERROR] Dimensions don't match" );
return _interpolationDot< Real >( UIntPack< FEMSigs ... >() , UIntPack< FEMSigs ... >() , coefficients , coefficients , []( Real v , Real w ){ return v*w; } , iInfos... );
}
// Generic
template< typename T , typename TDotT , unsigned int ... FEMDegrees1 , unsigned int ... FEMSigs1 , unsigned int ... FEMDegrees2 , unsigned int ... FEMSigs2 >
double dot( TDotT Dot , typename BaseFEMIntegrator::Constraint< UIntPack< FEMDegrees1 ... > , UIntPack< FEMDegrees2 ... > , 1 >& F , const _SparseOrDenseNodeData< T , UIntPack< FEMSigs1 ... > >& coefficients1 , const _SparseOrDenseNodeData< T , UIntPack< FEMSigs2 ... > >& coefficients2 ) const
{
typedef SparseNodeData< T , UIntPack< FEMSigs1 ... > > SparseType1;
typedef DenseNodeData< T , UIntPack< FEMSigs1 ... > > DenseType1;
typedef SparseNodeData< T , UIntPack< FEMSigs2 ... > > SparseType2;
typedef DenseNodeData< T , UIntPack< FEMSigs2 ... > > DenseType2;
static_assert( sizeof...( FEMDegrees1 )==Dim && sizeof...( FEMSigs1 )==Dim && sizeof...( FEMDegrees2 )==Dim && sizeof...( FEMSigs2 )==Dim , "[ERROR] Dimensions don't match" );
static_assert( UIntPack< FEMDegrees1 ... >::template Compare< UIntPack< FEMSignature< FEMSigs1 >::Degree ... > >::Equal , "[ERROR] FEM signature and degrees don't match" );
static_assert( UIntPack< FEMDegrees2 ... >::template Compare< UIntPack< FEMSignature< FEMSigs2 >::Degree ... > >::Equal , "[ERROR] FEM signature and degrees don't match" );
if ( typeid(coefficients1)==typeid(SparseType1) && typeid(coefficients2)==typeid(SparseType2) ) return _dot< T >( UIntPack< FEMSigs1 ... >() , UIntPack< FEMSigs2 ... >() , F , static_cast< const SparseType1& >( coefficients1 ) , static_cast< const SparseType2& >( coefficients2 ) , Dot );
else if( typeid(coefficients1)==typeid(SparseType1) && typeid(coefficients2)==typeid( DenseType2) ) return _dot< T >( UIntPack< FEMSigs1 ... >() , UIntPack< FEMSigs2 ... >() , F , static_cast< const SparseType1& >( coefficients1 ) , static_cast< const DenseType2& >( coefficients2 ) , Dot );
else if( typeid(coefficients1)==typeid( DenseType1) && typeid(coefficients2)==typeid( DenseType2) ) return _dot< T >( UIntPack< FEMSigs1 ... >() , UIntPack< FEMSigs2 ... >() , F , static_cast< const DenseType1& >( coefficients1 ) , static_cast< const DenseType2& >( coefficients2 ) , Dot );
else if( typeid(coefficients1)==typeid( DenseType1) && typeid(coefficients2)==typeid(SparseType2) ) return _dot< T >( UIntPack< FEMSigs1 ... >() , UIntPack< FEMSigs2 ... >() , F , static_cast< const DenseType1& >( coefficients1 ) , static_cast< const SparseType2& >( coefficients2 ) , Dot );
else return _dot< T >( UIntPack< FEMSigs1 ... >() , UIntPack< FEMSigs2 ... >() , F , coefficients1 , coefficients2 , Dot );
}
template< typename T , typename TDotT , unsigned int ... FEMDegrees , unsigned int ... FEMSigs >
double dot( TDotT Dot , typename BaseFEMIntegrator::System< UIntPack< FEMDegrees ... > >& F , const _SparseOrDenseNodeData< T , UIntPack< FEMSigs ... > >& coefficients1 , const _SparseOrDenseNodeData< T , UIntPack< FEMSigs ... > >& coefficients2 ) const
{
typedef SparseNodeData< T , UIntPack< FEMSigs ... > > SparseType;
typedef DenseNodeData< T , UIntPack< FEMSigs ... > > DenseType;
static_assert( sizeof...( FEMDegrees )==Dim && sizeof...( FEMSigs )==Dim , "[ERROR] Dimensions don't match" );
static_assert( UIntPack< FEMDegrees ... >::template Compare< UIntPack< FEMSignature< FEMSigs >::Degree ... > >::Equal , "[ERROR] FEM signatures and degrees don't match" );
typename BaseFEMIntegrator::template SystemConstraint< UIntPack< FEMDegrees ... > > _F( F );
if ( typeid(coefficients1)==typeid(SparseType) && typeid(coefficients2)==typeid(SparseType) ) return _dot< T >( UIntPack< FEMSigs ... >() , UIntPack< FEMSigs ... >() , _F , static_cast< const SparseType& >( coefficients1 ) , static_cast< const SparseType& >( coefficients2 ) , Dot );
else if( typeid(coefficients1)==typeid(SparseType) && typeid(coefficients2)==typeid( DenseType) ) return _dot< T >( UIntPack< FEMSigs ... >() , UIntPack< FEMSigs ... >() , _F , static_cast< const SparseType& >( coefficients1 ) , static_cast< const DenseType& >( coefficients2 ) , Dot );
else if( typeid(coefficients1)==typeid( DenseType) && typeid(coefficients2)==typeid( DenseType) ) return _dot< T >( UIntPack< FEMSigs ... >() , UIntPack< FEMSigs ... >() , _F , static_cast< const DenseType& >( coefficients1 ) , static_cast< const DenseType& >( coefficients2 ) , Dot );
else if( typeid(coefficients1)==typeid( DenseType) && typeid(coefficients2)==typeid(SparseType) ) return _dot< T >( UIntPack< FEMSigs ... >() , UIntPack< FEMSigs ... >() , _F , static_cast< const DenseType& >( coefficients1 ) , static_cast< const SparseType& >( coefficients2 ) , Dot );
else return _dot< T >( UIntPack< FEMSigs ... >() , UIntPack< FEMSigs ... >() , _F , coefficients1 , coefficients2 , Dot );
}
template< typename T , typename TDotT , unsigned int ... FEMDegrees , unsigned int ... FEMSigs >
double squareNorm( TDotT Dot , typename BaseFEMIntegrator::template System< UIntPack< FEMDegrees ... > >& F , const _SparseOrDenseNodeData< T , UIntPack< FEMSigs ... > >& coefficients ) const
{
typedef SparseNodeData< T , UIntPack< FEMSigs ... > > SparseType;
typedef DenseNodeData< T , UIntPack< FEMSigs ... > > DenseType;
typename BaseFEMIntegrator::template SystemConstraint< UIntPack< FEMDegrees ... > > _F( F );
if ( typeid(coefficients)==typeid(SparseType) ) return _dot< T >( UIntPack< FEMSigs ... >() , UIntPack< FEMSigs ... >() , _F , static_cast< const SparseType& >( coefficients ) , static_cast< const SparseType& >( coefficients ) , Dot );
else if( typeid(coefficients)==typeid( DenseType) ) return _dot< T >( UIntPack< FEMSigs ... >() , UIntPack< FEMSigs ... >() , _F , static_cast< const DenseType& >( coefficients ) , static_cast< const DenseType& >( coefficients ) , Dot );
else return _dot< T >( UIntPack< FEMSigs ... >() , UIntPack< FEMSigs ... >() , _F , coefficients , coefficients , Dot );
}
template< typename T , typename TDotT , unsigned int ... FEMSigs1 , unsigned int ... FEMSigs2 , unsigned int ... PointDs >
double interpolationDot( TDotT Dot , const DenseNodeData< T , UIntPack< FEMSigs1 ... > >& coefficients1 , const DenseNodeData< T , UIntPack< FEMSigs2 ... > >& coefficients2 , const InterpolationInfo< T , PointDs >* ... iInfos ) const
{
static_assert( sizeof...( FEMSigs1 )==Dim && sizeof...( FEMSigs2 )==Dim , "[ERROR] Dimensions don't match" );
return _interpolationDot< T >( UIntPack< FEMSigs1 ... >() , UIntPack< FEMSigs2 ... >() , coefficients1 , coefficients2 , Dot , iInfos... );
}
template< typename T , typename TDotT , unsigned int ... FEMSigs , unsigned int ... PointDs >
double interpolationSquareNorm( TDotT Dot , const DenseNodeData< T , UIntPack< FEMSigs ... > >& coefficients , const InterpolationInfo< T , PointDs >* ... iInfos ) const
{
static_assert( sizeof...( FEMSigs )==Dim , "[ERROR] Dimensions don't match" );
return _interpolationDot< T >( UIntPack< FEMSigs ... >() , UIntPack< FEMSigs ... >() , coefficients , coefficients , Dot , iInfos... );
}
template< typename T , unsigned int ... PointDs , unsigned int ... FEMSigs >
SparseMatrix< Real > systemMatrix( UIntPack< FEMSigs ... > , typename BaseFEMIntegrator::System< UIntPack< FEMSignature< FEMSigs >::Degree ... > >& F , LocalDepth depth , const InterpolationInfo< T , PointDs >* ... interpolationInfo ) const;
template< typename T , unsigned int ... PointDs , unsigned int ... FEMSigs >
SparseMatrix< Real > prolongedSystemMatrix( UIntPack< FEMSigs ... > , typename BaseFEMIntegrator::System< UIntPack< FEMSignature< FEMSigs >::Degree ... > >& F , LocalDepth highDepth , const InterpolationInfo< T , PointDs >* ... interpolationInfo ) const;
template< unsigned int ... FEMSigs >
SparseMatrix< Real > downSampleMatrix( UIntPack< FEMSigs ... > , LocalDepth highDepth ) const;
template< typename T , unsigned int ... PointDs , unsigned int ... FEMSigs >
SparseMatrix< Real > fullSystemMatrix( UIntPack< FEMSigs ... > , typename BaseFEMIntegrator::System< UIntPack< FEMSignature< FEMSigs >::Degree ... > >& F , LocalDepth depth , bool nonRefinableOnly , const InterpolationInfo< T , PointDs >* ... interpolationInfo ) const;
struct SolverInfo
{
protected:
struct _IterFunction
{
_IterFunction( int i ) : _i0(i) , _type(0) {}
_IterFunction( std::function< int ( int ) > iFunction ) : _i1(iFunction) , _type(1) {}
_IterFunction( std::function< int ( bool , int ) > iFunction ) : _i2(iFunction) , _type(2) {}
_IterFunction( std::function< int ( int , bool , int ) > iFunction ) : _i3(iFunction) , _type(3) {}
_IterFunction& operator = ( int i ){ *this = _IterFunction(i) ; return *this; }
_IterFunction& operator = ( std::function< int ( int ) > iFunction ){ *this = _IterFunction(iFunction) ; return *this; }
_IterFunction& operator = ( std::function< int ( bool , int ) > iFunction ){ *this = _IterFunction(iFunction) ; return *this; }
_IterFunction& operator = ( std::function< int ( int , bool , int ) > iFunction ){ *this = _IterFunction(iFunction) ; return *this; }
int operator()( int vCycle , bool restriction , int depth ) const
{
switch( _type )
{
case 0: return _i0;
case 1: return _i1( depth );
case 2: return _i2( restriction , depth );
case 3: return _i3( vCycle , restriction , depth );
default: return 0;
}
}
protected:
int _i0;
std::function< int ( int ) > _i1;
std::function< int ( bool , int ) > _i2;
std::function< int ( int i3 , bool , int ) > _i3;
int _type;
};
public:
// How to solve
bool wCycle;
LocalDepth cgDepth;
bool cascadic;
unsigned int sliceBlockSize;
bool useSupportWeights , useProlongationSupportWeights;
std::function< Real ( Real , Real ) > sorRestrictionFunction;
std::function< Real ( Real , Real ) > sorProlongationFunction;
_IterFunction iters;
int vCycles;
double cgAccuracy;
int baseDepth , baseVCycles;
// What to output
bool verbose , showResidual;
int showGlobalResidual;
SolverInfo( void ) : cgDepth(0) , wCycle(false) , cascadic(true) , iters(1) , vCycles(1) , cgAccuracy(0.) , verbose(false) , showResidual(false) , showGlobalResidual(SHOW_GLOBAL_RESIDUAL_NONE) , sliceBlockSize(1) , sorRestrictionFunction( []( Real , Real ){ return (Real)1; } ) , sorProlongationFunction( []( Real , Real ){ return (Real)1; } ) , useSupportWeights( false ) , useProlongationSupportWeights( false ) , baseDepth(0) , baseVCycles(1) { }
};
// Solve the linear system
template< unsigned int ... FEMSigs , typename T , typename TDotT , unsigned int ... PointDs >
void solveSystem( UIntPack< FEMSigs ... > , typename BaseFEMIntegrator::template System< UIntPack< FEMSignature< FEMSigs >::Degree ... > >& F , const DenseNodeData< T , UIntPack< FEMSigs ... > >& constraints , DenseNodeData< T , UIntPack< FEMSigs ... > >& solution , TDotT Dot , LocalDepth maxSolveDepth , const SolverInfo& solverInfo , InterpolationInfo< T , PointDs >* ... iData ) const;
template< unsigned int ... FEMSigs , typename T , typename TDotT , unsigned int ... PointDs >
DenseNodeData< T , UIntPack< FEMSigs ... > > solveSystem( UIntPack< FEMSigs ... > , typename BaseFEMIntegrator::template System< UIntPack< FEMSignature< FEMSigs >::Degree ... > >& F , const DenseNodeData< T , UIntPack< FEMSigs ... > >& constraints , TDotT Dot , LocalDepth maxSolveDepth , const SolverInfo& solverInfo , InterpolationInfo< T , PointDs >* ... iData ) const;
template< unsigned int ... FEMSigs , unsigned int ... PointDs >
void solveSystem( UIntPack< FEMSigs ... > , typename BaseFEMIntegrator::template System< UIntPack< FEMSignature< FEMSigs >::Degree ... > >& F , const DenseNodeData< Real , UIntPack< FEMSigs ... > >& constraints , DenseNodeData< Real , UIntPack< FEMSigs ... > >& solution , LocalDepth maxSolveDepth , const SolverInfo& solverInfo , InterpolationInfo< Real , PointDs >* ... iData ) const
{
return solveSystem< FEMSigs ... , Real >( UIntPack< FEMSigs ... >() , F , constraints , solution , []( Real v , Real w ){ return v*w; } , maxSolveDepth , solverInfo , iData ... );
}
template< unsigned int ... FEMSigs , unsigned int ... PointDs >
DenseNodeData< Real , UIntPack< FEMSigs ... > > solveSystem( UIntPack< FEMSigs ... > , typename BaseFEMIntegrator::template System< UIntPack< FEMSignature< FEMSigs >::Degree ... > >& F , const DenseNodeData< Real , UIntPack< FEMSigs ... > >& constraints , LocalDepth maxSolveDepth , const SolverInfo& solverInfo , InterpolationInfo< Real , PointDs >* ... iData ) const
{
return solveSystem( UIntPack< FEMSigs ... >() , F , constraints , []( Real v , Real w ){ return v*w; } , maxSolveDepth , solverInfo , iData ... );
}
FEMTreeNode& spaceRoot( void ){ return *_spaceRoot; }
const FEMTreeNode& tree( void ) const { return *_tree; }
std::function< void ( FEMTreeNode& ) > initializer( void ){ return _NodeInitializer( *this ); }
size_t leaves( void ) const { return _tree->leaves(); }
size_t nodes( void ) const { int count = 0 ; for( const FEMTreeNode* n=_tree->nextNode() ; n ; n=_tree->nextNode( n ) ) if( IsActiveNode< Dim >( n ) ) count++ ; return count; }
size_t ghostNodes( void ) const { int count = 0 ; for( const FEMTreeNode* n=_tree->nextNode() ; n ; n=_tree->nextNode( n ) ) if( !IsActiveNode< Dim >( n ) ) count++ ; return count; }
inline size_t validSpaceNodes( void ) const { int count = 0 ; for( const FEMTreeNode* n=_tree->nextNode() ; n ; n=_tree->nextNode( n ) ) if( isValidSpaceNode( n ) ) count++ ; return count; }
inline size_t validSpaceNodes( LocalDepth d ) const { int count = 0 ; for( const FEMTreeNode* n=_tree->nextNode() ; n ; n=_tree->nextNode( n ) ) if( _localDepth(n)==d && isValidSpaceNode( n ) ) count++ ; return count; }
template< unsigned int ... FEMSigs > size_t validFEMNodes( UIntPack< FEMSigs ... > ) const { int count = 0 ; for( const FEMTreeNode* n=_tree->nextNode() ; n ; n=_tree->nextNode( n ) ) if( isValidFEMNode( UIntPack< FEMSigs ... >() , n ) ) count++ ; return count; }
template< unsigned int ... FEMSigs > size_t validFEMNodes( UIntPack< FEMSigs ... > , LocalDepth d ) const { int count = 0 ; for( const FEMTreeNode* n=_tree->nextNode() ; n ; n=_tree->nextNode( n ) ) if( _localDepth(n)==d && isValidFEMNode( UIntPack< FEMSigs ... >() , n ) ) count++ ; return count; }
LocalDepth depth( void ) const { return _spaceRoot->maxDepth(); }
void resetNodeIndices( void ){ _nodeCount = 0 ; for( FEMTreeNode* node=_tree->nextNode() ; node ; node=_tree->nextNode( node ) ) _nodeInitializer( *node ) , node->nodeData.flags=0; }
std::vector< int > merge( FEMTree* tree );
protected:
template< class Real1 , unsigned int _Dim > static bool _IsZero( Point< Real1 , _Dim > p );
template< class Real1 > static bool _IsZero( Real1 p );
template< class SReal , class Data , unsigned int _Dim > static Data _StencilDot( Point< SReal , _Dim > p1 , Point< Data , _Dim > p2 );
template< class SReal , class Data > static Data _StencilDot( Point< SReal , 1 > p1 , Point< Data , 1 > p2 );
template< class SReal , class Data > static Data _StencilDot( SReal p1 , Point< Data , 1 > p2 );
template< class SReal , class Data > static Data _StencilDot( Point< SReal , 1 > p1 , Data p2 );
template< class SReal , class Data > static Data _StencilDot( SReal p1 , Data p2 );
// We need the signatures to test if nodes are valid
template< typename T , unsigned int ... FEMSigs , unsigned int ... CSigs , unsigned int ... FEMDegrees , unsigned int ... CDegrees , unsigned int CDim , class Coefficients >
void _addFEMConstraints( UIntPack< FEMSigs ... > , UIntPack< CSigs ... > , typename BaseFEMIntegrator::Constraint< UIntPack< FEMDegrees ... > , UIntPack< CDegrees ... > , CDim >& F , const Coefficients& coefficients , Pointer( T ) constraints , LocalDepth maxDepth ) const;
template< typename T , typename TDotT , unsigned int ... FEMSigs1 , unsigned int ... FEMSigs2 , unsigned int ... Degrees1 , unsigned int ... Degrees2 , class Coefficients1 , class Coefficients2 >
double _dot( UIntPack< FEMSigs1 ... > , UIntPack< FEMSigs2 ... > , typename BaseFEMIntegrator::Constraint< UIntPack< Degrees1 ... > , UIntPack< Degrees2 ... > , 1 >& F , const Coefficients1& coefficients1 , const Coefficients2& coefficients2 , TDotT Dot ) const;
template< typename T , typename TDotT , unsigned int ... FEMSigs1 , unsigned int ... FEMSigs2 , class Coefficients1 , class Coefficients2 , unsigned int PointD >
double _interpolationDot( UIntPack< FEMSigs1 ... > , UIntPack< FEMSigs2 ... > , const Coefficients1& coefficients1 , const Coefficients2& coefficients2 , TDotT Dot , const InterpolationInfo< T , PointD >* iInfo ) const;
template< typename T , typename TDotT , unsigned int ... FEMSigs1 , unsigned int ... FEMSigs2 , class Coefficients1 , class Coefficients2 , unsigned int PointD , unsigned int ... PointDs >
double _interpolationDot( UIntPack< FEMSigs1 ... > , UIntPack< FEMSigs2 ... > , const Coefficients1& coefficients1 , const Coefficients2& coefficients2 , TDotT Dot , const InterpolationInfo< T , PointD >* iInfo , const InterpolationInfo< T , PointDs >* ... iInfos ) const
{
return _interpolationDot< T >( UIntPack< FEMSigs1 ... >() , UIntPack< FEMSigs2 ... >() , coefficients1 , coefficients2 , Dot , iInfo ) + _interpolationDot< T >( UIntPack< FEMSigs1 ... >() , UIntPack< FEMSigs2 ... >() , coefficients1 , coefficients2 , Dot , iInfos... );
}
template< typename T , typename TDotT , unsigned int ... FEMSigs1 , unsigned int ... FEMSigs2 , class Coefficients1 , class Coefficients2 > double _interpolationDot( UIntPack< FEMSigs1 ... > , UIntPack< FEMSigs2 ... > , const Coefficients1& coefficients1 , const Coefficients2& coefficients2 , TDotT Dot ) const{ return 0; }
};
template< unsigned int Dim , class Real > double FEMTree< Dim , Real >::_MaxMemoryUsage = 0;
template< unsigned int Dim , class Real > double FEMTree< Dim , Real >::_LocalMemoryUsage = 0;
template< unsigned int Dim , class Real , class Vertex >
struct IsoSurfaceExtractor
{
struct IsoStats{};
template< typename Data , unsigned int ... FEMSigs , unsigned int WeightDegree , unsigned int DataSig >
static IsoStats Extract
(
UIntPack< FEMSigs ... > , UIntPack< WeightDegree > , UIntPack< DataSig > , // Dummy variables for grouping the parameter
const FEMTree< Dim , Real >& tree , // The tree over which the system is discretized
const typename FEMTree< Dim , Real >::template DensityEstimator< WeightDegree >* densityWeights , // Density weights
const SparseNodeData< ProjectiveData< Data , Real > , IsotropicUIntPack< Dim , DataSig > >* data , // Auxiliary spatial data
const DenseNodeData< Real , UIntPack< FEMSigs ... > >& coefficients , // The coefficients of the function
Real isoValue , // The value at which to extract the level-set
CoredMeshData< Vertex >& mesh , // The mesh in which to store the output
std::function< void ( Vertex& , Point< Real , Dim > , Real , Data ) > SetVertex , // A function for setting the depth and data of a vertex
bool nonLinearFit , // Should a linear interpolant be used
bool addBarycenter , // Should we triangulate polygons by adding a mid-point
bool polygonMesh , // Should we output triangles or polygons
bool flipOrientation // Should we flip the orientation
)
{
// The unspecialized implementation is not supported
fprintf( stderr , "[WARNING] Iso-surface extraction not supported for dimension %d\n" , Dim );
return IsoStats();
}
};
template< unsigned int Dim , class Real >
struct FEMTreeInitializer
{
typedef RegularTreeNode< Dim , FEMTreeNodeData > FEMTreeNode;
typedef NodeAndPointSample< Dim , Real > PointSample;
template< class Data >
struct DerivativeStream
{
virtual void resolution( unsigned int res[] ) const = 0;
virtual bool nextDerivative( unsigned int idx[] , unsigned int& dir , Data& dValue ) = 0;
};
// Initialize the tree using a refinement avatar
static int Initialize( FEMTreeNode& root , int maxDepth , std::function< bool ( int , int[] ) > Refine , Allocator< FEMTreeNode >* nodeAllocator , std::function< void ( FEMTreeNode& ) > NodeInitializer );
// Initialize the tree using a point stream
static int Initialize( FEMTreeNode& root , InputPointStream< Real , Dim >& pointStream , int maxDepth , std::vector< PointSample >& samplePoints , Allocator< FEMTreeNode >* nodeAllocator , std::function< void ( FEMTreeNode& ) > NodeInitializer );
template< class Data > static int Initialize( FEMTreeNode& root , InputPointStreamWithData< Real , Dim , Data >& pointStream , int maxDepth , std::vector< PointSample >& samplePoints , std::vector< Data >& sampleData , bool mergeNodeSamples , Allocator< FEMTreeNode >* nodeAllocator , std::function< void ( FEMTreeNode& ) > NodeInitializer , std::function< Real ( const Point< Real , Dim >& , Data& ) > ProcessData = []( const Point< Real , Dim >& , Data& ){ return (Real)1.; } );
// Initialize the tree using simplices
static void Initialize( FEMTreeNode& root , const std::vector< Point< Real , Dim > >& vertices , const std::vector< SimplexIndex< Dim-1 > >& simplices , int maxDepth , std::vector< PointSample >& samples , bool mergeNodeSamples , Allocator< FEMTreeNode >* nodeAllocator , std::function< void ( FEMTreeNode& ) > NodeInitializer );
static void Initialize( FEMTreeNode& root , const std::vector< Point< Real , Dim > >& vertices , const std::vector< SimplexIndex< Dim-1 > >& simplices , int maxDepth , std::vector< NodeSimplices< Dim , Real > >& nodeSimplices , Allocator< FEMTreeNode >* nodeAllocator , std::function< void ( FEMTreeNode& ) > NodeInitializer );
template< class Data , class _Data , bool Dual=true >
static int Initialize( FEMTreeNode& root , ConstPointer( Data ) values , ConstPointer( int ) labels , int resolution[Dim] , std::vector< NodeSample< Dim , _Data > > derivatives[Dim] , Allocator< FEMTreeNode >* nodeAllocator , std::function< void ( FEMTreeNode& ) > NodeInitializer , std::function< _Data ( const Data& ) > DataConverter = []( const Data& d ){ return (_Data)d; } );
template< bool Dual , class Data >
static unsigned int Initialize( FEMTreeNode& root , DerivativeStream< Data >& dStream , std::vector< NodeSample< Dim , Data > > derivatives[Dim] , Allocator< FEMTreeNode >* nodeAllocator , std::function< void ( FEMTreeNode& ) > NodeInitializer );
protected:
static int _AddSimplex( FEMTreeNode& root , Simplex< Real , Dim , Dim-1 >& s , int maxDepth , std::vector< PointSample >& samples , std::vector< int >* nodeToIndexMap , Allocator< FEMTreeNode >* nodeAllocator , std::function< void ( FEMTreeNode& ) > NodeInitializer );
static int _AddSimplex( FEMTreeNode& root , Simplex< Real , Dim , Dim-1 >& s , int maxDepth , std::vector< NodeSimplices< Dim , Real > >& simplices , std::vector< int >& nodeToIndexMap , Allocator< FEMTreeNode >* nodeAllocator , std::function< void ( FEMTreeNode& ) > NodeInitializer );
static int _AddSimplex( FEMTreeNode* node , Simplex< Real , Dim , Dim-1 >& s , int maxDepth , std::vector< PointSample >& samples , std::vector< int >* nodeToIndexMap , Allocator< FEMTreeNode >* nodeAllocator , std::function< void ( FEMTreeNode& ) > NodeInitializer );
static int _AddSimplex( FEMTreeNode* node , Simplex< Real , Dim , Dim-1 >& s , int maxDepth , std::vector< NodeSimplices< Dim , Real > >& simplices , std::vector< int >& nodeToIndexMap , Allocator< FEMTreeNode >* nodeAllocator , std::function< void ( FEMTreeNode& ) > NodeInitializer );
};
template< unsigned int Dim , class Real >
template< unsigned int ... SupportSizes >
const unsigned int FEMTree< Dim , Real >::CornerLoopData< SupportSizes ... >::supportSizes[] = { SupportSizes ... };
#include "FEMTree.inl"
#include "FEMTree.SortedTreeNodes.inl"
#include "FEMTree.WeightedSamples.inl"
#include "FEMTree.System.inl"
#include "FEMTree.Evaluation.inl"
#include "FEMTree.IsoSurface.specialized.inl"
#include "FEMTree.Initialize.inl"
#endif // FEM_TREE_INCLUDED
|
GB_unop__identity_uint32_uint32.c
|
//------------------------------------------------------------------------------
// GB_unop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved.
// http://suitesparse.com See GraphBLAS/Doc/License.txt for license.
//------------------------------------------------------------------------------
// If this file is in the Generated/ folder, do not edit it (auto-generated).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_unop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: (none)
// op(A') function: GB_unop_tran__identity_uint32_uint32
// C type: uint32_t
// A type: uint32_t
// cast: uint32_t cij = aij
// unaryop: cij = aij
#define GB_ATYPE \
uint32_t
#define GB_CTYPE \
uint32_t
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
uint32_t aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = x ;
// casting
#define GB_CAST(z, aij) \
uint32_t z = aij ;
// cij = op (aij)
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
uint32_t aij = Ax [pA] ; \
/* Cx [pC] = op (cast (aij)) */ \
uint32_t z = aij ; \
Cx [pC] = z ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_IDENTITY || GxB_NO_UINT32)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
#if 0
GrB_Info (none)
(
uint32_t *Cx, // Cx and Ax may be aliased
const uint32_t *Ax,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
uint32_t aij = Ax [p] ;
uint32_t z = aij ;
Cx [p] = z ;
}
return (GrB_SUCCESS) ;
#endif
}
#endif
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop_tran__identity_uint32_uint32
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t *GB_RESTRICT *Rowcounts,
GBI_single_iterator Iter,
const int64_t *GB_RESTRICT A_slice,
int naslice
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#define GB_PHASE_2_OF_2
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
3d7pt_var.lbpar.c
|
#include <omp.h>
#include <math.h>
#define ceild(n,d) ceil(((double)(n))/((double)(d)))
#define floord(n,d) floor(((double)(n))/((double)(d)))
#define max(x,y) ((x) > (y)? (x) : (y))
#define min(x,y) ((x) < (y)? (x) : (y))
/*
* Order-1, 3D 7 point stencil with variable coefficients
* Adapted from PLUTO and Pochoir test bench
*
* Tareq Malas
*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#ifdef LIKWID_PERFMON
#include <likwid.h>
#endif
#include "print_utils.h"
#define TESTS 2
#define MAX(a,b) ((a) > (b) ? a : b)
#define MIN(a,b) ((a) < (b) ? a : b)
/* Subtract the `struct timeval' values X and Y,
* storing the result in RESULT.
*
* Return 1 if the difference is negative, otherwise 0.
*/
int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y)
{
/* Perform the carry for the later subtraction by updating y. */
if (x->tv_usec < y->tv_usec)
{
int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1;
y->tv_usec -= 1000000 * nsec;
y->tv_sec += nsec;
}
if (x->tv_usec - y->tv_usec > 1000000)
{
int nsec = (x->tv_usec - y->tv_usec) / 1000000;
y->tv_usec += 1000000 * nsec;
y->tv_sec -= nsec;
}
/* Compute the time remaining to wait.
* tv_usec is certainly positive.
*/
result->tv_sec = x->tv_sec - y->tv_sec;
result->tv_usec = x->tv_usec - y->tv_usec;
/* Return 1 if result is negative. */
return x->tv_sec < y->tv_sec;
}
int main(int argc, char *argv[])
{
int t, i, j, k, m, test;
int Nx, Ny, Nz, Nt;
if (argc > 3) {
Nx = atoi(argv[1])+2;
Ny = atoi(argv[2])+2;
Nz = atoi(argv[3])+2;
}
if (argc > 4)
Nt = atoi(argv[4]);
// allocate the arrays
double ****A = (double ****) malloc(sizeof(double***)*2);
for(m=0; m<2;m++){
A[m] = (double ***) malloc(sizeof(double**)*Nz);
for(i=0; i<Nz; i++){
A[m][i] = (double**) malloc(sizeof(double*)*Ny);
for(j=0;j<Ny;j++){
A[m][i][j] = (double*) malloc(sizeof(double)*Nx);
}
}
}
double ****coef = (double ****) malloc(sizeof(double***)*7);
for(m=0; m<7;m++){
coef[m] = (double ***) malloc(sizeof(double**)*Nz);
for(i=0; i<Nz; i++){
coef[m][i] = (double**) malloc(sizeof(double*)*Ny);
for(j=0;j<Ny;j++){
coef[m][i][j] = (double*) malloc(sizeof(double)*Nx);
}
}
}
// tile size information, including extra element to decide the list length
int *tile_size = (int*) malloc(sizeof(int));
tile_size[0] = -1;
// The list is modified here before source-to-source transformations
tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5);
tile_size[0] = 8;
tile_size[1] = 8;
tile_size[2] = 32;
tile_size[3] = 512;
tile_size[4] = -1;
// for timekeeping
int ts_return = -1;
struct timeval start, end, result;
double tdiff = 0.0, min_tdiff=1.e100;
const int BASE = 1024;
// initialize variables
//
srand(42);
for (i = 1; i < Nz; i++) {
for (j = 1; j < Ny; j++) {
for (k = 1; k < Nx; k++) {
A[0][i][j][k] = 1.0 * (rand() % BASE);
}
}
}
for (m=0; m<7; m++) {
for (i=1; i<Nz; i++) {
for (j=1; j<Ny; j++) {
for (k=1; k<Nx; k++) {
coef[m][i][j][k] = 1.0 * (rand() % BASE);
}
}
}
}
#ifdef LIKWID_PERFMON
LIKWID_MARKER_INIT;
#pragma omp parallel
{
LIKWID_MARKER_THREADINIT;
#pragma omp barrier
LIKWID_MARKER_START("calc");
}
#endif
int num_threads = 1;
#if defined(_OPENMP)
num_threads = omp_get_max_threads();
#endif
for(test=0; test<TESTS; test++){
gettimeofday(&start, 0);
// serial execution - Addition: 6 && Multiplication: 2
/* Copyright (C) 1991-2014 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
/* This header is separate from features.h so that the compiler can
include it implicitly at the start of every compilation. It must
not itself include <features.h> or any other header that includes
<features.h> because the implicit include comes before any feature
test macros that may be defined in a source file before it first
explicitly includes a system header. GCC knows the name of this
header in order to preinclude it. */
/* glibc's intent is to support the IEC 559 math functionality, real
and complex. If the GCC (4.9 and later) predefined macros
specifying compiler intent are available, use them to determine
whether the overall intent is to support these features; otherwise,
presume an older compiler has intent to support these features and
define these macros by default. */
/* wchar_t uses ISO/IEC 10646 (2nd ed., published 2011-03-15) /
Unicode 6.0. */
/* We do not support C11 <threads.h>. */
int t1, t2, t3, t4, t5, t6, t7, t8;
int lb, ub, lbp, ubp, lb2, ub2;
register int lbv, ubv;
/* Start of CLooG code */
if ((Nt >= 2) && (Nx >= 3) && (Ny >= 3) && (Nz >= 3)) {
for (t1=-1;t1<=floord(Nt-2,4);t1++) {
lbp=max(ceild(t1,2),ceild(8*t1-Nt+3,8));
ubp=min(floord(Nt+Nz-4,8),floord(4*t1+Nz+1,8));
#pragma omp parallel for private(lbv,ubv,t3,t4,t5,t6,t7,t8)
for (t2=lbp;t2<=ubp;t2++) {
for (t3=max(max(0,ceild(t1-7,8)),ceild(8*t2-Nz-28,32));t3<=min(min(min(floord(Nt+Ny-4,32),floord(4*t1+Ny+5,32)),floord(8*t2+Ny+4,32)),floord(8*t1-8*t2+Nz+Ny+3,32));t3++) {
for (t4=max(max(max(0,ceild(t1-127,128)),ceild(8*t2-Nz-508,512)),ceild(32*t3-Ny-508,512));t4<=min(min(min(min(floord(Nt+Nx-4,512),floord(4*t1+Nx+5,512)),floord(8*t2+Nx+4,512)),floord(32*t3+Nx+28,512)),floord(8*t1-8*t2+Nz+Nx+3,512));t4++) {
for (t5=max(max(max(max(max(0,4*t1),8*t1-8*t2+1),8*t2-Nz+2),32*t3-Ny+2),512*t4-Nx+2);t5<=min(min(min(min(min(Nt-2,4*t1+7),8*t2+6),32*t3+30),512*t4+510),8*t1-8*t2+Nz+5);t5++) {
for (t6=max(max(8*t2,t5+1),-8*t1+8*t2+2*t5-7);t6<=min(min(8*t2+7,-8*t1+8*t2+2*t5),t5+Nz-2);t6++) {
for (t7=max(32*t3,t5+1);t7<=min(32*t3+31,t5+Ny-2);t7++) {
lbv=max(512*t4,t5+1);
ubv=min(512*t4+511,t5+Nx-2);
#pragma ivdep
#pragma vector always
for (t8=lbv;t8<=ubv;t8++) {
A[( t5 + 1) % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] = (((((((coef[0][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] * A[ t5 % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)]) + (coef[1][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] * A[ t5 % 2][ (-t5+t6) - 1][ (-t5+t7)][ (-t5+t8)])) + (coef[2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] * A[ t5 % 2][ (-t5+t6)][ (-t5+t7) - 1][ (-t5+t8)])) + (coef[3][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] * A[ t5 % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8) - 1])) + (coef[4][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] * A[ t5 % 2][ (-t5+t6) + 1][ (-t5+t7)][ (-t5+t8)])) + (coef[5][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] * A[ t5 % 2][ (-t5+t6)][ (-t5+t7) + 1][ (-t5+t8)])) + (coef[6][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] * A[ t5 % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8) + 1]));;
}
}
}
}
}
}
}
}
}
/* End of CLooG code */
gettimeofday(&end, 0);
ts_return = timeval_subtract(&result, &end, &start);
tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6);
min_tdiff = min(min_tdiff, tdiff);
printf("Rank 0 TEST# %d time: %f\n", test, tdiff);
}
PRINT_RESULTS(1, "variable no-symmetry")
#ifdef LIKWID_PERFMON
#pragma omp parallel
{
LIKWID_MARKER_STOP("calc");
}
LIKWID_MARKER_CLOSE;
#endif
// Free allocated arrays
for(i=0; i<Nz; i++){
for(j=0;j<Ny;j++){
free(A[0][i][j]);
free(A[1][i][j]);
}
free(A[0][i]);
free(A[1][i]);
}
free(A[0]);
free(A[1]);
for(m=0; m<7;m++){
for(i=0; i<Nz; i++){
for(j=0;j<Ny;j++){
free(coef[m][i][j]);
}
free(coef[m][i]);
}
free(coef[m]);
}
return 0;
}
|
GB_unop__identity_fc64_int8.c
|
//------------------------------------------------------------------------------
// GB_unop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated/ folder, do not edit it (auto-generated).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_atomics.h"
#include "GB_unop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB_unop_apply__identity_fc64_int8
// op(A') function: GB_unop_tran__identity_fc64_int8
// C type: GxB_FC64_t
// A type: int8_t
// cast: GxB_FC64_t cij = GxB_CMPLX ((double) (aij), 0)
// unaryop: cij = aij
#define GB_ATYPE \
int8_t
#define GB_CTYPE \
GxB_FC64_t
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
int8_t aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = x ;
// casting
#define GB_CAST(z, aij) \
GxB_FC64_t z = GxB_CMPLX ((double) (aij), 0) ;
// cij = op (aij)
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
int8_t aij = Ax [pA] ; \
/* Cx [pC] = op (cast (aij)) */ \
GxB_FC64_t z = GxB_CMPLX ((double) (aij), 0) ; \
Cx [pC] = z ; \
}
// true if operator is the identity op with no typecasting
#define GB_OP_IS_IDENTITY_WITH_NO_TYPECAST \
0
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_IDENTITY || GxB_NO_FC64 || GxB_NO_INT8)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop_apply__identity_fc64_int8
(
GxB_FC64_t *Cx, // Cx and Ax may be aliased
const int8_t *Ax,
const int8_t *GB_RESTRICT Ab, // A->b if A is bitmap
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
if (Ab == NULL)
{
#if ( GB_OP_IS_IDENTITY_WITH_NO_TYPECAST )
GB_memcpy (Cx, Ax, anz * sizeof (int8_t), nthreads) ;
#else
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
int8_t aij = Ax [p] ;
GxB_FC64_t z = GxB_CMPLX ((double) (aij), 0) ;
Cx [p] = z ;
}
#endif
}
else
{
// bitmap case, no transpose; A->b already memcpy'd into C->b
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!Ab [p]) continue ;
int8_t aij = Ax [p] ;
GxB_FC64_t z = GxB_CMPLX ((double) (aij), 0) ;
Cx [p] = z ;
}
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop_tran__identity_fc64_int8
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t *GB_RESTRICT *Workspaces,
const int64_t *GB_RESTRICT A_slice,
int nworkspaces,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
3d7pt.c
|
/*
* Order-1, 3D 7 point stencil
* Adapted from PLUTO and Pochoir test bench
*
* Tareq Malas
*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#ifdef LIKWID_PERFMON
#include <likwid.h>
#endif
#include "print_utils.h"
#define TESTS 2
#define MAX(a,b) ((a) > (b) ? a : b)
#define MIN(a,b) ((a) < (b) ? a : b)
/* Subtract the `struct timeval' values X and Y,
* storing the result in RESULT.
*
* Return 1 if the difference is negative, otherwise 0.
*/
int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y)
{
/* Perform the carry for the later subtraction by updating y. */
if (x->tv_usec < y->tv_usec)
{
int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1;
y->tv_usec -= 1000000 * nsec;
y->tv_sec += nsec;
}
if (x->tv_usec - y->tv_usec > 1000000)
{
int nsec = (x->tv_usec - y->tv_usec) / 1000000;
y->tv_usec += 1000000 * nsec;
y->tv_sec -= nsec;
}
/* Compute the time remaining to wait.
* tv_usec is certainly positive.
*/
result->tv_sec = x->tv_sec - y->tv_sec;
result->tv_usec = x->tv_usec - y->tv_usec;
/* Return 1 if result is negative. */
return x->tv_sec < y->tv_sec;
}
int main(int argc, char *argv[])
{
int t, i, j, k, test;
int Nx, Ny, Nz, Nt;
if (argc > 3) {
Nx = atoi(argv[1])+2;
Ny = atoi(argv[2])+2;
Nz = atoi(argv[3])+2;
}
if (argc > 4)
Nt = atoi(argv[4]);
double ****A = (double ****) malloc(sizeof(double***)*2);
A[0] = (double ***) malloc(sizeof(double**)*Nz);
A[1] = (double ***) malloc(sizeof(double**)*Nz);
for(i=0; i<Nz; i++){
A[0][i] = (double**) malloc(sizeof(double*)*Ny);
A[1][i] = (double**) malloc(sizeof(double*)*Ny);
for(j=0;j<Ny;j++){
A[0][i][j] = (double*) malloc(sizeof(double)*Nx);
A[1][i][j] = (double*) malloc(sizeof(double)*Nx);
}
}
// tile size information, including extra element to decide the list length
int *tile_size = (int*) malloc(sizeof(int));
tile_size[0] = -1;
// The list is modified here before source-to-source transformations
tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5);
tile_size[0] = 8;
tile_size[1] = 8;
tile_size[2] = 32;
tile_size[3] = 1024;
tile_size[4] = -1;
// for timekeeping
int ts_return = -1;
struct timeval start, end, result;
double tdiff = 0.0, min_tdiff=1.e100;
const int BASE = 1024;
const double alpha = 0.0876;
const double beta = 0.0765;
// initialize variables
//
srand(42);
for (i = 1; i < Nz; i++) {
for (j = 1; j < Ny; j++) {
for (k = 1; k < Nx; k++) {
A[0][i][j][k] = 1.0 * (rand() % BASE);
}
}
}
#ifdef LIKWID_PERFMON
LIKWID_MARKER_INIT;
#pragma omp parallel
{
LIKWID_MARKER_THREADINIT;
#pragma omp barrier
LIKWID_MARKER_START("calc");
}
#endif
int num_threads = 1;
#if defined(_OPENMP)
num_threads = omp_get_max_threads();
#endif
for(test=0; test<TESTS; test++){
gettimeofday(&start, 0);
// serial execution - Addition: 6 && Multiplication: 2
#pragma scop
for (t = 0; t < Nt-1; t++) {
for (i = 1; i < Nz-1; i++) {
for (j = 1; j < Ny-1; j++) {
for (k = 1; k < Nx-1; k++) {
A[(t+1)%2][i][j][k] = alpha * (A[t%2][i][j][k])
+ beta * (A[t%2][i - 1][j][k] + A[t%2][i][j - 1][k] + A[t%2][i][j][k - 1] +
A[t%2][i + 1][j][k] + A[t%2][i][j + 1][k] + A[t%2][i][j][k + 1]);
}
}
}
}
#pragma endscop
gettimeofday(&end, 0);
ts_return = timeval_subtract(&result, &end, &start);
tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6);
min_tdiff = min(min_tdiff, tdiff);
printf("Rank 0 TEST# %d time: %f\n", test, tdiff);
}
PRINT_RESULTS(1, "constant")
#ifdef LIKWID_PERFMON
#pragma omp parallel
{
LIKWID_MARKER_STOP("calc");
}
LIKWID_MARKER_CLOSE;
#endif
// Free allocated arrays (Causing performance degradation
/* for(i=0; i<Nz; i++){
for(j=0;j<Ny;j++){
free(A[0][i][j]);
free(A[1][i][j]);
}
free(A[0][i]);
free(A[1][i]);
}
free(A[0]);
free(A[1]);
*/
return 0;
}
|
DRB038-truedepseconddimension-var-yes.c
|
/*
Copyright (c) 2017, Lawrence Livermore National Security, LLC.
Produced at the Lawrence Livermore National Laboratory
Written by Chunhua Liao, Pei-Hung Lin, Joshua Asplund,
Markus Schordan, and Ian Karlin
(email: [email protected], [email protected], [email protected],
[email protected], [email protected])
LLNL-CODE-732144
All rights reserved.
This file is part of DataRaceBench. For details, see
https://github.com/LLNL/dataracebench. Please also see the LICENSE file
for our additional BSD notice.
Redistribution and use in source and binary forms, with
or without modification, are permitted provided that the following
conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the disclaimer below.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the disclaimer (as noted below)
in the documentation and/or other materials provided with the
distribution.
* Neither the name of the LLNS/LLNL nor the names of its contributors
may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL LAWRENCE LIVERMORE NATIONAL
SECURITY, LLC, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
Only the outmost loop can be parallelized in this program.
Data race pair: b[i][j]@65:7 vs. b[i][j-1]@65:15
*/
#include <stdlib.h>
int main(int argc, char* argv[])
{
int i,j;
int len = 1000;
if (argc>1)
len = atoi(argv[1]);
int n=len, m=len;
double b[n][m];
#pragma omp parallel for private(i, j)
for (i=0;i<n;i++)
#pragma omp parallel for private(j)
for (j=0;j<m;j++)
b[i][j] = i + j;
#pragma omp parallel for private(i, j)
for (i=0;i<n;i++)
for (j=1;j<m;j++)
b[i][j]=b[i][j-1];
for (i=0;i<n;i++)
for (j=0;j<m;j++)
printf("%d\n", b[i][j]);
return 0;
}
|
target-1.c
|
extern
#ifdef __cplusplus
"C"
#endif
void abort (void);
void
fn1 (double *x, double *y, int z)
{
int i;
for (i = 0; i < z; i++)
{
x[i] = i & 31;
y[i] = (i & 63) - 30;
}
}
#pragma omp declare target
int tgtv = 6;
int
tgt (void)
{
#pragma omp atomic update
tgtv++;
return 0;
}
#pragma omp end declare target
double
fn2 (int x, int y, int z)
{
double b[1024], c[1024], s = 0;
int i, j;
fn1 (b, c, x);
#pragma omp target data map(to: b)
{
#pragma omp target map(tofrom: c, s)
#pragma omp teams num_teams(y) thread_limit(z) reduction(+:s) firstprivate(x)
#pragma omp distribute dist_schedule(static, 4) collapse(1)
for (j=0; j < x; j += y)
#pragma omp parallel for reduction(+:s)
for (i = j; i < j + y; i++)
tgt (), s += b[i] * c[i];
#pragma omp target update from(b, tgtv)
}
return s;
}
double
fn3 (int x)
{
double b[1024], c[1024], s = 0;
int i;
fn1 (b, c, x);
#pragma omp target map(to: b, c) map(tofrom:s)
#pragma omp parallel for reduction(+:s)
for (i = 0; i < x; i++)
tgt (), s += b[i] * c[i];
return s;
}
double
fn4 (int x, double *p)
{
double b[1024], c[1024], d[1024], s = 0;
int i;
fn1 (b, c, x);
fn1 (d + x, p + x, x);
#pragma omp target map(to: b, c[0:x], d[x:x]) map(to:p[x:64 + (x & 31)]) \
map(tofrom: s)
#pragma omp parallel for reduction(+:s)
for (i = 0; i < x; i++)
s += b[i] * c[i] + d[x + i] + p[x + i];
return s;
}
int
main ()
{
double a = fn2 (128, 4, 6);
int b = tgtv;
double c = fn3 (61);
#pragma omp target update from(tgtv)
int d = tgtv;
double e[1024];
double f = fn4 (64, e);
if (a != 13888.0 || b != 6 + 128 || c != 4062.0 || d != 6 + 128 + 61
|| f != 8032.0)
abort ();
return 0;
}
|
@mropes.nim.c
|
/* Generated by Nim Compiler v1.0.10 */
/* (c) 2019 Andreas Rumpf */
/* The generated code is subject to the original license. */
#define NIM_INTBITS 32
#include "nimbase.h"
#include <string.h>
#include <stdio.h>
#undef LANGUAGE_C
#undef MIPSEB
#undef MIPSEL
#undef PPC
#undef R3000
#undef R4000
#undef i386
#undef linux
#undef mips
#undef near
#undef far
#undef powerpc
#undef unix
#define nimfr_(x, y)
#define nimln_(x, y)
typedef struct tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA;
typedef struct TNimType TNimType;
typedef struct TNimNode TNimNode;
typedef struct RootObj RootObj;
typedef struct NimStringDesc NimStringDesc;
typedef struct TGenericSeq TGenericSeq;
typedef struct tySequence__WwUFq9cJ2xKRlsAWVEHyPRg tySequence__WwUFq9cJ2xKRlsAWVEHyPRg;
typedef struct tyObject_Cell__1zcF9cV8XIAtbN8h5HRUB8g tyObject_Cell__1zcF9cV8XIAtbN8h5HRUB8g;
typedef struct tyObject_CellSeq__Axo1XVm9aaQueTOldv8le5w tyObject_CellSeq__Axo1XVm9aaQueTOldv8le5w;
typedef struct tyObject_GcHeap__1TRH1TZMaVZTnLNcIHuNFQ tyObject_GcHeap__1TRH1TZMaVZTnLNcIHuNFQ;
typedef struct tyObject_GcStack__7fytPA5bBsob6See21YMRA tyObject_GcStack__7fytPA5bBsob6See21YMRA;
typedef struct tyObject_MemRegion__x81NhDv59b8ercDZ9bi85jyg tyObject_MemRegion__x81NhDv59b8ercDZ9bi85jyg;
typedef struct tyObject_SmallChunk__tXn60W2f8h3jgAYdEmy5NQ tyObject_SmallChunk__tXn60W2f8h3jgAYdEmy5NQ;
typedef struct tyObject_BigChunk__Rv9c70Uhp2TytkX7eH78qEg tyObject_BigChunk__Rv9c70Uhp2TytkX7eH78qEg;
typedef struct tyObject_LLChunk__XsENErzHIZV9bhvyJx56wGw tyObject_LLChunk__XsENErzHIZV9bhvyJx56wGw;
typedef struct tyObject_IntSet__EZObFrE3NC9bIb3YMkY9crZA tyObject_IntSet__EZObFrE3NC9bIb3YMkY9crZA;
typedef struct tyObject_Trunk__W0r8S0Y3UGke6T9bIUWnnuw tyObject_Trunk__W0r8S0Y3UGke6T9bIUWnnuw;
typedef struct tyObject_AvlNode__IaqjtwKhxLEpvDS9bct9blEw tyObject_AvlNode__IaqjtwKhxLEpvDS9bct9blEw;
typedef struct tyObject_HeapLinks__PDV1HBZ8CQSQJC9aOBFNRSg tyObject_HeapLinks__PDV1HBZ8CQSQJC9aOBFNRSg;
typedef struct tyTuple__ujsjpB2O9cjj3uDHsXbnSzg tyTuple__ujsjpB2O9cjj3uDHsXbnSzg;
typedef struct tyObject_GcStat__0RwLoVBHZPfUAcLczmfQAg tyObject_GcStat__0RwLoVBHZPfUAcLczmfQAg;
typedef struct tyObject_CellSet__jG87P0AI9aZtss9ccTYBIISQ tyObject_CellSet__jG87P0AI9aZtss9ccTYBIISQ;
typedef struct tyObject_PageDesc__fublkgIY4LG3mT51LU2WHg tyObject_PageDesc__fublkgIY4LG3mT51LU2WHg;
typedef tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* tyArray__USLYl0Lpkimm4FABiJ3ldA[4096];
typedef NU8 tyEnum_TNimKind__jIBKr1ejBgsfM33Kxw4j7A;
typedef NU8 tySet_tyEnum_TNimTypeFlag__v8QUszD1sWlSIWZz7mC4bQ;
typedef N_NIMCALL_PTR(void, tyProc__ojoeKfW4VYIm36I9cpDTQIg) (void* p, NI op);
typedef N_NIMCALL_PTR(void*, tyProc__WSm2xU5ARYv9aAR4l0z9c9auQ) (void* p);
struct TNimType {
NI size;
tyEnum_TNimKind__jIBKr1ejBgsfM33Kxw4j7A kind;
tySet_tyEnum_TNimTypeFlag__v8QUszD1sWlSIWZz7mC4bQ flags;
TNimType* base;
TNimNode* node;
void* finalizer;
tyProc__ojoeKfW4VYIm36I9cpDTQIg marker;
tyProc__WSm2xU5ARYv9aAR4l0z9c9auQ deepcopy;
};
typedef NU8 tyEnum_TNimNodeKind__unfNsxrcATrufDZmpBq4HQ;
struct TNimNode {
tyEnum_TNimNodeKind__unfNsxrcATrufDZmpBq4HQ kind;
NI offset;
TNimType* typ;
NCSTRING name;
NI len;
TNimNode** sons;
};
struct RootObj {
TNimType* m_type;
};
struct TGenericSeq {
NI len;
NI reserved;
};
struct NimStringDesc {
TGenericSeq Sup;
NIM_CHAR data[SEQ_DECL_SIZE];
};
struct tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA {
RootObj Sup;
tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* left;
tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* right;
NI L;
NimStringDesc* data;
};
typedef N_NIMCALL_PTR(void, tyProc__T4eqaYlFJYZUv9aG9b1TV0bQ) (void);
struct tyObject_Cell__1zcF9cV8XIAtbN8h5HRUB8g {
NI refcount;
TNimType* typ;
};
struct tyObject_GcStack__7fytPA5bBsob6See21YMRA {
void* bottom;
};
struct tyObject_CellSeq__Axo1XVm9aaQueTOldv8le5w {
NI len;
NI cap;
tyObject_Cell__1zcF9cV8XIAtbN8h5HRUB8g** d;
};
typedef tyObject_SmallChunk__tXn60W2f8h3jgAYdEmy5NQ* tyArray__SiRwrEKZdLgxqz9a9aoVBglg[512];
typedef NU32 tyArray__BHbOSqU1t9b3Gt7K2c6fQig[24];
typedef tyObject_BigChunk__Rv9c70Uhp2TytkX7eH78qEg* tyArray__N1u1nqOgmuJN9cSZrnMHgOQ[32];
typedef tyArray__N1u1nqOgmuJN9cSZrnMHgOQ tyArray__B6durA4ZCi1xjJvRtyYxMg[24];
typedef tyObject_Trunk__W0r8S0Y3UGke6T9bIUWnnuw* tyArray__lh2A89ahMmYg9bCmpVaplLbA[256];
struct tyObject_IntSet__EZObFrE3NC9bIb3YMkY9crZA {
tyArray__lh2A89ahMmYg9bCmpVaplLbA data;
};
typedef tyObject_AvlNode__IaqjtwKhxLEpvDS9bct9blEw* tyArray__0aOLqZchNi8nWtMTi8ND8w[2];
struct tyObject_AvlNode__IaqjtwKhxLEpvDS9bct9blEw {
tyArray__0aOLqZchNi8nWtMTi8ND8w link;
NI key;
NI upperBound;
NI level;
};
struct tyTuple__ujsjpB2O9cjj3uDHsXbnSzg {
tyObject_BigChunk__Rv9c70Uhp2TytkX7eH78qEg* Field0;
NI Field1;
};
typedef tyTuple__ujsjpB2O9cjj3uDHsXbnSzg tyArray__LzOv2eCDGiceMKQstCLmhw[30];
struct tyObject_HeapLinks__PDV1HBZ8CQSQJC9aOBFNRSg {
NI len;
tyArray__LzOv2eCDGiceMKQstCLmhw chunks;
tyObject_HeapLinks__PDV1HBZ8CQSQJC9aOBFNRSg* next;
};
struct tyObject_MemRegion__x81NhDv59b8ercDZ9bi85jyg {
NI minLargeObj;
NI maxLargeObj;
tyArray__SiRwrEKZdLgxqz9a9aoVBglg freeSmallChunks;
NU32 flBitmap;
tyArray__BHbOSqU1t9b3Gt7K2c6fQig slBitmap;
tyArray__B6durA4ZCi1xjJvRtyYxMg matrix;
tyObject_LLChunk__XsENErzHIZV9bhvyJx56wGw* llmem;
NI currMem;
NI maxMem;
NI freeMem;
NI occ;
NI lastSize;
tyObject_IntSet__EZObFrE3NC9bIb3YMkY9crZA chunkStarts;
tyObject_AvlNode__IaqjtwKhxLEpvDS9bct9blEw* root;
tyObject_AvlNode__IaqjtwKhxLEpvDS9bct9blEw* deleted;
tyObject_AvlNode__IaqjtwKhxLEpvDS9bct9blEw* last;
tyObject_AvlNode__IaqjtwKhxLEpvDS9bct9blEw* freeAvlNodes;
NIM_BOOL locked;
NIM_BOOL blockChunkSizeIncrease;
NI nextChunkSize;
tyObject_AvlNode__IaqjtwKhxLEpvDS9bct9blEw bottomData;
tyObject_HeapLinks__PDV1HBZ8CQSQJC9aOBFNRSg heapLinks;
};
struct tyObject_GcStat__0RwLoVBHZPfUAcLczmfQAg {
NI stackScans;
NI cycleCollections;
NI maxThreshold;
NI maxStackSize;
NI maxStackCells;
NI cycleTableSize;
NI64 maxPause;
};
struct tyObject_CellSet__jG87P0AI9aZtss9ccTYBIISQ {
NI counter;
NI max;
tyObject_PageDesc__fublkgIY4LG3mT51LU2WHg* head;
tyObject_PageDesc__fublkgIY4LG3mT51LU2WHg** data;
};
struct tyObject_GcHeap__1TRH1TZMaVZTnLNcIHuNFQ {
tyObject_GcStack__7fytPA5bBsob6See21YMRA stack;
NI cycleThreshold;
NI zctThreshold;
tyObject_CellSeq__Axo1XVm9aaQueTOldv8le5w zct;
tyObject_CellSeq__Axo1XVm9aaQueTOldv8le5w decStack;
tyObject_CellSeq__Axo1XVm9aaQueTOldv8le5w tempStack;
NI recGcLock;
tyObject_MemRegion__x81NhDv59b8ercDZ9bi85jyg region;
tyObject_GcStat__0RwLoVBHZPfUAcLczmfQAg stat;
tyObject_CellSet__jG87P0AI9aZtss9ccTYBIISQ marked;
tyObject_CellSeq__Axo1XVm9aaQueTOldv8le5w additionalRoots;
NI gcThreadId;
};
typedef NU8 tyEnum_FileMode__ZJfK20XeZ9bv2j1pZjw9aswg;
typedef NIM_CHAR tyArray__9bKy7UA2LOi2vzOViufaW1Q[1024];
struct tySequence__WwUFq9cJ2xKRlsAWVEHyPRg {
TGenericSeq Sup;
tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* data[SEQ_DECL_SIZE];
};
N_NIMCALL(void, nimGCvisit)(void* d, NI op);
static N_NIMCALL(void, Marker_tyRef__4hi0XQqK9aLiPuWT9acsXm9aQ)(void* p, NI op);
static N_NIMCALL(void, TM__Vw9cfUOQOae9b9bzZBlucMZQg_3)(void);
N_NIMCALL(void, nimRegisterGlobalMarker)(tyProc__T4eqaYlFJYZUv9aG9b1TV0bQ markerProc);
N_NIMCALL(NimStringDesc*, mnewString)(NI len);
N_LIB_PRIVATE N_NIMCALL(NI, len__9b0YRltzV3kNSE9aQTsG82wg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* a);
N_NIMCALL(NimStringDesc*, setLengthStr)(NimStringDesc* s, NI newLen);
N_NIMCALL(void*, newSeq)(TNimType* typ, NI len);
static N_INLINE(void, asgnRef)(void** dest, void* src);
static N_INLINE(void, incRef__AT1eRuflKWyTTBdLjEDZbg_3system)(tyObject_Cell__1zcF9cV8XIAtbN8h5HRUB8g* c);
static N_INLINE(tyObject_Cell__1zcF9cV8XIAtbN8h5HRUB8g*, usrToCell__QFQqcLB3lgOdwipkv9a60xwsystem)(void* usr);
static N_INLINE(void, decRef__AT1eRuflKWyTTBdLjEDZbgsystem)(tyObject_Cell__1zcF9cV8XIAtbN8h5HRUB8g* c);
static N_INLINE(void, rtlAddZCT__AT1eRuflKWyTTBdLjEDZbg_2system)(tyObject_Cell__1zcF9cV8XIAtbN8h5HRUB8g* c);
N_LIB_PRIVATE N_NOINLINE(void, addZCT__Y66tOYFjgwJ0k4aLz4bc0Q)(tyObject_CellSeq__Axo1XVm9aaQueTOldv8le5w* s, tyObject_Cell__1zcF9cV8XIAtbN8h5HRUB8g* c);
static N_INLINE(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, pop__9c4Y4hTtvRqjj2EC8KP9aqDAsystem)(tySequence__WwUFq9cJ2xKRlsAWVEHyPRg** s);
N_NIMCALL(TGenericSeq*, setLengthSeqV2)(TGenericSeq* s, TNimType* typ, NI newLen);
N_NIMCALL(void, unsureAsgnRef)(void** dest, void* src);
N_NIMCALL(TGenericSeq*, incrSeqV3)(TGenericSeq* s, TNimType* typ);
static N_INLINE(void, appendString)(NimStringDesc* dest, NimStringDesc* src);
static N_INLINE(void, copyMem__M04YC71iJg1N7gBF3HZTngsystem)(void* dest, void* source, NI size);
static N_INLINE(void, nimCopyMem)(void* dest, void* source, NI size);
N_NIMCALL(NimStringDesc*, resizeString)(NimStringDesc* dest, NI addlen);
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA)(NimStringDesc* frmt, tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0);
N_LIB_PRIVATE N_NIMCALL(void, add__yG4AKzsBRS1W4MANDlXQeg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** a, NimStringDesc* b);
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, amp___Z7W1o5nPSc3ExfO5f7j1Gg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* a, NimStringDesc* b);
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, amp___ShdZ6VrAQkY0nWR9a39b9bGdQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* a, tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* b);
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, newRope__dBdikNFB2Y7QJ9aVJE7dGHg)(NimStringDesc* data);
N_NIMCALL(void*, newObj)(TNimType* typ, NI size);
N_NIMCALL(NimStringDesc*, copyStringRC1)(NimStringDesc* src);
static N_INLINE(void, nimGCunrefNoCycle)(void* p);
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, rope__yShmEg9cffWxI7s5XzEKBow)(NimStringDesc* s);
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, insertInCache__yShmEg9cffWxI7s5XzEKBow_2)(NimStringDesc* s);
N_LIB_PRIVATE N_NIMCALL(NI, hash__6PCYkKlCNhq9cnRLnqWKkwQ)(NimStringDesc* x);
static N_INLINE(NIM_BOOL, eqStrings)(NimStringDesc* a, NimStringDesc* b);
static N_INLINE(NIM_BOOL, equalMem__Bj9c9cm9cBM9coLsuNsT5BvZ9awsystem)(void* a, void* b, NI size);
static N_INLINE(int, nimCmpMem)(void* a, void* b, NI size);
N_LIB_PRIVATE N_NIMCALL(void, add__IM4kcMNkkOLJtqdEqSxR8A)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** a, tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* b);
N_LIB_PRIVATE N_NIMCALL(void, failedAssertImpl__W9cjVocn1tjhW7p7xohJj6A)(NimStringDesc* msg);
N_NIMCALL(NimStringDesc*, rawNewString)(NI space);
N_LIB_PRIVATE N_NIMCALL(NimStringDesc*, substr__2yh9cer0ymNRHlOOg8P7IuA)(NimStringDesc* s, NI first, NI last);
N_NIMCALL(NimStringDesc*, nimInt64ToStr)(NI64 x);
N_LIB_PRIVATE N_NIMCALL(void, write__PArlm09bKklm2BLsCg6YtaA)(FILE* f, NimStringDesc* s);
N_LIB_PRIVATE N_NIMCALL(NIM_BOOL, open__gq12VLhVO0NBzUTnGgz4nw)(FILE** f, NimStringDesc* filename, tyEnum_FileMode__ZJfK20XeZ9bv2j1pZjw9aswg mode, NI bufSize);
N_LIB_PRIVATE N_NIMCALL(NIM_BOOL, equalsFile__9bihNFg7Qajcg9arfx5cr9aHA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* r, FILE* f);
static N_INLINE(void, nimZeroMem)(void* p, NI size);
static N_INLINE(void, nimSetMem__JE6t4x7Z3v2iVz27Nx0MRAmemory)(void* a, int v, NI size);
N_LIB_PRIVATE N_NIMCALL(NI, readBuffer__f3MIZh4IV2qRTxlOpckbRA_2)(FILE* f, void* buffer, NI len);
static N_INLINE(NCSTRING, nimToCStringConv)(NimStringDesc* s);
N_LIB_PRIVATE N_NIMCALL(void, close__fU6ZlJAtQ9bre04EDZLdGsA_3)(FILE* f);
N_LIB_PRIVATE N_NIMCALL(void, writeRope__FwuzOBq6SLlanVUstm8q9cA)(FILE* f, tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* r);
N_LIB_PRIVATE N_NIMCALL(NIM_BOOL, equalsFile__Wiam9c8x73Mtmbj0r4Ppikg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* r, NimStringDesc* filename);
N_LIB_PRIVATE N_NIMCALL(NIM_BOOL, writeRope__LLRRC42xWBSkxzV9bsPu7lA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* head, NimStringDesc* filename);
tyArray__USLYl0Lpkimm4FABiJ3ldA cache__WGMp5Wo1NlgbAMOysPIfmQ;
extern TNimType NTI__ytyiCJqK439aF9cIibuRVpAg_;
TNimType NTI__OFzf0kSiPTcNreUIeJgWVA_;
extern TNimType NTI__rR5Bzr1D5krxoo1NcNyeMA_;
extern TNimType NTI__77mFvmsOLKik79ci2hXkHEg_;
TNimType NTI__4hi0XQqK9aLiPuWT9acsXm9aQ_;
TNimType NTI__USLYl0Lpkimm4FABiJ3ldA_;
NI gCacheTries__5GfZTThHPBfB9bjRZdFluBw;
NI gCacheMisses__fLRm9am8S0daYBVNK6JKyBg;
NI gCacheIntTries__opyfsNv023Md1P05mqsDew;
extern TNimType NTI__WwUFq9cJ2xKRlsAWVEHyPRg_;
extern tyObject_GcHeap__1TRH1TZMaVZTnLNcIHuNFQ gch__IcYaEuuWivYAS86vFMTS3Q;
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_4, "$", 1);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_5, "ropes.nim(238, 20) `false` invalid format string: ", 50);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_6, "ropes.nim(250, 20) `false` invalid format string: ", 50);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_7, "ropes.nim(253, 20) `false` invalid format string: ", 50);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_8, "\012", 1);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_9, "ropes.nim(263, 18) `false` invalid format string: ", 50);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_10, "[$1, $2, $3]", 12);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_11, "FR_.len-=$1;$n", 14);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_12, "} $1: ;$n", 9);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_13, "}$n", 3);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_14, "FR_.len+=$1;$n", 14);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_15, "void", 4);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_16, ", ", 2);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_17, "$1 $2;$n", 8);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_18, "typedef $1 $2 $2;$n", 19);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_19, "*", 1);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_20, " ", 1);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_21, ", NI $1Len_$2", 13);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_22, " Result", 7);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_23, "$1$2($3, $4)$5", 14);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_24, "(*$1)", 5);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_25, "static TNimType* $1;$n", 22);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_26, "\011$1 = (TNimType*)hcrGetGlobal($2, \"$1\");$n", 42);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_27, "extern TNimType $1;$n", 21);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_28, "NTI$1_", 6);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_29, "$1.size = sizeof($2);$n$1.kind = $3;$n$1.base = $4;$n", 53);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_30, "$1.flags = $2;$n", 16);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_31, "$1.name = $2;$n", 15);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_32, "$1.nextType = nimTypeRoot; nimTypeRoot=&$1;$n", 45);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_33, "\011hcrRegisterGlobal($2, \"$1\", sizeof(TNimType), NULL, (void**)&$"
"1);$n", 68);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_34, "TNimType $1;$n", 14);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_35, "$1[$2]", 6);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_36, "static TNimNode** $1;$n", 23);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_37, "\011hcrRegisterGlobal($3, \"$1\", sizeof(TNimNode*) * $2, NULL, (voi"
"d**)&$1);$n", 74);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_38, "static TNimNode* $1[$2];$n", 26);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_39, "$1[$2] = &$3;$n", 15);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_40, "$1.kind = 1;$n$1.offset = offsetof($2, Field$3);$n$1.typ = $4;$"
"n$1.name = \"Field$3\";$n", 86);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_41, "$1.len = $2; $1.kind = 2; $1.sons = &$3[0];$n", 45);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_42, "$1.len = $2; $1.kind = 2;$n", 27);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_43, "$1.node = &$2;$n", 16);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_44, "static N_NIMCALL(void, $1)(void* p, NI op)", 42);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_45, "$1 a;$n", 7);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_46, "a = ($1)p;$n", 12);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_47, "for ($1 = 0; $1 < $2; $1++) {$n", 31);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_48, "($1 \? $1->$2 : 0)", 17);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_49, "$1.Sup", 6);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_50, "#pragma pack(push, 1)$nstruct{", 30);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_51, "};$n", 4);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_52, "#pragma pack(pop)$n", 19);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_53, "union{$n$1};$n", 14);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_54, "$1 $2[SEQ_DECL_SIZE];$n", 23);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_55, "$1 $2:$3;$n", 11);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_56, "switch ($1.$2) {$n", 18);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_57, "case $1 ... $2:$n", 17);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_58, "(-2147483647 -1)", 16);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_59, "IL64($1)", 8);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_60, "(IL64(-9223372036854775807) - IL64(1))", 38);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_61, "NIM_TRUE", 8);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_62, "NIM_FALSE", 9);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_63, "(($1) $2)", 9);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_64, "static NIM_CONST $1 $2 = {NIM_NIL,NIM_NIL};$n", 45);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_65, "STRING_LITERAL($1, $2, $3);$n", 29);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_66, "static const struct {$n NI cap; void* allocator; NIM_CHAR data"
"[$2+1];$n} $1 = { $2, NIM_NIL, $3 };$n", 101);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_67, "static const NimStringV2 $1 = {$2, (NimStrPayload*)&$3};$n", 58);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_68, "case $1:$n", 10);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_69, "default:$n", 10);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_70, "break;$n", 8);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_71, "} $n", 4);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_72, "$1.$2", 5);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_73, "$1$3[$2]", 8);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_74, "$1 {$n$2$3$4}\012", 14);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_75, "$1;\012", 4);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_76, "N_NIMCALL_PTR(void, $1)(void*, NI);\012", 36);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_77, "\011$1 = (N_NIMCALL_PTR(void, )(void*, NI)) hcrRegisterProc($3, \"$"
"1\", (void*)$2);\012", 79);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_78, "$1.marker = $2;$n", 17);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_79, "$1.len = $2; $1.kind = 0;$n$3.node = &$1;$n", 43);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_80, "$1.offset = $2;$n", 17);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_81, "NI $1;$n", 8);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_82, "static char* NIM_CONST $1[$2] = {$n$3};$n", 41);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_83, "for ($1 = 0; $1 < $2; $1++) {$n$3[$1+$4].kind = 1;$n$3[$1+$4].o"
"ffset = $1;$n$3[$1+$4].name = $5[$1];$n$6[$1] = &$3[$1+$4];$n}$n", 127);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_84, "$1.len = $2; $1.kind = 2; $1.sons = &$3[0];$n$4.node = &$1;$n", 61);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_85, "$1.flags = 1<<2;$n", 18);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_86, "$1.destructor = (void*)$2; $1.size = sizeof($3); $1.name = $4;$"
"n", 64);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_87, "NimDT_$1_$2", 11);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_88, "$1.kind = 3;$n$1.offset = offsetof($2, $3);$n$1.typ = $4;$n$1.n"
"ame = $5;$n$1.sons = &$6[0];$n$1.len = $7;$n", 107);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_89, "TNimNode* $1[$2];$n", 19);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_90, "$1.kind = 1;$n$1.offset = offsetof($2, $3);$n$1.typ = $4;$n$1.n"
"ame = $5;$n", 74);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_91, "$1.deepcopy =(void* (N_RAW_NIMCALL*)(void*))$2;$n", 49);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_92, "Result", 6);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_93, "$N#line $2 $1$N", 15);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_94, "struct {$1} GCFRAME_;$n", 23);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_95, "\011}BeforeRet_: ;$n", 17);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_96, "}$N", 3);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_97, "\011$1 = ($3) hcrRegisterProc($4, \"$1\", (void*)$2);$n", 50);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_98, "$1(*)$2", 7);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_99, "static void* $1;$n", 18);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_100, "\011$1 = ($2) ($3$4));$n", 21);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_101, "$2 $1;$n", 8);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_102, "\011$1 = ($2) hcrRegisterProc($3, \"$1\", (void*)$1);$n", 50);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_103, "\011$1 = ($2) hcrGetProc($3, \"$1\");$n", 34);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_104, " $1;$n", 6);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_105, "\011$1 = ($2*)hcrGetGlobal($3, \"$1\");$n", 36);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_106, "NIM_CHECK_SIZE($1, $2);$n", 25);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_107, "typedef NI32 $1;$n", 18);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_108, "typedef NU8 $1;$n", 17);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_109, "typedef NU16 $1;$n", 18);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_110, "typedef NI64 $1;$n", 18);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_111, "typedef $1_PTR($2, $3) $4;$n", 28);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_112, "typedef struct {$nN_NIMCALL_PTR($2, ClP_0) $3;$nvoid* ClE_0;$n}"
" $1;$n", 69);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_113, "typedef $1 $2[1];$n", 19);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_114, "typedef $1 $2[$3];$n", 20);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_115, " {$n", 4);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_116, "char dummy;$n", 13);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_117, "TY", 2);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_118, "typedef $1 $2;$n", 16);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_119, "$1 $2 {$n", 9);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_120, "$1 Field$2;$n", 13);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_121, "typedef NU$2 $1;$n", 18);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_122, "typedef NU8 $1[$2];$n", 21);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_123, "Field$1", 7);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_124, "NIM_CONST $1 $2 = $3;$n", 23);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_125, ",$n", 3);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_126, "{$1, ($2*)&$3}", 14);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_127, "{{$1, $1 | NIM_STRLIT_FLAG}", 27);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_128, "(($1)&$2)", 9);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_129, "{NIM_NIL,NIM_NIL}", 17);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_130, "{(($1) $2),NIM_NIL}", 19);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_131, "$1,$n", 5);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_132, "$1", 2);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_133, "{{$1}}", 6);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_134, "{$1}$n", 6);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_135, "{$1, (NimStrPayload*)&$2}", 25);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_136, "extern NIM_CONST $1 $2;$n", 25);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_137, "goto NIMSTATE_$#;$n", 19);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_138, "$2* $1;$n", 9);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_139, "\011NimThreadVars* NimTV_;$n", 25);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_140, "static N_NIMCALL(void, $1)(void)", 32);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_141, "$1 {$n$2$3$4}$n", 15);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_142, "$1;$n", 5);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_143, "//", 2);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_144, "$#;$n", 5);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_145, "$#($#);$n", 9);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_146, "$# = $#;$n", 10);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_147, "NULL", 4);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_148, "((NU8)($1))", 11);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_149, "($4*)(($1)+($2)), ($3)-($2)+1", 29);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_150, "($5*)($1)+(($2)-($4)), ($3)-($2)+1", 34);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_151, "($4*)($1)+($2), ($3)-($2)+1", 27);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_152, "($5*)(*$1)$4+($2), ($3)-($2)+1", 30);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_153, "($5*)$1$4+($2), ($3)-($2)+1", 27);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_154, "$1, $1Len_0", 11);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_155, "(*$1)$3, $2", 11);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_156, "$1$3, $2", 8);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_157, "$1, $2", 6);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_158, "$1.ClP_0($3$1.ClE_0);$n", 23);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_159, "$1.ClE_0\? $1.ClP_0($3$1.ClE_0):(($4)($1.ClP_0))($2);$n", 54);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_160, "$1.ClP_0($3$1.ClE_0)", 20);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_161, "$1.ClE_0\? $1.ClP_0($3$1.ClE_0):(($4)($1.ClP_0))($2)", 51);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_162, "(", 1);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_163, ")", 1);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_164, ";$n", 3);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_165, ");$n", 4);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_166, "[", 1);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_167, ": ", 2);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_168, "Result: ", 8);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_169, "];$n", 4);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_170, "]", 1);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_171, "if ($1) goto $2;$n", 18);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_172, "if (!($1)) goto $2;$n", 21);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_173, "$1: ;$n", 7);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_174, "!($1)", 5);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_175, "($3)((NU$2) ~($1))", 18);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_176, "-($1)", 5);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_177, "((NI$2)-($1))", 13);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_178, "($1 > 0\? ($1) : -($1))", 22);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_179, "(($4)($1) + ($4)($2))", 21);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_180, "(($4)($1) - ($4)($2))", 21);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_181, "(($4)($1) * ($4)($2))", 21);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_182, "(($4)($1) / ($4)($2))", 21);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_183, "($4)((NU$5)($1) >> (NU$3)($2))", 30);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_184, "($4)((NU$3)($1) << (NU$3)($2))", 30);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_185, "($4)((NI$3)($1) >> (NU$3)($2))", 30);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_186, "($4)($1 & $2)", 13);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_187, "($4)($1 | $2)", 13);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_188, "($4)($1 ^ $2)", 13);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_189, "(($1 <= $2) \? $1 : $2)", 22);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_190, "(($1 >= $2) \? $1 : $2)", 22);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_191, "($4)((NU$3)($1) + (NU$3)($2))", 29);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_192, "($4)((NU$3)($1) - (NU$3)($2))", 29);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_193, "($4)((NU$3)($1) * (NU$3)($2))", 29);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_194, "($4)((NU$3)($1) / (NU$3)($2))", 29);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_195, "($4)((NU$3)($1) % (NU$3)($2))", 29);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_196, "($1 == $2)", 10);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_197, "($1 <= $2)", 10);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_198, "($1 < $2)", 9);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_199, "((NU$3)($1) <= (NU$3)($2))", 26);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_200, "((NU$3)($1) < (NU$3)($2))", 25);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_201, "((NU64)($1) <= (NU64)($2))", 26);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_202, "((NU64)($1) < (NU64)($2))", 25);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_203, "((NU8)($1) == (NU8)($2))", 24);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_204, "((NU8)($1) <= (NU8)($2))", 24);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_205, "((NU8)($1) < (NU8)($2))", 23);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_206, "($1 != $2)", 10);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_207, "($1.ClP_0 == $2.ClP_0 && $1.ClE_0 == $2.ClE_0)", 46);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_208, "($1)($2 $3 $4)", 14);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_209, "($#)($#)", 8);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_210, ".Sup", 4);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_211, "$1.m_type == $2", 15);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_212, "static TNimType* $#[2];$n", 25);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_213, "sizeof($1)", 10);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_214, "$1->finalizer = (void*)$2;$n", 28);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_215, "((NI)sizeof($1))", 16);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_216, "((NI)alignof($1))", 17);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_217, "((NI)offsetof($1, $2))", 22);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_218, "(*($1*) ($2))", 13);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_219, "(($1) ($2))", 11);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_220, "(($1) (ptrdiff_t) ($2))", 23);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_221, "(*($1*) (&$2))", 14);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_222, "($1-1)", 6);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_223, "$1 |= ((NU8)1)<<(($2) & 7);$n", 29);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_224, "($1- $2)", 8);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_225, "$1 |= ((NU16)1)<<(($2) & 15);$n", 31);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_226, "$1 |= ((NU32)1)<<(($2) & 31);$n", 31);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_227, "$1 |= ((NU64)1)<<(($2) & 63);$n", 31);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_228, "$1 &= ~(((NU8)1) << (($2) & 7));$n", 34);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_229, "$1 &= ~(((NU16)1) << (($2) & 15));$n", 36);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_230, "$1 &= ~(((NU32)1) << (($2) & 31));$n", 36);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_231, "$1 &= ~(((NU64)1) << (($2) & 63));$n", 36);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_232, "$1 >= $2 && $1 <= $3", 20);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_233, "$1 == $2", 8);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_234, "(($1 &((NU8)1<<((NU)($2)&7U)))!=0)", 34);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_235, "(($1 &((NU16)1<<((NU)($2)&15U)))!=0)", 36);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_236, "(($1 &((NU32)1<<((NU)($2)&31U)))!=0)", 36);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_237, "(($1 &((NU64)1<<((NU)($2)&63U)))!=0)", 36);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_238, "(($1[(NU)($2)>>3] &(1U<<((NU)($2)&7U)))!=0)", 43);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_239, "$1[(NU)($2)>>3] |=(1U<<($2&7U));$n", 34);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_240, "$1[(NU)($2)>>3] &= ~(1U<<($2&7U));$n", 36);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_241, "for ($1 = 0; $1 < $2; $1++) $n $3[$1] = $4[$1] $6 $5[$1];$n", 60);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_242, "static NIM_CONST $1 $2 = $3;$n", 30);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_243, "for ($1 = $3; $1 <= $4; $1++) $n$2[(NU)($1)>>3] |=(1U<<((NU)($1"
")&7U));$n", 72);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_244, "$1[(NU)($2)>>3] |=(1U<<((NU)($2)&7U));$n", 40);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_245, "$1 = 0;$n", 9);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_246, "for ($1 = $3; $1 <= $4; $1++) $n$2 |=(($5)(1)<<(($1)%(sizeof($5"
")*8)));$n", 72);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_247, "$1 |=(($3)(1)<<(($2)%(sizeof($3)*8)));$n", 40);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_248, "$1.Field$2", 10);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_249, "LOC$1.source", 12);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_250, "LOC$#.dest", 10);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_251, ".Field$1", 8);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_252, ".$1", 3);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_253, "TFrame $1;$n", 12);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_254, "if (!$1) goto $2;$n", 19);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_255, "goto $1;$n", 10);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_256, "TMP$1_", 6);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_257, "static void* $#[$#] = {", 23);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_258, "&&TMP$#_, ", 10);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_259, "&&TMP$#_};$n", 12);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_260, "goto *$#[$#];$n", 15);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_261, "TMP$#_:$n", 9);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_262, "case $1: $n$2break;$n", 21);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_263, "goto LA$1_;$n", 13);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_264, "LA$1_: ;$n", 10);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_265, "NIMSTATE_$#:$n", 14);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_266, "switch ($1) {$n", 15);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_267, "default: __assume(0);$n", 23);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_268, "goto BeforeRet_;$n", 18);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_269, "throw;$n", 8);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_270, "else", 4);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_271, "throw $1;$n", 11);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_272, "$n#pragma omp $4$nfor ($1 = $2; $1 <= $3; ++$1)", 47);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_273, "$n#pragma omp $5$nfor ($1 = $2; $1 <= $3; $1 += $4)", 51);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_274, "case -1:$n", 10);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_275, " goto BeforeRet_;$n", 19);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_276, "case $2: goto $1$2;$n", 21);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_277, "(((NI*) $1)[1] < 0)", 19);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_278, "((((NI*) $1.ClE_0)[1]) < 0)", 27);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_279, "$1 N_NIMCALL(void, $2)(void) {$N", 32);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_280, "\011int* nim_hcr_dummy_ = 0;$n\011NIM_BOOL nim_hcr_do_init_ = hcrRegi"
"sterGlobal($1, \"module_initialized_\", 1, NULL, (void**)&nim_hcr_"
"dummy_);$n", 137);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_281, "{$N", 3);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_282, "\011TFrame FR_; FR_.len = 0;$N", 27);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_283, "}$N$N", 5);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_284, "N_LIB_EXPORT N_NIMCALL(void, $1)(void* handle, N_NIMCALL_PTR(vo"
"id*, getProcAddr)(void*, char*)) {$N", 99);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_285, "static $2 $1;$n", 15);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_286, "\011$1 = ($2) $3($4, $5);$n", 24);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_287, "NIM_EXTERNC N_NIMCALL(void, nimLoadProcs$1)(void) {$2}$N$N", 58);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_288, "N_LIB_EXPORT N_NIMCALL(void, HcrCreateTypeInfos)(void) {$N", 58);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_289, "$nN_LIB_PRIVATE const char* hcr_module_list[] = {$n", 51);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_290, "\011$1,$n", 6);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_291, "\011\"\"};$n", 7);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_292, "$nN_LIB_EXPORT N_NIMCALL(void**, HcrGetImportedModules)() { ret"
"urn (void**)hcr_module_list; }$n", 95);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_293, "$nN_LIB_EXPORT N_NIMCALL(char*, HcrGetSigHash)() { return \"$1\";"
" }$n$n", 69);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_294, "static void* hcr_handle;$N", 26);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_295, "N_LIB_EXPORT N_NIMCALL(void, $1)(void);$N", 41);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_296, "N_LIB_EXPORT N_NIMCALL(void, $1)(void*, N_NIMCALL_PTR(void*, ge"
"tProcAddr)(void*, char*));$N", 91);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_297, "N_LIB_EXPORT N_NIMCALL(void, HcrCreateTypeInfos)(void);$N", 57);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_298, "\011$1();$N", 8);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_299, "\011hcrInit((void**)hcr_module_list, $1, $2, $3, hcr_handle, nimGe"
"tProcAddr);$n", 76);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_300, "\011$1(hcr_handle, nimGetProcAddr);$N", 34);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_301, "\011hcrAddModule($1);\012", 19);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_302, "\011HcrCreateTypeInfos();$N", 24);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_303, "\011hcrRegisterGlobal($1, \"cmdCount\", sizeof(cmd_count), NULL, (vo"
"id**)&cmd_count);$N", 82);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_304, "\011hcrRegisterGlobal($1, \"cmdLine\", sizeof(cmd_line), NULL, (void"
"**)&cmd_line);$N", 79);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_305, "N_LIB_PRIVATE N_NIMCALL(void, $1)(void);$N", 42);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_306, "$#NI NimThreadVarsSize(){return (NI)sizeof(NimThreadVars);}$n", 61);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_307, "/* Generated by Nim Compiler v$1 */$N/* (c) 2019 Andreas Rump"
"f */$N/* The generated code is subject to the original license. "
"*/$N", 131);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_308, "/* Generated by Nim Compiler v$1 */$N/* (c) 2019 Andreas Rump"
"f */$N/* The generated code is subject to the original license. "
"*/$N/* Compiled for: $2, $3, $4 */$N/* Command for C compiler:$n"
" $5 */$N", 201);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_309, "#define NIM_INTBITS $1\012", 23);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_310, "typedef struct {$1} NimThreadVars;$n", 36);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_311, "#include \"$1\"$N", 15);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_312, "#include $1$N", 13);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_313, "--file:r\"$1\"$N", 14);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_314, "\012[Symbols]$n$1", 14);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_315, "/* Generated by Nim Compiler v$1 */$N/* (c) 2017 Andreas Rump"
"f */$N/* The generated code is subject to the original license. "
"*/$N", 131);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_316, "__$1__", 6);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_317, "#ifndef $1$n#define $1$n", 24);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_318, "N_CDECL(void, NimMain)(void);$n", 31);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_319, "#endif /* $1 */$n", 17);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_320, "var F={procname:$1,prev:framePtr,filename:$2,line:0};$n", 55);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_321, "framePtr = F;$n", 15);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_322, "var $1;$n", 9);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_323, "if ($1 == undefined) {$n", 24);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_324, "if ($1 === undefined) {$n", 25);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_325, "var $1 = null;$n", 16);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_326, "var $1_Idx = 0;$n", 17);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_327, "[$1]", 4);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_328, "new $1($2)", 10);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_329, "var $# = null;$n", 16);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_330, "var $#_Idx = 0;$n", 17);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_331, "var $# = $#;$n", 14);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_332, "return [$#, $#];$n", 18);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_333, "return $#;$n", 12);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_334, "BeforeRet: do {$n", 17);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_335, "} while (false);$n", 18);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_336, "try {$n$1} catch (e) {$n alert(\"Unhandled exception:\\n\" + e.mes"
"sage + \"\\n\"$n}", 77);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_337, "function $#() { return $#.apply(this, arguments); }$n", 53);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_338, "function $#($#) {$n$#$#$#$#$#", 29);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_339, "arrayConstr($1, $2, $3)", 23);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_340, "NTI$1", 5);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_341, "var $1 = {size: 0,kind: $2,base: null,node: null,finalizer: nul"
"l};$n", 68);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_342, "$1.base = $2;$n", 15);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_343, "\"$1\": {kind: 1, offset: $1, typ: $2, name: $3, len: 0, sons: nu"
"ll}", 66);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_344, "var NNI$1 = {kind: 2, offset: 0, typ: null, name: null, len: $2"
", sons: {$3}};$n", 79);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_345, "var $1 = {size: 0, kind: $2, base: null, node: null, finalizer:"
" null};$n", 72);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_346, "$1.node = NNI$2;$n", 18);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_347, "var NNI$1 = $2;$n", 17);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_348, "{kind: 2, len: $1, offset: 0, typ: null, name: null, sons: [$2]"
"}", 64);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_349, "{kind: 1, offset: \"$1\", len: 0, typ: $2, name: $3, sons: null}", 62);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_350, "[$1, $2]", 8);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_351, "[setConstr($1), $2]", 19);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_352, "{kind: 3, offset: \"$1\", len: $3, typ: $2, name: $4, sons: [$5]}", 63);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_353, "{kind: 1, offset: \"Field$1\", len: 0, typ: $2, name: \"Field$1\", "
"sons: null}", 74);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_354, "Field$1: $2", 11);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_355, "m_type: $1", 10);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_356, "$#: ", 4);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_357, "({$1})", 6);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_358, "nimCopy(null, $1, $2)", 21);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_359, "Tmp$1", 5);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_360, "var $1 = $2, $3 = $1[0], $3_Idx = $1[1];$n", 42);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_361, "$1 = nimCopy(null, $1, $2);$n", 29);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_362, "$1[0][0]", 8);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_363, "$1[0][1]", 8);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_364, "$1[0]", 5);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_365, "$1[1]", 5);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_366, "makeNimstrLit($1)", 17);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_367, "// line $2 \"$1\"$n", 17);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_368, "F.line = $1;$n", 14);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_369, "($1 || $2)", 10);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_370, "if ($1) $2 = true; else {", 25);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_371, "$2 = $1;", 8);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_372, "($1 && $2)", 10);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_373, "if (!$1) $2 = false; else {", 27);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_374, "$1[0][$1[1]]", 12);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_375, "($1 = $2, $1)", 13);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_376, "$1 = (($5 $2 $3) $4)", 20);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_377, "(($1 $2 $3) $4)", 15);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_378, "addInt($1, $2)", 14);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_379, "($1 + $2)", 9);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_380, "subInt($1, $2)", 14);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_381, "($1 - $2)", 9);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_382, "mulInt($1, $2)", 14);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_383, "($1 * $2)", 9);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_384, "divInt($1, $2)", 14);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_385, "Math.trunc($1 / $2)", 19);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_386, "modInt($1, $2)", 14);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_387, "Math.trunc($1 % $2)", 19);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_388, "($1 / $2)", 9);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_389, "($1 << $2)", 10);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_390, "($1 >> $2)", 10);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_391, "($1 & $2)", 9);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_392, "($1 | $2)", 9);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_393, "($1 ^ $2)", 9);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_394, "nimMin($1, $2)", 14);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_395, "nimMax($1, $2)", 14);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_396, "($1 % $2)", 9);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_397, "negInt($1)", 10);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_398, "negInt64($1)", 12);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_399, "absInt($1)", 10);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_400, "Math.abs($1)", 12);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_401, "+($1)", 5);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_402, "~($1)", 5);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_403, "nimCharToStr($1)", 16);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_404, "nimBoolToStr($1)", 16);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_405, "cstrToNimstr(($1)+\"\")", 21);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_406, "cstrToNimstr($1)", 16);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_407, "(($1 $2) >>> $3)", 16);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_408, "($# == $# && $# == $#)", 22);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_409, "var $1 = $2; $2 = $3; $3 = $1;$n", 32);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_410, "var $1 = $2; $2 = $3; $3 = $1;", 30);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_411, "$1 - 1", 6);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_412, "subInt($1, 1)", 13);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_413, "if ($1 != null) { addChar($3, $2); } else { $3 = [$2]; }", 56);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_414, "if ($1 != null) { $4 += $2; } else { $4 = $2$3; }", 49);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_415, ".slice()", 8);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_416, "if ($1 != null) { $4 = ($4).concat($2); } else { $4 = $2$3; }", 61);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_417, "if ($1 != null) { $3.push($2); } else { $3 = [$2]; }", 52);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_418, "var $1 = nimCopy(null, $2, $3);$n", 33);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_419, "[$1].concat(", 12);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_420, "($1 || []).concat(", 18);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_421, "[$1],", 5);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_422, "$1 || [],", 9);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_423, "[$1])", 5);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_424, "$1 || [])", 9);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_425, "eqStrings($1, $2)", 17);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_426, "(cmpStrings($1, $2) <= 0)", 25);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_427, "(cmpStrings($1, $2) < 0)", 24);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_428, "($1 == null)", 12);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_429, "($# == null && $# === 0)", 24);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_430, "$1 = $2;$n", 10);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_431, "$1 = [$3]; $2 = 0;$n", 20);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_432, "$1 = [[$2], 0];$n", 17);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_433, "($1 \? 1:0)", 10);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_434, "($1 != null \? $2.length : 0)", 28);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_435, "$1.length", 9);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_436, "($1 != null \? ($2.length-1) : -1)", 33);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_437, "$1 += $2", 8);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_438, "$1 = addInt($3, $2)", 19);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_439, "$1 -= $2", 8);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_440, "$1 = subInt($3, $2)", 19);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_441, "($1 == null \? $3 = mnewString($2) : $3.length = $2)", 51);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_442, "if ($1 === null) $4 = [];\012 if ($4.length < $2) { "
"for (var i=$4.length;i<$5;++i) $4.push($3); }\012 els"
"e { $4.length = $5; }", 148);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_443, "SetCard($1)", 11);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_444, "SetLt($1, $2)", 13);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_445, "SetLe($1, $2)", 13);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_446, "SetEq($1, $2)", 13);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_447, "SetMul($1, $2)", 14);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_448, "SetPlus($1, $2)", 15);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_449, "SetMinus($1, $2)", 16);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_450, "$1[$2] = true", 13);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_451, "delete $1[$2]", 13);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_452, "($1[$2] != undefined)", 21);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_453, "$1 = new Array($2); for (var i=0;i<$2;++i) {$1[i]=$3;}", 54);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_454, "[]", 2);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_455, "($1.m_type == $2)", 17);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_456, "isObj($1.m_type, $2)", 20);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_457, "$1 = null, $2 = 0;$n", 20);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_458, "$1 = genericReset($3, $2);$n", 28);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_459, "($1.slice($2))", 14);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_460, "mnewString($1)", 14);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_461, "mnewString(0)", 13);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_462, "($1 = $2, $1[0]), $1[1]", 23);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_463, "($1 = $2, $1)[0]", 16);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_464, "($1.slice($2, $3+1))", 20);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_465, "var $1 = $2;$n", 14);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_466, "Field$#: [$#, $#]", 17);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_467, "Field$#: $#", 11);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_468, "$#: [$#, $#]", 12);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_469, "$#: $#", 6);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_470, "{$1}", 4);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_471, "(!!($1))", 8);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_472, "(($1)|0)", 8);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_473, "if ($1[$2.$3]$4undefined) { raiseFieldError(makeNimstrLit($5));"
" }$n", 67);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_474, "!==", 3);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_475, "===", 3);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_476, "chckIndx($1, $2, ($3 != null \? $3.length : 0)+$2-1)-$2", 54);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_477, "($1)-$2", 7);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_478, "$1.charCodeAt($2)", 17);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_479, "($1 $2)", 7);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_480, "($1|0)", 6);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_481, "($1 - ($2 $3))", 14);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_482, "null", 4);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_483, "chckRange($1, $2, $3)", 21);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_484, "toJSStr($1)", 11);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_485, "L$1: do {$n", 11);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_486, "} while(false);$n", 17);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_487, "else {$n", 8);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_488, "if ($1) {$n", 11);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_489, "L$1: while (true) {$n", 21);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_490, "if (!$1) break L$2;$n", 21);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_491, "switch (toJSStr($1)) {$n", 24);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_492, "default: $n", 11);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_493, "break BeforeRet;$n", 18);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_494, "break L$1;$n", 12);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_495, "$1 = nimCopy(null, $2, $3);$n", 29);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_496, "nimCopy($1, $2, $3);$n", 22);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_497, "var $1 = $4; $2 = $1[0]; $3 = $1[1];$n", 38);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_498, "$# = [$#, $#];$n", 16);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_499, "$1 = $2; $3 = $4;$n", 19);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_500, "try {$n", 7);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_501, "--excHandler;$n} catch (EXC) {$n var prevJSError = lastJSError;"
"$n lastJSError = EXC;$n --excHandler;$n", 102);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_502, "framePtr = $1;$n", 16);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_503, "lastJSError instanceof $1", 25);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_504, "isObj(lastJSError.m_type, $1)", 29);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_505, "if (lastJSError && ($1)) {$n", 28);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_506, "var $1 = lastJSError;$n", 23);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_507, "lastJSError = prevJSError;$n", 28);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_508, "raiseException($1, $2);$n", 25);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_509, "$1 = true;$n", 12);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_510, "/* Generated by the Nim Compiler v$1 */$n/* (c) 2019 Andreas "
"Rumpf */$n$nvar framePtr = null;$nvar excHandler = 0;$nvar lastJ"
"SError = null;$nif (typeof Int8Array === \'undefined\') Int8Array "
"= Array;$nif (typeof Int16Array === \'undefined\') Int16Array = Ar"
"ray;$nif (typeof Int32Array === \'undefined\') Int32Array = Array;"
"$nif (typeof Uint8Array === \'undefined\') Uint8Array = Array;$nif"
" (typeof Uint16Array === \'undefined\') Uint16Array = Array;$nif ("
"typeof Uint32Array === \'undefined\') Uint32Array = Array;$nif (ty"
"peof Float32Array === \'undefined\') Float32Array = Array;$nif (ty"
"peof Float64Array === \'undefined\') Float64Array = Array;$n", 633);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_511, "Deprecated", 10);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_512, "Deprecated:", 11);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_513, "\012<p><strong class=\"examples_text\">$1</strong></p>\012", 50);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_514, "\012\\textbf{$1}\012", 13);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_515, "<span class=\"Comment\">$1</span>", 31);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_516, "\\spanComment{$1}", 16);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_517, "<span class=\"Keyword\">$1</span>", 31);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_518, "\\spanKeyword{$1}", 16);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_519, "<span class=\"Operator\">$1</span>", 32);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_520, "\\spanOperator{$1}", 17);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_521, "<span class=\"StringLit\">$1</span>", 33);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_522, "\\spanStringLit{$1}", 18);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_523, "<span class=\"CharLit\">$1</span>", 31);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_524, "\\spanCharLit{$1}", 16);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_525, "<span class=\"DecNumber\">$1</span>", 33);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_526, "\\spanDecNumber{$1}", 18);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_527, "<span class=\"FloatNumber\">$1</span>", 35);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_528, "\\spanFloatNumber{$1}", 20);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_529, "<a href=\"#$2\"><span class=\"Identifier\">$1</span></a>", 52);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_530, "\\spanIdentifier{$1}", 19);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_531, "<a href=\"$1#$2\"><span class=\"Identifier\">$3</span></a>", 54);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_532, "<span class=\"Identifier\">$1</span>", 34);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_533, "<span><span class=\"Other\">{</span><span class=\"Other pragmadots"
"\">...</span><span class=\"Other\">}</span></span><span class=\"prag"
"mawrap\"><span class=\"Other\">$1</span><span class=\"pragma\">", 185);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_534, "\\spanOther{$1}", 14);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_535, "</span><span class=\"Other\">$1</span></span>", 43);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_536, "<span class=\"Other\">$1</span>", 29);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_537, "<a class=\"reference external\" href=\"$2\">$1</a>", 46);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_538, "<a href=\"$2#$1\"><span class=\"Identifier\">$1</span></a>", 54);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_539, "$1 -> \"$2\";$n", 13);
STRING_LITERAL(TM__Vw9cfUOQOae9b9bzZBlucMZQg_540, "digraph $1 {$n$2}$n", 19);
static N_NIMCALL(void, Marker_tyRef__4hi0XQqK9aLiPuWT9acsXm9aQ)(void* p, NI op) {
tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* a;
a = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)p;
nimGCvisit((void*)(*a).left, op);
nimGCvisit((void*)(*a).right, op);
nimGCvisit((void*)(*a).data, op);
}
static N_NIMCALL(void, TM__Vw9cfUOQOae9b9bzZBlucMZQg_3)(void) {
NI T1_;
T1_ = (NI)0;
for (T1_ = 0; T1_ < 4096; T1_++) {
nimGCvisit((void*)cache__WGMp5Wo1NlgbAMOysPIfmQ[T1_], 0);
}
}
N_LIB_PRIVATE N_NIMCALL(NI, len__9b0YRltzV3kNSE9aQTsG82wg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* a) { NI result;
result = (NI)0;
{
if (!(a == NIM_NIL)) goto LA3_;
result = ((NI) 0);
}
goto LA1_;
LA3_: ;
{
result = ((*a).L > 0? ((*a).L) : -((*a).L));
}
LA1_: ;
return result;
}
static N_INLINE(void, incRef__AT1eRuflKWyTTBdLjEDZbg_3system)(tyObject_Cell__1zcF9cV8XIAtbN8h5HRUB8g* c) { (*c).refcount = (NI)((NU32)((*c).refcount) + (NU32)(((NI) 8)));
}
static N_INLINE(tyObject_Cell__1zcF9cV8XIAtbN8h5HRUB8g*, usrToCell__QFQqcLB3lgOdwipkv9a60xwsystem)(void* usr) { tyObject_Cell__1zcF9cV8XIAtbN8h5HRUB8g* result;
result = (tyObject_Cell__1zcF9cV8XIAtbN8h5HRUB8g*)0;
result = ((tyObject_Cell__1zcF9cV8XIAtbN8h5HRUB8g*) ((NI)((NU32)(((NI) (ptrdiff_t) (usr))) - (NU32)(((NI) 8)))));
return result;
}
static N_INLINE(void, rtlAddZCT__AT1eRuflKWyTTBdLjEDZbg_2system)(tyObject_Cell__1zcF9cV8XIAtbN8h5HRUB8g* c) { addZCT__Y66tOYFjgwJ0k4aLz4bc0Q((&gch__IcYaEuuWivYAS86vFMTS3Q.zct), c);
}
static N_INLINE(void, decRef__AT1eRuflKWyTTBdLjEDZbgsystem)(tyObject_Cell__1zcF9cV8XIAtbN8h5HRUB8g* c) { (*c).refcount = (NI)((NU32)((*c).refcount) - (NU32)(((NI) 8)));
{
if (!((NU32)((*c).refcount) < (NU32)(((NI) 8)))) goto LA3_;
rtlAddZCT__AT1eRuflKWyTTBdLjEDZbg_2system(c);
}
LA3_: ;
}
static N_INLINE(void, asgnRef)(void** dest, void* src) { {
tyObject_Cell__1zcF9cV8XIAtbN8h5HRUB8g* T5_;
if (!!((src == NIM_NIL))) goto LA3_;
T5_ = (tyObject_Cell__1zcF9cV8XIAtbN8h5HRUB8g*)0;
T5_ = usrToCell__QFQqcLB3lgOdwipkv9a60xwsystem(src);
incRef__AT1eRuflKWyTTBdLjEDZbg_3system(T5_);
}
LA3_: ;
{
tyObject_Cell__1zcF9cV8XIAtbN8h5HRUB8g* T10_;
if (!!(((*dest) == NIM_NIL))) goto LA8_;
T10_ = (tyObject_Cell__1zcF9cV8XIAtbN8h5HRUB8g*)0;
T10_ = usrToCell__QFQqcLB3lgOdwipkv9a60xwsystem((*dest));
decRef__AT1eRuflKWyTTBdLjEDZbgsystem(T10_);
}
LA8_: ;
(*dest) = src;
}
static N_INLINE(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, pop__9c4Y4hTtvRqjj2EC8KP9aqDAsystem)(tySequence__WwUFq9cJ2xKRlsAWVEHyPRg** s) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
NI L;
NI T1_;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
T1_ = ((*s) ? (*s)->Sup.len : 0);
L = (NI)(T1_ - ((NI) 1));
result = (*s)->data[L];
unsureAsgnRef((void**) (&(*s)), (tySequence__WwUFq9cJ2xKRlsAWVEHyPRg*) setLengthSeqV2(&((*s))->Sup, (&NTI__WwUFq9cJ2xKRlsAWVEHyPRg_), ((NI) (L))));
return result;
}
static N_INLINE(void, nimCopyMem)(void* dest, void* source, NI size) { void* T1_;
T1_ = (void*)0;
T1_ = memcpy(dest, source, ((size_t) (size)));
}
static N_INLINE(void, copyMem__M04YC71iJg1N7gBF3HZTngsystem)(void* dest, void* source, NI size) { nimCopyMem(dest, source, size);
}
static N_INLINE(void, appendString)(NimStringDesc* dest, NimStringDesc* src) { {
if (!!((src == NIM_NIL))) goto LA3_;
copyMem__M04YC71iJg1N7gBF3HZTngsystem(((void*) ((&(*dest).data[(*dest).Sup.len]))), ((void*) ((*src).data)), ((NI) ((NI)((*src).Sup.len + ((NI) 1)))));
(*dest).Sup.len += (*src).Sup.len;
}
LA3_: ;
}
N_LIB_PRIVATE N_NIMCALL(NimStringDesc*, dollar___mZ66tEveFIQokq3arf8Klw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* r) { NimStringDesc* result;
NI T1_;
result = (NimStringDesc*)0;
T1_ = (NI)0;
T1_ = len__9b0YRltzV3kNSE9aQTsG82wg(r);
result = mnewString(((NI) (T1_)));
result = setLengthStr(result, ((NI) 0));
{
NimStringDesc* s;
s = (NimStringDesc*)0;
{
tySequence__WwUFq9cJ2xKRlsAWVEHyPRg* stack;
if (!!((r == NIM_NIL))) goto LA5_;
stack = (tySequence__WwUFq9cJ2xKRlsAWVEHyPRg*) newSeq((&NTI__WwUFq9cJ2xKRlsAWVEHyPRg_), 1);
asgnRef((void**) (&stack->data[0]), r);
{
while (1) {
NI T9_;
tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* it;
T9_ = (stack ? stack->Sup.len : 0);
if (!(((NI) 0) < T9_)) goto LA8;
it = pop__9c4Y4hTtvRqjj2EC8KP9aqDAsystem((&stack));
{
while (1) {
NI T12_;
if (!!(((*it).left == NIM_NIL))) goto LA11;
stack = (tySequence__WwUFq9cJ2xKRlsAWVEHyPRg*) incrSeqV3((TGenericSeq*)(stack), (&NTI__WwUFq9cJ2xKRlsAWVEHyPRg_));
T12_ = stack->Sup.len++;
asgnRef((void**) (&stack->data[T12_]), (*it).right);
it = (*it).left;
} LA11: ;
}
s = (*it).data;
result = resizeString(result, (s ? s->Sup.len : 0) + 0);
appendString(result, s);
} LA8: ;
}
}
LA5_: ;
}
return result;
}
static N_INLINE(void, nimGCunrefNoCycle)(void* p) { tyObject_Cell__1zcF9cV8XIAtbN8h5HRUB8g* T1_;
T1_ = (tyObject_Cell__1zcF9cV8XIAtbN8h5HRUB8g*)0;
T1_ = usrToCell__QFQqcLB3lgOdwipkv9a60xwsystem(p);
decRef__AT1eRuflKWyTTBdLjEDZbgsystem(T1_);
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, newRope__dBdikNFB2Y7QJ9aVJE7dGHg)(NimStringDesc* data) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
NimStringDesc* T1_;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*) newObj((&NTI__4hi0XQqK9aLiPuWT9acsXm9aQ_), sizeof(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA));
(*result).Sup.m_type = (&NTI__OFzf0kSiPTcNreUIeJgWVA_);
(*result).L = ((NI32)-((data ? data->Sup.len : 0)));
T1_ = (NimStringDesc*)0;
T1_ = (*result).data; (*result).data = copyStringRC1(data);
if (T1_) nimGCunrefNoCycle(T1_);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, amp___ShdZ6VrAQkY0nWR9a39b9bGdQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* a, tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* b) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
{
if (!(a == NIM_NIL)) goto LA3_;
result = b;
}
goto LA1_;
LA3_: ;
{
if (!(b == NIM_NIL)) goto LA6_;
result = a;
}
goto LA1_;
LA6_: ;
{
result = newRope__dBdikNFB2Y7QJ9aVJE7dGHg(((NimStringDesc*) NIM_NIL));
(*result).L = (NI)(((*a).L > 0? ((*a).L) : -((*a).L)) + ((*b).L > 0? ((*b).L) : -((*b).L)));
asgnRef((void**) (&(*result).left), a);
asgnRef((void**) (&(*result).right), b);
}
LA1_: ;
return result;
}
static N_INLINE(int, nimCmpMem)(void* a, void* b, NI size) { int result;
result = (int)0;
result = memcmp(a, b, ((size_t) (size)));
return result;
}
static N_INLINE(NIM_BOOL, equalMem__Bj9c9cm9cBM9coLsuNsT5BvZ9awsystem)(void* a, void* b, NI size) { NIM_BOOL result;
int T1_;
result = (NIM_BOOL)0;
T1_ = (int)0;
T1_ = nimCmpMem(a, b, size);
result = (T1_ == ((NI32) 0));
return result;
}
static N_INLINE(NIM_BOOL, eqStrings)(NimStringDesc* a, NimStringDesc* b) { NIM_BOOL result;
NI alen;
NI blen;
{ result = (NIM_BOOL)0;
alen = (a ? a->Sup.len : 0);
blen = (b ? b->Sup.len : 0);
{
if (!(alen == blen)) goto LA3_;
{
if (!(alen == ((NI) 0))) goto LA7_;
result = NIM_TRUE;
goto BeforeRet_;
}
LA7_: ;
result = equalMem__Bj9c9cm9cBM9coLsuNsT5BvZ9awsystem(((void*) ((&a->data[((NI) 0)]))), ((void*) ((&b->data[((NI) 0)]))), ((NI) (alen)));
goto BeforeRet_;
}
LA3_: ;
}BeforeRet_: ;
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, insertInCache__yShmEg9cffWxI7s5XzEKBow_2)(NimStringDesc* s) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
NI h;
NI T1_;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
gCacheTries__5GfZTThHPBfB9bjRZdFluBw += ((NI) 1);
T1_ = (NI)0;
T1_ = hash__6PCYkKlCNhq9cnRLnqWKkwQ(s);
h = (NI)(T1_ & ((NI) 4095));
result = cache__WGMp5Wo1NlgbAMOysPIfmQ[(h)- 0];
{
NIM_BOOL T4_;
T4_ = (NIM_BOOL)0;
T4_ = (result == 0);
if (T4_) goto LA5_;
T4_ = !(eqStrings((*result).data, s));
LA5_: ;
if (!T4_) goto LA6_;
gCacheMisses__fLRm9am8S0daYBVNK6JKyBg += ((NI) 1);
result = newRope__dBdikNFB2Y7QJ9aVJE7dGHg(s);
asgnRef((void**) (&cache__WGMp5Wo1NlgbAMOysPIfmQ[(h)- 0]), result);
}
LA6_: ;
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, rope__yShmEg9cffWxI7s5XzEKBow)(NimStringDesc* s) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
{
if (!((s ? s->Sup.len : 0) == ((NI) 0))) goto LA3_;
result = NIM_NIL;
}
goto LA1_;
LA3_: ;
{
result = insertInCache__yShmEg9cffWxI7s5XzEKBow_2(s);
}
LA1_: ;
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, amp___Z7W1o5nPSc3ExfO5f7j1Gg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* a, NimStringDesc* b) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* T1_;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
T1_ = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
T1_ = rope__yShmEg9cffWxI7s5XzEKBow(b);
result = amp___ShdZ6VrAQkY0nWR9a39b9bGdQ(a, T1_);
return result;
}
N_LIB_PRIVATE N_NIMCALL(void, add__yG4AKzsBRS1W4MANDlXQeg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** a, NimStringDesc* b) { unsureAsgnRef((void**) (&(*a)), amp___Z7W1o5nPSc3ExfO5f7j1Gg((*a), b));
}
N_LIB_PRIVATE N_NIMCALL(void, add__IM4kcMNkkOLJtqdEqSxR8A)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** a, tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* b) { unsureAsgnRef((void**) (&(*a)), amp___ShdZ6VrAQkY0nWR9a39b9bGdQ((*a), b));
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA)(NimStringDesc* frmt, tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
NI i;
NI length;
NI num;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
i = ((NI) 0);
length = (frmt ? frmt->Sup.len : 0);
result = NIM_NIL;
num = ((NI) 0);
{
while (1) {
NI start;
if (!(i < length)) goto LA2;
{
if (!((NU8)(frmt->data[i]) == (NU8)(36))) goto LA5_;
i += ((NI) 1);
switch (((NU8)(frmt->data[i]))) {
case 36:
{
add__yG4AKzsBRS1W4MANDlXQeg(&result, ((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_4));
i += ((NI) 1);
}
break;
case 35:
{
i += ((NI) 1);
add__IM4kcMNkkOLJtqdEqSxR8A(&result, args[num]);
num += ((NI) 1);
}
break;
case 48 ... 57:
{
NI j;
j = ((NI) 0);
{
while (1) {
j = (NI)((NI)((NI)(j * ((NI) 10)) + ((NU8)(frmt->data[i]))) - ((NI) 48));
i += ((NI) 1);
{
NIM_BOOL T14_;
T14_ = (NIM_BOOL)0;
T14_ = ((frmt ? frmt->Sup.len : 0) <= i);
if (T14_) goto LA15_;
T14_ = !((((NU8)(frmt->data[i])) >= ((NU8)(48)) && ((NU8)(frmt->data[i])) <= ((NU8)(57))));
LA15_: ;
if (!T14_) goto LA16_;
goto LA10;
}
LA16_: ;
}
} LA10: ;
num = j;
{
if (!((NI)((argsLen_0-1) + ((NI) 1)) < j)) goto LA20_;
{
NimStringDesc* T26_;
if (!NIM_TRUE) goto LA24_;
T26_ = (NimStringDesc*)0;
T26_ = rawNewString((frmt ? frmt->Sup.len : 0) + 50);
appendString(T26_, ((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_5));
appendString(T26_, frmt);
failedAssertImpl__W9cjVocn1tjhW7p7xohJj6A(T26_);
}
LA24_: ;
}
goto LA18_;
LA20_: ;
{
add__IM4kcMNkkOLJtqdEqSxR8A(&result, args[(NI)(j - ((NI) 1))]);
}
LA18_: ;
}
break;
case 123:
{
NI j_2;
i += ((NI) 1);
j_2 = ((NI) 0);
{
while (1) {
if (!(((NU8)(frmt->data[i])) >= ((NU8)(48)) && ((NU8)(frmt->data[i])) <= ((NU8)(57)))) goto LA30;
j_2 = (NI)((NI)((NI)(j_2 * ((NI) 10)) + ((NU8)(frmt->data[i]))) - ((NI) 48));
i += ((NI) 1);
} LA30: ;
}
num = j_2;
{
if (!((NU8)(frmt->data[i]) == (NU8)(125))) goto LA33_;
i += ((NI) 1);
}
goto LA31_;
LA33_: ;
{
{
NimStringDesc* T40_;
if (!NIM_TRUE) goto LA38_;
T40_ = (NimStringDesc*)0;
T40_ = rawNewString((frmt ? frmt->Sup.len : 0) + 50);
appendString(T40_, ((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_6));
appendString(T40_, frmt);
failedAssertImpl__W9cjVocn1tjhW7p7xohJj6A(T40_);
}
LA38_: ;
}
LA31_: ;
{
if (!((NI)((argsLen_0-1) + ((NI) 1)) < j_2)) goto LA43_;
{
NimStringDesc* T49_;
if (!NIM_TRUE) goto LA47_;
T49_ = (NimStringDesc*)0;
T49_ = rawNewString((frmt ? frmt->Sup.len : 0) + 50);
appendString(T49_, ((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_7));
appendString(T49_, frmt);
failedAssertImpl__W9cjVocn1tjhW7p7xohJj6A(T49_);
}
LA47_: ;
}
goto LA41_;
LA43_: ;
{
add__IM4kcMNkkOLJtqdEqSxR8A(&result, args[(NI)(j_2 - ((NI) 1))]);
}
LA41_: ;
}
break;
case 110:
{
add__yG4AKzsBRS1W4MANDlXQeg(&result, ((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_8));
i += ((NI) 1);
}
break;
case 78:
{
add__yG4AKzsBRS1W4MANDlXQeg(&result, ((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_8));
i += ((NI) 1);
}
break;
default:
{
{
NimStringDesc* T58_;
if (!NIM_TRUE) goto LA56_;
T58_ = (NimStringDesc*)0;
T58_ = rawNewString((frmt ? frmt->Sup.len : 0) + 50);
appendString(T58_, ((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_9));
appendString(T58_, frmt);
failedAssertImpl__W9cjVocn1tjhW7p7xohJj6A(T58_);
}
LA56_: ;
}
break;
}
}
LA5_: ;
start = i;
{
while (1) {
if (!(i < length)) goto LA60;
{
if (!!(((NU8)(frmt->data[i]) == (NU8)(36)))) goto LA63_;
i += ((NI) 1);
}
goto LA61_;
LA63_: ;
{
goto LA59;
}
LA61_: ;
} LA60: ;
} LA59: ;
{
NimStringDesc* T70_;
if (!(start <= (NI)(i - ((NI) 1)))) goto LA68_;
T70_ = (NimStringDesc*)0;
T70_ = substr__2yh9cer0ymNRHlOOg8P7IuA(frmt, start, (NI)(i - ((NI) 1)));
add__yG4AKzsBRS1W4MANDlXQeg(&result, T70_);
}
LA68_: ;
} LA2: ;
}
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___UQfMnMPks8jKz20fTXQy9bQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_10), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, rope__KOisMGxcPhz6CcSmxgwEQQ)(NI64 i) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
NimStringDesc* T1_;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
gCacheIntTries__opyfsNv023Md1P05mqsDew += ((NI) 1);
T1_ = (NimStringDesc*)0;
T1_ = nimInt64ToStr(i);
result = rope__yShmEg9cffWxI7s5XzEKBow(T1_);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___KxpxlR6eqq3gRIOYTfR67w)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_11), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___IFeEbVhQpPGgxkLehuSiBA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_12), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___BYiowJAm8zF7RBRISElaLg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_13), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___ZkZcMxwzInnijXy5kz1K3A)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_14), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(void, prepend__IM4kcMNkkOLJtqdEqSxR8A_2)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** a, tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* b) { unsureAsgnRef((void**) (&(*a)), amp___ShdZ6VrAQkY0nWR9a39b9bGdQ(b, (*a)));
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, amp___4cYKitaHx6RQ9azRtQsZp6w)(NimStringDesc* a, tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* b) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* T1_;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
T1_ = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
T1_ = rope__yShmEg9cffWxI7s5XzEKBow(a);
result = amp___ShdZ6VrAQkY0nWR9a39b9bGdQ(T1_, b);
return result;
}
N_LIB_PRIVATE N_NIMCALL(void, writeRope__FwuzOBq6SLlanVUstm8q9cA)(FILE* f, tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* r) { {
NimStringDesc* s;
s = (NimStringDesc*)0;
{
tySequence__WwUFq9cJ2xKRlsAWVEHyPRg* stack;
if (!!((r == NIM_NIL))) goto LA4_;
stack = (tySequence__WwUFq9cJ2xKRlsAWVEHyPRg*) newSeq((&NTI__WwUFq9cJ2xKRlsAWVEHyPRg_), 1);
asgnRef((void**) (&stack->data[0]), r);
{
while (1) {
NI T8_;
tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* it;
T8_ = (stack ? stack->Sup.len : 0);
if (!(((NI) 0) < T8_)) goto LA7;
it = pop__9c4Y4hTtvRqjj2EC8KP9aqDAsystem((&stack));
{
while (1) {
NI T11_;
if (!!(((*it).left == NIM_NIL))) goto LA10;
stack = (tySequence__WwUFq9cJ2xKRlsAWVEHyPRg*) incrSeqV3((TGenericSeq*)(stack), (&NTI__WwUFq9cJ2xKRlsAWVEHyPRg_));
T11_ = stack->Sup.len++;
asgnRef((void**) (&stack->data[T11_]), (*it).right);
it = (*it).left;
} LA10: ;
}
s = (*it).data;
write__PArlm09bKklm2BLsCg6YtaA(f, s);
} LA7: ;
}
}
LA4_: ;
}
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___G9aA37gQrW88KHzpCAwhgjQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_15), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___PoDv5ydEvGdd9aiIF9cOiAPw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_16), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___vzbf0XksfaFTXNoTT6BCwA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_17), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___lQVSDPkAFXHNoa1N7jYrNw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_18), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___6d8an6hdqiIrRjPW1wEh5Q)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_19), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___gMbiWAc0IjihIq46IYhmAw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_20), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___uHsu7fLXac4OhMNd79bSJwA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_21), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___3WM9b4PeyDKoIDFMvYcQX3w)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_22), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___p4LhaCxKpUERrq9cB9b8Mp9cw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_23), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___TbMwXzwNL7txOQADiTjwKA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_24), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___E0nDsXp7tY4mC1BnrrjWmA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_25), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___mbjeaBETPixw9bUvyk31B6g)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_26), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___AfR9bXoD9bcehKoM7F8O79bYA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_27), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___nlZFDYB4M9bmBbYqEropRVw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_28), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___dwsIkeXQe0E8HKrzN9aRE5A)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_29), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___fIR1FG0QPRsKvEYKq4tJUQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_30), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___jADQs38xm62v1oxF2cSvEw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_31), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___DZV83DjWnQ9a19atC2oeswXg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_32), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___sfvTjNjtOC86mU9bHczF6ow)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_33), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___9ab1aKSDn70Vte0NcIItnaQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_34), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___jadqNPnY9aM3oxYK6jarLrA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_35), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___LvsIDF8olc08xBiqCYIUog)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_36), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___6Tfa1iP1ENVlWbe89cSELSQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_37), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___hKg2Id9cvzE5Dgl9cU31c4Vw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_38), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___H3xXuIFdbz4MNb5T6BSfcQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_39), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___ELXFo0GedkhGYj9bocTHZAg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_40), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___9aLrcjgzGJE3f9ab2uR37jog)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_41), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___3Q9c5iS9btBDBXZVoQktb1XQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_42), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___MALQXTKXJv7x9a9c247satLQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_43), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___0nBiBCva6YS9a9bSV2Vr7Zxw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_44), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___yyhPPkMkLJqWG6p8HGn9aoA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_45), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___t8gRNGR1flvaCNlBxuLn1A)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_46), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___xQaqlAwFuwxqBFixw7ewLg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_47), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___2SWcbuU7RHQR0b8y9aJ9a5VQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_48), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___gSgutt9b7GMWVGBkCt0UHAQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_49), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___Vcuq0AWiVDndx4UH9cJ9cBRg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_50), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___l4wxq9cmPihXoF5xnDVNR1w)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_51), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___zgEKWXsZtT6lqQ6XlgfrsA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_52), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___uXZ30k0oJEqGPZW57O3dwg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_53), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___tTI9aMQiBZdiEeBIVh7QtYA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_54), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___VJBBlA9aMl5p0yYB1WzSMVg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_55), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___jw4Sb0OSpKH1T5cLz7iyzA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_56), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___0RQ2PINB4t8FjFlNUM6N9cQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_57), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___LQ9bGxpANW8yeg5P9c0UYAaQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_58), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___f8tdlskieCnWysl9c9blzqZg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_59), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___KbFpNe1pZ7hIuQi7dp1dSQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_60), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___nunbo9aB0HmmYQJ3InIBEzQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_61), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___RBxLok7DyUB0aHl9bxPIl9bQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_62), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___NARRjCd1x5Fr7NTTcoPRrw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_63), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___NlLLwmZHOiJUpZfuk00AWA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_64), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___mF9aI9b3hDjj53TD2C2gTrHA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_65), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___PafMws9cJ9arr9a0RVMoIHmAw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_66), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___3lAlmrWiRqEg9a9cd9a8kNhig)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_67), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___f8NIixSwWrk6SXQ3BFamWw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_68), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___TTRh79a14hh1gb0owIP1Y6Q)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_69), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___TmeCjGna9cPfiHHcfqmKXjw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_70), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___FsfRVuOOBePjn9cQ9aK7Vh1w)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_71), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___paA0sar8RKZqiwEaDfWo2A)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_72), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___jr9cXNQhhlLDfFJH4RSjeZg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_73), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___EnzikEr9bDhOR6GYxWuYSwQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_74), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___QqzUiJcAEZE2azDhIWHrgg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_75), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___20ZujjIFPkyqvS2OmenEAA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_76), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___Vxo9ayk1xB18if39aZ1TBnKA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_77), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___NtQEfuK9bXszNTfYU57z19bw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_78), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___AKNexo4CH8G2vDeWW34Vpg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_79), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___LE3oWAmB5YDSDHm3LNHhCg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_80), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___W83I2xs7lC32PrMs9bq4P2w)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_81), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___JKMGBJtXtDvc0NwxujFmZQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_82), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___TA8WFV49atYpIneJatQWALw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_83), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___nPenDL3j2Q6A1an1Cl3oCA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_84), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___TNkzce2Sd9bck2QRtketc8A)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_85), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___kqRXw2WRJqDnfQK0N30ydw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_86), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___BKnrQUIV2xGn2MO0RK09aUw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_87), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___SCyrk9acEm3vLZhXCV1fGNg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_88), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___erDe9aYc2BNxzH9brKlmtEBg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_89), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___HSAgkeH84eiEd8MfKIuBQA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_90), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___1AD3Wp47Hcdfg6PO2ac0NQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_91), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___T11tCz9bIGT2CcftAwrDXZw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_92), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___lS9bA1j3Ue6pp7sCliDsT8g)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_93), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___M3h9cTlVBrj2vakKBqQRlMA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_94), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___BBAyGuVoK6QA7nXfPUIYKA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_95), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___g9b9arp3BWCGRHDe21SJso6w)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_96), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___09aVguRR64dWfw4b6fKBcqg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_97), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___tgUnLdPVK0vRqC0pWxMClQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_98), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___FBNsdfF5FNrY4P9cYQIfvZQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_99), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___cB7zULPbG5vWWdCukRjdqg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_100), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___dpzmcz9a6kXbhFacdElIMOw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_101), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___AWFBEodxoi9a61KDUc9aiw1w)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_102), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___vHbYzYlzLPcurSm0Hu8InQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_103), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___nzT6Rke9c7tkW9b3XMmld2LA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_104), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___9cCc2iMcL3MEBZTTL3LCW1w)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_105), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___ahBYcGrhpPvM5dTdzCQBrQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_106), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___XI9awM9a9aQ9cB9bcS7uDRsa1Rw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_107), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___9cWNaGuyEpBbdBlD9b5nY1ug)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_108), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___6P67I9czJ9aa9aZzVyYWUiGlw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_109), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___S4jE5dFDtcCC8ODzxaJk6A)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_110), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___Msid9awGKVeVe7p3v7WfNQA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_111), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___xyRsdWsGY1DVVispyn0Xeg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_112), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___EPABzhs2B9atAvHV4CUTw2Q)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_113), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___2MhCcipNmSHgcDtN4cr8ng)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_114), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___0ul9cDZYl7YkH1RhZBTd9c6A)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_115), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___QFf4DPoOk6Jy59cL2OASJzw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_116), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___7yDHbEsisDNKcqQHIRgOuQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_117), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___GwVmUG4AZCEAP8dBk4TGHg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_118), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___q7DaQZqCe0lRO0rhBWzM0w)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_119), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___hGIvKp3CGssDQ2vSvfksxQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_120), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___9c1P82lz6H9anMKDbz1vYNpg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_121), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___dbg9bsMENUwtF9aO45wEGG3Q)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_122), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___ym0Pr6z8A9ajyOAgotpd9a9bw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_123), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___izqbVTMtpY7kMiTK4bPJ6Q)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_124), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___rouofEnBX1ok9aMXmOsKdHg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_125), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___C3GQZbey70223GyG307UFg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_126), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___yxmLIVRKySYknm2wSBp9cpg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_127), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___8u7UPO7ZpaMkWoJRtZLlYQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_128), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___xXT7cKE1NTiL4U2MdlA2yQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_129), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___44q9ak51X9b9bmuZ9cK4LsFWOg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_130), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___77dMna2dOod5LqwYkRMZGg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_131), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___QXMcmOst45ThYFLo9cOKDiQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_132), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___zldA3DCxzpAhONjlfz7iIg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_133), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___dnB3So2xw9c189c09a9cc9b4hxA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_134), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___r2gXVULKoAtQjkgjf0Z4wg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_135), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___VsLzrOz1nS9cRBBz9ccZfETQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_136), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___tRSKshYob5uzZE3eBVe59cg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_137), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___vcbf2lEZaiSjbAHwgt9aKXw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_138), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___sb2NV56uvmvOtYkgVsaVQQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_139), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___7STLi75js8HXlmFg7Abt9bQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_140), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___5O50gePV9adn3wgFGWjlOLQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_141), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___9a3Y7eeGNXkOCLUktwxzN9ag)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_142), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___Ng8dczn37bLzoM9bsVdPwjQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_143), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___boICAAvO1zkTlYDOuEaj6g)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_144), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___LeuvM3mIc6pSNktpm9cHSVw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_145), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___mxQQ2vwZhwfDagj5SEXeHA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_146), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___x2NKZw9brJpylbwEtLfx9a9bg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_147), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___TmT2Gs9cB7RN9cmo9c9cBpfKsA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_148), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___RiPFNabSvay09bAW4Jic2ag)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_149), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___efSHgbCUYoX1lUK7M9aj4Pg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_150), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___Vmgih7rhd9cXUC9cEBz2cwXQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_151), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___rB3209aHcqpT39anNUezpSjg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_152), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___x85Q1O2QUnYbstPlxUCyAQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_153), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___L3AeZ1n9aK4C1jsBCeaCmlQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_154), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___ebmRHYtM9cCbYF6WvKDfQ9cg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_155), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___qE1JtEDDOvP6J49a9cv9aK1Dg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_156), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___ctvQ2lU9b9bnVVpNP4GhIo2Q)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_157), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___8bHx2qDxS2yWIId1X52mqg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_158), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___kTDR7D9c9aomjcaUQOmKJ9csg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_159), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___1tj59chZC08k4TWYeZiqDnQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_160), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___533QKY9a8quvLM1SsLE1JfQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_161), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___uFJUSitn9c1Tw6cF9cZf6x6Q)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_162), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___G8iCcDovsaw25PkF7wHs0g)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_163), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___SY4U2QvmoQxocaG8MOmyHA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_164), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___bhkFYKbURxGcJnKpswdr2Q)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_165), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___lTsL0bi6njxzDh9c8A32r2w)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_166), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___k4VEB3kaBL72FRQN8buzSg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_167), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___YbQIA9cHUESCyYT1WEeIVbA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_168), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___66KauNYQRukYNgmb6bVXEA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_169), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___S550SlHmWbDpD7rs0J2lrA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_170), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___sGnLi1DjaBomQ9c9a6MOCA5g)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_171), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___bEKtSmboScaCP8PPnlOWqw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_172), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___ZpwWwpfBXgcQ6xoLOH4CJw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_173), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___GHW5yjG8N9c2BQBun6aBJzQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_174), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___Yup67SPGRVcwMdmZwc9cSag)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_175), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___ec65mR1N7BSL9cmUa3z9czvA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_176), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___ibyK70G44kCK9cN8nAkxyGA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_177), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___H9b69aGZGrLOiKWQdd30yQ9bg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_178), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___Te7bvH18PbGe5siNJ9aDTTA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_179), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___MUaBvSw0MHw3qQi9bYavAmg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_180), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___bWYxjLMocXEvYgQQcC63rw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_181), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___ZpcNBrQMfioSvQNxKHhu9aw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_182), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___gywCjjjPZobIva6liQWNLQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_183), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___6PDHoyz05lEjxGNE0k0ikw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_184), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___AXGsBlGV5DoEOwPJSl9bdJw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_185), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___ygzR9aJ6oM1bZTq4Z2lNO3Q)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_186), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___uYVc6UX8hcaEdrHosUQAOw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_187), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___AlV8xJkjCXujAUesHxezgw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_188), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___L9asecuKwevQN2h9cWzyv6oA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_189), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___nZD9cadh12dcqTFsXBHbCRg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_190), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___dz1JHdrf1p9bPB9ad2dZBtYw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_191), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___0MUu7DVBoaLHTVUZe9bKoIA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_192), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___29aIWEGnJW0wnITIeSKWfFg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_193), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___n2CigWG38YNInkiL4n8g7A)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_194), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___bb3v9bDRLv9c9bcQzGH9c5H4Gw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_195), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___tkJq8W3gQVDjuu9aT3THC6Q)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_196), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___oyQkqbRkRzo43y6iRevkaA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_197), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___YuphtPwdJHG6BUJOVa9bX3w)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_198), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___EQxs5xa4FNWtMfcvmFZ9cMA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_199), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___5YbjRZxm0g3SrdnL73aQaw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_200), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___MEALpIIbc0cKMcjQ7Xckzg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_201), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___yUc5o9ax9c9asIVNkfprLRPpA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_202), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___4JrnABFfF3UTQ3nO9a6mXzQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_203), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___bkAwkKoaz09cAQo9arQjGA0A)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_204), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___7N9bV9cjVBHs9ciAhz7vgdI9aw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_205), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___QX9cU2fNK0jJrZNDQKnAycA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_206), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___vTbVjc6faJqdBrTckFLLWQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_207), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___v4k9cDtOUzGyUHJbnJ7kQKg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_208), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___0ym49cR6ES8k9bYWsnh1fELA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_209), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___Jx78R9a9anGvjjocCaP8YgIg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_210), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___s0lnM9cZDB9bOREa4Fx1leBw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_211), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___aT7p9bNEmP3LxrK3OhspnSw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_212), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___mV75vMLuQ8rrQEUzNz6llA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_213), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___jhVz7tKuf0heLM2D3nL0gw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_214), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___c4YKWXetPKpaUUF7Qft2gA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_215), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___rCIIoKC0OrXhpuTFTIZn0g)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_216), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___lXaYcLcHHuQ46VvpH6Qr2A)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_217), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___duX6hgjmpJtFFdvJVuoafg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_218), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___GNSb4l0oRsR1gu66azz1LQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_219), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___LGbUtKnsZL8FcQiQN7sWEA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_220), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___e8Xf9ajw9cRlpuqnFnlEuSpA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_221), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___nVQhtKHyPC8pvPbUAUBU7A)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_222), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___9bI5GhokFUA9bgO9av819cgdBg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_223), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___qTicKO8EMC9cWGOyybIz4WQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_224), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___yZHx0qMqBvbhmZ0fMuAP6A)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_225), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___YQzyPnY5vKAqE2RyLX0cew)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_226), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___cIILAsA6BeRrvHfloZIscg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_227), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___IwDTuHqkGn7wW16ga2ktSg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_228), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___lbkoHJP5AIgE86vP7MmlKw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_229), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___9b84wNYrm79cLYfx9bsPNHjPQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_230), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___K5ihI3kW9cFBh6sKlfEpJwg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_231), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___nEiBK88oEGnvYfkiei9cyJA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_232), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___Psy1qActyEYmIhrRo2KkJA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_233), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___9cZzkwYphs086zWiuLotXLA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_234), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___kPsYd8d9cco3hhqO7CEAFeg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_235), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___BbOsdTh4ZRNKmiISHDyg3A)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_236), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___Py40oiVtYdIelNuiQQjpjw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_237), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___QzVlk7tEXgagMWC19aLvbkg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_238), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___qxufH5vUl9aY2l9cFq39bnVwA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_239), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___jiTCvQQpgMU0bTrdVuECiw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_240), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___n4OrLXC1r9a83k5wz2NoWxQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_241), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___bJpxHYPJaxWBQn6QxwBA4w)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_242), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___fOn9b5Ij3ytw2Ui9a2CPI5zw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_243), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___zJU3FoYOdJ9bmuODPmqtgdQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_244), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___1MXpJAdeOMc2XMg5H7t9aSg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_245), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___VNAv31sqVgxrd9aXeFF5wYw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_246), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___MULS9c8dKz2mJ1U9a9cMyTCYw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_247), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___5TB09c2Iz60T0YagbSbI5RQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_248), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___NIzUqj4Mr1E3EKy0AkJaXQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_249), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___yQdCkIARIVr9aqI8oVxi9cQw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_250), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___WYvjnWcyRjjjI0lasIi1YA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_251), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___hR4oq6WdDjEl0JIvQtvUlg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_252), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___84GQPNcrIJtbrzuA7JnMPw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_253), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___SqZEI7bxySjmJX4GsXyvKw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_254), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___c1f569aWpTd825BTnv9bq4Xg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_255), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___ibl3qMPOrpGT2x8X7vmbeQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_256), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___bBcuDHMXr6Kz1tr7BzD9aKw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_257), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___aDvifvZOUmduC6Unfm69bKA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_258), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___5kuxCbMO8PVJc9aJbXScUOQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_259), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___Uu9cBz7dxPVDFhF9aLzWecyQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_260), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___WWt3il4CHPiYP10KdNLrWw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_261), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___hc7hMh137dtaNdd3qw28EQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_262), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___XWz49cQA2QiZaLkqHBU5L3g)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_263), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___Au81R9a68Rv3gwlPtvDarPg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_264), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___Yw741acxvsUs9cOX9cuiDj9bw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_265), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___T9caGByKkBhaXSZ6fCJLIdQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_266), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___JmTWN8YiVKTZuvCYW2XNZA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_267), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___Kbv8OIo8zpawh7SNMbfgkA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_268), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___B0OBOTOJQENvDd71LJ9b19bw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_269), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___22ELRKd9bDuNug6qvIihS3A)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_270), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___ddrHnMlEhcHznkXv27msmQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_271), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___yhJ9aDxHfJqHvWO0i6N9bukQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_272), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___MLJpsW0DAZYB8lAgq09cUjg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_273), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___8tWfSjtTOlDafxpQPvChAA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_274), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___xKLwwPkFSVy2Dtn9cuJ78xw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_275), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___hdRijZdoPR3UGq9aUw2zFDQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_276), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___ZjQc8bFVF8ePFYxjN0iVVg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_277), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___SiqB8gWmdYKb4vtgqYrrMA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_278), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___2Ixv9aZ9bvpNaVAVzYBJlUPg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_279), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___HoXSbgR7plMG7Fef0fcy9aw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_280), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___H1Ma2EXqegHnMqzJZ4SA1g)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_281), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___jpXTCDNVjIi5r4hbHN5SVQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_282), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___4L62Yp9bLO2ZDcvBG9bSvP9bw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_283), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___MCSdS9cTdQvttqiM9azLzkDg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_284), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___E9bSTz8DQ4tgiLV9avQjFgFA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_285), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___3CQpPXVDiNqC3jKO8Juliw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_286), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___w50CkyHBltcyR8rWxttZCg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_287), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___fmEfDTfNDkVDxWi9c0O6D2g)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_288), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___k9bgPIs43oLgxnk1l4TNQaw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_289), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___5MqeIopvDuA9aozxL79cQ88g)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_290), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___Zp9bMZDO5tEkvVLTxiKsBkA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_291), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___j5FZyaqnqjc2dcsUkAp28Q)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_292), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___EbvvG9awBeRKzx8xuBIb7TA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_293), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___9a8besSQa09cOOt9b9cgdVwY9aQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_294), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___oVKF7oq59cRGAaMpvWzNWbw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_295), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___7ru3bwKuSx4Sc8ilsBmX3g)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_296), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___MDIdJXTVckPj57aO7LMVgw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_297), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___vQDE0VOBftnrpkVsM9cme4w)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_298), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___9bmR9bM9b0qqEqU0QJKnmLQnA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_299), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___88tWbH31SmOWJjgJ7RnfHA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_300), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___t1CB59bEwlxfHZhNwNNz1bw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_301), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___YbLM7ZajsWOFLl4iSo0Krg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_302), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___rH7Ns9bqAnnfkukwBIlz9bKg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_303), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___zx9ctq3Ffe9aysjoWhZOzevQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_304), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___T9a21DAzFCa3OqRooKKtkqw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_305), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___Y4DThr9bpMbmoKpvgT1rYwg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_306), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___811qrD9bMr21weOkImaKvIA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_307), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___YNifhKTQWQRf1atK7E3Qmg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_308), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___YfbBxPLyPvVS6F2y9bSUFIA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_309), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___OBvl4G6evYkvK9b9bClFGqNw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_310), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___pHsLkkx9bTDctZjmJqwCYRA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_311), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___ksH6NowTz9bh4eMOdyaiR1w)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_312), args, argsLen_0);
return result;
}
static N_INLINE(void, nimSetMem__JE6t4x7Z3v2iVz27Nx0MRAmemory)(void* a, int v, NI size) { void* T1_;
T1_ = (void*)0;
T1_ = memset(a, v, ((size_t) (size)));
}
static N_INLINE(void, nimZeroMem)(void* p, NI size) { nimSetMem__JE6t4x7Z3v2iVz27Nx0MRAmemory(p, ((int) 0), size);
}
static N_INLINE(NCSTRING, nimToCStringConv)(NimStringDesc* s) { NCSTRING result;
result = (NCSTRING)0;
{
NIM_BOOL T3_;
T3_ = (NIM_BOOL)0;
T3_ = (s == NIM_NIL);
if (T3_) goto LA4_;
T3_ = ((*s).Sup.len == ((NI) 0));
LA4_: ;
if (!T3_) goto LA5_;
result = "";
}
goto LA1_;
LA5_: ;
{
result = ((NCSTRING) ((*s).data));
}
LA1_: ;
return result;
}
N_LIB_PRIVATE N_NIMCALL(NIM_BOOL, equalsFile__9bihNFg7Qajcg9arfx5cr9aHA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* r, FILE* f) { NIM_BOOL result;
tyArray__9bKy7UA2LOi2vzOViufaW1Q buf;
NI bpos;
NI blen;
NI btotal;
NI rtotal;
NIM_BOOL T27_;
NI T28_;
{ result = (NIM_BOOL)0;
nimZeroMem((void*)buf, sizeof(tyArray__9bKy7UA2LOi2vzOViufaW1Q));
bpos = ((NI) 1024);
blen = ((NI) 1024);
btotal = ((NI) 0);
rtotal = ((NI) 0);
{
NimStringDesc* s;
s = (NimStringDesc*)0;
{
tySequence__WwUFq9cJ2xKRlsAWVEHyPRg* stack;
if (!!((r == NIM_NIL))) goto LA4_;
stack = (tySequence__WwUFq9cJ2xKRlsAWVEHyPRg*) newSeq((&NTI__WwUFq9cJ2xKRlsAWVEHyPRg_), 1);
asgnRef((void**) (&stack->data[0]), r);
{
while (1) {
NI T8_;
tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* it;
NI spos;
NI slen;
T8_ = (stack ? stack->Sup.len : 0);
if (!(((NI) 0) < T8_)) goto LA7;
it = pop__9c4Y4hTtvRqjj2EC8KP9aqDAsystem((&stack));
{
while (1) {
NI T11_;
if (!!(((*it).left == NIM_NIL))) goto LA10;
stack = (tySequence__WwUFq9cJ2xKRlsAWVEHyPRg*) incrSeqV3((TGenericSeq*)(stack), (&NTI__WwUFq9cJ2xKRlsAWVEHyPRg_));
T11_ = stack->Sup.len++;
asgnRef((void**) (&stack->data[T11_]), (*it).right);
it = (*it).left;
} LA10: ;
}
s = (*it).data;
spos = ((NI) 0);
slen = (s ? s->Sup.len : 0);
rtotal += slen;
{
while (1) {
NI n;
if (!(spos < slen)) goto LA13;
{
if (!(bpos == blen)) goto LA16_;
bpos = ((NI) 0);
blen = readBuffer__f3MIZh4IV2qRTxlOpckbRA_2(f, ((void*) ((&buf[(((NI) 0))- 0]))), ((NI) 1024));
btotal += blen;
{
if (!(blen == ((NI) 0))) goto LA20_;
result = NIM_FALSE;
goto BeforeRet_;
}
LA20_: ;
}
LA16_: ;
n = (((NI)(blen - bpos) <= (NI)(slen - spos)) ? (NI)(blen - bpos) : (NI)(slen - spos));
{
NIM_BOOL T24_;
T24_ = (NIM_BOOL)0;
T24_ = equalMem__Bj9c9cm9cBM9coLsuNsT5BvZ9awsystem(((void*) ((&buf[(bpos)- 0]))), ((void*) ((NI)(((NI) (nimToCStringConv(s))) + spos))), ((NI) (n)));
if (!!(T24_)) goto LA25_;
result = NIM_FALSE;
goto BeforeRet_;
}
LA25_: ;
spos += n;
bpos += n;
} LA13: ;
}
} LA7: ;
}
}
LA4_: ;
}
T27_ = (NIM_BOOL)0;
T28_ = (NI)0;
T28_ = readBuffer__f3MIZh4IV2qRTxlOpckbRA_2(f, ((void*) ((&buf[(((NI) 0))- 0]))), ((NI) 1));
T27_ = (T28_ == ((NI) 0));
if (!(T27_)) goto LA29_;
T27_ = (btotal == rtotal);
LA29_: ;
result = T27_;
}BeforeRet_: ;
return result;
}
N_LIB_PRIVATE N_NIMCALL(NIM_BOOL, equalsFile__Wiam9c8x73Mtmbj0r4Ppikg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* r, NimStringDesc* filename) { NIM_BOOL result;
FILE* f;
result = (NIM_BOOL)0;
f = (FILE*)0;
result = open__gq12VLhVO0NBzUTnGgz4nw(&f, filename, ((tyEnum_FileMode__ZJfK20XeZ9bv2j1pZjw9aswg) 0), ((NI) -1));
{
if (!result) goto LA3_;
result = equalsFile__9bihNFg7Qajcg9arfx5cr9aHA(r, f);
close__fU6ZlJAtQ9bre04EDZLdGsA_3(f);
}
LA3_: ;
return result;
}
N_LIB_PRIVATE N_NIMCALL(NIM_BOOL, writeRope__LLRRC42xWBSkxzV9bsPu7lA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* head, NimStringDesc* filename) { NIM_BOOL result;
FILE* f;
result = (NIM_BOOL)0;
f = (FILE*)0;
{
NIM_BOOL T3_;
T3_ = (NIM_BOOL)0;
T3_ = open__gq12VLhVO0NBzUTnGgz4nw(&f, filename, ((tyEnum_FileMode__ZJfK20XeZ9bv2j1pZjw9aswg) 1), ((NI) -1));
if (!T3_) goto LA4_;
{
if (!!((head == NIM_NIL))) goto LA8_;
writeRope__FwuzOBq6SLlanVUstm8q9cA(f, head);
}
LA8_: ;
close__fU6ZlJAtQ9bre04EDZLdGsA_3(f);
result = NIM_TRUE;
}
goto LA1_;
LA4_: ;
{
result = NIM_FALSE;
}
LA1_: ;
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___T3CpMgcFHzYracJ80CUZBQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_313), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___6wQcdZnh9aH29ay5rwY6M5fA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_314), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___y39ant8iE9bjKB0kbkRCAibQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_315), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___RKXvZR1cmZW5dfjtFQCG3g)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_316), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___nEA33x9cMfuJw3ZiGbn25iw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_317), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___0xK6HolrLvVFWil73hZYbA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_318), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___Z2c9cvs0wVVVqTEZ3Qwe9bfw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_319), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___AxDJCYpgPoquRsZtiOnpRw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_320), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___dU9cenGIcVUltUO1088LhYQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_321), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___TLpRy9aDJ1Ni4vccOIoiMbA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_322), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___RzB0z3UV9bb4kXUEGyS9crRA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_323), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___Z1QwTAihBHnxe59cytXnhmw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_324), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___XZnCV59at0sqX6ShEjlFLgw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_325), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___YLzwVVtf4fuPYZVeMQOa0Q)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_326), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___CtS8L8cOLTsSuQ10mtHsvw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) NIM_NIL), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___mPpmmd13MIZLTbd1oOdSkw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_327), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___Th3qC4WgcAhWPSlLw7vZ9cg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_328), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___3RPy0XXevrEBMts1Mb9arGw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_329), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___gqwqalZtiJtCgAF9bY5S6qQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_330), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___G9bYX9bu7ufcttiARCDUJ0qg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_331), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___W0CV9bE9bNiLgazfFZjoQCBg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_332), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___ecC7jlB6gBWrt0K9byHohPw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_333), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___hFzCKQOJ8Eao2AJk5HOvxA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_334), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___62079cK9bsws1aAJqEmAGo6w)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_335), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___hO1UTpWJhaojnhUyqfmgPQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_336), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___wlKCT75QSpBNooI9a2xvWeQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_8), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___uD0SC9bUeWpB9cK7V1aBT9aNQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_337), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___Uez7zQbKzeDFToq2Yh43bA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_338), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___JbygmsEkVsyK85BPVFvwbg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_339), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___FLXrAGf7HFTHIGh8Xuickg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_340), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___hmfCuT8fgBmRlPR25L7ZOw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_341), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___HUHatwko3S0fuszXQAOSQQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_342), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___gGKEcvCOVzpTQoSXzO01Dw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_343), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___LMnNsJkYlruXHnF5LV9c3pA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_344), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___uJ11bTQ8dBBAX88A2cyICw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_345), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___2D3IUNoEAKKLxuRqVNosPQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_346), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___o7SGM9buciKf5BOjTvMKA7w)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_347), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___Ht0mWR3LosfEZ8SopJcmEA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_348), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___GweM9byC8cQI9cehUzlYVs5A)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_349), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___Xnze9a4kYSwHurdPnhyNGzQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_350), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___sGaOrvR5YSM9cGUajaqcNOw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_351), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___GF60428RM29aXV0LYutm9aOA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_352), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___ciTj4q9cGhcXiXY9bPemZVvw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_353), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___HLoe040Vi0LPzmTid9aLGdw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_354), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___tnP9cO5PduJRSEeqtm9bocEg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_355), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___S6XcU2shl8EfYxL7utXbwg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_356), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___3GvB8fuMNh8BXF8IoORCxw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_357), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___RhAtD9c9aECDorIc8rDhMF9bw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_358), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___CSdlEV0i9aXEHNuC1G9aIEbw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_359), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___4SLS9cx2c8VCFIilepFlOeg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_360), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___amX0pef5rA4JAmWZ6ZB2Nw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_361), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___xAta147ahLKNrJMPPP5B6g)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_362), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___sshAiIx49ba6saVSAWuyFuA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_363), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___TmulmJw2SZspd0rz2PYvQw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_364), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___UFeu00R8dNoyzL8vy54mnQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_365), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___qYiwFpynEwFeSf3Aa2sS0g)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_366), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___6xseTZmgyslBQb6RMm9b4wA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_367), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___KsZXXO4zKP47iruPcSEryQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_368), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___TUxzei0sBfo3GESRTg1T5w)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_369), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___ikDBM4Dyw9c2kuwAAswRyOw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_370), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___ht9cduX4yJQKi2Gi685ag5A)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_371), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___Wsnl5zC9cCEBdwJcHgpLf0g)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_372), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___deWmrKhbFG0MxH9cDr9cnhfQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_373), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___HiCTlq0dXhMZvpDtUGWGQA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_374), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___aagcnoz4kFWlzsoVgR9b0NQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_375), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___oYhFcOWR4tEylepRJJLrlA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_376), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___3RBmOS8xzFTxpuGVryQycg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_377), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___apXghcMDCUp9col7jN5spHA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_378), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___9cNvJ1SVovK9b29bKmwKyiijw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_379), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___0mbMVYCe5Qwl9aQOKV3sh3w)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_380), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___03lrwELd9clj29bFkdXAVxkw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_381), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___8croAZ6oMdSPXHbIisuppw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_382), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___TDLJ9ciKDBoW4ouZs855Csg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_383), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___Mk2KRdMWX4H3L9aBEG2elgQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_384), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___pFXgvxsz2L5f27ImZwJwzQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_385), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___n9aTlv49bCxoRKQNZiWsaW2g)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_386), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___y3oNivo8px1XzxmB9b2OY5g)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_387), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___Pnqkcr360suaX84kwXMuCA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_388), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___FA4ohw0aOufzzLhmw9aUAhA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_389), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___SWZi8EY4Pz39bBPSp9cbtZMg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_390), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___XaBXRInsoVU7DBc2WK8dzg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_391), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___NdMO5d09brFwLfDc8ciTSqQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_392), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___E62TlyqwqpEwqcA0YTjttw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_393), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___m4T7v0qnGpOgwmMenKcgwg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_394), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___SKTmZPSgcdPr3Du3ia9b9czg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_395), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___ItxAXpnPzfUbYRPsHgKrPw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_396), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___ggqZXIgPaS71ubw22cYODw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_397), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___LLnl4aDVJynim7LQvfJKLQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_398), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___Ob6yLhv7QvbU9bdZj8Nw2kA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_399), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___qfsHROU9aHSaYGq3tpw1XDg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_400), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___j9bcJJvtd9bur0VZUQL3ibgA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_401), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___32ITt7hKDrhn9bXvKbmnE9bw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_402), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___ZAOkVi5SmgPcGpCSuSRXVA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_403), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___smDIOmjGgf8ZP9bfDyv43bQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_404), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___1jtIbjhXi2wH1iWPyC9bgAQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_405), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___NPgb4kECDcV8MICSil6Rjw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_406), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___cQHGAtgSLYV7mm9bnVGYGRA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_407), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___Q4LBu2cVl8IcNTrtxd6B6A)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_408), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___M36w8F9bFwighD3K39bvtVWw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_409), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___Wm11wQtuJBQgTy9a39apz0eA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_410), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___0bUw514mSumiNnSjkD0bqw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_411), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___6hxDi5nlebu1DFLqpYq5lw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_412), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___GkWgkK8SyjrFfWjGRwKWrw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_413), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___oubCLvBtU9aRB9bhG2vbCDeg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_414), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___KTcAQx04UE87HYZ48ZBm2A)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_415), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___Y6zpqvbZwK8tJZiKs9agbGw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_416), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___2OGTIxEeE0xFVRpz5TxKyg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_417), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___0xZtTB2eXM1dRd9aneL5VPw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_418), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___amO46kEKgIeOmW50ayV6nA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_419), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___3lABfXU9aXZsyfylYizY8KA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_420), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___5JCQx3oDHEcLdsEz6Rx0Rw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_421), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___dTtf7fil83VcW2Mkkr7scw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_422), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___88NG6Rr5xfTcA6hqLfZ2iw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_423), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___1DWSTPxvqlc4A2xRDmjZDw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_424), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___y5Z6ewsHLxj9ctzxTLPCLmw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_425), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___CHBd5pGE9c8nq4KNqM8K48g)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_426), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___y2h2X887dhz5sEoD4C8ezQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_427), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___dQfg2HrsVY6E7P22Nis1MA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_428), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___0b2Bm7vpM8YAMKp9cuAwg3g)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_429), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___1Hh3EN9c4pkzdKB09bo9c9aTBg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_430), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___AOSgPOjXfsLWEICRXv3U2g)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_431), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___gN4yb6p4ql6iVJOPAjLEJQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_432), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___WIg2bxfQLkmzIdOv1JkRqw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_433), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___3Klw9agVDELeF44OQ6PnRiA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_434), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___LL6jCaqBGLwC1sCgmCAEhQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_435), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___S9b9bs03lj0NJlhXUmrylsnA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_436), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___fphSfWWyYSWLARtGIpYB9aw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_437), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___As9aDT7fkqstj16MQnIGPhA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_438), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___eAZ21NmzzIsugeSSkcxIkQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_439), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___D2dSwFjTnRSmeKOoMm6w0Q)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_440), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___HlU9bV2X0HOPcGJnQlGm9c9aQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_441), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___p2lIQAdDBUpuVZML6ecUOg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_442), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___5hzyGWCNjqgqPj0O7sSnkg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_443), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___l1wvVBeU1Nnie8cWddgPCA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_444), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___yVZN2jQzbJwg3E9cehLff9cg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_445), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___E9br9b8BVYaWzg6CXcn9c6EXw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_446), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___qPugJ1Nc2L1EdGwEF0AJ0Q)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_447), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___HzZyrXo2QFynm1T8X76cCw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_448), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___O2nyVw4tGD6MMc6u7I9bH9cA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_449), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___IQYZUimFiAV9axFM9c64hKjA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_450), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___RCJU8UTq9cE0Jsi59anAbTIQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_451), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___S6vmSaSCgC4V2L5H7OWeZg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_452), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___Eqr9cgWCkrZrUG3sg0CawIQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_453), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___9c1lq60gbfPY9cyjQN4YouTQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_454), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___1nMXoOe6cENU7004pnh6wQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_455), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___ALynLzo8zWvno8ZxASdm4A)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_456), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___tlkWMVJPsx9aWUbp8FMjQ4w)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_457), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___xPW5KjObCPL2lJmHFoqfjg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_458), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___mTh2rYVPWUnI8B7kU3NWUg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_459), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___aoMj8hrcFi4HlPDZ9a9alpig)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_460), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___Yj64cHk9ajrzJI39bfpBfOVA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_461), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___9bY6R9buTsrqJYQAuD39cegOA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_462), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___U9b6hkqS6N7XIWr0gy8z9bug)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_463), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___2MwhwhkHOiavfXQl9aey8nA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_464), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___JRV6DlpqdegYGLcFjNPv0g)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_465), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___ryMkoQkM4zAjyp0800DrDQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_466), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___iW9bjdQoXkul7L0e76qo8XQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_467), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___i3z9am8Hzy69bSo575pRdzGw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_468), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___SkAQPSnCyiRvin57XULW4A)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_469), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___Bym8FwH29aQE8fth9ar38yJQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_470), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___CbbQqCp6itJgwKVRfTr69ag)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_471), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___HWgoOloM1oqcI9aZ9bEkoBhg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_472), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___Anf1UHjOzz9aHgMOgtnEPZA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_473), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___tDrtnFWakp63hyE9cfImgZw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_474), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___JwpI2xnYNfR68HstfDi1yQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_475), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___23SvbIxPpf5MIOga79arr6g)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_476), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___uVZXJGmbOGIG9bfkI4ZDwJQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_477), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___UxL9a0Hh7Km0Z0DIk7hp9cBA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_478), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___QxiH9aM0po7vA19b2s1CjdEA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_479), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___FZt89ajG3TKAhfL9aW4s7hcA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_480), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___5GaE39bOOeQZy3EFOEIy5QA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_481), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___SA9cvbR3uc9cP50nnaEBJctw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_482), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___KweYGQ9bFYg76nmoxpk8ksA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_483), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___AhY63HjLy2bPe9bslUNBuBQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_484), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___3m7YwdrxIvOkmvfnm5JYSA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_485), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___TEWiK8QWtRTCIQ9av7sW8LA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_486), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___9an6bUHwpxqyL2kgNHX3MEg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_487), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___kLwAORKb0c4oFgFTN9aEN8Q)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_488), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___Qm29ctdy9c4sqKctTsqiBWIg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_489), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___UyNt2Asj9aa2ScoGVo9cCnNw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_490), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___xXvQyblNYV215UGR9cTka7Q)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_491), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___LYjQOKn1i9ccw8AFlvPGkCg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_492), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___THj0xNXkqJf6reD7exsGbA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_493), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___3oFXAbir9c7XcKzu9bpgAM9bA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_494), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___4sbi76q7ZLqpKbD3pwJ59bQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_495), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___Q9cOQGrP4lOdbYHXMQ1yZtg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_496), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___0AX4Q6cA8nOXUagvzFqt0A)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_497), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___qQ3g8SwjZoIFAay85NaiEA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_498), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___M0TByFCTj9bbOkDSRpFz3LA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_499), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___OikfyLf8HmjI9auYLFoaVqg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_500), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___3KVF9aLACI1h11BqZrkzjNg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_501), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___ial810twbEzfkHaHMFYNCg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_502), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___Z7wCJf0WipOQOQ4ZZNBIEw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_503), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___Xpm9cGf2grEXdjAQV9arqWBQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_504), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___sqxyWwlLrfrdyc9b3BINcXQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_505), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___ztLQ2Orupb9b9b3KrCvoK9cbQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_506), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___PI6febxsdTbySkLsIEqHKw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_507), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___sGRyuC9caCxfdM1i8W4fjgw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_508), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___vWWA89aSvs5QwAFN4Jdr2IA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_509), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(NIM_BOOL, writeRopeIfNotEqual__Wiam9c8x73Mtmbj0r4Ppikg_2)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* r, NimStringDesc* filename) { NIM_BOOL result;
result = (NIM_BOOL)0;
{
NIM_BOOL T3_;
T3_ = (NIM_BOOL)0;
T3_ = equalsFile__Wiam9c8x73Mtmbj0r4Ppikg(r, filename);
if (!!(T3_)) goto LA4_;
result = writeRope__LLRRC42xWBSkxzV9bsPu7lA(r, filename);
}
goto LA1_;
LA4_: ;
{
result = NIM_FALSE;
}
LA1_: ;
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___lQuk161wRVxbYxfH80Iwcw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_510), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___UQrwMIIitnm9cEflSXdCkPg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_511), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___A9aKFJUF6ZjJQfrcPHJigOQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_512), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___8ehuHmXS8omgqFrdYMsPBg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_513), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___2Opo6JkHmCRmDA87qcGfvg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_514), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___C7jQ1fH79bR8HRQrbJjFKDg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_515), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___2eu2gmgXiDUZkBgTVqD7pg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_516), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___cCI1wZSoDB14achJW7ZFSQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_517), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___dkLAWa1dMAcGEAyfUZ59bRA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_518), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___DuvwOyJJ9b2gpVM9cV7DCFSQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_519), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___4MBgNtJLOyqbjfGytl2OTw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_520), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___336bx9aXX7GZckfWQE5Jy3g)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_521), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___IbsmsXdtDOH7pLpzh9cmAOA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_522), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___9cGelOO9b6sliTnobJf6XAsg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_523), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___aNorSJCSJyyDo7w0s6eynA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_524), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___BYRFs7dwiqyMIzbsx9cDq8Q)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_525), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___TavFv5xK0dxxJCk9b4v34zg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_526), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___9aAWQyBOqadJYgBT29bzliAw)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_527), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___zpFS2Xy9cmoAoqCFSUQj1gg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_528), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___Nz9cwOtMmcX2gklRogKhyEA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_529), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___YGYo0XYmypYw3N26AYh7ug)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_530), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___e8Z4ajz6IErIB0a6mpq4Wg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_531), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___eqn09cqDPu9csxGUOSa2untg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_532), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___rZ5o6ziDKz4d3bfaN54Dgg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_533), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___YGa4o1aenD9cjoU03CAgtqQ)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_534), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___b2PLtFwpZkVmYhHWvW4i1Q)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_535), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___ctY4Nx9aQFC9bl9c2wbRLoFYA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_536), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___xsFAphqq4CRpmuZ79bXVLrA)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_537), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___SSpcZv60d0mAp5H4Mb5hpg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_538), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___TtzOadDB4I9a89cWej19a2PNg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_539), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*, percent___KKiSvh9a121M0uSQjcJhhMg)(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA** args, NI argsLen_0) { tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA* result;
result = (tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*)0;
result = runtimeFormat__9bvKdnhoYI2ta9agQNm3orMA(((NimStringDesc*) &TM__Vw9cfUOQOae9b9bzZBlucMZQg_540), args, argsLen_0);
return result;
}
N_LIB_PRIVATE N_NIMCALL(void, compiler_ropesInit000)(void) {
{
nimRegisterGlobalMarker(TM__Vw9cfUOQOae9b9bzZBlucMZQg_3);
gCacheTries__5GfZTThHPBfB9bjRZdFluBw = ((NI) 0);
gCacheMisses__fLRm9am8S0daYBVNK6JKyBg = ((NI) 0);
gCacheIntTries__opyfsNv023Md1P05mqsDew = ((NI) 0);
}
}
N_LIB_PRIVATE N_NIMCALL(void, compiler_ropesDatInit000)(void) {
static TNimNode* TM__Vw9cfUOQOae9b9bzZBlucMZQg_2_4[4];
static TNimNode TM__Vw9cfUOQOae9b9bzZBlucMZQg_0[5];
NTI__OFzf0kSiPTcNreUIeJgWVA_.size = sizeof(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA);
NTI__OFzf0kSiPTcNreUIeJgWVA_.kind = 17;
NTI__OFzf0kSiPTcNreUIeJgWVA_.base = (&NTI__ytyiCJqK439aF9cIibuRVpAg_);
TM__Vw9cfUOQOae9b9bzZBlucMZQg_2_4[0] = &TM__Vw9cfUOQOae9b9bzZBlucMZQg_0[1];
TM__Vw9cfUOQOae9b9bzZBlucMZQg_0[1].kind = 1;
TM__Vw9cfUOQOae9b9bzZBlucMZQg_0[1].offset = offsetof(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA, left);
TM__Vw9cfUOQOae9b9bzZBlucMZQg_0[1].typ = (&NTI__4hi0XQqK9aLiPuWT9acsXm9aQ_);
TM__Vw9cfUOQOae9b9bzZBlucMZQg_0[1].name = "left";
TM__Vw9cfUOQOae9b9bzZBlucMZQg_2_4[1] = &TM__Vw9cfUOQOae9b9bzZBlucMZQg_0[2];
TM__Vw9cfUOQOae9b9bzZBlucMZQg_0[2].kind = 1;
TM__Vw9cfUOQOae9b9bzZBlucMZQg_0[2].offset = offsetof(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA, right);
TM__Vw9cfUOQOae9b9bzZBlucMZQg_0[2].typ = (&NTI__4hi0XQqK9aLiPuWT9acsXm9aQ_);
TM__Vw9cfUOQOae9b9bzZBlucMZQg_0[2].name = "right";
TM__Vw9cfUOQOae9b9bzZBlucMZQg_2_4[2] = &TM__Vw9cfUOQOae9b9bzZBlucMZQg_0[3];
TM__Vw9cfUOQOae9b9bzZBlucMZQg_0[3].kind = 1;
TM__Vw9cfUOQOae9b9bzZBlucMZQg_0[3].offset = offsetof(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA, L);
TM__Vw9cfUOQOae9b9bzZBlucMZQg_0[3].typ = (&NTI__rR5Bzr1D5krxoo1NcNyeMA_);
TM__Vw9cfUOQOae9b9bzZBlucMZQg_0[3].name = "L";
TM__Vw9cfUOQOae9b9bzZBlucMZQg_2_4[3] = &TM__Vw9cfUOQOae9b9bzZBlucMZQg_0[4];
TM__Vw9cfUOQOae9b9bzZBlucMZQg_0[4].kind = 1;
TM__Vw9cfUOQOae9b9bzZBlucMZQg_0[4].offset = offsetof(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA, data);
TM__Vw9cfUOQOae9b9bzZBlucMZQg_0[4].typ = (&NTI__77mFvmsOLKik79ci2hXkHEg_);
TM__Vw9cfUOQOae9b9bzZBlucMZQg_0[4].name = "data";
TM__Vw9cfUOQOae9b9bzZBlucMZQg_0[0].len = 4; TM__Vw9cfUOQOae9b9bzZBlucMZQg_0[0].kind = 2; TM__Vw9cfUOQOae9b9bzZBlucMZQg_0[0].sons = &TM__Vw9cfUOQOae9b9bzZBlucMZQg_2_4[0];
NTI__OFzf0kSiPTcNreUIeJgWVA_.node = &TM__Vw9cfUOQOae9b9bzZBlucMZQg_0[0];
NTI__4hi0XQqK9aLiPuWT9acsXm9aQ_.size = sizeof(tyObject_RopeObj__OFzf0kSiPTcNreUIeJgWVA*);
NTI__4hi0XQqK9aLiPuWT9acsXm9aQ_.kind = 22;
NTI__4hi0XQqK9aLiPuWT9acsXm9aQ_.base = (&NTI__OFzf0kSiPTcNreUIeJgWVA_);
NTI__4hi0XQqK9aLiPuWT9acsXm9aQ_.marker = Marker_tyRef__4hi0XQqK9aLiPuWT9acsXm9aQ;
NTI__USLYl0Lpkimm4FABiJ3ldA_.size = sizeof(tyArray__USLYl0Lpkimm4FABiJ3ldA);
NTI__USLYl0Lpkimm4FABiJ3ldA_.kind = 16;
NTI__USLYl0Lpkimm4FABiJ3ldA_.base = (&NTI__4hi0XQqK9aLiPuWT9acsXm9aQ_);
}
|
GB_unaryop__ainv_bool_bool.c
|
//------------------------------------------------------------------------------
// GB_unaryop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved.
// http://suitesparse.com See GraphBLAS/Doc/License.txt for license.
//------------------------------------------------------------------------------
// If this file is in the Generated/ folder, do not edit it (auto-generated).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_iterator.h"
#include "GB_unaryop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB_unop__ainv_bool_bool
// op(A') function: GB_tran__ainv_bool_bool
// C type: bool
// A type: bool
// cast: bool cij = (bool) aij
// unaryop: cij = aij
#define GB_ATYPE \
bool
#define GB_CTYPE \
bool
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
bool aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = x ;
// casting
#define GB_CASTING(z, aij) \
bool z = (bool) aij ;
// cij = op (cast (aij))
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
GB_GETA (aij, Ax, pA) ; \
/* Cx [pC] = op (cast (aij)) */ \
GB_CASTING (z, aij) ; \
GB_OP (GB_CX (pC), z) ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_AINV || GxB_NO_BOOL)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop__ainv_bool_bool
(
bool *Cx, // Cx and Ax may be aliased
bool *Ax,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
GB_CAST_OP (p, p) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_tran__ainv_bool_bool
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t *GB_RESTRICT *Rowcounts,
GBI_single_iterator Iter,
const int64_t *GB_RESTRICT A_slice,
int naslice
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#define GB_PHASE_2_OF_2
#include "GB_unaryop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
box3d1r.c
|
#define BENCH_DIM 3
#define BENCH_FPP 53
#define BENCH_RAD 1
#include "common.h"
double kernel_stencil(SB_TYPE *A1, int compsize, int timestep, bool scop)
{
double start_time = sb_time(), end_time = 0.0;
int dimsize = compsize + BENCH_RAD * 2;
SB_TYPE (*A)[dimsize][dimsize][dimsize]
= (SB_TYPE (*)[dimsize][dimsize][dimsize])A1;
if (scop) {
#pragma scop
for (int t = 0; t < timestep; t++)
for (int i = BENCH_RAD; i < dimsize - BENCH_RAD; i++)
for (int j = BENCH_RAD; j < dimsize - BENCH_RAD; j++)
for (int k = BENCH_RAD; k < dimsize - BENCH_RAD; k++)
A[(t+1)%2][i][j][k] =
0.0375f*A[t%2][i-1][j][k] +
0.0371f*A[t%2][i-1][j-1][k-1] +
0.0372f*A[t%2][i-1][j-1][k] +
0.0373f*A[t%2][i-1][j-1][k+1] +
0.0374f*A[t%2][i-1][j][k-1] +
0.0376f*A[t%2][i-1][j][k+1] +
0.0377f*A[t%2][i-1][j+1][k-1] +
0.0378f*A[t%2][i-1][j+1][k] +
0.0379f*A[t%2][i-1][j+1][k+1] +
0.0355f*A[t%2][i][j][k] +
0.0351f*A[t%2][i][j-1][k-1] +
0.0352f*A[t%2][i][j-1][k] +
0.0353f*A[t%2][i][j-1][k+1] +
0.0354f*A[t%2][i][j][k-1] +
0.0356f*A[t%2][i][j][k+1] +
0.0357f*A[t%2][i][j+1][k-1] +
0.0358f*A[t%2][i][j+1][k] +
0.0359f*A[t%2][i][j+1][k+1] +
0.0365f*A[t%2][i+1][j][k] +
0.0361f*A[t%2][i+1][j-1][k-1] +
0.0362f*A[t%2][i+1][j-1][k] +
0.0363f*A[t%2][i+1][j-1][k+1] +
0.0364f*A[t%2][i+1][j][k-1] +
0.0366f*A[t%2][i+1][j][k+1] +
0.0367f*A[t%2][i+1][j+1][k-1] +
0.0368f*A[t%2][i+1][j+1][k] +
0.0369f*A[t%2][i+1][j+1][k+1];
#pragma endscop
}
else {
for (int t = 0; t < timestep; t++)
#pragma omp parallel for
for (int i = BENCH_RAD; i < dimsize - BENCH_RAD; i++)
for (int j = BENCH_RAD; j < dimsize - BENCH_RAD; j++)
for (int k = BENCH_RAD; k < dimsize - BENCH_RAD; k++)
A[(t+1)%2][i][j][k] =
0.0375f*A[t%2][i-1][j][k] +
0.0371f*A[t%2][i-1][j-1][k-1] +
0.0372f*A[t%2][i-1][j-1][k] +
0.0373f*A[t%2][i-1][j-1][k+1] +
0.0374f*A[t%2][i-1][j][k-1] +
0.0376f*A[t%2][i-1][j][k+1] +
0.0377f*A[t%2][i-1][j+1][k-1] +
0.0378f*A[t%2][i-1][j+1][k] +
0.0379f*A[t%2][i-1][j+1][k+1] +
0.0355f*A[t%2][i][j][k] +
0.0351f*A[t%2][i][j-1][k-1] +
0.0352f*A[t%2][i][j-1][k] +
0.0353f*A[t%2][i][j-1][k+1] +
0.0354f*A[t%2][i][j][k-1] +
0.0356f*A[t%2][i][j][k+1] +
0.0357f*A[t%2][i][j+1][k-1] +
0.0358f*A[t%2][i][j+1][k] +
0.0359f*A[t%2][i][j+1][k+1] +
0.0365f*A[t%2][i+1][j][k] +
0.0361f*A[t%2][i+1][j-1][k-1] +
0.0362f*A[t%2][i+1][j-1][k] +
0.0363f*A[t%2][i+1][j-1][k+1] +
0.0364f*A[t%2][i+1][j][k-1] +
0.0366f*A[t%2][i+1][j][k+1] +
0.0367f*A[t%2][i+1][j+1][k-1] +
0.0368f*A[t%2][i+1][j+1][k] +
0.0369f*A[t%2][i+1][j+1][k+1];
}
return (((end_time != 0.0) ? end_time : sb_time()) - start_time);
}
|
sageInterface.h
|
#ifndef ROSE_SAGE_INTERFACE
#define ROSE_SAGE_INTERFACE
#include "sage3basic.hhh"
#include <stdint.h>
#include <utility>
#include "rosePublicConfig.h" // for ROSE_BUILD_JAVA_LANGUAGE_SUPPORT
#include "OmpAttribute.h"
#if 0 // FMZ(07/07/2010): the argument "nextErrorCode" should be call-by-reference
SgFile* determineFileType ( std::vector<std::string> argv, int nextErrorCode, SgProject* project );
#else
SgFile* determineFileType ( std::vector<std::string> argv, int& nextErrorCode, SgProject* project );
#endif
#ifndef ROSE_USE_INTERNAL_FRONTEND_DEVELOPMENT
#include "rewrite.h"
#endif
// DQ (7/20/2008): Added support for unparsing abitrary strings in the unparser.
#include "astUnparseAttribute.h"
#include <set>
#ifndef ROSE_USE_INTERNAL_FRONTEND_DEVELOPMENT
#include "LivenessAnalysis.h"
#include "abstract_handle.h"
#include "ClassHierarchyGraph.h"
#endif
// DQ (8/19/2004): Moved from ROSE/src/midend/astRewriteMechanism/rewrite.h
//! A global function for getting the string associated with an enum (which is defined in global scope)
ROSE_DLL_API std::string getVariantName (VariantT v);
// DQ (12/9/2004): Qing, Rich and Dan have decided to start this namespace within ROSE
// This namespace is specific to interface functions that operate on the Sage III AST.
// The name was chosen so as not to conflict with other classes within ROSE.
// This will become the future home of many interface functions which operate on
// the AST and which are generally useful to users. As a namespace multiple files can be used
// to represent the compete interface and different developers may contribute interface
// functions easily.
// Constructor handling: (We have sageBuilder.h now for this purpose, Liao 2/1/2008)
// We could add simpler layers of support for construction of IR nodes by
// hiding many details in "makeSg***()" functions. Such functions would
// return pointers to the associated Sg*** objects and would be able to hide
// many IR specific details, including:
// memory handling
// optional parameter settings not often required
// use of Sg_File_Info objects (and setting them as transformations)
//
// namespace AST_Interface (this name is taken already by some of Qing's work :-)
//! An alias for Sg_File_Info::generateDefaultFileInfoForTransformationNode()
#define TRANS_FILE Sg_File_Info::generateDefaultFileInfoForTransformationNode()
/** Functions that are useful when operating on the AST.
*
* The Sage III IR design attempts to be minimalist. Thus additional functionality is intended to be presented using separate
* higher level interfaces which work with the IR. This namespace collects functions that operate on the IR and support
* numerous types of operations that are common to general analysis and transformation of the AST. */
namespace SageInterface
{
// Liao 6/22/2016: keep records of loop init-stmt normalization, later help undo it to support autoPar.
struct Transformation_Record
{
// a lookup table to check if a for loop has been normalized for its c99-style init-stmt
std::map <SgForStatement* , bool > forLoopInitNormalizationTable;
// Detailed record about the original declaration (1st in the pair) and the normalization generated new declaration (2nd in the pair)
std::map <SgForStatement* , std::pair<SgVariableDeclaration*, SgVariableDeclaration*> > forLoopInitNormalizationRecord;
} ;
ROSE_DLL_API extern Transformation_Record trans_records;
// DQ (4/3/2014): Added general AST support separate from the AST.
// Container and API for analysis information that is outside of the AST and as a result
// prevents frequent modification of the IR.
class DeclarationSets
{
// DQ (4/3/2014): This stores all associated declarations as a map of sets.
// the key to the map is the first nondefining declaration and the elements of the set are
// all of the associated declarations (including the defining declaration).
private:
//! Map of first-nondefining declaration to all other associated declarations.
std::map<SgDeclarationStatement*,std::set<SgDeclarationStatement*>* > declarationMap;
public:
void addDeclaration(SgDeclarationStatement* decl);
const std::set<SgDeclarationStatement*>* getDeclarations(SgDeclarationStatement* decl);
std::map<SgDeclarationStatement*,std::set<SgDeclarationStatement*>* > & getDeclarationMap();
bool isLocatedInDefiningScope(SgDeclarationStatement* decl);
};
// DQ (4/3/2014): This constructs a data structure that holds analysis information about
// the AST that is separate from the AST. This is intended to be a general mechanism
// to support analysis information without constantly modifying the IR.
DeclarationSets* buildDeclarationSets(SgNode*);
//! An internal counter for generating unique SgName
ROSE_DLL_API extern int gensym_counter;
#ifdef ROSE_ENABLE_BINARY_ANALYSIS
//! Find the main interpretation.
SgAsmInterpretation* getMainInterpretation(SgAsmGenericFile* file);
//! Get the unsigned value of a disassembled constant.
uint64_t getAsmConstant(SgAsmValueExpression* e);
//! Get the signed value of a disassembled constant.
int64_t getAsmSignedConstant(SgAsmValueExpression *e);
#endif
//! Function to add "C" style comment to statement.
void addMessageStatement( SgStatement* stmt, std::string message );
//! A persistent attribute to represent a unique name for an expression
class UniqueNameAttribute : public AstAttribute
{
private:
std::string name;
public:
UniqueNameAttribute(std::string n="") {name =n; };
void set_name (std::string n) {name = n;};
std::string get_name () {return name;};
};
//------------------------------------------------------------------------
//@{
/*! @name Symbol tables
\brief utility functions for symbol tables
*/
// DQ (8/5/2020): the "using namespace" directive will not hide existing visability of symbols in resolving visability.
// So we need to test if a symbol is visible exclusing matching alises due to using direectives before we can decide to
// persue name space qualification. This is best demonstrated by Cxx_tests/test2020_18.C, test2020_19.C, test2020_20.C,
// and test2020_21.C.
ROSE_DLL_API SgSymbol *lookupSymbolInParentScopesIgnoringAliasSymbols (const SgName & name, SgScopeStatement *currentScope = NULL, SgTemplateParameterPtrList* templateParameterList = NULL, SgTemplateArgumentPtrList* templateArgumentList = NULL);
// DQ (8/21/2013): Modified to make newest function parameters be default arguments.
// DQ (8/16/2013): For now we want to remove the use of default parameters and add the support for template parameters and template arguments.
//! Find a symbol in current and ancestor scopes for a given variable name, starting from top of ScopeStack if currentscope is not given or NULL.
// SgSymbol *lookupSymbolInParentScopes (const SgName & name, SgScopeStatement *currentScope=NULL);
// SgSymbol *lookupSymbolInParentScopes (const SgName & name, SgScopeStatement *currentScope, SgTemplateParameterPtrList* templateParameterList, SgTemplateArgumentPtrList* templateArgumentList);
ROSE_DLL_API SgSymbol *lookupSymbolInParentScopes (const SgName & name, SgScopeStatement *currentScope = NULL, SgTemplateParameterPtrList* templateParameterList = NULL, SgTemplateArgumentPtrList* templateArgumentList = NULL);
// Liao 1/22/2008, used for get symbols for generating variable reference nodes
// ! Find a variable symbol in current and ancestor scopes for a given name
ROSE_DLL_API SgVariableSymbol *lookupVariableSymbolInParentScopes (const SgName & name, SgScopeStatement *currentScope=NULL);
// DQ (11/24/2007): Functions moved from the Fortran support so that they could be called from within astPostProcessing.
//!look up the first matched function symbol in parent scopes given only a function name, starting from top of ScopeStack if currentscope is not given or NULL
ROSE_DLL_API SgFunctionSymbol *lookupFunctionSymbolInParentScopes (const SgName & functionName, SgScopeStatement *currentScope=NULL);
// Liao, 1/24/2008, find exact match for a function
//!look up function symbol in parent scopes given both name and function type, starting from top of ScopeStack if currentscope is not given or NULL
ROSE_DLL_API SgFunctionSymbol *lookupFunctionSymbolInParentScopes (const SgName & functionName,
const SgType* t,
SgScopeStatement *currentScope=NULL);
ROSE_DLL_API SgFunctionSymbol *lookupTemplateFunctionSymbolInParentScopes (const SgName & functionName, SgFunctionType * ftype, SgTemplateParameterPtrList * tplparams, SgScopeStatement *currentScope=NULL);
ROSE_DLL_API SgFunctionSymbol *lookupTemplateMemberFunctionSymbolInParentScopes (const SgName & functionName, SgFunctionType * ftype, SgTemplateParameterPtrList * tplparams, SgScopeStatement *currentScope=NULL);
ROSE_DLL_API SgTemplateVariableSymbol * lookupTemplateVariableSymbolInParentScopes (const SgName & name, SgTemplateParameterPtrList * tplparams, SgTemplateArgumentPtrList* tplargs, SgScopeStatement *currentScope=NULL);
// DQ (8/21/2013): Modified to make newest function parameters be default arguments.
// DQ (8/16/2013): For now we want to remove the use of default parameters and add the support for template parameters and template arguments.
// DQ (5/7/2011): Added support for SgClassSymbol (used in name qualification support).
// SgClassSymbol* lookupClassSymbolInParentScopes (const SgName & name, SgScopeStatement *currentScope = NULL);
ROSE_DLL_API SgClassSymbol* lookupClassSymbolInParentScopes (const SgName & name, SgScopeStatement *currentScope = NULL, SgTemplateArgumentPtrList* templateArgumentList = NULL);
ROSE_DLL_API SgTypedefSymbol* lookupTypedefSymbolInParentScopes (const SgName & name, SgScopeStatement *currentScope = NULL);
ROSE_DLL_API SgNonrealSymbol* lookupNonrealSymbolInParentScopes (const SgName & name, SgScopeStatement *currentScope = NULL, SgTemplateParameterPtrList* templateParameterList = NULL, SgTemplateArgumentPtrList* templateArgumentList = NULL);
#if 0
// DQ (8/13/2013): This function does not make since any more, now that we have made the symbol
// table handling more precise and we have to provide template parameters for any template lookup.
// We also have to know if we want to lookup template classes, template functions, or template
// member functions (since each have specific requirements).
SgTemplateSymbol* lookupTemplateSymbolInParentScopes (const SgName & name, SgScopeStatement *currentScope = NULL);
#endif
#if 0
// DQ (8/13/2013): I am not sure if we want this functions in place of lookupTemplateSymbolInParentScopes.
// Where these are called we might not know enough information about the template parameters or function
// types, for example.
SgTemplateClassSymbol* lookupTemplateClassSymbolInParentScopes (const SgName & name, SgScopeStatement *currentScope = NULL, SgTemplateParameterPtrList* templateParameterList = NULL, SgTemplateArgumentPtrList* templateArgumentList = NULL);
SgTemplateFunctionSymbol* lookupTemplateFunctionSymbolInParentScopes (const SgName & name, SgScopeStatement *currentScope = NULL, SgTemplateParameterPtrList* templateParameterList = NULL);
SgTemplateMemberFunctionSymbol* lookupTemplateMemberFunctionSymbolInParentScopes (const SgName & name, SgScopeStatement *currentScope = NULL, SgTemplateParameterPtrList* templateParameterList = NULL);
#endif
// DQ (8/21/2013): Modified to make some of the newest function parameters be default arguments.
// DQ (8/13/2013): I am not sure if we want this functions in place of lookupTemplateSymbolInParentScopes.
ROSE_DLL_API SgTemplateClassSymbol* lookupTemplateClassSymbolInParentScopes (const SgName & name, SgTemplateParameterPtrList* templateParameterList, SgTemplateArgumentPtrList* templateArgumentList, SgScopeStatement *cscope = NULL);
ROSE_DLL_API SgEnumSymbol* lookupEnumSymbolInParentScopes (const SgName & name, SgScopeStatement *currentScope = NULL);
ROSE_DLL_API SgNamespaceSymbol* lookupNamespaceSymbolInParentScopes(const SgName & name, SgScopeStatement *currentScope = NULL);
// DQ (7/17/2011): Added function from cxx branch that I need here for the Java support.
// SgClassSymbol* lookupClassSymbolInParentScopes (const SgName & name, SgScopeStatement *cscope);
/*! \brief set_name of symbol in symbol table.
This function extracts the symbol from the relavant symbol table,
changes the name (at the declaration) and reinserts it into the
symbol table.
\internal I think this is what this function does, I need to double check.
*/
// DQ (12/9/2004): Moved this function (by Alin Jula) from being a member of SgInitializedName
// to this location where it can be a part of the interface for the Sage III AST.
ROSE_DLL_API int set_name (SgInitializedName * initializedNameNode, SgName new_name);
/*! \brief Output function type symbols in global function type symbol table.
*/
void outputGlobalFunctionTypeSymbolTable ();
// DQ (6/27/2005):
/*! \brief Output the local symbol tables.
\implementation Each symbol table is output with the file infor where it is located in the source code.
*/
ROSE_DLL_API void outputLocalSymbolTables (SgNode * node);
class OutputLocalSymbolTables:public AstSimpleProcessing
{
public:
void visit (SgNode * node);
};
/*! \brief Regenerate the symbol table.
\implementation current symbol table must be NULL pointer before calling this
function (for safety, but is this a good idea?)
*/
// DQ (9/28/2005):
void rebuildSymbolTable (SgScopeStatement * scope);
/*! \brief Clear those variable symbols with unknown type (together with initialized names) which are also not referenced by any variable references or declarations under root. If root is NULL, all symbols with unknown type will be deleted.
*/
void clearUnusedVariableSymbols (SgNode* root = NULL);
// DQ (3/1/2009):
//! All the symbol table references in the copied AST need to be reset after rebuilding the copied scope's symbol table.
void fixupReferencesToSymbols( const SgScopeStatement* this_scope, SgScopeStatement* copy_scope, SgCopyHelp & help );
//@}
//------------------------------------------------------------------------
//@{
/*! @name Stringify
\brief Generate a useful string (name) to describe a SgNode
*/
/*! \brief Generate a useful name to describe the SgNode
\internal default names are used for SgNode objects that can not be associated with a name.
*/
// DQ (9/21/2005): General function for extracting the name of declarations (when they have names)
std::string get_name (const SgNode * node);
/*! \brief Generate a useful name to describe the declaration
\internal default names are used for declarations that can not be associated with a name.
*/
// DQ (6/13/2005): General function for extracting the name of declarations (when they have names)
std::string get_name (const SgStatement * stmt);
/*! \brief Generate a useful name to describe the expression
\internal default names are used for expressions that can not be associated with a name.
*/
std::string get_name (const SgExpression * expr);
/*! \brief Generate a useful name to describe the declaration
\internal default names are used for declarations that can not be associated with a name.
*/
// DQ (6/13/2005): General function for extracting the name of declarations (when they have names)
std::string get_name (const SgDeclarationStatement * declaration);
/*! \brief Generate a useful name to describe the scope
\internal default names are used for scope that cannot be associated with a name.
*/
// DQ (6/13/2005): General function for extracting the name of declarations (when they have names)
std::string get_name (const SgScopeStatement * scope);
/*! \brief Generate a useful name to describe the SgSymbol
\internal default names are used for SgSymbol objects that cannot be associated with a name.
*/
// DQ (2/11/2007): Added this function to make debugging support more complete (useful for symbol table debugging support).
std::string get_name (const SgSymbol * symbol);
/*! \brief Generate a useful name to describe the SgType
\internal default names are used for SgType objects that cannot be associated with a name.
*/
std::string get_name (const SgType * type);
/*! \brief Generate a useful name to describe the SgSupport IR node
*/
std::string get_name (const SgSupport * node);
/*! \brief Generate a useful name to describe the SgLocatedNodeSupport IR node
*/
std::string get_name (const SgLocatedNodeSupport * node);
/*! \brief Generate a useful name to describe the SgC_PreprocessorDirectiveStatement IR node
*/
std::string get_name ( const SgC_PreprocessorDirectiveStatement* directive );
/*! \brief Generate a useful name to describe the SgToken IR node
*/
std::string get_name ( const SgToken* token );
// DQ (3/20/2016): Added to refactor some of the DSL infrastructure support.
/*! \brief Generate a useful name to support construction of identifiers from declarations.
This function permits names to be generated that will be unique across translation units
(a specific requirement different from the context of the get_name() functions above).
\internal This supports only a restricted set of declarations presently.
*/
std::string generateUniqueNameForUseAsIdentifier ( SgDeclarationStatement* declaration );
std::string generateUniqueNameForUseAsIdentifier_support ( SgDeclarationStatement* declaration );
/*! \brief Global map of name collisions to support generateUniqueNameForUseAsIdentifier() function.
*/
extern std::map<std::string,int> local_name_collision_map;
extern std::map<std::string,SgNode*> local_name_to_node_map;
extern std::map<SgNode*,std::string> local_node_to_name_map;
/*! \brief Traversal to set the global map of names to node and node to names.collisions to support generateUniqueNameForUseAsIdentifier() function.
*/
void computeUniqueNameForUseAsIdentifier( SgNode* astNode );
/*! \brief Reset map variables used to support generateUniqueNameForUseAsIdentifier() function.
*/
void reset_name_collision_map();
//@}
//------------------------------------------------------------------------
//@{
/*! @name Class utilities
\brief
*/
/*! \brief Get the default destructor from the class declaration
*/
// DQ (6/21/2005): Get the default destructor from the class declaration
ROSE_DLL_API SgMemberFunctionDeclaration *getDefaultDestructor (SgClassDeclaration* classDeclaration);
/*! \brief Get the default constructor from the class declaration
*/
// DQ (6/22/2005): Get the default constructor from the class declaration
ROSE_DLL_API SgMemberFunctionDeclaration *getDefaultConstructor (SgClassDeclaration* classDeclaration);
/*! \brief Return true if template definition is in the class, false if outside of class.
*/
// DQ (8/27/2005):
ROSE_DLL_API bool templateDefinitionIsInClass (SgTemplateInstantiationMemberFunctionDecl* memberFunctionDeclaration);
/*! \brief Generate a non-defining (forward) declaration from a defining function declaration.
\internal should put into sageBuilder ?
*/
// DQ (9/17/2005):
ROSE_DLL_API SgTemplateInstantiationMemberFunctionDecl* buildForwardFunctionDeclaration (SgTemplateInstantiationMemberFunctionDecl * memberFunctionInstantiation);
//! Check if a SgNode is a declaration for a structure
ROSE_DLL_API bool isStructDeclaration(SgNode * node);
//! Check if a SgNode is a declaration for a union
ROSE_DLL_API bool isUnionDeclaration(SgNode * node);
#if 0
// DQ (8/28/2005): This is already a member function of the SgFunctionDeclaration
// (so that it can handle template functions and member functions)
/*! \brief Return true if member function of a template member function,
of false if a non-template member function in a templated class.
*/
// DQ (8/27/2005):
bool isTemplateMemberFunction (SgTemplateInstantiationMemberFunctionDecl* memberFunctionDeclaration);
#endif
// DQ (11/9/2020): Added function to support adding a default constructor definition to a class
// if it does not have a default constructor, but has any other constructor that would prevend
// a compiler generated default constructor from being generated by the compiler.
// Note the physical_file_id is so that it can be marked to be unparsed when header file unparsing is active.
ROSE_DLL_API bool addDefaultConstructorIfRequired ( SgClassType* classType, int physical_file_id = Sg_File_Info::TRANSFORMATION_FILE_ID );
//@}
//------------------------------------------------------------------------
//@{
/*! @name Misc.
\brief Not sure the classifications right now
*/
//! Recursively print current and parent nodes. used within gdb to probe the context of a node.
void recursivePrintCurrentAndParent (SgNode* n) ;
//! Save AST into a pdf file. Start from a node to find its enclosing file node. The entire file's AST will be saved into a pdf.
void saveToPDF(SgNode* node, std::string filename);
void saveToPDF(SgNode* node); // enable calling from gdb
//! Pretty print AST horizontally, output to std output
void printAST (SgNode* node);
//! Pretty print AST horizontally, output to a specified text file.
void printAST2TextFile (SgNode* node, const char* filename);
void printAST2TextFile (SgNode* node, std::string filename);
// DQ (2/12/2012): Added some diagnostic support.
//! Diagnostic function for tracing back through the parent list to understand at runtime where in the AST a failure happened.
void whereAmI(SgNode* node);
//! Extract a SgPragmaDeclaration's leading keyword . For example "#pragma omp parallel" has a keyword of "omp".
std::string extractPragmaKeyword(const SgPragmaDeclaration *);
//! Check if a node is SgOmp*Statement
ROSE_DLL_API bool isOmpStatement(SgNode* );
/*! \brief Return true if function is overloaded.
*/
// DQ (8/27/2005):
bool isOverloaded (SgFunctionDeclaration * functionDeclaration);
// DQ (2/14/2012): Added support function used for variable declarations in conditionals.
//! Support function used for variable declarations in conditionals
void initializeIfStmt(SgIfStmt *ifstmt, SgStatement* conditional, SgStatement * true_body, SgStatement * false_body);
//! Support function used for variable declarations in conditionals
void initializeSwitchStatement(SgSwitchStatement* switchStatement,SgStatement *item_selector,SgStatement *body);
//! Support function used for variable declarations in conditionals
void initializeWhileStatement(SgWhileStmt* whileStatement, SgStatement * condition, SgStatement *body, SgStatement *else_body);
//! Generate unique names for expressions and attach the names as persistent attributes ("UniqueNameAttribute")
void annotateExpressionsWithUniqueNames (SgProject* project);
//! Check if a SgNode is a main() function declaration
ROSE_DLL_API bool isMain (const SgNode* node);
// DQ (6/22/2005):
/*! \brief Generate unique name from C and C++ constructs. The name may contain space.
This is support for the AST merge, but is generally useful as a more general mechanism than
name mangling which is more closely ties to the generation of names to support link-time function name
resolution. This is more general than common name mangling in that it resolves more relevant differences
between C and C++ declarations. (e.g. the type within the declaration: "struct { int:8; } foo;").
\implementation current work does not support expressions.
*/
std::string generateUniqueName ( const SgNode * node, bool ignoreDifferenceBetweenDefiningAndNondefiningDeclarations);
/** Generate a name like __temp#__ that is unique in the current scope and any parent and children scopes. # is a unique integer counter.
* @param baseName the word to be included in the variable names. */
std::string generateUniqueVariableName(SgScopeStatement* scope, std::string baseName = "temp");
// DQ (8/10/2010): Added const to first parameter.
// DQ (3/10/2007):
//! Generate a unique string from the source file position information
std::string declarationPositionString (const SgDeclarationStatement * declaration);
// DQ (1/20/2007):
//! Added mechanism to generate project name from list of file names
ROSE_DLL_API std::string generateProjectName (const SgProject * project, bool supressSuffix = false );
//! Given a SgExpression that represents a named function (or bound member
//! function), return the mentioned function
SgFunctionDeclaration* getDeclarationOfNamedFunction(SgExpression* func);
//! Get the mask expression from the header of a SgForAllStatement
SgExpression* forallMaskExpression(SgForAllStatement* stmt);
//! Find all SgPntrArrRefExp under astNode, then add SgVarRefExp (if any) of SgPntrArrRefExp's dim_info into NodeList_t
void addVarRefExpFromArrayDimInfo(SgNode * astNode, Rose_STL_Container<SgNode *>& NodeList_t);
// DQ (10/6/2006): Added support for faster mangled name generation (caching avoids recomputation).
/*! \brief Support for faster mangled name generation (caching avoids recomputation).
*/
#ifndef SWIG
// DQ (3/10/2013): This appears to be a problem for the SWIG interface (undefined reference at link-time).
void clearMangledNameCache (SgGlobal * globalScope);
void resetMangledNameCache (SgGlobal * globalScope);
#endif
std::string getMangledNameFromCache (SgNode * astNode);
std::string addMangledNameToCache (SgNode * astNode, const std::string & mangledName);
SgDeclarationStatement * getNonInstantiatonDeclarationForClass (SgTemplateInstantiationMemberFunctionDecl * memberFunctionInstantiation);
//! a better version for SgVariableDeclaration::set_baseTypeDefininingDeclaration(), handling all side effects automatically
//! Used to have a struct declaration embedded into a variable declaration
void setBaseTypeDefiningDeclaration(SgVariableDeclaration* var_decl, SgDeclarationStatement *base_decl);
// DQ (10/14/2006): This function tests the AST to see if for a non-defining declaration, the
// bool declarationPreceedsDefinition ( SgClassDeclaration* classNonDefiningDeclaration, SgClassDeclaration* classDefiningDeclaration );
//! Check if a defining declaration comes before of after the non-defining declaration.
bool declarationPreceedsDefinition (SgDeclarationStatement *nonDefiningDeclaration, SgDeclarationStatement *definingDeclaration);
// DQ (10/19/2006): Function calls have interesting context dependent rules to determine if
// they are output with a global qualifier or not. Were this is true we have to avoid global
// qualifiers, since the function's scope has not been defined. This is an example of where
// qualification of function names in function calls are context dependent; an interesting
// example of where the C++ language is not friendly to source-to-source processing :-).
bool functionCallExpressionPreceedsDeclarationWhichAssociatesScope (SgFunctionCallExp * functionCall);
/*! \brief Compute the intersection set for two ASTs.
This is part of a test done by the copy function to compute those IR nodes in the copy that still reference the original AST.
*/
ROSE_DLL_API std::vector < SgNode * >astIntersection (SgNode * original, SgNode * copy, SgCopyHelp * help = NULL);
//! Deep copy an arbitrary subtree
ROSE_DLL_API SgNode* deepCopyNode (const SgNode* subtree);
//! A template function for deep copying a subtree. It is also used to create deepcopy functions with specialized parameter and return types. e.g SgExpression* copyExpression(SgExpression* e);
template <typename NodeType>
NodeType* deepCopy (const NodeType* subtree) {
return dynamic_cast<NodeType*>(deepCopyNode(subtree));
}
//! Deep copy an expression
ROSE_DLL_API SgExpression* copyExpression(SgExpression* e);
//!Deep copy a statement
ROSE_DLL_API SgStatement* copyStatement(SgStatement* s);
// from VarSym.cc in src/midend/astOutlining/src/ASTtools
//! Get the variable symbol for the first initialized name of a declaration stmt.
ROSE_DLL_API SgVariableSymbol* getFirstVarSym (SgVariableDeclaration* decl);
//! Get the first initialized name of a declaration statement
ROSE_DLL_API SgInitializedName* getFirstInitializedName (SgVariableDeclaration* decl);
//! A special purpose statement removal function, originally from inlinerSupport.h, Need Jeremiah's attention to refine it. Please don't use it for now.
ROSE_DLL_API void myRemoveStatement(SgStatement* stmt);
ROSE_DLL_API bool isConstantTrue(SgExpression* e);
ROSE_DLL_API bool isConstantFalse(SgExpression* e);
ROSE_DLL_API bool isCallToParticularFunction(SgFunctionDeclaration* decl, SgExpression* e);
ROSE_DLL_API bool isCallToParticularFunction(const std::string& qualifiedName, size_t arity, SgExpression* e);
//! Check if a declaration has a "static' modifier
bool ROSE_DLL_API isStatic(SgDeclarationStatement* stmt);
//! Set a declaration as static
ROSE_DLL_API void setStatic(SgDeclarationStatement* stmt);
//! Check if a declaration has an "extern" modifier
ROSE_DLL_API bool isExtern(SgDeclarationStatement* stmt);
//! Set a declaration as extern
ROSE_DLL_API void setExtern(SgDeclarationStatement* stmt);
//! True if an SgInitializedName is "mutable' (has storage modifier set)
bool ROSE_DLL_API isMutable(SgInitializedName* name);
//! True if a parameter name is a Jovial output parameter
bool ROSE_DLL_API isJovialOutParam(SgInitializedName* name);
//! Get a vector of Jovial input parameters from the function parameter list (may work for Fortran in the future)
std::vector<SgInitializedName*> getInParameters(const SgInitializedNamePtrList ¶ms);
//! Get a vector of Jovial output parameters from the function parameter list (may work for Fortran in the future)
std::vector<SgInitializedName*> getOutParameters(const SgInitializedNamePtrList ¶ms);
//! Interface for creating a statement whose computation writes its answer into
//! a given variable.
class StatementGenerator {
public:
virtual ~StatementGenerator() {};
virtual SgStatement* generate(SgExpression* where_to_write_answer) = 0;
};
//! Check if a SgNode _s is an assignment statement (any of =,+=,-=,&=,/=, ^=, etc)
//!
//! Return the left hand, right hand expressions and if the left hand variable is also being read
bool isAssignmentStatement(SgNode* _s, SgExpression** lhs=NULL, SgExpression** rhs=NULL, bool* readlhs=NULL);
//! Variable references can be introduced by SgVarRef, SgPntrArrRefExp, SgInitializedName, SgMemberFunctionRef etc. For Dot and Arrow Expressions, their lhs is used to obtain SgInitializedName (coarse grain) by default. Otherwise, fine-grain rhs is used.
ROSE_DLL_API SgInitializedName* convertRefToInitializedName(SgNode* current, bool coarseGrain=true);
//! Build an abstract handle from an AST node, reuse previously built handle when possible
ROSE_DLL_API AbstractHandle::abstract_handle* buildAbstractHandle(SgNode*);
//! Obtain a matching SgNode from an abstract handle string
ROSE_DLL_API SgNode* getSgNodeFromAbstractHandleString(const std::string& input_string);
//! Dump information about a SgNode for debugging
ROSE_DLL_API void dumpInfo(SgNode* node, std::string desc="");
//! Reorder a list of declaration statements based on their appearance order in source files
ROSE_DLL_API std::vector<SgDeclarationStatement*>
sortSgNodeListBasedOnAppearanceOrderInSource(const std::vector<SgDeclarationStatement*>& nodevec);
// DQ (4/13/2013): We need these to support the unparing of operators defined by operator syntax or member function names.
//! Is an overloaded operator a prefix operator (e.g. address operator X * operator&(), dereference operator X & operator*(), unary plus operator X & operator+(), etc.
// bool isPrefixOperator( const SgMemberFunctionRefExp* memberFunctionRefExp );
bool isPrefixOperator( SgExpression* exp );
//! Check for proper names of possible prefix operators (used in isPrefixOperator()).
bool isPrefixOperatorName( const SgName & functionName );
//! Is an overloaded operator a postfix operator. (e.g. ).
bool isPostfixOperator( SgExpression* exp );
//! Is an overloaded operator an index operator (also referred to as call or subscript operators). (e.g. X & operator()() or X & operator[]()).
bool isIndexOperator( SgExpression* exp );
// DQ (1/10/2014): Adding more general support for token based unparsing.
//! Used to support token unparsing (when the output the trailing token sequence).
SgStatement* lastStatementOfScopeWithTokenInfo (SgScopeStatement* scope, std::map<SgNode*,TokenStreamSequenceToNodeMapping*> & tokenStreamSequenceMap);
// DQ (8/12/2020): Check the access permissions of all defining and nodefining declarations.
void checkAccessPermissions ( SgNode* );
// DQ (8/14/2020): Check the symbol tables for specific scopes (debugging support).
void checkSymbolTables ( SgNode* );
// DQ (11/9/2020): Added support for makring IR nodes and subtrees of the AST to be unparsed (physical_file_id
// is required when unparsing header files is true or support multiple files and shared IR nodes).
void markSubtreeToBeUnparsed(SgNode* root, int physical_file_id);
void markNodeToBeUnparsed(SgNode* node, int physical_file_id);
//@}
//------------------------------------------------------------------------
//@{
/*! @name AST properties
\brief version, language properties of current AST.
*/
// DQ (11/25/2020): Add support to set this as a specific language kind file (there is at least one language kind file processed by ROSE).
// The value of 0 allows the old implementation to be tested, and the value of 1 allows the new optimized implementation to be tested.
// However to get all of the functions to be inlined, we have to recompile all of ROSE.
#define INLINE_OPTIMIZED_IS_LANGUAGE_KIND_FUNCTIONS 1
// std::string version(); // utility_functions.h, version number
/*! Brief These traverse the memory pool of SgFile IR nodes and determine what languages are in use!
*/
#if INLINE_OPTIMIZED_IS_LANGUAGE_KIND_FUNCTIONS
ROSE_DLL_API inline bool is_Ada_language () { return Rose::is_Ada_language; }
ROSE_DLL_API inline bool is_C_language () { return Rose::is_C_language; }
ROSE_DLL_API inline bool is_Cobol_language () { return Rose::is_Cobol_language; }
ROSE_DLL_API inline bool is_OpenMP_language () { return Rose::is_OpenMP_language; }
ROSE_DLL_API inline bool is_UPC_language () { return Rose::is_UPC_language; }
ROSE_DLL_API inline bool is_UPC_dynamic_threads() { return Rose::is_UPC_dynamic_threads; }
ROSE_DLL_API inline bool is_C99_language () { return Rose::is_C99_language; }
ROSE_DLL_API inline bool is_Cxx_language () { return Rose::is_Cxx_language; }
ROSE_DLL_API inline bool is_Java_language () { return Rose::is_Java_language; }
ROSE_DLL_API inline bool is_Jovial_language () { return Rose::is_Jovial_language; }
ROSE_DLL_API inline bool is_Fortran_language () { return Rose::is_Fortran_language; }
ROSE_DLL_API inline bool is_CAF_language () { return Rose::is_CAF_language; }
ROSE_DLL_API inline bool is_PHP_language() { return Rose::is_PHP_language; }
ROSE_DLL_API inline bool is_Python_language() { return Rose::is_Python_language; }
ROSE_DLL_API inline bool is_Cuda_language() { return Rose::is_Cuda_language; }
ROSE_DLL_API inline bool is_OpenCL_language() { return Rose::is_OpenCL_language; }
ROSE_DLL_API inline bool is_X10_language() { return Rose::is_X10_language; }
ROSE_DLL_API inline bool is_binary_executable() { return Rose::is_binary_executable; }
#else
ROSE_DLL_API bool is_Ada_language ();
ROSE_DLL_API bool is_C_language ();
ROSE_DLL_API bool is_Cobol_language ();
ROSE_DLL_API bool is_OpenMP_language ();
ROSE_DLL_API bool is_UPC_language ();
//! Check if dynamic threads compilation is used for UPC programs
ROSE_DLL_API bool is_UPC_dynamic_threads();
ROSE_DLL_API bool is_C99_language ();
ROSE_DLL_API bool is_Cxx_language ();
ROSE_DLL_API bool is_Java_language ();
ROSE_DLL_API bool is_Jovial_language ();
ROSE_DLL_API bool is_Fortran_language ();
ROSE_DLL_API bool is_CAF_language ();
ROSE_DLL_API bool is_PHP_language();
ROSE_DLL_API bool is_Python_language();
ROSE_DLL_API bool is_Cuda_language();
ROSE_DLL_API bool is_OpenCL_language();
ROSE_DLL_API bool is_X10_language();
ROSE_DLL_API bool is_binary_executable();
#endif
ROSE_DLL_API bool is_mixed_C_and_Cxx_language ();
ROSE_DLL_API bool is_mixed_Fortran_and_C_language ();
ROSE_DLL_API bool is_mixed_Fortran_and_Cxx_language ();
ROSE_DLL_API bool is_mixed_Fortran_and_C_and_Cxx_language ();
ROSE_DLL_API bool is_language_case_insensitive ();
ROSE_DLL_API bool language_may_contain_nondeclarations_in_scope ();
//@}
//------------------------------------------------------------------------
//@{
/*! @name Scope
\brief
*/
// DQ (10/5/2006): Added support for faster (non-quadratic) computation of unique
// labels for scopes in a function (as required for name mangling).
/*! \brief Assigns unique numbers to each SgScopeStatement of a function.
This is used to provide unique names for variables and types defined is
different nested scopes of a function (used in mangled name generation).
*/
void resetScopeNumbers (SgFunctionDefinition * functionDeclaration);
// DQ (10/5/2006): Added support for faster (non-quadratic) computation of unique
// labels for scopes in a function (as required for name mangling).
/*! \brief Clears the cache of scope,integer pairs for the input function.
This is used to clear the cache of computed unique labels for scopes in a function.
This function should be called after any transformation on a function that might effect
the allocation of scopes and cause the existing unique numbers to be incorrect.
This is part of support to provide unique names for variables and types defined is
different nested scopes of a function (used in mangled name generation).
*/
void clearScopeNumbers (SgFunctionDefinition * functionDefinition);
//!Find the enclosing namespace of a declaration
SgNamespaceDefinitionStatement * enclosingNamespaceScope (SgDeclarationStatement * declaration);
// SgNamespaceDefinitionStatement * getEnclosingNamespaceScope (SgNode * node);
bool isPrototypeInScope (SgScopeStatement * scope,
SgFunctionDeclaration * functionDeclaration,
SgDeclarationStatement * startingAtDeclaration);
//!check if node1 is a strict ancestor of node 2. (a node is not considered its own ancestor)
bool ROSE_DLL_API isAncestor(SgNode* node1, SgNode* node2);
//@}
//------------------------------------------------------------------------
//@{
/*! @name Preprocessing Information
\brief #if-#else-#end, comments, #include, etc
*/
//! Dumps a located node's preprocessing information.
void dumpPreprocInfo (SgLocatedNode* locatedNode);
//! Find the preprocessingInfo node representing #include <header.h> or #include "header.h" within a source file. Return NULL if not found.
ROSE_DLL_API PreprocessingInfo * findHeader(SgSourceFile * source_file, const std::string & header_file_name, bool isSystemHeader);
//! Insert #include "filename" or #include <filename> (system header) onto the global scope of a source file, add to be the last #include .. by default among existing headers, Or as the first header. Recommended for use.
ROSE_DLL_API PreprocessingInfo * insertHeader(SgSourceFile * source_file, const std::string & header_file_name, bool isSystemHeader, bool asLastHeader);
//! Insert a new header right before stmt, if there are existing headers attached to stmt, insert it as the last or first header as specified by asLastHeader
ROSE_DLL_API void insertHeader (SgStatement* stmt, PreprocessingInfo* newheader, bool asLastHeader);
//! Insert #include "filename" or #include <filename> (system header) onto the global scope of a source file
ROSE_DLL_API PreprocessingInfo * insertHeader(SgSourceFile * source_file, const std::string & header_file_name, bool isSystemHeader = false, PreprocessingInfo::RelativePositionType position = PreprocessingInfo::before);
//! Insert #include "filename" or #include <filename> (system header) into the global scope containing the current scope, right after other #include XXX.
ROSE_DLL_API PreprocessingInfo* insertHeader(const std::string& filename, PreprocessingInfo::RelativePositionType position=PreprocessingInfo::after, bool isSystemHeader=false, SgScopeStatement* scope=NULL);
//! Identical to movePreprocessingInfo(), except for the stale name and confusing order of parameters. It will be deprecated soon.
ROSE_DLL_API void moveUpPreprocessingInfo (SgStatement* stmt_dst, SgStatement* stmt_src, PreprocessingInfo::RelativePositionType src_position=PreprocessingInfo::undef, PreprocessingInfo::RelativePositionType dst_position=PreprocessingInfo::undef, bool usePrepend= false);
//! Move preprocessing information of stmt_src to stmt_dst, Only move preprocessing information from the specified source-relative position to a specified target position, otherwise move all preprocessing information with position information intact. The preprocessing information is appended to the existing preprocessing information list of the target node by default. Prepending is used if usePreprend is set to true. Optionally, the relative position can be adjust after the moving using dst_position.
ROSE_DLL_API void movePreprocessingInfo (SgStatement* stmt_src, SgStatement* stmt_dst, PreprocessingInfo::RelativePositionType src_position=PreprocessingInfo::undef,
PreprocessingInfo::RelativePositionType dst_position=PreprocessingInfo::undef, bool usePrepend= false);
//!Cut preprocessing information from a source node and save it into a buffer. Used in combination of pastePreprocessingInfo(). The cut-paste operation is similar to moveUpPreprocessingInfo() but it is more flexible in that the destination node can be unknown during the cut operation.
ROSE_DLL_API void cutPreprocessingInfo (SgLocatedNode* src_node, PreprocessingInfo::RelativePositionType pos, AttachedPreprocessingInfoType& save_buf);
//!Paste preprocessing information from a buffer to a destination node. Used in combination of cutPreprocessingInfo()
ROSE_DLL_API void pastePreprocessingInfo (SgLocatedNode* dst_node, PreprocessingInfo::RelativePositionType pos, AttachedPreprocessingInfoType& saved_buf);
//! Attach an arbitrary string to a located node. A workaround to insert irregular statements or vendor-specific attributes.
ROSE_DLL_API PreprocessingInfo* attachArbitraryText(SgLocatedNode* target,
const std::string & text,
PreprocessingInfo::RelativePositionType position=PreprocessingInfo::before);
//!Check if a pragma declaration node has macro calls attached, if yes, replace macro calls within the pragma string with expanded strings. This only works if -rose:wave is turned on.
ROSE_DLL_API void replaceMacroCallsWithExpandedStrings(SgPragmaDeclaration* target);
//@}
//! Build and attach comment onto the global scope of a source file
PreprocessingInfo* attachComment(
SgSourceFile * source_file,
const std::string & content,
PreprocessingInfo::DirectiveType directive_type = PreprocessingInfo::C_StyleComment,
PreprocessingInfo::RelativePositionType position = PreprocessingInfo::before
);
//! Build and attach comment, comment style is inferred from the language type of the target node if not provided
ROSE_DLL_API PreprocessingInfo* attachComment(SgLocatedNode* target, const std::string & content,
PreprocessingInfo::RelativePositionType position=PreprocessingInfo::before,
PreprocessingInfo::DirectiveType dtype= PreprocessingInfo::CpreprocessorUnknownDeclaration);
// DQ (7/20/2008): I am not clear were I should put this function, candidates include: SgLocatedNode or SgInterface
//! Add a string to be unparsed to support code generation for back-end specific tools or compilers.
ROSE_DLL_API void addTextForUnparser ( SgNode* astNode, std::string s, AstUnparseAttribute::RelativePositionType inputlocation );
/**
* Add preproccessor guard around a given node.
* It surrounds the node with "#if guard" and "#endif"
*/
void guardNode(SgLocatedNode * target, std::string guard);
//@}
//------------------------------------------------------------------------
//@{
/*! @name Source File Position
\brief set Sg_File_Info for a SgNode
*/
// ************************************************************************
// Newer versions of now depricated functions
// ************************************************************************
// DQ (5/1/2012): This function queries the SageBuilder::SourcePositionClassification mode (stored in the SageBuilder
// interface) and used the specified mode to initialize the source position data (Sg_File_Info objects). This
// function is the only function that should be called directly (though in a namespace we can't define permissions).
//! Set the source code positon for the current (input) node.
ROSE_DLL_API void setSourcePosition(SgNode* node);
// A better name might be "setSourcePositionForSubTree"
//! Set the source code positon for the subtree (including the root).
ROSE_DLL_API void setSourcePositionAtRootAndAllChildren(SgNode *root);
//! DQ (5/1/2012): New function with improved name.
void setSourcePositionAsTransformation(SgNode *node);
// DQ (5/1/2012): Newly renamed function (previous name preserved for backward compatability).
void setSourcePositionPointersToNull(SgNode *node);
// ************************************************************************
// ************************************************************************
// Older deprecated functions
// ************************************************************************
// Liao, 1/8/2007, set file info. for a whole subtree as transformation generated
//! Set current node's source position as transformation generated
ROSE_DLL_API void setOneSourcePositionForTransformation(SgNode *node);
//! Set current node's source position as NULL
ROSE_DLL_API void setOneSourcePositionNull(SgNode *node);
//! Recursively set source position info(Sg_File_Info) as transformation generated
ROSE_DLL_API void setSourcePositionForTransformation (SgNode * root);
//! Set source position info(Sg_File_Info) as transformation generated for all SgNodes in memory pool
// ROSE_DLL_API void setSourcePositionForTransformation_memoryPool();
//! Check if a node is from a system header file
ROSE_DLL_API bool insideSystemHeader (SgLocatedNode* node);
// DQ (2/27/2021): Adding support to detect if a SgLocatedNode is located in a header file.
//! Check if a node is from a header file
ROSE_DLL_API bool insideHeader (SgLocatedNode* node);
//! Set the source position of SgLocatedNode to Sg_File_Info::generateDefaultFileInfo(). These nodes WILL be unparsed. Not for transformation usage.
// ROSE_DLL_API void setSourcePosition (SgLocatedNode * locatedNode);
// ************************************************************************
//@}
//------------------------------------------------------------------------
//@{
/*! @name Data types
\brief
*/
// from src/midend/astInlining/typeTraits.h
// src/midend/astUtil/astInterface/AstInterface.h
//! Get the right bool type according to C or C++ language input
SgType* getBoolType(SgNode* n);
//! Check if a type is an integral type, only allowing signed/unsigned short, int, long, long long.
////!
////! There is another similar function named SgType::isIntegerType(), which allows additional types char, wchar, and bool to be treated as integer types
ROSE_DLL_API bool isStrictIntegerType(SgType* t);
//!Get the data type of the first initialized name of a declaration statement
ROSE_DLL_API SgType* getFirstVarType(SgVariableDeclaration* decl);
//! Is a type default constructible? This may not quite work properly.
ROSE_DLL_API bool isDefaultConstructible(SgType* type);
//! Is a type copy constructible? This may not quite work properly.
ROSE_DLL_API bool isCopyConstructible(SgType* type);
//! Is a type assignable? This may not quite work properly.
ROSE_DLL_API bool isAssignable(SgType* type);
#ifndef ROSE_USE_INTERNAL_FRONTEND_DEVELOPMENT
//! Check if a class type is a pure virtual class. True means that there is at least
//! one pure virtual function that has not been overridden.
//! In the case of an incomplete class type (forward declaration), this function returns false.
ROSE_DLL_API bool isPureVirtualClass(SgType* type, const ClassHierarchyWrapper& classHierarchy);
#endif
//! Does a type have a trivial (built-in) destructor?
ROSE_DLL_API bool hasTrivialDestructor(SgType* t);
//! Is this type a non-constant reference type? (Handles typedefs correctly)
ROSE_DLL_API bool isNonconstReference(SgType* t);
//! Is this type a const or non-const reference type? (Handles typedefs correctly)
ROSE_DLL_API bool isReferenceType(SgType* t);
//! Is this type a pointer type? (Handles typedefs correctly)
ROSE_DLL_API bool isPointerType(SgType* t);
//! Is this a pointer to a non-const type? Note that this function will return true for const pointers pointing to
//! non-const types. For example, (int* const y) points to a modifiable int, so this function returns true. Meanwhile,
//! it returns false for (int const * x) and (int const * const x) because these types point to a const int.
//! Also, only the outer layer of nested pointers is unwrapped. So the function returns true for (const int ** y), but returns
//! false for const (int * const * x)
ROSE_DLL_API bool isPointerToNonConstType(SgType* type);
//! Is this a const type?
/* const char* p = "aa"; is not treated as having a const type. It is a pointer to const char.
* Similarly, neither for const int b[10]; or const int & c =10;
* The standard says, "A compound type is not cv-qualified by the cv-qualifiers (if any) of
the types from which it is compounded. Any cv-qualifiers applied to an array type affect the array element type, not the array type".
*/
ROSE_DLL_API bool isConstType(SgType* t);
//! Remove const (if present) from a type. stripType() cannot do this because it removes all modifiers.
SgType* removeConst(SgType* t);
//! Is this a volatile type?
ROSE_DLL_API bool isVolatileType(SgType* t);
//! Is this a restrict type?
ROSE_DLL_API bool isRestrictType(SgType* t);
//! Is this a scalar type?
/*! We define the following SgType as scalar types: char, short, int, long , void, Wchar, Float, double, long long, string, bool, complex, imaginary
*/
ROSE_DLL_API bool isScalarType(SgType* t);
//! Check if a type is an integral type, only allowing signed/unsigned short, int, long, long long.
//!
//! There is another similar function named SgType::isIntegerType(), which allows additional types char, wchar, and bool.
ROSE_DLL_API bool isStrictIntegerType(SgType* t);
//! Check if a type is a struct type (a special SgClassType in ROSE)
ROSE_DLL_API bool isStructType(SgType* t);
//! Generate a mangled string for a given type based on Itanium C++ ABI
ROSE_DLL_API std::string mangleType(SgType* type);
//! Generate mangled scalar type names according to Itanium C++ ABI, the input type should pass isScalarType() in ROSE
ROSE_DLL_API std::string mangleScalarType(SgType* type);
//! Generated mangled modifier types, include const, volatile,according to Itanium C++ ABI, with extension to handle UPC shared types.
ROSE_DLL_API std::string mangleModifierType(SgModifierType* type);
//! Calculate the number of elements of an array type: dim1* dim2*... , assume element count is 1 for int a[]; Strip off THREADS if it is a UPC array.
ROSE_DLL_API size_t getArrayElementCount(SgArrayType* t);
//! Get the number of dimensions of an array type
ROSE_DLL_API int getDimensionCount(SgType* t);
//! Get the element type of an array. It recursively find the base type for multi-dimension array types
ROSE_DLL_API SgType* getArrayElementType(SgType* t);
//! Get the element type of an array, pointer or string, or NULL if not applicable. This function only check one level base type. No recursion.
ROSE_DLL_API SgType* getElementType(SgType* t);
/// \brief returns the array dimensions in an array as defined for arrtype
/// \param arrtype the type of a C/C++ array
/// \return an array that contains an expression indicating each dimension's size.
/// OWNERSHIP of the expressions is TRANSFERED TO the CALLER (which
/// becomes responsible for freeing the expressions).
/// Note, the first entry of the array is a SgNullExpression, iff the
/// first array dimension was not specified.
/// \code
/// int x[] = { 1, 2, 3 };
/// \endcode
/// note, the expression does not have to be a constant
/// \code
/// int x[i*5];
/// \endcode
/// \post return-value.empty() == false
/// \post return-value[*] != NULL (no nullptr in the returned vector)
std::vector<SgExpression*>
get_C_array_dimensions(const SgArrayType& arrtype);
/// \brief returns the array dimensions in an array as defined for arrtype
/// \param arrtype the type of a C/C++ array
/// \param varref a reference to an array variable (the variable of type arrtype)
/// \return an array that contains an expression indicating each dimension's size.
/// OWNERSHIP of the expressions is TRANSFERED TO the CALLER (which
/// becomes responsible for freeing the expressions).
/// If the first array dimension was not specified an expression
/// that indicates that size is generated.
/// \code
/// int x[][3] = { 1, 2, 3, 4, 5, 6 };
/// \endcode
/// the entry for the first dimension will be:
/// \code
/// // 3 ... size of 2nd dimension
/// sizeof(x) / (sizeof(int) * 3)
/// \endcode
/// \pre arrtype is the array-type of varref
/// \post return-value.empty() == false
/// \post return-value[*] != NULL (no nullptr in the returned vector)
/// \post !isSgNullExpression(return-value[*])
std::vector<SgExpression*>
get_C_array_dimensions(const SgArrayType& arrtype, const SgVarRefExp& varref);
/// \overload
/// \note see get_C_array_dimensions for SgVarRefExp for details.
/// \todo make initname const
std::vector<SgExpression*>
get_C_array_dimensions(const SgArrayType& arrtype, SgInitializedName& initname);
//! Check if an expression is an array access (SgPntrArrRefExp). If so, return its name expression and subscripts if requested. Users can use convertRefToInitializedName() to get the possible name. It does not check if the expression is a top level SgPntrArrRefExp.
ROSE_DLL_API bool isArrayReference(SgExpression* ref, SgExpression** arrayNameExp=NULL, std::vector<SgExpression*>** subscripts=NULL);
//! Collect variable references in array types. The default NodeQuery::querySubTree() will miss variables referenced in array type's index list. e.g. double *buffer = new double[numItems] ;
ROSE_DLL_API int collectVariableReferencesInArrayTypes (SgLocatedNode* root, Rose_STL_Container<SgNode*> & currentVarRefList);
//! Has a UPC shared type of any kinds (shared-to-shared, private-to-shared, shared-to-private, shared scalar/array)? An optional parameter, mod_type_out, stores the first SgModifierType with UPC access information.
/*!
* Note: we classify private-to-shared as 'has shared' type for convenience here. It is indeed a private type in strict sense.
AST graph for some examples:
- shared scalar: SgModifierType -->base type
- shared array: SgArrayType --> SgModiferType --> base type
- shared to shared: SgModifierType --> SgPointerType --> SgModifierType ->SgTypeInt
- shared to private: SgModifierType --> SgPointerType --> base type
- private to shared: SgPointerType --> SgModifierType --> base type
*/
ROSE_DLL_API bool hasUpcSharedType(SgType* t, SgModifierType ** mod_type_out = NULL );
//! Check if a type is a UPC shared type, including shared array, shared pointers etc. Exclude private pointers to shared types. Optionally return the modifier type with the UPC shared property.
/*!
* ROSE uses SgArrayType of SgModifierType to represent shared arrays, not SgModifierType points to SgArrayType. Also typedef may cause a chain of nodes before reach the actual SgModifierType with UPC shared property.
*/
ROSE_DLL_API bool isUpcSharedType(SgType* t, SgModifierType ** mod_type_out = NULL);
//! Check if a modifier type is a UPC shared type.
ROSE_DLL_API bool isUpcSharedModifierType (SgModifierType* mod_type);
//! Check if an array type is a UPC shared type. ROSE AST represents a UPC shared array as regular array of elements of UPC shared Modifier Type. Not directly a UPC shared Modifier Type of an array.
ROSE_DLL_API bool isUpcSharedArrayType (SgArrayType* array_type);
//! Check if a shared UPC type is strict memory consistency or not. Return false if it is relaxed. (So isUpcRelaxedSharedModifierType() is not necessary.)
ROSE_DLL_API bool isUpcStrictSharedModifierType(SgModifierType* mode_type);
//! Get the block size of a UPC shared modifier type
ROSE_DLL_API size_t getUpcSharedBlockSize(SgModifierType* mod_type);
//! Get the block size of a UPC shared type, including Modifier types and array of modifier types (shared arrays)
ROSE_DLL_API size_t getUpcSharedBlockSize(SgType* t);
//! Is UPC phase-less shared type? Phase-less means block size of the first SgModifierType with UPC information is 1 or 0/unspecified. Also return false if the type is not a UPC shared type.
ROSE_DLL_API bool isUpcPhaseLessSharedType (SgType* t);
//! Is a UPC private-to-shared pointer? SgPointerType comes first compared to SgModifierType with UPC information. Input type must be any of UPC shared types first.
ROSE_DLL_API bool isUpcPrivateToSharedType(SgType* t);
//! Is a UPC array with dimension of X*THREADS
ROSE_DLL_API bool isUpcArrayWithThreads(SgArrayType* t);
//! Lookup a named type based on its name, bottomup searching from a specified scope. Note name collison might be allowed for c (not C++) between typedef and enum/struct. Only the first matched named type will be returned in this case. typedef is returned as it is, not the base type it actually refers to.
ROSE_DLL_API SgType* lookupNamedTypeInParentScopes(const std::string& type_name, SgScopeStatement* scope=NULL);
// DQ (7/22/2014): Added support for comparing expression types in actual arguments with those expected from the formal function parameter types.
//! Get the type of the associated argument expression from the function type.
ROSE_DLL_API SgType* getAssociatedTypeFromFunctionTypeList(SgExpression* actual_argument_expression);
//! Verify that 2 SgTemplateArgument are equivalent (same type, same expression, or same template declaration)
ROSE_DLL_API bool templateArgumentEquivalence(SgTemplateArgument * arg1, SgTemplateArgument * arg2);
//! Verify that 2 SgTemplateArgumentPtrList are equivalent.
ROSE_DLL_API bool templateArgumentListEquivalence(const SgTemplateArgumentPtrList & list1, const SgTemplateArgumentPtrList & list2);
//! Test for equivalence of types independent of access permissions (private or protected modes for members of classes).
ROSE_DLL_API bool isEquivalentType (const SgType* lhs, const SgType* rhs);
//! Find the function type matching a function signature plus a given return type
ROSE_DLL_API SgFunctionType* findFunctionType (SgType* return_type, SgFunctionParameterTypeList* typeList);
//! Test if two types are equivalent SgFunctionType nodes. This is necessary for template function types
//! They may differ in one SgTemplateType pointer but identical otherwise.
ROSE_DLL_API bool isEquivalentFunctionType (const SgFunctionType* lhs, const SgFunctionType* rhs);
//@}
//------------------------------------------------------------------------
//@{
/*! @name Loop handling
\brief
*/
// by Jeremiah
//! Add a step statement to the end of a loop body
//! Add a new label to the end of the loop, with the step statement after
//! it; then change all continue statements in the old loop body into
//! jumps to the label
//!
//! For example:
//! while (a < 5) {if (a < -3) continue;} (adding "a++" to end) becomes
//! while (a < 5) {if (a < -3) goto label; label: a++;}
ROSE_DLL_API void addStepToLoopBody(SgScopeStatement* loopStmt, SgStatement* step);
ROSE_DLL_API void moveForStatementIncrementIntoBody(SgForStatement* f);
ROSE_DLL_API void convertForToWhile(SgForStatement* f);
ROSE_DLL_API void convertAllForsToWhiles(SgNode* top);
//! Change continue statements in a given block of code to gotos to a label
ROSE_DLL_API void changeContinuesToGotos(SgStatement* stmt, SgLabelStatement* label);
//!Return the loop index variable for a for loop
ROSE_DLL_API SgInitializedName* getLoopIndexVariable(SgNode* loop);
//!Check if a SgInitializedName is used as a loop index within a AST subtree
//! This function will use a bottom-up traverse starting from the subtree_root to find all enclosing loops and check if ivar is used as an index for either of them.
ROSE_DLL_API bool isLoopIndexVariable(SgInitializedName* ivar, SgNode* subtree_root);
//! Check if a for loop uses C99 style initialization statement with multiple expressions like for (int i=0, j=0; ..) or for (i=0,j=0;...)
/*!
for (int i=0, j=0; ..) is stored as two variable declarations under SgForInitStatement's init_stmt member
for (i=0,j=0;...) is stored as a single expression statement, with comma expression (i=0,j=0).
*/
ROSE_DLL_API bool hasMultipleInitStatmentsOrExpressions (SgForStatement* for_loop);
//! Routines to get and set the body of a loop
ROSE_DLL_API SgStatement* getLoopBody(SgScopeStatement* loop);
ROSE_DLL_API void setLoopBody(SgScopeStatement* loop, SgStatement* body);
//! Routines to get the condition of a loop. It recognize While-loop, For-loop, and Do-While-loop
ROSE_DLL_API SgStatement* getLoopCondition(SgScopeStatement* loop);
//! Set the condition statement of a loop, including While-loop, For-loop, and Do-While-loop.
ROSE_DLL_API void setLoopCondition(SgScopeStatement* loop, SgStatement* cond);
//! Check if a for-loop has a canonical form, return loop index, bounds, step, and body if requested
//!
//! A canonical form is defined as : one initialization statement, a test expression, and an increment expression , loop index variable should be of an integer type. IsInclusiveUpperBound is true when <= or >= is used for loop condition
ROSE_DLL_API bool isCanonicalForLoop(SgNode* loop, SgInitializedName** ivar=NULL, SgExpression** lb=NULL, SgExpression** ub=NULL, SgExpression** step=NULL, SgStatement** body=NULL, bool *hasIncrementalIterationSpace = NULL, bool* isInclusiveUpperBound = NULL);
//! Check if a Fortran Do loop has a complete canonical form: Do I=1, 10, 1
ROSE_DLL_API bool isCanonicalDoLoop(SgFortranDo* loop,SgInitializedName** ivar/*=NULL*/, SgExpression** lb/*=NULL*/, SgExpression** ub/*=NULL*/, SgExpression** step/*=NULL*/, SgStatement** body/*=NULL*/, bool *hasIncrementalIterationSpace/*= NULL*/, bool* isInclusiveUpperBound/*=NULL*/);
//! Set the lower bound of a loop header for (i=lb; ...)
ROSE_DLL_API void setLoopLowerBound(SgNode* loop, SgExpression* lb);
//! Set the upper bound of a loop header,regardless the condition expression type. for (i=lb; i op up, ...)
ROSE_DLL_API void setLoopUpperBound(SgNode* loop, SgExpression* ub);
//! Set the stride(step) of a loop 's incremental expression, regardless the expression types (i+=s; i= i+s, etc)
ROSE_DLL_API void setLoopStride(SgNode* loop, SgExpression* stride);
//! Normalize loop init stmt by promoting the single variable declaration statement outside of the for loop header's init statement, e.g. for (int i=0;) becomes int i_x; for (i_x=0;..) and rewrite the loop with the new index variable, if necessary
ROSE_DLL_API bool normalizeForLoopInitDeclaration(SgForStatement* loop);
//! Undo the normalization of for loop's C99 init declaration. Previous record of normalization is used to ease the reverse transformation.
ROSE_DLL_API bool unnormalizeForLoopInitDeclaration(SgForStatement* loop);
//! Normalize a for loop, return true if successful. Generated constants will be fold by default.
//!
//! Translations are :
//! For the init statement: for (int i=0;... ) becomes int i; for (i=0;..)
//! For test expression:
//! i<x is normalized to i<= (x-1) and
//! i>x is normalized to i>= (x+1)
//! For increment expression:
//! i++ is normalized to i+=1 and
//! i-- is normalized to i+=-1
//! i-=s is normalized to i+= -s
ROSE_DLL_API bool forLoopNormalization(SgForStatement* loop, bool foldConstant = true);
//! Normalize a for loop's test expression
//! i<x is normalized to i<= (x-1) and
//! i>x is normalized to i>= (x+1)
ROSE_DLL_API bool normalizeForLoopTest(SgForStatement* loop);
ROSE_DLL_API bool normalizeForLoopIncrement(SgForStatement* loop);
//!Normalize a Fortran Do loop. Make the default increment expression (1) explicit
ROSE_DLL_API bool doLoopNormalization(SgFortranDo* loop);
//! Unroll a target loop with a specified unrolling factor. It handles steps larger than 1 and adds a fringe loop if the iteration count is not evenly divisible by the unrolling factor.
ROSE_DLL_API bool loopUnrolling(SgForStatement* loop, size_t unrolling_factor);
//! Interchange/permutate a n-level perfectly-nested loop rooted at 'loop' using a lexicographical order number within (0,depth!).
ROSE_DLL_API bool loopInterchange(SgForStatement* loop, size_t depth, size_t lexicoOrder);
//! Tile the n-level (starting from 1) loop of a perfectly nested loop nest using tiling size s
ROSE_DLL_API bool loopTiling(SgForStatement* loopNest, size_t targetLevel, size_t tileSize);
//Winnie Loop Collapsing
SgExprListExp * loopCollapsing(SgForStatement* target_loop, size_t collapsing_factor);
bool getForLoopInformations(
SgForStatement * for_loop,
SgVariableSymbol * & iterator,
SgExpression * & lower_bound,
SgExpression * & upper_bound,
SgExpression * & stride
);
//@}
//------------------------------------------------------------------------
//@{
/*! @name Topdown search
\brief Top-down traversal from current node to find a node of a specified type
*/
//! Query a subtree to get all nodes of a given type, with an appropriate downcast.
template <typename NodeType>
std::vector<NodeType*> querySubTree(SgNode* top, VariantT variant = (VariantT)NodeType::static_variant)
{
#if 0
printf ("Top of SageInterface::querySubTree() \n");
#endif
Rose_STL_Container<SgNode*> nodes = NodeQuery::querySubTree(top,variant);
std::vector<NodeType*> result(nodes.size(), NULL);
int count = 0;
#if 0
printf ("In SageInterface::querySubTree(): before initialization loop \n");
#endif
for (Rose_STL_Container<SgNode*>::const_iterator i = nodes.begin(); i != nodes.end(); ++i, ++count)
{
#if 0
printf ("In SageInterface::querySubTree(): in loop: count = %d \n",count);
#endif
NodeType* node = dynamic_cast<NodeType*>(*i);
ROSE_ASSERT (node);
result[count] = node;
}
#if 0
printf ("Leaving SageInterface::querySubTree(): after initialization loop \n");
#endif
return result;
}
/*! \brief Returns STL vector of SgFile IR node pointers.
Demonstrates use of restricted traversal over just SgFile IR nodes.
*/
std::vector < SgFile * >generateFileList ();
/** Get the current SgProject IR Node.
*
* The library should never have more than one project and it asserts such. If no project has been created yet then this
* function returns the null pointer. */
ROSE_DLL_API SgProject * getProject();
//! \return the project associated with a node
SgProject * getProject(const SgNode * node);
//! Query memory pools to grab SgNode of a specified type
template <typename NodeType>
static std::vector<NodeType*> getSgNodeListFromMemoryPool()
{
// This function uses a memory pool traversal specific to the SgFile IR nodes
class MyTraversal : public ROSE_VisitTraversal
{
public:
std::vector<NodeType*> resultlist;
void visit ( SgNode* node)
{
NodeType* result = dynamic_cast<NodeType* > (node);
ROSE_ASSERT(result!= NULL);
if (result!= NULL)
{
resultlist.push_back(result);
}
};
virtual ~MyTraversal() {}
};
MyTraversal my_traversal;
NodeType::traverseMemoryPoolNodes(my_traversal);
return my_traversal.resultlist;
}
/*! \brief top-down traversal from current node to find the main() function declaration
*/
ROSE_DLL_API SgFunctionDeclaration* findMain(SgNode* currentNode);
//! Find the last declaration statement within a scope (if any). This is often useful to decide where to insert another variable declaration statement. Pragma declarations are not treated as a declaration by default in this context.
SgStatement* findLastDeclarationStatement(SgScopeStatement * scope, bool includePragma = false);
//midend/programTransformation/partialRedundancyElimination/pre.h
//! Find referenced symbols within an expression
std::vector<SgVariableSymbol*> getSymbolsUsedInExpression(SgExpression* expr);
//! Find break statements inside a particular statement, stopping at nested loops or switches
/*! loops or switch statements defines their own contexts for break
statements. The function will stop immediately if run on a loop or switch
statement. If fortranLabel is non-empty, breaks (EXITs) to that label within
nested loops are included in the returned list.
*/
std::vector<SgBreakStmt*> findBreakStmts(SgStatement* code, const std::string& fortranLabel = "");
//! Find all continue statements inside a particular statement, stopping at nested loops
/*! Nested loops define their own contexts for continue statements. The
function will stop immediately if run on a loop
statement. If fortranLabel is non-empty, continues (CYCLEs) to that label
within nested loops are included in the returned list.
*/
std::vector<SgContinueStmt*> findContinueStmts(SgStatement* code, const std::string& fortranLabel = "");
std::vector<SgGotoStatement*> findGotoStmts(SgStatement* scope, SgLabelStatement* l);
std::vector<SgStatement*> getSwitchCases(SgSwitchStatement* sw);
//! Collect all variable references in a subtree
void collectVarRefs(SgLocatedNode* root, std::vector<SgVarRefExp* >& result);
//! Topdown traverse a subtree from root to find the first declaration given its name, scope (optional, can be NULL), and defining or nondefining flag.
template <typename T>
T* findDeclarationStatement(SgNode* root, std::string name, SgScopeStatement* scope, bool isDefining)
{
bool found = false;
#if 0
printf ("In findDeclarationStatement(): root = %p \n",root);
printf ("In findDeclarationStatement(): name = %s \n",name.c_str());
printf ("In findDeclarationStatement(): scope = %p \n",scope);
printf ("In findDeclarationStatement(): isDefining = %s \n",isDefining ? "true" : "false");
#endif
// Do we really want a NULL pointer to be acceptable input to this function?
// Maybe we should have an assertion that it is non-null?
if (!root) return NULL;
T* decl = dynamic_cast<T*>(root);
#if 0
printf ("In findDeclarationStatement(): decl = %p \n",decl);
#endif
if (decl != NULL)
{
if (scope)
{
if ((decl->get_scope() == scope) && (decl->search_for_symbol_from_symbol_table()->get_name() == name))
{
found = true;
}
}
else // Liao 2/9/2010. We should allow NULL scope
{
#if 0
// DQ (12/6/2016): Include this into the debugging code to aboid compiler warning about unused variable.
SgSymbol* symbol = decl->search_for_symbol_from_symbol_table();
printf ("In findDeclarationStatement(): decl->search_for_symbol_from_symbol_table() = %p \n",symbol);
printf ("In findDeclarationStatement(): decl->search_for_symbol_from_symbol_table()->get_name() = %s \n",symbol->get_name().str());
#endif
if (decl->search_for_symbol_from_symbol_table()->get_name() == name)
{
found = true;
}
}
}
if (found)
{
if (isDefining)
{
#if 0
printf ("In findDeclarationStatement(): decl->get_firstNondefiningDeclaration() = %p \n",decl->get_firstNondefiningDeclaration());
printf ("In findDeclarationStatement(): decl->get_definingDeclaration() = %p \n",decl->get_definingDeclaration());
#endif
ROSE_ASSERT (decl->get_definingDeclaration() != NULL);
#if 0
printf ("In findDeclarationStatement(): returing decl->get_definingDeclaration() = %p \n",decl->get_definingDeclaration());
#endif
return dynamic_cast<T*> (decl->get_definingDeclaration());
}
else
{
#if 0
printf ("In findDeclarationStatement(): returing decl = %p \n",decl);
#endif
return decl;
}
}
std::vector<SgNode*> children = root->get_traversalSuccessorContainer();
#if 0
printf ("In findDeclarationStatement(): children.size() = %zu \n",children.size());
#endif
// DQ (4/10/2016): Note that if we are searching for a function member that has it's defining
// declaration defined outside of the class then it will not be found in the child list.
for (std::vector<SgNode*>::const_iterator i = children.begin(); i != children.end(); ++i)
{
T* target = findDeclarationStatement<T> (*i,name,scope,isDefining);
if (target)
{
return target;
}
}
return NULL;
}
//! Topdown traverse a subtree from root to find the first function declaration matching the given name, scope (optional, can be NULL), and defining or nondefining flag. This is an instantiation of findDeclarationStatement<T>.
SgFunctionDeclaration* findFunctionDeclaration(SgNode* root, std::string name, SgScopeStatement* scope, bool isDefining);
#if 0 //TODO
// 1. preorder traversal from current SgNode till find next SgNode of type V_SgXXX
// until reach the end node
SgNode* getNextSgNode( const SgNode* astSourceNode, VariantT=V_SgNode, SgNode* astEndNode=NULL);
// 2. return all nodes of type VariantT following the source node
std::vector<SgNode*> getAllNextSgNode( const SgNode* astSourceNode, VariantT=V_SgNode, SgNode* astEndNode=NULL);
#endif
//@}
//------------------------------------------------------------------------
//@{
/*! @name Bottom up search
\brief Backwards traverse through the AST to find a node, findEnclosingXXX()
*/
// remember to put const to all arguments.
/** Find a node by type using upward traversal.
*
* Traverse backward through a specified node's ancestors, starting with the node's parent and progressing to more distant
* ancestors, to find the first node matching the specified or derived type. If @p includingSelf is true then the
* starting node, @p astNode, is returned if its type matches, otherwise the search starts at the parent of @p astNode.
*
* For the purposes of this function, the parent (P) of an SgDeclarationStatement node (N) is considered to be the first
* non-defining declaration of N if N has both a defining declaration and a first non-defining declaration and the defining
* declaration is different than the first non-defining declaration.
*
* If no ancestor of the requisite type of subtypes is found then this function returns a null pointer.
*
* If @p astNode is the null pointer, then the return value is a null pointer. That is, if there is no node, then there cannot
* be an enclosing node of the specified type. */
template <typename NodeType>
NodeType* getEnclosingNode(const SgNode* astNode, const bool includingSelf = false)
{
#define DEBUG_GET_ENCLOSING_NODE 0
#if 1 /* TOP_LEVEL_IF */
// DQ (12/31/2019): This version does not detect a cycle that Robb's version detects in processing Cxx11_tests/test2016_23.C.
// This will have to be investigated seperately from the issue I am working on currently.
// DQ (10/20/2012): This is the older version of this implementation. Until I am sure that
// the newer version (below) is what we want to use I will resolve this conflict by keeping
// the previous version in place.
if (NULL == astNode)
{
return NULL;
}
if ( (includingSelf ) && (dynamic_cast<const NodeType*>(astNode)) )
{
return const_cast<NodeType*>(dynamic_cast<const NodeType*> (astNode));
}
// DQ (3/5/2012): Check for reference to self...
ROSE_ASSERT(astNode->get_parent() != astNode);
SgNode* parent = astNode->get_parent();
// DQ (3/5/2012): Check for loops that will cause infinite loops.
SgNode* previouslySeenParent = parent;
bool foundCycle = false;
int counter = 0;
#if DEBUG_GET_ENCLOSING_NODE
printf ("In getEnclosingNode(): previouslySeenParent = %p = %s \n",previouslySeenParent,previouslySeenParent->class_name().c_str());
#endif
while ( (foundCycle == false) && (parent != NULL) && (!dynamic_cast<const NodeType*>(parent)) )
{
ROSE_ASSERT(parent->get_parent() != parent);
#if DEBUG_GET_ENCLOSING_NODE
printf (" --- parent = %p = %s \n",parent,parent->class_name().c_str());
printf (" --- --- parent->get_parent() = %p = %s \n",parent->get_parent(),parent->get_parent()->class_name().c_str());
#endif
#if 1
// DQ (1/8/2020): ROSE-82 (on RZ) This limit needs to be larger and increasing it to 500 was enough
// for a specific code with a long chain of if-then-else nesting, So to make this sufficent for more
// general code we have increased the lomit to 100,000. Note that 50 was not enough for real code,
// but was enough for our regression tests.
// DQ (12/30/2019): This is added to support detection of infinite loops over parent pointers.
// if (counter >= 500)
if (counter >= 100000)
{
printf ("Exiting: In getEnclosingNode(): loop limit exceeded: counter = %d \n",counter);
ROSE_ABORT();
}
#endif
parent = parent->get_parent();
// DQ (3/5/2012): Check for loops that will cause infinite loops.
// ROSE_ASSERT(parent != previouslySeenParent);
if (parent == previouslySeenParent)
{
foundCycle = true;
}
counter++;
}
#if DEBUG_GET_ENCLOSING_NODE
printf ("previouslySeenParent = %p = %s \n",previouslySeenParent,previouslySeenParent->class_name().c_str());
#endif
parent = previouslySeenParent;
SgDeclarationStatement* declarationStatement = isSgDeclarationStatement(parent);
if (declarationStatement != NULL)
{
#if 0
printf ("Found a SgDeclarationStatement \n");
#endif
SgDeclarationStatement* definingDeclaration = declarationStatement->get_definingDeclaration();
SgDeclarationStatement* firstNondefiningDeclaration = declarationStatement->get_firstNondefiningDeclaration();
#if 0
printf (" --- declarationStatement = %p \n",declarationStatement);
printf (" --- definingDeclaration = %p \n",definingDeclaration);
if (definingDeclaration != NULL && definingDeclaration->get_parent() != NULL)
printf (" --- definingDeclaration ->get_parent() = %p = %s \n",definingDeclaration->get_parent(),definingDeclaration->get_parent()->class_name().c_str());
printf (" --- firstNondefiningDeclaration = %p \n",firstNondefiningDeclaration);
if (firstNondefiningDeclaration != NULL && firstNondefiningDeclaration->get_parent() != NULL)
printf (" --- firstNondefiningDeclaration ->get_parent() = %p = %s \n",firstNondefiningDeclaration->get_parent(),firstNondefiningDeclaration->get_parent()->class_name().c_str());
#endif
if (definingDeclaration != NULL && declarationStatement != firstNondefiningDeclaration)
{
#if 0
printf ("Found a nondefining declaration so use the non-defining declaration instead \n");
#endif
// DQ (10/19/2012): Use the defining declaration instead.
// parent = firstNondefiningDeclaration;
parent = definingDeclaration;
}
}
#if 0
printf ("reset: previouslySeenParent = %p = %s \n",previouslySeenParent,previouslySeenParent->class_name().c_str());
#endif
// DQ (10/19/2012): This branch is just to document the cycle that was previously detected, it is for
// debugging only. Thus it ony make sense for it to be executed when "(foundCycle == true)". However,
// this will have to be revisited later since it appears clear that it is a problem for the binary analysis
// work when it is visited for this case. Since the cycle is detected, but there is no assertion on the
// cycle, we don't exit when a cycle is identified (which is the point of the code below).
// Note also that I have fixed the code (above and below) to only chase pointers through defining
// declarations (where they exist), this is important since non-defining declarations can be almost
// anywhere (and thus chasing them can make it appear that there are cycles where there are none
// (I think); test2012_234.C demonstrates an example of this.
// DQ (10/9/2012): Robb has suggested this change to fix the binary analysis work.
// if (foundCycle == true)
if (foundCycle == false)
{
while ( (parent != NULL) && (!dynamic_cast<const NodeType*>(parent)) )
{
ROSE_ASSERT(parent->get_parent() != parent);
#if 0
printf ("In getEnclosingNode() (2nd try): parent = %p = %s \n",parent,parent->class_name().c_str());
if (parent->get_file_info() != NULL)
parent->get_file_info()->display("In getEnclosingNode() (2nd try): debug");
#endif
SgDeclarationStatement* declarationStatement = isSgDeclarationStatement(parent);
if (declarationStatement != NULL)
{
#if DEBUG_GET_ENCLOSING_NODE
printf ("Found a SgDeclarationStatement \n");
#endif
SgDeclarationStatement* definingDeclaration = declarationStatement->get_definingDeclaration();
SgDeclarationStatement* firstNondefiningDeclaration = declarationStatement->get_firstNondefiningDeclaration();
#if 0
printf (" --- declarationStatement = %p = %s \n",declarationStatement,(declarationStatement != NULL) ? declarationStatement->class_name().c_str() : "null");
printf (" --- definingDeclaration = %p \n",definingDeclaration);
if (definingDeclaration != NULL && definingDeclaration->get_parent() != NULL)
printf (" --- definingDeclaration ->get_parent() = %p = %s \n",definingDeclaration->get_parent(),definingDeclaration->get_parent()->class_name().c_str());
printf (" --- firstNondefiningDeclaration = %p \n",firstNondefiningDeclaration);
if (firstNondefiningDeclaration != NULL && firstNondefiningDeclaration->get_parent() != NULL)
printf (" --- firstNondefiningDeclaration ->get_parent() = %p = %s \n",firstNondefiningDeclaration->get_parent(),firstNondefiningDeclaration->get_parent()->class_name().c_str());
#endif
if (definingDeclaration != NULL && declarationStatement != firstNondefiningDeclaration)
{
#if 0
printf ("Found a nondefining declaration so use the firstNondefining declaration instead \n");
#endif
// DQ (10/19/2012): Use the defining declaration instead.
// parent = firstNondefiningDeclaration;
parent = definingDeclaration;
}
}
parent = parent->get_parent();
#if 1
// DQ (3/5/2012): Check for loops that will cause infinite loops.
ROSE_ASSERT(parent != previouslySeenParent);
#else
printf ("WARNING::WARNING::WARNING commented out assertion for parent != previouslySeenParent \n");
if (parent == previouslySeenParent)
break;
#endif
}
}
return const_cast<NodeType*>(dynamic_cast<const NodeType*> (parent));
#else /* TOP_LEVEL_IF */
// DQ (10/20/2012): Using Robb's newer version with my modification to use the definingDeclaration rather than firstNondefiningDeclaration (below).
// Find the parent of specified type, but watch out for cycles in the ancestry (which would cause an infinite loop).
// Cast away const because isSg* functions aren't defined for const node pointers; and our return is not const.
SgNode *node = const_cast<SgNode*>(!astNode || includingSelf ? astNode : astNode->get_parent());
std::set<const SgNode*> seen; // nodes we've seen, in order to detect cycles
while (node) {
if (NodeType *found = dynamic_cast<NodeType*>(node))
return found;
// FIXME: Cycle detection could be moved elsewhere so we don't need to do it on every call. [RPM 2012-10-09]
// DQ (12/30/2019): Provide more detail in error message.
if (seen.insert(node).second == false)
{
printf ("Error: node is already in set and defines a cycle: node = %p = %s \n",node,node->class_name().c_str());
std::set<const SgNode*>::const_iterator i = seen.begin();
while (i != seen.end())
{
const SgNode* element = *i;
printf (" --- seen element: element = %p = %s \n",element,element->class_name().c_str());
i++;
}
printf ("Exiting after error! \n");
ROSE_ABORT();
}
// ROSE_ASSERT(seen.insert(node).second);
// Traverse to parent (declaration statements are a special case)
if (SgDeclarationStatement *declarationStatement = isSgDeclarationStatement(node)) {
SgDeclarationStatement *definingDeclaration = declarationStatement->get_definingDeclaration();
SgDeclarationStatement *firstNondefiningDeclaration = declarationStatement->get_firstNondefiningDeclaration();
if (definingDeclaration && firstNondefiningDeclaration && declarationStatement != firstNondefiningDeclaration) {
// DQ (10/19/2012): Use the defining declaration instead.
// node = firstNondefiningDeclaration;
node = definingDeclaration;
}
} else {
node = node->get_parent();
}
}
return NULL;
#endif /* TOP_LEVEL_IF */
}
//! Find enclosing source file node
ROSE_DLL_API SgSourceFile* getEnclosingSourceFile(SgNode* n, const bool includingSelf=false);
//! Get the closest scope from astNode. Return astNode if it is already a scope.
ROSE_DLL_API SgScopeStatement* getScope(const SgNode* astNode);
//! Get the enclosing scope from a node n
ROSE_DLL_API SgScopeStatement* getEnclosingScope(SgNode* n, const bool includingSelf=false);
//! Traverse back through a node's parents to find the enclosing global scope
ROSE_DLL_API SgGlobal* getGlobalScope( const SgNode* astNode);
// DQ (12/7/2020): This is supporting the recognition of functions in header files from two different AST.
//! This is supporting the recognition of functions in header files from two different ASTs
ROSE_DLL_API bool hasSameGlobalScope ( SgStatement* statement_1, SgStatement* statement_2 );
//! Find the function definition
ROSE_DLL_API SgFunctionDefinition* getEnclosingProcedure(SgNode* n, const bool includingSelf=false);
ROSE_DLL_API SgFunctionDefinition* getEnclosingFunctionDefinition(SgNode* astNode, const bool includingSelf=false);
//! Find the closest enclosing statement, including the given node
ROSE_DLL_API SgStatement* getEnclosingStatement(SgNode* n);
//! Find the closest switch outside a given statement (normally used for case and default statements)
ROSE_DLL_API SgSwitchStatement* findEnclosingSwitch(SgStatement* s);
//! Find enclosing OpenMP clause body statement from s. If s is already one, return it directly.
ROSE_DLL_API SgOmpClauseBodyStatement* findEnclosingOmpClauseBodyStatement(SgStatement* s);
//! Find the closest loop outside the given statement; if fortranLabel is not empty, the Fortran label of the loop must be equal to it
ROSE_DLL_API SgScopeStatement* findEnclosingLoop(SgStatement* s, const std::string& fortranLabel = "", bool stopOnSwitches = false);
//! Find the enclosing function declaration, including its derived instances like isSgProcedureHeaderStatement, isSgProgramHeaderStatement, and isSgMemberFunctionDeclaration.
ROSE_DLL_API SgFunctionDeclaration * getEnclosingFunctionDeclaration (SgNode * astNode, const bool includingSelf=false);
//roseSupport/utility_functions.h
//! get the SgFile node from current node
ROSE_DLL_API SgFile* getEnclosingFileNode (SgNode* astNode );
//! Get the initializer containing an expression if it is within an initializer.
ROSE_DLL_API SgInitializer* getInitializerOfExpression(SgExpression* n);
//! Get the closest class definition enclosing the specified AST node,
ROSE_DLL_API SgClassDefinition* getEnclosingClassDefinition(SgNode* astnode, const bool includingSelf=false);
//! Get the closest class declaration enclosing the specified AST node,
ROSE_DLL_API SgClassDeclaration* getEnclosingClassDeclaration( SgNode* astNode );
// DQ (2/7/2019): Adding support for name qualification of variable references associated with SgPointerMemberType function parameters.
//! Get the enclosing SgExprListExp (used as part of function argument index evaluation in subexpressions).
ROSE_DLL_API SgExprListExp* getEnclosingExprListExp(SgNode* astNode, const bool includingSelf = false);
// DQ (2/7/2019): Need a function to return when an expression is in an expression subtree.
// This is part of index evaluation ofr expressions in function argument lists, but likely usefule elsewhere as well.
ROSE_DLL_API bool isInSubTree(SgExpression* subtree, SgExpression* exp);
// DQ (2/7/2019): Need a function to return the SgFunctionDeclaration from a SgFunctionCallExp.
ROSE_DLL_API SgFunctionDeclaration* getFunctionDeclaration ( SgFunctionCallExp* functionCallExp );
// DQ (2/17/2019): Generalizing this support for SgVarRefExp and SgMemberFunctionRefExp nodes.
// DQ (2/8/2019): Adding support for detecting when to use added name qualification for pointer-to-member expressions.
ROSE_DLL_API bool isDataMemberReference(SgVarRefExp* varRefExp);
// ROSE_DLL_API bool isAddressTaken(SgVarRefExp* varRefExp);
ROSE_DLL_API bool isAddressTaken(SgExpression* refExp);
// DQ (2/17/2019): Adding support for detecting when to use added name qualification for membr function references.
ROSE_DLL_API bool isMemberFunctionMemberReference(SgMemberFunctionRefExp* memberFunctionRefExp);
// DQ (2/15/2019): Adding support for detecting which class a member reference is being made from.
// ROSE_DLL_API SgClassType* getClassTypeForDataMemberReference(SgVarRefExp* varRefExp);
// ROSE_DLL_API std::list<SgClassType*> getClassTypeChainForDataMemberReference(SgVarRefExp* varRefExp);
ROSE_DLL_API std::list<SgClassType*> getClassTypeChainForMemberReference(SgExpression* refExp);
ROSE_DLL_API std::set<SgNode*> getFrontendSpecificNodes();
// DQ (2/17/2019): Display the shared nodes in the AST for debugging.
ROSE_DLL_API void outputSharedNodes( SgNode* node );
// DQ (10/31/2020): Added function to help debug edits to statements in scopes.
ROSE_DLL_API void displayScope(SgScopeStatement* scope);
// TODO
#if 0
SgNode * getEnclosingSgNode(SgNode* source,VariantT, SgNode* endNode=NULL);
std::vector<SgNode *> getAllEnclosingSgNode(SgNode* source,VariantT, SgNode* endNode=NULL);
SgVariableDeclaration* findVariableDeclaratin( const string& varname)
SgClassDeclaration* getEnclosingClassDeclaration( const SgNode* astNode);
// e.g. for some expression, find its parent statement
SgStatement* getEnclosingStatement(const SgNode* astNode);
SgSwitchStatement* getEnclosingSwitch(SgStatement* s);
SgModuleStatement* getEnclosingModuleStatement( const SgNode* astNode);
// used to build a variable reference for compiler generated code in current scope
SgSymbol * findReachingDefinition (SgScopeStatement* startScope, SgName &name);
#endif
//@}
//------------------------------------------------------------------------
//@{
/*! @name AST Walk and Traversal
\brief
*/
// Liao, 1/9/2008
/*!
\brief return the first global scope under current project
*/
ROSE_DLL_API SgGlobal * getFirstGlobalScope(SgProject *project);
/*!
\brief get the last statement within a scope, return NULL if it does not exit
*/
ROSE_DLL_API SgStatement* getLastStatement(SgScopeStatement *scope);
//! Get the first statement within a scope, return NULL if it does not exist. Skip compiler-generated statement by default. Count transformation-generated ones, but excluding those which are not to be outputted in unparsers.
ROSE_DLL_API SgStatement* getFirstStatement(SgScopeStatement *scope,bool includingCompilerGenerated=false);
//!Find the first defining function declaration statement in a scope
ROSE_DLL_API SgFunctionDeclaration* findFirstDefiningFunctionDecl(SgScopeStatement* scope);
//! Get next statement within the same scope of current statement
ROSE_DLL_API SgStatement* getNextStatement(SgStatement * currentStmt);
//! Get previous statement of the current statement. It may return a previous statement of a parent scope by default (climbOutScope is true), otherwise only a previous statement of the same scope is returned.
ROSE_DLL_API SgStatement* getPreviousStatement(SgStatement * currentStmt, bool climbOutScope = true);
#if 0 //TODO
// preorder traversal from current SgNode till find next SgNode of type V_SgXXX
SgNode* getNextSgNode( const SgNode* currentNode, VariantT=V_SgNode);
#endif
// DQ (11/15/2018): Adding support for traversals over the include file tree.
//! return path prefix for subtree of include files.
void listHeaderFiles ( SgIncludeFile* includeFile );
//@}
//------------------------------------------------------------------------
//@{
/*! @name AST Comparison
\brief Compare AST nodes, subtree, etc
*/
//! Check if a SgIntVal node has a given value
ROSE_DLL_API bool isEqualToIntConst(SgExpression* e, int value);
//! Check if two function declarations refer to the same one. Two function declarations are the same when they are a) identical, b) same name in C c) same qualified named and mangled name in C++. A nondefining (prototype) declaration and a defining declaration of a same function are treated as the same.
/*!
* There is a similar function bool compareFunctionDeclarations(SgFunctionDeclaration *f1, SgFunctionDeclaration *f2) from Classhierarchy.C
*/
ROSE_DLL_API bool isSameFunction(SgFunctionDeclaration* func1, SgFunctionDeclaration* func2);
//! Check if a statement is the last statement within its closed scope
ROSE_DLL_API bool isLastStatement(SgStatement* stmt);
//@}
//------------------------------------------------------------------------
//@{
/*! @name AST insert, removal, and replacement
\brief Add, remove,and replace AST
scope->append_statement(), exprListExp->append_expression() etc. are not enough to handle side effect of parent pointers, symbol tables, preprocessing info, defining/nondefining pointers etc.
*/
#if 1
struct DeferredTransformation
{
// DQ (11/19/2020): We need to expand the use of this to cover deffered transformations of common SageInterface transformations (e.g. replaceStatement).
// So I needed to move this out of being specific to the outliner and make it more generally data structure in the SageInterface.
// DQ (11/15/2020): Need to add the concept of deffered transformation to cover replaceStatement operations.
// DQ (8/7/2019): Store data required to support defering the transformation to insert the outlined function prototypes
// into class declaration (when this is required to support the outlined function's access to protected or private data members).
// This is part of an optimization to support the optimization of header file unparsing (limiting the overhead of supporting any
// header file to just focus on the few (typically one) header file that would have to be unparsed.
enum TransformationKind
{
// DQ (11/22/2020): Might need to also add SageInterface::addDefaultConstructorIfRequired() and SageStatement::insert_statment()
// to support the processStatements.C transforamtions to pre-process the AST (return expressions and variable initializations).
e_error,
e_default,
e_outliner,
e_replaceStatement,
e_removeStatement,
e_replaceDefiningFunctionDeclarationWithFunctionPrototype,
e_last
};
TransformationKind deferredTransformationKind;
// DQ (12/12/2020): Adding a string label so that we can name the different kinds of transformations.
// E.g. moving pattern matched function from header file to dynamic library, vs. replacing function
// definitions in the dynamic library file with function prototypes.
std::string transformationLabel;
// Remove sets statementToRemove, replace sets statementToRemove and StatementToAdd.
SgStatement* statementToRemove;
SgStatement* statementToAdd;
SgClassDefinition* class_definition;
SgDeclarationStatement* target_class_member;
SgDeclarationStatement* new_function_prototype;
typedef std::set<SgClassDefinition *> ClassDefSet_t;
ClassDefSet_t targetClasses;
typedef std::vector<SgFunctionDeclaration *> FuncDeclList_t;
FuncDeclList_t targetFriends;
// DQ (2/28/2021): Adding support for outlining where it involves building up pre-transformations.
// For example, in the code segregation, we build a conditiona around the interval of statements
// that we are outlining. This conditional is used to overwrite the first statement in the interval
// list. Because we don't want to transform the AST until after the outlining, we need so save the
// whole interval so that we, after the outlining, remove the statements in the interval after that
// first statement.
typedef std::vector<SgStatement*> IntervalType;
IntervalType statementInterval;
SgStatement* locationToOverwriteWithTransformation;
SgStatement* transformationToOverwriteFirstStatementInInterval;
SgBasicBlock* blockOfStatementsToOutline;
// DQ (12/5/2019): Added ROSE_DLL_API prefix for Windows support (too all of these functions).
ROSE_DLL_API DeferredTransformation();
ROSE_DLL_API DeferredTransformation(SgClassDefinition* class_definition, SgDeclarationStatement* target_class_member, SgDeclarationStatement* new_function_prototype);
ROSE_DLL_API DeferredTransformation (const DeferredTransformation& X); //! Copy constructor.
ROSE_DLL_API ~DeferredTransformation (void); //! Shallow; does not delete fields.
ROSE_DLL_API DeferredTransformation & operator= (const DeferredTransformation& X); //! operator=()
// DQ (11/20/20): static function to generate specialized version of deferred transformation object.
static ROSE_DLL_API DeferredTransformation replaceDefiningFunctionDeclarationWithFunctionPrototype( SgFunctionDeclaration* functionDeclaration );
static ROSE_DLL_API DeferredTransformation replaceStatement(SgStatement* oldStmt, SgStatement* newStmt, bool movePreprocessinInfo = false);
static ROSE_DLL_API std::string outputDeferredTransformationKind(const TransformationKind & kind);
ROSE_DLL_API void display ( std::string label ) const;
};
#endif
// DQ (2/24/2009): Simple function to delete an AST subtree (used in outlining).
//! Function to delete AST subtree's nodes only, users must take care of any dangling pointers, symbols or types that result.
ROSE_DLL_API void deleteAST(SgNode* node);
//! Special purpose function for deleting AST expression tress containing valid original expression trees in constant folded expressions (for internal use only).
ROSE_DLL_API void deleteExpressionTreeWithOriginalExpressionSubtrees(SgNode* root);
// DQ (2/25/2009): Added new function to support outliner.
//! Move statements in first block to the second block (preserves order and rebuilds the symbol table).
ROSE_DLL_API void moveStatementsBetweenBlocks ( SgBasicBlock* sourceBlock, SgBasicBlock* targetBlock );
//! Move statements in Ada's package spec into C++ namespace's definition
ROSE_DLL_API void moveStatementsBetweenBlocks ( SgAdaPackageSpec * sourceBlock, SgNamespaceDefinitionStatement* targetBlock );
//! Move statements in Ada's package body into C++ namespace's definition
ROSE_DLL_API void moveStatementsBetweenBlocks ( SgAdaPackageBody* sourceBlock, SgNamespaceDefinitionStatement* targetBlock );
//! Move statements between C++ namespace's definitions
ROSE_DLL_API void moveStatementsBetweenBlocks ( SgNamespaceDefinitionStatement* sourceBlock, SgNamespaceDefinitionStatement* targetBlock );
//! Move a variable declaration to a new scope, handle symbol, special scopes like For loop, etc.
ROSE_DLL_API void moveVariableDeclaration(SgVariableDeclaration* decl, SgScopeStatement* target_scope);
//! Append a statement to the end of the current scope, handle side effect of appending statements, e.g. preprocessing info, defining/nondefining pointers etc.
ROSE_DLL_API void appendStatement(SgStatement *stmt, SgScopeStatement* scope=NULL);
//! Append a statement to the end of SgForInitStatement
ROSE_DLL_API void appendStatement(SgStatement *stmt, SgForInitStatement* for_init_stmt);
//! Append a list of statements to the end of the current scope, handle side effect of appending statements, e.g. preprocessing info, defining/nondefining pointers etc.
ROSE_DLL_API void appendStatementList(const std::vector<SgStatement*>& stmt, SgScopeStatement* scope=NULL);
// DQ (2/6/2009): Added function to support outlining into separate file.
//! Append a copy ('decl') of a function ('original_statement') into a 'scope', include any referenced declarations required if the scope is within a compiler generated file. All referenced declarations, including those from headers, are inserted if excludeHeaderFiles is set to true (the new file will not have any headers).
ROSE_DLL_API void appendStatementWithDependentDeclaration( SgDeclarationStatement* decl, SgGlobal* scope, SgStatement* original_statement, bool excludeHeaderFiles );
//! Prepend a statement to the beginning of the current scope, handling side
//! effects as appropriate
ROSE_DLL_API void prependStatement(SgStatement *stmt, SgScopeStatement* scope=NULL);
//! Prepend a statement to the beginning of SgForInitStatement
ROSE_DLL_API void prependStatement(SgStatement *stmt, SgForInitStatement* for_init_stmt);
//! prepend a list of statements to the beginning of the current scope,
//! handling side effects as appropriate
ROSE_DLL_API void prependStatementList(const std::vector<SgStatement*>& stmt, SgScopeStatement* scope=NULL);
//! Check if a scope statement has a simple children statement list
//! so insert additional statements under the scope is straightforward and unambiguous .
//! for example, SgBasicBlock has a simple statement list while IfStmt does not.
ROSE_DLL_API bool hasSimpleChildrenList (SgScopeStatement* scope);
//! Insert a statement before or after the target statement within the target's scope. Move around preprocessing info automatically
ROSE_DLL_API void insertStatement(SgStatement *targetStmt, SgStatement* newStmt, bool insertBefore= true, bool autoMovePreprocessingInfo = true);
//! Insert a list of statements before or after the target statement within the
//target's scope
ROSE_DLL_API void insertStatementList(SgStatement *targetStmt, const std::vector<SgStatement*>& newStmts, bool insertBefore= true);
//! Insert a statement before a target statement
ROSE_DLL_API void insertStatementBefore(SgStatement *targetStmt, SgStatement* newStmt, bool autoMovePreprocessingInfo = true);
//! Insert a list of statements before a target statement
ROSE_DLL_API void insertStatementListBefore(SgStatement *targetStmt, const std::vector<SgStatement*>& newStmts);
//! Insert a statement after a target statement, Move around preprocessing info automatically by default
ROSE_DLL_API void insertStatementAfter(SgStatement *targetStmt, SgStatement* newStmt, bool autoMovePreprocessingInfo = true);
//! Insert a list of statements after a target statement
ROSE_DLL_API void insertStatementListAfter(SgStatement *targetStmt, const std::vector<SgStatement*>& newStmt);
//! Insert a statement after the last declaration within a scope. The statement will be prepended to the scope if there is no declaration statement found
ROSE_DLL_API void insertStatementAfterLastDeclaration(SgStatement* stmt, SgScopeStatement* scope);
//! Insert a list of statements after the last declaration within a scope. The statement will be prepended to the scope if there is no declaration statement found
ROSE_DLL_API void insertStatementAfterLastDeclaration(std::vector<SgStatement*> stmt_list, SgScopeStatement* scope);
//! Insert a statement before the first non-declaration statement in a scope. If the scope has no non-declaration statements
// then the statement is inserted at the end of the scope.
ROSE_DLL_API void insertStatementBeforeFirstNonDeclaration(SgStatement *newStmt, SgScopeStatement *scope,
bool movePreprocessingInfo=true);
//! Insert statements before the first non-declaration statement in a scope. If the scope has no non-declaration statements
//then the new statements are inserted at the end of the scope.
ROSE_DLL_API void insertStatementListBeforeFirstNonDeclaration(const std::vector<SgStatement*> &newStmts, SgScopeStatement *scope);
// DQ (11/21/2018): We need to sometimes insert something after the last statement of the collection from rose_edg_required_macros_and_functions.h.
ROSE_DLL_API SgStatement* lastFrontEndSpecificStatement( SgGlobal* globalScope );
//! Remove a statement from its attach point of the AST. Automatically keep its associated preprocessing information at the original place after the removal. The statement is still in memory and it is up to the users to decide if the removed one will be inserted somewhere else or released from memory (deleteAST()).
ROSE_DLL_API void removeStatement(SgStatement* stmt, bool autoRelocatePreprocessingInfo = true);
//! Deep delete a sub AST tree. It uses postorder traversal to delete each child node. Users must take care of any dangling pointers, symbols or types that result. This is identical to deleteAST()
ROSE_DLL_API void deepDelete(SgNode* root);
//! Replace a statement with another. Move preprocessing information from oldStmt to newStmt if requested.
ROSE_DLL_API void replaceStatement(SgStatement* oldStmt, SgStatement* newStmt, bool movePreprocessinInfo = false);
//! Replace an anchor node with a specified pattern subtree with optional SgVariantExpression. All SgVariantExpression in the pattern will be replaced with copies of the anchor node.
ROSE_DLL_API SgNode* replaceWithPattern (SgNode * anchor, SgNode* new_pattern);
//! Replace all variable references to an old symbol in a scope to being references to a new symbol.
// Essentially replace variable a with b.
ROSE_DLL_API void replaceVariableReferences(SgVariableSymbol* old_sym, SgVariableSymbol* new_sym, SgScopeStatement * scope );
// DQ (11/12/2018): Adding test to avoid issues that we can't test for in the unparsing of header files using the token based unparsing.
//! If header file unparsing and token-based unparsing are used, then some statements in header files
//! used with the same name and different include syntax can't be transformed. This is currently because
//! there is no way to generally test the resulting transformed code generated by ROSE.
ROSE_DLL_API bool statementCanBeTransformed(SgStatement* stmt);
/** Given an expression, generates a temporary variable whose initializer optionally evaluates
* that expression. Then, the var reference expression returned can be used instead of the original
* expression. The temporary variable created can be reassigned to the expression by the returned SgAssignOp;
* this can be used when the expression the variable represents needs to be evaluated. NOTE: This handles
* reference types correctly by using pointer types for the temporary.
* @param expression Expression which will be replaced by a variable
* @param scope scope in which the temporary variable will be generated
* @param reEvaluate an assignment op to reevaluate the expression. Leave NULL if not needed
* @return declaration of the temporary variable, and a a variable reference expression to use instead of
* the original expression. */
std::pair<SgVariableDeclaration*, SgExpression* > createTempVariableForExpression(SgExpression* expression,
SgScopeStatement* scope, bool initializeInDeclaration, SgAssignOp** reEvaluate = NULL);
/* This function creates a temporary variable for a given expression in the given scope
This is different from SageInterface::createTempVariableForExpression in that it does not
try to be smart to create pointers to reference types and so on. The tempt is initialized to expression.
The caller is responsible for setting the parent of SgVariableDeclaration since buildVariableDeclaration
may not set_parent() when the scope stack is empty. See programTransformation/extractFunctionArgumentsNormalization/ExtractFunctionArguments.C for sample usage.
@param expression Expression which will be replaced by a variable
@param scope scope in which the temporary variable will be generated
*/
std::pair<SgVariableDeclaration*, SgExpression*> createTempVariableAndReferenceForExpression
(SgExpression* expression, SgScopeStatement* scope);
//! Append an argument to SgFunctionParameterList, transparently set parent,scope, and symbols for arguments when possible
/*! We recommend to build SgFunctionParameterList before building a function declaration
However, it is still allowed to append new arguments for existing function declarations.
\todo function type , function symbol also need attention.
*/
ROSE_DLL_API SgVariableSymbol* appendArg(SgFunctionParameterList *, SgInitializedName*);
//!Prepend an argument to SgFunctionParameterList
ROSE_DLL_API SgVariableSymbol* prependArg(SgFunctionParameterList *, SgInitializedName*);
//! Append an expression to a SgExprListExp, set the parent pointer also
ROSE_DLL_API void appendExpression(SgExprListExp *, SgExpression*);
//! Append an expression list to a SgExprListExp, set the parent pointers also
ROSE_DLL_API void appendExpressionList(SgExprListExp *, const std::vector<SgExpression*>&);
//! Set parameter list for a function declaration, considering existing parameter list etc.
template <class actualFunction>
void setParameterList(actualFunction *func,SgFunctionParameterList *paralist) {
// TODO consider the difference between C++ and Fortran
// fixup the scope of arguments,no symbols for nondefining function declaration's arguments
// DQ (11/25/2011): templated function so that we can handle both
// SgFunctionDeclaration and SgTemplateFunctionDeclaration (and their associated member
// function derived classes).
ROSE_ASSERT(func != NULL);
ROSE_ASSERT(paralist != NULL);
#if 0
// At this point we don't have cerr and endl defined, so comment this code out.
// Warn to users if a paralist is being shared
if (paralist->get_parent() !=NULL)
{
cerr << "Waring! Setting a used SgFunctionParameterList to function: "
<< (func->get_name()).getString()<<endl
<< " Sharing parameter lists can corrupt symbol tables!"<<endl
<< " Please use deepCopy() to get an exclusive parameter list for each function declaration!"<<endl;
// ROSE_ASSERT(false);
}
#endif
// Liao,2/5/2008 constructor of SgFunctionDeclaration will automatically generate SgFunctionParameterList, so be cautious when set new paralist!!
if (func->get_parameterList() != NULL)
{
if (func->get_parameterList() != paralist)
{
delete func->get_parameterList();
}
}
func->set_parameterList(paralist);
paralist->set_parent(func);
if (SageInterface::is_Ada_language())
{
// Ada stores variable declarations in the function parameter scope (for functions)
// and in a discriminantScope (for discriminated declarations).
// ==> just make sure that these are set.
SgInitializedNamePtrList& args = paralist->get_args();
for (SgInitializedNamePtrList::iterator i = args.begin(); i != args.end(); ++i)
{
ROSE_ASSERT(*i && isSgVariableDeclaration((*i)->get_declptr()));
}
}
else
{
// DQ (5/15/2012): Need to set the declptr in each SgInitializedName IR node.
// This is needed to support the AST Copy mechanism (at least). The files: test2005_150.C,
// test2012_81.C and testcode2012_82.C demonstrate this problem.
SgInitializedNamePtrList & args = paralist->get_args();
for (SgInitializedNamePtrList::iterator i = args.begin(); i != args.end(); i++)
{
(*i)->set_declptr(func);
}
}
}
//! Set a pragma of a pragma declaration. handle memory release for preexisting pragma, and set parent pointer.
ROSE_DLL_API void setPragma(SgPragmaDeclaration* decl, SgPragma *pragma);
//! Replace an expression with another, used for variable reference substitution and others. the old expression can be deleted (default case) or kept.
ROSE_DLL_API void replaceExpression(SgExpression* oldExp, SgExpression* newExp, bool keepOldExp=false);
//! Replace a given expression with a list of statements produced by a generator
ROSE_DLL_API void replaceExpressionWithStatement(SgExpression* from,
SageInterface::StatementGenerator* to);
//! Similar to replaceExpressionWithStatement, but with more restrictions.
//! Assumptions: from is not within the test of a loop or ifStmt, not currently traversing from or the statement it is in
ROSE_DLL_API void replaceSubexpressionWithStatement(SgExpression* from,
SageInterface::StatementGenerator* to);
//! Set operands for expressions with single operand, such as unary expressions. handle file info, lvalue, pointer downcasting, parent pointer etc.
ROSE_DLL_API void setOperand(SgExpression* target, SgExpression* operand);
//!set left hand operand for binary expressions, transparently downcasting target expressions when necessary
ROSE_DLL_API void setLhsOperand(SgExpression* target, SgExpression* lhs);
//!set left hand operand for binary expression
ROSE_DLL_API void setRhsOperand(SgExpression* target, SgExpression* rhs);
//! Set original expression trees to NULL for SgValueExp or SgCastExp expressions, so you can change the value and have it unparsed correctly.
ROSE_DLL_API void removeAllOriginalExpressionTrees(SgNode* top);
// DQ (1/25/2010): Added support for directories
//! Move file to be generated in a subdirectory (will be generated by the unparser).
ROSE_DLL_API void moveToSubdirectory ( std::string directoryName, SgFile* file );
//! Supporting function to comment relocation in insertStatement() and removeStatement().
ROSE_DLL_API SgStatement* findSurroundingStatementFromSameFile(SgStatement* targetStmt, bool & surroundingStatementPreceedsTargetStatement);
//! Relocate comments and CPP directives from one statement to another.
ROSE_DLL_API void moveCommentsToNewStatement(SgStatement* sourceStatement, const std::vector<int> & indexList, SgStatement* targetStatement, bool surroundingStatementPreceedsTargetStatement);
// DQ (7/19/2015): This is required to support general unparsing of template instantations for the GNU g++
// compiler which does not permit name qualification to be used to support the expression of the namespace
// where a template instantiatoon would be places. Such name qualification would also sometimes require
// global qualification which is also not allowed by the GNU g++ compiler. These issues appear to be
// specific to the GNU compiler versions, at least versions 4.4 through 4.8.
//! Relocate the declaration to be explicitly represented in its associated namespace (required for some backend compilers to process template instantiations).
ROSE_DLL_API void moveDeclarationToAssociatedNamespace ( SgDeclarationStatement* declarationStatement );
ROSE_DLL_API bool isTemplateInstantiationNode(SgNode* node);
ROSE_DLL_API void wrapAllTemplateInstantiationsInAssociatedNamespaces(SgProject* root);
// DQ (12/1/2015): Adding support for fixup internal data struuctures that have references to statements (e.g. macro expansions).
ROSE_DLL_API void resetInternalMapsForTargetStatement(SgStatement* sourceStatement);
// DQ (6/7/2019): Add support for transforming function definitions to function prototypes in a subtree.
// We might have to make this specific to a file (only traversing the functions in that file).
/*!\brief XXX
* This function operates on the new file used to support outlined function definitions.
* We use a copy of the file where the code will be outlined FROM, so that if there are references to
* declarations in the outlined code we can support the outpiled code with those references. This
* approach has the added advantage of also supporting the same include file tree as the original
* file where the outlined code is being taken from.
*/
ROSE_DLL_API void convertFunctionDefinitionsToFunctionPrototypes(SgNode* node);
// DQ (11/10/2019): Lower level support for convertFunctionDefinitionsToFunctionPrototypes().
// DQ (10/27/2020): Need to return the generated function prototype (incase we want to mark it for output or template unparsing from the AST).
// ROSE_DLL_API void replaceDefiningFunctionDeclarationWithFunctionPrototype ( SgFunctionDeclaration* functionDeclaration );
// ROSE_DLL_API SgDeclarationStatement* replaceDefiningFunctionDeclarationWithFunctionPrototype ( SgFunctionDeclaration* functionDeclaration );
ROSE_DLL_API SgFunctionDeclaration* replaceDefiningFunctionDeclarationWithFunctionPrototype ( SgFunctionDeclaration* functionDeclaration );
ROSE_DLL_API std::vector<SgFunctionDeclaration*> generateFunctionDefinitionsList(SgNode* node);
// DQ (10/29/2020): build a function prototype for all but member functions outside of the class (except for template instantiations).
// The reason why member functions outside of the class are an exception is because they can not be used except in a class and there
// would already be one present for the code to compile.
ROSE_DLL_API SgFunctionDeclaration* buildFunctionPrototype ( SgFunctionDeclaration* functionDeclaration );
//@}
//------------------------------------------------------------------------
//@{
/*! @name AST repair, fix, and postprocessing.
\brief Mostly used internally when some AST pieces are built without knowing their target
scope/parent, especially during bottom-up construction of AST. The associated symbols,
parent and scope pointers cannot be set on construction then.
A set of utility functions are provided to
patch up scope, parent, symbol for them when the target scope/parent become know.
*/
//! Connect variable reference to the right variable symbols when feasible, return the number of references being fixed.
/*! In AST translation, it is possible to build a variable reference before the variable
is being declared. buildVarRefExp() will use fake initialized name and symbol as placeholders
to get the work done. Users should call fixVariableReference() when AST is complete and all
variable declarations are in place.
*/
ROSE_DLL_API int fixVariableReferences(SgNode* root, bool cleanUnusedSymbol=true);
//!Patch up symbol, scope, and parent information when a SgVariableDeclaration's scope is known.
/*!
It is possible to build a variable declaration without knowing its scope information during bottom-up construction of AST, though top-down construction is recommended in general.
In this case, we have to patch up symbol table, scope and parent information when the scope is known. This function is usually used internally within appendStatment(), insertStatement().
*/
ROSE_DLL_API void fixVariableDeclaration(SgVariableDeclaration* varDecl, SgScopeStatement* scope);
//! Fix symbols, parent and scope pointers. Used internally within appendStatment(), insertStatement() etc when a struct declaration was built without knowing its target scope.
ROSE_DLL_API void fixStructDeclaration(SgClassDeclaration* structDecl, SgScopeStatement* scope);
//! Fix symbols, parent and scope pointers. Used internally within appendStatment(), insertStatement() etc when a class declaration was built without knowing its target scope.
ROSE_DLL_API void fixClassDeclaration(SgClassDeclaration* classDecl, SgScopeStatement* scope);
//! Fix symbols, parent and scope pointers. Used internally within appendStatment(), insertStatement() etc when a namespace declaration was built without knowing its target scope.
ROSE_DLL_API void fixNamespaceDeclaration(SgNamespaceDeclarationStatement* structDecl, SgScopeStatement* scope);
//! Fix symbol table for SgLabelStatement. Used Internally when the label is built without knowing its target scope. Both parameters cannot be NULL.
ROSE_DLL_API void fixLabelStatement(SgLabelStatement* label_stmt, SgScopeStatement* scope);
//! Set a numerical label for a Fortran statement. The statement should have a enclosing function definition already. SgLabelSymbol and SgLabelRefExp are created transparently as needed.
ROSE_DLL_API void setFortranNumericLabel(SgStatement* stmt, int label_value,
SgLabelSymbol::label_type_enum label_type=SgLabelSymbol::e_start_label_type,
SgScopeStatement* label_scope=NULL);
//! Suggest next usable (non-conflicting) numeric label value for a Fortran function definition scope
ROSE_DLL_API int suggestNextNumericLabel(SgFunctionDefinition* func_def);
//! Fix the symbol table and set scope (only if scope in declaration is not already set).
ROSE_DLL_API void fixFunctionDeclaration(SgFunctionDeclaration* stmt, SgScopeStatement* scope);
//! Fix the symbol table and set scope (only if scope in declaration is not already set).
ROSE_DLL_API void fixTemplateDeclaration(SgTemplateDeclaration* stmt, SgScopeStatement* scope);
//! A wrapper containing fixes (fixVariableDeclaration(),fixStructDeclaration(), fixLabelStatement(), etc) for all kinds statements. Should be used before attaching the statement into AST.
ROSE_DLL_API void fixStatement(SgStatement* stmt, SgScopeStatement* scope);
// DQ (6/11/2015): This reports the statements that are marked as transformed (used to debug the token-based unparsing).
//! This collects the statements that are marked as transformed (useful in debugging).
ROSE_DLL_API std::set<SgStatement*> collectTransformedStatements( SgNode* node );
//! This collects the statements that are marked as modified (a flag automatically set by all set_* generated functions) (useful in debugging).
ROSE_DLL_API std::set<SgStatement*> collectModifiedStatements( SgNode* node );
//! This collects the SgLocatedNodes that are marked as modified (a flag automatically set by all set_* generated functions) (useful in debugging).
ROSE_DLL_API std::set<SgLocatedNode*> collectModifiedLocatedNodes( SgNode* node );
// DQ (6/5/2019): Use the previously constructed set (above) to reset the IR nodes to be marked as isModified.
//! Use the set of IR nodes and set the isModified flag in each IR node to true.
ROSE_DLL_API void resetModifiedLocatedNodes(const std::set<SgLocatedNode*> & modifiedNodeSet);
// DQ (10/23/2018): Report nodes that are marked as modified.
ROSE_DLL_API void reportModifiedStatements(const std::string & label, SgNode* node);
// DQ (3/22/2019): Translate CPP directives from attached preprocessor information to CPP Directive Declaration IR nodes.
ROSE_DLL_API void translateToUseCppDeclarations( SgNode* n );
ROSE_DLL_API void translateScopeToUseCppDeclarations( SgScopeStatement* scope );
ROSE_DLL_API std::vector<SgC_PreprocessorDirectiveStatement*> translateStatementToUseCppDeclarations( SgStatement* statement, SgScopeStatement* scope);
ROSE_DLL_API void printOutComments ( SgLocatedNode* locatedNode );
ROSE_DLL_API bool skipTranslateToUseCppDeclaration( PreprocessingInfo* currentPreprocessingInfo );
// DQ (12/2/2019): Debugging support.
ROSE_DLL_API void outputFileIds( SgNode* node );
//@}
//! Update defining and nondefining links due to a newly introduced function declaration. Should be used after inserting the function into a scope.
/*! This function not only set the defining and nondefining links of the newly introduced
* function declaration inside a scope, but also update other same function declarations' links
* accordingly if there are any.
* Assumption: The function has already inserted/appended/prepended into the scope before calling this function.
*/
ROSE_DLL_API void updateDefiningNondefiningLinks(SgFunctionDeclaration* func, SgScopeStatement* scope);
//------------------------------------------------------------------------
//@{
/*! @name Advanced AST transformations, analyses, and optimizations
\brief Some complex but commonly used AST transformations.
*/
//! Collect all read and write references within stmt, which can be a function, a scope statement, or a single statement. Note that a reference can be both read and written, like i++
ROSE_DLL_API bool
collectReadWriteRefs(SgStatement* stmt, std::vector<SgNode*>& readRefs, std::vector<SgNode*>& writeRefs, bool useCachedDefUse=false);
//!Collect unique variables which are read or written within a statement. Note that a variable can be both read and written. The statement can be either of a function, a scope, or a single line statement. For accesses to members of aggregate data, we return the coarse grain aggregate mem obj by default.
ROSE_DLL_API bool collectReadWriteVariables(SgStatement* stmt, std::set<SgInitializedName*>& readVars, std::set<SgInitializedName*>& writeVars, bool coarseGrain=true);
//!Collect read only variables within a statement. The statement can be either of a function, a scope, or a single line statement. For accesses to members of aggregate data, we return the coarse grain aggregate mem obj by default.
ROSE_DLL_API void collectReadOnlyVariables(SgStatement* stmt, std::set<SgInitializedName*>& readOnlyVars, bool coarseGrain=true);
//!Collect read only variable symbols within a statement. The statement can be either of a function, a scope, or a single line statement. For accesses to members of aggregate data, we return the coarse grain aggregate mem obj by default.
ROSE_DLL_API void collectReadOnlySymbols(SgStatement* stmt, std::set<SgVariableSymbol*>& readOnlySymbols, bool coarseGrain=true);
//! Check if a variable reference is used by its address: including &a expression and foo(a) when type2 foo(Type& parameter) in C++
ROSE_DLL_API bool isUseByAddressVariableRef(SgVarRefExp* ref);
//! Collect variable references involving use by address: including &a expression and foo(a) when type2 foo(Type& parameter) in C++
ROSE_DLL_API void collectUseByAddressVariableRefs (const SgStatement* s, std::set<SgVarRefExp* >& varSetB);
#ifndef ROSE_USE_INTERNAL_FRONTEND_DEVELOPMENT
//!Call liveness analysis on an entire project
ROSE_DLL_API LivenessAnalysis * call_liveness_analysis(SgProject* project, bool debug=false);
//!get liveIn and liveOut variables for a for loop from liveness analysis result liv.
ROSE_DLL_API void getLiveVariables(LivenessAnalysis * liv, SgForStatement* loop, std::set<SgInitializedName*>& liveIns, std::set<SgInitializedName*> & liveOuts);
#endif
//!Recognize and collect reduction variables and operations within a C/C++ loop, following OpenMP 3.0 specification for allowed reduction variable types and operation types.
ROSE_DLL_API void ReductionRecognition(SgForStatement* loop, std::set< std::pair <SgInitializedName*, OmpSupport::omp_construct_enum> > & results);
//! Constant folding an AST subtree rooted at 'r' (replacing its children with their constant values, if applicable). Please be advised that constant folding on floating point computation may decrease the accuracy of floating point computations!
/*! It is a wrapper function for ConstantFolding::constantFoldingOptimization(). Note that only r's children are replaced with their corresponding constant values, not the input SgNode r itself. You have to call this upon an expression's parent node if you want to fold the expression. */
ROSE_DLL_API void constantFolding(SgNode* r);
//!Instrument(Add a statement, often a function call) into a function right before the return points, handle multiple return statements (with duplicated statement s) and return expressions with side effects. Return the number of statements inserted.
/*! Useful when adding a runtime library call to terminate the runtime system right before the end of a program, especially for OpenMP and UPC runtime systems. Return with complex expressions with side effects are rewritten using an additional assignment statement.
*/
ROSE_DLL_API int instrumentEndOfFunction(SgFunctionDeclaration * func, SgStatement* s);
//! Remove jumps whose label is immediately after the jump. Used to clean up inlined code fragments.
ROSE_DLL_API void removeJumpsToNextStatement(SgNode*);
//! Remove labels which are not targets of any goto statements: its child statement is also removed by default.
ROSE_DLL_API void removeUnusedLabels(SgNode* top, bool keepChild =false);
//! Find unused labels which are not targets of any goto statements
ROSE_DLL_API std::set<SgLabelStatement*> findUnusedLabels (SgNode* top);
//! Remove consecutive labels
ROSE_DLL_API void removeConsecutiveLabels(SgNode* top);
//! Merge a variable assignment statement into a matching variable declaration statement. Callers should make sure the merge is semantically correct (by not introducing compilation errors). This function simply does the merge transformation, without eligibility check.
/*!
* e.g. int i; i=10; becomes int i=10; the original i=10 will be deleted after the merge
* if success, return true, otherwise return false (e.g. variable declaration does not match or already has an initializer)
* The original assignment stmt will be removed by default
* This function is a bit ambiguous about the merge direction, to be phased out.
*/
ROSE_DLL_API bool mergeDeclarationAndAssignment (SgVariableDeclaration* decl, SgExprStatement* assign_stmt, bool removeAssignStmt = true);
//! Merge an assignment into its upstream declaration statement. Callers should make sure the merge is semantically correct.
ROSE_DLL_API bool mergeAssignmentWithDeclaration (SgExprStatement* assign_stmt, SgVariableDeclaration* decl, bool removeAssignStmt = true);
//! Merge a declaration statement into a matching followed variable assignment. Callers should make sure the merge is semantically correct (by not introducing compilation errors). This function simply does the merge transformation, without eligibility check.
/*!
* e.g. int i; i=10; becomes int i=10; the original int i; will be deleted after the merge
*/
ROSE_DLL_API bool mergeDeclarationWithAssignment (SgVariableDeclaration* decl, SgExprStatement* assign_stmt);
//! Split a variable declaration with an rhs assignment into two statements: a declaration and an assignment.
/*! Return the generated assignment statement, if any
* e.g. int i =10; becomes int i; i=10;
* This can be seen as a normalization of declarations
*/
ROSE_DLL_API SgExprStatement* splitVariableDeclaration (SgVariableDeclaration* decl);
//! Split declarations within a scope into declarations and assignment statements, by default only top level declarations are considered. Return the number of declarations split.
ROSE_DLL_API int splitVariableDeclaration (SgScopeStatement* scope, bool topLevelOnly = true);
//! Replace an expression with a temporary variable and an assignment statement
/*!
Add a new temporary variable to contain the value of 'from'.
Change reference to 'from' to use this new variable.
Assumptions: (1)'from' is not within the test of a loop or 'if';
(2)not currently traversing 'from' or the statement it is in.
Return value: the new temp variable declaration's assign initializer containing the from expression.
*/
ROSE_DLL_API SgAssignInitializer* splitExpression(SgExpression* from, std::string newName = "");
//! Split long expressions into blocks of statements
ROSE_DLL_API void splitExpressionIntoBasicBlock(SgExpression* expr);
//! Remove labeled goto statements
ROSE_DLL_API void removeLabeledGotos(SgNode* top);
//! If the given statement contains any break statements in its body, add a new label below the statement and change the breaks into gotos to that new label.
ROSE_DLL_API void changeBreakStatementsToGotos(SgStatement* loopOrSwitch);
//! Check if the body of a 'for' statement is a SgBasicBlock, create one if not.
ROSE_DLL_API SgBasicBlock* ensureBasicBlockAsBodyOfFor(SgForStatement* fs);
//! Check if the body of a 'upc_forall' statement is a SgBasicBlock, create one if not.
ROSE_DLL_API SgBasicBlock* ensureBasicBlockAsBodyOfUpcForAll(SgUpcForAllStatement* fs);
//! Check if the body of a 'while' statement is a SgBasicBlock, create one if not.
ROSE_DLL_API SgBasicBlock* ensureBasicBlockAsBodyOfWhile(SgWhileStmt* ws);
//! Check if the body of a 'do .. while' statement is a SgBasicBlock, create one if not.
ROSE_DLL_API SgBasicBlock* ensureBasicBlockAsBodyOfDoWhile(SgDoWhileStmt* ws);
//! Check if the body of a 'switch' statement is a SgBasicBlock, create one if not.
ROSE_DLL_API SgBasicBlock* ensureBasicBlockAsBodyOfSwitch(SgSwitchStatement* ws);
//! Check if the body of a 'case option' statement is a SgBasicBlock, create one if not.
SgBasicBlock* ensureBasicBlockAsBodyOfCaseOption(SgCaseOptionStmt* cs);
//! Check if the body of a 'default option' statement is a SgBasicBlock, create one if not.
SgBasicBlock* ensureBasicBlockAsBodyOfDefaultOption(SgDefaultOptionStmt * cs);
//! Check if the true body of a 'if' statement is a SgBasicBlock, create one if not.
ROSE_DLL_API SgBasicBlock* ensureBasicBlockAsTrueBodyOfIf(SgIfStmt* ifs);
//! Check if the false body of a 'if' statement is a SgBasicBlock, create one if not when the flag is true.
ROSE_DLL_API SgBasicBlock* ensureBasicBlockAsFalseBodyOfIf(SgIfStmt* ifs, bool createEmptyBody = true);
//! Check if the body of a 'catch' statement is a SgBasicBlock, create one if not.
ROSE_DLL_API SgBasicBlock* ensureBasicBlockAsBodyOfCatch(SgCatchOptionStmt* cos);
//! Check if the body of a SgOmpBodyStatement is a SgBasicBlock, create one if not
ROSE_DLL_API SgBasicBlock* ensureBasicBlockAsBodyOfOmpBodyStmt(SgOmpBodyStatement* ompbodyStmt);
// DQ (1/18/2015): This is added to support better quality token-based unparsing.
//! Remove unused basic block IR nodes added as part of normalization.
ROSE_DLL_API void cleanupNontransformedBasicBlockNode();
// DQ (1/18/2015): This is added to support better quality token-based unparsing.
//! Record where normalization have been done so that we can preform denormalizations as required for the token-based unparsing to generate minimal diffs.
ROSE_DLL_API void recordNormalizations(SgStatement* s);
//! Check if a statement is a (true or false) body of a container-like parent, such as For, Upc_forall, Do-while,
//! switch, If, Catch, OmpBodyStmt, etc
bool isBodyStatement (SgStatement* s);
//! Fix up ifs, loops, while, switch, Catch, OmpBodyStatement, etc. to have blocks as body components. It also adds an empty else body to if statements that don't have them.
void changeAllBodiesToBlocks(SgNode* top, bool createEmptyBody = true);
// The same as changeAllBodiesToBlocks(SgNode* top). Phased out.
//void changeAllLoopBodiesToBlocks(SgNode* top);
//! Make a single statement body to be a basic block. Its parent is if, while, catch, or upc_forall etc.
SgBasicBlock * makeSingleStatementBodyToBlock(SgStatement* singleStmt);
#if 0
/** If s is the body of a loop, catch, or if statement and is already a basic block,
* s is returned unmodified. Otherwise generate a SgBasicBlock between s and its parent
* (a loop, catch, or if statement, etc). */
SgLocatedNode* ensureBasicBlockAsParent(SgStatement* s);
#endif
//! Get the constant value from a constant integer expression; abort on
//! everything else. Note that signed long longs are converted to unsigned.
unsigned long long getIntegerConstantValue(SgValueExp* expr);
//! Get a statement's dependent declarations which declares the types used in the statement. The returned vector of declaration statements are sorted according to their appearance order in the original AST. Any reference to a class or template class from a namespace will treated as a reference to the enclosing namespace.
std::vector<SgDeclarationStatement*> getDependentDeclarations (SgStatement* stmt );
//! Insert an expression (new_exp )before another expression (anchor_exp) has possible side effects, without changing the original semantics. This is achieved by using a comma operator: (new_exp, anchor_exp). The comma operator is returned.
SgCommaOpExp *insertBeforeUsingCommaOp (SgExpression* new_exp, SgExpression* anchor_exp);
//! Insert an expression (new_exp ) after another expression (anchor_exp) has possible side effects, without changing the original semantics. This is done by using two comma operators: type T1; ... ((T1 = anchor_exp, new_exp),T1) )... , where T1 is a temp variable saving the possible side effect of anchor_exp. The top level comma op exp is returned. The reference to T1 in T1 = anchor_exp is saved in temp_ref.
SgCommaOpExp *insertAfterUsingCommaOp (SgExpression* new_exp, SgExpression* anchor_exp, SgStatement** temp_decl = NULL, SgVarRefExp** temp_ref = NULL);
/// \brief moves the body of a function f to a new function f`;
/// f's body is replaced with code that forwards the call to f`.
/// \return a pair indicating the statement containing the call of f`
/// and an initialized name refering to the temporary variable
/// holding the result of f`. In case f returns void
/// the initialized name is NULL.
/// \param definingDeclaration the defining function declaration of f
/// \param newName the name of function f`
/// \details f's new body becomes { f`(...); } and { int res = f`(...); return res; }
/// for functions returning void and a value, respectively.
/// two function declarations are inserted in f's enclosing scope
/// \code
/// result_type f`(...); <--- (1)
/// result_type f (...) { forward call to f` }
/// result_type f`(...) { original code } <--- (2)
/// \endcode
/// Calls to f are not updated, thus in the transformed code all
/// calls will continue calling f (this is also true for
/// recursive function calls from within the body of f`).
/// After the function has created the wrapper,
/// definingDeclaration becomes the wrapper function
/// The definition of f` is the next entry in the
/// statement list; the forward declaration of f` is the previous
/// entry in the statement list.
/// \pre definingDeclaration must be a defining declaration of a
/// free standing function.
/// typeid(SgFunctionDeclaration) == typeid(definingDeclaration)
/// i.e., this function is NOT implemented for class member functions,
/// template functions, procedures, etc.
std::pair<SgStatement*, SgInitializedName*>
wrapFunction(SgFunctionDeclaration& definingDeclaration, SgName newName);
/// \overload
/// \tparam NameGen functor that generates a new name based on the old name.
/// interface: SgName nameGen(const SgName&)
/// \param nameGen name generator
/// \brief see wrapFunction for details
template <class NameGen>
std::pair<SgStatement*, SgInitializedName*>
wrapFunction(SgFunctionDeclaration& definingDeclaration, NameGen nameGen)
{
return wrapFunction(definingDeclaration, nameGen(definingDeclaration.get_name()));
}
/// \brief convenience function that returns the first initialized name in a
/// list of variable declarations.
SgInitializedName& getFirstVariable(SgVariableDeclaration& vardecl);
//@}
// DQ (6/7/2012): Unclear where this function should go...
bool hasTemplateSyntax( const SgName & name );
#if 0
//------------------------AST dump, stringify-----------------------------
//------------------------------------------------------------------------
std::string buildOperatorString ( SgNode* astNode ); //transformationSupport.h
// do we need these?
std::string dump_node(const SgNode* astNode);
std::string dump_tree(const SgNode* astNode);
// or a friendly version of unparseToString(), as a memeber function
std::string SgNode::toString(bool asSubTree=true); // dump node or subtree
//----------------------------AST comparison------------------------------
//------------------------------------------------------------------------
// How to get generic functions for comparison?
bool isNodeEqual(SgNode* node1, SgNode* node2); //?
bool isTreeEqual(SgNode* tree1, SgNode* tree2);
//! Are two expressions equal (using a deep comparison)?
bool expressionTreeEqual(SgExpression*, SgExpression*);
//! Are corresponding expressions in two lists equal (using a deep comparison)?
bool expressionTreeEqualStar(const SgExpressionPtrList&,
const SgExpressionPtrList&);
//----------------------AST verfication/repair----------------------------
//------------------------------------------------------------------------
// sanity check of AST subtree, any suggestions?
// TODO
verifySgNode(SgNode* node, bool subTree=true);
//src/midend/astDiagnostics/AstConsistencyTests.h
// AstTests::runAllTests(SgProject * )
//src/midend/astUtil/astInterface/AstInterface.h.C
//FixSgProject(SgProject &project)
//FixSgTree(SgNode* r)
//src/frontend/SageIII/astPostProcessing
//AstPostProcessing(SgNode * node)
//--------------------------AST modification------------------------------
//------------------------------------------------------------------------
// any operations changing AST tree, including
// insert, copy, delete(remove), replace
// insert before or after some point, argument list is consistent with LowLevelRewrite
void insertAst(SgNode* targetPosition, SgNode* newNode, bool insertBefore=true);
// previous examples
//void myStatementInsert(SgStatement* target,...)
// void AstInterfaceBase::InsertStmt(AstNodePtr const & orig, AstNodePtr const &n, bool insertbefore, bool extractfromBasicBlock)
// copy
// copy children of one basic block to another basic block
//void appendStatementCopy (const SgBasicBlock* a, SgBasicBlock* b);
void copyStatements (const SgBasicBlock* src, SgBasicBlock* dst);
// delete (remove) a node or a whole subtree
void removeSgNode(SgNode* targetNode); // need this?
void removeSgNodeTree(SgNode* subtree); // need this?
void removeStatement( SgStatement* targetStmt);
//Move = delete + insert
void moveAst (SgNode* src, SgNode* target); // need this?
// similar to
void moveStatements (SgBasicBlock* src, SgBasicBlock* target);
// replace= delete old + insert new (via building or copying)
// DQ (1/25/2010): This does not appear to exist as a definition anywhere in ROSE.
// void replaceAst(SgNode* oldNode, SgNode* newNode);
//void replaceChild(SgNode* parent, SgNode* from, SgNode* to);
//bool AstInterface::ReplaceAst( const AstNodePtr& orig, const AstNodePtr& n)
//--------------------------AST transformations---------------------------
//------------------------------------------------------------------------
// Advanced AST modifications through basic AST modifications
// Might not be included in AST utitlity list, but listed here for the record.
// extract statements/content from a scope
void flattenBlocks(SgNode* n);
//src/midend/astInlining/inlinerSupport.h
void renameVariables(SgNode* n);
void renameLabels(SgNode* n, SgFunctionDefinition* enclosingFunctionDefinition);
void simpleCopyAndConstantPropagation(SgNode* top);
void changeAllMembersToPublic(SgNode* n);
void removeVariableDeclaration(SgInitializedName* initname);
//! Convert something like "int a = foo();" into "int a; a = foo();"
SgAssignOp* convertInitializerIntoAssignment(SgAssignInitializer* init);
//! Rewrites a while or for loop so that the official test is changed to
//! "true" and what had previously been the test is now an if-break
//! combination (with an inverted condition) at the beginning of the loop
//! body
void pushTestIntoBody(LoopStatement* loopStmt);
//programTransformation/finiteDifferencing/finiteDifferencing.h
//! Move variables declared in a for statement to just outside that statement.
void moveForDeclaredVariables(SgNode* root);
//------------------------ Is/Has functions ------------------------------
//------------------------------------------------------------------------
// misc. boolean functions
// some of them could moved to SgXXX class as a member function
bool isOverloaded (SgFunctionDeclaration * functionDeclaration);
bool isSwitchCond (const SgStatement* s);
bool isIfCond (const SgStatement* s);
bool isWhileCond (const SgStatement* s);
bool isStdNamespace (const SgScopeStatement* scope);
bool isTemplateInst (const SgDeclarationStatement* decl);
bool isCtor (const SgFunctionDeclaration* func);
bool isDtor (const SgFunctionDeclaration* func);
// src/midend/astInlining/typeTraits.h
bool hasTrivialDestructor(SgType* t);
ROSE_DLL_API bool isNonconstReference(SgType* t);
ROSE_DLL_API bool isReferenceType(SgType* t);
// generic ones, or move to the SgXXX class as a member function
bool isConst(SgNode* node); // const type, variable, function, etc.
// .... and more
bool isConstType (const SgType* type);
bool isConstFunction (const SgFunctionDeclaration* decl);
bool isMemberVariable(const SgInitializedName & var);
//bool isMemberVariable(const SgNode& in);
bool isPrototypeInScope (SgScopeStatement * scope,
SgFunctionDeclaration * functionDeclaration,
SgDeclarationStatement * startingAtDeclaration);
bool MayRedefined(SgExpression* expr, SgNode* root);
// bool isPotentiallyModified(SgExpression* expr, SgNode* root); // inlinderSupport.h
bool hasAddressTaken(SgExpression* expr, SgNode* root);
//src/midend/astInlining/inlinerSupport.C
// can also classified as topdown search
bool containsVariableReference(SgNode* root, SgInitializedName* var);
bool isDeclarationOf(SgVariableDeclaration* decl, SgInitializedName* var);
bool isPotentiallyModifiedDuringLifeOf(SgBasicBlock* sc,
SgInitializedName* toCheck,
SgInitializedName* lifetime)
//src/midend/programTransformation/partialRedundancyElimination/pre.h
bool anyOfListPotentiallyModifiedIn(const std::vector<SgVariableSymbol*>& syms, SgNode* n);
//------------------------ loop handling ---------------------------------
//------------------------------------------------------------------------
//get and set loop control expressions
// 0: init expr, 1: condition expr, 2: stride expr
SgExpression* getForLoopTripleValues(int valuetype,SgForStatement* forstmt );
int setForLoopTripleValues(int valuetype,SgForStatement* forstmt, SgExpression* exp);
bool isLoopIndexVarRef(SgForStatement* forstmt, SgVarRefExp *varref);
SgInitializedName * getLoopIndexVar(SgForStatement* forstmt);
//------------------------expressions-------------------------------------
//------------------------------------------------------------------------
//src/midend/programTransformation/partialRedundancyElimination/pre.h
int countComputationsOfExpressionIn(SgExpression* expr, SgNode* root);
//src/midend/astInlining/replaceExpressionWithStatement.h
void replaceAssignmentStmtWithStatement(SgExprStatement* from, StatementGenerator* to);
void replaceSubexpressionWithStatement(SgExpression* from,
StatementGenerator* to);
SgExpression* getRootOfExpression(SgExpression* n);
//--------------------------preprocessing info. -------------------------
//------------------------------------------------------------------------
//! Removes all preprocessing information at a given position.
void cutPreprocInfo (SgBasicBlock* b,
PreprocessingInfo::RelativePositionType pos,
AttachedPreprocessingInfoType& save_buf);
//! Pastes preprocessing information at the front of a statement.
void pastePreprocInfoFront (AttachedPreprocessingInfoType& save_buf,
SgStatement* s);
//! Pastes preprocessing information at the back of a statement.
void pastePreprocInfoBack (AttachedPreprocessingInfoType& save_buf,
SgStatement* s);
/*!
* \brief Moves 'before' preprocessing information.
* Moves all preprocessing information attached 'before' the source
* statement to the front of the destination statement.
*/
// a generic one for all
/// void movePreprocessingInfo(src, dest, RelativePositionType);
void moveBeforePreprocInfo (SgStatement* src, SgStatement* dest);
void moveInsidePreprocInfo (SgBasicBlock* src, SgBasicBlock* dest);
void moveAfterPreprocInfo (SgStatement* src, SgStatement* dest);
//--------------------------------operator--------------------------------
//------------------------------------------------------------------------
from transformationSupport.h, not sure if they should be included here
/* return enum code for SAGE operators */
operatorCodeType classifyOverloadedOperator(); // transformationSupport.h
/*! \brief generates a source code string from operator name.
This function returns a string representing the elementwise operator (for primative types)
that would be match that associated with the overloaded operator for a user-defined
abstractions (e.g. identifyOperator("operator+()") returns "+").
*/
std::string stringifyOperator (std::string name);
//--------------------------------macro ----------------------------------
//------------------------------------------------------------------------
std::string buildMacro ( std::string s ); //transformationSupport.h
//--------------------------------access functions---------------------------
//----------------------------------get/set sth.-----------------------------
// several categories:
* get/set a direct child/grandchild node or fields
* get/set a property flag value
* get a descendent child node using preorder searching
* get an ancestor node using bottomup/reverse searching
// SgName or string?
std::string getFunctionName (SgFunctionCallExp* functionCallExp);
std::string getFunctionTypeName ( SgFunctionCallExp* functionCallExpression );
// do we need them anymore? or existing member functions are enought?
// a generic one:
std::string get_name (const SgNode* node);
std::string get_name (const SgDeclarationStatement * declaration);
// get/set some property: should moved to SgXXX as an inherent memeber function?
// access modifier
void setExtern (SgFunctionDeclartion*)
void clearExtern()
// similarly for other declarations and other properties
void setExtern (SgVariableDeclaration*)
void setPublic()
void setPrivate()
#endif
// DQ (1/23/2013): Added support for generated a set of source sequence entries.
std::set<unsigned int> collectSourceSequenceNumbers( SgNode* astNode );
//--------------------------------Type Traits (C++)---------------------------
bool HasNoThrowAssign(const SgType * const inputType);
bool HasNoThrowCopy(const SgType * const inputType);
bool HasNoThrowConstructor(const SgType * const inputType);
bool HasTrivialAssign(const SgType * const inputType);
bool HasTrivialCopy(const SgType * const inputType);
bool HasTrivialConstructor(const SgType * const inputType);
bool HasTrivialDestructor(const SgType * const inputType);
bool HasVirtualDestructor(const SgType * const inputType);
bool IsBaseOf(const SgType * const inputBaseType, const SgType * const inputDerivedType);
bool IsAbstract(const SgType * const inputType);
bool IsClass(const SgType * const inputType);
bool IsEmpty(const SgType * const inputType);
bool IsEnum(const SgType * const inputType);
bool IsPod(const SgType * const inputType);
bool IsPolymorphic(const SgType * const inputType);
bool IsStandardLayout(const SgType * const inputType);
bool IsLiteralType(const SgType * const inputType);
bool IsTrivial(const SgType * const inputType);
bool IsUnion(const SgType * const inputType);
SgType * UnderlyingType(SgType *type);
// DQ (3/2/2014): Added a new interface function (used in the snippet insertion support).
// void supportForInitializedNameLists ( SgScopeStatement* scope, SgInitializedNamePtrList & variableList );
// DQ (3/4/2014): Added support for testing two trees for equivalents using the AST iterators.
bool isStructurallyEquivalentAST( SgNode* tree1, SgNode* tree2 );
// JP (10/14/24): Moved code to evaluate a const integer expression (like in array size definitions) to SageInterface
/*! The datastructure is used as the return type for SageInterface::evaluateConstIntegerExpression(). One needs to always check whether hasValue_ is true before accessing value_ */
struct const_int_expr_t {
size_t value_;
bool hasValue_;
};
/*! \brief The function tries to evaluate const integer expressions (such as are used in array dimension sizes). It follows variable symbols, and requires constness. */
struct const_int_expr_t evaluateConstIntegerExpression(SgExpression *expr);
// JP (9/17/14): Added function to test whether two SgType* are equivalent or not
bool checkTypesAreEqual(SgType *typeA, SgType *typeB);
//--------------------------------Java interface functions ---------------------
#ifdef ROSE_BUILD_JAVA_LANGUAGE_SUPPORT
ROSE_DLL_API std::string getTempDirectory(SgProject *project);
ROSE_DLL_API void destroyTempDirectory(std::string);
ROSE_DLL_API SgFile *processFile(SgProject *, std::string, bool unparse = false);
ROSE_DLL_API std::string preprocessPackage(SgProject *, std::string);
ROSE_DLL_API std::string preprocessImport(SgProject *, std::string);
ROSE_DLL_API SgFile* preprocessCompilationUnit(SgProject *, std::string, std::string, bool unparse = true);
ROSE_DLL_API SgClassDefinition *findJavaPackage(SgScopeStatement *, std::string);
ROSE_DLL_API SgClassDefinition *findOrInsertJavaPackage(SgProject *, std::string, bool create_directory = false);
ROSE_DLL_API SgClassDeclaration *findOrImportJavaClass(SgProject *, SgClassDefinition *package_definition, std::string);
ROSE_DLL_API SgClassDeclaration *findOrImportJavaClass(SgProject *, std::string, std::string);
ROSE_DLL_API SgClassDeclaration *findOrImportJavaClass(SgProject *, SgClassType *);
ROSE_DLL_API SgMemberFunctionDeclaration *findJavaMain(SgClassDefinition *);
ROSE_DLL_API SgMemberFunctionDeclaration *findJavaMain(SgClassType *);
#endif // ROSE_BUILD_JAVA_LANGUAGE_SUPPORT
// DQ (8/31/2016): Making this a template function so that we can have it work with user defined filters.
//! This function detects template instantiations that are relevant when filters are used.
/*!
EDG normalizes some in-class template functions and member functions to be redefined outside of a class. this causes the associated template instantiations
to be declared outside of the class, and to be marked as compiler generated (since the compiler generated form outside of the class declaration).
ROSE captures the function definitions, but in the new location (defined outside of the class declaration). This can confuse some simple tests
for template instantiations that are a part of definitions in a file, thus we have this function to detect this specific normalization.
*/
template < class T >
bool isTemplateInstantiationFromTemplateDeclarationSatisfyingFilter (SgFunctionDeclaration* function, T* filter )
{
// DQ (9/1/2016): This function is called in the Call graph generation to avoid filtering out EDG normalized
// function template instnatiations (which come from normalized template functions and member functions).
// Note that because of the EDG normailzation the membr function is moved outside of the class, and
// thus marked as compiler generated. However the template instantiations are always marked as compiler
// generated (if not specializations) and so we want to include a template instantiation that is marked
// as compiler generated, but is from a template declaration that satisfyied a specific user defined filter.
// The complexity of this detection is isolated here, but knowing that it must be called is more complex.
// This function is call in the CG.C file of tests/nonsmoke/functional/roseTests/programAnalysisTests/testCallGraphAnalysis.
bool retval = false;
#define DEBUG_TEMPLATE_NORMALIZATION_DETECTION 0
#if DEBUG_TEMPLATE_NORMALIZATION_DETECTION
printf ("In isNormalizedTemplateInstantiation(): function = %p = %s = %s \n",function,function->class_name().c_str(),function->get_name().str());
#endif
// Test for this to be a template instantation (in which case it was marked as
// compiler generated but we may want to allow it to be used in the call graph,
// if it's template was a part was defined in the current directory).
SgTemplateInstantiationFunctionDecl* templateInstantiationFunction = isSgTemplateInstantiationFunctionDecl(function);
SgTemplateInstantiationMemberFunctionDecl* templateInstantiationMemberFunction = isSgTemplateInstantiationMemberFunctionDecl(function);
if (templateInstantiationFunction != NULL)
{
// When the defining function has been normalized by EDG, only the non-defining declaration will have a source position.
templateInstantiationFunction = isSgTemplateInstantiationFunctionDecl(templateInstantiationFunction->get_firstNondefiningDeclaration());
SgTemplateFunctionDeclaration* templateFunctionDeclaration = templateInstantiationFunction->get_templateDeclaration();
if (templateFunctionDeclaration != NULL)
{
retval = filter->operator()(templateFunctionDeclaration);
}
else
{
// Assume false.
}
#if DEBUG_TEMPLATE_NORMALIZATION_DETECTION
printf (" --- case of templateInstantiationFunction: retval = %s \n",retval ? "true" : "false");
#endif
}
else
{
if (templateInstantiationMemberFunction != NULL)
{
// When the defining function has been normalized by EDG, only the non-defining declaration will have a source position.
templateInstantiationMemberFunction = isSgTemplateInstantiationMemberFunctionDecl(templateInstantiationMemberFunction->get_firstNondefiningDeclaration());
SgTemplateMemberFunctionDeclaration* templateMemberFunctionDeclaration = templateInstantiationMemberFunction->get_templateDeclaration();
if (templateMemberFunctionDeclaration != NULL)
{
retval = filter->operator()(templateMemberFunctionDeclaration);
}
else
{
// Assume false.
}
#if DEBUG_TEMPLATE_NORMALIZATION_DETECTION
printf (" --- case of templateInstantiationMemberFunction: retval = %s \n",retval ? "true" : "false");
#endif
}
}
return retval;
}
void detectCycleInType(SgType * type, const std::string & from);
// DQ (7/14/2020): Debugging support.
void checkForInitializers( SgNode* node );
}// end of namespace
#endif
|
3d25pt_var.lbpar.c
|
#include <omp.h>
#include <math.h>
#define ceild(n,d) ceil(((double)(n))/((double)(d)))
#define floord(n,d) floor(((double)(n))/((double)(d)))
#define max(x,y) ((x) > (y)? (x) : (y))
#define min(x,y) ((x) < (y)? (x) : (y))
/*
* Order-1, 3D 25 point stencil with axis-symmetric ariable coefficients
* Adapted from PLUTO and Pochoir test bench
*
* Tareq Malas
*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#ifdef LIKWID_PERFMON
#include <likwid.h>
#endif
#include "print_utils.h"
#define TESTS 2
#define MAX(a,b) ((a) > (b) ? a : b)
#define MIN(a,b) ((a) < (b) ? a : b)
/* Subtract the `struct timeval' values X and Y,
* storing the result in RESULT.
*
* Return 1 if the difference is negative, otherwise 0.
*/
int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y)
{
/* Perform the carry for the later subtraction by updating y. */
if (x->tv_usec < y->tv_usec)
{
int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1;
y->tv_usec -= 1000000 * nsec;
y->tv_sec += nsec;
}
if (x->tv_usec - y->tv_usec > 1000000)
{
int nsec = (x->tv_usec - y->tv_usec) / 1000000;
y->tv_usec += 1000000 * nsec;
y->tv_sec -= nsec;
}
/* Compute the time remaining to wait.
* tv_usec is certainly positive.
*/
result->tv_sec = x->tv_sec - y->tv_sec;
result->tv_usec = x->tv_usec - y->tv_usec;
/* Return 1 if result is negative. */
return x->tv_sec < y->tv_sec;
}
int main(int argc, char *argv[])
{
int t, i, j, k, m, test;
int Nx, Ny, Nz, Nt;
if (argc > 3) {
Nx = atoi(argv[1])+8;
Ny = atoi(argv[2])+8;
Nz = atoi(argv[3])+8;
}
if (argc > 4)
Nt = atoi(argv[4]);
// allocate the arrays
double ****A = (double ****) malloc(sizeof(double***)*2);
for(m=0; m<2;m++){
A[m] = (double ***) malloc(sizeof(double**)*Nz);
for(i=0; i<Nz; i++){
A[m][i] = (double**) malloc(sizeof(double*)*Ny);
for(j=0;j<Ny;j++){
A[m][i][j] = (double*) malloc(sizeof(double)*Nx);
}
}
}
double ****coef = (double ****) malloc(sizeof(double***)*13);
for(m=0; m<13;m++){
coef[m] = (double ***) malloc(sizeof(double**)*Nz);
for(i=0; i<Nz; i++){
coef[m][i] = (double**) malloc(sizeof(double*)*Ny);
for(j=0;j<Ny;j++){
coef[m][i][j] = (double*) malloc(sizeof(double)*Nx);
}
}
}
// tile size information, including extra element to decide the list length
int *tile_size = (int*) malloc(sizeof(int));
tile_size[0] = -1;
// The list is modified here before source-to-source transformations
tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5);
tile_size[0] = 8;
tile_size[1] = 8;
tile_size[2] = 24;
tile_size[3] = 1024;
tile_size[4] = -1;
// for timekeeping
int ts_return = -1;
struct timeval start, end, result;
double tdiff = 0.0, min_tdiff=1.e100;
const int BASE = 1024;
// initialize variables
//
srand(42);
for (i = 1; i < Nz; i++) {
for (j = 1; j < Ny; j++) {
for (k = 1; k < Nx; k++) {
A[0][i][j][k] = 1.0 * (rand() % BASE);
}
}
}
for (m=0; m<13; m++) {
for (i=1; i<Nz; i++) {
for (j=1; j<Ny; j++) {
for (k=1; k<Nx; k++) {
coef[m][i][j][k] = 1.0 * (rand() % BASE);
}
}
}
}
#ifdef LIKWID_PERFMON
LIKWID_MARKER_INIT;
#pragma omp parallel
{
LIKWID_MARKER_THREADINIT;
#pragma omp barrier
LIKWID_MARKER_START("calc");
}
#endif
int num_threads = 1;
#if defined(_OPENMP)
num_threads = omp_get_max_threads();
#endif
for(test=0; test<TESTS; test++){
gettimeofday(&start, 0);
// serial execution - Addition: 6 && Multiplication: 2
/* Copyright (C) 1991-2014 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
/* This header is separate from features.h so that the compiler can
include it implicitly at the start of every compilation. It must
not itself include <features.h> or any other header that includes
<features.h> because the implicit include comes before any feature
test macros that may be defined in a source file before it first
explicitly includes a system header. GCC knows the name of this
header in order to preinclude it. */
/* glibc's intent is to support the IEC 559 math functionality, real
and complex. If the GCC (4.9 and later) predefined macros
specifying compiler intent are available, use them to determine
whether the overall intent is to support these features; otherwise,
presume an older compiler has intent to support these features and
define these macros by default. */
/* wchar_t uses ISO/IEC 10646 (2nd ed., published 2011-03-15) /
Unicode 6.0. */
/* We do not support C11 <threads.h>. */
int t1, t2, t3, t4, t5, t6, t7, t8;
int lb, ub, lbp, ubp, lb2, ub2;
register int lbv, ubv;
/* Start of CLooG code */
if ((Nt >= 1) && (Nx >= 9) && (Ny >= 9) && (Nz >= 9)) {
for (t1=-1;t1<=Nt-1;t1++) {
lbp=ceild(t1+1,2);
ubp=min(floord(4*Nt+Nz-9,8),floord(4*t1+Nz-2,8));
#pragma omp parallel for private(lbv,ubv,t3,t4,t5,t6,t7,t8)
for (t2=lbp;t2<=ubp;t2++) {
for (t3=max(ceild(t1-4,6),ceild(8*t2-Nz-11,24));t3<=min(floord(4*Nt+Ny-9,24),floord(4*t1+Ny-1,24));t3++) {
for (t4=max(max(ceild(t1-254,256),ceild(8*t2-Nz-1011,1024)),ceild(24*t3-Ny-1011,1024));t4<=min(min(floord(4*Nt+Nx-9,1024),floord(4*t1+Nx-1,1024)),floord(24*t3+Nx+11,1024));t4++) {
for (t5=max(max(max(max(0,ceild(8*t2-Nz+5,4)),ceild(24*t3-Ny+5,4)),ceild(1024*t4-Nx+5,4)),t1);t5<=min(min(min(Nt-1,t1+1),6*t3+4),256*t4+254);t5++) {
for (t6=max(max(8*t2,4*t5+4),-8*t1+8*t2+8*t5-7);t6<=min(min(8*t2+7,-8*t1+8*t2+8*t5),4*t5+Nz-5);t6++) {
for (t7=max(24*t3,4*t5+4);t7<=min(24*t3+23,4*t5+Ny-5);t7++) {
lbv=max(1024*t4,4*t5+4);
ubv=min(1024*t4+1023,4*t5+Nx-5);
#pragma ivdep
#pragma vector always
for (t8=lbv;t8<=ubv;t8++) {
A[( t5 + 1) % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] = (((((((((((((coef[0][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)]) + (coef[1][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6) - 1][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 1][ (-4*t5+t7)][ (-4*t5+t8)]))) + (coef[2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 1][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 1][ (-4*t5+t8)]))) + (coef[3][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 1] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 1]))) + (coef[4][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6) - 2][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 2][ (-4*t5+t7)][ (-4*t5+t8)]))) + (coef[5][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 2][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 2][ (-4*t5+t8)]))) + (coef[6][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 2] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 2]))) + (coef[7][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6) - 3][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 3][ (-4*t5+t7)][ (-4*t5+t8)]))) + (coef[8][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 3][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 3][ (-4*t5+t8)]))) + (coef[9][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 3] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 3]))) + (coef[10][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6) - 4][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 4][ (-4*t5+t7)][ (-4*t5+t8)]))) + (coef[11][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 4][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 4][ (-4*t5+t8)]))) + (coef[12][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 4] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 4])));;
}
}
}
}
}
}
}
}
}
/* End of CLooG code */
gettimeofday(&end, 0);
ts_return = timeval_subtract(&result, &end, &start);
tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6);
min_tdiff = min(min_tdiff, tdiff);
printf("Rank 0 TEST# %d time: %f\n", test, tdiff);
}
PRINT_RESULTS(4, "variable axis-symmetric")
#ifdef LIKWID_PERFMON
#pragma omp parallel
{
LIKWID_MARKER_STOP("calc");
}
LIKWID_MARKER_CLOSE;
#endif
// Free allocated arrays
for(i=0; i<Nz; i++){
for(j=0;j<Ny;j++){
free(A[0][i][j]);
free(A[1][i][j]);
}
free(A[0][i]);
free(A[1][i]);
}
free(A[0]);
free(A[1]);
for(m=0; m<13;m++){
for(i=0; i<Nz; i++){
for(j=0;j<Ny;j++){
free(coef[m][i][j]);
}
free(coef[m][i]);
}
free(coef[m]);
}
return 0;
}
|
GB_binop__band_uint32.c
|
//------------------------------------------------------------------------------
// GB_binop: hard-coded functions for each built-in binary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated2/ folder, do not edit it
// (it is auto-generated from Generator/*).
#include "GB.h"
#ifndef GBCUDA_DEV
#include "GB_emult.h"
#include "GB_control.h"
#include "GB_ek_slice.h"
#include "GB_dense.h"
#include "GB_atomics.h"
#include "GB_bitmap_assign_methods.h"
#include "GB_binop__include.h"
// C=binop(A,B) is defined by the following types and operators:
// A+B function (eWiseAdd): GB (_AaddB__band_uint32)
// A.*B function (eWiseMult): GB (_AemultB_08__band_uint32)
// A.*B function (eWiseMult): GB (_AemultB_02__band_uint32)
// A.*B function (eWiseMult): GB (_AemultB_04__band_uint32)
// A.*B function (eWiseMult): GB (_AemultB_bitmap__band_uint32)
// A*D function (colscale): GB (_AxD__band_uint32)
// D*A function (rowscale): GB (_DxB__band_uint32)
// C+=B function (dense accum): GB (_Cdense_accumB__band_uint32)
// C+=b function (dense accum): GB (_Cdense_accumb__band_uint32)
// C+=A+B function (dense ewise3): GB ((none))
// C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__band_uint32)
// C=scalar+B GB (_bind1st__band_uint32)
// C=scalar+B' GB (_bind1st_tran__band_uint32)
// C=A+scalar GB (_bind2nd__band_uint32)
// C=A'+scalar GB (_bind2nd_tran__band_uint32)
// C type: uint32_t
// A type: uint32_t
// A pattern? 0
// B type: uint32_t
// B pattern? 0
// BinaryOp: cij = (aij) & (bij)
#define GB_ATYPE \
uint32_t
#define GB_BTYPE \
uint32_t
#define GB_CTYPE \
uint32_t
// true if the types of A and B are identical
#define GB_ATYPE_IS_BTYPE \
1
// true if the types of C and A are identical
#define GB_CTYPE_IS_ATYPE \
1
// true if the types of C and B are identical
#define GB_CTYPE_IS_BTYPE \
1
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA,A_iso) \
uint32_t aij = GBX (Ax, pA, A_iso)
// true if values of A are not used
#define GB_A_IS_PATTERN \
0 \
// bij = Bx [pB]
#define GB_GETB(bij,Bx,pB,B_iso) \
uint32_t bij = GBX (Bx, pB, B_iso)
// true if values of B are not used
#define GB_B_IS_PATTERN \
0 \
// declare scalar of the same type as C
#define GB_CTYPE_SCALAR(t) \
uint32_t t
// cij = Ax [pA]
#define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \
cij = GBX (Ax, pA, A_iso)
// cij = Bx [pB]
#define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \
cij = GBX (Bx, pB, B_iso)
#define GB_CX(p) Cx [p]
// binary operator
#define GB_BINOP(z,x,y,i,j) \
z = (x) & (y) ;
// true if the binop must be flipped
#define GB_BINOP_FLIP \
0
// op is second
#define GB_OP_IS_SECOND \
0
// do the numerical phases of GB_add and GB_emult
#define GB_PHASE_2_OF_2
// hard-coded loops can be vectorized
#define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_BAND || GxB_NO_UINT32 || GxB_NO_BAND_UINT32)
//------------------------------------------------------------------------------
// C += A+B, all 3 matrices dense
//------------------------------------------------------------------------------
#if 0
// The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV.
void GB ((none))
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#include "GB_dense_ewise3_accum_template.c"
}
#endif
//------------------------------------------------------------------------------
// C = A+B, all 3 matrices dense
//------------------------------------------------------------------------------
void GB (_Cdense_ewise3_noaccum__band_uint32)
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#include "GB_dense_ewise3_noaccum_template.c"
}
//------------------------------------------------------------------------------
// C += B, accumulate a sparse matrix into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_accumB__band_uint32)
(
GrB_Matrix C,
const GrB_Matrix B,
const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
{
#include "GB_dense_subassign_23_template.c"
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C += b, accumulate a scalar into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_accumb__band_uint32)
(
GrB_Matrix C,
const GB_void *p_bwork,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
{
// get the scalar b for C += b, of type uint32_t
uint32_t bwork = (*((uint32_t *) p_bwork)) ;
#include "GB_dense_subassign_22_template.c"
return (GrB_SUCCESS) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = A*D, column scale with diagonal D matrix
//------------------------------------------------------------------------------
GrB_Info GB (_AxD__band_uint32)
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix D,
const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint32_t *restrict Cx = (uint32_t *) C->x ;
#include "GB_AxB_colscale_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = D*B, row scale with diagonal D matrix
//------------------------------------------------------------------------------
GrB_Info GB (_DxB__band_uint32)
(
GrB_Matrix C,
const GrB_Matrix D,
const GrB_Matrix B,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint32_t *restrict Cx = (uint32_t *) C->x ;
#include "GB_AxB_rowscale_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B
//------------------------------------------------------------------------------
GrB_Info GB (_AaddB__band_uint32)
(
GrB_Matrix C,
const int C_sparsity,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const bool is_eWiseUnion,
const GB_void *alpha_scalar_in,
const GB_void *beta_scalar_in,
const bool Ch_is_Mh,
const int64_t *restrict C_to_M,
const int64_t *restrict C_to_A,
const int64_t *restrict C_to_B,
const GB_task_struct *restrict TaskList,
const int C_ntasks,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
GB_WERK_DECLARE (M_ek_slicing, int64_t) ;
GB_WERK_DECLARE (A_ek_slicing, int64_t) ;
GB_WERK_DECLARE (B_ek_slicing, int64_t) ;
uint32_t alpha_scalar ;
uint32_t beta_scalar ;
if (is_eWiseUnion)
{
alpha_scalar = (*((uint32_t *) alpha_scalar_in)) ;
beta_scalar = (*((uint32_t *) beta_scalar_in )) ;
}
#include "GB_add_template.c"
GB_FREE_WORKSPACE ;
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C=A.*B, C<M>=A.*B, or C<M!>=A.*B where C is sparse/hyper
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_08__band_uint32)
(
GrB_Matrix C,
const int C_sparsity,
const int ewise_method,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *restrict C_to_M,
const int64_t *restrict C_to_A,
const int64_t *restrict C_to_B,
const GB_task_struct *restrict TaskList,
const int C_ntasks,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_emult_08_meta.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_02__band_uint32)
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const bool flipxy,
const int64_t *restrict Cp_kfirst,
const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#if GB_BINOP_FLIP
// The operator is not commutative, and does not have a flipped
// variant. For example z=atan2(y,x).
if (flipxy)
{
// use fmult(y,x)
#undef GB_FLIPPED
#define GB_FLIPPED 1
#include "GB_emult_02_template.c"
}
else
{
// use fmult(x,y)
#undef GB_FLIPPED
#define GB_FLIPPED 0
#include "GB_emult_02_template.c"
}
#else
// No need to handle the flip: the operator is either commutative, or
// has been handled by changing z=div(y,x) to z=rdiv(x,y) for example.
#undef GB_FLIPPED
#define GB_FLIPPED 0
#include "GB_emult_02_template.c"
#endif
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_04__band_uint32)
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *restrict Cp_kfirst,
const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_emult_04_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_bitmap__band_uint32)
(
GrB_Matrix C,
const int ewise_method,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_bitmap_emult_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st
//------------------------------------------------------------------------------
GrB_Info GB (_bind1st__band_uint32)
(
GB_void *Cx_output, // Cx and Bx may be aliased
const GB_void *x_input,
const GB_void *Bx_input,
const int8_t *restrict Bb,
int64_t bnz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint32_t *Cx = (uint32_t *) Cx_output ;
uint32_t x = (*((uint32_t *) x_input)) ;
uint32_t *Bx = (uint32_t *) Bx_input ;
int64_t p ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < bnz ; p++)
{
if (!GBB (Bb, p)) continue ;
uint32_t bij = GBX (Bx, p, false) ;
Cx [p] = (x) & (bij) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd
//------------------------------------------------------------------------------
GrB_Info GB (_bind2nd__band_uint32)
(
GB_void *Cx_output, // Cx and Ax may be aliased
const GB_void *Ax_input,
const GB_void *y_input,
const int8_t *restrict Ab,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
uint32_t *Cx = (uint32_t *) Cx_output ;
uint32_t *Ax = (uint32_t *) Ax_input ;
uint32_t y = (*((uint32_t *) y_input)) ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!GBB (Ab, p)) continue ;
uint32_t aij = GBX (Ax, p, false) ;
Cx [p] = (aij) & (y) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (x, A'): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (x, aij), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
uint32_t aij = GBX (Ax, pA, false) ; \
Cx [pC] = (x) & (aij) ; \
}
GrB_Info GB (_bind1st_tran__band_uint32)
(
GrB_Matrix C,
const GB_void *x_input,
const GrB_Matrix A,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
// GB_unop_transpose.c uses GB_ATYPE, but A is
// the 2nd input to binary operator z=f(x,y).
#undef GB_ATYPE
#define GB_ATYPE \
uint32_t
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint32_t x = (*((const uint32_t *) x_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
#undef GB_ATYPE
#define GB_ATYPE \
uint32_t
}
//------------------------------------------------------------------------------
// C = op (A', y): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (aij, y), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
uint32_t aij = GBX (Ax, pA, false) ; \
Cx [pC] = (aij) & (y) ; \
}
GrB_Info GB (_bind2nd_tran__band_uint32)
(
GrB_Matrix C,
const GrB_Matrix A,
const GB_void *y_input,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint32_t y = (*((const uint32_t *) y_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
StVenantKirchhoffMaterial.c
|
/* This file is part of redbKIT.
* Copyright (c) 2016, Ecole Polytechnique Federale de Lausanne (EPFL)
* Author: Federico Negri <[email protected]>
*/
#include "StVenantKirchhoffMaterial.h"
/*************************************************************************/
void StVenantKirchhoffMaterial_forces(mxArray* plhs[], const mxArray* prhs[])
{
double* dim_ptr = mxGetPr(prhs[0]);
int dim = (int)(dim_ptr[0]);
int noe = mxGetN(prhs[4]);
double* nln_ptr = mxGetPr(prhs[5]);
int nln = (int)(nln_ptr[0]);
int numRowsElements = mxGetM(prhs[4]);
int nln2 = nln*nln;
plhs[0] = mxCreateDoubleMatrix(nln*noe*dim,1, mxREAL);
plhs[1] = mxCreateDoubleMatrix(nln*noe*dim,1, mxREAL);
double* myRrows = mxGetPr(plhs[0]);
double* myRcoef = mxGetPr(plhs[1]);
int k,l;
int q;
int NumQuadPoints = mxGetN(prhs[6]);
int NumNodes = (int)(mxGetM(prhs[3]) / dim);
double* U_h = mxGetPr(prhs[3]);
double* w = mxGetPr(prhs[6]);
double* invjac = mxGetPr(prhs[7]);
double* detjac = mxGetPr(prhs[8]);
double* phi = mxGetPr(prhs[9]);
double* gradrefphi = mxGetPr(prhs[10]);
double* elements = mxGetPr(prhs[4]);
double Id[dim][dim];
int d1,d2;
for (d1 = 0; d1 < dim; d1 = d1 + 1 )
{
for (d2 = 0; d2 < dim; d2 = d2 + 1 )
{
Id[d1][d2] = 0;
if (d1==d2)
{
Id[d1][d2] = 1;
}
}
}
double* material_param = mxGetPr(prhs[2]);
double Young = material_param[0];
double Poisson = material_param[1];
double mu = Young / (2 + 2 * Poisson);
double lambda = Young * Poisson /( (1+Poisson) * (1-2*Poisson) );
/* Assembly: loop over the elements */
int ie;
#pragma omp parallel for shared(invjac,detjac,elements,myRrows,myRcoef,U_h) private(ie,k,l,q,d1,d2) firstprivate(phi,w,numRowsElements,nln2,nln,NumNodes,Id,mu,lambda)
for (ie = 0; ie < noe; ie = ie + 1 )
{
double gradphi[NumQuadPoints][dim][nln];
double GradV[dim][dim];
double GradUh[NumQuadPoints][dim][dim];
double F[NumQuadPoints][dim][dim];
double E[NumQuadPoints][dim][dim];
double P_Uh[dim][dim];
double FE[NumQuadPoints][dim][dim];
double traceE[NumQuadPoints];
for (q = 0; q < NumQuadPoints; q = q + 1 )
{
/* Compute Gradient of Basis functions*/
for (k = 0; k < nln; k = k + 1 )
{
for (d1 = 0; d1 < dim; d1 = d1 + 1 )
{
gradphi[q][d1][k] = 0;
for (d2 = 0; d2 < dim; d2 = d2 + 1 )
{
gradphi[q][d1][k] = gradphi[q][d1][k] + INVJAC(ie,d1,d2)*GRADREFPHI(k,q,d2);
}
}
}
for (d1 = 0; d1 < dim; d1 = d1 + 1 )
{
for (d2 = 0; d2 < dim; d2 = d2 + 1 )
{
GradUh[q][d1][d2] = 0;
for (k = 0; k < nln; k = k + 1 )
{
int e_k;
e_k = (int)(elements[ie*numRowsElements + k] + d1*NumNodes - 1);
GradUh[q][d1][d2] = GradUh[q][d1][d2] + U_h[e_k] * gradphi[q][d2][k];
}
F[q][d1][d2] = Id[d1][d2] + GradUh[q][d1][d2];
}
}
MatrixProductAlphaT1(dim, 1.0, F[q], F[q], E[q] );
for (d1 = 0; d1 < dim; d1 = d1 + 1 )
{
for (d2 = 0; d2 < dim; d2 = d2 + 1 )
{
E[q][d1][d2] = 0.5 * ( E[q][d1][d2] - Id[d1][d2] );
}
}
traceE[q] = Trace(dim, E[q]);
MatrixProduct(dim, F[q], E[q], FE[q] );
}
int ii = 0;
int a, i_c, j_c;
/* loop over test functions --> a */
for (a = 0; a < nln; a = a + 1 )
{
/* loop over test components --> i_c */
for (i_c = 0; i_c < dim; i_c = i_c + 1 )
{
/* set gradV to zero*/
for (d1 = 0; d1 < dim; d1 = d1 + 1 )
{
for (d2 = 0; d2 < dim; d2 = d2 + 1 )
{
GradV[d1][d2] = 0;
}
}
double rloc = 0;
for (q = 0; q < NumQuadPoints; q = q + 1 )
{
for (d2 = 0; d2 < dim; d2 = d2 + 1 )
{
GradV[i_c][d2] = gradphi[q][d2][a];
}
for (d1 = 0; d1 < dim; d1 = d1 + 1 )
{
for (d2 = 0; d2 < dim; d2 = d2 + 1 )
{
P_Uh[d1][d2] = ( 2 * mu * FE[q][d1][d2] + lambda * traceE[q] * F[q][d1][d2] );
}
}
rloc = rloc + Mdot( dim, GradV, P_Uh) * w[q];
}
myRrows[ie*nln*dim+ii] = elements[a+ie*numRowsElements] + i_c * NumNodes;
myRcoef[ie*nln*dim+ii] = rloc*detjac[ie];
ii = ii + 1;
}
}
}
}
/*************************************************************************/
void StVenantKirchhoffMaterial_jacobian(mxArray* plhs[], const mxArray* prhs[])
{
double* dim_ptr = mxGetPr(prhs[0]);
int dim = (int)(dim_ptr[0]);
int noe = mxGetN(prhs[4]);
double* nln_ptr = mxGetPr(prhs[5]);
int nln = (int)(nln_ptr[0]);
int numRowsElements = mxGetM(prhs[4]);
int nln2 = nln*nln;
plhs[0] = mxCreateDoubleMatrix(nln2*noe*dim*dim,1, mxREAL);
plhs[1] = mxCreateDoubleMatrix(nln2*noe*dim*dim,1, mxREAL);
plhs[2] = mxCreateDoubleMatrix(nln2*noe*dim*dim,1, mxREAL);
double* myArows = mxGetPr(plhs[0]);
double* myAcols = mxGetPr(plhs[1]);
double* myAcoef = mxGetPr(plhs[2]);
int k,l;
int q;
int NumQuadPoints = mxGetN(prhs[6]);
int NumNodes = (int)(mxGetM(prhs[3]) / dim);
double* U_h = mxGetPr(prhs[3]);
double* w = mxGetPr(prhs[6]);
double* invjac = mxGetPr(prhs[7]);
double* detjac = mxGetPr(prhs[8]);
double* phi = mxGetPr(prhs[9]);
double* gradrefphi = mxGetPr(prhs[10]);
double gradphi[dim][nln][NumQuadPoints];
double* elements = mxGetPr(prhs[4]);
double GradV[dim][dim];
double GradU[dim][dim];
double GradUh[dim][dim][NumQuadPoints];
double Id[dim][dim];
int d1,d2;
for (d1 = 0; d1 < dim; d1 = d1 + 1 )
{
for (d2 = 0; d2 < dim; d2 = d2 + 1 )
{
Id[d1][d2] = 0;
if (d1==d2)
{
Id[d1][d2] = 1;
}
}
}
double F[dim][dim][NumQuadPoints];
double E[dim][dim][NumQuadPoints];
double dP[dim][dim];
double P_Uh[dim][dim];
double dF[dim][dim];
double dE[dim][dim];
double* material_param = mxGetPr(prhs[2]);
double Young = material_param[0];
double Poisson = material_param[1];
double mu = Young / (2 + 2 * Poisson);
double lambda = Young * Poisson /( (1+Poisson) * (1-2*Poisson) );
/* Assembly: loop over the elements */
int ie;
#pragma omp parallel for shared(invjac,detjac,elements,myAcols,myArows,myAcoef,U_h) private(gradphi,F,E,dP,P_Uh,dF,dE,GradV,GradU,GradUh,ie,k,l,q,d1,d2) firstprivate(phi,gradrefphi,w,numRowsElements,nln2,nln,NumNodes,Id,mu,lambda)
for (ie = 0; ie < noe; ie = ie + 1 )
{
double traceE[NumQuadPoints];
for (q = 0; q < NumQuadPoints; q = q + 1 )
{
/* Compute Gradient of Basis functions*/
for (k = 0; k < nln; k = k + 1 )
{
for (d1 = 0; d1 < dim; d1 = d1 + 1 )
{
gradphi[d1][k][q] = 0;
for (d2 = 0; d2 < dim; d2 = d2 + 1 )
{
gradphi[d1][k][q] = gradphi[d1][k][q] + INVJAC(ie,d1,d2)*GRADREFPHI(k,q,d2);
}
}
}
for (d1 = 0; d1 < dim; d1 = d1 + 1 )
{
for (d2 = 0; d2 < dim; d2 = d2 + 1 )
{
GradUh[d1][d2][q] = 0;
for (k = 0; k < nln; k = k + 1 )
{
int e_k;
e_k = (int)(elements[ie*numRowsElements + k] + d1*NumNodes - 1);
GradUh[d1][d2][q] = GradUh[d1][d2][q] + U_h[e_k] * gradphi[d2][k][q];
}
F[d1][d2][q] = Id[d1][d2] + GradUh[d1][d2][q];
}
}
compute_GreenStrainTensor(dim, NumQuadPoints, F, Id, E, q );
traceE[q] = TraceQ(dim, NumQuadPoints, E, q);
}
int iii = 0;
int ii = 0;
int a, b, i_c, j_c;
/* loop over test functions --> a */
for (a = 0; a < nln; a = a + 1 )
{
/* loop over test components --> i_c */
for (i_c = 0; i_c < dim; i_c = i_c + 1 )
{
/* set gradV to zero*/
for (d1 = 0; d1 < dim; d1 = d1 + 1 )
{
for (d2 = 0; d2 < dim; d2 = d2 + 1 )
{
GradV[d1][d2] = 0;
}
}
/* loop over trial functions --> b */
for (b = 0; b < nln; b = b + 1 )
{
/* loop over trial components --> j_c */
for (j_c = 0; j_c < dim; j_c = j_c + 1 )
{
/* set gradU to zero*/
for (d1 = 0; d1 < dim; d1 = d1 + 1 )
{
for (d2 = 0; d2 < dim; d2 = d2 + 1 )
{
GradU[d1][d2] = 0;
}
}
double aloc = 0;
for (q = 0; q < NumQuadPoints; q = q + 1 )
{
for (d2 = 0; d2 < dim; d2 = d2 + 1 )
{
GradV[i_c][d2] = gradphi[d2][a][q];
GradU[j_c][d2] = gradphi[d2][b][q];
}
for (d1 = 0; d1 < dim; d1 = d1 + 1 )
{
for (d2 = 0; d2 < dim; d2 = d2 + 1 )
{
dF[d1][d2] = GradU[d1][d2];
}
}
compute_DerGreenStrainTensor(dim, NumQuadPoints, F, dF, dE, q );
double trace_dE = Trace(dim, dE);
double P1[dim][dim];
double P2[dim][dim];
double P_tmp[dim][dim];
for (d1 = 0; d1 < dim; d1 = d1 + 1 )
{
for (d2 = 0; d2 < dim; d2 = d2 + 1 )
{
P1[d1][d2] = 2 * mu * E[d1][d2][q] + lambda * traceE[q] * Id[d1][d2] ;
P2[d1][d2] = 2 * mu * dE[d1][d2] + lambda * trace_dE * Id[d1][d2] ;
}
}
MatrixProduct(dim, dF, P1, dP);
MatrixProductQ1(dim, NumQuadPoints, F, P2, P_tmp, q);
MatrixSum(dim, dP, P_tmp);
aloc = aloc + Mdot( dim, GradV, dP) * w[q];
}
myArows[ie*nln2*dim*dim+iii] = elements[a+ie*numRowsElements] + i_c * NumNodes;
myAcols[ie*nln2*dim*dim+iii] = elements[b+ie*numRowsElements] + j_c * NumNodes;
myAcoef[ie*nln2*dim*dim+iii] = aloc*detjac[ie];
iii = iii + 1;
}
}
}
}
}
}
/*************************************************************************/
void StVenantKirchhoffMaterial_jacobianFast3D(mxArray* plhs[], const mxArray* prhs[])
{
double* dim_ptr = mxGetPr(prhs[0]);
int dim = (int)(dim_ptr[0]);
int noe = mxGetN(prhs[4]);
double* nln_ptr = mxGetPr(prhs[5]);
int nln = (int)(nln_ptr[0]);
int numRowsElements = mxGetM(prhs[4]);
int nln2 = nln*nln;
plhs[0] = mxCreateDoubleMatrix(nln2*noe*dim*dim,1, mxREAL);
plhs[1] = mxCreateDoubleMatrix(nln2*noe*dim*dim,1, mxREAL);
plhs[2] = mxCreateDoubleMatrix(nln2*noe*dim*dim,1, mxREAL);
double* myArows = mxGetPr(plhs[0]);
double* myAcols = mxGetPr(plhs[1]);
double* myAcoef = mxGetPr(plhs[2]);
int k,l;
int q;
int NumQuadPoints = mxGetN(prhs[6]);
int NumNodes = (int)(mxGetM(prhs[3]) / dim);
double* U_h = mxGetPr(prhs[3]);
double* w = mxGetPr(prhs[6]);
double* invjac = mxGetPr(prhs[7]);
double* detjac = mxGetPr(prhs[8]);
double* phi = mxGetPr(prhs[9]);
double* gradrefphi = mxGetPr(prhs[10]);
double* elements = mxGetPr(prhs[4]);
double Id[dim][dim];
int d1,d2;
for (d1 = 0; d1 < dim; d1 = d1 + 1 )
{
for (d2 = 0; d2 < dim; d2 = d2 + 1 )
{
Id[d1][d2] = 0;
if (d1==d2)
{
Id[d1][d2] = 1;
}
}
}
double* material_param = mxGetPr(prhs[2]);
double Young = material_param[0];
double Poisson = material_param[1];
double mu = Young / (2 + 2 * Poisson);
double lambda = Young * Poisson /( (1+Poisson) * (1-2*Poisson) );
/* Assembly: loop over the elements */
int ie;
#pragma omp parallel for shared(invjac,detjac,elements,myAcols,myArows,myAcoef,U_h) private(ie,k,l,q,d1,d2) firstprivate(phi,w,numRowsElements,nln2,nln,NumNodes,Id,mu,lambda)
for (ie = 0; ie < noe; ie = ie + 1 )
{
double GradV[dim][dim];
double GradU[dim][dim];
double GradUh[NumQuadPoints][dim][dim];
double F[NumQuadPoints][dim][dim];
double E[NumQuadPoints][dim][dim];
double traceE[NumQuadPoints];
double gradphi[NumQuadPoints][dim][nln];
for (q = 0; q < NumQuadPoints; q = q + 1 )
{
/* Compute Gradient of Basis functions*/
for (k = 0; k < nln; k = k + 1 )
{
for (d1 = 0; d1 < dim; d1 = d1 + 1 )
{
gradphi[q][d1][k] = 0;
for (d2 = 0; d2 < dim; d2 = d2 + 1 )
{
gradphi[q][d1][k] = gradphi[q][d1][k] + INVJAC(ie,d1,d2)*GRADREFPHI(k,q,d2);
}
}
}
for (d1 = 0; d1 < dim; d1 = d1 + 1 )
{
for (d2 = 0; d2 < dim; d2 = d2 + 1 )
{
GradUh[q][d1][d2] = 0;
for (k = 0; k < nln; k = k + 1 )
{
int e_k;
e_k = (int)(elements[ie*numRowsElements + k] + d1*NumNodes - 1);
GradUh[q][d1][d2] = GradUh[q][d1][d2] + U_h[e_k] * gradphi[q][d2][k];
}
F[q][d1][d2] = Id[d1][d2] + GradUh[q][d1][d2];
}
}
MatrixProductAlphaT1(dim, 1.0, F[q], F[q], E[q] );
for (d1 = 0; d1 < dim; d1 = d1 + 1 )
{
for (d2 = 0; d2 < dim; d2 = d2 + 1 )
{
E[q][d1][d2] = 0.5 * ( E[q][d1][d2] - Id[d1][d2] );
}
}
traceE[q] = Trace(dim, E[q]);
}
int iii = 0;
int ii = 0;
int a, b, i_c, j_c;
double aloc[nln][dim][nln][dim];
/* loop over test functions --> a */
for (a = 0; a < nln; a = a + 1 )
{
/* loop over test components --> i_c */
for (i_c = 0; i_c < 3; i_c = i_c + 1 )
{
/* loop over trial functions --> b */
for (b = 0; b < nln; b = b + 1 )
{
/* loop over trial components --> j_c */
for (j_c = 0; j_c < 3; j_c = j_c + 1 )
{
aloc[a][i_c][b][j_c] = 0.0;
}
}
}
}
for (q = 0; q < NumQuadPoints; q = q + 1 )
{
/* loop over test functions --> a */
for (a = 0; a < nln; a = a + 1 )
{
/* loop over trial functions --> b */
for (b = 0; b < nln; b = b + 1 )
{
aloc[a][0][b][0] += ( gradphi[q][0][a]*(gradphi[q][0][b]*(2*E[q][0][0]*mu + lambda*traceE[q]) + F[q][0][0]*(lambda*(F[q][0][0]*gradphi[q][0][b] + F[q][0][1]*gradphi[q][1][b] + F[q][0][2]*gradphi[q][2][b]) + 2*F[q][0][0]*mu*gradphi[q][0][b]) + 2*F[q][0][1]*mu*((F[q][0][0]*gradphi[q][1][b])/2.0 + (F[q][0][1]*gradphi[q][0][b])/2.0) + 2*F[q][0][2]*mu*((F[q][0][0]*gradphi[q][2][b])/2.0 + (F[q][0][2]*gradphi[q][0][b])/2.0) + 2*E[q][1][0]*mu*gradphi[q][1][b] + 2*E[q][2][0]*mu*gradphi[q][2][b]) + gradphi[q][1][a]*(gradphi[q][1][b]*(2*E[q][1][1]*mu + lambda*traceE[q]) + F[q][0][1]*(lambda*(F[q][0][0]*gradphi[q][0][b] + F[q][0][1]*gradphi[q][1][b] + F[q][0][2]*gradphi[q][2][b]) + 2*F[q][0][1]*mu*gradphi[q][1][b]) + 2*F[q][0][0]*mu*((F[q][0][0]*gradphi[q][1][b])/2.0 + (F[q][0][1]*gradphi[q][0][b])/2.0) + 2*F[q][0][2]*mu*((F[q][0][1]*gradphi[q][2][b])/2.0 + (F[q][0][2]*gradphi[q][1][b])/2.0) + 2*E[q][0][1]*mu*gradphi[q][0][b] + 2*E[q][2][1]*mu*gradphi[q][2][b]) + gradphi[q][2][a]*(gradphi[q][2][b]*(2*E[q][2][2]*mu + lambda*traceE[q]) + F[q][0][2]*(lambda*(F[q][0][0]*gradphi[q][0][b] + F[q][0][1]*gradphi[q][1][b] + F[q][0][2]*gradphi[q][2][b]) + 2*F[q][0][2]*mu*gradphi[q][2][b]) + 2*F[q][0][0]*mu*((F[q][0][0]*gradphi[q][2][b])/2.0 + (F[q][0][2]*gradphi[q][0][b])/2.0) + 2*F[q][0][1]*mu*((F[q][0][1]*gradphi[q][2][b])/2.0 + (F[q][0][2]*gradphi[q][1][b])/2.0) + 2*E[q][0][2]*mu*gradphi[q][0][b] + 2*E[q][1][2]*mu*gradphi[q][1][b]) ) * w[q];
aloc[a][0][b][1] += ( gradphi[q][0][a]*(F[q][0][0]*(lambda*(F[q][1][0]*gradphi[q][0][b] + F[q][1][1]*gradphi[q][1][b] + F[q][1][2]*gradphi[q][2][b]) + 2*F[q][1][0]*mu*gradphi[q][0][b]) + 2*F[q][0][1]*mu*((F[q][1][0]*gradphi[q][1][b])/2.0 + (F[q][1][1]*gradphi[q][0][b])/2.0) + 2*F[q][0][2]*mu*((F[q][1][0]*gradphi[q][2][b])/2.0 + (F[q][1][2]*gradphi[q][0][b])/2.0)) + gradphi[q][1][a]*(F[q][0][1]*(lambda*(F[q][1][0]*gradphi[q][0][b] + F[q][1][1]*gradphi[q][1][b] + F[q][1][2]*gradphi[q][2][b]) + 2*F[q][1][1]*mu*gradphi[q][1][b]) + 2*F[q][0][0]*mu*((F[q][1][0]*gradphi[q][1][b])/2.0 + (F[q][1][1]*gradphi[q][0][b])/2.0) + 2*F[q][0][2]*mu*((F[q][1][1]*gradphi[q][2][b])/2.0 + (F[q][1][2]*gradphi[q][1][b])/2.0)) + gradphi[q][2][a]*(F[q][0][2]*(lambda*(F[q][1][0]*gradphi[q][0][b] + F[q][1][1]*gradphi[q][1][b] + F[q][1][2]*gradphi[q][2][b]) + 2*F[q][1][2]*mu*gradphi[q][2][b]) + 2*F[q][0][0]*mu*((F[q][1][0]*gradphi[q][2][b])/2.0 + (F[q][1][2]*gradphi[q][0][b])/2.0) + 2*F[q][0][1]*mu*((F[q][1][1]*gradphi[q][2][b])/2.0 + (F[q][1][2]*gradphi[q][1][b])/2.0)) ) * w[q];
aloc[a][0][b][2] += ( gradphi[q][0][a]*(F[q][0][0]*(lambda*(F[q][2][0]*gradphi[q][0][b] + F[q][2][1]*gradphi[q][1][b] + F[q][2][2]*gradphi[q][2][b]) + 2*F[q][2][0]*mu*gradphi[q][0][b]) + 2*F[q][0][1]*mu*((F[q][2][0]*gradphi[q][1][b])/2.0 + (F[q][2][1]*gradphi[q][0][b])/2.0) + 2*F[q][0][2]*mu*((F[q][2][0]*gradphi[q][2][b])/2.0 + (F[q][2][2]*gradphi[q][0][b])/2.0)) + gradphi[q][1][a]*(F[q][0][1]*(lambda*(F[q][2][0]*gradphi[q][0][b] + F[q][2][1]*gradphi[q][1][b] + F[q][2][2]*gradphi[q][2][b]) + 2*F[q][2][1]*mu*gradphi[q][1][b]) + 2*F[q][0][0]*mu*((F[q][2][0]*gradphi[q][1][b])/2.0 + (F[q][2][1]*gradphi[q][0][b])/2.0) + 2*F[q][0][2]*mu*((F[q][2][1]*gradphi[q][2][b])/2.0 + (F[q][2][2]*gradphi[q][1][b])/2.0)) + gradphi[q][2][a]*(F[q][0][2]*(lambda*(F[q][2][0]*gradphi[q][0][b] + F[q][2][1]*gradphi[q][1][b] + F[q][2][2]*gradphi[q][2][b]) + 2*F[q][2][2]*mu*gradphi[q][2][b]) + 2*F[q][0][0]*mu*((F[q][2][0]*gradphi[q][2][b])/2.0 + (F[q][2][2]*gradphi[q][0][b])/2.0) + 2*F[q][0][1]*mu*((F[q][2][1]*gradphi[q][2][b])/2.0 + (F[q][2][2]*gradphi[q][1][b])/2.0)) ) * w[q];
aloc[a][1][b][0] += ( gradphi[q][0][a]*(F[q][1][0]*(lambda*(F[q][0][0]*gradphi[q][0][b] + F[q][0][1]*gradphi[q][1][b] + F[q][0][2]*gradphi[q][2][b]) + 2*F[q][0][0]*mu*gradphi[q][0][b]) + 2*F[q][1][1]*mu*((F[q][0][0]*gradphi[q][1][b])/2.0 + (F[q][0][1]*gradphi[q][0][b])/2.0) + 2*F[q][1][2]*mu*((F[q][0][0]*gradphi[q][2][b])/2.0 + (F[q][0][2]*gradphi[q][0][b])/2.0)) + gradphi[q][1][a]*(F[q][1][1]*(lambda*(F[q][0][0]*gradphi[q][0][b] + F[q][0][1]*gradphi[q][1][b] + F[q][0][2]*gradphi[q][2][b]) + 2*F[q][0][1]*mu*gradphi[q][1][b]) + 2*F[q][1][0]*mu*((F[q][0][0]*gradphi[q][1][b])/2.0 + (F[q][0][1]*gradphi[q][0][b])/2.0) + 2*F[q][1][2]*mu*((F[q][0][1]*gradphi[q][2][b])/2.0 + (F[q][0][2]*gradphi[q][1][b])/2.0)) + gradphi[q][2][a]*(F[q][1][2]*(lambda*(F[q][0][0]*gradphi[q][0][b] + F[q][0][1]*gradphi[q][1][b] + F[q][0][2]*gradphi[q][2][b]) + 2*F[q][0][2]*mu*gradphi[q][2][b]) + 2*F[q][1][0]*mu*((F[q][0][0]*gradphi[q][2][b])/2.0 + (F[q][0][2]*gradphi[q][0][b])/2.0) + 2*F[q][1][1]*mu*((F[q][0][1]*gradphi[q][2][b])/2.0 + (F[q][0][2]*gradphi[q][1][b])/2.0)) ) * w[q];
aloc[a][1][b][1] += ( gradphi[q][0][a]*(gradphi[q][0][b]*(2*E[q][0][0]*mu + lambda*traceE[q]) + F[q][1][0]*(lambda*(F[q][1][0]*gradphi[q][0][b] + F[q][1][1]*gradphi[q][1][b] + F[q][1][2]*gradphi[q][2][b]) + 2*F[q][1][0]*mu*gradphi[q][0][b]) + 2*F[q][1][1]*mu*((F[q][1][0]*gradphi[q][1][b])/2.0 + (F[q][1][1]*gradphi[q][0][b])/2.0) + 2*F[q][1][2]*mu*((F[q][1][0]*gradphi[q][2][b])/2.0 + (F[q][1][2]*gradphi[q][0][b])/2.0) + 2*E[q][1][0]*mu*gradphi[q][1][b] + 2*E[q][2][0]*mu*gradphi[q][2][b]) + gradphi[q][1][a]*(gradphi[q][1][b]*(2*E[q][1][1]*mu + lambda*traceE[q]) + F[q][1][1]*(lambda*(F[q][1][0]*gradphi[q][0][b] + F[q][1][1]*gradphi[q][1][b] + F[q][1][2]*gradphi[q][2][b]) + 2*F[q][1][1]*mu*gradphi[q][1][b]) + 2*F[q][1][0]*mu*((F[q][1][0]*gradphi[q][1][b])/2.0 + (F[q][1][1]*gradphi[q][0][b])/2.0) + 2*F[q][1][2]*mu*((F[q][1][1]*gradphi[q][2][b])/2.0 + (F[q][1][2]*gradphi[q][1][b])/2.0) + 2*E[q][0][1]*mu*gradphi[q][0][b] + 2*E[q][2][1]*mu*gradphi[q][2][b]) + gradphi[q][2][a]*(gradphi[q][2][b]*(2*E[q][2][2]*mu + lambda*traceE[q]) + F[q][1][2]*(lambda*(F[q][1][0]*gradphi[q][0][b] + F[q][1][1]*gradphi[q][1][b] + F[q][1][2]*gradphi[q][2][b]) + 2*F[q][1][2]*mu*gradphi[q][2][b]) + 2*F[q][1][0]*mu*((F[q][1][0]*gradphi[q][2][b])/2.0 + (F[q][1][2]*gradphi[q][0][b])/2.0) + 2*F[q][1][1]*mu*((F[q][1][1]*gradphi[q][2][b])/2.0 + (F[q][1][2]*gradphi[q][1][b])/2.0) + 2*E[q][0][2]*mu*gradphi[q][0][b] + 2*E[q][1][2]*mu*gradphi[q][1][b]) ) * w[q];
aloc[a][1][b][2] += ( gradphi[q][0][a]*(F[q][1][0]*(lambda*(F[q][2][0]*gradphi[q][0][b] + F[q][2][1]*gradphi[q][1][b] + F[q][2][2]*gradphi[q][2][b]) + 2*F[q][2][0]*mu*gradphi[q][0][b]) + 2*F[q][1][1]*mu*((F[q][2][0]*gradphi[q][1][b])/2.0 + (F[q][2][1]*gradphi[q][0][b])/2.0) + 2*F[q][1][2]*mu*((F[q][2][0]*gradphi[q][2][b])/2.0 + (F[q][2][2]*gradphi[q][0][b])/2.0)) + gradphi[q][1][a]*(F[q][1][1]*(lambda*(F[q][2][0]*gradphi[q][0][b] + F[q][2][1]*gradphi[q][1][b] + F[q][2][2]*gradphi[q][2][b]) + 2*F[q][2][1]*mu*gradphi[q][1][b]) + 2*F[q][1][0]*mu*((F[q][2][0]*gradphi[q][1][b])/2.0 + (F[q][2][1]*gradphi[q][0][b])/2.0) + 2*F[q][1][2]*mu*((F[q][2][1]*gradphi[q][2][b])/2.0 + (F[q][2][2]*gradphi[q][1][b])/2.0)) + gradphi[q][2][a]*(F[q][1][2]*(lambda*(F[q][2][0]*gradphi[q][0][b] + F[q][2][1]*gradphi[q][1][b] + F[q][2][2]*gradphi[q][2][b]) + 2*F[q][2][2]*mu*gradphi[q][2][b]) + 2*F[q][1][0]*mu*((F[q][2][0]*gradphi[q][2][b])/2.0 + (F[q][2][2]*gradphi[q][0][b])/2.0) + 2*F[q][1][1]*mu*((F[q][2][1]*gradphi[q][2][b])/2.0 + (F[q][2][2]*gradphi[q][1][b])/2.0)) ) * w[q];
aloc[a][2][b][0] += ( gradphi[q][0][a]*(F[q][2][0]*(lambda*(F[q][0][0]*gradphi[q][0][b] + F[q][0][1]*gradphi[q][1][b] + F[q][0][2]*gradphi[q][2][b]) + 2*F[q][0][0]*mu*gradphi[q][0][b]) + 2*F[q][2][1]*mu*((F[q][0][0]*gradphi[q][1][b])/2.0 + (F[q][0][1]*gradphi[q][0][b])/2.0) + 2*F[q][2][2]*mu*((F[q][0][0]*gradphi[q][2][b])/2.0 + (F[q][0][2]*gradphi[q][0][b])/2.0)) + gradphi[q][1][a]*(F[q][2][1]*(lambda*(F[q][0][0]*gradphi[q][0][b] + F[q][0][1]*gradphi[q][1][b] + F[q][0][2]*gradphi[q][2][b]) + 2*F[q][0][1]*mu*gradphi[q][1][b]) + 2*F[q][2][0]*mu*((F[q][0][0]*gradphi[q][1][b])/2.0 + (F[q][0][1]*gradphi[q][0][b])/2.0) + 2*F[q][2][2]*mu*((F[q][0][1]*gradphi[q][2][b])/2.0 + (F[q][0][2]*gradphi[q][1][b])/2.0)) + gradphi[q][2][a]*(F[q][2][2]*(lambda*(F[q][0][0]*gradphi[q][0][b] + F[q][0][1]*gradphi[q][1][b] + F[q][0][2]*gradphi[q][2][b]) + 2*F[q][0][2]*mu*gradphi[q][2][b]) + 2*F[q][2][0]*mu*((F[q][0][0]*gradphi[q][2][b])/2.0 + (F[q][0][2]*gradphi[q][0][b])/2.0) + 2*F[q][2][1]*mu*((F[q][0][1]*gradphi[q][2][b])/2.0 + (F[q][0][2]*gradphi[q][1][b])/2.0)) ) * w[q];
aloc[a][2][b][1] += ( gradphi[q][0][a]*(F[q][2][0]*(lambda*(F[q][1][0]*gradphi[q][0][b] + F[q][1][1]*gradphi[q][1][b] + F[q][1][2]*gradphi[q][2][b]) + 2*F[q][1][0]*mu*gradphi[q][0][b]) + 2*F[q][2][1]*mu*((F[q][1][0]*gradphi[q][1][b])/2.0 + (F[q][1][1]*gradphi[q][0][b])/2.0) + 2*F[q][2][2]*mu*((F[q][1][0]*gradphi[q][2][b])/2.0 + (F[q][1][2]*gradphi[q][0][b])/2.0)) + gradphi[q][1][a]*(F[q][2][1]*(lambda*(F[q][1][0]*gradphi[q][0][b] + F[q][1][1]*gradphi[q][1][b] + F[q][1][2]*gradphi[q][2][b]) + 2*F[q][1][1]*mu*gradphi[q][1][b]) + 2*F[q][2][0]*mu*((F[q][1][0]*gradphi[q][1][b])/2.0 + (F[q][1][1]*gradphi[q][0][b])/2.0) + 2*F[q][2][2]*mu*((F[q][1][1]*gradphi[q][2][b])/2.0 + (F[q][1][2]*gradphi[q][1][b])/2.0)) + gradphi[q][2][a]*(F[q][2][2]*(lambda*(F[q][1][0]*gradphi[q][0][b] + F[q][1][1]*gradphi[q][1][b] + F[q][1][2]*gradphi[q][2][b]) + 2*F[q][1][2]*mu*gradphi[q][2][b]) + 2*F[q][2][0]*mu*((F[q][1][0]*gradphi[q][2][b])/2.0 + (F[q][1][2]*gradphi[q][0][b])/2.0) + 2*F[q][2][1]*mu*((F[q][1][1]*gradphi[q][2][b])/2.0 + (F[q][1][2]*gradphi[q][1][b])/2.0)) ) * w[q];
aloc[a][2][b][2] += ( gradphi[q][0][a]*(gradphi[q][0][b]*(2*E[q][0][0]*mu + lambda*traceE[q]) + F[q][2][0]*(lambda*(F[q][2][0]*gradphi[q][0][b] + F[q][2][1]*gradphi[q][1][b] + F[q][2][2]*gradphi[q][2][b]) + 2*F[q][2][0]*mu*gradphi[q][0][b]) + 2*F[q][2][1]*mu*((F[q][2][0]*gradphi[q][1][b])/2.0 + (F[q][2][1]*gradphi[q][0][b])/2.0) + 2*F[q][2][2]*mu*((F[q][2][0]*gradphi[q][2][b])/2.0 + (F[q][2][2]*gradphi[q][0][b])/2.0) + 2*E[q][1][0]*mu*gradphi[q][1][b] + 2*E[q][2][0]*mu*gradphi[q][2][b]) + gradphi[q][1][a]*(gradphi[q][1][b]*(2*E[q][1][1]*mu + lambda*traceE[q]) + F[q][2][1]*(lambda*(F[q][2][0]*gradphi[q][0][b] + F[q][2][1]*gradphi[q][1][b] + F[q][2][2]*gradphi[q][2][b]) + 2*F[q][2][1]*mu*gradphi[q][1][b]) + 2*F[q][2][0]*mu*((F[q][2][0]*gradphi[q][1][b])/2.0 + (F[q][2][1]*gradphi[q][0][b])/2.0) + 2*F[q][2][2]*mu*((F[q][2][1]*gradphi[q][2][b])/2.0 + (F[q][2][2]*gradphi[q][1][b])/2.0) + 2*E[q][0][1]*mu*gradphi[q][0][b] + 2*E[q][2][1]*mu*gradphi[q][2][b]) + gradphi[q][2][a]*(gradphi[q][2][b]*(2*E[q][2][2]*mu + lambda*traceE[q]) + F[q][2][2]*(lambda*(F[q][2][0]*gradphi[q][0][b] + F[q][2][1]*gradphi[q][1][b] + F[q][2][2]*gradphi[q][2][b]) + 2*F[q][2][2]*mu*gradphi[q][2][b]) + 2*F[q][2][0]*mu*((F[q][2][0]*gradphi[q][2][b])/2.0 + (F[q][2][2]*gradphi[q][0][b])/2.0) + 2*F[q][2][1]*mu*((F[q][2][1]*gradphi[q][2][b])/2.0 + (F[q][2][2]*gradphi[q][1][b])/2.0) + 2*E[q][0][2]*mu*gradphi[q][0][b] + 2*E[q][1][2]*mu*gradphi[q][1][b]) ) * w[q];
}
}
}
for (a = 0; a < nln; a = a + 1 )
{
/* loop over test components --> i_c */
for (i_c = 0; i_c < 3; i_c = i_c + 1 )
{
/* loop over trial functions --> b */
for (b = 0; b < nln; b = b + 1 )
{
/* loop over trial components --> j_c */
for (j_c = 0; j_c < 3; j_c = j_c + 1 )
{
myArows[ie*nln2*9+iii] = elements[a+ie*numRowsElements] + i_c * NumNodes;
myAcols[ie*nln2*9+iii] = elements[b+ie*numRowsElements] + j_c * NumNodes;
myAcoef[ie*nln2*9+iii] = aloc[a][i_c][b][j_c]*detjac[ie];
iii = iii + 1;
}
}
}
}
}
}
/*************************************************************************/
void StVenantKirchhoffMaterial_jacobianFast2D(mxArray* plhs[], const mxArray* prhs[])
{
double* dim_ptr = mxGetPr(prhs[0]);
int dim = (int)(dim_ptr[0]);
int noe = mxGetN(prhs[4]);
double* nln_ptr = mxGetPr(prhs[5]);
int nln = (int)(nln_ptr[0]);
int numRowsElements = mxGetM(prhs[4]);
int nln2 = nln*nln;
plhs[0] = mxCreateDoubleMatrix(nln2*noe*dim*dim,1, mxREAL);
plhs[1] = mxCreateDoubleMatrix(nln2*noe*dim*dim,1, mxREAL);
plhs[2] = mxCreateDoubleMatrix(nln2*noe*dim*dim,1, mxREAL);
double* myArows = mxGetPr(plhs[0]);
double* myAcols = mxGetPr(plhs[1]);
double* myAcoef = mxGetPr(plhs[2]);
int k,l;
int q;
int NumQuadPoints = mxGetN(prhs[6]);
int NumNodes = (int)(mxGetM(prhs[3]) / dim);
double* U_h = mxGetPr(prhs[3]);
double* w = mxGetPr(prhs[6]);
double* invjac = mxGetPr(prhs[7]);
double* detjac = mxGetPr(prhs[8]);
double* phi = mxGetPr(prhs[9]);
double* gradrefphi = mxGetPr(prhs[10]);
double* elements = mxGetPr(prhs[4]);
double Id[dim][dim];
int d1,d2;
for (d1 = 0; d1 < dim; d1 = d1 + 1 )
{
for (d2 = 0; d2 < dim; d2 = d2 + 1 )
{
Id[d1][d2] = 0;
if (d1==d2)
{
Id[d1][d2] = 1;
}
}
}
double* material_param = mxGetPr(prhs[2]);
double Young = material_param[0];
double Poisson = material_param[1];
double mu = Young / (2 + 2 * Poisson);
double lambda = Young * Poisson /( (1+Poisson) * (1-2*Poisson) );
/* Assembly: loop over the elements */
int ie;
#pragma omp parallel for shared(invjac,detjac,elements,myAcols,myArows,myAcoef,U_h) private(ie,k,l,q,d1,d2) firstprivate(phi,w,numRowsElements,nln2,nln,NumNodes,Id,mu,lambda)
for (ie = 0; ie < noe; ie = ie + 1 )
{
double GradV[dim][dim];
double GradU[dim][dim];
double GradUh[NumQuadPoints][dim][dim];
double F[NumQuadPoints][dim][dim];
double E[NumQuadPoints][dim][dim];
double traceE[NumQuadPoints];
double gradphi[NumQuadPoints][dim][nln];
for (q = 0; q < NumQuadPoints; q = q + 1 )
{
/* Compute Gradient of Basis functions*/
for (k = 0; k < nln; k = k + 1 )
{
for (d1 = 0; d1 < dim; d1 = d1 + 1 )
{
gradphi[q][d1][k] = 0;
for (d2 = 0; d2 < dim; d2 = d2 + 1 )
{
gradphi[q][d1][k] = gradphi[q][d1][k] + INVJAC(ie,d1,d2)*GRADREFPHI(k,q,d2);
}
}
}
for (d1 = 0; d1 < dim; d1 = d1 + 1 )
{
for (d2 = 0; d2 < dim; d2 = d2 + 1 )
{
GradUh[q][d1][d2] = 0;
for (k = 0; k < nln; k = k + 1 )
{
int e_k;
e_k = (int)(elements[ie*numRowsElements + k] + d1*NumNodes - 1);
GradUh[q][d1][d2] = GradUh[q][d1][d2] + U_h[e_k] * gradphi[q][d2][k];
}
F[q][d1][d2] = Id[d1][d2] + GradUh[q][d1][d2];
}
}
MatrixProductAlphaT1(dim, 1.0, F[q], F[q], E[q] );
for (d1 = 0; d1 < dim; d1 = d1 + 1 )
{
for (d2 = 0; d2 < dim; d2 = d2 + 1 )
{
E[q][d1][d2] = 0.5 * ( E[q][d1][d2] - Id[d1][d2] );
}
}
traceE[q] = Trace(dim, E[q]);
}
int iii = 0;
int ii = 0;
int a, b, i_c, j_c;
double aloc[nln][dim][nln][dim];
/* loop over test functions --> a */
for (a = 0; a < nln; a = a + 1 )
{
/* loop over test components --> i_c */
for (i_c = 0; i_c < 2; i_c = i_c + 1 )
{
/* loop over trial functions --> b */
for (b = 0; b < nln; b = b + 1 )
{
/* loop over trial components --> j_c */
for (j_c = 0; j_c < 2; j_c = j_c + 1 )
{
aloc[a][i_c][b][j_c] = 0.0;
}
}
}
}
for (q = 0; q < NumQuadPoints; q = q + 1 )
{
/* loop over test functions --> a */
for (a = 0; a < nln; a = a + 1 )
{
/* loop over trial functions --> b */
for (b = 0; b < nln; b = b + 1 )
{
aloc[a][0][b][0] += ( gradphi[q][0][a]*(F[q][0][0]*(lambda*(F[q][0][0]*gradphi[q][0][b] + F[q][0][1]*gradphi[q][1][b]) + 2.0*F[q][0][0]*mu*gradphi[q][0][b]) + gradphi[q][0][b]*(2.0*E[q][0][0]*mu + lambda*traceE[q]) + 2.0*F[q][0][1]*mu*((F[q][0][0]*gradphi[q][1][b])/2.0 + (F[q][0][1]*gradphi[q][0][b])/2.0) + 2.0*E[q][1][0]*mu*gradphi[q][1][b]) + gradphi[q][1][a]*(F[q][0][1]*(lambda*(F[q][0][0]*gradphi[q][0][b] + F[q][0][1]*gradphi[q][1][b]) + 2.0*F[q][0][1]*mu*gradphi[q][1][b]) + gradphi[q][1][b]*(2.0*E[q][1][1]*mu + lambda*traceE[q]) + 2.0*F[q][0][0]*mu*((F[q][0][0]*gradphi[q][1][b])/2.0 + (F[q][0][1]*gradphi[q][0][b])/2.0) + 2.0*E[q][0][1]*mu*gradphi[q][0][b]) ) * w[q];
aloc[a][0][b][1] += ( gradphi[q][0][a]*(F[q][0][0]*(lambda*(F[q][1][0]*gradphi[q][0][b] + F[q][1][1]*gradphi[q][1][b]) + 2.0*F[q][1][0]*mu*gradphi[q][0][b]) + 2.0*F[q][0][1]*mu*((F[q][1][0]*gradphi[q][1][b])/2.0 + (F[q][1][1]*gradphi[q][0][b])/2.0)) + gradphi[q][1][a]*(F[q][0][1]*(lambda*(F[q][1][0]*gradphi[q][0][b] + F[q][1][1]*gradphi[q][1][b]) + 2.0*F[q][1][1]*mu*gradphi[q][1][b]) + 2.0*F[q][0][0]*mu*((F[q][1][0]*gradphi[q][1][b])/2.0 + (F[q][1][1]*gradphi[q][0][b])/2.0)) ) * w[q];
aloc[a][1][b][0] += ( gradphi[q][0][a]*(F[q][1][0]*(lambda*(F[q][0][0]*gradphi[q][0][b] + F[q][0][1]*gradphi[q][1][b]) + 2.0*F[q][0][0]*mu*gradphi[q][0][b]) + 2.0*F[q][1][1]*mu*((F[q][0][0]*gradphi[q][1][b])/2.0 + (F[q][0][1]*gradphi[q][0][b])/2.0)) + gradphi[q][1][a]*(F[q][1][1]*(lambda*(F[q][0][0]*gradphi[q][0][b] + F[q][0][1]*gradphi[q][1][b]) + 2.0*F[q][0][1]*mu*gradphi[q][1][b]) + 2.0*F[q][1][0]*mu*((F[q][0][0]*gradphi[q][1][b])/2.0 + (F[q][0][1]*gradphi[q][0][b])/2.0)) ) * w[q];
aloc[a][1][b][1] += ( gradphi[q][0][a]*(F[q][1][0]*(lambda*(F[q][1][0]*gradphi[q][0][b] + F[q][1][1]*gradphi[q][1][b]) + 2.0*F[q][1][0]*mu*gradphi[q][0][b]) + gradphi[q][0][b]*(2.0*E[q][0][0]*mu + lambda*traceE[q]) + 2.0*F[q][1][1]*mu*((F[q][1][0]*gradphi[q][1][b])/2.0 + (F[q][1][1]*gradphi[q][0][b])/2.0) + 2.0*E[q][1][0]*mu*gradphi[q][1][b]) + gradphi[q][1][a]*(F[q][1][1]*(lambda*(F[q][1][0]*gradphi[q][0][b] + F[q][1][1]*gradphi[q][1][b]) + 2.0*F[q][1][1]*mu*gradphi[q][1][b]) + gradphi[q][1][b]*(2.0*E[q][1][1]*mu + lambda*traceE[q]) + 2.0*F[q][1][0]*mu*((F[q][1][0]*gradphi[q][1][b])/2.0 + (F[q][1][1]*gradphi[q][0][b])/2.0) + 2.0*E[q][0][1]*mu*gradphi[q][0][b]) ) * w[q];
}
}
}
for (a = 0; a < nln; a = a + 1 )
{
/* loop over test components --> i_c */
for (i_c = 0; i_c < 2; i_c = i_c + 1 )
{
/* loop over trial functions --> b */
for (b = 0; b < nln; b = b + 1 )
{
/* loop over trial components --> j_c */
for (j_c = 0; j_c < 2; j_c = j_c + 1 )
{
myArows[ie*nln2*4+iii] = elements[a+ie*numRowsElements] + i_c * NumNodes;
myAcols[ie*nln2*4+iii] = elements[b+ie*numRowsElements] + j_c * NumNodes;
myAcoef[ie*nln2*4+iii] = aloc[a][i_c][b][j_c]*detjac[ie];
iii = iii + 1;
}
}
}
}
}
}
/*************************************************************************/
void StVenantKirchhoffMaterial_stress(mxArray* plhs[], const mxArray* prhs[])
{
double* dim_ptr = mxGetPr(prhs[0]);
int dim = (int)(dim_ptr[0]);
int noe = mxGetN(prhs[4]);
double* nln_ptr = mxGetPr(prhs[5]);
int nln = (int)(nln_ptr[0]);
int numRowsElements = mxGetM(prhs[4]);
int nln2 = nln*nln;
plhs[0] = mxCreateDoubleMatrix(noe,dim*dim, mxREAL);
plhs[1] = mxCreateDoubleMatrix(noe,dim*dim, mxREAL);
double* P = mxGetPr(plhs[0]);
double* Sigma = mxGetPr(plhs[1]);
int k,l;
int q;
int NumQuadPoints = mxGetN(prhs[6]);
int NumNodes = (int)(mxGetM(prhs[3]) / dim);
double* U_h = mxGetPr(prhs[3]);
double* w = mxGetPr(prhs[6]);
double* invjac = mxGetPr(prhs[7]);
double* detjac = mxGetPr(prhs[8]);
double* phi = mxGetPr(prhs[9]);
double* gradrefphi = mxGetPr(prhs[10]);
double gradphi[dim][nln][NumQuadPoints];
double* elements = mxGetPr(prhs[4]);
double GradUh[dim][dim][NumQuadPoints];
double Id[dim][dim];
int d1,d2;
for (d1 = 0; d1 < dim; d1 = d1 + 1 )
{
for (d2 = 0; d2 < dim; d2 = d2 + 1 )
{
Id[d1][d2] = 0;
if (d1==d2)
{
Id[d1][d2] = 1;
}
}
}
double F[dim][dim][NumQuadPoints];
double E[dim][dim][NumQuadPoints];
double P_Uh[dim][dim];
double* material_param = mxGetPr(prhs[2]);
double Young = material_param[0];
double Poisson = material_param[1];
double mu = Young / (2 + 2 * Poisson);
double lambda = Young * Poisson /( (1+Poisson) * (1-2*Poisson) );
/* Assembly: loop over the elements */
int ie;
#pragma omp parallel for shared(invjac,detjac,elements,Sigma,U_h) private(gradphi,F,E,P_Uh,GradUh,ie,k,l,q,d1,d2) firstprivate(phi,gradrefphi,w,numRowsElements,nln2,nln,NumNodes,Id,mu,lambda)
for (ie = 0; ie < noe; ie = ie + 1 )
{
double F2[dim][dim];
double traceE[NumQuadPoints];
q = 0;
/* Compute Gradient of Basis functions*/
for (k = 0; k < nln; k = k + 1 )
{
for (d1 = 0; d1 < dim; d1 = d1 + 1 )
{
gradphi[d1][k][q] = 0;
for (d2 = 0; d2 < dim; d2 = d2 + 1 )
{
gradphi[d1][k][q] = gradphi[d1][k][q] + INVJAC(ie,d1,d2)*GRADREFPHI(k,q,d2);
}
}
}
for (d1 = 0; d1 < dim; d1 = d1 + 1 )
{
for (d2 = 0; d2 < dim; d2 = d2 + 1 )
{
GradUh[d1][d2][q] = 0;
for (k = 0; k < nln; k = k + 1 )
{
int e_k;
e_k = (int)(elements[ie*numRowsElements + k] + d1*NumNodes - 1);
GradUh[d1][d2][q] = GradUh[d1][d2][q] + U_h[e_k] * gradphi[d2][k][q];
}
F[d1][d2][q] = Id[d1][d2] + GradUh[d1][d2][q];
F2[d1][d2] = Id[d1][d2] + GradUh[d1][d2][q];
}
}
compute_GreenStrainTensor(dim, NumQuadPoints, F, Id, E, q );
traceE[q] = TraceQ(dim, NumQuadPoints, E, q);
double detF = MatrixDeterminant(dim, F2);
double P1[dim][dim];
for (d1 = 0; d1 < dim; d1 = d1 + 1 )
{
for (d2 = 0; d2 < dim; d2 = d2 + 1 )
{
P1[d1][d2] = ( 2 * mu * E[d1][d2][q] + lambda * traceE[q] * Id[d1][d2] );
}
}
MatrixProductQ1(dim, NumQuadPoints, F, P1, P_Uh, q);
for (d1 = 0; d1 < dim; d1 = d1 + 1 )
{
for (d2 = 0; d2 < dim; d2 = d2 + 1 )
{
P[ie+(d1+d2*dim)*noe] = P_Uh[d1][d2] ;
}
}
double Sigma_tmp[dim][dim];
/* Sigma = 1 / det(F) * P * F^T */
MatrixProductAlphaT2(dim, 1.0 / detF, P_Uh, F2, Sigma_tmp );
for (d1 = 0; d1 < dim; d1 = d1 + 1 )
{
for (d2 = 0; d2 < dim; d2 = d2 + 1 )
{
Sigma[ie+(d1+d2*dim)*noe] = Sigma_tmp[d1][d2] ;
}
}
}
}
/*************************************************************************/
|
divsufsort.c
|
/*
* divsufsort.c for libdivsufsort
* Copyright (c) 2003-2008 Yuta Mori All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
#include "../include/divsufsort_private.h"
#ifdef _OPENMP
# include <omp.h>
#endif
/*- Private Functions -*/
/* Sorts suffixes of type B*. */
static
saidx_t
sort_typeBstar(const sauchar_t *T, saidx_t *SA,
saidx_t *bucket_A, saidx_t *bucket_B,
saidx_t n) {
saidx_t *PAb, *ISAb, *buf;
#ifdef _OPENMP
saidx_t *curbuf;
saidx_t l;
#endif
saidx_t i, j, k, t, m, bufsize;
saint_t c0, c1;
#ifdef _OPENMP
saint_t d0, d1;
int tmp;
#endif
/* Initialize bucket arrays. */
for(i = 0; i < BUCKET_A_SIZE; ++i) { bucket_A[i] = 0; }
for(i = 0; i < BUCKET_B_SIZE; ++i) { bucket_B[i] = 0; }
/* Count the number of occurrences of the first one or two characters of each
type A, B and B* suffix. Moreover, store the beginning position of all
type B* suffixes into the array SA. */
for(i = n - 1, m = n, c0 = T[n - 1]; 0 <= i;) {
/* type A suffix. */
do { ++BUCKET_A(c1 = c0); } while((0 <= --i) && ((c0 = T[i]) >= c1));
if(0 <= i) {
/* type B* suffix. */
++BUCKET_BSTAR(c0, c1);
SA[--m] = i;
/* type B suffix. */
for(--i, c1 = c0; (0 <= i) && ((c0 = T[i]) <= c1); --i, c1 = c0) {
++BUCKET_B(c0, c1);
}
}
}
m = n - m;
/*
note:
A type B* suffix is lexicographically smaller than a type B suffix that
begins with the same first two characters.
*/
/* Calculate the index of start/end point of each bucket. */
for(c0 = 0, i = 0, j = 0; c0 < ALPHABET_SIZE; ++c0) {
t = i + BUCKET_A(c0);
BUCKET_A(c0) = i + j; /* start point */
i = t + BUCKET_B(c0, c0);
for(c1 = c0 + 1; c1 < ALPHABET_SIZE; ++c1) {
j += BUCKET_BSTAR(c0, c1);
BUCKET_BSTAR(c0, c1) = j; /* end point */
i += BUCKET_B(c0, c1);
}
}
if(0 < m) {
/* Sort the type B* suffixes by their first two characters. */
PAb = SA + n - m; ISAb = SA + m;
for(i = m - 2; 0 <= i; --i) {
t = PAb[i], c0 = T[t], c1 = T[t + 1];
SA[--BUCKET_BSTAR(c0, c1)] = i;
}
t = PAb[m - 1], c0 = T[t], c1 = T[t + 1];
SA[--BUCKET_BSTAR(c0, c1)] = m - 1;
/* Sort the type B* substrings using sssort. */
#ifdef _OPENMP
tmp = omp_get_max_threads();
buf = SA + m, bufsize = (n - (2 * m)) / tmp;
c0 = ALPHABET_SIZE - 2, c1 = ALPHABET_SIZE - 1, j = m;
#pragma omp parallel default(shared) private(curbuf, k, l, d0, d1, tmp)
{
tmp = omp_get_thread_num();
curbuf = buf + tmp * bufsize;
k = 0;
for(;;) {
#pragma omp critical(sssort_lock)
{
if(0 < (l = j)) {
d0 = c0, d1 = c1;
do {
k = BUCKET_BSTAR(d0, d1);
if(--d1 <= d0) {
d1 = ALPHABET_SIZE - 1;
if(--d0 < 0) { break; }
}
} while(((l - k) <= 1) && (0 < (l = k)));
c0 = d0, c1 = d1, j = k;
}
}
if(l == 0) { break; }
sssort(T, PAb, SA + k, SA + l,
curbuf, bufsize, 2, n, *(SA + k) == (m - 1));
}
}
#else
buf = SA + m, bufsize = n - (2 * m);
for(c0 = ALPHABET_SIZE - 2, j = m; 0 < j; --c0) {
for(c1 = ALPHABET_SIZE - 1; c0 < c1; j = i, --c1) {
i = BUCKET_BSTAR(c0, c1);
if(1 < (j - i)) {
sssort(T, PAb, SA + i, SA + j,
buf, bufsize, 2, n, *(SA + i) == (m - 1));
}
}
}
#endif
/* Compute ranks of type B* substrings. */
for(i = m - 1; 0 <= i; --i) {
if(0 <= SA[i]) {
j = i;
do { ISAb[SA[i]] = i; } while((0 <= --i) && (0 <= SA[i]));
SA[i + 1] = i - j;
if(i <= 0) { break; }
}
j = i;
do { ISAb[SA[i] = ~SA[i]] = j; } while(SA[--i] < 0);
ISAb[SA[i]] = j;
}
/* Construct the inverse suffix array of type B* suffixes using trsort. */
trsort(ISAb, SA, m, 1);
/* Set the sorted order of tyoe B* suffixes. */
for(i = n - 1, j = m, c0 = T[n - 1]; 0 <= i;) {
for(--i, c1 = c0; (0 <= i) && ((c0 = T[i]) >= c1); --i, c1 = c0) { }
if(0 <= i) {
t = i;
for(--i, c1 = c0; (0 <= i) && ((c0 = T[i]) <= c1); --i, c1 = c0) { }
SA[ISAb[--j]] = ((t == 0) || (1 < (t - i))) ? t : ~t;
}
}
/* Calculate the index of start/end point of each bucket. */
BUCKET_B(ALPHABET_SIZE - 1, ALPHABET_SIZE - 1) = n; /* end point */
for(c0 = ALPHABET_SIZE - 2, k = m - 1; 0 <= c0; --c0) {
i = BUCKET_A(c0 + 1) - 1;
for(c1 = ALPHABET_SIZE - 1; c0 < c1; --c1) {
t = i - BUCKET_B(c0, c1);
BUCKET_B(c0, c1) = i; /* end point */
/* Move all type B* suffixes to the correct position. */
for(i = t, j = BUCKET_BSTAR(c0, c1);
j <= k;
--i, --k) { SA[i] = SA[k]; }
}
BUCKET_BSTAR(c0, c0 + 1) = i - BUCKET_B(c0, c0) + 1; /* start point */
BUCKET_B(c0, c0) = i; /* end point */
}
}
return m;
}
/* Constructs the suffix array by using the sorted order of type B* suffixes. */
static
void
construct_SA(const sauchar_t *T, saidx_t *SA,
saidx_t *bucket_A, saidx_t *bucket_B,
saidx_t n, saidx_t m) {
saidx_t *i, *j, *k;
saidx_t s;
saint_t c0, c1, c2;
if(0 < m) {
/* Construct the sorted order of type B suffixes by using
the sorted order of type B* suffixes. */
for(c1 = ALPHABET_SIZE - 2; 0 <= c1; --c1) {
/* Scan the suffix array from right to left. */
for(i = SA + BUCKET_BSTAR(c1, c1 + 1),
j = SA + BUCKET_A(c1 + 1) - 1, k = NULL, c2 = -1;
i <= j;
--j) {
if(0 < (s = *j)) {
assert(T[s] == c1);
assert(((s + 1) < n) && (T[s] <= T[s + 1]));
assert(T[s - 1] <= T[s]);
*j = ~s;
c0 = T[--s];
if((0 < s) && (T[s - 1] > c0)) { s = ~s; }
if(c0 != c2) {
if(0 <= c2) { BUCKET_B(c2, c1) = k - SA; }
k = SA + BUCKET_B(c2 = c0, c1);
}
assert(k < j);
*k-- = s;
} else {
assert(((s == 0) && (T[s] == c1)) || (s < 0));
*j = ~s;
}
}
}
}
/* Construct the suffix array by using
the sorted order of type B suffixes. */
k = SA + BUCKET_A(c2 = T[n - 1]);
*k++ = (T[n - 2] < c2) ? ~(n - 1) : (n - 1);
/* Scan the suffix array from left to right. */
for(i = SA, j = SA + n; i < j; ++i) {
if(0 < (s = *i)) {
assert(T[s - 1] >= T[s]);
c0 = T[--s];
if((s == 0) || (T[s - 1] < c0)) { s = ~s; }
if(c0 != c2) {
BUCKET_A(c2) = k - SA;
k = SA + BUCKET_A(c2 = c0);
}
assert(i < k);
*k++ = s;
} else {
assert(s < 0);
*i = ~s;
}
}
}
#if 0
/* Constructs the burrows-wheeler transformed string directly
by using the sorted order of type B* suffixes. */
static
saidx_t
construct_BWT(const sauchar_t *T, saidx_t *SA,
saidx_t *bucket_A, saidx_t *bucket_B,
saidx_t n, saidx_t m) {
saidx_t *i, *j, *k, *orig;
saidx_t s;
saint_t c0, c1, c2;
if(0 < m) {
/* Construct the sorted order of type B suffixes by using
the sorted order of type B* suffixes. */
for(c1 = ALPHABET_SIZE - 2; 0 <= c1; --c1) {
/* Scan the suffix array from right to left. */
for(i = SA + BUCKET_BSTAR(c1, c1 + 1),
j = SA + BUCKET_A(c1 + 1) - 1, k = NULL, c2 = -1;
i <= j;
--j) {
if(0 < (s = *j)) {
assert(T[s] == c1);
assert(((s + 1) < n) && (T[s] <= T[s + 1]));
assert(T[s - 1] <= T[s]);
c0 = T[--s];
*j = ~((saidx_t)c0);
if((0 < s) && (T[s - 1] > c0)) { s = ~s; }
if(c0 != c2) {
if(0 <= c2) { BUCKET_B(c2, c1) = k - SA; }
k = SA + BUCKET_B(c2 = c0, c1);
}
assert(k < j);
*k-- = s;
} else if(s != 0) {
*j = ~s;
#ifndef NDEBUG
} else {
assert(T[s] == c1);
#endif
}
}
}
}
/* Construct the BWTed string by using
the sorted order of type B suffixes. */
k = SA + BUCKET_A(c2 = T[n - 1]);
*k++ = (T[n - 2] < c2) ? ~((saidx_t)T[n - 2]) : (n - 1);
/* Scan the suffix array from left to right. */
for(i = SA, j = SA + n, orig = SA; i < j; ++i) {
if(0 < (s = *i)) {
assert(T[s - 1] >= T[s]);
c0 = T[--s];
*i = c0;
if((0 < s) && (T[s - 1] < c0)) { s = ~((saidx_t)T[s - 1]); }
if(c0 != c2) {
BUCKET_A(c2) = k - SA;
k = SA + BUCKET_A(c2 = c0);
}
assert(i < k);
*k++ = s;
} else if(s != 0) {
*i = ~s;
} else {
orig = i;
}
}
return orig - SA;
}
#endif
/*---------------------------------------------------------------------------*/
/**
* Initialize suffix array context
*
* @param ctx suffix array context
* @param zalloc memory allocator
* @param zfree memory deallocator
* @param opaque object passed to memory functions
*
* @return 0 for success, or non-zero in case of an error
*/
int divsufsort_init(divsufsort_ctx_t *ctx, void* (*zalloc)(void *opaque, unsigned int items, unsigned int size), void(*zfree)(void *opaque, void *address), void *opaque) {
ctx->bucket_A = (saidx_t *)zalloc(opaque, BUCKET_A_SIZE, sizeof(saidx_t));
ctx->bucket_B = NULL;
if (ctx->bucket_A) {
ctx->bucket_B = (saidx_t *)zalloc(opaque, BUCKET_B_SIZE, sizeof(saidx_t));
if (ctx->bucket_B)
return 0;
}
divsufsort_destroy(ctx, zfree, opaque);
return -1;
}
/**
* Destroy suffix array context
*
* @param ctx suffix array context to destroy
* @param zfree memory deallocator
* @param opaque object passed to memory functions
*/
void divsufsort_destroy(divsufsort_ctx_t *ctx, void(*zfree)(void *opaque, void *address), void *opaque) {
if (ctx->bucket_B) {
zfree(opaque, ctx->bucket_B);
ctx->bucket_B = NULL;
}
if (ctx->bucket_A) {
zfree(opaque, ctx->bucket_A);
ctx->bucket_A = NULL;
}
}
/*- Function -*/
saint_t
divsufsort_build_array(divsufsort_ctx_t *ctx, const sauchar_t *T, saidx_t *SA, saidx_t n) {
saidx_t m;
saint_t err = 0;
/* Check arguments. */
if((T == NULL) || (SA == NULL) || (n < 0)) { return -1; }
else if(n == 0) { return 0; }
else if(n == 1) { SA[0] = 0; return 0; }
else if(n == 2) { m = (T[0] < T[1]); SA[m ^ 1] = 0, SA[m] = 1; return 0; }
/* Suffixsort. */
if((ctx->bucket_A != NULL) && (ctx->bucket_B != NULL)) {
m = sort_typeBstar(T, SA, ctx->bucket_A, ctx->bucket_B, n);
construct_SA(T, SA, ctx->bucket_A, ctx->bucket_B, n, m);
} else {
err = -2;
}
return err;
}
#if 0
saidx_t
divbwt(const sauchar_t *T, sauchar_t *U, saidx_t *A, saidx_t n) {
saidx_t *B;
saidx_t *bucket_A, *bucket_B;
saidx_t m, pidx, i;
/* Check arguments. */
if((T == NULL) || (U == NULL) || (n < 0)) { return -1; }
else if(n <= 1) { if(n == 1) { U[0] = T[0]; } return n; }
if((B = A) == NULL) { B = (saidx_t *)malloc((size_t)(n + 1) * sizeof(saidx_t)); }
bucket_A = (saidx_t *)malloc(BUCKET_A_SIZE * sizeof(saidx_t));
bucket_B = (saidx_t *)malloc(BUCKET_B_SIZE * sizeof(saidx_t));
/* Burrows-Wheeler Transform. */
if((B != NULL) && (bucket_A != NULL) && (bucket_B != NULL)) {
m = sort_typeBstar(T, B, bucket_A, bucket_B, n);
pidx = construct_BWT(T, B, bucket_A, bucket_B, n, m);
/* Copy to output string. */
U[0] = T[n - 1];
for(i = 0; i < pidx; ++i) { U[i + 1] = (sauchar_t)B[i]; }
for(i += 1; i < n; ++i) { U[i] = (sauchar_t)B[i]; }
pidx += 1;
} else {
pidx = -2;
}
free(bucket_B);
free(bucket_A);
if(A == NULL) { free(B); }
return pidx;
}
const char *
divsufsort_version(void) {
return PROJECT_VERSION_FULL;
}
#endif
|
ssh_fmt_plug.c
|
/* "SSH private key cracker" patch for JtR. Hacked together during
* April of 2011 by Dhiru Kholia <dhiru.kholia at gmail.com> for GSoC.
*
* This software is Copyright (c) 2011, Dhiru Kholia <dhiru.kholia at gmail.com>,
* and it is hereby released to the general public under the following terms:
* Redistribution and use in source and binary forms, with or without modification,
* are permitted.
*
* This patch is inspired by the ssh-privkey-crack program.
* http://neophob.com/2007/10/ssh-private-key-cracker/
*
* PEM_read_bio_PrivateKey and related OpenSSL functions are too high
* level for brute-forcing purposes. So we drill down and find suitable
* low-level OpenSSL functions. */
#if FMT_EXTERNS_H
extern struct fmt_main fmt_ssh;
#elif FMT_REGISTERS_H
john_register_one(&fmt_ssh);
#else
#include <openssl/opensslv.h>
#include <openssl/crypto.h>
#include <openssl/ssl.h>
#include <openssl/bio.h>
#include <openssl/evp.h>
#include <openssl/pem.h>
#include <openssl/err.h>
#undef MEM_FREE
#include "options.h"
#ifdef _OPENMP
#include <omp.h>
#define OMP_SCALE 64
#endif
#include <string.h>
#include "arch.h"
#include "common.h"
#include "formats.h"
#include "params.h"
#include "misc.h"
#include "memdbg.h"
#define FORMAT_LABEL "SSH"
#define FORMAT_NAME ""
#define ALGORITHM_NAME "RSA/DSA 32/" ARCH_BITS_STR
#define BENCHMARK_COMMENT " (one 2048-bit RSA and one 1024-bit DSA key)"
#define BENCHMARK_LENGTH -1001
#define PLAINTEXT_LENGTH 32
#define BINARY_SIZE 0
#define SALT_SIZE sizeof(struct custom_salt)
#define BINARY_ALIGN 1
#define SALT_ALIGN sizeof(long)
#define MIN_KEYS_PER_CRYPT 1
#define MAX_KEYS_PER_CRYPT 1
static char (*saved_key)[PLAINTEXT_LENGTH + 1];
static int any_cracked, *cracked;
static size_t cracked_size;
static struct custom_salt {
long len;
char data[4096];
EVP_CIPHER_INFO cipher;
EVP_PKEY pk;
} *restored_custom_salt;
static struct fmt_tests ssh_tests[] = {
{"$ssh2$2d2d2d2d2d424547494e205253412050524956415445204b45592d2d2d2d2d0a50726f632d547970653a20342c454e435259505445440a44454b2d496e666f3a204445532d454445332d4342432c464446343843343633303936433641360a0a2f4f6548434273304156786472773771564d646e2b68624a524f4f7454446f3376503371436678426c534b54627547676d4d39726b387866756b4f394b706a560a4a513136676a4a35366976375558393345486e466873454264706371395441544e3574733741655973374d73687961346532496f78616c634a377053427362670a5a2f69344f67327954317477586c4f655464716f413354444f68382b5750496d47426133785a412b4e334a4947354e306e526b6757466263354a554a46767a6f0a766c2f3545437466324143455a37744b39325a56556e59464f6c2b6a59525a665a456f664f38725169496f3236594668547a6c694258384b6b566777575756440a344a31797563427576675365583046574b566f6554306f574232353379316e686a386a6150784262663930664b5a666e394945764438482f4a4c4e4c38736a790a53787965557a356d714372695a44786254796d6153697348704b61464d2f63627743625a2f764954384a486a69555657543531715871484e61522f63617764610a647a6b7a6e4d516b57475645377947613476484c56417166764c77362b4e56475950474170614a5668414a5132423235356362526e454e496c356466544437760a717348684b6a78387a2b43453976326270754c516e7179746e6c654638414f2b764d39426e4667306d4e5169585a75584a54305833425152706b4845724a435a0a4f4f736f6e6c6c6a32684f46764b3479504468694c453672394b386a6a44766b58554339375755663742303751536362576871386b64566c43355532493341680a6e50515035354d66452f52535a544837306159562b64647278526f62543768506a44306332394e7666313745314e793437776c696b567072742f352b516c36310a67336e52454c786662664c67517451434673566c4b454f6c32356a57786c6c526759522f794e3165767a4a333673516231574d4747417239386e6a346f7646310a2b34705152616b6d6c58784f535335362b754b58365255434b62534635764b50516e49364b33745871545a36314e487a726254456469554c635a54507a6769730a37564f3064786e317a34437343415a4975634c69645547744d6d6c615953686a547843432f2f5247645a442b46597054666a73592b76473932793436314c536b0a4d4c705034686d436f34705a31644e636c594f716d614b68483553357459496a69617970576d63784f34524f4432707132335337785a71394e467a4948676a660a4e5064322f5671696274516c6a326f6a6335476d32784b73777243356334785759735978376a766c3369706a7168385269516d3478536c43505376304e6765540a6a77374979754b3847785233714a4641506f42516968506c7663692f794b544e6d456d6e2b733850566d70394d70725a6c496952365345502f453044385748760a794862462f6e56534a484b674252584f2f694f6a526e5576416b6f38557254353043687046513746734a384e695255386b586c4f434c59714778594e484a4d700a543042706159506343312b704d5345744675516c513277797a6473784574574a69306c55666335465331516c7a3870646d4659744e4a66794f7252356b502f4e0a4570424833792b795939704279386b62466b71526e6d55564477686768454f33654c6c564e4e566438324e5a7a464a4a32617777776a31794e345a3042617a660a4e455839543146684c496e634c4e7241696e4c4c32474f42737036533379426f5474796c477a5264326b4b484a74686c6261674b73336a3138375571673652350a53376c6b2b3269366c787344574d7a6772312f4e782b77662b3479572b622f506663747a4637716e68695441563473576e63304e5175476732494f74613875760a494d32456c474675684c465335636a49333875644c32384d2f4354376b4c436b5658342b622b5a444551472f5956697a4f6d4f704d5842594f4c6658586751390a534c6f2b323278555548744c4a434e2b66384d7154395a3141677043484270315a6c4b73357831464d7267433771666c4a73667a4d6e5a63534764706538766b0a46743954593756396a6e4132424a5a4f6f46717a6634533059676c477458545358376c6b4566506355475739696d6463777a554772626170334b2b687a6b4c4a0a4e2b4b4f4830772f46537143312f63436857646b7167767131497465773373716d7854477739446e575a35666735726b4f504f5670673d3d0a2d2d2d2d2d454e44205253412050524956415445204b45592d2d2d2d2d0a*1743", "kingdom"},
{"$ssh2$2d2d2d2d2d424547494e204453412050524956415445204b45592d2d2d2d2d0a50726f632d547970653a20342c454e435259505445440a44454b2d496e666f3a204145532d3132382d4342432c35413830363832373943304634364539383230373135304133433245433631340a0a2f756954696e4a3452556a6f5a76302b705931694d763163695661724369347a2f62365a694c4161565970794a31685854327463692b593266334c61614578630a6f357772316141464d3437786d526d476f3832492f76434847413952786735776147433970574f475a5675555172447355367463556b434d422b325a344753390a354f44474364444b32674e6574446e62324a764873714154736d3443633633476468695a30734346594c71796d2b576531774359616c78734f3231572b4f676f0a42336f6746464977327232462b714a7a714d37415543794c466869357a476d7536534e6558765534477a784750464a4e47306d414f55497761614e3161446a630a4e326b3462437266796271337a366e436533444273384b3232694e2b3875526e534162434f717a5a5845645971555959354b6b6a326e654354525458494e64670a512b61535359673379355937626f4b6b6a494f727650555748654f796475512b74657273414577376e43564a7a72394e387452673271563450557631434b66700a4f49467742372f39736f6d6a59496a71576f61537a6a784b30633852777a305331706d722b7571726277792b50656f75354d3373656d486c426b4769553237660a776f684b792b4d554e4862734e6a7973535a53456c4e4b734d4950715449567a5a45316d5646412f30754d477164705133627a424f6a58325a6f36656446434f0a6d4a34775961765735774d2b6a6d75564b5056564e7939395a78796570304645644c50354b623263345a6c3053396631342f62366836415069785665377a75760a5662536b4279664a6e797a68494f5942497954374d64773134723441584a56362b5a6f457730397769774d3d0a2d2d2d2d2d454e44204453412050524956415445204b45592d2d2d2d2d0a*771", "12345"},
/* following test vectors are from CMIYC 2012 */
{"$ssh2$2d2d2d2d2d424547494e205253412050524956415445204b45592d2d2d2d2d0a50726f632d547970653a20342c454e435259505445440a44454b2d496e666f3a204145532d3132382d4342432c41304238464341423242363535424133443034423230323042383941313432450a0a704e75307853616d76714f757969626d324a384d476576667552564d354d3230752f773049502f4f574e317134516439757064546f4147794b77666b4a4975790a314b50457679793635442b4d4b6656635044624756717079597630765170715066377845504264576837494d654f302b514a6f442b33734b2b694c764c36316a0a3159444f414f4d5a5342635868366947486a545579576251785530706c595866645870326f6e6a436a6f6d626578622b644e4f4b32665969436936373072516e0a6f2f4b554e7636793441436a38624a714f5162726844464b6a34334345613672446c316364327455705a77324d4b6c74355162392f50656d6d527575547044760a4c322b5a31616b73654f336348337658577053385279777937344b31596d47496d6d44377275344c4646784b7034572f2b4c6855754d5966336a38426a6844700a744e35767631716e2f7a445a6861693432683556525a68567a5a59486251336c2f7a476c6b38702f394c72624234686f434d596b7a712b5656576b546a4666390a6b41614866596f585338347a5237636b6b4e555948594f694251446353656757445164575762566f676772436549705171364249696c6d4d625a43434543624a0a7069452f4a357548632b73385732436e506b675a6e74664c706d5756352f495a784e4431346a45686c686e2f76543137306472557261692f6a5a3362315447660a39486b69356f574a526e654e727735725235633974333957334d4e5761527a4d5a537a4e55396e356956794a625a6e5044456d4f576f31784c79364b465a71410a364b506d6934456d55504464734f457742446935465054436a534d735244646f764d7272494549535355654341444e44706339745256755637386c4d6a5a56550a54624d7342546e5134667743694c58732f4c784c7437596e696c514a4f6c6273437457536a42453671576f5254582f547273467a645a3963434238644369384a0a496b4d2f38586b526b4277504435514c487a526446683252374e524662707545574b464f443875764b3355434163454d2f7a79504f484145755a766c466652630a4143414f2f71546a62594e53536e594d4946474e6b4334343168496237796d306565322f524c354d55584d4d4f37794733577138514c5a30634f4572676a584c0a4578653232754e4e6d5353504f6f2b597033324567324441476d526664734f72772f5a71384e4877393775336554437a2b46517742692b78714378612f784e510a76626f456d6f7648764d4d2b5966302b68495335357455656f53457a653356544b457a5249696f6b61654848465938542f324d776454416b4f764a62537a62520a6d36426751684c7279304b30554d5231346a6a43756641684349735771732b32355754752b4768672f51642f6b4e354848384a6d495459474365556d524535310a5672754e626563444a78704c714e3743564442633052592f6b4b4d74695762316d5a4139344f53324c6a714e735664542b776d64466b326231457746385750390a6c75397a4f4378336b685449374a4e4a6a7939666f7870307257724445326f337876624365783358755477654b533875384e56705742394679776448376c6f760a79365634484e795775624c7765397576662f54675179687a427945532f5264354c4a46556735504e574b667269784a76462b345166355a77566e774b747561350a6f706c77564e6c6f2f724b6652352b34743469424f4a636146434b4c7252685532594250472b70334155742f4452413352454634316d3074735a746d4450586f0a52796179397a426d4b6833354f727855726c4964505261522b302b6b6977682b725a33387a30356a5a396d6958306967476161762b2b79457767726e735177710a46707a364236545362464131774330376651466f472f5672395769724833514d6875357651376930514f366838524f6169667062786c4d5752436146626a70650a4976396637515736656756506255594a3678517538524f69547757354b366373514d326233676e59456c31474c394d4c7178584c52784d506f776377736d774e0a4f5a30557563744337466266416b7535753830597130306e6e4d2b437373482b36503236336f7656426e6b616239555453624a4d3344627354596a6d33554f6f0a57354b6e46466951676e48536d476766564b7057636d4c386343594d7756312f56566d72312b667554537838636e7631413278476d326b4f7a7061556743514d0a2d2d2d2d2d454e44205253412050524956415445204b45592d2d2d2d2d0a*1766", "Olympics"},
{"$ssh2$2d2d2d2d2d424547494e205253412050524956415445204b45592d2d2d2d2d0a50726f632d547970653a20342c454e435259505445440a44454b2d496e666f3a204145532d3132382d4342432c39323546413041324546373238334132463639433643453639313231443433430a0a424a68414b46483951464555714743682f63646764537649742f524d64374c76616d314737547a75534e6c6a767a533542524a4d474949377870675a752b77700a37657630357065762f2b77734e6565626d542f7969354c514e5664597563547141507366533953484d67575751386f68524c6e4458656330324e73355548624c0a6641526f39732b3675785a474e462b516576677238566d484d39657170556c7356655a69423131723230664c6c4246672f52454756774d4430416d39794a2b6a0a374d4238684d5035456a696c48626a73774a2b4f613277546c6335586c77792f4b6a37784e4233637441547057444c7755316f77735842495655737a5156416d0a4763534768647448426f5663356971477335552f45686e553275454351795a6441535a50706b43414268694b5147672b586553564c4c5a35624e4a5a50704e6c0a426c39522f7947794f347641645552534a676b726d4945556c693756394c6c784b4d7870374b656a305261644c594f6d4d71584d55536b464a3779456a4833540a31325655736f75797671426962302f53667a7557454f676e3643456359496564642b6f566b39674a4347474c56516751534c7772727661456a45454463726d6d0a6b316a2b7556776a3130663447316c586647416456544e3766484e39643731304b6846576761643477396a6c4536504d306c7a344d364d7363373845523245780a7372744a6a3679556c6c6c7859335a7258305a724a48696c5a484e734a467a776f4c394c4d37345436794e6732737634567a73304c7a4e74413045696c6c544e0a46415a307359343177452b5265705a6f4d47744d6b7968594a623349535577676e52417945756f64367365446e624b4b7a375550713858437451567a4d2b79380a746f5774373136574b6c4a7141763145394170612b634a39516847764570725565312b3848562b6641655774484650334b4f7257616b584c6a6d7163456a65750a73434e30496c3779746a7644366d7372477259546235416a6274586558346a473764364f703132347a35727467444254647a4866342b36465772554238434e610a36775849737550305a6f796771794d4d79485a495937382b70787538346e59315671464d3346344a7350714f6e4f61556a54643743482f6754527061347370680a4e5155554e327a305278476672513668574c46726872365051335176755a4e4e5042364d78475358775a485263447146344c697841724a316c556357683858520a4d316f696b43465031473256614e537968467549385262567772506a646d4177767250584556662f44452b723054716863336c647462694e425a37486d2f554d0a49764d526c4247304a35306366413649703741667048355356546b54734d37754a7955412f742b6968494f6f536347477a6a477945306c46334b71457754392b0a5230315a734b44313932696f37457a566a49535a73376f2b47494436643254716e6b4a4c4b65583236704e6e4738347068656f4e55652f4364303843504758700a6d2b50625638536f506a77765766376d4c3244366a483632622f687738467a2f312b6f67685343675a412f6f6232475a524c4f4a7a2b6156566e3638676f4b550a42796336786e4577303743636a2f46797033714f3957735971735a64566766766e32376e6b6344735732524876595237585770554552517145516341316273450a516b45523366376963546e72725a4d6470673368364c2f4966797454754849454e6450627331684558384e4a4f7470434753654464423979745a4e4e616a6d650a487146696b66725a3834354a386a3436317a41395452355764376d6f47762b4e2f4b6572737a5256354f65466970336d5675516a6e434b734c704731574c7a430a577a567235594e49662f776b525a687a2f723072374b3567566c524e5676356e413049306345696f71386f426e53494465552f595a533078695a384a545765710a4d4530655948526737373377577a74416665565079654d3947486e2b5633435241327433354434344c78724c76424c4c4f38672f4a615235456d56304867474c0a5343572b734b61514862476535596f384e3433302f2b744d6e65392b63776f495647302f6159396370506d4d676436796d4363707135555766737168316a494c0a4574535054654c386d4a473434526649696d39622f77527248716a4b744c4376696b694e2b6d4e547a4b6f784a656c5a4d69765172555a69725258502b34627a0a2d2d2d2d2d454e44205253412050524956415445204b45592d2d2d2d2d0a*1766", "C0Ld.FUS10N"},
{"$ssh2$2d2d2d2d2d424547494e205253412050524956415445204b45592d2d2d2d2d0a50726f632d547970653a20342c454e435259505445440a44454b2d496e666f3a204145532d3132382d4342432c41424638364346373834394242433543363631413639463146374234433837410a0a5355484c486a305a2f58467a35376c2f723253453241502b5a7a6469676b486e3645693030433732504a47706d72715544424668562f6c7566493652565133310a486667444a4b566a416b5375672f7a415177544b6e33704e6c69484b74467074555472384272493254434971655164796e6a5669396e62376c4e656a7a374a560a48654a326270316e7744582b7a6552562f5851615a3149644433466e5058773253734d5568514d557378746f6d526d46524d44797133694f76554e63307047750a6a424a5861446633684b7438324b6d384a4c366a676a41304655337873396d326f47515447703634477a2f536d50456f52597a383546417756674c67682b715a0a562b4b524635517535364c396970674e70567732543367663772472f4e563767336c544f6c4732466b773934625739686453564e576b4e77336358496a76452b0a49304b62445a3042394250776a4f556c4d55485954494e6f4d4969517870746c76704f6b465a492f6d4c794a6a35793071362f4c7a64386e68666159344a48580a58756f4b6b43467370483045576373726a5a576f6d4a396753677837794e787042354841787a35766569596f366e36396a686f35726c67386b57614e796e67470a386961724e68384876394e66635443752f494d4847345a6377415435592b2b41703141416a7049504746517947556e5746442f384d37594c57414664587a4c490a49414272437047714348566632466e4952644f6e58596b31445a77533539387975627a52694767624359477352784e515845745262755452427a366e4662614e0a4442444f5031597643317454673661395577434f774f695366586a592f534858594f5a3970774462593438344e632f564977527534504c2f2f7442634f396b430a746d646c5970394369384b416a6a41507669426b723571784a6178426c664f316457344a425a7a446b524a386a76756f35513675742b436b325956687a7056410a2b6d7562597a4f2b73652f745631486e724d47713950442f6c31355569694777696971306e553572386a4e75594f7547684e362b585745586163376866446a670a4c5342584b4531355350322b525a43536f4f52484551663156574b73367842463850484f2b7a324a35556c434c796468675466456a633466464a397368306a550a6f652f346e753252514f785a6a652b4e4f455636493537685a363974594b365a556d485a7930664f4c55306c73564950693356416930556d5850464e4f4a4c630a745463792b6b46524d5339506249314770553048776a744c4a544144534a6f6f315554366b44367770796f36365254612f7455686a4f6a5852624937336a504a0a3430626265515565646a686d2b364f50456a737977524330466f77377279724f633130507a317a5066436f70316e31494d6344504e484b7269786c2b32564d460a62454c587a4a466b624b4571652b757950365437426a49587437664a2f73646f683468356843537377797338634571527675616d504b57694747333444694a660a6c6d6556614d6b327961523756685746676848484a4547702f3033435a62715938306159532f6b7061612b62304458354f6b66642b4c37766d36684f724d48330a6275533948724a43334a2b796c4a306f66326854616445534b475753596e44347649505845596742353335492f533355755a596a465754525a4a78474e7263300a35494d47664247423065334733554a5055587a54366a2f687135424d326e69337439624956716773666878726f2b6e376b396f642f71394f50762b47744651610a73343953623143626b56393466577139536b7878644e2f4c47504e7270792b6d6d324767594c4a34577a302b6a536a7039716f614d71796a6c49376b6759696e0a3769537859504f6d764a67706539685330485751674d374e6864764a472f5241527757556a476f576e68514b4a486e4e39626841773962356e7154676d335a7a0a4330307a4d4139716c6a795179773448677a704c387854584c5947756a745850584b533874764e617977783967706933436c74682b487354773748514b31622b0a5173564757745639314151626d7a61554d59697375485167556d61626c66325938394744556668306a70367739483052704e624b4c7341306a76665354702b410a7764776a6d31452b31345a2f4a5a41346461487071595046794564626a6548333977516a386652792f4b48706d6c4b7851515845704837625a58363466514e540a2d2d2d2d2d454e44205253412050524956415445204b45592d2d2d2d2d0a*1766", "extuitive"},
{NULL}
};
struct fmt_main fmt_ssh;
static void init(struct fmt_main *self)
{
/* OpenSSL init, cleanup part is left to OS */
SSL_load_error_strings();
SSL_library_init();
OpenSSL_add_all_algorithms();
#if defined(_OPENMP) && OPENSSL_VERSION_NUMBER >= 0x10000000
if (SSLeay() < 0x10000000) {
fprintf(stderr, "Warning: compiled against OpenSSL 1.0+, "
"but running with an older version -\n"
"disabling OpenMP for SSH because of thread-safety issues "
"of older OpenSSL\n");
fmt_ssh.params.min_keys_per_crypt =
fmt_ssh.params.max_keys_per_crypt = 1;
fmt_ssh.params.flags &= ~FMT_OMP;
}
else {
int omp_t = 1;
omp_t = omp_get_max_threads();
self->params.min_keys_per_crypt *= omp_t;
omp_t *= OMP_SCALE;
self->params.max_keys_per_crypt *= omp_t;
}
#endif
saved_key = mem_calloc_tiny(sizeof(*saved_key) *
self->params.max_keys_per_crypt, MEM_ALIGN_WORD);
any_cracked = 0;
cracked_size = sizeof(*cracked) * self->params.max_keys_per_crypt;
cracked = mem_calloc_tiny(cracked_size, MEM_ALIGN_WORD);
}
static int ishex(char *q)
{
while (atoi16[ARCH_INDEX(*q)] != 0x7F)
q++;
return !*q;
}
static int valid(char *ciphertext, struct fmt_main *self)
{
char *ctcopy;
char *keeptr;
char *p;
int res;
if (strncmp(ciphertext, "$ssh2$", 6))
return 0;
ctcopy = strdup(ciphertext);
keeptr = ctcopy;
ctcopy += 6;
/* find length field */
p = strrchr(ctcopy, '*');
if (!p)
goto err;
p += 1;
res = atoi(p);
if ((p = strtok(ctcopy, "*")) == NULL) /* data */
goto err;
if (!ishex(p))
goto err;
if(strlen(p) != res * 2)
goto err;
MEM_FREE(keeptr);
return 1;
err:
MEM_FREE(keeptr);
return 0;
}
#define M_do_cipher(ctx, out, in, inl) ctx->cipher->do_cipher(ctx, out, in, inl)
int EVP_DecryptFinal_ex_safe(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
{
int i,n;
unsigned int b;
*outl=0;
#ifndef EVP_CIPH_FLAG_CUSTOM_CIPHER
#define EVP_CIPH_FLAG_CUSTOM_CIPHER 0x100000
#endif
if (ctx->cipher->flags & EVP_CIPH_FLAG_CUSTOM_CIPHER) {
i = M_do_cipher(ctx, out, NULL, 0);
if (i < 0)
return 0;
else
*outl = i;
return 1;
}
b=ctx->cipher->block_size;
#ifndef EVP_CIPH_NO_PADDING
#define EVP_CIPH_NO_PADDING 0x100
#endif
if (ctx->flags & EVP_CIPH_NO_PADDING) {
if(ctx->buf_len) {
return 0;
}
*outl = 0;
return 1;
}
if (b > 1) {
if (ctx->buf_len || !ctx->final_used) {
return(0);
}
OPENSSL_assert(b <= sizeof ctx->final);
n=ctx->final[b-1];
if (n == 0 || n > (int)b) {
return(0);
}
for (i=0; i<n; i++) {
if (ctx->final[--b] != n) {
return(0);
}
}
n=ctx->cipher->block_size-n;
for (i=0; i<n; i++)
out[i]=ctx->final[i];
*outl=n;
}
else
*outl=0;
return(1);
}
int PEM_do_header_safe(EVP_CIPHER_INFO *cipher, unsigned char *data, long *plen,
pem_password_cb *callback,void *u)
{
int i,j,o,klen;
long len;
EVP_CIPHER_CTX ctx;
unsigned char key[EVP_MAX_KEY_LENGTH];
char buf[PEM_BUFSIZE];
len= *plen;
if (cipher->cipher == NULL) return(1);
if (callback == NULL)
klen=PEM_def_callback(buf,PEM_BUFSIZE,0,u);
else
klen=callback(buf,PEM_BUFSIZE,0,u);
if (klen <= 0) {
return(0);
}
EVP_BytesToKey(cipher->cipher,EVP_md5(),&(cipher->iv[0]),
(unsigned char *)buf,klen,1,key,NULL);
j=(int)len;
EVP_CIPHER_CTX_init(&ctx);
EVP_DecryptInit_ex(&ctx,cipher->cipher,NULL, key,&(cipher->iv[0]));
EVP_DecryptUpdate(&ctx,data,&i,data,j);
o=EVP_DecryptFinal_ex_safe(&ctx,&(data[i]),&j);
EVP_CIPHER_CTX_cleanup(&ctx);
OPENSSL_cleanse((char *)buf,sizeof(buf));
OPENSSL_cleanse((char *)key,sizeof(key));
j+=i;
if (!o) {
return(0);
}
*plen=j;
return(1);
}
static void *get_salt(char *ciphertext)
{
int i, filelength;
char *decoded_data;
char *copy = strdup(ciphertext);
char *encoded_data = strtok(copy, "*");
BIO *bp;
char *nm = NULL, *header = NULL;
unsigned char *data = NULL;
EVP_CIPHER_INFO cipher;
EVP_PKEY pk;
long len;
static struct custom_salt cs;
if (!copy || !encoded_data) {
fprintf(stderr, "BUG in parsing ciphertext, aborting!\n");
exit(-1);
}
filelength = atoi(strtok(NULL, "*"));
encoded_data += 6; /* skip over "$ssh2$ marker */
decoded_data = (char *) mem_alloc(filelength + 1);
for (i = 0; i < filelength; i++)
decoded_data[i] =
atoi16[ARCH_INDEX(encoded_data[i * 2])] * 16 +
atoi16[ARCH_INDEX(encoded_data[i * 2 + 1])];
decoded_data[filelength] = 0;
/* load decoded data into OpenSSL structures */
bp = BIO_new(BIO_s_mem());
if (!bp) {
fprintf(stderr, "OpenSSL BIO allocation failure\n");
exit(-2);
}
BIO_write(bp, decoded_data, filelength);
/* PEM_bytes_read_bio function in crypto/pem/pem_lib.c
* check_pem function in crypto/pem/pem_lib.c */
for (;;) {
if (!PEM_read_bio(bp, &nm, &header, &data, &len)) {
if (ERR_GET_REASON(ERR_peek_error()) ==
PEM_R_NO_START_LINE) {
ERR_print_errors_fp(stderr);
exit(-3);
}
}
/* only PEM encoded DSA and RSA private keys are supported. */
if (!strcmp(nm, PEM_STRING_DSA)) {
pk.save_type = EVP_PKEY_DSA;
pk.type = EVP_PKEY_type(EVP_PKEY_DSA);
break;
}
if (!strcmp(nm, PEM_STRING_RSA)) {
pk.save_type = EVP_PKEY_RSA;
pk.type = EVP_PKEY_type(EVP_PKEY_RSA);
break;
}
OPENSSL_free(nm);
OPENSSL_free(header);
OPENSSL_free(data);
OPENSSL_free(bp);
}
if (!PEM_get_EVP_CIPHER_INFO(header, &cipher)) {
ERR_print_errors_fp(stderr);
exit(-4);
}
#ifdef SSH_FMT_DEBUG
printf("Header Information:\n%s\n", header);
#endif
/* save custom_salt information */
memset(&cs, 0, sizeof(cs));
memcpy(&cs.cipher, &cipher, sizeof(cipher));
memcpy(&cs.pk, &pk, sizeof(pk));
memcpy(cs.data, data, len);
cs.len = len;
OPENSSL_free(nm);
OPENSSL_free(header);
OPENSSL_free(data);
BIO_free(bp);
MEM_FREE(copy);
MEM_FREE(decoded_data);
return (void *) &cs;
}
static void set_salt(void *salt)
{
/* restore custom_salt back */
restored_custom_salt = (struct custom_salt *) salt;
}
static void ssh_set_key(char *key, int index)
{
int len = strlen(key);
if (len > PLAINTEXT_LENGTH)
len = PLAINTEXT_LENGTH;
memcpy(saved_key[index], key, len);
saved_key[index][len] = 0;
}
static char *get_key(int index)
{
return saved_key[index];
}
static int crypt_all(int *pcount, struct db_salt *salt)
{
int count = *pcount;
int index = 0;
if (any_cracked) {
memset(cracked, 0, cracked_size);
any_cracked = 0;
}
#if defined(_OPENMP) && OPENSSL_VERSION_NUMBER >= 0x10000000
#pragma omp parallel for default(none) private(index) shared(count, any_cracked, cracked, saved_key, restored_custom_salt)
for (index = 0; index < count; index++)
#endif
{
/* copy restored items into working copy */
unsigned char working_data[4096];
long working_len = restored_custom_salt->len;
EVP_CIPHER_INFO cipher = restored_custom_salt->cipher;
EVP_PKEY pk = restored_custom_salt->pk;
const char unsigned *dc = working_data;
DSA *dsapkc = NULL;
RSA *rsapkc = NULL;
memcpy(working_data, restored_custom_salt->data, working_len);
if (PEM_do_header_safe(&cipher, working_data, &working_len, NULL,
(char *) saved_key[index])) {
if (pk.save_type == EVP_PKEY_DSA) {
if ((dsapkc =
d2i_DSAPrivateKey(NULL, &dc,
working_len)) != NULL) {
DSA_free(dsapkc);
{
cracked[index] = 1;
#if defined(_OPENMP) && OPENSSL_VERSION_NUMBER >= 0x10000000
#pragma omp atomic
#endif
any_cracked |= 1;
}
}
} else if (pk.save_type == EVP_PKEY_RSA) {
if ((rsapkc =
d2i_RSAPrivateKey(NULL, &dc,
working_len)) != NULL) {
RSA_free(rsapkc);
{
cracked[index] = 1;
#if defined(_OPENMP) && OPENSSL_VERSION_NUMBER >= 0x10000000
#pragma omp atomic
#endif
any_cracked |= 1;
}
}
}
}
}
return count;
}
static int cmp_all(void *binary, int count)
{
return any_cracked;
}
static int cmp_one(void *binary, int index)
{
return cracked[index];
}
static int cmp_exact(char *source, int index)
{
return cracked[index];
}
struct fmt_main fmt_ssh = {
{
FORMAT_LABEL,
FORMAT_NAME,
ALGORITHM_NAME,
BENCHMARK_COMMENT,
BENCHMARK_LENGTH,
PLAINTEXT_LENGTH,
BINARY_SIZE,
BINARY_ALIGN,
SALT_SIZE,
SALT_ALIGN,
MIN_KEYS_PER_CRYPT,
MAX_KEYS_PER_CRYPT,
#if defined(_OPENMP) && OPENSSL_VERSION_NUMBER >= 0x10000000
FMT_OMP |
#endif
FMT_CASE | FMT_8_BIT,
#if FMT_MAIN_VERSION > 11
{ NULL },
#endif
ssh_tests
}, {
init,
fmt_default_done,
fmt_default_reset,
fmt_default_prepare,
valid,
fmt_default_split,
fmt_default_binary,
get_salt,
#if FMT_MAIN_VERSION > 11
{ NULL },
#endif
fmt_default_source,
{
fmt_default_binary_hash
},
fmt_default_salt_hash,
set_salt,
ssh_set_key,
get_key,
fmt_default_clear_keys,
crypt_all,
{
fmt_default_get_hash
},
cmp_all,
cmp_one,
cmp_exact
}
};
#endif /* plugin stanza */
|
GB_unop__identity_bool_int8.c
|
//------------------------------------------------------------------------------
// GB_unop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated2/ folder, do not edit it
// (it is auto-generated from Generator/*).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_atomics.h"
#include "GB_unop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB (_unop_apply__identity_bool_int8)
// op(A') function: GB (_unop_tran__identity_bool_int8)
// C type: bool
// A type: int8_t
// cast: bool cij = (bool) aij
// unaryop: cij = aij
#define GB_ATYPE \
int8_t
#define GB_CTYPE \
bool
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
int8_t aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = x ;
// casting
#define GB_CAST(z, aij) \
bool z = (bool) aij ;
// cij = op (aij)
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
int8_t aij = Ax [pA] ; \
/* Cx [pC] = op (cast (aij)) */ \
bool z = (bool) aij ; \
Cx [pC] = z ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_IDENTITY || GxB_NO_BOOL || GxB_NO_INT8)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_apply__identity_bool_int8)
(
bool *Cx, // Cx and Ax may be aliased
const int8_t *Ax,
const int8_t *restrict Ab, // A->b if A is bitmap
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
if (Ab == NULL)
{
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
int8_t aij = Ax [p] ;
bool z = (bool) aij ;
Cx [p] = z ;
}
}
else
{
// bitmap case, no transpose; A->b already memcpy'd into C->b
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!Ab [p]) continue ;
int8_t aij = Ax [p] ;
bool z = (bool) aij ;
Cx [p] = z ;
}
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_tran__identity_bool_int8)
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
eb24237de8e5a03acb8c2e2c9f0ddd4a6bca7bdb.c
|
#define _POSIX_C_SOURCE 200809L
#include "stdlib.h"
#include "math.h"
#include "sys/time.h"
#include "omp.h"
struct dataobj
{
void *restrict data;
int * size;
int * npsize;
int * dsize;
int * hsize;
int * hofs;
int * oofs;
} ;
struct profiler
{
double section0;
} ;
int padfunc(struct dataobj *restrict vp_vec, const int x_M, const int y_M, const int z_M, const int abc_x_l_ltkn, const int abc_x_r_rtkn, const int abc_y_l_ltkn, const int abc_y_r_rtkn, const int abc_z_l_ltkn, const int abc_z_r_rtkn, struct profiler * timers, const int x_m, const int y_m, const int z_m)
{
float (*restrict vp)[vp_vec->size[1]][vp_vec->size[2]] __attribute__ ((aligned (64))) = (float (*)[vp_vec->size[1]][vp_vec->size[2]]) vp_vec->data;
#pragma omp target enter data map(to: vp[0:vp_vec->size[0]][0:vp_vec->size[1]][0:vp_vec->size[2]])
struct timeval start_section0, end_section0;
gettimeofday(&start_section0, NULL);
/* Begin section0 */
for (int abc_x_l = x_m; abc_x_l <= abc_x_l_ltkn + x_m - 1; abc_x_l += 1)
{
#pragma omp target teams distribute parallel for collapse(2)
for (int y = y_m; y <= y_M; y += 1)
{
for (int z = z_m; z <= z_M; z += 1)
{
vp[abc_x_l + 2][y + 2][z + 2] = vp[12][y + 2][z + 2];
}
}
}
for (int abc_x_r = -abc_x_r_rtkn + x_M + 1; abc_x_r <= x_M; abc_x_r += 1)
{
#pragma omp target teams distribute parallel for collapse(2)
for (int y = y_m; y <= y_M; y += 1)
{
for (int z = z_m; z <= z_M; z += 1)
{
vp[abc_x_r + 2][y + 2][z + 2] = vp[x_M - 8][y + 2][z + 2];
}
}
}
#pragma omp target teams distribute parallel for collapse(1)
for (int x = x_m; x <= x_M; x += 1)
{
for (int abc_y_l = y_m; abc_y_l <= abc_y_l_ltkn + y_m - 1; abc_y_l += 1)
{
for (int z = z_m; z <= z_M; z += 1)
{
vp[x + 2][abc_y_l + 2][z + 2] = vp[x + 2][12][z + 2];
}
}
for (int abc_y_r = -abc_y_r_rtkn + y_M + 1; abc_y_r <= y_M; abc_y_r += 1)
{
for (int z = z_m; z <= z_M; z += 1)
{
vp[x + 2][abc_y_r + 2][z + 2] = vp[x + 2][y_M - 8][z + 2];
}
}
for (int y = y_m; y <= y_M; y += 1)
{
for (int abc_z_l = z_m; abc_z_l <= abc_z_l_ltkn + z_m - 1; abc_z_l += 1)
{
vp[x + 2][y + 2][abc_z_l + 2] = vp[x + 2][y + 2][12];
}
for (int abc_z_r = -abc_z_r_rtkn + z_M + 1; abc_z_r <= z_M; abc_z_r += 1)
{
vp[x + 2][y + 2][abc_z_r + 2] = vp[x + 2][y + 2][z_M - 8];
}
}
}
/* End section0 */
gettimeofday(&end_section0, NULL);
timers->section0 += (double)(end_section0.tv_sec-start_section0.tv_sec)+(double)(end_section0.tv_usec-start_section0.tv_usec)/1000000;
#pragma omp target update from(vp[0:vp_vec->size[0]][0:vp_vec->size[1]][0:vp_vec->size[2]])
#pragma omp target exit data map(release: vp[0:vp_vec->size[0]][0:vp_vec->size[1]][0:vp_vec->size[2]])
return 0;
}
|
convolution_1x1_bf16s.h
|
// Tencent is pleased to support the open source community by making ncnn available.
//
// Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// https://opensource.org/licenses/BSD-3-Clause
//
// 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.
static void conv1x1s1_sgemm_transform_kernel_bf16s_neon(const Mat& _kernel, Mat& kernel_tm, int inch, int outch)
{
const float* kernel = _kernel;
// interleave
#if __ARM_NEON && __aarch64__
kernel_tm.create(4 * 8, inch / 4 + inch % 4, outch / 8 + (outch % 8) / 4 + outch % 4, (size_t)2u, 1);
#else
kernel_tm.create(4 * 4, inch / 4 + inch % 4, outch / 4 + outch % 4, (size_t)2u, 1);
#endif // __ARM_NEON && __aarch64__
int p = 0;
#if __ARM_NEON && __aarch64__
for (; p + 7 < outch; p += 8)
{
const float* kernel0 = kernel + (p + 0) * inch;
const float* kernel1 = kernel + (p + 1) * inch;
const float* kernel2 = kernel + (p + 2) * inch;
const float* kernel3 = kernel + (p + 3) * inch;
const float* kernel4 = kernel + (p + 4) * inch;
const float* kernel5 = kernel + (p + 5) * inch;
const float* kernel6 = kernel + (p + 6) * inch;
const float* kernel7 = kernel + (p + 7) * inch;
unsigned short* ktmp = kernel_tm.channel(p / 8);
for (int q = 0; q < inch; q++)
{
// kernel0...7 0
ktmp[0] = float32_to_bfloat16(kernel0[0]);
ktmp[1] = float32_to_bfloat16(kernel1[0]);
ktmp[2] = float32_to_bfloat16(kernel2[0]);
ktmp[3] = float32_to_bfloat16(kernel3[0]);
ktmp[4] = float32_to_bfloat16(kernel4[0]);
ktmp[5] = float32_to_bfloat16(kernel5[0]);
ktmp[6] = float32_to_bfloat16(kernel6[0]);
ktmp[7] = float32_to_bfloat16(kernel7[0]);
ktmp += 8;
kernel0 += 1;
kernel1 += 1;
kernel2 += 1;
kernel3 += 1;
kernel4 += 1;
kernel5 += 1;
kernel6 += 1;
kernel7 += 1;
}
}
#endif // __ARM_NEON && __aarch64__
for (; p + 3 < outch; p += 4)
{
const float* kernel0 = kernel + (p + 0) * inch;
const float* kernel1 = kernel + (p + 1) * inch;
const float* kernel2 = kernel + (p + 2) * inch;
const float* kernel3 = kernel + (p + 3) * inch;
#if __ARM_NEON && __aarch64__
unsigned short* ktmp = kernel_tm.channel(p / 8 + (p % 8) / 4);
#else
unsigned short* ktmp = kernel_tm.channel(p / 4);
#endif // __ARM_NEON && __aarch64__
for (int q = 0; q < inch; q++)
{
// kernel0...3 0
ktmp[0] = float32_to_bfloat16(kernel0[0]);
ktmp[1] = float32_to_bfloat16(kernel1[0]);
ktmp[2] = float32_to_bfloat16(kernel2[0]);
ktmp[3] = float32_to_bfloat16(kernel3[0]);
ktmp += 4;
kernel0 += 1;
kernel1 += 1;
kernel2 += 1;
kernel3 += 1;
}
}
for (; p < outch; p++)
{
const float* kernel0 = kernel + p * inch;
#if __ARM_NEON && __aarch64__
unsigned short* ktmp = kernel_tm.channel(p / 8 + (p % 8) / 4 + p % 4);
#else
unsigned short* ktmp = kernel_tm.channel(p / 4 + p % 4);
#endif // __ARM_NEON && __aarch64__
for (int q = 0; q < inch; q++)
{
ktmp[0] = float32_to_bfloat16(kernel0[0]);
ktmp++;
kernel0++;
}
}
}
static void conv1x1s1_sgemm_bf16s_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel, const Mat& _bias, const Option& opt)
{
int w = bottom_blob.w;
int h = bottom_blob.h;
int inch = bottom_blob.c;
int outch = top_blob.c;
const int size = w * h;
const float* bias = _bias;
// interleave
Mat tmp(8 * 4, inch / 4 + inch % 4, size / 8 + (size % 8) / 4 + size % 4, 2u, opt.workspace_allocator);
{
int nn_size = size >> 3;
int remain_size_start = nn_size << 3;
#pragma omp parallel for num_threads(opt.num_threads)
for (int ii = 0; ii < nn_size; ii++)
{
int i = ii * 8;
const unsigned short* img0 = bottom_blob.channel(0);
img0 += i;
unsigned short* tmpptr = tmp.channel(i / 8);
for (int q = 0; q < inch; q++)
{
#if __ARM_NEON
#if __aarch64__
vst1q_u16(tmpptr, vld1q_u16(img0));
tmpptr += 8;
img0 += bottom_blob.cstep;
#else
asm volatile(
"pld [%0, #128] \n"
"vld1.u16 {d0-d1}, [%0 :64] \n"
"vst1.u16 {d0-d1}, [%1 :64]! \n"
: "=r"(img0), // %0
"=r"(tmpptr) // %1
: "0"(img0),
"1"(tmpptr)
: "memory", "q0");
img0 += bottom_blob.cstep;
#endif // __aarch64__
#else
tmpptr[0] = img0[0];
tmpptr[1] = img0[1];
tmpptr[2] = img0[2];
tmpptr[3] = img0[3];
tmpptr[4] = img0[4];
tmpptr[5] = img0[5];
tmpptr[6] = img0[6];
tmpptr[7] = img0[7];
tmpptr += 8;
img0 += bottom_blob.cstep;
#endif // __ARM_NEON
}
}
nn_size = (size - remain_size_start) >> 2;
#pragma omp parallel for num_threads(opt.num_threads)
for (int ii = 0; ii < nn_size; ii++)
{
int i = remain_size_start + ii * 4;
const unsigned short* img0 = bottom_blob.channel(0);
img0 += i;
unsigned short* tmpptr = tmp.channel(i / 8 + (i % 8) / 4);
for (int q = 0; q < inch; q++)
{
#if __ARM_NEON
#if __aarch64__
vst1_u16(tmpptr, vld1_u16(img0));
tmpptr += 4;
img0 += bottom_blob.cstep;
#else
asm volatile(
"pld [%0, #64] \n"
"vld1.u16 {d0}, [%0 :64] \n"
"vst1.u16 {d0}, [%1 :64]! \n"
: "=r"(img0), // %0
"=r"(tmpptr) // %1
: "0"(img0),
"1"(tmpptr)
: "memory", "d0");
img0 += bottom_blob.cstep;
#endif // __aarch64__
#else
tmpptr[0] = img0[0];
tmpptr[1] = img0[1];
tmpptr[2] = img0[2];
tmpptr[3] = img0[3];
tmpptr += 4;
img0 += bottom_blob.cstep;
#endif // __ARM_NEON
}
}
remain_size_start += nn_size << 2;
#pragma omp parallel for num_threads(opt.num_threads)
for (int i = remain_size_start; i < size; i++)
{
const unsigned short* img0 = bottom_blob.channel(0);
img0 += i;
unsigned short* tmpptr = tmp.channel(i / 8 + (i % 8) / 4 + i % 4);
for (int q = 0; q < inch; q++)
{
tmpptr[0] = img0[0];
tmpptr++;
img0 += bottom_blob.cstep;
}
}
}
int nn_outch = 0;
int remain_outch_start = 0;
#if __ARM_NEON && __aarch64__
nn_outch = outch >> 3;
remain_outch_start = nn_outch << 3;
#pragma omp parallel for num_threads(opt.num_threads)
for (int pp = 0; pp < nn_outch; pp++)
{
int p = pp * 8;
unsigned short* outptr0 = top_blob.channel(p);
unsigned short* outptr1 = top_blob.channel(p + 1);
unsigned short* outptr2 = top_blob.channel(p + 2);
unsigned short* outptr3 = top_blob.channel(p + 3);
unsigned short* outptr4 = top_blob.channel(p + 4);
unsigned short* outptr5 = top_blob.channel(p + 5);
unsigned short* outptr6 = top_blob.channel(p + 6);
unsigned short* outptr7 = top_blob.channel(p + 7);
const float zeros[8] = {0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f};
const float* biasptr = bias ? bias + p : zeros;
int i = 0;
for (; i + 7 < size; i += 8)
{
const unsigned short* tmpptr = tmp.channel(i / 8);
const unsigned short* kptr = kernel.channel(p / 8);
asm volatile(
"ld1 {v0.4s, v1.4s}, [%20] \n"
"dup v16.4s, v0.s[0] \n"
"dup v17.4s, v0.s[0] \n"
"dup v18.4s, v0.s[1] \n"
"dup v19.4s, v0.s[1] \n"
"dup v20.4s, v0.s[2] \n"
"dup v21.4s, v0.s[2] \n"
"dup v22.4s, v0.s[3] \n"
"dup v23.4s, v0.s[3] \n"
"dup v24.4s, v1.s[0] \n"
"dup v25.4s, v1.s[0] \n"
"dup v26.4s, v1.s[1] \n"
"dup v27.4s, v1.s[1] \n"
"dup v28.4s, v1.s[2] \n"
"dup v29.4s, v1.s[2] \n"
"dup v30.4s, v1.s[3] \n"
"dup v31.4s, v1.s[3] \n"
// inch loop
"lsr w4, %w21, #2 \n" // w4 = nn = inch >> 2
"cmp w4, #0 \n"
"beq 1f \n"
"0: \n"
"prfm pldl1keep, [%8, #256] \n"
"ld1 {v8.4h, v9.4h, v10.4h, v11.4h}, [%8], #32 \n"
"shll v8.4s, v8.4h, #16 \n"
"shll v9.4s, v9.4h, #16 \n"
"shll v10.4s, v10.4h, #16 \n"
"shll v11.4s, v11.4h, #16 \n"
"prfm pldl1keep, [%9, #256] \n"
"ld1 {v0.4h, v1.4h, v2.4h, v3.4h}, [%9], #32 \n"
"shll v0.4s, v0.4h, #16 \n"
"shll v1.4s, v1.4h, #16 \n"
"shll v2.4s, v2.4h, #16 \n"
"shll v3.4s, v3.4h, #16 \n"
"fmla v16.4s, v8.4s, v0.s[0] \n"
"fmla v18.4s, v8.4s, v0.s[1] \n"
"fmla v20.4s, v8.4s, v0.s[2] \n"
"fmla v22.4s, v8.4s, v0.s[3] \n"
"fmla v17.4s, v9.4s, v0.s[0] \n"
"fmla v19.4s, v9.4s, v0.s[1] \n"
"fmla v21.4s, v9.4s, v0.s[2] \n"
"fmla v23.4s, v9.4s, v0.s[3] \n"
"fmla v24.4s, v8.4s, v1.s[0] \n"
"fmla v26.4s, v8.4s, v1.s[1] \n"
"fmla v28.4s, v8.4s, v1.s[2] \n"
"fmla v30.4s, v8.4s, v1.s[3] \n"
"fmla v25.4s, v9.4s, v1.s[0] \n"
"fmla v27.4s, v9.4s, v1.s[1] \n"
"fmla v29.4s, v9.4s, v1.s[2] \n"
"fmla v31.4s, v9.4s, v1.s[3] \n"
"prfm pldl1keep, [%8, #256] \n"
"ld1 {v12.4h, v13.4h, v14.4h, v15.4h}, [%8], #32 \n"
"shll v12.4s, v12.4h, #16 \n"
"shll v13.4s, v13.4h, #16 \n"
"shll v14.4s, v14.4h, #16 \n"
"shll v15.4s, v15.4h, #16 \n"
"fmla v16.4s, v10.4s, v2.s[0] \n"
"fmla v18.4s, v10.4s, v2.s[1] \n"
"fmla v20.4s, v10.4s, v2.s[2] \n"
"fmla v22.4s, v10.4s, v2.s[3] \n"
"fmla v17.4s, v11.4s, v2.s[0] \n"
"fmla v19.4s, v11.4s, v2.s[1] \n"
"fmla v21.4s, v11.4s, v2.s[2] \n"
"fmla v23.4s, v11.4s, v2.s[3] \n"
"fmla v24.4s, v10.4s, v3.s[0] \n"
"fmla v26.4s, v10.4s, v3.s[1] \n"
"fmla v28.4s, v10.4s, v3.s[2] \n"
"fmla v30.4s, v10.4s, v3.s[3] \n"
"fmla v25.4s, v11.4s, v3.s[0] \n"
"fmla v27.4s, v11.4s, v3.s[1] \n"
"fmla v29.4s, v11.4s, v3.s[2] \n"
"fmla v31.4s, v11.4s, v3.s[3] \n"
"prfm pldl1keep, [%9, #256] \n"
"ld1 {v4.4h, v5.4h, v6.4h, v7.4h}, [%9], #32 \n"
"shll v4.4s, v4.4h, #16 \n"
"shll v5.4s, v5.4h, #16 \n"
"shll v6.4s, v6.4h, #16 \n"
"shll v7.4s, v7.4h, #16 \n"
"fmla v16.4s, v12.4s, v4.s[0] \n"
"fmla v18.4s, v12.4s, v4.s[1] \n"
"fmla v20.4s, v12.4s, v4.s[2] \n"
"fmla v22.4s, v12.4s, v4.s[3] \n"
"fmla v17.4s, v13.4s, v4.s[0] \n"
"fmla v19.4s, v13.4s, v4.s[1] \n"
"fmla v21.4s, v13.4s, v4.s[2] \n"
"fmla v23.4s, v13.4s, v4.s[3] \n"
"fmla v24.4s, v12.4s, v5.s[0] \n"
"fmla v26.4s, v12.4s, v5.s[1] \n"
"fmla v28.4s, v12.4s, v5.s[2] \n"
"fmla v30.4s, v12.4s, v5.s[3] \n"
"fmla v25.4s, v13.4s, v5.s[0] \n"
"fmla v27.4s, v13.4s, v5.s[1] \n"
"fmla v29.4s, v13.4s, v5.s[2] \n"
"fmla v31.4s, v13.4s, v5.s[3] \n"
"subs w4, w4, #1 \n"
"fmla v16.4s, v14.4s, v6.s[0] \n"
"fmla v18.4s, v14.4s, v6.s[1] \n"
"fmla v20.4s, v14.4s, v6.s[2] \n"
"fmla v22.4s, v14.4s, v6.s[3] \n"
"fmla v17.4s, v15.4s, v6.s[0] \n"
"fmla v19.4s, v15.4s, v6.s[1] \n"
"fmla v21.4s, v15.4s, v6.s[2] \n"
"fmla v23.4s, v15.4s, v6.s[3] \n"
"fmla v24.4s, v14.4s, v7.s[0] \n"
"fmla v26.4s, v14.4s, v7.s[1] \n"
"fmla v28.4s, v14.4s, v7.s[2] \n"
"fmla v30.4s, v14.4s, v7.s[3] \n"
"fmla v25.4s, v15.4s, v7.s[0] \n"
"fmla v27.4s, v15.4s, v7.s[1] \n"
"fmla v29.4s, v15.4s, v7.s[2] \n"
"fmla v31.4s, v15.4s, v7.s[3] \n"
"bne 0b \n"
"1: \n"
// remain loop
"and w4, %w21, #3 \n" // w4 = remain = inch & 3;
"cmp w4, #0 \n"
"beq 3f \n"
"2: \n"
"prfm pldl1keep, [%8, #128] \n"
"ld1 {v8.4h, v9.4h}, [%8], #16 \n"
"shll v8.4s, v8.4h, #16 \n"
"shll v9.4s, v9.4h, #16 \n"
"prfm pldl1keep, [%9, #128] \n"
"ld1 {v0.4h, v1.4h}, [%9], #16 \n"
"shll v0.4s, v0.4h, #16 \n"
"shll v1.4s, v1.4h, #16 \n"
"fmla v16.4s, v8.4s, v0.s[0] \n"
"fmla v18.4s, v8.4s, v0.s[1] \n"
"fmla v20.4s, v8.4s, v0.s[2] \n"
"fmla v22.4s, v8.4s, v0.s[3] \n"
"fmla v17.4s, v9.4s, v0.s[0] \n"
"fmla v19.4s, v9.4s, v0.s[1] \n"
"fmla v21.4s, v9.4s, v0.s[2] \n"
"fmla v23.4s, v9.4s, v0.s[3] \n"
"subs w4, w4, #1 \n"
"fmla v24.4s, v8.4s, v1.s[0] \n"
"fmla v26.4s, v8.4s, v1.s[1] \n"
"fmla v28.4s, v8.4s, v1.s[2] \n"
"fmla v30.4s, v8.4s, v1.s[3] \n"
"fmla v25.4s, v9.4s, v1.s[0] \n"
"fmla v27.4s, v9.4s, v1.s[1] \n"
"fmla v29.4s, v9.4s, v1.s[2] \n"
"fmla v31.4s, v9.4s, v1.s[3] \n"
"bne 2b \n"
"3: \n"
"shrn v16.4h, v16.4s, #16 \n"
"shrn v17.4h, v17.4s, #16 \n"
"shrn v18.4h, v18.4s, #16 \n"
"shrn v19.4h, v19.4s, #16 \n"
"shrn v20.4h, v20.4s, #16 \n"
"shrn v21.4h, v21.4s, #16 \n"
"shrn v22.4h, v22.4s, #16 \n"
"shrn v23.4h, v23.4s, #16 \n"
"shrn v24.4h, v24.4s, #16 \n"
"shrn v25.4h, v25.4s, #16 \n"
"shrn v26.4h, v26.4s, #16 \n"
"shrn v27.4h, v27.4s, #16 \n"
"shrn v28.4h, v28.4s, #16 \n"
"shrn v29.4h, v29.4s, #16 \n"
"shrn v30.4h, v30.4s, #16 \n"
"shrn v31.4h, v31.4s, #16 \n"
"st1 {v16.4h, v17.4h}, [%0], #16 \n"
"st1 {v18.4h, v19.4h}, [%1], #16 \n"
"st1 {v20.4h, v21.4h}, [%2], #16 \n"
"st1 {v22.4h, v23.4h}, [%3], #16 \n"
"st1 {v24.4h, v25.4h}, [%4], #16 \n"
"st1 {v26.4h, v27.4h}, [%5], #16 \n"
"st1 {v28.4h, v29.4h}, [%6], #16 \n"
"st1 {v30.4h, v31.4h}, [%7], #16 \n"
: "=r"(outptr0), // %0
"=r"(outptr1), // %1
"=r"(outptr2), // %2
"=r"(outptr3), // %3
"=r"(outptr4), // %4
"=r"(outptr5), // %5
"=r"(outptr6), // %6
"=r"(outptr7), // %7
"=r"(tmpptr), // %8
"=r"(kptr) // %9
: "0"(outptr0),
"1"(outptr1),
"2"(outptr2),
"3"(outptr3),
"4"(outptr4),
"5"(outptr5),
"6"(outptr6),
"7"(outptr7),
"8"(tmpptr),
"9"(kptr),
"r"(biasptr), // %20
"r"(inch) // %21
: "cc", "memory", "x4", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23", "v24", "v25", "v26", "v27", "v28", "v29", "v30", "v31");
}
for (; i + 3 < size; i += 4)
{
const unsigned short* tmpptr = tmp.channel(i / 8 + (i % 8) / 4);
const unsigned short* kptr = kernel.channel(p / 8);
asm volatile(
"ld1 {v0.4s, v1.4s}, [%20] \n"
"dup v16.4s, v0.s[0] \n"
"dup v17.4s, v0.s[1] \n"
"dup v18.4s, v0.s[2] \n"
"dup v19.4s, v0.s[3] \n"
"dup v20.4s, v1.s[0] \n"
"dup v21.4s, v1.s[1] \n"
"dup v22.4s, v1.s[2] \n"
"dup v23.4s, v1.s[3] \n"
// inch loop
"lsr w4, %w21, #2 \n" // w4 = nn = inch >> 2
"cmp w4, #0 \n"
"beq 1f \n"
"0: \n"
"prfm pldl1keep, [%8, #256] \n"
"ld1 {v8.4h, v9.4h, v10.4h, v11.4h}, [%8], #32 \n"
"shll v8.4s, v8.4h, #16 \n"
"shll v9.4s, v9.4h, #16 \n"
"shll v10.4s, v10.4h, #16 \n"
"shll v11.4s, v11.4h, #16 \n"
"prfm pldl1keep, [%9, #256] \n"
"ld1 {v0.4h, v1.4h, v2.4h, v3.4h}, [%9], #32 \n"
"shll v0.4s, v0.4h, #16 \n"
"shll v1.4s, v1.4h, #16 \n"
"shll v2.4s, v2.4h, #16 \n"
"shll v3.4s, v3.4h, #16 \n"
"fmla v16.4s, v8.4s, v0.s[0] \n"
"fmla v17.4s, v8.4s, v0.s[1] \n"
"fmla v18.4s, v8.4s, v0.s[2] \n"
"fmla v19.4s, v8.4s, v0.s[3] \n"
"fmla v20.4s, v8.4s, v1.s[0] \n"
"fmla v21.4s, v8.4s, v1.s[1] \n"
"fmla v22.4s, v8.4s, v1.s[2] \n"
"fmla v23.4s, v8.4s, v1.s[3] \n"
"prfm pldl1keep, [%9, #256] \n"
"ld1 {v4.4h, v5.4h, v6.4h, v7.4h}, [%9], #32 \n"
"shll v4.4s, v4.4h, #16 \n"
"shll v5.4s, v5.4h, #16 \n"
"shll v6.4s, v6.4h, #16 \n"
"shll v7.4s, v7.4h, #16 \n"
"fmla v16.4s, v9.4s, v2.s[0] \n"
"fmla v17.4s, v9.4s, v2.s[1] \n"
"fmla v18.4s, v9.4s, v2.s[2] \n"
"fmla v19.4s, v9.4s, v2.s[3] \n"
"fmla v20.4s, v9.4s, v3.s[0] \n"
"fmla v21.4s, v9.4s, v3.s[1] \n"
"fmla v22.4s, v9.4s, v3.s[2] \n"
"fmla v23.4s, v9.4s, v3.s[3] \n"
"subs w4, w4, #1 \n"
"fmla v16.4s, v10.4s, v4.s[0] \n"
"fmla v17.4s, v10.4s, v4.s[1] \n"
"fmla v18.4s, v10.4s, v4.s[2] \n"
"fmla v19.4s, v10.4s, v4.s[3] \n"
"fmla v20.4s, v10.4s, v5.s[0] \n"
"fmla v21.4s, v10.4s, v5.s[1] \n"
"fmla v22.4s, v10.4s, v5.s[2] \n"
"fmla v23.4s, v10.4s, v5.s[3] \n"
"fmla v16.4s, v11.4s, v6.s[0] \n"
"fmla v17.4s, v11.4s, v6.s[1] \n"
"fmla v18.4s, v11.4s, v6.s[2] \n"
"fmla v19.4s, v11.4s, v6.s[3] \n"
"fmla v20.4s, v11.4s, v7.s[0] \n"
"fmla v21.4s, v11.4s, v7.s[1] \n"
"fmla v22.4s, v11.4s, v7.s[2] \n"
"fmla v23.4s, v11.4s, v7.s[3] \n"
"bne 0b \n"
"1: \n"
// remain loop
"and w4, %w21, #3 \n" // w4 = remain = inch & 3;
"cmp w4, #0 \n"
"beq 3f \n"
"2: \n"
"prfm pldl1keep, [%8, #64] \n"
"ld1 {v8.4h}, [%8], #8 \n"
"shll v8.4s, v8.4h, #16 \n"
"prfm pldl1keep, [%9, #128] \n"
"ld1 {v0.4h, v1.4h}, [%9], #16 \n"
"shll v0.4s, v0.4h, #16 \n"
"shll v1.4s, v1.4h, #16 \n"
"fmla v16.4s, v8.4s, v0.s[0] \n"
"fmla v17.4s, v8.4s, v0.s[1] \n"
"fmla v18.4s, v8.4s, v0.s[2] \n"
"fmla v19.4s, v8.4s, v0.s[3] \n"
"subs w4, w4, #1 \n"
"fmla v20.4s, v8.4s, v1.s[0] \n"
"fmla v21.4s, v8.4s, v1.s[1] \n"
"fmla v22.4s, v8.4s, v1.s[2] \n"
"fmla v23.4s, v8.4s, v1.s[3] \n"
"bne 2b \n"
"3: \n"
"shrn v16.4h, v16.4s, #16 \n"
"shrn v17.4h, v17.4s, #16 \n"
"shrn v18.4h, v18.4s, #16 \n"
"shrn v19.4h, v19.4s, #16 \n"
"shrn v20.4h, v20.4s, #16 \n"
"shrn v21.4h, v21.4s, #16 \n"
"shrn v22.4h, v22.4s, #16 \n"
"shrn v23.4h, v23.4s, #16 \n"
"st1 {v16.4h}, [%0], #8 \n"
"st1 {v17.4h}, [%1], #8 \n"
"st1 {v18.4h}, [%2], #8 \n"
"st1 {v19.4h}, [%3], #8 \n"
"st1 {v20.4h}, [%4], #8 \n"
"st1 {v21.4h}, [%5], #8 \n"
"st1 {v22.4h}, [%6], #8 \n"
"st1 {v23.4h}, [%7], #8 \n"
: "=r"(outptr0), // %0
"=r"(outptr1), // %1
"=r"(outptr2), // %2
"=r"(outptr3), // %3
"=r"(outptr4), // %4
"=r"(outptr5), // %5
"=r"(outptr6), // %6
"=r"(outptr7), // %7
"=r"(tmpptr), // %8
"=r"(kptr) // %9
: "0"(outptr0),
"1"(outptr1),
"2"(outptr2),
"3"(outptr3),
"4"(outptr4),
"5"(outptr5),
"6"(outptr6),
"7"(outptr7),
"8"(tmpptr),
"9"(kptr),
"r"(biasptr), // %20
"r"(inch) // %21
: "cc", "memory", "x4", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23");
}
for (; i < size; i++)
{
const unsigned short* tmpptr = tmp.channel(i / 8 + (i % 8) / 4 + i % 4);
const unsigned short* kptr = kernel.channel(p / 8);
asm volatile(
"ld1 {v24.4s, v25.4s}, [%20] \n"
// inch loop
"lsr w4, %w21, #2 \n" // w4 = nn = inch >> 2
"cmp w4, #0 \n"
"beq 1f \n"
"eor v16.16b, v16.16b, v16.16b \n"
"eor v17.16b, v17.16b, v17.16b \n"
"eor v18.16b, v18.16b, v18.16b \n"
"eor v19.16b, v19.16b, v19.16b \n"
"eor v20.16b, v20.16b, v20.16b \n"
"eor v21.16b, v21.16b, v21.16b \n"
"eor v22.16b, v22.16b, v22.16b \n"
"eor v23.16b, v23.16b, v23.16b \n"
"0: \n"
"prfm pldl1keep, [%8, #64] \n"
"ld1 {v8.4h}, [%8], #8 \n"
"shll v8.4s, v8.4h, #16 \n"
"prfm pldl1keep, [%9, #256] \n"
"ld1 {v0.4h, v1.4h, v2.4h, v3.4h}, [%9], #32 \n"
"shll v0.4s, v0.4h, #16 \n"
"shll v1.4s, v1.4h, #16 \n"
"shll v2.4s, v2.4h, #16 \n"
"shll v3.4s, v3.4h, #16 \n"
"fmla v16.4s, v0.4s, v8.s[0] \n"
"fmla v17.4s, v1.4s, v8.s[0] \n"
"fmla v18.4s, v2.4s, v8.s[1] \n"
"fmla v19.4s, v3.4s, v8.s[1] \n"
"prfm pldl1keep, [%9, #256] \n"
"ld1 {v4.4h, v5.4h, v6.4h, v7.4h}, [%9], #32 \n"
"shll v4.4s, v4.4h, #16 \n"
"shll v5.4s, v5.4h, #16 \n"
"shll v6.4s, v6.4h, #16 \n"
"shll v7.4s, v7.4h, #16 \n"
"subs w4, w4, #1 \n"
"fmla v20.4s, v4.4s, v8.s[2] \n"
"fmla v21.4s, v5.4s, v8.s[2] \n"
"fmla v22.4s, v6.4s, v8.s[3] \n"
"fmla v23.4s, v7.4s, v8.s[3] \n"
"bne 0b \n"
"fadd v16.4s, v16.4s, v18.4s \n"
"fadd v17.4s, v17.4s, v19.4s \n"
"fadd v20.4s, v20.4s, v22.4s \n"
"fadd v21.4s, v21.4s, v23.4s \n"
"fadd v16.4s, v16.4s, v20.4s \n"
"fadd v17.4s, v17.4s, v21.4s \n"
"fadd v24.4s, v24.4s, v16.4s \n"
"fadd v25.4s, v25.4s, v17.4s \n"
"1: \n"
// remain loop
"and w4, %w21, #3 \n" // w4 = remain = inch & 3;
"cmp w4, #0 \n"
"beq 3f \n"
"2: \n"
"prfm pldl1keep, [%8, #16] \n"
"ld1r {v8.4h}, [%8], #2 \n"
"shll v8.4s, v8.4h, #16 \n"
"prfm pldl1keep, [%9, #128] \n"
"ld1 {v0.4h, v1.4h}, [%9], #16 \n"
"shll v0.4s, v0.4h, #16 \n"
"shll v1.4s, v1.4h, #16 \n"
"subs w4, w4, #1 \n"
"fmla v24.4s, v8.4s, v0.4s \n"
"fmla v25.4s, v8.4s, v1.4s \n"
"bne 2b \n"
"3: \n"
"shrn v24.4h, v24.4s, #16 \n"
"shrn v25.4h, v25.4s, #16 \n"
"st1 {v24.h}[0],[%0], #2 \n"
"st1 {v24.h}[1],[%1], #2 \n"
"st1 {v24.h}[2],[%2], #2 \n"
"st1 {v24.h}[3],[%3], #2 \n"
"st1 {v25.h}[0],[%4], #2 \n"
"st1 {v25.h}[1],[%5], #2 \n"
"st1 {v25.h}[2],[%6], #2 \n"
"st1 {v25.h}[3],[%7], #2 \n"
: "=r"(outptr0), // %0
"=r"(outptr1), // %1
"=r"(outptr2), // %2
"=r"(outptr3), // %3
"=r"(outptr4), // %4
"=r"(outptr5), // %5
"=r"(outptr6), // %6
"=r"(outptr7), // %7
"=r"(tmpptr), // %8
"=r"(kptr) // %9
: "0"(outptr0),
"1"(outptr1),
"2"(outptr2),
"3"(outptr3),
"4"(outptr4),
"5"(outptr5),
"6"(outptr6),
"7"(outptr7),
"8"(tmpptr),
"9"(kptr),
"r"(biasptr), // %20
"r"(inch) // %21
: "cc", "memory", "x4", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23", "v24", "v25");
}
}
#endif // __ARM_NEON && __aarch64__
nn_outch = (outch - remain_outch_start) >> 2;
#pragma omp parallel for num_threads(opt.num_threads)
for (int pp = 0; pp < nn_outch; pp++)
{
int p = remain_outch_start + pp * 4;
unsigned short* outptr0 = top_blob.channel(p);
unsigned short* outptr1 = top_blob.channel(p + 1);
unsigned short* outptr2 = top_blob.channel(p + 2);
unsigned short* outptr3 = top_blob.channel(p + 3);
const float zeros[4] = {0.f, 0.f, 0.f, 0.f};
const float* biasptr = bias ? bias + p : zeros;
int i = 0;
for (; i + 7 < size; i += 8)
{
const unsigned short* tmpptr = tmp.channel(i / 8);
#if __ARM_NEON && __aarch64__
const unsigned short* kptr = kernel.channel(p / 8 + (p % 8) / 4);
#else
const unsigned short* kptr = kernel.channel(p / 4);
#endif // __ARM_NEON && __aarch64__
#if __ARM_NEON
#if __aarch64__
asm volatile(
"ld1 {v0.4s}, [%12] \n"
"dup v8.4s, v0.s[0] \n"
"dup v9.4s, v0.s[0] \n"
"dup v10.4s, v0.s[1] \n"
"dup v11.4s, v0.s[1] \n"
"dup v12.4s, v0.s[2] \n"
"dup v13.4s, v0.s[2] \n"
"dup v14.4s, v0.s[3] \n"
"dup v15.4s, v0.s[3] \n"
// inch loop
"lsr w4, %w13, #2 \n" // w4 = nn = inch >> 2
"cmp w4, #0 \n"
"beq 1f \n"
"0: \n"
"prfm pldl1keep, [%4, #256] \n"
"ld1 {v4.4h, v5.4h, v6.4h, v7.4h}, [%4], #32 \n"
"shll v4.4s, v4.4h, #16 \n"
"shll v5.4s, v5.4h, #16 \n"
"shll v6.4s, v6.4h, #16 \n"
"shll v7.4s, v7.4h, #16 \n"
"prfm pldl1keep, [%5, #256] \n"
"ld1 {v0.4h, v1.4h, v2.4h, v3.4h}, [%5], #32 \n"
"shll v0.4s, v0.4h, #16 \n"
"shll v1.4s, v1.4h, #16 \n"
"shll v2.4s, v2.4h, #16 \n"
"shll v3.4s, v3.4h, #16 \n"
"fmla v8.4s, v4.4s, v0.s[0] \n"
"fmla v10.4s, v4.4s, v0.s[1] \n"
"fmla v12.4s, v4.4s, v0.s[2] \n"
"fmla v14.4s, v4.4s, v0.s[3] \n"
"fmla v9.4s, v5.4s, v0.s[0] \n"
"fmla v11.4s, v5.4s, v0.s[1] \n"
"fmla v13.4s, v5.4s, v0.s[2] \n"
"fmla v15.4s, v5.4s, v0.s[3] \n"
"prfm pldl1keep, [%4, #256] \n"
"ld1 {v16.4h, v17.4h, v18.4h, v19.4h}, [%4], #32 \n"
"shll v16.4s, v16.4h, #16 \n"
"shll v17.4s, v17.4h, #16 \n"
"shll v18.4s, v18.4h, #16 \n"
"shll v19.4s, v19.4h, #16 \n"
"fmla v8.4s, v6.4s, v1.s[0] \n"
"fmla v10.4s, v6.4s, v1.s[1] \n"
"fmla v12.4s, v6.4s, v1.s[2] \n"
"fmla v14.4s, v6.4s, v1.s[3] \n"
"fmla v9.4s, v7.4s, v1.s[0] \n"
"fmla v11.4s, v7.4s, v1.s[1] \n"
"fmla v13.4s, v7.4s, v1.s[2] \n"
"fmla v15.4s, v7.4s, v1.s[3] \n"
"subs w4, w4, #1 \n"
"fmla v8.4s, v16.4s, v2.s[0] \n"
"fmla v10.4s, v16.4s, v2.s[1] \n"
"fmla v12.4s, v16.4s, v2.s[2] \n"
"fmla v14.4s, v16.4s, v2.s[3] \n"
"fmla v9.4s, v17.4s, v2.s[0] \n"
"fmla v11.4s, v17.4s, v2.s[1] \n"
"fmla v13.4s, v17.4s, v2.s[2] \n"
"fmla v15.4s, v17.4s, v2.s[3] \n"
"fmla v8.4s, v18.4s, v3.s[0] \n"
"fmla v10.4s, v18.4s, v3.s[1] \n"
"fmla v12.4s, v18.4s, v3.s[2] \n"
"fmla v14.4s, v18.4s, v3.s[3] \n"
"fmla v9.4s, v19.4s, v3.s[0] \n"
"fmla v11.4s, v19.4s, v3.s[1] \n"
"fmla v13.4s, v19.4s, v3.s[2] \n"
"fmla v15.4s, v19.4s, v3.s[3] \n"
"bne 0b \n"
"1: \n"
// remain loop
"and w4, %w13, #3 \n" // w4 = remain = inch & 3;
"cmp w4, #0 \n"
"beq 3f \n"
"2: \n"
"prfm pldl1keep, [%4, #128] \n"
"ld1 {v4.4h, v5.4h}, [%4], #16 \n"
"shll v4.4s, v4.4h, #16 \n"
"shll v5.4s, v5.4h, #16 \n"
"prfm pldl1keep, [%5, #64] \n"
"ld1 {v0.4h}, [%5], #8 \n"
"shll v0.4s, v0.4h, #16 \n"
"fmla v8.4s, v4.4s, v0.s[0] \n"
"fmla v10.4s, v4.4s, v0.s[1] \n"
"fmla v12.4s, v4.4s, v0.s[2] \n"
"fmla v14.4s, v4.4s, v0.s[3] \n"
"subs w4, w4, #1 \n"
"fmla v9.4s, v5.4s, v0.s[0] \n"
"fmla v11.4s, v5.4s, v0.s[1] \n"
"fmla v13.4s, v5.4s, v0.s[2] \n"
"fmla v15.4s, v5.4s, v0.s[3] \n"
"bne 2b \n"
"3: \n"
"shrn v8.4h, v8.4s, #16 \n"
"shrn v9.4h, v9.4s, #16 \n"
"shrn v10.4h, v10.4s, #16 \n"
"shrn v11.4h, v11.4s, #16 \n"
"shrn v12.4h, v12.4s, #16 \n"
"shrn v13.4h, v13.4s, #16 \n"
"shrn v14.4h, v14.4s, #16 \n"
"shrn v15.4h, v15.4s, #16 \n"
"st1 {v8.4h, v9.4h}, [%0], #16 \n"
"st1 {v10.4h, v11.4h}, [%1], #16 \n"
"st1 {v12.4h, v13.4h}, [%2], #16 \n"
"st1 {v14.4h, v15.4h}, [%3], #16 \n"
: "=r"(outptr0), // %0
"=r"(outptr1), // %1
"=r"(outptr2), // %2
"=r"(outptr3), // %3
"=r"(tmpptr), // %4
"=r"(kptr) // %5
: "0"(outptr0),
"1"(outptr1),
"2"(outptr2),
"3"(outptr3),
"4"(tmpptr),
"5"(kptr),
"r"(biasptr), // %12
"r"(inch) // %13
: "cc", "memory", "x4", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19");
#else // __aarch64__
asm volatile(
"vld1.f32 {d0-d1}, [%12] \n"
"vdup.f32 q8, d0[0] \n"
"vdup.f32 q9, d0[0] \n"
"vdup.f32 q10, d0[1] \n"
"vdup.f32 q11, d0[1] \n"
"vdup.f32 q12, d1[0] \n"
"vdup.f32 q13, d1[0] \n"
"vdup.f32 q14, d1[1] \n"
"vdup.f32 q15, d1[1] \n"
// inch loop
"lsr r4, %13, #2 \n" // r4 = nn = inch >> 2
"cmp r4, #0 \n"
"beq 1f \n"
"0: \n"
"pld [%4, #256] \n"
"vld1.u16 {d12-d15}, [%4 :64]! \n"
"vshll.u16 q4, d12, #16 \n"
"vshll.u16 q5, d13, #16 \n"
"vshll.u16 q6, d14, #16 \n"
"vshll.u16 q7, d15, #16 \n"
"pld [%5, #256] \n"
"vld1.u16 {d4-d7}, [%5 :64]! \n"
"vshll.u16 q0, d4, #16 \n"
"vshll.u16 q1, d5, #16 \n"
"vshll.u16 q2, d6, #16 \n"
"vshll.u16 q3, d7, #16 \n"
"vmla.f32 q8, q4, d0[0] \n"
"vmla.f32 q10, q4, d0[1] \n"
"vmla.f32 q12, q4, d1[0] \n"
"vmla.f32 q14, q4, d1[1] \n"
"vmla.f32 q9, q5, d0[0] \n"
"vmla.f32 q11, q5, d0[1] \n"
"vmla.f32 q13, q5, d1[0] \n"
"vmla.f32 q15, q5, d1[1] \n"
"vmla.f32 q8, q6, d2[0] \n"
"vmla.f32 q10, q6, d2[1] \n"
"vmla.f32 q12, q6, d3[0] \n"
"vmla.f32 q14, q6, d3[1] \n"
"vmla.f32 q9, q7, d2[0] \n"
"vmla.f32 q11, q7, d2[1] \n"
"vmla.f32 q13, q7, d3[0] \n"
"vmla.f32 q15, q7, d3[1] \n"
"pld [%4, #256] \n"
"vld1.u16 {d12-d15}, [%4 :64]! \n"
"vshll.u16 q4, d12, #16 \n"
"vshll.u16 q5, d13, #16 \n"
"vshll.u16 q6, d14, #16 \n"
"vshll.u16 q7, d15, #16 \n"
"vmla.f32 q8, q4, d4[0] \n"
"vmla.f32 q10, q4, d4[1] \n"
"vmla.f32 q12, q4, d5[0] \n"
"vmla.f32 q14, q4, d5[1] \n"
"vmla.f32 q9, q5, d4[0] \n"
"vmla.f32 q11, q5, d4[1] \n"
"vmla.f32 q13, q5, d5[0] \n"
"vmla.f32 q15, q5, d5[1] \n"
"subs r4, r4, #1 \n"
"vmla.f32 q8, q6, d6[0] \n"
"vmla.f32 q10, q6, d6[1] \n"
"vmla.f32 q12, q6, d7[0] \n"
"vmla.f32 q14, q6, d7[1] \n"
"vmla.f32 q9, q7, d6[0] \n"
"vmla.f32 q11, q7, d6[1] \n"
"vmla.f32 q13, q7, d7[0] \n"
"vmla.f32 q15, q7, d7[1] \n"
"bne 0b \n"
"1: \n"
// remain loop
"and r4, %13, #3 \n" // r4 = remain = inch & 3;
"cmp r4, #0 \n"
"beq 3f \n"
"2: \n"
"pld [%4, #128] \n"
"vld1.u16 {d10-d11}, [%4 :64]! \n"
"vshll.u16 q4, d10, #16 \n"
"vshll.u16 q5, d11, #16 \n"
"pld [%5, #64] \n"
"vld1.u16 {d1}, [%5 :64]! \n"
"vshll.u16 q0, d1, #16 \n"
"vmla.f32 q8, q4, d0[0] \n"
"vmla.f32 q10, q4, d0[1] \n"
"vmla.f32 q12, q4, d1[0] \n"
"vmla.f32 q14, q4, d1[1] \n"
"subs r4, r4, #1 \n"
"vmla.f32 q9, q5, d0[0] \n"
"vmla.f32 q11, q5, d0[1] \n"
"vmla.f32 q13, q5, d1[0] \n"
"vmla.f32 q15, q5, d1[1] \n"
"bne 2b \n"
"3: \n"
"vshrn.u32 d16, q8, #16 \n"
"vshrn.u32 d17, q9, #16 \n"
"vshrn.u32 d20, q10, #16 \n"
"vshrn.u32 d21, q11, #16 \n"
"vshrn.u32 d24, q12, #16 \n"
"vshrn.u32 d25, q13, #16 \n"
"vshrn.u32 d28, q14, #16 \n"
"vshrn.u32 d29, q15, #16 \n"
"vst1.u16 {d16-d17}, [%0 :64]! \n"
"vst1.u16 {d20-d21}, [%1 :64]! \n"
"vst1.u16 {d24-d25}, [%2 :64]! \n"
"vst1.u16 {d28-d29}, [%3 :64]! \n"
: "=r"(outptr0), // %0
"=r"(outptr1), // %1
"=r"(outptr2), // %2
"=r"(outptr3), // %3
"=r"(tmpptr), // %4
"=r"(kptr) // %5
: "0"(outptr0),
"1"(outptr1),
"2"(outptr2),
"3"(outptr3),
"4"(tmpptr),
"5"(kptr),
"r"(biasptr), // %12
"r"(inch) // %13
: "cc", "memory", "r4", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15");
#endif // __aarch64__
#else
float sum0_0 = biasptr[0];
float sum0_1 = biasptr[0];
float sum0_2 = biasptr[0];
float sum0_3 = biasptr[0];
float sum0_4 = biasptr[0];
float sum0_5 = biasptr[0];
float sum0_6 = biasptr[0];
float sum0_7 = biasptr[0];
float sum1_0 = biasptr[1];
float sum1_1 = biasptr[1];
float sum1_2 = biasptr[1];
float sum1_3 = biasptr[1];
float sum1_4 = biasptr[1];
float sum1_5 = biasptr[1];
float sum1_6 = biasptr[1];
float sum1_7 = biasptr[1];
float sum2_0 = biasptr[2];
float sum2_1 = biasptr[2];
float sum2_2 = biasptr[2];
float sum2_3 = biasptr[2];
float sum2_4 = biasptr[2];
float sum2_5 = biasptr[2];
float sum2_6 = biasptr[2];
float sum2_7 = biasptr[2];
float sum3_0 = biasptr[3];
float sum3_1 = biasptr[3];
float sum3_2 = biasptr[3];
float sum3_3 = biasptr[3];
float sum3_4 = biasptr[3];
float sum3_5 = biasptr[3];
float sum3_6 = biasptr[3];
float sum3_7 = biasptr[3];
for (int q = 0; q < inch; q++)
{
sum0_0 += bfloat16_to_float32(tmpptr[0]) * bfloat16_to_float32(kptr[0]);
sum0_1 += bfloat16_to_float32(tmpptr[1]) * bfloat16_to_float32(kptr[0]);
sum0_2 += bfloat16_to_float32(tmpptr[2]) * bfloat16_to_float32(kptr[0]);
sum0_3 += bfloat16_to_float32(tmpptr[3]) * bfloat16_to_float32(kptr[0]);
sum0_4 += bfloat16_to_float32(tmpptr[4]) * bfloat16_to_float32(kptr[0]);
sum0_5 += bfloat16_to_float32(tmpptr[5]) * bfloat16_to_float32(kptr[0]);
sum0_6 += bfloat16_to_float32(tmpptr[6]) * bfloat16_to_float32(kptr[0]);
sum0_7 += bfloat16_to_float32(tmpptr[7]) * bfloat16_to_float32(kptr[0]);
sum1_0 += bfloat16_to_float32(tmpptr[0]) * bfloat16_to_float32(kptr[1]);
sum1_1 += bfloat16_to_float32(tmpptr[1]) * bfloat16_to_float32(kptr[1]);
sum1_2 += bfloat16_to_float32(tmpptr[2]) * bfloat16_to_float32(kptr[1]);
sum1_3 += bfloat16_to_float32(tmpptr[3]) * bfloat16_to_float32(kptr[1]);
sum1_4 += bfloat16_to_float32(tmpptr[4]) * bfloat16_to_float32(kptr[1]);
sum1_5 += bfloat16_to_float32(tmpptr[5]) * bfloat16_to_float32(kptr[1]);
sum1_6 += bfloat16_to_float32(tmpptr[6]) * bfloat16_to_float32(kptr[1]);
sum1_7 += bfloat16_to_float32(tmpptr[7]) * bfloat16_to_float32(kptr[1]);
sum2_0 += bfloat16_to_float32(tmpptr[0]) * bfloat16_to_float32(kptr[2]);
sum2_1 += bfloat16_to_float32(tmpptr[1]) * bfloat16_to_float32(kptr[2]);
sum2_2 += bfloat16_to_float32(tmpptr[2]) * bfloat16_to_float32(kptr[2]);
sum2_3 += bfloat16_to_float32(tmpptr[3]) * bfloat16_to_float32(kptr[2]);
sum2_4 += bfloat16_to_float32(tmpptr[4]) * bfloat16_to_float32(kptr[2]);
sum2_5 += bfloat16_to_float32(tmpptr[5]) * bfloat16_to_float32(kptr[2]);
sum2_6 += bfloat16_to_float32(tmpptr[6]) * bfloat16_to_float32(kptr[2]);
sum2_7 += bfloat16_to_float32(tmpptr[7]) * bfloat16_to_float32(kptr[2]);
sum3_0 += bfloat16_to_float32(tmpptr[0]) * bfloat16_to_float32(kptr[3]);
sum3_1 += bfloat16_to_float32(tmpptr[1]) * bfloat16_to_float32(kptr[3]);
sum3_2 += bfloat16_to_float32(tmpptr[2]) * bfloat16_to_float32(kptr[3]);
sum3_3 += bfloat16_to_float32(tmpptr[3]) * bfloat16_to_float32(kptr[3]);
sum3_4 += bfloat16_to_float32(tmpptr[4]) * bfloat16_to_float32(kptr[3]);
sum3_5 += bfloat16_to_float32(tmpptr[5]) * bfloat16_to_float32(kptr[3]);
sum3_6 += bfloat16_to_float32(tmpptr[6]) * bfloat16_to_float32(kptr[3]);
sum3_7 += bfloat16_to_float32(tmpptr[7]) * bfloat16_to_float32(kptr[3]);
tmpptr += 8;
kptr += 4;
}
outptr0[0] = float32_to_bfloat16(sum0_0);
outptr0[1] = float32_to_bfloat16(sum0_1);
outptr0[2] = float32_to_bfloat16(sum0_2);
outptr0[3] = float32_to_bfloat16(sum0_3);
outptr0[4] = float32_to_bfloat16(sum0_4);
outptr0[5] = float32_to_bfloat16(sum0_5);
outptr0[6] = float32_to_bfloat16(sum0_6);
outptr0[7] = float32_to_bfloat16(sum0_7);
outptr1[0] = float32_to_bfloat16(sum1_0);
outptr1[1] = float32_to_bfloat16(sum1_1);
outptr1[2] = float32_to_bfloat16(sum1_2);
outptr1[3] = float32_to_bfloat16(sum1_3);
outptr1[4] = float32_to_bfloat16(sum1_4);
outptr1[5] = float32_to_bfloat16(sum1_5);
outptr1[6] = float32_to_bfloat16(sum1_6);
outptr1[7] = float32_to_bfloat16(sum1_7);
outptr2[0] = float32_to_bfloat16(sum2_0);
outptr2[1] = float32_to_bfloat16(sum2_1);
outptr2[2] = float32_to_bfloat16(sum2_2);
outptr2[3] = float32_to_bfloat16(sum2_3);
outptr2[4] = float32_to_bfloat16(sum2_4);
outptr2[5] = float32_to_bfloat16(sum2_5);
outptr2[6] = float32_to_bfloat16(sum2_6);
outptr2[7] = float32_to_bfloat16(sum2_7);
outptr3[0] = float32_to_bfloat16(sum3_0);
outptr3[1] = float32_to_bfloat16(sum3_1);
outptr3[2] = float32_to_bfloat16(sum3_2);
outptr3[3] = float32_to_bfloat16(sum3_3);
outptr3[4] = float32_to_bfloat16(sum3_4);
outptr3[5] = float32_to_bfloat16(sum3_5);
outptr3[6] = float32_to_bfloat16(sum3_6);
outptr3[7] = float32_to_bfloat16(sum3_7);
outptr0 += 8;
outptr1 += 8;
outptr2 += 8;
outptr3 += 8;
#endif // __ARM_NEON
}
for (; i + 3 < size; i += 4)
{
const unsigned short* tmpptr = tmp.channel(i / 8 + (i % 8) / 4);
#if __ARM_NEON && __aarch64__
const unsigned short* kptr = kernel.channel(p / 8 + (p % 8) / 4);
#else
const unsigned short* kptr = kernel.channel(p / 4);
#endif // __ARM_NEON && __aarch64__
#if __ARM_NEON
#if __aarch64__
asm volatile(
"ld1 {v0.4s}, [%12] \n"
"dup v8.4s, v0.s[0] \n"
"dup v9.4s, v0.s[1] \n"
"dup v10.4s, v0.s[2] \n"
"dup v11.4s, v0.s[3] \n"
// inch loop
"lsr w4, %w13, #2 \n" // w4 = nn = inch >> 2
"cmp w4, #0 \n"
"beq 1f \n"
"0: \n"
"prfm pldl1keep, [%4, #256] \n"
"ld1 {v4.4h, v5.4h, v6.4h, v7.4h}, [%4], #32 \n"
"shll v4.4s, v4.4h, #16 \n"
"shll v5.4s, v5.4h, #16 \n"
"shll v6.4s, v6.4h, #16 \n"
"shll v7.4s, v7.4h, #16 \n"
"prfm pldl1keep, [%5, #256] \n"
"ld1 {v0.4h, v1.4h, v2.4h, v3.4h}, [%5], #32 \n"
"shll v0.4s, v0.4h, #16 \n"
"shll v1.4s, v1.4h, #16 \n"
"shll v2.4s, v2.4h, #16 \n"
"shll v3.4s, v3.4h, #16 \n"
"fmla v8.4s, v4.4s, v0.s[0] \n"
"fmla v9.4s, v4.4s, v0.s[1] \n"
"fmla v10.4s, v4.4s, v0.s[2] \n"
"fmla v11.4s, v4.4s, v0.s[3] \n"
"fmla v8.4s, v5.4s, v1.s[0] \n"
"fmla v9.4s, v5.4s, v1.s[1] \n"
"fmla v10.4s, v5.4s, v1.s[2] \n"
"fmla v11.4s, v5.4s, v1.s[3] \n"
"subs w4, w4, #1 \n"
"fmla v8.4s, v6.4s, v2.s[0] \n"
"fmla v9.4s, v6.4s, v2.s[1] \n"
"fmla v10.4s, v6.4s, v2.s[2] \n"
"fmla v11.4s, v6.4s, v2.s[3] \n"
"fmla v8.4s, v7.4s, v3.s[0] \n"
"fmla v9.4s, v7.4s, v3.s[1] \n"
"fmla v10.4s, v7.4s, v3.s[2] \n"
"fmla v11.4s, v7.4s, v3.s[3] \n"
"bne 0b \n"
"1: \n"
// remain loop
"and w4, %w13, #3 \n" // w4 = remain = inch & 3;
"cmp w4, #0 \n"
"beq 3f \n"
"2: \n"
"prfm pldl1keep, [%4, #64] \n"
"ld1 {v4.4h}, [%4], #8 \n"
"shll v4.4s, v4.4h, #16 \n"
"prfm pldl1keep, [%5, #64] \n"
"ld1 {v0.4h}, [%5], #8 \n"
"shll v0.4s, v0.4h, #16 \n"
"subs w4, w4, #1 \n"
"fmla v8.4s, v4.4s, v0.s[0] \n"
"fmla v9.4s, v4.4s, v0.s[1] \n"
"fmla v10.4s, v4.4s, v0.s[2] \n"
"fmla v11.4s, v4.4s, v0.s[3] \n"
"bne 2b \n"
"3: \n"
"shrn v8.4h, v8.4s, #16 \n"
"shrn v9.4h, v9.4s, #16 \n"
"shrn v10.4h, v10.4s, #16 \n"
"shrn v11.4h, v11.4s, #16 \n"
"st1 {v8.4h}, [%0], #8 \n"
"st1 {v9.4h}, [%1], #8 \n"
"st1 {v10.4h}, [%2], #8 \n"
"st1 {v11.4h}, [%3], #8 \n"
: "=r"(outptr0), // %0
"=r"(outptr1), // %1
"=r"(outptr2), // %2
"=r"(outptr3), // %3
"=r"(tmpptr), // %4
"=r"(kptr) // %5
: "0"(outptr0),
"1"(outptr1),
"2"(outptr2),
"3"(outptr3),
"4"(tmpptr),
"5"(kptr),
"r"(biasptr), // %12
"r"(inch) // %13
: "cc", "memory", "x4", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11");
#else // __aarch64__
asm volatile(
"vld1.f32 {d0-d1}, [%12] \n"
"vdup.f32 q8, d0[0] \n"
"vdup.f32 q9, d0[1] \n"
"vdup.f32 q10, d1[0] \n"
"vdup.f32 q11, d1[1] \n"
// inch loop
"lsr r4, %13, #2 \n" // r4 = nn = inch >> 2
"cmp r4, #0 \n"
"beq 1f \n"
"0: \n"
"pld [%4, #256] \n"
"vld1.u16 {d12-d15}, [%4 :64]! \n"
"vshll.u16 q4, d12, #16 \n"
"vshll.u16 q5, d13, #16 \n"
"vshll.u16 q6, d14, #16 \n"
"vshll.u16 q7, d15, #16 \n"
"pld [%5, #256] \n"
"vld1.u16 {d4-d7}, [%5 :64]! \n"
"vshll.u16 q0, d4, #16 \n"
"vshll.u16 q1, d5, #16 \n"
"vshll.u16 q2, d6, #16 \n"
"vshll.u16 q3, d7, #16 \n"
"vmla.f32 q8, q4, d0[0] \n"
"vmla.f32 q9, q4, d0[1] \n"
"vmla.f32 q10, q4, d1[0] \n"
"vmla.f32 q11, q4, d1[1] \n"
"vmla.f32 q8, q5, d2[0] \n"
"vmla.f32 q9, q5, d2[1] \n"
"vmla.f32 q10, q5, d3[0] \n"
"vmla.f32 q11, q5, d3[1] \n"
"subs r4, r4, #1 \n"
"vmla.f32 q8, q6, d4[0] \n"
"vmla.f32 q9, q6, d4[1] \n"
"vmla.f32 q10, q6, d5[0] \n"
"vmla.f32 q11, q6, d5[1] \n"
"vmla.f32 q8, q7, d6[0] \n"
"vmla.f32 q9, q7, d6[1] \n"
"vmla.f32 q10, q7, d7[0] \n"
"vmla.f32 q11, q7, d7[1] \n"
"bne 0b \n"
"1: \n"
// remain loop
"and r4, %13, #3 \n" // r4 = remain = inch & 3;
"cmp r4, #0 \n"
"beq 3f \n"
"2: \n"
"pld [%4, #64] \n"
"vld1.u16 {d9}, [%4 :64]! \n"
"vshll.u16 q4, d9, #16 \n"
"pld [%5, #64] \n"
"vld1.u16 {d1}, [%5 :64]! \n"
"vshll.u16 q0, d1, #16 \n"
"subs r4, r4, #1 \n"
"vmla.f32 q8, q4, d0[0] \n"
"vmla.f32 q9, q4, d0[1] \n"
"vmla.f32 q10, q4, d1[0] \n"
"vmla.f32 q11, q4, d1[1] \n"
"bne 2b \n"
"3: \n"
"vshrn.u32 d16, q8, #16 \n"
"vshrn.u32 d18, q9, #16 \n"
"vshrn.u32 d20, q10, #16 \n"
"vshrn.u32 d22, q11, #16 \n"
"vst1.u16 {d16}, [%0 :64]! \n"
"vst1.u16 {d18}, [%1 :64]! \n"
"vst1.u16 {d20}, [%2 :64]! \n"
"vst1.u16 {d22}, [%3 :64]! \n"
: "=r"(outptr0), // %0
"=r"(outptr1), // %1
"=r"(outptr2), // %2
"=r"(outptr3), // %3
"=r"(tmpptr), // %4
"=r"(kptr) // %5
: "0"(outptr0),
"1"(outptr1),
"2"(outptr2),
"3"(outptr3),
"4"(tmpptr),
"5"(kptr),
"r"(biasptr), // %12
"r"(inch) // %13
: "cc", "memory", "r4", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11");
#endif // __aarch64__
#else
float sum0_0 = biasptr[0];
float sum0_1 = biasptr[0];
float sum0_2 = biasptr[0];
float sum0_3 = biasptr[0];
float sum1_0 = biasptr[1];
float sum1_1 = biasptr[1];
float sum1_2 = biasptr[1];
float sum1_3 = biasptr[1];
float sum2_0 = biasptr[2];
float sum2_1 = biasptr[2];
float sum2_2 = biasptr[2];
float sum2_3 = biasptr[2];
float sum3_0 = biasptr[3];
float sum3_1 = biasptr[3];
float sum3_2 = biasptr[3];
float sum3_3 = biasptr[3];
for (int q = 0; q < inch; q++)
{
sum0_0 += bfloat16_to_float32(tmpptr[0]) * bfloat16_to_float32(kptr[0]);
sum0_1 += bfloat16_to_float32(tmpptr[1]) * bfloat16_to_float32(kptr[0]);
sum0_2 += bfloat16_to_float32(tmpptr[2]) * bfloat16_to_float32(kptr[0]);
sum0_3 += bfloat16_to_float32(tmpptr[3]) * bfloat16_to_float32(kptr[0]);
sum1_0 += bfloat16_to_float32(tmpptr[0]) * bfloat16_to_float32(kptr[1]);
sum1_1 += bfloat16_to_float32(tmpptr[1]) * bfloat16_to_float32(kptr[1]);
sum1_2 += bfloat16_to_float32(tmpptr[2]) * bfloat16_to_float32(kptr[1]);
sum1_3 += bfloat16_to_float32(tmpptr[3]) * bfloat16_to_float32(kptr[1]);
sum2_0 += bfloat16_to_float32(tmpptr[0]) * bfloat16_to_float32(kptr[2]);
sum2_1 += bfloat16_to_float32(tmpptr[1]) * bfloat16_to_float32(kptr[2]);
sum2_2 += bfloat16_to_float32(tmpptr[2]) * bfloat16_to_float32(kptr[2]);
sum2_3 += bfloat16_to_float32(tmpptr[3]) * bfloat16_to_float32(kptr[2]);
sum3_0 += bfloat16_to_float32(tmpptr[0]) * bfloat16_to_float32(kptr[3]);
sum3_1 += bfloat16_to_float32(tmpptr[1]) * bfloat16_to_float32(kptr[3]);
sum3_2 += bfloat16_to_float32(tmpptr[2]) * bfloat16_to_float32(kptr[3]);
sum3_3 += bfloat16_to_float32(tmpptr[3]) * bfloat16_to_float32(kptr[3]);
tmpptr += 4;
kptr += 4;
}
outptr0[0] = float32_to_bfloat16(sum0_0);
outptr0[1] = float32_to_bfloat16(sum0_1);
outptr0[2] = float32_to_bfloat16(sum0_2);
outptr0[3] = float32_to_bfloat16(sum0_3);
outptr1[0] = float32_to_bfloat16(sum1_0);
outptr1[1] = float32_to_bfloat16(sum1_1);
outptr1[2] = float32_to_bfloat16(sum1_2);
outptr1[3] = float32_to_bfloat16(sum1_3);
outptr2[0] = float32_to_bfloat16(sum2_0);
outptr2[1] = float32_to_bfloat16(sum2_1);
outptr2[2] = float32_to_bfloat16(sum2_2);
outptr2[3] = float32_to_bfloat16(sum2_3);
outptr3[0] = float32_to_bfloat16(sum3_0);
outptr3[1] = float32_to_bfloat16(sum3_1);
outptr3[2] = float32_to_bfloat16(sum3_2);
outptr3[3] = float32_to_bfloat16(sum3_3);
outptr0 += 4;
outptr1 += 4;
outptr2 += 4;
outptr3 += 4;
#endif // __ARM_NEON
}
for (; i < size; i++)
{
const unsigned short* tmpptr = tmp.channel(i / 8 + (i % 8) / 4 + i % 4);
#if __ARM_NEON && __aarch64__
const unsigned short* kptr = kernel.channel(p / 8 + (p % 8) / 4);
#else
const unsigned short* kptr = kernel.channel(p / 4);
#endif // __ARM_NEON && __aarch64__
#if __ARM_NEON
#if __aarch64__
asm volatile(
"ld1 {v12.4s}, [%12] \n"
// inch loop
"lsr w4, %w13, #2 \n" // w4 = nn = inch >> 2
"cmp w4, #0 \n"
"beq 1f \n"
"eor v8.16b, v8.16b, v8.16b \n"
"eor v9.16b, v9.16b, v9.16b \n"
"eor v10.16b, v10.16b, v10.16b \n"
"eor v11.16b, v11.16b, v11.16b \n"
"0: \n"
"prfm pldl1keep, [%4, #64] \n"
"ld1 {v4.4h}, [%4], #8 \n"
"shll v4.4s, v4.4h, #16 \n"
"prfm pldl1keep, [%5, #256] \n"
"ld1 {v0.4h, v1.4h, v2.4h, v3.4h}, [%5], #32 \n"
"shll v0.4s, v0.4h, #16 \n"
"shll v1.4s, v1.4h, #16 \n"
"shll v2.4s, v2.4h, #16 \n"
"shll v3.4s, v3.4h, #16 \n"
"subs w4, w4, #1 \n"
"fmla v8.4s, v0.4s, v4.s[0] \n"
"fmla v9.4s, v1.4s, v4.s[1] \n"
"fmla v10.4s, v2.4s, v4.s[2] \n"
"fmla v11.4s, v3.4s, v4.s[3] \n"
"bne 0b \n"
"fadd v8.4s, v8.4s, v9.4s \n"
"fadd v10.4s, v10.4s, v11.4s \n"
"fadd v8.4s, v8.4s, v10.4s \n"
"fadd v12.4s, v12.4s, v8.4s \n"
"1: \n"
// remain loop
"and w4, %w13, #3 \n" // w4 = remain = inch & 3;
"cmp w4, #0 \n"
"beq 3f \n"
"2: \n"
"prfm pldl1keep, [%4, #16] \n"
"ld1r {v4.4h}, [%4], #2 \n"
"shll v4.4s, v4.4h, #16 \n"
"prfm pldl1keep, [%5, #64] \n"
"ld1 {v0.4h}, [%5], #8 \n"
"shll v0.4s, v0.4h, #16 \n"
"subs w4, w4, #1 \n"
"fmla v12.4s, v4.4s, v0.4s \n"
"bne 2b \n"
"3: \n"
"shrn v12.4h, v12.4s, #16 \n"
"st1 {v12.h}[0], [%0], #2 \n"
"st1 {v12.h}[1], [%1], #2 \n"
"st1 {v12.h}[2], [%2], #2 \n"
"st1 {v12.h}[3], [%3], #2 \n"
: "=r"(outptr0), // %0
"=r"(outptr1), // %1
"=r"(outptr2), // %2
"=r"(outptr3), // %3
"=r"(tmpptr), // %4
"=r"(kptr) // %5
: "0"(outptr0),
"1"(outptr1),
"2"(outptr2),
"3"(outptr3),
"4"(tmpptr),
"5"(kptr),
"r"(biasptr), // %12
"r"(inch) // %13
: "cc", "memory", "x4", "v0", "v1", "v2", "v3", "v4", "v8", "v9", "v10", "v11", "v12");
#else // __aarch64__
asm volatile(
"vld1.f32 {d24-d25}, [%12] \n"
// inch loop
"lsr r4, %13, #2 \n" // r4 = nn = inch >> 2
"cmp r4, #0 \n"
"beq 1f \n"
"veor q8, q8, q8 \n"
"veor q9, q9, q9 \n"
"veor q10, q10, q10 \n"
"veor q11, q11, q11 \n"
"0: \n"
"pld [%4, #64] \n"
"vld1.u16 {d9}, [%4 :64]! \n"
"vshll.u16 q4, d9, #16 \n"
"pld [%5, #256] \n"
"vld1.u16 {d4-d7}, [%5 :64]! \n"
"vshll.u16 q0, d4, #16 \n"
"vshll.u16 q1, d5, #16 \n"
"vshll.u16 q2, d6, #16 \n"
"vshll.u16 q3, d7, #16 \n"
"subs r4, r4, #1 \n"
"vmla.f32 q8, q0, d8[0] \n"
"vmla.f32 q9, q1, d8[1] \n"
"vmla.f32 q10, q2, d9[0] \n"
"vmla.f32 q11, q3, d9[1] \n"
"bne 0b \n"
"vadd.f32 q8, q8, q9 \n"
"vadd.f32 q10, q10, q11 \n"
"vadd.f32 q8, q8, q10 \n"
"vadd.f32 q12, q12, q8 \n"
"1: \n"
// remain loop
"and r4, %13, #3 \n" // r4 = remain = inch & 3;
"cmp r4, #0 \n"
"beq 3f \n"
"2: \n"
"pld [%4, #16] \n"
"vld1.u16 {d9[]}, [%4]! \n"
"vshll.u16 q4, d9, #16 \n"
"pld [%5, #64] \n"
"vld1.u16 {d1}, [%5 :64]! \n"
"vshll.u16 q0, d1, #16 \n"
"subs r4, r4, #1 \n"
"vmla.f32 q12, q4, q0 \n"
"bne 2b \n"
"3: \n"
"vshrn.u32 d24, q12, #16 \n"
"vst1.u16 {d24[0]}, [%0]! \n"
"vst1.u16 {d24[1]}, [%1]! \n"
"vst1.u16 {d24[2]}, [%2]! \n"
"vst1.u16 {d24[3]}, [%3]! \n"
: "=r"(outptr0), // %0
"=r"(outptr1), // %1
"=r"(outptr2), // %2
"=r"(outptr3), // %3
"=r"(tmpptr), // %4
"=r"(kptr) // %5
: "0"(outptr0),
"1"(outptr1),
"2"(outptr2),
"3"(outptr3),
"4"(tmpptr),
"5"(kptr),
"r"(biasptr), // %12
"r"(inch) // %13
: "cc", "memory", "r4", "q0", "q1", "q2", "q3", "q4", "q8", "q9", "q10", "q11", "q12");
#endif // __aarch64__
#else
float sum0 = biasptr[0];
float sum1 = biasptr[1];
float sum2 = biasptr[2];
float sum3 = biasptr[3];
for (int q = 0; q < inch; q++)
{
sum0 += bfloat16_to_float32(tmpptr[0]) * bfloat16_to_float32(kptr[0]);
sum1 += bfloat16_to_float32(tmpptr[0]) * bfloat16_to_float32(kptr[1]);
sum2 += bfloat16_to_float32(tmpptr[0]) * bfloat16_to_float32(kptr[2]);
sum3 += bfloat16_to_float32(tmpptr[0]) * bfloat16_to_float32(kptr[3]);
tmpptr++;
kptr += 4;
}
outptr0[0] = float32_to_bfloat16(sum0);
outptr1[0] = float32_to_bfloat16(sum1);
outptr2[0] = float32_to_bfloat16(sum2);
outptr3[0] = float32_to_bfloat16(sum3);
outptr0++;
outptr1++;
outptr2++;
outptr3++;
#endif // __ARM_NEON
}
}
remain_outch_start += nn_outch << 2;
#pragma omp parallel for num_threads(opt.num_threads)
for (int p = remain_outch_start; p < outch; p++)
{
Mat out0 = top_blob.channel(p);
const float bias0 = bias ? bias[p] : 0.f;
unsigned short* outptr0 = out0;
int i = 0;
for (; i + 7 < size; i += 8)
{
const unsigned short* tmpptr = tmp.channel(i / 8);
#if __ARM_NEON && __aarch64__
const unsigned short* kptr = kernel.channel(p / 8 + (p % 8) / 4 + p % 4);
#else
const unsigned short* kptr = kernel.channel(p / 4 + p % 4);
#endif // __ARM_NEON && __aarch64__
#if __ARM_NEON
#if __aarch64__
asm volatile(
"dup v8.4s, %w6 \n"
"dup v9.4s, %w6 \n"
// inch loop
"lsr w4, %w7, #2 \n" // w4 = nn = inch >> 2
"cmp w4, #0 \n"
"beq 1f \n"
"0: \n"
"prfm pldl1keep, [%1, #256] \n"
"ld1 {v4.4h, v5.4h, v6.4h, v7.4h}, [%1], #32 \n"
"shll v4.4s, v4.4h, #16 \n"
"shll v5.4s, v5.4h, #16 \n"
"shll v6.4s, v6.4h, #16 \n"
"shll v7.4s, v7.4h, #16 \n"
"prfm pldl1keep, [%2, #64] \n"
"ld1 {v0.4h}, [%2], #8 \n"
"shll v0.4s, v0.4h, #16 \n"
"fmla v8.4s, v4.4s, v0.s[0] \n"
"fmla v9.4s, v5.4s, v0.s[0] \n"
"prfm pldl1keep, [%1, #256] \n"
"ld1 {v12.4h, v13.4h, v14.4h, v15.4h}, [%1], #32 \n"
"shll v12.4s, v12.4h, #16 \n"
"shll v13.4s, v13.4h, #16 \n"
"shll v14.4s, v14.4h, #16 \n"
"shll v15.4s, v15.4h, #16 \n"
"fmla v8.4s, v6.4s, v0.s[1] \n"
"fmla v9.4s, v7.4s, v0.s[1] \n"
"subs w4, w4, #1 \n"
"fmla v8.4s, v12.4s, v0.s[2] \n"
"fmla v9.4s, v13.4s, v0.s[2] \n"
"fmla v8.4s, v14.4s, v0.s[3] \n"
"fmla v9.4s, v15.4s, v0.s[3] \n"
"bne 0b \n"
"1: \n"
// remain loop
"and w4, %w7, #3 \n" // w4 = remain = inch & 3;
"cmp w4, #0 \n"
"beq 3f \n"
"2: \n"
"prfm pldl1keep, [%1, #128] \n"
"ld1 {v4.4h, v5.4h}, [%1], #16 \n"
"shll v4.4s, v4.4h, #16 \n"
"shll v5.4s, v5.4h, #16 \n"
"prfm pldl1keep, [%2, #16] \n"
"ld1r {v0.4h}, [%2], #2 \n"
"shll v0.4s, v0.4h, #16 \n"
"subs w4, w4, #1 \n"
"fmla v8.4s, v4.4s, v0.4s \n"
"fmla v9.4s, v5.4s, v0.4s \n"
"bne 2b \n"
"3: \n"
"shrn v8.4h, v8.4s, #16 \n"
"shrn v9.4h, v9.4s, #16 \n"
"st1 {v8.4h, v9.4h}, [%0], #16 \n"
: "=r"(outptr0), // %0
"=r"(tmpptr), // %1
"=r"(kptr) // %2
: "0"(outptr0),
"1"(tmpptr),
"2"(kptr),
"r"(bias0), // %6
"r"(inch) // %7
: "cc", "memory", "x4", "v0", "v4", "v5", "v6", "v7", "v8", "v9", "v12", "v13", "v14", "v15");
#else // __aarch64__
asm volatile(
"vdup.f32 q8, %6 \n"
"vdup.f32 q9, %6 \n"
// inch loop
"lsr r4, %7, #2 \n" // r4 = nn = inch >> 2
"cmp r4, #0 \n"
"beq 1f \n"
"0: \n"
"pld [%1, #256] \n"
"vld1.u16 {d12-d15}, [%1 :64]! \n"
"vshll.u16 q4, d12, #16 \n"
"vshll.u16 q5, d13, #16 \n"
"vshll.u16 q6, d14, #16 \n"
"vshll.u16 q7, d15, #16 \n"
"pld [%2, #64] \n"
"vld1.u16 {d1}, [%2 :64]! \n"
"vshll.u16 q0, d1, #16 \n"
"vmla.f32 q8, q4, d0[0] \n"
"vmla.f32 q9, q5, d0[0] \n"
"pld [%1, #256] \n"
"vld1.u16 {d28-d31}, [%1 :64]! \n"
"vshll.u16 q12, d28, #16 \n"
"vshll.u16 q13, d29, #16 \n"
"vshll.u16 q14, d30, #16 \n"
"vshll.u16 q15, d31, #16 \n"
"vmla.f32 q8, q6, d0[1] \n"
"vmla.f32 q9, q7, d0[1] \n"
"subs r4, r4, #1 \n"
"vmla.f32 q8, q12, d1[0] \n"
"vmla.f32 q9, q13, d1[0] \n"
"vmla.f32 q8, q14, d1[1] \n"
"vmla.f32 q9, q15, d1[1] \n"
"bne 0b \n"
"1: \n"
// remain loop
"and r4, %7, #3 \n" // r4 = remain = inch & 3;
"cmp r4, #0 \n"
"beq 3f \n"
"2: \n"
"pld [%1, #128] \n"
"vld1.u16 {d10-d11}, [%1 :64]! \n"
"vshll.u16 q4, d10, #16 \n"
"vshll.u16 q5, d11, #16 \n"
"pld [%2, #16] \n"
"vld1.u16 {d1[]}, [%2]! \n"
"vshll.u16 q0, d1, #16 \n"
"subs r4, r4, #1 \n"
"vmla.f32 q8, q4, q0 \n"
"vmla.f32 q9, q5, q0 \n"
"bne 2b \n"
"3: \n"
"vshrn.u32 d16, q8, #16 \n"
"vshrn.u32 d17, q9, #16 \n"
"vst1.u16 {d16-d17}, [%0 :64]! \n"
: "=r"(outptr0), // %0
"=r"(tmpptr), // %1
"=r"(kptr) // %2
: "0"(outptr0),
"1"(tmpptr),
"2"(kptr),
"r"(bias0), // %6
"r"(inch) // %7
: "cc", "memory", "r4", "q0", "q4", "q5", "q6", "q7", "q8", "q9", "q12", "q13", "q14", "q15");
#endif // __aarch64__
#else
float sum0 = bias0;
float sum1 = bias0;
float sum2 = bias0;
float sum3 = bias0;
float sum4 = bias0;
float sum5 = bias0;
float sum6 = bias0;
float sum7 = bias0;
for (int q = 0; q < inch; q++)
{
sum0 += bfloat16_to_float32(tmpptr[0]) * bfloat16_to_float32(kptr[0]);
sum1 += bfloat16_to_float32(tmpptr[1]) * bfloat16_to_float32(kptr[0]);
sum2 += bfloat16_to_float32(tmpptr[2]) * bfloat16_to_float32(kptr[0]);
sum3 += bfloat16_to_float32(tmpptr[3]) * bfloat16_to_float32(kptr[0]);
sum4 += bfloat16_to_float32(tmpptr[4]) * bfloat16_to_float32(kptr[0]);
sum5 += bfloat16_to_float32(tmpptr[5]) * bfloat16_to_float32(kptr[0]);
sum6 += bfloat16_to_float32(tmpptr[6]) * bfloat16_to_float32(kptr[0]);
sum7 += bfloat16_to_float32(tmpptr[7]) * bfloat16_to_float32(kptr[0]);
tmpptr += 8;
kptr++;
}
outptr0[0] = float32_to_bfloat16(sum0);
outptr0[1] = float32_to_bfloat16(sum1);
outptr0[2] = float32_to_bfloat16(sum2);
outptr0[3] = float32_to_bfloat16(sum3);
outptr0[4] = float32_to_bfloat16(sum4);
outptr0[5] = float32_to_bfloat16(sum5);
outptr0[6] = float32_to_bfloat16(sum6);
outptr0[7] = float32_to_bfloat16(sum7);
outptr0 += 8;
#endif // __ARM_NEON
}
for (; i + 3 < size; i += 4)
{
const unsigned short* tmpptr = tmp.channel(i / 8 + (i % 8) / 4);
#if __ARM_NEON && __aarch64__
const unsigned short* kptr = kernel.channel(p / 8 + (p % 8) / 4 + p % 4);
#else
const unsigned short* kptr = kernel.channel(p / 4 + p % 4);
#endif // __ARM_NEON && __aarch64__
#if __ARM_NEON
#if __aarch64__
asm volatile(
"dup v8.4s, %w6 \n"
// inch loop
"lsr w4, %w7, #2 \n" // w4 = nn = inch >> 2
"cmp w4, #0 \n"
"beq 1f \n"
"0: \n"
"prfm pldl1keep, [%1, #256] \n"
"ld1 {v4.4h, v5.4h, v6.4h, v7.4h}, [%1], #32 \n"
"shll v4.4s, v4.4h, #16 \n"
"shll v5.4s, v5.4h, #16 \n"
"shll v6.4s, v6.4h, #16 \n"
"shll v7.4s, v7.4h, #16 \n"
"prfm pldl1keep, [%2, #64] \n"
"ld1 {v0.4h}, [%2], #8 \n"
"shll v0.4s, v0.4h, #16 \n"
"subs w4, w4, #1 \n"
"fmla v8.4s, v4.4s, v0.s[0] \n"
"fmla v8.4s, v5.4s, v0.s[1] \n"
"fmla v8.4s, v6.4s, v0.s[2] \n"
"fmla v8.4s, v7.4s, v0.s[3] \n"
"bne 0b \n"
"1: \n"
// remain loop
"and w4, %w7, #3 \n" // w4 = remain = inch & 3;
"cmp w4, #0 \n"
"beq 3f \n"
"2: \n"
"prfm pldl1keep, [%1, #64] \n"
"ld1 {v4.4h}, [%1], #8 \n"
"shll v4.4s, v4.4h, #16 \n"
"prfm pldl1keep, [%2, #16] \n"
"ld1r {v0.4h}, [%2], #2 \n"
"shll v0.4s, v0.4h, #16 \n"
"subs w4, w4, #1 \n"
"fmla v8.4s, v4.4s, v0.4s \n"
"bne 2b \n"
"3: \n"
"shrn v8.4h, v8.4s, #16 \n"
"st1 {v8.4h}, [%0], #8 \n"
: "=r"(outptr0), // %0
"=r"(tmpptr), // %1
"=r"(kptr) // %2
: "0"(outptr0),
"1"(tmpptr),
"2"(kptr),
"r"(bias0), // %6
"r"(inch) // %7
: "cc", "memory", "x4", "v0", "v4", "v5", "v6", "v7", "v8");
#else // __aarch64__
asm volatile(
"vdup.f32 q8, %6 \n"
// inch loop
"lsr r4, %7, #2 \n" // r4 = nn = inch >> 2
"cmp r4, #0 \n"
"beq 1f \n"
"0: \n"
"pld [%1, #256] \n"
"vld1.u16 {d12-d15}, [%1 :64]! \n"
"vshll.u16 q4, d12, #16 \n"
"vshll.u16 q5, d13, #16 \n"
"vshll.u16 q6, d14, #16 \n"
"vshll.u16 q7, d15, #16 \n"
"pld [%2, #64] \n"
"vld1.u16 {d1}, [%2]! \n"
"vshll.u16 q0, d1, #16 \n"
"subs r4, r4, #1 \n"
"vmla.f32 q8, q4, d0[0] \n"
"vmla.f32 q8, q5, d0[1] \n"
"vmla.f32 q8, q6, d1[0] \n"
"vmla.f32 q8, q7, d1[1] \n"
"bne 0b \n"
"1: \n"
// remain loop
"and r4, %7, #3 \n" // r4 = remain = inch & 3;
"cmp r4, #0 \n"
"beq 3f \n"
"2: \n"
"pld [%1, #64] \n"
"vld1.u16 {d9}, [%1 :64]! \n"
"vshll.u16 q4, d9, #16 \n"
"pld [%2, #16] \n"
"vld1.u16 {d1[]}, [%2]! \n"
"vshll.u16 q0, d1, #16 \n"
"subs r4, r4, #1 \n"
"vmla.f32 q8, q4, q0 \n"
"bne 2b \n"
"3: \n"
"vshrn.u32 d16, q8, #16 \n"
"vst1.u16 {d16}, [%0 :64]! \n"
: "=r"(outptr0), // %0
"=r"(tmpptr), // %1
"=r"(kptr) // %2
: "0"(outptr0),
"1"(tmpptr),
"2"(kptr),
"r"(bias0), // %6
"r"(inch) // %7
: "cc", "memory", "r4", "q0", "q4", "q5", "q6", "q7", "q8");
#endif // __aarch64__
#else
float sum0 = bias0;
float sum1 = bias0;
float sum2 = bias0;
float sum3 = bias0;
for (int q = 0; q < inch; q++)
{
sum0 += bfloat16_to_float32(tmpptr[0]) * bfloat16_to_float32(kptr[0]);
sum1 += bfloat16_to_float32(tmpptr[1]) * bfloat16_to_float32(kptr[0]);
sum2 += bfloat16_to_float32(tmpptr[2]) * bfloat16_to_float32(kptr[0]);
sum3 += bfloat16_to_float32(tmpptr[3]) * bfloat16_to_float32(kptr[0]);
tmpptr += 4;
kptr++;
}
outptr0[0] = float32_to_bfloat16(sum0);
outptr0[1] = float32_to_bfloat16(sum1);
outptr0[2] = float32_to_bfloat16(sum2);
outptr0[3] = float32_to_bfloat16(sum3);
outptr0 += 4;
#endif // __ARM_NEON
}
for (; i < size; i++)
{
const unsigned short* tmpptr = tmp.channel(i / 8 + (i % 8) / 4 + i % 4);
#if __ARM_NEON && __aarch64__
const unsigned short* kptr = kernel.channel(p / 8 + (p % 8) / 4 + p % 4);
#else
const unsigned short* kptr = kernel.channel(p / 4 + p % 4);
#endif // __ARM_NEON && __aarch64__
int q = 0;
#if __ARM_NEON
float32x4_t _sum0 = vdupq_n_f32(0.f);
for (; q + 3 < inch; q += 4)
{
float32x4_t _p0 = vcvt_f32_bf16(vld1_u16(tmpptr));
tmpptr += 4;
float32x4_t _k0 = vcvt_f32_bf16(vld1_u16(kptr));
kptr += 4;
#if __aarch64__
_sum0 = vfmaq_f32(_sum0, _p0, _k0);
#else
_sum0 = vmlaq_f32(_sum0, _p0, _k0);
#endif
}
#if __aarch64__
float sum0 = bias0 + vaddvq_f32(_sum0);
#else
float32x2_t _ss = vadd_f32(vget_low_f32(_sum0), vget_high_f32(_sum0));
float sum0 = bias0 + vget_lane_f32(vpadd_f32(_ss, _ss), 0);
#endif
#else
float sum0 = bias0;
#endif // __ARM_NEON
for (; q < inch; q++)
{
sum0 += bfloat16_to_float32(tmpptr[0]) * bfloat16_to_float32(kptr[0]);
tmpptr++;
kptr++;
}
outptr0[0] = float32_to_bfloat16(sum0);
outptr0++;
}
}
// // NOTE sgemm
// for (; p<outch; p++)
// {
// Mat out0 = top_blob.channel(p);
//
// const float bias0 = bias ? bias[p] : 0.f;
//
// float* outptr0 = out0;
//
// for (int i=0; i<size; i++)
// {
// float sum = bias0;
//
// const float* kptr = _kernel.channel(p/8 + p%8);
//
// for (int q=0; q<inch; q++)
// {
// const float* img0 = bottom_blob.channel(q);
//
// sum += img0[i] * kptr[0];
// kptr ++;
// }
//
// outptr0[i] = sum;
// }
// }
}
|
vector_template_func_ext.h
|
CPS_START_NAMESPACE
template < typename AFloat, typename BFloat >
inline void compDotProduct (IFloat * c_r, IFloat * c_i,
const AFloat * a, const BFloat * b, int len)
{
*c_r = *c_i = 0.0;
Float re=0.,im=0.;
#pragma omp parallel for reduction(+:re,im)
for(int i = 0; i < len; i += 2)
{
re+= a[i] * b[i] + a[i+1] * b[i+1]; // real part
im+= a[i] * b[i+1] - a[i+1] * b[i]; // imag part
}
*c_r =re;
*c_i =im;
}
CPS_END_NAMESPACE
|
bitmap.h
|
/*!
* Copyright 2014 by Contributors
* \file bitmap.h
* \brief a simple implement of bitmap
* NOTE: bitmap is only threadsafe per word access, remember this when using bitmap
* \author Tianqi Chen
*/
#ifndef XGBOOST_UTILS_BITMAP_H_
#define XGBOOST_UTILS_BITMAP_H_
#include <vector>
#include "./utils.h"
#include "./omp.h"
// GLC parallel lambda premitive
#include <core/parallel/lambda_omp.hpp>
#include <core/parallel/pthread_tools.hpp>
namespace xgboost {
namespace utils {
/*! \brief bit map that contains set of bit indicators */
struct BitMap {
/*! \brief internal data structure */
std::vector<uint32_t> data;
/*!
* \brief resize the bitmap to be certain size
* \param size the size of bitmap
*/
inline void Resize(size_t size) {
data.resize((size + 31U) >> 5, 0);
}
/*!
* \brief query the i-th position of bitmap
* \param i the position in
*/
inline bool Get(size_t i) const {
return (data[i >> 5] >> (i & 31U)) & 1U;
}
/*!
* \brief set i-th position to true
* \param i position index
*/
inline void SetTrue(size_t i) {
data[i >> 5] |= (1 << (i & 31U));
}
/*! \brief initialize the value of bit map from vector of bool*/
inline void InitFromBool(const std::vector<int> &vec) {
this->Resize(vec.size());
// parallel over the full cases
bst_omp_uint nsize = static_cast<bst_omp_uint>(vec.size() / 32);
// #pragma omp parallel for schedule(static)
// for (bst_omp_uint i = 0; i < nsize; ++i) {
turi::parallel_for(0, nsize, [&](size_t i) {
uint32_t res = 0;
for (int k = 0; k < 32; ++k) {
int bit = vec[(i << 5) | k];
res |= (bit << k);
}
data[i] = res;
});
if (nsize != vec.size()) data.back() = 0;
for (size_t i = nsize; i < vec.size(); ++i) {
if (vec[i]) this->SetTrue(i);
}
}
/*! \brief clear the bitmap, set all places to false */
inline void Clear(void) {
std::fill(data.begin(), data.end(), 0U);
}
};
} // namespace utils
} // namespace xgboost
#endif // XGBOOST_UTILS_BITMAP_H_
|
GB_unop__identity_fc32_int32.c
|
//------------------------------------------------------------------------------
// GB_unop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated2/ folder, do not edit it
// (it is auto-generated from Generator/*).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_atomics.h"
#include "GB_unop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB (_unop_apply__identity_fc32_int32)
// op(A') function: GB (_unop_tran__identity_fc32_int32)
// C type: GxB_FC32_t
// A type: int32_t
// cast: GxB_FC32_t cij = GxB_CMPLXF ((float) (aij), 0)
// unaryop: cij = aij
#define GB_ATYPE \
int32_t
#define GB_CTYPE \
GxB_FC32_t
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
int32_t aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = x ;
// casting
#define GB_CAST(z, aij) \
GxB_FC32_t z = GxB_CMPLXF ((float) (aij), 0) ;
// cij = op (aij)
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
int32_t aij = Ax [pA] ; \
/* Cx [pC] = op (cast (aij)) */ \
GxB_FC32_t z = GxB_CMPLXF ((float) (aij), 0) ; \
Cx [pC] = z ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_IDENTITY || GxB_NO_FC32 || GxB_NO_INT32)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_apply__identity_fc32_int32)
(
GxB_FC32_t *Cx, // Cx and Ax may be aliased
const int32_t *Ax,
const int8_t *restrict Ab, // A->b if A is bitmap
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
if (Ab == NULL)
{
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
int32_t aij = Ax [p] ;
GxB_FC32_t z = GxB_CMPLXF ((float) (aij), 0) ;
Cx [p] = z ;
}
}
else
{
// bitmap case, no transpose; A->b already memcpy'd into C->b
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!Ab [p]) continue ;
int32_t aij = Ax [p] ;
GxB_FC32_t z = GxB_CMPLXF ((float) (aij), 0) ;
Cx [p] = z ;
}
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_tran__identity_fc32_int32)
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
actionAngleStaeckel.c
|
/*
C code for Binney (2012)'s Staeckel approximation code
*/
#ifdef _WIN32
#include <Python.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <math.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_roots.h>
#include <gsl/gsl_min.h>
#include <gsl/gsl_integration.h>
#ifdef _OPENMP
#include <omp.h>
#endif
#define CHUNKSIZE 10
//Potentials
#include <galpy_potentials.h>
#include <integrateFullOrbit.h>
#include <actionAngle.h>
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
//Macros to export functions in DLL on different OS
#if defined(_WIN32)
#define EXPORT __declspec(dllexport)
#elif defined(__GNUC__)
#define EXPORT __attribute__((visibility("default")))
#else
// Just do nothing?
#define EXPORT
#endif
#ifdef _WIN32
// On Windows, *need* to define this function to allow the package to be imported
#if PY_MAJOR_VERSION >= 3
PyMODINIT_FUNC PyInit_galpy_actionAngle_c(void) { // Python 3
return NULL;
}
#else
PyMODINIT_FUNC initgalpy_actionAngle_c(void) {} // Python 2
#endif
#endif
/*
Structure Declarations
*/
struct JRStaeckelArg{
double E;
double Lz22delta;
double I3U;
double delta;
double u0;
double sinh2u0;
double v0;
double sin2v0;
double potu0v0;
int nargs;
struct potentialArg * actionAngleArgs;
};
struct JzStaeckelArg{
double E;
double Lz22delta;
double I3V;
double delta;
double u0;
double cosh2u0;
double sinh2u0;
double potupi2;
int nargs;
struct potentialArg * actionAngleArgs;
};
struct dJRStaeckelArg{
double E;
double Lz22delta;
double I3U;
double delta;
double u0;
double sinh2u0;
double v0;
double sin2v0;
double potu0v0;
double umin;
double umax;
int nargs;
struct potentialArg * actionAngleArgs;
};
struct dJzStaeckelArg{
double E;
double Lz22delta;
double I3V;
double delta;
double u0;
double cosh2u0;
double sinh2u0;
double potupi2;
double vmin;
int nargs;
struct potentialArg * actionAngleArgs;
};
struct u0EqArg{
double E;
double Lz22delta;
double delta;
int nargs;
struct potentialArg * actionAngleArgs;
};
/*
Function Declarations
*/
EXPORT void calcu0(int,double *,double *,int,int *,double *,int,double*,
double *,int *);
EXPORT void actionAngleStaeckel_uminUmaxVmin(int,double *,double *,double *,double *,
double *,double *,int,int *,double *,
int,double *,double *,
double *,double *,int *);
EXPORT void actionAngleStaeckel_actions(int,double *,double *,double *,double *,
double *,double *,int,int *,double *,int,
double *,int,double *,double *,int *);
EXPORT void actionAngleStaeckel_actionsFreqsAngles(int,double *,double *,double *,
double *,double *,double *,
int,int *,double *,
int,double *,int,double *,double *,
double *,double *,double *,
double *,double *,double *,int *);
EXPORT void actionAngleStaeckel_actionsFreqs(int,double *,double *,double *,double *,
double *,double *,int,int *,double *,
int,double *,int,double *,double *,
double *,double *,double *,int *);
void calcAnglesStaeckel(int,double *,double *,double *,double *,double *,
double *,double *,double *,double *,double *,double *,
double *,double *,double *,double *,double *,double *,
double *,double *,double *,double *,double *,double *,
double *,int,double *,double *,double *,double *,
double *,double *,double *,double *,double *,double *,
int,struct potentialArg *,int);
void calcFreqsFromDerivsStaeckel(int,double *,double *,double *,
double *,double *,double *,
double *,double *,double *,double *);
void calcdI3dJFromDerivsStaeckel(int,double *,double *,double *,double *,
double *,double *,double *,double *);
void calcJRStaeckel(int,double *,double *,double *,double *,double *,double *,
int,double *,double *,double *,double *,double *,double *,
int,struct potentialArg *,int);
void calcJzStaeckel(int,double *,double *,double *,double *,double *,int,
double *,double *,double *,double *,double *,int,
struct potentialArg *,int);
void calcdJRStaeckel(int,double *,double *,double *,double *,double *,
double *,double *,double *,int,
double *,double *,double *,double *,double *,double *,int,
struct potentialArg *,int);
void calcdJzStaeckel(int,double *,double *,double *,double *,double *,
double *,double *,int,double *,double *,double *,double *,
double *,int,
struct potentialArg *,int);
void calcUminUmax(int,double *,double *,double *,double *,double *,double *,
double *,int,double *,double *,double *,double *,double *,
double *,int,struct potentialArg *);
void calcVmin(int,double *,double *,double *,double *,double *,double *,int,
double *,double *,double *,double *,double *,int,
struct potentialArg *);
double JRStaeckelIntegrandSquared(double,void *);
double JRStaeckelIntegrand(double,void *);
double JzStaeckelIntegrandSquared(double,void *);
double JzStaeckelIntegrand(double,void *);
double dJRdEStaeckelIntegrand(double,void *);
double dJRdELowStaeckelIntegrand(double,void *);
double dJRdEHighStaeckelIntegrand(double,void *);
double dJRdLzStaeckelIntegrand(double,void *);
double dJRdLzLowStaeckelIntegrand(double,void *);
double dJRdLzHighStaeckelIntegrand(double,void *);
double dJRdI3StaeckelIntegrand(double,void *);
double dJRdI3LowStaeckelIntegrand(double,void *);
double dJRdI3HighStaeckelIntegrand(double,void *);
double dJzdEStaeckelIntegrand(double,void *);
double dJzdELowStaeckelIntegrand(double,void *);
double dJzdEHighStaeckelIntegrand(double,void *);
double dJzdLzStaeckelIntegrand(double,void *);
double dJzdLzLowStaeckelIntegrand(double,void *);
double dJzdLzHighStaeckelIntegrand(double,void *);
double dJzdI3StaeckelIntegrand(double,void *);
double dJzdI3LowStaeckelIntegrand(double,void *);
double dJzdI3HighStaeckelIntegrand(double,void *);
double u0Equation(double,void *);
double evaluatePotentials(double,double,int, struct potentialArg *);
double evaluatePotentialsUV(double,double,double,int,struct potentialArg *);
/*
Actual functions, inlines first
*/
static inline void uv_to_Rz(double u, double v, double * R, double *z,
double delta){
*R= delta * sinh(u) * sin(v);
*z= delta * cosh(u) * cos(v);
}
static inline void Rz_to_uv_vec(int ndata,
double *R,
double *z,
double *u,
double *v,
int ndelta,
double * delta){
int ii;
double d12, d22, coshu, cosv,tdelta;
int delta_stride= ndelta == 1 ? 0 : 1;
for (ii=0; ii < ndata; ii++) {
tdelta= *(delta+ii*delta_stride);
d12= (*(z+ii)+tdelta)*(*(z+ii)+tdelta)+(*(R+ii))*(*(R+ii));
d22= (*(z+ii)-tdelta)*(*(z+ii)-tdelta)+(*(R+ii))*(*(R+ii));
coshu= 0.5/tdelta*(sqrt(d12)+sqrt(d22));
cosv= 0.5/tdelta*(sqrt(d12)-sqrt(d22));
*u++= acosh(coshu);
*v++= acos(cosv);
}
u-= ndata;
v-= ndata;
}
static inline void calcEL(int ndata,
double *R,
double *vR,
double *vT,
double *z,
double *vz,
double *E,
double *Lz,
int nargs,
struct potentialArg * actionAngleArgs){
int ii;
for (ii=0; ii < ndata; ii++){
*(E+ii)= evaluatePotentials(*(R+ii),*(z+ii),
nargs,actionAngleArgs)
+ 0.5 * *(vR+ii) * *(vR+ii)
+ 0.5 * *(vT+ii) * *(vT+ii)
+ 0.5 * *(vz+ii) * *(vz+ii);
*(Lz+ii)= *(R+ii) * *(vT+ii);
}
}
/*
MAIN FUNCTIONS
*/
void calcu0(int ndata,
double *E,
double *Lz,
int npot,
int * pot_type,
double * pot_args,
int ndelta,
double * delta,
double *u0,
int * err){
int ii;
//Set up the potentials
struct potentialArg * actionAngleArgs= (struct potentialArg *) malloc ( npot * sizeof (struct potentialArg) );
parse_leapFuncArgs_Full(npot,actionAngleArgs,&pot_type,&pot_args);
//setup the function to be minimized
gsl_function u0Eq;
struct u0EqArg * params= (struct u0EqArg *) malloc ( sizeof (struct u0EqArg) );
params->nargs= npot;
params->actionAngleArgs= actionAngleArgs;
//Setup solver
int status;
int iter, max_iter = 100;
const gsl_min_fminimizer_type *T;
gsl_min_fminimizer *s;
double u_guess, u_lo, u_hi;
T = gsl_min_fminimizer_brent;
s = gsl_min_fminimizer_alloc (T);
u0Eq.function = &u0Equation;
int delta_stride= ndelta == 1 ? 0 : 1;
for (ii=0; ii < ndata; ii++){
//Setup function
params->delta= *(delta+ii*delta_stride);
params->E= *(E+ii);
params->Lz22delta= 0.5 * *(Lz+ii) * *(Lz+ii) / *(delta+ii*delta_stride) / *(delta+ii*delta_stride);
u0Eq.params = params;
//Find starting points for minimum
u_guess= 1.;
u_lo= 0.001;
u_hi= 100.;
gsl_set_error_handler_off();
status = gsl_min_fminimizer_set (s, &u0Eq, u_guess, u_lo, u_hi);
if (status == GSL_EINVAL) {
*(u0+ii)= u_hi;
gsl_set_error_handler (NULL);
continue;
}
gsl_set_error_handler (NULL);
iter= 0;
do
{
iter++;
status = gsl_min_fminimizer_iterate (s);
u_guess = gsl_min_fminimizer_x_minimum (s);
u_lo = gsl_min_fminimizer_x_lower (s);
u_hi = gsl_min_fminimizer_x_upper (s);
status = gsl_min_test_interval (u_lo, u_hi,
9.9999999999999998e-13,
4.4408920985006262e-16);
}
while (status == GSL_CONTINUE && iter < max_iter);
*(u0+ii)= gsl_min_fminimizer_x_minimum (s);
}
gsl_min_fminimizer_free (s);
free(params);
free_potentialArgs(npot,actionAngleArgs);
free(actionAngleArgs);
*err= status;
}
void actionAngleStaeckel_uminUmaxVmin(int ndata,
double *R,
double *vR,
double *vT,
double *z,
double *vz,
double *u0,
int npot,
int * pot_type,
double * pot_args,
int ndelta,
double * delta,
double *umin,
double *umax,
double *vmin,
int * err){
// Just copied this over from actionAngleStaeckel_actions below, not elegant
// but does the job...
int ii;
double tdelta;
//Set up the potentials
struct potentialArg * actionAngleArgs= (struct potentialArg *) malloc ( npot * sizeof (struct potentialArg) );
parse_leapFuncArgs_Full(npot,actionAngleArgs,&pot_type,&pot_args);
//E,Lz
double *E= (double *) malloc ( ndata * sizeof(double) );
double *Lz= (double *) malloc ( ndata * sizeof(double) );
calcEL(ndata,R,vR,vT,z,vz,E,Lz,npot,actionAngleArgs);
//Calculate all necessary parameters
double *ux= (double *) malloc ( ndata * sizeof(double) );
double *vx= (double *) malloc ( ndata * sizeof(double) );
Rz_to_uv_vec(ndata,R,z,ux,vx,ndelta,delta);
double *coshux= (double *) malloc ( ndata * sizeof(double) );
double *sinhux= (double *) malloc ( ndata * sizeof(double) );
double *sinvx= (double *) malloc ( ndata * sizeof(double) );
double *cosvx= (double *) malloc ( ndata * sizeof(double) );
double *pux= (double *) malloc ( ndata * sizeof(double) );
double *pvx= (double *) malloc ( ndata * sizeof(double) );
double *sinh2u0= (double *) malloc ( ndata * sizeof(double) );
double *cosh2u0= (double *) malloc ( ndata * sizeof(double) );
double *v0= (double *) malloc ( ndata * sizeof(double) );
double *sin2v0= (double *) malloc ( ndata * sizeof(double) );
double *potu0v0= (double *) malloc ( ndata * sizeof(double) );
double *potupi2= (double *) malloc ( ndata * sizeof(double) );
double *I3U= (double *) malloc ( ndata * sizeof(double) );
double *I3V= (double *) malloc ( ndata * sizeof(double) );
int delta_stride= ndelta == 1 ? 0 : 1;
UNUSED int chunk= CHUNKSIZE;
#pragma omp parallel for schedule(static,chunk) private(ii,tdelta)
for (ii=0; ii < ndata; ii++){
tdelta= *(delta+ii*delta_stride);
*(coshux+ii)= cosh(*(ux+ii));
*(sinhux+ii)= sinh(*(ux+ii));
*(cosvx+ii)= cos(*(vx+ii));
*(sinvx+ii)= sin(*(vx+ii));
*(pux+ii)= tdelta * (*(vR+ii) * *(coshux+ii) * *(sinvx+ii)
+ *(vz+ii) * *(sinhux+ii) * *(cosvx+ii));
*(pvx+ii)= tdelta * (*(vR+ii) * *(sinhux+ii) * *(cosvx+ii)
- *(vz+ii) * *(coshux+ii) * *(sinvx+ii));
*(sinh2u0+ii)= sinh(*(u0+ii)) * sinh(*(u0+ii));
*(cosh2u0+ii)= cosh(*(u0+ii)) * cosh(*(u0+ii));
*(v0+ii)= 0.5 * M_PI; //*(vx+ii);
*(sin2v0+ii)= sin(*(v0+ii)) * sin(*(v0+ii));
*(potu0v0+ii)= evaluatePotentialsUV(*(u0+ii),*(v0+ii),tdelta,
npot,actionAngleArgs);
*(I3U+ii)= *(E+ii) * *(sinhux+ii) * *(sinhux+ii)
- 0.5 * *(pux+ii) * *(pux+ii) / tdelta / tdelta
- 0.5 * *(Lz+ii) * *(Lz+ii) / tdelta / tdelta / *(sinhux+ii) / *(sinhux+ii)
- ( *(sinhux+ii) * *(sinhux+ii) + *(sin2v0+ii))
*evaluatePotentialsUV(*(ux+ii),*(v0+ii),tdelta,
npot,actionAngleArgs)
+ ( *(sinh2u0+ii) + *(sin2v0+ii) )* *(potu0v0+ii);
*(potupi2+ii)= evaluatePotentialsUV(*(u0+ii),0.5 * M_PI,tdelta,
npot,actionAngleArgs);
*(I3V+ii)= - *(E+ii) * *(sinvx+ii) * *(sinvx+ii)
+ 0.5 * *(pvx+ii) * *(pvx+ii) / tdelta / tdelta
+ 0.5 * *(Lz+ii) * *(Lz+ii) / tdelta / tdelta / *(sinvx+ii) / *(sinvx+ii)
- *(cosh2u0+ii) * *(potupi2+ii)
+ ( *(sinh2u0+ii) + *(sinvx+ii) * *(sinvx+ii))
* evaluatePotentialsUV(*(u0+ii),*(vx+ii),tdelta,
npot,actionAngleArgs);
}
//Calculate 'peri' and 'apo'centers
calcUminUmax(ndata,umin,umax,ux,pux,E,Lz,I3U,ndelta,delta,u0,sinh2u0,v0,
sin2v0,potu0v0,npot,actionAngleArgs);
calcVmin(ndata,vmin,vx,pvx,E,Lz,I3V,ndelta,delta,u0,cosh2u0,sinh2u0,potupi2,
npot,actionAngleArgs);
//Free
free_potentialArgs(npot,actionAngleArgs);
free(actionAngleArgs);
free(E);
free(Lz);
free(ux);
free(vx);
free(coshux);
free(sinhux);
free(sinvx);
free(cosvx);
free(pux);
free(pvx);
free(sinh2u0);
free(cosh2u0);
free(v0);
free(sin2v0);
free(potu0v0);
free(potupi2);
free(I3U);
free(I3V);
}
void actionAngleStaeckel_actions(int ndata,
double *R,
double *vR,
double *vT,
double *z,
double *vz,
double *u0,
int npot,
int * pot_type,
double * pot_args,
int ndelta,
double * delta,
int order,
double *jr,
double *jz,
int * err){
int ii;
double tdelta;
//Set up the potentials
struct potentialArg * actionAngleArgs= (struct potentialArg *) malloc ( npot * sizeof (struct potentialArg) );
parse_leapFuncArgs_Full(npot,actionAngleArgs,&pot_type,&pot_args);
//E,Lz
double *E= (double *) malloc ( ndata * sizeof(double) );
double *Lz= (double *) malloc ( ndata * sizeof(double) );
calcEL(ndata,R,vR,vT,z,vz,E,Lz,npot,actionAngleArgs);
//Calculate all necessary parameters
double *ux= (double *) malloc ( ndata * sizeof(double) );
double *vx= (double *) malloc ( ndata * sizeof(double) );
Rz_to_uv_vec(ndata,R,z,ux,vx,ndelta,delta);
double *coshux= (double *) malloc ( ndata * sizeof(double) );
double *sinhux= (double *) malloc ( ndata * sizeof(double) );
double *sinvx= (double *) malloc ( ndata * sizeof(double) );
double *cosvx= (double *) malloc ( ndata * sizeof(double) );
double *pux= (double *) malloc ( ndata * sizeof(double) );
double *pvx= (double *) malloc ( ndata * sizeof(double) );
double *sinh2u0= (double *) malloc ( ndata * sizeof(double) );
double *cosh2u0= (double *) malloc ( ndata * sizeof(double) );
double *v0= (double *) malloc ( ndata * sizeof(double) );
double *sin2v0= (double *) malloc ( ndata * sizeof(double) );
double *potu0v0= (double *) malloc ( ndata * sizeof(double) );
double *potupi2= (double *) malloc ( ndata * sizeof(double) );
double *I3U= (double *) malloc ( ndata * sizeof(double) );
double *I3V= (double *) malloc ( ndata * sizeof(double) );
int delta_stride= ndelta == 1 ? 0 : 1;
UNUSED int chunk= CHUNKSIZE;
#pragma omp parallel for schedule(static,chunk) private(ii,tdelta)
for (ii=0; ii < ndata; ii++){
tdelta= *(delta+ii*delta_stride);
*(coshux+ii)= cosh(*(ux+ii));
*(sinhux+ii)= sinh(*(ux+ii));
*(cosvx+ii)= cos(*(vx+ii));
*(sinvx+ii)= sin(*(vx+ii));
*(pux+ii)= tdelta * (*(vR+ii) * *(coshux+ii) * *(sinvx+ii)
+ *(vz+ii) * *(sinhux+ii) * *(cosvx+ii));
*(pvx+ii)= tdelta * (*(vR+ii) * *(sinhux+ii) * *(cosvx+ii)
- *(vz+ii) * *(coshux+ii) * *(sinvx+ii));
*(sinh2u0+ii)= sinh(*(u0+ii)) * sinh(*(u0+ii));
*(cosh2u0+ii)= cosh(*(u0+ii)) * cosh(*(u0+ii));
*(v0+ii)= 0.5 * M_PI; //*(vx+ii);
*(sin2v0+ii)= sin(*(v0+ii)) * sin(*(v0+ii));
*(potu0v0+ii)= evaluatePotentialsUV(*(u0+ii),*(v0+ii),tdelta,
npot,actionAngleArgs);
*(I3U+ii)= *(E+ii) * *(sinhux+ii) * *(sinhux+ii)
- 0.5 * *(pux+ii) * *(pux+ii) / tdelta / tdelta
- 0.5 * *(Lz+ii) * *(Lz+ii) / tdelta / tdelta / *(sinhux+ii) / *(sinhux+ii)
- ( *(sinhux+ii) * *(sinhux+ii) + *(sin2v0+ii))
*evaluatePotentialsUV(*(ux+ii),*(v0+ii),tdelta,
npot,actionAngleArgs)
+ ( *(sinh2u0+ii) + *(sin2v0+ii) )* *(potu0v0+ii);
*(potupi2+ii)= evaluatePotentialsUV(*(u0+ii),0.5 * M_PI,tdelta,
npot,actionAngleArgs);
*(I3V+ii)= - *(E+ii) * *(sinvx+ii) * *(sinvx+ii)
+ 0.5 * *(pvx+ii) * *(pvx+ii) / tdelta / tdelta
+ 0.5 * *(Lz+ii) * *(Lz+ii) / tdelta / tdelta / *(sinvx+ii) / *(sinvx+ii)
- *(cosh2u0+ii) * *(potupi2+ii)
+ ( *(sinh2u0+ii) + *(sinvx+ii) * *(sinvx+ii))
* evaluatePotentialsUV(*(u0+ii),*(vx+ii),tdelta,
npot,actionAngleArgs);
}
//Calculate 'peri' and 'apo'centers
double *umin= (double *) malloc ( ndata * sizeof(double) );
double *umax= (double *) malloc ( ndata * sizeof(double) );
double *vmin= (double *) malloc ( ndata * sizeof(double) );
calcUminUmax(ndata,umin,umax,ux,pux,E,Lz,I3U,ndelta,delta,u0,sinh2u0,v0,
sin2v0,potu0v0,npot,actionAngleArgs);
calcVmin(ndata,vmin,vx,pvx,E,Lz,I3V,ndelta,delta,u0,cosh2u0,sinh2u0,potupi2,
npot,actionAngleArgs);
//Calculate the actions
calcJRStaeckel(ndata,jr,umin,umax,E,Lz,I3U,ndelta,delta,u0,sinh2u0,v0,sin2v0,
potu0v0,npot,actionAngleArgs,order);
calcJzStaeckel(ndata,jz,vmin,E,Lz,I3V,ndelta,delta,u0,cosh2u0,sinh2u0,
potupi2,npot,actionAngleArgs,order);
//Free
free_potentialArgs(npot,actionAngleArgs);
free(actionAngleArgs);
free(E);
free(Lz);
free(ux);
free(vx);
free(coshux);
free(sinhux);
free(sinvx);
free(cosvx);
free(pux);
free(pvx);
free(sinh2u0);
free(cosh2u0);
free(v0);
free(sin2v0);
free(potu0v0);
free(potupi2);
free(I3U);
free(I3V);
free(umin);
free(umax);
free(vmin);
}
void calcJRStaeckel(int ndata,
double * jr,
double * umin,
double * umax,
double * E,
double * Lz,
double * I3U,
int ndelta,
double * delta,
double * u0,
double * sinh2u0,
double * v0,
double * sin2v0,
double * potu0v0,
int nargs,
struct potentialArg * actionAngleArgs,
int order){
int ii, tid, nthreads;
#ifdef _OPENMP
nthreads = omp_get_max_threads();
#else
nthreads = 1;
#endif
gsl_function * JRInt= (gsl_function *) malloc ( nthreads * sizeof(gsl_function) );
struct JRStaeckelArg * params= (struct JRStaeckelArg *) malloc ( nthreads * sizeof (struct JRStaeckelArg) );
for (tid=0; tid < nthreads; tid++){
(params+tid)->nargs= nargs;
(params+tid)->actionAngleArgs= actionAngleArgs;
}
//Setup integrator
gsl_integration_glfixed_table * T= gsl_integration_glfixed_table_alloc (order);
int delta_stride= ndelta == 1 ? 0 : 1;
UNUSED int chunk= CHUNKSIZE;
#pragma omp parallel for schedule(static,chunk) \
private(tid,ii) \
shared(jr,umin,umax,JRInt,params,T,delta,E,Lz,I3U,u0,sinh2u0,v0,sin2v0,potu0v0)
for (ii=0; ii < ndata; ii++){
#ifdef _OPENMP
tid= omp_get_thread_num();
#else
tid = 0;
#endif
if ( *(umin+ii) == -9999.99 || *(umax+ii) == -9999.99 ){
*(jr+ii)= 9999.99;
continue;
}
if ( (*(umax+ii) - *(umin+ii)) / *(umax+ii) < 0.000001 ){//circular
*(jr+ii) = 0.;
continue;
}
//Setup function
(params+tid)->delta= *(delta+ii*delta_stride);
(params+tid)->E= *(E+ii);
(params+tid)->Lz22delta= 0.5 * *(Lz+ii) * *(Lz+ii) / *(delta+ii*delta_stride) / *(delta+ii*delta_stride);
(params+tid)->I3U= *(I3U+ii);
(params+tid)->u0= *(u0+ii);
(params+tid)->sinh2u0= *(sinh2u0+ii);
(params+tid)->v0= *(v0+ii);
(params+tid)->sin2v0= *(sin2v0+ii);
(params+tid)->potu0v0= *(potu0v0+ii);
(JRInt+tid)->function = &JRStaeckelIntegrand;
(JRInt+tid)->params = params+tid;
//Integrate
*(jr+ii)= gsl_integration_glfixed (JRInt+tid,*(umin+ii),*(umax+ii),T)
* sqrt(2.) * *(delta+ii*delta_stride) / M_PI;
}
free(JRInt);
free(params);
gsl_integration_glfixed_table_free ( T );
}
void calcJzStaeckel(int ndata,
double * jz,
double * vmin,
double * E,
double * Lz,
double * I3V,
int ndelta,
double * delta,
double * u0,
double * cosh2u0,
double * sinh2u0,
double * potupi2,
int nargs,
struct potentialArg * actionAngleArgs,
int order){
int ii, tid, nthreads;
#ifdef _OPENMP
nthreads = omp_get_max_threads();
#else
nthreads = 1;
#endif
gsl_function * JzInt= (gsl_function *) malloc ( nthreads * sizeof(gsl_function) );
struct JzStaeckelArg * params= (struct JzStaeckelArg *) malloc ( nthreads * sizeof (struct JzStaeckelArg) );
for (tid=0; tid < nthreads; tid++){
(params+tid)->nargs= nargs;
(params+tid)->actionAngleArgs= actionAngleArgs;
}
//Setup integrator
gsl_integration_glfixed_table * T= gsl_integration_glfixed_table_alloc (order);
int delta_stride= ndelta == 1 ? 0 : 1;
UNUSED int chunk= CHUNKSIZE;
#pragma omp parallel for schedule(static,chunk) \
private(tid,ii) \
shared(jz,vmin,JzInt,params,T,delta,E,Lz,I3V,u0,cosh2u0,sinh2u0,potupi2)
for (ii=0; ii < ndata; ii++){
#ifdef _OPENMP
tid= omp_get_thread_num();
#else
tid = 0;
#endif
if ( *(vmin+ii) == -9999.99 ){
*(jz+ii)= 9999.99;
continue;
}
if ( (0.5 * M_PI - *(vmin+ii)) / M_PI * 2. < 0.000001 ){//circular
*(jz+ii) = 0.;
continue;
}
//Setup function
(params+tid)->delta= *(delta+ii*delta_stride);
(params+tid)->E= *(E+ii);
(params+tid)->Lz22delta= 0.5 * *(Lz+ii) * *(Lz+ii) / *(delta+ii*delta_stride) / *(delta+ii*delta_stride);
(params+tid)->I3V= *(I3V+ii);
(params+tid)->u0= *(u0+ii);
(params+tid)->cosh2u0= *(cosh2u0+ii);
(params+tid)->sinh2u0= *(sinh2u0+ii);
(params+tid)->potupi2= *(potupi2+ii);
(JzInt+tid)->function = &JzStaeckelIntegrand;
(JzInt+tid)->params = params+tid;
//Integrate
*(jz+ii)= gsl_integration_glfixed (JzInt+tid,*(vmin+ii),M_PI/2.,T)
* 2 * sqrt(2.) * *(delta+ii*delta_stride) / M_PI;
}
free(JzInt);
free(params);
gsl_integration_glfixed_table_free ( T );
}
void actionAngleStaeckel_actionsFreqs(int ndata,
double *R,
double *vR,
double *vT,
double *z,
double *vz,
double *u0,
int npot,
int * pot_type,
double * pot_args,
int ndelta,
double * delta,
int order,
double *jr,
double *jz,
double *Omegar,
double *Omegaphi,
double *Omegaz,
int * err){
int ii;
double tdelta;
//Set up the potentials
struct potentialArg * actionAngleArgs= (struct potentialArg *) malloc ( npot * sizeof (struct potentialArg) );
parse_leapFuncArgs_Full(npot,actionAngleArgs,&pot_type,&pot_args);
//E,Lz
double *E= (double *) malloc ( ndata * sizeof(double) );
double *Lz= (double *) malloc ( ndata * sizeof(double) );
calcEL(ndata,R,vR,vT,z,vz,E,Lz,npot,actionAngleArgs);
//Calculate all necessary parameters
double *ux= (double *) malloc ( ndata * sizeof(double) );
double *vx= (double *) malloc ( ndata * sizeof(double) );
Rz_to_uv_vec(ndata,R,z,ux,vx,ndelta,delta);
double *coshux= (double *) malloc ( ndata * sizeof(double) );
double *sinhux= (double *) malloc ( ndata * sizeof(double) );
double *sinvx= (double *) malloc ( ndata * sizeof(double) );
double *cosvx= (double *) malloc ( ndata * sizeof(double) );
double *pux= (double *) malloc ( ndata * sizeof(double) );
double *pvx= (double *) malloc ( ndata * sizeof(double) );
double *sinh2u0= (double *) malloc ( ndata * sizeof(double) );
double *cosh2u0= (double *) malloc ( ndata * sizeof(double) );
double *v0= (double *) malloc ( ndata * sizeof(double) );
double *sin2v0= (double *) malloc ( ndata * sizeof(double) );
double *potu0v0= (double *) malloc ( ndata * sizeof(double) );
double *potupi2= (double *) malloc ( ndata * sizeof(double) );
double *I3U= (double *) malloc ( ndata * sizeof(double) );
double *I3V= (double *) malloc ( ndata * sizeof(double) );
int delta_stride= ndelta == 1 ? 0 : 1;
UNUSED int chunk= CHUNKSIZE;
#pragma omp parallel for schedule(static,chunk) private(ii,tdelta)
for (ii=0; ii < ndata; ii++){
tdelta= *(delta+ii*delta_stride);
*(coshux+ii)= cosh(*(ux+ii));
*(sinhux+ii)= sinh(*(ux+ii));
*(cosvx+ii)= cos(*(vx+ii));
*(sinvx+ii)= sin(*(vx+ii));
*(pux+ii)= tdelta * (*(vR+ii) * *(coshux+ii) * *(sinvx+ii)
+ *(vz+ii) * *(sinhux+ii) * *(cosvx+ii));
*(pvx+ii)= tdelta * (*(vR+ii) * *(sinhux+ii) * *(cosvx+ii)
- *(vz+ii) * *(coshux+ii) * *(sinvx+ii));
*(sinh2u0+ii)= sinh(*(u0+ii)) * sinh(*(u0+ii));
*(cosh2u0+ii)= cosh(*(u0+ii)) * cosh(*(u0+ii));
*(v0+ii)= 0.5 * M_PI; //*(vx+ii);
*(sin2v0+ii)= sin(*(v0+ii)) * sin(*(v0+ii));
*(potu0v0+ii)= evaluatePotentialsUV(*(u0+ii),*(v0+ii),tdelta,
npot,actionAngleArgs);
*(I3U+ii)= *(E+ii) * *(sinhux+ii) * *(sinhux+ii)
- 0.5 * *(pux+ii) * *(pux+ii) / tdelta / tdelta
- 0.5 * *(Lz+ii) * *(Lz+ii) / tdelta / tdelta / *(sinhux+ii) / *(sinhux+ii)
- ( *(sinhux+ii) * *(sinhux+ii) + *(sin2v0+ii))
*evaluatePotentialsUV(*(ux+ii),*(v0+ii),tdelta,
npot,actionAngleArgs)
+ ( *(sinh2u0+ii) + *(sin2v0+ii) )* *(potu0v0+ii);
*(potupi2+ii)= evaluatePotentialsUV(*(u0+ii),0.5 * M_PI,tdelta,
npot,actionAngleArgs);
*(I3V+ii)= - *(E+ii) * *(sinvx+ii) * *(sinvx+ii)
+ 0.5 * *(pvx+ii) * *(pvx+ii) / tdelta / tdelta
+ 0.5 * *(Lz+ii) * *(Lz+ii) / tdelta / tdelta / *(sinvx+ii) / *(sinvx+ii)
- *(cosh2u0+ii) * *(potupi2+ii)
+ ( *(sinh2u0+ii) + *(sinvx+ii) * *(sinvx+ii))
* evaluatePotentialsUV(*(u0+ii),*(vx+ii),tdelta,
npot,actionAngleArgs);
}
//Calculate 'peri' and 'apo'centers
double *umin= (double *) malloc ( ndata * sizeof(double) );
double *umax= (double *) malloc ( ndata * sizeof(double) );
double *vmin= (double *) malloc ( ndata * sizeof(double) );
calcUminUmax(ndata,umin,umax,ux,pux,E,Lz,I3U,ndelta,delta,u0,sinh2u0,v0,
sin2v0,potu0v0,npot,actionAngleArgs);
calcVmin(ndata,vmin,vx,pvx,E,Lz,I3V,ndelta,delta,u0,cosh2u0,sinh2u0,potupi2,
npot,actionAngleArgs);
//Calculate the actions
calcJRStaeckel(ndata,jr,umin,umax,E,Lz,I3U,ndelta,delta,u0,sinh2u0,v0,sin2v0,
potu0v0,npot,actionAngleArgs,order);
calcJzStaeckel(ndata,jz,vmin,E,Lz,I3V,ndelta,delta,u0,cosh2u0,sinh2u0,
potupi2,npot,actionAngleArgs,order);
//Calculate the derivatives of the actions wrt the integrals of motion
double *dJRdE= (double *) malloc ( ndata * sizeof(double) );
double *dJRdLz= (double *) malloc ( ndata * sizeof(double) );
double *dJRdI3= (double *) malloc ( ndata * sizeof(double) );
double *dJzdE= (double *) malloc ( ndata * sizeof(double) );
double *dJzdLz= (double *) malloc ( ndata * sizeof(double) );
double *dJzdI3= (double *) malloc ( ndata * sizeof(double) );
double *detA= (double *) malloc ( ndata * sizeof(double) );
calcdJRStaeckel(ndata,dJRdE,dJRdLz,dJRdI3,
umin,umax,E,Lz,I3U,ndelta,delta,u0,sinh2u0,v0,sin2v0,
potu0v0,npot,actionAngleArgs,order);
calcdJzStaeckel(ndata,dJzdE,dJzdLz,dJzdI3,
vmin,E,Lz,I3V,ndelta,delta,u0,cosh2u0,sinh2u0,
potupi2,npot,actionAngleArgs,order);
calcFreqsFromDerivsStaeckel(ndata,Omegar,Omegaphi,Omegaz,detA,
dJRdE,dJRdLz,dJRdI3,
dJzdE,dJzdLz,dJzdI3);
//Free
free_potentialArgs(npot,actionAngleArgs);
free(actionAngleArgs);
free(E);
free(Lz);
free(ux);
free(vx);
free(coshux);
free(sinhux);
free(sinvx);
free(cosvx);
free(pux);
free(pvx);
free(sinh2u0);
free(cosh2u0);
free(v0);
free(sin2v0);
free(potu0v0);
free(potupi2);
free(I3U);
free(I3V);
free(umin);
free(umax);
free(vmin);
free(dJRdE);
free(dJRdLz);
free(dJRdI3);
free(dJzdE);
free(detA);
free(dJzdLz);
free(dJzdI3);
}
void actionAngleStaeckel_actionsFreqsAngles(int ndata,
double *R,
double *vR,
double *vT,
double *z,
double *vz,
double *u0,
int npot,
int * pot_type,
double * pot_args,
int ndelta,
double * delta,
int order,
double *jr,
double *jz,
double *Omegar,
double *Omegaphi,
double *Omegaz,
double *Angler,
double *Anglephi,
double *Anglez,
int * err){
int ii;
double tdelta;
//Set up the potentials
struct potentialArg * actionAngleArgs= (struct potentialArg *) malloc ( npot * sizeof (struct potentialArg) );
parse_leapFuncArgs_Full(npot,actionAngleArgs,&pot_type,&pot_args);
//E,Lz
double *E= (double *) malloc ( ndata * sizeof(double) );
double *Lz= (double *) malloc ( ndata * sizeof(double) );
calcEL(ndata,R,vR,vT,z,vz,E,Lz,npot,actionAngleArgs);
//Calculate all necessary parameters
double *ux= (double *) malloc ( ndata * sizeof(double) );
double *vx= (double *) malloc ( ndata * sizeof(double) );
Rz_to_uv_vec(ndata,R,z,ux,vx,ndelta,delta);
double *coshux= (double *) malloc ( ndata * sizeof(double) );
double *sinhux= (double *) malloc ( ndata * sizeof(double) );
double *sinvx= (double *) malloc ( ndata * sizeof(double) );
double *cosvx= (double *) malloc ( ndata * sizeof(double) );
double *pux= (double *) malloc ( ndata * sizeof(double) );
double *pvx= (double *) malloc ( ndata * sizeof(double) );
double *sinh2u0= (double *) malloc ( ndata * sizeof(double) );
double *cosh2u0= (double *) malloc ( ndata * sizeof(double) );
double *v0= (double *) malloc ( ndata * sizeof(double) );
double *sin2v0= (double *) malloc ( ndata * sizeof(double) );
double *potu0v0= (double *) malloc ( ndata * sizeof(double) );
double *potupi2= (double *) malloc ( ndata * sizeof(double) );
double *I3U= (double *) malloc ( ndata * sizeof(double) );
double *I3V= (double *) malloc ( ndata * sizeof(double) );
int delta_stride= ndelta == 1 ? 0 : 1;
UNUSED int chunk= CHUNKSIZE;
#pragma omp parallel for schedule(static,chunk) private(ii,tdelta)
for (ii=0; ii < ndata; ii++){
tdelta= *(delta+ii*delta_stride);
*(coshux+ii)= cosh(*(ux+ii));
*(sinhux+ii)= sinh(*(ux+ii));
*(cosvx+ii)= cos(*(vx+ii));
*(sinvx+ii)= sin(*(vx+ii));
*(pux+ii)= tdelta * (*(vR+ii) * *(coshux+ii) * *(sinvx+ii)
+ *(vz+ii) * *(sinhux+ii) * *(cosvx+ii));
*(pvx+ii)= tdelta * (*(vR+ii) * *(sinhux+ii) * *(cosvx+ii)
- *(vz+ii) * *(coshux+ii) * *(sinvx+ii));
*(sinh2u0+ii)= sinh(*(u0+ii)) * sinh(*(u0+ii));
*(cosh2u0+ii)= cosh(*(u0+ii)) * cosh(*(u0+ii));
*(v0+ii)= 0.5 * M_PI; //*(vx+ii);
*(sin2v0+ii)= sin(*(v0+ii)) * sin(*(v0+ii));
*(potu0v0+ii)= evaluatePotentialsUV(*(u0+ii),*(v0+ii),tdelta,
npot,actionAngleArgs);
*(I3U+ii)= *(E+ii) * *(sinhux+ii) * *(sinhux+ii)
- 0.5 * *(pux+ii) * *(pux+ii) / tdelta / tdelta
- 0.5 * *(Lz+ii) * *(Lz+ii) / tdelta / tdelta / *(sinhux+ii) / *(sinhux+ii)
- ( *(sinhux+ii) * *(sinhux+ii) + *(sin2v0+ii))
*evaluatePotentialsUV(*(ux+ii),*(v0+ii),tdelta,
npot,actionAngleArgs)
+ ( *(sinh2u0+ii) + *(sin2v0+ii) )* *(potu0v0+ii);
*(potupi2+ii)= evaluatePotentialsUV(*(u0+ii),0.5 * M_PI,tdelta,
npot,actionAngleArgs);
*(I3V+ii)= - *(E+ii) * *(sinvx+ii) * *(sinvx+ii)
+ 0.5 * *(pvx+ii) * *(pvx+ii) / tdelta / tdelta
+ 0.5 * *(Lz+ii) * *(Lz+ii) / tdelta / tdelta / *(sinvx+ii) / *(sinvx+ii)
- *(cosh2u0+ii) * *(potupi2+ii)
+ ( *(sinh2u0+ii) + *(sinvx+ii) * *(sinvx+ii))
* evaluatePotentialsUV(*(u0+ii),*(vx+ii),tdelta,
npot,actionAngleArgs);
}
//Calculate 'peri' and 'apo'centers
double *umin= (double *) malloc ( ndata * sizeof(double) );
double *umax= (double *) malloc ( ndata * sizeof(double) );
double *vmin= (double *) malloc ( ndata * sizeof(double) );
calcUminUmax(ndata,umin,umax,ux,pux,E,Lz,I3U,ndelta,delta,u0,sinh2u0,v0,
sin2v0,potu0v0,npot,actionAngleArgs);
calcVmin(ndata,vmin,vx,pvx,E,Lz,I3V,ndelta,delta,u0,cosh2u0,sinh2u0,potupi2,
npot,actionAngleArgs);
//Calculate the actions
calcJRStaeckel(ndata,jr,umin,umax,E,Lz,I3U,ndelta,delta,u0,sinh2u0,v0,sin2v0,
potu0v0,npot,actionAngleArgs,order);
calcJzStaeckel(ndata,jz,vmin,E,Lz,I3V,ndelta,delta,u0,cosh2u0,sinh2u0,
potupi2,npot,actionAngleArgs,order);
//Calculate the derivatives of the actions wrt the integrals of motion
double *dJRdE= (double *) malloc ( ndata * sizeof(double) );
double *dJRdLz= (double *) malloc ( ndata * sizeof(double) );
double *dJRdI3= (double *) malloc ( ndata * sizeof(double) );
double *dJzdE= (double *) malloc ( ndata * sizeof(double) );
double *dJzdLz= (double *) malloc ( ndata * sizeof(double) );
double *dJzdI3= (double *) malloc ( ndata * sizeof(double) );
double *detA= (double *) malloc ( ndata * sizeof(double) );
calcdJRStaeckel(ndata,dJRdE,dJRdLz,dJRdI3,
umin,umax,E,Lz,I3U,ndelta,delta,u0,sinh2u0,v0,sin2v0,
potu0v0,npot,actionAngleArgs,order);
calcdJzStaeckel(ndata,dJzdE,dJzdLz,dJzdI3,
vmin,E,Lz,I3V,ndelta,delta,u0,cosh2u0,sinh2u0,
potupi2,npot,actionAngleArgs,order);
calcFreqsFromDerivsStaeckel(ndata,Omegar,Omegaphi,Omegaz,detA,
dJRdE,dJRdLz,dJRdI3,
dJzdE,dJzdLz,dJzdI3);
double *dI3dJR= (double *) malloc ( ndata * sizeof(double) );
double *dI3dJz= (double *) malloc ( ndata * sizeof(double) );
double *dI3dLz= (double *) malloc ( ndata * sizeof(double) );
calcdI3dJFromDerivsStaeckel(ndata,dI3dJR,dI3dJz,dI3dLz,detA,
dJRdE,dJzdE,dJRdLz,dJzdLz);
calcAnglesStaeckel(ndata,Angler,Anglephi,Anglez,
Omegar,Omegaphi,Omegaz,dI3dJR,dI3dJz,dI3dLz,
dJRdE,dJRdLz,dJRdI3,
dJzdE,dJzdLz,dJzdI3,
ux,vx,pux,pvx,
umin,umax,E,Lz,I3U,ndelta,delta,u0,sinh2u0,v0,sin2v0,
potu0v0,
vmin,I3V,cosh2u0,potupi2,
npot,actionAngleArgs,order);
//Free
free_potentialArgs(npot,actionAngleArgs);
free(actionAngleArgs);
free(E);
free(Lz);
free(ux);
free(vx);
free(coshux);
free(sinhux);
free(sinvx);
free(cosvx);
free(pux);
free(pvx);
free(sinh2u0);
free(cosh2u0);
free(v0);
free(sin2v0);
free(potu0v0);
free(potupi2);
free(I3U);
free(I3V);
free(umin);
free(umax);
free(vmin);
free(dJRdE);
free(dJRdLz);
free(dJRdI3);
free(dJzdE);
free(dJzdLz);
free(dJzdI3);
free(detA);
free(dI3dJR);
free(dI3dJz);
free(dI3dLz);
}
void calcFreqsFromDerivsStaeckel(int ndata,
double * Omegar,
double * Omegaphi,
double * Omegaz,
double * detA,
double * djrdE,
double * djrdLz,
double * djrdI3,
double * djzdE,
double * djzdLz,
double * djzdI3){
int ii;
UNUSED int chunk= CHUNKSIZE;
#pragma omp parallel for schedule(static,chunk) \
private(ii) \
shared(Omegar,Omegaphi,Omegaz,djrdE,djrdLz,djrdI3,djzdE,djzdLz,djzdI3,detA)
for (ii=0; ii < ndata; ii++){
if ( *(djrdE+ii) == 9999.99 || *(djzdE+ii) == 9999.99 ) {
*(Omegar+ii)= 9999.99;
*(Omegaz+ii)= 9999.99;
*(Omegaphi+ii)= 9999.99;
} else {
//First calculate the determinant of the relevant matrix
*(detA+ii)= *(djrdE+ii) * *(djzdI3+ii) - *(djzdE+ii) * *(djrdI3+ii);
//Then calculate the frequencies
*(Omegar+ii)= *(djzdI3+ii) / *(detA+ii);
*(Omegaz+ii)= - *(djrdI3+ii) / *(detA+ii);
*(Omegaphi+ii)= ( *(djrdI3+ii) * *(djzdLz+ii) - *(djzdI3+ii) * *(djrdLz+ii)) / *(detA+ii);
}
}
}
void calcdI3dJFromDerivsStaeckel(int ndata,
double * dI3dJR,
double * dI3dJz,
double * dI3dLz,
double * detA,
double * djrdE,
double * djzdE,
double * djrdLz,
double * djzdLz){
int ii;
UNUSED int chunk= CHUNKSIZE;
#pragma omp parallel for schedule(static,chunk) \
private(ii) \
shared(djrdE,djzdE,djrdLz,djzdLz,dI3dJR,dI3dJz,dI3dLz,detA)
for (ii=0; ii < ndata; ii++){
*(dI3dJR+ii)= - *(djzdE+ii) / *(detA+ii);
*(dI3dJz+ii)= *(djrdE+ii) / *(detA+ii);
*(dI3dLz+ii)= -( *(djrdE+ii) * *(djzdLz+ii) - *(djzdE+ii) * *(djrdLz+ii) ) / *(detA+ii);
}
}
void calcdJRStaeckel(int ndata,
double * djrdE,
double * djrdLz,
double * djrdI3,
double * umin,
double * umax,
double * E,
double * Lz,
double * I3U,
int ndelta,
double * delta,
double * u0,
double * sinh2u0,
double * v0,
double * sin2v0,
double * potu0v0,
int nargs,
struct potentialArg * actionAngleArgs,
int order){
int ii, tid, nthreads;
double mid;
#ifdef _OPENMP
nthreads = omp_get_max_threads();
#else
nthreads = 1;
#endif
gsl_function * dJRInt= (gsl_function *) malloc ( nthreads * sizeof(gsl_function) );
struct dJRStaeckelArg * params= (struct dJRStaeckelArg *) malloc ( nthreads * sizeof (struct dJRStaeckelArg) );
for (tid=0; tid < nthreads; tid++){
(params+tid)->nargs= nargs;
(params+tid)->actionAngleArgs= actionAngleArgs;
}
//Setup integrator
gsl_integration_glfixed_table * T= gsl_integration_glfixed_table_alloc (order);
int delta_stride= ndelta == 1 ? 0 : 1;
UNUSED int chunk= CHUNKSIZE;
#pragma omp parallel for schedule(static,chunk) \
private(tid,ii,mid) \
shared(djrdE,djrdLz,djrdI3,umin,umax,dJRInt,params,T,delta,E,Lz,I3U,u0,sinh2u0,v0,sin2v0,potu0v0)
for (ii=0; ii < ndata; ii++){
#ifdef _OPENMP
tid= omp_get_thread_num();
#else
tid = 0;
#endif
if ( *(umin+ii) == -9999.99 || *(umax+ii) == -9999.99 ){
*(djrdE+ii)= 9999.99;
*(djrdLz+ii)= 9999.99;
*(djrdI3+ii)= 9999.99;
continue;
}
if ( (*(umax+ii) - *(umin+ii)) / *(umax+ii) < 0.000001 ){//circular
*(djrdE+ii) = 0.;
*(djrdLz+ii) = 0.;
*(djrdI3+ii) = 0.;
continue;
}
//Setup function
(params+tid)->delta= *(delta+ii*delta_stride);
(params+tid)->E= *(E+ii);
(params+tid)->Lz22delta= 0.5 * *(Lz+ii) * *(Lz+ii) / *(delta+ii*delta_stride) / *(delta+ii*delta_stride);
(params+tid)->I3U= *(I3U+ii);
(params+tid)->u0= *(u0+ii);
(params+tid)->sinh2u0= *(sinh2u0+ii);
(params+tid)->v0= *(v0+ii);
(params+tid)->sin2v0= *(sin2v0+ii);
(params+tid)->potu0v0= *(potu0v0+ii);
(params+tid)->umin= *(umin+ii);
(params+tid)->umax= *(umax+ii);
(dJRInt+tid)->function = &dJRdELowStaeckelIntegrand;
(dJRInt+tid)->params = params+tid;
mid= sqrt( 0.5 * ( *(umax+ii) - *(umin+ii) ) );
//Integrate to get djrdE
*(djrdE+ii)= gsl_integration_glfixed (dJRInt+tid,0.,mid,T);
(dJRInt+tid)->function = &dJRdEHighStaeckelIntegrand;
*(djrdE+ii)+= gsl_integration_glfixed (dJRInt+tid,0.,mid,T);
*(djrdE+ii)*= *(delta+ii*delta_stride) / M_PI / sqrt(2.);
//then calculate djrdLz
(dJRInt+tid)->function = &dJRdLzLowStaeckelIntegrand;
*(djrdLz+ii)= gsl_integration_glfixed (dJRInt+tid,0.,mid,T);
(dJRInt+tid)->function = &dJRdLzHighStaeckelIntegrand;
*(djrdLz+ii)+= gsl_integration_glfixed (dJRInt+tid,0.,mid,T);
*(djrdLz+ii)*= - *(Lz+ii) / M_PI / sqrt(2.) / *(delta+ii*delta_stride);
//then calculate djrdI3
(dJRInt+tid)->function = &dJRdI3LowStaeckelIntegrand;
*(djrdI3+ii)= gsl_integration_glfixed (dJRInt+tid,0.,mid,T);
(dJRInt+tid)->function = &dJRdI3HighStaeckelIntegrand;
*(djrdI3+ii)+= gsl_integration_glfixed (dJRInt+tid,0.,mid,T);
*(djrdI3+ii)*= - *(delta+ii*delta_stride) / M_PI / sqrt(2.);
}
free(dJRInt);
free(params);
gsl_integration_glfixed_table_free ( T );
}
void calcdJzStaeckel(int ndata,
double * djzdE,
double * djzdLz,
double * djzdI3,
double * vmin,
double * E,
double * Lz,
double * I3V,
int ndelta,
double * delta,
double * u0,
double * cosh2u0,
double * sinh2u0,
double * potupi2,
int nargs,
struct potentialArg * actionAngleArgs,
int order){
int ii, tid, nthreads;
double mid;
#ifdef _OPENMP
nthreads = omp_get_max_threads();
#else
nthreads = 1;
#endif
gsl_function * dJzInt= (gsl_function *) malloc ( nthreads * sizeof(gsl_function) );
struct dJzStaeckelArg * params= (struct dJzStaeckelArg *) malloc ( nthreads * sizeof (struct dJzStaeckelArg) );
for (tid=0; tid < nthreads; tid++){
(params+tid)->nargs= nargs;
(params+tid)->actionAngleArgs= actionAngleArgs;
}
//Setup integrator
gsl_integration_glfixed_table * T= gsl_integration_glfixed_table_alloc (order);
int delta_stride= ndelta == 1 ? 0 : 1;
UNUSED int chunk= CHUNKSIZE;
#pragma omp parallel for schedule(static,chunk) \
private(tid,ii,mid) \
shared(djzdE,djzdLz,djzdI3,vmin,dJzInt,params,T,delta,E,Lz,I3V,u0,cosh2u0,sinh2u0,potupi2)
for (ii=0; ii < ndata; ii++){
#ifdef _OPENMP
tid= omp_get_thread_num();
#else
tid = 0;
#endif
if ( *(vmin+ii) == -9999.99 ){
*(djzdE+ii)= 9999.99;
*(djzdLz+ii)= 9999.99;
*(djzdI3+ii)= 9999.99;
continue;
}
if ( (0.5 * M_PI - *(vmin+ii)) / M_PI * 2. < 0.000001 ){//circular
*(djzdE+ii) = 0.;
*(djzdLz+ii) = 0.;
*(djzdI3+ii) = 0.;
continue;
}
//Setup function
(params+tid)->delta= *(delta+ii*delta_stride);
(params+tid)->E= *(E+ii);
(params+tid)->Lz22delta= 0.5 * *(Lz+ii) * *(Lz+ii) / *(delta+ii*delta_stride) / *(delta+ii*delta_stride);
(params+tid)->I3V= *(I3V+ii);
(params+tid)->u0= *(u0+ii);
(params+tid)->cosh2u0= *(cosh2u0+ii);
(params+tid)->sinh2u0= *(sinh2u0+ii);
(params+tid)->potupi2= *(potupi2+ii);
(params+tid)->vmin= *(vmin+ii);
//First calculate dJzdE
(dJzInt+tid)->function = &dJzdELowStaeckelIntegrand;
(dJzInt+tid)->params = params+tid;
mid= sqrt( 0.5 * (M_PI/2. - *(vmin+ii) ) );
//BOVY: pv does not vanish at pi/2, so no need to break up the integral
//Integrate
*(djzdE+ii)= gsl_integration_glfixed (dJzInt+tid,0.,mid,T);
(dJzInt+tid)->function = &dJzdEHighStaeckelIntegrand;
*(djzdE+ii)+= gsl_integration_glfixed (dJzInt+tid,0.,mid,T);
*(djzdE+ii)*= sqrt(2.) * *(delta+ii*delta_stride) / M_PI;
//Then calculate dJzdLz
(dJzInt+tid)->function = &dJzdLzLowStaeckelIntegrand;
//Integrate
*(djzdLz+ii)= gsl_integration_glfixed (dJzInt+tid,0.,mid,T);
(dJzInt+tid)->function = &dJzdLzHighStaeckelIntegrand;
*(djzdLz+ii)+= gsl_integration_glfixed (dJzInt+tid,0.,mid,T);
*(djzdLz+ii)*= - *(Lz+ii) * sqrt(2.) / M_PI / *(delta+ii*delta_stride);
//Then calculate dJzdI3
(dJzInt+tid)->function = &dJzdI3LowStaeckelIntegrand;
//Integrate
*(djzdI3+ii)= gsl_integration_glfixed (dJzInt+tid,0.,mid,T);
(dJzInt+tid)->function = &dJzdI3HighStaeckelIntegrand;
*(djzdI3+ii)+= gsl_integration_glfixed (dJzInt+tid,0.,mid,T);
*(djzdI3+ii)*= sqrt(2.) * *(delta+ii*delta_stride) / M_PI;
}
free(dJzInt);
free(params);
gsl_integration_glfixed_table_free ( T );
}
void calcAnglesStaeckel(int ndata,
double * Angler,
double * Anglephi,
double * Anglez,
double * Omegar,
double * Omegaphi,
double * Omegaz,
double * dI3dJR,
double * dI3dJz,
double * dI3dLz,
double * dJRdE,
double * dJRdLz,
double * dJRdI3,
double * dJzdE,
double * dJzdLz,
double * dJzdI3,
double * ux,
double * vx,
double * pux,
double * pvx,
double * umin,
double * umax,
double * E,
double * Lz,
double * I3U,
int ndelta,
double * delta,
double * u0,
double * sinh2u0,
double * v0,
double * sin2v0,
double * potu0v0,
double * vmin,
double * I3V,
double * cosh2u0,
double * potupi2,
int nargs,
struct potentialArg * actionAngleArgs,
int order){
int ii, tid, nthreads;
double Or1, Or2, I3r1, I3r2,phitmp;
double mid, midpoint;
#ifdef _OPENMP
nthreads = omp_get_max_threads();
#else
nthreads = 1;
#endif
gsl_function * AngleuInt= (gsl_function *) malloc ( nthreads * sizeof(gsl_function) );
gsl_function * AnglevInt= (gsl_function *) malloc ( nthreads * sizeof(gsl_function) );
struct dJRStaeckelArg * paramsu= (struct dJRStaeckelArg *) malloc ( nthreads * sizeof (struct dJRStaeckelArg) );
struct dJzStaeckelArg * paramsv= (struct dJzStaeckelArg *) malloc ( nthreads * sizeof (struct dJzStaeckelArg) );
for (tid=0; tid < nthreads; tid++){
(paramsu+tid)->nargs= nargs;
(paramsu+tid)->actionAngleArgs= actionAngleArgs;
(paramsv+tid)->nargs= nargs;
(paramsv+tid)->actionAngleArgs= actionAngleArgs;
}
//Setup integrator
gsl_integration_glfixed_table * T= gsl_integration_glfixed_table_alloc (order);
int delta_stride= ndelta == 1 ? 0 : 1;
UNUSED int chunk= CHUNKSIZE;
#pragma omp parallel for schedule(static,chunk) \
private(tid,ii,mid,midpoint,Or1,Or2,I3r1,I3r2,phitmp) \
shared(Angler,Anglephi,Anglez,Omegar,Omegaz,dI3dJR,dI3dJz,umin,umax,AngleuInt,AnglevInt,paramsu,paramsv,T,delta,E,Lz,I3U,u0,sinh2u0,v0,sin2v0,potu0v0,vmin,I3V,cosh2u0,potupi2)
for (ii=0; ii < ndata; ii++){
#ifdef _OPENMP
tid= omp_get_thread_num();
#else
tid = 0;
#endif
if ( *(umin+ii) == -9999.99 || *(umax+ii) == -9999.99 ){
*(Angler+ii)= 9999.99;
*(Anglephi+ii)= 9999.99;
*(Anglez+ii)= 9999.99;
continue;
}
if ( (*(umax+ii) - *(umin+ii)) / *(umax+ii) < 0.000001 ){//circular
*(Angler+ii) = 0.;
*(Anglephi+ii) = 0.;
*(Anglez+ii) = 0.;
continue;
}
//Setup u function
(paramsu+tid)->delta= *(delta+ii*delta_stride);
(paramsu+tid)->E= *(E+ii);
(paramsu+tid)->Lz22delta= 0.5 * *(Lz+ii) * *(Lz+ii) / *(delta+ii*delta_stride) / *(delta+ii*delta_stride);
(paramsu+tid)->I3U= *(I3U+ii);
(paramsu+tid)->u0= *(u0+ii);
(paramsu+tid)->sinh2u0= *(sinh2u0+ii);
(paramsu+tid)->v0= *(v0+ii);
(paramsu+tid)->sin2v0= *(sin2v0+ii);
(paramsu+tid)->potu0v0= *(potu0v0+ii);
(paramsu+tid)->umin= *(umin+ii);
(paramsu+tid)->umax= *(umax+ii);
(AngleuInt+tid)->params = paramsu+tid;
midpoint= *(umin+ii)+ 0.5 * ( *(umax+ii) - *(umin+ii) );
if ( *(pux+ii) > 0. ) {
if ( *(ux+ii) > midpoint ) {
mid= sqrt( ( *(umax+ii) - *(ux+ii) ) );
(AngleuInt+tid)->function = &dJRdEHighStaeckelIntegrand;
Or1= gsl_integration_glfixed (AngleuInt+tid,0.,mid,T);
(AngleuInt+tid)->function = &dJRdI3HighStaeckelIntegrand;
I3r1= -gsl_integration_glfixed (AngleuInt+tid,0.,mid,T);
(AngleuInt+tid)->function = &dJRdLzHighStaeckelIntegrand;
*(Anglephi+ii)= M_PI * *(dJRdLz+ii) + *(Lz+ii) * gsl_integration_glfixed (AngleuInt+tid,0.,mid,T) / *(delta+ii*delta_stride) / sqrt(2.);
Or1*= *(delta+ii*delta_stride) / sqrt(2.);
I3r1*= *(delta+ii*delta_stride) / sqrt(2.);
Or1= M_PI * *(dJRdE+ii) - Or1;
I3r1= M_PI * *(dJRdI3+ii) - I3r1;
}
else {
mid= sqrt( ( *(ux+ii) - *(umin+ii) ) );
(AngleuInt+tid)->function = &dJRdELowStaeckelIntegrand;
Or1= gsl_integration_glfixed (AngleuInt+tid,0.,mid,T);
(AngleuInt+tid)->function = &dJRdI3LowStaeckelIntegrand;
I3r1= -gsl_integration_glfixed (AngleuInt+tid,0.,mid,T);
(AngleuInt+tid)->function = &dJRdLzLowStaeckelIntegrand;
*(Anglephi+ii)= - *(Lz+ii) * gsl_integration_glfixed (AngleuInt+tid,0.,mid,T) / *(delta+ii*delta_stride) / sqrt(2.);
Or1*= *(delta+ii*delta_stride) / sqrt(2.);
I3r1*= *(delta+ii*delta_stride) / sqrt(2.);
}
}
else {
if ( *(ux+ii) > midpoint ) {
mid= sqrt( ( *(umax+ii) - *(ux+ii) ) );
(AngleuInt+tid)->function = &dJRdEHighStaeckelIntegrand;
Or1= gsl_integration_glfixed (AngleuInt+tid,0.,mid,T);
Or1*= *(delta+ii*delta_stride) / sqrt(2.);
Or1= M_PI * *(dJRdE+ii) + Or1;
(AngleuInt+tid)->function = &dJRdI3HighStaeckelIntegrand;
I3r1= -gsl_integration_glfixed (AngleuInt+tid,0.,mid,T);
I3r1*= *(delta+ii*delta_stride) / sqrt(2.);
I3r1= M_PI * *(dJRdI3+ii) + I3r1;
(AngleuInt+tid)->function = &dJRdLzHighStaeckelIntegrand;
*(Anglephi+ii)= M_PI * *(dJRdLz+ii) - *(Lz+ii) * gsl_integration_glfixed (AngleuInt+tid,0.,mid,T) / *(delta+ii*delta_stride) / sqrt(2.);
}
else {
mid= sqrt( ( *(ux+ii) - *(umin+ii) ) );
(AngleuInt+tid)->function = &dJRdELowStaeckelIntegrand;
Or1= gsl_integration_glfixed (AngleuInt+tid,0.,mid,T);
Or1*= *(delta+ii*delta_stride) / sqrt(2.);
Or1= 2. * M_PI * *(dJRdE+ii) - Or1;
(AngleuInt+tid)->function = &dJRdI3LowStaeckelIntegrand;
I3r1= -gsl_integration_glfixed (AngleuInt+tid,0.,mid,T);
I3r1*= *(delta+ii*delta_stride) / sqrt(2.);
I3r1= 2. * M_PI * *(dJRdI3+ii) - I3r1;
(AngleuInt+tid)->function = &dJRdLzLowStaeckelIntegrand;
*(Anglephi+ii)= 2. * M_PI * *(dJRdLz+ii) + *(Lz+ii) * gsl_integration_glfixed (AngleuInt+tid,0.,mid,T) / *(delta+ii*delta_stride) / sqrt(2.);
}
}
//Setup v function
(paramsv+tid)->delta= *(delta+ii*delta_stride);
(paramsv+tid)->E= *(E+ii);
(paramsv+tid)->Lz22delta= 0.5 * *(Lz+ii) * *(Lz+ii) / *(delta+ii*delta_stride) / *(delta+ii*delta_stride);
(paramsv+tid)->I3V= *(I3V+ii);
(paramsv+tid)->u0= *(u0+ii);
(paramsv+tid)->cosh2u0= *(cosh2u0+ii);
(paramsv+tid)->sinh2u0= *(sinh2u0+ii);
(paramsv+tid)->potupi2= *(potupi2+ii);
(paramsv+tid)->vmin= *(vmin+ii);
(AnglevInt+tid)->params = paramsv+tid;
midpoint= *(vmin+ii)+ 0.5 * ( 0.5 * M_PI - *(vmin+ii) );
if ( *(pvx+ii) > 0. ) {
if ( *(vx+ii) < midpoint || *(vx+ii) > (M_PI - midpoint) ) {
mid = ( *(vx+ii) > 0.5 * M_PI ) ? sqrt( (M_PI - *(vx+ii) - *(vmin+ii))): sqrt( *(vx+ii) - *(vmin+ii));
(AnglevInt+tid)->function = &dJzdELowStaeckelIntegrand;
Or2= gsl_integration_glfixed (AnglevInt+tid,0.,mid,T);
Or2*= *(delta+ii*delta_stride) / sqrt(2.);
(AnglevInt+tid)->function = &dJzdI3LowStaeckelIntegrand;
I3r2= gsl_integration_glfixed (AnglevInt+tid,0.,mid,T);
I3r2*= *(delta+ii*delta_stride) / sqrt(2.);
(AnglevInt+tid)->function = &dJzdLzLowStaeckelIntegrand;
phitmp= gsl_integration_glfixed (AnglevInt+tid,0.,mid,T);
phitmp*= - *(Lz+ii) / *(delta+ii*delta_stride) / sqrt(2.);
if ( *(vx+ii) > 0.5 * M_PI ) {
Or2= M_PI * *(dJzdE+ii) - Or2;
I3r2= M_PI * *(dJzdI3+ii) - I3r2;
phitmp= M_PI * *(dJzdLz+ii) - phitmp;
}
}
else {
mid= sqrt( fabs ( 0.5 * M_PI - *(vx+ii) ) );
(AnglevInt+tid)->function = &dJzdEHighStaeckelIntegrand;
Or2= gsl_integration_glfixed (AnglevInt+tid,0.,mid,T);
Or2*= *(delta+ii*delta_stride) / sqrt(2.);
(AnglevInt+tid)->function = &dJzdI3HighStaeckelIntegrand;
I3r2= gsl_integration_glfixed (AnglevInt+tid,0.,mid,T);
I3r2*= *(delta+ii*delta_stride) / sqrt(2.);
(AnglevInt+tid)->function = &dJzdLzHighStaeckelIntegrand;
phitmp= gsl_integration_glfixed (AnglevInt+tid,0.,mid,T);
phitmp*= - *(Lz+ii) / *(delta+ii*delta_stride) / sqrt(2.);
if ( *(vx+ii) > 0.5 * M_PI ) {
Or2= 0.5 * M_PI * *(dJzdE+ii) + Or2;
I3r2= 0.5 * M_PI * *(dJzdI3+ii) + I3r2;
phitmp= 0.5 * M_PI * *(dJzdLz+ii) + phitmp;
}
else {
Or2= 0.5 * M_PI * *(dJzdE+ii) - Or2;
I3r2= 0.5 * M_PI * *(dJzdI3+ii) - I3r2;
phitmp= 0.5 * M_PI * *(dJzdLz+ii) - phitmp;
}
}
}
else {
if ( *(vx+ii) < midpoint || *(vx+ii) > (M_PI - midpoint)) {
mid = ( *(vx+ii) > 0.5 * M_PI ) ? sqrt( (M_PI - *(vx+ii) - *(vmin+ii))): sqrt( *(vx+ii) - *(vmin+ii));
(AnglevInt+tid)->function = &dJzdELowStaeckelIntegrand;
Or2= gsl_integration_glfixed (AnglevInt+tid,0.,mid,T);
Or2*= *(delta+ii*delta_stride) / sqrt(2.);
(AnglevInt+tid)->function = &dJzdI3LowStaeckelIntegrand;
I3r2= gsl_integration_glfixed (AnglevInt+tid,0.,mid,T);
I3r2*= *(delta+ii*delta_stride) / sqrt(2.);
(AnglevInt+tid)->function = &dJzdLzLowStaeckelIntegrand;
phitmp= gsl_integration_glfixed (AnglevInt+tid,0.,mid,T);
phitmp*= - *(Lz+ii) / *(delta+ii*delta_stride) / sqrt(2.);
if ( *(vx+ii) < 0.5 * M_PI ) {
Or2= 2. * M_PI * *(dJzdE+ii) - Or2;
I3r2= 2. * M_PI * *(dJzdI3+ii) - I3r2;
phitmp= 2. * M_PI * *(dJzdLz+ii) - phitmp;
}
else {
Or2= M_PI * *(dJzdE+ii) + Or2;
I3r2= M_PI * *(dJzdI3+ii) + I3r2;
phitmp= M_PI * *(dJzdLz+ii) + phitmp;
}
}
else {
mid= sqrt( fabs ( 0.5 * M_PI - *(vx+ii) ) );
(AnglevInt+tid)->function = &dJzdEHighStaeckelIntegrand;
Or2= gsl_integration_glfixed (AnglevInt+tid,0.,mid,T);
Or2*= *(delta+ii*delta_stride) / sqrt(2.);
(AnglevInt+tid)->function = &dJzdI3HighStaeckelIntegrand;
I3r2= gsl_integration_glfixed (AnglevInt+tid,0.,mid,T);
I3r2*= *(delta+ii*delta_stride) / sqrt(2.);
(AnglevInt+tid)->function = &dJzdLzHighStaeckelIntegrand;
phitmp= gsl_integration_glfixed (AnglevInt+tid,0.,mid,T);
phitmp*= - *(Lz+ii) / *(delta+ii*delta_stride) / sqrt(2.);
if ( *(vx+ii) < 0.5 * M_PI ) {
Or2= 1.5 * M_PI * *(dJzdE+ii) + Or2;
I3r2= 1.5 * M_PI * *(dJzdI3+ii) + I3r2;
phitmp= 1.5 * M_PI * *(dJzdLz+ii) + phitmp;
}
else {
Or2= 1.5 * M_PI * *(dJzdE+ii) - Or2;
I3r2= 1.5 * M_PI * *(dJzdI3+ii) - I3r2;
phitmp= 1.5 * M_PI * *(dJzdLz+ii) - phitmp;
}
}
}
*(Angler+ii)= *(Omegar+ii) * ( Or1 + Or2 )
+ *(dI3dJR+ii) * ( I3r1 + I3r2 );
// In Binney (2012) Anglez starts at zmax/vmin and v_z < 0 / v_v > 0;
// Put this on the same system as Isochrone and Spherical angles +pi/2
*(Anglez+ii)= *(Omegaz+ii) * ( Or1 + Or2 )
+ *(dI3dJz+ii) * ( I3r1 + I3r2 ) + 0.5 * M_PI;
*(Anglephi+ii)+= phitmp;
*(Anglephi+ii)+= *(Omegaphi+ii) * ( Or1 + Or2 )
+ *(dI3dLz+ii) * ( I3r1 + I3r2 );
*(Angler+ii)= fmod(*(Angler+ii),2. * M_PI);
*(Anglez+ii)= fmod(*(Anglez+ii),2. * M_PI);
while ( *(Angler+ii) < 0. )
*(Angler+ii)+= 2. * M_PI;
while ( *(Anglez+ii) < 0. )
*(Anglez+ii)+= 2. * M_PI;
while ( *(Angler+ii) > 2. * M_PI )
*(Angler+ii)-= 2. * M_PI;
while ( *(Anglez+ii) > 2. * M_PI )
*(Anglez+ii)-= 2. * M_PI;
}
free(AngleuInt);
free(AnglevInt);
free(paramsu);
free(paramsv);
gsl_integration_glfixed_table_free ( T );
}
void calcUminUmax(int ndata,
double * umin,
double * umax,
double * ux,
double * pux,
double * E,
double * Lz,
double * I3U,
int ndelta,
double * delta,
double * u0,
double * sinh2u0,
double * v0,
double * sin2v0,
double * potu0v0,
int nargs,
struct potentialArg * actionAngleArgs){
int ii, tid, nthreads;
#ifdef _OPENMP
nthreads = omp_get_max_threads();
#else
nthreads = 1;
#endif
double peps, meps;
gsl_function * JRRoot= (gsl_function *) malloc ( nthreads * sizeof(gsl_function) );
struct JRStaeckelArg * params= (struct JRStaeckelArg *) malloc ( nthreads * sizeof (struct JRStaeckelArg) );
//Setup solver
int status;
int iter, max_iter = 100;
const gsl_root_fsolver_type *T;
struct pragmasolver *s= (struct pragmasolver *) malloc ( nthreads * sizeof (struct pragmasolver) );;
double u_lo, u_hi;
T = gsl_root_fsolver_brent;
for (tid=0; tid < nthreads; tid++){
(params+tid)->nargs= nargs;
(params+tid)->actionAngleArgs= actionAngleArgs;
(s+tid)->s= gsl_root_fsolver_alloc (T);
}
int delta_stride= ndelta == 1 ? 0 : 1;
UNUSED int chunk= CHUNKSIZE;
gsl_set_error_handler_off();
#pragma omp parallel for schedule(static,chunk) \
private(tid,ii,iter,status,u_lo,u_hi,meps,peps) \
shared(umin,umax,JRRoot,params,s,ux,delta,E,Lz,I3U,u0,sinh2u0,v0,sin2v0,potu0v0,max_iter)
for (ii=0; ii < ndata; ii++){
#ifdef _OPENMP
tid= omp_get_thread_num();
#else
tid = 0;
#endif
//Setup function
(params+tid)->delta= *(delta+ii*delta_stride);
(params+tid)->E= *(E+ii);
(params+tid)->Lz22delta= 0.5 * *(Lz+ii) * *(Lz+ii) / *(delta+ii*delta_stride) / *(delta+ii*delta_stride);
(params+tid)->I3U= *(I3U+ii);
(params+tid)->u0= *(u0+ii);
(params+tid)->sinh2u0= *(sinh2u0+ii);
(params+tid)->v0= *(v0+ii);
(params+tid)->sin2v0= *(sin2v0+ii);
(params+tid)->potu0v0= *(potu0v0+ii);
(JRRoot+tid)->function = &JRStaeckelIntegrandSquared;
(JRRoot+tid)->params = params+tid;
//Find starting points for minimum
if ( fabs(GSL_FN_EVAL(JRRoot+tid,*(ux+ii))) < 0.0000001){ //we are at umin or umax
peps= GSL_FN_EVAL(JRRoot+tid,*(ux+ii)+0.000001);
meps= GSL_FN_EVAL(JRRoot+tid,*(ux+ii)-0.000001);
if ( fabs(peps) < 0.00000001 && fabs(meps) < 0.00000001 ) {//circular
*(umin+ii) = *(ux+ii);
*(umax+ii) = *(ux+ii);
}
else if ( peps < 0. && meps > 0. ) {//umax
*(umax+ii)= *(ux+ii);
u_lo= 0.9 * (*(ux+ii) - 0.000001);
u_hi= *(ux+ii) - 0.0000001;
while ( GSL_FN_EVAL(JRRoot+tid,u_lo) >= 0. && u_lo > 0.000000001){
u_hi= u_lo; //this makes sure that brent evaluates using previous
u_lo*= 0.9;
}
//Find root
status = gsl_root_fsolver_set ((s+tid)->s, JRRoot+tid, u_lo, u_hi);
if (status == GSL_EINVAL) {
*(umin+ii) = 0.;//Assume zero if below 0.000000001
} else {
iter= 0;
do
{
iter++;
status = gsl_root_fsolver_iterate ((s+tid)->s);
u_lo = gsl_root_fsolver_x_lower ((s+tid)->s);
u_hi = gsl_root_fsolver_x_upper ((s+tid)->s);
status = gsl_root_test_interval (u_lo, u_hi,
9.9999999999999998e-13,
4.4408920985006262e-16);
}
while (status == GSL_CONTINUE && iter < max_iter);
// LCOV_EXCL_START
if (status == GSL_EINVAL) {//Shouldn't ever get here
*(umin+ii) = -9999.99;
*(umax+ii) = -9999.99;
continue;
}
// LCOV_EXCL_STOP
*(umin+ii) = gsl_root_fsolver_root ((s+tid)->s);
}
}
else if ( peps > 0. && meps < 0. ){//umin
*(umin+ii)= *(ux+ii);
u_lo= *(ux+ii) + 0.000001;
u_hi= 1.1 * (*(ux+ii) + 0.000001);
while ( GSL_FN_EVAL(JRRoot+tid,u_hi) >= 0. && u_hi < asinh(37.5/ *(delta+ii*delta_stride))) {
u_lo= u_hi; //this makes sure that brent evaluates using previous
u_hi*= 1.1;
}
//Find root
status = gsl_root_fsolver_set ((s+tid)->s, JRRoot+tid, u_lo, u_hi);
if (status == GSL_EINVAL) {
*(umin+ii) = -9999.99;
*(umax+ii) = -9999.99;
continue;
}
iter= 0;
do
{
iter++;
status = gsl_root_fsolver_iterate ((s+tid)->s);
u_lo = gsl_root_fsolver_x_lower ((s+tid)->s);
u_hi = gsl_root_fsolver_x_upper ((s+tid)->s);
status = gsl_root_test_interval (u_lo, u_hi,
9.9999999999999998e-13,
4.4408920985006262e-16);
}
while (status == GSL_CONTINUE && iter < max_iter);
// LCOV_EXCL_START
if (status == GSL_EINVAL) {//Shouldn't ever get here
*(umin+ii) = -9999.99;
*(umax+ii) = -9999.99;
continue;
}
// LCOV_EXCL_STOP
*(umax+ii) = gsl_root_fsolver_root ((s+tid)->s);
}
}
else {
u_lo= 0.9 * *(ux+ii);
u_hi= *(ux+ii);
while ( GSL_FN_EVAL(JRRoot+tid,u_lo) >= 0. && u_lo > 0.000000001){
u_hi= u_lo; //this makes sure that brent evaluates using previous
u_lo*= 0.9;
}
u_hi= (u_lo < 0.9 * *(ux+ii)) ? u_lo / 0.9 / 0.9: *(ux+ii);
//Find root
status = gsl_root_fsolver_set ((s+tid)->s, JRRoot+tid, u_lo, u_hi);
if (status == GSL_EINVAL) {
*(umin+ii) = 0.;//Assume zero if below 0.000000001
} else {
iter= 0;
do
{
iter++;
status = gsl_root_fsolver_iterate ((s+tid)->s);
u_lo = gsl_root_fsolver_x_lower ((s+tid)->s);
u_hi = gsl_root_fsolver_x_upper ((s+tid)->s);
status = gsl_root_test_interval (u_lo, u_hi,
9.9999999999999998e-13,
4.4408920985006262e-16);
}
while (status == GSL_CONTINUE && iter < max_iter);
// LCOV_EXCL_START
if (status == GSL_EINVAL) {//Shouldn't ever get here
*(umin+ii) = -9999.99;
*(umax+ii) = -9999.99;
continue;
}
// LCOV_EXCL_STOP
*(umin+ii) = gsl_root_fsolver_root ((s+tid)->s);
}
//Find starting points for maximum
u_lo= *(ux+ii);
u_hi= 1.1 * *(ux+ii);
while ( GSL_FN_EVAL(JRRoot+tid,u_hi) > 0. && u_hi < asinh(37.5/ *(delta+ii*delta_stride))) {
u_lo= u_hi; //this makes sure that brent evaluates using previous
u_hi*= 1.1;
}
u_lo= (u_hi > 1.1 * *(ux+ii)) ? u_hi / 1.1 / 1.1: *(ux+ii);
//Find root
status = gsl_root_fsolver_set ((s+tid)->s, JRRoot+tid, u_lo, u_hi);
if (status == GSL_EINVAL) {
*(umin+ii) = -9999.99;
*(umax+ii) = -9999.99;
continue;
}
iter= 0;
do
{
iter++;
status = gsl_root_fsolver_iterate ((s+tid)->s);
u_lo = gsl_root_fsolver_x_lower ((s+tid)->s);
u_hi = gsl_root_fsolver_x_upper ((s+tid)->s);
status = gsl_root_test_interval (u_lo, u_hi,
9.9999999999999998e-13,
4.4408920985006262e-16);
}
while (status == GSL_CONTINUE && iter < max_iter);
// LCOV_EXCL_START
if (status == GSL_EINVAL) {//Shouldn't ever get here
*(umin+ii) = -9999.99;
*(umax+ii) = -9999.99;
continue;
}
// LCOV_EXCL_STOP
*(umax+ii) = gsl_root_fsolver_root ((s+tid)->s);
}
}
gsl_set_error_handler (NULL);
for (tid=0; tid < nthreads; tid++)
gsl_root_fsolver_free( (s+tid)->s);
free(s);
free(JRRoot);
free(params);
}
void calcVmin(int ndata,
double * vmin,
double * vx,
double * pvx,
double * E,
double * Lz,
double * I3V,
int ndelta,
double * delta,
double * u0,
double * cosh2u0,
double * sinh2u0,
double * potupi2,
int nargs,
struct potentialArg * actionAngleArgs){
int ii, tid, nthreads;
#ifdef _OPENMP
nthreads = omp_get_max_threads();
#else
nthreads = 1;
#endif
gsl_function * JzRoot= (gsl_function *) malloc ( nthreads * sizeof(gsl_function) );
struct JzStaeckelArg * params= (struct JzStaeckelArg *) malloc ( nthreads * sizeof (struct JzStaeckelArg) );
//Setup solver
int status;
int iter, max_iter = 100;
const gsl_root_fsolver_type *T;
struct pragmasolver *s= (struct pragmasolver *) malloc ( nthreads * sizeof (struct pragmasolver) );;
double v_lo, v_hi;
T = gsl_root_fsolver_brent;
for (tid=0; tid < nthreads; tid++){
(params+tid)->nargs= nargs;
(params+tid)->actionAngleArgs= actionAngleArgs;
(s+tid)->s= gsl_root_fsolver_alloc (T);
}
int delta_stride= ndelta == 1 ? 0 : 1;
UNUSED int chunk= CHUNKSIZE;
gsl_set_error_handler_off();
#pragma omp parallel for schedule(static,chunk) \
private(tid,ii,iter,status,v_lo,v_hi) \
shared(vmin,JzRoot,params,s,vx,delta,E,Lz,I3V,u0,cosh2u0,sinh2u0,potupi2,max_iter)
for (ii=0; ii < ndata; ii++){
#ifdef _OPENMP
tid= omp_get_thread_num();
#else
tid = 0;
#endif
//Setup function
(params+tid)->delta= *(delta+ii*delta_stride);
(params+tid)->E= *(E+ii);
(params+tid)->Lz22delta= 0.5 * *(Lz+ii) * *(Lz+ii) / *(delta+ii*delta_stride) / *(delta+ii*delta_stride);
(params+tid)->I3V= *(I3V+ii);
(params+tid)->u0= *(u0+ii);
(params+tid)->cosh2u0= *(cosh2u0+ii);
(params+tid)->sinh2u0= *(sinh2u0+ii);
(params+tid)->potupi2= *(potupi2+ii);
(JzRoot+tid)->function = &JzStaeckelIntegrandSquared;
(JzRoot+tid)->params = params+tid;
//Find starting points for minimum
if ( fabs(GSL_FN_EVAL(JzRoot+tid,*(vx+ii))) < 0.0000001) //we are at vmin
*(vmin+ii)= ( *(vx+ii) > 0.5 * M_PI ) ? M_PI - *(vx+ii): *(vx+ii);
else {
if ( *(vx+ii) > 0.5 * M_PI ){
v_lo= 0.9 * ( M_PI - *(vx+ii) );
v_hi= M_PI - *(vx+ii);
}
else {
v_lo= 0.9 * *(vx+ii);
v_hi= *(vx+ii);
}
while ( GSL_FN_EVAL(JzRoot+tid,v_lo) >= 0. && v_lo > 0.000000001){
v_hi= v_lo; //this makes sure that brent evaluates using previous
v_lo*= 0.9;
}
//Find root
status = gsl_root_fsolver_set ((s+tid)->s, JzRoot+tid, v_lo, v_hi);
if (status == GSL_EINVAL) {
*(vmin+ii) = -9999.99;
continue;
}
iter= 0;
do
{
iter++;
status = gsl_root_fsolver_iterate ((s+tid)->s);
v_lo = gsl_root_fsolver_x_lower ((s+tid)->s);
v_hi = gsl_root_fsolver_x_upper ((s+tid)->s);
status = gsl_root_test_interval (v_lo, v_hi,
9.9999999999999998e-13,
4.4408920985006262e-16);
}
while (status == GSL_CONTINUE && iter < max_iter);
// LCOV_EXCL_START
if (status == GSL_EINVAL) {//Shouldn't ever get here
*(vmin+ii) = -9999.99;
continue;
}
// LCOV_EXCL_STOP
*(vmin+ii) = gsl_root_fsolver_root ((s+tid)->s);
fflush(stdout);
}
}
gsl_set_error_handler (NULL);
for (tid=0; tid < nthreads; tid++)
gsl_root_fsolver_free( (s+tid)->s);
free(s);
free(JzRoot);
free(params);
}
double JRStaeckelIntegrand(double u,
void * p){
double out= JRStaeckelIntegrandSquared(u,p);
if ( out <= 0.) return 0.;
else return sqrt(out);
}
double JRStaeckelIntegrandSquared(double u,
void * p){
struct JRStaeckelArg * params= (struct JRStaeckelArg *) p;
double sinh2u= sinh(u) * sinh(u);
double dU= (sinh2u+params->sin2v0)
*evaluatePotentialsUV(u,params->v0,params->delta,
params->nargs,params->actionAngleArgs)
- (params->sinh2u0+params->sin2v0)*params->potu0v0;
return params->E * sinh2u - params->I3U - dU - params->Lz22delta / sinh2u;
}
double JRStaeckelIntegrandSquared4dJR(double u,
void * p){
struct dJRStaeckelArg * params= (struct dJRStaeckelArg *) p;
double sinh2u= sinh(u) * sinh(u);
double dU= (sinh2u+params->sin2v0)
*evaluatePotentialsUV(u,params->v0,params->delta,
params->nargs,params->actionAngleArgs)
- (params->sinh2u0+params->sin2v0)*params->potu0v0;
return params->E * sinh2u - params->I3U - dU - params->Lz22delta / sinh2u;
}
double JzStaeckelIntegrand(double v,
void * p){
double out= JzStaeckelIntegrandSquared(v,p);
if ( out <= 0. ) return 0.;
else return sqrt(out);
}
double JzStaeckelIntegrandSquared(double v,
void * p){
struct JzStaeckelArg * params= (struct JzStaeckelArg *) p;
double sin2v= sin(v) * sin(v);
double dV= params->cosh2u0 * params->potupi2
- (params->sinh2u0+sin2v)
*evaluatePotentialsUV(params->u0,v,params->delta,
params->nargs,params->actionAngleArgs);
return params->E * sin2v + params->I3V + dV - params->Lz22delta / sin2v;
}
double JzStaeckelIntegrandSquared4dJz(double v,
void * p){
struct dJzStaeckelArg * params= (struct dJzStaeckelArg *) p;
double sin2v= sin(v) * sin(v);
double dV= params->cosh2u0 * params->potupi2
- (params->sinh2u0+sin2v)
*evaluatePotentialsUV(params->u0,v,params->delta,
params->nargs,params->actionAngleArgs);
return params->E * sin2v + params->I3V + dV - params->Lz22delta / sin2v;
}
double dJRdELowStaeckelIntegrand(double t,
void * p){
struct dJRStaeckelArg * params= (struct dJRStaeckelArg *) p;
double u= params->umin + t * t;
return 2. * t * dJRdEStaeckelIntegrand(u,p);
}
double dJRdEHighStaeckelIntegrand(double t,
void * p){
struct dJRStaeckelArg * params= (struct dJRStaeckelArg *) p;
double u= params->umax - t * t;
return 2. * t * dJRdEStaeckelIntegrand(u,p);
}
double dJRdEStaeckelIntegrand(double u,
void * p){
double out= JRStaeckelIntegrandSquared4dJR(u,p);
if ( out <= 0. ) return 0.;
else return sinh(u)*sinh(u)/sqrt(out);
}
double dJRdLzLowStaeckelIntegrand(double t,
void * p){
struct dJRStaeckelArg * params= (struct dJRStaeckelArg *) p;
double u= params->umin + t * t;
return 2. * t * dJRdLzStaeckelIntegrand(u,p);
}
double dJRdLzHighStaeckelIntegrand(double t,
void * p){
struct dJRStaeckelArg * params= (struct dJRStaeckelArg *) p;
double u= params->umax - t * t;
return 2. * t * dJRdLzStaeckelIntegrand(u,p);
}
double dJRdLzStaeckelIntegrand(double u,
void * p){
double out= JRStaeckelIntegrandSquared4dJR(u,p);
if ( out <= 0. ) return 0.;
else return 1./sinh(u)/sinh(u)/sqrt(out);
}
double dJRdI3LowStaeckelIntegrand(double t,
void * p){
struct dJRStaeckelArg * params= (struct dJRStaeckelArg *) p;
double u= params->umin + t * t;
return 2. * t * dJRdI3StaeckelIntegrand(u,p);
}
double dJRdI3HighStaeckelIntegrand(double t,
void * p){
struct dJRStaeckelArg * params= (struct dJRStaeckelArg *) p;
double u= params->umax - t * t;
return 2. * t * dJRdI3StaeckelIntegrand(u,p);
}
double dJRdI3StaeckelIntegrand(double u,
void * p){
double out= JRStaeckelIntegrandSquared4dJR(u,p);
if ( out <= 0. ) return 0.;
else return 1./sqrt(out);
}
double dJzdELowStaeckelIntegrand(double t,
void * p){
struct dJzStaeckelArg * params= (struct dJzStaeckelArg *) p;
double v= params->vmin + t * t;
return 2. * t * dJzdEStaeckelIntegrand(v,p);
}
double dJzdEHighStaeckelIntegrand(double t,
void * p){
double v= M_PI/2. - t * t;
return 2. * t * dJzdEStaeckelIntegrand(v,p);
}
double dJzdEStaeckelIntegrand(double v,
void * p){
double out= JzStaeckelIntegrandSquared4dJz(v,p);
if ( out <= 0. ) return 0.;
else return sin(v)*sin(v)/sqrt(out);
}
double dJzdLzLowStaeckelIntegrand(double t,
void * p){
struct dJzStaeckelArg * params= (struct dJzStaeckelArg *) p;
double v= params->vmin + t * t;
return 2. * t * dJzdLzStaeckelIntegrand(v,p);
}
double dJzdLzHighStaeckelIntegrand(double t,
void * p){
double v= M_PI/2. - t * t;
return 2. * t * dJzdLzStaeckelIntegrand(v,p);
}
double dJzdLzStaeckelIntegrand(double v,
void * p){
double out= JzStaeckelIntegrandSquared4dJz(v,p);
if ( out <= 0. ) return 0.;
else return 1./sin(v)/sin(v)/sqrt(out);
}
double dJzdI3LowStaeckelIntegrand(double t,
void * p){
struct dJzStaeckelArg * params= (struct dJzStaeckelArg *) p;
double v= params->vmin + t * t;
return 2. * t * dJzdI3StaeckelIntegrand(v,p);
}
double dJzdI3HighStaeckelIntegrand(double t,
void * p){
double v= M_PI/2. - t * t;
return 2. * t * dJzdI3StaeckelIntegrand(v,p);
}
double dJzdI3StaeckelIntegrand(double v,
void * p){
double out= JzStaeckelIntegrandSquared4dJz(v,p);
if ( out <= 0. ) return 0.;
else return 1./sqrt(out);
}
double u0Equation(double u, void * p){
struct u0EqArg * params= (struct u0EqArg *) p;
double sinh2u= sinh(u) * sinh(u);
double cosh2u= cosh(u) * cosh(u);
double dU= cosh2u * evaluatePotentialsUV(u,0.5*M_PI,params->delta,
params->nargs,params->actionAngleArgs);
return -(params->E*sinh2u-dU-params->Lz22delta/sinh2u);
}
double evaluatePotentialsUV(double u, double v, double delta,
int nargs,
struct potentialArg * actionAngleArgs){
double R,z;
uv_to_Rz(u,v,&R,&z,delta);
return evaluatePotentials(R,z,nargs,actionAngleArgs);
}
|
paint.c
|
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% PPPP AAA IIIII N N TTTTT %
% P P A A I NN N T %
% PPPP AAAAA I N N N T %
% P A A I N NN T %
% P A A IIIII N N T %
% %
% %
% Methods to Paint on an Image %
% %
% Software Design %
% Cristy %
% July 1998 %
% %
% %
% Copyright @ 1999 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% https://imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "MagickCore/studio.h"
#include "MagickCore/artifact.h"
#include "MagickCore/channel.h"
#include "MagickCore/color.h"
#include "MagickCore/color-private.h"
#include "MagickCore/colorspace-private.h"
#include "MagickCore/composite.h"
#include "MagickCore/composite-private.h"
#include "MagickCore/draw.h"
#include "MagickCore/draw-private.h"
#include "MagickCore/exception.h"
#include "MagickCore/exception-private.h"
#include "MagickCore/gem.h"
#include "MagickCore/gem-private.h"
#include "MagickCore/monitor.h"
#include "MagickCore/monitor-private.h"
#include "MagickCore/option.h"
#include "MagickCore/paint.h"
#include "MagickCore/pixel-accessor.h"
#include "MagickCore/resource_.h"
#include "MagickCore/statistic.h"
#include "MagickCore/string_.h"
#include "MagickCore/string-private.h"
#include "MagickCore/thread-private.h"
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% F l o o d f i l l P a i n t I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% FloodfillPaintImage() changes the color value of any pixel that matches
% target and is an immediate neighbor. If the method FillToBorderMethod is
% specified, the color value is changed for any neighbor pixel that does not
% match the bordercolor member of image.
%
% By default target must match a particular pixel color exactly. However,
% in many cases two colors may differ by a small amount. The fuzz member of
% image defines how much tolerance is acceptable to consider two colors as
% the same. For example, set fuzz to 10 and the color red at intensities of
% 100 and 102 respectively are now interpreted as the same color for the
% purposes of the floodfill.
%
% The format of the FloodfillPaintImage method is:
%
% MagickBooleanType FloodfillPaintImage(Image *image,
% const DrawInfo *draw_info,const PixelInfo target,
% const ssize_t x_offset,const ssize_t y_offset,
% const MagickBooleanType invert,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o draw_info: the draw info.
%
% o target: the RGB value of the target color.
%
% o x_offset,y_offset: the starting location of the operation.
%
% o invert: paint any pixel that does not match the target color.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType FloodfillPaintImage(Image *image,
const DrawInfo *draw_info,const PixelInfo *target,const ssize_t x_offset,
const ssize_t y_offset,const MagickBooleanType invert,
ExceptionInfo *exception)
{
#define MaxStacksize 524288UL
#define PushSegmentStack(up,left,right,delta) \
{ \
if (s >= (segment_stack+MaxStacksize)) \
{ \
segment_info=RelinquishVirtualMemory(segment_info); \
image_view=DestroyCacheView(image_view); \
floodplane_view=DestroyCacheView(floodplane_view); \
floodplane_image=DestroyImage(floodplane_image); \
ThrowBinaryException(DrawError,"SegmentStackOverflow",image->filename) \
} \
else \
{ \
if ((((up)+(delta)) >= 0) && (((up)+(delta)) < (ssize_t) image->rows)) \
{ \
s->x1=(double) (left); \
s->y1=(double) (up); \
s->x2=(double) (right); \
s->y2=(double) (delta); \
s++; \
} \
} \
}
CacheView
*floodplane_view,
*image_view;
Image
*floodplane_image;
MagickBooleanType
skip,
status;
MemoryInfo
*segment_info;
PixelInfo
fill_color,
pixel;
SegmentInfo
*s;
SegmentInfo
*segment_stack;
ssize_t
offset,
start,
x1,
x2,
y;
/*
Check boundary conditions.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
assert(draw_info != (DrawInfo *) NULL);
assert(draw_info->signature == MagickCoreSignature);
if (IsEventLogging() != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if ((x_offset < 0) || (x_offset >= (ssize_t) image->columns))
return(MagickFalse);
if ((y_offset < 0) || (y_offset >= (ssize_t) image->rows))
return(MagickFalse);
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
return(MagickFalse);
if (IsGrayColorspace(image->colorspace) != MagickFalse)
(void) SetImageColorspace(image,sRGBColorspace,exception);
if ((image->alpha_trait == UndefinedPixelTrait) &&
(draw_info->fill.alpha_trait != UndefinedPixelTrait))
(void) SetImageAlpha(image,OpaqueAlpha,exception);
/*
Set floodfill state.
*/
floodplane_image=CloneImage(image,0,0,MagickTrue,exception);
if (floodplane_image == (Image *) NULL)
return(MagickFalse);
floodplane_image->alpha_trait=UndefinedPixelTrait;
floodplane_image->colorspace=GRAYColorspace;
(void) QueryColorCompliance("#000",AllCompliance,
&floodplane_image->background_color,exception);
(void) SetImageBackgroundColor(floodplane_image,exception);
segment_info=AcquireVirtualMemory(MaxStacksize,sizeof(*segment_stack));
if (segment_info == (MemoryInfo *) NULL)
{
floodplane_image=DestroyImage(floodplane_image);
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
segment_stack=(SegmentInfo *) GetVirtualMemoryBlob(segment_info);
/*
Push initial segment on stack.
*/
status=MagickTrue;
start=0;
s=segment_stack;
GetPixelInfo(image,&pixel);
image_view=AcquireVirtualCacheView(image,exception);
floodplane_view=AcquireAuthenticCacheView(floodplane_image,exception);
PushSegmentStack(y_offset,x_offset,x_offset,1);
PushSegmentStack(y_offset+1,x_offset,x_offset,-1);
while (s > segment_stack)
{
const Quantum
*magick_restrict p;
Quantum
*magick_restrict q;
ssize_t
x;
/*
Pop segment off stack.
*/
s--;
x1=(ssize_t) s->x1;
x2=(ssize_t) s->x2;
offset=(ssize_t) s->y2;
y=(ssize_t) s->y1+offset;
/*
Recolor neighboring pixels.
*/
p=GetCacheViewVirtualPixels(image_view,0,y,(size_t) (x1+1),1,exception);
q=GetCacheViewAuthenticPixels(floodplane_view,0,y,(size_t) (x1+1),1,
exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
break;
p+=x1*GetPixelChannels(image);
q+=x1*GetPixelChannels(floodplane_image);
for (x=x1; x >= 0; x--)
{
if (GetPixelGray(floodplane_image,q) != 0)
break;
GetPixelInfoPixel(image,p,&pixel);
if (IsFuzzyEquivalencePixelInfo(&pixel,target) == invert)
break;
SetPixelGray(floodplane_image,QuantumRange,q);
p-=GetPixelChannels(image);
q-=GetPixelChannels(floodplane_image);
}
if (SyncCacheViewAuthenticPixels(floodplane_view,exception) == MagickFalse)
break;
skip=x >= x1 ? MagickTrue : MagickFalse;
if (skip == MagickFalse)
{
start=x+1;
if (start < x1)
PushSegmentStack(y,start,x1-1,-offset);
x=x1+1;
}
do
{
if (skip == MagickFalse)
{
if (x < (ssize_t) image->columns)
{
p=GetCacheViewVirtualPixels(image_view,x,y,image->columns-x,1,
exception);
q=GetCacheViewAuthenticPixels(floodplane_view,x,y,image->columns-
x,1,exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
break;
for ( ; x < (ssize_t) image->columns; x++)
{
if (GetPixelGray(floodplane_image,q) != 0)
break;
GetPixelInfoPixel(image,p,&pixel);
if (IsFuzzyEquivalencePixelInfo(&pixel,target) == invert)
break;
SetPixelGray(floodplane_image,QuantumRange,q);
p+=GetPixelChannels(image);
q+=GetPixelChannels(floodplane_image);
}
status=SyncCacheViewAuthenticPixels(floodplane_view,exception);
if (status == MagickFalse)
break;
}
PushSegmentStack(y,start,x-1,offset);
if (x > (x2+1))
PushSegmentStack(y,x2+1,x-1,-offset);
}
skip=MagickFalse;
x++;
if (x <= x2)
{
p=GetCacheViewVirtualPixels(image_view,x,y,(size_t) (x2-x+1),1,
exception);
q=GetCacheViewAuthenticPixels(floodplane_view,x,y,(size_t) (x2-x+1),1,
exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
break;
for ( ; x <= x2; x++)
{
if (GetPixelGray(floodplane_image,q) != 0)
break;
GetPixelInfoPixel(image,p,&pixel);
if (IsFuzzyEquivalencePixelInfo(&pixel,target) != invert)
break;
p+=GetPixelChannels(image);
q+=GetPixelChannels(floodplane_image);
}
}
start=x;
} while (x <= x2);
}
status=MagickTrue;
for (y=0; y < (ssize_t) image->rows; y++)
{
const Quantum
*magick_restrict p;
Quantum
*magick_restrict q;
ssize_t
x;
/*
Tile fill color onto floodplane.
*/
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(floodplane_view,0,y,image->columns,1,exception);
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
if (GetPixelGray(floodplane_image,p) != 0)
{
GetFillColor(draw_info,x,y,&fill_color,exception);
SetPixelViaPixelInfo(image,&fill_color,q);
}
p+=GetPixelChannels(floodplane_image);
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
floodplane_view=DestroyCacheView(floodplane_view);
image_view=DestroyCacheView(image_view);
segment_info=RelinquishVirtualMemory(segment_info);
floodplane_image=DestroyImage(floodplane_image);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ G r a d i e n t I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GradientImage() applies a continuously smooth color transitions along a
% vector from one color to another.
%
% Note, the interface of this method will change in the future to support
% more than one transistion.
%
% The format of the GradientImage method is:
%
% MagickBooleanType GradientImage(Image *image,const GradientType type,
% const SpreadMethod method,const PixelInfo *start_color,
% const PixelInfo *stop_color,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o type: the gradient type: linear or radial.
%
% o spread: the gradient spread meathod: pad, reflect, or repeat.
%
% o start_color: the start color.
%
% o stop_color: the stop color.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType GradientImage(Image *image,
const GradientType type,const SpreadMethod method,const StopInfo *stops,
const size_t number_stops,ExceptionInfo *exception)
{
const char
*artifact;
DrawInfo
*draw_info;
GradientInfo
*gradient;
MagickBooleanType
status;
/*
Set gradient start-stop end points.
*/
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
assert(stops != (const StopInfo *) NULL);
assert(number_stops > 0);
if (IsEventLogging() != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
draw_info=AcquireDrawInfo();
gradient=(&draw_info->gradient);
gradient->type=type;
gradient->bounding_box.width=image->columns;
gradient->bounding_box.height=image->rows;
artifact=GetImageArtifact(image,"gradient:bounding-box");
if (artifact != (const char *) NULL)
(void) ParseAbsoluteGeometry(artifact,&gradient->bounding_box);
gradient->gradient_vector.x2=(double) image->columns-1;
gradient->gradient_vector.y2=(double) image->rows-1;
artifact=GetImageArtifact(image,"gradient:direction");
if (artifact != (const char *) NULL)
{
GravityType
direction;
direction=(GravityType) ParseCommandOption(MagickGravityOptions,
MagickFalse,artifact);
switch (direction)
{
case NorthWestGravity:
{
gradient->gradient_vector.x1=(double) image->columns-1;
gradient->gradient_vector.y1=(double) image->rows-1;
gradient->gradient_vector.x2=0.0;
gradient->gradient_vector.y2=0.0;
break;
}
case NorthGravity:
{
gradient->gradient_vector.x1=0.0;
gradient->gradient_vector.y1=(double) image->rows-1;
gradient->gradient_vector.x2=0.0;
gradient->gradient_vector.y2=0.0;
break;
}
case NorthEastGravity:
{
gradient->gradient_vector.x1=0.0;
gradient->gradient_vector.y1=(double) image->rows-1;
gradient->gradient_vector.x2=(double) image->columns-1;
gradient->gradient_vector.y2=0.0;
break;
}
case WestGravity:
{
gradient->gradient_vector.x1=(double) image->columns-1;
gradient->gradient_vector.y1=0.0;
gradient->gradient_vector.x2=0.0;
gradient->gradient_vector.y2=0.0;
break;
}
case EastGravity:
{
gradient->gradient_vector.x1=0.0;
gradient->gradient_vector.y1=0.0;
gradient->gradient_vector.x2=(double) image->columns-1;
gradient->gradient_vector.y2=0.0;
break;
}
case SouthWestGravity:
{
gradient->gradient_vector.x1=(double) image->columns-1;
gradient->gradient_vector.y1=0.0;
gradient->gradient_vector.x2=0.0;
gradient->gradient_vector.y2=(double) image->rows-1;
break;
}
case SouthGravity:
{
gradient->gradient_vector.x1=0.0;
gradient->gradient_vector.y1=0.0;
gradient->gradient_vector.x2=0.0;
gradient->gradient_vector.y2=(double) image->columns-1;
break;
}
case SouthEastGravity:
{
gradient->gradient_vector.x1=0.0;
gradient->gradient_vector.y1=0.0;
gradient->gradient_vector.x2=(double) image->columns-1;
gradient->gradient_vector.y2=(double) image->rows-1;
break;
}
default:
break;
}
}
artifact=GetImageArtifact(image,"gradient:angle");
if (artifact != (const char *) NULL)
gradient->angle=StringToDouble(artifact,(char **) NULL);
artifact=GetImageArtifact(image,"gradient:vector");
if (artifact != (const char *) NULL)
(void) sscanf(artifact,"%lf%*[ ,]%lf%*[ ,]%lf%*[ ,]%lf",
&gradient->gradient_vector.x1,&gradient->gradient_vector.y1,
&gradient->gradient_vector.x2,&gradient->gradient_vector.y2);
if ((GetImageArtifact(image,"gradient:angle") == (const char *) NULL) &&
(GetImageArtifact(image,"gradient:direction") == (const char *) NULL) &&
(GetImageArtifact(image,"gradient:extent") == (const char *) NULL) &&
(GetImageArtifact(image,"gradient:vector") == (const char *) NULL))
if ((type == LinearGradient) && (gradient->gradient_vector.y2 != 0.0))
gradient->gradient_vector.x2=0.0;
gradient->center.x=(double) gradient->gradient_vector.x2/2.0;
gradient->center.y=(double) gradient->gradient_vector.y2/2.0;
artifact=GetImageArtifact(image,"gradient:center");
if (artifact != (const char *) NULL)
(void) sscanf(artifact,"%lf%*[ ,]%lf",&gradient->center.x,
&gradient->center.y);
artifact=GetImageArtifact(image,"gradient:angle");
if ((type == LinearGradient) && (artifact != (const char *) NULL))
{
double
sine,
cosine,
distance;
/*
Reference https://drafts.csswg.org/css-images-3/#linear-gradients.
*/
sine=sin((double) DegreesToRadians(gradient->angle-90.0));
cosine=cos((double) DegreesToRadians(gradient->angle-90.0));
distance=fabs((double) (image->columns-1.0)*cosine)+
fabs((double) (image->rows-1.0)*sine);
gradient->gradient_vector.x1=0.5*((image->columns-1.0)-distance*cosine);
gradient->gradient_vector.y1=0.5*((image->rows-1.0)-distance*sine);
gradient->gradient_vector.x2=0.5*((image->columns-1.0)+distance*cosine);
gradient->gradient_vector.y2=0.5*((image->rows-1.0)+distance*sine);
}
gradient->radii.x=(double) MagickMax((image->columns-1.0),(image->rows-1.0))/
2.0;
gradient->radii.y=gradient->radii.x;
artifact=GetImageArtifact(image,"gradient:extent");
if (artifact != (const char *) NULL)
{
if (LocaleCompare(artifact,"Circle") == 0)
{
gradient->radii.x=(double) MagickMax((image->columns-1.0),
(image->rows-1.0))/2.0;
gradient->radii.y=gradient->radii.x;
}
if (LocaleCompare(artifact,"Diagonal") == 0)
{
gradient->radii.x=(double) (sqrt((double) (image->columns-1.0)*
(image->columns-1.0)+(image->rows-1.0)*(image->rows-1.0)))/2.0;
gradient->radii.y=gradient->radii.x;
}
if (LocaleCompare(artifact,"Ellipse") == 0)
{
gradient->radii.x=(double) (image->columns-1.0)/2.0;
gradient->radii.y=(double) (image->rows-1.0)/2.0;
}
if (LocaleCompare(artifact,"Maximum") == 0)
{
gradient->radii.x=(double) MagickMax((image->columns-1.0),
(image->rows-1.0))/2.0;
gradient->radii.y=gradient->radii.x;
}
if (LocaleCompare(artifact,"Minimum") == 0)
{
gradient->radii.x=(double) (MagickMin((image->columns-1.0),
(image->rows-1.0)))/2.0;
gradient->radii.y=gradient->radii.x;
}
}
artifact=GetImageArtifact(image,"gradient:radii");
if (artifact != (const char *) NULL)
(void) sscanf(artifact,"%lf%*[ ,]%lf",&gradient->radii.x,
&gradient->radii.y);
gradient->radius=MagickMax(gradient->radii.x,gradient->radii.y);
gradient->spread=method;
/*
Define the gradient to fill between the stops.
*/
gradient->number_stops=number_stops;
gradient->stops=(StopInfo *) AcquireQuantumMemory(gradient->number_stops,
sizeof(*gradient->stops));
if (gradient->stops == (StopInfo *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
(void) memcpy(gradient->stops,stops,(size_t) number_stops*sizeof(*stops));
/*
Draw a gradient on the image.
*/
status=DrawGradientImage(image,draw_info,exception);
draw_info=DestroyDrawInfo(draw_info);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% O i l P a i n t I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% OilPaintImage() applies a special effect filter that simulates an oil
% painting. Each pixel is replaced by the most frequent color occurring
% in a circular region defined by radius.
%
% The format of the OilPaintImage method is:
%
% Image *OilPaintImage(const Image *image,const double radius,
% const double sigma,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o radius: the radius of the circular neighborhood.
%
% o sigma: the standard deviation of the Gaussian, in pixels.
%
% o exception: return any errors or warnings in this structure.
%
*/
static size_t **DestroyHistogramTLS(size_t **histogram)
{
ssize_t
i;
assert(histogram != (size_t **) NULL);
for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++)
if (histogram[i] != (size_t *) NULL)
histogram[i]=(size_t *) RelinquishMagickMemory(histogram[i]);
histogram=(size_t **) RelinquishMagickMemory(histogram);
return(histogram);
}
static size_t **AcquireHistogramTLS(const size_t count)
{
ssize_t
i;
size_t
**histogram,
number_threads;
number_threads=(size_t) GetMagickResourceLimit(ThreadResource);
histogram=(size_t **) AcquireQuantumMemory(number_threads,sizeof(*histogram));
if (histogram == (size_t **) NULL)
return((size_t **) NULL);
(void) memset(histogram,0,number_threads*sizeof(*histogram));
for (i=0; i < (ssize_t) number_threads; i++)
{
histogram[i]=(size_t *) AcquireQuantumMemory(count,sizeof(**histogram));
if (histogram[i] == (size_t *) NULL)
return(DestroyHistogramTLS(histogram));
}
return(histogram);
}
MagickExport Image *OilPaintImage(const Image *image,const double radius,
const double sigma,ExceptionInfo *exception)
{
#define NumberPaintBins 256
#define OilPaintImageTag "OilPaint/Image"
CacheView
*image_view,
*paint_view;
Image
*linear_image,
*paint_image;
MagickBooleanType
status;
MagickOffsetType
progress;
size_t
**histograms,
width;
ssize_t
center,
y;
/*
Initialize painted image attributes.
*/
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
if (IsEventLogging() != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
width=GetOptimalKernelWidth2D(radius,sigma);
linear_image=CloneImage(image,0,0,MagickTrue,exception);
paint_image=CloneImage(image,0,0,MagickTrue,exception);
if ((linear_image == (Image *) NULL) || (paint_image == (Image *) NULL))
{
if (linear_image != (Image *) NULL)
linear_image=DestroyImage(linear_image);
if (paint_image != (Image *) NULL)
linear_image=DestroyImage(paint_image);
return((Image *) NULL);
}
if (SetImageStorageClass(paint_image,DirectClass,exception) == MagickFalse)
{
linear_image=DestroyImage(linear_image);
paint_image=DestroyImage(paint_image);
return((Image *) NULL);
}
histograms=AcquireHistogramTLS(NumberPaintBins);
if (histograms == (size_t **) NULL)
{
linear_image=DestroyImage(linear_image);
paint_image=DestroyImage(paint_image);
ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
}
/*
Oil paint image.
*/
status=MagickTrue;
progress=0;
center=(ssize_t) GetPixelChannels(linear_image)*(linear_image->columns+width)*
(width/2L)+GetPixelChannels(linear_image)*(width/2L);
image_view=AcquireVirtualCacheView(linear_image,exception);
paint_view=AcquireAuthenticCacheView(paint_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(linear_image,paint_image,linear_image->rows,1)
#endif
for (y=0; y < (ssize_t) linear_image->rows; y++)
{
const Quantum
*magick_restrict p;
Quantum
*magick_restrict q;
size_t
*histogram;
ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,-((ssize_t) width/2L),y-(ssize_t)
(width/2L),linear_image->columns+width,width,exception);
q=QueueCacheViewAuthenticPixels(paint_view,0,y,paint_image->columns,1,
exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
histogram=histograms[GetOpenMPThreadId()];
for (x=0; x < (ssize_t) linear_image->columns; x++)
{
ssize_t
i,
u;
size_t
count;
ssize_t
j,
k,
n,
v;
/*
Assign most frequent color.
*/
k=0;
j=0;
count=0;
(void) memset(histogram,0,NumberPaintBins* sizeof(*histogram));
for (v=0; v < (ssize_t) width; v++)
{
for (u=0; u < (ssize_t) width; u++)
{
n=(ssize_t) ScaleQuantumToChar(ClampToQuantum(GetPixelIntensity(
linear_image,p+GetPixelChannels(linear_image)*(u+k))));
histogram[n]++;
if (histogram[n] > count)
{
j=k+u;
count=histogram[n];
}
}
k+=(ssize_t) (linear_image->columns+width);
}
for (i=0; i < (ssize_t) GetPixelChannels(linear_image); i++)
{
PixelChannel channel = GetPixelChannelChannel(linear_image,i);
PixelTrait traits = GetPixelChannelTraits(linear_image,channel);
PixelTrait paint_traits=GetPixelChannelTraits(paint_image,channel);
if ((traits == UndefinedPixelTrait) ||
(paint_traits == UndefinedPixelTrait))
continue;
if ((paint_traits & CopyPixelTrait) != 0)
{
SetPixelChannel(paint_image,channel,p[center+i],q);
continue;
}
SetPixelChannel(paint_image,channel,p[j*GetPixelChannels(linear_image)+
i],q);
}
p+=GetPixelChannels(linear_image);
q+=GetPixelChannels(paint_image);
}
if (SyncCacheViewAuthenticPixels(paint_view,exception) == MagickFalse)
status=MagickFalse;
if (linear_image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(linear_image,OilPaintImageTag,progress,
linear_image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
paint_view=DestroyCacheView(paint_view);
image_view=DestroyCacheView(image_view);
histograms=DestroyHistogramTLS(histograms);
linear_image=DestroyImage(linear_image);
if (status == MagickFalse)
paint_image=DestroyImage(paint_image);
return(paint_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% O p a q u e P a i n t I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% OpaquePaintImage() changes any pixel that matches color with the color
% defined by fill argument.
%
% By default color must match a particular pixel color exactly. However, in
% many cases two colors may differ by a small amount. Fuzz defines how much
% tolerance is acceptable to consider two colors as the same. For example,
% set fuzz to 10 and the color red at intensities of 100 and 102 respectively
% are now interpreted as the same color.
%
% The format of the OpaquePaintImage method is:
%
% MagickBooleanType OpaquePaintImage(Image *image,const PixelInfo *target,
% const PixelInfo *fill,const MagickBooleanType invert,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o target: the RGB value of the target color.
%
% o fill: the replacement color.
%
% o invert: paint any pixel that does not match the target color.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType OpaquePaintImage(Image *image,
const PixelInfo *target,const PixelInfo *fill,const MagickBooleanType invert,
ExceptionInfo *exception)
{
#define OpaquePaintImageTag "Opaque/Image"
CacheView
*image_view;
MagickBooleanType
status;
MagickOffsetType
progress;
PixelInfo
conform_fill,
conform_target,
zero;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
assert(target != (PixelInfo *) NULL);
assert(fill != (PixelInfo *) NULL);
if (IsEventLogging() != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
return(MagickFalse);
ConformPixelInfo(image,fill,&conform_fill,exception);
ConformPixelInfo(image,target,&conform_target,exception);
/*
Make image color opaque.
*/
status=MagickTrue;
progress=0;
GetPixelInfo(image,&zero);
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
PixelInfo
pixel;
Quantum
*magick_restrict q;
ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
pixel=zero;
for (x=0; x < (ssize_t) image->columns; x++)
{
GetPixelInfoPixel(image,q,&pixel);
if (IsFuzzyEquivalencePixelInfo(&pixel,&conform_target) != invert)
{
PixelTrait
traits;
traits=GetPixelChannelTraits(image,RedPixelChannel);
if ((traits & UpdatePixelTrait) != 0)
SetPixelRed(image,(Quantum) conform_fill.red,q);
traits=GetPixelChannelTraits(image,GreenPixelChannel);
if ((traits & UpdatePixelTrait) != 0)
SetPixelGreen(image,(Quantum) conform_fill.green,q);
traits=GetPixelChannelTraits(image,BluePixelChannel);
if ((traits & UpdatePixelTrait) != 0)
SetPixelBlue(image,(Quantum) conform_fill.blue,q);
traits=GetPixelChannelTraits(image,BlackPixelChannel);
if ((traits & UpdatePixelTrait) != 0)
SetPixelBlack(image,(Quantum) conform_fill.black,q);
traits=GetPixelChannelTraits(image,AlphaPixelChannel);
if ((traits & UpdatePixelTrait) != 0)
SetPixelAlpha(image,(Quantum) conform_fill.alpha,q);
}
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,OpaquePaintImageTag,progress,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% T r a n s p a r e n t P a i n t I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% TransparentPaintImage() changes the opacity value associated with any pixel
% that matches color to the value defined by opacity.
%
% By default color must match a particular pixel color exactly. However, in
% many cases two colors may differ by a small amount. Fuzz defines how much
% tolerance is acceptable to consider two colors as the same. For example,
% set fuzz to 10 and the color red at intensities of 100 and 102 respectively
% are now interpreted as the same color.
%
% The format of the TransparentPaintImage method is:
%
% MagickBooleanType TransparentPaintImage(Image *image,
% const PixelInfo *target,const Quantum opacity,
% const MagickBooleanType invert,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o target: the target color.
%
% o opacity: the replacement opacity value.
%
% o invert: paint any pixel that does not match the target color.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType TransparentPaintImage(Image *image,
const PixelInfo *target,const Quantum opacity,const MagickBooleanType invert,
ExceptionInfo *exception)
{
#define TransparentPaintImageTag "Transparent/Image"
CacheView
*image_view;
MagickBooleanType
status;
MagickOffsetType
progress;
PixelInfo
zero;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
assert(target != (PixelInfo *) NULL);
if (IsEventLogging() != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
return(MagickFalse);
if (image->alpha_trait == UndefinedPixelTrait)
(void) SetImageAlphaChannel(image,OpaqueAlphaChannel,exception);
/*
Make image color transparent.
*/
status=MagickTrue;
progress=0;
GetPixelInfo(image,&zero);
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
PixelInfo
pixel;
ssize_t
x;
Quantum
*magick_restrict q;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
pixel=zero;
for (x=0; x < (ssize_t) image->columns; x++)
{
GetPixelInfoPixel(image,q,&pixel);
if (IsFuzzyEquivalencePixelInfo(&pixel,target) != invert)
SetPixelAlpha(image,opacity,q);
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,TransparentPaintImageTag,progress,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% T r a n s p a r e n t P a i n t I m a g e C h r o m a %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% TransparentPaintImageChroma() changes the opacity value associated with any
% pixel that matches color to the value defined by opacity.
%
% As there is one fuzz value for the all the channels, TransparentPaintImage()
% is not suitable for the operations like chroma, where the tolerance for
% similarity of two color component (RGB) can be different. Thus we define
% this method to take two target pixels (one low and one high) and all the
% pixels of an image which are lying between these two pixels are made
% transparent.
%
% The format of the TransparentPaintImageChroma method is:
%
% MagickBooleanType TransparentPaintImageChroma(Image *image,
% const PixelInfo *low,const PixelInfo *high,const Quantum opacity,
% const MagickBooleanType invert,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o low: the low target color.
%
% o high: the high target color.
%
% o opacity: the replacement opacity value.
%
% o invert: paint any pixel that does not match the target color.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType TransparentPaintImageChroma(Image *image,
const PixelInfo *low,const PixelInfo *high,const Quantum opacity,
const MagickBooleanType invert,ExceptionInfo *exception)
{
#define TransparentPaintImageTag "Transparent/Image"
CacheView
*image_view;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
assert(high != (PixelInfo *) NULL);
assert(low != (PixelInfo *) NULL);
if (IsEventLogging() != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
return(MagickFalse);
if (image->alpha_trait == UndefinedPixelTrait)
(void) SetImageAlphaChannel(image,OpaqueAlphaChannel,exception);
/*
Make image color transparent.
*/
status=MagickTrue;
progress=0;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
MagickBooleanType
match;
PixelInfo
pixel;
Quantum
*magick_restrict q;
ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
GetPixelInfo(image,&pixel);
for (x=0; x < (ssize_t) image->columns; x++)
{
GetPixelInfoPixel(image,q,&pixel);
match=((pixel.red >= low->red) && (pixel.red <= high->red) &&
(pixel.green >= low->green) && (pixel.green <= high->green) &&
(pixel.blue >= low->blue) && (pixel.blue <= high->blue)) ? MagickTrue :
MagickFalse;
if (match != invert)
SetPixelAlpha(image,opacity,q);
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,TransparentPaintImageTag,progress,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
return(status);
}
|
sections_construct.c
|
#include <omp.h>
#include <stdio.h>
void sum_num(int a,int b)
{
printf("Adding %d and %d gives %d on thread %d\n",a,b,a+b, omp_get_thread_num());
}
void sum_n_num(int n)
{
int i;
int sum=0;
for(i=0;i<=n;i++)
{
sum+=i;
}
printf("\nSum of first %d numbers is %d from thread %d\n",n,sum,omp_get_thread_num());
}
int main(int argc, char** argv[])
{
#pragma omp parallel sections num_threads(2)
{
#pragma omp section
sum_num(2,3);
#pragma omp section
sum_n_num(5);
}
}
|
cholesky_escalar.c
|
/*
* Cholesky por bloques.
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "ctimer.h"
#include <cblas.h>
#include <omp.h>
#define L(i,j) L[j*n+i]
#define A(i,j) A[j*n+i]
#define C(i,j) C[j*n+i]
int cholesky_escalar( int n, double *C );
int cholesky_bloques( int n, int b, double *C );
int main( int argc, char *argv[] ) {
int n, b, i, j, info;
double *L, *A;
if( argc<3 ) {
fprintf(stderr,"usage: %s n block_size\n",argv[0]);
exit(-1);
}
sscanf(argv[1],"%d",&n);
if( ( L = (double*) malloc(n*n*sizeof(double)) ) == NULL ) {
fprintf(stderr,"Error en la reserva de memoria para la matriz L\n");
exit(-1);
}
for( j=0; j<n; j++ ) {
for( i=0; i<j; i++ ) {
L(i,j) = 0.0;
}
for( i=j; i<n; i++ ) {
L(i,j) = ((double) rand()) / RAND_MAX;
}
L(j,j) += n;
}
/* Imprimir matriz */
/*
for( i=0; i<n; i++ ) {
for( j=0; j<n; j++ ) {
printf("%10.3lf",L(i,j));
}
printf("\n");
}
*/
if( ( A = (double*) malloc(n*n*sizeof(double)) ) == NULL ) {
fprintf(stderr,"Error en la reserva de memoria para la matriz A\n");
exit(-1);
}
/*********************************************************/
/* Multiplicación A=L*L', donde L es triangular inferior */
/* Devuelve la parte triangular inferior en A */
double zero = 0.0;
double one = 1.0;
dsyrk_( "L", "N", &n, &n, &one, &L(0,0), &n, &zero, &A(0,0), &n );
/*********************************************************/
sscanf(argv[2],"%d",&b);
/* Imprimir matriz */
/*
for( i=0; i<n; i++ ) {
for( j=0; j<n; j++ ) {
printf("%10.3lf",A(i,j));
}
printf("\n");
}
*/
double t1, t2, ucpu, scpu;
ctimer( &t1, &ucpu, &scpu );
info = cholesky_escalar( n, A );
//info = cholesky_bloques( n, b, A );
//dpotrf_( "L", &n, A, &n, &info );
ctimer( &t2, &ucpu, &scpu );
if( info != 0 ) {
fprintf(stderr,"Error = %d en la descomposición de Cholesky de la matriz A\n",info);
exit(-1);
}
/* Imprimir matriz */
/*
for( i=0; i<n; i++ ) {
for( j=0; j<n; j++ ) {
printf("%10.3lf",A(i,j));
}
printf("\n");
}
*/
/* ¿ A = L ? */
double error = 0.0;
for( j=0; j<n; j++ ) {
for( i=j; i<n; i++ ) {
double b = (A(i,j)-L(i,j));
error += b*b;
}
}
error = sqrt(error);
//printf("Error = %10.4e\n",error);
printf("%10d %10d %20.2f sec. %15.4e\n",n,b,t2-t1,error);
free(A);
free(L);
}
int cholesky_escalar( int n, double *C ) {
int k;
for ( k = 0; k < n ; k++ ) {
/* CODIGO DE CHOLESKY ESCALAR */
double c;
int i,j;
c = sqrt(C(k,k));
C(k,k) = c;
#pragma omp parallel for schedule(runtime)
for (i=k+1; i < n; i++) {
C(i,k) = C(i,k)/c;
}
#pragma omp parallel for private(j) schedule(runtime)
for (i=k+1; i < n; i++){
for(j=k+1; j < i-1; j++){
C(i, j) = C(i, j) - C(i, k) * C(j, k);
}
C(i, i) = C(i, i) - C(i, k) * C(i, k);
}
}
return 0;
}
inline int min(int a, int b) { return (a < b) ? a : b; }
int cholesky_bloques( int n, int b, double *C ) {
int i, j, k, m;
int info;
const double one = 1.0;
const double minusone = -1.0;
for ( k = 0; k < n ; k+=b ) {
m = min( n-k, b );
dpotrf_( "L", &m, &C(k,k), &n, &info );
if( info != 0 ) {
fprintf(stderr,"Error = %d en la descomposición de Cholesky de la matriz C\n",info);
return info;
}
#pragma omp parallel for schedule(runtime)
for ( i = k + b; i < n; i += b ) {
m = min( n-i, b );
dtrsm_( "R", "L", "T", "N", &m, &b, &one, &C(k,k), &n, &C(i,k), &n );
}
#pragma omp parallel for private(j) schedule(runtime)
for ( i = k + b; i < n; i += b ) {
m = min( n-i, b );
for ( j = k + b; j < i ; j += b ) {
dgemm_( "N", "T", &m, &b, &b, &minusone, &C(i,k), &n, &C(j,k), &n, &one, &C(i,j), &n );
}
dsyrk_( "L", "N", &m, &b, &minusone, &C(i,k), &n, &one, &C(i,i), &n );
}
}
return 0;
}
|
GB_binop__second_uint8.c
|
//------------------------------------------------------------------------------
// GB_binop: hard-coded functions for each built-in binary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated2/ folder, do not edit it
// (it is auto-generated from Generator/*).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_emult.h"
#include "GB_control.h"
#include "GB_ek_slice.h"
#include "GB_dense.h"
#include "GB_atomics.h"
#include "GB_bitmap_assign_methods.h"
#include "GB_binop__include.h"
// C=binop(A,B) is defined by the following types and operators:
// A+B function (eWiseAdd): GB (_AaddB__second_uint8)
// A.*B function (eWiseMult): GB (_AemultB_08__second_uint8)
// A.*B function (eWiseMult): GB (_AemultB_02__second_uint8)
// A.*B function (eWiseMult): GB (_AemultB_04__second_uint8)
// A.*B function (eWiseMult): GB (_AemultB_bitmap__second_uint8)
// A*D function (colscale): GB (_AxD__second_uint8)
// D*A function (rowscale): GB (_DxB__second_uint8)
// C+=B function (dense accum): GB (_Cdense_accumB__second_uint8)
// C+=b function (dense accum): GB (_Cdense_accumb__second_uint8)
// C+=A+B function (dense ewise3): GB ((none))
// C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__second_uint8)
// C=scalar+B GB ((none))
// C=scalar+B' GB ((none))
// C=A+scalar GB ((none))
// C=A'+scalar GB ((none))
// C type: uint8_t
// A type: uint8_t
// A pattern? 1
// B type: uint8_t
// B pattern? 0
// BinaryOp: cij = bij
#define GB_ATYPE \
uint8_t
#define GB_BTYPE \
uint8_t
#define GB_CTYPE \
uint8_t
// true if the types of A and B are identical
#define GB_ATYPE_IS_BTYPE \
1
// true if the types of C and A are identical
#define GB_CTYPE_IS_ATYPE \
1
// true if the types of C and B are identical
#define GB_CTYPE_IS_BTYPE \
1
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA,A_iso) \
;
// true if values of A are not used
#define GB_A_IS_PATTERN \
1 \
// bij = Bx [pB]
#define GB_GETB(bij,Bx,pB,B_iso) \
uint8_t bij = GBX (Bx, pB, B_iso)
// true if values of B are not used
#define GB_B_IS_PATTERN \
0 \
// declare scalar of the same type as C
#define GB_CTYPE_SCALAR(t) \
uint8_t t
// cij = Ax [pA]
#define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \
cij = GBX (Ax, pA, A_iso)
// cij = Bx [pB]
#define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \
cij = GBX (Bx, pB, B_iso)
#define GB_CX(p) Cx [p]
// binary operator
#define GB_BINOP(z,x,y,i,j) \
z = y ;
// true if the binop must be flipped
#define GB_BINOP_FLIP \
0
// op is second
#define GB_OP_IS_SECOND \
1
// do the numerical phases of GB_add and GB_emult
#define GB_PHASE_2_OF_2
// hard-coded loops can be vectorized
#define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_SECOND || GxB_NO_UINT8 || GxB_NO_SECOND_UINT8)
//------------------------------------------------------------------------------
// C += A+B, all 3 matrices dense
//------------------------------------------------------------------------------
#if 0
// The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV.
void GB ((none))
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#include "GB_dense_ewise3_accum_template.c"
}
#endif
//------------------------------------------------------------------------------
// C = A+B, all 3 matrices dense
//------------------------------------------------------------------------------
void GB (_Cdense_ewise3_noaccum__second_uint8)
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#include "GB_dense_ewise3_noaccum_template.c"
}
//------------------------------------------------------------------------------
// C += B, accumulate a sparse matrix into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_accumB__second_uint8)
(
GrB_Matrix C,
const GrB_Matrix B,
const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
{
#include "GB_dense_subassign_23_template.c"
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C += b, accumulate a scalar into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_accumb__second_uint8)
(
GrB_Matrix C,
const GB_void *p_bwork,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
{
// get the scalar b for C += b, of type uint8_t
uint8_t bwork = (*((uint8_t *) p_bwork)) ;
#include "GB_dense_subassign_22_template.c"
return (GrB_SUCCESS) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = A*D, column scale with diagonal D matrix
//------------------------------------------------------------------------------
GrB_Info GB (_AxD__second_uint8)
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix D,
const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint8_t *restrict Cx = (uint8_t *) C->x ;
#include "GB_AxB_colscale_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = D*B, row scale with diagonal D matrix
//------------------------------------------------------------------------------
GrB_Info GB (_DxB__second_uint8)
(
GrB_Matrix C,
const GrB_Matrix D,
const GrB_Matrix B,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint8_t *restrict Cx = (uint8_t *) C->x ;
#include "GB_AxB_rowscale_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B
//------------------------------------------------------------------------------
GrB_Info GB (_AaddB__second_uint8)
(
GrB_Matrix C,
const int C_sparsity,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const bool is_eWiseUnion,
const GB_void *alpha_scalar_in,
const GB_void *beta_scalar_in,
const bool Ch_is_Mh,
const int64_t *restrict C_to_M,
const int64_t *restrict C_to_A,
const int64_t *restrict C_to_B,
const GB_task_struct *restrict TaskList,
const int C_ntasks,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
GB_WERK_DECLARE (M_ek_slicing, int64_t) ;
GB_WERK_DECLARE (A_ek_slicing, int64_t) ;
GB_WERK_DECLARE (B_ek_slicing, int64_t) ;
uint8_t alpha_scalar ;
uint8_t beta_scalar ;
if (is_eWiseUnion)
{
alpha_scalar = (*((uint8_t *) alpha_scalar_in)) ;
beta_scalar = (*((uint8_t *) beta_scalar_in )) ;
}
#include "GB_add_template.c"
GB_FREE_WORKSPACE ;
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C=A.*B, C<M>=A.*B, or C<M!>=A.*B where C is sparse/hyper
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_08__second_uint8)
(
GrB_Matrix C,
const int C_sparsity,
const int ewise_method,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *restrict C_to_M,
const int64_t *restrict C_to_A,
const int64_t *restrict C_to_B,
const GB_task_struct *restrict TaskList,
const int C_ntasks,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_emult_08_meta.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_02__second_uint8)
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const bool flipxy,
const int64_t *restrict Cp_kfirst,
const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#if GB_BINOP_FLIP
// The operator is not commutative, and does not have a flipped
// variant. For example z=atan2(y,x).
if (flipxy)
{
// use fmult(y,x)
#undef GB_FLIPPED
#define GB_FLIPPED 1
#include "GB_emult_02_template.c"
}
else
{
// use fmult(x,y)
#undef GB_FLIPPED
#define GB_FLIPPED 0
#include "GB_emult_02_template.c"
}
#else
// No need to handle the flip: the operator is either commutative, or
// has been handled by changing z=div(y,x) to z=rdiv(x,y) for example.
#undef GB_FLIPPED
#define GB_FLIPPED 0
#include "GB_emult_02_template.c"
#endif
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_04__second_uint8)
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *restrict Cp_kfirst,
const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_emult_04_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_bitmap__second_uint8)
(
GrB_Matrix C,
const int ewise_method,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_bitmap_emult_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st
//------------------------------------------------------------------------------
#if 0
GrB_Info GB ((none))
(
GB_void *Cx_output, // Cx and Bx may be aliased
const GB_void *x_input,
const GB_void *Bx_input,
const int8_t *restrict Bb,
int64_t bnz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint8_t *Cx = (uint8_t *) Cx_output ;
uint8_t x = (*((uint8_t *) x_input)) ;
uint8_t *Bx = (uint8_t *) Bx_input ;
int64_t p ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < bnz ; p++)
{
if (!GBB (Bb, p)) continue ;
uint8_t bij = GBX (Bx, p, false) ;
Cx [p] = bij ;
}
return (GrB_SUCCESS) ;
#endif
}
#endif
//------------------------------------------------------------------------------
// Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd
//------------------------------------------------------------------------------
#if 0
GrB_Info GB ((none))
(
GB_void *Cx_output, // Cx and Ax may be aliased
const GB_void *Ax_input,
const GB_void *y_input,
const int8_t *restrict Ab,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
uint8_t *Cx = (uint8_t *) Cx_output ;
uint8_t *Ax = (uint8_t *) Ax_input ;
uint8_t y = (*((uint8_t *) y_input)) ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!GBB (Ab, p)) continue ;
; ;
Cx [p] = y ;
}
return (GrB_SUCCESS) ;
#endif
}
#endif
//------------------------------------------------------------------------------
// C = op (x, A'): transpose and apply a binary operator
//------------------------------------------------------------------------------
#if 0
// cij = op (x, aij), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
uint8_t aij = GBX (Ax, pA, false) ; \
Cx [pC] = aij ; \
}
GrB_Info GB ((none))
(
GrB_Matrix C,
const GB_void *x_input,
const GrB_Matrix A,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
// GB_unop_transpose.c uses GB_ATYPE, but A is
// the 2nd input to binary operator z=f(x,y).
#undef GB_ATYPE
#define GB_ATYPE \
uint8_t
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint8_t x = (*((const uint8_t *) x_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
#undef GB_ATYPE
#define GB_ATYPE \
uint8_t
}
#endif
//------------------------------------------------------------------------------
// C = op (A', y): transpose and apply a binary operator
//------------------------------------------------------------------------------
#if 0
// cij = op (aij, y), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
; ; \
Cx [pC] = y ; \
}
GrB_Info GB ((none))
(
GrB_Matrix C,
const GrB_Matrix A,
const GB_void *y_input,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint8_t y = (*((const uint8_t *) y_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
#endif
|
GB_unop__lnot_uint64_uint64.c
|
//------------------------------------------------------------------------------
// GB_unop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated2/ folder, do not edit it
// (it is auto-generated from Generator/*).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_atomics.h"
#include "GB_unop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB (_unop_apply__lnot_uint64_uint64)
// op(A') function: GB (_unop_tran__lnot_uint64_uint64)
// C type: uint64_t
// A type: uint64_t
// cast: uint64_t cij = aij
// unaryop: cij = !(aij != 0)
#define GB_ATYPE \
uint64_t
#define GB_CTYPE \
uint64_t
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
uint64_t aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = !(x != 0) ;
// casting
#define GB_CAST(z, aij) \
uint64_t z = aij ;
// cij = op (aij)
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
uint64_t aij = Ax [pA] ; \
/* Cx [pC] = op (cast (aij)) */ \
uint64_t z = aij ; \
Cx [pC] = !(z != 0) ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_LNOT || GxB_NO_UINT64)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_apply__lnot_uint64_uint64)
(
uint64_t *Cx, // Cx and Ax may be aliased
const uint64_t *Ax,
const int8_t *restrict Ab, // A->b if A is bitmap
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
if (Ab == NULL)
{
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
uint64_t aij = Ax [p] ;
uint64_t z = aij ;
Cx [p] = !(z != 0) ;
}
}
else
{
// bitmap case, no transpose; A->b already memcpy'd into C->b
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!Ab [p]) continue ;
uint64_t aij = Ax [p] ;
uint64_t z = aij ;
Cx [p] = !(z != 0) ;
}
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_tran__lnot_uint64_uint64)
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
pi_omp_lock.c
|
/*
* Compute pi by approximating the area under the curve f(x) = 4 / (1 + x*x)
* between 0 and 1.
*
* Parallel version using OpenMP
*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <omp.h> /* OpenMP */
#if _EXTRAE_
#include "extrae_user_events.h"
// Extrae Constants
#define PROGRAM 1000
#define END 0
#define SERIAL 1
#define PARALLEL 2
#else
double getusec_() {
struct timeval time;
gettimeofday(&time, NULL);
return ((double)time.tv_sec * (double)1e6 + (double)time.tv_usec);
}
#define START_COUNT_TIME stamp = getusec_();
#define STOP_COUNT_TIME(_m) stamp = getusec_() - stamp;\
stamp = stamp/1e6;\
printf ("%s: %0.6fs\n",(_m), stamp);
#endif
int main(int argc, char *argv[]) {
#if _EXTRAE_
Extrae_event (PROGRAM, SERIAL);
#else
double stamp;
START_COUNT_TIME;
#endif
double x, sum=0.0, pi=0.0;
double step;
const char Usage[] = "Usage: pi <num_steps> (try 1000000000)\n";
if (argc < 2) {
fprintf(stderr, Usage);
exit(1);
}
long int num_steps = atoi(argv[1]);
step = 1.0/(double) num_steps;
#if _EXTRAE_
Extrae_event (PROGRAM, END);
#endif
/* do computation -- using all available threads */
#if _EXTRAE_
Extrae_event (PROGRAM, PARALLEL);
#endif
omp_lock_t lock;
omp_init_lock(&lock);
#pragma omp parallel private(x)
{
#pragma omp for
for (long int i=0; i<num_steps; ++i) {
x = (i+0.5)*step;
omp_set_lock(&lock);
sum += 4.0/(1.0+x*x);
omp_unset_lock(&lock);
}
}
omp_destroy_lock(&lock);
#if _EXTRAE_
Extrae_event (PROGRAM, END);
Extrae_event (PROGRAM, SERIAL);
#endif
pi = step * sum;
/* print results */
printf("Number pi after %ld iterations = %.15f\n", num_steps, pi);
#if _EXTRAE_
Extrae_event (PROGRAM, END);
#else
STOP_COUNT_TIME("Total execution time");
#endif
return EXIT_SUCCESS;
}
|
graph.c
|
/******************************************************************************
* INCLUDES
*****************************************************************************/
#include "base.h"
#include "graph.h"
#include "csf.h"
#include "sort.h"
#include "util.h"
#ifdef SPLATT_USE_PATOH
#include <patoh.h>
#endif
#ifdef SPLATT_USE_ASHADO
#include <ashado.h>
#endif
/******************************************************************************
* TYPES
*****************************************************************************/
/**
* @brief Represents a set with a known (and reasonable) maximum value.
*/
typedef struct
{
wgt_t * counts; /** The number of times an element was updated. */
vtx_t * seen; /** The (unsorted) list of elements that have been seen. */
vtx_t nseen; /** The length of seen[]. */
} adj_set;
/******************************************************************************
* PRIVATE FUNCTIONS
*****************************************************************************/
/**
* @brief Allocate/initialize a set.
*
* @param set The set to allocate.
* @param max_size The maximum element in the set. 2x this memory is allocated.
*/
static void p_set_init(
adj_set * set,
vtx_t max_size)
{
set->counts = calloc(max_size, sizeof(*(set->counts)));
set->seen = calloc(max_size, sizeof(*(set->seen)));
set->nseen = 0;
}
/**
* @brief Free all memory allocated for a set.
*
* @param set The set to free.
*/
static void p_set_free(
adj_set * set)
{
set->nseen = 0;
free(set->counts);
free(set->seen);
}
/**
* @brief Remove (but do not free) all elements from a set. This runs in
* O(nseen) time.
*
* @param set the set to clear.
*/
static void p_set_clear(
adj_set * set)
{
wgt_t * const counts = set->counts;
vtx_t * const seen = set->seen;
for(vtx_t i=0; i < set->nseen; ++i) {
counts[seen[i]] = 0;
seen[i] = 0;
}
set->nseen = 0;
}
/**
* @brief Add a new element to the set or update its count.
*
* @param set The set to modify.
* @param vid The id of the element.
* @param upd How much to modify counts[] by.
*/
static void p_set_update(
adj_set * set,
vtx_t vid,
wgt_t upd)
{
/* add to set if necessary */
if(set->counts[vid] == 0) {
set->seen[set->nseen] = vid;
set->nseen += 1;
}
/* update count */
set->counts[vid] += upd;
}
/**
* @brief Count the number of edges (i.e., the size of adjacency list) of a
* sparse tensor converted to m-partite graph.
*
* @param csf The tensor to convert.
*
* @return The number of edges.
*/
static adj_t p_count_adj_size(
splatt_csf * const csf)
{
adj_t ncon = 0;
assert(csf->ntiles == 1);
csf_sparsity * pt = csf->pt;
vtx_t const nvtxs = pt->nfibs[0];
/* type better be big enough */
assert((idx_t) nvtxs == (vtx_t) nvtxs);
adj_set set;
p_set_init(&set, csf->dims[argmax_elem(csf->dims, csf->nmodes)]);
idx_t parent_start = 0;
idx_t parent_end = 0;
for(vtx_t v=0; v < nvtxs; ++v) {
parent_start = v;
parent_end = v+1;
for(idx_t d=1; d < csf->nmodes; ++d) {
idx_t const start = pt->fptr[d-1][parent_start];
idx_t const end = pt->fptr[d-1][parent_end];
fidx_t const * const fids = pt->fids[d];
for(idx_t f=start; f < end; ++f) {
p_set_update(&set, fids[f], 1);
}
ncon += set.nseen;
/* prepare for next level in the tree */
parent_start = start;
parent_end = end;
p_set_clear(&set);
}
}
p_set_free(&set);
return ncon;
}
/**
* @brief Compute the offset of a certain CSF tree depth (when all indices are
* mapped to vertices). This accounts for csf->dim_perm.
*
* For example, with no permutation and depth=2, this returns
* csf->dims[0] + csf->dims[1].
*
* @param csf The tensor to use for calculation.
* @param depth The depth to work on.
*
* @return The offset.
*/
static idx_t p_calc_offset(
splatt_csf const * const csf,
idx_t const depth)
{
idx_t const mode = csf->dim_perm[depth];
idx_t offset = 0;
for(idx_t m=0; m < mode; ++m) {
offset += csf->dims[m];
}
return offset;
}
/**
* @brief Count the nonzeros below a given node in a CSF tensor.
*
* @param fptr The adjacency pointer of the CSF tensor.
* @param nmodes The number of modes in the tensor.
* @param depth The depth of the node
* @param fiber The id of the node.
*
* @return The nonzeros below fptr[depth][fiber].
*/
static wgt_t p_count_nnz(
idx_t * * fptr,
idx_t const nmodes,
idx_t depth,
idx_t const fiber)
{
if(depth == nmodes-1) {
return 1;
}
idx_t left = fptr[depth][fiber];
idx_t right = fptr[depth][fiber+1];
++depth;
for(; depth < nmodes-1; ++depth) {
left = fptr[depth][left];
right = fptr[depth][right];
}
return right - left;
}
/**
* @brief Fill the contents of a splatt_graph. The graph must already be
* allocated!
*
* @param csf The tensor to convert.
* @param graph The graph to fill, ALREADY ALLOCATED!
*/
static void p_fill_ijk_graph(
splatt_csf const * const csf,
splatt_graph * graph)
{
csf_sparsity * pt = csf->pt;
vtx_t const nvtxs = graph->nvtxs;
adj_set set;
p_set_init(&set, csf->dims[argmax_elem(csf->dims, csf->nmodes)]);
/* pointing into eind */
adj_t ncon = 0;
/* start/end of my subtree */
idx_t parent_start;
idx_t parent_end;
for(vtx_t v=0; v < nvtxs; ++v) {
parent_start = v;
parent_end = v+1;
graph->eptr[v] = ncon;
for(idx_t d=1; d < csf->nmodes; ++d) {
idx_t const start = pt->fptr[d-1][parent_start];
idx_t const end = pt->fptr[d-1][parent_end];
/* compute adjacency info */
fidx_t const * const fids = pt->fids[d];
for(idx_t f=start; f < end; ++f) {
p_set_update(&set, fids[f], p_count_nnz(pt->fptr, csf->nmodes, d, f));
}
/* things break if vtx size isn't our sorting size... */
if(sizeof(*(set.seen)) == sizeof(splatt_idx_t)) {
quicksort((idx_t *) set.seen, set.nseen);
}
/* fill in graph->eind */
idx_t const id_offset = p_calc_offset(csf, d);
for(vtx_t e=0; e < set.nseen; ++e) {
graph->eind[ncon] = set.seen[e] + id_offset;
if(graph->ewgts != NULL) {
graph->ewgts[ncon] = set.counts[set.seen[e]];
}
++ncon;
}
/* prepare for next level in the tree */
parent_start = start;
parent_end = end;
p_set_clear(&set);
}
}
p_set_free(&set);
graph->eptr[nvtxs] = graph->nedges;
}
/**
* @brief Takes a list of graphs and returns them stacked on top of each other.
* No adjacency lists are altered, only vertices added.
*
* @param graphs The graphs to merge.
* @param ngraphs The number of graphs.
*
* @return All graphs stacked.
*/
static splatt_graph * p_merge_graphs(
splatt_graph * * graphs,
idx_t const ngraphs)
{
/* count total size */
vtx_t nvtxs = 0;
adj_t ncon = 0;
for(idx_t m=0; m < ngraphs; ++m) {
nvtxs += graphs[m]->nvtxs;
ncon += graphs[m]->nedges;
}
splatt_graph * ret = graph_alloc(nvtxs, ncon, 0, 1);
/* fill in ret */
vtx_t voffset = 0;
adj_t eoffset = 0;
for(idx_t m=0; m < ngraphs; ++m) {
for(vtx_t v=0; v < graphs[m]->nvtxs; ++v) {
vtx_t const * const eptr = graphs[m]->eptr;
adj_t const * const eind = graphs[m]->eind;
wgt_t const * const ewgts = graphs[m]->ewgts;
ret->eptr[v + voffset] = eptr[v] + eoffset;
for(adj_t e=eptr[v]; e < eptr[v+1]; ++e) {
ret->eind[e + eoffset] = eind[e];
ret->ewgts[e + eoffset] = ewgts[e];
}
}
voffset += graphs[m]->nvtxs;
eoffset += graphs[m]->nedges;
}
return ret;
}
/**
* @brief Fill the vertex weights array.
*
* @param ft The CSF tensor to derive vertex weights from.
* @param hg The hypegraph structure to modify.
* @param which Vertex weight model to follow, see graph.h.
*/
static void p_fill_vwts(
ftensor_t const * const ft,
hgraph_t * const hg,
hgraph_vwt_type const which)
{
switch(which) {
case VTX_WT_NONE:
hg->vwts = NULL;
break;
/* weight based on nnz in fiber */
case VTX_WT_FIB_NNZ:
hg->vwts = (idx_t *) splatt_malloc(hg->nvtxs * sizeof(idx_t));
#pragma omp parallel for
for(idx_t v=0; v < hg->nvtxs; ++v) {
hg->vwts[v] = ft->fptr[v+1] - ft->fptr[v];
}
}
}
/**
* @brief Maps an index in a mode of a permuted CSF tensor to a global vertex
* index. This accounts for the mode permutation using the CSF dim-perm.
*
* @param id The index we are converting (local to the mode).
* @param mode The mode the index lies in (LOCAL TO THE CSF TENSOR).
* EXAMPLE: a 3 mode tensor would use mode-0 to represent slices,
* mode-1 to represent fids, and mode-2 to represent the fiber nnz
* @param ft The CSF tensor with dim_perm.
*
* @return 'id', converted to global vertex indices. EXAMPLE: k -> (I+J+k).
*/
static idx_t p_map_idx(
idx_t id,
idx_t const mode,
ftensor_t const * const ft)
{
idx_t m = 0;
while(m != ft->dim_perm[mode]) {
id += ft->dims[m++];
}
return id;
}
/******************************************************************************
* PUBLIC FUNCTIONS
*****************************************************************************/
hgraph_t * hgraph_nnz_alloc(
sptensor_t const * const tt)
{
hgraph_t * hg = (hgraph_t *) splatt_malloc(sizeof(hgraph_t));
hg->nvtxs = tt->nnz;
p_fill_vwts(NULL, hg, VTX_WT_NONE);
/* # hyper-edges = I + J + K + ... */
hg->hewts = NULL;
hg->nhedges = 0;
for(idx_t m=0; m < tt->nmodes; ++m) {
hg->nhedges += tt->dims[m];
}
/* fill in eptr shifted by 1 index. */
hg->eptr = (idx_t *) calloc(hg->nhedges+1, sizeof(idx_t));
idx_t * const restrict eptr = hg->eptr;
idx_t offset = 1;
for(idx_t m=0; m < tt->nmodes; ++m) {
fidx_t const * const restrict ind = tt->ind[m];
for(idx_t n=0; n < tt->nnz; ++n) {
eptr[offset+ind[n]] += 1;
}
offset += tt->dims[m];
}
/* do a shifted prefix sum to get eptr */
idx_t saved = eptr[1];
eptr[1] = 0;
for(idx_t i=2; i <= hg->nhedges; ++i) {
idx_t tmp = eptr[i];
eptr[i] = eptr[i-1] + saved;
saved = tmp;
}
/* each nnz causes 'nmodes' connections */
hg->eind = (idx_t *) splatt_malloc(tt->nnz * tt->nmodes * sizeof(idx_t));
idx_t * const restrict eind = hg->eind;
offset = 1;
for(idx_t m=0; m < tt->nmodes; ++m) {
fidx_t const * const restrict ind = tt->ind[m];
for(idx_t n=0; n < tt->nnz; ++n) {
eind[eptr[offset+ind[n]]++] = n;
}
offset += tt->dims[m];
}
assert(eptr[hg->nhedges] == tt->nnz * tt->nmodes);
return hg;
}
hgraph_t * hgraph_fib_alloc(
ftensor_t const * const ft,
idx_t const mode)
{
hgraph_t * hg = (hgraph_t *) splatt_malloc(sizeof(hgraph_t));
/* vertex weights are nnz per fiber */
hg->nvtxs = ft->nfibs;
p_fill_vwts(ft, hg, VTX_WT_FIB_NNZ);
/* # hyper-edges = I + J + K + ... */
hg->hewts = NULL;
hg->nhedges = 0;
for(idx_t m=0; m < ft->nmodes; ++m) {
hg->nhedges += ft->dims[m];
}
/* fill in eptr shifted by 1 idx:
* a) each nnz induces a hyperedge connection
* b) each non-fiber mode accounts for a hyperedge connection
*/
hg->eptr = (idx_t *) calloc(hg->nhedges+1, sizeof(idx_t));
idx_t * const restrict eptr = hg->eptr;
for(idx_t s=0; s < ft->nslcs; ++s) {
/* the slice hyperedge has nfibers more connections */
eptr[1+p_map_idx(s, 0, ft)] += ft->sptr[s+1] - ft->sptr[s];
for(idx_t f=ft->sptr[s]; f < ft->sptr[s+1]; ++f) {
/* fiber makes another connection with fid */
eptr[1+p_map_idx(ft->fids[f], 1, ft)] += 1;
/* each nnz now has a contribution too */
for(idx_t jj=ft->fptr[f]; jj < ft->fptr[f+1]; ++jj) {
eptr[1+p_map_idx(ft->inds[jj], 2, ft)] += 1;
}
}
}
/* do a shifted prefix sum to get eptr */
idx_t ncon = eptr[1];
idx_t saved = eptr[1];
eptr[1] = 0;
for(idx_t i=2; i <= hg->nhedges; ++i) {
ncon += eptr[i];
idx_t tmp = eptr[i];
eptr[i] = eptr[i-1] + saved;
saved = tmp;
}
hg->eind = (idx_t *) splatt_malloc(ncon * sizeof(idx_t));
idx_t * const restrict eind = hg->eind;
/* now fill in eind while using eptr as a marker */
for(idx_t s=0; s < ft->nslcs; ++s) {
idx_t const sid = p_map_idx(s, 0, ft);
for(idx_t f = ft->sptr[s]; f < ft->sptr[s+1]; ++f) {
idx_t const fid = p_map_idx(ft->fids[f], 1, ft);
eind[eptr[1+sid]++] = f;
eind[eptr[1+fid]++] = f;
for(idx_t jj=ft->fptr[f]; jj < ft->fptr[f+1]; ++jj) {
idx_t const nid = p_map_idx(ft->inds[jj], 2, ft);
eind[eptr[1+nid]++] = f;
}
}
}
return hg;
}
idx_t * hgraph_uncut(
hgraph_t const * const hg,
idx_t const * const parts,
idx_t * const ret_nnotcut)
{
idx_t const nhedges = (idx_t) hg->nhedges;
idx_t const nvtxs = (idx_t)hg->nvtxs;
idx_t const * const eptr = hg->eptr;
idx_t const * const eind = hg->eind;
idx_t ncut = 0;
for(idx_t h=0; h < nhedges; ++h) {
int iscut = 0;
idx_t const firstpart = parts[eind[eptr[h]]];
for(idx_t e=eptr[h]+1; e < eptr[h+1]; ++e) {
idx_t const vtx = eind[e];
if(parts[vtx] != firstpart) {
iscut = 1;
break;
}
}
if(iscut == 0) {
++ncut;
}
}
*ret_nnotcut = ncut;
/* go back and fill in uncut edges */
idx_t * cut = (idx_t *) splatt_malloc(ncut * sizeof(idx_t));
idx_t ptr = 0;
for(idx_t h=0; h < nhedges; ++h) {
int iscut = 0;
idx_t const firstpart = parts[eind[eptr[h]]];
for(idx_t e=eptr[h]+1; e < eptr[h+1]; ++e) {
idx_t const vtx = eind[e];
if(parts[vtx] != firstpart) {
iscut = 1;
break;
}
}
if(iscut == 0) {
cut[ptr++] = h;
}
}
return cut;
}
void hgraph_free(
hgraph_t * hg)
{
free(hg->eptr);
free(hg->eind);
free(hg->vwts);
free(hg->hewts);
free(hg);
}
splatt_graph * graph_convert(
sptensor_t * const tt)
{
double * opts = splatt_default_opts();
opts[SPLATT_OPTION_TILE] = SPLATT_NOTILE;
splatt_graph * graphs[MAX_NMODES];
splatt_csf csf;
for(idx_t m=0; m < tt->nmodes; ++m) {
csf_alloc_mode(tt, CSF_INORDER_MINUSONE, m, &csf, opts);
/* count size of adjacency list */
adj_t const ncon = p_count_adj_size(&csf);
graphs[m] = graph_alloc(tt->dims[m], ncon, 0, 1);
p_fill_ijk_graph(&csf, graphs[m]);
csf_free_mode(&csf);
}
/* merge graphs and write */
splatt_graph * full_graph = p_merge_graphs(graphs, tt->nmodes);
/* cleanup */
splatt_free_opts(opts);
for(idx_t m=0; m < tt->nmodes; ++m) {
graph_free(graphs[m]);
}
return full_graph;
}
splatt_graph * graph_alloc(
vtx_t nvtxs,
adj_t nedges,
int use_vtx_wgts,
int use_edge_wgts)
{
splatt_graph * ret = splatt_malloc(sizeof(*ret));
ret->nvtxs = nvtxs;
ret->nedges = nedges;
ret->eptr = splatt_malloc((nvtxs+1) * sizeof(*(ret->eptr)));
ret->eind = splatt_malloc(nedges * sizeof(*(ret->eind)));
ret->eptr[nvtxs] = nedges;
if(use_vtx_wgts) {
ret->vwgts = splatt_malloc(nvtxs * sizeof(*(ret->vwgts)));
} else {
ret->vwgts = NULL;
}
if(use_edge_wgts) {
ret->ewgts = splatt_malloc(nedges * sizeof(*(ret->ewgts)));
} else {
ret->ewgts = NULL;
}
return ret;
}
void graph_free(
splatt_graph * graph)
{
free(graph->eptr);
free(graph->eind);
free(graph->vwgts);
free(graph->ewgts);
free(graph);
}
#ifdef SPLATT_USE_PATOH
idx_t * patoh_part(
hgraph_t const * const hg,
idx_t const nparts)
{
PaToH_Parameters args;
PaToH_Initialize_Parameters(&args, PATOH_CUTPART, PATOH_SUGPARAM_SPEED);
int const nvtxs = hg->nvtxs;
int const nnets = hg->nhedges;
int const ncon = 1;
/* vertex weights */
int * vwts = (int *) splatt_malloc(nvtxs * sizeof(int));
if(hg->vwts != NULL) {
for(int v=0; v < nvtxs; ++v) {
vwts[v] = (int) hg->vwts[v];
}
} else {
for(int v=0; v < nvtxs; ++v) {
vwts[v] = 1;
}
}
/* edge weights */
int * hwts = NULL;
if(hg->hewts != NULL) {
hwts = (int *) splatt_malloc(nnets * sizeof(int));
for(int h=0; h < nnets; ++h) {
hwts[h] = (int) hg->hewts[h];
}
}
/* net start/end */
int * eptr = (int *) splatt_malloc((nnets+1) * sizeof(int));
for(int v=0; v <= nnets; ++v) {
eptr[v] = (int) hg->eptr[v];
}
/* netted vertices */
int * eind = (int *) splatt_malloc(eptr[nnets] * sizeof(int));
for(int v=0; v < eptr[nnets]; ++v) {
eind[v] = (int) hg->eind[v];
}
int * pvec = (int *) splatt_malloc(nvtxs * sizeof(int));
int * pwts = (int *) splatt_malloc(nparts * sizeof(int));
int cut;
args._k = (int) nparts;
PaToH_Alloc(&args, nvtxs, nnets, ncon, vwts, hwts, eptr, eind);
/* do the partitioning! */
PaToH_Part(&args, nvtxs, nnets, ncon, 0, vwts, hwts, eptr, eind, NULL, pvec,
pwts, &cut);
/* copy patoh output to idx_t */
idx_t * parts = (idx_t *) splatt_malloc(nvtxs * sizeof(idx_t));
for(idx_t p=0; p < hg->nvtxs; ++p) {
parts[p] = (idx_t) pvec[p];
}
PaToH_Free();
free(vwts);
free(hwts);
free(eptr);
free(eind);
free(pvec);
free(pwts);
return parts;
}
#endif
#ifdef SPLATT_USE_ASHADO
idx_t * ashado_part(
hgraph_t const * const hg,
idx_t const nparts)
{
double * opts = ashado_default_opts();
idx_t * part = (idx_t *) splatt_malloc(hg->nvtxs * sizeof(idx_t));
ashado_partition(nparts, hg->nvtxs, hg->nhedges, hg->eptr, hg->eind,
hg->vwts, hg->hewts, opts, 5, part);
free(opts);
return part;
}
#endif
|
GB_unaryop__lnot_bool_uint32.c
|
//------------------------------------------------------------------------------
// GB_unaryop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved.
// http://suitesparse.com See GraphBLAS/Doc/License.txt for license.
//------------------------------------------------------------------------------
// If this file is in the Generated/ folder, do not edit it (auto-generated).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_iterator.h"
#include "GB_unaryop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB_unop__lnot_bool_uint32
// op(A') function: GB_tran__lnot_bool_uint32
// C type: bool
// A type: uint32_t
// cast: bool cij = (bool) aij
// unaryop: cij = !aij
#define GB_ATYPE \
uint32_t
#define GB_CTYPE \
bool
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
uint32_t aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = !x ;
// casting
#define GB_CASTING(z, x) \
bool z = (bool) x ;
// cij = op (cast (aij))
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
GB_GETA (aij, Ax, pA) ; \
/* Cx [pC] = op (cast (aij)) */ \
GB_CASTING (x, aij) ; \
GB_OP (GB_CX (pC), x) ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_LNOT || GxB_NO_BOOL || GxB_NO_UINT32)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop__lnot_bool_uint32
(
bool *restrict Cx,
const uint32_t *restrict Ax,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (int64_t p = 0 ; p < anz ; p++)
{
GB_CAST_OP (p, p) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_tran__lnot_bool_uint32
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t **Rowcounts,
GBI_single_iterator Iter,
const int64_t *restrict A_slice,
int naslice
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#define GB_PHASE_2_OF_2
#include "GB_unaryop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
HaloArray3D.h
|
/* ParSGCT Code source file.
Copyright (c) 2015 Peter Edward Strazdins. All rights reserved.
Licensed under the terms of the BSD License as described in the LICENSE_SGCT file.
This comment must be retained in any redistributions of this source file.
*/
// Simple 3D (x,y) array with a halo class.
// Storage is contiguous in the x co-ordinate
// written by Peter Strazdins, May 13
// updated for block arrays, Apr 14
// updated for 3D, Jun 14
#ifndef HALOARRAY3D_INCLUDED
#define HALOARRAY3D_INCLUDED
#include <stdio.h>
#include <assert.h>
#include <cmath> //std::abs, log2
#include <string> //std::string
#ifdef _OPENMP
#include <omp.h>
#endif
#include "Vec3D.h"
class HaloArray3D {
public:
double *u;
Vec3D<int> l, s; // local size, storage size (= local + halo)
Vec3D<int> halo;
int B; // size of individual elements
HaloArray3D(Vec3D<int> l_, Vec3D<int> h, int blk=1) {
l = l_; B = blk;
l.x = l.x*B;
assert (h.prod() >= 0);
halo = h;
s = l + Vec3D<int>(B, 1, 1) * 2*halo;
// check for potential overflow; should change to Vec3D<long> in future
if (s.x > 0 && s.y > 0 && s.z > 0) // this process owns part of the grid
assert(log2(s.x) + log2(s.y) + log2(s.z) < sizeof(int)*8 - 1);
if (s.prod() > 0)
u = new double[s.prod()];
else
u = 0;
}
~HaloArray3D() {
if (u != 0)
delete[] u;
}
// to take into account B>1, i = i'B + ib, where i' is the logical
// i-index of block and iB is offset within block, 0 <= ib < B
inline double *ix(int i, int j, int k) {
#if 0
assert (0 <= i && i < s.x && 0 <= j && j < s.y && 0 <= k && k < s.z);
#endif
return(&u[i + s.x * (j + s.y*k)]);
}
inline double *ix_h(int i, int j, int k) {
return ix(i + halo.x*B, j + halo.y, k + halo.z);
}
void zero() {
#pragma omp parallel for default(shared)
for (int kj = 0; kj < l.z*l.y; kj++) {
int k = kj / l.y, j = kj % l.y;
for (int i=0; i < l.x; i++) {
*ix_h(i, j, k) = 0.0;
}
}
}
double norm1() {
double norm = 0.0;
for (int k=0; k < l.z; k++)
for (int j=0; j < l.y; j++)
for (int i=0; i < l.x; i++) {
norm += std::abs(*ix_h(i, j, k));
}
return (norm);
}
double *pack(Vec3D<int> i0, Vec3D<int> m) {
double* buf = new double [m.prod()*B];
#pragma omp parallel for default(shared)
for (int kj = 0; kj < m.z*m.y; kj++) {
int k = kj / m.y, j = kj % m.y;
double *b = &buf[kj * m.x*B];
for (int i=0; i < m.x*B; i++) {
*b = *ix_h(i+i0.x*B, j+i0.y, k+i0.z);
b++;
}
}
return (buf);
}
void unpack(double* buf, Vec3D<int> i0, Vec3D<int> m) {
#pragma omp parallel for default(shared)
for (int kj = 0; kj < m.z*m.y; kj++) {
int k = kj / m.y, j = kj % m.y;
double *b = &buf[kj * m.x*B];
for (int i=0; i < m.x*B; i++) {
*ix_h(i+i0.x*B, j+i0.y, k+i0.z) = *b;
b++;
}
}
}
void interpolate(double coeff, HaloArray3D *v, Vec3D<int> rV,
Vec3D<int> i0, Vec3D<int> n) {
#if 0
printf("v.h=%d,%d,%d v.s=%d,%d,%d i0=%d,%d,%d n=%d,%d,%d\n",
v->halo.x, v->halo.y, v->halo.z, v->s.x, v->s.y, v->s.z,
i0.x, i0.y, i0.z, n.x, n.y, n.z);
#endif
#pragma omp parallel for default(shared)
for (int kj = 0; kj < n.z*n.y; kj++) {
int k = kj / n.y, j = kj % n.y;
double z = (1.0 * k) / rV.z;
int iz = std::min((int) z, n.z-1);
double rz = z - iz, rzc = 1.0 - rz;
double y = (1.0 * j) / rV.y;
int iy = std::min((int) y, n.y-1);
double ry = y - iy, ryc = 1.0 - ry;
for (int i=0; i < n.x; i++) {
double x = (1.0 * i) / rV.x;
int ix = std::min((int) x, n.x-1);
double rx = x - ix, rxc = 1.0 - rx;
int iB = (i+i0.x)*B, ixB = ix*B;
for (int ib=0; ib < B; ib++) {
// avoid potentially undefined iy+1, iz+1 elts when ry, rz == 0
// if (ixB+B+ib >= 65) printf("oob on v B=%d\n", B);
double interpolant =
rxc*ryc*rzc * *(v->ix_h(ixB+ib, iy, iz)) +
rx *ryc*rzc * *(v->ix_h(ixB+B+ib, iy, iz));
if (rV.y > 1)
interpolant +=
rxc*ry *rzc * *(v->ix_h(ixB+ib, iy+1, iz)) +
rx *ry *rzc * *(v->ix_h(ixB+B+ib, iy+1, iz));
if (rV.z > 1) {
interpolant +=
rxc*ryc*rz * *(v->ix_h(ixB+ib, iy, iz+1)) +
rx *ryc*rz * *(v->ix_h(ixB+B+ib, iy, iz+1));
if (rV.y > 1)
interpolant +=
rxc*ry *rz * *(v->ix_h(ixB+ib, iy+1, iz+1)) +
rx *ry *rz * *(v->ix_h(ixB+B+ib, iy+1, iz+1));
}
*ix_h(iB+ib, j+i0.y, k+i0.z) += coeff * interpolant;
}
}
}
} //interpolate()
double *sample(Vec3D<int> i0, Vec3D<int> rV, Vec3D<int> n) {
double *buf = new double [n.prod()*B];
#pragma omp parallel for default(shared)
for (int kj = 0; kj < n.z*n.y; kj++) {
int k = kj / n.y, j = kj % n.y;
double *v = &buf[kj * n.x * B];
for (int i=0; i < n.x; i++) {
int iB = (i0.x + i*rV.x)*B;
for (int ib=0; ib < B; ib++) {
*v = *ix_h(iB + ib, i0.y + j*rV.y, i0.z + k*rV.z);
v++;
}
}
}
return buf;
} //sample()
void print(int rank, std::string label) {
printf("l.z=%d s.z=%d\n", l.z, s.z);
for (int k=0; k < l.z; k++) {
if (label.c_str()[0] != 0)
printf("%d: %s[%d]:\n", rank, label.c_str(), k);
for (int j=0; j < l.y; j++) {
if (rank >= 0)
printf("%d: ", rank);
for (int i=0; i < l.x; i++)
// printf("%0.2e ", *ix_h(i, j, k));
printf("(%d,%d)%0.2e ", i,j,*ix_h(i, j, k));
printf("\n");
}
printf("\n");
}
}
void printh(int rank, std::string label) {
for (int k=0; k < l.z; k++) {
if (label.c_str()[0] != 0)
printf("%d: %s[%d]:\n", rank, label.c_str(), k);
for (int j=0; j < s.y; j++) {
if (rank >= 0)
printf("%d: ", rank);
for (int i=0; i < s.x; i++)
printf("%0.2e ", *ix(i, j, k));
printf("\n");
}
printf("\n");
}
}
};
// macros for access elements for logical array without the halo
#define V(u, i, j, k) (*((u)->ix(i, j, k)))
// macros for accessing elements taking into account the halo
#define Vh(u, i, j, k) (*((u)->ix_h(i, j, k)))
#endif /*HALOARRAY3D_INCLUDED*/
|
DRB093-doall2-collapse-orig-no.c
|
/*
Copyright (c) 2017, Lawrence Livermore National Security, LLC.
Produced at the Lawrence Livermore National Laboratory
Written by Chunhua Liao, Pei-Hung Lin, Joshua Asplund,
Markus Schordan, and Ian Karlin
(email: [email protected], [email protected], [email protected],
[email protected], [email protected])
LLNL-CODE-732144
All rights reserved.
This file is part of DataRaceBench. For details, see
https://github.com/LLNL/dataracebench. Please also see the LICENSE file
for our additional BSD notice.
Redistribution and use in source and binary forms, with
or without modification, are permitted provided that the following
conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the disclaimer below.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the disclaimer (as noted below)
in the documentation and/or other materials provided with the
distribution.
* Neither the name of the LLNS/LLNL nor the names of its contributors
may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL LAWRENCE LIVERMORE NATIONAL
SECURITY, LLC, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
Two-dimensional array computation:
collapse(2) is used to associate two loops with omp for.
The corresponding loop iteration variables are private.
*/
#include <stdio.h>
#include <omp.h>
int a[100][100];
int main()
{
int i;
int j;
#pragma omp parallel for private (i,j)
for (i = 0; i <= 99; i += 1) {
#pragma omp parallel for private (j)
for (j = 0; j <= 99; j += 1) {
a[i][j] = i;
}
}
#pragma omp parallel for private (i,j)
for (i = 0; i <= 99; i += 1) {
#pragma omp parallel for private (j)
for (j = 0; j <= 99; j += 1) {
a[i][j] = a[i][j] + 1;
}
}
for (i = 0; i <= 99; i += 1) {
for (j = 0; j <= 99; j += 1) {
printf("%d\n",a[i][j]);
}
}
return 0;
}
|
MKL_flops_32_omp.c
|
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <time.h>
#include <omp.h>
#include "gene_bruit_rayleigh_scalaire.c"
#ifdef MKL_LIB
#include "mkl.h"
#include "mkl_dfti.h"
#endif
int main(int argc, char** argv) {
int NFFT,NPOINTS,NTOT;
NTOT=67108864;
printf("-*/*-*/- Programme MKL/FFTw simple precision -*/*-*/-\n");
FILE *fichier1;
fichier1=fopen("../results/MKL_32_GFLOPS.dat","w");
for (NPOINTS=2 ; NPOINTS<262144+1 ; NPOINTS=2*NPOINTS)
{
NFFT=NTOT/NPOINTS;
struct timespec tpdeb, tpfin, tpcour;
clockid_t clock_id = CLOCK_REALTIME;
int status2;
float dureeloc;
float dureetot = 0.0;
float mflops;
float param;
float *scalar_real, *scalar_imag;
int i, j, k;
param = 20.0;
float f_num = 30000;
float f_0 = f_num / 4.0;
#ifdef MKL_LIB
MKL_LONG status = 0;
DFTI_DESCRIPTOR_HANDLE hand [8];
MKL_Complex8 * data[8];
MKL_Complex8 * dataCour = NULL;
memset(hand, 0, 8 * sizeof (DFTI_DESCRIPTOR_HANDLE));
memset(data, 0, 8 * sizeof (MKL_Complex8));
#endif
scalar_real = (float *) calloc(NPOINTS, sizeof (float));
scalar_imag = (float *) calloc(NPOINTS, sizeof (float));
//FILE *fichier1,*fichier2;
//fichier1=fopen("/home/jfd/PROGRAMMES/FFT/scalar_real.dat","w");
//fichier2=fopen("/home/jfd/PROGRAMMES/FFT/scalar_imag.dat","w");
#ifndef MKL_LIB
/*----------- Declaration talbeaux FFT -----------------*/
// CPU #1
fftwf_complex *data, *fft_result, *data2, *fft_result2, *data3, *fft_result3, *data4, *fft_result4;
fftwf_plan plan_forward, plan_forward2, plan_forward3, plan_forward4;
data = (fftwf_complex*) fftwf_malloc(sizeof (fftwf_complex) * NPOINTS);
fft_result = (fftwf_complex*) fftwf_malloc(sizeof (fftwf_complex) * NPOINTS);
data2 = (fftwf_complex*) fftwf_malloc(sizeof (fftwf_complex) * NPOINTS);
fft_result2 = (fftwf_complex*) fftwf_malloc(sizeof (fftwf_complex) * NPOINTS);
data3 = (fftwf_complex*) fftwf_malloc(sizeof (fftwf_complex) * NPOINTS);
fft_result3 = (fftwf_complex*) fftwf_malloc(sizeof (fftwf_complex) * NPOINTS);
data4 = (fftwf_complex*) fftwf_malloc(sizeof (fftwf_complex) * NPOINTS);
fft_result4 = (fftwf_complex*) fftwf_malloc(sizeof (fftwf_complex) * NPOINTS);
plan_forward = fftwf_plan_dft_1d(NPOINTS, data, fft_result, FFTW_FORWARD, FFTW_ESTIMATE);
plan_forward2 = fftwf_plan_dft_1d(NPOINTS, data2, fft_result2, FFTW_FORWARD, FFTW_ESTIMATE);
plan_forward3 = fftwf_plan_dft_1d(NPOINTS, data3, fft_result3, FFTW_FORWARD, FFTW_ESTIMATE);
plan_forward4 = fftwf_plan_dft_1d(NPOINTS, data4, fft_result4, FFTW_FORWARD, FFTW_ESTIMATE);
// CPU #2
fftwf_complex *data5, *fft_result5, *data6, *fft_result6, *data7, *fft_result7, *data8, *fft_result8;
fftwf_plan plan_forward5, plan_forward6, plan_forward7, plan_forward8;
data5 = (fftwf_complex*) fftwf_malloc(sizeof (fftwf_complex) * NPOINTS);
fft_result5 = (fftwf_complex*) fftwf_malloc(sizeof (fftwf_complex) * NPOINTS);
data6 = (fftwf_complex*) fftwf_malloc(sizeof (fftwf_complex) * NPOINTS);
fft_result6 = (fftwf_complex*) fftwf_malloc(sizeof (fftwf_complex) * NPOINTS);
data7 = (fftwf_complex*) fftwf_malloc(sizeof (fftwf_complex) * NPOINTS);
fft_result7 = (fftwf_complex*) fftwf_malloc(sizeof (fftwf_complex) * NPOINTS);
data8 = (fftwf_complex*) fftwf_malloc(sizeof (fftwf_complex) * NPOINTS);
fft_result8 = (fftwf_complex*) fftwf_malloc(sizeof (fftwf_complex) * NPOINTS);
plan_forward5 = fftwf_plan_dft_1d(NPOINTS, data5, fft_result5, FFTW_FORWARD, FFTW_ESTIMATE);
plan_forward6 = fftwf_plan_dft_1d(NPOINTS, data6, fft_result6, FFTW_FORWARD, FFTW_ESTIMATE);
plan_forward7 = fftwf_plan_dft_1d(NPOINTS, data7, fft_result7, FFTW_FORWARD, FFTW_ESTIMATE);
plan_forward8 = fftwf_plan_dft_1d(NPOINTS, data8, fft_result8, FFTW_FORWARD, FFTW_ESTIMATE);
/*------------------------------------------------------*/
#else
for (i = 0; i < 8; i++) {
if ((data[i] = (MKL_Complex8 *) mkl_malloc(NPOINTS *
(size_t)sizeof (MKL_Complex8), 64)) == NULL) {
exit(0);
}
status = DftiCreateDescriptor(&hand[i],
DFTI_SINGLE,
DFTI_COMPLEX,
1,
(MKL_LONG) NPOINTS);
if (0 != status) {
printf(" ERROR, status = %li\n", status);
exit(0);
}
status = DftiCommitDescriptor(hand[i]);
if (0 != status) {
printf(" %d ERROR, status = %li\n", __LINE__, status);
exit(0);
}
}
#endif
// Debut boucle
for (i = 0; i < NPOINTS; i++) {
gene_bruit_rayleigh_scalaire(param, scalar_real + i, scalar_imag + i);
// scalar_real[i] = cos((2 * M_PI * i * f_0) / (f_num));
//scalar_imag[i] = 0;
}
for (j = 0; j < 8; j++) {
dataCour = data[j];
for (i = 0; i < NPOINTS; i++) {
dataCour[i].real = scalar_real[i];
dataCour[i].imag = scalar_imag[i];
}
#if 0
data2[i][0] = scalar_real[i];
data2[i][1] = scalar_imag[i];
data3[i][0] = scalar_real[i];
data3[i][1] = scalar_imag[i];
data4[i][0] = scalar_real[i];
data4[i][1] = scalar_imag[i];
data5[i][0] = scalar_real[i];
data5[i][1] = scalar_imag[i];
data6[i][0] = scalar_real[i];
data6[i][1] = scalar_imag[i];
data7[i][0] = scalar_real[i];
data7[i][1] = scalar_imag[i];
data8[i][0] = scalar_real[i];
data8[i][1] = scalar_imag[i];
#endif
}
/*
for (i = 0 ; i<NPOINTS ; i++)
{
fprintf(fichier1,"%20.15e\n",data[i][0]);
fprintf(fichier2,"%20.15e\n",data[i][1]);
}
*/
// Fin remplissage des talbeaux
// Debut du chrono
status2 = clock_gettime(clock_id, &tpdeb);
if (status2 < 0) fprintf(stderr, "Erreur clock_gettime (f:%s n:%d)\n", __FILE__, __LINE__);
if (status2 < 0) printf("Erreur CLOCKGETIME");
/*----------- Calcul de la FFT----------*/
#pragma omp parallel num_threads(NBCORES) default(shared) private(j)
#ifndef MKL_LIB
{
#pragma omp sections
{
// CPU #1
#pragma omp section
{
for (j = 0; j < NFFT / 8; j++) {
fftwf_execute(plan_forward);
}
}
#pragma omp section
{
for (j = NFFT / 8; j < NFFT / 4; j++) {
fftwf_execute(plan_forward2);
}
}
#pragma omp section
{
for (j = NFFT / 4; j < (3 * NFFT / 8); j++) {
fftwf_execute(plan_forward3);
}
}
#pragma omp section
{
for (j = (3 * NFFT / 8); j < NFFT / 2; j++) {
fftwf_execute(plan_forward4);
}
}
// CPU #1
#pragma omp section
{
for (j = NFFT / 2; j < (5 * NFFT / 8); j++) {
fftwf_execute(plan_forward5);
}
}
#pragma omp section
{
for (j = (5 * NFFT / 8); j < (3 * NFFT / 4); j++) {
fftwf_execute(plan_forward6);
}
}
#pragma omp section
{
for (j = (6 * NFFT / 8); j < (7 * NFFT / 8); j++) {
fftwf_execute(plan_forward7);
}
}
#pragma omp section
{
for (j = (7 * NFFT / 8); j < NFFT; j++) {
fftwf_execute(plan_forward8);
}
}
}
}
/*--------------------------------------*/
#else
#if 0
for (j = 0; j < NFFT; j++) {
status = DftiComputeForward(hand, data);
if (0 != status) {
printf(" %d ERROR, status = %li\n", __LINE__, status);
exit(0);
}
}
#endif
#pragma omp sections
{
// CPU #1
#pragma omp section
{
int k = 0;
for (j = 0; j < NFFT / 8; j++) {
status = DftiComputeForward(hand[k], data[k]);
if (0 != status) {
printf(" %d ERROR, status = %li\n", __LINE__, status);
exit(0);
}
}
}
#pragma omp section
{
int k = 1;
for (j = NFFT / 8; j < NFFT / 4; j++) {
status = DftiComputeForward(hand[k], data[k]);
if (0 != status) {
printf(" %d ERROR, status = %li\n", __LINE__, status);
exit(0);
}
}
}
#pragma omp section
{
int k = 2;
for (j = NFFT / 4; j < (3 * NFFT / 8); j++) {
status = DftiComputeForward(hand[k], data[k]);
if (0 != status) {
printf(" %d ERROR, status = %li\n", __LINE__, status);
exit(0);
}
}
}
#pragma omp section
{
int k = 3;
for (j = (3 * NFFT / 8); j < NFFT / 2; j++) {
status = DftiComputeForward(hand[k], data[k]);
if (0 != status) {
printf(" %d ERROR, status = %li\n", __LINE__, status);
exit(0);
}
}
}
// CPU #1
#pragma omp section
{
int k = 4;
for (j = NFFT / 2; j < (5 * NFFT / 8); j++) {
status = DftiComputeForward(hand[k], data[k]);
if (0 != status) {
printf(" %d ERROR, status = %li\n", __LINE__, status);
exit(0);
}
}
}
#pragma omp section
{
int k = 5;
for (j = (5 * NFFT / 8); j < (3 * NFFT / 4); j++) {
status = DftiComputeForward(hand[k], data[k]);
if (0 != status) {
printf(" %d ERROR, status = %li\n", __LINE__, status);
exit(0);
}
}
}
#pragma omp section
{
int k = 6;
for (j = (6 * NFFT / 8); j < (7 * NFFT / 8); j++) {
status = DftiComputeForward(hand[k], data[k]);
if (0 != status) {
printf(" %d ERROR, status = %li\n", __LINE__, status);
exit(0);
}
}
}
#pragma omp section
{
int k = 7;
for (j = (7 * NFFT / 8); j < NFFT; j++) {
status = DftiComputeForward(hand[k], data[k]);
if (0 != status) {
printf(" %d ERROR, status = %li\n", __LINE__, status);
exit(0);
}
}
}
}
/*--------------------------------------*/
#endif
status2 = clock_gettime(clock_id, &tpfin);
if (status2 < 0) fprintf(stderr, "Erreur clock_gettime (f:%s n:%d)\n", __FILE__, __LINE__);
if (status2 < 0) printf("Erreur CLOCKGETTIME 2");
dureeloc = (float) (tpfin.tv_sec - tpdeb.tv_sec)+(float) (tpfin.tv_nsec - tpdeb.tv_nsec)*1.e-9;
dureetot = dureetot + dureeloc;
// Affichage du temps
printf("Temps pour %d FFT de %d points complexes = %f ms \n",NFFT,NPOINTS,(dureeloc*1000));
printf("Temps CPU sans transfert (timeur GPU) = %f s \n",dureeloc);
mflops=NFFT*(5*NPOINTS*(log10(NPOINTS)/log10(2)))/dureeloc;
printf("PUISSANCE DE CALCUL = %f Gflops \n",mflops/1e9);
fprintf(fichier1,"%20.15f\n",mflops/1e9);
printf("\n\n");
#ifndef MKL_LIB
fftwf_destroy_plan(plan_forward);
fftwf_destroy_plan(plan_forward2);
fftwf_destroy_plan(plan_forward3);
fftwf_destroy_plan(plan_forward4); // CPU1
fftwf_free(data);
fftwf_free(data2);
fftwf_free(data3);
fftwf_free(data4);
fftwf_free(fft_result);
fftwf_free(fft_result2);
fftwf_free(fft_result3);
fftwf_free(fft_result4);
fftwf_destroy_plan(plan_forward5);
fftwf_destroy_plan(plan_forward6);
fftwf_destroy_plan(plan_forward7);
fftwf_destroy_plan(plan_forward8); // CPU2
fftwf_free(data5);
fftwf_free(data6);
fftwf_free(data7);
fftwf_free(data8);
fftwf_free(fft_result5);
fftwf_free(fft_result6);
fftwf_free(fft_result7);
fftwf_free(fft_result8);
#else
for (j = 0; j < 8; j++) {
if (hand[j])
DftiFreeDescriptor(&hand[j]);
if (data[j])
mkl_free(data[j]);
}
#endif
free(scalar_real);
free(scalar_imag);
}
fclose(fichier1);
return 0;
}
|
Layer_Linear.h
|
/*
* Layers.h
*
* Created by Guido Novati on 29.10.18.
* Copyright 2018 ETH Zurich. All rights reserved.
*
*/
#pragma once
#include "Layers.h"
template<int nOutputs, int nInputs>
struct LinearLayer: public Layer
{
Params* allocate_params() const override {
return new Params(nInputs*nOutputs, nOutputs);
}
LinearLayer(const int _ID) : Layer(nOutputs, _ID)
{
printf("(%d) Linear Layer of Input:%d Output:%d\n", ID, nInputs, nOutputs);
assert(nOutputs>0 && nInputs>0);
}
void forward(const std::vector<Activation*>& act,
const std::vector<Params*>& param) const override
{
const int batchSize = act[ID]->batchSize;
const Real*const inputs = act[ID-1]->output; //size is batchSize * nInputs
const Real*const weight = param[ID]->weights; //size is nInputs * nOutputs
const Real*const bias = param[ID]->biases; //size is nOutputs
Real*const output = act[ID]->output; //size is batchSize * nOutputs
// TO CHECK: TODO : reset layer's workspace and add the bias
#pragma omp parallel for schedule(static)
for(int b=0; b<batchSize; b++)
for(int n=0; n<nOutputs; n++) output[n + b*nOutputs] = bias[n];
// TO CHECK: TODO : perform the forward step with gemm
gemm(CblasRowMajor, CblasNoTrans, CblasNoTrans,
batchSize, nOutputs, nInputs,
(Real)1.0, inputs, nInputs,
weight, nOutputs,
(Real)1.0, output, nOutputs);
}
void bckward(const std::vector<Activation*>& act,
const std::vector<Params*>& param,
const std::vector<Params*>& grad) const override
{
// At this point, act[ID]->dError_dOutput contins derivative of error
// with respect to the outputs of the network.
const Real* const deltas = act[ID]->dError_dOutput;
const Real* const inputs = act[ID-1]->output;
const Real* const weight = param[ID]->weights;
const int batchSize = act[ID]->batchSize;
// TO CHECK: TODO: Implement BackProp to compute bias gradient:
{
// This array will contain dError / dBias, has size nOutputs
Real* const grad_B = grad[ID]->biases;
std::fill(grad_B, grad_B + nOutputs, 0);
#pragma omp parallel for schedule(static, 64/sizeof(Real))
for(int n=0; n<nOutputs; n++)
for(int b=0; b<batchSize; b++)
grad_B[n] += deltas[n + b*nOutputs]; }
// TO CHECK: TODO: Implement BackProp to compute weight gradient
{
// This array will contain dError / dBias, has size nInputs * nOutputs
Real* const grad_W = grad[ID]->weights;
gemm(CblasRowMajor, CblasTrans, CblasNoTrans,
nInputs, nOutputs, batchSize,
(Real)1.0, inputs, nInputs,
deltas, nOutputs,
(Real)0.0, grad_W, nOutputs);
}
// TO CHECK: TODO: Implement BackProp to compute dEdO of previous layer
{
Real* const errinp = act[ID-1]->dError_dOutput;
gemm(CblasRowMajor, CblasNoTrans, CblasTrans,
batchSize, nInputs, nOutputs,
(Real)1.0, deltas, nOutputs,
weight, nOutputs,
(Real)0.0, errinp, nInputs);
}
}
void init(std::mt19937& gen, const std::vector<Params*>& param) const override
{
assert(param[ID] not_eq nullptr);
// get pointers to layer's weights and bias
Real *const W = param[ID]->weights, *const B = param[ID]->biases;
assert(param[ID]->nWeights == nInputs*size && param[ID]->nBiases == size);
// initialize weights with Xavier initialization
const Real scale = std::sqrt( 6.0 / (nInputs + size) );
std::uniform_real_distribution<Real> dis(-scale, scale);
std::generate( W, W + nInputs*nOutputs, [&]() { return dis( gen ); } );
std::generate( B, B + nOutputs, [&]() { return dis( gen ); } );
}
};
|
stats.c
|
/******************************************************************************
* INCLUDES
*****************************************************************************/
#include "base.h"
#include "stats.h"
#include "sptensor.h"
#include "ftensor.h"
#include "csf.h"
#include "io.h"
#include "reorder.h"
#include "util.h"
#include <limits.h>
#include <math.h>
#include <omp.h>
/******************************************************************************
* PRIVATE FUNCTIONS
*****************************************************************************/
/**
* @brief Output basic statistics about tt to STDOUT.
*
* @param tt The tensor to inspect.
* @param ifname The filename of tt. Can be NULL.
*/
static void p_stats_basic(
sptensor_t const * const tt,
char const * const ifname)
{
printf("Tensor information ---------------------------------------------\n");
printf("FILE=%s\n", ifname);
printf("DIMS=%"SPLATT_PF_IDX, tt->dims[0]);
for(idx_t m=1; m < tt->nmodes; ++m) {
printf("x%"SPLATT_PF_IDX, tt->dims[m]);
}
printf(" NNZ=%"SPLATT_PF_IDX, tt->nnz);
printf(" DENSITY=%e\n" , tt_density(tt));
char * bytestr = bytes_str(tt->nnz * ((sizeof(fidx_t) * tt->nmodes) + sizeof(val_t)));
printf("COORD-STORAGE=%s\n", bytestr);
printf("\n");
free(bytestr);
}
/**
* @brief Compute statistics about a hypergraph partitioning of tt.
*
* @param tt The tensor to inspect.
* @param mode The mode to operate on.
* @param pfname The file containing the partitioning.
*/
static void p_stats_hparts(
sptensor_t * const tt,
idx_t const mode,
char const * const pfname)
{
if(pfname == NULL) {
fprintf(stderr, "SPLATT ERROR: analysis type requires partition file\n");
exit(1);
}
ftensor_t ft;
ften_alloc(&ft, tt, mode, 0);
idx_t const nvtxs = ft.nfibs;
idx_t nhedges = 0;
for(idx_t m=0; m < tt->nmodes; ++m) {
nhedges += tt->dims[m];
}
idx_t nparts = 0;
idx_t * parts = part_read(pfname, nvtxs, &nparts);
idx_t * pptr = NULL;
idx_t * plookup = NULL;
build_pptr(parts, nparts, nvtxs, &pptr, &plookup);
/* get stats on partition sizes */
idx_t minp = tt->nnz;
idx_t maxp = 0;
for(idx_t p=0; p < nparts; ++p) {
idx_t nnz = 0;
for(idx_t f=pptr[p]; f < pptr[p+1]; ++f) {
idx_t const findex = plookup[f];
nnz += ft.fptr[findex+1] - ft.fptr[findex];
}
if(nnz < minp) {
minp = nnz;
}
if(nnz > maxp) {
maxp = nnz;
}
}
printf("Partition information ------------------------------------------\n");
printf("FILE=%s\n", pfname);
printf("NVTXS=%"SPLATT_PF_IDX" NHEDGES=%"SPLATT_PF_IDX"\n", nvtxs, nhedges);
printf("NPARTS=%"SPLATT_PF_IDX" LIGHTEST=%"SPLATT_PF_IDX" HEAVIEST="
"%"SPLATT_PF_IDX" AVG=%0.1f\n",
nparts, minp, maxp, (val_t)(ft.nnz) / (val_t) nparts);
printf("\n");
idx_t * unique[MAX_NMODES];
idx_t nunique[MAX_NMODES];
for(idx_t m=0; m < ft.nmodes; ++m) {
unique[m] = (idx_t *) splatt_malloc(ft.dims[ft.dim_perm[m]]
* sizeof(idx_t));
}
/* now track unique ind info for each partition */
for(idx_t p=0; p < nparts; ++p) {
for(idx_t m=0; m < ft.nmodes; ++m) {
memset(unique[m], 0, ft.dims[ft.dim_perm[m]] * sizeof(idx_t));
nunique[m] = 0;
}
idx_t nnz = 0;
idx_t ptr = 0;
for(idx_t f=pptr[p]; f < pptr[p+1]; ++f) {
idx_t const findex = plookup[f];
nnz += ft.fptr[findex+1] - ft.fptr[findex];
/* find slice of findex */
while(ft.sptr[ptr] < findex && ft.sptr[ptr+1] < findex) {
++ptr;
}
if(unique[0][ptr] == 0) {
++nunique[0];
unique[0][ptr] = 1;
}
/* mark unique fids */
if(unique[1][ft.fids[f]] == 0) {
++nunique[1];
unique[1][ft.fids[f]] = 1;
}
for(idx_t j=ft.fptr[findex]; j < ft.fptr[findex+1]; ++j) {
idx_t const jind = ft.inds[j];
/* mark unique inds */
if(unique[2][jind] == 0) {
++nunique[2];
unique[2][jind] = 1;
}
}
}
printf("%"SPLATT_PF_IDX" ", p);
printf("fibs: %"SPLATT_PF_IDX"(%4.1f%%) ", pptr[p+1] - pptr[p],
100. * (val_t)(pptr[p+1]-pptr[p]) / nvtxs);
printf("nnz: %"SPLATT_PF_IDX" (%4.1f%%) ", nnz, 100. * (val_t)nnz / (val_t) tt->nnz);
printf("I: %"SPLATT_PF_IDX" (%4.1f%%) ", nunique[0],
100. * (val_t)nunique[0] / (val_t) ft.dims[mode]);
printf("K: %"SPLATT_PF_IDX" (%4.1f%%) ", nunique[1],
100. * (val_t)nunique[1] / (val_t) ft.dims[ft.dim_perm[1]]);
printf("J: %"SPLATT_PF_IDX" (%4.1f%%)\n", nunique[2],
100. * (val_t)nunique[2] / (val_t) ft.dims[ft.dim_perm[2]]);
}
for(idx_t m=0; m < ft.nmodes; ++m) {
free(unique[m]);
}
free(parts);
free(plookup);
free(pptr);
ften_free(&ft);
}
/******************************************************************************
* PUBLIC FUNCTIONS
*****************************************************************************/
void stats_tt(
sptensor_t * const tt,
char const * const ifname,
splatt_stats_type const type,
idx_t const mode,
char const * const pfile)
{
switch(type) {
case STATS_BASIC:
p_stats_basic(tt, ifname);
break;
case STATS_HPARTS:
p_stats_hparts(tt, mode, pfile);
break;
default:
fprintf(stderr, "SPLATT ERROR: analysis type not implemented\n");
exit(1);
}
}
void stats_csf(
splatt_csf const *ct, int ncopies, double const * const opts)
{
printf("nmodes: %"SPLATT_PF_IDX" nnz: %"SPLATT_PF_IDX"\n", ct->nmodes,
ct->nnz);
printf("dims: %"SPLATT_PF_IDX"", ct->dims[0]);
for(idx_t m=1; m < ct->nmodes; ++m) {
printf("x%"SPLATT_PF_IDX"", ct->dims[m]);
}
for (idx_t k=0; k < ncopies; ++k, ++ct) {
printf(" (%"SPLATT_PF_IDX"", ct->dim_perm[0]);
for(idx_t m=1; m < ct->nmodes; ++m) {
printf("->%"SPLATT_PF_IDX"", ct->dim_perm[m]);
}
printf(")\n");
printf("ntiles: %"SPLATT_PF_IDX" tile dims: %"SPLATT_PF_IDX"", ct->ntiles,
ct->tile_dims[0]);
for(idx_t m=1; m < ct->nmodes; ++m) {
printf("x%"SPLATT_PF_IDX"", ct->tile_dims[m]);
}
idx_t empty = 0;
unsigned long long total_width = 0;
int max_width = 0;
idx_t total_nslices = 0;
idx_t total_nfibers = 0;
idx_t min_slice_nnz = INT_MAX;
idx_t max_slice_nnz = 0;
double sq_sum_slice_nnz = 0;
idx_t min_fiber_nnz = INT_MAX;
idx_t max_fiber_nnz = 0;
double sq_sum_fiber_nnz = 0;
#pragma omp parallel for if (ct->ntiles > 1) schedule(dynamic, 1) reduction(min:min_slice_nnz,min_fiber_nnz) reduction(max:max_slice_nnz,max_fiber_nnz,max_width) reduction(+:sq_sum_slice_nnz,sq_sum_fiber_nnz,total_width,empty,total_nslices,total_nfibers)
for (idx_t t=0; t < ct->ntiles; ++t) {
if(ct->pt[t].vals == NULL) {
++empty;
}
idx_t const * const restrict sptr = ct->pt[t].fptr[ct->nmodes - 3];
idx_t const * const restrict fptr = ct->pt[t].fptr[ct->nmodes - 2];
fidx_t const * const restrict sids = ct->pt[t].fids[ct->nmodes - 3];
fidx_t const * const restrict fids = ct->pt[t].fids[ct->nmodes - 2];
fidx_t const * const restrict inds = ct->pt[t].fids[ct->nmodes - 1];
idx_t const nslices = ct->pt[t].nfibs[ct->nmodes - 3];
total_nslices += nslices;
idx_t nfibers = sptr[nslices];
total_nfibers += nfibers;
#pragma omp parallel for if (ct->ntiles <= 1) reduction(min:min_slice_nnz,min_fiber_nnz) reduction(max:max_slice_nnz,max_fiber_nnz,max_width) reduction(+:sq_sum_slice_nnz,sq_sum_fiber_nnz,total_width)
for(idx_t s=0; s < nslices; ++s) {
idx_t const fid = (sids == NULL) ? s : sids[s];
idx_t slice_nnz = fptr[sptr[s+1]] - fptr[sptr[s]];
min_slice_nnz = SS_MIN(min_slice_nnz, slice_nnz);
max_slice_nnz = SS_MAX(max_slice_nnz, slice_nnz);
sq_sum_slice_nnz += slice_nnz*slice_nnz;
for(idx_t f=sptr[s]; f < sptr[s+1]; ++f) {
idx_t fiber_nnz = fptr[f+1] - fptr[f];
min_fiber_nnz = SS_MIN(min_fiber_nnz, fiber_nnz);
max_fiber_nnz = SS_MAX(max_fiber_nnz, fiber_nnz);
sq_sum_fiber_nnz += fiber_nnz*fiber_nnz;
idx_t min_ind = INT_MAX, max_ind = 0;
for(idx_t jj=fptr[f]; jj < fptr[f+1]; ++jj) {
min_ind = SS_MIN(inds[jj], min_ind);
max_ind = SS_MAX(inds[jj], max_ind);
}
if (fptr[f+1] > fptr[f]) {
int width = max_ind - min_ind;
total_width += width;
max_width = SS_MAX(width, max_width);
}
}
}
} /* for each tile */
printf(" empty: %"SPLATT_PF_IDX" (%0.1f%%)\n", empty,
100. * (double)empty/ (double)ct->ntiles);
if (opts[SPLATT_OPTION_VERBOSITY] > SPLATT_VERBOSITY_LOW) {
printf(" nslices: %"SPLATT_PF_IDX" nfibers: %"SPLATT_PF_IDX"\n", total_nslices, total_nfibers);
double avg_width = (float)total_width/total_nfibers;
printf(" avg_width = %f max_width = %d\n", avg_width, max_width);
double avg_slice_nnz = (double)ct->nnz/total_nslices;
double stddev_slice_nnz = sqrt(sq_sum_slice_nnz/total_nslices - avg_slice_nnz*avg_slice_nnz);
double avg_fiber_nnz = (double)ct->nnz/total_nfibers;
double stddev_fiber_nnz = sqrt(sq_sum_fiber_nnz/total_nfibers - avg_fiber_nnz*avg_fiber_nnz);
printf(" slice_nnz (min,max,avg,stddev): %ld %ld %f %f\n", min_slice_nnz, max_slice_nnz, avg_slice_nnz, stddev_slice_nnz);
printf(" fiber_nnz (min,max,avg,stddev): %ld %ld %f %f\n", min_fiber_nnz, max_fiber_nnz, avg_fiber_nnz, stddev_fiber_nnz);
}
}
}
void cpd_stats(
splatt_csf const * const csf,
idx_t const nfactors,
double const * const opts)
{
/* find total storage */
size_t fbytes = csf_storage(csf, opts);
size_t mbytes = 0;
for(idx_t m=0; m < csf[0].nmodes; ++m) {
mbytes += csf[0].dims[m] * nfactors * sizeof(val_t);
}
/* header */
printf("Factoring "
"------------------------------------------------------\n");
printf("NFACTORS=%"SPLATT_PF_IDX" MAXITS=%"SPLATT_PF_IDX" TOL=%0.1e ",
nfactors,
(idx_t) opts[SPLATT_OPTION_NITER],
opts[SPLATT_OPTION_TOLERANCE]);
printf("THREADS=%"SPLATT_PF_IDX" ", (idx_t) opts[SPLATT_OPTION_NTHREADS]);
printf("\n");
/* CSF allocation */
printf("CSF-ALLOC=");
splatt_csf_type which_csf = (splatt_csf_type)opts[SPLATT_OPTION_CSF_ALLOC];
switch(which_csf) {
case SPLATT_CSF_ONEMODE:
printf("ONEMODE");
break;
case SPLATT_CSF_TWOMODE:
printf("TWOMODE");
break;
case SPLATT_CSF_ALLMODE:
printf("ALLMODE");
break;
}
printf(" ");
/* tiling info */
printf("TILE=");
splatt_tile_type which_tile = (splatt_tile_type)opts[SPLATT_OPTION_TILE];
switch(which_tile) {
case SPLATT_NOTILE:
printf("NO");
break;
case SPLATT_DENSETILE:
printf("DENSE TILE-DEPTH=%"SPLATT_PF_IDX,
(idx_t)opts[SPLATT_OPTION_TILEDEPTH]);
break;
case SPLATT_SYNCTILE:
printf("SYNC");
break;
case SPLATT_COOPTILE:
printf("COOP");
break;
}
/* synchronization method */
if(which_csf != SPLATT_CSF_ALLMODE) {
printf(" SYNC-TYPE=");
splatt_sync_type sync_type = (splatt_sync_type)opts[SPLATT_OPTION_SYNCHRONIZATION];
switch(sync_type) {
case SPLATT_SYNC_OMP_LOCK:
printf("OMP");
break;
case SPLATT_SYNC_TTAS:
printf("TTAS");
break;
case SPLATT_SYNC_RTM:
printf("RTM");
break;
case SPLATT_SYNC_CAS:
printf("CAS");
break;
case SPLATT_SYNC_NOSYNC:
printf("NOSYNC");
break;
}
printf(" PRIV_THRE=%g", opts[SPLATT_OPTION_PRIVATIZATION_THREASHOLD]);
}
printf("\n");
char * fstorage = bytes_str(fbytes);
char * mstorage = bytes_str(mbytes);
printf("CSF-STORAGE=%s FACTOR-STORAGE=%s", fstorage, mstorage);
free(fstorage);
free(mstorage);
printf("\n\n");
}
#ifdef SPLATT_USE_MPI
void mpi_cpd_stats(
splatt_csf const * const csf,
idx_t const nfactors,
double const * const opts,
rank_info * const rinfo)
{
/* find total storage */
unsigned long fbytes = csf_storage(csf, opts);
unsigned long mbytes = 0;
for(idx_t m=0; m < csf[0].nmodes; ++m) {
mbytes += csf[0].dims[m] * nfactors * sizeof(val_t);
}
/* get storage across all nodes */
if(rinfo->rank == 0) {
MPI_Reduce(MPI_IN_PLACE, &fbytes, 1, MPI_UNSIGNED_LONG, MPI_SUM, 0,
rinfo->comm_3d);
MPI_Reduce(MPI_IN_PLACE, &mbytes, 1, MPI_UNSIGNED_LONG, MPI_SUM, 0,
rinfo->comm_3d);
} else {
MPI_Reduce(&fbytes, NULL, 1, MPI_UNSIGNED_LONG, MPI_SUM, 0, rinfo->comm_3d);
MPI_Reduce(&mbytes, NULL, 1, MPI_UNSIGNED_LONG, MPI_SUM, 0, rinfo->comm_3d);
}
/* only master rank prints from here */
if(rinfo->rank != 0) {
return;
}
/* header */
printf("Factoring "
"------------------------------------------------------\n");
printf("NFACTORS=%"SPLATT_PF_IDX" MAXITS=%"SPLATT_PF_IDX" TOL=%0.1e ",
nfactors,
(idx_t) opts[SPLATT_OPTION_NITER],
opts[SPLATT_OPTION_TOLERANCE]);
printf("RANKS=%d THREADS=%"SPLATT_PF_IDX" ", rinfo->npes,
(idx_t) opts[SPLATT_OPTION_NTHREADS]);
printf("\n");
/* CSF allocation */
printf("CSF-ALLOC=");
splatt_csf_type which_csf = (splatt_csf_type)opts[SPLATT_OPTION_CSF_ALLOC];
switch(which_csf) {
case SPLATT_CSF_ONEMODE:
printf("ONEMODE");
break;
case SPLATT_CSF_TWOMODE:
printf("TWOMODE");
break;
case SPLATT_CSF_ALLMODE:
printf("ALLMODE");
break;
}
printf(" ");
/* tiling info */
printf("TILE=");
splatt_tile_type which_tile = (splatt_tile_type)opts[SPLATT_OPTION_TILE];
switch(which_tile) {
case SPLATT_NOTILE:
printf("NO");
break;
case SPLATT_DENSETILE:
printf("DENSE TILE-DEPTH=%"SPLATT_PF_IDX,
(idx_t)opts[SPLATT_OPTION_TILEDEPTH]);
break;
case SPLATT_SYNCTILE:
printf("SYNC");
break;
case SPLATT_COOPTILE:
printf("COOP");
break;
}
printf("\n");
char * fstorage = bytes_str(fbytes);
char * mstorage = bytes_str(mbytes);
printf("CSF-STORAGE=%s FACTOR-STORAGE=%s", fstorage, mstorage);
free(fstorage);
free(mstorage);
printf("\n\n");
}
void mpi_global_stats(
sptensor_t * const tt,
rank_info * const rinfo,
char const * const ifname)
{
idx_t * tmpdims = tt->dims;
idx_t tmpnnz = tt->nnz;
tt->dims = rinfo->global_dims;
tt->nnz = rinfo->global_nnz;
/* print stats */
stats_tt(tt, ifname, STATS_BASIC, 0, NULL);
/* restore local stats */
tt->dims = tmpdims;
tt->nnz = tmpnnz;
}
void mpi_rank_stats(
sptensor_t const * const tt,
rank_info const * const rinfo)
{
idx_t totnnz = 0;
idx_t maxnnz = 0;
idx_t totvolume = 0;
idx_t maxvolume = 0;
idx_t volume = 0;
for(idx_t m=0; m < tt->nmodes; ++m) {
/* if a layer has > 1 rank there is a necessary reduction step too */
if(rinfo->decomp != SPLATT_DECOMP_COARSE && rinfo->layer_size[m] > 1) {
volume += 2 * (rinfo->nlocal2nbr[m] + rinfo->nnbr2globs[m]);
} else {
volume += rinfo->nlocal2nbr[m] + rinfo->nnbr2globs[m];
}
}
MPI_Reduce(&volume, &totvolume, 1, SPLATT_MPI_IDX, MPI_SUM, 0, rinfo->comm_3d);
MPI_Reduce(&volume, &maxvolume, 1, SPLATT_MPI_IDX, MPI_MAX, 0, rinfo->comm_3d);
MPI_Reduce(&tt->nnz, &totnnz, 1, SPLATT_MPI_IDX, MPI_SUM, 0, rinfo->comm_3d);
MPI_Reduce(&tt->nnz, &maxnnz, 1, SPLATT_MPI_IDX, MPI_MAX, 0, rinfo->comm_3d);
if(rinfo->rank == 0) {
printf("MPI information ------------------------------------------------\n");
switch(rinfo->decomp) {
case SPLATT_DECOMP_COARSE:
printf("DISTRIBUTION=COARSE\n");
break;
case SPLATT_DECOMP_MEDIUM:
printf("DISTRIBUTION=MEDIUM ");
printf("DIMS=%d", rinfo->dims_3d[0]);
for(idx_t m=1; m < rinfo->nmodes; ++m) {
printf("x%d", rinfo->dims_3d[m]);
}
printf("\n");
break;
case SPLATT_DECOMP_FINE:
printf("DISTRIBUTION=FINE\n");
break;
}
idx_t avgvolume = totvolume / rinfo->npes;
idx_t const avgnnz = totnnz / rinfo->npes;
double nnzimbalance = 100. * ((double)(maxnnz - avgnnz) / (double)maxnnz);
double volimbalance = 100. * ((double)(maxvolume - avgvolume) /
SS_MAX((double)maxvolume, 1));
printf("AVG NNZ=%"SPLATT_PF_IDX"\nMAX NNZ=%"SPLATT_PF_IDX" (%0.2f%% diff)\n",
avgnnz, maxnnz, nnzimbalance);
printf("AVG COMMUNICATION VOL=%"SPLATT_PF_IDX"\nMAX COMMUNICATION VOL=%"SPLATT_PF_IDX" "
"(%0.2f%% diff)\n", avgvolume, maxvolume, volimbalance);
printf("\n");
}
}
#endif
|
GB_unaryop__abs_int16_fp32.c
|
//------------------------------------------------------------------------------
// GB_unaryop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved.
// http://suitesparse.com See GraphBLAS/Doc/License.txt for license.
//------------------------------------------------------------------------------
// If this file is in the Generated/ folder, do not edit it (auto-generated).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_iterator.h"
#include "GB_unaryop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB_unop__abs_int16_fp32
// op(A') function: GB_tran__abs_int16_fp32
// C type: int16_t
// A type: float
// cast: int16_t cij ; GB_CAST_SIGNED(cij,aij,16)
// unaryop: cij = GB_IABS (aij)
#define GB_ATYPE \
float
#define GB_CTYPE \
int16_t
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
float aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = GB_IABS (x) ;
// casting
#define GB_CASTING(z, x) \
int16_t z ; GB_CAST_SIGNED(z,x,16) ;
// cij = op (cast (aij))
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
GB_GETA (aij, Ax, pA) ; \
/* Cx [pC] = op (cast (aij)) */ \
GB_CASTING (x, aij) ; \
GB_OP (GB_CX (pC), x) ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_ABS || GxB_NO_INT16 || GxB_NO_FP32)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop__abs_int16_fp32
(
int16_t *restrict Cx,
const float *restrict Ax,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (int64_t p = 0 ; p < anz ; p++)
{
GB_CAST_OP (p, p) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_tran__abs_int16_fp32
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t **Rowcounts,
GBI_single_iterator Iter,
const int64_t *restrict A_slice,
int naslice
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#define GB_PHASE_2_OF_2
#include "GB_unaryop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
duplex.c
|
/*
* compute the duplex structure of two RNA strands,
* allowing only inter-strand base pairs.
* see cofold() for computing hybrid structures without
* restriction.
*
* Ivo Hofacker
* Vienna RNA package
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <ctype.h>
#include <string.h>
#include "ViennaRNA/utils/basic.h"
#include "ViennaRNA/params/default.h"
#include "ViennaRNA/fold_vars.h"
#include "ViennaRNA/fold.h"
#include "ViennaRNA/pair_mat.h"
#include "ViennaRNA/params/basic.h"
#include "ViennaRNA/alifold.h"
#include "ViennaRNA/subopt.h"
#include "ViennaRNA/loops/all.h"
#include "ViennaRNA/duplex.h"
#ifdef _OPENMP
#include <omp.h>
#endif
#define STACK_BULGE1 1 /* stacking energies for bulges of size 1 */
#define NEW_NINIO 1 /* new asymetry penalty */
#define MAXSECTORS 500 /* dimension for a backtrack array */
#define LOCALITY 0. /* locality parameter for base-pairs */
#define UNIT 100
#define MINPSCORE -2 * UNIT
#define NONE -10000 /* score for forbidden pairs */
/*
#################################
# GLOBAL VARIABLES #
#################################
*/
/*
#################################
# PRIVATE VARIABLES #
#################################
*/
PRIVATE vrna_param_t *P = NULL;
PRIVATE int **c = NULL; /* energy array, given that i-j pair */
PRIVATE short *S1 = NULL, *SS1 = NULL, *S2 = NULL, *SS2 = NULL;
PRIVATE int n1, n2; /* sequence lengths */
#ifdef _OPENMP
/* NOTE: all variables are assumed to be uninitialized if they are declared as threadprivate
*/
#pragma omp threadprivate(P, c, S1, SS1, S2, SS2, n1, n2)
#endif
/*
#################################
# PRIVATE FUNCTION DECLARATIONS #
#################################
*/
PRIVATE duplexT
duplexfold_cu(const char *s1,
const char *s2,
int clean_up);
PRIVATE duplexT
aliduplexfold_cu(const char *s1[],
const char *s2[],
int clean_up);
PRIVATE char *
backtrack(int i,
int j);
PRIVATE char *
alibacktrack(int i,
int j,
const short **S1,
const short **S2);
PRIVATE int
compare(const void *sub1,
const void *sub2);
PRIVATE int
covscore(const int *types,
int n_seq);
/*
#################################
# BEGIN OF FUNCTION DEFINITIONS #
#################################
*/
PUBLIC duplexT
duplexfold(const char *s1,
const char *s2)
{
return duplexfold_cu(s1, s2, 1);
}
PRIVATE duplexT
duplexfold_cu(const char *s1,
const char *s2,
int clean_up)
{
int i, j, Emin = INF, i_min = 0, j_min = 0;
char *struc;
duplexT mfe;
vrna_md_t md;
n1 = (int)strlen(s1);
n2 = (int)strlen(s2);
set_model_details(&md);
if ((!P) || (fabs(P->temperature - temperature) > 1e-6)) {
if (P)
free(P);
P = vrna_params(&md);
make_pair_matrix();
}
c = (int **)vrna_alloc(sizeof(int *) * (n1 + 1));
for (i = 1; i <= n1; i++)
c[i] = (int *)vrna_alloc(sizeof(int) * (n2 + 1));
S1 = encode_sequence(s1, 0);
S2 = encode_sequence(s2, 0);
SS1 = encode_sequence(s1, 1);
SS2 = encode_sequence(s2, 1);
for (i = 1; i <= n1; i++) {
for (j = n2; j > 0; j--) {
int type, type2, E, k, l;
type = pair[S1[i]][S2[j]];
c[i][j] = type ? P->DuplexInit : INF;
if (!type)
continue;
c[i][j] += vrna_E_ext_stem(type, (i > 1) ? SS1[i - 1] : -1, (j < n2) ? SS2[j + 1] : -1, P);
for (k = i - 1; k > 0 && k > i - MAXLOOP - 2; k--) {
for (l = j + 1; l <= n2; l++) {
if (i - k + l - j - 2 > MAXLOOP)
break;
type2 = pair[S1[k]][S2[l]];
if (!type2)
continue;
E = E_IntLoop(i - k - 1, l - j - 1, type2, rtype[type],
SS1[k + 1], SS2[l - 1], SS1[i - 1], SS2[j + 1], P);
c[i][j] = MIN2(c[i][j], c[k][l] + E);
}
}
E = c[i][j];
E += vrna_E_ext_stem(rtype[type], (j > 1) ? SS2[j - 1] : -1, (i < n1) ? SS1[i + 1] : -1, P);
if (E < Emin) {
Emin = E;
i_min = i;
j_min = j;
}
}
}
struc = backtrack(i_min, j_min);
if (i_min < n1)
i_min++;
if (j_min > 1)
j_min--;
mfe.i = i_min;
mfe.j = j_min;
mfe.energy = (float)Emin / 100.;
mfe.structure = struc;
if (clean_up) {
for (i = 1; i <= n1; i++)
free(c[i]);
free(c);
free(S1);
free(S2);
free(SS1);
free(SS2);
}
return mfe;
}
PUBLIC duplexT *
duplex_subopt(const char *s1,
const char *s2,
int delta,
int w)
{
int i, j, n1, n2, thresh, E, n_subopt = 0, n_max;
char *struc;
duplexT mfe;
duplexT *subopt;
n_max = 16;
subopt = (duplexT *)vrna_alloc(n_max * sizeof(duplexT));
mfe = duplexfold_cu(s1, s2, 0);
free(mfe.structure);
thresh = (int)mfe.energy * 100 + 0.1 + delta;
n1 = strlen(s1);
n2 = strlen(s2);
for (i = n1; i > 0; i--) {
for (j = 1; j <= n2; j++) {
int type, ii, jj, Ed;
type = pair[S2[j]][S1[i]];
if (!type)
continue;
E = Ed = c[i][j];
Ed += vrna_E_ext_stem(type, (j > 1) ? SS2[j - 1] : -1, (i < n1) ? SS1[i + 1] : -1, P);
if (Ed > thresh)
continue;
/* too keep output small, remove hits that are dominated by a
* better one close (w) by. For simplicity we do test without
* adding dangles, which is slightly inaccurate.
*/
for (ii = MAX2(i - w, 1); (ii <= MIN2(i + w, n1)) && type; ii++) {
for (jj = MAX2(j - w, 1); jj <= MIN2(j + w, n2); jj++)
if (c[ii][jj] < E) {
type = 0;
break;
}
}
if (!type)
continue;
struc = backtrack(i, j);
vrna_message_info(stderr, "%d %d %d", i, j, E);
if (n_subopt + 1 >= n_max) {
n_max *= 2;
subopt = (duplexT *)vrna_realloc(subopt, n_max * sizeof(duplexT));
}
subopt[n_subopt].i = MIN2(i + 1, n1);
subopt[n_subopt].j = MAX2(j - 1, 1);
subopt[n_subopt].energy = Ed * 0.01;
subopt[n_subopt++].structure = struc;
}
}
/* free all static globals */
for (i = 1; i <= n1; i++)
free(c[i]);
free(c);
free(S1);
free(S2);
free(SS1);
free(SS2);
if (subopt_sorted)
qsort(subopt, n_subopt, sizeof(duplexT), compare);
subopt[n_subopt].i = 0;
subopt[n_subopt].j = 0;
subopt[n_subopt].structure = NULL;
return subopt;
}
PRIVATE char *
backtrack(int i,
int j)
{
/* backtrack structure going backwards from i, and forwards from j
* return structure in bracket notation with & as separator */
int k, l, type, type2, E, traced, i0, j0;
char *st1, *st2, *struc;
st1 = (char *)vrna_alloc(sizeof(char) * (n1 + 1));
st2 = (char *)vrna_alloc(sizeof(char) * (n2 + 1));
i0 = MIN2(i + 1, n1);
j0 = MAX2(j - 1, 1);
while (i > 0 && j <= n2) {
E = c[i][j];
traced = 0;
st1[i - 1] = '(';
st2[j - 1] = ')';
type = pair[S1[i]][S2[j]];
if (!type)
vrna_message_error("backtrack failed in fold duplex");
for (k = i - 1; k > 0 && k > i - MAXLOOP - 2; k--) {
for (l = j + 1; l <= n2; l++) {
int LE;
if (i - k + l - j - 2 > MAXLOOP)
break;
type2 = pair[S1[k]][S2[l]];
if (!type2)
continue;
LE = E_IntLoop(i - k - 1, l - j - 1, type2, rtype[type],
SS1[k + 1], SS2[l - 1], SS1[i - 1], SS2[j + 1], P);
if (E == c[k][l] + LE) {
traced = 1;
i = k;
j = l;
break;
}
}
if (traced)
break;
}
if (!traced) {
E -= vrna_E_ext_stem(type, (i > 1) ? SS1[i - 1] : -1, (j < n2) ? SS2[j + 1] : -1, P);
if (E != P->DuplexInit)
vrna_message_error("backtrack failed in fold duplex");
else
break;
}
}
if (i > 1)
i--;
if (j < n2)
j++;
struc = (char *)vrna_alloc(i0 - i + 1 + j - j0 + 1 + 2);
for (k = MAX2(i, 1); k <= i0; k++)
if (!st1[k - 1])
st1[k - 1] = '.';
for (k = j0; k <= j; k++)
if (!st2[k - 1])
st2[k - 1] = '.';
strcpy(struc, st1 + MAX2(i - 1, 0));
strcat(struc, "&");
strcat(struc, st2 + j0 - 1);
/* printf("%s %3d,%-3d : %3d,%-3d\n", struc, i,i0,j0,j); */
free(st1);
free(st2);
return struc;
}
/*------------------------------------------------------------------------*/
PRIVATE int
compare(const void *sub1,
const void *sub2)
{
int d;
if (((duplexT *)sub1)->energy > ((duplexT *)sub2)->energy)
return 1;
if (((duplexT *)sub1)->energy < ((duplexT *)sub2)->energy)
return -1;
d = ((duplexT *)sub1)->i - ((duplexT *)sub2)->i;
if (d != 0)
return d;
return ((duplexT *)sub1)->j - ((duplexT *)sub2)->j;
}
/*---------------------------------------------------------------------------*/
PUBLIC duplexT
aliduplexfold(const char *s1[],
const char *s2[])
{
return aliduplexfold_cu(s1, s2, 1);
}
PRIVATE duplexT
aliduplexfold_cu(const char *s1[],
const char *s2[],
int clean_up)
{
int i, j, s, n_seq, Emin = INF, i_min = 0, j_min = 0;
char *struc;
duplexT mfe;
short **S1, **S2;
int *type;
vrna_md_t md;
n1 = (int)strlen(s1[0]);
n2 = (int)strlen(s2[0]);
for (s = 0; s1[s] != NULL; s++);
n_seq = s;
for (s = 0; s2[s] != NULL; s++);
if (n_seq != s)
vrna_message_error("unequal number of sequences in aliduplexfold()\n");
set_model_details(&md);
if ((!P) || (fabs(P->temperature - temperature) > 1e-6)) {
if (P)
free(P);
P = vrna_params(&md);
make_pair_matrix();
}
c = (int **)vrna_alloc(sizeof(int *) * (n1 + 1));
for (i = 1; i <= n1; i++)
c[i] = (int *)vrna_alloc(sizeof(int) * (n2 + 1));
S1 = (short **)vrna_alloc((n_seq + 1) * sizeof(short *));
S2 = (short **)vrna_alloc((n_seq + 1) * sizeof(short *));
for (s = 0; s < n_seq; s++) {
if (strlen(s1[s]) != n1)
vrna_message_error("uneqal seqence lengths");
if (strlen(s2[s]) != n2)
vrna_message_error("uneqal seqence lengths");
S1[s] = encode_sequence(s1[s], 0);
S2[s] = encode_sequence(s2[s], 0);
}
type = (int *)vrna_alloc(n_seq * sizeof(int));
for (i = 1; i <= n1; i++) {
for (j = n2; j > 0; j--) {
int k, l, E, psc;
for (s = 0; s < n_seq; s++)
type[s] = pair[S1[s][i]][S2[s][j]];
psc = covscore(type, n_seq);
for (s = 0; s < n_seq; s++)
if (type[s] == 0)
type[s] = 7;
c[i][j] = (psc >= MINPSCORE) ? (n_seq * P->DuplexInit) : INF;
if (psc < MINPSCORE)
continue;
for (s = 0; s < n_seq; s++)
c[i][j] += vrna_E_ext_stem(type[s],
(i > 1) ? S1[s][i - 1] : -1,
(j < n2) ? S2[s][j + 1] : -1,
P);
for (k = i - 1; k > 0 && k > i - MAXLOOP - 2; k--) {
for (l = j + 1; l <= n2; l++) {
int type2;
if (i - k + l - j - 2 > MAXLOOP)
break;
if (c[k][l] > INF / 2)
continue;
for (E = s = 0; s < n_seq; s++) {
type2 = pair[S1[s][k]][S2[s][l]];
if (type2 == 0)
type2 = 7;
E += E_IntLoop(i - k - 1, l - j - 1, type2, rtype[type[s]],
S1[s][k + 1], S2[s][l - 1], S1[s][i - 1], S2[s][j + 1], P);
}
c[i][j] = MIN2(c[i][j], c[k][l] + E);
}
}
c[i][j] -= psc;
E = c[i][j];
for (s = 0; s < n_seq; s++)
E +=
vrna_E_ext_stem(rtype[type[s]],
(j > 1) ? S2[s][j - 1] : -1,
(i < n1) ? S1[s][i + 1] : -1,
P);
if (E < Emin) {
Emin = E;
i_min = i;
j_min = j;
}
}
}
struc = alibacktrack(i_min, j_min, (const short **)S1, (const short **)S2);
if (i_min < n1)
i_min++;
if (j_min > 1)
j_min--;
mfe.i = i_min;
mfe.j = j_min;
mfe.energy = (float)(Emin / (100. * n_seq));
mfe.structure = struc;
if (clean_up) {
for (i = 1; i <= n1; i++)
free(c[i]);
free(c);
}
for (s = 0; s < n_seq; s++) {
free(S1[s]);
free(S2[s]);
}
free(S1);
free(S2);
free(type);
return mfe;
}
PUBLIC duplexT *
aliduplex_subopt(const char *s1[],
const char *s2[],
int delta,
int w)
{
int i, j, n1, n2, thresh, E, n_subopt = 0, n_max, s, n_seq, *type;
char *struc;
duplexT mfe;
duplexT *subopt;
short **S1, **S2;
n_max = 16;
subopt = (duplexT *)vrna_alloc(n_max * sizeof(duplexT));
mfe = aliduplexfold_cu(s1, s2, 0);
free(mfe.structure);
for (s = 0; s1[s] != NULL; s++);
n_seq = s;
thresh = (int)((mfe.energy * 100. + delta) * n_seq + 0.1);
n1 = strlen(s1[0]);
n2 = strlen(s2[0]);
S1 = (short **)vrna_alloc((n_seq + 1) * sizeof(short *));
S2 = (short **)vrna_alloc((n_seq + 1) * sizeof(short *));
for (s = 0; s < n_seq; s++) {
if (strlen(s1[s]) != n1)
vrna_message_error("uneqal seqence lengths");
if (strlen(s2[s]) != n2)
vrna_message_error("uneqal seqence lengths");
S1[s] = encode_sequence(s1[s], 0);
S2[s] = encode_sequence(s2[s], 0);
}
type = (int *)vrna_alloc(n_seq * sizeof(int));
for (i = n1; i > 0; i--) {
for (j = 1; j <= n2; j++) {
int ii, jj, skip, Ed, psc;
for (s = 0; s < n_seq; s++)
type[s] = pair[S2[s][j]][S1[s][i]];
psc = covscore(type, n_seq);
for (s = 0; s < n_seq; s++)
if (type[s] == 0)
type[s] = 7;
if (psc < MINPSCORE)
continue;
E = Ed = c[i][j];
for (s = 0; s < n_seq; s++)
Ed +=
vrna_E_ext_stem(type[s], (j > 1) ? S2[s][j - 1] : -1, (i < n1) ? S1[s][i + 1] : -1, P);
if (Ed > thresh)
continue;
/* too keep output small, skip hits that are dominated by a
* better one close (w) by. For simplicity we don't take dangels
* into account here, thus the heuristic is somewhat inaccurate.
*/
for (skip = 0, ii = MAX2(i - w, 1); (ii <= MIN2(i + w, n1)) && type; ii++) {
for (jj = MAX2(j - w, 1); jj <= MIN2(j + w, n2); jj++)
if (c[ii][jj] < E) {
skip = 1;
break;
}
}
if (skip)
continue;
struc = alibacktrack(i, j, (const short **)S1, (const short **)S2);
vrna_message_info(stderr, "%d %d %d", i, j, E);
if (n_subopt + 1 >= n_max) {
n_max *= 2;
subopt = (duplexT *)vrna_realloc(subopt, n_max * sizeof(duplexT));
}
subopt[n_subopt].i = MIN2(i + 1, n1);
subopt[n_subopt].j = MAX2(j - 1, 1);
subopt[n_subopt].energy = Ed * 0.01 / n_seq;
subopt[n_subopt++].structure = struc;
}
}
for (i = 1; i <= n1; i++)
free(c[i]);
free(c);
for (s = 0; s < n_seq; s++) {
free(S1[s]);
free(S2[s]);
}
free(S1);
free(S2);
free(type);
if (subopt_sorted)
qsort(subopt, n_subopt, sizeof(duplexT), compare);
subopt[n_subopt].i = 0;
subopt[n_subopt].j = 0;
subopt[n_subopt].structure = NULL;
return subopt;
}
PRIVATE char *
alibacktrack(int i,
int j,
const short **S1,
const short **S2)
{
/* backtrack structure going backwards from i, and forwards from j
* return structure in bracket notation with & as separator */
int k, l, *type, type2, E, traced, i0, j0, s, n_seq;
char *st1, *st2, *struc;
n1 = (int)S1[0][0];
n2 = (int)S2[0][0];
for (s = 0; S1[s] != NULL; s++);
n_seq = s;
for (s = 0; S2[s] != NULL; s++);
if (n_seq != s)
vrna_message_error("unequal number of sequences in alibacktrack()\n");
st1 = (char *)vrna_alloc(sizeof(char) * (n1 + 1));
st2 = (char *)vrna_alloc(sizeof(char) * (n2 + 1));
type = (int *)vrna_alloc(n_seq * sizeof(int));
i0 = MIN2(i + 1, n1);
j0 = MAX2(j - 1, 1);
while (i > 0 && j <= n2) {
int psc;
E = c[i][j];
traced = 0;
st1[i - 1] = '(';
st2[j - 1] = ')';
for (s = 0; s < n_seq; s++)
type[s] = pair[S1[s][i]][S2[s][j]];
psc = covscore(type, n_seq);
for (s = 0; s < n_seq; s++)
if (type[s] == 0)
type[s] = 7;
E += psc;
for (k = i - 1; k > 0 && k > i - MAXLOOP - 2; k--) {
for (l = j + 1; l <= n2; l++) {
int LE;
if (i - k + l - j - 2 > MAXLOOP)
break;
if (c[k][l] > INF / 2)
continue;
for (s = LE = 0; s < n_seq; s++) {
type2 = pair[S1[s][k]][S2[s][l]];
if (type2 == 0)
type2 = 7;
LE += E_IntLoop(i - k - 1, l - j - 1, type2, rtype[type[s]],
S1[s][k + 1], S2[s][l - 1], S1[s][i - 1], S2[s][j + 1], P);
}
if (E == c[k][l] + LE) {
traced = 1;
i = k;
j = l;
break;
}
}
if (traced)
break;
}
if (!traced) {
for (s = 0; s < n_seq; s++)
E -= vrna_E_ext_stem(type[s], (i > 1) ? S1[s][i - 1] : -1, (j < n2) ? S2[s][j + 1] : -1, P);
if (E != n_seq * P->DuplexInit)
vrna_message_error("backtrack failed in aliduplex");
else
break;
}
}
if (i > 1)
i--;
if (j < n2)
j++;
struc = (char *)vrna_alloc(i0 - i + 1 + j - j0 + 1 + 2);
for (k = MAX2(i, 1); k <= i0; k++)
if (!st1[k - 1])
st1[k - 1] = '.';
for (k = j0; k <= j; k++)
if (!st2[k - 1])
st2[k - 1] = '.';
strcpy(struc, st1 + MAX2(i - 1, 0));
strcat(struc, "&");
strcat(struc, st2 + j0 - 1);
/* printf("%s %3d,%-3d : %3d,%-3d\n", struc, i,i0,j0,j); */
free(st1);
free(st2);
free(type);
return struc;
}
PRIVATE int
covscore(const int *types,
int n_seq)
{
/*
* calculate co-variance bonus for a pair depending on
* compensatory/consistent mutations and incompatible seqs
* should be 0 for conserved pairs, >0 for good pairs
*/
int k, l, s, score, pscore;
int dm[7][7] = { { 0, 0, 0, 0, 0, 0, 0 }, /* hamming distance between pairs */
{ 0, 0, 2, 2, 1, 2, 2 } /* CG */,
{ 0, 2, 0, 1, 2, 2, 2 } /* GC */,
{ 0, 2, 1, 0, 2, 1, 2 } /* GU */,
{ 0, 1, 2, 2, 0, 2, 1 } /* UG */,
{ 0, 2, 2, 1, 2, 0, 2 } /* AU */,
{ 0, 2, 2, 2, 1, 2, 0 } /* UA */ };
int pfreq[8] = {
0, 0, 0, 0, 0, 0, 0, 0
};
for (s = 0; s < n_seq; s++)
pfreq[types[s]]++;
if (pfreq[0] * 2 > n_seq)
return NONE;
for (k = 1, score = 0; k <= 6; k++) /* ignore pairtype 7 (gap-gap) */
for (l = k + 1; l <= 6; l++)
/*
* scores for replacements between pairtypes
* consistent or compensatory mutations score 1 or 2
*/
score += pfreq[k] * pfreq[l] * dm[k][l];
/* counter examples score -1, gap-gap scores -0.25 */
pscore = cv_fact *
((UNIT * score) / n_seq - nc_fact * UNIT * (pfreq[0] + pfreq[7] * 0.25));
return pscore;
}
|
mandelbrot-omp.c
|
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <omp.h>
void mandelbrot(double zreal, double zimag){
int i, niter = 500000, threshold = 4;
double temp, zabs, x = 0, y = 0;
for (i = 0; i < niter; i++){
temp = x;
x = (x*x) - (y*y) + zreal;
y = (2*temp*y) + zimag;
zabs = (x*x) + (y*y);
if (zabs > threshold){
#pragma omp ordered
printf(" ");
return;
}
}
#pragma omp ordered
printf(".");
return;
}
int main(){
int a, b, n = 80, m = 50;
double zreal, zimag;
double zimag_start = -1, zimag_end = 1;
double zreal_start = -2, zreal_end = 1;
double zimag_middle = (fabs(zimag_start) + fabs(zimag_end))/m;
double zreal_middle = (fabs(zreal_start) + fabs(zreal_end))/n;
// start timer
double start_time, end_time;
start_time = omp_get_wtime();
// set number of threads
omp_set_dynamic(0);
omp_set_num_threads(4);
for (a = 0; a <= m; a++){
zimag = zimag_start + zimag_middle*a;
#pragma omp parallel for ordered schedule(dynamic)
for (b = 0; b <= n; b++){
zreal = zreal_start + zreal_middle*b;
mandelbrot(zreal, zimag);
}
printf("\n");
}
// end timer
end_time = omp_get_wtime();
printf("Total execution time: %.2lf\n", end_time - start_time);
return 0;
}
/*
Notes:
- parallelization makes code only slightly faster
- for 8 threads: 2.50s -> 2.34s (-O3)
Output:
.
.....
.....
.....
...
......
.. .............
.. ................. ...
.....................
......................
..........................
..........................
..........................
............................
.............................
. .... .............................
......... .............................
........... ..............................
............ .............................
............ .............................
.. .........................................
.............................................................
.. .........................................
............ .............................
............ .............................
........... ..............................
......... .............................
. .... .............................
.............................
............................
..........................
..........................
..........................
......................
.....................
.. ................. ...
.. .............
......
...
.....
.....
.....
.
*/
|
quantile.c
|
/******************************************************************
* Melissa *
*-----------------------------------------------------------------*
* COPYRIGHT (C) 2017 by INRIA and EDF. ALL RIGHTS RESERVED. *
* *
* This source is covered by the BSD 3-Clause License. *
* Refer to the LICENCE file for further information. *
* *
*-----------------------------------------------------------------*
* Original Contributors: *
* Theophile Terraz, *
* Bruno Raffin, *
* Alejandro Ribes, *
* Bertrand Iooss, *
******************************************************************/
/**
*
* @file quantile.c
* @brief Quantile related functions.
* @author Terraz Théophile
* @date 2017-18-05
*
**/
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <math.h>
#ifdef BUILD_WITH_OPENMP
#include <omp.h>
#endif // BUILD_WITH_OPENMP
#include "quantile.h"
#include "melissa_utils.h"
/**
*******************************************************************************
*
* @ingroup stats_base
*
* This function initializes a quantile structure.
*
*******************************************************************************
*
* @param[in,out] *quantile
* the quantile structure to initialize
*
* @param[in] vect_size
* size of the quantile vector
*
* @param[in] alpha
* the quantile order
*
*******************************************************************************/
void init_quantile (quantile_t *quantile,
const int vect_size,
const double alpha)
{
quantile->quantile = melissa_calloc (vect_size, sizeof(double));
quantile->increment = 0;
quantile->alpha = alpha;
}
/**
*******************************************************************************
*
* @ingroup stats_base
*
* This function updates the incremental quantile.
*
*******************************************************************************
*
* @param[in,out] *quantile
* input: previously computed iterative quantile,
* output: updated partial quantile
*
* @param[in] nmax
* maximum number of iterations
*
* @param[in] in_vect[]
* input vector of double values
*
* @param[in] vect_size
* size of the input vectors
*
*******************************************************************************/
void increment_quantile (quantile_t *quantile,
const int nmax,
double in_vect[],
const int vect_size)
{
int i;
double temp, gamma;
quantile->increment += 1;
if (quantile->increment > 1)
{
#pragma omp parallel for schedule(static) private(temp)
for (i=0; i<vect_size; i++)
{
gamma = (quantile->increment - 1) * 0.9 / (nmax-1) + 0.1;
if (quantile->quantile[i] >= in_vect[i])
{
temp = 1 - quantile->alpha;
}
else
{
temp = 0 - quantile->alpha;
}
quantile->quantile[i] -= temp/pow(quantile->increment, gamma);
}
}
else
{
//#pragma omp parallel for schedule(static)
// for (i=0; i<vect_size; i++)
// {
// quantile->quantile[i] = in_vect[i];
// }
memcpy (quantile->quantile, in_vect, vect_size * sizeof(double));
}
}
/**
*******************************************************************************
*
* @ingroup save_stats
*
* This function writes an array of quantile structures on disc
*
*******************************************************************************
*
* @param[in] *quantiles
* quantile structures to save, size nb_time_steps
*
* @param[in] vect_size
* size of double vectors
*
* @param[in] nb_time_steps
* number of time_steps of the study
*
* @param[in] nb_quantiles
* number of quantile values
*
* @param[in] f
* file descriptor
*
*******************************************************************************/
void save_quantile(quantile_t **quantiles,
int vect_size,
int nb_time_steps,
int nb_quantiles,
FILE* f)
{
int i, j;
for (i=0; i<nb_time_steps; i++)
{
for (j=0; j<nb_quantiles; j++)
{
fwrite(quantiles[i][j].quantile, sizeof(double), vect_size, f);
fwrite(&quantiles[i][j].increment, sizeof(int), 1, f);
fwrite(&quantiles[i][j].alpha, sizeof(double), 1, f);
}
}
}
/**
*******************************************************************************
*
* @ingroup save_stats
*
* This function reads an array of quantile structures on disc
*
*******************************************************************************
*
* @param[in] *quantiles
* quantile structures to read, size nb_time_steps
*
* @param[in] vect_size
* size of double vectors
*
* @param[in] nb_time_steps
* number of time_steps of the study
*
* @param[in] nb_quantiles
* number of quantile values
*
* @param[in] f
* file descriptor
*
*******************************************************************************/
void read_quantile(quantile_t **quantiles,
int vect_size,
int nb_time_steps,
int nb_quantiles,
FILE* f)
{
int i, j;
for (i=0; i<nb_time_steps; i++)
{
for (j=0; j<nb_quantiles; j++)
{
fread(quantiles[i][j].quantile, sizeof(double), vect_size, f);
fread(&quantiles[i][j].increment, sizeof(int), 1, f);
fread(&quantiles[i][j].alpha, sizeof(double), 1, f);
}
}
}
/**
*******************************************************************************
*
* @ingroup stats_base
*
* This function frees a quantile structure.
*
*******************************************************************************
*
* @param[in,out] *quantile
* the quantile structure to free
*
*******************************************************************************/
void free_quantile (quantile_t *quantile)
{
melissa_free (quantile->quantile);
}
|
GB_binop__band_int32.c
|
//------------------------------------------------------------------------------
// GB_binop: hard-coded functions for each built-in binary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated2/ folder, do not edit it
// (it is auto-generated from Generator/*).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_emult.h"
#include "GB_control.h"
#include "GB_ek_slice.h"
#include "GB_dense.h"
#include "GB_atomics.h"
#include "GB_bitmap_assign_methods.h"
#include "GB_binop__include.h"
// C=binop(A,B) is defined by the following types and operators:
// A+B function (eWiseAdd): GB (_AaddB__band_int32)
// A.*B function (eWiseMult): GB (_AemultB_08__band_int32)
// A.*B function (eWiseMult): GB (_AemultB_02__band_int32)
// A.*B function (eWiseMult): GB (_AemultB_04__band_int32)
// A.*B function (eWiseMult): GB (_AemultB_bitmap__band_int32)
// A*D function (colscale): GB ((none))
// D*A function (rowscale): GB ((none))
// C+=B function (dense accum): GB (_Cdense_accumB__band_int32)
// C+=b function (dense accum): GB (_Cdense_accumb__band_int32)
// C+=A+B function (dense ewise3): GB ((none))
// C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__band_int32)
// C=scalar+B GB (_bind1st__band_int32)
// C=scalar+B' GB (_bind1st_tran__band_int32)
// C=A+scalar GB (_bind2nd__band_int32)
// C=A'+scalar GB (_bind2nd_tran__band_int32)
// C type: int32_t
// A type: int32_t
// A pattern? 0
// B type: int32_t
// B pattern? 0
// BinaryOp: cij = (aij) & (bij)
#define GB_ATYPE \
int32_t
#define GB_BTYPE \
int32_t
#define GB_CTYPE \
int32_t
// true if the types of A and B are identical
#define GB_ATYPE_IS_BTYPE \
1
// true if the types of C and A are identical
#define GB_CTYPE_IS_ATYPE \
1
// true if the types of C and B are identical
#define GB_CTYPE_IS_BTYPE \
1
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA,A_iso) \
int32_t aij = GBX (Ax, pA, A_iso)
// true if values of A are not used
#define GB_A_IS_PATTERN \
0 \
// bij = Bx [pB]
#define GB_GETB(bij,Bx,pB,B_iso) \
int32_t bij = GBX (Bx, pB, B_iso)
// true if values of B are not used
#define GB_B_IS_PATTERN \
0 \
// declare scalar of the same type as C
#define GB_CTYPE_SCALAR(t) \
int32_t t
// cij = Ax [pA]
#define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \
cij = GBX (Ax, pA, A_iso)
// cij = Bx [pB]
#define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \
cij = GBX (Bx, pB, B_iso)
#define GB_CX(p) Cx [p]
// binary operator
#define GB_BINOP(z,x,y,i,j) \
z = (x) & (y) ;
// true if the binop must be flipped
#define GB_BINOP_FLIP \
0
// op is second
#define GB_OP_IS_SECOND \
0
// do the numerical phases of GB_add and GB_emult
#define GB_PHASE_2_OF_2
// hard-coded loops can be vectorized
#define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_BAND || GxB_NO_INT32 || GxB_NO_BAND_INT32)
//------------------------------------------------------------------------------
// C += A+B, all 3 matrices dense
//------------------------------------------------------------------------------
#if 0
// The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV.
void GB ((none))
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#include "GB_dense_ewise3_accum_template.c"
}
#endif
//------------------------------------------------------------------------------
// C = A+B, all 3 matrices dense
//------------------------------------------------------------------------------
void GB (_Cdense_ewise3_noaccum__band_int32)
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#include "GB_dense_ewise3_noaccum_template.c"
}
//------------------------------------------------------------------------------
// C += B, accumulate a sparse matrix into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_accumB__band_int32)
(
GrB_Matrix C,
const GrB_Matrix B,
const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
{
#include "GB_dense_subassign_23_template.c"
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C += b, accumulate a scalar into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_accumb__band_int32)
(
GrB_Matrix C,
const GB_void *p_bwork,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
{
// get the scalar b for C += b, of type int32_t
int32_t bwork = (*((int32_t *) p_bwork)) ;
#include "GB_dense_subassign_22_template.c"
return (GrB_SUCCESS) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = A*D, column scale with diagonal D matrix
//------------------------------------------------------------------------------
#if 0
GrB_Info GB ((none))
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix D,
const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int32_t *restrict Cx = (int32_t *) C->x ;
#include "GB_AxB_colscale_template.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
//------------------------------------------------------------------------------
// C = D*B, row scale with diagonal D matrix
//------------------------------------------------------------------------------
#if 0
GrB_Info GB ((none))
(
GrB_Matrix C,
const GrB_Matrix D,
const GrB_Matrix B,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int32_t *restrict Cx = (int32_t *) C->x ;
#include "GB_AxB_rowscale_template.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
//------------------------------------------------------------------------------
// eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B
//------------------------------------------------------------------------------
GrB_Info GB (_AaddB__band_int32)
(
GrB_Matrix C,
const int C_sparsity,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const bool is_eWiseUnion,
const GB_void *alpha_scalar_in,
const GB_void *beta_scalar_in,
const bool Ch_is_Mh,
const int64_t *restrict C_to_M,
const int64_t *restrict C_to_A,
const int64_t *restrict C_to_B,
const GB_task_struct *restrict TaskList,
const int C_ntasks,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
GB_WERK_DECLARE (M_ek_slicing, int64_t) ;
GB_WERK_DECLARE (A_ek_slicing, int64_t) ;
GB_WERK_DECLARE (B_ek_slicing, int64_t) ;
int32_t alpha_scalar ;
int32_t beta_scalar ;
if (is_eWiseUnion)
{
alpha_scalar = (*((int32_t *) alpha_scalar_in)) ;
beta_scalar = (*((int32_t *) beta_scalar_in )) ;
}
#include "GB_add_template.c"
GB_FREE_WORKSPACE ;
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C=A.*B, C<M>=A.*B, or C<M!>=A.*B where C is sparse/hyper
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_08__band_int32)
(
GrB_Matrix C,
const int C_sparsity,
const int ewise_method,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *restrict C_to_M,
const int64_t *restrict C_to_A,
const int64_t *restrict C_to_B,
const GB_task_struct *restrict TaskList,
const int C_ntasks,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_emult_08_meta.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_02__band_int32)
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const bool flipxy,
const int64_t *restrict Cp_kfirst,
const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#if GB_BINOP_FLIP
// The operator is not commutative, and does not have a flipped
// variant. For example z=atan2(y,x).
if (flipxy)
{
// use fmult(y,x)
#undef GB_FLIPPED
#define GB_FLIPPED 1
#include "GB_emult_02_template.c"
}
else
{
// use fmult(x,y)
#undef GB_FLIPPED
#define GB_FLIPPED 0
#include "GB_emult_02_template.c"
}
#else
// No need to handle the flip: the operator is either commutative, or
// has been handled by changing z=div(y,x) to z=rdiv(x,y) for example.
#undef GB_FLIPPED
#define GB_FLIPPED 0
#include "GB_emult_02_template.c"
#endif
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_04__band_int32)
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *restrict Cp_kfirst,
const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_emult_04_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_bitmap__band_int32)
(
GrB_Matrix C,
const int ewise_method,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_bitmap_emult_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st
//------------------------------------------------------------------------------
GrB_Info GB (_bind1st__band_int32)
(
GB_void *Cx_output, // Cx and Bx may be aliased
const GB_void *x_input,
const GB_void *Bx_input,
const int8_t *restrict Bb,
int64_t bnz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int32_t *Cx = (int32_t *) Cx_output ;
int32_t x = (*((int32_t *) x_input)) ;
int32_t *Bx = (int32_t *) Bx_input ;
int64_t p ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < bnz ; p++)
{
if (!GBB (Bb, p)) continue ;
int32_t bij = GBX (Bx, p, false) ;
Cx [p] = (x) & (bij) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd
//------------------------------------------------------------------------------
GrB_Info GB (_bind2nd__band_int32)
(
GB_void *Cx_output, // Cx and Ax may be aliased
const GB_void *Ax_input,
const GB_void *y_input,
const int8_t *restrict Ab,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
int32_t *Cx = (int32_t *) Cx_output ;
int32_t *Ax = (int32_t *) Ax_input ;
int32_t y = (*((int32_t *) y_input)) ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!GBB (Ab, p)) continue ;
int32_t aij = GBX (Ax, p, false) ;
Cx [p] = (aij) & (y) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (x, A'): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (x, aij), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
int32_t aij = GBX (Ax, pA, false) ; \
Cx [pC] = (x) & (aij) ; \
}
GrB_Info GB (_bind1st_tran__band_int32)
(
GrB_Matrix C,
const GB_void *x_input,
const GrB_Matrix A,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
// GB_unop_transpose.c uses GB_ATYPE, but A is
// the 2nd input to binary operator z=f(x,y).
#undef GB_ATYPE
#define GB_ATYPE \
int32_t
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int32_t x = (*((const int32_t *) x_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
#undef GB_ATYPE
#define GB_ATYPE \
int32_t
}
//------------------------------------------------------------------------------
// C = op (A', y): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (aij, y), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
int32_t aij = GBX (Ax, pA, false) ; \
Cx [pC] = (aij) & (y) ; \
}
GrB_Info GB (_bind2nd_tran__band_int32)
(
GrB_Matrix C,
const GrB_Matrix A,
const GB_void *y_input,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int32_t y = (*((const int32_t *) y_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
GB_unop__lnot_uint16_uint16.c
|
//------------------------------------------------------------------------------
// GB_unop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated2/ folder, do not edit it
// (it is auto-generated from Generator/*).
#include "GB.h"
#ifndef GBCUDA_DEV
#include "GB_control.h"
#include "GB_atomics.h"
#include "GB_unop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB (_unop_apply__lnot_uint16_uint16)
// op(A') function: GB (_unop_tran__lnot_uint16_uint16)
// C type: uint16_t
// A type: uint16_t
// cast: uint16_t cij = aij
// unaryop: cij = !(aij != 0)
#define GB_ATYPE \
uint16_t
#define GB_CTYPE \
uint16_t
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
uint16_t aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = !(x != 0) ;
// casting
#define GB_CAST(z, aij) \
uint16_t z = aij ;
// cij = op (aij)
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
uint16_t aij = Ax [pA] ; \
/* Cx [pC] = op (cast (aij)) */ \
uint16_t z = aij ; \
Cx [pC] = !(z != 0) ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_LNOT || GxB_NO_UINT16)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_apply__lnot_uint16_uint16)
(
uint16_t *Cx, // Cx and Ax may be aliased
const uint16_t *Ax,
const int8_t *restrict Ab, // A->b if A is bitmap
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
if (Ab == NULL)
{
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
uint16_t aij = Ax [p] ;
uint16_t z = aij ;
Cx [p] = !(z != 0) ;
}
}
else
{
// bitmap case, no transpose; A->b already memcpy'd into C->b
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!Ab [p]) continue ;
uint16_t aij = Ax [p] ;
uint16_t z = aij ;
Cx [p] = !(z != 0) ;
}
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_tran__lnot_uint16_uint16)
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
edges_container.h
|
#pragma once
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
class EdgesContainer
{
private:
int vertices_count;
long long edges_count;
int *src_ids;
int *dst_ids;
public:
int *get_src_ids() {return src_ids;};
int *get_dst_ids() {return dst_ids;};
int get_vertices_count() {return vertices_count;};
long long get_edges_count() {return edges_count;};
void transpose()
{
int *tmp = src_ids;
src_ids = dst_ids;
dst_ids = tmp;
}
void print()
{
for(long long i = 0; i < edges_count; i++)
{
cout << src_ids[i] << " " << dst_ids[i] << endl;
}
}
void resize(int _vertices_count, long long _edges_count)
{
vertices_count = _vertices_count;
edges_count = _edges_count;
MemoryAPI::free_array(src_ids);
MemoryAPI::free_array(dst_ids);
MemoryAPI::allocate_array(&src_ids, edges_count);
MemoryAPI::allocate_array(&dst_ids, edges_count);
}
EdgesContainer(int _vertices_count = 1, long long _edges_count = 1)
{
vertices_count = _vertices_count;
edges_count = _edges_count;
MemoryAPI::allocate_array(&src_ids, edges_count);
MemoryAPI::allocate_array(&dst_ids, edges_count);
}
~EdgesContainer()
{
MemoryAPI::free_array(src_ids);
MemoryAPI::free_array(dst_ids);
}
bool save_to_binary_file(string _file_name)
{
FILE *graph_file = fopen(_file_name.c_str(), "wb");
if(graph_file == NULL)
return false;
GraphStorageFormat graph_type = EDGES_CONTAINER;
fwrite(reinterpret_cast<const void*>(&vertices_count), sizeof(int), 1, graph_file);
fwrite(reinterpret_cast<const void*>(&edges_count), sizeof(long long), 1, graph_file);
fwrite(reinterpret_cast<void*>(&graph_type), sizeof(GraphStorageFormat), 1, graph_file);
fwrite(reinterpret_cast<const void*>(src_ids), sizeof(int), edges_count, graph_file);
fwrite(reinterpret_cast<const void*>(dst_ids), sizeof(int), edges_count, graph_file);
fclose(graph_file);
return true;
}
bool load_from_binary_file(string _file_name)
{
FILE *graph_file = fopen(_file_name.c_str(), "rb");
if(graph_file == NULL)
return false;
GraphStorageFormat graph_type = EDGES_CONTAINER;
fread(reinterpret_cast<void*>(&vertices_count), sizeof(int), 1, graph_file);
fread(reinterpret_cast<void*>(&edges_count), sizeof(long long), 1, graph_file);
fread(reinterpret_cast<void*>(&graph_type), sizeof(GraphStorageFormat), 1, graph_file);
if(graph_type != EDGES_CONTAINER)
throw "Error in EdgesContainer::load_from_binary_file : incorrect type of graph in file";
resize(vertices_count, edges_count);
fread(reinterpret_cast<void*>(src_ids), sizeof(int), edges_count, graph_file);
fread(reinterpret_cast<void*>(dst_ids), sizeof(int), edges_count, graph_file);
fclose(graph_file);
return true;
}
void preprocess_into_csr_based(int *_work_buffer, vgl_sort_indexes *_sort_buffer)
{
bool work_buffer_was_allocated = false;
if(_work_buffer == NULL)
{
work_buffer_was_allocated = true;
MemoryAPI::allocate_array(&_work_buffer, this->edges_count);
}
bool sort_buffer_was_allocated = false;
if(_sort_buffer == NULL)
{
sort_buffer_was_allocated = true;
MemoryAPI::allocate_array(&_sort_buffer, this->edges_count);
}
// init sort indexes
#pragma _NEC ivdep
#pragma omp parallel for
for(int i = 0; i < this->edges_count; i++)
{
_sort_buffer[i] = i;
}
// sort src_ids
Timer tm;
tm.start();
Sorter::sort(src_ids, _sort_buffer, this->edges_count, SORT_ASCENDING);
tm.end();
#ifdef __PRINT_API_PERFORMANCE_STATS__
tm.print_time_stats("EdgesListGraph sorting (to CSR) time");
#endif
// reorder dst_ids
#pragma _NEC ivdep
#pragma _NEC vovertake
#pragma _NEC novob
#pragma _NEC vector
#pragma _NEC gather_reorder
#pragma omp parallel for
for(long long edge_pos = 0; edge_pos < this->edges_count; edge_pos++)
{
_work_buffer[edge_pos] = dst_ids[_sort_buffer[edge_pos]];
}
#pragma _NEC ivdep
#pragma omp parallel for
for(long long edge_pos = 0; edge_pos < this->edges_count; edge_pos++)
{
dst_ids[edge_pos] = _work_buffer[edge_pos];
}
if(work_buffer_was_allocated)
{
MemoryAPI::free_array(_work_buffer);
}
if(sort_buffer_was_allocated)
{
MemoryAPI::free_array(_sort_buffer);
}
}
void renumber_vertices(int *_conversion_array, int *_work_buffer)
{
Timer tm;
tm.start();
bool work_buffer_was_allocated = false;
if(_work_buffer == NULL)
{
work_buffer_was_allocated = true;
MemoryAPI::allocate_array(&_work_buffer, this->edges_count);
}
#pragma _NEC ivdep
#pragma _NEC novob
#pragma _NEC vector
#pragma _NEC gather_reorder
#pragma omp parallel for
for(long long edge_pos = 0; edge_pos < this->edges_count; edge_pos++)
{
_work_buffer[edge_pos] = _conversion_array[src_ids[edge_pos]];
}
#pragma _NEC ivdep
#pragma omp parallel for
for(long long edge_pos = 0; edge_pos < this->edges_count; edge_pos++)
{
src_ids[edge_pos] = _work_buffer[edge_pos];
}
#pragma _NEC ivdep
#pragma _NEC novob
#pragma _NEC vector
#pragma _NEC gather_reorder
#pragma omp parallel for
for(long long edge_pos = 0; edge_pos < this->edges_count; edge_pos++)
{
_work_buffer[edge_pos] = _conversion_array[dst_ids[edge_pos]];
}
#pragma _NEC ivdep
#pragma omp parallel for
for(long long edge_pos = 0; edge_pos < this->edges_count; edge_pos++)
{
dst_ids[edge_pos] = _work_buffer[edge_pos];
}
if(work_buffer_was_allocated)
{
MemoryAPI::free_array(_work_buffer);
}
}
void random_shuffle_edges()
{
srand ( unsigned ( time(0) ) );
vector<int> reorder_ids(vertices_count);
#pragma omp parallel for
for (int i = 0; i < vertices_count; i++)
reorder_ids[i] = i;
random_shuffle(reorder_ids.begin(), reorder_ids.end() );
#pragma _NEC ivdep
#pragma _NEC novob
#pragma omp parallel for
for(long long i = 0; i < edges_count; i++)
{
src_ids[i] = reorder_ids[src_ids[i]];
dst_ids[i] = reorder_ids[dst_ids[i]];
}
}
};
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
GB_to_hyper.c
|
//------------------------------------------------------------------------------
// GB_to_hyper: convert a matrix to hyperspasre
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved.
// http://suitesparse.com See GraphBLAS/Doc/License.txt for license.
//------------------------------------------------------------------------------
// On input, the matrix may have shallow A->p content; it is safely removed.
// On output, the matrix is always hypersparse (even if out of memory). If the
// input matrix is non-hypersparse, it is given new A->p and A->h that are not
// shallow. If the input matrix is already hypersparse, nothing is changed
// (and in that case A->p and A->h remain shallow on output if shallow on
// input). The A->x and A->i content is not changed; it remains in whatever
// shallow/non-shallow state that it had on input).
// If an out-of-memory condition occurs, all content of the matrix is cleared.
// The input matrix may be jumbled; this is not an error condition.
#include "GB.h"
GrB_Info GB_to_hyper // convert a matrix to hypersparse
(
GrB_Matrix A, // matrix to convert to hypersparse
GB_Context Context
)
{
//--------------------------------------------------------------------------
// check inputs
//--------------------------------------------------------------------------
ASSERT_MATRIX_OK_OR_JUMBLED (A, "A converting to hypersparse", GB0) ;
int64_t anz = GB_NNZ (A) ;
ASSERT (GB_ZOMBIES_OK (A)) ;
//--------------------------------------------------------------------------
// convert A to hypersparse form
//--------------------------------------------------------------------------
if (!A->is_hyper)
{
//----------------------------------------------------------------------
// determine the number of threads to use
//----------------------------------------------------------------------
int64_t n = A->vdim ;
GB_GET_NTHREADS_MAX (nthreads_max, chunk, Context) ;
int nthreads = GB_nthreads (n, chunk, nthreads_max) ;
int ntasks = (nthreads == 1) ? 1 : (8 * nthreads) ;
ntasks = GB_IMIN (ntasks, n) ;
ntasks = GB_IMAX (ntasks, 1) ;
//----------------------------------------------------------------------
// count the number of non-empty vectors in A in each slice
//----------------------------------------------------------------------
A->is_hyper = true ; // A becomes hypersparse
ASSERT (A->h == NULL) ;
ASSERT (A->nvec == A->plen && A->plen == n) ;
const int64_t *GB_RESTRICT Ap_old = A->p ;
bool Ap_old_shallow = A->p_shallow ;
int64_t *GB_RESTRICT Count = GB_MALLOC (ntasks+1, int64_t) ;
if (Count == NULL)
{
// out of memory
GB_PHIX_FREE (A) ;
return (GB_OUT_OF_MEMORY) ;
}
int tid ;
#pragma omp parallel for num_threads(nthreads) schedule(dynamic,1)
for (tid = 0 ; tid < ntasks ; tid++)
{
int64_t jstart, jend, my_nvec_nonempty = 0 ; ;
GB_PARTITION (jstart, jend, n, tid, ntasks) ;
for (int64_t j = jstart ; j < jend ; j++)
{
if (Ap_old [j] < Ap_old [j+1]) my_nvec_nonempty++ ;
}
Count [tid] = my_nvec_nonempty ;
}
//----------------------------------------------------------------------
// compute cumulative sum of Counts and nvec_nonempty
//----------------------------------------------------------------------
GB_cumsum (Count, ntasks, NULL, 1) ;
int64_t nvec_nonempty = Count [ntasks] ;
A->nvec_nonempty = nvec_nonempty ;
//----------------------------------------------------------------------
// allocate the new A->p and A->h
//----------------------------------------------------------------------
int64_t *GB_RESTRICT Ap_new = GB_MALLOC (nvec_nonempty+1, int64_t) ;
int64_t *GB_RESTRICT Ah_new = GB_MALLOC (nvec_nonempty , int64_t) ;
if (Ap_new == NULL || Ah_new == NULL)
{
// out of memory
GB_FREE (Count) ;
GB_FREE (Ap_new) ;
GB_FREE (Ah_new) ;
GB_PHIX_FREE (A) ;
return (GB_OUT_OF_MEMORY) ;
}
//----------------------------------------------------------------------
// transplant the new A->p and A->h into the matrix
//----------------------------------------------------------------------
A->plen = nvec_nonempty ;
A->nvec = nvec_nonempty ;
A->p = Ap_new ;
A->h = Ah_new ;
A->p_shallow = false ;
A->h_shallow = false ;
//----------------------------------------------------------------------
// construct the new hyperlist in the new A->p and A->h
//----------------------------------------------------------------------
#pragma omp parallel for num_threads(nthreads) schedule(dynamic,1)
for (tid = 0 ; tid < ntasks ; tid++)
{
int64_t jstart, jend, k = Count [tid] ;
GB_PARTITION (jstart, jend, n, tid, ntasks) ;
for (int64_t j = jstart ; j < jend ; j++)
{
if (Ap_old [j] < Ap_old [j+1])
{
// vector index j is the kth vector in the new Ah
Ap_new [k] = Ap_old [j] ;
Ah_new [k] = j ;
k++ ;
}
}
ASSERT (k == Count [tid+1]) ;
}
Ap_new [nvec_nonempty] = anz ;
A->magic = GB_MAGIC ;
ASSERT (A->nvec_nonempty == GB_nvec_nonempty (A, Context)) ;
//----------------------------------------------------------------------
// free workspace, and free the old A->p unless it's shallow
//----------------------------------------------------------------------
GB_FREE (Count) ;
if (!Ap_old_shallow)
{
GB_FREE (Ap_old) ;
}
}
//--------------------------------------------------------------------------
// A is now in hypersparse form
//--------------------------------------------------------------------------
ASSERT (anz == GB_NNZ (A)) ;
ASSERT_MATRIX_OK_OR_JUMBLED (A, "A converted to hypersparse", GB0) ;
ASSERT (A->is_hyper) ;
return (GrB_SUCCESS) ;
}
|
GB_binop__lor_uint8.c
|
//------------------------------------------------------------------------------
// GB_binop: hard-coded functions for each built-in binary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated2/ folder, do not edit it
// (it is auto-generated from Generator/*).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_emult.h"
#include "GB_control.h"
#include "GB_ek_slice.h"
#include "GB_dense.h"
#include "GB_atomics.h"
#include "GB_bitmap_assign_methods.h"
#include "GB_binop__include.h"
// C=binop(A,B) is defined by the following types and operators:
// A+B function (eWiseAdd): GB (_AaddB__lor_uint8)
// A.*B function (eWiseMult): GB (_AemultB_01__lor_uint8)
// A.*B function (eWiseMult): GB (_AemultB_02__lor_uint8)
// A.*B function (eWiseMult): GB (_AemultB_03__lor_uint8)
// A.*B function (eWiseMult): GB (_AemultB_bitmap__lor_uint8)
// A*D function (colscale): GB (_AxD__lor_uint8)
// D*A function (rowscale): GB (_DxB__lor_uint8)
// C+=B function (dense accum): GB (_Cdense_accumB__lor_uint8)
// C+=b function (dense accum): GB (_Cdense_accumb__lor_uint8)
// C+=A+B function (dense ewise3): GB ((none))
// C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__lor_uint8)
// C=scalar+B GB (_bind1st__lor_uint8)
// C=scalar+B' GB (_bind1st_tran__lor_uint8)
// C=A+scalar GB (_bind2nd__lor_uint8)
// C=A'+scalar GB (_bind2nd_tran__lor_uint8)
// C type: uint8_t
// A type: uint8_t
// B,b type: uint8_t
// BinaryOp: cij = ((aij != 0) || (bij != 0))
#define GB_ATYPE \
uint8_t
#define GB_BTYPE \
uint8_t
#define GB_CTYPE \
uint8_t
// true if the types of A and B are identical
#define GB_ATYPE_IS_BTYPE \
1
// true if the types of C and A are identical
#define GB_CTYPE_IS_ATYPE \
1
// true if the types of C and B are identical
#define GB_CTYPE_IS_BTYPE \
1
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA,A_iso) \
uint8_t aij = GBX (Ax, pA, A_iso)
// bij = Bx [pB]
#define GB_GETB(bij,Bx,pB,B_iso) \
uint8_t bij = GBX (Bx, pB, B_iso)
// declare scalar of the same type as C
#define GB_CTYPE_SCALAR(t) \
uint8_t t
// cij = Ax [pA]
#define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \
cij = GBX (Ax, pA, A_iso)
// cij = Bx [pB]
#define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \
cij = GBX (Bx, pB, B_iso)
#define GB_CX(p) Cx [p]
// binary operator
#define GB_BINOP(z,x,y,i,j) \
z = ((x != 0) || (y != 0)) ;
// true if the binop must be flipped
#define GB_BINOP_FLIP \
0
// op is second
#define GB_OP_IS_SECOND \
0
// do the numerical phases of GB_add and GB_emult
#define GB_PHASE_2_OF_2
// hard-coded loops can be vectorized
#define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_LOR || GxB_NO_UINT8 || GxB_NO_LOR_UINT8)
//------------------------------------------------------------------------------
// C += A+B, all 3 matrices dense
//------------------------------------------------------------------------------
#if 0
// The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV.
void GB ((none))
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#include "GB_dense_ewise3_accum_template.c"
}
#endif
//------------------------------------------------------------------------------
// C = A+B, all 3 matrices dense
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_ewise3_noaccum__lor_uint8)
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_dense_ewise3_noaccum_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C += B, accumulate a sparse matrix into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_accumB__lor_uint8)
(
GrB_Matrix C,
const GrB_Matrix B,
const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
{
#include "GB_dense_subassign_23_template.c"
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C += b, accumulate a scalar into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_accumb__lor_uint8)
(
GrB_Matrix C,
const GB_void *p_bwork,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
{
// get the scalar b for C += b, of type uint8_t
uint8_t bwork = (*((uint8_t *) p_bwork)) ;
#include "GB_dense_subassign_22_template.c"
return (GrB_SUCCESS) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = A*D, column scale with diagonal D matrix
//------------------------------------------------------------------------------
GrB_Info GB (_AxD__lor_uint8)
(
GrB_Matrix C,
const GrB_Matrix A, bool A_is_pattern,
const GrB_Matrix D, bool D_is_pattern,
const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint8_t *restrict Cx = (uint8_t *) C->x ;
#include "GB_AxB_colscale_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = D*B, row scale with diagonal D matrix
//------------------------------------------------------------------------------
GrB_Info GB (_DxB__lor_uint8)
(
GrB_Matrix C,
const GrB_Matrix D, bool D_is_pattern,
const GrB_Matrix B, bool B_is_pattern,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint8_t *restrict Cx = (uint8_t *) C->x ;
#include "GB_AxB_rowscale_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseAdd: C = A+B or C<M> = A+B
//------------------------------------------------------------------------------
GrB_Info GB (_AaddB__lor_uint8)
(
GrB_Matrix C,
const int C_sparsity,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const bool Ch_is_Mh,
const int64_t *restrict C_to_M,
const int64_t *restrict C_to_A,
const int64_t *restrict C_to_B,
const GB_task_struct *restrict TaskList,
const int C_ntasks,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
GB_WERK_DECLARE (M_ek_slicing, int64_t) ;
GB_WERK_DECLARE (A_ek_slicing, int64_t) ;
GB_WERK_DECLARE (B_ek_slicing, int64_t) ;
#include "GB_add_template.c"
GB_FREE_WORK ;
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C = A.*B or C<M> = A.*B
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_01__lor_uint8)
(
GrB_Matrix C,
const int C_sparsity,
const int ewise_method,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *restrict C_to_M,
const int64_t *restrict C_to_A,
const int64_t *restrict C_to_B,
const GB_task_struct *restrict TaskList,
const int C_ntasks,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_emult_01_meta.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_02__lor_uint8)
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const bool flipxy,
const int64_t *restrict Cp_kfirst,
const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#if GB_BINOP_FLIP
// The operator is not commutative, and does not have a flipped
// variant. For example z=atan2(y,x).
if (flipxy)
{
// use fmult(y,x)
#undef GB_FLIPPED
#define GB_FLIPPED 1
#include "GB_emult_02_template.c"
}
else
{
// use fmult(x,y)
#undef GB_FLIPPED
#define GB_FLIPPED 0
#include "GB_emult_02_template.c"
}
#else
// No need to handle the flip: the operator is either commutative, or
// has been handled by changing z=div(y,x) to z=rdiv(x,y) for example.
#undef GB_FLIPPED
#define GB_FLIPPED 0
#include "GB_emult_02_template.c"
#endif
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_03__lor_uint8)
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *restrict Cp_kfirst,
const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_emult_03_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_bitmap__lor_uint8)
(
GrB_Matrix C,
const int ewise_method,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_bitmap_emult_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st
//------------------------------------------------------------------------------
GrB_Info GB (_bind1st__lor_uint8)
(
GB_void *Cx_output, // Cx and Bx may be aliased
const GB_void *x_input,
const GB_void *Bx_input,
const int8_t *restrict Bb,
int64_t bnz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint8_t *Cx = (uint8_t *) Cx_output ;
uint8_t x = (*((uint8_t *) x_input)) ;
uint8_t *Bx = (uint8_t *) Bx_input ;
int64_t p ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < bnz ; p++)
{
if (!GBB (Bb, p)) continue ;
uint8_t bij = GBX (Bx, p, false) ;
Cx [p] = ((x != 0) || (bij != 0)) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd
//------------------------------------------------------------------------------
GrB_Info GB (_bind2nd__lor_uint8)
(
GB_void *Cx_output, // Cx and Ax may be aliased
const GB_void *Ax_input,
const GB_void *y_input,
const int8_t *restrict Ab,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
uint8_t *Cx = (uint8_t *) Cx_output ;
uint8_t *Ax = (uint8_t *) Ax_input ;
uint8_t y = (*((uint8_t *) y_input)) ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!GBB (Ab, p)) continue ;
uint8_t aij = GBX (Ax, p, false) ;
Cx [p] = ((aij != 0) || (y != 0)) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (x, A'): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (x, aij), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
uint8_t aij = GBX (Ax, pA, false) ; \
Cx [pC] = ((x != 0) || (aij != 0)) ; \
}
GrB_Info GB (_bind1st_tran__lor_uint8)
(
GrB_Matrix C,
const GB_void *x_input,
const GrB_Matrix A,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
// GB_unop_transpose.c uses GB_ATYPE, but A is
// the 2nd input to binary operator z=f(x,y).
#undef GB_ATYPE
#define GB_ATYPE \
uint8_t
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint8_t x = (*((const uint8_t *) x_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
#undef GB_ATYPE
#define GB_ATYPE \
uint8_t
}
//------------------------------------------------------------------------------
// C = op (A', y): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (aij, y), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
uint8_t aij = GBX (Ax, pA, false) ; \
Cx [pC] = ((aij != 0) || (y != 0)) ; \
}
GrB_Info GB (_bind2nd_tran__lor_uint8)
(
GrB_Matrix C,
const GrB_Matrix A,
const GB_void *y_input,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint8_t y = (*((const uint8_t *) y_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
purkinje_matrix_assembly.c
|
//
// Created by bergolho on 04/09/19.
//
#include <stdbool.h>
#include <stdint.h>
#include <stdlib.h>
#include <time.h>
#include "../alg/grid/grid.h"
#include "../config/assembly_matrix_config.h"
#include "../monodomain/constants.h"
#include "../utils/utils.h"
#include "../single_file_libraries/stb_ds.h"
#include "../libraries_common/common_data_structures.h"
#include "../config_helpers/config_helpers.h"
INIT_ASSEMBLY_MATRIX(set_initial_conditions_fvm) {
real_cpu alpha;
struct cell_node **ac = the_grid->the_purkinje->purkinje_cells;
uint32_t active_cells = the_grid->the_purkinje->num_active_purkinje_cells;
real_cpu beta = the_solver->beta;
real_cpu cm = the_solver->cm;
real_cpu dt = the_solver->dt;
int i;
#pragma omp parallel for private(alpha)
for(i = 0; i < active_cells; i++)
{
alpha = ALPHA(beta, cm, dt, ac[i]->discretization.x, ac[i]->discretization.y, ac[i]->discretization.z);
ac[i]->v = purkinje_initial_v;
ac[i]->b = purkinje_initial_v * alpha;
}
}
void initialize_diagonal_elements_purkinje (struct monodomain_solver *the_solver, struct grid *the_grid)
{
real_cpu alpha;
real_cpu dx, dy, dz;
uint32_t num_active_cells = the_grid->the_purkinje->num_active_purkinje_cells;
struct cell_node **ac = the_grid->the_purkinje->purkinje_cells;
struct node *n = the_grid->the_purkinje->the_network->list_nodes;
real_cpu beta = the_solver->beta;
real_cpu cm = the_solver->cm;
real_cpu dt = the_solver->dt;
int i;
for (i = 0; i < num_active_cells; i++)
{
dx = ac[i]->discretization.x;
dy = ac[i]->discretization.y;
dz = ac[i]->discretization.z;
alpha = ALPHA(beta, cm, dt, dx, dy, dz);
struct element element;
element.column = ac[i]->grid_position;
element.cell = ac[i];
element.value = alpha;
if (ac[i]->elements != NULL)
{
arrfree(ac[i]->elements);
}
ac[i]->elements = NULL;
arrsetcap(ac[i]->elements,n->num_edges);
arrput(ac[i]->elements, element);
n = n->next;
}
}
// For the Purkinje fibers we only need to solve the 1D Monodomain equation
static void fill_discretization_matrix_elements_purkinje (real_cpu sigma_x, struct cell_node **grid_cells, uint32_t num_active_cells,
struct node *pk_node)
{
struct edge *e;
struct element **cell_elements;
real_cpu dx, dy, dz;
real_cpu multiplier;
int i;
for (i = 0; i < num_active_cells; i++, pk_node = pk_node->next)
{
cell_elements = &grid_cells[i]->elements;
dx = grid_cells[i]->discretization.x;
dy = grid_cells[i]->discretization.x;
dz = grid_cells[i]->discretization.x;
multiplier = ((dy * dz) / dx);
e = pk_node->list_edges;
// Do the mapping of the edges from the graph to the sparse matrix data structure ...
while (e != NULL)
{
struct element new_element;
// Neighbour elements ...
new_element.column = e->id;
new_element.value = (-sigma_x * multiplier);
new_element.cell = grid_cells[e->id];
// Diagonal element ...
cell_elements[0]->value += (sigma_x * multiplier);
arrput(grid_cells[i]->elements,new_element);
e = e->next;
}
}
}
ASSEMBLY_MATRIX(purkinje_fibers_assembly_matrix)
{
static bool sigma_initialized = false;
uint32_t num_active_cells = the_grid->the_purkinje->num_active_purkinje_cells;
struct cell_node **ac = the_grid->the_purkinje->purkinje_cells;
struct node *pk_node = the_grid->the_purkinje->the_network->list_nodes;
initialize_diagonal_elements_purkinje(the_solver, the_grid);
real sigma_x = 0.0;
GET_PARAMETER_NUMERIC_VALUE_OR_REPORT_ERROR(real,sigma_x, config->config_data, "sigma_x");
if(!sigma_initialized)
{
#pragma omp parallel for
for (uint32_t i = 0; i < num_active_cells; i++)
{
ac[i]->sigma.x = sigma_x;
}
sigma_initialized = true;
}
fill_discretization_matrix_elements_purkinje(sigma_x,ac,num_active_cells,pk_node);
}
|
GB_unaryop__lnot_int32_fp64.c
|
//------------------------------------------------------------------------------
// GB_unaryop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved.
// http://suitesparse.com See GraphBLAS/Doc/License.txt for license.
//------------------------------------------------------------------------------
// If this file is in the Generated/ folder, do not edit it (auto-generated).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_iterator.h"
#include "GB_unaryop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB_unop__lnot_int32_fp64
// op(A') function: GB_tran__lnot_int32_fp64
// C type: int32_t
// A type: double
// cast: int32_t cij ; GB_CAST_SIGNED(cij,aij,32)
// unaryop: cij = !(aij != 0)
#define GB_ATYPE \
double
#define GB_CTYPE \
int32_t
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
double aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = !(x != 0) ;
// casting
#define GB_CASTING(z, x) \
int32_t z ; GB_CAST_SIGNED(z,x,32) ;
// cij = op (cast (aij))
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
GB_GETA (aij, Ax, pA) ; \
/* Cx [pC] = op (cast (aij)) */ \
GB_CASTING (x, aij) ; \
GB_OP (GB_CX (pC), x) ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_LNOT || GxB_NO_INT32 || GxB_NO_FP64)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop__lnot_int32_fp64
(
int32_t *restrict Cx,
const double *restrict Ax,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (int64_t p = 0 ; p < anz ; p++)
{
GB_CAST_OP (p, p) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_tran__lnot_int32_fp64
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t *restrict *Rowcounts,
GBI_single_iterator Iter,
const int64_t *restrict A_slice,
int naslice
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#define GB_PHASE_2_OF_2
#include "GB_unaryop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
apery.c
|
/*
* Copyright (c) 2017 Leonhard Reichenbach
*
* This file is released under the MIT license.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <inttypes.h>
#include <omp.h>
#include <time.h>
#include "pcg_basic.h"
#define FAILURE(progname, msg...) \
fprintf(stderr,msg); usage(progname); exit(EXIT_FAILURE);
static void usage(const char *progname) {
int indent = strlen(progname) + 8;
fprintf(stderr, "Usage: %s %s\n%*s%s\n",
progname, "<Number of random number tripletts used N>",
indent, " ", "<Max random number size M>");
}
int gcd(int a, int b) {
uint64_t temp;
while (b != 0) {
temp = b;
b = a % b;
a = temp;
}
return a;
}
int triple_gcd(int a, int b, int c) {
uint64_t d = gcd(a, b);
if (d != 1) {
d = gcd(d, c);
}
return d;
}
int main(int argc, char *argv[]) {
uint64_t N, M;
switch (argc) {
case 1:
N = 1000;
M = 1000;
break;
case 3:
if (sscanf(argv[1], "%lu", &N) * sscanf(argv[2], "%lu", &M) != 1) {
FAILURE(argv[0], "%s","");
}
break;
default:
FAILURE(argv[0], "%s\n","Illegal parameter count!");
}
pcg32_random_t rng1;
pcg32_srandom_r(&rng1, time(NULL), (intptr_t)&rng1);
uint64_t coprimes = 0;
uint64_t a, b, c;
/*#pragma omp parallel for private(a, b, c) reduction(+:coprimes)*/
for (uint64_t i = 0; i < N; i++) {
a = pcg32_boundedrand_r(&rng1, M);
b = pcg32_boundedrand_r(&rng1, M);
c = pcg32_boundedrand_r(&rng1, M);
if (triple_gcd(a, b, c) == 1) {
coprimes++;
}
}
printf("N: %lu\n", N);
printf("Number of coprimes: %lu\n", coprimes);
printf("Approximation of Apery's constant: %lf\n", (N/((double) coprimes)));
return EXIT_SUCCESS;
}
|
set_horz_pres_BCs.h
|
#pragma omp target teams distribute parallel for thread_limit(BLOCK_SIZE)
for (int col = 1; col < NUM/2+1; col++)
{
col = (col * 2) - 1;
int NUM_2 = NUM >> 1;
// p_i,0 = p_i,1
pres_black(col, 0) = pres_red(col, 1);
pres_red(col + 1, 0) = pres_black(col + 1, 1);
// p_i,jmax+1 = p_i,jmax
pres_red(col, NUM_2 + 1) = pres_black(col, NUM_2);
pres_black(col + 1, NUM_2 + 1) = pres_red(col + 1, NUM_2);
}
|
x86_functions_fp32.h
|
// Copyright (C) 2019. Huawei Technologies Co., Ltd. All rights reserved.
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#ifndef CHEETAH_X86_FUNCTIONS_FP32_H
#define CHEETAH_X86_FUNCTIONS_FP32_H
#include "cpu/cpu_functions_template.h"
#include "x86_avx2_expand.h"
#include "thread_affinity.h"
inline EE activation_fp32(F32 *input, U32 len, ActivationParamSpec activationDesc, F32 *output)
{
__m256 zero = _mm256_set1_ps(0.);
__m256 one = _mm256_set1_ps(1.);
__m256 three = _mm256_set1_ps(3.);
__m256 six = _mm256_set1_ps(6.);
__m256 signm = _mm256_set1_ps(-0.0);
U32 loops = len / 8 * 8;
EE ret = SUCCESS;
switch (activationDesc.mode) {
case ACTIVATION_NULL: {
if (output != input) {
UNI_MEMCPY(output, input, sizeof(float) * len);
}
loops = len;
break;
}
case ACTIVATION_RELU: {
if (activationDesc.value[0] == 0) {
#ifdef _USE_OPENMP
#pragma omp parallel for num_threads(OMP_NUM_THREADS) schedule(static)
#endif
for (U32 i = 0; i < loops; i += 8) {
_mm256_storeu_ps(output + i, _mm256_max_ps(zero, _mm256_loadu_ps(input + i)));
}
} else {
__m256 scale = _mm256_set1_ps(activationDesc.value[0]);
#ifdef _USE_OPENMP
#pragma omp parallel for num_threads(OMP_NUM_THREADS) schedule(static)
#endif
for (U32 i = 0; i < loops; i += 8) {
__m256 tmp = _mm256_loadu_ps(input + i);
_mm256_storeu_ps(output + i, _mm256_max_ps(_mm256_mul_ps(scale, tmp), tmp));
}
}
break;
}
case ACTIVATION_RELU6: {
for (U32 i = 0; i < loops; i += 8) {
__m256 in = _mm256_loadu_ps(input + i);
__m256 out = _mm256_max_ps(zero, in);
out = _mm256_min_ps(six, out);
_mm256_storeu_ps(output + i, out);
}
break;
}
case ACTIVATION_H_SIGMOID: {
for (U32 i = 0; i < loops; i += 8) {
__m256 in = _mm256_loadu_ps(input + i);
__m256 out = _mm256_add_ps(in, three);
out = _mm256_max_ps(out, zero);
out = _mm256_min_ps(out, six);
out = _mm256_div_ps(out, six);
_mm256_storeu_ps(output + i, out);
}
break;
}
case ACTIVATION_H_SWISH: {
#ifdef _USE_OPENMP
#pragma omp parallel for num_threads(OMP_NUM_THREADS) schedule(static)
#endif
for (U32 i = 0; i < loops; i += 8) {
__m256 in = _mm256_loadu_ps(input + i);
__m256 out = _mm256_add_ps(in, three);
out = _mm256_max_ps(out, zero);
out = _mm256_min_ps(out, six);
out = _mm256_div_ps(out, six);
out = _mm256_mul_ps(out, in);
_mm256_storeu_ps(output + i, out);
}
break;
}
case ACTIVATION_H_SWISH_NODIV: {
for (U32 i = 0; i < loops; i += 8) {
__m256 in = _mm256_loadu_ps(input + i);
__m256 out = _mm256_add_ps(in, three);
out = _mm256_max_ps(out, zero);
out = _mm256_min_ps(out, six);
out = _mm256_mul_ps(out, in);
_mm256_storeu_ps(output + i, out);
}
break;
}
case ACTIVATION_GELU: {
__m256 vec0 = _mm256_set1_ps(sqrt(2 / 3.14159265358979323846));
__m256 vec1 = _mm256_set1_ps(0.044715);
__m256 vec2 = _mm256_set1_ps(0.5);
for (U32 i = 0; i < loops; i += 8) {
__m256 in = _mm256_loadu_ps(input + i);
__m256 out = _mm256_mul_ps(in, in);
out = _mm256_mul_ps(out, in);
out = _mm256_fmadd_ps(vec1, out, in);
out = _mm256_mul_ps(vec0, out);
out = _mm256_tanh_ps(out);
out = _mm256_add_ps(one, out);
out = _mm256_mul_ps(vec2, out);
out = _mm256_mul_ps(in, out);
_mm256_storeu_ps(output + i, out);
}
break;
}
case ACTIVATION_TANH: {
for (U32 i = 0; i < loops; i += 8) {
__m256 in = _mm256_loadu_ps(input + i);
__m256 out = _mm256_tanh_ps(in);
_mm256_storeu_ps(output + i, out);
}
break;
}
case ACTIVATION_SIGMOID: {
for (U32 i = 0; i < loops; i += 8) {
__m256 in = _mm256_loadu_ps(input + i);
__m256 out = _mm256_sigmod_ps(in);
_mm256_storeu_ps(output + i, out);
}
break;
}
case ACTIVATION_SWISH: {
#ifdef _USE_OPENMP
#pragma omp parallel for num_threads(OMP_NUM_THREADS) schedule(static)
#endif
for (U32 i = 0; i < loops; i += 8) {
__m256 in = _mm256_loadu_ps(input + i);
__m256 out = _mm256_mul_ps(in, _mm256_sigmod_ps(in));
_mm256_storeu_ps(output + i, out);
}
break;
}
case ACTIVATION_MISH: {
for (U32 i = 0; i < loops; i += 8) {
__m256 in = _mm256_loadu_ps(input + i);
__m256 out = _mm256_mul_ps(
in, _mm256_tanh_ps(_mm256_log_ps(_mm256_add_ps(_mm256_exp_ps(in), one))));
_mm256_storeu_ps(output + i, out);
}
break;
}
case ACTIVATION_SOFTPLUS: {
for (U32 i = 0; i < loops; i += 8) {
__m256 in = _mm256_loadu_ps(input + i);
__m256 out = _mm256_log_ps(_mm256_add_ps(_mm256_exp_ps(in), one));
_mm256_storeu_ps(output + i, out);
}
break;
}
case ACTIVATION_EXP: {
for (U32 i = 0; i < loops; i += 8) {
__m256 in = _mm256_loadu_ps(input + i);
__m256 out = _mm256_exp_ps(in);
_mm256_storeu_ps(output + i, out);
}
break;
}
case ACTIVATION_ABS: {
for (U32 i = 0; i < loops; i += 8) {
__m256 in = _mm256_loadu_ps(input + i);
__m256 out = _mm256_andnot_ps(signm, in);
_mm256_storeu_ps(output + i, out);
}
break;
}
case ACTIVATION_LOG: {
for (U32 i = 0; i < loops; i += 8) {
__m256 in = _mm256_loadu_ps(input + i);
__m256 out = _mm256_log_ps(in);
_mm256_storeu_ps(output + i, out);
}
break;
}
case ACTIVATION_ROUND: {
for (U32 i = 0; i < loops; i += 8) {
__m256 in = _mm256_loadu_ps(input + i);
__m256 out = _mm256_round_ps(in, _MM_FROUND_TO_NEAREST_INT);
_mm256_storeu_ps(output + i, out);
}
break;
}
case ACTIVATION_CEIL: {
for (U32 i = 0; i < loops; i += 8) {
__m256 in = _mm256_loadu_ps(input + i);
__m256 out = _mm256_ceil_ps(in);
_mm256_storeu_ps(output + i, out);
}
break;
}
case ACTIVATION_FLOOR: {
for (U32 i = 0; i < loops; i += 8) {
__m256 in = _mm256_loadu_ps(input + i);
__m256 out = _mm256_floor_ps(in);
_mm256_storeu_ps(output + i, out);
}
break;
}
case ACTIVATION_RECIPROCAL: {
for (U32 i = 0; i < loops; i += 8) {
__m256 in = _mm256_loadu_ps(input + i);
__m256 out = _mm256_div_ps(one, in);
_mm256_storeu_ps(output + i, out);
}
break;
}
case ACTIVATION_SIGN:
case ACTIVATION_NOT:
case ACTIVATION_GREATER:
case ACTIVATION_NEG: {
loops = 0;
break;
}
default:
ret = NOT_SUPPORTED;
break;
}
if (ret == SUCCESS) {
for (U32 i = loops; i < len; i++) {
ret = activation_template<F32>(activationDesc, input[i], output + i);
}
}
return ret;
}
inline void array_scale_f32(const F32 *input, F32 *output, I32 len, F32 alpha, F32 beta)
{
__m256 alpha_v = _mm256_set1_ps(alpha);
__m256 beta_v = _mm256_set1_ps(beta);
I32 i = 0;
for (i = 0; i < len - 7; i += 8) {
__m256 in = _mm256_loadu_ps(input + i);
__m256 tmp_v = _mm256_add_ps(beta_v, _mm256_mul_ps(alpha_v, in));
_mm256_storeu_ps(output + i, tmp_v);
}
for (; i < len; i++) {
output[i] = alpha * input[i] + beta;
}
}
inline void array_power_f32(F32 *input, F32 *output, I32 len, F32 power)
{
I32 i = 0;
if (power == -1) {
__m256 one_v = _mm256_set1_ps(1);
for (i = 0; i < len - 7; i += 8) {
__m256 in = _mm256_loadu_ps(input + i);
__m256 tmp_v = _mm256_div_ps(one_v, in);
_mm256_storeu_ps(output + i, tmp_v);
}
} else if (power == -0.5) {
__m256 one_v = _mm256_set1_ps(1);
for (i = 0; i < len - 7; i += 8) {
__m256 in = _mm256_loadu_ps(input + i);
__m256 tmp_v = _mm256_div_ps(one_v, _mm256_sqrt_ps(in));
_mm256_storeu_ps(output + i, tmp_v);
}
} else if (power == 0.5) {
for (i = 0; i < len - 7; i += 8) {
__m256 in = _mm256_loadu_ps(input + i);
__m256 tmp_v = _mm256_sqrt_ps(in);
_mm256_storeu_ps(output + i, tmp_v);
}
} else if (power == 1) {
if (input != output) {
UNI_MEMCPY(output, input, len * sizeof(F32));
}
i = len;
} else if (power == 2) {
for (i = 0; i < len - 7; i += 8) {
__m256 in = _mm256_loadu_ps(input + i);
__m256 tmp_v = _mm256_mul_ps(in, in);
_mm256_storeu_ps(output + i, tmp_v);
}
}
for (; i < len; i++) {
output[i] = powf(input[i], power);
}
}
template <int mode>
inline static void array_minmax_value_f32_template(const F32 *data, I32 len, F32 *result)
{
F32 min_s = data[0];
F32 max_s = data[0];
I32 i = 0;
if (len >= 8) {
__m256 min_v, max_v, tmp_v;
min_v = max_v = _mm256_loadu_ps(data);
for (i = 8; i < len - 7; i += 8) {
tmp_v = _mm256_loadu_ps(data + i);
if (mode & 1)
min_v = _mm256_min_ps(tmp_v, min_v);
if (mode & 2)
max_v = _mm256_max_ps(tmp_v, max_v);
}
if (mode & 1)
max_s = _mm256_hmax_ps(min_v);
if (mode & 2)
max_s = _mm256_hmax_ps(max_v);
}
for (; i < len; i++) {
if (data[i] < min_s) {
min_s = data[i];
}
if (data[i] > max_s) {
max_s = data[i];
}
}
int id = 0;
if (mode & 1)
result[id++] = min_s;
if (mode & 2)
result[id++] = max_s;
}
inline EE array_minmax_value_f32(const F32 *data, I32 len, int mode, F32 *result)
{
EE ret = SUCCESS;
switch (mode) {
case 1:
array_minmax_value_f32_template<1>(data, len, result);
break;
case 2:
array_minmax_value_f32_template<2>(data, len, result);
break;
case 3:
array_minmax_value_f32_template<3>(data, len, result);
break;
default:
ret = NOT_SUPPORTED;
break;
}
return ret;
}
template <int mode>
inline static void array_minmax_value_i32_template(const I32 *data, I32 len, F32 *result)
{
I32 min_s = data[0];
I32 max_s = data[0];
I32 i = 0;
if (len >= 8) {
__m256i min_v, max_v, tmp_v;
min_v = max_v = _mm256_loadu_si256((__m256i const *)data);
for (i = 8; i < len - 7; i += 8) {
tmp_v = _mm256_loadu_si256((__m256i const *)(data + i));
if (mode & 1)
min_v = _mm256_min_epu32(tmp_v, min_v);
if (mode & 2)
max_v = _mm256_max_epu32(tmp_v, max_v);
}
if (mode & 1)
max_s = _mm256_hmax_epu32(min_v);
if (mode & 2)
max_s = _mm256_hmax_epu32(max_v);
}
for (; i < len; i++) {
if (data[i] < min_s) {
min_s = data[i];
}
if (data[i] > max_s) {
max_s = data[i];
}
}
int id = 0;
if (mode & 1)
result[id++] = min_s;
if (mode & 2)
result[id++] = max_s;
}
inline EE array_minmax_value_i32(const I32 *data, I32 len, int mode, F32 *result)
{
EE ret = SUCCESS;
switch (mode) {
case 1:
array_minmax_value_i32_template<1>(data, len, result);
break;
case 2:
array_minmax_value_i32_template<2>(data, len, result);
break;
case 3:
array_minmax_value_i32_template<3>(data, len, result);
break;
default:
ret = NOT_SUPPORTED;
break;
}
return ret;
}
// array var
inline F32 array_var_f32(const F32 *data, I32 len, F32 mean)
{
if (len <= 0) {
return 0;
}
I32 i = 0;
F32 sum_s = 0;
__m256 mean_v = _mm256_set1_ps(mean);
for (i = 0; i < len - 7; i += 8) {
__m256 in = _mm256_loadu_ps(data + i);
__m256 tmp_v = _mm256_sub_ps(in, mean_v);
__m256 sum_v = _mm256_mul_ps(tmp_v, tmp_v);
sum_s += _mm256_sum_ps(sum_v);
}
for (; i < len; i++) {
F32 tmp = data[i] - mean;
sum_s += tmp * tmp;
}
return sum_s / len;
}
// array sum
inline F32 array_sum_f32(const F32 *data, I32 len)
{
if (len <= 0) {
return 0;
}
I32 i = 0;
F32 sum_s = 0;
__m256 sum_v = _mm256_set1_ps(0);
for (i = 0; i < len - 7; i += 8) {
__m256 in = _mm256_loadu_ps(data + i);
sum_v = _mm256_add_ps(sum_v, in);
}
sum_s += _mm256_sum_ps(sum_v);
for (; i < len; i++) {
sum_s += data[i];
}
return sum_s;
}
inline I32 array_sum_i32(const I32 *data, I32 len)
{
if (len <= 0) {
return 0;
}
I32 i = 0;
I32 sum_s = 0;
__m256i sum_v = _mm256_set1_epi32(0);
for (i = 0; i < len - 7; i += 8) {
__m256i in = _mm256_loadu_si256((const __m256i *)(data + i));
sum_v = _mm256_add_epi32(sum_v, in);
}
sum_s += _mm256_sum_epi32(sum_v);
for (; i < len; i++) {
sum_s += data[i];
}
return sum_s;
}
// array mean
inline F32 array_mean_f32(const F32 *data, I32 len)
{
if (len <= 0) {
return 0;
}
return array_sum_f32(data, len) / len;
}
inline void array_add_f32(const F32 *inputA, const F32 *inputB, F32 *output, I32 len)
{
I32 i = 0;
for (i = 0; i < len - 7; i += 8) {
__m256 a = _mm256_loadu_ps(inputA + i);
__m256 b = _mm256_loadu_ps(inputB + i);
__m256 c = _mm256_add_ps(a, b);
_mm256_storeu_ps(output + i, c);
}
for (; i < len; i++) {
output[i] = inputA[i] + inputB[i];
}
}
inline void array_mul_f32(const F32 *inputA, const F32 *inputB, F32 *output, I32 len)
{
I32 i = 0;
for (i = 0; i < len - 7; i += 8) {
__m256 a = _mm256_loadu_ps(inputA + i);
__m256 b = _mm256_loadu_ps(inputB + i);
__m256 c = _mm256_mul_ps(a, b);
_mm256_storeu_ps(output + i, c);
}
for (; i < len; i++) {
output[i] = inputA[i] * inputB[i];
}
}
inline void array_mul_and_add_f32(
const F32 *inputA, const F32 *inputB, const F32 *inputC, F32 *output, I32 len)
{
I32 i = 0;
for (i = 0; i < len - 7; i += 8) {
__m256 a = _mm256_loadu_ps(inputA + i);
__m256 b;
if (inputA == inputB) {
b = a;
} else {
b = _mm256_loadu_ps(inputB + i);
}
__m256 c = _mm256_add_ps(_mm256_mul_ps(a, b), _mm256_loadu_ps(inputC + i));
_mm256_storeu_ps(output + i, c);
}
for (; i < len; i++) {
output[i] = inputA[i] * inputB[i] + inputC[i];
}
}
inline void array_max_f32(const F32 *inputA, const F32 *inputB, F32 *output, I32 len)
{
I32 i = 0;
for (; i < len - 7; i += 8) {
__m256 a = _mm256_loadu_ps(inputA + i);
__m256 b = _mm256_loadu_ps(inputB + i);
_mm256_storeu_ps(output + i, _mm256_max_ps(a, b));
}
for (; i < len; i++) {
output[i] = UNI_MAX(inputA[i], inputB[i]);
}
}
inline void array_norm_scalar_scale_fp32(
F32 *input, F32 *output, I32 len, F32 mean, F32 var, F32 *alpha, F32 *beta)
{
F32 eps = 1e-6;
F32 std_value = sqrt(var + eps);
__m256 mean_v = _mm256_set1_ps(mean);
__m256 std_v = _mm256_set1_ps(std_value);
__m256 alpha_v = _mm256_set1_ps(*alpha);
__m256 beta_v = _mm256_set1_ps(*beta);
I32 i = 0;
for (i = 0; i < len - 7; i += 8) {
__m256 in = _mm256_loadu_ps(input + i);
__m256 tmp_v = _mm256_sub_ps(in, mean_v);
tmp_v = _mm256_div_ps(tmp_v, std_v);
tmp_v = _mm256_fmadd_ps(alpha_v, tmp_v, beta_v);
_mm256_storeu_ps(output + i, tmp_v);
}
for (; i < len; i++) {
output[i] = *alpha * (input[i] - mean) / std_value + *beta;
}
}
#endif //CHEETAH_X86_FUNCTION_FP32_H
|
pi.c
|
#include<stdio.h>
#include<omp.h>
int main(int argc, char *argv[]){
int nThreads = 4;
omp_set_num_threads(nThreads);
unsigned long long n = 100000000;
//scanf("%ld", &n);
double sum = 0, step = 1.0/((double)n);
/*
* FOR
* schedule(type, [chunk])
* shared(list)
* private(list)
* firstprivate(list)
* lastprivate(list)
* reduction(operator: list)
* nowait
* ordered
*/
#pragma omp parallel for reduction(+: sum)
for(unsigned long long i = 0; i < n; i++){
sum += 4.0/(1.0 + ((i + 0.5) * step)*((i + 0.5) * step));
}
printf("Pi = %.20lf\n", step*sum);
return 0;
}
|
mafillvmain.c
|
/* CalculiX - A 3-dimensional finite element program */
/* Copyright (C) 1998-2015 Guido Dhondt */
/* This program is free software; you can redistribute it and/or */
/* modify it under the terms of the GNU General Public License as */
/* published by the Free Software Foundation(version 2); */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* You should have received a copy of the GNU General Public License */
/* along with this program; if not, write to the Free Software */
/* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */
#include <unistd.h>
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <pthread.h>
#include "CalculiX.h"
static char *lakonf1;
static ITG num_cpus,*nef1,*ipnei1,*neifa1,*neiel1,*jq1,*irow1,*nzs1,*ielfa1,*
ifabou1,*nbody1,*neq1,*nactdohinv1;
static double *auv1=NULL,*adv1=NULL,*bv1=NULL,*vfa1,*xxn1,*area1,*vel1,
*cosa1,*umfa1,*xlet1,*xle1,*gradvfa1,*xxi1,*body1,*volume1,*dtimef1,
*velo1,*veloo1,*sel1,*xrlfa1,*gamma1,*xxj1,*a11,*a21,*a31,*flux1;
void mafillvmain(ITG *nef,ITG *ipnei,ITG *neifa,ITG *neiel,
double *vfa,double *xxn,double *area,double *auv,double *adv,
ITG *jq,ITG *irow,ITG *nzs,double *bv,double *vel,double *cosa,
double *umfa,double *xlet,double *xle,double *gradvfa,
double *xxi,double *body,double *volume,
ITG *ielfa,char *lakonf,ITG *ifabou,ITG *nbody,ITG *neq,
double *dtimef,double *velo,double *veloo,
double *sel,double *xrlfa,double *gamma,double *xxj,
ITG *nactdohinv,double *a1,double *a2,double *a3,double *flux){
ITG i,j;
/* variables for multithreading procedure */
ITG sys_cpus,*ithread=NULL;
char *env,*envloc,*envsys;
num_cpus = 0;
sys_cpus=0;
/* explicit user declaration prevails */
envsys=getenv("NUMBER_OF_CPUS");
if(envsys){
sys_cpus=atoi(envsys);
if(sys_cpus<0) sys_cpus=0;
}
/* automatic detection of available number of processors */
if(sys_cpus==0){
sys_cpus = getSystemCPUs();
if(sys_cpus<1) sys_cpus=1;
}
/* local declaration prevails, if strictly positive */
envloc = getenv("CCX_NPROC_CFD");
if(envloc){
num_cpus=atoi(envloc);
if(num_cpus<0){
num_cpus=0;
}else if(num_cpus>sys_cpus){
num_cpus=sys_cpus;
}
}
/* else global declaration, if any, applies */
env = getenv("OMP_NUM_THREADS");
if(num_cpus==0){
if (env)
num_cpus = atoi(env);
if (num_cpus < 1) {
num_cpus=1;
}else if(num_cpus>sys_cpus){
num_cpus=sys_cpus;
}
}
// next line is to be inserted in a similar way for all other paralell parts
if(*nef<num_cpus) num_cpus=*nef;
pthread_t tid[num_cpus];
/* allocating fields for lhs and rhs matrix */
NNEW(adv1,double,num_cpus**neq);
NNEW(auv1,double,(long long)num_cpus*2**nzs);
NNEW(bv1,double,num_cpus*3**neq);
/* calculating the stiffness and/or mass matrix
(symmetric part) */
nef1=nef;ipnei1=ipnei;neifa1=neifa;neiel1=neiel;vfa1=vfa;xxn1=xxn;
area1=area;jq1=jq;irow1=irow;nzs1=nzs;vel1=vel;cosa1=cosa;umfa1=umfa;
xlet1=xlet;xle1=xle;gradvfa1=gradvfa;xxi1=xxi;body1=body;volume1=volume;
ielfa1=ielfa;lakonf1=lakonf;ifabou1=ifabou;nbody1=nbody;neq1=neq;
dtimef1=dtimef;velo1=velo;veloo1=veloo;sel1=sel;xrlfa1=xrlfa;
gamma1=gamma;xxj1=xxj;nactdohinv1=nactdohinv;a11=a1;a21=a2;a31=a3;
flux1=flux;
/* create threads and wait */
NNEW(ithread,ITG,num_cpus);
for(i=0; i<num_cpus; i++) {
ithread[i]=i;
pthread_create(&tid[i], NULL, (void *)mafillvmt, (void *)&ithread[i]);
}
for(i=0; i<num_cpus; i++) pthread_join(tid[i], NULL);
SFREE(ithread);
/* copying and accumulating the stiffnes and/or mass matrix */
#pragma omp parallel \
default(none) \
shared(neq,adv,adv1,num_cpus,nzs,auv,auv1,bv,bv1) \
private(i,j)
{
#pragma omp for
for(i=0;i<*neq;i++){
adv[i]=adv1[i];
for(j=1;j<num_cpus;j++){
adv[i]+=adv1[i+j**neq];
}
}
#pragma omp for
for(i=0;i<2**nzs;i++){
auv[i]=auv1[i];
for(j=1;j<num_cpus;j++){
auv[i]+=auv1[i+(long long)j*2**nzs];
}
}
#pragma omp for
for(i=0;i<3**neq;i++){
bv[i]=bv1[i];
for(j=1;j<num_cpus;j++){
bv[i]+=bv1[i+j*3**neq];
}
}
}
SFREE(adv1);
SFREE(auv1);
SFREE(bv1);
return;
}
/* subroutine for multithreading of mafillv */
void *mafillvmt(ITG *i){
ITG indexadv,indexbv,nefa,nefb,nefdelta;
long long indexauv;
indexadv=*i**neq1;
indexauv=(long long)*i*2**nzs1;
indexbv=*i*3**neq1;
// ceil -> floor
nefdelta=(ITG)floor(*nef1/(double)num_cpus);
nefa=*i*nefdelta+1;
nefb=(*i+1)*nefdelta;
// next line! -> all parallel sections
if((*i==num_cpus-1)&&(nefb<*nef1)) nefb=*nef1;
FORTRAN(mafillv,(nef1,ipnei1,neifa1,neiel1,vfa1,xxn1,area1,
&auv1[indexauv],&adv1[indexadv],jq1,irow1,nzs1,&bv1[indexbv],
vel1,cosa1,umfa1,xlet1,xle1,gradvfa1,xxi1,
body1,volume1,ielfa1,lakonf1,ifabou1,nbody1,neq1,
dtimef1,velo1,veloo1,sel1,xrlfa1,gamma1,xxj1,nactdohinv1,a11,
a21,a31,flux1,&nefa,&nefb));
return NULL;
}
|
matrixmultiply-ompacc2.c
|
/*
Naive matrix-matrix multiplication(mmm)
multiple GPUs, standard OpenMP 4.0 directives
By C. Liao
*/
#include <stdio.h>
#include <assert.h>
#include <omp.h>
#define N 1024
#define M 1024
#define K 1024
#define REAL float
int i,j,k;
REAL a[N][M],b[M][K],c[N][K], c2[N][K];
int init();
int mmm();
int mmm2();
int verify();
//#define MAX_GPU_COUNT 4
int main(void)
{
init();
mmm();
mmm2();
return verify();
}
int init()
{
for (i=0;i<N;i++)
for(j=0;j<M;j++)
a[i][j]=3.0*i*j/N/M;
for (i=0;i<M;i++)
for(j=0;j<K;j++)
b[i][j]=5.0*j*i/N/M;
for (i=0;i<N;i++)
for(j=0;j<K;j++)
{
c[i][j]=0.0;
c2[i][j]=0.0;
}
return 0;
}
/*
TODO: try different i,j,k orders
a b e f a*e+ b*g , a*f+ b*h
c d x g h = c*e+ d*g, c*f+ d*h
*/
int mmm()
{
int GPU_N , idev;
int n = N;
// GPU_N = xomp_get_num_devices();
GPU_N = 1;
printf("CUDA-capable device count: %i\n", GPU_N);
#if 0
if (GPU_N > MAX_GPU_COUNT)
{
GPU_N = MAX_GPU_COUNT;
}
assert (GPU_N>0 && GPU_N<=MAX_GPU_COUNT);
#endif
omp_set_num_threads(GPU_N);
#pragma omp parallel shared (GPU_N, a, b, c, n) private(idev)
// for (idev = 0; idev < GPU_N; idev++)
{
int tid = omp_get_thread_num();
// cudaSetDevice(tid);
xomp_set_default_device (tid);
long size ;
long offset;
#if 0
int size = n / GPU_N;
int offset = size * tid;
if(tid < n%GPU_N)
{
size++;
}
if(tid >= n%GPU_N)
offset += n%GPU_N;
else
offset += tid;
#endif
XOMP_static_even_divide (0, n, GPU_N, tid, &offset, &size);
printf("thread %d working on GPU devices %d with size %ld copying data from y_ompacc with offset %ld\n",tid, tid, size,offset);
int i, j, k;
#pragma omp target device (tid) map(tofrom:c[offset:size][0:n]), map(to:a[offset:size][0:n],b[0:n][0:n], offset,size,n)
#pragma omp parallel for private(i,j,k) shared (a,b,c, n, offset, size)
for (i = offset; i < offset + size; i++)
for (j = 0; j < M; j++)
for (k = 0; k < K; k++)
c[i][j]= c[i][j]+a[i][k]*b[k][j];
}
return 0;
}
int mmm2()
{
for (i = 0; i < N; i++)
for (j = 0; j < M; j++)
for (k = 0; k < K; k++)
c2[i][j]= c2[i][j]+a[i][k]*b[k][j];
return 0;
}
int verify()
{
REAL sum=0.0, sum2=0.0;
for (i=0;i<N;i++)
for(j=0;j<K;j++)
{
sum+=c[i][j];
sum2+=c2[i][j];
}
printf("sum of c[i][j] is %f\n",sum);
printf("sum of c2[i][j] is %f\n",sum2);
assert (sum == sum2);
return 0;
}
|
HDAA_fmt_plug.c
|
/* HTTP Digest access authentication patch for john
*
* Written by Romain Raboin. OMP and intrinsics support by magnum
*
* This software is Copyright (c) 2008 Romain Raboin - romain.raboin at
* gmail.com, and Copyright (c) 2012 magnum and it is hereby released to
* the general public under the following terms: Redistribution and
* use in source and binary forms, with or without modification, are
* permitted.
*/
#if FMT_EXTERNS_H
extern struct fmt_main fmt_HDAA;
#elif FMT_REGISTERS_H
john_register_one(&fmt_HDAA);
#else
#include <stdint.h>
#include <string.h>
#ifdef __MMX__
#include <mmintrin.h>
#endif
#include "arch.h"
#include "misc.h"
#include "common.h"
#include "formats.h"
#include "md5.h"
#include "simd-intrinsics.h"
#define ALGORITHM_NAME "MD5 " MD5_ALGORITHM_NAME
#if !FAST_FORMATS_OMP
#undef _OPENMP
#endif
#if defined(_OPENMP)
#include <omp.h>
#endif
#include "memdbg.h"
#define FORMAT_LABEL "hdaa"
#define FORMAT_NAME "HTTP Digest access authentication"
#define BENCHMARK_COMMENT ""
#define BENCHMARK_LENGTH 0
#define PLAINTEXT_LENGTH 32
#define CIPHERTEXT_LENGTH 32
#define BINARY_SIZE 16
#define BINARY_ALIGN 4
#define SALT_SIZE sizeof(reqinfo_t)
#define SALT_ALIGN 4
#if defined(_OPENMP)
static unsigned int omp_t = 1;
#ifdef SIMD_COEF_32
#ifndef OMP_SCALE
#define OMP_SCALE 256
#endif
#else
#ifndef OMP_SCALE
#define OMP_SCALE 64
#endif
#endif
#endif
#ifdef SIMD_COEF_32
#define NBKEYS (SIMD_COEF_32 * SIMD_PARA_MD5)
#define MIN_KEYS_PER_CRYPT NBKEYS
#define MAX_KEYS_PER_CRYPT NBKEYS
#define GETPOS(i, index) ( (index&(SIMD_COEF_32-1))*4 + ((i)&60)*SIMD_COEF_32 + ((i)&3) + (unsigned int)index/SIMD_COEF_32*64*SIMD_COEF_32 )
#define GETOUTPOS(i, index) ( (index&(SIMD_COEF_32-1))*4 + ((i)&0x1c)*SIMD_COEF_32 + ((i)&3) + (unsigned int)index/SIMD_COEF_32*16*SIMD_COEF_32 )
#else
#define MIN_KEYS_PER_CRYPT 1
#define MAX_KEYS_PER_CRYPT 1
#endif
#define SEPARATOR '$'
#define MAGIC "$response$"
#define MAGIC_LEN (sizeof(MAGIC)-1)
#define SIZE_TAB 12
// This is 8 x 64 bytes, so in MMX/SSE2 we support up to 9 limbs of MD5
#define HTMP 512
typedef struct
{
size_t h1tmplen;
size_t h3tmplen;
char h1tmp[HTMP];
char h3tmp[HTMP];
} reqinfo_t;
/*
digest authentication scheme :
h1 = md5(user:realm:password)
h2 = md5(method:digestURI)
response = h3 = md5(h1:nonce:nonceCount:ClientNonce:qop:h2)
*/
/* request information */
enum e_req {
R_RESPONSE,
R_USER,
R_REALM,
R_METHOD,
R_URI,
R_NONCE,
R_NONCECOUNT,
R_CLIENTNONCE,
R_QOP
};
/* response:user:realm:method:uri:nonce:nonceCount:ClientNonce:qop */
static struct fmt_tests tests[] = {
{"$response$679066476e67b5c7c4e88f04be567f8b$user$myrealm$GET$/$8c12bd8f728afe56d45a0ce846b70e5a$00000001$4b61913cec32e2c9$auth", "nocode"},
{"$response$faa6cb7d676e5b7c17fcbf966436aa0c$moi$myrealm$GET$/$af32592775d27b1cd06356b3a0db9ddf$00000001$8e1d49754a25aea7$auth", "kikou"},
{"$response$56940f87f1f53ade8b7d3c5a102c2bf3$usrx$teN__chars$GET$/4TLHS1TMN9cfsbqSUAdTG3CRq7qtXMptnYfn7mIIi3HRKOMhOks56e$2c0366dcbc$00000001$0153$auth", "passWOrd"},
{"$response$8663faf2337dbcb2c52882807592ec2c$user$myrealm$GET$/$8c12bd8f728afe56d45a0ce846b70e5a$", "pass"},
{"$response$8663faf2337dbcb2c52882807592ec2c$user$myrealm$GET$/$8c12bd8f728afe56d45a0ce846b70e5a", "pass"},
{NULL}
};
/* used by set_key */
static char (*saved_plain)[PLAINTEXT_LENGTH + 1];
#ifdef SIMD_COEF_32
#define LIMBS 9
static unsigned char *saved_key[LIMBS];
static unsigned int *interm_key;
static unsigned int *crypt_key;
#else
static int (*saved_len);
static unsigned char (*crypt_key)[BINARY_SIZE];
#endif
/* Store information about the request ()*/
static reqinfo_t *rinfo = NULL;
static void init(struct fmt_main *self)
{
#ifdef SIMD_COEF_32
int i;
#endif
#if defined (_OPENMP)
omp_t = omp_get_max_threads();
self->params.min_keys_per_crypt *= omp_t;
omp_t *= OMP_SCALE;
self->params.max_keys_per_crypt *= omp_t;
#endif
#ifdef SIMD_COEF_32
for (i = 0; i < LIMBS; i++)
saved_key[i] = mem_calloc_align(self->params.max_keys_per_crypt,
64, MEM_ALIGN_SIMD);
interm_key = mem_calloc_align(self->params.max_keys_per_crypt,
16, MEM_ALIGN_SIMD);
crypt_key = mem_calloc_align(self->params.max_keys_per_crypt,
16, MEM_ALIGN_SIMD);
#else
saved_len = mem_calloc(self->params.max_keys_per_crypt,
sizeof(*saved_len));
crypt_key = mem_calloc(self->params.max_keys_per_crypt,
sizeof(*crypt_key));
#endif
saved_plain = mem_calloc(self->params.max_keys_per_crypt,
sizeof(*saved_plain));
}
static void done(void)
{
#ifdef SIMD_COEF_32
int i;
#endif
MEM_FREE(saved_plain);
MEM_FREE(crypt_key);
#ifdef SIMD_COEF_32
MEM_FREE(interm_key);
for (i = 0; i < LIMBS; i++)
MEM_FREE(saved_key[i]);
#else
MEM_FREE(saved_len);
#endif
}
static int valid(char *ciphertext, struct fmt_main *self)
{
char *ctcopy, *keeptr, *p;
if (strncmp(ciphertext, MAGIC, MAGIC_LEN) != 0)
return 0;
ctcopy = strdup(ciphertext);
keeptr = ctcopy;
ctcopy += MAGIC_LEN;
if ((p = strtokm(ctcopy, "$")) == NULL) /* hash */
goto err;
if (!ishexlc(p) || strlen(p) != 32)
goto err;
if ((p = strtokm(NULL, "$")) == NULL) /* user */
goto err;
if ((p = strtokm(NULL, "$")) == NULL) /* realm */
goto err;
if ((p = strtokm(NULL, "$")) == NULL) /* method */
goto err;
if ((p = strtokm(NULL, "$")) == NULL) /* uri */
goto err;
if ((p = strtokm(NULL, "$")) == NULL) /* nonce */
goto err;
if ((p = strtokm(NULL, "$")) == NULL) /* End of legacy HDAA or noncecount */
goto end_hdaa_legacy;
if ((p = strtokm(NULL, "$")) == NULL) /* clientnonce */
goto err;
if (!ishexlc(p) )
goto err;
if ((p = strtokm(NULL, "$")) == NULL) /* qop */
goto err;
if ((p = strtokm(NULL, "$")) != NULL)
goto err;
end_hdaa_legacy:
MEM_FREE(keeptr);
return 1;
err:
MEM_FREE(keeptr);
return 0;
}
// Normalize shorter hashes, to allow with or without trailing '$' character.
static char *split(char *ciphertext, int index, struct fmt_main *self)
{
char *cp;
if (strncmp(ciphertext, MAGIC, MAGIC_LEN))
return ciphertext;
cp = ciphertext + MAGIC_LEN;
cp = strchr(cp, '$'); if (!cp) return ciphertext;
cp = strchr(cp+1, '$'); if (!cp) return ciphertext;
cp = strchr(cp+1, '$'); if (!cp) return ciphertext;
cp = strchr(cp+1, '$'); if (!cp) return ciphertext;
cp = strchr(cp+1, '$'); if (!cp) return ciphertext;
// now if we have $binary_hash$ then we remove the last '$' char
if (strlen(cp) == 1 + BINARY_SIZE*2 + 1) {
static char out[256];
strnzcpy(out, ciphertext, sizeof(out));
out[strlen(out)-1] = 0;
return out;
}
return ciphertext;
}
static void set_salt(void *salt)
{
rinfo = salt;
}
static void set_key(char *key, int index)
{
strcpy(saved_plain[index], key);
#ifndef SIMD_COEF_32
saved_len[index] = -1;
#endif
}
static char *get_key(int index)
{
return saved_plain[index];
}
static int cmp_all(void *binary, int count)
{
#ifdef SIMD_COEF_32
unsigned int x,y=0;
#ifdef _OPENMP
for (; y < SIMD_PARA_MD5 * omp_t; y++)
#else
for (; y < SIMD_PARA_MD5; y++)
#endif
for (x = 0; x < SIMD_COEF_32; x++)
{
if ( ((uint32_t*)binary)[0] == ((uint32_t*)crypt_key)[y*SIMD_COEF_32*4+x] )
return 1;
}
return 0;
#else
int index;
for (index = 0; index < count; index++)
if (!(memcmp(binary, crypt_key[index], BINARY_SIZE)))
return 1;
return 0;
#endif
}
static int cmp_one(void *binary, int index)
{
#ifdef SIMD_COEF_32
unsigned int i,x,y;
x = index&(SIMD_COEF_32-1);
y = (unsigned int)index/SIMD_COEF_32;
for (i=0;i<(BINARY_SIZE/4);i++)
if ( ((uint32_t*)binary)[i] != ((uint32_t*)crypt_key)[y*SIMD_COEF_32*4+i*SIMD_COEF_32+x] )
return 0;
return 1;
#else
return !(memcmp(binary, crypt_key[index], BINARY_SIZE));
#endif
}
static int cmp_exact(char *source, int index)
{
return 1;
}
/* convert hash from binary to ascii */
#ifdef SIMD_COEF_32
// This code should be rewritten in intrinsics, reading from
// MMX or SSE2 output buffers and writing to MMX/SSE2 input buffers.
inline static void sse_bin2ascii(unsigned char *conv, unsigned char *src)
{
unsigned int index;
for (index = 0; index < NBKEYS; index++) {
unsigned int i, j = 0;
for (i = 0; i < BINARY_SIZE; i += 2) {
unsigned int t;
t = (src[GETOUTPOS((i + 1), index)] & 0x0f);
t <<= 12;
t |= (src[GETOUTPOS((i + 1), index)] & 0xf0);
t <<= 4;
t |= (src[GETOUTPOS(i, index)] & 0x0f);
t <<= 8;
t |= ((src[GETOUTPOS(i, index)] & 0xf0) >> 4);
t += 0x06060606;
t += ((((t >> 4) & 0x01010101) * 0x27) + 0x2a2a2a2a);
*(unsigned int*)&conv[GETPOS(j, index)] = t;
j+=4;
}
}
}
#endif /* SIMD_COEF_32 */
#ifdef __MMX__
inline static void bin2ascii(__m64 *conv, __m64 *src)
{
unsigned int i = 0;
while (i != 4) {
__m64 l;
__m64 r;
__m64 t;
__m64 u;
__m64 v;
/* 32 bits to 64 bits */
t = _mm_set1_pi32(0x0f0f0f0f);
/* Bit-wise AND the 64-bit values in M1 and M2. */
u = _mm_and_si64(_mm_srli_si64(src[(i / 2)], 4), t);
v = _mm_and_si64(src[(i / 2)], t);
/* interleaving */
l = _mm_unpacklo_pi8(u, v);
r = _mm_unpackhi_pi8(u, v);
t = _mm_set1_pi32(0x06060606);
l = _mm_add_pi32(l, t);
r = _mm_add_pi32(r, t);
t = _mm_set1_pi32(0x01010101);
/* u = (l << 4) & t */
u = _mm_and_si64(_mm_srli_si64(l, 4), t);
/* v = (r << 4) & t */
v = _mm_and_si64(_mm_srli_si64(r, 4), t);
t = _mm_set1_pi32(0x00270027);
/* Multiply four 16-bit values in M1 by four 16-bit values in M2 and produce
the low 16 bits of the results. */
u = _mm_mullo_pi16(u, t);
v = _mm_mullo_pi16(v, t);
t = _mm_set1_pi32(0x2a2a2a2a);
u = _mm_add_pi32(u, t);
v = _mm_add_pi32(v, t);
conv[(i++)] = _mm_add_pi32(l, u);
conv[(i++)] = _mm_add_pi32(r, v);
}
__asm__ __volatile__("emms");
}
#else
inline static void bin2ascii(uint32_t *conv, uint32_t *source)
{
unsigned char *src = (unsigned char*)source;
unsigned int i;
unsigned int j = 0;
uint32_t t = 0;
for (i = 0; i < BINARY_SIZE; i += 2) {
#if (ARCH_LITTLE_ENDIAN == 0)
t = (src[i] & 0xf0);
t *= 0x10;
t += (src[i] & 0x0f);
t *= 0x1000;
t += (src[(i + 1)] & 0xf0);
t *= 0x10;
t += (src[(i + 1)] & 0x0f);
#else
t = (src[(i + 1)] & 0x0f);
t *= 0x1000;
t += (src[(i + 1)] & 0xf0);
t *= 0x10;
t += (src[i] & 0x0f);
t *= 0x100;
t += ((src[i] & 0xf0) >> 4);
#endif
t += 0x06060606;
t += ((((t >> 4) & 0x01010101) * 0x27) + 0x2a2a2a2a);
conv[(j++)] = t;
}
}
#endif /* MMX */
#if SIMD_COEF_32
inline static void crypt_done(unsigned const int *source, unsigned int *dest, int index)
{
unsigned int i;
unsigned const int *s = &source[(index&(SIMD_COEF_32-1)) + (unsigned int)index/SIMD_COEF_32*4*SIMD_COEF_32];
unsigned int *d = &dest[(index&(SIMD_COEF_32-1)) + (unsigned int)index/SIMD_COEF_32*4*SIMD_COEF_32];
for (i = 0; i < BINARY_SIZE / 4; i++) {
*d = *s;
s += SIMD_COEF_32;
d += SIMD_COEF_32;
}
}
#endif
static int crypt_all(int *pcount, struct db_salt *salt)
{
const int count = *pcount;
#if SIMD_COEF_32
#if defined(_OPENMP)
#define ti (thread*NBKEYS+index)
int thread;
#pragma omp parallel for
for (thread = 0; thread < (count+NBKEYS-1)/NBKEYS; thread++)
#else
#define thread 0
#define ti index
#endif
{
static unsigned int crypt_len[NBKEYS];
unsigned int index, i, shortest, longest;
for (index = 0; index < NBKEYS; index++)
{
int len;
char temp;
const char *key;
key = rinfo->h1tmp;
for (len = 0; len < rinfo->h1tmplen; len += 4, key += 4)
*(uint32_t*)&saved_key[len>>6][GETPOS(len, ti)] = *(uint32_t*)key;
len = rinfo->h1tmplen;
key = (char*)&saved_plain[ti];
while((temp = *key++)) {
saved_key[len>>6][GETPOS(len, ti)] = temp;
len++;
}
saved_key[len>>6][GETPOS(len, ti)] = 0x80;
// Clean rest of this buffer
i = len;
while (++i & 3)
saved_key[i>>6][GETPOS(i, ti)] = 0;
for (; i < (((len+8)>>6)+1)*64; i += 4)
*(uint32_t*)&saved_key[i>>6][GETPOS(i, ti)] = 0;
((unsigned int *)saved_key[(len+8)>>6])[14*SIMD_COEF_32 + (ti&(SIMD_COEF_32-1)) + (ti/SIMD_COEF_32)*16*SIMD_COEF_32] = len << 3;
}
SIMDmd5body(&saved_key[0][thread*64*NBKEYS], &crypt_key[thread*4*NBKEYS], NULL, SSEi_MIXED_IN);
sse_bin2ascii((unsigned char*)&saved_key[0][thread*64*NBKEYS], (unsigned char*)&crypt_key[thread*4*NBKEYS]);
longest = 0; shortest = HTMP;
for (index = 0; index < NBKEYS; index++)
{
const char *key;
int i, len;
len = CIPHERTEXT_LENGTH - 1;
key = rinfo->h3tmp + CIPHERTEXT_LENGTH;
// Copy a char at a time until aligned at destination
while (++len & 3)
saved_key[len>>6][GETPOS(len, ti)] = *key++;
// ...then a word at a time. This is a good boost, we are copying over 100 bytes.
for (;len < rinfo->h3tmplen; len += 4, key += 4)
*(uint32_t*)&saved_key[len>>6][GETPOS(len, ti)] = *(uint32_t*)key;
len = rinfo->h3tmplen;
saved_key[len>>6][GETPOS(len, ti)] = 0x80;
// Clean rest of this buffer
i = len;
while (++i & 3)
saved_key[i>>6][GETPOS(i, ti)] = 0;
//for (; i < (((len+8)>>6)+1)*64; i += 4)
for (; i <= crypt_len[index]; i += 4)
*(uint32_t*)&saved_key[i>>6][GETPOS(i, ti)] = 0;
((unsigned int *)saved_key[(len+8)>>6])[14*SIMD_COEF_32 + (ti&(SIMD_COEF_32-1)) + (ti/SIMD_COEF_32)*16*SIMD_COEF_32] = len << 3;
crypt_len[index] = len;
if (len > longest)
longest = len;
if (len < shortest)
shortest = len;
}
// First limb
SIMDmd5body(&saved_key[0][thread*64*NBKEYS], &interm_key[thread*4*NBKEYS], NULL, SSEi_MIXED_IN);
// Copy any output that is done now
if (shortest < 56) {
if (longest < 56)
memcpy(&crypt_key[thread*4*NBKEYS], &interm_key[thread*4*NBKEYS], 16*NBKEYS);
else
for (index = 0; index < NBKEYS; index++)
if (crypt_len[index] < 56)
crypt_done(interm_key, crypt_key, ti);
}
// Do the rest of the limbs
for (i = 1; i < (((longest + 8) >> 6) + 1); i++) {
SIMDmd5body(&saved_key[i][thread*64*NBKEYS], &interm_key[thread*4*NBKEYS], &interm_key[thread*4*NBKEYS], SSEi_RELOAD|SSEi_MIXED_IN);
// Copy any output that is done now
if (shortest < i*64+56) {
if (shortest > (i-1)*64+55 && longest < i*64+56)
memcpy(&crypt_key[thread*4*NBKEYS], &interm_key[thread*4*NBKEYS], 16*NBKEYS);
else
for (index = 0; index < NBKEYS; index++)
if (((crypt_len[index] + 8) >> 6) == i)
crypt_done(interm_key, crypt_key, ti);
}
}
}
#undef thread
#undef ti
#else
int index = 0;
#ifdef _OPENMP
#pragma omp parallel for
for (index = 0; index < count; index++)
#endif
{
MD5_CTX ctx;
int len;
#ifdef _OPENMP
char h3tmp[HTMP];
char h1tmp[HTMP];
#else
char *h3tmp;
char *h1tmp;
#endif
size_t tmp;
#ifdef __MMX__
__m64 h1[BINARY_SIZE / sizeof(__m64)];
__m64 conv[CIPHERTEXT_LENGTH / sizeof(__m64) + 1];
#else
uint32_t h1[BINARY_SIZE / sizeof(uint32_t)];
uint32_t conv[(CIPHERTEXT_LENGTH / sizeof(uint32_t)) + 1];
#endif
tmp = rinfo->h1tmplen;
if ((len = saved_len[index]) < 0)
len = saved_len[index] = strlen(saved_plain[index]);
#ifdef _OPENMP
memcpy(h1tmp, rinfo->h1tmp, tmp);
memcpy(h3tmp + CIPHERTEXT_LENGTH, rinfo->h3tmp + CIPHERTEXT_LENGTH, rinfo->h3tmplen - CIPHERTEXT_LENGTH);
#else
h3tmp = rinfo->h3tmp;
h1tmp = rinfo->h1tmp;
#endif
memcpy(&h1tmp[tmp], saved_plain[index], len);
MD5_Init(&ctx);
MD5_Update(&ctx, h1tmp, len + tmp);
MD5_Final((unsigned char*)h1, &ctx);
bin2ascii(conv, h1);
memcpy(h3tmp, conv, CIPHERTEXT_LENGTH);
MD5_Init(&ctx);
MD5_Update(&ctx, h3tmp, rinfo->h3tmplen);
MD5_Final(crypt_key[index], &ctx);
}
#endif
return count;
}
static char *mystrndup(const char *s, size_t n)
{
size_t tmp;
size_t size;
char *ret;
for (tmp = 0; s[tmp] != 0 && tmp <= n; tmp++);
size = n;
if (tmp < size)
size = tmp;
if ((ret = mem_alloc(sizeof(char) * size + 1)) == NULL)
return NULL;
memmove(ret, s, size);
ret[size] = 0;
return ret;
}
static size_t reqlen(char *str)
{
size_t len;
for (len = 0; str[len] != 0 && str[len] != SEPARATOR; len++);
return len;
}
static void *get_salt(char *ciphertext)
{
int nb;
int i;
char *request[SIZE_TAB];
char *str;
static reqinfo_t *r;
#ifdef __MMX__
__m64 h2[BINARY_SIZE / sizeof(__m64)];
__m64 conv[CIPHERTEXT_LENGTH / sizeof(__m64) + 1];
#else
unsigned int h2[BINARY_SIZE / sizeof(unsigned int)];
uint32_t conv[(CIPHERTEXT_LENGTH / sizeof(uint32_t)) + 1];
#endif
MD5_CTX ctx;
/* parse the password string */
if (!r) r = mem_alloc_tiny(sizeof(*r), MEM_ALIGN_WORD);
memset(r, 0, sizeof(*r));
for (nb = 0, i = 1; ciphertext[i] != 0; i++) {
if (ciphertext[i] == SEPARATOR) {
i++;
request[nb] = mystrndup(&ciphertext[i], reqlen(&ciphertext[i]));
nb++;
if (!ciphertext[i])
break;
}
}
while (nb < SIZE_TAB) {
request[nb++] = NULL;
}
/* calculate h2 (h2 = md5(method:digestURI))*/
str = mem_alloc(strlen(request[R_METHOD]) + strlen(request[R_URI]) + 2);
sprintf(str, "%s:%s", request[R_METHOD], request[R_URI]);
MD5_Init(&ctx);
MD5_Update(&ctx, str, strlen(str));
MD5_Final((unsigned char*)h2, &ctx);
memset(conv, 0, CIPHERTEXT_LENGTH + 1);
bin2ascii(conv, h2);
MEM_FREE(str);
/* create a part of h1 (h1tmp = request:realm:)*/
snprintf(r->h1tmp, HTMP - PLAINTEXT_LENGTH, "%s:%s:", request[R_USER], request[R_REALM]);
/* create a part of h3 (h3tmp = nonce:noncecount:clientnonce:qop:h2)*/
if (request[R_CLIENTNONCE] == NULL)
snprintf(&r->h3tmp[CIPHERTEXT_LENGTH], HTMP - CIPHERTEXT_LENGTH, ":%s:%s",
request[R_NONCE], (char*)conv);
else
snprintf(&r->h3tmp[CIPHERTEXT_LENGTH], HTMP - CIPHERTEXT_LENGTH, ":%s:%s:%s:%s:%s",
request[R_NONCE], request[R_NONCECOUNT], request[R_CLIENTNONCE],
request[R_QOP], (char*)conv);
r->h1tmplen = strlen(r->h1tmp);
r->h3tmplen = strlen(&r->h3tmp[CIPHERTEXT_LENGTH]) + CIPHERTEXT_LENGTH;
for (nb=0; nb < SIZE_TAB; ++nb) {
MEM_FREE(request[nb]);
}
return r;
}
/* convert response to binary form */
static void *get_binary(char *ciphertext)
{
static unsigned int realcipher[BINARY_SIZE / sizeof(int)];
int i;
ciphertext += 10;
for (i = 0; i < BINARY_SIZE; i++) {
((unsigned char*)realcipher)[i] = atoi16[ARCH_INDEX(ciphertext[i * 2])] * 16 +
atoi16[ARCH_INDEX(ciphertext[i * 2 + 1])];
}
return (void*) realcipher;
}
#ifdef SIMD_COEF_32
#define HASH_OFFSET (index&(SIMD_COEF_32-1))+((unsigned int)index/SIMD_COEF_32)*SIMD_COEF_32*4
static int get_hash_0(int index) { return ((uint32_t *)crypt_key)[HASH_OFFSET] & PH_MASK_0; }
static int get_hash_1(int index) { return ((uint32_t *)crypt_key)[HASH_OFFSET] & PH_MASK_1; }
static int get_hash_2(int index) { return ((uint32_t *)crypt_key)[HASH_OFFSET] & PH_MASK_2; }
static int get_hash_3(int index) { return ((uint32_t *)crypt_key)[HASH_OFFSET] & PH_MASK_3; }
static int get_hash_4(int index) { return ((uint32_t *)crypt_key)[HASH_OFFSET] & PH_MASK_4; }
static int get_hash_5(int index) { return ((uint32_t *)crypt_key)[HASH_OFFSET] & PH_MASK_5; }
static int get_hash_6(int index) { return ((uint32_t *)crypt_key)[HASH_OFFSET] & PH_MASK_6; }
#else
static int get_hash_0(int index) { return *(uint32_t*)&crypt_key[index] & PH_MASK_0; }
static int get_hash_1(int index) { return *(uint32_t*)&crypt_key[index] & PH_MASK_1; }
static int get_hash_2(int index) { return *(uint32_t*)&crypt_key[index] & PH_MASK_2; }
static int get_hash_3(int index) { return *(uint32_t*)&crypt_key[index] & PH_MASK_3; }
static int get_hash_4(int index) { return *(uint32_t*)&crypt_key[index] & PH_MASK_4; }
static int get_hash_5(int index) { return *(uint32_t*)&crypt_key[index] & PH_MASK_5; }
static int get_hash_6(int index) { return *(uint32_t*)&crypt_key[index] & PH_MASK_6; }
#endif
struct fmt_main fmt_HDAA = {
{
FORMAT_LABEL,
FORMAT_NAME,
ALGORITHM_NAME,
BENCHMARK_COMMENT,
BENCHMARK_LENGTH,
0,
PLAINTEXT_LENGTH,
BINARY_SIZE,
BINARY_ALIGN,
SALT_SIZE,
SALT_ALIGN,
MIN_KEYS_PER_CRYPT,
MAX_KEYS_PER_CRYPT,
#ifdef _OPENMP
FMT_OMP | FMT_OMP_BAD |
#endif
FMT_CASE | FMT_8_BIT,
{ NULL },
{ MAGIC },
tests
}, {
init,
done,
fmt_default_reset,
fmt_default_prepare,
valid,
split,
get_binary,
get_salt,
{ NULL },
fmt_default_source,
{
fmt_default_binary_hash_0,
fmt_default_binary_hash_1,
fmt_default_binary_hash_2,
fmt_default_binary_hash_3,
fmt_default_binary_hash_4,
fmt_default_binary_hash_5,
fmt_default_binary_hash_6
},
fmt_default_salt_hash,
NULL,
set_salt,
set_key,
get_key,
fmt_default_clear_keys,
crypt_all,
{
get_hash_0,
get_hash_1,
get_hash_2,
get_hash_3,
get_hash_4,
get_hash_5,
get_hash_6
},
cmp_all,
cmp_one,
cmp_exact
}
};
#endif /* plugin stanza */
|
9802.c
|
/* POLYBENCH/GPU-OPENMP
*
* This file is a part of the Polybench/GPU-OpenMP suite
*
* Contact:
* William Killian <[email protected]>
*
* Copyright 2013, The University of Delaware
*/
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <math.h>
/* Include polybench common header. */
#include <polybench.h>
/* Include benchmark-specific header. */
/* Default data type is double, default size is 4000. */
#include "atax.h"
/* Array initialization. */
static
void init_array (int nx, int ny,
DATA_TYPE POLYBENCH_2D(A,NX,NY,nx,ny),
DATA_TYPE POLYBENCH_1D(x,NY,ny))
{
int i, j;
for (i = 0; i < ny; i++)
x[i] = i * M_PI;
for (i = 0; i < nx; i++)
for (j = 0; j < ny; j++)
A[i][j] = ((DATA_TYPE) i*(j+1)) / nx;
}
/* DCE code. Must scan the entire live-out data.
Can be used also to check the correctness of the output. */
static
void print_array(int nx,
DATA_TYPE POLYBENCH_1D(y,NX,nx))
{
int i;
for (i = 0; i < nx; i++) {
fprintf (stderr, DATA_PRINTF_MODIFIER, y[i]);
if (i % 20 == 0) fprintf (stderr, "\n");
}
fprintf (stderr, "\n");
}
/* Main computational kernel. The whole function will be timed,
including the call and return. */
static
void kernel_atax(int nx, int ny,
DATA_TYPE POLYBENCH_2D(A,NX,NY,nx,ny),
DATA_TYPE POLYBENCH_1D(x,NY,ny),
DATA_TYPE POLYBENCH_1D(y,NY,ny),
DATA_TYPE POLYBENCH_1D(tmp,NX,nx))
{
int i, j;
#pragma scop
#pragma omp parallel num_threads(1)
{
#pragma omp for schedule(static, 1)
for (i = 0; i < _PB_NY; i++)
y[i] = 0;
#pragma omp for private (j) schedule(static, 1)
for (i = 0; i < _PB_NX; i++)
{
tmp[i] = 0;
for (j = 0; j < _PB_NY; j++)
tmp[i] = tmp[i] + A[i][j] * x[j];
for (j = 0; j < _PB_NY; j++)
y[j] = y[j] + A[i][j] * tmp[i];
}
}
#pragma endscop
}
int main(int argc, char** argv)
{
/* Retrieve problem size. */
int nx = NX;
int ny = NY;
/* Variable declaration/allocation. */
POLYBENCH_2D_ARRAY_DECL(A, DATA_TYPE, NX, NY, nx, ny);
POLYBENCH_1D_ARRAY_DECL(x, DATA_TYPE, NY, ny);
POLYBENCH_1D_ARRAY_DECL(y, DATA_TYPE, NY, ny);
POLYBENCH_1D_ARRAY_DECL(tmp, DATA_TYPE, NX, nx);
/* Initialize array(s). */
init_array (nx, ny, POLYBENCH_ARRAY(A), POLYBENCH_ARRAY(x));
/* Start timer. */
polybench_start_instruments;
/* Run kernel. */
kernel_atax (nx, ny,
POLYBENCH_ARRAY(A),
POLYBENCH_ARRAY(x),
POLYBENCH_ARRAY(y),
POLYBENCH_ARRAY(tmp));
/* Stop and print timer. */
polybench_stop_instruments;
polybench_print_instruments;
/* Prevent dead-code elimination. All live-out data must be printed
by the function call in argument. */
polybench_prevent_dce(print_array(nx, POLYBENCH_ARRAY(y)));
/* Be clean. */
POLYBENCH_FREE_ARRAY(A);
POLYBENCH_FREE_ARRAY(x);
POLYBENCH_FREE_ARRAY(y);
POLYBENCH_FREE_ARRAY(tmp);
return 0;
}
|
DenseTensor.h
|
//=================================================================================================
/*!
// \file blaze/math/smp/openmp/DenseTensor.h
// \brief Header file for the OpenMP-based dense tensor SMP implementation
//
// Copyright (C) 2012-2018 Klaus Iglberger - All Rights Reserved
// Copyright (C) 2018 Hartmut Kaiser - All Rights Reserved
//
// This file is part of the Blaze library. You can redistribute it and/or modify it under
// the terms of the New (Revised) BSD License. Redistribution and use in source and binary
// forms, with or without modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
// 3. Neither the names of the Blaze development group nor the names of its contributors
// may be used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
// SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
// BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
*/
//=================================================================================================
#ifndef _BLAZE_TENSOR_MATH_SMP_OPENMP_DENSETENSOR_H_
#define _BLAZE_TENSOR_MATH_SMP_OPENMP_DENSETENSOR_H_
//*************************************************************************************************
// Includes
//*************************************************************************************************
#include <blaze/math/Aliases.h>
#include <blaze/math/AlignmentFlag.h>
#include <blaze/math/StorageOrder.h>
#include <blaze/math/constraints/SMPAssignable.h>
#include <blaze/math/simd/SIMDTrait.h>
#include <blaze/math/smp/ParallelSection.h>
#include <blaze/math/smp/SerialSection.h>
#include <blaze/math/smp/ThreadMapping.h>
#include <blaze/math/typetraits/IsSIMDCombinable.h>
#include <blaze/math/typetraits/IsSMPAssignable.h>
#include <blaze/math/views/Submatrix.h>
#include <blaze/system/SMP.h>
#include <blaze/util/Assert.h>
#include <blaze/util/EnableIf.h>
#include <blaze/util/FunctionTrace.h>
#include <blaze/util/StaticAssert.h>
#include <blaze/util/Types.h>
#include <blaze/util/algorithms/Min.h>
#include <omp.h>
#include <blaze_tensor/math/expressions/DenseTensor.h>
#include <blaze_tensor/math/smp/TensorThreadMapping.h>
#include <blaze_tensor/math/typetraits/IsDenseTensor.h>
#include <blaze_tensor/math/views/PageSlice.h>
namespace blaze {
//=================================================================================================
//
// OPENMP-BASED ASSIGNMENT KERNELS
//
//=================================================================================================
//*************************************************************************************************
/*! \cond BLAZE_INTERNAL */
/*!\brief Backend of the OpenMP-based SMP (compound) assignment of a dense tensor to a dense tensor.
// \ingroup math
//
// \param lhs The target left-hand side dense tensor.
// \param rhs The right-hand side dense tensor to be assigned.
// \param op The (compound) assignment operation.
// \return void
//
// This function is the backend implementation of the OpenMP-based SMP assignment of a dense
// tensor to a dense tensor.\n
// This function must \b NOT be called explicitly! It is used internally for the performance
// optimized evaluation of expression templates. Calling this function explicitly might result
// in erroneous results and/or in compilation errors. Instead of using this function use the
// assignment operator.
*/
template< typename MT1 // Type of the left-hand side dense tensor
, typename MT2 // Type of the right-hand side dense tensor
, typename OP > // Type of the assignment operation
void openmpAssign( DenseTensor<MT1>& lhs, const DenseTensor<MT2>& rhs, OP op )
{
BLAZE_FUNCTION_TRACE;
BLAZE_INTERNAL_ASSERT( isParallelSectionActive(), "Invalid call outside a parallel section" );
using ET1 = ElementType_t<MT1>;
using ET2 = ElementType_t<MT2>;
constexpr bool simdEnabled( MT1::simdEnabled && MT2::simdEnabled && IsSIMDCombinable_v<ET1,ET2> );
constexpr size_t SIMDSIZE( SIMDTrait< ElementType_t<MT1> >::size );
const bool lhsAligned( (~lhs).isAligned() );
const bool rhsAligned( (~rhs).isAligned() );
const int threads( omp_get_num_threads() );
const ThreadMapping threadmap( createThreadMapping( threads, ~rhs ) );
const size_t addon1 ( ( ( (~rhs).rows() % threadmap.first ) != 0UL )? 1UL : 0UL );
const size_t equalShare1( (~rhs).rows() / threadmap.first + addon1 );
const size_t rest1 ( equalShare1 & ( SIMDSIZE - 1UL ) );
const size_t rowsPerThread( ( simdEnabled && rest1 )?( equalShare1 - rest1 + SIMDSIZE ):( equalShare1 ) );
const size_t addon2 ( ( ( (~rhs).columns() % threadmap.second ) != 0UL )? 1UL : 0UL );
const size_t equalShare2( (~rhs).columns() / threadmap.second + addon2 );
const size_t rest2 ( equalShare2 & ( SIMDSIZE - 1UL ) );
const size_t colsPerThread( ( simdEnabled && rest2 )?( equalShare2 - rest2 + SIMDSIZE ):( equalShare2 ) );
#pragma omp for schedule(dynamic,1) nowait
for( int i=0; i<threads; ++i )
{
const size_t row ( ( i / threadmap.second ) * rowsPerThread );
const size_t column( ( i % threadmap.second ) * colsPerThread );
if( row >= (~rhs).rows() || column >= (~rhs).columns() )
continue;
for (size_t k = 0; k != (~rhs).pages(); ++k)
{
const size_t m( min( rowsPerThread, (~rhs).rows() - row ) );
const size_t n( min( colsPerThread, (~rhs).columns() - column ) );
auto lhs_slice = pageslice( ~lhs, k );
auto rhs_slice = pageslice( ~rhs, k );
if( simdEnabled && lhsAligned && rhsAligned ) {
auto target( submatrix<aligned> ( ~lhs_slice, row, column, m, n ) );
const auto source( submatrix<aligned> ( ~rhs_slice, row, column, m, n ) );
op( target, source );
}
else if( simdEnabled && lhsAligned ) {
auto target( submatrix<aligned> ( ~lhs_slice, row, column, m, n ) );
const auto source( submatrix<unaligned>( ~rhs_slice, row, column, m, n ) );
op( target, source );
}
else if( simdEnabled && rhsAligned ) {
auto target( submatrix<unaligned>( ~lhs_slice, row, column, m, n ) );
const auto source( submatrix<aligned> ( ~rhs_slice, row, column, m, n ) );
op( target, source );
}
else {
auto target( submatrix<unaligned>( ~lhs_slice, row, column, m, n ) );
const auto source( submatrix<unaligned>( ~rhs_slice, row, column, m, n ) );
op( target, source );
}
}
}
}
/*! \endcond */
//*************************************************************************************************
//=================================================================================================
//
// PLAIN ASSIGNMENT
//
//=================================================================================================
//*************************************************************************************************
/*! \cond BLAZE_INTERNAL */
/*!\brief Default implementation of the OpenMP-based SMP assignment to a dense tensor.
// \ingroup smp
//
// \param lhs The target left-hand side dense tensor.
// \param rhs The right-hand side tensor to be assigned.
// \return void
//
// This function implements the default OpenMP-based SMP assignment to a dense tensor. Due to
// the explicit application of the SFINAE principle, this function can only be selected by the
// compiler in case both operands are SMP-assignable and the element types of both operands are
// not SMP-assignable.\n
// This function must \b NOT be called explicitly! It is used internally for the performance
// optimized evaluation of expression templates. Calling this function explicitly might result
// in erroneous results and/or in compilation errors. Instead of using this function use the
// assignment operator.
*/
template< typename MT1 // Type of the left-hand side dense tensor
, typename MT2 > // Type of the right-hand side dense tensor
inline EnableIf_t< IsDenseTensor_v<MT1> && ( !IsSMPAssignable_v<MT1> || !IsSMPAssignable_v<MT2> ) >
smpAssign( Tensor<MT1>& lhs, const Tensor<MT2>& rhs )
{
BLAZE_FUNCTION_TRACE;
BLAZE_INTERNAL_ASSERT( (~lhs).rows() == (~rhs).rows() , "Invalid number of rows" );
BLAZE_INTERNAL_ASSERT( (~lhs).columns() == (~rhs).columns(), "Invalid number of columns" );
BLAZE_INTERNAL_ASSERT( (~lhs).pages() == (~rhs).pages(), "Invalid number of pages" );
assign( ~lhs, ~rhs );
}
/*! \endcond */
//*************************************************************************************************
//*************************************************************************************************
/*! \cond BLAZE_INTERNAL */
/*!\brief Implementation of the OpenMP-based SMP assignment to a dense tensor.
// \ingroup math
//
// \param lhs The target left-hand side dense tensor.
// \param rhs The right-hand side tensor to be assigned.
// \return void
//
// This function implements the OpenMP-based SMP assignment to a dense tensor. Due to the
// explicit application of the SFINAE principle, this function can only be selected by the
// compiler in case both operands are SMP-assignable and the element types of both operands
// are not SMP-assignable.\n
// This function must \b NOT be called explicitly! It is used internally for the performance
// optimized evaluation of expression templates. Calling this function explicitly might result
// in erroneous results and/or in compilation errors. Instead of using this function use the
// assignment operator.
*/
template< typename MT1 // Type of the left-hand side dense tensor
, typename MT2 > // Type of the right-hand side dense tensor
inline EnableIf_t< IsDenseTensor_v<MT1> && IsSMPAssignable_v<MT1> && IsSMPAssignable_v<MT2> >
smpAssign( Tensor<MT1>& lhs, const Tensor<MT2>& rhs )
{
BLAZE_FUNCTION_TRACE;
BLAZE_CONSTRAINT_MUST_NOT_BE_SMP_ASSIGNABLE( ElementType_t<MT1> );
BLAZE_CONSTRAINT_MUST_NOT_BE_SMP_ASSIGNABLE( ElementType_t<MT2> );
BLAZE_INTERNAL_ASSERT( (~lhs).rows() == (~rhs).rows() , "Invalid number of rows" );
BLAZE_INTERNAL_ASSERT( (~lhs).columns() == (~rhs).columns(), "Invalid number of columns" );
BLAZE_INTERNAL_ASSERT( (~lhs).pages() == (~rhs).pages(), "Invalid number of pages" );
BLAZE_PARALLEL_SECTION
{
if( isSerialSectionActive() || !(~rhs).canSMPAssign() ) {
assign( ~lhs, ~rhs );
}
else {
#pragma omp parallel shared( lhs, rhs )
openmpAssign( ~lhs, ~rhs, []( auto& a, const auto& b ){ assign( a, b ); } );
}
}
}
/*! \endcond */
//*************************************************************************************************
//=================================================================================================
//
// ADDITION ASSIGNMENT
//
//=================================================================================================
//*************************************************************************************************
/*! \cond BLAZE_INTERNAL */
/*!\brief Default implementation of the OpenMP-based SMP addition assignment to a dense tensor.
// \ingroup smp
//
// \param lhs The target left-hand side dense tensor.
// \param rhs The right-hand side tensor to be added.
// \return void
//
// This function implements the default OpenMP-based SMP addition assignment to a dense tensor.
// Due to the explicit application of the SFINAE principle, this function can only be selected
// by the compiler in case both operands are SMP-assignable and the element types of both operands
// are not SMP-assignable.\n
// This function must \b NOT be called explicitly! It is used internally for the performance
// optimized evaluation of expression templates. Calling this function explicitly might result
// in erroneous results and/or in compilation errors. Instead of using this function use the
// assignment operator.
*/
template< typename MT1 // Type of the left-hand side dense tensor
, typename MT2 > // Type of the right-hand side dense tensor
inline EnableIf_t< IsDenseTensor_v<MT1> && ( !IsSMPAssignable_v<MT1> || !IsSMPAssignable_v<MT2> ) >
smpAddAssign( Tensor<MT1>& lhs, const Tensor<MT2>& rhs )
{
BLAZE_FUNCTION_TRACE;
BLAZE_INTERNAL_ASSERT( (~lhs).rows() == (~rhs).rows() , "Invalid number of rows" );
BLAZE_INTERNAL_ASSERT( (~lhs).columns() == (~rhs).columns(), "Invalid number of columns" );
BLAZE_INTERNAL_ASSERT( (~lhs).pages() == (~rhs).pages(), "Invalid number of pages" );
addAssign( ~lhs, ~rhs );
}
/*! \endcond */
//*************************************************************************************************
//*************************************************************************************************
/*! \cond BLAZE_INTERNAL */
/*!\brief Implementation of the OpenMP-based SMP addition assignment to a dense tensor.
// \ingroup math
//
// \param lhs The target left-hand side dense tensor.
// \param rhs The right-hand side tensor to be added.
// \return void
//
// This function implements the OpenMP-based SMP addition assignment to a dense tensor. Due to
// the explicit application of the SFINAE principle, this function can only be selected by the
// compiler in case both operands are SMP-assignable and the element types of both operands are
// not SMP-assignable.\n
// This function must \b NOT be called explicitly! It is used internally for the performance
// optimized evaluation of expression templates. Calling this function explicitly might result
// in erroneous results and/or in compilation errors. Instead of using this function use the
// assignment operator.
*/
template< typename MT1 // Type of the left-hand side dense tensor
, typename MT2 > // Type of the right-hand side dense tensor
inline EnableIf_t< IsDenseTensor_v<MT1> && IsSMPAssignable_v<MT1> && IsSMPAssignable_v<MT2> >
smpAddAssign( Tensor<MT1>& lhs, const Tensor<MT2>& rhs )
{
BLAZE_FUNCTION_TRACE;
BLAZE_CONSTRAINT_MUST_NOT_BE_SMP_ASSIGNABLE( ElementType_t<MT1> );
BLAZE_CONSTRAINT_MUST_NOT_BE_SMP_ASSIGNABLE( ElementType_t<MT2> );
BLAZE_INTERNAL_ASSERT( (~lhs).rows() == (~rhs).rows() , "Invalid number of rows" );
BLAZE_INTERNAL_ASSERT( (~lhs).columns() == (~rhs).columns(), "Invalid number of columns" );
BLAZE_INTERNAL_ASSERT( (~lhs).pages() == (~rhs).pages(), "Invalid number of pages" );
BLAZE_PARALLEL_SECTION
{
if( isSerialSectionActive() || !(~rhs).canSMPAssign() ) {
addAssign( ~lhs, ~rhs );
}
else {
#pragma omp parallel shared( lhs, rhs )
openmpAssign( ~lhs, ~rhs, []( auto& a, const auto& b ){ addAssign( a, b ); } );
}
}
}
/*! \endcond */
//*************************************************************************************************
//=================================================================================================
//
// SUBTRACTION ASSIGNMENT
//
//=================================================================================================
//*************************************************************************************************
/*! \cond BLAZE_INTERNAL */
/*!\brief Default implementation of the OpenMP-based SMP subtracction assignment to a dense tensor.
// \ingroup smp
//
// \param lhs The target left-hand side dense tensor.
// \param rhs The right-hand side tensor to be subtracted.
// \return void
//
// This function implements the default OpenMP-based SMP subtraction assignment to a dense tensor.
// Due to the explicit application of the SFINAE principle, this function can only be selected by
// the compiler in case both operands are SMP-assignable and the element types of both operands
// are not SMP-assignable.\n
// This function must \b NOT be called explicitly! It is used internally for the performance
// optimized evaluation of expression templates. Calling this function explicitly might result
// in erroneous results and/or in compilation errors. Instead of using this function use the
// assignment operator.
*/
template< typename MT1 // Type of the left-hand side dense tensor
, typename MT2 > // Type of the right-hand side dense tensor
inline EnableIf_t< IsDenseTensor_v<MT1> && ( !IsSMPAssignable_v<MT1> || !IsSMPAssignable_v<MT2> ) >
smpSubAssign( Tensor<MT1>& lhs, const Tensor<MT2>& rhs )
{
BLAZE_FUNCTION_TRACE;
BLAZE_INTERNAL_ASSERT( (~lhs).rows() == (~rhs).rows() , "Invalid number of rows" );
BLAZE_INTERNAL_ASSERT( (~lhs).columns() == (~rhs).columns(), "Invalid number of columns" );
BLAZE_INTERNAL_ASSERT( (~lhs).pages() == (~rhs).pages(), "Invalid number of pages" );
subAssign( ~lhs, ~rhs );
}
/*! \endcond */
//*************************************************************************************************
//*************************************************************************************************
/*! \cond BLAZE_INTERNAL */
/*!\brief Implementation of the OpenMP-based SMP subtracction assignment to a dense tensor.
// \ingroup smp
//
// \param lhs The target left-hand side dense tensor.
// \param rhs The right-hand side tensor to be subtracted.
// \return void
//
// This function implements the default OpenMP-based SMP subtraction assignment of a tensor to a
// dense tensor. Due to the explicit application of the SFINAE principle, this function can only
// be selected by the compiler in case both operands are SMP-assignable and the element types of
// both operands are not SMP-assignable.\n
// This function must \b NOT be called explicitly! It is used internally for the performance
// optimized evaluation of expression templates. Calling this function explicitly might result
// in erroneous results and/or in compilation errors. Instead of using this function use the
// assignment operator.
*/
template< typename MT1 // Type of the left-hand side dense tensor
, typename MT2 > // Type of the right-hand side dense tensor
inline EnableIf_t< IsDenseTensor_v<MT1> && IsSMPAssignable_v<MT1> && IsSMPAssignable_v<MT2> >
smpSubAssign( Tensor<MT1>& lhs, const Tensor<MT2>& rhs )
{
BLAZE_FUNCTION_TRACE;
BLAZE_CONSTRAINT_MUST_NOT_BE_SMP_ASSIGNABLE( ElementType_t<MT1> );
BLAZE_CONSTRAINT_MUST_NOT_BE_SMP_ASSIGNABLE( ElementType_t<MT2> );
BLAZE_INTERNAL_ASSERT( (~lhs).rows() == (~rhs).rows() , "Invalid number of rows" );
BLAZE_INTERNAL_ASSERT( (~lhs).columns() == (~rhs).columns(), "Invalid number of columns" );
BLAZE_INTERNAL_ASSERT( (~lhs).pages() == (~rhs).pages(), "Invalid number of pages" );
BLAZE_PARALLEL_SECTION
{
if( isSerialSectionActive() || !(~rhs).canSMPAssign() ) {
subAssign( ~lhs, ~rhs );
}
else {
#pragma omp parallel shared( lhs, rhs )
openmpAssign( ~lhs, ~rhs, []( auto& a, const auto& b ){ subAssign( a, b ); } );
}
}
}
/*! \endcond */
//*************************************************************************************************
//=================================================================================================
//
// SCHUR PRODUCT ASSIGNMENT
//
//=================================================================================================
//*************************************************************************************************
/*! \cond BLAZE_INTERNAL */
/*!\brief Default implementation of the OpenMP-based SMP Schur product assignment to a dense tensor.
// \ingroup smp
//
// \param lhs The target left-hand side dense tensor.
// \param rhs The right-hand side tensor for the Schur product.
// \return void
//
// This function implements the default OpenMP-based SMP Schur product assignment to a dense
// tensor. Due to the explicit application of the SFINAE principle, this function can only be
// selected by the compiler in case both operands are SMP-assignable and the element types of
// both operands are not SMP-assignable.\n
// This function must \b NOT be called explicitly! It is used internally for the performance
// optimized evaluation of expression templates. Calling this function explicitly might result
// in erroneous results and/or in compilation errors. Instead of using this function use the
// assignment operator.
*/
template< typename MT1 // Type of the left-hand side dense tensor
, typename MT2 > // Type of the right-hand side dense tensor
inline EnableIf_t< IsDenseTensor_v<MT1> && ( !IsSMPAssignable_v<MT1> || !IsSMPAssignable_v<MT2> ) >
smpSchurAssign( Tensor<MT1>& lhs, const Tensor<MT2>& rhs )
{
BLAZE_FUNCTION_TRACE;
BLAZE_INTERNAL_ASSERT( (~lhs).rows() == (~rhs).rows() , "Invalid number of rows" );
BLAZE_INTERNAL_ASSERT( (~lhs).columns() == (~rhs).columns(), "Invalid number of columns" );
BLAZE_INTERNAL_ASSERT( (~lhs).pages() == (~rhs).pages(), "Invalid number of pages" );
schurAssign( ~lhs, ~rhs );
}
/*! \endcond */
//*************************************************************************************************
//*************************************************************************************************
/*! \cond BLAZE_INTERNAL */
/*!\brief Implementation of the OpenMP-based SMP Schur product assignment to a dense tensor.
// \ingroup math
//
// \param lhs The target left-hand side dense tensor.
// \param rhs The right-hand side tensor for the Schur product.
// \return void
//
// This function implements the OpenMP-based SMP Schur product assignment to a dense tensor. Due
// to the explicit application of the SFINAE principle, this function can only be selected by the
// compiler in case both operands are SMP-assignable and the element types of both operands are
// not SMP-assignable.\n
// This function must \b NOT be called explicitly! It is used internally for the performance
// optimized evaluation of expression templates. Calling this function explicitly might result
// in erroneous results and/or in compilation errors. Instead of using this function use the
// assignment operator.
*/
template< typename MT1 // Type of the left-hand side dense tensor
, typename MT2 > // Type of the right-hand side dense tensor
inline EnableIf_t< IsDenseTensor_v<MT1> && IsSMPAssignable_v<MT1> && IsSMPAssignable_v<MT2> >
smpSchurAssign( Tensor<MT1>& lhs, const Tensor<MT2>& rhs )
{
BLAZE_FUNCTION_TRACE;
BLAZE_CONSTRAINT_MUST_NOT_BE_SMP_ASSIGNABLE( ElementType_t<MT1> );
BLAZE_CONSTRAINT_MUST_NOT_BE_SMP_ASSIGNABLE( ElementType_t<MT2> );
BLAZE_INTERNAL_ASSERT( (~lhs).rows() == (~rhs).rows() , "Invalid number of rows" );
BLAZE_INTERNAL_ASSERT( (~lhs).columns() == (~rhs).columns(), "Invalid number of columns" );
BLAZE_INTERNAL_ASSERT( (~lhs).pages() == (~rhs).pages(), "Invalid number of pages" );
BLAZE_PARALLEL_SECTION
{
if( isSerialSectionActive() || !(~rhs).canSMPAssign() ) {
schurAssign( ~lhs, ~rhs );
}
else {
#pragma omp parallel shared( lhs, rhs )
openmpAssign( ~lhs, ~rhs, []( auto& a, const auto& b ){ schurAssign( a, b ); } );
}
}
}
/*! \endcond */
//*************************************************************************************************
//=================================================================================================
//
// MULTIPLICATION ASSIGNMENT
//
//=================================================================================================
//*************************************************************************************************
/*! \cond BLAZE_INTERNAL */
/*!\brief Default implementation of the OpenMP-based SMP multiplication assignment to a dense tensor.
// \ingroup smp
//
// \param lhs The target left-hand side dense tensor.
// \param rhs The right-hand side tensor to be multiplied.
// \return void
//
// This function implements the default OpenMP-based SMP multiplication assignment to a dense
// tensor.\n
// This function must \b NOT be called explicitly! It is used internally for the performance
// optimized evaluation of expression templates. Calling this function explicitly might result
// in erroneous results and/or in compilation errors. Instead of using this function use the
// assignment operator.
*/
template< typename MT1 // Type of the left-hand side dense tensor
, typename MT2 > // Type of the right-hand side dense tensor
inline EnableIf_t< IsDenseTensor_v<MT1> >
smpMultAssign( Tensor<MT1>& lhs, const Tensor<MT2>& rhs )
{
BLAZE_FUNCTION_TRACE;
BLAZE_INTERNAL_ASSERT( (~lhs).rows() == (~rhs).rows() , "Invalid number of rows" );
BLAZE_INTERNAL_ASSERT( (~lhs).columns() == (~rhs).columns(), "Invalid number of columns" );
BLAZE_INTERNAL_ASSERT( (~lhs).pages() == (~rhs).pages(), "Invalid number of pages" );
multAssign( ~lhs, ~rhs );
}
/*! \endcond */
//*************************************************************************************************
//=================================================================================================
//
// COMPILE TIME CONSTRAINT
//
//=================================================================================================
//*************************************************************************************************
/*! \cond BLAZE_INTERNAL */
namespace {
BLAZE_STATIC_ASSERT( BLAZE_OPENMP_PARALLEL_MODE );
}
/*! \endcond */
//*************************************************************************************************
} // namespace blaze
#endif
|
GB_unop__identity_uint32_fc32.c
|
//------------------------------------------------------------------------------
// GB_unop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved.
// http://suitesparse.com See GraphBLAS/Doc/License.txt for license.
//------------------------------------------------------------------------------
// If this file is in the Generated/ folder, do not edit it (auto-generated).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_unop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB_unop_apply__identity_uint32_fc32
// op(A') function: GB_unop_tran__identity_uint32_fc32
// C type: uint32_t
// A type: GxB_FC32_t
// cast: uint32_t cij = GB_cast_to_uint32_t ((double) crealf (aij))
// unaryop: cij = aij
#define GB_ATYPE \
GxB_FC32_t
#define GB_CTYPE \
uint32_t
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
GxB_FC32_t aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = x ;
// casting
#define GB_CAST(z, aij) \
uint32_t z = GB_cast_to_uint32_t ((double) crealf (aij)) ;
// cij = op (aij)
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
GxB_FC32_t aij = Ax [pA] ; \
/* Cx [pC] = op (cast (aij)) */ \
uint32_t z = GB_cast_to_uint32_t ((double) crealf (aij)) ; \
Cx [pC] = z ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_IDENTITY || GxB_NO_UINT32 || GxB_NO_FC32)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop_apply__identity_uint32_fc32
(
uint32_t *Cx, // Cx and Ax may be aliased
const GxB_FC32_t *Ax,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
GxB_FC32_t aij = Ax [p] ;
uint32_t z = GB_cast_to_uint32_t ((double) crealf (aij)) ;
Cx [p] = z ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop_tran__identity_uint32_fc32
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t *GB_RESTRICT *Rowcounts,
GBI_single_iterator Iter,
const int64_t *GB_RESTRICT A_slice,
int naslice
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#define GB_PHASE_2_OF_2
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
omp.c
|
// RUN: mlir-clang %s --function=* -fopenmp -S | FileCheck %s
void square(double* x, int sstart, int send, int sinc) {
#pragma omp parallel for
for(int i=sstart; i < send; i+= sinc) {
x[i] = i;
}
}
// CHECK: func @square(%arg0: memref<?xf64>, %arg1: i32, %arg2: i32, %arg3: i32) attributes {llvm.linkage = #llvm.linkage<external>} {
// CHECK-NEXT: %0 = arith.index_cast %arg1 : i32 to index
// CHECK-NEXT: %1 = arith.index_cast %arg2 : i32 to index
// CHECK-NEXT: %2 = arith.index_cast %arg3 : i32 to index
// CHECK-NEXT: scf.parallel (%arg4) = (%0) to (%1) step (%2) {
// CHECK-NEXT: %3 = arith.index_cast %arg4 : index to i32
// CHECK-NEXT: %4 = arith.sitofp %3 : i32 to f64
// CHECK-NEXT: memref.store %4, %arg0[%arg4] : memref<?xf64>
// CHECK-NEXT: scf.yield
// CHECK-NEXT: }
// CHECK-NEXT: return
// CHECK-NEXT: }
|
chi_calc.c
|
////////////////////////////////////////////////////////
// Chi Square Calculation and Trapezoidal Integration //
// Matheus J. Castro //
// Version 2.3 //
// Last Modification: 06/11/2021 (month/day/year) //
////////////////////////////////////////////////////////
#include<stdbool.h>
#include<stdlib.h>
#include<string.h>
#include<stdio.h>
#include<time.h>
#include<math.h>
#include<omp.h>
#define MAX 100
#define c 299792458 //velocidade da luz em m/s
double e_func(double z, double param[3], double omega_k){
double omega_m_factor = param[0] * pow((1 + z), 3);
double omega_de_factor = param[1] * pow((1 + z), (3 + 3 * param[2]));
double omega_k_factor = omega_k * pow((1 + z), 2);
double sq = 1/sqrt(omega_m_factor + omega_de_factor + omega_k_factor);
return sq;
}
double calc_trapezium_formula(double lim[2], double n, double params[3], double omega_k){
double h = (lim[1] - lim[0]) / n;
double sum = 0;
for(double j = lim[0] + h; j < lim[1]; j = j + 2*h){
sum = sum + e_func(j, params, omega_k);
}
double trapezium = h * sum;
return trapezium;
}
double integrate(double params[3], double omega_k, double lim[2], double eps_desired){
if(lim[0] == lim[1])
return 0;
double result = (e_func(lim[0], params, omega_k) + e_func(lim[1], params, omega_k)) * (lim[1] - lim[0]) / 2;
int count = 0;
double eps = 1;
while(eps >= eps_desired){
count++;
double result_old = result;
double divisions = pow(2, count);
result = result / 2 + calc_trapezium_formula(lim, divisions, params, omega_k);
eps = fabs((result - result_old) / result);
}
return result;
}
double comoving_distance(double h0, double redshift, double params[3], double precision){
double omega_k = 1 - (params[0] + params[1]);
double hubble_distance = c / h0;
double factor_k;
double lim[2] = {0, redshift};
double integration_result = integrate(params, omega_k, lim, precision);
if(omega_k == 0){
factor_k = hubble_distance * integrate(params, omega_k, lim, precision);
}
else if(omega_k > 0){
double sqr_om = sqrt(omega_k);
factor_k = hubble_distance / sqr_om * sinh(sqr_om * integration_result);
}
else{
double sqr_om = sqrt(fabs(omega_k));
factor_k = hubble_distance / sqr_om * sin(sqr_om * integration_result);
}
return factor_k;
}
double luminosity_distance(double h0, double redshift, double params[3], double precision){
double lum = (1 + redshift) * comoving_distance(h0, redshift, params, precision);
return lum;
}
double dist_mod(double dist_lum){
//dist_lum is the luminosity distance in Mpc
double mod = 5 * log10(dist_lum * pow(10, 6) / 10);
return mod;
}
double lumin_dist_mod_func(double h0, double redshift, double params[3], double precision){
double mpc_to_km = 3.086E+19; //conversão de Mpc para km
h0 = h0 / mpc_to_km;
double lum_dist_val = luminosity_distance(h0, redshift, params, precision);
lum_dist_val = lum_dist_val * pow(10, -3) / mpc_to_km; //conversão de m para Mpc
double dist_mod_val = dist_mod(lum_dist_val);
return dist_mod_val;
}
double calc_chi(int h0, int nrows, double data[3][nrows], double params[3], double precision){
double chi2 = 0;
#pragma omp parallel shared(h0, nrows, data, params, precision)
{
//if(omp_get_thread_num() == 0){
// printf("Executing for %d thread(s).\n", omp_get_num_threads());
//}
#pragma omp for reduction(+: chi2)
for(int i = 0; i < nrows; i++){
double teor_data = lumin_dist_mod_func(h0, data[0][i], params, precision);
chi2 += pow((data[1][i] - teor_data) / data[2][i], 2);
}
}
return chi2;
}
double main_execution(char fl_name[MAX], double h0, double omega_m, double omega_ee, double w, double precision, int nrows){
FILE *csv;
char header[4][MAX];
double data[3][nrows];
csv = fopen(fl_name, "r");
if(fscanf(csv, "%s %s %s %s\n", header[0], header[1], header[2], header[3])){}
//printf("%s %s %s %s\n", header[0],header[1], header[2], header[3]);
for (int i = 0; i < nrows ; i++) // Read until the last line.
{
if(fscanf(csv, "%lf %lf %lf\n", &data[0][i], &data[1][i], &data[2][i])){} // Create the matrix of catalogs.
//printf("%.15lf %.15lf %.15lf\n", data[0][i], data[1][i], data[2][i]);
}
fclose(csv);
double params[3] = {omega_m, omega_ee, w};
double chi2 = calc_chi(h0, nrows, data, params, precision);
return chi2;
}
int main(){
double h0 = 70;
double omega_m = 0.3;
double omega_ee = 0.7;
double w = -1;
double precision = 1E-10;
int nrows = 580;
char fl_name[MAX] = "fake_data.cat";
double chi2 = main_execution(fl_name, h0, omega_m, omega_ee, w, precision, nrows);
printf("%e\n", chi2);
return 0;
}
|
3d25pt.c
|
/*
* Order-2, 3D 25 point stencil
* Adapted from PLUTO and Pochoir test bench
*
* Tareq Malas
*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#ifdef LIKWID_PERFMON
#include <likwid.h>
#endif
#include "print_utils.h"
#define TESTS 2
#define MAX(a,b) ((a) > (b) ? a : b)
#define MIN(a,b) ((a) < (b) ? a : b)
#ifndef min
#define min(x,y) ((x) < (y)? (x) : (y))
#endif
/* Subtract the `struct timeval' values X and Y,
* storing the result in RESULT.
*
* Return 1 if the difference is negative, otherwise 0.
*/
int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y)
{
/* Perform the carry for the later subtraction by updating y. */
if (x->tv_usec < y->tv_usec)
{
int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1;
y->tv_usec -= 1000000 * nsec;
y->tv_sec += nsec;
}
if (x->tv_usec - y->tv_usec > 1000000)
{
int nsec = (x->tv_usec - y->tv_usec) / 1000000;
y->tv_usec += 1000000 * nsec;
y->tv_sec -= nsec;
}
/* Compute the time remaining to wait.
* tv_usec is certainly positive.
*/
result->tv_sec = x->tv_sec - y->tv_sec;
result->tv_usec = x->tv_usec - y->tv_usec;
/* Return 1 if result is negative. */
return x->tv_sec < y->tv_sec;
}
int main(int argc, char *argv[])
{
int t, i, j, k, test;
int Nx, Ny, Nz, Nt;
if (argc > 3) {
Nx = atoi(argv[1])+8;
Ny = atoi(argv[2])+8;
Nz = atoi(argv[3])+8;
}
if (argc > 4)
Nt = atoi(argv[4]);
double ****A = (double ****) malloc(sizeof(double***)*2);
double ***roc2 = (double ***) malloc(sizeof(double**));
A[0] = (double ***) malloc(sizeof(double**)*Nz);
A[1] = (double ***) malloc(sizeof(double**)*Nz);
roc2 = (double ***) malloc(sizeof(double**)*Nz);
for(i=0; i<Nz; i++){
A[0][i] = (double**) malloc(sizeof(double*)*Ny);
A[1][i] = (double**) malloc(sizeof(double*)*Ny);
roc2[i] = (double**) malloc(sizeof(double*)*Ny);
for(j=0;j<Ny;j++){
A[0][i][j] = (double*) malloc(sizeof(double)*Nx);
A[1][i][j] = (double*) malloc(sizeof(double)*Nx);
roc2[i][j] = (double*) malloc(sizeof(double)*Nx);
}
}
// tile size information, including extra element to decide the list length
int *tile_size = (int*) malloc(sizeof(int));
tile_size[0] = -1;
// The list is modified here before source-to-source transformations
tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5);
tile_size[0] = 16;
tile_size[1] = 16;
tile_size[2] = 8;
tile_size[3] = 128;
tile_size[4] = -1;
// for timekeeping
int ts_return = -1;
struct timeval start, end, result;
double tdiff = 0.0, min_tdiff=1.e100;
const int BASE = 1024;
// initialize variables
//
srand(42);
for (i = 1; i < Nz; i++) {
for (j = 1; j < Ny; j++) {
for (k = 1; k < Nx; k++) {
A[0][i][j][k] = 1.0 * (rand() % BASE);
roc2[i][j][k] = 2.0 * (rand() % BASE);
}
}
}
#ifdef LIKWID_PERFMON
LIKWID_MARKER_INIT;
#pragma omp parallel
{
LIKWID_MARKER_THREADINIT;
#pragma omp barrier
LIKWID_MARKER_START("calc");
}
#endif
int num_threads = 1;
#if defined(_OPENMP)
num_threads = omp_get_max_threads();
#endif
const double coef0 = -0.28472;
const double coef1 = 0.16000;
const double coef2 = -0.02000;
const double coef3 = 0.00254;
const double coef4 = -0.00018;
for(test=0; test<TESTS; test++){
gettimeofday(&start, 0);
// serial execution - Addition: 6 && Multiplication: 2
#pragma scop
for (t = 0; t < Nt; t++) {
for (i = 4; i < Nz-4; i++) {
for (j = 4; j < Ny-4; j++) {
for (k = 4; k < Nx-4; k++) {
A[(t+1)%2][i][j][k] = 2.0*A[t%2][i][j][k] - A[(t+1)%2][i][j][k] + roc2[i][j][k]*(
coef0* A[t%2][i ][j ][k ] +
coef1*(A[t%2][i-1][j ][k ] + A[t%2][i+1][j ][k ] +
A[t%2][i ][j-1][k ] + A[t%2][i ][j+1][k ] +
A[t%2][i ][j ][k-1] + A[t%2][i ][j ][k+1]) +
coef2*(A[t%2][i-2][j ][k ] + A[t%2][i+2][j ][k ] +
A[t%2][i ][j-2][k ] + A[t%2][i ][j+2][k ] +
A[t%2][i ][j ][k-2] + A[t%2][i ][j ][k+2]) +
coef3*(A[t%2][i-3][j ][k ] + A[t%2][i+3][j ][k ] +
A[t%2][i ][j-3][k ] + A[t%2][i ][j+3][k ] +
A[t%2][i ][j ][k-3] + A[t%2][i ][j ][k+3]) +
coef4*(A[t%2][i-4][j ][k ] + A[t%2][i+4][j ][k ] +
A[t%2][i ][j-4][k ] + A[t%2][i ][j+4][k ] +
A[t%2][i ][j ][k-4] + A[t%2][i ][j ][k+4]) );
}
}
}
}
#pragma endscop
gettimeofday(&end, 0);
ts_return = timeval_subtract(&result, &end, &start);
tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6);
min_tdiff = MIN(min_tdiff, tdiff);
printf("Rank 0 TEST# %d time: %f\n", test, tdiff);
}
PRINT_RESULTS(4, "constant")
#ifdef LIKWID_PERFMON
#pragma omp parallel
{
LIKWID_MARKER_STOP("calc");
}
LIKWID_MARKER_CLOSE;
#endif
// Free allocated arrays
for(i=0; i<Nz; i++){
for(j=0;j<Ny;j++){
free(A[0][i][j]);
free(A[1][i][j]);
free(roc2[i][j]);
}
free(A[0][i]);
free(A[1][i]);
free(roc2[i]);
}
free(A[0]);
free(A[1]);
free(roc2);
return 0;
}
|
t005.c
|
#include<stdint.h>
#include<stdlib.h>
#include<stdio.h>
#include<omp.h>
typedef struct {int64_t nteam; int64_t nthread; int64_t team_n; int64_t thread_n;} tinfo;
int
main(int argc, char **argv)
{
const int64_t narr = 1 << 10;
tinfo tinit = {-1, -1, -1, -1};
tinfo *t = aligned_alloc(1 << 22, sizeof(tinfo)*narr);
for(int64_t i = 0; i < narr; ++i) t[i] = tinit;
#pragma omp target teams distribute parallel for simd map(t[0:narr]) aligned(t) num_teams(32)
for(int64_t i = 0; i < narr; ++i){
t[i].nteam = omp_get_num_teams();
t[i].nthread = omp_get_num_threads();
t[i].team_n = omp_get_team_num();
t[i].thread_n = omp_get_thread_num();
}
for(int64_t i = 0; i < narr; ++i){
printf("%4ld: nteam: %ld nthread: %ld team_n: %ld thread_n: %ld\n",
i, t[i].nteam, t[i].nthread, t[i].team_n, t[i].thread_n);
}
int ret = 0;
//if(t->nteam <= 0 || t->nthread <= 0) ret = 1;
free(t);
return ret;
}
|
KadabraBetweenness.h
|
/*
* KadabraBetweenness.h
*
* Created on: 18.07.2018
* Author: Eugenio Angriman, Alexander van der Grinten
*/
#ifndef KADABRA_H_
#define KADABRA_H_
#include <atomic>
#include "../auxiliary/SortedList.h"
#include "../base/Algorithm.h"
#include "../components/ConnectedComponents.h"
#include "../graph/Graph.h"
namespace NetworKit {
class Status {
public:
Status(const count k);
const count k;
std::vector<node> top;
std::vector<double> approxTop;
std::vector<bool> finished;
std::vector<double> bet;
std::vector<double> errL;
std::vector<double> errU;
count nPairs;
};
class SpSampler {
public:
SpSampler(const Graph &G, const ConnectedComponents &cc);
std::vector<node> randomPath();
private:
const Graph &G;
const count n;
Graph pred;
std::vector<count> ballInd;
std::vector<count> dist;
std::vector<count> nPaths;
std::vector<node> q;
const ConnectedComponents &cc;
inline node randomNode() const;
void backtrackPath(const node u, const node v, const node start,
std::vector<node> &path);
void removeAllEdges(const count endQ);
count getDegree(const Graph &graph, node y, bool useDegreeIn);
};
/**
* @ingroup centrality
* Approximation of the betweenness centrality and computation of the top-k
* nodes with highest betweenness centrality according to the algorithm
* described in Borassi M. and Natale M. (2016): KADABRA is an ADaptive
* Algorithm for Betweenness via Random Approximation.
*/
class KadabraBetweenness : public Algorithm {
public:
/**
* If k = 0 the algorithm approximates the betweenness centrality of all
* vertices of the graph so that the scores are within an additive error @a
* err with probability at least (1 - @a delta). Otherwise, the algorithm
* computes the exact ranking of the top-k nodes with highest betweenness
* centrality.
* The algorithm relies on an adaptive random sampling technique of shortest
* paths and the number of samples in the worst case is w = ((log(D - 2) +
* log(2/delta))/err^2 samples, where D is the diameter of the graph.
* Thus, the worst-case performance is O(w * (|E| + |V|)), but performs better
* in practice.
* NB: in order to work properly the Kadabra algorithm requires a random seed
* to be previously set with 'useThreadId' set to true.
*
* @param G the graph
* @param err maximum additive error guaranteed when approximating the
* betweenness centrality of all nodes.
* @param delta probability that the values of the betweenness centrality are
* within the error guarantee.
* @param k the number of top-k nodes to be computed. Set it to zero to
* approximate the betweenness centrality of all the nodes.
* @param unionSample, startFactor algorithm parameters that are automatically
* chosen.
*/
KadabraBetweenness(const Graph &G, const double err = 0.01,
const double delta = 0.1, const count k = 0,
count unionSample = 0, const count startFactor = 100);
/**
* Executes the Kadabra algorithm.
*/
void run() override;
/**
* @return The ranking of the nodes according to their approximated
* betweenness centrality.
*/
std::vector<std::pair<node, double>> ranking() const;
/**
* @return Nodes of the graph sorted by their approximated betweenness
* centrality.
*/
std::vector<node> topkNodesList() const {
assureFinished();
return topkNodes;
}
/**
* @return Sorted list of approximated betweenness centrality scores.
*/
std::vector<double> topkScoresList() const {
assureFinished();
return topkScores;
}
/**
* @return Approximated betweenness centrality score of all the nodes of the
* graph.
*/
std::vector<double> scores() const {
assureFinished();
return approxSum;
}
/**
* @return Total number of samples.
*/
count getNumberOfIterations() const {
assureFinished();
return nPairs;
}
/**
* @return Upper bound to the number of samples.
*/
double getOmega() const {
assureFinished();
return omega;
}
protected:
const Graph &G;
const double delta, err;
const count k, n, startFactor;
count unionSample, omp_max_threads;
std::atomic<std::uint64_t> nPairs;
const bool absolute;
double deltaLMinGuess, deltaUMinGuess, omega;
std::vector<node> topkNodes;
std::vector<double> topkScores;
std::vector<std::pair<node, double>> rankingVector;
Aux::SortedList *top;
ConnectedComponents *cc;
std::vector<std::vector<double>> approx;
std::vector<double> approxSum;
std::vector<double> deltaLGuess;
std::vector<double> deltaUGuess;
const double balancingFactor = 0.001;
const unsigned short itersPerStep = 11;
void init();
void computeDeltaGuess();
void computeBetErr(Status *status, std::vector<double> &bet,
std::vector<double> &errL,
std::vector<double> &errU) const;
void oneRound(SpSampler &sampler);
bool computeFinished(Status *status) const;
void getStatus(Status *status, const bool parallel = false) const;
void computeApproxParallel(const bool normalize = false);
double computeF(const double btilde, const count iterNum,
const double deltaL) const;
double computeG(const double btilde, const count iterNum,
const double deltaU) const;
void fillResult();
void fillPQ() {
for (count i = 0; i < n; ++i) {
top->insert(i, approxSum[i]);
}
}
};
inline std::vector<std::pair<node, double>>
KadabraBetweenness::ranking() const {
assureFinished();
std::vector<std::pair<node, double>> result(topkNodes.size());
#pragma omp parallel for
for (omp_index i = 0; i < static_cast<omp_index>(result.size()); ++i) {
result[i] = std::make_pair(topkNodes[i], topkScores[i]);
}
return result;
}
} // namespace NetworKit
#endif /* ifndef KADABRA_H_ */
|
cg_single.c
|
/*--------------------------------------------------------------------
NAS Parallel Benchmarks 2.3 OpenMP C versions - CG
This benchmark is an OpenMP C version of the NPB CG code.
The OpenMP C versions are developed by RWCP and derived from the serial
Fortran versions in "NPB 2.3-serial" developed by NAS.
Permission to use, copy, distribute and modify this software for any
purpose with or without fee is hereby granted.
This software is provided "as is" without express or implied warranty.
Send comments on the OpenMP C versions to [email protected]
Information on OpenMP activities at RWCP is available at:
http://pdplab.trc.rwcp.or.jp/pdperf/Omni/
Information on NAS Parallel Benchmarks 2.3 is available at:
http://www.nas.nasa.gov/NAS/NPB/
--------------------------------------------------------------------*/
/*--------------------------------------------------------------------
Authors: M. Yarrow
C. Kuszmaul
OpenMP C version: S. Satoh
--------------------------------------------------------------------*/
/*
c---------------------------------------------------------------------
c Note: please observe that in the routine conj_grad three
c implementations of the sparse matrix-vector multiply have
c been supplied. The default matrix-vector multiply is not
c loop unrolled. The alternate implementations are unrolled
c to a depth of 2 and unrolled to a depth of 8. Please
c experiment with these to find the fastest for your particular
c architecture. If reporting timing results, any of these three may
c be used without penalty.
c---------------------------------------------------------------------
*/
//#include "npb-C.h"
/*
NAS Parallel Benchmarks 2.3 OpenMP C Versions
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#if defined(_OPENMP)
#include <omp.h>
#endif /* _OPENMP */
typedef int boolean;
typedef struct { double real; double imag; } dcomplex;
#define TRUE 1
#define FALSE 0
#define max(a,b) (((a) > (b)) ? (a) : (b))
#define min(a,b) (((a) < (b)) ? (a) : (b))
#define pow2(a) ((a)*(a))
#define get_real(c) c.real
#define get_imag(c) c.imag
#define cadd(c,a,b) (c.real = a.real + b.real, c.imag = a.imag + b.imag)
#define csub(c,a,b) (c.real = a.real - b.real, c.imag = a.imag - b.imag)
#define cmul(c,a,b) (c.real = a.real * b.real - a.imag * b.imag, \
c.imag = a.real * b.imag + a.imag * b.real)
#define crmul(c,a,b) (c.real = a.real * b, c.imag = a.imag * b)
extern double randlc(double *, double);
extern void vranlc(int, double *, double, double *);
extern void timer_clear(int);
extern void timer_start(int);
extern void timer_stop(int);
extern double timer_read(int);
extern void c_print_results(char *name, char cclass, int n1, int n2,
int n3, int niter, int nthreads, double t,
double mops, char *optype, int passed_verification,
char *npbversion, char *compiletime, char *cc,
char *clink, char *c_lib, char *c_inc,
char *cflags, char *clinkflags, char *rand);
//#include "npbparams.h"
/******************/
/* default values */
/******************/
#ifndef CLASS
#define CLASS 'B'
#endif
#if CLASS == 'S'
/* CLASS = S */
/*
c This file is generated automatically by the setparams utility.
c It sets the number of processors and the classc of the NPB
c in this directory. Do not modify it by hand.
*/
#define NA 1400
#define NONZER 7
#define NITER 15
#define SHIFT 10.0
#define RCOND 1.0e-1
#define CONVERTDOUBLE FALSE
#endif
#if CLASS == 'W'
/* CLASS = W */
/*
c This file is generated automatically by the setparams utility.
c It sets the number of processors and the classc of the NPB
c in this directory. Do not modify it by hand.
*/
#define NA 7000
#define NONZER 8
#define NITER 15
#define SHIFT 12.0
#define RCOND 1.0e-1
#define CONVERTDOUBLE FALSE
#endif
#if CLASS == 'A'
/* CLASS = A */
/*
c This file is generated automatically by the setparams utility.
c It sets the number of processors and the classc of the NPB
c in this directory. Do not modify it by hand.
*/
#define NA 14000
#define NONZER 11
#define NITER 15
#define SHIFT 20.0
#define RCOND 1.0e-1
#define CONVERTDOUBLE FALSE
#endif
#if CLASS == 'B'
/* CLASS = B */
/*
c This file is generated automatically by the setparams utility.
c It sets the number of processors and the classc of the NPB
c in this directory. Do not modify it by hand.
*/
#define NA 75000
#define NONZER 13
#define NITER 75
#define SHIFT 60.0
#define RCOND 1.0e-1
#define CONVERTDOUBLE FALSE
#endif
#if CLASS == 'C'
/* CLASS = C */
/*
c This file is generated automatically by the setparams utility.
c It sets the number of processors and the classc of the NPB
c in this directory. Do not modify it by hand.
*/
#define NA 150000
#define NONZER 15
#define NITER 75
#define SHIFT 110.0
#define RCOND 1.0e-1
#define CONVERTDOUBLE FALSE
#endif
#define COMPILETIME "28 Oct 2014"
#define NPBVERSION "2.3"
#define CS1 "gcc"
#define CS2 "$(CC)"
#define CS3 "(none)"
#define CS4 "-I../common"
#define CS5 "-fopenmp -O2"
#define CS6 "-lm -fopenmp"
#define CS7 "randdp"
#define NZ NA*(NONZER+1)*(NONZER+1)+NA*(NONZER+2)
/* global variables */
/* common /partit_size/ */
static int naa;
static int nzz;
static int firstrow;
static int lastrow;
static int firstcol;
static int lastcol;
/* common /main_int_mem/ */
static int colidx[NZ+1]; /* colidx[1:NZ] */
static int rowstr[NA+1+1]; /* rowstr[1:NA+1] */
static int iv[2*NA+1+1]; /* iv[1:2*NA+1] */
static int arow[NZ+1]; /* arow[1:NZ] */
static int acol[NZ+1]; /* acol[1:NZ] */
/* common /main_flt_mem/ */
static double v[NA+1+1]; /* v[1:NA+1] */
static double aelt[NZ+1]; /* aelt[1:NZ] */
static double a[NZ+1]; /* a[1:NZ] */
static double x[NA+2+1]; /* x[1:NA+2] */
static double z[NA+2+1]; /* z[1:NA+2] */
static double p[NA+2+1]; /* p[1:NA+2] */
static double q[NA+2+1]; /* q[1:NA+2] */
static double r[NA+2+1]; /* r[1:NA+2] */
static double w[NA+2+1]; /* w[1:NA+2] */
/* common /urando/ */
static double amult;
static double tran;
/* function declarations */
static void conj_grad (int colidx[], int rowstr[], double x[], double z[],
double a[], double p[], double q[], double r[],
double w[], double *rnorm);
static void makea(int n, int nz, double a[], int colidx[], int rowstr[],
int nonzer, int firstrow, int lastrow, int firstcol,
int lastcol, double rcond, int arow[], int acol[],
double aelt[], double v[], int iv[], double shift );
static void sparse(double a[], int colidx[], int rowstr[], int n,
int arow[], int acol[], double aelt[],
int firstrow, int lastrow,
double x[], boolean mark[], int nzloc[], int nnza);
static void sprnvc(int n, int nz, double v[], int iv[], int nzloc[],
int mark[]);
static int icnvrt(double x, int ipwr2);
static void vecset(int n, double v[], int iv[], int *nzv, int i, double val);
/*--------------------------------------------------------------------
program cg
--------------------------------------------------------------------*/
int main(int argc, char **argv) {
int i, j, k, it;
int nthreads = 1;
double zeta;
double rnorm;
double norm_temp11;
double norm_temp12;
double t, mflops;
char cclass;
boolean verified;
double zeta_verify_value, epsilon;
firstrow = 1;
lastrow = NA;
firstcol = 1;
lastcol = NA;
if (NA == 1400 && NONZER == 7 && NITER == 15 && SHIFT == 10.0) {
cclass = 'S';
zeta_verify_value = 8.5971775078648;
} else if (NA == 7000 && NONZER == 8 && NITER == 15 && SHIFT == 12.0) {
cclass = 'W';
zeta_verify_value = 10.362595087124;
} else if (NA == 14000 && NONZER == 11 && NITER == 15 && SHIFT == 20.0) {
cclass = 'A';
zeta_verify_value = 17.130235054029;
} else if (NA == 75000 && NONZER == 13 && NITER == 75 && SHIFT == 60.0) {
cclass = 'B';
zeta_verify_value = 22.712745482631;
} else if (NA == 150000 && NONZER == 15 && NITER == 75 && SHIFT == 110.0) {
cclass = 'C';
zeta_verify_value = 28.973605592845;
} else {
cclass = 'U';
}
printf("\n\n NAS Parallel Benchmarks 2.3 OpenMP C version"
" - CG Benchmark\n");
printf(" Size: %10d\n", NA);
printf(" Iterations: %5d\n", NITER);
naa = NA;
nzz = NZ;
/*--------------------------------------------------------------------
c Initialize random number generator
c-------------------------------------------------------------------*/
tran = 314159265.0;
amult = 1220703125.0;
zeta = randlc( &tran, amult );
/*--------------------------------------------------------------------
c
c-------------------------------------------------------------------*/
makea(naa, nzz, a, colidx, rowstr, NONZER,
firstrow, lastrow, firstcol, lastcol,
RCOND, arow, acol, aelt, v, iv, SHIFT);
/*---------------------------------------------------------------------
c Note: as a result of the above call to makea:
c values of j used in indexing rowstr go from 1 --> lastrow-firstrow+1
c values of colidx which are col indexes go from firstcol --> lastcol
c So:
c Shift the col index vals from actual (firstcol --> lastcol )
c to local, i.e., (1 --> lastcol-firstcol+1)
c---------------------------------------------------------------------*/
#pragma omp parallel private(it,i,j,k)
{
#pragma omp for nowait
for (j = 1; j <= lastrow - firstrow + 1; j++) {
for (k = rowstr[j]; k < rowstr[j+1]; k++) {
colidx[k] = colidx[k] - firstcol + 1;
}
}
/*--------------------------------------------------------------------
c set starting vector to (1, 1, .... 1)
c-------------------------------------------------------------------*/
#pragma omp for nowait
for (i = 1; i <= NA+1; i++) {
x[i] = 1.0;
}
#pragma omp single
zeta = 0.0;
/*-------------------------------------------------------------------
c---->
c Do one iteration untimed to init all code and data page tables
c----> (then reinit, start timing, to niter its)
c-------------------------------------------------------------------*/
for (it = 1; it <= 1; it++) {
/*--------------------------------------------------------------------
c The call to the conjugate gradient routine:
c-------------------------------------------------------------------*/
conj_grad (colidx, rowstr, x, z, a, p, q, r, w, &rnorm);
/*--------------------------------------------------------------------
c zeta = shift + 1/(x.z)
c So, first: (x.z)
c Also, find norm of z
c So, first: (z.z)
c-------------------------------------------------------------------*/
#pragma omp single
{
norm_temp11 = 0.0;
norm_temp12 = 0.0;
} /* end single */
#pragma omp for reduction(+:norm_temp11,norm_temp12)
for (j = 1; j <= lastcol-firstcol+1; j++) {
norm_temp11 = norm_temp11 + x[j]*z[j];
norm_temp12 = norm_temp12 + z[j]*z[j];
}
#pragma omp single
norm_temp12 = 1.0 / sqrt( norm_temp12 );
/*--------------------------------------------------------------------
c Normalize z to obtain x
c-------------------------------------------------------------------*/
#pragma omp for
for (j = 1; j <= lastcol-firstcol+1; j++) {
x[j] = norm_temp12*z[j];
}
} /* end of do one iteration untimed */
/*--------------------------------------------------------------------
c set starting vector to (1, 1, .... 1)
c-------------------------------------------------------------------*/
#pragma omp for nowait
for (i = 1; i <= NA+1; i++) {
x[i] = 1.0;
}
#pragma omp single
zeta = 0.0;
} /* end parallel */
timer_clear( 1 );
timer_start( 1 );
/*--------------------------------------------------------------------
c---->
c Main Iteration for inverse power method
c---->
c-------------------------------------------------------------------*/
#pragma omp parallel private(it,i,j,k)
{
for (it = 1; it <= NITER; it++) {
/*--------------------------------------------------------------------
c The call to the conjugate gradient routine:
c-------------------------------------------------------------------*/
conj_grad(colidx, rowstr, x, z, a, p, q, r, w, &rnorm);
/*--------------------------------------------------------------------
c zeta = shift + 1/(x.z)
c So, first: (x.z)
c Also, find norm of z
c So, first: (z.z)
c-------------------------------------------------------------------*/
#pragma omp single
{
norm_temp11 = 0.0;
norm_temp12 = 0.0;
} /* end single */
#pragma omp for reduction(+:norm_temp11,norm_temp12)
for (j = 1; j <= lastcol-firstcol+1; j++) {
norm_temp11 = norm_temp11 + x[j]*z[j];
norm_temp12 = norm_temp12 + z[j]*z[j];
}
#pragma omp single
{
norm_temp12 = 1.0 / sqrt( norm_temp12 );
zeta = SHIFT + 1.0 / norm_temp11;
} /* end single */
#pragma omp master
{
if( it == 1 ) {
printf(" iteration ||r|| zeta\n");
}
printf(" %5d %20.14e%20.13e\n", it, rnorm, zeta);
} /* end master */
/*--------------------------------------------------------------------
c Normalize z to obtain x
c-------------------------------------------------------------------*/
#pragma omp for
for (j = 1; j <= lastcol-firstcol+1; j++) {
x[j] = norm_temp12*z[j];
}
} /* end of main iter inv pow meth */
#if defined(_OPENMP)
#pragma omp master
nthreads = omp_get_num_threads();
#endif /* _OPENMP */
} /* end parallel */
timer_stop( 1 );
/*--------------------------------------------------------------------
c End of timed section
c-------------------------------------------------------------------*/
t = timer_read( 1 );
printf(" Benchmark completed\n");
epsilon = 1.0e-10;
if (cclass != 'U') {
if (fabs(zeta - zeta_verify_value) <= epsilon) {
verified = TRUE;
printf(" VERIFICATION SUCCESSFUL\n");
printf(" Zeta is %20.12e\n", zeta);
printf(" Error is %20.12e\n", zeta - zeta_verify_value);
} else {
verified = FALSE;
printf(" VERIFICATION FAILED\n");
printf(" Zeta %20.12e\n", zeta);
printf(" The correct zeta is %20.12e\n", zeta_verify_value);
}
} else {
verified = FALSE;
printf(" Problem size unknown\n");
printf(" NO VERIFICATION PERFORMED\n");
}
if ( t != 0.0 ) {
mflops = (2.0*NITER*NA)
* (3.0+(NONZER*(NONZER+1)) + 25.0*(5.0+(NONZER*(NONZER+1))) + 3.0 )
/ t / 1000000.0;
} else {
mflops = 0.0;
}
c_print_results("CG", cclass, NA, 0, 0, NITER, nthreads, t,
mflops, " floating point",
verified, NPBVERSION, COMPILETIME,
CS1, CS2, CS3, CS4, CS5, CS6, CS7);
}
/*--------------------------------------------------------------------
c-------------------------------------------------------------------*/
static void conj_grad (
int colidx[], /* colidx[1:nzz] */
int rowstr[], /* rowstr[1:naa+1] */
double x[], /* x[*] */
double z[], /* z[*] */
double a[], /* a[1:nzz] */
double p[], /* p[*] */
double q[], /* q[*] */
double r[], /* r[*] */
double w[], /* w[*] */
double *rnorm )
/*--------------------------------------------------------------------
c-------------------------------------------------------------------*/
/*---------------------------------------------------------------------
c Floaging point arrays here are named as in NPB1 spec discussion of
c CG algorithm
c---------------------------------------------------------------------*/
{
static double d, sum, rho, rho0, alpha, beta;
int i, j, k;
int cgit, cgitmax = 25;
#pragma omp single nowait
rho = 0.0;
/*--------------------------------------------------------------------
c Initialize the CG algorithm:
c-------------------------------------------------------------------*/
#pragma omp for nowait
for (j = 1; j <= naa+1; j++) {
q[j] = 0.0;
z[j] = 0.0;
r[j] = x[j];
p[j] = r[j];
w[j] = 0.0;
}
/*--------------------------------------------------------------------
c rho = r.r
c Now, obtain the norm of r: First, sum squares of r elements locally...
c-------------------------------------------------------------------*/
#pragma omp for reduction(+:rho)
for (j = 1; j <= lastcol-firstcol+1; j++) {
rho = rho + x[j]*x[j];
}
/*--------------------------------------------------------------------
c---->
c The conj grad iteration loop
c---->
c-------------------------------------------------------------------*/
for (cgit = 1; cgit <= cgitmax; cgit++) {
#pragma omp single nowait
{
rho0 = rho;
d = 0.0;
rho = 0.0;
} /* end single */
/*--------------------------------------------------------------------
c q = A.p
c The partition submatrix-vector multiply: use workspace w
c---------------------------------------------------------------------
C
C NOTE: this version of the multiply is actually (slightly: maybe %5)
C faster on the sp2 on 16 nodes than is the unrolled-by-2 version
C below. On the Cray t3d, the reverse is true, i.e., the
C unrolled-by-two version is some 10% faster.
C The unrolled-by-8 version below is significantly faster
C on the Cray t3d - overall speed of code is 1.5 times faster.
*/
/* rolled version */
#pragma omp for private(sum,k)
for (j = 1; j <= lastrow-firstrow+1; j++) {
sum = 0.0;
for (k = rowstr[j]; k < rowstr[j+1]; k++) {
sum = sum + a[k]*p[colidx[k]];
}
w[j] = sum;
}
/* unrolled-by-two version
#pragma omp for private(i,k)
for (j = 1; j <= lastrow-firstrow+1; j++) {
int iresidue;
double sum1, sum2;
i = rowstr[j];
iresidue = (rowstr[j+1]-i) % 2;
sum1 = 0.0;
sum2 = 0.0;
if (iresidue == 1) sum1 = sum1 + a[i]*p[colidx[i]];
for (k = i+iresidue; k <= rowstr[j+1]-2; k += 2) {
sum1 = sum1 + a[k] * p[colidx[k]];
sum2 = sum2 + a[k+1] * p[colidx[k+1]];
}
w[j] = sum1 + sum2;
}
*/
/* unrolled-by-8 version
#pragma omp for private(i,k,sum)
for (j = 1; j <= lastrow-firstrow+1; j++) {
int iresidue;
i = rowstr[j];
iresidue = (rowstr[j+1]-i) % 8;
sum = 0.0;
for (k = i; k <= i+iresidue-1; k++) {
sum = sum + a[k] * p[colidx[k]];
}
for (k = i+iresidue; k <= rowstr[j+1]-8; k += 8) {
sum = sum + a[k ] * p[colidx[k ]]
+ a[k+1] * p[colidx[k+1]]
+ a[k+2] * p[colidx[k+2]]
+ a[k+3] * p[colidx[k+3]]
+ a[k+4] * p[colidx[k+4]]
+ a[k+5] * p[colidx[k+5]]
+ a[k+6] * p[colidx[k+6]]
+ a[k+7] * p[colidx[k+7]];
}
w[j] = sum;
}
*/
#pragma omp for
for (j = 1; j <= lastcol-firstcol+1; j++) {
q[j] = w[j];
}
/*--------------------------------------------------------------------
c Clear w for reuse...
c-------------------------------------------------------------------*/
#pragma omp for nowait
for (j = 1; j <= lastcol-firstcol+1; j++) {
w[j] = 0.0;
}
/*--------------------------------------------------------------------
c Obtain p.q
c-------------------------------------------------------------------*/
#pragma omp for reduction(+:d)
for (j = 1; j <= lastcol-firstcol+1; j++) {
d = d + p[j]*q[j];
}
/*--------------------------------------------------------------------
c Obtain alpha = rho / (p.q)
c-------------------------------------------------------------------*/
#pragma omp single
alpha = rho0 / d;
/*--------------------------------------------------------------------
c Save a temporary of rho
c-------------------------------------------------------------------*/
/* rho0 = rho;*/
/*---------------------------------------------------------------------
c Obtain z = z + alpha*p
c and r = r - alpha*q
c---------------------------------------------------------------------*/
#pragma omp for
for (j = 1; j <= lastcol-firstcol+1; j++) {
z[j] = z[j] + alpha*p[j];
r[j] = r[j] - alpha*q[j];
}
/*---------------------------------------------------------------------
c rho = r.r
c Now, obtain the norm of r: First, sum squares of r elements locally...
c---------------------------------------------------------------------*/
#pragma omp for reduction(+:rho)
for (j = 1; j <= lastcol-firstcol+1; j++) {
rho = rho + r[j]*r[j];
}
/*--------------------------------------------------------------------
c Obtain beta:
c-------------------------------------------------------------------*/
#pragma omp single
beta = rho / rho0;
/*--------------------------------------------------------------------
c p = r + beta*p
c-------------------------------------------------------------------*/
#pragma omp for
for (j = 1; j <= lastcol-firstcol+1; j++) {
p[j] = r[j] + beta*p[j];
}
} /* end of do cgit=1,cgitmax */
/*---------------------------------------------------------------------
c Compute residual norm explicitly: ||r|| = ||x - A.z||
c First, form A.z
c The partition submatrix-vector multiply
c---------------------------------------------------------------------*/
#pragma omp single nowait
sum = 0.0;
#pragma omp for private(d, k)
for (j = 1; j <= lastrow-firstrow+1; j++) {
d = 0.0;
for (k = rowstr[j]; k <= rowstr[j+1]-1; k++) {
d = d + a[k]*z[colidx[k]];
}
w[j] = d;
}
#pragma omp for
for (j = 1; j <= lastcol-firstcol+1; j++) {
r[j] = w[j];
}
/*--------------------------------------------------------------------
c At this point, r contains A.z
c-------------------------------------------------------------------*/
#pragma omp for reduction(+:sum) private(d)
for (j = 1; j <= lastcol-firstcol+1; j++) {
d = x[j] - r[j];
sum = sum + d*d;
}
#pragma omp single
{
(*rnorm) = sqrt(sum);
} /* end single */
}
/*---------------------------------------------------------------------
c generate the test problem for benchmark 6
c makea generates a sparse matrix with a
c prescribed sparsity distribution
c
c parameter type usage
c
c input
c
c n i number of cols/rows of matrix
c nz i nonzeros as declared array size
c rcond r*8 condition number
c shift r*8 main diagonal shift
c
c output
c
c a r*8 array for nonzeros
c colidx i col indices
c rowstr i row pointers
c
c workspace
c
c iv, arow, acol i
c v, aelt r*8
c---------------------------------------------------------------------*/
static void makea(
int n,
int nz,
double a[], /* a[1:nz] */
int colidx[], /* colidx[1:nz] */
int rowstr[], /* rowstr[1:n+1] */
int nonzer,
int firstrow,
int lastrow,
int firstcol,
int lastcol,
double rcond,
int arow[], /* arow[1:nz] */
int acol[], /* acol[1:nz] */
double aelt[], /* aelt[1:nz] */
double v[], /* v[1:n+1] */
int iv[], /* iv[1:2*n+1] */
double shift )
{
int i, nnza, iouter, ivelt, ivelt1, irow, nzv;
/*--------------------------------------------------------------------
c nonzer is approximately (int(sqrt(nnza /n)));
c-------------------------------------------------------------------*/
double size, ratio, scale;
int jcol;
size = 1.0;
ratio = pow(rcond, (1.0 / (double)n));
nnza = 0;
/*---------------------------------------------------------------------
c Initialize colidx(n+1 .. 2n) to zero.
c Used by sprnvc to mark nonzero positions
c---------------------------------------------------------------------*/
#pragma omp parallel for
for (i = 1; i <= n; i++) {
colidx[n+i] = 0;
}
for (iouter = 1; iouter <= n; iouter++) {
nzv = nonzer;
sprnvc(n, nzv, v, iv, &(colidx[0]), &(colidx[n]));
vecset(n, v, iv, &nzv, iouter, 0.5);
for (ivelt = 1; ivelt <= nzv; ivelt++) {
jcol = iv[ivelt];
if (jcol >= firstcol && jcol <= lastcol) {
scale = size * v[ivelt];
for (ivelt1 = 1; ivelt1 <= nzv; ivelt1++) {
irow = iv[ivelt1];
if (irow >= firstrow && irow <= lastrow) {
nnza = nnza + 1;
if (nnza > nz) {
printf("Space for matrix elements exceeded in"
" makea\n");
printf("nnza, nzmax = %d, %d\n", nnza, nz);
printf("iouter = %d\n", iouter);
exit(1);
}
acol[nnza] = jcol;
arow[nnza] = irow;
aelt[nnza] = v[ivelt1] * scale;
}
}
}
}
size = size * ratio;
}
/*---------------------------------------------------------------------
c ... add the identity * rcond to the generated matrix to bound
c the smallest eigenvalue from below by rcond
c---------------------------------------------------------------------*/
for (i = firstrow; i <= lastrow; i++) {
if (i >= firstcol && i <= lastcol) {
iouter = n + i;
nnza = nnza + 1;
if (nnza > nz) {
printf("Space for matrix elements exceeded in makea\n");
printf("nnza, nzmax = %d, %d\n", nnza, nz);
printf("iouter = %d\n", iouter);
exit(1);
}
acol[nnza] = i;
arow[nnza] = i;
aelt[nnza] = rcond - shift;
}
}
/*---------------------------------------------------------------------
c ... make the sparse matrix from list of elements with duplicates
c (v and iv are used as workspace)
c---------------------------------------------------------------------*/
sparse(a, colidx, rowstr, n, arow, acol, aelt,
firstrow, lastrow, v, &(iv[0]), &(iv[n]), nnza);
}
/*---------------------------------------------------
c generate a sparse matrix from a list of
c [col, row, element] tri
c---------------------------------------------------*/
static void sparse(
double a[], /* a[1:*] */
int colidx[], /* colidx[1:*] */
int rowstr[], /* rowstr[1:*] */
int n,
int arow[], /* arow[1:*] */
int acol[], /* acol[1:*] */
double aelt[], /* aelt[1:*] */
int firstrow,
int lastrow,
double x[], /* x[1:n] */
boolean mark[], /* mark[1:n] */
int nzloc[], /* nzloc[1:n] */
int nnza)
/*---------------------------------------------------------------------
c rows range from firstrow to lastrow
c the rowstr pointers are defined for nrows = lastrow-firstrow+1 values
c---------------------------------------------------------------------*/
{
int nrows;
int i, j, jajp1, nza, k, nzrow;
double xi;
/*--------------------------------------------------------------------
c how many rows of result
c-------------------------------------------------------------------*/
nrows = lastrow - firstrow + 1;
/*--------------------------------------------------------------------
c ...count the number of triples in each row
c-------------------------------------------------------------------*/
#pragma omp parallel for
for (j = 1; j <= n; j++) {
rowstr[j] = 0;
mark[j] = FALSE;
}
rowstr[n+1] = 0;
for (nza = 1; nza <= nnza; nza++) {
j = (arow[nza] - firstrow + 1) + 1;
rowstr[j] = rowstr[j] + 1;
}
rowstr[1] = 1;
for (j = 2; j <= nrows+1; j++) {
rowstr[j] = rowstr[j] + rowstr[j-1];
}
/*---------------------------------------------------------------------
c ... rowstr(j) now is the location of the first nonzero
c of row j of a
c---------------------------------------------------------------------*/
/*--------------------------------------------------------------------
c ... do a bucket sort of the triples on the row index
c-------------------------------------------------------------------*/
for (nza = 1; nza <= nnza; nza++) {
j = arow[nza] - firstrow + 1;
k = rowstr[j];
a[k] = aelt[nza];
colidx[k] = acol[nza];
rowstr[j] = rowstr[j] + 1;
}
/*--------------------------------------------------------------------
c ... rowstr(j) now points to the first element of row j+1
c-------------------------------------------------------------------*/
for (j = nrows; j >= 1; j--) {
rowstr[j+1] = rowstr[j];
}
rowstr[1] = 1;
/*--------------------------------------------------------------------
c ... generate the actual output rows by adding elements
c-------------------------------------------------------------------*/
nza = 0;
#pragma omp parallel for
for (i = 1; i <= n; i++) {
x[i] = 0.0;
mark[i] = FALSE;
}
jajp1 = rowstr[1];
for (j = 1; j <= nrows; j++) {
nzrow = 0;
/*--------------------------------------------------------------------
c ...loop over the jth row of a
c-------------------------------------------------------------------*/
for (k = jajp1; k < rowstr[j+1]; k++) {
i = colidx[k];
x[i] = x[i] + a[k];
if ( mark[i] == FALSE && x[i] != 0.0) {
mark[i] = TRUE;
nzrow = nzrow + 1;
nzloc[nzrow] = i;
}
}
/*--------------------------------------------------------------------
c ... extract the nonzeros of this row
c-------------------------------------------------------------------*/
for (k = 1; k <= nzrow; k++) {
i = nzloc[k];
mark[i] = FALSE;
xi = x[i];
x[i] = 0.0;
if (xi != 0.0) {
nza = nza + 1;
a[nza] = xi;
colidx[nza] = i;
}
}
jajp1 = rowstr[j+1];
rowstr[j+1] = nza + rowstr[1];
}
}
/*---------------------------------------------------------------------
c generate a sparse n-vector (v, iv)
c having nzv nonzeros
c
c mark(i) is set to 1 if position i is nonzero.
c mark is all zero on entry and is reset to all zero before exit
c this corrects a performance bug found by John G. Lewis, caused by
c reinitialization of mark on every one of the n calls to sprnvc
---------------------------------------------------------------------*/
static void sprnvc(
int n,
int nz,
double v[], /* v[1:*] */
int iv[], /* iv[1:*] */
int nzloc[], /* nzloc[1:n] */
int mark[] ) /* mark[1:n] */
{
int nn1;
int nzrow, nzv, ii, i;
double vecelt, vecloc;
nzv = 0;
nzrow = 0;
nn1 = 1;
do {
nn1 = 2 * nn1;
} while (nn1 < n);
/*--------------------------------------------------------------------
c nn1 is the smallest power of two not less than n
c-------------------------------------------------------------------*/
while (nzv < nz) {
vecelt = randlc(&tran, amult);
/*--------------------------------------------------------------------
c generate an integer between 1 and n in a portable manner
c-------------------------------------------------------------------*/
vecloc = randlc(&tran, amult);
i = icnvrt(vecloc, nn1) + 1;
if (i > n) continue;
/*--------------------------------------------------------------------
c was this integer generated already?
c-------------------------------------------------------------------*/
if (mark[i] == 0) {
mark[i] = 1;
nzrow = nzrow + 1;
nzloc[nzrow] = i;
nzv = nzv + 1;
v[nzv] = vecelt;
iv[nzv] = i;
}
}
for (ii = 1; ii <= nzrow; ii++) {
i = nzloc[ii];
mark[i] = 0;
}
}
/*---------------------------------------------------------------------
* scale a double precision number x in (0,1) by a power of 2 and chop it
*---------------------------------------------------------------------*/
static int icnvrt(double x, int ipwr2) {
return ((int)(ipwr2 * x));
}
/*--------------------------------------------------------------------
c set ith element of sparse vector (v, iv) with
c nzv nonzeros to val
c-------------------------------------------------------------------*/
static void vecset(
int n,
double v[], /* v[1:*] */
int iv[], /* iv[1:*] */
int *nzv,
int i,
double val)
{
int k;
boolean set;
set = FALSE;
for (k = 1; k <= *nzv; k++) {
if (iv[k] == i) {
v[k] = val;
set = TRUE;
}
}
if (set == FALSE) {
*nzv = *nzv + 1;
v[*nzv] = val;
iv[*nzv] = i;
}
}
/* cat ./common/c_print_results.c */
/*****************************************************************/
/****** C _ P R I N T _ R E S U L T S ******/
/*****************************************************************/
void c_print_results( char *name,
char cclass,
int n1,
int n2,
int n3,
int niter,
int nthreads,
double t,
double mops,
char *optype,
int passed_verification,
char *npbversion,
char *compiletime,
char *cc,
char *clink,
char *c_lib,
char *c_inc,
char *cflags,
char *clinkflags,
char *rand)
{
char *evalue="1000";
printf( "\n\n %s Benchmark Completed\n", name );
printf( " Class = %c\n", cclass );
if( n2 == 0 && n3 == 0 )
printf( " Size = %12d\n", n1 ); /* as in IS */
else
printf( " Size = %3dx%3dx%3d\n", n1,n2,n3 );
printf( " Iterations = %12d\n", niter );
printf( " Threads = %12d\n", nthreads );
printf( " Time in seconds = %12.2f\n", t );
printf( " Mop/s total = %12.2f\n", mops );
printf( " Operation type = %24s\n", optype);
if( passed_verification )
printf( " Verification = SUCCESSFUL\n" );
else
printf( " Verification = UNSUCCESSFUL\n" );
printf( " Version = %12s\n", npbversion );
printf( " Compile date = %12s\n", compiletime );
printf( "\n Compile options:\n" );
printf( " CC = %s\n", cc );
printf( " CLINK = %s\n", clink );
printf( " C_LIB = %s\n", c_lib );
printf( " C_INC = %s\n", c_inc );
printf( " CFLAGS = %s\n", cflags );
printf( " CLINKFLAGS = %s\n", clinkflags );
printf( " RAND = %s\n", rand );
#ifdef SMP
evalue = getenv("MP_SET_NUMTHREADS");
printf( " MULTICPUS = %s\n", evalue );
#endif
/* printf( "\n\n" );
printf( " Please send the results of this run to:\n\n" );
printf( " NPB Development Team\n" );
printf( " Internet: [email protected]\n \n" );
printf( " If email is not available, send this to:\n\n" );
printf( " MS T27A-1\n" );
printf( " NASA Ames Research Center\n" );
printf( " Moffett Field, CA 94035-1000\n\n" );
printf( " Fax: 415-604-3957\n\n" );*/
}
/*
cat ./common/c_timers.c
*/
/*
#include "wtime.h"
#if defined(IBM)
#define wtime wtime
#elif defined(CRAY)
#define wtime WTIME
#else
#define wtime wtime_
#endif
*/
/* Prototype */
void wtime( double * );
/*****************************************************************/
/****** E L A P S E D _ T I M E ******/
/*****************************************************************/
double elapsed_time( void )
{
double t;
wtime( &t );
return( t );
}
double start[64], elapsed[64];
/*****************************************************************/
/****** T I M E R _ C L E A R ******/
/*****************************************************************/
void timer_clear( int n )
{
elapsed[n] = 0.0;
}
/*****************************************************************/
/****** T I M E R _ S T A R T ******/
/*****************************************************************/
void timer_start( int n )
{
start[n] = elapsed_time();
}
/*****************************************************************/
/****** T I M E R _ S T O P ******/
/*****************************************************************/
void timer_stop( int n )
{
double t, now;
now = elapsed_time();
t = now - start[n];
elapsed[n] += t;
}
/*****************************************************************/
/****** T I M E R _ R E A D ******/
/*****************************************************************/
double timer_read( int n )
{
return( elapsed[n] );
}
void wtime(double *t)
{
static int sec = -1;
struct timeval tv;
gettimeofday(&tv, (void *)0);
// gettimeofday(&tv, (struct timezone *)0);
if (sec < 0) sec = tv.tv_sec;
*t = (tv.tv_sec - sec) + 1.0e-6*tv.tv_usec;
}
// common/c_randdp.c
/*
*/
#if defined(USE_POW)
#define r23 pow(0.5, 23.0)
#define r46 (r23*r23)
#define t23 pow(2.0, 23.0)
#define t46 (t23*t23)
#else
#define r23 (0.5*0.5*0.5*0.5*0.5*0.5*0.5*0.5*0.5*0.5*0.5*0.5*0.5*0.5*0.5*0.5*0.5*0.5*0.5*0.5*0.5*0.5*0.5)
#define r46 (r23*r23)
#define t23 (2.0*2.0*2.0*2.0*2.0*2.0*2.0*2.0*2.0*2.0*2.0*2.0*2.0*2.0*2.0*2.0*2.0*2.0*2.0*2.0*2.0*2.0*2.0)
#define t46 (t23*t23)
#endif
/*c---------------------------------------------------------------------
c---------------------------------------------------------------------*/
double randlc (double *x, double a) {
/*c---------------------------------------------------------------------
c---------------------------------------------------------------------*/
/*c---------------------------------------------------------------------
c
c This routine returns a uniform pseudorandom double precision number in the
c range (0, 1) by using the linear congruential generator
c
c x_{k+1} = a x_k (mod 2^46)
c
c where 0 < x_k < 2^46 and 0 < a < 2^46. This scheme generates 2^44 numbers
c before repeating. The argument A is the same as 'a' in the above formula,
c and X is the same as x_0. A and X must be odd double precision integers
c in the range (1, 2^46). The returned value RANDLC is normalized to be
c between 0 and 1, i.e. RANDLC = 2^(-46) * x_1. X is updated to contain
c the new seed x_1, so that subsequent calls to RANDLC using the same
c arguments will generate a continuous sequence.
c
c This routine should produce the same results on any computer with at least
c 48 mantissa bits in double precision floating point data. On 64 bit
c systems, double precision should be disabled.
c
c David H. Bailey October 26, 1990
c
c---------------------------------------------------------------------*/
double t1,t2,t3,t4,a1,a2,x1,x2,z;
/*c---------------------------------------------------------------------
c Break A into two parts such that A = 2^23 * A1 + A2.
c---------------------------------------------------------------------*/
t1 = r23 * a;
a1 = (int)t1;
a2 = a - t23 * a1;
/*c---------------------------------------------------------------------
c Break X into two parts such that X = 2^23 * X1 + X2, compute
c Z = A1 * X2 + A2 * X1 (mod 2^23), and then
c X = 2^23 * Z + A2 * X2 (mod 2^46).
c---------------------------------------------------------------------*/
t1 = r23 * (*x);
x1 = (int)t1;
x2 = (*x) - t23 * x1;
t1 = a1 * x2 + a2 * x1;
t2 = (int)(r23 * t1);
z = t1 - t23 * t2;
t3 = t23 * z + a2 * x2;
t4 = (int)(r46 * t3);
(*x) = t3 - t46 * t4;
return (r46 * (*x));
}
|
wave1d.c
|
#ifndef TAPENADE
#include <math.h>
#endif
#define Max(x,y) fmax(x,y)
#define Min(x,y) fmin(x,y)
#define Heaviside(x) ((x>=0)?1.0:0.0)
#define u(x) u[x]
#define c(x) c[x]
#define u_1(x) u_1[x]
#define u_2(x) u_2[x]
void wave1d(double* u, double* c, double* u_1, double* u_2, double D, int n) {
int i;
#pragma omp parallel for private(i)
for ( i=1; i<=n - 2; i++ ) {
u(i) += D*(-2*u_1(i) + u_1(i - 1) + u_1(i + 1))*c(i) + 2.0*u_1(i) - u_2(i);
}
}
|
convolution_1x1_pack4.h
|
// Tencent is pleased to support the open source community by making ncnn available.
//
// Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// https://opensource.org/licenses/BSD-3-Clause
//
// 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.
static void conv1x1s1_sgemm_pack4_msa(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel, const Mat& _bias, const Option& opt)
{
int w = bottom_blob.w;
int h = bottom_blob.h;
const int size = w * h;
Mat bottom_im2col = bottom_blob;
bottom_im2col.w = size;
bottom_im2col.h = 1;
im2col_sgemm_pack4_msa(bottom_im2col, top_blob, kernel, _bias, opt);
}
static void conv1x1s2_pack4_msa(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel, const Mat& _bias, const Option& opt)
{
int w = bottom_blob.w;
int channels = bottom_blob.c;
size_t elemsize = bottom_blob.elemsize;
int elempack = bottom_blob.elempack;
int outw = top_blob.w;
int outh = top_blob.h;
const int tailstep = (w - 2 * outw + w) * 4;
Mat bottom_blob_shrinked;
bottom_blob_shrinked.create(outw, outh, channels, elemsize, elempack, opt.workspace_allocator);
#pragma omp parallel for num_threads(opt.num_threads)
for (int p = 0; p < channels; p++)
{
const float* r0 = bottom_blob.channel(p);
float* outptr = bottom_blob_shrinked.channel(p);
for (int i = 0; i < outh; i++)
{
for (int j = 0; j < outw; j++)
{
v4f32 _val = (v4f32)__msa_ld_w(r0, 0);
__msa_st_w((v4i32)_val, outptr, 0);
r0 += 4 * 2;
outptr += 4;
}
r0 += tailstep;
}
}
conv1x1s1_sgemm_pack4_msa(bottom_blob_shrinked, top_blob, kernel, _bias, opt);
}
|
Example_nesting_restrict.3.c
|
/*
* @@name: nesting_restrict.3c
* @@type: C
* @@compilable: no
* @@linkable: no
* @@expect: failure
*/
void work(int i, int j) {}
void wrong3(int n)
{
#pragma omp parallel default(shared)
{
int i;
#pragma omp for
for (i=0; i<n; i++) {
/* incorrect nesting of regions */
#pragma omp single
work(i, 0);
}
}
}
|
idaFoodWeb_bnd_omp.c
|
/*
* -----------------------------------------------------------------
* Programmer(s): Daniel R. Reynolds and Ting Yan @ SMU
* Based on idaFoodWeb_bnd.c and parallelized with OpenMP
* -----------------------------------------------------------------
* SUNDIALS Copyright Start
* Copyright (c) 2002-2020, Lawrence Livermore National Security
* and Southern Methodist University.
* All rights reserved.
*
* See the top-level LICENSE and NOTICE files for details.
*
* SPDX-License-Identifier: BSD-3-Clause
* SUNDIALS Copyright End
* -----------------------------------------------------------------
* Example program for IDA: Food web problem.
*
* This example program (OpenMP version) uses the SUNBAND linear
* solver, and IDACalcIC for initial condition calculation.
*
* The mathematical problem solved in this example is a DAE system
* that arises from a system of partial differential equations after
* spatial discretization. The PDE system is a food web population
* model, with predator-prey interaction and diffusion on the unit
* square in two dimensions. The dependent variable vector is:
*
* 1 2 ns
* c = (c , c , ..., c ) , ns = 2 * np
*
* and the PDE's are as follows:
*
* i i i
* dc /dt = d(i)*(c + c ) + R (x,y,c) (i = 1,...,np)
* xx yy i
*
* i i
* 0 = d(i)*(c + c ) + R (x,y,c) (i = np+1,...,ns)
* xx yy i
*
* where the reaction terms R are:
*
* i ns j
* R (x,y,c) = c * (b(i) + sum a(i,j)*c )
* i j=1
*
* The number of species is ns = 2 * np, with the first np being
* prey and the last np being predators. The coefficients a(i,j),
* b(i), d(i) are:
*
* a(i,i) = -AA (all i)
* a(i,j) = -GG (i <= np , j > np)
* a(i,j) = EE (i > np, j <= np)
* all other a(i,j) = 0
* b(i) = BB*(1+ alpha * x*y + beta*sin(4 pi x)*sin(4 pi y)) (i <= np)
* b(i) =-BB*(1+ alpha * x*y + beta*sin(4 pi x)*sin(4 pi y)) (i > np)
* d(i) = DPREY (i <= np)
* d(i) = DPRED (i > np)
*
* The various scalar parameters required are set using '#define'
* statements or directly in routine InitUserData. In this program,
* np = 1, ns = 2. The boundary conditions are homogeneous Neumann:
* normal derivative = 0.
*
* A polynomial in x and y is used to set the initial values of the
* first np variables (the prey variables) at each x,y location,
* while initial values for the remaining (predator) variables are
* set to a flat value, which is corrected by IDACalcIC.
*
* The PDEs are discretized by central differencing on a MX by MY
* mesh.
*
* The DAE system is solved by IDA using the SUNBAND linear solver.
* Output is printed at t = 0, .001, .01, .1, .4, .7, 1.
*
* Optionally, we can set the number of threads from environment
* variable or command line. To check the current value for number
* of threads from environment:
* % echo $OMP_NUM_THREADS
*
* Execution:
*
* To use the default value for the number of threads from
* the OMP_NUM_THREADS environment value:
* % ./idaFoodWeb_bnd_omp
* To specify the number of threads at the command line, use
* % ./idaFoodWeb_bnd_omp num_threads
* where num_threads is the desired number of threads.
*
* -----------------------------------------------------------------
* References:
* [1] Peter N. Brown and Alan C. Hindmarsh,
* Reduced Storage Matrix Methods in Stiff ODE systems, Journal
* of Applied Mathematics and Computation, Vol. 31 (May 1989),
* pp. 40-91.
*
* [2] Peter N. Brown, Alan C. Hindmarsh, and Linda R. Petzold,
* Using Krylov Methods in the Solution of Large-Scale
* Differential-Algebraic Systems, SIAM J. Sci. Comput., 15
* (1994), pp. 1467-1488.
*
* [3] Peter N. Brown, Alan C. Hindmarsh, and Linda R. Petzold,
* Consistent Initial Condition Calculation for Differential-
* Algebraic Systems, SIAM J. Sci. Comput., 19 (1998),
* pp. 1495-1512.
* -----------------------------------------------------------------
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <ida/ida.h>
#include <sunmatrix/sunmatrix_band.h>
#include <sunlinsol/sunlinsol_band.h>
#include <nvector/nvector_openmp.h>
#include <sundials/sundials_direct.h>
#include <sundials/sundials_types.h>
#ifdef _OPENMP
#include <omp.h>
#endif
/* Problem Constants. */
#define NPREY 1 /* No. of prey (= no. of predators). */
#define NUM_SPECIES 2*NPREY
#define PI RCONST(3.1415926535898)
#define FOURPI (RCONST(4.0)*PI)
#define MX 20 /* MX = number of x mesh points */
#define MY 20 /* MY = number of y mesh points */
#define NSMX (NUM_SPECIES * MX)
#define NEQ (NUM_SPECIES*MX*MY)
#define AA RCONST(1.0) /* Coefficient in above eqns. for a */
#define EE RCONST(10000.) /* Coefficient in above eqns. for a */
#define GG RCONST(0.5e-6) /* Coefficient in above eqns. for a */
#define BB RCONST(1.0) /* Coefficient in above eqns. for b */
#define DPREY RCONST(1.0) /* Coefficient in above eqns. for d */
#define DPRED RCONST(0.05) /* Coefficient in above eqns. for d */
#define ALPHA RCONST(50.) /* Coefficient alpha in above eqns. */
#define BETA RCONST(1000.) /* Coefficient beta in above eqns. */
#define AX RCONST(1.0) /* Total range of x variable */
#define AY RCONST(1.0) /* Total range of y variable */
#define RTOL RCONST(1.e-5) /* Relative tolerance */
#define ATOL RCONST(1.e-5) /* Absolute tolerance */
#define NOUT 6 /* Number of output times */
#define TMULT RCONST(10.0) /* Multiplier for tout values */
#define TADD RCONST(0.3) /* Increment for tout values */
#define ZERO RCONST(0.)
#define ONE RCONST(1.0)
/*
* User-defined vector and accessor macro: IJ_Vptr.
* IJ_Vptr is defined in order to express the underlying 3-D structure of
* the dependent variable vector from its underlying 1-D storage (an N_Vector).
* IJ_Vptr(vv,i,j) returns a pointer to the location in vv corresponding to
* species index is = 0, x-index ix = i, and y-index jy = j.
*/
#define IJ_Vptr(vv,i,j) (&NV_Ith_OMP(vv, (i)*NUM_SPECIES + (j)*NSMX))
/* Type: UserData. Contains problem constants, etc. */
typedef struct {
sunindextype Neq, ns, np, mx, my;
realtype dx, dy, **acoef;
realtype cox[NUM_SPECIES], coy[NUM_SPECIES], bcoef[NUM_SPECIES];
N_Vector rates;
int nthreads;
} *UserData;
/* Prototypes for functions called by the IDA Solver. */
static int resweb(realtype time, N_Vector cc, N_Vector cp, N_Vector resval,
void *user_data);
/* Prototypes for private Helper Functions. */
static void InitUserData(UserData webdata);
static void SetInitialProfiles(N_Vector cc, N_Vector cp, N_Vector id,
UserData webdata);
static void PrintHeader(sunindextype mu, sunindextype ml, realtype rtol, realtype atol);
static void PrintOutput(void *ida_mem, N_Vector c, realtype t);
static void PrintFinalStats(void *ida_mem);
static void Fweb(realtype tcalc, N_Vector cc, N_Vector crate, UserData webdata);
static void WebRates(realtype xx, realtype yy, realtype *cxy, realtype *ratesxy,
UserData webdata);
static realtype dotprod(sunindextype size, realtype *x1, realtype *x2);
static int check_retval(void *returnvalue, char *funcname, int opt);
/*
*--------------------------------------------------------------------
* MAIN PROGRAM
*--------------------------------------------------------------------
*/
int main(int argc, char *argv[])
{
void *ida_mem;
SUNMatrix A;
SUNLinearSolver LS;
UserData webdata;
N_Vector cc, cp, id;
int iout, retval;
sunindextype mu, ml;
realtype rtol, atol, t0, tout, tret;
int num_threads;
ida_mem = NULL;
A = NULL;
LS = NULL;
webdata = NULL;
cc = cp = id = NULL;
/* Set the number of threads to use */
num_threads = 1; /* default value */
#ifdef _OPENMP
num_threads = omp_get_max_threads(); /* overwrite with OMP_NUM_THREADS enviroment variable */
#endif
if (argc > 1) /* overwrite with command line value, if supplied */
num_threads = (int) strtol(argv[1], NULL, 0);
/* Allocate and initialize user data block webdata. */
webdata = (UserData) malloc(sizeof *webdata);
webdata->rates = N_VNew_OpenMP(NEQ, num_threads);
webdata->acoef = newDenseMat(NUM_SPECIES, NUM_SPECIES);
webdata->nthreads = num_threads;
InitUserData(webdata);
/* Allocate N-vectors and initialize cc, cp, and id. */
cc = N_VNew_OpenMP(NEQ, num_threads);
if(check_retval((void *)cc, "N_VNew_OpenMP", 0)) return(1);
cp = N_VNew_OpenMP(NEQ, num_threads);
if(check_retval((void *)cp, "N_VNew_OpenMP", 0)) return(1);
id = N_VNew_OpenMP(NEQ, num_threads);
if(check_retval((void *)id, "N_VNew_OpenMP", 0)) return(1);
SetInitialProfiles(cc, cp, id, webdata);
/* Set remaining inputs to IDAMalloc. */
t0 = ZERO;
rtol = RTOL;
atol = ATOL;
/* Call IDACreate and IDAMalloc to initialize IDA. */
ida_mem = IDACreate();
if(check_retval((void *) ida_mem, "IDACreate", 0)) return(1);
retval = IDASetUserData(ida_mem, webdata);
if(check_retval(&retval, "IDASetUserData", 1)) return(1);
retval = IDASetId(ida_mem, id);
if(check_retval(&retval, "IDASetId", 1)) return(1);
retval = IDAInit(ida_mem, resweb, t0, cc, cp);
if(check_retval(&retval, "IDAInit", 1)) return(1);
retval = IDASStolerances(ida_mem, rtol, atol);
if(check_retval(&retval, "IDASStolerances", 1)) return(1);
/* Setup band matrix and linear solver, and attach to IDA. */
mu = ml = NSMX;
A = SUNBandMatrix(NEQ, mu, ml);
if(check_retval((void *)A, "SUNBandMatrix", 0)) return(1);
LS = SUNLinSol_Band(cc, A);
if(check_retval((void *)LS, "SUNLinSol_Band", 0)) return(1);
retval = IDASetLinearSolver(ida_mem, LS, A);
if(check_retval(&retval, "IDASetLinearSolver", 1)) return(1);
/* Call IDACalcIC (with default options) to correct the initial values. */
tout = RCONST(0.001);
retval = IDACalcIC(ida_mem, IDA_YA_YDP_INIT, tout);
if(check_retval(&retval, "IDACalcIC", 1)) return(1);
/* Print heading, basic parameters, and initial values. */
PrintHeader(mu, ml, rtol, atol);
PrintOutput(ida_mem, cc, ZERO);
/* Loop over iout, call IDASolve (normal mode), print selected output. */
for (iout = 1; iout <= NOUT; iout++) {
retval = IDASolve(ida_mem, tout, &tret, cc, cp, IDA_NORMAL);
if(check_retval(&retval, "IDASolve", 1)) return(retval);
PrintOutput(ida_mem, cc, tret);
if (iout < 3) tout *= TMULT; else tout += TADD;
}
/* Print final statistics and free memory. */
PrintFinalStats(ida_mem);
printf("num_threads = %i\n\n", num_threads);
/* Free memory */
IDAFree(&ida_mem);
SUNLinSolFree(LS);
SUNMatDestroy(A);
N_VDestroy_OpenMP(cc);
N_VDestroy_OpenMP(cp);
N_VDestroy_OpenMP(id);
destroyMat(webdata->acoef);
N_VDestroy_OpenMP(webdata->rates);
free(webdata);
return(0);
}
/* Define lines for readability in later routines */
#define acoef (webdata->acoef)
#define bcoef (webdata->bcoef)
#define cox (webdata->cox)
#define coy (webdata->coy)
/*
*--------------------------------------------------------------------
* FUNCTIONS CALLED BY IDA
*--------------------------------------------------------------------
*/
/*
* resweb: System residual function for predator-prey system.
* This routine calls Fweb to get all the right-hand sides of the
* equations, then loads the residual vector accordingly,
* using cp in the case of prey species.
*/
static int resweb(realtype tt, N_Vector cc, N_Vector cp,
N_Vector res, void *user_data)
{
sunindextype jx, jy, is, yloc, loc, np;
realtype *resv, *cpv;
UserData webdata;
jx = jy = is = 0;
webdata = (UserData)user_data;
cpv = NV_DATA_OMP(cp);
resv = NV_DATA_OMP(res);
np = webdata->np;
/* Call Fweb to set res to vector of right-hand sides. */
Fweb(tt, cc, res, webdata);
/* Loop over all grid points, setting residual values appropriately
for differential or algebraic components. */
#pragma omp parallel for default(shared) private(jy, yloc, jx, loc, is) schedule(static) num_threads(webdata->nthreads)
for (jy = 0; jy < MY; jy++) {
yloc = NSMX * jy;
for (jx = 0; jx < MX; jx++) {
loc = yloc + NUM_SPECIES * jx;
for (is = 0; is < NUM_SPECIES; is++) {
if (is < np)
resv[loc+is] = cpv[loc+is] - resv[loc+is];
else
resv[loc+is] = -resv[loc+is];
}
}
}
return(0);
}
/*
*--------------------------------------------------------------------
* PRIVATE FUNCTIONS
*--------------------------------------------------------------------
*/
/*
* InitUserData: Load problem constants in webdata (of type UserData).
*/
static void InitUserData(UserData webdata)
{
sunindextype i, j, np;
realtype *a1,*a2, *a3, *a4, dx2, dy2;
webdata->mx = MX;
webdata->my = MY;
webdata->ns = NUM_SPECIES;
webdata->np = NPREY;
webdata->dx = AX/(MX-1);
webdata->dy = AY/(MY-1);
webdata->Neq= NEQ;
/* Set up the coefficients a and b, and others found in the equations. */
np = webdata->np;
dx2 = (webdata->dx)*(webdata->dx); dy2 = (webdata->dy)*(webdata->dy);
for (i = 0; i < np; i++) {
a1 = &(acoef[i][np]);
a2 = &(acoef[i+np][0]);
a3 = &(acoef[i][0]);
a4 = &(acoef[i+np][np]);
/* Fill in the portion of acoef in the four quadrants, row by row. */
for (j = 0; j < np; j++) {
*a1++ = -GG;
*a2++ = EE;
*a3++ = ZERO;
*a4++ = ZERO;
}
/* Reset the diagonal elements of acoef to -AA. */
acoef[i][i] = -AA; acoef[i+np][i+np] = -AA;
/* Set coefficients for b and diffusion terms. */
bcoef[i] = BB; bcoef[i+np] = -BB;
cox[i] = DPREY/dx2; cox[i+np] = DPRED/dx2;
coy[i] = DPREY/dy2; coy[i+np] = DPRED/dy2;
}
}
/*
* SetInitialProfiles: Set initial conditions in cc, cp, and id.
* A polynomial profile is used for the prey cc values, and a constant
* (1.0e5) is loaded as the initial guess for the predator cc values.
* The id values are set to 1 for the prey and 0 for the predators.
* The prey cp values are set according to the given system, and
* the predator cp values are set to zero.
*/
static void SetInitialProfiles(N_Vector cc, N_Vector cp, N_Vector id,
UserData webdata)
{
sunindextype loc, yloc, is, jx, jy, np;
realtype xx, yy, xyfactor;
realtype *ccv, *cpv, *idv;
ccv = NV_DATA_OMP(cc);
cpv = NV_DATA_OMP(cp);
idv = NV_DATA_OMP(id);
np = webdata->np;
/* Loop over grid, load cc values and id values. */
for (jy = 0; jy < MY; jy++) {
yy = jy * webdata->dy;
yloc = NSMX * jy;
for (jx = 0; jx < MX; jx++) {
xx = jx * webdata->dx;
xyfactor = RCONST(16.0)*xx*(ONE-xx)*yy*(ONE-yy);
xyfactor *= xyfactor;
loc = yloc + NUM_SPECIES*jx;
for (is = 0; is < NUM_SPECIES; is++) {
if (is < np) {
ccv[loc+is] = RCONST(10.0) + (realtype)(is+1) * xyfactor;
idv[loc+is] = ONE;
}
else {
ccv[loc+is] = RCONST(1.0e5);
idv[loc+is] = ZERO;
}
}
}
}
/* Set c' for the prey by calling the function Fweb. */
Fweb(ZERO, cc, cp, webdata);
/* Set c' for predators to 0. */
for (jy = 0; jy < MY; jy++) {
yloc = NSMX * jy;
for (jx = 0; jx < MX; jx++) {
loc = yloc + NUM_SPECIES * jx;
for (is = np; is < NUM_SPECIES; is++) {
cpv[loc+is] = ZERO;
}
}
}
}
/*
* Print first lines of output (problem description)
*/
static void PrintHeader(sunindextype mu, sunindextype ml, realtype rtol, realtype atol)
{
printf("\nidaFoodWeb_bnd_omp: Predator-prey DAE OpenMP example problem for IDA \n\n");
printf("Number of species ns: %d", NUM_SPECIES);
printf(" Mesh dimensions: %d x %d", MX, MY);
printf(" System size: %d\n", NEQ);
#if defined(SUNDIALS_EXTENDED_PRECISION)
printf("Tolerance parameters: rtol = %Lg atol = %Lg\n", rtol, atol);
#elif defined(SUNDIALS_DOUBLE_PRECISION)
printf("Tolerance parameters: rtol = %g atol = %g\n", rtol, atol);
#else
printf("Tolerance parameters: rtol = %g atol = %g\n", rtol, atol);
#endif
printf("Linear solver: SUNBAND, Band parameters mu = %ld, ml = %ld\n",
(long int) mu, (long int) ml);
printf("CalcIC called to correct initial predator concentrations.\n\n");
printf("-----------------------------------------------------------\n");
printf(" t bottom-left top-right");
printf(" | nst k h\n");
printf("-----------------------------------------------------------\n\n");
}
/*
* PrintOutput: Print output values at output time t = tt.
* Selected run statistics are printed. Then values of the concentrations
* are printed for the bottom left and top right grid points only.
*/
static void PrintOutput(void *ida_mem, N_Vector c, realtype t)
{
int i, kused, retval;
long int nst;
realtype *c_bl, *c_tr, hused;
retval = IDAGetLastOrder(ida_mem, &kused);
check_retval(&retval, "IDAGetLastOrder", 1);
retval = IDAGetNumSteps(ida_mem, &nst);
check_retval(&retval, "IDAGetNumSteps", 1);
retval = IDAGetLastStep(ida_mem, &hused);
check_retval(&retval, "IDAGetLastStep", 1);
c_bl = IJ_Vptr(c,0,0);
c_tr = IJ_Vptr(c,MX-1,MY-1);
#if defined(SUNDIALS_EXTENDED_PRECISION)
printf("%8.2Le %12.4Le %12.4Le | %3ld %1d %12.4Le\n",
t, c_bl[0], c_tr[0], nst, kused, hused);
for (i=1;i<NUM_SPECIES;i++)
printf(" %12.4Le %12.4Le |\n",c_bl[i],c_tr[i]);
#elif defined(SUNDIALS_DOUBLE_PRECISION)
printf("%8.2e %12.4e %12.4e | %3ld %1d %12.4e\n",
t, c_bl[0], c_tr[0], nst, kused, hused);
for (i=1;i<NUM_SPECIES;i++)
printf(" %12.4e %12.4e |\n",c_bl[i],c_tr[i]);
#else
printf("%8.2e %12.4e %12.4e | %3ld %1d %12.4e\n",
t, c_bl[0], c_tr[0], nst, kused, hused);
for (i=1;i<NUM_SPECIES;i++)
printf(" %12.4e %12.4e |\n",c_bl[i],c_tr[i]);
#endif
printf("\n");
}
/*
* PrintFinalStats: Print final run data contained in iopt.
*/
static void PrintFinalStats(void *ida_mem)
{
long int nst, nre, nreLS, nni, nje, netf, ncfn;
int retval;
retval = IDAGetNumSteps(ida_mem, &nst);
check_retval(&retval, "IDAGetNumSteps", 1);
retval = IDAGetNumNonlinSolvIters(ida_mem, &nni);
check_retval(&retval, "IDAGetNumNonlinSolvIters", 1);
retval = IDAGetNumResEvals(ida_mem, &nre);
check_retval(&retval, "IDAGetNumResEvals", 1);
retval = IDAGetNumErrTestFails(ida_mem, &netf);
check_retval(&retval, "IDAGetNumErrTestFails", 1);
retval = IDAGetNumNonlinSolvConvFails(ida_mem, &ncfn);
check_retval(&retval, "IDAGetNumNonlinSolvConvFails", 1);
retval = IDAGetNumJacEvals(ida_mem, &nje);
check_retval(&retval, "IDAGetNumJacEvals", 1);
retval = IDAGetNumLinResEvals(ida_mem, &nreLS);
check_retval(&retval, "IDAGetNumLinResEvals", 1);
printf("-----------------------------------------------------------\n");
printf("Final run statistics: \n\n");
printf("Number of steps = %ld\n", nst);
printf("Number of residual evaluations = %ld\n", nre+nreLS);
printf("Number of Jacobian evaluations = %ld\n", nje);
printf("Number of nonlinear iterations = %ld\n", nni);
printf("Number of error test failures = %ld\n", netf);
printf("Number of nonlinear conv. failures = %ld\n", ncfn);
}
/*
* Fweb: Rate function for the food-web problem.
* This routine computes the right-hand sides of the system equations,
* consisting of the diffusion term and interaction term.
* The interaction term is computed by the function WebRates.
*/
static void Fweb(realtype tcalc, N_Vector cc, N_Vector crate,
UserData webdata)
{
sunindextype jx, jy, is, idyu, idyl, idxu, idxl;
realtype xx, yy, *cxy, *ratesxy, *cratexy, dcyli, dcyui, dcxli, dcxui;
/* Loop over grid points, evaluate interaction vector (length ns),
form diffusion difference terms, and load crate. */
jx = jy = is = 0;
for (jy = 0; jy < MY; jy++) {
yy = (webdata->dy) * jy ;
idyu = (jy!=MY-1) ? NSMX : -NSMX;
idyl = (jy!= 0 ) ? NSMX : -NSMX;
for (jx = 0; jx < MX; jx++) {
xx = (webdata->dx) * jx;
idxu = (jx!= MX-1) ? NUM_SPECIES : -NUM_SPECIES;
idxl = (jx!= 0 ) ? NUM_SPECIES : -NUM_SPECIES;
cxy = IJ_Vptr(cc,jx,jy);
ratesxy = IJ_Vptr(webdata->rates,jx,jy);
cratexy = IJ_Vptr(crate,jx,jy);
/* Get interaction vector at this grid point. */
WebRates(xx, yy, cxy, ratesxy, webdata);
/* Loop over species, do differencing, load crate segment. */
#pragma omp parallel for default(shared) private(is, dcyli, dcyui, dcxli, dcxui) schedule(static) num_threads(webdata->nthreads)
for (is = 0; is < NUM_SPECIES; is++) {
/* Differencing in y. */
dcyli = *(cxy+is) - *(cxy - idyl + is) ;
dcyui = *(cxy + idyu + is) - *(cxy+is);
/* Differencing in x. */
dcxli = *(cxy+is) - *(cxy - idxl + is);
dcxui = *(cxy + idxu +is) - *(cxy+is);
/* Compute the crate values at (xx,yy). */
cratexy[is] = coy[is] * (dcyui - dcyli) +
cox[is] * (dcxui - dcxli) + ratesxy[is];
} /* End is loop */
} /* End of jx loop */
} /* End of jy loop */
}
/*
* WebRates: Evaluate reaction rates at a given spatial point.
* At a given (x,y), evaluate the array of ns reaction terms R.
*/
static void WebRates(realtype xx, realtype yy, realtype *cxy, realtype *ratesxy,
UserData webdata)
{
int is;
realtype fac;
for (is = 0; is < NUM_SPECIES; is++)
ratesxy[is] = dotprod(NUM_SPECIES, cxy, acoef[is]);
fac = ONE + ALPHA*xx*yy + BETA*sin(FOURPI*xx)*sin(FOURPI*yy);
for (is = 0; is < NUM_SPECIES; is++)
ratesxy[is] = cxy[is]*( bcoef[is]*fac + ratesxy[is] );
}
/*
* dotprod: dot product routine for realtype arrays, for use by WebRates.
*/
static realtype dotprod(sunindextype size, realtype *x1, realtype *x2)
{
sunindextype i;
realtype *xx1, *xx2, temp = ZERO;
xx1 = x1; xx2 = x2;
for (i = 0; i < size; i++) temp += (*xx1++) * (*xx2++);
return(temp);
}
/*
* Check function return value...
* opt == 0 means SUNDIALS function allocates memory so check if
* returned NULL pointer
* opt == 1 means SUNDIALS function returns an integer value so check if
* retval < 0
* opt == 2 means function allocates memory so check if returned
* NULL pointer
*/
static int check_retval(void *returnvalue, char *funcname, int opt)
{
int *retval;
if (opt == 0 && returnvalue == NULL) {
/* Check if SUNDIALS function returned NULL pointer - no memory allocated */
fprintf(stderr,
"\nSUNDIALS_ERROR: %s() failed - returned NULL pointer\n\n",
funcname);
return(1);
} else if (opt == 1) {
/* Check if retval < 0 */
retval = (int *) returnvalue;
if (*retval < 0) {
fprintf(stderr,
"\nSUNDIALS_ERROR: %s() failed with retval = %d\n\n",
funcname, *retval);
return(1);
}
} else if (opt == 2 && returnvalue == NULL) {
/* Check if function returned NULL pointer - no memory allocated */
fprintf(stderr,
"\nMEMORY_ERROR: %s() failed - returned NULL pointer\n\n",
funcname);
return(1);
}
return(0);
}
|
visualize_helper.c
|
#include <ruby.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <math.h>
#include <omp.h>
void RemoveSpaces(char* source)
{
char* i = source;
char* j = source;
while(*j != 0)
{
*i = *j++;
if(*i != ' ')
i++;
}
*i = 0;
}
int myCompare (const void * a, const void * b ) {
const char *pa = *(const char**)a;
const char *pb = *(const char**)b;
return strcmp(pa,pb);
}
// recive a sorted array of strings and return a sorted array with only the unique elements
static VALUE uniq(VALUE sorted_array){
//initialize return variable in ruby
VALUE uniq_array = rb_ary_new();
//initialize variables for compare
char* previous;
char* current;
int i;
for( i = 0; i < RARRAY_LEN(sorted_array); i++){
VALUE current_temp = rb_ary_entry(sorted_array,i);
current = StringValuePtr(current_temp);
// initial case, when there is no previous
if ( i == 0 ){
VALUE previous_temp = rb_ary_entry(sorted_array,i);
previous = StringValuePtr(previous_temp);
rb_ary_push(uniq_array,rb_ary_entry(sorted_array,i));
} else {
if (strcmp(previous,current) != 0 ){
rb_ary_push(uniq_array,rb_ary_entry(sorted_array,i));
VALUE previous_temp = rb_ary_entry(sorted_array,i);
previous = StringValuePtr(previous_temp);
}
}
}
return uniq_array;
}
//static VALUE join(VALUE self, VALUE strings){
static char* join(VALUE strings){
// initial variables
char* joined;
int strings_size = RARRAY_LEN(strings);
int string_size;
int string_total_size = 0;
VALUE string_temp;
VALUE result;
int i;
// calculate the exact size of malloc
for ( i = 0; i < strings_size; i++) {
string_temp = rb_ary_entry(strings,i);
string_total_size += strlen(StringValuePtr(string_temp));
}
joined = (char*) malloc(string_total_size +strings_size + 1);
string_temp = rb_ary_entry(strings,0);
//string_size = strlen(StringValuePtr(string_temp));
sprintf(joined,"%s", StringValuePtr(string_temp));
for (i = 1 ; i < strings_size; i++) {
string_temp = rb_ary_entry(strings,i);
sprintf(joined,"%s,%s", joined, StringValuePtr(string_temp));
}
strcat(joined,"\0");
return joined;
}
// Receive an array of unsorted strings with repeated strings and return a single a sorted array with unique elementes or with all
// strings = array of strings
// unique = 0 or 1 if want to call unique or not
static VALUE sort_uniq(VALUE strings, int unique)
{
int strings_size = RARRAY_LEN(strings);
const char *input[strings_size];
int i;
for (i = 0; i< strings_size; i++){
VALUE string = rb_ary_entry(strings,i);
input[i] = StringValuePtr(string);
}
int stringLen = sizeof(input) / sizeof(char *);
qsort(input, stringLen, sizeof(char *), myCompare);
// Transform the result input into a ruby array
VALUE resultado = rb_ary_new();
for (i=0; i<stringLen; ++i) {
rb_ary_push(resultado,rb_str_new2(input[i]));
}
return (unique == 0 ) ? resultado : uniq(resultado);
}
// Find the index of the target value inside array
int findIndex(VALUE intervals, size_t size, int target)
{
int i=0;
while((i<size) && (FIX2INT(rb_ary_entry(intervals,i)) != target)) i++;
return (i<size) ? (i) : (-1);
}
// Function callback to iterate in hash
// Params:
// days: hash key (VALUE)
// traj: hash value (VALUE)
// array: [min (int) ,max (int) ,period (Qnil/int), intervals (C array), intervals_size(int), aggr (VALUE)]
static int encontra_min_max_period(VALUE days, VALUE traj, VALUE array){
// Convert every variable need to C value
VALUE intervals = rb_ary_entry(array,3);
VALUE aggr = rb_ary_entry(array,4);
int intervals_size = RARRAY_LEN(intervals);
int aggr_size = RARRAY_LEN(aggr);
VALUE first_interval = rb_ary_entry(intervals,0);
VALUE last_interval = rb_ary_entry(intervals,intervals_size - 1);
int first_interval_c = FIX2INT(first_interval);
int last_interval_c = FIX2INT(last_interval);
int days_c = atoi(StringValuePtr(days));
int min_c = FIX2INT(rb_ary_entry(array,0));
int max_c = FIX2INT(rb_ary_entry(array,1));
int period, traj_size, index, i;
if (days_c < first_interval_c) {
if (min_c > days_c) {
min_c = days_c;
}
period = 0;
}else if (days_c == 0) {
period = findIndex(intervals,intervals_size,0)+1;
}else if (days_c > last_interval_c ) {
if (max_c < days_c) {
max_c = days_c;
}
period = aggr_size -1;
}else {
for ( index = 0 ; index < intervals_size ; index++){
if( index < (intervals_size - 1) ){
int intervals_index_plus_1 = FIX2INT(rb_ary_entry(intervals,index+1));
if ( intervals_index_plus_1 <= 0 ){
if (( days_c >= FIX2INT(rb_ary_entry(intervals,index))) && (days_c < intervals_index_plus_1)) {
period = index +1;
break;
}
}else if ( (days_c > FIX2INT(rb_ary_entry(intervals,index)) ) && (days_c <= intervals_index_plus_1) ) {
period = index + 2;
break;
}
}
}
}
rb_ary_store(array,0,INT2FIX(min_c));
rb_ary_store(array,1,INT2FIX(max_c));
traj_size = RARRAY_LEN(traj);
for ( i =0; i < traj_size; i++){
rb_ary_push(rb_ary_entry(aggr,period),rb_ary_entry(traj,i));
}
return ST_CONTINUE;
}
// Function to find min, max and the period of the HashMapValue of trajectories in Visualize app
// Return: [ min, max, period]
static VALUE min_max_period(VALUE self, VALUE min, VALUE max, VALUE hash, VALUE intervals, VALUE aggr)
{
int period = Qnil;
// Create Ruby array that will be the result
VALUE array = rb_ary_new();
// Push initial values of the result
rb_ary_push(array,min);
rb_ary_push(array,max);
rb_ary_push(array,period);
rb_ary_push(array,intervals);
rb_ary_push(array,aggr);
// iterate on hash calling "encontra_min_max_period" for each
rb_hash_foreach(hash,encontra_min_max_period,array);
// Return results
return array;
}
//function to remove element from a array of strings
static VALUE remove_entry_from_array (VALUE strings, char* element){
//initial variables
VALUE result = rb_ary_new();
char* current_value;
VALUE current_value_temp;
int i;
for( i = 0; i < RARRAY_LEN(strings); i++){
current_value_temp = rb_ary_entry(strings,i);
current_value = StringValuePtr(current_value_temp);
if (strcmp(current_value, element) != 0) {
rb_ary_push(result,rb_ary_entry(strings,i));
}
}
return result;
}
// Function to generate the boxes and links of each trajectory
static VALUE generate_boxes_and_links(VALUE self, VALUE aggr, VALUE boxes, VALUE links, VALUE dict, VALUE type_agroupment, VALUE value)
{
char* seq_key_result;
char* prox_key_result;
// Initial Variables
int length_seq_sorted;
int length_prox_sorted;
VALUE result_final;
VALUE boxes_period_value;
VALUE links_period_value;
VALUE seq_key;
VALUE prox_key;
VALUE seq;
VALUE aggr_prox;
int seq_size;
int aggr_prox_size;
int prox;
int aggr_size = RARRAY_LEN(aggr);
char* link_key = (char*) malloc(1000);
char* period_s;
char* prox_s;
int period,i;
for(period = 0; period < aggr_size; period++ ){
seq_key = rb_ary_new();
if (period < aggr_size - 1) {
prox_key = rb_ary_new();
}
seq = rb_ary_entry(aggr,period);
seq_size = (int) RARRAY_LEN(seq);
// Translate sequences with dict
if (seq_size == 0) {
rb_ary_push(seq_key,rb_hash_aref(dict, rb_str_new2("M-2")));
}else{
for(i = 0; i < seq_size; i++ ) {
rb_ary_push(seq_key,rb_hash_aref(dict,rb_ary_entry(seq,i)));
}
}
// agroup by unique or not
if ( strcmp(StringValuePtr(type_agroupment),"n") == 0 ) {
//sort with uniq
seq_key = sort_uniq(seq_key,1);
}else{
//sort without uniq
seq_key = sort_uniq(seq_key,0);
}
// if there is "no-event" and other one selected, remove the "no-event"
length_seq_sorted = (strcmp(StringValuePtr(type_agroupment),"s") == 0 ) ? RARRAY_LEN(seq_key) : RARRAY_LEN(uniq(seq_key)) ;
if (length_seq_sorted != 1) {
seq_key = remove_entry_from_array(seq_key,"M-3");
}
// Generate the key
seq_key_result = join(seq_key);
//
boxes_period_value = rb_hash_aref(rb_ary_entry(boxes,period),rb_str_new2(seq_key_result));
if (boxes_period_value == Qnil) {
rb_hash_aset(rb_ary_entry(boxes,period),rb_str_new2(seq_key_result), value);
}else {
rb_hash_aset(rb_ary_entry(boxes,period),rb_str_new2(seq_key_result),INT2FIX(FIX2INT(boxes_period_value) + FIX2INT(value)));
}
prox = period +1;
if (prox < aggr_size ) {
aggr_prox = rb_ary_entry(aggr,prox);
aggr_prox_size = (int) RARRAY_LEN(aggr_prox);
if ( aggr_prox_size == 0) {
rb_ary_push(prox_key,rb_hash_aref(dict, rb_str_new2("M-2")));
}else{
for( i = 0; i < aggr_prox_size ; i++ ) {
rb_ary_push(prox_key,rb_hash_aref(dict,rb_ary_entry(aggr_prox,i)));
}
}
// agroup by unique or not
if ( strcmp(StringValuePtr(type_agroupment),"n") == 0 ) {
//sort with uniq
prox_key = sort_uniq(prox_key,1);
}
//else{
// //sort without uniq
// prox_key = prox_key;
//}
//
// if there is "no-event" and other one selected, remove the "no-event"
length_prox_sorted = (strcmp(StringValuePtr(type_agroupment),"n") == 0 ) ? RARRAY_LEN(prox_key) : RARRAY_LEN(sort_uniq(prox_key,1)) ;
if (length_prox_sorted != 1) {
prox_key = remove_entry_from_array(prox_key,"M-3");
}
// Generate the key
prox_key_result = join(prox_key);
// generate a key link
period_s = ( period == 0 ) ? (char*) malloc(1) : (char*) malloc(floor(log10(abs(period))) + 1);
prox_s = ( prox == 0 ) ? (char*) malloc(1) : (char*) malloc(floor(log10(abs(prox))) + 1);
sprintf(period_s,"%d",period);
sprintf(prox_s,"%d",prox);
//link_key = (char*) malloc( strlen(period_s) + strlen(seq_key_result) + strlen(prox_s) + strlen(prox_key_result) + 3);
sprintf(link_key,"%s_%s;%s_%s", period_s,seq_key_result,prox_s,prox_key_result);
RemoveSpaces(link_key);
links_period_value = rb_hash_aref(rb_ary_entry(links,period),rb_str_new2(link_key));
if (links_period_value == Qnil) {
rb_hash_aset(rb_ary_entry(links,period),rb_str_new2(link_key),value);
}else {
rb_hash_aset(rb_ary_entry(links,period),rb_str_new2(link_key), INT2FIX(FIX2INT(links_period_value) + FIX2INT(value)));
}
}//end prox < aggr_size
}// end for
free(period_s);
free(prox_s);
free(link_key);
return Qnil;
}
static VALUE join_teste(VALUE self, VALUE strings){
return rb_str_new2(join(strings));
}
// iterate over all the tracjetories and create the boxes and links needed for the dashboard
static VALUE iterate_over_trajectories(VALUE self, VALUE trajectories, VALUE min, VALUE max, VALUE hash_v, VALUE hash_t, VALUE intervals, VALUE dict, VALUE agrupamento, VALUE boxes, VALUE links) {
VALUE trajectory;
VALUE aggr;
VALUE value;
VALUE min_max_aggr;
int i,j;
// iterate over each trajectory
for (i = 0; i < RARRAY_LEN(trajectories); i++ ){
trajectory = rb_ary_entry(trajectories,i);
aggr = rb_ary_new();
for (j = 0; j < RARRAY_LEN(intervals) + 2; j++){
rb_ary_push(aggr,rb_ary_new());
}
value = rb_hash_aref(hash_v,trajectory);
min_max_aggr = min_max_period(self,min,max,rb_hash_aref(hash_t,trajectory),intervals,aggr);
aggr = rb_ary_entry(min_max_aggr,4);
min = rb_ary_entry(min_max_aggr,0);
max = rb_ary_entry(min_max_aggr,1);
generate_boxes_and_links(self,aggr,boxes,links,dict,agrupamento,value);
}
return Qnil;
}
static VALUE openmp_test(VALUE self, VALUE string) {
FILE *f = fopen("/tmp/open_mp", "w");
int nthreads, tid;
/* Fork a team of threads giving them their own copies of variables */
#pragma omp parallel private(nthreads, tid)
{
/* Obtain thread number */
tid = omp_get_thread_num();
fprintf(f,"Hello World from thread = %d\n", tid);
/* Only master thread does this */
if (tid == 0)
{
nthreads = omp_get_num_threads();
fprintf(f,"Number of threads = %d\n", nthreads);
}
} /* All threads join master thread and disband */
fclose(f);
return string;
}
// Function callback to iterate in hash of boxes or links
static int update_boxes_links(VALUE key, VALUE value, VALUE parameters){
VALUE boxes_links_result = rb_ary_entry(parameters,0);
int index = FIX2INT(rb_ary_entry(parameters,1));
VALUE boxes_links_result_index = rb_ary_entry(boxes_links_result,index);
// if the key isnt already set on the boxes_result, create it
if (rb_hash_aref(boxes_links_result_index,key) == Qnil) {
rb_hash_aset(boxes_links_result_index,key,value);
}else{
// if the key is already on the boxes_result, sum the results
rb_hash_aset(boxes_links_result_index,key, FIX2INT(rb_hash_aref(boxes_links_result_index,key)) + FIX2INT(value));
}
return ST_CONTINUE;
}
// iterate over all the trajectories and create the boxes and links needed for the dashboard (Parallel)
//static VALUE iterate_over_trajectories_parallel(VALUE self, VALUE trajectories, VALUE min, VALUE max, VALUE hash_v, VALUE hash_t, VALUE intervals, VALUE dict, VALUE agrupamento, VALUE boxes, VALUE links) {
static VALUE iterate_over_trajectories_parallel() {
//VALUE trajectory;
VALUE aggr;
//VALUE value;
//VALUE min_max_aggr;
//VALUE boxes_result = rb_ary_new();
//VALUE links_result = rb_ary_new();
int i,j;
//initialize boxes_result and links_result
//for (j = 0; j < RARRAY_LEN(intervals) + 2; j++){
// rb_ary_push(boxes_result,rb_hash_new());
// if ( j != 0) {
// rb_ary_push(links_result,rb_hash_new());
// }
//}
//#pragma omp parallel firstprivate(boxes,links,i,j)
//#pragma omp parallel private(i,j,aggr,boxes,links)
//{
// //#pragma omp for nowait
// #pragma omp for firstprivate(min,max) nowait
// for (i = 0; i < RARRAY_LEN(trajectories); i++ ){
//
//
// trajectory = rb_ary_entry(trajectories,i);
#pragma omp parallel for private(i,aggr)
for (i = 0; i < 500; i++ ){
aggr = rb_ary_new();
//for (j = 0; j < RARRAY_LEN(intervals) + 2; j++){
// rb_ary_push(aggr,rb_ary_new());
//}
//value = rb_hash_aref(hash_v,trajectory);
//min_max_aggr = min_max_period(self,min,max,rb_hash_aref(hash_t,trajectory),intervals,aggr);
//aggr = rb_ary_entry(min_max_aggr,4);
//min = rb_ary_entry(min_max_aggr,0);
//max = rb_ary_entry(min_max_aggr,1);
//generate_boxes_and_links(self,aggr,boxes,links,dict,agrupamento,value);
// }// end pragma for
}
// // must aggregate the boxes from each thread into boxes_result
// #pragma omp critical
// {
// int i;
// VALUE parameters = rb_ary_new2(2);
// // iterate over the size of boxes
// for(i = 0; i < RARRAY_LEN(boxes); i++ ){
//
// rb_ary_store(parameters,0,boxes_result);
// rb_ary_store(parameters,1,INT2FIX(i));
// VALUE hash = rb_ary_entry(boxes,i);
// //iterate over each key of the hashmap
// rb_hash_foreach(hash,update_boxes_links,parameters);
// }
// }
// // must aggregate the links from each thread into links_result
// #pragma omp critical
// {
// int i;
// VALUE parameters = rb_ary_new2(2);
// for(i = 0; i < RARRAY_LEN(links); i++ ){
//
// rb_ary_store(parameters,0,links_result);
// rb_ary_store(parameters,1,INT2FIX(i));
// VALUE hash = rb_ary_entry(links,i);
// //iterate over each key of the hashmap
// rb_hash_foreach(hash,update_boxes_links,parameters);
// }
// }
//}// and pragma parallel
return Qnil;
}
// Main function called when the gem is loaded
void Init_visualize_helper(void) {
// Register the VisualizeHelper module
VALUE mVisualizeHelper = rb_define_module("VisualizeHelper");
// Register the method min_max_period
rb_define_singleton_method(mVisualizeHelper, "min_max_period", min_max_period, 5);
// Register the method generate_boxes_and_links
rb_define_singleton_method(mVisualizeHelper, "generate_boxes_and_links", generate_boxes_and_links, 6);
// Register the method sort
rb_define_singleton_method(mVisualizeHelper, "sort_uniq", sort_uniq, 2 );
// Register the method that iterates on each trajectory
rb_define_singleton_method(mVisualizeHelper, "iterate_over_trajectories", iterate_over_trajectories, 10);
// Register the method sort
rb_define_singleton_method(mVisualizeHelper, "join_teste", join_teste, 1 );
// Register a test with openmp
rb_define_singleton_method(mVisualizeHelper, "openmp_test", openmp_test, 1 );
// Register the method that iterates on each trajectory using openmp
rb_define_singleton_method(mVisualizeHelper, "iterate_over_trajectories_parallel", iterate_over_trajectories_parallel, 0);
}
|
1999.c
|
/* POLYBENCH/GPU-OPENMP
*
* This file is a part of the Polybench/GPU-OpenMP suite
*
* Contact:
* William Killian <[email protected]>
*
* Copyright 2013, The University of Delaware
*/
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <math.h>
/* Include polybench common header. */
#include <polybench.h>
/* Include benchmark-specific header. */
/* Default data type is double, default size is 4000. */
#include "3mm.h"
/* Array initialization. */
static
void init_array(int ni, int nj, int nk, int nl, int nm,
DATA_TYPE POLYBENCH_2D(A,NI,NK,ni,nk),
DATA_TYPE POLYBENCH_2D(B,NK,NJ,nk,nj),
DATA_TYPE POLYBENCH_2D(C,NJ,NM,nj,nm),
DATA_TYPE POLYBENCH_2D(D,NM,NL,nm,nl))
{
int i, j;
for (i = 0; i < ni; i++)
for (j = 0; j < nk; j++)
A[i][j] = ((DATA_TYPE) i*j) / ni;
for (i = 0; i < nk; i++)
for (j = 0; j < nj; j++)
B[i][j] = ((DATA_TYPE) i*(j+1)) / nj;
for (i = 0; i < nj; i++)
for (j = 0; j < nm; j++)
C[i][j] = ((DATA_TYPE) i*(j+3)) / nl;
for (i = 0; i < nm; i++)
for (j = 0; j < nl; j++)
D[i][j] = ((DATA_TYPE) i*(j+2)) / nk;
}
/* DCE code. Must scan the entire live-out data.
Can be used also to check the correctness of the output. */
static
void print_array(int ni, int nl,
DATA_TYPE POLYBENCH_2D(G,NI,NL,ni,nl))
{
int i, j;
for (i = 0; i < ni; i++)
for (j = 0; j < nl; j++) {
fprintf (stderr, DATA_PRINTF_MODIFIER, G[i][j]);
if ((i * ni + j) % 20 == 0) fprintf (stderr, "\n");
}
fprintf (stderr, "\n");
}
/* Main computational kernel. The whole function will be timed,
including the call and return. */
static
void kernel_3mm(int ni, int nj, int nk, int nl, int nm,
DATA_TYPE POLYBENCH_2D(E,NI,NJ,ni,nj),
DATA_TYPE POLYBENCH_2D(A,NI,NK,ni,nk),
DATA_TYPE POLYBENCH_2D(B,NK,NJ,nk,nj),
DATA_TYPE POLYBENCH_2D(F,NJ,NL,nj,nl),
DATA_TYPE POLYBENCH_2D(C,NJ,NM,nj,nm),
DATA_TYPE POLYBENCH_2D(D,NM,NL,nm,nl),
DATA_TYPE POLYBENCH_2D(G,NI,NL,ni,nl))
{
int i, j, k;
#pragma scop
#pragma omp parallel private (j, k) num_threads(2)
{
/* E := A*B */
#pragma omp for schedule(static, 16)
for (i = 0; i < _PB_NI; i++)
for (j = 0; j < _PB_NJ; j++)
{
E[i][j] = 0;
for (k = 0; k < _PB_NK; ++k)
E[i][j] += A[i][k] * B[k][j];
}
/* F := C*D */
#pragma omp for schedule(static, 16)
for (i = 0; i < _PB_NJ; i++)
for (j = 0; j < _PB_NL; j++)
{
F[i][j] = 0;
for (k = 0; k < _PB_NM; ++k)
F[i][j] += C[i][k] * D[k][j];
}
/* G := E*F */
#pragma omp for schedule(static, 16)
for (i = 0; i < _PB_NI; i++)
for (j = 0; j < _PB_NL; j++)
{
G[i][j] = 0;
for (k = 0; k < _PB_NJ; ++k)
G[i][j] += E[i][k] * F[k][j];
}
}
#pragma endscop
}
int main(int argc, char** argv)
{
/* Retrieve problem size. */
int ni = NI;
int nj = NJ;
int nk = NK;
int nl = NL;
int nm = NM;
/* Variable declaration/allocation. */
POLYBENCH_2D_ARRAY_DECL(E, DATA_TYPE, NI, NJ, ni, nj);
POLYBENCH_2D_ARRAY_DECL(A, DATA_TYPE, NI, NK, ni, nk);
POLYBENCH_2D_ARRAY_DECL(B, DATA_TYPE, NK, NJ, nk, nj);
POLYBENCH_2D_ARRAY_DECL(F, DATA_TYPE, NJ, NL, nj, nl);
POLYBENCH_2D_ARRAY_DECL(C, DATA_TYPE, NJ, NM, nj, nm);
POLYBENCH_2D_ARRAY_DECL(D, DATA_TYPE, NM, NL, nm, nl);
POLYBENCH_2D_ARRAY_DECL(G, DATA_TYPE, NI, NL, ni, nl);
/* Initialize array(s). */
init_array (ni, nj, nk, nl, nm,
POLYBENCH_ARRAY(A),
POLYBENCH_ARRAY(B),
POLYBENCH_ARRAY(C),
POLYBENCH_ARRAY(D));
/* Start timer. */
polybench_start_instruments;
/* Run kernel. */
kernel_3mm (ni, nj, nk, nl, nm,
POLYBENCH_ARRAY(E),
POLYBENCH_ARRAY(A),
POLYBENCH_ARRAY(B),
POLYBENCH_ARRAY(F),
POLYBENCH_ARRAY(C),
POLYBENCH_ARRAY(D),
POLYBENCH_ARRAY(G));
/* Stop and print timer. */
polybench_stop_instruments;
polybench_print_instruments;
/* Prevent dead-code elimination. All live-out data must be printed
by the function call in argument. */
polybench_prevent_dce(print_array(ni, nl, POLYBENCH_ARRAY(G)));
/* Be clean. */
POLYBENCH_FREE_ARRAY(E);
POLYBENCH_FREE_ARRAY(A);
POLYBENCH_FREE_ARRAY(B);
POLYBENCH_FREE_ARRAY(F);
POLYBENCH_FREE_ARRAY(C);
POLYBENCH_FREE_ARRAY(D);
POLYBENCH_FREE_ARRAY(G);
return 0;
}
|
FLASH_Queue_exec.c
|
/*
Copyright (C) 2014, The University of Texas at Austin
This file is part of libflame and is available under the 3-Clause
BSD license, which can be found in the LICENSE file at the top-level
directory, or at http://opensource.org/licenses/BSD-3-Clause
*/
#include "FLAME.h"
#if FLA_MULTITHREADING_MODEL == FLA_OPENMP
#ifdef FLA_ENABLE_TIDSP
#include <ti/omp/omp.h>
#else
#include <omp.h>
#endif
#elif FLA_MULTITHREADING_MODEL == FLA_PTHREADS
#include <pthread.h>
#endif
#ifdef FLA_ENABLE_WINDOWS_BUILD
#define _CRT_RAND_S
#include <stdlib.h>
#endif
#ifdef FLA_ENABLE_SUPERMATRIX
#ifndef FLA_ENABLE_SCC
#define MIN_CACHE_BLOCKS 3
#ifdef FLA_ENABLE_GPU
typedef struct FLA_Obj_gpu_struct
{
// Block stored in a GPU.
FLA_Obj obj;
// Pointer to the data stored on the GPU.
void* buffer_gpu;
// Whether the block is clean or dirty on the GPU.
FLA_Bool clean;
// Whether the block has been requested by another GPU.
FLA_Bool request;
} FLA_Obj_gpu;
#endif
typedef struct FLASH_Queue_variables
{
// A lock on the global task counter.
// Needed only when multithreading is enabled.
FLA_Lock all_lock;
// A lock that protects the thread's waiting queue.
// Needed only when multithreading is enabled.
FLA_Lock* run_lock;
// A lock that allows threads to safely check for and place ready dependent
// tasks on waiting queue. Needed only when multithreading is enabled.
FLA_Lock* dep_lock;
// A lock that allows threads to safely free the anti-dependency queue
// within each block. Needed only when multithreading is enabled.
FLA_Lock* war_lock;
// A lock that allows threads to safely access the cache structures.
// Needed only when multithreading is enabled.
FLA_Lock* cac_lock;
// Number of queues.
integer n_queues;
// Number of caches.
integer n_caches;
// The number of blocks that can be stored in the cache on each thread.
integer size;
// LRU cache simulation of blocks.
FLA_Obj* cache;
// List of blocks accessed by the first tasks.
FLA_Obj* prefetch;
// The waiting queue of tasks for each thread.
FLASH_Queue* wait_queue;
// A global task counter that keeps track of how many tasks on the waiting
// queue have been processed.
integer pc;
#ifdef FLA_ENABLE_GPU
// A lock that allows threads to safely access the cache structures.
// Needed only when multithreading is enabled.
FLA_Lock* gpu_lock;
// LRU software cache of GPU memory.
FLA_Obj_gpu* gpu;
// Storing the block being evicted.
FLA_Obj_gpu* victim;
// Temporary storage for logging blocks on GPU.
FLA_Obj_gpu* gpu_log;
// The size of each block to allocate on GPU.
dim_t block_size;
// The datatype of each block to allocate on GPU.
FLA_Datatype datatype;
#endif
} FLASH_Queue_vars;
void FLASH_Queue_exec( void )
/*----------------------------------------------------------------------------
FLASH_Queue_exec
----------------------------------------------------------------------------*/
{
integer n_tasks = FLASH_Queue_get_num_tasks();
integer n_threads = FLASH_Queue_get_num_threads();
integer n_queues;
integer n_caches;
integer size;
integer i;
dim_t block_size = FLASH_Queue_get_block_size();
double dtime;
FLA_Lock* run_lock;
FLA_Lock* dep_lock;
FLA_Lock* war_lock;
FLA_Lock* cac_lock;
FLA_Obj* cache;
FLA_Obj* prefetch;
FLASH_Queue* wait_queue;
#ifdef FLA_ENABLE_GPU
#ifdef FLA_ENABLE_MULTITHREADING
FLA_Lock* gpu_lock;
#endif
FLA_Obj_gpu* gpu;
FLA_Obj_gpu* victim;
FLA_Obj_gpu* gpu_log;
dim_t gpu_n_blocks = FLASH_Queue_get_gpu_num_blocks();
#endif
// All the necessary variables for the SuperMatrix mechanism.
FLASH_Queue_vars args;
// If the queue is empty, return early.
if ( n_tasks == 0 )
return;
#ifndef FLA_ENABLE_MULTITHREADING
// Turn off work stealing in simulation mode.
FLASH_Queue_set_work_stealing( FALSE );
#endif
// Query the number of user set threads per queue.
n_queues = FLASH_Queue_get_cores_per_queue();
// Default user setting for number of threads.
if ( n_queues <= 0 )
{
// Do not use data affinity or work stealing when caching is enabled.
if ( FLASH_Queue_get_caching() )
{
FLASH_Queue_set_data_affinity( FLASH_QUEUE_AFFINITY_NONE );
FLASH_Queue_set_work_stealing( FALSE );
}
// Do not use work stealing when data affinity is enabled.
if ( FLASH_Queue_get_data_affinity() != FLASH_QUEUE_AFFINITY_NONE )
{
FLASH_Queue_set_work_stealing( FALSE );
}
// Allocate different arrays if using data affinity.
n_queues = ( FLASH_Queue_get_data_affinity() ==
FLASH_QUEUE_AFFINITY_NONE &&
!FLASH_Queue_get_work_stealing() ? 1 : n_threads );
}
else
{
// Set the number of queues.
n_queues = n_threads / n_queues;
// Must use at least one queue.
if ( n_queues == 0 )
n_queues = 1;
if ( n_queues == 1 )
{
// Turn off all multiple queue implementations.
FLASH_Queue_set_data_affinity( FLASH_QUEUE_AFFINITY_NONE );
FLASH_Queue_set_work_stealing( FALSE );
}
else
{
// Use 2D data affinity for multiple queues if nothing is set.
if ( FLASH_Queue_get_data_affinity() == FLASH_QUEUE_AFFINITY_NONE &&
!FLASH_Queue_get_work_stealing() )
{
FLASH_Queue_set_data_affinity( FLASH_QUEUE_AFFINITY_2D_BLOCK_CYCLIC );
}
}
}
// Determine the number of caches.
n_caches = n_threads / FLASH_Queue_get_cores_per_cache();
args.n_queues = n_queues;
args.n_caches = n_caches;
#ifdef FLA_ENABLE_MULTITHREADING
// Allocate memory for array of locks.
run_lock = ( FLA_Lock* ) FLA_malloc( n_queues * sizeof( FLA_Lock ) );
dep_lock = ( FLA_Lock* ) FLA_malloc( n_threads * sizeof( FLA_Lock ) );
war_lock = ( FLA_Lock* ) FLA_malloc( n_threads * sizeof( FLA_Lock ) );
cac_lock = ( FLA_Lock* ) FLA_malloc( n_caches * sizeof( FLA_Lock ) );
args.run_lock = run_lock;
args.dep_lock = dep_lock;
args.war_lock = war_lock;
args.cac_lock = cac_lock;
// Initialize the all lock.
FLA_Lock_init( &(args.all_lock) );
// Initialize the run lock for thread i.
for ( i = 0; i < n_queues; i++ )
{
FLA_Lock_init( &(args.run_lock[i]) );
}
// Initialize the dep and war locks for thread i.
for ( i = 0; i < n_threads; i++ )
{
FLA_Lock_init( &(args.dep_lock[i]) );
FLA_Lock_init( &(args.war_lock[i]) );
}
// Initialize the cac locks for each cache.
for ( i = 0; i < n_caches; i++ )
{
FLA_Lock_init( &(args.cac_lock[i]) );
}
#endif
// The number of blocks that can fit into the cache on each thread.
if ( block_size == 0 )
size = MIN_CACHE_BLOCKS;
else
size = max( FLASH_Queue_get_cache_size() / block_size, MIN_CACHE_BLOCKS);
args.size = size;
// Allocate memory for cache, prefetch buffer, and waiting queue.
cache = ( FLA_Obj* ) FLA_malloc( size * n_caches * sizeof( FLA_Obj ) );
prefetch = ( FLA_Obj* ) FLA_malloc( size * sizeof( FLA_Obj ) );
wait_queue = ( FLASH_Queue* ) FLA_malloc( n_queues * sizeof( FLASH_Queue ));
args.cache = cache;
args.prefetch = prefetch;
args.wait_queue = wait_queue;
// Initialize cache, prefetch buffer, and waiting queue.
for ( i = 0; i < size * n_caches; i++ )
args.cache[i].base = NULL;
for ( i = 0; i < size; i++ )
args.prefetch[i].base = NULL;
for ( i = 0; i < n_queues; i++ )
{
args.wait_queue[i].n_tasks = 0;
args.wait_queue[i].head = NULL;
args.wait_queue[i].tail = NULL;
}
// Initialize the aggregate task counter.
args.pc = 0;
#ifdef FLA_ENABLE_GPU
#ifdef FLA_ENABLE_MULTITHREADING
// Allocate and initialize the gpu locks.
gpu_lock = ( FLA_Lock* ) FLA_malloc( n_threads * sizeof( FLA_Lock ) );
args.gpu_lock = gpu_lock;
for ( i = 0; i < n_threads; i++ )
FLA_Lock_init( &(args.gpu_lock[i]) );
#endif
// Allocate and initialize GPU software cache.
gpu = ( FLA_Obj_gpu* ) FLA_malloc( gpu_n_blocks * n_threads * sizeof( FLA_Obj_gpu ) );
args.gpu = gpu;
for ( i = 0; i < gpu_n_blocks * n_threads; i++ )
{
args.gpu[i].obj.base = NULL;
args.gpu[i].buffer_gpu = NULL;
args.gpu[i].clean = TRUE;
args.gpu[i].request = FALSE;
}
victim = ( FLA_Obj_gpu* ) FLA_malloc( n_threads * sizeof( FLA_Obj_gpu ) );
args.victim = victim;
for ( i = 0; i < n_threads; i++ )
args.victim[i].obj.base = NULL;
gpu_log = ( FLA_Obj_gpu* ) FLA_malloc( gpu_n_blocks * n_threads * sizeof( FLA_Obj_gpu ) );
args.gpu_log = gpu_log;
#endif
// Initialize tasks with critical information.
FLASH_Queue_init_tasks( ( void* ) &args );
// Display verbose output before free all tasks.
if ( FLASH_Queue_get_verbose_output() )
FLASH_Queue_verbose_output();
// Start timing the parallel execution.
dtime = FLA_Clock();
#ifdef FLA_ENABLE_MULTITHREADING
// Parallel Execution!
FLASH_Queue_exec_parallel( ( void* ) &args );
#else
// Simulation!
FLASH_Queue_exec_simulation( ( void* ) &args );
#endif
// End timing the parallel execution.
dtime = FLA_Clock() - dtime;
FLASH_Queue_set_parallel_time( dtime );
#ifdef FLA_ENABLE_MULTITHREADING
// Destroy the locks.
FLA_Lock_destroy( &(args.all_lock) );
for ( i = 0; i < n_queues; i++ )
{
FLA_Lock_destroy( &(args.run_lock[i]) );
}
for ( i = 0; i < n_threads; i++ )
{
FLA_Lock_destroy( &(args.dep_lock[i]) );
FLA_Lock_destroy( &(args.war_lock[i]) );
}
for ( i = 0; i < n_caches; i++ )
{
FLA_Lock_destroy( &(args.cac_lock[i]) );
}
// Deallocate memory.
FLA_free( run_lock );
FLA_free( dep_lock );
FLA_free( war_lock );
FLA_free( cac_lock );
#endif
FLA_free( cache );
FLA_free( prefetch );
FLA_free( wait_queue );
#ifdef FLA_ENABLE_GPU
#ifdef FLA_ENABLE_MULTITHREADING
for ( i = 0; i < n_threads; i++ )
FLA_Lock_destroy( &(args.gpu_lock[i]) );
FLA_free( gpu_lock );
#endif
FLA_free( gpu );
FLA_free( victim );
FLA_free( gpu_log );
#endif
// Reset values for next call to FLASH_Queue_exec().
FLASH_Queue_reset();
return;
}
void FLASH_Queue_init_tasks( void* arg )
/*----------------------------------------------------------------------------
FLASH_Queue_init_tasks
----------------------------------------------------------------------------*/
{
FLASH_Queue_vars* args = ( FLASH_Queue_vars* ) arg;
integer i, j, k;
integer n_tasks = FLASH_Queue_get_num_tasks();
integer n_queues = args->n_queues;
integer n_prefetch = 0;
integer n_ready = 0;
integer length = 0;
integer width = 0;
integer height = 0;
integer size = args->size;
FLASH_Data_aff data_aff = FLASH_Queue_get_data_affinity();
FLASH_Task* t;
FLASH_Dep* d;
FLA_Obj obj;
#ifdef FLA_ENABLE_GPU
dim_t block_size = 0;
FLA_Datatype datatype = FLA_FLOAT;
dim_t datatype_size = FLA_Obj_datatype_size( datatype );
#endif
// Find the 2D factorization of the number of threads.
if ( data_aff == FLASH_QUEUE_AFFINITY_2D_BLOCK_CYCLIC )
{
integer sq_rt = 0;
while ( sq_rt * sq_rt <= n_queues ) sq_rt++;
sq_rt--;
while ( n_queues % sq_rt != 0 ) sq_rt--;
length = n_queues / sq_rt;
width = sq_rt;
}
// Grab the tail of the task queue.
t = FLASH_Queue_get_tail_task();
for ( i = n_tasks - 1; i >= 0; i-- )
{
// Determine data affinity.
if ( data_aff == FLASH_QUEUE_AFFINITY_NONE )
{ // No data affinity
t->queue = 0;
}
else
{
// Use the first output block to determine data affinity.
obj = t->output_arg[0];
// Use the top left block of the macroblock.
if ( FLA_Obj_elemtype( obj ) == FLA_MATRIX )
obj = *FLASH_OBJ_PTR_AT( obj );
if ( data_aff == FLASH_QUEUE_AFFINITY_2D_BLOCK_CYCLIC )
{ // Two-dimensional block cyclic
t->queue = ( obj.base->m_index % length ) +
( obj.base->n_index % width ) * length;
}
else if ( data_aff == FLASH_QUEUE_AFFINITY_1D_ROW_BLOCK_CYCLIC )
{ // One-dimensional row block cyclic
t->queue = obj.base->m_index % n_queues;
}
else if ( data_aff == FLASH_QUEUE_AFFINITY_1D_COLUMN_BLOCK_CYCLIC )
{ // One-dimensional column block cyclic
t->queue = obj.base->n_index % n_queues;
}
else
{ // Round-robin
t->queue = t->queue % n_queues;
}
}
// Determine the height of each task in the DAG.
height = 0;
d = t->dep_arg_head;
// Take the maximum height of dependent tasks.
for ( j = 0; j < t->n_dep_args; j++ )
{
height = max( height, d->task->height );
d = d->next_dep;
}
t->height = height + 1;
// Since freeing a task is always a leaf, we want to force it to execute
// earlier by giving it a greater height in order to reclaim memory.
if ( t->func == (void *) FLA_Obj_free_buffer_task )
t->height += n_tasks;
#ifdef FLA_ENABLE_GPU
for ( j = 0; j < t->n_output_args + t->n_input_args; j++ )
{
// Find the correct input or output argument.
if ( j < t->n_output_args )
obj = t->output_arg[j];
else
obj = t->input_arg[j - t->n_output_args];
// Macroblock is used.
if ( FLA_Obj_elemtype( obj ) == FLA_MATRIX )
{
dim_t jj, kk;
dim_t m = FLA_Obj_length( obj );
dim_t n = FLA_Obj_width( obj );
dim_t cs = FLA_Obj_col_stride( obj );
FLA_Obj* buf = FLASH_OBJ_PTR_AT( obj );
// Check each block in macroblock.
for ( jj = 0; jj < n; jj++ )
{
for ( kk = 0; kk < m; kk++ )
{
obj = *( buf + jj * cs + kk );
block_size = max( FLA_Obj_length( obj ) * FLA_Obj_width( obj ), block_size );
if ( jj == 0 && FLA_Obj_datatype( obj ) != datatype && FLA_Obj_datatype_size( FLA_Obj_datatype( obj ) ) > datatype_size )
{
datatype = FLA_Obj_datatype( obj );
datatype_size = FLA_Obj_datatype_size( datatype );
}
}
}
}
else // Regular block.
{
block_size = max( FLA_Obj_length( obj ) * FLA_Obj_width( obj ), block_size );
if ( FLA_Obj_datatype( obj ) != datatype && FLA_Obj_datatype_size( FLA_Obj_datatype( obj ) ) > datatype_size )
{
datatype = FLA_Obj_datatype( obj );
datatype_size = FLA_Obj_datatype_size( datatype );
}
}
}
#endif
// Find the first blocks accessed each task.
if ( n_prefetch < size )
{
for ( j = 0; j < t->n_output_args; j++ )
{
obj = t->output_arg[j];
// Macroblock is used.
if ( FLA_Obj_elemtype( obj ) == FLA_MATRIX )
{
dim_t jj, kk;
dim_t m = FLA_Obj_length( obj );
dim_t n = FLA_Obj_width( obj );
dim_t cs = FLA_Obj_col_stride( obj );
FLA_Obj* buf = FLASH_OBJ_PTR_AT( obj );
// Check each block in macroblock.
for ( jj = 0; jj < n; jj++ )
{
for ( kk = 0; kk < m; kk++ )
{
obj = *( buf + jj * cs + kk );
k = obj.base->n_write_blocks;
// This block is one of the first blocks to be accessed.
if ( k < size && k == n_prefetch )
{
args->prefetch[k] = obj;
n_prefetch++;
}
}
}
}
else // Regular block.
{
k = obj.base->n_write_blocks;
// This block is one of the first blocks to be accessed.
if ( k < size && k == n_prefetch )
{
args->prefetch[k] = obj;
n_prefetch++;
}
}
}
}
// Find all ready tasks.
t->n_ready += t->n_input_args + t->n_output_args +
t->n_macro_args + t->n_war_args;
if ( t->n_ready == 0 )
{
// Save the number of ready and available tasks.
n_ready++;
}
// Go to the previous task.
t = t->prev_task;
}
// Grab the head of the task queue.
t = FLASH_Queue_get_head_task();
for ( i = 0; i < n_tasks && n_ready > 0; i++ )
{
if ( t->n_ready == 0 )
{
// Enqueue all the ready and available tasks.
FLASH_Queue_wait_enqueue( t, arg );
// Decrement the number of ready tasks left to be enqueued.
n_ready--;
}
// Go to the next task.
t = t->next_task;
}
#ifdef FLA_ENABLE_GPU
args->block_size = block_size;
args->datatype = datatype;
#endif
return;
}
void FLASH_Queue_wait_enqueue( FLASH_Task* t, void* arg )
/*----------------------------------------------------------------------------
FLASH_Queue_wait_enqueue
----------------------------------------------------------------------------*/
{
FLASH_Queue_vars* args = ( FLASH_Queue_vars* ) arg;
integer queue = t->queue;
if ( args->wait_queue[queue].n_tasks == 0 )
{
args->wait_queue[queue].head = t;
args->wait_queue[queue].tail = t;
}
else
{
t->prev_wait = args->wait_queue[queue].tail;
// Insertion sort of tasks in waiting queue.
if ( FLASH_Queue_get_sorting() )
{
while ( t->prev_wait != NULL )
{
if ( t->prev_wait->height >= t->height )
break;
t->next_wait = t->prev_wait;
t->prev_wait = t->prev_wait->prev_wait;
}
}
// Checking if the task is the head of the waiting queue.
if ( t->prev_wait == NULL )
args->wait_queue[queue].head = t;
else
t->prev_wait->next_wait = t;
// Checking if the task is the tail of the waiting queue.
if ( t->next_wait == NULL )
args->wait_queue[queue].tail = t;
else
t->next_wait->prev_wait = t;
}
// Increment number of tasks on waiting queue.
args->wait_queue[queue].n_tasks++;
return;
}
FLASH_Task* FLASH_Queue_wait_dequeue( integer queue, integer cache, void* arg )
/*----------------------------------------------------------------------------
FLASH_Queue_wait_dequeue
----------------------------------------------------------------------------*/
{
FLASH_Queue_vars* args = ( FLASH_Queue_vars* ) arg;
FLASH_Task* t = NULL;
FLA_Bool enabled = FALSE;
#ifdef FLA_ENABLE_GPU
enabled = FLASH_Queue_get_enabled_gpu();
#endif
if ( args->wait_queue[queue].n_tasks > 0 )
{
// Dequeue the first task.
t = args->wait_queue[queue].head;
if ( args->wait_queue[queue].n_tasks == 1 )
{
// Clear the queue of its only task.
args->wait_queue[queue].head = NULL;
args->wait_queue[queue].tail = NULL;
}
else
{
// Grab a new task if using cache affinity.
if ( FLASH_Queue_get_caching() )
{
// Determine if using GPU or not.
if ( enabled )
{
#ifdef FLA_ENABLE_GPU
#ifdef FLA_ENABLE_MULTITHREADING
FLA_Lock_acquire( &(args->gpu_lock[cache]) ); // G ***
#endif
// Find a task where the task has blocks currently in GPU.
t = FLASH_Queue_wait_dequeue_block( queue, cache, arg );
#ifdef FLA_ENABLE_MULTITHREADING
FLA_Lock_release( &(args->gpu_lock[cache]) ); // G ***
#endif
#endif
}
else
{
#ifdef FLA_ENABLE_MULTITHREADING
FLA_Lock_acquire( &(args->cac_lock[cache]) ); // C ***
#endif
// Find a task where the task has blocks currently in cache.
t = FLASH_Queue_wait_dequeue_block( queue, cache, arg );
#ifdef FLA_ENABLE_MULTITHREADING
FLA_Lock_release( &(args->cac_lock[cache]) ); // C ***
#endif
}
// Adjust pointers if the task is head of waiting queue.
if ( t->prev_wait == NULL )
{
args->wait_queue[queue].head = t->next_wait;
args->wait_queue[queue].head->prev_wait = NULL;
}
else
{
t->prev_wait->next_wait = t->next_wait;
}
// Adjust pointers if the task is tail of waiting queue.
if ( t->next_wait == NULL )
{
args->wait_queue[queue].tail = t->prev_wait;
args->wait_queue[queue].tail->next_wait = NULL;
}
else
{
t->next_wait->prev_wait = t->prev_wait;
}
}
else
{
// Adjust pointers in waiting queue.
args->wait_queue[queue].head = t->next_wait;
args->wait_queue[queue].head->prev_wait = NULL;
}
}
// Clear the task's waiting linked list pointers.
t->prev_wait = NULL;
t->next_wait = NULL;
// Decrement number of tasks on waiting queue.
args->wait_queue[queue].n_tasks--;
}
return t;
}
FLASH_Task* FLASH_Queue_wait_dequeue_block( integer queue, integer cache, void* arg )
/*----------------------------------------------------------------------------
FLASH_Queue_wait_dequeue_block
----------------------------------------------------------------------------*/
{
FLASH_Queue_vars* args = ( FLASH_Queue_vars* ) arg;
integer i, j, k;
integer size = args->size;
integer n_tasks = args->wait_queue[queue].n_tasks;
FLA_Bool enabled = FALSE;
FLASH_Task* t;
FLA_Obj obj;
FLA_Obj mem;
#ifdef FLA_ENABLE_GPU
enabled = FLASH_Queue_get_enabled_gpu();
// If using GPUs, then only check GPU and not the cache.
if ( enabled )
size = FLASH_Queue_get_gpu_num_blocks();
#endif
t = args->wait_queue[queue].head;
// Check if any of the output blocks are in the cache.
for ( i = 0; i < n_tasks; i++ )
{
for ( j = 0; j < size; j++ )
{
// Initialize the memory just in case.
mem.base = NULL;
// Determine if using GPU or not.
if ( enabled )
{
#ifdef FLA_ENABLE_GPU
mem = args->gpu[cache * size + j].obj;
#endif
}
else
{
mem = args->cache[cache * size + j];
}
for ( k = 0; k < t->n_output_args; k++ )
{
obj = t->output_arg[k];
if ( FLA_Obj_elemtype( obj ) == FLA_MATRIX )
obj = *FLASH_OBJ_PTR_AT( obj );
// Return the task if its output block is in cache.
if ( mem.base == obj.base )
{
t->hit = TRUE;
return t;
}
}
}
t = t->next_wait;
}
return args->wait_queue[queue].head;
}
void FLASH_Queue_update_cache( FLASH_Task* t, void* arg )
/*----------------------------------------------------------------------------
FLASH_Queue_update_cache
----------------------------------------------------------------------------*/
{
integer i, j;
FLA_Bool duplicate;
FLA_Obj obj;
if ( t == NULL )
return;
// Updating the input blocks.
for ( i = t->n_input_args - 1; i >= 0; i-- )
{
// Check for duplicate blocks.
duplicate = FALSE;
for ( j = 0; j < t->n_output_args && !duplicate; j++ )
{
if ( t->input_arg[i].base == t->output_arg[j].base )
duplicate = TRUE;
}
for ( j = 0; j < i && !duplicate; j++ )
{
if ( t->input_arg[i].base == t->input_arg[j].base )
duplicate = TRUE;
}
// If the input block has not been processed before.
if ( !duplicate )
{
obj = t->input_arg[i];
// Macroblock is used.
if ( FLA_Obj_elemtype( obj ) == FLA_MATRIX )
{
dim_t jj, kk;
dim_t m = FLA_Obj_length( obj );
dim_t n = FLA_Obj_width( obj );
dim_t cs = FLA_Obj_col_stride( obj );
FLA_Obj* buf = FLASH_OBJ_PTR_AT( obj );
// Dependence analysis for each input block in macroblock.
for ( jj = 0; jj < n; jj++ )
for ( kk = 0; kk < m; kk++ )
FLASH_Queue_update_cache_block( *( buf + jj * cs + kk ),
t->cache, FALSE, arg );
}
else // Regular block.
{
FLASH_Queue_update_cache_block( obj, t->cache, FALSE, arg );
}
}
}
// Updating the output blocks.
for ( i = t->n_output_args - 1; i >= 0; i-- )
{
// Check for duplicate blocks.
duplicate = FALSE;
for ( j = 0; j < i && !duplicate; j++ )
{
if ( t->output_arg[i].base == t->output_arg[j].base )
duplicate = TRUE;
}
// If the output block has not been processed before.
if ( !duplicate )
{
obj = t->output_arg[i];
// Macroblock is used.
if ( FLA_Obj_elemtype( obj ) == FLA_MATRIX )
{
dim_t jj, kk;
dim_t m = FLA_Obj_length( obj );
dim_t n = FLA_Obj_width( obj );
dim_t cs = FLA_Obj_col_stride( obj );
FLA_Obj* buf = FLASH_OBJ_PTR_AT( obj );
// Dependence analysis for each input block in macroblock.
for ( jj = 0; jj < n; jj++ )
for ( kk = 0; kk < m; kk++ )
FLASH_Queue_update_cache_block( *( buf + jj * cs + kk ),
t->cache, TRUE, arg );
}
else // Regular block.
{
FLASH_Queue_update_cache_block( obj, t->cache, TRUE, arg );
}
}
}
return;
}
void FLASH_Queue_update_cache_block( FLA_Obj obj,
integer cache,
FLA_Bool output,
void* arg )
/*----------------------------------------------------------------------------
FLASH_Queue_update_cache_block
----------------------------------------------------------------------------*/
{
FLASH_Queue_vars* args = ( FLASH_Queue_vars* ) arg;
integer i, j, k;
integer n_caches = args->n_caches;
integer size = args->size;
#ifdef FLA_ENABLE_MULTITHREADING
FLA_Lock_acquire( &(args->cac_lock[cache]) ); // C ***
#endif
// Locate the position of the block in the cache.
for ( k = 0; k < size - 1; k++ )
{
if ( obj.base == args->cache[cache * size + k].base )
break;
}
// Shift all the previous tasks for LRU replacement.
for ( j = k; j > 0; j-- )
args->cache[cache * size + j] = args->cache[cache * size + j - 1];
// Place the block on the cache as the most recently used.
args->cache[cache * size] = obj;
#ifdef FLA_ENABLE_MULTITHREADING
FLA_Lock_release( &(args->cac_lock[cache]) ); // C ***
#endif
// Write invalidate if updating with output block.
if ( output )
{
for ( i = 0; i < n_caches; i++ )
{
if ( i != cache )
{
#ifdef FLA_ENABLE_MULTITHREADING
FLA_Lock_acquire( &(args->cac_lock[i]) ); // C ***
#endif
// Locate the position of the block in the cache.
for ( k = 0; k < size; k++ )
{
if ( obj.base == args->cache[i * size + k].base )
break;
}
// The block is owned by other thread.
if ( k < size )
{
// Shift all the blocks for the invalidated block.
for ( j = k; j < size - 1; j++ )
args->cache[i * size + j] = args->cache[i * size + j + 1];
// Invalidate the block.
args->cache[i * size + size - 1].base = NULL;
}
#ifdef FLA_ENABLE_MULTITHREADING
FLA_Lock_release( &(args->cac_lock[i]) ); // C ***
#endif
}
}
}
return;
}
void FLASH_Queue_prefetch( integer cache, void* arg )
/*----------------------------------------------------------------------------
FLASH_Queue_prefetch
----------------------------------------------------------------------------*/
{
FLASH_Queue_vars* args = ( FLASH_Queue_vars* ) arg;
integer i;
integer size = args->size;
FLA_Obj obj;
// Prefetch blocks in opposite order to maintain LRU.
for ( i = size - 1; i >= 0; i-- )
{
obj = args->prefetch[i];
// Only prefetch if it is a valid block.
if ( obj.base != NULL )
{
// Prefetch the block.
FLASH_Queue_prefetch_block( obj );
// Record the prefetched block in the cache.
args->cache[cache * size + i] = obj;
}
}
return;
}
void FLASH_Queue_prefetch_block( FLA_Obj obj )
/*----------------------------------------------------------------------------
FLASH_Queue_prefetch_block
----------------------------------------------------------------------------*/
{
integer i, inc;
integer line_size = FLASH_Queue_get_cache_line_size();
integer elem_size = FLA_Obj_elem_size( obj );
integer length = FLA_Obj_length( obj );
integer width = FLA_Obj_width( obj );
FLA_Datatype datatype = FLA_Obj_datatype( obj );
// Determine stride to prefetch block into cache.
inc = line_size / elem_size;
// Switch between the four different datatypes.
switch ( datatype )
{
case FLA_FLOAT:
{
float *buffer = ( float * ) FLA_FLOAT_PTR( obj );
float access;
// Access each cache line of the block.
for ( i = 0; i < length * width; i += inc )
access = buffer[i];
// Prevent dead code elimination.
access += 1.0;
break;
}
case FLA_DOUBLE:
{
double *buffer = ( double * ) FLA_DOUBLE_PTR( obj );
double access;
// Access each cache line of the block.
for ( i = 0; i < length * width; i += inc )
access = buffer[i];
// Prevent dead code elimination.
access += 1.0;
break;
}
case FLA_COMPLEX:
{
scomplex *buffer = ( scomplex * ) FLA_COMPLEX_PTR( obj );
scomplex access;
// Access each cache line of the block.
for ( i = 0; i < length * width; i += inc )
access = buffer[i];
// Prevent dead code elimination.
access.real += 1.0;
break;
}
case FLA_DOUBLE_COMPLEX:
{
dcomplex *buffer = ( dcomplex * ) FLA_DOUBLE_COMPLEX_PTR( obj );
dcomplex access;
// Access each cache line of the block.
for ( i = 0; i < length * width; i += inc )
access = buffer[i];
// Prevent dead code elimination.
access.real += 1.0;
break;
}
case FLA_INT:
{
integer *buffer = ( integer * ) FLA_INT_PTR( obj );
integer access;
// Access each cache line of the block.
for ( i = 0; i < length * width; i += inc )
access = buffer[i];
// Prevent dead code elimination.
access += 1.0;
break;
}
default:
// This default case should never execute.
FLA_Check_error_code( FLA_INVALID_DATATYPE );
}
return;
}
FLASH_Task* FLASH_Queue_work_stealing( integer queue, void *arg )
/*----------------------------------------------------------------------------
FLASH_Queue_work_stealing
----------------------------------------------------------------------------*/
{
FLASH_Queue_vars* args = ( FLASH_Queue_vars* ) arg;
integer q;
integer n_queues = args->n_queues;
FLASH_Task* t = NULL;
// Do not perform work stealing if there is only one queue.
if ( n_queues == 1 )
return t;
// Find a random queue not equal to the current queue.
do
{
#ifdef FLA_ENABLE_WINDOWS_BUILD
rand_s( &q );
q = q % n_queues;
#else
#ifdef FLA_ENABLE_TIDSP
q = rand() % n_queues;
#else
q = lrand48() % n_queues;
#endif
#endif
}
while ( q == queue );
#ifdef FLA_ENABLE_MULTITHREADING
FLA_Lock_acquire( &(args->run_lock[q]) ); // R ***
#endif
// If there are tasks that this thread can steal.
if ( args->wait_queue[q].n_tasks > 0 )
{
// Dequeue the last task.
t = args->wait_queue[q].tail;
if ( args->wait_queue[q].n_tasks == 1 )
{
// Clear the queue of its only task.
args->wait_queue[q].head = NULL;
args->wait_queue[q].tail = NULL;
}
else
{
// Adjust pointers in waiting queue.
args->wait_queue[q].tail = t->prev_wait;
args->wait_queue[q].tail->next_wait = NULL;
}
// Reset waiting queue data about the stolen task.
t->queue = queue;
t->prev_wait = NULL;
t->next_wait = NULL;
args->wait_queue[q].n_tasks--;
}
#ifdef FLA_ENABLE_MULTITHREADING
FLA_Lock_release( &(args->run_lock[q]) ); // R ***
#endif
return t;
}
#ifdef FLA_ENABLE_GPU
void FLASH_Queue_create_gpu( integer thread, void *arg )
/*----------------------------------------------------------------------------
FLASH_Queue_create_gpu
----------------------------------------------------------------------------*/
{
FLASH_Queue_vars* args = ( FLASH_Queue_vars* ) arg;
integer i;
dim_t gpu_n_blocks = FLASH_Queue_get_gpu_num_blocks();
dim_t block_size = args->block_size;
FLA_Datatype datatype = args->datatype;
// Exit if not using GPU.
if ( !FLASH_Queue_get_enabled_gpu() )
return;
// Bind thread to GPU.
FLASH_Queue_bind_gpu( thread );
// Allocate the memory on the GPU for all the blocks a priori.
for ( i = 0; i < gpu_n_blocks; i++ )
FLASH_Queue_alloc_gpu( block_size, datatype, &(args->gpu[thread * gpu_n_blocks + i].buffer_gpu) );
return;
}
void FLASH_Queue_destroy_gpu( integer thread, void *arg )
/*----------------------------------------------------------------------------
FLASH_Queue_destroy_gpu
----------------------------------------------------------------------------*/
{
FLASH_Queue_vars* args = ( FLASH_Queue_vars* ) arg;
integer i;
dim_t gpu_n_blocks = FLASH_Queue_get_gpu_num_blocks();
FLA_Obj_gpu gpu_obj;
// Exit if not using GPU.
if ( !FLASH_Queue_get_enabled_gpu() )
return;
// Examine every block left on the GPU.
for ( i = 0; i < gpu_n_blocks; i++ )
{
gpu_obj = args->gpu[thread * gpu_n_blocks + i];
// Flush the blocks that are dirty.
if ( gpu_obj.obj.base != NULL && !gpu_obj.clean )
FLASH_Queue_read_gpu( gpu_obj.obj, gpu_obj.buffer_gpu );
// Free the memory on the GPU for all the blocks.
FLASH_Queue_free_gpu( gpu_obj.buffer_gpu );
}
return;
}
FLA_Bool FLASH_Queue_exec_gpu( FLASH_Task *t, void *arg )
/*----------------------------------------------------------------------------
FLASH_Queue_exec_gpu
----------------------------------------------------------------------------*/
{
void** input_arg;
void** output_arg;
if ( t == NULL )
return TRUE;
// If not using the GPU, then execute on CPU.
if ( !FLASH_Queue_get_enabled_gpu() )
{
FLASH_Queue_exec_task( t );
return TRUE;
}
// Check if all the operands are ready and up to date.
if ( !FLASH_Queue_check_gpu( t, arg ) )
{
FLASH_Queue_vars* args = ( FLASH_Queue_vars* ) arg;
integer queue = t->queue;
t->hit = FALSE;
#ifdef FLA_ENABLE_MULTITHREADING
FLA_Lock_acquire( &(args->run_lock[queue]) ); // R ***
#endif
// Reenqueue the task if the blocks are not all flushed.
FLASH_Queue_wait_enqueue( t, arg );
#ifdef FLA_ENABLE_MULTITHREADING
FLA_Lock_release( &(args->run_lock[queue]) ); // R ***
#endif
return FALSE;
}
// If GPU is enabled, but the task is not supported for GPU execution.
if ( !t->enabled_gpu )
{
integer i, j, k;
integer thread = t->thread;
integer n_input_args = t->n_input_args;
integer n_output_args = t->n_output_args;
integer n_threads = FLASH_Queue_get_num_threads();
FLA_Bool duplicate;
FLA_Obj obj;
// Check the blocks on each GPU.
for ( k = 0; k < n_threads; k++ )
{
// Check the input and output arguments on the GPUs.
for ( i = 0; i < n_input_args + n_output_args; i++ )
{
// Check for duplicate blocks.
duplicate = FALSE;
// Find the correct input or output argument.
if ( i < n_input_args )
{
obj = t->input_arg[i];
for ( j = 0; j < n_output_args && !duplicate; j++ )
{
if ( obj.base == t->output_arg[j].base )
duplicate = TRUE;
}
for ( j = 0; j < i && !duplicate; j++ )
{
if ( obj.base == t->input_arg[j].base )
duplicate = TRUE;
}
}
else
{
obj = t->output_arg[i - n_input_args];
for ( j = 0; j < i - n_input_args && !duplicate; j++ )
{
if ( obj.base == t->output_arg[j].base )
duplicate = TRUE;
}
}
// If the block has not been processed before.
if ( !duplicate )
{
// Macroblock is used.
if ( FLA_Obj_elemtype( obj ) == FLA_MATRIX )
{
dim_t jj, kk;
dim_t m = FLA_Obj_length( obj );
dim_t n = FLA_Obj_width( obj );
dim_t cs = FLA_Obj_col_stride( obj );
FLA_Obj* buf = FLASH_OBJ_PTR_AT( obj );
// Clear each block in macroblock.
for ( jj = 0; jj < n; jj++ )
{
for ( kk = 0; kk < m; kk++ )
{
obj = *( buf + jj * cs + kk );
// Flush the block to main memory if it is on the GPU.
if ( k == thread )
FLASH_Queue_flush_block_gpu( obj, k, arg );
// Invalidate output block on all GPUs.
if ( i >= n_input_args )
FLASH_Queue_invalidate_block_gpu( obj, k, arg );
}
}
}
else
{
// Flush the block to main memory if it is on the GPU.
if ( k == thread )
FLASH_Queue_flush_block_gpu( obj, k, arg );
// Invalidate output block on all GPUs.
if ( i >= n_input_args )
FLASH_Queue_invalidate_block_gpu( obj, k, arg );
}
}
}
}
// Execute the task on CPU instead of GPU.
FLASH_Queue_exec_task( t );
return TRUE;
}
// Gather the pointers for the data on the GPU.
input_arg = ( void** ) FLA_malloc( t->n_input_args * sizeof( void* ) );
output_arg = ( void** ) FLA_malloc( t->n_output_args * sizeof( void* ) );
// Bring all the blocks to GPU.
FLASH_Queue_update_gpu( t, input_arg, output_arg, arg );
// Execute the task on GPU.
FLASH_Queue_exec_task_gpu( t, input_arg, output_arg );
// Mark all the output blocks as dirty.
FLASH_Queue_mark_gpu( t, arg );
// Free memory.
FLA_free( input_arg );
FLA_free( output_arg );
return TRUE;
}
FLA_Bool FLASH_Queue_check_gpu( FLASH_Task *t, void *arg )
/*----------------------------------------------------------------------------
FLASH_Queue_check_gpu
----------------------------------------------------------------------------*/
{
integer i, j, k;
integer thread = t->thread;
integer n_input_args = t->n_input_args;
integer n_output_args = t->n_output_args;
integer n_threads = FLASH_Queue_get_num_threads();
FLA_Bool r_val = TRUE;
FLA_Bool t_val;
FLA_Bool duplicate;
FLA_Obj obj;
// Check the input and output arguments on the GPUs.
for ( i = 0; i < n_input_args + n_output_args; i++ )
{
// Check for duplicate blocks.
duplicate = FALSE;
// Find the correct input or output argument.
if ( i < n_input_args )
{
obj = t->input_arg[i];
for ( j = 0; j < n_output_args && !duplicate; j++ )
{
if ( obj.base == t->output_arg[j].base )
duplicate = TRUE;
}
for ( j = 0; j < i && !duplicate; j++ )
{
if ( obj.base == t->input_arg[j].base )
duplicate = TRUE;
}
}
else
{
obj = t->output_arg[i - n_input_args];
for ( j = 0; j < i - n_input_args && !duplicate; j++ )
{
if ( obj.base == t->output_arg[j].base )
duplicate = TRUE;
}
}
// If the block has not been processed before.
if ( !duplicate )
{
// Macroblock is used.
if ( FLA_Obj_elemtype( obj ) == FLA_MATRIX )
{
dim_t jj, kk;
dim_t m = FLA_Obj_length( obj );
dim_t n = FLA_Obj_width( obj );
dim_t cs = FLA_Obj_col_stride( obj );
FLA_Obj* buf = FLASH_OBJ_PTR_AT( obj );
// Clear each block in macroblock.
for ( jj = 0; jj < n; jj++ )
{
for ( kk = 0; kk < m; kk++ )
{
obj = *( buf + jj * cs + kk );
t_val = TRUE;
// Check to see if the block is dirty on another GPU.
for ( k = 0; k < n_threads && t_val; k++ )
if ( k != thread )
t_val = t_val && FLASH_Queue_check_block_gpu( obj, k, arg );
r_val = r_val && t_val;
}
}
}
else
{
t_val = TRUE;
// Check to see if the block is dirty on another GPU.
for ( k = 0; k < n_threads && t_val; k++ )
if ( k != thread )
t_val = t_val && FLASH_Queue_check_block_gpu( obj, k, arg );
r_val = r_val && t_val;
}
}
}
return r_val;
}
FLA_Bool FLASH_Queue_check_block_gpu( FLA_Obj obj, integer thread, void *arg )
/*----------------------------------------------------------------------------
FLASH_Queue_check_block_gpu
----------------------------------------------------------------------------*/
{
FLASH_Queue_vars* args = ( FLASH_Queue_vars* ) arg;
integer k;
dim_t gpu_n_blocks = FLASH_Queue_get_gpu_num_blocks();
FLA_Bool r_val = TRUE;
#ifdef FLA_ENABLE_MULTITHREADING
FLA_Lock_acquire( &(args->gpu_lock[thread]) ); // G ***
#endif
// Locate the position of the block on the GPU.
for ( k = 0; k < gpu_n_blocks; k++ )
if ( obj.base == args->gpu[thread * gpu_n_blocks + k].obj.base )
break;
if ( k < gpu_n_blocks )
{
// Request this block if it is dirty.
if ( !args->gpu[thread * gpu_n_blocks + k].clean )
{
args->gpu[thread * gpu_n_blocks + k].request = TRUE;
r_val = FALSE;
}
}
// Check the victim block.
if ( obj.base == args->victim[thread].obj.base )
r_val = FALSE;
#ifdef FLA_ENABLE_MULTITHREADING
FLA_Lock_release( &(args->gpu_lock[thread]) ); // G ***
#endif
return r_val;
}
void FLASH_Queue_update_gpu( FLASH_Task *t,
void **input_arg,
void **output_arg,
void *arg )
/*----------------------------------------------------------------------------
FLASH_Queue_update_gpu
----------------------------------------------------------------------------*/
{
integer i, j, k;
integer thread = t->thread;
integer n_threads = FLASH_Queue_get_num_threads();
FLA_Bool duplicate;
// None of the arguments can be macroblocks yet.
// Complicating factor is copying macroblock to contiguous memory on GPU.
// Bring the input arguments to the GPU.
for ( i = t->n_input_args - 1; i >= 0; i-- )
{
// Check for duplicate blocks.
duplicate = FALSE;
for ( j = 0; j < t->n_output_args && !duplicate; j++ )
{
if ( t->input_arg[i].base == t->output_arg[j].base )
duplicate = TRUE;
}
for ( j = 0; j < i && !duplicate; j++ )
{
if ( t->input_arg[i].base == t->input_arg[j].base )
duplicate = TRUE;
}
// If the input block has not been processed before.
if ( !duplicate )
{
FLASH_Queue_update_block_gpu( t->input_arg[i], input_arg + i, thread, arg );
}
else
{
input_arg[i] = NULL;
}
}
// Bring the output arguments to the GPU.
for ( i = t->n_output_args - 1; i >= 0; i-- )
{
// Check for duplicate blocks.
duplicate = FALSE;
for ( j = 0; j < i && !duplicate; j++ )
{
if ( t->output_arg[i].base == t->output_arg[j].base )
duplicate = TRUE;
}
// If the output block has not been processed before.
if ( !duplicate )
{
FLASH_Queue_update_block_gpu( t->output_arg[i], output_arg + i, thread, arg );
// Invalidate output blocks on all other GPUs.
for ( k = 0; k < n_threads; k++ )
if ( k != thread )
FLASH_Queue_invalidate_block_gpu( t->output_arg[i], k, arg );
}
else
{
output_arg[i] = NULL;
}
}
// Check to see if there are any duplicates.
for ( i = t->n_input_args - 1; i >= 0; i-- )
{
for ( j = 0; j < t->n_output_args && input_arg[i] == NULL; j++ )
{
if ( t->input_arg[i].base == t->output_arg[j].base )
input_arg[i] = output_arg[j];
}
for ( j = 0; j < i && input_arg[i] == NULL; j++ )
{
if ( t->input_arg[i].base == t->input_arg[j].base )
input_arg[i] = input_arg[j];
}
}
// Check to see if there are any duplicates.
for ( i = t->n_output_args - 1; i >= 0; i-- )
{
for ( j = 0; j < i && output_arg[i] == NULL; j++ )
{
if ( t->output_arg[i].base == t->output_arg[j].base )
output_arg[i] = output_arg[j];
}
}
return;
}
void FLASH_Queue_update_block_gpu( FLA_Obj obj,
void **buffer_gpu,
integer thread,
void *arg )
/*----------------------------------------------------------------------------
FLASH_Queue_update_block_gpu
----------------------------------------------------------------------------*/
{
FLASH_Queue_vars* args = ( FLASH_Queue_vars* ) arg;
integer j, k;
dim_t gpu_n_blocks = FLASH_Queue_get_gpu_num_blocks();
FLA_Bool transfer = FALSE;
FLA_Bool evict = FALSE;
FLA_Obj_gpu evict_obj;
FLA_Obj_gpu gpu_obj;
#ifdef FLA_ENABLE_MULTITHREADING
FLA_Lock_acquire( &(args->gpu_lock[thread]) ); // G ***
#endif
// Locate the position of the block on GPU.
for ( k = 0; k < gpu_n_blocks - 1; k++ )
if ( obj.base == args->gpu[thread * gpu_n_blocks + k].obj.base )
break;
// Save the pointer to the data on the GPU.
buffer_gpu[0] = args->gpu[thread * gpu_n_blocks + k].buffer_gpu;
// Save the victim block.
evict_obj = args->gpu[thread * gpu_n_blocks + k];
// The block is not already in the GPU.
if ( obj.base != args->gpu[thread * gpu_n_blocks + k].obj.base )
{
// Save for data transfer outside of critical section.
transfer = TRUE;
// Save for eviction outside of critical section.
if ( evict_obj.obj.base != NULL && !evict_obj.clean )
{
evict = TRUE;
args->victim[thread] = evict_obj;
}
// Save the block in the data structure.
args->gpu[thread * gpu_n_blocks + k].obj = obj;
// Make sure the new block is clean.
args->gpu[thread * gpu_n_blocks + k].clean = TRUE;
args->gpu[thread * gpu_n_blocks + k].request = FALSE;
}
// Use the block on the GPU that is a hit or LRU.
gpu_obj = args->gpu[thread * gpu_n_blocks + k];
// Shift all the previous tasks for LRU replacement.
for ( j = k; j > 0; j-- )
args->gpu[thread * gpu_n_blocks + j] = args->gpu[thread * gpu_n_blocks + j - 1];
// Place the block on the cache as the most recently used.
args->gpu[thread * gpu_n_blocks] = gpu_obj;
#ifdef FLA_ENABLE_MULTITHREADING
FLA_Lock_release( &(args->gpu_lock[thread]) ); // G ***
#endif
// Evict and flush the LRU dirty block.
if ( evict )
{
FLASH_Queue_read_gpu( evict_obj.obj, evict_obj.buffer_gpu );
#ifdef FLA_ENABLE_MULTITHREADING
FLA_Lock_acquire( &(args->gpu_lock[thread]) ); // G ***
#endif
args->victim[thread].obj.base = NULL;
#ifdef FLA_ENABLE_MULTITHREADING
FLA_Lock_release( &(args->gpu_lock[thread]) ); // G ***
#endif
}
// Move the block to the GPU.
if ( transfer )
FLASH_Queue_write_gpu( gpu_obj.obj, gpu_obj.buffer_gpu );
return;
}
void FLASH_Queue_mark_gpu( FLASH_Task *t, void *arg )
/*----------------------------------------------------------------------------
FLASH_Queue_mark_gpu
----------------------------------------------------------------------------*/
{
FLASH_Queue_vars* args = ( FLASH_Queue_vars* ) arg;
integer i, j, k;
integer thread = t->thread;
dim_t gpu_n_blocks = FLASH_Queue_get_gpu_num_blocks();
FLA_Bool duplicate;
FLA_Obj obj;
// Mark all the output blocks on the GPU as dirty.
for ( i = t->n_output_args - 1; i >= 0; i-- )
{
obj = t->output_arg[i];
// Check for duplicate blocks.
duplicate = FALSE;
for ( j = 0; j < i && !duplicate; j++ )
{
if ( obj.base == t->output_arg[j].base )
duplicate = TRUE;
}
// If the output block has not been processed before.
if ( !duplicate )
{
#ifdef FLA_ENABLE_MULTITHREADING
FLA_Lock_acquire( &(args->gpu_lock[thread]) ); // G ***
#endif
// Locate the position of the block on the GPU.
for ( k = 0; k < gpu_n_blocks; k++ )
if ( obj.base == args->gpu[thread * gpu_n_blocks + k].obj.base )
break;
if ( k < gpu_n_blocks )
{
// Change the bits for the new dirty block.
args->gpu[thread * gpu_n_blocks + k].clean = FALSE;
args->gpu[thread * gpu_n_blocks + k].request = FALSE;
}
#ifdef FLA_ENABLE_MULTITHREADING
FLA_Lock_release( &(args->gpu_lock[thread]) ); // G ***
#endif
}
}
return;
}
void FLASH_Queue_invalidate_block_gpu( FLA_Obj obj, integer thread, void *arg )
/*----------------------------------------------------------------------------
FLASH_Queue_invalidate_block_gpu
----------------------------------------------------------------------------*/
{
FLASH_Queue_vars* args = ( FLASH_Queue_vars* ) arg;
integer j, k;
dim_t gpu_n_blocks = FLASH_Queue_get_gpu_num_blocks();
FLA_Obj_gpu gpu_obj;
#ifdef FLA_ENABLE_MULTITHREADING
FLA_Lock_acquire( &(args->gpu_lock[thread]) ); // G ***
#endif
// Locate the position of the block on the GPU.
for ( k = 0; k < gpu_n_blocks; k++ )
if ( obj.base == args->gpu[thread * gpu_n_blocks + k].obj.base )
break;
// The block is owned by other GPU.
if ( k < gpu_n_blocks )
{
// Invalidate the block.
args->gpu[thread * gpu_n_blocks + k].obj.base = NULL;
args->gpu[thread * gpu_n_blocks + k].clean = TRUE;
args->gpu[thread * gpu_n_blocks + k].request = FALSE;
// Save the block that will be invalidated.
gpu_obj = args->gpu[thread * gpu_n_blocks + k];
// Shift all the blocks for the invalidated block.
for ( j = k; j < gpu_n_blocks - 1; j++ )
args->gpu[thread * gpu_n_blocks + j] = args->gpu[thread * gpu_n_blocks + j + 1];
// Move to the LRU block.
args->gpu[thread * gpu_n_blocks + gpu_n_blocks - 1] = gpu_obj;
}
#ifdef FLA_ENABLE_MULTITHREADING
FLA_Lock_release( &(args->gpu_lock[thread]) ); // G ***
#endif
return;
}
void FLASH_Queue_flush_block_gpu( FLA_Obj obj, integer thread, void *arg )
/*----------------------------------------------------------------------------
FLASH_Queue_flush_block_gpu
----------------------------------------------------------------------------*/
{
FLASH_Queue_vars* args = ( FLASH_Queue_vars* ) arg;
integer k;
dim_t gpu_n_blocks = FLASH_Queue_get_gpu_num_blocks();
FLA_Bool transfer = FALSE;
FLA_Obj_gpu gpu_obj;
#ifdef FLA_ENABLE_MULTITHREADING
FLA_Lock_acquire( &(args->gpu_lock[thread]) ); // G ***
#endif
// Locate the position of the block on the GPU.
for ( k = 0; k < gpu_n_blocks; k++ )
if ( obj.base == args->gpu[thread * gpu_n_blocks + k].obj.base )
break;
// The block is owned by the GPU.
if ( k < gpu_n_blocks )
{
// Save the block that will be flushed.
gpu_obj = args->gpu[thread * gpu_n_blocks + k];
// If the block is dirty, then flush it.
if ( gpu_obj.obj.base != NULL && !gpu_obj.clean )
transfer = TRUE;
}
#ifdef FLA_ENABLE_MULTITHREADING
FLA_Lock_release( &(args->gpu_lock[thread]) ); // G ***
#endif
// Exit early if a flush is not required.
if ( !transfer )
return;
// Flush the block outside the critical section.
FLASH_Queue_read_gpu( gpu_obj.obj, gpu_obj.buffer_gpu );
#ifdef FLA_ENABLE_MULTITHREADING
FLA_Lock_acquire( &(args->gpu_lock[thread]) ); // G ***
#endif
// Locate the position of the block on the GPU.
for ( k = 0; k < gpu_n_blocks; k++ )
if ( obj.base == args->gpu[thread * gpu_n_blocks + k].obj.base )
break;
if ( k < gpu_n_blocks )
{
// Update the bits for the flushed block.
args->gpu[thread * gpu_n_blocks + k].clean = TRUE;
args->gpu[thread * gpu_n_blocks + k].request = FALSE;
}
#ifdef FLA_ENABLE_MULTITHREADING
FLA_Lock_release( &(args->gpu_lock[thread]) ); // G ***
#endif
return;
}
void FLASH_Queue_flush_gpu( integer thread, void *arg )
/*----------------------------------------------------------------------------
FLASH_Queue_flush_gpu
----------------------------------------------------------------------------*/
{
FLASH_Queue_vars* args = ( FLASH_Queue_vars* ) arg;
integer i, k;
dim_t gpu_n_blocks = FLASH_Queue_get_gpu_num_blocks();
integer n_transfer = 0;
FLA_Obj_gpu gpu_obj;
// Exit if not using GPU.
if ( !FLASH_Queue_get_enabled_gpu() )
return;
#ifdef FLA_ENABLE_MULTITHREADING
FLA_Lock_acquire( &(args->gpu_lock[thread]) ); // G ***
#endif
for ( k = 0; k < gpu_n_blocks; k++ )
{
// Save the block that might be flushed.
gpu_obj = args->gpu[thread * gpu_n_blocks + k];
// Flush the block if it is dirty and requested.
if ( gpu_obj.obj.base != NULL && !gpu_obj.clean && gpu_obj.request )
{
// Save the block for data transfer outside the critical section.
args->gpu_log[thread * gpu_n_blocks + n_transfer] = gpu_obj;
n_transfer++;
}
}
#ifdef FLA_ENABLE_MULTITHREADING
FLA_Lock_release( &(args->gpu_lock[thread]) ); // G ***
#endif
// Exit early if a flush is not required.
if ( n_transfer == 0 )
return;
// Flush the block outside the critical section.
for ( i = 0; i < n_transfer; i++ )
{
gpu_obj = args->gpu_log[thread * gpu_n_blocks + i];
FLASH_Queue_read_gpu( gpu_obj.obj, gpu_obj.buffer_gpu );
}
#ifdef FLA_ENABLE_MULTITHREADING
FLA_Lock_acquire( &(args->gpu_lock[thread]) ); // G ***
#endif
// Update the bits for each block that is flushed.
for ( i = 0; i < n_transfer; i++ )
{
// Locate the position of the block on the GPU.
for ( k = 0; k < gpu_n_blocks; k++ )
if ( args->gpu_log[thread * gpu_n_blocks + i].obj.base ==
args->gpu[thread * gpu_n_blocks + k].obj.base )
break;
if ( k < gpu_n_blocks )
{
// The block is now clean.
args->gpu[thread * gpu_n_blocks + k].clean = TRUE;
args->gpu[thread * gpu_n_blocks + k].request = FALSE;
}
}
#ifdef FLA_ENABLE_MULTITHREADING
FLA_Lock_release( &(args->gpu_lock[thread]) ); // G ***
#endif
return;
}
#endif
#ifdef FLA_ENABLE_MULTITHREADING
void FLASH_Queue_exec_parallel( void* arg )
/*----------------------------------------------------------------------------
FLASH_Queue_exec_parallel
----------------------------------------------------------------------------*/
{
integer i;
integer n_threads = FLASH_Queue_get_num_threads();
void* (*thread_entry_point)( void* );
// Allocate the thread structures array. Here, an array of FLASH_Thread
// structures of length n_threads is allocated and the fields of each
// structure set to appropriate values.
FLASH_Thread* thread = ( FLASH_Thread* ) FLA_malloc( n_threads * sizeof( FLASH_Thread ) );
// Initialize the thread structures array.
for ( i = 0; i < n_threads; i++ )
{
// Save the thread's identifier.
thread[i].id = i;
// Save the pointer to the necessary variables with the thread.
thread[i].args = arg;
// The pthread object, if it was even compiled into the FLASH_Thread
// structure, will be initialized by the pthread implementation when we
// call pthread_create() and does not need to be touched at this time.
}
// Determine which function to send threads to.
thread_entry_point = FLASH_Queue_exec_parallel_function;
#if FLA_MULTITHREADING_MODEL == FLA_OPENMP
// An OpenMP parallel for region spawns n_threads threads. Each thread
// executes the work function with a different FLASH_Thread argument.
// An implicit synchronization point exists at the end of the curly
// brace scope.
#pragma omp parallel for \
private( i ) \
shared( thread, n_threads, thread_entry_point ) \
schedule( static, 1 ) \
num_threads( n_threads )
for ( i = 0; i < n_threads; ++i )
{
thread_entry_point( ( void* ) &thread[i] );
}
#elif FLA_MULTITHREADING_MODEL == FLA_PTHREADS
// Create each POSIX thread needed in addition to the main thread.
for ( i = 1; i < n_threads; i++ )
{
integer pthread_e_val;
// Create thread i with default attributes.
pthread_e_val = pthread_create( &(thread[i].pthread_obj),
NULL,
thread_entry_point,
( void* ) &thread[i] );
#ifdef FLA_ENABLE_INTERNAL_ERROR_CHECKING
FLA_Error e_val = FLA_Check_pthread_create_result( pthread_e_val );
FLA_Check_error_code( e_val );
#endif
}
// The main thread is assigned the role of thread 0. Here we manually
// execute it as a worker thread.
thread_entry_point( ( void* ) &thread[0] );
// Wait for non-main threads to finish.
for ( i = 1; i < n_threads; i++ )
{
// These two variables are declared local to this for loop since this
// is the only place they are needed, and since they would show up as
// unused variables if FLA_MULTITHREADING_MODEL == FLA_PTHREADS.
// Strangely, the Intel compiler produces code that results in an
// "unaligned access" runtime message if thread_status is declared as
// an integer. Declaring it as a long or void* appears to force the
// compiler (not surprisingly) into aligning it to an 8-byte boundary.
integer pthread_e_val;
void* thread_status;
// Wait for thread i to invoke its respective pthread_exit().
// The return value passed to pthread_exit() is provided to us
// via status, if one was given.
pthread_e_val = pthread_join( thread[i].pthread_obj,
( void** ) &thread_status );
#ifdef FLA_ENABLE_INTERNAL_ERROR_CHECKING
FLA_Error e_val = FLA_Check_pthread_join_result( pthread_e_val );
FLA_Check_error_code( e_val );
#endif
}
#endif
FLA_free( thread );
return;
}
//#include <sched.h>
//#include <sys/types.h>
//#include <linux/unistd.h>
//#include <errno.h>
//#include <unistd.h>
//#include <sys/syscall.h>
void* FLASH_Queue_exec_parallel_function( void* arg )
/*----------------------------------------------------------------------------
FLASH_Queue_exec_parallel_function
----------------------------------------------------------------------------*/
{
FLASH_Queue_vars* args;
integer i;
integer queue;
integer cache;
integer n_tasks = FLASH_Queue_get_num_tasks();
integer n_threads = FLASH_Queue_get_num_threads();
integer n_cores = FLASH_Queue_get_cores_per_cache();
FLA_Bool caching = FLASH_Queue_get_caching();
FLA_Bool stealing = FLASH_Queue_get_work_stealing();
FLA_Bool committed = TRUE;
FLA_Bool condition = TRUE;
FLA_Bool enabled = FALSE;
FLA_Bool available;
FLASH_Task* t = NULL;
FLASH_Task* r = NULL;
FLASH_Thread* me;
//cpu_set_t cpu_set;
// Interpret the thread argument as what it really is--a pointer to an
// FLASH_Thread structure.
me = ( FLASH_Thread* ) arg;
// Extract the variables from the current thread.
args = ( FLASH_Queue_vars* ) me->args;
// Figure out the id of the current thread.
i = me->id;
// Set the CPU affinity; We want the current thread i to run only on CPU i.
//CPU_ZERO( &cpu_set );
//CPU_SET( i, &cpu_set );
//sched_setaffinity( syscall( __NR_gettid ), sizeof(cpu_set_t), &cpu_set );
// Determine to which queue this thread belongs.
queue = i / ( n_threads / args->n_queues );
// Determine to which cache this thread belongs.
cache = i / n_cores;
#ifdef FLA_ENABLE_GPU
// Create memory on GPU.
FLASH_Queue_create_gpu( i, ( void* ) args );
// Save whether GPUs are enabled.
enabled = FLASH_Queue_get_enabled_gpu();
// Only use each GPU as its own cache when GPUs are enabled.
if ( enabled )
cache = i;
#endif
// Prefetch blocks into the cache before execution.
if ( caching && !enabled && i % n_cores == 0 )
FLASH_Queue_prefetch( cache, ( void* ) args );
// Loop until all the tasks have committed.
while ( condition )
{
#ifdef FLA_ENABLE_GPU
// Check to see if any blocks on GPU need to be flushed.
FLASH_Queue_flush_gpu( i, ( void* ) args );
#endif
// Dequeue a task if there has not been one binded to thread.
if ( r == NULL )
{
FLA_Lock_acquire( &(args->run_lock[queue]) ); // R ***
// Obtain task to execute.
t = FLASH_Queue_wait_dequeue( queue, cache, ( void* ) args );
FLA_Lock_release( &(args->run_lock[queue]) ); // R ***
}
else
{
// Obtain the binded task.
t = r;
r = NULL;
}
// Dequeued a task from the waiting queue.
available = ( t != NULL );
if ( available )
{
// Save the thread and cache that executes the task.
t->thread = i;
t->cache = cache;
if ( caching && !enabled )
{
// Update the current state of the cache.
FLASH_Queue_update_cache( t, ( void* ) args );
}
#ifdef FLA_ENABLE_GPU
// Execute the task on GPU.
committed = FLASH_Queue_exec_gpu( t, ( void* ) args );
#else
// Execute the task.
FLASH_Queue_exec_task( t );
#endif
// If the task has executed or not.
if ( committed )
{
// Update task dependencies.
r = FLASH_Task_update_dependencies( t, ( void* ) args );
// Free the task once it executes in parallel.
FLASH_Task_free_parallel( t, ( void* ) args );
}
}
else
{
if ( stealing )
{
// Perform work stealing if there are no tasks to dequeue.
r = FLASH_Queue_work_stealing( queue, ( void* ) args );
}
}
FLA_Lock_acquire( &(args->all_lock) ); // A ***
// Increment program counter.
if ( available && committed )
args->pc++;
// Terminate loop.
if ( args->pc >= n_tasks )
condition = FALSE;
FLA_Lock_release( &(args->all_lock) ); // A ***
}
#ifdef FLA_ENABLE_GPU
// Destroy and flush contents of GPU back to main memory.
FLASH_Queue_destroy_gpu( i, ( void* ) args );
#endif
#if FLA_MULTITHREADING_MODEL == FLA_PTHREADS
// If this is a non-main thread, then exit with a zero (normal) error code.
// The main thread cannot call pthread_exit() because this routine never
// returns. The main thread must proceed so it can oversee the joining of
// the exited non-main pthreads.
if ( i != 0 )
pthread_exit( ( void* ) NULL );
#endif
return ( void* ) NULL;
}
FLASH_Task* FLASH_Task_update_dependencies( FLASH_Task* t, void* arg )
/*----------------------------------------------------------------------------
FLASH_Task_update_dependencies
----------------------------------------------------------------------------*/
{
FLASH_Queue_vars* args = ( FLASH_Queue_vars* ) arg;
integer i;
integer q = t->queue;
integer queue;
integer thread;
integer n_threads = FLASH_Queue_get_num_threads();
FLA_Bool caching = FLASH_Queue_get_caching();
FLA_Bool stealing = FLASH_Queue_get_work_stealing();
FLA_Bool available;
FLASH_Task* task;
FLASH_Task* r = NULL;
FLASH_Dep* d = t->dep_arg_head;
// Dequeue task to bind to thread if caching is enabled.
if ( caching )
{
FLA_Lock_acquire( &(args->run_lock[q]) ); // R ***
// Obtain task to execute.
r = FLASH_Queue_wait_dequeue( q, t->cache, arg );
FLA_Lock_release( &(args->run_lock[q]) ); // R ***
}
// Check each dependent task.
for ( i = 0; i < t->n_dep_args; i++ )
{
if ( stealing )
{
// Place all dependent tasks onto same queue as predecessor task.
d->task->queue = q;
}
task = d->task;
queue = task->queue;
thread = task->order % n_threads;
FLA_Lock_acquire( &(args->dep_lock[thread]) ); // D ***
task->n_ready--;
available = ( task->n_ready == 0 );
FLA_Lock_release( &(args->dep_lock[thread]) ); // D ***
// Place newly ready tasks on waiting queue.
if ( available )
{
// If caching is enabled and the task belongs to this thread's queue.
if ( caching && q == queue )
{
// Determine if there is a new binded task.
r = FLASH_Task_update_binding( task, r, arg );
}
else
{
FLA_Lock_acquire( &(args->run_lock[queue]) ); // R ***
FLASH_Queue_wait_enqueue( task, arg );
FLA_Lock_release( &(args->run_lock[queue]) ); // R ***
}
}
// Go to the next dep.
d = d->next_dep;
}
return r;
}
FLASH_Task* FLASH_Task_update_binding( FLASH_Task* t, FLASH_Task* r,
void* arg )
/*----------------------------------------------------------------------------
FLASH_Task_update_binding
----------------------------------------------------------------------------*/
{
FLASH_Queue_vars* args = ( FLASH_Queue_vars* ) arg;
integer queue;
if ( r == NULL )
{
// There are no tasks on waiting queue, so bind the first task.
r = t;
r->hit = TRUE;
}
else
{
// Swap the binded task for the new ready task.
if ( !r->hit || ( FLASH_Queue_get_sorting() && r->height < t->height ) )
{
queue = r->queue;
r->hit = FALSE;
FLA_Lock_acquire( &(args->run_lock[queue]) ); // R ***
// Place swapped task back onto waiting queue.
FLASH_Queue_wait_enqueue( r, arg );
FLA_Lock_release( &(args->run_lock[queue]) ); // R ***
// Bind the new ready task.
r = t;
r->hit = TRUE;
}
else // Keep the binded task and enqueue new ready task.
{
queue = t->queue;
FLA_Lock_acquire( &(args->run_lock[queue]) ); // R ***
FLASH_Queue_wait_enqueue( t, arg );
FLA_Lock_release( &(args->run_lock[queue]) ); // R ***
}
}
return r;
}
void FLASH_Task_free_parallel( FLASH_Task* t, void* arg )
/*----------------------------------------------------------------------------
FLASH_Task_free_parallel
----------------------------------------------------------------------------*/
{
FLASH_Queue_vars* args = ( FLASH_Queue_vars* ) arg;
integer i, j, k;
integer thread;
integer n_threads = FLASH_Queue_get_num_threads();
FLASH_Dep* d;
FLASH_Dep* next_dep;
FLA_Obj obj;
// Clearing the last write task in each output block.
for ( i = 0; i < t->n_output_args; i++ )
{
obj = t->output_arg[i];
// Macroblock is used.
if ( FLA_Obj_elemtype( obj ) == FLA_MATRIX )
{
dim_t jj, kk;
dim_t m = FLA_Obj_length( obj );
dim_t n = FLA_Obj_width( obj );
dim_t cs = FLA_Obj_col_stride( obj );
FLA_Obj* buf = FLASH_OBJ_PTR_AT( obj );
// Clear each block in macroblock.
for ( jj = 0; jj < n; jj++ )
for ( kk = 0; kk < m; kk++ )
( buf + jj * cs + kk )->base->write_task = NULL;
}
else // Clear regular block.
{
obj.base->write_task = NULL;
}
}
// Cleaning the last read tasks in each input block.
for ( i = 0; i < t->n_input_args; i++ )
{
obj = t->input_arg[i];
// Macroblock is used.
if ( FLA_Obj_elemtype( obj ) == FLA_MATRIX )
{
dim_t jj, kk;
dim_t m = FLA_Obj_length( obj );
dim_t n = FLA_Obj_width( obj );
dim_t cs = FLA_Obj_col_stride( obj );
FLA_Obj* buf = FLASH_OBJ_PTR_AT( obj );
// Clear each block in macroblock.
for ( jj = 0; jj < n; jj++ )
{
for ( kk = 0; kk < m; kk++ )
{
obj = *( buf + jj * cs + kk );
thread = obj.base->n_read_blocks % n_threads;
FLA_Lock_acquire( &(args->war_lock[thread]) ); // W ***
k = obj.base->n_read_tasks;
d = obj.base->read_task_head;
obj.base->n_read_tasks = 0;
obj.base->read_task_head = NULL;
obj.base->read_task_tail = NULL;
FLA_Lock_release( &(args->war_lock[thread]) ); // W ***
for ( j = 0; j < k; j++ )
{
next_dep = d->next_dep;
FLA_free( d );
d = next_dep;
}
}
}
}
else // Regular block.
{
thread = obj.base->n_read_blocks % n_threads;
FLA_Lock_acquire( &(args->war_lock[thread]) ); // W ***
k = obj.base->n_read_tasks;
d = obj.base->read_task_head;
obj.base->n_read_tasks = 0;
obj.base->read_task_head = NULL;
obj.base->read_task_tail = NULL;
FLA_Lock_release( &(args->war_lock[thread]) ); // W ***
for ( j = 0; j < k; j++ )
{
next_dep = d->next_dep;
FLA_free( d );
d = next_dep;
}
}
}
// Free the dep_arg field of t.
d = t->dep_arg_head;
for ( i = 0; i < t->n_dep_args; i++ )
{
next_dep = d->next_dep;
FLA_free( d );
d = next_dep;
}
// Free the int_arg field of t.
FLA_free( t->int_arg );
// Free the fla_arg field of t.
FLA_free( t->fla_arg );
// Free the input_arg field of t.
FLA_free( t->input_arg );
// Free the output_arg field of t.
FLA_free( t->output_arg );
// Finally, free the struct itself.
FLA_free( t );
return;
}
#endif
// ============================================================================
#ifndef FLA_ENABLE_MULTITHREADING
void FLASH_Queue_exec_simulation( void* arg )
/*----------------------------------------------------------------------------
FLASH_Queue_exec_simulation
----------------------------------------------------------------------------*/
{
FLASH_Queue_vars* args = ( FLASH_Queue_vars* ) arg;
integer i, j;
integer queue;
integer cache;
integer n_stages = 0;
integer n_queues = args->n_queues;
integer n_tasks = FLASH_Queue_get_num_tasks();
integer n_threads = FLASH_Queue_get_num_threads();
integer n_cores = FLASH_Queue_get_cores_per_cache();
FLASH_Verbose verbose = FLASH_Queue_get_verbose_output();
FLASH_Task* task;
FLASH_Task* t;
FLASH_Dep* d;
// An array to hold tasks to be executed during of simulation.
#ifdef FLA_ENABLE_WINDOWS_BUILD
FLASH_Task** exec_array = ( FLASH_Task** ) FLA_malloc( n_threads * sizeof( FLASH_Task* ) );
#else
FLASH_Task* exec_array[n_threads];
#endif
for ( i = 0; i < n_threads; i++ )
{
// Initialize all exec_array to NULL.
exec_array[i] = NULL;
// Prefetch blocks into the cache before execution.
if ( i % n_cores == 0 )
FLASH_Queue_prefetch( i, arg );
}
// Loop until all the tasks have committed.
while ( args->pc < n_tasks )
{
for ( i = 0; i < n_threads; i++ )
{
// Update waiting queue with ready tasks.
t = exec_array[i];
if ( t != NULL )
{
// Check each dependent task.
d = t->dep_arg_head;
for ( j = 0; j < t->n_dep_args; j++ )
{
task = d->task;
task->n_ready--;
// Place newly ready tasks on waiting queue.
if ( task->n_ready == 0 )
{
FLASH_Queue_wait_enqueue( task, arg );
}
// Go to the next dep.
d = d->next_dep;
}
// Free the task.
FLASH_Task_free( t );
}
}
n_stages++;
if ( !verbose )
printf( "%7d", n_stages );
// Move ready tasks from the waiting queue to execution queue.
for ( i = 0; i < n_threads; i++ )
{
// Determine to which queue this thread belongs.
queue = i / ( n_threads / n_queues );
// Determine to which cache this thread belongs.
cache = i / n_cores;
// Dequeue a task.
t = FLASH_Queue_wait_dequeue( queue, cache, arg );
// Save the task for execution.
exec_array[i] = t;
if ( t != NULL )
{
// Save the thread and cache that executes the task.
t->thread = i;
t->cache = cache;
// Increment program counter.
args->pc++;
}
}
// Execute independent tasks.
for ( i = 0; i < n_threads; i++ )
{
t = exec_array[i];
FLASH_Queue_update_cache( t, arg );
FLASH_Queue_exec_task( t );
if ( !verbose )
printf( "%7s", ( t == NULL ? " " : t->name ) );
// Free the task if this is the last stage.
if ( args->pc == n_tasks && t != NULL )
FLASH_Task_free( t );
}
if ( !verbose )
printf( "\n" );
}
if ( !verbose )
printf( "\n" );
#ifdef FLA_ENABLE_WINDOWS_BUILD
FLA_free( exec_array );
#endif
return;
}
#endif
#else // FLA_ENABLE_SCC
integer RCCE_acquire_lock(integer);
integer RCCE_release_lock(integer);
double RCCE_wtime(void);
integer RCCE_ue(void);
//This function needs to be defined in the driver
// or linked in some how by the user.
//It just just RCCE_barrier( &RCCE_COMM_WORLD ),
// but we can't implement it here because we're
// trying not to link in RCCE.h
void Synch_all();
typedef struct FLASH_Queue_variables
{
// Queue of all the tasks.
FLASH_Task** task_queue;
// The waiting queue of tasks for each thread.
integer* n_ready;
// The waiting queue of tasks for each thread.
integer* wait_queue;
// The number of tasks on waiting queue.
integer* n_wait;
// A global task counter that keeps track of how many tasks on the waiting
// queue have been processed.
integer* pc;
} FLASH_Queue_vars;
void FLASH_Queue_exec( void )
/*----------------------------------------------------------------------------
FLASH_Queue_exec
----------------------------------------------------------------------------*/
{
integer n_tasks = FLASH_Queue_get_num_tasks();
integer i;
double dtime;
// All the necessary variables for the SuperMatrix mechanism.
FLASH_Queue_vars args;
// If the queue is empty, return early.
if ( n_tasks == 0 )
return;
// Turn off all multiple queue implementations.
FLASH_Queue_set_data_affinity( FLASH_QUEUE_AFFINITY_NONE );
FLASH_Queue_set_work_stealing( FALSE );
// Do not use cache affinity yet.
FLASH_Queue_set_caching( FALSE );
// Allocate memory for task queues.
args.task_queue = ( FLASH_Task** ) FLA_malloc( n_tasks * sizeof( FLASH_Task* ) );
args.n_ready = ( integer* ) FLA_shmalloc( n_tasks * sizeof( integer ) );
args.wait_queue = ( integer* ) FLA_shmalloc( n_tasks * sizeof( integer ) );
args.n_wait = ( integer* ) FLA_shmalloc( sizeof( integer ) );
args.pc = ( integer* ) FLA_shmalloc( sizeof( integer ) );
// Initialize data.
if ( FLA_is_owner() )
{
args.n_wait[0] = 0;
args.pc[0] = 0;
}
Synch_all();
// Initialize tasks with critical information.
FLASH_Queue_init_tasks( ( void* ) &args );
// Display verbose output before free all tasks.
if ( FLASH_Queue_get_verbose_output() )
FLASH_Queue_verbose_output();
// Start timing the parallel execution.
dtime = RCCE_wtime();
FLASH_Queue_exec_parallel_function( ( void* ) &args );
// End timing the parallel execution.
dtime = RCCE_wtime() - dtime;
FLASH_Queue_set_parallel_time( dtime );
// Free all tasks sequentially.
for ( i = 0; i < n_tasks; i++ )
FLASH_Task_free( args.task_queue[i] );
// Free data.
FLA_free( args.task_queue );
FLA_shfree( args.n_ready );
FLA_shfree( args.wait_queue );
FLA_shfree( args.n_wait );
FLA_shfree( args.pc );
// Reset values for next call to FLASH_Queue_exec().
FLASH_Queue_reset();
return;
}
void FLASH_Queue_init_tasks( void* arg )
/*----------------------------------------------------------------------------
FLASH_Queue_init_tasks
----------------------------------------------------------------------------*/
{
FLASH_Queue_vars* args = ( FLASH_Queue_vars* ) arg;
integer i, j;
integer n_tasks = FLASH_Queue_get_num_tasks();
integer n_ready = 0;
integer height;
FLASH_Task* t;
FLASH_Dep* d;
// Grab the tail of the task queue.
t = FLASH_Queue_get_tail_task();
for ( i = n_tasks - 1; i >= 0; i-- )
{
// Save all the task pointers.
args->task_queue[i] = t;
// Only use a single queue implementation.
t->queue = 0;
// Determine the height of each task in the DAG.
height = 0;
d = t->dep_arg_head;
// Take the maximum height of dependent tasks.
for ( j = 0; j < t->n_dep_args; j++ )
{
height = max( height, d->task->height );
d = d->next_dep;
}
t->height = height + 1;
// Since freeing a task is always a leaf, we want to force it to execute
// earlier by giving it a greater height in order to reclaim memory.
if ( t->func == (void *) FLA_Obj_free_buffer_task )
t->height += n_tasks;
// Find all ready tasks.
t->n_ready += t->n_input_args + t->n_output_args +
t->n_macro_args + t->n_war_args;
if ( t->n_ready == 0 )
{
// Save the number of ready and available tasks.
n_ready++;
}
if ( FLA_is_owner() )
{
// Record all the ready values.
args->n_ready[i] = t->n_ready;
}
// Go to the previous task.
t = t->prev_task;
}
// Only allow the first core to enqueue the initial ready tasks.
if ( !FLA_is_owner() )
return;
// Grab the head of the task queue.
t = FLASH_Queue_get_head_task();
for ( i = 0; i < n_tasks && n_ready > 0; i++ )
{
if ( t->n_ready == 0 )
{
RCCE_acquire_lock( 0 );
// Enqueue all the ready and available tasks.
FLASH_Queue_wait_enqueue( t, arg );
RCCE_release_lock( 0 );
// Decrement the number of ready tasks left to be enqueued.
n_ready--;
}
// Go to the next task.
t = t->next_task;
}
return;
}
void FLASH_Queue_wait_enqueue( FLASH_Task* t, void* arg )
/*----------------------------------------------------------------------------
FLASH_Queue_wait_enqueue
----------------------------------------------------------------------------*/
{
FLASH_Queue_vars* args = ( FLASH_Queue_vars* ) arg;
integer i = args->n_wait[0] + args->pc[0];
// Insertion sort of tasks in waiting queue.
if ( FLASH_Queue_get_sorting() )
{
for ( ; i > args->pc[0]; i-- )
{
if ( args->task_queue[args->wait_queue[i-1]]->height >
args->task_queue[t->order]->height )
break;
args->wait_queue[i] = args->wait_queue[i-1];
}
}
args->wait_queue[i] = t->order;
// Increment number of tasks on waiting queue.
args->n_wait[0]++;
return;
}
FLASH_Task* FLASH_Queue_wait_dequeue( integer queue, integer cache, void* arg )
/*----------------------------------------------------------------------------
FLASH_Queue_wait_dequeue
----------------------------------------------------------------------------*/
{
FLASH_Queue_vars* args = ( FLASH_Queue_vars* ) arg;
FLASH_Task* t = NULL;
if ( args->n_wait[0] > 0 )
{
// Grab the head of the queue.
t = args->task_queue[args->wait_queue[args->pc[0]]];
// Decrement number of tasks on waiting queue.
args->n_wait[0]--;
// Increment the program counter.
args->pc[0]++;
}
return t;
}
void* FLASH_Queue_exec_parallel_function( void* arg )
/*----------------------------------------------------------------------------
FLASH_Queue_exec_parallel_function
----------------------------------------------------------------------------*/
{
FLASH_Queue_vars* args = ( FLASH_Queue_vars* ) arg;
integer i = RCCE_ue();
integer queue = 0;
integer cache = 0;
integer n_tasks = FLASH_Queue_get_num_tasks();
integer n_threads = FLASH_Queue_get_num_threads();
FLA_Bool condition;
FLA_Bool available;
FLASH_Task* t = NULL;
// Do not let extraneous cores execute.
if ( i < n_threads )
condition = TRUE;
else
condition = FALSE;
// Loop until all the tasks have committed.
while ( condition )
{
RCCE_acquire_lock( 0 );
// Obtain task to execute.
t = FLASH_Queue_wait_dequeue( queue, cache, ( void* ) args );
RCCE_release_lock( 0 );
// Dequeued a task from the waiting queue.
available = ( t != NULL );
if ( available )
{
// Save the thread and cache that executes the task.
t->thread = i;
t->cache = cache;
// Execute the task.
FLASH_Queue_exec_task( t );
// Update task dependencies.
FLASH_Task_update_dependencies( t, ( void* ) args );
}
RCCE_acquire_lock( 0 );
// Terminate loop.
if ( args->pc[0] >= n_tasks )
condition = FALSE;
RCCE_release_lock( 0 );
}
return ( void* ) NULL;
}
FLASH_Task* FLASH_Task_update_dependencies( FLASH_Task* t, void* arg )
/*----------------------------------------------------------------------------
FLASH_Task_update_dependencies
----------------------------------------------------------------------------*/
{
FLASH_Queue_vars* args = ( FLASH_Queue_vars* ) arg;
integer i;
integer n_threads = FLASH_Queue_get_num_threads();
integer thread;
FLA_Bool available;
FLASH_Task* task;
FLASH_Task* r = NULL;
FLASH_Dep* d = t->dep_arg_head;
// Check each dependent task.
for ( i = 0; i < t->n_dep_args; i++ )
{
task = d->task;
// Use the remaining locks except for the first one.
thread = ( n_threads > 1 ? task->order % ( n_threads - 1 ) + 1 : 0 );
RCCE_acquire_lock( thread );
args->n_ready[task->order]--;
available = ( args->n_ready[task->order] == 0 );
RCCE_release_lock( thread );
// Place newly ready tasks on waiting queue.
if ( available )
{
RCCE_acquire_lock( 0 );
FLASH_Queue_wait_enqueue( task, arg );
RCCE_release_lock( 0 );
}
// Go to the next dep.
d = d->next_dep;
}
return r;
}
#endif // FLA_ENABLE_SCC
#endif // FLA_ENABLE_SUPERMATRIX
|
Reconstruction3D.h
|
/*
* 3DReconstruction.h
*
* Created on: Oct 25, 2015
* Author: nicolasrosa
*/
#ifndef RECONSTRUCTION_3D_H
#define RECONSTRUCTION_3D_H
/* Libraries */
#include "opencv2/opencv.hpp"
//TODO: Arrumar Bibliotecas
//#include <pcl/common/common_headers.h>
//#include <pcl/io/pcd_io.h>
//#include <pcl/visualization/pcl_visualizer.h>
//#include <boost/thread/thread.hpp>
using namespace cv;
using namespace std;
class Reconstruction3D{
public:
/* Constructor and Destructor */
Reconstruction3D();
~Reconstruction3D();
void setViewPoint(double x,double y,double z);
void setLookAtPoint(double x,double y,double z);
void PointCloudInit(double baseline,bool isSub);
/* 3D Reconstruction Functions */
void eular2rot(double yaw,double pitch, double roll,Mat& dest);
void lookat(Point3d from, Point3d to, Mat& destR);
void projectImagefromXYZ(Mat &image, Mat &destimage, Mat &disp, Mat &destdisp, Mat &xyz, Mat &R, Mat &t, Mat &K, Mat &dist, bool isSub);
void fillOcclusion(Mat& src, int invalidvalue, bool isInv);
/* Templates Declaration */
template <class T>
static void projectImagefromXYZ_(Mat& image, Mat& destimage, Mat& disp, Mat& destdisp, Mat& xyz, Mat& R, Mat& t, Mat& K, Mat& dist, Mat& mask, bool isSub){
if(destimage.empty())destimage=Mat::zeros(Size(image.size()),image.type());
if(destdisp.empty())destdisp=Mat::zeros(Size(image.size()),disp.type());
vector<Point2f> pt;
if(dist.empty()) dist = Mat::zeros(Size(5,1),CV_32F);
cv::projectPoints(xyz,R,t,K,dist,pt);
destimage.setTo(0);
destdisp.setTo(0);
//#pragma omp parallel for
for(int j=1;j<image.rows-1;j++){
int count=j*image.cols;
uchar* img=image.ptr<uchar>(j);
uchar* m=mask.ptr<uchar>(j);
for(int i=0;i<image.cols;i++,count++){
int x=(int)(pt[count].x+0.5);
int y=(int)(pt[count].y+0.5);
if(m[i]==255)continue;
if(pt[count].x>=1 && pt[count].x<image.cols-1 && pt[count].y>=1 && pt[count].y<image.rows-1){
short v=destdisp.at<T>(y,x);
if(v<disp.at<T>(j,i)){
destimage.at<uchar>(y,3*x+0)=img[3*i+0];
destimage.at<uchar>(y,3*x+1)=img[3*i+1];
destimage.at<uchar>(y,3*x+2)=img[3*i+2];
destdisp.at<T>(y,x)=disp.at<T>(j,i);
if(isSub){
if((int)pt[count+image.cols].y-y>1 && (int)pt[count+1].x-x>1){
destimage.at<uchar>(y,3*x+3)=img[3*i+0];
destimage.at<uchar>(y,3*x+4)=img[3*i+1];
destimage.at<uchar>(y,3*x+5)=img[3*i+2];
destimage.at<uchar>(y+1,3*x+0)=img[3*i+0];
destimage.at<uchar>(y+1,3*x+1)=img[3*i+1];
destimage.at<uchar>(y+1,3*x+2)=img[3*i+2];
destimage.at<uchar>(y+1,3*x+3)=img[3*i+0];
destimage.at<uchar>(y+1,3*x+4)=img[3*i+1];
destimage.at<uchar>(y+1,3*x+5)=img[3*i+2];
destdisp.at<T>(y,x+1)=disp.at<T>(j,i);
destdisp.at<T>(y+1,x)=disp.at<T>(j,i);
destdisp.at<T>(y+1,x+1)=disp.at<T>(j,i);
}
else if((int)pt[count-image.cols].y-y<-1 && (int)pt[count-1].x-x<-1){
destimage.at<uchar>(y,3*x-3)=img[3*i+0];
destimage.at<uchar>(y,3*x-2)=img[3*i+1];
destimage.at<uchar>(y,3*x-1)=img[3*i+2];
destimage.at<uchar>(y-1,3*x+0)=img[3*i+0];
destimage.at<uchar>(y-1,3*x+1)=img[3*i+1];
destimage.at<uchar>(y-1,3*x+2)=img[3*i+2];
destimage.at<uchar>(y-1,3*x-3)=img[3*i+0];
destimage.at<uchar>(y-1,3*x-2)=img[3*i+1];
destimage.at<uchar>(y-1,3*x-1)=img[3*i+2];
destdisp.at<T>(y,x-1)=disp.at<T>(j,i);
destdisp.at<T>(y-1,x)=disp.at<T>(j,i);
destdisp.at<T>(y-1,x-1)=disp.at<T>(j,i);
}
else if((int)pt[count+1].x-x>1){
destimage.at<uchar>(y,3*x+3)=img[3*i+0];
destimage.at<uchar>(y,3*x+4)=img[3*i+1];
destimage.at<uchar>(y,3*x+5)=img[3*i+2];
destdisp.at<T>(y,x+1)=disp.at<T>(j,i);
}
else if((int)pt[count-1].x-x<-1){
destimage.at<uchar>(y,3*x-3)=img[3*i+0];
destimage.at<uchar>(y,3*x-2)=img[3*i+1];
destimage.at<uchar>(y,3*x-1)=img[3*i+2];
destdisp.at<T>(y,x-1)=disp.at<T>(j,i);
}
else if((int)pt[count+image.cols].y-y>1){
destimage.at<uchar>(y+1,3*x+0)=img[3*i+0];
destimage.at<uchar>(y+1,3*x+1)=img[3*i+1];
destimage.at<uchar>(y+1,3*x+2)=img[3*i+2];
destdisp.at<T>(y+1,x)=disp.at<T>(j,i);
}
else if((int)pt[count-image.cols].y-y<-1){
destimage.at<uchar>(y-1,3*x+0)=img[3*i+0];
destimage.at<uchar>(y-1,3*x+1)=img[3*i+1];
destimage.at<uchar>(y-1,3*x+2)=img[3*i+2];
destdisp.at<T>(y-1,x)=disp.at<T>(j,i);
}
}
}
}
}
}
if(isSub)
{
Mat image2;
Mat disp2;
destimage.copyTo(image2);
destdisp.copyTo(disp2);
const int BS=1;
//#pragma omp parallel for
for(int j=BS;j<image.rows-BS;j++){
uchar* img=destimage.ptr<uchar>(j);
T* m = disp2.ptr<T>(j);
T* dp = destdisp.ptr<T>(j);
for(int i=BS;i<image.cols-BS;i++){
if(m[i]==0){
int count=0;
int d=0;
int r=0;
int g=0;
int b=0;
for(int l=-BS;l<=BS;l++){
T* dp2 = disp2.ptr<T>(j+l);
uchar* imageR = image2.ptr<uchar>(j+l);
for(int k=-BS;k<=BS;k++){
if(dp2[i+k]!=0){
count++;
d+=dp2[i+k];
r+=imageR[3*(i+k)+0];
g+=imageR[3*(i+k)+1];
b+=imageR[3*(i+k)+2];
}
}
}
if(count!=0){
double div = 1.0/count;
dp[i]=d*div;
img[3*i+0]=r*div;
img[3*i+1]=g*div;
img[3*i+2]=b*div;
}
}
}
}
}
}
template <class T>
static void fillOcclusion_(Mat& src, T invalidvalue){
int bb=1;
const int MAX_LENGTH=src.cols*0.5;
//#pragma omp parallel for
for(int j=bb;j<src.rows-bb;j++){
T* s = src.ptr<T>(j);
//const T st = s[0];
//const T ed = s[src.cols-1];
s[0]=255;
s[src.cols-1]=255;
for(int i=0;i<src.cols;i++){
if(s[i]<=invalidvalue){
int t=i;
do{
t++;
if(t>src.cols-1)break;
}while(s[t]<=invalidvalue);
const T dd = min(s[i-1],s[t]);
if(t-i>MAX_LENGTH){
for(int n=0;n<src.cols;n++){
s[n]=invalidvalue;
}
}
else{
for(;i<t;i++){
s[i]=dd;
}
}
}
}
}
}
template <class T>
static void fillOcclusionInv_(Mat& src, T invalidvalue){
int bb=1;
const int MAX_LENGTH=src.cols*0.8;
//#pragma omp parallel for
for(int j=bb;j<src.rows-bb;j++){
T* s = src.ptr<T>(j);
//const T st = s[0];
//const T ed = s[src.cols-1];
s[0]=0;
s[src.cols-1]=0;
for(int i=0;i<src.cols;i++){
if(s[i]==invalidvalue){
int t=i;
do{
t++;
if(t>src.cols-1)break;
}while(s[t]==invalidvalue);
const T dd = max(s[i-1],s[t]);
if(t-i>MAX_LENGTH){
for(int n=0;n<src.cols;n++){
s[n]=invalidvalue;
}
}
else{
for(;i<t;i++){
s[i]=dd;
}
}
}
}
}
}
/* Results */
Mat disp3Dviewer;
Mat disp3D;
Mat disp3D_8U;
Mat disp3D_BGR;
Point3d viewpoint;
Point3d lookatpoint;
Mat dist;
Mat Rotation;
Mat t;
Mat xyz;
Mat depth;
double step;
bool isSub;
};
#endif // RECONSTRUCTION_3D_H
|
hierarchical_sne_inl.h
|
/*
*
* Copyright (c) 2014, Nicola Pezzotti (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 NICOLA PEZZOTTI ''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 NICOLA PEZZOTTI 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 HIERARCHICAL_SNE_INL
#define HIERARCHICAL_SNE_INL
#if defined(_OPENMP)
#include <omp.h>
#endif
#include "hdi/dimensionality_reduction/hierarchical_sne.h"
#include "hdi/utils/math_utils.h"
#include "hdi/utils/log_helper_functions.h"
#include "hdi/utils/scoped_timers.h"
#include <random>
#include <chrono>
#include <unordered_set>
#include <unordered_map>
#include <numeric>
#include "hdi/utils/memory_utils.h"
#include "hdi/data/map_mem_eff.h"
#include "hdi/data/map_helpers.h"
#include "hdi/data/io.h"
#include "hdi/utils/log_progress.h"
#ifdef HNSWLIB_FOUND
#ifdef _MSC_VER
#if(_MSC_VER >= 1900)
#include "hnswlib/hnswlib.h"
#include "hnswlib/space_l2.h"
#define HNSWLIB_SUPPORTED
#endif //(_MSC_VER >= 1900)
#else // _MSC_VER
#if (__cplusplus >=201103)
#include "hnswlib/hnswlib.h"
#include "hnswlib/space_l2.h"
#define HNSWLIB_SUPPORTED
#endif //(__cplusplus >=201103)
#endif // _MSC_VER
#endif //HNSWLIB_FOUND
#ifdef __USE_ANNOY__
#ifndef WIN32
#define isnan std::isnan
#endif
#include "annoylib.h"
#include "kissrandom.h"
#ifndef WIN32
#undef isnan
#endif
#endif // __USE_ANNOY__
#pragma warning( push )
#pragma warning( disable : 4267)
#pragma warning( push )
#pragma warning( disable : 4291)
#pragma warning( push )
#pragma warning( disable : 4996)
#pragma warning( push )
#pragma warning( disable : 4018)
#pragma warning( push )
#pragma warning( disable : 4244)
#pragma warning( pop )
#pragma warning( pop )
#pragma warning( pop )
#pragma warning( pop )
#pragma warning( pop )
namespace hdi {
namespace dr {
/////////////////////////////////////////////////////////////////////////
template <typename scalar_type, typename sparse_scalar_matrix_type>
HierarchicalSNE<scalar_type, sparse_scalar_matrix_type>::Parameters::Parameters() :
_seed(-1),
_num_neighbors(30),
_aknn_num_trees(4),
_aknn_num_checks(1024),
_aknn_algorithm(hdi::dr::KNN_ANNOY),
_aknn_metric(hdi::dr::KNN_METRIC_EUCLIDEAN),
_aknn_algorithmP1(16), // default parameter for HNSW
_aknn_algorithmP2(200), // default parameter for HNSW
_monte_carlo_sampling(true),
_mcmcs_num_walks(10),
_mcmcs_landmark_thresh(1.5),
_mcmcs_walk_length(10),
_hard_cut_off(false),
_hard_cut_off_percentage(0.1f),
_rs_reduction_factor_per_layer{ static_cast<scalar_type>(.1) },
_rs_outliers_removal_jumps(10),
_num_walks_per_landmark(100),
_transition_matrix_prune_thresh(1.5),
_out_of_core_computation(false)
{}
/////////////////////////////////////////////////////////////////////////
template <typename scalar_type, typename sparse_scalar_matrix_type>
HierarchicalSNE<scalar_type, sparse_scalar_matrix_type>::Statistics::Statistics() :
_total_time(-1),
_init_knn_time(-1),
_init_probabilities_time(-1),
_init_fmc_time(-1),
_mcmc_sampling_time(-1),
_landmarks_selection_time(-1),
_landmarks_selection_num_walks(-1),
_aoi_time(-1),
_fmc_time(-1),
_aoi_num_walks(-1),
_aoi_sparsity(-1),
_fmc_sparsity(-1),
_fmc_effective_sparsity(-1)
{}
template <typename scalar_type, typename sparse_scalar_matrix_type>
void HierarchicalSNE<scalar_type, sparse_scalar_matrix_type>::Statistics::reset() {
_total_time = -1;
_init_knn_time = -1;
_init_probabilities_time = -1;
_init_fmc_time = -1;
_mcmc_sampling_time = -1;
_landmarks_selection_time = -1;
_landmarks_selection_num_walks = -1;
_aoi_time = -1;
_fmc_time = -1;
_aoi_num_walks = -1;
_aoi_sparsity = -1;
_fmc_sparsity = -1;
_fmc_effective_sparsity = -1;
}
template <typename scalar_type, typename sparse_scalar_matrix_type>
void HierarchicalSNE<scalar_type, sparse_scalar_matrix_type>::Statistics::log(utils::AbstractLog* logger)const {
utils::secureLog(logger, "\n--------------- Hierarchical-SNE Statistics ------------------");
utils::secureLogValue(logger, "Total time", _total_time);
if (_init_knn_time != -1) { utils::secureLogValue(logger, "\tAKNN graph computation time", _init_knn_time, true, 2); }
if (_init_probabilities_time != -1) { utils::secureLogValue(logger, "\tTransition probabilities computation time", _init_probabilities_time, true, 1); }
if (_init_fmc_time != -1) { utils::secureLogValue(logger, "\tFMC computation time", _init_fmc_time, true, 3); }
if (_mcmc_sampling_time != -1) { utils::secureLogValue(logger, "\tMarkov Chain Monte Carlo sampling time", _mcmc_sampling_time, true, 1); }
if (_landmarks_selection_time != -1) { utils::secureLogValue(logger, "\tLandmark selection time", _landmarks_selection_time, true, 2); }
if (_landmarks_selection_num_walks != -1) { utils::secureLogValue(logger, "\tLndks Slct #walks", _landmarks_selection_num_walks, true, 3); }
if (_aoi_time != -1) { utils::secureLogValue(logger, "\tArea of Influence computation time", _aoi_time, true, 1); }
if (_fmc_time != -1) { utils::secureLogValue(logger, "\tFMC computation time", _fmc_time, true, 3); }
if (_aoi_num_walks != -1) { utils::secureLogValue(logger, "\tAoI #walks", _aoi_num_walks, true, 4); }
if (_aoi_sparsity != -1) { utils::secureLogValue(logger, "\tIs sparsity (%)", _aoi_sparsity * 100, true, 3); }
if (_fmc_sparsity != -1) { utils::secureLogValue(logger, "\tTs sparsity (%)", _fmc_sparsity * 100, true, 3); }
if (_fmc_effective_sparsity != -1) { utils::secureLogValue(logger, "\tTs effective sparsity (%)", _fmc_effective_sparsity * 100, true, 2); }
utils::secureLog(logger, "--------------------------------------------------------------\n");
}
/////////////////////////////////////////////////////////////////////////
template <typename scalar_type, typename sparse_scalar_matrix_type>
scalar_type HierarchicalSNE<scalar_type, sparse_scalar_matrix_type>::Scale::mimMemoryOccupation()const {
scalar_type mem(0);
mem += _landmark_to_original_data_idx.capacity() * sizeof(unsigned_int_type);
mem += _landmark_to_previous_scale_idx.capacity() * sizeof(unsigned_int_type);
mem += _landmark_weight.capacity() * sizeof(scalar_type);
for (int i = 0; i < _transition_matrix.size(); ++i) {
mem += _transition_matrix[i].size()*(sizeof(unsigned_int_type) + sizeof(scalar_type));
}
mem += _previous_scale_to_landmark_idx.capacity() * sizeof(int_type);
for (int i = 0; i < _area_of_influence.size(); ++i) {
mem += _area_of_influence[i].size()*(sizeof(unsigned_int_type) + sizeof(scalar_type));
}
return mem / 1024 / 1024;
}
/////////////////////////////////////////////////////////////////////////
template <typename scalar_type, typename sparse_scalar_matrix_type>
HierarchicalSNE<scalar_type, sparse_scalar_matrix_type>::HierarchicalSNE() :
_initialized(false),
_dimensionality(0),
_logger(nullptr),
_high_dimensional_data(nullptr),
_verbose(false)
{
}
template <typename scalar_type, typename sparse_scalar_matrix_type>
void HierarchicalSNE<scalar_type, sparse_scalar_matrix_type>::reset() {
_initialized = false;
}
template <typename scalar_type, typename sparse_scalar_matrix_type>
void HierarchicalSNE<scalar_type, sparse_scalar_matrix_type>::clear() {
_high_dimensional_data = nullptr;
_initialized = false;
}
template <typename scalar_type, typename sparse_scalar_matrix_type>
void HierarchicalSNE<scalar_type, sparse_scalar_matrix_type>::getHighDimensionalDescriptor(scalar_vector_type& data_point, data_handle_type handle)const {
data_point.resize(_dimensionality);
for (unsigned_int_type i = 0; i < _dimensionality; ++i) {
data_point[i] = *(_high_dimensional_data + handle * _dimensionality + i);
}
}
/////////////////////////////////////////////////////////////////////////
template <typename scalar_type, typename sparse_scalar_matrix_type>
void HierarchicalSNE<scalar_type, sparse_scalar_matrix_type>::initialize(scalar_type* high_dimensional_data, unsigned_int_type num_dps, Parameters params) {
_statistics.reset();
utils::ScopedTimer<scalar_type, utils::Seconds> timer(_statistics._total_time);
utils::secureLog(_logger, "Initializing Hierarchical-SNE...");
_params = params;
_high_dimensional_data = high_dimensional_data;
_num_dps = num_dps;
utils::secureLogValue(_logger, "Number of data points", _num_dps);
initializeFirstScale();
_initialized = true;
utils::secureLog(_logger, "Initialization complete!");
}
template <typename scalar_type, typename sparse_scalar_matrix_type>
void HierarchicalSNE<scalar_type, sparse_scalar_matrix_type>::initialize(const sparse_scalar_matrix_type& similarities, Parameters params) {
_statistics.reset();
utils::ScopedTimer<scalar_type, utils::Seconds> timer(_statistics._total_time);
utils::secureLog(_logger, "Initializing Hierarchical-SNE...");
_params = params;
_high_dimensional_data = nullptr;
_num_dps = similarities.size();
utils::secureLogValue(_logger, "Number of data points", _num_dps);
initializeFirstScale(similarities);
_initialized = true;
utils::secureLog(_logger, "Initialization complete!");
}
template <typename scalar_type, typename sparse_scalar_matrix_type>
bool HierarchicalSNE<scalar_type, sparse_scalar_matrix_type>::addScale() {
_statistics.reset();
utils::ScopedTimer<scalar_type, utils::Seconds> timer(_statistics._total_time);
bool res(true);
if (_params._out_of_core_computation) {
addScaleOutOfCoreImpl();
}
else {
addScaleImpl();
}
_statistics.log(_logger);
return res;
}
template <typename scalar_type, typename sparse_scalar_matrix_type>
void HierarchicalSNE<scalar_type, sparse_scalar_matrix_type>::computeNeighborhoodGraph(scalar_vector_type& distance_based_probabilities, std::vector<int>& neighborhood_graph) {
unsigned_int_type nn = _params._num_neighbors + 1;
scalar_type perplexity = _params._num_neighbors / 3.;
neighborhood_graph.resize(_num_dps*nn);
distance_based_probabilities.resize(_num_dps*nn);
// Fallback to ANNOY if others are not supported
#ifndef HNSWLIB_SUPPORTED
if (_params._aknn_algorithm == hdi::dr::KNN_HNSW)
{
hdi::utils::secureLog(_logger, "HNSW not available, falling back to ANNOY");
_params._aknn_algorithm = hdi::dr::KNN_ANNOY;
}
#endif // HNSWLIB_SUPPORTED
#ifndef __USE_ANNOY__
if (_params._aknn_algorithm == hdi::dr::KNN_ANNOY)
{
_params._aknn_algorithm = hdi::dr::KNN_HNSW;
}
#endif // __USE_ANNOY__
if (_params._aknn_algorithm == hdi::dr::KNN_HNSW)
{
#ifdef HNSWLIB_SUPPORTED
utils::secureLog(_logger, "Computing the neighborhood graph with HNSW Lib...");
hnswlib::SpaceInterface<float> *space = NULL;
switch (_params._aknn_metric) {
case hdi::dr::KNN_METRIC_EUCLIDEAN:
space = new hnswlib::L2Space(_dimensionality);
break;
case hdi::dr::KNN_METRIC_INNER_PRODUCT:
space = new hnswlib::InnerProductSpace(_dimensionality);
break;
default:
space = new hnswlib::L2Space(_dimensionality);
break;
}
hnswlib::HierarchicalNSW<scalar_type> appr_alg(space, _num_dps, _params._aknn_algorithmP1, _params._aknn_algorithmP2, 0);
utils::secureLog(_logger, "\tBuilding the trees...");
utils::ScopedTimer<scalar_type, utils::Seconds> timer(_statistics._init_knn_time);
appr_alg.addPoint((void*)_high_dimensional_data, (std::size_t) 0);
unsigned num_threads = std::thread::hardware_concurrency();
hnswlib::ParallelFor(1, _num_dps, num_threads, [&](size_t i, size_t threadId) {
appr_alg.addPoint((void*)(_high_dimensional_data + (i * _dimensionality)), (hnswlib::labeltype) i);
});
utils::secureLog(_logger, "\tAKNN queries...");
// #pragma omp parallel for
for (int i = 0; i < _num_dps; ++i)
{
auto top_candidates = appr_alg.searchKnn(_high_dimensional_data + (i*_dimensionality), (hnswlib::labeltype)nn);
scalar_type *distances = distance_based_probabilities.data() + (i*nn);
int *indices = neighborhood_graph.data() + (i*nn);
int j = 0;
assert(top_candidates.size() == nn);
while (top_candidates.size() > 0)
{
auto rez = top_candidates.top();
distances[nn - j - 1] = rez.first;
indices[nn - j - 1] = rez.second;
top_candidates.pop();
++j;
}
}
#endif // HNSWLIB_SUPPORTED
}
else if (_params._aknn_algorithm == hdi::dr::KNN_ANNOY)
{
#ifdef __USE_ANNOY__
hdi::utils::secureLog(_logger, "Computing approximated knn with Annoy...");
int search_k = nn * _params._aknn_num_trees;
AnnoyIndexInterface<int, double>* tree = NULL;
switch (_params._aknn_metric) {
case hdi::dr::KNN_METRIC_EUCLIDEAN:
hdi::utils::secureLog(_logger, "Computing approximated knn with Annoy using Euclidean distances ...");
tree = new AnnoyIndex<int, double, Euclidean, Kiss32Random, AnnoyIndexSingleThreadedBuildPolicy>(_dimensionality);
break;
case hdi::dr::KNN_METRIC_COSINE:
hdi::utils::secureLog(_logger, "Computing approximated knn with Annoy using Cosine distances ...");
tree = new AnnoyIndex<int, double, Angular, Kiss32Random, AnnoyIndexSingleThreadedBuildPolicy>(_dimensionality);
break;
case hdi::dr::KNN_METRIC_MANHATTAN:
hdi::utils::secureLog(_logger, "Computing approximated knn with Annoy using Manhattan distances ...");
tree = new AnnoyIndex<int, double, Manhattan, Kiss32Random, AnnoyIndexSingleThreadedBuildPolicy>(_dimensionality);
break;
//case hdi::dr::KNN_METRIC_HAMMING:
// hdi::utils::secureLog(_logger, "Computing approximated knn with Annoy using Euclidean distances ...");
// tree = new AnnoyIndex<int, double, Hamming, Kiss32Random>(num_dim);
// break;
case hdi::dr::KNN_METRIC_DOT:
hdi::utils::secureLog(_logger, "Computing approximated knn with Annoy using Dot product distances ...");
tree = new AnnoyIndex<int, double, DotProduct, Kiss32Random, AnnoyIndexSingleThreadedBuildPolicy>(_dimensionality);
break;
default:
hdi::utils::secureLog(_logger, "Computing approximated knn with Annoy using Euclidean distances ...");
tree = new AnnoyIndex<int, double, Euclidean, Kiss32Random, AnnoyIndexSingleThreadedBuildPolicy>(_dimensionality);
break;
}
{
utils::ScopedTimer<scalar_type, utils::Seconds> timer(_statistics._init_knn_time);
for (int i = 0; i < _num_dps; ++i) {
double* vec = new double[_dimensionality];
for (int z = 0; z < _dimensionality; ++z) {
vec[z] = _high_dimensional_data[i * _dimensionality + z];
}
tree->add_item(i, vec);
}
tree->build(_params._aknn_num_trees);
// Sample check if it returns enough neighbors
std::vector<int> closest;
std::vector<double> closest_distances;
for (int n = 0; n < 100; n++) {
tree->get_nns_by_item(n, nn, search_k, &closest, &closest_distances);
unsigned int neighbors_count = closest.size();
if (neighbors_count < nn) {
printf("Requesting %d neighbors, but ANNOY returned only %u. Please increase search_k\n", nn, neighbors_count);
return;
}
}
hdi::utils::secureLog(_logger, "Done building tree. Beginning nearest neighbor search... ");
#pragma omp parallel for
for (int n = 0; n < _num_dps; n++)
{
// Find nearest neighbors
std::vector<int> closest;
std::vector<double> closest_distances;
tree->get_nns_by_item(n, nn, search_k, &closest, &closest_distances);
// Copy current row
for (unsigned int m = 0; m < nn; m++) {
neighborhood_graph[n * nn + m] = closest[m];
distance_based_probabilities[n * nn + m] = closest_distances[m] * closest_distances[m];
}
}
}
delete tree;
#endif // __USE_ANNOY__
}
{
utils::secureLog(_logger, "\tFMC computation...");
utils::ScopedTimer<scalar_type, utils::Seconds> timer(_statistics._init_probabilities_time);
//#ifdef __USE_GCD__
// std::cout << "GCD dispatch, hierarchical_sne_inl 253.\n";
// dispatch_apply(_num_dps, dispatch_get_global_queue(0, 0), ^(size_t d) {
//#else
#pragma omp parallel for
for (int_type d = 0; d < _num_dps; ++d) {
//#endif //__USE_GCD__
//It could be that the point itself is not the nearest one if two points are identical... I want the point itself to be the first one!
if (neighborhood_graph[d*nn] != d) {
int to_swap = d * nn;
for (; to_swap < d*nn + (nn-1); ++to_swap) {
if (neighborhood_graph[to_swap] == d)
break;
}
std::swap(neighborhood_graph[nn*d], neighborhood_graph[to_swap]);
std::swap(distance_based_probabilities[nn*d], distance_based_probabilities[to_swap]);
}
scalar_vector_type temp_probability(nn, 0);
utils::computeGaussianDistributionWithFixedPerplexity<scalar_vector_type>(
distance_based_probabilities.cbegin() + d * nn,
distance_based_probabilities.cbegin() + (d + 1)*nn,
temp_probability.begin(),
temp_probability.begin() + nn,
perplexity,
200,
1e-5,
0
);
distance_based_probabilities[d*nn] = 0;
for (unsigned_int_type n = 1; n < nn; ++n) {
distance_based_probabilities[d*nn + n] = temp_probability[n];
}
}
//#ifdef __USE_GCD__
// );
//#endif
}
}
template <typename scalar_type, typename sparse_scalar_matrix_type>
void HierarchicalSNE<scalar_type, sparse_scalar_matrix_type>::initializeFirstScale() {
utils::secureLog(_logger, "Initializing the first scale...");
_hierarchy.clear();
_hierarchy.push_back(Scale());
Scale& scale = _hierarchy[0];
scalar_vector_type distance_based_probabilities;
std::vector<int> neighborhood_graph;
computeNeighborhoodGraph(distance_based_probabilities, neighborhood_graph);
unsigned_int_type nn = _params._num_neighbors + 1;
{
utils::ScopedTimer<scalar_type, utils::Seconds> timer(_statistics._init_fmc_time);
utils::secureLog(_logger, "Creating transition matrix...");
scale._landmark_to_original_data_idx.resize(_num_dps);
std::iota(scale._landmark_to_original_data_idx.begin(), scale._landmark_to_original_data_idx.end(), 0);
scale._landmark_to_previous_scale_idx = scale._landmark_to_original_data_idx;
scale._landmark_weight.resize(_num_dps, 1);
scale._transition_matrix.resize(_num_dps);
//#ifdef __USE_GCD__
// std::cout << "GCD dispatch, hierarchical_sne_inl 253.\n";
// dispatch_apply(_num_dps, dispatch_get_global_queue(0, 0), ^(size_t i) {
//#else
#pragma omp parallel for
for (int i = 0; i < _num_dps; ++i) {
//#endif //__USE_GCD__
scalar_type sum = 0;
for (int n = 1; n < nn; ++n) {
int idx = i * nn + n;
auto v = distance_based_probabilities[idx];
sum += v;
scale._transition_matrix[i][neighborhood_graph[idx]] = v;
}
}
//#ifdef __USE_GCD__
// );
//#endif
}
utils::secureLogValue(_logger, "Min memory requirements (MB)", scale.mimMemoryOccupation());
}
template <typename scalar_type, typename sparse_scalar_matrix_type>
void HierarchicalSNE<scalar_type, sparse_scalar_matrix_type>::initializeFirstScale(const sparse_scalar_matrix_type& similarities) {
utils::secureLog(_logger, "Initializing the first scale...");
_hierarchy.clear();
_hierarchy.push_back(Scale());
Scale& scale = _hierarchy[0];
{
utils::ScopedTimer<scalar_type, utils::Seconds> timer(_statistics._init_fmc_time);
utils::secureLog(_logger, "Creating transition matrix...");
scale._landmark_to_original_data_idx.resize(_num_dps);
std::iota(scale._landmark_to_original_data_idx.begin(), scale._landmark_to_original_data_idx.end(), 0);
scale._landmark_to_previous_scale_idx = scale._landmark_to_original_data_idx;
scale._landmark_weight.resize(_num_dps, 1);
scale._transition_matrix = similarities;
}
utils::secureLogValue(_logger, "Min memory requirements (MB)", scale.mimMemoryOccupation());
}
template <typename scalar_type, typename sparse_scalar_matrix_type>
void HierarchicalSNE<scalar_type, sparse_scalar_matrix_type>::selectLandmarks(const Scale& previous_scale, Scale& scale, unsigned_int_type& selected_landmarks) {
utils::ScopedTimer<scalar_type, utils::Seconds> timer(_statistics._landmarks_selection_time);
utils::secureLog(_logger, "Landmark selection with fixed reduction...");
const unsigned_int_type previous_scale_dp = previous_scale._transition_matrix.size();
const unsigned_int_type num_landmarks = previous_scale_dp * _params._rs_reduction_factor_per_layer;
std::default_random_engine generator(seed());
std::uniform_int_distribution<> distribution_int(0, previous_scale_dp - 1);
std::uniform_real_distribution<double> distribution_real(0.0, 1.0);
scale._landmark_to_original_data_idx.resize(num_landmarks, 0);
scale._landmark_to_previous_scale_idx.resize(num_landmarks, 0);
scale._landmark_weight.resize(num_landmarks, 0);
scale._previous_scale_to_landmark_idx.resize(previous_scale_dp, -1);
scale._transition_matrix.resize(num_landmarks);
scale._area_of_influence.resize(previous_scale_dp);
int num_tries = 0;
selected_landmarks = 0;
while (selected_landmarks < num_landmarks) {
++num_tries;
int idx = distribution_int(generator);
assert(idx >= 0);
assert(idx < _num_dps);
if (_params._rs_outliers_removal_jumps > 0) {
idx = randomWalk(idx, _params._rs_outliers_removal_jumps, previous_scale._transition_matrix, distribution_real, generator);
}
if (scale._previous_scale_to_landmark_idx[idx] != -1) {
continue;
}
scale._previous_scale_to_landmark_idx[idx] = selected_landmarks;
scale._landmark_to_original_data_idx[selected_landmarks] = previous_scale._landmark_to_original_data_idx[idx];
scale._landmark_to_previous_scale_idx[selected_landmarks] = idx;
++selected_landmarks;
}
_statistics._landmarks_selection_num_walks = num_tries * _params._rs_outliers_removal_jumps;
}
template <typename scalar_type, typename sparse_scalar_matrix_type>
void HierarchicalSNE<scalar_type, sparse_scalar_matrix_type>::selectLandmarksWithStationaryDistribution(const Scale& previous_scale, Scale& scale, unsigned_int_type& selected_landmarks) {
utils::secureLog(_logger, "Landmark selection...");
const unsigned_int_type previous_scale_dp = previous_scale._transition_matrix.size();
int count = 0;
int thresh = _params._mcmcs_num_walks * _params._mcmcs_landmark_thresh;
//__block std::vector<unsigned_int_type> importance_sampling(previous_scale_dp,0);
std::vector<unsigned_int_type> importance_sampling(previous_scale_dp, 0);
{
utils::ScopedTimer<scalar_type, utils::Seconds> timer(_statistics._mcmc_sampling_time);
//__block std::default_random_engine generator(seed());
//__block std::uniform_real_distribution<double> distribution_real(0.0, 1.0);
std::default_random_engine generator(seed());
std::uniform_real_distribution<double> distribution_real(0.0, 1.0);
selected_landmarks = 0;
utils::secureLog(_logger, "Monte Carlo Approximation...");
unsigned_int_type invalid = std::numeric_limits<unsigned_int_type>::max();
//#ifdef __USE_GCD__
// std::cout << "GCD dispatch, hierarchical_sne_inl 391.\n";
// dispatch_apply(previous_scale_dp, dispatch_get_global_queue(0, 0), ^(size_t d) {
//#else
#pragma omp parallel for
for (int d = 0; d < previous_scale_dp; ++d) {
//#endif //__USE_GCD__
for (int p = 0; p < _params._mcmcs_num_walks; ++p) {
int idx = d;
idx = randomWalk(idx, _params._mcmcs_walk_length, previous_scale._transition_matrix, distribution_real, generator);
if (idx != invalid) {
++importance_sampling[idx];
}
}
}
//#ifdef __USE_GCD__
// );
//#endif
// cheap hack to get the hard cutoff in, still computes the data driven part which should probably be replaced...
if (_params._hard_cut_off)
{
std::vector<unsigned_int_type> importance_sampling_sort = importance_sampling;
std::sort(importance_sampling_sort.begin(), importance_sampling_sort.end());
unsigned_int_type cutoff = importance_sampling_sort[(importance_sampling_sort.size() - 1) * (1.0f - _params._hard_cut_off_percentage)];
thresh = cutoff;
}
_statistics._landmarks_selection_num_walks = previous_scale_dp * _params._mcmcs_num_walks;
for (int i = 0; i < previous_scale_dp; ++i) {
if (importance_sampling[i] > thresh)
++count;
}
}
{
utils::ScopedTimer<scalar_type, utils::Seconds> timer(_statistics._landmarks_selection_time);
utils::secureLog(_logger, "Selection...");
scale._previous_scale_to_landmark_idx.resize(previous_scale_dp, -1);
scale._area_of_influence.resize(previous_scale_dp);
scale._landmark_to_original_data_idx.resize(count);
scale._landmark_to_previous_scale_idx.resize(count);
scale._landmark_weight.resize(count);
scale._transition_matrix.resize(count);
selected_landmarks = 0;
for (int i = 0; i < previous_scale_dp; ++i) {
if (importance_sampling[i] > thresh) {
scale._previous_scale_to_landmark_idx[i] = selected_landmarks;
scale._landmark_to_original_data_idx[selected_landmarks] = previous_scale._landmark_to_original_data_idx[i];
scale._landmark_to_previous_scale_idx[selected_landmarks] = i;
++selected_landmarks;
}
}
}
}
template <typename scalar_type, typename sparse_scalar_matrix_type>
bool HierarchicalSNE<scalar_type, sparse_scalar_matrix_type>::addScaleImpl() {
utils::ScopedTimer<scalar_type, utils::Seconds> timer_tot(_statistics._total_time);
utils::secureLog(_logger, "Add a new scale ...");
_hierarchy.push_back(Scale());
Scale& scale = _hierarchy[_hierarchy.size() - 1];
Scale& previous_scale = _hierarchy[_hierarchy.size() - 2];
const unsigned_int_type previous_scale_dp = previous_scale._landmark_to_original_data_idx.size();
// Landmark selection
unsigned_int_type selected_landmarks = 0;
if (_params._monte_carlo_sampling) {
selectLandmarksWithStationaryDistribution(previous_scale, scale, selected_landmarks);
}
else {
selectLandmarks(previous_scale, scale, selected_landmarks);
}
utils::secureLogValue(_logger, "\t#landmarks", selected_landmarks);
{//Area of influence
//__block std::default_random_engine generator(seed());
//__block std::uniform_real_distribution<double> distribution_real(0.0, 1.0);
std::default_random_engine generator(seed());
std::uniform_real_distribution<double> distribution_real(0.0, 1.0);
const unsigned_int_type max_jumps = 100;//1000.*selected_landmarks/previous_scale_dp;
const unsigned_int_type walks_per_dp = _params._num_walks_per_landmark;
utils::secureLog(_logger, "\tComputing area of influence...");
{
utils::ScopedTimer<scalar_type, utils::Seconds> timer(_statistics._aoi_time);
//__block unsigned_int_type num_elem_in_Is(0);
unsigned_int_type num_elem_in_Is(0);
//#ifdef __USE_GCD__
// std::cout << "GCD dispatch, hierarchical_sne_inl 473.\n";
// dispatch_queue_t criticalQueue = dispatch_queue_create("critical", NULL);
// dispatch_apply(previous_scale_dp, dispatch_get_global_queue(0, 0), ^(size_t d) {
//#else
#pragma omp parallel for
for (int d = 0; d < previous_scale_dp; ++d) {
//#endif //__USE_GCD__
std::unordered_map<unsigned_int_type, unsigned_int_type> landmarks_reached;
for (int i = 0; i < walks_per_dp; ++i) {
auto res = randomWalk(d, scale._previous_scale_to_landmark_idx, max_jumps, previous_scale._transition_matrix, distribution_real, generator);
if (res != -1) {
++landmarks_reached[scale._previous_scale_to_landmark_idx[res]];
}
else {
//--i;
}
}
//#ifdef __USE_GCD__
// dispatch_sync(criticalQueue, ^
//#else
#pragma omp critical
//#endif
{
num_elem_in_Is += landmarks_reached.size();
for (auto l : landmarks_reached) {
for (auto other_l : landmarks_reached) {
//to avoid that the sparsity of the matrix it is much different from the effective sparsity
if (l.second <= _params._transition_matrix_prune_thresh || other_l.second <= _params._transition_matrix_prune_thresh)
continue;
if (l.first != other_l.first) {
scale._transition_matrix[l.first][other_l.first] += l.second * other_l.second * previous_scale._landmark_weight[d];
}
}
}
for (auto l : landmarks_reached) {
const scalar_type prob = scalar_type(l.second) / walks_per_dp;
scale._area_of_influence[d][l.first] = prob;
scale._landmark_weight[l.first] += prob * previous_scale._landmark_weight[d];
}
}
//#ifdef __USE_GCD__
// );
//#endif
}
//#ifdef __USE_GCD__
// );
//#endif
_statistics._aoi_num_walks = previous_scale_dp * walks_per_dp;
_statistics._aoi_sparsity = 1 - scalar_type(num_elem_in_Is) / (previous_scale_dp*selected_landmarks);
}
{
utils::secureLog(_logger, "\tComputing finite markov chain...");
utils::ScopedTimer<scalar_type, utils::Seconds> timer(_statistics._fmc_time);
unsigned_int_type num_elem_in_Ts(0);
unsigned_int_type num_effective_elem_in_Ts(0);
for (int l = 0; l < scale._transition_matrix.size(); ++l) {
num_elem_in_Ts += scale._transition_matrix[l].size();
scalar_type sum(0);
for (auto& e : scale._transition_matrix[l]) {
sum += e.second;
}
for (auto& e : scale._transition_matrix[l]) {
e.second /= sum;
if (e.second > 0.01) {
++num_effective_elem_in_Ts;
}
}
}
_statistics._fmc_sparsity = 1 - scalar_type(num_elem_in_Ts) / (selected_landmarks*selected_landmarks);
_statistics._fmc_effective_sparsity = 1 - scalar_type(num_effective_elem_in_Ts) / (selected_landmarks*selected_landmarks);
}
}
utils::secureLogValue(_logger, "Min memory requirements (MB)", scale.mimMemoryOccupation());
return true;
}
template <typename scalar_type, typename sparse_scalar_matrix_type>
bool HierarchicalSNE<scalar_type, sparse_scalar_matrix_type>::addScaleOutOfCoreImpl() {
typedef typename sparse_scalar_matrix_type::value_type map_type;
typedef typename map_type::key_type key_type;
typedef typename map_type::mapped_type mapped_type;
typedef hdi::data::MapHelpers<key_type, mapped_type, map_type> map_helpers_type;
utils::ScopedTimer<scalar_type, utils::Seconds> timer_tot(_statistics._total_time);
utils::secureLog(_logger, "Add a new scale with out-of-core implementation ...");
_hierarchy.push_back(Scale());
Scale& scale = _hierarchy[_hierarchy.size() - 1];
Scale& previous_scale = _hierarchy[_hierarchy.size() - 2];
const unsigned_int_type previous_scale_dp = previous_scale._landmark_to_original_data_idx.size();
// Landmark selection
unsigned_int_type selected_landmarks = 0;
if (_params._monte_carlo_sampling) {
selectLandmarksWithStationaryDistribution(previous_scale, scale, selected_landmarks);
}
else {
selectLandmarks(previous_scale, scale, selected_landmarks);
}
utils::secureLogValue(_logger, "\t#landmarks", selected_landmarks);
{//Area of influence
std::default_random_engine generator(seed());
std::uniform_real_distribution<double> distribution_real(0.0, 1.0);
const unsigned_int_type max_jumps = 200;//1000.*selected_landmarks/previous_scale_dp;
const unsigned_int_type walks_per_dp = _params._num_walks_per_landmark;
utils::secureLog(_logger, "\tComputing area of influence...");
{
utils::ScopedTimer<scalar_type, utils::Seconds> timer(_statistics._aoi_time);
int d = 0;
unsigned_int_type num_elem_in_Is(0);
{
utils::LogProgress progress(_verbose ? _logger : nullptr);
progress.setNumSteps(previous_scale_dp);
progress.setNumTicks(previous_scale_dp / 50000);
progress.setName("Area of influence");
progress.start();
//#ifdef __USE_GCD__
// std::cout << "GCD dispatch, hierarchical_sne_inl 587.\n";
// dispatch_queue_t criticalQueue = dispatch_queue_create("critical", NULL);
// dispatch_apply(previous_scale_dp, dispatch_get_global_queue(0, 0), ^(size_t d) {
//#else
#pragma omp parallel for
for (int d = 0; d < previous_scale_dp; ++d) {
//#endif //__USE_GCD__
//map because it must be ordered for the initialization of the maps
std::map<unsigned_int_type, scalar_type> landmarks_reached;
for (int i = 0; i < walks_per_dp; ++i) {
auto res = randomWalk(d, scale._previous_scale_to_landmark_idx, max_jumps, previous_scale._transition_matrix, distribution_real, generator);
if (res != -1) {
++landmarks_reached[scale._previous_scale_to_landmark_idx[res]];
}
else {
//--i;
}
}
//normalization
for (auto& l : landmarks_reached) {
l.second = scalar_type(l.second) / walks_per_dp;
}
//saving aoi
map_helpers_type::initialize(scale._area_of_influence[d], landmarks_reached.begin(), landmarks_reached.end());
map_helpers_type::shrinkToFit(scale._area_of_influence[d]);
progress.step();
}
//#ifdef __USE_GCD__
// );
//#endif
progress.finish();
}
utils::secureLog(_logger, "\tCaching weights...");
//caching of the weights
for (d = 0; d < previous_scale_dp; ++d) {
num_elem_in_Is += scale._area_of_influence[d].size();
for (auto& e : scale._area_of_influence[d]) {
scale._landmark_weight[e.first] += e.second;
}
}
utils::secureLog(_logger, "\tInverting the AoI matrix...");
//Inverse AoI -> critical for the computation time
sparse_scalar_matrix_type inverse_aoi;
map_helpers_type::invert(scale._area_of_influence, inverse_aoi);
utils::secureLog(_logger, "\tComputing similarities...");
//Similarities -> compute the overlap of the area of influence
{
utils::LogProgress progress(_verbose ? _logger : nullptr);
progress.setNumSteps(scale._transition_matrix.size());
progress.setNumTicks(scale._transition_matrix.size() / 5000);
progress.setName("Similarities");
progress.start();
// #ifdef __USE_GCD__
// std::cout << "GCD dispatch, hierarchical_sne_inl 602.\n";
// dispatch_apply(scale._transition_matrix.size(), dispatch_get_global_queue(0, 0), ^(size_t l) {
// #else
#pragma omp parallel for
for (int l = 0; l < scale._transition_matrix.size(); ++l) {
// #endif //__USE_GCD__
//ordered for efficient initialization
std::map<typename sparse_scalar_matrix_type::value_type::key_type, typename sparse_scalar_matrix_type::value_type::mapped_type> temp_trans_mat; // use map here
for (const auto& d : inverse_aoi[l]) {
for (const auto& aoi : scale._area_of_influence[d.first]) {
double single_landmark_thresh = (1. / 100.)*_params._transition_matrix_prune_thresh;
if (l != aoi.first) {
if (d.second <= single_landmark_thresh || aoi.second <= single_landmark_thresh)
continue;
temp_trans_mat[aoi.first] += d.second * aoi.second * previous_scale._landmark_weight[d.first];
}
}
}
//normalization
double sum = 0;
for (auto& v : temp_trans_mat) { sum += v.second; }
for (auto& v : temp_trans_mat) { v.second /= sum; }
//removed the threshold depending on the scale -> it makes sense to remove only uneffective neighbors based at every scale -> memory is still under control
map_helpers_type::initialize(scale._transition_matrix[l],temp_trans_mat.begin(),temp_trans_mat.end(), static_cast<mapped_type>(0.001));
map_helpers_type::shrinkToFit(scale._transition_matrix[l]);
progress.step();
}
// #ifdef __USE_GCD__
// );
// #endif
progress.finish();
}
_statistics._aoi_num_walks = previous_scale_dp * walks_per_dp;
_statistics._aoi_sparsity = 1 - scalar_type(num_elem_in_Is) / (previous_scale_dp*selected_landmarks);
}
{
utils::secureLog(_logger, "\tComputing finite markov chain...");
utils::ScopedTimer<scalar_type, utils::Seconds> timer(_statistics._fmc_time);
unsigned_int_type num_elem_in_Ts(0);
unsigned_int_type num_effective_elem_in_Ts(0);
for (int l = 0; l < scale._transition_matrix.size(); ++l) {
num_elem_in_Ts += scale._transition_matrix[l].size();
scalar_type sum(0);
for (auto& e : scale._transition_matrix[l]) {
sum += e.second;
}
for (auto& e : scale._transition_matrix[l]) {
e.second /= sum;
if (e.second > 0.001) {
++num_effective_elem_in_Ts;
}
}
}
_statistics._fmc_sparsity = 1 - scalar_type(num_elem_in_Ts) / (selected_landmarks*selected_landmarks);
_statistics._fmc_effective_sparsity = 1 - scalar_type(num_effective_elem_in_Ts) / (selected_landmarks*selected_landmarks);
}
}
return true;
}
template <typename scalar_type, typename sparse_scalar_matrix_type>
typename HierarchicalSNE<scalar_type, sparse_scalar_matrix_type>::unsigned_int_type HierarchicalSNE<scalar_type, sparse_scalar_matrix_type>::seed()const {
return(_params._seed > 0) ? static_cast<unsigned_int_type>(_params._seed) : std::chrono::system_clock::now().time_since_epoch().count();
}
///////////////////////////////////////////////////////////////////
template <typename scalar_type, typename sparse_scalar_matrix_type>
void HierarchicalSNE<scalar_type, sparse_scalar_matrix_type>::getInfluencedLandmarksInPreviousScale(unsigned_int_type scale_id, std::vector<unsigned_int_type>& idxes, std::map<unsigned_int_type, scalar_type>& neighbors)const {
neighbors.clear();
std::unordered_set<unsigned_int_type> set_idxes;
set_idxes.insert(idxes.begin(), idxes.end());
auto not_found = set_idxes.end();
for (int d = 0; d < _hierarchy[scale_id]._area_of_influence.size(); ++d) {
double probability = 0;
for (auto& v : _hierarchy[scale_id]._area_of_influence[d]) {
if (set_idxes.find(v.first) != not_found) {
probability += v.second;
}
}
if (probability > 0) {
neighbors[d] = probability;
}
}
}
template <typename scalar_type, typename sparse_scalar_matrix_type>
void HierarchicalSNE<scalar_type, sparse_scalar_matrix_type>::getInfluencingLandmarksInNextScale(unsigned_int_type scale_id, std::vector<unsigned_int_type>& idxes, std::map<unsigned_int_type, scalar_type>& neighbors)const {
neighbors.clear();
int next_scale_id = scale_id + 1;
if (next_scale_id + 1 > _hierarchy.size()) return;
std::map<unsigned_int_type, scalar_type> completeSet;
for (int i = 0; i < idxes.size(); i++)
{
for (auto& v : _hierarchy[next_scale_id]._area_of_influence[idxes[i]]) {
neighbors[v.first] += v.second;
}
}
for (int i = 0; i < _hierarchy[next_scale_id]._area_of_influence.size(); i++)
{
for (auto& v : _hierarchy[next_scale_id]._area_of_influence[i]) {
completeSet[v.first] += v.second;
}
}
for (auto& v : neighbors)
{
neighbors[v.first] /= completeSet[v.first];
}
}
template <typename scalar_type, typename sparse_scalar_matrix_type>
void HierarchicalSNE<scalar_type, sparse_scalar_matrix_type>::getInterpolationWeights(sparse_scalar_matrix_type& influence, int scale)const {
influence.clear();
influence.resize(_num_dps);
scale = (scale < 0) ? (_hierarchy.size() - 1) : scale;
checkAndThrowLogic(scale < _hierarchy.size(), "getInterpolationWeights: Invalid scale");
//#ifdef __USE_GCD__
// std::cout << "GCD dispatch, hierarchical_sne_inl 724.\n";
// dispatch_apply(_num_dps, dispatch_get_global_queue(0, 0), ^(size_t i) {
//#else
#pragma omp parallel for
for (int i = 0; i < _num_dps; ++i) {
//#endif //__USE_GCD__
influence[i] = _hierarchy[1]._area_of_influence[i];
for (int s = 2; s <= scale; ++s) {
typename sparse_scalar_matrix_type::value_type temp_link;
for (auto l : influence[i]) {
for (auto new_l : _hierarchy[s]._area_of_influence[l.first]) {
temp_link[new_l.first] += l.second * new_l.second;
}
}
influence[i] = temp_link;
}
}
//#ifdef __USE_GCD__
// );
//#endif
}
template <typename scalar_type, typename sparse_scalar_matrix_type>
void HierarchicalSNE<scalar_type, sparse_scalar_matrix_type>::getInterpolationWeights(const std::vector<unsigned int>& data_points, sparse_scalar_matrix_type& influence, int scale)const {
auto n = data_points.size();
influence.clear();
influence.resize(n);
scale = (scale < 0) ? (_hierarchy.size() - 1) : scale;
checkAndThrowLogic(scale < _hierarchy.size(), "getInterpolationWeights: Invalid scale");
//#ifdef __USE_GCD__
// std::cout << "GCD dispatch, hierarchical_sne_inl 755.\n";
// dispatch_apply(n, dispatch_get_global_queue(0, 0), ^(size_t i) {
//#else
#pragma omp parallel for
for (int i = 0; i < n; ++i) {
//#endif //__USE_GCD__
influence[i] = _hierarchy[1]._area_of_influence[data_points[i]];
for (int s = 2; s <= scale; ++s) {
typename sparse_scalar_matrix_type::value_type temp_link;
for (auto l : influence[i]) {
for (auto new_l : _hierarchy[s]._area_of_influence[l.first]) {
temp_link[new_l.first] += l.second * new_l.second;
}
}
influence[i] = temp_link;
}
}
//#ifdef __USE_GCD__
// );
//#endif
}
template <typename scalar_type, typename sparse_scalar_matrix_type>
void HierarchicalSNE<scalar_type, sparse_scalar_matrix_type>::getInfluenceOnDataPoint(unsigned_int_type dp, std::vector<std::unordered_map<unsigned_int_type, scalar_type>>& influence, scalar_type thresh, bool normalized)const {
assert(dp < _hierarchy[0].size());
influence.resize(_hierarchy.size());
influence[0][dp] = 1; //Hey it's me!
if (influence.size() == 1) {
return;
}
for (auto& v : _hierarchy[1]._area_of_influence[dp]) {
influence[1][v.first] = v.second;
}
if (normalized)
{
double sum = 0;
for (auto& v : influence[1]) { sum += v.second; }
for (auto& v : influence[1]) { v.second /= sum; }
}
for (int s = 2; s < _hierarchy.size(); ++s) {
for (auto l : influence[s - 1]) {
if (l.second >= thresh) {
for (auto new_l : _hierarchy[s]._area_of_influence[l.first]) {
influence[s][new_l.first] += l.second * new_l.second;
}
}
}
if (normalized)
{
double sum = 0;
for (auto& v : influence[s]) { sum += v.second; }
for (auto& v : influence[s]) { v.second /= sum; }
}
}
}
template <typename scalar_type, typename sparse_scalar_matrix_type>
void HierarchicalSNE<scalar_type, sparse_scalar_matrix_type>::getStochasticLocationAtHigherScale(unsigned_int_type orig_scale, unsigned_int_type dest_scale, const std::vector<unsigned_int_type>& subset_orig_scale, sparse_scalar_matrix_type& closeness)const {
checkAndThrowLogic(dest_scale > orig_scale, "getStochasticLocationAtHigherScale (0)");
checkAndThrowLogic(orig_scale < _hierarchy.size() - 1, "getStochasticLocationAtHigherScale (2)");
checkAndThrowLogic(dest_scale < _hierarchy.size(), "getStochasticLocationAtHigherScale (3)");
closeness.clear();
closeness.resize(subset_orig_scale.size());
//#ifdef __USE_GCD__
// std::cout << "GCD dispatch, hierarchical_sne_inl 814.\n";
// dispatch_apply(subset_orig_scale.size(), dispatch_get_global_queue(0, 0), ^(size_t i) {
//#else
#pragma omp parallel for
for (int i = 0; i < subset_orig_scale.size(); ++i) {
//#endif //__USE_GCD__
assert(subset_orig_scale[i] < _hierarchy[orig_scale + 1]._area_of_influence.size());
closeness[i] = _hierarchy[orig_scale + 1]._area_of_influence[subset_orig_scale[i]];
for (int s = orig_scale + 2; s <= dest_scale; ++s) {
typename sparse_scalar_matrix_type::value_type temp_link;
for (auto l : closeness[i]) {
for (auto new_l : _hierarchy[s]._area_of_influence[l.first]) {
temp_link[new_l.first] += l.second * new_l.second;
}
}
closeness[i] = temp_link;
}
}
//#ifdef __USE_GCD__
// );
//#endif
}
//! This function computes the cumulative area of influence (aoi) of a "selection"of landmark points at scale "scale_id" for each point at the data level. This process is described in Section 3.3 of https://doi.org/10.1111/cgf.12878
template <typename scalar_type, typename sparse_scalar_matrix_type>
void HierarchicalSNE<scalar_type, sparse_scalar_matrix_type>::getAreaOfInfluence(unsigned_int_type scale_id, const std::vector<unsigned_int_type>& selection, std::vector<scalar_type>& aoi)const {
typedef typename sparse_scalar_matrix_type::value_type map_type;
typedef typename map_type::key_type key_type;
typedef typename map_type::mapped_type mapped_type;
typedef hdi::data::MapHelpers<key_type, mapped_type, map_type> map_helpers_type;
checkAndThrowLogic(scale_id < _hierarchy.size(), "getAreaOfInfluence (3)");
// initialize the area of influence vector
aoi.assign(scale(0).size(), 0);
// at scale 0 every point has a maximum area of influence (1) on itself.
if (scale_id == 0) {
#pragma omp parallel for
for (int i = 0; i < selection.size(); ++i) {
aoi[selection[i]] = 1;
}
}
else {
const std::unordered_set<unsigned_int_type> selected_scale_id_landmarks(selection.cbegin(), selection.cend()); // unordered set since we need all items to be unique
// Compute for every point at the data level the area of influence (aoi)
// of the "selection" landmark points at scale scale_id through a chain of sparse matrix multiplications
#pragma omp parallel for schedule(dynamic,1)
for (int i = 0; i < scale(0).size(); ++i) {
const auto& scale_1_aois = scale(1)._area_of_influence[i];
// Declare a holder for the super scale landmarks aois, using std::vector for quick look-up
std::vector<std::pair<key_type, mapped_type>> super_aois(scale_1_aois.begin(), scale_1_aois.end());
// Walk the scale hierarchy from super-scale to sub-scale
// For each scale compute the cumulative influence
// of the landmark points from the lower scale on data point "i" at the current scale.
for (int s = 2; s <= scale_id; ++s) {
// Use unordered_map for quick insertion
// Ordering is not needed but we do want to avoid multiple entries per data/landmark point.
std::unordered_map<key_type, mapped_type> current_aoi_cumulative;
// Factor in the influence of all the super scale landmark aois
for (auto super_aoi : super_aois) {
for (auto current_aoi : scale(s)._area_of_influence[super_aoi.first]) {
// compute cumulative aoi sum of products
current_aoi_cumulative[current_aoi.first] += super_aoi.second * current_aoi.second;
}
}
// Copy the influence of the current_aoi_cumulative to the super scale aoi holder for the next iteration
super_aois.resize(current_aoi_cumulative.size());
std::copy(current_aoi_cumulative.cbegin(), current_aoi_cumulative.cend(), super_aois.begin());
}
// Now the current scale for super_aois is scale_id.
// So the indices in "selection" match the indices in super_aois
// Check if that landmark is in the selection,
// if so add the area of influence to the cumulative area of influence of the selection on point i
for (auto scale_id_aoi : super_aois) {
if (selected_scale_id_landmarks.find(scale_id_aoi.first) != selected_scale_id_landmarks.end()) {
aoi[i] += scale_id_aoi.second;
}
}
}
}
}
template <typename scalar_type, typename sparse_scalar_matrix_type>
void HierarchicalSNE<scalar_type, sparse_scalar_matrix_type>::getAreaOfInfluenceTopDown(unsigned_int_type scale_id, const std::vector<unsigned_int_type>& selection, std::vector<scalar_type>& aoi, double threshold)const {
typedef typename sparse_scalar_matrix_type::value_type map_type;
typedef typename map_type::key_type key_type;
typedef typename map_type::mapped_type mapped_type;
typedef hdi::data::MapHelpers<key_type, mapped_type, map_type> map_helpers_type;
checkAndThrowLogic(scale_id < _hierarchy.size(), "getAreaOfInfluenceTopDown (3)");
double gamma = 0.3;
if ((threshold >= 0) && (threshold <= 1.0)) {
gamma = threshold;
}
aoi.clear();
aoi.resize(scale(0).size(), 0);
std::unordered_set<unsigned int> set_selected_idxes;
set_selected_idxes.insert(selection.begin(), selection.end());
if (scale_id == 0) {
for (int i = 0; i < selection.size(); ++i) {
aoi[selection[i]] = 1;
}
}
else {
std::vector<unsigned_int_type> scale_selection = selection;
for (int s = scale_id; s > 0; --s) {
std::map<unsigned_int_type, scalar_type> neighbors;
getInfluencedLandmarksInPreviousScale(s, scale_selection, neighbors);
scale_selection.clear();
for (auto neigh : neighbors) {
if (neigh.second > gamma) {
scale_selection.push_back(neigh.first);
}
}
}
for (int i = 0; i < scale_selection.size(); ++i) {
aoi[scale_selection[i]] = 1;
}
}
}
///////////////////////////////////////////////////////////////////
/// RANDOM WALKS
///////////////////////////////////////////////////////////////////
//Compute a random walk using a transition matrix
template <typename scalar_type, typename sparse_scalar_matrix_type>
typename HierarchicalSNE<scalar_type, sparse_scalar_matrix_type>::unsigned_int_type HierarchicalSNE<scalar_type, sparse_scalar_matrix_type>::randomWalk(unsigned_int_type starting_point, unsigned_int_type max_length, const sparse_scalar_matrix_type& transition_matrix, std::uniform_real_distribution<double>& distribution, std::default_random_engine& generator) {
unsigned_int_type dp_idx = starting_point;
int walk_length = 0;
do {
const double rnd_num = distribution(generator);
unsigned_int_type idx_knn = dp_idx;
double incremental_prob = 0;
for (auto& elem : transition_matrix[dp_idx]) {
incremental_prob += elem.second;
if (rnd_num < incremental_prob) {
idx_knn = elem.first;
break;
}
}
//assert(idx_knn != dp_idx);
if (idx_knn == dp_idx) {
return std::numeric_limits<unsigned_int_type>::max();
// std::cout << "DISCONNECTED!" << std::endl;
}
dp_idx = idx_knn;
++walk_length;
} while (walk_length <= max_length);
return dp_idx;
}
//!Compute a random walk using a transition matrix
template <typename scalar_type, typename sparse_scalar_matrix_type>
int HierarchicalSNE<scalar_type, sparse_scalar_matrix_type>::randomWalk(unsigned_int_type starting_point, const std::vector<int>& stopping_points, unsigned_int_type max_length, const sparse_scalar_matrix_type& transition_matrix, std::uniform_real_distribution<double>& distribution, std::default_random_engine& generator) {
unsigned_int_type dp_idx = starting_point;
int walk_length = 0;
do {
const double rnd_num = distribution(generator);
unsigned_int_type idx_knn = dp_idx;
double incremental_prob = 0;
for (auto& elem : transition_matrix[dp_idx]) {
incremental_prob += elem.second;
if (rnd_num < incremental_prob) {
idx_knn = elem.first;
break;
}
}
//assert(idx_knn != dp_idx);
if (idx_knn == dp_idx) {
return -1;
std::cout << "42!" << std::endl;
}
dp_idx = idx_knn;
++walk_length;
} while (stopping_points[dp_idx] == -1 && walk_length <= max_length);
if (walk_length > max_length) {
return -1;
}
return static_cast<int>(dp_idx);
}
////////////////////////////////////////////////////////////////////////////////////
template <typename scalar_type, typename sparse_scalar_matrix_type>
typename HierarchicalSNE<scalar_type, sparse_scalar_matrix_type>::int_type HierarchicalSNE<scalar_type, sparse_scalar_matrix_type>::ClusterTree::getFreeClusterId(unsigned_int_type scale_id) {
int_type max = std::numeric_limits<int_type>::max();
for (int_type i = 0; i < max; ++i) {
for (int j = 0; j < _cluster_tree[scale_id].size(); ++j) {
if (i != _cluster_tree[scale_id][j].id()) {
return i;
}
}
}
return 0;
}
template <typename scalar_type, typename sparse_scalar_matrix_type>
void HierarchicalSNE<scalar_type, sparse_scalar_matrix_type>::ClusterTree::addCluster(unsigned_int_type scale_id, const cluster_type& cluster) {
checkAndThrowLogic(scale_id < _cluster_tree.size(), "ClusterHierarchy::addCluster: invalid scale");
for (int j = 0; j < _cluster_tree[scale_id].size(); ++j) {
checkAndThrowLogic(cluster.id() != _cluster_tree[scale_id][j].id(), "ClusterHierarchy::addCluster: duplicated id");
}
if (scale_id == _cluster_tree.size() - 1) {
checkAndThrowLogic(cluster.parent_id() == Cluster::NULL_LINK, "ClusterHierarchy::addCluster: root clusters must have parent_id = Cluster::NULL_LINK");
}
else {
checkAndThrowLogic(cluster.parent_id() != Cluster::NULL_LINK, "ClusterHierarchy::addCluster: non-root clusters must have parent_id != Cluster::NULL_LINK");
}
_cluster_tree[scale_id].push_back(cluster);
}
template <typename scalar_type, typename sparse_scalar_matrix_type>
void HierarchicalSNE<scalar_type, sparse_scalar_matrix_type>::ClusterTree::removeCluster(unsigned_int_type scale_id, int_type cluster_id) {
checkAndThrowLogic(scale_id < _cluster_tree.size(), "ClusterHierarchy::removeCluster: invalid scale");
for (int i = 0; i < _cluster_tree[scale_id].size(); ++i) {
if (_cluster_tree[scale_id][i].id() == cluster_id) {
_cluster_tree[scale_id].erase(_cluster_tree[scale_id].begin() + i);
break;
}
}
}
template <typename scalar_type, typename sparse_scalar_matrix_type>
bool HierarchicalSNE<scalar_type, sparse_scalar_matrix_type>::ClusterTree::hasClusterId(unsigned_int_type scale_id, int_type cluster_id)const {
checkAndThrowLogic(scale_id < _cluster_tree.size(), "ClusterHierarchy::hasClusterId: invalid scale");
for (int j = 0; j < _cluster_tree[scale_id].size(); ++j) {
if (cluster_id == _cluster_tree[scale_id][j].id()) { return true; }
}
return false;
}
template <typename scalar_type, typename sparse_scalar_matrix_type>
const typename HierarchicalSNE<scalar_type, sparse_scalar_matrix_type>::ClusterTree::cluster_type& HierarchicalSNE<scalar_type, sparse_scalar_matrix_type>::ClusterTree::cluster(unsigned_int_type scale_id, int_type cluster_id)const {
checkAndThrowLogic(hasClusterId(scale_id, cluster_id), "ClusterHierarchy::cluster: invalid cluster");
for (int j = 0; j < _cluster_tree[scale_id].size(); ++j) {
if (cluster_id == _cluster_tree[scale_id][j].id()) {
return _cluster_tree[scale_id][j];
}
}
throw std::logic_error("Invalid cluster");
//return cluster_type(); //INVALID
}
template <typename scalar_type, typename sparse_scalar_matrix_type>
bool HierarchicalSNE<scalar_type, sparse_scalar_matrix_type>::ClusterTree::checkCluterConsistency(const HierarchicalSNE& hsne, unsigned_int_type scale_id, int_type cluster_id) {
checkAndThrowLogic(hasClusterId(scale_id, cluster_id), "ClusterHierarchy::checkCluterConsistency: invalid cluster");
if (scale_id == _cluster_tree.size() - 1) {
std::stringstream ss;
ss << "Validating cluster " << cluster_id << " at scale " << scale_id << ":\tis a root node => valid";
utils::secureLog(_logger, ss.str());
return true;
}
int_type cluster_id_in_vector = -1;
for (int j = 0; j < _cluster_tree[scale_id].size(); ++j) {
if (cluster_id == _cluster_tree[scale_id][j].id()) {
cluster_id_in_vector = j;
}
}
std::vector<scalar_type> influence(_cluster_tree[scale_id + 1].size(), 0);
scalar_type unclustered_influence(0);
auto& scale = hsne.scale(scale_id + 1);
for (auto e : _cluster_tree[scale_id][cluster_id_in_vector].landmarks()) {
for (auto aoi : scale._area_of_influence[e]) {
bool found = false;
for (int i = 0; i < influence.size(); ++i) {
auto it = _cluster_tree[scale_id + 1][i].landmarks().find(aoi.first);
if (it != _cluster_tree[scale_id + 1][i].landmarks().end()) {
influence[i] += aoi.second;
found = true;
}
}
if (!found) {
unclustered_influence += aoi.second;
}
}
}
std::stringstream ss;
ss << "Validating cluster " << cluster_id << " at scale " << scale_id << " with parent " << _cluster_tree[scale_id][cluster_id_in_vector].parent_id() << " (" << _cluster_tree[scale_id][cluster_id_in_vector].notes() << ")" << std::endl;
ss << "\tUnclusterd:\t" << unclustered_influence << std::endl;
scalar_type max(unclustered_influence);
int_type res_id(-1);
for (int i = 0; i < influence.size(); ++i) {
ss << "\tCluster-" << _cluster_tree[scale_id + 1][i].id() << " (" << _cluster_tree[scale_id + 1][i].notes() << ") :\t" << influence[i] << std::endl;
if (influence[i] > max) {
max = influence[i];
res_id = _cluster_tree[scale_id + 1][i].id();
}
}
utils::secureLog(_logger, ss.str());
if (res_id == _cluster_tree[scale_id][cluster_id_in_vector].parent_id()) {
utils::secureLog(_logger, "Valid");
return true;
}
utils::secureLog(_logger, "INVALID!");
return false;
}
template <typename scalar_type, typename sparse_scalar_matrix_type>
bool HierarchicalSNE<scalar_type, sparse_scalar_matrix_type>::ClusterTree::checkTreeConsistency(const HierarchicalSNE& hsne) {
bool res = true;
for (int s = _cluster_tree.size() - 1; s >= 0; --s) {
for (int c = 0; c < _cluster_tree[s].size(); ++c) {
res &= checkCluterConsistency(hsne, s, _cluster_tree[s][c].id());
}
}
return res;
}
template <typename scalar_type, typename sparse_scalar_matrix_type>
void HierarchicalSNE<scalar_type, sparse_scalar_matrix_type>::ClusterTree::computePointToClusterAssociation(const HierarchicalSNE& hsne, unsigned_int_type pnt_id, std::tuple<unsigned_int_type, int_type, scalar_type>& res) {
std::vector<std::unordered_map<unsigned_int_type, scalar_type>> influence;
hsne.getInfluenceOnDataPoint(pnt_id, influence);
res = std::tuple<unsigned_int_type, int_type, scalar_type>(_cluster_tree.size() - 1, -1, 1);
std::vector<unsigned_int_type> clusters_to_analyze(_cluster_tree[_cluster_tree.size() - 1].size());
std::iota(clusters_to_analyze.begin(), clusters_to_analyze.end(), 0);
//just for test
for (int s = _cluster_tree.size() - 1; s >= 0 && clusters_to_analyze.size(); --s) {
unsigned_int_type scale_id = s;
std::vector<scalar_type> cluster_influence(clusters_to_analyze.size(), 0);
scalar_type unclustered_influence(0);
for (auto aoi : influence[scale_id]) {
bool found = false;
for (int i = 0; i < clusters_to_analyze.size(); ++i) {
auto it = _cluster_tree[scale_id][clusters_to_analyze[i]].landmarks().find(aoi.first);
if (it != _cluster_tree[scale_id][clusters_to_analyze[i]].landmarks().end()) {
cluster_influence[i] += aoi.second;
found = true;
}
}
if (!found) {
unclustered_influence += aoi.second;
}
}
scalar_type max(unclustered_influence);
int_type cluster_id(-1);
for (int i = 0; i < clusters_to_analyze.size(); ++i) {
if (cluster_influence[i] > max) {
max = cluster_influence[i];
cluster_id = _cluster_tree[scale_id][clusters_to_analyze[i]].id();
}
}
if (cluster_id == -1) {
return;
}
res = std::tuple<unsigned_int_type, int_type, scalar_type>(scale_id, cluster_id, max);
//compute children nodes
clusters_to_analyze.clear();
if (s != 0) {
for (int i = 0; i < _cluster_tree[s - 1].size(); ++i) {
if (_cluster_tree[s - 1][i].parent_id() == cluster_id) {
clusters_to_analyze.push_back(i);
}
}
}
}
}
template <typename scalar_type, typename sparse_scalar_matrix_type>
void HierarchicalSNE<scalar_type, sparse_scalar_matrix_type>::ClusterTree::computePointsToClusterAssociation(const HierarchicalSNE& hsne, std::vector<std::tuple<unsigned_int_type, int_type, scalar_type>>& res) {
res.resize(hsne.scale(0).size());
//#ifdef __USE_GCD__
// std::cout << "GCD dispatch, hierarchical_sne_inl 1227.\n";
// dispatch_apply(res.size(), dispatch_get_global_queue(0, 0), ^(size_t i) {
//#else
#pragma omp parallel for
for (int i = 0; i < res.size(); ++i) {
//#endif //__USE_GCD__
computePointToClusterAssociation(hsne, i, res[i]);
}
//#ifdef __USE_GCD__
// );
//#endif
}
///////////////////////////////////////////////////////////////////////////////////7
namespace IO {
template <typename hsne_type, class output_stream_type>
void saveHSNE(const hsne_type& hsne, output_stream_type& stream, utils::AbstractLog* log) {
checkAndThrowLogic(hsne.hierarchy().size(), "Cannot save an empty H-SNE hierarchy!!!");
utils::secureLog(log, "Saving H-SNE hierarchy to file");
typedef float io_scalar_type;
typedef float io_unsigned_int_type;
//Version
io_unsigned_int_type major_version = 0;
io_unsigned_int_type minor_version = 0;
stream.write(reinterpret_cast<char*>(&major_version), sizeof(io_unsigned_int_type));
stream.write(reinterpret_cast<char*>(&minor_version), sizeof(io_unsigned_int_type));
//Number of scales
io_unsigned_int_type num_scales = static_cast<io_unsigned_int_type>(hsne.hierarchy().size());
stream.write(reinterpret_cast<char*>(&num_scales), sizeof(io_unsigned_int_type));
{
//The first scale contains only the transition matrix
auto& scale = hsne.scale(0);
io_unsigned_int_type n = static_cast<io_unsigned_int_type>(scale.size());
utils::secureLogValue(log, "Saving scale", 0);
utils::secureLog(log, "\tsize", n);
stream.write(reinterpret_cast<char*>(&n), sizeof(io_unsigned_int_type));
utils::secureLog(log, "\t... transition matrix ...");
data::IO::saveSparseMatrix(scale._transition_matrix, stream, log);
}
for (int s = 1; s < num_scales; ++s) {
auto& scale = hsne.scale(s);
io_unsigned_int_type n = static_cast<io_unsigned_int_type>(scale.size());
utils::secureLogValue(log, "Saving scale", s);
utils::secureLogValue(log, "\tsize", n);
stream.write(reinterpret_cast<char*>(&n), sizeof(io_unsigned_int_type));
utils::secureLog(log, "\t... transition matrix ...");
data::IO::saveSparseMatrix(scale._transition_matrix, stream, log);
utils::secureLog(log, "\t... landmarks to original data ...");
data::IO::saveUIntVector(scale._landmark_to_original_data_idx, stream, log);
utils::secureLog(log, "\t... landmarks to previous scale ...");
data::IO::saveUIntVector(scale._landmark_to_previous_scale_idx, stream, log);
utils::secureLog(log, "\t... landmark weights ...");
data::IO::saveScalarVector(scale._landmark_weight, stream, log);
utils::secureLog(log, "\t... previous scale to current scale landmarks ...");
data::IO::saveIntVector(scale._previous_scale_to_landmark_idx, stream, log);
utils::secureLog(log, "\t... area of influence ...");
data::IO::saveSparseMatrix(scale._area_of_influence, stream, log);
}
}
///////////////////////////////////////////////////////
template <typename hsne_type, class input_stream_type>
void loadHSNE(hsne_type& hsne, input_stream_type& stream, utils::AbstractLog* log) {
utils::secureLog(log, "Loading H-SNE hierarchy from file");
typedef float io_scalar_type;
typedef float io_unsigned_int_type;
//Version
io_unsigned_int_type major_version = 0;
io_unsigned_int_type minor_version = 0;
stream.read(reinterpret_cast<char*>(&major_version), sizeof(io_unsigned_int_type));
stream.read(reinterpret_cast<char*>(&minor_version), sizeof(io_unsigned_int_type));
checkAndThrowRuntime(major_version == 0, "Invalid major version");
checkAndThrowRuntime(minor_version == 0, "Invalid minor version");
//Number of scales
io_unsigned_int_type num_scales;
stream.read(reinterpret_cast<char*>(&num_scales), sizeof(io_unsigned_int_type));
checkAndThrowRuntime(num_scales > 0, "Cannot load an empty hierarchy");
{
hsne.hierarchy().clear();
hsne.hierarchy().push_back(typename hsne_type::Scale());
auto& scale = hsne.scale(0);
io_unsigned_int_type n = static_cast<io_unsigned_int_type>(scale.size());
utils::secureLogValue(log, "Loading scale", 0);
stream.read(reinterpret_cast<char*>(&n), sizeof(io_unsigned_int_type));
utils::secureLog(log, "\tsize", n);
utils::secureLog(log, "\t... transition matrix ...");
data::IO::loadSparseMatrix(scale._transition_matrix, stream, log);
utils::secureLog(log, "\t... (init) landmarks to original data ...");
scale._landmark_to_original_data_idx.resize(n);
std::iota(scale._landmark_to_original_data_idx.begin(), scale._landmark_to_original_data_idx.end(), 0);
utils::secureLog(log, "\t... (init) landmarks to previous scale ...");
scale._landmark_to_previous_scale_idx.resize(n);
std::iota(scale._landmark_to_previous_scale_idx.begin(), scale._landmark_to_previous_scale_idx.end(), 0);
utils::secureLog(log, "\t... (init) landmark weights ...");
scale._landmark_weight.resize(n, 1);
}
for (int s = 1; s < num_scales; ++s) {
hsne.hierarchy().push_back(typename hsne_type::Scale());
auto& scale = hsne.scale(s);
io_unsigned_int_type n;
utils::secureLogValue(log, "Loading scale", s);
stream.read(reinterpret_cast<char*>(&n), sizeof(io_unsigned_int_type));
utils::secureLogValue(log, "\tsize", n);
utils::secureLog(log, "\t... transition matrix ...");
data::IO::loadSparseMatrix(scale._transition_matrix, stream, log);
utils::secureLog(log, "\t... landmarks to original data ...");
data::IO::loadUIntVector(scale._landmark_to_original_data_idx, stream, log);
utils::secureLog(log, "\t... landmarks to previous scale ...");
data::IO::loadUIntVector(scale._landmark_to_previous_scale_idx, stream, log);
utils::secureLog(log, "\t... landmark weights ...");
data::IO::loadScalarVector(scale._landmark_weight, stream, log);
utils::secureLog(log, "\t... previous scale to current scale landmarks ...");
data::IO::loadIntVector(scale._previous_scale_to_landmark_idx, stream, log);
utils::secureLog(log, "\t... area of influence ...");
data::IO::loadSparseMatrix(scale._area_of_influence, stream, log);
}
}
}
}
}
#endif
|
yescrypt-simd.c
|
/*-
* Copyright 2009 Colin Percival
* Copyright 2012-2014 Alexander Peslyak
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* This file was originally written by Colin Percival as part of the Tarsnap
* online backup system.
*/
/*
* On 64-bit, enabling SSE4.1 helps our pwxform code indirectly, via avoiding
* gcc bug 54349 (fixed for gcc 4.9+). On 32-bit, it's of direct help. AVX
* and XOP are of further help either way.
*/
//#ifndef __SSE4_1__
//#warning "Consider enabling SSE4.1, AVX, or XOP in the C compiler for significantly better performance"
//#endif
#include <emmintrin.h>
#ifdef __XOP__
#include <x86intrin.h>
#endif
#include <errno.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include "sha256_Y.h"
#include "sysendian.h"
#include "sph/yescrypt.h"
#include "sph/yescrypt-platform.c"
#if __STDC_VERSION__ >= 199901L
/* have restrict */
#elif defined(__GNUC__)
#define restrict __restrict
#else
#define restrict
#endif
#define PREFETCH(x, hint) _mm_prefetch((const char *)(x), (hint));
#define PREFETCH_OUT(x, hint) /* disabled */
#ifdef __XOP__
#define ARX(out, in1, in2, s) \
out = _mm_xor_si128(out, _mm_roti_epi32(_mm_add_epi32(in1, in2), s));
#else
#define ARX(out, in1, in2, s) \
{ \
__m128i T = _mm_add_epi32(in1, in2); \
out = _mm_xor_si128(out, _mm_slli_epi32(T, s)); \
out = _mm_xor_si128(out, _mm_srli_epi32(T, 32-s)); \
}
#endif
#define SALSA20_2ROUNDS \
/* Operate on "columns" */ \
ARX(X1, X0, X3, 7) \
ARX(X2, X1, X0, 9) \
ARX(X3, X2, X1, 13) \
ARX(X0, X3, X2, 18) \
\
/* Rearrange data */ \
X1 = _mm_shuffle_epi32(X1, 0x93); \
X2 = _mm_shuffle_epi32(X2, 0x4E); \
X3 = _mm_shuffle_epi32(X3, 0x39); \
\
/* Operate on "rows" */ \
ARX(X3, X0, X1, 7) \
ARX(X2, X3, X0, 9) \
ARX(X1, X2, X3, 13) \
ARX(X0, X1, X2, 18) \
\
/* Rearrange data */ \
X1 = _mm_shuffle_epi32(X1, 0x39); \
X2 = _mm_shuffle_epi32(X2, 0x4E); \
X3 = _mm_shuffle_epi32(X3, 0x93);
/**
* Apply the salsa20/8 core to the block provided in (X0 ... X3).
*/
#define SALSA20_8_BASE(maybe_decl, out) \
{ \
maybe_decl Y0 = X0; \
maybe_decl Y1 = X1; \
maybe_decl Y2 = X2; \
maybe_decl Y3 = X3; \
SALSA20_2ROUNDS \
SALSA20_2ROUNDS \
SALSA20_2ROUNDS \
SALSA20_2ROUNDS \
(out)[0] = X0 = _mm_add_epi32(X0, Y0); \
(out)[1] = X1 = _mm_add_epi32(X1, Y1); \
(out)[2] = X2 = _mm_add_epi32(X2, Y2); \
(out)[3] = X3 = _mm_add_epi32(X3, Y3); \
}
#define SALSA20_8(out) \
SALSA20_8_BASE(__m128i, out)
/**
* Apply the salsa20/8 core to the block provided in (X0 ... X3) ^ (Z0 ... Z3).
*/
#define SALSA20_8_XOR_ANY(maybe_decl, Z0, Z1, Z2, Z3, out) \
X0 = _mm_xor_si128(X0, Z0); \
X1 = _mm_xor_si128(X1, Z1); \
X2 = _mm_xor_si128(X2, Z2); \
X3 = _mm_xor_si128(X3, Z3); \
SALSA20_8_BASE(maybe_decl, out)
#define SALSA20_8_XOR_MEM(in, out) \
SALSA20_8_XOR_ANY(__m128i, (in)[0], (in)[1], (in)[2], (in)[3], out)
#define SALSA20_8_XOR_REG(out) \
SALSA20_8_XOR_ANY(/* empty */, Y0, Y1, Y2, Y3, out)
typedef union {
uint32_t w[16];
__m128i q[4];
} salsa20_blk_t;
/**
* blockmix_salsa8(Bin, Bout, r):
* Compute Bout = BlockMix_{salsa20/8, r}(Bin). The input Bin must be 128r
* bytes in length; the output Bout must also be the same size.
*/
static inline void
blockmix_salsa8(const salsa20_blk_t *restrict Bin,
salsa20_blk_t *restrict Bout, size_t r)
{
__m128i X0, X1, X2, X3;
size_t i;
r--;
PREFETCH(&Bin[r * 2 + 1], _MM_HINT_T0)
for (i = 0; i < r; i++) {
PREFETCH(&Bin[i * 2], _MM_HINT_T0)
PREFETCH_OUT(&Bout[i], _MM_HINT_T0)
PREFETCH(&Bin[i * 2 + 1], _MM_HINT_T0)
PREFETCH_OUT(&Bout[r + 1 + i], _MM_HINT_T0)
}
PREFETCH(&Bin[r * 2], _MM_HINT_T0)
PREFETCH_OUT(&Bout[r], _MM_HINT_T0)
PREFETCH_OUT(&Bout[r * 2 + 1], _MM_HINT_T0)
/* 1: X <-- B_{2r - 1} */
X0 = Bin[r * 2 + 1].q[0];
X1 = Bin[r * 2 + 1].q[1];
X2 = Bin[r * 2 + 1].q[2];
X3 = Bin[r * 2 + 1].q[3];
/* 3: X <-- H(X \xor B_i) */
/* 4: Y_i <-- X */
/* 6: B' <-- (Y_0, Y_2 ... Y_{2r-2}, Y_1, Y_3 ... Y_{2r-1}) */
SALSA20_8_XOR_MEM(Bin[0].q, Bout[0].q)
/* 2: for i = 0 to 2r - 1 do */
for (i = 0; i < r;) {
/* 3: X <-- H(X \xor B_i) */
/* 4: Y_i <-- X */
/* 6: B' <-- (Y_0, Y_2 ... Y_{2r-2}, Y_1, Y_3 ... Y_{2r-1}) */
SALSA20_8_XOR_MEM(Bin[i * 2 + 1].q, Bout[r + 1 + i].q)
i++;
/* 3: X <-- H(X \xor B_i) */
/* 4: Y_i <-- X */
/* 6: B' <-- (Y_0, Y_2 ... Y_{2r-2}, Y_1, Y_3 ... Y_{2r-1}) */
SALSA20_8_XOR_MEM(Bin[i * 2].q, Bout[i].q)
}
/* 3: X <-- H(X \xor B_i) */
/* 4: Y_i <-- X */
/* 6: B' <-- (Y_0, Y_2 ... Y_{2r-2}, Y_1, Y_3 ... Y_{2r-1}) */
SALSA20_8_XOR_MEM(Bin[r * 2 + 1].q, Bout[r * 2 + 1].q)
}
/*
* (V)PSRLDQ and (V)PSHUFD have higher throughput than (V)PSRLQ on some CPUs
* starting with Sandy Bridge. Additionally, PSHUFD uses separate source and
* destination registers, whereas the shifts would require an extra move
* instruction for our code when building without AVX. Unfortunately, PSHUFD
* is much slower on Conroe (4 cycles latency vs. 1 cycle latency for PSRLQ)
* and somewhat slower on some non-Intel CPUs (luckily not including AMD
* Bulldozer and Piledriver). Since for many other CPUs using (V)PSHUFD is a
* win in terms of throughput or/and not needing a move instruction, we
* currently use it despite of the higher latency on some older CPUs. As an
* alternative, the #if below may be patched to only enable use of (V)PSHUFD
* when building with SSE4.1 or newer, which is not available on older CPUs
* where this instruction has higher latency.
*/
#if 1
#define HI32(X) \
_mm_shuffle_epi32((X), _MM_SHUFFLE(2,3,0,1))
#elif 0
#define HI32(X) \
_mm_srli_si128((X), 4)
#else
#define HI32(X) \
_mm_srli_epi64((X), 32)
#endif
#if defined(__x86_64__) && (defined(__ICC) || defined(__llvm__))
/* Intel's name, also supported by recent gcc */
#define EXTRACT64(X) _mm_cvtsi128_si64(X)
#elif defined(__x86_64__) && !defined(_MSC_VER) && !defined(__OPEN64__)
/* gcc got the 'x' name earlier than non-'x', MSVC and Open64 had bugs */
#define EXTRACT64(X) _mm_cvtsi128_si64x(X)
#elif defined(__x86_64__) && defined(__SSE4_1__)
/* No known bugs for this intrinsic */
#include <smmintrin.h>
#define EXTRACT64(X) _mm_extract_epi64((X), 0)
#elif defined(__SSE4_1__)
/* 32-bit */
#include <smmintrin.h>
#if 0
/* This is currently unused by the code below, which instead uses these two
* intrinsics explicitly when (!defined(__x86_64__) && defined(__SSE4_1__)) */
#define EXTRACT64(X) \
((uint64_t)(uint32_t)_mm_cvtsi128_si32(X) | \
((uint64_t)(uint32_t)_mm_extract_epi32((X), 1) << 32))
#endif
#else
/* 32-bit or compilers with known past bugs in _mm_cvtsi128_si64*() */
#define EXTRACT64(X) \
((uint64_t)(uint32_t)_mm_cvtsi128_si32(X) | \
((uint64_t)(uint32_t)_mm_cvtsi128_si32(HI32(X)) << 32))
#endif
/* This is tunable */
#define S_BITS 8
/* Not tunable in this implementation, hard-coded in a few places */
#define S_SIMD 2
#define S_P 4
/* Number of S-boxes. Not tunable by design, hard-coded in a few places. */
#define S_N 2
/* Derived values. Not tunable except via S_BITS above. */
#define S_SIZE1 (1 << S_BITS)
#define S_MASK ((S_SIZE1 - 1) * S_SIMD * 8)
#define S_MASK2 (((uint64_t)S_MASK << 32) | S_MASK)
#define S_SIZE_ALL (S_N * S_SIZE1 * S_SIMD * 8)
#if !defined(__x86_64__) && defined(__SSE4_1__)
/* 32-bit with SSE4.1 */
#define PWXFORM_X_T __m128i
#define PWXFORM_SIMD(X, x, s0, s1) \
x = _mm_and_si128(X, _mm_set1_epi64x(S_MASK2)); \
s0 = *(const __m128i *)(S0 + (uint32_t)_mm_cvtsi128_si32(x)); \
s1 = *(const __m128i *)(S1 + (uint32_t)_mm_extract_epi32(x, 1)); \
X = _mm_mul_epu32(HI32(X), X); \
X = _mm_add_epi64(X, s0); \
X = _mm_xor_si128(X, s1);
#else
/* 64-bit, or 32-bit without SSE4.1 */
#define PWXFORM_X_T uint64_t
#define PWXFORM_SIMD(X, x, s0, s1) \
x = EXTRACT64(X) & S_MASK2; \
s0 = *(const __m128i *)(S0 + (uint32_t)x); \
s1 = *(const __m128i *)(S1 + (x >> 32)); \
X = _mm_mul_epu32(HI32(X), X); \
X = _mm_add_epi64(X, s0); \
X = _mm_xor_si128(X, s1);
#endif
#define PWXFORM_ROUND \
PWXFORM_SIMD(X0, x0, s00, s01) \
PWXFORM_SIMD(X1, x1, s10, s11) \
PWXFORM_SIMD(X2, x2, s20, s21) \
PWXFORM_SIMD(X3, x3, s30, s31)
#define PWXFORM \
{ \
PWXFORM_X_T x0, x1, x2, x3; \
__m128i s00, s01, s10, s11, s20, s21, s30, s31; \
PWXFORM_ROUND PWXFORM_ROUND \
PWXFORM_ROUND PWXFORM_ROUND \
PWXFORM_ROUND PWXFORM_ROUND \
}
#define XOR4(in) \
X0 = _mm_xor_si128(X0, (in)[0]); \
X1 = _mm_xor_si128(X1, (in)[1]); \
X2 = _mm_xor_si128(X2, (in)[2]); \
X3 = _mm_xor_si128(X3, (in)[3]);
#define OUT(out) \
(out)[0] = X0; \
(out)[1] = X1; \
(out)[2] = X2; \
(out)[3] = X3;
/**
* blockmix_pwxform(Bin, Bout, r, S):
* Compute Bout = BlockMix_pwxform{salsa20/8, r, S}(Bin). The input Bin must
* be 128r bytes in length; the output Bout must also be the same size.
*/
static void
blockmix(const salsa20_blk_t *restrict Bin, salsa20_blk_t *restrict Bout,
size_t r, const __m128i *restrict S)
{
const uint8_t * S0, * S1;
__m128i X0, X1, X2, X3;
size_t i;
if (!S) {
blockmix_salsa8(Bin, Bout, r);
return;
}
S0 = (const uint8_t *)S;
S1 = (const uint8_t *)S + S_SIZE_ALL / 2;
/* Convert 128-byte blocks to 64-byte blocks */
r *= 2;
r--;
PREFETCH(&Bin[r], _MM_HINT_T0)
for (i = 0; i < r; i++) {
PREFETCH(&Bin[i], _MM_HINT_T0)
PREFETCH_OUT(&Bout[i], _MM_HINT_T0)
}
PREFETCH_OUT(&Bout[r], _MM_HINT_T0)
/* X <-- B_{r1 - 1} */
X0 = Bin[r].q[0];
X1 = Bin[r].q[1];
X2 = Bin[r].q[2];
X3 = Bin[r].q[3];
/* for i = 0 to r1 - 1 do */
for (i = 0; i < r; i++) {
/* X <-- H'(X \xor B_i) */
XOR4(Bin[i].q)
PWXFORM
/* B'_i <-- X */
OUT(Bout[i].q)
}
/* Last iteration of the loop above */
XOR4(Bin[i].q)
PWXFORM
/* B'_i <-- H(B'_i) */
SALSA20_8(Bout[i].q)
}
#define XOR4_2(in1, in2) \
X0 = _mm_xor_si128((in1)[0], (in2)[0]); \
X1 = _mm_xor_si128((in1)[1], (in2)[1]); \
X2 = _mm_xor_si128((in1)[2], (in2)[2]); \
X3 = _mm_xor_si128((in1)[3], (in2)[3]);
static inline uint32_t
blockmix_salsa8_xor(const salsa20_blk_t *restrict Bin1,
const salsa20_blk_t *restrict Bin2, salsa20_blk_t *restrict Bout,
size_t r, int Bin2_in_ROM)
{
__m128i X0, X1, X2, X3;
size_t i;
r--;
if (Bin2_in_ROM) {
PREFETCH(&Bin2[r * 2 + 1], _MM_HINT_NTA)
PREFETCH(&Bin1[r * 2 + 1], _MM_HINT_T0)
for (i = 0; i < r; i++) {
PREFETCH(&Bin2[i * 2], _MM_HINT_NTA)
PREFETCH(&Bin1[i * 2], _MM_HINT_T0)
PREFETCH(&Bin2[i * 2 + 1], _MM_HINT_NTA)
PREFETCH(&Bin1[i * 2 + 1], _MM_HINT_T0)
PREFETCH_OUT(&Bout[i], _MM_HINT_T0)
PREFETCH_OUT(&Bout[r + 1 + i], _MM_HINT_T0)
}
PREFETCH(&Bin2[r * 2], _MM_HINT_T0)
} else {
PREFETCH(&Bin2[r * 2 + 1], _MM_HINT_T0)
PREFETCH(&Bin1[r * 2 + 1], _MM_HINT_T0)
for (i = 0; i < r; i++) {
PREFETCH(&Bin2[i * 2], _MM_HINT_T0)
PREFETCH(&Bin1[i * 2], _MM_HINT_T0)
PREFETCH(&Bin2[i * 2 + 1], _MM_HINT_T0)
PREFETCH(&Bin1[i * 2 + 1], _MM_HINT_T0)
PREFETCH_OUT(&Bout[i], _MM_HINT_T0)
PREFETCH_OUT(&Bout[r + 1 + i], _MM_HINT_T0)
}
PREFETCH(&Bin2[r * 2], _MM_HINT_T0)
}
PREFETCH(&Bin1[r * 2], _MM_HINT_T0)
PREFETCH_OUT(&Bout[r], _MM_HINT_T0)
PREFETCH_OUT(&Bout[r * 2 + 1], _MM_HINT_T0)
/* 1: X <-- B_{2r - 1} */
XOR4_2(Bin1[r * 2 + 1].q, Bin2[r * 2 + 1].q)
/* 3: X <-- H(X \xor B_i) */
/* 4: Y_i <-- X */
/* 6: B' <-- (Y_0, Y_2 ... Y_{2r-2}, Y_1, Y_3 ... Y_{2r-1}) */
XOR4(Bin1[0].q)
SALSA20_8_XOR_MEM(Bin2[0].q, Bout[0].q)
/* 2: for i = 0 to 2r - 1 do */
for (i = 0; i < r;) {
/* 3: X <-- H(X \xor B_i) */
/* 4: Y_i <-- X */
/* 6: B' <-- (Y_0, Y_2 ... Y_{2r-2}, Y_1, Y_3 ... Y_{2r-1}) */
XOR4(Bin1[i * 2 + 1].q)
SALSA20_8_XOR_MEM(Bin2[i * 2 + 1].q, Bout[r + 1 + i].q)
i++;
/* 3: X <-- H(X \xor B_i) */
/* 4: Y_i <-- X */
/* 6: B' <-- (Y_0, Y_2 ... Y_{2r-2}, Y_1, Y_3 ... Y_{2r-1}) */
XOR4(Bin1[i * 2].q)
SALSA20_8_XOR_MEM(Bin2[i * 2].q, Bout[i].q)
}
/* 3: X <-- H(X \xor B_i) */
/* 4: Y_i <-- X */
/* 6: B' <-- (Y_0, Y_2 ... Y_{2r-2}, Y_1, Y_3 ... Y_{2r-1}) */
XOR4(Bin1[r * 2 + 1].q)
SALSA20_8_XOR_MEM(Bin2[r * 2 + 1].q, Bout[r * 2 + 1].q)
return _mm_cvtsi128_si32(X0);
}
static uint32_t
blockmix_xor(const salsa20_blk_t *restrict Bin1,
const salsa20_blk_t *restrict Bin2, salsa20_blk_t *restrict Bout,
size_t r, int Bin2_in_ROM, const __m128i *restrict S)
{
const uint8_t * S0, * S1;
__m128i X0, X1, X2, X3;
size_t i;
if (!S)
return blockmix_salsa8_xor(Bin1, Bin2, Bout, r, Bin2_in_ROM);
S0 = (const uint8_t *)S;
S1 = (const uint8_t *)S + S_SIZE_ALL / 2;
/* Convert 128-byte blocks to 64-byte blocks */
r *= 2;
r--;
if (Bin2_in_ROM) {
PREFETCH(&Bin2[r], _MM_HINT_NTA)
PREFETCH(&Bin1[r], _MM_HINT_T0)
for (i = 0; i < r; i++) {
PREFETCH(&Bin2[i], _MM_HINT_NTA)
PREFETCH(&Bin1[i], _MM_HINT_T0)
PREFETCH_OUT(&Bout[i], _MM_HINT_T0)
}
} else {
PREFETCH(&Bin2[r], _MM_HINT_T0)
PREFETCH(&Bin1[r], _MM_HINT_T0)
for (i = 0; i < r; i++) {
PREFETCH(&Bin2[i], _MM_HINT_T0)
PREFETCH(&Bin1[i], _MM_HINT_T0)
PREFETCH_OUT(&Bout[i], _MM_HINT_T0)
}
}
PREFETCH_OUT(&Bout[r], _MM_HINT_T0);
/* X <-- B_{r1 - 1} */
XOR4_2(Bin1[r].q, Bin2[r].q)
/* for i = 0 to r1 - 1 do */
for (i = 0; i < r; i++) {
/* X <-- H'(X \xor B_i) */
XOR4(Bin1[i].q)
XOR4(Bin2[i].q)
PWXFORM
/* B'_i <-- X */
OUT(Bout[i].q)
}
/* Last iteration of the loop above */
XOR4(Bin1[i].q)
XOR4(Bin2[i].q)
PWXFORM
/* B'_i <-- H(B'_i) */
SALSA20_8(Bout[i].q)
return _mm_cvtsi128_si32(X0);
}
#undef XOR4
#define XOR4(in, out) \
(out)[0] = Y0 = _mm_xor_si128((in)[0], (out)[0]); \
(out)[1] = Y1 = _mm_xor_si128((in)[1], (out)[1]); \
(out)[2] = Y2 = _mm_xor_si128((in)[2], (out)[2]); \
(out)[3] = Y3 = _mm_xor_si128((in)[3], (out)[3]);
static inline uint32_t
blockmix_salsa8_xor_save(const salsa20_blk_t *restrict Bin1,
salsa20_blk_t *restrict Bin2, salsa20_blk_t *restrict Bout,
size_t r)
{
__m128i X0, X1, X2, X3, Y0, Y1, Y2, Y3;
size_t i;
r--;
PREFETCH(&Bin2[r * 2 + 1], _MM_HINT_T0)
PREFETCH(&Bin1[r * 2 + 1], _MM_HINT_T0)
for (i = 0; i < r; i++) {
PREFETCH(&Bin2[i * 2], _MM_HINT_T0)
PREFETCH(&Bin1[i * 2], _MM_HINT_T0)
PREFETCH(&Bin2[i * 2 + 1], _MM_HINT_T0)
PREFETCH(&Bin1[i * 2 + 1], _MM_HINT_T0)
PREFETCH_OUT(&Bout[i], _MM_HINT_T0)
PREFETCH_OUT(&Bout[r + 1 + i], _MM_HINT_T0)
}
PREFETCH(&Bin2[r * 2], _MM_HINT_T0)
PREFETCH(&Bin1[r * 2], _MM_HINT_T0)
PREFETCH_OUT(&Bout[r], _MM_HINT_T0)
PREFETCH_OUT(&Bout[r * 2 + 1], _MM_HINT_T0)
/* 1: X <-- B_{2r - 1} */
XOR4_2(Bin1[r * 2 + 1].q, Bin2[r * 2 + 1].q)
/* 3: X <-- H(X \xor B_i) */
/* 4: Y_i <-- X */
/* 6: B' <-- (Y_0, Y_2 ... Y_{2r-2}, Y_1, Y_3 ... Y_{2r-1}) */
XOR4(Bin1[0].q, Bin2[0].q)
SALSA20_8_XOR_REG(Bout[0].q)
/* 2: for i = 0 to 2r - 1 do */
for (i = 0; i < r;) {
/* 3: X <-- H(X \xor B_i) */
/* 4: Y_i <-- X */
/* 6: B' <-- (Y_0, Y_2 ... Y_{2r-2}, Y_1, Y_3 ... Y_{2r-1}) */
XOR4(Bin1[i * 2 + 1].q, Bin2[i * 2 + 1].q)
SALSA20_8_XOR_REG(Bout[r + 1 + i].q)
i++;
/* 3: X <-- H(X \xor B_i) */
/* 4: Y_i <-- X */
/* 6: B' <-- (Y_0, Y_2 ... Y_{2r-2}, Y_1, Y_3 ... Y_{2r-1}) */
XOR4(Bin1[i * 2].q, Bin2[i * 2].q)
SALSA20_8_XOR_REG(Bout[i].q)
}
/* 3: X <-- H(X \xor B_i) */
/* 4: Y_i <-- X */
/* 6: B' <-- (Y_0, Y_2 ... Y_{2r-2}, Y_1, Y_3 ... Y_{2r-1}) */
XOR4(Bin1[r * 2 + 1].q, Bin2[r * 2 + 1].q)
SALSA20_8_XOR_REG(Bout[r * 2 + 1].q)
return _mm_cvtsi128_si32(X0);
}
#define XOR4_Y \
X0 = _mm_xor_si128(X0, Y0); \
X1 = _mm_xor_si128(X1, Y1); \
X2 = _mm_xor_si128(X2, Y2); \
X3 = _mm_xor_si128(X3, Y3);
static uint32_t
blockmix_xor_save(const salsa20_blk_t *restrict Bin1,
salsa20_blk_t *restrict Bin2, salsa20_blk_t *restrict Bout,
size_t r, const __m128i *restrict S)
{
const uint8_t * S0, * S1;
__m128i X0, X1, X2, X3, Y0, Y1, Y2, Y3;
size_t i;
if (!S)
return blockmix_salsa8_xor_save(Bin1, Bin2, Bout, r);
S0 = (const uint8_t *)S;
S1 = (const uint8_t *)S + S_SIZE_ALL / 2;
/* Convert 128-byte blocks to 64-byte blocks */
r *= 2;
r--;
PREFETCH(&Bin2[r], _MM_HINT_T0)
PREFETCH(&Bin1[r], _MM_HINT_T0)
for (i = 0; i < r; i++) {
PREFETCH(&Bin2[i], _MM_HINT_T0)
PREFETCH(&Bin1[i], _MM_HINT_T0)
PREFETCH_OUT(&Bout[i], _MM_HINT_T0)
}
PREFETCH_OUT(&Bout[r], _MM_HINT_T0);
/* X <-- B_{r1 - 1} */
XOR4_2(Bin1[r].q, Bin2[r].q)
/* for i = 0 to r1 - 1 do */
for (i = 0; i < r; i++) {
XOR4(Bin1[i].q, Bin2[i].q)
/* X <-- H'(X \xor B_i) */
XOR4_Y
PWXFORM
/* B'_i <-- X */
OUT(Bout[i].q)
}
/* Last iteration of the loop above */
XOR4(Bin1[i].q, Bin2[i].q)
XOR4_Y
PWXFORM
/* B'_i <-- H(B'_i) */
SALSA20_8(Bout[i].q)
return _mm_cvtsi128_si32(X0);
}
#undef ARX
#undef SALSA20_2ROUNDS
#undef SALSA20_8
#undef SALSA20_8_XOR_ANY
#undef SALSA20_8_XOR_MEM
#undef SALSA20_8_XOR_REG
#undef PWXFORM_SIMD_1
#undef PWXFORM_SIMD_2
#undef PWXFORM_ROUND
#undef PWXFORM
#undef OUT
#undef XOR4
#undef XOR4_2
#undef XOR4_Y
/**
* integerify(B, r):
* Return the result of parsing B_{2r-1} as a little-endian integer.
*/
static inline uint32_t
integerify(const salsa20_blk_t * B, size_t r)
{
return B[2 * r - 1].w[0];
}
/**
* smix1(B, r, N, flags, V, NROM, shared, XY, S):
* Compute first loop of B = SMix_r(B, N). The input B must be 128r bytes in
* length; the temporary storage V must be 128rN bytes in length; the temporary
* storage XY must be 128r bytes in length. The value N must be even and no
* smaller than 2. The array V must be aligned to a multiple of 64 bytes, and
* arrays B and XY to a multiple of at least 16 bytes (aligning them to 64
* bytes as well saves cache lines, but might result in cache bank conflicts).
*/
static void
smix1(uint8_t * B, size_t r, uint32_t N, yescrypt_flags_t flags,
salsa20_blk_t * V, uint32_t NROM, const yescrypt_shared_t * shared,
salsa20_blk_t * XY, void * S)
{
const salsa20_blk_t * VROM = shared->shared1.aligned;
uint32_t VROM_mask = shared->mask1;
size_t s = 2 * r;
salsa20_blk_t * X = V, * Y;
uint32_t i, j;
size_t k;
/* 1: X <-- B */
/* 3: V_i <-- X */
for (k = 0; k < 2 * r; k++) {
for (i = 0; i < 16; i++) {
X[k].w[i] = le32dec(&B[(k * 16 + (i * 5 % 16)) * 4]);
}
}
if (NROM && (VROM_mask & 1)) {
uint32_t n;
salsa20_blk_t * V_n;
const salsa20_blk_t * V_j;
/* 4: X <-- H(X) */
/* 3: V_i <-- X */
Y = &V[s];
blockmix(X, Y, r, S);
X = &V[2 * s];
if ((1 & VROM_mask) == 1) {
/* j <-- Integerify(X) mod NROM */
j = integerify(Y, r) & (NROM - 1);
V_j = &VROM[j * s];
/* X <-- H(X \xor VROM_j) */
j = blockmix_xor(Y, V_j, X, r, 1, S);
} else {
/* X <-- H(X) */
blockmix(Y, X, r, S);
j = integerify(X, r);
}
for (n = 2; n < N; n <<= 1) {
uint32_t m = (n < N / 2) ? n : (N - 1 - n);
V_n = &V[n * s];
/* 2: for i = 0 to N - 1 do */
for (i = 1; i < m; i += 2) {
/* j <-- Wrap(Integerify(X), i) */
j &= n - 1;
j += i - 1;
V_j = &V[j * s];
/* X <-- X \xor V_j */
/* 4: X <-- H(X) */
/* 3: V_i <-- X */
Y = &V_n[i * s];
j = blockmix_xor(X, V_j, Y, r, 0, S);
if (((n + i) & VROM_mask) == 1) {
/* j <-- Integerify(X) mod NROM */
j &= NROM - 1;
V_j = &VROM[j * s];
} else {
/* j <-- Wrap(Integerify(X), i) */
j &= n - 1;
j += i;
V_j = &V[j * s];
}
/* X <-- H(X \xor VROM_j) */
X = &V_n[(i + 1) * s];
j = blockmix_xor(Y, V_j, X, r, 1, S);
}
}
n >>= 1;
/* j <-- Wrap(Integerify(X), i) */
j &= n - 1;
j += N - 2 - n;
V_j = &V[j * s];
/* X <-- X \xor V_j */
/* 4: X <-- H(X) */
/* 3: V_i <-- X */
Y = &V[(N - 1) * s];
j = blockmix_xor(X, V_j, Y, r, 0, S);
if (((N - 1) & VROM_mask) == 1) {
/* j <-- Integerify(X) mod NROM */
j &= NROM - 1;
V_j = &VROM[j * s];
} else {
/* j <-- Wrap(Integerify(X), i) */
j &= n - 1;
j += N - 1 - n;
V_j = &V[j * s];
}
/* X <-- X \xor V_j */
/* 4: X <-- H(X) */
X = XY;
blockmix_xor(Y, V_j, X, r, 1, S);
} else if (flags & YESCRYPT_RW) {
uint32_t n;
salsa20_blk_t * V_n, * V_j;
/* 4: X <-- H(X) */
/* 3: V_i <-- X */
Y = &V[s];
blockmix(X, Y, r, S);
/* 4: X <-- H(X) */
/* 3: V_i <-- X */
X = &V[2 * s];
blockmix(Y, X, r, S);
j = integerify(X, r);
for (n = 2; n < N; n <<= 1) {
uint32_t m = (n < N / 2) ? n : (N - 1 - n);
V_n = &V[n * s];
/* 2: for i = 0 to N - 1 do */
for (i = 1; i < m; i += 2) {
Y = &V_n[i * s];
/* j <-- Wrap(Integerify(X), i) */
j &= n - 1;
j += i - 1;
V_j = &V[j * s];
/* X <-- X \xor V_j */
/* 4: X <-- H(X) */
/* 3: V_i <-- X */
j = blockmix_xor(X, V_j, Y, r, 0, S);
/* j <-- Wrap(Integerify(X), i) */
j &= n - 1;
j += i;
V_j = &V[j * s];
/* X <-- X \xor V_j */
/* 4: X <-- H(X) */
/* 3: V_i <-- X */
X = &V_n[(i + 1) * s];
j = blockmix_xor(Y, V_j, X, r, 0, S);
}
}
n >>= 1;
/* j <-- Wrap(Integerify(X), i) */
j &= n - 1;
j += N - 2 - n;
V_j = &V[j * s];
/* X <-- X \xor V_j */
/* 4: X <-- H(X) */
/* 3: V_i <-- X */
Y = &V[(N - 1) * s];
j = blockmix_xor(X, V_j, Y, r, 0, S);
/* j <-- Wrap(Integerify(X), i) */
j &= n - 1;
j += N - 1 - n;
V_j = &V[j * s];
/* X <-- X \xor V_j */
/* 4: X <-- H(X) */
X = XY;
blockmix_xor(Y, V_j, X, r, 0, S);
} else {
/* 2: for i = 0 to N - 1 do */
for (i = 1; i < N - 1; i += 2) {
/* 4: X <-- H(X) */
/* 3: V_i <-- X */
Y = &V[i * s];
blockmix(X, Y, r, S);
/* 4: X <-- H(X) */
/* 3: V_i <-- X */
X = &V[(i + 1) * s];
blockmix(Y, X, r, S);
}
/* 4: X <-- H(X) */
/* 3: V_i <-- X */
Y = &V[i * s];
blockmix(X, Y, r, S);
/* 4: X <-- H(X) */
X = XY;
blockmix(Y, X, r, S);
}
/* B' <-- X */
for (k = 0; k < 2 * r; k++) {
for (i = 0; i < 16; i++) {
le32enc(&B[(k * 16 + (i * 5 % 16)) * 4], X[k].w[i]);
}
}
}
/**
* smix2(B, r, N, Nloop, flags, V, NROM, shared, XY, S):
* Compute second loop of B = SMix_r(B, N). The input B must be 128r bytes in
* length; the temporary storage V must be 128rN bytes in length; the temporary
* storage XY must be 256r bytes in length. The value N must be a power of 2
* greater than 1. The value Nloop must be even. The array V must be aligned
* to a multiple of 64 bytes, and arrays B and XY to a multiple of at least 16
* bytes (aligning them to 64 bytes as well saves cache lines, but might result
* in cache bank conflicts).
*/
static void
smix2(uint8_t * B, size_t r, uint32_t N, uint64_t Nloop,
yescrypt_flags_t flags, salsa20_blk_t * V, uint32_t NROM,
const yescrypt_shared_t * shared, salsa20_blk_t * XY, void * S)
{
const salsa20_blk_t * VROM = shared->shared1.aligned;
uint32_t VROM_mask = shared->mask1;
size_t s = 2 * r;
salsa20_blk_t * X = XY, * Y = &XY[s];
uint64_t i;
uint32_t j;
size_t k;
if (Nloop == 0)
return;
/* X <-- B' */
/* 3: V_i <-- X */
for (k = 0; k < 2 * r; k++) {
for (i = 0; i < 16; i++) {
X[k].w[i] = le32dec(&B[(k * 16 + (i * 5 % 16)) * 4]);
}
}
i = Nloop / 2;
/* 7: j <-- Integerify(X) mod N */
j = integerify(X, r) & (N - 1);
/*
* Normally, NROM implies YESCRYPT_RW, but we check for these separately
* because YESCRYPT_PARALLEL_SMIX resets YESCRYPT_RW for the smix2() calls
* operating on the entire V.
*/
if (NROM && (flags & YESCRYPT_RW)) {
/* 6: for i = 0 to N - 1 do */
for (i = 0; i < Nloop; i += 2) {
salsa20_blk_t * V_j = &V[j * s];
/* 8: X <-- H(X \xor V_j) */
/* V_j <-- Xprev \xor V_j */
/* j <-- Integerify(X) mod NROM */
j = blockmix_xor_save(X, V_j, Y, r, S);
if (((i + 1) & VROM_mask) == 1) {
const salsa20_blk_t * VROM_j;
j &= NROM - 1;
VROM_j = &VROM[j * s];
/* X <-- H(X \xor VROM_j) */
/* 7: j <-- Integerify(X) mod N */
j = blockmix_xor(Y, VROM_j, X, r, 1, S);
} else {
j &= N - 1;
V_j = &V[j * s];
/* 8: X <-- H(X \xor V_j) */
/* V_j <-- Xprev \xor V_j */
/* j <-- Integerify(X) mod NROM */
j = blockmix_xor_save(Y, V_j, X, r, S);
}
j &= N - 1;
V_j = &V[j * s];
}
} else if (NROM) {
/* 6: for i = 0 to N - 1 do */
for (i = 0; i < Nloop; i += 2) {
const salsa20_blk_t * V_j = &V[j * s];
/* 8: X <-- H(X \xor V_j) */
/* V_j <-- Xprev \xor V_j */
/* j <-- Integerify(X) mod NROM */
j = blockmix_xor(X, V_j, Y, r, 0, S);
if (((i + 1) & VROM_mask) == 1) {
j &= NROM - 1;
V_j = &VROM[j * s];
} else {
j &= N - 1;
V_j = &V[j * s];
}
/* X <-- H(X \xor VROM_j) */
/* 7: j <-- Integerify(X) mod N */
j = blockmix_xor(Y, V_j, X, r, 1, S);
j &= N - 1;
V_j = &V[j * s];
}
} else if (flags & YESCRYPT_RW) {
/* 6: for i = 0 to N - 1 do */
do {
salsa20_blk_t * V_j = &V[j * s];
/* 8: X <-- H(X \xor V_j) */
/* V_j <-- Xprev \xor V_j */
/* 7: j <-- Integerify(X) mod N */
j = blockmix_xor_save(X, V_j, Y, r, S);
j &= N - 1;
V_j = &V[j * s];
/* 8: X <-- H(X \xor V_j) */
/* V_j <-- Xprev \xor V_j */
/* 7: j <-- Integerify(X) mod N */
j = blockmix_xor_save(Y, V_j, X, r, S);
j &= N - 1;
} while (--i);
} else {
/* 6: for i = 0 to N - 1 do */
do {
const salsa20_blk_t * V_j = &V[j * s];
/* 8: X <-- H(X \xor V_j) */
/* 7: j <-- Integerify(X) mod N */
j = blockmix_xor(X, V_j, Y, r, 0, S);
j &= N - 1;
V_j = &V[j * s];
/* 8: X <-- H(X \xor V_j) */
/* 7: j <-- Integerify(X) mod N */
j = blockmix_xor(Y, V_j, X, r, 0, S);
j &= N - 1;
} while (--i);
}
/* 10: B' <-- X */
for (k = 0; k < 2 * r; k++) {
for (i = 0; i < 16; i++) {
le32enc(&B[(k * 16 + (i * 5 % 16)) * 4], X[k].w[i]);
}
}
}
/**
* p2floor(x):
* Largest power of 2 not greater than argument.
*/
static uint64_t
p2floor(uint64_t x)
{
uint64_t y;
while ((y = x & (x - 1)))
x = y;
return x;
}
/**
* smix(B, r, N, p, t, flags, V, NROM, shared, XY, S):
* Compute B = SMix_r(B, N). The input B must be 128rp bytes in length; the
* temporary storage V must be 128rN bytes in length; the temporary storage XY
* must be 256r or 256rp bytes in length (the larger size is required with
* OpenMP-enabled builds). The value N must be a power of 2 greater than 1.
* The array V must be aligned to a multiple of 64 bytes, and arrays B and
* XY to a multiple of at least 16 bytes (aligning them to 64 bytes as well
* saves cache lines and helps avoid false sharing in OpenMP-enabled builds
* when p > 1, but it might also result in cache bank conflicts).
*/
static void
smix(uint8_t * B, size_t r, uint32_t N, uint32_t p, uint32_t t,
yescrypt_flags_t flags,
salsa20_blk_t * V, uint32_t NROM, const yescrypt_shared_t * shared,
salsa20_blk_t * XY, void * S)
{
size_t s = 2 * r;
uint32_t Nchunk = N / p;
uint64_t Nloop_all, Nloop_rw;
uint32_t i;
Nloop_all = Nchunk;
if (flags & YESCRYPT_RW) {
if (t <= 1) {
if (t)
Nloop_all *= 2; /* 2/3 */
Nloop_all = (Nloop_all + 2) / 3; /* 1/3, round up */
} else {
Nloop_all *= t - 1;
}
} else if (t) {
if (t == 1)
Nloop_all += (Nloop_all + 1) / 2; /* 1.5, round up */
Nloop_all *= t;
}
Nloop_rw = 0;
if (flags & __YESCRYPT_INIT_SHARED)
Nloop_rw = Nloop_all;
else if (flags & YESCRYPT_RW)
Nloop_rw = Nloop_all / p;
Nchunk &= ~(uint32_t)1; /* round down to even */
Nloop_all++; Nloop_all &= ~(uint64_t)1; /* round up to even */
Nloop_rw &= ~(uint64_t)1; /* round down to even */
#ifdef _OPENMP
#pragma omp parallel if (p > 1) default(none) private(i) shared(B, r, N, p, flags, V, NROM, shared, XY, S, s, Nchunk, Nloop_all, Nloop_rw)
{
#pragma omp for
#endif
for (i = 0; i < p; i++) {
uint32_t Vchunk = i * Nchunk;
uint8_t * Bp = &B[128 * r * i];
salsa20_blk_t * Vp = &V[Vchunk * s];
#ifdef _OPENMP
salsa20_blk_t * XYp = &XY[i * (2 * s)];
#else
salsa20_blk_t * XYp = XY;
#endif
uint32_t Np = (i < p - 1) ? Nchunk : (N - Vchunk);
void * Sp = S ? ((uint8_t *)S + i * S_SIZE_ALL) : S;
if (Sp)
smix1(Bp, 1, S_SIZE_ALL / 128,
flags & ~YESCRYPT_PWXFORM,
Sp, NROM, shared, XYp, NULL);
if (!(flags & __YESCRYPT_INIT_SHARED_2))
smix1(Bp, r, Np, flags, Vp, NROM, shared, XYp, Sp);
smix2(Bp, r, p2floor(Np), Nloop_rw, flags, Vp,
NROM, shared, XYp, Sp);
}
if (Nloop_all > Nloop_rw) {
#ifdef _OPENMP
#pragma omp for
#endif
for (i = 0; i < p; i++) {
uint8_t * Bp = &B[128 * r * i];
#ifdef _OPENMP
salsa20_blk_t * XYp = &XY[i * (2 * s)];
#else
salsa20_blk_t * XYp = XY;
#endif
void * Sp = S ? ((uint8_t *)S + i * S_SIZE_ALL) : S;
smix2(Bp, r, N, Nloop_all - Nloop_rw,
flags & ~YESCRYPT_RW, V, NROM, shared, XYp, Sp);
}
}
#ifdef _OPENMP
}
#endif
}
/**
* yescrypt_kdf(shared, local, passwd, passwdlen, salt, saltlen,
* N, r, p, t, flags, buf, buflen):
* Compute scrypt(passwd[0 .. passwdlen - 1], salt[0 .. saltlen - 1], N, r,
* p, buflen), or a revision of scrypt as requested by flags and shared, and
* write the result into buf. The parameters r, p, and buflen must satisfy
* r * p < 2^30 and buflen <= (2^32 - 1) * 32. The parameter N must be a power
* of 2 greater than 1. (This optimized implementation currently additionally
* limits N to the range from 8 to 2^31, but other implementation might not.)
*
* t controls computation time while not affecting peak memory usage. shared
* and flags may request special modes as described in yescrypt.h. local is
* the thread-local data structure, allowing to preserve and reuse a memory
* allocation across calls, thereby reducing its overhead.
*
* Return 0 on success; or -1 on error.
*/
int
yescrypt_kdf(const yescrypt_shared_t * shared, yescrypt_local_t * local,
const uint8_t * passwd, size_t passwdlen,
const uint8_t * salt, size_t saltlen,
uint64_t N, uint32_t r, uint32_t p, uint32_t t, yescrypt_flags_t flags,
uint8_t * buf, size_t buflen)
{
yescrypt_region_t tmp;
uint64_t NROM;
size_t B_size, V_size, XY_size, need;
uint8_t * B, * S;
salsa20_blk_t * V, * XY;
uint8_t sha256[32];
/*
* YESCRYPT_PARALLEL_SMIX is a no-op at p = 1 for its intended purpose,
* so don't let it have side-effects. Without this adjustment, it'd
* enable the SHA-256 password pre-hashing and output post-hashing,
* because any deviation from classic scrypt implies those.
*/
if (p == 1)
flags &= ~YESCRYPT_PARALLEL_SMIX;
/* Sanity-check parameters */
if (flags & ~YESCRYPT_KNOWN_FLAGS) {
errno = EINVAL;
return -1;
}
#if SIZE_MAX > UINT32_MAX
if (buflen > (((uint64_t)(1) << 32) - 1) * 32) {
errno = EFBIG;
return -1;
}
#endif
if ((uint64_t)(r) * (uint64_t)(p) >= (1 << 30)) {
errno = EFBIG;
return -1;
}
if (N > UINT32_MAX) {
errno = EFBIG;
return -1;
}
if (((N & (N - 1)) != 0) || (N <= 7) || (r < 1) || (p < 1)) {
errno = EINVAL;
return -1;
}
if ((flags & YESCRYPT_PARALLEL_SMIX) && (N / p <= 7)) {
errno = EINVAL;
return -1;
}
if ((r > SIZE_MAX / 256 / p) ||
(N > SIZE_MAX / 128 / r)) {
errno = ENOMEM;
return -1;
}
#ifdef _OPENMP
if (!(flags & YESCRYPT_PARALLEL_SMIX) &&
(N > SIZE_MAX / 128 / (r * p))) {
errno = ENOMEM;
return -1;
}
#endif
if ((flags & YESCRYPT_PWXFORM) &&
#ifndef _OPENMP
(flags & YESCRYPT_PARALLEL_SMIX) &&
#endif
p > SIZE_MAX / S_SIZE_ALL) {
errno = ENOMEM;
return -1;
}
NROM = 0;
if (shared->shared1.aligned) {
NROM = shared->shared1.aligned_size / ((size_t)128 * r);
if (NROM > UINT32_MAX) {
errno = EFBIG;
return -1;
}
if (((NROM & (NROM - 1)) != 0) || (NROM <= 7) ||
!(flags & YESCRYPT_RW)) {
errno = EINVAL;
return -1;
}
}
/* Allocate memory */
V = NULL;
V_size = (size_t)128 * r * N;
#ifdef _OPENMP
if (!(flags & YESCRYPT_PARALLEL_SMIX))
V_size *= p;
#endif
need = V_size;
if (flags & __YESCRYPT_INIT_SHARED) {
if (local->aligned_size < need) {
if (local->base || local->aligned ||
local->base_size || local->aligned_size) {
errno = EINVAL;
return -1;
}
if (!alloc_region(local, need))
return -1;
}
V = (salsa20_blk_t *)local->aligned;
need = 0;
}
B_size = (size_t)128 * r * p;
need += B_size;
if (need < B_size) {
errno = ENOMEM;
return -1;
}
XY_size = (size_t)256 * r;
#ifdef _OPENMP
XY_size *= p;
#endif
need += XY_size;
if (need < XY_size) {
errno = ENOMEM;
return -1;
}
if (flags & YESCRYPT_PWXFORM) {
size_t S_size = S_SIZE_ALL;
#ifdef _OPENMP
S_size *= p;
#else
if (flags & YESCRYPT_PARALLEL_SMIX)
S_size *= p;
#endif
need += S_size;
if (need < S_size) {
errno = ENOMEM;
return -1;
}
}
if (flags & __YESCRYPT_INIT_SHARED) {
if (!alloc_region(&tmp, need))
return -1;
B = (uint8_t *)tmp.aligned;
XY = (salsa20_blk_t *)((uint8_t *)B + B_size);
} else {
init_region(&tmp);
if (local->aligned_size < need) {
if (free_region(local))
return -1;
if (!alloc_region(local, need))
return -1;
}
B = (uint8_t *)local->aligned;
V = (salsa20_blk_t *)((uint8_t *)B + B_size);
XY = (salsa20_blk_t *)((uint8_t *)V + V_size);
}
S = NULL;
if (flags & YESCRYPT_PWXFORM)
S = (uint8_t *)XY + XY_size;
if (t || flags) {
SHA256_CTX_Y ctx;
SHA256_Init_Y(&ctx);
SHA256_Update_Y(&ctx, passwd, passwdlen);
SHA256_Final_Y(sha256, &ctx);
passwd = sha256;
passwdlen = sizeof(sha256);
}
/* 1: (B_0 ... B_{p-1}) <-- PBKDF2(P, S, 1, p * MFLen) */
PBKDF2_SHA256(passwd, passwdlen, salt, saltlen, 1, B, B_size);
if (t || flags)
memcpy(sha256, B, sizeof(sha256));
if (p == 1 || (flags & YESCRYPT_PARALLEL_SMIX)) {
smix(B, r, N, p, t, flags, V, NROM, shared, XY, S);
} else {
uint32_t i;
/* 2: for i = 0 to p - 1 do */
#ifdef _OPENMP
#pragma omp parallel for default(none) private(i) shared(B, r, N, p, t, flags, V, NROM, shared, XY, S)
#endif
for (i = 0; i < p; i++) {
/* 3: B_i <-- MF(B_i, N) */
#ifdef _OPENMP
smix(&B[(size_t)128 * r * i], r, N, 1, t, flags,
&V[(size_t)2 * r * i * N],
NROM, shared,
&XY[(size_t)4 * r * i],
S ? &S[S_SIZE_ALL * i] : S);
#else
smix(&B[(size_t)128 * r * i], r, N, 1, t, flags, V,
NROM, shared, XY, S);
#endif
}
}
/* 5: DK <-- PBKDF2(P, B, 1, dkLen) */
PBKDF2_SHA256(passwd, passwdlen, B, B_size, 1, buf, buflen);
/*
* Except when computing classic scrypt, allow all computation so far
* to be performed on the client. The final steps below match those of
* SCRAM (RFC 5802), so that an extension of SCRAM (with the steps so
* far in place of SCRAM's use of PBKDF2 and with SHA-256 in place of
* SCRAM's use of SHA-1) would be usable with yescrypt hashes.
*/
if ((t || flags) && buflen == sizeof(sha256)) {
/* Compute ClientKey */
{
HMAC_SHA256_CTX_Y ctx;
HMAC_SHA256_Init_Y(&ctx, buf, buflen);
#if 0
/* Proper yescrypt */
HMAC_SHA256_Update_Y(&ctx, "Client Key", 10);
#else
/* GlobalBoost-Y buggy yescrypt */
HMAC_SHA256_Update_Y(&ctx, salt, saltlen);
#endif
HMAC_SHA256_Final_Y(sha256, &ctx);
}
/* Compute StoredKey */
{
SHA256_CTX_Y ctx;
SHA256_Init_Y(&ctx);
SHA256_Update_Y(&ctx, sha256, sizeof(sha256));
SHA256_Final_Y(buf, &ctx);
}
}
if (free_region(&tmp))
return -1;
/* Success! */
return 0;
}
|
darts-wrong.c
|
#include <stdio.h>
#include <omp.h>
#include "lcgenerator.h"
#include <mpi.h>
// This code gets the wrong answer.
static long num_trials = 1000000;
int main(int argc, char **argv) {
long i;
long Ncirc = 0;
double pi, x, y;
double r = 1.0; // radius of circle
double r2 = r*r;
int rank, size, manager = 0;
MPI_Status status;
long my_trials, temp;
int provided;
MPI_Init_thread(&argc, &argv, MPI_THREAD_MULTIPLE, &provided);
MPI_Comm_size(MPI_COMM_WORLD, &size);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
my_trials = num_trials/size;
if (num_trials%(long)size > (long)rank) my_trials++;
random_last = rank;
#pragma omp parallel
{
#pragma omp for private(x,y) reduction(+:Ncirc)
for (i = 0; i < num_trials; i++) {
x = lcgrandom();
y = lcgrandom();
if ((x*x + y*y) <= r2)
Ncirc++;
}
}
MPI_Reduce(&Ncirc, &temp, 1, MPI_LONG, MPI_SUM, manager, MPI_COMM_WORLD);
if (rank == manager) {
Ncirc = temp;
pi = 4.0 * ((double)Ncirc)/((double)num_trials);
printf("\n For %ld trials, pi = %f\n", num_trials, pi);
}
MPI_Finalize();
return 0;
}
|
task1_omp.c
|
#include <math.h>
#include <string.h>
#include "timer.h"
#include <stdio.h>
#define NN 1024
#define NM 1024
float A[NN][NM];
float Anew[NN][NM];
int main(int argc, char** argv)
{
int i,j;
const int n = NN;
const int m = NM;
const int iter_max = 1000;
const double tol = 1.0e-6;
double error = 1.0;
memset(A, 0, n * m * sizeof(float));
memset(Anew, 0, n * m * sizeof(float));
for (j = 0; j < n; j++)
{
A[j][0] = 1.0;
Anew[j][0] = 1.0;
}
printf("Jacobi relaxation Calculation: %d x %d mesh\n", n, m);
StartTimer();
int iter = 0;
while ( error > tol && iter < iter_max )
{
error = 0.0;
#pragma omp parallel for shared(m, n, Anew, A)
for( j = 1; j < n-1; j++)
{
for( i = 1; i < m-1; i++ )
{
Anew[j][i] = 0.25 * ( A[j][i+1] + A[j][i-1]
+ A[j-1][i] + A[j+1][i]);
error = fmax( error, fabs(Anew[j][i] - A[j][i]));
}
}
#pragma omp parallel for shared(m, n, Anew, A)
for( j = 1; j < n-1; j++)
{
for( i = 1; i < m-1; i++ )
{
A[j][i] = Anew[j][i];
}
}
if(iter % 100 == 0) printf("%5d, %0.6f\n", iter, error);
iter++;
}
double runtime = GetTimer();
printf(" total: %f s\n", runtime / 1000);
}
|
channel.c
|
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% CCCC H H AAA N N N N EEEEE L %
% C H H A A NN N NN N E L %
% C HHHHH AAAAA N N N N N N EEE L %
% C H H A A N NN N NN E L %
% CCCC H H A A N N N N EEEEE LLLLL %
% %
% %
% MagickCore Image Channel Methods %
% %
% Software Design %
% Cristy %
% December 2003 %
% %
% %
% Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% https://www.imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
%
*/
/*
Include declarations.
*/
#include "MagickCore/studio.h"
#include "MagickCore/cache-private.h"
#include "MagickCore/channel.h"
#include "MagickCore/colorspace-private.h"
#include "MagickCore/composite-private.h"
#include "MagickCore/enhance.h"
#include "MagickCore/image.h"
#include "MagickCore/list.h"
#include "MagickCore/log.h"
#include "MagickCore/monitor.h"
#include "MagickCore/monitor-private.h"
#include "MagickCore/option.h"
#include "MagickCore/pixel-accessor.h"
#include "MagickCore/pixel-private.h"
#include "MagickCore/resource_.h"
#include "MagickCore/string-private.h"
#include "MagickCore/thread-private.h"
#include "MagickCore/token.h"
#include "MagickCore/utility.h"
#include "MagickCore/version.h"
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C h a n n e l F x I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ChannelFxImage() applies a channel expression to the specified image. The
% expression consists of one or more channels, either mnemonic or numeric (e.g.
% red, 1), separated by actions as follows:
%
% <=> exchange two channels (e.g. red<=>blue)
% => copy one channel to another channel (e.g. red=>green)
% = assign a constant value to a channel (e.g. red=50%)
% , write new image channels in the specified order (e.g. red, green)
% | add a new output image for the next set of channel operations
% ; move to the next input image for the source of channel data
%
% For example, to create 3 grayscale images from the red, green, and blue
% channels of an image, use:
%
% -channel-fx "red; green; blue"
%
% A channel without an operation symbol implies separate (i.e, semicolon).
%
% The format of the ChannelFxImage method is:
%
% Image *ChannelFxImage(const Image *image,const char *expression,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o expression: A channel expression.
%
% o exception: return any errors or warnings in this structure.
%
*/
typedef enum
{
ExtractChannelOp,
AssignChannelOp,
ExchangeChannelOp,
TransferChannelOp
} ChannelFx;
static MagickBooleanType ChannelImage(Image *destination_image,
const PixelChannel destination_channel,const ChannelFx channel_op,
const Image *source_image,const PixelChannel source_channel,
const Quantum pixel,ExceptionInfo *exception)
{
CacheView
*source_view,
*destination_view;
MagickBooleanType
status;
size_t
height,
width;
ssize_t
y;
status=MagickTrue;
source_view=AcquireVirtualCacheView(source_image,exception);
destination_view=AcquireAuthenticCacheView(destination_image,exception);
height=MagickMin(source_image->rows,destination_image->rows);
width=MagickMin(source_image->columns,destination_image->columns);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_number_threads(source_image,source_image,height,1)
#endif
for (y=0; y < (ssize_t) height; y++)
{
PixelTrait
destination_traits,
source_traits;
register const Quantum
*magick_restrict p;
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(source_view,0,y,source_image->columns,1,
exception);
q=GetCacheViewAuthenticPixels(destination_view,0,y,
destination_image->columns,1,exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
destination_traits=GetPixelChannelTraits(destination_image,
destination_channel);
source_traits=GetPixelChannelTraits(source_image,source_channel);
if ((destination_traits == UndefinedPixelTrait) ||
(source_traits == UndefinedPixelTrait))
continue;
for (x=0; x < (ssize_t) width; x++)
{
if (channel_op == AssignChannelOp)
SetPixelChannel(destination_image,destination_channel,pixel,q);
else
SetPixelChannel(destination_image,destination_channel,
GetPixelChannel(source_image,source_channel,p),q);
p+=GetPixelChannels(source_image);
q+=GetPixelChannels(destination_image);
}
if (SyncCacheViewAuthenticPixels(destination_view,exception) == MagickFalse)
status=MagickFalse;
}
destination_view=DestroyCacheView(destination_view);
source_view=DestroyCacheView(source_view);
return(status);
}
MagickExport Image *ChannelFxImage(const Image *image,const char *expression,
ExceptionInfo *exception)
{
#define ChannelFxImageTag "ChannelFx/Image"
ChannelFx
channel_op;
ChannelType
channel_mask;
char
token[MagickPathExtent];
const char
*p;
const Image
*source_image;
double
pixel;
Image
*destination_image;
MagickBooleanType
status;
PixelChannel
source_channel,
destination_channel;
ssize_t
channels;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
source_image=image;
destination_image=CloneImage(source_image,0,0,MagickTrue,exception);
if (destination_image == (Image *) NULL)
return((Image *) NULL);
if (expression == (const char *) NULL)
return(destination_image);
status=SetImageStorageClass(destination_image,DirectClass,exception);
if (status == MagickFalse)
{
destination_image=GetLastImageInList(destination_image);
return((Image *) NULL);
}
destination_channel=RedPixelChannel;
channel_mask=UndefinedChannel;
pixel=0.0;
p=(char *) expression;
GetNextToken(p,&p,MagickPathExtent,token);
channel_op=ExtractChannelOp;
for (channels=0; *token != '\0'; )
{
ssize_t
i;
/*
Interpret channel expression.
*/
switch (*token)
{
case ',':
{
GetNextToken(p,&p,MagickPathExtent,token);
break;
}
case '|':
{
if (GetNextImageInList(source_image) != (Image *) NULL)
source_image=GetNextImageInList(source_image);
else
source_image=GetFirstImageInList(source_image);
GetNextToken(p,&p,MagickPathExtent,token);
break;
}
case ';':
{
Image
*canvas;
(void) SetPixelChannelMask(destination_image,channel_mask);
if ((channel_op == ExtractChannelOp) && (channels == 1))
{
(void) SetPixelMetaChannels(destination_image,0,exception);
(void) SetImageColorspace(destination_image,GRAYColorspace,
exception);
}
canvas=CloneImage(source_image,0,0,MagickTrue,exception);
if (canvas == (Image *) NULL)
{
destination_image=DestroyImageList(destination_image);
return(destination_image);
}
AppendImageToList(&destination_image,canvas);
destination_image=GetLastImageInList(destination_image);
status=SetImageStorageClass(destination_image,DirectClass,exception);
if (status == MagickFalse)
{
destination_image=GetLastImageInList(destination_image);
return((Image *) NULL);
}
GetNextToken(p,&p,MagickPathExtent,token);
channels=0;
destination_channel=RedPixelChannel;
channel_mask=UndefinedChannel;
break;
}
default:
break;
}
i=ParsePixelChannelOption(token);
if (i < 0)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"UnrecognizedChannelType","`%s'",token);
destination_image=DestroyImageList(destination_image);
return(destination_image);
}
source_channel=(PixelChannel) i;
channel_op=ExtractChannelOp;
GetNextToken(p,&p,MagickPathExtent,token);
if (*token == '<')
{
channel_op=ExchangeChannelOp;
GetNextToken(p,&p,MagickPathExtent,token);
}
if (*token == '=')
{
if (channel_op != ExchangeChannelOp)
channel_op=AssignChannelOp;
GetNextToken(p,&p,MagickPathExtent,token);
}
if (*token == '>')
{
if (channel_op != ExchangeChannelOp)
channel_op=TransferChannelOp;
GetNextToken(p,&p,MagickPathExtent,token);
}
switch (channel_op)
{
case AssignChannelOp:
case ExchangeChannelOp:
case TransferChannelOp:
{
if (channel_op == AssignChannelOp)
pixel=StringToDoubleInterval(token,(double) QuantumRange+1.0);
else
{
i=ParsePixelChannelOption(token);
if (i < 0)
{
(void) ThrowMagickException(exception,GetMagickModule(),
OptionError,"UnrecognizedChannelType","`%s'",token);
destination_image=DestroyImageList(destination_image);
return(destination_image);
}
}
destination_channel=(PixelChannel) i;
if (i >= (ssize_t) GetPixelChannels(destination_image))
(void) SetPixelMetaChannels(destination_image,(size_t) (
destination_channel-GetPixelChannels(destination_image)+1),
exception);
if (image->colorspace != UndefinedColorspace)
switch (destination_channel)
{
case RedPixelChannel:
case GreenPixelChannel:
case BluePixelChannel:
case BlackPixelChannel:
case IndexPixelChannel:
break;
case AlphaPixelChannel:
{
destination_image->alpha_trait=BlendPixelTrait;
break;
}
case ReadMaskPixelChannel:
{
destination_image->read_mask=MagickTrue;
break;
}
case WriteMaskPixelChannel:
{
destination_image->write_mask=MagickTrue;
break;
}
case MetaPixelChannel:
default:
{
(void) SetPixelMetaChannels(destination_image,(size_t) (
destination_channel-GetPixelChannels(destination_image)+1),
exception);
break;
}
}
channel_mask=(ChannelType) (channel_mask | ParseChannelOption(token));
if (((channels >= 1) || (destination_channel >= 1)) &&
(IsGrayColorspace(destination_image->colorspace) != MagickFalse))
(void) SetImageColorspace(destination_image,sRGBColorspace,exception);
GetNextToken(p,&p,MagickPathExtent,token);
break;
}
default:
break;
}
status=ChannelImage(destination_image,destination_channel,channel_op,
source_image,source_channel,ClampToQuantum(pixel),exception);
if (status == MagickFalse)
{
destination_image=DestroyImageList(destination_image);
break;
}
channels++;
if (channel_op == ExchangeChannelOp)
{
status=ChannelImage(destination_image,source_channel,channel_op,
source_image,destination_channel,ClampToQuantum(pixel),exception);
if (status == MagickFalse)
{
destination_image=DestroyImageList(destination_image);
break;
}
channels++;
}
switch (channel_op)
{
case ExtractChannelOp:
{
channel_mask=(ChannelType) (channel_mask | (1 << destination_channel));
destination_channel=(PixelChannel) (destination_channel+1);
break;
}
default:
break;
}
status=SetImageProgress(source_image,ChannelFxImageTag,p-expression,
strlen(expression));
if (status == MagickFalse)
break;
}
(void) SetPixelChannelMask(destination_image,channel_mask);
if ((channel_op == ExtractChannelOp) && (channels == 1))
{
(void) SetPixelMetaChannels(destination_image,0,exception);
(void) SetImageColorspace(destination_image,GRAYColorspace,exception);
}
return(GetFirstImageInList(destination_image));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C o m b i n e I m a g e s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% CombineImages() combines one or more images into a single image. The
% grayscale value of the pixels of each image in the sequence is assigned in
% order to the specified channels of the combined image. The typical
% ordering would be image 1 => Red, 2 => Green, 3 => Blue, etc.
%
% The format of the CombineImages method is:
%
% Image *CombineImages(const Image *images,const ColorspaceType colorspace,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o images: the image sequence.
%
% o colorspace: the image colorspace.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *CombineImages(const Image *image,
const ColorspaceType colorspace,ExceptionInfo *exception)
{
#define CombineImageTag "Combine/Image"
CacheView
*combine_view;
Image
*combine_image;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
/*
Ensure the image are the same size.
*/
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
combine_image=CloneImage(image,0,0,MagickTrue,exception);
if (combine_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(combine_image,DirectClass,exception) == MagickFalse)
{
combine_image=DestroyImage(combine_image);
return((Image *) NULL);
}
if (colorspace != UndefinedColorspace)
(void) SetImageColorspace(combine_image,colorspace,exception);
else
if (fabs(image->gamma-1.0) <= MagickEpsilon)
(void) SetImageColorspace(combine_image,RGBColorspace,exception);
else
(void) SetImageColorspace(combine_image,sRGBColorspace,exception);
switch (combine_image->colorspace)
{
case UndefinedColorspace:
case sRGBColorspace:
{
if (GetImageListLength(image) > 3)
combine_image->alpha_trait=BlendPixelTrait;
break;
}
case GRAYColorspace:
{
if (GetImageListLength(image) > 1)
combine_image->alpha_trait=BlendPixelTrait;
break;
}
case CMYKColorspace:
{
if (GetImageListLength(image) > 4)
combine_image->alpha_trait=BlendPixelTrait;
break;
}
default:
break;
}
/*
Combine images.
*/
status=MagickTrue;
progress=0;
combine_view=AcquireAuthenticCacheView(combine_image,exception);
for (y=0; y < (ssize_t) combine_image->rows; y++)
{
CacheView
*image_view;
const Image
*next;
Quantum
*pixels;
register const Quantum
*magick_restrict p;
register Quantum
*magick_restrict q;
register ssize_t
i;
if (status == MagickFalse)
continue;
pixels=GetCacheViewAuthenticPixels(combine_view,0,y,combine_image->columns,
1,exception);
if (pixels == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
next=image;
for (i=0; i < (ssize_t) GetPixelChannels(combine_image); i++)
{
register ssize_t
x;
PixelChannel channel = GetPixelChannelChannel(combine_image,i);
PixelTrait traits = GetPixelChannelTraits(combine_image,channel);
if (traits == UndefinedPixelTrait)
continue;
if (next == (Image *) NULL)
continue;
image_view=AcquireVirtualCacheView(next,exception);
p=GetCacheViewVirtualPixels(image_view,0,y,next->columns,1,exception);
if (p == (const Quantum *) NULL)
continue;
q=pixels;
for (x=0; x < (ssize_t) combine_image->columns; x++)
{
if (x < (ssize_t) next->columns)
{
q[i]=GetPixelGray(next,p);
p+=GetPixelChannels(next);
}
q+=GetPixelChannels(combine_image);
}
image_view=DestroyCacheView(image_view);
next=GetNextImageInList(next);
}
if (SyncCacheViewAuthenticPixels(combine_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,CombineImageTag,progress++,
combine_image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
combine_view=DestroyCacheView(combine_view);
if (status == MagickFalse)
combine_image=DestroyImage(combine_image);
return(combine_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t I m a g e A l p h a C h a n n e l %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetImageAlphaChannel() returns MagickFalse if the image alpha channel is
% not activated. That is, the image is RGB rather than RGBA or CMYK rather
% than CMYKA.
%
% The format of the GetImageAlphaChannel method is:
%
% MagickBooleanType GetImageAlphaChannel(const Image *image)
%
% A description of each parameter follows:
%
% o image: the image.
%
*/
MagickExport MagickBooleanType GetImageAlphaChannel(const Image *image)
{
assert(image != (const Image *) NULL);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(image->signature == MagickCoreSignature);
return(image->alpha_trait != UndefinedPixelTrait ? MagickTrue : MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e p a r a t e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SeparateImage() separates a channel from the image and returns it as a
% grayscale image.
%
% The format of the SeparateImage method is:
%
% Image *SeparateImage(const Image *image,const ChannelType channel,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o channel: the image channel.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *SeparateImage(const Image *image,
const ChannelType channel_type,ExceptionInfo *exception)
{
#define GetChannelBit(mask,bit) (((size_t) (mask) >> (size_t) (bit)) & 0x01)
#define SeparateImageTag "Separate/Image"
CacheView
*image_view,
*separate_view;
Image
*separate_image;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
/*
Initialize separate image attributes.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
separate_image=CloneImage(image,image->columns,image->rows,MagickTrue,
exception);
if (separate_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(separate_image,DirectClass,exception) == MagickFalse)
{
separate_image=DestroyImage(separate_image);
return((Image *) NULL);
}
separate_image->alpha_trait=UndefinedPixelTrait;
(void) SetImageColorspace(separate_image,GRAYColorspace,exception);
separate_image->gamma=image->gamma;
/*
Separate image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireVirtualCacheView(image,exception);
separate_view=AcquireAuthenticCacheView(separate_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(progress,status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
q=QueueCacheViewAuthenticPixels(separate_view,0,y,separate_image->columns,1,
exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
register ssize_t
i;
if (GetPixelWriteMask(image,p) <= (QuantumRange/2))
{
SetPixelBackgoundColor(separate_image,q);
p+=GetPixelChannels(image);
q+=GetPixelChannels(separate_image);
continue;
}
SetPixelChannel(separate_image,GrayPixelChannel,0,q);
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
if ((traits == UndefinedPixelTrait) ||
(GetChannelBit(channel_type,channel) == 0))
continue;
SetPixelChannel(separate_image,GrayPixelChannel,p[i],q);
}
p+=GetPixelChannels(image);
q+=GetPixelChannels(separate_image);
}
if (SyncCacheViewAuthenticPixels(separate_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_SeparateImage)
#endif
proceed=SetImageProgress(image,SeparateImageTag,progress++,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
separate_view=DestroyCacheView(separate_view);
image_view=DestroyCacheView(image_view);
(void) SetImageChannelMask(separate_image,DefaultChannels);
if (status == MagickFalse)
separate_image=DestroyImage(separate_image);
return(separate_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e p a r a t e I m a g e s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SeparateImages() returns a separate grayscale image for each channel
% specified.
%
% The format of the SeparateImages method is:
%
% Image *SeparateImages(const Image *image,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *SeparateImages(const Image *image,ExceptionInfo *exception)
{
Image
*images,
*separate_image;
register ssize_t
i;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
images=NewImageList();
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
if ((traits == UndefinedPixelTrait) || ((traits & UpdatePixelTrait) == 0))
continue;
separate_image=SeparateImage(image,(ChannelType) (1 << channel),exception);
if (separate_image != (Image *) NULL)
AppendImageToList(&images,separate_image);
}
if (images == (Image *) NULL)
images=SeparateImage(image,UndefinedChannel,exception);
return(images);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t I m a g e A l p h a C h a n n e l %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetImageAlphaChannel() activates, deactivates, resets, or sets the alpha
% channel.
%
% The format of the SetImageAlphaChannel method is:
%
% MagickBooleanType SetImageAlphaChannel(Image *image,
% const AlphaChannelOption alpha_type,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o alpha_type: The alpha channel type: ActivateAlphaChannel,
% AssociateAlphaChannel, CopyAlphaChannel, DeactivateAlphaChannel,
% DisassociateAlphaChannel, ExtractAlphaChannel, OffAlphaChannel,
% OnAlphaChannel, OpaqueAlphaChannel, SetAlphaChannel, ShapeAlphaChannel,
% and TransparentAlphaChannel.
%
% o exception: return any errors or warnings in this structure.
%
*/
static inline void FlattenPixelInfo(const Image *image,const PixelInfo *p,
const double alpha,const Quantum *q,const double beta,
Quantum *composite)
{
double
Da,
gamma,
Sa;
register ssize_t
i;
/*
Compose pixel p over pixel q with the given alpha.
*/
Sa=QuantumScale*alpha;
Da=QuantumScale*beta,
gamma=Sa*(-Da)+Sa+Da;
gamma=PerceptibleReciprocal(gamma);
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
if (traits == UndefinedPixelTrait)
continue;
switch (channel)
{
case RedPixelChannel:
{
composite[i]=ClampToQuantum(gamma*MagickOver_((double) q[i],beta,
(double) p->red,alpha));
break;
}
case GreenPixelChannel:
{
composite[i]=ClampToQuantum(gamma*MagickOver_((double) q[i],beta,
(double) p->green,alpha));
break;
}
case BluePixelChannel:
{
composite[i]=ClampToQuantum(gamma*MagickOver_((double) q[i],beta,
(double) p->blue,alpha));
break;
}
case BlackPixelChannel:
{
composite[i]=ClampToQuantum(gamma*MagickOver_((double) q[i],beta,
(double) p->black,alpha));
break;
}
case AlphaPixelChannel:
{
composite[i]=ClampToQuantum(QuantumRange*(Sa*(-Da)+Sa+Da));
break;
}
default:
break;
}
}
}
MagickExport MagickBooleanType SetImageAlphaChannel(Image *image,
const AlphaChannelOption alpha_type,ExceptionInfo *exception)
{
CacheView
*image_view;
MagickBooleanType
status;
ssize_t
y;
assert(image != (Image *) NULL);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(image->signature == MagickCoreSignature);
status=MagickTrue;
switch (alpha_type)
{
case ActivateAlphaChannel:
{
image->alpha_trait=BlendPixelTrait;
break;
}
case AssociateAlphaChannel:
{
/*
Associate alpha.
*/
status=SetImageStorageClass(image,DirectClass,exception);
if (status == MagickFalse)
break;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
double
gamma;
register ssize_t
i;
if (GetPixelWriteMask(image,q) <= (QuantumRange/2))
{
q+=GetPixelChannels(image);
continue;
}
gamma=QuantumScale*GetPixelAlpha(image,q);
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
if (channel == AlphaPixelChannel)
continue;
if ((traits & UpdatePixelTrait) == 0)
continue;
q[i]=ClampToQuantum(gamma*q[i]);
}
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
image->alpha_trait=CopyPixelTrait;
return(status);
}
case BackgroundAlphaChannel:
{
/*
Set transparent pixels to background color.
*/
if (image->alpha_trait == UndefinedPixelTrait)
break;
status=SetImageStorageClass(image,DirectClass,exception);
if (status == MagickFalse)
break;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
if (GetPixelAlpha(image,q) == TransparentAlpha)
{
SetPixelViaPixelInfo(image,&image->background_color,q);
SetPixelChannel(image,AlphaPixelChannel,TransparentAlpha,q);
}
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
return(status);
}
case CopyAlphaChannel:
{
image->alpha_trait=UpdatePixelTrait;
status=CompositeImage(image,image,IntensityCompositeOp,MagickTrue,0,0,
exception);
break;
}
case DeactivateAlphaChannel:
{
if (image->alpha_trait == UndefinedPixelTrait)
status=SetImageAlpha(image,OpaqueAlpha,exception);
image->alpha_trait=CopyPixelTrait;
break;
}
case DisassociateAlphaChannel:
{
/*
Disassociate alpha.
*/
status=SetImageStorageClass(image,DirectClass,exception);
if (status == MagickFalse)
break;
image->alpha_trait=BlendPixelTrait;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
double
gamma,
Sa;
register ssize_t
i;
if (GetPixelWriteMask(image,q) <= (QuantumRange/2))
{
q+=GetPixelChannels(image);
continue;
}
Sa=QuantumScale*GetPixelAlpha(image,q);
gamma=PerceptibleReciprocal(Sa);
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
if (channel == AlphaPixelChannel)
continue;
if ((traits & UpdatePixelTrait) == 0)
continue;
q[i]=ClampToQuantum(gamma*q[i]);
}
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
image->alpha_trait=UndefinedPixelTrait;
return(status);
}
case DiscreteAlphaChannel:
{
if (image->alpha_trait == UndefinedPixelTrait)
status=SetImageAlpha(image,OpaqueAlpha,exception);
image->alpha_trait=UpdatePixelTrait;
break;
}
case ExtractAlphaChannel:
{
status=CompositeImage(image,image,AlphaCompositeOp,MagickTrue,0,0,
exception);
image->alpha_trait=UndefinedPixelTrait;
break;
}
case OffAlphaChannel:
{
image->alpha_trait=UndefinedPixelTrait;
break;
}
case OnAlphaChannel:
{
if (image->alpha_trait == UndefinedPixelTrait)
status=SetImageAlpha(image,OpaqueAlpha,exception);
image->alpha_trait=BlendPixelTrait;
break;
}
case OpaqueAlphaChannel:
{
status=SetImageAlpha(image,OpaqueAlpha,exception);
break;
}
case RemoveAlphaChannel:
{
/*
Remove transparency.
*/
if (image->alpha_trait == UndefinedPixelTrait)
break;
status=SetImageStorageClass(image,DirectClass,exception);
if (status == MagickFalse)
break;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
FlattenPixelInfo(image,&image->background_color,
image->background_color.alpha,q,(double)
GetPixelAlpha(image,q),q);
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
image->alpha_trait=image->background_color.alpha_trait;
break;
}
case SetAlphaChannel:
{
if (image->alpha_trait == UndefinedPixelTrait)
status=SetImageAlpha(image,OpaqueAlpha,exception);
break;
}
case ShapeAlphaChannel:
{
/*
Set alpha channel by shape.
*/
status=SetImageStorageClass(image,DirectClass,exception);
if (status == MagickFalse)
break;
image->alpha_trait=UpdatePixelTrait;
(void) SetImageMask(image,WritePixelMask,image,exception);
(void) LevelImageColors(image,&image->background_color,
&image->background_color,MagickTrue,exception);
(void) SetImageMask(image,WritePixelMask,(Image *) NULL,exception);
break;
}
case TransparentAlphaChannel:
{
status=SetImageAlpha(image,TransparentAlpha,exception);
break;
}
case UndefinedAlphaChannel:
break;
}
if (status == MagickFalse)
return(status);
(void) SetPixelChannelMask(image,image->channel_mask);
return(SyncImagePixelCache(image,exception));
}
|
SKIM.h
|
/*
Algorithm for Influence Estimation and Maximization
Copyright (c) Microsoft Corporation
All rights reserved.
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ""Software""), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#pragma once
#include <array>
#include <vector>
#include <iostream>
#include <fstream>
#include <unordered_map>
#include <random>
#include <climits>
#include <omp.h>
#include <unordered_set>
#include <list>
using namespace std;
#include "FastStaticGraphs.h"
#include "Macros.h"
#include "FastSet.h"
#include "HashPair.h"
#include "Timer.h"
#include "KHeap.h"
namespace Algorithms{
namespace InfluenceMaximization {
class SKIM {
public:
// Type definitions.
typedef DataStructures::Graphs::FastUnweightedGraph GraphType;
typedef GraphType::ArcIdType ArcIdType;
static const uint32_t NullVertex = UINT_MAX;
vector<vector<vector<uint32_t>>> fwp;
vector<vector<vector<uint32_t>>> bwp;
enum ModelType { WEIGHTED, BINARY, TRIVALENCY };
// A seed vertex and associated data.
struct SeedType {
uint32_t VertexId = NullVertex;
double EstimatedInfluence = 0.0;
double ExactInfluence = 0.0;
double BuildSketchesElapsedMilliseconds = 0;
double ComputeInfluenceElapsedMilliseconds = 0;
};
// Default constructor.
SKIM(GraphType &g, vector<unordered_map<uint32_t, vector<uint32_t>>> &pgraphs, const uint16_t l, const uint32_t s, const bool v) :
verbose(v),
randomSeed(s),
graph(g),
resolution(3000000),
indeg(graph.NumVertices(), 0),
binprob(resolution / 10),
triprob{ { resolution / 10, resolution / 100, resolution / 1000 } }//,
//dis(0, resolution-1),
//gen(s)
{
if (verbose) cout << "Computing in-degrees... " << flush;
// Compute the degrees.
FORALL_ARCS(graph, vertexId, arc) {
if (!arc->Forward()) continue;
++indeg[arc->OtherVertexId()];
}
if (verbose) cout << "done." << endl;
//----------------------------
int n = pgraphs.size();
fwp.resize(l,vector<vector<uint32_t>>(n));
bwp.resize(l,vector<vector<uint32_t>>(n));
for(uint32_t i =0; i< l; i++){
for(uint32_t u =0; u <n; u++){
vector<uint32_t> visited(n, false);
// Create a queue for BFS
list<uint32_t> q;
// Mark the current node as visited and enqueue it
visited[u] = true;
q.push_back(u);
// 'i' will be used to get all adjacent
// vertices of a vertex
vector<uint32_t>::iterator it;
uint32_t s =0;
while(!q.empty())
{
// Dequeue a vertex from queue and print it
s = q.front();
//cout << s << " ";
q.pop_front();
// Get all adjacent vertices of the dequeued
// vertex s. If a adjacent has not been visited,
// then mark it visited and enqueue it
for (it = pgraphs[u][s].begin(); it != pgraphs[u][s].end(); ++it)
{
if (!visited[*it])
{
//cout<<"arcs: "<<u<<" "<<*it<<endl;
if((Murmur3Hash(s, *it, i, l) % resolution) < binprob){
q.push_back(*it);
visited[*it] = true;
fwp[i][u].push_back(*it);
bwp[i][*it].push_back(u);
//cout<<"pe: "<<u<<" "<<*it<<endl;
}
}
}
}
}
}
}
// Set the binary probability.
inline void SetBinaryProbability(const double prob) {
binprob = uint32_t(prob * double(resolution));
}
// Run.
template<ModelType modelType>
inline void Run(uint32_t N, const uint16_t k, const uint16_t l, const uint16_t lEval, const int32_t numt, const string statsFilename = "", const string coverageFilename = "") {
// Set N to number of vertices, if it's zero.
if (N == 0) N = static_cast<uint32_t>(graph.NumVertices());
/*
Initialize the algorithm.
*/
if (verbose) cout << "Setting up data structures... " << flush;
// Some datastructures that are necessary for the algorithm.
const uint64_t nl = graph.NumVertices()*l;
vector<SeedType> seedSet; // this will hold the seed vertices.
vector<uint32_t> permutation; // this is a permutation of the vertices to draw ranks from.
unordered_map< pair<uint32_t, uint16_t>, unordered_set<uint32_t> > invSketches; // these are the "inverse sketches" (search spaces).
vector<uint16_t> sketchSizes(graph.NumVertices(), 0); // these are the sizes of the real sketches.
vector<vector<bool>> covered(l); // this indicates whether a vertex/instance pair has been covered (influenced).
vector<vector<bool>> processed(l); // this indicates whether a vertex/instance pair has been processed (sketches built from it).
vector<DataStructures::Container::FastSet<uint32_t>> searchSpaces(numt); // this is for maintaining search spaces of BFSes; one per thread.
DataStructures::Container::FastSet<uint32_t> &S0 = searchSpaces[0];
DataStructures::Container::FastSet<uint32_t> S1(graph.NumVertices());
vector<vector<pair<uint32_t, uint16_t>>> updateQueues(numt);
vector<vector<uint32_t>> buck;
vector<uint32_t> buckind;
uint16_t buckp(0);
mt19937_64 rnd(randomSeed); // Random number generator.
uniform_int_distribution<uint16_t> distr(0, l - 1);
uint64_t rank(0); // this is the current rank value.
Platform::Timer timer, globalTimer;
double estinf(0), exinf(0), exinfloc(0), sketchms(0), infms(0);
bool runParallel(numt > 1), saturated(false);
uint32_t numperm(0), permthresh(l - (l / 10 + 1));
//vector<vector<uint32_t>> privRevEdges={{},{},{0},{},{1},{0,2,3}} ;//(graph.NumVertices());
//vector<vector<uint32_t>> Gu= {{2,5},{4},{5},{5},{},{}};
for (int32_t t = 0; t < numt; ++t)
searchSpaces[t].Resize(graph.NumVertices());
for (uint16_t i(0); i < l; ++i) {
processed[i].resize(graph.NumVertices(), false);
covered[i].resize(graph.NumVertices(), false);
}
if (verbose) cout << "done." << endl;
/*
Main iterations loop. Each iteration computes one seed vertex.
*/
globalTimer.Start();
while (seedSet.size() < N) {
SeedType newSeed;
exinfloc = 0.0;
/*
BFS computation to build sketches.
*/
if (!saturated) {
if (verbose) cout << "[" << seedSet.size() + 1 << "] Computing sketches from rank " << rank << "... " << flush;
timer.Start();
while (rank < nl) {
// Select next vertex/instance pair.
const Types::SizeType vi = rank % graph.NumVertices();
if (vi == 0) {
if (permutation.size() != graph.NumVertices()) {
permutation.resize(graph.NumVertices(), 0);
for (uint32_t u(0); u < graph.NumVertices(); ++u) permutation[u] = u;
}
shuffle(permutation.begin(), permutation.end(), rnd);
++numperm;
}
const uint32_t sourceVertexId = permutation[vi];
uint16_t i = 0;
if (numperm < permthresh) {
do {
i = distr(rnd);
} while (processed[i][sourceVertexId]);
}
else {
i = distr(rnd) % (l - numperm + 1);
for (uint16_t j = 0; j < l; ++j) {
if (!processed[j][sourceVertexId]) {
if (i == 0) {
i = j;
break;
}
--i;
}
}
}
processed[i][sourceVertexId] = true;
++rank; // Increase value for rank.
// Shortcut to some variables.
vector<bool> &cov = covered[i]; // cover of instance
unordered_set<uint32_t> &invSketch = invSketches[make_pair(sourceVertexId, i)]; // inverted sketch of of node-instance pair
vector<vector<uint32_t>> &privRevEdges=bwp[i];//(graph.NumVertices());
vector<vector<uint32_t>> &Gu=fwp[i];
//vector<uint32_t> &invSketchPrivate = invSketchesPrivate[make_pair(sourceVertexId, i)];
// Only process such ranks that are not yet covered.
if (cov[sourceVertexId]) continue; // if node is already covered in that instance go to start of loop
// Perform the BFS.
S0.Clear();
S0.Insert(sourceVertexId);
S1.Clear();
uint32_t ind = 0;
while (ind < S0.Size()) {
uint32_t u = S0.KeyByIndex(ind++);
if(!S1.IsContained(u)){
++sketchSizes[u];
//invSketchPrivate.remove(u);
}
invSketch.insert(u);
//cout<<"revbfs: "<<sourceVertexId<<" "<<u<<" "<<sketchSizes[u]<<endl;
// pruning.
if (sketchSizes[u]== k) {
// Set the vertex and compute marginal influence.
newSeed.VertexId = u;
newSeed.EstimatedInfluence = static_cast<double>(k - 1) * static_cast<double>(graph.NumVertices()) / static_cast<double>(rank);
break;
}
// arc expansion.
//for (auto arc = G.GetLastArc(u), firstArc = G.GetFirstArc(u); arc >= firstArc; --arc)
FORALL_INCIDENT_ARCS_BACKWARD(graph, u, a) {
if (!a->Backward()) break;
const uint32_t v = a->OtherVertexId();
if (Contained<modelType>(v, u, i, l) && !cov[v] && !S0.IsContained(v)){
//if (ContainedRandom<modelType>(v, u) && !cov[v] && !S0.IsContained(v))
S0.Insert(v);
}
}
/*FORALL_INCIDENT_ARCS_BACKWARD(pgraphs, u, a) {
if (!a->Backward()) break;
const uint32_t v = a->OtherVertexId();
if (Contained<modelType>(v, u, i, l) && !cov[v] && !S0.IsContained(v))
//if (ContainedRandom<modelType>(v, u) && !cov[v] && !S0.IsContained(v))
S0.Insert(v);
}*/
for(auto up : privRevEdges[u]){
if(!cov[up] && !S0.IsContained(up) && !S1.IsContained(up)){
++sketchSizes[up];
invSketch.insert(up);
//invSketchPrivate.push_back(up);
S1.Insert(up);
//cout<<"prirevbfs: "<<sourceVertexId<<" "<<up<<" "<<sketchSizes[up]<<endl;
if (sketchSizes[up]== k) {
// Set the vertex and compute marginal influence.
newSeed.VertexId = up;
newSeed.EstimatedInfluence = static_cast<double>(k - 1) * static_cast<double>(graph.NumVertices()) / static_cast<double>(rank);
break;
}
}
}
if(newSeed.VertexId != NullVertex && sketchSizes[newSeed.VertexId] ==k)
break;
}
if (newSeed.VertexId != NullVertex)
break;
//cout<<"seed: "<<newSeed.VertexId<<endl;
} // end sketch building.
sketchms += timer.LiveElapsedMilliseconds();
newSeed.BuildSketchesElapsedMilliseconds = sketchms;
if (verbose) cout << " done (u: " << newSeed.VertexId << ", est: " << newSeed.EstimatedInfluence << " r: " << rank << ", ms: " << newSeed.BuildSketchesElapsedMilliseconds << ")" << endl;
// Out of new vertices...
if (newSeed.VertexId == NullVertex) {
if (verbose) cout << "GRAPH SATURATED (|S|=" << seedSet.size() << ", rank=" << rank << ")." << endl;
if (verbose) cout << "Building buckets for the remaining vertices... " << flush;
buck.resize(k);
buckind.resize(graph.NumVertices(), 0);
uint32_t num(0);
FORALL_VERTICES(graph, u) {
if (sketchSizes[u] > 0) {
buckind[u] = uint32_t(buck[sketchSizes[u]].size());
buck[sketchSizes[u]].push_back(u);
buckp = max<uint16_t>(buckp, sketchSizes[u]);
++num;
}
}
if (verbose) cout << "done (" << num << " vertices)." << endl;
saturated = true;
}
}
if (saturated) {
while (buckp > 0 && buck[buckp].empty()) --buckp;
if (buckp == 0) {
if (verbose) cout << endl << "TOTAL COVERAGE REACHED (|S|=" << seedSet.size() << ")." << endl;
break;
}
// Select the next seed vertex as the one that has the highest number of things in the sketch.
if (verbose) cout << "[" << seedSet.size() + 1 << "] Determining the vertex that has highest marginal influence... " << flush;
Assert(!buck[buckp].empty());
//cout<<"buck: "<<buckp<<endl;
newSeed.VertexId = buck[buckp].back();
//cout<<"buck newvId: "<<newSeed.VertexId<<endl;
newSeed.EstimatedInfluence = double(sketchSizes[newSeed.VertexId]) / l;
newSeed.BuildSketchesElapsedMilliseconds = sketchms;
if (verbose) cout << " done (u: " << newSeed.VertexId << ", est: " << newSeed.EstimatedInfluence << ")" << endl;
}
/*
BFS computation on each instance to get the exact influence.
Also updates the sketch sizes.
*/
if (verbose) cout << "[" << seedSet.size() + 1 << "] Computing influence... vertexId: "<< newSeed.VertexId<< flush;
timer.Start();
// Call sequential or parallel BFS to compute influences.
if (runParallel) {
#pragma omp parallel num_threads(numt) reduction(+ : exinfloc)
{
// Get thread id.
const int32_t t = omp_get_thread_num();
// Shortcut to thread-local search spaces.
auto &S = searchSpaces[t];
auto &Q = updateQueues[t];
Q.clear();
#pragma omp for
for (int32_t i = 0; i < l; ++i) {
// Shortcut to some variables.
vector<bool> &cov = covered[i];
// Run a BFS.
S.Clear();
if (!cov[newSeed.VertexId])
S.Insert(newSeed.VertexId);
uint32_t ind = 0;
while (ind < S.Size()) {
uint32_t u = S.KeyByIndex(ind++);
cov[u] = true;
++exinfloc;
// Update counters and sketches.
const pair<uint32_t, uint16_t> key(u, i);
if (invSketches.count(key)) {
Q.push_back(key);
}
FORALL_INCIDENT_ARCS(graph, u, a) {
if (!a->Forward()) break;
const uint32_t v = a->OtherVertexId();
if (Contained<modelType>(u, v, i, l) && !S.IsContained(v) && !cov[v])
S.Insert(v);
}
}
} // end exact influence computation.
} // end parallel section.
// Update the counters.
for (int32_t t = 0; t < numt; ++t) {
vector<pair<uint32_t, uint16_t>> &Q = updateQueues[t];
for (const pair<uint32_t, uint16_t> &key : Q) {
const unordered_set<uint32_t> &invSketch = invSketches[key];
if (!saturated) {
for (const uint32_t &v : invSketch)
--sketchSizes[v];
}
else {
for (const uint32_t &v : invSketch) {
uint16_t s = sketchSizes[v];
// Erase from bucket.
buckind[buck[s].back()] = buckind[v];
swap(buck[s][buckind[v]], buck[s].back());
buck[s].pop_back();
if (sketchSizes[v] > 1) {
buckind[v] = uint32_t(buck[sketchSizes[v] - 1].size());
buck[sketchSizes[v] - 1].push_back(v);
}
--sketchSizes[v];
}
}
invSketches.erase(key);
}
}
} // end parallel branch.
else { // begin sequential branch.
for (int32_t i = 0; i < l; ++i) {
// Shortcut to some variables.
vector<bool> &cov = covered[i];
// Run a BFS.
S0.Clear();
if (!cov[newSeed.VertexId]){
S0.Insert(newSeed.VertexId);
for(auto up : fwp[i][newSeed.VertexId]){
if (!cov[up])
S0.Insert(up);
}
}
uint32_t ind = 0;
while (ind < S0.Size()) {
uint32_t u = S0.KeyByIndex(ind++);
cov[u] = true;
++exinfloc;
// Update counters and sketches.
const pair<uint32_t, uint16_t> key(u, i);
if (invSketches.count(key)) {
const unordered_set<uint32_t> &invSketch = invSketches[key];
if (!saturated) {
for (const uint32_t &v : invSketch)
--sketchSizes[v];
}
else {
for (const uint32_t &v : invSketch) {
uint16_t s = sketchSizes[v];
// Erase from bucket.
buckind[buck[s].back()] = buckind[v];
swap(buck[s][buckind[v]], buck[s].back());
buck[s].pop_back();
if (sketchSizes[v] > 1) {
buckind[v] = uint32_t(buck[sketchSizes[v] - 1].size());
buck[sketchSizes[v] - 1].push_back(v);
}
--sketchSizes[v];
}
}
invSketches.erase(key);
}
FORALL_INCIDENT_ARCS(graph, u, a) {
if (!a->Forward()) break;
const uint32_t v = a->OtherVertexId();
if (Contained<modelType>(u, v, i, l) && !S0.IsContained(v) && !cov[v])
S0.Insert(v);
}
}
} // end exact influence computation.
} // end sequential branch.
newSeed.ExactInfluence = double(exinfloc) / double(l);
infms += timer.LiveElapsedMilliseconds();
newSeed.ComputeInfluenceElapsedMilliseconds = infms;
estinf += newSeed.EstimatedInfluence;
exinf += newSeed.ExactInfluence;
seedSet.push_back(newSeed);
if (verbose) cout << " done (inf: " << newSeed.ExactInfluence << ", ms: " << newSeed.ComputeInfluenceElapsedMilliseconds << ")." << endl;
if (verbose) cout << endl;
} // end greedy iteration.
const double totalms = globalTimer.LiveElapsedMilliseconds();
// Compute the exact influence? This is not measured in the running time.
if (lEval != 0)
exinf = ComputeExactInfluence<modelType>(seedSet, lEval,l);
/*
Print results.
*/
if (verbose) cout << endl;
graph.DumpStatistics(cout);
cout << "Random seed: " << randomSeed << "." << endl
<< "Number of seed vertices computed: " << seedSet.size() << "." << endl
<< "Number of ranks used: " << rank << "." << endl
<< "Permutations computed: " << numperm << " (each of size: " << permutation.size() << ")." << endl
<< "Building sketches: " << sketchms / 1000.0 << " sec." << endl
<< "Computing influence: " << infms / 1000.0 << " sec." << endl
<< "Total time: " << totalms / 1000.0 << " sec." << endl
<< "Estimated spread of solution: " << estinf << " (" << (100.0*estinf / static_cast<double>(graph.NumVertices())) << " %)." << endl
<< "Exact spread of solution: " << exinf << " (" << (100.0*exinf / static_cast<double>(graph.NumVertices())) << " %)." << endl
<< "Quality gap: " << 100.0 * (1.0 - exinf / estinf) << " %" << endl;
/*
Dump statistics to a file.
*/
if (!statsFilename.empty()) {
IO::FileStream file;
file.OpenNewForWriting(statsFilename);
if (file.IsOpen()) {
stringstream ss;
ss << "NumberOfVertices = " << graph.NumVertices() << endl
<< "NumberOfArcs = " << graph.NumArcs() / 2 << endl
<< "TotalEstimatedInfluence = " << estinf << endl
<< "TotalExactInfluence = " << exinf << endl
<< "TotalElapsedMilliseconds = " << totalms << endl
<< "SketchBuildingElapsedMilliseconds = " << sketchms << endl
<< "InfluenceComputationElapsedMilliseconds = " << infms << endl
<< "NumberOfRanksUsed = " << rank << endl
<< "NumberOfSeedVertices = " << seedSet.size() << endl
<< "RankComputationMethod = " << "shuffle" << endl
<< "NumberOfPermutationsComputed = " << numperm << endl;
double sumEstimatedInfluence(0.0), sumExactInfluence(0.0);
for (Types::IndexType i = 0; i < seedSet.size(); ++i) {
sumEstimatedInfluence += seedSet[i].EstimatedInfluence;
sumExactInfluence += seedSet[i].ExactInfluence;
ss << i << "_MarginalEstimatedInfluence = " << seedSet[i].EstimatedInfluence << endl
<< i << "_CumulativeEstimatedInfluence = " << sumEstimatedInfluence << endl
<< i << "_MarginalExactInfluence = " << seedSet[i].ExactInfluence << endl
<< i << "_CumulativeExactInfluence = " << sumExactInfluence << endl
<< i << "_VertexId = " << seedSet[i].VertexId << endl
<< i << "_TotalElapsedMilliseconds = " << seedSet[i].BuildSketchesElapsedMilliseconds + seedSet[i].ComputeInfluenceElapsedMilliseconds << endl
<< i << "_SketchBuildingElapsedMilliseconds = " << seedSet[i].BuildSketchesElapsedMilliseconds << endl
<< i << "_InfluenceComputationElapsedMilliseconds = " << seedSet[i].ComputeInfluenceElapsedMilliseconds << endl;
}
file.WriteString(ss.str());
}
}
if (!coverageFilename.empty()) {
IO::FileStream file;
file.OpenNewForWriting(coverageFilename);
if (file.IsOpen()) {
stringstream ss;
ss << graph.NumVertices() << endl;
ss << seedSet.size() << endl;
ss << seedSet.back().ComputeInfluenceElapsedMilliseconds + seedSet.back().BuildSketchesElapsedMilliseconds << endl;
double sumExactInfluence(0.0);
double elapsedMilliseconds(0.0);
for (Types::IndexType i = 0; i < seedSet.size(); ++i) {
sumExactInfluence += seedSet[i].ExactInfluence;
elapsedMilliseconds = seedSet[i].BuildSketchesElapsedMilliseconds + seedSet[i].ComputeInfluenceElapsedMilliseconds;
ss << seedSet[i].VertexId << "\t" << sumExactInfluence << "\t" << elapsedMilliseconds << endl;
}
file.WriteString(ss.str());
}
}
}
protected:
// This evaluates the influence using a separate BFS with a separate seed.
template<ModelType modelType>
inline double ComputeExactInfluence(vector<SeedType> &seedSet, const uint16_t l,const uint16_t actl) {
// This essentially runs a bunch of BFSes in all l instances, one from each
// seed vertex. It then updates the exact influence value for the respective
// seed.
if (verbose) cout << "Allocating data structures... " << flush;
DataStructures::Container::FastSet<uint32_t> searchSpace(graph.NumVertices());
vector<vector<bool>> marked(l);
for (uint16_t i = 0; i < l; ++i)
marked[i].resize(graph.NumVertices(), false);
if (verbose) cout << "done." << endl;
// For each seed vertex, perform a BFS in every instance, and count the sarch space sizes.
if (verbose) cout << "Running BFSes to compute exact influence in " << l << " instances and " << seedSet.size() << " vertices:" << flush;
double exinf(0);
cout<<endl;
for (SeedType &s : seedSet) {
uint64_t size = 0;
for (uint16_t i = 0; i < l; ++i) {
vector<bool> &m = marked[i];
if (m[s.VertexId]) continue;
searchSpace.Clear();
searchSpace.Insert(s.VertexId);
for(auto up : fwp[i%(actl)][s.VertexId]){
if(!searchSpace.IsContained(up)){
searchSpace.Insert(up);
}
}
uint64_t cur = 0;
while (cur < searchSpace.Size()) {
const uint32_t u = searchSpace.KeyByIndex(cur++);
m[u] = true;
++size;
FORALL_INCIDENT_ARCS(graph, u, arc) {
if (!arc->Forward()) continue;
const uint32_t v = arc->OtherVertexId();
if (Contained<modelType>(u, v, i, l) && !m[v] && !searchSpace.IsContained(v)){
searchSpace.Insert(v);
/*for(auto up : fwp[i%(actl)][v]){
if(!searchSpace.IsContained(v)){
searchSpace.Insert(up);
}
}*/
}
}
}
}
s.ExactInfluence = double(size) / double(l);
exinf += s.ExactInfluence;
if (verbose) cout << " " << s.ExactInfluence << flush;
}
if (verbose) cout << endl << "done (exinf=" << exinf << ")." << endl;
return exinf;
}
protected:
// Returns true if the (forward) arc from u to v is contained in instance i.
template<ModelType modelType>
inline bool Contained(const uint32_t u, const uint32_t v, const uint16_t i, const uint16_t l) {
assert(false);
return false;
}
//// Returns true if the (forward) arc from u to v is contained in instance i.
//template<ModelType modelType>
//inline bool ContainedRandom(const uint32_t u, const uint32_t v) {
// assert(false);
// return false;
//}
// A tailored Murmur hash 3 function for pair of vertices and instance.
inline uint32_t Murmur3Hash(const uint32_t u, const uint32_t v, const uint16_t i, const uint16_t l) const {
// Seed with our seed value.
uint32_t h = (randomSeed << 16) + l;
// Declare magic constants c1 and c2.
const uint32_t c1 = 0xcc9e2d51;
const uint32_t c2 = 0x1b873593;
// Hash the first vertex.
uint32_t k = u;
k *= c1;
//k = _rotl(k, 15);
k = (k << 15) | (k >> (32-15));
k *= c2;
h ^= k;
//h = _rotl(h, 13);
h = (h << 13) | (h >> (32-13));
h = h * 5 + 0xe6546b64;
// Hash the second vertex.
k = v;
k *= c1;
//k = _rotl(k, 15);
k = (k << 15) | (k >> (32-15));
k *= c2;
h ^= k;
//h = _rotl(h, 13);
h = (h << 13) | (h >> (32-13));
h = h * 5 + 0xe6546b64;
// Hash the instance.
k = static_cast<uint32_t>(i);
k *= c1;
//k = _rotl(k, 15);
k = (k << 15) | (k >> (32-15));
k *= c2;
h ^= k;
// Mix the result.
h ^= 10; // length of input in bytes.
h ^= h >> 16;
h *= 0x85ebca6b;
h ^= h >> 13;
h *= 0xc2b2ae35;
h ^= h >> 16;
return h;
}
private:
// Indicates whether the algorithm procuces output.
bool verbose = true;
// This is the random seed.
uint32_t randomSeed;
// This is the graph we are using
GraphType &graph;
// The resolution for integer probabilities using the hash function.
const uint32_t resolution;
// The degrees of each vertex.
vector<ArcIdType> indeg;
// The binary probability.
uint32_t binprob;
// The trivalency probabilities.
const array<uint32_t, 3> triprob;
// Random distribution.
//uniform_int_distribution<uint32_t> dis;
// Random number generator.
//mt19937 gen;
};
template<>
inline bool SKIM::Contained<SKIM::WEIGHTED>(const uint32_t u, const uint32_t v, const uint16_t i, const uint16_t l) {
uint32_t prob = min(resolution, resolution / indeg[v]);
return (Murmur3Hash(u, v, i, l) % resolution) < prob;
}
template<>
inline bool SKIM::Contained<SKIM::BINARY>(const uint32_t u, const uint32_t v, const uint16_t i, const uint16_t l) {
//return true;
return (Murmur3Hash(u, v, i, l) % resolution) < binprob;
}
template<>
inline bool SKIM::Contained<SKIM::TRIVALENCY>(const uint32_t u, const uint32_t v, const uint16_t i, const uint16_t l) {
const uint32_t index = (Murmur3Hash(u, v, i, l) % triprob.size());
return (Murmur3Hash(u, v, i, l) % resolution) < triprob[index];
}
}
}
|
solver.c
|
//======================================================================================================================================================150
// UPDATE
//======================================================================================================================================================150
// Summary of changes by Lukasz G. Szafaryn:
// 1) The original code was obtained from: Mathematics Source Library (http://mymathlib.webtrellis.net/index.html)
// 2) This solver and particular solving algorithm used with it (embedded_fehlberg_7_8) were adapted to work with a set of equations, not just one like in original version.
// 3) In order for solver to provide deterministic number of steps (needed for particular amount of memore previousely allocated for results), every next step is incremented by 1 time unit (h_init).
// 4) Function assumes that time interval starts at 0 (xmin) and ends at integer value (xmax) specified by the uses as a parameter on command line.
// 5) The appropriate amount of memory is previousely allocated for that range (y).
// 5) This setup in 3) - 5) allows solver to adjust the step ony from current time instance to current time instance + 0.9. The next time instance is current time instance + 1;
// 6) Solver also takes parameters (params) that it then passes to the equations.
// 7) The original solver cannot handle cases when equations return NAN and INF values due to discontinuities and /0. That is why equations provided by user need to make sure that no NAN and INF are returned.
// Last update: 15 DEC 09
//======================================================================================================================================================150
// DESCRIPTION
//======================================================================================================================================================150
// int solver( fp (*f)(fp, fp), fp y[], //
// fp x, fp h, fp xmax, fp *h_next, fp tolerance ) //
// //
// Description: //
// This function solves the differential equation y'=f(x,y) with the //
// initial condition y(x) = y[0]. The value at xmax is returned in y[1]. //
// The function returns 0 if successful or -1 if it fails. //
// //
// Arguments: //
// fp *f Pointer to the function which returns the slope at (x,y) of //
// integral curve of the differential equation y' = f(x,y) //
// which passes through the point (x0,y0) corresponding to the //
// initial condition y(x0) = y0. //
// fp y[] On input y[0] is the initial value of y at x, on output //
// y[1] is the solution at xmax. //
// fp x The initial value of x. //
// fp h Initial step size. //
// fp xmax The endpoint of x. //
// fp *h_next A pointer to the estimated step size for successive //
// calls to solver. //
// fp tolerance The tolerance of y(xmax), i.e. a solution is sought //
// so that the relative error < tolerance. //
// //
// Return Values: //
// 0 The solution of y' = f(x,y) from x to xmax is stored y[1] and //
// h_next has the value to the next size to try. //
// -1 The solution of y' = f(x,y) from x to xmax failed. //
// -2 Failed because either xmax < x or the step size h <= 0. //
// -3 Memory limit allocated for results was reached //
//========================================================================================================================================================================================================200
// DEFINE/INCLUDE
//========================================================================================================================================================================================================200
//======================================================================================================================================================150
// COMMON
//======================================================================================================================================================150
//======================================================================================================================================================150
// DEFINE
//======================================================================================================================================================150
#define ATTEMPTS 12
#define MIN_SCALE_FACTOR 0.125
#define MAX_SCALE_FACTOR 4.0
//======================================================================================================================================================150
// KERNEL
//======================================================================================================================================================150
#include "./embedded_fehlberg_7_8.c" // (in path provided here)
//======================================================================================================================================================150
// LIBRARIES
//======================================================================================================================================================150
#include <stdlib.h> // (in path known to compiler) needed by malloc, free
#include <math.h> // (in path known to compiler) needed by pow, fabs
//======================================================================================================================================================150
// END
//======================================================================================================================================================150
//========================================================================================================================================================================================================200
// FUNCTION
//========================================================================================================================================================================================================200
int
solver( fp **y,
fp *x,
int xmax,
fp *params,
fp *com,
long long *timecopyin,
long long *timecopykernel,
long long *timecopyout)
{
//========================================================================================================================
// VARIABLES
//========================================================================================================================
// solver parameters
fp err_exponent;
int error;
int outside;
fp h;
fp h_init;
fp tolerance;
int xmin;
// memory
fp scale_min;
fp scale_fina;
fp* err= (fp *) malloc(EQUATIONS* sizeof(fp));
fp* scale= (fp *) malloc(EQUATIONS* sizeof(fp));
fp* yy= (fp *) malloc(EQUATIONS* sizeof(fp));
// counters
int i, j, k;
//========================================================================================================================
// INITIAL SETUP
//========================================================================================================================
// solver parameters
err_exponent = 1.0 / 7.0;
h_init = 1;
h = h_init;
xmin = 0;
tolerance = 10 / (fp)(xmax-xmin);
// save value for initial time instance
x[0] = 0;
//========================================================================================================================
// CHECKING
//========================================================================================================================
// Verify that the step size is positive and that the upper endpoint of integration is greater than the initial enpoint. //
if (xmax < xmin || h <= 0.0){
return -2;
}
// If the upper endpoint of the independent variable agrees with the initial value of the independent variable. Set the value of the dependent variable and return success. //
if (xmax == xmin){
return 0;
}
// Insure that the step size h is not larger than the length of the integration interval. //
if (h > (xmax - xmin) ) {
h = (fp)xmax - (fp)xmin;
}
//========================================================================================================================
// SOLVING
//========================================================================================================================
#ifdef DEBUG
printf("Time Steps: ");
fflush(0);
#endif
#pragma omp target enter data map(alloc: params[0:PARAMETERS], com[0:3])
for(k=1; k<=xmax; k++) { // start after initial value
x[k] = k-1;
h = h_init;
//==========================================================================================
// REINITIALIZE VARIABLES
//==========================================================================================
scale_fina = 1.0;
//==========================================================================================
// MAKE ATTEMPTS TO MINIMIZE ERROR
//==========================================================================================
// make attempts to minimize error
for (j = 0; j < ATTEMPTS; j++) {
//============================================================
// REINITIALIZE VARIABLES
//============================================================
error = 0;
outside = 0;
scale_min = MAX_SCALE_FACTOR;
//============================================================
// EVALUATE ALL EQUATIONS
//============================================================
embedded_fehlberg_7_8( x[k],
h,
y[k-1],
y[k],
params,
com,
err,
timecopyin,
timecopykernel,
timecopyout);
//============================================================
// IF THERE WAS NO ERROR FOR ANY OF EQUATIONS, SET SCALE AND LEAVE THE LOOP
//============================================================
for(i=0; i<EQUATIONS; i++){
if(err[i] > 0){
error = 1;
}
}
if (error != 1) {
scale_fina = MAX_SCALE_FACTOR;
break;
}
//============================================================
// FIGURE OUT SCALE AS THE MINIMUM OF COMPONENT SCALES
//============================================================
for(i=0; i<EQUATIONS; i++){
if(y[k-1][i] == 0.0){
yy[i] = tolerance;
}
else{
yy[i] = fabs(y[k-1][i]);
}
scale[i] = 0.8 * pow( tolerance * yy[i] / err[i] , err_exponent );
if(scale[i]<scale_min){
scale_min = scale[i];
}
}
#define max(x,y) ( (x) < (y) ? (y) : (x) )
#define min(x,y) ( (x) < (y) ? (x) : (y) )
scale_fina = min( max(scale_min,MIN_SCALE_FACTOR), MAX_SCALE_FACTOR);
//============================================================
// IF WITHIN TOLERANCE, FINISH ATTEMPTS...
//============================================================
for(i=0; i<EQUATIONS; i++){
if ( err[i] > ( tolerance * yy[i] ) ){
outside = 1;
}
}
if (outside == 0){
break;
}
//============================================================
// ...OTHERWISE, ADJUST STEP FOR NEXT ATTEMPT
//============================================================
// scale next step in a default way
h = h * scale_fina;
// limit step to 0.9, because when it gets close to 1, it no longer makes sense, as 1 is already the next time instance (added to original algorithm)
if (h >= 0.9) {
h = 0.9;
}
// if instance+step exceeds range limit, limit to that range
if ( x[k] + h > (fp)xmax ){
h = (fp)xmax - x[k];
}
// if getting closer to range limit, decrease step
else if ( x[k] + h + 0.5 * h > (fp)xmax ){
h = 0.5 * h;
}
}
//==========================================================================================
// SAVE TIME INSTANCE THAT SOLVER ENDED UP USING
//==========================================================================================
x[k] = x[k] + h;
//==========================================================================================
// IF MAXIMUM NUMBER OF ATTEMPTS REACHED AND CANNOT GIVE SOLUTION, EXIT PROGRAM WITH ERROR
//==========================================================================================
if ( j >= ATTEMPTS ) {
#pragma omp target exit data map(release: params[0:PARAMETERS], com[0:3])
return -1;
}
#ifdef DEBUG
printf("%d ", k);
fflush(0);
#endif
}
#pragma omp target exit data map(release: params[0:PARAMETERS], com[0:3])
#ifdef DEBUG
printf("\n");
fflush(0);
#endif
//========================================================================================================================
// FREE MEMORY
//========================================================================================================================
free(err);
free(scale);
free(yy);
//========================================================================================================================
// FINAL RETURN
//========================================================================================================================
return 0;
}
|
IndexLinear.c
|
#ifndef TH_GENERIC_FILE
#define TH_GENERIC_FILE "generic/IndexLinear.c"
#else
#ifdef _OPENMP
#include <omp.h>
#endif
/* Threshold used to trigger multithreading */
#ifndef THNN_SPARSE_OMP_THRESHOLD
#define THNN_SPARSE_OMP_THRESHOLD 100000
#endif
/* Threshold used to trigger BLAS axpy call */
#ifndef THNN_SPARSE_OUTDIM_THRESHOLD
#define THNN_SPARSE_OUTDIM_THRESHOLD 49
#endif
/* sign MACRO */
#ifndef THNN_INDEXLINEAR_SIGN
#define THNN_INDEXLINEAR_SIGN(a) ( ( (a) < 0 ) ? -1 : ( (a) > 0 ) )
#endif
static bool THNN_(checkKeysValues)(THLongTensor* keys, THTensor* values)
{
return THLongTensor_size(keys, 0) == THTensor_(nElement)(values)
&& THTensor_(nDimension)(values) == 1
&& THLongTensor_nDimension(keys) == 1;
}
void THNN_(IndexLinear_updateOutput)(
THNNState *state,
THLongTensor *keys,
int64_t keysOffset,
THTensor *values,
THLongTensor *sizes,
THLongTensor *cumSumSizes,
THTensor *output,
THTensor *weight,
THTensor *bias,
THTensor *normalizedValues,
int train)
{
/* Retrieve all the dimensions of the problem */
int64_t batchSize = THLongTensor_size(sizes, 0);
int64_t keysSize = THLongTensor_size(keys, 0);
int64_t outDim = THTensor_(size)(bias, 0);
int64_t woutDim = THTensor_(size)(weight, 1);
int maxNormalize = woutDim - outDim;
int64_t* sizesData = THLongTensor_data(sizes);
int64_t* cumSumSizesData = THLongTensor_data(cumSumSizes);
/* Define/resize the normalized values tensor if maxNormalize is > 0 */
real* normalizedValuesData = NULL;
if (maxNormalize)
{
THTensor_(resize1d)(normalizedValues, keysSize);
normalizedValuesData = THTensor_(data)(normalizedValues);
}
/* Resize the output */
THTensor_(resize2d)(output, batchSize, outDim);
/* Access the storage data/strides */
real* outputData = THTensor_(data)(output);
real* valuesData = THTensor_(data)(values);
real* weightData = THTensor_(data)(weight);
int64_t weightStride0 = weight->stride[0];
real* biasData = THTensor_(data)(bias);
int64_t* keysData = THLongTensor_data(keys);
/* Make sure these inputs are contiguous to accelerate computations */
THArgCheck(THLongTensor_isContiguous(keys), 1, "keys vector must be contiguous");
THArgCheck(THTensor_(isContiguous)(values), 3, "values vector must be contiguous");
THArgCheck(THTensor_(isContiguous)(output), 6, "output vector must be contiguous");
THArgCheck(THTensor_(isContiguous)(weight), 7, "weight matrix must be contiguous");
THArgCheck(THTensor_(isContiguous)(bias), 8, "bias vector must be contiguous");
THArgCheck(THNN_(checkKeysValues)(keys, values), 1, "Keys and values should have the same number of elements");
THArgCheck(THTensor_(isContiguous)(normalizedValues), 9, "normalizedValues vector must be contiguous");
int64_t i,j,k;
/* Separate cases: output dimension is == 1, or > 1
* This allows for some optimizations. */
if (outDim == 1)
{
THVector_(fill)(outputData, *biasData, batchSize);
if (maxNormalize)
{
/* Parallelize on the batch itself */
#pragma omp parallel \
for private(i,j) \
firstprivate(outDim, keysOffset, \
weightData, keysData, \
valuesData, outputData, \
cumSumSizesData, sizesData) \
schedule(static) \
if(keysSize*outDim > THNN_SPARSE_OMP_THRESHOLD && batchSize > 1)
for (j = 0; j < batchSize; j++)
{
real* loutputData = outputData + j;
real val = 0;
real absVal = 0;
int64_t offset = j == 0 ? 0 : cumSumSizesData[j - 1];
for (i = 0; i < sizesData[j]; i++)
{
int64_t woffset = weightStride0*(keysData[offset] + keysOffset);
absVal = fabs(valuesData[offset]);
if (train)
{
if (absVal > weightData[woffset])
{
weightData[woffset] = absVal;
weightData[woffset+1] = 1/absVal;
}
/*
* The following can be used to scale the size of the updates
* depending on some rule, e.g. the frequency of a feature, ...
* This is used at update time.
* TODO: implement a smarter update scale.
*/
weightData[woffset+2] = 1;
}
normalizedValuesData[offset] = (absVal > weightData[woffset] ? THNN_INDEXLINEAR_SIGN(valuesData[offset]):valuesData[offset]*weightData[woffset+1]) + weightData[woffset+3];
val += normalizedValuesData[offset] * weightData[woffset+maxNormalize];
offset++;
}
*loutputData += val;
}
}
else
{
/* Parallelize on the batch itself */
#pragma omp parallel \
for private(i,j) \
firstprivate(outDim, weightData, \
keysData, valuesData, \
outputData, cumSumSizesData, \
sizesData) \
schedule(static) \
if(keysSize*outDim > THNN_SPARSE_OMP_THRESHOLD && batchSize > 1)
for (j = 0; j < batchSize; j++)
{
int64_t offset = j == 0 ? 0 : cumSumSizesData[j - 1];
real* loutputData = outputData + j;
real val = 0;
for (i = 0; i < sizesData[j]; i++)
{
val += weightData[weightStride0*(keysData[offset] + keysOffset)] * valuesData[offset];
offset++;
}
*loutputData += val;
}
}
}
else {
#pragma omp parallel \
for private(i,j,k) \
firstprivate(outDim, weightData, \
keysData, valuesData, \
biasData, outputData, \
cumSumSizesData, sizesData) \
schedule(static) \
if(keysSize*outDim > THNN_SPARSE_OMP_THRESHOLD && batchSize > 1)
for (j = 0; j < batchSize; j++)
{
int64_t offset = j == 0 ? 0 : cumSumSizesData[j - 1];
real val = 0;
real* loutputData = outputData + j*outDim;
real* lweightData = weightData;
memcpy(loutputData, biasData, outDim*sizeof(real));
for (i = 0; i < sizesData[j]; i++)
{
real val;
int64_t woffset = weightStride0*(keysData[offset] + keysOffset);
if (maxNormalize)
{
val = valuesData[offset];
real absVal = fabs(val);
if (train)
{
if (absVal > weightData[woffset])
{
weightData[woffset] = absVal;
weightData[woffset+1] = 1/absVal;
}
/*
* The following can be used to scale the size of the updates
* depending on some rule, e.g. the frequency of a feature, ...
* The commented section thereafter is just an example of what can be done:
*
*```
* weightData[woffset+2] = weightData[woffset+2]==0?1:(weightData[woffset+2] / (weightData[woffset+2] + 1));
* real alpha = 1;
* real beta = 0.01;
* real gamma = 1 - 0.000001;
* real l = weightData[woffset+2]==0?1/gamma:(weightData[woffset+2] - beta) / (alpha - beta);
* l = gamma*l;
* weightData[woffset+2] = (alpha-beta)*l + beta;
* ```
*
* TODO: implement a smarter update scale.
*/
weightData[woffset+2] = 1;
}
/* Normalize + Clamp */
val = (absVal > weightData[woffset] ? THNN_INDEXLINEAR_SIGN(val):val*weightData[woffset+1]) + weightData[woffset+3];
normalizedValuesData[offset] = val;
lweightData = weightData + woffset + maxNormalize;
}
else
{
val = valuesData[offset];
lweightData = weightData + woffset;
}
if (outDim > THNN_SPARSE_OUTDIM_THRESHOLD)
{
THBlas_(axpy)(outDim, val, lweightData, 1, loutputData, 1);
}
else
{
for (k=0; k < outDim; k++)
{
loutputData[k] += lweightData[k] * val;
}
}
offset++;
}
}
}
return;
}
void THNN_(IndexLinear_updateParameters)(
THNNState *state,
THTensor *gradWeight,
THTensor *gradBias,
THTensor *weight,
THTensor *bias,
THLongTensor *runningKeys,
THLongTensor *cumSumSizes,
int64_t keysOffset,
accreal weightDecay_,
accreal learningRate_)
{
real weightDecay = TH_CONVERT_ACCREAL_TO_REAL(weightDecay_);
real learningRate = TH_CONVERT_ACCREAL_TO_REAL(learningRate_);
/* Retrieve all the dimensions of the problem */
int64_t outDim = THTensor_(size)(bias, 0);
int64_t woutDim = THTensor_(size)(weight, 1);
int maxNormalize = woutDim - outDim;
int64_t keysSize = THLongTensor_size(runningKeys, 0);
/* Access the storage data/strides */
real* gradWeightData = THTensor_(data)(gradWeight);
real* weightData = THTensor_(data)(weight);
int64_t weightStride0 = weight->stride[0];
real* gradBiasData = THTensor_(data)(gradBias);
real* biasData = THTensor_(data)(bias);
int64_t* keysData = THLongTensor_data(runningKeys);
/* Make sure these inputs are contiguous to accelerate computations */
THArgCheck(THTensor_(isContiguous)(gradWeight), 1, "gradWeight must be contiguous");
THArgCheck(THTensor_(isContiguous)(gradBias), 2, "gradBias vector must be contiguous");
THArgCheck(THTensor_(isContiguous)(weight), 3, "gradBias vector must be contiguous");
THArgCheck(THTensor_(isContiguous)(bias), 4, "gradBias vector must be contiguous");
THArgCheck(THLongTensor_isContiguous(runningKeys), 5, "keys vector must be contiguous");
int j,k;
int64_t offset = 0;
/* Update the bias first */
THVector_(cadd)(biasData, biasData, gradBiasData, -learningRate, outDim);
/* Separate cases: output dimension is == 1, or > 1
* This allows for some optimizations.
* No multithreading here as this could
* corrupt the results (hogwild style) */
if (outDim == 1)
{
if (maxNormalize)
{
if (weightDecay)
{
for (j = 0; j < keysSize; j++)
{
int64_t woffset = weightStride0*(keysData[j] + keysOffset) + maxNormalize;
real lr = learningRate*weightData[woffset-2];
weightData[woffset-1] -= weightData[woffset]*gradWeightData[2*j]*lr;
weightData[woffset] -= gradWeightData[2*j+1]*lr - weightDecay * weightData[woffset-2] * weightData[woffset];
}
}
else
{
for (j = 0; j < keysSize; j++)
{
int64_t woffset = weightStride0*(keysData[j] + keysOffset) + maxNormalize;
real lr = learningRate*weightData[woffset-2];
weightData[woffset-1] -= weightData[woffset]*gradWeightData[2*j]*lr;
weightData[woffset] -= gradWeightData[2*j+1]*lr;
}
}
}
else
{
if (weightDecay)
{
for (j = 0; j < keysSize; j++)
{
int64_t woffset = weightStride0*(keysData[j] + keysOffset);
weightData[woffset] -= gradWeightData[j]*learningRate + weightDecay * weightData[woffset];
}
}
else
{
for (j = 0; j < keysSize; j++)
{
weightData[weightStride0*(keysData[j] + keysOffset)] -= gradWeightData[j]*learningRate;
}
}
}
}
else
{
for (j = 0; j < keysSize; j++)
{
real lr = learningRate;
real wd = weightDecay;
real* lweightData;
int64_t woffset = weightStride0*(keysData[j] + keysOffset);
real* lgradWeightData = gradWeightData + j*outDim;
if (maxNormalize)
{
lgradWeightData += j*outDim;
/* weightData[woffset + 2] */
lweightData = weightData + woffset + maxNormalize - 2;
lr = lr*lweightData[0];
wd = weightDecay*lweightData[0];
/* weightData[woffset + 3] */
lweightData++;
for (k=0; k < outDim; k++)
{
lweightData[0] -= lgradWeightData[k]*lweightData[k+1]*lr;
}
lweightData++;
lgradWeightData += outDim;
}
else
{
lweightData = weightData + woffset;
}
/* We do sparse weight decay.
* We think it makes more sense. */
if (weightDecay)
{
for (k=0; k < outDim; k++)
{
lweightData[k] -= lweightData[k]*wd;
}
}
if (outDim > THNN_SPARSE_OUTDIM_THRESHOLD)
{
THBlas_(axpy)(outDim, -lr, lgradWeightData, 1, lweightData, 1);
}
else
{
for (k=0; k < outDim; k++)
{
lweightData[k] -= lgradWeightData[k]*lr;
}
}
}
}
}
void THNN_(IndexLinear_accUpdateGradParameters)(
THNNState *state,
THLongTensor *keys,
int64_t keysOffset,
THTensor *values,
THLongTensor *sizes,
THLongTensor *cumSumSizes,
THTensor *gradOutput,
THTensor *weight,
THTensor *bias,
accreal weightDecay_,
accreal scale_)
{
real weightDecay = TH_CONVERT_ACCREAL_TO_REAL(weightDecay_);
real scale = TH_CONVERT_ACCREAL_TO_REAL(scale_);
/* Retrieve all the dimensions of the problem */
int64_t batchSize = THLongTensor_size(sizes, 0);
int64_t keysSize = THLongTensor_size(keys, 0);
int64_t outDim = THTensor_(size)(bias, 0);
int64_t woutDim = THTensor_(size)(weight, 1);
int maxNormalize = woutDim - outDim;
THArgCheck(THNN_(checkKeysValues)(keys, values), 1, "Keys and values should have the same number of elements");
/* Access the storage data/strides */
real* gradOutputData = THTensor_(data)(gradOutput);
real* valuesData =THTensor_(data)(values);
real* weightData = THTensor_(data)(weight);
real* biasData = THTensor_(data)(bias);
int64_t weightStride0 = weight->stride[0];
int64_t biasStride = bias->stride[0];
int64_t* keysData = THLongTensor_data(keys);
int64_t* sizesData = THLongTensor_data(sizes);
/* Make sure these inputs are contiguous to accelerate computations */
THArgCheck(THLongTensor_isContiguous(keys), 1, "keys vector must be contiguous");
THArgCheck(THTensor_(isContiguous)(values), 3, "values vector must be contiguous");
THArgCheck(THTensor_(isContiguous)(gradOutput), 6, "gradOutput vector must be contiguous");
THArgCheck(THTensor_(isContiguous)(weight), 7, "weight matrix must be contiguous");
THArgCheck(THTensor_(isContiguous)(bias), 8, "bias matrix must be contiguous");
int i,j,k;
/* Separate cases: output dimension is == 1, or > 1
* This allows for some optimizations.
* No multithreading here as this could
* corrupt the results (hogwild style) */
if (outDim == 1)
{
if (maxNormalize)
{
int64_t offset = 0;
for (j = 0; j < batchSize; j++)
{
real* lgradOutputData = gradOutputData + j;
*biasData -= *lgradOutputData * scale;
real val = *lgradOutputData * scale;
real* lweightData = weightData;
for (i = 0; i < sizesData[j]; i++)
{
int64_t idx = weightStride0*(keysData[offset] + keysOffset) + maxNormalize;
weightData[idx-1] -= weightData[idx]*val*weightData[idx-2];
weightData[idx] -= (val*valuesData[offset] - weightDecay * weightData[idx])*weightData[idx-2];
offset++;
}
}
offset = 0;
for (j = 0; j < batchSize; j++)
{
real* lweightData = weightData;
for (i = 0; i < sizesData[j]; i++)
{
int64_t idx = weightStride0*(keysData[offset] + keysOffset) + maxNormalize;
weightData[idx-2] = 0;
offset++;
}
}
}
else
{
if (weightDecay)
{
int64_t offset = 0;
for (j = 0; j < batchSize; j++)
{
real* lgradOutputData = gradOutputData + j;
*biasData -= *lgradOutputData * scale;
real val = *lgradOutputData * scale;
real* lweightData = weightData;
for (i = 0; i < sizesData[j]; i++)
{
int64_t idx = weightStride0*(keysData[offset] + keysOffset);
weightData[idx] -= val * valuesData[offset] + weightData[idx] * weightDecay;
offset++;
}
}
}
else
{
int64_t offset = 0;
for (j = 0; j < batchSize; j++)
{
real val = gradOutputData[j] * scale;
for (i = 0; i < sizesData[j]; i++)
{
weightData[(keysData[offset] + keysOffset)*weightStride0] -= val * valuesData[offset];
offset++;
}
*biasData -= val;
}
}
}
}
else {
int64_t offset = 0;
for (j = 0; j < batchSize; j++)
{
real val = 0;
real* lgradOutputData = gradOutputData + j*outDim;
real* lweightData = weightData;
THVector_(cadd)(biasData, biasData, lgradOutputData, -scale, outDim);
for (i = 0; i < sizesData[j]; i++)
{
real val = valuesData[offset] * scale;
real wd = weightDecay;
// Max normalize case
if (maxNormalize)
{
lweightData = weightData + weightStride0*(keysData[offset] + keysOffset) + (maxNormalize-2);
val *= lweightData[0];
wd *= lweightData[0];
for (k=0; k < outDim; k++)
{
lweightData[1] -= lweightData[k+2]*scale*lgradOutputData[k]*lweightData[0];
}
lweightData += 2;
}
else
{
lweightData = weightData + weightStride0*(keysData[offset] + keysOffset);
}
/* We do sparse weight decay.
* We think it makes more sense. */
if (weightDecay)
{
if (outDim > THNN_SPARSE_OUTDIM_THRESHOLD)
{
THBlas_(axpy)(outDim, -wd, lweightData, 1, lweightData, 1);
}
else
{
for (k=0; k < outDim; k++)
{
lweightData[k] -= wd * lweightData[k];
}
}
}
if (outDim > THNN_SPARSE_OUTDIM_THRESHOLD)
{
THBlas_(axpy)(outDim, -val, lgradOutputData, 1, lweightData, 1);
}
else
{
for (k=0; k < outDim; k++)
{
lweightData[k] -= val * lgradOutputData[k];
}
}
offset++;
}
}
/* Max Normalize case:
* Reset the smart update scaling if
* one does it batch-wise.
* TODO: Decide what to do with that piece of code.
* NB: If the code belowe is uncommented, so should the commented
* code in IndexLinear:zeroGradParameters() */
/*
if (maxNormalize)
{
offset = 0;
for (j = 0; j < batchSize; j++)
{
real* lweightData = weightData;
for (i = 0; i < sizesData[j]; i++)
{
real val = valuesData[offset] * scale;
real wd = weightDecay;
lweightData = weightData + weightStride0*(keysData[offset] + keysOffset) + (maxNormalize-2);
lweightData[0] = 0;
offset++;
}
}
}
*/
}
return;
}
void THNN_(IndexLinear_accGradParameters)(
THNNState *state,
THLongTensor *keys,
int64_t keysOffset,
THTensor *values,
THLongTensor *sizes,
THLongTensor *cumSumSizes,
THTensor *gradOutput,
THTensor *gradWeight,
THTensor *gradBias,
THTensor *weight,
THTensor *bias,
THTensor *valuesBuffer,
accreal weightDecay_,
accreal scale_)
{
real weightDecay = TH_CONVERT_ACCREAL_TO_REAL(weightDecay_);
real scale = TH_CONVERT_ACCREAL_TO_REAL(scale_);
/* Retrieve all the dimensions of the problem */
int64_t batchSize = THLongTensor_size(sizes, 0);
int64_t keysSize = THLongTensor_size(keys, 0);
int64_t outDim = THTensor_(size)(bias, 0);
int64_t woutDim = THTensor_(size)(weight, 1);
int64_t maxNormalize = (woutDim - outDim) > 0 ?1:0;
THArgCheck(THNN_(checkKeysValues)(keys, values), 1, "Keys and values should have the same number of elements");
int64_t* sizesData = THLongTensor_data(sizes);
/* COmpute the cumulative sizes */
THLongTensor* cumSizes = THLongTensor_new();
THLongTensor_cumsum(cumSizes, sizes, 0);
int64_t* cumSizesData = THLongTensor_data(cumSizes);
/* Resize the gradWeight buffer to keep it dense.
* That speeds up updates A LOT assuming random mem access. */
THTensor_(resize2d)(gradWeight, keysSize, outDim * (maxNormalize>0?2:1));
/* Access the storage data/strides */
real* gradOutputData = THTensor_(data)(gradOutput);
real* valuesData =THTensor_(data)(values);
real* gradWeightData = THTensor_(data)(gradWeight);
real* weightData = THTensor_(data)(weight);
real* gradBiasData = THTensor_(data)(gradBias);
int64_t gradWeightStride0 = gradWeight->stride[0];
int64_t weightStride0 = weight->stride[0];
int64_t* keysData = THLongTensor_data(keys);
/* Make sure these inputs are contiguous to accelerate computations */
THArgCheck(THLongTensor_isContiguous(keys), 1, "keys vector must be contiguous");
THArgCheck(THTensor_(isContiguous)(values), 3, "values vector must be contiguous");
THArgCheck(THTensor_(isContiguous)(gradOutput), 6, "gradOutput vector must be contiguous");
THArgCheck(THTensor_(isContiguous)(gradWeight), 7, "gradWeight must be contiguous");
THArgCheck(THTensor_(isContiguous)(gradBias), 8, "gradBias vector must be contiguous");
THArgCheck(THTensor_(isContiguous)(weight), 9, "weight must be contiguous");
THArgCheck(THTensor_(isContiguous)(bias), 10, "bias vector must be contiguous");
THArgCheck(THTensor_(isContiguous)(valuesBuffer), 11, "valuesBuffer must be contiguous");
int i,j,k;
/* Separate cases: output dimension is == 1, or > 1
* This allows for some optimizations.
* No multithreading here as this could
* corrupt the results (hogwild style) */
if (outDim == 1)
{
for (j = 0; j < batchSize; j++)
{
int64_t offset = j==0?0:cumSizesData[j-1];
real val = gradOutputData[j] * scale;
real* lgradWeightData = gradWeightData + offset;
real* lvaluesData = valuesData + offset;
int64_t end = sizesData[j];
if (maxNormalize)
{
lgradWeightData += offset;
i = 0;
for(;i < end; i++)
{
lgradWeightData[2*i] = val;
lgradWeightData[2*i+1] = val * lvaluesData[i];
}
}
else
{
i = 0;
for(;i < end-4; i += 4)
{
lgradWeightData[i] = val * lvaluesData[i];
lgradWeightData[i+1] = val * lvaluesData[i+1];
lgradWeightData[i+2] = val * lvaluesData[i+2];
lgradWeightData[i+3] = val * lvaluesData[i+3];
}
for(; i < end; i++)
{
lgradWeightData[i] = val * lvaluesData[i];
}
}
*gradBiasData += val;
offset += end;
}
}
else {
for (j = 0; j < batchSize; j++)
{
int64_t offset = j==0?0:cumSizesData[j-1];
real val = 0;
real* lgradOutputData = gradOutputData + j*outDim;
real* lgradWeightData = gradWeightData;
real* lweightData = weightData;
THVector_(cadd)(gradBiasData, gradBiasData, lgradOutputData, scale, outDim);
for (i = 0; i < sizesData[j]; i++)
{
real val = valuesData[offset] * scale;
lgradWeightData = gradWeightData + offset*outDim;
if (maxNormalize)
{
lgradWeightData += offset*outDim;
k = 0;
for(;k < outDim-4; k += 4)
{
lgradWeightData[k] = lgradOutputData[k]*scale;
lgradWeightData[k+1] = lgradOutputData[k+1]*scale;
lgradWeightData[k+2] = lgradOutputData[k+2]*scale;
lgradWeightData[k+3] = lgradOutputData[k+3]*scale;
}
for(; k < outDim; k++)
{
lgradWeightData[k] = lgradOutputData[k]*scale;
}
lgradWeightData += outDim;
}
k = 0;
for(;k < outDim-4; k += 4)
{
lgradWeightData[k] = val * lgradOutputData[k];
lgradWeightData[k+1] = val * lgradOutputData[k+1];
lgradWeightData[k+2] = val * lgradOutputData[k+2];
lgradWeightData[k+3] = val * lgradOutputData[k+3];
}
for(; k < outDim; k++)
{
lgradWeightData[k] = val * lgradOutputData[k];
}
offset++;
}
}
}
THLongTensor_free(cumSizes);
return;
}
#endif
|
omp_loop.h
|
// -*- C++ -*-
// Copyright (C) 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library is free
// software; you can redistribute it and/or modify it under the terms
// of the GNU General Public License as published by the Free Software
// Foundation; either version 3, or (at your option) any later
// version.
// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
// Under Section 7 of GPL version 3, you are granted additional
// permissions described in the GCC Runtime Library Exception, version
// 3.1, as published by the Free Software Foundation.
// You should have received a copy of the GNU General Public License and
// a copy of the GCC Runtime Library Exception along with this program;
// see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
// <http://www.gnu.org/licenses/>.
/** @file parallel/omp_loop.h
* @brief Parallelization of embarrassingly parallel execution by
* means of an OpenMP for loop.
* This file is a GNU parallel extension to the Standard C++ Library.
*/
// Written by Felix Putze.
#ifndef _GLIBCXX_PARALLEL_OMP_LOOP_H
#define _GLIBCXX_PARALLEL_OMP_LOOP_H 1
#include <omp.h>
#include <parallel/settings.h>
#include <parallel/basic_iterator.h>
#include <parallel/base.h>
namespace __gnu_parallel
{
/** @brief Embarrassingly parallel algorithm for random access
* iterators, using an OpenMP for loop.
*
* @param __begin Begin iterator of element sequence.
* @param __end End iterator of element sequence.
* @param __o User-supplied functor (comparator, predicate, adding
* functor, etc.).
* @param __f Functor to @a process an element with __op (depends on
* desired functionality, e. g. for std::for_each(), ...).
* @param __r Functor to @a add a single __result to the already
* processed elements (depends on functionality).
* @param __base Base value for reduction.
* @param __output Pointer to position where final result is written to
* @param __bound Maximum number of elements processed (e. g. for
* std::count_n()).
* @return User-supplied functor (that may contain a part of the result).
*/
template<typename _RAIter,
typename _Op,
typename _Fu,
typename _Red,
typename _Result>
_Op
__for_each_template_random_access_omp_loop(_RAIter __begin, _RAIter __end,
_Op __o, _Fu& __f, _Red __r,
_Result __base,
_Result& __output,
typename std::iterator_traits<_RAIter>::difference_type __bound)
{
typedef typename std::iterator_traits<_RAIter>::difference_type
_DifferenceType;
_DifferenceType __length = __end - __begin;
_ThreadIndex __num_threads = __gnu_parallel::min<_DifferenceType>
(__get_max_threads(), __length);
_Result *__thread_results;
# pragma omp parallel num_threads(__num_threads)
{
# pragma omp single
{
__num_threads = omp_get_num_threads();
__thread_results = new _Result[__num_threads];
for (_ThreadIndex __i = 0; __i < __num_threads; ++__i)
__thread_results[__i] = _Result();
}
_ThreadIndex __iam = omp_get_thread_num();
#pragma omp for schedule(dynamic, _Settings::get().workstealing_chunk_size)
for (_DifferenceType __pos = 0; __pos < __length; ++__pos)
__thread_results[__iam] = __r(__thread_results[__iam],
__f(__o, __begin+__pos));
} //parallel
for (_ThreadIndex __i = 0; __i < __num_threads; ++__i)
__output = __r(__output, __thread_results[__i]);
delete [] __thread_results;
// Points to last element processed (needed as return value for
// some algorithms like transform).
__f._M_finish_iterator = __begin + __length;
return __o;
}
} // end namespace
#endif /* _GLIBCXX_PARALLEL_OMP_LOOP_H */
|
1999.c
|
/* POLYBENCH/GPU-OPENMP
*
* This file is a part of the Polybench/GPU-OpenMP suite
*
* Contact:
* William Killian <[email protected]>
*
* Copyright 2013, The University of Delaware
*/
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <math.h>
/* Include polybench common header. */
#include <polybench.h>
/* Include benchmark-specific header. */
/* Default data type is double, default size is 4000. */
#include "3mm.h"
/* Array initialization. */
static
void init_array(int ni, int nj, int nk, int nl, int nm,
DATA_TYPE POLYBENCH_2D(A,NI,NK,ni,nk),
DATA_TYPE POLYBENCH_2D(B,NK,NJ,nk,nj),
DATA_TYPE POLYBENCH_2D(C,NJ,NM,nj,nm),
DATA_TYPE POLYBENCH_2D(D,NM,NL,nm,nl))
{
int i, j;
for (i = 0; i < ni; i++)
for (j = 0; j < nk; j++)
A[i][j] = ((DATA_TYPE) i*j) / ni;
for (i = 0; i < nk; i++)
for (j = 0; j < nj; j++)
B[i][j] = ((DATA_TYPE) i*(j+1)) / nj;
for (i = 0; i < nj; i++)
for (j = 0; j < nm; j++)
C[i][j] = ((DATA_TYPE) i*(j+3)) / nl;
for (i = 0; i < nm; i++)
for (j = 0; j < nl; j++)
D[i][j] = ((DATA_TYPE) i*(j+2)) / nk;
}
/* DCE code. Must scan the entire live-out data.
Can be used also to check the correctness of the output. */
static
void print_array(int ni, int nl,
DATA_TYPE POLYBENCH_2D(G,NI,NL,ni,nl))
{
int i, j;
for (i = 0; i < ni; i++)
for (j = 0; j < nl; j++) {
fprintf (stderr, DATA_PRINTF_MODIFIER, G[i][j]);
if ((i * ni + j) % 20 == 0) fprintf (stderr, "\n");
}
fprintf (stderr, "\n");
}
/* Main computational kernel. The whole function will be timed,
including the call and return. */
static
void kernel_3mm(int ni, int nj, int nk, int nl, int nm,
DATA_TYPE POLYBENCH_2D(E,NI,NJ,ni,nj),
DATA_TYPE POLYBENCH_2D(A,NI,NK,ni,nk),
DATA_TYPE POLYBENCH_2D(B,NK,NJ,nk,nj),
DATA_TYPE POLYBENCH_2D(F,NJ,NL,nj,nl),
DATA_TYPE POLYBENCH_2D(C,NJ,NM,nj,nm),
DATA_TYPE POLYBENCH_2D(D,NM,NL,nm,nl),
DATA_TYPE POLYBENCH_2D(G,NI,NL,ni,nl))
{
int i, j, k;
#pragma scop
#pragma omp parallel private (j, k) num_threads(2)
{
/* E := A*B */
#pragma omp for schedule(static, 16)
for (i = 0; i < _PB_NI; i++)
for (j = 0; j < _PB_NJ; j++)
{
E[i][j] = 0;
for (k = 0; k < _PB_NK; ++k)
E[i][j] += A[i][k] * B[k][j];
}
/* F := C*D */
#pragma omp for schedule(static, 16)
for (i = 0; i < _PB_NJ; i++)
for (j = 0; j < _PB_NL; j++)
{
F[i][j] = 0;
for (k = 0; k < _PB_NM; ++k)
F[i][j] += C[i][k] * D[k][j];
}
/* G := E*F */
#pragma omp for schedule(static, 16)
for (i = 0; i < _PB_NI; i++)
for (j = 0; j < _PB_NL; j++)
{
G[i][j] = 0;
for (k = 0; k < _PB_NJ; ++k)
G[i][j] += E[i][k] * F[k][j];
}
}
#pragma endscop
}
int main(int argc, char** argv)
{
/* Retrieve problem size. */
int ni = NI;
int nj = NJ;
int nk = NK;
int nl = NL;
int nm = NM;
/* Variable declaration/allocation. */
POLYBENCH_2D_ARRAY_DECL(E, DATA_TYPE, NI, NJ, ni, nj);
POLYBENCH_2D_ARRAY_DECL(A, DATA_TYPE, NI, NK, ni, nk);
POLYBENCH_2D_ARRAY_DECL(B, DATA_TYPE, NK, NJ, nk, nj);
POLYBENCH_2D_ARRAY_DECL(F, DATA_TYPE, NJ, NL, nj, nl);
POLYBENCH_2D_ARRAY_DECL(C, DATA_TYPE, NJ, NM, nj, nm);
POLYBENCH_2D_ARRAY_DECL(D, DATA_TYPE, NM, NL, nm, nl);
POLYBENCH_2D_ARRAY_DECL(G, DATA_TYPE, NI, NL, ni, nl);
/* Initialize array(s). */
init_array (ni, nj, nk, nl, nm,
POLYBENCH_ARRAY(A),
POLYBENCH_ARRAY(B),
POLYBENCH_ARRAY(C),
POLYBENCH_ARRAY(D));
/* Start timer. */
polybench_start_instruments;
/* Run kernel. */
kernel_3mm (ni, nj, nk, nl, nm,
POLYBENCH_ARRAY(E),
POLYBENCH_ARRAY(A),
POLYBENCH_ARRAY(B),
POLYBENCH_ARRAY(F),
POLYBENCH_ARRAY(C),
POLYBENCH_ARRAY(D),
POLYBENCH_ARRAY(G));
/* Stop and print timer. */
polybench_stop_instruments;
polybench_print_instruments;
/* Prevent dead-code elimination. All live-out data must be printed
by the function call in argument. */
polybench_prevent_dce(print_array(ni, nl, POLYBENCH_ARRAY(G)));
/* Be clean. */
POLYBENCH_FREE_ARRAY(E);
POLYBENCH_FREE_ARRAY(A);
POLYBENCH_FREE_ARRAY(B);
POLYBENCH_FREE_ARRAY(F);
POLYBENCH_FREE_ARRAY(C);
POLYBENCH_FREE_ARRAY(D);
POLYBENCH_FREE_ARRAY(G);
return 0;
}
|
vq.h
|
//
// Created by xydai on 2020/5/18.
//
#ifndef HNSW_LIB_UTIL_H
#define HNSW_LIB_UTIL_H
#include <cstdint>
#include <stdexcept>
#include "simd.h"
int vq(const float *centroids, const float *x, int ks, int dsub) {
int id = 0;
float min_dist = fvec_L2sqr(centroids, x, dsub);
for (int i = 1; i < ks; ++i) {
centroids += dsub;
float dist = fvec_L2sqr(centroids, x, dsub);
if (dist < min_dist) {
id = i;
}
}
return id;
}
/**
* @param centroids M * ks * dsub
* @param codes nx * M
* @return
*/
void vq(uint8_t* codes, const float *centroids, const float *x,
const int ks, const int nx, const int d, const int M) {
if (d % M != 0) {
throw std::runtime_error("d is not dividable by M.");
}
const int dsub = d / M;
#pragma omp parallel for
for (int i = 0; i < nx; ++i) {
for (int m = 0; m < M; ++m) {
codes[i * M + m] = vq(centroids + m * ks * dsub,
x + i * d + m * dsub, ks, dsub);
}
}
}
/**
* @param dt M * ks
*/
void compute_distance_table(float* dt, const float *centroids,
const float *x, int ks, int d, int M) {
if (d % M != 0) {
throw std::runtime_error("d is not dividable by M.");
}
int dsub = d / M;
for (int m = 0; m < M; ++m) {
for (int k = 0; k < ks; ++k) {
dt[m * ks + k] = fvec_L2sqr(x + m * dsub,
centroids + m * ks * dsub + k * dsub, dsub);
}
}
}
#endif //HNSW_LIB_UTIL_H
|
GB_unop__identity_int16_int16.c
|
//------------------------------------------------------------------------------
// GB_unop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated/ folder, do not edit it (auto-generated).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_atomics.h"
#include "GB_unop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB_unop_apply__identity_int16_int16
// op(A') function: GB_unop_tran__identity_int16_int16
// C type: int16_t
// A type: int16_t
// cast: int16_t cij = aij
// unaryop: cij = aij
#define GB_ATYPE \
int16_t
#define GB_CTYPE \
int16_t
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
int16_t aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = x ;
// casting
#define GB_CAST(z, aij) \
int16_t z = aij ;
// cij = op (aij)
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
int16_t aij = Ax [pA] ; \
/* Cx [pC] = op (cast (aij)) */ \
int16_t z = aij ; \
Cx [pC] = z ; \
}
// true if operator is the identity op with no typecasting
#define GB_OP_IS_IDENTITY_WITH_NO_TYPECAST \
1
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_IDENTITY || GxB_NO_INT16)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop_apply__identity_int16_int16
(
int16_t *Cx, // Cx and Ax may be aliased
const int16_t *Ax,
const int8_t *GB_RESTRICT Ab, // A->b if A is bitmap
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
if (Ab == NULL)
{
#if ( GB_OP_IS_IDENTITY_WITH_NO_TYPECAST )
GB_memcpy (Cx, Ax, anz * sizeof (int16_t), nthreads) ;
#else
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
int16_t aij = Ax [p] ;
int16_t z = aij ;
Cx [p] = z ;
}
#endif
}
else
{
// bitmap case, no transpose; A->b already memcpy'd into C->b
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!Ab [p]) continue ;
int16_t aij = Ax [p] ;
int16_t z = aij ;
Cx [p] = z ;
}
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop_tran__identity_int16_int16
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t *GB_RESTRICT *Workspaces,
const int64_t *GB_RESTRICT A_slice,
int nworkspaces,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
sumavectores-Parallel.c
|
/* SumaVectoresC.c
Suma de dos vectores: v3 = v1 + v2
Para compilar usar (-lrt: real time library):
gcc -O2 SumaVectores.c -o SumaVectores -lrt
Para ejecutar use: SumaVectoresC longitud
*/
#include <stdlib.h> // biblioteca con funciones atoi(), malloc() y free()
#include <stdio.h> // biblioteca donde se encuentra la función printf()
#include <time.h> // biblioteca donde se encuentra la función clock_gettime()
//#define PRINTF_ALL // comentar para quitar el printf ...
// que imprime todos los componentes
//Sólo puede estar definida una de las tres constantes VECTOR_ (sólo uno de los ...
//tres defines siguientes puede estar descomentado):
//#define VECTOR_LOCAL // descomentar para que los vectores sean variables ...
// locales (si se supera el tamaño de la pila se ...
// generará el error "Violación de Segmento")
//#define VECTOR_GLOBAL// descomentar para que los vectores sean variables ...
// globales (su longitud no estará limitada por el ...
// tamaño de la pila del programa)
#define VECTOR_DYNAMIC // descomentar para que los vectores sean variables ...
// dinámicas (memoria reutilizable durante la ejecución)
#ifdef VECTOR_GLOBAL
#define MAX 4294967295//=2^32-1
double v1[MAX], v2[MAX], v3[MAX];
#endif
int main(int argc, char** argv){
int i;
struct timespec cgt1,cgt2; double ncgt; //para tiempo de ejecución
//Leer argumento de entrada (no de componentes del vector)
if (argc<2){
printf("Faltan no componentes del vector\n");
exit(-1);
}
unsigned int N = atoi(argv[1]); // Máximo N =2^32-1=4294967295 (sizeof(unsigned int) = 4 B)
#ifdef VECTOR_LOCAL
double v1[N], v2[N], v3[N];
// Tamaño variable local en tiempo de ejecución ...
// disponible en C a partir de actualización C99
#endif
#ifdef VECTOR_GLOBAL
if (N>MAX) N=MAX;
#endif
#ifdef VECTOR_DYNAMIC
double *v1, *v2, *v3;
v1 = (double*) malloc(N*sizeof(double));// malloc necesita el tamaño en bytes
v2 = (double*) malloc(N*sizeof(double)); //si no hay espacio suficiente malloc devuelve NULL
v3 = (double*) malloc(N*sizeof(double));
if ( (v1==NULL) || (v2==NULL) || (v3==NULL) ){
printf("Error en la reserva de espacio para los vectores\n");
exit(-2);
}
#endif
//Inicializando los vectores
#pragma omp parallel
{
#pragma omp for
for(i=0; i<N; i++){
v1[i] = N*0.1+i*0.1; v2[i] = N*0.1-i*0.1; //los valores dependen de N
}
#pragma omp single
{
clock_gettime(CLOCK_REALTIME,&cgt1);
}
//Calcular suma de vectores
#pragma omp for
for(i=0; i<N; i++)
{
v3[i] = v1[i] + v2[i];
}
#pragma omp sigle
{
clock_gettime(CLOCK_REALTIME,&cgt2);
}
}
ncgt=(double) (cgt2.tv_sec-cgt1.tv_sec)+
(double) ((cgt2.tv_nsec-cgt1.tv_nsec)/(1.e+9));
//Imprimir resultado de la suma y el tiempo de ejecución
#ifdef PRINTF_ALL
printf("Tiempo(seg.):%11.9f\t / Tamaño Vectores:%u\n",ncgt,N);
printf("/ V1[0] = %d, V2[0] = %d\n", v1[0],v2[0]);
for(i=0; i<N; i++)
{
printf("/ V1[%d]+V2[%d]=V3[%d](%8.6f+%8.6f=%8.6f) /\n", i,i,i,v1[i],v2[i],v3[i]);
}
printf("/ V1[%d] = %d, V2[%d] = %d", N,v1[N],N,v2[N]);
#else
printf("Tiempo(seg.):%11.9f\t / Tamaño Vectores:%u\t/ V1[0]+V2[0]=V3[0](%8.6f+%8.6f=%8.6f) / /V1[%d]+V2[%d]=V3[%d](%8.6f+%8.6f=%8.6f) /\n", ncgt,N,v1[0],v2[0],v3[0],N-1,N-1,N-1,v1[N-1],v2[N-1],v3[N-1]);
#endif
#ifdef VECTOR_DYNAMIC
free(v1); // libera el espacio reservado para v1
free(v2); // libera el espacio reservado para v2
free(v3); // libera el espacio reservado para v3
#endif
return 0;
}
|
math_array.h
|
// -----------------------------------------------------------------------------
//
// Copyright (C) 2021 CERN & Newcastle University for the benefit of the
// BioDynaMo collaboration. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
//
// See the LICENSE file distributed with this work for details.
// See the NOTICE file distributed with this work for additional information
// regarding copyright ownership.
//
// -----------------------------------------------------------------------------
#ifndef CORE_CONTAINER_MATH_ARRAY_H_
#define CORE_CONTAINER_MATH_ARRAY_H_
#include <algorithm>
#include <cassert>
#include <cmath>
#include <numeric>
#include <ostream>
#include <stdexcept>
#include <utility>
#include "core/util/root.h"
namespace bdm {
/// Array with a fixed number of elements. It implements the same behaviour
/// of the standard `std::array<T, N>` container. However, it provides also
/// several custom mathematical operations (e.g. Sum(), Norm() etc.).
template <class T, std::size_t N>
class MathArray { // NOLINT
public:
/// Default constructor
MathArray() {
#pragma omp simd
for (size_t i = 0; i < N; i++) {
data_[i] = T();
}
}
/// Constructor which accepts an std::initiliazer_list to set
/// the array's content.
/// \param l an initializer list
constexpr MathArray(std::initializer_list<T> l) {
assert(l.size() <= N);
auto it = l.begin();
for (uint64_t i = 0; i < N; i++) {
data_[i] = *(it++);
}
for (uint64_t i = l.size(); i < N; i++) {
data_[i] = T();
}
}
/// Return a pointer to the underlying data.
/// \return cont T pointer to the first entry of the array.
inline const T* data() const { return &data_[0]; } // NOLINT
/// Return the size of the array.
/// \return integer denoting the array's size.
inline const size_t size() const { return N; } // NOLINT
/// Check if the array is empty.
/// \return true if size() == 0, false otherwise.
inline const bool empty() const { return N == 0; } // NOLINT
/// Overloaded array subscript operator. It does not perform
/// any boundary checks.
/// \param idx element's index.
/// \return the requested element.
T& operator[](size_t idx) { return data_[idx]; }
/// Const overloaded array subscript operator.
/// \param idx element's index.
/// \return the requested element.
const T& operator[](size_t idx) const { return data_[idx]; }
/// Returns the element at the given position. It will throw
/// an std::out_of_range exception if the given index is out
/// of the array's boundaries.
/// \param idx the index of the element.
/// \return the requested element.
T& at(size_t idx) noexcept(false) { // NOLINT
if (idx > size() || idx < 0) {
throw std::out_of_range("The index is out of range");
}
return data_[idx];
}
const T* begin() const { return &(data_[0]); } // NOLINT
const T* end() const { return &(data_[N]); } // NOLINT
T* begin() { return &(data_[0]); } // NOLINT
T* end() { return &(data_[N]); } // NOLINT
/// Returns the element at the beginning of the array.
/// \return first element.
T& front() { return *(this->begin()); } // NOLINT
/// Return the element at the end of the array.
/// \return last element.
T& back() { // NOLINT
auto tmp = this->end();
tmp--;
return *tmp;
}
/// Assignment operator.
/// \param other the other MathArray instance.
/// \return the current MathArray.
MathArray& operator=(const MathArray& other) {
if (this != &other) {
assert(other.size() == N);
std::copy(other.data_, other.data_ + other.size(), data_);
}
return *this;
}
/// Equality operator.
/// \param other a MathArray instance.
/// \return true if they have the same content, false otherwise.
bool operator==(const MathArray& other) const {
if (other.size() != N) {
return false;
}
for (size_t i = 0; i < N; i++) {
if (other[i] != data_[i]) {
return false;
}
}
return true;
}
MathArray& operator++() {
#pragma omp simd
for (size_t i = 0; i < N; i++) {
++data_[i];
}
return *this;
}
MathArray operator++(int) {
MathArray tmp(*this);
operator++();
return tmp;
}
MathArray& operator--() {
#pragma omp simd
for (size_t i = 0; i < N; i++) {
--data_[i];
}
return *this;
}
MathArray operator--(int) {
MathArray tmp(*this);
operator--();
return tmp;
}
MathArray& operator+=(const MathArray& rhs) {
assert(N == rhs.size());
#pragma omp simd
for (size_t i = 0; i < N; i++) {
data_[i] += rhs[i];
}
return *this;
}
MathArray operator+(const MathArray& rhs) {
assert(size() == rhs.size());
MathArray tmp;
#pragma omp simd
for (size_t i = 0; i < N; i++) {
tmp[i] = data_[i] + rhs[i];
}
return tmp;
}
const MathArray operator+(const MathArray& rhs) const {
assert(size() == rhs.size());
MathArray tmp;
#pragma omp simd
for (size_t i = 0; i < N; i++) {
tmp[i] = data_[i] + rhs[i];
}
return tmp;
}
MathArray& operator+=(const T& rhs) {
#pragma omp simd
for (size_t i = 0; i < N; i++) {
data_[i] += rhs;
}
return *this;
}
MathArray operator+(const T& rhs) {
MathArray tmp;
#pragma omp simd
for (size_t i = 0; i < N; i++) {
tmp[i] = data_[i] + rhs;
}
return tmp;
}
MathArray& operator-=(const MathArray& rhs) {
assert(size() == rhs.size());
#pragma omp simd
for (size_t i = 0; i < N; i++) {
data_[i] -= rhs[i];
}
return *this;
}
MathArray operator-(const MathArray& rhs) {
assert(size() == rhs.size());
MathArray tmp;
#pragma omp simd
for (size_t i = 0; i < N; i++) {
tmp[i] = data_[i] - rhs[i];
}
return tmp;
}
const MathArray operator-(const MathArray& rhs) const {
assert(size() == rhs.size());
MathArray tmp;
#pragma omp simd
for (size_t i = 0; i < N; i++) {
tmp[i] = data_[i] - rhs[i];
}
return tmp;
}
MathArray& operator-=(const T& rhs) {
#pragma omp simd
for (size_t i = 0; i < N; i++) {
data_[i] -= rhs;
}
return *this;
}
MathArray operator-(const T& rhs) {
MathArray tmp;
#pragma omp simd
for (size_t i = 0; i < N; i++) {
tmp[i] = data_[i] - rhs;
}
return tmp;
}
T& operator*=(const MathArray& rhs) = delete;
T operator*(const MathArray& rhs) {
assert(size() == rhs.size());
T result = 0;
#pragma omp simd
for (size_t i = 0; i < N; i++) {
result += data_[i] * rhs[i];
}
return result;
}
const T operator*(const MathArray& rhs) const {
assert(size() == rhs.size());
T result = 0;
#pragma omp simd
for (size_t i = 0; i < N; i++) {
result += data_[i] * rhs[i];
}
return result;
}
MathArray& operator*=(const T& k) {
#pragma omp simd
for (size_t i = 0; i < N; i++) {
data_[i] *= k;
}
return *this;
}
MathArray operator*(const T& k) {
MathArray tmp;
#pragma omp simd
for (size_t i = 0; i < N; i++) {
tmp[i] = data_[i] * k;
}
return tmp;
}
const MathArray operator*(const T& k) const {
MathArray tmp;
#pragma omp simd
for (size_t i = 0; i < N; i++) {
tmp[i] = data_[i] * k;
}
return tmp;
}
MathArray& operator/=(const T& k) {
#pragma omp simd
for (size_t i = 0; i < N; i++) {
data_[i] /= k;
}
return *this;
}
MathArray operator/(const T& k) {
MathArray tmp;
#pragma omp simd
for (size_t i = 0; i < N; i++) {
tmp[i] = data_[i] / k;
}
return tmp;
}
/// Fill the MathArray with a constant value.
/// \param k the constant value
/// \return the array
MathArray& fill(const T& k) { // NOLINT
std::fill(std::begin(data_), std::end(data_), k);
return *this;
}
/// Return the sum of all the array's elements.
/// \return sum of the array's content.
T Sum() const { return std::accumulate(begin(), end(), 0); }
/// Compute the norm of the array's content.
/// \return array's norm.
T Norm() const {
T result = 0;
#pragma omp simd
for (size_t i = 0; i < N; i++) {
result += data_[i] * data_[i];
}
result = std::sqrt(result);
return result == 0 ? 1.0 : result;
}
/// Normalize the array. It will be done in-place.
/// \return the normalized array.
MathArray& Normalize() {
T norm = Norm();
#pragma omp simd
for (size_t i = 0; i < N; i++) {
data_[i] /= norm;
}
return *this;
}
/// Compute the entry wise product given another array
/// of the same size.
/// \param rhs the other array
/// \return a new array with the result
MathArray EntryWiseProduct(const MathArray& rhs) {
assert(rhs.size() == N);
MathArray tmp;
#pragma omp simd
for (size_t i = 0; i < N; ++i) {
tmp[i] = data_[i] * rhs[i];
}
return tmp;
}
private:
T data_[N];
BDM_CLASS_DEF_NV(MathArray, 1); // NOLINT
};
template <class T, std::size_t N>
std::ostream& operator<<(std::ostream& o, const MathArray<T, N>& arr) {
for (size_t i = 0; i < N; i++) {
o << arr[i];
if (i != N - 1) {
o << ", ";
}
}
return o;
}
/// Alias for a size 3 MathArray
using Double3 = MathArray<double, 3>;
/// Alias for a size 4 MathArray
using Double4 = MathArray<double, 4>;
} // namespace bdm
#endif // CORE_CONTAINER_MATH_ARRAY_H_
|
elkan_par8.c
|
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include <stdbool.h>
#include <string.h>
#include <omp.h>
#include "csvparser.h"
void vector_init(double *a, int length) {
for (int i = 0; i < length; i++) {
a[i] = 0;
}
}
void vector_copy(double *dst, double *src, int length) {
for (int i = 0; i < length; i++) {
dst[i] = src[i];
}
}
void vector_add(double *dst, double *a, double *b, int length) {
for (int i = 0; i < length; i++) {
dst[i] = a[i] + b[i];
}
}
void vector_elementwise_avg(double *dst, double *a, int denominator, int length) {
for (int i = 0; i < length; i++) {
dst[i] = a[i] / denominator;
}
}
double vector_L2_norm(double *a, int length) {
double vec_norm = 0;
for (int i = 0; i < length; i++) {
vec_norm += a[i] * a[i];
}
return sqrt(vec_norm);
}
void vector_sub(double *dst, double *a, double *b, int length) {
for (int i = 0; i < length; i++) {
dst[i] = a[i] - b[i];
}
}
static inline double max(double a, double b) {
return a > b ? a : b;
}
// Program should take K, a data set (.csv), a delimiter,
// a binary flag data_contains_header, and a binary flag to drop labels
int main(int argc, char *argv[]) {
// Seed for consistent cluster center selection
// In a working implementation, seeding would be variable (e.g. time(NULL))
srand(111);
CsvParser *reader;
CsvRow *row;
int i, j;
if(argc < 6){
printf("Incorrect number of args. Should be 5, received %d\n", argc - 1);
exit(1);
}
int K = atoi(argv[1]);
char *data_fp = argv[2];
char *delimiter = argv[3];
int has_header_row = atoi(argv[4]);
int drop_labels = atoi(argv[5]);
// Take in data set
reader = CsvParser_new(data_fp, delimiter, has_header_row);
// Get number of columns
row = CsvParser_getRow(reader);
int num_cols = CsvParser_getNumFields(row);
CsvParser_destroy_row(row);
if (drop_labels){
num_cols--;
}
// Get number of rows like lazy people
int num_rows = 1;
while ((row = CsvParser_getRow(reader))){
num_rows++;
CsvParser_destroy_row(row);
}
// Torch the CsvParser and start again so we can read data in.
CsvParser_destroy(reader);
reader = CsvParser_new(data_fp, delimiter, has_header_row);
double **data_matrix = malloc(num_rows * sizeof(double *));
for (i = 0; i < num_rows; i++) {
data_matrix[i] = malloc(num_cols * sizeof(double));
}
int row_index = 0;
while ((row = CsvParser_getRow(reader))){
const char **row_fields = CsvParser_getFields(row);
for (int col_index = 0; col_index < num_cols; col_index++) {
data_matrix[row_index][col_index] = atof(row_fields[col_index]);
}
CsvParser_destroy_row(row);
row_index++;
}
CsvParser_destroy(reader);
// Initialize some cluster centers from random rows in our data
// Given the fact that we will usually have way more rows than centers, we can
// probably just roll a number and reroll if we already rolled it. Collisions
// should be relatively infrequent
double prev_centers[K][num_cols];
double centers[K][num_cols];
bool collided;
if (argc == 7) {
int center_indices[3] = {12, 67, 106};
for (i = 0; i < K; i ++) {
vector_copy(centers[i], data_matrix[center_indices[i]], num_cols);
}
} else {
for (i = 0; i < K; i++) {
int center_indices[K];
collided = true;
while (collided) {
center_indices[i] = rand() % num_rows;
collided = false;
for (j = 0; j < i; j++) {
if (center_indices[j] == center_indices[i]) {
collided = true;
break;
}
}
vector_copy(centers[i], data_matrix[center_indices[i]], num_cols);
}
}
}
printf("Initial cluster centers:\n");
for (i = 0; i < K; i++) {
for (j = 0; j < num_cols; j++) {
printf("%f ", centers[i][j]);
}
printf("\n");
}
printf("\n");
int num_iterations = 0;
int *clusterings = calloc(num_rows, sizeof(int));
double *l_bounds = calloc(num_rows * K, sizeof(double));
double *u_bounds = calloc(num_rows, sizeof(double));
double *ctr_ctr_dists = malloc(K * K * sizeof(double));
double drifts[K];
bool changes;
bool ubound_not_tight = false;
// These need better names
double z;
double s[K];
int this_ctr, this_pt;
double tmp_diff[num_cols];
double min_diff;
int elements_in_cluster;
double cluster_means[num_cols];
double tstart = omp_get_wtime();
omp_set_num_threads(8);
#pragma omp parallel for private(this_pt) shared(num_rows, u_bounds)
for (this_pt = 0; this_pt < num_rows; this_pt++) {
u_bounds[this_pt] = INFINITY;
}
while(1) {
changes = false;
// Calculate center-center distances
// TODO: reduce number of distance calculations
#pragma omp parallel for private (i, j, tmp_diff, min_diff) \
shared(ctr_ctr_dists, centers, num_cols)
for (i = 0; i < K; i++) {
min_diff = INFINITY;
for (j = 0; j < K; j++) {
if (i == j) {
ctr_ctr_dists[i * K + j] = 0;
continue;
}
vector_sub(tmp_diff, centers[i], centers[j], num_cols);
ctr_ctr_dists[i * K + j] = vector_L2_norm(tmp_diff, num_cols);
if (ctr_ctr_dists[i * K + j] < min_diff) {
min_diff = ctr_ctr_dists[i * K + j];
}
}
s[i] = min_diff / 2;
}
// Assign points to cluster centers
#pragma omp parallel for private (this_pt, this_ctr, z, tmp_diff, ubound_not_tight) \
shared(num_rows, num_cols, l_bounds, u_bounds, s, clusterings, ctr_ctr_dists, centers, data_matrix, changes) schedule(dynamic)
for (this_pt = 0; this_pt < num_rows; this_pt++) {
if (u_bounds[this_pt] > s[clusterings[this_pt]]) {
ubound_not_tight = true;
for(this_ctr = 0; this_ctr < K; this_ctr++) {
z = max(l_bounds[this_pt * K + this_ctr],
ctr_ctr_dists[clusterings[this_pt] * K + this_ctr] / 2);
if (this_ctr == clusterings[this_pt] || u_bounds[this_pt] <= z) {
continue;
}
if (ubound_not_tight) {
vector_sub(tmp_diff, data_matrix[this_pt], centers[clusterings[this_pt]], num_cols);
u_bounds[this_pt] = vector_L2_norm(tmp_diff, num_cols);
ubound_not_tight = false;
if (u_bounds[this_pt] <= z) {
continue;
}
}
vector_sub(tmp_diff, data_matrix[this_pt], centers[this_ctr], num_cols);
l_bounds[this_pt * K + this_ctr] = vector_L2_norm(tmp_diff, num_cols);
if(l_bounds[this_pt * K + this_ctr] < u_bounds[this_pt]) {
// NOTE: There is an acceptable data race on changes. Threads only ever
// set it to true; lost updates are inconsequential. No need to slow
// things down for safety.
changes = true;
clusterings[this_pt] = this_ctr;
u_bounds[this_pt] = l_bounds[this_pt * K + this_ctr];
}
}
}
}
// If no clusterings have changed, we have reached convergence
if (!changes) {
break;
}
num_iterations++;
// Capture current centers for later re-use
memcpy(prev_centers, centers, num_cols * K * sizeof(double));
// Calculate cluster mean for each cluster
#pragma omp parallel for \
private(this_ctr, this_pt, elements_in_cluster, cluster_means) \
shared(num_rows, clusterings, data_matrix, K)
for (this_ctr = 0; this_ctr < K; this_ctr++) {
elements_in_cluster = 0;
vector_init(cluster_means, num_cols);
for (this_pt = 0; this_pt < num_rows; this_pt++) {
if (clusterings[this_pt] == this_ctr) {
vector_add(cluster_means, cluster_means, data_matrix[this_pt], num_cols);
elements_in_cluster++;
}
}
vector_elementwise_avg(cluster_means, cluster_means, elements_in_cluster, num_cols);
vector_copy(centers[this_ctr], cluster_means, num_cols);
}
// Compute centroid drift since last iteration
#pragma omp parallel for private(this_ctr, tmp_diff) shared(centers, prev_centers, num_cols, drifts)
for (this_ctr = 0; this_ctr < K; this_ctr++) {
vector_sub(tmp_diff, centers[this_ctr], prev_centers[this_ctr], num_cols);
drifts[this_ctr] = vector_L2_norm(tmp_diff, num_cols);
}
// Adjust bounds to account for centroid drift
#pragma omp parallel for private(this_pt, this_ctr, tmp_diff) \
shared(centers, prev_centers, clusterings, num_cols, u_bounds, l_bounds, drifts, K)
for (this_pt = 0; this_pt < num_rows; this_pt++) {
vector_sub(tmp_diff, centers[clusterings[this_pt]], prev_centers[clusterings[this_pt]], num_cols);
u_bounds[this_pt] += vector_L2_norm(tmp_diff, num_cols);
for (this_ctr = 0; this_ctr < K; this_ctr++) {
l_bounds[this_pt * K + this_ctr] -= drifts[this_ctr];
}
}
}
double tend = omp_get_wtime();
printf("Center-center distances:\n");
for (i = 0; i < K; i++) {
for (j = 0; j < K; j++) {
printf("%f ", ctr_ctr_dists[j + i * K]);
}
printf("\n");
}
printf("\nFinal cluster centers:\n");
for (i = 0; i < K; i++) {
for (j = 0; j < num_cols; j++) {
printf("%f ", centers[i][j]);
}
printf("\n");
}
printf("\nNum iterations: %d\n", num_iterations);
printf("Time taken for %d clusters: %f seconds\n", K, tend - tstart);
for (i = 0; i < num_rows; i++) {
free(data_matrix[i]);
}
free(data_matrix);
free(clusterings);
exit(0);
}
|
bitlocker_fmt_plug.c
|
/*
* JtR format to crack BitLocker hashes.
*
* This software is Copyright (c) 2017, Dhiru Kholia <kholia at kth.se> and it
* is hereby released to the general public under the following terms:
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted.
*
* Big thanks to Joachim Metz and Elena Ago for making this format possible.
*
* http://jessekornblum.com/publications/di09.pdf (Implementing BitLocker Drive
* Encryption for Forensic Analysis) by Jesse D. Kornblum is a useful reference.
*
* Tested with Windows 8.1 and 10 BitLocker volumes. AES-CBC and XTS-AES modes
* are supported. BitLocker To Go is supported.
*/
#if FMT_EXTERNS_H
extern struct fmt_main fmt_bitlocker;
#elif FMT_REGISTERS_H
john_register_one(&fmt_bitlocker);
#else
#include <string.h>
#include <assert.h>
#include <errno.h>
#ifdef _OPENMP
#include <omp.h>
#ifndef OMP_SCALE
#define OMP_SCALE 1
#endif
#endif
#include "arch.h"
#include "misc.h"
#include "common.h"
#include "formats.h"
#include "params.h"
#include "unicode.h"
#include "options.h"
#include "johnswap.h"
#include "aes.h"
#include "aes_ccm.h"
#include "sha.h"
#include "sha.h"
#include "jumbo.h"
#include "memdbg.h"
#include "bitlocker_common.h"
#define FORMAT_LABEL "BitLocker"
#if ARCH_BITS >= 64
#define ALGORITHM_NAME "SHA-256 AES 64/" ARCH_BITS_STR
#else
#define ALGORITHM_NAME "SHA-256 AES 32/" ARCH_BITS_STR
#endif
#define BENCHMARK_COMMENT ""
#define BENCHMARK_LENGTH -1
#define BINARY_SIZE 0
#define PLAINTEXT_LENGTH 125
#define SALT_SIZE sizeof(*cur_salt)
#define BINARY_ALIGN 1
#define SALT_ALIGN sizeof(int)
#define MIN_KEYS_PER_CRYPT 1
#define MAX_KEYS_PER_CRYPT 1
#if defined (_OPENMP)
static int omp_t = 1;
#endif
static UTF16 (*saved_key)[PLAINTEXT_LENGTH + 1];
static int *cracked, cracked_count;
static bitlocker_custom_salt *cur_salt;
static void init(struct fmt_main *self)
{
#if defined (_OPENMP)
omp_t = omp_get_max_threads();
self->params.min_keys_per_crypt *= omp_t;
omp_t *= OMP_SCALE;
self->params.max_keys_per_crypt *= omp_t;
#endif
saved_key = mem_calloc(sizeof(*saved_key), self->params.max_keys_per_crypt);
cracked = mem_calloc(sizeof(*cracked), self->params.max_keys_per_crypt);
cracked_count = self->params.max_keys_per_crypt;
}
static void done(void)
{
MEM_FREE(cracked);
MEM_FREE(saved_key);
}
static void set_salt(void *salt)
{
cur_salt = (bitlocker_custom_salt *)salt;
}
static void bitlocker_set_key(char *key, int index)
{
/* Convert key to UTF-16LE (--encoding aware) */
enc_to_utf16(saved_key[index], PLAINTEXT_LENGTH, (UTF8*)key, strlen(key));
}
static char *get_key(int index)
{
return (char*)utf16_to_enc(saved_key[index]);
}
// borrowed from libbde project
struct libbde_password_key_data
{
// the last calculated SHA256 hash
uint8_t last_sha256_hash[32];
// the initial calculated SHA256 hash
uint8_t initial_sha256_hash[32];
uint8_t salt[16];
uint64_t iteration_count;
};
// derived from libbde's libbde_password_calculate_key
static void bitlocker_kdf(unsigned char *password_hash, unsigned char *out)
{
struct libbde_password_key_data pkd;
SHA256_CTX ctx;
memset(&pkd, 0, sizeof(struct libbde_password_key_data));
memcpy(pkd.initial_sha256_hash, password_hash, 32);
memcpy(pkd.salt, cur_salt->salt, cur_salt->salt_length);
for (pkd.iteration_count = 0; pkd.iteration_count < cur_salt->iterations; pkd.iteration_count++) {
SHA256_Init(&ctx);
SHA256_Update(&ctx, &pkd, sizeof(struct libbde_password_key_data));
SHA256_Final(pkd.last_sha256_hash, &ctx);
}
memcpy(out, pkd.last_sha256_hash, 32); // this is the aes-ccm key
}
#ifdef BITLOCKER_DEBUG
static void print_hex(unsigned char *str, int len)
{
int i;
for (i = 0; i < len; ++i)
printf("%02x", str[i]);
printf("\n");
}
#endif
static int crypt_all(int *pcount, struct db_salt *salt)
{
const int count = *pcount;
int index = 0;
memset(cracked, 0, sizeof(cracked[0])*cracked_count);
#ifdef _OPENMP
#pragma omp parallel for
for (index = 0; index < count; index += MAX_KEYS_PER_CRYPT)
#endif
{
unsigned char *passwordBuf;
int passwordBufSize, i;
unsigned char out[MAX_KEYS_PER_CRYPT][32];
SHA256_CTX ctx;
unsigned char output[256] = { 0 };
uint32_t data_size = 0;
uint32_t version = 0;
unsigned char *vmk_blob = NULL; // contains volume master key
unsigned char v1, v2;
for (i = 0; i < MAX_KEYS_PER_CRYPT; ++i) {
// do double-sha256 of password encoded in "utf-16-le"
passwordBuf = (unsigned char*)saved_key[index+i];
passwordBufSize = strlen16((UTF16*)passwordBuf) * 2;
SHA256_Init(&ctx);
SHA256_Update(&ctx, passwordBuf, passwordBufSize);
SHA256_Final(out[i], &ctx);
SHA256_Init(&ctx);
SHA256_Update(&ctx, out[i], 32);
SHA256_Final(out[i], &ctx);
// run bitlocker kdf
bitlocker_kdf(out[i], out[i]);
libcaes_crypt_ccm(out[i], 256, 0, cur_salt->iv, IVLEN, // 0 -> decrypt mode
cur_salt->data, cur_salt->data_size,
output, cur_salt->data_size);
// do known plaintext attack (kpa), version and
// data_size checks come from libbde, v1 and v2 (vmk_blob)
// checks come from e-ago
version = output[20] | (output[21] << 8);
data_size = output[16] | (output[17] << 8);
vmk_blob = &output[16]; // the actual volume master key is at offset 28
v1 = vmk_blob[8];
v2 = vmk_blob[9];
if (version == 1 && data_size == 0x2c && v1 <= 0x05 && v2 == 0x20)
cracked[index+i] = 1;
else {
cracked[index+i] = 0;
#ifdef BITLOCKER_DEBUG
print_hex(output, cur_salt->data_size);
#endif
}
}
}
return count;
}
static int cmp_all(void *binary, int count)
{
int index;
for (index = 0; index < count; index++)
if (cracked[index])
return 1;
return 0;
}
static int cmp_one(void *binary, int index)
{
return cracked[index];
}
static int cmp_exact(char *source, int index)
{
return 1;
}
struct fmt_main fmt_bitlocker = {
{
FORMAT_LABEL,
FORMAT_NAME,
ALGORITHM_NAME,
BENCHMARK_COMMENT,
BENCHMARK_LENGTH,
0,
PLAINTEXT_LENGTH,
BINARY_SIZE,
BINARY_ALIGN,
SALT_SIZE,
SALT_ALIGN,
MIN_KEYS_PER_CRYPT,
MAX_KEYS_PER_CRYPT,
FMT_CASE | FMT_8_BIT | FMT_OMP | FMT_NOT_EXACT,
{
"iteration count",
},
{ FORMAT_TAG },
bitlocker_tests
}, {
init,
done,
fmt_default_reset,
fmt_default_prepare,
bitlocker_common_valid,
fmt_default_split,
fmt_default_binary,
bitlocker_common_get_salt,
{
bitlocker_common_iteration_count,
},
fmt_default_source,
{
fmt_default_binary_hash
},
fmt_default_salt_hash,
NULL,
set_salt,
bitlocker_set_key,
get_key,
fmt_default_clear_keys,
crypt_all,
{
fmt_default_get_hash
},
cmp_all,
cmp_one,
cmp_exact
}
};
#endif /* plugin stanza */
|
HYPRE_IJMatrix.c
|
/******************************************************************************
* Copyright 1998-2019 Lawrence Livermore National Security, LLC and other
* HYPRE Project Developers. See the top-level COPYRIGHT file for details.
*
* SPDX-License-Identifier: (Apache-2.0 OR MIT)
******************************************************************************/
/******************************************************************************
*
* HYPRE_IJMatrix interface
*
*****************************************************************************/
#include "./_hypre_IJ_mv.h"
#include "../HYPRE.h"
/*--------------------------------------------------------------------------
* HYPRE_IJMatrixCreate
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_IJMatrixCreate( MPI_Comm comm,
HYPRE_BigInt ilower,
HYPRE_BigInt iupper,
HYPRE_BigInt jlower,
HYPRE_BigInt jupper,
HYPRE_IJMatrix *matrix )
{
HYPRE_BigInt *row_partitioning;
HYPRE_BigInt *col_partitioning;
HYPRE_BigInt *info;
HYPRE_Int num_procs;
HYPRE_Int myid;
hypre_IJMatrix *ijmatrix;
HYPRE_BigInt row0, col0, rowN, colN;
ijmatrix = hypre_CTAlloc(hypre_IJMatrix, 1, HYPRE_MEMORY_HOST);
hypre_IJMatrixComm(ijmatrix) = comm;
hypre_IJMatrixObject(ijmatrix) = NULL;
hypre_IJMatrixTranslator(ijmatrix) = NULL;
hypre_IJMatrixAssumedPart(ijmatrix) = NULL;
hypre_IJMatrixObjectType(ijmatrix) = HYPRE_UNITIALIZED;
hypre_IJMatrixAssembleFlag(ijmatrix) = 0;
hypre_IJMatrixPrintLevel(ijmatrix) = 0;
hypre_IJMatrixOMPFlag(ijmatrix) = 0;
hypre_MPI_Comm_size(comm,&num_procs);
hypre_MPI_Comm_rank(comm, &myid);
if (ilower > iupper+1 || ilower < 0)
{
hypre_error_in_arg(2);
hypre_TFree(ijmatrix, HYPRE_MEMORY_HOST);
return hypre_error_flag;
}
if (iupper < -1)
{
hypre_error_in_arg(3);
hypre_TFree(ijmatrix, HYPRE_MEMORY_HOST);
return hypre_error_flag;
}
if (jlower > jupper+1 || jlower < 0)
{
hypre_error_in_arg(4);
hypre_TFree(ijmatrix, HYPRE_MEMORY_HOST);
return hypre_error_flag;
}
if (jupper < -1)
{
hypre_error_in_arg(5);
hypre_TFree(ijmatrix, HYPRE_MEMORY_HOST);
return hypre_error_flag;
}
info = hypre_CTAlloc(HYPRE_BigInt, 2, HYPRE_MEMORY_HOST);
row_partitioning = hypre_CTAlloc(HYPRE_BigInt, 2, HYPRE_MEMORY_HOST);
col_partitioning = hypre_CTAlloc(HYPRE_BigInt, 2, HYPRE_MEMORY_HOST);
row_partitioning[0] = ilower;
row_partitioning[1] = iupper+1;
col_partitioning[0] = jlower;
col_partitioning[1] = jupper+1;
/* now we need the global number of rows and columns as well
as the global first row and column index */
/* proc 0 has the first row and col */
if (myid == 0)
{
info[0] = ilower;
info[1] = jlower;
}
hypre_MPI_Bcast(info, 2, HYPRE_MPI_BIG_INT, 0, comm);
row0 = info[0];
col0 = info[1];
/* proc (num_procs-1) has the last row and col */
if (myid == (num_procs-1))
{
info[0] = iupper;
info[1] = jupper;
}
hypre_MPI_Bcast(info, 2, HYPRE_MPI_BIG_INT, num_procs-1, comm);
rowN = info[0];
colN = info[1];
hypre_IJMatrixGlobalFirstRow(ijmatrix) = row0;
hypre_IJMatrixGlobalFirstCol(ijmatrix) = col0;
hypre_IJMatrixGlobalNumRows(ijmatrix) = rowN - row0 + 1;
hypre_IJMatrixGlobalNumCols(ijmatrix) = colN - col0 + 1;
hypre_TFree(info, HYPRE_MEMORY_HOST);
hypre_IJMatrixRowPartitioning(ijmatrix) = row_partitioning;
hypre_IJMatrixColPartitioning(ijmatrix) = col_partitioning;
*matrix = (HYPRE_IJMatrix) ijmatrix;
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_IJMatrixDestroy( HYPRE_IJMatrix matrix )
{
hypre_IJMatrix *ijmatrix = (hypre_IJMatrix *) matrix;
if (!ijmatrix)
{
hypre_error_in_arg(1);
return hypre_error_flag;
}
if (ijmatrix)
{
if (hypre_IJMatrixRowPartitioning(ijmatrix) ==
hypre_IJMatrixColPartitioning(ijmatrix))
{
hypre_TFree(hypre_IJMatrixRowPartitioning(ijmatrix), HYPRE_MEMORY_HOST);
}
else
{
hypre_TFree(hypre_IJMatrixRowPartitioning(ijmatrix), HYPRE_MEMORY_HOST);
hypre_TFree(hypre_IJMatrixColPartitioning(ijmatrix), HYPRE_MEMORY_HOST);
}
if hypre_IJMatrixAssumedPart(ijmatrix)
{
hypre_AssumedPartitionDestroy((hypre_IJAssumedPart*)hypre_IJMatrixAssumedPart(ijmatrix));
}
if ( hypre_IJMatrixObjectType(ijmatrix) == HYPRE_PARCSR )
{
hypre_IJMatrixDestroyParCSR( ijmatrix );
}
else if ( hypre_IJMatrixObjectType(ijmatrix) != -1 )
{
hypre_error_in_arg(1);
return hypre_error_flag;
}
}
hypre_TFree(ijmatrix, HYPRE_MEMORY_HOST);
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_IJMatrixInitialize( HYPRE_IJMatrix matrix )
{
hypre_IJMatrix *ijmatrix = (hypre_IJMatrix *) matrix;
if (!ijmatrix)
{
hypre_error_in_arg(1);
return hypre_error_flag;
}
if ( hypre_IJMatrixObjectType(ijmatrix) == HYPRE_PARCSR )
{
hypre_IJMatrixInitializeParCSR( ijmatrix ) ;
}
else
{
hypre_error_in_arg(1);
}
return hypre_error_flag;
}
HYPRE_Int
HYPRE_IJMatrixInitialize_v2( HYPRE_IJMatrix matrix, HYPRE_MemoryLocation memory_location )
{
hypre_IJMatrix *ijmatrix = (hypre_IJMatrix *) matrix;
if (!ijmatrix)
{
hypre_error_in_arg(1);
return hypre_error_flag;
}
if ( hypre_IJMatrixObjectType(ijmatrix) == HYPRE_PARCSR )
{
hypre_IJMatrixInitializeParCSR_v2( ijmatrix, memory_location ) ;
}
else
{
hypre_error_in_arg(1);
}
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_IJMatrixSetPrintLevel( HYPRE_IJMatrix matrix,
HYPRE_Int print_level )
{
hypre_IJMatrix *ijmatrix = (hypre_IJMatrix *) matrix;
if (!ijmatrix)
{
hypre_error_in_arg(1);
return hypre_error_flag;
}
hypre_IJMatrixPrintLevel(ijmatrix) = 1;
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
* This is a helper routine to compute a prefix sum of integer values.
*
* The current implementation is okay for modest numbers of threads.
*--------------------------------------------------------------------------*/
HYPRE_Int
hypre_PrefixSumInt(HYPRE_Int nvals,
HYPRE_Int *vals,
HYPRE_Int *sums)
{
HYPRE_Int j, nthreads, bsize;
nthreads = hypre_NumThreads();
bsize = (nvals + nthreads - 1) / nthreads; /* This distributes the remainder */
if (nvals < nthreads || bsize == 1)
{
sums[0] = 0;
for (j=1; j < nvals; j++)
sums[j] += sums[j-1] + vals[j-1];
}
else
{
/* Compute preliminary partial sums (in parallel) within each interval */
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(j) HYPRE_SMP_SCHEDULE
#endif
for (j = 0; j < nvals; j += bsize)
{
HYPRE_Int i, n = hypre_min((j+bsize), nvals);
sums[0] = 0;
for (i = j+1; i < n; i++)
{
sums[i] = sums[i-1] + vals[i-1];
}
}
/* Compute final partial sums (in serial) for the first entry of every interval */
for (j = bsize; j < nvals; j += bsize)
{
sums[j] = sums[j-bsize] + sums[j-1] + vals[j-1];
}
/* Compute final partial sums (in parallel) for the remaining entries */
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(j) HYPRE_SMP_SCHEDULE
#endif
for (j = bsize; j < nvals; j += bsize)
{
HYPRE_Int i, n = hypre_min((j+bsize), nvals);
for (i = j+1; i < n; i++)
{
sums[i] += sums[j];
}
}
}
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_IJMatrixSetValues( HYPRE_IJMatrix matrix,
HYPRE_Int nrows,
HYPRE_Int *ncols,
const HYPRE_BigInt *rows,
const HYPRE_BigInt *cols,
const HYPRE_Complex *values )
{
hypre_IJMatrix *ijmatrix = (hypre_IJMatrix *) matrix;
if (nrows == 0)
{
return hypre_error_flag;
}
if (!ijmatrix)
{
hypre_error_in_arg(1);
return hypre_error_flag;
}
/*
if (!ncols)
{
hypre_error_in_arg(3);
return hypre_error_flag;
}
*/
if (!rows)
{
hypre_error_in_arg(4);
return hypre_error_flag;
}
if (!cols)
{
hypre_error_in_arg(5);
return hypre_error_flag;
}
if (!values)
{
hypre_error_in_arg(6);
return hypre_error_flag;
}
if ( hypre_IJMatrixObjectType(ijmatrix) != HYPRE_PARCSR )
{
hypre_error_in_arg(1);
return hypre_error_flag;
}
HYPRE_IJMatrixSetValues2(matrix, nrows, ncols, rows, NULL, cols, values);
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_IJMatrixSetValues2( HYPRE_IJMatrix matrix,
HYPRE_Int nrows,
HYPRE_Int *ncols,
const HYPRE_BigInt *rows,
const HYPRE_Int *row_indexes,
const HYPRE_BigInt *cols,
const HYPRE_Complex *values )
{
hypre_IJMatrix *ijmatrix = (hypre_IJMatrix *) matrix;
if (nrows == 0)
{
return hypre_error_flag;
}
if (!ijmatrix)
{
hypre_error_in_arg(1);
return hypre_error_flag;
}
if (nrows < 0)
{
hypre_error_in_arg(2);
return hypre_error_flag;
}
/*
if (!ncols)
{
hypre_error_in_arg(3);
return hypre_error_flag;
}
*/
if (!rows)
{
hypre_error_in_arg(4);
return hypre_error_flag;
}
if (!cols)
{
hypre_error_in_arg(6);
return hypre_error_flag;
}
if (!values)
{
hypre_error_in_arg(7);
return hypre_error_flag;
}
if ( hypre_IJMatrixObjectType(ijmatrix) != HYPRE_PARCSR )
{
hypre_error_in_arg(1);
return hypre_error_flag;
}
#if defined(HYPRE_USING_CUDA) || defined(HYPRE_USING_HIP)
HYPRE_ExecutionPolicy exec = hypre_GetExecPolicy1( hypre_IJMatrixMemoryLocation(matrix) );
if (exec == HYPRE_EXEC_DEVICE)
{
hypre_IJMatrixSetAddValuesParCSRDevice(ijmatrix, nrows, ncols, rows, row_indexes, cols, values, "set");
}
else
#endif
{
HYPRE_Int *row_indexes_tmp = (HYPRE_Int *) row_indexes;
HYPRE_Int *ncols_tmp = ncols;
if (!ncols_tmp)
{
HYPRE_Int i;
ncols_tmp = hypre_TAlloc(HYPRE_Int, nrows, HYPRE_MEMORY_HOST);
for (i = 0; i < nrows; i++)
{
ncols_tmp[i] = 1;
}
}
if (!row_indexes)
{
row_indexes_tmp = hypre_CTAlloc(HYPRE_Int, nrows, HYPRE_MEMORY_HOST);
hypre_PrefixSumInt(nrows, ncols_tmp, row_indexes_tmp);
}
if (hypre_IJMatrixOMPFlag(ijmatrix))
{
hypre_IJMatrixSetValuesOMPParCSR(ijmatrix, nrows, ncols_tmp, rows, row_indexes_tmp, cols, values);
}
else
{
hypre_IJMatrixSetValuesParCSR(ijmatrix, nrows, ncols_tmp, rows, row_indexes_tmp, cols, values);
}
if (!ncols)
{
hypre_TFree(ncols_tmp, HYPRE_MEMORY_HOST);
}
if (!row_indexes)
{
hypre_TFree(row_indexes_tmp, HYPRE_MEMORY_HOST);
}
}
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_IJMatrixSetConstantValues( HYPRE_IJMatrix matrix, HYPRE_Complex value)
{
hypre_IJMatrix *ijmatrix = (hypre_IJMatrix *) matrix;
if (!ijmatrix)
{
hypre_error_in_arg(1);
return hypre_error_flag;
}
if ( hypre_IJMatrixObjectType(ijmatrix) == HYPRE_PARCSR )
{
return( hypre_IJMatrixSetConstantValuesParCSR( ijmatrix, value));
}
else
{
hypre_error_in_arg(1);
}
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_IJMatrixAddToValues( HYPRE_IJMatrix matrix,
HYPRE_Int nrows,
HYPRE_Int *ncols,
const HYPRE_BigInt *rows,
const HYPRE_BigInt *cols,
const HYPRE_Complex *values )
{
hypre_IJMatrix *ijmatrix = (hypre_IJMatrix *) matrix;
if (nrows == 0)
{
return hypre_error_flag;
}
if (!ijmatrix)
{
hypre_error_in_arg(1);
return hypre_error_flag;
}
if (nrows < 0)
{
hypre_error_in_arg(2);
return hypre_error_flag;
}
/*
if (!ncols)
{
hypre_error_in_arg(3);
return hypre_error_flag;
}
*/
if (!rows)
{
hypre_error_in_arg(4);
return hypre_error_flag;
}
if (!cols)
{
hypre_error_in_arg(5);
return hypre_error_flag;
}
if (!values)
{
hypre_error_in_arg(6);
return hypre_error_flag;
}
if ( hypre_IJMatrixObjectType(ijmatrix) != HYPRE_PARCSR )
{
hypre_error_in_arg(1);
return hypre_error_flag;
}
HYPRE_IJMatrixAddToValues2(matrix, nrows, ncols, rows, NULL, cols, values);
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_IJMatrixAddToValues2( HYPRE_IJMatrix matrix,
HYPRE_Int nrows,
HYPRE_Int *ncols,
const HYPRE_BigInt *rows,
const HYPRE_Int *row_indexes,
const HYPRE_BigInt *cols,
const HYPRE_Complex *values )
{
hypre_IJMatrix *ijmatrix = (hypre_IJMatrix *) matrix;
if (nrows == 0)
{
return hypre_error_flag;
}
if (!ijmatrix)
{
hypre_error_in_arg(1);
return hypre_error_flag;
}
if (nrows < 0)
{
hypre_error_in_arg(2);
return hypre_error_flag;
}
/*
if (!ncols)
{
hypre_error_in_arg(3);
return hypre_error_flag;
}
*/
if (!rows)
{
hypre_error_in_arg(4);
return hypre_error_flag;
}
if (!cols)
{
hypre_error_in_arg(6);
return hypre_error_flag;
}
if (!values)
{
hypre_error_in_arg(7);
return hypre_error_flag;
}
if ( hypre_IJMatrixObjectType(ijmatrix) != HYPRE_PARCSR )
{
hypre_error_in_arg(1);
return hypre_error_flag;
}
#if defined(HYPRE_USING_CUDA) || defined(HYPRE_USING_HIP)
HYPRE_ExecutionPolicy exec = hypre_GetExecPolicy1( hypre_IJMatrixMemoryLocation(matrix) );
if (exec == HYPRE_EXEC_DEVICE)
{
hypre_IJMatrixSetAddValuesParCSRDevice(ijmatrix, nrows, ncols, rows, row_indexes, cols, values, "add");
}
else
#endif
{
HYPRE_Int *row_indexes_tmp = (HYPRE_Int *) row_indexes;
HYPRE_Int *ncols_tmp = ncols;
if (!ncols_tmp)
{
HYPRE_Int i;
ncols_tmp = hypre_TAlloc(HYPRE_Int, nrows, HYPRE_MEMORY_HOST);
for (i = 0; i < nrows; i++)
{
ncols_tmp[i] = 1;
}
}
if (!row_indexes)
{
row_indexes_tmp = hypre_CTAlloc(HYPRE_Int, nrows, HYPRE_MEMORY_HOST);
hypre_PrefixSumInt(nrows, ncols_tmp, row_indexes_tmp);
}
if (hypre_IJMatrixOMPFlag(ijmatrix))
{
hypre_IJMatrixAddToValuesOMPParCSR(ijmatrix, nrows, ncols_tmp, rows, row_indexes_tmp, cols, values);
}
else
{
hypre_IJMatrixAddToValuesParCSR(ijmatrix, nrows, ncols_tmp, rows, row_indexes_tmp, cols, values);
}
if (!ncols)
{
hypre_TFree(ncols_tmp, HYPRE_MEMORY_HOST);
}
if (!row_indexes)
{
hypre_TFree(row_indexes_tmp, HYPRE_MEMORY_HOST);
}
}
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_IJMatrixAssemble( HYPRE_IJMatrix matrix )
{
hypre_IJMatrix *ijmatrix = (hypre_IJMatrix *) matrix;
if (!ijmatrix)
{
hypre_error_in_arg(1);
return hypre_error_flag;
}
if ( hypre_IJMatrixObjectType(ijmatrix) == HYPRE_PARCSR )
{
#if defined(HYPRE_USING_CUDA) || defined(HYPRE_USING_HIP)
HYPRE_ExecutionPolicy exec = hypre_GetExecPolicy1( hypre_IJMatrixMemoryLocation(matrix) );
if (exec == HYPRE_EXEC_DEVICE)
{
return( hypre_IJMatrixAssembleParCSRDevice( ijmatrix ) );
}
else
#endif
{
return( hypre_IJMatrixAssembleParCSR( ijmatrix ) );
}
}
else
{
hypre_error_in_arg(1);
}
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_IJMatrixGetRowCounts( HYPRE_IJMatrix matrix,
HYPRE_Int nrows,
HYPRE_BigInt *rows,
HYPRE_Int *ncols )
{
hypre_IJMatrix *ijmatrix = (hypre_IJMatrix *) matrix;
if (nrows == 0)
{
return hypre_error_flag;
}
if (!ijmatrix)
{
hypre_error_in_arg(1);
return hypre_error_flag;
}
if (nrows < 0)
{
hypre_error_in_arg(2);
return hypre_error_flag;
}
if (!rows)
{
hypre_error_in_arg(3);
return hypre_error_flag;
}
if (!ncols)
{
hypre_error_in_arg(4);
return hypre_error_flag;
}
if ( hypre_IJMatrixObjectType(ijmatrix) == HYPRE_PARCSR )
{
hypre_IJMatrixGetRowCountsParCSR( ijmatrix, nrows, rows, ncols );
}
else
{
hypre_error_in_arg(1);
}
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_IJMatrixGetValues( HYPRE_IJMatrix matrix,
HYPRE_Int nrows,
HYPRE_Int *ncols,
HYPRE_BigInt *rows,
HYPRE_BigInt *cols,
HYPRE_Complex *values )
{
hypre_IJMatrix *ijmatrix = (hypre_IJMatrix *) matrix;
if (nrows == 0)
{
return hypre_error_flag;
}
if (!ijmatrix)
{
hypre_error_in_arg(1);
return hypre_error_flag;
}
if (!ncols)
{
hypre_error_in_arg(3);
return hypre_error_flag;
}
if (!rows)
{
hypre_error_in_arg(4);
return hypre_error_flag;
}
if (!cols)
{
hypre_error_in_arg(5);
return hypre_error_flag;
}
if (!values)
{
hypre_error_in_arg(6);
return hypre_error_flag;
}
if ( hypre_IJMatrixObjectType(ijmatrix) == HYPRE_PARCSR )
{
hypre_IJMatrixGetValuesParCSR( ijmatrix, nrows, ncols,
rows, cols, values );
}
else
{
hypre_error_in_arg(1);
}
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_IJMatrixSetObjectType( HYPRE_IJMatrix matrix,
HYPRE_Int type )
{
hypre_IJMatrix *ijmatrix = (hypre_IJMatrix *) matrix;
if (!ijmatrix)
{
hypre_error_in_arg(1);
return hypre_error_flag;
}
hypre_IJMatrixObjectType(ijmatrix) = type;
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_IJMatrixGetObjectType( HYPRE_IJMatrix matrix,
HYPRE_Int *type )
{
hypre_IJMatrix *ijmatrix = (hypre_IJMatrix *) matrix;
if (!ijmatrix)
{
hypre_error_in_arg(1);
return hypre_error_flag;
}
*type = hypre_IJMatrixObjectType(ijmatrix);
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_IJMatrixGetLocalRange( HYPRE_IJMatrix matrix,
HYPRE_BigInt *ilower,
HYPRE_BigInt *iupper,
HYPRE_BigInt *jlower,
HYPRE_BigInt *jupper )
{
hypre_IJMatrix *ijmatrix = (hypre_IJMatrix *) matrix;
MPI_Comm comm;
HYPRE_BigInt *row_partitioning;
HYPRE_BigInt *col_partitioning;
HYPRE_Int my_id;
if (!ijmatrix)
{
hypre_error_in_arg(1);
return hypre_error_flag;
}
comm = hypre_IJMatrixComm(ijmatrix);
row_partitioning = hypre_IJMatrixRowPartitioning(ijmatrix);
col_partitioning = hypre_IJMatrixColPartitioning(ijmatrix);
hypre_MPI_Comm_rank(comm, &my_id);
*ilower = row_partitioning[0];
*iupper = row_partitioning[1]-1;
*jlower = col_partitioning[0];
*jupper = col_partitioning[1]-1;
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
*--------------------------------------------------------------------------*/
/**
Returns a pointer to an underlying ijmatrix type used to implement IJMatrix.
Assumes that the implementation has an underlying matrix, so it would not
work with a direct implementation of IJMatrix.
@return integer error code
@param IJMatrix [IN]
The ijmatrix to be pointed to.
*/
HYPRE_Int
HYPRE_IJMatrixGetObject( HYPRE_IJMatrix matrix,
void **object )
{
hypre_IJMatrix *ijmatrix = (hypre_IJMatrix *) matrix;
if (!ijmatrix)
{
hypre_error_in_arg(1);
return hypre_error_flag;
}
*object = hypre_IJMatrixObject( ijmatrix );
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_IJMatrixSetRowSizes( HYPRE_IJMatrix matrix,
const HYPRE_Int *sizes )
{
hypre_IJMatrix *ijmatrix = (hypre_IJMatrix *) matrix;
if (!ijmatrix)
{
hypre_error_in_arg(1);
return hypre_error_flag;
}
if ( hypre_IJMatrixObjectType(ijmatrix) == HYPRE_PARCSR )
{
return( hypre_IJMatrixSetRowSizesParCSR( ijmatrix , sizes ) );
}
else
{
hypre_error_in_arg(1);
}
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_IJMatrixSetDiagOffdSizes( HYPRE_IJMatrix matrix,
const HYPRE_Int *diag_sizes,
const HYPRE_Int *offdiag_sizes )
{
hypre_IJMatrix *ijmatrix = (hypre_IJMatrix *) matrix;
if (!ijmatrix)
{
hypre_error_in_arg(1);
return hypre_error_flag;
}
if ( hypre_IJMatrixObjectType(ijmatrix) == HYPRE_PARCSR )
{
hypre_IJMatrixSetDiagOffdSizesParCSR( ijmatrix, diag_sizes, offdiag_sizes );
}
else
{
hypre_error_in_arg(1);
}
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_IJMatrixSetMaxOffProcElmts( HYPRE_IJMatrix matrix,
HYPRE_Int max_off_proc_elmts)
{
hypre_IJMatrix *ijmatrix = (hypre_IJMatrix *) matrix;
if (!ijmatrix)
{
hypre_error_in_arg(1);
return hypre_error_flag;
}
if ( hypre_IJMatrixObjectType(ijmatrix) == HYPRE_PARCSR )
{
return( hypre_IJMatrixSetMaxOffProcElmtsParCSR(ijmatrix,
max_off_proc_elmts) );
}
else
{
hypre_error_in_arg(1);
}
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_IJMatrixRead( const char *filename,
MPI_Comm comm,
HYPRE_Int type,
HYPRE_IJMatrix *matrix_ptr )
{
HYPRE_IJMatrix matrix;
HYPRE_BigInt ilower, iupper, jlower, jupper;
HYPRE_BigInt I, J;
HYPRE_Int ncols;
HYPRE_Complex value;
HYPRE_Int myid, ret;
char new_filename[255];
FILE *file;
hypre_MPI_Comm_rank(comm, &myid);
hypre_sprintf(new_filename,"%s.%05d", filename, myid);
if ((file = fopen(new_filename, "r")) == NULL)
{
hypre_error_in_arg(1);
return hypre_error_flag;
}
hypre_fscanf(file, "%b %b %b %b", &ilower, &iupper, &jlower, &jupper);
HYPRE_IJMatrixCreate(comm, ilower, iupper, jlower, jupper, &matrix);
HYPRE_IJMatrixSetObjectType(matrix, type);
HYPRE_IJMatrixInitialize_v2(matrix, HYPRE_MEMORY_HOST);
/* It is important to ensure that whitespace follows the index value to help
* catch mistakes in the input file. See comments in IJVectorRead(). */
ncols = 1;
while ( (ret = hypre_fscanf(file, "%b %b%*[ \t]%le", &I, &J, &value)) != EOF )
{
if (ret != 3)
{
hypre_error_w_msg(HYPRE_ERROR_GENERIC, "Error in IJ matrix input file.");
return hypre_error_flag;
}
if (I < ilower || I > iupper)
{
HYPRE_IJMatrixAddToValues(matrix, 1, &ncols, &I, &J, &value);
}
else
{
HYPRE_IJMatrixSetValues(matrix, 1, &ncols, &I, &J, &value);
}
}
HYPRE_IJMatrixAssemble(matrix);
fclose(file);
*matrix_ptr = matrix;
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_IJMatrixPrint( HYPRE_IJMatrix matrix,
const char *filename )
{
MPI_Comm comm;
HYPRE_BigInt *row_partitioning;
HYPRE_BigInt *col_partitioning;
HYPRE_BigInt ilower, iupper, jlower, jupper;
HYPRE_BigInt i, ii;
HYPRE_Int j;
HYPRE_Int ncols;
HYPRE_BigInt *cols;
HYPRE_Complex *values;
HYPRE_Int myid;
char new_filename[255];
FILE *file;
void *object;
if (!matrix)
{
hypre_error_in_arg(1);
return hypre_error_flag;
}
if ( (hypre_IJMatrixObjectType(matrix) != HYPRE_PARCSR) )
{
hypre_error_in_arg(1);
return hypre_error_flag;
}
comm = hypre_IJMatrixComm(matrix);
hypre_MPI_Comm_rank(comm, &myid);
hypre_sprintf(new_filename,"%s.%05d", filename, myid);
if ((file = fopen(new_filename, "w")) == NULL)
{
hypre_error_in_arg(2);
return hypre_error_flag;
}
row_partitioning = hypre_IJMatrixRowPartitioning(matrix);
col_partitioning = hypre_IJMatrixColPartitioning(matrix);
ilower = row_partitioning[0];
iupper = row_partitioning[1] - 1;
jlower = col_partitioning[0];
jupper = col_partitioning[1] - 1;
hypre_fprintf(file, "%b %b %b %b\n", ilower, iupper, jlower, jupper);
HYPRE_IJMatrixGetObject(matrix, &object);
for (i = ilower; i <= iupper; i++)
{
if ( hypre_IJMatrixObjectType(matrix) == HYPRE_PARCSR )
{
ii = i - hypre_IJMatrixGlobalFirstRow(matrix);
HYPRE_ParCSRMatrixGetRow((HYPRE_ParCSRMatrix) object,
ii, &ncols, &cols, &values);
for (j = 0; j < ncols; j++)
{
cols[j] += hypre_IJMatrixGlobalFirstCol(matrix);
}
}
for (j = 0; j < ncols; j++)
{
hypre_fprintf(file, "%b %b %.14e\n", i, cols[j], values[j]);
}
if ( hypre_IJMatrixObjectType(matrix) == HYPRE_PARCSR )
{
for (j = 0; j < ncols; j++)
{
cols[j] -= hypre_IJMatrixGlobalFirstCol(matrix);
}
HYPRE_ParCSRMatrixRestoreRow((HYPRE_ParCSRMatrix) object,
ii, &ncols, &cols, &values);
}
}
fclose(file);
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_IJMatrixSetOMPFlag( HYPRE_IJMatrix matrix,
HYPRE_Int omp_flag )
{
hypre_IJMatrix *ijmatrix = (hypre_IJMatrix *) matrix;
if (!ijmatrix)
{
hypre_error_in_arg(1);
return hypre_error_flag;
}
hypre_IJMatrixOMPFlag(ijmatrix) = omp_flag;
return hypre_error_flag;
}
|
kdtree_index.h
|
/***********************************************************************
* Software License Agreement (BSD License)
*
* Copyright 2008-2009 Marius Muja ([email protected]). All rights reserved.
* Copyright 2008-2009 David G. Lowe ([email protected]). All rights reserved.
*
* THE BSD LICENSE
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*************************************************************************/
#ifndef RTABMAP_FLANN_KDTREE_INDEX_H_
#define RTABMAP_FLANN_KDTREE_INDEX_H_
#include <algorithm>
#include <map>
#include <cassert>
#include <cstring>
#include <stdarg.h>
#include <cmath>
#include <vector>
#include <fstream>
#include <chrono>
#include <sys/mman.h>
#include "rtflann/general.h"
#include "rtflann/algorithms/nn_index.h"
#include "rtflann/util/dynamic_bitset.h"
#include "rtflann/util/matrix.h"
#include "rtflann/util/result_set.h"
#include "rtflann/util/heap.h"
#include "rtflann/util/allocator.h"
#include "rtflann/util/random.h"
#include "rtflann/util/saving.h"
using std::cout;
using std::endl;
using std::vector;
namespace rtflann
{
struct KDTreeIndexParams : public IndexParams
{
KDTreeIndexParams(int trees = 4)
{
(*this)["algorithm"] = FLANN_INDEX_KDTREE;
(*this)["trees"] = trees;
}
};
/**
* Randomized kd-tree index
*
* Contains the k-d trees and other information for indexing a set of points
* for nearest-neighbor matching.
*/
template <typename Distance>
class KDTreeIndex : public NNIndex<Distance>
{
public:
typedef typename Distance::ElementType ElementType;
typedef typename Distance::ResultType DistanceType;
typedef NNIndex<Distance> BaseClass;
typedef bool needs_kdtree_distance;
private:
/*--------------------- Internal Data Structures --------------------------*/
struct Node
{
/**
* Dimension used for subdivision.
*/
int divfeat;
/**
* The values used for subdivision.
*/
DistanceType divval;
/**
* Point data
*/
ElementType* point;
int point_num;
/**
* The child nodes.
*/
Node* child1, *child2;
int fix;
Node(){
child1 = NULL;
child2 = NULL;
}
~Node() {
if (child1 != NULL) { child1->~Node(); child1 = NULL; }
if (child2 != NULL) { child2->~Node(); child2 = NULL; }
}
private:
template<typename Archive>
void serialize(Archive& ar)
{
typedef KDTreeIndex<Distance> Index;
Index* obj = static_cast<Index*>(ar.getObject());
ar & divfeat;
ar & divval;
bool leaf_node = false;
if (Archive::is_saving::value) {
leaf_node = ((child1==NULL) && (child2==NULL));
}
ar & leaf_node;
if (leaf_node) {
if (Archive::is_loading::value) {
point = obj->points_[divfeat];
}
}
if (!leaf_node) {
if (Archive::is_loading::value) {
child1 = new(obj->pool_) Node();
child2 = new(obj->pool_) Node();
}
ar & *child1;
ar & *child2;
}
}
friend struct serialization::access;
};
typedef Node* NodePtr;
typedef BranchStruct<NodePtr, DistanceType> BranchSt;
typedef BranchSt* Branch;
public:
/**
* KDTree constructor
*
* Params:
* inputData = dataset with the input features
* params = parameters passed to the kdtree algorithm
*/
KDTreeIndex(const IndexParams& params = KDTreeIndexParams(), Distance d = Distance() ) :
BaseClass(params, d), mean_(NULL), var_(NULL)
{
trees_ = get_param(index_params_,"trees",4);
load_cached = 0;
}
/**
* KDTree constructor
*
* Params:
* inputData = dataset with the input features
* params = parameters passed to the kdtree algorithm
*/
KDTreeIndex(const Matrix<ElementType>& dataset, const IndexParams& params = KDTreeIndexParams(),
Distance d = Distance() ) : BaseClass(params,d ), mean_(NULL), var_(NULL)
{
trees_ = get_param(index_params_,"trees",4);
load_cached = 0;
this->cached = 0;
setDataset(dataset);
}
KDTreeIndex(const KDTreeIndex& other) : BaseClass(other),
trees_(other.trees_)
{
tree_roots_.resize(other.tree_roots_.size());
for (size_t i=0;i<tree_roots_.size();++i) {
copyTree(tree_roots_[i], other.tree_roots_[i]);
}
load_cached = 0;
}
KDTreeIndex& operator=(KDTreeIndex other)
{
this->swap(other);
return *this;
}
/**
* Standard destructor
*/
virtual ~KDTreeIndex()
{
freeIndex();
}
BaseClass* clone() const
{
return new KDTreeIndex(*this);
}
using BaseClass::buildIndex;
void addPoints(const Matrix<ElementType>& points, float rebuild_threshold = 2)
{
assert(points.cols==veclen_);
size_t old_size = size_;
//std::cout << "---(addPoints() - kdtree_index.h) size: " << old_size << "----" << std::endl;
extendDataset(points);
if (rebuild_threshold>1 && size_at_build_*rebuild_threshold<size_) {
buildIndex();
}
else {
for (size_t i=old_size;i<size_;++i) {
for (int j = 0; j < trees_; j++) {
addPointToTree(tree_roots_[j], i);
}
}
}
}
flann_algorithm_t getType() const
{
return FLANN_INDEX_KDTREE;
}
template<typename Archive>
void serialize(Archive& ar)
{
ar.setObject(this);
ar & *static_cast<NNIndex<Distance>*>(this);
ar & trees_;
if (Archive::is_loading::value) {
tree_roots_.resize(trees_);
}
for (size_t i=0;i<tree_roots_.size();++i) {
if (Archive::is_loading::value) {
tree_roots_[i] = new(pool_) Node();
}
ar & *tree_roots_[i];
}
if (Archive::is_loading::value) {
index_params_["algorithm"] = getType();
index_params_["trees"] = trees_;
}
}
void saveIndex(FILE* stream)
{
serialization::SaveArchive sa(stream);
sa & *this;
}
void loadIndex(FILE* stream)
{
freeIndex();
serialization::LoadArchive la(stream);
la & *this;
}
/**
* Computes the inde memory usage
* Returns: memory used by the index
*/
int usedMemory() const
{
return int(pool_.usedMemory+pool_.wastedMemory+size_*sizeof(int)); // pool memory and vind array memory
}
/**
* Find set of nearest neighbors to vec. Their indices are stored inside
* the result object.
*
* Params:
* result = the result object in which the indices of the nearest-neighbors are stored
* vec = the vector for which to search the nearest neighbors
* maxCheck = the maximum number of restarts (in a best-bin-first manner)
*/
void findNeighbors(ResultSet<DistanceType>& result, const ElementType* vec, const SearchParams& searchParams) const
{
int maxChecks = searchParams.checks;
float epsError = 1+searchParams.eps;
if (maxChecks==FLANN_CHECKS_UNLIMITED) {
if (removed_) {
getExactNeighbors<true>(result, vec, epsError);
}
else {
getExactNeighbors<false>(result, vec, epsError);
}
}
else {
if (removed_) {
getNeighbors<true>(result, vec, maxChecks, epsError);
}
else {
getNeighbors<false>(result, vec, maxChecks, epsError);
}
}
}
#ifdef FLANN_KDTREE_MEM_OPT
/**
* Find set of nearest neighbors to vec. Their indices are stored inside
* the result object.
*
* Params:
* result = the result object in which the indices of the nearest-neighbors are stored
* vec = the vector for which to search the nearest neighbors
* maxCheck = the maximum number of restarts (in a best-bin-first manner)
*/
void findNeighbors(ResultSet<DistanceType>& result, const ElementType* vec, const SearchParams& searchParams, Heap<BranchSt>* heap) const
{
int maxChecks = searchParams.checks;
float epsError = 1+searchParams.eps;
if (maxChecks==FLANN_CHECKS_UNLIMITED) {
if (removed_) {
getExactNeighbors<true>(result, vec, epsError);
}
else {
getExactNeighbors<false>(result, vec, epsError);
}
}
else {
if (removed_) {
getNeighbors<true>(result, vec, maxChecks, epsError, heap);
}
else {
getNeighbors<false>(result, vec, maxChecks, epsError, heap);
}
}
}
/**
* @brief Perform k-nearest neighbor search
* @param[in] queries The query points for which to find the nearest neighbors
* @param[out] indices The indices of the nearest neighbors found
* @param[out] dists Distances to the nearest neighbors found
* @param[in] knn Number of nearest neighbors to return
* @param[in] params Search parameters
*/
virtual int knnSearch(const Matrix<ElementType>& queries,
Matrix<size_t>& indices,
Matrix<DistanceType>& dists,
size_t knn,
const SearchParams& params) const
{
assert(queries.cols == veclen());
assert(indices.rows >= queries.rows);
assert(dists.rows >= queries.rows);
assert(indices.cols >= knn);
assert(dists.cols >= knn);
bool use_heap;
if (params.use_heap==FLANN_Undefined) {
use_heap = (knn>KNN_HEAP_THRESHOLD)?true:false;
}
else {
use_heap = (params.use_heap==FLANN_True)?true:false;
}
int count = 0;
Heap<BranchSt>* heap = new Heap<BranchSt>((int)size_);
if (use_heap) {
//#pragma omp parallel num_threads(params.cores)
{
KNNResultSet2<DistanceType> resultSet(knn);
//#pragma omp for schedule(static) reduction(+:count)
for (int i = 0; i < (int)queries.rows; i++) {
resultSet.clear();
findNeighbors(resultSet, queries[i], params, heap);
size_t n = std::min(resultSet.size(), knn);
resultSet.copy(indices[i], dists[i], n, params.sorted);
indices_to_ids(indices[i], indices[i], n);
count += n;
}
}
}
else {
std::vector<double> times(queries.rows);
//#pragma omp parallel num_threads(params.cores)
{
KNNSimpleResultSet<DistanceType> resultSet(knn);
//#pragma omp for schedule(static) reduction(+:count)
for (int i = 0; i < (int)queries.rows; i++) {
resultSet.clear();
findNeighbors(resultSet, queries[i], params, heap);
size_t n = std::min(resultSet.size(), knn);
resultSet.copy(indices[i], dists[i], n, params.sorted);
indices_to_ids(indices[i], indices[i], n);
count += n;
}
}
std::sort(times.begin(), times.end());
}
delete heap;
return count;
}
/**
* @brief Perform k-nearest neighbor search
* @param[in] queries The query points for which to find the nearest neighbors
* @param[out] indices The indices of the nearest neighbors found
* @param[out] dists Distances to the nearest neighbors found
* @param[in] knn Number of nearest neighbors to return
* @param[in] params Search parameters
*/
virtual int knnSearch(const Matrix<ElementType>& queries,
std::vector< std::vector<size_t> >& indices,
std::vector<std::vector<DistanceType> >& dists,
size_t knn,
const SearchParams& params) const
{
assert(queries.cols == veclen());
bool use_heap;
if (params.use_heap==FLANN_Undefined) {
use_heap = (knn>KNN_HEAP_THRESHOLD)?true:false;
}
else {
use_heap = (params.use_heap==FLANN_True)?true:false;
}
if (indices.size() < queries.rows ) indices.resize(queries.rows);
if (dists.size() < queries.rows ) dists.resize(queries.rows);
Heap<BranchSt>* heap = new Heap<BranchSt>((int)size_);
int count = 0;
if (use_heap) {
//#pragma omp parallel num_threads(params.cores)
{
KNNResultSet2<DistanceType> resultSet(knn);
//#pragma omp for schedule(static) reduction(+:count)
for (int i = 0; i < (int)queries.rows; i++) {
resultSet.clear();
findNeighbors(resultSet, queries[i], params, heap);
size_t n = std::min(resultSet.size(), knn);
indices[i].resize(n);
dists[i].resize(n);
if (n>0) {
resultSet.copy(&indices[i][0], &dists[i][0], n, params.sorted);
indices_to_ids(&indices[i][0], &indices[i][0], n);
}
count += n;
}
}
}
else {
//#pragma omp parallel num_threads(params.cores)
{
KNNSimpleResultSet<DistanceType> resultSet(knn);
//#pragma omp for schedule(static) reduction(+:count)
for (int i = 0; i < (int)queries.rows; i++) {
resultSet.clear();
findNeighbors(resultSet, queries[i], params, heap);
size_t n = std::min(resultSet.size(), knn);
indices[i].resize(n);
dists[i].resize(n);
if (n>0) {
resultSet.copy(&indices[i][0], &dists[i][0], n, params.sorted);
indices_to_ids(&indices[i][0], &indices[i][0], n);
}
count += n;
}
}
}
delete heap;
return count;
}
/**
* @brief Perform radius search
* @param[in] query The query point
* @param[out] indices The indices of the neighbors found within the given radius
* @param[out] dists The distances to the nearest neighbors found
* @param[in] radius The radius used for search
* @param[in] params Search parameters
* @return Number of neighbors found
*/
virtual int radiusSearch(const Matrix<ElementType>& queries,
Matrix<size_t>& indices,
Matrix<DistanceType>& dists,
float radius,
const SearchParams& params) const
{
assert(queries.cols == veclen());
int count = 0;
size_t num_neighbors = std::min(indices.cols, dists.cols);
int max_neighbors = params.max_neighbors;
if (max_neighbors<0) max_neighbors = num_neighbors;
else max_neighbors = std::min(max_neighbors,(int)num_neighbors);
Heap<BranchSt>* heap = new Heap<BranchSt>((int)size_);
if (max_neighbors==0) {
//#pragma omp parallel num_threads(params.cores)
{
CountRadiusResultSet<DistanceType> resultSet(radius);
//#pragma omp for schedule(static) reduction(+:count)
for (int i = 0; i < (int)queries.rows; i++) {
resultSet.clear();
findNeighbors(resultSet, queries[i], params, heap);
count += resultSet.size();
}
}
}
else {
// explicitly indicated to use unbounded radius result set
// and we know there'll be enough room for resulting indices and dists
if (params.max_neighbors<0 && (num_neighbors>=this->size())) {
//#pragma omp parallel num_threads(params.cores)
{
RadiusResultSet<DistanceType> resultSet(radius);
//#pragma omp for schedule(static) reduction(+:count)
for (int i = 0; i < (int)queries.rows; i++) {
resultSet.clear();
findNeighbors(resultSet, queries[i], params, heap);
size_t n = resultSet.size();
count += n;
if (n>num_neighbors) n = num_neighbors;
resultSet.copy(indices[i], dists[i], n, params.sorted);
// mark the next element in the output buffers as unused
if (n<indices.cols) indices[i][n] = size_t(-1);
if (n<dists.cols) dists[i][n] = std::numeric_limits<DistanceType>::infinity();
indices_to_ids(indices[i], indices[i], n);
}
}
}
else {
// number of neighbors limited to max_neighbors
//#pragma omp parallel num_threads(params.cores)
{
KNNRadiusResultSet<DistanceType> resultSet(radius, max_neighbors);
//#pragma omp for schedule(static) reduction(+:count)
for (int i = 0; i < (int)queries.rows; i++) {
resultSet.clear();
findNeighbors(resultSet, queries[i], params, heap);
size_t n = resultSet.size();
count += n;
if ((int)n>max_neighbors) n = max_neighbors;
resultSet.copy(indices[i], dists[i], n, params.sorted);
// mark the next element in the output buffers as unused
if (n<indices.cols) indices[i][n] = size_t(-1);
if (n<dists.cols) dists[i][n] = std::numeric_limits<DistanceType>::infinity();
indices_to_ids(indices[i], indices[i], n);
}
}
}
}
delete heap;
return count;
}
/**
* @brief Perform radius search
* @param[in] query The query point
* @param[out] indices The indices of the neighbors found within the given radius
* @param[out] dists The distances to the nearest neighbors found
* @param[in] radius The radius used for search
* @param[in] params Search parameters
* @return Number of neighbors found
*/
virtual int radiusSearch(const Matrix<ElementType>& queries,
std::vector< std::vector<size_t> >& indices,
std::vector<std::vector<DistanceType> >& dists,
float radius,
const SearchParams& params) const
{
assert(queries.cols == veclen());
int count = 0;
Heap<BranchSt>* heap = new Heap<BranchSt>((int)size_);
// just count neighbors
if (params.max_neighbors==0) {
//#pragma omp parallel num_threads(params.cores)
{
CountRadiusResultSet<DistanceType> resultSet(radius);
//#pragma omp for schedule(static) reduction(+:count)
for (int i = 0; i < (int)queries.rows; i++) {
resultSet.clear();
findNeighbors(resultSet, queries[i], params, heap);
count += resultSet.size();
}
}
}
else {
if (indices.size() < queries.rows ) indices.resize(queries.rows);
if (dists.size() < queries.rows ) dists.resize(queries.rows);
if (params.max_neighbors<0) {
// search for all neighbors
//#pragma omp parallel num_threads(params.cores)
{
RadiusResultSet<DistanceType> resultSet(radius);
//#pragma omp for schedule(static) reduction(+:count)
for (int i = 0; i < (int)queries.rows; i++) {
resultSet.clear();
findNeighbors(resultSet, queries[i], params, heap);
size_t n = resultSet.size();
count += n;
indices[i].resize(n);
dists[i].resize(n);
if (n > 0) {
resultSet.copy(&indices[i][0], &dists[i][0], n, params.sorted);
indices_to_ids(&indices[i][0], &indices[i][0], n);
}
}
}
}
else {
// number of neighbors limited to max_neighbors
//#pragma omp parallel num_threads(params.cores)
{
KNNRadiusResultSet<DistanceType> resultSet(radius, params.max_neighbors);
//#pragma omp for schedule(static) reduction(+:count)
for (int i = 0; i < (int)queries.rows; i++) {
resultSet.clear();
findNeighbors(resultSet, queries[i], params, heap);
size_t n = resultSet.size();
count += n;
if ((int)n>params.max_neighbors) n = params.max_neighbors;
indices[i].resize(n);
dists[i].resize(n);
if (n > 0) {
resultSet.copy(&indices[i][0], &dists[i][0], n, params.sorted);
indices_to_ids(&indices[i][0], &indices[i][0], n);
}
}
}
}
}
delete heap;
return count;
}
#endif
protected:
/**
* Builds the index
*/
void buildIndexImpl()
{
if (this->cached==0) {
std::cout << "---(buildIndexImpl() - kdtree_index.h)---" << std::endl;
// Create a permutable array of indices to the input vectors.
std::vector<int> ind(size_);
for (size_t i = 0; i < size_; ++i)
{
ind[i] = int(i);
}
mean_ = new DistanceType[veclen_];
var_ = new DistanceType[veclen_];
tree_roots_.resize(trees_);
/* Construct the randomized trees. */
for (int i = 0; i < trees_; i++)
{
/* Randomize the order of vectors to allow for unbiased sampling. */
std::random_shuffle(ind.begin(), ind.end());
tree_roots_[i] = divideTree(&ind[0], int(size_));
}
delete[] mean_;
delete[] var_;
}
}
void freeIndex()
{
//if (load_cached == 0) {
for (size_t i = 0; i < tree_roots_.size(); ++i)
{
// using placement new, so call destructor explicitly
if (tree_roots_[i] != NULL)
tree_roots_[i]->~Node();
}
pool_.free();
//}
}
private:
void copyTree(NodePtr& dst, const NodePtr& src)
{
dst = new(pool_) Node();
dst->divfeat = src->divfeat;
dst->divval = src->divval;
if (src->child1==NULL && src->child2==NULL) {
dst->point = points_[dst->divfeat];
dst->point_num = dst->divfeat;
dst->child1 = NULL;
dst->child2 = NULL;
}
else {
copyTree(dst->child1, src->child1);
copyTree(dst->child2, src->child2);
}
}
/**
* Create a tree node that subdivides the list of vecs from vind[first]
* to vind[last]. The routine is called recursively on each sublist.
* Place a pointer to this new tree node in the location pTree.
*
* Params: pTree = the new node to create
* first = index of the first vector
* last = index of the last vector
*/
NodePtr divideTree(int* ind, int count)
{
NodePtr node = new(pool_) Node(); // allocate memory
/* If too few exemplars remain, then make this a leaf node. */
if (count == 1) {
node->child1 = node->child2 = NULL; /* Mark as leaf node. */
node->divfeat = *ind; /* Store index of this vec. */
node->point = points_[*ind];
node->point_num = *ind;
}
else {
int idx;
int cutfeat;
DistanceType cutval;
meanSplit(ind, count, idx, cutfeat, cutval);
node->divfeat = cutfeat;
node->divval = cutval;
node->child1 = divideTree(ind, idx);
node->child2 = divideTree(ind+idx, count-idx);
}
return node;
}
/**
* Choose which feature to use in order to subdivide this set of vectors.
* Make a random choice among those with the highest variance, and use
* its variance as the threshold value.
*/
void meanSplit(int* ind, int count, int& index, int& cutfeat, DistanceType& cutval)
{
memset(mean_,0,veclen_*sizeof(DistanceType));
memset(var_,0,veclen_*sizeof(DistanceType));
/* Compute mean values. Only the first SAMPLE_MEAN values need to be
sampled to get a good estimate.
*/
int cnt = std::min((int)SAMPLE_MEAN+1, count);
for (int j = 0; j < cnt; ++j) {
ElementType* v = points_[ind[j]];
for (size_t k=0; k<veclen_; ++k) {
mean_[k] += v[k];
}
}
DistanceType div_factor = DistanceType(1)/cnt;
for (size_t k=0; k<veclen_; ++k) {
mean_[k] *= div_factor;
}
/* Compute variances (no need to divide by count). */
for (int j = 0; j < cnt; ++j) {
ElementType* v = points_[ind[j]];
for (size_t k=0; k<veclen_; ++k) {
DistanceType dist = v[k] - mean_[k];
var_[k] += dist * dist;
}
}
/* Select one of the highest variance indices at random. */
cutfeat = selectDivision(var_);
cutval = mean_[cutfeat];
int lim1, lim2;
planeSplit(ind, count, cutfeat, cutval, lim1, lim2);
if (lim1>count/2) index = lim1;
else if (lim2<count/2) index = lim2;
else index = count/2;
/* If either list is empty, it means that all remaining features
* are identical. Split in the middle to maintain a balanced tree.
*/
if ((lim1==count)||(lim2==0)) index = count/2;
}
/**
* Select the top RAND_DIM largest values from v and return the index of
* one of these selected at random.
*/
int selectDivision(DistanceType* v)
{
int num = 0;
size_t topind[RAND_DIM];
/* Create a list of the indices of the top RAND_DIM values. */
for (size_t i = 0; i < veclen_; ++i) {
if ((num < RAND_DIM)||(v[i] > v[topind[num-1]])) {
/* Put this element at end of topind. */
if (num < RAND_DIM) {
topind[num++] = i; /* Add to list. */
}
else {
topind[num-1] = i; /* Replace last element. */
}
/* Bubble end value down to right location by repeated swapping. */
int j = num - 1;
while (j > 0 && v[topind[j]] > v[topind[j-1]]) {
std::swap(topind[j], topind[j-1]);
--j;
}
}
}
/* Select a random integer in range [0,num-1], and return that index. */
int rnd = rand_int(num);
return (int)topind[rnd];
}
/**
* Subdivide the list of points by a plane perpendicular on axe corresponding
* to the 'cutfeat' dimension at 'cutval' position.
*
* On return:
* dataset[ind[0..lim1-1]][cutfeat]<cutval
* dataset[ind[lim1..lim2-1]][cutfeat]==cutval
* dataset[ind[lim2..count]][cutfeat]>cutval
*/
void planeSplit(int* ind, int count, int cutfeat, DistanceType cutval, int& lim1, int& lim2)
{
/* Move vector indices for left subtree to front of list. */
int left = 0;
int right = count-1;
for (;; ) {
while (left<=right && points_[ind[left]][cutfeat]<cutval) ++left;
while (left<=right && points_[ind[right]][cutfeat]>=cutval) --right;
if (left>right) break;
std::swap(ind[left], ind[right]); ++left; --right;
}
lim1 = left;
right = count-1;
for (;; ) {
while (left<=right && points_[ind[left]][cutfeat]<=cutval) ++left;
while (left<=right && points_[ind[right]][cutfeat]>cutval) --right;
if (left>right) break;
std::swap(ind[left], ind[right]); ++left; --right;
}
lim2 = left;
}
/**
* Performs an exact nearest neighbor search. The exact search performs a full
* traversal of the tree.
*/
template<bool with_removed>
void getExactNeighbors(ResultSet<DistanceType>& result, const ElementType* vec, float epsError) const
{
// checkID -= 1; /* Set a different unique ID for each search. */
if (trees_ > 1) {
fprintf(stderr,"It doesn't make any sense to use more than one tree for exact search");
}
if (trees_>0) {
searchLevelExact<with_removed>(result, vec, tree_roots_[0], 0.0, epsError);
}
}
/**
* Performs the approximate nearest-neighbor search. The search is approximate
* because the tree traversal is abandoned after a given number of descends in
* the tree.
*/
template<bool with_removed>
void getNeighbors(ResultSet<DistanceType>& result, const ElementType* vec, int maxCheck, float epsError) const
{
int i;
BranchSt branch;
int checkCount = 0;
Heap<BranchSt>* heap = new Heap<BranchSt>((int)size_);
DynamicBitset checked(size_);
/* Search once through each tree down to root. */
for (i = 0; i < trees_; ++i) {
searchLevel<with_removed>(result, vec, tree_roots_[i], 0, checkCount, maxCheck, epsError, heap, checked);
}
/* Keep searching other branches from heap until finished. */
while ( heap->popMin(branch) && (checkCount < maxCheck || !result.full() )) {
searchLevel<with_removed>(result, vec, branch.node, branch.mindist, checkCount, maxCheck, epsError, heap, checked);
}
delete heap;
}
#ifdef FLANN_KDTREE_MEM_OPT
/**
* Performs the approximate nearest-neighbor search. The search is approximate
* because the tree traversal is abandoned after a given number of descends in
* the tree.
*/
template<bool with_removed>
void getNeighbors(ResultSet<DistanceType>& result, const ElementType* vec, int maxCheck, float epsError, Heap<BranchSt>* heap) const
{
int i;
BranchSt branch;
int checkCount = 0;
DynamicBitset checked(size_);
heap->clear();
/* Search once through each tree down to root. */
for (i = 0; i < trees_; ++i) {
searchLevel<with_removed>(result, vec, tree_roots_[i], 0, checkCount, maxCheck, epsError, heap, checked);
}
/* Keep searching other branches from heap until finished. */
while ( heap->popMin(branch) && (checkCount < maxCheck || !result.full() )) {
searchLevel<with_removed>(result, vec, branch.node, branch.mindist, checkCount, maxCheck, epsError, heap, checked);
}
}
#endif
/**
* Search starting from a given node of the tree. Based on any mismatches at
* higher levels, all exemplars below this level must have a distance of
* at least "mindistsq".
*/
template<bool with_removed>
void searchLevel(ResultSet<DistanceType>& result_set, const ElementType* vec, NodePtr node, DistanceType mindist, int& checkCount, int maxCheck,
float epsError, Heap<BranchSt>* heap, DynamicBitset& checked) const
{
if (result_set.worstDist()<mindist) {
// printf("Ignoring branch, too far\n");
return;
}
/* If this is a leaf node, then do check and return. */
if ((node->child1 == NULL)&&(node->child2 == NULL)) {
int index = node->divfeat;
if (with_removed) {
if (removed_points_.test(index)) return;
}
/* Do not check same node more than once when searching multiple trees. */
if ( checked.test(index) || ((checkCount>=maxCheck)&& result_set.full()) ) return;
checked.set(index);
checkCount++;
DistanceType dist = distance_(node->point, vec, veclen_);
result_set.addPoint(dist,index);
return;
}
/* Which child branch should be taken first? */
ElementType val = vec[node->divfeat];
DistanceType diff = val - node->divval;
NodePtr bestChild = (diff < 0) ? node->child1 : node->child2;
NodePtr otherChild = (diff < 0) ? node->child2 : node->child1;
/* Create a branch record for the branch not taken. Add distance
of this feature boundary (we don't attempt to correct for any
use of this feature in a parent node, which is unlikely to
happen and would have only a small effect). Don't bother
adding more branches to heap after halfway point, as cost of
adding exceeds their value.
*/
DistanceType new_distsq = mindist + distance_.accum_dist(val, node->divval, node->divfeat);
// if (2 * checkCount < maxCheck || !result.full()) {
if ((new_distsq*epsError < result_set.worstDist())|| !result_set.full()) {
heap->insert( BranchSt(otherChild, new_distsq) );
}
/* Call recursively to search next level down. */
searchLevel<with_removed>(result_set, vec, bestChild, mindist, checkCount, maxCheck, epsError, heap, checked);
}
/**
* Performs an exact search in the tree starting from a node.
*/
template<bool with_removed>
void searchLevelExact(ResultSet<DistanceType>& result_set, const ElementType* vec, const NodePtr node, DistanceType mindist, const float epsError) const
{
/* If this is a leaf node, then do check and return. */
if ((node->child1 == NULL)&&(node->child2 == NULL)) {
int index = node->divfeat;
if (with_removed) {
if (removed_points_.test(index)) return; // ignore removed points
}
DistanceType dist = distance_(node->point, vec, veclen_);
result_set.addPoint(dist,index);
return;
}
/* Which child branch should be taken first? */
ElementType val = vec[node->divfeat];
DistanceType diff = val - node->divval;
NodePtr bestChild = (diff < 0) ? node->child1 : node->child2;
NodePtr otherChild = (diff < 0) ? node->child2 : node->child1;
/* Create a branch record for the branch not taken. Add distance
of this feature boundary (we don't attempt to correct for any
use of this feature in a parent node, which is unlikely to
happen and would have only a small effect). Don't bother
adding more branches to heap after halfway point, as cost of
adding exceeds their value.
*/
DistanceType new_distsq = mindist + distance_.accum_dist(val, node->divval, node->divfeat);
/* Call recursively to search next level down. */
searchLevelExact<with_removed>(result_set, vec, bestChild, mindist, epsError);
if (mindist*epsError<=result_set.worstDist()) {
searchLevelExact<with_removed>(result_set, vec, otherChild, new_distsq, epsError);
}
}
void addPointToTree(NodePtr node, int ind)
{
ElementType* point = points_[ind];
// std::cout << "pointer size: " << (points_[1]) - (points_[0]) << std::endl;
// std::cout << "pointer 0: " << (points_[0]) << std::endl;
// std::cout << "pointer 1: " << (points_[1]) << std::endl;
if ((node->child1==NULL) && (node->child2==NULL)) {
ElementType* leaf_point = node->point;
ElementType max_span = 0;
size_t div_feat = 0;
for (size_t i=0;i<veclen_;++i) {
ElementType span = std::abs(point[i]-leaf_point[i]);
if (span > max_span) {
max_span = span;
div_feat = i;
}
}
NodePtr left = new(pool_) Node();
left->child1 = left->child2 = NULL;
NodePtr right = new(pool_) Node();
right->child1 = right->child2 = NULL;
if (point[div_feat]<leaf_point[div_feat]) {
left->divfeat = ind;
left->point = point;
left->point_num = ind;
right->divfeat = node->divfeat;
right->point = node->point;
right->point_num = node->point_num;
}
else {
left->divfeat = node->divfeat;
left->point = node->point;
left->point_num = node->point_num;
right->divfeat = ind;
right->point = point;
right->point_num = ind;
}
node->divfeat = div_feat;
node->divval = (point[div_feat]+leaf_point[div_feat])/2;
node->child1 = left;
node->child2 = right;
}
else {
if (point[node->divfeat]<node->divval) {
addPointToTree(node->child1,ind);
}
else {
addPointToTree(node->child2,ind);
}
}
}
virtual void debug_index() {
std::cout << "------------------------------" << std::endl;
print_params(index_params_);
std::cout << "------------------------------" << std::endl;
std::cout << "number of flann datapoints: " << this->size_ << std::endl;
std::cout << "size of one flann datapoint: " << this->veclen_ << std::endl;
std::cout << "removed_count_: " << this->removed_count_ << std::endl;
std::cout << "data_ptr_: " << this->data_ptr_ << std::endl;
std::cout << "size of ids_: " << ids_.size() << std::endl;
std::cout << "size of points_: " << points_.size() << std::endl;
std::cout << "number of trees: " << trees_ << std::endl;
std::cout << "number of tree roots: " << tree_roots_.size() << std::endl;
}
/////////////////////////////////////////////////////////////
//check_trees() - this function is used to validate that the
//flattened tree matches the original tree
void check_trees(int tree_root_num, char* ptr) {
for(int i=0; i<2; i++) {
//in-order tree traversal
std::list<Node *> tree_nodes;
Node *root;
std::ofstream *outfile = new std::ofstream();
if (i==0) {
outfile->open("ref_tree.dat", std::ios::out | std::ios::binary | std::ios::trunc);
root = tree_roots_[tree_root_num];
} else {
outfile->open("test_tree.dat", std::ios::out | std::ios::binary | std::ios::trunc);
root = (Node*) ptr;
}
while (root != NULL || tree_nodes.size() != 0)
{
// Find the leftmost node
while (root != NULL)
{
tree_nodes.push_front(root); //inorder.push(root)
root = root->child1; //root = root.left
}
root = tree_nodes.front();
tree_nodes.pop_front(); //inorder.pop();
if (root->child1 == NULL && root->child2 == NULL)
{
//this is a leaf
outfile->write(reinterpret_cast<char *>(root->point), 256 * sizeof(float));
}
else
{
//this is a non-leaf
outfile->write(reinterpret_cast<char *>(&root->divfeat), sizeof(int));
outfile->write(reinterpret_cast<char *>(&root->divval), sizeof(float));
}
root = root->child2; //root = root.right;
}
outfile->close();
}
}
#define STARTING_ADDR 0x5000000000
virtual void save_index(std::ofstream *outfile)
{
//The save index file is in the following format:
//---------------------------------------------------------------------------------------
//| num visual words | visual words | num bytes tree 0 | pointer to tree 0 root | tree 0 bytes....
//| (4 bytes) | (many bytes) | (4 byte - int) | (8 byte - pointer) | (many bytes)
//---------------------------------------------------------------------------------------
//
//---------------------------------------------------------------------------------------
//| ....tree 0 bytes cont'd | num bytes tree 1 | pointer to tree 1 root | tree 1 bytes....
//| (many bytes) | (4 byte - int) | (8 byte - int) | (many bytes)
//---------------------------------------------------------------------------------------
//
//There are 4 trees total and the root node addresses are stored in tree_roots_
//Obtain the block of contiguous memory using mmap(). Malloc() does not return memory at a requested
//address, but mmap() does.
char *addr; //pointer to the new memory
unsigned long long int starting_addr = STARTING_ADDR;
unsigned int length = 1300000000; //1.3GB for now
addr = (char *)mmap((void *)starting_addr, length, PROT_READ | PROT_WRITE, MAP_FIXED | MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (addr == MAP_FAILED)
{
std::cout << "Error with mmap() call" << std::endl;
exit(EXIT_FAILURE);
}
else
{
std::cout << "Successful memory mapping to: 0x" << std::hex << (unsigned long long) addr << std::endl;
}
//Copy the visual word data to the new memory. Each visual word is a binary descriptor which consists of
//256 floats, where each float is a binary number (0 or 1). The visual words are copied into the new
//memory first and then the trees are placed after the visual words.
float *f_ptr, *f_write;
f_write = (float*) addr;
for(unsigned int i=0;i<points_.size();i++)
{
f_ptr = (float*) points_[i];
for (unsigned int j=0; j<256; j++)
{
*f_write = f_ptr[j];
f_write++;
}
}
char *tree_addr_base = (char *)(addr + points_.size() * 256 * sizeof(float));
char *tree_addr_cur, *region_start;
tree_addr_cur = tree_addr_base;
//map to store the mapping from the original memory address of a node, to the new memory address when it is loaded in again
std::map<unsigned long long, unsigned long long> memory_addresses;
struct Node *node_ptr;
std::list<Node *> tree_nodes; //used as a stack for in-order traversal of the tree
Node *root;
//This is the main loop that flattens the index trees. The loop does an in-order traversal of
//the trees and copies the nodes to the memory block obtained using mmap().
for (unsigned int tr = 0; tr<tree_roots_.size(); tr++) //there are 4 trees
{
//at the memory region beginning, store the total number of bytes for the tree (4 byte int - does not include
//the 8 byte pointer to the root node), then store the pointer to the root node of the tree (8 byte pointer)
region_start = tree_addr_base;
tree_addr_base += sizeof(int) + sizeof(struct Node *); //make space to store the pointer to the root
tree_addr_cur = tree_addr_base;
memory_addresses.clear();
tree_nodes.clear();
//in-order tree traversal
root = tree_roots_[tr];
int node_counter = 0;
int leaf_counter = 0;
while (root != NULL || tree_nodes.size() != 0)
{
// Find the leftmost node
while (root != NULL)
{
tree_nodes.push_front(root); //inorder.push(root)
root = root->child1; //root = root.left
}
root = tree_nodes.front();
tree_nodes.pop_front(); //inorder.pop();
if (root->child1 == NULL && root->child2 == NULL)
{
//this is a leaf
memory_addresses.insert(std::pair<unsigned long long, unsigned long long>((unsigned long long)root, (unsigned long long)tree_addr_cur));
node_ptr = (struct Node *)tree_addr_cur;
node_ptr->child1 = NULL;
node_ptr->child2 = NULL;
node_ptr->divfeat = root->divfeat;
node_ptr->divval = root->divval;
node_ptr->point_num = root->point_num;
node_ptr->point = (ElementType *)(starting_addr + (256 * sizeof(float) * node_ptr->point_num));
node_ptr->fix = 0;
leaf_counter++;
tree_addr_cur += sizeof(struct Node);
}
else
{
//this is a non-leaf
// memory_addresses.insert(std::pair<unsigned long long,unsigned long long>((unsigned long long)root, (unsigned long long)tree_addr_cur));
memory_addresses[(unsigned long long)root] = (unsigned long long)tree_addr_cur;
node_ptr = (struct Node *)tree_addr_cur;
if (root->child1 != NULL)
{
//If this node has a left child, then that child has already been traversed. Find
//the new address of the node and update the pointer.
node_ptr->child1 = (Node *)memory_addresses[(unsigned long long)root->child1];
memory_addresses.erase((unsigned long long)root->child1);
}
else
{
node_ptr->child1 = NULL;
}
if (root->child2 != NULL)
{
//If this node has a right child, then that child has not been traversed. Set a flag
//and placeholder address for updating in a final fixup pass through all the nodes.
node_ptr->child2 = root->child2; //have not traversed this node yet, so insert a placeholder to child2
node_ptr->fix = 1; //mark this node for fixup later
}
else
{
node_ptr->child2 = NULL;
node_ptr->fix = 0;
}
node_ptr->divfeat = root->divfeat;
node_ptr->divval = root->divval;
node_ptr->point_num = root->point_num;
node_ptr->point = (ElementType *)NULL;
node_counter++;
tree_addr_cur += sizeof(struct Node);
}
root = root->child2; //root = root.right;
}
//Final loop pass to fix up the child2 pointers
for (int i = 0; i < (node_counter + leaf_counter); i++)
{
Node *n_ptr = (Node *)(tree_addr_base + i * sizeof(struct Node));
if (n_ptr->fix == 1)
{
Node *new_ptr = (Node *)memory_addresses[(unsigned long long)n_ptr->child2];
memory_addresses.erase((unsigned long long)n_ptr->child2);
n_ptr->child2 = new_ptr;
n_ptr->fix = 0;
}
}
//only the root node is left in the memory addresses map
if (memory_addresses.size() != 1)
{
std::cout << "memory_addresses error: " << memory_addresses.size() << std::endl;
exit(0);
}
int *size_ptr = (int*) region_start;
*size_ptr = (node_counter + leaf_counter) * sizeof(struct Node); //store the number of bytes for the tree
region_start += sizeof(int);
unsigned long long *root_ptr = (unsigned long long *) region_start;
std::map<unsigned long long, unsigned long long>::iterator it = memory_addresses.begin();
*root_ptr = it->second; //store the new address of the root node
std::cout << "address of start of tree in memory: " << (unsigned long long)tree_addr_base << std::endl;
std::cout << "address of root node: " << it->second << std::endl;
std::cout << "address of end of tree in memory: " << (unsigned long long)tree_addr_cur << std::endl;
if(tr ==0) {
//check_trees(0, (char *)it->second);
}
std::cout << "nodes: " << node_counter << " leaves: " << leaf_counter << std::endl;
tree_addr_base = tree_addr_cur;
}
int total_flann_size = (unsigned long long)(tree_addr_cur - addr); //include visual words and 4 trees
std::cout << "total flann size: " << total_flann_size << std::endl;
//write out all the data to a file
int point_size = points_.size();
outfile->write(reinterpret_cast<char *>(&point_size), sizeof(int));
outfile->write(reinterpret_cast<char *>(addr), total_flann_size);
//write out the local variables of the class: KDTreeIndex
outfile->write(reinterpret_cast<char *>(&trees_), sizeof(int));
outfile->write(reinterpret_cast<char *>(&mean_), sizeof(DistanceType*));
outfile->write(reinterpret_cast<char *>(&var_), sizeof(DistanceType*));
//write out the local variables of the class: NNIndex
//Distance distance_;
outfile->write(reinterpret_cast<char *>(&this->last_id_), sizeof(size_t));
outfile->write(reinterpret_cast<char *>(&this->size_), sizeof(size_t));
outfile->write(reinterpret_cast<char *>(&this->size_at_build_), sizeof(size_t));
outfile->write(reinterpret_cast<char *>(&this->veclen_), sizeof(size_t));
//IndexParams index_params_;
// int indexparams_size = index_params_.size();
// outfile->write(reinterpret_cast<char *>(&indexparams_size), sizeof(int)); //store the parameter string
// for (std::map<std::string, any>::iterator iter = index_params_.begin(); iter != index_params_.end(); ++iter)
// {
// int length = iter->first.length();
// outfile->write(reinterpret_cast<char *>(&length), sizeof(int)); //store the parameter string
// outfile->write(iter->first.data(), iter->first.length()); //store the parameter string
// outfile->write(reinterpret_cast<char *>(&iter->second), sizeof(any)); //store the value
// }
outfile->write(reinterpret_cast<char *>(&this->removed_), sizeof(bool));
//DynamicBitset removed_points_; //should be 0, so do not store
outfile->write(reinterpret_cast<char *>(&this->removed_count_), sizeof(size_t));
std::cout << "ids_ size: " << ids_.size() << std::endl;
for (unsigned int i=0; i<ids_.size(); i++) {
outfile->write(reinterpret_cast<char *>(&ids_[i]), sizeof(size_t));
}
outfile->write(reinterpret_cast<char *>(&this->data_ptr_), sizeof(ElementType*));
//unmap the memory
munmap(addr,length);
}
///////////////////////////////////////////////////////////////////////
//load_index
virtual void load_index(std::ifstream *infile, char* data_ptr)
{
load_cached = 1;
//read in the tree data for 4 trees
this->tree_roots_.resize(trees_);
NodePtr root[4] = {NULL, NULL, NULL, NULL};
char* t_ptr = (char*) data_ptr;
for (int i=0; i<4; i++) //number of trees
{
int tree_size = 0;
infile->read(reinterpret_cast<char *>(&tree_size), sizeof(int)); //read in the tree size in bytes
//std::cout << "loading tree size: " << tree_size << std::endl;
infile->read(reinterpret_cast<char *>(&(root[i])), sizeof(NodePtr)); //read in the root node pointer address
//std::cout << "root address: " << root[i] << std::endl;
tree_roots_[i] = root[i];
t_ptr += sizeof(int) + sizeof(struct Node *);
infile->read(reinterpret_cast<char *>(t_ptr), tree_size); //read in the tree nodes in a contiguous block
t_ptr += tree_size;
}
//write out the local variables of the class: KDTreeIndex
infile->read(reinterpret_cast<char *>(&trees_), sizeof(int));
infile->read(reinterpret_cast<char *>(&mean_), sizeof(DistanceType*));
infile->read(reinterpret_cast<char *>(&var_), sizeof(DistanceType*));
//write out the local variables of the class: NNIndex
//Distance distance_;
infile->read(reinterpret_cast<char *>(&this->last_id_), sizeof(size_t));
infile->read(reinterpret_cast<char *>(&this->size_), sizeof(size_t));
infile->read(reinterpret_cast<char *>(&this->size_at_build_), sizeof(size_t));
infile->read(reinterpret_cast<char *>(&this->veclen_), sizeof(size_t));
//IndexParams index_params_;
// int indexparams_size;
// infile->read(reinterpret_cast<char *>(&indexparams_size), sizeof(int)); //restore the size of the parameters
// for (int i=0; i<indexparams_size; i++)
// {
// char buf[100];
// int length;
// infile->read(reinterpret_cast<char *>(&length), sizeof(int)); //read the length of the parameter string
// infile->read(reinterpret_cast<char *>(buf), length); //read the parameter string
// buf[length] = 0; //NULL terminate the string;
// std::string s(buf);
// // any a;
// infile->read(reinterpret_cast<char *>(buf), sizeof(any)); //read the parameter value
// //TODO - index_params is already set on construction, so do not modify it
// // index_params_.insert(std::pair<std::string,any>(s,a));
// }
infile->read(reinterpret_cast<char *>(&this->removed_), sizeof(bool));
//DynamicBitset removed_points_; //should be 0, so do not store
infile->read(reinterpret_cast<char *>(&this->removed_count_), sizeof(size_t));
for (unsigned int i=0; i<ids_.size(); i++) {
infile->read(reinterpret_cast<char *>(&ids_[i]), sizeof(size_t));
}
infile->read(reinterpret_cast<char *>(&this->data_ptr_), sizeof(ElementType*));
}
virtual void set_cached (int cache) {
this->cached = cache;
}
private:
void swap(KDTreeIndex& other)
{
BaseClass::swap(other);
std::swap(trees_, other.trees_);
std::swap(tree_roots_, other.tree_roots_);
std::swap(pool_, other.pool_);
}
private:
enum
{
/**
* To improve efficiency, only SAMPLE_MEAN random values are used to
* compute the mean and variance at each level when building a tree.
* A value of 100 seems to perform as well as using all values.
*/
SAMPLE_MEAN = 100,
/**
* Top random dimensions to consider
*
* When creating random trees, the dimension on which to subdivide is
* selected at random from among the top RAND_DIM dimensions with the
* highest variance. A value of 5 works well.
*/
RAND_DIM=5
};
/**
* Number of randomized trees that are used
*/
int trees_;
DistanceType* mean_;
DistanceType* var_;
/**
* Array of k-d trees used to find neighbours.
*/
std::vector<NodePtr> tree_roots_;
/**
* Pooled memory allocator.
*
* Using a pooled memory allocator is more efficient
* than allocating memory directly when there is a large
* number small of memory allocations.
*/
PooledAllocator pool_;
int load_cached;
USING_BASECLASS_SYMBOLS
}; // class KDTreeIndex
}
#endif //FLANN_KDTREE_INDEX_H_
|
utilityNestedDisectionMetis.h
|
// ***********************************************************************
//
// Grappolo: A C++ library for graph clustering
// Mahantesh Halappanavar ([email protected])
// Pacific Northwest National Laboratory
//
// ***********************************************************************
//
// Copyright (2014) Battelle Memorial Institute
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
// ************************************************************************
#ifndef _graph_NestDisect_
#define _graph_NestDisect_
/*
int METIS NodeND(idx t *nvtxs, idx t *xadj, idx t *adjncy, idx t *vwgt, idx t *options,
idx t *perm, idx t *iperm)
Description
This function computes fill reducing orderings of sparse matrices using the multilevel nested dissection algorithm.
Parameters
nvtxs: The number of vertices in the graph.
xadj, adjncy: The adjacency structure of the graph as described in Section 5.5.
vwgt (NULL): An array of size nvtxs specifying the weights of the vertices. If the graph is weighted, the nested dissection ordering computes vertex separators that minimize the sum of the weights of the vertices
on the separators. A NULL can be passed to indicate a graph with equal weight vertices (or unweighted).
options (NULL)
This is the array of options as described in Section 5.4. The following options are valid:
METIS_OPTION_CTYPE, METIS_OPTION_RTYPE, METIS_OPTION_NO2HOP,
METIS_OPTION_NSEPS, METIS_OPTION_NITER, METIS_OPTION_UFACTOR,
METIS_OPTION_COMPRESS, METIS_OPTION_CCORDER, METIS_OPTION_SEED,
METIS_OPTION_PFACTOR, METIS_OPTION_NUMBERING, METIS_OPTION_DBGLVL
perm, iperm: These are vectors, each of size nvtxs. Upon successful completion, they store the fill-reducing permutation and inverse-permutation. Let A be the original matrix and A0 be the permuted matrix. The
arrays perm and iperm are defined as follows.
Row (column) i of A0 is the perm[i] row (column) of A, and row (column) i of A is the iperm[i] row (column) of A0. The numbering of this vector starts from either 0 or 1, depending on the value of options[METIS OPTION NUMBERING].
Returns:
METIS OK Indicates that the function returned normally.
METIS ERROR INPUT Indicates an input error.
METIS ERROR MEMORY Indicates that it could not allocate the required memory.
METIS ERROR Indicates some other type of error.
*/
extern "C" {
#include "metis.h"
}
using namespace std;
/*
#ifdef __cplusplus
extern "C" {
#endif
//Nested dissection
int METIS_NodeND(idx t *nvtxs, idx t *xadj, idx t *adjncy, idx t *vwgt, idx t *options,
idx t *perm, idx t *iperm);
#ifdef __cplusplus
}
#endif
*/
//METIS Graph Partitioner:
void MetisNDReorder( graph *G, comm_type *old2NewMap ) {
printf("Within MetisNDReorder(): \n");
//Get the iterators for the graph:
comm_type NV = G->numVertices;
comm_type NE = G->numEdges;
comm_type *vtxPtr = G->edgeListPtrs;
edge *vtxInd = G->edgeList;
printf("|V|= %ld, |E|= %ld \n", NV, NE);
int status=0;
idx_t nvtxs = (idx_t) NV;
idx_t *xadj = (idx_t *) malloc ((NV+1) * sizeof(idx_t));
assert(xadj != 0);
#pragma omp parallel for
for(comm_type i=0; i<=NV; i++) {
xadj[i] = (idx_t) vtxPtr[i];
}
idx_t *adjncy = (idx_t *) malloc (2*NE * sizeof(idx_t));
assert(adjncy != 0);
#pragma omp parallel for
for(comm_type i=0; i<2*NE; i++) {
adjncy[i] = (idx_t) vtxInd[i].tail;
}
idx_t *adjwgt = (idx_t *) malloc (2*NE * sizeof(idx_t));
assert(adjwgt != 0);
#pragma omp parallel for
for(comm_type i=0; i<2*NE; i++) {
adjwgt[i] = (idx_t) vtxInd[i].weight;
}
idx_t *perm = (idx_t *) malloc (NV * sizeof(idx_t)); assert(perm != 0);
idx_t *iperm = (idx_t *) malloc (NV * sizeof(idx_t)); assert(iperm != 0);
real_t ubvec = 1.03;
idx_t options[METIS_NOPTIONS];
METIS_SetDefaultOptions(options);
options[METIS_OPTION_CTYPE] = METIS_CTYPE_SHEM; //Sorted heavy-edge matching
options[METIS_OPTION_IPTYPE] = METIS_IPTYPE_NODE; //Grows a bisection using a greedy strategy.
options[METIS_OPTION_RTYPE] = METIS_RTYPE_SEP1SIDED; //FM-based cut refinement.
options[METIS_OPTION_DBGLVL] = 1; //#different separators at each level of nested dissection.
options[METIS_OPTION_UFACTOR] = 200; //Maximum allowed load imbalance among partitions
options[METIS_OPTION_NO2HOP] = 0; //The 2–hop matching (0=perform; 1=Do not)
options[METIS_OPTION_COMPRESS] = 1; //Combine vertices with identical adjacency lists (0=do not)
options[METIS_OPTION_CCORDER] = 0; //Connected components identified and ordered separately (1=Yes)
options[METIS_OPTION_SEED] = 786; //Specifies the seed for the random number generator.
options[METIS_OPTION_NITER] = 10; //#iterations for the refinement algorithms
options[METIS_OPTION_NSEPS] = 1; //#different separators
options[METIS_OPTION_PFACTOR] = 10; //Min degree of the vertices that will be ordered last
options[METIS_OPTION_NUMBERING]= 0; //C-style numbering, starting from 0
/* int returnVal = METIS_PartGraphKway(&nvtxs, &ncon, xadj, adjncy, NULL, NULL, adjwgt,
&nparts, NULL, NULL, options, &objval, part); */
status = METIS_NodeND(&nvtxs, xadj, adjncy, NULL, options, perm, iperm);
if(status == METIS_OK)
printf("Nested dissection returned correctly. Will store the permutations in vectors perm and iperm.\n");
else {
if(status == METIS_ERROR_MEMORY)
printf("Metis could not allocate memory.\n");
else if(status == METIS_ERROR_INPUT)
printf("Metis had issues with input.\n");
else
printf("Some other Metis error: %ld\n", status);
}
#pragma omp parallel for
for(comm_type i=0; i<=NV; i++) {
old2NewMap[i] = (comm_type) perm[i]; //Do explicit typecasts
}
//Cleaup:
free(xadj); free(adjncy); free(adjwgt);
free(perm); free(iperm);
printf("Returning back from Metis\n");
}
#endif
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.