source
stringlengths
3
92
c
stringlengths
26
2.25M
configurator.c
/* Simple tool to create config.h. * Would be much easier with ccan modules, but deliberately standalone. * * Copyright 2011 Rusty Russell <rusty@rustcorp.com.au>. MIT license. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <stdio.h> #include <stdbool.h> #include <stdlib.h> #include <unistd.h> #include <err.h> #include <sys/types.h> #include <sys/wait.h> #include <sys/stat.h> #include <fcntl.h> #include <string.h> #define DEFAULT_COMPILER "cc" #define DEFAULT_FLAGS "-g3 -ggdb -Wall -Wundef -Wmissing-prototypes -Wmissing-declarations -Wstrict-prototypes -Wold-style-definition" #define OUTPUT_FILE "configurator.out" #define INPUT_FILE "configuratortest.c" static int verbose; enum test_style { OUTSIDE_MAIN = 0x1, DEFINES_FUNC = 0x2, INSIDE_MAIN = 0x4, DEFINES_EVERYTHING = 0x8, MAY_NOT_COMPILE = 0x10, EXECUTE = 0x8000 }; struct test { const char *name; enum test_style style; const char *depends; const char *link; const char *fragment; const char *flags; const char *overrides; /* On success, force this to '1' */ bool done; bool answer; }; static struct test tests[] = { { "HAVE_32BIT_OFF_T", DEFINES_EVERYTHING|EXECUTE, NULL, NULL, "#include <sys/types.h>\n" "int main(void) {\n" " return sizeof(off_t) == 4 ? 0 : 1;\n" "}\n" }, { "HAVE_ALIGNOF", INSIDE_MAIN, NULL, NULL, "return __alignof__(double) > 0 ? 0 : 1;" }, { "HAVE_ASPRINTF", DEFINES_FUNC, NULL, NULL, "#ifndef _GNU_SOURCE\n" "#define _GNU_SOURCE\n" "#endif\n" "#include <stdio.h>\n" "static char *func(int x) {" " char *p;\n" " if (asprintf(&p, \"%u\", x) == -1) p = NULL;" " return p;\n" "}" }, { "HAVE_ATTRIBUTE_COLD", DEFINES_FUNC, NULL, NULL, "static int __attribute__((cold)) func(int x) { return x; }" }, { "HAVE_ATTRIBUTE_CONST", DEFINES_FUNC, NULL, NULL, "static int __attribute__((const)) func(int x) { return x; }" }, { "HAVE_ATTRIBUTE_PURE", DEFINES_FUNC, NULL, NULL, "static int __attribute__((pure)) func(int x) { return x; }" }, { "HAVE_ATTRIBUTE_MAY_ALIAS", OUTSIDE_MAIN, NULL, NULL, "typedef short __attribute__((__may_alias__)) short_a;" }, { "HAVE_ATTRIBUTE_NORETURN", DEFINES_FUNC, NULL, NULL, "#include <stdlib.h>\n" "static void __attribute__((noreturn)) func(int x) { exit(x); }" }, { "HAVE_ATTRIBUTE_PRINTF", DEFINES_FUNC, NULL, NULL, "static void __attribute__((format(__printf__, 1, 2))) func(const char *fmt, ...) { (void)fmt; }" }, { "HAVE_ATTRIBUTE_UNUSED", OUTSIDE_MAIN, NULL, NULL, "static int __attribute__((unused)) func(int x) { return x; }" }, { "HAVE_ATTRIBUTE_USED", OUTSIDE_MAIN, NULL, NULL, "static int __attribute__((used)) func(int x) { return x; }" }, { "HAVE_BACKTRACE", DEFINES_FUNC, NULL, NULL, "#include <execinfo.h>\n" "static int func(int x) {" " void *bt[10];\n" " return backtrace(bt, 10) < x;\n" "}" }, { "HAVE_BIG_ENDIAN", INSIDE_MAIN|EXECUTE, NULL, NULL, "union { int i; char c[sizeof(int)]; } u;\n" "u.i = 0x01020304;\n" "return u.c[0] == 0x01 && u.c[1] == 0x02 && u.c[2] == 0x03 && u.c[3] == 0x04 ? 0 : 1;" }, { "HAVE_BSWAP_64", DEFINES_FUNC, "HAVE_BYTESWAP_H", NULL, "#include <byteswap.h>\n" "static int func(int x) { return bswap_64(x); }" }, { "HAVE_BUILTIN_CHOOSE_EXPR", INSIDE_MAIN, NULL, NULL, "return __builtin_choose_expr(1, 0, \"garbage\");" }, { "HAVE_BUILTIN_CLZ", INSIDE_MAIN, NULL, NULL, "return __builtin_clz(1) == (sizeof(int)*8 - 1) ? 0 : 1;" }, { "HAVE_BUILTIN_CLZL", INSIDE_MAIN, NULL, NULL, "return __builtin_clzl(1) == (sizeof(long)*8 - 1) ? 0 : 1;" }, { "HAVE_BUILTIN_CLZLL", INSIDE_MAIN, NULL, NULL, "return __builtin_clzll(1) == (sizeof(long long)*8 - 1) ? 0 : 1;" }, { "HAVE_BUILTIN_CTZ", INSIDE_MAIN, NULL, NULL, "return __builtin_ctz(1 << (sizeof(int)*8 - 1)) == (sizeof(int)*8 - 1) ? 0 : 1;" }, { "HAVE_BUILTIN_CTZL", INSIDE_MAIN, NULL, NULL, "return __builtin_ctzl(1UL << (sizeof(long)*8 - 1)) == (sizeof(long)*8 - 1) ? 0 : 1;" }, { "HAVE_BUILTIN_CTZLL", INSIDE_MAIN, NULL, NULL, "return __builtin_ctzll(1ULL << (sizeof(long long)*8 - 1)) == (sizeof(long long)*8 - 1) ? 0 : 1;" }, { "HAVE_BUILTIN_CONSTANT_P", INSIDE_MAIN, NULL, NULL, "return __builtin_constant_p(1) ? 0 : 1;" }, { "HAVE_BUILTIN_EXPECT", INSIDE_MAIN, NULL, NULL, "return __builtin_expect(argc == 1, 1) ? 0 : 1;" }, { "HAVE_BUILTIN_FFS", INSIDE_MAIN, NULL, NULL, "return __builtin_ffs(0) == 0 ? 0 : 1;" }, { "HAVE_BUILTIN_FFSL", INSIDE_MAIN, NULL, NULL, "return __builtin_ffsl(0L) == 0 ? 0 : 1;" }, { "HAVE_BUILTIN_FFSLL", INSIDE_MAIN, NULL, NULL, "return __builtin_ffsll(0LL) == 0 ? 0 : 1;" }, { "HAVE_BUILTIN_POPCOUNTL", INSIDE_MAIN, NULL, NULL, "return __builtin_popcountl(255L) == 8 ? 0 : 1;" }, { "HAVE_BUILTIN_TYPES_COMPATIBLE_P", INSIDE_MAIN, NULL, NULL, "return __builtin_types_compatible_p(char *, int) ? 1 : 0;" }, { "HAVE_ICCARM_INTRINSICS", DEFINES_FUNC, NULL, NULL, "#include <intrinsics.h>\n" "int func(int v) {\n" " return __CLZ(__RBIT(v));\n" "}" }, { "HAVE_BYTESWAP_H", OUTSIDE_MAIN, NULL, NULL, "#include <byteswap.h>\n" }, { "HAVE_CLOCK_GETTIME", DEFINES_FUNC, "HAVE_STRUCT_TIMESPEC", NULL, "#include <time.h>\n" "static struct timespec func(void) {\n" " struct timespec ts;\n" " clock_gettime(CLOCK_REALTIME, &ts);\n" " return ts;\n" "}\n" }, { "HAVE_CLOCK_GETTIME_IN_LIBRT", DEFINES_FUNC, "HAVE_STRUCT_TIMESPEC !HAVE_CLOCK_GETTIME", "-lrt", "#include <time.h>\n" "static struct timespec func(void) {\n" " struct timespec ts;\n" " clock_gettime(CLOCK_REALTIME, &ts);\n" " return ts;\n" "}\n", /* This means HAVE_CLOCK_GETTIME, too */ "HAVE_CLOCK_GETTIME" }, { "HAVE_COMPOUND_LITERALS", INSIDE_MAIN, NULL, NULL, "int *foo = (int[]) { 1, 2, 3, 4 };\n" "return foo[0] ? 0 : 1;" }, { "HAVE_FCHDIR", DEFINES_EVERYTHING|EXECUTE, NULL, NULL, "#include <sys/types.h>\n" "#include <sys/stat.h>\n" "#include <fcntl.h>\n" "#include <unistd.h>\n" "int main(void) {\n" " int fd = open(\"..\", O_RDONLY);\n" " return fchdir(fd) == 0 ? 0 : 1;\n" "}\n" }, { "HAVE_ERR_H", DEFINES_FUNC, NULL, NULL, "#include <err.h>\n" "static void func(int arg) {\n" " if (arg == 0)\n" " err(1, \"err %u\", arg);\n" " if (arg == 1)\n" " errx(1, \"err %u\", arg);\n" " if (arg == 3)\n" " warn(\"warn %u\", arg);\n" " if (arg == 4)\n" " warnx(\"warn %u\", arg);\n" "}\n" }, { "HAVE_FILE_OFFSET_BITS", DEFINES_EVERYTHING|EXECUTE, "HAVE_32BIT_OFF_T", NULL, "#define _FILE_OFFSET_BITS 64\n" "#include <sys/types.h>\n" "int main(void) {\n" " return sizeof(off_t) == 8 ? 0 : 1;\n" "}\n" }, { "HAVE_FOR_LOOP_DECLARATION", INSIDE_MAIN, NULL, NULL, "for (int i = 0; i < argc; i++) { return 0; };\n" "return 1;" }, { "HAVE_FLEXIBLE_ARRAY_MEMBER", OUTSIDE_MAIN, NULL, NULL, "struct foo { unsigned int x; int arr[]; };" }, { "HAVE_GETPAGESIZE", DEFINES_FUNC, NULL, NULL, "#include <unistd.h>\n" "static int func(void) { return getpagesize(); }" }, { "HAVE_ISBLANK", DEFINES_FUNC, NULL, NULL, "#ifndef _GNU_SOURCE\n" "#define _GNU_SOURCE\n" "#endif\n" "#include <ctype.h>\n" "static int func(void) { return isblank(' '); }" }, { "HAVE_LITTLE_ENDIAN", INSIDE_MAIN|EXECUTE, NULL, NULL, "union { int i; char c[sizeof(int)]; } u;\n" "u.i = 0x01020304;\n" "return u.c[0] == 0x04 && u.c[1] == 0x03 && u.c[2] == 0x02 && u.c[3] == 0x01 ? 0 : 1;" }, { "HAVE_MEMMEM", DEFINES_FUNC, NULL, NULL, "#ifndef _GNU_SOURCE\n" "#define _GNU_SOURCE\n" "#endif\n" "#include <string.h>\n" "static void *func(void *h, size_t hl, void *n, size_t nl) {\n" "return memmem(h, hl, n, nl);" "}\n", }, { "HAVE_MEMRCHR", DEFINES_FUNC, NULL, NULL, "#ifndef _GNU_SOURCE\n" "#define _GNU_SOURCE\n" "#endif\n" "#include <string.h>\n" "static void *func(void *s, int c, size_t n) {\n" "return memrchr(s, c, n);" "}\n", }, { "HAVE_MMAP", DEFINES_FUNC, NULL, NULL, "#include <sys/mman.h>\n" "static void *func(int fd) {\n" " return mmap(0, 65536, PROT_READ, MAP_SHARED, fd, 0);\n" "}" }, { "HAVE_PROC_SELF_MAPS", DEFINES_EVERYTHING|EXECUTE, NULL, NULL, "#include <sys/types.h>\n" "#include <sys/stat.h>\n" "#include <fcntl.h>\n" "int main(void) {\n" " return open(\"/proc/self/maps\", O_RDONLY) != -1 ? 0 : 1;\n" "}\n" }, { "HAVE_QSORT_R_PRIVATE_LAST", DEFINES_EVERYTHING|EXECUTE|MAY_NOT_COMPILE, NULL, NULL, "#ifndef _GNU_SOURCE\n" "#define _GNU_SOURCE\n" "#endif\n" "#include <stdlib.h>\n" "static int cmp(const void *lp, const void *rp, void *priv) {\n" " *(unsigned int *)priv = 1;\n" " return *(const int *)lp - *(const int *)rp; }\n" "int main(void) {\n" " int array[] = { 9, 2, 5 };\n" " unsigned int called = 0;\n" " qsort_r(array, 3, sizeof(int), cmp, &called);\n" " return called && array[0] == 2 && array[1] == 5 && array[2] == 9 ? 0 : 1;\n" "}\n" }, { "HAVE_STRUCT_TIMESPEC", DEFINES_FUNC, NULL, NULL, "#include <time.h>\n" "static void func(void) {\n" " struct timespec ts;\n" " ts.tv_sec = ts.tv_nsec = 1;\n" "}\n" }, { "HAVE_SECTION_START_STOP", DEFINES_FUNC, NULL, NULL, "static void *__attribute__((__section__(\"mysec\"))) p = &p;\n" "static int func(void) {\n" " extern void *__start_mysec[], *__stop_mysec[];\n" " return __stop_mysec - __start_mysec;\n" "}\n" }, { "HAVE_STACK_GROWS_UPWARDS", DEFINES_EVERYTHING|EXECUTE, NULL, NULL, "static long nest(const void *base, unsigned int i)\n" "{\n" " if (i == 0)\n" " return (const char *)&i - (const char *)base;\n" " return nest(base, i-1);\n" "}\n" "int main(int argc, char *argv[]) {\n" " (void)argv;\n" " return (nest(&argc, argc) > 0) ? 0 : 1;\n" "}\n" }, { "HAVE_STATEMENT_EXPR", INSIDE_MAIN, NULL, NULL, "return ({ int x = argc; x == argc ? 0 : 1; });" }, { "HAVE_SYS_FILIO_H", OUTSIDE_MAIN, NULL, NULL, /* Solaris needs this for FIONREAD */ "#include <sys/filio.h>\n" }, { "HAVE_SYS_TERMIOS_H", OUTSIDE_MAIN, NULL, NULL, "#include <sys/termios.h>\n" }, { "HAVE_TYPEOF", INSIDE_MAIN, NULL, NULL, "__typeof__(argc) i; i = argc; return i == argc ? 0 : 1;" }, { "HAVE_UNALIGNED_ACCESS", DEFINES_EVERYTHING|EXECUTE, NULL, NULL, "#include <string.h>\n" "int main(int argc, char *argv[]) {\n" " (void)argc;\n" " char pad[sizeof(int *) * 1];\n" " strncpy(pad, argv[0], sizeof(pad));\n" " int *x = (int *)pad, *y = (int *)(pad + 1);\n" " return *x == *y;\n" "}\n" }, { "HAVE_UTIME", DEFINES_FUNC, NULL, NULL, "#include <sys/types.h>\n" "#include <utime.h>\n" "static int func(const char *filename) {\n" " struct utimbuf times = { 0 };\n" " return utime(filename, &times);\n" "}" }, { "HAVE_WARN_UNUSED_RESULT", DEFINES_FUNC, NULL, NULL, "#include <sys/types.h>\n" "#include <utime.h>\n" "static __attribute__((warn_unused_result)) int func(int i) {\n" " return i + 1;\n" "}" }, { "HAVE_OPENMP", INSIDE_MAIN, NULL, NULL, "int i;\n" "#pragma omp parallel for\n" "for(i = 0; i < 0; i++) {};\n" "return 0;\n", "-Werror -fopenmp" }, { "HAVE_VALGRIND_MEMCHECK_H", OUTSIDE_MAIN, NULL, NULL, "#include <valgrind/memcheck.h>\n" }, }; static char *grab_fd(int fd) { int ret; size_t max, size = 0; char *buffer; max = 16384; buffer = malloc(max+1); while ((ret = read(fd, buffer + size, max - size)) > 0) { size += ret; if (size == max) buffer = realloc(buffer, max *= 2); } if (ret < 0) err(1, "reading from command"); buffer[size] = '\0'; return buffer; } static char *run(const char *cmd, int *exitstatus) { pid_t pid; int p[2]; char *ret; int status; if (pipe(p) != 0) err(1, "creating pipe"); pid = fork(); if (pid == -1) err(1, "forking"); if (pid == 0) { if (dup2(p[1], STDOUT_FILENO) != STDOUT_FILENO || dup2(p[1], STDERR_FILENO) != STDERR_FILENO || close(p[0]) != 0 || close(STDIN_FILENO) != 0 || open("/dev/null", O_RDONLY) != STDIN_FILENO) exit(128); status = system(cmd); if (WIFEXITED(status)) exit(WEXITSTATUS(status)); /* Here's a hint... */ exit(128 + WTERMSIG(status)); } close(p[1]); ret = grab_fd(p[0]); /* This shouldn't fail... */ if (waitpid(pid, &status, 0) != pid) err(1, "Failed to wait for child"); close(p[0]); if (WIFEXITED(status)) *exitstatus = WEXITSTATUS(status); else *exitstatus = -WTERMSIG(status); return ret; } static char *connect_args(const char *argv[], const char *extra) { unsigned int i, len = strlen(extra) + 1; char *ret; for (i = 1; argv[i]; i++) len += 1 + strlen(argv[i]); ret = malloc(len); len = 0; for (i = 1; argv[i]; i++) { strcpy(ret + len, argv[i]); len += strlen(argv[i]); if (argv[i+1]) ret[len++] = ' '; } strcpy(ret + len, extra); return ret; } static struct test *find_test(const char *name) { unsigned int i; for (i = 0; i < sizeof(tests)/sizeof(tests[0]); i++) { if (strcmp(tests[i].name, name) == 0) return &tests[i]; } abort(); } #define PRE_BOILERPLATE "/* Test program generated by configurator. */\n" #define MAIN_START_BOILERPLATE \ "int main(int argc, char *argv[]) {\n" \ " (void)argc;\n" \ " (void)argv;\n" #define USE_FUNC_BOILERPLATE "(void)func;\n" #define MAIN_BODY_BOILERPLATE "return 0;\n" #define MAIN_END_BOILERPLATE "}\n" static bool run_test(const char *cmd, struct test *test) { char *output, *newcmd; FILE *outf; int status; if (test->done) return test->answer; if (test->depends) { size_t len; const char *deps = test->depends; char *dep; /* Space-separated dependencies, could be ! for inverse. */ while ((len = strcspn(deps, " "))) { bool positive = true; if (deps[len]) { dep = strdup(deps); dep[len] = '\0'; } else { dep = (char *)deps; } if (dep[0] == '!') { dep++; positive = false; } if (run_test(cmd, find_test(dep)) != positive) { test->answer = false; test->done = true; return test->answer; } if (deps[len]) free(dep); deps += len; deps += strspn(deps, " "); } } outf = fopen(INPUT_FILE, "w"); if (!outf) err(1, "creating %s", INPUT_FILE); fprintf(outf, "%s", PRE_BOILERPLATE); switch (test->style & ~(EXECUTE|MAY_NOT_COMPILE)) { case INSIDE_MAIN: fprintf(outf, "%s", MAIN_START_BOILERPLATE); fprintf(outf, "%s", test->fragment); fprintf(outf, "%s", MAIN_END_BOILERPLATE); break; case OUTSIDE_MAIN: fprintf(outf, "%s", test->fragment); fprintf(outf, "%s", MAIN_START_BOILERPLATE); fprintf(outf, "%s", MAIN_BODY_BOILERPLATE); fprintf(outf, "%s", MAIN_END_BOILERPLATE); break; case DEFINES_FUNC: fprintf(outf, "%s", test->fragment); fprintf(outf, "%s", MAIN_START_BOILERPLATE); fprintf(outf, "%s", USE_FUNC_BOILERPLATE); fprintf(outf, "%s", MAIN_BODY_BOILERPLATE); fprintf(outf, "%s", MAIN_END_BOILERPLATE); break; case DEFINES_EVERYTHING: fprintf(outf, "%s", test->fragment); break; default: abort(); } fclose(outf); if (verbose > 1) if (system("cat " INPUT_FILE) == -1); newcmd = strdup(cmd); if (test->flags) { newcmd = realloc(newcmd, strlen(newcmd) + strlen(" ") + strlen(test->flags) + 1); strcat(newcmd, " "); strcat(newcmd, test->flags); if (verbose > 1) printf("Extra flags line: %s", newcmd); } if (test->link) { newcmd = realloc(newcmd, strlen(newcmd) + strlen(" ") + strlen(test->link) + 1); strcat(newcmd, " "); strcat(newcmd, test->link); if (verbose > 1) printf("Extra link line: %s", newcmd); } output = run(newcmd, &status); free(newcmd); if (status != 0 || strstr(output, "warning")) { if (verbose) printf("Compile %s for %s, status %i: %s\n", status ? "fail" : "warning", test->name, status, output); if ((test->style & EXECUTE) && !(test->style & MAY_NOT_COMPILE)) errx(1, "Test for %s did not compile:\n%s", test->name, output); test->answer = false; free(output); } else { /* Compile succeeded. */ free(output); /* We run INSIDE_MAIN tests for sanity checking. */ if ((test->style & EXECUTE) || (test->style & INSIDE_MAIN)) { output = run("./" OUTPUT_FILE, &status); if (!(test->style & EXECUTE) && status != 0) errx(1, "Test for %s failed with %i:\n%s", test->name, status, output); if (verbose && status) printf("%s exited %i\n", test->name, status); free(output); } test->answer = (status == 0); } test->done = true; if (test->answer && test->overrides) { struct test *override = find_test(test->overrides); override->done = true; override->answer = true; } return test->answer; } int main(int argc, const char *argv[]) { char *cmd; unsigned int i; const char *default_args[] = { "", DEFAULT_COMPILER, DEFAULT_FLAGS, NULL }; if (argc > 1) { if (strcmp(argv[1], "--help") == 0) { printf("Usage: configurator [-v] [<compiler> <flags>...]\n" " <compiler> <flags> will have \"-o <outfile> <infile.c>\" appended\n" "Default: %s %s\n", DEFAULT_COMPILER, DEFAULT_FLAGS); exit(0); } if (strcmp(argv[1], "-v") == 0) { argc--; argv++; verbose = 1; } else if (strcmp(argv[1], "-vv") == 0) { argc--; argv++; verbose = 2; } } if (argc == 1) argv = default_args; cmd = connect_args(argv, " -o " OUTPUT_FILE " " INPUT_FILE); for (i = 0; i < sizeof(tests)/sizeof(tests[0]); i++) run_test(cmd, &tests[i]); free(cmd); unlink(OUTPUT_FILE); unlink(INPUT_FILE); printf("/* Generated by CCAN configurator */\n" "#ifndef CCAN_CONFIG_H\n" "#define CCAN_CONFIG_H\n"); printf("#ifndef _GNU_SOURCE\n"); printf("#define _GNU_SOURCE /* Always use GNU extensions. */\n"); printf("#endif\n"); printf("#define CCAN_COMPILER \"%s\"\n", argv[1]); cmd = connect_args(argv+1, ""); printf("#define CCAN_CFLAGS \"%s\"\n\n", cmd); free(cmd); /* This one implies "#include <ccan/..." works, eg. for tdb2.h */ printf("#define HAVE_CCAN 1\n"); for (i = 0; i < sizeof(tests)/sizeof(tests[0]); i++) printf("#define %s %u\n", tests[i].name, tests[i].answer); printf("#endif /* CCAN_CONFIG_H */\n"); return 0; }
test.c
#include <stdio.h> #include <omp.h> #include "../utilities/check.h" #include "../utilities/utilities.h" #define N (992) #define INIT() INIT_LOOP(N, {C[i] = 1; D[i] = i; E[i] = -i;}) int main(void){ check_offloading(); int fail; double A[N], B[N], C[N], D[N], E[N]; INIT(); #if 0 // // Test: Execute on host // #pragma omp target if (target: C[0] == 0) { #pragma omp parallel for schedule(static,1) for (int i = 0; i < 992; i++) A[i] = C[i] + D[i] + omp_is_initial_device(); } fail = 0; VERIFY(0, N, A[i], i+2); if (fail) { printf ("Test1: Failed\n"); } else { printf ("Test1: Succeeded\n"); } #endif // // Test: Execute on device // #pragma omp target device(1) if (target: C[0] == 1) { #pragma omp parallel for schedule(static,1) for (int i = 0; i < 992; i++) A[i] = C[i] + D[i] + /*omp_is_initial_device()=*/1; // We cannot use omp_is_initial_device() directly because this is tested for // the host too. } // CHECK: Succeeded fail = 0; VERIFY(0, N, A[i], i+2); if (fail) { printf ("Test2: Failed\n"); } else { printf ("Test2: Succeeded\n"); } // // Test: Printf on device // #pragma omp target { printf ("Master %d\n", omp_get_thread_num()); int TT[2] = {0,0}; #pragma omp parallel num_threads(2) { TT[omp_get_thread_num()]++; } printf ("Parallel %d:%f\n", TT[0], D[0]); printf ("Parallel %d:%f\n", TT[1], D[1]); } return 0; }
mm_dist.c
#include <stdio.h> #include <stdlib.h> /* TEMPO SEQUENCIAL: real 3m30.117s user 1m15.715s sys 0m0.127s TEMPO PARALELO MULTICORE: real 1m29.670s user 1m14.390s sys 0m0.269s TEMPO PARALELO DISTRIBUTE: real 3m5.985s user 2m25.092s sys 0m40.084s Invocations Event Name Min Max Avg Total Device "GeForce GT 1030 (0)" Kernel: mm$_omp_fn$0 1 warps_launched 1985472 1985472 1985472 1985472 ==29739== Metric result: Invocations Metric Name Metric Description Min Max Avg Device "GeForce GT 1030 (0)" Kernel: mm$_omp_fn$0 1 warp_execution_efficiency Warp Execution Efficiency 100.00% 100.00% 100.00% TEMPO PARALELO DISTRIBUTE PARALLEL FOR: real 2m58.611s user 0m38.440s sys 0m9.928s Invocations Event Name Min Max Avg Total Device "GeForce GT 1030 (0)" Kernel: mm$_omp_fn$0 1 warps_launched 2520 2520 2520 2520 ==29658== Metric result: Invocations Metric Name Metric Description Min Max Avg Device "GeForce GT 1030 (0)" Kernel: mm$_omp_fn$0 1 warp_execution_efficiency Warp Execution Efficiency 100.00% 100.00% 100.00% TEMPO PARALELO GPU SIMD: real 0m22.656s user 0m5.845s sys 0m1.807s Invocations Event Name Min Max Avg Total Device "GeForce GT 1030 (0)" Kernel: mm$_omp_fn$0 1 warps_launched 2808 2808 2808 2808 ==29576== Metric result: Invocations Metric Name Metric Description Min Max Avg Device "GeForce GT 1030 (0)" Kernel: mm$_omp_fn$0 1 warp_execution_efficiency Warp Execution Efficiency 86.81% 86.81% 86.81% */ void mm(double* a, double* b, double* c, int width) { #pragma omp target map(to:a[0:width*width], b[0:width*width]) map(from:c[0:width*width]) #pragma omp teams distribute for (int i = 0; i < width; i++) { for (int j = 0; j < width; j++) { double sum = 0; for (int k = 0; k < width; k++) { double x = a[i * width + k]; double y = b[k * width + j]; sum += x * y; } c[i * width + j] = sum; } } } int main() { int width = 2000; double *a = (double*) malloc (width * width * sizeof(double)); double *b = (double*) malloc (width * width * sizeof(double)); double *c = (double*) malloc (width * width * sizeof(double)); #pragma omp parallel for for(int i = 0; i < width; i++) { for(int j = 0; j < width; j++) { a[i*width+j] = i; b[i*width+j] = j; c[i*width+j] = 0; } } mm(a,b,c,width); /*for(int i = 0; i < width; i++) { for(int j = 0; j < width; j++) { printf("%f\n",c[i*width+j]); } }*/ }
GB_binop__div_fp64.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 Generated/ folder, do not edit it (auto-generated). #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__div_fp64) // A.*B function (eWiseMult): GB (_AemultB) // A.*B function (eWiseMult): GB (_AemultB_02__div_fp64) // A.*B function (eWiseMult): GB (_AemultB_03__div_fp64) // A.*B function (eWiseMult): GB (_AemultB_bitmap__div_fp64) // A*D function (colscale): GB (_AxD__div_fp64) // D*A function (rowscale): GB (_DxB__div_fp64) // C+=B function (dense accum): GB (_Cdense_accumB__div_fp64) // C+=b function (dense accum): GB (_Cdense_accumb__div_fp64) // C+=A+B function (dense ewise3): GB (_Cdense_ewise3_accum__div_fp64) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__div_fp64) // C=scalar+B GB (_bind1st__div_fp64) // C=scalar+B' GB (_bind1st_tran__div_fp64) // C=A+scalar GB (_bind2nd__div_fp64) // C=A'+scalar GB (_bind2nd_tran__div_fp64) // C type: double // A type: double // B,b type: double // BinaryOp: cij = (aij / bij) #define GB_ATYPE \ double #define GB_BTYPE \ double #define GB_CTYPE \ double // 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) \ double aij = Ax [pA] // bij = Bx [pB] #define GB_GETB(bij,Bx,pB) \ double bij = Bx [pB] // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ double t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA) \ cij = Ax [pA] // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB) \ cij = Bx [pB] #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_DIV || GxB_NO_FP64 || GxB_NO_DIV_FP64) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB (_Cdense_ewise3_accum__div_fp64) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_ewise3_noaccum__div_fp64) ( 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__div_fp64) ( 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__div_fp64) ( 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 double double bwork = (*((double *) 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__div_fp64) ( 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 double *restrict Cx = (double *) C->x ; #include "GB_AxB_colscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_DxB__div_fp64) ( 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 double *restrict Cx = (double *) C->x ; #include "GB_AxB_rowscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C = A+B or C<M> = A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__div_fp64) ( 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__div_fp64) ( 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__div_fp64) ( 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__div_fp64) ( 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__div_fp64) ( 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__div_fp64) ( 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 anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else double *Cx = (double *) Cx_output ; double x = (*((double *) x_input)) ; double *Bx = (double *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Bb, p)) continue ; double bij = Bx [p] ; 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__div_fp64) ( 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 ; double *Cx = (double *) Cx_output ; double *Ax = (double *) Ax_input ; double y = (*((double *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; double aij = Ax [p] ; 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) \ { \ double aij = Ax [pA] ; \ Cx [pC] = (x / aij) ; \ } GrB_Info GB (_bind1st_tran__div_fp64) ( 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 \ double #if GB_DISABLE return (GrB_NO_VALUE) ; #else double x = (*((const double *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ double } //------------------------------------------------------------------------------ // 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) \ { \ double aij = Ax [pA] ; \ Cx [pC] = (aij / y) ; \ } GrB_Info GB (_bind2nd_tran__div_fp64) ( 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 double y = (*((const double *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
ordered.c
/* Copyright (c) 2015-2019, Lawrence Livermore National Security, LLC. Produced at the Lawrence Livermore National Laboratory Written by Simone Atzeni (simone@cs.utah.edu), Joachim Protze (joachim.protze@tu-dresden.de), Jonas Hahnfeld (hahnfeld@itc.rwth-aachen.de), Ganesh Gopalakrishnan, Zvonimir Rakamaric, Dong H. Ahn, Gregory L. Lee, Ignacio Laguna, and Martin Schulz. LLNL-CODE-773957 All rights reserved. This file is part of Archer. For details, see https://pruners.github.io/archer. Please also read https://github.com/PRUNERS/archer/blob/master/LICENSE. 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. */ // RUN: %libarcher-compile-and-run | FileCheck %s #include <omp.h> #include <stdio.h> #define NUM_THREADS 2 int main(int argc, char* argv[]) { int var = 0; int i; #pragma omp parallel for ordered num_threads(NUM_THREADS) shared(var) for (i = 0; i < NUM_THREADS; i++) { #pragma omp ordered { var++; } } fprintf(stderr, "DONE\n"); int error = (var != 2); return error; } // CHECK: DONE
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] = 32; tile_size[3] = 32; 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; }
omp_kmeans.c
#include <stdio.h> #include <stdlib.h> #include <omp.h> #include "kmeans.h" // distancia euclideana __inline static float euclid_dist_2(int numdims, /* num_dimensiones */ float *coord1, /* [num_dimensiones] */ float *coord2) /* [num_dimensiones] */ { int i; float ans=0.0; for (i=0; i<numdims; i++) ans += (coord1[i]-coord2[i]) * (coord1[i]-coord2[i]); return(ans); } // encontrar el cluster mas cercano __inline static int find_nearest_cluster(int numClusters, /* num de clusters */ int numCoords, /* num de coordenadas */ float *object, /* [num de coordenadas] */ float **clusters) /* [num_clusters][num_coordenadas] */ { int index, i; float dist, min_dist; // encontrar el id del cluster mas cercano al objeto index = 0; min_dist = euclid_dist_2(numCoords, object, clusters[0]); for (i=1; i<numClusters; i++) { dist = euclid_dist_2(numCoords, object, clusters[i]); if (dist < min_dist) { min_dist = dist; index = i; } } return(index); } /* retorna un arreglo de centros de los clusters de tamaño [num_clusters][num_coordenadas] */ float** omp_kmeans(int is_perform_atomic, float **objects, /* entrada: [num_objetos][num_coordenadas] */ int numCoords, /* num_coordenadas */ int numObjs, /* num_objetos */ int numClusters, /* num_clusters */ float threshold, int *membership) /* salidas: [num__objetos] */ { int i, j, k, index, loop=0; int *newClusterSize; /* [numClusters]: no. objects assigned in each new cluster */ float delta; /* % of objects change their clusters */ float **clusters; /* out: [numClusters][numCoords] */ float **newClusters; /* [numClusters][numCoords] */ double timing; int nthreads; /* no. threads */ int **local_newClusterSize; /* [nthreads][numClusters] */ float ***local_newClusters; /* [nthreads][numClusters][numCoords] */ nthreads = omp_get_max_threads(); /* allocate a 2D space for returning variable clusters[] (coordinates of cluster centers) */ clusters = (float**) malloc(numClusters * sizeof(float*)); assert(clusters != NULL); clusters[0] = (float*) malloc(numClusters * numCoords * sizeof(float)); assert(clusters[0] != NULL); for (i=1; i<numClusters; i++) clusters[i] = clusters[i-1] + numCoords; /* pick first numClusters elements of objects[] as initial cluster centers*/ for (i=0; i<numClusters; i++) for (j=0; j<numCoords; j++) clusters[i][j] = objects[i][j]; /* initialize membership[] */ for (i=0; i<numObjs; i++) membership[i] = -1; /* need to initialize newClusterSize and newClusters[0] to all 0 */ newClusterSize = (int*) calloc(numClusters, sizeof(int)); assert(newClusterSize != NULL); newClusters = (float**) malloc(numClusters * sizeof(float*)); assert(newClusters != NULL); newClusters[0] = (float*) calloc(numClusters * numCoords, sizeof(float)); assert(newClusters[0] != NULL); for (i=1; i<numClusters; i++) newClusters[i] = newClusters[i-1] + numCoords; if (!is_perform_atomic) { /* each thread calculates new centers using a private space, then thread 0 does an array reduction on them. This approach should be faster */ local_newClusterSize = (int**) malloc(nthreads * sizeof(int*)); assert(local_newClusterSize != NULL); local_newClusterSize[0] = (int*) calloc(nthreads*numClusters, sizeof(int)); assert(local_newClusterSize[0] != NULL); for (i=1; i<nthreads; i++) local_newClusterSize[i] = local_newClusterSize[i-1]+numClusters; /* local_newClusters is a 3D array */ local_newClusters =(float***)malloc(nthreads * sizeof(float**)); assert(local_newClusters != NULL); local_newClusters[0] =(float**) malloc(nthreads * numClusters * sizeof(float*)); assert(local_newClusters[0] != NULL); for (i=1; i<nthreads; i++) local_newClusters[i] = local_newClusters[i-1] + numClusters; for (i=0; i<nthreads; i++) { for (j=0; j<numClusters; j++) { local_newClusters[i][j] = (float*)calloc(numCoords, sizeof(float)); assert(local_newClusters[i][j] != NULL); } } } if (_debug) timing = omp_get_wtime(); do { delta = 0.0; if (is_perform_atomic) { #pragma omp parallel for \ private(i,j,index) \ firstprivate(numObjs,numClusters,numCoords) \ shared(objects,clusters,membership,newClusters,newClusterSize) \ schedule(static) \ reduction(+:delta) for (i=0; i<numObjs; i++) { /* encuentra el indice al cluster más cercano */ index = find_nearest_cluster(numClusters, numCoords, objects[i], clusters); /* incrementa delta */ if (membership[i] != index) delta += 1.0; /* asigna el id del cluster al objeto-i */ membership[i] = index; /*actualizar los nuevos centros : suma de todos los objetos en la misma región */ #pragma omp atomic newClusterSize[index]++; for (j=0; j<numCoords; j++) #pragma omp atomic newClusters[index][j] += objects[i][j]; } } else { #pragma omp parallel \ shared(objects,clusters,membership,local_newClusters,local_newClusterSize) { int tid = omp_get_thread_num(); #pragma omp for \ private(i,j,index) \ firstprivate(numObjs,numClusters,numCoords) \ schedule(static) \ reduction(+:delta) for (i=0; i<numObjs; i++) { /* encuentra el indice al cluster más cercano */ index = find_nearest_cluster(numClusters, numCoords, objects[i], clusters); /* incrementa delta */ if (membership[i] != index) delta += 1.0; /* asigna el id del cluster al objeto-i*/ membership[i] = index; /* actualizar los nuevos centros : suma de todos los objetos en la misma región*/ local_newClusterSize[tid][index]++; for (j=0; j<numCoords; j++) local_newClusters[tid][index][j] += objects[i][j]; } } /* fin #pragma omp parallel */ /* permite al hilo principal realizar la reduccion del array */ for (i=0; i<numClusters; i++) { for (j=0; j<nthreads; j++) { newClusterSize[i] += local_newClusterSize[j][i]; local_newClusterSize[j][i] = 0.0; for (k=0; k<numCoords; k++) { newClusters[i][k] += local_newClusters[j][i][k]; local_newClusters[j][i][k] = 0.0; } } } } /* promedio de la suma y se reemplaza los centros antiguos con los nuevos */ for (i=0; i<numClusters; i++) { for (j=0; j<numCoords; j++) { if (newClusterSize[i] > 1) clusters[i][j] = newClusters[i][j] / newClusterSize[i]; newClusters[i][j] = 0.0; } newClusterSize[i] = 0; } delta /= numObjs; } while (delta > threshold && loop++ < 500); if (_debug) { timing = omp_get_wtime() - timing; printf("nloops = %2d (T = %7.4f)",loop,timing); } if (!is_perform_atomic) { free(local_newClusterSize[0]); free(local_newClusterSize); for (i=0; i<nthreads; i++) for (j=0; j<numClusters; j++) free(local_newClusters[i][j]); free(local_newClusters[0]); free(local_newClusters); } free(newClusters[0]); free(newClusters); free(newClusterSize); return clusters; }
composite.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % CCCC OOO M M PPPP OOO SSSSS IIIII TTTTT EEEEE % % C O O MM MM P P O O SS I T E % % C O O M M M PPPP O O SSS I T EEE % % C O O M M P O O SS I T E % % CCCC OOO M M P OOO SSSSS IIIII T EEEEE % % % % % % MagickCore Image Composite Methods % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2018 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/artifact.h" #include "MagickCore/cache.h" #include "MagickCore/cache-private.h" #include "MagickCore/cache-view.h" #include "MagickCore/channel.h" #include "MagickCore/client.h" #include "MagickCore/color.h" #include "MagickCore/color-private.h" #include "MagickCore/colorspace.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/composite.h" #include "MagickCore/composite-private.h" #include "MagickCore/constitute.h" #include "MagickCore/draw.h" #include "MagickCore/fx.h" #include "MagickCore/gem.h" #include "MagickCore/geometry.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/list.h" #include "MagickCore/log.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/memory_.h" #include "MagickCore/option.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/property.h" #include "MagickCore/quantum.h" #include "MagickCore/resample.h" #include "MagickCore/resource_.h" #include "MagickCore/string_.h" #include "MagickCore/thread-private.h" #include "MagickCore/threshold.h" #include "MagickCore/token.h" #include "MagickCore/utility.h" #include "MagickCore/utility-private.h" #include "MagickCore/version.h" /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o m p o s i t e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CompositeImage() returns the second image composited onto the first % at the specified offset, using the specified composite method. % % The format of the CompositeImage method is: % % MagickBooleanType CompositeImage(Image *image, % const Image *source_image,const CompositeOperator compose, % const MagickBooleanType clip_to_self,const ssize_t x_offset, % const ssize_t y_offset,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the canvas image, modified by he composition % % o source_image: the source image. % % o compose: This operator affects how the composite is applied to % the image. The operators and how they are utilized are listed here % http://www.w3.org/TR/SVG12/#compositing. % % o clip_to_self: set to MagickTrue to limit composition to area composed. % % o x_offset: the column offset of the composited image. % % o y_offset: the row offset of the composited image. % % Extra Controls from Image meta-data in 'image' (artifacts) % % o "compose:args" % A string containing extra numerical arguments for specific compose % methods, generally expressed as a 'geometry' or a comma separated list % of numbers. % % Compose methods needing such arguments include "BlendCompositeOp" and % "DisplaceCompositeOp". % % o exception: return any errors or warnings in this structure. % */ /* Composition based on the SVG specification: A Composition is defined by... Color Function : f(Sc,Dc) where Sc and Dc are the normizalized colors Blending areas : X = 1 for area of overlap, ie: f(Sc,Dc) Y = 1 for source preserved Z = 1 for canvas preserved Conversion to transparency (then optimized) Dca' = f(Sc, Dc)*Sa*Da + Y*Sca*(1-Da) + Z*Dca*(1-Sa) Da' = X*Sa*Da + Y*Sa*(1-Da) + Z*Da*(1-Sa) Where... Sca = Sc*Sa normalized Source color divided by Source alpha Dca = Dc*Da normalized Dest color divided by Dest alpha Dc' = Dca'/Da' the desired color value for this channel. Da' in in the follow formula as 'gamma' The resulting alpla value. Most functions use a blending mode of over (X=1,Y=1,Z=1) this results in the following optimizations... gamma = Sa+Da-Sa*Da; gamma = 1 - QuantumScale*alpha * QuantumScale*beta; opacity = QuantumScale*alpha*beta; // over blend, optimized 1-Gamma The above SVG definitions also define that Mathematical Composition methods should use a 'Over' blending mode for Alpha Channel. It however was not applied for composition modes of 'Plus', 'Minus', the modulus versions of 'Add' and 'Subtract'. Mathematical operator changes to be applied from IM v6.7... 1) Modulus modes 'Add' and 'Subtract' are obsoleted and renamed 'ModulusAdd' and 'ModulusSubtract' for clarity. 2) All mathematical compositions work as per the SVG specification with regard to blending. This now includes 'ModulusAdd' and 'ModulusSubtract'. 3) When the special channel flag 'sync' (syncronize channel updates) is turned off (enabled by default) then mathematical compositions are only performed on the channels specified, and are applied independantally of each other. In other words the mathematics is performed as 'pure' mathematical operations, rather than as image operations. */ static void HCLComposite(const MagickRealType hue,const MagickRealType chroma, const MagickRealType luma,MagickRealType *red,MagickRealType *green, MagickRealType *blue) { MagickRealType b, c, g, h, m, r, x; /* Convert HCL to RGB colorspace. */ assert(red != (MagickRealType *) NULL); assert(green != (MagickRealType *) NULL); assert(blue != (MagickRealType *) NULL); h=6.0*hue; c=chroma; x=c*(1.0-fabs(fmod(h,2.0)-1.0)); r=0.0; g=0.0; b=0.0; if ((0.0 <= h) && (h < 1.0)) { r=c; g=x; } else if ((1.0 <= h) && (h < 2.0)) { r=x; g=c; } else if ((2.0 <= h) && (h < 3.0)) { g=c; b=x; } else if ((3.0 <= h) && (h < 4.0)) { g=x; b=c; } else if ((4.0 <= h) && (h < 5.0)) { r=x; b=c; } else if ((5.0 <= h) && (h < 6.0)) { r=c; b=x; } m=luma-(0.298839*r+0.586811*g+0.114350*b); *red=QuantumRange*(r+m); *green=QuantumRange*(g+m); *blue=QuantumRange*(b+m); } static void CompositeHCL(const MagickRealType red,const MagickRealType green, const MagickRealType blue,MagickRealType *hue,MagickRealType *chroma, MagickRealType *luma) { MagickRealType b, c, g, h, max, r; /* Convert RGB to HCL colorspace. */ assert(hue != (MagickRealType *) NULL); assert(chroma != (MagickRealType *) NULL); assert(luma != (MagickRealType *) NULL); r=red; g=green; b=blue; max=MagickMax(r,MagickMax(g,b)); c=max-(MagickRealType) MagickMin(r,MagickMin(g,b)); h=0.0; if (c == 0) h=0.0; else if (red == max) h=fmod((g-b)/c+6.0,6.0); else if (green == max) h=((b-r)/c)+2.0; else if (blue == max) h=((r-g)/c)+4.0; *hue=(h/6.0); *chroma=QuantumScale*c; *luma=QuantumScale*(0.298839*r+0.586811*g+0.114350*b); } static MagickBooleanType CompositeOverImage(Image *image, const Image *source_image,const MagickBooleanType clip_to_self, const ssize_t x_offset,const ssize_t y_offset,ExceptionInfo *exception) { #define CompositeImageTag "Composite/Image" CacheView *image_view, *source_view; const char *value; MagickBooleanType clamp, status; MagickOffsetType progress; ssize_t y; /* Composite image. */ status=MagickTrue; progress=0; clamp=MagickTrue; value=GetImageArtifact(image,"compose:clamp"); if (value != (const char *) NULL) clamp=IsStringTrue(value); status=MagickTrue; progress=0; source_view=AcquireVirtualCacheView(source_image,exception); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(source_image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { const Quantum *pixels; PixelInfo canvas_pixel, source_pixel; register const Quantum *magick_restrict p; register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; if (clip_to_self != MagickFalse) { if (y < y_offset) continue; if ((y-y_offset) >= (ssize_t) source_image->rows) continue; } /* If pixels is NULL, y is outside overlay region. */ pixels=(Quantum *) NULL; p=(Quantum *) NULL; if ((y >= y_offset) && ((y-y_offset) < (ssize_t) source_image->rows)) { p=GetCacheViewVirtualPixels(source_view,0,y-y_offset, source_image->columns,1,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; continue; } pixels=p; if (x_offset < 0) p-=x_offset*GetPixelChannels(source_image); } q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } GetPixelInfo(image,&canvas_pixel); GetPixelInfo(source_image,&source_pixel); for (x=0; x < (ssize_t) image->columns; x++) { double gamma; MagickRealType alpha, Da, Dc, Dca, Sa, Sc, Sca; register ssize_t i; size_t channels; if (clip_to_self != MagickFalse) { if (x < x_offset) { q+=GetPixelChannels(image); continue; } if ((x-x_offset) >= (ssize_t) source_image->columns) break; } if ((pixels == (Quantum *) NULL) || (x < x_offset) || ((x-x_offset) >= (ssize_t) source_image->columns)) { Quantum source[MaxPixelChannels]; /* Virtual composite: Sc: source color. Dc: canvas color. */ (void) GetOneVirtualPixel(source_image,x-x_offset,y-y_offset,source, exception); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { MagickRealType pixel; PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait source_traits=GetPixelChannelTraits(source_image, channel); if ((traits == UndefinedPixelTrait) || (source_traits == UndefinedPixelTrait)) continue; if (channel == AlphaPixelChannel) pixel=(MagickRealType) TransparentAlpha; else pixel=(MagickRealType) q[i]; q[i]=clamp != MagickFalse ? ClampPixel(pixel) : ClampToQuantum(pixel); } q+=GetPixelChannels(image); continue; } /* Authentic composite: Sa: normalized source alpha. Da: normalized canvas alpha. */ Sa=QuantumScale*GetPixelAlpha(source_image,p); Da=QuantumScale*GetPixelAlpha(image,q); alpha=Sa+Da-Sa*Da; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { MagickRealType pixel; PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait source_traits=GetPixelChannelTraits(source_image,channel); if (traits == UndefinedPixelTrait) continue; if ((source_traits == UndefinedPixelTrait) && (channel != AlphaPixelChannel)) continue; if (channel == AlphaPixelChannel) { /* Set alpha channel. */ pixel=QuantumRange*alpha; q[i]=clamp != MagickFalse ? ClampPixel(pixel) : ClampToQuantum(pixel); continue; } /* Sc: source color. Dc: canvas color. */ Sc=(MagickRealType) GetPixelChannel(source_image,channel,p); Dc=(MagickRealType) q[i]; if ((traits & CopyPixelTrait) != 0) { /* Copy channel. */ q[i]=ClampToQuantum(Sc); continue; } /* Porter-Duff compositions: Sca: source normalized color multiplied by alpha. Dca: normalized canvas color multiplied by alpha. */ Sca=QuantumScale*Sa*Sc; Dca=QuantumScale*Da*Dc; gamma=PerceptibleReciprocal(alpha); pixel=QuantumRange*gamma*(Sca+Dca*(1.0-Sa)); q[i]=clamp != MagickFalse ? ClampPixel(pixel) : ClampToQuantum(pixel); } p+=GetPixelChannels(source_image); channels=GetPixelChannels(source_image); if (p >= (pixels+channels*source_image->columns)) p=pixels; 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 critical (MagickCore_CompositeImage) #endif proceed=SetImageProgress(image,CompositeImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } source_view=DestroyCacheView(source_view); image_view=DestroyCacheView(image_view); return(status); } MagickExport MagickBooleanType CompositeImage(Image *image, const Image *composite,const CompositeOperator compose, const MagickBooleanType clip_to_self,const ssize_t x_offset, const ssize_t y_offset,ExceptionInfo *exception) { #define CompositeImageTag "Composite/Image" CacheView *source_view, *image_view; const char *value; GeometryInfo geometry_info; Image *canvas_image, *source_image; MagickBooleanType clamp, status; MagickOffsetType progress; MagickRealType amount, canvas_dissolve, midpoint, percent_luma, percent_chroma, source_dissolve, threshold; MagickStatusType flags; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(composite != (Image *) NULL); assert(composite->signature == MagickCoreSignature); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); source_image=CloneImage(composite,0,0,MagickTrue,exception); if (source_image == (const Image *) NULL) return(MagickFalse); if (IsGrayColorspace(image->colorspace) != MagickFalse) (void) SetImageColorspace(image,sRGBColorspace,exception); (void) SetImageColorspace(source_image,image->colorspace,exception); if ((compose == OverCompositeOp) || (compose == SrcOverCompositeOp)) { status=CompositeOverImage(image,source_image,clip_to_self,x_offset, y_offset,exception); source_image=DestroyImage(source_image); return(status); } amount=0.5; canvas_image=(Image *) NULL; canvas_dissolve=1.0; clamp=MagickTrue; value=GetImageArtifact(image,"compose:clamp"); if (value != (const char *) NULL) clamp=IsStringTrue(value); SetGeometryInfo(&geometry_info); percent_luma=100.0; percent_chroma=100.0; source_dissolve=1.0; threshold=0.05f; switch (compose) { case CopyCompositeOp: { if ((x_offset < 0) || (y_offset < 0)) break; if ((x_offset+(ssize_t) source_image->columns) > (ssize_t) image->columns) break; if ((y_offset+(ssize_t) source_image->rows) > (ssize_t) image->rows) break; status=MagickTrue; source_view=AcquireVirtualCacheView(source_image,exception); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(source_image,image,source_image->rows,1) #endif for (y=0; y < (ssize_t) source_image->rows; y++) { MagickBooleanType sync; register const Quantum *p; register Quantum *q; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(source_view,0,y,source_image->columns,1, exception); q=GetCacheViewAuthenticPixels(image_view,x_offset,y+y_offset, source_image->columns,1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) source_image->columns; x++) { register ssize_t i; if (GetPixelReadMask(source_image,p) <= (QuantumRange/2)) { p+=GetPixelChannels(source_image); q+=GetPixelChannels(image); continue; } for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait source_traits=GetPixelChannelTraits(source_image, channel); if (traits == UndefinedPixelTrait) continue; if (source_traits != UndefinedPixelTrait) SetPixelChannel(image,channel,p[i],q); else if (channel == AlphaPixelChannel) SetPixelChannel(image,channel,OpaqueAlpha,q); } p+=GetPixelChannels(source_image); q+=GetPixelChannels(image); } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_CompositeImage) #endif proceed=SetImageProgress(image,CompositeImageTag, (MagickOffsetType) y,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } source_view=DestroyCacheView(source_view); image_view=DestroyCacheView(image_view); source_image=DestroyImage(source_image); return(status); } case IntensityCompositeOp: { if ((x_offset < 0) || (y_offset < 0)) break; if ((x_offset+(ssize_t) source_image->columns) > (ssize_t) image->columns) break; if ((y_offset+(ssize_t) source_image->rows) > (ssize_t) image->rows) break; status=MagickTrue; source_view=AcquireVirtualCacheView(source_image,exception); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(source_image,image,source_image->rows,1) #endif for (y=0; y < (ssize_t) source_image->rows; y++) { MagickBooleanType sync; register const Quantum *p; register Quantum *q; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(source_view,0,y,source_image->columns,1, exception); q=GetCacheViewAuthenticPixels(image_view,x_offset,y+y_offset, source_image->columns,1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) source_image->columns; x++) { if (GetPixelReadMask(source_image,p) <= (QuantumRange/2)) { p+=GetPixelChannels(source_image); q+=GetPixelChannels(image); continue; } SetPixelAlpha(image,clamp != MagickFalse ? ClampPixel(GetPixelIntensity(source_image,p)) : ClampToQuantum(GetPixelIntensity(source_image,p)),q); p+=GetPixelChannels(source_image); q+=GetPixelChannels(image); } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_CompositeImage) #endif proceed=SetImageProgress(image,CompositeImageTag, (MagickOffsetType) y,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } source_view=DestroyCacheView(source_view); image_view=DestroyCacheView(image_view); source_image=DestroyImage(source_image); return(status); } case CopyAlphaCompositeOp: case ChangeMaskCompositeOp: { /* Modify canvas outside the overlaid region and require an alpha channel to exist, to add transparency. */ if (image->alpha_trait == UndefinedPixelTrait) (void) SetImageAlphaChannel(image,OpaqueAlphaChannel,exception); break; } case BlurCompositeOp: { CacheView *canvas_view; MagickRealType angle_range, angle_start, height, width; PixelInfo pixel; ResampleFilter *resample_filter; SegmentInfo blur; /* Blur Image by resampling. Blur Image dictated by an overlay gradient map: X = red_channel; Y = green_channel; compose:args = x_scale[,y_scale[,angle]]. */ canvas_image=CloneImage(image,0,0,MagickTrue, exception); if (canvas_image == (Image *) NULL) { source_image=DestroyImage(source_image); return(MagickFalse); } /* Gather the maximum blur sigma values from user. */ flags=NoValue; value=GetImageArtifact(image,"compose:args"); if (value != (const char *) NULL) flags=ParseGeometry(value,&geometry_info); if ((flags & WidthValue) == 0) { (void) ThrowMagickException(exception,GetMagickModule(),OptionWarning, "InvalidSetting","'%s' '%s'","compose:args",value); source_image=DestroyImage(source_image); canvas_image=DestroyImage(canvas_image); return(MagickFalse); } /* Users input sigma now needs to be converted to the EWA ellipse size. The filter defaults to a sigma of 0.5 so to make this match the users input the ellipse size needs to be doubled. */ width=height=geometry_info.rho*2.0; if ((flags & HeightValue) != 0 ) height=geometry_info.sigma*2.0; /* Default the unrotated ellipse width and height axis vectors. */ blur.x1=width; blur.x2=0.0; blur.y1=0.0; blur.y2=height; /* rotate vectors if a rotation angle is given */ if ((flags & XValue) != 0 ) { MagickRealType angle; angle=DegreesToRadians(geometry_info.xi); blur.x1=width*cos(angle); blur.x2=width*sin(angle); blur.y1=(-height*sin(angle)); blur.y2=height*cos(angle); } /* Otherwise lets set a angle range and calculate in the loop */ angle_start=0.0; angle_range=0.0; if ((flags & YValue) != 0 ) { angle_start=DegreesToRadians(geometry_info.xi); angle_range=DegreesToRadians(geometry_info.psi)-angle_start; } /* Set up a gaussian cylindrical filter for EWA Bluring. As the minimum ellipse radius of support*1.0 the EWA algorithm can only produce a minimum blur of 0.5 for Gaussian (support=2.0) This means that even 'No Blur' will be still a little blurry! The solution (as well as the problem of preventing any user expert filter settings, is to set our own user settings, then restore them afterwards. */ resample_filter=AcquireResampleFilter(image,exception); SetResampleFilter(resample_filter,GaussianFilter); /* do the variable blurring of each pixel in image */ GetPixelInfo(image,&pixel); source_view=AcquireVirtualCacheView(source_image,exception); canvas_view=AcquireAuthenticCacheView(canvas_image,exception); for (y=0; y < (ssize_t) source_image->rows; y++) { MagickBooleanType sync; register const Quantum *magick_restrict p; register Quantum *magick_restrict q; register ssize_t x; if (((y+y_offset) < 0) || ((y+y_offset) >= (ssize_t) image->rows)) continue; p=GetCacheViewVirtualPixels(source_view,0,y,source_image->columns,1, exception); q=QueueCacheViewAuthenticPixels(canvas_view,0,y,canvas_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) break; for (x=0; x < (ssize_t) source_image->columns; x++) { if (((x_offset+x) < 0) || ((x_offset+x) >= (ssize_t) image->columns)) { p+=GetPixelChannels(source_image); continue; } if (fabs((double) angle_range) > MagickEpsilon) { MagickRealType angle; angle=angle_start+angle_range*QuantumScale* GetPixelBlue(source_image,p); blur.x1=width*cos(angle); blur.x2=width*sin(angle); blur.y1=(-height*sin(angle)); blur.y2=height*cos(angle); } #if 0 if ( x == 10 && y == 60 ) { (void) fprintf(stderr, "blur.x=%lf,%lf, blur.y=%lf,%lf\n",blur.x1, blur.x2,blur.y1, blur.y2); (void) fprintf(stderr, "scaled by=%lf,%lf\n",QuantumScale* GetPixelRed(p),QuantumScale*GetPixelGreen(p)); #endif ScaleResampleFilter(resample_filter, blur.x1*QuantumScale*GetPixelRed(source_image,p), blur.y1*QuantumScale*GetPixelGreen(source_image,p), blur.x2*QuantumScale*GetPixelRed(source_image,p), blur.y2*QuantumScale*GetPixelGreen(source_image,p) ); (void) ResamplePixelColor(resample_filter,(double) x_offset+x, (double) y_offset+y,&pixel,exception); SetPixelViaPixelInfo(canvas_image,&pixel,q); p+=GetPixelChannels(source_image); q+=GetPixelChannels(canvas_image); } sync=SyncCacheViewAuthenticPixels(canvas_view,exception); if (sync == MagickFalse) break; } resample_filter=DestroyResampleFilter(resample_filter); source_view=DestroyCacheView(source_view); canvas_view=DestroyCacheView(canvas_view); source_image=DestroyImage(source_image); source_image=canvas_image; break; } case DisplaceCompositeOp: case DistortCompositeOp: { CacheView *canvas_view; MagickRealType horizontal_scale, vertical_scale; PixelInfo pixel; PointInfo center, offset; /* Displace/Distort based on overlay gradient map: X = red_channel; Y = green_channel; compose:args = x_scale[,y_scale[,center.x,center.y]] */ canvas_image=CloneImage(image,0,0,MagickTrue, exception); if (canvas_image == (Image *) NULL) { source_image=DestroyImage(source_image); return(MagickFalse); } SetGeometryInfo(&geometry_info); flags=NoValue; value=GetImageArtifact(image,"compose:args"); if (value != (char *) NULL) flags=ParseGeometry(value,&geometry_info); if ((flags & (WidthValue | HeightValue)) == 0 ) { if ((flags & AspectValue) == 0) { horizontal_scale=(MagickRealType) (source_image->columns-1)/2.0; vertical_scale=(MagickRealType) (source_image->rows-1)/2.0; } else { horizontal_scale=(MagickRealType) (image->columns-1)/2.0; vertical_scale=(MagickRealType) (image->rows-1)/2.0; } } else { horizontal_scale=geometry_info.rho; vertical_scale=geometry_info.sigma; if ((flags & PercentValue) != 0) { if ((flags & AspectValue) == 0) { horizontal_scale*=(source_image->columns-1)/200.0; vertical_scale*=(source_image->rows-1)/200.0; } else { horizontal_scale*=(image->columns-1)/200.0; vertical_scale*=(image->rows-1)/200.0; } } if ((flags & HeightValue) == 0) vertical_scale=horizontal_scale; } /* Determine fixed center point for absolute distortion map Absolute distort == Displace offset relative to a fixed absolute point Select that point according to +X+Y user inputs. default = center of overlay image arg flag '!' = locations/percentage relative to background image */ center.x=(MagickRealType) x_offset; center.y=(MagickRealType) y_offset; if (compose == DistortCompositeOp) { if ((flags & XValue) == 0) if ((flags & AspectValue) != 0) center.x=(MagickRealType) ((image->columns-1)/2.0); else center.x=(MagickRealType) (x_offset+(source_image->columns-1)/ 2.0); else if ((flags & AspectValue) != 0) center.x=geometry_info.xi; else center.x=(MagickRealType) (x_offset+geometry_info.xi); if ((flags & YValue) == 0) if ((flags & AspectValue) != 0) center.y=(MagickRealType) ((image->rows-1)/2.0); else center.y=(MagickRealType) (y_offset+(source_image->rows-1)/2.0); else if ((flags & AspectValue) != 0) center.y=geometry_info.psi; else center.y=(MagickRealType) (y_offset+geometry_info.psi); } /* Shift the pixel offset point as defined by the provided, displacement/distortion map. -- Like a lens... */ GetPixelInfo(image,&pixel); image_view=AcquireVirtualCacheView(image,exception); source_view=AcquireVirtualCacheView(source_image,exception); canvas_view=AcquireAuthenticCacheView(canvas_image,exception); for (y=0; y < (ssize_t) source_image->rows; y++) { MagickBooleanType sync; register const Quantum *magick_restrict p; register Quantum *magick_restrict q; register ssize_t x; if (((y+y_offset) < 0) || ((y+y_offset) >= (ssize_t) image->rows)) continue; p=GetCacheViewVirtualPixels(source_view,0,y,source_image->columns,1, exception); q=QueueCacheViewAuthenticPixels(canvas_view,0,y,canvas_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) break; for (x=0; x < (ssize_t) source_image->columns; x++) { if (((x_offset+x) < 0) || ((x_offset+x) >= (ssize_t) image->columns)) { p+=GetPixelChannels(source_image); continue; } /* Displace the offset. */ offset.x=(double) (horizontal_scale*(GetPixelRed(source_image,p)- (((MagickRealType) QuantumRange+1.0)/2.0)))/(((MagickRealType) QuantumRange+1.0)/2.0)+center.x+((compose == DisplaceCompositeOp) ? x : 0); offset.y=(double) (vertical_scale*(GetPixelGreen(source_image,p)- (((MagickRealType) QuantumRange+1.0)/2.0)))/(((MagickRealType) QuantumRange+1.0)/2.0)+center.y+((compose == DisplaceCompositeOp) ? y : 0); status=InterpolatePixelInfo(image,image_view, UndefinedInterpolatePixel,(double) offset.x,(double) offset.y, &pixel,exception); if (status == MagickFalse) break; /* Mask with the 'invalid pixel mask' in alpha channel. */ pixel.alpha=(MagickRealType) QuantumRange*(QuantumScale*pixel.alpha)* (QuantumScale*GetPixelAlpha(source_image,p)); SetPixelViaPixelInfo(canvas_image,&pixel,q); p+=GetPixelChannels(source_image); q+=GetPixelChannels(canvas_image); } if (x < (ssize_t) source_image->columns) break; sync=SyncCacheViewAuthenticPixels(canvas_view,exception); if (sync == MagickFalse) break; } canvas_view=DestroyCacheView(canvas_view); source_view=DestroyCacheView(source_view); image_view=DestroyCacheView(image_view); source_image=DestroyImage(source_image); source_image=canvas_image; break; } case DissolveCompositeOp: { /* Geometry arguments to dissolve factors. */ value=GetImageArtifact(image,"compose:args"); if (value != (char *) NULL) { flags=ParseGeometry(value,&geometry_info); source_dissolve=geometry_info.rho/100.0; canvas_dissolve=1.0; if ((source_dissolve-MagickEpsilon) < 0.0) source_dissolve=0.0; if ((source_dissolve+MagickEpsilon) > 1.0) { canvas_dissolve=2.0-source_dissolve; source_dissolve=1.0; } if ((flags & SigmaValue) != 0) canvas_dissolve=geometry_info.sigma/100.0; if ((canvas_dissolve-MagickEpsilon) < 0.0) canvas_dissolve=0.0; } break; } case BlendCompositeOp: { value=GetImageArtifact(image,"compose:args"); if (value != (char *) NULL) { flags=ParseGeometry(value,&geometry_info); source_dissolve=geometry_info.rho/100.0; canvas_dissolve=1.0-source_dissolve; if ((flags & SigmaValue) != 0) canvas_dissolve=geometry_info.sigma/100.0; } break; } case MathematicsCompositeOp: { /* Just collect the values from "compose:args", setting. Unused values are set to zero automagically. Arguments are normally a comma separated list, so this probably should be changed to some 'general comma list' parser, (with a minimum number of values) */ SetGeometryInfo(&geometry_info); value=GetImageArtifact(image,"compose:args"); if (value != (char *) NULL) (void) ParseGeometry(value,&geometry_info); break; } case ModulateCompositeOp: { /* Determine the luma and chroma scale. */ value=GetImageArtifact(image,"compose:args"); if (value != (char *) NULL) { flags=ParseGeometry(value,&geometry_info); percent_luma=geometry_info.rho; if ((flags & SigmaValue) != 0) percent_chroma=geometry_info.sigma; } break; } case ThresholdCompositeOp: { /* Determine the amount and threshold. */ value=GetImageArtifact(image,"compose:args"); if (value != (char *) NULL) { flags=ParseGeometry(value,&geometry_info); amount=geometry_info.rho; threshold=geometry_info.sigma; if ((flags & SigmaValue) == 0) threshold=0.05f; } threshold*=QuantumRange; break; } default: break; } /* Composite image. */ status=MagickTrue; progress=0; midpoint=((MagickRealType) QuantumRange+1.0)/2; source_view=AcquireVirtualCacheView(source_image,exception); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(source_image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { const Quantum *pixels; MagickRealType blue, chroma, green, hue, luma, red; PixelInfo canvas_pixel, source_pixel; register const Quantum *magick_restrict p; register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; if (clip_to_self != MagickFalse) { if (y < y_offset) continue; if ((y-y_offset) >= (ssize_t) source_image->rows) continue; } /* If pixels is NULL, y is outside overlay region. */ pixels=(Quantum *) NULL; p=(Quantum *) NULL; if ((y >= y_offset) && ((y-y_offset) < (ssize_t) source_image->rows)) { p=GetCacheViewVirtualPixels(source_view,0,y-y_offset, source_image->columns,1,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; continue; } pixels=p; if (x_offset < 0) p-=x_offset*GetPixelChannels(source_image); } q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } hue=0.0; chroma=0.0; luma=0.0; GetPixelInfo(image,&canvas_pixel); GetPixelInfo(source_image,&source_pixel); for (x=0; x < (ssize_t) image->columns; x++) { double gamma; MagickRealType alpha, Da, Dc, Dca, DcaDa, Sa, SaSca, Sc, Sca; register ssize_t i; size_t channels; if (clip_to_self != MagickFalse) { if (x < x_offset) { q+=GetPixelChannels(image); continue; } if ((x-x_offset) >= (ssize_t) source_image->columns) break; } if ((pixels == (Quantum *) NULL) || (x < x_offset) || ((x-x_offset) >= (ssize_t) source_image->columns)) { Quantum source[MaxPixelChannels]; /* Virtual composite: Sc: source color. Dc: canvas color. */ (void) GetOneVirtualPixel(source_image,x-x_offset,y-y_offset,source, exception); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { MagickRealType pixel; PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait source_traits=GetPixelChannelTraits(source_image, channel); if ((traits == UndefinedPixelTrait) || (source_traits == UndefinedPixelTrait)) continue; switch (compose) { case AlphaCompositeOp: case ChangeMaskCompositeOp: case CopyAlphaCompositeOp: case DstAtopCompositeOp: case DstInCompositeOp: case InCompositeOp: case OutCompositeOp: case SrcInCompositeOp: case SrcOutCompositeOp: { if (channel == AlphaPixelChannel) pixel=(MagickRealType) TransparentAlpha; else pixel=(MagickRealType) q[i]; break; } case ClearCompositeOp: case CopyCompositeOp: case ReplaceCompositeOp: case SrcCompositeOp: { if (channel == AlphaPixelChannel) pixel=(MagickRealType) TransparentAlpha; else pixel=0.0; break; } case BlendCompositeOp: case DissolveCompositeOp: { if (channel == AlphaPixelChannel) pixel=canvas_dissolve*GetPixelAlpha(source_image,source); else pixel=(MagickRealType) source[channel]; break; } default: { pixel=(MagickRealType) source[channel]; break; } } q[i]=clamp != MagickFalse ? ClampPixel(pixel) : ClampToQuantum(pixel); } q+=GetPixelChannels(image); continue; } /* Authentic composite: Sa: normalized source alpha. Da: normalized canvas alpha. */ Sa=QuantumScale*GetPixelAlpha(source_image,p); Da=QuantumScale*GetPixelAlpha(image,q); switch (compose) { case BumpmapCompositeOp: { alpha=GetPixelIntensity(source_image,p)*Sa; break; } case ColorBurnCompositeOp: case ColorDodgeCompositeOp: case DarkenCompositeOp: case DifferenceCompositeOp: case DivideDstCompositeOp: case DivideSrcCompositeOp: case ExclusionCompositeOp: case HardLightCompositeOp: case HardMixCompositeOp: case LinearBurnCompositeOp: case LinearDodgeCompositeOp: case LinearLightCompositeOp: case LightenCompositeOp: case MathematicsCompositeOp: case MinusDstCompositeOp: case MinusSrcCompositeOp: case ModulusAddCompositeOp: case ModulusSubtractCompositeOp: case MultiplyCompositeOp: case OverlayCompositeOp: case PegtopLightCompositeOp: case PinLightCompositeOp: case ScreenCompositeOp: case SoftLightCompositeOp: case VividLightCompositeOp: { alpha=RoundToUnity(Sa+Da-Sa*Da); break; } case DstAtopCompositeOp: case DstInCompositeOp: case InCompositeOp: case SrcInCompositeOp: { alpha=Sa*Da; break; } case DissolveCompositeOp: { alpha=source_dissolve*Sa*(-canvas_dissolve*Da)+source_dissolve*Sa+ canvas_dissolve*Da; break; } case DstOverCompositeOp: case OverCompositeOp: case SrcOverCompositeOp: { alpha=Sa+Da-Sa*Da; break; } case DstOutCompositeOp: { alpha=Da*(1.0-Sa); break; } case OutCompositeOp: case SrcOutCompositeOp: { alpha=Sa*(1.0-Da); break; } case BlendCompositeOp: case PlusCompositeOp: { alpha=RoundToUnity(source_dissolve*Sa+canvas_dissolve*Da); break; } case XorCompositeOp: { alpha=Sa+Da-2.0*Sa*Da; break; } default: { alpha=1.0; break; } } switch (compose) { case ColorizeCompositeOp: case HueCompositeOp: case LuminizeCompositeOp: case ModulateCompositeOp: case SaturateCompositeOp: { GetPixelInfoPixel(source_image,p,&source_pixel); GetPixelInfoPixel(image,q,&canvas_pixel); break; } default: break; } for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { MagickRealType pixel, sans; PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait source_traits = GetPixelChannelTraits(source_image,channel); if (traits == UndefinedPixelTrait) continue; if ((channel == AlphaPixelChannel) && ((traits & UpdatePixelTrait) != 0)) { /* Set alpha channel. */ switch (compose) { case AlphaCompositeOp: { pixel=QuantumRange*Sa; break; } case AtopCompositeOp: case CopyBlackCompositeOp: case CopyBlueCompositeOp: case CopyCyanCompositeOp: case CopyGreenCompositeOp: case CopyMagentaCompositeOp: case CopyRedCompositeOp: case CopyYellowCompositeOp: case SrcAtopCompositeOp: case DstCompositeOp: case NoCompositeOp: { pixel=QuantumRange*Da; break; } case ChangeMaskCompositeOp: { MagickBooleanType equivalent; if (Da < 0.5) { pixel=(MagickRealType) TransparentAlpha; break; } equivalent=IsFuzzyEquivalencePixel(source_image,p,image,q); if (equivalent != MagickFalse) pixel=(MagickRealType) TransparentAlpha; else pixel=(MagickRealType) OpaqueAlpha; break; } case ClearCompositeOp: { pixel=(MagickRealType) TransparentAlpha; break; } case ColorizeCompositeOp: case HueCompositeOp: case LuminizeCompositeOp: case SaturateCompositeOp: { if (fabs((double) (QuantumRange*Sa-TransparentAlpha)) < MagickEpsilon) { pixel=QuantumRange*Da; break; } if (fabs((double) (QuantumRange*Da-TransparentAlpha)) < MagickEpsilon) { pixel=QuantumRange*Sa; break; } if (Sa < Da) { pixel=QuantumRange*Da; break; } pixel=QuantumRange*Sa; break; } case CopyAlphaCompositeOp: { if (source_image->alpha_trait == UndefinedPixelTrait) pixel=GetPixelIntensity(source_image,p); else pixel=QuantumRange*Sa; break; } case CopyCompositeOp: case DisplaceCompositeOp: case DistortCompositeOp: case DstAtopCompositeOp: case ReplaceCompositeOp: case SrcCompositeOp: { pixel=QuantumRange*Sa; break; } case DarkenIntensityCompositeOp: { pixel=Sa*GetPixelIntensity(source_image,p) < Da*GetPixelIntensity(image,q) ? Sa : Da; break; } case LightenIntensityCompositeOp: { pixel=Sa*GetPixelIntensity(source_image,p) > Da*GetPixelIntensity(image,q) ? Sa : Da; break; } case ModulateCompositeOp: { pixel=QuantumRange*Da; break; } case MultiplyCompositeOp: { pixel=QuantumRange*Sa*Da; break; } default: { pixel=QuantumRange*alpha; break; } } q[i]=clamp != MagickFalse ? ClampPixel(pixel) : ClampToQuantum(pixel); continue; } if (source_traits == UndefinedPixelTrait) continue; /* Sc: source color. Dc: canvas color. */ Sc=(MagickRealType) GetPixelChannel(source_image,channel,p); Dc=(MagickRealType) q[i]; if ((traits & CopyPixelTrait) != 0) { /* Copy channel. */ q[i]=ClampToQuantum(Dc); continue; } /* Porter-Duff compositions: Sca: source normalized color multiplied by alpha. Dca: normalized canvas color multiplied by alpha. */ Sca=QuantumScale*Sa*Sc; Dca=QuantumScale*Da*Dc; SaSca=Sa*PerceptibleReciprocal(Sca); DcaDa=Dca*PerceptibleReciprocal(Da); switch (compose) { case DarkenCompositeOp: case LightenCompositeOp: case ModulusSubtractCompositeOp: { gamma=PerceptibleReciprocal(1.0-alpha); break; } default: { gamma=PerceptibleReciprocal(alpha); break; } } pixel=Dc; switch (compose) { case AlphaCompositeOp: { pixel=QuantumRange*Sa; break; } case AtopCompositeOp: case SrcAtopCompositeOp: { pixel=QuantumRange*(Sca*Da+Dca*(1.0-Sa)); break; } case BlendCompositeOp: { pixel=gamma*(source_dissolve*Sa*Sc+canvas_dissolve*Da*Dc); break; } case BlurCompositeOp: case CopyCompositeOp: case ReplaceCompositeOp: case SrcCompositeOp: { pixel=QuantumRange*Sca; break; } case DisplaceCompositeOp: case DistortCompositeOp: { pixel=Sc; break; } case BumpmapCompositeOp: { if (fabs((double) (QuantumRange*Sa-TransparentAlpha)) < MagickEpsilon) { pixel=Dc; break; } pixel=QuantumScale*GetPixelIntensity(source_image,p)*Dc; break; } case ChangeMaskCompositeOp: { pixel=Dc; break; } case ClearCompositeOp: { pixel=0.0; break; } case ColorBurnCompositeOp: { if ((Sca == 0.0) && (Dca == Da)) { pixel=QuantumRange*gamma*(Sa*Da+Dca*(1.0-Sa)); break; } if (Sca == 0.0) { pixel=QuantumRange*gamma*(Dca*(1.0-Sa)); break; } pixel=QuantumRange*gamma*(Sa*Da-Sa*Da*MagickMin(1.0,(1.0-DcaDa)* SaSca)+Sca*(1.0-Da)+Dca*(1.0-Sa)); break; } case ColorDodgeCompositeOp: { if ((Sca*Da+Dca*Sa) >= Sa*Da) pixel=QuantumRange*gamma*(Sa*Da+Sca*(1.0-Da)+Dca*(1.0-Sa)); else pixel=QuantumRange*gamma*(Dca*Sa*Sa*PerceptibleReciprocal(Sa-Sca)+ Sca*(1.0-Da)+Dca*(1.0-Sa)); break; } case ColorizeCompositeOp: { if (fabs((double) (QuantumRange*Sa-TransparentAlpha)) < MagickEpsilon) { pixel=Dc; break; } if (fabs((double) (QuantumRange*Da-TransparentAlpha)) < MagickEpsilon) { pixel=Sc; break; } CompositeHCL(canvas_pixel.red,canvas_pixel.green,canvas_pixel.blue, &sans,&sans,&luma); CompositeHCL(source_pixel.red,source_pixel.green,source_pixel.blue, &hue,&chroma,&sans); HCLComposite(hue,chroma,luma,&red,&green,&blue); switch (channel) { case RedPixelChannel: pixel=red; break; case GreenPixelChannel: pixel=green; break; case BluePixelChannel: pixel=blue; break; default: pixel=Dc; break; } break; } case CopyAlphaCompositeOp: { pixel=Dc; break; } case CopyBlackCompositeOp: { if (channel == BlackPixelChannel) pixel=(MagickRealType) (QuantumRange- GetPixelBlack(source_image,p)); break; } case CopyBlueCompositeOp: case CopyYellowCompositeOp: { if (channel == BluePixelChannel) pixel=(MagickRealType) GetPixelBlue(source_image,p); break; } case CopyGreenCompositeOp: case CopyMagentaCompositeOp: { if (channel == GreenPixelChannel) pixel=(MagickRealType) GetPixelGreen(source_image,p); break; } case CopyRedCompositeOp: case CopyCyanCompositeOp: { if (channel == RedPixelChannel) pixel=(MagickRealType) GetPixelRed(source_image,p); break; } case DarkenCompositeOp: { /* Darken is equivalent to a 'Minimum' method OR a greyscale version of a binary 'Or' OR the 'Intersection' of pixel sets. */ if ((Sca*Da) < (Dca*Sa)) { pixel=QuantumRange*(Sca+Dca*(1.0-Sa)); break; } pixel=QuantumRange*(Dca+Sca*(1.0-Da)); break; } case DarkenIntensityCompositeOp: { pixel=Sa*GetPixelIntensity(source_image,p) < Da*GetPixelIntensity(image,q) ? Sc : Dc; break; } case DifferenceCompositeOp: { pixel=QuantumRange*gamma*(Sca+Dca-2.0*MagickMin(Sca*Da,Dca*Sa)); break; } case DissolveCompositeOp: { pixel=gamma*(source_dissolve*Sa*Sc-source_dissolve*Sa* canvas_dissolve*Da*Dc+canvas_dissolve*Da*Dc); break; } case DivideDstCompositeOp: { if ((fabs((double) Sca) < MagickEpsilon) && (fabs((double) Dca) < MagickEpsilon)) { pixel=QuantumRange*gamma*(Sca*(1.0-Da)+Dca*(1.0-Sa)); break; } if (fabs((double) Dca) < MagickEpsilon) { pixel=QuantumRange*gamma*(Sa*Da+Sca*(1.0-Da)+Dca*(1.0-Sa)); break; } pixel=QuantumRange*gamma*(Sca*Da*Da/Dca+Sca*(1.0-Da)+Dca*(1.0-Sa)); break; } case DivideSrcCompositeOp: { if ((fabs((double) Dca) < MagickEpsilon) && (fabs((double) Sca) < MagickEpsilon)) { pixel=QuantumRange*gamma*(Dca*(1.0-Sa)+Sca*(1.0-Da)); break; } if (fabs((double) Sca) < MagickEpsilon) { pixel=QuantumRange*gamma*(Da*Sa+Dca*(1.0-Sa)+Sca*(1.0-Da)); break; } pixel=QuantumRange*gamma*(Dca*Sa*SaSca+Dca*(1.0-Sa)+Sca*(1.0-Da)); break; } case DstAtopCompositeOp: { pixel=QuantumRange*(Dca*Sa+Sca*(1.0-Da)); break; } case DstCompositeOp: case NoCompositeOp: { pixel=QuantumRange*Dca; break; } case DstInCompositeOp: { pixel=QuantumRange*(Dca*Sa); break; } case DstOutCompositeOp: { pixel=QuantumRange*(Dca*(1.0-Sa)); break; } case DstOverCompositeOp: { pixel=QuantumRange*gamma*(Dca+Sca*(1.0-Da)); break; } case ExclusionCompositeOp: { pixel=QuantumRange*gamma*(Sca*Da+Dca*Sa-2.0*Sca*Dca+Sca*(1.0-Da)+ Dca*(1.0-Sa)); break; } case HardLightCompositeOp: { if ((2.0*Sca) < Sa) { pixel=QuantumRange*gamma*(2.0*Sca*Dca+Sca*(1.0-Da)+Dca*(1.0- Sa)); break; } pixel=QuantumRange*gamma*(Sa*Da-2.0*(Da-Dca)*(Sa-Sca)+Sca*(1.0-Da)+ Dca*(1.0-Sa)); break; } case HardMixCompositeOp: { pixel=gamma*(((Sca+Dca) < 1.0) ? 0.0 : QuantumRange); break; } case HueCompositeOp: { if (fabs((double) (QuantumRange*Sa-TransparentAlpha)) < MagickEpsilon) { pixel=Dc; break; } if (fabs((double) (QuantumRange*Da-TransparentAlpha)) < MagickEpsilon) { pixel=Sc; break; } CompositeHCL(canvas_pixel.red,canvas_pixel.green,canvas_pixel.blue, &hue,&chroma,&luma); CompositeHCL(source_pixel.red,source_pixel.green,source_pixel.blue, &hue,&sans,&sans); HCLComposite(hue,chroma,luma,&red,&green,&blue); switch (channel) { case RedPixelChannel: pixel=red; break; case GreenPixelChannel: pixel=green; break; case BluePixelChannel: pixel=blue; break; default: pixel=Dc; break; } break; } case InCompositeOp: case SrcInCompositeOp: { pixel=QuantumRange*(Sca*Da); break; } case LinearBurnCompositeOp: { /* LinearBurn: as defined by Abode Photoshop, according to http://www.simplefilter.de/en/basics/mixmods.html is: f(Sc,Dc) = Sc + Dc - 1 */ pixel=QuantumRange*gamma*(Sca+Dca-Sa*Da); break; } case LinearDodgeCompositeOp: { pixel=gamma*(Sa*Sc+Da*Dc); break; } case LinearLightCompositeOp: { /* LinearLight: as defined by Abode Photoshop, according to http://www.simplefilter.de/en/basics/mixmods.html is: f(Sc,Dc) = Dc + 2*Sc - 1 */ pixel=QuantumRange*gamma*((Sca-Sa)*Da+Sca+Dca); break; } case LightenCompositeOp: { if ((Sca*Da) > (Dca*Sa)) { pixel=QuantumRange*(Sca+Dca*(1.0-Sa)); break; } pixel=QuantumRange*(Dca+Sca*(1.0-Da)); break; } case LightenIntensityCompositeOp: { /* Lighten is equivalent to a 'Maximum' method OR a greyscale version of a binary 'And' OR the 'Union' of pixel sets. */ pixel=Sa*GetPixelIntensity(source_image,p) > Da*GetPixelIntensity(image,q) ? Sc : Dc; break; } case LuminizeCompositeOp: { if (fabs((double) (QuantumRange*Sa-TransparentAlpha)) < MagickEpsilon) { pixel=Dc; break; } if (fabs((double) (QuantumRange*Da-TransparentAlpha)) < MagickEpsilon) { pixel=Sc; break; } CompositeHCL(canvas_pixel.red,canvas_pixel.green,canvas_pixel.blue, &hue,&chroma,&luma); CompositeHCL(source_pixel.red,source_pixel.green,source_pixel.blue, &sans,&sans,&luma); HCLComposite(hue,chroma,luma,&red,&green,&blue); switch (channel) { case RedPixelChannel: pixel=red; break; case GreenPixelChannel: pixel=green; break; case BluePixelChannel: pixel=blue; break; default: pixel=Dc; break; } break; } case MathematicsCompositeOp: { /* 'Mathematics' a free form user control mathematical composition is defined as... f(Sc,Dc) = A*Sc*Dc + B*Sc + C*Dc + D Where the arguments A,B,C,D are (currently) passed to composite as a command separated 'geometry' string in "compose:args" image artifact. A = a->rho, B = a->sigma, C = a->xi, D = a->psi Applying the SVG transparency formula (see above), we get... Dca' = Sa*Da*f(Sc,Dc) + Sca*(1.0-Da) + Dca*(1.0-Sa) Dca' = A*Sca*Dca + B*Sca*Da + C*Dca*Sa + D*Sa*Da + Sca*(1.0-Da) + Dca*(1.0-Sa) */ pixel=QuantumRange*gamma*(geometry_info.rho*Sca*Dca+ geometry_info.sigma*Sca*Da+geometry_info.xi*Dca*Sa+ geometry_info.psi*Sa*Da+Sca*(1.0-Da)+Dca*(1.0-Sa)); break; } case MinusDstCompositeOp: { pixel=gamma*(Sa*Sc+Da*Dc-2.0*Da*Dc*Sa); break; } case MinusSrcCompositeOp: { /* Minus source from canvas. f(Sc,Dc) = Sc - Dc */ pixel=gamma*(Da*Dc+Sa*Sc-2.0*Sa*Sc*Da); break; } case ModulateCompositeOp: { ssize_t offset; if (fabs((double) (QuantumRange*Sa-TransparentAlpha)) < MagickEpsilon) { pixel=Dc; break; } offset=(ssize_t) (GetPixelIntensity(source_image,p)-midpoint); if (offset == 0) { pixel=Dc; break; } CompositeHCL(canvas_pixel.red,canvas_pixel.green,canvas_pixel.blue, &hue,&chroma,&luma); luma+=(0.01*percent_luma*offset)/midpoint; chroma*=0.01*percent_chroma; HCLComposite(hue,chroma,luma,&red,&green,&blue); switch (channel) { case RedPixelChannel: pixel=red; break; case GreenPixelChannel: pixel=green; break; case BluePixelChannel: pixel=blue; break; default: pixel=Dc; break; } break; } case ModulusAddCompositeOp: { pixel=Sc+Dc; while (pixel > QuantumRange) pixel-=QuantumRange; while (pixel < 0.0) pixel+=QuantumRange; pixel=(Sa*Da*pixel+Sa*Sc*(1.0-Da)+Da*Dc*(1.0-Sa)); break; } case ModulusSubtractCompositeOp: { pixel=Sc-Dc; while (pixel > QuantumRange) pixel-=QuantumRange; while (pixel < 0.0) pixel+=QuantumRange; pixel=(Sa*Da*pixel+Sa*Sc*(1.0-Da)+Da*Dc*(1.0-Sa)); break; } case MultiplyCompositeOp: { pixel=QuantumRange*gamma*(Sca*Dca+Sca*(1.0-Da)+Dca*(1.0-Sa)); break; } case OutCompositeOp: case SrcOutCompositeOp: { pixel=QuantumRange*(Sca*(1.0-Da)); break; } case OverCompositeOp: case SrcOverCompositeOp: { pixel=QuantumRange*gamma*(Sca+Dca*(1.0-Sa)); break; } case OverlayCompositeOp: { if ((2.0*Dca) < Da) { pixel=QuantumRange*gamma*(2.0*Dca*Sca+Dca*(1.0-Sa)+Sca*(1.0- Da)); break; } pixel=QuantumRange*gamma*(Da*Sa-2.0*(Sa-Sca)*(Da-Dca)+Dca*(1.0-Sa)+ Sca*(1.0-Da)); break; } case PegtopLightCompositeOp: { /* PegTop: A Soft-Light alternative: A continuous version of the Softlight function, producing very similar results. f(Sc,Dc) = Dc^2*(1-2*Sc) + 2*Sc*Dc http://www.pegtop.net/delphi/articles/blendmodes/softlight.htm. */ if (fabs((double) Da) < MagickEpsilon) { pixel=QuantumRange*gamma*(Sca); break; } pixel=QuantumRange*gamma*(Dca*Dca*(Sa-2.0*Sca)/Da+Sca*(2.0*Dca+1.0- Da)+Dca*(1.0-Sa)); break; } case PinLightCompositeOp: { /* PinLight: A Photoshop 7 composition method http://www.simplefilter.de/en/basics/mixmods.html f(Sc,Dc) = Dc<2*Sc-1 ? 2*Sc-1 : Dc>2*Sc ? 2*Sc : Dc */ if ((Dca*Sa) < (Da*(2.0*Sca-Sa))) { pixel=QuantumRange*gamma*(Sca*(Da+1.0)-Sa*Da+Dca*(1.0-Sa)); break; } if ((Dca*Sa) > (2.0*Sca*Da)) { pixel=QuantumRange*gamma*(Sca*Da+Sca+Dca*(1.0-Sa)); break; } pixel=QuantumRange*gamma*(Sca*(1.0-Da)+Dca); break; } case PlusCompositeOp: { pixel=QuantumRange*(Sca+Dca); break; } case SaturateCompositeOp: { if (fabs((double) (QuantumRange*Sa-TransparentAlpha)) < MagickEpsilon) { pixel=Dc; break; } if (fabs((double) (QuantumRange*Da-TransparentAlpha)) < MagickEpsilon) { pixel=Sc; break; } CompositeHCL(canvas_pixel.red,canvas_pixel.green,canvas_pixel.blue, &hue,&chroma,&luma); CompositeHCL(source_pixel.red,source_pixel.green,source_pixel.blue, &sans,&chroma,&sans); HCLComposite(hue,chroma,luma,&red,&green,&blue); switch (channel) { case RedPixelChannel: pixel=red; break; case GreenPixelChannel: pixel=green; break; case BluePixelChannel: pixel=blue; break; default: pixel=Dc; break; } break; } case ScreenCompositeOp: { /* Screen: a negated multiply: f(Sc,Dc) = 1.0-(1.0-Sc)*(1.0-Dc) */ pixel=QuantumRange*gamma*(Sca+Dca-Sca*Dca); break; } case SoftLightCompositeOp: { if ((2.0*Sca) < Sa) { pixel=QuantumRange*gamma*(Dca*(Sa+(2.0*Sca-Sa)*(1.0-DcaDa))+ Sca*(1.0-Da)+Dca*(1.0-Sa)); break; } if (((2.0*Sca) > Sa) && ((4.0*Dca) <= Da)) { pixel=QuantumRange*gamma*(Dca*Sa+Da*(2.0*Sca-Sa)*(4.0*DcaDa* (4.0*DcaDa+1.0)*(DcaDa-1.0)+7.0*DcaDa)+Sca*(1.0-Da)+ Dca*(1.0-Sa)); break; } pixel=QuantumRange*gamma*(Dca*Sa+Da*(2.0*Sca-Sa)*(pow(DcaDa,0.5)- DcaDa)+Sca*(1.0-Da)+Dca*(1.0-Sa)); break; } case StereoCompositeOp: { if (channel == RedPixelChannel) pixel=(MagickRealType) GetPixelRed(source_image,p); break; } case ThresholdCompositeOp: { MagickRealType delta; delta=Sc-Dc; if ((MagickRealType) fabs((double) (2.0*delta)) < threshold) { pixel=gamma*Dc; break; } pixel=gamma*(Dc+delta*amount); break; } case VividLightCompositeOp: { /* VividLight: A Photoshop 7 composition method. See http://www.simplefilter.de/en/basics/mixmods.html. f(Sc,Dc) = (2*Sc < 1) ? 1-(1-Dc)/(2*Sc) : Dc/(2*(1-Sc)) */ if ((fabs((double) Sa) < MagickEpsilon) || (fabs((double) (Sca-Sa)) < MagickEpsilon)) { pixel=QuantumRange*gamma*(Sa*Da+Sca*(1.0-Da)+Dca*(1.0-Sa)); break; } if ((2.0*Sca) <= Sa) { pixel=QuantumRange*gamma*(Sa*(Da+Sa*(Dca-Da)* PerceptibleReciprocal(2.0*Sca))+Sca*(1.0-Da)+Dca*(1.0-Sa)); break; } pixel=QuantumRange*gamma*(Dca*Sa*Sa*PerceptibleReciprocal(2.0* (Sa-Sca))+Sca*(1.0-Da)+Dca*(1.0-Sa)); break; } case XorCompositeOp: { pixel=QuantumRange*(Sca*(1.0-Da)+Dca*(1.0-Sa)); break; } default: { pixel=Sc; break; } } q[i]=clamp != MagickFalse ? ClampPixel(pixel) : ClampToQuantum(pixel); } p+=GetPixelChannels(source_image); channels=GetPixelChannels(source_image); if (p >= (pixels+channels*source_image->columns)) p=pixels; 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 critical (MagickCore_CompositeImage) #endif proceed=SetImageProgress(image,CompositeImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } source_view=DestroyCacheView(source_view); image_view=DestroyCacheView(image_view); if (canvas_image != (Image * ) NULL) canvas_image=DestroyImage(canvas_image); else source_image=DestroyImage(source_image); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % T e x t u r e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % TextureImage() repeatedly tiles the texture image across and down the image % canvas. % % The format of the TextureImage method is: % % MagickBooleanType TextureImage(Image *image,const Image *texture, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o texture_image: This image is the texture to layer on the background. % */ MagickExport MagickBooleanType TextureImage(Image *image,const Image *texture, ExceptionInfo *exception) { #define TextureImageTag "Texture/Image" CacheView *image_view, *texture_view; Image *texture_image; MagickBooleanType status; ssize_t y; assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image->signature == MagickCoreSignature); if (texture == (const Image *) NULL) return(MagickFalse); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); texture_image=CloneImage(texture,0,0,MagickTrue,exception); if (texture_image == (const Image *) NULL) return(MagickFalse); (void) TransformImageColorspace(texture_image,image->colorspace,exception); (void) SetImageVirtualPixelMethod(texture_image,TileVirtualPixelMethod, exception); status=MagickTrue; if ((image->compose != CopyCompositeOp) && ((image->compose != OverCompositeOp) || (image->alpha_trait != UndefinedPixelTrait) || (texture_image->alpha_trait != UndefinedPixelTrait))) { /* Tile texture onto the image background. */ for (y=0; y < (ssize_t) image->rows; y+=(ssize_t) texture_image->rows) { register ssize_t x; if (status == MagickFalse) continue; for (x=0; x < (ssize_t) image->columns; x+=(ssize_t) texture_image->columns) { MagickBooleanType thread_status; thread_status=CompositeImage(image,texture_image,image->compose, MagickTrue,x+texture_image->tile_offset.x,y+ texture_image->tile_offset.y,exception); if (thread_status == MagickFalse) { status=thread_status; break; } } if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,TextureImageTag,(MagickOffsetType) y, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } (void) SetImageProgress(image,TextureImageTag,(MagickOffsetType) image->rows,image->rows); texture_image=DestroyImage(texture_image); return(status); } /* Tile texture onto the image background (optimized). */ status=MagickTrue; texture_view=AcquireVirtualCacheView(texture_image,exception); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(texture_image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { MagickBooleanType sync; register const Quantum *p, *pixels; register ssize_t x; register Quantum *q; size_t width; if (status == MagickFalse) continue; pixels=GetCacheViewVirtualPixels(texture_view,texture_image->tile_offset.x, (y+texture_image->tile_offset.y) % texture_image->rows, texture_image->columns,1,exception); q=QueueCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if ((pixels == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x+=(ssize_t) texture_image->columns) { register ssize_t j; p=pixels; width=texture_image->columns; if ((x+(ssize_t) width) > (ssize_t) image->columns) width=image->columns-x; for (j=0; j < (ssize_t) width; j++) { register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(texture_image); i++) { PixelChannel channel = GetPixelChannelChannel(texture_image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait texture_traits=GetPixelChannelTraits(texture_image, channel); if ((traits == UndefinedPixelTrait) || (texture_traits == UndefinedPixelTrait)) continue; SetPixelChannel(image,channel,p[i],q); } p+=GetPixelChannels(texture_image); q+=GetPixelChannels(image); } } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,TextureImageTag,(MagickOffsetType) y, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } texture_view=DestroyCacheView(texture_view); image_view=DestroyCacheView(image_view); texture_image=DestroyImage(texture_image); return(status); }
for-15.c
/* { dg-do compile } */ /* { dg-options "-fopenmp" } */ void foo() { long n = 10; int i; #pragma omp for for (i=0; i < n; ++i) ; #pragma omp for for (i=0; n > i; ++i) ; }
tutorial_region_prof.c
/* * Copyright (c) 2015 - 2021, Intel Corporation * * 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 Intel Corporation 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 LOG OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <stdlib.h> #include <stdio.h> #include <time.h> #include <math.h> #include <stdint.h> #include <mpi.h> #ifdef _OPENMP #include <omp.h> #endif #include <geopm.h> #include "tutorial_region.h" #ifdef _OPENMP static int stream_profiled_omp(uint64_t region_id, size_t num_stream, double scalar, double *a, double *b, double *c) { const size_t block = 256; const size_t num_block = num_stream / block; const size_t num_remain = num_stream % block; int err = 0; #pragma omp parallel for for (size_t i = 0; i < num_block; ++i) { for (size_t j = 0; j < block; ++j) { a[i * block + j] = b[i * block + j] + scalar * c[i * block + j]; } geopm_tprof_post(); } #pragma omp parallel for for (size_t j = 0; j < num_remain; ++j) { a[num_block * block + j] = b[num_block * block + j] + scalar * c[num_block * block + j]; } return err; } #endif static int stream_profiled_serial(uint64_t region_id, size_t num_stream, double scalar, double *a, double *b, double *c) { const size_t block = 256; const size_t num_block = num_stream / block; const size_t num_remain = num_stream % block; geopm_tprof_init(num_block); for (size_t i = 0; i < num_block; ++i) { for (size_t j = 0; j < block; ++j) { a[i * block + j] = b[i * block + j] + scalar * c[i * block + j]; } geopm_tprof_post(); } for (size_t j = 0; j < num_remain; ++j) { a[num_block * block + j] = b[num_block * block + j] + scalar * c[num_block * block + j]; } return 0; } int tutorial_stream_profiled(double big_o, int do_report) { int err = 0; if (big_o != 0.0) { size_t cline_size = 64; size_t num_stream = (size_t)big_o * 500000000; size_t mem_size = sizeof(double) * num_stream; double *a = NULL; double *b = NULL; double *c = NULL; double scalar = 3.0; uint64_t stream_rid; if (!err) { err = geopm_prof_region("tutorial_stream", GEOPM_REGION_HINT_MEMORY, &stream_rid); } err = posix_memalign((void *)&a, cline_size, mem_size); if (!err) { err = posix_memalign((void *)&b, cline_size, mem_size); } if (!err) { err = posix_memalign((void *)&c, cline_size, mem_size); } if (!err) { #pragma omp parallel for for (int i = 0; i < num_stream; i++) { a[i] = 0.0; b[i] = 1.0; c[i] = 2.0; } if (do_report) { printf("Executing profiled STREAM triad on length %d vectors.\n", num_stream); fflush(stdout); } err = geopm_prof_enter(stream_rid); } if (!err) { #ifdef _OPENMP err = stream_profiled_omp(stream_rid, num_stream, scalar, a, b, c); #else err = stream_profiled_serial(stream_rid, num_stream, scalar, a, b, c); #endif } if (!err) { err = geopm_prof_exit(stream_rid); } if (!err) { free(c); free(b); free(a); } } }
residualbased_newton_raphson_contact_strategy.h
// KRATOS ______ __ __ _____ __ __ __ // / ____/___ ____ / /_____ ______/ /_/ ___// /________ _______/ /___ ___________ _/ / // / / / __ \/ __ \/ __/ __ `/ ___/ __/\__ \/ __/ ___/ / / / ___/ __/ / / / ___/ __ `/ / // / /___/ /_/ / / / / /_/ /_/ / /__/ /_ ___/ / /_/ / / /_/ / /__/ /_/ /_/ / / / /_/ / / // \____/\____/_/ /_/\__/\__,_/\___/\__//____/\__/_/ \__,_/\___/\__/\__,_/_/ \__,_/_/ MECHANICS // // License: BSD License // license: ContactStructuralMechanicsApplication/license.txt // // Main authors: Vicente Mataix Ferrandiz // #if !defined(KRATOS_RESIDUALBASED_NEWTON_RAPHSON_CONTACT_STRATEGY) #define KRATOS_RESIDUALBASED_NEWTON_RAPHSON_CONTACT_STRATEGY /* System Includes */ /* External Includes */ /* Project includes */ #include "contact_structural_mechanics_application_variables.h" #include "includes/kratos_parameters.h" #include "includes/define.h" #include "includes/model_part.h" #include "includes/variables.h" // Strategies #include "solving_strategies/strategies/residualbased_newton_raphson_strategy.h" // Utilities #include "utilities/variable_utils.h" #include "utilities/color_utilities.h" #include "utilities/math_utils.h" #include "custom_python/process_factory_utility.h" #include "custom_utilities/contact_utilities.h" namespace Kratos { ///@name Kratos Globals ///@{ ///@} ///@name Type Definitions ///@{ ///@} ///@name Enum's ///@{ ///@} ///@name Functions ///@{ ///@} ///@name Kratos Classes ///@{ /** * @class ResidualBasedNewtonRaphsonContactStrategy * @ingroup ContactStructuralMechanicsApplication * @brief Contact Newton Raphson class * @details This class is a specialization of the Newton Raphson strategy with some custom modifications for contact problems * @author Vicente Mataix Ferrandiz */ template<class TSparseSpace, class TDenseSpace, // = DenseSpace<double>, class TLinearSolver //= LinearSolver<TSparseSpace,TDenseSpace> > class ResidualBasedNewtonRaphsonContactStrategy : public ResidualBasedNewtonRaphsonStrategy< TSparseSpace, TDenseSpace, TLinearSolver > { public: ///@name Type Definitions ///@{ /** Counted pointer of ClassName */ KRATOS_CLASS_POINTER_DEFINITION( ResidualBasedNewtonRaphsonContactStrategy ); typedef SolvingStrategy<TSparseSpace, TDenseSpace> SolvingStrategyType; typedef ImplicitSolvingStrategy<TSparseSpace, TDenseSpace, TLinearSolver> StrategyBaseType; typedef ResidualBasedNewtonRaphsonStrategy<TSparseSpace, TDenseSpace, TLinearSolver> BaseType; typedef ResidualBasedNewtonRaphsonContactStrategy<TSparseSpace, TDenseSpace, TLinearSolver> ClassType; typedef ConvergenceCriteria<TSparseSpace, TDenseSpace> TConvergenceCriteriaType; typedef typename BaseType::TBuilderAndSolverType TBuilderAndSolverType; typedef typename BaseType::TDataType TDataType; typedef TSparseSpace SparseSpaceType; typedef typename BaseType::TSchemeType TSchemeType; typedef typename BaseType::DofsArrayType DofsArrayType; typedef typename BaseType::TSystemMatrixType TSystemMatrixType; typedef typename BaseType::TSystemVectorType TSystemVectorType; typedef typename BaseType::LocalSystemVectorType LocalSystemVectorType; typedef typename BaseType::LocalSystemMatrixType LocalSystemMatrixType; typedef typename BaseType::TSystemMatrixPointerType TSystemMatrixPointerType; typedef typename BaseType::TSystemVectorPointerType TSystemVectorPointerType; typedef ModelPart::NodesContainerType NodesArrayType; typedef ModelPart::ElementsContainerType ElementsArrayType; typedef ModelPart::ConditionsContainerType ConditionsArrayType; typedef ProcessFactoryUtility::Pointer ProcessesListType; typedef std::size_t IndexType; /** * @brief Default constructor */ explicit ResidualBasedNewtonRaphsonContactStrategy() { } /** * @brief Default constructor. (with parameters) * @param rModelPart The model part of the problem * @param ThisParameters The configuration parameters */ explicit ResidualBasedNewtonRaphsonContactStrategy(ModelPart& rModelPart, Parameters ThisParameters) : BaseType(rModelPart), mpMyProcesses(nullptr), mpPostProcesses(nullptr) { // Validate and assign defaults ThisParameters = this->ValidateAndAssignParameters(ThisParameters, this->GetDefaultParameters()); this->AssignSettings(ThisParameters); // Auxiliar assign mConvergenceCriteriaEchoLevel = BaseType::mpConvergenceCriteria->GetEchoLevel(); } /** * @brief Default constructor * @param rModelPart The model part of the problem * @param pScheme The integration scheme * @param pNewConvergenceCriteria The convergence criteria employed * @param MaxIterations The maximum number of iterations * @param CalculateReactions The flag for the reaction calculation * @param ReformDofSetAtEachStep The flag that allows to compute the modification of the DOF * @param MoveMeshFlag The flag that allows to move the mesh */ ResidualBasedNewtonRaphsonContactStrategy( ModelPart& rModelPart, typename TSchemeType::Pointer pScheme, typename TConvergenceCriteriaType::Pointer pNewConvergenceCriteria, typename TBuilderAndSolverType::Pointer pNewBuilderAndSolver, IndexType MaxIterations = 30, bool CalculateReactions = false, bool ReformDofSetAtEachStep = false, bool MoveMeshFlag = false, Parameters ThisParameters = Parameters(R"({})"), ProcessesListType pMyProcesses = nullptr, ProcessesListType pPostProcesses = nullptr ) : BaseType(rModelPart, pScheme, pNewConvergenceCriteria, pNewBuilderAndSolver, MaxIterations, CalculateReactions, ReformDofSetAtEachStep, MoveMeshFlag ), mThisParameters(ThisParameters), mpMyProcesses(pMyProcesses), mpPostProcesses(pPostProcesses) { KRATOS_TRY; mConvergenceCriteriaEchoLevel = pNewConvergenceCriteria->GetEchoLevel(); Parameters default_parameters = GetDefaultParameters(); mThisParameters.ValidateAndAssignDefaults(default_parameters); KRATOS_CATCH(""); } /** * @brief Default constructor * @param rModelPart The model part of the problem * @param pScheme The integration scheme * @param pNewLinearSolver The linear solver employed * @param pNewConvergenceCriteria The convergence criteria employed * @param MaxIterations The maximum number of iterations * @param CalculateReactions The flag for the reaction calculation * @param ReformDofSetAtEachStep The flag that allows to compute the modification of the DOF * @param MoveMeshFlag The flag that allows to move the mesh */ ResidualBasedNewtonRaphsonContactStrategy( ModelPart& rModelPart, typename TSchemeType::Pointer pScheme, typename TLinearSolver::Pointer pNewLinearSolver, typename TConvergenceCriteriaType::Pointer pNewConvergenceCriteria, IndexType MaxIterations = 30, bool CalculateReactions = false, bool ReformDofSetAtEachStep = false, bool MoveMeshFlag = false, Parameters ThisParameters = Parameters(R"({})"), ProcessesListType pMyProcesses = nullptr, ProcessesListType pPostProcesses = nullptr ) : BaseType(rModelPart, pScheme, pNewLinearSolver, pNewConvergenceCriteria, MaxIterations, CalculateReactions, ReformDofSetAtEachStep, MoveMeshFlag), mThisParameters(ThisParameters), mpMyProcesses(pMyProcesses), mpPostProcesses(pPostProcesses) { KRATOS_TRY; mConvergenceCriteriaEchoLevel = pNewConvergenceCriteria->GetEchoLevel(); Parameters default_parameters = GetDefaultParameters(); mThisParameters.ValidateAndAssignDefaults(default_parameters); KRATOS_CATCH(""); } /** * @brief Default constructor * @param rModelPart The model part of the problem * @param pScheme The integration scheme * @param pNewLinearSolver The linear solver employed * @param pNewConvergenceCriteria The convergence criteria employed * @param MaxIterations The maximum number of iterations * @param CalculateReactions The flag for the reaction calculation * @param ReformDofSetAtEachStep The flag that allows to compute the modification of the DOF * @param MoveMeshFlag The flag that allows to move the mesh */ ResidualBasedNewtonRaphsonContactStrategy( ModelPart& rModelPart, typename TSchemeType::Pointer pScheme, typename TLinearSolver::Pointer pNewLinearSolver, typename TConvergenceCriteriaType::Pointer pNewConvergenceCriteria, typename TBuilderAndSolverType::Pointer pNewBuilderAndSolver, IndexType MaxIterations = 30, bool CalculateReactions = false, bool ReformDofSetAtEachStep = false, bool MoveMeshFlag = false, Parameters ThisParameters = Parameters(R"({})"), ProcessesListType pMyProcesses = nullptr, ProcessesListType pPostProcesses = nullptr ) : ResidualBasedNewtonRaphsonStrategy<TSparseSpace, TDenseSpace, TLinearSolver>(rModelPart, pScheme, pNewLinearSolver, pNewConvergenceCriteria, pNewBuilderAndSolver, MaxIterations, CalculateReactions, ReformDofSetAtEachStep, MoveMeshFlag ), mThisParameters(ThisParameters), mpMyProcesses(pMyProcesses), mpPostProcesses(pPostProcesses) { KRATOS_TRY; mConvergenceCriteriaEchoLevel = pNewConvergenceCriteria->GetEchoLevel(); Parameters default_parameters = GetDefaultParameters(); mThisParameters.ValidateAndAssignDefaults(default_parameters); KRATOS_CATCH(""); } /** * Destructor. */ ~ResidualBasedNewtonRaphsonContactStrategy() override = default; ///@} ///@name Operators ///@{ ///@} ///@name Operations ///@{ /** * @brief Create method * @param rModelPart The model part of the problem * @param ThisParameters The configuration parameters */ typename SolvingStrategyType::Pointer Create( ModelPart& rModelPart, Parameters ThisParameters ) const override { return Kratos::make_shared<ClassType>(rModelPart, ThisParameters); } /** * @brief Operation to predict the solution ... if it is not called a trivial predictor is used in which the * values of the solution step of interest are assumed equal to the old values */ void Predict() override { KRATOS_TRY // Auxiliar zero array const array_1d<double, 3> zero_array = ZeroVector(3); // Set to zero the weighted gap ModelPart& r_model_part = StrategyBaseType::GetModelPart(); NodesArrayType& nodes_array = r_model_part.GetSubModelPart("Contact").Nodes(); const bool frictional = r_model_part.Is(SLIP); // We predict contact pressure in case of contact problem if (nodes_array.begin()->SolutionStepsDataHas(WEIGHTED_GAP)) { VariableUtils().SetVariable(WEIGHTED_GAP, 0.0, nodes_array); if (frictional) { VariableUtils().SetVariable(WEIGHTED_SLIP, zero_array, nodes_array); } // Compute the current gap ContactUtilities::ComputeExplicitContributionConditions(r_model_part.GetSubModelPart("ComputingContact")); // We predict a contact pressure ProcessInfo& r_process_info = r_model_part.GetProcessInfo(); const std::size_t step = r_process_info[STEP]; if (step == 1) { #pragma omp parallel for for(int i = 0; i < static_cast<int>(nodes_array.size()); ++i) { auto it_node = nodes_array.begin() + i; noalias(it_node->Coordinates()) += it_node->FastGetSolutionStepValue(DISPLACEMENT); } } else { #pragma omp parallel for for(int i = 0; i < static_cast<int>(nodes_array.size()); ++i) { auto it_node = nodes_array.begin() + i; noalias(it_node->Coordinates()) += (it_node->FastGetSolutionStepValue(DISPLACEMENT) - it_node->FastGetSolutionStepValue(DISPLACEMENT, 1)); } } } // BaseType::Predict(); // NOTE: May cause problems in dynamics!!! // // // Set to zero the weighted gap // NOTE: This can be done during the search if the predict is deactivated // ModelPart& r_model_part = StrategyBaseType::GetModelPart(); // NodesArrayType& nodes_array = r_model_part.GetSubModelPart("Contact").Nodes(); // // // We predict contact pressure in case of contact problem // if (nodes_array.begin()->SolutionStepsDataHas(WEIGHTED_GAP)) { // VariableUtils().SetVariable(WEIGHTED_GAP, 0.0, nodes_array); // // // Compute the current gap // ContactUtilities::ComputeExplicitContributionConditions(r_model_part.GetSubModelPart("ComputingContact")); // // // We predict a contact pressure // ProcessInfo& r_process_info = r_model_part.GetProcessInfo(); // const double initial_penalty_parameter = r_process_info[INITIAL_PENALTY]; // // // We iterate over the nodes // bool is_components = nodes_array.begin()->SolutionStepsDataHas(LAGRANGE_MULTIPLIER_CONTACT_PRESSURE) ? false : true; // // #pragma omp parallel for // for(int i = 0; i < static_cast<int>(nodes_array.size()); ++i) { // auto it_node = nodes_array.begin() + i; // // const double current_gap = it_node->FastGetSolutionStepValue(WEIGHTED_GAP); // // const double penalty = it_node->Has(INITIAL_PENALTY) ? it_node->GetValue(INITIAL_PENALTY) : initial_penalty_parameter; // // if (current_gap < 0.0) { // it_node->Set(ACTIVE, true); // if (is_components) { // it_node->FastGetSolutionStepValue(LAGRANGE_MULTIPLIER_CONTACT_PRESSURE) = penalty * current_gap; // } else { // const array_1d<double, 3>& normal = it_node->FastGetSolutionStepValue(NORMAL); // it_node->FastGetSolutionStepValue(VECTOR_LAGRANGE_MULTIPLIER) = penalty * current_gap * normal; // } // } // } // } KRATOS_CATCH("") } /** * @brief Initialization of member variables and prior operations */ void Initialize() override { KRATOS_TRY; BaseType::Initialize(); mFinalizeWasPerformed = false; // Initializing NL_ITERATION_NUMBER ModelPart& r_model_part = StrategyBaseType::GetModelPart(); ProcessInfo& r_process_info = r_model_part.GetProcessInfo(); r_process_info[NL_ITERATION_NUMBER] = 1; KRATOS_CATCH(""); } /** * @brief The problem of interest is solved. * @details This function calls sequentially: Initialize(), InitializeSolutionStep(), Predict(), * SolveSolutionStep() and FinalizeSolutionStep(). * All those functions can otherwise be called separately. */ double Solve() override { this->Initialize(); this->InitializeSolutionStep(); this->Predict(); this->SolveSolutionStep(); this->FinalizeSolutionStep(); // TODO: Add something if necessary return 0.0; } /** * @brief Performs all the required operations that should be done (for each step) * before solving the solution step. * @details A member variable should be used as a flag to make sure this function is called only once per step. */ void InitializeSolutionStep() override { BaseType::mpConvergenceCriteria->SetEchoLevel(0); BaseType::InitializeSolutionStep(); BaseType::mpConvergenceCriteria->SetEchoLevel(mConvergenceCriteriaEchoLevel); mFinalizeWasPerformed = false; } /** * @brief Performs all the required operations that should be done (for each step) * after solving the solution step. */ void FinalizeSolutionStep() override { KRATOS_TRY; if (mFinalizeWasPerformed == false) { BaseType::FinalizeSolutionStep(); // To avoid compute twice the FinalizeSolutionStep mFinalizeWasPerformed = true; } KRATOS_CATCH(""); } /** * @brief Solves the current step. * @details This function returns true if a solution has been found, false otherwise. */ bool SolveSolutionStep() override { KRATOS_TRY; // bool is_converged = BaseType::SolveSolutionStep(); // FIXME: Requires to separate the non linear iterations // bool is_converged = BaseSolveSolutionStep(); // Direct solution bool is_converged = false; // Getting model part ModelPart& r_model_part = StrategyBaseType::GetModelPart(); if (r_model_part.IsNot(INTERACTION)) { // We get the system TSystemMatrixType& A = *BaseType::mpA; TSystemVectorType& Dx = *BaseType::mpDx; TSystemVectorType& b = *BaseType::mpb; // We get the process info ProcessInfo& r_process_info = r_model_part.GetProcessInfo(); int inner_iteration = 0; while (!is_converged && inner_iteration < mThisParameters["inner_loop_iterations"].GetInt()) { ++inner_iteration; if (mConvergenceCriteriaEchoLevel > 0 && StrategyBaseType::GetModelPart().GetCommunicator().MyPID() == 0 ) { std::cout << std::endl << BOLDFONT("Simplified semi-smooth strategy. INNER ITERATION: ") << inner_iteration;; } // We solve one loop r_process_info[NL_ITERATION_NUMBER] = 1; r_process_info[INNER_LOOP_ITERATION] = inner_iteration; is_converged = BaseSolveSolutionStep(); // We check the convergence BaseType::mpConvergenceCriteria->SetEchoLevel(0); is_converged = BaseType::mpConvergenceCriteria->PostCriteria(r_model_part, BaseType::GetBuilderAndSolver()->GetDofSet(), A, Dx, b); BaseType::mpConvergenceCriteria->SetEchoLevel(mConvergenceCriteriaEchoLevel); if (mConvergenceCriteriaEchoLevel > 0 && StrategyBaseType::GetModelPart().GetCommunicator().MyPID() == 0 ) { if (is_converged) std::cout << BOLDFONT("Simplified semi-smooth strategy. INNER ITERATION: ") << BOLDFONT(FGRN("CONVERGED")) << std::endl; else std::cout << BOLDFONT("Simplified semi-smooth strategy. INNER ITERATION: ") << BOLDFONT(FRED("NOT CONVERGED")) << std::endl; } } } else { // We compute the base loop r_model_part.GetProcessInfo()[INNER_LOOP_ITERATION] = 1; is_converged = BaseSolveSolutionStep(); } if (mThisParameters["adaptative_strategy"].GetBool()) { if (!is_converged) { is_converged = AdaptativeStep(); } } return is_converged; KRATOS_CATCH(""); } /** * @brief This method returns the defaulr parameters in order to avoid code duplication * @return Returns the default parameters */ Parameters GetDefaultParameters() const override { Parameters default_parameters = Parameters(R"( { "name" : "newton_raphson_contact_strategy", "adaptative_strategy" : false, "split_factor" : 10.0, "max_number_splits" : 3, "inner_loop_iterations" : 5 })" ); // Getting base class default parameters const Parameters base_default_parameters = BaseType::GetDefaultParameters(); default_parameters.RecursivelyAddMissingParameters(base_default_parameters); return default_parameters; } /** * @brief Returns the name of the class as used in the settings (snake_case format) * @return The name of the class */ static std::string Name() { return "newton_raphson_contact_strategy"; } ///@} ///@name Access ///@{ ///@} ///@name Inquiry ///@{ ///@} ///@name Input and output ///@{ ///@} ///@name Friends ///@{ protected: ///@name Protected static Member Variables ///@{ ///@} ///@name Protected member Variables ///@{ Parameters mThisParameters; /// The configuration parameters // ADAPTATIVE STRATEGY PARAMETERS bool mFinalizeWasPerformed; /// If the FinalizeSolutionStep has been already permformed ProcessesListType mpMyProcesses; /// The processes list ProcessesListType mpPostProcesses; /// The post processes list // OTHER PARAMETERS int mConvergenceCriteriaEchoLevel; /// The echo level of the convergence criteria ///@} ///@name Protected Operators ///@{ ///@} ///@name Protected Operations ///@{ /** * @brief This method assigns settings to member variables * @param ThisParameters Parameters that are assigned to the member variables */ void AssignSettings(const Parameters ThisParameters) override { BaseType::AssignSettings(ThisParameters); // Copy the parameters mThisParameters = ThisParameters; } /** * @brief Solves the current step. * @details This function returns true if a solution has been found, false otherwise. */ bool BaseSolveSolutionStep() { KRATOS_TRY; // Pointers needed in the solution ModelPart& r_model_part = StrategyBaseType::GetModelPart(); ProcessInfo& r_process_info = r_model_part.GetProcessInfo(); typename TSchemeType::Pointer p_scheme = BaseType::GetScheme(); typename TBuilderAndSolverType::Pointer p_builder_and_solver = BaseType::GetBuilderAndSolver(); auto& r_dof_set = p_builder_and_solver->GetDofSet(); TSystemMatrixType& rA = *BaseType::mpA; TSystemVectorType& rDx = *BaseType::mpDx; TSystemVectorType& rb = *BaseType::mpb; // Initializing the parameters of the Newton-Raphson cicle IndexType iteration_number = 1; r_process_info[NL_ITERATION_NUMBER] = iteration_number; bool is_converged = false; bool residual_is_updated = false; p_scheme->InitializeNonLinIteration(r_model_part, rA, rDx, rb); BaseType::mpConvergenceCriteria->InitializeNonLinearIteration(r_model_part, r_dof_set, rA, rDx, rb); is_converged = BaseType::mpConvergenceCriteria->PreCriteria(r_model_part, r_dof_set, rA, rDx, rb); // We do a geometry check before solve the system for first time if (mThisParameters["adaptative_strategy"].GetBool()) { if (CheckGeometryInverted()) { KRATOS_WARNING("Element inverted") << "INVERTED ELEMENT BEFORE FIRST SOLVE" << std::endl; r_process_info[STEP] -= 1; // We revert one step in the case that the geometry is already broken before start the computing return false; } } // Function to perform the building and the solving phase. if (StrategyBaseType::mRebuildLevel > 1 || StrategyBaseType::mStiffnessMatrixIsBuilt == false) { TSparseSpace::SetToZero(rA); TSparseSpace::SetToZero(rDx); TSparseSpace::SetToZero(rb); p_builder_and_solver->BuildAndSolve(p_scheme, r_model_part, rA, rDx, rb); } else { TSparseSpace::SetToZero(rDx); //Dx=0.00; TSparseSpace::SetToZero(rb); p_builder_and_solver->BuildRHSAndSolve(p_scheme, r_model_part, rA, rDx, rb); } // Debugging info BaseType::EchoInfo(iteration_number); // Updating the results stored in the database UpdateDatabase(rA, rDx, rb, StrategyBaseType::MoveMeshFlag()); // We now check the geometry if (mThisParameters["adaptative_strategy"].GetBool()) { if (CheckGeometryInverted()) { KRATOS_WARNING("Element inverted") << "INVERTED ELEMENT DURING DATABASE UPDATE" << std::endl; r_process_info[STEP] -= 1; // We revert one step in the case that the geometry is already broken before start the computing return false; } } p_scheme->FinalizeNonLinIteration(r_model_part, rA, rDx, rb); BaseType::mpConvergenceCriteria->FinalizeNonLinearIteration(r_model_part, r_dof_set, rA, rDx, rb); if (is_converged) { // Initialisation of the convergence criteria BaseType::mpConvergenceCriteria->InitializeSolutionStep(r_model_part, r_dof_set, rA, rDx, rb); if (BaseType::mpConvergenceCriteria->GetActualizeRHSflag()) { TSparseSpace::SetToZero(rb); p_builder_and_solver->BuildRHS(p_scheme, r_model_part, rb); } is_converged = BaseType::mpConvergenceCriteria->PostCriteria(r_model_part, r_dof_set, rA, rDx, rb); } // Iteration Cicle... performed only for NonLinearProblems while (is_converged == false && iteration_number++<BaseType::mMaxIterationNumber) { //setting the number of iteration r_process_info[NL_ITERATION_NUMBER] = iteration_number; p_scheme->InitializeNonLinIteration(r_model_part, rA, rDx, rb); BaseType::mpConvergenceCriteria->InitializeNonLinearIteration(r_model_part, r_dof_set, rA, rDx, rb); is_converged = BaseType::mpConvergenceCriteria->PreCriteria(r_model_part, r_dof_set, rA, rDx, rb); //call the linear system solver to find the correction mDx for the //it is not called if there is no system to solve if (SparseSpaceType::Size(rDx) != 0) { if (StrategyBaseType::mRebuildLevel > 1 || StrategyBaseType::mStiffnessMatrixIsBuilt == false ) { if( BaseType::GetKeepSystemConstantDuringIterations() == false) { //A = 0.00; TSparseSpace::SetToZero(rA); TSparseSpace::SetToZero(rDx); TSparseSpace::SetToZero(rb); p_builder_and_solver->BuildAndSolve(p_scheme, r_model_part, rA, rDx, rb); } else { TSparseSpace::SetToZero(rDx); TSparseSpace::SetToZero(rb); p_builder_and_solver->BuildRHSAndSolve(p_scheme, r_model_part, rA, rDx, rb); } } else { TSparseSpace::SetToZero(rDx); TSparseSpace::SetToZero(rb); p_builder_and_solver->BuildRHSAndSolve(p_scheme, r_model_part, rA, rDx, rb); } } else { KRATOS_WARNING("No DoFs") << "ATTENTION: no free DOFs!! " << std::endl; } // Debugging info BaseType::EchoInfo(iteration_number); // Updating the results stored in the database UpdateDatabase(rA, rDx, rb, StrategyBaseType::MoveMeshFlag()); // We now check the geometry if (mThisParameters["adaptative_strategy"].GetBool()) { if (CheckGeometryInverted()) { KRATOS_WARNING("Element inverted") << "INVERTED ELEMENT DURING DATABASE UPDATE" << std::endl; r_process_info[STEP] -= 1; // We revert one step in the case that the geometry is already broken before start the computing return false; } } p_scheme->FinalizeNonLinIteration(r_model_part, rA, rDx, rb); BaseType::mpConvergenceCriteria->FinalizeNonLinearIteration(r_model_part, r_dof_set, rA, rDx, rb); residual_is_updated = false; if (is_converged) { if (BaseType::mpConvergenceCriteria->GetActualizeRHSflag()) { TSparseSpace::SetToZero(rb); p_builder_and_solver->BuildRHS(p_scheme, r_model_part, rb); residual_is_updated = true; //std::cout << "mb is calculated" << std::endl; } is_converged = BaseType::mpConvergenceCriteria->PostCriteria(r_model_part, r_dof_set, rA, rDx, rb); } } // Plots a warning if the maximum number of iterations is exceeded if (iteration_number >= BaseType::mMaxIterationNumber && r_model_part.GetCommunicator().MyPID() == 0) MaxIterationsExceeded(); // Recalculate residual if needed // (note that some convergence criteria need it to be recalculated) if (residual_is_updated == false) { // NOTE: // The following part will be commented because it is time consuming // and there is no obvious reason to be here. If someone need this // part please notify the community via mailing list before uncommenting it. // Pooyan. // TSparseSpace::SetToZero(mb); // p_builder_and_solver->BuildRHS(p_scheme, r_model_part, mb); } // Calculate reactions if required if (BaseType::mCalculateReactionsFlag) p_builder_and_solver->CalculateReactions(p_scheme, r_model_part, rA, rDx, rb); return is_converged; KRATOS_CATCH(""); } /** * @brief This method performs the adaptative step */ bool AdaptativeStep() { KRATOS_TRY; bool is_converged = false; // Plots a warning if the maximum number of iterations is exceeded if (mpMyProcesses == nullptr && StrategyBaseType::mEchoLevel > 0) KRATOS_WARNING("No python processes") << "If you have not implemented any method to recalculate BC or loads in function of time, this strategy will be USELESS" << std::endl; if (mpPostProcesses == nullptr && StrategyBaseType::mEchoLevel > 0) KRATOS_WARNING("No python post processes") << "If you don't add the postprocesses and the time step if splitted you won't postprocess that steps" << std::endl; ModelPart& r_model_part = StrategyBaseType::GetModelPart(); ProcessInfo& r_process_info = r_model_part.GetProcessInfo(); const double original_delta_time = r_process_info[DELTA_TIME]; // We save the delta time to restore later int split_number = 0; // We iterate until we reach the convergence or we split more than desired while (is_converged == false && split_number <= mThisParameters["max_number_splits"].GetInt()) { // Expliting time step as a way to try improve the convergence split_number += 1; double aux_delta_time, current_time; const double aux_time = SplitTimeStep(aux_delta_time, current_time); current_time += aux_delta_time; bool inside_the_split_is_converged = false; IndexType inner_iteration = 0; while (current_time <= aux_time) { inner_iteration += 1; r_process_info[STEP] += 1; if (inner_iteration == 1) { if (StrategyBaseType::MoveMeshFlag()) UnMoveMesh(); NodesArrayType& nodes_array = r_model_part.Nodes(); #pragma omp parallel for for(int i = 0; i < static_cast<int>(nodes_array.size()); ++i) { auto it_node = nodes_array.begin() + i; it_node->OverwriteSolutionStepData(1, 0); // it_node->OverwriteSolutionStepData(2, 1); } r_process_info.SetCurrentTime(current_time); // Reduces the time step FinalizeSolutionStep(); } else { NodesArrayType& nodes_array = r_model_part.Nodes(); #pragma omp parallel for for(int i = 0; i < static_cast<int>(nodes_array.size()); ++i) (nodes_array.begin() + i)->CloneSolutionStepData(); r_process_info.CloneSolutionStepInfo(); r_process_info.ClearHistory(r_model_part.GetBufferSize()); r_process_info.SetAsTimeStepInfo(current_time); // Sets the new time step } // We execute the processes before the non-linear iteration if (mpMyProcesses != nullptr) mpMyProcesses->ExecuteInitializeSolutionStep(); if (mpPostProcesses != nullptr) mpPostProcesses->ExecuteInitializeSolutionStep(); // In order to initialize again everything BaseType::mInitializeWasPerformed = false; mFinalizeWasPerformed = false; // We repeat the solve with the new DELTA_TIME this->Initialize(); this->InitializeSolutionStep(); this->Predict(); inside_the_split_is_converged = BaseType::SolveSolutionStep(); this->FinalizeSolutionStep(); // We execute the processes after the non-linear iteration if (mpMyProcesses != nullptr) mpMyProcesses->ExecuteFinalizeSolutionStep(); if (mpPostProcesses != nullptr) mpPostProcesses->ExecuteFinalizeSolutionStep(); if (mpMyProcesses != nullptr) mpMyProcesses->ExecuteBeforeOutputStep(); if (mpPostProcesses != nullptr) mpPostProcesses->PrintOutput(); if (mpMyProcesses != nullptr) mpMyProcesses->ExecuteAfterOutputStep(); current_time += aux_delta_time; } if (inside_the_split_is_converged) is_converged = true; } // Plots a warning if the maximum number of iterations and splits are exceeded if (is_converged == false) MaxIterationsAndSplitsExceeded(); // Restoring original DELTA_TIME r_process_info[DELTA_TIME] = original_delta_time; return is_converged; KRATOS_CATCH(""); } /** * @brief Here the database is updated * @param A The LHS matrix * @param Dx The increment of solution after solving system * @param b The RHS vector * @param MoveMesh The flag that tells if the mesh should be moved */ void UpdateDatabase( TSystemMatrixType& A, TSystemVectorType& Dx, TSystemVectorType& b, const bool MoveMesh ) override { BaseType::UpdateDatabase(A,Dx,b,MoveMesh); // TODO: Add something if necessary } /** * @brief his method checks if there is no element inverted */ bool CheckGeometryInverted() { ModelPart& r_model_part = StrategyBaseType::GetModelPart(); ProcessInfo& r_process_info = r_model_part.GetProcessInfo(); bool inverted_element = false; ElementsArrayType& elements_array = r_model_part.Elements(); // NOT OMP for(int i = 0; i < static_cast<int>(elements_array.size()); ++i) { auto it_elem = elements_array.begin() + i; auto& geom = it_elem->GetGeometry(); if (geom.DeterminantOfJacobian(0) < 0.0) { if (mConvergenceCriteriaEchoLevel > 0) { KRATOS_WATCH(it_elem->Id()) KRATOS_WATCH(geom.DeterminantOfJacobian(0)) } return true; } // We check now the deformation gradient std::vector<Matrix> deformation_gradient_matrices; it_elem->CalculateOnIntegrationPoints( DEFORMATION_GRADIENT, deformation_gradient_matrices, r_process_info); for (IndexType i_gp = 0; i_gp < deformation_gradient_matrices.size(); ++i_gp) { const double det_f = MathUtils<double>::Det(deformation_gradient_matrices[i_gp]); if (det_f < 0.0) { if (mConvergenceCriteriaEchoLevel > 0) { KRATOS_WATCH(it_elem->Id()) KRATOS_WATCH(det_f) } return true; } } } return inverted_element; } /** * @brief Here the time step is splitted * @param AuxDeltaTime The new delta time to be considered * @param CurrentTime The current time * @return The destination time */ double SplitTimeStep( double& AuxDeltaTime, double& CurrentTime ) { KRATOS_TRY; const double aux_time = StrategyBaseType::GetModelPart().GetProcessInfo()[TIME]; AuxDeltaTime = StrategyBaseType::GetModelPart().GetProcessInfo()[DELTA_TIME]; CurrentTime = aux_time - AuxDeltaTime; StrategyBaseType::GetModelPart().GetProcessInfo()[TIME] = CurrentTime; // Restore time to the previous one AuxDeltaTime /= mThisParameters["split_factor"].GetDouble(); StrategyBaseType::GetModelPart().GetProcessInfo()[DELTA_TIME] = AuxDeltaTime; // Change delta time CoutSplittingTime(AuxDeltaTime, aux_time); return aux_time; KRATOS_CATCH(""); } /** * This method moves bak the mesh to the previous position */ void UnMoveMesh() { KRATOS_TRY; if (StrategyBaseType::GetModelPart().NodesBegin()->SolutionStepsDataHas(DISPLACEMENT_X) == false) KRATOS_ERROR << "It is impossible to move the mesh since the DISPLACEMENT var is not in the model_part. Either use SetMoveMeshFlag(False) or add DISPLACEMENT to the list of variables" << std::endl; NodesArrayType& nodes_array = StrategyBaseType::GetModelPart().Nodes(); #pragma omp parallel for for(int i = 0; i < static_cast<int>(nodes_array.size()); ++i) { auto it_node = nodes_array.begin() + i; noalias(it_node->Coordinates()) = it_node->GetInitialPosition().Coordinates(); noalias(it_node->Coordinates()) += it_node->FastGetSolutionStepValue(DISPLACEMENT, 1); } KRATOS_CATCH(""); } /** * @brief This method prints information after solving the problem */ void CoutSolvingProblem() { if (mConvergenceCriteriaEchoLevel != 0) { std::cout << "STEP: " << StrategyBaseType::GetModelPart().GetProcessInfo()[STEP] << "\t NON LINEAR ITERATION: " << StrategyBaseType::GetModelPart().GetProcessInfo()[NL_ITERATION_NUMBER] << "\t TIME: " << StrategyBaseType::GetModelPart().GetProcessInfo()[TIME] << "\t DELTA TIME: " << StrategyBaseType::GetModelPart().GetProcessInfo()[DELTA_TIME] << std::endl; } } /** * @brief This method prints information after split the increment of time * @param AuxDeltaTime The new time step to be considered * @param AuxTime The destination time */ void CoutSplittingTime( const double AuxDeltaTime, const double AuxTime ) { if (mConvergenceCriteriaEchoLevel > 0 && StrategyBaseType::GetModelPart().GetCommunicator().MyPID() == 0 ) { const double Time = StrategyBaseType::GetModelPart().GetProcessInfo()[TIME]; std::cout.precision(4); std::cout << "|----------------------------------------------------|" << std::endl; std::cout << "| " << BOLDFONT("SPLITTING TIME STEP") << " |" << std::endl; std::cout << "| " << BOLDFONT("COMING BACK TO TIME: ") << std::scientific << Time << " |" << std::endl; std::cout << "| " << BOLDFONT(" NEW TIME STEP: ") << std::scientific << AuxDeltaTime << " |" << std::endl; std::cout << "| " << BOLDFONT(" UNTIL TIME: ") << std::scientific << AuxTime << " |" << std::endl; std::cout << "|----------------------------------------------------|" << std::endl; } } /** * @brief This method prints information after reach the max number of interations */ void MaxIterationsExceeded() override { if (mConvergenceCriteriaEchoLevel > 0 && StrategyBaseType::GetModelPart().GetCommunicator().MyPID() == 0 ) { std::cout << "|----------------------------------------------------|" << std::endl; std::cout << "| " << BOLDFONT(FRED("ATTENTION: Max iterations exceeded")) << " |" << std::endl; std::cout << "|----------------------------------------------------|" << std::endl; } } /** * @brief This method prints information after reach the max number of interations and splits */ void MaxIterationsAndSplitsExceeded() { if (mConvergenceCriteriaEchoLevel > 0 && StrategyBaseType::GetModelPart().GetCommunicator().MyPID() == 0 ) { std::cout << "|----------------------------------------------------|" << std::endl; std::cout << "| " << BOLDFONT(FRED("ATTENTION: Max iterations exceeded")) << " |" << std::endl; std::cout << "| " << BOLDFONT(FRED(" Max number of splits exceeded ")) << " |" << std::endl; std::cout << "|----------------------------------------------------|" << std::endl; } } ///@} ///@name Protected Access ///@{ ///@} ///@name Protected Inquiry ///@{ ///@} ///@name Protected LifeCycle ///@{ ///@{ /** * Copy constructor. */ ResidualBasedNewtonRaphsonContactStrategy(const ResidualBasedNewtonRaphsonContactStrategy& Other) { }; private: ///@name Static Member Variables ///@{ ///@} ///@name Member Variables ///@{ ///@} ///@name Private Operators ///@{ ///@} ///@name Private Operations ///@{ ///@} ///@name Private Access ///@{ ///@} ///@} ///@name Serialization ///@{ ///@name Private Inquiry ///@{ ///@} ///@name Un accessible methods ///@{ ///@} }; /* Class ResidualBasedNewtonRaphsonContactStrategy */ ///@} ///@name Type Definitions ///@{ ///@} ///@name Input and output ///@{ ///@} } // namespace Kratos #endif /* KRATOS_RESIDUALBASED_NEWTON_RAPHSON_CONTACT_STRATEGY */
syncbench.c
/**************************************************************************** * * * OpenMP MicroBenchmark Suite - Version 3.1 * * * * produced by * * * * Mark Bull, Fiona Reid and Nix Mc Donnell * * * * at * * * * Edinburgh Parallel Computing Centre * * * * email: markb@epcc.ed.ac.uk or fiona@epcc.ed.ac.uk * * * * * * This version copyright (c) The University of Edinburgh, 2015. * * * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * * * ****************************************************************************/ #include "common.h" #include "syncbench.h" omp_lock_t lock; int syncbench_main(int argc, char **argv) { // Start Paraver tracing #ifdef PARAVERTRACE Extrae_init(); #endif ompbench_init(argc, argv); omp_init_lock(&lock); /* GENERATE REFERENCE TIME */ reference("reference time 1", &refer); /* TEST PARALLEL REGION */ benchmark("PARALLEL", &testpr); /* TEST FOR */ benchmark("FOR", &testfor); /* TEST PARALLEL FOR */ benchmark("PARALLEL FOR", &testpfor); /* TEST BARRIER */ benchmark("BARRIER", &testbar); /* TEST SINGLE */ benchmark("SINGLE", &testsing); /* TEST CRITICAL*/ benchmark("CRITICAL", &testcrit); /* TEST LOCK/UNLOCK */ benchmark("LOCK/UNLOCK", &testlock); /* TEST ORDERED SECTION */ benchmark("ORDERED", &testorder); /* GENERATE NEW REFERENCE TIME */ reference("reference time 2", &referatom); /* TEST ATOMIC */ benchmark("ATOMIC", &testatom); /* GENERATE NEW REFERENCE TIME */ reference("reference time 3", &referred); /* TEST REDUCTION (1 var) */ benchmark("REDUCTION", &testred); #ifdef PARAVERTRACE Extrae_fini(); #endif finalise(); return EXIT_SUCCESS; } static void refer() { int j; for (j = 0; j < innerreps; j++) { delay(delaylength); } } void referatom(){ int j; double aaaa = 0.0; double epsilon = 1.0e-15; double b, c; b = 1.0; c = (1.0 + epsilon); for (j = 0; j < innerreps; j++) { aaaa += b; b *= c; } if (aaaa < 0.0) printf("%f\n", aaaa); } void referred() { int j; int aaaa = 0; for (j = 0; j < innerreps; j++) { delay(delaylength); aaaa += 1; } } void testpr() { int j; for (j = 0; j < innerreps; j++) { #pragma omp parallel { delay(delaylength); } } } void testfor() { int i, j; #pragma omp parallel private(j) { for (j = 0; j < innerreps; j++) { #pragma omp for for (i = 0; i < nthreads; i++) { delay(delaylength); } } } } void testpfor() { int i, j; for (j = 0; j < innerreps; j++) { #pragma omp parallel for for (i = 0; i < nthreads; i++) { delay(delaylength); } } } void testbar() { int j; #pragma omp parallel private(j) { for (j = 0; j < innerreps; j++) { delay(delaylength); #pragma omp barrier } } } void testsing() { int j; #pragma omp parallel private(j) { for (j = 0; j < innerreps; j++) { #pragma omp single delay(delaylength); } } } void testcrit() { int j; #pragma omp parallel private(j) { for (j = 0; j < innerreps / nthreads; j++) { #pragma omp critical { delay(delaylength); } } } } void testlock() { int j; #pragma omp parallel private(j) { for (j = 0; j < innerreps / nthreads; j++) { omp_set_lock(&lock); delay(delaylength); omp_unset_lock(&lock); } } } void testorder() { int j; #pragma omp parallel for ordered schedule (static,1) for (j = 0; j < (int)innerreps; j++) { #pragma omp ordered delay(delaylength); } } void testatom() { int j; double aaaa = 0.0; double epsilon = 1.0e-15; double b,c; b = 1.0; c = (1.0 + epsilon); #pragma omp parallel private(j) firstprivate(b) { for (j = 0; j < innerreps / nthreads; j++) { #pragma omp atomic aaaa += b; b *= c; } } if (aaaa < 0.0) printf("%f\n", aaaa); } void testred() { int j; int aaaa = 0; for (j = 0; j < innerreps; j++) { #pragma omp parallel reduction(+:aaaa) { delay(delaylength); aaaa += 1; } } }
trmm_x_dia_u_hi_col.c
#include "alphasparse/kernel.h" #include "alphasparse/util.h" #include "alphasparse/opt.h" #ifdef _OPENMP #include <omp.h> #endif alphasparse_status_t ONAME(const ALPHA_Number alpha, const ALPHA_SPMAT_DIA *mat, const ALPHA_Number *x, const ALPHA_INT columns, const ALPHA_INT ldx, const ALPHA_Number beta, ALPHA_Number *y, const ALPHA_INT ldy) { ALPHA_INT num_threads = alpha_get_thread_num(); #ifdef _OPENMP #pragma omp parallel for num_threads(num_threads) #endif for(ALPHA_INT c = 0; c < columns; c++) for (ALPHA_INT r = 0; r < mat->rows; r++){ alpha_mul(y[index2(c,r,ldy)],y[index2(c,r,ldy)],beta); alpha_madde(y[index2(c,r,ldy)],x[index2(c,r,ldx)],alpha); } #ifdef _OPENMP #pragma omp parallel for num_threads(num_threads) #endif for (ALPHA_INT cc = 0; cc < columns; ++cc) { ALPHA_Number* Y = &y[index2(cc,0,ldy)]; const ALPHA_Number* X = &x[index2(cc,0,ldx)]; for(ALPHA_INT di = 0; di < mat->ndiag;++di){ ALPHA_INT d = mat->distance[di]; if(d > 0){ ALPHA_INT ars = alpha_max(0,-d); ALPHA_INT acs = alpha_max(0,d); ALPHA_INT an = alpha_min(mat->rows - ars,mat->cols - acs); for(ALPHA_INT i = 0; i < an; ++i){ ALPHA_INT ar = ars + i; ALPHA_INT ac = acs + i; ALPHA_Number val; alpha_mul(val,mat->values[index2(di,ar,mat->lval)],alpha); alpha_madde(Y[ar],val,X[ac]); } } } } return ALPHA_SPARSE_STATUS_SUCCESS; }
top_k_op.h
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #pragma once #include <algorithm> #include <iostream> #include <utility> #include <vector> #include "paddle/fluid/framework/eigen.h" #include "paddle/fluid/framework/op_registry.h" namespace paddle { namespace operators { using Tensor = framework::Tensor; template <typename T, int MajorType = Eigen::RowMajor, typename IndexType = Eigen::DenseIndex> using EigenMatrix = framework::EigenMatrix<T, MajorType, IndexType>; template <typename DeviceContext, typename T> class TopkKernel : public framework::OpKernel<T> { public: void Compute(const framework::ExecutionContext& ctx) const override { // Get the top k elements of each row of input tensor // FIXME: only deal with matrix(2d tensor). auto* input = ctx.Input<Tensor>("X"); auto* output = ctx.Output<Tensor>("Out"); auto* indices = ctx.Output<Tensor>("Indices"); // k is determined by Attr const size_t k = static_cast<int>(ctx.Attr<int>("k")); T* output_data = output->mutable_data<T>(ctx.GetPlace()); int64_t* indices_data = indices->mutable_data<int64_t>(ctx.GetPlace()); auto eg_input = EigenMatrix<T>::From(*input); // reshape input to a flattern matrix(like flat_inner_dims) framework::DDim inputdims = input->dims(); const size_t row = framework::product( framework::slice_ddim(inputdims, 0, inputdims.size() - 1)); const size_t col = inputdims[inputdims.size() - 1]; Eigen::DSizes<int, 2> flat2dims(row, col); // NOTE: eigen shape doesn't affect paddle tensor. eg_input.reshape(flat2dims); #ifdef PADDLE_WITH_MKLML #pragma omp parallel for #endif for (size_t i = 0; i < row; i++) { std::vector<std::pair<T, size_t>> vec; vec.reserve(col); for (size_t j = 0; j < col; j++) { vec.push_back(std::pair<T, size_t>(eg_input(i, j), j)); } std::partial_sort( vec.begin(), vec.begin() + k, vec.end(), [](const std::pair<T, size_t>& l, const std::pair<T, size_t>& r) { return l.first > r.first; }); for (size_t j = 0; j < k; j++) { output_data[i * k + j] = vec[j].first; indices_data[i * k + j] = int64_t(vec[j].second); } } } }; } // namespace operators } // namespace paddle
cache.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % CCCC AAA CCCC H H EEEEE % % C A A C H H E % % C AAAAA C HHHHH EEE % % C A A C H H E % % CCCC A A CCCC H H EEEEE % % % % % % MagickCore Pixel Cache Methods % % % % Software Design % % Cristy % % July 1999 % % % % % % Copyright 1999-2019 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 "magick/studio.h" #include "magick/blob.h" #include "magick/blob-private.h" #include "magick/cache.h" #include "magick/cache-private.h" #include "magick/color-private.h" #include "magick/colorspace.h" #include "magick/colorspace-private.h" #include "magick/composite-private.h" #include "magick/distribute-cache-private.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/geometry.h" #include "magick/list.h" #include "magick/log.h" #include "magick/magick.h" #include "magick/memory_.h" #include "magick/memory-private.h" #include "magick/nt-base-private.h" #include "magick/option.h" #include "magick/pixel.h" #include "magick/pixel-accessor.h" #include "magick/pixel-private.h" #include "magick/policy.h" #include "magick/quantum.h" #include "magick/random_.h" #include "magick/registry.h" #include "magick/resource_.h" #include "magick/semaphore.h" #include "magick/splay-tree.h" #include "magick/string_.h" #include "magick/string-private.h" #include "magick/thread-private.h" #include "magick/utility.h" #include "magick/utility-private.h" #if defined(MAGICKCORE_ZLIB_DELEGATE) #include "zlib.h" #endif /* Define declarations. */ #define CacheTick(offset,extent) QuantumTick((MagickOffsetType) offset,extent) #define IsFileDescriptorLimitExceeded() (GetMagickResource(FileResource) > \ GetMagickResourceLimit(FileResource) ? MagickTrue : MagickFalse) /* Typedef declarations. */ typedef struct _MagickModulo { ssize_t quotient, remainder; } MagickModulo; /* Forward declarations. */ #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif static Cache GetImagePixelCache(Image *,const MagickBooleanType,ExceptionInfo *) magick_hot_spot; static const IndexPacket *GetVirtualIndexesFromCache(const Image *); static const PixelPacket *GetVirtualPixelCache(const Image *,const VirtualPixelMethod,const ssize_t, const ssize_t,const size_t,const size_t,ExceptionInfo *), *GetVirtualPixelsCache(const Image *); static MagickBooleanType GetOneAuthenticPixelFromCache(Image *,const ssize_t,const ssize_t, PixelPacket *,ExceptionInfo *), GetOneVirtualPixelFromCache(const Image *,const VirtualPixelMethod, const ssize_t,const ssize_t,PixelPacket *,ExceptionInfo *), OpenPixelCache(Image *,const MapMode,ExceptionInfo *), OpenPixelCacheOnDisk(CacheInfo *,const MapMode), ReadPixelCacheIndexes(CacheInfo *magick_restrict,NexusInfo *magick_restrict, ExceptionInfo *), ReadPixelCachePixels(CacheInfo *magick_restrict,NexusInfo *magick_restrict, ExceptionInfo *), SyncAuthenticPixelsCache(Image *,ExceptionInfo *), WritePixelCacheIndexes(CacheInfo *,NexusInfo *magick_restrict, ExceptionInfo *), WritePixelCachePixels(CacheInfo *,NexusInfo *magick_restrict, ExceptionInfo *); static PixelPacket *GetAuthenticPixelsCache(Image *,const ssize_t,const ssize_t,const size_t, const size_t,ExceptionInfo *), *QueueAuthenticPixelsCache(Image *,const ssize_t,const ssize_t,const size_t, const size_t,ExceptionInfo *), *SetPixelCacheNexusPixels(const CacheInfo *,const MapMode, const RectangleInfo *,const MagickBooleanType,NexusInfo *,ExceptionInfo *) magick_hot_spot; #if defined(MAGICKCORE_OPENCL_SUPPORT) static void CopyOpenCLBuffer(CacheInfo *magick_restrict); #endif #if defined(__cplusplus) || defined(c_plusplus) } #endif /* Global declarations. */ static SemaphoreInfo *cache_semaphore = (SemaphoreInfo *) NULL; static ssize_t cache_anonymous_memory = (-1); static time_t cache_epoch = 0; #if defined(MAGICKCORE_OPENCL_SUPPORT) static inline OpenCLCacheInfo *RelinquishOpenCLCacheInfo(MagickCLEnv clEnv, OpenCLCacheInfo *info) { ssize_t i; for (i=0; i < (ssize_t) info->event_count; i++) clEnv->library->clReleaseEvent(info->events[i]); info->events=(cl_event *) RelinquishMagickMemory(info->events); DestroySemaphoreInfo(&info->events_semaphore); if (info->buffer != (cl_mem) NULL) { clEnv->library->clReleaseMemObject(info->buffer); info->buffer=(cl_mem) NULL; } return((OpenCLCacheInfo *) RelinquishMagickMemory(info)); } static void CL_API_CALL RelinquishPixelCachePixelsDelayed( cl_event magick_unused(event),cl_int magick_unused(event_command_exec_status), void *user_data) { MagickCLEnv clEnv; OpenCLCacheInfo *info; PixelPacket *pixels; ssize_t i; magick_unreferenced(event); magick_unreferenced(event_command_exec_status); info=(OpenCLCacheInfo *) user_data; clEnv=GetDefaultOpenCLEnv(); for (i=(ssize_t)info->event_count-1; i >= 0; i--) { cl_int event_status; cl_uint status; status=clEnv->library->clGetEventInfo(info->events[i], CL_EVENT_COMMAND_EXECUTION_STATUS,sizeof(cl_int),&event_status,NULL); if ((status == CL_SUCCESS) && (event_status > CL_COMPLETE)) { clEnv->library->clSetEventCallback(info->events[i],CL_COMPLETE, &RelinquishPixelCachePixelsDelayed,info); return; } } pixels=info->pixels; RelinquishMagickResource(MemoryResource,info->length); (void) RelinquishOpenCLCacheInfo(clEnv,info); (void) RelinquishAlignedMemory(pixels); } static MagickBooleanType RelinquishOpenCLBuffer( CacheInfo *magick_restrict cache_info) { MagickCLEnv clEnv; assert(cache_info != (CacheInfo *) NULL); if (cache_info->opencl == (OpenCLCacheInfo *) NULL) return(MagickFalse); RelinquishPixelCachePixelsDelayed((cl_event) NULL,0,cache_info->opencl); return(MagickTrue); } static cl_event *CopyOpenCLEvents(OpenCLCacheInfo *opencl_info, cl_uint *event_count) { cl_event *events; register size_t i; assert(opencl_info != (OpenCLCacheInfo *) NULL); events=(cl_event *) NULL; LockSemaphoreInfo(opencl_info->events_semaphore); *event_count=opencl_info->event_count; if (*event_count > 0) { events=AcquireQuantumMemory(*event_count,sizeof(*events)); if (events == (cl_event *) NULL) *event_count=0; else { for (i=0; i < opencl_info->event_count; i++) events[i]=opencl_info->events[i]; } } UnlockSemaphoreInfo(opencl_info->events_semaphore); return(events); } #endif #if defined(MAGICKCORE_OPENCL_SUPPORT) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + A d d O p e n C L E v e n t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AddOpenCLEvent() adds an event to the list of operations the next operation % should wait for. % % The format of the AddOpenCLEvent() method is: % % void AddOpenCLEvent(const Image *image,cl_event event) % % A description of each parameter follows: % % o image: the image. % % o event: the event that should be added. % */ extern MagickPrivate void AddOpenCLEvent(const Image *image,cl_event event) { CacheInfo *magick_restrict cache_info; MagickCLEnv clEnv; assert(image != (const Image *) NULL); assert(event != (cl_event) NULL); cache_info=(CacheInfo *)image->cache; assert(cache_info->opencl != (OpenCLCacheInfo *) NULL); clEnv=GetDefaultOpenCLEnv(); if (clEnv->library->clRetainEvent(event) != CL_SUCCESS) { clEnv->library->clWaitForEvents(1,&event); return; } LockSemaphoreInfo(cache_info->opencl->events_semaphore); if (cache_info->opencl->events == (cl_event *) NULL) { cache_info->opencl->events=AcquireMagickMemory(sizeof( *cache_info->opencl->events)); cache_info->opencl->event_count=1; } else cache_info->opencl->events=ResizeQuantumMemory(cache_info->opencl->events, ++cache_info->opencl->event_count,sizeof(*cache_info->opencl->events)); if (cache_info->opencl->events == (cl_event *) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); cache_info->opencl->events[cache_info->opencl->event_count-1]=event; UnlockSemaphoreInfo(cache_info->opencl->events_semaphore); } #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + A c q u i r e P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquirePixelCache() acquires a pixel cache. % % The format of the AcquirePixelCache() method is: % % Cache AcquirePixelCache(const size_t number_threads) % % A description of each parameter follows: % % o number_threads: the number of nexus threads. % */ MagickExport Cache AcquirePixelCache(const size_t number_threads) { CacheInfo *magick_restrict cache_info; char *value; cache_info=(CacheInfo *) AcquireCriticalMemory(sizeof(*cache_info)); (void) memset(cache_info,0,sizeof(*cache_info)); cache_info->type=UndefinedCache; cache_info->mode=IOMode; cache_info->disk_mode=IOMode; cache_info->colorspace=sRGBColorspace; cache_info->channels=4; cache_info->file=(-1); cache_info->id=GetMagickThreadId(); cache_info->number_threads=number_threads; if (GetOpenMPMaximumThreads() > cache_info->number_threads) cache_info->number_threads=GetOpenMPMaximumThreads(); if (GetMagickResourceLimit(ThreadResource) > cache_info->number_threads) cache_info->number_threads=(size_t) GetMagickResourceLimit(ThreadResource); if (cache_info->number_threads == 0) cache_info->number_threads=1; cache_info->nexus_info=AcquirePixelCacheNexus(cache_info->number_threads); value=GetEnvironmentValue("MAGICK_SYNCHRONIZE"); if (value != (const char *) NULL) { cache_info->synchronize=IsStringTrue(value); value=DestroyString(value); } value=GetPolicyValue("cache:synchronize"); if (value != (const char *) NULL) { cache_info->synchronize=IsStringTrue(value); value=DestroyString(value); } cache_info->semaphore=AllocateSemaphoreInfo(); cache_info->reference_count=1; cache_info->file_semaphore=AllocateSemaphoreInfo(); cache_info->debug=IsEventLogging(); cache_info->signature=MagickCoreSignature; return((Cache ) cache_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e P i x e l C a c h e N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquirePixelCacheNexus() allocates the NexusInfo structure. % % The format of the AcquirePixelCacheNexus method is: % % NexusInfo **AcquirePixelCacheNexus(const size_t number_threads) % % A description of each parameter follows: % % o number_threads: the number of nexus threads. % */ MagickExport NexusInfo **AcquirePixelCacheNexus(const size_t number_threads) { NexusInfo **magick_restrict nexus_info; register ssize_t i; nexus_info=(NexusInfo **) MagickAssumeAligned(AcquireAlignedMemory( number_threads,sizeof(*nexus_info))); if (nexus_info == (NexusInfo **) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); nexus_info[0]=(NexusInfo *) AcquireQuantumMemory(number_threads, sizeof(**nexus_info)); if (nexus_info[0] == (NexusInfo *) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); (void) memset(nexus_info[0],0,number_threads*sizeof(**nexus_info)); for (i=0; i < (ssize_t) number_threads; i++) { nexus_info[i]=(&nexus_info[0][i]); nexus_info[i]->signature=MagickCoreSignature; } return(nexus_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e P i x e l C a c h e P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquirePixelCachePixels() returns the pixels associated with the specified % image. % % The format of the AcquirePixelCachePixels() method is: % % const void *AcquirePixelCachePixels(const Image *image, % MagickSizeType *length,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o length: the pixel cache length. % % o exception: return any errors or warnings in this structure. % */ MagickExport const void *AcquirePixelCachePixels(const Image *image, MagickSizeType *length,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); (void) exception; *length=0; if ((cache_info->type != MemoryCache) && (cache_info->type != MapCache)) return((const void *) NULL); *length=cache_info->length; return((const void *) cache_info->pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C a c h e C o m p o n e n t G e n e s i s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CacheComponentGenesis() instantiates the cache component. % % The format of the CacheComponentGenesis method is: % % MagickBooleanType CacheComponentGenesis(void) % */ MagickExport MagickBooleanType CacheComponentGenesis(void) { if (cache_semaphore == (SemaphoreInfo *) NULL) cache_semaphore=AllocateSemaphoreInfo(); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C a c h e C o m p o n e n t T e r m i n u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CacheComponentTerminus() destroys the cache component. % % The format of the CacheComponentTerminus() method is: % % CacheComponentTerminus(void) % */ MagickExport void CacheComponentTerminus(void) { if (cache_semaphore == (SemaphoreInfo *) NULL) ActivateSemaphoreInfo(&cache_semaphore); /* no op-- nothing to destroy */ DestroySemaphoreInfo(&cache_semaphore); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C l i p P i x e l C a c h e N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ClipPixelCacheNexus() clips the cache nexus as defined by the image clip % mask. The method returns MagickTrue if the pixel region is clipped, % otherwise MagickFalse. % % The format of the ClipPixelCacheNexus() method is: % % MagickBooleanType ClipPixelCacheNexus(Image *image,NexusInfo *nexus_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o nexus_info: the cache nexus to clip. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType ClipPixelCacheNexus(Image *image, NexusInfo *nexus_info,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; MagickSizeType number_pixels; NexusInfo **magick_restrict clip_nexus, **magick_restrict image_nexus; register const PixelPacket *magick_restrict r; register IndexPacket *magick_restrict nexus_indexes, *magick_restrict indexes; register PixelPacket *magick_restrict p, *magick_restrict q; register ssize_t i; /* Apply clip mask. */ if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if ((image->clip_mask == (Image *) NULL) || (image->storage_class == PseudoClass)) return(MagickTrue); cache_info=(CacheInfo *) image->cache; if (cache_info == (Cache) NULL) return(MagickFalse); image_nexus=AcquirePixelCacheNexus(1); clip_nexus=AcquirePixelCacheNexus(1); p=GetAuthenticPixelCacheNexus(image,nexus_info->region.x,nexus_info->region.y, nexus_info->region.width,nexus_info->region.height,image_nexus[0], exception); indexes=image_nexus[0]->indexes; q=nexus_info->pixels; nexus_indexes=nexus_info->indexes; r=GetVirtualPixelCacheNexus(image->clip_mask,MaskVirtualPixelMethod, nexus_info->region.x,nexus_info->region.y,nexus_info->region.width, nexus_info->region.height,clip_nexus[0],exception); number_pixels=(MagickSizeType) nexus_info->region.width* nexus_info->region.height; for (i=0; i < (ssize_t) number_pixels; i++) { double mask_alpha; if ((p == (PixelPacket *) NULL) || (r == (const PixelPacket *) NULL)) break; mask_alpha=QuantumScale*GetPixelIntensity(image,r); if (fabs(mask_alpha) >= MagickEpsilon) { SetPixelRed(q,mask_alpha*MagickOver_((MagickRealType) p->red, (MagickRealType) GetPixelOpacity(p),(MagickRealType) q->red, (MagickRealType) GetPixelOpacity(q))); SetPixelGreen(q,mask_alpha*MagickOver_((MagickRealType) p->green, (MagickRealType) GetPixelOpacity(p),(MagickRealType) q->green, (MagickRealType) GetPixelOpacity(q))); SetPixelBlue(q,mask_alpha*MagickOver_((MagickRealType) p->blue, (MagickRealType) GetPixelOpacity(p),(MagickRealType) q->blue, (MagickRealType) GetPixelOpacity(q))); SetPixelOpacity(q,GetPixelOpacity(p)); if (cache_info->active_index_channel != MagickFalse) SetPixelIndex(nexus_indexes+i,GetPixelIndex(indexes+i)); } p++; q++; r++; } clip_nexus=DestroyPixelCacheNexus(clip_nexus,1); image_nexus=DestroyPixelCacheNexus(image_nexus,1); if (i < (ssize_t) number_pixels) return(MagickFalse); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C l o n e P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ClonePixelCache() clones a pixel cache. % % The format of the ClonePixelCache() method is: % % Cache ClonePixelCache(const Cache cache) % % A description of each parameter follows: % % o cache: the pixel cache. % */ MagickExport Cache ClonePixelCache(const Cache cache) { CacheInfo *magick_restrict clone_info; const CacheInfo *magick_restrict cache_info; assert(cache != NULL); cache_info=(const CacheInfo *) cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", cache_info->filename); clone_info=(CacheInfo *) AcquirePixelCache(cache_info->number_threads); clone_info->virtual_pixel_method=cache_info->virtual_pixel_method; return((Cache ) clone_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C l o n e P i x e l C a c h e M e t h o d s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ClonePixelCacheMethods() clones the pixel cache methods from one cache to % another. % % The format of the ClonePixelCacheMethods() method is: % % void ClonePixelCacheMethods(Cache clone,const Cache cache) % % A description of each parameter follows: % % o clone: Specifies a pointer to a Cache structure. % % o cache: the pixel cache. % */ MagickExport void ClonePixelCacheMethods(Cache clone,const Cache cache) { CacheInfo *magick_restrict cache_info, *magick_restrict source_info; assert(clone != (Cache) NULL); source_info=(CacheInfo *) clone; assert(source_info->signature == MagickCoreSignature); if (source_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", source_info->filename); assert(cache != (Cache) NULL); cache_info=(CacheInfo *) cache; assert(cache_info->signature == MagickCoreSignature); source_info->methods=cache_info->methods; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C l o n e P i x e l C a c h e R e p o s i t o r y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ClonePixelCacheRepository() clones the source pixel cache to the destination % cache. % % The format of the ClonePixelCacheRepository() method is: % % MagickBooleanType ClonePixelCacheRepository(CacheInfo *cache_info, % CacheInfo *source_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o cache_info: the pixel cache. % % o source_info: the source pixel cache. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType ClonePixelCacheOnDisk( CacheInfo *magick_restrict cache_info,CacheInfo *magick_restrict clone_info, ExceptionInfo *exception) { MagickSizeType extent; size_t quantum; ssize_t count; struct stat file_stats; unsigned char *buffer; /* Clone pixel cache on disk with identical morphology. */ if ((OpenPixelCacheOnDisk(cache_info,ReadMode) == MagickFalse) || (OpenPixelCacheOnDisk(clone_info,IOMode) == MagickFalse)) return(MagickFalse); if ((lseek(cache_info->file,0,SEEK_SET) < 0) || (lseek(clone_info->file,0,SEEK_SET) < 0)) return(MagickFalse); quantum=(size_t) MagickMaxBufferExtent; if ((fstat(cache_info->file,&file_stats) == 0) && (file_stats.st_size > 0)) quantum=(size_t) MagickMin(file_stats.st_size,MagickMaxBufferExtent); buffer=(unsigned char *) AcquireQuantumMemory(quantum,sizeof(*buffer)); if (buffer == (unsigned char *) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); extent=0; while ((count=read(cache_info->file,buffer,quantum)) > 0) { ssize_t number_bytes; number_bytes=write(clone_info->file,buffer,(size_t) count); if (number_bytes != count) break; extent+=number_bytes; } buffer=(unsigned char *) RelinquishMagickMemory(buffer); if (extent != cache_info->length) return(MagickFalse); return(MagickTrue); } static MagickBooleanType ClonePixelCacheRepository( CacheInfo *magick_restrict clone_info,CacheInfo *magick_restrict cache_info, ExceptionInfo *exception) { #define MaxCacheThreads ((size_t) GetMagickResourceLimit(ThreadResource)) #define cache_number_threads(source,destination,chunk,multithreaded) \ num_threads((multithreaded) == 0 ? 1 : \ (((source)->type != MemoryCache) && ((source)->type != MapCache)) || \ (((destination)->type != MemoryCache) && ((destination)->type != MapCache)) ? \ MagickMax(MagickMin(GetMagickResourceLimit(ThreadResource),2),1) : \ MagickMax(MagickMin((ssize_t) GetMagickResourceLimit(ThreadResource),(ssize_t) (chunk)/256),1)) MagickBooleanType status; NexusInfo **magick_restrict cache_nexus, **magick_restrict clone_nexus; size_t length; ssize_t y; assert(cache_info != (CacheInfo *) NULL); assert(clone_info != (CacheInfo *) NULL); assert(exception != (ExceptionInfo *) NULL); if (cache_info->type == PingCache) return(MagickTrue); if ((cache_info->storage_class == clone_info->storage_class) && (cache_info->colorspace == clone_info->colorspace) && (cache_info->channels == clone_info->channels) && (cache_info->columns == clone_info->columns) && (cache_info->rows == clone_info->rows) && (cache_info->active_index_channel == clone_info->active_index_channel)) { /* Identical pixel cache morphology. */ if (((cache_info->type == MemoryCache) || (cache_info->type == MapCache)) && ((clone_info->type == MemoryCache) || (clone_info->type == MapCache))) { (void) memcpy(clone_info->pixels,cache_info->pixels, cache_info->columns*cache_info->rows*sizeof(*cache_info->pixels)); if ((cache_info->active_index_channel != MagickFalse) && (clone_info->active_index_channel != MagickFalse)) (void) memcpy(clone_info->indexes,cache_info->indexes, cache_info->columns*cache_info->rows* sizeof(*cache_info->indexes)); return(MagickTrue); } if ((cache_info->type == DiskCache) && (clone_info->type == DiskCache)) return(ClonePixelCacheOnDisk(cache_info,clone_info,exception)); } /* Mismatched pixel cache morphology. */ cache_nexus=AcquirePixelCacheNexus(MaxCacheThreads); clone_nexus=AcquirePixelCacheNexus(MaxCacheThreads); length=(size_t) MagickMin(cache_info->columns,clone_info->columns)* sizeof(*cache_info->pixels); status=MagickTrue; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ cache_number_threads(cache_info,clone_info,cache_info->rows,1) #endif for (y=0; y < (ssize_t) cache_info->rows; y++) { const int id = GetOpenMPThreadId(); PixelPacket *pixels; RectangleInfo region; if (status == MagickFalse) continue; if (y >= (ssize_t) clone_info->rows) continue; region.width=cache_info->columns; region.height=1; region.x=0; region.y=y; pixels=SetPixelCacheNexusPixels(cache_info,ReadMode,&region,MagickFalse, cache_nexus[id],exception); if (pixels == (PixelPacket *) NULL) continue; status=ReadPixelCachePixels(cache_info,cache_nexus[id],exception); if (status == MagickFalse) continue; region.width=clone_info->columns; pixels=SetPixelCacheNexusPixels(clone_info,WriteMode,&region,MagickFalse, clone_nexus[id],exception); if (pixels == (PixelPacket *) NULL) continue; (void) memset(clone_nexus[id]->pixels,0,(size_t) clone_nexus[id]->length); (void) memcpy(clone_nexus[id]->pixels,cache_nexus[id]->pixels,length); status=WritePixelCachePixels(clone_info,clone_nexus[id],exception); } if ((cache_info->active_index_channel != MagickFalse) && (clone_info->active_index_channel != MagickFalse)) { /* Clone indexes. */ length=(size_t) MagickMin(cache_info->columns,clone_info->columns)* sizeof(*cache_info->indexes); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ cache_number_threads(cache_info,clone_info,cache_info->rows,1) #endif for (y=0; y < (ssize_t) cache_info->rows; y++) { const int id = GetOpenMPThreadId(); PixelPacket *pixels; RectangleInfo region; if (status == MagickFalse) continue; if (y >= (ssize_t) clone_info->rows) continue; region.width=cache_info->columns; region.height=1; region.x=0; region.y=y; pixels=SetPixelCacheNexusPixels(cache_info,ReadMode,&region,MagickFalse, cache_nexus[id],exception); if (pixels == (PixelPacket *) NULL) continue; status=ReadPixelCacheIndexes(cache_info,cache_nexus[id],exception); if (status == MagickFalse) continue; region.width=clone_info->columns; pixels=SetPixelCacheNexusPixels(clone_info,WriteMode,&region, MagickFalse,clone_nexus[id],exception); if (pixels == (PixelPacket *) NULL) continue; (void) memcpy(clone_nexus[id]->indexes,cache_nexus[id]->indexes,length); status=WritePixelCacheIndexes(clone_info,clone_nexus[id],exception); } } cache_nexus=DestroyPixelCacheNexus(cache_nexus,MaxCacheThreads); clone_nexus=DestroyPixelCacheNexus(clone_nexus,MaxCacheThreads); if (cache_info->debug != MagickFalse) { char message[MaxTextExtent]; (void) FormatLocaleString(message,MaxTextExtent,"%s => %s", CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) cache_info->type), CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) clone_info->type)); (void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s",message); } return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D e s t r o y I m a g e P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyImagePixelCache() deallocates memory associated with the pixel cache. % % The format of the DestroyImagePixelCache() method is: % % void DestroyImagePixelCache(Image *image) % % A description of each parameter follows: % % o image: the image. % */ static void DestroyImagePixelCache(Image *image) { assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->cache != (void *) NULL) image->cache=DestroyPixelCache(image->cache); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D e s t r o y I m a g e P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyImagePixels() deallocates memory associated with the pixel cache. % % The format of the DestroyImagePixels() method is: % % void DestroyImagePixels(Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport void DestroyImagePixels(Image *image) { CacheInfo *magick_restrict cache_info; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->methods.destroy_pixel_handler != (DestroyPixelHandler) NULL) { cache_info->methods.destroy_pixel_handler(image); return; } image->cache=DestroyPixelCache(image->cache); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D e s t r o y P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyPixelCache() deallocates memory associated with the pixel cache. % % The format of the DestroyPixelCache() method is: % % Cache DestroyPixelCache(Cache cache) % % A description of each parameter follows: % % o cache: the pixel cache. % */ static MagickBooleanType ClosePixelCacheOnDisk(CacheInfo *cache_info) { int status; status=(-1); if (cache_info->file != -1) { status=close(cache_info->file); cache_info->file=(-1); RelinquishMagickResource(FileResource,1); } return(status == -1 ? MagickFalse : MagickTrue); } static inline void RelinquishPixelCachePixels(CacheInfo *cache_info) { switch (cache_info->type) { case MemoryCache: { #if defined(MAGICKCORE_OPENCL_SUPPORT) if (RelinquishOpenCLBuffer(cache_info) != MagickFalse) { cache_info->pixels=(PixelPacket *) NULL; break; } #endif if (cache_info->mapped == MagickFalse) cache_info->pixels=(PixelPacket *) RelinquishAlignedMemory( cache_info->pixels); else (void) UnmapBlob(cache_info->pixels,(size_t) cache_info->length); RelinquishMagickResource(MemoryResource,cache_info->length); break; } case MapCache: { (void) UnmapBlob(cache_info->pixels,(size_t) cache_info->length); cache_info->pixels=(PixelPacket *) NULL; if ((cache_info->mode != ReadMode) && (cache_info->mode != PersistMode)) (void) RelinquishUniqueFileResource(cache_info->cache_filename); *cache_info->cache_filename='\0'; RelinquishMagickResource(MapResource,cache_info->length); } case DiskCache: { if (cache_info->file != -1) (void) ClosePixelCacheOnDisk(cache_info); if ((cache_info->mode != ReadMode) && (cache_info->mode != PersistMode)) (void) RelinquishUniqueFileResource(cache_info->cache_filename); *cache_info->cache_filename='\0'; RelinquishMagickResource(DiskResource,cache_info->length); break; } case DistributedCache: { *cache_info->cache_filename='\0'; (void) RelinquishDistributePixelCache((DistributeCacheInfo *) cache_info->server_info); break; } default: break; } cache_info->type=UndefinedCache; cache_info->mapped=MagickFalse; cache_info->indexes=(IndexPacket *) NULL; } MagickExport Cache DestroyPixelCache(Cache cache) { CacheInfo *magick_restrict cache_info; assert(cache != (Cache) NULL); cache_info=(CacheInfo *) cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", cache_info->filename); LockSemaphoreInfo(cache_info->semaphore); cache_info->reference_count--; if (cache_info->reference_count != 0) { UnlockSemaphoreInfo(cache_info->semaphore); return((Cache) NULL); } UnlockSemaphoreInfo(cache_info->semaphore); if (cache_info->debug != MagickFalse) { char message[MaxTextExtent]; (void) FormatLocaleString(message,MaxTextExtent,"destroy %s", cache_info->filename); (void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s",message); } RelinquishPixelCachePixels(cache_info); if (cache_info->server_info != (DistributeCacheInfo *) NULL) cache_info->server_info=DestroyDistributeCacheInfo((DistributeCacheInfo *) cache_info->server_info); if (cache_info->nexus_info != (NexusInfo **) NULL) cache_info->nexus_info=DestroyPixelCacheNexus(cache_info->nexus_info, cache_info->number_threads); if (cache_info->random_info != (RandomInfo *) NULL) cache_info->random_info=DestroyRandomInfo(cache_info->random_info); if (cache_info->file_semaphore != (SemaphoreInfo *) NULL) DestroySemaphoreInfo(&cache_info->file_semaphore); if (cache_info->semaphore != (SemaphoreInfo *) NULL) DestroySemaphoreInfo(&cache_info->semaphore); cache_info->signature=(~MagickCoreSignature); cache_info=(CacheInfo *) RelinquishMagickMemory(cache_info); cache=(Cache) NULL; return(cache); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D e s t r o y P i x e l C a c h e N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyPixelCacheNexus() destroys a pixel cache nexus. % % The format of the DestroyPixelCacheNexus() method is: % % NexusInfo **DestroyPixelCacheNexus(NexusInfo *nexus_info, % const size_t number_threads) % % A description of each parameter follows: % % o nexus_info: the nexus to destroy. % % o number_threads: the number of nexus threads. % */ static inline void RelinquishCacheNexusPixels(NexusInfo *nexus_info) { if (nexus_info->mapped == MagickFalse) (void) RelinquishAlignedMemory(nexus_info->cache); else (void) UnmapBlob(nexus_info->cache,(size_t) nexus_info->length); nexus_info->cache=(PixelPacket *) NULL; nexus_info->pixels=(PixelPacket *) NULL; nexus_info->indexes=(IndexPacket *) NULL; nexus_info->length=0; nexus_info->mapped=MagickFalse; } MagickExport NexusInfo **DestroyPixelCacheNexus(NexusInfo **nexus_info, const size_t number_threads) { register ssize_t i; assert(nexus_info != (NexusInfo **) NULL); for (i=0; i < (ssize_t) number_threads; i++) { if (nexus_info[i]->cache != (PixelPacket *) NULL) RelinquishCacheNexusPixels(nexus_info[i]); nexus_info[i]->signature=(~MagickCoreSignature); } nexus_info[0]=(NexusInfo *) RelinquishMagickMemory(nexus_info[0]); nexus_info=(NexusInfo **) RelinquishAlignedMemory(nexus_info); return(nexus_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t A u t h e n t i c I n d e x e s F r o m C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetAuthenticIndexesFromCache() returns the indexes associated with the last % call to QueueAuthenticPixelsCache() or GetAuthenticPixelsCache(). % % The format of the GetAuthenticIndexesFromCache() method is: % % IndexPacket *GetAuthenticIndexesFromCache(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ static IndexPacket *GetAuthenticIndexesFromCache(const Image *image) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); return(cache_info->nexus_info[id]->indexes); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t A u t h e n t i c I n d e x Q u e u e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetAuthenticIndexQueue() returns the authentic black channel or the colormap % indexes associated with the last call to QueueAuthenticPixels() or % GetVirtualPixels(). NULL is returned if the black channel or colormap % indexes are not available. % % The format of the GetAuthenticIndexQueue() method is: % % IndexPacket *GetAuthenticIndexQueue(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport IndexPacket *GetAuthenticIndexQueue(const Image *image) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->methods.get_authentic_indexes_from_handler != (GetAuthenticIndexesFromHandler) NULL) return(cache_info->methods.get_authentic_indexes_from_handler(image)); assert(id < (int) cache_info->number_threads); return(cache_info->nexus_info[id]->indexes); } #if defined(MAGICKCORE_OPENCL_SUPPORT) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t A u t h e n t i c O p e n C L B u f f e r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetAuthenticOpenCLBuffer() returns an OpenCL buffer used to execute OpenCL % operations. % % The format of the GetAuthenticOpenCLBuffer() method is: % % cl_mem GetAuthenticOpenCLBuffer(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickPrivate cl_mem GetAuthenticOpenCLBuffer(const Image *image, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; cl_context context; cl_int status; MagickCLEnv clEnv; assert(image != (const Image *) NULL); cache_info=(CacheInfo *)image->cache; if ((cache_info->type == UndefinedCache) || (cache_info->reference_count > 1)) { SyncImagePixelCache((Image *) image,exception); cache_info=(CacheInfo *)image->cache; } if ((cache_info->type != MemoryCache) || (cache_info->mapped != MagickFalse)) return((cl_mem) NULL); LockSemaphoreInfo(cache_info->semaphore); clEnv=GetDefaultOpenCLEnv(); if (cache_info->opencl == (OpenCLCacheInfo *) NULL) { assert(cache_info->pixels != NULL); context=GetOpenCLContext(clEnv); cache_info->opencl=(OpenCLCacheInfo *) AcquireCriticalMemory( sizeof(*cache_info->opencl)); (void) memset(cache_info->opencl,0,sizeof(*cache_info->opencl)); cache_info->opencl->events_semaphore=AllocateSemaphoreInfo(); cache_info->opencl->length=cache_info->length; cache_info->opencl->pixels=cache_info->pixels; cache_info->opencl->buffer=clEnv->library->clCreateBuffer(context, CL_MEM_USE_HOST_PTR,cache_info->length,cache_info->pixels,&status); if (status != CL_SUCCESS) cache_info->opencl=RelinquishOpenCLCacheInfo(clEnv,cache_info->opencl); } if (cache_info->opencl != (OpenCLCacheInfo *) NULL) clEnv->library->clRetainMemObject(cache_info->opencl->buffer); UnlockSemaphoreInfo(cache_info->semaphore); if (cache_info->opencl == (OpenCLCacheInfo *) NULL) return((cl_mem) NULL); return(cache_info->opencl->buffer); } #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t A u t h e n t i c P i x e l C a c h e N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetAuthenticPixelCacheNexus() gets authentic pixels from the in-memory or % disk pixel cache as defined by the geometry parameters. A pointer to the % pixels is returned if the pixels are transferred, otherwise a NULL is % returned. % % The format of the GetAuthenticPixelCacheNexus() method is: % % PixelPacket *GetAuthenticPixelCacheNexus(Image *image,const ssize_t x, % const ssize_t y,const size_t columns,const size_t rows, % NexusInfo *nexus_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % % o nexus_info: the cache nexus to return. % % o exception: return any errors or warnings in this structure. % */ MagickExport PixelPacket *GetAuthenticPixelCacheNexus(Image *image, const ssize_t x,const ssize_t y,const size_t columns,const size_t rows, NexusInfo *nexus_info,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; PixelPacket *magick_restrict pixels; /* Transfer pixels from the cache. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); pixels=QueueAuthenticPixelCacheNexus(image,x,y,columns,rows,MagickTrue, nexus_info,exception); if (pixels == (PixelPacket *) NULL) return((PixelPacket *) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if (nexus_info->authentic_pixel_cache != MagickFalse) return(pixels); if (ReadPixelCachePixels(cache_info,nexus_info,exception) == MagickFalse) return((PixelPacket *) NULL); if (cache_info->active_index_channel != MagickFalse) if (ReadPixelCacheIndexes(cache_info,nexus_info,exception) == MagickFalse) return((PixelPacket *) NULL); return(pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t A u t h e n t i c P i x e l s F r o m C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetAuthenticPixelsFromCache() returns the pixels associated with the last % call to the QueueAuthenticPixelsCache() or GetAuthenticPixelsCache() methods. % % The format of the GetAuthenticPixelsFromCache() method is: % % PixelPacket *GetAuthenticPixelsFromCache(const Image image) % % A description of each parameter follows: % % o image: the image. % */ static PixelPacket *GetAuthenticPixelsFromCache(const Image *image) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); return(cache_info->nexus_info[id]->pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t A u t h e n t i c P i x e l Q u e u e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetAuthenticPixelQueue() returns the authentic pixels associated with the % last call to QueueAuthenticPixels() or GetAuthenticPixels(). % % The format of the GetAuthenticPixelQueue() method is: % % PixelPacket *GetAuthenticPixelQueue(const Image image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport PixelPacket *GetAuthenticPixelQueue(const Image *image) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->methods.get_authentic_pixels_from_handler != (GetAuthenticPixelsFromHandler) NULL) return(cache_info->methods.get_authentic_pixels_from_handler(image)); assert(id < (int) cache_info->number_threads); return(cache_info->nexus_info[id]->pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t A u t h e n t i c P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetAuthenticPixels() obtains a pixel region for read/write access. If the % region is successfully accessed, a pointer to a PixelPacket array % representing the region is returned, otherwise NULL is returned. % % The returned pointer may point to a temporary working copy of the pixels % or it may point to the original pixels in memory. Performance is maximized % if the selected region is part of one row, or one or more full rows, since % then there is opportunity to access the pixels in-place (without a copy) % if the image is in memory, or in a memory-mapped file. The returned pointer % must *never* be deallocated by the user. % % Pixels accessed via the returned pointer represent a simple array of type % PixelPacket. If the image type is CMYK or if the storage class is % PseduoClass, call GetAuthenticIndexQueue() after invoking % GetAuthenticPixels() to obtain the black color component or colormap indexes % (of type IndexPacket) corresponding to the region. Once the PixelPacket % (and/or IndexPacket) array has been updated, the changes must be saved back % to the underlying image using SyncAuthenticPixels() or they may be lost. % % The format of the GetAuthenticPixels() method is: % % PixelPacket *GetAuthenticPixels(Image *image,const ssize_t x, % const ssize_t y,const size_t columns,const size_t rows, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % % o exception: return any errors or warnings in this structure. % */ MagickExport PixelPacket *GetAuthenticPixels(Image *image,const ssize_t x, const ssize_t y,const size_t columns,const size_t rows, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->methods.get_authentic_pixels_handler != (GetAuthenticPixelsHandler) NULL) return(cache_info->methods.get_authentic_pixels_handler(image,x,y,columns, rows,exception)); assert(id < (int) cache_info->number_threads); return(GetAuthenticPixelCacheNexus(image,x,y,columns,rows, cache_info->nexus_info[id],exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t A u t h e n t i c P i x e l s C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetAuthenticPixelsCache() gets pixels from the in-memory or disk pixel cache % as defined by the geometry parameters. A pointer to the pixels is returned % if the pixels are transferred, otherwise a NULL is returned. % % The format of the GetAuthenticPixelsCache() method is: % % PixelPacket *GetAuthenticPixelsCache(Image *image,const ssize_t x, % const ssize_t y,const size_t columns,const size_t rows, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % % o exception: return any errors or warnings in this structure. % */ static PixelPacket *GetAuthenticPixelsCache(Image *image,const ssize_t x, const ssize_t y,const size_t columns,const size_t rows, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; if (cache_info == (Cache) NULL) return((PixelPacket *) NULL); assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); return(GetAuthenticPixelCacheNexus(image,x,y,columns,rows, cache_info->nexus_info[id],exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t I m a g e E x t e n t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageExtent() returns the extent of the pixels associated with the % last call to QueueAuthenticPixels() or GetAuthenticPixels(). % % The format of the GetImageExtent() method is: % % MagickSizeType GetImageExtent(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport MagickSizeType GetImageExtent(const Image *image) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); return(GetPixelCacheNexusExtent(cache_info,cache_info->nexus_info[id])); } #if defined(MAGICKCORE_OPENCL_SUPPORT) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t O p e n C L E v e n t s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetOpenCLEvents() returns the events that the next operation should wait % for. The argument event_count is set to the number of events. % % The format of the GetOpenCLEvents() method is: % % const cl_event *GetOpenCLEvents(const Image *image, % cl_command_queue queue) % % A description of each parameter follows: % % o image: the image. % % o event_count: will be set to the number of events. % */ extern MagickPrivate cl_event *GetOpenCLEvents(const Image *image, cl_uint *event_count) { CacheInfo *magick_restrict cache_info; cl_event *events; assert(image != (const Image *) NULL); assert(event_count != (cl_uint *) NULL); cache_info=(CacheInfo *) image->cache; *event_count=0; events=(cl_event *) NULL; if (cache_info->opencl != (OpenCLCacheInfo *) NULL) events=CopyOpenCLEvents(cache_info->opencl,event_count); return(events); } #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t I m a g e P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImagePixelCache() ensures that there is only a single reference to the % pixel cache to be modified, updating the provided cache pointer to point to % a clone of the original pixel cache if necessary. % % The format of the GetImagePixelCache method is: % % Cache GetImagePixelCache(Image *image,const MagickBooleanType clone, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o clone: any value other than MagickFalse clones the cache pixels. % % o exception: return any errors or warnings in this structure. % */ static inline MagickBooleanType ValidatePixelCacheMorphology( const Image *magick_restrict image) { CacheInfo *magick_restrict cache_info; /* Does the image match the pixel cache morphology? */ cache_info=(CacheInfo *) image->cache; if ((image->storage_class != cache_info->storage_class) || (image->colorspace != cache_info->colorspace) || (image->channels != cache_info->channels) || (image->columns != cache_info->columns) || (image->rows != cache_info->rows) || (cache_info->nexus_info == (NexusInfo **) NULL)) return(MagickFalse); return(MagickTrue); } static Cache GetImagePixelCache(Image *image,const MagickBooleanType clone, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; MagickBooleanType destroy, status; static MagickSizeType cache_timelimit = MagickResourceInfinity, cpu_throttle = MagickResourceInfinity, cycles = 0; status=MagickTrue; if (cpu_throttle == MagickResourceInfinity) cpu_throttle=GetMagickResourceLimit(ThrottleResource); if ((cpu_throttle != 0) && ((cycles++ % 32) == 0)) MagickDelay(cpu_throttle); if (cache_epoch == 0) { /* Set the expire time in seconds. */ cache_epoch=time((time_t *) NULL); cache_timelimit=GetMagickResourceLimit(TimeResource); } if ((cache_timelimit != MagickResourceInfinity) && ((MagickSizeType) (time((time_t *) NULL)-cache_epoch) >= cache_timelimit)) { #if defined(ECANCELED) errno=ECANCELED; #endif cache_info=(CacheInfo *) image->cache; if (cache_info->file != -1) (void) ClosePixelCacheOnDisk(cache_info); ThrowFatalException(ResourceLimitFatalError,"TimeLimitExceeded"); } LockSemaphoreInfo(image->semaphore); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; #if defined(MAGICKCORE_OPENCL_SUPPORT) CopyOpenCLBuffer(cache_info); #endif destroy=MagickFalse; if ((cache_info->reference_count > 1) || (cache_info->mode == ReadMode)) { LockSemaphoreInfo(cache_info->semaphore); if ((cache_info->reference_count > 1) || (cache_info->mode == ReadMode)) { CacheInfo *clone_info; Image clone_image; /* Clone pixel cache. */ clone_image=(*image); clone_image.semaphore=AllocateSemaphoreInfo(); clone_image.reference_count=1; clone_image.cache=ClonePixelCache(cache_info); clone_info=(CacheInfo *) clone_image.cache; status=OpenPixelCache(&clone_image,IOMode,exception); if (status == MagickFalse) clone_info=(CacheInfo *) DestroyPixelCache(clone_info); else { if (clone != MagickFalse) status=ClonePixelCacheRepository(clone_info,cache_info, exception); if (status == MagickFalse) clone_info=(CacheInfo *) DestroyPixelCache(clone_info); else { destroy=MagickTrue; image->cache=clone_info; } } DestroySemaphoreInfo(&clone_image.semaphore); } UnlockSemaphoreInfo(cache_info->semaphore); } if (destroy != MagickFalse) cache_info=(CacheInfo *) DestroyPixelCache(cache_info); if (status != MagickFalse) { /* Ensure the image matches the pixel cache morphology. */ image->type=UndefinedType; if (ValidatePixelCacheMorphology(image) == MagickFalse) { status=OpenPixelCache(image,IOMode,exception); cache_info=(CacheInfo *) image->cache; if (cache_info->file != -1) (void) ClosePixelCacheOnDisk(cache_info); } } UnlockSemaphoreInfo(image->semaphore); if (status == MagickFalse) return((Cache) NULL); return(image->cache); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t I m a g e P i x e l C a c h e T y p e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImagePixelCacheType() returns the pixel cache type: UndefinedCache, % DiskCache, MapCache, MemoryCache, or PingCache. % % The format of the GetImagePixelCacheType() method is: % % CacheType GetImagePixelCacheType(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport CacheType GetPixelCacheType(const Image *image) { return(GetImagePixelCacheType(image)); } MagickExport CacheType GetImagePixelCacheType(const Image *image) { CacheInfo *magick_restrict cache_info; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); return(cache_info->type); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t O n e A u t h e n t i c P i x e l % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetOneAuthenticPixel() returns a single pixel at the specified (x,y) % location. The image background color is returned if an error occurs. % % The format of the GetOneAuthenticPixel() method is: % % MagickBooleanType GetOneAuthenticPixel(const Image image,const ssize_t x, % const ssize_t y,PixelPacket *pixel,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x,y: These values define the location of the pixel to return. % % o pixel: return a pixel at the specified (x,y) location. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GetOneAuthenticPixel(Image *image, const ssize_t x,const ssize_t y,PixelPacket *pixel,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; PixelPacket *magick_restrict pixels; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); *pixel=image->background_color; if (cache_info->methods.get_one_authentic_pixel_from_handler != (GetOneAuthenticPixelFromHandler) NULL) return(cache_info->methods.get_one_authentic_pixel_from_handler(image,x,y,pixel,exception)); pixels=GetAuthenticPixelsCache(image,x,y,1UL,1UL,exception); if (pixels == (PixelPacket *) NULL) return(MagickFalse); *pixel=(*pixels); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t O n e A u t h e n t i c P i x e l F r o m C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetOneAuthenticPixelFromCache() returns a single pixel at the specified (x,y) % location. The image background color is returned if an error occurs. % % The format of the GetOneAuthenticPixelFromCache() method is: % % MagickBooleanType GetOneAuthenticPixelFromCache(const Image image, % const ssize_t x,const ssize_t y,PixelPacket *pixel, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x,y: These values define the location of the pixel to return. % % o pixel: return a pixel at the specified (x,y) location. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType GetOneAuthenticPixelFromCache(Image *image, const ssize_t x,const ssize_t y,PixelPacket *pixel,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); PixelPacket *magick_restrict pixels; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); *pixel=image->background_color; assert(id < (int) cache_info->number_threads); pixels=GetAuthenticPixelCacheNexus(image,x,y,1UL,1UL, cache_info->nexus_info[id],exception); if (pixels == (PixelPacket *) NULL) return(MagickFalse); *pixel=(*pixels); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t O n e V i r t u a l M a g i c k P i x e l % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetOneVirtualMagickPixel() returns a single pixel at the specified (x,y) % location. The image background color is returned if an error occurs. If % you plan to modify the pixel, use GetOneAuthenticPixel() instead. % % The format of the GetOneVirtualMagickPixel() method is: % % MagickBooleanType GetOneVirtualMagickPixel(const Image image, % const ssize_t x,const ssize_t y,MagickPixelPacket *pixel, % ExceptionInfo exception) % % A description of each parameter follows: % % o image: the image. % % o x,y: these values define the location of the pixel to return. % % o pixel: return a pixel at the specified (x,y) location. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GetOneVirtualMagickPixel(const Image *image, const ssize_t x,const ssize_t y,MagickPixelPacket *pixel, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); register const IndexPacket *magick_restrict indexes; register const PixelPacket *magick_restrict pixels; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); pixels=GetVirtualPixelCacheNexus(image,GetPixelCacheVirtualMethod(image),x,y, 1UL,1UL,cache_info->nexus_info[id],exception); GetMagickPixelPacket(image,pixel); if (pixels == (const PixelPacket *) NULL) return(MagickFalse); indexes=GetVirtualIndexesFromNexus(cache_info,cache_info->nexus_info[id]); SetMagickPixelPacket(image,pixels,indexes,pixel); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t O n e V i r t u a l M e t h o d P i x e l % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetOneVirtualMethodPixel() returns a single pixel at the specified (x,y) % location as defined by specified pixel method. The image background color % is returned if an error occurs. If you plan to modify the pixel, use % GetOneAuthenticPixel() instead. % % The format of the GetOneVirtualMethodPixel() method is: % % MagickBooleanType GetOneVirtualMethodPixel(const Image image, % const VirtualPixelMethod virtual_pixel_method,const ssize_t x, % const ssize_t y,Pixelpacket *pixel,ExceptionInfo exception) % % A description of each parameter follows: % % o image: the image. % % o virtual_pixel_method: the virtual pixel method. % % o x,y: These values define the location of the pixel to return. % % o pixel: return a pixel at the specified (x,y) location. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GetOneVirtualMethodPixel(const Image *image, const VirtualPixelMethod virtual_pixel_method,const ssize_t x,const ssize_t y, PixelPacket *pixel,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); const PixelPacket *magick_restrict pixels; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); *pixel=image->background_color; if (cache_info->methods.get_one_virtual_pixel_from_handler != (GetOneVirtualPixelFromHandler) NULL) return(cache_info->methods.get_one_virtual_pixel_from_handler(image, virtual_pixel_method,x,y,pixel,exception)); assert(id < (int) cache_info->number_threads); pixels=GetVirtualPixelCacheNexus(image,virtual_pixel_method,x,y,1UL,1UL, cache_info->nexus_info[id],exception); if (pixels == (const PixelPacket *) NULL) return(MagickFalse); *pixel=(*pixels); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t O n e V i r t u a l P i x e l % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetOneVirtualPixel() returns a single virtual pixel at the specified % (x,y) location. The image background color is returned if an error occurs. % If you plan to modify the pixel, use GetOneAuthenticPixel() instead. % % The format of the GetOneVirtualPixel() method is: % % MagickBooleanType GetOneVirtualPixel(const Image image,const ssize_t x, % const ssize_t y,PixelPacket *pixel,ExceptionInfo exception) % % A description of each parameter follows: % % o image: the image. % % o x,y: These values define the location of the pixel to return. % % o pixel: return a pixel at the specified (x,y) location. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GetOneVirtualPixel(const Image *image, const ssize_t x,const ssize_t y,PixelPacket *pixel,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); const PixelPacket *magick_restrict pixels; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); *pixel=image->background_color; if (cache_info->methods.get_one_virtual_pixel_from_handler != (GetOneVirtualPixelFromHandler) NULL) return(cache_info->methods.get_one_virtual_pixel_from_handler(image, GetPixelCacheVirtualMethod(image),x,y,pixel,exception)); assert(id < (int) cache_info->number_threads); pixels=GetVirtualPixelCacheNexus(image,GetPixelCacheVirtualMethod(image),x,y, 1UL,1UL,cache_info->nexus_info[id],exception); if (pixels == (const PixelPacket *) NULL) return(MagickFalse); *pixel=(*pixels); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t O n e V i r t u a l P i x e l F r o m C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetOneVirtualPixelFromCache() returns a single virtual pixel at the % specified (x,y) location. The image background color is returned if an % error occurs. % % The format of the GetOneVirtualPixelFromCache() method is: % % MagickBooleanType GetOneVirtualPixelFromCache(const Image image, % const VirtualPixelPacket method,const ssize_t x,const ssize_t y, % PixelPacket *pixel,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o virtual_pixel_method: the virtual pixel method. % % o x,y: These values define the location of the pixel to return. % % o pixel: return a pixel at the specified (x,y) location. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType GetOneVirtualPixelFromCache(const Image *image, const VirtualPixelMethod virtual_pixel_method,const ssize_t x,const ssize_t y, PixelPacket *pixel,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); const PixelPacket *magick_restrict pixels; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); *pixel=image->background_color; pixels=GetVirtualPixelCacheNexus(image,virtual_pixel_method,x,y,1UL,1UL, cache_info->nexus_info[id],exception); if (pixels == (const PixelPacket *) NULL) return(MagickFalse); *pixel=(*pixels); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t P i x e l C a c h e C h a n n e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPixelCacheChannels() returns the number of pixel channels associated % with this instance of the pixel cache. % % The format of the GetPixelCacheChannels() method is: % % size_t GetPixelCacheChannels(Cache cache) % % A description of each parameter follows: % % o type: GetPixelCacheChannels returns DirectClass or PseudoClass. % % o cache: the pixel cache. % */ MagickExport size_t GetPixelCacheChannels(const Cache cache) { CacheInfo *magick_restrict cache_info; assert(cache != (Cache) NULL); cache_info=(CacheInfo *) cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", cache_info->filename); return(cache_info->channels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t P i x e l C a c h e C o l o r s p a c e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPixelCacheColorspace() returns the class type of the pixel cache. % % The format of the GetPixelCacheColorspace() method is: % % Colorspace GetPixelCacheColorspace(Cache cache) % % A description of each parameter follows: % % o cache: the pixel cache. % */ MagickExport ColorspaceType GetPixelCacheColorspace(const Cache cache) { CacheInfo *magick_restrict cache_info; assert(cache != (Cache) NULL); cache_info=(CacheInfo *) cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", cache_info->filename); return(cache_info->colorspace); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t P i x e l C a c h e F i l e n a m e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPixelCacheFilename() returns the filename associated with the pixel % cache. % % The format of the GetPixelCacheFilename() method is: % % const char *GetPixelCacheFilename(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport const char *GetPixelCacheFilename(const Image *image) { CacheInfo *magick_restrict cache_info; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); return(cache_info->cache_filename); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t P i x e l C a c h e M e t h o d s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPixelCacheMethods() initializes the CacheMethods structure. % % The format of the GetPixelCacheMethods() method is: % % void GetPixelCacheMethods(CacheMethods *cache_methods) % % A description of each parameter follows: % % o cache_methods: Specifies a pointer to a CacheMethods structure. % */ MagickExport void GetPixelCacheMethods(CacheMethods *cache_methods) { assert(cache_methods != (CacheMethods *) NULL); (void) memset(cache_methods,0,sizeof(*cache_methods)); cache_methods->get_virtual_pixel_handler=GetVirtualPixelCache; cache_methods->get_virtual_pixels_handler=GetVirtualPixelsCache; cache_methods->get_virtual_indexes_from_handler=GetVirtualIndexesFromCache; cache_methods->get_one_virtual_pixel_from_handler=GetOneVirtualPixelFromCache; cache_methods->get_authentic_pixels_handler=GetAuthenticPixelsCache; cache_methods->get_authentic_indexes_from_handler= GetAuthenticIndexesFromCache; cache_methods->get_authentic_pixels_from_handler=GetAuthenticPixelsFromCache; cache_methods->get_one_authentic_pixel_from_handler= GetOneAuthenticPixelFromCache; cache_methods->queue_authentic_pixels_handler=QueueAuthenticPixelsCache; cache_methods->sync_authentic_pixels_handler=SyncAuthenticPixelsCache; cache_methods->destroy_pixel_handler=DestroyImagePixelCache; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t P i x e l C a c h e N e x u s E x t e n t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPixelCacheNexusExtent() returns the extent of the pixels associated with % the last call to SetPixelCacheNexusPixels() or GetPixelCacheNexusPixels(). % % The format of the GetPixelCacheNexusExtent() method is: % % MagickSizeType GetPixelCacheNexusExtent(const Cache cache, % NexusInfo *nexus_info) % % A description of each parameter follows: % % o nexus_info: the nexus info. % */ MagickExport MagickSizeType GetPixelCacheNexusExtent(const Cache cache, NexusInfo *nexus_info) { CacheInfo *magick_restrict cache_info; MagickSizeType extent; assert(cache != NULL); cache_info=(CacheInfo *) cache; assert(cache_info->signature == MagickCoreSignature); extent=(MagickSizeType) nexus_info->region.width*nexus_info->region.height; if (extent == 0) return((MagickSizeType) cache_info->columns*cache_info->rows); return(extent); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t P i x e l C a c h e P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPixelCachePixels() returns the pixels associated with the specified image. % % The format of the GetPixelCachePixels() method is: % % void *GetPixelCachePixels(Image *image,MagickSizeType *length, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o length: the pixel cache length. % % o exception: return any errors or warnings in this structure. % */ MagickExport void *GetPixelCachePixels(Image *image,MagickSizeType *length, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); assert(length != (MagickSizeType *) NULL); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); (void) exception; *length=cache_info->length; if ((cache_info->type != MemoryCache) && (cache_info->type != MapCache)) return((void *) NULL); return((void *) cache_info->pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t P i x e l C a c h e S t o r a g e C l a s s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPixelCacheStorageClass() returns the class type of the pixel cache. % % The format of the GetPixelCacheStorageClass() method is: % % ClassType GetPixelCacheStorageClass(Cache cache) % % A description of each parameter follows: % % o type: GetPixelCacheStorageClass returns DirectClass or PseudoClass. % % o cache: the pixel cache. % */ MagickExport ClassType GetPixelCacheStorageClass(const Cache cache) { CacheInfo *magick_restrict cache_info; assert(cache != (Cache) NULL); cache_info=(CacheInfo *) cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", cache_info->filename); return(cache_info->storage_class); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t P i x e l C a c h e T i l e S i z e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPixelCacheTileSize() returns the pixel cache tile size. % % The format of the GetPixelCacheTileSize() method is: % % void GetPixelCacheTileSize(const Image *image,size_t *width, % size_t *height) % % A description of each parameter follows: % % o image: the image. % % o width: the optimize cache tile width in pixels. % % o height: the optimize cache tile height in pixels. % */ MagickExport void GetPixelCacheTileSize(const Image *image,size_t *width, size_t *height) { assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); *width=2048UL/sizeof(PixelPacket); if (GetImagePixelCacheType(image) == DiskCache) *width=8192UL/sizeof(PixelPacket); *height=(*width); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t P i x e l C a c h e V i r t u a l M e t h o d % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPixelCacheVirtualMethod() gets the "virtual pixels" method for the % pixel cache. A virtual pixel is any pixel access that is outside the % boundaries of the image cache. % % The format of the GetPixelCacheVirtualMethod() method is: % % VirtualPixelMethod GetPixelCacheVirtualMethod(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport VirtualPixelMethod GetPixelCacheVirtualMethod(const Image *image) { CacheInfo *magick_restrict cache_info; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); return(cache_info->virtual_pixel_method); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t V i r t u a l I n d e x e s F r o m C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetVirtualIndexesFromCache() returns the indexes associated with the last % call to QueueAuthenticPixelsCache() or GetVirtualPixelCache(). % % The format of the GetVirtualIndexesFromCache() method is: % % IndexPacket *GetVirtualIndexesFromCache(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ static const IndexPacket *GetVirtualIndexesFromCache(const Image *image) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); return(GetVirtualIndexesFromNexus(cache_info,cache_info->nexus_info[id])); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t V i r t u a l I n d e x e s F r o m N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetVirtualIndexesFromNexus() returns the indexes associated with the % specified cache nexus. % % The format of the GetVirtualIndexesFromNexus() method is: % % const IndexPacket *GetVirtualIndexesFromNexus(const Cache cache, % NexusInfo *nexus_info) % % A description of each parameter follows: % % o cache: the pixel cache. % % o nexus_info: the cache nexus to return the colormap indexes. % */ MagickExport const IndexPacket *GetVirtualIndexesFromNexus(const Cache cache, NexusInfo *nexus_info) { CacheInfo *magick_restrict cache_info; assert(cache != (Cache) NULL); cache_info=(CacheInfo *) cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->storage_class == UndefinedClass) return((IndexPacket *) NULL); return(nexus_info->indexes); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t V i r t u a l I n d e x Q u e u e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetVirtualIndexQueue() returns the virtual black channel or the % colormap indexes associated with the last call to QueueAuthenticPixels() or % GetVirtualPixels(). NULL is returned if the black channel or colormap % indexes are not available. % % The format of the GetVirtualIndexQueue() method is: % % const IndexPacket *GetVirtualIndexQueue(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport const IndexPacket *GetVirtualIndexQueue(const Image *image) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->methods.get_virtual_indexes_from_handler != (GetVirtualIndexesFromHandler) NULL) return(cache_info->methods.get_virtual_indexes_from_handler(image)); assert(id < (int) cache_info->number_threads); return(GetVirtualIndexesFromNexus(cache_info,cache_info->nexus_info[id])); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t V i r t u a l P i x e l C a c h e N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetVirtualPixelCacheNexus() gets virtual pixels from the in-memory or disk % pixel cache as defined by the geometry parameters. A pointer to the pixels % is returned if the pixels are transferred, otherwise a NULL is returned. % % The format of the GetVirtualPixelCacheNexus() method is: % % PixelPacket *GetVirtualPixelCacheNexus(const Image *image, % const VirtualPixelMethod method,const ssize_t x,const ssize_t y, % const size_t columns,const size_t rows,NexusInfo *nexus_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o virtual_pixel_method: the virtual pixel method. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % % o nexus_info: the cache nexus to acquire. % % o exception: return any errors or warnings in this structure. % */ static ssize_t DitherMatrix[64] = { 0, 48, 12, 60, 3, 51, 15, 63, 32, 16, 44, 28, 35, 19, 47, 31, 8, 56, 4, 52, 11, 59, 7, 55, 40, 24, 36, 20, 43, 27, 39, 23, 2, 50, 14, 62, 1, 49, 13, 61, 34, 18, 46, 30, 33, 17, 45, 29, 10, 58, 6, 54, 9, 57, 5, 53, 42, 26, 38, 22, 41, 25, 37, 21 }; static inline ssize_t DitherX(const ssize_t x,const size_t columns) { ssize_t index; index=x+DitherMatrix[x & 0x07]-32L; if (index < 0L) return(0L); if (index >= (ssize_t) columns) return((ssize_t) columns-1L); return(index); } static inline ssize_t DitherY(const ssize_t y,const size_t rows) { ssize_t index; index=y+DitherMatrix[y & 0x07]-32L; if (index < 0L) return(0L); if (index >= (ssize_t) rows) return((ssize_t) rows-1L); return(index); } static inline ssize_t EdgeX(const ssize_t x,const size_t columns) { if (x < 0L) return(0L); if (x >= (ssize_t) columns) return((ssize_t) (columns-1)); return(x); } static inline ssize_t EdgeY(const ssize_t y,const size_t rows) { if (y < 0L) return(0L); if (y >= (ssize_t) rows) return((ssize_t) (rows-1)); return(y); } static inline ssize_t RandomX(RandomInfo *random_info,const size_t columns) { return((ssize_t) (columns*GetPseudoRandomValue(random_info))); } static inline ssize_t RandomY(RandomInfo *random_info,const size_t rows) { return((ssize_t) (rows*GetPseudoRandomValue(random_info))); } static inline MagickModulo VirtualPixelModulo(const ssize_t offset, const size_t extent) { MagickModulo modulo; /* Compute the remainder of dividing offset by extent. It returns not only the quotient (tile the offset falls in) but also the positive remainer within that tile such that 0 <= remainder < extent. This method is essentially a ldiv() using a floored modulo division rather than the normal default truncated modulo division. */ modulo.quotient=offset/(ssize_t) extent; if ((offset < 0L) && (modulo.quotient != INT64_MIN)) modulo.quotient--; modulo.remainder=(ssize_t) (offset-(double) modulo.quotient*extent); return(modulo); } MagickExport const PixelPacket *GetVirtualPixelCacheNexus(const Image *image, const VirtualPixelMethod virtual_pixel_method,const ssize_t x,const ssize_t y, const size_t columns,const size_t rows,NexusInfo *nexus_info, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; IndexPacket virtual_index; MagickOffsetType offset; MagickSizeType length, number_pixels; NexusInfo **magick_restrict virtual_nexus; PixelPacket *magick_restrict pixels, virtual_pixel; RectangleInfo region; register const IndexPacket *magick_restrict virtual_indexes; register const PixelPacket *magick_restrict p; register IndexPacket *magick_restrict indexes; register PixelPacket *magick_restrict q; register ssize_t u, v; /* Acquire pixels. */ assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->type == UndefinedCache) return((const PixelPacket *) NULL); #if defined(MAGICKCORE_OPENCL_SUPPORT) CopyOpenCLBuffer(cache_info); #endif region.x=x; region.y=y; region.width=columns; region.height=rows; pixels=SetPixelCacheNexusPixels(cache_info,ReadMode,&region, (image->clip_mask != (Image *) NULL) || (image->mask != (Image *) NULL) ? MagickTrue : MagickFalse,nexus_info,exception); if (pixels == (PixelPacket *) NULL) return((const PixelPacket *) NULL); offset=(MagickOffsetType) nexus_info->region.y*cache_info->columns+ nexus_info->region.x; length=(MagickSizeType) (nexus_info->region.height-1L)*cache_info->columns+ nexus_info->region.width-1L; number_pixels=(MagickSizeType) cache_info->columns*cache_info->rows; if ((offset >= 0) && (((MagickSizeType) offset+length) < number_pixels)) if ((x >= 0) && ((ssize_t) (x+columns) <= (ssize_t) cache_info->columns) && (y >= 0) && ((ssize_t) (y+rows) <= (ssize_t) cache_info->rows)) { MagickBooleanType status; /* Pixel request is inside cache extents. */ if (nexus_info->authentic_pixel_cache != MagickFalse) return(pixels); status=ReadPixelCachePixels(cache_info,nexus_info,exception); if (status == MagickFalse) return((const PixelPacket *) NULL); if ((cache_info->storage_class == PseudoClass) || (cache_info->colorspace == CMYKColorspace)) { status=ReadPixelCacheIndexes(cache_info,nexus_info,exception); if (status == MagickFalse) return((const PixelPacket *) NULL); } return(pixels); } /* Pixel request is outside cache extents. */ q=pixels; indexes=nexus_info->indexes; virtual_nexus=AcquirePixelCacheNexus(1); switch (virtual_pixel_method) { case BlackVirtualPixelMethod: { SetPixelRed(&virtual_pixel,0); SetPixelGreen(&virtual_pixel,0); SetPixelBlue(&virtual_pixel,0); SetPixelOpacity(&virtual_pixel,OpaqueOpacity); break; } case GrayVirtualPixelMethod: { SetPixelRed(&virtual_pixel,QuantumRange/2); SetPixelGreen(&virtual_pixel,QuantumRange/2); SetPixelBlue(&virtual_pixel,QuantumRange/2); SetPixelOpacity(&virtual_pixel,OpaqueOpacity); break; } case TransparentVirtualPixelMethod: { SetPixelRed(&virtual_pixel,0); SetPixelGreen(&virtual_pixel,0); SetPixelBlue(&virtual_pixel,0); SetPixelOpacity(&virtual_pixel,TransparentOpacity); break; } case MaskVirtualPixelMethod: case WhiteVirtualPixelMethod: { SetPixelRed(&virtual_pixel,QuantumRange); SetPixelGreen(&virtual_pixel,QuantumRange); SetPixelBlue(&virtual_pixel,QuantumRange); SetPixelOpacity(&virtual_pixel,OpaqueOpacity); break; } default: { virtual_pixel=image->background_color; break; } } virtual_index=0; for (v=0; v < (ssize_t) rows; v++) { ssize_t y_offset; y_offset=y+v; if ((virtual_pixel_method == EdgeVirtualPixelMethod) || (virtual_pixel_method == UndefinedVirtualPixelMethod)) y_offset=EdgeY(y_offset,cache_info->rows); for (u=0; u < (ssize_t) columns; u+=length) { ssize_t x_offset; x_offset=x+u; length=(MagickSizeType) MagickMin(cache_info->columns-x_offset,columns-u); if (((x_offset < 0) || (x_offset >= (ssize_t) cache_info->columns)) || ((y_offset < 0) || (y_offset >= (ssize_t) cache_info->rows)) || (length == 0)) { MagickModulo x_modulo, y_modulo; /* Transfer a single pixel. */ length=(MagickSizeType) 1; switch (virtual_pixel_method) { case BackgroundVirtualPixelMethod: case ConstantVirtualPixelMethod: case BlackVirtualPixelMethod: case GrayVirtualPixelMethod: case TransparentVirtualPixelMethod: case MaskVirtualPixelMethod: case WhiteVirtualPixelMethod: { p=(&virtual_pixel); virtual_indexes=(&virtual_index); break; } case EdgeVirtualPixelMethod: default: { p=GetVirtualPixelCacheNexus(image,virtual_pixel_method, EdgeX(x_offset,cache_info->columns), EdgeY(y_offset,cache_info->rows),1UL,1UL,*virtual_nexus, exception); virtual_indexes=GetVirtualIndexesFromNexus(cache_info, *virtual_nexus); break; } case RandomVirtualPixelMethod: { if (cache_info->random_info == (RandomInfo *) NULL) cache_info->random_info=AcquireRandomInfo(); p=GetVirtualPixelCacheNexus(image,virtual_pixel_method, RandomX(cache_info->random_info,cache_info->columns), RandomY(cache_info->random_info,cache_info->rows),1UL,1UL, *virtual_nexus,exception); virtual_indexes=GetVirtualIndexesFromNexus(cache_info, *virtual_nexus); break; } case DitherVirtualPixelMethod: { p=GetVirtualPixelCacheNexus(image,virtual_pixel_method, DitherX(x_offset,cache_info->columns), DitherY(y_offset,cache_info->rows),1UL,1UL,*virtual_nexus, exception); virtual_indexes=GetVirtualIndexesFromNexus(cache_info, *virtual_nexus); break; } case TileVirtualPixelMethod: { x_modulo=VirtualPixelModulo(x_offset,cache_info->columns); y_modulo=VirtualPixelModulo(y_offset,cache_info->rows); p=GetVirtualPixelCacheNexus(image,virtual_pixel_method, x_modulo.remainder,y_modulo.remainder,1UL,1UL,*virtual_nexus, exception); virtual_indexes=GetVirtualIndexesFromNexus(cache_info, *virtual_nexus); break; } case MirrorVirtualPixelMethod: { x_modulo=VirtualPixelModulo(x_offset,cache_info->columns); if ((x_modulo.quotient & 0x01) == 1L) x_modulo.remainder=(ssize_t) cache_info->columns- x_modulo.remainder-1L; y_modulo=VirtualPixelModulo(y_offset,cache_info->rows); if ((y_modulo.quotient & 0x01) == 1L) y_modulo.remainder=(ssize_t) cache_info->rows- y_modulo.remainder-1L; p=GetVirtualPixelCacheNexus(image,virtual_pixel_method, x_modulo.remainder,y_modulo.remainder,1UL,1UL,*virtual_nexus, exception); virtual_indexes=GetVirtualIndexesFromNexus(cache_info, *virtual_nexus); break; } case CheckerTileVirtualPixelMethod: { x_modulo=VirtualPixelModulo(x_offset,cache_info->columns); y_modulo=VirtualPixelModulo(y_offset,cache_info->rows); if (((x_modulo.quotient ^ y_modulo.quotient) & 0x01) != 0L) { p=(&virtual_pixel); virtual_indexes=(&virtual_index); break; } p=GetVirtualPixelCacheNexus(image,virtual_pixel_method, x_modulo.remainder,y_modulo.remainder,1UL,1UL,*virtual_nexus, exception); virtual_indexes=GetVirtualIndexesFromNexus(cache_info, *virtual_nexus); break; } case HorizontalTileVirtualPixelMethod: { if ((y_offset < 0) || (y_offset >= (ssize_t) cache_info->rows)) { p=(&virtual_pixel); virtual_indexes=(&virtual_index); break; } x_modulo=VirtualPixelModulo(x_offset,cache_info->columns); y_modulo=VirtualPixelModulo(y_offset,cache_info->rows); p=GetVirtualPixelCacheNexus(image,virtual_pixel_method, x_modulo.remainder,y_modulo.remainder,1UL,1UL,*virtual_nexus, exception); virtual_indexes=GetVirtualIndexesFromNexus(cache_info, *virtual_nexus); break; } case VerticalTileVirtualPixelMethod: { if ((x_offset < 0) || (x_offset >= (ssize_t) cache_info->columns)) { p=(&virtual_pixel); virtual_indexes=(&virtual_index); break; } x_modulo=VirtualPixelModulo(x_offset,cache_info->columns); y_modulo=VirtualPixelModulo(y_offset,cache_info->rows); p=GetVirtualPixelCacheNexus(image,virtual_pixel_method, x_modulo.remainder,y_modulo.remainder,1UL,1UL,*virtual_nexus, exception); virtual_indexes=GetVirtualIndexesFromNexus(cache_info, *virtual_nexus); break; } case HorizontalTileEdgeVirtualPixelMethod: { x_modulo=VirtualPixelModulo(x_offset,cache_info->columns); p=GetVirtualPixelCacheNexus(image,virtual_pixel_method, x_modulo.remainder,EdgeY(y_offset,cache_info->rows),1UL,1UL, *virtual_nexus,exception); virtual_indexes=GetVirtualIndexesFromNexus(cache_info, *virtual_nexus); break; } case VerticalTileEdgeVirtualPixelMethod: { y_modulo=VirtualPixelModulo(y_offset,cache_info->rows); p=GetVirtualPixelCacheNexus(image,virtual_pixel_method, EdgeX(x_offset,cache_info->columns),y_modulo.remainder,1UL,1UL, *virtual_nexus,exception); virtual_indexes=GetVirtualIndexesFromNexus(cache_info, *virtual_nexus); break; } } if (p == (const PixelPacket *) NULL) break; *q++=(*p); if ((indexes != (IndexPacket *) NULL) && (virtual_indexes != (const IndexPacket *) NULL)) *indexes++=(*virtual_indexes); continue; } /* Transfer a run of pixels. */ p=GetVirtualPixelCacheNexus(image,virtual_pixel_method,x_offset,y_offset, (size_t) length,1UL,*virtual_nexus,exception); if (p == (const PixelPacket *) NULL) break; virtual_indexes=GetVirtualIndexesFromNexus(cache_info,*virtual_nexus); (void) memcpy(q,p,(size_t) length*sizeof(*p)); q+=length; if ((indexes != (IndexPacket *) NULL) && (virtual_indexes != (const IndexPacket *) NULL)) { (void) memcpy(indexes,virtual_indexes,(size_t) length* sizeof(*virtual_indexes)); indexes+=length; } } if (u < (ssize_t) columns) break; } /* Free resources. */ virtual_nexus=DestroyPixelCacheNexus(virtual_nexus,1); if (v < (ssize_t) rows) return((const PixelPacket *) NULL); return(pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t V i r t u a l P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetVirtualPixelCache() get virtual pixels from the in-memory or disk pixel % cache as defined by the geometry parameters. A pointer to the pixels % is returned if the pixels are transferred, otherwise a NULL is returned. % % The format of the GetVirtualPixelCache() method is: % % const PixelPacket *GetVirtualPixelCache(const Image *image, % const VirtualPixelMethod virtual_pixel_method,const ssize_t x, % const ssize_t y,const size_t columns,const size_t rows, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o virtual_pixel_method: the virtual pixel method. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % % o exception: return any errors or warnings in this structure. % */ static const PixelPacket *GetVirtualPixelCache(const Image *image, const VirtualPixelMethod virtual_pixel_method,const ssize_t x,const ssize_t y, const size_t columns,const size_t rows,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); return(GetVirtualPixelCacheNexus(image,virtual_pixel_method,x,y,columns,rows, cache_info->nexus_info[id],exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t V i r t u a l P i x e l Q u e u e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetVirtualPixelQueue() returns the virtual pixels associated with the % last call to QueueAuthenticPixels() or GetVirtualPixels(). % % The format of the GetVirtualPixelQueue() method is: % % const PixelPacket *GetVirtualPixelQueue(const Image image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport const PixelPacket *GetVirtualPixelQueue(const Image *image) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->methods.get_virtual_pixels_handler != (GetVirtualPixelsHandler) NULL) return(cache_info->methods.get_virtual_pixels_handler(image)); assert(id < (int) cache_info->number_threads); return(GetVirtualPixelsNexus(cache_info,cache_info->nexus_info[id])); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t V i r t u a l P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetVirtualPixels() returns an immutable pixel region. If the % region is successfully accessed, a pointer to it is returned, otherwise % NULL is returned. The returned pointer may point to a temporary working % copy of the pixels or it may point to the original pixels in memory. % Performance is maximized if the selected region is part of one row, or one % or more full rows, since there is opportunity to access the pixels in-place % (without a copy) if the image is in memory, or in a memory-mapped file. The % returned pointer must *never* be deallocated by the user. % % Pixels accessed via the returned pointer represent a simple array of type % PixelPacket. If the image type is CMYK or the storage class is PseudoClass, % call GetAuthenticIndexQueue() after invoking GetAuthenticPixels() to access % the black color component or to obtain the colormap indexes (of type % IndexPacket) corresponding to the region. % % If you plan to modify the pixels, use GetAuthenticPixels() instead. % % Note, the GetVirtualPixels() and GetAuthenticPixels() methods are not thread- % safe. In a threaded environment, use GetCacheViewVirtualPixels() or % GetCacheViewAuthenticPixels() instead. % % The format of the GetVirtualPixels() method is: % % const PixelPacket *GetVirtualPixels(const Image *image,const ssize_t x, % const ssize_t y,const size_t columns,const size_t rows, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % % o exception: return any errors or warnings in this structure. % */ MagickExport const PixelPacket *GetVirtualPixels(const Image *image, const ssize_t x,const ssize_t y,const size_t columns,const size_t rows, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->methods.get_virtual_pixel_handler != (GetVirtualPixelHandler) NULL) return(cache_info->methods.get_virtual_pixel_handler(image, GetPixelCacheVirtualMethod(image),x,y,columns,rows,exception)); assert(id < (int) cache_info->number_threads); return(GetVirtualPixelCacheNexus(image,GetPixelCacheVirtualMethod(image),x,y, columns,rows,cache_info->nexus_info[id],exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t V i r t u a l P i x e l s F r o m C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetVirtualPixelsCache() returns the pixels associated with the last call % to QueueAuthenticPixelsCache() or GetVirtualPixelCache(). % % The format of the GetVirtualPixelsCache() method is: % % PixelPacket *GetVirtualPixelsCache(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ static const PixelPacket *GetVirtualPixelsCache(const Image *image) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); return(GetVirtualPixelsNexus(image->cache,cache_info->nexus_info[id])); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t V i r t u a l P i x e l s N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetVirtualPixelsNexus() returns the pixels associated with the specified % cache nexus. % % The format of the GetVirtualPixelsNexus() method is: % % const IndexPacket *GetVirtualPixelsNexus(const Cache cache, % NexusInfo *nexus_info) % % A description of each parameter follows: % % o cache: the pixel cache. % % o nexus_info: the cache nexus to return the colormap pixels. % */ MagickExport const PixelPacket *GetVirtualPixelsNexus(const Cache cache, NexusInfo *nexus_info) { CacheInfo *magick_restrict cache_info; assert(cache != (Cache) NULL); cache_info=(CacheInfo *) cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->storage_class == UndefinedClass) return((PixelPacket *) NULL); return((const PixelPacket *) nexus_info->pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + M a s k P i x e l C a c h e N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MaskPixelCacheNexus() masks the cache nexus as defined by the image mask. % The method returns MagickTrue if the pixel region is masked, otherwise % MagickFalse. % % The format of the MaskPixelCacheNexus() method is: % % MagickBooleanType MaskPixelCacheNexus(Image *image, % NexusInfo *nexus_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o nexus_info: the cache nexus to clip. % % o exception: return any errors or warnings in this structure. % */ static inline void ApplyPixelCompositeMask(const MagickPixelPacket *p, const MagickRealType alpha,const MagickPixelPacket *q, const MagickRealType beta,MagickPixelPacket *composite) { double gamma; if (fabs(alpha-TransparentOpacity) < MagickEpsilon) { *composite=(*q); return; } gamma=1.0-QuantumScale*QuantumScale*alpha*beta; gamma=PerceptibleReciprocal(gamma); composite->red=gamma*MagickOver_(p->red,alpha,q->red,beta); composite->green=gamma*MagickOver_(p->green,alpha,q->green,beta); composite->blue=gamma*MagickOver_(p->blue,alpha,q->blue,beta); if ((p->colorspace == CMYKColorspace) && (q->colorspace == CMYKColorspace)) composite->index=gamma*MagickOver_(p->index,alpha,q->index,beta); } static MagickBooleanType MaskPixelCacheNexus(Image *image,NexusInfo *nexus_info, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; MagickPixelPacket alpha, beta; MagickSizeType number_pixels; NexusInfo **magick_restrict image_nexus, **magick_restrict mask_nexus; register const PixelPacket *magick_restrict r; register IndexPacket *magick_restrict nexus_indexes, *magick_restrict indexes; register PixelPacket *magick_restrict p, *magick_restrict q; register ssize_t i; /* Apply clip mask. */ if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if ((image->mask == (Image *) NULL) || (image->storage_class == PseudoClass)) return(MagickTrue); cache_info=(CacheInfo *) image->cache; if (cache_info == (Cache) NULL) return(MagickFalse); image_nexus=AcquirePixelCacheNexus(1); mask_nexus=AcquirePixelCacheNexus(1); p=GetAuthenticPixelCacheNexus(image,nexus_info->region.x, nexus_info->region.y,nexus_info->region.width,nexus_info->region.height, image_nexus[0],exception); indexes=image_nexus[0]->indexes; q=nexus_info->pixels; nexus_indexes=nexus_info->indexes; r=GetVirtualPixelCacheNexus(image->mask,MaskVirtualPixelMethod, nexus_info->region.x,nexus_info->region.y,nexus_info->region.width, nexus_info->region.height,mask_nexus[0],&image->exception); GetMagickPixelPacket(image,&alpha); GetMagickPixelPacket(image,&beta); number_pixels=(MagickSizeType) nexus_info->region.width* nexus_info->region.height; for (i=0; i < (ssize_t) number_pixels; i++) { if ((p == (PixelPacket *) NULL) || (r == (const PixelPacket *) NULL)) break; SetMagickPixelPacket(image,p,indexes+i,&alpha); SetMagickPixelPacket(image,q,nexus_indexes+i,&beta); ApplyPixelCompositeMask(&beta,GetPixelIntensity(image,r),&alpha, alpha.opacity,&beta); SetPixelRed(q,ClampToQuantum(beta.red)); SetPixelGreen(q,ClampToQuantum(beta.green)); SetPixelBlue(q,ClampToQuantum(beta.blue)); SetPixelOpacity(q,ClampToQuantum(beta.opacity)); if (cache_info->active_index_channel != MagickFalse) SetPixelIndex(nexus_indexes+i,GetPixelIndex(indexes+i)); p++; q++; r++; } mask_nexus=DestroyPixelCacheNexus(mask_nexus,1); image_nexus=DestroyPixelCacheNexus(image_nexus,1); if (i < (ssize_t) number_pixels) return(MagickFalse); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + O p e n P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % OpenPixelCache() allocates the pixel cache. This includes defining the cache % dimensions, allocating space for the image pixels and optionally the % colormap indexes, and memory mapping the cache if it is disk based. The % cache nexus array is initialized as well. % % The format of the OpenPixelCache() method is: % % MagickBooleanType OpenPixelCache(Image *image,const MapMode mode, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o mode: ReadMode, WriteMode, or IOMode. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType OpenPixelCacheOnDisk(CacheInfo *cache_info, const MapMode mode) { int file; /* Open pixel cache on disk. */ if ((cache_info->file != -1) && (cache_info->disk_mode == mode)) return(MagickTrue); /* cache already open and in the proper mode */ if (*cache_info->cache_filename == '\0') file=AcquireUniqueFileResource(cache_info->cache_filename); else switch (mode) { case ReadMode: { file=open_utf8(cache_info->cache_filename,O_RDONLY | O_BINARY,0); break; } case WriteMode: { file=open_utf8(cache_info->cache_filename,O_WRONLY | O_CREAT | O_BINARY | O_EXCL,S_MODE); if (file == -1) file=open_utf8(cache_info->cache_filename,O_WRONLY | O_BINARY,S_MODE); break; } case IOMode: default: { file=open_utf8(cache_info->cache_filename,O_RDWR | O_CREAT | O_BINARY | O_EXCL,S_MODE); if (file == -1) file=open_utf8(cache_info->cache_filename,O_RDWR | O_BINARY,S_MODE); break; } } if (file == -1) return(MagickFalse); (void) AcquireMagickResource(FileResource,1); if (cache_info->file != -1) (void) ClosePixelCacheOnDisk(cache_info); cache_info->file=file; cache_info->disk_mode=mode; return(MagickTrue); } static inline MagickOffsetType WritePixelCacheRegion( const CacheInfo *magick_restrict cache_info,const MagickOffsetType offset, const MagickSizeType length,const unsigned char *magick_restrict buffer) { register MagickOffsetType i; ssize_t count; #if !defined(MAGICKCORE_HAVE_PWRITE) if (lseek(cache_info->file,offset,SEEK_SET) < 0) return((MagickOffsetType) -1); #endif count=0; for (i=0; i < (MagickOffsetType) length; i+=count) { #if !defined(MAGICKCORE_HAVE_PWRITE) count=write(cache_info->file,buffer+i,(size_t) MagickMin(length-i,(size_t) SSIZE_MAX)); #else count=pwrite(cache_info->file,buffer+i,(size_t) MagickMin(length-i,(size_t) SSIZE_MAX),(off_t) (offset+i)); #endif if (count <= 0) { count=0; if (errno != EINTR) break; } } return(i); } static MagickBooleanType SetPixelCacheExtent(Image *image,MagickSizeType length) { CacheInfo *magick_restrict cache_info; MagickOffsetType count, extent, offset; cache_info=(CacheInfo *) image->cache; if (image->debug != MagickFalse) { char format[MaxTextExtent], message[MaxTextExtent]; (void) FormatMagickSize(length,MagickFalse,format); (void) FormatLocaleString(message,MaxTextExtent, "extend %s (%s[%d], disk, %s)",cache_info->filename, cache_info->cache_filename,cache_info->file,format); (void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s",message); } offset=(MagickOffsetType) lseek(cache_info->file,0,SEEK_END); if (offset < 0) return(MagickFalse); if ((MagickSizeType) offset >= length) count=(MagickOffsetType) 1; else { extent=(MagickOffsetType) length-1; count=WritePixelCacheRegion(cache_info,extent,1,(const unsigned char *) ""); if (count != 1) return(MagickFalse); #if defined(MAGICKCORE_HAVE_POSIX_FALLOCATE) if (cache_info->synchronize != MagickFalse) (void) posix_fallocate(cache_info->file,offset+1,extent-offset); #endif } offset=(MagickOffsetType) lseek(cache_info->file,0,SEEK_SET); if (offset < 0) return(MagickFalse); return(MagickTrue); } static MagickBooleanType OpenPixelCache(Image *image,const MapMode mode, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info, source_info; char format[MaxTextExtent], message[MaxTextExtent]; const char *hosts, *type; MagickSizeType length, number_pixels; MagickStatusType status; size_t columns, packet_size; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (cache_anonymous_memory < 0) { char *value; /* Does the security policy require anonymous mapping for pixel cache? */ cache_anonymous_memory=0; value=GetPolicyValue("pixel-cache-memory"); if (value == (char *) NULL) value=GetPolicyValue("cache:memory-map"); if (LocaleCompare(value,"anonymous") == 0) { #if defined(MAGICKCORE_HAVE_MMAP) && defined(MAP_ANONYMOUS) cache_anonymous_memory=1; #else (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateError,"DelegateLibrarySupportNotBuiltIn", "'%s' (policy requires anonymous memory mapping)",image->filename); #endif } value=DestroyString(value); } if ((image->columns == 0) || (image->rows == 0)) ThrowBinaryException(CacheError,"NoPixelsDefinedInCache",image->filename); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if ((AcquireMagickResource(WidthResource,image->columns) == MagickFalse) || (AcquireMagickResource(HeightResource,image->rows) == MagickFalse)) ThrowBinaryException(ImageError,"WidthOrHeightExceedsLimit", image->filename); length=GetImageListLength(image); if (AcquireMagickResource(ListLengthResource,length) == MagickFalse) ThrowBinaryException(ResourceLimitError,"ListLengthExceedsLimit", image->filename); source_info=(*cache_info); source_info.file=(-1); (void) FormatLocaleString(cache_info->filename,MaxTextExtent,"%s[%.20g]", image->filename,(double) image->scene); cache_info->mode=mode; cache_info->rows=image->rows; cache_info->columns=image->columns; cache_info->channels=image->channels; cache_info->active_index_channel=((image->storage_class == PseudoClass) || (image->colorspace == CMYKColorspace)) ? MagickTrue : MagickFalse; number_pixels=(MagickSizeType) cache_info->columns*cache_info->rows; packet_size=sizeof(PixelPacket); if (cache_info->active_index_channel != MagickFalse) packet_size+=sizeof(IndexPacket); length=number_pixels*packet_size; columns=(size_t) (length/cache_info->rows/packet_size); if ((cache_info->columns != columns) || ((ssize_t) cache_info->columns < 0) || ((ssize_t) cache_info->rows < 0)) ThrowBinaryException(ResourceLimitError,"PixelCacheAllocationFailed", image->filename); cache_info->length=length; if (image->ping != MagickFalse) { cache_info->storage_class=image->storage_class; cache_info->colorspace=image->colorspace; cache_info->type=PingCache; return(MagickTrue); } status=AcquireMagickResource(AreaResource,(MagickSizeType) cache_info->columns*cache_info->rows); if (cache_info->mode == PersistMode) status=MagickFalse; length=number_pixels*(sizeof(PixelPacket)+sizeof(IndexPacket)); if ((status != MagickFalse) && (length == (MagickSizeType) ((size_t) length)) && ((cache_info->type == UndefinedCache) || (cache_info->type == MemoryCache))) { status=AcquireMagickResource(MemoryResource,cache_info->length); if (status != MagickFalse) { status=MagickTrue; if (cache_anonymous_memory <= 0) { cache_info->mapped=MagickFalse; cache_info->pixels=(PixelPacket *) MagickAssumeAligned( AcquireAlignedMemory(1,(size_t) cache_info->length)); } else { cache_info->mapped=MagickTrue; cache_info->pixels=(PixelPacket *) MapBlob(-1,IOMode,0,(size_t) cache_info->length); } if (cache_info->pixels == (PixelPacket *) NULL) { cache_info->mapped=source_info.mapped; cache_info->pixels=source_info.pixels; } else { /* Create memory pixel cache. */ cache_info->colorspace=image->colorspace; cache_info->type=MemoryCache; cache_info->indexes=(IndexPacket *) NULL; if (cache_info->active_index_channel != MagickFalse) cache_info->indexes=(IndexPacket *) (cache_info->pixels+ number_pixels); if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode)) { status&=ClonePixelCacheRepository(cache_info,&source_info, exception); RelinquishPixelCachePixels(&source_info); } if (image->debug != MagickFalse) { (void) FormatMagickSize(cache_info->length,MagickTrue,format); type=CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) cache_info->type); (void) FormatLocaleString(message,MaxTextExtent, "open %s (%s %s, %.20gx%.20g %s)",cache_info->filename, cache_info->mapped != MagickFalse ? "Anonymous" : "Heap", type,(double) cache_info->columns,(double) cache_info->rows, format); (void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s", message); } cache_info->storage_class=image->storage_class; return(status == 0 ? MagickFalse : MagickTrue); } } } status=AcquireMagickResource(DiskResource,cache_info->length); hosts=(const char *) GetImageRegistry(StringRegistryType,"cache:hosts", exception); if ((status == MagickFalse) && (hosts != (const char *) NULL)) { DistributeCacheInfo *server_info; /* Distribute the pixel cache to a remote server. */ server_info=AcquireDistributeCacheInfo(exception); if (server_info != (DistributeCacheInfo *) NULL) { status=OpenDistributePixelCache(server_info,image); if (status == MagickFalse) { ThrowFileException(exception,CacheError,"UnableToOpenPixelCache", GetDistributeCacheHostname(server_info)); server_info=DestroyDistributeCacheInfo(server_info); } else { /* Create a distributed pixel cache. */ status=MagickTrue; cache_info->type=DistributedCache; cache_info->storage_class=image->storage_class; cache_info->colorspace=image->colorspace; cache_info->server_info=server_info; (void) FormatLocaleString(cache_info->cache_filename, MaxTextExtent,"%s:%d",GetDistributeCacheHostname( (DistributeCacheInfo *) cache_info->server_info), GetDistributeCachePort((DistributeCacheInfo *) cache_info->server_info)); if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode)) { status=ClonePixelCacheRepository(cache_info,&source_info, exception); RelinquishPixelCachePixels(&source_info); } if (image->debug != MagickFalse) { (void) FormatMagickSize(cache_info->length,MagickFalse, format); type=CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) cache_info->type); (void) FormatLocaleString(message,MaxTextExtent, "open %s (%s[%d], %s, %.20gx%.20g %s)",cache_info->filename, cache_info->cache_filename,GetDistributeCacheFile( (DistributeCacheInfo *) cache_info->server_info),type, (double) cache_info->columns,(double) cache_info->rows, format); (void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s", message); } return(status == 0 ? MagickFalse : MagickTrue); } } cache_info->type=UndefinedCache; (void) ThrowMagickException(exception,GetMagickModule(),CacheError, "CacheResourcesExhausted","`%s'",image->filename); return(MagickFalse); } /* Create pixel cache on disk. */ if (status == MagickFalse) { cache_info->type=UndefinedCache; (void) ThrowMagickException(exception,GetMagickModule(),CacheError, "CacheResourcesExhausted","`%s'",image->filename); return(MagickFalse); } if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode) && (cache_info->mode != PersistMode)) { (void) ClosePixelCacheOnDisk(cache_info); *cache_info->cache_filename='\0'; } if (OpenPixelCacheOnDisk(cache_info,mode) == MagickFalse) { ThrowFileException(exception,CacheError,"UnableToOpenPixelCache", image->filename); return(MagickFalse); } status=SetPixelCacheExtent(image,(MagickSizeType) cache_info->offset+ cache_info->length); if (status == MagickFalse) { ThrowFileException(exception,CacheError,"UnableToExtendCache", image->filename); return(MagickFalse); } cache_info->storage_class=image->storage_class; cache_info->colorspace=image->colorspace; length=number_pixels*(sizeof(PixelPacket)+sizeof(IndexPacket)); if (length != (MagickSizeType) ((size_t) length)) cache_info->type=DiskCache; else { status=AcquireMagickResource(MapResource,cache_info->length); if (status == MagickFalse) cache_info->type=DiskCache; else if ((cache_info->type != MapCache) && (cache_info->type != MemoryCache)) { cache_info->type=DiskCache; RelinquishMagickResource(MapResource,cache_info->length); } else { cache_info->pixels=(PixelPacket *) MapBlob(cache_info->file,mode, cache_info->offset,(size_t) cache_info->length); if (cache_info->pixels == (PixelPacket *) NULL) { cache_info->type=DiskCache; cache_info->mapped=source_info.mapped; cache_info->pixels=source_info.pixels; RelinquishMagickResource(MapResource,cache_info->length); } else { /* Create file-backed memory-mapped pixel cache. */ (void) ClosePixelCacheOnDisk(cache_info); cache_info->type=MapCache; cache_info->mapped=MagickTrue; cache_info->indexes=(IndexPacket *) NULL; if (cache_info->active_index_channel != MagickFalse) cache_info->indexes=(IndexPacket *) (cache_info->pixels+ number_pixels); if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode)) { status=ClonePixelCacheRepository(cache_info,&source_info, exception); RelinquishPixelCachePixels(&source_info); } if (image->debug != MagickFalse) { (void) FormatMagickSize(cache_info->length,MagickTrue, format); type=CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) cache_info->type); (void) FormatLocaleString(message,MaxTextExtent, "open %s (%s[%d], %s, %.20gx%.20g %s)", cache_info->filename,cache_info->cache_filename, cache_info->file,type,(double) cache_info->columns, (double) cache_info->rows,format); (void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s", message); } return(status == 0 ? MagickFalse : MagickTrue); } } } status=MagickTrue; if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode)) { status=ClonePixelCacheRepository(cache_info,&source_info,exception); RelinquishPixelCachePixels(&source_info); } if (image->debug != MagickFalse) { (void) FormatMagickSize(cache_info->length,MagickFalse,format); type=CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) cache_info->type); (void) FormatLocaleString(message,MaxTextExtent, "open %s (%s[%d], %s, %.20gx%.20g %s)",cache_info->filename, cache_info->cache_filename,cache_info->file,type,(double) cache_info->columns,(double) cache_info->rows,format); (void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s",message); } return(status == 0 ? MagickFalse : MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + P e r s i s t P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % PersistPixelCache() attaches to or initializes a persistent pixel cache. A % persistent pixel cache is one that resides on disk and is not destroyed % when the program exits. % % The format of the PersistPixelCache() method is: % % MagickBooleanType PersistPixelCache(Image *image,const char *filename, % const MagickBooleanType attach,MagickOffsetType *offset, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o filename: the persistent pixel cache filename. % % o attach: A value other than zero initializes the persistent pixel cache. % % o initialize: A value other than zero initializes the persistent pixel % cache. % % o offset: the offset in the persistent cache to store pixels. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType PersistPixelCache(Image *image, const char *filename,const MagickBooleanType attach,MagickOffsetType *offset, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info, *magick_restrict clone_info; MagickBooleanType status; ssize_t page_size; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(image->cache != (void *) NULL); assert(filename != (const char *) NULL); assert(offset != (MagickOffsetType *) NULL); page_size=GetMagickPageSize(); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); #if defined(MAGICKCORE_OPENCL_SUPPORT) CopyOpenCLBuffer(cache_info); #endif if (attach != MagickFalse) { /* Attach existing persistent pixel cache. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CacheEvent,GetMagickModule(), "attach persistent cache"); (void) CopyMagickString(cache_info->cache_filename,filename, MaxTextExtent); cache_info->type=DiskCache; cache_info->offset=(*offset); if (OpenPixelCache(image,ReadMode,exception) == MagickFalse) return(MagickFalse); *offset+=cache_info->length+page_size-(cache_info->length % page_size); return(SyncImagePixelCache(image,exception)); } /* Clone persistent pixel cache. */ status=AcquireMagickResource(DiskResource,cache_info->length); if (status == MagickFalse) { (void) ThrowMagickException(exception,GetMagickModule(),CacheError, "CacheResourcesExhausted","`%s'",image->filename); return(MagickFalse); } clone_info=(CacheInfo *) ClonePixelCache(cache_info); clone_info->type=DiskCache; (void) CopyMagickString(clone_info->cache_filename,filename,MaxTextExtent); clone_info->file=(-1); clone_info->storage_class=cache_info->storage_class; clone_info->colorspace=cache_info->colorspace; clone_info->columns=cache_info->columns; clone_info->rows=cache_info->rows; clone_info->active_index_channel=cache_info->active_index_channel; clone_info->mode=PersistMode; clone_info->length=cache_info->length; clone_info->channels=cache_info->channels; clone_info->offset=(*offset); status=ClonePixelCacheRepository(clone_info,cache_info,exception); *offset+=cache_info->length+page_size-(cache_info->length % page_size); clone_info=(CacheInfo *) DestroyPixelCache(clone_info); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + Q u e u e A u t h e n t i c P i x e l C a c h e N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % QueueAuthenticPixelCacheNexus() allocates an region to store image pixels as % defined by the region rectangle and returns a pointer to the region. This % region is subsequently transferred from the pixel cache with % SyncAuthenticPixelsCache(). A pointer to the pixels is returned if the % pixels are transferred, otherwise a NULL is returned. % % The format of the QueueAuthenticPixelCacheNexus() method is: % % PixelPacket *QueueAuthenticPixelCacheNexus(Image *image,const ssize_t x, % const ssize_t y,const size_t columns,const size_t rows, % const MagickBooleanType clone,NexusInfo *nexus_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % % o nexus_info: the cache nexus to set. % % o clone: clone the pixel cache. % % o exception: return any errors or warnings in this structure. % */ MagickExport PixelPacket *QueueAuthenticPixel(Image *image,const ssize_t x, const ssize_t y,const size_t columns,const size_t rows, const MagickBooleanType clone,NexusInfo *nexus_info, ExceptionInfo *exception) { return(QueueAuthenticPixelCacheNexus(image,x,y,columns,rows,clone,nexus_info, exception)); } MagickExport PixelPacket *QueueAuthenticPixelCacheNexus(Image *image, const ssize_t x,const ssize_t y,const size_t columns,const size_t rows, const MagickBooleanType clone,NexusInfo *nexus_info,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; MagickOffsetType offset; MagickSizeType number_pixels; PixelPacket *magick_restrict pixels; RectangleInfo region; /* Validate pixel cache geometry. */ assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) GetImagePixelCache(image,clone,exception); if (cache_info == (Cache) NULL) return((PixelPacket *) NULL); assert(cache_info->signature == MagickCoreSignature); if ((cache_info->columns == 0) || (cache_info->rows == 0) || (x < 0) || (y < 0) || (x >= (ssize_t) cache_info->columns) || (y >= (ssize_t) cache_info->rows)) { (void) ThrowMagickException(exception,GetMagickModule(),CacheError, "PixelsAreNotAuthentic","`%s'",image->filename); return((PixelPacket *) NULL); } offset=(MagickOffsetType) y*cache_info->columns+x; if (offset < 0) return((PixelPacket *) NULL); number_pixels=(MagickSizeType) cache_info->columns*cache_info->rows; offset+=(MagickOffsetType) (rows-1)*cache_info->columns+columns-1; if ((MagickSizeType) offset >= number_pixels) return((PixelPacket *) NULL); /* Return pixel cache. */ region.x=x; region.y=y; region.width=columns; region.height=rows; pixels=SetPixelCacheNexusPixels(cache_info,WriteMode,&region, (image->clip_mask != (Image *) NULL) || (image->mask != (Image *) NULL) ? MagickTrue : MagickFalse,nexus_info,exception); return(pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + Q u e u e A u t h e n t i c P i x e l s C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % QueueAuthenticPixelsCache() allocates an region to store image pixels as % defined by the region rectangle and returns a pointer to the region. This % region is subsequently transferred from the pixel cache with % SyncAuthenticPixelsCache(). A pointer to the pixels is returned if the % pixels are transferred, otherwise a NULL is returned. % % The format of the QueueAuthenticPixelsCache() method is: % % PixelPacket *QueueAuthenticPixelsCache(Image *image,const ssize_t x, % const ssize_t y,const size_t columns,const size_t rows, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % % o exception: return any errors or warnings in this structure. % */ static PixelPacket *QueueAuthenticPixelsCache(Image *image,const ssize_t x, const ssize_t y,const size_t columns,const size_t rows, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); return(QueueAuthenticPixelCacheNexus(image,x,y,columns,rows,MagickFalse, cache_info->nexus_info[id],exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % Q u e u e A u t h e n t i c P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % QueueAuthenticPixels() queues a mutable pixel region. If the region is % successfully initialized a pointer to a PixelPacket array representing the % region is returned, otherwise NULL is returned. The returned pointer may % point to a temporary working buffer for the pixels or it may point to the % final location of the pixels in memory. % % Write-only access means that any existing pixel values corresponding to % the region are ignored. This is useful if the initial image is being % created from scratch, or if the existing pixel values are to be % completely replaced without need to refer to their pre-existing values. % The application is free to read and write the pixel buffer returned by % QueueAuthenticPixels() any way it pleases. QueueAuthenticPixels() does not % initialize the pixel array values. Initializing pixel array values is the % application's responsibility. % % Performance is maximized if the selected region is part of one row, or % one or more full rows, since then there is opportunity to access the % pixels in-place (without a copy) if the image is in memory, or in a % memory-mapped file. The returned pointer must *never* be deallocated % by the user. % % Pixels accessed via the returned pointer represent a simple array of type % PixelPacket. If the image type is CMYK or the storage class is PseudoClass, % call GetAuthenticIndexQueue() after invoking GetAuthenticPixels() to obtain % the black color component or the colormap indexes (of type IndexPacket) % corresponding to the region. Once the PixelPacket (and/or IndexPacket) % array has been updated, the changes must be saved back to the underlying % image using SyncAuthenticPixels() or they may be lost. % % The format of the QueueAuthenticPixels() method is: % % PixelPacket *QueueAuthenticPixels(Image *image,const ssize_t x, % const ssize_t y,const size_t columns,const size_t rows, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % % o exception: return any errors or warnings in this structure. % */ MagickExport PixelPacket *QueueAuthenticPixels(Image *image,const ssize_t x, const ssize_t y,const size_t columns,const size_t rows, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->methods.queue_authentic_pixels_handler != (QueueAuthenticPixelsHandler) NULL) return(cache_info->methods.queue_authentic_pixels_handler(image,x,y,columns, rows,exception)); assert(id < (int) cache_info->number_threads); return(QueueAuthenticPixelCacheNexus(image,x,y,columns,rows,MagickFalse, cache_info->nexus_info[id],exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + R e a d P i x e l C a c h e I n d e x e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadPixelCacheIndexes() reads colormap indexes from the specified region of % the pixel cache. % % The format of the ReadPixelCacheIndexes() method is: % % MagickBooleanType ReadPixelCacheIndexes(CacheInfo *cache_info, % NexusInfo *nexus_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o cache_info: the pixel cache. % % o nexus_info: the cache nexus to read the colormap indexes. % % o exception: return any errors or warnings in this structure. % */ static inline MagickOffsetType ReadPixelCacheRegion( const CacheInfo *magick_restrict cache_info,const MagickOffsetType offset, const MagickSizeType length,unsigned char *magick_restrict buffer) { register MagickOffsetType i; ssize_t count; #if !defined(MAGICKCORE_HAVE_PREAD) if (lseek(cache_info->file,offset,SEEK_SET) < 0) return((MagickOffsetType) -1); #endif count=0; for (i=0; i < (MagickOffsetType) length; i+=count) { #if !defined(MAGICKCORE_HAVE_PREAD) count=read(cache_info->file,buffer+i,(size_t) MagickMin(length-i,(size_t) SSIZE_MAX)); #else count=pread(cache_info->file,buffer+i,(size_t) MagickMin(length-i,(size_t) SSIZE_MAX),(off_t) (offset+i)); #endif if (count <= 0) { count=0; if (errno != EINTR) break; } } return(i); } static MagickBooleanType ReadPixelCacheIndexes( CacheInfo *magick_restrict cache_info,NexusInfo *magick_restrict nexus_info, ExceptionInfo *exception) { MagickOffsetType count, offset; MagickSizeType extent, length; register IndexPacket *magick_restrict q; register ssize_t y; size_t rows; if (cache_info->active_index_channel == MagickFalse) return(MagickFalse); if (nexus_info->authentic_pixel_cache != MagickFalse) return(MagickTrue); offset=(MagickOffsetType) nexus_info->region.y*cache_info->columns+ nexus_info->region.x; length=(MagickSizeType) nexus_info->region.width*sizeof(IndexPacket); rows=nexus_info->region.height; extent=length*rows; q=nexus_info->indexes; y=0; switch (cache_info->type) { case MemoryCache: case MapCache: { register IndexPacket *magick_restrict p; /* Read indexes from memory. */ if ((cache_info->columns == nexus_info->region.width) && (extent == (MagickSizeType) ((size_t) extent))) { length=extent; rows=1UL; } p=cache_info->indexes+offset; for (y=0; y < (ssize_t) rows; y++) { (void) memcpy(q,p,(size_t) length); p+=cache_info->columns; q+=nexus_info->region.width; } break; } case DiskCache: { /* Read indexes from disk. */ LockSemaphoreInfo(cache_info->file_semaphore); if (OpenPixelCacheOnDisk(cache_info,IOMode) == MagickFalse) { ThrowFileException(exception,FileOpenError,"UnableToOpenFile", cache_info->cache_filename); UnlockSemaphoreInfo(cache_info->file_semaphore); return(MagickFalse); } if ((cache_info->columns == nexus_info->region.width) && (extent <= MagickMaxBufferExtent)) { length=extent; rows=1UL; } extent=(MagickSizeType) cache_info->columns*cache_info->rows; for (y=0; y < (ssize_t) rows; y++) { count=ReadPixelCacheRegion(cache_info,cache_info->offset+extent* sizeof(PixelPacket)+offset*sizeof(*q),length,(unsigned char *) q); if (count < (MagickOffsetType) length) break; offset+=cache_info->columns; q+=nexus_info->region.width; } if (IsFileDescriptorLimitExceeded() != MagickFalse) (void) ClosePixelCacheOnDisk(cache_info); UnlockSemaphoreInfo(cache_info->file_semaphore); break; } case DistributedCache: { RectangleInfo region; /* Read indexes from distributed cache. */ LockSemaphoreInfo(cache_info->file_semaphore); region=nexus_info->region; if ((cache_info->columns != nexus_info->region.width) || (extent > MagickMaxBufferExtent)) region.height=1UL; else { length=extent; rows=1UL; } for (y=0; y < (ssize_t) rows; y++) { count=ReadDistributePixelCacheIndexes((DistributeCacheInfo *) cache_info->server_info,&region,length,(unsigned char *) q); if (count != (MagickOffsetType) length) break; q+=nexus_info->region.width; region.y++; } UnlockSemaphoreInfo(cache_info->file_semaphore); break; } default: break; } if (y < (ssize_t) rows) { ThrowFileException(exception,CacheError,"UnableToReadPixelCache", cache_info->cache_filename); return(MagickFalse); } if ((cache_info->debug != MagickFalse) && (CacheTick(nexus_info->region.y,cache_info->rows) != MagickFalse)) (void) LogMagickEvent(CacheEvent,GetMagickModule(), "%s[%.20gx%.20g%+.20g%+.20g]",cache_info->filename,(double) nexus_info->region.width,(double) nexus_info->region.height,(double) nexus_info->region.x,(double) nexus_info->region.y); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + R e a d P i x e l C a c h e P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadPixelCachePixels() reads pixels from the specified region of the pixel % cache. % % The format of the ReadPixelCachePixels() method is: % % MagickBooleanType ReadPixelCachePixels(CacheInfo *cache_info, % NexusInfo *nexus_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o cache_info: the pixel cache. % % o nexus_info: the cache nexus to read the pixels. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType ReadPixelCachePixels( CacheInfo *magick_restrict cache_info,NexusInfo *magick_restrict nexus_info, ExceptionInfo *exception) { MagickOffsetType count, offset; MagickSizeType extent, length; register PixelPacket *magick_restrict q; register ssize_t y; size_t rows; if (nexus_info->authentic_pixel_cache != MagickFalse) return(MagickTrue); offset=(MagickOffsetType) nexus_info->region.y*cache_info->columns; if ((ssize_t) (offset/cache_info->columns) != nexus_info->region.y) return(MagickFalse); offset+=nexus_info->region.x; length=(MagickSizeType) nexus_info->region.width*sizeof(PixelPacket); if ((length/sizeof(PixelPacket)) != nexus_info->region.width) return(MagickFalse); rows=nexus_info->region.height; extent=length*rows; if ((extent == 0) || ((extent/length) != rows)) return(MagickFalse); q=nexus_info->pixels; y=0; switch (cache_info->type) { case MemoryCache: case MapCache: { register PixelPacket *magick_restrict p; /* Read pixels from memory. */ if ((cache_info->columns == nexus_info->region.width) && (extent == (MagickSizeType) ((size_t) extent))) { length=extent; rows=1UL; } p=cache_info->pixels+offset; for (y=0; y < (ssize_t) rows; y++) { (void) memcpy(q,p,(size_t) length); p+=cache_info->columns; q+=nexus_info->region.width; } break; } case DiskCache: { /* Read pixels from disk. */ LockSemaphoreInfo(cache_info->file_semaphore); if (OpenPixelCacheOnDisk(cache_info,IOMode) == MagickFalse) { ThrowFileException(exception,FileOpenError,"UnableToOpenFile", cache_info->cache_filename); UnlockSemaphoreInfo(cache_info->file_semaphore); return(MagickFalse); } if ((cache_info->columns == nexus_info->region.width) && (extent <= MagickMaxBufferExtent)) { length=extent; rows=1UL; } for (y=0; y < (ssize_t) rows; y++) { count=ReadPixelCacheRegion(cache_info,cache_info->offset+offset* sizeof(*q),length,(unsigned char *) q); if (count < (MagickOffsetType) length) break; offset+=cache_info->columns; q+=nexus_info->region.width; } if (IsFileDescriptorLimitExceeded() != MagickFalse) (void) ClosePixelCacheOnDisk(cache_info); UnlockSemaphoreInfo(cache_info->file_semaphore); break; } case DistributedCache: { RectangleInfo region; /* Read pixels from distributed cache. */ LockSemaphoreInfo(cache_info->file_semaphore); region=nexus_info->region; if ((cache_info->columns != nexus_info->region.width) || (extent > MagickMaxBufferExtent)) region.height=1UL; else { length=extent; rows=1UL; } for (y=0; y < (ssize_t) rows; y++) { count=ReadDistributePixelCachePixels((DistributeCacheInfo *) cache_info->server_info,&region,length,(unsigned char *) q); if (count != (MagickOffsetType) length) break; q+=nexus_info->region.width; region.y++; } UnlockSemaphoreInfo(cache_info->file_semaphore); break; } default: break; } if (y < (ssize_t) rows) { ThrowFileException(exception,CacheError,"UnableToReadPixelCache", cache_info->cache_filename); return(MagickFalse); } if ((cache_info->debug != MagickFalse) && (CacheTick(nexus_info->region.y,cache_info->rows) != MagickFalse)) (void) LogMagickEvent(CacheEvent,GetMagickModule(), "%s[%.20gx%.20g%+.20g%+.20g]",cache_info->filename,(double) nexus_info->region.width,(double) nexus_info->region.height,(double) nexus_info->region.x,(double) nexus_info->region.y); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + R e f e r e n c e P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReferencePixelCache() increments the reference count associated with the % pixel cache returning a pointer to the cache. % % The format of the ReferencePixelCache method is: % % Cache ReferencePixelCache(Cache cache_info) % % A description of each parameter follows: % % o cache_info: the pixel cache. % */ MagickExport Cache ReferencePixelCache(Cache cache) { CacheInfo *magick_restrict cache_info; assert(cache != (Cache *) NULL); cache_info=(CacheInfo *) cache; assert(cache_info->signature == MagickCoreSignature); LockSemaphoreInfo(cache_info->semaphore); cache_info->reference_count++; UnlockSemaphoreInfo(cache_info->semaphore); return(cache_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + R e s e t P i x e l C a c h e E p o c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ResetPixelCacheEpoch() resets the pixel cache epoch. % % The format of the ResetPixelCacheEpoch method is: % % void ResetPixelCacheEpoch(void) % */ MagickPrivate void ResetPixelCacheEpoch(void) { cache_epoch=0; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + S e t P i x e l C a c h e M e t h o d s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetPixelCacheMethods() sets the image pixel methods to the specified ones. % % The format of the SetPixelCacheMethods() method is: % % SetPixelCacheMethods(Cache *,CacheMethods *cache_methods) % % A description of each parameter follows: % % o cache: the pixel cache. % % o cache_methods: Specifies a pointer to a CacheMethods structure. % */ MagickExport void SetPixelCacheMethods(Cache cache,CacheMethods *cache_methods) { CacheInfo *magick_restrict cache_info; GetOneAuthenticPixelFromHandler get_one_authentic_pixel_from_handler; GetOneVirtualPixelFromHandler get_one_virtual_pixel_from_handler; /* Set cache pixel methods. */ assert(cache != (Cache) NULL); assert(cache_methods != (CacheMethods *) NULL); cache_info=(CacheInfo *) cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", cache_info->filename); if (cache_methods->get_virtual_pixel_handler != (GetVirtualPixelHandler) NULL) cache_info->methods.get_virtual_pixel_handler= cache_methods->get_virtual_pixel_handler; if (cache_methods->destroy_pixel_handler != (DestroyPixelHandler) NULL) cache_info->methods.destroy_pixel_handler= cache_methods->destroy_pixel_handler; if (cache_methods->get_virtual_indexes_from_handler != (GetVirtualIndexesFromHandler) NULL) cache_info->methods.get_virtual_indexes_from_handler= cache_methods->get_virtual_indexes_from_handler; if (cache_methods->get_authentic_pixels_handler != (GetAuthenticPixelsHandler) NULL) cache_info->methods.get_authentic_pixels_handler= cache_methods->get_authentic_pixels_handler; if (cache_methods->queue_authentic_pixels_handler != (QueueAuthenticPixelsHandler) NULL) cache_info->methods.queue_authentic_pixels_handler= cache_methods->queue_authentic_pixels_handler; if (cache_methods->sync_authentic_pixels_handler != (SyncAuthenticPixelsHandler) NULL) cache_info->methods.sync_authentic_pixels_handler= cache_methods->sync_authentic_pixels_handler; if (cache_methods->get_authentic_pixels_from_handler != (GetAuthenticPixelsFromHandler) NULL) cache_info->methods.get_authentic_pixels_from_handler= cache_methods->get_authentic_pixels_from_handler; if (cache_methods->get_authentic_indexes_from_handler != (GetAuthenticIndexesFromHandler) NULL) cache_info->methods.get_authentic_indexes_from_handler= cache_methods->get_authentic_indexes_from_handler; get_one_virtual_pixel_from_handler= cache_info->methods.get_one_virtual_pixel_from_handler; if (get_one_virtual_pixel_from_handler != (GetOneVirtualPixelFromHandler) NULL) cache_info->methods.get_one_virtual_pixel_from_handler= cache_methods->get_one_virtual_pixel_from_handler; get_one_authentic_pixel_from_handler= cache_methods->get_one_authentic_pixel_from_handler; if (get_one_authentic_pixel_from_handler != (GetOneAuthenticPixelFromHandler) NULL) cache_info->methods.get_one_authentic_pixel_from_handler= cache_methods->get_one_authentic_pixel_from_handler; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + S e t P i x e l C a c h e N e x u s P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetPixelCacheNexusPixels() defines the region of the cache for the % specified cache nexus. % % The format of the SetPixelCacheNexusPixels() method is: % % PixelPacket SetPixelCacheNexusPixels(const CacheInfo *cache_info, % const MapMode mode,const RectangleInfo *region, % const MagickBooleanType buffered,NexusInfo *nexus_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o cache_info: the pixel cache. % % o mode: ReadMode, WriteMode, or IOMode. % % o region: A pointer to the RectangleInfo structure that defines the % region of this particular cache nexus. % % o buffered: pixels are buffered. % % o nexus_info: the cache nexus to set. % % o exception: return any errors or warnings in this structure. % */ static inline MagickBooleanType AcquireCacheNexusPixels( const CacheInfo *magick_restrict cache_info,NexusInfo *nexus_info, ExceptionInfo *exception) { if (nexus_info->length != (MagickSizeType) ((size_t) nexus_info->length)) return(MagickFalse); if (cache_anonymous_memory <= 0) { nexus_info->mapped=MagickFalse; nexus_info->cache=(PixelPacket *) MagickAssumeAligned( AcquireAlignedMemory(1,(size_t) nexus_info->length)); if (nexus_info->cache != (PixelPacket *) NULL) (void) memset(nexus_info->cache,0,(size_t) nexus_info->length); } else { nexus_info->mapped=MagickTrue; nexus_info->cache=(PixelPacket *) MapBlob(-1,IOMode,0,(size_t) nexus_info->length); } if (nexus_info->cache == (PixelPacket *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", cache_info->filename); return(MagickFalse); } return(MagickTrue); } static inline MagickBooleanType IsAuthenticPixelCache( const CacheInfo *magick_restrict cache_info, const NexusInfo *magick_restrict nexus_info) { MagickBooleanType status; MagickOffsetType offset; /* Does nexus pixels point directly to in-core cache pixels or is it buffered? */ if (cache_info->type == PingCache) return(MagickTrue); offset=(MagickOffsetType) nexus_info->region.y*cache_info->columns+ nexus_info->region.x; status=nexus_info->pixels == (cache_info->pixels+offset) ? MagickTrue : MagickFalse; return(status); } static inline void PrefetchPixelCacheNexusPixels(const NexusInfo *nexus_info, const MapMode mode) { magick_unreferenced(nexus_info); magick_unreferenced(mode); if (mode == ReadMode) { MagickCachePrefetch((unsigned char *) nexus_info->pixels,0,1); return; } MagickCachePrefetch((unsigned char *) nexus_info->pixels,1,1); } static PixelPacket *SetPixelCacheNexusPixels(const CacheInfo *cache_info, const MapMode mode,const RectangleInfo *region, const MagickBooleanType buffered,NexusInfo *nexus_info, ExceptionInfo *exception) { MagickBooleanType status; MagickSizeType length, number_pixels; assert(cache_info != (const CacheInfo *) NULL); assert(cache_info->signature == MagickCoreSignature); if (cache_info->type == UndefinedCache) return((PixelPacket *) NULL); if ((region->width == 0) || (region->height == 0)) return((PixelPacket *) NULL); nexus_info->region=(*region); if (((cache_info->type == MemoryCache) || (cache_info->type == MapCache)) && (buffered == MagickFalse)) { ssize_t x, y; x=nexus_info->region.x+(ssize_t) nexus_info->region.width-1; y=nexus_info->region.y+(ssize_t) nexus_info->region.height-1; if (((nexus_info->region.x >= 0) && (nexus_info->region.y >= 0) && (y < (ssize_t) cache_info->rows)) && (((nexus_info->region.x == 0) && (nexus_info->region.width == cache_info->columns)) || ((nexus_info->region.height == 1) && (x < (ssize_t) cache_info->columns)))) { MagickOffsetType offset; /* Pixels are accessed directly from memory. */ offset=(MagickOffsetType) nexus_info->region.y*cache_info->columns+ nexus_info->region.x; nexus_info->pixels=cache_info->pixels+offset; nexus_info->indexes=(IndexPacket *) NULL; if (cache_info->active_index_channel != MagickFalse) nexus_info->indexes=cache_info->indexes+offset; PrefetchPixelCacheNexusPixels(nexus_info,mode); nexus_info->authentic_pixel_cache=IsAuthenticPixelCache(cache_info, nexus_info); return(nexus_info->pixels); } } /* Pixels are stored in a staging region until they are synced to the cache. */ number_pixels=(MagickSizeType) nexus_info->region.width* nexus_info->region.height; length=number_pixels*sizeof(PixelPacket); if (cache_info->active_index_channel != MagickFalse) length+=number_pixels*sizeof(IndexPacket); if (nexus_info->cache == (PixelPacket *) NULL) { nexus_info->length=length; status=AcquireCacheNexusPixels(cache_info,nexus_info,exception); if (status == MagickFalse) { nexus_info->length=0; return((PixelPacket *) NULL); } } else if (nexus_info->length < length) { RelinquishCacheNexusPixels(nexus_info); nexus_info->length=length; status=AcquireCacheNexusPixels(cache_info,nexus_info,exception); if (status == MagickFalse) { nexus_info->length=0; return((PixelPacket *) NULL); } } nexus_info->pixels=nexus_info->cache; nexus_info->indexes=(IndexPacket *) NULL; if (cache_info->active_index_channel != MagickFalse) nexus_info->indexes=(IndexPacket *) (nexus_info->pixels+number_pixels); PrefetchPixelCacheNexusPixels(nexus_info,mode); nexus_info->authentic_pixel_cache=IsAuthenticPixelCache(cache_info, nexus_info); return(nexus_info->pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t P i x e l C a c h e V i r t u a l M e t h o d % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetPixelCacheVirtualMethod() sets the "virtual pixels" method for the % pixel cache and returns the previous setting. A virtual pixel is any pixel % access that is outside the boundaries of the image cache. % % The format of the SetPixelCacheVirtualMethod() method is: % % VirtualPixelMethod SetPixelCacheVirtualMethod(const Image *image, % const VirtualPixelMethod virtual_pixel_method) % % A description of each parameter follows: % % o image: the image. % % o virtual_pixel_method: choose the type of virtual pixel. % */ static MagickBooleanType SetCacheAlphaChannel(Image *image, const Quantum opacity) { CacheInfo *magick_restrict cache_info; CacheView *magick_restrict image_view; MagickBooleanType status; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); image->matte=MagickTrue; status=MagickTrue; image_view=AcquireVirtualCacheView(image,&image->exception); /* must be virtual */ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, &image->exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { q->opacity=opacity; q++; } status=SyncCacheViewAuthenticPixels(image_view,&image->exception); } image_view=DestroyCacheView(image_view); return(status); } MagickExport VirtualPixelMethod SetPixelCacheVirtualMethod(const Image *image, const VirtualPixelMethod virtual_pixel_method) { CacheInfo *magick_restrict cache_info; VirtualPixelMethod method; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); method=cache_info->virtual_pixel_method; cache_info->virtual_pixel_method=virtual_pixel_method; if ((image->columns != 0) && (image->rows != 0)) switch (virtual_pixel_method) { case BackgroundVirtualPixelMethod: { if ((image->background_color.opacity != OpaqueOpacity) && (image->matte == MagickFalse)) (void) SetCacheAlphaChannel((Image *) image,OpaqueOpacity); if ((IsPixelGray(&image->background_color) == MagickFalse) && (IsGrayColorspace(image->colorspace) != MagickFalse)) (void) SetImageColorspace((Image *) image,sRGBColorspace); break; } case TransparentVirtualPixelMethod: { if (image->matte == MagickFalse) (void) SetCacheAlphaChannel((Image *) image,OpaqueOpacity); break; } default: break; } return(method); } #if defined(MAGICKCORE_OPENCL_SUPPORT) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + S y n c A u t h e n t i c O p e n C L B u f f e r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SyncAuthenticOpenCLBuffer() ensures all the OpenCL operations have been % completed and updates the host memory. % % The format of the SyncAuthenticOpenCLBuffer() method is: % % void SyncAuthenticOpenCLBuffer(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ static void CopyOpenCLBuffer(CacheInfo *magick_restrict cache_info) { MagickCLEnv clEnv; assert(cache_info != (CacheInfo *)NULL); if ((cache_info->type != MemoryCache) || (cache_info->opencl == (OpenCLCacheInfo *)NULL)) return; /* Ensure single threaded access to OpenCL environment. */ LockSemaphoreInfo(cache_info->semaphore); if (cache_info->opencl != (OpenCLCacheInfo *)NULL) { cl_event *events; cl_uint event_count; clEnv=GetDefaultOpenCLEnv(); events=CopyOpenCLEvents(cache_info->opencl,&event_count); if (events != (cl_event *) NULL) { cl_command_queue queue; cl_context context; cl_int status; PixelPacket *pixels; context=GetOpenCLContext(clEnv); queue=AcquireOpenCLCommandQueue(clEnv); pixels=(PixelPacket *) clEnv->library->clEnqueueMapBuffer(queue, cache_info->opencl->buffer,CL_TRUE, CL_MAP_READ | CL_MAP_WRITE,0, cache_info->length,event_count,events,NULL,&status); assert(pixels == cache_info->pixels); events=(cl_event *) RelinquishMagickMemory(events); RelinquishOpenCLCommandQueue(clEnv,queue); } cache_info->opencl=RelinquishOpenCLCacheInfo(clEnv,cache_info->opencl); } UnlockSemaphoreInfo(cache_info->semaphore); } MagickPrivate void SyncAuthenticOpenCLBuffer(const Image *image) { CacheInfo *magick_restrict cache_info; assert(image != (Image *)NULL); cache_info = (CacheInfo *)image->cache; CopyOpenCLBuffer(cache_info); } #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + S y n c A u t h e n t i c P i x e l C a c h e N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SyncAuthenticPixelCacheNexus() saves the authentic image pixels to the % in-memory or disk cache. The method returns MagickTrue if the pixel region % is synced, otherwise MagickFalse. % % The format of the SyncAuthenticPixelCacheNexus() method is: % % MagickBooleanType SyncAuthenticPixelCacheNexus(Image *image, % NexusInfo *nexus_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o nexus_info: the cache nexus to sync. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType SyncAuthenticPixelCacheNexus(Image *image, NexusInfo *magick_restrict nexus_info,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; MagickBooleanType status; /* Transfer pixels to the cache. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->cache == (Cache) NULL) ThrowBinaryException(CacheError,"PixelCacheIsNotOpen",image->filename); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->type == UndefinedCache) return(MagickFalse); if ((image->storage_class == DirectClass) && (image->clip_mask != (Image *) NULL) && (ClipPixelCacheNexus(image,nexus_info,exception) == MagickFalse)) return(MagickFalse); if ((image->storage_class == DirectClass) && (image->mask != (Image *) NULL) && (MaskPixelCacheNexus(image,nexus_info,exception) == MagickFalse)) return(MagickFalse); if (nexus_info->authentic_pixel_cache != MagickFalse) { image->taint=MagickTrue; return(MagickTrue); } assert(cache_info->signature == MagickCoreSignature); status=WritePixelCachePixels(cache_info,nexus_info,exception); if ((cache_info->active_index_channel != MagickFalse) && (WritePixelCacheIndexes(cache_info,nexus_info,exception) == MagickFalse)) return(MagickFalse); if (status != MagickFalse) image->taint=MagickTrue; return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + S y n c A u t h e n t i c P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SyncAuthenticPixelsCache() saves the authentic image pixels to the in-memory % or disk cache. The method returns MagickTrue if the pixel region is synced, % otherwise MagickFalse. % % The format of the SyncAuthenticPixelsCache() method is: % % MagickBooleanType SyncAuthenticPixelsCache(Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType SyncAuthenticPixelsCache(Image *image, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); MagickBooleanType status; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); status=SyncAuthenticPixelCacheNexus(image,cache_info->nexus_info[id], exception); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S y n c A u t h e n t i c P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SyncAuthenticPixels() saves the image pixels to the in-memory or disk cache. % The method returns MagickTrue if the pixel region is flushed, otherwise % MagickFalse. % % The format of the SyncAuthenticPixels() method is: % % MagickBooleanType SyncAuthenticPixels(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 MagickBooleanType SyncAuthenticPixels(Image *image, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); MagickBooleanType status; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->methods.sync_authentic_pixels_handler != (SyncAuthenticPixelsHandler) NULL) return(cache_info->methods.sync_authentic_pixels_handler(image,exception)); assert(id < (int) cache_info->number_threads); status=SyncAuthenticPixelCacheNexus(image,cache_info->nexus_info[id], exception); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + S y n c I m a g e P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SyncImagePixelCache() saves the image pixels to the in-memory or disk cache. % The method returns MagickTrue if the pixel region is flushed, otherwise % MagickFalse. % % The format of the SyncImagePixelCache() method is: % % MagickBooleanType SyncImagePixelCache(Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickPrivate MagickBooleanType SyncImagePixelCache(Image *image, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; assert(image != (Image *) NULL); assert(exception != (ExceptionInfo *) NULL); cache_info=(CacheInfo *) GetImagePixelCache(image,MagickTrue,exception); return(cache_info == (CacheInfo *) NULL ? MagickFalse : MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + W r i t e P i x e l C a c h e I n d e x e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WritePixelCacheIndexes() writes the colormap indexes to the specified % region of the pixel cache. % % The format of the WritePixelCacheIndexes() method is: % % MagickBooleanType WritePixelCacheIndexes(CacheInfo *cache_info, % NexusInfo *nexus_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o cache_info: the pixel cache. % % o nexus_info: the cache nexus to write the colormap indexes. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType WritePixelCacheIndexes(CacheInfo *cache_info, NexusInfo *magick_restrict nexus_info,ExceptionInfo *exception) { MagickOffsetType count, offset; MagickSizeType extent, length; register const IndexPacket *magick_restrict p; register ssize_t y; size_t rows; if (cache_info->active_index_channel == MagickFalse) return(MagickFalse); if (nexus_info->authentic_pixel_cache != MagickFalse) return(MagickTrue); offset=(MagickOffsetType) nexus_info->region.y*cache_info->columns+ nexus_info->region.x; length=(MagickSizeType) nexus_info->region.width*sizeof(IndexPacket); rows=nexus_info->region.height; extent=(MagickSizeType) length*rows; p=nexus_info->indexes; y=0; switch (cache_info->type) { case MemoryCache: case MapCache: { register IndexPacket *magick_restrict q; /* Write indexes to memory. */ if ((cache_info->columns == nexus_info->region.width) && (extent == (MagickSizeType) ((size_t) extent))) { length=extent; rows=1UL; } q=cache_info->indexes+offset; for (y=0; y < (ssize_t) rows; y++) { (void) memcpy(q,p,(size_t) length); p+=nexus_info->region.width; q+=cache_info->columns; } break; } case DiskCache: { /* Write indexes to disk. */ LockSemaphoreInfo(cache_info->file_semaphore); if (OpenPixelCacheOnDisk(cache_info,IOMode) == MagickFalse) { ThrowFileException(exception,FileOpenError,"UnableToOpenFile", cache_info->cache_filename); UnlockSemaphoreInfo(cache_info->file_semaphore); return(MagickFalse); } if ((cache_info->columns == nexus_info->region.width) && (extent <= MagickMaxBufferExtent)) { length=extent; rows=1UL; } extent=(MagickSizeType) cache_info->columns*cache_info->rows; for (y=0; y < (ssize_t) rows; y++) { count=WritePixelCacheRegion(cache_info,cache_info->offset+extent* sizeof(PixelPacket)+offset*sizeof(*p),length,(const unsigned char *) p); if (count < (MagickOffsetType) length) break; p+=nexus_info->region.width; offset+=cache_info->columns; } if (IsFileDescriptorLimitExceeded() != MagickFalse) (void) ClosePixelCacheOnDisk(cache_info); UnlockSemaphoreInfo(cache_info->file_semaphore); break; } case DistributedCache: { RectangleInfo region; /* Write indexes to distributed cache. */ LockSemaphoreInfo(cache_info->file_semaphore); region=nexus_info->region; if ((cache_info->columns != nexus_info->region.width) || (extent > MagickMaxBufferExtent)) region.height=1UL; else { length=extent; rows=1UL; } for (y=0; y < (ssize_t) rows; y++) { count=WriteDistributePixelCacheIndexes((DistributeCacheInfo *) cache_info->server_info,&region,length,(const unsigned char *) p); if (count != (MagickOffsetType) length) break; p+=nexus_info->region.width; region.y++; } UnlockSemaphoreInfo(cache_info->file_semaphore); break; } default: break; } if (y < (ssize_t) rows) { ThrowFileException(exception,CacheError,"UnableToWritePixelCache", cache_info->cache_filename); return(MagickFalse); } if ((cache_info->debug != MagickFalse) && (CacheTick(nexus_info->region.y,cache_info->rows) != MagickFalse)) (void) LogMagickEvent(CacheEvent,GetMagickModule(), "%s[%.20gx%.20g%+.20g%+.20g]",cache_info->filename,(double) nexus_info->region.width,(double) nexus_info->region.height,(double) nexus_info->region.x,(double) nexus_info->region.y); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + W r i t e P i x e l C a c h e P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WritePixelCachePixels() writes image pixels to the specified region of the % pixel cache. % % The format of the WritePixelCachePixels() method is: % % MagickBooleanType WritePixelCachePixels(CacheInfo *cache_info, % NexusInfo *nexus_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o cache_info: the pixel cache. % % o nexus_info: the cache nexus to write the pixels. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType WritePixelCachePixels(CacheInfo *cache_info, NexusInfo *magick_restrict nexus_info,ExceptionInfo *exception) { MagickOffsetType count, offset; MagickSizeType extent, length; register const PixelPacket *magick_restrict p; register ssize_t y; size_t rows; if (nexus_info->authentic_pixel_cache != MagickFalse) return(MagickTrue); offset=(MagickOffsetType) nexus_info->region.y*cache_info->columns+ nexus_info->region.x; length=(MagickSizeType) nexus_info->region.width*sizeof(PixelPacket); rows=nexus_info->region.height; extent=length*rows; p=nexus_info->pixels; y=0; switch (cache_info->type) { case MemoryCache: case MapCache: { register PixelPacket *magick_restrict q; /* Write pixels to memory. */ if ((cache_info->columns == nexus_info->region.width) && (extent == (MagickSizeType) ((size_t) extent))) { length=extent; rows=1UL; } q=cache_info->pixels+offset; for (y=0; y < (ssize_t) rows; y++) { (void) memcpy(q,p,(size_t) length); p+=nexus_info->region.width; q+=cache_info->columns; } break; } case DiskCache: { /* Write pixels to disk. */ LockSemaphoreInfo(cache_info->file_semaphore); if (OpenPixelCacheOnDisk(cache_info,IOMode) == MagickFalse) { ThrowFileException(exception,FileOpenError,"UnableToOpenFile", cache_info->cache_filename); UnlockSemaphoreInfo(cache_info->file_semaphore); return(MagickFalse); } if ((cache_info->columns == nexus_info->region.width) && (extent <= MagickMaxBufferExtent)) { length=extent; rows=1UL; } for (y=0; y < (ssize_t) rows; y++) { count=WritePixelCacheRegion(cache_info,cache_info->offset+offset* sizeof(*p),length,(const unsigned char *) p); if (count < (MagickOffsetType) length) break; p+=nexus_info->region.width; offset+=cache_info->columns; } if (IsFileDescriptorLimitExceeded() != MagickFalse) (void) ClosePixelCacheOnDisk(cache_info); UnlockSemaphoreInfo(cache_info->file_semaphore); break; } case DistributedCache: { RectangleInfo region; /* Write pixels to distributed cache. */ LockSemaphoreInfo(cache_info->file_semaphore); region=nexus_info->region; if ((cache_info->columns != nexus_info->region.width) || (extent > MagickMaxBufferExtent)) region.height=1UL; else { length=extent; rows=1UL; } for (y=0; y < (ssize_t) rows; y++) { count=WriteDistributePixelCachePixels((DistributeCacheInfo *) cache_info->server_info,&region,length,(const unsigned char *) p); if (count != (MagickOffsetType) length) break; p+=nexus_info->region.width; region.y++; } UnlockSemaphoreInfo(cache_info->file_semaphore); break; } default: break; } if (y < (ssize_t) rows) { ThrowFileException(exception,CacheError,"UnableToWritePixelCache", cache_info->cache_filename); return(MagickFalse); } if ((cache_info->debug != MagickFalse) && (CacheTick(nexus_info->region.y,cache_info->rows) != MagickFalse)) (void) LogMagickEvent(CacheEvent,GetMagickModule(), "%s[%.20gx%.20g%+.20g%+.20g]",cache_info->filename,(double) nexus_info->region.width,(double) nexus_info->region.height,(double) nexus_info->region.x,(double) nexus_info->region.y); return(MagickTrue); }
GB_binop__isle_uint16.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__isle_uint16) // A.*B function (eWiseMult): GB (_AemultB_08__isle_uint16) // A.*B function (eWiseMult): GB (_AemultB_02__isle_uint16) // A.*B function (eWiseMult): GB (_AemultB_04__isle_uint16) // A.*B function (eWiseMult): GB (_AemultB_bitmap__isle_uint16) // A*D function (colscale): GB (_AxD__isle_uint16) // D*A function (rowscale): GB (_DxB__isle_uint16) // C+=B function (dense accum): GB (_Cdense_accumB__isle_uint16) // C+=b function (dense accum): GB (_Cdense_accumb__isle_uint16) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__isle_uint16) // C=scalar+B GB (_bind1st__isle_uint16) // C=scalar+B' GB (_bind1st_tran__isle_uint16) // C=A+scalar GB (_bind2nd__isle_uint16) // C=A'+scalar GB (_bind2nd_tran__isle_uint16) // C type: uint16_t // A type: uint16_t // B,b type: uint16_t // BinaryOp: cij = (aij <= bij) #define GB_ATYPE \ uint16_t #define GB_BTYPE \ uint16_t #define GB_CTYPE \ uint16_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) \ uint16_t aij = GBX (Ax, pA, A_iso) // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ uint16_t bij = GBX (Bx, pB, B_iso) // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ uint16_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_ISLE || GxB_NO_UINT16 || GxB_NO_ISLE_UINT16) //------------------------------------------------------------------------------ // 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__isle_uint16) ( 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__isle_uint16) ( 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__isle_uint16) ( 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 uint16_t uint16_t bwork = (*((uint16_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__isle_uint16) ( 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 uint16_t *restrict Cx = (uint16_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__isle_uint16) ( 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 uint16_t *restrict Cx = (uint16_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__isle_uint16) ( 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, C<M>=A.*B, or C<M!>=A.*B where C is sparse/hyper //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_08__isle_uint16) ( 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__isle_uint16) ( 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__isle_uint16) ( 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__isle_uint16) ( 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__isle_uint16) ( 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 uint16_t *Cx = (uint16_t *) Cx_output ; uint16_t x = (*((uint16_t *) x_input)) ; uint16_t *Bx = (uint16_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 ; uint16_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__isle_uint16) ( 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 ; uint16_t *Cx = (uint16_t *) Cx_output ; uint16_t *Ax = (uint16_t *) Ax_input ; uint16_t y = (*((uint16_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; uint16_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) \ { \ uint16_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (x <= aij) ; \ } GrB_Info GB (_bind1st_tran__isle_uint16) ( 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 \ uint16_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint16_t x = (*((const uint16_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ uint16_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) \ { \ uint16_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (aij <= y) ; \ } GrB_Info GB (_bind2nd_tran__isle_uint16) ( 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 uint16_t y = (*((const uint16_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
light.h
/* light.h */ #include "mytypes.h" /******************************************************************************/ /* Access macros */ /* light */ #define t0(a,b,c) t0[CELTNDX(a,b,c)] #define t0_sav(a,b,c) t0_sav[CELTNDX(a,b,c)] #define t2(a,b,c) t2[CELTNDX(a,b,c)] /* t0_big has NO guard zones and is nxfull-by-nyfull zones in xy */ #define t0_big(i,j,k) t0_big[(((k)*nyfull + (j))*nxfull + (i))] /* tN_new is nxl-by-nyl-by-nzl (no guard zones) */ #define tN_new(a,b,c) tN_new[CELTNDX3(a,b,c)] /******************************************************************************/ /* Light Functions */ void reset_tvar(rcomplex * restrict tvar, rcomplex * restrict tvar_sav); void reset_tvar_omp45(rcomplex * restrict tvar); void get_tvar_omp45(rcomplex * restrict tvar); void reset_t0_big(rcomplex * restrict tbig, rcomplex * restrict tbig_sav); /* perform rotation using Buneman's method */ void rotth_z_merge(rcomplex * restrict ct0wk, real * restrict thetb, int izlo, int izhi); void rotth_z_merge3(rcomplex * restrict ct0wk, real * restrict thetb, int izlo, int izhi); #ifdef _OPENMP #pragma omp declare target #endif void rotth_omp45(rcomplex * restrict tvar, real * restrict thetb, int iz); void rotth_omp45_pre3D(int nzl, rcomplex * restrict tvar, real * restrict thetb, int izlo, int izhi); #ifdef _OPENMP #pragma omp end declare target #endif void rotth_mult_omp45(int nzl, rcomplex * restrict tvar, real * restrict thetb); void rotth_mult_omp45_pre(int nzl, rcomplex * restrict tvar, real * restrict thetb); void rotth_premap(rcomplex * restrict tvar, real * restrict thetb); void rotth_unmap(rcomplex * restrict tvar, real * restrict thetb); void couple_z(rcomplex * restrict t0, rcomplex * restrict t2, rcomplex * restrict denp); void couple_z_merge3(rcomplex * restrict t0, rcomplex * restrict t2, rcomplex * restrict denp); void couple_omp45(rcomplex * restrict t0, rcomplex * restrict t2, rcomplex * restrict denp); void couple_premap(rcomplex * restrict t0, rcomplex * restrict t2, rcomplex * restrict denp); void couple_unmap(rcomplex * restrict t0, rcomplex * restrict t2, rcomplex * restrict denp); void couple_omp45_pre(rcomplex * restrict t0, rcomplex * restrict t2, rcomplex * restrict denp); void couple_omp45_pre_simd(rcomplex * restrict t0, rcomplex * restrict t2, rcomplex * restrict denp);
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] = 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); 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; }
GB_binop__lxor_int64.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__lxor_int64) // A.*B function (eWiseMult): GB (_AemultB_08__lxor_int64) // A.*B function (eWiseMult): GB (_AemultB_02__lxor_int64) // A.*B function (eWiseMult): GB (_AemultB_04__lxor_int64) // A.*B function (eWiseMult): GB (_AemultB_bitmap__lxor_int64) // A*D function (colscale): GB (_AxD__lxor_int64) // D*A function (rowscale): GB (_DxB__lxor_int64) // C+=B function (dense accum): GB (_Cdense_accumB__lxor_int64) // C+=b function (dense accum): GB (_Cdense_accumb__lxor_int64) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__lxor_int64) // C=scalar+B GB (_bind1st__lxor_int64) // C=scalar+B' GB (_bind1st_tran__lxor_int64) // C=A+scalar GB (_bind2nd__lxor_int64) // C=A'+scalar GB (_bind2nd_tran__lxor_int64) // C type: int64_t // A type: int64_t // A pattern? 0 // B type: int64_t // B pattern? 0 // BinaryOp: cij = ((aij != 0) != (bij != 0)) #define GB_ATYPE \ int64_t #define GB_BTYPE \ int64_t #define GB_CTYPE \ int64_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) \ int64_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) \ int64_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) \ int64_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_LXOR || GxB_NO_INT64 || GxB_NO_LXOR_INT64) //------------------------------------------------------------------------------ // 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__lxor_int64) ( 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__lxor_int64) ( 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__lxor_int64) ( 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 int64_t int64_t bwork = (*((int64_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__lxor_int64) ( 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 int64_t *restrict Cx = (int64_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__lxor_int64) ( GrB_Matrix C, const GrB_Matrix D, const GrB_Matrix B, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t *restrict Cx = (int64_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__lxor_int64) ( 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) ; int64_t alpha_scalar ; int64_t beta_scalar ; if (is_eWiseUnion) { alpha_scalar = (*((int64_t *) alpha_scalar_in)) ; beta_scalar = (*((int64_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__lxor_int64) ( 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__lxor_int64) ( 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__lxor_int64) ( 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__lxor_int64) ( 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__lxor_int64) ( 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 int64_t *Cx = (int64_t *) Cx_output ; int64_t x = (*((int64_t *) x_input)) ; int64_t *Bx = (int64_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 ; int64_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__lxor_int64) ( 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 ; int64_t *Cx = (int64_t *) Cx_output ; int64_t *Ax = (int64_t *) Ax_input ; int64_t y = (*((int64_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; int64_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) \ { \ int64_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = ((x != 0) != (aij != 0)) ; \ } GrB_Info GB (_bind1st_tran__lxor_int64) ( 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 \ int64_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t x = (*((const int64_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ int64_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) \ { \ int64_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = ((aij != 0) != (y != 0)) ; \ } GrB_Info GB (_bind2nd_tran__lxor_int64) ( 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 int64_t y = (*((const int64_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
DRB040-truedepsingleelement-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: liao6@llnl.gov, lin32@llnl.gov, asplund1@llnl.gov, schordan1@llnl.gov, karlin1@llnl.gov) 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. */ /* Data race pair: a[i]@63:5 vs. a[0]@63:15 */ #include <stdlib.h> int main (int argc, char* argv[]) { int len=1000; int i; if (argc>1) len = atoi(argv[1]); int a[len]; #pragma omp parallel for private(i ) for (i=0;i<len;i++) a[i]=i; a[0] = 2; for (i=0;i<len;i++) a[i]=a[i]+a[0]; for (i=0;i<len;i++) printf("%d\n", a[i]); return 0; }
nvptx_target_printf_codegen.c
// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py UTC_ARGS: --function-signature --include-generated-funcs --replace-value-regex "__omp_offloading_[0-9a-z]+_[0-9a-z]+" "reduction_size[.].+[.]" "pl_cond[.].+[.|,]" --prefix-filecheck-ir-name _ // Test target codegen - host bc file has to be created first. // RUN: %clang_cc1 -no-opaque-pointers -verify -fopenmp -x c -triple powerpc64le-unknown-unknown -fopenmp-targets=nvptx64-nvidia-cuda -emit-llvm-bc %s -o %t-ppc-host.bc // RUN: %clang_cc1 -no-opaque-pointers -verify -fopenmp -x c -triple nvptx64-unknown-unknown -fopenmp-targets=nvptx64-nvidia-cuda -emit-llvm %s -fopenmp-is-device -fopenmp-host-ir-file-path %t-ppc-host.bc -o - | FileCheck %s --check-prefix CHECK --check-prefix CHECK-64 // RUN: %clang_cc1 -no-opaque-pointers -verify -fopenmp -x c -triple i386-unknown-unknown -fopenmp-targets=nvptx-nvidia-cuda -emit-llvm-bc %s -o %t-x86-host.bc // RUN: %clang_cc1 -no-opaque-pointers -verify -fopenmp -x c -triple nvptx-unknown-unknown -fopenmp-targets=nvptx-nvidia-cuda -emit-llvm %s -fopenmp-is-device -fopenmp-host-ir-file-path %t-x86-host.bc -o - | FileCheck %s --check-prefix CHECK --check-prefix CHECK-32 // expected-no-diagnostics extern int printf(const char *, ...); // Check a simple call to printf end-to-end. int CheckSimple(void) { #pragma omp target { // printf in master-only basic block. const char* fmt = "%d %lld %f"; printf(fmt, 1, 2ll, 3.0); } return 0; } void CheckNoArgs(void) { #pragma omp target { // printf in master-only basic block. printf("hello, world!"); } } // Check that printf's alloca happens in the entry block, not inside the if // statement. int foo; void CheckAllocaIsInEntryBlock(void) { #pragma omp target { if (foo) { printf("%d", 42); } } } // // // // CHECK-64-LABEL: define {{[^@]+}}@{{__omp_offloading_[0-9a-z]+_[0-9a-z]+}}_CheckSimple_l13 // CHECK-64-SAME: () #[[ATTR0:[0-9]+]] { // CHECK-64-NEXT: entry: // CHECK-64-NEXT: [[FMT:%.*]] = alloca i8*, align 8 // CHECK-64-NEXT: [[TMP:%.*]] = alloca [[PRINTF_ARGS:%.*]], align 8 // CHECK-64-NEXT: [[TMP0:%.*]] = call i32 @__kmpc_target_init(%struct.ident_t* @[[GLOB1:[0-9]+]], i8 1, i1 true, i1 true) // CHECK-64-NEXT: [[EXEC_USER_CODE:%.*]] = icmp eq i32 [[TMP0]], -1 // CHECK-64-NEXT: br i1 [[EXEC_USER_CODE]], label [[USER_CODE_ENTRY:%.*]], label [[WORKER_EXIT:%.*]] // CHECK-64: user_code.entry: // CHECK-64-NEXT: store i8* getelementptr inbounds ([11 x i8], [11 x i8]* @.str, i64 0, i64 0), i8** [[FMT]], align 8 // CHECK-64-NEXT: [[TMP1:%.*]] = load i8*, i8** [[FMT]], align 8 // CHECK-64-NEXT: [[TMP2:%.*]] = getelementptr inbounds [[PRINTF_ARGS]], %printf_args* [[TMP]], i32 0, i32 0 // CHECK-64-NEXT: store i32 1, i32* [[TMP2]], align 4 // CHECK-64-NEXT: [[TMP3:%.*]] = getelementptr inbounds [[PRINTF_ARGS]], %printf_args* [[TMP]], i32 0, i32 1 // CHECK-64-NEXT: store i64 2, i64* [[TMP3]], align 8 // CHECK-64-NEXT: [[TMP4:%.*]] = getelementptr inbounds [[PRINTF_ARGS]], %printf_args* [[TMP]], i32 0, i32 2 // CHECK-64-NEXT: store double 3.000000e+00, double* [[TMP4]], align 8 // CHECK-64-NEXT: [[TMP5:%.*]] = bitcast %printf_args* [[TMP]] to i8* // CHECK-64-NEXT: [[TMP6:%.*]] = call i32 @__llvm_omp_vprintf(i8* [[TMP1]], i8* [[TMP5]], i32 24) // CHECK-64-NEXT: call void @__kmpc_target_deinit(%struct.ident_t* @[[GLOB1]], i8 1, i1 true) // CHECK-64-NEXT: ret void // CHECK-64: worker.exit: // CHECK-64-NEXT: ret void // // // CHECK-64-LABEL: define {{[^@]+}}@{{__omp_offloading_[0-9a-z]+_[0-9a-z]+}}_CheckNoArgs_l25 // CHECK-64-SAME: () #[[ATTR0]] { // CHECK-64-NEXT: entry: // CHECK-64-NEXT: [[TMP0:%.*]] = call i32 @__kmpc_target_init(%struct.ident_t* @[[GLOB1]], i8 1, i1 true, i1 true) // CHECK-64-NEXT: [[EXEC_USER_CODE:%.*]] = icmp eq i32 [[TMP0]], -1 // CHECK-64-NEXT: br i1 [[EXEC_USER_CODE]], label [[USER_CODE_ENTRY:%.*]], label [[WORKER_EXIT:%.*]] // CHECK-64: user_code.entry: // CHECK-64-NEXT: [[TMP1:%.*]] = call i32 @__llvm_omp_vprintf(i8* getelementptr inbounds ([14 x i8], [14 x i8]* @.str1, i64 0, i64 0), i8* null, i32 0) // CHECK-64-NEXT: call void @__kmpc_target_deinit(%struct.ident_t* @[[GLOB1]], i8 1, i1 true) // CHECK-64-NEXT: ret void // CHECK-64: worker.exit: // CHECK-64-NEXT: ret void // // // CHECK-64-LABEL: define {{[^@]+}}@{{__omp_offloading_[0-9a-z]+_[0-9a-z]+}}_CheckAllocaIsInEntryBlock_l36 // CHECK-64-SAME: (i64 noundef [[FOO:%.*]]) #[[ATTR0]] { // CHECK-64-NEXT: entry: // CHECK-64-NEXT: [[FOO_ADDR:%.*]] = alloca i64, align 8 // CHECK-64-NEXT: [[TMP:%.*]] = alloca [[PRINTF_ARGS_0:%.*]], align 8 // CHECK-64-NEXT: store i64 [[FOO]], i64* [[FOO_ADDR]], align 8 // CHECK-64-NEXT: [[CONV:%.*]] = bitcast i64* [[FOO_ADDR]] to i32* // CHECK-64-NEXT: [[TMP0:%.*]] = call i32 @__kmpc_target_init(%struct.ident_t* @[[GLOB1]], i8 1, i1 true, i1 true) // CHECK-64-NEXT: [[EXEC_USER_CODE:%.*]] = icmp eq i32 [[TMP0]], -1 // CHECK-64-NEXT: br i1 [[EXEC_USER_CODE]], label [[USER_CODE_ENTRY:%.*]], label [[WORKER_EXIT:%.*]] // CHECK-64: user_code.entry: // CHECK-64-NEXT: [[TMP1:%.*]] = load i32, i32* [[CONV]], align 4 // CHECK-64-NEXT: [[TOBOOL:%.*]] = icmp ne i32 [[TMP1]], 0 // CHECK-64-NEXT: br i1 [[TOBOOL]], label [[IF_THEN:%.*]], label [[IF_END:%.*]] // CHECK-64: if.then: // CHECK-64-NEXT: [[TMP2:%.*]] = getelementptr inbounds [[PRINTF_ARGS_0]], %printf_args.0* [[TMP]], i32 0, i32 0 // CHECK-64-NEXT: store i32 42, i32* [[TMP2]], align 4 // CHECK-64-NEXT: [[TMP3:%.*]] = bitcast %printf_args.0* [[TMP]] to i8* // CHECK-64-NEXT: [[TMP4:%.*]] = call i32 @__llvm_omp_vprintf(i8* getelementptr inbounds ([3 x i8], [3 x i8]* @.str2, i64 0, i64 0), i8* [[TMP3]], i32 4) // CHECK-64-NEXT: br label [[IF_END]] // CHECK-64: worker.exit: // CHECK-64-NEXT: ret void // CHECK-64: if.end: // CHECK-64-NEXT: call void @__kmpc_target_deinit(%struct.ident_t* @[[GLOB1]], i8 1, i1 true) // CHECK-64-NEXT: ret void // // // // // // CHECK-32-LABEL: define {{[^@]+}}@{{__omp_offloading_[0-9a-z]+_[0-9a-z]+}}_CheckSimple_l13 // CHECK-32-SAME: () #[[ATTR0:[0-9]+]] { // CHECK-32-NEXT: entry: // CHECK-32-NEXT: [[FMT:%.*]] = alloca i8*, align 4 // CHECK-32-NEXT: [[TMP:%.*]] = alloca [[PRINTF_ARGS:%.*]], align 8 // CHECK-32-NEXT: [[TMP0:%.*]] = call i32 @__kmpc_target_init(%struct.ident_t* @[[GLOB1:[0-9]+]], i8 1, i1 true, i1 true) // CHECK-32-NEXT: [[EXEC_USER_CODE:%.*]] = icmp eq i32 [[TMP0]], -1 // CHECK-32-NEXT: br i1 [[EXEC_USER_CODE]], label [[USER_CODE_ENTRY:%.*]], label [[WORKER_EXIT:%.*]] // CHECK-32: user_code.entry: // CHECK-32-NEXT: store i8* getelementptr inbounds ([11 x i8], [11 x i8]* @.str, i32 0, i32 0), i8** [[FMT]], align 4 // CHECK-32-NEXT: [[TMP1:%.*]] = load i8*, i8** [[FMT]], align 4 // CHECK-32-NEXT: [[TMP2:%.*]] = getelementptr inbounds [[PRINTF_ARGS]], %printf_args* [[TMP]], i32 0, i32 0 // CHECK-32-NEXT: store i32 1, i32* [[TMP2]], align 4 // CHECK-32-NEXT: [[TMP3:%.*]] = getelementptr inbounds [[PRINTF_ARGS]], %printf_args* [[TMP]], i32 0, i32 1 // CHECK-32-NEXT: store i64 2, i64* [[TMP3]], align 8 // CHECK-32-NEXT: [[TMP4:%.*]] = getelementptr inbounds [[PRINTF_ARGS]], %printf_args* [[TMP]], i32 0, i32 2 // CHECK-32-NEXT: store double 3.000000e+00, double* [[TMP4]], align 8 // CHECK-32-NEXT: [[TMP5:%.*]] = bitcast %printf_args* [[TMP]] to i8* // CHECK-32-NEXT: [[TMP6:%.*]] = call i32 @__llvm_omp_vprintf(i8* [[TMP1]], i8* [[TMP5]], i32 24) // CHECK-32-NEXT: call void @__kmpc_target_deinit(%struct.ident_t* @[[GLOB1]], i8 1, i1 true) // CHECK-32-NEXT: ret void // CHECK-32: worker.exit: // CHECK-32-NEXT: ret void // // // CHECK-32-LABEL: define {{[^@]+}}@{{__omp_offloading_[0-9a-z]+_[0-9a-z]+}}_CheckNoArgs_l25 // CHECK-32-SAME: () #[[ATTR0]] { // CHECK-32-NEXT: entry: // CHECK-32-NEXT: [[TMP0:%.*]] = call i32 @__kmpc_target_init(%struct.ident_t* @[[GLOB1]], i8 1, i1 true, i1 true) // CHECK-32-NEXT: [[EXEC_USER_CODE:%.*]] = icmp eq i32 [[TMP0]], -1 // CHECK-32-NEXT: br i1 [[EXEC_USER_CODE]], label [[USER_CODE_ENTRY:%.*]], label [[WORKER_EXIT:%.*]] // CHECK-32: user_code.entry: // CHECK-32-NEXT: [[TMP1:%.*]] = call i32 @__llvm_omp_vprintf(i8* getelementptr inbounds ([14 x i8], [14 x i8]* @.str1, i32 0, i32 0), i8* null, i32 0) // CHECK-32-NEXT: call void @__kmpc_target_deinit(%struct.ident_t* @[[GLOB1]], i8 1, i1 true) // CHECK-32-NEXT: ret void // CHECK-32: worker.exit: // CHECK-32-NEXT: ret void // // // CHECK-32-LABEL: define {{[^@]+}}@{{__omp_offloading_[0-9a-z]+_[0-9a-z]+}}_CheckAllocaIsInEntryBlock_l36 // CHECK-32-SAME: (i32 noundef [[FOO:%.*]]) #[[ATTR0]] { // CHECK-32-NEXT: entry: // CHECK-32-NEXT: [[FOO_ADDR:%.*]] = alloca i32, align 4 // CHECK-32-NEXT: [[TMP:%.*]] = alloca [[PRINTF_ARGS_0:%.*]], align 8 // CHECK-32-NEXT: store i32 [[FOO]], i32* [[FOO_ADDR]], align 4 // CHECK-32-NEXT: [[TMP0:%.*]] = call i32 @__kmpc_target_init(%struct.ident_t* @[[GLOB1]], i8 1, i1 true, i1 true) // CHECK-32-NEXT: [[EXEC_USER_CODE:%.*]] = icmp eq i32 [[TMP0]], -1 // CHECK-32-NEXT: br i1 [[EXEC_USER_CODE]], label [[USER_CODE_ENTRY:%.*]], label [[WORKER_EXIT:%.*]] // CHECK-32: user_code.entry: // CHECK-32-NEXT: [[TMP1:%.*]] = load i32, i32* [[FOO_ADDR]], align 4 // CHECK-32-NEXT: [[TOBOOL:%.*]] = icmp ne i32 [[TMP1]], 0 // CHECK-32-NEXT: br i1 [[TOBOOL]], label [[IF_THEN:%.*]], label [[IF_END:%.*]] // CHECK-32: if.then: // CHECK-32-NEXT: [[TMP2:%.*]] = getelementptr inbounds [[PRINTF_ARGS_0]], %printf_args.0* [[TMP]], i32 0, i32 0 // CHECK-32-NEXT: store i32 42, i32* [[TMP2]], align 4 // CHECK-32-NEXT: [[TMP3:%.*]] = bitcast %printf_args.0* [[TMP]] to i8* // CHECK-32-NEXT: [[TMP4:%.*]] = call i32 @__llvm_omp_vprintf(i8* getelementptr inbounds ([3 x i8], [3 x i8]* @.str2, i32 0, i32 0), i8* [[TMP3]], i32 4) // CHECK-32-NEXT: br label [[IF_END]] // CHECK-32: worker.exit: // CHECK-32-NEXT: ret void // CHECK-32: if.end: // CHECK-32-NEXT: call void @__kmpc_target_deinit(%struct.ident_t* @[[GLOB1]], i8 1, i1 true) // CHECK-32-NEXT: ret void //
lone_target_exit_data.c
// Check that a target exit data directive behaves correctly when the runtime // has not yet been initialized. // RUN: %libomptarget-compile-run-and-check-generic #include <stdio.h> int main() { // CHECK: x = 98 int x = 98; #pragma omp target exit data map(from:x) printf("x = %d\n", x); return 0; }
par_csr_matop.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) ******************************************************************************/ #include "_hypre_utilities.h" #include "_hypre_parcsr_mv.h" #include "_hypre_lapack.h" #include "_hypre_blas.h" /*-------------------------------------------------------------------------- * hypre_ParMatmul_RowSizes: * * Computes sizes of C rows. Formerly part of hypre_ParMatmul but removed * so it can also be used for multiplication of Boolean matrices. * * Arrays computed: C_diag_i, C_offd_i. * * Arrays needed: (17, all HYPRE_Int*) * rownnz_A, * A_diag_i, A_diag_j, * A_offd_i, A_offd_j, * B_diag_i, B_diag_j, * B_offd_i, B_offd_j, * B_ext_i, B_ext_j, * col_map_offd_B, col_map_offd_B, * B_offd_i, B_offd_j, * B_ext_i, B_ext_j. * * Scalars computed: C_diag_size, C_offd_size. * * Scalars needed: * num_rownnz_A, num_rows_diag_A, num_cols_offd_A, allsquare, * first_col_diag_B, num_cols_diag_B, num_cols_offd_B, num_cols_offd_C *--------------------------------------------------------------------------*/ void hypre_ParMatmul_RowSizes( HYPRE_MemoryLocation memory_location, HYPRE_Int **C_diag_i, HYPRE_Int **C_offd_i, HYPRE_Int *rownnz_A, HYPRE_Int *A_diag_i, HYPRE_Int *A_diag_j, HYPRE_Int *A_offd_i, HYPRE_Int *A_offd_j, HYPRE_Int *B_diag_i, HYPRE_Int *B_diag_j, HYPRE_Int *B_offd_i, HYPRE_Int *B_offd_j, HYPRE_Int *B_ext_diag_i, HYPRE_Int *B_ext_diag_j, HYPRE_Int *B_ext_offd_i, HYPRE_Int *B_ext_offd_j, HYPRE_Int *map_B_to_C, HYPRE_Int *C_diag_size, HYPRE_Int *C_offd_size, HYPRE_Int num_rownnz_A, HYPRE_Int num_rows_diag_A, HYPRE_Int num_cols_offd_A, HYPRE_Int allsquare, HYPRE_Int num_cols_diag_B, HYPRE_Int num_cols_offd_B, HYPRE_Int num_cols_offd_C ) { HYPRE_Int *jj_count_diag_array; HYPRE_Int *jj_count_offd_array; HYPRE_Int start_indexing = 0; /* start indexing for C_data at 0 */ HYPRE_Int num_threads = hypre_NumThreads(); *C_diag_i = hypre_CTAlloc(HYPRE_Int, num_rows_diag_A+1, memory_location); *C_offd_i = hypre_CTAlloc(HYPRE_Int, num_rows_diag_A+1, memory_location); jj_count_diag_array = hypre_CTAlloc(HYPRE_Int, num_threads, HYPRE_MEMORY_HOST); jj_count_offd_array = hypre_CTAlloc(HYPRE_Int, num_threads, HYPRE_MEMORY_HOST); /*----------------------------------------------------------------------- * Loop over rows of A *-----------------------------------------------------------------------*/ #ifdef HYPRE_USING_OPENMP #pragma omp parallel #endif { HYPRE_Int *B_marker = NULL; HYPRE_Int jj_row_begin_diag, jj_count_diag; HYPRE_Int jj_row_begin_offd, jj_count_offd; HYPRE_Int i1, ii1, i2, i3, jj2, jj3; HYPRE_Int size, rest, num_threads; HYPRE_Int ii, ns, ne; num_threads = hypre_NumActiveThreads(); size = num_rownnz_A/num_threads; rest = num_rownnz_A - size*num_threads; ii = hypre_GetThreadNum(); if (ii < rest) { ns = ii*size+ii; ne = (ii+1)*size+ii+1; } else { ns = ii*size+rest; ne = (ii+1)*size+rest; } jj_count_diag = start_indexing; jj_count_offd = start_indexing; if (num_cols_diag_B || num_cols_offd_C) { B_marker = hypre_CTAlloc(HYPRE_Int, num_cols_diag_B + num_cols_offd_C, HYPRE_MEMORY_HOST); } for (i1 = 0; i1 < num_cols_diag_B + num_cols_offd_C; i1++) { B_marker[i1] = -1; } for (i1 = ns; i1 < ne; i1++) { jj_row_begin_diag = jj_count_diag; jj_row_begin_offd = jj_count_offd; if (rownnz_A) { ii1 = rownnz_A[i1]; } else { ii1 = i1; /*-------------------------------------------------------------------- * Set marker for diagonal entry, C_{i1,i1} (for square matrices). *--------------------------------------------------------------------*/ if (allsquare) { B_marker[i1] = jj_count_diag; jj_count_diag++; } } /*----------------------------------------------------------------- * Loop over entries in row ii1 of A_offd. *-----------------------------------------------------------------*/ if (num_cols_offd_A) { for (jj2 = A_offd_i[ii1]; jj2 < A_offd_i[ii1+1]; jj2++) { i2 = A_offd_j[jj2]; /*----------------------------------------------------------- * Loop over entries in row i2 of B_ext. *-----------------------------------------------------------*/ for (jj3 = B_ext_offd_i[i2]; jj3 < B_ext_offd_i[i2+1]; jj3++) { i3 = num_cols_diag_B+B_ext_offd_j[jj3]; /*-------------------------------------------------------- * Check B_marker to see that C_{ii1,i3} has not already * been accounted for. If it has not, mark it and increment * counter. *--------------------------------------------------------*/ if (B_marker[i3] < jj_row_begin_offd) { B_marker[i3] = jj_count_offd; jj_count_offd++; } } for (jj3 = B_ext_diag_i[i2]; jj3 < B_ext_diag_i[i2+1]; jj3++) { i3 = B_ext_diag_j[jj3]; if (B_marker[i3] < jj_row_begin_diag) { B_marker[i3] = jj_count_diag; jj_count_diag++; } } } } /*----------------------------------------------------------------- * Loop over entries in row ii1 of A_diag. *-----------------------------------------------------------------*/ for (jj2 = A_diag_i[ii1]; jj2 < A_diag_i[ii1+1]; jj2++) { i2 = A_diag_j[jj2]; /*----------------------------------------------------------- * Loop over entries in row i2 of B_diag. *-----------------------------------------------------------*/ for (jj3 = B_diag_i[i2]; jj3 < B_diag_i[i2+1]; jj3++) { i3 = B_diag_j[jj3]; /*-------------------------------------------------------- * Check B_marker to see that C_{ii1,i3} has not already * been accounted for. If it has not, mark it and increment * counter. *--------------------------------------------------------*/ if (B_marker[i3] < jj_row_begin_diag) { B_marker[i3] = jj_count_diag; jj_count_diag++; } } /*----------------------------------------------------------- * Loop over entries in row i2 of B_offd. *-----------------------------------------------------------*/ if (num_cols_offd_B) { for (jj3 = B_offd_i[i2]; jj3 < B_offd_i[i2+1]; jj3++) { i3 = num_cols_diag_B+map_B_to_C[B_offd_j[jj3]]; /*-------------------------------------------------------- * Check B_marker to see that C_{ii1,i3} has not already * been accounted for. If it has not, mark it and increment * counter. *--------------------------------------------------------*/ if (B_marker[i3] < jj_row_begin_offd) { B_marker[i3] = jj_count_offd; jj_count_offd++; } } } } /*-------------------------------------------------------------------- * Set C_diag_i and C_offd_i for this row. *--------------------------------------------------------------------*/ (*C_diag_i)[ii1] = jj_row_begin_diag; (*C_offd_i)[ii1] = jj_row_begin_offd; } jj_count_diag_array[ii] = jj_count_diag; jj_count_offd_array[ii] = jj_count_offd; hypre_TFree(B_marker, HYPRE_MEMORY_HOST); #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif /* Correct diag_i and offd_i - phase 1 */ if (ii) { jj_count_diag = jj_count_diag_array[0]; jj_count_offd = jj_count_offd_array[0]; for (i1 = 1; i1 < ii; i1++) { jj_count_diag += jj_count_diag_array[i1]; jj_count_offd += jj_count_offd_array[i1]; } for (i1 = ns; i1 < ne; i1++) { ii1 = rownnz_A ? rownnz_A[i1] : i1; (*C_diag_i)[ii1] += jj_count_diag; (*C_offd_i)[ii1] += jj_count_offd; } } else { (*C_diag_i)[num_rows_diag_A] = 0; (*C_offd_i)[num_rows_diag_A] = 0; for (i1 = 0; i1 < num_threads; i1++) { (*C_diag_i)[num_rows_diag_A] += jj_count_diag_array[i1]; (*C_offd_i)[num_rows_diag_A] += jj_count_offd_array[i1]; } } /* Correct diag_i and offd_i - phase 2 */ if (rownnz_A != NULL) { #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif for (i1 = ns; i1 < (ne-1); i1++) { for (ii1 = rownnz_A[i1] + 1; ii1 < rownnz_A[i1+1]; ii1++) { (*C_diag_i)[ii1] = (*C_diag_i)[rownnz_A[i1+1]]; (*C_offd_i)[ii1] = (*C_offd_i)[rownnz_A[i1+1]]; } } if (ii < (num_threads - 1)) { for (ii1 = rownnz_A[ne-1] + 1; ii1 < rownnz_A[ne]; ii1++) { (*C_diag_i)[ii1] = (*C_diag_i)[rownnz_A[ne]]; (*C_offd_i)[ii1] = (*C_offd_i)[rownnz_A[ne]]; } } else { for (ii1 = rownnz_A[ne-1] + 1; ii1 < num_rows_diag_A; ii1++) { (*C_diag_i)[ii1] = (*C_diag_i)[num_rows_diag_A]; (*C_offd_i)[ii1] = (*C_offd_i)[num_rows_diag_A]; } } } } /* end parallel loop */ *C_diag_size = (*C_diag_i)[num_rows_diag_A]; *C_offd_size = (*C_offd_i)[num_rows_diag_A]; #ifdef HYPRE_DEBUG HYPRE_Int i; for (i = 0; i < num_rows_diag_A; i++) { hypre_assert((*C_diag_i)[i] <= (*C_diag_i)[i+1]); hypre_assert((*C_offd_i)[i] <= (*C_offd_i)[i+1]); } #endif hypre_TFree(jj_count_diag_array, HYPRE_MEMORY_HOST); hypre_TFree(jj_count_offd_array, HYPRE_MEMORY_HOST); /* End of First Pass */ } /*-------------------------------------------------------------------------- * hypre_ParMatmul: * * Multiplies two ParCSRMatrices A and B and returns the product in * ParCSRMatrix C. * * Note: C does not own the partitionings since its row_starts * is owned by A and col_starts by B. *--------------------------------------------------------------------------*/ hypre_ParCSRMatrix* hypre_ParMatmul( hypre_ParCSRMatrix *A, hypre_ParCSRMatrix *B ) { #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_MATMUL] -= hypre_MPI_Wtime(); #endif /* ParCSRMatrix A */ MPI_Comm comm = hypre_ParCSRMatrixComm(A); HYPRE_BigInt nrows_A = hypre_ParCSRMatrixGlobalNumRows(A); HYPRE_BigInt ncols_A = hypre_ParCSRMatrixGlobalNumCols(A); HYPRE_BigInt *row_starts_A = hypre_ParCSRMatrixRowStarts(A); HYPRE_Int num_rownnz_A; HYPRE_Int *rownnz_A = NULL; /* ParCSRMatrix B */ HYPRE_BigInt nrows_B = hypre_ParCSRMatrixGlobalNumRows(B); HYPRE_BigInt ncols_B = hypre_ParCSRMatrixGlobalNumCols(B); HYPRE_BigInt first_col_diag_B = hypre_ParCSRMatrixFirstColDiag(B); HYPRE_BigInt *col_starts_B = hypre_ParCSRMatrixColStarts(B); HYPRE_BigInt last_col_diag_B; /* A_diag */ hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); HYPRE_Complex *A_diag_data = hypre_CSRMatrixData(A_diag); HYPRE_Int *A_diag_i = hypre_CSRMatrixI(A_diag); HYPRE_Int *A_diag_j = hypre_CSRMatrixJ(A_diag); HYPRE_Int *A_diag_ir = hypre_CSRMatrixRownnz(A_diag); HYPRE_Int num_rownnz_diag_A = hypre_CSRMatrixNumRownnz(A_diag); HYPRE_Int num_rows_diag_A = hypre_CSRMatrixNumRows(A_diag); HYPRE_Int num_cols_diag_A = hypre_CSRMatrixNumCols(A_diag); /* A_offd */ hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A); HYPRE_Complex *A_offd_data = hypre_CSRMatrixData(A_offd); HYPRE_Int *A_offd_i = hypre_CSRMatrixI(A_offd); HYPRE_Int *A_offd_j = hypre_CSRMatrixJ(A_offd); HYPRE_Int *A_offd_ir = hypre_CSRMatrixRownnz(A_offd); HYPRE_Int num_rownnz_offd_A = hypre_CSRMatrixNumRownnz(A_offd); HYPRE_Int num_rows_offd_A = hypre_CSRMatrixNumRows(A_offd); HYPRE_Int num_cols_offd_A = hypre_CSRMatrixNumCols(A_offd); /* B_diag */ hypre_CSRMatrix *B_diag = hypre_ParCSRMatrixDiag(B); HYPRE_Complex *B_diag_data = hypre_CSRMatrixData(B_diag); HYPRE_Int *B_diag_i = hypre_CSRMatrixI(B_diag); HYPRE_Int *B_diag_j = hypre_CSRMatrixJ(B_diag); HYPRE_Int num_rows_diag_B = hypre_CSRMatrixNumRows(B_diag); HYPRE_Int num_cols_diag_B = hypre_CSRMatrixNumCols(B_diag); /* B_offd */ hypre_CSRMatrix *B_offd = hypre_ParCSRMatrixOffd(B); HYPRE_BigInt *col_map_offd_B = hypre_ParCSRMatrixColMapOffd(B); HYPRE_Complex *B_offd_data = hypre_CSRMatrixData(B_offd); HYPRE_Int *B_offd_i = hypre_CSRMatrixI(B_offd); HYPRE_Int *B_offd_j = hypre_CSRMatrixJ(B_offd); HYPRE_Int num_cols_offd_B = hypre_CSRMatrixNumCols(B_offd); /* ParCSRMatrix C */ hypre_ParCSRMatrix *C; HYPRE_BigInt *col_map_offd_C; HYPRE_Int *map_B_to_C = NULL; /* C_diag */ hypre_CSRMatrix *C_diag; HYPRE_Complex *C_diag_data; HYPRE_Int *C_diag_i; HYPRE_Int *C_diag_j; HYPRE_Int C_offd_size; HYPRE_Int num_cols_offd_C = 0; /* C_offd */ hypre_CSRMatrix *C_offd; HYPRE_Complex *C_offd_data = NULL; HYPRE_Int *C_offd_i = NULL; HYPRE_Int *C_offd_j = NULL; HYPRE_Int C_diag_size; /* Bs_ext */ hypre_CSRMatrix *Bs_ext; HYPRE_Complex *Bs_ext_data; HYPRE_Int *Bs_ext_i; HYPRE_BigInt *Bs_ext_j; HYPRE_Complex *B_ext_diag_data; HYPRE_Int *B_ext_diag_i; HYPRE_Int *B_ext_diag_j; HYPRE_Int B_ext_diag_size; HYPRE_Complex *B_ext_offd_data; HYPRE_Int *B_ext_offd_i; HYPRE_Int *B_ext_offd_j; HYPRE_BigInt *B_big_offd_j = NULL; HYPRE_Int B_ext_offd_size; HYPRE_Int allsquare = 0; HYPRE_Int num_procs; HYPRE_Int *my_diag_array; HYPRE_Int *my_offd_array; HYPRE_Int max_num_threads; HYPRE_Complex zero = 0.0; HYPRE_MemoryLocation memory_location_A = hypre_ParCSRMatrixMemoryLocation(A); HYPRE_MemoryLocation memory_location_B = hypre_ParCSRMatrixMemoryLocation(B); /* RL: TODO cannot guarantee, maybe should never assert hypre_assert(memory_location_A == memory_location_B); */ /* RL: in the case of A=H, B=D, or A=D, B=H, let C = D, * not sure if this is the right thing to do. * Also, need something like this in other places * TODO */ HYPRE_MemoryLocation memory_location_C = hypre_max(memory_location_A, memory_location_B); max_num_threads = hypre_NumThreads(); my_diag_array = hypre_CTAlloc(HYPRE_Int, max_num_threads, HYPRE_MEMORY_HOST); my_offd_array = hypre_CTAlloc(HYPRE_Int, max_num_threads, HYPRE_MEMORY_HOST); if (ncols_A != nrows_B || num_cols_diag_A != num_rows_diag_B) { hypre_error_w_msg(HYPRE_ERROR_GENERIC," Error! Incompatible matrix dimensions!\n"); return NULL; } /* if C=A*B is square globally and locally, then C_diag should be square also */ if ( num_rows_diag_A == num_cols_diag_B && nrows_A == ncols_B ) { allsquare = 1; } /* Set rownnz of A */ if (num_rownnz_diag_A != num_rows_diag_A && num_rownnz_offd_A != num_rows_offd_A ) { hypre_MergeOrderedArrays(num_rownnz_diag_A, A_diag_ir, num_rownnz_offd_A, A_offd_ir, &num_rownnz_A, &rownnz_A); } else { num_rownnz_A = hypre_max(num_rows_diag_A, num_rows_offd_A); } /*----------------------------------------------------------------------- * Extract B_ext, i.e. portion of B that is stored on neighbor procs * and needed locally for matrix matrix product *-----------------------------------------------------------------------*/ hypre_MPI_Comm_size(comm, &num_procs); #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_RENUMBER_COLIDX] -= hypre_MPI_Wtime(); #endif if (num_procs > 1) { /*--------------------------------------------------------------------- * If there exists no CommPkg for A, a CommPkg is generated using * equally load balanced partitionings within * hypre_ParCSRMatrixExtractBExt *--------------------------------------------------------------------*/ Bs_ext = hypre_ParCSRMatrixExtractBExt(B,A,1); Bs_ext_data = hypre_CSRMatrixData(Bs_ext); Bs_ext_i = hypre_CSRMatrixI(Bs_ext); Bs_ext_j = hypre_CSRMatrixBigJ(Bs_ext); } B_ext_diag_i = hypre_CTAlloc(HYPRE_Int, num_cols_offd_A+1, HYPRE_MEMORY_HOST); B_ext_offd_i = hypre_CTAlloc(HYPRE_Int, num_cols_offd_A+1, HYPRE_MEMORY_HOST); B_ext_diag_size = 0; B_ext_offd_size = 0; last_col_diag_B = first_col_diag_B + (HYPRE_BigInt) num_cols_diag_B - 1; #ifdef HYPRE_CONCURRENT_HOPSCOTCH hypre_UnorderedBigIntSet set; #pragma omp parallel { HYPRE_Int size, rest, ii; HYPRE_Int ns, ne; HYPRE_Int i1, i, j; HYPRE_Int my_offd_size, my_diag_size; HYPRE_Int cnt_offd, cnt_diag; HYPRE_Int num_threads = hypre_NumActiveThreads(); size = num_cols_offd_A/num_threads; rest = num_cols_offd_A - size*num_threads; ii = hypre_GetThreadNum(); if (ii < rest) { ns = ii*size+ii; ne = (ii+1)*size+ii+1; } else { ns = ii*size+rest; ne = (ii+1)*size+rest; } my_diag_size = 0; my_offd_size = 0; for (i = ns; i < ne; i++) { B_ext_diag_i[i] = my_diag_size; B_ext_offd_i[i] = my_offd_size; for (j = Bs_ext_i[i]; j < Bs_ext_i[i+1]; j++) { if (Bs_ext_j[j] < first_col_diag_B || Bs_ext_j[j] > last_col_diag_B) { my_offd_size++; } else { my_diag_size++; } } } my_diag_array[ii] = my_diag_size; my_offd_array[ii] = my_offd_size; #pragma omp barrier if (ii) { my_diag_size = my_diag_array[0]; my_offd_size = my_offd_array[0]; for (i1 = 1; i1 < ii; i1++) { my_diag_size += my_diag_array[i1]; my_offd_size += my_offd_array[i1]; } for (i1 = ns; i1 < ne; i1++) { B_ext_diag_i[i1] += my_diag_size; B_ext_offd_i[i1] += my_offd_size; } } else { B_ext_diag_size = 0; B_ext_offd_size = 0; for (i1 = 0; i1 < num_threads; i1++) { B_ext_diag_size += my_diag_array[i1]; B_ext_offd_size += my_offd_array[i1]; } B_ext_diag_i[num_cols_offd_A] = B_ext_diag_size; B_ext_offd_i[num_cols_offd_A] = B_ext_offd_size; if (B_ext_diag_size) { B_ext_diag_j = hypre_CTAlloc(HYPRE_Int, B_ext_diag_size, HYPRE_MEMORY_HOST); B_ext_diag_data = hypre_CTAlloc(HYPRE_Complex, B_ext_diag_size, HYPRE_MEMORY_HOST); } if (B_ext_offd_size) { B_ext_offd_j = hypre_CTAlloc(HYPRE_Int, B_ext_offd_size, HYPRE_MEMORY_HOST); B_big_offd_j = hypre_CTAlloc(HYPRE_BigInt, B_ext_offd_size, HYPRE_MEMORY_HOST); B_ext_offd_data = hypre_CTAlloc(HYPRE_Complex, B_ext_offd_size, HYPRE_MEMORY_HOST); } hypre_UnorderedBigIntSetCreate(&set, B_ext_offd_size + num_cols_offd_B, 16*hypre_NumThreads()); } #pragma omp barrier cnt_offd = B_ext_offd_i[ns]; cnt_diag = B_ext_diag_i[ns]; for (i = ns; i < ne; i++) { for (j = Bs_ext_i[i]; j < Bs_ext_i[i+1]; j++) { if (Bs_ext_j[j] < first_col_diag_B || Bs_ext_j[j] > last_col_diag_B) { hypre_UnorderedBigIntSetPut(&set, Bs_ext_j[j]); B_big_offd_j[cnt_offd] = Bs_ext_j[j]; //Bs_ext_j[cnt_offd] = Bs_ext_j[j]; B_ext_offd_data[cnt_offd++] = Bs_ext_data[j]; } else { B_ext_diag_j[cnt_diag] = (HYPRE_Int)(Bs_ext_j[j] - first_col_diag_B); B_ext_diag_data[cnt_diag++] = Bs_ext_data[j]; } } } HYPRE_Int i_begin, i_end; hypre_GetSimpleThreadPartition(&i_begin, &i_end, num_cols_offd_B); for (i = i_begin; i < i_end; i++) { hypre_UnorderedBigIntSetPut(&set, col_map_offd_B[i]); } } /* omp parallel */ col_map_offd_C = hypre_UnorderedBigIntSetCopyToArray(&set, &num_cols_offd_C); hypre_UnorderedBigIntSetDestroy(&set); hypre_UnorderedBigIntMap col_map_offd_C_inverse; hypre_big_sort_and_create_inverse_map(col_map_offd_C, num_cols_offd_C, &col_map_offd_C, &col_map_offd_C_inverse); HYPRE_Int i, j; #pragma omp parallel for private(j) HYPRE_SMP_SCHEDULE for (i = 0; i < num_cols_offd_A; i++) { for (j = B_ext_offd_i[i]; j < B_ext_offd_i[i+1]; j++) { //B_ext_offd_j[j] = hypre_UnorderedIntMapGet(&col_map_offd_C_inverse, B_ext_offd_j[j]); B_ext_offd_j[j] = hypre_UnorderedBigIntMapGet(&col_map_offd_C_inverse, B_big_offd_j[j]); } } if (num_cols_offd_C) { hypre_UnorderedBigIntMapDestroy(&col_map_offd_C_inverse); } hypre_TFree(my_diag_array, HYPRE_MEMORY_HOST); hypre_TFree(my_offd_array, HYPRE_MEMORY_HOST); if (num_cols_offd_B) { HYPRE_Int i; map_B_to_C = hypre_CTAlloc(HYPRE_Int, num_cols_offd_B, HYPRE_MEMORY_HOST); #pragma omp parallel private(i) { HYPRE_Int i_begin, i_end; hypre_GetSimpleThreadPartition(&i_begin, &i_end, num_cols_offd_C); HYPRE_Int cnt; if (i_end > i_begin) { cnt = hypre_BigLowerBound(col_map_offd_B, col_map_offd_B + (HYPRE_BigInt)num_cols_offd_B, col_map_offd_C[i_begin]) - col_map_offd_B; } for (i = i_begin; i < i_end && cnt < num_cols_offd_B; i++) { if (col_map_offd_C[i] == col_map_offd_B[cnt]) { map_B_to_C[cnt++] = i; } } } } if (num_procs > 1) { hypre_CSRMatrixDestroy(Bs_ext); Bs_ext = NULL; } #else /* !HYPRE_CONCURRENT_HOPSCOTCH */ HYPRE_BigInt *temp; #ifdef HYPRE_USING_OPENMP #pragma omp parallel #endif { HYPRE_Int size, rest, ii; HYPRE_Int ns, ne; HYPRE_Int i1, i, j; HYPRE_Int my_offd_size, my_diag_size; HYPRE_Int cnt_offd, cnt_diag; HYPRE_Int num_threads = hypre_NumActiveThreads(); size = num_cols_offd_A/num_threads; rest = num_cols_offd_A - size*num_threads; ii = hypre_GetThreadNum(); if (ii < rest) { ns = ii*size+ii; ne = (ii+1)*size+ii+1; } else { ns = ii*size+rest; ne = (ii+1)*size+rest; } my_diag_size = 0; my_offd_size = 0; for (i = ns; i < ne; i++) { B_ext_diag_i[i] = my_diag_size; B_ext_offd_i[i] = my_offd_size; for (j = Bs_ext_i[i]; j < Bs_ext_i[i+1]; j++) { if (Bs_ext_j[j] < first_col_diag_B || Bs_ext_j[j] > last_col_diag_B) { my_offd_size++; } else { my_diag_size++; } } } my_diag_array[ii] = my_diag_size; my_offd_array[ii] = my_offd_size; #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif if (ii) { my_diag_size = my_diag_array[0]; my_offd_size = my_offd_array[0]; for (i1 = 1; i1 < ii; i1++) { my_diag_size += my_diag_array[i1]; my_offd_size += my_offd_array[i1]; } for (i1 = ns; i1 < ne; i1++) { B_ext_diag_i[i1] += my_diag_size; B_ext_offd_i[i1] += my_offd_size; } } else { B_ext_diag_size = 0; B_ext_offd_size = 0; for (i1 = 0; i1 < num_threads; i1++) { B_ext_diag_size += my_diag_array[i1]; B_ext_offd_size += my_offd_array[i1]; } B_ext_diag_i[num_cols_offd_A] = B_ext_diag_size; B_ext_offd_i[num_cols_offd_A] = B_ext_offd_size; if (B_ext_diag_size) { B_ext_diag_j = hypre_CTAlloc(HYPRE_Int, B_ext_diag_size, HYPRE_MEMORY_HOST); B_ext_diag_data = hypre_CTAlloc(HYPRE_Complex, B_ext_diag_size, HYPRE_MEMORY_HOST); } if (B_ext_offd_size) { B_ext_offd_j = hypre_CTAlloc(HYPRE_Int, B_ext_offd_size, HYPRE_MEMORY_HOST); B_big_offd_j = hypre_CTAlloc(HYPRE_BigInt, B_ext_offd_size, HYPRE_MEMORY_HOST); B_ext_offd_data = hypre_CTAlloc(HYPRE_Complex, B_ext_offd_size, HYPRE_MEMORY_HOST); } if (B_ext_offd_size || num_cols_offd_B) { temp = hypre_CTAlloc(HYPRE_BigInt, B_ext_offd_size+num_cols_offd_B, HYPRE_MEMORY_HOST); } } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif cnt_offd = B_ext_offd_i[ns]; cnt_diag = B_ext_diag_i[ns]; for (i = ns; i < ne; i++) { for (j = Bs_ext_i[i]; j < Bs_ext_i[i+1]; j++) { if (Bs_ext_j[j] < first_col_diag_B || Bs_ext_j[j] > last_col_diag_B) { temp[cnt_offd] = Bs_ext_j[j]; B_big_offd_j[cnt_offd] = Bs_ext_j[j]; //Bs_ext_j[cnt_offd] = Bs_ext_j[j]; B_ext_offd_data[cnt_offd++] = Bs_ext_data[j]; } else { B_ext_diag_j[cnt_diag] = (HYPRE_Int)(Bs_ext_j[j] - first_col_diag_B); B_ext_diag_data[cnt_diag++] = Bs_ext_data[j]; } } } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif if (ii == 0) { HYPRE_Int cnt; if (num_procs > 1) { hypre_CSRMatrixDestroy(Bs_ext); Bs_ext = NULL; } cnt = 0; if (B_ext_offd_size || num_cols_offd_B) { cnt = B_ext_offd_size; for (i = 0; i < num_cols_offd_B; i++) { temp[cnt++] = col_map_offd_B[i]; } if (cnt) { HYPRE_BigInt value; hypre_BigQsort0(temp, 0, cnt-1); num_cols_offd_C = 1; value = temp[0]; for (i = 1; i < cnt; i++) { if (temp[i] > value) { value = temp[i]; temp[num_cols_offd_C++] = value; } } } if (num_cols_offd_C) { col_map_offd_C = hypre_CTAlloc(HYPRE_BigInt, num_cols_offd_C, HYPRE_MEMORY_HOST); } for (i = 0; i < num_cols_offd_C; i++) { col_map_offd_C[i] = temp[i]; } hypre_TFree(temp, HYPRE_MEMORY_HOST); } } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif for (i = ns; i < ne; i++) { for (j = B_ext_offd_i[i]; j < B_ext_offd_i[i+1]; j++) { B_ext_offd_j[j] = hypre_BigBinarySearch(col_map_offd_C, B_big_offd_j[j], //B_ext_offd_j[j] = hypre_BigBinarySearch(col_map_offd_C, Bs_ext_j[j], num_cols_offd_C); } } } /* end parallel region */ hypre_TFree(B_big_offd_j, HYPRE_MEMORY_HOST); hypre_TFree(my_diag_array, HYPRE_MEMORY_HOST); hypre_TFree(my_offd_array, HYPRE_MEMORY_HOST); if (num_cols_offd_B) { HYPRE_Int i, cnt; map_B_to_C = hypre_CTAlloc(HYPRE_Int, num_cols_offd_B, HYPRE_MEMORY_HOST); cnt = 0; for (i = 0; i < num_cols_offd_C; i++) { if (col_map_offd_C[i] == col_map_offd_B[cnt]) { map_B_to_C[cnt++] = i; if (cnt == num_cols_offd_B) break; } } } #endif /* !HYPRE_CONCURRENT_HOPSCOTCH */ #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_RENUMBER_COLIDX] += hypre_MPI_Wtime(); #endif hypre_ParMatmul_RowSizes(memory_location_C, &C_diag_i, &C_offd_i, rownnz_A, A_diag_i, A_diag_j, A_offd_i, A_offd_j, B_diag_i, B_diag_j, B_offd_i, B_offd_j, B_ext_diag_i, B_ext_diag_j, B_ext_offd_i, B_ext_offd_j, map_B_to_C, &C_diag_size, &C_offd_size, num_rownnz_A, num_rows_diag_A, num_cols_offd_A, allsquare, num_cols_diag_B, num_cols_offd_B, num_cols_offd_C); /*----------------------------------------------------------------------- * Allocate C_diag_data and C_diag_j arrays. * Allocate C_offd_data and C_offd_j arrays. *-----------------------------------------------------------------------*/ last_col_diag_B = first_col_diag_B + (HYPRE_BigInt)num_cols_diag_B - 1; C_diag_data = hypre_CTAlloc(HYPRE_Complex, C_diag_size, memory_location_C); C_diag_j = hypre_CTAlloc(HYPRE_Int, C_diag_size, memory_location_C); if (C_offd_size) { C_offd_data = hypre_CTAlloc(HYPRE_Complex, C_offd_size, memory_location_C); C_offd_j = hypre_CTAlloc(HYPRE_Int, C_offd_size, memory_location_C); } /*----------------------------------------------------------------------- * Second Pass: Fill in C_diag_data and C_diag_j. * Second Pass: Fill in C_offd_data and C_offd_j. *-----------------------------------------------------------------------*/ /*----------------------------------------------------------------------- * Initialize some stuff. *-----------------------------------------------------------------------*/ #ifdef HYPRE_USING_OPENMP #pragma omp parallel #endif { HYPRE_Int *B_marker = NULL; HYPRE_Int ns, ne, size, rest, ii; HYPRE_Int i1, ii1, i2, i3, jj2, jj3; HYPRE_Int jj_row_begin_diag, jj_count_diag; HYPRE_Int jj_row_begin_offd, jj_count_offd; HYPRE_Int num_threads; HYPRE_Complex a_entry; /*, a_b_product;*/ num_threads = hypre_NumActiveThreads(); size = num_rownnz_A/num_threads; rest = num_rownnz_A - size*num_threads; ii = hypre_GetThreadNum(); if (ii < rest) { ns = ii*size+ii; ne = (ii+1)*size+ii+1; } else { ns = ii*size+rest; ne = (ii+1)*size+rest; } jj_count_diag = C_diag_i[rownnz_A ? rownnz_A[ns] : ns]; jj_count_offd = C_offd_i[rownnz_A ? rownnz_A[ns] : ns]; if (num_cols_diag_B || num_cols_offd_C) { B_marker = hypre_CTAlloc(HYPRE_Int, num_cols_diag_B + num_cols_offd_C, HYPRE_MEMORY_HOST); for (i1 = 0; i1 < num_cols_diag_B + num_cols_offd_C; i1++) { B_marker[i1] = -1; } } /*----------------------------------------------------------------------- * Loop over interior c-points. *-----------------------------------------------------------------------*/ for (i1 = ns; i1 < ne; i1++) { jj_row_begin_diag = jj_count_diag; jj_row_begin_offd = jj_count_offd; if (rownnz_A) { ii1 = rownnz_A[i1]; } else { ii1 = i1; /*-------------------------------------------------------------------- * Create diagonal entry, C_{i1,i1} *--------------------------------------------------------------------*/ if (allsquare) { B_marker[i1] = jj_count_diag; C_diag_data[jj_count_diag] = zero; C_diag_j[jj_count_diag] = i1; jj_count_diag++; } } /*----------------------------------------------------------------- * Loop over entries in row i1 of A_offd. *-----------------------------------------------------------------*/ if (num_cols_offd_A) { for (jj2 = A_offd_i[ii1]; jj2 < A_offd_i[ii1+1]; jj2++) { i2 = A_offd_j[jj2]; a_entry = A_offd_data[jj2]; /*----------------------------------------------------------- * Loop over entries in row i2 of B_ext. *-----------------------------------------------------------*/ for (jj3 = B_ext_offd_i[i2]; jj3 < B_ext_offd_i[i2+1]; jj3++) { i3 = num_cols_diag_B+B_ext_offd_j[jj3]; /*-------------------------------------------------------- * Check B_marker to see that C_{ii1,i3} has not already * been accounted for. If it has not, create a new entry. * If it has, add new contribution. *--------------------------------------------------------*/ if (B_marker[i3] < jj_row_begin_offd) { B_marker[i3] = jj_count_offd; C_offd_data[jj_count_offd] = a_entry*B_ext_offd_data[jj3]; C_offd_j[jj_count_offd] = i3-num_cols_diag_B; jj_count_offd++; } else { C_offd_data[B_marker[i3]] += a_entry*B_ext_offd_data[jj3]; } } for (jj3 = B_ext_diag_i[i2]; jj3 < B_ext_diag_i[i2+1]; jj3++) { i3 = B_ext_diag_j[jj3]; if (B_marker[i3] < jj_row_begin_diag) { B_marker[i3] = jj_count_diag; C_diag_data[jj_count_diag] = a_entry*B_ext_diag_data[jj3]; C_diag_j[jj_count_diag] = i3; jj_count_diag++; } else { C_diag_data[B_marker[i3]] += a_entry*B_ext_diag_data[jj3]; } } } } /*----------------------------------------------------------------- * Loop over entries in row ii1 of A_diag. *-----------------------------------------------------------------*/ for (jj2 = A_diag_i[ii1]; jj2 < A_diag_i[ii1+1]; jj2++) { i2 = A_diag_j[jj2]; a_entry = A_diag_data[jj2]; /*----------------------------------------------------------- * Loop over entries in row i2 of B_diag. *-----------------------------------------------------------*/ for (jj3 = B_diag_i[i2]; jj3 < B_diag_i[i2+1]; jj3++) { i3 = B_diag_j[jj3]; /*-------------------------------------------------------- * Check B_marker to see that C_{ii1,i3} has not already * been accounted for. If it has not, create a new entry. * If it has, add new contribution. *--------------------------------------------------------*/ if (B_marker[i3] < jj_row_begin_diag) { B_marker[i3] = jj_count_diag; C_diag_data[jj_count_diag] = a_entry*B_diag_data[jj3]; C_diag_j[jj_count_diag] = i3; jj_count_diag++; } else { C_diag_data[B_marker[i3]] += a_entry*B_diag_data[jj3]; } } if (num_cols_offd_B) { for (jj3 = B_offd_i[i2]; jj3 < B_offd_i[i2+1]; jj3++) { i3 = num_cols_diag_B+map_B_to_C[B_offd_j[jj3]]; /*-------------------------------------------------------- * Check B_marker to see that C_{ii1,i3} has not already * been accounted for. If it has not, create a new entry. * If it has, add new contribution. *--------------------------------------------------------*/ if (B_marker[i3] < jj_row_begin_offd) { B_marker[i3] = jj_count_offd; C_offd_data[jj_count_offd] = a_entry*B_offd_data[jj3]; C_offd_j[jj_count_offd] = i3-num_cols_diag_B; jj_count_offd++; } else { C_offd_data[B_marker[i3]] += a_entry*B_offd_data[jj3]; } } } } } hypre_TFree(B_marker, HYPRE_MEMORY_HOST); } /*end parallel region */ C = hypre_ParCSRMatrixCreate(comm, nrows_A, ncols_B, row_starts_A, col_starts_B, num_cols_offd_C, C_diag_size, C_offd_size); /* Note that C does not own the partitionings */ hypre_ParCSRMatrixSetRowStartsOwner(C, 0); hypre_ParCSRMatrixSetColStartsOwner(C, 0); C_diag = hypre_ParCSRMatrixDiag(C); hypre_CSRMatrixData(C_diag) = C_diag_data; hypre_CSRMatrixI(C_diag) = C_diag_i; hypre_CSRMatrixJ(C_diag) = C_diag_j; hypre_CSRMatrixSetRownnz(C_diag); C_offd = hypre_ParCSRMatrixOffd(C); hypre_CSRMatrixI(C_offd) = C_offd_i; hypre_ParCSRMatrixOffd(C) = C_offd; if (num_cols_offd_C) { hypre_CSRMatrixData(C_offd) = C_offd_data; hypre_CSRMatrixJ(C_offd) = C_offd_j; hypre_ParCSRMatrixColMapOffd(C) = col_map_offd_C; } hypre_CSRMatrixSetRownnz(C_offd); hypre_CSRMatrixMemoryLocation(C_diag) = memory_location_C; hypre_CSRMatrixMemoryLocation(C_offd) = memory_location_C; /*----------------------------------------------------------------------- * Free various arrays *-----------------------------------------------------------------------*/ hypre_TFree(B_ext_diag_i, HYPRE_MEMORY_HOST); if (B_ext_diag_size) { hypre_TFree(B_ext_diag_j, HYPRE_MEMORY_HOST); hypre_TFree(B_ext_diag_data, HYPRE_MEMORY_HOST); } hypre_TFree(B_ext_offd_i, HYPRE_MEMORY_HOST); if (B_ext_offd_size) { hypre_TFree(B_ext_offd_j, HYPRE_MEMORY_HOST); hypre_TFree(B_ext_offd_data, HYPRE_MEMORY_HOST); } if (num_cols_offd_B) { hypre_TFree(map_B_to_C, HYPRE_MEMORY_HOST); } hypre_TFree(rownnz_A, HYPRE_MEMORY_HOST); #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_MATMUL] += hypre_MPI_Wtime(); #endif return C; } /* The following function was formerly part of hypre_ParCSRMatrixExtractBExt but the code was removed so it can be used for a corresponding function for Boolean matrices JSP: to allow communication overlapping, it returns comm_handle_idx and comm_handle_data. Before accessing B, they should be destroyed (including send_data contained in the comm_handle). */ void hypre_ParCSRMatrixExtractBExt_Arrays_Overlap( HYPRE_Int ** pB_ext_i, HYPRE_BigInt ** pB_ext_j, HYPRE_Complex ** pB_ext_data, HYPRE_BigInt ** pB_ext_row_map, HYPRE_Int * num_nonzeros, HYPRE_Int data, HYPRE_Int find_row_map, MPI_Comm comm, hypre_ParCSRCommPkg * comm_pkg, HYPRE_Int num_cols_B, HYPRE_Int num_recvs, HYPRE_Int num_sends, HYPRE_BigInt first_col_diag, HYPRE_BigInt * row_starts, HYPRE_Int * recv_vec_starts, HYPRE_Int * send_map_starts, HYPRE_Int * send_map_elmts, HYPRE_Int * diag_i, HYPRE_Int * diag_j, HYPRE_Int * offd_i, HYPRE_Int * offd_j, HYPRE_BigInt * col_map_offd, HYPRE_Real * diag_data, HYPRE_Real * offd_data, hypre_ParCSRCommHandle **comm_handle_idx, hypre_ParCSRCommHandle **comm_handle_data, HYPRE_Int *CF_marker, HYPRE_Int *CF_marker_offd, HYPRE_Int skip_fine, /* 1 if only coarse points are needed */ HYPRE_Int skip_same_sign /* 1 if only points that have the same sign are needed */ // extended based long range interpolation: skip_fine = 1, skip_same_sign = 0 for S matrix, skip_fine = 1, skip_same_sign = 1 for A matrix // other interpolation: skip_fine = 0, skip_same_sign = 0 ) { hypre_ParCSRCommHandle *comm_handle, *row_map_comm_handle = NULL; hypre_ParCSRCommPkg *tmp_comm_pkg; HYPRE_Int *B_int_i; HYPRE_BigInt *B_int_j; HYPRE_Int *B_ext_i; HYPRE_BigInt * B_ext_j; HYPRE_Complex * B_ext_data; HYPRE_Complex * B_int_data; HYPRE_BigInt * B_int_row_map; HYPRE_BigInt * B_ext_row_map; HYPRE_Int num_procs, my_id; HYPRE_Int *jdata_recv_vec_starts; HYPRE_Int *jdata_send_map_starts; HYPRE_Int i, j, k; HYPRE_Int start_index; /*HYPRE_Int jrow;*/ HYPRE_Int num_rows_B_ext; HYPRE_Int *prefix_sum_workspace; hypre_MPI_Comm_size(comm,&num_procs); hypre_MPI_Comm_rank(comm,&my_id); HYPRE_BigInt first_row_index = row_starts[0]; num_rows_B_ext = recv_vec_starts[num_recvs]; if ( num_rows_B_ext < 0 ) { /* no B_ext, no communication */ *pB_ext_i = NULL; *pB_ext_j = NULL; if ( data ) *pB_ext_data = NULL; if ( find_row_map ) *pB_ext_row_map = NULL; *num_nonzeros = 0; return; }; B_int_i = hypre_CTAlloc(HYPRE_Int, send_map_starts[num_sends]+1, HYPRE_MEMORY_HOST); B_ext_i = hypre_CTAlloc(HYPRE_Int, num_rows_B_ext+1, HYPRE_MEMORY_HOST); *pB_ext_i = B_ext_i; if ( find_row_map ) { B_int_row_map = hypre_CTAlloc( HYPRE_BigInt, send_map_starts[num_sends]+1 , HYPRE_MEMORY_HOST); B_ext_row_map = hypre_CTAlloc( HYPRE_BigInt, num_rows_B_ext+1 , HYPRE_MEMORY_HOST); *pB_ext_row_map = B_ext_row_map; }; /*-------------------------------------------------------------------------- * generate B_int_i through adding number of row-elements of offd and diag * for corresponding rows. B_int_i[j+1] contains the number of elements of * a row j (which is determined through send_map_elmts) *--------------------------------------------------------------------------*/ jdata_send_map_starts = hypre_CTAlloc(HYPRE_Int, num_sends+1, HYPRE_MEMORY_HOST); jdata_recv_vec_starts = hypre_CTAlloc(HYPRE_Int, num_recvs+1, HYPRE_MEMORY_HOST); jdata_send_map_starts[0] = B_int_i[0] = 0; /*HYPRE_Int prefix_sum_workspace[(hypre_NumThreads() + 1)*num_sends];*/ prefix_sum_workspace = hypre_TAlloc(HYPRE_Int, (hypre_NumThreads() + 1)*num_sends, HYPRE_MEMORY_HOST); #ifdef HYPRE_USING_OPENMP #pragma omp parallel private(i,j,k) #endif { /*HYPRE_Int counts[num_sends];*/ HYPRE_Int *counts; counts = hypre_TAlloc(HYPRE_Int, num_sends, HYPRE_MEMORY_HOST); for (i=0; i < num_sends; i++) { HYPRE_Int j_begin, j_end; hypre_GetSimpleThreadPartition(&j_begin, &j_end, send_map_starts[i + 1] - send_map_starts[i]); j_begin += send_map_starts[i]; j_end += send_map_starts[i]; HYPRE_Int count = 0; if (skip_fine && skip_same_sign) { for (j = j_begin; j < j_end; j++) { HYPRE_Int jrow = send_map_elmts[j]; HYPRE_Int len = 0; if (diag_data[diag_i[jrow]] >= 0) { for (k = diag_i[jrow] + 1; k < diag_i[jrow + 1]; k++) { if (diag_data[k] < 0 && CF_marker[diag_j[k]] >= 0) len++; } for (k = offd_i[jrow]; k < offd_i[jrow + 1]; k++) { if (offd_data[k] < 0) len++; } } else { for (k = diag_i[jrow] + 1; k < diag_i[jrow + 1]; k++) { if (diag_data[k] > 0 && CF_marker[diag_j[k]] >= 0) len++; } for (k = offd_i[jrow]; k < offd_i[jrow + 1]; k++) { if (offd_data[k] > 0) len++; } } B_int_i[j + 1] = len; count += len; } } else if (skip_fine) { for (j = j_begin; j < j_end; j++) { HYPRE_Int jrow = send_map_elmts[j]; HYPRE_Int len = 0; for (k = diag_i[jrow]; k < diag_i[jrow + 1]; k++) { if (CF_marker[diag_j[k]] >= 0) len++; } for (k = offd_i[jrow]; k < offd_i[jrow + 1]; k++) { if (CF_marker_offd[offd_j[k]] >= 0) len++; } B_int_i[j + 1] = len; count += len; } } else { for (j = j_begin; j < j_end; j++) { HYPRE_Int jrow = send_map_elmts[j]; HYPRE_Int len = diag_i[jrow + 1] - diag_i[jrow]; len += offd_i[jrow + 1] - offd_i[jrow]; B_int_i[j + 1] = len; count += len; } } if (find_row_map) { for (j = j_begin; j < j_end; j++) { HYPRE_Int jrow = send_map_elmts[j]; B_int_row_map[j] = (HYPRE_BigInt)jrow + first_row_index; } } counts[i] = count; } hypre_prefix_sum_multiple(counts, jdata_send_map_starts + 1, num_sends, prefix_sum_workspace); #ifdef HYPRE_USING_OPENMP #pragma omp master #endif { for (i = 1; i < num_sends; i++) { jdata_send_map_starts[i + 1] += jdata_send_map_starts[i]; } /*-------------------------------------------------------------------------- * initialize communication *--------------------------------------------------------------------------*/ comm_handle = hypre_ParCSRCommHandleCreate(11,comm_pkg, &B_int_i[1],&(B_ext_i[1]) ); if ( find_row_map ) { /* scatter/gather B_int row numbers to form array of B_ext row numbers */ row_map_comm_handle = hypre_ParCSRCommHandleCreate (21,comm_pkg, B_int_row_map, B_ext_row_map ); } B_int_j = hypre_TAlloc(HYPRE_BigInt, jdata_send_map_starts[num_sends], HYPRE_MEMORY_HOST); if (data) B_int_data = hypre_TAlloc(HYPRE_Complex, jdata_send_map_starts[num_sends], HYPRE_MEMORY_HOST); } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif for (i = 0; i < num_sends; i++) { HYPRE_Int j_begin, j_end; hypre_GetSimpleThreadPartition(&j_begin, &j_end, send_map_starts[i + 1] - send_map_starts[i]); j_begin += send_map_starts[i]; j_end += send_map_starts[i]; HYPRE_Int count = counts[i] + jdata_send_map_starts[i]; if (data) { if (skip_same_sign && skip_fine) { for (j = j_begin; j < j_end; j++) { HYPRE_Int jrow = send_map_elmts[j]; /*HYPRE_Int count_begin = count;*/ if (diag_data[diag_i[jrow]] >= 0) { for (k = diag_i[jrow] + 1; k < diag_i[jrow + 1]; k++) { if (diag_data[k] < 0 && CF_marker[diag_j[k]] >= 0) { B_int_j[count] = (HYPRE_BigInt)diag_j[k]+first_col_diag; B_int_data[count] = diag_data[k]; count++; } } for (k = offd_i[jrow]; k < offd_i[jrow + 1]; k++) { HYPRE_Int c = offd_j[k]; HYPRE_BigInt c_global = col_map_offd[c]; if (offd_data[k] < 0) { B_int_j[count] = c_global; B_int_data[count] = offd_data[k]; count++; } } } else { for (k = diag_i[jrow] + 1; k < diag_i[jrow + 1]; k++) { if (diag_data[k] > 0 && CF_marker[diag_j[k]] >= 0) { B_int_j[count] = (HYPRE_BigInt)diag_j[k]+first_col_diag; B_int_data[count] = diag_data[k]; count++; } } for (k = offd_i[jrow]; k < offd_i[jrow + 1]; k++) { HYPRE_Int c = offd_j[k]; HYPRE_BigInt c_global = col_map_offd[c]; if (offd_data[k] > 0) { B_int_j[count] = c_global; B_int_data[count] = offd_data[k]; count++; } } } } } else { for (j = j_begin; j < j_end; ++j) { HYPRE_Int jrow = send_map_elmts[j]; for (k = diag_i[jrow]; k < diag_i[jrow+1]; k++) { B_int_j[count] = (HYPRE_BigInt)diag_j[k]+first_col_diag; B_int_data[count] = diag_data[k]; count++; } for (k = offd_i[jrow]; k < offd_i[jrow+1]; k++) { B_int_j[count] = col_map_offd[offd_j[k]]; B_int_data[count] = offd_data[k]; count++; } } } } // data else { if (skip_fine) { for (j = j_begin; j < j_end; j++) { HYPRE_Int jrow = send_map_elmts[j]; for (k = diag_i[jrow]; k < diag_i[jrow + 1]; k++) { if (CF_marker[diag_j[k]] >= 0) { B_int_j[count] = (HYPRE_BigInt)diag_j[k] + first_col_diag; count++; } } for (k = offd_i[jrow]; k < offd_i[jrow + 1]; k++) { if (CF_marker_offd[offd_j[k]] >= 0) { B_int_j[count] = col_map_offd[offd_j[k]]; count++; } } } } else { for (j = j_begin; j < j_end; ++j) { HYPRE_Int jrow = send_map_elmts[j]; for (k = diag_i[jrow]; k < diag_i[jrow+1]; k++) { B_int_j[count] = (HYPRE_BigInt)diag_j[k]+first_col_diag; count++; } for (k = offd_i[jrow]; k < offd_i[jrow+1]; k++) { B_int_j[count] = col_map_offd[offd_j[k]]; count++; } } } } // !data } /* for each send target */ hypre_TFree(counts, HYPRE_MEMORY_HOST); } /* omp parallel. JSP: this takes most of time in this function */ hypre_TFree(prefix_sum_workspace, HYPRE_MEMORY_HOST); tmp_comm_pkg = hypre_CTAlloc(hypre_ParCSRCommPkg, 1, HYPRE_MEMORY_HOST); hypre_ParCSRCommPkgComm(tmp_comm_pkg) = comm; hypre_ParCSRCommPkgNumSends(tmp_comm_pkg) = num_sends; hypre_ParCSRCommPkgNumRecvs(tmp_comm_pkg) = num_recvs; hypre_ParCSRCommPkgSendProcs(tmp_comm_pkg) = hypre_ParCSRCommPkgSendProcs(comm_pkg); hypre_ParCSRCommPkgRecvProcs(tmp_comm_pkg) = hypre_ParCSRCommPkgRecvProcs(comm_pkg); hypre_ParCSRCommPkgSendMapStarts(tmp_comm_pkg) = jdata_send_map_starts; hypre_ParCSRCommHandleDestroy(comm_handle); comm_handle = NULL; /*-------------------------------------------------------------------------- * after communication exchange B_ext_i[j+1] contains the number of elements * of a row j ! * evaluate B_ext_i and compute *num_nonzeros for B_ext *--------------------------------------------------------------------------*/ for (i = 0; i < num_recvs; i++) { for (j = recv_vec_starts[i]; j < recv_vec_starts[i+1]; j++) { B_ext_i[j+1] += B_ext_i[j]; } } *num_nonzeros = B_ext_i[num_rows_B_ext]; *pB_ext_j = hypre_TAlloc(HYPRE_BigInt, *num_nonzeros, HYPRE_MEMORY_HOST); B_ext_j = *pB_ext_j; if (data) { *pB_ext_data = hypre_TAlloc(HYPRE_Complex, *num_nonzeros, HYPRE_MEMORY_HOST); B_ext_data = *pB_ext_data; } for (i = 0; i < num_recvs; i++) { start_index = B_ext_i[recv_vec_starts[i]]; *num_nonzeros = B_ext_i[recv_vec_starts[i+1]]-start_index; jdata_recv_vec_starts[i+1] = B_ext_i[recv_vec_starts[i+1]]; } hypre_ParCSRCommPkgRecvVecStarts(tmp_comm_pkg) = jdata_recv_vec_starts; *comm_handle_idx = hypre_ParCSRCommHandleCreate(21,tmp_comm_pkg,B_int_j,B_ext_j); if (data) { *comm_handle_data = hypre_ParCSRCommHandleCreate(1,tmp_comm_pkg,B_int_data, B_ext_data); } if (row_map_comm_handle) { hypre_ParCSRCommHandleDestroy(row_map_comm_handle); row_map_comm_handle = NULL; } hypre_TFree(jdata_send_map_starts, HYPRE_MEMORY_HOST); hypre_TFree(jdata_recv_vec_starts, HYPRE_MEMORY_HOST); hypre_TFree(tmp_comm_pkg, HYPRE_MEMORY_HOST); hypre_TFree(B_int_i, HYPRE_MEMORY_HOST); if ( find_row_map ) hypre_TFree(B_int_row_map, HYPRE_MEMORY_HOST); /* end generic part */ } void hypre_ParCSRMatrixExtractBExt_Arrays( HYPRE_Int ** pB_ext_i, HYPRE_BigInt ** pB_ext_j, HYPRE_Complex ** pB_ext_data, HYPRE_BigInt ** pB_ext_row_map, HYPRE_Int * num_nonzeros, HYPRE_Int data, HYPRE_Int find_row_map, MPI_Comm comm, hypre_ParCSRCommPkg * comm_pkg, HYPRE_Int num_cols_B, HYPRE_Int num_recvs, HYPRE_Int num_sends, HYPRE_BigInt first_col_diag, HYPRE_BigInt * row_starts, HYPRE_Int * recv_vec_starts, HYPRE_Int * send_map_starts, HYPRE_Int * send_map_elmts, HYPRE_Int * diag_i, HYPRE_Int * diag_j, HYPRE_Int * offd_i, HYPRE_Int * offd_j, HYPRE_BigInt * col_map_offd, HYPRE_Real * diag_data, HYPRE_Real * offd_data ) { hypre_ParCSRCommHandle *comm_handle_idx, *comm_handle_data; hypre_ParCSRMatrixExtractBExt_Arrays_Overlap( pB_ext_i, pB_ext_j, pB_ext_data, pB_ext_row_map, num_nonzeros, data, find_row_map, comm, comm_pkg, num_cols_B, num_recvs, num_sends, first_col_diag, row_starts, recv_vec_starts, send_map_starts, send_map_elmts, diag_i, diag_j, offd_i, offd_j, col_map_offd, diag_data, offd_data, &comm_handle_idx, &comm_handle_data, NULL, NULL, 0, 0); HYPRE_Int *send_idx = (HYPRE_Int *)comm_handle_idx->send_data; hypre_ParCSRCommHandleDestroy(comm_handle_idx); hypre_TFree(send_idx, HYPRE_MEMORY_HOST); if (data) { HYPRE_Real *send_data = (HYPRE_Real *)comm_handle_data->send_data; hypre_ParCSRCommHandleDestroy(comm_handle_data); hypre_TFree(send_data, HYPRE_MEMORY_HOST); } } /*-------------------------------------------------------------------------- * hypre_ParCSRMatrixExtractBExt : extracts rows from B which are located on * other processors and needed for multiplication with A locally. The rows * are returned as CSRMatrix. *--------------------------------------------------------------------------*/ hypre_CSRMatrix * hypre_ParCSRMatrixExtractBExt_Overlap( hypre_ParCSRMatrix *B, hypre_ParCSRMatrix *A, HYPRE_Int data, hypre_ParCSRCommHandle **comm_handle_idx, hypre_ParCSRCommHandle **comm_handle_data, HYPRE_Int *CF_marker, HYPRE_Int *CF_marker_offd, HYPRE_Int skip_fine, HYPRE_Int skip_same_sign ) { MPI_Comm comm = hypre_ParCSRMatrixComm(B); HYPRE_BigInt first_col_diag = hypre_ParCSRMatrixFirstColDiag(B); /*HYPRE_Int first_row_index = hypre_ParCSRMatrixFirstRowIndex(B);*/ HYPRE_BigInt *col_map_offd = hypre_ParCSRMatrixColMapOffd(B); hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(A); HYPRE_Int num_recvs; HYPRE_Int *recv_vec_starts; HYPRE_Int num_sends; HYPRE_Int *send_map_starts; HYPRE_Int *send_map_elmts; hypre_CSRMatrix *diag = hypre_ParCSRMatrixDiag(B); HYPRE_Int *diag_i = hypre_CSRMatrixI(diag); HYPRE_Int *diag_j = hypre_CSRMatrixJ(diag); HYPRE_Real *diag_data = hypre_CSRMatrixData(diag); hypre_CSRMatrix *offd = hypre_ParCSRMatrixOffd(B); HYPRE_Int *offd_i = hypre_CSRMatrixI(offd); HYPRE_Int *offd_j = hypre_CSRMatrixJ(offd); HYPRE_Real *offd_data = hypre_CSRMatrixData(offd); HYPRE_Int num_cols_B, num_nonzeros; HYPRE_Int num_rows_B_ext; hypre_CSRMatrix *B_ext; HYPRE_Int *B_ext_i; HYPRE_BigInt *B_ext_j; HYPRE_Complex *B_ext_data; HYPRE_BigInt *idummy; /*--------------------------------------------------------------------- * If there exists no CommPkg for A, a CommPkg is generated using * equally load balanced partitionings *--------------------------------------------------------------------*/ if (!hypre_ParCSRMatrixCommPkg(A)) { hypre_MatvecCommPkgCreate(A); } comm_pkg = hypre_ParCSRMatrixCommPkg(A); num_recvs = hypre_ParCSRCommPkgNumRecvs(comm_pkg); recv_vec_starts = hypre_ParCSRCommPkgRecvVecStarts(comm_pkg); num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); send_map_starts = hypre_ParCSRCommPkgSendMapStarts(comm_pkg); send_map_elmts = hypre_ParCSRCommPkgSendMapElmts(comm_pkg); num_cols_B = hypre_ParCSRMatrixGlobalNumCols(B); num_rows_B_ext = recv_vec_starts[num_recvs]; hypre_ParCSRMatrixExtractBExt_Arrays_Overlap ( &B_ext_i, &B_ext_j, &B_ext_data, &idummy, &num_nonzeros, data, 0, comm, comm_pkg, num_cols_B, num_recvs, num_sends, first_col_diag, B->row_starts, recv_vec_starts, send_map_starts, send_map_elmts, diag_i, diag_j, offd_i, offd_j, col_map_offd, diag_data, offd_data, comm_handle_idx, comm_handle_data, CF_marker, CF_marker_offd, skip_fine, skip_same_sign ); B_ext = hypre_CSRMatrixCreate(num_rows_B_ext,num_cols_B,num_nonzeros); hypre_CSRMatrixMemoryLocation(B_ext) = HYPRE_MEMORY_HOST; hypre_CSRMatrixI(B_ext) = B_ext_i; hypre_CSRMatrixBigJ(B_ext) = B_ext_j; if (data) hypre_CSRMatrixData(B_ext) = B_ext_data; return B_ext; } hypre_CSRMatrix * hypre_ParCSRMatrixExtractBExt( hypre_ParCSRMatrix *B, hypre_ParCSRMatrix *A, HYPRE_Int want_data ) { #if 0 hypre_ParCSRCommHandle *comm_handle_idx, *comm_handle_data; hypre_CSRMatrix *B_ext = hypre_ParCSRMatrixExtractBExt_Overlap(B, A, want_data, &comm_handle_idx, &comm_handle_data, NULL, NULL, 0, 0); HYPRE_Int *send_idx = (HYPRE_Int *)comm_handle_idx->send_data; hypre_ParCSRCommHandleDestroy(comm_handle_idx); hypre_TFree(send_idx, HYPRE_MEMORY_HOST); if (want_data) { HYPRE_Real *send_data = (HYPRE_Real *)comm_handle_data->send_data; hypre_ParCSRCommHandleDestroy(comm_handle_data); hypre_TFree(send_data, HYPRE_MEMORY_HOST); } #else hypre_assert( hypre_CSRMatrixMemoryLocation(hypre_ParCSRMatrixDiag(B)) == hypre_CSRMatrixMemoryLocation(hypre_ParCSRMatrixOffd(B)) ); hypre_CSRMatrix *B_ext; void *request; if (!hypre_ParCSRMatrixCommPkg(A)) { hypre_MatvecCommPkgCreate(A); } hypre_ParcsrGetExternalRowsInit(B, hypre_CSRMatrixNumCols(hypre_ParCSRMatrixOffd(A)), hypre_ParCSRMatrixColMapOffd(A), hypre_ParCSRMatrixCommPkg(A), want_data, &request); B_ext = hypre_ParcsrGetExternalRowsWait(request); #endif return B_ext; } /*-------------------------------------------------------------------------- * hypre_ParCSRMatrixTranspose *--------------------------------------------------------------------------*/ HYPRE_Int hypre_ParCSRMatrixTransposeHost( hypre_ParCSRMatrix *A, hypre_ParCSRMatrix **AT_ptr, HYPRE_Int data ) { hypre_ParCSRCommHandle *comm_handle; MPI_Comm comm = hypre_ParCSRMatrixComm(A); hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(A); hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A); HYPRE_Int num_cols = hypre_ParCSRMatrixNumCols(A); HYPRE_BigInt first_row_index = hypre_ParCSRMatrixFirstRowIndex(A); HYPRE_BigInt *row_starts = hypre_ParCSRMatrixRowStarts(A); HYPRE_BigInt *col_starts = hypre_ParCSRMatrixColStarts(A); HYPRE_Int num_cols_offd = hypre_CSRMatrixNumCols(A_offd); HYPRE_Int ierr = 0; HYPRE_Int num_sends, num_recvs, num_cols_offd_AT; HYPRE_Int i, j, k, index, counter, j_row; HYPRE_BigInt value; hypre_ParCSRMatrix *AT; hypre_CSRMatrix *AT_diag; hypre_CSRMatrix *AT_offd; hypre_CSRMatrix *AT_tmp; HYPRE_BigInt first_row_index_AT, first_col_diag_AT; HYPRE_Int local_num_rows_AT, local_num_cols_AT; HYPRE_Int *AT_tmp_i; HYPRE_Int *AT_tmp_j; HYPRE_BigInt *AT_big_j = NULL; HYPRE_Complex *AT_tmp_data; HYPRE_Int *AT_buf_i; HYPRE_BigInt *AT_buf_j; HYPRE_Complex *AT_buf_data; HYPRE_Int *AT_offd_i; HYPRE_Int *AT_offd_j; HYPRE_Complex *AT_offd_data; HYPRE_BigInt *col_map_offd_AT; HYPRE_BigInt *row_starts_AT; HYPRE_BigInt *col_starts_AT; HYPRE_Int num_procs, my_id; HYPRE_Int *recv_procs; HYPRE_Int *send_procs; HYPRE_Int *recv_vec_starts; HYPRE_Int *send_map_starts; HYPRE_Int *send_map_elmts; HYPRE_Int *tmp_recv_vec_starts; HYPRE_Int *tmp_send_map_starts; hypre_ParCSRCommPkg *tmp_comm_pkg; hypre_MPI_Comm_size(comm,&num_procs); hypre_MPI_Comm_rank(comm,&my_id); num_cols_offd_AT = 0; counter = 0; AT_offd_j = NULL; AT_offd_data = NULL; col_map_offd_AT = NULL; HYPRE_MemoryLocation memory_location = hypre_ParCSRMatrixMemoryLocation(A); /*--------------------------------------------------------------------- * If there exists no CommPkg for A, a CommPkg is generated using * equally load balanced partitionings *--------------------------------------------------------------------*/ if (!comm_pkg) { hypre_MatvecCommPkgCreate(A); comm_pkg = hypre_ParCSRMatrixCommPkg(A); } if (num_procs > 1) { hypre_CSRMatrixTranspose (A_offd, &AT_tmp, data); AT_tmp_i = hypre_CSRMatrixI(AT_tmp); AT_tmp_j = hypre_CSRMatrixJ(AT_tmp); if (data) { AT_tmp_data = hypre_CSRMatrixData(AT_tmp); } num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); num_recvs = hypre_ParCSRCommPkgNumRecvs(comm_pkg); recv_procs = hypre_ParCSRCommPkgRecvProcs(comm_pkg); send_procs = hypre_ParCSRCommPkgSendProcs(comm_pkg); recv_vec_starts = hypre_ParCSRCommPkgRecvVecStarts(comm_pkg); send_map_starts = hypre_ParCSRCommPkgSendMapStarts(comm_pkg); send_map_elmts = hypre_ParCSRCommPkgSendMapElmts(comm_pkg); AT_buf_i = hypre_CTAlloc(HYPRE_Int, send_map_starts[num_sends], HYPRE_MEMORY_HOST); if (AT_tmp_i[num_cols_offd]) { AT_big_j = hypre_CTAlloc(HYPRE_BigInt, AT_tmp_i[num_cols_offd], HYPRE_MEMORY_HOST); } for (i = 0; i < AT_tmp_i[num_cols_offd]; i++) { //AT_tmp_j[i] += first_row_index; AT_big_j[i] = (HYPRE_BigInt)AT_tmp_j[i]+first_row_index; } for (i = 0; i < num_cols_offd; i++) { AT_tmp_i[i] = AT_tmp_i[i+1]-AT_tmp_i[i]; } comm_handle = hypre_ParCSRCommHandleCreate(12, comm_pkg, AT_tmp_i, AT_buf_i); } hypre_CSRMatrixTranspose(A_diag, &AT_diag, data); AT_offd_i = hypre_CTAlloc(HYPRE_Int, num_cols+1, memory_location); if (num_procs > 1) { hypre_ParCSRCommHandleDestroy(comm_handle); comm_handle = NULL; tmp_send_map_starts = hypre_CTAlloc(HYPRE_Int, num_sends+1, HYPRE_MEMORY_HOST); tmp_recv_vec_starts = hypre_CTAlloc(HYPRE_Int, num_recvs+1, HYPRE_MEMORY_HOST); tmp_send_map_starts[0] = send_map_starts[0]; for (i = 0; i < num_sends; i++) { tmp_send_map_starts[i+1] = tmp_send_map_starts[i]; for (j = send_map_starts[i]; j < send_map_starts[i+1]; j++) { tmp_send_map_starts[i+1] += AT_buf_i[j]; AT_offd_i[send_map_elmts[j]+1] += AT_buf_i[j]; } } for (i = 0; i < num_cols; i++) { AT_offd_i[i+1] += AT_offd_i[i]; } tmp_recv_vec_starts[0] = recv_vec_starts[0]; for (i = 0; i < num_recvs; i++) { tmp_recv_vec_starts[i+1] = tmp_recv_vec_starts[i]; for (j = recv_vec_starts[i]; j < recv_vec_starts[i+1]; j++) { tmp_recv_vec_starts[i+1] += AT_tmp_i[j]; } } tmp_comm_pkg = hypre_CTAlloc(hypre_ParCSRCommPkg, 1, HYPRE_MEMORY_HOST); hypre_ParCSRCommPkgComm(tmp_comm_pkg) = comm; hypre_ParCSRCommPkgNumSends(tmp_comm_pkg) = num_sends; hypre_ParCSRCommPkgNumRecvs(tmp_comm_pkg) = num_recvs; hypre_ParCSRCommPkgRecvProcs(tmp_comm_pkg) = recv_procs; hypre_ParCSRCommPkgSendProcs(tmp_comm_pkg) = send_procs; hypre_ParCSRCommPkgRecvVecStarts(tmp_comm_pkg) = tmp_recv_vec_starts; hypre_ParCSRCommPkgSendMapStarts(tmp_comm_pkg) = tmp_send_map_starts; AT_buf_j = hypre_CTAlloc(HYPRE_BigInt, tmp_send_map_starts[num_sends], HYPRE_MEMORY_HOST); comm_handle = hypre_ParCSRCommHandleCreate(22, tmp_comm_pkg, AT_big_j, AT_buf_j); hypre_ParCSRCommHandleDestroy(comm_handle); comm_handle = NULL; hypre_TFree(AT_big_j, HYPRE_MEMORY_HOST); if (data) { AT_buf_data = hypre_CTAlloc(HYPRE_Complex, tmp_send_map_starts[num_sends], HYPRE_MEMORY_HOST); comm_handle = hypre_ParCSRCommHandleCreate(2,tmp_comm_pkg,AT_tmp_data, AT_buf_data); hypre_ParCSRCommHandleDestroy(comm_handle); comm_handle = NULL; } hypre_TFree(tmp_recv_vec_starts, HYPRE_MEMORY_HOST); hypre_TFree(tmp_send_map_starts, HYPRE_MEMORY_HOST); hypre_TFree(tmp_comm_pkg, HYPRE_MEMORY_HOST); hypre_CSRMatrixDestroy(AT_tmp); if (AT_offd_i[num_cols]) { AT_offd_j = hypre_CTAlloc(HYPRE_Int, AT_offd_i[num_cols], memory_location); AT_big_j = hypre_CTAlloc(HYPRE_BigInt, AT_offd_i[num_cols], HYPRE_MEMORY_HOST); if (data) { AT_offd_data = hypre_CTAlloc(HYPRE_Complex, AT_offd_i[num_cols], memory_location); } } else { AT_offd_j = NULL; AT_offd_data = NULL; } counter = 0; for (i = 0; i < num_sends; i++) { for (j = send_map_starts[i]; j < send_map_starts[i+1]; j++) { j_row = send_map_elmts[j]; index = AT_offd_i[j_row]; for (k = 0; k < AT_buf_i[j]; k++) { if (data) { AT_offd_data[index] = AT_buf_data[counter]; } AT_big_j[index++] = AT_buf_j[counter++]; } AT_offd_i[j_row] = index; } } for (i = num_cols; i > 0; i--) { AT_offd_i[i] = AT_offd_i[i-1]; } AT_offd_i[0] = 0; if (counter) { hypre_BigQsort0(AT_buf_j,0,counter-1); num_cols_offd_AT = 1; value = AT_buf_j[0]; for (i = 1; i < counter; i++) { if (value < AT_buf_j[i]) { AT_buf_j[num_cols_offd_AT++] = AT_buf_j[i]; value = AT_buf_j[i]; } } } if (num_cols_offd_AT) { col_map_offd_AT = hypre_CTAlloc(HYPRE_BigInt, num_cols_offd_AT, HYPRE_MEMORY_HOST); } else { col_map_offd_AT = NULL; } for (i = 0; i < num_cols_offd_AT; i++) { col_map_offd_AT[i] = AT_buf_j[i]; } hypre_TFree(AT_buf_i, HYPRE_MEMORY_HOST); hypre_TFree(AT_buf_j, HYPRE_MEMORY_HOST); if (data) { hypre_TFree(AT_buf_data, HYPRE_MEMORY_HOST); } for (i = 0; i < counter; i++) { AT_offd_j[i] = hypre_BigBinarySearch(col_map_offd_AT,AT_big_j[i], num_cols_offd_AT); } hypre_TFree(AT_big_j, HYPRE_MEMORY_HOST); } AT_offd = hypre_CSRMatrixCreate(num_cols, num_cols_offd_AT, counter); hypre_CSRMatrixMemoryLocation(AT_offd) = memory_location; hypre_CSRMatrixI(AT_offd) = AT_offd_i; hypre_CSRMatrixJ(AT_offd) = AT_offd_j; hypre_CSRMatrixData(AT_offd) = AT_offd_data; row_starts_AT = hypre_CTAlloc(HYPRE_BigInt, 2, HYPRE_MEMORY_HOST); for (i = 0; i < 2; i++) { row_starts_AT[i] = col_starts[i]; } if (row_starts != col_starts) { col_starts_AT = hypre_CTAlloc(HYPRE_BigInt, 2, HYPRE_MEMORY_HOST); for (i = 0; i < 2; i++) { col_starts_AT[i] = row_starts[i]; } } else { col_starts_AT = row_starts_AT; } first_row_index_AT = row_starts_AT[0]; first_col_diag_AT = col_starts_AT[0]; local_num_rows_AT = (HYPRE_Int)(row_starts_AT[1]-first_row_index_AT ); local_num_cols_AT = (HYPRE_Int)(col_starts_AT[1]-first_col_diag_AT); AT = hypre_CTAlloc(hypre_ParCSRMatrix, 1, HYPRE_MEMORY_HOST); hypre_ParCSRMatrixComm(AT) = comm; hypre_ParCSRMatrixDiag(AT) = AT_diag; hypre_ParCSRMatrixOffd(AT) = AT_offd; hypre_ParCSRMatrixGlobalNumRows(AT) = hypre_ParCSRMatrixGlobalNumCols(A); hypre_ParCSRMatrixGlobalNumCols(AT) = hypre_ParCSRMatrixGlobalNumRows(A); hypre_ParCSRMatrixRowStarts(AT) = row_starts_AT; hypre_ParCSRMatrixColStarts(AT) = col_starts_AT; hypre_ParCSRMatrixColMapOffd(AT) = col_map_offd_AT; hypre_ParCSRMatrixFirstRowIndex(AT) = first_row_index_AT; hypre_ParCSRMatrixFirstColDiag(AT) = first_col_diag_AT; hypre_ParCSRMatrixLastRowIndex(AT) = first_row_index_AT + local_num_rows_AT - 1; hypre_ParCSRMatrixLastColDiag(AT) = first_col_diag_AT + local_num_cols_AT - 1; hypre_ParCSRMatrixOwnsData(AT) = 1; hypre_ParCSRMatrixOwnsRowStarts(AT) = 1; hypre_ParCSRMatrixOwnsColStarts(AT) = 1; if (row_starts_AT == col_starts_AT) { hypre_ParCSRMatrixOwnsColStarts(AT) = 0; } hypre_ParCSRMatrixCommPkg(AT) = NULL; hypre_ParCSRMatrixCommPkgT(AT) = NULL; hypre_ParCSRMatrixRowindices(AT) = NULL; hypre_ParCSRMatrixRowvalues(AT) = NULL; hypre_ParCSRMatrixGetrowactive(AT) = 0; hypre_ParCSRMatrixOwnsAssumedPartition(AT) = 1; *AT_ptr = AT; return ierr; } HYPRE_Int hypre_ParCSRMatrixTranspose( hypre_ParCSRMatrix *A, hypre_ParCSRMatrix **AT_ptr, HYPRE_Int data ) { #if defined(HYPRE_USING_CUDA) || defined(HYPRE_USING_HIP) hypre_GpuProfilingPushRange("ParCSRMatrixTranspose"); #endif #if defined(HYPRE_USING_CUDA) || defined(HYPRE_USING_HIP) HYPRE_ExecutionPolicy exec = hypre_GetExecPolicy1( hypre_ParCSRMatrixMemoryLocation(A) ); if (exec == HYPRE_EXEC_DEVICE) { hypre_ParCSRMatrixTransposeDevice(A, AT_ptr, data); } else #endif { hypre_ParCSRMatrixTransposeHost(A, AT_ptr, data); } #if defined(HYPRE_USING_CUDA) || defined(HYPRE_USING_HIP) hypre_GpuProfilingPopRange(); #endif return hypre_error_flag; } /* ----------------------------------------------------------------------------- * generate a parallel spanning tree (for Maxwell Equation) * G_csr is the node to edge connectivity matrix * ----------------------------------------------------------------------------- */ void hypre_ParCSRMatrixGenSpanningTree( hypre_ParCSRMatrix *G_csr, HYPRE_Int **indices, HYPRE_Int G_type ) { HYPRE_BigInt nrows_G, ncols_G; HYPRE_Int *G_diag_i, *G_diag_j, *GT_diag_mat, i, j, k, edge; HYPRE_Int *nodes_marked, *edges_marked, *queue, queue_tail, queue_head, node; HYPRE_Int mypid, nprocs, n_children, *children, nsends, *send_procs, *recv_cnts; HYPRE_Int nrecvs, *recv_procs, n_proc_array, *proc_array, *pgraph_i, *pgraph_j; HYPRE_Int parent, proc, proc2, node2, found, *t_indices, tree_size, *T_diag_i; HYPRE_Int *T_diag_j, *counts, offset; MPI_Comm comm; hypre_ParCSRCommPkg *comm_pkg; hypre_CSRMatrix *G_diag; /* fetch G matrix (G_type = 0 ==> node to edge) */ if (G_type == 0) { nrows_G = hypre_ParCSRMatrixGlobalNumRows(G_csr); ncols_G = hypre_ParCSRMatrixGlobalNumCols(G_csr); G_diag = hypre_ParCSRMatrixDiag(G_csr); G_diag_i = hypre_CSRMatrixI(G_diag); G_diag_j = hypre_CSRMatrixJ(G_diag); } else { nrows_G = hypre_ParCSRMatrixGlobalNumCols(G_csr); ncols_G = hypre_ParCSRMatrixGlobalNumRows(G_csr); G_diag = hypre_ParCSRMatrixDiag(G_csr); T_diag_i = hypre_CSRMatrixI(G_diag); T_diag_j = hypre_CSRMatrixJ(G_diag); counts = hypre_TAlloc(HYPRE_Int, nrows_G , HYPRE_MEMORY_HOST); for (i = 0; i < nrows_G; i++) counts[i] = 0; for (i = 0; i < T_diag_i[ncols_G]; i++) counts[T_diag_j[i]]++; G_diag_i = hypre_TAlloc(HYPRE_Int, (nrows_G+1) , HYPRE_MEMORY_HOST); G_diag_j = hypre_TAlloc(HYPRE_Int, T_diag_i[ncols_G] , HYPRE_MEMORY_HOST); G_diag_i[0] = 0; for (i = 1; i <= nrows_G; i++) G_diag_i[i] = G_diag_i[i-1] + counts[i-1]; for (i = 0; i < ncols_G; i++) { for (j = T_diag_i[i]; j < T_diag_i[i+1]; j++) { k = T_diag_j[j]; offset = G_diag_i[k]++; G_diag_j[offset] = i; } } G_diag_i[0] = 0; for (i = 1; i <= nrows_G; i++) { G_diag_i[i] = G_diag_i[i-1] + counts[i-1]; } hypre_TFree(counts, HYPRE_MEMORY_HOST); } /* form G transpose in special form (2 nodes per edge max) */ GT_diag_mat = hypre_TAlloc(HYPRE_Int, 2 * ncols_G , HYPRE_MEMORY_HOST); for (i = 0; i < 2 * ncols_G; i++) GT_diag_mat[i] = -1; for (i = 0; i < nrows_G; i++) { for (j = G_diag_i[i]; j < G_diag_i[i+1]; j++) { edge = G_diag_j[j]; if (GT_diag_mat[edge*2] == -1) GT_diag_mat[edge*2] = i; else GT_diag_mat[edge*2+1] = i; } } /* BFS on the local matrix graph to find tree */ nodes_marked = hypre_TAlloc(HYPRE_Int, nrows_G , HYPRE_MEMORY_HOST); edges_marked = hypre_TAlloc(HYPRE_Int, ncols_G , HYPRE_MEMORY_HOST); for (i = 0; i < nrows_G; i++) nodes_marked[i] = 0; for (i = 0; i < ncols_G; i++) edges_marked[i] = 0; queue = hypre_TAlloc(HYPRE_Int, nrows_G , HYPRE_MEMORY_HOST); queue_head = 0; queue_tail = 1; queue[0] = 0; nodes_marked[0] = 1; while ((queue_tail-queue_head) > 0) { node = queue[queue_tail-1]; queue_tail--; for (i = G_diag_i[node]; i < G_diag_i[node+1]; i++) { edge = G_diag_j[i]; if (edges_marked[edge] == 0) { if (GT_diag_mat[2*edge+1] != -1) { node2 = GT_diag_mat[2*edge]; if (node2 == node) node2 = GT_diag_mat[2*edge+1]; if (nodes_marked[node2] == 0) { nodes_marked[node2] = 1; edges_marked[edge] = 1; queue[queue_tail] = node2; queue_tail++; } } } } } hypre_TFree(nodes_marked, HYPRE_MEMORY_HOST); hypre_TFree(queue, HYPRE_MEMORY_HOST); hypre_TFree(GT_diag_mat, HYPRE_MEMORY_HOST); /* fetch the communication information from */ comm = hypre_ParCSRMatrixComm(G_csr); hypre_MPI_Comm_rank(comm, &mypid); hypre_MPI_Comm_size(comm, &nprocs); comm_pkg = hypre_ParCSRMatrixCommPkg(G_csr); if (nprocs == 1 && comm_pkg == NULL) { hypre_MatvecCommPkgCreate((hypre_ParCSRMatrix *) G_csr); comm_pkg = hypre_ParCSRMatrixCommPkg(G_csr); } /* construct processor graph based on node-edge connection */ /* (local edges connected to neighbor processor nodes) */ n_children = 0; nrecvs = nsends = 0; if (nprocs > 1) { nsends = hypre_ParCSRCommPkgNumSends(comm_pkg); send_procs = hypre_ParCSRCommPkgSendProcs(comm_pkg); nrecvs = hypre_ParCSRCommPkgNumRecvs(comm_pkg); recv_procs = hypre_ParCSRCommPkgRecvProcs(comm_pkg); proc_array = NULL; if ((nsends+nrecvs) > 0) { n_proc_array = 0; proc_array = hypre_TAlloc(HYPRE_Int, (nsends+nrecvs) , HYPRE_MEMORY_HOST); for (i = 0; i < nsends; i++) proc_array[i] = send_procs[i]; for (i = 0; i < nrecvs; i++) proc_array[nsends+i] = recv_procs[i]; hypre_qsort0(proc_array, 0, nsends+nrecvs-1); n_proc_array = 1; for (i = 1; i < nrecvs+nsends; i++) if (proc_array[i] != proc_array[n_proc_array]) proc_array[n_proc_array++] = proc_array[i]; } pgraph_i = hypre_TAlloc(HYPRE_Int, (nprocs+1) , HYPRE_MEMORY_HOST); recv_cnts = hypre_TAlloc(HYPRE_Int, nprocs , HYPRE_MEMORY_HOST); hypre_MPI_Allgather(&n_proc_array, 1, HYPRE_MPI_INT, recv_cnts, 1, HYPRE_MPI_INT, comm); pgraph_i[0] = 0; for (i = 1; i <= nprocs; i++) pgraph_i[i] = pgraph_i[i-1] + recv_cnts[i-1]; pgraph_j = hypre_TAlloc(HYPRE_Int, pgraph_i[nprocs] , HYPRE_MEMORY_HOST); hypre_MPI_Allgatherv(proc_array, n_proc_array, HYPRE_MPI_INT, pgraph_j, recv_cnts, pgraph_i, HYPRE_MPI_INT, comm); hypre_TFree(recv_cnts, HYPRE_MEMORY_HOST); /* BFS on the processor graph to determine parent and children */ nodes_marked = hypre_TAlloc(HYPRE_Int, nprocs , HYPRE_MEMORY_HOST); for (i = 0; i < nprocs; i++) nodes_marked[i] = -1; queue = hypre_TAlloc(HYPRE_Int, nprocs , HYPRE_MEMORY_HOST); queue_head = 0; queue_tail = 1; node = 0; queue[0] = node; while ((queue_tail-queue_head) > 0) { proc = queue[queue_tail-1]; queue_tail--; for (i = pgraph_i[proc]; i < pgraph_i[proc+1]; i++) { proc2 = pgraph_j[i]; if (nodes_marked[proc2] < 0) { nodes_marked[proc2] = proc; queue[queue_tail] = proc2; queue_tail++; } } } parent = nodes_marked[mypid]; n_children = 0; for (i = 0; i < nprocs; i++) if (nodes_marked[i] == mypid) n_children++; if (n_children == 0) {n_children = 0; children = NULL;} else { children = hypre_TAlloc(HYPRE_Int, n_children , HYPRE_MEMORY_HOST); n_children = 0; for (i = 0; i < nprocs; i++) if (nodes_marked[i] == mypid) children[n_children++] = i; } hypre_TFree(nodes_marked, HYPRE_MEMORY_HOST); hypre_TFree(queue, HYPRE_MEMORY_HOST); hypre_TFree(pgraph_i, HYPRE_MEMORY_HOST); hypre_TFree(pgraph_j, HYPRE_MEMORY_HOST); } /* first, connection with my parent : if the edge in my parent * * is incident to one of my nodes, then my parent will mark it */ found = 0; for (i = 0; i < nrecvs; i++) { proc = hypre_ParCSRCommPkgRecvProc(comm_pkg, i); if (proc == parent) { found = 1; break; } } /* but if all the edges connected to my parent are on my side, * * then I will just pick one of them as tree edge */ if (found == 0) { for (i = 0; i < nsends; i++) { proc = hypre_ParCSRCommPkgSendProc(comm_pkg, i); if (proc == parent) { k = hypre_ParCSRCommPkgSendMapStart(comm_pkg,i); edge = hypre_ParCSRCommPkgSendMapElmt(comm_pkg,k); edges_marked[edge] = 1; break; } } } /* next, if my processor has an edge incident on one node in my * * child, put this edge on the tree. But if there is no such * * edge, then I will assume my child will pick up an edge */ for (j = 0; j < n_children; j++) { proc = children[j]; for (i = 0; i < nsends; i++) { proc2 = hypre_ParCSRCommPkgSendProc(comm_pkg, i); if (proc == proc2) { k = hypre_ParCSRCommPkgSendMapStart(comm_pkg,i); edge = hypre_ParCSRCommPkgSendMapElmt(comm_pkg,k); edges_marked[edge] = 1; break; } } } if (n_children > 0) { hypre_TFree(children, HYPRE_MEMORY_HOST); } /* count the size of the tree */ tree_size = 0; for (i = 0; i < ncols_G; i++) if (edges_marked[i] == 1) tree_size++; t_indices = hypre_TAlloc(HYPRE_Int, (tree_size+1) , HYPRE_MEMORY_HOST); t_indices[0] = tree_size; tree_size = 1; for (i = 0; i < ncols_G; i++) if (edges_marked[i] == 1) t_indices[tree_size++] = i; (*indices) = t_indices; hypre_TFree(edges_marked, HYPRE_MEMORY_HOST); if (G_type != 0) { hypre_TFree(G_diag_i, HYPRE_MEMORY_HOST); hypre_TFree(G_diag_j, HYPRE_MEMORY_HOST); } } /* ----------------------------------------------------------------------------- * extract submatrices based on given indices * ----------------------------------------------------------------------------- */ void hypre_ParCSRMatrixExtractSubmatrices( hypre_ParCSRMatrix *A_csr, HYPRE_Int *indices2, hypre_ParCSRMatrix ***submatrices ) { HYPRE_Int nrows_A, nindices, *indices, *A_diag_i, *A_diag_j, mypid, nprocs; HYPRE_Int i, j, k, *proc_offsets1, *proc_offsets2, *exp_indices; HYPRE_BigInt *itmp_array; HYPRE_Int nnz11, nnz12, nnz21, nnz22, col, ncols_offd, nnz_offd, nnz_diag; HYPRE_Int nrows, nnz; HYPRE_BigInt global_nrows, global_ncols, *row_starts, *col_starts; HYPRE_Int *diag_i, *diag_j, row, *offd_i; HYPRE_Complex *A_diag_a, *diag_a; hypre_ParCSRMatrix *A11_csr, *A12_csr, *A21_csr, *A22_csr; hypre_CSRMatrix *A_diag, *diag, *offd; MPI_Comm comm; /* ----------------------------------------------------- * first make sure the incoming indices are in order * ----------------------------------------------------- */ nindices = indices2[0]; indices = &(indices2[1]); hypre_qsort0(indices, 0, nindices-1); /* ----------------------------------------------------- * fetch matrix information * ----------------------------------------------------- */ nrows_A = (HYPRE_Int) hypre_ParCSRMatrixGlobalNumRows(A_csr); A_diag = hypre_ParCSRMatrixDiag(A_csr); A_diag_i = hypre_CSRMatrixI(A_diag); A_diag_j = hypre_CSRMatrixJ(A_diag); A_diag_a = hypre_CSRMatrixData(A_diag); comm = hypre_ParCSRMatrixComm(A_csr); hypre_MPI_Comm_rank(comm, &mypid); hypre_MPI_Comm_size(comm, &nprocs); if (nprocs > 1) { hypre_error_w_msg(HYPRE_ERROR_GENERIC,"ExtractSubmatrices: cannot handle nprocs > 1 yet.\n"); exit(1); } /* ----------------------------------------------------- * compute new matrix dimensions * ----------------------------------------------------- */ proc_offsets1 = hypre_TAlloc(HYPRE_Int, (nprocs+1) , HYPRE_MEMORY_HOST); proc_offsets2 = hypre_TAlloc(HYPRE_Int, (nprocs+1) , HYPRE_MEMORY_HOST); hypre_MPI_Allgather(&nindices, 1, HYPRE_MPI_INT, proc_offsets1, 1, HYPRE_MPI_INT, comm); k = 0; for (i = 0; i < nprocs; i++) { j = proc_offsets1[i]; proc_offsets1[i] = k; k += j; } proc_offsets1[nprocs] = k; itmp_array = hypre_ParCSRMatrixRowStarts(A_csr); for (i = 0; i <= nprocs; i++) { proc_offsets2[i] = itmp_array[i] - proc_offsets1[i]; } /* ----------------------------------------------------- * assign id's to row and col for later processing * ----------------------------------------------------- */ exp_indices = hypre_TAlloc(HYPRE_Int, nrows_A , HYPRE_MEMORY_HOST); for (i = 0; i < nrows_A; i++) exp_indices[i] = -1; for (i = 0; i < nindices; i++) { if (exp_indices[indices[i]] == -1) exp_indices[indices[i]] = i; else { hypre_error_w_msg(HYPRE_ERROR_GENERIC,"ExtractSubmatrices: wrong index %d %d\n"); exit(1); } } k = 0; for (i = 0; i < nrows_A; i++) { if (exp_indices[i] < 0) { exp_indices[i] = - k - 1; k++; } } /* ----------------------------------------------------- * compute number of nonzeros for each block * ----------------------------------------------------- */ nnz11 = nnz12 = nnz21 = nnz22 = 0; for (i = 0; i < nrows_A; i++) { if (exp_indices[i] >= 0) { for (j = A_diag_i[i]; j < A_diag_i[i+1]; j++) { col = A_diag_j[j]; if (exp_indices[col] >= 0) nnz11++; else nnz12++; } } else { for (j = A_diag_i[i]; j < A_diag_i[i+1]; j++) { col = A_diag_j[j]; if (exp_indices[col] >= 0) nnz21++; else nnz22++; } } } /* ----------------------------------------------------- * create A11 matrix (assume sequential for the moment) * ----------------------------------------------------- */ ncols_offd = 0; nnz_offd = 0; nnz_diag = nnz11; /* This case is not yet implemented! */ global_nrows = 0; global_ncols = 0; row_starts = NULL; col_starts = NULL; A11_csr = hypre_ParCSRMatrixCreate(comm, global_nrows, global_ncols, row_starts, col_starts, ncols_offd, nnz_diag, nnz_offd); nrows = nindices; diag_i = hypre_CTAlloc(HYPRE_Int, nrows+1, HYPRE_MEMORY_HOST); diag_j = hypre_CTAlloc(HYPRE_Int, nnz_diag, HYPRE_MEMORY_HOST); diag_a = hypre_CTAlloc(HYPRE_Complex, nnz_diag, HYPRE_MEMORY_HOST); nnz = 0; row = 0; diag_i[0] = 0; for (i = 0; i < nrows_A; i++) { if (exp_indices[i] >= 0) { for (j = A_diag_i[i]; j < A_diag_i[i+1]; j++) { col = A_diag_j[j]; if (exp_indices[col] >= 0) { diag_j[nnz] = exp_indices[col]; diag_a[nnz++] = A_diag_a[j]; } } row++; diag_i[row] = nnz; } } diag = hypre_ParCSRMatrixDiag(A11_csr); hypre_CSRMatrixI(diag) = diag_i; hypre_CSRMatrixJ(diag) = diag_j; hypre_CSRMatrixData(diag) = diag_a; offd_i = hypre_CTAlloc(HYPRE_Int, nrows+1, HYPRE_MEMORY_HOST); for (i = 0; i <= nrows; i++) offd_i[i] = 0; offd = hypre_ParCSRMatrixOffd(A11_csr); hypre_CSRMatrixI(offd) = offd_i; hypre_CSRMatrixJ(offd) = NULL; hypre_CSRMatrixData(offd) = NULL; /* ----------------------------------------------------- * create A12 matrix (assume sequential for the moment) * ----------------------------------------------------- */ ncols_offd = 0; nnz_offd = 0; nnz_diag = nnz12; global_nrows = (HYPRE_BigInt)proc_offsets1[nprocs]; global_ncols = (HYPRE_BigInt)proc_offsets2[nprocs]; row_starts = hypre_CTAlloc(HYPRE_BigInt, nprocs+1, HYPRE_MEMORY_HOST); col_starts = hypre_CTAlloc(HYPRE_BigInt, nprocs+1, HYPRE_MEMORY_HOST); for (i = 0; i <= nprocs; i++) { row_starts[i] = (HYPRE_BigInt)proc_offsets1[i]; col_starts[i] = (HYPRE_BigInt)proc_offsets2[i]; } A12_csr = hypre_ParCSRMatrixCreate(comm, global_nrows, global_ncols, row_starts, col_starts, ncols_offd, nnz_diag, nnz_offd); nrows = nindices; diag_i = hypre_CTAlloc(HYPRE_Int, nrows+1, HYPRE_MEMORY_HOST); diag_j = hypre_CTAlloc(HYPRE_Int, nnz_diag, HYPRE_MEMORY_HOST); diag_a = hypre_CTAlloc(HYPRE_Complex, nnz_diag, HYPRE_MEMORY_HOST); nnz = 0; row = 0; diag_i[0] = 0; for (i = 0; i < nrows_A; i++) { if (exp_indices[i] >= 0) { for (j = A_diag_i[i]; j < A_diag_i[i+1]; j++) { col = A_diag_j[j]; if (exp_indices[col] < 0) { diag_j[nnz] = - exp_indices[col] - 1; diag_a[nnz++] = A_diag_a[j]; } } row++; diag_i[row] = nnz; } } if (nnz > nnz_diag) { hypre_assert(0); hypre_error(HYPRE_ERROR_GENERIC); } diag = hypre_ParCSRMatrixDiag(A12_csr); hypre_CSRMatrixI(diag) = diag_i; hypre_CSRMatrixJ(diag) = diag_j; hypre_CSRMatrixData(diag) = diag_a; offd_i = hypre_CTAlloc(HYPRE_Int, nrows+1, HYPRE_MEMORY_HOST); for (i = 0; i <= nrows; i++) offd_i[i] = 0; offd = hypre_ParCSRMatrixOffd(A12_csr); hypre_CSRMatrixI(offd) = offd_i; hypre_CSRMatrixJ(offd) = NULL; hypre_CSRMatrixData(offd) = NULL; /* ----------------------------------------------------- * create A21 matrix (assume sequential for the moment) * ----------------------------------------------------- */ ncols_offd = 0; nnz_offd = 0; nnz_diag = nnz21; global_nrows = (HYPRE_BigInt)proc_offsets2[nprocs]; global_ncols = (HYPRE_BigInt)proc_offsets1[nprocs]; row_starts = hypre_CTAlloc(HYPRE_BigInt, nprocs+1, HYPRE_MEMORY_HOST); col_starts = hypre_CTAlloc(HYPRE_BigInt, nprocs+1, HYPRE_MEMORY_HOST); for (i = 0; i <= nprocs; i++) { row_starts[i] = (HYPRE_BigInt)proc_offsets2[i]; col_starts[i] = (HYPRE_BigInt)proc_offsets1[i]; } A21_csr = hypre_ParCSRMatrixCreate(comm, global_nrows, global_ncols, row_starts, col_starts, ncols_offd, nnz_diag, nnz_offd); nrows = nrows_A - nindices; diag_i = hypre_CTAlloc(HYPRE_Int, nrows+1, HYPRE_MEMORY_HOST); diag_j = hypre_CTAlloc(HYPRE_Int, nnz_diag, HYPRE_MEMORY_HOST); diag_a = hypre_CTAlloc(HYPRE_Complex, nnz_diag, HYPRE_MEMORY_HOST); nnz = 0; row = 0; diag_i[0] = 0; for (i = 0; i < nrows_A; i++) { if (exp_indices[i] < 0) { for (j = A_diag_i[i]; j < A_diag_i[i+1]; j++) { col = A_diag_j[j]; if (exp_indices[col] >= 0) { diag_j[nnz] = exp_indices[col]; diag_a[nnz++] = A_diag_a[j]; } } row++; diag_i[row] = nnz; } } diag = hypre_ParCSRMatrixDiag(A21_csr); hypre_CSRMatrixI(diag) = diag_i; hypre_CSRMatrixJ(diag) = diag_j; hypre_CSRMatrixData(diag) = diag_a; offd_i = hypre_CTAlloc(HYPRE_Int, nrows+1, HYPRE_MEMORY_HOST); for (i = 0; i <= nrows; i++) offd_i[i] = 0; offd = hypre_ParCSRMatrixOffd(A21_csr); hypre_CSRMatrixI(offd) = offd_i; hypre_CSRMatrixJ(offd) = NULL; hypre_CSRMatrixData(offd) = NULL; /* ----------------------------------------------------- * create A22 matrix (assume sequential for the moment) * ----------------------------------------------------- */ ncols_offd = 0; nnz_offd = 0; nnz_diag = nnz22; global_nrows = (HYPRE_BigInt)proc_offsets2[nprocs]; global_ncols = (HYPRE_BigInt)proc_offsets2[nprocs]; row_starts = hypre_CTAlloc(HYPRE_BigInt, nprocs+1, HYPRE_MEMORY_HOST); col_starts = hypre_CTAlloc(HYPRE_BigInt, nprocs+1, HYPRE_MEMORY_HOST); for (i = 0; i <= nprocs; i++) { row_starts[i] = (HYPRE_BigInt)proc_offsets2[i]; col_starts[i] = (HYPRE_BigInt)proc_offsets2[i]; } A22_csr = hypre_ParCSRMatrixCreate(comm, global_nrows, global_ncols, row_starts, col_starts, ncols_offd, nnz_diag, nnz_offd); nrows = nrows_A - nindices; diag_i = hypre_CTAlloc(HYPRE_Int, nrows+1, HYPRE_MEMORY_HOST); diag_j = hypre_CTAlloc(HYPRE_Int, nnz_diag, HYPRE_MEMORY_HOST); diag_a = hypre_CTAlloc(HYPRE_Complex, nnz_diag, HYPRE_MEMORY_HOST); nnz = 0; row = 0; diag_i[0] = 0; for (i = 0; i < nrows_A; i++) { if (exp_indices[i] < 0) { for (j = A_diag_i[i]; j < A_diag_i[i+1]; j++) { col = A_diag_j[j]; if (exp_indices[col] < 0) { diag_j[nnz] = - exp_indices[col] - 1; diag_a[nnz++] = A_diag_a[j]; } } row++; diag_i[row] = nnz; } } diag = hypre_ParCSRMatrixDiag(A22_csr); hypre_CSRMatrixI(diag) = diag_i; hypre_CSRMatrixJ(diag) = diag_j; hypre_CSRMatrixData(diag) = diag_a; offd_i = hypre_CTAlloc(HYPRE_Int, nrows+1, HYPRE_MEMORY_HOST); for (i = 0; i <= nrows; i++) offd_i[i] = 0; offd = hypre_ParCSRMatrixOffd(A22_csr); hypre_CSRMatrixI(offd) = offd_i; hypre_CSRMatrixJ(offd) = NULL; hypre_CSRMatrixData(offd) = NULL; /* ----------------------------------------------------- * hand the matrices back to the caller and clean up * ----------------------------------------------------- */ (*submatrices)[0] = A11_csr; (*submatrices)[1] = A12_csr; (*submatrices)[2] = A21_csr; (*submatrices)[3] = A22_csr; hypre_TFree(proc_offsets1, HYPRE_MEMORY_HOST); hypre_TFree(proc_offsets2, HYPRE_MEMORY_HOST); hypre_TFree(exp_indices, HYPRE_MEMORY_HOST); } /* ----------------------------------------------------------------------------- * extract submatrices of a rectangular matrix * ----------------------------------------------------------------------------- */ void hypre_ParCSRMatrixExtractRowSubmatrices( hypre_ParCSRMatrix *A_csr, HYPRE_Int *indices2, hypre_ParCSRMatrix ***submatrices ) { HYPRE_Int nrows_A, nindices, *indices, *A_diag_i, *A_diag_j, mypid, nprocs; HYPRE_Int i, j, k, *proc_offsets1, *proc_offsets2, *exp_indices; HYPRE_Int nnz11, nnz21, col, ncols_offd, nnz_offd, nnz_diag; HYPRE_Int *A_offd_i, *A_offd_j; HYPRE_Int nrows, nnz; HYPRE_BigInt global_nrows, global_ncols, *row_starts, *col_starts, *itmp_array; HYPRE_Int *diag_i, *diag_j, row, *offd_i, *offd_j, nnz11_offd, nnz21_offd; HYPRE_Complex *A_diag_a, *diag_a, *offd_a; hypre_ParCSRMatrix *A11_csr, *A21_csr; hypre_CSRMatrix *A_diag, *diag, *A_offd, *offd; MPI_Comm comm; /* ----------------------------------------------------- * first make sure the incoming indices are in order * ----------------------------------------------------- */ nindices = indices2[0]; indices = &(indices2[1]); hypre_qsort0(indices, 0, nindices-1); /* ----------------------------------------------------- * fetch matrix information * ----------------------------------------------------- */ nrows_A = (HYPRE_Int)hypre_ParCSRMatrixGlobalNumRows(A_csr); A_diag = hypre_ParCSRMatrixDiag(A_csr); A_diag_i = hypre_CSRMatrixI(A_diag); A_diag_j = hypre_CSRMatrixJ(A_diag); A_diag_a = hypre_CSRMatrixData(A_diag); A_offd = hypre_ParCSRMatrixOffd(A_csr); A_offd_i = hypre_CSRMatrixI(A_offd); A_offd_j = hypre_CSRMatrixJ(A_offd); comm = hypre_ParCSRMatrixComm(A_csr); hypre_MPI_Comm_rank(comm, &mypid); hypre_MPI_Comm_size(comm, &nprocs); /* ----------------------------------------------------- * compute new matrix dimensions * ----------------------------------------------------- */ proc_offsets1 = hypre_TAlloc(HYPRE_Int, (nprocs+1) , HYPRE_MEMORY_HOST); proc_offsets2 = hypre_TAlloc(HYPRE_Int, (nprocs+1) , HYPRE_MEMORY_HOST); hypre_MPI_Allgather(&nindices, 1, HYPRE_MPI_INT, proc_offsets1, 1, HYPRE_MPI_INT, comm); k = 0; for (i = 0; i < nprocs; i++) { j = proc_offsets1[i]; proc_offsets1[i] = k; k += j; } proc_offsets1[nprocs] = k; itmp_array = hypre_ParCSRMatrixRowStarts(A_csr); for (i = 0; i <= nprocs; i++) proc_offsets2[i] = (HYPRE_Int)(itmp_array[i] - proc_offsets1[i]); /* ----------------------------------------------------- * assign id's to row and col for later processing * ----------------------------------------------------- */ exp_indices = hypre_TAlloc(HYPRE_Int, nrows_A , HYPRE_MEMORY_HOST); for (i = 0; i < nrows_A; i++) exp_indices[i] = -1; for (i = 0; i < nindices; i++) { if (exp_indices[indices[i]] == -1) exp_indices[indices[i]] = i; else { hypre_error_w_msg(HYPRE_ERROR_GENERIC,"ExtractRowSubmatrices: wrong index %d %d\n"); exit(1); } } k = 0; for (i = 0; i < nrows_A; i++) { if (exp_indices[i] < 0) { exp_indices[i] = - k - 1; k++; } } /* ----------------------------------------------------- * compute number of nonzeros for each block * ----------------------------------------------------- */ nnz11 = nnz21 = nnz11_offd = nnz21_offd = 0; for (i = 0; i < nrows_A; i++) { if (exp_indices[i] >= 0) { for (j = A_diag_i[i]; j < A_diag_i[i+1]; j++) { col = A_diag_j[j]; if (exp_indices[col] >= 0) nnz11++; } nnz11_offd += A_offd_i[i+1] - A_offd_i[i]; } else { for (j = A_diag_i[i]; j < A_diag_i[i+1]; j++) { col = A_diag_j[j]; if (exp_indices[col] < 0) nnz21++; } nnz21_offd += A_offd_i[i+1] - A_offd_i[i]; } } /* ----------------------------------------------------- * create A11 matrix (assume sequential for the moment) * ----------------------------------------------------- */ ncols_offd = hypre_CSRMatrixNumCols(hypre_ParCSRMatrixDiag(A_csr)); nnz_diag = nnz11; nnz_offd = nnz11_offd; global_nrows = (HYPRE_BigInt)proc_offsets1[nprocs]; itmp_array = hypre_ParCSRMatrixColStarts(A_csr); global_ncols = itmp_array[nprocs]; row_starts = hypre_CTAlloc(HYPRE_BigInt, nprocs+1, HYPRE_MEMORY_HOST); col_starts = hypre_CTAlloc(HYPRE_BigInt, nprocs+1, HYPRE_MEMORY_HOST); for (i = 0; i <= nprocs; i++) { row_starts[i] = (HYPRE_BigInt)proc_offsets1[i]; col_starts[i] = itmp_array[i]; } A11_csr = hypre_ParCSRMatrixCreate(comm, global_nrows, global_ncols, row_starts, col_starts, ncols_offd, nnz_diag, nnz_offd); nrows = nindices; diag_i = hypre_CTAlloc(HYPRE_Int, nrows+1, HYPRE_MEMORY_HOST); diag_j = hypre_CTAlloc(HYPRE_Int, nnz_diag, HYPRE_MEMORY_HOST); diag_a = hypre_CTAlloc(HYPRE_Complex, nnz_diag, HYPRE_MEMORY_HOST); nnz = 0; row = 0; diag_i[0] = 0; for (i = 0; i < nrows_A; i++) { if (exp_indices[i] >= 0) { for (j = A_diag_i[i]; j < A_diag_i[i+1]; j++) { col = A_diag_j[j]; if (exp_indices[col] >= 0) { diag_j[nnz] = exp_indices[col]; diag_a[nnz++] = A_diag_a[j]; } } row++; diag_i[row] = nnz; } } diag = hypre_ParCSRMatrixDiag(A11_csr); hypre_CSRMatrixI(diag) = diag_i; hypre_CSRMatrixJ(diag) = diag_j; hypre_CSRMatrixData(diag) = diag_a; offd_i = hypre_CTAlloc(HYPRE_Int, nrows+1, HYPRE_MEMORY_HOST); offd_j = hypre_CTAlloc(HYPRE_Int, nnz_offd, HYPRE_MEMORY_HOST); offd_a = hypre_CTAlloc(HYPRE_Complex, nnz_offd, HYPRE_MEMORY_HOST); nnz = 0; row = 0; offd_i[0] = 0; for (i = 0; i < nrows_A; i++) { if (exp_indices[i] >= 0) { for (j = A_offd_i[i]; j < A_offd_i[i+1]; j++) { offd_j[nnz] = A_offd_j[j]; offd_a[nnz++] = A_diag_a[j]; } row++; offd_i[row] = nnz; } } offd = hypre_ParCSRMatrixOffd(A11_csr); hypre_CSRMatrixI(offd) = offd_i; hypre_CSRMatrixJ(offd) = offd_j; hypre_CSRMatrixData(offd) = offd_a; /* ----------------------------------------------------- * create A21 matrix * ----------------------------------------------------- */ ncols_offd = hypre_CSRMatrixNumCols(hypre_ParCSRMatrixDiag(A_csr)); nnz_offd = nnz21_offd; nnz_diag = nnz21; global_nrows = (HYPRE_BigInt)proc_offsets2[nprocs]; itmp_array = hypre_ParCSRMatrixColStarts(A_csr); global_ncols = itmp_array[nprocs]; row_starts = hypre_CTAlloc(HYPRE_BigInt, nprocs+1, HYPRE_MEMORY_HOST); col_starts = hypre_CTAlloc(HYPRE_BigInt, nprocs+1, HYPRE_MEMORY_HOST); for (i = 0; i <= nprocs; i++) { row_starts[i] = (HYPRE_BigInt)proc_offsets2[i]; col_starts[i] = itmp_array[i]; } A21_csr = hypre_ParCSRMatrixCreate(comm, global_nrows, global_ncols, row_starts, col_starts, ncols_offd, nnz_diag, nnz_offd); nrows = nrows_A - nindices; diag_i = hypre_CTAlloc(HYPRE_Int, nrows+1, HYPRE_MEMORY_HOST); diag_j = hypre_CTAlloc(HYPRE_Int, nnz_diag, HYPRE_MEMORY_HOST); diag_a = hypre_CTAlloc(HYPRE_Complex, nnz_diag, HYPRE_MEMORY_HOST); nnz = 0; row = 0; diag_i[0] = 0; for (i = 0; i < nrows_A; i++) { if (exp_indices[i] < 0) { for (j = A_diag_i[i]; j < A_diag_i[i+1]; j++) { diag_j[nnz] = A_diag_j[j]; diag_a[nnz++] = A_diag_a[j]; } row++; diag_i[row] = nnz; } } diag = hypre_ParCSRMatrixDiag(A21_csr); hypre_CSRMatrixI(diag) = diag_i; hypre_CSRMatrixJ(diag) = diag_j; hypre_CSRMatrixData(diag) = diag_a; offd_i = hypre_CTAlloc(HYPRE_Int, nrows+1, HYPRE_MEMORY_HOST); offd_j = hypre_CTAlloc(HYPRE_Int, nnz_offd, HYPRE_MEMORY_HOST); offd_a = hypre_CTAlloc(HYPRE_Complex, nnz_offd, HYPRE_MEMORY_HOST); nnz = 0; row = 0; offd_i[0] = 0; for (i = 0; i < nrows_A; i++) { if (exp_indices[i] < 0) { for (j = A_offd_i[i]; j < A_offd_i[i+1]; j++) { offd_j[nnz] = A_offd_j[j]; offd_a[nnz++] = A_diag_a[j]; } row++; offd_i[row] = nnz; } } offd = hypre_ParCSRMatrixOffd(A21_csr); hypre_CSRMatrixI(offd) = offd_i; hypre_CSRMatrixJ(offd) = offd_j; hypre_CSRMatrixData(offd) = offd_a; /* ----------------------------------------------------- * hand the matrices back to the caller and clean up * ----------------------------------------------------- */ (*submatrices)[0] = A11_csr; (*submatrices)[1] = A21_csr; hypre_TFree(proc_offsets1, HYPRE_MEMORY_HOST); hypre_TFree(proc_offsets2, HYPRE_MEMORY_HOST); hypre_TFree(exp_indices, HYPRE_MEMORY_HOST); } /* ----------------------------------------------------------------------------- * return the sum of all local elements of the matrix * ----------------------------------------------------------------------------- */ HYPRE_Complex hypre_ParCSRMatrixLocalSumElts( hypre_ParCSRMatrix * A ) { hypre_CSRMatrix * A_diag = hypre_ParCSRMatrixDiag( A ); hypre_CSRMatrix * A_offd = hypre_ParCSRMatrixOffd( A ); return hypre_CSRMatrixSumElts(A_diag) + hypre_CSRMatrixSumElts(A_offd); } /*-------------------------------------------------------------------------- * hypre_ParCSRMatrixMatAminvDB * computes C = (A - inv(D)B) where D is a diagonal matrix * Note: Data structure of A is expected to be a subset of data structure of B! *--------------------------------------------------------------------------*/ HYPRE_Int hypre_ParCSRMatrixAminvDB( hypre_ParCSRMatrix *A, hypre_ParCSRMatrix *B, HYPRE_Complex *d, hypre_ParCSRMatrix **C_ptr) { MPI_Comm comm = hypre_ParCSRMatrixComm(B); hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A); hypre_ParCSRMatrix *C = NULL; HYPRE_Int num_cols_offd_A = hypre_CSRMatrixNumCols(A_offd); hypre_ParCSRCommPkg *comm_pkg_B = hypre_ParCSRMatrixCommPkg(B); hypre_CSRMatrix *B_diag = hypre_ParCSRMatrixDiag(B); hypre_CSRMatrix *B_offd = hypre_ParCSRMatrixOffd(B); HYPRE_Int num_cols_offd_B = hypre_CSRMatrixNumCols(B_offd); HYPRE_Int num_sends_B, num_recvs_B; HYPRE_Int i, j, cnt; HYPRE_Int *A_diag_i = hypre_CSRMatrixI(A_diag); HYPRE_Int *A_diag_j = hypre_CSRMatrixJ(A_diag); HYPRE_Complex *A_diag_data = hypre_CSRMatrixData(A_diag); HYPRE_Int *A_offd_i = hypre_CSRMatrixI(A_offd); HYPRE_Int *A_offd_j = hypre_CSRMatrixJ(A_offd); HYPRE_Complex *A_offd_data = hypre_CSRMatrixData(A_offd); HYPRE_BigInt *col_map_offd_A = hypre_ParCSRMatrixColMapOffd(A); HYPRE_Int num_rows = hypre_CSRMatrixNumRows(B_diag); HYPRE_Int *B_diag_i = hypre_CSRMatrixI(B_diag); HYPRE_Int *B_diag_j = hypre_CSRMatrixJ(B_diag); HYPRE_Complex *B_diag_data = hypre_CSRMatrixData(B_diag); HYPRE_Int *B_offd_i = hypre_CSRMatrixI(B_offd); HYPRE_Int *B_offd_j = hypre_CSRMatrixJ(B_offd); HYPRE_Complex *B_offd_data = hypre_CSRMatrixData(B_offd); HYPRE_BigInt *col_map_offd_B = hypre_ParCSRMatrixColMapOffd(B); hypre_CSRMatrix *C_diag = NULL; hypre_CSRMatrix *C_offd = NULL; HYPRE_Int *C_diag_i = NULL; HYPRE_Int *C_diag_j = NULL; HYPRE_Complex *C_diag_data = NULL; HYPRE_Int *C_offd_i = NULL; HYPRE_Int *C_offd_j = NULL; HYPRE_Complex *C_offd_data = NULL; HYPRE_Int num_procs, my_id; HYPRE_Int *recv_procs_B; HYPRE_Int *send_procs_B; HYPRE_Int *recv_vec_starts_B; HYPRE_Int *send_map_starts_B; HYPRE_Int *send_map_elmts_B; hypre_ParCSRCommPkg *comm_pkg_C; HYPRE_Int *recv_procs_C; HYPRE_Int *send_procs_C; HYPRE_Int *recv_vec_starts_C; HYPRE_Int *send_map_starts_C; HYPRE_Int *send_map_elmts_C; HYPRE_Int *map_to_B; /*HYPRE_Int *C_diag_array; HYPRE_Int *C_offd_array;*/ HYPRE_Complex *D_tmp; HYPRE_Int size, rest, num_threads, ii; hypre_MPI_Comm_size(comm,&num_procs); hypre_MPI_Comm_rank(comm,&my_id); num_threads = hypre_NumThreads(); /*C_diag_array = hypre_CTAlloc(HYPRE_Int, num_threads); C_offd_array = hypre_CTAlloc(HYPRE_Int, num_threads, HYPRE_MEMORY_HOST);*/ /*--------------------------------------------------------------------- * If there exists no CommPkg for B, a CommPkg is generated *--------------------------------------------------------------------*/ if (!comm_pkg_B) { hypre_MatvecCommPkgCreate(B); comm_pkg_B = hypre_ParCSRMatrixCommPkg(B); } C = hypre_ParCSRMatrixClone(B, 0); /*hypre_ParCSRMatrixInitialize(C);*/ C_diag = hypre_ParCSRMatrixDiag(C); C_diag_i = hypre_CSRMatrixI(C_diag); C_diag_j = hypre_CSRMatrixJ(C_diag); C_diag_data = hypre_CSRMatrixData(C_diag); C_offd = hypre_ParCSRMatrixOffd(C); C_offd_i = hypre_CSRMatrixI(C_offd); C_offd_j = hypre_CSRMatrixJ(C_offd); C_offd_data = hypre_CSRMatrixData(C_offd); size = num_rows/num_threads; rest = num_rows - size*num_threads; D_tmp = hypre_CTAlloc(HYPRE_Complex, num_rows, HYPRE_MEMORY_HOST); if (num_cols_offd_A) { map_to_B = hypre_CTAlloc(HYPRE_Int, num_cols_offd_A, HYPRE_MEMORY_HOST); cnt = 0; for (i=0; i < num_cols_offd_A; i++) { while (col_map_offd_B[cnt] < col_map_offd_A[i]) { cnt++; } map_to_B[i] = cnt; cnt++; } } #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(ii, i, j) #endif for (ii=0; ii < num_threads; ii++) { HYPRE_Int *A_marker = NULL; HYPRE_Int ns, ne, A_col, num_cols, nmax; if (ii < rest) { ns = ii*size+ii; ne = (ii+1)*size+ii+1; } else { ns = ii*size+rest; ne = (ii+1)*size+rest; } nmax = hypre_max(num_rows, num_cols_offd_B); A_marker = hypre_CTAlloc(HYPRE_Int, nmax, HYPRE_MEMORY_HOST); for (i=0; i < num_rows; i++) { A_marker[i] = -1; } for (i = ns; i < ne; i++) { D_tmp[i] = 1.0/d[i]; } num_cols = C_diag_i[ns]; for (i = ns; i < ne; i++) { for (j = A_diag_i[i]; j < A_diag_i[i+1]; j++) { A_col = A_diag_j[j]; if (A_marker[A_col] < C_diag_i[i]) { A_marker[A_col] = num_cols; C_diag_j[num_cols] = A_col; C_diag_data[num_cols] = A_diag_data[j]; num_cols++; } else { C_diag_data[A_marker[A_col]] += A_diag_data[j]; } } for (j = B_diag_i[i]; j < B_diag_i[i+1]; j++) { A_col = B_diag_j[j]; if (A_marker[A_col] < C_diag_i[i]) { A_marker[A_col] = num_cols; C_diag_j[num_cols] = A_col; C_diag_data[num_cols] = -D_tmp[i]*B_diag_data[j]; num_cols++; } else { C_diag_data[A_marker[A_col]] -= D_tmp[i]*B_diag_data[j]; } } } for (i = 0; i < num_cols_offd_B; i++) { A_marker[i] = -1; } num_cols = C_offd_i[ns]; for (i = ns; i < ne; i++) { for (j = A_offd_i[i]; j < A_offd_i[i+1]; j++) { A_col = map_to_B[A_offd_j[j]]; if (A_marker[A_col] < B_offd_i[i]) { A_marker[A_col] = num_cols; C_offd_j[num_cols] = A_col; C_offd_data[num_cols] = A_offd_data[j]; num_cols++; } else { C_offd_data[A_marker[A_col]] += A_offd_data[j]; } } for (j = B_offd_i[i]; j < B_offd_i[i+1]; j++) { A_col = B_offd_j[j]; if (A_marker[A_col] < B_offd_i[i]) { A_marker[A_col] = num_cols; C_offd_j[num_cols] = A_col; C_offd_data[num_cols] = -D_tmp[i]*B_offd_data[j]; num_cols++; } else { C_offd_data[A_marker[A_col]] -= D_tmp[i]*B_offd_data[j]; } } } hypre_TFree(A_marker, HYPRE_MEMORY_HOST); } /* end parallel region */ /*for (i=0; i < num_cols_offd_B; i++) col_map_offd_C[i] = col_map_offd_B[i]; */ num_sends_B = hypre_ParCSRCommPkgNumSends(comm_pkg_B); num_recvs_B = hypre_ParCSRCommPkgNumRecvs(comm_pkg_B); recv_procs_B = hypre_ParCSRCommPkgRecvProcs(comm_pkg_B); recv_vec_starts_B = hypre_ParCSRCommPkgRecvVecStarts(comm_pkg_B); send_procs_B = hypre_ParCSRCommPkgSendProcs(comm_pkg_B); send_map_starts_B = hypre_ParCSRCommPkgSendMapStarts(comm_pkg_B); send_map_elmts_B = hypre_ParCSRCommPkgSendMapElmts(comm_pkg_B); recv_procs_C = hypre_CTAlloc(HYPRE_Int, num_recvs_B, HYPRE_MEMORY_HOST); recv_vec_starts_C = hypre_CTAlloc(HYPRE_Int, num_recvs_B+1, HYPRE_MEMORY_HOST); send_procs_C = hypre_CTAlloc(HYPRE_Int, num_sends_B, HYPRE_MEMORY_HOST); send_map_starts_C = hypre_CTAlloc(HYPRE_Int, num_sends_B+1, HYPRE_MEMORY_HOST); send_map_elmts_C = hypre_CTAlloc(HYPRE_Int, send_map_starts_B[num_sends_B], HYPRE_MEMORY_HOST); for (i=0; i < num_recvs_B; i++) recv_procs_C[i] = recv_procs_B[i]; for (i=0; i < num_recvs_B+1; i++) recv_vec_starts_C[i] = recv_vec_starts_B[i]; for (i=0; i < num_sends_B; i++) send_procs_C[i] = send_procs_B[i]; for (i=0; i < num_sends_B+1; i++) send_map_starts_C[i] = send_map_starts_B[i]; for (i=0; i < send_map_starts_B[num_sends_B]; i++) send_map_elmts_C[i] = send_map_elmts_B[i]; comm_pkg_C = hypre_CTAlloc(hypre_ParCSRCommPkg, 1, HYPRE_MEMORY_HOST); hypre_ParCSRCommPkgComm(comm_pkg_C) = comm; hypre_ParCSRCommPkgNumRecvs(comm_pkg_C) = num_recvs_B; hypre_ParCSRCommPkgRecvProcs(comm_pkg_C) = recv_procs_C; hypre_ParCSRCommPkgRecvVecStarts(comm_pkg_C) = recv_vec_starts_C; hypre_ParCSRCommPkgNumSends(comm_pkg_C) = num_sends_B; hypre_ParCSRCommPkgSendProcs(comm_pkg_C) = send_procs_C; hypre_ParCSRCommPkgSendMapStarts(comm_pkg_C) = send_map_starts_C; hypre_ParCSRCommPkgSendMapElmts(comm_pkg_C) = send_map_elmts_C; hypre_ParCSRMatrixCommPkg(C) = comm_pkg_C; hypre_TFree(D_tmp, HYPRE_MEMORY_HOST); if (num_cols_offd_A) hypre_TFree(map_to_B, HYPRE_MEMORY_HOST); *C_ptr = C; return (hypre_error_flag); } /*-------------------------------------------------------------------------- * hypre_ParTMatmul: * * Multiplies two ParCSRMatrices transpose(A) and B and returns * the product in ParCSRMatrix C * * Note that C does not own the partitionings since its row_starts * is owned by A and col_starts by B. *--------------------------------------------------------------------------*/ hypre_ParCSRMatrix* hypre_ParTMatmul( hypre_ParCSRMatrix *A, hypre_ParCSRMatrix *B) { MPI_Comm comm = hypre_ParCSRMatrixComm(A); hypre_ParCSRCommPkg *comm_pkg_A = hypre_ParCSRMatrixCommPkg(A); hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); hypre_CSRMatrix *AT_diag = NULL; hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A); hypre_CSRMatrix *AT_offd = NULL; HYPRE_Int num_rows_diag_A = hypre_CSRMatrixNumRows(A_diag); HYPRE_Int num_cols_diag_A = hypre_CSRMatrixNumCols(A_diag); hypre_CSRMatrix *B_diag = hypre_ParCSRMatrixDiag(B); hypre_CSRMatrix *B_offd = hypre_ParCSRMatrixOffd(B); HYPRE_BigInt *col_map_offd_B = hypre_ParCSRMatrixColMapOffd(B); HYPRE_BigInt first_col_diag_B = hypre_ParCSRMatrixFirstColDiag(B); HYPRE_BigInt *col_starts_A = hypre_ParCSRMatrixColStarts(A); HYPRE_BigInt *col_starts_B = hypre_ParCSRMatrixColStarts(B); HYPRE_Int num_rows_diag_B = hypre_CSRMatrixNumRows(B_diag); HYPRE_Int num_cols_diag_B = hypre_CSRMatrixNumCols(B_diag); HYPRE_Int num_cols_offd_B = hypre_CSRMatrixNumCols(B_offd); hypre_ParCSRMatrix *C; HYPRE_BigInt *col_map_offd_C = NULL; HYPRE_Int *map_B_to_C; hypre_CSRMatrix *C_diag = NULL; hypre_CSRMatrix *C_tmp_diag = NULL; HYPRE_Complex *C_diag_data = NULL; HYPRE_Int *C_diag_i = NULL; HYPRE_Int *C_diag_j = NULL; HYPRE_BigInt first_col_diag_C; HYPRE_BigInt last_col_diag_C; hypre_CSRMatrix *C_offd = NULL; hypre_CSRMatrix *C_tmp_offd = NULL; hypre_CSRMatrix *C_int = NULL; hypre_CSRMatrix *C_ext = NULL; HYPRE_Int *C_ext_i; HYPRE_BigInt *C_ext_j; HYPRE_Complex *C_ext_data; HYPRE_Int *C_ext_diag_i; HYPRE_Int *C_ext_diag_j; HYPRE_Complex *C_ext_diag_data; HYPRE_Int *C_ext_offd_i; HYPRE_Int *C_ext_offd_j; HYPRE_Complex *C_ext_offd_data; HYPRE_Int C_ext_size = 0; HYPRE_Int C_ext_diag_size = 0; HYPRE_Int C_ext_offd_size = 0; HYPRE_Int *C_tmp_diag_i; HYPRE_Int *C_tmp_diag_j; HYPRE_Complex *C_tmp_diag_data; HYPRE_Int *C_tmp_offd_i; HYPRE_Int *C_tmp_offd_j; HYPRE_Complex *C_tmp_offd_data; HYPRE_Complex *C_offd_data=NULL; HYPRE_Int *C_offd_i=NULL; HYPRE_Int *C_offd_j=NULL; HYPRE_BigInt *temp; HYPRE_Int *send_map_starts_A; HYPRE_Int *send_map_elmts_A; HYPRE_Int num_sends_A; HYPRE_Int num_cols_offd_C = 0; HYPRE_Int *P_marker; HYPRE_Int i, j; HYPRE_Int i1, j_indx; HYPRE_BigInt nrows_A, ncols_A; HYPRE_BigInt nrows_B, ncols_B; /*HYPRE_Int allsquare = 0;*/ HYPRE_Int cnt, cnt_offd, cnt_diag; HYPRE_BigInt value; HYPRE_Int num_procs, my_id; HYPRE_Int max_num_threads; HYPRE_Int *C_diag_array = NULL; HYPRE_Int *C_offd_array = NULL; HYPRE_BigInt first_row_index, first_col_diag; HYPRE_Int local_num_rows, local_num_cols; nrows_A = hypre_ParCSRMatrixGlobalNumRows(A); ncols_A = hypre_ParCSRMatrixGlobalNumCols(A); nrows_B = hypre_ParCSRMatrixGlobalNumRows(B); ncols_B = hypre_ParCSRMatrixGlobalNumCols(B); hypre_MPI_Comm_size(comm,&num_procs); hypre_MPI_Comm_rank(comm, &my_id); max_num_threads = hypre_NumThreads(); if (nrows_A != nrows_B || num_rows_diag_A != num_rows_diag_B) { hypre_error_w_msg(HYPRE_ERROR_GENERIC," Error! Incompatible matrix dimensions!\n"); return NULL; } HYPRE_MemoryLocation memory_location_A = hypre_ParCSRMatrixMemoryLocation(A); HYPRE_MemoryLocation memory_location_B = hypre_ParCSRMatrixMemoryLocation(B); /* RL: TODO cannot guarantee, maybe should never assert hypre_assert(memory_location_A == memory_location_B); */ /* RL: in the case of A=H, B=D, or A=D, B=H, let C = D, * not sure if this is the right thing to do. * Also, need something like this in other places * TODO */ HYPRE_MemoryLocation memory_location_C = hypre_max(memory_location_A, memory_location_B); /*if (num_cols_diag_A == num_cols_diag_B) allsquare = 1;*/ hypre_CSRMatrixTranspose(A_diag, &AT_diag, 1); hypre_CSRMatrixTranspose(A_offd, &AT_offd, 1); C_tmp_diag = hypre_CSRMatrixMultiply(AT_diag, B_diag); C_ext_size = 0; if (num_procs > 1) { hypre_CSRMatrix *C_int_diag; hypre_CSRMatrix *C_int_offd; void *request; C_tmp_offd = hypre_CSRMatrixMultiply(AT_diag, B_offd); C_int_diag = hypre_CSRMatrixMultiply(AT_offd, B_diag); C_int_offd = hypre_CSRMatrixMultiply(AT_offd, B_offd); hypre_ParCSRMatrixDiag(B) = C_int_diag; hypre_ParCSRMatrixOffd(B) = C_int_offd; C_int = hypre_MergeDiagAndOffd(B); hypre_ParCSRMatrixDiag(B) = B_diag; hypre_ParCSRMatrixOffd(B) = B_offd; hypre_ExchangeExternalRowsInit(C_int, comm_pkg_A, &request); C_ext = hypre_ExchangeExternalRowsWait(request); C_ext_i = hypre_CSRMatrixI(C_ext); C_ext_j = hypre_CSRMatrixBigJ(C_ext); C_ext_data = hypre_CSRMatrixData(C_ext); C_ext_size = C_ext_i[hypre_CSRMatrixNumRows(C_ext)]; hypre_CSRMatrixDestroy(C_int); hypre_CSRMatrixDestroy(C_int_diag); hypre_CSRMatrixDestroy(C_int_offd); } else { C_tmp_offd = hypre_CSRMatrixCreate(num_cols_diag_A, 0, 0); hypre_CSRMatrixInitialize(C_tmp_offd); hypre_CSRMatrixNumRownnz(C_tmp_offd) = 0; } hypre_CSRMatrixDestroy(AT_diag); hypre_CSRMatrixDestroy(AT_offd); /*----------------------------------------------------------------------- * Add contents of C_ext to C_tmp_diag and C_tmp_offd * to obtain C_diag and C_offd *-----------------------------------------------------------------------*/ /* check for new nonzero columns in C_offd generated through C_ext */ first_col_diag_C = first_col_diag_B; last_col_diag_C = first_col_diag_B + (HYPRE_BigInt)num_cols_diag_B - 1; C_tmp_diag_i = hypre_CSRMatrixI(C_tmp_diag); if (C_ext_size || num_cols_offd_B) { HYPRE_Int C_ext_num_rows; num_sends_A = hypre_ParCSRCommPkgNumSends(comm_pkg_A); send_map_starts_A = hypre_ParCSRCommPkgSendMapStarts(comm_pkg_A); send_map_elmts_A = hypre_ParCSRCommPkgSendMapElmts(comm_pkg_A); C_ext_num_rows = send_map_starts_A[num_sends_A]; C_ext_diag_i = hypre_CTAlloc(HYPRE_Int, C_ext_num_rows+1, HYPRE_MEMORY_HOST); C_ext_offd_i = hypre_CTAlloc(HYPRE_Int, C_ext_num_rows+1, HYPRE_MEMORY_HOST); temp = hypre_CTAlloc(HYPRE_BigInt, C_ext_size+num_cols_offd_B, HYPRE_MEMORY_HOST); C_ext_diag_size = 0; C_ext_offd_size = 0; for (i = 0; i < C_ext_num_rows; i++) { for (j = C_ext_i[i]; j < C_ext_i[i+1]; j++) { if (C_ext_j[j] < first_col_diag_C || C_ext_j[j] > last_col_diag_C) { temp[C_ext_offd_size++] = C_ext_j[j]; } else { C_ext_diag_size++; } } C_ext_diag_i[i+1] = C_ext_diag_size; C_ext_offd_i[i+1] = C_ext_offd_size; } cnt = C_ext_offd_size; for (i = 0; i < num_cols_offd_B; i++) { temp[cnt++] = col_map_offd_B[i]; } if (cnt) { hypre_BigQsort0(temp,0,cnt-1); value = temp[0]; num_cols_offd_C = 1; for (i = 1; i < cnt; i++) { if (temp[i] > value) { value = temp[i]; temp[num_cols_offd_C++] = value; } } } if (num_cols_offd_C) { col_map_offd_C = hypre_CTAlloc(HYPRE_BigInt, num_cols_offd_C, HYPRE_MEMORY_HOST); } for (i = 0; i < num_cols_offd_C; i++) { col_map_offd_C[i] = temp[i]; } hypre_TFree(temp, HYPRE_MEMORY_HOST); if (C_ext_diag_size) { C_ext_diag_j = hypre_CTAlloc(HYPRE_Int, C_ext_diag_size, HYPRE_MEMORY_HOST); C_ext_diag_data = hypre_CTAlloc(HYPRE_Complex, C_ext_diag_size, HYPRE_MEMORY_HOST); } if (C_ext_offd_size) { C_ext_offd_j = hypre_CTAlloc(HYPRE_Int, C_ext_offd_size, HYPRE_MEMORY_HOST); C_ext_offd_data = hypre_CTAlloc(HYPRE_Complex, C_ext_offd_size, HYPRE_MEMORY_HOST); } C_tmp_diag_j = hypre_CSRMatrixJ(C_tmp_diag); C_tmp_diag_data = hypre_CSRMatrixData(C_tmp_diag); C_tmp_offd_i = hypre_CSRMatrixI(C_tmp_offd); C_tmp_offd_j = hypre_CSRMatrixJ(C_tmp_offd); C_tmp_offd_data = hypre_CSRMatrixData(C_tmp_offd); cnt_offd = 0; cnt_diag = 0; for (i = 0; i < C_ext_num_rows; i++) { for (j = C_ext_i[i]; j < C_ext_i[i+1]; j++) { if (C_ext_j[j] < first_col_diag_C || C_ext_j[j] > last_col_diag_C) { C_ext_offd_j[cnt_offd] = hypre_BigBinarySearch(col_map_offd_C, C_ext_j[j], num_cols_offd_C); C_ext_offd_data[cnt_offd++] = C_ext_data[j]; } else { C_ext_diag_j[cnt_diag] = (HYPRE_Int)(C_ext_j[j] - first_col_diag_C); C_ext_diag_data[cnt_diag++] = C_ext_data[j]; } } } } if (C_ext) { hypre_CSRMatrixDestroy(C_ext); C_ext = NULL; } if (num_cols_offd_B) { map_B_to_C = hypre_CTAlloc(HYPRE_Int, num_cols_offd_B, HYPRE_MEMORY_HOST); cnt = 0; for (i = 0; i < num_cols_offd_C; i++) { if (col_map_offd_C[i] == col_map_offd_B[cnt]) { map_B_to_C[cnt++] = i; if (cnt == num_cols_offd_B) break; } } for (i = 0; i < hypre_CSRMatrixI(C_tmp_offd)[hypre_CSRMatrixNumRows(C_tmp_offd)]; i++) { j_indx = C_tmp_offd_j[i]; C_tmp_offd_j[i] = map_B_to_C[j_indx]; } } /*----------------------------------------------------------------------- * Need to compute: * C_diag = C_tmp_diag + C_ext_diag * C_offd = C_tmp_offd + C_ext_offd * * First generate structure *-----------------------------------------------------------------------*/ if (C_ext_size || num_cols_offd_B) { C_diag_i = hypre_CTAlloc(HYPRE_Int, num_cols_diag_A+1, memory_location_C); C_offd_i = hypre_CTAlloc(HYPRE_Int, num_cols_diag_A+1, memory_location_C); C_diag_array = hypre_CTAlloc(HYPRE_Int, max_num_threads, HYPRE_MEMORY_HOST); C_offd_array = hypre_CTAlloc(HYPRE_Int, max_num_threads, HYPRE_MEMORY_HOST); #ifdef HYPRE_USING_OPENMP #pragma omp parallel #endif { HYPRE_Int *B_marker = NULL; HYPRE_Int *B_marker_offd = NULL; HYPRE_Int ik, jk, j1, j2, jcol; HYPRE_Int ns, ne, ii, nnz_d, nnz_o; HYPRE_Int rest, size; HYPRE_Int num_threads = hypre_NumActiveThreads(); size = num_cols_diag_A/num_threads; rest = num_cols_diag_A - size*num_threads; ii = hypre_GetThreadNum(); if (ii < rest) { ns = ii*size+ii; ne = (ii+1)*size+ii+1; } else { ns = ii*size+rest; ne = (ii+1)*size+rest; } B_marker = hypre_CTAlloc(HYPRE_Int, num_cols_diag_B, HYPRE_MEMORY_HOST); B_marker_offd = hypre_CTAlloc(HYPRE_Int, num_cols_offd_C, HYPRE_MEMORY_HOST); for (ik = 0; ik < num_cols_diag_B; ik++) { B_marker[ik] = -1; } for (ik = 0; ik < num_cols_offd_C; ik++) { B_marker_offd[ik] = -1; } nnz_d = 0; nnz_o = 0; for (ik = ns; ik < ne; ik++) { for (jk = C_tmp_diag_i[ik]; jk < C_tmp_diag_i[ik+1]; jk++) { jcol = C_tmp_diag_j[jk]; B_marker[jcol] = ik; nnz_d++; } for (jk = C_tmp_offd_i[ik]; jk < C_tmp_offd_i[ik+1]; jk++) { jcol = C_tmp_offd_j[jk]; B_marker_offd[jcol] = ik; nnz_o++; } for (jk = 0; jk < num_sends_A; jk++) { for (j1 = send_map_starts_A[jk]; j1 < send_map_starts_A[jk+1]; j1++) { if (send_map_elmts_A[j1] == ik) { for (j2 = C_ext_diag_i[j1]; j2 < C_ext_diag_i[j1+1]; j2++) { jcol = C_ext_diag_j[j2]; if (B_marker[jcol] < ik) { B_marker[jcol] = ik; nnz_d++; } } for (j2 = C_ext_offd_i[j1]; j2 < C_ext_offd_i[j1+1]; j2++) { jcol = C_ext_offd_j[j2]; if (B_marker_offd[jcol] < ik) { B_marker_offd[jcol] = ik; nnz_o++; } } break; } } } C_diag_array[ii] = nnz_d; C_offd_array[ii] = nnz_o; } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif if (ii == 0) { nnz_d = 0; nnz_o = 0; for (ik = 0; ik < num_threads-1; ik++) { C_diag_array[ik+1] += C_diag_array[ik]; C_offd_array[ik+1] += C_offd_array[ik]; } nnz_d = C_diag_array[num_threads-1]; nnz_o = C_offd_array[num_threads-1]; C_diag_i[num_cols_diag_A] = nnz_d; C_offd_i[num_cols_diag_A] = nnz_o; C_diag = hypre_CSRMatrixCreate(num_cols_diag_A, num_cols_diag_A, nnz_d); C_offd = hypre_CSRMatrixCreate(num_cols_diag_A, num_cols_offd_C, nnz_o); hypre_CSRMatrixI(C_diag) = C_diag_i; hypre_CSRMatrixInitialize_v2(C_diag, 0, memory_location_C); C_diag_j = hypre_CSRMatrixJ(C_diag); C_diag_data = hypre_CSRMatrixData(C_diag); hypre_CSRMatrixI(C_offd) = C_offd_i; hypre_CSRMatrixInitialize_v2(C_offd, 0, memory_location_C); C_offd_j = hypre_CSRMatrixJ(C_offd); C_offd_data = hypre_CSRMatrixData(C_offd); } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif /*----------------------------------------------------------------------- * Need to compute C_diag = C_tmp_diag + C_ext_diag * and C_offd = C_tmp_offd + C_ext_offd !!!! * Now fill in values *-----------------------------------------------------------------------*/ for (ik = 0; ik < num_cols_diag_B; ik++) { B_marker[ik] = -1; } for (ik = 0; ik < num_cols_offd_C; ik++) { B_marker_offd[ik] = -1; } /*----------------------------------------------------------------------- * Populate matrices *-----------------------------------------------------------------------*/ nnz_d = 0; nnz_o = 0; if (ii) { nnz_d = C_diag_array[ii-1]; nnz_o = C_offd_array[ii-1]; } for (ik = ns; ik < ne; ik++) { C_diag_i[ik] = nnz_d; C_offd_i[ik] = nnz_o; for (jk = C_tmp_diag_i[ik]; jk < C_tmp_diag_i[ik+1]; jk++) { jcol = C_tmp_diag_j[jk]; C_diag_j[nnz_d] = jcol; C_diag_data[nnz_d] = C_tmp_diag_data[jk]; B_marker[jcol] = nnz_d; nnz_d++; } for (jk = C_tmp_offd_i[ik]; jk < C_tmp_offd_i[ik+1]; jk++) { jcol = C_tmp_offd_j[jk]; C_offd_j[nnz_o] = jcol; C_offd_data[nnz_o] = C_tmp_offd_data[jk]; B_marker_offd[jcol] = nnz_o; nnz_o++; } for (jk = 0; jk < num_sends_A; jk++) { for (j1 = send_map_starts_A[jk]; j1 < send_map_starts_A[jk+1]; j1++) { if (send_map_elmts_A[j1] == ik) { for (j2 = C_ext_diag_i[j1]; j2 < C_ext_diag_i[j1+1]; j2++) { jcol = C_ext_diag_j[j2]; if (B_marker[jcol] < C_diag_i[ik]) { C_diag_j[nnz_d] = jcol; C_diag_data[nnz_d] = C_ext_diag_data[j2]; B_marker[jcol] = nnz_d; nnz_d++; } else { C_diag_data[B_marker[jcol]] += C_ext_diag_data[j2]; } } for (j2 = C_ext_offd_i[j1]; j2 < C_ext_offd_i[j1+1]; j2++) { jcol = C_ext_offd_j[j2]; if (B_marker_offd[jcol] < C_offd_i[ik]) { C_offd_j[nnz_o] = jcol; C_offd_data[nnz_o] = C_ext_offd_data[j2]; B_marker_offd[jcol] = nnz_o; nnz_o++; } else { C_offd_data[B_marker_offd[jcol]] += C_ext_offd_data[j2]; } } break; } } } } hypre_TFree(B_marker, HYPRE_MEMORY_HOST); hypre_TFree(B_marker_offd, HYPRE_MEMORY_HOST); } /*end parallel region */ hypre_TFree(C_diag_array, HYPRE_MEMORY_HOST); hypre_TFree(C_offd_array, HYPRE_MEMORY_HOST); } /*C = hypre_ParCSRMatrixCreate(comm, ncols_A, ncols_B, col_starts_A, col_starts_B, num_cols_offd_C, nnz_diag, nnz_offd); hypre_CSRMatrixDestroy(hypre_ParCSRMatrixDiag(C)); hypre_CSRMatrixDestroy(hypre_ParCSRMatrixOffd(C)); */ /* row_starts[0] is start of local rows. row_starts[1] is start of next processor's rows */ first_row_index = col_starts_A[0]; local_num_rows = (HYPRE_Int)(col_starts_A[1]-first_row_index ); first_col_diag = col_starts_B[0]; local_num_cols = (HYPRE_Int)(col_starts_B[1]-first_col_diag); C = hypre_CTAlloc(hypre_ParCSRMatrix, 1, HYPRE_MEMORY_HOST); hypre_ParCSRMatrixComm(C) = comm; hypre_ParCSRMatrixGlobalNumRows(C) = ncols_A; hypre_ParCSRMatrixGlobalNumCols(C) = ncols_B; hypre_ParCSRMatrixFirstRowIndex(C) = first_row_index; hypre_ParCSRMatrixFirstColDiag(C) = first_col_diag; hypre_ParCSRMatrixLastRowIndex(C) = first_row_index + (HYPRE_BigInt)local_num_rows - 1; hypre_ParCSRMatrixLastColDiag(C) = first_col_diag + (HYPRE_BigInt)local_num_cols - 1; hypre_ParCSRMatrixColMapOffd(C) = NULL; hypre_ParCSRMatrixAssumedPartition(C) = NULL; hypre_ParCSRMatrixRowStarts(C) = col_starts_A; hypre_ParCSRMatrixColStarts(C) = col_starts_B; hypre_ParCSRMatrixCommPkg(C) = NULL; hypre_ParCSRMatrixCommPkgT(C) = NULL; /* set defaults */ hypre_ParCSRMatrixOwnsData(C) = 1; hypre_ParCSRMatrixRowindices(C) = NULL; hypre_ParCSRMatrixRowvalues(C) = NULL; hypre_ParCSRMatrixGetrowactive(C) = 0; /* Note that C does not own the partitionings */ hypre_ParCSRMatrixSetRowStartsOwner(C,0); hypre_ParCSRMatrixSetColStartsOwner(C,0); if (C_diag) { hypre_CSRMatrixSetRownnz(C_diag); hypre_ParCSRMatrixDiag(C) = C_diag; } else { hypre_ParCSRMatrixDiag(C) = C_tmp_diag; } if (C_offd) { hypre_CSRMatrixSetRownnz(C_offd); hypre_ParCSRMatrixOffd(C) = C_offd; } else { hypre_ParCSRMatrixOffd(C) = C_tmp_offd; } hypre_CSRMatrixMemoryLocation(hypre_ParCSRMatrixDiag(C)) = memory_location_C; hypre_CSRMatrixMemoryLocation(hypre_ParCSRMatrixOffd(C)) = memory_location_C; if (num_cols_offd_C) { HYPRE_Int jj_count_offd, nnz_offd; HYPRE_BigInt *new_col_map_offd_C = NULL; P_marker = hypre_CTAlloc(HYPRE_Int, num_cols_offd_C, HYPRE_MEMORY_HOST); for (i = 0; i < num_cols_offd_C; i++) { P_marker[i] = -1; } jj_count_offd = 0; nnz_offd = C_offd_i[num_cols_diag_A]; for (i = 0; i < nnz_offd; i++) { i1 = C_offd_j[i]; if (P_marker[i1]) { P_marker[i1] = 0; jj_count_offd++; } } if (jj_count_offd < num_cols_offd_C) { new_col_map_offd_C = hypre_CTAlloc(HYPRE_BigInt, jj_count_offd, HYPRE_MEMORY_HOST); jj_count_offd = 0; for (i = 0; i < num_cols_offd_C; i++) { if (!P_marker[i]) { P_marker[i] = jj_count_offd; new_col_map_offd_C[jj_count_offd++] = col_map_offd_C[i]; } } for (i = 0; i < nnz_offd; i++) { i1 = C_offd_j[i]; C_offd_j[i] = P_marker[i1]; } num_cols_offd_C = jj_count_offd; hypre_TFree(col_map_offd_C, HYPRE_MEMORY_HOST); col_map_offd_C = new_col_map_offd_C; hypre_CSRMatrixNumCols(hypre_ParCSRMatrixOffd(C)) = num_cols_offd_C; } hypre_TFree(P_marker, HYPRE_MEMORY_HOST); } hypre_ParCSRMatrixColMapOffd(C) = col_map_offd_C; /*----------------------------------------------------------------------- * Free various arrays *-----------------------------------------------------------------------*/ if (C_ext_size || num_cols_offd_B) { hypre_TFree(C_ext_diag_i, HYPRE_MEMORY_HOST); hypre_TFree(C_ext_offd_i, HYPRE_MEMORY_HOST); } if (C_ext_diag_size) { hypre_TFree(C_ext_diag_j, HYPRE_MEMORY_HOST); hypre_TFree(C_ext_diag_data, HYPRE_MEMORY_HOST); } if (C_ext_offd_size) { hypre_TFree(C_ext_offd_j, HYPRE_MEMORY_HOST); hypre_TFree(C_ext_offd_data, HYPRE_MEMORY_HOST); } if (num_cols_offd_B) { hypre_TFree(map_B_to_C, HYPRE_MEMORY_HOST); } if (C_diag) { hypre_CSRMatrixDestroy(C_tmp_diag); } if (C_offd) { hypre_CSRMatrixDestroy(C_tmp_offd); } #if defined(HYPRE_USING_CUDA) || defined(HYPRE_USING_HIP) if ( hypre_GetExecPolicy2(memory_location_A, memory_location_B) == HYPRE_EXEC_DEVICE ) { hypre_CSRMatrixMoveDiagFirstDevice(hypre_ParCSRMatrixDiag(C)); hypre_SyncCudaComputeStream(hypre_handle()); } #endif return C; } HYPRE_Int hypre_ParvecBdiagInvScal( hypre_ParVector *b, HYPRE_Int blockSize, hypre_ParVector **bs, hypre_ParCSRMatrix *A) { MPI_Comm comm = hypre_ParCSRMatrixComm(b); HYPRE_Int num_procs, my_id; hypre_MPI_Comm_rank(comm, &my_id); hypre_MPI_Comm_size(comm, &num_procs); HYPRE_Int i, j, s, block_start, block_end; HYPRE_BigInt nrow_global = hypre_ParVectorGlobalSize(b); HYPRE_BigInt first_row = hypre_ParVectorFirstIndex(b); HYPRE_BigInt last_row = hypre_ParVectorLastIndex(b); HYPRE_BigInt end_row = last_row + 1; /* one past-the-last */ HYPRE_BigInt first_row_block = first_row / (HYPRE_BigInt)(blockSize) * (HYPRE_BigInt)blockSize; HYPRE_BigInt end_row_block = hypre_min( (last_row / (HYPRE_BigInt)blockSize + 1) * (HYPRE_BigInt)blockSize, nrow_global ); hypre_assert(blockSize == A->bdiag_size); HYPRE_Complex *bdiaginv = A->bdiaginv; hypre_ParCSRCommPkg *comm_pkg = A->bdiaginv_comm_pkg; HYPRE_Complex *dense = bdiaginv; //for (i=first_row_block; i < end_row; i+=blockSize) ; //printf("===[%d %d), [ %d %d ) %d === \n", first_row, end_row, first_row_block, end_row_block, i); /* local vector of b */ hypre_Vector *b_local = hypre_ParVectorLocalVector(b); HYPRE_Complex *b_local_data = hypre_VectorData(b_local); /* number of sends (#procs) */ HYPRE_Int num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); /* number of rows to send */ HYPRE_Int num_rows_send = hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends); /* number of recvs (#procs) */ HYPRE_Int num_recvs = hypre_ParCSRCommPkgNumRecvs(comm_pkg); /* number of rows to recv */ HYPRE_Int num_rows_recv = hypre_ParCSRCommPkgRecvVecStart(comm_pkg, num_recvs); hypre_ParCSRCommHandle *comm_handle; HYPRE_BigInt *part = hypre_TAlloc(HYPRE_BigInt, 2, HYPRE_MEMORY_HOST); hypre_TMemcpy(part, hypre_ParVectorPartitioning(b), HYPRE_BigInt, 2, HYPRE_MEMORY_HOST, HYPRE_MEMORY_HOST); hypre_ParVector *bnew = hypre_ParVectorCreate( hypre_ParVectorComm(b), hypre_ParVectorGlobalSize(b), part ); hypre_ParVectorInitialize(bnew); hypre_Vector *bnew_local = hypre_ParVectorLocalVector(bnew); HYPRE_Complex *bnew_local_data = hypre_VectorData(bnew_local); /* send and recv b */ HYPRE_Complex *send_b = hypre_TAlloc(HYPRE_Complex, num_rows_send, HYPRE_MEMORY_HOST); HYPRE_Complex *recv_b = hypre_TAlloc(HYPRE_Complex, num_rows_recv, HYPRE_MEMORY_HOST); for (i = 0; i < num_rows_send; i++) { j = hypre_ParCSRCommPkgSendMapElmt(comm_pkg, i); send_b[i] = b_local_data[j]; } comm_handle = hypre_ParCSRCommHandleCreate(1, comm_pkg, send_b, recv_b); /* ... */ hypre_ParCSRCommHandleDestroy(comm_handle); for (block_start = first_row_block; block_start < end_row_block; block_start += blockSize) { HYPRE_BigInt big_i; block_end = hypre_min(block_start + (HYPRE_BigInt)blockSize, nrow_global); s = (HYPRE_Int)(block_end - block_start); for (big_i = block_start; big_i < block_end; big_i++) { if (big_i < first_row || big_i >= end_row) { continue; } HYPRE_Int local_i = (HYPRE_Int)(big_i - first_row); HYPRE_Int block_i = (HYPRE_Int)(big_i - block_start); bnew_local_data[local_i] = 0.0; for (j = 0; j < s; j++) { HYPRE_BigInt global_rid = block_start + (HYPRE_BigInt)j; HYPRE_Complex val = dense[block_i + j*blockSize]; if (val == 0.0) { continue; } if (global_rid >= first_row && global_rid < end_row) { HYPRE_Int rid = (HYPRE_Int)(global_rid - first_row); bnew_local_data[local_i] += val * b_local_data[rid]; } else { HYPRE_Int rid; if (global_rid < first_row) { rid = (HYPRE_Int)(global_rid - first_row_block); } else { rid = (HYPRE_Int)(first_row - first_row_block + global_rid - end_row); } bnew_local_data[local_i] += val * recv_b[rid]; } } } dense += blockSize * blockSize; } hypre_TFree(send_b, HYPRE_MEMORY_HOST); hypre_TFree(recv_b, HYPRE_MEMORY_HOST); *bs = bnew; return hypre_error_flag; } /** * @brief Compute As = B^{-1}*A, where B is the block diagonal of A * @param[in] A : * @param[in] blockSize: block size * @param[out] B : * @return * @warning */ HYPRE_Int hypre_ParcsrBdiagInvScal( hypre_ParCSRMatrix *A, HYPRE_Int blockSize, hypre_ParCSRMatrix **As) { MPI_Comm comm = hypre_ParCSRMatrixComm(A); HYPRE_Int num_procs, my_id; hypre_MPI_Comm_rank(comm, &my_id); hypre_MPI_Comm_size(comm, &num_procs); HYPRE_Int i, j, k, s; HYPRE_BigInt block_start, block_end; /* diag part of A */ hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); HYPRE_Real *A_diag_a = hypre_CSRMatrixData(A_diag); HYPRE_Int *A_diag_i = hypre_CSRMatrixI(A_diag); HYPRE_Int *A_diag_j = hypre_CSRMatrixJ(A_diag); /* off-diag part of A */ hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A); HYPRE_Real *A_offd_a = hypre_CSRMatrixData(A_offd); HYPRE_Int *A_offd_i = hypre_CSRMatrixI(A_offd); HYPRE_Int *A_offd_j = hypre_CSRMatrixJ(A_offd); HYPRE_Int num_cols_A_offd = hypre_CSRMatrixNumCols(A_offd); HYPRE_BigInt *col_map_offd_A = hypre_ParCSRMatrixColMapOffd(A); HYPRE_Int nrow_local = hypre_CSRMatrixNumRows(A_diag); HYPRE_BigInt first_row = hypre_ParCSRMatrixFirstRowIndex(A); HYPRE_BigInt last_row = hypre_ParCSRMatrixLastRowIndex(A); HYPRE_BigInt end_row = first_row + (HYPRE_BigInt)nrow_local; /* one past-the-last */ HYPRE_Int ncol_local = hypre_CSRMatrixNumCols(A_diag); HYPRE_BigInt first_col = hypre_ParCSRMatrixFirstColDiag(A); /* HYPRE_Int last_col = hypre_ParCSRMatrixLastColDiag(A); */ HYPRE_BigInt end_col = first_col + (HYPRE_BigInt)ncol_local; HYPRE_BigInt nrow_global = hypre_ParCSRMatrixGlobalNumRows(A); HYPRE_BigInt ncol_global = hypre_ParCSRMatrixGlobalNumCols(A); HYPRE_BigInt *row_starts = hypre_ParCSRMatrixRowStarts(A); void *request; /* if square globally and locally */ HYPRE_Int square2 = (nrow_global == ncol_global) && (nrow_local == ncol_local) && (first_row == first_col); if (nrow_global != ncol_global) { hypre_printf("hypre_ParcsrBdiagInvScal: only support N_ROW == N_COL\n"); return hypre_error_flag; } /* in block diagonals, row range of the blocks this proc span */ HYPRE_BigInt first_row_block = first_row / (HYPRE_BigInt)blockSize * (HYPRE_BigInt)blockSize; HYPRE_BigInt end_row_block = hypre_min( (last_row / (HYPRE_BigInt)blockSize + 1) * (HYPRE_BigInt)blockSize, nrow_global ); HYPRE_Int num_blocks = (HYPRE_Int)(last_row / (HYPRE_BigInt)blockSize + 1 - first_row / (HYPRE_BigInt)blockSize); //for (i=first_row_block; i < end_row; i+=blockSize) ; //printf("===[%d %d), [ %d %d ) %d === \n", first_row, end_row, first_row_block, end_row_block, i); //return 0; /* number of external rows */ HYPRE_Int num_ext_rows = (HYPRE_Int)(end_row_block - first_row_block - (end_row - first_row)); HYPRE_BigInt *ext_indices; HYPRE_Int A_ext_nnz; hypre_CSRMatrix *A_ext = NULL; HYPRE_Complex *A_ext_a = NULL; HYPRE_Int *A_ext_i = NULL; HYPRE_BigInt *A_ext_j = NULL; HYPRE_Real *dense_all = hypre_CTAlloc(HYPRE_Complex, num_blocks*blockSize*blockSize, HYPRE_MEMORY_HOST); HYPRE_Real *dense = dense_all; HYPRE_Int *IPIV = hypre_TAlloc(HYPRE_Int, blockSize, HYPRE_MEMORY_HOST); HYPRE_Complex *dgetri_work = NULL; HYPRE_Int dgetri_lwork = -1, lapack_info; HYPRE_Int num_cols_A_offd_new; HYPRE_BigInt *col_map_offd_A_new; HYPRE_BigInt big_i; HYPRE_Int *offd2new = NULL; HYPRE_Int *marker_diag, *marker_newoffd; HYPRE_Int nnz_diag = A_diag_i[nrow_local]; HYPRE_Int nnz_offd = A_offd_i[nrow_local]; HYPRE_Int nnz_diag_new = 0, nnz_offd_new = 0; HYPRE_Int *A_diag_i_new, *A_diag_j_new, *A_offd_i_new, *A_offd_j_new; HYPRE_Complex *A_diag_a_new, *A_offd_a_new; /* heuristic */ HYPRE_Int nnz_diag_alloc = 2 * nnz_diag; HYPRE_Int nnz_offd_alloc = 2 * nnz_offd; A_diag_i_new = hypre_CTAlloc(HYPRE_Int, nrow_local + 1, HYPRE_MEMORY_HOST); A_diag_j_new = hypre_CTAlloc(HYPRE_Int, nnz_diag_alloc, HYPRE_MEMORY_HOST); A_diag_a_new = hypre_CTAlloc(HYPRE_Complex, nnz_diag_alloc, HYPRE_MEMORY_HOST); A_offd_i_new = hypre_CTAlloc(HYPRE_Int, nrow_local + 1, HYPRE_MEMORY_HOST); A_offd_j_new = hypre_CTAlloc(HYPRE_Int, nnz_offd_alloc, HYPRE_MEMORY_HOST); A_offd_a_new = hypre_CTAlloc(HYPRE_Complex, nnz_offd_alloc, HYPRE_MEMORY_HOST); hypre_ParCSRMatrix *Anew; hypre_CSRMatrix *Anew_diag; hypre_CSRMatrix *Anew_offd; HYPRE_BigInt *row_starts_new, *col_starts_new; HYPRE_Real eps = 2.2e-16; /* Start with extracting the external rows */ HYPRE_BigInt *ext_offd; ext_indices = hypre_CTAlloc(HYPRE_BigInt, num_ext_rows, HYPRE_MEMORY_HOST); j = 0; for (big_i = first_row_block; big_i < first_row; big_i++) { ext_indices[j++] = big_i; } for (big_i = end_row; big_i < end_row_block; big_i++) { ext_indices[j++] = big_i; } hypre_assert(j == num_ext_rows); /* create CommPkg for external rows */ hypre_ParCSRFindExtendCommPkg(comm, nrow_global, first_row, nrow_local, row_starts, hypre_ParCSRMatrixAssumedPartition(A), num_ext_rows, ext_indices, &A->bdiaginv_comm_pkg); hypre_ParcsrGetExternalRowsInit(A, num_ext_rows, ext_indices, A->bdiaginv_comm_pkg, 1, &request); A_ext = hypre_ParcsrGetExternalRowsWait(request); hypre_TFree(ext_indices, HYPRE_MEMORY_HOST); A_ext_i = hypre_CSRMatrixI(A_ext); A_ext_j = hypre_CSRMatrixBigJ(A_ext); A_ext_a = hypre_CSRMatrixData(A_ext); A_ext_nnz = A_ext_i[num_ext_rows]; ext_offd = hypre_CTAlloc(HYPRE_BigInt, A_ext_nnz, HYPRE_MEMORY_HOST); /* fint the offd incides in A_ext */ for (i = 0, j = 0; i < A_ext_nnz; i++) { /* global index */ HYPRE_BigInt cid = A_ext_j[i]; /* keep the offd indices */ if (cid < first_col || cid >= end_col) { ext_offd[j++] = cid; } } /* remove duplicates after sorting (TODO better ways?) */ hypre_BigQsort0(ext_offd, 0, j-1); for (i = 0, k = 0; i < j; i++) { if (i == 0 || ext_offd[i] != ext_offd[i-1]) { ext_offd[k++] = ext_offd[i]; } } /* uniion these `k' new indices into col_map_offd_A */ col_map_offd_A_new = hypre_CTAlloc(HYPRE_BigInt, num_cols_A_offd + k, HYPRE_MEMORY_HOST); if (k) { /* map offd to offd_new */ offd2new = hypre_CTAlloc(HYPRE_Int, num_cols_A_offd, HYPRE_MEMORY_HOST); } hypre_union2(num_cols_A_offd, col_map_offd_A, k, ext_offd, &num_cols_A_offd_new, col_map_offd_A_new, offd2new, NULL); hypre_TFree(ext_offd, HYPRE_MEMORY_HOST); /* * adjust column indices in A_ext */ for (i = 0; i < A_ext_nnz; i++) { HYPRE_BigInt cid = A_ext_j[i]; if (cid < first_col || cid >= end_col) { j = hypre_BigBinarySearch(col_map_offd_A_new, cid, num_cols_A_offd_new); /* searching must succeed */ hypre_assert(j >= 0 && j < num_cols_A_offd_new); /* trick: save ncol_local + j back */ A_ext_j[i] = ncol_local + j; } else { /* save local index: [0, ncol_local-1] */ A_ext_j[i] = cid - first_col; } } /* marker for diag */ marker_diag = hypre_TAlloc(HYPRE_Int, ncol_local, HYPRE_MEMORY_HOST); for (i = 0; i < ncol_local; i++) { marker_diag[i] = -1; } /* marker for newoffd */ marker_newoffd = hypre_TAlloc(HYPRE_Int, num_cols_A_offd_new, HYPRE_MEMORY_HOST); for (i = 0; i < num_cols_A_offd_new; i++) { marker_newoffd[i] = -1; } /* outer most loop for blocks */ for (block_start = first_row_block; block_start < end_row_block; block_start += (HYPRE_BigInt)blockSize) { HYPRE_BigInt big_i; block_end = hypre_min(block_start + (HYPRE_BigInt)blockSize, nrow_global); s = (HYPRE_Int)(block_end - block_start); /* 1. fill the dense block diag matrix */ for (big_i = block_start; big_i < block_end; big_i++) { /* row index in this block */ HYPRE_Int block_i = (HYPRE_Int)(big_i - block_start); /* row index i: it can be local or external */ if (big_i >= first_row && big_i < end_row) { /* is a local row */ j = (HYPRE_Int)(big_i - first_row); for (k = A_diag_i[j]; k < A_diag_i[j+1]; k++) { HYPRE_BigInt cid = (HYPRE_BigInt)A_diag_j[k] + first_col; if (cid >= block_start && cid < block_end) { dense[block_i + (HYPRE_Int)(cid-block_start)*blockSize] = A_diag_a[k]; } } if (num_cols_A_offd) { for (k = A_offd_i[j]; k < A_offd_i[j+1]; k++) { HYPRE_BigInt cid = col_map_offd_A[A_offd_j[k]]; if (cid >= block_start && cid < block_end) { dense[block_i + (HYPRE_Int)(cid-block_start)*blockSize] = A_offd_a[k]; } } } } else { /* is an external row */ if (big_i < first_row) { j = (HYPRE_Int)(big_i - first_row_block); } else { j = (HYPRE_Int)(first_row - first_row_block + big_i - end_row); } for (k = A_ext_i[j]; k < A_ext_i[j+1]; k++) { HYPRE_BigInt cid = A_ext_j[k]; /* recover the global index */ cid = cid < (HYPRE_BigInt)ncol_local ? cid + first_col : col_map_offd_A_new[cid-ncol_local]; if (cid >= block_start && cid < block_end) { dense[block_i + (HYPRE_Int)(cid-block_start)*blockSize] = A_ext_a[k]; } } } } /* 2. invert the dense matrix */ hypre_dgetrf(&s, &s, dense, &blockSize, IPIV, &lapack_info); hypre_assert(lapack_info == 0); if (lapack_info == 0) { HYPRE_Int query = -1; HYPRE_Real lwork_opt; /* query the optimal size of work */ hypre_dgetri(&s, dense, &blockSize, IPIV, &lwork_opt, &query, &lapack_info); hypre_assert(lapack_info == 0); if (lwork_opt > dgetri_lwork) { dgetri_lwork = lwork_opt; dgetri_work = hypre_TReAlloc(dgetri_work, HYPRE_Complex, dgetri_lwork, HYPRE_MEMORY_HOST); } hypre_dgetri(&s, dense, &blockSize, IPIV, dgetri_work, &dgetri_lwork, &lapack_info); hypre_assert(lapack_info == 0); } /* filter out *zeros* */ HYPRE_Real Fnorm = 0.0; for (i = 0; i < s; i++) { for (j = 0; j < s; j++) { HYPRE_Complex t = dense[j+i*blockSize]; Fnorm += t * t; } } Fnorm = sqrt(Fnorm); for (i = 0; i < s; i++) { for (j = 0; j < s; j++) { if ( hypre_abs(dense[j+i*blockSize]) < eps * Fnorm ) { dense[j+i*blockSize] = 0.0; } } } /* 3. premultiplication: one-pass dynamic allocation */ for (big_i = block_start; big_i < block_end; big_i++) { /* starting points of this row in j */ HYPRE_Int diag_i_start = nnz_diag_new; HYPRE_Int offd_i_start = nnz_offd_new; /* compute a new row with global index 'i' and local index 'local_i' */ HYPRE_Int local_i = (HYPRE_Int)(big_i - first_row); /* row index in this block */ HYPRE_Int block_i = (HYPRE_Int)(big_i - block_start); if (big_i < first_row || big_i >= end_row) { continue; } /* if square^2: reserve the first space in diag part to the diag entry */ if (square2) { marker_diag[local_i] = nnz_diag_new; if (nnz_diag_new == nnz_diag_alloc) { nnz_diag_alloc = nnz_diag_alloc * 2 + 1; A_diag_j_new = hypre_TReAlloc(A_diag_j_new, HYPRE_Int, nnz_diag_alloc, HYPRE_MEMORY_HOST); A_diag_a_new = hypre_TReAlloc(A_diag_a_new, HYPRE_Complex, nnz_diag_alloc, HYPRE_MEMORY_HOST); } A_diag_j_new[nnz_diag_new] = local_i; A_diag_a_new[nnz_diag_new] = 0.0; nnz_diag_new ++; } /* combine s rows */ for (j = 0; j < s; j++) { /* row to combine: global row id */ HYPRE_BigInt global_rid = block_start + (HYPRE_BigInt)j; /* the multipiler */ HYPRE_Complex val = dense[block_i + j*blockSize]; if (val == 0.0) { continue; } if (global_rid >= first_row && global_rid < end_row) { /* this row is local */ HYPRE_Int rid = (HYPRE_Int)(global_rid - first_row); HYPRE_Int ii; for (ii = A_diag_i[rid]; ii < A_diag_i[rid+1]; ii++) { HYPRE_Int col = A_diag_j[ii]; HYPRE_Complex vv = A_diag_a[ii]; if (marker_diag[col] < diag_i_start) { /* this col has not been seen before, create new entry */ marker_diag[col] = nnz_diag_new; if (nnz_diag_new == nnz_diag_alloc) { nnz_diag_alloc = nnz_diag_alloc * 2 + 1; A_diag_j_new = hypre_TReAlloc(A_diag_j_new, HYPRE_Int, nnz_diag_alloc, HYPRE_MEMORY_HOST); A_diag_a_new = hypre_TReAlloc(A_diag_a_new, HYPRE_Complex, nnz_diag_alloc, HYPRE_MEMORY_HOST); } A_diag_j_new[nnz_diag_new] = col; A_diag_a_new[nnz_diag_new] = val * vv; nnz_diag_new ++; } else { /* existing entry, update */ HYPRE_Int p = marker_diag[col]; hypre_assert(A_diag_j_new[p] == col); A_diag_a_new[p] += val * vv; } } for (ii = A_offd_i[rid]; ii < A_offd_i[rid+1]; ii++) { HYPRE_Int col = A_offd_j[ii]; /* use the mapper to map to new offd */ HYPRE_Int col_new = offd2new ? offd2new[col] : col; HYPRE_Complex vv = A_offd_a[ii]; if (marker_newoffd[col_new] < offd_i_start) { /* this col has not been seen before, create new entry */ marker_newoffd[col_new] = nnz_offd_new; if (nnz_offd_new == nnz_offd_alloc) { nnz_offd_alloc = nnz_offd_alloc * 2 + 1; A_offd_j_new = hypre_TReAlloc(A_offd_j_new, HYPRE_Int, nnz_offd_alloc, HYPRE_MEMORY_HOST); A_offd_a_new = hypre_TReAlloc(A_offd_a_new, HYPRE_Complex, nnz_offd_alloc, HYPRE_MEMORY_HOST); } A_offd_j_new[nnz_offd_new] = col_new; A_offd_a_new[nnz_offd_new] = val * vv; nnz_offd_new ++; } else { /* existing entry, update */ HYPRE_Int p = marker_newoffd[col_new]; hypre_assert(A_offd_j_new[p] == col_new); A_offd_a_new[p] += val * vv; } } } else { /* this is an external row: go to A_ext */ HYPRE_Int rid, ii; if (global_rid < first_row) { rid = (HYPRE_Int)(global_rid - first_row_block); } else { rid = (HYPRE_Int)(first_row - first_row_block + global_rid - end_row); } for (ii = A_ext_i[rid]; ii < A_ext_i[rid+1]; ii++) { HYPRE_Int col = (HYPRE_Int)A_ext_j[ii]; HYPRE_Complex vv = A_ext_a[ii]; if (col < ncol_local) { /* in diag part */ if (marker_diag[col] < diag_i_start) { /* this col has not been seen before, create new entry */ marker_diag[col] = nnz_diag_new; if (nnz_diag_new == nnz_diag_alloc) { nnz_diag_alloc = nnz_diag_alloc * 2 + 1; A_diag_j_new = hypre_TReAlloc(A_diag_j_new, HYPRE_Int, nnz_diag_alloc, HYPRE_MEMORY_HOST); A_diag_a_new = hypre_TReAlloc(A_diag_a_new, HYPRE_Complex, nnz_diag_alloc, HYPRE_MEMORY_HOST); } A_diag_j_new[nnz_diag_new] = col; A_diag_a_new[nnz_diag_new] = val * vv; nnz_diag_new ++; } else { /* existing entry, update */ HYPRE_Int p = marker_diag[col]; hypre_assert(A_diag_j_new[p] == col); A_diag_a_new[p] += val * vv; } } else { /* in offd part */ col -= ncol_local; if (marker_newoffd[col] < offd_i_start) { /* this col has not been seen before, create new entry */ marker_newoffd[col] = nnz_offd_new; if (nnz_offd_new == nnz_offd_alloc) { nnz_offd_alloc = nnz_offd_alloc * 2 + 1; A_offd_j_new = hypre_TReAlloc(A_offd_j_new, HYPRE_Int, nnz_offd_alloc, HYPRE_MEMORY_HOST); A_offd_a_new = hypre_TReAlloc(A_offd_a_new, HYPRE_Complex, nnz_offd_alloc, HYPRE_MEMORY_HOST); } A_offd_j_new[nnz_offd_new] = col; A_offd_a_new[nnz_offd_new] = val * vv; nnz_offd_new ++; } else { /* existing entry, update */ HYPRE_Int p = marker_newoffd[col]; hypre_assert(A_offd_j_new[p] == col); A_offd_a_new[p] += val * vv; } } } } } /* done for row local_i */ A_diag_i_new[local_i + 1] = nnz_diag_new; A_offd_i_new[local_i + 1] = nnz_offd_new; } /* for i, each row */ dense += blockSize * blockSize; } /* for each block */ /* done with all rows */ /* resize properly */ A_diag_j_new = hypre_TReAlloc(A_diag_j_new, HYPRE_Int, nnz_diag_new, HYPRE_MEMORY_HOST); A_diag_a_new = hypre_TReAlloc(A_diag_a_new, HYPRE_Complex, nnz_diag_new, HYPRE_MEMORY_HOST); A_offd_j_new = hypre_TReAlloc(A_offd_j_new, HYPRE_Int, nnz_offd_new, HYPRE_MEMORY_HOST); A_offd_a_new = hypre_TReAlloc(A_offd_a_new, HYPRE_Complex, nnz_offd_new, HYPRE_MEMORY_HOST); /* readjust col_map_offd_new */ for (i = 0; i < num_cols_A_offd_new; i++) { marker_newoffd[i] = -1; } for (i = 0; i < nnz_offd_new; i++) { j = A_offd_j_new[i]; if (marker_newoffd[j] == -1) { marker_newoffd[j] = 1; } } for (i = 0, j = 0; i < num_cols_A_offd_new; i++) { if (marker_newoffd[i] == 1) { col_map_offd_A_new[j] = col_map_offd_A_new[i]; marker_newoffd[i] = j++; } } num_cols_A_offd_new = j; for (i = 0; i < nnz_offd_new; i++) { j = marker_newoffd[A_offd_j_new[i]]; hypre_assert(j >= 0 && j < num_cols_A_offd_new); A_offd_j_new[i] = j; } row_starts_new = hypre_CTAlloc(HYPRE_BigInt, j, HYPRE_MEMORY_HOST); col_starts_new = hypre_CTAlloc(HYPRE_BigInt, j, HYPRE_MEMORY_HOST); hypre_TMemcpy(row_starts_new, hypre_ParCSRMatrixRowStarts(A), HYPRE_BigInt, 2, HYPRE_MEMORY_HOST, HYPRE_MEMORY_HOST); hypre_TMemcpy(col_starts_new, hypre_ParCSRMatrixColStarts(A), HYPRE_BigInt, 2, HYPRE_MEMORY_HOST, HYPRE_MEMORY_HOST); /* Now, we should have everything of Parcsr matrix As */ Anew = hypre_ParCSRMatrixCreate(comm, nrow_global, ncol_global, row_starts_new, col_starts_new, num_cols_A_offd_new, nnz_diag_new, nnz_offd_new); Anew_diag = hypre_ParCSRMatrixDiag(Anew); hypre_CSRMatrixData(Anew_diag) = A_diag_a_new; hypre_CSRMatrixI(Anew_diag) = A_diag_i_new; hypre_CSRMatrixJ(Anew_diag) = A_diag_j_new; Anew_offd = hypre_ParCSRMatrixOffd(Anew); hypre_CSRMatrixData(Anew_offd) = A_offd_a_new; hypre_CSRMatrixI(Anew_offd) = A_offd_i_new; hypre_CSRMatrixJ(Anew_offd) = A_offd_j_new; hypre_ParCSRMatrixColMapOffd(Anew) = col_map_offd_A_new; hypre_ParCSRMatrixSetNumNonzeros(Anew); hypre_ParCSRMatrixDNumNonzeros(Anew) = (HYPRE_Real) hypre_ParCSRMatrixNumNonzeros(Anew); //printf("nnz_diag %d --> %d, nnz_offd %d --> %d\n", nnz_diag, nnz_diag_new, nnz_offd, nnz_offd_new); /* create CommPkg of Anew */ hypre_MatvecCommPkgCreate(Anew); *As = Anew; /* if (bdiaginv) { *bdiaginv = dense_all; } else { hypre_TFree(dense_all, HYPRE_MEMORY_HOST); } */ /* save diagonal blocks in A */ A->bdiag_size = blockSize; A->bdiaginv = dense_all; /* free workspace */ hypre_TFree(IPIV, HYPRE_MEMORY_HOST); hypre_TFree(dgetri_work, HYPRE_MEMORY_HOST); hypre_TFree(marker_diag, HYPRE_MEMORY_HOST); hypre_TFree(marker_newoffd, HYPRE_MEMORY_HOST); hypre_TFree(offd2new, HYPRE_MEMORY_HOST); hypre_CSRMatrixDestroy(A_ext); return hypre_error_flag; } HYPRE_Int hypre_ParcsrGetExternalRowsInit( hypre_ParCSRMatrix *A, HYPRE_Int indices_len, HYPRE_BigInt *indices, hypre_ParCSRCommPkg *comm_pkg, HYPRE_Int want_data, void **request_ptr) { HYPRE_Int i, j, k; HYPRE_Int num_sends, num_rows_send, num_nnz_send, *send_i, num_recvs, num_rows_recv, num_nnz_recv, *recv_i, *send_jstarts, *recv_jstarts, *send_i_offset; HYPRE_BigInt *send_j, *recv_j; HYPRE_Complex *send_a = NULL, *recv_a = NULL; hypre_ParCSRCommPkg *comm_pkg_j; hypre_ParCSRCommHandle *comm_handle, *comm_handle_j, *comm_handle_a; /* HYPRE_Int global_num_rows = hypre_ParCSRMatrixGlobalNumRows(A); */ /* diag part of A */ hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); HYPRE_Real *A_diag_a = hypre_CSRMatrixData(A_diag); HYPRE_Int *A_diag_i = hypre_CSRMatrixI(A_diag); HYPRE_Int *A_diag_j = hypre_CSRMatrixJ(A_diag); /* HYPRE_Int local_num_rows = hypre_CSRMatrixNumRows(A_diag); */ /* off-diag part of A */ hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A); HYPRE_Real *A_offd_a = hypre_CSRMatrixData(A_offd); HYPRE_Int *A_offd_i = hypre_CSRMatrixI(A_offd); HYPRE_Int *A_offd_j = hypre_CSRMatrixJ(A_offd); /* HYPRE_BigInt *row_starts = hypre_ParCSRMatrixRowStarts(A); */ /* HYPRE_BigInt first_row = hypre_ParCSRMatrixFirstRowIndex(A); */ HYPRE_BigInt first_col = hypre_ParCSRMatrixFirstColDiag(A); HYPRE_BigInt *col_map_offd_A = hypre_ParCSRMatrixColMapOffd(A); MPI_Comm comm = hypre_ParCSRMatrixComm(A); HYPRE_Int num_procs; HYPRE_Int my_id; void **vrequest; hypre_CSRMatrix *A_ext; hypre_MPI_Comm_size(comm, &num_procs); hypre_MPI_Comm_rank(comm, &my_id); /* number of sends (#procs) */ num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); /* number of rows to send */ num_rows_send = hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends); /* number of recvs (#procs) */ num_recvs = hypre_ParCSRCommPkgNumRecvs(comm_pkg); /* number of rows to recv */ num_rows_recv = hypre_ParCSRCommPkgRecvVecStart(comm_pkg, num_recvs); /* must be true if indices contains proper offd indices */ hypre_assert(indices_len == num_rows_recv); /* send_i/recv_i: * the arrays to send and recv: we first send and recv the row lengths */ send_i = hypre_TAlloc(HYPRE_Int, num_rows_send, HYPRE_MEMORY_HOST); recv_i = hypre_CTAlloc(HYPRE_Int, num_rows_recv + 1, HYPRE_MEMORY_HOST); /* fill the send array with row lengths */ for (i = 0, num_nnz_send = 0; i < num_rows_send; i++) { /* j: row index to send */ j = hypre_ParCSRCommPkgSendMapElmt(comm_pkg, i); send_i[i] = A_diag_i[j+1] - A_diag_i[j] + A_offd_i[j+1] - A_offd_i[j]; num_nnz_send += send_i[i]; } /* send this array out: note the shift in recv_i by one (async) */ comm_handle = hypre_ParCSRCommHandleCreate(11, comm_pkg, send_i, recv_i+1); /* prepare data to send out. overlap with the above commmunication */ send_j = hypre_TAlloc(HYPRE_BigInt, num_nnz_send, HYPRE_MEMORY_HOST); if (want_data) { send_a = hypre_TAlloc(HYPRE_Complex, num_nnz_send, HYPRE_MEMORY_HOST); } send_i_offset = hypre_TAlloc(HYPRE_Int, num_rows_send + 1, HYPRE_MEMORY_HOST); send_i_offset[0] = 0; hypre_TMemcpy(send_i_offset + 1, send_i, HYPRE_Int, num_rows_send, HYPRE_MEMORY_HOST, HYPRE_MEMORY_HOST); /* prefix sum. TODO: OMP parallelization */ for (i = 1; i <= num_rows_send; i++) { send_i_offset[i] += send_i_offset[i-1]; } hypre_assert(send_i_offset[num_rows_send] == num_nnz_send); /* pointers to each proc in send_j */ send_jstarts = hypre_TAlloc(HYPRE_Int, num_sends + 1, HYPRE_MEMORY_HOST); #ifdef HYPRE_USING_OPENMP #pragma omp parallel for HYPRE_SMP_SCHEDULE #endif for (i = 0; i <= num_sends; i++) { send_jstarts[i] = send_i_offset[hypre_ParCSRCommPkgSendMapStart(comm_pkg, i)]; } hypre_assert(send_jstarts[num_sends] == num_nnz_send); /* fill the CSR matrix: j and a */ #ifdef HYPRE_USING_OPENMP #pragma omp parallel for HYPRE_SMP_SCHEDULE private(i,j,k) #endif for (i = 0; i < num_rows_send; i++) { HYPRE_Int i1 = send_i_offset[i]; j = hypre_ParCSRCommPkgSendMapElmt(comm_pkg, i); /* open row j and fill ja and a to send */ for (k = A_diag_i[j]; k < A_diag_i[j+1]; k++) { send_j[i1] = first_col + A_diag_j[k]; if (want_data) { send_a[i1] = A_diag_a[k]; } i1++; } if (num_procs > 1) { for (k = A_offd_i[j]; k < A_offd_i[j+1]; k++) { send_j[i1] = col_map_offd_A[A_offd_j[k]]; if (want_data) { send_a[i1] = A_offd_a[k]; } i1++; } } hypre_assert(send_i_offset[i+1] == i1); } /* finish the above communication: send_i/recv_i */ hypre_ParCSRCommHandleDestroy(comm_handle); /* adjust recv_i to ptrs */ for (i = 1; i <= num_rows_recv; i++) { recv_i[i] += recv_i[i-1]; } num_nnz_recv = recv_i[num_rows_recv]; recv_j = hypre_CTAlloc(HYPRE_BigInt, num_nnz_recv, HYPRE_MEMORY_HOST); if (want_data) { recv_a = hypre_CTAlloc(HYPRE_Complex, num_nnz_recv, HYPRE_MEMORY_HOST); } recv_jstarts = hypre_CTAlloc(HYPRE_Int, num_recvs + 1, HYPRE_MEMORY_HOST); for (i = 1; i <= num_recvs; i++) { j = hypre_ParCSRCommPkgRecvVecStart(comm_pkg, i); recv_jstarts[i] = recv_i[j]; } /* ready to send and recv: create a communication package for data */ comm_pkg_j = hypre_CTAlloc(hypre_ParCSRCommPkg, 1, HYPRE_MEMORY_HOST); hypre_ParCSRCommPkgComm (comm_pkg_j) = comm; hypre_ParCSRCommPkgNumSends (comm_pkg_j) = num_sends; hypre_ParCSRCommPkgSendProcs (comm_pkg_j) = hypre_ParCSRCommPkgSendProcs(comm_pkg); hypre_ParCSRCommPkgSendMapStarts(comm_pkg_j) = send_jstarts; hypre_ParCSRCommPkgNumRecvs (comm_pkg_j) = num_recvs; hypre_ParCSRCommPkgRecvProcs (comm_pkg_j) = hypre_ParCSRCommPkgRecvProcs(comm_pkg); hypre_ParCSRCommPkgRecvVecStarts(comm_pkg_j) = recv_jstarts; /* init communication */ /* ja */ comm_handle_j = hypre_ParCSRCommHandleCreate(21, comm_pkg_j, send_j, recv_j); if (want_data) { /* a */ comm_handle_a = hypre_ParCSRCommHandleCreate(1, comm_pkg_j, send_a, recv_a); } else { comm_handle_a = NULL; } /* create A_ext */ A_ext = hypre_CSRMatrixCreate(num_rows_recv, hypre_ParCSRMatrixGlobalNumCols(A), num_nnz_recv); hypre_CSRMatrixMemoryLocation(A_ext) = HYPRE_MEMORY_HOST; hypre_CSRMatrixI (A_ext) = recv_i; hypre_CSRMatrixBigJ(A_ext) = recv_j; hypre_CSRMatrixData(A_ext) = recv_a; /* output */ vrequest = hypre_TAlloc(void *, 4, HYPRE_MEMORY_HOST); vrequest[0] = (void *) comm_handle_j; vrequest[1] = (void *) comm_handle_a; vrequest[2] = (void *) A_ext; vrequest[3] = (void *) comm_pkg_j; *request_ptr = (void *) vrequest; /* free */ hypre_TFree(send_i, HYPRE_MEMORY_HOST); hypre_TFree(send_i_offset, HYPRE_MEMORY_HOST); return hypre_error_flag; } hypre_CSRMatrix* hypre_ParcsrGetExternalRowsWait(void *vrequest) { void **request = (void **) vrequest; hypre_ParCSRCommHandle *comm_handle_j = (hypre_ParCSRCommHandle *) request[0]; hypre_ParCSRCommHandle *comm_handle_a = (hypre_ParCSRCommHandle *) request[1]; hypre_CSRMatrix *A_ext = (hypre_CSRMatrix *) request[2]; hypre_ParCSRCommPkg *comm_pkg_j = (hypre_ParCSRCommPkg *) request[3]; HYPRE_BigInt *send_j = (HYPRE_BigInt *) hypre_ParCSRCommHandleSendData(comm_handle_j); if (comm_handle_a) { HYPRE_Complex *send_a = (HYPRE_Complex *) hypre_ParCSRCommHandleSendData(comm_handle_a); hypre_ParCSRCommHandleDestroy(comm_handle_a); hypre_TFree(send_a, HYPRE_MEMORY_HOST); } hypre_ParCSRCommHandleDestroy(comm_handle_j); hypre_TFree(send_j, HYPRE_MEMORY_HOST); hypre_TFree(hypre_ParCSRCommPkgSendMapStarts(comm_pkg_j), HYPRE_MEMORY_HOST); hypre_TFree(hypre_ParCSRCommPkgRecvVecStarts(comm_pkg_j), HYPRE_MEMORY_HOST); hypre_TFree(comm_pkg_j, HYPRE_MEMORY_HOST); hypre_TFree(request, HYPRE_MEMORY_HOST); return A_ext; } /*-------------------------------------------------------------------------- * hypre_ParCSRMatrixAdd: performs C = alpha*A + beta*B * * A and B are assumed to have the same row and column partitionings *--------------------------------------------------------------------------*/ HYPRE_Int hypre_ParCSRMatrixAddHost( HYPRE_Complex alpha, hypre_ParCSRMatrix *A, HYPRE_Complex beta, hypre_ParCSRMatrix *B, hypre_ParCSRMatrix **C_ptr ) { /* ParCSRMatrix data */ MPI_Comm comm = hypre_ParCSRMatrixComm(A); HYPRE_BigInt num_rows_A = hypre_ParCSRMatrixGlobalNumRows(A); HYPRE_BigInt num_cols_A = hypre_ParCSRMatrixGlobalNumCols(A); /* HYPRE_BigInt num_rows_B = hypre_ParCSRMatrixGlobalNumRows(B); */ /* HYPRE_BigInt num_cols_B = hypre_ParCSRMatrixGlobalNumCols(B); */ /* diag part of A */ hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); HYPRE_Int *rownnz_diag_A = hypre_CSRMatrixRownnz(A_diag); HYPRE_Int num_rownnz_diag_A = hypre_CSRMatrixNumRownnz(A_diag); HYPRE_Int num_rows_diag_A = hypre_CSRMatrixNumRows(A_diag); HYPRE_Int num_cols_diag_A = hypre_CSRMatrixNumCols(A_diag); /* off-diag part of A */ hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A); HYPRE_Int *rownnz_offd_A = hypre_CSRMatrixRownnz(A_offd); HYPRE_Int num_rownnz_offd_A = hypre_CSRMatrixNumRownnz(A_offd); HYPRE_Int num_rows_offd_A = hypre_CSRMatrixNumRows(A_offd); HYPRE_Int num_cols_offd_A = hypre_CSRMatrixNumCols(A_offd); HYPRE_BigInt *col_map_offd_A = hypre_ParCSRMatrixColMapOffd(A); HYPRE_Int *A2C_offd; /* diag part of B */ hypre_CSRMatrix *B_diag = hypre_ParCSRMatrixDiag(B); HYPRE_Int *rownnz_diag_B = hypre_CSRMatrixRownnz(B_diag); HYPRE_Int num_rownnz_diag_B = hypre_CSRMatrixNumRownnz(B_diag); HYPRE_Int num_rows_diag_B = hypre_CSRMatrixNumRows(B_diag); /* HYPRE_Int num_cols_diag_B = hypre_CSRMatrixNumCols(B_diag); */ /* off-diag part of B */ hypre_CSRMatrix *B_offd = hypre_ParCSRMatrixOffd(B); HYPRE_Int *rownnz_offd_B = hypre_CSRMatrixRownnz(B_offd); HYPRE_Int num_rownnz_offd_B = hypre_CSRMatrixNumRownnz(B_offd); HYPRE_Int num_rows_offd_B = hypre_CSRMatrixNumRows(B_offd); HYPRE_Int num_cols_offd_B = hypre_CSRMatrixNumCols(B_offd); HYPRE_BigInt *col_map_offd_B = hypre_ParCSRMatrixColMapOffd(B); HYPRE_Int *B2C_offd; /* C data */ hypre_ParCSRMatrix *C; HYPRE_BigInt *row_starts_C; HYPRE_BigInt *col_starts_C; hypre_CSRMatrix *C_diag; hypre_CSRMatrix *C_offd; HYPRE_BigInt *col_map_offd_C; HYPRE_Int *C_diag_i, *C_offd_i; HYPRE_Int *rownnz_diag_C = NULL; HYPRE_Int *rownnz_offd_C = NULL; HYPRE_Int num_rownnz_diag_C; HYPRE_Int num_rownnz_offd_C; HYPRE_Int num_rows_diag_C = num_rows_diag_A; HYPRE_Int num_cols_diag_C = num_cols_diag_A; HYPRE_Int num_rows_offd_C = num_rows_offd_A; HYPRE_Int num_cols_offd_C = num_cols_offd_A + num_cols_offd_B; HYPRE_Int *twspace; HYPRE_MemoryLocation memory_location_A = hypre_ParCSRMatrixMemoryLocation(A); HYPRE_MemoryLocation memory_location_B = hypre_ParCSRMatrixMemoryLocation(B); /* RL: TODO cannot guarantee, maybe should never assert hypre_assert(memory_location_A == memory_location_B); */ /* RL: in the case of A=H, B=D, or A=D, B=H, let C = D, * not sure if this is the right thing to do. * Also, need something like this in other places * TODO */ HYPRE_MemoryLocation memory_location_C = hypre_max(memory_location_A, memory_location_B); HYPRE_ANNOTATE_FUNC_BEGIN; /* Allocate memory */ twspace = hypre_TAlloc(HYPRE_Int, hypre_NumThreads(), HYPRE_MEMORY_HOST); C_diag_i = hypre_CTAlloc(HYPRE_Int, num_rows_diag_A + 1, memory_location_C); C_offd_i = hypre_CTAlloc(HYPRE_Int, num_rows_offd_A + 1, memory_location_C); col_map_offd_C = hypre_TAlloc(HYPRE_BigInt, num_cols_offd_C, HYPRE_MEMORY_HOST); /* Compute num_cols_offd_C, A2C_offd, and B2C_offd*/ A2C_offd = hypre_TAlloc(HYPRE_Int, num_cols_offd_A, HYPRE_MEMORY_HOST); B2C_offd = hypre_TAlloc(HYPRE_Int, num_cols_offd_B, HYPRE_MEMORY_HOST); hypre_union2(num_cols_offd_A, col_map_offd_A, num_cols_offd_B, col_map_offd_B, &num_cols_offd_C, col_map_offd_C, A2C_offd, B2C_offd); /* Set nonzero rows data of diag_C */ num_rownnz_diag_C = num_rows_diag_A; if ((num_rownnz_diag_A < num_rows_diag_A) && (num_rownnz_diag_B < num_rows_diag_B)) { hypre_MergeOrderedArrays( num_rownnz_diag_A, rownnz_diag_A, num_rownnz_diag_B, rownnz_diag_B, &num_rownnz_diag_C, &rownnz_diag_C); } /* Set nonzero rows data of offd_C */ num_rownnz_offd_C = num_rows_offd_A; if ((num_rownnz_offd_A < num_rows_offd_A) && (num_rownnz_offd_B < num_rows_offd_B)) { hypre_MergeOrderedArrays( num_rownnz_offd_A, rownnz_offd_A, num_rownnz_offd_B, rownnz_offd_B, &num_rownnz_offd_C, &rownnz_offd_C); } /* Set diag_C */ #ifdef HYPRE_USING_OPENMP #pragma omp parallel #endif { HYPRE_Int ii, num_threads; HYPRE_Int size, rest, ns, ne; HYPRE_Int *marker_diag; HYPRE_Int *marker_offd; ii = hypre_GetThreadNum(); num_threads = hypre_NumActiveThreads(); /*----------------------------------------------------------------------- * Compute C_diag = alpha*A_diag + beta*B_diag *-----------------------------------------------------------------------*/ size = num_rownnz_diag_C/num_threads; rest = num_rownnz_diag_C - size*num_threads; if (ii < rest) { ns = ii*size+ii; ne = (ii+1)*size+ii+1; } else { ns = ii*size+rest; ne = (ii+1)*size+rest; } marker_diag = hypre_TAlloc(HYPRE_Int, num_cols_diag_A, HYPRE_MEMORY_HOST); hypre_CSRMatrixAddFirstPass(ns, ne, twspace, marker_diag, NULL, NULL, A_diag, B_diag, num_rows_diag_C, num_rownnz_diag_C, num_cols_diag_C, rownnz_diag_C, memory_location_C, C_diag_i, &C_diag); hypre_CSRMatrixAddSecondPass(ns, ne, twspace, marker_diag, NULL, NULL, rownnz_diag_C, alpha, beta, A_diag, B_diag, C_diag); hypre_TFree(marker_diag, HYPRE_MEMORY_HOST); /*----------------------------------------------------------------------- * Compute C_offd = alpha*A_offd + beta*B_offd *-----------------------------------------------------------------------*/ size = num_rownnz_offd_C/num_threads; rest = num_rownnz_offd_C - size*num_threads; if (ii < rest) { ns = ii*size+ii; ne = (ii+1)*size+ii+1; } else { ns = ii*size+rest; ne = (ii+1)*size+rest; } marker_offd = hypre_TAlloc(HYPRE_Int, num_cols_offd_C, HYPRE_MEMORY_HOST); hypre_CSRMatrixAddFirstPass(ns, ne, twspace, marker_offd, A2C_offd, B2C_offd, A_offd, B_offd, num_rows_offd_C, num_rownnz_offd_C, num_cols_offd_C, rownnz_offd_C, memory_location_C, C_offd_i, &C_offd); hypre_CSRMatrixAddSecondPass(ns, ne, twspace, marker_offd, A2C_offd, B2C_offd, rownnz_offd_C, alpha, beta, A_offd, B_offd, C_offd); hypre_TFree(marker_offd, HYPRE_MEMORY_HOST); } /* end of omp parallel region */ /* Free memory */ hypre_TFree(twspace, HYPRE_MEMORY_HOST); hypre_TFree(A2C_offd, HYPRE_MEMORY_HOST); hypre_TFree(B2C_offd, HYPRE_MEMORY_HOST); /* Create ParCSRMatrix C */ row_starts_C = hypre_TAlloc(HYPRE_BigInt, 2, HYPRE_MEMORY_HOST); col_starts_C = hypre_TAlloc(HYPRE_BigInt, 2, HYPRE_MEMORY_HOST); hypre_TMemcpy(row_starts_C, hypre_ParCSRMatrixRowStarts(A), HYPRE_BigInt, 2, HYPRE_MEMORY_HOST, HYPRE_MEMORY_HOST); hypre_TMemcpy(col_starts_C, hypre_ParCSRMatrixColStarts(A), HYPRE_BigInt, 2, HYPRE_MEMORY_HOST, HYPRE_MEMORY_HOST); C = hypre_ParCSRMatrixCreate(comm, num_rows_A, num_cols_A, row_starts_C, col_starts_C, num_cols_offd_C, hypre_CSRMatrixNumNonzeros(C_diag), hypre_CSRMatrixNumNonzeros(C_offd)); hypre_CSRMatrixDestroy(hypre_ParCSRMatrixDiag(C)); hypre_CSRMatrixDestroy(hypre_ParCSRMatrixOffd(C)); hypre_ParCSRMatrixDiag(C) = C_diag; hypre_ParCSRMatrixOffd(C) = C_offd; hypre_ParCSRMatrixColMapOffd(C) = col_map_offd_C; hypre_ParCSRMatrixSetNumNonzeros(C); hypre_ParCSRMatrixDNumNonzeros(C) = (HYPRE_Real) hypre_ParCSRMatrixNumNonzeros(C); /* create CommPkg of C */ hypre_MatvecCommPkgCreate(C); *C_ptr = C; HYPRE_ANNOTATE_FUNC_END; return hypre_error_flag; } HYPRE_Int hypre_ParCSRMatrixAdd( HYPRE_Complex alpha, hypre_ParCSRMatrix *A, HYPRE_Complex beta, hypre_ParCSRMatrix *B, hypre_ParCSRMatrix **C_ptr ) { hypre_assert(hypre_ParCSRMatrixGlobalNumRows(A) == hypre_ParCSRMatrixGlobalNumRows(B)); hypre_assert(hypre_ParCSRMatrixGlobalNumCols(A) == hypre_ParCSRMatrixGlobalNumCols(B)); hypre_assert(hypre_ParCSRMatrixNumRows(A) == hypre_ParCSRMatrixNumRows(B)); hypre_assert(hypre_ParCSRMatrixNumCols(A) == hypre_ParCSRMatrixNumCols(B)); #if defined(HYPRE_USING_CUDA) || defined(HYPRE_USING_HIP) if ( hypre_GetExecPolicy2( hypre_ParCSRMatrixMemoryLocation(A), hypre_ParCSRMatrixMemoryLocation(B) ) == HYPRE_EXEC_DEVICE ) { hypre_ParCSRMatrixAddDevice(alpha, A, beta, B, C_ptr); } else #endif { hypre_ParCSRMatrixAddHost(alpha, A, beta, B, C_ptr); } return hypre_error_flag; } /*-------------------------------------------------------------------------- * hypre_ParCSRMatrixFnorm *--------------------------------------------------------------------------*/ HYPRE_Real hypre_ParCSRMatrixFnorm( hypre_ParCSRMatrix *A ) { MPI_Comm comm = hypre_ParCSRMatrixComm(A); HYPRE_Real f_diag, f_offd, local_result, result; f_diag = hypre_CSRMatrixFnorm(hypre_ParCSRMatrixDiag(A)); f_offd = hypre_CSRMatrixFnorm(hypre_ParCSRMatrixOffd(A)); local_result = f_diag * f_diag + f_offd * f_offd; hypre_MPI_Allreduce(&local_result, &result, 1, HYPRE_MPI_REAL, hypre_MPI_SUM, comm); return sqrt(result); } /*-------------------------------------------------------------------------- * hypre_ExchangeExternalRowsInit *--------------------------------------------------------------------------*/ HYPRE_Int hypre_ExchangeExternalRowsInit( hypre_CSRMatrix *B_ext, hypre_ParCSRCommPkg *comm_pkg_A, void **request_ptr) { MPI_Comm comm = hypre_ParCSRCommPkgComm(comm_pkg_A); HYPRE_Int num_recvs = hypre_ParCSRCommPkgNumRecvs(comm_pkg_A); HYPRE_Int *recv_procs = hypre_ParCSRCommPkgRecvProcs(comm_pkg_A); HYPRE_Int *recv_vec_starts = hypre_ParCSRCommPkgRecvVecStarts(comm_pkg_A); HYPRE_Int num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg_A); HYPRE_Int *send_procs = hypre_ParCSRCommPkgSendProcs(comm_pkg_A); HYPRE_Int *send_map_starts = hypre_ParCSRCommPkgSendMapStarts(comm_pkg_A); HYPRE_Int num_elmts_send = send_map_starts[num_sends]; HYPRE_Int num_elmts_recv = recv_vec_starts[num_recvs]; HYPRE_Int *B_ext_i = B_ext ? hypre_CSRMatrixI(B_ext) : NULL; HYPRE_BigInt *B_ext_j = B_ext ? hypre_CSRMatrixBigJ(B_ext) : NULL; HYPRE_Complex *B_ext_data = B_ext ? hypre_CSRMatrixData(B_ext) : NULL; HYPRE_Int B_ext_ncols = B_ext ? hypre_CSRMatrixNumCols(B_ext) : 0; HYPRE_Int B_ext_nrows = B_ext ? hypre_CSRMatrixNumRows(B_ext) : 0; HYPRE_Int *B_ext_rownnz = hypre_CTAlloc(HYPRE_Int, B_ext_nrows, HYPRE_MEMORY_HOST); hypre_assert(num_elmts_recv == B_ext_nrows); /* output matrix */ hypre_CSRMatrix *B_int; HYPRE_Int B_int_nrows = num_elmts_send; HYPRE_Int B_int_ncols = B_ext_ncols; HYPRE_Int *B_int_i = hypre_TAlloc(HYPRE_Int, B_int_nrows + 1, HYPRE_MEMORY_HOST); HYPRE_BigInt *B_int_j = NULL; HYPRE_Complex *B_int_data = NULL; HYPRE_Int B_int_nnz; hypre_ParCSRCommHandle *comm_handle, *comm_handle_j, *comm_handle_a; hypre_ParCSRCommPkg *comm_pkg_j; HYPRE_Int *jdata_recv_vec_starts; HYPRE_Int *jdata_send_map_starts; HYPRE_Int i; HYPRE_Int num_procs; void **vrequest; hypre_MPI_Comm_size(comm, &num_procs); jdata_send_map_starts = hypre_TAlloc(HYPRE_Int, num_sends+1, HYPRE_MEMORY_HOST); /*-------------------------------------------------------------------------- * B_ext_rownnz contains the number of elements of row j * (to be determined through send_map_elmnts on the receiving end) *--------------------------------------------------------------------------*/ for (i = 0; i < B_ext_nrows; i++) { B_ext_rownnz[i] = B_ext_i[i+1] - B_ext_i[i]; } /*-------------------------------------------------------------------------- * initialize communication: send/recv the row nnz * (note the use of comm_pkg_A, mode 12, as in transpose matvec *--------------------------------------------------------------------------*/ comm_handle = hypre_ParCSRCommHandleCreate(12, comm_pkg_A, B_ext_rownnz, B_int_i + 1); jdata_recv_vec_starts = hypre_TAlloc(HYPRE_Int, num_recvs + 1, HYPRE_MEMORY_HOST); jdata_recv_vec_starts[0] = 0; for (i = 1; i <= num_recvs; i++) { jdata_recv_vec_starts[i] = B_ext_i[recv_vec_starts[i]]; } comm_pkg_j = hypre_CTAlloc(hypre_ParCSRCommPkg, 1, HYPRE_MEMORY_HOST); hypre_ParCSRCommPkgComm(comm_pkg_j) = comm; hypre_ParCSRCommPkgNumSends(comm_pkg_j) = num_recvs; hypre_ParCSRCommPkgNumRecvs(comm_pkg_j) = num_sends; hypre_ParCSRCommPkgSendProcs(comm_pkg_j) = recv_procs; hypre_ParCSRCommPkgRecvProcs(comm_pkg_j) = send_procs; hypre_ParCSRCommHandleDestroy(comm_handle); /*-------------------------------------------------------------------------- * compute B_int: row nnz to row ptrs *--------------------------------------------------------------------------*/ B_int_i[0] = 0; for (i = 1; i <= B_int_nrows; i++) { B_int_i[i] += B_int_i[i-1]; } B_int_nnz = B_int_i[B_int_nrows]; B_int_j = hypre_TAlloc(HYPRE_BigInt, B_int_nnz, HYPRE_MEMORY_HOST); B_int_data = hypre_TAlloc(HYPRE_Complex, B_int_nnz, HYPRE_MEMORY_HOST); for (i = 0; i <= num_sends; i++) { jdata_send_map_starts[i] = B_int_i[send_map_starts[i]]; } /* note the order of send/recv is reversed */ hypre_ParCSRCommPkgRecvVecStarts(comm_pkg_j) = jdata_send_map_starts; hypre_ParCSRCommPkgSendMapStarts(comm_pkg_j) = jdata_recv_vec_starts; /* send/recv CSR rows */ comm_handle_a = hypre_ParCSRCommHandleCreate( 1, comm_pkg_j, B_ext_data, B_int_data); comm_handle_j = hypre_ParCSRCommHandleCreate(21, comm_pkg_j, B_ext_j, B_int_j); /* create CSR */ B_int = hypre_CSRMatrixCreate(B_int_nrows, B_int_ncols, B_int_nnz); hypre_CSRMatrixMemoryLocation(B_int) = HYPRE_MEMORY_HOST; hypre_CSRMatrixI(B_int) = B_int_i; hypre_CSRMatrixBigJ(B_int) = B_int_j; hypre_CSRMatrixData(B_int) = B_int_data; /* output */ vrequest = hypre_TAlloc(void *, 4, HYPRE_MEMORY_HOST); vrequest[0] = (void *) comm_handle_j; vrequest[1] = (void *) comm_handle_a; vrequest[2] = (void *) B_int; vrequest[3] = (void *) comm_pkg_j; *request_ptr = (void *) vrequest; hypre_TFree(B_ext_rownnz, HYPRE_MEMORY_HOST); return hypre_error_flag; } /*-------------------------------------------------------------------------- * hypre_ExchangeExternalRowsWait *--------------------------------------------------------------------------*/ hypre_CSRMatrix* hypre_ExchangeExternalRowsWait(void *vrequest) { void **request = (void **) vrequest; hypre_ParCSRCommHandle *comm_handle_j = (hypre_ParCSRCommHandle *) request[0]; hypre_ParCSRCommHandle *comm_handle_a = (hypre_ParCSRCommHandle *) request[1]; hypre_CSRMatrix *B_int = (hypre_CSRMatrix *) request[2]; hypre_ParCSRCommPkg *comm_pkg_j = (hypre_ParCSRCommPkg *) request[3]; /* communication done */ hypre_ParCSRCommHandleDestroy(comm_handle_a); hypre_ParCSRCommHandleDestroy(comm_handle_j); hypre_TFree(hypre_ParCSRCommPkgSendMapStarts(comm_pkg_j), HYPRE_MEMORY_HOST); hypre_TFree(hypre_ParCSRCommPkgRecvVecStarts(comm_pkg_j), HYPRE_MEMORY_HOST); hypre_TFree(comm_pkg_j, HYPRE_MEMORY_HOST); hypre_TFree(request, HYPRE_MEMORY_HOST); return B_int; } /*-------------------------------------------------------------------------- * hypre_ParCSRMatrixExtractSubmatrixFC * * extract submatrix A_{FF}, A_{FC}, A_{CF} or A_{CC} * char job[2] = "FF", "FC", "CF" or "CC" *--------------------------------------------------------------------------*/ HYPRE_Int hypre_ParCSRMatrixExtractSubmatrixFC( hypre_ParCSRMatrix *A, HYPRE_Int *CF_marker, HYPRE_BigInt *cpts_starts_in, const char *job, hypre_ParCSRMatrix **B_ptr, HYPRE_Real strength_thresh) { MPI_Comm comm = hypre_ParCSRMatrixComm(A); hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(A); hypre_ParCSRCommHandle *comm_handle; /* diag part of A */ hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); HYPRE_Complex *A_diag_a = hypre_CSRMatrixData(A_diag); HYPRE_Int *A_diag_i = hypre_CSRMatrixI(A_diag); HYPRE_Int *A_diag_j = hypre_CSRMatrixJ(A_diag); /* off-diag part of A */ hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A); HYPRE_Complex *A_offd_a = hypre_CSRMatrixData(A_offd); HYPRE_Int *A_offd_i = hypre_CSRMatrixI(A_offd); HYPRE_Int *A_offd_j = hypre_CSRMatrixJ(A_offd); HYPRE_Int num_cols_A_offd = hypre_CSRMatrixNumCols(A_offd); //HYPRE_Int *col_map_offd_A = hypre_ParCSRMatrixColMapOffd(A); hypre_ParCSRMatrix *B; hypre_CSRMatrix *B_diag, *B_offd; HYPRE_Real *B_maxel_row; HYPRE_Int *B_diag_i, *B_diag_j, *B_offd_i, *B_offd_j; HYPRE_Complex *B_diag_a, *B_offd_a; HYPRE_Int num_cols_B_offd; HYPRE_BigInt *col_map_offd_B; HYPRE_Int i, j, k, k1, k2; HYPRE_BigInt B_nrow_global, B_ncol_global; HYPRE_Int A_nlocal, B_nrow_local, B_ncol_local, B_nnz_diag, B_nnz_offd; HYPRE_BigInt total_global_fpts, total_global_cpts, *fpts_starts, *cpts_starts; HYPRE_Int nf_local, nc_local; HYPRE_Int row_set, col_set; HYPRE_BigInt *B_row_starts, *B_col_starts, B_first_col; HYPRE_Int my_id, num_procs, *sub_idx_diag, *sub_idx_offd; HYPRE_Int num_sends, *send_buf_data; /* MPI size and rank*/ hypre_MPI_Comm_size(comm, &num_procs); hypre_MPI_Comm_rank(comm, &my_id); row_set = job[0] == 'F' ? -1 : 1; col_set = job[1] == 'F' ? -1 : 1; A_nlocal = hypre_CSRMatrixNumRows(A_diag); /*-------------- global number of C points and local C points * assuming cpts_starts is given */ if (row_set == 1 || col_set == 1) { /* copy cpts_starts first */ HYPRE_Int len; len = 2; cpts_starts = hypre_TAlloc(HYPRE_BigInt, len, HYPRE_MEMORY_HOST); hypre_TMemcpy(cpts_starts, cpts_starts_in, HYPRE_BigInt, len, HYPRE_MEMORY_HOST, HYPRE_MEMORY_HOST); if (my_id == (num_procs -1)) { total_global_cpts = cpts_starts[1]; } hypre_MPI_Bcast(&total_global_cpts, 1, HYPRE_MPI_INT, num_procs-1, comm); nc_local = (HYPRE_Int)(cpts_starts[1] - cpts_starts[0]); } /*-------------- global number of F points, local F points, and F starts */ if (row_set == -1 || col_set == -1) { nf_local = 0; for (i = 0; i < A_nlocal; i++) { if (CF_marker[i] < 0) { nf_local++; } } fpts_starts = hypre_TAlloc(HYPRE_BigInt, 2, HYPRE_MEMORY_HOST); hypre_MPI_Scan(&nf_local, fpts_starts+1, 1, HYPRE_MPI_BIG_INT, hypre_MPI_SUM, comm); fpts_starts[0] = fpts_starts[1] - nf_local; if (my_id == num_procs - 1) { total_global_fpts = fpts_starts[1]; } hypre_MPI_Bcast(&total_global_fpts, 1, HYPRE_MPI_INT, num_procs-1, comm); } if (row_set == -1 && col_set == -1) { /* FF */ B_nrow_local = nf_local; B_ncol_local = nf_local; B_nrow_global = total_global_fpts; B_ncol_global = total_global_fpts; B_row_starts = B_col_starts = fpts_starts; } else if (row_set == -1 && col_set == 1) { /* FC */ B_nrow_local = nf_local; B_ncol_local = nc_local; B_nrow_global = total_global_fpts; B_ncol_global = total_global_cpts; B_row_starts = fpts_starts; B_col_starts = cpts_starts; } else if (row_set == 1 && col_set == -1) { /* CF */ B_nrow_local = nc_local; B_ncol_local = nf_local; B_nrow_global = total_global_cpts; B_ncol_global = total_global_fpts; B_row_starts = cpts_starts; B_col_starts = fpts_starts; } else { /* CC */ B_nrow_local = nc_local; B_ncol_local = nc_local; B_nrow_global = total_global_cpts; B_ncol_global = total_global_cpts; B_row_starts = B_col_starts = cpts_starts; } /* global index of my first col */ B_first_col = B_col_starts[0]; /* sub_idx_diag: [local] mapping from F+C to F/C, if not selected, be -1 */ sub_idx_diag = hypre_TAlloc(HYPRE_Int, A_nlocal, HYPRE_MEMORY_HOST); for (i = 0, k = 0; i < A_nlocal; i++) { HYPRE_Int CF_i = CF_marker[i] > 0 ? 1 : -1; if (CF_i == col_set) { sub_idx_diag[i] = k++; } else { sub_idx_diag[i] = -1; } } hypre_assert(k == B_ncol_local); num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); send_buf_data = hypre_TAlloc(HYPRE_Int, hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends), HYPRE_MEMORY_HOST); k = 0; for (i = 0; i < num_sends; i++) { /* start pos of elements sent to send_proc[i] */ HYPRE_Int si = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i); HYPRE_Int ei = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i+1); /* loop through all elems to send_proc[i] */ for (j = si; j < ei; j++) { /* j1: local idx */ HYPRE_Int j1 = sub_idx_diag[hypre_ParCSRCommPkgSendMapElmt(comm_pkg, j)]; if (j1 != -1) { /* adjust j1 to B global idx */ j1 += B_first_col; } send_buf_data[k++] = j1; } } hypre_assert(k == hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends)); /* recv buffer */ sub_idx_offd = hypre_TAlloc(HYPRE_Int, num_cols_A_offd, HYPRE_MEMORY_HOST); /* create a handle to start communication. 11: for integer */ comm_handle = hypre_ParCSRCommHandleCreate(11, comm_pkg, send_buf_data, sub_idx_offd); /* destroy the handle to finish communication */ hypre_ParCSRCommHandleDestroy(comm_handle); for (i = 0, num_cols_B_offd = 0; i < num_cols_A_offd; i++) { if (sub_idx_offd[i] != -1) { num_cols_B_offd ++; } } col_map_offd_B = hypre_TAlloc(HYPRE_BigInt, num_cols_B_offd, HYPRE_MEMORY_HOST); for (i = 0, k = 0; i < num_cols_A_offd; i++) { if (sub_idx_offd[i] != -1) { col_map_offd_B[k] = sub_idx_offd[i]; sub_idx_offd[i] = k++; } } hypre_assert(k == num_cols_B_offd); /* count nnz and set ia */ B_nnz_diag = B_nnz_offd = 0; B_maxel_row = hypre_TAlloc(HYPRE_Real, B_nrow_local, HYPRE_MEMORY_HOST); B_diag_i = hypre_TAlloc(HYPRE_Int, B_nrow_local+1, HYPRE_MEMORY_HOST); B_offd_i = hypre_TAlloc(HYPRE_Int, B_nrow_local+1, HYPRE_MEMORY_HOST); B_diag_i[0] = B_offd_i[0] = 0; for (i = 0, k = 0; i < A_nlocal; i++) { HYPRE_Int CF_i = CF_marker[i] > 0 ? 1 : -1; if (CF_i != row_set) { continue; } k++; // Get max abs-value element of this row HYPRE_Real temp_max = 0; if (strength_thresh > 0) { for (j = A_diag_i[i]+1; j < A_diag_i[i+1]; j++) { if (hypre_cabs(A_diag_a[j]) > temp_max) { temp_max = hypre_cabs(A_diag_a[j]); } } for (j = A_offd_i[i]; j < A_offd_i[i+1]; j++) { if (hypre_cabs(A_offd_a[j]) > temp_max) { temp_max = hypre_cabs(A_offd_a[j]); } } } B_maxel_row[k-1] = temp_max; // add one for diagonal element j = A_diag_i[i]; if (sub_idx_diag[A_diag_j[j]] != -1) { B_nnz_diag++; } // Count nnzs larger than tolerance times max row element for (j = A_diag_i[i]+1; j < A_diag_i[i+1]; j++) { if ( (sub_idx_diag[A_diag_j[j]] != -1) && (hypre_cabs(A_diag_a[j]) > (strength_thresh*temp_max)) ) { B_nnz_diag++; } } for (j = A_offd_i[i]; j < A_offd_i[i+1]; j++) { if ( (sub_idx_offd[A_offd_j[j]] != -1) && (hypre_cabs(A_offd_a[j]) > (strength_thresh*temp_max)) ) { B_nnz_offd++; } } B_diag_i[k] = B_nnz_diag; B_offd_i[k] = B_nnz_offd; } hypre_assert(k == B_nrow_local); B_diag_j = hypre_TAlloc(HYPRE_Int, B_nnz_diag, HYPRE_MEMORY_HOST); B_diag_a = hypre_TAlloc(HYPRE_Complex, B_nnz_diag, HYPRE_MEMORY_HOST); B_offd_j = hypre_TAlloc(HYPRE_Int, B_nnz_offd, HYPRE_MEMORY_HOST); B_offd_a = hypre_TAlloc(HYPRE_Complex, B_nnz_offd, HYPRE_MEMORY_HOST); for (i = 0, k=0, k1 = 0, k2 = 0; i < A_nlocal; i++) { HYPRE_Int CF_i = CF_marker[i] > 0 ? 1 : -1; if (CF_i != row_set) { continue; } HYPRE_Real maxel = B_maxel_row[k]; k++; for (j = A_diag_i[i]; j < A_diag_i[i+1]; j++) { HYPRE_Int j1 = sub_idx_diag[A_diag_j[j]]; if ( (j1 != -1) && ( (hypre_cabs(A_diag_a[j]) > (strength_thresh*maxel)) || j==A_diag_i[i] ) ) { B_diag_j[k1] = j1; B_diag_a[k1] = A_diag_a[j]; k1++; } } for (j = A_offd_i[i]; j < A_offd_i[i+1]; j++) { HYPRE_Int j1 = sub_idx_offd[A_offd_j[j]]; if ((j1 != -1) && (hypre_cabs(A_offd_a[j]) > (strength_thresh*maxel))) { hypre_assert(j1 >= 0 && j1 < num_cols_B_offd); B_offd_j[k2] = j1; B_offd_a[k2] = A_offd_a[j]; k2++; } } } hypre_assert(k1 == B_nnz_diag && k2 == B_nnz_offd); /* ready to create B = A(rowset, colset) */ B = hypre_ParCSRMatrixCreate(comm, B_nrow_global, B_ncol_global, B_row_starts, B_col_starts, num_cols_B_offd, B_nnz_diag, B_nnz_offd); B_diag = hypre_ParCSRMatrixDiag(B); hypre_CSRMatrixMemoryLocation(B_diag) = HYPRE_MEMORY_HOST; hypre_CSRMatrixData(B_diag) = B_diag_a; hypre_CSRMatrixI(B_diag) = B_diag_i; hypre_CSRMatrixJ(B_diag) = B_diag_j; B_offd = hypre_ParCSRMatrixOffd(B); hypre_CSRMatrixMemoryLocation(B_offd) = HYPRE_MEMORY_HOST; hypre_CSRMatrixData(B_offd) = B_offd_a; hypre_CSRMatrixI(B_offd) = B_offd_i; hypre_CSRMatrixJ(B_offd) = B_offd_j; hypre_ParCSRMatrixColMapOffd(B) = col_map_offd_B; hypre_ParCSRMatrixSetNumNonzeros(B); hypre_ParCSRMatrixDNumNonzeros(B) = (HYPRE_Real) hypre_ParCSRMatrixNumNonzeros(B); hypre_MatvecCommPkgCreate(B); *B_ptr = B; hypre_TFree(B_maxel_row, HYPRE_MEMORY_HOST); hypre_TFree(send_buf_data, HYPRE_MEMORY_HOST); hypre_TFree(sub_idx_diag, HYPRE_MEMORY_HOST); hypre_TFree(sub_idx_offd, HYPRE_MEMORY_HOST); return hypre_error_flag; }
GB_mask_template.c
//------------------------------------------------------------------------------ // GB_mask_template: phase1 and phase2 for R = masker (M, C, Z) //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // Computes C<M>=Z or C<!M>=Z, returning the result in R. The input matrix C // is not modified. Effectively, this computes R=C and then R<M>=Z or R<!M>=Z. // If the C_replace descriptor is enabled, then C has already been cleared, and // is an empty (but non-NULL) matrix. // phase1: does not compute R itself, but just counts the # of entries in each // vector of R. Fine tasks compute the # of entries in their slice of a // single vector of R, and the results are cumsum'd in GB_task_cumsum. // phase2: computes R, using the counts computed by phase1. // FUTURE:: add special cases for C==Z, C==M, and Z==M aliases //------------------------------------------------------------------------------ // R(i,j) = Z(i,j) //------------------------------------------------------------------------------ #if defined ( GB_PHASE_1_OF_2 ) #define GB_COPY_Z \ { \ rjnz++ ; \ } #else #define GB_COPY_Z \ { \ Ri [pR] = i ; \ memcpy (Rx +(pR)*rsize, Zx +(pZ)*rsize, rsize) ; \ pR++ ; \ } #endif //------------------------------------------------------------------------------ // R(i,j) = C(i,j) //------------------------------------------------------------------------------ #if defined ( GB_PHASE_1_OF_2 ) #define GB_COPY_C \ { \ rjnz++ ; \ } #else #define GB_COPY_C \ { \ Ri [pR] = i ; \ memcpy (Rx +(pR)*rsize, Cx +(pC)*rsize, rsize) ; \ pR++ ; \ } #endif //------------------------------------------------------------------------------ // mask template //------------------------------------------------------------------------------ { //-------------------------------------------------------------------------- // get C, Z, M, and R //-------------------------------------------------------------------------- const int64_t *restrict Cp = C->p ; const int64_t *restrict Ci = C->i ; const int64_t vlen = C->vlen ; const int64_t *restrict Zp = Z->p ; const int64_t *restrict Zi = Z->i ; const int64_t *restrict Mp = NULL ; // const int64_t *restrict Mh = NULL ; const int64_t *restrict Mi = NULL ; const GB_void *restrict Mx = NULL ; GB_cast_function cast_M = NULL ; size_t msize = 0 ; // int64_t Mnvec = 0 ; // bool M_is_hyper = false ; if (M != NULL) { Mp = M->p ; // Mh = M->h ; Mi = M->i ; Mx = M->x ; cast_M = GB_cast_factory (GB_BOOL_code, M->type->code) ; msize = M->type->size ; // Mnvec = M->nvec ; // M_is_hyper = M->is_hyper ; } #if defined ( GB_PHASE_2_OF_2 ) const GB_void *restrict Cx = C->x ; const GB_void *restrict Zx = Z->x ; const int64_t *restrict Rp = R->p ; const int64_t *restrict Rh = R->h ; int64_t *restrict Ri = R->i ; GB_void *restrict Rx = R->x ; size_t rsize = R->type->size ; #endif //-------------------------------------------------------------------------- // phase1: count entries in each C(:,j); phase2: compute C //-------------------------------------------------------------------------- #pragma omp parallel for num_threads(nthreads) schedule(dynamic,1) for (int taskid = 0 ; taskid < ntasks ; taskid++) { //---------------------------------------------------------------------- // get the task descriptor //---------------------------------------------------------------------- int64_t kfirst = TaskList [taskid].kfirst ; int64_t klast = TaskList [taskid].klast ; bool fine_task = (klast == -1) ; int64_t len ; if (fine_task) { // a fine task operates on a slice of a single vector klast = kfirst ; len = TaskList [taskid].len ; } else { // a coarse task operates on one or more whole vectors len = vlen ; } //---------------------------------------------------------------------- // compute all vectors in this task //---------------------------------------------------------------------- for (int64_t k = kfirst ; k <= klast ; k++) { //------------------------------------------------------------------ // get j, the kth vector of R //------------------------------------------------------------------ int64_t j = (Rh == NULL) ? k : Rh [k] ; #if defined ( GB_PHASE_1_OF_2 ) int64_t rjnz = 0 ; #else int64_t pR, pR_end ; if (fine_task) { // A fine task computes a slice of R(:,j) pR = TaskList [taskid ].pC ; pR_end = TaskList [taskid+1].pC ; ASSERT (Rp [k] <= pR && pR <= pR_end && pR_end <= Rp [k+1]) ; } else { // The vectors of R are never sliced for a coarse task. pR = Rp [k] ; pR_end = Rp [k+1] ; } int64_t rjnz = pR_end - pR ; if (rjnz == 0) continue ; #endif //------------------------------------------------------------------ // get C(:,j) //------------------------------------------------------------------ int64_t pC = -1, pC_end = -1 ; if (fine_task) { // A fine task operates on Ci,Cx [pC...pC_end-1], which is // a subset of the vector C(:,j) pC = TaskList [taskid].pA ; pC_end = TaskList [taskid].pA_end ; } else { // A coarse task operates on the entire vector C(:,j) int64_t kC = (R_to_C == NULL) ? j : R_to_C [k] ; if (kC >= 0) { pC = Cp [kC] ; pC_end = Cp [kC+1] ; } } int64_t cjnz = pC_end - pC ; // nnz in C(:,j) for this slice bool cdense = (cjnz == len) && (cjnz > 0) ; #if defined ( GB_PHASE_2_OF_2 ) || defined ( GB_DEBUG ) // get the first index in C(:,j) for this vector int64_t iC_first = -1 ; if (cjnz > 0) iC_first = Ci [pC] ; #endif #ifdef GB_DEBUG int64_t iC_last = -1 ; if (cjnz > 0) iC_last = Ci [pC_end-1] ; #endif //------------------------------------------------------------------ // get Z(:,j) //------------------------------------------------------------------ int64_t pZ = -1, pZ_end = -1 ; if (fine_task) { // A fine task operates on Zi,Zx [pZ...pZ_end-1], which is // a subset of the vector Z(:,j) pZ = TaskList [taskid].pB ; pZ_end = TaskList [taskid].pB_end ; } else { // A coarse task operates on the entire vector Z(:,j) int64_t kZ = (R_to_Z == NULL) ? j : R_to_Z [k] ; if (kZ >= 0) { pZ = Zp [kZ] ; pZ_end = Zp [kZ+1] ; } } int64_t zjnz = pZ_end - pZ ; // nnz in Z(:,j) for this slice bool zdense = (zjnz == len) && (zjnz > 0) ; #ifdef GB_DEBUG int64_t iZ_first = -1, iZ_last = -1 ; if (zjnz > 0) { iZ_first = Zi [pZ] ; iZ_last = Zi [pZ_end-1] ; } #endif //------------------------------------------------------------------ // get M(:,j) //------------------------------------------------------------------ int64_t pM = -1, pM_end = -1 ; if (fine_task) { // A fine task operates on Mi,Mx [pM...pM_end-1], which is // a subset of the vector M(:,j) pM = TaskList [taskid].pM ; pM_end = TaskList [taskid].pM_end ; } else { // A coarse task operates on the entire vector M (:,j) int64_t kM = (R_to_M == NULL) ? j : R_to_M [k] ; if (kM >= 0) { pM = Mp [kM] ; pM_end = Mp [kM+1] ; } } int64_t mjnz = pM_end - pM ; // nnz (M (:,j)) //------------------------------------------------------------------ // phase1: count nnz (R(:,j)); phase2: compute R(:,j) //------------------------------------------------------------------ if (mjnz == 0) { //-------------------------------------------------------------- // M(:,j) is empty //-------------------------------------------------------------- if (!Mask_comp) { //---------------------------------------------------------- // M(:,j) is empty and not complemented //---------------------------------------------------------- // R(:,j) = C(:,j), regardless of Z(:,j) #if defined ( GB_PHASE_1_OF_2 ) rjnz = cjnz ; #else ASSERT (rjnz == cjnz) ; memcpy (Ri +(pR), Ci +(pC), cjnz * sizeof (int64_t)) ; memcpy (Rx +(pR)*rsize, Cx +(pC)*rsize, cjnz*rsize) ; #endif } else { //---------------------------------------------------------- // M(:,j) is empty and complemented //---------------------------------------------------------- // R(:,j) = Z(:,j), regardless of C(:,j) #if defined ( GB_PHASE_1_OF_2 ) rjnz = zjnz ; #else ASSERT (rjnz == zjnz) ; memcpy (Ri +(pR), Zi +(pZ), zjnz * sizeof (int64_t)) ; memcpy (Rx +(pR)*rsize, Zx +(pZ)*rsize, zjnz*rsize) ; #endif } } else if (cdense && zdense) { //-------------------------------------------------------------- // C(:,j) and Z(:,j) dense: thus R(:,j) dense //-------------------------------------------------------------- ASSERT (cjnz == zjnz) ; ASSERT (iC_first == iZ_first) ; ASSERT (iC_last == iZ_last ) ; #if defined ( GB_PHASE_1_OF_2 ) rjnz = cjnz ; #else ASSERT (rjnz == cjnz) ; for (int64_t p = 0 ; p < cjnz ; p++) { int64_t i = p + iC_first ; Ri [pR + p] = i ; int64_t iM = (pM < pM_end) ? Mi [pM] : INT64_MAX ; bool mij = false ; if (i == iM) { cast_M (&mij, Mx +(pM*msize), 0) ; pM++ ; } if (Mask_comp) mij = !mij ; if (mij) { memcpy (Rx +(pR+p)*rsize, Zx +(pZ+p)*rsize, rsize) ; } else { memcpy (Rx +(pR+p)*rsize, Cx +(pC+p)*rsize, rsize) ; } } #endif } else { //-------------------------------------------------------------- // 2-way merge of C(:,j) and Z(:,j); binary search of M(:,j) //-------------------------------------------------------------- while (pC < pC_end && pZ < pZ_end) { //---------------------------------------------------------- // get the next i for R(:,j) //---------------------------------------------------------- int64_t iC = Ci [pC] ; int64_t iZ = Zi [pZ] ; int64_t i = GB_IMIN (iC, iZ) ; //---------------------------------------------------------- // get M(i,j) //---------------------------------------------------------- // Use GB_BINARY_SPLIT_SEARCH so that pM can be used in // the for loop with index pM in the wrapup phase. bool mij = false ; int64_t pright = pM_end - 1 ; bool found ; GB_BINARY_SPLIT_SEARCH (i, Mi, pM, pright, found) ; if (found) { cast_M (&mij, Mx +(pM*msize), 0) ; // increment pM for the wrapup phase below pM++ ; } if (Mask_comp) mij = !mij ; //---------------------------------------------------------- // R(i,j) = C(i,j) or Z(i,j) //---------------------------------------------------------- if (iC < iZ) { // C(i,j) is present but Z(i,j) is not if (!mij) GB_COPY_C ; pC++ ; } else if (iC > iZ) { // Z(i,j) is present but C(i,j) is not if (mij) GB_COPY_Z ; pZ++ ; } else { // both C(i,j) and Z(i,j) are present if (mij) { GB_COPY_Z ; } else { GB_COPY_C ; } pC++ ; pZ++ ; } } //-------------------------------------------------------------- // wrapup: C or Z are exhausted, or initially empty //-------------------------------------------------------------- cjnz = pC_end - pC ; // nnz (C(:,j)) remaining zjnz = pZ_end - pZ ; // nnz (Z(:,j)) remaining mjnz = pM_end - pM ; // nnz (M(:,j)) remaining if (cjnz == 0) { //---------------------------------------------------------- // C(:,j) is empty //---------------------------------------------------------- if (!Mask_comp) { //------------------------------------------------------ // mask is not complemented //------------------------------------------------------ if (zjnz > 32 * mjnz) { //-------------------------------------------------- // Z(:,j) is much denser than M(:,j) //-------------------------------------------------- // This loop requires pM to start at the first // entry in M(:,j) that has not yet been handled. for ( ; pM < pM_end ; pM++) { bool mij ; cast_M (&mij, Mx +(pM*msize), 0) ; if (mij) { int64_t i = Mi [pM] ; int64_t pright = pZ_end - 1 ; bool found ; GB_BINARY_SEARCH (i, Zi, pZ, pright, found); if (found) GB_COPY_Z ; } } } else if (mjnz > 32 * zjnz) { //-------------------------------------------------- // M(:,j) is much denser than Z(:,j) //-------------------------------------------------- for ( ; pZ < pZ_end ; pZ++) { int64_t i = Zi [pZ] ; bool mij = false ; int64_t pright = pM_end - 1 ; bool found ; GB_BINARY_SEARCH (i, Mi, pM, pright, found) ; if (found) cast_M (&mij, Mx +(pM*msize), 0) ; if (mij) GB_COPY_Z ; } } else { //-------------------------------------------------- // M(:,j) and Z(:,j) have about the same # entries //-------------------------------------------------- while (pM < pM_end && pZ < pZ_end) { int64_t iM = Mi [pM] ; int64_t i = Zi [pZ] ; if (iM < i) { // M(i,j) exists but not Z(i,j) pM++ ; } else if (i < iM) { // Z(i,j) exists but not M(i,j) pZ++ ; } else { // both M(i,j) and Z(i,j) exist bool mij ; cast_M (&mij, Mx +(pM*msize), 0) ; if (mij) GB_COPY_Z ; pM++ ; pZ++ ; } } } } else { //------------------------------------------------------ // complemented mask, and C(:,j) empty //------------------------------------------------------ for ( ; pZ < pZ_end ; pZ++) { int64_t i = Zi [pZ] ; bool mij = false ; // M(i,j) false if not present int64_t pright = pM_end - 1 ; bool found ; GB_BINARY_SEARCH (i, Mi, pM, pright, found) ; if (found) cast_M (&mij, Mx +(pM*msize), 0) ; if (!mij) GB_COPY_Z ; // mask is complemented } } } else if (zjnz == 0) { //---------------------------------------------------------- // Z(:,j) is empty //---------------------------------------------------------- if (Mask_comp) { //------------------------------------------------------ // mask is complemented //------------------------------------------------------ if (cjnz > 32 * mjnz) { //-------------------------------------------------- // C(:,j) is much denser than M(:,j) //-------------------------------------------------- for ( ; pM < pM_end ; pM++) { bool mij ; cast_M (&mij, Mx +(pM*msize), 0) ; if (mij) { int64_t i = Mi [pM] ; int64_t pright = pC_end - 1 ; bool found ; GB_BINARY_SEARCH (i, Ci, pC, pright, found); if (found) GB_COPY_C ; } } } else if (mjnz > 32 * cjnz) { //-------------------------------------------------- // M(:,j) is much denser than C(:,j) //-------------------------------------------------- for ( ; pC < pC_end ; pC++) { int64_t i = Ci [pC] ; bool mij = false ; int64_t pright = pM_end - 1 ; bool found ; GB_BINARY_SEARCH (i, Mi, pM, pright, found) ; if (found) cast_M (&mij, Mx +(pM*msize), 0) ; if (mij) GB_COPY_C ; } } else { //-------------------------------------------------- // M(:,j) and C(:,j) have about the same # entries //-------------------------------------------------- while (pM < pM_end && pC < pC_end) { int64_t iM = Mi [pM] ; int64_t i = Ci [pC] ; if (iM < i) { // M(i,j) exists but not C(i,j) pM++ ; } else if (i < iM) { // C(i,j) exists but not M(i,j) pC++ ; } else { // both M(i,j) and C(i,j) exist bool mij ; cast_M (&mij, Mx +(pM*msize), 0) ; if (mij) GB_COPY_C ; pM++ ; pC++ ; } } } } else { //------------------------------------------------------ // non-complemented mask, and Z(:,j) empty //------------------------------------------------------ for ( ; pC < pC_end ; pC++) { int64_t i = Ci [pC] ; bool mij = false ; // M(i,j) false if not present int64_t pright = pM_end - 1 ; bool found ; GB_BINARY_SEARCH (i, Mi, pM, pright, found) ; if (found) cast_M (&mij, Mx +(pM*msize), 0) ; if (!mij) GB_COPY_C ; } } } #if defined ( GB_PHASE_2_OF_2 ) ASSERT (pR == pR_end) ; #endif } //------------------------------------------------------------------ // final count of nnz (R(:,j)) //------------------------------------------------------------------ #if defined ( GB_PHASE_1_OF_2 ) if (fine_task) { TaskList [taskid].pC = rjnz ; } else { Rp [k] = rjnz ; } #endif } } }
3d7pt_var.c
/* * 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] = 32; tile_size[1] = 32; tile_size[2] = 4; tile_size[3] = 32; 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 #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] = coef[0][i][j][k] * A[t%2][i ][j ][k ] + coef[1][i][j][k] * A[t%2][i-1][j ][k ] + coef[2][i][j][k] * A[t%2][i ][j-1][k ] + coef[3][i][j][k] * A[t%2][i ][j ][k-1] + coef[4][i][j][k] * A[t%2][i+1][j ][k ] + coef[5][i][j][k] * A[t%2][i ][j+1][k ] + coef[6][i][j][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, "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; }
transform.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % TTTTT RRRR AAA N N SSSSS FFFFF OOO RRRR M M % % T R R A A NN N SS F O O R R MM MM % % T RRRR AAAAA N N N SSS FFF O O RRRR M M M % % T R R A A N NN SS F O O R R M M % % T R R A A N N SSSSS F OOO R R M M % % % % % % MagickCore Image Transform Methods % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2021 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/attribute.h" #include "MagickCore/cache.h" #include "MagickCore/cache-view.h" #include "MagickCore/color.h" #include "MagickCore/color-private.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/composite.h" #include "MagickCore/distort.h" #include "MagickCore/draw.h" #include "MagickCore/effect.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/geometry.h" #include "MagickCore/image.h" #include "MagickCore/memory_.h" #include "MagickCore/layer.h" #include "MagickCore/list.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/profile-private.h" #include "MagickCore/property.h" #include "MagickCore/resource_.h" #include "MagickCore/resize.h" #include "MagickCore/statistic.h" #include "MagickCore/string_.h" #include "MagickCore/thread-private.h" #include "MagickCore/transform.h" #include "MagickCore/transform-private.h" /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A u t o O r i e n t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AutoOrientImage() adjusts an image so that its orientation is suitable for % viewing (i.e. top-left orientation). % % The format of the AutoOrientImage method is: % % Image *AutoOrientImage(const Image *image, % const OrientationType orientation,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: The image. % % o orientation: Current image orientation. % % o exception: Return any errors or warnings in this structure. % */ MagickExport Image *AutoOrientImage(const Image *image, const OrientationType orientation,ExceptionInfo *exception) { Image *orient_image; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); orient_image=(Image *) NULL; switch(orientation) { case UndefinedOrientation: case TopLeftOrientation: default: { orient_image=CloneImage(image,0,0,MagickTrue,exception); break; } case TopRightOrientation: { orient_image=FlopImage(image,exception); break; } case BottomRightOrientation: { orient_image=RotateImage(image,180.0,exception); break; } case BottomLeftOrientation: { orient_image=FlipImage(image,exception); break; } case LeftTopOrientation: { orient_image=TransposeImage(image,exception); break; } case RightTopOrientation: { orient_image=RotateImage(image,90.0,exception); break; } case RightBottomOrientation: { orient_image=TransverseImage(image,exception); break; } case LeftBottomOrientation: { orient_image=RotateImage(image,270.0,exception); break; } } if (orient_image != (Image *) NULL) orient_image->orientation=TopLeftOrientation; return(orient_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C h o p I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ChopImage() removes a region of an image and collapses the image to occupy % the removed portion. % % The format of the ChopImage method is: % % Image *ChopImage(const Image *image,const RectangleInfo *chop_info) % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o chop_info: Define the region of the image to chop. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *ChopImage(const Image *image,const RectangleInfo *chop_info, ExceptionInfo *exception) { #define ChopImageTag "Chop/Image" CacheView *chop_view, *image_view; Image *chop_image; MagickBooleanType status; MagickOffsetType progress; RectangleInfo extent; ssize_t y; /* Check chop geometry. */ 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); assert(chop_info != (RectangleInfo *) NULL); if (((chop_info->x+(ssize_t) chop_info->width) < 0) || ((chop_info->y+(ssize_t) chop_info->height) < 0) || (chop_info->x > (ssize_t) image->columns) || (chop_info->y > (ssize_t) image->rows)) ThrowImageException(OptionWarning,"GeometryDoesNotContainImage"); extent=(*chop_info); if ((extent.x+(ssize_t) extent.width) > (ssize_t) image->columns) extent.width=(size_t) ((ssize_t) image->columns-extent.x); if ((extent.y+(ssize_t) extent.height) > (ssize_t) image->rows) extent.height=(size_t) ((ssize_t) image->rows-extent.y); if (extent.x < 0) { extent.width-=(size_t) (-extent.x); extent.x=0; } if (extent.y < 0) { extent.height-=(size_t) (-extent.y); extent.y=0; } chop_image=CloneImage(image,image->columns-extent.width,image->rows- extent.height,MagickTrue,exception); if (chop_image == (Image *) NULL) return((Image *) NULL); /* Extract chop image. */ status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); chop_view=AcquireAuthenticCacheView(chop_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,chop_image,extent.y,1) #endif for (y=0; y < (ssize_t) extent.y; y++) { const Quantum *magick_restrict p; ssize_t x; Quantum *magick_restrict q; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); q=QueueCacheViewAuthenticPixels(chop_view,0,y,chop_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 ((x < extent.x) || (x >= (ssize_t) (extent.x+extent.width))) { ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait chop_traits=GetPixelChannelTraits(chop_image,channel); if ((traits == UndefinedPixelTrait) || (chop_traits == UndefinedPixelTrait)) continue; SetPixelChannel(chop_image,channel,p[i],q); } q+=GetPixelChannels(chop_image); } p+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(chop_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,ChopImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } /* Extract chop image. */ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,chop_image,image->rows-(extent.y+extent.height),1) #endif for (y=0; y < (ssize_t) (image->rows-(extent.y+extent.height)); y++) { const Quantum *magick_restrict p; ssize_t x; Quantum *magick_restrict q; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,extent.y+extent.height+y, image->columns,1,exception); q=QueueCacheViewAuthenticPixels(chop_view,0,extent.y+y,chop_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 ((x < extent.x) || (x >= (ssize_t) (extent.x+extent.width))) { ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait chop_traits=GetPixelChannelTraits(chop_image,channel); if ((traits == UndefinedPixelTrait) || (chop_traits == UndefinedPixelTrait)) continue; SetPixelChannel(chop_image,channel,p[i],q); } q+=GetPixelChannels(chop_image); } p+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(chop_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,ChopImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } chop_view=DestroyCacheView(chop_view); image_view=DestroyCacheView(image_view); chop_image->type=image->type; if (status == MagickFalse) chop_image=DestroyImage(chop_image); return(chop_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C o n s o l i d a t e C M Y K I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ConsolidateCMYKImage() consolidates separate C, M, Y, and K planes into a % single image. % % The format of the ConsolidateCMYKImage method is: % % Image *ConsolidateCMYKImage(const Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image sequence. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *ConsolidateCMYKImages(const Image *images, ExceptionInfo *exception) { CacheView *cmyk_view, *image_view; Image *cmyk_image, *cmyk_images; ssize_t j; ssize_t y; /* Consolidate separate C, M, Y, and K planes into a single image. */ assert(images != (Image *) NULL); assert(images->signature == MagickCoreSignature); if (images->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); cmyk_images=NewImageList(); for (j=0; j < (ssize_t) GetImageListLength(images); j+=4) { ssize_t i; assert(images != (Image *) NULL); cmyk_image=CloneImage(images,0,0,MagickTrue, exception); if (cmyk_image == (Image *) NULL) break; if (SetImageStorageClass(cmyk_image,DirectClass,exception) == MagickFalse) break; (void) SetImageColorspace(cmyk_image,CMYKColorspace,exception); for (i=0; i < 4; i++) { image_view=AcquireVirtualCacheView(images,exception); cmyk_view=AcquireAuthenticCacheView(cmyk_image,exception); for (y=0; y < (ssize_t) images->rows; y++) { const Quantum *magick_restrict p; ssize_t x; Quantum *magick_restrict q; p=GetCacheViewVirtualPixels(image_view,0,y,images->columns,1,exception); q=QueueCacheViewAuthenticPixels(cmyk_view,0,y,cmyk_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) break; for (x=0; x < (ssize_t) images->columns; x++) { Quantum pixel; pixel=ClampToQuantum(QuantumRange-GetPixelIntensity(images,p)); switch (i) { case 0: SetPixelCyan(cmyk_image,pixel,q); break; case 1: SetPixelMagenta(cmyk_image,pixel,q); break; case 2: SetPixelYellow(cmyk_image,pixel,q); break; case 3: SetPixelBlack(cmyk_image,pixel,q); break; default: break; } p+=GetPixelChannels(images); q+=GetPixelChannels(cmyk_image); } if (SyncCacheViewAuthenticPixels(cmyk_view,exception) == MagickFalse) break; } cmyk_view=DestroyCacheView(cmyk_view); image_view=DestroyCacheView(image_view); images=GetNextImageInList(images); if (images == (Image *) NULL) break; } AppendImageToList(&cmyk_images,cmyk_image); } return(cmyk_images); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C r o p I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CropImage() extracts a region of the image starting at the offset defined % by geometry. Region must be fully defined, and no special handling of % geometry flags is performed. % % The format of the CropImage method is: % % Image *CropImage(const Image *image,const RectangleInfo *geometry, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o geometry: Define the region of the image to crop with members % x, y, width, and height. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *CropImage(const Image *image,const RectangleInfo *geometry, ExceptionInfo *exception) { #define CropImageTag "Crop/Image" CacheView *crop_view, *image_view; Image *crop_image; MagickBooleanType status; MagickOffsetType progress; OffsetInfo offset; RectangleInfo bounding_box, page; ssize_t y; /* Check crop geometry. */ assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(geometry != (const RectangleInfo *) NULL); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); bounding_box=image->page; if ((bounding_box.width == 0) || (bounding_box.height == 0)) { bounding_box.width=image->columns; bounding_box.height=image->rows; } page=(*geometry); if (page.width == 0) page.width=bounding_box.width; if (page.height == 0) page.height=bounding_box.height; if (((bounding_box.x-page.x) >= (ssize_t) page.width) || ((bounding_box.y-page.y) >= (ssize_t) page.height) || ((page.x-bounding_box.x) > (ssize_t) image->columns) || ((page.y-bounding_box.y) > (ssize_t) image->rows)) { /* Crop is not within virtual canvas, return 1 pixel transparent image. */ (void) ThrowMagickException(exception,GetMagickModule(),OptionWarning, "GeometryDoesNotContainImage","`%s'",image->filename); crop_image=CloneImage(image,1,1,MagickTrue,exception); if (crop_image == (Image *) NULL) return((Image *) NULL); crop_image->background_color.alpha_trait=BlendPixelTrait; crop_image->background_color.alpha=(MagickRealType) TransparentAlpha; (void) SetImageBackgroundColor(crop_image,exception); crop_image->page=bounding_box; crop_image->page.x=(-1); crop_image->page.y=(-1); if (crop_image->dispose == BackgroundDispose) crop_image->dispose=NoneDispose; return(crop_image); } if ((page.x < 0) && (bounding_box.x >= 0)) { page.width+=page.x-bounding_box.x; page.x=0; } else { page.width-=bounding_box.x-page.x; page.x-=bounding_box.x; if (page.x < 0) page.x=0; } if ((page.y < 0) && (bounding_box.y >= 0)) { page.height+=page.y-bounding_box.y; page.y=0; } else { page.height-=bounding_box.y-page.y; page.y-=bounding_box.y; if (page.y < 0) page.y=0; } if ((page.x+(ssize_t) page.width) > (ssize_t) image->columns) page.width=image->columns-page.x; if ((geometry->width != 0) && (page.width > geometry->width)) page.width=geometry->width; if ((page.y+(ssize_t) page.height) > (ssize_t) image->rows) page.height=image->rows-page.y; if ((geometry->height != 0) && (page.height > geometry->height)) page.height=geometry->height; bounding_box.x+=page.x; bounding_box.y+=page.y; if ((page.width == 0) || (page.height == 0)) { (void) ThrowMagickException(exception,GetMagickModule(),OptionWarning, "GeometryDoesNotContainImage","`%s'",image->filename); return((Image *) NULL); } /* Initialize crop image attributes. */ crop_image=CloneImage(image,page.width,page.height,MagickTrue,exception); if (crop_image == (Image *) NULL) return((Image *) NULL); crop_image->page.width=image->page.width; crop_image->page.height=image->page.height; offset.x=(ssize_t) (bounding_box.x+bounding_box.width); offset.y=(ssize_t) (bounding_box.y+bounding_box.height); if ((offset.x > (ssize_t) image->page.width) || (offset.y > (ssize_t) image->page.height)) { crop_image->page.width=bounding_box.width; crop_image->page.height=bounding_box.height; } crop_image->page.x=bounding_box.x; crop_image->page.y=bounding_box.y; /* Crop image. */ status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); crop_view=AcquireAuthenticCacheView(crop_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,crop_image,crop_image->rows,1) #endif for (y=0; y < (ssize_t) crop_image->rows; y++) { const Quantum *magick_restrict p; Quantum *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,page.x,page.y+y,crop_image->columns, 1,exception); q=QueueCacheViewAuthenticPixels(crop_view,0,y,crop_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) crop_image->columns; x++) { ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait crop_traits=GetPixelChannelTraits(crop_image,channel); if ((traits == UndefinedPixelTrait) || (crop_traits == UndefinedPixelTrait)) continue; SetPixelChannel(crop_image,channel,p[i],q); } p+=GetPixelChannels(image); q+=GetPixelChannels(crop_image); } if (SyncCacheViewAuthenticPixels(crop_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,CropImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } crop_view=DestroyCacheView(crop_view); image_view=DestroyCacheView(image_view); crop_image->type=image->type; if (status == MagickFalse) crop_image=DestroyImage(crop_image); return(crop_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C r o p I m a g e T o T i l e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CropImageToTiles() crops a single image, into a possible list of tiles. % This may include a single sub-region of the image. This basically applies % all the normal geometry flags for Crop. % % Image *CropImageToTiles(const Image *image, % const RectangleInfo *crop_geometry, ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image The transformed image is returned as this parameter. % % o crop_geometry: A crop geometry string. % % o exception: return any errors or warnings in this structure. % */ static inline ssize_t PixelRoundOffset(double x) { /* Round the fraction to nearest integer. */ if ((x-floor(x)) < (ceil(x)-x)) return(CastDoubleToLong(floor(x))); return(CastDoubleToLong(ceil(x))); } MagickExport Image *CropImageToTiles(const Image *image, const char *crop_geometry,ExceptionInfo *exception) { Image *next, *crop_image; MagickStatusType flags; RectangleInfo geometry; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); crop_image=NewImageList(); next=NewImageList(); flags=ParseGravityGeometry(image,crop_geometry,&geometry,exception); if ((flags & AreaValue) != 0) { PointInfo delta, offset; RectangleInfo crop; size_t height, width; /* Crop into NxM tiles (@ flag). */ width=image->columns; height=image->rows; if (geometry.width == 0) geometry.width=1; if (geometry.height == 0) geometry.height=1; if ((flags & AspectValue) == 0) { width-=(geometry.x < 0 ? -1 : 1)*geometry.x; height-=(geometry.y < 0 ? -1 : 1)*geometry.y; } else { width+=(geometry.x < 0 ? -1 : 1)*geometry.x; height+=(geometry.y < 0 ? -1 : 1)*geometry.y; } delta.x=(double) width/geometry.width; delta.y=(double) height/geometry.height; if (delta.x < 1.0) delta.x=1.0; if (delta.y < 1.0) delta.y=1.0; for (offset.y=0; offset.y < (double) height; ) { if ((flags & AspectValue) == 0) { crop.y=PixelRoundOffset((double) (offset.y- (geometry.y > 0 ? 0 : geometry.y))); offset.y+=delta.y; /* increment now to find width */ crop.height=(size_t) PixelRoundOffset((double) (offset.y+ (geometry.y < 0 ? 0 : geometry.y))); } else { crop.y=PixelRoundOffset((double) (offset.y- (geometry.y > 0 ? geometry.y : 0))); offset.y+=delta.y; /* increment now to find width */ crop.height=(size_t) PixelRoundOffset((double) (offset.y+(geometry.y < -1 ? geometry.y : 0))); } crop.height-=crop.y; crop.y+=image->page.y; for (offset.x=0; offset.x < (double) width; ) { if ((flags & AspectValue) == 0) { crop.x=PixelRoundOffset((double) (offset.x- (geometry.x > 0 ? 0 : geometry.x))); offset.x+=delta.x; /* increment now to find height */ crop.width=(size_t) PixelRoundOffset((double) (offset.x+ (geometry.x < 0 ? 0 : geometry.x))); } else { crop.x=PixelRoundOffset((double) (offset.x- (geometry.x > 0 ? geometry.x : 0))); offset.x+=delta.x; /* increment now to find height */ crop.width=(size_t) PixelRoundOffset((double) (offset.x+ (geometry.x < 0 ? geometry.x : 0))); } crop.width-=crop.x; crop.x+=image->page.x; next=CropImage(image,&crop,exception); if (next != (Image *) NULL) AppendImageToList(&crop_image,next); } } ClearMagickException(exception); return(crop_image); } if (((geometry.width == 0) && (geometry.height == 0)) || ((flags & XValue) != 0) || ((flags & YValue) != 0)) { /* Crop a single region at +X+Y. */ crop_image=CropImage(image,&geometry,exception); if ((crop_image != (Image *) NULL) && ((flags & AspectValue) != 0)) { crop_image->page.width=geometry.width; crop_image->page.height=geometry.height; crop_image->page.x-=geometry.x; crop_image->page.y-=geometry.y; } return(crop_image); } if ((image->columns > geometry.width) || (image->rows > geometry.height)) { RectangleInfo page; size_t height, width; ssize_t x, y; /* Crop into tiles of fixed size WxH. */ page=image->page; if (page.width == 0) page.width=image->columns; if (page.height == 0) page.height=image->rows; width=geometry.width; if (width == 0) width=page.width; height=geometry.height; if (height == 0) height=page.height; next=NewImageList(); for (y=0; y < (ssize_t) page.height; y+=(ssize_t) height) { for (x=0; x < (ssize_t) page.width; x+=(ssize_t) width) { geometry.width=width; geometry.height=height; geometry.x=x; geometry.y=y; next=CropImage(image,&geometry,exception); if (next == (Image *) NULL) break; AppendImageToList(&crop_image,next); } if (next == (Image *) NULL) break; } return(crop_image); } return(CloneImage(image,0,0,MagickTrue,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % E x c e r p t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ExcerptImage() returns a excerpt of the image as defined by the geometry. % % The format of the ExcerptImage method is: % % Image *ExcerptImage(const Image *image,const RectangleInfo *geometry, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o geometry: Define the region of the image to extend with members % x, y, width, and height. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *ExcerptImage(const Image *image, const RectangleInfo *geometry,ExceptionInfo *exception) { #define ExcerptImageTag "Excerpt/Image" CacheView *excerpt_view, *image_view; Image *excerpt_image; MagickBooleanType status; MagickOffsetType progress; ssize_t y; /* Allocate excerpt image. */ assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(geometry != (const RectangleInfo *) NULL); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); excerpt_image=CloneImage(image,geometry->width,geometry->height,MagickTrue, exception); if (excerpt_image == (Image *) NULL) return((Image *) NULL); /* Excerpt each row. */ status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); excerpt_view=AcquireAuthenticCacheView(excerpt_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,excerpt_image,excerpt_image->rows,1) #endif for (y=0; y < (ssize_t) excerpt_image->rows; y++) { const Quantum *magick_restrict p; Quantum *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,geometry->x,geometry->y+y, geometry->width,1,exception); q=GetCacheViewAuthenticPixels(excerpt_view,0,y,excerpt_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) excerpt_image->columns; x++) { ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait excerpt_traits=GetPixelChannelTraits(excerpt_image,channel); if ((traits == UndefinedPixelTrait) || (excerpt_traits == UndefinedPixelTrait)) continue; SetPixelChannel(excerpt_image,channel,p[i],q); } p+=GetPixelChannels(image); q+=GetPixelChannels(excerpt_image); } if (SyncCacheViewAuthenticPixels(excerpt_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,ExcerptImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } excerpt_view=DestroyCacheView(excerpt_view); image_view=DestroyCacheView(image_view); excerpt_image->type=image->type; if (status == MagickFalse) excerpt_image=DestroyImage(excerpt_image); return(excerpt_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % E x t e n t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ExtentImage() extends the image as defined by the geometry, gravity, and % image background color. Set the (x,y) offset of the geometry to move the % original image relative to the extended image. % % The format of the ExtentImage method is: % % Image *ExtentImage(const Image *image,const RectangleInfo *geometry, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o geometry: Define the region of the image to extend with members % x, y, width, and height. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *ExtentImage(const Image *image, const RectangleInfo *geometry,ExceptionInfo *exception) { Image *extent_image; MagickBooleanType status; /* Allocate extent image. */ assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(geometry != (const RectangleInfo *) NULL); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); extent_image=CloneImage(image,geometry->width,geometry->height,MagickTrue, exception); if (extent_image == (Image *) NULL) return((Image *) NULL); status=SetImageBackgroundColor(extent_image,exception); if (status == MagickFalse) { extent_image=DestroyImage(extent_image); return((Image *) NULL); } status=CompositeImage(extent_image,image,image->compose,MagickTrue, -geometry->x,-geometry->y,exception); if (status != MagickFalse) Update8BIMClipPath(extent_image,image->columns,image->rows,geometry); return(extent_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % F l i p I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FlipImage() creates a vertical mirror image by reflecting the pixels % around the central x-axis. % % The format of the FlipImage method is: % % Image *FlipImage(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 *FlipImage(const Image *image,ExceptionInfo *exception) { #define FlipImageTag "Flip/Image" CacheView *flip_view, *image_view; Image *flip_image; MagickBooleanType status; MagickOffsetType progress; RectangleInfo page; ssize_t y; 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); flip_image=CloneImage(image,0,0,MagickTrue,exception); if (flip_image == (Image *) NULL) return((Image *) NULL); /* Flip image. */ status=MagickTrue; progress=0; page=image->page; image_view=AcquireVirtualCacheView(image,exception); flip_view=AcquireAuthenticCacheView(flip_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,flip_image,flip_image->rows,1) #endif for (y=0; y < (ssize_t) flip_image->rows; y++) { const Quantum *magick_restrict p; Quantum *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); q=QueueCacheViewAuthenticPixels(flip_view,0,(ssize_t) (flip_image->rows-y- 1),flip_image->columns,1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) flip_image->columns; x++) { ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait flip_traits=GetPixelChannelTraits(flip_image,channel); if ((traits == UndefinedPixelTrait) || (flip_traits == UndefinedPixelTrait)) continue; SetPixelChannel(flip_image,channel,p[i],q); } p+=GetPixelChannels(image); q+=GetPixelChannels(flip_image); } if (SyncCacheViewAuthenticPixels(flip_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,FlipImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } flip_view=DestroyCacheView(flip_view); image_view=DestroyCacheView(image_view); flip_image->type=image->type; if (page.height != 0) page.y=(ssize_t) (page.height-flip_image->rows-page.y); flip_image->page=page; if (status == MagickFalse) flip_image=DestroyImage(flip_image); return(flip_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % F l o p I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FlopImage() creates a horizontal mirror image by reflecting the pixels % around the central y-axis. % % The format of the FlopImage method is: % % Image *FlopImage(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 *FlopImage(const Image *image,ExceptionInfo *exception) { #define FlopImageTag "Flop/Image" CacheView *flop_view, *image_view; Image *flop_image; MagickBooleanType status; MagickOffsetType progress; RectangleInfo page; ssize_t y; 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); flop_image=CloneImage(image,0,0,MagickTrue,exception); if (flop_image == (Image *) NULL) return((Image *) NULL); /* Flop each row. */ status=MagickTrue; progress=0; page=image->page; image_view=AcquireVirtualCacheView(image,exception); flop_view=AcquireAuthenticCacheView(flop_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,flop_image,flop_image->rows,1) #endif for (y=0; y < (ssize_t) flop_image->rows; y++) { const Quantum *magick_restrict p; ssize_t x; Quantum *magick_restrict q; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); q=QueueCacheViewAuthenticPixels(flop_view,0,y,flop_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } q+=GetPixelChannels(flop_image)*flop_image->columns; for (x=0; x < (ssize_t) flop_image->columns; x++) { ssize_t i; q-=GetPixelChannels(flop_image); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait flop_traits=GetPixelChannelTraits(flop_image,channel); if ((traits == UndefinedPixelTrait) || (flop_traits == UndefinedPixelTrait)) continue; SetPixelChannel(flop_image,channel,p[i],q); } p+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(flop_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,FlopImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } flop_view=DestroyCacheView(flop_view); image_view=DestroyCacheView(image_view); flop_image->type=image->type; if (page.width != 0) page.x=(ssize_t) (page.width-flop_image->columns-page.x); flop_image->page=page; if (status == MagickFalse) flop_image=DestroyImage(flop_image); return(flop_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R o l l I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RollImage() offsets an image as defined by x_offset and y_offset. % % The format of the RollImage method is: % % Image *RollImage(const Image *image,const ssize_t x_offset, % const ssize_t y_offset,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x_offset: the number of columns to roll in the horizontal direction. % % o y_offset: the number of rows to roll in the vertical direction. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType CopyImageRegion(Image *destination,const Image *source, const size_t columns,const size_t rows,const ssize_t sx,const ssize_t sy, const ssize_t dx,const ssize_t dy,ExceptionInfo *exception) { CacheView *source_view, *destination_view; MagickBooleanType status; ssize_t y; if (columns == 0) return(MagickTrue); status=MagickTrue; source_view=AcquireVirtualCacheView(source,exception); destination_view=AcquireAuthenticCacheView(destination,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(source,destination,rows,1) #endif for (y=0; y < (ssize_t) rows; y++) { MagickBooleanType sync; const Quantum *magick_restrict p; Quantum *magick_restrict q; ssize_t x; /* Transfer scanline. */ if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(source_view,sx,sy+y,columns,1,exception); q=GetCacheViewAuthenticPixels(destination_view,dx,dy+y,columns,1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) columns; x++) { ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(source); i++) { PixelChannel channel = GetPixelChannelChannel(source,i); PixelTrait source_traits=GetPixelChannelTraits(source,channel); PixelTrait destination_traits=GetPixelChannelTraits(destination, channel); if ((source_traits == UndefinedPixelTrait) || (destination_traits == UndefinedPixelTrait)) continue; SetPixelChannel(destination,channel,p[i],q); } p+=GetPixelChannels(source); q+=GetPixelChannels(destination); } sync=SyncCacheViewAuthenticPixels(destination_view,exception); if (sync == MagickFalse) status=MagickFalse; } destination_view=DestroyCacheView(destination_view); source_view=DestroyCacheView(source_view); return(status); } MagickExport Image *RollImage(const Image *image,const ssize_t x_offset, const ssize_t y_offset,ExceptionInfo *exception) { #define RollImageTag "Roll/Image" Image *roll_image; MagickStatusType status; RectangleInfo offset; /* Initialize roll image attributes. */ 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); roll_image=CloneImage(image,0,0,MagickTrue,exception); if (roll_image == (Image *) NULL) return((Image *) NULL); offset.x=x_offset; offset.y=y_offset; while (offset.x < 0) offset.x+=(ssize_t) image->columns; while (offset.x >= (ssize_t) image->columns) offset.x-=(ssize_t) image->columns; while (offset.y < 0) offset.y+=(ssize_t) image->rows; while (offset.y >= (ssize_t) image->rows) offset.y-=(ssize_t) image->rows; /* Roll image. */ status=CopyImageRegion(roll_image,image,(size_t) offset.x, (size_t) offset.y,(ssize_t) image->columns-offset.x,(ssize_t) image->rows- offset.y,0,0,exception); (void) SetImageProgress(image,RollImageTag,0,3); status&=CopyImageRegion(roll_image,image,image->columns-offset.x, (size_t) offset.y,0,(ssize_t) image->rows-offset.y,offset.x,0, exception); (void) SetImageProgress(image,RollImageTag,1,3); status&=CopyImageRegion(roll_image,image,(size_t) offset.x,image->rows- offset.y,(ssize_t) image->columns-offset.x,0,0,offset.y,exception); (void) SetImageProgress(image,RollImageTag,2,3); status&=CopyImageRegion(roll_image,image,image->columns-offset.x,image->rows- offset.y,0,0,offset.x,offset.y,exception); (void) SetImageProgress(image,RollImageTag,3,3); roll_image->type=image->type; if (status == MagickFalse) roll_image=DestroyImage(roll_image); return(roll_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S h a v e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ShaveImage() shaves pixels from the image edges. It allocates the memory % necessary for the new Image structure and returns a pointer to the new % image. % % The format of the ShaveImage method is: % % Image *ShaveImage(const Image *image,const RectangleInfo *shave_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o shave_image: Method ShaveImage returns a pointer to the shaved % image. A null image is returned if there is a memory shortage or % if the image width or height is zero. % % o image: the image. % % o shave_info: Specifies a pointer to a RectangleInfo which defines the % region of the image to crop. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *ShaveImage(const Image *image, const RectangleInfo *shave_info,ExceptionInfo *exception) { Image *shave_image; RectangleInfo geometry; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (((2*shave_info->width) >= image->columns) || ((2*shave_info->height) >= image->rows)) ThrowImageException(OptionWarning,"GeometryDoesNotContainImage"); SetGeometry(image,&geometry); geometry.width-=2*shave_info->width; geometry.height-=2*shave_info->height; geometry.x=(ssize_t) shave_info->width+image->page.x; geometry.y=(ssize_t) shave_info->height+image->page.y; shave_image=CropImage(image,&geometry,exception); if (shave_image == (Image *) NULL) return((Image *) NULL); shave_image->page.width-=2*shave_info->width; shave_image->page.height-=2*shave_info->height; shave_image->page.x-=(ssize_t) shave_info->width; shave_image->page.y-=(ssize_t) shave_info->height; return(shave_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S p l i c e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SpliceImage() splices a solid color into the image as defined by the % geometry. % % The format of the SpliceImage method is: % % Image *SpliceImage(const Image *image,const RectangleInfo *geometry, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o geometry: Define the region of the image to splice with members % x, y, width, and height. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *SpliceImage(const Image *image, const RectangleInfo *geometry,ExceptionInfo *exception) { #define SpliceImageTag "Splice/Image" CacheView *image_view, *splice_view; Image *splice_image; MagickBooleanType status; MagickOffsetType progress; RectangleInfo splice_geometry; ssize_t columns, y; /* Allocate splice image. */ assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(geometry != (const RectangleInfo *) NULL); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); splice_geometry=(*geometry); splice_image=CloneImage(image,image->columns+splice_geometry.width, image->rows+splice_geometry.height,MagickTrue,exception); if (splice_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(splice_image,DirectClass,exception) == MagickFalse) { splice_image=DestroyImage(splice_image); return((Image *) NULL); } if ((IsPixelInfoGray(&splice_image->background_color) == MagickFalse) && (IsGrayColorspace(splice_image->colorspace) != MagickFalse)) (void) SetImageColorspace(splice_image,sRGBColorspace,exception); if ((splice_image->background_color.alpha_trait != UndefinedPixelTrait) && (splice_image->alpha_trait == UndefinedPixelTrait)) (void) SetImageAlpha(splice_image,OpaqueAlpha,exception); (void) SetImageBackgroundColor(splice_image,exception); /* Respect image geometry. */ switch (image->gravity) { default: case UndefinedGravity: case NorthWestGravity: break; case NorthGravity: { splice_geometry.x+=(ssize_t) splice_geometry.width/2; break; } case NorthEastGravity: { splice_geometry.x+=(ssize_t) splice_geometry.width; break; } case WestGravity: { splice_geometry.y+=(ssize_t) splice_geometry.width/2; break; } case CenterGravity: { splice_geometry.x+=(ssize_t) splice_geometry.width/2; splice_geometry.y+=(ssize_t) splice_geometry.height/2; break; } case EastGravity: { splice_geometry.x+=(ssize_t) splice_geometry.width; splice_geometry.y+=(ssize_t) splice_geometry.height/2; break; } case SouthWestGravity: { splice_geometry.y+=(ssize_t) splice_geometry.height; break; } case SouthGravity: { splice_geometry.x+=(ssize_t) splice_geometry.width/2; splice_geometry.y+=(ssize_t) splice_geometry.height; break; } case SouthEastGravity: { splice_geometry.x+=(ssize_t) splice_geometry.width; splice_geometry.y+=(ssize_t) splice_geometry.height; break; } } /* Splice image. */ status=MagickTrue; progress=0; columns=MagickMin(splice_geometry.x,(ssize_t) splice_image->columns); image_view=AcquireVirtualCacheView(image,exception); splice_view=AcquireAuthenticCacheView(splice_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,splice_image,splice_geometry.y,1) #endif for (y=0; y < (ssize_t) splice_geometry.y; y++) { const Quantum *magick_restrict p; ssize_t x; Quantum *magick_restrict q; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,splice_image->columns,1, exception); q=QueueCacheViewAuthenticPixels(splice_view,0,y,splice_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < columns; x++) { ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait splice_traits=GetPixelChannelTraits(splice_image,channel); if ((traits == UndefinedPixelTrait) || (splice_traits == UndefinedPixelTrait)) continue; SetPixelChannel(splice_image,channel,p[i],q); } SetPixelRed(splice_image,GetPixelRed(image,p),q); SetPixelGreen(splice_image,GetPixelGreen(image,p),q); SetPixelBlue(splice_image,GetPixelBlue(image,p),q); SetPixelAlpha(splice_image,GetPixelAlpha(image,p),q); p+=GetPixelChannels(image); q+=GetPixelChannels(splice_image); } for ( ; x < (ssize_t) (splice_geometry.x+splice_geometry.width); x++) q+=GetPixelChannels(splice_image); for ( ; x < (ssize_t) splice_image->columns; x++) { ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait splice_traits=GetPixelChannelTraits(splice_image,channel); if ((traits == UndefinedPixelTrait) || (splice_traits == UndefinedPixelTrait)) continue; SetPixelChannel(splice_image,channel,p[i],q); } SetPixelRed(splice_image,GetPixelRed(image,p),q); SetPixelGreen(splice_image,GetPixelGreen(image,p),q); SetPixelBlue(splice_image,GetPixelBlue(image,p),q); SetPixelAlpha(splice_image,GetPixelAlpha(image,p),q); p+=GetPixelChannels(image); q+=GetPixelChannels(splice_image); } if (SyncCacheViewAuthenticPixels(splice_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,SpliceImageTag,progress, splice_image->rows); if (proceed == MagickFalse) status=MagickFalse; } } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,splice_image,splice_image->rows,2) #endif for (y=(ssize_t) (splice_geometry.y+splice_geometry.height); y < (ssize_t) splice_image->rows; y++) { const Quantum *magick_restrict p; ssize_t x; Quantum *magick_restrict q; if (status == MagickFalse) continue; if ((y < 0) || (y >= (ssize_t)splice_image->rows)) continue; p=GetCacheViewVirtualPixels(image_view,0,y-(ssize_t) splice_geometry.height, splice_image->columns,1,exception); q=QueueCacheViewAuthenticPixels(splice_view,0,y,splice_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < columns; x++) { ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait splice_traits=GetPixelChannelTraits(splice_image,channel); if ((traits == UndefinedPixelTrait) || (splice_traits == UndefinedPixelTrait)) continue; SetPixelChannel(splice_image,channel,p[i],q); } SetPixelRed(splice_image,GetPixelRed(image,p),q); SetPixelGreen(splice_image,GetPixelGreen(image,p),q); SetPixelBlue(splice_image,GetPixelBlue(image,p),q); SetPixelAlpha(splice_image,GetPixelAlpha(image,p),q); p+=GetPixelChannels(image); q+=GetPixelChannels(splice_image); } for ( ; x < (ssize_t) (splice_geometry.x+splice_geometry.width); x++) q+=GetPixelChannels(splice_image); for ( ; x < (ssize_t) splice_image->columns; x++) { ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait splice_traits=GetPixelChannelTraits(splice_image,channel); if ((traits == UndefinedPixelTrait) || (splice_traits == UndefinedPixelTrait)) continue; SetPixelChannel(splice_image,channel,p[i],q); } SetPixelRed(splice_image,GetPixelRed(image,p),q); SetPixelGreen(splice_image,GetPixelGreen(image,p),q); SetPixelBlue(splice_image,GetPixelBlue(image,p),q); SetPixelAlpha(splice_image,GetPixelAlpha(image,p),q); p+=GetPixelChannels(image); q+=GetPixelChannels(splice_image); } if (SyncCacheViewAuthenticPixels(splice_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,SpliceImageTag,progress, splice_image->rows); if (proceed == MagickFalse) status=MagickFalse; } } splice_view=DestroyCacheView(splice_view); image_view=DestroyCacheView(image_view); if (status == MagickFalse) splice_image=DestroyImage(splice_image); return(splice_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % T r a n s f o r m I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % TransformImage() is a convenience method that behaves like ResizeImage() or % CropImage() but accepts scaling and/or cropping information as a region % geometry specification. If the operation fails, the original image handle % is left as is. % % This should only be used for single images. % % This function destroys what it assumes to be a single image list. % If the input image is part of a larger list, all other images in that list % will be simply 'lost', not destroyed. % % Also if the crop generates a list of images only the first image is resized. % And finally if the crop succeeds and the resize failed, you will get a % cropped image, as well as a 'false' or 'failed' report. % % This function and should probably be deprecated in favor of direct calls % to CropImageToTiles() or ResizeImage(), as appropriate. % % The format of the TransformImage method is: % % MagickBooleanType TransformImage(Image **image,const char *crop_geometry, % const char *image_geometry,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image The transformed image is returned as this parameter. % % o crop_geometry: A crop geometry string. This geometry defines a % subregion of the image to crop. % % o image_geometry: An image geometry string. This geometry defines the % final size of the image. % % o exception: return any errors or warnings in this structure. % */ MagickPrivate MagickBooleanType TransformImage(Image **image, const char *crop_geometry,const char *image_geometry,ExceptionInfo *exception) { Image *resize_image, *transform_image; RectangleInfo geometry; assert(image != (Image **) NULL); assert((*image)->signature == MagickCoreSignature); if ((*image)->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",(*image)->filename); transform_image=(*image); if (crop_geometry != (const char *) NULL) { Image *crop_image; /* Crop image to a user specified size. */ crop_image=CropImageToTiles(*image,crop_geometry,exception); if (crop_image == (Image *) NULL) transform_image=CloneImage(*image,0,0,MagickTrue,exception); else { transform_image=DestroyImage(transform_image); transform_image=GetFirstImageInList(crop_image); } *image=transform_image; } if (image_geometry == (const char *) NULL) return(MagickTrue); /* Scale image to a user specified size. */ (void) ParseRegionGeometry(transform_image,image_geometry,&geometry, exception); if ((transform_image->columns == geometry.width) && (transform_image->rows == geometry.height)) return(MagickTrue); resize_image=ResizeImage(transform_image,geometry.width,geometry.height, transform_image->filter,exception); if (resize_image == (Image *) NULL) return(MagickFalse); transform_image=DestroyImage(transform_image); transform_image=resize_image; *image=transform_image; return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % T r a n s p o s e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % TransposeImage() creates a horizontal mirror image by reflecting the pixels % around the central y-axis while rotating them by 90 degrees. % % The format of the TransposeImage method is: % % Image *TransposeImage(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 *TransposeImage(const Image *image,ExceptionInfo *exception) { #define TransposeImageTag "Transpose/Image" CacheView *image_view, *transpose_view; Image *transpose_image; MagickBooleanType status; MagickOffsetType progress; RectangleInfo page; ssize_t y; 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); transpose_image=CloneImage(image,image->rows,image->columns,MagickTrue, exception); if (transpose_image == (Image *) NULL) return((Image *) NULL); /* Transpose image. */ status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); transpose_view=AcquireAuthenticCacheView(transpose_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,transpose_image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { const Quantum *magick_restrict p; Quantum *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,(ssize_t) image->rows-y-1, image->columns,1,exception); q=QueueCacheViewAuthenticPixels(transpose_view,(ssize_t) (image->rows-y-1), 0,1,transpose_image->rows,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait transpose_traits=GetPixelChannelTraits(transpose_image, channel); if ((traits == UndefinedPixelTrait) || (transpose_traits == UndefinedPixelTrait)) continue; SetPixelChannel(transpose_image,channel,p[i],q); } p+=GetPixelChannels(image); q+=GetPixelChannels(transpose_image); } if (SyncCacheViewAuthenticPixels(transpose_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,TransposeImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } transpose_view=DestroyCacheView(transpose_view); image_view=DestroyCacheView(image_view); transpose_image->type=image->type; page=transpose_image->page; Swap(page.width,page.height); Swap(page.x,page.y); transpose_image->page=page; if (status == MagickFalse) transpose_image=DestroyImage(transpose_image); return(transpose_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % T r a n s v e r s e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % TransverseImage() creates a vertical mirror image by reflecting the pixels % around the central x-axis while rotating them by 270 degrees. % % The format of the TransverseImage method is: % % Image *TransverseImage(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 *TransverseImage(const Image *image,ExceptionInfo *exception) { #define TransverseImageTag "Transverse/Image" CacheView *image_view, *transverse_view; Image *transverse_image; MagickBooleanType status; MagickOffsetType progress; RectangleInfo page; ssize_t y; 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); transverse_image=CloneImage(image,image->rows,image->columns,MagickTrue, exception); if (transverse_image == (Image *) NULL) return((Image *) NULL); /* Transverse image. */ status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); transverse_view=AcquireAuthenticCacheView(transverse_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,transverse_image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { MagickBooleanType sync; const Quantum *magick_restrict p; Quantum *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); q=QueueCacheViewAuthenticPixels(transverse_view,(ssize_t) (image->rows-y-1), 0,1,transverse_image->rows,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } q+=GetPixelChannels(transverse_image)*image->columns; for (x=0; x < (ssize_t) image->columns; x++) { ssize_t i; q-=GetPixelChannels(transverse_image); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait transverse_traits=GetPixelChannelTraits(transverse_image, channel); if ((traits == UndefinedPixelTrait) || (transverse_traits == UndefinedPixelTrait)) continue; SetPixelChannel(transverse_image,channel,p[i],q); } p+=GetPixelChannels(image); } sync=SyncCacheViewAuthenticPixels(transverse_view,exception); if (sync == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,TransverseImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } transverse_view=DestroyCacheView(transverse_view); image_view=DestroyCacheView(image_view); transverse_image->type=image->type; page=transverse_image->page; Swap(page.width,page.height); Swap(page.x,page.y); if (page.width != 0) page.x=(ssize_t) (page.width-transverse_image->columns-page.x); if (page.height != 0) page.y=(ssize_t) (page.height-transverse_image->rows-page.y); transverse_image->page=page; if (status == MagickFalse) transverse_image=DestroyImage(transverse_image); return(transverse_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % T r i m I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % TrimImage() trims pixels from the image edges. It allocates the memory % necessary for the new Image structure and returns a pointer to the new % image. % % The format of the TrimImage method is: % % Image *TrimImage(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 *TrimImage(const Image *image,ExceptionInfo *exception) { Image *trim_image; RectangleInfo geometry; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); geometry=GetImageBoundingBox(image,exception); if ((geometry.width == 0) || (geometry.height == 0)) { Image *crop_image; crop_image=CloneImage(image,1,1,MagickTrue,exception); if (crop_image == (Image *) NULL) return((Image *) NULL); crop_image->background_color.alpha_trait=BlendPixelTrait; crop_image->background_color.alpha=(MagickRealType) TransparentAlpha; (void) SetImageBackgroundColor(crop_image,exception); crop_image->page=image->page; crop_image->page.x=(-1); crop_image->page.y=(-1); return(crop_image); } geometry.x+=image->page.x; geometry.y+=image->page.y; trim_image=CropImage(image,&geometry,exception); if (trim_image != (Image *) NULL) Update8BIMClipPath(trim_image,image->columns,image->rows,&geometry); return(trim_image); }
gdal_sam_eta.c
#include<stdio.h> #include<omp.h> #include<math.h> #include "gdal.h" #include "sam_eta.h" #include "libcrop.h" void usage() { printf( "-----------------------------------------\n"); printf( "--Modis Processing chain--OpenMP code----\n"); printf( "-----------------------------------------\n"); printf( "./sam_eta inLULC inCropAge inRnet inG0\n"); printf( "\tinLST inAlbedo inNDVI inSUNZA inTime\n printf( "\tinEmissivity inETPOT\n"); printf( "\toutSam_evapfr outSam_eta\n"); printf( "---Following inputs from meteorological station----\n"); printf( "\twind_speed wind_height\n"); printf( "\ttemperature temperature_height\n"); printf( "\tatmospheric_pressure\n"); printf( "-----------------------------------------\n"); return; } int main( int argc, char *argv[] ) { if( argc < 19 ) { usage(); return 1; } char *inB1 = argv[1]; //LULC char *inB2 = argv[2]; //CropAge char *inB3 = argv[3]; //Rnet char *inB4 = argv[4]; //G0 char *inB5 = argv[5]; //LST char *inB6 = argv[6]; //Albedo char *inB7 = argv[7]; //NDVI char *inB8 = argv[8]; //SUNZA char *inB9 = argv[9]; //Time char *inB10 = argv[10]; //Emissivity char *inB11 = argv[11]; //DEM char *inB12 = argv[12]; //ETPOT char *sam_evapfrF = argv[13]; char *sam_etaF = argv[14]; float wind_speed = argv[15]; float wind_height = argv[16]; float temperature = argv[17]; float temperature_height= argv[18]; float atmo_pressure = argv[19]; //NDVI boundaries where lAI=0 or LAI=max //from temporal statistics around crop season float ndvimin=0.1; float ndvimax=0.9; GDALAllRegister(); GDALDatasetH hD1 = GDALOpen(inB1,GA_ReadOnly);//LULC GDALDatasetH hD2 = GDALOpen(inB2,GA_ReadOnly);//CropAge GDALDatasetH hD3 = GDALOpen(inB3,GA_ReadOnly);//Rnet GDALDatasetH hD4 = GDALOpen(inB4,GA_ReadOnly);//G0 GDALDatasetH hD5 = GDALOpen(inB5,GA_ReadOnly);//LST GDALDatasetH hD6 = GDALOpen(inB6,GA_ReadOnly);//Albedo GDALDatasetH hD7 = GDALOpen(inB7,GA_ReadOnly);//NDVI GDALDatasetH hD8 = GDALOpen(inB8,GA_ReadOnly);//SUNZA GDALDatasetH hD9 = GDALOpen(inB9,GA_ReadOnly);//Time GDALDatasetH hD10 = GDALOpen(inB10,GA_ReadOnly);//Emissivity GDALDatasetH hD11 = GDALOpen(inB11,GA_ReadOnly);//DEM GDALDatasetH hD12 = GDALOpen(inB12,GA_ReadOnly);//ETPOT if(hD1==NULL||hD2==NULL||hD3==NULL||hD4==NULL ||hD5==NULL||hD6==NULL||hD7==NULL||hD8==NULL ||hD9==NULL||hD10==NULL||hD11==NULL||hD12==NULL){ printf("One or more input files "); printf("could not be loaded\n"); exit(1); } GDALDriverH hDr3 = GDALGetDatasetDriver(hD3); char **options = NULL; options = CSLSetNameValue( options, "TILED", "YES" ); options = CSLSetNameValue( options, "COMPRESS", "DEFLATE" ); options = CSLSetNameValue( options, "PREDICTOR", "2" ); //Evapfr out GDALDatasetH hDOut0 = GDALCreateCopy( hDr3, sam_evapfrF,hD3,FALSE,options,NULL,NULL); GDALRasterBandH hBOut0 = GDALGetRasterBand(hDOut0,1); //ETa out GDALDatasetH hDOut = GDALCreateCopy( hDr3, sam_etaF,hD3,FALSE,options,NULL,NULL); GDALRasterBandH hBOut = GDALGetRasterBand(hDOut,1); //Load bands GDALRasterBandH hB1 = GDALGetRasterBand(hD1,1);//LULC GDALRasterBandH hB2 = GDALGetRasterBand(hD2,1);//CropAge GDALRasterBandH hB3 = GDALGetRasterBand(hD3,1);//Rnet GDALRasterBandH hB4 = GDALGetRasterBand(hD4,1);//G0 GDALRasterBandH hB5 = GDALGetRasterBand(hD5,1);//LST GDALRasterBandH hB6 = GDALGetRasterBand(hD6,1);//Albedo GDALRasterBandH hB7 = GDALGetRasterBand(hD7,1);//NDVI GDALRasterBandH hB8 = GDALGetRasterBand(hD8,1);//SUNZA GDALRasterBandH hB9 = GDALGetRasterBand(hD9,1);//Time GDALRasterBandH hB10 = GDALGetRasterBand(hD10,1);//Emissivity GDALRasterBandH hB11 = GDALGetRasterBand(hD11,1);//DEM GDALRasterBandH hB12 = GDALGetRasterBand(hD12,1);//ETPOT int nX = GDALGetRasterBandXSize(hB1); int nY = GDALGetRasterBandYSize(hB1); int N = nX*nY; int rowcol; float *mat1 = (float *) malloc(sizeof(float)*N); float *mat2 = (float *) malloc(sizeof(float)*N); float *mat3 = (float *) malloc(sizeof(float)*N); float *mat4 = (float *) malloc(sizeof(float)*N); float *mat5 = (float *) malloc(sizeof(float)*N); float *mat6 = (float *) malloc(sizeof(float)*N); float *mat7 = (float *) malloc(sizeof(float)*N); float *mat8 = (float *) malloc(sizeof(float)*N); float *mat9 = (float *) malloc(sizeof(float)*N); float *mat10 = (float *) malloc(sizeof(float)*N); float *mat11 = (float *) malloc(sizeof(float)*N); float *mat12 = (float *) malloc(sizeof(float)*N); float *matOut0 = (float *) malloc(sizeof(float)*N); float *matOut = (float *) malloc(sizeof(float)*N); GDALRasterIO(hB1,GF_Read,0,0,nX,nY,mat1,nX,nY,GDT_Float32,0,0); GDALRasterIO(hB2,GF_Read,0,0,nX,nY,mat2,nX,nY,GDT_Float32,0,0); GDALRasterIO(hB3,GF_Read,0,0,nX,nY,mat3,nX,nY,GDT_Float32,0,0); GDALRasterIO(hB4,GF_Read,0,0,nX,nY,mat4,nX,nY,GDT_Float32,0,0); GDALRasterIO(hB5,GF_Read,0,0,nX,nY,mat5,nX,nY,GDT_Float32,0,0); GDALRasterIO(hB6,GF_Read,0,0,nX,nY,mat6,nX,nY,GDT_Float32,0,0); GDALRasterIO(hB7,GF_Read,0,0,nX,nY,mat7,nX,nY,GDT_Float32,0,0); GDALRasterIO(hB8,GF_Read,0,0,nX,nY,mat8,nX,nY,GDT_Float32,0,0); GDALRasterIO(hB9,GF_Read,0,0,nX,nY,mat9,nX,nY,GDT_Float32,0,0); GDALRasterIO(hB10,GF_Read,0,0,nX,nY,mat10,nX,nY,GDT_Float32,0,0); GDALRasterIO(hB11,GF_Read,0,0,nX,nY,mat11,nX,nY,GDT_Float32,0,0); GDALRasterIO(hB12,GF_Read,0,0,nX,nY,mat12,nX,nY,GDT_Float32,0,0); //Parallel process your image #pragma omp parallel for default(none) \ private(rowcol)\ shared(N,mat1,mat2,mat3,mat4,mat5,mat6,\ mat7,mat8,mat9,mat10,mat11,mat12,\ matOut0, matOut ) for(rowcol=0;rowcol<N;rowcol++){ //---------------------------------------------------------- //TO Add: Check NODATA values for EACH INPUT raster //and include them in the case here //the more NODATA identified, the fastest processing is... //---------------------------------------------------------- if(mat1[rowcol]==-28768||mat1[rowcol]==0){ matOut[rowcol] = -28768; matOut0[rowcol] = -28768; } else { float lulc_code = mat1[rowcol]; float crop_age = mat2[rowcol]; float lst = mat5[rowcol]*0.02; float lst_c = lst-273.15; //---------------------------------------------------------- //CSU-ICWater libcrop functions (for CIA initially) //---------------------------------------------------------- //To add: DOY/season dependent DeltaT //if required by complexity to come //---------------------------------------------------------- // Tsoil: Temperature for Soil from MODIS 1Km float tsoil = Tsoil(lst_c, crop_code); // Tair: Temperature for air from MODIS 1Km float tair = Tair(lst_c, crop_code); // Roughness length for heat momentum float z0_m = z0m(crop_age, crop_code); // LAI function using MODIS 1Km input float la_i = lai(ndvi, crop_code); // Leaf area and perimeter (ratio is important so we use average at finalmax values for rs()) float leaf_area = leafarea(crop_code); float leaf_perimeter = leafperimeter(crop_code); //---------------------------------------------------------- //Back to Generic Formulation //---------------------------------------------------------- // Canopy_height is z0m/0.136 float canopy_height = z0_m/0.136; // disp = displacement height (m) if(canopy_height<1.0) { float disp = 0.65*canopy_height; } else { float disp = 0; } // kg for g0() float kg = 1.0; // k for fc() float k = 0.4631; // C for Rns (LAI attenuation equation) // c=0.5 is a generic formulation, // you may have a case for crop_code!=0 after float c = 0.5; //---------------------------------------------------------- //Renaming (for readability of algorithm inputs really) //---------------------------------------------------------- float rn = mat3[rowcol]; float g0 = mat4[rowcol]; float albedo = mat6[rowcol]*0.001; float ndvi = mat7[rowcol]*0.0001; float sunza = mat8[rowcol]*0.1; float time = mat9[rowcol]*0.1; float e0 = mat10[rowcol]; float dem = mat11[rowcol]; float etpot = mat12[rowcol]; //---------------------------------------------------------- //Computing Algorithm //---------------------------------------------------------- float h = sens_h(rn,c,la_i,sunza,k,ndvi,ndvimin,ndvimax,lst_c,e0,wind_speed,wind_height,canopy_height,atmo_pressure,z0_m,disp,tair,temperature_height,leaf_area,leaf_perimeter,tsoil); if(crop_code!=0){ //crop_code=0 means unknown land use type //In this case we replace g0 //because it is known by libcrop.c (crop_code !=0) g0 = g0_sam(rn,c,la_i,sunza,kg,ndvi,ndvimin,ndvimax,crop_code); } float samevapfr = sam_evapfr(rn, g0, h, lst); matOut0[rowcol] = samevapfr; float sameta = samevapfr * etpot; matOut[rowcol] = sameta; } } //pragma omp barrier GDALRasterIO(hBOut,GF_Write,0,0,nX,nY,matOut1,nX,nY,GDT_Float32,0,0); GDALClose(hDOut); GDALRasterIO(hBOut0,GF_Write,0,0,nX,nY,matOut0,nX,nY,GDT_Float32,0,0); GDALClose(hDOut0); //Free Memory if(mat1 != NULL) free(mat1); if(mat2 != NULL) free(mat2); if(matOut0 != NULL) free(matOut0); if(matOut != NULL) free(matOut); GDALClose(hD1); GDALClose(hD2); return(EXIT_SUCCESS); }
munit.c
/* Copyright (c) 2013-2018 Evan Nemerson <evan@nemerson.com> * * 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. */ /*** Configuration ***/ /* This is just where the output from the test goes. It's really just * meant to let you choose stdout or stderr, but if anyone really want * to direct it to a file let me know, it would be fairly easy to * support. */ #if !defined(MUNIT_OUTPUT_FILE) # define MUNIT_OUTPUT_FILE stdout #endif /* This is a bit more useful; it tells µnit how to format the seconds in * timed tests. If your tests run for longer you might want to reduce * it, and if your computer is really fast and your tests are tiny you * can increase it. */ #if !defined(MUNIT_TEST_TIME_FORMAT) # define MUNIT_TEST_TIME_FORMAT "0.8f" #endif /* If you have long test names you might want to consider bumping * this. The result information takes 43 characters. */ #if !defined(MUNIT_TEST_NAME_LEN) # define MUNIT_TEST_NAME_LEN 37 #endif /* If you don't like the timing information, you can disable it by * defining MUNIT_DISABLE_TIMING. */ #if !defined(MUNIT_DISABLE_TIMING) # define MUNIT_ENABLE_TIMING #endif /*** End configuration ***/ #if defined(_POSIX_C_SOURCE) && (_POSIX_C_SOURCE < 200809L) # undef _POSIX_C_SOURCE #endif #if !defined(_POSIX_C_SOURCE) # define _POSIX_C_SOURCE 200809L #endif /* Solaris freaks out if you try to use a POSIX or SUS standard without * the "right" C standard. */ #if defined(_XOPEN_SOURCE) # undef _XOPEN_SOURCE #endif #if defined(__STDC_VERSION__) # if __STDC_VERSION__ >= 201112L # define _XOPEN_SOURCE 700 # elif __STDC_VERSION__ >= 199901L # define _XOPEN_SOURCE 600 # endif #endif /* Because, according to Microsoft, POSIX is deprecated. You've got * to appreciate the chutzpah. */ #if defined(_MSC_VER) && !defined(_CRT_NONSTDC_NO_DEPRECATE) # define _CRT_NONSTDC_NO_DEPRECATE #endif #if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) # include <stdbool.h> #elif defined(_WIN32) /* https://msdn.microsoft.com/en-us/library/tf4dy80a.aspx */ #endif #include <limits.h> #include <time.h> #include <errno.h> #include <string.h> #include <stdlib.h> #include <stdio.h> #include <stdarg.h> #include <setjmp.h> #if !defined(MUNIT_NO_NL_LANGINFO) && !defined(_WIN32) #define MUNIT_NL_LANGINFO #include <locale.h> #include <langinfo.h> #include <strings.h> #endif #if !defined(_WIN32) # include <unistd.h> # include <sys/types.h> # include <sys/wait.h> #else # include <windows.h> # include <io.h> # include <fcntl.h> # if !defined(STDERR_FILENO) # define STDERR_FILENO _fileno(stderr) # endif #endif #include "munit.h" #define MUNIT_STRINGIFY(x) #x #define MUNIT_XSTRINGIFY(x) MUNIT_STRINGIFY(x) #if defined(__GNUC__) || defined(__INTEL_COMPILER) || defined(__SUNPRO_CC) || defined(__IBMCPP__) # define MUNIT_THREAD_LOCAL __thread #elif (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201102L)) || defined(_Thread_local) # define MUNIT_THREAD_LOCAL _Thread_local #elif defined(_WIN32) # define MUNIT_THREAD_LOCAL __declspec(thread) #endif /* MSVC 12.0 will emit a warning at /W4 for code like 'do { ... } * while (0)', or 'do { ... } while (1)'. I'm pretty sure nobody * at Microsoft compiles with /W4. */ #if defined(_MSC_VER) && (_MSC_VER <= 1800) #pragma warning(disable: 4127) #endif #if defined(_WIN32) || defined(__EMSCRIPTEN__) # define MUNIT_NO_FORK #endif #if defined(__EMSCRIPTEN__) # define MUNIT_NO_BUFFER #endif /*** Logging ***/ static MunitLogLevel munit_log_level_visible = MUNIT_LOG_INFO; static MunitLogLevel munit_log_level_fatal = MUNIT_LOG_ERROR; #if defined(MUNIT_THREAD_LOCAL) static MUNIT_THREAD_LOCAL munit_bool munit_error_jmp_buf_valid = 0; static MUNIT_THREAD_LOCAL jmp_buf munit_error_jmp_buf; #endif /* At certain warning levels, mingw will trigger warnings about * suggesting the format attribute, which we've explicity *not* set * because it will then choke on our attempts to use the MS-specific * I64 modifier for size_t (which we have to use since MSVC doesn't * support the C99 z modifier). */ #if defined(__MINGW32__) || defined(__MINGW64__) # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wsuggest-attribute=format" #endif MUNIT_PRINTF(5,0) static void munit_logf_exv(MunitLogLevel level, FILE* fp, const char* filename, int line, const char* format, va_list ap) { if (level < munit_log_level_visible) return; switch (level) { case MUNIT_LOG_DEBUG: fputs("Debug", fp); break; case MUNIT_LOG_INFO: fputs("Info", fp); break; case MUNIT_LOG_WARNING: fputs("Warning", fp); break; case MUNIT_LOG_ERROR: fputs("Error", fp); break; default: munit_logf_ex(MUNIT_LOG_ERROR, filename, line, "Invalid log level (%d)", level); return; } fputs(": ", fp); if (filename != NULL) fprintf(fp, "%s:%d: ", filename, line); vfprintf(fp, format, ap); fputc('\n', fp); } MUNIT_PRINTF(3,4) static void munit_logf_internal(MunitLogLevel level, FILE* fp, const char* format, ...) { va_list ap; va_start(ap, format); munit_logf_exv(level, fp, NULL, 0, format, ap); va_end(ap); } static void munit_log_internal(MunitLogLevel level, FILE* fp, const char* message) { munit_logf_internal(level, fp, "%s", message); } void munit_logf_ex(MunitLogLevel level, const char* filename, int line, const char* format, ...) { va_list ap; va_start(ap, format); munit_logf_exv(level, stderr, filename, line, format, ap); va_end(ap); if (level >= munit_log_level_fatal) { #if defined(MUNIT_THREAD_LOCAL) if (munit_error_jmp_buf_valid) longjmp(munit_error_jmp_buf, 1); #endif abort(); } } void munit_errorf_ex(const char* filename, int line, const char* format, ...) { va_list ap; va_start(ap, format); munit_logf_exv(MUNIT_LOG_ERROR, stderr, filename, line, format, ap); va_end(ap); #if defined(MUNIT_THREAD_LOCAL) if (munit_error_jmp_buf_valid) longjmp(munit_error_jmp_buf, 1); #endif abort(); } #if defined(__MINGW32__) || defined(__MINGW64__) #pragma GCC diagnostic pop #endif #if !defined(MUNIT_STRERROR_LEN) # define MUNIT_STRERROR_LEN 80 #endif static void munit_log_errno(MunitLogLevel level, FILE* fp, const char* msg) { #if defined(MUNIT_NO_STRERROR_R) || (defined(__MINGW32__) && !defined(MINGW_HAS_SECURE_API)) munit_logf_internal(level, fp, "%s: %s (%d)", msg, strerror(errno), errno); #else char munit_error_str[MUNIT_STRERROR_LEN]; munit_error_str[0] = '\0'; #if !defined(_WIN32) strerror_r(errno, munit_error_str, MUNIT_STRERROR_LEN); #else strerror_s(munit_error_str, MUNIT_STRERROR_LEN, errno); #endif munit_logf_internal(level, fp, "%s: %s (%d)", msg, munit_error_str, errno); #endif } /*** Memory allocation ***/ void* munit_malloc_ex(const char* filename, int line, size_t size) { void* ptr; if (size == 0) return NULL; ptr = calloc(1, size); if (MUNIT_UNLIKELY(ptr == NULL)) { munit_logf_ex(MUNIT_LOG_ERROR, filename, line, "Failed to allocate %" MUNIT_SIZE_MODIFIER "u bytes.", size); } return ptr; } /*** Timer code ***/ #if defined(MUNIT_ENABLE_TIMING) #define psnip_uint64_t munit_uint64_t #define psnip_uint32_t munit_uint32_t /* Code copied from portable-snippets * <https://github.com/nemequ/portable-snippets/>. If you need to * change something, please do it there so we can keep the code in * sync. */ /* Clocks (v1) * Portable Snippets - https://gitub.com/nemequ/portable-snippets * Created by Evan Nemerson <evan@nemerson.com> * * To the extent possible under law, the authors have waived all * copyright and related or neighboring rights to this code. For * details, see the Creative Commons Zero 1.0 Universal license at * https://creativecommons.org/publicdomain/zero/1.0/ */ #if !defined(PSNIP_CLOCK_H) #define PSNIP_CLOCK_H #if !defined(psnip_uint64_t) # include "../exact-int/exact-int.h" #endif #if !defined(PSNIP_CLOCK_STATIC_INLINE) # if defined(__GNUC__) # define PSNIP_CLOCK__COMPILER_ATTRIBUTES __attribute__((__unused__)) # else # define PSNIP_CLOCK__COMPILER_ATTRIBUTES # endif # define PSNIP_CLOCK__FUNCTION PSNIP_CLOCK__COMPILER_ATTRIBUTES static #endif enum PsnipClockType { /* This clock provides the current time, in units since 1970-01-01 * 00:00:00 UTC not including leap seconds. In other words, UNIX * time. Keep in mind that this clock doesn't account for leap * seconds, and can go backwards (think NTP adjustments). */ PSNIP_CLOCK_TYPE_WALL = 1, /* The CPU time is a clock which increases only when the current * process is active (i.e., it doesn't increment while blocking on * I/O). */ PSNIP_CLOCK_TYPE_CPU = 2, /* Monotonic time is always running (unlike CPU time), but it only ever moves forward unless you reboot the system. Things like NTP adjustments have no effect on this clock. */ PSNIP_CLOCK_TYPE_MONOTONIC = 3 }; struct PsnipClockTimespec { psnip_uint64_t seconds; psnip_uint64_t nanoseconds; }; /* Methods we support: */ #define PSNIP_CLOCK_METHOD_CLOCK_GETTIME 1 #define PSNIP_CLOCK_METHOD_TIME 2 #define PSNIP_CLOCK_METHOD_GETTIMEOFDAY 3 #define PSNIP_CLOCK_METHOD_QUERYPERFORMANCECOUNTER 4 #define PSNIP_CLOCK_METHOD_MACH_ABSOLUTE_TIME 5 #define PSNIP_CLOCK_METHOD_CLOCK 6 #define PSNIP_CLOCK_METHOD_GETPROCESSTIMES 7 #define PSNIP_CLOCK_METHOD_GETRUSAGE 8 #define PSNIP_CLOCK_METHOD_GETSYSTEMTIMEPRECISEASFILETIME 9 #define PSNIP_CLOCK_METHOD_GETTICKCOUNT64 10 #include <assert.h> #if defined(HEDLEY_UNREACHABLE) # define PSNIP_CLOCK_UNREACHABLE() HEDLEY_UNREACHABLE() #else # define PSNIP_CLOCK_UNREACHABLE() assert(0) #endif /* Choose an implementation */ /* #undef PSNIP_CLOCK_WALL_METHOD */ /* #undef PSNIP_CLOCK_CPU_METHOD */ /* #undef PSNIP_CLOCK_MONOTONIC_METHOD */ /* We want to be able to detect the libc implementation, so we include <limits.h> (<features.h> isn't available everywhere). */ #if defined(__unix__) || defined(__unix) || defined(__linux__) # include <limits.h> # include <unistd.h> #endif #if defined(_POSIX_TIMERS) && (_POSIX_TIMERS > 0) /* These are known to work without librt. If you know of others * please let us know so we can add them. */ # if \ (defined(__GLIBC__) && (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 17))) || \ (defined(__FreeBSD__)) # define PSNIP_CLOCK_HAVE_CLOCK_GETTIME # elif !defined(PSNIP_CLOCK_NO_LIBRT) # define PSNIP_CLOCK_HAVE_CLOCK_GETTIME # endif #endif #if defined(_WIN32) # if !defined(PSNIP_CLOCK_CPU_METHOD) # define PSNIP_CLOCK_CPU_METHOD PSNIP_CLOCK_METHOD_GETPROCESSTIMES # endif # if !defined(PSNIP_CLOCK_MONOTONIC_METHOD) # define PSNIP_CLOCK_MONOTONIC_METHOD PSNIP_CLOCK_METHOD_QUERYPERFORMANCECOUNTER # endif #endif #if defined(__MACH__) && !defined(__gnu_hurd__) # if !defined(PSNIP_CLOCK_MONOTONIC_METHOD) # define PSNIP_CLOCK_MONOTONIC_METHOD PSNIP_CLOCK_METHOD_MACH_ABSOLUTE_TIME # endif #endif #if defined(PSNIP_CLOCK_HAVE_CLOCK_GETTIME) # include <time.h> # if !defined(PSNIP_CLOCK_WALL_METHOD) # if defined(CLOCK_REALTIME_PRECISE) # define PSNIP_CLOCK_WALL_METHOD PSNIP_CLOCK_METHOD_CLOCK_GETTIME # define PSNIP_CLOCK_CLOCK_GETTIME_WALL CLOCK_REALTIME_PRECISE # elif !defined(__sun) # define PSNIP_CLOCK_WALL_METHOD PSNIP_CLOCK_METHOD_CLOCK_GETTIME # define PSNIP_CLOCK_CLOCK_GETTIME_WALL CLOCK_REALTIME # endif # endif # if !defined(PSNIP_CLOCK_CPU_METHOD) # if defined(_POSIX_CPUTIME) || defined(CLOCK_PROCESS_CPUTIME_ID) # define PSNIP_CLOCK_CPU_METHOD PSNIP_CLOCK_METHOD_CLOCK_GETTIME # define PSNIP_CLOCK_CLOCK_GETTIME_CPU CLOCK_PROCESS_CPUTIME_ID # elif defined(CLOCK_VIRTUAL) # define PSNIP_CLOCK_CPU_METHOD PSNIP_CLOCK_METHOD_CLOCK_GETTIME # define PSNIP_CLOCK_CLOCK_GETTIME_CPU CLOCK_VIRTUAL # endif # endif # if !defined(PSNIP_CLOCK_MONOTONIC_METHOD) # if defined(CLOCK_MONOTONIC_RAW) # define PSNIP_CLOCK_MONOTONIC_METHOD PSNIP_CLOCK_METHOD_CLOCK_GETTIME # define PSNIP_CLOCK_CLOCK_GETTIME_MONOTONIC CLOCK_MONOTONIC # elif defined(CLOCK_MONOTONIC_PRECISE) # define PSNIP_CLOCK_MONOTONIC_METHOD PSNIP_CLOCK_METHOD_CLOCK_GETTIME # define PSNIP_CLOCK_CLOCK_GETTIME_MONOTONIC CLOCK_MONOTONIC_PRECISE # elif defined(_POSIX_MONOTONIC_CLOCK) || defined(CLOCK_MONOTONIC) # define PSNIP_CLOCK_MONOTONIC_METHOD PSNIP_CLOCK_METHOD_CLOCK_GETTIME # define PSNIP_CLOCK_CLOCK_GETTIME_MONOTONIC CLOCK_MONOTONIC # endif # endif #endif #if defined(_POSIX_VERSION) && (_POSIX_VERSION >= 200112L) # if !defined(PSNIP_CLOCK_WALL_METHOD) # define PSNIP_CLOCK_WALL_METHOD PSNIP_CLOCK_METHOD_GETTIMEOFDAY # endif #endif #if !defined(PSNIP_CLOCK_WALL_METHOD) # define PSNIP_CLOCK_WALL_METHOD PSNIP_CLOCK_METHOD_TIME #endif #if !defined(PSNIP_CLOCK_CPU_METHOD) # define PSNIP_CLOCK_CPU_METHOD PSNIP_CLOCK_METHOD_CLOCK #endif /* Primarily here for testing. */ #if !defined(PSNIP_CLOCK_MONOTONIC_METHOD) && defined(PSNIP_CLOCK_REQUIRE_MONOTONIC) # error No monotonic clock found. #endif /* Implementations */ #if \ (defined(PSNIP_CLOCK_CPU_METHOD) && (PSNIP_CLOCK_CPU_METHOD == PSNIP_CLOCK_METHOD_CLOCK_GETTIME)) || \ (defined(PSNIP_CLOCK_WALL_METHOD) && (PSNIP_CLOCK_WALL_METHOD == PSNIP_CLOCK_METHOD_CLOCK_GETTIME)) || \ (defined(PSNIP_CLOCK_MONOTONIC_METHOD) && (PSNIP_CLOCK_MONOTONIC_METHOD == PSNIP_CLOCK_METHOD_CLOCK_GETTIME)) || \ (defined(PSNIP_CLOCK_CPU_METHOD) && (PSNIP_CLOCK_CPU_METHOD == PSNIP_CLOCK_METHOD_CLOCK)) || \ (defined(PSNIP_CLOCK_WALL_METHOD) && (PSNIP_CLOCK_WALL_METHOD == PSNIP_CLOCK_METHOD_CLOCK)) || \ (defined(PSNIP_CLOCK_MONOTONIC_METHOD) && (PSNIP_CLOCK_MONOTONIC_METHOD == PSNIP_CLOCK_METHOD_CLOCK)) || \ (defined(PSNIP_CLOCK_CPU_METHOD) && (PSNIP_CLOCK_CPU_METHOD == PSNIP_CLOCK_METHOD_TIME)) || \ (defined(PSNIP_CLOCK_WALL_METHOD) && (PSNIP_CLOCK_WALL_METHOD == PSNIP_CLOCK_METHOD_TIME)) || \ (defined(PSNIP_CLOCK_MONOTONIC_METHOD) && (PSNIP_CLOCK_MONOTONIC_METHOD == PSNIP_CLOCK_METHOD_TIME)) # include <time.h> #endif #if \ (defined(PSNIP_CLOCK_CPU_METHOD) && (PSNIP_CLOCK_CPU_METHOD == PSNIP_CLOCK_METHOD_GETTIMEOFDAY)) || \ (defined(PSNIP_CLOCK_WALL_METHOD) && (PSNIP_CLOCK_WALL_METHOD == PSNIP_CLOCK_METHOD_GETTIMEOFDAY)) || \ (defined(PSNIP_CLOCK_MONOTONIC_METHOD) && (PSNIP_CLOCK_MONOTONIC_METHOD == PSNIP_CLOCK_METHOD_GETTIMEOFDAY)) # include <sys/time.h> #endif #if \ (defined(PSNIP_CLOCK_CPU_METHOD) && (PSNIP_CLOCK_CPU_METHOD == PSNIP_CLOCK_METHOD_GETPROCESSTIMES)) || \ (defined(PSNIP_CLOCK_WALL_METHOD) && (PSNIP_CLOCK_WALL_METHOD == PSNIP_CLOCK_METHOD_GETPROCESSTIMES)) || \ (defined(PSNIP_CLOCK_MONOTONIC_METHOD) && (PSNIP_CLOCK_MONOTONIC_METHOD == PSNIP_CLOCK_METHOD_GETPROCESSTIMES)) || \ (defined(PSNIP_CLOCK_CPU_METHOD) && (PSNIP_CLOCK_CPU_METHOD == PSNIP_CLOCK_METHOD_GETTICKCOUNT64)) || \ (defined(PSNIP_CLOCK_WALL_METHOD) && (PSNIP_CLOCK_WALL_METHOD == PSNIP_CLOCK_METHOD_GETTICKCOUNT64)) || \ (defined(PSNIP_CLOCK_MONOTONIC_METHOD) && (PSNIP_CLOCK_MONOTONIC_METHOD == PSNIP_CLOCK_METHOD_GETTICKCOUNT64)) # include <windows.h> #endif #if \ (defined(PSNIP_CLOCK_CPU_METHOD) && (PSNIP_CLOCK_CPU_METHOD == PSNIP_CLOCK_METHOD_GETRUSAGE)) || \ (defined(PSNIP_CLOCK_WALL_METHOD) && (PSNIP_CLOCK_WALL_METHOD == PSNIP_CLOCK_METHOD_GETRUSAGE)) || \ (defined(PSNIP_CLOCK_MONOTONIC_METHOD) && (PSNIP_CLOCK_MONOTONIC_METHOD == PSNIP_CLOCK_METHOD_GETRUSAGE)) # include <sys/time.h> # include <sys/resource.h> #endif #if \ (defined(PSNIP_CLOCK_CPU_METHOD) && (PSNIP_CLOCK_CPU_METHOD == PSNIP_CLOCK_METHOD_MACH_ABSOLUTE_TIME)) || \ (defined(PSNIP_CLOCK_WALL_METHOD) && (PSNIP_CLOCK_WALL_METHOD == PSNIP_CLOCK_METHOD_MACH_ABSOLUTE_TIME)) || \ (defined(PSNIP_CLOCK_MONOTONIC_METHOD) && (PSNIP_CLOCK_MONOTONIC_METHOD == PSNIP_CLOCK_METHOD_MACH_ABSOLUTE_TIME)) # include <CoreServices/CoreServices.h> # include <mach/mach.h> # include <mach/mach_time.h> #endif /*** Implementations ***/ #define PSNIP_CLOCK_NSEC_PER_SEC ((psnip_uint32_t) (1000000000ULL)) #if \ (defined(PSNIP_CLOCK_CPU_METHOD) && (PSNIP_CLOCK_CPU_METHOD == PSNIP_CLOCK_METHOD_CLOCK_GETTIME)) || \ (defined(PSNIP_CLOCK_WALL_METHOD) && (PSNIP_CLOCK_WALL_METHOD == PSNIP_CLOCK_METHOD_CLOCK_GETTIME)) || \ (defined(PSNIP_CLOCK_MONOTONIC_METHOD) && (PSNIP_CLOCK_MONOTONIC_METHOD == PSNIP_CLOCK_METHOD_CLOCK_GETTIME)) PSNIP_CLOCK__FUNCTION psnip_uint32_t psnip_clock__clock_getres (clockid_t clk_id) { struct timespec res; int r; r = clock_getres(clk_id, &res); if (r != 0) return 0; return (psnip_uint32_t) (PSNIP_CLOCK_NSEC_PER_SEC / res.tv_nsec); } PSNIP_CLOCK__FUNCTION int psnip_clock__clock_gettime (clockid_t clk_id, struct PsnipClockTimespec* res) { struct timespec ts; if (clock_gettime(clk_id, &ts) != 0) return -10; res->seconds = (psnip_uint64_t) (ts.tv_sec); res->nanoseconds = (psnip_uint64_t) (ts.tv_nsec); return 0; } #endif PSNIP_CLOCK__FUNCTION psnip_uint32_t psnip_clock_wall_get_precision (void) { #if !defined(PSNIP_CLOCK_WALL_METHOD) return 0; #elif defined(PSNIP_CLOCK_WALL_METHOD) && PSNIP_CLOCK_WALL_METHOD == PSNIP_CLOCK_METHOD_CLOCK_GETTIME return psnip_clock__clock_getres(PSNIP_CLOCK_CLOCK_GETTIME_WALL); #elif defined(PSNIP_CLOCK_WALL_METHOD) && PSNIP_CLOCK_WALL_METHOD == PSNIP_CLOCK_METHOD_GETTIMEOFDAY return 1000000; #elif defined(PSNIP_CLOCK_WALL_METHOD) && PSNIP_CLOCK_WALL_METHOD == PSNIP_CLOCK_METHOD_TIME return 1; #else return 0; #endif } PSNIP_CLOCK__FUNCTION int psnip_clock_wall_get_time (struct PsnipClockTimespec* res) { (void) res; #if !defined(PSNIP_CLOCK_WALL_METHOD) return -2; #elif defined(PSNIP_CLOCK_WALL_METHOD) && PSNIP_CLOCK_WALL_METHOD == PSNIP_CLOCK_METHOD_CLOCK_GETTIME return psnip_clock__clock_gettime(PSNIP_CLOCK_CLOCK_GETTIME_WALL, res); #elif defined(PSNIP_CLOCK_WALL_METHOD) && PSNIP_CLOCK_WALL_METHOD == PSNIP_CLOCK_METHOD_TIME res->seconds = time(NULL); res->nanoseconds = 0; #elif defined(PSNIP_CLOCK_WALL_METHOD) && PSNIP_CLOCK_WALL_METHOD == PSNIP_CLOCK_METHOD_GETTIMEOFDAY struct timeval tv; if (gettimeofday(&tv, NULL) != 0) return -6; res->seconds = tv.tv_sec; res->nanoseconds = tv.tv_usec * 1000; #else return -2; #endif return 0; } PSNIP_CLOCK__FUNCTION psnip_uint32_t psnip_clock_cpu_get_precision (void) { #if !defined(PSNIP_CLOCK_CPU_METHOD) return 0; #elif defined(PSNIP_CLOCK_CPU_METHOD) && PSNIP_CLOCK_CPU_METHOD == PSNIP_CLOCK_METHOD_CLOCK_GETTIME return psnip_clock__clock_getres(PSNIP_CLOCK_CLOCK_GETTIME_CPU); #elif defined(PSNIP_CLOCK_CPU_METHOD) && PSNIP_CLOCK_CPU_METHOD == PSNIP_CLOCK_METHOD_CLOCK return CLOCKS_PER_SEC; #elif defined(PSNIP_CLOCK_CPU_METHOD) && PSNIP_CLOCK_CPU_METHOD == PSNIP_CLOCK_METHOD_GETPROCESSTIMES return PSNIP_CLOCK_NSEC_PER_SEC / 100; #else return 0; #endif } PSNIP_CLOCK__FUNCTION int psnip_clock_cpu_get_time (struct PsnipClockTimespec* res) { #if !defined(PSNIP_CLOCK_CPU_METHOD) (void) res; return -2; #elif defined(PSNIP_CLOCK_CPU_METHOD) && PSNIP_CLOCK_CPU_METHOD == PSNIP_CLOCK_METHOD_CLOCK_GETTIME return psnip_clock__clock_gettime(PSNIP_CLOCK_CLOCK_GETTIME_CPU, res); #elif defined(PSNIP_CLOCK_CPU_METHOD) && PSNIP_CLOCK_CPU_METHOD == PSNIP_CLOCK_METHOD_CLOCK clock_t t = clock(); if (t == ((clock_t) -1)) return -5; res->seconds = t / CLOCKS_PER_SEC; res->nanoseconds = (t % CLOCKS_PER_SEC) * (PSNIP_CLOCK_NSEC_PER_SEC / CLOCKS_PER_SEC); #elif defined(PSNIP_CLOCK_CPU_METHOD) && PSNIP_CLOCK_CPU_METHOD == PSNIP_CLOCK_METHOD_GETPROCESSTIMES FILETIME CreationTime, ExitTime, KernelTime, UserTime; LARGE_INTEGER date, adjust; if (!GetProcessTimes(GetCurrentProcess(), &CreationTime, &ExitTime, &KernelTime, &UserTime)) return -7; /* http://www.frenk.com/2009/12/convert-filetime-to-unix-timestamp/ */ date.HighPart = UserTime.dwHighDateTime; date.LowPart = UserTime.dwLowDateTime; adjust.QuadPart = 11644473600000 * 10000; date.QuadPart -= adjust.QuadPart; res->seconds = date.QuadPart / 10000000; res->nanoseconds = (date.QuadPart % 10000000) * (PSNIP_CLOCK_NSEC_PER_SEC / 100); #elif PSNIP_CLOCK_CPU_METHOD == PSNIP_CLOCK_METHOD_GETRUSAGE struct rusage usage; if (getrusage(RUSAGE_SELF, &usage) != 0) return -8; res->seconds = usage.ru_utime.tv_sec; res->nanoseconds = tv.tv_usec * 1000; #else (void) res; return -2; #endif return 0; } PSNIP_CLOCK__FUNCTION psnip_uint32_t psnip_clock_monotonic_get_precision (void) { #if !defined(PSNIP_CLOCK_MONOTONIC_METHOD) return 0; #elif defined(PSNIP_CLOCK_MONOTONIC_METHOD) && PSNIP_CLOCK_MONOTONIC_METHOD == PSNIP_CLOCK_METHOD_CLOCK_GETTIME return psnip_clock__clock_getres(PSNIP_CLOCK_CLOCK_GETTIME_MONOTONIC); #elif defined(PSNIP_CLOCK_MONOTONIC_METHOD) && PSNIP_CLOCK_MONOTONIC_METHOD == PSNIP_CLOCK_METHOD_MACH_ABSOLUTE_TIME static mach_timebase_info_data_t tbi = { 0, }; if (tbi.denom == 0) mach_timebase_info(&tbi); return (psnip_uint32_t) (tbi.numer / tbi.denom); #elif defined(PSNIP_CLOCK_MONOTONIC_METHOD) && PSNIP_CLOCK_MONOTONIC_METHOD == PSNIP_CLOCK_METHOD_GETTICKCOUNT64 return 1000; #elif defined(PSNIP_CLOCK_MONOTONIC_METHOD) && PSNIP_CLOCK_MONOTONIC_METHOD == PSNIP_CLOCK_METHOD_QUERYPERFORMANCECOUNTER LARGE_INTEGER Frequency; QueryPerformanceFrequency(&Frequency); return (psnip_uint32_t) ((Frequency.QuadPart > PSNIP_CLOCK_NSEC_PER_SEC) ? PSNIP_CLOCK_NSEC_PER_SEC : Frequency.QuadPart); #else return 0; #endif } PSNIP_CLOCK__FUNCTION int psnip_clock_monotonic_get_time (struct PsnipClockTimespec* res) { #if !defined(PSNIP_CLOCK_MONOTONIC_METHOD) (void) res; return -2; #elif defined(PSNIP_CLOCK_MONOTONIC_METHOD) && PSNIP_CLOCK_MONOTONIC_METHOD == PSNIP_CLOCK_METHOD_CLOCK_GETTIME return psnip_clock__clock_gettime(PSNIP_CLOCK_CLOCK_GETTIME_MONOTONIC, res); #elif defined(PSNIP_CLOCK_MONOTONIC_METHOD) && PSNIP_CLOCK_MONOTONIC_METHOD == PSNIP_CLOCK_METHOD_MACH_ABSOLUTE_TIME psnip_uint64_t nsec = mach_absolute_time(); static mach_timebase_info_data_t tbi = { 0, }; if (tbi.denom == 0) mach_timebase_info(&tbi); nsec *= ((psnip_uint64_t) tbi.numer) / ((psnip_uint64_t) tbi.denom); res->seconds = nsec / PSNIP_CLOCK_NSEC_PER_SEC; res->nanoseconds = nsec % PSNIP_CLOCK_NSEC_PER_SEC; #elif defined(PSNIP_CLOCK_MONOTONIC_METHOD) && PSNIP_CLOCK_MONOTONIC_METHOD == PSNIP_CLOCK_METHOD_QUERYPERFORMANCECOUNTER LARGE_INTEGER t, f; if (QueryPerformanceCounter(&t) == 0) return -12; QueryPerformanceFrequency(&f); res->seconds = t.QuadPart / f.QuadPart; res->nanoseconds = t.QuadPart % f.QuadPart; if (f.QuadPart > PSNIP_CLOCK_NSEC_PER_SEC) res->nanoseconds /= f.QuadPart / PSNIP_CLOCK_NSEC_PER_SEC; else res->nanoseconds *= PSNIP_CLOCK_NSEC_PER_SEC / f.QuadPart; #elif defined(PSNIP_CLOCK_MONOTONIC_METHOD) && PSNIP_CLOCK_MONOTONIC_METHOD == PSNIP_CLOCK_METHOD_GETTICKCOUNT64 const ULONGLONG msec = GetTickCount64(); res->seconds = msec / 1000; res->nanoseconds = sec % 1000; #else return -2; #endif return 0; } /* Returns the number of ticks per second for the specified clock. * For example, a clock with millisecond precision would return 1000, * and a clock with 1 second (such as the time() function) would * return 1. * * If the requested clock isn't available, it will return 0. * Hopefully this will be rare, but if it happens to you please let us * know so we can work on finding a way to support your system. * * Note that different clocks on the same system often have a * different precisions. */ PSNIP_CLOCK__FUNCTION psnip_uint32_t psnip_clock_get_precision (enum PsnipClockType clock_type) { switch (clock_type) { case PSNIP_CLOCK_TYPE_MONOTONIC: return psnip_clock_monotonic_get_precision (); case PSNIP_CLOCK_TYPE_CPU: return psnip_clock_cpu_get_precision (); case PSNIP_CLOCK_TYPE_WALL: return psnip_clock_wall_get_precision (); } PSNIP_CLOCK_UNREACHABLE(); return 0; } /* Set the provided timespec to the requested time. Returns 0 on * success, or a negative value on failure. */ PSNIP_CLOCK__FUNCTION int psnip_clock_get_time (enum PsnipClockType clock_type, struct PsnipClockTimespec* res) { assert(res != NULL); switch (clock_type) { case PSNIP_CLOCK_TYPE_MONOTONIC: return psnip_clock_monotonic_get_time (res); case PSNIP_CLOCK_TYPE_CPU: return psnip_clock_cpu_get_time (res); case PSNIP_CLOCK_TYPE_WALL: return psnip_clock_wall_get_time (res); } return -1; } #endif /* !defined(PSNIP_CLOCK_H) */ static psnip_uint64_t munit_clock_get_elapsed(struct PsnipClockTimespec* start, struct PsnipClockTimespec* end) { psnip_uint64_t r = (end->seconds - start->seconds) * PSNIP_CLOCK_NSEC_PER_SEC; if (end->nanoseconds < start->nanoseconds) { r -= (start->nanoseconds - end->nanoseconds); } else { r += (end->nanoseconds - start->nanoseconds); } return r; } #else # include <time.h> #endif /* defined(MUNIT_ENABLE_TIMING) */ /*** PRNG stuff ***/ /* This is (unless I screwed up, which is entirely possible) the * version of PCG with 32-bit state. It was chosen because it has a * small enough state that we should reliably be able to use CAS * instead of requiring a lock for thread-safety. * * If I did screw up, I probably will not bother changing it unless * there is a significant bias. It's really not important this be * particularly strong, as long as it is fairly random it's much more * important that it be reproducible, so bug reports have a better * chance of being reproducible. */ #if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L) && !defined(__STDC_NO_ATOMICS__) && !defined(__EMSCRIPTEN__) && (!defined(__GNUC_MINOR__) || (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ > 8)) # define HAVE_STDATOMIC #elif defined(__clang__) # if __has_extension(c_atomic) # define HAVE_CLANG_ATOMICS # endif #endif /* Workaround for http://llvm.org/bugs/show_bug.cgi?id=26911 */ #if defined(__clang__) && defined(_WIN32) # undef HAVE_STDATOMIC # if defined(__c2__) # undef HAVE_CLANG_ATOMICS # endif #endif #if defined(_OPENMP) # define ATOMIC_UINT32_T uint32_t # define ATOMIC_UINT32_INIT(x) (x) #elif defined(HAVE_STDATOMIC) # include <stdatomic.h> # define ATOMIC_UINT32_T _Atomic uint32_t # define ATOMIC_UINT32_INIT(x) ATOMIC_VAR_INIT(x) #elif defined(HAVE_CLANG_ATOMICS) # define ATOMIC_UINT32_T _Atomic uint32_t # define ATOMIC_UINT32_INIT(x) (x) #elif defined(_WIN32) # define ATOMIC_UINT32_T volatile LONG # define ATOMIC_UINT32_INIT(x) (x) #else # define ATOMIC_UINT32_T volatile uint32_t # define ATOMIC_UINT32_INIT(x) (x) #endif static ATOMIC_UINT32_T munit_rand_state = ATOMIC_UINT32_INIT(42); #if defined(_OPENMP) static inline void munit_atomic_store(ATOMIC_UINT32_T* dest, ATOMIC_UINT32_T value) { #pragma omp critical (munit_atomics) *dest = value; } static inline uint32_t munit_atomic_load(ATOMIC_UINT32_T* src) { int ret; #pragma omp critical (munit_atomics) ret = *src; return ret; } static inline uint32_t munit_atomic_cas(ATOMIC_UINT32_T* dest, ATOMIC_UINT32_T* expected, ATOMIC_UINT32_T desired) { munit_bool ret; #pragma omp critical (munit_atomics) { if (*dest == *expected) { *dest = desired; ret = 1; } else { ret = 0; } } return ret; } #elif defined(HAVE_STDATOMIC) # define munit_atomic_store(dest, value) atomic_store(dest, value) # define munit_atomic_load(src) atomic_load(src) # define munit_atomic_cas(dest, expected, value) atomic_compare_exchange_weak(dest, expected, value) #elif defined(HAVE_CLANG_ATOMICS) # define munit_atomic_store(dest, value) __c11_atomic_store(dest, value, __ATOMIC_SEQ_CST) # define munit_atomic_load(src) __c11_atomic_load(src, __ATOMIC_SEQ_CST) # define munit_atomic_cas(dest, expected, value) __c11_atomic_compare_exchange_weak(dest, expected, value, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST) #elif defined(__GNUC__) && (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 7) # define munit_atomic_store(dest, value) __atomic_store_n(dest, value, __ATOMIC_SEQ_CST) # define munit_atomic_load(src) __atomic_load_n(src, __ATOMIC_SEQ_CST) # define munit_atomic_cas(dest, expected, value) __atomic_compare_exchange_n(dest, expected, value, 1, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST) #elif defined(__GNUC__) && (__GNUC__ >= 4) # define munit_atomic_store(dest,value) do { *(dest) = (value); } while (0) # define munit_atomic_load(src) (*(src)) # define munit_atomic_cas(dest, expected, value) __sync_bool_compare_and_swap(dest, *expected, value) #elif defined(_WIN32) /* Untested */ # define munit_atomic_store(dest,value) do { *(dest) = (value); } while (0) # define munit_atomic_load(src) (*(src)) # define munit_atomic_cas(dest, expected, value) InterlockedCompareExchange((dest), (value), *(expected)) #else # warning No atomic implementation, PRNG will not be thread-safe # define munit_atomic_store(dest, value) do { *(dest) = (value); } while (0) # define munit_atomic_load(src) (*(src)) static inline munit_bool munit_atomic_cas(ATOMIC_UINT32_T* dest, ATOMIC_UINT32_T* expected, ATOMIC_UINT32_T desired) { if (*dest == *expected) { *dest = desired; return 1; } else { return 0; } } #endif #define MUNIT_PRNG_MULTIPLIER (747796405U) #define MUNIT_PRNG_INCREMENT (1729U) static munit_uint32_t munit_rand_next_state(munit_uint32_t state) { return state * MUNIT_PRNG_MULTIPLIER + MUNIT_PRNG_INCREMENT; } static munit_uint32_t munit_rand_from_state(munit_uint32_t state) { munit_uint32_t res = ((state >> ((state >> 28) + 4)) ^ state) * (277803737U); res ^= res >> 22; return res; } void munit_rand_seed(munit_uint32_t seed) { munit_uint32_t state = munit_rand_next_state(seed + MUNIT_PRNG_INCREMENT); munit_atomic_store(&munit_rand_state, state); } static munit_uint32_t munit_rand_generate_seed(void) { munit_uint32_t seed, state; #if defined(MUNIT_ENABLE_TIMING) struct PsnipClockTimespec wc = { 0, }; psnip_clock_get_time(PSNIP_CLOCK_TYPE_WALL, &wc); seed = (munit_uint32_t) wc.nanoseconds; #else seed = (munit_uint32_t) time(NULL); #endif state = munit_rand_next_state(seed + MUNIT_PRNG_INCREMENT); return munit_rand_from_state(state); } static munit_uint32_t munit_rand_state_uint32(munit_uint32_t* state) { const munit_uint32_t old = *state; *state = munit_rand_next_state(old); return munit_rand_from_state(old); } munit_uint32_t munit_rand_uint32(void) { munit_uint32_t old, state; do { old = munit_atomic_load(&munit_rand_state); state = munit_rand_next_state(old); } while (!munit_atomic_cas(&munit_rand_state, &old, state)); return munit_rand_from_state(old); } static void munit_rand_state_memory(munit_uint32_t* state, size_t size, munit_uint8_t data[MUNIT_ARRAY_PARAM(size)]) { size_t members_remaining = size / sizeof(munit_uint32_t); size_t bytes_remaining = size % sizeof(munit_uint32_t); munit_uint8_t* b = data; munit_uint32_t rv; while (members_remaining-- > 0) { rv = munit_rand_state_uint32(state); memcpy(b, &rv, sizeof(munit_uint32_t)); b += sizeof(munit_uint32_t); } if (bytes_remaining != 0) { rv = munit_rand_state_uint32(state); memcpy(b, &rv, bytes_remaining); } } void munit_rand_memory(size_t size, munit_uint8_t data[MUNIT_ARRAY_PARAM(size)]) { munit_uint32_t old, state; do { state = old = munit_atomic_load(&munit_rand_state); munit_rand_state_memory(&state, size, data); } while (!munit_atomic_cas(&munit_rand_state, &old, state)); } static munit_uint32_t munit_rand_state_at_most(munit_uint32_t* state, munit_uint32_t salt, munit_uint32_t max) { /* We want (UINT32_MAX + 1) % max, which in unsigned arithmetic is the same * as (UINT32_MAX + 1 - max) % max = -max % max. We compute -max using not * to avoid compiler warnings. */ const munit_uint32_t min = (~max + 1U) % max; munit_uint32_t x; if (max == (~((munit_uint32_t) 0U))) return munit_rand_state_uint32(state) ^ salt; max++; do { x = munit_rand_state_uint32(state) ^ salt; } while (x < min); return x % max; } static munit_uint32_t munit_rand_at_most(munit_uint32_t salt, munit_uint32_t max) { munit_uint32_t old, state; munit_uint32_t retval; do { state = old = munit_atomic_load(&munit_rand_state); retval = munit_rand_state_at_most(&state, salt, max); } while (!munit_atomic_cas(&munit_rand_state, &old, state)); return retval; } int munit_rand_int_range(int min, int max) { munit_uint64_t range = (munit_uint64_t) max - (munit_uint64_t) min; if (min > max) return munit_rand_int_range(max, min); if (range > (~((munit_uint32_t) 0U))) range = (~((munit_uint32_t) 0U)); return min + munit_rand_at_most(0, (munit_uint32_t) range); } double munit_rand_double(void) { munit_uint32_t old, state; double retval = 0.0; do { state = old = munit_atomic_load(&munit_rand_state); /* See http://mumble.net/~campbell/tmp/random_real.c for how to do * this right. Patches welcome if you feel that this is too * biased. */ retval = munit_rand_state_uint32(&state) / ((~((munit_uint32_t) 0U)) + 1.0); } while (!munit_atomic_cas(&munit_rand_state, &old, state)); return retval; } /*** Test suite handling ***/ typedef struct { unsigned int successful; unsigned int skipped; unsigned int failed; unsigned int errored; #if defined(MUNIT_ENABLE_TIMING) munit_uint64_t cpu_clock; munit_uint64_t wall_clock; #endif } MunitReport; typedef struct { const char* prefix; const MunitSuite* suite; const MunitSuite* current_suite; const char** tests; munit_uint32_t seed; unsigned int iterations; MunitParameter* parameters; munit_bool single_parameter_mode; void* user_data; void* suite_setup_data; MunitReport report; munit_bool colorize; munit_bool fork; munit_bool show_stderr; munit_bool fatal_failures; } MunitTestRunner; const char* munit_parameters_get(const MunitParameter params[], const char* key) { const MunitParameter* param; for (param = params ; param != NULL && param->name != NULL ; param++) if (strcmp(param->name, key) == 0) return param->value; return NULL; } #if defined(MUNIT_ENABLE_TIMING) static void munit_print_time(FILE* fp, munit_uint64_t nanoseconds) { fprintf(fp, "%" MUNIT_TEST_TIME_FORMAT, ((double) nanoseconds) / ((double) PSNIP_CLOCK_NSEC_PER_SEC)); } #endif /* Add a paramter to an array of parameters. */ static MunitResult munit_parameters_add(size_t* params_size, MunitParameter* params[MUNIT_ARRAY_PARAM(*params_size)], char* name, char* value) { *params = realloc(*params, sizeof(MunitParameter) * (*params_size + 2)); if (*params == NULL) return MUNIT_ERROR; (*params)[*params_size].name = name; (*params)[*params_size].value = value; (*params_size)++; (*params)[*params_size].name = NULL; (*params)[*params_size].value = NULL; return MUNIT_OK; } /* Concatenate two strings, but just return one of the components * unaltered if the other is NULL or "". */ static char* munit_maybe_concat(size_t* len, char* prefix, char* suffix) { char* res; size_t res_l; const size_t prefix_l = prefix != NULL ? strlen(prefix) : 0; const size_t suffix_l = suffix != NULL ? strlen(suffix) : 0; if (prefix_l == 0 && suffix_l == 0) { res = NULL; res_l = 0; } else if (prefix_l == 0 && suffix_l != 0) { res = suffix; res_l = suffix_l; } else if (prefix_l != 0 && suffix_l == 0) { res = prefix; res_l = prefix_l; } else { res_l = prefix_l + suffix_l; res = malloc(res_l + 1); memcpy(res, prefix, prefix_l); memcpy(res + prefix_l, suffix, suffix_l); res[res_l] = 0; } if (len != NULL) *len = res_l; return res; } /* Possbily free a string returned by munit_maybe_concat. */ static void munit_maybe_free_concat(char* s, const char* prefix, const char* suffix) { if (prefix != s && suffix != s) free(s); } /* Cheap string hash function, just used to salt the PRNG. */ static munit_uint32_t munit_str_hash(const char* name) { const char *p; munit_uint32_t h = 5381U; for (p = name; *p != '\0'; p++) h = (h << 5) + h + *p; return h; } static void munit_splice(int from, int to) { munit_uint8_t buf[1024]; #if !defined(_WIN32) ssize_t len; ssize_t bytes_written; ssize_t write_res; #else int len; int bytes_written; int write_res; #endif do { len = read(from, buf, sizeof(buf)); if (len > 0) { bytes_written = 0; do { write_res = write(to, buf + bytes_written, len - bytes_written); if (write_res < 0) break; bytes_written += write_res; } while (bytes_written < len); } else break; } while (1); } /* This is the part that should be handled in the child process */ static MunitResult munit_test_runner_exec(MunitTestRunner* runner, const MunitTest* test, const MunitParameter params[], MunitReport* report) { unsigned int iterations = runner->iterations; MunitResult result = MUNIT_FAIL; #if defined(MUNIT_ENABLE_TIMING) struct PsnipClockTimespec wall_clock_begin = { 0, }, wall_clock_end = { 0, }; struct PsnipClockTimespec cpu_clock_begin = { 0, }, cpu_clock_end = { 0, }; #endif unsigned int i = 0; if ((test->options & MUNIT_TEST_OPTION_SINGLE_ITERATION) == MUNIT_TEST_OPTION_SINGLE_ITERATION) iterations = 1; else if (iterations == 0) iterations = runner->current_suite->iterations; munit_rand_seed(runner->seed); do { void* data = (runner->suite_setup_data == NULL) ? runner->user_data : runner->suite_setup_data; if (test->setup != NULL) { data = test->setup(params, data); } #if defined(MUNIT_ENABLE_TIMING) psnip_clock_get_time(PSNIP_CLOCK_TYPE_WALL, &wall_clock_begin); psnip_clock_get_time(PSNIP_CLOCK_TYPE_CPU, &cpu_clock_begin); #endif result = test->test(params, data); #if defined(MUNIT_ENABLE_TIMING) psnip_clock_get_time(PSNIP_CLOCK_TYPE_WALL, &wall_clock_end); psnip_clock_get_time(PSNIP_CLOCK_TYPE_CPU, &cpu_clock_end); #endif if (test->tear_down != NULL) test->tear_down(data); if (MUNIT_LIKELY(result == MUNIT_OK)) { report->successful++; #if defined(MUNIT_ENABLE_TIMING) report->wall_clock += munit_clock_get_elapsed(&wall_clock_begin, &wall_clock_end); report->cpu_clock += munit_clock_get_elapsed(&cpu_clock_begin, &cpu_clock_end); #endif } else { switch ((int) result) { case MUNIT_SKIP: report->skipped++; break; case MUNIT_FAIL: report->failed++; break; case MUNIT_ERROR: report->errored++; break; default: break; } break; } } while (++i < iterations); return result; } #if defined(MUNIT_EMOTICON) # define MUNIT_RESULT_STRING_OK ":)" # define MUNIT_RESULT_STRING_SKIP ":|" # define MUNIT_RESULT_STRING_FAIL ":(" # define MUNIT_RESULT_STRING_ERROR ":o" # define MUNIT_RESULT_STRING_TODO ":/" #else # define MUNIT_RESULT_STRING_OK "OK " # define MUNIT_RESULT_STRING_SKIP "SKIP " # define MUNIT_RESULT_STRING_FAIL "FAIL " # define MUNIT_RESULT_STRING_ERROR "ERROR" # define MUNIT_RESULT_STRING_TODO "TODO " #endif static void munit_test_runner_print_color(const MunitTestRunner* runner, const char* string, char color) { if (runner->colorize) fprintf(MUNIT_OUTPUT_FILE, "\x1b[3%cm%s\x1b[39m", color, string); else fputs(string, MUNIT_OUTPUT_FILE); } #if !defined(MUNIT_NO_BUFFER) static int munit_replace_stderr(FILE* stderr_buf) { if (stderr_buf != NULL) { const int orig_stderr = dup(STDERR_FILENO); int errfd = fileno(stderr_buf); if (MUNIT_UNLIKELY(errfd == -1)) { exit(EXIT_FAILURE); } dup2(errfd, STDERR_FILENO); return orig_stderr; } return -1; } static void munit_restore_stderr(int orig_stderr) { if (orig_stderr != -1) { dup2(orig_stderr, STDERR_FILENO); close(orig_stderr); } } #endif /* !defined(MUNIT_NO_BUFFER) */ /* Run a test with the specified parameters. */ static void munit_test_runner_run_test_with_params(MunitTestRunner* runner, const MunitTest* test, const MunitParameter params[]) { MunitResult result = MUNIT_OK; MunitReport report = { 0, 0, 0, 0, #if defined(MUNIT_ENABLE_TIMING) 0, 0 #endif }; unsigned int output_l; munit_bool first; const MunitParameter* param; FILE* stderr_buf; #if !defined(MUNIT_NO_FORK) int pipefd[2]; pid_t fork_pid; int orig_stderr; ssize_t bytes_written = 0; ssize_t write_res; ssize_t bytes_read = 0; ssize_t read_res; int status = 0; pid_t changed_pid; #endif if (params != NULL) { output_l = 2; fputs(" ", MUNIT_OUTPUT_FILE); first = 1; for (param = params ; param != NULL && param->name != NULL ; param++) { if (!first) { fputs(", ", MUNIT_OUTPUT_FILE); output_l += 2; } else { first = 0; } output_l += fprintf(MUNIT_OUTPUT_FILE, "%s=%s", param->name, param->value); } while (output_l++ < MUNIT_TEST_NAME_LEN) { fputc(' ', MUNIT_OUTPUT_FILE); } } fflush(MUNIT_OUTPUT_FILE); stderr_buf = NULL; #if !defined(_WIN32) || defined(__MINGW32__) stderr_buf = tmpfile(); #else tmpfile_s(&stderr_buf); #endif if (stderr_buf == NULL) { munit_log_errno(MUNIT_LOG_ERROR, stderr, "unable to create buffer for stderr"); result = MUNIT_ERROR; goto print_result; } #if !defined(MUNIT_NO_FORK) if (runner->fork) { pipefd[0] = -1; pipefd[1] = -1; if (pipe(pipefd) != 0) { munit_log_errno(MUNIT_LOG_ERROR, stderr, "unable to create pipe"); result = MUNIT_ERROR; goto print_result; } fork_pid = fork(); if (fork_pid == 0) { close(pipefd[0]); orig_stderr = munit_replace_stderr(stderr_buf); munit_test_runner_exec(runner, test, params, &report); /* Note that we don't restore stderr. This is so we can buffer * things written to stderr later on (such as by * asan/tsan/ubsan, valgrind, etc.) */ close(orig_stderr); do { write_res = write(pipefd[1], ((munit_uint8_t*) (&report)) + bytes_written, sizeof(report) - bytes_written); if (write_res < 0) { if (stderr_buf != NULL) { munit_log_errno(MUNIT_LOG_ERROR, stderr, "unable to write to pipe"); } exit(EXIT_FAILURE); } bytes_written += write_res; } while ((size_t) bytes_written < sizeof(report)); if (stderr_buf != NULL) fclose(stderr_buf); close(pipefd[1]); exit(EXIT_SUCCESS); } else if (fork_pid == -1) { close(pipefd[0]); close(pipefd[1]); if (stderr_buf != NULL) { munit_log_errno(MUNIT_LOG_ERROR, stderr, "unable to fork"); } report.errored++; result = MUNIT_ERROR; } else { close(pipefd[1]); do { read_res = read(pipefd[0], ((munit_uint8_t*) (&report)) + bytes_read, sizeof(report) - bytes_read); if (read_res < 1) break; bytes_read += read_res; } while (bytes_read < (ssize_t) sizeof(report)); changed_pid = waitpid(fork_pid, &status, 0); if (MUNIT_LIKELY(changed_pid == fork_pid) && MUNIT_LIKELY(WIFEXITED(status))) { if (bytes_read != sizeof(report)) { munit_logf_internal(MUNIT_LOG_ERROR, stderr_buf, "child exited unexpectedly with status %d", WEXITSTATUS(status)); report.errored++; } else if (WEXITSTATUS(status) != EXIT_SUCCESS) { munit_logf_internal(MUNIT_LOG_ERROR, stderr_buf, "child exited with status %d", WEXITSTATUS(status)); report.errored++; } } else { if (WIFSIGNALED(status)) { #if defined(_XOPEN_VERSION) && (_XOPEN_VERSION >= 700) munit_logf_internal(MUNIT_LOG_ERROR, stderr_buf, "child killed by signal %d (%s)", WTERMSIG(status), strsignal(WTERMSIG(status))); #else munit_logf_internal(MUNIT_LOG_ERROR, stderr_buf, "child killed by signal %d", WTERMSIG(status)); #endif } else if (WIFSTOPPED(status)) { munit_logf_internal(MUNIT_LOG_ERROR, stderr_buf, "child stopped by signal %d", WSTOPSIG(status)); } report.errored++; } close(pipefd[0]); waitpid(fork_pid, NULL, 0); } } else #endif { #if !defined(MUNIT_NO_BUFFER) const volatile int orig_stderr = munit_replace_stderr(stderr_buf); #endif #if defined(MUNIT_THREAD_LOCAL) if (MUNIT_UNLIKELY(setjmp(munit_error_jmp_buf) != 0)) { result = MUNIT_FAIL; report.failed++; } else { munit_error_jmp_buf_valid = 1; result = munit_test_runner_exec(runner, test, params, &report); } #else result = munit_test_runner_exec(runner, test, params, &report); #endif #if !defined(MUNIT_NO_BUFFER) munit_restore_stderr(orig_stderr); #endif /* Here just so that the label is used on Windows and we don't get * a warning */ goto print_result; } print_result: fputs("[ ", MUNIT_OUTPUT_FILE); if ((test->options & MUNIT_TEST_OPTION_TODO) == MUNIT_TEST_OPTION_TODO) { if (report.failed != 0 || report.errored != 0 || report.skipped != 0) { munit_test_runner_print_color(runner, MUNIT_RESULT_STRING_TODO, '3'); result = MUNIT_OK; } else { munit_test_runner_print_color(runner, MUNIT_RESULT_STRING_ERROR, '1'); if (MUNIT_LIKELY(stderr_buf != NULL)) munit_log_internal(MUNIT_LOG_ERROR, stderr_buf, "Test marked TODO, but was successful."); runner->report.failed++; result = MUNIT_ERROR; } } else if (report.failed > 0) { munit_test_runner_print_color(runner, MUNIT_RESULT_STRING_FAIL, '1'); runner->report.failed++; result = MUNIT_FAIL; } else if (report.errored > 0) { munit_test_runner_print_color(runner, MUNIT_RESULT_STRING_ERROR, '1'); runner->report.errored++; result = MUNIT_ERROR; } else if (report.skipped > 0) { munit_test_runner_print_color(runner, MUNIT_RESULT_STRING_SKIP, '3'); runner->report.skipped++; result = MUNIT_SKIP; } else if (report.successful > 1) { munit_test_runner_print_color(runner, MUNIT_RESULT_STRING_OK, '2'); #if defined(MUNIT_ENABLE_TIMING) fputs(" ] [ ", MUNIT_OUTPUT_FILE); munit_print_time(MUNIT_OUTPUT_FILE, report.wall_clock / report.successful); fputs(" / ", MUNIT_OUTPUT_FILE); munit_print_time(MUNIT_OUTPUT_FILE, report.cpu_clock / report.successful); fprintf(MUNIT_OUTPUT_FILE, " CPU ]\n %-" MUNIT_XSTRINGIFY(MUNIT_TEST_NAME_LEN) "s Total: [ ", ""); munit_print_time(MUNIT_OUTPUT_FILE, report.wall_clock); fputs(" / ", MUNIT_OUTPUT_FILE); munit_print_time(MUNIT_OUTPUT_FILE, report.cpu_clock); fputs(" CPU", MUNIT_OUTPUT_FILE); #endif runner->report.successful++; result = MUNIT_OK; } else if (report.successful > 0) { munit_test_runner_print_color(runner, MUNIT_RESULT_STRING_OK, '2'); #if defined(MUNIT_ENABLE_TIMING) fputs(" ] [ ", MUNIT_OUTPUT_FILE); munit_print_time(MUNIT_OUTPUT_FILE, report.wall_clock); fputs(" / ", MUNIT_OUTPUT_FILE); munit_print_time(MUNIT_OUTPUT_FILE, report.cpu_clock); fputs(" CPU", MUNIT_OUTPUT_FILE); #endif runner->report.successful++; result = MUNIT_OK; } fputs(" ]\n", MUNIT_OUTPUT_FILE); if (stderr_buf != NULL) { if (result == MUNIT_FAIL || result == MUNIT_ERROR || runner->show_stderr) { fflush(MUNIT_OUTPUT_FILE); rewind(stderr_buf); munit_splice(fileno(stderr_buf), STDERR_FILENO); fflush(stderr); } fclose(stderr_buf); } } static void munit_test_runner_run_test_wild(MunitTestRunner* runner, const MunitTest* test, const char* test_name, MunitParameter* params, MunitParameter* p) { const MunitParameterEnum* pe; char** values; MunitParameter* next; for (pe = test->parameters ; pe != NULL && pe->name != NULL ; pe++) { if (p->name == pe->name) break; } if (pe == NULL) return; for (values = pe->values ; *values != NULL ; values++) { next = p + 1; p->value = *values; if (next->name == NULL) { munit_test_runner_run_test_with_params(runner, test, params); } else { munit_test_runner_run_test_wild(runner, test, test_name, params, next); } if (runner->fatal_failures && (runner->report.failed != 0 || runner->report.errored != 0)) break; } } /* Run a single test, with every combination of parameters * requested. */ static void munit_test_runner_run_test(MunitTestRunner* runner, const MunitTest* test, const char* prefix) { char* test_name = munit_maybe_concat(NULL, (char*) prefix, (char*) test->name); /* The array of parameters to pass to * munit_test_runner_run_test_with_params */ MunitParameter* params = NULL; size_t params_l = 0; /* Wildcard parameters are parameters which have possible values * specified in the test, but no specific value was passed to the * CLI. That means we want to run the test once for every * possible combination of parameter values or, if --single was * passed to the CLI, a single time with a random set of * parameters. */ MunitParameter* wild_params = NULL; size_t wild_params_l = 0; const MunitParameterEnum* pe; const MunitParameter* cli_p; munit_bool filled; unsigned int possible; char** vals; size_t first_wild; const MunitParameter* wp; int pidx; munit_rand_seed(runner->seed); fprintf(MUNIT_OUTPUT_FILE, "%-" MUNIT_XSTRINGIFY(MUNIT_TEST_NAME_LEN) "s", test_name); if (test->parameters == NULL) { /* No parameters. Simple, nice. */ munit_test_runner_run_test_with_params(runner, test, NULL); } else { fputc('\n', MUNIT_OUTPUT_FILE); for (pe = test->parameters ; pe != NULL && pe->name != NULL ; pe++) { /* Did we received a value for this parameter from the CLI? */ filled = 0; for (cli_p = runner->parameters ; cli_p != NULL && cli_p->name != NULL ; cli_p++) { if (strcmp(cli_p->name, pe->name) == 0) { if (MUNIT_UNLIKELY(munit_parameters_add(&params_l, &params, pe->name, cli_p->value) != MUNIT_OK)) goto cleanup; filled = 1; break; } } if (filled) continue; /* Nothing from CLI, is the enum NULL/empty? We're not a * fuzzer… */ if (pe->values == NULL || pe->values[0] == NULL) continue; /* If --single was passed to the CLI, choose a value from the * list of possibilities randomly. */ if (runner->single_parameter_mode) { possible = 0; for (vals = pe->values ; *vals != NULL ; vals++) possible++; /* We want the tests to be reproducible, even if you're only * running a single test, but we don't want every test with * the same number of parameters to choose the same parameter * number, so use the test name as a primitive salt. */ pidx = munit_rand_at_most(munit_str_hash(test_name), possible - 1); if (MUNIT_UNLIKELY(munit_parameters_add(&params_l, &params, pe->name, pe->values[pidx]) != MUNIT_OK)) goto cleanup; } else { /* We want to try every permutation. Put in a placeholder * entry, we'll iterate through them later. */ if (MUNIT_UNLIKELY(munit_parameters_add(&wild_params_l, &wild_params, pe->name, NULL) != MUNIT_OK)) goto cleanup; } } if (wild_params_l != 0) { first_wild = params_l; for (wp = wild_params ; wp != NULL && wp->name != NULL ; wp++) { for (pe = test->parameters ; pe != NULL && pe->name != NULL && pe->values != NULL ; pe++) { if (strcmp(wp->name, pe->name) == 0) { if (MUNIT_UNLIKELY(munit_parameters_add(&params_l, &params, pe->name, pe->values[0]) != MUNIT_OK)) goto cleanup; } } } munit_test_runner_run_test_wild(runner, test, test_name, params, params + first_wild); } else { munit_test_runner_run_test_with_params(runner, test, params); } cleanup: free(params); free(wild_params); } munit_maybe_free_concat(test_name, prefix, test->name); } static void munit_test_runner_ruin_suite_setup(MunitTestRunner *runner, const MunitSuite *suite, int *setup_was_executed) { if ((*setup_was_executed == 0) && (suite->setup != NULL)) { munit_rand_seed(runner->seed); runner->suite_setup_data = suite->setup(runner->user_data); *setup_was_executed = 1; } } static void munit_test_runner_ruin_suite_teardown(MunitTestRunner *runner, const MunitSuite *suite, int *setup_was_executed) { if ((*setup_was_executed == 1) && (suite->tear_down != NULL)) { suite->tear_down(runner->suite_setup_data); *setup_was_executed = 0; } runner->suite_setup_data = NULL; } /* Recurse through the suite and run all the tests. If a list of * tests to run was provied on the command line, run only those * tests. */ static void munit_test_runner_run_suite(MunitTestRunner* runner, const MunitSuite* suite, const char* prefix) { size_t pre_l; size_t test_name_l; int is_suite_name_prefix; int is_test_name_prefix; char* pre = munit_maybe_concat(&pre_l, (char*) prefix, (char*) suite->prefix); const MunitTest* test; const char** test_name; const MunitSuite* child_suite; runner->current_suite = suite; int suite_setup_was_executed = 0; /* Run the tests. */ for (test = suite->tests ; test != NULL && test->test != NULL ; test++) { if (runner->tests != NULL) { /* Specific tests were requested on the CLI */ for (test_name = runner->tests ; test_name != NULL && *test_name != NULL ; test_name++) { test_name_l = strlen(*test_name); /* test_name contains only a suite name prefix */ is_suite_name_prefix = (test_name_l < pre_l) && strncmp(pre, *test_name, test_name_l) == 0; /* test_name is a test name with suite name prefix */ is_test_name_prefix = (pre_l == 0 || strncmp(pre, *test_name, pre_l) == 0) && strncmp(test->name, *test_name + pre_l, strlen(*test_name + pre_l)) == 0; if (is_suite_name_prefix || is_test_name_prefix) { munit_test_runner_ruin_suite_setup(runner, suite, &suite_setup_was_executed); munit_test_runner_run_test(runner, test, pre); if (runner->fatal_failures && (runner->report.failed != 0 || runner->report.errored != 0)) { goto cleanup; } } } } else { /* Run all tests */ munit_test_runner_ruin_suite_setup(runner, suite, &suite_setup_was_executed); munit_test_runner_run_test(runner, test, pre); } } if (runner->fatal_failures && (runner->report.failed != 0 || runner->report.errored != 0)) goto cleanup; munit_test_runner_ruin_suite_teardown(runner, suite, &suite_setup_was_executed); /* Run any child suites. */ for (child_suite = suite->suites ; child_suite != NULL && child_suite->prefix != NULL ; child_suite++) { munit_test_runner_run_suite(runner, child_suite, pre); } cleanup: munit_test_runner_ruin_suite_teardown(runner, suite, &suite_setup_was_executed); munit_maybe_free_concat(pre, prefix, suite->prefix); } static void munit_test_runner_run(MunitTestRunner* runner) { munit_test_runner_run_suite(runner, runner->suite, NULL); } static void munit_print_help(int argc, char* const argv[MUNIT_ARRAY_PARAM(argc + 1)], void* user_data, const MunitArgument arguments[]) { const MunitArgument* arg; (void) argc; printf("USAGE: %s [OPTIONS...] [TEST...]\n\n", argv[0]); puts(" --seed SEED\n" " Value used to seed the PRNG. Must be a 32-bit integer in decimal\n" " notation with no separators (commas, decimals, spaces, etc.), or\n" " hexidecimal prefixed by \"0x\".\n" " --iterations N\n" " Run each test N times. 0 means the default number.\n" " --param name value\n" " A parameter key/value pair which will be passed to any test with\n" " takes a parameter of that name. If not provided, the test will be\n" " run once for each possible parameter value.\n" " --list Write a list of all available tests.\n" " --list-params\n" " Write a list of all available tests and their possible parameters.\n" " --single Run each parameterized test in a single configuration instead of\n" " every possible combination\n" " --log-visible debug|info|warning|error\n" " --log-fatal debug|info|warning|error\n" " Set the level at which messages of different severities are visible,\n" " or cause the test to terminate.\n" #if !defined(MUNIT_NO_FORK) " --no-fork Do not execute tests in a child process. If this option is supplied\n" " and a test crashes (including by failing an assertion), no further\n" " tests will be performed.\n" #endif " --fatal-failures\n" " Stop executing tests as soon as a failure is found.\n" " --show-stderr\n" " Show data written to stderr by the tests, even if the test succeeds.\n" " --color auto|always|never\n" " Colorize (or don't) the output.\n" /* 12345678901234567890123456789012345678901234567890123456789012345678901234567890 */ " --help Print this help message and exit.\n"); #if defined(MUNIT_NL_LANGINFO) setlocale(LC_ALL, ""); fputs((strcasecmp("UTF-8", nl_langinfo(CODESET)) == 0) ? "µnit" : "munit", stdout); #else puts("munit"); #endif printf(" %d.%d.%d\n" "Full documentation at: https://nemequ.github.io/munit/\n", (MUNIT_CURRENT_VERSION >> 16) & 0xff, (MUNIT_CURRENT_VERSION >> 8) & 0xff, (MUNIT_CURRENT_VERSION >> 0) & 0xff); for (arg = arguments ; arg != NULL && arg->name != NULL ; arg++) arg->write_help(arg, user_data); } static const MunitArgument* munit_arguments_find(const MunitArgument arguments[], const char* name) { const MunitArgument* arg; for (arg = arguments ; arg != NULL && arg->name != NULL ; arg++) if (strcmp(arg->name, name) == 0) return arg; return NULL; } static void munit_suite_list_tests(const MunitSuite* suite, munit_bool show_params, const char* prefix) { size_t pre_l; char* pre = munit_maybe_concat(&pre_l, (char*) prefix, (char*) suite->prefix); const MunitTest* test; const MunitParameterEnum* params; munit_bool first; char** val; const MunitSuite* child_suite; for (test = suite->tests ; test != NULL && test->name != NULL ; test++) { if (pre != NULL) fputs(pre, stdout); puts(test->name); if (show_params) { for (params = test->parameters ; params != NULL && params->name != NULL ; params++) { fprintf(stdout, " - %s: ", params->name); if (params->values == NULL) { puts("Any"); } else { first = 1; for (val = params->values ; *val != NULL ; val++ ) { if(!first) { fputs(", ", stdout); } else { first = 0; } fputs(*val, stdout); } putc('\n', stdout); } } } } for (child_suite = suite->suites ; child_suite != NULL && child_suite->prefix != NULL ; child_suite++) { munit_suite_list_tests(child_suite, show_params, pre); } munit_maybe_free_concat(pre, prefix, suite->prefix); } static munit_bool munit_stream_supports_ansi(FILE *stream) { #if !defined(_WIN32) return isatty(fileno(stream)); #else #if !defined(__MINGW32__) size_t ansicon_size = 0; #endif if (isatty(fileno(stream))) { #if !defined(__MINGW32__) getenv_s(&ansicon_size, NULL, 0, "ANSICON"); return ansicon_size != 0; #else return getenv("ANSICON") != NULL; #endif } return 0; #endif } int munit_suite_main_custom(const MunitSuite* suite, void* user_data, int argc, char* const argv[MUNIT_ARRAY_PARAM(argc + 1)], const MunitArgument arguments[]) { int result = EXIT_FAILURE; MunitTestRunner runner; size_t parameters_size = 0; size_t tests_size = 0; int arg; char* envptr; unsigned long ts; char* endptr; unsigned long long iterations; MunitLogLevel level; const MunitArgument* argument; const char** runner_tests; unsigned int tests_run; unsigned int tests_total; runner.prefix = NULL; runner.suite = NULL; runner.current_suite = NULL; runner.tests = NULL; runner.seed = 0; runner.iterations = 0; runner.parameters = NULL; runner.single_parameter_mode = 0; runner.user_data = NULL; runner.suite_setup_data = NULL; runner.report.successful = 0; runner.report.skipped = 0; runner.report.failed = 0; runner.report.errored = 0; #if defined(MUNIT_ENABLE_TIMING) runner.report.cpu_clock = 0; runner.report.wall_clock = 0; #endif runner.colorize = 0; #if !defined(_WIN32) runner.fork = 1; #else runner.fork = 0; #endif runner.show_stderr = 0; runner.fatal_failures = 0; runner.suite = suite; runner.user_data = user_data; runner.seed = munit_rand_generate_seed(); runner.colorize = munit_stream_supports_ansi(MUNIT_OUTPUT_FILE); for (arg = 1 ; arg < argc ; arg++) { if (strncmp("--", argv[arg], 2) == 0) { if (strcmp("seed", argv[arg] + 2) == 0) { if (arg + 1 >= argc) { munit_logf_internal(MUNIT_LOG_ERROR, stderr, "%s requires an argument", argv[arg]); goto cleanup; } envptr = argv[arg + 1]; ts = strtoul(argv[arg + 1], &envptr, 0); if (*envptr != '\0' || ts > (~((munit_uint32_t) 0U))) { munit_logf_internal(MUNIT_LOG_ERROR, stderr, "invalid value ('%s') passed to %s", argv[arg + 1], argv[arg]); goto cleanup; } runner.seed = (munit_uint32_t) ts; arg++; } else if (strcmp("iterations", argv[arg] + 2) == 0) { if (arg + 1 >= argc) { munit_logf_internal(MUNIT_LOG_ERROR, stderr, "%s requires an argument", argv[arg]); goto cleanup; } endptr = argv[arg + 1]; iterations = strtoul(argv[arg + 1], &endptr, 0); if (*endptr != '\0' || iterations > UINT_MAX) { munit_logf_internal(MUNIT_LOG_ERROR, stderr, "invalid value ('%s') passed to %s", argv[arg + 1], argv[arg]); goto cleanup; } runner.iterations = (unsigned int) iterations; arg++; } else if (strcmp("param", argv[arg] + 2) == 0) { if (arg + 2 >= argc) { munit_logf_internal(MUNIT_LOG_ERROR, stderr, "%s requires two arguments", argv[arg]); goto cleanup; } runner.parameters = realloc(runner.parameters, sizeof(MunitParameter) * (parameters_size + 2)); if (runner.parameters == NULL) { munit_log_internal(MUNIT_LOG_ERROR, stderr, "failed to allocate memory"); goto cleanup; } runner.parameters[parameters_size].name = (char*) argv[arg + 1]; runner.parameters[parameters_size].value = (char*) argv[arg + 2]; parameters_size++; runner.parameters[parameters_size].name = NULL; runner.parameters[parameters_size].value = NULL; arg += 2; } else if (strcmp("color", argv[arg] + 2) == 0) { if (arg + 1 >= argc) { munit_logf_internal(MUNIT_LOG_ERROR, stderr, "%s requires an argument", argv[arg]); goto cleanup; } if (strcmp(argv[arg + 1], "always") == 0) runner.colorize = 1; else if (strcmp(argv[arg + 1], "never") == 0) runner.colorize = 0; else if (strcmp(argv[arg + 1], "auto") == 0) runner.colorize = munit_stream_supports_ansi(MUNIT_OUTPUT_FILE); else { munit_logf_internal(MUNIT_LOG_ERROR, stderr, "invalid value ('%s') passed to %s", argv[arg + 1], argv[arg]); goto cleanup; } arg++; } else if (strcmp("help", argv[arg] + 2) == 0) { munit_print_help(argc, argv, user_data, arguments); result = EXIT_SUCCESS; goto cleanup; } else if (strcmp("single", argv[arg] + 2) == 0) { runner.single_parameter_mode = 1; } else if (strcmp("show-stderr", argv[arg] + 2) == 0) { runner.show_stderr = 1; #if !defined(_WIN32) } else if (strcmp("no-fork", argv[arg] + 2) == 0) { runner.fork = 0; #endif } else if (strcmp("fatal-failures", argv[arg] + 2) == 0) { runner.fatal_failures = 1; } else if (strcmp("log-visible", argv[arg] + 2) == 0 || strcmp("log-fatal", argv[arg] + 2) == 0) { if (arg + 1 >= argc) { munit_logf_internal(MUNIT_LOG_ERROR, stderr, "%s requires an argument", argv[arg]); goto cleanup; } if (strcmp(argv[arg + 1], "debug") == 0) level = MUNIT_LOG_DEBUG; else if (strcmp(argv[arg + 1], "info") == 0) level = MUNIT_LOG_INFO; else if (strcmp(argv[arg + 1], "warning") == 0) level = MUNIT_LOG_WARNING; else if (strcmp(argv[arg + 1], "error") == 0) level = MUNIT_LOG_ERROR; else { munit_logf_internal(MUNIT_LOG_ERROR, stderr, "invalid value ('%s') passed to %s", argv[arg + 1], argv[arg]); goto cleanup; } if (strcmp("log-visible", argv[arg] + 2) == 0) munit_log_level_visible = level; else munit_log_level_fatal = level; arg++; } else if (strcmp("list", argv[arg] + 2) == 0) { munit_suite_list_tests(suite, 0, NULL); result = EXIT_SUCCESS; goto cleanup; } else if (strcmp("list-params", argv[arg] + 2) == 0) { munit_suite_list_tests(suite, 1, NULL); result = EXIT_SUCCESS; goto cleanup; } else { argument = munit_arguments_find(arguments, argv[arg] + 2); if (argument == NULL) { munit_logf_internal(MUNIT_LOG_ERROR, stderr, "unknown argument ('%s')", argv[arg]); goto cleanup; } if (!argument->parse_argument(suite, user_data, &arg, argc, argv)) goto cleanup; } } else { runner_tests = realloc((void*) runner.tests, sizeof(char*) * (tests_size + 2)); if (runner_tests == NULL) { munit_log_internal(MUNIT_LOG_ERROR, stderr, "failed to allocate memory"); goto cleanup; } runner.tests = runner_tests; runner.tests[tests_size++] = argv[arg]; runner.tests[tests_size] = NULL; } } fflush(stderr); fprintf(MUNIT_OUTPUT_FILE, "Running test suite with seed 0x%08" PRIx32 "...\n", runner.seed); munit_test_runner_run(&runner); tests_run = runner.report.successful + runner.report.failed + runner.report.errored; tests_total = tests_run + runner.report.skipped; if (tests_run == 0) { fprintf(stderr, "No tests run, %d (100%%) skipped.\n", runner.report.skipped); } else { fprintf(MUNIT_OUTPUT_FILE, "%d of %d (%0.0f%%) tests successful, %d (%0.0f%%) test skipped.\n", runner.report.successful, tests_run, (((double) runner.report.successful) / ((double) tests_run)) * 100.0, runner.report.skipped, (((double) runner.report.skipped) / ((double) tests_total)) * 100.0); } #if defined(MUNIT_FAIL_NO_TEST_RUN) if (runner.report.failed == 0 && runner.report.errored == 0 && tests_run > 0) { #else if (runner.report.failed == 0 && runner.report.errored == 0) { #endif result = EXIT_SUCCESS; } cleanup: free(runner.parameters); free((void*) runner.tests); return result; } int munit_suite_main(const MunitSuite* suite, void* user_data, int argc, char* const argv[MUNIT_ARRAY_PARAM(argc + 1)]) { return munit_suite_main_custom(suite, user_data, argc, argv, NULL); }
lock.c
#include <stdio.h> #include <omp.h> omp_lock_t my_lock; int main() { omp_init_lock(&my_lock); #pragma omp parallel num_threads(4) { int tid = omp_get_thread_num( ); int i, j; for (i = 0; i < 5; ++i) { omp_set_lock(&my_lock); printf("Thread %d - starting locked region\n", tid); printf("Thread %d - ending locked region\n", tid); omp_unset_lock(&my_lock); } } omp_destroy_lock(&my_lock); }
mixed_tentusscher_myo_epi_2004.c
#include <stdio.h> #include "mixed_tentusscher_myo_epi_2004.h" GET_CELL_MODEL_DATA(init_cell_model_data) { if(get_initial_v) cell_model->initial_v = INITIAL_V; if(get_neq) cell_model->number_of_ode_equations = NEQ; } SET_ODE_INITIAL_CONDITIONS_CPU(set_model_initial_conditions_cpu) { static bool first_call = true; if(first_call) { print_to_stdout_and_file("Using mixed version of TenTusscher 2004 myocardium + epicardium CPU model\n"); first_call = false; } // Get the mapping array uint32_t *mapping = NULL; if(extra_data) { mapping = (uint32_t*)extra_data; } else { print_to_stderr_and_file_and_exit("You need to specify a mask function when using a mixed model!\n"); } // Initial conditions for TenTusscher myocardium if (mapping[sv_id] == 0) { sv[0] = INITIAL_V; // V; millivolt sv[1] = 0.f; //M sv[2] = 0.75; //H sv[3] = 0.75f; //J sv[4] = 0.f; //Xr1 sv[5] = 1.f; //Xr2 sv[6] = 0.f; //Xs sv[7] = 1.f; //S sv[8] = 0.f; //R sv[9] = 0.f; //D sv[10] = 1.f; //F sv[11] = 1.f; //FCa sv[12] = 1.f; //G sv[13] = 0.0002; //Cai sv[14] = 0.2f; //CaSR sv[15] = 11.6f; //Nai sv[16] = 138.3f; //Ki } // Initial conditions for TenTusscher epicardium else { sv[0] = INITIAL_V; // V; millivolt sv[1] = 0.f; //M sv[2] = 0.75; //H sv[3] = 0.75f; //J sv[4] = 0.f; //Xr1 sv[5] = 1.f; //Xr2 sv[6] = 0.f; //Xs sv[7] = 1.f; //S sv[8] = 0.f; //R sv[9] = 0.f; //D sv[10] = 1.f; //F sv[11] = 1.f; //FCa sv[12] = 1.f; //G sv[13] = 0.0002; //Cai sv[14] = 0.2f; //CaSR sv[15] = 11.6f; //Nai sv[16] = 138.3f; //Ki } } SOLVE_MODEL_ODES_CPU(solve_model_odes_cpu) { // Get the mapping array uint32_t *mapping = NULL; if(extra_data) { mapping = (uint32_t*)extra_data; } else { print_to_stderr_and_file_and_exit("You need to specify a mask function when using a mixed model!\n"); } uint32_t sv_id; int i; #pragma omp parallel for private(sv_id) for (i = 0; i < num_cells_to_solve; i++) { if(cells_to_solve) sv_id = cells_to_solve[i]; else sv_id = (uint32_t )i; for (int j = 0; j < num_steps; ++j) { if (mapping[i] == 0) solve_model_ode_cpu_myo(dt, sv + (sv_id * NEQ), stim_currents[i]); else solve_model_ode_cpu_epi(dt, sv + (sv_id * NEQ), stim_currents[i]); } } } void solve_model_ode_cpu_myo (real dt, real *sv, real stim_current) { real rY[NEQ], rDY[NEQ]; for(int i = 0; i < NEQ; i++) rY[i] = sv[i]; RHS_cpu_myo(rY, rDY, stim_current, dt); for(int i = 0; i < NEQ; i++) sv[i] = rDY[i]; } void RHS_cpu_myo(const real *sv, real *rDY_, real stim_current, real dt) { // State variables real svolt = sv[0]; real sm = sv[1]; real sh = sv[2]; real sj = sv[3]; real sxr1 = sv[4]; real sxr2 = sv[5]; real sxs = sv[6]; real ss = sv[7]; real sr = sv[8]; real sd = sv[9]; real sf = sv[10]; real sfca = sv[11]; real sg = sv[12]; real Cai = sv[13]; real CaSR = sv[14]; real Nai = sv[15]; real Ki = sv[16]; //External concentrations real Ko=5.4; real Cao=2.0; real Nao=140.0; //Intracellular volumes real Vc=0.016404; real Vsr=0.001094; //Calcium dynamics real Bufc=0.15f; real Kbufc=0.001f; real Bufsr=10.f; real Kbufsr=0.3f; real taufca=2.f; real taug=2.f; real Vmaxup=0.000425f; real Kup=0.00025f; //Constants const real R = 8314.472f; const real F = 96485.3415f; const real T =310.0f; real RTONF =(R*T)/F; //Cellular capacitance real CAPACITANCE=0.185; //Parameters for currents //Parameters for IKr real Gkr=0.096; //Parameters for Iks real pKNa=0.03; // [!] Myocardium cell real Gks=0.062; //Parameters for Ik1 real GK1=5.405; //Parameters for Ito // [!] Myocardium cell real Gto=0.294; //Parameters for INa real GNa=14.838; //Parameters for IbNa real GbNa=0.00029; //Parameters for INaK real KmK=1.0; real KmNa=40.0; real knak=1.362; //Parameters for ICaL real GCaL=0.000175; //Parameters for IbCa real GbCa=0.000592; //Parameters for INaCa real knaca=1000; real KmNai=87.5; real KmCa=1.38; real ksat=0.1; real n=0.35; //Parameters for IpCa real GpCa=0.825; real KpCa=0.0005; //Parameters for IpK; real GpK=0.0146; real IKr; real IKs; real IK1; real Ito; real INa; real IbNa; real ICaL; real IbCa; real INaCa; real IpCa; real IpK; real INaK; real Irel; real Ileak; real dNai; real dKi; real dCai; real dCaSR; real A; // real BufferFactorc; // real BufferFactorsr; real SERCA; real Caisquare; real CaSRsquare; real CaCurrent; real CaSRCurrent; real fcaold; real gold; real Ek; real Ena; real Eks; real Eca; real CaCSQN; real bjsr; real cjsr; real CaBuf; real bc; real cc; real Ak1; real Bk1; real rec_iK1; real rec_ipK; real rec_iNaK; real AM; real BM; real AH_1; real BH_1; real AH_2; real BH_2; real AJ_1; real BJ_1; real AJ_2; real BJ_2; real M_INF; real H_INF; real J_INF; real TAU_M; real TAU_H; real TAU_J; real axr1; real bxr1; real axr2; real bxr2; real Xr1_INF; real Xr2_INF; real TAU_Xr1; real TAU_Xr2; real Axs; real Bxs; real Xs_INF; real TAU_Xs; real R_INF; real TAU_R; real S_INF; real TAU_S; real Ad; real Bd; real Cd; real TAU_D; real D_INF; real TAU_F; real F_INF; real FCa_INF; real G_INF; real inverseVcF2=1/(2*Vc*F); real inverseVcF=1./(Vc*F); real Kupsquare=Kup*Kup; // real BufcKbufc=Bufc*Kbufc; // real Kbufcsquare=Kbufc*Kbufc; // real Kbufc2=2*Kbufc; // real BufsrKbufsr=Bufsr*Kbufsr; // const real Kbufsrsquare=Kbufsr*Kbufsr; // const real Kbufsr2=2*Kbufsr; const real exptaufca=exp(-dt/taufca); const real exptaug=exp(-dt/taug); real sItot; //Needed to compute currents Ek=RTONF*(log((Ko/Ki))); Ena=RTONF*(log((Nao/Nai))); Eks=RTONF*(log((Ko+pKNa*Nao)/(Ki+pKNa*Nai))); Eca=0.5*RTONF*(log((Cao/Cai))); Ak1=0.1/(1.+exp(0.06*(svolt-Ek-200))); Bk1=(3.*exp(0.0002*(svolt-Ek+100))+ exp(0.1*(svolt-Ek-10)))/(1.+exp(-0.5*(svolt-Ek))); rec_iK1=Ak1/(Ak1+Bk1); rec_iNaK=(1./(1.+0.1245*exp(-0.1*svolt*F/(R*T))+0.0353*exp(-svolt*F/(R*T)))); rec_ipK=1./(1.+exp((25-svolt)/5.98)); //Compute currents INa=GNa*sm*sm*sm*sh*sj*(svolt-Ena); ICaL=GCaL*sd*sf*sfca*4*svolt*(F*F/(R*T))* (exp(2*svolt*F/(R*T))*Cai-0.341*Cao)/(exp(2*svolt*F/(R*T))-1.); Ito=Gto*sr*ss*(svolt-Ek); IKr=Gkr*sqrt(Ko/5.4)*sxr1*sxr2*(svolt-Ek); IKs=Gks*sxs*sxs*(svolt-Eks); IK1=GK1*rec_iK1*(svolt-Ek); INaCa=knaca*(1./(KmNai*KmNai*KmNai+Nao*Nao*Nao))*(1./(KmCa+Cao))* (1./(1+ksat*exp((n-1)*svolt*F/(R*T))))* (exp(n*svolt*F/(R*T))*Nai*Nai*Nai*Cao- exp((n-1)*svolt*F/(R*T))*Nao*Nao*Nao*Cai*2.5); INaK=knak*(Ko/(Ko+KmK))*(Nai/(Nai+KmNa))*rec_iNaK; IpCa=GpCa*Cai/(KpCa+Cai); IpK=GpK*rec_ipK*(svolt-Ek); IbNa=GbNa*(svolt-Ena); IbCa=GbCa*(svolt-Eca); //Determine total current (sItot) = IKr + IKs + IK1 + Ito + INa + IbNa + ICaL + IbCa + INaK + INaCa + IpCa + IpK + stim_current; //update concentrations Caisquare=Cai*Cai; CaSRsquare=CaSR*CaSR; CaCurrent=-(ICaL+IbCa+IpCa-2.0f*INaCa)*inverseVcF2*CAPACITANCE; A=0.016464f*CaSRsquare/(0.0625f+CaSRsquare)+0.008232f; Irel=A*sd*sg; Ileak=0.00008f*(CaSR-Cai); SERCA=Vmaxup/(1.f+(Kupsquare/Caisquare)); CaSRCurrent=SERCA-Irel-Ileak; CaCSQN=Bufsr*CaSR/(CaSR+Kbufsr); dCaSR=dt*(Vc/Vsr)*CaSRCurrent; bjsr=Bufsr-CaCSQN-dCaSR-CaSR+Kbufsr; cjsr=Kbufsr*(CaCSQN+dCaSR+CaSR); CaSR=(sqrt(bjsr*bjsr+4.*cjsr)-bjsr)/2.; CaBuf=Bufc*Cai/(Cai+Kbufc); dCai=dt*(CaCurrent-CaSRCurrent); bc=Bufc-CaBuf-dCai-Cai+Kbufc; cc=Kbufc*(CaBuf+dCai+Cai); Cai=(sqrt(bc*bc+4*cc)-bc)/2; dNai=-(INa+IbNa+3*INaK+3*INaCa)*inverseVcF*CAPACITANCE; Nai+=dt*dNai; dKi=-(stim_current+IK1+Ito+IKr+IKs-2*INaK+IpK)*inverseVcF*CAPACITANCE; Ki+=dt*dKi; //compute steady state values and time constants AM=1./(1.+exp((-60.-svolt)/5.)); BM=0.1/(1.+exp((svolt+35.)/5.))+0.10/(1.+exp((svolt-50.)/200.)); TAU_M=AM*BM; M_INF=1./((1.+exp((-56.86-svolt)/9.03))*(1.+exp((-56.86-svolt)/9.03))); if (svolt>=-40.) { AH_1=0.; BH_1=(0.77/(0.13*(1.+exp(-(svolt+10.66)/11.1)))); TAU_H= 1.0/(AH_1+BH_1); } else { AH_2=(0.057*exp(-(svolt+80.)/6.8)); BH_2=(2.7*exp(0.079*svolt)+(3.1e5)*exp(0.3485*svolt)); TAU_H=1.0/(AH_2+BH_2); } H_INF=1./((1.+exp((svolt+71.55)/7.43))*(1.+exp((svolt+71.55)/7.43))); if(svolt>=-40.) { AJ_1=0.; BJ_1=(0.6*exp((0.057)*svolt)/(1.+exp(-0.1*(svolt+32.)))); TAU_J= 1.0/(AJ_1+BJ_1); } else { AJ_2=(((-2.5428e4)*exp(0.2444*svolt)-(6.948e-6)* exp(-0.04391*svolt))*(svolt+37.78)/ (1.+exp(0.311*(svolt+79.23)))); BJ_2=(0.02424*exp(-0.01052*svolt)/(1.+exp(-0.1378*(svolt+40.14)))); TAU_J= 1.0/(AJ_2+BJ_2); } J_INF=H_INF; Xr1_INF=1./(1.+exp((-26.-svolt)/7.)); axr1=450./(1.+exp((-45.-svolt)/10.)); bxr1=6./(1.+exp((svolt-(-30.))/11.5)); TAU_Xr1=axr1*bxr1; Xr2_INF=1./(1.+exp((svolt-(-88.))/24.)); axr2=3./(1.+exp((-60.-svolt)/20.)); bxr2=1.12/(1.+exp((svolt-60.)/20.)); TAU_Xr2=axr2*bxr2; Xs_INF=1./(1.+exp((-5.-svolt)/14.)); Axs=1100./(sqrt(1.+exp((-10.-svolt)/6))); Bxs=1./(1.+exp((svolt-60.)/20.)); TAU_Xs=Axs*Bxs; // [!] Myocardium cell R_INF=1./(1.+exp((20-svolt)/6.)); S_INF=1./(1.+exp((svolt+20)/5.)); TAU_R=9.5*exp(-(svolt+40.)*(svolt+40.)/1800.)+0.8; TAU_S=85.*exp(-(svolt+45.)*(svolt+45.)/320.)+5./(1.+exp((svolt-20.)/5.))+3.; D_INF=1./(1.+exp((-5-svolt)/7.5)); Ad=1.4/(1.+exp((-35-svolt)/13))+0.25; Bd=1.4/(1.+exp((svolt+5)/5)); Cd=1./(1.+exp((50-svolt)/20)); TAU_D=Ad*Bd+Cd; F_INF=1./(1.+exp((svolt+20)/7)); //TAU_F=1125*exp(-(svolt+27)*(svolt+27)/300)+80+165/(1.+exp((25-svolt)/10)); TAU_F=1125*exp(-(svolt+27)*(svolt+27)/240)+80+165/(1.+exp((25-svolt)/10)); // Updated from CellML FCa_INF=(1./(1.+pow((Cai/0.000325),8))+ 0.1/(1.+exp((Cai-0.0005)/0.0001))+ 0.20/(1.+exp((Cai-0.00075)/0.0008))+ 0.23 )/1.46; if(Cai<0.00035) G_INF=1./(1.+pow((Cai/0.00035),6)); else G_INF=1./(1.+pow((Cai/0.00035),16)); //Update gates rDY_[1] = M_INF-(M_INF-sm)*exp(-dt/TAU_M); rDY_[2] = H_INF-(H_INF-sh)*exp(-dt/TAU_H); rDY_[3] = J_INF-(J_INF-sj)*exp(-dt/TAU_J); rDY_[4] = Xr1_INF-(Xr1_INF-sxr1)*exp(-dt/TAU_Xr1); rDY_[5] = Xr2_INF-(Xr2_INF-sxr2)*exp(-dt/TAU_Xr2); rDY_[6] = Xs_INF-(Xs_INF-sxs)*exp(-dt/TAU_Xs); rDY_[7] = S_INF-(S_INF-ss)*exp(-dt/TAU_S); rDY_[8] = R_INF-(R_INF-sr)*exp(-dt/TAU_R); rDY_[9] = D_INF-(D_INF-sd)*exp(-dt/TAU_D); rDY_[10] = F_INF-(F_INF-sf)*exp(-dt/TAU_F); fcaold= sfca; sfca = FCa_INF-(FCa_INF-sfca)*exptaufca; if(sfca>fcaold && (svolt)>-37.0) sfca = fcaold; gold = sg; sg = G_INF-(G_INF-sg)*exptaug; if(sg>gold && (svolt)>-37.0) sg=gold; //update voltage rDY_[0] = svolt + dt*(-sItot); rDY_[11] = sfca; rDY_[12] = sg; rDY_[13] = Cai; rDY_[14] = CaSR; rDY_[15] = Nai; rDY_[16] = Ki; } void solve_model_ode_cpu_epi (real dt, real *sv, real stim_current) { real rY[NEQ], rDY[NEQ]; for(int i = 0; i < NEQ; i++) rY[i] = sv[i]; RHS_cpu_epi(rY, rDY, stim_current, dt); for(int i = 0; i < NEQ; i++) sv[i] = rDY[i]; } void RHS_cpu_epi(const real *sv, real *rDY_, real stim_current, real dt) { // State variables real svolt = sv[0]; real sm = sv[1]; real sh = sv[2]; real sj = sv[3]; real sxr1 = sv[4]; real sxr2 = sv[5]; real sxs = sv[6]; real ss = sv[7]; real sr = sv[8]; real sd = sv[9]; real sf = sv[10]; real sfca = sv[11]; real sg = sv[12]; real Cai = sv[13]; real CaSR = sv[14]; real Nai = sv[15]; real Ki = sv[16]; //External concentrations real Ko=5.4; real Cao=2.0; real Nao=140.0; //Intracellular volumes real Vc=0.016404; real Vsr=0.001094; //Calcium dynamics real Bufc=0.15f; real Kbufc=0.001f; real Bufsr=10.f; real Kbufsr=0.3f; real taufca=2.f; real taug=2.f; real Vmaxup=0.000425f; real Kup=0.00025f; //Constants const real R = 8314.472f; const real F = 96485.3415f; const real T =310.0f; real RTONF =(R*T)/F; //Cellular capacitance real CAPACITANCE=0.185; //Parameters for currents //Parameters for IKr real Gkr=0.096; //Parameters for Iks real pKNa=0.03; // [!] Epicardium cell real Gks=0.245; //Parameters for Ik1 real GK1=5.405; //Parameters for Ito // [!] Epicardium cell real Gto=0.294; //Parameters for INa real GNa=14.838; //Parameters for IbNa real GbNa=0.00029; //Parameters for INaK real KmK=1.0; real KmNa=40.0; real knak=1.362; //Parameters for ICaL real GCaL=0.000175; //Parameters for IbCa real GbCa=0.000592; //Parameters for INaCa real knaca=1000; real KmNai=87.5; real KmCa=1.38; real ksat=0.1; real n=0.35; //Parameters for IpCa real GpCa=0.825; real KpCa=0.0005; //Parameters for IpK; real GpK=0.0146; real IKr; real IKs; real IK1; real Ito; real INa; real IbNa; real ICaL; real IbCa; real INaCa; real IpCa; real IpK; real INaK; real Irel; real Ileak; real dNai; real dKi; real dCai; real dCaSR; real A; // real BufferFactorc; // real BufferFactorsr; real SERCA; real Caisquare; real CaSRsquare; real CaCurrent; real CaSRCurrent; real fcaold; real gold; real Ek; real Ena; real Eks; real Eca; real CaCSQN; real bjsr; real cjsr; real CaBuf; real bc; real cc; real Ak1; real Bk1; real rec_iK1; real rec_ipK; real rec_iNaK; real AM; real BM; real AH_1; real BH_1; real AH_2; real BH_2; real AJ_1; real BJ_1; real AJ_2; real BJ_2; real M_INF; real H_INF; real J_INF; real TAU_M; real TAU_H; real TAU_J; real axr1; real bxr1; real axr2; real bxr2; real Xr1_INF; real Xr2_INF; real TAU_Xr1; real TAU_Xr2; real Axs; real Bxs; real Xs_INF; real TAU_Xs; real R_INF; real TAU_R; real S_INF; real TAU_S; real Ad; real Bd; real Cd; real TAU_D; real D_INF; real TAU_F; real F_INF; real FCa_INF; real G_INF; real inverseVcF2=1/(2*Vc*F); real inverseVcF=1./(Vc*F); real Kupsquare=Kup*Kup; // real BufcKbufc=Bufc*Kbufc; // real Kbufcsquare=Kbufc*Kbufc; // real Kbufc2=2*Kbufc; // real BufsrKbufsr=Bufsr*Kbufsr; // const real Kbufsrsquare=Kbufsr*Kbufsr; // const real Kbufsr2=2*Kbufsr; const real exptaufca=exp(-dt/taufca); const real exptaug=exp(-dt/taug); real sItot; //Needed to compute currents Ek=RTONF*(log((Ko/Ki))); Ena=RTONF*(log((Nao/Nai))); Eks=RTONF*(log((Ko+pKNa*Nao)/(Ki+pKNa*Nai))); Eca=0.5*RTONF*(log((Cao/Cai))); Ak1=0.1/(1.+exp(0.06*(svolt-Ek-200))); Bk1=(3.*exp(0.0002*(svolt-Ek+100))+ exp(0.1*(svolt-Ek-10)))/(1.+exp(-0.5*(svolt-Ek))); rec_iK1=Ak1/(Ak1+Bk1); rec_iNaK=(1./(1.+0.1245*exp(-0.1*svolt*F/(R*T))+0.0353*exp(-svolt*F/(R*T)))); rec_ipK=1./(1.+exp((25-svolt)/5.98)); //Compute currents INa=GNa*sm*sm*sm*sh*sj*(svolt-Ena); ICaL=GCaL*sd*sf*sfca*4*svolt*(F*F/(R*T))* (exp(2*svolt*F/(R*T))*Cai-0.341*Cao)/(exp(2*svolt*F/(R*T))-1.); Ito=Gto*sr*ss*(svolt-Ek); IKr=Gkr*sqrt(Ko/5.4)*sxr1*sxr2*(svolt-Ek); IKs=Gks*sxs*sxs*(svolt-Eks); IK1=GK1*rec_iK1*(svolt-Ek); INaCa=knaca*(1./(KmNai*KmNai*KmNai+Nao*Nao*Nao))*(1./(KmCa+Cao))* (1./(1+ksat*exp((n-1)*svolt*F/(R*T))))* (exp(n*svolt*F/(R*T))*Nai*Nai*Nai*Cao- exp((n-1)*svolt*F/(R*T))*Nao*Nao*Nao*Cai*2.5); INaK=knak*(Ko/(Ko+KmK))*(Nai/(Nai+KmNa))*rec_iNaK; IpCa=GpCa*Cai/(KpCa+Cai); IpK=GpK*rec_ipK*(svolt-Ek); IbNa=GbNa*(svolt-Ena); IbCa=GbCa*(svolt-Eca); //Determine total current (sItot) = IKr + IKs + IK1 + Ito + INa + IbNa + ICaL + IbCa + INaK + INaCa + IpCa + IpK + stim_current; //update concentrations Caisquare=Cai*Cai; CaSRsquare=CaSR*CaSR; CaCurrent=-(ICaL+IbCa+IpCa-2.0f*INaCa)*inverseVcF2*CAPACITANCE; A=0.016464f*CaSRsquare/(0.0625f+CaSRsquare)+0.008232f; Irel=A*sd*sg; Ileak=0.00008f*(CaSR-Cai); SERCA=Vmaxup/(1.f+(Kupsquare/Caisquare)); CaSRCurrent=SERCA-Irel-Ileak; CaCSQN=Bufsr*CaSR/(CaSR+Kbufsr); dCaSR=dt*(Vc/Vsr)*CaSRCurrent; bjsr=Bufsr-CaCSQN-dCaSR-CaSR+Kbufsr; cjsr=Kbufsr*(CaCSQN+dCaSR+CaSR); CaSR=(sqrt(bjsr*bjsr+4.*cjsr)-bjsr)/2.; CaBuf=Bufc*Cai/(Cai+Kbufc); dCai=dt*(CaCurrent-CaSRCurrent); bc=Bufc-CaBuf-dCai-Cai+Kbufc; cc=Kbufc*(CaBuf+dCai+Cai); Cai=(sqrt(bc*bc+4*cc)-bc)/2; dNai=-(INa+IbNa+3*INaK+3*INaCa)*inverseVcF*CAPACITANCE; Nai+=dt*dNai; dKi=-(stim_current+IK1+Ito+IKr+IKs-2*INaK+IpK)*inverseVcF*CAPACITANCE; Ki+=dt*dKi; //compute steady state values and time constants AM=1./(1.+exp((-60.-svolt)/5.)); BM=0.1/(1.+exp((svolt+35.)/5.))+0.10/(1.+exp((svolt-50.)/200.)); TAU_M=AM*BM; M_INF=1./((1.+exp((-56.86-svolt)/9.03))*(1.+exp((-56.86-svolt)/9.03))); if (svolt>=-40.) { AH_1=0.; BH_1=(0.77/(0.13*(1.+exp(-(svolt+10.66)/11.1)))); TAU_H= 1.0/(AH_1+BH_1); } else { AH_2=(0.057*exp(-(svolt+80.)/6.8)); BH_2=(2.7*exp(0.079*svolt)+(3.1e5)*exp(0.3485*svolt)); TAU_H=1.0/(AH_2+BH_2); } H_INF=1./((1.+exp((svolt+71.55)/7.43))*(1.+exp((svolt+71.55)/7.43))); if(svolt>=-40.) { AJ_1=0.; BJ_1=(0.6*exp((0.057)*svolt)/(1.+exp(-0.1*(svolt+32.)))); TAU_J= 1.0/(AJ_1+BJ_1); } else { AJ_2=(((-2.5428e4)*exp(0.2444*svolt)-(6.948e-6)* exp(-0.04391*svolt))*(svolt+37.78)/ (1.+exp(0.311*(svolt+79.23)))); BJ_2=(0.02424*exp(-0.01052*svolt)/(1.+exp(-0.1378*(svolt+40.14)))); TAU_J= 1.0/(AJ_2+BJ_2); } J_INF=H_INF; Xr1_INF=1./(1.+exp((-26.-svolt)/7.)); axr1=450./(1.+exp((-45.-svolt)/10.)); bxr1=6./(1.+exp((svolt-(-30.))/11.5)); TAU_Xr1=axr1*bxr1; Xr2_INF=1./(1.+exp((svolt-(-88.))/24.)); axr2=3./(1.+exp((-60.-svolt)/20.)); bxr2=1.12/(1.+exp((svolt-60.)/20.)); TAU_Xr2=axr2*bxr2; Xs_INF=1./(1.+exp((-5.-svolt)/14.)); Axs=1100./(sqrt(1.+exp((-10.-svolt)/6))); Bxs=1./(1.+exp((svolt-60.)/20.)); TAU_Xs=Axs*Bxs; R_INF=1./(1.+exp((20-svolt)/6.)); S_INF=1./(1.+exp((svolt+20)/5.)); TAU_R=9.5*exp(-(svolt+40.)*(svolt+40.)/1800.)+0.8; TAU_S=85.*exp(-(svolt+45.)*(svolt+45.)/320.)+5./(1.+exp((svolt-20.)/5.))+3.; D_INF=1./(1.+exp((-5-svolt)/7.5)); Ad=1.4/(1.+exp((-35-svolt)/13))+0.25; Bd=1.4/(1.+exp((svolt+5)/5)); Cd=1./(1.+exp((50-svolt)/20)); TAU_D=Ad*Bd+Cd; F_INF=1./(1.+exp((svolt+20)/7)); //TAU_F=1125*exp(-(svolt+27)*(svolt+27)/300)+80+165/(1.+exp((25-svolt)/10)); TAU_F=1125*exp(-(svolt+27)*(svolt+27)/240)+80+165/(1.+exp((25-svolt)/10)); // Updated from CellML FCa_INF=(1./(1.+pow((Cai/0.000325),8))+ 0.1/(1.+exp((Cai-0.0005)/0.0001))+ 0.20/(1.+exp((Cai-0.00075)/0.0008))+ 0.23 )/1.46; if(Cai<0.00035) G_INF=1./(1.+pow((Cai/0.00035),6)); else G_INF=1./(1.+pow((Cai/0.00035),16)); //Update gates rDY_[1] = M_INF-(M_INF-sm)*exp(-dt/TAU_M); rDY_[2] = H_INF-(H_INF-sh)*exp(-dt/TAU_H); rDY_[3] = J_INF-(J_INF-sj)*exp(-dt/TAU_J); rDY_[4] = Xr1_INF-(Xr1_INF-sxr1)*exp(-dt/TAU_Xr1); rDY_[5] = Xr2_INF-(Xr2_INF-sxr2)*exp(-dt/TAU_Xr2); rDY_[6] = Xs_INF-(Xs_INF-sxs)*exp(-dt/TAU_Xs); rDY_[7] = S_INF-(S_INF-ss)*exp(-dt/TAU_S); rDY_[8] = R_INF-(R_INF-sr)*exp(-dt/TAU_R); rDY_[9] = D_INF-(D_INF-sd)*exp(-dt/TAU_D); rDY_[10] = F_INF-(F_INF-sf)*exp(-dt/TAU_F); fcaold= sfca; sfca = FCa_INF-(FCa_INF-sfca)*exptaufca; if(sfca>fcaold && (svolt)>-37.0) sfca = fcaold; gold = sg; sg = G_INF-(G_INF-sg)*exptaug; if(sg>gold && (svolt)>-37.0) sg=gold; //update voltage rDY_[0] = svolt + dt*(-sItot); rDY_[11] = sfca; rDY_[12] = sg; rDY_[13] = Cai; rDY_[14] = CaSR; rDY_[15] = Nai; rDY_[16] = Ki; }
symv_c_csr_n_lo_conj.c
#include "alphasparse/kernel.h" #include "alphasparse/util.h" #include "alphasparse/opt.h" #ifdef _OPENMP #include <omp.h> #endif #include <memory.h> #include<stdlib.h> static alphasparse_status_t symv_x_csr_n_lo_conj_omp(const ALPHA_Number alpha, const ALPHA_SPMAT_CSR *A, const ALPHA_Number *x, const ALPHA_Number beta, ALPHA_Number *y) { const ALPHA_INT m = A->rows; const ALPHA_INT n = A->cols; if(m != n) return ALPHA_SPARSE_STATUS_INVALID_VALUE; ALPHA_INT num_threads = alpha_get_thread_num(); #ifdef _OPENMP #pragma omp parallel for num_threads(num_threads) #endif for(ALPHA_INT i = 0; i < m; ++i) { alpha_mule(y[i], beta); } ALPHA_Number **y_local = alpha_memalign(num_threads * sizeof(ALPHA_Number *), DEFAULT_ALIGNMENT); for(ALPHA_INT i = 0; i < num_threads; i++) { y_local[i] = alpha_memalign(m * sizeof(ALPHA_Number), DEFAULT_ALIGNMENT); memset(y_local[i], '\0', sizeof(ALPHA_Number) * m); } #ifdef _OPENMP #pragma omp parallel for num_threads(num_threads) #endif for(ALPHA_INT i = 0; i < m; ++i) { ALPHA_INT tid = alpha_get_thread_id(); ALPHA_Number tmp; for(ALPHA_INT ai = A->rows_start[i]; ai < A->rows_end[i]; ++ai) { const ALPHA_INT col = A->col_indx[ai]; if(col > i) { continue; } else if(col == i) { alpha_setzero(tmp); cmp_conj(tmp, A->values[ai]); alpha_mul(tmp, alpha, tmp); alpha_madde(y_local[tid][i], tmp, x[col]); } else { alpha_setzero(tmp); cmp_conj(tmp, A->values[ai]); alpha_mul(tmp, alpha, tmp); alpha_madde(y_local[tid][col], tmp, x[i]); alpha_madde(y_local[tid][i], tmp, x[col]); } } } #ifdef _OPENMP #pragma omp parallel for num_threads(num_threads) #endif for(ALPHA_INT row = 0; row < m; row++) for(ALPHA_INT i = 0; i < num_threads; i++) alpha_adde(y[row], y_local[i][row]); for(ALPHA_INT i = 0; i < num_threads; i++) { alpha_free(y_local[i]); } alpha_free(y_local); return ALPHA_SPARSE_STATUS_SUCCESS; } alphasparse_status_t ONAME(const ALPHA_Number alpha, const ALPHA_SPMAT_CSR *A, const ALPHA_Number *x, const ALPHA_Number beta, ALPHA_Number *y) { return symv_x_csr_n_lo_conj_omp(alpha, A, x, beta, y); }
rose_v1_break2.c
#include <omp.h> int i; int j; int a[100][100]; void foo() { #pragma omp parallel for private (i) for (i = 0; i <= 99; i += 1) { for (j = 0; j <= 99; j += 1) { a[i][j] = a[i][j] + 1; if (a[i][j] == 100) break; } } }
postgres_fmt_plug.c
/* PostgreSQL MD5 challenge-response cracker patch for JtR. Hacked together * during October of 2012 by Dhiru Kholia <dhiru.kholia at gmail.com>. * * Use Ettercap to get PostgreSQL MD5 challenge-response pairs in JtR format. * E.g. ettercap -Tq -r /home/user/sample.pcap * * Input format: * $postgres$user*salt*hash * * This software is Copyright (c) 2012, Dhiru Kholia <dhiru.kholia at gmail.com> * and Copyright magnum 2013, * 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_postgres; #elif FMT_REGISTERS_H john_register_one(&fmt_postgres); #else #include <string.h> #include <errno.h> #ifdef _OPENMP static int omp_t = 1; #include <omp.h> #ifndef OMP_SCALE #define OMP_SCALE 2048 // scaled on K8-dual HT #endif #endif #include "md5.h" #include "arch.h" #include "misc.h" #include "common.h" #include "formats.h" #include "params.h" #include "options.h" #include "memdbg.h" #define FORMAT_LABEL "postgres" #define FORMAT_NAME "PostgreSQL C/R" #define FORMAT_TAG "$postgres$" #define FORMAT_TAG_LEN (sizeof(FORMAT_TAG)-1) #define FORMAT_TAG2 "$postgre$" #define FORMAT_TAG2_LEN (sizeof(FORMAT_TAG2)-1) #define ALGORITHM_NAME "MD5 32/" ARCH_BITS_STR #define BENCHMARK_COMMENT "" #define BENCHMARK_LENGTH -1 #define PLAINTEXT_LENGTH 32 #define BINARY_SIZE 16 #define BINARY_ALIGN MEM_ALIGN_WORD #define SALT_SIZE sizeof(struct custom_salt) #define SALT_ALIGN MEM_ALIGN_NONE #define MAX_USERNAME_LEN 64 #define MIN_KEYS_PER_CRYPT 1 #define MAX_KEYS_PER_CRYPT 1 static struct fmt_tests postgres_tests[] = { {"$postgres$postgres*f063f05d*1d586cc8d137e5f1733f234d224393e8", "openwall"}, {"$postgres$postgres*c31803a2*1c4e11fb51835c3bbe9851ec91ec1375", "password"}, /* $postgre$ is supported but deprecated */ {"$postgre$postgres*684697c8*bf2a64f35feba7bf1b633d60393c1356", "openwall"}, /* $postgres$ with longer user name */ {"$postgres$Twelve_chars*55393156*c01df9affa7573ef32ec143759f3e005", "HookFish__2"}, {"$postgres$postgres*65687433*b782eca219ad84b58f26d25e19a1bbc9", "thisisalongstring"}, {"$postgres$postgres*33374273*77e0016f1b92cdea7291ab0ed21798b8", "string with space"}, {"$postgres$postgres*6f734f37*d5451e93f6ac9a0d30336ec106e91cf5", "123456789"}, {"$postgres$postgres*3348654b*0f0f46a3dfebf45f4320d2edeabc318f", ""}, {NULL} }; static char (*saved_key)[PLAINTEXT_LENGTH + 1]; static uint32_t (*crypt_out)[BINARY_SIZE / sizeof(uint32_t)]; static struct custom_salt { unsigned char user[MAX_USERNAME_LEN + 1]; unsigned char salt[4]; } *cur_salt; static void init(struct fmt_main *self) { #ifdef _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(self->params.max_keys_per_crypt, sizeof(*saved_key)); crypt_out = mem_calloc(self->params.max_keys_per_crypt, sizeof(*crypt_out)); } static void done(void) { MEM_FREE(crypt_out); MEM_FREE(saved_key); } static int valid(char *ciphertext, struct fmt_main *self) { const char *p; int extra; if (strncmp(ciphertext, FORMAT_TAG, FORMAT_TAG_LEN)) return 0; /* Check hash */ if (!(p = strrchr(ciphertext, '*'))) return 0; if (hexlenl(&p[1], &extra) != 2*BINARY_SIZE || extra) return 0; /* Check salt */ p -= 9; if (*p != '*') return 0; if (hexlenl(&p[1], 0) != 8) return 0; /* Check username length */ if (p - ciphertext - FORMAT_TAG_LEN > MAX_USERNAME_LEN) return 0; return 1; } static char *prepare(char *split_fields[10], struct fmt_main *self) { static char out[FORMAT_TAG_LEN + sizeof(struct custom_salt) + 2*BINARY_SIZE +2+1]; /* Replace deprecated tag */ if (*split_fields[1] && !strncmp(split_fields[1], FORMAT_TAG2, FORMAT_TAG2_LEN)) { snprintf(out, sizeof(out), "%s%s", FORMAT_TAG, &split_fields[1][FORMAT_TAG2_LEN]); if (valid(out, self)) return out; } return split_fields[1]; } static void *get_salt(char *ciphertext) { char *ctcopy = strdup(ciphertext); char *keeptr = ctcopy; char *p; int i; static struct custom_salt cs; ctcopy += FORMAT_TAG_LEN; /* skip over "$postgres$" */ p = strtokm(ctcopy, "*"); memset(&cs, 0, sizeof(cs)); strnzcpy((char*)cs.user, p, MAX_USERNAME_LEN + 1); p = strtokm(NULL, "*"); for (i = 0; i < 4; i++) cs.salt[i] = atoi16[ARCH_INDEX(p[i * 2])] * 16 + atoi16[ARCH_INDEX(p[i * 2 + 1])]; MEM_FREE(keeptr); return (void *)&cs; } static void *get_binary(char *ciphertext) { static union { unsigned char c[BINARY_SIZE]; ARCH_WORD dummy; } buf; unsigned char *out = buf.c; char *p; int i; p = strrchr(ciphertext, '*') + 1; for (i = 0; i < BINARY_SIZE; i++) { out[i] = (atoi16[ARCH_INDEX(*p)] << 4) | atoi16[ARCH_INDEX(p[1])]; p += 2; } return out; } #define COMMON_GET_HASH_VAR crypt_out #include "common-get-hash.h" static void set_salt(void *salt) { cur_salt = (struct custom_salt *)salt; } inline static void hex_encode(unsigned char *str, int len, unsigned char *out) { int i; for (i = 0; i < len; ++i) { out[0] = itoa16[str[i]>>4]; out[1] = itoa16[str[i]&0xF]; out += 2; } } static int crypt_all(int *pcount, struct db_salt *salt) { const int count = *pcount; int index = 0; #ifdef _OPENMP #pragma omp parallel for #endif #if defined(_OPENMP) || MAX_KEYS_PER_CRYPT > 1 for (index = 0; index < count; index++) #endif { MD5_CTX ctx; unsigned char out[32]; MD5_Init(&ctx); MD5_Update(&ctx, saved_key[index], strlen(saved_key[index])); MD5_Update(&ctx, cur_salt->user, strlen((char*)cur_salt->user)); MD5_Final((unsigned char*)crypt_out[index], &ctx); hex_encode((unsigned char*)crypt_out[index], 16, out); MD5_Init(&ctx); MD5_Update(&ctx, out, 32); MD5_Update(&ctx, cur_salt->salt, 4); MD5_Final((unsigned char*)crypt_out[index], &ctx); } return count; } static int cmp_all(void *binary, int count) { int index = 0; #if defined(_OPENMP) || MAX_KEYS_PER_CRYPT > 1 for (; index < count; index++) #endif if (!memcmp(binary, crypt_out[index], ARCH_SIZE)) return 1; return 0; } static int cmp_one(void *binary, int index) { return !memcmp(binary, crypt_out[index], BINARY_SIZE); } static int cmp_exact(char *source, int index) { return 1; } static void postgres_set_key(char *key, int index) { strnzcpy(saved_key[index], key, sizeof(*saved_key)); } static char *get_key(int index) { return saved_key[index]; } struct fmt_main fmt_postgres = { { 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_OMP_BAD, { NULL }, { FORMAT_TAG, FORMAT_TAG2 }, postgres_tests }, { init, done, fmt_default_reset, prepare, valid, fmt_default_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, postgres_set_key, get_key, fmt_default_clear_keys, crypt_all, { #define COMMON_GET_HASH_LINK #include "common-get-hash.h" }, cmp_all, cmp_one, cmp_exact } }; #endif /* plugin stanza */
convolution_sgemm_int8.h
// BUG1989 is pleased to support the open source community by supporting ncnn available. // // Copyright (C) 2019 BUG1989. 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. #if __aarch64__ static void conv_im2col_sgemm_transform_kernel_int8_neon(const Mat& _kernel, Mat& kernel_tm, int inch, int outch, int kernel_size) { const signed char* kernel = _kernel; // kernel memory packed 4 x 4 kernel_tm.create(4*kernel_size, inch, outch/4 + outch%4, (size_t)1u); int nn_outch = 0; int remain_outch_start = 0; nn_outch = outch >> 2; remain_outch_start = nn_outch << 2; for (int pp=0; pp<nn_outch; pp++) { int p = pp * 4; const signed char* k0 = kernel + (p+0)*inch*kernel_size; const signed char* k1 = kernel + (p+1)*inch*kernel_size; const signed char* k2 = kernel + (p+2)*inch*kernel_size; const signed char* k3 = kernel + (p+3)*inch*kernel_size; signed char* ktmp = kernel_tm.channel(p/4); int q=0; for (; q+1<inch*kernel_size; q+=2) { ktmp[0] = k0[0]; ktmp[1] = k0[1]; ktmp[2] = k1[0]; ktmp[3] = k1[1]; ktmp[4] = k2[0]; ktmp[5] = k2[1]; ktmp[6] = k3[0]; ktmp[7] = k3[1]; ktmp += 8; k0 += 2; k1 += 2; k2 += 2; k3 += 2; } for (; q<inch*kernel_size; q++) { ktmp[0] = k0[0]; ktmp[1] = k1[0]; ktmp[2] = k2[0]; ktmp[3] = k3[0]; ktmp += 4; k0 += 1; k1 += 1; k2 += 1; k3 += 1; } } for (int p=remain_outch_start; p<outch; p++) { const signed char* k0 = kernel + (p+0)*inch*kernel_size; signed char* ktmp = kernel_tm.channel(p/4 + p%4); int q=0; for (; q+1<inch*kernel_size; q=q+2) { ktmp[0] = k0[0]; ktmp[1] = k0[1]; ktmp += 2; k0 += 2; } for (; q<inch*kernel_size; q++) { ktmp[0] = k0[0]; ktmp++; k0++; } } } static void conv_im2col_sgemm_int8_neon(const Mat &bottom_blob, Mat &top_blob, const Mat &kernel_tm, \ const int kernel_w, const int kernel_h, const int stride_w, const int stride_h, const Option& opt) { int w = bottom_blob.w; int inch = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; // im2row Mat bottom_im2row(kernel_h*kernel_w*inch, outw*outh, 1UL, opt.workspace_allocator); { int out_stride = kernel_h*kernel_w*inch*outw; signed char* ret = (signed char*)bottom_im2row; // #pragma omp parallel for num_threads(opt.num_threads) for (int i=0; i<outh; i++) { int retID = out_stride * i; for (int j=0; j<outw; j++) { for (int p=0; p<inch; p++) { const signed char* input = bottom_blob.channel(p); for (int u=0; u<kernel_h; u++) { for (int v=0; v<kernel_w; v++) { int row = u + i * stride_h; int col = v + j * stride_w; int index = row * w + col; ret[retID] = input[index]; retID++; } } } } } } int kernel_size = kernel_w * kernel_h; int out_size = outw * outh; // int M = outch; // outch int N = outw * outh; // outsize or out stride int K = kernel_w * kernel_h * inch; // ksize * inch // bottom_im2row memory packed 4 x 4 Mat bottom_tm(4*kernel_size, inch, out_size/4 + out_size%4, (size_t)1u, opt.workspace_allocator); { int nn_size = out_size >> 2; int remain_size_start = nn_size << 2; #pragma omp parallel for num_threads(opt.num_threads) for (int ii=0; ii<nn_size; ii++) { int i = ii * 4; const signed char* img0 = bottom_im2row.row<signed char>(i); const signed char* img1 = bottom_im2row.row<signed char>(i+1); const signed char* img2 = bottom_im2row.row<signed char>(i+2); const signed char* img3 = bottom_im2row.row<signed char>(i+3); signed char* tmpptr = bottom_tm.channel(i/4); int q = 0; for (; q+1<inch*kernel_size; q=q+2) { tmpptr[0] = img0[0]; tmpptr[1] = img0[1]; tmpptr[2] = img1[0]; tmpptr[3] = img1[1]; tmpptr[4] = img2[0]; tmpptr[5] = img2[1]; tmpptr[6] = img3[0]; tmpptr[7] = img3[1]; tmpptr += 8; img0 += 2; img1 += 2; img2 += 2; img3 += 2; } for (; q<inch*kernel_size; q++) { tmpptr[0] = img0[0]; tmpptr[1] = img1[0]; tmpptr[2] = img2[0]; tmpptr[3] = img3[0]; tmpptr += 4; img0 += 1; img1 += 1; img2 += 1; img3 += 1; } } #pragma omp parallel for num_threads(opt.num_threads) for (int i=remain_size_start; i<out_size; i++) { const signed char* img0 = bottom_im2row.row<signed char>(i); signed char* tmpptr = bottom_tm.channel(i/4 + i%4); int q=0; for (; q+1<inch*kernel_size; q=q+2) { tmpptr[0] = img0[0]; tmpptr[1] = img0[1]; tmpptr += 2; img0 += 2; } for (; q<inch*kernel_size; q++) { tmpptr[0] = img0[0]; tmpptr += 1; img0 += 1; } } } // 4x4 // sgemm(int M, int N, int K, float* A, float* B, float* C) { // int M = outch; // outch // int N = outw * outh; // outsize or out stride // int L = kernel_w * kernel_h * inch; // ksize * inch int nn_outch = 0; int remain_outch_start = 0; nn_outch = outch >> 2; remain_outch_start = nn_outch << 2; #pragma omp parallel for num_threads(opt.num_threads) for (int pp=0; pp<nn_outch; pp++) { int i = pp * 4; int* output0 = top_blob.channel(i); int* output1 = top_blob.channel(i+1); int* output2 = top_blob.channel(i+2); int* output3 = top_blob.channel(i+3); int j=0; for (; j+3<N; j=j+4) { const signed char* vb = bottom_tm.channel(j/4); const signed char* va = kernel_tm.channel(i/4); #if __ARM_NEON asm volatile( "prfm pldl1keep, [%4, #128] \n" "prfm pldl1keep, [%5, #128] \n" "eor v16.16b, v16.16b, v16.16b \n" // sum0 "eor v17.16b, v17.16b, v17.16b \n" // sum1 "eor v18.16b, v18.16b, v18.16b \n" // sum2 "eor v19.16b, v19.16b, v19.16b \n" // sum3 "lsr w4, %w12, #2 \n"// r4 = nn = L >> 2 "cmp w4, #0 \n" "beq 1f \n" "0: \n"// for (; k+3<L; k=k+4) "ld1 {v0.16b}, [%4] \n"// i0, i1, i2, i3 "ld1 {v4.16b}, [%5] \n"// k0, k1, k2, k3 "add %4, %4, #16 \n" "add %5, %5, #16 \n" "rev32 v1.8h, v0.8h \n"// i1, i0, i3, i2 "rev64 v2.4s, v0.4s \n"// i2, i3, i0, i1 "rev64 v3.8h, v0.8h \n"// i3, i2, i1, i0 "smull v8.8h, v4.8b, v0.8b \n" "smull v9.8h, v4.8b, v1.8b \n" "smull v10.8h, v4.8b, v2.8b \n" "smull v11.8h, v4.8b, v3.8b \n" "prfm pldl1keep, [%4, #128] \n" "prfm pldl1keep, [%5, #128] \n" "smlal2 v8.8h, v4.16b, v0.16b \n" "smlal2 v9.8h, v4.16b, v1.16b \n" "smlal2 v10.8h, v4.16b, v2.16b \n" "smlal2 v11.8h, v4.16b, v3.16b \n" "sadalp v16.4s, v8.8h \n"// i0k0, i1k1, i2k2, i3k3 "sadalp v17.4s, v9.8h \n"// i1k0, i0k1, i3k2, i2k3 "sadalp v18.4s, v10.8h \n"// i2k0, i3k1, i0k2, i1k3 "sadalp v19.4s, v11.8h \n"// i3k0, i2k1, i1k2, i0k3 "subs w4, w4, #1 \n" "bne 0b \n" "1: \n"// for (; k+1<L; k=k+2) // remain loop "and w4, %w12, #3 \n"// w4 = remain = K & 3; "cmp w4, #0 \n" "beq 3f \n" "lsr w4, w4, #1 \n"// r4 = nn = L >> 1 "cmp w4, #0 \n" "beq 3f \n" "2: \n"// for (; k+1<L; k=k+2) "ld1 {v0.8b}, [%4] \n"// i0, i1, i2, i3 "ld1 {v4.8b}, [%5] \n"// k0, k1, k2, k3 "add %4, %4, #8 \n" "add %5, %5, #8 \n" "rev32 v1.4h, v0.4h \n"// i2, i3, i0, i1 "rev64 v2.2s, v0.2s \n"// i1, i0, i3, i2 "rev64 v3.4h, v0.4h \n"// i0, i1, i2, i3 "smull v8.8h, v4.8b, v0.8b \n" "smull v9.8h, v4.8b, v1.8b \n" "smull v10.8h, v4.8b, v2.8b \n" "smull v11.8h, v4.8b, v3.8b \n" "sadalp v16.4s, v8.8h \n" "sadalp v17.4s, v9.8h \n" "sadalp v18.4s,v10.8h \n" "sadalp v19.4s,v11.8h \n" "subs w4, w4, #1 \n" "bne 2b \n" "3: \n"// realloc "mov v20.s[0], v16.s[0] \n" "mov v20.s[1], v17.s[0] \n" "mov v20.s[2], v18.s[0] \n" "mov v20.s[3], v19.s[0] \n" "mov v21.s[0], v17.s[1] \n" "mov v21.s[1], v16.s[1] \n" "mov v21.s[2], v19.s[1] \n" "mov v21.s[3], v18.s[1] \n" "mov v22.s[0], v18.s[2] \n" "mov v22.s[1], v19.s[2] \n" "mov v22.s[2], v16.s[2] \n" "mov v22.s[3], v17.s[2] \n" "mov v23.s[0], v19.s[3] \n" "mov v23.s[1], v18.s[3] \n" "mov v23.s[2], v17.s[3] \n" "mov v23.s[3], v16.s[3] \n" "and w4, %w12, #1 \n"// w4 = remain = K & 1; "cmp w4, #0 \n" "beq 5f \n" "4: \n" "ld1 {v0.8b}, [%4] \n" "ld1 {v1.8b}, [%5] \n" "add %4, %4, #4 \n" "add %5, %5, #4 \n" "sshll v0.8h, v0.8b, #0 \n"// i0[0], i1[0], i2[0], i3[0] "sshll v1.8h, v1.8b, #0 \n"// k0[0], k1[0], k2[0], k3[0] "smlal v20.4s, v0.4h, v1.h[0] \n"// i0k0, i1k0, i2k0, i3k0 "smlal v21.4s, v0.4h, v1.h[1] \n"// i0k1, i1k1, i2k1, i3k1 "smlal v22.4s, v0.4h, v1.h[2] \n"// i0k2, i1k2, i2k2, i3k2 "smlal v23.4s, v0.4h, v1.h[3] \n"// i0k3, i1k3, i2k3, i3k3 "subs w4, w4, #1 \n" "bne 2b \n" "5: \n" "st1 {v20.4s}, [%0] \n" "st1 {v21.4s}, [%1] \n" "st1 {v22.4s}, [%2] \n" "st1 {v23.4s}, [%3] \n" : "=r"(output0), // %0 "=r"(output1), // %1 "=r"(output2), // %2 "=r"(output3), // %3 "=r"(vb), // %4 "=r"(va) // %5 : "0"(output0), "1"(output1), "2"(output2), "3"(output3), "4"(vb), "5"(va), "r"(K) // %12 : "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" ); #else int sum0[4] = {0}; int sum1[4] = {0}; int sum2[4] = {0}; int sum3[4] = {0}; int k=0; for (; k+1<K; k=k+2) { for (int n=0; n<4; n++) { sum0[n] += (int)va[0] * vb[2*n]; // k0 sum0[n] += (int)va[1] * vb[2*n+1]; sum1[n] += (int)va[2] * vb[2*n]; // k1 sum1[n] += (int)va[3] * vb[2*n+1]; sum2[n] += (int)va[4] * vb[2*n]; // k2 sum2[n] += (int)va[5] * vb[2*n+1]; sum3[n] += (int)va[6] * vb[2*n]; // k3 sum3[n] += (int)va[7] * vb[2*n+1]; } va += 8; vb += 8; } for (; k<K; k++) { for (int n=0; n<4; n++) { sum0[n] += (int)va[0] * vb[n]; sum1[n] += (int)va[1] * vb[n]; sum2[n] += (int)va[2] * vb[n]; sum3[n] += (int)va[3] * vb[n]; } va += 4; vb += 4; } for (int n=0; n<4; n++) { output0[n] = sum0[n]; output1[n] = sum1[n]; output2[n] = sum2[n]; output3[n] = sum3[n]; } #endif output0 += 4; output1 += 4; output2 += 4; output3 += 4; } for (; j<N; j++) { const signed char* vb = bottom_tm.channel(j/4 + j%4); const signed char* va = kernel_tm.channel(i/4); #if __ARM_NEON int32x4_t _sum = vdupq_n_s32(0); int k=0; for (; k+3<K; k=k+4) { int8x8_t _r0 = vld1_s8(vb); // i0[0-3] int8x8x2_t _k = vld2_s8(va); // k0[0-1], k1[0-1], k2[0-1], k3[0-1];k0[2-3], k1[2-3], k2[2-3], k3[2-3] int16x8_t _r0_s16 = vmovl_s8(_r0); // i0[0],i0[1],i0[2],i0[3] int16x8_t _k02_s16 = vmovl_s8(_k.val[0]); // k0[0],k1[0],k2[0],k3[0],k0[2],k1[2],k2[2],k3[2] int16x8_t _k13_s16 = vmovl_s8(_k.val[1]); // k0[1],k1[1],k2[1],k3[1],k0[3],k1[3],k2[3],k3[3] _sum = vmlal_lane_s16(_sum, vget_low_s16(_k02_s16), vget_low_s16(_r0_s16), 0); // i0[0]*k[0-3][0] _sum = vmlal_lane_s16(_sum, vget_low_s16(_k13_s16), vget_low_s16(_r0_s16), 1); // i0[1]*k[0-3][1] _sum = vmlal_lane_s16(_sum, vget_high_s16(_k02_s16), vget_low_s16(_r0_s16), 2); // i0[2]*k[0-3][2] _sum = vmlal_lane_s16(_sum, vget_high_s16(_k13_s16), vget_low_s16(_r0_s16), 3); // i0[3]*k[0-3][3] va += 16; vb += 4; } for (; k+1<K; k=k+2) { int8x8_t _r0 = vld1_s8(vb); // i0[0-3] int8x8_t _k = vld1_s8(va); // k0[0-1], k1[0-1], k2[0-1], k3[0-1] _r0[2] = _r0[0]; _r0[3] = _r0[1]; _r0[4] = _r0[0]; _r0[5] = _r0[1]; _r0[6] = _r0[0]; _r0[7] = _r0[1]; int16x8_t _tp0 = vmull_s8(_k, _r0); _sum = vpadalq_s16(_sum, _tp0); va += 8; vb += 2; } for (; k<K; k++) { int8x8_t _r0 = vld1_s8(vb); // i0[0-3] int8x8_t _k = vld1_s8(va); // k[0-3][0] int16x8_t _tp0 = vmull_s8(_k, _r0); _sum = vaddw_s16(_sum, vget_low_s16(_tp0)); va += 4; vb += 1; } vst1q_lane_s32(output0, _sum, 0); vst1q_lane_s32(output1, _sum, 1); vst1q_lane_s32(output2, _sum, 2); vst1q_lane_s32(output3, _sum, 3); #else int sum0 = 0; int sum1 = 0; int sum2 = 0; int sum3 = 0; int k=0; for (; k+1<K; k=k+2) { sum0 += (int)va[0] * vb[0]; sum0 += (int)va[1] * vb[1]; sum1 += (int)va[2] * vb[0]; sum1 += (int)va[3] * vb[1]; sum2 += (int)va[4] * vb[0]; sum2 += (int)va[5] * vb[1]; sum3 += (int)va[6] * vb[0]; sum3 += (int)va[7] * vb[1]; va += 8; vb += 2; } for (; k<K; k++) { sum0 += (int)va[0] * vb[0]; sum1 += (int)va[1] * vb[0]; sum2 += (int)va[2] * vb[0]; sum3 += (int)va[3] * vb[0]; va += 4; vb += 1; } output0[0] = sum0; output1[0] = sum1; output2[0] = sum2; output3[0] = sum3; #endif output0++; output1++; output2++; output3++; } } #pragma omp parallel for num_threads(opt.num_threads) for (int i=remain_outch_start; i<outch; i++) { int* output = top_blob.channel(i); int j=0; for (; j+3<N; j=j+4) { const signed char* vb = bottom_tm.channel(j/4); const signed char* va = kernel_tm.channel(i/4 + i%4); #if __ARM_NEON int32x4_t _sum = vdupq_n_s32(0); int k=0; for (; k+1<K; k=k+2) { int8x8_t _r0 = vld1_s8(vb); // i0[0-1], i1[0-1], i2[0-1], i3[0-1] int8x8_t _k = vld1_s8(va); // k0[0-1] _k[2] = _k[0]; _k[3] = _k[1]; _k[4] = _k[0]; _k[5] = _k[1]; _k[6] = _k[0]; _k[7] = _k[1]; int16x8_t _tp0 = vmull_s8(_k, _r0); _sum = vpadalq_s16(_sum, _tp0); va += 2; vb += 8; } for (; k<K; k++) { int8x8_t _r0 = vld1_s8(vb); // i0[0], i1[0], i2[0], i3[0] int8x8_t _k = vld1_s8(va); // k[0][0] int16x8_t _r0_s16 = vmovl_s8(_r0); int16x8_t _k_s16 = vmovl_s8(_k); _sum = vmlal_lane_s16(_sum, vget_low_s16(_r0_s16), vget_low_s16(_k_s16), 0); // i0k0, i1k0, i2k0, i3k0 va += 1; vb += 4; } vst1q_s32(output, _sum); #else int sum[4] = {0}; int k=0; for (; k+1<K; k=k+2) { for (int n=0; n<4; n++) { sum[n] += (int)va[0] * vb[2*n]; sum[n] += (int)va[1] * vb[2*n+1]; } va += 2; vb += 8; } for (; k<K; k++) { for (int n=0; n<4; n++) { sum[n] += (int)va[0] * vb[n]; } va += 1; vb += 4; } for (int n=0; n<4; n++) { output[n] = sum[n]; } #endif output += 4; } for (; j<N; j++) { int sum = 0; const signed char* vb = bottom_tm.channel(j/4 + j%4); const signed char* va = kernel_tm.channel(i/4 + i%4); for (int k=0; k<K; k++) { sum += (int)va[0] * vb[0]; va += 1; vb += 1; } output[0] = sum; output++; } } } // // sgemm(int M, int N, int K, float* A, float* B, float* C) // { // for (int i=0; i<M; i++) // { // int* output = top_blob.channel(i); // for (int j=0; j<N; j++) // { // int sum = 0; // signed char* vb = (signed char*)bottom_im2row + K * j; // const signed char* va = kernel + K * i; // for (int k=0; k<K; k++) // { // sum += (int)va[0] * vb[0]; // va += 1; // vb += 1; // } // output[0] = sum; // output++; // } // } // } } #else static void conv_im2col_sgemm_transform_kernel_int8_neon(const Mat& _kernel, Mat& kernel_tm, int inch, int outch, int kernel_size) { const signed char* kernel = _kernel; #if __ARM_NEON && __aarch64__ // kernel memory packed 8 x 8 kernel_tm.create(8*kernel_size, inch, outch/8 + (outch%8)/4 + outch%4, (size_t)1u); #else // kernel memory packed 4 x 8 kernel_tm.create(4*kernel_size, inch, outch/4 + outch%4, (size_t)1u); #endif int nn_outch = 0; int remain_outch_start = 0; #if __ARM_NEON && __aarch64__ nn_outch = outch >> 3; remain_outch_start = nn_outch << 3; for (int pp=0; pp<nn_outch; pp++) { int p = pp * 8; const signed char* k0 = kernel + (p+0)*inch*kernel_size; const signed char* k1 = kernel + (p+1)*inch*kernel_size; const signed char* k2 = kernel + (p+2)*inch*kernel_size; const signed char* k3 = kernel + (p+3)*inch*kernel_size; const signed char* k4 = kernel + (p+4)*inch*kernel_size; const signed char* k5 = kernel + (p+5)*inch*kernel_size; const signed char* k6 = kernel + (p+6)*inch*kernel_size; const signed char* k7 = kernel + (p+7)*inch*kernel_size; signed char* ktmp = kernel_tm.channel(p/8); for (int q=0; q<inch*kernel_size; q++) { ktmp[0] = k0[0]; ktmp[1] = k1[0]; ktmp[2] = k2[0]; ktmp[3] = k3[0]; ktmp[4] = k4[0]; ktmp[5] = k5[0]; ktmp[6] = k6[0]; ktmp[7] = k7[0]; ktmp += 8; k0 += 1; k1 += 1; k2 += 1; k3 += 1; k4 += 1; k5 += 1; k6 += 1; k7 += 1; } } #endif nn_outch = (outch - remain_outch_start) >> 2; for (int pp=0; pp<nn_outch; pp++) { int p = remain_outch_start + pp * 4; const signed char* k0 = kernel + (p+0)*inch*kernel_size; const signed char* k1 = kernel + (p+1)*inch*kernel_size; const signed char* k2 = kernel + (p+2)*inch*kernel_size; const signed char* k3 = kernel + (p+3)*inch*kernel_size; #if __ARM_NEON && __aarch64__ signed char* ktmp = kernel_tm.channel(p/8 + (p%8)/4); #else signed char* ktmp = kernel_tm.channel(p/4); #endif // __ARM_NEON && __aarch64__ for (int q=0; q<inch*kernel_size; q++) { ktmp[0] = k0[0]; ktmp[1] = k1[0]; ktmp[2] = k2[0]; ktmp[3] = k3[0]; ktmp += 4; k0 += 1; k1 += 1; k2 += 1; k3 += 1; } } remain_outch_start += nn_outch << 2; for (int p=remain_outch_start; p<outch; p++) { const signed char* k0 = kernel + (p+0)*inch*kernel_size; #if __ARM_NEON && __aarch64__ signed char* ktmp = kernel_tm.channel(p/8 + (p%8)/4 + p%4); #else signed char* ktmp = kernel_tm.channel(p/4 + p%4); #endif // __ARM_NEON && __aarch64__ for (int q=0; q<inch*kernel_size; q++) { ktmp[0] = k0[0]; ktmp++; k0++; } } } static void conv_im2col_sgemm_int8_neon(const Mat &bottom_blob, Mat &top_blob, const Mat & kernel_tm, \ const int kernel_w, const int kernel_h, const int stride_w, const int stride_h, const Option& opt) { int w = bottom_blob.w; int inch = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; // im2col Mat bottom_im2col(outw*outh, kernel_h*kernel_w*inch, 1UL, opt.workspace_allocator); { const int stride = kernel_h*kernel_w*outw*outh; signed char* ret = (signed char*)bottom_im2col; #pragma omp parallel for num_threads(opt.num_threads) for (int p=0; p<inch; p++) { const signed char* input = bottom_blob.channel(p); int retID = stride * p; for (int u=0; u<kernel_h; u++) { for (int v=0; v<kernel_w; v++) { for (int i=0; i<outh; i++) { for (int j=0; j<outw; j++) { int row = u + i * stride_h; int col = v + j * stride_w; int index = row * w + col; ret[retID] = input[index]; retID++; } } } } } } int kernel_size = kernel_w * kernel_h; int out_size = outw * outh; // bottom_im2col memory packed 8 x 8 Mat bottom_tm(8*kernel_size, inch, out_size/8 + out_size%8, (size_t)1u, opt.workspace_allocator); { int nn_size = out_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 signed char* img0 = bottom_im2col.channel(0); img0 += i; signed char* tmpptr = bottom_tm.channel(i/8); for (int q=0; q<inch*kernel_size; q++) { #if __ARM_NEON #if __aarch64__ asm volatile( "prfm pldl1keep, [%0, #64] \n" "ld1 {v0.8b}, [%0] \n" "st1 {v0.8b}, [%1] \n" : "=r"(img0), // %0 "=r"(tmpptr) // %1 : "0"(img0), "1"(tmpptr) : "cc", "memory", "v0" ); #else asm volatile( "pld [%0, #64] \n" "vld1.s8 {d0}, [%0] \n" "vst1.s8 {d0}, [%1] \n" : "=r"(img0), // %0 "=r"(tmpptr) // %1 : "0"(img0), "1"(tmpptr) : "cc", "memory", "d0" ); #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]; #endif // __ARM_NEON tmpptr += 8; img0 += out_size; } } #pragma omp parallel for num_threads(opt.num_threads) for (int i=remain_size_start; i<out_size; i++) { const signed char* img0 = bottom_im2col.channel(0); img0 += i; signed char* tmpptr = bottom_tm.channel(i/8 + i%8); for (int q=0; q<inch*kernel_size; q++) { tmpptr[0] = img0[0]; tmpptr += 1; img0 += out_size; } } } // sgemm(int M, int N, int L, float* A, float* B, float* C) { //int M = outch; // outch int N = outw * outh; // outsize or out stride int L = kernel_w * kernel_h * inch; // ksize * inch 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 i = pp * 8; int* output0 = top_blob.channel(i); int* output1 = top_blob.channel(i+1); int* output2 = top_blob.channel(i+2); int* output3 = top_blob.channel(i+3); int* output4 = top_blob.channel(i+4); int* output5 = top_blob.channel(i+5); int* output6 = top_blob.channel(i+6); int* output7 = top_blob.channel(i+7); int j=0; for (; j+7<N; j=j+8) { signed char* vb = bottom_tm.channel(j/8); const signed char* va = kernel_tm.channel(i/8); #if __aarch64__ asm volatile( "eor v16.16b, v16.16b, v16.16b \n" // sum0 "eor v17.16b, v17.16b, v17.16b \n" // sum0n "eor v18.16b, v18.16b, v18.16b \n" // sum1 "eor v19.16b, v19.16b, v19.16b \n" // sum1n "eor v20.16b, v20.16b, v20.16b \n" // sum2 "eor v21.16b, v21.16b, v21.16b \n" // sum2n "eor v22.16b, v22.16b, v22.16b \n" // sum3 "eor v23.16b, v23.16b, v23.16b \n" // sum3n "eor v24.16b, v24.16b, v24.16b \n" // sum4 "eor v25.16b, v25.16b, v25.16b \n" // sum4n "eor v26.16b, v26.16b, v26.16b \n" // sum5 "eor v27.16b, v27.16b, v27.16b \n" // sum5n "eor v28.16b, v28.16b, v28.16b \n" // sum6 "eor v29.16b, v29.16b, v29.16b \n" // sum6n "eor v30.16b, v30.16b, v30.16b \n" // sum7 "eor v31.16b, v31.16b, v31.16b \n" // sum7n "lsr w4, %w20, #2 \n"// r4 = nn = L >> 2 "cmp w4, #0 \n" "beq 1f \n" "0: \n"// for (; k+3<L; k=k+4) "prfm pldl1keep, [%9, #128] \n" "ld1 {v0.8b, v1.8b, v2.8b, v3.8b}, [%9], #32 \n" "prfm pldl1keep, [%8, #128] \n" "ld1 {v8.8b, v9.8b, v10.8b, v11.8b}, [%8], #32 \n" "sshll v0.8h, v0.8b, #0 \n" // k00 - k70 "sshll v1.8h, v1.8b, #0 \n" // k01 - k71 "sshll v2.8h, v2.8b, #0 \n" // k02 - k72 "sshll v3.8h, v3.8b, #0 \n" // k03 - k73 "sshll v8.8h, v8.8b, #0 \n" // a00 - a70 "sshll v9.8h, v9.8b, #0 \n" // a01 - a71 "sshll v10.8h, v10.8b, #0 \n" // a02 - a72 "sshll v11.8h, v11.8b, #0 \n" // a03 - a73 // k0 "smlal v16.4s, v8.4h, v0.h[0] \n"// sum0 += (a00-a70) * k00 "smlal2 v17.4s, v8.8h, v0.h[0] \n"// "smlal v18.4s, v8.4h, v0.h[1] \n"// sum1 += (a00-a70) * k10 "smlal2 v19.4s, v8.8h, v0.h[1] \n"// "smlal v20.4s, v8.4h, v0.h[2] \n"// sum2 += (a00-a70) * k20 "smlal2 v21.4s, v8.8h, v0.h[2] \n"// "smlal v22.4s, v8.4h, v0.h[3] \n"// sum3 += (a00-a70) * k30 "smlal2 v23.4s, v8.8h, v0.h[3] \n"// "smlal v24.4s, v8.4h, v0.h[4] \n"// sum4 += (a00-a70) * k40 "smlal2 v25.4s, v8.8h, v0.h[4] \n"// "smlal v26.4s, v8.4h, v0.h[5] \n"// sum5 += (a00-a70) * k50 "smlal2 v27.4s, v8.8h, v0.h[5] \n"// "smlal v28.4s, v8.4h, v0.h[6] \n"// sum6 += (a00-a70) * k60 "smlal2 v29.4s, v8.8h, v0.h[6] \n"// "smlal v30.4s, v8.4h, v0.h[7] \n"// sum7 += (a00-a70) * k70 "smlal2 v31.4s, v8.8h, v0.h[7] \n"// // k1 "smlal v16.4s, v9.4h, v1.h[0] \n"// sum0 += (a01-a71) * k01 "smlal2 v17.4s, v9.8h, v1.h[0] \n"// "smlal v18.4s, v9.4h, v1.h[1] \n"// sum1 += (a01-a71) * k11 "smlal2 v19.4s, v9.8h, v1.h[1] \n"// "smlal v20.4s, v9.4h, v1.h[2] \n"// sum2 += (a01-a71) * k21 "smlal2 v21.4s, v9.8h, v1.h[2] \n"// "smlal v22.4s, v9.4h, v1.h[3] \n"// sum3 += (a01-a71) * k31 "smlal2 v23.4s, v9.8h, v1.h[3] \n"// "smlal v24.4s, v9.4h, v1.h[4] \n"// sum4 += (a01-a71) * k41 "smlal2 v25.4s, v9.8h, v1.h[4] \n"// "smlal v26.4s, v9.4h, v1.h[5] \n"// sum5 += (a01-a71) * k51 "smlal2 v27.4s, v9.8h, v1.h[5] \n"// "smlal v28.4s, v9.4h, v1.h[6] \n"// sum6 += (a01-a71) * k61 "smlal2 v29.4s, v9.8h, v1.h[6] \n"// "smlal v30.4s, v9.4h, v1.h[7] \n"// sum7 += (a01-a71) * k71 "smlal2 v31.4s, v9.8h, v1.h[7] \n"// // k2 "smlal v16.4s, v10.4h, v2.h[0] \n"// sum0 += (a02-a72) * k02 "smlal2 v17.4s, v10.8h, v2.h[0] \n"// "smlal v18.4s, v10.4h, v2.h[1] \n"// sum1 += (a02-a72) * k12 "smlal2 v19.4s, v10.8h, v2.h[1] \n"// "smlal v20.4s, v10.4h, v2.h[2] \n"// sum2 += (a02-a72) * k22 "smlal2 v21.4s, v10.8h, v2.h[2] \n"// "smlal v22.4s, v10.4h, v2.h[3] \n"// sum3 += (a02-a72) * k32 "smlal2 v23.4s, v10.8h, v2.h[3] \n"// "smlal v24.4s, v10.4h, v2.h[4] \n"// sum4 += (a02-a72) * k42 "smlal2 v25.4s, v10.8h, v2.h[4] \n"// "smlal v26.4s, v10.4h, v2.h[5] \n"// sum5 += (a02-a72) * k52 "smlal2 v27.4s, v10.8h, v2.h[5] \n"// "smlal v28.4s, v10.4h, v2.h[6] \n"// sum6 += (a02-a72) * k62 "smlal2 v29.4s, v10.8h, v2.h[6] \n"// "smlal v30.4s, v10.4h, v2.h[7] \n"// sum7 += (a02-a72) * k72 "smlal2 v31.4s, v10.8h, v2.h[7] \n"// // k3 "smlal v16.4s, v11.4h, v3.h[0] \n"// sum0 += (a03-a73) * k03 "smlal2 v17.4s, v11.8h, v3.h[0] \n"// "smlal v18.4s, v11.4h, v3.h[1] \n"// sum1 += (a03-a73) * k13 "smlal2 v19.4s, v11.8h, v3.h[1] \n"// "smlal v20.4s, v11.4h, v3.h[2] \n"// sum2 += (a03-a73) * k23 "smlal2 v21.4s, v11.8h, v3.h[2] \n"// "smlal v22.4s, v11.4h, v3.h[3] \n"// sum3 += (a03-a73) * k33 "smlal2 v23.4s, v11.8h, v3.h[3] \n"// "smlal v24.4s, v11.4h, v3.h[4] \n"// sum4 += (a03-a73) * k43 "smlal2 v25.4s, v11.8h, v3.h[4] \n"// "smlal v26.4s, v11.4h, v3.h[5] \n"// sum5 += (a03-a73) * k53 "smlal2 v27.4s, v11.8h, v3.h[5] \n"// "smlal v28.4s, v11.4h, v3.h[6] \n"// sum6 += (a03-a73) * k63 "smlal2 v29.4s, v11.8h, v3.h[6] \n"// "smlal v30.4s, v11.4h, v3.h[7] \n"// sum7 += (a03-a73) * k73 "smlal2 v31.4s, v11.8h, v3.h[7] \n"// "subs w4, w4, #1 \n" "bne 0b \n" "1: \n" // remain loop "and w4, %w20, #3 \n"// w4 = remain = inch & 3; "cmp w4, #0 \n" "beq 3f \n" "2: \n" "prfm pldl1keep, [%9, #128] \n" "ld1 {v0.8b}, [%9], #8 \n" "prfm pldl1keep, [%8, #128] \n" "ld1 {v8.8b}, [%8], #8 \n" "sshll v0.8h, v0.8b, #0 \n" // k00 - k70 "sshll v8.8h, v8.8b, #0 \n" // a00 - a70 // k0 "smlal v16.4s, v8.4h, v0.h[0] \n"// sum0 += (a00-a70) * k00 "smlal2 v17.4s, v8.8h, v0.h[0] \n"// "smlal v18.4s, v8.4h, v0.h[1] \n"// sum1 += (a00-a70) * k10 "smlal2 v19.4s, v8.8h, v0.h[1] \n"// "smlal v20.4s, v8.4h, v0.h[2] \n"// sum2 += (a00-a70) * k20 "smlal2 v21.4s, v8.8h, v0.h[2] \n"// "smlal v22.4s, v8.4h, v0.h[3] \n"// sum3 += (a00-a70) * k30 "smlal2 v23.4s, v8.8h, v0.h[3] \n"// "smlal v24.4s, v8.4h, v0.h[4] \n"// sum4 += (a00-a70) * k40 "smlal2 v25.4s, v8.8h, v0.h[4] \n"// "smlal v26.4s, v8.4h, v0.h[5] \n"// sum5 += (a00-a70) * k50 "smlal2 v27.4s, v8.8h, v0.h[5] \n"// "smlal v28.4s, v8.4h, v0.h[6] \n"// sum6 += (a00-a70) * k60 "smlal2 v29.4s, v8.8h, v0.h[6] \n"// "smlal v30.4s, v8.4h, v0.h[7] \n"// sum7 += (a00-a70) * k70 "smlal2 v31.4s, v8.8h, v0.h[7] \n"// "subs w4, w4, #1 \n" "bne 2b \n" "3: \n" "st1 {v16.4s, v17.4s}, [%0] \n" "st1 {v18.4s, v19.4s}, [%1] \n" "st1 {v20.4s, v21.4s}, [%2] \n" "st1 {v22.4s, v23.4s}, [%3] \n" "st1 {v24.4s, v25.4s}, [%4] \n" "st1 {v26.4s, v27.4s}, [%5] \n" "st1 {v28.4s, v29.4s}, [%6] \n" "st1 {v30.4s, v31.4s}, [%7] \n" : "=r"(output0), // %0 "=r"(output1), // %1 "=r"(output2), // %2 "=r"(output3), // %3 "=r"(output4), // %4 "=r"(output5), // %5 "=r"(output6), // %6 "=r"(output7), // %7 "=r"(vb), // %8 "=r"(va) // %9 : "0"(output0), "1"(output1), "2"(output2), "3"(output3), "4"(output4), "5"(output5), "6"(output6), "7"(output7), "8"(vb), "9"(va), "r"(L) // %20 : "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" ); #else int sum0[8] = {0}; int sum1[8] = {0}; int sum2[8] = {0}; int sum3[8] = {0}; int sum4[8] = {0}; int sum5[8] = {0}; int sum6[8] = {0}; int sum7[8] = {0}; int k=0; for (; k+7<L; k=k+8) { for (int n=0; n<8; n++) { sum0[n] += (int)va[0] * vb[n]; sum1[n] += (int)va[1] * vb[n]; sum2[n] += (int)va[2] * vb[n]; sum3[n] += (int)va[3] * vb[n]; sum4[n] += (int)va[4] * vb[n]; sum5[n] += (int)va[5] * vb[n]; sum6[n] += (int)va[6] * vb[n]; sum7[n] += (int)va[7] * vb[n]; va += 8; sum0[n] += (int)va[0] * vb[n+8]; sum1[n] += (int)va[1] * vb[n+8]; sum2[n] += (int)va[2] * vb[n+8]; sum3[n] += (int)va[3] * vb[n+8]; sum4[n] += (int)va[4] * vb[n+8]; sum5[n] += (int)va[5] * vb[n+8]; sum6[n] += (int)va[6] * vb[n+8]; sum7[n] += (int)va[7] * vb[n+8]; va += 8; sum0[n] += (int)va[0] * vb[n+16]; sum1[n] += (int)va[1] * vb[n+16]; sum2[n] += (int)va[2] * vb[n+16]; sum3[n] += (int)va[3] * vb[n+16]; sum4[n] += (int)va[4] * vb[n+16]; sum5[n] += (int)va[5] * vb[n+16]; sum6[n] += (int)va[6] * vb[n+16]; sum7[n] += (int)va[7] * vb[n+16]; va += 8; sum0[n] += (int)va[0] * vb[n+24]; sum1[n] += (int)va[1] * vb[n+24]; sum2[n] += (int)va[2] * vb[n+24]; sum3[n] += (int)va[3] * vb[n+24]; sum4[n] += (int)va[4] * vb[n+24]; sum5[n] += (int)va[5] * vb[n+24]; sum6[n] += (int)va[6] * vb[n+24]; sum7[n] += (int)va[7] * vb[n+24]; va += 8; sum0[n] += (int)va[0] * vb[n+32]; sum1[n] += (int)va[1] * vb[n+32]; sum2[n] += (int)va[2] * vb[n+32]; sum3[n] += (int)va[3] * vb[n+32]; sum4[n] += (int)va[4] * vb[n+32]; sum5[n] += (int)va[5] * vb[n+32]; sum6[n] += (int)va[6] * vb[n+32]; sum7[n] += (int)va[7] * vb[n+32]; va += 8; sum0[n] += (int)va[0] * vb[n+40]; sum1[n] += (int)va[1] * vb[n+40]; sum2[n] += (int)va[2] * vb[n+40]; sum3[n] += (int)va[3] * vb[n+40]; sum4[n] += (int)va[4] * vb[n+40]; sum5[n] += (int)va[5] * vb[n+40]; sum6[n] += (int)va[6] * vb[n+40]; sum7[n] += (int)va[7] * vb[n+40]; va += 8; sum0[n] += (int)va[0] * vb[n+48]; sum1[n] += (int)va[1] * vb[n+48]; sum2[n] += (int)va[2] * vb[n+48]; sum3[n] += (int)va[3] * vb[n+48]; sum4[n] += (int)va[4] * vb[n+48]; sum5[n] += (int)va[5] * vb[n+48]; sum6[n] += (int)va[6] * vb[n+48]; sum7[n] += (int)va[7] * vb[n+48]; va += 8; sum0[n] += (int)va[0] * vb[n+56]; sum1[n] += (int)va[1] * vb[n+56]; sum2[n] += (int)va[2] * vb[n+56]; sum3[n] += (int)va[3] * vb[n+56]; sum4[n] += (int)va[4] * vb[n+56]; sum5[n] += (int)va[5] * vb[n+56]; sum6[n] += (int)va[6] * vb[n+56]; sum7[n] += (int)va[7] * vb[n+56]; va -= 56; } va += 64; vb += 64; } for (; k<L; k++) { for (int n=0; n<8; n++) { sum0[n] += (int)va[0] * vb[n]; sum1[n] += (int)va[1] * vb[n]; sum2[n] += (int)va[2] * vb[n]; sum3[n] += (int)va[3] * vb[n]; sum4[n] += (int)va[4] * vb[n]; sum5[n] += (int)va[5] * vb[n]; sum6[n] += (int)va[6] * vb[n]; sum7[n] += (int)va[7] * vb[n]; } va += 8; vb += 8; } for (int n=0; n<8; n++) { output0[n] = sum0[n]; output1[n] = sum1[n]; output2[n] = sum2[n]; output3[n] = sum3[n]; output4[n] = sum4[n]; output5[n] = sum5[n]; output6[n] = sum6[n]; output7[n] = sum7[n]; } #endif // __aarch64__ output0 += 8; output1 += 8; output2 += 8; output3 += 8; output4 += 8; output5 += 8; output6 += 8; output7 += 8; } for (; j<N; j++) { signed char* vb = bottom_tm.channel(j/8 + j%8); const signed char* va = kernel_tm.channel(i/8); #if __aarch64__ asm volatile( "eor v14.16b, v14.16b, v14.16b \n" // sum0_3 "eor v15.16b, v15.16b, v15.16b \n" // sum4_7 "eor v16.16b, v16.16b, v16.16b \n" // sum0 "eor v17.16b, v17.16b, v17.16b \n" // sum1 "eor v18.16b, v18.16b, v18.16b \n" // sum2 "eor v19.16b, v19.16b, v19.16b \n" // sum3 "eor v20.16b, v20.16b, v20.16b \n" // sum4 "eor v21.16b, v21.16b, v21.16b \n" // sum5 "eor v22.16b, v22.16b, v22.16b \n" // sum6 "eor v23.16b, v23.16b, v23.16b \n" // sum7 "lsr w4, %w20, #2 \n"// r4 = nn = L >> 2 "cmp w4, #0 \n" "beq 1f \n" "0: \n"// for (; k+3<L; k=k+4) "prfm pldl1keep, [%9, #128] \n" "ld1 {v0.8b, v1.8b, v2.8b, v3.8b}, [%9], #32 \n" // k //"prfm pldl1keep, [%8, #128] \n" "ld1 {v4.8b}, [%8] \n" // d "add %8, %8, #4 \n" "sshll v0.8h, v0.8b, #0 \n" // k00 - k70 "sshll v1.8h, v1.8b, #0 \n" // k01 - k71 "sshll v2.8h, v2.8b, #0 \n" // k02 - k72 "sshll v3.8h, v3.8b, #0 \n" // k03 - k73 "sshll v4.8h, v4.8b, #0 \n" // a00 - a30 // k0 "smlal v16.4s, v0.4h, v4.h[0] \n"// sum0 += (k00-k70) * a00 "smlal2 v17.4s, v0.8h, v4.h[0] \n"// "smlal v18.4s, v1.4h, v4.h[1] \n"// sum1 += (k01-k71) * a10 "smlal2 v19.4s, v1.8h, v4.h[1] \n"// "smlal v20.4s, v2.4h, v4.h[2] \n"// sum2 += (k02-k72) * a20 "smlal2 v21.4s, v2.8h, v4.h[2] \n"// "smlal v22.4s, v3.4h, v4.h[3] \n"// sum3 += (k03-k73) * a30 "smlal2 v23.4s, v3.8h, v4.h[3] \n"// "subs w4, w4, #1 \n" "bne 0b \n" "add v16.4s, v16.4s, v18.4s \n" "add v17.4s, v17.4s, v19.4s \n" "add v20.4s, v20.4s, v22.4s \n" "add v21.4s, v21.4s, v23.4s \n" "add v14.4s, v16.4s, v20.4s \n" "add v15.4s, v17.4s, v21.4s \n" "1: \n" // remain loop "and w4, %w20, #3 \n"// w4 = remain = inch & 3; "cmp w4, #0 \n" "beq 3f \n" "2: \n" //"prfm pldl1keep, [%9, #128] \n" "ld1 {v0.8b}, [%9], #8 \n" //"prfm pldl1keep, [%8, #128] \n" "ld1 {v4.8b}, [%8] \n" "add %8, %8, #1 \n" "sshll v0.8h, v0.8b, #0 \n" // k00 - k70 "sshll v4.8h, v4.8b, #0 \n" // a00 // k0 "smlal v14.4s, v0.4h, v4.h[0] \n"// sum0 += (k00-k70) * a00 "smlal2 v15.4s, v0.8h, v4.h[0] \n"// "subs w4, w4, #1 \n" "bne 2b \n" "3: \n" "st1 {v14.s}[0], [%0] \n" "st1 {v14.s}[1], [%1] \n" "st1 {v14.s}[2], [%2] \n" "st1 {v14.s}[3], [%3] \n" "st1 {v15.s}[0], [%4] \n" "st1 {v15.s}[1], [%5] \n" "st1 {v15.s}[2], [%6] \n" "st1 {v15.s}[3], [%7] \n" : "=r"(output0), // %0 "=r"(output1), // %1 "=r"(output2), // %2 "=r"(output3), // %3 "=r"(output4), // %4 "=r"(output5), // %5 "=r"(output6), // %6 "=r"(output7), // %7 "=r"(vb), // %8 "=r"(va) // %9 : "0"(output0), "1"(output1), "2"(output2), "3"(output3), "4"(output4), "5"(output5), "6"(output6), "7"(output7), "8"(vb), "9"(va), "r"(L) // %20 : "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" ); #else int sum0 = 0; int sum1 = 0; int sum2 = 0; int sum3 = 0; int sum4 = 0; int sum5 = 0; int sum6 = 0; int sum7 = 0; for (int k=0; k<L; k++) { sum0 += (int)va[0] * vb[0]; sum1 += (int)va[1] * vb[0]; sum2 += (int)va[2] * vb[0]; sum3 += (int)va[3] * vb[0]; sum4 += (int)va[4] * vb[0]; sum5 += (int)va[5] * vb[0]; sum6 += (int)va[6] * vb[0]; sum7 += (int)va[7] * vb[0]; va += 8; vb += 1; } output0[0] = sum0; output1[0] = sum1; output2[0] = sum2; output3[0] = sum3; output4[0] = sum4; output5[0] = sum5; output6[0] = sum6; output7[0] = sum7; #endif // __aarch64__ output0++; output1++; output2++; output3++; output4++; output5++; output6++; output7++; } } #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 i = remain_outch_start + pp * 4; int* output0 = top_blob.channel(i); int* output1 = top_blob.channel(i+1); int* output2 = top_blob.channel(i+2); int* output3 = top_blob.channel(i+3); int j=0; for (; j+7<N; j=j+8) { signed char* vb = bottom_tm.channel(j/8); #if __ARM_NEON && __aarch64__ const signed char* va = kernel_tm.channel(i/8 + (i%8)/4); #else const signed char* va = kernel_tm.channel(i/4); #endif // __ARM_NEON && __aarch64__ #if __ARM_NEON #if __aarch64__ asm volatile( "eor v16.16b, v16.16b, v16.16b \n" // sum0 "eor v17.16b, v17.16b, v17.16b \n" // sum0n "eor v18.16b, v18.16b, v18.16b \n" // sum1 "eor v19.16b, v19.16b, v19.16b \n" // sum1n "eor v20.16b, v20.16b, v20.16b \n" // sum2 "eor v21.16b, v21.16b, v21.16b \n" // sum2n "eor v22.16b, v22.16b, v22.16b \n" // sum3 "eor v23.16b, v23.16b, v23.16b \n" // sum3n "lsr w4, %w12, #2 \n"// r4 = nn = L >> 2 "cmp w4, #0 \n" "beq 1f \n" "0: \n"// for (; k+3<L; k=k+4) "prfm pldl1keep, [%5, #128] \n" "ld1 {v0.8b, v1.8b}, [%5], #16 \n" "prfm pldl1keep, [%4, #128] \n" "ld1 {v8.8b, v9.8b, v10.8b, v11.8b}, [%4], #32 \n" "sshll v0.8h, v0.8b, #0 \n" // k00 - k30,k01 - k31 "sshll v1.8h, v1.8b, #0 \n" // k02 - k32,k03 - k33 "sshll v8.8h, v8.8b, #0 \n" // a00 - a70 "sshll v9.8h, v9.8b, #0 \n" // a01 - a71 "sshll v10.8h, v10.8b, #0 \n" // a02 - a72 "sshll v11.8h, v11.8b, #0 \n" // a03 - a73 // k0 "smlal v16.4s, v8.4h, v0.h[0] \n"// sum0 += (a00-a70) * k00 "smlal2 v17.4s, v8.8h, v0.h[0] \n"// "smlal v18.4s, v8.4h, v0.h[1] \n"// sum1 += (a00-a70) * k10 "smlal2 v19.4s, v8.8h, v0.h[1] \n"// "smlal v20.4s, v8.4h, v0.h[2] \n"// sum2 += (a00-a70) * k20 "smlal2 v21.4s, v8.8h, v0.h[2] \n"// "smlal v22.4s, v8.4h, v0.h[3] \n"// sum3 += (a00-a70) * k30 "smlal2 v23.4s, v8.8h, v0.h[3] \n"// // k1 "smlal v16.4s, v9.4h, v0.h[4] \n"// sum0 += (a01-a71) * k01 "smlal2 v17.4s, v9.8h, v0.h[4] \n"// "smlal v18.4s, v9.4h, v0.h[5] \n"// sum1 += (a01-a71) * k11 "smlal2 v19.4s, v9.8h, v0.h[5] \n"// "smlal v20.4s, v9.4h, v0.h[6] \n"// sum2 += (a01-a71) * k21 "smlal2 v21.4s, v9.8h, v0.h[6] \n"// "smlal v22.4s, v9.4h, v0.h[7] \n"// sum3 += (a01-a71) * k31 "smlal2 v23.4s, v9.8h, v0.h[7] \n"// // k2 "smlal v16.4s, v10.4h, v1.h[0] \n"// sum0 += (a02-a72) * k02 "smlal2 v17.4s, v10.8h, v1.h[0] \n"// "smlal v18.4s, v10.4h, v1.h[1] \n"// sum1 += (a02-a72) * k12 "smlal2 v19.4s, v10.8h, v1.h[1] \n"// "smlal v20.4s, v10.4h, v1.h[2] \n"// sum2 += (a02-a72) * k22 "smlal2 v21.4s, v10.8h, v1.h[2] \n"// "smlal v22.4s, v10.4h, v1.h[3] \n"// sum3 += (a02-a72) * k32 "smlal2 v23.4s, v10.8h, v1.h[3] \n"// // k3 "smlal v16.4s, v11.4h, v1.h[4] \n"// sum0 += (a03-a73) * k03 "smlal2 v17.4s, v11.8h, v1.h[4] \n"// "smlal v18.4s, v11.4h, v1.h[5] \n"// sum1 += (a03-a73) * k13 "smlal2 v19.4s, v11.8h, v1.h[5] \n"// "smlal v20.4s, v11.4h, v1.h[6] \n"// sum2 += (a03-a73) * k23 "smlal2 v21.4s, v11.8h, v1.h[6] \n"// "smlal v22.4s, v11.4h, v1.h[7] \n"// sum3 += (a03-a73) * k33 "smlal2 v23.4s, v11.8h, v1.h[7] \n"// "subs w4, w4, #1 \n" "bne 0b \n" "1: \n" // remain loop "and w4, %w12, #3 \n"// w4 = remain = inch & 3; "cmp w4, #0 \n" "beq 3f \n" "2: \n" //"prfm pldl1keep, [%5, #128] \n" "ld1 {v0.8b}, [%5] \n" //"prfm pldl1keep, [%4, #128] \n" "ld1 {v8.8b}, [%4], #8 \n" "add %5, %5, #4 \n" "sshll v0.8h, v0.8b, #0 \n" // k00 - k30 "sshll v8.8h, v8.8b, #0 \n" // a00 - a70 // k0 "smlal v16.4s, v8.4h, v0.h[0] \n"// sum0 += (a00-a70) * k00 "smlal2 v17.4s, v8.8h, v0.h[0] \n"// "smlal v18.4s, v8.4h, v0.h[1] \n"// sum1 += (a00-a70) * k10 "smlal2 v19.4s, v8.8h, v0.h[1] \n"// "smlal v20.4s, v8.4h, v0.h[2] \n"// sum2 += (a00-a70) * k20 "smlal2 v21.4s, v8.8h, v0.h[2] \n"// "smlal v22.4s, v8.4h, v0.h[3] \n"// sum3 += (a00-a70) * k30 "smlal2 v23.4s, v8.8h, v0.h[3] \n"// "subs w4, w4, #1 \n" "bne 2b \n" "3: \n" "st1 {v16.4s, v17.4s}, [%0] \n" "st1 {v18.4s, v19.4s}, [%1] \n" "st1 {v20.4s, v21.4s}, [%2] \n" "st1 {v22.4s, v23.4s}, [%3] \n" : "=r"(output0), // %0 "=r"(output1), // %1 "=r"(output2), // %2 "=r"(output3), // %3 "=r"(vb), // %4 "=r"(va) // %5 : "0"(output0), "1"(output1), "2"(output2), "3"(output3), "4"(vb), "5"(va), "r"(L) // %12 : "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" ); #else asm volatile( // K loop "vmov.s32 q8, #0 \n" "vmov.s32 q9, #0 \n" "vmov.s32 q10, #0 \n" "vmov.s32 q11, #0 \n" "vmov.s32 q12, #0 \n" "vmov.s32 q13, #0 \n" "vmov.s32 q14, #0 \n" "vmov.s32 q15, #0 \n" "lsr r4, %12, #3 \n"// r4 = nn = L >> 3 "cmp r4, #0 \n" "beq 1f \n" "0: \n"// for(; nn != 0; nn--) "pld [%4, #128] \n" "vld1.s8 {d8-d11}, [%4]! \n"// tmpr a00-a07,a10-a17,a20-a27,a30-a37 a(inch)(data) "vmovl.s8 q7, d11 \n"// a30-a37 "vmovl.s8 q6, d10 \n"// a20-a27 "vmovl.s8 q5, d9 \n"// a10-a17 "vmovl.s8 q4, d8 \n"// a00-a07 "pld [%5, #128] \n" "vld1.s8 {d0-d3}, [%5]! \n"// kptr k00-k30,k01-k31, k02-k32,k03-k33, k04-k34,k05-k35, k06-k36,k07-k37 k(outch)(inch) "vmovl.s8 q3, d3 \n"// k06-k36,k07-k37 "vmovl.s8 q2, d2 \n"// k04-k34,k05-k35 "vmovl.s8 q1, d1 \n"// k02-k32,k03-k33 "vmovl.s8 q0, d0 \n"// k00-k30,k01-k31 "vmlal.s16 q8, d8, d0[0] \n"// sum0 = (a00-a07) * k00 "vmlal.s16 q9, d9, d0[0] \n" "vmlal.s16 q10, d8, d0[1] \n"// sum1 = (a00-a07) * k10 "vmlal.s16 q11, d9, d0[1] \n" "vmlal.s16 q12, d8, d0[2] \n"// sum2 = (a00-a07) * k20 "vmlal.s16 q13, d9, d0[2] \n" "vmlal.s16 q14, d8, d0[3] \n"// sum3 = (a00-a07) * k30 "vmlal.s16 q15, d9, d0[3] \n" "vmlal.s16 q8, d10, d1[0] \n"// sum0 += (a10-a17) * k01 "vmlal.s16 q9, d11, d1[0] \n" "vmlal.s16 q10, d10, d1[1] \n"// sum1 += (a10-a17) * k11 "vmlal.s16 q11, d11, d1[1] \n" "vmlal.s16 q12, d10, d1[2] \n"// sum2 += (a10-a17) * k21 "vmlal.s16 q13, d11, d1[2] \n" "vmlal.s16 q14, d10, d1[3] \n"// sum3 += (a10-a17) * k31 "vmlal.s16 q15, d11, d1[3] \n" "pld [%4, #128] \n" "vld1.s8 {d8-d9}, [%4]! \n"// tmpr a00-a07,a10-a17,a20-a27,a30-a37 a(inch)(data) "vmovl.s8 q5, d9 \n"// a10-a17 "vmovl.s8 q4, d8 \n"// a00-a07 "vmlal.s16 q8, d12, d2[0] \n"// sum0 += (a20-a27) * k02 "vmlal.s16 q9, d13, d2[0] \n" "vmlal.s16 q10, d12, d2[1] \n"// sum1 += (a20-a27) * k12 "vmlal.s16 q11, d13, d2[1] \n" "vmlal.s16 q12, d12, d2[2] \n"// sum2 += (a20-a27) * k22 "vmlal.s16 q13, d13, d2[2] \n" "vmlal.s16 q14, d12, d2[3] \n"// sum3 += (a20-a27) * k32 "vmlal.s16 q15, d13, d2[3] \n" "vmlal.s16 q8, d14, d3[0] \n"// sum0 += (a30-a37) * k03 "vmlal.s16 q9, d15, d3[0] \n" "vmlal.s16 q10, d14, d3[1] \n"// sum1 += (a30-a37) * k13 "vmlal.s16 q11, d15, d3[1] \n" "vmlal.s16 q12, d14, d3[2] \n"// sum2 += (a30-a37) * k23 "vmlal.s16 q13, d15, d3[2] \n" "vmlal.s16 q14, d14, d3[3] \n"// sum3 += (a30-a37) * k33 "vmlal.s16 q15, d15, d3[3] \n" "pld [%4, #128] \n" "vld1.s8 {d0-d1}, [%4]! \n"// tmpr a00-a07,a10-a17,a20-a27,a30-a37 a(inch)(data) "vmovl.s8 q1, d1 \n"// a10-a17 "vmovl.s8 q0, d0 \n"// a00-a07 "vmlal.s16 q8, d8, d4[0] \n"// sum0 += (a40-a47) * k04 "vmlal.s16 q9, d9, d4[0] \n" "vmlal.s16 q10, d8, d4[1] \n"// sum1 += (a40-a47) * k14 "vmlal.s16 q11, d9, d4[1] \n" "vmlal.s16 q12, d8, d4[2] \n"// sum2 += (a40-a47) * k24 "vmlal.s16 q13, d9, d4[2] \n" "vmlal.s16 q14, d8, d4[3] \n"// sum3 += (a40-a47) * k34 "vmlal.s16 q15, d9, d4[3] \n" "vmlal.s16 q8, d10, d5[0] \n"// sum0 += (a50-a57) * k05 "vmlal.s16 q9, d11, d5[0] \n" "vmlal.s16 q10, d10, d5[1] \n"// sum1 += (a50-a57) * k15 "vmlal.s16 q11, d11, d5[1] \n" "vmlal.s16 q12, d10, d5[2] \n"// sum2 += (a50-a57) * k25 "vmlal.s16 q13, d11, d5[2] \n" "vmlal.s16 q14, d10, d5[3] \n"// sum3 += (a50-a57) * k35 "vmlal.s16 q15, d11, d5[3] \n" "vmlal.s16 q8, d0, d6[0] \n"// sum0 += (a60-a67) * k06 "vmlal.s16 q9, d1, d6[0] \n" "vmlal.s16 q10, d0, d6[1] \n"// sum1 += (a60-a67) * k16 "vmlal.s16 q11, d1, d6[1] \n" "vmlal.s16 q12, d0, d6[2] \n"// sum2 += (a60-a67) * k26 "vmlal.s16 q13, d1, d6[2] \n" "vmlal.s16 q14, d0, d6[3] \n"// sum3 += (a60-a67) * k36 "vmlal.s16 q15, d1, d6[3] \n" "vmlal.s16 q8, d2, d7[0] \n"// sum0 += (a70-a77) * k07 "vmlal.s16 q9, d3, d7[0] \n" "vmlal.s16 q10, d2, d7[1] \n"// sum1 += (a70-a77) * k17 "vmlal.s16 q11, d3, d7[1] \n" "vmlal.s16 q12, d2, d7[2] \n"// sum2 += (a70-a77) * k27 "vmlal.s16 q13, d3, d7[2] \n" "vmlal.s16 q14, d2, d7[3] \n"// sum3 += (a70-a77) * k37 "vmlal.s16 q15, d3, d7[3] \n" "subs r4, r4, #1 \n" "bne 0b \n"// end for "1: \n" // remain loop "and r4, %12, #7 \n"// r4 = remain = inch & 7 "cmp r4, #0 \n" "beq 3f \n" "2: \n"// for(; remain != 0; remain--) "vld1.s8 {d2}, [%4]! \n"// tmpr a00-a70 a(inch)(data) "vld1.s8 {d0}, [%5] \n"// kptr k00-k30 k(outch)(inch) "vmovl.s8 q1, d2 \n" "vmovl.s8 q0, d0 \n" "add %5, #4 \n" "vmlal.s16 q8, d2, d0[0] \n"// sum0 += (a00-a70) * k00 "vmlal.s16 q9, d3, d0[0] \n" "vmlal.s16 q10, d2, d0[1] \n"// sum1 += (a00-a70) * k10 "vmlal.s16 q11, d3, d0[1] \n" "vmlal.s16 q12, d2, d0[2] \n"// sum2 += (a00-a70) * k20 "vmlal.s16 q13, d3, d0[2] \n" "vmlal.s16 q14, d2, d0[3] \n"// sum3 += (a00-a70) * k30 "vmlal.s16 q15, d3, d0[3] \n" "subs r4, r4, #1 \n" "bne 2b \n" "3: \n"// store the result to memory "vst1.s32 {d16-d19}, [%0] \n" "vst1.s32 {d20-d23}, [%1] \n" "vst1.s32 {d24-d27}, [%2] \n" "vst1.s32 {d28-d31}, [%3] \n" : "=r"(output0), // %0 "=r"(output1), // %1 "=r"(output2), // %2 "=r"(output3), // %3 "=r"(vb), // %4 "=r"(va) // %5 : "0"(output0), "1"(output1), "2"(output2), "3"(output3), "4"(vb), "5"(va), "r"(L) // %12 : "cc", "memory", "r4", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15" ); #endif // __aarch64__ #else int sum0[8] = {0}; int sum1[8] = {0}; int sum2[8] = {0}; int sum3[8] = {0}; int k=0; for (; k+7<L; k=k+8) { for (int n=0; n<8; n++) { sum0[n] += (int)va[0] * vb[n]; sum1[n] += (int)va[1] * vb[n]; sum2[n] += (int)va[2] * vb[n]; sum3[n] += (int)va[3] * vb[n]; va += 4; sum0[n] += (int)va[0] * vb[n+8]; sum1[n] += (int)va[1] * vb[n+8]; sum2[n] += (int)va[2] * vb[n+8]; sum3[n] += (int)va[3] * vb[n+8]; va += 4; sum0[n] += (int)va[0] * vb[n+16]; sum1[n] += (int)va[1] * vb[n+16]; sum2[n] += (int)va[2] * vb[n+16]; sum3[n] += (int)va[3] * vb[n+16]; va += 4; sum0[n] += (int)va[0] * vb[n+24]; sum1[n] += (int)va[1] * vb[n+24]; sum2[n] += (int)va[2] * vb[n+24]; sum3[n] += (int)va[3] * vb[n+24]; va += 4; sum0[n] += (int)va[0] * vb[n+32]; sum1[n] += (int)va[1] * vb[n+32]; sum2[n] += (int)va[2] * vb[n+32]; sum3[n] += (int)va[3] * vb[n+32]; va += 4; sum0[n] += (int)va[0] * vb[n+40]; sum1[n] += (int)va[1] * vb[n+40]; sum2[n] += (int)va[2] * vb[n+40]; sum3[n] += (int)va[3] * vb[n+40]; va += 4; sum0[n] += (int)va[0] * vb[n+48]; sum1[n] += (int)va[1] * vb[n+48]; sum2[n] += (int)va[2] * vb[n+48]; sum3[n] += (int)va[3] * vb[n+48]; va += 4; sum0[n] += (int)va[0] * vb[n+56]; sum1[n] += (int)va[1] * vb[n+56]; sum2[n] += (int)va[2] * vb[n+56]; sum3[n] += (int)va[3] * vb[n+56]; va -= 28; } va += 32; vb += 64; } for (; k<L; k++) { for (int n=0; n<8; n++) { sum0[n] += (int)va[0] * vb[n]; sum1[n] += (int)va[1] * vb[n]; sum2[n] += (int)va[2] * vb[n]; sum3[n] += (int)va[3] * vb[n]; } va += 4; vb += 8; } for (int n=0; n<8; n++) { output0[n] = sum0[n]; output1[n] = sum1[n]; output2[n] = sum2[n]; output3[n] = sum3[n]; } #endif // __ARM_NEON output0 += 8; output1 += 8; output2 += 8; output3 += 8; } for (; j<N; j++) { signed char* vb = bottom_tm.channel(j/8 + j%8); #if __ARM_NEON && __aarch64__ const signed char* va = kernel_tm.channel(i/8 + (i%8)/4); #else const signed char* va = kernel_tm.channel(i/4); #endif // __ARM_NEON && __aarch64__ #if __ARM_NEON #if __aarch64__ asm volatile( "eor v14.16b, v14.16b, v14.16b \n" // sum0_3 "eor v16.16b, v16.16b, v16.16b \n" // sum0 "eor v17.16b, v17.16b, v17.16b \n" // sum1 "eor v18.16b, v18.16b, v18.16b \n" // sum2 "eor v19.16b, v19.16b, v19.16b \n" // sum3 "lsr w4, %w12, #2 \n"// r4 = nn = L >> 2 "cmp w4, #0 \n" "beq 1f \n" "0: \n"// for (; k+3<L; k=k+4) "prfm pldl1keep, [%5, #128] \n" "ld1 {v0.8b, v1.8b}, [%5], #16 \n" // k //"prfm pldl1keep, [%4, #128] \n" "ld1 {v4.8b}, [%4] \n" // d "add %4, %4, #4 \n" "sshll v0.8h, v0.8b, #0 \n" // k00 - k30,k01 - k31 "sshll v1.8h, v1.8b, #0 \n" // k02 - k32,k03 - k33 "sshll v4.8h, v4.8b, #0 \n" // a00 - a30 "subs w4, w4, #1 \n" // k0 "smlal v16.4s, v0.4h, v4.h[0] \n"// sum0 += (k00-k30) * a00 "smlal2 v17.4s, v0.8h, v4.h[0] \n"// sum1 += (k01-k31) * a10 "smlal v18.4s, v1.4h, v4.h[1] \n"// sum2 += (k02-k32) * a20 "smlal2 v19.4s, v1.8h, v4.h[1] \n"// sum3 += (k03-k33) * a30 "bne 0b \n" "add v16.4s, v16.4s, v18.4s \n" "add v17.4s, v17.4s, v19.4s \n" "add v14.4s, v16.4s, v17.4s \n" "1: \n" // remain loop "and w4, %w12, #3 \n"// w4 = remain = inch & 3; "cmp w4, #0 \n" "beq 3f \n" "2: \n" //"prfm pldl1keep, [%5, #128] \n" "ld1 {v0.8b}, [%5] \n" //"prfm pldl1keep, [4, #128] \n" "ld1 {v4.8b}, [%4] \n" "add %4, %4, #1 \n" "add %5, %5, #4 \n" "subs w4, w4, #1 \n" "sshll v0.8h, v0.8b, #0 \n" // k00 - k30 "sshll v4.8h, v4.8b, #0 \n" // a00 // k0 "smlal v14.4s, v0.4h, v4.h[0] \n"// sum0 += (k00-k30) * a00 "bne 2b \n" "3: \n" "st1 {v14.s}[0], [%0] \n" "st1 {v14.s}[1], [%1] \n" "st1 {v14.s}[2], [%2] \n" "st1 {v14.s}[3], [%3] \n" : "=r"(output0), // %0 "=r"(output1), // %1 "=r"(output2), // %2 "=r"(output3), // %3 "=r"(vb), // %4 "=r"(va) // %5 : "0"(output0), "1"(output1), "2"(output2), "3"(output3), "4"(vb), "5"(va), "r"(L) // %12 : "cc", "memory", "x4", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19" ); #else asm volatile( // inch loop "veor q6, q6, q6 \n" "veor q7, q7, q7 \n" "veor q8, q8, q8 \n" "veor q9, q9, q9 \n" "veor q10, q10, q10 \n" "veor q11, q11, q11 \n" "veor q12, q12, q12 \n" "veor q13, q13, q13 \n" "vmov.s32 q14, #0 \n" "lsr r4, %12, #3 \n"// r4 = nn = L >> 2 "cmp r4, #0 \n" "beq 1f \n" "0: \n"// for(; nn != 0; nn--) "pld [%4, #128] \n" "vld1.s8 {d0}, [%4]! \n"// tmpr a00,a10,a20,a30 a(inch)(data) "vmovl.s8 q0, d0 \n"// a00-a07 "pld [%5, #128] \n" "vld1.s8 {d2-d5}, [%5]! \n"// kptr k00-k30,k01-k31, k02-k32,k03-k33, k04-k34,k05-k35, k06-k36,k07-k37 k(outch)(inch) "vmovl.s8 q4, d5 \n"// k06-k36,k07-k37 "vmovl.s8 q3, d4 \n"// k04-k34,k05-k35 "vmovl.s8 q2, d3 \n"// k02-k32,k03-k33 "vmovl.s8 q1, d2 \n"// k00-k30,k01-k31 "vmlal.s16 q6, d2, d0[0] \n"// (k00-k30) * a00 "vmlal.s16 q7, d3, d0[1] \n"// (k01-k31) * a01 "vmlal.s16 q8, d4, d0[2] \n"// (k02-k32) * a02 "vmlal.s16 q9, d5, d0[3] \n"// (k03-k33) * a03 "vmlal.s16 q10, d6, d1[0] \n"// (k04-k34) * a04 "vmlal.s16 q11, d7, d1[1] \n"// (k05-k35) * a05 "vmlal.s16 q12, d8, d1[2] \n"// (k06-k36) * a06 "vmlal.s16 q13, d9, d1[3] \n"// (k07-k37) * a07 "subs r4, r4, #1 \n" "bne 0b \n"// end for "vadd.s32 q6, q6, q7 \n" "vadd.s32 q9, q9, q8 \n" "vadd.s32 q11, q11, q10 \n" "vadd.s32 q13, q13, q12 \n" "vadd.s32 q9, q9, q6 \n" "vadd.s32 q13, q13, q11 \n" "vadd.s32 q14, q13, q9 \n" "1: \n" // remain loop "and r4, %12, #7 \n"// r4 = remain = inch & 3 "cmp r4, #0 \n" "beq 3f \n" "2: \n"// for(; remain != 0; remain--) "vld1.s8 {d2}, [%4] \n"// tmpr a00 a(inch)(data) "vld1.s8 {d0}, [%5] \n"// kptr k00-k30 k(outch)(inch) "vmovl.s8 q1, d2 \n" "vmovl.s8 q0, d0 \n" "add %4, #1 \n" "add %5, #4 \n" "vmlal.s16 q14, d0, d2[0] \n" "subs r4, r4, #1 \n" "bne 2b \n" "3: \n"// store the result to memory "vst1.s32 {d28[0]}, [%0] \n" "vst1.s32 {d28[1]}, [%1] \n" "vst1.s32 {d29[0]}, [%2] \n" "vst1.s32 {d29[1]}, [%3] \n" : "=r"(output0), // %0 "=r"(output1), // %1 "=r"(output2), // %2 "=r"(output3), // %3 "=r"(vb), // %4 "=r"(va) // %5 : "0"(output0), "1"(output1), "2"(output2), "3"(output3), "4"(vb), "5"(va), "r"(L) // %12 : "cc", "memory", "r4", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14" ); #endif // __aarch64__ #else int sum0 = 0; int sum1 = 0; int sum2 = 0; int sum3 = 0; for (int k=0; k<L; k++) { sum0 += (int)va[0] * vb[0]; sum1 += (int)va[1] * vb[0]; sum2 += (int)va[2] * vb[0]; sum3 += (int)va[3] * vb[0]; va += 4; vb += 1; } output0[0] = sum0; output1[0] = sum1; output2[0] = sum2; output3[0] = sum3; #endif // __ARM_NEON output0++; output1++; output2++; output3++; } } remain_outch_start += nn_outch << 2; #pragma omp parallel for num_threads(opt.num_threads) for (int i=remain_outch_start; i<outch; i++) { int* output = top_blob.channel(i); int j=0; for (; j+7<N; j=j+8) { signed char* vb = bottom_tm.channel(j/8); #if __ARM_NEON && __aarch64__ const signed char* va = kernel_tm.channel(i/8 + (i%8)/4 + i%4); #else const signed char* va = kernel_tm.channel(i/4 + i%4); #endif // __ARM_NEON && __aarch64__ #if __ARM_NEON #if __aarch64__ asm volatile( "eor v16.16b, v16.16b, v16.16b \n" // sum0 "eor v17.16b, v17.16b, v17.16b \n" // sum0n "lsr w4, %w6, #2 \n"// r4 = nn = L >> 2 "cmp w4, #0 \n" "beq 1f \n" "0: \n"// for (; k+3<L; k=k+4) "prfm pldl1keep, [%2, #128] \n" "ld1 {v0.8b}, [%2] \n" "prfm pldl1keep, [%1, #128] \n" "ld1 {v8.8b, v9.8b, v10.8b, v11.8b}, [%1], #32 \n" "add %2, %2, #4 \n" "sshll v0.8h, v0.8b, #0 \n" // k00 - k03 "sshll v8.8h, v8.8b, #0 \n" // a00 - a70 "sshll v9.8h, v9.8b, #0 \n" // a01 - a71 "sshll v10.8h, v10.8b, #0 \n" // a02 - a72 "sshll v11.8h, v11.8b, #0 \n" // a03 - a73 // k0 "smlal v16.4s, v8.4h, v0.h[0] \n"// sum0 += (a00-a70) * k00 "smlal2 v17.4s, v8.8h, v0.h[0] \n"// // k1 "smlal v16.4s, v9.4h, v0.h[1] \n"// sum0 += (a01-a71) * k01 "smlal2 v17.4s, v9.8h, v0.h[1] \n"// // k2 "smlal v16.4s, v10.4h, v0.h[2] \n"// sum0 += (a02-a72) * k02 "smlal2 v17.4s, v10.8h, v0.h[2] \n"// // k3 "smlal v16.4s, v11.4h, v0.h[3] \n"// sum0 += (a03-a73) * k03 "smlal2 v17.4s, v11.8h, v0.h[3] \n"// "subs w4, w4, #1 \n" "bne 0b \n" "1: \n" // remain loop "and w4, %w6, #3 \n"// w4 = remain = inch & 3; "cmp w4, #0 \n" "beq 3f \n" "2: \n" //"prfm pldl1keep, [%2, #128] \n" "ld1 {v0.8b}, [%2] \n" //"prfm pldl1keep, [%1, #128] \n" "ld1 {v8.8b}, [%1], #8 \n" "add %2, %2, #1 \n" "sshll v0.8h, v0.8b, #0 \n" // k00 - k30 "sshll v8.8h, v8.8b, #0 \n" // a00 - a70 // k0 "smlal v16.4s, v8.4h, v0.h[0] \n"// sum0 += (a00-a70) * k00 "smlal2 v17.4s, v8.8h, v0.h[0] \n"// "subs w4, w4, #1 \n" "bne 2b \n" "3: \n" "st1 {v16.4s, v17.4s}, [%0] \n" : "=r"(output), // %0 "=r"(vb), // %1 "=r"(va) // %2 : "0"(output), "1"(vb), "2"(va), "r"(L) // %6 : "cc", "memory", "x4", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17" ); #else asm volatile( // inch loop "vmov.s32 q6, #0 \n" "vmov.s32 q7, #0 \n" "lsr r4, %6, #3 \n"// r4 = nn = inch >> 3 "cmp r4, #0 \n" "beq 1f \n" "0: \n"// for(; nn != 0; nn--) "pld [%1, #128] \n" "vld1.s8 {d4-d7}, [%1]! \n"// tmpr a00-a07,a10-a17,a20-a27,a30-a37 a(inch)(data) "vmovl.s8 q5, d7 \n"// a30-a37 "vmovl.s8 q4, d6 \n"// a20-a27 "vmovl.s8 q3, d5 \n"// a10-a17 "vmovl.s8 q2, d4 \n"// a00-a07 "pld [%2, #128] \n" "vld1.s8 {d0}, [%2]! \n"// kptr k00-k07 k(outch)(inch) "vmovl.s8 q1, d1 \n"// k04,k05,k06,k07 "vmovl.s8 q0, d0 \n"// k00,k01,k02,k03 "vmlal.s16 q6, d4, d0[0] \n"// (a00-a07) * k00 "vmlal.s16 q7, d5, d0[0] \n" "vmlal.s16 q6, d6, d0[1] \n"// (a10-a17) * k01 "vmlal.s16 q7, d7, d0[1] \n" "vmlal.s16 q6, d8, d0[2] \n"// (a20-a27) * k02 "vmlal.s16 q7, d9, d0[2] \n" "vmlal.s16 q6, d10, d0[3] \n"// (a30-a37) * k03 "vmlal.s16 q7, d11, d0[3] \n" "pld [%1, #128] \n" "vld1.s8 {d4-d7}, [%1]! \n"// tmpr a40-a47,a50-a57,a60-a67,a70-a77 a(inch)(data) "vmovl.s8 q5, d7 \n"// a70-a77 "vmovl.s8 q4, d6 \n"// a60-a67 "vmovl.s8 q3, d5 \n"// a50-a57 "vmovl.s8 q2, d4 \n"// a40-a47 "vmlal.s16 q6, d4, d1[0] \n"// (a00-a07) * k00 "vmlal.s16 q7, d5, d1[0] \n" "vmlal.s16 q6, d6, d1[1] \n"// (a10-a17) * k01 "vmlal.s16 q7, d7, d1[1] \n" "vmlal.s16 q6, d8, d1[2] \n"// (a20-a27) * k02 "vmlal.s16 q7, d9, d1[2] \n" "vmlal.s16 q6, d10, d1[3] \n"// (a30-a37) * k03 "vmlal.s16 q7, d11, d1[3] \n" "subs r4, r4, #1 \n" "bne 0b \n"// end for "1: \n" // remain loop "and r4, %6, #7 \n"// r4 = remain = inch & 7 "cmp r4, #0 \n" "beq 3f \n" "2: \n"// for(; remain != 0; remain--) "vld1.s8 {d2}, [%1]! \n"// tmpr a00-a07 a(inch)(data) "vld1.s8 {d0}, [%2] \n"// kptr k00 k(outch)(inch) "vmovl.s8 q1, d2 \n" "vmovl.s8 q0, d0 \n" "add %2, #1 \n" "vmlal.s16 q6, d2, d0[0] \n"// (a00-a07) * k00 "vmlal.s16 q7, d3, d0[0] \n" "subs r4, r4, #1 \n" "bne 2b \n" "3: \n"// store the result to memory "vst1.s32 {d12-d15}, [%0] \n" : "=r"(output), // %0 "=r"(vb), // %1 "=r"(va) // %2 : "0"(output), "1"(vb), "2"(va), "r"(L) // %6 : "cc", "memory", "r4", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7" ); #endif // __aarch64__ #else int sum[8] = {0}; int k=0; for (; k+7<L; k=k+8) { for (int n=0; n<8; n++) { sum[n] += (int)va[0] * vb[n]; sum[n] += (int)va[1] * vb[n+8]; sum[n] += (int)va[2] * vb[n+16]; sum[n] += (int)va[3] * vb[n+24]; sum[n] += (int)va[4] * vb[n+32]; sum[n] += (int)va[5] * vb[n+40]; sum[n] += (int)va[6] * vb[n+48]; sum[n] += (int)va[7] * vb[n+56]; } va += 8; vb += 64; } for (; k<L; k++) { for (int n=0; n<8; n++) { sum[n] += (int)va[0] * vb[n]; } va += 1; vb += 8; } for (int n=0; n<8; n++) { output[n] = sum[n]; } #endif // __ARM_NEON output += 8; } for (; j<N; j++) { int sum = 0; signed char* vb = bottom_tm.channel(j/8 + j%8); #if __ARM_NEON && __aarch64__ const signed char* va = kernel_tm.channel(i/8 + (i%8)/4 + i%4); #else const signed char* va = kernel_tm.channel(i/4 + i%4); #endif // __ARM_NEON && __aarch64__ for (int k=0; k<L; k++) { sum += (int)va[0] * vb[0]; va += 1; vb += 1; } output[0] = sum; output++; } } } } #endif
KDTree.h
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #ifndef _SPTAG_COMMON_KDTREE_H_ #define _SPTAG_COMMON_KDTREE_H_ #include <vector> #include <string> #include <shared_mutex> #include "../VectorIndex.h" #include "CommonUtils.h" #include "QueryResultSet.h" #include "WorkSpace.h" namespace SPTAG { namespace COMMON { // node type for storing KDT struct KDTNode { SizeType left; SizeType right; DimensionType split_dim; float split_value; }; class KDTree { public: KDTree() : m_iTreeNumber(2), m_numTopDimensionKDTSplit(5), m_iSamples(1000), m_lock(new std::shared_timed_mutex) {} KDTree(const KDTree& other) : m_iTreeNumber(other.m_iTreeNumber), m_numTopDimensionKDTSplit(other.m_numTopDimensionKDTSplit), m_iSamples(other.m_iSamples), m_lock(new std::shared_timed_mutex) {} ~KDTree() {} inline const KDTNode& operator[](SizeType index) const { return m_pTreeRoots[index]; } inline KDTNode& operator[](SizeType index) { return m_pTreeRoots[index]; } inline SizeType size() const { return (SizeType)m_pTreeRoots.size(); } inline SizeType sizePerTree() const { std::shared_lock<std::shared_timed_mutex> lock(*m_lock); return (SizeType)m_pTreeRoots.size() - m_pTreeStart.back(); } template <typename T> void Rebuild(const Dataset<T>& data) { COMMON::KDTree newTrees(*this); newTrees.BuildTrees<T>(data, 1); std::unique_lock<std::shared_timed_mutex> lock(*m_lock); m_pTreeRoots.swap(newTrees.m_pTreeRoots); m_pTreeStart.swap(newTrees.m_pTreeStart); } template <typename T> void BuildTrees(const Dataset<T>& data, int numOfThreads, std::vector<SizeType>* indices = nullptr) { std::vector<SizeType> localindices; if (indices == nullptr) { localindices.resize(data.R()); for (SizeType i = 0; i < localindices.size(); ++i) localindices[i] = i; } else { localindices.assign(indices->begin(), indices->end()); } m_pTreeRoots.resize(m_iTreeNumber * localindices.size()); m_pTreeStart.resize(m_iTreeNumber, 0); #pragma omp parallel for num_threads(numOfThreads) for (int i = 0; i < m_iTreeNumber; ++i) { Sleep(i * 100); std::srand(clock()); std::vector<SizeType> pindices(localindices.begin(), localindices.end()); std::random_shuffle(pindices.begin(), pindices.end()); m_pTreeStart[i] = i * (SizeType)pindices.size(); LOG(Helper::LogLevel::LL_Info, "Start to build KDTree %d\n", i + 1); SizeType iTreeSize = m_pTreeStart[i]; DivideTree<T>(data, pindices, 0, (SizeType)pindices.size() - 1, m_pTreeStart[i], iTreeSize); LOG(Helper::LogLevel::LL_Info, "%d KDTree built, %d %zu\n", i + 1, iTreeSize - m_pTreeStart[i], pindices.size()); } } inline std::uint64_t BufferSize() const { return sizeof(int) + sizeof(SizeType) * m_iTreeNumber + sizeof(SizeType) + sizeof(KDTNode) * m_pTreeRoots.size(); } ErrorCode SaveTrees(std::shared_ptr<Helper::DiskPriorityIO> p_out) const { std::shared_lock<std::shared_timed_mutex> lock(*m_lock); IOBINARY(p_out, WriteBinary, sizeof(m_iTreeNumber), (char*)&m_iTreeNumber); IOBINARY(p_out, WriteBinary, sizeof(SizeType) * m_iTreeNumber, (char*)m_pTreeStart.data()); SizeType treeNodeSize = (SizeType)m_pTreeRoots.size(); IOBINARY(p_out, WriteBinary, sizeof(treeNodeSize), (char*)&treeNodeSize); IOBINARY(p_out, WriteBinary, sizeof(KDTNode) * treeNodeSize, (char*)m_pTreeRoots.data()); LOG(Helper::LogLevel::LL_Info, "Save KDT (%d,%d) Finish!\n", m_iTreeNumber, treeNodeSize); return ErrorCode::Success; } ErrorCode SaveTrees(std::string sTreeFileName) const { LOG(Helper::LogLevel::LL_Info, "Save KDT to %s\n", sTreeFileName.c_str()); auto ptr = f_createIO(); if (ptr == nullptr || !ptr->Initialize(sTreeFileName.c_str(), std::ios::binary | std::ios::out)) return ErrorCode::FailedCreateFile; return SaveTrees(ptr); } ErrorCode LoadTrees(char* pKDTMemFile) { m_iTreeNumber = *((int*)pKDTMemFile); pKDTMemFile += sizeof(int); m_pTreeStart.resize(m_iTreeNumber); memcpy(m_pTreeStart.data(), pKDTMemFile, sizeof(SizeType) * m_iTreeNumber); pKDTMemFile += sizeof(SizeType)*m_iTreeNumber; SizeType treeNodeSize = *((SizeType*)pKDTMemFile); pKDTMemFile += sizeof(SizeType); m_pTreeRoots.resize(treeNodeSize); memcpy(m_pTreeRoots.data(), pKDTMemFile, sizeof(KDTNode) * treeNodeSize); LOG(Helper::LogLevel::LL_Info, "Load KDT (%d,%d) Finish!\n", m_iTreeNumber, treeNodeSize); return ErrorCode::Success; } ErrorCode LoadTrees(std::shared_ptr<Helper::DiskPriorityIO> p_input) { IOBINARY(p_input, ReadBinary, sizeof(m_iTreeNumber), (char*)&m_iTreeNumber); m_pTreeStart.resize(m_iTreeNumber); IOBINARY(p_input, ReadBinary, sizeof(SizeType) * m_iTreeNumber, (char*)m_pTreeStart.data()); SizeType treeNodeSize; IOBINARY(p_input, ReadBinary, sizeof(treeNodeSize), (char*)&treeNodeSize); m_pTreeRoots.resize(treeNodeSize); IOBINARY(p_input, ReadBinary, sizeof(KDTNode) * treeNodeSize, (char*)m_pTreeRoots.data()); LOG(Helper::LogLevel::LL_Info, "Load KDT (%d,%d) Finish!\n", m_iTreeNumber, treeNodeSize); return ErrorCode::Success; } ErrorCode LoadTrees(std::string sTreeFileName) { LOG(Helper::LogLevel::LL_Info, "Load KDT From %s\n", sTreeFileName.c_str()); auto ptr = f_createIO(); if (ptr == nullptr || !ptr->Initialize(sTreeFileName.c_str(), std::ios::binary | std::ios::in)) return ErrorCode::FailedOpenFile; return LoadTrees(ptr); } template <typename T> void InitSearchTrees(const Dataset<T>& p_data, float(*fComputeDistance)(const T* pX, const T* pY, DimensionType length), const COMMON::QueryResultSet<T> &p_query, COMMON::WorkSpace &p_space) const { for (int i = 0; i < m_iTreeNumber; ++i) { KDTSearch(p_data, fComputeDistance, p_query, p_space, m_pTreeStart[i], 0); } } template <typename T> void SearchTrees(const Dataset<T>& p_data, float(*fComputeDistance)(const T* pX, const T* pY, DimensionType length), const COMMON::QueryResultSet<T> &p_query, COMMON::WorkSpace &p_space, const int p_limits) const { while (!p_space.m_SPTQueue.empty() && p_space.m_iNumberOfCheckedLeaves < p_limits) { auto& tcell = p_space.m_SPTQueue.pop(); KDTSearch(p_data, fComputeDistance, p_query, p_space, tcell.node, tcell.distance); } } private: template <typename T> void KDTSearch(const Dataset<T>& p_data, float(*fComputeDistance)(const T* pX, const T* pY, DimensionType length), const COMMON::QueryResultSet<T> &p_query, COMMON::WorkSpace& p_space, const SizeType node, const float distBound) const { if (node < 0) { SizeType index = -node - 1; if (index >= p_data.R()) return; #ifdef PREFETCH const T* data = p_data[index]; _mm_prefetch((const char*)data, _MM_HINT_T0); _mm_prefetch((const char*)(data + 64), _MM_HINT_T0); #endif if (p_space.CheckAndSet(index)) return; ++p_space.m_iNumberOfTreeCheckedLeaves; ++p_space.m_iNumberOfCheckedLeaves; p_space.m_NGQueue.insert(COMMON::HeapCell(index, fComputeDistance(p_query.GetTarget(), data, p_data.C()))); return; } auto& tnode = m_pTreeRoots[node]; float diff = (p_query.GetTarget())[tnode.split_dim] - tnode.split_value; float distanceBound = distBound + diff * diff; SizeType otherChild, bestChild; if (diff < 0) { bestChild = tnode.left; otherChild = tnode.right; } else { otherChild = tnode.left; bestChild = tnode.right; } p_space.m_SPTQueue.insert(COMMON::HeapCell(otherChild, distanceBound)); KDTSearch(p_data, fComputeDistance, p_query, p_space, bestChild, distBound); } template <typename T> void DivideTree(const Dataset<T>& data, std::vector<SizeType>& indices, SizeType first, SizeType last, SizeType index, SizeType &iTreeSize) { ChooseDivision<T>(data, m_pTreeRoots[index], indices, first, last); SizeType i = Subdivide<T>(data, m_pTreeRoots[index], indices, first, last); if (i - 1 <= first) { m_pTreeRoots[index].left = -indices[first] - 1; } else { iTreeSize++; m_pTreeRoots[index].left = iTreeSize; DivideTree<T>(data, indices, first, i - 1, iTreeSize, iTreeSize); } if (last == i) { m_pTreeRoots[index].right = -indices[last] - 1; } else { iTreeSize++; m_pTreeRoots[index].right = iTreeSize; DivideTree<T>(data, indices, i, last, iTreeSize, iTreeSize); } } template <typename T> void ChooseDivision(const Dataset<T>& data, KDTNode& node, const std::vector<SizeType>& indices, const SizeType first, const SizeType last) { std::vector<float> meanValues(data.C(), 0); std::vector<float> varianceValues(data.C(), 0); SizeType end = std::min(first + m_iSamples, last); SizeType count = end - first + 1; // calculate the mean of each dimension for (SizeType j = first; j <= end; ++j) { const T* v = (const T*)data[indices[j]]; for (DimensionType k = 0; k < data.C(); k++) { meanValues[k] += v[k]; } } for (DimensionType k = 0; k < data.C(); k++) { meanValues[k] /= count; } // calculate the variance of each dimension for (SizeType j = first; j <= end; ++j) { const T* v = (const T*)data[indices[j]]; for (DimensionType k = 0; k < data.C(); k++) { float dist = v[k] - meanValues[k]; varianceValues[k] += dist*dist; } } // choose the split dimension as one of the dimension inside TOP_DIM maximum variance node.split_dim = SelectDivisionDimension(varianceValues); // determine the threshold node.split_value = meanValues[node.split_dim]; } DimensionType SelectDivisionDimension(const std::vector<float>& varianceValues) const { // Record the top maximum variances std::vector<DimensionType> topind(m_numTopDimensionKDTSplit); int num = 0; // order the variances for (DimensionType i = 0; i < (DimensionType)varianceValues.size(); ++i) { if (num < m_numTopDimensionKDTSplit || varianceValues[i] > varianceValues[topind[num - 1]]) { if (num < m_numTopDimensionKDTSplit) { topind[num++] = i; } else { topind[num - 1] = i; } int j = num - 1; // order the TOP_DIM variances while (j > 0 && varianceValues[topind[j]] > varianceValues[topind[j - 1]]) { Kokkos::swap(topind[j], topind[j - 1]); j--; } } } // randomly choose a dimension from TOP_DIM return topind[COMMON::Utils::rand(num)]; } template <typename T> SizeType Subdivide(const Dataset<T>& data, const KDTNode& node, std::vector<SizeType>& indices, const SizeType first, const SizeType last) const { SizeType i = first; SizeType j = last; // decide which child one point belongs while (i <= j) { SizeType ind = indices[i]; const T* v = (const T*)data[ind]; float val = v[node.split_dim]; if (val < node.split_value) { i++; } else { Kokkos::swap(indices[i], indices[j]); j--; } } // if all the points in the node are equal,equally split the node into 2 if ((i == first) || (i == last + 1)) { i = (first + last + 1) / 2; } return i; } private: std::vector<SizeType> m_pTreeStart; std::vector<KDTNode> m_pTreeRoots; public: std::unique_ptr<std::shared_timed_mutex> m_lock; int m_iTreeNumber, m_numTopDimensionKDTSplit, m_iSamples; }; } } #endif
util.h
/* Copyright (c) 2013, Taiga Nomi 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 <organization> 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. */ #pragma once #include <vector> #include <functional> #include <random> #include <type_traits> #include <limits> #include <cassert> #include <cstdio> #include <cstdarg> #ifdef CNN_USE_TBB #ifndef NOMINMAX #define NOMINMAX // tbb includes windows.h in tbb/machine/windows_api.h #endif #include <tbb/tbb.h> #include <tbb/task_group.h> #endif #define CNN_UNREFERENCED_PARAMETER(x) (void)(x) namespace tiny_cnn { typedef double float_t; typedef unsigned short layer_size_t; typedef size_t label_t; typedef std::vector<float_t> vec_t; class nn_error : public std::exception { public: explicit nn_error(const std::string& msg) : msg_(msg) {} const char* what() const throw() override { return msg_.c_str(); } private: std::string msg_; }; template<typename T> inline typename std::enable_if<std::is_integral<T>::value, T>::type uniform_rand(T min, T max) { // avoid gen(0) for MSVC known issue // https://connect.microsoft.com/VisualStudio/feedback/details/776456 static std::mt19937 gen(1); std::uniform_int_distribution<T> dst(min, max); return dst(gen); } template<typename T> inline typename std::enable_if<std::is_floating_point<T>::value, T>::type uniform_rand(T min, T max) { static std::mt19937 gen(1); std::uniform_real_distribution<T> dst(min, max); return dst(gen); } template<typename Container> inline int uniform_idx(const Container& t) { return uniform_rand(0, (int) t.size() - 1); } inline bool bernoulli(double p) { return uniform_rand(0.0, 1.0) <= p; } template<typename Iter> void uniform_rand(Iter begin, Iter end, float_t min, float_t max) { for (Iter it = begin; it != end; ++it) *it = uniform_rand(min, max); } template<typename T> T* reverse_endian(T* p) { std::reverse(reinterpret_cast<char*>(p), reinterpret_cast<char*>(p) + sizeof(T)); return p; } inline bool is_little_endian() { int x = 1; return *(char*) &x != 0; } template<typename T> int max_index(const T& vec) { typename T::value_type max_val = std::numeric_limits<typename T::value_type>::lowest(); int max_index = -1; for (size_t i = 0; i < vec.size(); i++) { if (vec[i] > max_val) { max_index = i; max_val = vec[i]; } } return max_index; } template<typename T, typename U> U rescale(T x, T src_min, T src_max, U dst_min, U dst_max) { U value = static_cast<U>(((x - src_min) * (dst_max - dst_min)) / (src_max - src_min) + dst_min); return std::min(dst_max, std::max(value, dst_min)); } inline void nop() { // do nothing } #ifdef CNN_USE_TBB static tbb::task_scheduler_init tbbScheduler(tbb::task_scheduler_init::automatic);//tbb::task_scheduler_init::deferred); typedef tbb::blocked_range<int> blocked_range; typedef tbb::task_group task_group; template<typename Func> void parallel_for(int begin, int end, const Func& f) { tbb::parallel_for(blocked_range(begin, end, 100), f); } template<typename Func> void xparallel_for(int begin, int end, const Func& f) { f(blocked_range(begin, end, 100)); } template<typename Func> void for_(bool parallelize, int begin, int end, Func f) { parallelize ? parallel_for(begin, end, f) : xparallel_for(begin, end, f); } #else struct blocked_range { typedef int const_iterator; blocked_range(int begin, int end) : begin_(begin), end_(end) {} const_iterator begin() const { return begin_; } const_iterator end() const { return end_; } private: int begin_; int end_; }; template<typename Func> void xparallel_for(size_t begin, size_t end, const Func& f) { blocked_range r(begin, end); f(r); } #ifdef CNN_USE_OMP template<typename Func> void parallel_for(int begin, int end, const Func& f) { #pragma omp parallel for for (int i=begin; i<end; ++i) f(blocked_range(i,i+1)); } template<typename T, typename U> bool const value_representation(U const &value) { return static_cast<U>(static_cast<T>(value)) == value; } template<typename Func> void for_(bool parallelize, size_t begin, size_t end, Func f) { parallelize = parallelize && value_representation<int>(begin); parallelize = parallelize && value_representation<int>(end); parallelize? parallel_for(static_cast<int>(begin), static_cast<int>(end), f) : xparallel_for(begin, end, f); } #else template<typename Func> void for_(bool /*parallelize*/, size_t begin, size_t end, Func f) { // ignore parallelize if you don't define CNN_USE_TBB xparallel_for(begin, end, f); } #endif class task_group { public: template<typename Func> void run(Func f) { functions_.push_back(f); } void wait() { for (auto f : functions_) f(); } private: std::vector<std::function<void()>> functions_; }; #endif // CNN_USE_TBB template <typename Func> void for_i(bool parallelize, int size, Func f) { for_(parallelize, 0, size, [&](const blocked_range& r) { #ifdef CNN_USE_OMP #pragma omp parallel for #endif for (int i = r.begin(); i < r.end(); i++) f(i); }); } template <typename Func> void for_i(int size, Func f) { for_i(true, size, f); } template <typename T> inline T sqr(T value) { return value*value; } inline bool isfinite(float_t x) { return x == x; } template <typename Container> inline bool has_infinite(const Container& c) { for (auto v : c) if (!isfinite(v)) return true; return false; } template <typename Container> size_t max_size(const Container& c) { typedef typename Container::value_type value_t; return std::max_element(c.begin(), c.end(), [](const value_t& left, const value_t& right) { return left.size() < right.size(); })->size(); } inline std::string format_str(const char *fmt, ...) { static char buf[2048]; #ifdef _MSC_VER #pragma warning(disable:4996) #endif va_list args; va_start(args, fmt); vsnprintf(buf, sizeof(buf), fmt, args); va_end(args); #ifdef _MSC_VER #pragma warning(default:4996) #endif return std::string(buf); } template <typename T> struct index3d { index3d(T width, T height, T depth) : width_(width), height_(height), depth_(depth) { if ((long long) width * height * depth > std::numeric_limits<T>::max()) throw nn_error( format_str("error while constructing layer: layer size too large for tiny-cnn\nWidthxHeightxChannels=%dx%dx%d >= max size of [%s](=%d)", width, height, depth, typeid(T).name(), std::numeric_limits<T>::max())); } T get_index(T x, T y, T channel) const { return (height_ * channel + y) * width_ + x; } T size() const { return width_ * height_ * depth_; } T width_; T height_; T depth_; }; template <typename Stream, typename T> Stream& operator << (Stream& s, const index3d<T>& d) { s << d.width_ << "x" << d.height_ << "x" << d.depth_; return s; } // boilerplate to resolve dependent name #define CNN_USE_LAYER_MEMBERS using layer_base::in_size_;\ using layer_base::out_size_; \ using layer_base::parallelize_; \ using layer_base::next_; \ using layer_base::prev_; \ using layer_base::a_; \ using layer_base::output_; \ using layer_base::prev_delta_; \ using layer_base::W_; \ using layer_base::b_; \ using layer_base::dW_; \ using layer_base::db_; \ using layer_base::Whessian_; \ using layer_base::bhessian_; \ using layer_base::prev_delta2_; \ using layer<Activation>::h_ } // namespace tiny_cnn
conv.h
#ifndef CONV_H #define CONV_H namespace TSnap { /// Sequentially converts the table into a graph with links from nodes in \c SrcCol to those in \c DstCol. template<class PGraph> PGraph ToGraph(PTable Table, const TStr& SrcCol, const TStr& DstCol, TAttrAggr AggrPolicy) { PGraph Graph = PGraph::TObj::New(); const TAttrType NodeType = Table->GetColType(SrcCol); Assert(NodeType == Table->GetColType(DstCol)); const TInt SrcColIdx = Table->GetColIdx(SrcCol); const TInt DstColIdx = Table->GetColIdx(DstCol); // make single pass over all rows in the table if (NodeType == atInt) { for (int CurrRowIdx = 0; CurrRowIdx < (Table->Next).Len(); CurrRowIdx++) { if ((Table->Next)[CurrRowIdx] == Table->Invalid) { continue; } // add src and dst nodes to graph if they are not seen earlier TInt SVal = (Table->IntCols)[SrcColIdx][CurrRowIdx]; TInt DVal = (Table->IntCols)[DstColIdx][CurrRowIdx]; //Using AddNodeUnchecked ensures that no error is thrown when the same node is seen twice Graph->AddNodeUnchecked(SVal); Graph->AddNodeUnchecked(DVal); Graph->AddEdgeUnchecked(SVal, DVal); } } else if (NodeType == atFlt) { // node values - i.e. the unique values of src/dst col //THashSet<TInt> IntNodeVals; // for both int and string node attr types. THash<TFlt, TInt> FltNodeVals; for (int CurrRowIdx = 0; CurrRowIdx < (Table->Next).Len(); CurrRowIdx++) { if ((Table->Next)[CurrRowIdx] == Table->Invalid) { continue; } // add src and dst nodes to graph if they are not seen earlier TInt SVal, DVal; TFlt FSVal = (Table->FltCols)[SrcColIdx][CurrRowIdx]; SVal = Table->CheckAndAddFltNode(Graph, FltNodeVals, FSVal); TFlt FDVal = (Table->FltCols)[SrcColIdx][CurrRowIdx]; DVal = Table->CheckAndAddFltNode(Graph, FltNodeVals, FDVal); Graph->AddEdge(SVal, DVal); } } else { for (int CurrRowIdx = 0; CurrRowIdx < (Table->Next).Len(); CurrRowIdx++) { if ((Table->Next)[CurrRowIdx] == Table->Invalid) { continue; } // add src and dst nodes to graph if they are not seen earlier TInt SVal = (Table->StrColMaps)[SrcColIdx][CurrRowIdx]; // if (strlen(Table->GetContextKey(SVal)) == 0) { continue; } //illegal value TInt DVal = (Table->StrColMaps)[DstColIdx][CurrRowIdx]; // if (strlen(Table->GetContextKey(DVal)) == 0) { continue; } //illegal value //Using AddNodeUnchecked ensures that no error is thrown when the same node is seen twice Graph->AddNodeUnchecked(SVal); Graph->AddNodeUnchecked(DVal); Graph->AddEdgeUnchecked(SVal, DVal); } } Graph->SortNodeAdjV(); return Graph; } /// Converts the Table into a graph with edges from \c SrcCol to \c DstCol, and attribute vector defined by the arguments. template<class PGraph> PGraph ToNetwork(PTable Table, const TStr& SrcCol, const TStr& DstCol, TStrV& SrcAttrV, TStrV& DstAttrV, TStrV& EdgeAttrV, TAttrAggr AggrPolicy) { PGraph Graph = PGraph::TObj::New(); const TAttrType NodeType = Table->GetColType(SrcCol); Assert(NodeType == Table->GetColType(DstCol)); const TInt SrcColIdx = Table->GetColIdx(SrcCol); const TInt DstColIdx = Table->GetColIdx(DstCol); //Table->AddGraphAttributeV(SrcAttrV, false, true, false); //Table->AddGraphAttributeV(DstAttrV, false, false, true); //Table->AddGraphAttributeV(EdgeAttrV, true, false, true); // node values - i.e. the unique values of src/dst col //THashSet<TInt> IntNodeVals; // for both int and string node attr types. THash<TFlt, TInt> FltNodeVals; // node attributes THash<TInt, TStrIntVH> NodeIntAttrs; THash<TInt, TStrFltVH> NodeFltAttrs; THash<TInt, TStrStrVH> NodeStrAttrs; // make single pass over all rows in the table for (int CurrRowIdx = 0; CurrRowIdx < (Table->Next).Len(); CurrRowIdx++) { if ((Table->Next)[CurrRowIdx] == Table->Invalid) { continue; } // add src and dst nodes to graph if they are not seen earlier TInt SVal, DVal; if (NodeType == atFlt) { TFlt FSVal = (Table->FltCols)[SrcColIdx][CurrRowIdx]; SVal = Table->CheckAndAddFltNode(Graph, FltNodeVals, FSVal); TFlt FDVal = (Table->FltCols)[SrcColIdx][CurrRowIdx]; DVal = Table->CheckAndAddFltNode(Graph, FltNodeVals, FDVal); } else if (NodeType == atInt || NodeType == atStr) { if (NodeType == atInt) { SVal = (Table->IntCols)[SrcColIdx][CurrRowIdx]; DVal = (Table->IntCols)[DstColIdx][CurrRowIdx]; } else { SVal = (Table->StrColMaps)[SrcColIdx][CurrRowIdx]; if (strlen(Table->GetContextKey(SVal)) == 0) { continue; } //illegal value DVal = (Table->StrColMaps)[DstColIdx][CurrRowIdx]; if (strlen(Table->GetContextKey(DVal)) == 0) { continue; } //illegal value } if (!Graph->IsNode(SVal)) {Graph->AddNode(SVal); } if (!Graph->IsNode(DVal)) {Graph->AddNode(DVal); } //CheckAndAddIntNode(Graph, IntNodeVals, SVal); //CheckAndAddIntNode(Graph, IntNodeVals, DVal); } // add edge and edge attributes Graph->AddEdge(SVal, DVal, CurrRowIdx); // Aggregate edge attributes and add to graph for (TInt i = 0; i < EdgeAttrV.Len(); i++) { TStr ColName = EdgeAttrV[i]; TAttrType T = Table->GetColType(ColName); TInt Index = Table->GetColIdx(ColName); switch (T) { case atInt: Graph->AddIntAttrDatE(CurrRowIdx, Table->IntCols[Index][CurrRowIdx], ColName); break; case atFlt: Graph->AddFltAttrDatE(CurrRowIdx, Table->FltCols[Index][CurrRowIdx], ColName); break; case atStr: Graph->AddStrAttrDatE(CurrRowIdx, Table->GetStrValIdx(Index, CurrRowIdx), ColName); break; } } // get src and dst node attributes into hashmaps if ((Table->SrcNodeAttrV).Len() > 0) { Table->AddNodeAttributes(SVal, Table->SrcNodeAttrV, CurrRowIdx, NodeIntAttrs, NodeFltAttrs, NodeStrAttrs); } if ((Table->DstNodeAttrV).Len() > 0) { Table->AddNodeAttributes(DVal, Table->DstNodeAttrV, CurrRowIdx, NodeIntAttrs, NodeFltAttrs, NodeStrAttrs); } } // aggregate node attributes and add to graph if ((Table->SrcNodeAttrV).Len() > 0 || (Table->DstNodeAttrV).Len() > 0) { for (TNEANet::TNodeI NodeI = Graph->BegNI(); NodeI < Graph->EndNI(); NodeI++) { TInt NId = NodeI.GetId(); if (NodeIntAttrs.IsKey(NId)) { TStrIntVH IntAttrVals = NodeIntAttrs.GetDat(NId); for (TStrIntVH::TIter it = IntAttrVals.BegI(); it < IntAttrVals.EndI(); it++) { TInt AttrVal = Table->AggregateVector<TInt>(it.GetDat(), AggrPolicy); Graph->AddIntAttrDatN(NId, AttrVal, it.GetKey()); } } if (NodeFltAttrs.IsKey(NId)) { TStrFltVH FltAttrVals = NodeFltAttrs.GetDat(NId); for (TStrFltVH::TIter it = FltAttrVals.BegI(); it < FltAttrVals.EndI(); it++) { TFlt AttrVal = Table->AggregateVector<TFlt>(it.GetDat(), AggrPolicy); Graph->AddFltAttrDatN(NId, AttrVal, it.GetKey()); } } if (NodeStrAttrs.IsKey(NId)) { TStrStrVH StrAttrVals = NodeStrAttrs.GetDat(NId); for (TStrStrVH::TIter it = StrAttrVals.BegI(); it < StrAttrVals.EndI(); it++) { TStr AttrVal = Table->AggregateVector<TStr>(it.GetDat(), AggrPolicy); Graph->AddStrAttrDatN(NId, AttrVal, it.GetKey()); } } } } return Graph; } /// Calls ToNetwork with an empty attribute vector. Convenience wrapper. template<class PGraph> PGraph ToNetwork(PTable Table, const TStr& SrcCol, const TStr& DstCol, TAttrAggr AggrPolicy) { TStrV V; return ToNetwork<PGraph>(Table, SrcCol, DstCol, V, AggrPolicy); } #ifdef GCC_ATOMIC /// Performs table to graph conversion in parallel using the sort-first algorithm. This is the recommended method to use. template<class PGraphMP> PGraphMP ToGraphMP(PTable Table, const TStr& SrcCol, const TStr& DstCol) { // double start = omp_get_wtime(); const TInt SrcColIdx = Table->GetColIdx(SrcCol); const TInt DstColIdx = Table->GetColIdx(DstCol); const TAttrType NodeType = Table->GetColType(SrcCol); Assert(NodeType == Table->GetColType(DstCol)); const TInt NumRows = Table->NumValidRows; TIntV SrcCol1, DstCol1, SrcCol2, DstCol2; #pragma omp parallel sections num_threads(4) { #pragma omp section { SrcCol1.Reserve(NumRows, NumRows); } #pragma omp section { SrcCol2.Reserve(NumRows, NumRows); } #pragma omp section { DstCol1.Reserve(NumRows, NumRows); } #pragma omp section { DstCol2.Reserve(NumRows, NumRows); } } // double endResize = omp_get_wtime(); // printf("Resize time = %f\n", endResize-start); TIntPrV Partitions; Table->GetPartitionRanges(Partitions, omp_get_max_threads()); TInt PartitionSize = Partitions[0].GetVal2()-Partitions[0].GetVal1()+1; // double endPartition = omp_get_wtime(); // printf("Partition time = %f\n", endPartition-endResize); omp_set_num_threads(omp_get_max_threads()); if (NodeType == atInt) { #pragma omp parallel for schedule(static) for (int i = 0; i < Partitions.Len(); i++) { TRowIterator RowI(Partitions[i].GetVal1(), Table()); TRowIterator EndI(Partitions[i].GetVal2(), Table()); while (RowI < EndI) { TInt RowId = RowI.GetRowIdx(); SrcCol1[RowId] = RowI.GetIntAttr(SrcColIdx); SrcCol2[RowId] = RowI.GetIntAttr(SrcColIdx); DstCol1[RowId] = RowI.GetIntAttr(DstColIdx); DstCol2[RowId] = RowI.GetIntAttr(DstColIdx); RowI++; } } } else if (NodeType == atStr) { #pragma omp parallel for schedule(static) for (int i = 0; i < Partitions.Len(); i++) { TRowIterator RowI(Partitions[i].GetVal1(), Table()); TRowIterator EndI(Partitions[i].GetVal2(), Table()); while (RowI < EndI) { TInt RowId = RowI.GetRowIdx(); SrcCol1[RowId] = RowI.GetStrMapById(SrcColIdx); SrcCol2[RowId] = RowI.GetStrMapById(SrcColIdx); DstCol1[RowId] = RowI.GetStrMapById(DstColIdx); DstCol2[RowId] = RowI.GetStrMapById(DstColIdx); RowI++; } } } omp_set_num_threads(omp_get_max_threads()); #pragma omp parallel { #pragma omp single nowait { #pragma omp task untied shared(SrcCol1, DstCol1) { TTable::QSortKeyVal(SrcCol1, DstCol1, 0, NumRows-1); } } #pragma omp single nowait { #pragma omp task untied shared(SrcCol2, DstCol2) { TTable::QSortKeyVal(DstCol2, SrcCol2, 0, NumRows-1); } } #pragma omp taskwait } // TTable::PSRSKeyVal(SrcCol1, DstCol1, 0, NumRows-1); // TTable::PSRSKeyVal(DstCol2, SrcCol2, 0, NumRows-1); // TInt IsS = TTable::CheckSortedKeyVal(SrcCol1, DstCol1, 0, NumRows-1); // TInt IsD = TTable::CheckSortedKeyVal(DstCol2, SrcCol2, 0, NumRows-1); // printf("IsSorted = %d %d\n", IsS.Val, IsD.Val); // double endSort = omp_get_wtime(); // printf("Sort time = %f\n", endSort-endCopy); //return TNGraphMP::New(10, 100); TInt NumThreads = omp_get_max_threads(); TInt PartSize = (NumRows/NumThreads); TIntV SrcOffsets, DstOffsets; SrcOffsets.Add(0); for (TInt i = 1; i < NumThreads; i++) { TInt CurrOffset = i * PartSize; while (CurrOffset < (i+1) * PartSize && SrcCol1[CurrOffset-1] == SrcCol1[CurrOffset]) { CurrOffset++; } if (CurrOffset < (i+1) * PartSize) { SrcOffsets.Add(CurrOffset); } } SrcOffsets.Add(NumRows); DstOffsets.Add(0); for (TInt i = 1; i < NumThreads; i++) { TInt CurrOffset = i * PartSize; while (CurrOffset < (i+1) * PartSize && DstCol2[CurrOffset-1] == DstCol2[CurrOffset]) { CurrOffset++; } if (CurrOffset < (i+1) * PartSize) { DstOffsets.Add(CurrOffset); } } DstOffsets.Add(NumRows); TInt SrcPartCnt = SrcOffsets.Len()-1; TInt DstPartCnt = DstOffsets.Len()-1; // for (TInt i = 0; i < SrcOffsets.Len(); i++) { // printf("%d ", SrcOffsets[i].Val); // } // printf("\n"); // for (TInt i = 0; i < DstOffsets.Len(); i++) { // printf("%d ", DstOffsets[i].Val); // } // printf("\n"); TIntV SrcNodeCounts, DstNodeCounts; SrcNodeCounts.Reserve(SrcPartCnt, SrcPartCnt); DstNodeCounts.Reserve(DstPartCnt, DstPartCnt); #pragma omp parallel for schedule(dynamic) for (int t = 0; t < SrcPartCnt+DstPartCnt; t++) { if (t < SrcPartCnt) { TInt i = t; if (SrcOffsets[i] != SrcOffsets[i+1]) { SrcNodeCounts[i] = 1; TInt CurrNode = SrcCol1[SrcOffsets[i]]; for (TInt j = SrcOffsets[i]+1; j < SrcOffsets[i+1]; j++) { while (j < SrcOffsets[i+1] && SrcCol1[j] == CurrNode) { j++; } if (j < SrcOffsets[i+1]) { SrcNodeCounts[i]++; CurrNode = SrcCol1[j]; } } } } else { TInt i = t - SrcPartCnt; if (DstOffsets[i] != DstOffsets[i+1]) { DstNodeCounts[i] = 1; TInt CurrNode = DstCol2[DstOffsets[i]]; for (TInt j = DstOffsets[i]+1; j < DstOffsets[i+1]; j++) { while (j < DstOffsets[i+1] && DstCol2[j] == CurrNode) { j++; } if (j < DstOffsets[i+1]) { DstNodeCounts[i]++; CurrNode = DstCol2[j]; } } } } } // for (TInt i = 0; i < SrcNodeCounts.Len(); i++) { // printf("%d ", SrcNodeCounts[i].Val); // } // printf("\n"); // for (TInt i = 0; i < DstNodeCounts.Len(); i++) { // printf("%d ", DstNodeCounts[i].Val); // } // printf("\n"); TInt TotalSrcNodes = 0; TIntV SrcIdOffsets; for (int i = 0; i < SrcPartCnt; i++) { SrcIdOffsets.Add(TotalSrcNodes); TotalSrcNodes += SrcNodeCounts[i]; } TInt TotalDstNodes = 0; TIntV DstIdOffsets; for (int i = 0; i < DstPartCnt; i++) { DstIdOffsets.Add(TotalDstNodes); TotalDstNodes += DstNodeCounts[i]; } // printf("Total Src = %d, Total Dst = %d\n", TotalSrcNodes.Val, TotalDstNodes.Val); TIntPrV SrcNodeIds, DstNodeIds; #pragma omp parallel sections { #pragma omp section { SrcNodeIds.Reserve(TotalSrcNodes, TotalSrcNodes); } #pragma omp section { DstNodeIds.Reserve(TotalDstNodes, TotalDstNodes); } } #pragma omp parallel for schedule(dynamic) for (int t = 0; t < SrcPartCnt+DstPartCnt; t++) { if (t < SrcPartCnt) { TInt i = t; if (SrcOffsets[i] != SrcOffsets[i+1]) { TInt CurrNode = SrcCol1[SrcOffsets[i]]; TInt ThreadOffset = SrcIdOffsets[i]; SrcNodeIds[ThreadOffset] = TIntPr(CurrNode, SrcOffsets[i]); TInt CurrCount = 1; for (TInt j = SrcOffsets[i]+1; j < SrcOffsets[i+1]; j++) { while (j < SrcOffsets[i+1] && SrcCol1[j] == CurrNode) { j++; } if (j < SrcOffsets[i+1]) { CurrNode = SrcCol1[j]; SrcNodeIds[ThreadOffset+CurrCount] = TIntPr(CurrNode, j); CurrCount++; } } } } else { TInt i = t - SrcPartCnt; if (DstOffsets[i] != DstOffsets[i+1]) { TInt CurrNode = DstCol2[DstOffsets[i]]; TInt ThreadOffset = DstIdOffsets[i]; DstNodeIds[ThreadOffset] = TIntPr(CurrNode, DstOffsets[i]); TInt CurrCount = 1; for (TInt j = DstOffsets[i]+1; j < DstOffsets[i+1]; j++) { while (j < DstOffsets[i+1] && DstCol2[j] == CurrNode) { j++; } if (j < DstOffsets[i+1]) { CurrNode = DstCol2[j]; DstNodeIds[ThreadOffset+CurrCount] = TIntPr(CurrNode, j); CurrCount++; } } } } } // double endNode = omp_get_wtime(); // printf("Node time = %f\n", endNode-endSort); TIntTrV Nodes; Nodes.Reserve(TotalSrcNodes+TotalDstNodes); // double endNodeResize = omp_get_wtime(); // printf("(NodeResize time = %f)\n", endNodeResize-endNode); TInt i = 0, j = 0; while (i < TotalSrcNodes && j < TotalDstNodes) { if (SrcNodeIds[i].Val1 == DstNodeIds[j].Val1) { Nodes.Add(TIntTr(SrcNodeIds[i].Val1, i, j)); i++; j++; } else if (SrcNodeIds[i].Val1 < DstNodeIds[j].Val1) { Nodes.Add(TIntTr(SrcNodeIds[i].Val1, i, -1)); i++; } else { Nodes.Add(TIntTr(DstNodeIds[j].Val1, -1, j)); j++; } } for (; i < TotalSrcNodes; i++) { Nodes.Add(TIntTr(SrcNodeIds[i].Val1, i, -1)); } for (; j < TotalDstNodes; j++) { Nodes.Add(TIntTr(DstNodeIds[j].Val1, -1, j)); } // double endMerge = omp_get_wtime(); // printf("Merge time = %f\n", endMerge-endNode); TInt NumNodes = Nodes.Len(); // printf("NumNodes = %d\n", NumNodes.Val); PGraphMP Graph = TNGraphMP::New(NumNodes, NumRows); NumThreads = 1; int Delta = (NumNodes+NumThreads-1)/NumThreads; TVec<TIntV> InVV(NumNodes); TVec<TIntV> OutVV(NumNodes); omp_set_num_threads(NumThreads); #pragma omp parallel for schedule(static,Delta) for (int m = 0; m < NumNodes; m++) { //double startTr = omp_get_wtime(); //TIntV OutV, InV; TInt n, i, j; Nodes[m].GetVal(n, i, j); if (i >= 0) { TInt Offset = SrcNodeIds[i].GetVal2(); TInt Sz = DstCol1.Len()-Offset; if (i < SrcNodeIds.Len()-1) { Sz = SrcNodeIds[i+1].GetVal2()-Offset; } //printf("OutV: %d %d %d\n", n.Val, Offset.Val, Sz.Val); OutVV[m].Reserve(Sz); } if (j >= 0) { TInt Offset = DstNodeIds[j].GetVal2(); TInt Sz = SrcCol2.Len()-Offset; if (j < DstNodeIds.Len()-1) { Sz = DstNodeIds[j+1].GetVal2()-Offset; } //printf("OutV: %d %d %d\n", n.Val, Offset.Val, Sz.Val); InVV[m].Reserve(Sz); } //double endTr = omp_get_wtime(); //printf("Thread=%d, i=%d, t=%f\n", omp_get_thread_num(), m, endTr-startTr); } // double endAlloc = omp_get_wtime(); // printf("Alloc time = %f\n", endAlloc-endMerge); NumThreads = omp_get_max_threads(); Delta = (NumNodes+NumThreads-1)/(10*NumThreads); omp_set_num_threads(NumThreads); #pragma omp parallel for schedule(dynamic) for (int m = 0; m < NumNodes; m++) { //double startTr = omp_get_wtime(); //TIntV OutV, InV; TInt n, i, j; Nodes[m].GetVal(n, i, j); if (i >= 0) { TInt Offset = SrcNodeIds[i].GetVal2(); TInt Sz = DstCol1.Len()-Offset; if (i < SrcNodeIds.Len()-1) { Sz = SrcNodeIds[i+1].GetVal2()-Offset; } //printf("OutV: %d %d %d\n", n.Val, Offset.Val, Sz.Val); OutVV[m].CopyUniqueFrom(DstCol1, Offset, Sz); } if (j >= 0) { TInt Offset = DstNodeIds[j].GetVal2(); TInt Sz = SrcCol2.Len()-Offset; if (j < DstNodeIds.Len()-1) { Sz = DstNodeIds[j+1].GetVal2()-Offset; } //printf("OutV: %d %d %d\n", n.Val, Offset.Val, Sz.Val); InVV[m].CopyUniqueFrom(SrcCol2, Offset, Sz); } Graph->AddNodeWithEdges(n, InVV[m], OutVV[m]); //double endTr = omp_get_wtime(); //printf("Thread=%d, i=%d, t=%f\n", omp_get_thread_num(), m, endTr-startTr); } Graph->SetNodes(NumNodes); // double endAdd = omp_get_wtime(); // printf("Add time = %f\n", endAdd-endAlloc); return Graph; } /// Performs table to graph conversion in parallel. Uses the hash-first method, which is less optimal, use ToGraphMP instead. template<class PGraphMP> PGraphMP ToGraphMP3(PTable Table, const TStr& SrcCol, const TStr& DstCol) { PNGraphMP Graph; int MaxThreads = omp_get_max_threads(); int Length, Threads, Delta, Nodes, Last; uint64_t NumNodesEst; TInt SrcColIdx, DstColIdx; TIntV InVec, OutVec; SrcColIdx = Table->GetColIdx(SrcCol); DstColIdx = Table->GetColIdx(DstCol); const TAttrType NodeType = Table->GetColType(SrcCol); Assert(NodeType == Table->GetColType(DstCol)); /* Estimate number of nodes in the graph */ int NumRows = Table->Next.Len(); double Load = 10; int sz = NumRows / Load; int *buckets = (int *)malloc(sz * sizeof(int)); #pragma omp parallel for for (int i = 0; i < sz; i++) buckets[i] = 0; if (NodeType == atInt) { #pragma omp parallel for for (int i = 0; i < NumRows; i++) { int vert = Table->IntCols[DstColIdx][i]; buckets[vert % sz] = 1; } } else if (NodeType == atStr ) { #pragma omp parallel for for (int i = 0; i < NumRows; i++) { int vert = (Table->StrColMaps)[DstColIdx][i]; buckets[vert % sz] = 1; } } int cnt = 0; #pragma omp parallel for reduction(+:cnt) for (int i = 0; i < sz; i++) { if (buckets[i] == 0) cnt += 1; } NumNodesEst = sz * log ((double)sz / cnt); free (buckets); /* Until we correctly estimate the number of nodes */ while (1) { Graph = TNGraphMP::New(NumNodesEst, 100); Length = Graph->Reserved(); Threads = MaxThreads/2; Delta = (Length + Threads - 1) / Threads; OutVec.Gen(Length); InVec.Gen(Length); /* build the node hash table, count the size of edge lists */ Last = NumRows; Nodes = 0; omp_set_num_threads(Threads); #pragma omp parallel for schedule(static, Delta) for (int CurrRowIdx = 0; CurrRowIdx < Last; CurrRowIdx++) { if ((uint64_t) Nodes + 1000 >= NumNodesEst) { /* need bigger hash table */ continue; } TInt SVal, DVal; if (NodeType == atInt) { SVal = Table->IntCols[SrcColIdx][CurrRowIdx]; DVal = Table->IntCols[DstColIdx][CurrRowIdx]; } else if (NodeType == atStr ) { SVal = (Table->StrColMaps)[SrcColIdx][CurrRowIdx]; DVal = (Table->StrColMaps)[DstColIdx][CurrRowIdx]; } int SrcIdx = abs((SVal.GetPrimHashCd()) % Length); if (!Graph->AddOutEdge1(SrcIdx, SVal, DVal)) { #pragma omp critical { Nodes++; } } __sync_fetch_and_add(&OutVec[SrcIdx].Val, 1); int DstIdx = abs((DVal.GetPrimHashCd()) % Length); if (!Graph->AddInEdge1(DstIdx, SVal, DVal)) { #pragma omp critical { Nodes++; } } __sync_fetch_and_add(&InVec[DstIdx].Val, 1); } if ((uint64_t) Nodes + 1000 >= NumNodesEst) { /* We need to double our num nodes estimate */ Graph.Clr(); InVec.Clr(); OutVec.Clr(); NumNodesEst *= 2; } else { break; } } Graph->SetNodes(Nodes); uint Edges = 0; for (int i = 0; i < Length; i++) { Edges += OutVec[i] + InVec[i]; } for (int Idx = 0; Idx < Length; Idx++) { if (OutVec[Idx] > 0 || InVec[Idx] > 0) { Graph->ReserveNodeDegs(Idx, InVec[Idx], OutVec[Idx]); } } /* assign edges */ Length = Graph->Reserved(); Threads = MaxThreads; Delta = (Length + Threads - 1) / Threads; omp_set_num_threads(Threads); #pragma omp parallel for schedule(static,Delta) for (int CurrRowIdx = 0; CurrRowIdx < Last; CurrRowIdx++) { TInt SVal, DVal; if (NodeType == atInt) { SVal = Table->IntCols[SrcColIdx][CurrRowIdx]; DVal = Table->IntCols[DstColIdx][CurrRowIdx]; } else if (NodeType == atStr) { SVal = (Table->StrColMaps)[SrcColIdx][CurrRowIdx]; DVal = (Table->StrColMaps)[DstColIdx][CurrRowIdx]; } Graph->AddOutEdge2(SVal, DVal); Graph->AddInEdge2(SVal, DVal); } /* sort edges */ Length = Graph->Reserved(); Threads = MaxThreads*2; Delta = (Length + Threads - 1) / Threads; omp_set_num_threads(Threads); #pragma omp parallel for schedule(dynamic) for (int Idx = 0; Idx < Length; Idx++) { if (OutVec[Idx] > 0 || InVec[Idx] > 0) { Graph->SortEdges(Idx, InVec[Idx], OutVec[Idx]); } } return Graph; } /// Does Table to Network conversion in parallel using the sort-first algorithm. This is the recommended method to use. template<class PGraphMP> inline PGraphMP ToNetworkMP(PTable Table, const TStr& SrcCol, const TStr& DstCol, TStrV& SrcAttrV, TStrV& DstAttrV, TStrV& EdgeAttrV, TAttrAggr AggrPolicy) { TStopwatch* Sw = TStopwatch::GetInstance(); Sw->Start(TStopwatch::AllocateColumnCopies); const TInt SrcColIdx = Table->GetColIdx(SrcCol); const TInt DstColIdx = Table->GetColIdx(DstCol); const TInt NumRows = Table->GetNumValidRows(); const TAttrType NodeType = Table->GetColType(SrcCol); Assert(NodeType == Table->GetColType(DstCol)); TIntV SrcCol1, EdgeCol1, EdgeCol2, DstCol2; THash<TInt, TStrIntVH> NodeIntAttrs; THash<TInt, TStrFltVH> NodeFltAttrs; THash<TInt, TStrStrVH> NodeStrAttrs; #pragma omp parallel sections num_threads(4) { #pragma omp section { SrcCol1.Reserve(NumRows, NumRows); } #pragma omp section { EdgeCol1.Reserve(NumRows, NumRows); } #pragma omp section { DstCol2.Reserve(NumRows, NumRows); } #pragma omp section { EdgeCol2.Reserve(NumRows, NumRows); } } Sw->Stop(TStopwatch::AllocateColumnCopies); Sw->Start(TStopwatch::CopyColumns); TIntPrV Partitions; Table->GetPartitionRanges(Partitions, omp_get_max_threads()); TInt PartitionSize = Partitions[0].GetVal2()-Partitions[0].GetVal1()+1; // double endPartition = omp_get_wtime(); // printf("Partition time = %f\n", endPartition-endResize); omp_set_num_threads(omp_get_max_threads()); if (NodeType == atInt) { #pragma omp parallel for schedule(static) for (int i = 0; i < Partitions.Len(); i++) { TRowIterator RowI(Partitions[i].GetVal1(), Table()); TRowIterator EndI(Partitions[i].GetVal2(), Table()); while (RowI < EndI) { TInt RowId = RowI.GetRowIdx(); SrcCol1[RowId] = RowI.GetIntAttr(SrcColIdx); EdgeCol1[RowId] = RowId; DstCol2[RowId] = RowI.GetIntAttr(DstColIdx); EdgeCol2[RowId] = RowId; RowI++; } } } else if (NodeType == atStr) { #pragma omp parallel for schedule(static) for (int i = 0; i < Partitions.Len(); i++) { TRowIterator RowI(Partitions[i].GetVal1(), Table()); TRowIterator EndI(Partitions[i].GetVal2(), Table()); while (RowI < EndI) { TInt RowId = RowI.GetRowIdx(); SrcCol1[RowId] = RowI.GetStrMapById(SrcColIdx); EdgeCol1[RowId] = RowId; DstCol2[RowId] = RowI.GetStrMapById(DstColIdx); EdgeCol2[RowId] = RowId; RowI++; } } } Sw->Stop(TStopwatch::CopyColumns); Sw->Start(TStopwatch::Sort); omp_set_num_threads(omp_get_max_threads()); #pragma omp parallel { #pragma omp single nowait { #ifndef GLib_WIN32 #pragma omp task untied shared(SrcCol1, EdgeCol1) #endif { TTable::QSortKeyVal(SrcCol1, EdgeCol1, 0, NumRows-1); } } #pragma omp single nowait { #ifndef GLib_WIN32 #pragma omp task untied shared(EdgeCol2, DstCol2) #endif { TTable::QSortKeyVal(DstCol2, EdgeCol2, 0, NumRows-1); } } #ifndef GLib_WIN32 #pragma omp taskwait #endif } Sw->Stop(TStopwatch::Sort); Sw->Start(TStopwatch::Group); TInt NumThreads = omp_get_max_threads(); TInt PartSize = (NumRows/NumThreads); // Find the offset of all partitions, each of which contains a list of rows. // Nodes from same sources or destinations are ensured to be kept within same partition. TIntV SrcOffsets, DstOffsets; SrcOffsets.Add(0); for (TInt i = 1; i < NumThreads; i++) { TInt CurrOffset = i * PartSize; while (CurrOffset < (i+1) * PartSize && SrcCol1[CurrOffset-1] == SrcCol1[CurrOffset]) { // ensure that rows from the same sources are grouped together CurrOffset++; } if (CurrOffset < (i+1) * PartSize) { SrcOffsets.Add(CurrOffset); } } SrcOffsets.Add(NumRows); DstOffsets.Add(0); for (TInt i = 1; i < NumThreads; i++) { TInt CurrOffset = i * PartSize; while (CurrOffset < (i+1) * PartSize && DstCol2[CurrOffset-1] == DstCol2[CurrOffset]) { // ensure that rows to the same destinations are grouped together CurrOffset++; } if (CurrOffset < (i+1) * PartSize) { DstOffsets.Add(CurrOffset); } } DstOffsets.Add(NumRows); TInt SrcPartCnt = SrcOffsets.Len()-1; // number of partitions TInt DstPartCnt = DstOffsets.Len()-1; // number of partitions // count the number of source nodes and destination nodes in each partition TIntV SrcNodeCounts, DstNodeCounts; SrcNodeCounts.Reserve(SrcPartCnt, SrcPartCnt); DstNodeCounts.Reserve(DstPartCnt, DstPartCnt); #pragma omp parallel for schedule(dynamic) for (int t = 0; t < SrcPartCnt+DstPartCnt; t++) { if (t < SrcPartCnt) { TInt i = t; if (SrcOffsets[i] != SrcOffsets[i+1]) { SrcNodeCounts[i] = 1; TInt CurrNode = SrcCol1[SrcOffsets[i]]; for (TInt j = SrcOffsets[i]+1; j < SrcOffsets[i+1]; j++) { while (j < SrcOffsets[i+1] && SrcCol1[j] == CurrNode) { j++; } if (j < SrcOffsets[i+1]) { SrcNodeCounts[i]++; CurrNode = SrcCol1[j]; } } } } else { TInt i = t - SrcPartCnt; if (DstOffsets[i] != DstOffsets[i+1]) { DstNodeCounts[i] = 1; TInt CurrNode = DstCol2[DstOffsets[i]]; for (TInt j = DstOffsets[i]+1; j < DstOffsets[i+1]; j++) { while (j < DstOffsets[i+1] && DstCol2[j] == CurrNode) { j++; } if (j < DstOffsets[i+1]) { DstNodeCounts[i]++; CurrNode = DstCol2[j]; } } } } } TInt TotalSrcNodes = 0; TIntV SrcIdOffsets; for (int i = 0; i < SrcPartCnt; i++) { SrcIdOffsets.Add(TotalSrcNodes); TotalSrcNodes += SrcNodeCounts[i]; } TInt TotalDstNodes = 0; TIntV DstIdOffsets; for (int i = 0; i < DstPartCnt; i++) { DstIdOffsets.Add(TotalDstNodes); TotalDstNodes += DstNodeCounts[i]; } // printf("Total Src = %d, Total Dst = %d\n", TotalSrcNodes.Val, TotalDstNodes.Val); // find vector of (node_id, start_offset) where start_offset is the index of the first row with node_id TIntPrV SrcNodeIds, DstNodeIds; #pragma omp parallel sections { #pragma omp section { SrcNodeIds.Reserve(TotalSrcNodes, TotalSrcNodes); } #pragma omp section { DstNodeIds.Reserve(TotalDstNodes, TotalDstNodes); } } // Find the starting offset of each node (in both src and dst) #pragma omp parallel for schedule(dynamic) for (int t = 0; t < SrcPartCnt+DstPartCnt; t++) { if (t < SrcPartCnt) { TInt i = t; if (SrcOffsets[i] != SrcOffsets[i+1]) { TInt CurrNode = SrcCol1[SrcOffsets[i]]; TInt ThreadOffset = SrcIdOffsets[i]; SrcNodeIds[ThreadOffset] = TIntPr(CurrNode, SrcOffsets[i]); TInt CurrCount = 1; for (TInt j = SrcOffsets[i]+1; j < SrcOffsets[i+1]; j++) { while (j < SrcOffsets[i+1] && SrcCol1[j] == CurrNode) { j++; } if (j < SrcOffsets[i+1]) { CurrNode = SrcCol1[j]; SrcNodeIds[ThreadOffset+CurrCount] = TIntPr(CurrNode, j); CurrCount++; } } } } else { TInt i = t - SrcPartCnt; if (DstOffsets[i] != DstOffsets[i+1]) { TInt CurrNode = DstCol2[DstOffsets[i]]; TInt ThreadOffset = DstIdOffsets[i]; DstNodeIds[ThreadOffset] = TIntPr(CurrNode, DstOffsets[i]); TInt CurrCount = 1; for (TInt j = DstOffsets[i]+1; j < DstOffsets[i+1]; j++) { while (j < DstOffsets[i+1] && DstCol2[j] == CurrNode) { j++; } if (j < DstOffsets[i+1]) { CurrNode = DstCol2[j]; DstNodeIds[ThreadOffset+CurrCount] = TIntPr(CurrNode, j); CurrCount++; } } } } } Sw->Stop(TStopwatch::Group); Sw->Start(TStopwatch::MergeNeighborhoods); // Find the combined neighborhood (both out-neighbors and in-neighbors) of each node TIntTrV Nodes; Nodes.Reserve(TotalSrcNodes+TotalDstNodes); TInt i = 0, j = 0; while (i < TotalSrcNodes && j < TotalDstNodes) { if (SrcNodeIds[i].Val1 == DstNodeIds[j].Val1) { Nodes.Add(TIntTr(SrcNodeIds[i].Val1, i, j)); i++; j++; } else if (SrcNodeIds[i].Val1 < DstNodeIds[j].Val1) { Nodes.Add(TIntTr(SrcNodeIds[i].Val1, i, -1)); i++; } else { Nodes.Add(TIntTr(DstNodeIds[j].Val1, -1, j)); j++; } } for (; i < TotalSrcNodes; i++) { Nodes.Add(TIntTr(SrcNodeIds[i].Val1, i, -1)); } for (; j < TotalDstNodes; j++) { Nodes.Add(TIntTr(DstNodeIds[j].Val1, -1, j)); } Sw->Stop(TStopwatch::MergeNeighborhoods); Sw->Start(TStopwatch::AddNeighborhoods); TInt NumNodes = Nodes.Len(); PGraphMP Graph = PGraphMP::TObj::New(NumNodes, NumRows); // NumThreads = omp_get_max_threads(); // int Delta = (NumNodes+NumThreads-1)/NumThreads; TVec<TIntV> InVV(NumNodes); TVec<TIntV> OutVV(NumNodes); // omp_set_num_threads(NumThreads); #pragma omp parallel for schedule(static,100) for (int m = 0; m < NumNodes; m++) { //double startTr = omp_get_wtime(); //TIntV OutV, InV; TInt n, i, j; Nodes[m].GetVal(n, i, j); if (i >= 0) { TInt Offset = SrcNodeIds[i].GetVal2(); TInt Sz = EdgeCol1.Len()-Offset; if (i < SrcNodeIds.Len()-1) { Sz = SrcNodeIds[i+1].GetVal2()-Offset; } OutVV[m].Reserve(Sz); OutVV[m].CopyUniqueFrom(EdgeCol1, Offset, Sz); } if (j >= 0) { TInt Offset = DstNodeIds[j].GetVal2(); TInt Sz = EdgeCol2.Len()-Offset; if (j < DstNodeIds.Len()-1) { Sz = DstNodeIds[j+1].GetVal2()-Offset; } InVV[m].Reserve(Sz); InVV[m].CopyUniqueFrom(EdgeCol2, Offset, Sz); } Graph->AddNodeWithEdges(n, InVV[m], OutVV[m]); } Graph->SetNodes(NumNodes); Sw->Stop(TStopwatch::AddNeighborhoods); Sw->Start(TStopwatch::AddEdges); omp_set_num_threads(omp_get_max_threads()); if (NodeType == atInt) { #pragma omp parallel for schedule(static) for (int i = 0; i < Partitions.Len(); i++) { TRowIterator RowI(Partitions[i].GetVal1(), Table()); TRowIterator EndI(Partitions[i].GetVal2(), Table()); while (RowI < EndI) { TInt RowId = RowI.GetRowIdx(); // EdgeId TInt SrcId = RowI.GetIntAttr(SrcColIdx); TInt DstId = RowI.GetIntAttr(DstColIdx); Graph->AddEdgeUnchecked(RowId, SrcId, DstId); RowI++; for (TInt ea_i = 0; ea_i < EdgeAttrV.Len(); ea_i++) { TStr ColName = EdgeAttrV[ea_i]; TAttrType T = Table->GetColType(ColName); TInt Index = Table->GetColIdx(ColName); switch (T) { case atInt: Graph->AddIntAttrDatE(RowId, Table->IntCols[Index][RowId], ColName); break; case atFlt: Graph->AddFltAttrDatE(RowId, Table->FltCols[Index][RowId], ColName); break; case atStr: Graph->AddStrAttrDatE(RowId, Table->GetStrValIdx(Index, RowId), ColName); break; } } if ((Table->SrcNodeAttrV).Len() > 0) { Table->AddNodeAttributes(SrcId, Table->SrcNodeAttrV, RowId, NodeIntAttrs, NodeFltAttrs, NodeStrAttrs); } if ((Table->DstNodeAttrV).Len() > 0) { Table->AddNodeAttributes(SrcId, Table->DstNodeAttrV, RowId, NodeIntAttrs, NodeFltAttrs, NodeStrAttrs); } } } } else if (NodeType == atStr) { #pragma omp parallel for schedule(static) for (int i = 0; i < Partitions.Len(); i++) { TRowIterator RowI(Partitions[i].GetVal1(), Table()); TRowIterator EndI(Partitions[i].GetVal2(), Table()); while (RowI < EndI) { TInt RowId = RowI.GetRowIdx(); // EdgeId TInt SrcId = RowI.GetStrMapById(SrcColIdx); TInt DstId = RowI.GetStrMapById(DstColIdx); Graph->AddEdgeUnchecked(RowId, SrcId, DstId); RowI++; for (TInt ea_i = 0; ea_i < EdgeAttrV.Len(); ea_i++) { TStr ColName = EdgeAttrV[ea_i]; TAttrType T = Table->GetColType(ColName); TInt Index = Table->GetColIdx(ColName); switch (T) { case atInt: Graph->AddIntAttrDatE(RowId, Table->IntCols[Index][RowId], ColName); break; case atFlt: Graph->AddFltAttrDatE(RowId, Table->FltCols[Index][RowId], ColName); break; case atStr: Graph->AddStrAttrDatE(RowId, Table->GetStrValIdx(Index, RowId), ColName); break; } } if ((Table->SrcNodeAttrV).Len() > 0) { Table->AddNodeAttributes(SrcId, Table->SrcNodeAttrV, RowId, NodeIntAttrs, NodeFltAttrs, NodeStrAttrs); } if ((Table->DstNodeAttrV).Len() > 0) { Table->AddNodeAttributes(SrcId, Table->DstNodeAttrV, RowId, NodeIntAttrs, NodeFltAttrs, NodeStrAttrs); } } } } // aggregate node attributes and add to graph if ((Table->SrcNodeAttrV).Len() > 0 || (Table->DstNodeAttrV).Len() > 0) { for (typename PGraphMP::TObj::TNodeI NodeI = Graph->BegNI(); NodeI < Graph->EndNI(); NodeI++) { TInt NId = NodeI.GetId(); if (NodeIntAttrs.IsKey(NId)) { TStrIntVH IntAttrVals = NodeIntAttrs.GetDat(NId); for (TStrIntVH::TIter it = IntAttrVals.BegI(); it < IntAttrVals.EndI(); it++) { TInt AttrVal = Table->AggregateVector<TInt>(it.GetDat(), AggrPolicy); Graph->AddIntAttrDatN(NId, AttrVal, it.GetKey()); } } if (NodeFltAttrs.IsKey(NId)) { TStrFltVH FltAttrVals = NodeFltAttrs.GetDat(NId); for (TStrFltVH::TIter it = FltAttrVals.BegI(); it < FltAttrVals.EndI(); it++) { TFlt AttrVal = Table->AggregateVector<TFlt>(it.GetDat(), AggrPolicy); Graph->AddFltAttrDatN(NId, AttrVal, it.GetKey()); } } if (NodeStrAttrs.IsKey(NId)) { TStrStrVH StrAttrVals = NodeStrAttrs.GetDat(NId); for (TStrStrVH::TIter it = StrAttrVals.BegI(); it < StrAttrVals.EndI(); it++) { TStr AttrVal = Table->AggregateVector<TStr>(it.GetDat(), AggrPolicy); Graph->AddStrAttrDatN(NId, AttrVal, it.GetKey()); } } } } Graph->SetEdges(NumRows); Sw->Stop(TStopwatch::AddEdges); // double endAdd = omp_get_wtime(); // printf("Add time = %f\n", endAdd-endAlloc); return Graph; } /// Calls ToNetworkMP with empty attribute vector. Convenience wrapper. template<class PGraphMP> PGraphMP ToNetworkMP(PTable Table, const TStr& SrcCol, const TStr& DstCol, TAttrAggr AggrPolicy) { TStrV V; return ToNetworkMP<PGraphMP>(Table, SrcCol, DstCol, V,AggrPolicy); } ///Implements table to network conversion in parallel. Not the recommended algorithm, using ToNetworkMP instead. template<class PGraphMP> inline PGraphMP ToNetworkMP2(PTable Table, const TStr& SrcCol, const TStr& DstCol, TStrV& SrcAttrV, TStrV& DstAttrV, TStrV& EdgeAttrV, TAttrAggr AggrPolicy) { TStopwatch* Sw = TStopwatch::GetInstance(); Sw->Start(TStopwatch::AllocateColumnCopies); const TInt SrcColIdx = Table->GetColIdx(SrcCol); const TInt DstColIdx = Table->GetColIdx(DstCol); const TInt NumRows = Table->NumValidRows; const TAttrType NodeType = Table->GetColType(SrcCol); Assert(NodeType == Table->GetColType(DstCol)); TIntV SrcCol1, EdgeCol1, EdgeCol2, DstCol2; #pragma omp parallel sections num_threads(4) { #pragma omp section { SrcCol1.Reserve(NumRows, NumRows); } #pragma omp section { EdgeCol1.Reserve(NumRows, NumRows); } #pragma omp section { DstCol2.Reserve(NumRows, NumRows); } #pragma omp section { EdgeCol2.Reserve(NumRows, NumRows); } } Sw->Stop(TStopwatch::AllocateColumnCopies); Sw->Start(TStopwatch::CopyColumns); TIntPrV Partitions; // int NThreads = omp_get_max_threads(); const int NThreads = 40; Table->GetPartitionRanges(Partitions, NThreads); TInt PartitionSize = Partitions[0].GetVal2()-Partitions[0].GetVal1()+1; // double endPartition = omp_get_wtime(); // printf("Partition time = %f\n", endPartition-endResize); if (NodeType == atInt) { #pragma omp parallel for schedule(static) for (int i = 0; i < Partitions.Len(); i++) { TRowIterator RowI(Partitions[i].GetVal1(), Table()); TRowIterator EndI(Partitions[i].GetVal2(), Table()); while (RowI < EndI) { TInt RowId = RowI.GetRowIdx(); SrcCol1[RowId] = RowI.GetIntAttr(SrcColIdx); EdgeCol1[RowId] = RowId; DstCol2[RowId] = RowI.GetIntAttr(DstColIdx); EdgeCol2[RowId] = RowId; RowI++; } } } else if (NodeType == atStr) { #pragma omp parallel for schedule(static) for (int i = 0; i < Partitions.Len(); i++) { TRowIterator RowI(Partitions[i].GetVal1(), Table()); TRowIterator EndI(Partitions[i].GetVal2(), Table()); while (RowI < EndI) { TInt RowId = RowI.GetRowIdx(); SrcCol1[RowId] = RowI.GetStrMapById(SrcColIdx); EdgeCol1[RowId] = RowId; DstCol2[RowId] = RowI.GetStrMapById(DstColIdx); EdgeCol2[RowId] = RowId; RowI++; } } } // printf("NumRows = %d\n", NumRows.Val); // printf("NThreads = %d\n", NThreads); // for (int i = 0; i < Partitions.Len(); i++) { // printf("Partition %d %d->%d\n", i, Partitions[i].GetVal1().Val, Partitions[i].GetVal2().Val); // } int Parts[NThreads+1]; for (int i = 0; i < NThreads; i++) { Parts[i] = NumRows.Val / NThreads * i; } Parts[NThreads] = NumRows; // for (int i = 0; i < NThreads+1; i++) { // printf("Parts[%d] = %d\n", i, Parts[i]); // } Sw->Stop(TStopwatch::CopyColumns); Sw->Start(TStopwatch::Sort); TInt ExtremePoints[4][NThreads]; omp_set_num_threads(omp_get_max_threads()); #pragma omp parallel { #pragma omp for schedule(static) nowait for (int i = 0; i < NThreads; i++) { TInt StartPos = Parts[i]; TInt EndPos = Parts[i+1]-1; // TODO: Handle empty partition TTable::QSortKeyVal(SrcCol1, EdgeCol1, StartPos, EndPos); ExtremePoints[0][i] = SrcCol1[StartPos]; ExtremePoints[2][i] = SrcCol1[EndPos]; } #pragma omp for schedule(static) nowait for (int i = 0; i < NThreads; i++) { TInt StartPos = Parts[i]; TInt EndPos = Parts[i+1]-1; // TODO: Handle empty partition TTable::QSortKeyVal(DstCol2, EdgeCol2, StartPos, EndPos); ExtremePoints[1][i] = DstCol2[StartPos]; ExtremePoints[3][i] = DstCol2[EndPos]; } } // for (int i = 0; i < NThreads; i++) { // printf("ExtremePoints[%d] = %d-%d -> %d-%d\n", i, ExtremePoints[0][i].Val, ExtremePoints[1][i].Val, ExtremePoints[2][i].Val, ExtremePoints[3][i].Val); // } // find min points TInt MinId(INT_MAX); for (int j = 0; j < 2; j++) { for (int i = 0; i < NThreads; i++) { if (MinId > ExtremePoints[j][i]) { MinId = ExtremePoints[j][i]; } } } TInt MaxId(-1); for (int j = 2; j < 4; j++) { for (int i = 0; i < NThreads; i++) { if (MaxId < ExtremePoints[j][i]) { MaxId = ExtremePoints[j][i]; } } } // printf("MinId = %d\n", MinId.Val); // printf("MaxId = %d\n", MaxId.Val); Sw->Stop(TStopwatch::Sort); Sw->Start(TStopwatch::Group); // const int NumCollectors = omp_get_max_threads(); const int NumCollectors = 20; int Range = MaxId.Val - MinId.Val; TIntV IdRanges(NumCollectors+1); for (int j = 0; j < NumCollectors; j++) { IdRanges[j] = MinId + Range/NumCollectors*j; } IdRanges[NumCollectors] = MaxId+1; // for (int i = 0; i < NumCollectors+1; i++) { // printf("IdRanges[%d] = %d\n", i, IdRanges[i].Val); // } int SrcOffsets[NThreads][NumCollectors+1]; #pragma omp parallel for schedule(static) for (int i = 0; i < NThreads; i++) { int CollectorId = 0; for (int j = Parts[i]; j < Parts[i+1]; j++) { while (SrcCol1[j] >= IdRanges[CollectorId]) { SrcOffsets[i][CollectorId++] = j; } } while (CollectorId <= NumCollectors) { SrcOffsets[i][CollectorId++] = Parts[i+1]; } } int DstOffsets[NThreads][NumCollectors+1]; #pragma omp parallel for schedule(static) for (int i = 0; i < NThreads; i++) { int CollectorId = 0; for (int j = Parts[i]; j < Parts[i+1]; j++) { while (DstCol2[j] >= IdRanges[CollectorId]) { DstOffsets[i][CollectorId++] = j; } } while (CollectorId <= NumCollectors) { DstOffsets[i][CollectorId++] = Parts[i+1]; } } // for (int i = 0; i < NThreads; i++) { // for (int j = 0; j < NumCollectors+1; j++) { // printf("SrcOffsets[%d][%d] = %d\n", i, j, SrcOffsets[i][j]); // } // } // for (int i = 0; i < NThreads; i++) { // for (int j = 0; j < NumCollectors+1; j++) { // printf("DstOffsets[%d][%d] = %d\n", i, j, DstOffsets[i][j]); // } // } TIntV SrcCollectorOffsets(NumCollectors+1); SrcCollectorOffsets[0] = 0; for (int k = 0; k < NumCollectors; k++) { int SumOffset = 0; for (int i = 0; i < NThreads; i++) { SumOffset += SrcOffsets[i][k+1] - SrcOffsets[i][k]; } SrcCollectorOffsets[k+1] = SrcCollectorOffsets[k] + SumOffset; } TIntV DstCollectorOffsets(NumCollectors+1); DstCollectorOffsets[0] = 0; for (int k = 0; k < NumCollectors; k++) { int SumOffset = 0; for (int i = 0; i < NThreads; i++) { SumOffset += DstOffsets[i][k+1] - DstOffsets[i][k]; } DstCollectorOffsets[k+1] = DstCollectorOffsets[k] + SumOffset; } // for (int i = 0; i < NumCollectors+1; i++) { // printf("SrcCollectorOffsets[%d] = %d\n", i, SrcCollectorOffsets[i].Val); // } // for (int i = 0; i < NumCollectors+1; i++) { // printf("DstCollectorOffsets[%d] = %d\n", i, DstCollectorOffsets[i].Val); // } TIntV SrcCol3, EdgeCol3, EdgeCol4, DstCol4; #pragma omp parallel sections num_threads(4) { #pragma omp section { SrcCol3.Reserve(NumRows, NumRows); } #pragma omp section { EdgeCol3.Reserve(NumRows, NumRows); } #pragma omp section { DstCol4.Reserve(NumRows, NumRows); } #pragma omp section { EdgeCol4.Reserve(NumRows, NumRows); } } TIntV SrcNodeCounts(NumCollectors), DstNodeCounts(NumCollectors); #pragma omp parallel for schedule(static) for (int k = 0; k < NumCollectors; k++) { int ind = SrcCollectorOffsets[k]; for (int i = 0; i < NThreads; i++) { for (int j = SrcOffsets[i][k]; j < SrcOffsets[i][k+1]; j++) { SrcCol3[ind] = SrcCol1[j]; EdgeCol3[ind] = EdgeCol1[j]; ind++; } } TTable::QSortKeyVal(SrcCol3, EdgeCol3, SrcCollectorOffsets[k], SrcCollectorOffsets[k+1]-1); int SrcCount = 0; if (SrcCollectorOffsets[k+1] > SrcCollectorOffsets[k]) { SrcCount = 1; for (int j = SrcCollectorOffsets[k]+1; j < SrcCollectorOffsets[k+1]; j++) { if (SrcCol3[j] != SrcCol3[j-1]) { SrcCount++; } } } SrcNodeCounts[k] = SrcCount; ind = DstCollectorOffsets[k]; for (int i = 0; i < NThreads; i++) { for (int j = DstOffsets[i][k]; j < DstOffsets[i][k+1]; j++) { DstCol4[ind] = DstCol2[j]; EdgeCol4[ind] = EdgeCol2[j]; ind++; } } TTable::QSortKeyVal(DstCol4, EdgeCol4, DstCollectorOffsets[k], DstCollectorOffsets[k+1]-1); int DstCount = 0; if (DstCollectorOffsets[k+1] > DstCollectorOffsets[k]) { DstCount = 1; for (int j = DstCollectorOffsets[k]+1; j < DstCollectorOffsets[k+1]; j++) { if (DstCol4[j] != DstCol4[j-1]) { DstCount++; } } } DstNodeCounts[k] = DstCount; } TInt TotalSrcNodes = 0; TIntV SrcIdOffsets; for (int i = 0; i < NumCollectors; i++) { SrcIdOffsets.Add(TotalSrcNodes); TotalSrcNodes += SrcNodeCounts[i]; } // printf("Sorted = %d - %d\n", SrcCol3.IsSorted(), DstCol4.IsSorted()); // for (int i = 0; i < NumRows-1; i++) { // if (SrcCol3[i] > SrcCol3[i+1]) { printf("i=%d: %d %d\n", i, SrcCol3[i].Val, SrcCol3[i+1].Val); } // } // for (int i = 0; i < NumRows-1; i++) { // if (DstCol4[i] > DstCol4[i+1]) { printf("i=%d: %d %d\n", i, DstCol4[i].Val, DstCol4[i+1].Val); } // } TInt TotalDstNodes = 0; TIntV DstIdOffsets; for (int i = 0; i < NumCollectors; i++) { DstIdOffsets.Add(TotalDstNodes); TotalDstNodes += DstNodeCounts[i]; } // find vector of (node_id, start_offset) where start_offset is the index of the first row with node_id TIntPrV SrcNodeIds, DstNodeIds; #pragma omp parallel sections { #pragma omp section { SrcNodeIds.Reserve(TotalSrcNodes, TotalSrcNodes); } #pragma omp section { DstNodeIds.Reserve(TotalDstNodes, TotalDstNodes); } } // Find the starting offset of each node (in both src and dst) #pragma omp parallel for schedule(dynamic) for (int t = 0; t < 2*NumCollectors; t++) { if (t < NumCollectors) { TInt i = t; if (SrcCollectorOffsets[i] < SrcCollectorOffsets[i+1]) { TInt CurrNode = SrcCol3[SrcCollectorOffsets[i]]; TInt ThreadOffset = SrcIdOffsets[i]; SrcNodeIds[ThreadOffset] = TIntPr(CurrNode, SrcCollectorOffsets[i]); TInt CurrCount = 1; for (TInt j = SrcCollectorOffsets[i]+1; j < SrcCollectorOffsets[i+1]; j++) { while (j < SrcCollectorOffsets[i+1] && SrcCol3[j] == CurrNode) { j++; } if (j < SrcCollectorOffsets[i+1]) { CurrNode = SrcCol3[j]; SrcNodeIds[ThreadOffset+CurrCount] = TIntPr(CurrNode, j); CurrCount++; } } } } else { TInt i = t - NumCollectors; if (DstCollectorOffsets[i] < DstCollectorOffsets[i+1]) { TInt CurrNode = DstCol4[DstCollectorOffsets[i]]; TInt ThreadOffset = DstIdOffsets[i]; DstNodeIds[ThreadOffset] = TIntPr(CurrNode, DstCollectorOffsets[i]); TInt CurrCount = 1; for (TInt j = DstCollectorOffsets[i]+1; j < DstCollectorOffsets[i+1]; j++) { while (j < DstCollectorOffsets[i+1] && DstCol4[j] == CurrNode) { j++; } if (j < DstCollectorOffsets[i+1]) { CurrNode = DstCol4[j]; DstNodeIds[ThreadOffset+CurrCount] = TIntPr(CurrNode, j); CurrCount++; } } } } } Sw->Stop(TStopwatch::Group); Sw->Start(TStopwatch::MergeNeighborhoods); // Find the combined neighborhood (both out-neighbors and in-neighbors) of each node TIntTrV Nodes; Nodes.Reserve(TotalSrcNodes+TotalDstNodes); TInt i = 0, j = 0; while (i < TotalSrcNodes && j < TotalDstNodes) { if (SrcNodeIds[i].Val1 == DstNodeIds[j].Val1) { Nodes.Add(TIntTr(SrcNodeIds[i].Val1, i, j)); i++; j++; } else if (SrcNodeIds[i].Val1 < DstNodeIds[j].Val1) { Nodes.Add(TIntTr(SrcNodeIds[i].Val1, i, -1)); i++; } else { Nodes.Add(TIntTr(DstNodeIds[j].Val1, -1, j)); j++; } } for (; i < TotalSrcNodes; i++) { Nodes.Add(TIntTr(SrcNodeIds[i].Val1, i, -1)); } for (; j < TotalDstNodes; j++) { Nodes.Add(TIntTr(DstNodeIds[j].Val1, -1, j)); } Sw->Stop(TStopwatch::MergeNeighborhoods); Sw->Start(TStopwatch::AddNeighborhoods); TInt NumNodes = Nodes.Len(); PGraphMP Graph = PGraphMP::TObj::New(NumNodes, NumRows); // NumThreads = omp_get_max_threads(); // int Delta = (NumNodes+NumThreads-1)/NumThreads; TVec<TIntV> InVV(NumNodes); TVec<TIntV> OutVV(NumNodes); // omp_set_num_threads(NumThreads); #pragma omp parallel for schedule(static,100) for (int m = 0; m < NumNodes; m++) { //double startTr = omp_get_wtime(); //TIntV OutV, InV; TInt n, i, j; Nodes[m].GetVal(n, i, j); if (i >= 0) { TInt Offset = SrcNodeIds[i].GetVal2(); TInt Sz = EdgeCol3.Len()-Offset; if (i < SrcNodeIds.Len()-1) { Sz = SrcNodeIds[i+1].GetVal2()-Offset; } OutVV[m].Reserve(Sz); OutVV[m].CopyUniqueFrom(EdgeCol3, Offset, Sz); } if (j >= 0) { TInt Offset = DstNodeIds[j].GetVal2(); TInt Sz = EdgeCol4.Len()-Offset; if (j < DstNodeIds.Len()-1) { Sz = DstNodeIds[j+1].GetVal2()-Offset; } InVV[m].Reserve(Sz); InVV[m].CopyUniqueFrom(EdgeCol4, Offset, Sz); } Graph->AddNodeWithEdges(n, InVV[m], OutVV[m]); } Graph->SetNodes(NumNodes); Sw->Stop(TStopwatch::AddNeighborhoods); Sw->Start(TStopwatch::AddEdges); omp_set_num_threads(omp_get_max_threads()); if (NodeType == atInt) { #pragma omp parallel for schedule(static) for (int i = 0; i < Partitions.Len(); i++) { TRowIterator RowI(Partitions[i].GetVal1(), Table()); TRowIterator EndI(Partitions[i].GetVal2(), Table()); while (RowI < EndI) { TInt RowId = RowI.GetRowIdx(); // EdgeId TInt SrcId = RowI.GetIntAttr(SrcColIdx); TInt DstId = RowI.GetIntAttr(DstColIdx); Graph->AddEdgeUnchecked(RowId, SrcId, DstId); RowI++; } } } else if (NodeType == atStr) { #pragma omp parallel for schedule(static) for (int i = 0; i < Partitions.Len(); i++) { TRowIterator RowI(Partitions[i].GetVal1(), Table()); TRowIterator EndI(Partitions[i].GetVal2(), Table()); while (RowI < EndI) { TInt RowId = RowI.GetRowIdx(); // EdgeId TInt SrcId = RowI.GetStrMapById(SrcColIdx); TInt DstId = RowI.GetStrMapById(DstColIdx); Graph->AddEdgeUnchecked(RowId, SrcId, DstId); RowI++; } } } Graph->SetEdges(NumRows); Sw->Stop(TStopwatch::AddEdges); // double endAdd = omp_get_wtime(); // printf("Add time = %f\n", endAdd-endAlloc); return Graph; } /// Calls ToNetworkMP2 with an empty attribute vector. Convenience wrapper. template<class PGraphMP> PGraphMP ToNetworkMP2(PTable Table, const TStr& SrcCol, const TStr& DstCol, TAttrAggr AggrPolicy) { TStrV V; return ToNetworkMP2<PGraphMP>(Table, SrcCol, DstCol, V, V, V, AggrPolicy); } #endif // GCC_ATOMIC /// Loads a mode, with name Name, into the PMMNet from the TTable. NCol specifies the node id column and NodeAttrV the node attributes. int LoadModeNetToNet(PMMNet Graph, const TStr& Name, PTable Table, const TStr& NCol, TStrV& NodeAttrV); /// Loads the nodes specified in column NCol from the TTable with the attributes specified in NodeAttrV. int LoadMode(TModeNet& Graph, PTable Table, const TStr& NCol, TStrV& NodeAttrV); /// Loads a crossnet from Mode1 to Mode2, with name CrossName, from the provided TTable. EdgeAttrV specifies edge attributes. int LoadCrossNetToNet(PMMNet Graph, const TStr& Mode1, const TStr& Mode2, const TStr& CrossName, PTable Table, const TStr& SrcCol, const TStr& DstCol, TStrV& EdgeAttrV); /// Loads the edges from the TTable and EdgeAttrV specifies columns containing edge attributes. int LoadCrossNet(TCrossNet& Graph, PTable Table, const TStr& SrcCol, const TStr& DstCol, TStrV& EdgeAttrV); /// Converts table to a network sequentially. Use if network has only edge attributes. template<class PGraph> PGraph ToNetwork(PTable Table, const TStr& SrcCol, const TStr& DstCol, TStrV& EdgeAttrV, TAttrAggr AggrPolicy) { PGraph Graph = PGraph::TObj::New(); const TAttrType NodeType = Table->GetColType(SrcCol); Assert(NodeType == Table->GetColType(DstCol)); const TInt SrcColIdx = Table->GetColIdx(SrcCol); const TInt DstColIdx = Table->GetColIdx(DstCol); //Table->AddGraphAttributeV(SrcAttrV, false, true, false); //Table->AddGraphAttributeV(DstAttrV, false, false, true); //Table->AddGraphAttributeV(EdgeAttrV, true, false, true); // node values - i.e. the unique values of src/dst col //THashSet<TInt> IntNodeVals; // for both int and string node attr types. THash<TFlt, TInt> FltNodeVals; // make single pass over all rows in the table for (int CurrRowIdx = 0; CurrRowIdx < (Table->Next).Len(); CurrRowIdx++) { if ((Table->Next)[CurrRowIdx] == Table->Invalid) { continue; } // add src and dst nodes to graph if they are not seen earlier TInt SVal, DVal; if (NodeType == atFlt) { TFlt FSVal = (Table->FltCols)[SrcColIdx][CurrRowIdx]; SVal = Table->CheckAndAddFltNode(Graph, FltNodeVals, FSVal); TFlt FDVal = (Table->FltCols)[SrcColIdx][CurrRowIdx]; DVal = Table->CheckAndAddFltNode(Graph, FltNodeVals, FDVal); } else if (NodeType == atInt || NodeType == atStr) { if (NodeType == atInt) { SVal = (Table->IntCols)[SrcColIdx][CurrRowIdx]; DVal = (Table->IntCols)[DstColIdx][CurrRowIdx]; } else { SVal = (Table->StrColMaps)[SrcColIdx][CurrRowIdx]; // if (strlen(Table->GetContextKey(SVal)) == 0) { continue; } //illegal value DVal = (Table->StrColMaps)[DstColIdx][CurrRowIdx]; // if (strlen(Table->GetContextKey(DVal)) == 0) { continue; } //illegal value } if (!Graph->IsNode(SVal)) {Graph->AddNode(SVal); } if (!Graph->IsNode(DVal)) {Graph->AddNode(DVal); } //CheckAndAddIntNode(Graph, IntNodeVals, SVal); //CheckAndAddIntNode(Graph, IntNodeVals, DVal); } // add edge and edge attributes Graph->AddEdge(SVal, DVal, CurrRowIdx); // Aggregate edge attributes and add to graph for (TInt i = 0; i < EdgeAttrV.Len(); i++) { TStr ColName = EdgeAttrV[i]; TAttrType T = Table->GetColType(ColName); TInt Index = Table->GetColIdx(ColName); switch (T) { case atInt: Graph->AddIntAttrDatE(CurrRowIdx, Table->IntCols[Index][CurrRowIdx], ColName); break; case atFlt: Graph->AddFltAttrDatE(CurrRowIdx, Table->FltCols[Index][CurrRowIdx], ColName); break; case atStr: Graph->AddStrAttrDatE(CurrRowIdx, Table->GetStrValIdx(Index, CurrRowIdx), ColName); break; } } } return Graph; } #ifdef GCC_ATOMIC /// Converts table to network in parallel. Use if network has only edge attributes. template<class PGraphMP> inline PGraphMP ToNetworkMP(PTable Table, const TStr& SrcCol, const TStr& DstCol, TStrV& EdgeAttrV, TAttrAggr AggrPolicy) { TStopwatch* Sw = TStopwatch::GetInstance(); Sw->Start(TStopwatch::AllocateColumnCopies); const TInt SrcColIdx = Table->GetColIdx(SrcCol); const TInt DstColIdx = Table->GetColIdx(DstCol); const TInt NumRows = Table->GetNumValidRows(); const TAttrType NodeType = Table->GetColType(SrcCol); Assert(NodeType == Table->GetColType(DstCol)); TIntV SrcCol1, EdgeCol1, EdgeCol2, DstCol2; THash<TInt, TStrIntVH> NodeIntAttrs; THash<TInt, TStrFltVH> NodeFltAttrs; THash<TInt, TStrStrVH> NodeStrAttrs; #pragma omp parallel sections num_threads(4) { #pragma omp section { SrcCol1.Reserve(NumRows, NumRows); } #pragma omp section { EdgeCol1.Reserve(NumRows, NumRows); } #pragma omp section { DstCol2.Reserve(NumRows, NumRows); } #pragma omp section { EdgeCol2.Reserve(NumRows, NumRows); } } Sw->Stop(TStopwatch::AllocateColumnCopies); Sw->Start(TStopwatch::CopyColumns); TIntPrV Partitions; Table->GetPartitionRanges(Partitions, omp_get_max_threads()); TInt PartitionSize = Partitions[0].GetVal2()-Partitions[0].GetVal1()+1; // double endPartition = omp_get_wtime(); // printf("Partition time = %f\n", endPartition-endResize); omp_set_num_threads(omp_get_max_threads()); if (NodeType == atInt) { #pragma omp parallel for schedule(static) for (int i = 0; i < Partitions.Len(); i++) { TRowIterator RowI(Partitions[i].GetVal1(), Table()); TRowIterator EndI(Partitions[i].GetVal2(), Table()); while (RowI < EndI) { TInt RowId = RowI.GetRowIdx(); SrcCol1[RowId] = RowI.GetIntAttr(SrcColIdx); EdgeCol1[RowId] = RowId; DstCol2[RowId] = RowI.GetIntAttr(DstColIdx); EdgeCol2[RowId] = RowId; RowI++; } } } else if (NodeType == atStr) { #pragma omp parallel for schedule(static) for (int i = 0; i < Partitions.Len(); i++) { TRowIterator RowI(Partitions[i].GetVal1(), Table()); TRowIterator EndI(Partitions[i].GetVal2(), Table()); while (RowI < EndI) { TInt RowId = RowI.GetRowIdx(); SrcCol1[RowId] = RowI.GetStrMapById(SrcColIdx); EdgeCol1[RowId] = RowId; DstCol2[RowId] = RowI.GetStrMapById(DstColIdx); EdgeCol2[RowId] = RowId; RowI++; } } } Sw->Stop(TStopwatch::CopyColumns); Sw->Start(TStopwatch::Sort); omp_set_num_threads(omp_get_max_threads()); #pragma omp parallel { #pragma omp single nowait { #ifndef GLib_WIN32 #pragma omp task untied shared(SrcCol1, EdgeCol1) #endif { TTable::QSortKeyVal(SrcCol1, EdgeCol1, 0, NumRows-1); } } #pragma omp single nowait { #ifndef GLib_WIN32 #pragma omp task untied shared(EdgeCol2, DstCol2) #endif { TTable::QSortKeyVal(DstCol2, EdgeCol2, 0, NumRows-1); } } #ifndef GLib_WIN32 #pragma omp taskwait #endif } Sw->Stop(TStopwatch::Sort); Sw->Start(TStopwatch::Group); TInt NumThreads = omp_get_max_threads(); TInt PartSize = (NumRows/NumThreads); // Find the offset of all partitions, each of which contains a list of rows. // Nodes from same sources or destinations are ensured to be kept within same partition. TIntV SrcOffsets, DstOffsets; SrcOffsets.Add(0); for (TInt i = 1; i < NumThreads; i++) { TInt CurrOffset = i * PartSize; while (CurrOffset < (i+1) * PartSize && SrcCol1[CurrOffset-1] == SrcCol1[CurrOffset]) { // ensure that rows from the same sources are grouped together CurrOffset++; } if (CurrOffset < (i+1) * PartSize) { SrcOffsets.Add(CurrOffset); } } SrcOffsets.Add(NumRows); DstOffsets.Add(0); for (TInt i = 1; i < NumThreads; i++) { TInt CurrOffset = i * PartSize; while (CurrOffset < (i+1) * PartSize && DstCol2[CurrOffset-1] == DstCol2[CurrOffset]) { // ensure that rows to the same destinations are grouped together CurrOffset++; } if (CurrOffset < (i+1) * PartSize) { DstOffsets.Add(CurrOffset); } } DstOffsets.Add(NumRows); TInt SrcPartCnt = SrcOffsets.Len()-1; // number of partitions TInt DstPartCnt = DstOffsets.Len()-1; // number of partitions // count the number of source nodes and destination nodes in each partition TIntV SrcNodeCounts, DstNodeCounts; SrcNodeCounts.Reserve(SrcPartCnt, SrcPartCnt); DstNodeCounts.Reserve(DstPartCnt, DstPartCnt); #pragma omp parallel for schedule(dynamic) for (int t = 0; t < SrcPartCnt+DstPartCnt; t++) { if (t < SrcPartCnt) { TInt i = t; if (SrcOffsets[i] != SrcOffsets[i+1]) { SrcNodeCounts[i] = 1; TInt CurrNode = SrcCol1[SrcOffsets[i]]; for (TInt j = SrcOffsets[i]+1; j < SrcOffsets[i+1]; j++) { while (j < SrcOffsets[i+1] && SrcCol1[j] == CurrNode) { j++; } if (j < SrcOffsets[i+1]) { SrcNodeCounts[i]++; CurrNode = SrcCol1[j]; } } } } else { TInt i = t - SrcPartCnt; if (DstOffsets[i] != DstOffsets[i+1]) { DstNodeCounts[i] = 1; TInt CurrNode = DstCol2[DstOffsets[i]]; for (TInt j = DstOffsets[i]+1; j < DstOffsets[i+1]; j++) { while (j < DstOffsets[i+1] && DstCol2[j] == CurrNode) { j++; } if (j < DstOffsets[i+1]) { DstNodeCounts[i]++; CurrNode = DstCol2[j]; } } } } } TInt TotalSrcNodes = 0; TIntV SrcIdOffsets; for (int i = 0; i < SrcPartCnt; i++) { SrcIdOffsets.Add(TotalSrcNodes); TotalSrcNodes += SrcNodeCounts[i]; } TInt TotalDstNodes = 0; TIntV DstIdOffsets; for (int i = 0; i < DstPartCnt; i++) { DstIdOffsets.Add(TotalDstNodes); TotalDstNodes += DstNodeCounts[i]; } // printf("Total Src = %d, Total Dst = %d\n", TotalSrcNodes.Val, TotalDstNodes.Val); // find vector of (node_id, start_offset) where start_offset is the index of the first row with node_id TIntPrV SrcNodeIds, DstNodeIds; #pragma omp parallel sections { #pragma omp section { SrcNodeIds.Reserve(TotalSrcNodes, TotalSrcNodes); } #pragma omp section { DstNodeIds.Reserve(TotalDstNodes, TotalDstNodes); } } // Find the starting offset of each node (in both src and dst) #pragma omp parallel for schedule(dynamic) for (int t = 0; t < SrcPartCnt+DstPartCnt; t++) { if (t < SrcPartCnt) { TInt i = t; if (SrcOffsets[i] != SrcOffsets[i+1]) { TInt CurrNode = SrcCol1[SrcOffsets[i]]; TInt ThreadOffset = SrcIdOffsets[i]; SrcNodeIds[ThreadOffset] = TIntPr(CurrNode, SrcOffsets[i]); TInt CurrCount = 1; for (TInt j = SrcOffsets[i]+1; j < SrcOffsets[i+1]; j++) { while (j < SrcOffsets[i+1] && SrcCol1[j] == CurrNode) { j++; } if (j < SrcOffsets[i+1]) { CurrNode = SrcCol1[j]; SrcNodeIds[ThreadOffset+CurrCount] = TIntPr(CurrNode, j); CurrCount++; } } } } else { TInt i = t - SrcPartCnt; if (DstOffsets[i] != DstOffsets[i+1]) { TInt CurrNode = DstCol2[DstOffsets[i]]; TInt ThreadOffset = DstIdOffsets[i]; DstNodeIds[ThreadOffset] = TIntPr(CurrNode, DstOffsets[i]); TInt CurrCount = 1; for (TInt j = DstOffsets[i]+1; j < DstOffsets[i+1]; j++) { while (j < DstOffsets[i+1] && DstCol2[j] == CurrNode) { j++; } if (j < DstOffsets[i+1]) { CurrNode = DstCol2[j]; DstNodeIds[ThreadOffset+CurrCount] = TIntPr(CurrNode, j); CurrCount++; } } } } } Sw->Stop(TStopwatch::Group); Sw->Start(TStopwatch::MergeNeighborhoods); // Find the combined neighborhood (both out-neighbors and in-neighbors) of each node TIntTrV Nodes; Nodes.Reserve(TotalSrcNodes+TotalDstNodes); TInt i = 0, j = 0; while (i < TotalSrcNodes && j < TotalDstNodes) { if (SrcNodeIds[i].Val1 == DstNodeIds[j].Val1) { Nodes.Add(TIntTr(SrcNodeIds[i].Val1, i, j)); i++; j++; } else if (SrcNodeIds[i].Val1 < DstNodeIds[j].Val1) { Nodes.Add(TIntTr(SrcNodeIds[i].Val1, i, -1)); i++; } else { Nodes.Add(TIntTr(DstNodeIds[j].Val1, -1, j)); j++; } } for (; i < TotalSrcNodes; i++) { Nodes.Add(TIntTr(SrcNodeIds[i].Val1, i, -1)); } for (; j < TotalDstNodes; j++) { Nodes.Add(TIntTr(DstNodeIds[j].Val1, -1, j)); } Sw->Stop(TStopwatch::MergeNeighborhoods); Sw->Start(TStopwatch::AddNeighborhoods); TInt NumNodes = Nodes.Len(); PGraphMP Graph = PGraphMP::TObj::New(NumNodes, NumRows); // NumThreads = omp_get_max_threads(); // int Delta = (NumNodes+NumThreads-1)/NumThreads; TVec<TIntV> InVV(NumNodes); TVec<TIntV> OutVV(NumNodes); // omp_set_num_threads(NumThreads); #pragma omp parallel for schedule(static,100) for (int m = 0; m < NumNodes; m++) { //double startTr = omp_get_wtime(); //TIntV OutV, InV; TInt n, i, j; Nodes[m].GetVal(n, i, j); if (i >= 0) { TInt Offset = SrcNodeIds[i].GetVal2(); TInt Sz = EdgeCol1.Len()-Offset; if (i < SrcNodeIds.Len()-1) { Sz = SrcNodeIds[i+1].GetVal2()-Offset; } OutVV[m].Reserve(Sz); OutVV[m].CopyUniqueFrom(EdgeCol1, Offset, Sz); } if (j >= 0) { TInt Offset = DstNodeIds[j].GetVal2(); TInt Sz = EdgeCol2.Len()-Offset; if (j < DstNodeIds.Len()-1) { Sz = DstNodeIds[j+1].GetVal2()-Offset; } InVV[m].Reserve(Sz); InVV[m].CopyUniqueFrom(EdgeCol2, Offset, Sz); } Graph->AddNodeWithEdges(n, InVV[m], OutVV[m]); } Graph->SetNodes(NumNodes); Sw->Stop(TStopwatch::AddNeighborhoods); Sw->Start(TStopwatch::AddEdges); omp_set_num_threads(omp_get_max_threads()); if (NodeType == atInt) { #pragma omp parallel for schedule(static) for (int i = 0; i < Partitions.Len(); i++) { TRowIterator RowI(Partitions[i].GetVal1(), Table()); TRowIterator EndI(Partitions[i].GetVal2(), Table()); while (RowI < EndI) { TInt RowId = RowI.GetRowIdx(); // EdgeId TInt SrcId = RowI.GetIntAttr(SrcColIdx); TInt DstId = RowI.GetIntAttr(DstColIdx); Graph->AddEdgeUnchecked(RowId, SrcId, DstId); RowI++; } } } else if (NodeType == atStr) { #pragma omp parallel for schedule(static) for (int i = 0; i < Partitions.Len(); i++) { TRowIterator RowI(Partitions[i].GetVal1(), Table()); TRowIterator EndI(Partitions[i].GetVal2(), Table()); while (RowI < EndI) { TInt RowId = RowI.GetRowIdx(); // EdgeId TInt SrcId = RowI.GetStrMapById(SrcColIdx); TInt DstId = RowI.GetStrMapById(DstColIdx); Graph->AddEdgeUnchecked(RowId, SrcId, DstId); RowI++; } } } Graph->SetEdges(NumRows); Graph->SetMxEId(NumRows); Sw->Stop(TStopwatch::AddEdges); // make single pass over all rows in the table to add attributes for (int CurrRowIdx = 0; CurrRowIdx < (Table->Next).Len(); CurrRowIdx++) { if ((Table->Next)[CurrRowIdx] == Table->Invalid) { continue; } for (TInt ea_i = 0; ea_i < EdgeAttrV.Len(); ea_i++) { TStr ColName = EdgeAttrV[ea_i]; TAttrType T = Table->GetColType(ColName); TInt Index = Table->GetColIdx(ColName); switch (T) { case atInt: Graph->AddIntAttrDatE(CurrRowIdx, Table->IntCols[Index][CurrRowIdx], ColName); break; case atFlt: Graph->AddFltAttrDatE(CurrRowIdx, Table->FltCols[Index][CurrRowIdx], ColName); break; case atStr: Graph->AddStrAttrDatE(CurrRowIdx, Table->GetStrValIdx(Index, CurrRowIdx), ColName); break; } } } // double endAdd = omp_get_wtime(); // printf("Add time = %f\n", endAdd-endAlloc); return Graph; } #endif // GCC_ATOMIC /// Converts table to network sequentially. Takes edges from \c Table and nodes explicitly from \c NodeCol in \c NodeTable, with attribute vectors passed as columns in corresponding tables. template<class PGraph> PGraph ToNetwork(PTable Table, const TStr& SrcCol, const TStr& DstCol, TStrV& EdgeAttrV, PTable NodeTable, const TStr& NodeCol, TStrV& NodeAttrV, TAttrAggr AggrPolicy) { PGraph Graph = PGraph::TObj::New(); const TAttrType NodeType = Table->GetColType(SrcCol); Assert(NodeType == Table->GetColType(DstCol)); const TInt SrcColIdx = Table->GetColIdx(SrcCol); const TInt DstColIdx = Table->GetColIdx(DstCol); const TAttrType NodeTypeN = NodeTable->GetColType(NodeCol); const TInt NodeColIdx = NodeTable->GetColIdx(NodeCol); THash<TInt, TStrIntVH> NodeIntAttrs; THash<TInt, TStrFltVH> NodeFltAttrs; THash<TInt, TStrStrVH> NodeStrAttrs; //Table->AddGraphAttributeV(SrcAttrV, false, true, false); //Table->AddGraphAttributeV(DstAttrV, false, false, true); //Table->AddGraphAttributeV(EdgeAttrV, true, false, true); // node values - i.e. the unique values of src/dst col //THashSet<TInt> IntNodeVals; // for both int and string node attr types. THash<TFlt, TInt> FltNodeVals; // make single pass over all rows in the table for (int CurrRowIdx = 0; CurrRowIdx < (Table->Next).Len(); CurrRowIdx++) { if ((Table->Next)[CurrRowIdx] == Table->Invalid) { continue; } // add src and dst nodes to graph if they are not seen earlier TInt SVal, DVal; if (NodeType == atFlt) { TFlt FSVal = (Table->FltCols)[SrcColIdx][CurrRowIdx]; SVal = Table->CheckAndAddFltNode(Graph, FltNodeVals, FSVal); TFlt FDVal = (Table->FltCols)[SrcColIdx][CurrRowIdx]; DVal = Table->CheckAndAddFltNode(Graph, FltNodeVals, FDVal); } else if (NodeType == atInt || NodeType == atStr) { if (NodeType == atInt) { SVal = (Table->IntCols)[SrcColIdx][CurrRowIdx]; DVal = (Table->IntCols)[DstColIdx][CurrRowIdx]; } else { SVal = (Table->StrColMaps)[SrcColIdx][CurrRowIdx]; // if (strlen(Table->GetContextKey(SVal)) == 0) { continue; } //illegal value DVal = (Table->StrColMaps)[DstColIdx][CurrRowIdx]; // if (strlen(Table->GetContextKey(DVal)) == 0) { continue; } //illegal value } if (!Graph->IsNode(SVal)) {Graph->AddNode(SVal); } if (!Graph->IsNode(DVal)) {Graph->AddNode(DVal); } //CheckAndAddIntNode(Graph, IntNodeVals, SVal); //CheckAndAddIntNode(Graph, IntNodeVals, DVal); } // add edge and edge attributes Graph->AddEdge(SVal, DVal, CurrRowIdx); // Aggregate edge attributes and add to graph for (TInt i = 0; i < EdgeAttrV.Len(); i++) { TStr ColName = EdgeAttrV[i]; TAttrType T = Table->GetColType(ColName); TInt Index = Table->GetColIdx(ColName); switch (T) { case atInt: Graph->AddIntAttrDatE(CurrRowIdx, Table->IntCols[Index][CurrRowIdx], ColName); break; case atFlt: Graph->AddFltAttrDatE(CurrRowIdx, Table->FltCols[Index][CurrRowIdx], ColName); break; case atStr: Graph->AddStrAttrDatE(CurrRowIdx, Table->GetStrValIdx(Index, CurrRowIdx), ColName); break; } } } //Add node attribtes if (NodeAttrV.Len() > 0) { for (int CurrRowIdx = 0; CurrRowIdx < (NodeTable->Next).Len(); CurrRowIdx++) { if ((NodeTable->Next)[CurrRowIdx] == NodeTable->Invalid) { continue; } TInt NId; if (NodeTypeN == atInt) { NId = (NodeTable->IntCols)[NodeColIdx][CurrRowIdx]; } else if (NodeTypeN == atStr){ NId = (NodeTable->StrColMaps)[NodeColIdx][CurrRowIdx]; } for (TInt i = 0; i < NodeAttrV.Len(); i++) { TStr ColName = NodeAttrV[i]; TAttrType T = NodeTable->GetColType(ColName); TInt Index = NodeTable->GetColIdx(ColName); switch (T) { case atInt: Graph->AddIntAttrDatN(NId, NodeTable->IntCols[Index][CurrRowIdx], ColName); break; case atFlt: Graph->AddFltAttrDatN(NId, NodeTable->FltCols[Index][CurrRowIdx], ColName); break; case atStr: Graph->AddStrAttrDatN(NId, NodeTable->GetStrValIdx(Index, CurrRowIdx), ColName); break; } } } } return Graph; } #ifdef GCC_ATOMIC /// Converts table to network in parallel. Takes edges from \c Table and nodes explicitly from \c NodeCol in \c NodeTable, with attribute vectors passed as columns in corresponding tables. template<class PGraphMP> inline PGraphMP ToNetworkMP(PTable Table, const TStr& SrcCol, const TStr& DstCol, TStrV& EdgeAttrV, PTable NodeTable, const TStr& NodeCol, TStrV& NodeAttrV, TAttrAggr AggrPolicy) { TStopwatch* Sw = TStopwatch::GetInstance(); Sw->Start(TStopwatch::AllocateColumnCopies); const TInt SrcColIdx = Table->GetColIdx(SrcCol); const TInt DstColIdx = Table->GetColIdx(DstCol); const TInt NumRows = Table->GetNumValidRows(); const TAttrType NodeType = Table->GetColType(SrcCol); Assert(NodeType == Table->GetColType(DstCol)); TIntV SrcCol1, EdgeCol1, EdgeCol2, DstCol2; const TAttrType NodeTypeN = NodeTable->GetColType(NodeCol); const TInt NodeColIdx = NodeTable->GetColIdx(NodeCol); THash<TInt, TStrIntVH> NodeIntAttrs; THash<TInt, TStrFltVH> NodeFltAttrs; THash<TInt, TStrStrVH> NodeStrAttrs; #pragma omp parallel sections num_threads(4) { #pragma omp section { SrcCol1.Reserve(NumRows, NumRows); } #pragma omp section { EdgeCol1.Reserve(NumRows, NumRows); } #pragma omp section { DstCol2.Reserve(NumRows, NumRows); } #pragma omp section { EdgeCol2.Reserve(NumRows, NumRows); } } Sw->Stop(TStopwatch::AllocateColumnCopies); Sw->Start(TStopwatch::CopyColumns); TIntPrV Partitions; Table->GetPartitionRanges(Partitions, omp_get_max_threads()); TInt PartitionSize = Partitions[0].GetVal2()-Partitions[0].GetVal1()+1; // double endPartition = omp_get_wtime(); // printf("Partition time = %f\n", endPartition-endResize); omp_set_num_threads(omp_get_max_threads()); if (NodeType == atInt) { #pragma omp parallel for schedule(static) for (int i = 0; i < Partitions.Len(); i++) { TRowIterator RowI(Partitions[i].GetVal1(), Table()); TRowIterator EndI(Partitions[i].GetVal2(), Table()); while (RowI < EndI) { TInt RowId = RowI.GetRowIdx(); SrcCol1[RowId] = RowI.GetIntAttr(SrcColIdx); EdgeCol1[RowId] = RowId; DstCol2[RowId] = RowI.GetIntAttr(DstColIdx); EdgeCol2[RowId] = RowId; RowI++; } } } else if (NodeType == atStr) { #pragma omp parallel for schedule(static) for (int i = 0; i < Partitions.Len(); i++) { TRowIterator RowI(Partitions[i].GetVal1(), Table()); TRowIterator EndI(Partitions[i].GetVal2(), Table()); while (RowI < EndI) { TInt RowId = RowI.GetRowIdx(); SrcCol1[RowId] = RowI.GetStrMapById(SrcColIdx); EdgeCol1[RowId] = RowId; DstCol2[RowId] = RowI.GetStrMapById(DstColIdx); EdgeCol2[RowId] = RowId; RowI++; } } } Sw->Stop(TStopwatch::CopyColumns); Sw->Start(TStopwatch::Sort); omp_set_num_threads(omp_get_max_threads()); #pragma omp parallel { #pragma omp single nowait { #ifndef GLib_WIN32 #pragma omp task untied shared(SrcCol1, EdgeCol1) #endif { TTable::QSortKeyVal(SrcCol1, EdgeCol1, 0, NumRows-1); } } #pragma omp single nowait { #ifndef GLib_WIN32 #pragma omp task untied shared(EdgeCol2, DstCol2) #endif { TTable::QSortKeyVal(DstCol2, EdgeCol2, 0, NumRows-1); } } #ifndef GLib_WIN32 #pragma omp taskwait #endif } Sw->Stop(TStopwatch::Sort); Sw->Start(TStopwatch::Group); TInt NumThreads = omp_get_max_threads(); TInt PartSize = (NumRows/NumThreads); // Find the offset of all partitions, each of which contains a list of rows. // Nodes from same sources or destinations are ensured to be kept within same partition. TIntV SrcOffsets, DstOffsets; SrcOffsets.Add(0); for (TInt i = 1; i < NumThreads; i++) { TInt CurrOffset = i * PartSize; while (CurrOffset < (i+1) * PartSize && SrcCol1[CurrOffset-1] == SrcCol1[CurrOffset]) { // ensure that rows from the same sources are grouped together CurrOffset++; } if (CurrOffset < (i+1) * PartSize) { SrcOffsets.Add(CurrOffset); } } SrcOffsets.Add(NumRows); DstOffsets.Add(0); for (TInt i = 1; i < NumThreads; i++) { TInt CurrOffset = i * PartSize; while (CurrOffset < (i+1) * PartSize && DstCol2[CurrOffset-1] == DstCol2[CurrOffset]) { // ensure that rows to the same destinations are grouped together CurrOffset++; } if (CurrOffset < (i+1) * PartSize) { DstOffsets.Add(CurrOffset); } } DstOffsets.Add(NumRows); TInt SrcPartCnt = SrcOffsets.Len()-1; // number of partitions TInt DstPartCnt = DstOffsets.Len()-1; // number of partitions // count the number of source nodes and destination nodes in each partition TIntV SrcNodeCounts, DstNodeCounts; SrcNodeCounts.Reserve(SrcPartCnt, SrcPartCnt); DstNodeCounts.Reserve(DstPartCnt, DstPartCnt); #pragma omp parallel for schedule(dynamic) for (int t = 0; t < SrcPartCnt+DstPartCnt; t++) { if (t < SrcPartCnt) { TInt i = t; if (SrcOffsets[i] != SrcOffsets[i+1]) { SrcNodeCounts[i] = 1; TInt CurrNode = SrcCol1[SrcOffsets[i]]; for (TInt j = SrcOffsets[i]+1; j < SrcOffsets[i+1]; j++) { while (j < SrcOffsets[i+1] && SrcCol1[j] == CurrNode) { j++; } if (j < SrcOffsets[i+1]) { SrcNodeCounts[i]++; CurrNode = SrcCol1[j]; } } } } else { TInt i = t - SrcPartCnt; if (DstOffsets[i] != DstOffsets[i+1]) { DstNodeCounts[i] = 1; TInt CurrNode = DstCol2[DstOffsets[i]]; for (TInt j = DstOffsets[i]+1; j < DstOffsets[i+1]; j++) { while (j < DstOffsets[i+1] && DstCol2[j] == CurrNode) { j++; } if (j < DstOffsets[i+1]) { DstNodeCounts[i]++; CurrNode = DstCol2[j]; } } } } } TInt TotalSrcNodes = 0; TIntV SrcIdOffsets; for (int i = 0; i < SrcPartCnt; i++) { SrcIdOffsets.Add(TotalSrcNodes); TotalSrcNodes += SrcNodeCounts[i]; } TInt TotalDstNodes = 0; TIntV DstIdOffsets; for (int i = 0; i < DstPartCnt; i++) { DstIdOffsets.Add(TotalDstNodes); TotalDstNodes += DstNodeCounts[i]; } // printf("Total Src = %d, Total Dst = %d\n", TotalSrcNodes.Val, TotalDstNodes.Val); // find vector of (node_id, start_offset) where start_offset is the index of the first row with node_id TIntPrV SrcNodeIds, DstNodeIds; #pragma omp parallel sections { #pragma omp section { SrcNodeIds.Reserve(TotalSrcNodes, TotalSrcNodes); } #pragma omp section { DstNodeIds.Reserve(TotalDstNodes, TotalDstNodes); } } // Find the starting offset of each node (in both src and dst) #pragma omp parallel for schedule(dynamic) for (int t = 0; t < SrcPartCnt+DstPartCnt; t++) { if (t < SrcPartCnt) { TInt i = t; if (SrcOffsets[i] != SrcOffsets[i+1]) { TInt CurrNode = SrcCol1[SrcOffsets[i]]; TInt ThreadOffset = SrcIdOffsets[i]; SrcNodeIds[ThreadOffset] = TIntPr(CurrNode, SrcOffsets[i]); TInt CurrCount = 1; for (TInt j = SrcOffsets[i]+1; j < SrcOffsets[i+1]; j++) { while (j < SrcOffsets[i+1] && SrcCol1[j] == CurrNode) { j++; } if (j < SrcOffsets[i+1]) { CurrNode = SrcCol1[j]; SrcNodeIds[ThreadOffset+CurrCount] = TIntPr(CurrNode, j); CurrCount++; } } } } else { TInt i = t - SrcPartCnt; if (DstOffsets[i] != DstOffsets[i+1]) { TInt CurrNode = DstCol2[DstOffsets[i]]; TInt ThreadOffset = DstIdOffsets[i]; DstNodeIds[ThreadOffset] = TIntPr(CurrNode, DstOffsets[i]); TInt CurrCount = 1; for (TInt j = DstOffsets[i]+1; j < DstOffsets[i+1]; j++) { while (j < DstOffsets[i+1] && DstCol2[j] == CurrNode) { j++; } if (j < DstOffsets[i+1]) { CurrNode = DstCol2[j]; DstNodeIds[ThreadOffset+CurrCount] = TIntPr(CurrNode, j); CurrCount++; } } } } } Sw->Stop(TStopwatch::Group); Sw->Start(TStopwatch::MergeNeighborhoods); // Find the combined neighborhood (both out-neighbors and in-neighbors) of each node TIntTrV Nodes; Nodes.Reserve(TotalSrcNodes+TotalDstNodes); TInt i = 0, j = 0; while (i < TotalSrcNodes && j < TotalDstNodes) { if (SrcNodeIds[i].Val1 == DstNodeIds[j].Val1) { Nodes.Add(TIntTr(SrcNodeIds[i].Val1, i, j)); i++; j++; } else if (SrcNodeIds[i].Val1 < DstNodeIds[j].Val1) { Nodes.Add(TIntTr(SrcNodeIds[i].Val1, i, -1)); i++; } else { Nodes.Add(TIntTr(DstNodeIds[j].Val1, -1, j)); j++; } } for (; i < TotalSrcNodes; i++) { Nodes.Add(TIntTr(SrcNodeIds[i].Val1, i, -1)); } for (; j < TotalDstNodes; j++) { Nodes.Add(TIntTr(DstNodeIds[j].Val1, -1, j)); } Sw->Stop(TStopwatch::MergeNeighborhoods); Sw->Start(TStopwatch::AddNeighborhoods); TInt NumNodes = Nodes.Len(); PGraphMP Graph = PGraphMP::TObj::New(NumNodes, NumRows); // NumThreads = omp_get_max_threads(); // int Delta = (NumNodes+NumThreads-1)/NumThreads; TVec<TIntV> InVV(NumNodes); TVec<TIntV> OutVV(NumNodes); // omp_set_num_threads(NumThreads); #pragma omp parallel for schedule(static,100) for (int m = 0; m < NumNodes; m++) { //double startTr = omp_get_wtime(); //TIntV OutV, InV; TInt n, i, j; Nodes[m].GetVal(n, i, j); if (i >= 0) { TInt Offset = SrcNodeIds[i].GetVal2(); TInt Sz = EdgeCol1.Len()-Offset; if (i < SrcNodeIds.Len()-1) { Sz = SrcNodeIds[i+1].GetVal2()-Offset; } OutVV[m].Reserve(Sz); OutVV[m].CopyUniqueFrom(EdgeCol1, Offset, Sz); } if (j >= 0) { TInt Offset = DstNodeIds[j].GetVal2(); TInt Sz = EdgeCol2.Len()-Offset; if (j < DstNodeIds.Len()-1) { Sz = DstNodeIds[j+1].GetVal2()-Offset; } InVV[m].Reserve(Sz); InVV[m].CopyUniqueFrom(EdgeCol2, Offset, Sz); } Graph->AddNodeWithEdges(n, InVV[m], OutVV[m]); } Graph->SetNodes(NumNodes); Sw->Stop(TStopwatch::AddNeighborhoods); Sw->Start(TStopwatch::AddEdges); omp_set_num_threads(omp_get_max_threads()); if (NodeType == atInt) { #pragma omp parallel for schedule(static) for (int i = 0; i < Partitions.Len(); i++) { TRowIterator RowI(Partitions[i].GetVal1(), Table()); TRowIterator EndI(Partitions[i].GetVal2(), Table()); while (RowI < EndI) { TInt RowId = RowI.GetRowIdx(); // EdgeId TInt SrcId = RowI.GetIntAttr(SrcColIdx); TInt DstId = RowI.GetIntAttr(DstColIdx); Graph->AddEdgeUnchecked(RowId, SrcId, DstId); RowI++; } } } else if (NodeType == atStr) { #pragma omp parallel for schedule(static) for (int i = 0; i < Partitions.Len(); i++) { TRowIterator RowI(Partitions[i].GetVal1(), Table()); TRowIterator EndI(Partitions[i].GetVal2(), Table()); while (RowI < EndI) { TInt RowId = RowI.GetRowIdx(); // EdgeId TInt SrcId = RowI.GetStrMapById(SrcColIdx); TInt DstId = RowI.GetStrMapById(DstColIdx); Graph->AddEdgeUnchecked(RowId, SrcId, DstId); RowI++; } } } Graph->SetEdges(NumRows); Graph->SetMxEId(NumRows); Sw->Stop(TStopwatch::AddEdges); // make single pass over all rows in the table to add attributes for (int CurrRowIdx = 0; CurrRowIdx < (Table->Next).Len(); CurrRowIdx++) { if ((Table->Next)[CurrRowIdx] == Table->Invalid) { continue; } for (TInt ea_i = 0; ea_i < EdgeAttrV.Len(); ea_i++) { TStr ColName = EdgeAttrV[ea_i]; TAttrType T = Table->GetColType(ColName); TInt Index = Table->GetColIdx(ColName); switch (T) { case atInt: Graph->AddIntAttrDatE(CurrRowIdx, Table->IntCols[Index][CurrRowIdx], ColName); break; case atFlt: Graph->AddFltAttrDatE(CurrRowIdx, Table->FltCols[Index][CurrRowIdx], ColName); break; case atStr: Graph->AddStrAttrDatE(CurrRowIdx, Table->GetStrValIdx(Index, CurrRowIdx), ColName); break; } } } // Add node attribtes if (NodeAttrV.Len() > 0) { for (int CurrRowIdx = 0; CurrRowIdx < (NodeTable->Next).Len(); CurrRowIdx++) { if ((NodeTable->Next)[CurrRowIdx] == NodeTable->Invalid) { continue; } TInt NId; if (NodeTypeN == atInt) { NId = (NodeTable->IntCols)[NodeColIdx][CurrRowIdx]; } else if (NodeTypeN == atStr){ NId = (NodeTable->StrColMaps)[NodeColIdx][CurrRowIdx]; } for (TInt i = 0; i < NodeAttrV.Len(); i++) { TStr ColName = NodeAttrV[i]; TAttrType T = NodeTable->GetColType(ColName); TInt Index = NodeTable->GetColIdx(ColName); switch (T) { case atInt: Graph->AddIntAttrDatN(NId, NodeTable->IntCols[Index][CurrRowIdx], ColName); break; case atFlt: Graph->AddFltAttrDatN(NId, NodeTable->FltCols[Index][CurrRowIdx], ColName); break; case atStr: Graph->AddStrAttrDatN(NId, NodeTable->GetStrValIdx(Index, CurrRowIdx), ColName); break; } } } } // double endAdd = omp_get_wtime(); // printf("Add time = %f\n", endAdd-endAlloc); return Graph; } #endif // GCC_ATOMIC }; // TSnap namespace #endif // CONV_H
UnitLocality.h
#ifndef DASH__UTIL__UNIT_LOCALITY_H__INCLUDED #define DASH__UTIL__UNIT_LOCALITY_H__INCLUDED #include <dash/util/Locality.h> #include <dash/util/LocalityDomain.h> #include <dash/util/Config.h> #include <dash/algorithm/internal/String.h> #include <dash/dart/if/dart_types.h> #include <dash/dart/if/dart_locality.h> #include <dash/Exception.h> #include <dash/Team.h> #include <string> #include <vector> #include <unordered_map> #include <utility> #include <iterator> #include <algorithm> namespace dash { namespace util { /** * Wrapper of a single \c dart_unit_locality_t object. */ class UnitLocality { private: typedef UnitLocality self_t; public: UnitLocality( const dash::Team & team, team_unit_t unit) : _team(&team) { DASH_ASSERT_RETURNS( dart_unit_locality( _team->dart_id(), unit, &_unit_locality), DART_OK); dart_domain_locality_t * team_domain; DASH_ASSERT_RETURNS( dart_domain_team_locality( team.dart_id(), ".", &team_domain), DART_OK); DASH_ASSERT_RETURNS( dart_domain_find( team_domain, _unit_locality->domain_tag, &_unit_domain), DART_OK); dart_domain_locality_t * node_locality = _unit_domain; while (node_locality->scope > DART_LOCALITY_SCOPE_NODE) { node_locality = node_locality->parent; } _node_domain = dash::util::LocalityDomain(node_locality); } UnitLocality( global_unit_t unit) : UnitLocality(dash::Team::All(), team_unit_t(unit)) { } UnitLocality() : UnitLocality(dash::Team::All(), dash::Team::All().myid()) { } UnitLocality(const UnitLocality &) = default; UnitLocality & operator=(const UnitLocality &) = default; inline const dart_hwinfo_t & hwinfo() const { DASH_ASSERT(nullptr != _unit_locality); return _unit_locality->hwinfo; } inline dart_hwinfo_t & hwinfo() { DASH_ASSERT(nullptr != _unit_locality); return _unit_locality->hwinfo; } inline dart_domain_locality_t & domain() { DASH_ASSERT(nullptr != _unit_locality); return *_unit_domain; } inline const dart_domain_locality_t & domain() const { DASH_ASSERT(nullptr != _unit_locality); return *_unit_domain; } inline const dash::Team & team() const { if (nullptr == _team) { return dash::Team::Null(); } return *_team; } inline team_unit_t unit_id() const { return nullptr == _unit_locality ? UNDEFINED_TEAM_UNIT_ID : team_unit_t(_unit_locality->unit); } inline dash::util::LocalityDomain & node_domain() { return _node_domain; } inline dash::util::LocalityDomain parent() { return dash::util::LocalityDomain(*_unit_domain->parent); } inline dash::util::LocalityDomain parent_in_scope( dash::util::Locality::Scope scope) { if (scope == dash::util::Locality::Scope::Node) { return node_domain(); } dart_domain_locality_t * parent_domain = _unit_domain; for (int rlevel = _unit_locality->hwinfo.num_scopes; rlevel >= 0; rlevel--) { if (parent_domain == nullptr) { DASH_THROW( dash::exception::InvalidArgument, "Unit domain is undefined"); } if (static_cast<int>(_unit_locality->hwinfo.scopes[rlevel].scope) <= static_cast<int>(scope)) { return dash::util::LocalityDomain(*parent_domain); } parent_domain = parent_domain->parent; } DASH_THROW( dash::exception::InvalidArgument, "Could not find parent domain of unit in scope " << scope); } inline std::string domain_tag() const { DASH_ASSERT(nullptr != _unit_locality); return _unit_domain->domain_tag; } inline std::string host() const { DASH_ASSERT(nullptr != _unit_locality); return _unit_locality->hwinfo.host; } inline void set_domain_tag( const std::string & tag) { strcpy(_unit_domain->domain_tag, tag.c_str()); } inline void set_host( const std::string & hostname) { strcpy(_unit_locality->hwinfo.host, hostname.c_str()); } inline int num_cores() const { DASH_ASSERT(nullptr != _unit_locality); return (_unit_locality->hwinfo.num_cores); } inline int min_threads() { return (_unit_locality == nullptr) ? -1 : std::max<int>(_unit_locality->hwinfo.min_threads, 1); } inline int max_threads() { return (_unit_locality == nullptr) ? -1 : std::max<int>(_unit_locality->hwinfo.max_threads, 1); } inline int num_threads() const { DASH_ASSERT(nullptr != _unit_locality); return (dash::util::Config::get<bool>("DASH_MAX_SMT") ? _unit_locality->hwinfo.max_threads : _unit_locality->hwinfo.min_threads); } inline int num_numa() const { dart_domain_locality_t * dom = _unit_domain; while (dom->scope >= DART_LOCALITY_SCOPE_NUMA) { dom = dom->parent; } return dom->num_domains; } inline int numa_id() const { return (nullptr == _unit_locality ? -1 : _unit_locality->hwinfo.numa_id); } inline int cpu_id() const { return (nullptr == _unit_locality ? -1 : _unit_locality->hwinfo.cpu_id); } inline int cpu_mhz() const { DASH_ASSERT(nullptr != _unit_locality); return (_unit_locality->hwinfo.max_cpu_mhz); } inline int max_shmem_mbps() const { DASH_ASSERT(nullptr != _unit_locality); return (_unit_locality->hwinfo.max_shmem_mbps); } inline int max_cpu_mhz() { return (_unit_locality == nullptr) ? -1 : std::max<int>(_unit_locality->hwinfo.max_cpu_mhz, 1); } inline int min_cpu_mhz() { return (_unit_locality == nullptr) ? -1 : std::max<int>(_unit_locality->hwinfo.min_cpu_mhz, 1); } inline int cache_line_size(int cache_level) { return (_unit_locality == nullptr) ? 64 : std::max<int>( _unit_locality->hwinfo.cache_line_sizes[cache_level], 64); } inline std::string hostname() { return (_unit_locality == nullptr) ? "" : _unit_locality->hwinfo.host; } /** * Number of threads currently available to the active unit. * * The returned value is calculated from unit locality data and hardware * specifications and can, for example, be used to set the \c num_threads * parameter of OpenMP sections: * * \code * #ifdef DASH_ENABLE_OPENMP * auto n_threads = dash::util::Locality::NumUnitDomainThreads(); * if (n_threads > 1) { * #pragma omp parallel num_threads(n_threads) private(t_id) * { * // ... * } * #endif * \endcode * * The following configuration keys affect the number of available * threads: * * - <tt>DASH_DISABLE_THREADS</tt>: * If set, disables multi-threading at unit scope and this method * returns 1. * - <tt>DASH_MAX_SMT</tt>: * If set, virtual SMT CPUs (hyperthreads) instead of physical cores * are used to determine availble threads. * - <tt>DASH_MAX_UNIT_THREADS</tt>: * Specifies the maximum number of threads available to a single * unit. * * Note that these settings may differ between hosts. * * Example for MPI: * * <tt> * mpirun -host node.0 -env DASH_MAX_UNIT_THREADS 4 -n 16 myprogram * : -host node.1 -env DASH_MAX_UNIT_THREADS 2 -n 32 myprogram * </tt> * * The DASH configuration can also be changed at run time with the * \c dash::util::Config interface. * * \see dash::util::Config * \see dash::util::TeamLocality * */ inline int num_domain_threads() { auto n_threads = num_cores(); if (dash::util::Config::get<bool>("DASH_DISABLE_THREADS")) { // Threads disabled in unit scope: n_threads = 1; } else if (dash::util::Config::get<bool>("DASH_MAX_SMT")) { // Configured to use SMT (hyperthreads): n_threads *= max_threads(); } else { // Start one thread on every physical core assigned to this unit: n_threads *= min_threads(); } if (dash::util::Config::is_set("DASH_MAX_UNIT_THREADS")) { n_threads = std::min(dash::util::Config::get<int>( "DASH_MAX_UNIT_THREADS"), n_threads); } return n_threads; } private: const dash::Team * _team = nullptr; dart_unit_locality_t * _unit_locality = nullptr; dart_domain_locality_t * _unit_domain = nullptr; dash::util::LocalityDomain _node_domain; }; // class UnitLocality } // namespace util } // namespace dash #endif // DASH__UTIL__UNIT_LOCALITY_H__INCLUDED
Rasterizer.h
#ifndef RASTERIZER_INCLUDED #define RASTERIZER_INCLUDED #include <vector> #include <omp.h> #include "Util/Geometry.h" #include "SignalProcessing/CubeGrid.h" template< class Real > void Rasterize( Point3D< Real > v1 , CubeGrid< char >& grid , Real scale=Real(1.) ); template< class Real > void Rasterize( Point3D< Real > v1 , Point3D< Real > v2 , CubeGrid< char >& grid , Real scale=Real(1.) ); template< class Real > void Rasterize( Point3D< Real > v1 , Point3D< Real > v2 , Point3D< Real > v3 , CubeGrid< char >& grid , Real scale=Real(1.) ); template< class Real > void Rasterize( const std::vector< Point3D< Real > >& vertices , const std::vector< TriangleIndex >& triangles , CubeGrid< char >& grid , Real scale=Real(1.) , int threads=1 ); template< class Real > void RasterizeEdges( const std::vector< Point3D< Real > >& vertices , const std::vector< TriangleIndex >& triangles , CubeGrid< char >& grid , Real scale=Real(1.) , int threads=1 ); /////////////////////////////// // Rasterization definitions // /////////////////////////////// template< class Real > void Rasterize( const std::vector< Point3D< Real > >& vertices , const std::vector< TriangleIndex >& triangles , CubeGrid< char >& grid , Real scale , int threads ) { if( !grid.resolution() ) { fprintf( stderr , "[WARNING] Cannot rasterize triangles to grid of resolution zero\n" ); return; } #pragma omp parallel for num_threads( threads ) for( int i=0 ; i<triangles.size() ; i++ ) Rasterize< Real >( vertices[ triangles[i][0] ] * Real( grid.resolution() ) , vertices[ triangles[i][1] ] * Real( grid.resolution() ) , vertices[ triangles[i][2] ] * Real( grid.resolution() ) , grid , scale ); } template< class Real > void RasterizeEdges( const std::vector< Point3D< Real > >& vertices , const std::vector< TriangleIndex >& triangles , CubeGrid< char >& grid , Real scale , int threads ) { if( !grid.resolution() ) { fprintf( stderr , "[WARNING] Cannot rasterize triangle edges to grid of resolution zero\n" ); return; } #pragma omp parallel for num_threads( threads ) for( int i=0 ; i<triangles.size() ; i++ ) for( int j=0 ; j<3 ; j++ ) Rasterize< Real >( vertices[ triangles[i][j] ] * Real( grid.resolution() ) , vertices[ triangles[i][(j+1)%3] ] * Real( grid.resolution() ) , grid , scale ); } template< class Real > void Rasterize( Point3D< Real > v1 , Point3D< Real > v2 , Point3D< Real > v3 , CubeGrid< char >& grid , Real scale ) { if( !grid.resolution() ) { fprintf( stderr , "[WARNING] Cannot rasterize triangleto grid of resolution zero\n" ); return; } Point3D< Real > w1 = v2-v1 , w2 = v3-v1; Real l1 = Point3D< Real >::SquareNorm( w1 ) , l2 = Point3D< Real >::SquareNorm( w2 ); if( !l1 && !l2 ) // The triangle is a point Rasterize< Real >( v1 , grid , scale ); else if( !l1 ) // The triangle is the line from v1 to v3 Rasterize< Real >( v1 , v3 , grid , scale ); else if( !l2 ) // The triangle is the line from v1 to v2 Rasterize< Real >( v1 , v2 , grid , scale ); else { w1 /= Real( sqrt( double( l1 ) ) ); Real dot = Point3D< Real >::Dot( w1 , w2 ); Real l = Real( sqrt( l2 - dot*dot ) ); int steps = (int)( l + 3 ); steps = (int)( steps*scale ); for( int i=0 ; i<steps ; i++ ) { Real t = Real(i)/(steps-1); Rasterize< Real >( v2*(1-t) + v1*t , v2*(1-t) + v3*t , grid , scale ); } } } template< class Real > void Rasterize( Point3D< Real > v1 , Point3D< Real > v2 , CubeGrid< char >& grid , Real scale ) { Point3D< Real > w = v2-v1; Real l = Real( sqrt( double( Point3D< Real >::SquareNorm( w ) ) ) ); int steps = (int)( l+3 ); steps = (int)( steps*scale ); for( int i=0 ; i<steps ; i++ ) { Real t = Real(i)/(steps-1); Rasterize< Real >( v1*t + v2*(1-t) , grid ); } } template< class Real > void Rasterize( Point3D< Real > v , CubeGrid< char >& grid , Real scale ) { int x = (int)( v[0]+0.5 ) , y = (int)( v[1]+0.5 ) , z = (int)( v[2]+0.5 ); if( x>=0 && y>=0 && z>=0 && x<grid.resolution() && y<grid.resolution() && z<grid.resolution() ) grid(x,y,z)=1; } #endif // RASTERIZER_INCLUDED
cholesky-no-dependency.c
/* * Cholesky por bloques. */ #include <stdio.h> #include <stdlib.h> #include <math.h> #include "ctimer.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 ); #pragma omp parallel #pragma omp single 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 */ } 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; } for ( i = k + b; i < n; i += b ) { #pragma omp task { m = min( n-i, b ); dtrsm_( "R", "L", "T", "N", &m, &b, &one, &C(k,k), &n, &C(i,k), &n ); } } #pragma omp taskwait for ( i = k + b; i < n; i += b ) { m = min( n-i, b ); for ( j = k + b; j < i ; j += b ) { #pragma omp task dgemm_( "N", "T", &m, &b, &b, &minusone, &C(i,k), &n, &C(j,k), &n, &one, &C(i,j), &n ); } #pragma omp task dsyrk_( "L", "N", &m, &b, &minusone, &C(i,k), &n, &one, &C(i,i), &n ); } #pragma omp taskwait } return 0; }
build_tree.c
/******************************************************************************* * 2pt/build_tree.c: this file is part of the FCFC program. * FCFC: Fast Correlation Function Calculator. * Github repository: https://github.com/cheng-zhao/FCFC * Copyright (c) 2020 -- 2021 Cheng Zhao <zhaocheng03@gmail.com> [MIT license] *******************************************************************************/ #include "define.h" #include "build_tree.h" #include "read_file.h" #include "kdtree.h" #include <stdio.h> /*============================================================================*\ Functions for tree creation and deconstruction \*============================================================================*/ /****************************************************************************** Function `tree_create`: Construct the tree from an input catalogue for pair counting. Arguments: * `conf`: structure for storing configurations; * `cf`: structure for correlation function evaluations; * `idx`: index of the catalogue to be processed; * `type`: type of the tree. Return: Address of the tree on success; NULL on error. ******************************************************************************/ void *tree_create(const CONF *conf, CF *cf, const int idx, const int type) { if (!conf) { P_ERR("configuration parameters are not loaded\n"); return NULL; } if (!cf) { P_ERR("correlation function evaluation has not been initialised\n"); return NULL; } if (idx < 0 || idx > conf->ninput) { P_ERR("unexpected index of the catalog: %d\n", idx); return NULL; } printf("Construct the tree for catalog '%c' ...", cf->label[idx]); if (conf->verbose) printf("\n"); fflush(stdout); /* Read catalogue from file. */ const size_t skip = (conf->skip) ? conf->skip[idx] : DEFAULT_ASCII_SKIP; const char cmt = (conf->comment) ? conf->comment[idx] : DEFAULT_ASCII_COMMENT; const char *wt = (conf->has_wt[idx]) ? conf->wt[idx] : NULL; const char *sel = (conf->sel) ? conf->sel[idx] : NULL; if (sel && ((sel[0] == '\'' && sel[1] == '\'') || (sel[0] == '"' && sel[1] == '"')) && sel[2] == '\0') sel = NULL; if (read_ascii_data(conf->input[idx], skip, cmt, conf->fmtr[idx], conf->pos + idx * 3, wt, sel, cf->data + idx, cf->ndata + idx, conf->verbose)) return NULL; /* Apply coordinate conversion if necessary. */ if ((!conf->cnvt && DEFAULT_COORD_CNVT == true) || (conf->cnvt && conf->cnvt[idx])) { if (cnvt_coord(conf, cf->data[idx], cf->ndata[idx], cf->coord)) return NULL; } /* Precompute the squared distance between tracers and the origin, and compute the total weights if necessary. */ if (cf->wt[idx]) { double sum = 0; #ifdef OMP #pragma omp parallel for reduction(+:sum) #endif for (size_t i = 0; i < cf->ndata[idx]; i++) { cf->data[idx][i].s = cf->data[idx][i].x[0] * cf->data[idx][i].x[0] + cf->data[idx][i].x[1] * cf->data[idx][i].x[1] + cf->data[idx][i].x[2] * cf->data[idx][i].x[2]; sum += cf->data[idx][i].w; } cf->wdata[idx] = sum; } else { #ifdef OMP #pragma omp parallel for #endif for (size_t i = 0; i < cf->ndata[idx]; i++) { cf->data[idx][i].s = cf->data[idx][i].x[0] * cf->data[idx][i].x[0] + cf->data[idx][i].x[1] * cf->data[idx][i].x[1] + cf->data[idx][i].x[2] * cf->data[idx][i].x[2]; } cf->wdata[idx] = (double) cf->ndata[idx]; } /* Construct the tree. */ DATA tmp; void *tree = NULL; int err = 0; switch (type) { case FCFC_TREE_TYPE_KDTREE: tree = kdtree_build(cf->data[idx], cf->ndata[idx], &tmp, &err); if (err) return NULL; if (conf->verbose) printf(" k-D tree constructed for the catalog\n"); break; default: P_ERR("unsupported tree type\n"); return NULL; } printf(FMT_DONE); return tree; } /****************************************************************************** Function `tree_destroy`: Deconstruct a tree used for pair counting. Arguments: * `tree`: address of the tree; * `type`: type of the tree. ******************************************************************************/ void tree_destroy(void *tree, const int type) { if (!tree) return; switch (type) { case FCFC_TREE_TYPE_KDTREE: kdtree_free((KDT *) tree); break; default: P_WRN("unsupported tree type\n"); } }
FourierTransform.h
#pragma once #include <omp.h> #include "ScalarField.h" #include "Grid.h" #include "Enums.h" #ifdef __USE_FFT__ #include "fftw3.h" #endif namespace pfc { namespace fourier_transform { inline Int3 getSizeOfComplexArray(Int3 sizeOfFP) { return Int3(sizeOfFP.x, sizeOfFP.y, sizeOfFP.z / 2 + 1); } enum Direction { RtoC, CtoR }; } class FourierTransformField { #ifdef __USE_FFT__ Int3 size; fftw_plan plans[2]; // RtoC/CtoR ScalarField<FP>* realField; ScalarField<complexFP>* complexField; #endif public: #ifdef __USE_FFT__ FourierTransformField() { plans[fourier_transform::Direction::RtoC] = 0; plans[fourier_transform::Direction::CtoR] = 0; } void initialize(ScalarField<FP>* _realField, ScalarField<complexFP>* _complexField, Int3 _size) { size = _size; realField = _realField; complexField = _complexField; createPlans(); } ~FourierTransformField() { destroyPlans(); } void doDirectFourierTransform() { fftw_execute(plans[fourier_transform::Direction::RtoC]); } void doInverseFourierTransform() { fftw_execute(plans[fourier_transform::Direction::CtoR]); ScalarField<FP>& res = *realField; #pragma omp parallel for for (int i = 0; i < size.x; i++) for (int j = 0; j < size.y; j++) //#pragma omp simd for (int k = 0; k < size.z; k++) res(i, j, k) /= (FP)size.x*size.y*size.z; } #else FourierTransformField() {} void initialize(ScalarField<FP>* _realField, ScalarField<complexFP>* _complexField, Int3 _size) {} void doDirectFourierTransform() {} void doInverseFourierTransform() {} ~FourierTransformField() {} #endif FourierTransformField(ScalarField<FP>* _realField, ScalarField<complexFP>* _complexField, Int3 _size) { initialize(_realField, _complexField, _size); } void doFourierTransform(fourier_transform::Direction direction) { switch (direction) { case fourier_transform::Direction::RtoC: doDirectFourierTransform(); break; case fourier_transform::Direction::CtoR: doInverseFourierTransform(); break; default: break; } } private: #ifdef __USE_FFT__ void createPlans() { int Nx = size.x, Ny = size.y, Nz = size.z; ScalarField<FP>& arrD = *(realField); ScalarField<complexFP>& arrC = *(complexField); #ifdef __USE_OMP__ fftw_plan_with_nthreads(omp_get_max_threads()); #endif plans[fourier_transform::Direction::RtoC] = fftw_plan_dft_r2c_3d(Nx, Ny, Nz, &(arrD(0, 0, 0)), (fftw_complex*)&(arrC(0, 0, 0)), FFTW_ESTIMATE); #ifdef __USE_OMP__ fftw_plan_with_nthreads(omp_get_max_threads()); #endif plans[fourier_transform::Direction::CtoR] = fftw_plan_dft_c2r_3d(Nx, Ny, Nz, (fftw_complex*)&(arrC(0, 0, 0)), &(arrD(0, 0, 0)), FFTW_ESTIMATE); } void destroyPlans() { if (plans[fourier_transform::Direction::RtoC] != 0) fftw_destroy_plan(plans[fourier_transform::Direction::RtoC]); if (plans[fourier_transform::Direction::CtoR] != 0) fftw_destroy_plan(plans[fourier_transform::Direction::CtoR]); } #endif }; class FourierTransformGrid { FourierTransformField transform[3][3]; // field, coordinate public: FourierTransformGrid() {} template<GridTypes gridType> void initialize(Grid<FP, gridType>* gridFP, Grid<complexFP, gridType>* gridCFP) { transform[(int)FieldEnum::E][(int)CoordinateEnum::x].initialize(&gridFP->Ex, &gridCFP->Ex, gridFP->numCells); transform[(int)FieldEnum::E][(int)CoordinateEnum::y].initialize(&gridFP->Ey, &gridCFP->Ey, gridFP->numCells); transform[(int)FieldEnum::E][(int)CoordinateEnum::z].initialize(&gridFP->Ez, &gridCFP->Ez, gridFP->numCells); transform[(int)FieldEnum::B][(int)CoordinateEnum::x].initialize(&gridFP->Bx, &gridCFP->Bx, gridFP->numCells); transform[(int)FieldEnum::B][(int)CoordinateEnum::y].initialize(&gridFP->By, &gridCFP->By, gridFP->numCells); transform[(int)FieldEnum::B][(int)CoordinateEnum::z].initialize(&gridFP->Bz, &gridCFP->Bz, gridFP->numCells); transform[(int)FieldEnum::J][(int)CoordinateEnum::x].initialize(&gridFP->Jx, &gridCFP->Jx, gridFP->numCells); transform[(int)FieldEnum::J][(int)CoordinateEnum::y].initialize(&gridFP->Jy, &gridCFP->Jy, gridFP->numCells); transform[(int)FieldEnum::J][(int)CoordinateEnum::z].initialize(&gridFP->Jz, &gridCFP->Jz, gridFP->numCells); } void doDirectFourierTransform(FieldEnum field, CoordinateEnum coord) { transform[(int)field][(int)coord].doDirectFourierTransform(); } void doInverseFourierTransform(FieldEnum field, CoordinateEnum coord) { transform[(int)field][(int)coord].doInverseFourierTransform(); } void doFourierTransform(FieldEnum field, CoordinateEnum coord, fourier_transform::Direction direction) { transform[(int)field][(int)coord].doFourierTransform(direction); } }; }
GB_binop__lt_bool.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__lt_bool) // A.*B function (eWiseMult): GB (_AemultB_08__lt_bool) // A.*B function (eWiseMult): GB (_AemultB_02__lt_bool) // A.*B function (eWiseMult): GB (_AemultB_04__lt_bool) // A.*B function (eWiseMult): GB (_AemultB_bitmap__lt_bool) // A*D function (colscale): GB (_AxD__lt_bool) // D*A function (rowscale): GB (_DxB__lt_bool) // C+=B function (dense accum): GB (_Cdense_accumB__lt_bool) // C+=b function (dense accum): GB (_Cdense_accumb__lt_bool) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__lt_bool) // C=scalar+B GB (_bind1st__lt_bool) // C=scalar+B' GB (_bind1st_tran__lt_bool) // C=A+scalar GB (_bind2nd__lt_bool) // C=A'+scalar GB (_bind2nd_tran__lt_bool) // C type: bool // A type: bool // A pattern? 0 // B type: bool // B pattern? 0 // BinaryOp: cij = (aij < bij) #define GB_ATYPE \ bool #define GB_BTYPE \ bool #define GB_CTYPE \ bool // 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) \ bool 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) \ bool 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) \ bool 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_LT || GxB_NO_BOOL || GxB_NO_LT_BOOL) //------------------------------------------------------------------------------ // 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__lt_bool) ( 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__lt_bool) ( 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__lt_bool) ( 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 bool bool bwork = (*((bool *) 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__lt_bool) ( 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 bool *restrict Cx = (bool *) 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__lt_bool) ( GrB_Matrix C, const GrB_Matrix D, const GrB_Matrix B, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else bool *restrict Cx = (bool *) 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__lt_bool) ( 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) ; bool alpha_scalar ; bool beta_scalar ; if (is_eWiseUnion) { alpha_scalar = (*((bool *) alpha_scalar_in)) ; beta_scalar = (*((bool *) 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__lt_bool) ( 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__lt_bool) ( 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__lt_bool) ( 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__lt_bool) ( 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__lt_bool) ( 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 bool *Cx = (bool *) Cx_output ; bool x = (*((bool *) x_input)) ; bool *Bx = (bool *) 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 ; bool 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__lt_bool) ( 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 ; bool *Cx = (bool *) Cx_output ; bool *Ax = (bool *) Ax_input ; bool y = (*((bool *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; bool 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) \ { \ bool aij = GBX (Ax, pA, false) ; \ Cx [pC] = (x < aij) ; \ } GrB_Info GB (_bind1st_tran__lt_bool) ( 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 \ bool #if GB_DISABLE return (GrB_NO_VALUE) ; #else bool x = (*((const bool *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ bool } //------------------------------------------------------------------------------ // 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) \ { \ bool aij = GBX (Ax, pA, false) ; \ Cx [pC] = (aij < y) ; \ } GrB_Info GB (_bind2nd_tran__lt_bool) ( 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 bool y = (*((const bool *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
softmax-inl.h
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * Copyright (c) 2017 by Contributors * \file softmax-inl.h * \brief */ #ifndef MXNET_OPERATOR_NN_SOFTMAX_INL_H_ #define MXNET_OPERATOR_NN_SOFTMAX_INL_H_ #include <algorithm> #include <string> #include <utility> #include <vector> #include <type_traits> #include "../mxnet_op.h" #include "../operator_common.h" #include "../tensor/broadcast_reduce_op.h" #include "../../common/cuda_utils.h" namespace mxnet { namespace op { namespace mxnet_op { struct softmax_fwd { template<typename AType> MSHADOW_XINLINE static AType Map(float a, AType b) { return AType(expf(a)/b); } template<typename AType> MSHADOW_XINLINE static AType Map(double a, AType b) { return AType(exp(a)/b); } }; struct log_softmax_fwd { template<typename DType> MSHADOW_XINLINE static float Map(DType a, float b) { return a - logf(b); } template<typename DType> MSHADOW_XINLINE static double Map(DType a, double b) { return a - log(b); } }; template<typename OP, bool negate, typename AType, typename DType, typename OType, typename IType, int ndim> inline void Softmax(Stream<cpu> *s, DType *in, OType *out, IType *length, Shape<ndim> shape, int axis, const DType temperature) { index_t M = shape[axis]; index_t N = shape.Size()/M; Shape<ndim> stride = calc_stride(shape); Shape<ndim> sshape = shape; sshape[axis] = 1; index_t sa = stride[axis]; if (length == nullptr) { #pragma omp parallel for for (index_t i = 0; i < N; ++i) { index_t base = unravel_dot(i, sshape, stride); DType mmax = negate ? -in[base] : in[base]; DType val; for (index_t j = 1; j < M; ++j) { val = negate ? -in[base + j*sa] : in[base + j*sa]; if (mmax < val) mmax = val; } AType sum = AType(0); DType in_val; // By default temperature is 1.0. // Adding a branch here to save the CPU 'divide-by-1' computation at runtime if (temperature == 1.0) { for (index_t j = 0; j < M; ++j) { in_val = negate ? -in[base + j*sa] : in[base + j*sa]; sum += std::exp(in_val - mmax); } for (index_t j = 0; j < M; ++j) { in_val = negate ? -in[base + j*sa] : in[base + j*sa]; out[base + j*sa] = OP::Map(in_val - mmax, sum); } } else { for (index_t j = 0; j < M; ++j) { in_val = negate ? -in[base + j*sa] : in[base + j*sa]; sum += std::exp((in_val - mmax)/temperature); } for (index_t j = 0; j < M; ++j) { in_val = negate ? -in[base + j*sa] : in[base + j*sa]; out[base + j*sa] = OP::Map((in_val - mmax)/temperature, sum); } } } } else { #pragma omp parallel for for (index_t i = 0; i < N; ++i) { index_t len = static_cast<index_t>(length[i]); index_t base = unravel_dot(i, sshape, stride); DType mmax = negate ? -in[base] : in[base]; DType val; for (index_t j = 1; j < len; ++j) { val = negate ? -in[base + j*sa] : in[base + j*sa]; if (mmax < val) mmax = val; } for (index_t j = len; j < M; ++j) { out[base + j*sa] = OType(0.0f); } AType sum = AType(0); DType in_val; // By default temperature is 1.0. // Adding a branch here to save the CPU 'divide-by-1' computation at runtime if (temperature == 1.0) { for (index_t j = 0; j < len; ++j) { in_val = negate ? -in[base + j*sa] : in[base + j*sa]; sum += std::exp(in_val - mmax); } for (index_t j = 0; j < len; ++j) { in_val = negate ? -in[base + j*sa] : in[base + j*sa]; out[base + j*sa] = OP::Map(in_val - mmax, sum); } } else { for (index_t j = 0; j < len; ++j) { in_val = negate ? -in[base + j*sa] : in[base + j*sa]; sum += std::exp((in_val - mmax)/temperature); } for (index_t j = 0; j < len; ++j) { in_val = negate ? -in[base + j*sa] : in[base + j*sa]; out[base + j*sa] = OP::Map((in_val - mmax)/temperature, sum); } } } } } struct softmax_bwd { template<typename DType, typename AType> MSHADOW_XINLINE static AType Map(DType ograd, DType out, AType sum) { return AType(out * (ograd - sum)); } }; struct log_softmax_bwd { template<typename AType> MSHADOW_XINLINE static AType Map(float ograd, float out, AType sum) { return AType(ograd - expf(out)*sum); } template<typename AType> MSHADOW_XINLINE static AType Map(double ograd, double out, AType sum) { return AType(ograd - exp(out)*sum); } }; template<typename OP1, typename OP2, int Req, bool negate, typename AType, typename DType, typename OType, typename IType, int ndim> inline void SoftmaxGrad(Stream<cpu> *s, OType *out, OType *ograd, DType *igrad, IType *length, Shape<ndim> shape, int axis, const DType temperature) { index_t M = shape[axis]; index_t N = shape.Size()/M; Shape<ndim> stride = calc_stride(shape); Shape<ndim> sshape = shape; sshape[axis] = 1; index_t sa = stride[axis]; if (length != nullptr) { #pragma omp parallel for for (index_t i = 0; i < N; ++i) { index_t base = unravel_dot(i, sshape, stride); index_t len = static_cast<index_t>(length[i]); AType sum = AType(0); for (index_t j = 0; j < len; ++j) { sum += OP1::Map(ograd[base + j*sa], out[base + j*sa]); } // By default temperature is 1.0. // Adding a branch here to save the CPU 'divide-by-1' computation at runtime DType final_result; if (temperature == 1.0) { for (index_t j = 0; j < M; ++j) { final_result = negate ? -OP2::Map(ograd[base + j*sa], out[base + j*sa], sum) : OP2::Map(ograd[base + j*sa], out[base + j*sa], sum); final_result = (j < len) ? final_result : DType(0.0f); KERNEL_ASSIGN(igrad[base + j*sa], Req, final_result); } } else { for (index_t j = 0; j < M; ++j) { final_result = negate ? -OP2::Map(ograd[base + j*sa], out[base + j*sa], sum) / temperature : OP2::Map(ograd[base + j*sa], out[base + j*sa], sum) / temperature; final_result = (j < len) ? final_result : DType(0.0f); KERNEL_ASSIGN(igrad[base + j*sa], Req, final_result); } } } } else { #pragma omp parallel for for (index_t i = 0; i < N; ++i) { index_t base = unravel_dot(i, sshape, stride); AType sum = AType(0); for (index_t j = 0; j < M; ++j) { sum += OP1::Map(ograd[base + j*sa], out[base + j*sa]); } // By default temperature is 1.0. // Adding a branch here to save the CPU 'divide-by-1' computation at runtime DType final_result; if (temperature == 1.0) { for (index_t j = 0; j < M; ++j) { final_result = negate ? -OP2::Map(ograd[base + j*sa], out[base + j*sa], sum) : OP2::Map(ograd[base + j*sa], out[base + j*sa], sum); KERNEL_ASSIGN(igrad[base + j*sa], Req, final_result); } } else { for (index_t j = 0; j < M; ++j) { final_result = negate ? -OP2::Map(ograd[base + j*sa], out[base + j*sa], sum) / temperature : OP2::Map(ograd[base + j*sa], out[base + j*sa], sum) / temperature; KERNEL_ASSIGN(igrad[base + j*sa], Req, final_result); } } } } } #ifdef __CUDACC__ template<int x_bits, typename OP, bool negate, typename AType, int ndim, typename DType, typename OType, typename IType> __global__ void softmax_compute_kernel(DType *in, OType *out, IType *length, index_t M, int axis, Shape<ndim> sshape, Shape<ndim> stride, const double temperature) { const unsigned x_size = 1 << x_bits; __shared__ AType smem[x_size]; index_t sa = stride[axis]; index_t base = unravel_dot(blockIdx.x, sshape, stride); index_t x = threadIdx.x; const index_t len = length == nullptr ? M : static_cast<index_t>(length[blockIdx.x]); red::maximum::SetInitValue(smem[x]); for (index_t i = x; i < len; i += x_size) { smem[x] = ::max(smem[x], negate ? -in[base + i*sa] : in[base + i*sa]); } __syncthreads(); cuda::Reduce1D<red::maximum, x_bits>(smem); __syncthreads(); DType smax = smem[0]; __syncthreads(); red::sum::SetInitValue(smem[x]); DType val; for (index_t i = x; i < len; i += x_size) { val = negate ? -in[base + i*sa]:in[base + i*sa]; smem[x] += static_cast<AType>(expf((val - smax) / static_cast<AType>(temperature))); } __syncthreads(); cuda::Reduce1D<red::sum, x_bits>(smem); __syncthreads(); AType ssum = smem[0]; __syncthreads(); for (index_t i = x; i < M; i += x_size) { val = negate ? -in[base + i*sa] : in[base + i*sa]; out[base + i*sa] = (i < len) ? OType(OP::Map((val - smax)/static_cast<DType>(temperature), ssum)) : OType(0.0f); } } const int softmax_threads_per_block = 512; template<typename OP, bool negate, typename AType, typename LType, typename DType, typename OType, typename IType> __global__ void softmax_stride1_compute_kernel(const DType *in, OType *out, IType *length, const index_t M, const double temperature, const int rows_per_block, const index_t total_rows) { __shared__ AType scratch[softmax_threads_per_block]; __shared__ LType persistent_storage[20 * 1024 / sizeof(LType)]; const int warp_size = 32; const int threads_per_row = softmax_threads_per_block / rows_per_block; const int my_local_row = threadIdx.x / threads_per_row; const int my_row = blockIdx.x * rows_per_block + my_local_row; if (my_row >= total_rows) return; const int my_id = threadIdx.x % threads_per_row; const int entries_per_load = sizeof(LType)/sizeof(DType); const index_t len = length == nullptr ? M : static_cast<index_t>(length[my_row]); // Due to usage of MSHADOW_TYPE_SWITCH macro we are generating // kernels where sizeof(LType) may be less than sizeof(DType), // resulting in entries_per_load being 0. // This is not a valid combination and is being checked against // in the launcher code. This switch here is just to silence // the division by zero warning generated for such invalid cases. const int row_length = entries_per_load > 0 ? M / entries_per_load : 0; const LType* in_aligned = reinterpret_cast<const LType*>(in); size_t base = my_row * row_length; for (index_t i = my_id; i < row_length; i += threads_per_row) { persistent_storage[my_local_row * row_length + i] = in_aligned[base + i]; } DType * row = reinterpret_cast<DType *>(persistent_storage + my_local_row * row_length); __syncthreads(); DType my_max_value; red::maximum::SetInitValue(my_max_value); for (index_t i = my_id; i < len; i += threads_per_row) { my_max_value = ::max(my_max_value, negate ? -row[i] : row[i]); } scratch[threadIdx.x] = my_max_value; __syncthreads(); for (int size = threads_per_row / 2; size >= warp_size; size /= 2) { if (my_id < size) { scratch[threadIdx.x] = ::max(scratch[threadIdx.x], scratch[threadIdx.x + size]); } __syncthreads(); } if (my_id < warp_size) { AType my_value = warp_reduce(scratch[threadIdx.x], [](AType x, AType y) { return ::max(x, y); }); scratch[threadIdx.x] = my_value; } __syncthreads(); DType smax = scratch[threadIdx.x - threadIdx.x % threads_per_row]; __syncthreads(); AType my_sum; red::sum::SetInitValue(my_sum); for (index_t i = my_id; i < len; i += threads_per_row) { const DType val = negate ? -row[i] : row[i]; my_sum += static_cast<AType>(expf((val - smax) / static_cast<AType>(temperature))); } scratch[threadIdx.x] = my_sum; __syncthreads(); for (int size = threads_per_row / 2; size >= warp_size; size /= 2) { if (my_id < size) { scratch[threadIdx.x] += scratch[threadIdx.x + size]; } __syncthreads(); } if (my_id < warp_size) { AType my_value = warp_reduce(scratch[threadIdx.x], [](AType x, AType y) { return x + y;}); scratch[threadIdx.x] = my_value; } __syncthreads(); AType ssum = scratch[threadIdx.x - threadIdx.x % threads_per_row]; __syncthreads(); for (index_t i = my_id; i < M; i += threads_per_row) { const DType val = negate ? -row[i] : row[i]; row[i] = (i < len) ? DType(OP::Map((val - smax)/static_cast<DType>(temperature), ssum)) : DType(0.0f); } __syncthreads(); LType* out_aligned = reinterpret_cast<LType*>(out); for (index_t i = my_id; i < row_length; i += threads_per_row) { out_aligned[base + i] = persistent_storage[my_local_row * row_length + i]; } } template<typename OP, bool negate, typename AType, typename DType, typename OType, typename IType, int ndim> inline void Softmax(Stream<gpu> *s, DType *in, OType *out, IType *length, Shape<ndim> shape, int axis, const double temperature) { const int x_bits = 7; const int x_size = 1 << x_bits; index_t M = shape[axis]; index_t N = shape.Size()/M; Shape<ndim> stride = calc_stride(shape); Shape<ndim> sshape = shape; sshape[axis] = 1; const size_t DSize = sizeof(DType); // Using 20 kB of shared memory for persistent storage in the optimized case const size_t max_opt_M = 20 * 1024 / DSize; if (stride[axis] == 1 && static_cast<size_t>(M) <= max_opt_M && std::is_same<DType, OType>::value) { int ltype = mxnet::common::cuda::get_load_type(M * sizeof(DType)); MXNET_LOAD_TYPE_SWITCH(ltype, LType, { int rows_per_block = mxnet::common::cuda::get_rows_per_block(M * sizeof(DType) / sizeof(LType), softmax_threads_per_block); int nblocks = (N + rows_per_block - 1) / rows_per_block; CHECK_LE(sizeof(DType), sizeof(LType)); softmax_stride1_compute_kernel<OP, negate, AType, LType> <<<nblocks, softmax_threads_per_block, 0, mshadow::Stream<gpu>::GetStream(s)>>>( in, out, length, M, temperature, rows_per_block, N); }); MSHADOW_CUDA_POST_KERNEL_CHECK(softmax_stride1_compute_kernel); } else { softmax_compute_kernel<x_bits, OP, negate, AType, ndim> <<<N, x_size, 0, mshadow::Stream<gpu>::GetStream(s)>>>( in, out, length, M, axis, sshape, stride, temperature); MSHADOW_CUDA_POST_KERNEL_CHECK(softmax_compute_kernel); } } template<typename OP1, typename OP2, int Req, bool negate, typename AType, typename LType, typename DType, typename OType, typename IType> __global__ void softmax_stride1_grad_kernel(const OType *out, const OType *ograd, DType *igrad, const IType *length, const index_t M, const double temperature, const int rows_per_block, const index_t total_rows) { __shared__ AType scratch[softmax_threads_per_block]; __shared__ LType persistent_storage[20 * 1024 / sizeof(LType)]; const int warp_size = 32; const int threads_per_row = softmax_threads_per_block / rows_per_block; const int my_local_row = threadIdx.x / threads_per_row; const int my_row = blockIdx.x * rows_per_block + my_local_row; if (my_row >= total_rows) return; const int my_id = threadIdx.x % threads_per_row; const int entries_per_load = sizeof(LType)/sizeof(DType); const index_t len = length == nullptr ? M : static_cast<index_t>(length[my_row]); // Due to usage of MSHADOW_TYPE_SWITCH macro we are generating // kernels where sizeof(LType) may be less than sizeof(DType), // resulting in entries_per_load being 0. // This is not a valid combination and is being checked against // in the launcher code. This switch here is just to silence // the division by zero warning generated for such invalid cases. const int row_length = entries_per_load > 0 ? M / entries_per_load : 0; const LType* out_aligned = reinterpret_cast<const LType*>(out); const LType* ograd_aligned = reinterpret_cast<const LType*>(ograd); size_t base = my_row * row_length; for (index_t i = my_id; i < row_length; i += threads_per_row) { persistent_storage[my_local_row * row_length * 2 + i] = out_aligned[base + i]; persistent_storage[my_local_row * row_length * 2 + row_length + i] = ograd_aligned[base + i]; } DType * row = reinterpret_cast<DType *>(persistent_storage + my_local_row * row_length * 2); __syncthreads(); AType my_sum_value; red::sum::SetInitValue(my_sum_value); for (index_t i = my_id; i < len; i += threads_per_row) { my_sum_value += OP1::Map(row[i + M], row[i]); } scratch[threadIdx.x] = my_sum_value; __syncthreads(); for (int size = threads_per_row / 2; size >= warp_size; size /= 2) { if (my_id < size) { scratch[threadIdx.x] = scratch[threadIdx.x] + scratch[threadIdx.x + size]; } __syncthreads(); } if (my_id < warp_size) { AType my_value = warp_reduce(scratch[threadIdx.x], [](AType x, AType y) { return x + y; }); scratch[threadIdx.x] = my_value; } __syncthreads(); AType ssum = scratch[threadIdx.x - threadIdx.x % threads_per_row]; __syncthreads(); for (index_t i = my_id; i < M; i += threads_per_row) { const DType val = negate ? -OP2::Map(row[i + M], row[i], ssum) : OP2::Map(row[i + M], row[i], ssum); row[i] = (i < len) ? DType(val / static_cast<DType>(temperature)) : DType(0.0f); if (Req == kAddTo) { row[i] += igrad[my_row * M + i]; } } __syncthreads(); LType* igrad_aligned = reinterpret_cast<LType*>(igrad); for (index_t i = my_id; i < row_length; i += threads_per_row) { igrad_aligned[base + i] = persistent_storage[my_local_row * row_length * 2 + i]; } } template<int x_bits, typename OP1, typename OP2, int Req, bool negate, typename AType, int ndim, typename DType, typename OType, typename IType> __global__ void softmax_grad_kernel(OType *out, OType *ograd, DType *igrad, const IType *length, index_t M, int axis, Shape<ndim> sshape, Shape<ndim> stride, const double temperature) { const unsigned x_size = 1 << x_bits; __shared__ AType smem[x_size]; index_t sa = stride[axis]; index_t base = unravel_dot(blockIdx.x, sshape, stride); index_t x = threadIdx.x; index_t len = length != nullptr ? static_cast<index_t>(length[blockIdx.x]) : M; red::sum::SetInitValue(smem[x]); for (index_t i = x; i < len; i += x_size) { smem[x] += OP1::Map(ograd[base + i*sa], out[base + i*sa]); } __syncthreads(); cuda::Reduce1D<red::sum, x_bits>(smem); __syncthreads(); AType ssum = smem[0]; __syncthreads(); DType final_result; for (index_t i = x; i < M; i += x_size) { final_result = negate ? -OP2::Map(ograd[base + i*sa], out[base + i*sa], ssum) : OP2::Map(ograd[base + i*sa], out[base + i*sa], ssum); final_result = (i < len) ? final_result : DType(0.0f); KERNEL_ASSIGN(igrad[base + i*sa], Req, final_result / static_cast<DType>(temperature)); } } template<typename OP1, typename OP2, int Req, bool negate, typename AType, int ndim, typename DType, typename OType, typename IType> inline void SoftmaxGrad(Stream<gpu> *s, OType *out, OType *ograd, DType *igrad, IType *length, Shape<ndim> shape, int axis, const double temperature) { const int x_bits = 7; const int x_size = 1 << x_bits; index_t M = shape[axis]; index_t N = shape.Size()/M; Shape<ndim> stride = calc_stride(shape); Shape<ndim> sshape = shape; sshape[axis] = 1; const size_t DSize = sizeof(DType); // Using 20 kB of shared memory for persistent storage in the optimized case // Need to store both out and ograd, so M can be only half compared to // forward pass. const size_t max_opt_M = 20 * 1024 / DSize / 2; if (stride[axis] == 1 && static_cast<size_t>(M) <= max_opt_M && std::is_same<DType, OType>::value) { int ltype = mxnet::common::cuda::get_load_type(M * sizeof(DType)); MXNET_LOAD_TYPE_SWITCH(ltype, LType, { int rows_per_block = mxnet::common::cuda::get_rows_per_block(M * sizeof(DType) / sizeof(LType), softmax_threads_per_block); int nblocks = (N + rows_per_block - 1) / rows_per_block; CHECK_LE(sizeof(DType), sizeof(LType)); softmax_stride1_grad_kernel<OP1, OP2, Req, negate, AType, LType> <<<nblocks, softmax_threads_per_block, 0, mshadow::Stream<gpu>::GetStream(s)>>>( out, ograd, igrad, length, M, temperature, rows_per_block, N); }); MSHADOW_CUDA_POST_KERNEL_CHECK(softmax_stride1_grad_kernel); } else { softmax_grad_kernel<x_bits, OP1, OP2, Req, negate, AType, ndim> <<<N, x_size, 0, mshadow::Stream<gpu>::GetStream(s)>>>( out, ograd, igrad, length, M, axis, sshape, stride, temperature); MSHADOW_CUDA_POST_KERNEL_CHECK(softmax_grad_kernel); } } #endif } // namespace mxnet_op struct SoftmaxParam : public dmlc::Parameter<SoftmaxParam> { int axis; dmlc::optional<double> temperature; dmlc::optional<int> dtype; dmlc::optional<bool> use_length; DMLC_DECLARE_PARAMETER(SoftmaxParam) { DMLC_DECLARE_FIELD(axis).set_default(-1) .describe("The axis along which to compute softmax."); DMLC_DECLARE_FIELD(temperature).set_default(dmlc::optional<double>()) .describe("Temperature parameter in softmax"); DMLC_DECLARE_FIELD(dtype) .add_enum("float16", mshadow::kFloat16) .add_enum("float32", mshadow::kFloat32) .add_enum("float64", mshadow::kFloat64) .set_default(dmlc::optional<int>()) .describe("DType of the output in case this can't be inferred. " "Defaults to the same as input's dtype if not defined (dtype=None)."); DMLC_DECLARE_FIELD(use_length) .set_default(dmlc::optional<bool>(false)) .describe("Whether to use the length input as a mask over the data input."); } bool operator==(const SoftmaxParam& other) const { return this->axis == other.axis && this->temperature == other.temperature && this->dtype == other.dtype && this->use_length == other.use_length; } }; static inline bool softmax_has_dtype_override(const nnvm::NodeAttrs& attrs) { const SoftmaxParam& param = nnvm::get<SoftmaxParam>(attrs.parsed); return param.dtype.has_value() && param.dtype.value() != -1; } static inline bool softmax_use_length(const nnvm::NodeAttrs& attrs) { const SoftmaxParam& param = nnvm::get<SoftmaxParam>(attrs.parsed); return param.use_length.value(); } static inline bool SoftmaxOpType(const nnvm::NodeAttrs& attrs, std::vector<int>* in_attrs, std::vector<int>* out_attrs) { CHECK_EQ(out_attrs->size(), 1); const SoftmaxParam& param = nnvm::get<SoftmaxParam>(attrs.parsed); CHECK_EQ(in_attrs->size(), softmax_use_length(attrs) ? 2U : 1U); if (softmax_has_dtype_override(attrs)) { TYPE_ASSIGN_CHECK(*out_attrs, 0, param.dtype.value()); type_assign(&(*in_attrs)[0], (*out_attrs)[0]); return true; } else { std::vector<int> tmp = {in_attrs->at(0)}; return ElemwiseType<1, 1>(attrs, &tmp, out_attrs); } } static inline bool SoftmaxOpShape(const nnvm::NodeAttrs& attrs, mxnet::ShapeVector *in_attrs, mxnet::ShapeVector *out_attrs) { CHECK_EQ(out_attrs->size(), 1U); const SoftmaxParam& param = nnvm::get<SoftmaxParam>(attrs.parsed); CHECK_EQ(in_attrs->size(), param.use_length.value() ? 2U : 1U); if (param.use_length.value()) { mxnet::TShape& dshape = in_attrs->at(0); mxnet::TShape tmp_shape((dshape.ndim() == 1) ? 1U : dshape.ndim() - 1, 1); int j = 0; int axis = param.axis != -1 ? param.axis : dshape.ndim() - 1; for (int i = 0; i < dshape.ndim(); ++i) { if (i != axis) { tmp_shape[j++] = dshape[i]; } } SHAPE_ASSIGN_CHECK(*in_attrs, 1, tmp_shape); } mxnet::ShapeVector tmp = {in_attrs->at(0)}; return ElemwiseShape<1, 1>(attrs, &tmp, out_attrs); } static inline bool SoftmaxGradOpShape(const nnvm::NodeAttrs& attrs, mxnet::ShapeVector *in_attrs, mxnet::ShapeVector *out_attrs) { if (softmax_has_dtype_override(attrs) || softmax_use_length(attrs)) { if (softmax_use_length(attrs)) { mxnet::ShapeVector ins = {in_attrs->at(0), in_attrs->at(1), in_attrs->at(3)}; mxnet::ShapeVector dgrad = {out_attrs->at(0)}; bool res = ElemwiseShape<3, 1>(attrs, &ins, &dgrad); SHAPE_ASSIGN_CHECK(*in_attrs, 0, ins[0]); SHAPE_ASSIGN_CHECK(*in_attrs, 1, ins[1]); SHAPE_ASSIGN_CHECK(*in_attrs, 3, ins[2]); SHAPE_ASSIGN_CHECK(*out_attrs, 0, dgrad[0]); mxnet::ShapeVector length = {in_attrs->at(2)}; mxnet::ShapeVector lgrad = {out_attrs->at(1)}; res = (res && ElemwiseShape<1, 1>(attrs, &length, &lgrad)); SHAPE_ASSIGN_CHECK(*in_attrs, 2, length[0]); SHAPE_ASSIGN_CHECK(*out_attrs, 1, lgrad[0]); return res; } else { return ElemwiseShape<3, 1>(attrs, in_attrs, out_attrs); } } else { return ElemwiseShape<2, 1>(attrs, in_attrs, out_attrs); } } static inline bool SoftmaxGradOpType(const nnvm::NodeAttrs& attrs, std::vector<int>* in_attrs, std::vector<int>* out_attrs) { CHECK_EQ(out_attrs->size(), softmax_use_length(attrs) ? 2U : 1U); if (softmax_has_dtype_override(attrs) || softmax_use_length(attrs)) { CHECK_EQ(in_attrs->size(), softmax_use_length(attrs) ? 4U : 3U); int in_dtype = (*in_attrs)[1]; int out_dtype = (*in_attrs)[softmax_use_length(attrs) ? 3 : 2]; TYPE_ASSIGN_CHECK(*in_attrs, 0, out_dtype); TYPE_ASSIGN_CHECK(*out_attrs, 0, in_dtype); if (softmax_use_length(attrs)) { TYPE_ASSIGN_CHECK(*out_attrs, 1, in_attrs->at(2)); } return (*out_attrs)[0] != -1 && (*in_attrs)[0] != -1 && (!softmax_use_length(attrs) || ((*out_attrs)[1] != -1 && (*in_attrs)[1] != -1)); } else { CHECK_EQ(in_attrs->size(), 2U); int out_dtype = (*in_attrs)[1]; TYPE_ASSIGN_CHECK(*out_attrs, 0, out_dtype); TYPE_ASSIGN_CHECK(*in_attrs, 0, out_dtype); return (*out_attrs)[0] != -1 && (*in_attrs)[0] != -1; } } static inline std::vector<std::pair<int, int> > SoftmaxGradOpInplaceOption(const nnvm::NodeAttrs& attrs) { if (softmax_has_dtype_override(attrs) || softmax_use_length(attrs)) { if (softmax_use_length(attrs)) { return std::vector<std::pair<int, int> >{{0, 0}, {1, 0}, {2, 1}, {3, 0}}; } else { return std::vector<std::pair<int, int> >{{0, 0}, {1, 0}, {2, 0}}; } } else { return std::vector<std::pair<int, int> >{{0, 0}, {1, 0}}; } } static inline uint32_t SoftmaxGradOpNumInputs(const nnvm::NodeAttrs& attrs) { if (softmax_has_dtype_override(attrs) || softmax_use_length(attrs)) { return softmax_use_length(attrs) ? 4 : 3; } return 2; } static inline std::vector<std::string> SoftmaxGradOpInputNames(const nnvm::NodeAttrs& attrs) { if (softmax_has_dtype_override(attrs) || softmax_use_length(attrs)) { if (softmax_use_length(attrs)) { return std::vector<std::string>{"ograd", "data", "length", "output"}; } else { return std::vector<std::string>{"ograd", "data", "output"}; } } else { return std::vector<std::string>{"ograd", "output"}; } } struct SoftmaxFGradient { const char *op_name; std::vector<nnvm::NodeEntry> operator()(const nnvm::ObjectPtr& n, const std::vector<nnvm::NodeEntry>& ograds) const { if (softmax_has_dtype_override(n->attrs) || softmax_use_length(n->attrs)) { return ElemwiseGradUseInOut {op_name}(n, ograds); } else { return ElemwiseGradUseOut {op_name}(n, ograds); } } }; template<typename xpu, typename OP, bool negate = false> void SoftmaxCompute(const nnvm::NodeAttrs& attrs, const OpContext& ctx, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs) { using namespace mxnet_op; if (req[0] == kNullOp) return; CHECK_NE(req[0], kAddTo); const SoftmaxParam& param = nnvm::get<SoftmaxParam>(attrs.parsed); int axis = CheckAxis(param.axis, inputs[0].ndim()); const double temperature = param.temperature.has_value() ? param.temperature.value() : 1.0; mxnet::TShape shape = AxisShapeCompact(inputs[0].shape_, &axis, true); bool safe_acc = dmlc::GetEnv("MXNET_SAFE_ACCUMULATION", false); if (!safe_acc && inputs[0].type_flag_ == mshadow::kFloat16) { common::LogOnce("MXNET_SAFE_ACCUMULATION=1 is recommended for softmax with float16 inputs. " "See https://mxnet.apache.org/api/faq/env_var " "for more details."); } MXNET_REAL_ACC_TYPE_SWITCH(inputs[0].type_flag_, DType, AType, { MSHADOW_REAL_TYPE_SWITCH(outputs[0].type_flag_, OType, { int type = kInt32; if (param.use_length.value()) { CHECK(inputs.size() > 1) << "Mask needs to be provided when using softmax with use_length=True."; type = inputs[1].type_flag_; } MXNET_INT32_INT64_TYPE_SWITCH(type, IType, { IType* mask_ptr = nullptr; if (param.use_length.value()) { mask_ptr = inputs[1].dptr<IType>(); } if (safe_acc) { if (shape.ndim() == 2) { Softmax<OP, negate, AType>( ctx.get_stream<xpu>(), inputs[0].dptr<DType>(), outputs[0].dptr<OType>(), mask_ptr, shape.get<2>(), axis, static_cast<DType>(temperature)); } else { Softmax<OP, negate, AType>( ctx.get_stream<xpu>(), inputs[0].dptr<DType>(), outputs[0].dptr<OType>(), mask_ptr, shape.get<3>(), axis, static_cast<DType>(temperature)); } } else { if (shape.ndim() == 2) { Softmax<OP, negate, DType>( ctx.get_stream<xpu>(), inputs[0].dptr<DType>(), outputs[0].dptr<OType>(), mask_ptr, shape.get<2>(), axis, static_cast<DType>(temperature)); } else { Softmax<OP, negate, DType>( ctx.get_stream<xpu>(), inputs[0].dptr<DType>(), outputs[0].dptr<OType>(), mask_ptr, shape.get<3>(), axis, static_cast<DType>(temperature)); } } }); }); }); } template<typename xpu, typename OP1, typename OP2, bool negate = false> void SoftmaxGradCompute(const nnvm::NodeAttrs& attrs, const OpContext& ctx, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs) { using namespace mxnet_op; if (softmax_use_length(attrs)) { MXNET_INT32_INT64_TYPE_SWITCH(inputs[2].type_flag_, IType, { if (req[1] != kNullOp) { mxnet_op::Kernel<mxnet_op::set_zero, xpu>::Launch( ctx.get_stream<xpu>(), outputs[1].Size(), outputs[1].dptr<IType>()); } }); } if (req[0] == kNullOp) return; const int itype = softmax_use_length(attrs) ? inputs[2].type_flag_ : kInt32; const SoftmaxParam& param = nnvm::get<SoftmaxParam>(attrs.parsed); int axis = CheckAxis(param.axis, inputs[0].ndim()); const double temperature = param.temperature.has_value() ? param.temperature.value() : 1.0; mxnet::TShape shape = AxisShapeCompact(inputs[0].shape_, &axis, true); int out_idx = softmax_has_dtype_override(attrs) ? 2 : 1; out_idx = softmax_use_length(attrs) ? 3 : out_idx; bool safe_acc = dmlc::GetEnv("MXNET_SAFE_ACCUMULATION", false); MXNET_REAL_ACC_TYPE_SWITCH(inputs[0].type_flag_, OType, AType, { MSHADOW_REAL_TYPE_SWITCH(outputs[0].type_flag_, DType, { MXNET_ASSIGN_REQ_SWITCH(req[0], Req, { MXNET_INT32_INT64_TYPE_SWITCH(itype, IType, { IType * length_ptr = nullptr; if (softmax_use_length(attrs)) { length_ptr = inputs[2].dptr<IType>(); } if (safe_acc) { if (shape.ndim() == 2) { SoftmaxGrad<OP1, OP2, Req, negate, AType>( ctx.get_stream<xpu>(), inputs[out_idx].dptr<OType>(), inputs[0].dptr<OType>(), outputs[0].dptr<DType>(), length_ptr, shape.get<2>(), axis, static_cast<DType>(temperature)); } else { SoftmaxGrad<OP1, OP2, Req, negate, AType>( ctx.get_stream<xpu>(), inputs[out_idx].dptr<OType>(), inputs[0].dptr<OType>(), outputs[0].dptr<DType>(), length_ptr, shape.get<3>(), axis, static_cast<DType>(temperature)); } } else { if (shape.ndim() == 2) { SoftmaxGrad<OP1, OP2, Req, negate, DType>( ctx.get_stream<xpu>(), inputs[out_idx].dptr<OType>(), inputs[0].dptr<OType>(), outputs[0].dptr<DType>(), length_ptr, shape.get<2>(), axis, static_cast<DType>(temperature)); } else { SoftmaxGrad<OP1, OP2, Req, negate, DType>( ctx.get_stream<xpu>(), inputs[out_idx].dptr<OType>(), inputs[0].dptr<OType>(), outputs[0].dptr<DType>(), length_ptr, shape.get<3>(), axis, static_cast<DType>(temperature)); } } }); }); }); }); } } // namespace op } // namespace mxnet namespace std { template<> struct hash<mxnet::op::SoftmaxParam> { size_t operator()(const mxnet::op::SoftmaxParam& val) { size_t ret = 0; ret = dmlc::HashCombine(ret, val.axis); ret = dmlc::HashCombine(ret, val.temperature); ret = dmlc::HashCombine(ret, val.dtype); ret = dmlc::HashCombine(ret, val.use_length); return ret; } }; } // namespace std #endif // MXNET_OPERATOR_NN_SOFTMAX_INL_H_
scheduler-clause.c
#include <stdio.h> #include <stdlib.h> #ifdef _OPENMP #include <omp.h> #else #define omp_get_thread_num() 0 #endif int main(int argc, char **argv) { int i, n=20,a[n],suma=0; if(argc < 2) { fprintf(stderr,"\nFalta iteraciones \n"); exit(-1); } n = atoi(argv[1]); if (n>20) n=20; for (i=0; i<n; i++) a[i] = i; #pragma omp parallel for firstprivate(suma) lastprivate(suma) schedule(runtime) for (i=0; i<n; i++) { suma = suma + a[i]; printf(" thread %d suma a[%d]=%d suma=%d \n",omp_get_thread_num(),i,a[i],suma); } printf("Fuera de 'parallel for' suma=%d\n",suma); }
csf.c
/****************************************************************************** * INCLUDES *****************************************************************************/ #include "csf.h" #include "sort.h" #include "tile.h" #include "ccp/ccp.h" #include "io.h" #include "sptensor.h" /****************************************************************************** * API FUNCTIONS *****************************************************************************/ splatt_error_type splatt_csf_load( char const * const fname, splatt_idx_t * nmodes, splatt_csf ** tensors, double const * const options) { sptensor_t * tt = tt_read(fname); if(tt == NULL) { return SPLATT_ERROR_BADINPUT; } tt_remove_empty(tt); *tensors = csf_alloc(tt, options); *nmodes = tt->nmodes; tt_free(tt); return SPLATT_SUCCESS; } void splatt_free_csf( splatt_csf * tensors, double const * const options) { csf_free(tensors, options); } /****************************************************************************** * PRIVATE FUNCTIONS *****************************************************************************/ /** * @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]. */ idx_t p_csf_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 Find a permutation of modes that results in non-increasing mode size. * * @param dims The tensor dimensions. * @param nmodes The number of modes. * @param perm_dims The resulting permutation. */ static void p_order_dims_small( idx_t const * const dims, idx_t const nmodes, idx_t * const perm_dims) { idx_t sorted[MAX_NMODES]; idx_t matched[MAX_NMODES]; for(idx_t m=0; m < nmodes; ++m) { sorted[m] = dims[m]; matched[m] = 0; } quicksort(sorted, nmodes); /* silly n^2 comparison to grab modes from sorted dimensions. * TODO: make a key/val sort...*/ for(idx_t mfind=0; mfind < nmodes; ++mfind) { for(idx_t mcheck=0; mcheck < nmodes; ++mcheck) { if(sorted[mfind] == dims[mcheck] && !matched[mcheck]) { perm_dims[mfind] = mcheck; matched[mcheck] = 1; break; } } } } /** * @brief Find a permutation of modes such that the first mode is 'custom-mode' * and the remaining are naturally ordered (0, 1, ...). * * @param dims The tensor dimensions. * @param nmodes The number of modes. * @param custom_mode The mode to place first. * @param perm_dims The resulting permutation. */ static void p_order_dims_inorder( idx_t const * const dims, idx_t const nmodes, idx_t const custom_mode, idx_t * const perm_dims) { /* initialize to natural ordering */ for(idx_t m=0; m < nmodes; ++m) { perm_dims[m] = m; } /* find where custom_mode was placed and adjust from there */ for(idx_t m=0; m < nmodes; ++m) { if(perm_dims[m] == custom_mode) { memmove(perm_dims + 1, perm_dims, (m) * sizeof(m)); perm_dims[0] = custom_mode; break; } } } /** * @brief Find a permutation of modes such that the first mode is 'custom-mode' * and the remaining are sorted in non-increasing order. * * @param dims The tensor dimensions. * @param nmodes The number of modes. * @param custom_mode The mode to place first. * @param perm_dims The resulting permutation. */ static void p_order_dims_minusone( idx_t const * const dims, idx_t const nmodes, idx_t const custom_mode, idx_t * const perm_dims) { p_order_dims_small(dims, nmodes, perm_dims); /* find where custom_mode was placed and adjust from there */ for(idx_t m=0; m < nmodes; ++m) { if(perm_dims[m] == custom_mode) { memmove(perm_dims + 1, perm_dims, (m) * sizeof(m)); perm_dims[0] = custom_mode; break; } } } /** * @brief Find a permutation of modes that results in non-decreasing mode size. * * @param dims The tensor dimensions. * @param nmodes The number of modes. * @param perm_dims The resulting permutation. */ static void p_order_dims_large( idx_t const * const dims, idx_t const nmodes, idx_t * const perm_dims) { idx_t sorted[MAX_NMODES]; idx_t matched[MAX_NMODES]; for(idx_t m=0; m < nmodes; ++m) { sorted[m] = dims[m]; matched[m] = 0; } /* sort small -> large */ quicksort(sorted, nmodes); /* reverse list */ for(idx_t m=0; m < nmodes/2; ++m) { idx_t tmp = sorted[nmodes-m-1]; sorted[nmodes-m-1] = sorted[m]; sorted[m] = tmp; } /* silly n^2 comparison to grab modes from sorted dimensions. * TODO: make a key/val sort...*/ for(idx_t mfind=0; mfind < nmodes; ++mfind) { for(idx_t mcheck=0; mcheck < nmodes; ++mcheck) { if(sorted[mfind] == dims[mcheck] && !matched[mcheck]) { perm_dims[mfind] = mcheck; matched[mcheck] = 1; break; } } } } /** * @brief Construct the sparsity structure of the outer-mode of a CSF tensor. * * @param ct The CSF tensor to construct. * @param tt The coordinate tensor to construct from. Assumed to be already * sorted. * @param tile_id The ID of the tile to construct. * @param nnztile_ptr A pointer into 'tt' that marks the start of each tile. */ static void p_mk_outerptr( splatt_csf * const ct, sptensor_t const * const tt, idx_t const tile_id, idx_t const * const nnztile_ptr) { idx_t const nnzstart = nnztile_ptr[tile_id]; idx_t const nnzend = nnztile_ptr[tile_id+1]; idx_t const nnz = nnzend - nnzstart; assert(nnzstart < nnzend); /* grap top-level indices */ idx_t const * const restrict ttind = nnzstart + tt->ind[csf_depth_to_mode(ct, 0)]; /* count fibers */ idx_t nfibs = 1; for(idx_t x=1; x < nnz; ++x) { assert(ttind[x-1] <= ttind[x]); if(ttind[x] != ttind[x-1]) { ++nfibs; } } ct->pt[tile_id].nfibs[0] = nfibs; assert(nfibs <= ct->dims[csf_depth_to_mode(ct, 0)]); /* grab sparsity pattern */ csf_sparsity * const pt = ct->pt + tile_id; pt->fptr[0] = splatt_malloc((nfibs+1) * sizeof(**(pt->fptr))); if(ct->ntiles > 1) { pt->fids[0] = splatt_malloc(nfibs * sizeof(**(pt->fids))); } else { pt->fids[0] = NULL; } idx_t * const restrict fp = pt->fptr[0]; idx_t * const restrict fi = pt->fids[0]; fp[0] = 0; if(fi != NULL) { fi[0] = ttind[0]; } idx_t nfound = 1; for(idx_t n=1; n < nnz; ++n) { /* check for end of outer index */ if(ttind[n] != ttind[n-1]) { if(fi != NULL) { fi[nfound] = ttind[n]; } fp[nfound++] = n; } } fp[nfibs] = nnz; } /** * @brief Construct the sparsity structure of any mode but the last. The first * (root) mode is handled by p_mk_outerptr and the first is simply a copy * of the nonzeros. * * @param ct The CSF tensor to construct. * @param tt The coordinate tensor to construct from. Assumed to be already * sorted. * @param tile_id The ID of the tile to construct. * @param nnztile_ptr A pointer into 'tt' that marks the start of each tile. * @param mode Which mode we are constructing. */ static void p_mk_fptr( splatt_csf * const ct, sptensor_t const * const tt, idx_t const tile_id, idx_t const * const nnztile_ptr, idx_t const mode) { assert(mode < ct->nmodes); idx_t const nnzstart = nnztile_ptr[tile_id]; idx_t const nnzend = nnztile_ptr[tile_id+1]; idx_t const nnz = nnzend - nnzstart; /* outer mode is easy; just look at outer indices */ if(mode == 0) { p_mk_outerptr(ct, tt, tile_id, nnztile_ptr); return; } /* the mode after accounting for dim_perm */ idx_t const * const restrict ttind = nnzstart + tt->ind[csf_depth_to_mode(ct, mode)]; csf_sparsity * const pt = ct->pt + tile_id; /* we will edit this to point to the new fiber idxs instead of nnz */ idx_t * const restrict fprev = pt->fptr[mode-1]; /* first count nfibers */ idx_t nfibs = 0; /* foreach 'slice' in the previous dimension */ for(idx_t s=0; s < pt->nfibs[mode-1]; ++s) { ++nfibs; /* one by default per 'slice' */ /* count fibers in current hyperplane*/ for(idx_t f=fprev[s]+1; f < fprev[s+1]; ++f) { if(ttind[f] != ttind[f-1]) { ++nfibs; } } } pt->nfibs[mode] = nfibs; pt->fptr[mode] = splatt_malloc((nfibs+1) * sizeof(**(pt->fptr))); pt->fids[mode] = splatt_malloc(nfibs * sizeof(**(pt->fids))); idx_t * const restrict fp = pt->fptr[mode]; idx_t * const restrict fi = pt->fids[mode]; fp[0] = 0; /* now fill in fiber info */ idx_t nfound = 0; for(idx_t s=0; s < pt->nfibs[mode-1]; ++s) { idx_t const start = fprev[s]+1; idx_t const end = fprev[s+1]; /* mark start of subtree */ fprev[s] = nfound; fi[nfound] = ttind[start-1]; fp[nfound++] = start-1; /* mark fibers in current hyperplane */ for(idx_t f=start; f < end; ++f) { if(ttind[f] != ttind[f-1]) { fi[nfound] = ttind[f]; fp[nfound++] = f; } } } /* mark end of last hyperplane */ fprev[pt->nfibs[mode-1]] = nfibs; fp[nfibs] = nnz; } /** * @brief Allocate and fill a CSF tensor from a coordinate tensor without * tiling. * * @param ct The CSF tensor to fill out. * @param tt The sparse tensor to start from. */ static void p_csf_alloc_untiled( splatt_csf * const ct, sptensor_t * const tt) { idx_t const nmodes = tt->nmodes; tt_sort(tt, ct->dim_perm[0], ct->dim_perm); ct->ntiles = 1; ct->ntiled_modes = 0; for(idx_t m=0; m < nmodes; ++m) { ct->tile_dims[m] = 1; } ct->pt = splatt_malloc(sizeof(*(ct->pt))); csf_sparsity * const pt = ct->pt; /* last row of fptr is just nonzero inds */ pt->nfibs[nmodes-1] = ct->nnz; pt->fids[nmodes-1] = splatt_malloc(ct->nnz * sizeof(**(pt->fids))); pt->vals = splatt_malloc(ct->nnz * sizeof(*(pt->vals))); memcpy(pt->fids[nmodes-1], tt->ind[csf_depth_to_mode(ct, nmodes-1)], ct->nnz * sizeof(**(pt->fids))); memcpy(pt->vals, tt->vals, ct->nnz * sizeof(*(pt->vals))); /* setup a basic tile ptr for one tile */ idx_t nnz_ptr[2]; nnz_ptr[0] = 0; nnz_ptr[1] = tt->nnz; /* create fptr entries for the rest of the modes, working down from roots. * Skip the bottom level (nnz) */ for(idx_t m=0; m < tt->nmodes-1; ++m) { p_mk_fptr(ct, tt, 0, nnz_ptr, m); } } /** * @brief Reorder the nonzeros in a sparse tensor using dense tiling and fill * a CSF tensor with the data. * * @param ct The CSF tensor to fill. * @param tt The sparse tensor to start from. * @param splatt_opts Options array for SPLATT - used for tile dimensions. */ static void p_csf_alloc_densetile( splatt_csf * const ct, sptensor_t * const tt, double const * const splatt_opts) { idx_t const nmodes = tt->nmodes; /* how many levels we tile (counting from the bottom) */ ct->ntiled_modes = (idx_t)splatt_opts[SPLATT_OPTION_TILELEVEL]; ct->ntiled_modes = SS_MIN(ct->ntiled_modes, ct->nmodes); /* how many levels from the root do we start tiling? */ idx_t const tile_depth = ct->nmodes - ct->ntiled_modes; idx_t ntiles = 1; for(idx_t m=0; m < nmodes; ++m) { idx_t const depth = csf_mode_to_depth(ct, m); if(depth >= tile_depth) { ct->tile_dims[m] = (idx_t) splatt_opts[SPLATT_OPTION_NTHREADS]; } else { ct->tile_dims[m] = 1; } ntiles *= ct->tile_dims[m]; } /* perform tensor tiling */ tt_sort(tt, ct->dim_perm[0], ct->dim_perm); idx_t * nnz_ptr = tt_densetile(tt, ct->tile_dims); ct->ntiles = ntiles; ct->pt = splatt_malloc(ntiles * sizeof(*(ct->pt))); for(idx_t t=0; t < ntiles; ++t) { idx_t const startnnz = nnz_ptr[t]; idx_t const endnnz = nnz_ptr[t+1]; idx_t const ptnnz = endnnz - startnnz; csf_sparsity * const pt = ct->pt + t; /* empty tile */ if(ptnnz == 0) { for(idx_t m=0; m < ct->nmodes; ++m) { pt->fptr[m] = NULL; pt->fids[m] = NULL; pt->nfibs[m] = 0; } /* first fptr may be accessed anyway */ pt->fptr[0] = (idx_t *) splatt_malloc(2 * sizeof(**(pt->fptr))); pt->fptr[0][0] = 0; pt->fptr[0][1] = 0; pt->vals = NULL; continue; } idx_t const leaves = nmodes-1; /* last row of fptr is just nonzero inds */ pt->nfibs[leaves] = ptnnz; pt->fids[leaves] = splatt_malloc(ptnnz * sizeof(**(pt->fids))); memcpy(pt->fids[leaves], tt->ind[csf_depth_to_mode(ct, leaves)] + startnnz, ptnnz * sizeof(**(pt->fids))); pt->vals = splatt_malloc(ptnnz * sizeof(*(pt->vals))); memcpy(pt->vals, tt->vals + startnnz, ptnnz * sizeof(*(pt->vals))); /* create fptr entries for the rest of the modes */ for(idx_t m=0; m < leaves; ++m) { p_mk_fptr(ct, tt, t, nnz_ptr, m); } } free(nnz_ptr); } /** * @brief Construct dim_iperm, which is the inverse of dim_perm. * * @param ct The CSF tensor. */ static void p_fill_dim_iperm( splatt_csf * const ct) { for(idx_t level=0; level < ct->nmodes; ++level) { ct->dim_iperm[ct->dim_perm[level]] = level; } } /** * @brief Allocate and fill a CSF tensor. * * @param ct The CSF tensor to fill. * @param tt The coordinate tensor to work from. * @param mode_type The allocation scheme for the CSF tensor. * @param mode Which mode we are converting for (if applicable). * @param splatt_opts Used to determine tiling scheme. */ static void p_mk_csf( splatt_csf * const ct, sptensor_t * const tt, csf_mode_type mode_type, idx_t const mode, double const * const splatt_opts) { ct->nnz = tt->nnz; ct->nmodes = tt->nmodes; for(idx_t m=0; m < tt->nmodes; ++m) { ct->dims[m] = tt->dims[m]; } /* get the indices in order */ csf_find_mode_order(tt->dims, tt->nmodes, mode_type, mode, ct->dim_perm); p_fill_dim_iperm(ct); ct->which_tile = splatt_opts[SPLATT_OPTION_TILE]; switch(ct->which_tile) { case SPLATT_NOTILE: p_csf_alloc_untiled(ct, tt); break; case SPLATT_DENSETILE: p_csf_alloc_densetile(ct, tt, splatt_opts); break; default: fprintf(stderr, "SPLATT: tiling '%d' unsupported for CSF tensors.\n", ct->which_tile); break; } } /****************************************************************************** * PUBLIC FUNCTIONS *****************************************************************************/ void csf_free( splatt_csf * const csf, double const * const opts) { idx_t ntensors = 0; splatt_csf_type which = opts[SPLATT_OPTION_CSF_ALLOC]; switch(which) { case SPLATT_CSF_ONEMODE: ntensors = 1; break; case SPLATT_CSF_TWOMODE: ntensors = 2; break; case SPLATT_CSF_ALLMODE: ntensors = csf[0].nmodes; break; } for(idx_t i=0; i < ntensors; ++i) { csf_free_mode(csf + i); } free(csf); } void csf_free_mode( splatt_csf * const csf) { /* free each tile of sparsity pattern */ for(idx_t t=0; t < csf->ntiles; ++t) { free(csf->pt[t].vals); free(csf->pt[t].fids[csf->nmodes-1]); for(idx_t m=0; m < csf->nmodes-1; ++m) { free(csf->pt[t].fptr[m]); free(csf->pt[t].fids[m]); } } free(csf->pt); } void csf_find_mode_order( idx_t const * const dims, idx_t const nmodes, csf_mode_type which, idx_t const mode, idx_t * const perm_dims) { /* CSF_MODE_CUSTOM sanity check */ idx_t check_dims[MAX_NMODES]; switch(which) { case CSF_SORTED_SMALLFIRST: p_order_dims_small(dims, nmodes, perm_dims); break; case CSF_SORTED_BIGFIRST: p_order_dims_large(dims, nmodes, perm_dims); break; case CSF_INORDER_MINUSONE: p_order_dims_inorder(dims, nmodes, mode, perm_dims); break; case CSF_SORTED_MINUSONE: p_order_dims_minusone(dims, nmodes, mode, perm_dims); break; /* no-op, perm_dims better be set... */ case CSF_MODE_CUSTOM: /* just make sure it's actually set to something reasonable */ memcpy(check_dims, perm_dims, nmodes * sizeof(*perm_dims)); quicksort(check_dims, nmodes); for(idx_t m=0; m < nmodes; ++m) { if(check_dims[m] != m) { fprintf(stderr, "SPLATT: invalid permutation for CSF_MODE_CUSTOM.\n"); } } break; default: fprintf(stderr, "SPLATT: csf_mode_type '%d' not recognized.\n", which); break; } } size_t csf_storage( splatt_csf const * const tensors, double const * const opts) { idx_t ntensors = 0; splatt_csf_type which_alloc = opts[SPLATT_OPTION_CSF_ALLOC]; switch(which_alloc) { case SPLATT_CSF_ONEMODE: ntensors = 1; break; case SPLATT_CSF_TWOMODE: ntensors = 2; break; case SPLATT_CSF_ALLMODE: ntensors = tensors[0].nmodes; break; } size_t bytes = 0; for(idx_t m=0; m < ntensors; ++m) { splatt_csf const * const ct = tensors + m; bytes += ct->nnz * sizeof(*(ct->pt->vals)); /* vals */ bytes += ct->nnz * sizeof(**(ct->pt->fids)); /* fids[nmodes] */ bytes += ct->ntiles * sizeof(*(ct->pt)); /* pt */ for(idx_t t=0; t < ct->ntiles; ++t) { csf_sparsity const * const pt = ct->pt + t; for(idx_t m=0; m < ct->nmodes-1; ++m) { bytes += (pt->nfibs[m]+1) * sizeof(**(pt->fptr)); /* fptr */ if(pt->fids[m] != NULL) { bytes += pt->nfibs[m] * sizeof(**(pt->fids)); /* fids */ } } } } return bytes; } splatt_csf * csf_alloc( sptensor_t * const tt, double const * const opts) { splatt_csf * ret = NULL; double * tmp_opts = NULL; idx_t last_mode = 0; int tmp = 0; switch((splatt_csf_type) opts[SPLATT_OPTION_CSF_ALLOC]) { case SPLATT_CSF_ONEMODE: ret = splatt_malloc(sizeof(*ret)); p_mk_csf(ret, tt, CSF_SORTED_SMALLFIRST, 0, opts); break; case SPLATT_CSF_TWOMODE: ret = splatt_malloc(2 * sizeof(*ret)); /* regular CSF allocation */ p_mk_csf(ret + 0, tt, CSF_SORTED_SMALLFIRST, 0, opts); /* make a copy of opts and don't tile the last mode * TODO make this configurable? */ tmp_opts = splatt_default_opts(); memcpy(tmp_opts, opts, SPLATT_OPTION_NOPTIONS * sizeof(*opts)); tmp_opts[SPLATT_OPTION_TILE] = SPLATT_NOTILE; /* allocate with no tiling for the last mode */ last_mode = csf_depth_to_mode(&(ret[0]), tt->nmodes-1); p_mk_csf(ret + 1, tt, CSF_SORTED_MINUSONE, last_mode, tmp_opts); free(tmp_opts); break; case SPLATT_CSF_ALLMODE: ret = splatt_malloc(tt->nmodes * sizeof(*ret)); for(idx_t m=0; m < tt->nmodes; ++m) { p_mk_csf(ret + m, tt, CSF_SORTED_MINUSONE, m, opts); } break; } return ret; } void csf_alloc_mode( sptensor_t * const tt, csf_mode_type which_ordering, idx_t const mode_special, splatt_csf * const csf, double const * const opts) { p_mk_csf(csf, tt, which_ordering, mode_special, opts); } val_t csf_frobsq( splatt_csf const * const tensor) { /* accumulate into double to help with some precision loss */ double norm = 0; #pragma omp parallel reduction(+:norm) { for(idx_t t=0; t < tensor->ntiles; ++t) { val_t const * const vals = tensor->pt[t].vals; if(vals == NULL) { continue; } idx_t const nnz = tensor->pt[t].nfibs[tensor->nmodes-1]; #pragma omp for schedule(static) nowait for(idx_t n=0; n < nnz; ++n) { norm += vals[n] * vals[n]; } } } /* end omp parallel */ return (val_t) norm; } idx_t * csf_partition_1d( splatt_csf const * const csf, idx_t const tile_id, idx_t const nparts) { idx_t const nslices = csf->pt[tile_id].nfibs[0]; idx_t * weights = splatt_malloc(nslices * sizeof(*weights)); #pragma omp parallel for schedule(static) for(idx_t i=0; i < nslices; ++i) { weights[i] = p_csf_count_nnz(csf->pt[tile_id].fptr, csf->nmodes, 0, i); } idx_t * parts = partition_1d(weights, nslices, nparts); splatt_free(weights); return parts; } idx_t * csf_partition_tiles_1d( splatt_csf const * const csf, idx_t const nparts) { idx_t const nmodes = csf->nmodes; idx_t const ntiles = csf->ntiles; idx_t * weights = splatt_malloc(ntiles * sizeof(*weights)); #pragma omp parallel for schedule(static) for(idx_t i=0; i < ntiles; ++i) { weights[i] = csf->pt[i].nfibs[nmodes-1]; } idx_t * parts = partition_1d(weights, ntiles, nparts); splatt_free(weights); return parts; }
debug_private.c
// This testcase checks emission of debug info for variables inside // private/firstprivate/lastprivate. // REQUIRES: x86_64-linux // RUN: %clang_cc1 -debug-info-kind=constructor -x c -verify -triple x86_64-pc-linux-gnu -fopenmp -emit-llvm %s -o - | FileCheck %s // expected-no-diagnostics // CHECK: define internal i32 @.omp_task_entry. // CHECK: call void @llvm.dbg.declare(metadata i32** %.priv.ptr.addr.i, metadata [[PRIV1:![0-9]+]], metadata !DIExpression(DW_OP_deref)) // CHECK: call void @llvm.dbg.declare(metadata i32** %.priv.ptr.addr1.i, metadata [[PRIV2:![0-9]+]], metadata !DIExpression(DW_OP_deref)) // CHECK: call void @llvm.dbg.declare(metadata i32** %.firstpriv.ptr.addr.i, metadata [[FPRIV:![0-9]+]], metadata !DIExpression(DW_OP_deref)) // CHECK: [[PRIV1]] = !DILocalVariable(name: "priv1" // CHECK: [[PRIV2]] = !DILocalVariable(name: "priv2" // CHECK: [[FPRIV]] = !DILocalVariable(name: "fpriv" extern int printf(const char *, ...); int foo(int n) { int res, priv1, priv2, fpriv; fpriv = n + 4; if (n < 2) return n; else { #pragma omp task shared(res) private(priv1, priv2) firstprivate(fpriv) { priv1 = n; priv2 = n + 2; printf("Task n=%d,priv1=%d,priv2=%d,fpriv=%d\n", n, priv1, priv2, fpriv); res = priv1 + priv2 + fpriv + foo(n - 1); } #pragma omp taskwait return res; } } int main() { int n = 10; printf("foo(%d) = %d\n", n, foo(n)); return 0; }
opencl_keyring_fmt_plug.c
/* * This software is Copyright (c) 2012 Lukas Odzioba <ukasz@openwall.net>, * Copyright (c) 2012 Dhiru Kholia <dhiru at openwall.com> and * Copyright (c) 2012-2014 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. */ #ifdef HAVE_OPENCL #if FMT_EXTERNS_H extern struct fmt_main fmt_opencl_keyring; #elif FMT_REGISTERS_H john_register_one(&fmt_opencl_keyring); #else #include <string.h> #include "aes.h" #ifdef _OPENMP #include <omp.h> #endif #include "arch.h" #include "formats.h" #include "common.h" #include "misc.h" #include "common-opencl.h" #include "options.h" #include "sha2.h" #include "md5.h" #include "stdint.h" #define FORMAT_LABEL "keyring-opencl" #define FORMAT_NAME "GNOME Keyring" #define ALGORITHM_NAME "SHA256 OpenCL AES" #define BENCHMARK_COMMENT "" #define BENCHMARK_LENGTH -1 #define MIN_KEYS_PER_CRYPT 1 #define MAX_KEYS_PER_CRYPT 1 #define PLAINTEXT_LENGTH (55-8) #define BINARY_SIZE 0 #define BINARY_ALIGN 1 #define SALT_SIZE sizeof(struct custom_salt) #define SALT_ALIGN 4 #define SALTLEN 8 typedef unsigned char guchar; /* How many aliases do we need?! */ typedef unsigned int guint; typedef int gint; typedef struct { uint32_t length; uint8_t v[PLAINTEXT_LENGTH]; } keyring_password; typedef struct { uint8_t key[16]; uint8_t iv[16]; } keyring_hash; typedef struct { uint32_t length; uint32_t iterations; uint8_t salt[SALTLEN]; } keyring_salt; static int *cracked; static int any_cracked; static struct custom_salt { unsigned int iterations; unsigned char salt[SALTLEN]; unsigned int crypto_size; unsigned int inlined; unsigned char ct[LINE_BUFFER_SIZE / 2]; /* after hex conversion */ } *cur_salt; static struct fmt_tests keyring_tests[] = { {"$keyring$db1b562e453a0764*3221*16*0*02b5c084e4802369c42507300f2e5e56", "openwall"}, {"$keyring$4f3f1557a7da17f5*2439*144*0*12215fabcff6782aa23605ab2cd843f7be9477b172b615eaa9130836f189d32ffda2e666747378f09c6e76ad817154daae83a36c0a0a35f991d40bcfcba3b7807ef57a0ce4c7f835bf34c6e358f0d66aa048d73dacaaaf6d7fa4b3510add6b88cc237000ff13cb4dbd132db33be3ea113bedeba80606f86662cc226af0dad789c703a7df5ad8700542e0f7a5e1f10cf0", "password"}, {NULL} }; static keyring_password *inbuffer; static keyring_hash *outbuffer; static keyring_salt currentsalt; static cl_mem mem_in, mem_out, mem_setting; static struct fmt_main *self; #define insize (sizeof(keyring_password) * global_work_size) #define outsize (sizeof(keyring_hash) * global_work_size) #define settingsize (sizeof(keyring_salt)) #define cracked_size (sizeof(*cracked) * global_work_size) #define STEP 0 #define SEED 256 static const char * warn[] = { "xfer: " , ", crypt: " , ", xfer: " }; //This file contains auto-tuning routine(s). It has to be included after formats definitions. #include "opencl-autotune.h" #include "memdbg.h" /* ------- Helper functions ------- */ static size_t get_task_max_work_group_size() { return autotune_get_task_max_work_group_size(FALSE, 0, crypt_kernel); } static void create_clobj(size_t global_work_size, struct fmt_main *self) { cl_int cl_error; inbuffer = (keyring_password*) mem_calloc(1, insize); outbuffer = (keyring_hash*) mem_alloc(outsize); cracked = mem_calloc(1, cracked_size); /// Allocate memory mem_in = clCreateBuffer(context[gpu_id], CL_MEM_READ_ONLY, insize, NULL, &cl_error); HANDLE_CLERROR(cl_error, "Error allocating mem in"); mem_setting = clCreateBuffer(context[gpu_id], CL_MEM_READ_ONLY, settingsize, NULL, &cl_error); HANDLE_CLERROR(cl_error, "Error allocating mem setting"); mem_out = clCreateBuffer(context[gpu_id], CL_MEM_WRITE_ONLY, outsize, NULL, &cl_error); HANDLE_CLERROR(cl_error, "Error allocating mem out"); HANDLE_CLERROR(clSetKernelArg(crypt_kernel, 0, sizeof(mem_in), &mem_in), "Error while setting mem_in kernel argument"); HANDLE_CLERROR(clSetKernelArg(crypt_kernel, 1, sizeof(mem_out), &mem_out), "Error while setting mem_out kernel argument"); HANDLE_CLERROR(clSetKernelArg(crypt_kernel, 2, sizeof(mem_setting), &mem_setting), "Error while setting mem_salt kernel argument"); } static void release_clobj(void) { if (cracked) { HANDLE_CLERROR(clReleaseMemObject(mem_in), "Release mem in"); HANDLE_CLERROR(clReleaseMemObject(mem_setting), "Release mem setting"); HANDLE_CLERROR(clReleaseMemObject(mem_out), "Release mem out"); MEM_FREE(inbuffer); MEM_FREE(outbuffer); MEM_FREE(cracked); } } static void done(void) { if (autotuned) { release_clobj(); HANDLE_CLERROR(clReleaseKernel(crypt_kernel), "Release kernel"); HANDLE_CLERROR(clReleaseProgram(program[gpu_id]), "Release Program"); autotuned--; } } static void init(struct fmt_main *_self) { self = _self; opencl_prepare_dev(gpu_id); } static void reset(struct db_main *db) { if (!autotuned) { char build_opts[64]; cl_int cl_error; snprintf(build_opts, sizeof(build_opts), "-DPLAINTEXT_LENGTH=%d -DSALTLEN=%d", PLAINTEXT_LENGTH, SALTLEN); opencl_init("$JOHN/kernels/keyring_kernel.cl", gpu_id, build_opts); crypt_kernel = clCreateKernel(program[gpu_id], "keyring", &cl_error); HANDLE_CLERROR(cl_error, "Error creating kernel"); // Initialize openCL tuning (library) for this format. opencl_init_auto_setup(SEED, 0, NULL, warn, 1, self, create_clobj, release_clobj, sizeof(keyring_password), 0, db); //Auto tune execution from shared/included code. autotune_run(self, 1, 0, cpu(device_info[gpu_id]) ? 500000000ULL : 1000000000ULL); } } static int looks_like_nice_int(char *p) { // reasonability check + avoids atoi's UB if (strlen(p) > 9) return 0; for (; *p; p++) if (*p < '0' || *p > '9') return 0; return 1; } static int valid(char *ciphertext, struct fmt_main *self) { char *ctcopy, *keeptr, *p; int ctlen; if (strncmp(ciphertext, "$keyring$", 9) != 0) return 0; ctcopy = strdup(ciphertext); keeptr = ctcopy; if (keeptr == NULL) goto err; ctcopy += 9; if ((p = strtokm(ctcopy, "*")) == NULL) /* salt */ goto err; if (hexlenl(p) != SALTLEN * 2) goto err; while (*p) if (atoi16[ARCH_INDEX(*p++)] == 0x7f) goto err; if ((p = strtokm(NULL, "*")) == NULL) /* iterations */ goto err; if (!looks_like_nice_int(p)) goto err; if ((p = strtokm(NULL, "*")) == NULL) /* crypto size */ goto err; if (!looks_like_nice_int(p)) goto err; ctlen = atoi(p); if (ctlen > sizeof(cur_salt->ct)) goto err; if ((p = strtokm(NULL, "*")) == NULL) /* inlined - unused? TODO */ goto err; if (!looks_like_nice_int(p)) goto err; if ((p = strtokm(NULL, "*")) == NULL) /* ciphertext */ goto err; if (ctlen > LINE_BUFFER_SIZE) goto err; if (hexlenl(p) != ctlen * 2) goto err; if (strlen(p) < 32) /* this shouldn't happen for valid hashes */ goto err; while (*p) if (atoi16l[ARCH_INDEX(*p++)] == 0x7f) goto err; MEM_FREE(keeptr); return 1; err: MEM_FREE(keeptr); return 0; } static void *get_salt(char *ciphertext) { char *ctcopy = strdup(ciphertext); char *keeptr = ctcopy; int i; char *p; static struct custom_salt cs; memset(&cs, 0, sizeof(cs)); if (!cur_salt) cur_salt = mem_alloc_tiny(sizeof(struct custom_salt), MEM_ALIGN_WORD); ctcopy += 9; /* skip over "$keyring$" */ p = strtokm(ctcopy, "*"); for (i = 0; i < SALTLEN; i++) cs.salt[i] = atoi16[ARCH_INDEX(p[i * 2])] * 16 + atoi16[ARCH_INDEX(p[i * 2 + 1])]; p = strtokm(NULL, "*"); cs.iterations = atoi(p); p = strtokm(NULL, "*"); cs.crypto_size = atoi(p); p = strtokm(NULL, "*"); cs.inlined = atoi(p); p = strtokm(NULL, "*"); for (i = 0; i < cs.crypto_size; i++) cs.ct[i] = atoi16[ARCH_INDEX(p[i * 2])] * 16 + atoi16[ARCH_INDEX(p[i * 2 + 1])]; MEM_FREE(keeptr); return (void *)&cs; } static void set_salt(void *salt) { cur_salt = (struct custom_salt *)salt; memcpy((char*)currentsalt.salt, cur_salt->salt, SALTLEN); currentsalt.length = SALTLEN; currentsalt.iterations = cur_salt->iterations; HANDLE_CLERROR(clEnqueueWriteBuffer(queue[gpu_id], mem_setting, CL_FALSE, 0, settingsize, &currentsalt, 0, NULL, NULL), "Copy setting to gpu"); } static void keyring_set_key(char *key, int index) { uint8_t length = strlen(key); if (length > PLAINTEXT_LENGTH) length = PLAINTEXT_LENGTH; inbuffer[index].length = length; memcpy(inbuffer[index].v, key, length); } static char *get_key(int index) { static char ret[PLAINTEXT_LENGTH + 1]; uint8_t length = inbuffer[index].length; memcpy(ret, inbuffer[index].v, length); ret[length] = '\0'; return ret; } static int verify_decrypted_buffer(unsigned char *buffer, int len) { guchar digest[16]; MD5_CTX ctx; MD5_Init(&ctx); MD5_Update(&ctx, buffer + 16, len - 16); MD5_Final(digest, &ctx); return memcmp(buffer, digest, 16) == 0; } static int crypt_all(int *pcount, struct db_salt *salt) { const int count = *pcount; int index; size_t *lws = local_work_size ? &local_work_size : NULL; global_work_size = GET_MULTIPLE_OR_BIGGER(count, local_work_size); if (any_cracked) { memset(cracked, 0, cracked_size); any_cracked = 0; } /// Copy data to gpu BENCH_CLERROR(clEnqueueWriteBuffer(queue[gpu_id], mem_in, CL_FALSE, 0, insize, inbuffer, 0, NULL, multi_profilingEvent[0]), "Copy data to gpu"); /// Run kernel BENCH_CLERROR(clEnqueueNDRangeKernel(queue[gpu_id], crypt_kernel, 1, NULL, &global_work_size, lws, 0, NULL, multi_profilingEvent[1]), "Run kernel"); BENCH_CLERROR(clFinish(queue[gpu_id]), "clFinish"); /// Read the result back BENCH_CLERROR(clEnqueueReadBuffer(queue[gpu_id], mem_out, CL_FALSE, 0, outsize, outbuffer, 0, NULL, multi_profilingEvent[2]), "Copy result back"); /// Await completion of all the above BENCH_CLERROR(clFinish(queue[gpu_id]), "clFinish"); if (ocl_autotune_running) return count; #ifdef _OPENMP #pragma omp parallel for #endif for (index = 0; index < count; index++) { unsigned char buffer[LINE_BUFFER_SIZE / 2]; unsigned char iv[16]; AES_KEY akey; unsigned char *p = outbuffer[index].iv; memcpy(iv, p, 16); memcpy(buffer, cur_salt->ct, cur_salt->crypto_size); memset(&akey, 0, sizeof(AES_KEY)); if (AES_set_decrypt_key(outbuffer[index].key, 128, &akey) < 0) { fprintf(stderr, "AES_set_decrypt_key failed!\n"); } AES_cbc_encrypt(buffer, buffer, cur_salt->crypto_size, &akey, iv, AES_DECRYPT); if (verify_decrypted_buffer(buffer, cur_salt->crypto_size)) { cracked[index] = 1; #ifdef _OPENMP #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 1; } static unsigned int iteration_count(void *salt) { struct custom_salt *my_salt; my_salt = salt; return (unsigned int) my_salt->iterations; } struct fmt_main fmt_opencl_keyring = { { 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, { "iteration count", }, keyring_tests }, { init, done, reset, fmt_default_prepare, valid, fmt_default_split, fmt_default_binary, get_salt, { iteration_count, }, fmt_default_source, { fmt_default_binary_hash }, fmt_default_salt_hash, NULL, set_salt, keyring_set_key, get_key, fmt_default_clear_keys, crypt_all, { fmt_default_get_hash }, cmp_all, cmp_one, cmp_exact } }; #endif /* plugin stanza */ #endif /* HAVE_OPENCL */
colorspace.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % CCCC OOO L OOO RRRR SSSSS PPPP AAA CCCC EEEEE % % C O O L O O R R SS P P A A C E % % C O O L O O RRRR SSS PPPP AAAAA C EEE % % C O O L O O R R SS P A A C E % % CCCC OOO LLLLL OOO R R SSSSS P A A CCCC EEEEE % % % % % % MagickCore Image Colorspace Methods % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2018 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/attribute.h" #include "MagickCore/property.h" #include "MagickCore/cache.h" #include "MagickCore/cache-private.h" #include "MagickCore/cache-view.h" #include "MagickCore/color.h" #include "MagickCore/color-private.h" #include "MagickCore/colorspace.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/enhance.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/gem.h" #include "MagickCore/gem-private.h" #include "MagickCore/memory_.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/pixel-private.h" #include "MagickCore/quantize.h" #include "MagickCore/quantum.h" #include "MagickCore/quantum-private.h" #include "MagickCore/resource_.h" #include "MagickCore/string_.h" #include "MagickCore/string-private.h" #include "MagickCore/utility.h" /* Typedef declarations. */ typedef struct _TransformPacket { MagickRealType x, y, z; } TransformPacket; /* Forward declarations. */ static MagickBooleanType TransformsRGBImage(Image *,ExceptionInfo *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e C o l o r s p a c e T y p e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageColorspaceType() returns the potential type of image: % sRGBColorspaceType, RGBColorspaceType, GRAYColorspaceType, etc. % % To ensure the image type matches its potential, use SetImageColorspaceType(): % % (void) SetImageColorspaceType(image,GetImageColorspaceType(image), % exception); % % The format of the GetImageColorspaceType method is: % % ColorspaceType GetImageColorspaceType(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 ColorspaceType GetImageColorspaceType(const Image *image, ExceptionInfo *exception) { ColorspaceType colorspace; ImageType type; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); colorspace=image->colorspace; type=IdentifyImageType(image,exception); if ((type == BilevelType) || (type == GrayscaleType) || (type == GrayscaleAlphaType)) colorspace=GRAYColorspace; return(colorspace); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + s R G B T r a n s f o r m I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % sRGBTransformImage() converts the reference image from sRGB to an alternate % colorspace. The transformation matrices are not the standard ones: the % weights are rescaled to normalized the range of the transformed values to % be [0..QuantumRange]. % % The format of the sRGBTransformImage method is: % % MagickBooleanType sRGBTransformImage(Image *image, % const ColorspaceType colorspace,EsceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o colorspace: the colorspace to transform the image to. % % o exception: return any errors or warnings in this structure. % */ static inline void ConvertRGBToCMY(const double red,const double green, const double blue,double *cyan,double *magenta,double *yellow) { *cyan=QuantumScale*(QuantumRange-red); *magenta=QuantumScale*(QuantumRange-green); *yellow=QuantumScale*(QuantumRange-blue); } static inline void ConvertXYZToLMS(const double x,const double y, const double z,double *L,double *M,double *S) { *L=0.7328*x+0.4296*y-0.1624*z; *M=(-0.7036*x+1.6975*y+0.0061*z); *S=0.0030*x+0.0136*y+0.9834*z; } static void ConvertRGBToLMS(const double red,const double green, const double blue,double *L,double *M,double *S) { double X, Y, Z; ConvertRGBToXYZ(red,green,blue,&X,&Y,&Z); ConvertXYZToLMS(X,Y,Z,L,M,S); } static void ConvertRGBToLab(const double red,const double green, const double blue,double *L,double *a,double *b) { double X, Y, Z; ConvertRGBToXYZ(red,green,blue,&X,&Y,&Z); ConvertXYZToLab(X,Y,Z,L,a,b); } static void ConvertRGBToLuv(const double red,const double green, const double blue,double *L,double *u,double *v) { double X, Y, Z; ConvertRGBToXYZ(red,green,blue,&X,&Y,&Z); ConvertXYZToLuv(X,Y,Z,L,u,v); } static void ConvertRGBToxyY(const double red,const double green, const double blue,double *low_x,double *low_y,double *cap_Y) { double gamma, X, Y, Z; ConvertRGBToXYZ(red,green,blue,&X,&Y,&Z); gamma=PerceptibleReciprocal(X+Y+Z); *low_x=gamma*X; *low_y=gamma*Y; *cap_Y=Y; } static void ConvertRGBToYDbDr(const double red,const double green, const double blue,double *Y,double *Db,double *Dr) { *Y=QuantumScale*(0.298839*red+0.586811*green+0.114350*blue); *Db=QuantumScale*(-0.450*red-0.883*green+1.333*blue)+0.5; *Dr=QuantumScale*(-1.333*red+1.116*green+0.217*blue)+0.5; } static void ConvertRGBToYIQ(const double red,const double green, const double blue,double *Y,double *I,double *Q) { *Y=QuantumScale*(0.298839*red+0.586811*green+0.114350*blue); *I=QuantumScale*(0.595716*red-0.274453*green-0.321263*blue)+0.5; *Q=QuantumScale*(0.211456*red-0.522591*green+0.311135*blue)+0.5; } static void ConvertRGBToYPbPr(const double red,const double green, const double blue,double *Y,double *Pb,double *Pr) { *Y=QuantumScale*(0.298839*red+0.586811*green+0.114350*blue); *Pb=QuantumScale*((-0.1687367)*red-0.331264*green+0.5*blue)+0.5; *Pr=QuantumScale*(0.5*red-0.418688*green-0.081312*blue)+0.5; } static void ConvertRGBToYCbCr(const double red,const double green, const double blue,double *Y,double *Cb,double *Cr) { ConvertRGBToYPbPr(red,green,blue,Y,Cb,Cr); } static void ConvertRGBToYUV(const double red,const double green, const double blue,double *Y,double *U,double *V) { *Y=QuantumScale*(0.298839*red+0.586811*green+0.114350*blue); *U=QuantumScale*((-0.147)*red-0.289*green+0.436*blue)+0.5; *V=QuantumScale*(0.615*red-0.515*green-0.100*blue)+0.5; } static MagickBooleanType sRGBTransformImage(Image *image, const ColorspaceType colorspace,ExceptionInfo *exception) { #define sRGBTransformImageTag "RGBTransform/Image" CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; PrimaryInfo primary_info; register ssize_t i; ssize_t y; TransformPacket *x_map, *y_map, *z_map; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(colorspace != sRGBColorspace); assert(colorspace != TransparentColorspace); assert(colorspace != UndefinedColorspace); status=MagickTrue; progress=0; switch (colorspace) { case CMYKColorspace: { PixelInfo zero; /* Convert RGB to CMYK colorspace. */ if (image->storage_class == PseudoClass) { if (SyncImage(image,exception) == MagickFalse) return(MagickFalse); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); } if (SetImageColorspace(image,colorspace,exception) == MagickFalse) return(MagickFalse); GetPixelInfo(image,&zero); 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++) { MagickBooleanType sync; PixelInfo pixel; register ssize_t x; register 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); ConvertRGBToCMYK(&pixel); SetPixelViaPixelInfo(image,&pixel,q); q+=GetPixelChannels(image); } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); image->type=image->alpha_trait == UndefinedPixelTrait ? ColorSeparationType : ColorSeparationAlphaType; if (SetImageColorspace(image,colorspace,exception) == MagickFalse) return(MagickFalse); return(status); } case LinearGRAYColorspace: case GRAYColorspace: { /* Transform image from sRGB to GRAY. */ if (image->storage_class == PseudoClass) { if (SyncImage(image,exception) == MagickFalse) return(MagickFalse); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); } 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++) { MagickBooleanType sync; register ssize_t x; register 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; } for (x=0; x < (ssize_t) image->columns; x++) { SetPixelGray(image,ClampToQuantum(GetPixelIntensity(image,q)),q); q+=GetPixelChannels(image); } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); if (SetImageColorspace(image,colorspace,exception) == MagickFalse) return(MagickFalse); image->type=GrayscaleType; return(status); } case CMYColorspace: case HCLColorspace: case HCLpColorspace: case HSBColorspace: case HSIColorspace: case HSLColorspace: case HSVColorspace: case HWBColorspace: case LabColorspace: case LCHColorspace: case LCHabColorspace: case LCHuvColorspace: case LMSColorspace: case LuvColorspace: case xyYColorspace: case XYZColorspace: case YCbCrColorspace: case YDbDrColorspace: case YIQColorspace: case YPbPrColorspace: case YUVColorspace: { /* Transform image from sRGB to target colorspace. */ if (image->storage_class == PseudoClass) { if (SyncImage(image,exception) == MagickFalse) return(MagickFalse); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); } 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++) { MagickBooleanType sync; register ssize_t x; register 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; } for (x=0; x < (ssize_t) image->columns; x++) { double blue, green, red, X, Y, Z; red=(double) GetPixelRed(image,q); green=(double) GetPixelGreen(image,q); blue=(double) GetPixelBlue(image,q); switch (colorspace) { case CMYColorspace: { ConvertRGBToCMY(red,green,blue,&X,&Y,&Z); break; } case HCLColorspace: { ConvertRGBToHCL(red,green,blue,&X,&Y,&Z); break; } case HCLpColorspace: { ConvertRGBToHCLp(red,green,blue,&X,&Y,&Z); break; } case HSBColorspace: { ConvertRGBToHSB(red,green,blue,&X,&Y,&Z); break; } case HSIColorspace: { ConvertRGBToHSI(red,green,blue,&X,&Y,&Z); break; } case HSLColorspace: { ConvertRGBToHSL(red,green,blue,&X,&Y,&Z); break; } case HSVColorspace: { ConvertRGBToHSV(red,green,blue,&X,&Y,&Z); break; } case HWBColorspace: { ConvertRGBToHWB(red,green,blue,&X,&Y,&Z); break; } case LabColorspace: { ConvertRGBToLab(red,green,blue,&X,&Y,&Z); break; } case LCHColorspace: case LCHabColorspace: { ConvertRGBToLCHab(red,green,blue,&X,&Y,&Z); break; } case LCHuvColorspace: { ConvertRGBToLCHuv(red,green,blue,&X,&Y,&Z); break; } case LMSColorspace: { ConvertRGBToLMS(red,green,blue,&X,&Y,&Z); break; } case LuvColorspace: { ConvertRGBToLuv(red,green,blue,&X,&Y,&Z); break; } case xyYColorspace: { ConvertRGBToxyY(red,green,blue,&X,&Y,&Z); break; } case XYZColorspace: { ConvertRGBToXYZ(red,green,blue,&X,&Y,&Z); break; } case YCbCrColorspace: { ConvertRGBToYCbCr(red,green,blue,&X,&Y,&Z); break; } case YDbDrColorspace: { ConvertRGBToYDbDr(red,green,blue,&X,&Y,&Z); break; } case YIQColorspace: { ConvertRGBToYIQ(red,green,blue,&X,&Y,&Z); break; } case YPbPrColorspace: { ConvertRGBToYPbPr(red,green,blue,&X,&Y,&Z); break; } case YUVColorspace: { ConvertRGBToYUV(red,green,blue,&X,&Y,&Z); break; } default: { X=QuantumScale*red; Y=QuantumScale*green; Z=QuantumScale*blue; break; } } SetPixelRed(image,ClampToQuantum(QuantumRange*X),q); SetPixelGreen(image,ClampToQuantum(QuantumRange*Y),q); SetPixelBlue(image,ClampToQuantum(QuantumRange*Z),q); q+=GetPixelChannels(image); } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); if (SetImageColorspace(image,colorspace,exception) == MagickFalse) return(MagickFalse); return(status); } case LogColorspace: { #define DisplayGamma (1.0/1.7) #define FilmGamma 0.6 #define ReferenceBlack 95.0 #define ReferenceWhite 685.0 const char *value; double black, density, film_gamma, gamma, reference_black, reference_white; Quantum *logmap; /* Transform RGB to Log colorspace. */ density=DisplayGamma; gamma=DisplayGamma; value=GetImageProperty(image,"gamma",exception); if (value != (const char *) NULL) gamma=PerceptibleReciprocal(StringToDouble(value,(char **) NULL)); film_gamma=FilmGamma; value=GetImageProperty(image,"film-gamma",exception); if (value != (const char *) NULL) film_gamma=StringToDouble(value,(char **) NULL); reference_black=ReferenceBlack; value=GetImageProperty(image,"reference-black",exception); if (value != (const char *) NULL) reference_black=StringToDouble(value,(char **) NULL); reference_white=ReferenceWhite; value=GetImageProperty(image,"reference-white",exception); if (value != (const char *) NULL) reference_white=StringToDouble(value,(char **) NULL); logmap=(Quantum *) AcquireQuantumMemory((size_t) MaxMap+1UL, sizeof(*logmap)); if (logmap == (Quantum *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); black=pow(10.0,(reference_black-reference_white)*(gamma/density)*0.002/ film_gamma); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) #endif for (i=0; i <= (ssize_t) MaxMap; i++) logmap[i]=ScaleMapToQuantum((double) (MaxMap*(reference_white+ log10(black+(1.0*i/MaxMap)*(1.0-black))/((gamma/density)*0.002/ film_gamma))/1024.0)); 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++) { MagickBooleanType sync; register ssize_t x; register 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; } for (x=(ssize_t) image->columns; x != 0; x--) { double blue, green, red; red=(double) DecodePixelGamma((MagickRealType) GetPixelRed(image,q)); green=(double) DecodePixelGamma((MagickRealType) GetPixelGreen(image,q)); blue=(double) DecodePixelGamma((MagickRealType) GetPixelBlue(image,q)); SetPixelRed(image,logmap[ScaleQuantumToMap(ClampToQuantum(red))],q); SetPixelGreen(image,logmap[ScaleQuantumToMap(ClampToQuantum(green))], q); SetPixelBlue(image,logmap[ScaleQuantumToMap(ClampToQuantum(blue))],q); q+=GetPixelChannels(image); } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); logmap=(Quantum *) RelinquishMagickMemory(logmap); if (SetImageColorspace(image,colorspace,exception) == MagickFalse) return(MagickFalse); return(status); } case RGBColorspace: case scRGBColorspace: { /* Transform image from sRGB to linear RGB. */ if (image->storage_class == PseudoClass) { if (SyncImage(image,exception) == MagickFalse) return(MagickFalse); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); } 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++) { MagickBooleanType sync; register ssize_t x; register 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; } for (x=0; x < (ssize_t) image->columns; x++) { double blue, green, red; red=DecodePixelGamma((MagickRealType) GetPixelRed(image,q)); green=DecodePixelGamma((MagickRealType) GetPixelGreen(image,q)); blue=DecodePixelGamma((MagickRealType) GetPixelBlue(image,q)); SetPixelRed(image,ClampToQuantum(red),q); SetPixelGreen(image,ClampToQuantum(green),q); SetPixelBlue(image,ClampToQuantum(blue),q); q+=GetPixelChannels(image); } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); if (SetImageColorspace(image,colorspace,exception) == MagickFalse) return(MagickFalse); return(status); } default: break; } /* Allocate the tables. */ x_map=(TransformPacket *) AcquireQuantumMemory((size_t) MaxMap+1UL, sizeof(*x_map)); y_map=(TransformPacket *) AcquireQuantumMemory((size_t) MaxMap+1UL, sizeof(*y_map)); z_map=(TransformPacket *) AcquireQuantumMemory((size_t) MaxMap+1UL, sizeof(*z_map)); if ((x_map == (TransformPacket *) NULL) || (y_map == (TransformPacket *) NULL) || (z_map == (TransformPacket *) NULL)) { if (x_map != (TransformPacket *) NULL) x_map=(TransformPacket *) RelinquishMagickMemory(x_map); if (y_map != (TransformPacket *) NULL) y_map=(TransformPacket *) RelinquishMagickMemory(y_map); if (z_map != (TransformPacket *) NULL) z_map=(TransformPacket *) RelinquishMagickMemory(z_map); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } (void) ResetMagickMemory(&primary_info,0,sizeof(primary_info)); switch (colorspace) { case OHTAColorspace: { /* Initialize OHTA tables: I1 = 0.33333*R+0.33334*G+0.33333*B I2 = 0.50000*R+0.00000*G-0.50000*B I3 =-0.25000*R+0.50000*G-0.25000*B I and Q, normally -0.5 through 0.5, are normalized to the range 0 through QuantumRange. */ primary_info.y=(double) (MaxMap+1.0)/2.0; primary_info.z=(double) (MaxMap+1.0)/2.0; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) #endif for (i=0; i <= (ssize_t) MaxMap; i++) { x_map[i].x=(MagickRealType) (0.33333*(double) i); y_map[i].x=(MagickRealType) (0.33334*(double) i); z_map[i].x=(MagickRealType) (0.33333*(double) i); x_map[i].y=(MagickRealType) (0.50000*(double) i); y_map[i].y=(MagickRealType) (0.00000*(double) i); z_map[i].y=(MagickRealType) (-0.50000*(double) i); x_map[i].z=(MagickRealType) (-0.25000*(double) i); y_map[i].z=(MagickRealType) (0.50000*(double) i); z_map[i].z=(MagickRealType) (-0.25000*(double) i); } break; } case Rec601YCbCrColorspace: { /* Initialize YCbCr tables (ITU-R BT.601): Y = 0.2988390*R+0.5868110*G+0.1143500*B Cb= -0.1687367*R-0.3312640*G+0.5000000*B Cr= 0.5000000*R-0.4186880*G-0.0813120*B Cb and Cr, normally -0.5 through 0.5, are normalized to the range 0 through QuantumRange. */ primary_info.y=(double) (MaxMap+1.0)/2.0; primary_info.z=(double) (MaxMap+1.0)/2.0; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) #endif for (i=0; i <= (ssize_t) MaxMap; i++) { x_map[i].x=(MagickRealType) (0.298839*(double) i); y_map[i].x=(MagickRealType) (0.586811*(double) i); z_map[i].x=(MagickRealType) (0.114350*(double) i); x_map[i].y=(MagickRealType) (-0.1687367*(double) i); y_map[i].y=(MagickRealType) (-0.331264*(double) i); z_map[i].y=(MagickRealType) (0.500000*(double) i); x_map[i].z=(MagickRealType) (0.500000*(double) i); y_map[i].z=(MagickRealType) (-0.418688*(double) i); z_map[i].z=(MagickRealType) (-0.081312*(double) i); } break; } case Rec709YCbCrColorspace: { /* Initialize YCbCr tables (ITU-R BT.709): Y = 0.212656*R+0.715158*G+0.072186*B Cb= -0.114572*R-0.385428*G+0.500000*B Cr= 0.500000*R-0.454153*G-0.045847*B Cb and Cr, normally -0.5 through 0.5, are normalized to the range 0 through QuantumRange. */ primary_info.y=(double) (MaxMap+1.0)/2.0; primary_info.z=(double) (MaxMap+1.0)/2.0; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) #endif for (i=0; i <= (ssize_t) MaxMap; i++) { x_map[i].x=(MagickRealType) (0.212656*(double) i); y_map[i].x=(MagickRealType) (0.715158*(double) i); z_map[i].x=(MagickRealType) (0.072186*(double) i); x_map[i].y=(MagickRealType) (-0.114572*(double) i); y_map[i].y=(MagickRealType) (-0.385428*(double) i); z_map[i].y=(MagickRealType) (0.500000*(double) i); x_map[i].z=(MagickRealType) (0.500000*(double) i); y_map[i].z=(MagickRealType) (-0.454153*(double) i); z_map[i].z=(MagickRealType) (-0.045847*(double) i); } break; } case YCCColorspace: { /* Initialize YCC tables: Y = 0.298839*R+0.586811*G+0.114350*B C1= -0.298839*R-0.586811*G+0.88600*B C2= 0.70100*R-0.586811*G-0.114350*B YCC is scaled by 1.3584. C1 zero is 156 and C2 is at 137. */ primary_info.y=(double) ScaleQuantumToMap(ScaleCharToQuantum(156)); primary_info.z=(double) ScaleQuantumToMap(ScaleCharToQuantum(137)); for (i=0; i <= (ssize_t) (0.018*MaxMap); i++) { x_map[i].x=0.005382*i; y_map[i].x=0.010566*i; z_map[i].x=0.002052*i; x_map[i].y=(-0.003296)*i; y_map[i].y=(-0.006471)*i; z_map[i].y=0.009768*i; x_map[i].z=0.009410*i; y_map[i].z=(-0.007880)*i; z_map[i].z=(-0.001530)*i; } for ( ; i <= (ssize_t) MaxMap; i++) { x_map[i].x=0.298839*(1.099*i-0.099); y_map[i].x=0.586811*(1.099*i-0.099); z_map[i].x=0.114350*(1.099*i-0.099); x_map[i].y=(-0.298839)*(1.099*i-0.099); y_map[i].y=(-0.586811)*(1.099*i-0.099); z_map[i].y=0.88600*(1.099*i-0.099); x_map[i].z=0.70100*(1.099*i-0.099); y_map[i].z=(-0.586811)*(1.099*i-0.099); z_map[i].z=(-0.114350)*(1.099*i-0.099); } break; } default: { /* Linear conversion tables. */ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) #endif for (i=0; i <= (ssize_t) MaxMap; i++) { x_map[i].x=(MagickRealType) (1.0*(double) i); y_map[i].x=(MagickRealType) 0.0; z_map[i].x=(MagickRealType) 0.0; x_map[i].y=(MagickRealType) 0.0; y_map[i].y=(MagickRealType) (1.0*(double) i); z_map[i].y=(MagickRealType) 0.0; x_map[i].z=(MagickRealType) 0.0; y_map[i].z=(MagickRealType) 0.0; z_map[i].z=(MagickRealType) (1.0*(double) i); } break; } } /* Convert from sRGB. */ switch (image->storage_class) { case DirectClass: default: { /* Convert DirectClass image. */ 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++) { MagickBooleanType sync; PixelInfo pixel; register Quantum *magick_restrict q; register ssize_t x; register unsigned int blue, green, red; 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++) { red=ScaleQuantumToMap(ClampToQuantum((MagickRealType) GetPixelRed(image,q))); green=ScaleQuantumToMap(ClampToQuantum((MagickRealType) GetPixelGreen(image,q))); blue=ScaleQuantumToMap(ClampToQuantum((MagickRealType) GetPixelBlue(image,q))); pixel.red=(x_map[red].x+y_map[green].x+z_map[blue].x)+ primary_info.x; pixel.green=(x_map[red].y+y_map[green].y+z_map[blue].y)+ primary_info.y; pixel.blue=(x_map[red].z+y_map[green].z+z_map[blue].z)+ primary_info.z; SetPixelRed(image,ScaleMapToQuantum(pixel.red),q); SetPixelGreen(image,ScaleMapToQuantum(pixel.green),q); SetPixelBlue(image,ScaleMapToQuantum(pixel.blue),q); q+=GetPixelChannels(image); } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_sRGBTransformImage) #endif proceed=SetImageProgress(image,sRGBTransformImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); break; } case PseudoClass: { register unsigned int blue, green, red; /* Convert PseudoClass image. */ for (i=0; i < (ssize_t) image->colors; i++) { PixelInfo pixel; red=ScaleQuantumToMap(ClampToQuantum(image->colormap[i].red)); green=ScaleQuantumToMap(ClampToQuantum(image->colormap[i].green)); blue=ScaleQuantumToMap(ClampToQuantum(image->colormap[i].blue)); pixel.red=x_map[red].x+y_map[green].x+z_map[blue].x+primary_info.x; pixel.green=x_map[red].y+y_map[green].y+z_map[blue].y+primary_info.y; pixel.blue=x_map[red].z+y_map[green].z+z_map[blue].z+primary_info.z; image->colormap[i].red=(double) ScaleMapToQuantum(pixel.red); image->colormap[i].green=(double) ScaleMapToQuantum(pixel.green); image->colormap[i].blue=(double) ScaleMapToQuantum(pixel.blue); } (void) SyncImage(image,exception); break; } } /* Relinquish resources. */ z_map=(TransformPacket *) RelinquishMagickMemory(z_map); y_map=(TransformPacket *) RelinquishMagickMemory(y_map); x_map=(TransformPacket *) RelinquishMagickMemory(x_map); if (SetImageColorspace(image,colorspace,exception) == MagickFalse) return(MagickFalse); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e C o l o r s p a c e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageColorspace() sets the colorspace member of the Image structure. % % The format of the SetImageColorspace method is: % % MagickBooleanType SetImageColorspace(Image *image, % const ColorspaceType colorspace,ExceptiionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o colorspace: the colorspace. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType SetImageColorspace(Image *image, const ColorspaceType colorspace,ExceptionInfo *exception) { ImageType type; MagickBooleanType status; 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); if (image->colorspace == colorspace) return(MagickTrue); image->colorspace=colorspace; image->rendering_intent=UndefinedIntent; image->gamma=1.000/2.200; (void) ResetMagickMemory(&image->chromaticity,0,sizeof(image->chromaticity)); type=image->type; if (IsGrayColorspace(colorspace) != MagickFalse) { if (colorspace == LinearGRAYColorspace) image->gamma=1.000; type=GrayscaleType; } else if ((IsRGBColorspace(colorspace) != MagickFalse) || (colorspace == XYZColorspace) || (colorspace == xyYColorspace)) image->gamma=1.000; else { image->rendering_intent=PerceptualIntent; image->chromaticity.red_primary.x=0.6400; image->chromaticity.red_primary.y=0.3300; image->chromaticity.red_primary.z=0.0300; image->chromaticity.green_primary.x=0.3000; image->chromaticity.green_primary.y=0.6000; image->chromaticity.green_primary.z=0.1000; image->chromaticity.blue_primary.x=0.1500; image->chromaticity.blue_primary.y=0.0600; image->chromaticity.blue_primary.z=0.7900; image->chromaticity.white_point.x=0.3127; image->chromaticity.white_point.y=0.3290; image->chromaticity.white_point.z=0.3583; } status=SyncImagePixelCache(image,exception); image->type=type; return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e G r a y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageGray() returns MagickTrue if all the pixels in the image have the % same red, green, and blue intensities and changes the type of the image to % bi-level or grayscale. % % The format of the SetImageGray method is: % % MagickBooleanType SetImageGray(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 MagickBooleanType SetImageGray(Image *image, ExceptionInfo *exception) { const char *value; ImageType type; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (IsImageGray(image)) return(MagickTrue); if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) return(MagickFalse); value=GetImageProperty(image,"colorspace:auto-grayscale",exception); if (IsStringFalse(value) != MagickFalse) return(MagickFalse); type=IdentifyImageGray(image,exception); if (type == UndefinedType) return(MagickFalse); image->colorspace=GRAYColorspace; if (SyncImagePixelCache((Image *) image,exception) == MagickFalse) return(MagickFalse); image->type=type; return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e M o n o c h r o m e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageMonochrome() returns MagickTrue if all the pixels in the image have % the same red, green, and blue intensities and the intensity is either % 0 or QuantumRange and changes the type of the image to bi-level. % % The format of the SetImageMonochrome method is: % % MagickBooleanType SetImageMonochrome(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 MagickBooleanType SetImageMonochrome(Image *image, ExceptionInfo *exception) { const char *value; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->type == BilevelType) return(MagickTrue); if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) return(MagickFalse); value=GetImageProperty(image,"colorspace:auto-grayscale",exception); if (IsStringFalse(value) != MagickFalse) return(MagickFalse); if (IdentifyImageMonochrome(image,exception) == MagickFalse) return(MagickFalse); image->colorspace=GRAYColorspace; if (SyncImagePixelCache((Image *) image,exception) == MagickFalse) return(MagickFalse); image->type=BilevelType; return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % T r a n s f o r m I m a g e C o l o r s p a c e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % TransformImageColorspace() transforms an image colorspace, changing the % image data to reflect the new colorspace. % % The format of the TransformImageColorspace method is: % % MagickBooleanType TransformImageColorspace(Image *image, % const ColorspaceType colorspace,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o colorspace: the colorspace. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType TransformImageColorspace(Image *image, const ColorspaceType colorspace,ExceptionInfo *exception) { MagickBooleanType status; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->colorspace == colorspace) return(SetImageColorspace(image,colorspace,exception)); (void) DeleteImageProfile(image,"icc"); (void) DeleteImageProfile(image,"icm"); if (colorspace == LinearGRAYColorspace) return(GrayscaleImage(image,Rec709LuminancePixelIntensityMethod,exception)); if (colorspace == GRAYColorspace) return(GrayscaleImage(image,Rec709LumaPixelIntensityMethod,exception)); if (colorspace == UndefinedColorspace) return(SetImageColorspace(image,colorspace,exception)); /* Convert the reference image from an alternate colorspace to sRGB. */ if (IssRGBColorspace(colorspace) != MagickFalse) return(TransformsRGBImage(image,exception)); status=MagickTrue; if (IssRGBColorspace(image->colorspace) == MagickFalse) status=TransformsRGBImage(image,exception); if (status == MagickFalse) return(status); /* Convert the reference image from sRGB to an alternate colorspace. */ if (sRGBTransformImage(image,colorspace,exception) == MagickFalse) status=MagickFalse; return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + T r a n s f o r m s R G B I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % TransformsRGBImage() converts the reference image from an alternate % colorspace to sRGB. The transformation matrices are not the standard ones: % the weights are rescaled to normalize the range of the transformed values % to be [0..QuantumRange]. % % The format of the TransformsRGBImage method is: % % MagickBooleanType TransformsRGBImage(Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ static inline void ConvertCMYToRGB(const double cyan,const double magenta, const double yellow,double *red,double *green,double *blue) { *red=QuantumRange*(1.0-cyan); *green=QuantumRange*(1.0-magenta); *blue=QuantumRange*(1.0-yellow); } static inline void ConvertLMSToXYZ(const double L,const double M,const double S, double *X,double *Y,double *Z) { *X=1.096123820835514*L-0.278869000218287*M+0.182745179382773*S; *Y=0.454369041975359*L+0.473533154307412*M+0.072097803717229*S; *Z=(-0.009627608738429)*L-0.005698031216113*M+1.015325639954543*S; } static inline void ConvertLMSToRGB(const double L,const double M, const double S,double *red,double *green,double *blue) { double X, Y, Z; ConvertLMSToXYZ(L,M,S,&X,&Y,&Z); ConvertXYZToRGB(X,Y,Z,red,green,blue); } static inline void ConvertLuvToRGB(const double L,const double u, const double v,double *red,double *green,double *blue) { double X, Y, Z; ConvertLuvToXYZ(100.0*L,354.0*u-134.0,262.0*v-140.0,&X,&Y,&Z); ConvertXYZToRGB(X,Y,Z,red,green,blue); } static inline ssize_t RoundToYCC(const double value) { if (value <= 0.0) return(0); if (value >= 1388.0) return(1388); return((ssize_t) (value+0.5)); } static inline void ConvertLabToRGB(const double L,const double a, const double b,double *red,double *green,double *blue) { double X, Y, Z; ConvertLabToXYZ(100.0*L,255.0*(a-0.5),255.0*(b-0.5),&X,&Y,&Z); ConvertXYZToRGB(X,Y,Z,red,green,blue); } static inline void ConvertxyYToRGB(const double low_x,const double low_y, const double cap_Y,double *red,double *green,double *blue) { double gamma, X, Y, Z; gamma=PerceptibleReciprocal(low_y); X=gamma*cap_Y*low_x; Y=cap_Y; Z=gamma*cap_Y*(1.0-low_x-low_y); ConvertXYZToRGB(X,Y,Z,red,green,blue); } static void ConvertYPbPrToRGB(const double Y,const double Pb,const double Pr, double *red,double *green,double *blue) { *red=QuantumRange*(0.99999999999914679361*Y-1.2188941887145875e-06*(Pb-0.5)+ 1.4019995886561440468*(Pr-0.5)); *green=QuantumRange*(0.99999975910502514331*Y-0.34413567816504303521*(Pb-0.5)- 0.71413649331646789076*(Pr-0.5)); *blue=QuantumRange*(1.00000124040004623180*Y+1.77200006607230409200*(Pb-0.5)+ 2.1453384174593273e-06*(Pr-0.5)); } static void ConvertYCbCrToRGB(const double Y,const double Cb, const double Cr,double *red,double *green,double *blue) { ConvertYPbPrToRGB(Y,Cb,Cr,red,green,blue); } static void ConvertYIQToRGB(const double Y,const double I,const double Q, double *red,double *green,double *blue) { *red=QuantumRange*(Y+0.9562957197589482261*(I-0.5)+0.6210244164652610754* (Q-0.5)); *green=QuantumRange*(Y-0.2721220993185104464*(I-0.5)-0.6473805968256950427* (Q-0.5)); *blue=QuantumRange*(Y-1.1069890167364901945*(I-0.5)+1.7046149983646481374* (Q-0.5)); } static void ConvertYDbDrToRGB(const double Y,const double Db,const double Dr, double *red,double *green,double *blue) { *red=QuantumRange*(Y+9.2303716147657e-05*(Db-0.5)- 0.52591263066186533*(Dr-0.5)); *green=QuantumRange*(Y-0.12913289889050927*(Db-0.5)+ 0.26789932820759876*(Dr-0.5)); *blue=QuantumRange*(Y+0.66467905997895482*(Db-0.5)- 7.9202543533108e-05*(Dr-0.5)); } static void ConvertYUVToRGB(const double Y,const double U,const double V, double *red,double *green,double *blue) { *red=QuantumRange*(Y-3.945707070708279e-05*(U-0.5)+1.1398279671717170825* (V-0.5)); *green=QuantumRange*(Y-0.3946101641414141437*(U-0.5)-0.5805003156565656797* (V-0.5)); *blue=QuantumRange*(Y+2.0319996843434342537*(U-0.5)-4.813762626262513e-04* (V-0.5)); } static MagickBooleanType TransformsRGBImage(Image *image, ExceptionInfo *exception) { #define TransformsRGBImageTag "Transform/Image" static const float YCCMap[1389] = { 0.000000f, 0.000720f, 0.001441f, 0.002161f, 0.002882f, 0.003602f, 0.004323f, 0.005043f, 0.005764f, 0.006484f, 0.007205f, 0.007925f, 0.008646f, 0.009366f, 0.010086f, 0.010807f, 0.011527f, 0.012248f, 0.012968f, 0.013689f, 0.014409f, 0.015130f, 0.015850f, 0.016571f, 0.017291f, 0.018012f, 0.018732f, 0.019452f, 0.020173f, 0.020893f, 0.021614f, 0.022334f, 0.023055f, 0.023775f, 0.024496f, 0.025216f, 0.025937f, 0.026657f, 0.027378f, 0.028098f, 0.028818f, 0.029539f, 0.030259f, 0.030980f, 0.031700f, 0.032421f, 0.033141f, 0.033862f, 0.034582f, 0.035303f, 0.036023f, 0.036744f, 0.037464f, 0.038184f, 0.038905f, 0.039625f, 0.040346f, 0.041066f, 0.041787f, 0.042507f, 0.043228f, 0.043948f, 0.044669f, 0.045389f, 0.046110f, 0.046830f, 0.047550f, 0.048271f, 0.048991f, 0.049712f, 0.050432f, 0.051153f, 0.051873f, 0.052594f, 0.053314f, 0.054035f, 0.054755f, 0.055476f, 0.056196f, 0.056916f, 0.057637f, 0.058357f, 0.059078f, 0.059798f, 0.060519f, 0.061239f, 0.061960f, 0.062680f, 0.063401f, 0.064121f, 0.064842f, 0.065562f, 0.066282f, 0.067003f, 0.067723f, 0.068444f, 0.069164f, 0.069885f, 0.070605f, 0.071326f, 0.072046f, 0.072767f, 0.073487f, 0.074207f, 0.074928f, 0.075648f, 0.076369f, 0.077089f, 0.077810f, 0.078530f, 0.079251f, 0.079971f, 0.080692f, 0.081412f, 0.082133f, 0.082853f, 0.083573f, 0.084294f, 0.085014f, 0.085735f, 0.086455f, 0.087176f, 0.087896f, 0.088617f, 0.089337f, 0.090058f, 0.090778f, 0.091499f, 0.092219f, 0.092939f, 0.093660f, 0.094380f, 0.095101f, 0.095821f, 0.096542f, 0.097262f, 0.097983f, 0.098703f, 0.099424f, 0.100144f, 0.100865f, 0.101585f, 0.102305f, 0.103026f, 0.103746f, 0.104467f, 0.105187f, 0.105908f, 0.106628f, 0.107349f, 0.108069f, 0.108790f, 0.109510f, 0.110231f, 0.110951f, 0.111671f, 0.112392f, 0.113112f, 0.113833f, 0.114553f, 0.115274f, 0.115994f, 0.116715f, 0.117435f, 0.118156f, 0.118876f, 0.119597f, 0.120317f, 0.121037f, 0.121758f, 0.122478f, 0.123199f, 0.123919f, 0.124640f, 0.125360f, 0.126081f, 0.126801f, 0.127522f, 0.128242f, 0.128963f, 0.129683f, 0.130403f, 0.131124f, 0.131844f, 0.132565f, 0.133285f, 0.134006f, 0.134726f, 0.135447f, 0.136167f, 0.136888f, 0.137608f, 0.138329f, 0.139049f, 0.139769f, 0.140490f, 0.141210f, 0.141931f, 0.142651f, 0.143372f, 0.144092f, 0.144813f, 0.145533f, 0.146254f, 0.146974f, 0.147695f, 0.148415f, 0.149135f, 0.149856f, 0.150576f, 0.151297f, 0.152017f, 0.152738f, 0.153458f, 0.154179f, 0.154899f, 0.155620f, 0.156340f, 0.157061f, 0.157781f, 0.158501f, 0.159222f, 0.159942f, 0.160663f, 0.161383f, 0.162104f, 0.162824f, 0.163545f, 0.164265f, 0.164986f, 0.165706f, 0.166427f, 0.167147f, 0.167867f, 0.168588f, 0.169308f, 0.170029f, 0.170749f, 0.171470f, 0.172190f, 0.172911f, 0.173631f, 0.174352f, 0.175072f, 0.175793f, 0.176513f, 0.177233f, 0.177954f, 0.178674f, 0.179395f, 0.180115f, 0.180836f, 0.181556f, 0.182277f, 0.182997f, 0.183718f, 0.184438f, 0.185159f, 0.185879f, 0.186599f, 0.187320f, 0.188040f, 0.188761f, 0.189481f, 0.190202f, 0.190922f, 0.191643f, 0.192363f, 0.193084f, 0.193804f, 0.194524f, 0.195245f, 0.195965f, 0.196686f, 0.197406f, 0.198127f, 0.198847f, 0.199568f, 0.200288f, 0.201009f, 0.201729f, 0.202450f, 0.203170f, 0.203890f, 0.204611f, 0.205331f, 0.206052f, 0.206772f, 0.207493f, 0.208213f, 0.208934f, 0.209654f, 0.210375f, 0.211095f, 0.211816f, 0.212536f, 0.213256f, 0.213977f, 0.214697f, 0.215418f, 0.216138f, 0.216859f, 0.217579f, 0.218300f, 0.219020f, 0.219741f, 0.220461f, 0.221182f, 0.221902f, 0.222622f, 0.223343f, 0.224063f, 0.224784f, 0.225504f, 0.226225f, 0.226945f, 0.227666f, 0.228386f, 0.229107f, 0.229827f, 0.230548f, 0.231268f, 0.231988f, 0.232709f, 0.233429f, 0.234150f, 0.234870f, 0.235591f, 0.236311f, 0.237032f, 0.237752f, 0.238473f, 0.239193f, 0.239914f, 0.240634f, 0.241354f, 0.242075f, 0.242795f, 0.243516f, 0.244236f, 0.244957f, 0.245677f, 0.246398f, 0.247118f, 0.247839f, 0.248559f, 0.249280f, 0.250000f, 0.250720f, 0.251441f, 0.252161f, 0.252882f, 0.253602f, 0.254323f, 0.255043f, 0.255764f, 0.256484f, 0.257205f, 0.257925f, 0.258646f, 0.259366f, 0.260086f, 0.260807f, 0.261527f, 0.262248f, 0.262968f, 0.263689f, 0.264409f, 0.265130f, 0.265850f, 0.266571f, 0.267291f, 0.268012f, 0.268732f, 0.269452f, 0.270173f, 0.270893f, 0.271614f, 0.272334f, 0.273055f, 0.273775f, 0.274496f, 0.275216f, 0.275937f, 0.276657f, 0.277378f, 0.278098f, 0.278818f, 0.279539f, 0.280259f, 0.280980f, 0.281700f, 0.282421f, 0.283141f, 0.283862f, 0.284582f, 0.285303f, 0.286023f, 0.286744f, 0.287464f, 0.288184f, 0.288905f, 0.289625f, 0.290346f, 0.291066f, 0.291787f, 0.292507f, 0.293228f, 0.293948f, 0.294669f, 0.295389f, 0.296109f, 0.296830f, 0.297550f, 0.298271f, 0.298991f, 0.299712f, 0.300432f, 0.301153f, 0.301873f, 0.302594f, 0.303314f, 0.304035f, 0.304755f, 0.305476f, 0.306196f, 0.306916f, 0.307637f, 0.308357f, 0.309078f, 0.309798f, 0.310519f, 0.311239f, 0.311960f, 0.312680f, 0.313401f, 0.314121f, 0.314842f, 0.315562f, 0.316282f, 0.317003f, 0.317723f, 0.318444f, 0.319164f, 0.319885f, 0.320605f, 0.321326f, 0.322046f, 0.322767f, 0.323487f, 0.324207f, 0.324928f, 0.325648f, 0.326369f, 0.327089f, 0.327810f, 0.328530f, 0.329251f, 0.329971f, 0.330692f, 0.331412f, 0.332133f, 0.332853f, 0.333573f, 0.334294f, 0.335014f, 0.335735f, 0.336455f, 0.337176f, 0.337896f, 0.338617f, 0.339337f, 0.340058f, 0.340778f, 0.341499f, 0.342219f, 0.342939f, 0.343660f, 0.344380f, 0.345101f, 0.345821f, 0.346542f, 0.347262f, 0.347983f, 0.348703f, 0.349424f, 0.350144f, 0.350865f, 0.351585f, 0.352305f, 0.353026f, 0.353746f, 0.354467f, 0.355187f, 0.355908f, 0.356628f, 0.357349f, 0.358069f, 0.358790f, 0.359510f, 0.360231f, 0.360951f, 0.361671f, 0.362392f, 0.363112f, 0.363833f, 0.364553f, 0.365274f, 0.365994f, 0.366715f, 0.367435f, 0.368156f, 0.368876f, 0.369597f, 0.370317f, 0.371037f, 0.371758f, 0.372478f, 0.373199f, 0.373919f, 0.374640f, 0.375360f, 0.376081f, 0.376801f, 0.377522f, 0.378242f, 0.378963f, 0.379683f, 0.380403f, 0.381124f, 0.381844f, 0.382565f, 0.383285f, 0.384006f, 0.384726f, 0.385447f, 0.386167f, 0.386888f, 0.387608f, 0.388329f, 0.389049f, 0.389769f, 0.390490f, 0.391210f, 0.391931f, 0.392651f, 0.393372f, 0.394092f, 0.394813f, 0.395533f, 0.396254f, 0.396974f, 0.397695f, 0.398415f, 0.399135f, 0.399856f, 0.400576f, 0.401297f, 0.402017f, 0.402738f, 0.403458f, 0.404179f, 0.404899f, 0.405620f, 0.406340f, 0.407061f, 0.407781f, 0.408501f, 0.409222f, 0.409942f, 0.410663f, 0.411383f, 0.412104f, 0.412824f, 0.413545f, 0.414265f, 0.414986f, 0.415706f, 0.416427f, 0.417147f, 0.417867f, 0.418588f, 0.419308f, 0.420029f, 0.420749f, 0.421470f, 0.422190f, 0.422911f, 0.423631f, 0.424352f, 0.425072f, 0.425793f, 0.426513f, 0.427233f, 0.427954f, 0.428674f, 0.429395f, 0.430115f, 0.430836f, 0.431556f, 0.432277f, 0.432997f, 0.433718f, 0.434438f, 0.435158f, 0.435879f, 0.436599f, 0.437320f, 0.438040f, 0.438761f, 0.439481f, 0.440202f, 0.440922f, 0.441643f, 0.442363f, 0.443084f, 0.443804f, 0.444524f, 0.445245f, 0.445965f, 0.446686f, 0.447406f, 0.448127f, 0.448847f, 0.449568f, 0.450288f, 0.451009f, 0.451729f, 0.452450f, 0.453170f, 0.453891f, 0.454611f, 0.455331f, 0.456052f, 0.456772f, 0.457493f, 0.458213f, 0.458934f, 0.459654f, 0.460375f, 0.461095f, 0.461816f, 0.462536f, 0.463256f, 0.463977f, 0.464697f, 0.465418f, 0.466138f, 0.466859f, 0.467579f, 0.468300f, 0.469020f, 0.469741f, 0.470461f, 0.471182f, 0.471902f, 0.472622f, 0.473343f, 0.474063f, 0.474784f, 0.475504f, 0.476225f, 0.476945f, 0.477666f, 0.478386f, 0.479107f, 0.479827f, 0.480548f, 0.481268f, 0.481988f, 0.482709f, 0.483429f, 0.484150f, 0.484870f, 0.485591f, 0.486311f, 0.487032f, 0.487752f, 0.488473f, 0.489193f, 0.489914f, 0.490634f, 0.491354f, 0.492075f, 0.492795f, 0.493516f, 0.494236f, 0.494957f, 0.495677f, 0.496398f, 0.497118f, 0.497839f, 0.498559f, 0.499280f, 0.500000f, 0.500720f, 0.501441f, 0.502161f, 0.502882f, 0.503602f, 0.504323f, 0.505043f, 0.505764f, 0.506484f, 0.507205f, 0.507925f, 0.508646f, 0.509366f, 0.510086f, 0.510807f, 0.511527f, 0.512248f, 0.512968f, 0.513689f, 0.514409f, 0.515130f, 0.515850f, 0.516571f, 0.517291f, 0.518012f, 0.518732f, 0.519452f, 0.520173f, 0.520893f, 0.521614f, 0.522334f, 0.523055f, 0.523775f, 0.524496f, 0.525216f, 0.525937f, 0.526657f, 0.527378f, 0.528098f, 0.528818f, 0.529539f, 0.530259f, 0.530980f, 0.531700f, 0.532421f, 0.533141f, 0.533862f, 0.534582f, 0.535303f, 0.536023f, 0.536744f, 0.537464f, 0.538184f, 0.538905f, 0.539625f, 0.540346f, 0.541066f, 0.541787f, 0.542507f, 0.543228f, 0.543948f, 0.544669f, 0.545389f, 0.546109f, 0.546830f, 0.547550f, 0.548271f, 0.548991f, 0.549712f, 0.550432f, 0.551153f, 0.551873f, 0.552594f, 0.553314f, 0.554035f, 0.554755f, 0.555476f, 0.556196f, 0.556916f, 0.557637f, 0.558357f, 0.559078f, 0.559798f, 0.560519f, 0.561239f, 0.561960f, 0.562680f, 0.563401f, 0.564121f, 0.564842f, 0.565562f, 0.566282f, 0.567003f, 0.567723f, 0.568444f, 0.569164f, 0.569885f, 0.570605f, 0.571326f, 0.572046f, 0.572767f, 0.573487f, 0.574207f, 0.574928f, 0.575648f, 0.576369f, 0.577089f, 0.577810f, 0.578530f, 0.579251f, 0.579971f, 0.580692f, 0.581412f, 0.582133f, 0.582853f, 0.583573f, 0.584294f, 0.585014f, 0.585735f, 0.586455f, 0.587176f, 0.587896f, 0.588617f, 0.589337f, 0.590058f, 0.590778f, 0.591499f, 0.592219f, 0.592939f, 0.593660f, 0.594380f, 0.595101f, 0.595821f, 0.596542f, 0.597262f, 0.597983f, 0.598703f, 0.599424f, 0.600144f, 0.600865f, 0.601585f, 0.602305f, 0.603026f, 0.603746f, 0.604467f, 0.605187f, 0.605908f, 0.606628f, 0.607349f, 0.608069f, 0.608790f, 0.609510f, 0.610231f, 0.610951f, 0.611671f, 0.612392f, 0.613112f, 0.613833f, 0.614553f, 0.615274f, 0.615994f, 0.616715f, 0.617435f, 0.618156f, 0.618876f, 0.619597f, 0.620317f, 0.621037f, 0.621758f, 0.622478f, 0.623199f, 0.623919f, 0.624640f, 0.625360f, 0.626081f, 0.626801f, 0.627522f, 0.628242f, 0.628963f, 0.629683f, 0.630403f, 0.631124f, 0.631844f, 0.632565f, 0.633285f, 0.634006f, 0.634726f, 0.635447f, 0.636167f, 0.636888f, 0.637608f, 0.638329f, 0.639049f, 0.639769f, 0.640490f, 0.641210f, 0.641931f, 0.642651f, 0.643372f, 0.644092f, 0.644813f, 0.645533f, 0.646254f, 0.646974f, 0.647695f, 0.648415f, 0.649135f, 0.649856f, 0.650576f, 0.651297f, 0.652017f, 0.652738f, 0.653458f, 0.654179f, 0.654899f, 0.655620f, 0.656340f, 0.657061f, 0.657781f, 0.658501f, 0.659222f, 0.659942f, 0.660663f, 0.661383f, 0.662104f, 0.662824f, 0.663545f, 0.664265f, 0.664986f, 0.665706f, 0.666427f, 0.667147f, 0.667867f, 0.668588f, 0.669308f, 0.670029f, 0.670749f, 0.671470f, 0.672190f, 0.672911f, 0.673631f, 0.674352f, 0.675072f, 0.675793f, 0.676513f, 0.677233f, 0.677954f, 0.678674f, 0.679395f, 0.680115f, 0.680836f, 0.681556f, 0.682277f, 0.682997f, 0.683718f, 0.684438f, 0.685158f, 0.685879f, 0.686599f, 0.687320f, 0.688040f, 0.688761f, 0.689481f, 0.690202f, 0.690922f, 0.691643f, 0.692363f, 0.693084f, 0.693804f, 0.694524f, 0.695245f, 0.695965f, 0.696686f, 0.697406f, 0.698127f, 0.698847f, 0.699568f, 0.700288f, 0.701009f, 0.701729f, 0.702450f, 0.703170f, 0.703891f, 0.704611f, 0.705331f, 0.706052f, 0.706772f, 0.707493f, 0.708213f, 0.708934f, 0.709654f, 0.710375f, 0.711095f, 0.711816f, 0.712536f, 0.713256f, 0.713977f, 0.714697f, 0.715418f, 0.716138f, 0.716859f, 0.717579f, 0.718300f, 0.719020f, 0.719741f, 0.720461f, 0.721182f, 0.721902f, 0.722622f, 0.723343f, 0.724063f, 0.724784f, 0.725504f, 0.726225f, 0.726945f, 0.727666f, 0.728386f, 0.729107f, 0.729827f, 0.730548f, 0.731268f, 0.731988f, 0.732709f, 0.733429f, 0.734150f, 0.734870f, 0.735591f, 0.736311f, 0.737032f, 0.737752f, 0.738473f, 0.739193f, 0.739914f, 0.740634f, 0.741354f, 0.742075f, 0.742795f, 0.743516f, 0.744236f, 0.744957f, 0.745677f, 0.746398f, 0.747118f, 0.747839f, 0.748559f, 0.749280f, 0.750000f, 0.750720f, 0.751441f, 0.752161f, 0.752882f, 0.753602f, 0.754323f, 0.755043f, 0.755764f, 0.756484f, 0.757205f, 0.757925f, 0.758646f, 0.759366f, 0.760086f, 0.760807f, 0.761527f, 0.762248f, 0.762968f, 0.763689f, 0.764409f, 0.765130f, 0.765850f, 0.766571f, 0.767291f, 0.768012f, 0.768732f, 0.769452f, 0.770173f, 0.770893f, 0.771614f, 0.772334f, 0.773055f, 0.773775f, 0.774496f, 0.775216f, 0.775937f, 0.776657f, 0.777378f, 0.778098f, 0.778818f, 0.779539f, 0.780259f, 0.780980f, 0.781700f, 0.782421f, 0.783141f, 0.783862f, 0.784582f, 0.785303f, 0.786023f, 0.786744f, 0.787464f, 0.788184f, 0.788905f, 0.789625f, 0.790346f, 0.791066f, 0.791787f, 0.792507f, 0.793228f, 0.793948f, 0.794669f, 0.795389f, 0.796109f, 0.796830f, 0.797550f, 0.798271f, 0.798991f, 0.799712f, 0.800432f, 0.801153f, 0.801873f, 0.802594f, 0.803314f, 0.804035f, 0.804755f, 0.805476f, 0.806196f, 0.806916f, 0.807637f, 0.808357f, 0.809078f, 0.809798f, 0.810519f, 0.811239f, 0.811960f, 0.812680f, 0.813401f, 0.814121f, 0.814842f, 0.815562f, 0.816282f, 0.817003f, 0.817723f, 0.818444f, 0.819164f, 0.819885f, 0.820605f, 0.821326f, 0.822046f, 0.822767f, 0.823487f, 0.824207f, 0.824928f, 0.825648f, 0.826369f, 0.827089f, 0.827810f, 0.828530f, 0.829251f, 0.829971f, 0.830692f, 0.831412f, 0.832133f, 0.832853f, 0.833573f, 0.834294f, 0.835014f, 0.835735f, 0.836455f, 0.837176f, 0.837896f, 0.838617f, 0.839337f, 0.840058f, 0.840778f, 0.841499f, 0.842219f, 0.842939f, 0.843660f, 0.844380f, 0.845101f, 0.845821f, 0.846542f, 0.847262f, 0.847983f, 0.848703f, 0.849424f, 0.850144f, 0.850865f, 0.851585f, 0.852305f, 0.853026f, 0.853746f, 0.854467f, 0.855187f, 0.855908f, 0.856628f, 0.857349f, 0.858069f, 0.858790f, 0.859510f, 0.860231f, 0.860951f, 0.861671f, 0.862392f, 0.863112f, 0.863833f, 0.864553f, 0.865274f, 0.865994f, 0.866715f, 0.867435f, 0.868156f, 0.868876f, 0.869597f, 0.870317f, 0.871037f, 0.871758f, 0.872478f, 0.873199f, 0.873919f, 0.874640f, 0.875360f, 0.876081f, 0.876801f, 0.877522f, 0.878242f, 0.878963f, 0.879683f, 0.880403f, 0.881124f, 0.881844f, 0.882565f, 0.883285f, 0.884006f, 0.884726f, 0.885447f, 0.886167f, 0.886888f, 0.887608f, 0.888329f, 0.889049f, 0.889769f, 0.890490f, 0.891210f, 0.891931f, 0.892651f, 0.893372f, 0.894092f, 0.894813f, 0.895533f, 0.896254f, 0.896974f, 0.897695f, 0.898415f, 0.899135f, 0.899856f, 0.900576f, 0.901297f, 0.902017f, 0.902738f, 0.903458f, 0.904179f, 0.904899f, 0.905620f, 0.906340f, 0.907061f, 0.907781f, 0.908501f, 0.909222f, 0.909942f, 0.910663f, 0.911383f, 0.912104f, 0.912824f, 0.913545f, 0.914265f, 0.914986f, 0.915706f, 0.916427f, 0.917147f, 0.917867f, 0.918588f, 0.919308f, 0.920029f, 0.920749f, 0.921470f, 0.922190f, 0.922911f, 0.923631f, 0.924352f, 0.925072f, 0.925793f, 0.926513f, 0.927233f, 0.927954f, 0.928674f, 0.929395f, 0.930115f, 0.930836f, 0.931556f, 0.932277f, 0.932997f, 0.933718f, 0.934438f, 0.935158f, 0.935879f, 0.936599f, 0.937320f, 0.938040f, 0.938761f, 0.939481f, 0.940202f, 0.940922f, 0.941643f, 0.942363f, 0.943084f, 0.943804f, 0.944524f, 0.945245f, 0.945965f, 0.946686f, 0.947406f, 0.948127f, 0.948847f, 0.949568f, 0.950288f, 0.951009f, 0.951729f, 0.952450f, 0.953170f, 0.953891f, 0.954611f, 0.955331f, 0.956052f, 0.956772f, 0.957493f, 0.958213f, 0.958934f, 0.959654f, 0.960375f, 0.961095f, 0.961816f, 0.962536f, 0.963256f, 0.963977f, 0.964697f, 0.965418f, 0.966138f, 0.966859f, 0.967579f, 0.968300f, 0.969020f, 0.969741f, 0.970461f, 0.971182f, 0.971902f, 0.972622f, 0.973343f, 0.974063f, 0.974784f, 0.975504f, 0.976225f, 0.976945f, 0.977666f, 0.978386f, 0.979107f, 0.979827f, 0.980548f, 0.981268f, 0.981988f, 0.982709f, 0.983429f, 0.984150f, 0.984870f, 0.985591f, 0.986311f, 0.987032f, 0.987752f, 0.988473f, 0.989193f, 0.989914f, 0.990634f, 0.991354f, 0.992075f, 0.992795f, 0.993516f, 0.994236f, 0.994957f, 0.995677f, 0.996398f, 0.997118f, 0.997839f, 0.998559f, 0.999280f, 1.000000f }; CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; register ssize_t i; ssize_t y; TransformPacket *y_map, *x_map, *z_map; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=MagickTrue; progress=0; switch (image->colorspace) { case CMYKColorspace: { PixelInfo zero; /* Transform image from CMYK to sRGB. */ if (image->storage_class == PseudoClass) { if (SyncImage(image,exception) == MagickFalse) return(MagickFalse); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); } GetPixelInfo(image,&zero); 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++) { MagickBooleanType sync; PixelInfo pixel; register ssize_t x; register 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); ConvertCMYKToRGB(&pixel); SetPixelViaPixelInfo(image,&pixel,q); q+=GetPixelChannels(image); } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); if (SetImageColorspace(image,sRGBColorspace,exception) == MagickFalse) return(MagickFalse); return(status); } case LinearGRAYColorspace: case GRAYColorspace: { /* Transform linear GRAY to sRGB colorspace. */ if (image->storage_class == PseudoClass) { if (SyncImage(image,exception) == MagickFalse) return(MagickFalse); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); } if (SetImageColorspace(image,sRGBColorspace,exception) == MagickFalse) return(MagickFalse); 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++) { MagickBooleanType sync; register ssize_t x; register 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; } for (x=(ssize_t) image->columns; x != 0; x--) { MagickRealType gray; gray=(MagickRealType) GetPixelGray(image,q); if ((image->intensity == Rec601LuminancePixelIntensityMethod) || (image->intensity == Rec709LuminancePixelIntensityMethod)) gray=EncodePixelGamma(gray); SetPixelRed(image,ClampToQuantum(gray),q); SetPixelGreen(image,ClampToQuantum(gray),q); SetPixelBlue(image,ClampToQuantum(gray),q); q+=GetPixelChannels(image); } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); if (SetImageColorspace(image,sRGBColorspace,exception) == MagickFalse) return(MagickFalse); return(status); } case CMYColorspace: case HCLColorspace: case HCLpColorspace: case HSBColorspace: case HSIColorspace: case HSLColorspace: case HSVColorspace: case HWBColorspace: case LabColorspace: case LCHColorspace: case LCHabColorspace: case LCHuvColorspace: case LMSColorspace: case LuvColorspace: case xyYColorspace: case XYZColorspace: case YCbCrColorspace: case YDbDrColorspace: case YIQColorspace: case YPbPrColorspace: case YUVColorspace: { /* Transform image from source colorspace to sRGB. */ if (image->storage_class == PseudoClass) { if (SyncImage(image,exception) == MagickFalse) return(MagickFalse); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); } 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++) { MagickBooleanType sync; register ssize_t x; register 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; } for (x=0; x < (ssize_t) image->columns; x++) { double blue, green, red, X, Y, Z; X=QuantumScale*GetPixelRed(image,q); Y=QuantumScale*GetPixelGreen(image,q); Z=QuantumScale*GetPixelBlue(image,q); switch (image->colorspace) { case CMYColorspace: { ConvertCMYToRGB(X,Y,Z,&red,&green,&blue); break; } case HCLColorspace: { ConvertHCLToRGB(X,Y,Z,&red,&green,&blue); break; } case HCLpColorspace: { ConvertHCLpToRGB(X,Y,Z,&red,&green,&blue); break; } case HSBColorspace: { ConvertHSBToRGB(X,Y,Z,&red,&green,&blue); break; } case HSIColorspace: { ConvertHSIToRGB(X,Y,Z,&red,&green,&blue); break; } case HSLColorspace: { ConvertHSLToRGB(X,Y,Z,&red,&green,&blue); break; } case HSVColorspace: { ConvertHSVToRGB(X,Y,Z,&red,&green,&blue); break; } case HWBColorspace: { ConvertHWBToRGB(X,Y,Z,&red,&green,&blue); break; } case LabColorspace: { ConvertLabToRGB(X,Y,Z,&red,&green,&blue); break; } case LCHColorspace: case LCHabColorspace: { ConvertLCHabToRGB(X,Y,Z,&red,&green,&blue); break; } case LCHuvColorspace: { ConvertLCHuvToRGB(X,Y,Z,&red,&green,&blue); break; } case LMSColorspace: { ConvertLMSToRGB(X,Y,Z,&red,&green,&blue); break; } case LuvColorspace: { ConvertLuvToRGB(X,Y,Z,&red,&green,&blue); break; } case xyYColorspace: { ConvertxyYToRGB(X,Y,Z,&red,&green,&blue); break; } case XYZColorspace: { ConvertXYZToRGB(X,Y,Z,&red,&green,&blue); break; } case YCbCrColorspace: { ConvertYCbCrToRGB(X,Y,Z,&red,&green,&blue); break; } case YDbDrColorspace: { ConvertYDbDrToRGB(X,Y,Z,&red,&green,&blue); break; } case YIQColorspace: { ConvertYIQToRGB(X,Y,Z,&red,&green,&blue); break; } case YPbPrColorspace: { ConvertYPbPrToRGB(X,Y,Z,&red,&green,&blue); break; } case YUVColorspace: { ConvertYUVToRGB(X,Y,Z,&red,&green,&blue); break; } default: { red=QuantumRange*X; green=QuantumRange*Y; blue=QuantumRange*Z; break; } } SetPixelRed(image,ClampToQuantum(red),q); SetPixelGreen(image,ClampToQuantum(green),q); SetPixelBlue(image,ClampToQuantum(blue),q); q+=GetPixelChannels(image); } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); if (SetImageColorspace(image,sRGBColorspace,exception) == MagickFalse) return(MagickFalse); return(status); } case LogColorspace: { const char *value; double black, density, film_gamma, gamma, reference_black, reference_white; Quantum *logmap; /* Transform Log to sRGB colorspace. */ density=DisplayGamma; gamma=DisplayGamma; value=GetImageProperty(image,"gamma",exception); if (value != (const char *) NULL) gamma=PerceptibleReciprocal(StringToDouble(value,(char **) NULL)); film_gamma=FilmGamma; value=GetImageProperty(image,"film-gamma",exception); if (value != (const char *) NULL) film_gamma=StringToDouble(value,(char **) NULL); reference_black=ReferenceBlack; value=GetImageProperty(image,"reference-black",exception); if (value != (const char *) NULL) reference_black=StringToDouble(value,(char **) NULL); reference_white=ReferenceWhite; value=GetImageProperty(image,"reference-white",exception); if (value != (const char *) NULL) reference_white=StringToDouble(value,(char **) NULL); logmap=(Quantum *) AcquireQuantumMemory((size_t) MaxMap+1UL, sizeof(*logmap)); if (logmap == (Quantum *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); black=pow(10.0,(reference_black-reference_white)*(gamma/density)*0.002/ film_gamma); for (i=0; i <= (ssize_t) (reference_black*MaxMap/1024.0); i++) logmap[i]=(Quantum) 0; for ( ; i < (ssize_t) (reference_white*MaxMap/1024.0); i++) logmap[i]=ClampToQuantum(QuantumRange/(1.0-black)* (pow(10.0,(1024.0*i/MaxMap-reference_white)*(gamma/density)*0.002/ film_gamma)-black)); for ( ; i <= (ssize_t) MaxMap; i++) logmap[i]=QuantumRange; if (image->storage_class == PseudoClass) { if (SyncImage(image,exception) == MagickFalse) return(MagickFalse); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); } 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++) { MagickBooleanType sync; register ssize_t x; register 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; } for (x=(ssize_t) image->columns; x != 0; x--) { double blue, green, red; red=(double) logmap[ScaleQuantumToMap(GetPixelRed(image,q))]; green=(double) logmap[ScaleQuantumToMap(GetPixelGreen(image,q))]; blue=(double) logmap[ScaleQuantumToMap(GetPixelBlue(image,q))]; SetPixelRed(image,ClampToQuantum(EncodePixelGamma((MagickRealType) red)),q); SetPixelGreen(image,ClampToQuantum(EncodePixelGamma((MagickRealType) green)),q); SetPixelBlue(image,ClampToQuantum(EncodePixelGamma((MagickRealType) blue)),q); q+=GetPixelChannels(image); } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); logmap=(Quantum *) RelinquishMagickMemory(logmap); if (SetImageColorspace(image,sRGBColorspace,exception) == MagickFalse) return(MagickFalse); return(status); } case RGBColorspace: case scRGBColorspace: { /* Transform linear RGB to sRGB colorspace. */ if (image->storage_class == PseudoClass) { if (SyncImage(image,exception) == MagickFalse) return(MagickFalse); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); } 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++) { MagickBooleanType sync; register ssize_t x; register 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; } for (x=(ssize_t) image->columns; x != 0; x--) { double blue, green, red; red=EncodePixelGamma((MagickRealType) GetPixelRed(image,q)); green=EncodePixelGamma((MagickRealType) GetPixelGreen(image,q)); blue=EncodePixelGamma((MagickRealType) GetPixelBlue(image,q)); SetPixelRed(image,ClampToQuantum(red),q); SetPixelGreen(image,ClampToQuantum(green),q); SetPixelBlue(image,ClampToQuantum(blue),q); q+=GetPixelChannels(image); } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); if (SetImageColorspace(image,sRGBColorspace,exception) == MagickFalse) return(MagickFalse); return(status); } default: break; } /* Allocate the tables. */ x_map=(TransformPacket *) AcquireQuantumMemory((size_t) MaxMap+1UL, sizeof(*x_map)); y_map=(TransformPacket *) AcquireQuantumMemory((size_t) MaxMap+1UL, sizeof(*y_map)); z_map=(TransformPacket *) AcquireQuantumMemory((size_t) MaxMap+1UL, sizeof(*z_map)); if ((x_map == (TransformPacket *) NULL) || (y_map == (TransformPacket *) NULL) || (z_map == (TransformPacket *) NULL)) { if (z_map != (TransformPacket *) NULL) z_map=(TransformPacket *) RelinquishMagickMemory(z_map); if (y_map != (TransformPacket *) NULL) y_map=(TransformPacket *) RelinquishMagickMemory(y_map); if (x_map != (TransformPacket *) NULL) x_map=(TransformPacket *) RelinquishMagickMemory(x_map); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } switch (image->colorspace) { case OHTAColorspace: { /* Initialize OHTA tables: I1 = 0.33333*R+0.33334*G+0.33333*B I2 = 0.50000*R+0.00000*G-0.50000*B I3 =-0.25000*R+0.50000*G-0.25000*B R = I1+1.00000*I2-0.66668*I3 G = I1+0.00000*I2+1.33333*I3 B = I1-1.00000*I2-0.66668*I3 I and Q, normally -0.5 through 0.5, must be normalized to the range 0 through QuantumRange. */ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) #endif for (i=0; i <= (ssize_t) MaxMap; i++) { x_map[i].x=(MagickRealType) (1.0*(double) i); y_map[i].x=(MagickRealType) (0.5*1.00000*(2.0*(double) i-MaxMap)); z_map[i].x=(MagickRealType) (-0.5*0.66668*(2.0*(double) i-MaxMap)); x_map[i].y=(MagickRealType) (1.0*(double) i); y_map[i].y=(MagickRealType) (0.5*0.00000*(2.0*(double) i-MaxMap)); z_map[i].y=(MagickRealType) (0.5*1.33333*(2.0*(double) i-MaxMap)); x_map[i].z=(MagickRealType) (1.0*(double) i); y_map[i].z=(MagickRealType) (-0.5*1.00000*(2.0*(double) i-MaxMap)); z_map[i].z=(MagickRealType) (-0.5*0.66668*(2.0*(double) i-MaxMap)); } break; } case Rec601YCbCrColorspace: { /* Initialize YCbCr tables: R = Y +1.402000*Cr G = Y-0.344136*Cb-0.714136*Cr B = Y+1.772000*Cb Cb and Cr, normally -0.5 through 0.5, must be normalized to the range 0 through QuantumRange. */ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) \ magick_number_threads(image,image,image->rows,1) #endif for (i=0; i <= (ssize_t) MaxMap; i++) { x_map[i].x=0.99999999999914679361*(double) i; y_map[i].x=0.5*(-1.2188941887145875e-06)*(2.00*(double) i-MaxMap); z_map[i].x=0.5*1.4019995886561440468*(2.00*(double) i-MaxMap); x_map[i].y=0.99999975910502514331*(double) i; y_map[i].y=0.5*(-0.34413567816504303521)*(2.00*(double) i-MaxMap); z_map[i].y=0.5*(-0.71413649331646789076)*(2.00*(double) i-MaxMap); x_map[i].z=1.00000124040004623180*(double) i; y_map[i].z=0.5*1.77200006607230409200*(2.00*(double) i-MaxMap); z_map[i].z=0.5*2.1453384174593273e-06*(2.00*(double) i-MaxMap); } break; } case Rec709YCbCrColorspace: { /* Initialize YCbCr tables: R = Y +1.574800*Cr G = Y-0.187324*Cb-0.468124*Cr B = Y+1.855600*Cb Cb and Cr, normally -0.5 through 0.5, must be normalized to the range 0 through QuantumRange. */ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) \ magick_number_threads(image,image,image->rows,1) #endif for (i=0; i <= (ssize_t) MaxMap; i++) { x_map[i].x=(MagickRealType) (1.0*i); y_map[i].x=(MagickRealType) (0.5*0.000000*(2.0*i-MaxMap)); z_map[i].x=(MagickRealType) (0.5*1.574800*(2.0*i-MaxMap)); x_map[i].y=(MagickRealType) (1.0*i); y_map[i].y=(MagickRealType) (0.5*(-0.187324)*(2.0*i-MaxMap)); z_map[i].y=(MagickRealType) (0.5*(-0.468124)*(2.0*i-MaxMap)); x_map[i].z=(MagickRealType) (1.0*i); y_map[i].z=(MagickRealType) (0.5*1.855600*(2.0*i-MaxMap)); z_map[i].z=(MagickRealType) (0.5*0.000000*(2.0*i-MaxMap)); } break; } case YCCColorspace: { /* Initialize YCC tables: R = Y +1.340762*C2 G = Y-0.317038*C1-0.682243*C2 B = Y+1.632639*C1 YCC is scaled by 1.3584. C1 zero is 156 and C2 is at 137. */ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) \ magick_number_threads(image,image,image->rows,1) #endif for (i=0; i <= (ssize_t) MaxMap; i++) { x_map[i].x=(MagickRealType) (1.3584000*(double) i); y_map[i].x=(MagickRealType) 0.0000000; z_map[i].x=(MagickRealType) (1.8215000*(1.0*(double) i-(double) ScaleQuantumToMap(ScaleCharToQuantum(137)))); x_map[i].y=(MagickRealType) (1.3584000*(double) i); y_map[i].y=(MagickRealType) (-0.4302726*(1.0*(double) i-(double) ScaleQuantumToMap(ScaleCharToQuantum(156)))); z_map[i].y=(MagickRealType) (-0.9271435*(1.0*(double) i-(double) ScaleQuantumToMap(ScaleCharToQuantum(137)))); x_map[i].z=(MagickRealType) (1.3584000*(double) i); y_map[i].z=(MagickRealType) (2.2179000*(1.0*(double) i-(double) ScaleQuantumToMap(ScaleCharToQuantum(156)))); z_map[i].z=(MagickRealType) 0.0000000; } break; } default: { /* Linear conversion tables. */ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) \ magick_number_threads(image,image,image->rows,1) #endif for (i=0; i <= (ssize_t) MaxMap; i++) { x_map[i].x=(MagickRealType) (1.0*(double) i); y_map[i].x=(MagickRealType) 0.0; z_map[i].x=(MagickRealType) 0.0; x_map[i].y=(MagickRealType) 0.0; y_map[i].y=(MagickRealType) (1.0*(double) i); z_map[i].y=(MagickRealType) 0.0; x_map[i].z=(MagickRealType) 0.0; y_map[i].z=(MagickRealType) 0.0; z_map[i].z=(MagickRealType) (1.0*(double) i); } break; } } /* Convert to sRGB. */ switch (image->storage_class) { case DirectClass: default: { /* Convert DirectClass image. */ 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++) { MagickBooleanType sync; PixelInfo pixel; register ssize_t x; register 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; } for (x=0; x < (ssize_t) image->columns; x++) { register size_t blue, green, red; red=ScaleQuantumToMap(GetPixelRed(image,q)); green=ScaleQuantumToMap(GetPixelGreen(image,q)); blue=ScaleQuantumToMap(GetPixelBlue(image,q)); pixel.red=x_map[red].x+y_map[green].x+z_map[blue].x; pixel.green=x_map[red].y+y_map[green].y+z_map[blue].y; pixel.blue=x_map[red].z+y_map[green].z+z_map[blue].z; if (image->colorspace == YCCColorspace) { pixel.red=QuantumRange*YCCMap[RoundToYCC(1024.0*pixel.red/ (double) MaxMap)]; pixel.green=QuantumRange*YCCMap[RoundToYCC(1024.0*pixel.green/ (double) MaxMap)]; pixel.blue=QuantumRange*YCCMap[RoundToYCC(1024.0*pixel.blue/ (double) MaxMap)]; } else { pixel.red=(MagickRealType) ScaleMapToQuantum(pixel.red); pixel.green=(MagickRealType) ScaleMapToQuantum(pixel.green); pixel.blue=(MagickRealType) ScaleMapToQuantum(pixel.blue); } SetPixelRed(image,ClampToQuantum(pixel.red),q); SetPixelGreen(image,ClampToQuantum(pixel.green),q); SetPixelBlue(image,ClampToQuantum(pixel.blue),q); q+=GetPixelChannels(image); } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_TransformsRGBImage) #endif proceed=SetImageProgress(image,TransformsRGBImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); break; } case PseudoClass: { /* Convert PseudoClass image. */ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_number_threads(image,image,image->rows,1) #endif for (i=0; i < (ssize_t) image->colors; i++) { PixelInfo pixel; register size_t blue, green, red; red=ScaleQuantumToMap(ClampToQuantum(image->colormap[i].red)); green=ScaleQuantumToMap(ClampToQuantum(image->colormap[i].green)); blue=ScaleQuantumToMap(ClampToQuantum(image->colormap[i].blue)); pixel.red=x_map[red].x+y_map[green].x+z_map[blue].x; pixel.green=x_map[red].y+y_map[green].y+z_map[blue].y; pixel.blue=x_map[red].z+y_map[green].z+z_map[blue].z; if (image->colorspace == YCCColorspace) { pixel.red=QuantumRange*YCCMap[RoundToYCC(1024.0*pixel.red/ (double) MaxMap)]; pixel.green=QuantumRange*YCCMap[RoundToYCC(1024.0*pixel.green/ (double) MaxMap)]; pixel.blue=QuantumRange*YCCMap[RoundToYCC(1024.0*pixel.blue/ (double) MaxMap)]; } else { pixel.red=(MagickRealType) ScaleMapToQuantum(pixel.red); pixel.green=(MagickRealType) ScaleMapToQuantum(pixel.green); pixel.blue=(MagickRealType) ScaleMapToQuantum(pixel.blue); } image->colormap[i].red=(double) ClampToQuantum(pixel.red); image->colormap[i].green=(double) ClampToQuantum(pixel.green); image->colormap[i].blue=(double) ClampToQuantum(pixel.blue); } (void) SyncImage(image,exception); break; } } /* Relinquish resources. */ z_map=(TransformPacket *) RelinquishMagickMemory(z_map); y_map=(TransformPacket *) RelinquishMagickMemory(y_map); x_map=(TransformPacket *) RelinquishMagickMemory(x_map); if (SetImageColorspace(image,sRGBColorspace,exception) == MagickFalse) return(MagickFalse); return(MagickTrue); }
main.c
//===--- Adi.c ---- Alternating Direction Implicit ---------------*- C -*-===// // // This file implements the Alternating Direction Implicit(ADI) method which is // an iterative method used to solve partial differential equations. // //===----------------------------------------------------------------------===// #include <math.h> #include <stdio.h> #include <stdlib.h> #define MAX(A, b) ((A) > (b) ? (A) : (b)) #define NX 384 #define NY 384 #define NZ 384 double A[NX][NY][NZ]; void init(); double iter(); int main(int Argc, char *Argv[]) { double MaxEps, Eps; int It, ItMax, I, J, K; MaxEps = 0.01; ItMax = 100; init(); for (It = 1; It <= ItMax; It++) { Eps = iter(); printf(" IT = %4i EPS = %14.7E\n", It, Eps); if (Eps < MaxEps) break; } printf(" ADI Benchmark Completed.\n"); printf(" Size = %4d x %4d x %4d\n", NX, NY, NZ); printf(" Iterations = %12d\n", ItMax); printf(" Operation type = double precision\n"); printf(" Verification = %12s\n", (fabs(Eps - 0.07249074) < 1e-6 ? "SUCCESSFUL" : "UNSUCCESSFUL")); printf(" END OF ADI Benchmark\n"); return 0; } void init() { int I, J, K; #pragma omp parallel default(shared) { #pragma omp for private(J, K) for (I = 0; I < NX; I++) for (J = 0; J < NY; J++) for (K = 0; K < NZ; K++) if (K == 0 || K == NZ - 1 || J == 0 || J == NY - 1 || I == 0 || I == NX - 1) A[I][J][K] = 10.0 * I / (NX - 1) + 10.0 * J / (NY - 1) + 10.0 * K / (NZ - 1); else A[I][J][K] = 0; } } double iter() { int I, J, K; double Eps = 0; #pragma omp parallel default(shared) { #pragma omp for private(K) collapse(2) ordered(2) schedule(static, 1) for (I = 1; I < NX - 1; I++) for (J = 1; J < NY - 1; J++) { #pragma omp ordered depend(sink : I - 1, J) for (K = 1; K < NZ - 1; K++) A[I][J][K] = (A[I - 1][J][K] + A[I + 1][J][K]) / 2; #pragma omp ordered depend(source) } #pragma omp for private(J, K) for (I = 1; I < NX - 1; I++) for (J = 1; J < NY - 1; J++) for (K = 1; K < NZ - 1; K++) A[I][J][K] = (A[I][J - 1][K] + A[I][J + 1][K]) / 2; #pragma omp for private(J, K) reduction(max : Eps) for (I = 1; I < NX - 1; I++) for (J = 1; J < NY - 1; J++) for (K = 1; K < NZ - 1; K++) { double Tmp1 = (A[I][J][K - 1] + A[I][J][K + 1]) / 2; double Tmp2 = fabs(A[I][J][K] - Tmp1); Eps = MAX(Eps, Tmp2); A[I][J][K] = Tmp1; } } return Eps; }
spmv.c
////Example of sparse matrix-vector multiply, using CSR (compressed sparse row format). #include <stdio.h> #include <stdlib.h> #include <string.h> // Add timing support #include <sys/timeb.h> #define REAL float double read_timer() { struct timeb tm; ftime(&tm); return (double) tm.time + (double) tm.millitm / 1000.0; } //#define DEFAULT_DIMSIZE 256 void print_array(char *title, char *name, REAL *A, int n, int m) { printf("%s:\n", title); int i, j; for (i = 0; i < n; i++) { for (j = 0; j < m; j++) { printf("%s[%d][%d]:%f ", name, i, j, A[i * m + j]); } printf("\n"); } printf("\n"); } /* subroutine error_check (n,m,alpha,dx,dy,u,f) implicit none ************************************************************ * Checks error between numerical and exact solution * ************************************************************/ int main(int argc, char *argv[]) { int *ia, *ja; REAL *a, *x, *y; int row, i, j, idx, n, nnzMax, nnz, nrows; REAL ts, t, rate; n = 10240; //n = 24; if (argc > 1) n = atoi(argv[1]); nrows = n * n; nnzMax = nrows * 5; ia = (int*)malloc(nrows*sizeof(int)); ja = (int*)malloc(nnzMax*sizeof(int)); a = (REAL*)malloc(nnzMax*sizeof(REAL)); /* Allocate the source and result vectors */ x = (REAL*)malloc(nrows*sizeof(REAL)); y = (REAL*)malloc(nrows*sizeof(REAL)); row = 0; nnz = 0; for (i=0; i<n; i++) { for (j=0; j<n; j++) { ia[row] = nnz; if (i>0) { ja[nnz] = row - n; a[nnz] = -1.0; nnz++; } if (j>0) { ja[nnz] = row - 1; a[nnz] = -1.0; nnz++; } ja[nnz] = row; a[nnz] = 4.0; nnz++; if (j<n-1) { ja[nnz] = row + 1; a[nnz] = -1.0; nnz++; } if (i<n-1) { ja[nnz] = row + n; a[nnz] = -1.0; nnz++; } row++; } } ia[row] = nnz; /* Create the source (x) vector */ for (i=0; i<nrows; i++) x[i] = 1.0; double elapsed = read_timer(); int flops = 0; for (row=0; row<nrows; row++) { REAL sum = 0.0; #pragma omp simd reduction(+:sum,flops) simdlen(8) for (idx=ia[row]; idx<ia[row+1]; idx++) { sum += a[idx] * x[ja[idx]]; flops += 2; } y[row] = sum; } elapsed = read_timer() - elapsed; double gflops = flops / (1.0e9 * elapsed); printf("seq elasped time(s): %.4f\n", elapsed); printf("GFlops: %.4f\n", gflops); for (row=0; row<nrows; row++) { if (y[row] < 0) { fprintf(stderr,"y[%d]=%f, fails consistency test\n", row, y[row]); } } free(ia); free(ja); free(a); free(x); free(y); return 0; }
elemwise_binary_op.h
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * \file elemwise_binary_op.h * \brief Function definition of elementwise binary operators */ #ifndef MXNET_OPERATOR_TENSOR_ELEMWISE_BINARY_OP_H_ #define MXNET_OPERATOR_TENSOR_ELEMWISE_BINARY_OP_H_ #include <mxnet/operator_util.h> #include <mxnet/op_attr_types.h> #include <vector> #include <string> #include <utility> #include <typeinfo> #include <algorithm> #include "../mxnet_op.h" #include "../mshadow_op.h" #include "elemwise_unary_op.h" #include "../../common/utils.h" namespace mxnet { namespace op { /*! Gather binary operator functions into ElemwiseBinaryOp class */ class ElemwiseBinaryOp : public OpBase { public: template<typename OP, int Req> struct BackwardUseNoneOp { template<typename DType> MSHADOW_XINLINE static void Map(int i, DType *igrad, const DType *ograd) { KERNEL_ASSIGN(igrad[i], Req, OP::Map(ograd[i])); } }; template<typename OP, int Req> struct BackwardUseInOp { template<typename DType> MSHADOW_XINLINE static void Map(int i, DType *igrad, const DType *ograd, const DType *lhs, const DType *rhs) { KERNEL_ASSIGN(igrad[i], Req, ograd[i] * OP::Map(lhs[i], rhs[i])); } }; /*! \brief For sparse, assume missing rvalue is 0 */ template<typename OP, int Req> struct MissingRValueOp { template<typename DType> MSHADOW_XINLINE static void Map(int i, DType *out, const DType *lhs) { KERNEL_ASSIGN(out[i], Req, OP::Map(lhs[i], DType(0))); } }; /*! \brief For sparse, assume missing lvalue is 0 */ template<typename OP, int Req> struct MissingLValueOp { template<typename DType> MSHADOW_XINLINE static void Map(int i, DType *out, const DType *rhs) { KERNEL_ASSIGN(out[i], Req, OP::Map(DType(0), rhs[i])); } }; private: /*! \brief Fill contiguous dense output rows with value computed from 0 lhs and 0 rhs input */ template<typename xpu, typename DType, typename OP> static inline size_t FillDense(mshadow::Stream<xpu> *s, const size_t idx_l, const size_t idx_r, const OpReqType req, mshadow::Tensor<xpu, 2, DType> *out, const size_t iter_out) { using namespace mshadow::expr; const int index_out_min = std::min(idx_l, idx_r); if (static_cast<size_t>(index_out_min) > iter_out) { const size_t size = (*out)[iter_out].shape_.Size(); const DType zero_input_val = OP::Map(DType(0), DType(0)); #pragma omp parallel for for (int i = iter_out; i < index_out_min; ++i) { MXNET_ASSIGN_REQ_SWITCH(req, Req, { mxnet_op::Kernel<SetToScalar<Req>, xpu>::Launch(s, size, (*out)[i].dptr_, zero_input_val); }); } } return index_out_min; } template<typename DType> static inline bool IsSameArray(const NDArray& a1, const NDArray& a2) { return a1.var() == a2.var(); } /*! \brief Binary op handling for lhr/rhs: RspDns, RspRsp, DnsRsp, or RspRsp->Dns result */ template<typename DType, typename IType, typename OP> static void RspRspOp(mshadow::Stream<cpu> *s, const nnvm::NodeAttrs &attrs, const OpContext &ctx, const NDArray &lhs, const NDArray &rhs, const OpReqType req, const NDArray &output, const bool lhs_may_be_dense, const bool rhs_may_be_dense, const bool allow_inplace); /*! \brief CSR -op- CSR binary operator for non-canonical NDArray */ template<typename DType, typename IType, typename CType, typename OP> static inline void CsrCsrOp(mshadow::Stream<cpu> *s, const nnvm::NodeAttrs &attrs, const OpContext &ctx, const NDArray &lhs, const NDArray &rhs, const OpReqType req, const NDArray &output); /*! \brief Minimum of three */ static MSHADOW_XINLINE size_t minthree(const size_t a, const size_t b, const size_t c) { return a < b ? (a < c ? a : c) : (b < c ? b : c); } /*! \brief Maximum of three */ static MSHADOW_XINLINE size_t maxthree(const size_t a, const size_t b, const size_t c) { return a > b ? (a > c ? a : c) : (b > c ? b : c); } /*! \brief LaunchEx allowing dense lvalue and/or rvalue */ template<typename xpu, typename OP, typename DType, bool lhs_may_be_dense, bool rhs_may_be_dense, typename BackupCompute> static void ComputeExDenseLRValue_(const nnvm::NodeAttrs &attrs, const OpContext &ctx, const std::vector<NDArray> &inputs, const std::vector<OpReqType> &req, const std::vector<NDArray> &outputs, BackupCompute backup_compute) { using namespace mshadow; using namespace mshadow::expr; CHECK_EQ(inputs.size(), 2); CHECK_EQ(outputs.size(), 1); if (req[0] != kNullOp) { const NDArray *sparse = &inputs[0]; if (sparse->storage_type() == kDefaultStorage) { sparse = &inputs[1]; if (sparse->storage_type() == kDefaultStorage) { // Do we need to worry about sparse result here? CHECK_EQ(outputs[0].storage_type(), kDefaultStorage); MapToFCompute<xpu>(attrs, ctx, inputs, req, outputs, Compute<xpu, OP>); return; } } bool allowed = false; if (lhs_may_be_dense && rhs_may_be_dense) { allowed = common::ContainsNonDefaultStorage(inputs); } else if (lhs_may_be_dense) { allowed = inputs[1].storage_type() != kDefaultStorage; } else if (rhs_may_be_dense) { allowed = inputs[0].storage_type() != kDefaultStorage; } else { allowed = !common::ContainsNonDefaultStorage(inputs); } if (allowed) { allowed = !common::ContainsStorage(inputs, kCSRStorage); } // If any input or output is dense, fallback to FCompute if (allowed) { mshadow::Stream<xpu> *s = ctx.get_stream<xpu>(); MSHADOW_IDX_TYPE_SWITCH(sparse->aux_type(rowsparse::kIdx), IType, { RspRspOp<DType, IType, OP>( s, attrs, ctx, inputs[0], inputs[1], req[0], outputs[0], lhs_may_be_dense, rhs_may_be_dense, false); }); } else { // May be lhs=dense, rhs=sparse FCompExFallback<xpu>(attrs, ctx, inputs, req, outputs, backup_compute, "ComputeExDenseLRValue_"); } } } template<typename xpu, typename LOP, typename ROP, typename DType> static void BackwardUseNone_(const nnvm::NodeAttrs &attrs, const OpContext &ctx, const std::vector<TBlob> &inputs, const std::vector<OpReqType> &req, const std::vector<TBlob> &outputs) { using namespace mxnet_op; Stream<xpu> *s = ctx.get_stream<xpu>(); const int size = static_cast<int>((outputs[0].Size() + DataType<DType>::kLanes - 1) / DataType<DType>::kLanes); const DType *ograd_dptr = inputs[0].dptr<DType>(); if (std::is_same<LOP, mshadow_op::identity>::value && req[0] == kWriteInplace) { CHECK_EQ(ograd_dptr, outputs[0].dptr<DType>()); } else if (req[0] != kNullOp) { DType *lgrad_dptr = outputs[0].dptr<DType>(); MXNET_ASSIGN_REQ_SWITCH(req[0], Req, { Kernel<BackwardUseNoneOp<LOP, Req>, xpu>::Launch(s, size, lgrad_dptr, ograd_dptr); }); } if (std::is_same<ROP, mshadow_op::identity>::value && req[1] == kWriteInplace) { CHECK_EQ(ograd_dptr, outputs[1].dptr<DType>()); } else if (req[1] != kNullOp) { DType *rgrad_dptr = outputs[1].dptr<DType>(); MXNET_ASSIGN_REQ_SWITCH(req[1], Req, { Kernel<BackwardUseNoneOp<ROP, Req>, xpu>::Launch(s, size, rgrad_dptr, ograd_dptr); }); } } template<typename xpu, typename LOP, typename ROP, typename DType> static void BackwardUseIn_(const nnvm::NodeAttrs &attrs, const OpContext &ctx, const std::vector<TBlob> &inputs, const std::vector<OpReqType> &req, const std::vector<TBlob> &outputs) { DCHECK_EQ(outputs.size(), 2U); DCHECK_EQ(inputs.size(), 3U); mxnet_op::Stream<xpu> *s = ctx.get_stream<xpu>(); const DType *ograd_dptr = inputs[0].dptr<DType>(); const DType *lhs_dptr = inputs[1].dptr<DType>(); const DType *rhs_dptr = inputs[2].dptr<DType>(); MXNET_ASSIGN_REQ_SWITCH(req[0], Req, { const int size = static_cast<int>( (outputs[0].Size() + mxnet_op::DataType<DType>::kLanes - 1) / mxnet_op::DataType<DType>::kLanes); DType * lgrad_dptr = outputs[0].dptr<DType>(); mxnet_op::Kernel<BackwardUseInOp<LOP, Req>, xpu>::Launch( s, size, lgrad_dptr, ograd_dptr, lhs_dptr, rhs_dptr);}); MXNET_ASSIGN_REQ_SWITCH(req[1], Req, { const int size = static_cast<int>( (outputs[1].Size() + mxnet_op::DataType<DType>::kLanes - 1) / mxnet_op::DataType<DType>::kLanes); DType * rgrad_dptr = outputs[1].dptr<DType>(); mxnet_op::Kernel<BackwardUseInOp<ROP, Req>, xpu>::Launch( s, size, rgrad_dptr, ograd_dptr, lhs_dptr, rhs_dptr);}); } template< typename xpu, typename LOP, typename ROP, typename DType, bool in0_ok_dense = false, bool in1_ok_dense = false, bool in2_ok_dense = false, typename BackupCompute> static inline void BackwardUseInEx_(const nnvm::NodeAttrs &attrs, const OpContext &ctx, const std::vector<NDArray> &inputs, const std::vector<OpReqType> &req, const std::vector<NDArray> &outputs, BackupCompute backup_compute) { CHECK_EQ(inputs.size(), 3U); // output grad, CHECK_EQ(outputs.size(), 2U); // lhs input grad, rhs input grad if (req[0] != kNullOp) { // If any input is dense, fallback to FCompute if (common::ContainsOnlyStorage(inputs, kRowSparseStorage)) { mshadow::Stream<xpu> *s = ctx.get_stream<xpu>(); // ComputeRspRsp can handle dense outputs so long as OP(0, 0) == 0 MSHADOW_IDX_TYPE_SWITCH(inputs[0].aux_type(rowsparse::kIdx), IType, { RspRspOp<DType, IType, LOP>( s, attrs, ctx, inputs[1], inputs[2], req[0], outputs[0], false, false, false); }); // LHS in-place MSHADOW_IDX_TYPE_SWITCH(inputs[0].aux_type(rowsparse::kIdx), IType, { RspRspOp<DType, IType, mshadow::op::mul>( s, attrs, ctx, outputs[0], inputs[0], req[0], outputs[0], false, false, true); }); MSHADOW_IDX_TYPE_SWITCH(inputs[0].aux_type(rowsparse::kIdx), IType, { RspRspOp<DType, IType, ROP>( s, attrs, ctx, inputs[1], inputs[2], req[1], outputs[1], false, false, false); }); // RHS in-place MSHADOW_IDX_TYPE_SWITCH(inputs[0].aux_type(rowsparse::kIdx), IType, { RspRspOp<DType, IType, mshadow::op::mul>( s, attrs, ctx, inputs[0], outputs[1], req[1], outputs[1], false, false, true); }); } else { FCompExFallback<xpu>(attrs, ctx, inputs, req, outputs, backup_compute, "BackwardUseInEx_"); } } } public: template<typename xpu, typename OP> static void Compute(const nnvm::NodeAttrs &attrs, const OpContext &ctx, const std::vector<TBlob> &inputs, const std::vector<OpReqType> &req, const std::vector<TBlob> &outputs) { using namespace mxnet_op; if (req[0] != kNullOp) { Stream<xpu> *s = ctx.get_stream<xpu>(); CHECK_EQ(inputs.size(), 2U); CHECK_EQ(outputs.size(), 1U); MXNET_ASSIGN_REQ_SWITCH(req[0], Req, { MSHADOW_TYPE_SWITCH(outputs[0].type_flag_, DType, { const size_t size = (minthree(outputs[0].Size(), inputs[0].Size(), inputs[1].Size()) + DataType<DType>::kLanes - 1) / DataType<DType>::kLanes; Kernel<mxnet_op::op_with_req<OP, Req>, xpu>::Launch(s, size, outputs[0].dptr<DType>(), inputs[0].dptr<DType>(), inputs[1].dptr<DType>()); }); }); } } template<typename xpu, typename OP> static void ComputeWithHalf2(const nnvm::NodeAttrs &attrs, const OpContext &ctx, const std::vector<TBlob> &inputs, const std::vector<OpReqType> &req, const std::vector<TBlob> &outputs) { using namespace mxnet_op; if (req[0] != kNullOp) { Stream<xpu> *s = ctx.get_stream<xpu>(); CHECK_EQ(inputs.size(), 2U); CHECK_EQ(outputs.size(), 1U); MXNET_ASSIGN_REQ_SWITCH(req[0], Req, { MSHADOW_TYPE_SWITCH_WITH_HALF2(outputs[0].type_flag_, DType, { const size_t size = (minthree(outputs[0].Size(), inputs[0].Size(), inputs[1].Size()) + DataType<DType>::kLanes - 1) / DataType<DType>::kLanes; Kernel<mxnet_op::op_with_req<OP, Req>, xpu>::Launch(s, size, outputs[0].dptr<DType>(), inputs[0].dptr<DType>(), inputs[1].dptr<DType>()); }); }); } } template<typename xpu, typename OP> static void ComputeEx(const nnvm::NodeAttrs &attrs, const OpContext &ctx, const std::vector<NDArray> &inputs, const std::vector<OpReqType> &req, const std::vector<NDArray> &outputs) { using namespace mshadow; using namespace mshadow::expr; CHECK_EQ(inputs.size(), 2); CHECK_EQ(outputs.size(), 1); if (req[0] != kNullOp) { // If any input or output is dense, fallback to FCompute if (!common::ContainsDefaultStorage(inputs) && inputs[0].storage_type() == inputs[1].storage_type()) { mshadow::Stream<xpu> *s = ctx.get_stream<xpu>(); switch (inputs[0].storage_type()) { case kRowSparseStorage: MSHADOW_IDX_TYPE_SWITCH(inputs[0].aux_type(rowsparse::kIdx), IType, { MSHADOW_TYPE_SWITCH(outputs[0].dtype(), DType, { RspRspOp<DType, IType, OP>( s, attrs, ctx, inputs[0], inputs[1], req[0], outputs[0], false, false, false); }); }); break; case kCSRStorage: MSHADOW_IDX_TYPE_SWITCH(inputs[0].aux_type(csr::kIdx), IType, { MSHADOW_IDX_TYPE_SWITCH(inputs[0].aux_type(csr::kIndPtr), CType, { MSHADOW_TYPE_SWITCH(outputs[0].dtype(), DType, { CsrCsrOp<DType, IType, CType, OP>( s, attrs, ctx, inputs[0], inputs[1], req[0], outputs[0]); }); }); }); break; default: CHECK(false) << "Unsupported storage type for ComputeEx" << inputs[0].storage_type(); break; } } else { FCompExFallback<xpu>(attrs, ctx, inputs, req, outputs, Compute<xpu, OP>, "ComputeEx"); } } } /*! \brief LaunchEx allowing dense lvalue and/or rvalue */ template<typename xpu, typename OP, bool lhs_may_be_dense, bool rhs_may_be_dense> static void ComputeExDenseLRValue(const nnvm::NodeAttrs &attrs, const OpContext &ctx, const std::vector<NDArray> &inputs, const std::vector<OpReqType> &req, const std::vector<NDArray> &outputs) { MSHADOW_TYPE_SWITCH(outputs[0].dtype(), DType, { ComputeExDenseLRValue_<xpu, OP, DType, lhs_may_be_dense, rhs_may_be_dense>( attrs, ctx, inputs, req, outputs, Compute<xpu, OP>); }); } template<typename xpu, typename LOP, typename ROP> static inline void BackwardUseNone(const nnvm::NodeAttrs &attrs, const OpContext &ctx, const std::vector<TBlob> &inputs, const std::vector<OpReqType> &req, const std::vector<TBlob> &outputs) { MSHADOW_TYPE_SWITCH(outputs[0].type_flag_, DType, { BackwardUseNone_<xpu, LOP, ROP, DType>(attrs, ctx, inputs, req, outputs); }); } template<typename xpu, typename LOP, typename ROP> static inline void BackwardUseNoneWithHalf2(const nnvm::NodeAttrs &attrs, const OpContext &ctx, const std::vector<TBlob> &inputs, const std::vector<OpReqType> &req, const std::vector<TBlob> &outputs) { MSHADOW_TYPE_SWITCH_WITH_HALF2(outputs[0].type_flag_, DType, { BackwardUseNone_<xpu, LOP, ROP, DType>(attrs, ctx, inputs, req, outputs); }); } template<typename xpu, typename LOP, typename ROP> static inline void BackwardUseNoneEx(const nnvm::NodeAttrs &attrs, const OpContext &ctx, const std::vector<NDArray> &inputs, const std::vector<OpReqType> &req, const std::vector<NDArray> &outputs) { CHECK_EQ(inputs.size(), 1U); // output grad, CHECK_EQ(outputs.size(), 2U); // lhs input grad, rhs input grad using namespace mshadow; using namespace mshadow::expr; if (req[0] != kNullOp) { // If any input is dense, fallback to FCompute if (!common::ContainsDefaultStorage(inputs)) { CHECK_EQ(inputs[0].storage_type(), kRowSparseStorage); DCHECK_LT(fabs(static_cast<float>(LOP::Map(0))), 1e-5f); // op requires 0-input // returns 0-output DCHECK_LT(fabs(static_cast<float>(ROP::Map(0))), 1e-5f); // op requires 0-input // returns 0-output MXNET_ASSIGN_REQ_SWITCH(req[0], Req, { UnaryOp::KernelComputeEx<xpu, BackwardUseNoneOp<LOP, Req>>(attrs, ctx, inputs, req, {outputs[0]}); }); MXNET_ASSIGN_REQ_SWITCH(req[1], Req, { UnaryOp::KernelComputeEx<xpu, BackwardUseNoneOp<ROP, Req>>(attrs, ctx, inputs, req, {outputs[1]}); }); } else { FCompExFallback<xpu>(attrs, ctx, inputs, req, outputs, BackwardUseNone<xpu, LOP, ROP>, "BackwardUseNoneEx"); } } } template<typename xpu, typename LOP, typename ROP> static inline void BackwardUseIn(const nnvm::NodeAttrs &attrs, const OpContext &ctx, const std::vector<TBlob> &inputs, const std::vector<OpReqType> &req, const std::vector<TBlob> &outputs) { MSHADOW_TYPE_SWITCH(outputs[0].type_flag_, DType, { BackwardUseIn_<xpu, LOP, ROP, DType>(attrs, ctx, inputs, req, outputs); }); } template<typename xpu, typename LOP, typename ROP> static inline void BackwardUseInWithHalf2(const nnvm::NodeAttrs &attrs, const OpContext &ctx, const std::vector<TBlob> &inputs, const std::vector<OpReqType> &req, const std::vector<TBlob> &outputs) { MSHADOW_TYPE_SWITCH_WITH_HALF2(outputs[0].type_flag_, DType, { BackwardUseIn_<xpu, LOP, ROP, DType>(attrs, ctx, inputs, req, outputs); }); } template< typename xpu, typename LOP, typename ROP, bool in0_ok_dense = false, bool in1_ok_dense = false, bool in2_ok_dense = false> static inline void BackwardUseInEx(const nnvm::NodeAttrs &attrs, const OpContext &ctx, const std::vector<NDArray> &inputs, const std::vector<OpReqType> &req, const std::vector<NDArray> &outputs) { MSHADOW_TYPE_SWITCH(outputs[0].dtype(), DType, { BackwardUseInEx_<xpu, LOP, ROP, DType, in0_ok_dense, in1_ok_dense, in2_ok_dense>( attrs, ctx, inputs, req, outputs, BackwardUseIn<xpu, LOP, ROP>); }); } }; // class ElemwiseBinaryOp #define MXNET_OPERATOR_REGISTER_BINARY(name) \ NNVM_REGISTER_OP(name) \ .set_num_inputs(2) \ .set_num_outputs(1) \ .set_attr<nnvm::FListInputNames>("FListInputNames", \ [](const NodeAttrs& attrs) { \ return std::vector<std::string>{"lhs", "rhs"}; \ }) \ .set_attr<nnvm::FInferShape>("FInferShape", ElemwiseShape<2, 1>) \ .set_attr<nnvm::FInferType>("FInferType", ElemwiseType<2, 1>) \ .set_attr<nnvm::FInplaceOption>("FInplaceOption", \ [](const NodeAttrs& attrs){ \ return std::vector<std::pair<int, int> >{{0, 0}, {1, 0}}; \ }) \ .add_argument("lhs", "NDArray-or-Symbol", "first input") \ .add_argument("rhs", "NDArray-or-Symbol", "second input") /*! \brief Binary launch */ #define MXNET_OPERATOR_REGISTER_BINARY_WITH_SPARSE_CPU(__name$, __kernel$) \ MXNET_OPERATOR_REGISTER_BINARY(__name$) \ .set_attr<FInferStorageType>("FInferStorageType", ElemwiseStorageType<2, 1>) \ .set_attr<FCompute>("FCompute<cpu>", ElemwiseBinaryOp::Compute<cpu, __kernel$>) \ .set_attr<FComputeEx>("FComputeEx<cpu>", ElemwiseBinaryOp::ComputeEx<cpu, __kernel$>) /*! \brief Binary launch, dense result */ #define MXNET_OPERATOR_REGISTER_BINARY_WITH_SPARSE_CPU_DR(__name$, __kernel$) \ MXNET_OPERATOR_REGISTER_BINARY(__name$) \ .set_attr<FInferStorageType>("FInferStorageType", ElemwiseStorageTypeDenseOutput<1>) \ .set_attr<FCompute>("FCompute<cpu>", ElemwiseBinaryOp::Compute<cpu, __kernel$>) \ .set_attr<FComputeEx>("FComputeEx<cpu>", ElemwiseBinaryOp::ComputeEx<cpu, __kernel$>) } // namespace op } // namespace mxnet #endif // MXNET_OPERATOR_TENSOR_ELEMWISE_BINARY_OP_H_
GB_binop__times_fp32.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary 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_ek_slice.h" #include "GB_dense.h" #include "GB_mkl.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB_AaddB__times_fp32 // A.*B function (eWiseMult): GB_AemultB__times_fp32 // A*D function (colscale): GB_AxD__times_fp32 // D*A function (rowscale): GB_DxB__times_fp32 // C+=B function (dense accum): GB_Cdense_accumB__times_fp32 // C+=b function (dense accum): GB_Cdense_accumb__times_fp32 // C+=A+B function (dense ewise3): GB_Cdense_ewise3_accum__times_fp32 // C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__times_fp32 // C=scalar+B GB_bind1st__times_fp32 // C=scalar+B' GB_bind1st_tran__times_fp32 // C=A+scalar GB_bind2nd__times_fp32 // C=A'+scalar GB_bind2nd_tran__times_fp32 // C type: float // A type: float // B,b type: float // BinaryOp: cij = (aij * bij) #define GB_ATYPE \ float #define GB_BTYPE \ float #define GB_CTYPE \ float // 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) \ float aij = Ax [pA] // bij = Bx [pB] #define GB_GETB(bij,Bx,pB) \ float bij = Bx [pB] // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ float t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA) \ cij = Ax [pA] // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB) \ cij = Bx [pB] #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z, x, y) \ z = (x * y) ; // op is second #define GB_OP_IS_SECOND \ 0 // op is plus_fp32 or plus_fp64 #define GB_OP_IS_PLUS_REAL \ 0 // op is minus_fp32 or minus_fp64 #define GB_OP_IS_MINUS_REAL \ 0 // GB_cblas_*axpy gateway routine, if it exists for this operator and type: #define GB_CBLAS_AXPY \ (none) // 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_TIMES || GxB_NO_FP32 || GxB_NO_TIMES_FP32) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB_Cdense_ewise3_accum__times_fp32 ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB_Cdense_ewise3_noaccum__times_fp32 ( 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__times_fp32 ( GrB_Matrix C, const GrB_Matrix B, const int64_t *GB_RESTRICT kfirst_slice, const int64_t *GB_RESTRICT klast_slice, const int64_t *GB_RESTRICT pstart_slice, const int ntasks, const int 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__times_fp32 ( 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 float float bwork = (*((float *) 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__times_fp32 ( GrB_Matrix C, const GrB_Matrix A, bool A_is_pattern, const GrB_Matrix D, bool D_is_pattern, const int64_t *GB_RESTRICT kfirst_slice, const int64_t *GB_RESTRICT klast_slice, const int64_t *GB_RESTRICT pstart_slice, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else float *GB_RESTRICT Cx = (float *) C->x ; #include "GB_AxB_colscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB_DxB__times_fp32 ( 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 float *GB_RESTRICT Cx = (float *) C->x ; #include "GB_AxB_rowscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C = A+B or C<M> = A+B //------------------------------------------------------------------------------ GrB_Info GB_AaddB__times_fp32 ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const bool Ch_is_Mh, const int64_t *GB_RESTRICT C_to_M, const int64_t *GB_RESTRICT C_to_A, const int64_t *GB_RESTRICT C_to_B, const GB_task_struct *GB_RESTRICT TaskList, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_add_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C = A.*B or C<M> = A.*B //------------------------------------------------------------------------------ GrB_Info GB_AemultB__times_fp32 ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *GB_RESTRICT C_to_M, const int64_t *GB_RESTRICT C_to_A, const int64_t *GB_RESTRICT C_to_B, const GB_task_struct *GB_RESTRICT TaskList, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_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__times_fp32 ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else float *Cx = (float *) Cx_output ; float x = (*((float *) x_input)) ; float *Bx = (float *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { float bij = Bx [p] ; 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__times_fp32 ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; float *Cx = (float *) Cx_output ; float *Ax = (float *) Ax_input ; float y = (*((float *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { float aij = Ax [p] ; Cx [p] = (aij * y) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typcasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ float aij = Ax [pA] ; \ Cx [pC] = (x * aij) ; \ } GrB_Info GB_bind1st_tran__times_fp32 ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *GB_RESTRICT *Rowcounts, GBI_single_iterator Iter, const int64_t *GB_RESTRICT A_slice, int naslice ) { // 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 \ float #if GB_DISABLE return (GrB_NO_VALUE) ; #else float x = (*((const float *) x_input)) ; #define GB_PHASE_2_OF_2 #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ float } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typcasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ float aij = Ax [pA] ; \ Cx [pC] = (aij * y) ; \ } GrB_Info GB_bind2nd_tran__times_fp32 ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, 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 float y = (*((const float *) y_input)) ; #define GB_PHASE_2_OF_2 #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
pfmg_setup_rap5.c
/*BHEADER********************************************************************** * Copyright (c) 2008, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * This file is part of HYPRE. See file COPYRIGHT for details. * * HYPRE 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) version 2.1 dated February 1999. * * $Revision$ ***********************************************************************EHEADER*/ #include "_hypre_struct_ls.h" #include "pfmg.h" /*-------------------------------------------------------------------------- * Macro to "change coordinates". This routine is written as though * coarsening is being done in the y-direction. This macro is used to * allow for coarsening to be done in the x-direction also. *--------------------------------------------------------------------------*/ #define MapIndex(in_index, cdir, out_index) \ hypre_IndexD(out_index, 2) = hypre_IndexD(in_index, 2); \ hypre_IndexD(out_index, cdir) = hypre_IndexD(in_index, 1); \ cdir = (cdir + 1) % 2; \ hypre_IndexD(out_index, cdir) = hypre_IndexD(in_index, 0); \ cdir = (cdir + 1) % 2; /*-------------------------------------------------------------------------- * hypre_PFMGCreateCoarseOp5 * Sets up new coarse grid operator stucture. Fine grid * operator is 5pt and so is coarse, i.e. non-Galerkin. *--------------------------------------------------------------------------*/ hypre_StructMatrix * hypre_PFMGCreateCoarseOp5( hypre_StructMatrix *R, hypre_StructMatrix *A, hypre_StructMatrix *P, hypre_StructGrid *coarse_grid, HYPRE_Int cdir ) { hypre_StructMatrix *RAP; hypre_Index *RAP_stencil_shape; hypre_StructStencil *RAP_stencil; HYPRE_Int RAP_stencil_size; HYPRE_Int RAP_stencil_dim; HYPRE_Int RAP_num_ghost[] = {1, 1, 1, 1, 1, 1}; hypre_Index index_temp; HYPRE_Int j, i; HYPRE_Int stencil_rank; RAP_stencil_dim = 2; /*----------------------------------------------------------------------- * Define RAP_stencil *-----------------------------------------------------------------------*/ stencil_rank = 0; /*----------------------------------------------------------------------- * non-symmetric case *-----------------------------------------------------------------------*/ if (!hypre_StructMatrixSymmetric(A)) { /*-------------------------------------------------------------------- * 5 point coarse grid stencil *--------------------------------------------------------------------*/ RAP_stencil_size = 5; RAP_stencil_shape = hypre_CTAlloc(hypre_Index, RAP_stencil_size); for (j = -1; j < 2; j++) { for (i = -1; i < 2; i++) { /*-------------------------------------------------------------- * Storage for 5 elements (c,w,e,n,s) *--------------------------------------------------------------*/ if (i*j == 0) { hypre_SetIndex3(index_temp,i,j,0); MapIndex(index_temp, cdir, RAP_stencil_shape[stencil_rank]); stencil_rank++; } } } } /*----------------------------------------------------------------------- * symmetric case *-----------------------------------------------------------------------*/ else { /*-------------------------------------------------------------------- * 5 point coarse grid stencil * Only store the lower triangular part + diagonal = 3 entries, * lower triangular means the lower triangular part on the matrix * in the standard lexicographic ordering. *--------------------------------------------------------------------*/ RAP_stencil_size = 3; RAP_stencil_shape = hypre_CTAlloc(hypre_Index, RAP_stencil_size); for (j = -1; j < 1; j++) { for (i = -1; i < 1; i++) { /*-------------------------------------------------------------- * Store 3 elements in (c,w,s) *--------------------------------------------------------------*/ if( i*j == 0 ) { hypre_SetIndex3(index_temp,i,j,0); MapIndex(index_temp, cdir, RAP_stencil_shape[stencil_rank]); stencil_rank++; } } } } RAP_stencil = hypre_StructStencilCreate(RAP_stencil_dim, RAP_stencil_size, RAP_stencil_shape); RAP = hypre_StructMatrixCreate(hypre_StructMatrixComm(A), coarse_grid, RAP_stencil); hypre_StructStencilDestroy(RAP_stencil); /*----------------------------------------------------------------------- * Coarse operator in symmetric iff fine operator is *-----------------------------------------------------------------------*/ hypre_StructMatrixSymmetric(RAP) = hypre_StructMatrixSymmetric(A); /*----------------------------------------------------------------------- * Set number of ghost points - one one each boundary *-----------------------------------------------------------------------*/ hypre_StructMatrixSetNumGhost(RAP, RAP_num_ghost); return RAP; } /*-------------------------------------------------------------------------- * hypre_PFMGBuildCoarseOp5 * Sets up new coarse grid operator stucture. Fine grid operator is 5pt and * so is coarse, i.e. non-Galerkin. * * Uses the non-Galerkin strategy from Ashby & Falgout's original ParFlow * algorithm. For constant_coefficient==2, see [issue663]. *--------------------------------------------------------------------------*/ HYPRE_Int hypre_PFMGBuildCoarseOp5( hypre_StructMatrix *A, hypre_StructMatrix *P, hypre_StructMatrix *R, HYPRE_Int cdir, hypre_Index cindex, hypre_Index cstride, hypre_StructMatrix *RAP ) { HYPRE_Int ndim = hypre_StructMatrixNDim(A); hypre_Index index; hypre_Index index_temp; hypre_StructGrid *fgrid; hypre_BoxArray *fgrid_boxes; hypre_Box *fgrid_box; HYPRE_Int *fgrid_ids; hypre_StructGrid *cgrid; hypre_BoxArray *cgrid_boxes; hypre_Box *cgrid_box; HYPRE_Int *cgrid_ids; hypre_IndexRef cstart, bfstart, stridef; hypre_Index fstart, bcstart, stridec; hypre_Index loop_size; HYPRE_Int constant_coefficient; HYPRE_Int fi, ci, fbi; hypre_Box *A_dbox; hypre_Box *P_dbox; hypre_Box *RAP_dbox; hypre_BoxArray *bdy_boxes, *tmp_boxes; hypre_Box *bdy_box, *fcbox; HYPRE_Real *pb, *pa; HYPRE_Real *a_cc, *a_cw, *a_ce, *a_cb, *a_ca; HYPRE_Real *rap_cc, *rap_cw, *rap_ce; HYPRE_Real *rap_cb, *rap_ca; HYPRE_Real west, east; HYPRE_Real center_int, center_bdy; HYPRE_Int iA, iAm1, iAp1; HYPRE_Int iAc; HYPRE_Int iP, iPm1, iPp1; HYPRE_Int OffsetA; HYPRE_Int OffsetP; stridef = cstride; hypre_SetIndex3(stridec, 1, 1, 1); fgrid = hypre_StructMatrixGrid(A); fgrid_boxes = hypre_StructGridBoxes(fgrid); fgrid_ids = hypre_StructGridIDs(fgrid); cgrid = hypre_StructMatrixGrid(RAP); cgrid_boxes = hypre_StructGridBoxes(cgrid); cgrid_ids = hypre_StructGridIDs(cgrid); constant_coefficient = hypre_StructMatrixConstantCoefficient(RAP); hypre_assert( hypre_StructMatrixConstantCoefficient(A) == constant_coefficient ); if ( constant_coefficient==0 ) { hypre_assert( hypre_StructMatrixConstantCoefficient(R) == 0 ); hypre_assert( hypre_StructMatrixConstantCoefficient(P) == 0 ); } else /* 1 or 2 */ { hypre_assert( hypre_StructMatrixConstantCoefficient(R) == 1 ); hypre_assert( hypre_StructMatrixConstantCoefficient(P) == 1 ); } fcbox = hypre_BoxCreate(ndim); bdy_boxes = hypre_BoxArrayCreate(0, ndim); tmp_boxes = hypre_BoxArrayCreate(0, ndim); fi = 0; hypre_ForBoxI(ci, cgrid_boxes) { while (fgrid_ids[fi] != cgrid_ids[ci]) { fi++; } cgrid_box = hypre_BoxArrayBox(cgrid_boxes, ci); fgrid_box = hypre_BoxArrayBox(fgrid_boxes, fi); cstart = hypre_BoxIMin(cgrid_box); hypre_StructMapCoarseToFine(cstart, cindex, cstride, fstart); A_dbox = hypre_BoxArrayBox(hypre_StructMatrixDataSpace(A), fi); P_dbox = hypre_BoxArrayBox(hypre_StructMatrixDataSpace(P), fi); RAP_dbox = hypre_BoxArrayBox(hypre_StructMatrixDataSpace(RAP), ci); /*----------------------------------------------------------------- * Extract pointers for interpolation operator: * pb is pointer for weight for f-point below c-point * pa is pointer for weight for f-point above c-point *-----------------------------------------------------------------*/ hypre_SetIndex3(index_temp,0,-1,0); MapIndex(index_temp, cdir, index); pa = hypre_StructMatrixExtractPointerByIndex(P, fi, index); hypre_SetIndex3(index_temp,0,1,0); MapIndex(index_temp, cdir, index); pb = hypre_StructMatrixExtractPointerByIndex(P, fi, index) - hypre_BoxOffsetDistance(P_dbox, index); /*----------------------------------------------------------------- * Extract pointers for 5-point fine grid operator: * * a_cc is pointer for center coefficient * a_cw is pointer for west coefficient * a_ce is pointer for east coefficient * a_cb is pointer for below coefficient * a_ca is pointer for above coefficient *-----------------------------------------------------------------*/ hypre_SetIndex3(index_temp,0,0,0); MapIndex(index_temp, cdir, index); a_cc = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,-1,0,0); MapIndex(index_temp, cdir, index); a_cw = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,1,0,0); MapIndex(index_temp, cdir, index); a_ce = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,0,-1,0); MapIndex(index_temp, cdir, index); a_cb = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,0,1,0); MapIndex(index_temp, cdir, index); a_ca = hypre_StructMatrixExtractPointerByIndex(A, fi, index); /*----------------------------------------------------------------- * Extract pointers for coarse grid operator * rap_cc is pointer for center coefficient (etc.) *-----------------------------------------------------------------*/ hypre_SetIndex3(index_temp,0,0,0); MapIndex(index_temp, cdir, index); rap_cc = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,-1,0,0); MapIndex(index_temp, cdir, index); rap_cw = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,1,0,0); MapIndex(index_temp, cdir, index); rap_ce = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,0,-1,0); MapIndex(index_temp, cdir, index); rap_cb = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,0,1,0); MapIndex(index_temp, cdir, index); rap_ca = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); /*----------------------------------------------------------------- * Define offsets for fine grid stencil and interpolation * * In the BoxLoop below I assume iA and iP refer to data associated * with the point which we are building the stencil for. The below * Offsets are used in refering to data associated with other points. *-----------------------------------------------------------------*/ hypre_SetIndex3(index_temp,0,1,0); MapIndex(index_temp, cdir, index); OffsetP = hypre_BoxOffsetDistance(P_dbox,index); OffsetA = hypre_BoxOffsetDistance(A_dbox,index); /*-------------------------------------------------------------- * Loop for symmetric 5-point fine grid operator; produces a * symmetric 5-point coarse grid operator. *--------------------------------------------------------------*/ if ( constant_coefficient==0 ) { hypre_BoxGetSize(cgrid_box, loop_size); hypre_BoxLoop3Begin(hypre_StructMatrixNDim(A), loop_size, P_dbox, cstart, stridec, iP, A_dbox, fstart, stridef, iA, RAP_dbox, cstart, stridec, iAc); #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(HYPRE_BOX_PRIVATE,iP,iA,iAc,iAm1,iAp1,iPm1,iPp1,west,east) HYPRE_SMP_SCHEDULE #endif hypre_BoxLoop3For(iP, iA, iAc) { iAm1 = iA - OffsetA; iAp1 = iA + OffsetA; iPm1 = iP - OffsetP; iPp1 = iP + OffsetP; rap_cb[iAc] = a_cb[iA] * pa[iPm1]; rap_ca[iAc] = a_ca[iA] * pb[iPp1]; west = a_cw[iA] + 0.5 * a_cw[iAm1] + 0.5 * a_cw[iAp1]; east = a_ce[iA] + 0.5 * a_ce[iAm1] + 0.5 * a_ce[iAp1]; /*----------------------------------------------------- * Prevent non-zero entries reaching off grid *-----------------------------------------------------*/ if(a_cw[iA] == 0.0) west = 0.0; if(a_ce[iA] == 0.0) east = 0.0; rap_cw[iAc] = west; rap_ce[iAc] = east; rap_cc[iAc] = a_cc[iA] + a_cw[iA] + a_ce[iA] + a_cb[iA] * pb[iP] + a_ca[iA] * pa[iP] - west - east; } hypre_BoxLoop3End(iP, iA, iAc); } else if ( constant_coefficient==1 ) { rap_cb[0] = rap_ca[0] = a_cb[0] * pa[0]; rap_cw[0] = rap_ce[0] = 2.0*a_cw[0]; rap_cc[0] = a_cc[0] - 2.0*( a_cw[0] - rap_cb[0] ); } else if ( constant_coefficient==2 ) { /* NOTE: This does not reduce to either of the above operators unless * the row sum is zero and the interpolation weights are 1/2 */ rap_cb[0] = rap_ca[0] = 0.5*a_cb[0]; rap_cw[0] = rap_ce[0] = 2.0*a_cw[0]; center_int = 3.0*a_cb[0]; center_bdy = 0.5*a_cb[0] + (a_cw[0] + a_cb[0]); hypre_BoxGetSize(cgrid_box, loop_size); hypre_BoxLoop2Begin(hypre_StructMatrixNDim(A), loop_size, A_dbox, fstart, stridef, iA, RAP_dbox, cstart, stridec, iAc); #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(HYPRE_BOX_PRIVATE,iA,iAc) HYPRE_SMP_SCHEDULE #endif hypre_BoxLoop2For(iA, iAc) { rap_cc[iAc] = 2.0*a_cc[iA] + center_int; } hypre_BoxLoop2End(iA, iAc); hypre_CopyBox(cgrid_box, fcbox); hypre_StructMapCoarseToFine(hypre_BoxIMin(fcbox), cindex, cstride, hypre_BoxIMin(fcbox)); hypre_StructMapCoarseToFine(hypre_BoxIMax(fcbox), cindex, cstride, hypre_BoxIMax(fcbox)); hypre_BoxArraySetSize(bdy_boxes, 0); if (hypre_BoxIMinD(fcbox, cdir) == hypre_BoxIMinD(fgrid_box, cdir)) { hypre_BoxBoundaryIntersect(fcbox, fgrid, cdir, -1, bdy_boxes); } if (hypre_BoxIMaxD(fcbox, cdir) == hypre_BoxIMaxD(fgrid_box, cdir)) { hypre_BoxBoundaryIntersect(fcbox, fgrid, cdir, 1, tmp_boxes); hypre_AppendBoxArray(tmp_boxes, bdy_boxes); } hypre_ForBoxI(fbi, bdy_boxes) { bdy_box = hypre_BoxArrayBox(bdy_boxes, fbi); hypre_BoxGetSize(bdy_box, loop_size); bfstart = hypre_BoxIMin(bdy_box); hypre_StructMapFineToCoarse(bfstart, cindex, cstride, bcstart); hypre_BoxLoop2Begin(hypre_StructMatrixNDim(A), loop_size, A_dbox, bfstart, stridef, iA, RAP_dbox, bcstart, stridec, iAc); #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(HYPRE_BOX_PRIVATE,iA,iAc) HYPRE_SMP_SCHEDULE #endif hypre_BoxLoop2For(iA, iAc) { rap_cc[iAc] -= 0.5*a_cc[iA] + center_bdy; } hypre_BoxLoop2End(iA, iAc); } } } /* end ForBoxI */ hypre_BoxDestroy(fcbox); hypre_BoxArrayDestroy(bdy_boxes); hypre_BoxArrayDestroy(tmp_boxes); return hypre_error_flag; }
cv_basic.h
// Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma once #include "lite/utils/cv/paddle_image_preprocess.h" typedef paddle::lite::utils::cv::ImageFormat ImageFormat; typedef paddle::lite::utils::cv::FlipParam FlipParam; typedef paddle::lite::Tensor Tensor; typedef paddle::lite_api::DataLayoutType LayoutType; void nv2bgr(const uint8_t* in_data, uint8_t* out_data, int srcw, int srch, int v_num, int u_num) { int size = srch * srcw; const uint8_t* y_ptr = in_data; const uint8_t* uv_ptr = in_data + size; for (int i = 0; i < srch; i++) { int j = 0; const uint8_t* ptr_y1 = y_ptr + i * srcw; const uint8_t* ptr_vu = uv_ptr + (i / 2) * srcw; uint8_t* ptr_bgr1 = out_data + i * 3 * srcw; for (; j < srcw; j += 2) { uint8_t _y0 = ptr_y1[0]; uint8_t _y1 = ptr_y1[1]; uint8_t _v = ptr_vu[v_num]; uint8_t _u = ptr_vu[u_num]; int ra = floor((179 * (_v - 128)) >> 7); int ga = floor((44 * (_u - 128) + 91 * (_v - 128)) >> 7); int ba = floor((227 * (_u - 128)) >> 7); int r = _y0 + ra; int g = _y0 - ga; int b = _y0 + ba; int r1 = _y1 + ra; int g1 = _y1 - ga; int b1 = _y1 + ba; r = r < 0 ? 0 : (r > 255) ? 255 : r; g = g < 0 ? 0 : (g > 255) ? 255 : g; b = b < 0 ? 0 : (b > 255) ? 255 : b; r1 = r1 < 0 ? 0 : (r1 > 255) ? 255 : r1; g1 = g1 < 0 ? 0 : (g1 > 255) ? 255 : g1; b1 = b1 < 0 ? 0 : (b1 > 255) ? 255 : b1; *ptr_bgr1++ = b; *ptr_bgr1++ = g; *ptr_bgr1++ = r; *ptr_bgr1++ = b1; *ptr_bgr1++ = g1; *ptr_bgr1++ = r1; ptr_y1 += 2; ptr_vu += 2; } if (j < srcw) { uint8_t _y = ptr_y1[0]; uint8_t _v = ptr_vu[v_num]; uint8_t _u = ptr_vu[u_num]; int r = _y + ((179 * (_v - 128)) >> 7); int g = _y - ((44 * (_u - 128) - 91 * (_v - 128)) >> 7); int b = _y + ((227 * (_u - 128)) >> 7); r = r < 0 ? 0 : (r > 255) ? 255 : r; g = g < 0 ? 0 : (g > 255) ? 255 : g; b = b < 0 ? 0 : (b > 255) ? 255 : b; ptr_bgr1[0] = b; ptr_bgr1[1] = g; ptr_bgr1[2] = r; } } } void nv2bgra(const uint8_t* in_data, uint8_t* out_data, int srcw, int srch, int v_num, int u_num) { int size = srch * srcw; const uint8_t* y_ptr = in_data; const uint8_t* uv_ptr = in_data + size; for (int i = 0; i < srch; i++) { int j = 0; const uint8_t* ptr_y1 = y_ptr + i * srcw; const uint8_t* ptr_vu = uv_ptr + (i / 2) * srcw; uint8_t* ptr_bgr1 = out_data + i * 4 * srcw; for (; j < srcw; j += 2) { uint8_t _y0 = ptr_y1[0]; uint8_t _y1 = ptr_y1[1]; uint8_t _v = ptr_vu[v_num]; uint8_t _u = ptr_vu[u_num]; int ra = floor((179 * (_v - 128)) >> 7); int ga = floor((44 * (_u - 128) + 91 * (_v - 128)) >> 7); int ba = floor((227 * (_u - 128)) >> 7); int r = _y0 + ra; int g = _y0 - ga; int b = _y0 + ba; int r1 = _y1 + ra; int g1 = _y1 - ga; int b1 = _y1 + ba; r = r < 0 ? 0 : (r > 255) ? 255 : r; g = g < 0 ? 0 : (g > 255) ? 255 : g; b = b < 0 ? 0 : (b > 255) ? 255 : b; r1 = r1 < 0 ? 0 : (r1 > 255) ? 255 : r1; g1 = g1 < 0 ? 0 : (g1 > 255) ? 255 : g1; b1 = b1 < 0 ? 0 : (b1 > 255) ? 255 : b1; *ptr_bgr1++ = b; *ptr_bgr1++ = g; *ptr_bgr1++ = r; *ptr_bgr1++ = 255; *ptr_bgr1++ = b1; *ptr_bgr1++ = g1; *ptr_bgr1++ = r1; *ptr_bgr1++ = 255; ptr_y1 += 2; ptr_vu += 2; } if (j < srcw) { uint8_t _y = ptr_y1[0]; uint8_t _v = ptr_vu[v_num]; uint8_t _u = ptr_vu[u_num]; int r = _y + ((179 * (_v - 128)) >> 7); int g = _y - ((44 * (_u - 128) - 91 * (_v - 128)) >> 7); int b = _y + ((227 * (_u - 128)) >> 7); r = r < 0 ? 0 : (r > 255) ? 255 : r; g = g < 0 ? 0 : (g > 255) ? 255 : g; b = b < 0 ? 0 : (b > 255) ? 255 : b; ptr_bgr1[0] = b; ptr_bgr1[1] = g; ptr_bgr1[2] = r; ptr_bgr1[3] = 255; } } } void nv12_bgr_basic(const uint8_t* in_data, uint8_t* out_data, int srcw, int srch) { nv2bgr(in_data, out_data, srcw, srch, 1, 0); } void nv21_bgr_basic(const uint8_t* in_data, uint8_t* out_data, int srcw, int srch) { nv2bgr(in_data, out_data, srcw, srch, 0, 1); } void nv12_bgra_basic(const uint8_t* in_data, uint8_t* out_data, int srcw, int srch) { nv2bgra(in_data, out_data, srcw, srch, 1, 0); } void nv21_bgra_basic(const uint8_t* in_data, uint8_t* out_data, int srcw, int srch) { nv2bgra(in_data, out_data, srcw, srch, 0, 1); } /* 采用CV_BGR2GRAY,转换公式Gray = 0.1140*B + 0.5870*G + 0.2989*R 采用CV_RGB2GRAY,转换公式Gray = 0.1140*R + 0.5870*G + 0.2989*B b = 0.114 *128 = 14.529 = 15 g = 0.587 * 128 = 75.136 = 75 r = 0.2989 * 128 = 38.2592 = 38 Gray = (15*B + 75*G + 38*R)/128 bgr2gray, rgb2gray */ void bgr_gray_basic(const uint8_t* in_data, uint8_t* out_data, int srcw, int srch) { for (int i = 0; i < srch; i++) { const uint8_t* din_ptr = in_data + i * 3 * srcw; uint8_t* dout_ptr = out_data + i * srcw; for (int j = 0; j < srcw; j++) { int sum = din_ptr[0] * 15 + din_ptr[1] * 75 + din_ptr[2] * 38; sum = sum >> 7; *dout_ptr++ = sum; din_ptr += 3; } } } void bgra_gray_basic(const uint8_t* in_data, uint8_t* out_data, int srcw, int srch) { for (int i = 0; i < srch; i++) { const uint8_t* din_ptr = in_data + i * 4 * srcw; uint8_t* dout_ptr = out_data + i * srcw; for (int j = 0; j < srcw; j++) { int sum = din_ptr[0] * 15 + din_ptr[1] * 75 + din_ptr[2] * 38; sum = sum >> 7; *dout_ptr++ = sum; din_ptr += 4; } } } void gray_bgr_basic(const uint8_t* src, uint8_t* dst, int srcw, int srch) { for (int i = 0; i < srch; i++) { for (int j = 0; j < srcw; j++) { *dst++ = *src; *dst++ = *src; *dst++ = *src; src++; } } } void gray_bgra_basic(const uint8_t* src, uint8_t* dst, int srcw, int srch) { for (int i = 0; i < srch; i++) { for (int j = 0; j < srcw; j++) { *dst++ = *src; *dst++ = *src; *dst++ = *src; *dst++ = 255; src++; } } } // bgr2bgra, rgb2rgba void hwc3_to_hwc4_basic(const uint8_t* src, uint8_t* dst, int srcw, int srch) { for (int i = 0; i < srch; i++) { for (int j = 0; j < srcw; j++) { *dst++ = *src++; *dst++ = *src++; *dst++ = *src++; *dst++ = 255; } } } // bgra2bgr, rgba2rgb void hwc4_to_hwc3_basic(const uint8_t* src, uint8_t* dst, int srcw, int srch) { for (int i = 0; i < srch; i++) { for (int j = 0; j < srcw; j++) { *dst++ = *src++; *dst++ = *src++; *dst++ = *src++; src++; } } } // bgr2rgb, rgb2bgr void hwc3_trans_basic(const uint8_t* src, uint8_t* dst, int srcw, int srch) { for (int i = 0; i < srch; i++) { for (int j = 0; j < srcw; j++) { *dst++ = src[2]; // r *dst++ = src[1]; // g *dst++ = src[0]; // b src += 3; } } } // bgra2rgba, rgba2bgra void hwc4_trans_basic(const uint8_t* src, uint8_t* dst, int srcw, int srch) { for (int i = 0; i < srch; i++) { for (int j = 0; j < srcw; j++) { *dst++ = src[2]; // r *dst++ = src[1]; // g *dst++ = src[0]; // b *dst++ = src[3]; // a src += 4; } } } // bgra2rgb, rgba2bgr void hwc4_trans_hwc3_basic(const uint8_t* src, uint8_t* dst, int srcw, int srch) { for (int i = 0; i < srch; i++) { for (int j = 0; j < srcw; j++) { *dst++ = src[2]; // r *dst++ = src[1]; // g *dst++ = src[0]; // b // *dst++ = src[4];//a src += 4; } } } // bgr2rgba, rgb2bga void hwc3_trans_hwc4_basic(const uint8_t* src, uint8_t* dst, int srcw, int srch) { for (int i = 0; i < srch; i++) { for (int j = 0; j < srcw; j++) { *dst++ = src[2]; // r *dst++ = src[1]; // g *dst++ = src[0]; // b *dst++ = 255; // a src += 3; } } } void image_convert_basic(const uint8_t* in_data, uint8_t* out_data, ImageFormat srcFormat, ImageFormat dstFormat, int srcw, int srch, int out_size) { if (srcFormat == dstFormat) { // copy memcpy(out_data, in_data, sizeof(uint8_t) * out_size); return; } else { if (srcFormat == ImageFormat::NV12 && (dstFormat == ImageFormat::BGR || dstFormat == ImageFormat::RGB)) { nv12_bgr_basic(in_data, out_data, srcw, srch); } else if (srcFormat == ImageFormat::NV21 && (dstFormat == ImageFormat::BGR || dstFormat == ImageFormat::RGB)) { nv21_bgr_basic(in_data, out_data, srcw, srch); } else if (srcFormat == ImageFormat::NV12 && (dstFormat == ImageFormat::BGRA || dstFormat == ImageFormat::RGBA)) { nv12_bgra_basic(in_data, out_data, srcw, srch); } else if (srcFormat == ImageFormat::NV21 && (dstFormat == ImageFormat::BGRA || dstFormat == ImageFormat::RGBA)) { nv21_bgra_basic(in_data, out_data, srcw, srch); } else if ((srcFormat == ImageFormat::RGB && dstFormat == ImageFormat::GRAY) || (srcFormat == ImageFormat::BGR && dstFormat == ImageFormat::GRAY)) { bgr_gray_basic(in_data, out_data, srcw, srch); } else if ((srcFormat == ImageFormat::GRAY && dstFormat == ImageFormat::RGB) || (srcFormat == ImageFormat::GRAY && dstFormat == ImageFormat::BGR)) { gray_bgr_basic(in_data, out_data, srcw, srch); } else if ((srcFormat == ImageFormat::RGBA && dstFormat == ImageFormat::GRAY) || (srcFormat == ImageFormat::BGRA && dstFormat == ImageFormat::GRAY)) { bgra_gray_basic(in_data, out_data, srcw, srch); } else if ((srcFormat == ImageFormat::GRAY && dstFormat == ImageFormat::RGBA) || (srcFormat == ImageFormat::GRAY && dstFormat == ImageFormat::BGRA)) { gray_bgra_basic(in_data, out_data, srcw, srch); } else if ((srcFormat == ImageFormat::RGBA && dstFormat == ImageFormat::RGB) || (srcFormat == ImageFormat::BGRA && dstFormat == ImageFormat::BGR)) { hwc4_to_hwc3_basic(in_data, out_data, srcw, srch); } else if ((srcFormat == ImageFormat::RGB && dstFormat == ImageFormat::RGBA) || (srcFormat == ImageFormat::BGR && dstFormat == ImageFormat::BGRA)) { hwc3_to_hwc4_basic(in_data, out_data, srcw, srch); } else if ((srcFormat == ImageFormat::RGB && dstFormat == ImageFormat::BGR) || (srcFormat == ImageFormat::BGR && dstFormat == ImageFormat::RGB)) { hwc3_trans_basic(in_data, out_data, srcw, srch); } else if ((srcFormat == ImageFormat::RGBA && dstFormat == ImageFormat::BGRA) || (srcFormat == ImageFormat::BGRA && dstFormat == ImageFormat::RGBA)) { hwc4_trans_basic(in_data, out_data, srcw, srch); } else if ((srcFormat == ImageFormat::RGBA && dstFormat == ImageFormat::BGR) || (srcFormat == ImageFormat::BGRA && dstFormat == ImageFormat::RGB)) { hwc4_trans_hwc3_basic(in_data, out_data, srcw, srch); } else if ((srcFormat == ImageFormat::RGB && dstFormat == ImageFormat::BGRA) || (srcFormat == ImageFormat::BGR && dstFormat == ImageFormat::RGBA)) { hwc3_trans_hwc4_basic(in_data, out_data, srcw, srch); } else { printf("srcFormat: %d, dstFormat: %d does not support! \n", srcFormat, dstFormat); } // for (int i = 0; i < out_size; i++){ // printf("%d ", *out_data++); // if ((i+1) % 10 == 0){ // printf("\n"); // } // } } } void compute_xy(int srcw, int srch, int dstw, int dsth, double scale_x, double scale_y, int* xofs, int* yofs, float* ialpha, float* ibeta) { float fy = 0.f; float fx = 0.f; int sy = 0; int sx = 0; const int resize_coef_bits = 11; const int resize_coef_scale = 1 << resize_coef_bits; for (int dx = 0; dx < dstw; dx++) { fx = static_cast<float>((dx + 0.5) * scale_x - 0.5); sx = floor(fx); fx -= sx; if (sx < 0) { sx = 0; fx = 0.f; } if (sx >= srcw - 1) { sx = srcw - 2; fx = 1.f; } xofs[dx] = sx; float a0 = (1.f - fx); float a1 = fx; ialpha[dx * 2] = a0; ialpha[dx * 2 + 1] = a1; } for (int dy = 0; dy < dsth; dy++) { fy = static_cast<float>((dy + 0.5) * scale_y - 0.5); sy = floor(fy); fy -= sy; if (sy < 0) { sy = 0; fy = 0.f; } if (sy >= srch - 1) { sy = srch - 2; fy = 1.f; } yofs[dy] = sy; float b0 = (1.f - fy); float b1 = fy; ibeta[dy * 2] = b0; ibeta[dy * 2 + 1] = b1; } } void image_resize_basic(const uint8_t* in_data, uint8_t* out_data, ImageFormat srcFormat, int srcw, int srch, int dstw, int dsth) { int size = srcw * srch; if (srcw == dstw && srch == dsth) { if (srcFormat == ImageFormat::NV12 || srcFormat == ImageFormat::NV21) { size = srcw * (ceil(1.5 * srch)); } else if (srcFormat == ImageFormat::BGR || srcFormat == ImageFormat::RGB) { size = 3 * srcw * srch; } else if (srcFormat == ImageFormat::BGRA || srcFormat == ImageFormat::RGBA) { size = 4 * srcw * srch; } memcpy(out_data, in_data, sizeof(uint8_t) * size); return; } double scale_x = static_cast<double>(srcw / dstw); double scale_y = static_cast<double>(srch / dsth); int* buf = new int[dstw + dsth]; int* xofs = buf; int* yofs = buf + dstw; float* ialpha = new float[dstw * 2]; float* ibeta = new float[dsth * 2]; int w_in = srcw; int w_out = dstw; int num = 1; int orih = dsth; compute_xy( srcw, srch, dstw, dsth, scale_x, scale_y, xofs, yofs, ialpha, ibeta); if (srcFormat == ImageFormat::GRAY) { num = 1; } else if (srcFormat == ImageFormat::NV12 || srcFormat == ImageFormat::NV21) { int hout = static_cast<int>(0.5 * dsth); // uv todo w_out = dstw; num = 1; dsth += hout; } else if (srcFormat == ImageFormat::BGR || srcFormat == ImageFormat::RGB) { w_in = srcw * 3; w_out = dstw * 3; num = 3; } else if (srcFormat == ImageFormat::BGRA || srcFormat == ImageFormat::RGBA) { w_in = srcw * 4; w_out = dstw * 4; num = 4; } float* ialpha1 = nullptr; int* xofs1 = nullptr; int* yofs1 = nullptr; if (orih < dsth) { int tmp = dsth - orih; float* ialpha1 = new float[dstw]; int* xofs1 = new int[srcw]; int* yofs1 = new int[tmp]; compute_xy(srcw / 2, srch / 2, dstw / 2, tmp, scale_x, scale_y, xofs1, yofs1, ialpha1, ibeta + dsth); } #pragma omp parallel for for (int dy = 0; dy < dsth; dy++) { uint8_t* out_ptr = out_data + dy * w_out; int y_in_start = yofs[dy]; int y_in_end = y_in_start + 1; int y_flag = 0; // only one line if (y_in_start < 0) { y_flag = 1; y_in_end = 0; } float b0 = ibeta[dy * 2]; float b1 = ibeta[dy * 2 + 1]; if (dy >= orih) { num = 2; // uv ialpha = ialpha1; xofs = xofs1; yofs = yofs1; } for (int dx = 0; dx < w_out; dx += num) { int tmp = dx / num; int x_in_start = xofs[tmp] * num; // 0 int x_in_end = x_in_start + num; // 2 int x_flag = 0; if (x_in_start < 0) { x_flag = 1; x_in_end = 0; } // printf("x_in: %d, y_in: %d \n", x_in_start, y_in_start); float a0 = ialpha[tmp * 2]; float a1 = ialpha[tmp * 2 + 1]; int tl_index = y_in_start * w_in + x_in_start; // 0 int tr_index = y_in_start * w_in + x_in_end; // 2 int bl_index = y_in_end * w_in + x_in_start; int br_index = y_in_end * w_in + x_in_end; int ind = dx; for (int i = 0; i < num; i++) { int tl = in_data[tl_index]; int tr = in_data[tr_index]; int bl = in_data[bl_index]; int br = in_data[br_index]; if (y_flag == 1) { tl = 0; tr = 0; } if (x_flag == 1) { tl = 0; bl = 0; } tl_index++; tr_index++; bl_index++; br_index++; float outval = (tl * a0 + tr * a1) * b0 + (bl * a0 + br * a1) * b1; // printf("tl: %d, tr: %d, bl: %d, br: %d \n", tl, tr, bl, br); // printf("br_index: %d, a0: %f, b1: %f, out: %f \n", br_index, a0, b1, // outval); out_ptr[ind++] = ceil(outval); } } } } void rotate90_basic(const uint8_t* in_data, int h_in, int w_in, uint8_t* out_data, int h_out, int w_out, int num) { int win = w_in * num; int wout = w_out * num; for (int x = 0; x < h_in; x++) { for (int y = 0; y < w_in; y++) { int tmpy = y * num; int tmpx = (w_out - 1 - x) * num; // x for (int i = 0; i < num; i++) { out_data[y * wout + tmpx] = in_data[x * win + tmpy]; tmpx++; tmpy++; } } } } void rotate180_basic(const uint8_t* in_data, int h_in, int w_in, uint8_t* out_data, int h_out, int w_out, int num) { int win = w_in * num; int h = h_in - 1; int w = win - 1; for (int x = 0; x < h_in; x++) { for (int y = 0; y < w_in; y++) { int tmpy = y * num; int tmp = tmpy + (num - 1); for (int i = 0; i < num; i++) { out_data[(h - x) * win + w - tmp] = in_data[x * win + tmpy]; tmpy++; tmp--; } } } } void rotate270_basic(const uint8_t* in_data, int h_in, int w_in, uint8_t* out_data, int h_out, int w_out, int num) { int win = w_in * num; int wout = w_out * num; int h = h_out - 1; for (int x = 0; x < h_in; x++) { for (int y = 0; y < w_in; y++) { int tmpy = y * num; int tmpx = x * num; for (int i = 0; i < num; i++) { out_data[(h - y) * wout + tmpx] = in_data[x * win + tmpy]; // (y,x) = in(x,y) tmpx++; tmpy++; } } } } void image_rotate_basic(const uint8_t* in_data, uint8_t* out_data, ImageFormat srcFormat, int srcw, int srch, float rotate) { int num = 1; if (srcFormat == ImageFormat::GRAY) { num = 1; } else if (srcFormat == ImageFormat::NV12 || srcFormat == ImageFormat::NV21) { num = 1; // todo return; } else if (srcFormat == ImageFormat::BGR || srcFormat == ImageFormat::RGB) { num = 3; } else if (srcFormat == ImageFormat::BGRA || srcFormat == ImageFormat::RGBA) { num = 4; } if (rotate == 90) { rotate90_basic(in_data, srch, srcw, out_data, srcw, srch, num); } else if (rotate == 180) { rotate180_basic(in_data, srch, srcw, out_data, srch, srcw, num); } else if (rotate == 270) { rotate270_basic(in_data, srch, srcw, out_data, srcw, srch, num); } } void flipx_basic( const uint8_t* in_data, int h_in, int w_in, uint8_t* out_data, int num) { int h = h_in - 1; int w = w_in * num; for (int x = 0; x < h_in; x++) { for (int y = 0; y < w_in; y++) { int tmpy = y * num; for (int i = 0; i < num; i++) { out_data[(h - x) * w + tmpy] = in_data[x * w + tmpy]; // (y,x) = in(x,y) tmpy++; } } } } void flipy_basic( const uint8_t* in_data, int h_in, int w_in, uint8_t* out_data, int num) { int w = w_in * num - 1; for (int x = 0; x < h_in; x++) { for (int y = 0; y < w_in; y++) { int tmpy = y * num; int tmp = tmpy + (num - 1); for (int i = 0; i < num; i++) { out_data[x * w_in * num + w - tmp] = in_data[x * w_in * num + tmpy]; // (y,x) = in(x,y) tmpy++; tmp--; } } } } void flipxy_basic( const uint8_t* in_data, int h_in, int w_in, uint8_t* out_data, int num) { int win = w_in * num; int h = h_in - 1; int w = win - 1; for (int x = 0; x < h_in; x++) { for (int y = 0; y < w_in; y++) { int tmpy = y * num; int tmp = tmpy + (num - 1); for (int i = 0; i < num; i++) { out_data[(h - x) * win + w - tmp] = in_data[x * win + tmpy]; // (h-y,w-x) = in(x,y) tmpy++; tmp--; } } } } void image_flip_basic(const uint8_t* in_data, uint8_t* out_data, ImageFormat srcFormat, int srcw, int srch, FlipParam flip) { int num = 1; if (srcFormat == ImageFormat::GRAY) { num = 1; } else if (srcFormat == ImageFormat::NV12 || srcFormat == ImageFormat::NV21) { num = 1; // todo return; } else if (srcFormat == ImageFormat::BGR || srcFormat == ImageFormat::RGB) { num = 3; } else if (srcFormat == ImageFormat::BGRA || srcFormat == ImageFormat::RGBA) { num = 4; } // printf("image_flip_basic: %d \n", flip); if (flip == FlipParam::X) { flipx_basic(in_data, srch, srcw, out_data, num); } else if (flip == FlipParam::Y) { flipy_basic(in_data, srch, srcw, out_data, num); } else if (flip == FlipParam::XY) { flipxy_basic(in_data, srch, srcw, out_data, num); } } void gray_to_tensor_basic(const uint8_t* bgr, float* output, int width, int height, float* means, float* scales, int num) { int size = width * height; float mean_val = means[0]; float scale_val = scales[0]; for (int h = 0; h < height; h++) { const uint8_t* ptr_bgr = bgr + h * width * num; float* ptr_h = output + h * width; for (int i = 0; i < width; i++) { *ptr_h++ = (ptr_bgr[0] - mean_val) * scale_val; ptr_bgr += num; } } } void bgr_to_tensor_chw_basic(const uint8_t* bgr, float* output, int width, int height, float* means, float* scales, int num) { int size = width * height; float r_means = means[0]; float g_means = means[1]; float b_means = means[2]; float r_scales = scales[0]; float g_scales = scales[1]; float b_scales = scales[2]; for (int h = 0; h < height; h++) { const uint8_t* ptr_bgr = bgr + h * width * num; float* ptr_b = output + h * width; float* ptr_g = ptr_b + size; float* ptr_r = ptr_g + size; for (int i = 0; i < width; i++) { *ptr_b++ = (ptr_bgr[0] - b_means) * b_scales; *ptr_g++ = (ptr_bgr[1] - g_means) * g_scales; *ptr_r++ = (ptr_bgr[2] - r_means) * r_scales; ptr_bgr += num; } } } void bgr_to_tensor_hwc_basic(const uint8_t* bgr, float* output, int width, int height, float* means, float* scales, int num) { int size = width * height; float r_means = means[0]; float g_means = means[1]; float b_means = means[2]; float r_scales = scales[0]; float g_scales = scales[1]; float b_scales = scales[2]; for (int h = 0; h < height; h++) { const uint8_t* ptr_bgr = bgr + h * width * num; float* out_bgr = output + h * width * num; for (int i = 0; i < width; i++) { *out_bgr++ = (ptr_bgr[0] - b_means) * b_scales; *out_bgr++ = (ptr_bgr[1] - g_means) * g_scales; *out_bgr++ = (ptr_bgr[2] - r_means) * r_scales; ptr_bgr += num; } } } void image_to_tensor_basic(const uint8_t* in_data, Tensor* dst, ImageFormat srcFormat, LayoutType layout, int srcw, int srch, float* means, float* scales) { float* output = dst->mutable_data<float>(); if (layout == LayoutType::kNCHW && (srcFormat == ImageFormat::BGR || srcFormat == ImageFormat::RGB)) { bgr_to_tensor_chw_basic(in_data, output, srcw, srch, means, scales, 3); } else if (layout == LayoutType::kNHWC && (srcFormat == ImageFormat::BGR || srcFormat == ImageFormat::RGB)) { bgr_to_tensor_hwc_basic(in_data, output, srcw, srch, means, scales, 3); } else if (layout == LayoutType::kNCHW && (srcFormat == ImageFormat::BGRA || srcFormat == ImageFormat::RGBA)) { bgr_to_tensor_chw_basic(in_data, output, srcw, srch, means, scales, 4); } else if (layout == LayoutType::kNHWC && (srcFormat == ImageFormat::BGRA || srcFormat == ImageFormat::RGBA)) { bgr_to_tensor_hwc_basic(in_data, output, srcw, srch, means, scales, 4); } else if (srcFormat == ImageFormat::GRAY && (layout == LayoutType::kNHWC || layout == LayoutType::kNCHW)) { gray_to_tensor_basic(in_data, output, srcw, srch, means, scales, 1); } }
linked_tasks.c
#include <omp.h> #include <stdlib.h> #include <stdio.h> #ifndef N #define N 5 #endif #ifndef FS #define FS 38 #endif struct node { int data; int fibdata; struct node* next; }; struct node* init_list(struct node* p); void processwork(struct node* p); int fib(int n); int fib(int n) { int x, y; if (n < 2) { return (n); } else { x = fib(n - 1); y = fib(n - 2); return (x + y); } } void processwork(struct node* p) { int n, temp; n = p->data; temp = fib(n); p->fibdata = temp; } struct node* init_list(struct node* p) { int i; struct node* head = NULL; struct node* temp = NULL; head = malloc(sizeof(struct node)); p = head; p->data = FS; p->fibdata = 0; for (i=0; i< N; i++) { temp = malloc(sizeof(struct node)); p->next = temp; p = temp; p->data = FS + i + 1; p->fibdata = i+1; } p->next = NULL; return head; } int main() { double start, end; struct node *p=NULL; struct node *temp=NULL; struct node *head=NULL; printf("Process linked list\n"); printf(" Each linked list node will be processed by function 'processwork()'\n"); printf(" Each ll node will compute %d fibonacci numbers beginning with %d\n",N,FS); p = init_list(p); head = p; start = omp_get_wtime(); #pragma omp parallel { #pragma omp master printf("Threads: %d\n", omp_get_num_threads()); #pragma omp single { p=head; while (p) { #pragma omp task firstprivate(p) //first private is required { processwork(p); } p = p->next; } } } end = omp_get_wtime(); p = head; while (p != NULL) { printf("%d : %d\n",p->data, p->fibdata); temp = p->next; free (p); p = temp; } free (p); printf("Compute Time: %f seconds\n", end - start); return 0; }
GB_binop__gt_int8.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__gt_int8) // A.*B function (eWiseMult): GB (_AemultB_08__gt_int8) // A.*B function (eWiseMult): GB (_AemultB_02__gt_int8) // A.*B function (eWiseMult): GB (_AemultB_04__gt_int8) // A.*B function (eWiseMult): GB (_AemultB_bitmap__gt_int8) // A*D function (colscale): GB (_AxD__gt_int8) // D*A function (rowscale): GB (_DxB__gt_int8) // C+=B function (dense accum): GB (_Cdense_accumB__gt_int8) // C+=b function (dense accum): GB (_Cdense_accumb__gt_int8) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__gt_int8) // C=scalar+B GB (_bind1st__gt_int8) // C=scalar+B' GB (_bind1st_tran__gt_int8) // C=A+scalar GB (_bind2nd__gt_int8) // C=A'+scalar GB (_bind2nd_tran__gt_int8) // C type: bool // A type: int8_t // A pattern? 0 // B type: int8_t // B pattern? 0 // BinaryOp: cij = (aij > bij) #define GB_ATYPE \ int8_t #define GB_BTYPE \ int8_t #define GB_CTYPE \ bool // 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 \ 0 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 0 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA,A_iso) \ int8_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) \ int8_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) \ bool 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_GT || GxB_NO_INT8 || GxB_NO_GT_INT8) //------------------------------------------------------------------------------ // 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__gt_int8) ( 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__gt_int8) ( 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 #if 0 { #include "GB_dense_subassign_23_template.c" } #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__gt_int8) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if 0 { // get the scalar b for C += b, of type int8_t int8_t bwork = (*((int8_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_AxD__gt_int8) ( 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 bool *restrict Cx = (bool *) 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__gt_int8) ( GrB_Matrix C, const GrB_Matrix D, const GrB_Matrix B, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else bool *restrict Cx = (bool *) 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__gt_int8) ( 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) ; int8_t alpha_scalar ; int8_t beta_scalar ; if (is_eWiseUnion) { alpha_scalar = (*((int8_t *) alpha_scalar_in)) ; beta_scalar = (*((int8_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__gt_int8) ( 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__gt_int8) ( 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__gt_int8) ( 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__gt_int8) ( 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__gt_int8) ( 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 bool *Cx = (bool *) Cx_output ; int8_t x = (*((int8_t *) x_input)) ; int8_t *Bx = (int8_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 ; int8_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__gt_int8) ( 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 ; bool *Cx = (bool *) Cx_output ; int8_t *Ax = (int8_t *) Ax_input ; int8_t y = (*((int8_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; int8_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) \ { \ int8_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (x > aij) ; \ } GrB_Info GB (_bind1st_tran__gt_int8) ( 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 \ int8_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else int8_t x = (*((const int8_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ int8_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) \ { \ int8_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (aij > y) ; \ } GrB_Info GB (_bind2nd_tran__gt_int8) ( 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 int8_t y = (*((const int8_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
grid_ao_drv.c
/* * Author: Qiming Sun <osirpt.sun@gmail.com> */ #include <stdlib.h> #include <string.h> #include <math.h> #include <complex.h> #include "config.h" #include "grid_ao_drv.h" #define MIN(X,Y) ((X)<(Y)?(X):(Y)) #define MAX(X,Y) ((X)>(Y)?(X):(Y)) double exp_cephes(double x); double CINTcommon_fac_sp(int l); void GTOnabla1(double *fx1, double *fy1, double *fz1, double *fx0, double *fy0, double *fz0, int l, double a) { int i, n; double a2 = -2 * a; for (n = 0; n < SIMDD; n++) { fx1[n] = a2*fx0[SIMDD+n]; fy1[n] = a2*fy0[SIMDD+n]; fz1[n] = a2*fz0[SIMDD+n]; } for (i = 1; i <= l; i++) { for (n = 0; n < SIMDD; n++) { fx1[i*SIMDD+n] = i*fx0[(i-1)*SIMDD+n] + a2*fx0[(i+1)*SIMDD+n]; fy1[i*SIMDD+n] = i*fy0[(i-1)*SIMDD+n] + a2*fy0[(i+1)*SIMDD+n]; fz1[i*SIMDD+n] = i*fz0[(i-1)*SIMDD+n] + a2*fz0[(i+1)*SIMDD+n]; } } } /* * r - R_O = (r-R_i) + ri, ri = (x,y,z) = R_i - R_O */ void GTOx1(double *fx1, double *fy1, double *fz1, double *fx0, double *fy0, double *fz0, int l, double *ri) { int i, n; for (i = 0; i <= l; i++) { for (n = 0; n < SIMDD; n++) { fx1[i*SIMDD+n] = ri[0] * fx0[i*SIMDD+n] + fx0[(i+1)*SIMDD+n]; fy1[i*SIMDD+n] = ri[1] * fy0[i*SIMDD+n] + fy0[(i+1)*SIMDD+n]; fz1[i*SIMDD+n] = ri[2] * fz0[i*SIMDD+n] + fz0[(i+1)*SIMDD+n]; } } } int GTOprim_exp(double *eprim, double *coord, double *alpha, double *coeff, int l, int nprim, int nctr, int ngrids, double fac) { int i, j; double arr, maxc; double logcoeff[nprim]; double rr[ngrids]; double *gridx = coord; double *gridy = coord+BLKSIZE; double *gridz = coord+BLKSIZE*2; int not0 = 0; // the maximum value of the coefficients for each pGTO for (j = 0; j < nprim; j++) { maxc = 0; for (i = 0; i < nctr; i++) { maxc = MAX(maxc, fabs(coeff[i*nprim+j])); } logcoeff[j] = log(maxc); } for (i = 0; i < ngrids; i++) { rr[i] = gridx[i]*gridx[i] + gridy[i]*gridy[i] + gridz[i]*gridz[i]; } for (j = 0; j < nprim; j++) { for (i = 0; i < ngrids; i++) { arr = alpha[j] * rr[i]; if (arr-logcoeff[j] < EXPCUTOFF) { eprim[j*BLKSIZE+i] = exp_cephes(-arr) * fac; not0 = 1; } else { eprim[j*BLKSIZE+i] = 0; } } } return not0; } // grid2atm[atm_id,xyz,grid_id] static void _fill_grid2atm(double *grid2atm, double *coord, int bgrids, int ngrids, int *atm, int natm, int *bas, int nbas, double *env) { int atm_id, ig; double *r_atm; for (atm_id = 0; atm_id < natm; atm_id++) { r_atm = env + atm[PTR_COORD+atm_id*ATM_SLOTS]; for (ig = 0; ig < bgrids; ig++) { grid2atm[0*BLKSIZE+ig] = coord[0*ngrids+ig] - r_atm[0]; grid2atm[1*BLKSIZE+ig] = coord[1*ngrids+ig] - r_atm[1]; grid2atm[2*BLKSIZE+ig] = coord[2*ngrids+ig] - r_atm[2]; } grid2atm += 3*BLKSIZE; } } static void _dset0(double *out, int odim, int bgrids, int counts) { int i, j; for (i = 0; i < counts; i++) { for (j = 0; j < bgrids; j++) { out[i*odim+j] = 0; } } } static void _zset0(double complex *out, int odim, int bgrids, int counts) { int i, j; for (i = 0; i < counts; i++) { for (j = 0; j < bgrids; j++) { out[i*odim+j] = 0; } } } void GTOeval_sph_iter(void (*feval)(), int (*fexp)(), double fac, int nao, int ngrids, int bgrids, int param[], int *shls_slice, int *ao_loc, double *buf, double *ao, double *coord, char *non0table, int *atm, int natm, int *bas, int nbas, double *env) { const int ncomp = param[TENSOR]; const int sh0 = shls_slice[0]; const int sh1 = shls_slice[1]; const int atmstart = bas[sh0*BAS_SLOTS+ATOM_OF]; const int atmend = bas[(sh1-1)*BAS_SLOTS+ATOM_OF]+1; const int atmcount = atmend - atmstart; const size_t Ngrids = ngrids; int i, k, l, np, nc, atm_id, bas_id, deg, dcart, ao_id; double fac1; double *p_exp, *pcoeff, *pcoord, *pcart, *ri, *pao; double *grid2atm = buf; // [atm_id,xyz,grid] double *eprim = grid2atm + atmcount*3*BLKSIZE; double *cart_gto = eprim + NPRIMAX*BLKSIZE*2; _fill_grid2atm(grid2atm, coord, bgrids, ngrids, atm+atmstart*ATM_SLOTS, atmcount, bas, nbas, env); for (bas_id = sh0; bas_id < sh1; bas_id++) { np = bas[bas_id*BAS_SLOTS+NPRIM_OF]; nc = bas[bas_id*BAS_SLOTS+NCTR_OF ]; l = bas[bas_id*BAS_SLOTS+ANG_OF ]; deg = l * 2 + 1; fac1 = fac * CINTcommon_fac_sp(l); p_exp = env + bas[bas_id*BAS_SLOTS+PTR_EXP]; pcoeff = env + bas[bas_id*BAS_SLOTS+PTR_COEFF]; atm_id = bas[bas_id*BAS_SLOTS+ATOM_OF]; pcoord = grid2atm + (atm_id - atmstart) * 3*BLKSIZE; ao_id = ao_loc[bas_id] - ao_loc[sh0]; if (non0table[bas_id] && (*fexp)(eprim, pcoord, p_exp, pcoeff, l, np, nc, bgrids, fac1)) { dcart = (l+1)*(l+2)/2; ri = env + atm[PTR_COORD+atm_id*ATM_SLOTS]; if (l <= 1) { // s, p functions (*feval)(ao+ao_id*Ngrids, ri, eprim, pcoord, p_exp, pcoeff, env, l, np, nc, nao, ngrids, bgrids); } else { (*feval)(cart_gto, ri, eprim, pcoord, p_exp, pcoeff, env, l, np, nc, nc*dcart, bgrids, bgrids); pcart = cart_gto; for (i = 0; i < ncomp; i++) { pao = ao + (i*nao+ao_id)*Ngrids; for (k = 0; k < nc; k++) { CINTc2s_ket_sph1(pao, pcart, ngrids, bgrids, l); pao += deg * ngrids; pcart += dcart * bgrids; } } } } else { for (i = 0; i < ncomp; i++) { _dset0(ao+(i*nao+ao_id)*Ngrids, ngrids, bgrids, nc*deg); } } } } void GTOeval_cart_iter(void (*feval)(), int (*fexp)(), double fac, int nao, int ngrids, int bgrids, int param[], int *shls_slice, int *ao_loc, double *buf, double *ao, double *coord, char *non0table, int *atm, int natm, int *bas, int nbas, double *env) { const int ncomp = param[TENSOR]; const int sh0 = shls_slice[0]; const int sh1 = shls_slice[1]; const int atmstart = bas[sh0*BAS_SLOTS+ATOM_OF]; const int atmend = bas[(sh1-1)*BAS_SLOTS+ATOM_OF]+1; const int atmcount = atmend - atmstart; const size_t Ngrids = ngrids; int i, k, l, np, nc, atm_id, bas_id, deg, ao_id; double fac1; double *p_exp, *pcoeff, *pcoord, *pcart, *ri, *pao; double *grid2atm = buf; // [atm_id,xyz,grid] double *eprim = grid2atm + atmcount*3*BLKSIZE; _fill_grid2atm(grid2atm, coord, bgrids, ngrids, atm+atmstart*ATM_SLOTS, atmcount, bas, nbas, env); for (bas_id = sh0; bas_id < sh1; bas_id++) { np = bas[bas_id*BAS_SLOTS+NPRIM_OF]; nc = bas[bas_id*BAS_SLOTS+NCTR_OF ]; l = bas[bas_id*BAS_SLOTS+ANG_OF ]; deg = (l+1)*(l+2)/2; fac1 = fac * CINTcommon_fac_sp(l); p_exp = env + bas[bas_id*BAS_SLOTS+PTR_EXP]; pcoeff = env + bas[bas_id*BAS_SLOTS+PTR_COEFF]; atm_id = bas[bas_id*BAS_SLOTS+ATOM_OF]; pcoord = grid2atm + (atm_id - atmstart) * 3*BLKSIZE; ao_id = ao_loc[bas_id] - ao_loc[sh0]; if (non0table[bas_id] && (*fexp)(eprim, pcoord, p_exp, pcoeff, l, np, nc, bgrids, fac1)) { ri = env + atm[PTR_COORD+atm_id*ATM_SLOTS]; (*feval)(ao+ao_id*Ngrids, ri, eprim, pcoord, p_exp, pcoeff, env, l, np, nc, nao, ngrids, bgrids); } else { for (i = 0; i < ncomp; i++) { _dset0(ao+(i*nao+ao_id)*Ngrids, ngrids, bgrids, nc*deg); } } } } void GTOeval_spinor_iter(void (*feval)(), int (*fexp)(), void (*c2s)(), double fac, int nao, int ngrids, int bgrids, int param[], int *shls_slice, int *ao_loc, double *buf, double complex *ao, double *coord, char *non0table, int *atm, int natm, int *bas, int nbas, double *env) { const int ncomp_e1 = param[POS_E1]; const int ncomp = param[TENSOR]; const int sh0 = shls_slice[0]; const int sh1 = shls_slice[1]; const int atmstart = bas[sh0*BAS_SLOTS+ATOM_OF]; const int atmend = bas[(sh1-1)*BAS_SLOTS+ATOM_OF]+1; const int atmcount = atmend - atmstart; const size_t Ngrids = ngrids; int i, k, l, np, nc, atm_id, bas_id, deg, kappa, dcart, ao_id; size_t off; double fac1; double *p_exp, *pcoeff, *pcoord, *pcart, *ri; double complex *aoa = ao; double complex *aob = ao + ncomp*nao*ngrids; double *grid2atm = buf; // [atm_id,xyz,grid] double *eprim = grid2atm + atmcount*3*BLKSIZE; double *cart_gto = eprim + NPRIMAX*BLKSIZE*2; _fill_grid2atm(grid2atm, coord, bgrids, ngrids, atm+atmstart*ATM_SLOTS, atmcount, bas, nbas, env); for (bas_id = sh0; bas_id < sh1; bas_id++) { np = bas[bas_id*BAS_SLOTS+NPRIM_OF]; nc = bas[bas_id*BAS_SLOTS+NCTR_OF ]; l = bas[bas_id*BAS_SLOTS+ANG_OF ]; deg = CINTlen_spinor(bas_id, bas); fac1 = fac * CINTcommon_fac_sp(l); p_exp = env + bas[bas_id*BAS_SLOTS+PTR_EXP]; pcoeff = env + bas[bas_id*BAS_SLOTS+PTR_COEFF]; atm_id = bas[bas_id*BAS_SLOTS+ATOM_OF]; pcoord = grid2atm + (atm_id - atmstart) * 3*BLKSIZE; ao_id = ao_loc[bas_id] - ao_loc[sh0]; if (non0table[bas_id] && (*fexp)(eprim, pcoord, p_exp, pcoeff, l, np, nc, bgrids, fac1)) { kappa = bas[bas_id*BAS_SLOTS+KAPPA_OF]; dcart = (l+1)*(l+2)/2; ri = env + atm[PTR_COORD+atm_id*ATM_SLOTS]; (*feval)(cart_gto, ri, eprim, pcoord, p_exp, pcoeff, env, l, np, nc, nc*dcart, bgrids, bgrids); for (i = 0; i < ncomp; i++) { pcart = cart_gto + i * nc*dcart*bgrids*ncomp_e1; off = (i*nao+ao_id)*Ngrids; (*c2s)(aoa+off, aob+off, pcart, ngrids, bgrids, nc, kappa, l); } } else { for (i = 0; i < ncomp; i++) { off = (i*nao+ao_id)*Ngrids; _zset0(aoa+off, ngrids, bgrids, nc*deg); _zset0(aob+off, ngrids, bgrids, nc*deg); } } } } int GTOshloc_by_atom(int *shloc, int *shls_slice, int *ao_loc, int *atm, int *bas) { const int sh0 = shls_slice[0]; const int sh1 = shls_slice[1]; int ish, nshblk, lastatm; shloc[0] = sh0; nshblk = 1; lastatm = bas[BAS_SLOTS*sh0+ATOM_OF]; for (ish = sh0; ish < sh1; ish++) { if (lastatm != bas[BAS_SLOTS*ish+ATOM_OF]) { lastatm = bas[BAS_SLOTS*ish+ATOM_OF]; shloc[nshblk] = ish; nshblk++; } } shloc[nshblk] = sh1; return nshblk; } /* * non0table[ngrids/blksize,natm] is the T/F table for ao values to * screen the ao evaluation for each shell */ void GTOeval_loop(void (*fiter)(), void (*feval)(), int (*fexp)(), double fac, int ngrids, int param[], int *shls_slice, int *ao_loc, double *ao, double *coord, char *non0table, int *atm, int natm, int *bas, int nbas, double *env) { int shloc[shls_slice[1]-shls_slice[0]+1]; const int nshblk = GTOshloc_by_atom(shloc, shls_slice, ao_loc, atm, bas); const int nblk = (ngrids+BLKSIZE-1) / BLKSIZE; const size_t Ngrids = ngrids; #pragma omp parallel default(none) \ shared(fiter, feval, fexp, fac, param, ao_loc, shls_slice, ngrids, \ ao, coord, non0table, atm, natm, bas, nbas, env, shloc) { const int sh0 = shls_slice[0]; const int sh1 = shls_slice[1]; const int nao = ao_loc[sh1] - ao_loc[sh0]; int ip, ib, k, iloc, ish; size_t aoff; int ncart = NCTR_CART * param[TENSOR] * param[POS_E1]; double *buf = malloc(sizeof(double) * BLKSIZE*(NPRIMAX*2+ncart)); #pragma omp for schedule(static) for (k = 0; k < nblk*nshblk; k++) { iloc = k / nblk; ish = shloc[iloc]; aoff = ao_loc[ish] - ao_loc[sh0]; ib = k - iloc * nblk; ip = ib * BLKSIZE; (*fiter)(feval, fexp, fac, nao, ngrids, MIN(ngrids-ip, BLKSIZE), param, shloc+iloc, ao_loc, buf, ao+aoff*Ngrids+ip, coord+ip, non0table+ib*nbas, atm, natm, bas, nbas, env); } free(buf); } } void GTOeval_sph_drv(void (*feval)(), int (*fexp)(), double fac, int ngrids, int param[], int *shls_slice, int *ao_loc, double *ao, double *coord, char *non0table, int *atm, int natm, int *bas, int nbas, double *env) { GTOeval_loop(GTOeval_sph_iter, feval, fexp, fac, ngrids, param, shls_slice, ao_loc, ao, coord, non0table, atm, natm, bas, nbas, env); } void GTOeval_cart_drv(void (*feval)(), int (*fexp)(), double fac, int ngrids, int param[], int *shls_slice, int *ao_loc, double *ao, double *coord, char *non0table, int *atm, int natm, int *bas, int nbas, double *env) { GTOeval_loop(GTOeval_cart_iter, feval, fexp, fac, ngrids, param, shls_slice, ao_loc, ao, coord, non0table, atm, natm, bas, nbas, env); } void GTOeval_spinor_drv(void (*feval)(), int (*fexp)(), void (*c2s)(), double fac, int ngrids, int param[], int *shls_slice, int *ao_loc, double complex *ao, double *coord, char *non0table, int *atm, int natm, int *bas, int nbas, double *env) { int shloc[shls_slice[1]-shls_slice[0]+1]; const int nshblk = GTOshloc_by_atom(shloc, shls_slice, ao_loc, atm, bas); const int nblk = (ngrids+BLKSIZE-1) / BLKSIZE; const size_t Ngrids = ngrids; #pragma omp parallel default(none) \ shared(feval, fexp, c2s, fac, ngrids, param, ao_loc, shls_slice, \ ao, coord, non0table, atm, natm, bas, nbas, env, shloc) { const int sh0 = shls_slice[0]; const int sh1 = shls_slice[1]; const int nao = ao_loc[sh1] - ao_loc[sh0]; int ip, ib, k, iloc, ish; size_t aoff; int ncart = NCTR_CART * param[TENSOR] * param[POS_E1]; double *buf = malloc(sizeof(double) * BLKSIZE*(NPRIMAX*2+ncart)); #pragma omp for schedule(static) for (k = 0; k < nblk*nshblk; k++) { iloc = k / nblk; ish = shloc[iloc]; aoff = ao_loc[ish] - ao_loc[sh0]; ib = k - iloc * nblk; ip = ib * BLKSIZE; GTOeval_spinor_iter(feval, fexp, c2s, fac, nao, ngrids, MIN(ngrids-ip, BLKSIZE), param, shloc+iloc, ao_loc, buf, ao+aoff*Ngrids+ip, coord+ip, non0table+ib*nbas, atm, natm, bas, nbas, env); } free(buf); } }
CGOpenMPRuntime.h
//===----- CGOpenMPRuntime.h - Interface to OpenMP Runtimes -----*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This provides a class for OpenMP runtime code generation. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_LIB_CODEGEN_CGOPENMPRUNTIME_H #define LLVM_CLANG_LIB_CODEGEN_CGOPENMPRUNTIME_H #include "CGValue.h" #include "clang/AST/DeclOpenMP.h" #include "clang/AST/GlobalDecl.h" #include "clang/AST/Type.h" #include "clang/Basic/OpenMPKinds.h" #include "clang/Basic/SourceLocation.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/PointerIntPair.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/ADT/StringMap.h" #include "llvm/ADT/StringSet.h" #include "llvm/Frontend/OpenMP/OMPConstants.h" #include "llvm/Frontend/OpenMP/OMPIRBuilder.h" #include "llvm/IR/Function.h" #include "llvm/IR/ValueHandle.h" #include "llvm/Support/AtomicOrdering.h" namespace llvm { class ArrayType; class Constant; class FunctionType; class GlobalVariable; class Type; class Value; class OpenMPIRBuilder; } // namespace llvm namespace clang { class Expr; class OMPDependClause; class OMPExecutableDirective; class OMPLoopDirective; class VarDecl; class OMPDeclareReductionDecl; namespace CodeGen { class Address; class CodeGenFunction; class CodeGenModule; /// A basic class for pre|post-action for advanced codegen sequence for OpenMP /// region. class PrePostActionTy { public: explicit PrePostActionTy() {} virtual void Enter(CodeGenFunction &CGF) {} virtual void Exit(CodeGenFunction &CGF) {} virtual ~PrePostActionTy() {} }; /// Class provides a way to call simple version of codegen for OpenMP region, or /// an advanced with possible pre|post-actions in codegen. class RegionCodeGenTy final { intptr_t CodeGen; typedef void (*CodeGenTy)(intptr_t, CodeGenFunction &, PrePostActionTy &); CodeGenTy Callback; mutable PrePostActionTy *PrePostAction; RegionCodeGenTy() = delete; template <typename Callable> static void CallbackFn(intptr_t CodeGen, CodeGenFunction &CGF, PrePostActionTy &Action) { return (*reinterpret_cast<Callable *>(CodeGen))(CGF, Action); } public: template <typename Callable> RegionCodeGenTy( Callable &&CodeGen, std::enable_if_t<!std::is_same<std::remove_reference_t<Callable>, RegionCodeGenTy>::value> * = nullptr) : CodeGen(reinterpret_cast<intptr_t>(&CodeGen)), Callback(CallbackFn<std::remove_reference_t<Callable>>), PrePostAction(nullptr) {} void setAction(PrePostActionTy &Action) const { PrePostAction = &Action; } void operator()(CodeGenFunction &CGF) const; }; struct OMPTaskDataTy final { SmallVector<const Expr *, 4> PrivateVars; SmallVector<const Expr *, 4> PrivateCopies; SmallVector<const Expr *, 4> FirstprivateVars; SmallVector<const Expr *, 4> FirstprivateCopies; SmallVector<const Expr *, 4> FirstprivateInits; SmallVector<const Expr *, 4> LastprivateVars; SmallVector<const Expr *, 4> LastprivateCopies; SmallVector<const Expr *, 4> ReductionVars; SmallVector<const Expr *, 4> ReductionOrigs; SmallVector<const Expr *, 4> ReductionCopies; SmallVector<const Expr *, 4> ReductionOps; SmallVector<CanonicalDeclPtr<const VarDecl>, 4> PrivateLocals; struct DependData { OpenMPDependClauseKind DepKind = OMPC_DEPEND_unknown; const Expr *IteratorExpr = nullptr; SmallVector<const Expr *, 4> DepExprs; explicit DependData() = default; DependData(OpenMPDependClauseKind DepKind, const Expr *IteratorExpr) : DepKind(DepKind), IteratorExpr(IteratorExpr) {} }; SmallVector<DependData, 4> Dependences; llvm::PointerIntPair<llvm::Value *, 1, bool> Final; llvm::PointerIntPair<llvm::Value *, 1, bool> Schedule; llvm::PointerIntPair<llvm::Value *, 1, bool> Priority; llvm::Value *Reductions = nullptr; unsigned NumberOfParts = 0; bool Tied = true; bool Nogroup = false; bool IsReductionWithTaskMod = false; bool IsWorksharingReduction = false; }; /// Class intended to support codegen of all kind of the reduction clauses. class ReductionCodeGen { private: /// Data required for codegen of reduction clauses. struct ReductionData { /// Reference to the item shared between tasks to reduce into. const Expr *Shared = nullptr; /// Reference to the original item. const Expr *Ref = nullptr; /// Helper expression for generation of private copy. const Expr *Private = nullptr; /// Helper expression for generation reduction operation. const Expr *ReductionOp = nullptr; ReductionData(const Expr *Shared, const Expr *Ref, const Expr *Private, const Expr *ReductionOp) : Shared(Shared), Ref(Ref), Private(Private), ReductionOp(ReductionOp) { } }; /// List of reduction-based clauses. SmallVector<ReductionData, 4> ClausesData; /// List of addresses of shared variables/expressions. SmallVector<std::pair<LValue, LValue>, 4> SharedAddresses; /// List of addresses of original variables/expressions. SmallVector<std::pair<LValue, LValue>, 4> OrigAddresses; /// Sizes of the reduction items in chars. SmallVector<std::pair<llvm::Value *, llvm::Value *>, 4> Sizes; /// Base declarations for the reduction items. SmallVector<const VarDecl *, 4> BaseDecls; /// Emits lvalue for shared expression. LValue emitSharedLValue(CodeGenFunction &CGF, const Expr *E); /// Emits upper bound for shared expression (if array section). LValue emitSharedLValueUB(CodeGenFunction &CGF, const Expr *E); /// Performs aggregate initialization. /// \param N Number of reduction item in the common list. /// \param PrivateAddr Address of the corresponding private item. /// \param SharedAddr Address of the original shared variable. /// \param DRD Declare reduction construct used for reduction item. void emitAggregateInitialization(CodeGenFunction &CGF, unsigned N, Address PrivateAddr, Address SharedAddr, const OMPDeclareReductionDecl *DRD); public: ReductionCodeGen(ArrayRef<const Expr *> Shareds, ArrayRef<const Expr *> Origs, ArrayRef<const Expr *> Privates, ArrayRef<const Expr *> ReductionOps); /// Emits lvalue for the shared and original reduction item. /// \param N Number of the reduction item. void emitSharedOrigLValue(CodeGenFunction &CGF, unsigned N); /// Emits the code for the variable-modified type, if required. /// \param N Number of the reduction item. void emitAggregateType(CodeGenFunction &CGF, unsigned N); /// Emits the code for the variable-modified type, if required. /// \param N Number of the reduction item. /// \param Size Size of the type in chars. void emitAggregateType(CodeGenFunction &CGF, unsigned N, llvm::Value *Size); /// Performs initialization of the private copy for the reduction item. /// \param N Number of the reduction item. /// \param PrivateAddr Address of the corresponding private item. /// \param DefaultInit Default initialization sequence that should be /// performed if no reduction specific initialization is found. /// \param SharedAddr Address of the original shared variable. void emitInitialization(CodeGenFunction &CGF, unsigned N, Address PrivateAddr, Address SharedAddr, llvm::function_ref<bool(CodeGenFunction &)> DefaultInit); /// Returns true if the private copy requires cleanups. bool needCleanups(unsigned N); /// Emits cleanup code for the reduction item. /// \param N Number of the reduction item. /// \param PrivateAddr Address of the corresponding private item. void emitCleanups(CodeGenFunction &CGF, unsigned N, Address PrivateAddr); /// Adjusts \p PrivatedAddr for using instead of the original variable /// address in normal operations. /// \param N Number of the reduction item. /// \param PrivateAddr Address of the corresponding private item. Address adjustPrivateAddress(CodeGenFunction &CGF, unsigned N, Address PrivateAddr); /// Returns LValue for the reduction item. LValue getSharedLValue(unsigned N) const { return SharedAddresses[N].first; } /// Returns LValue for the original reduction item. LValue getOrigLValue(unsigned N) const { return OrigAddresses[N].first; } /// Returns the size of the reduction item (in chars and total number of /// elements in the item), or nullptr, if the size is a constant. std::pair<llvm::Value *, llvm::Value *> getSizes(unsigned N) const { return Sizes[N]; } /// Returns the base declaration of the reduction item. const VarDecl *getBaseDecl(unsigned N) const { return BaseDecls[N]; } /// Returns the base declaration of the reduction item. const Expr *getRefExpr(unsigned N) const { return ClausesData[N].Ref; } /// Returns true if the initialization of the reduction item uses initializer /// from declare reduction construct. bool usesReductionInitializer(unsigned N) const; /// Return the type of the private item. QualType getPrivateType(unsigned N) const { return cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl()) ->getType(); } }; class CGOpenMPRuntime { public: /// Allows to disable automatic handling of functions used in target regions /// as those marked as `omp declare target`. class DisableAutoDeclareTargetRAII { CodeGenModule &CGM; bool SavedShouldMarkAsGlobal; public: DisableAutoDeclareTargetRAII(CodeGenModule &CGM); ~DisableAutoDeclareTargetRAII(); }; /// Manages list of nontemporal decls for the specified directive. class NontemporalDeclsRAII { CodeGenModule &CGM; const bool NeedToPush; public: NontemporalDeclsRAII(CodeGenModule &CGM, const OMPLoopDirective &S); ~NontemporalDeclsRAII(); }; /// Manages list of nontemporal decls for the specified directive. class UntiedTaskLocalDeclsRAII { CodeGenModule &CGM; const bool NeedToPush; public: UntiedTaskLocalDeclsRAII( CodeGenFunction &CGF, const llvm::MapVector<CanonicalDeclPtr<const VarDecl>, std::pair<Address, Address>> &LocalVars); ~UntiedTaskLocalDeclsRAII(); }; /// Maps the expression for the lastprivate variable to the global copy used /// to store new value because original variables are not mapped in inner /// parallel regions. Only private copies are captured but we need also to /// store private copy in shared address. /// Also, stores the expression for the private loop counter and it /// threaprivate name. struct LastprivateConditionalData { llvm::MapVector<CanonicalDeclPtr<const Decl>, SmallString<16>> DeclToUniqueName; LValue IVLVal; llvm::Function *Fn = nullptr; bool Disabled = false; }; /// Manages list of lastprivate conditional decls for the specified directive. class LastprivateConditionalRAII { enum class ActionToDo { DoNotPush, PushAsLastprivateConditional, DisableLastprivateConditional, }; CodeGenModule &CGM; ActionToDo Action = ActionToDo::DoNotPush; /// Check and try to disable analysis of inner regions for changes in /// lastprivate conditional. void tryToDisableInnerAnalysis(const OMPExecutableDirective &S, llvm::DenseSet<CanonicalDeclPtr<const Decl>> &NeedToAddForLPCsAsDisabled) const; LastprivateConditionalRAII(CodeGenFunction &CGF, const OMPExecutableDirective &S); public: explicit LastprivateConditionalRAII(CodeGenFunction &CGF, const OMPExecutableDirective &S, LValue IVLVal); static LastprivateConditionalRAII disable(CodeGenFunction &CGF, const OMPExecutableDirective &S); ~LastprivateConditionalRAII(); }; llvm::OpenMPIRBuilder &getOMPBuilder() { return OMPBuilder; } protected: CodeGenModule &CGM; StringRef FirstSeparator, Separator; /// An OpenMP-IR-Builder instance. llvm::OpenMPIRBuilder OMPBuilder; /// Constructor allowing to redefine the name separator for the variables. explicit CGOpenMPRuntime(CodeGenModule &CGM, StringRef FirstSeparator, StringRef Separator); /// Creates offloading entry for the provided entry ID \a ID, /// address \a Addr, size \a Size, and flags \a Flags. virtual void createOffloadEntry(llvm::Constant *ID, llvm::Constant *Addr, uint64_t Size, int32_t Flags, llvm::GlobalValue::LinkageTypes Linkage); /// Helper to emit outlined function for 'target' directive. /// \param D Directive to emit. /// \param ParentName Name of the function that encloses the target region. /// \param OutlinedFn Outlined function value to be defined by this call. /// \param OutlinedFnID Outlined function ID value to be defined by this call. /// \param IsOffloadEntry True if the outlined function is an offload entry. /// \param CodeGen Lambda codegen specific to an accelerator device. /// An outlined function may not be an entry if, e.g. the if clause always /// evaluates to false. virtual void emitTargetOutlinedFunctionHelper(const OMPExecutableDirective &D, StringRef ParentName, llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID, bool IsOffloadEntry, const RegionCodeGenTy &CodeGen); /// Emits object of ident_t type with info for source location. /// \param Flags Flags for OpenMP location. /// llvm::Value *emitUpdateLocation(CodeGenFunction &CGF, SourceLocation Loc, unsigned Flags = 0); /// Emit the number of teams for a target directive. Inspect the num_teams /// clause associated with a teams construct combined or closely nested /// with the target directive. /// /// Emit a team of size one for directives such as 'target parallel' that /// have no associated teams construct. /// /// Otherwise, return nullptr. const Expr *getNumTeamsExprForTargetDirective(CodeGenFunction &CGF, const OMPExecutableDirective &D, int32_t &DefaultVal); llvm::Value *emitNumTeamsForTargetDirective(CodeGenFunction &CGF, const OMPExecutableDirective &D); /// Emit the number of threads for a target directive. Inspect the /// thread_limit clause associated with a teams construct combined or closely /// nested with the target directive. /// /// Emit the num_threads clause for directives such as 'target parallel' that /// have no associated teams construct. /// /// Otherwise, return nullptr. const Expr * getNumThreadsExprForTargetDirective(CodeGenFunction &CGF, const OMPExecutableDirective &D, int32_t &DefaultVal); llvm::Value * emitNumThreadsForTargetDirective(CodeGenFunction &CGF, const OMPExecutableDirective &D); /// Returns pointer to ident_t type. llvm::Type *getIdentTyPointerTy(); /// Gets thread id value for the current thread. /// llvm::Value *getThreadID(CodeGenFunction &CGF, SourceLocation Loc); /// Get the function name of an outlined region. // The name can be customized depending on the target. // virtual StringRef getOutlinedHelperName() const { return ".omp_outlined."; } /// Emits \p Callee function call with arguments \p Args with location \p Loc. void emitCall(CodeGenFunction &CGF, SourceLocation Loc, llvm::FunctionCallee Callee, ArrayRef<llvm::Value *> Args = llvm::None) const; /// Emits address of the word in a memory where current thread id is /// stored. virtual Address emitThreadIDAddress(CodeGenFunction &CGF, SourceLocation Loc); void setLocThreadIdInsertPt(CodeGenFunction &CGF, bool AtCurrentPoint = false); void clearLocThreadIdInsertPt(CodeGenFunction &CGF); /// Check if the default location must be constant. /// Default is false to support OMPT/OMPD. virtual bool isDefaultLocationConstant() const { return false; } /// Returns additional flags that can be stored in reserved_2 field of the /// default location. virtual unsigned getDefaultLocationReserved2Flags() const { return 0; } /// Returns default flags for the barriers depending on the directive, for /// which this barier is going to be emitted. static unsigned getDefaultFlagsForBarriers(OpenMPDirectiveKind Kind); /// Get the LLVM type for the critical name. llvm::ArrayType *getKmpCriticalNameTy() const {return KmpCriticalNameTy;} /// Returns corresponding lock object for the specified critical region /// name. If the lock object does not exist it is created, otherwise the /// reference to the existing copy is returned. /// \param CriticalName Name of the critical region. /// llvm::Value *getCriticalRegionLock(StringRef CriticalName); private: /// Map for SourceLocation and OpenMP runtime library debug locations. typedef llvm::DenseMap<SourceLocation, llvm::Value *> OpenMPDebugLocMapTy; OpenMPDebugLocMapTy OpenMPDebugLocMap; /// The type for a microtask which gets passed to __kmpc_fork_call(). /// Original representation is: /// typedef void (kmpc_micro)(kmp_int32 global_tid, kmp_int32 bound_tid,...); llvm::FunctionType *Kmpc_MicroTy = nullptr; /// Stores debug location and ThreadID for the function. struct DebugLocThreadIdTy { llvm::Value *DebugLoc; llvm::Value *ThreadID; /// Insert point for the service instructions. llvm::AssertingVH<llvm::Instruction> ServiceInsertPt = nullptr; }; /// Map of local debug location, ThreadId and functions. typedef llvm::DenseMap<llvm::Function *, DebugLocThreadIdTy> OpenMPLocThreadIDMapTy; OpenMPLocThreadIDMapTy OpenMPLocThreadIDMap; /// Map of UDRs and corresponding combiner/initializer. typedef llvm::DenseMap<const OMPDeclareReductionDecl *, std::pair<llvm::Function *, llvm::Function *>> UDRMapTy; UDRMapTy UDRMap; /// Map of functions and locally defined UDRs. typedef llvm::DenseMap<llvm::Function *, SmallVector<const OMPDeclareReductionDecl *, 4>> FunctionUDRMapTy; FunctionUDRMapTy FunctionUDRMap; /// Map from the user-defined mapper declaration to its corresponding /// functions. llvm::DenseMap<const OMPDeclareMapperDecl *, llvm::Function *> UDMMap; /// Map of functions and their local user-defined mappers. using FunctionUDMMapTy = llvm::DenseMap<llvm::Function *, SmallVector<const OMPDeclareMapperDecl *, 4>>; FunctionUDMMapTy FunctionUDMMap; /// Maps local variables marked as lastprivate conditional to their internal /// types. llvm::DenseMap<llvm::Function *, llvm::DenseMap<CanonicalDeclPtr<const Decl>, std::tuple<QualType, const FieldDecl *, const FieldDecl *, LValue>>> LastprivateConditionalToTypes; /// Maps function to the position of the untied task locals stack. llvm::DenseMap<llvm::Function *, unsigned> FunctionToUntiedTaskStackMap; /// Type kmp_critical_name, originally defined as typedef kmp_int32 /// kmp_critical_name[8]; llvm::ArrayType *KmpCriticalNameTy; /// An ordered map of auto-generated variables to their unique names. /// It stores variables with the following names: 1) ".gomp_critical_user_" + /// <critical_section_name> + ".var" for "omp critical" directives; 2) /// <mangled_name_for_global_var> + ".cache." for cache for threadprivate /// variables. llvm::StringMap<llvm::AssertingVH<llvm::GlobalVariable>, llvm::BumpPtrAllocator> InternalVars; /// Type typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *); llvm::Type *KmpRoutineEntryPtrTy = nullptr; QualType KmpRoutineEntryPtrQTy; /// Type typedef struct kmp_task { /// void * shareds; /**< pointer to block of pointers to /// shared vars */ /// kmp_routine_entry_t routine; /**< pointer to routine to call for /// executing task */ /// kmp_int32 part_id; /**< part id for the task */ /// kmp_routine_entry_t destructors; /* pointer to function to invoke /// deconstructors of firstprivate C++ objects */ /// } kmp_task_t; QualType KmpTaskTQTy; /// Saved kmp_task_t for task directive. QualType SavedKmpTaskTQTy; /// Saved kmp_task_t for taskloop-based directive. QualType SavedKmpTaskloopTQTy; /// Type typedef struct kmp_depend_info { /// kmp_intptr_t base_addr; /// size_t len; /// struct { /// bool in:1; /// bool out:1; /// } flags; /// } kmp_depend_info_t; QualType KmpDependInfoTy; /// Type typedef struct kmp_task_affinity_info { /// kmp_intptr_t base_addr; /// size_t len; /// struct { /// bool flag1 : 1; /// bool flag2 : 1; /// kmp_int32 reserved : 30; /// } flags; /// } kmp_task_affinity_info_t; QualType KmpTaskAffinityInfoTy; /// struct kmp_dim { // loop bounds info casted to kmp_int64 /// kmp_int64 lo; // lower /// kmp_int64 up; // upper /// kmp_int64 st; // stride /// }; QualType KmpDimTy; /// Type struct __tgt_offload_entry{ /// void *addr; // Pointer to the offload entry info. /// // (function or global) /// char *name; // Name of the function or global. /// size_t size; // Size of the entry info (0 if it a function). /// int32_t flags; /// int32_t reserved; /// }; QualType TgtOffloadEntryQTy; /// Entity that registers the offloading constants that were emitted so /// far. class OffloadEntriesInfoManagerTy { CodeGenModule &CGM; /// Number of entries registered so far. unsigned OffloadingEntriesNum = 0; public: /// Base class of the entries info. class OffloadEntryInfo { public: /// Kind of a given entry. enum OffloadingEntryInfoKinds : unsigned { /// Entry is a target region. OffloadingEntryInfoTargetRegion = 0, /// Entry is a declare target variable. OffloadingEntryInfoDeviceGlobalVar = 1, /// Invalid entry info. OffloadingEntryInfoInvalid = ~0u }; protected: OffloadEntryInfo() = delete; explicit OffloadEntryInfo(OffloadingEntryInfoKinds Kind) : Kind(Kind) {} explicit OffloadEntryInfo(OffloadingEntryInfoKinds Kind, unsigned Order, uint32_t Flags) : Flags(Flags), Order(Order), Kind(Kind) {} ~OffloadEntryInfo() = default; public: bool isValid() const { return Order != ~0u; } unsigned getOrder() const { return Order; } OffloadingEntryInfoKinds getKind() const { return Kind; } uint32_t getFlags() const { return Flags; } void setFlags(uint32_t NewFlags) { Flags = NewFlags; } llvm::Constant *getAddress() const { return cast_or_null<llvm::Constant>(Addr); } void setAddress(llvm::Constant *V) { assert(!Addr.pointsToAliveValue() && "Address has been set before!"); Addr = V; } static bool classof(const OffloadEntryInfo *Info) { return true; } private: /// Address of the entity that has to be mapped for offloading. llvm::WeakTrackingVH Addr; /// Flags associated with the device global. uint32_t Flags = 0u; /// Order this entry was emitted. unsigned Order = ~0u; OffloadingEntryInfoKinds Kind = OffloadingEntryInfoInvalid; }; /// Return true if a there are no entries defined. bool empty() const; /// Return number of entries defined so far. unsigned size() const { return OffloadingEntriesNum; } OffloadEntriesInfoManagerTy(CodeGenModule &CGM) : CGM(CGM) {} // // Target region entries related. // /// Kind of the target registry entry. enum OMPTargetRegionEntryKind : uint32_t { /// Mark the entry as target region. OMPTargetRegionEntryTargetRegion = 0x0, /// Mark the entry as a global constructor. OMPTargetRegionEntryCtor = 0x02, /// Mark the entry as a global destructor. OMPTargetRegionEntryDtor = 0x04, }; /// Target region entries info. class OffloadEntryInfoTargetRegion final : public OffloadEntryInfo { /// Address that can be used as the ID of the entry. llvm::Constant *ID = nullptr; public: OffloadEntryInfoTargetRegion() : OffloadEntryInfo(OffloadingEntryInfoTargetRegion) {} explicit OffloadEntryInfoTargetRegion(unsigned Order, llvm::Constant *Addr, llvm::Constant *ID, OMPTargetRegionEntryKind Flags) : OffloadEntryInfo(OffloadingEntryInfoTargetRegion, Order, Flags), ID(ID) { setAddress(Addr); } llvm::Constant *getID() const { return ID; } void setID(llvm::Constant *V) { assert(!ID && "ID has been set before!"); ID = V; } static bool classof(const OffloadEntryInfo *Info) { return Info->getKind() == OffloadingEntryInfoTargetRegion; } }; /// Initialize target region entry. void initializeTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID, StringRef ParentName, unsigned LineNum, unsigned Order); /// Register target region entry. void registerTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID, StringRef ParentName, unsigned LineNum, llvm::Constant *Addr, llvm::Constant *ID, OMPTargetRegionEntryKind Flags); /// Return true if a target region entry with the provided information /// exists. bool hasTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID, StringRef ParentName, unsigned LineNum, bool IgnoreAddressId = false) const; /// brief Applies action \a Action on all registered entries. typedef llvm::function_ref<void(unsigned, unsigned, StringRef, unsigned, const OffloadEntryInfoTargetRegion &)> OffloadTargetRegionEntryInfoActTy; void actOnTargetRegionEntriesInfo( const OffloadTargetRegionEntryInfoActTy &Action); // // Device global variable entries related. // /// Kind of the global variable entry.. enum OMPTargetGlobalVarEntryKind : uint32_t { /// Mark the entry as a to declare target. OMPTargetGlobalVarEntryTo = 0x0, /// Mark the entry as a to declare target link. OMPTargetGlobalVarEntryLink = 0x1, }; /// Device global variable entries info. class OffloadEntryInfoDeviceGlobalVar final : public OffloadEntryInfo { /// Type of the global variable. CharUnits VarSize; llvm::GlobalValue::LinkageTypes Linkage; public: OffloadEntryInfoDeviceGlobalVar() : OffloadEntryInfo(OffloadingEntryInfoDeviceGlobalVar) {} explicit OffloadEntryInfoDeviceGlobalVar(unsigned Order, OMPTargetGlobalVarEntryKind Flags) : OffloadEntryInfo(OffloadingEntryInfoDeviceGlobalVar, Order, Flags) {} explicit OffloadEntryInfoDeviceGlobalVar( unsigned Order, llvm::Constant *Addr, CharUnits VarSize, OMPTargetGlobalVarEntryKind Flags, llvm::GlobalValue::LinkageTypes Linkage) : OffloadEntryInfo(OffloadingEntryInfoDeviceGlobalVar, Order, Flags), VarSize(VarSize), Linkage(Linkage) { setAddress(Addr); } CharUnits getVarSize() const { return VarSize; } void setVarSize(CharUnits Size) { VarSize = Size; } llvm::GlobalValue::LinkageTypes getLinkage() const { return Linkage; } void setLinkage(llvm::GlobalValue::LinkageTypes LT) { Linkage = LT; } static bool classof(const OffloadEntryInfo *Info) { return Info->getKind() == OffloadingEntryInfoDeviceGlobalVar; } }; /// Initialize device global variable entry. void initializeDeviceGlobalVarEntryInfo(StringRef Name, OMPTargetGlobalVarEntryKind Flags, unsigned Order); /// Register device global variable entry. void registerDeviceGlobalVarEntryInfo(StringRef VarName, llvm::Constant *Addr, CharUnits VarSize, OMPTargetGlobalVarEntryKind Flags, llvm::GlobalValue::LinkageTypes Linkage); /// Checks if the variable with the given name has been registered already. bool hasDeviceGlobalVarEntryInfo(StringRef VarName) const { return OffloadEntriesDeviceGlobalVar.count(VarName) > 0; } /// Applies action \a Action on all registered entries. typedef llvm::function_ref<void(StringRef, const OffloadEntryInfoDeviceGlobalVar &)> OffloadDeviceGlobalVarEntryInfoActTy; void actOnDeviceGlobalVarEntriesInfo( const OffloadDeviceGlobalVarEntryInfoActTy &Action); private: // Storage for target region entries kind. The storage is to be indexed by // file ID, device ID, parent function name and line number. typedef llvm::DenseMap<unsigned, OffloadEntryInfoTargetRegion> OffloadEntriesTargetRegionPerLine; typedef llvm::StringMap<OffloadEntriesTargetRegionPerLine> OffloadEntriesTargetRegionPerParentName; typedef llvm::DenseMap<unsigned, OffloadEntriesTargetRegionPerParentName> OffloadEntriesTargetRegionPerFile; typedef llvm::DenseMap<unsigned, OffloadEntriesTargetRegionPerFile> OffloadEntriesTargetRegionPerDevice; typedef OffloadEntriesTargetRegionPerDevice OffloadEntriesTargetRegionTy; OffloadEntriesTargetRegionTy OffloadEntriesTargetRegion; /// Storage for device global variable entries kind. The storage is to be /// indexed by mangled name. typedef llvm::StringMap<OffloadEntryInfoDeviceGlobalVar> OffloadEntriesDeviceGlobalVarTy; OffloadEntriesDeviceGlobalVarTy OffloadEntriesDeviceGlobalVar; }; OffloadEntriesInfoManagerTy OffloadEntriesInfoManager; bool ShouldMarkAsGlobal = true; /// List of the emitted declarations. llvm::DenseSet<CanonicalDeclPtr<const Decl>> AlreadyEmittedTargetDecls; /// List of the global variables with their addresses that should not be /// emitted for the target. llvm::StringMap<llvm::WeakTrackingVH> EmittedNonTargetVariables; /// List of variables that can become declare target implicitly and, thus, /// must be emitted. llvm::SmallDenseSet<const VarDecl *> DeferredGlobalVariables; using NontemporalDeclsSet = llvm::SmallDenseSet<CanonicalDeclPtr<const Decl>>; /// Stack for list of declarations in current context marked as nontemporal. /// The set is the union of all current stack elements. llvm::SmallVector<NontemporalDeclsSet, 4> NontemporalDeclsStack; using UntiedLocalVarsAddressesMap = llvm::MapVector<CanonicalDeclPtr<const VarDecl>, std::pair<Address, Address>>; llvm::SmallVector<UntiedLocalVarsAddressesMap, 4> UntiedLocalVarsStack; /// Stack for list of addresses of declarations in current context marked as /// lastprivate conditional. The set is the union of all current stack /// elements. llvm::SmallVector<LastprivateConditionalData, 4> LastprivateConditionalStack; /// Flag for keeping track of weather a requires unified_shared_memory /// directive is present. bool HasRequiresUnifiedSharedMemory = false; /// Atomic ordering from the omp requires directive. llvm::AtomicOrdering RequiresAtomicOrdering = llvm::AtomicOrdering::Monotonic; /// Flag for keeping track of weather a target region has been emitted. bool HasEmittedTargetRegion = false; /// Flag for keeping track of weather a device routine has been emitted. /// Device routines are specific to the bool HasEmittedDeclareTargetRegion = false; /// Loads all the offload entries information from the host IR /// metadata. void loadOffloadInfoMetadata(); /// Returns __tgt_offload_entry type. QualType getTgtOffloadEntryQTy(); /// Start scanning from statement \a S and and emit all target regions /// found along the way. /// \param S Starting statement. /// \param ParentName Name of the function declaration that is being scanned. void scanForTargetRegionsFunctions(const Stmt *S, StringRef ParentName); /// Build type kmp_routine_entry_t (if not built yet). void emitKmpRoutineEntryT(QualType KmpInt32Ty); /// Returns pointer to kmpc_micro type. llvm::Type *getKmpc_MicroPointerTy(); /// Returns __kmpc_for_static_init_* runtime function for the specified /// size \a IVSize and sign \a IVSigned. Will create a distribute call /// __kmpc_distribute_static_init* if \a IsGPUDistribute is set. llvm::FunctionCallee createForStaticInitFunction(unsigned IVSize, bool IVSigned, bool IsGPUDistribute); /// Returns __kmpc_dispatch_init_* runtime function for the specified /// size \a IVSize and sign \a IVSigned. llvm::FunctionCallee createDispatchInitFunction(unsigned IVSize, bool IVSigned); /// Returns __kmpc_dispatch_next_* runtime function for the specified /// size \a IVSize and sign \a IVSigned. llvm::FunctionCallee createDispatchNextFunction(unsigned IVSize, bool IVSigned); /// Returns __kmpc_dispatch_fini_* runtime function for the specified /// size \a IVSize and sign \a IVSigned. llvm::FunctionCallee createDispatchFiniFunction(unsigned IVSize, bool IVSigned); /// If the specified mangled name is not in the module, create and /// return threadprivate cache object. This object is a pointer's worth of /// storage that's reserved for use by the OpenMP runtime. /// \param VD Threadprivate variable. /// \return Cache variable for the specified threadprivate. llvm::Constant *getOrCreateThreadPrivateCache(const VarDecl *VD); /// Gets (if variable with the given name already exist) or creates /// internal global variable with the specified Name. The created variable has /// linkage CommonLinkage by default and is initialized by null value. /// \param Ty Type of the global variable. If it is exist already the type /// must be the same. /// \param Name Name of the variable. llvm::GlobalVariable *getOrCreateInternalVariable(llvm::Type *Ty, const llvm::Twine &Name, unsigned AddressSpace = 0); /// Set of threadprivate variables with the generated initializer. llvm::StringSet<> ThreadPrivateWithDefinition; /// Set of declare target variables with the generated initializer. llvm::StringSet<> DeclareTargetWithDefinition; /// Emits initialization code for the threadprivate variables. /// \param VDAddr Address of the global variable \a VD. /// \param Ctor Pointer to a global init function for \a VD. /// \param CopyCtor Pointer to a global copy function for \a VD. /// \param Dtor Pointer to a global destructor function for \a VD. /// \param Loc Location of threadprivate declaration. void emitThreadPrivateVarInit(CodeGenFunction &CGF, Address VDAddr, llvm::Value *Ctor, llvm::Value *CopyCtor, llvm::Value *Dtor, SourceLocation Loc); /// Emit the array initialization or deletion portion for user-defined mapper /// code generation. void emitUDMapperArrayInitOrDel(CodeGenFunction &MapperCGF, llvm::Value *Handle, llvm::Value *BasePtr, llvm::Value *Ptr, llvm::Value *Size, llvm::Value *MapType, llvm::Value *MapName, CharUnits ElementSize, llvm::BasicBlock *ExitBB, bool IsInit); struct TaskResultTy { llvm::Value *NewTask = nullptr; llvm::Function *TaskEntry = nullptr; llvm::Value *NewTaskNewTaskTTy = nullptr; LValue TDBase; const RecordDecl *KmpTaskTQTyRD = nullptr; llvm::Value *TaskDupFn = nullptr; }; /// Emit task region for the task directive. The task region is emitted in /// several steps: /// 1. Emit a call to kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 /// gtid, kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds, /// kmp_routine_entry_t *task_entry). Here task_entry is a pointer to the /// function: /// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) { /// TaskFunction(gtid, tt->part_id, tt->shareds); /// return 0; /// } /// 2. Copy a list of shared variables to field shareds of the resulting /// structure kmp_task_t returned by the previous call (if any). /// 3. Copy a pointer to destructions function to field destructions of the /// resulting structure kmp_task_t. /// \param D Current task directive. /// \param TaskFunction An LLVM function with type void (*)(i32 /*gtid*/, i32 /// /*part_id*/, captured_struct */*__context*/); /// \param SharedsTy A type which contains references the shared variables. /// \param Shareds Context with the list of shared variables from the \p /// TaskFunction. /// \param Data Additional data for task generation like tiednsee, final /// state, list of privates etc. TaskResultTy emitTaskInit(CodeGenFunction &CGF, SourceLocation Loc, const OMPExecutableDirective &D, llvm::Function *TaskFunction, QualType SharedsTy, Address Shareds, const OMPTaskDataTy &Data); /// Emit code that pushes the trip count of loops associated with constructs /// 'target teams distribute' and 'teams distribute parallel for'. /// \param SizeEmitter Emits the int64 value for the number of iterations of /// the associated loop. void emitTargetNumIterationsCall( CodeGenFunction &CGF, const OMPExecutableDirective &D, llvm::Value *DeviceID, llvm::function_ref<llvm::Value *(CodeGenFunction &CGF, const OMPLoopDirective &D)> SizeEmitter); /// Emit update for lastprivate conditional data. void emitLastprivateConditionalUpdate(CodeGenFunction &CGF, LValue IVLVal, StringRef UniqueDeclName, LValue LVal, SourceLocation Loc); /// Returns the number of the elements and the address of the depobj /// dependency array. /// \return Number of elements in depobj array and the pointer to the array of /// dependencies. std::pair<llvm::Value *, LValue> getDepobjElements(CodeGenFunction &CGF, LValue DepobjLVal, SourceLocation Loc); SmallVector<llvm::Value *, 4> emitDepobjElementsSizes(CodeGenFunction &CGF, QualType &KmpDependInfoTy, const OMPTaskDataTy::DependData &Data); void emitDepobjElements(CodeGenFunction &CGF, QualType &KmpDependInfoTy, LValue PosLVal, const OMPTaskDataTy::DependData &Data, Address DependenciesArray); public: explicit CGOpenMPRuntime(CodeGenModule &CGM) : CGOpenMPRuntime(CGM, ".", ".") {} virtual ~CGOpenMPRuntime() {} virtual void clear(); /// Emits code for OpenMP 'if' clause using specified \a CodeGen /// function. Here is the logic: /// if (Cond) { /// ThenGen(); /// } else { /// ElseGen(); /// } void emitIfClause(CodeGenFunction &CGF, const Expr *Cond, const RegionCodeGenTy &ThenGen, const RegionCodeGenTy &ElseGen); /// Checks if the \p Body is the \a CompoundStmt and returns its child /// statement iff there is only one that is not evaluatable at the compile /// time. static const Stmt *getSingleCompoundChild(ASTContext &Ctx, const Stmt *Body); /// Get the platform-specific name separator. std::string getName(ArrayRef<StringRef> Parts) const; /// Emit code for the specified user defined reduction construct. virtual void emitUserDefinedReduction(CodeGenFunction *CGF, const OMPDeclareReductionDecl *D); /// Get combiner/initializer for the specified user-defined reduction, if any. virtual std::pair<llvm::Function *, llvm::Function *> getUserDefinedReduction(const OMPDeclareReductionDecl *D); /// Emit the function for the user defined mapper construct. void emitUserDefinedMapper(const OMPDeclareMapperDecl *D, CodeGenFunction *CGF = nullptr); /// Get the function for the specified user-defined mapper. If it does not /// exist, create one. llvm::Function * getOrCreateUserDefinedMapperFunc(const OMPDeclareMapperDecl *D); /// Emits outlined function for the specified OpenMP parallel directive /// \a D. This outlined function has type void(*)(kmp_int32 *ThreadID, /// kmp_int32 BoundID, struct context_vars*). /// \param D OpenMP directive. /// \param ThreadIDVar Variable for thread id in the current OpenMP region. /// \param InnermostKind Kind of innermost directive (for simple directives it /// is a directive itself, for combined - its innermost directive). /// \param CodeGen Code generation sequence for the \a D directive. virtual llvm::Function *emitParallelOutlinedFunction( const OMPExecutableDirective &D, const VarDecl *ThreadIDVar, OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen); /// Emits outlined function for the specified OpenMP teams directive /// \a D. This outlined function has type void(*)(kmp_int32 *ThreadID, /// kmp_int32 BoundID, struct context_vars*). /// \param D OpenMP directive. /// \param ThreadIDVar Variable for thread id in the current OpenMP region. /// \param InnermostKind Kind of innermost directive (for simple directives it /// is a directive itself, for combined - its innermost directive). /// \param CodeGen Code generation sequence for the \a D directive. virtual llvm::Function *emitTeamsOutlinedFunction( const OMPExecutableDirective &D, const VarDecl *ThreadIDVar, OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen); /// Emits outlined function for the OpenMP task directive \a D. This /// outlined function has type void(*)(kmp_int32 ThreadID, struct task_t* /// TaskT). /// \param D OpenMP directive. /// \param ThreadIDVar Variable for thread id in the current OpenMP region. /// \param PartIDVar Variable for partition id in the current OpenMP untied /// task region. /// \param TaskTVar Variable for task_t argument. /// \param InnermostKind Kind of innermost directive (for simple directives it /// is a directive itself, for combined - its innermost directive). /// \param CodeGen Code generation sequence for the \a D directive. /// \param Tied true if task is generated for tied task, false otherwise. /// \param NumberOfParts Number of parts in untied task. Ignored for tied /// tasks. /// virtual llvm::Function *emitTaskOutlinedFunction( const OMPExecutableDirective &D, const VarDecl *ThreadIDVar, const VarDecl *PartIDVar, const VarDecl *TaskTVar, OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen, bool Tied, unsigned &NumberOfParts); /// Cleans up references to the objects in finished function. /// virtual void functionFinished(CodeGenFunction &CGF); /// Emits code for parallel or serial call of the \a OutlinedFn with /// variables captured in a record which address is stored in \a /// CapturedStruct. /// \param OutlinedFn Outlined function to be run in parallel threads. Type of /// this function is void(*)(kmp_int32 *, kmp_int32, struct context_vars*). /// \param CapturedVars A pointer to the record with the references to /// variables used in \a OutlinedFn function. /// \param IfCond Condition in the associated 'if' clause, if it was /// specified, nullptr otherwise. /// \param NumThreads The value corresponding to the num_threads clause, if /// any, or nullptr. /// virtual void emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc, llvm::Function *OutlinedFn, ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond, llvm::Value *NumThreads); /// Emits a critical region. /// \param CriticalName Name of the critical region. /// \param CriticalOpGen Generator for the statement associated with the given /// critical region. /// \param Hint Value of the 'hint' clause (optional). virtual void emitCriticalRegion(CodeGenFunction &CGF, StringRef CriticalName, const RegionCodeGenTy &CriticalOpGen, SourceLocation Loc, const Expr *Hint = nullptr); /// Emits a master region. /// \param MasterOpGen Generator for the statement associated with the given /// master region. virtual void emitMasterRegion(CodeGenFunction &CGF, const RegionCodeGenTy &MasterOpGen, SourceLocation Loc); /// Emits a masked region. /// \param MaskedOpGen Generator for the statement associated with the given /// masked region. virtual void emitMaskedRegion(CodeGenFunction &CGF, const RegionCodeGenTy &MaskedOpGen, SourceLocation Loc, const Expr *Filter = nullptr); /// Emits code for a taskyield directive. virtual void emitTaskyieldCall(CodeGenFunction &CGF, SourceLocation Loc); /// Emit a taskgroup region. /// \param TaskgroupOpGen Generator for the statement associated with the /// given taskgroup region. virtual void emitTaskgroupRegion(CodeGenFunction &CGF, const RegionCodeGenTy &TaskgroupOpGen, SourceLocation Loc); /// Emits a single region. /// \param SingleOpGen Generator for the statement associated with the given /// single region. virtual void emitSingleRegion(CodeGenFunction &CGF, const RegionCodeGenTy &SingleOpGen, SourceLocation Loc, ArrayRef<const Expr *> CopyprivateVars, ArrayRef<const Expr *> DestExprs, ArrayRef<const Expr *> SrcExprs, ArrayRef<const Expr *> AssignmentOps); /// Emit an ordered region. /// \param OrderedOpGen Generator for the statement associated with the given /// ordered region. virtual void emitOrderedRegion(CodeGenFunction &CGF, const RegionCodeGenTy &OrderedOpGen, SourceLocation Loc, bool IsThreads); /// Emit an implicit/explicit barrier for OpenMP threads. /// \param Kind Directive for which this implicit barrier call must be /// generated. Must be OMPD_barrier for explicit barrier generation. /// \param EmitChecks true if need to emit checks for cancellation barriers. /// \param ForceSimpleCall true simple barrier call must be emitted, false if /// runtime class decides which one to emit (simple or with cancellation /// checks). /// virtual void emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc, OpenMPDirectiveKind Kind, bool EmitChecks = true, bool ForceSimpleCall = false); /// Check if the specified \a ScheduleKind is static non-chunked. /// This kind of worksharing directive is emitted without outer loop. /// \param ScheduleKind Schedule kind specified in the 'schedule' clause. /// \param Chunked True if chunk is specified in the clause. /// virtual bool isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind, bool Chunked) const; /// Check if the specified \a ScheduleKind is static non-chunked. /// This kind of distribute directive is emitted without outer loop. /// \param ScheduleKind Schedule kind specified in the 'dist_schedule' clause. /// \param Chunked True if chunk is specified in the clause. /// virtual bool isStaticNonchunked(OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) const; /// Check if the specified \a ScheduleKind is static chunked. /// \param ScheduleKind Schedule kind specified in the 'schedule' clause. /// \param Chunked True if chunk is specified in the clause. /// virtual bool isStaticChunked(OpenMPScheduleClauseKind ScheduleKind, bool Chunked) const; /// Check if the specified \a ScheduleKind is static non-chunked. /// \param ScheduleKind Schedule kind specified in the 'dist_schedule' clause. /// \param Chunked True if chunk is specified in the clause. /// virtual bool isStaticChunked(OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) const; /// Check if the specified \a ScheduleKind is dynamic. /// This kind of worksharing directive is emitted without outer loop. /// \param ScheduleKind Schedule Kind specified in the 'schedule' clause. /// virtual bool isDynamic(OpenMPScheduleClauseKind ScheduleKind) const; /// struct with the values to be passed to the dispatch runtime function struct DispatchRTInput { /// Loop lower bound llvm::Value *LB = nullptr; /// Loop upper bound llvm::Value *UB = nullptr; /// Chunk size specified using 'schedule' clause (nullptr if chunk /// was not specified) llvm::Value *Chunk = nullptr; DispatchRTInput() = default; DispatchRTInput(llvm::Value *LB, llvm::Value *UB, llvm::Value *Chunk) : LB(LB), UB(UB), Chunk(Chunk) {} }; /// Call the appropriate runtime routine to initialize it before start /// of loop. /// This is used for non static scheduled types and when the ordered /// clause is present on the loop construct. /// Depending on the loop schedule, it is necessary to call some runtime /// routine before start of the OpenMP loop to get the loop upper / lower /// bounds \a LB and \a UB and stride \a ST. /// /// \param CGF Reference to current CodeGenFunction. /// \param Loc Clang source location. /// \param ScheduleKind Schedule kind, specified by the 'schedule' clause. /// \param IVSize Size of the iteration variable in bits. /// \param IVSigned Sign of the iteration variable. /// \param Ordered true if loop is ordered, false otherwise. /// \param DispatchValues struct containing llvm values for lower bound, upper /// bound, and chunk expression. /// For the default (nullptr) value, the chunk 1 will be used. /// virtual void emitForDispatchInit(CodeGenFunction &CGF, SourceLocation Loc, const OpenMPScheduleTy &ScheduleKind, unsigned IVSize, bool IVSigned, bool Ordered, const DispatchRTInput &DispatchValues); /// Struct with the values to be passed to the static runtime function struct StaticRTInput { /// Size of the iteration variable in bits. unsigned IVSize = 0; /// Sign of the iteration variable. bool IVSigned = false; /// true if loop is ordered, false otherwise. bool Ordered = false; /// Address of the output variable in which the flag of the last iteration /// is returned. Address IL = Address::invalid(); /// Address of the output variable in which the lower iteration number is /// returned. Address LB = Address::invalid(); /// Address of the output variable in which the upper iteration number is /// returned. Address UB = Address::invalid(); /// Address of the output variable in which the stride value is returned /// necessary to generated the static_chunked scheduled loop. Address ST = Address::invalid(); /// Value of the chunk for the static_chunked scheduled loop. For the /// default (nullptr) value, the chunk 1 will be used. llvm::Value *Chunk = nullptr; StaticRTInput(unsigned IVSize, bool IVSigned, bool Ordered, Address IL, Address LB, Address UB, Address ST, llvm::Value *Chunk = nullptr) : IVSize(IVSize), IVSigned(IVSigned), Ordered(Ordered), IL(IL), LB(LB), UB(UB), ST(ST), Chunk(Chunk) {} }; /// Call the appropriate runtime routine to initialize it before start /// of loop. /// /// This is used only in case of static schedule, when the user did not /// specify a ordered clause on the loop construct. /// Depending on the loop schedule, it is necessary to call some runtime /// routine before start of the OpenMP loop to get the loop upper / lower /// bounds LB and UB and stride ST. /// /// \param CGF Reference to current CodeGenFunction. /// \param Loc Clang source location. /// \param DKind Kind of the directive. /// \param ScheduleKind Schedule kind, specified by the 'schedule' clause. /// \param Values Input arguments for the construct. /// virtual void emitForStaticInit(CodeGenFunction &CGF, SourceLocation Loc, OpenMPDirectiveKind DKind, const OpenMPScheduleTy &ScheduleKind, const StaticRTInput &Values); /// /// \param CGF Reference to current CodeGenFunction. /// \param Loc Clang source location. /// \param SchedKind Schedule kind, specified by the 'dist_schedule' clause. /// \param Values Input arguments for the construct. /// virtual void emitDistributeStaticInit(CodeGenFunction &CGF, SourceLocation Loc, OpenMPDistScheduleClauseKind SchedKind, const StaticRTInput &Values); /// Call the appropriate runtime routine to notify that we finished /// iteration of the ordered loop with the dynamic scheduling. /// /// \param CGF Reference to current CodeGenFunction. /// \param Loc Clang source location. /// \param IVSize Size of the iteration variable in bits. /// \param IVSigned Sign of the iteration variable. /// virtual void emitForOrderedIterationEnd(CodeGenFunction &CGF, SourceLocation Loc, unsigned IVSize, bool IVSigned); /// Call the appropriate runtime routine to notify that we finished /// all the work with current loop. /// /// \param CGF Reference to current CodeGenFunction. /// \param Loc Clang source location. /// \param DKind Kind of the directive for which the static finish is emitted. /// virtual void emitForStaticFinish(CodeGenFunction &CGF, SourceLocation Loc, OpenMPDirectiveKind DKind); /// Call __kmpc_dispatch_next( /// ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter, /// kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper, /// kmp_int[32|64] *p_stride); /// \param IVSize Size of the iteration variable in bits. /// \param IVSigned Sign of the iteration variable. /// \param IL Address of the output variable in which the flag of the /// last iteration is returned. /// \param LB Address of the output variable in which the lower iteration /// number is returned. /// \param UB Address of the output variable in which the upper iteration /// number is returned. /// \param ST Address of the output variable in which the stride value is /// returned. virtual llvm::Value *emitForNext(CodeGenFunction &CGF, SourceLocation Loc, unsigned IVSize, bool IVSigned, Address IL, Address LB, Address UB, Address ST); /// Emits call to void __kmpc_push_num_threads(ident_t *loc, kmp_int32 /// global_tid, kmp_int32 num_threads) to generate code for 'num_threads' /// clause. /// \param NumThreads An integer value of threads. virtual void emitNumThreadsClause(CodeGenFunction &CGF, llvm::Value *NumThreads, SourceLocation Loc); /// Emit call to void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 /// global_tid, int proc_bind) to generate code for 'proc_bind' clause. virtual void emitProcBindClause(CodeGenFunction &CGF, llvm::omp::ProcBindKind ProcBind, SourceLocation Loc); /// Returns address of the threadprivate variable for the current /// thread. /// \param VD Threadprivate variable. /// \param VDAddr Address of the global variable \a VD. /// \param Loc Location of the reference to threadprivate var. /// \return Address of the threadprivate variable for the current thread. virtual Address getAddrOfThreadPrivate(CodeGenFunction &CGF, const VarDecl *VD, Address VDAddr, SourceLocation Loc); /// Returns the address of the variable marked as declare target with link /// clause OR as declare target with to clause and unified memory. virtual Address getAddrOfDeclareTargetVar(const VarDecl *VD); /// Emit a code for initialization of threadprivate variable. It emits /// a call to runtime library which adds initial value to the newly created /// threadprivate variable (if it is not constant) and registers destructor /// for the variable (if any). /// \param VD Threadprivate variable. /// \param VDAddr Address of the global variable \a VD. /// \param Loc Location of threadprivate declaration. /// \param PerformInit true if initialization expression is not constant. virtual llvm::Function * emitThreadPrivateVarDefinition(const VarDecl *VD, Address VDAddr, SourceLocation Loc, bool PerformInit, CodeGenFunction *CGF = nullptr); /// Emit a code for initialization of declare target variable. /// \param VD Declare target variable. /// \param Addr Address of the global variable \a VD. /// \param PerformInit true if initialization expression is not constant. virtual bool emitDeclareTargetVarDefinition(const VarDecl *VD, llvm::GlobalVariable *Addr, bool PerformInit); /// Creates artificial threadprivate variable with name \p Name and type \p /// VarType. /// \param VarType Type of the artificial threadprivate variable. /// \param Name Name of the artificial threadprivate variable. virtual Address getAddrOfArtificialThreadPrivate(CodeGenFunction &CGF, QualType VarType, StringRef Name); /// Emit flush of the variables specified in 'omp flush' directive. /// \param Vars List of variables to flush. virtual void emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *> Vars, SourceLocation Loc, llvm::AtomicOrdering AO); /// Emit task region for the task directive. The task region is /// emitted in several steps: /// 1. Emit a call to kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 /// gtid, kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds, /// kmp_routine_entry_t *task_entry). Here task_entry is a pointer to the /// function: /// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) { /// TaskFunction(gtid, tt->part_id, tt->shareds); /// return 0; /// } /// 2. Copy a list of shared variables to field shareds of the resulting /// structure kmp_task_t returned by the previous call (if any). /// 3. Copy a pointer to destructions function to field destructions of the /// resulting structure kmp_task_t. /// 4. Emit a call to kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, /// kmp_task_t *new_task), where new_task is a resulting structure from /// previous items. /// \param D Current task directive. /// \param TaskFunction An LLVM function with type void (*)(i32 /*gtid*/, i32 /// /*part_id*/, captured_struct */*__context*/); /// \param SharedsTy A type which contains references the shared variables. /// \param Shareds Context with the list of shared variables from the \p /// TaskFunction. /// \param IfCond Not a nullptr if 'if' clause was specified, nullptr /// otherwise. /// \param Data Additional data for task generation like tiednsee, final /// state, list of privates etc. virtual void emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc, const OMPExecutableDirective &D, llvm::Function *TaskFunction, QualType SharedsTy, Address Shareds, const Expr *IfCond, const OMPTaskDataTy &Data); /// Emit task region for the taskloop directive. The taskloop region is /// emitted in several steps: /// 1. Emit a call to kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 /// gtid, kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds, /// kmp_routine_entry_t *task_entry). Here task_entry is a pointer to the /// function: /// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) { /// TaskFunction(gtid, tt->part_id, tt->shareds); /// return 0; /// } /// 2. Copy a list of shared variables to field shareds of the resulting /// structure kmp_task_t returned by the previous call (if any). /// 3. Copy a pointer to destructions function to field destructions of the /// resulting structure kmp_task_t. /// 4. Emit a call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t /// *task, int if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int /// nogroup, int sched, kmp_uint64 grainsize, void *task_dup ), where new_task /// is a resulting structure from /// previous items. /// \param D Current task directive. /// \param TaskFunction An LLVM function with type void (*)(i32 /*gtid*/, i32 /// /*part_id*/, captured_struct */*__context*/); /// \param SharedsTy A type which contains references the shared variables. /// \param Shareds Context with the list of shared variables from the \p /// TaskFunction. /// \param IfCond Not a nullptr if 'if' clause was specified, nullptr /// otherwise. /// \param Data Additional data for task generation like tiednsee, final /// state, list of privates etc. virtual void emitTaskLoopCall(CodeGenFunction &CGF, SourceLocation Loc, const OMPLoopDirective &D, llvm::Function *TaskFunction, QualType SharedsTy, Address Shareds, const Expr *IfCond, const OMPTaskDataTy &Data); /// Emit code for the directive that does not require outlining. /// /// \param InnermostKind Kind of innermost directive (for simple directives it /// is a directive itself, for combined - its innermost directive). /// \param CodeGen Code generation sequence for the \a D directive. /// \param HasCancel true if region has inner cancel directive, false /// otherwise. virtual void emitInlinedDirective(CodeGenFunction &CGF, OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen, bool HasCancel = false); /// Emits reduction function. /// \param ArgsElemType Array type containing pointers to reduction variables. /// \param Privates List of private copies for original reduction arguments. /// \param LHSExprs List of LHS in \a ReductionOps reduction operations. /// \param RHSExprs List of RHS in \a ReductionOps reduction operations. /// \param ReductionOps List of reduction operations in form 'LHS binop RHS' /// or 'operator binop(LHS, RHS)'. llvm::Function *emitReductionFunction(SourceLocation Loc, llvm::Type *ArgsElemType, ArrayRef<const Expr *> Privates, ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs, ArrayRef<const Expr *> ReductionOps); /// Emits single reduction combiner void emitSingleReductionCombiner(CodeGenFunction &CGF, const Expr *ReductionOp, const Expr *PrivateRef, const DeclRefExpr *LHS, const DeclRefExpr *RHS); struct ReductionOptionsTy { bool WithNowait; bool SimpleReduction; OpenMPDirectiveKind ReductionKind; }; /// Emit a code for reduction clause. Next code should be emitted for /// reduction: /// \code /// /// static kmp_critical_name lock = { 0 }; /// /// void reduce_func(void *lhs[<n>], void *rhs[<n>]) { /// ... /// *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]); /// ... /// } /// /// ... /// void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]}; /// switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList), /// RedList, reduce_func, &<lock>)) { /// case 1: /// ... /// <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]); /// ... /// __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>); /// break; /// case 2: /// ... /// Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i])); /// ... /// break; /// default:; /// } /// \endcode /// /// \param Privates List of private copies for original reduction arguments. /// \param LHSExprs List of LHS in \a ReductionOps reduction operations. /// \param RHSExprs List of RHS in \a ReductionOps reduction operations. /// \param ReductionOps List of reduction operations in form 'LHS binop RHS' /// or 'operator binop(LHS, RHS)'. /// \param Options List of options for reduction codegen: /// WithNowait true if parent directive has also nowait clause, false /// otherwise. /// SimpleReduction Emit reduction operation only. Used for omp simd /// directive on the host. /// ReductionKind The kind of reduction to perform. virtual void emitReduction(CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> Privates, ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs, ArrayRef<const Expr *> ReductionOps, ReductionOptionsTy Options); /// Emit a code for initialization of task reduction clause. Next code /// should be emitted for reduction: /// \code /// /// _taskred_item_t red_data[n]; /// ... /// red_data[i].shar = &shareds[i]; /// red_data[i].orig = &origs[i]; /// red_data[i].size = sizeof(origs[i]); /// red_data[i].f_init = (void*)RedInit<i>; /// red_data[i].f_fini = (void*)RedDest<i>; /// red_data[i].f_comb = (void*)RedOp<i>; /// red_data[i].flags = <Flag_i>; /// ... /// void* tg1 = __kmpc_taskred_init(gtid, n, red_data); /// \endcode /// For reduction clause with task modifier it emits the next call: /// \code /// /// _taskred_item_t red_data[n]; /// ... /// red_data[i].shar = &shareds[i]; /// red_data[i].orig = &origs[i]; /// red_data[i].size = sizeof(origs[i]); /// red_data[i].f_init = (void*)RedInit<i>; /// red_data[i].f_fini = (void*)RedDest<i>; /// red_data[i].f_comb = (void*)RedOp<i>; /// red_data[i].flags = <Flag_i>; /// ... /// void* tg1 = __kmpc_taskred_modifier_init(loc, gtid, is_worksharing, n, /// red_data); /// \endcode /// \param LHSExprs List of LHS in \a Data.ReductionOps reduction operations. /// \param RHSExprs List of RHS in \a Data.ReductionOps reduction operations. /// \param Data Additional data for task generation like tiedness, final /// state, list of privates, reductions etc. virtual llvm::Value *emitTaskReductionInit(CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs, const OMPTaskDataTy &Data); /// Emits the following code for reduction clause with task modifier: /// \code /// __kmpc_task_reduction_modifier_fini(loc, gtid, is_worksharing); /// \endcode virtual void emitTaskReductionFini(CodeGenFunction &CGF, SourceLocation Loc, bool IsWorksharingReduction); /// Required to resolve existing problems in the runtime. Emits threadprivate /// variables to store the size of the VLAs/array sections for /// initializer/combiner/finalizer functions. /// \param RCG Allows to reuse an existing data for the reductions. /// \param N Reduction item for which fixups must be emitted. virtual void emitTaskReductionFixups(CodeGenFunction &CGF, SourceLocation Loc, ReductionCodeGen &RCG, unsigned N); /// Get the address of `void *` type of the privatue copy of the reduction /// item specified by the \p SharedLVal. /// \param ReductionsPtr Pointer to the reduction data returned by the /// emitTaskReductionInit function. /// \param SharedLVal Address of the original reduction item. virtual Address getTaskReductionItem(CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *ReductionsPtr, LValue SharedLVal); /// Emit code for 'taskwait' directive. virtual void emitTaskwaitCall(CodeGenFunction &CGF, SourceLocation Loc, const OMPTaskDataTy &Data); /// Emit code for 'cancellation point' construct. /// \param CancelRegion Region kind for which the cancellation point must be /// emitted. /// virtual void emitCancellationPointCall(CodeGenFunction &CGF, SourceLocation Loc, OpenMPDirectiveKind CancelRegion); /// Emit code for 'cancel' construct. /// \param IfCond Condition in the associated 'if' clause, if it was /// specified, nullptr otherwise. /// \param CancelRegion Region kind for which the cancel must be emitted. /// virtual void emitCancelCall(CodeGenFunction &CGF, SourceLocation Loc, const Expr *IfCond, OpenMPDirectiveKind CancelRegion); /// Emit outilined function for 'target' directive. /// \param D Directive to emit. /// \param ParentName Name of the function that encloses the target region. /// \param OutlinedFn Outlined function value to be defined by this call. /// \param OutlinedFnID Outlined function ID value to be defined by this call. /// \param IsOffloadEntry True if the outlined function is an offload entry. /// \param CodeGen Code generation sequence for the \a D directive. /// An outlined function may not be an entry if, e.g. the if clause always /// evaluates to false. virtual void emitTargetOutlinedFunction(const OMPExecutableDirective &D, StringRef ParentName, llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID, bool IsOffloadEntry, const RegionCodeGenTy &CodeGen); /// Emit the target offloading code associated with \a D. The emitted /// code attempts offloading the execution to the device, an the event of /// a failure it executes the host version outlined in \a OutlinedFn. /// \param D Directive to emit. /// \param OutlinedFn Host version of the code to be offloaded. /// \param OutlinedFnID ID of host version of the code to be offloaded. /// \param IfCond Expression evaluated in if clause associated with the target /// directive, or null if no if clause is used. /// \param Device Expression evaluated in device clause associated with the /// target directive, or null if no device clause is used and device modifier. /// \param SizeEmitter Callback to emit number of iterations for loop-based /// directives. virtual void emitTargetCall( CodeGenFunction &CGF, const OMPExecutableDirective &D, llvm::Function *OutlinedFn, llvm::Value *OutlinedFnID, const Expr *IfCond, llvm::PointerIntPair<const Expr *, 2, OpenMPDeviceClauseModifier> Device, llvm::function_ref<llvm::Value *(CodeGenFunction &CGF, const OMPLoopDirective &D)> SizeEmitter); /// Emit the target regions enclosed in \a GD function definition or /// the function itself in case it is a valid device function. Returns true if /// \a GD was dealt with successfully. /// \param GD Function to scan. virtual bool emitTargetFunctions(GlobalDecl GD); /// Emit the global variable if it is a valid device global variable. /// Returns true if \a GD was dealt with successfully. /// \param GD Variable declaration to emit. virtual bool emitTargetGlobalVariable(GlobalDecl GD); /// Checks if the provided global decl \a GD is a declare target variable and /// registers it when emitting code for the host. virtual void registerTargetGlobalVariable(const VarDecl *VD, llvm::Constant *Addr); /// Emit the global \a GD if it is meaningful for the target. Returns /// if it was emitted successfully. /// \param GD Global to scan. virtual bool emitTargetGlobal(GlobalDecl GD); /// Creates and returns a registration function for when at least one /// requires directives was used in the current module. llvm::Function *emitRequiresDirectiveRegFun(); /// Creates all the offload entries in the current compilation unit /// along with the associated metadata. void createOffloadEntriesAndInfoMetadata(); /// Emits code for teams call of the \a OutlinedFn with /// variables captured in a record which address is stored in \a /// CapturedStruct. /// \param OutlinedFn Outlined function to be run by team masters. Type of /// this function is void(*)(kmp_int32 *, kmp_int32, struct context_vars*). /// \param CapturedVars A pointer to the record with the references to /// variables used in \a OutlinedFn function. /// virtual void emitTeamsCall(CodeGenFunction &CGF, const OMPExecutableDirective &D, SourceLocation Loc, llvm::Function *OutlinedFn, ArrayRef<llvm::Value *> CapturedVars); /// Emits call to void __kmpc_push_num_teams(ident_t *loc, kmp_int32 /// global_tid, kmp_int32 num_teams, kmp_int32 thread_limit) to generate code /// for num_teams clause. /// \param NumTeams An integer expression of teams. /// \param ThreadLimit An integer expression of threads. virtual void emitNumTeamsClause(CodeGenFunction &CGF, const Expr *NumTeams, const Expr *ThreadLimit, SourceLocation Loc); /// Struct that keeps all the relevant information that should be kept /// throughout a 'target data' region. class TargetDataInfo { /// Set to true if device pointer information have to be obtained. bool RequiresDevicePointerInfo = false; /// Set to true if Clang emits separate runtime calls for the beginning and /// end of the region. These calls might have separate map type arrays. bool SeparateBeginEndCalls = false; public: /// The array of base pointer passed to the runtime library. llvm::Value *BasePointersArray = nullptr; /// The array of section pointers passed to the runtime library. llvm::Value *PointersArray = nullptr; /// The array of sizes passed to the runtime library. llvm::Value *SizesArray = nullptr; /// The array of map types passed to the runtime library for the beginning /// of the region or for the entire region if there are no separate map /// types for the region end. llvm::Value *MapTypesArray = nullptr; /// The array of map types passed to the runtime library for the end of the /// region, or nullptr if there are no separate map types for the region /// end. llvm::Value *MapTypesArrayEnd = nullptr; /// The array of user-defined mappers passed to the runtime library. llvm::Value *MappersArray = nullptr; /// The array of original declaration names of mapped pointers sent to the /// runtime library for debugging llvm::Value *MapNamesArray = nullptr; /// Indicate whether any user-defined mapper exists. bool HasMapper = false; /// The total number of pointers passed to the runtime library. unsigned NumberOfPtrs = 0u; /// Map between the a declaration of a capture and the corresponding base /// pointer address where the runtime returns the device pointers. llvm::DenseMap<const ValueDecl *, Address> CaptureDeviceAddrMap; explicit TargetDataInfo() {} explicit TargetDataInfo(bool RequiresDevicePointerInfo, bool SeparateBeginEndCalls) : RequiresDevicePointerInfo(RequiresDevicePointerInfo), SeparateBeginEndCalls(SeparateBeginEndCalls) {} /// Clear information about the data arrays. void clearArrayInfo() { BasePointersArray = nullptr; PointersArray = nullptr; SizesArray = nullptr; MapTypesArray = nullptr; MapTypesArrayEnd = nullptr; MapNamesArray = nullptr; MappersArray = nullptr; HasMapper = false; NumberOfPtrs = 0u; } /// Return true if the current target data information has valid arrays. bool isValid() { return BasePointersArray && PointersArray && SizesArray && MapTypesArray && (!HasMapper || MappersArray) && NumberOfPtrs; } bool requiresDevicePointerInfo() { return RequiresDevicePointerInfo; } bool separateBeginEndCalls() { return SeparateBeginEndCalls; } }; /// Emit the target data mapping code associated with \a D. /// \param D Directive to emit. /// \param IfCond Expression evaluated in if clause associated with the /// target directive, or null if no device clause is used. /// \param Device Expression evaluated in device clause associated with the /// target directive, or null if no device clause is used. /// \param Info A record used to store information that needs to be preserved /// until the region is closed. virtual void emitTargetDataCalls(CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond, const Expr *Device, const RegionCodeGenTy &CodeGen, TargetDataInfo &Info); /// Emit the data mapping/movement code associated with the directive /// \a D that should be of the form 'target [{enter|exit} data | update]'. /// \param D Directive to emit. /// \param IfCond Expression evaluated in if clause associated with the target /// directive, or null if no if clause is used. /// \param Device Expression evaluated in device clause associated with the /// target directive, or null if no device clause is used. virtual void emitTargetDataStandAloneCall(CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond, const Expr *Device); /// Marks function \a Fn with properly mangled versions of vector functions. /// \param FD Function marked as 'declare simd'. /// \param Fn LLVM function that must be marked with 'declare simd' /// attributes. virtual void emitDeclareSimdFunction(const FunctionDecl *FD, llvm::Function *Fn); /// Emit initialization for doacross loop nesting support. /// \param D Loop-based construct used in doacross nesting construct. virtual void emitDoacrossInit(CodeGenFunction &CGF, const OMPLoopDirective &D, ArrayRef<Expr *> NumIterations); /// Emit code for doacross ordered directive with 'depend' clause. /// \param C 'depend' clause with 'sink|source' dependency kind. virtual void emitDoacrossOrdered(CodeGenFunction &CGF, const OMPDependClause *C); /// Translates the native parameter of outlined function if this is required /// for target. /// \param FD Field decl from captured record for the parameter. /// \param NativeParam Parameter itself. virtual const VarDecl *translateParameter(const FieldDecl *FD, const VarDecl *NativeParam) const { return NativeParam; } /// Gets the address of the native argument basing on the address of the /// target-specific parameter. /// \param NativeParam Parameter itself. /// \param TargetParam Corresponding target-specific parameter. virtual Address getParameterAddress(CodeGenFunction &CGF, const VarDecl *NativeParam, const VarDecl *TargetParam) const; /// Choose default schedule type and chunk value for the /// dist_schedule clause. virtual void getDefaultDistScheduleAndChunk(CodeGenFunction &CGF, const OMPLoopDirective &S, OpenMPDistScheduleClauseKind &ScheduleKind, llvm::Value *&Chunk) const {} /// Choose default schedule type and chunk value for the /// schedule clause. virtual void getDefaultScheduleAndChunk(CodeGenFunction &CGF, const OMPLoopDirective &S, OpenMPScheduleClauseKind &ScheduleKind, const Expr *&ChunkExpr) const; /// Emits call of the outlined function with the provided arguments, /// translating these arguments to correct target-specific arguments. virtual void emitOutlinedFunctionCall(CodeGenFunction &CGF, SourceLocation Loc, llvm::FunctionCallee OutlinedFn, ArrayRef<llvm::Value *> Args = llvm::None) const; /// Emits OpenMP-specific function prolog. /// Required for device constructs. virtual void emitFunctionProlog(CodeGenFunction &CGF, const Decl *D); /// Gets the OpenMP-specific address of the local variable. virtual Address getAddressOfLocalVariable(CodeGenFunction &CGF, const VarDecl *VD); /// Marks the declaration as already emitted for the device code and returns /// true, if it was marked already, and false, otherwise. bool markAsGlobalTarget(GlobalDecl GD); /// Emit deferred declare target variables marked for deferred emission. void emitDeferredTargetDecls() const; /// Adjust some parameters for the target-based directives, like addresses of /// the variables captured by reference in lambdas. virtual void adjustTargetSpecificDataForLambdas(CodeGenFunction &CGF, const OMPExecutableDirective &D) const; /// Perform check on requires decl to ensure that target architecture /// supports unified addressing virtual void processRequiresDirective(const OMPRequiresDecl *D); /// Gets default memory ordering as specified in requires directive. llvm::AtomicOrdering getDefaultMemoryOrdering() const; /// Checks if the variable has associated OMPAllocateDeclAttr attribute with /// the predefined allocator and translates it into the corresponding address /// space. virtual bool hasAllocateAttributeForGlobalVar(const VarDecl *VD, LangAS &AS); /// Return whether the unified_shared_memory has been specified. bool hasRequiresUnifiedSharedMemory() const; /// Checks if the \p VD variable is marked as nontemporal declaration in /// current context. bool isNontemporalDecl(const ValueDecl *VD) const; /// Create specialized alloca to handle lastprivate conditionals. Address emitLastprivateConditionalInit(CodeGenFunction &CGF, const VarDecl *VD); /// Checks if the provided \p LVal is lastprivate conditional and emits the /// code to update the value of the original variable. /// \code /// lastprivate(conditional: a) /// ... /// <type> a; /// lp_a = ...; /// #pragma omp critical(a) /// if (last_iv_a <= iv) { /// last_iv_a = iv; /// global_a = lp_a; /// } /// \endcode virtual void checkAndEmitLastprivateConditional(CodeGenFunction &CGF, const Expr *LHS); /// Checks if the lastprivate conditional was updated in inner region and /// writes the value. /// \code /// lastprivate(conditional: a) /// ... /// <type> a;bool Fired = false; /// #pragma omp ... shared(a) /// { /// lp_a = ...; /// Fired = true; /// } /// if (Fired) { /// #pragma omp critical(a) /// if (last_iv_a <= iv) { /// last_iv_a = iv; /// global_a = lp_a; /// } /// Fired = false; /// } /// \endcode virtual void checkAndEmitSharedLastprivateConditional( CodeGenFunction &CGF, const OMPExecutableDirective &D, const llvm::DenseSet<CanonicalDeclPtr<const VarDecl>> &IgnoredDecls); /// Gets the address of the global copy used for lastprivate conditional /// update, if any. /// \param PrivLVal LValue for the private copy. /// \param VD Original lastprivate declaration. virtual void emitLastprivateConditionalFinalUpdate(CodeGenFunction &CGF, LValue PrivLVal, const VarDecl *VD, SourceLocation Loc); /// Emits list of dependecies based on the provided data (array of /// dependence/expression pairs). /// \returns Pointer to the first element of the array casted to VoidPtr type. std::pair<llvm::Value *, Address> emitDependClause(CodeGenFunction &CGF, ArrayRef<OMPTaskDataTy::DependData> Dependencies, SourceLocation Loc); /// Emits list of dependecies based on the provided data (array of /// dependence/expression pairs) for depobj construct. In this case, the /// variable is allocated in dynamically. \returns Pointer to the first /// element of the array casted to VoidPtr type. Address emitDepobjDependClause(CodeGenFunction &CGF, const OMPTaskDataTy::DependData &Dependencies, SourceLocation Loc); /// Emits the code to destroy the dependency object provided in depobj /// directive. void emitDestroyClause(CodeGenFunction &CGF, LValue DepobjLVal, SourceLocation Loc); /// Updates the dependency kind in the specified depobj object. /// \param DepobjLVal LValue for the main depobj object. /// \param NewDepKind New dependency kind. void emitUpdateClause(CodeGenFunction &CGF, LValue DepobjLVal, OpenMPDependClauseKind NewDepKind, SourceLocation Loc); /// Initializes user defined allocators specified in the uses_allocators /// clauses. void emitUsesAllocatorsInit(CodeGenFunction &CGF, const Expr *Allocator, const Expr *AllocatorTraits); /// Destroys user defined allocators specified in the uses_allocators clause. void emitUsesAllocatorsFini(CodeGenFunction &CGF, const Expr *Allocator); /// Returns true if the variable is a local variable in untied task. bool isLocalVarInUntiedTask(CodeGenFunction &CGF, const VarDecl *VD) const; }; /// Class supports emissionof SIMD-only code. class CGOpenMPSIMDRuntime final : public CGOpenMPRuntime { public: explicit CGOpenMPSIMDRuntime(CodeGenModule &CGM) : CGOpenMPRuntime(CGM) {} ~CGOpenMPSIMDRuntime() override {} /// Emits outlined function for the specified OpenMP parallel directive /// \a D. This outlined function has type void(*)(kmp_int32 *ThreadID, /// kmp_int32 BoundID, struct context_vars*). /// \param D OpenMP directive. /// \param ThreadIDVar Variable for thread id in the current OpenMP region. /// \param InnermostKind Kind of innermost directive (for simple directives it /// is a directive itself, for combined - its innermost directive). /// \param CodeGen Code generation sequence for the \a D directive. llvm::Function * emitParallelOutlinedFunction(const OMPExecutableDirective &D, const VarDecl *ThreadIDVar, OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) override; /// Emits outlined function for the specified OpenMP teams directive /// \a D. This outlined function has type void(*)(kmp_int32 *ThreadID, /// kmp_int32 BoundID, struct context_vars*). /// \param D OpenMP directive. /// \param ThreadIDVar Variable for thread id in the current OpenMP region. /// \param InnermostKind Kind of innermost directive (for simple directives it /// is a directive itself, for combined - its innermost directive). /// \param CodeGen Code generation sequence for the \a D directive. llvm::Function * emitTeamsOutlinedFunction(const OMPExecutableDirective &D, const VarDecl *ThreadIDVar, OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) override; /// Emits outlined function for the OpenMP task directive \a D. This /// outlined function has type void(*)(kmp_int32 ThreadID, struct task_t* /// TaskT). /// \param D OpenMP directive. /// \param ThreadIDVar Variable for thread id in the current OpenMP region. /// \param PartIDVar Variable for partition id in the current OpenMP untied /// task region. /// \param TaskTVar Variable for task_t argument. /// \param InnermostKind Kind of innermost directive (for simple directives it /// is a directive itself, for combined - its innermost directive). /// \param CodeGen Code generation sequence for the \a D directive. /// \param Tied true if task is generated for tied task, false otherwise. /// \param NumberOfParts Number of parts in untied task. Ignored for tied /// tasks. /// llvm::Function *emitTaskOutlinedFunction( const OMPExecutableDirective &D, const VarDecl *ThreadIDVar, const VarDecl *PartIDVar, const VarDecl *TaskTVar, OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen, bool Tied, unsigned &NumberOfParts) override; /// Emits code for parallel or serial call of the \a OutlinedFn with /// variables captured in a record which address is stored in \a /// CapturedStruct. /// \param OutlinedFn Outlined function to be run in parallel threads. Type of /// this function is void(*)(kmp_int32 *, kmp_int32, struct context_vars*). /// \param CapturedVars A pointer to the record with the references to /// variables used in \a OutlinedFn function. /// \param IfCond Condition in the associated 'if' clause, if it was /// specified, nullptr otherwise. /// \param NumThreads The value corresponding to the num_threads clause, if /// any, or nullptr. /// void emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc, llvm::Function *OutlinedFn, ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond, llvm::Value *NumThreads) override; /// Emits a critical region. /// \param CriticalName Name of the critical region. /// \param CriticalOpGen Generator for the statement associated with the given /// critical region. /// \param Hint Value of the 'hint' clause (optional). void emitCriticalRegion(CodeGenFunction &CGF, StringRef CriticalName, const RegionCodeGenTy &CriticalOpGen, SourceLocation Loc, const Expr *Hint = nullptr) override; /// Emits a master region. /// \param MasterOpGen Generator for the statement associated with the given /// master region. void emitMasterRegion(CodeGenFunction &CGF, const RegionCodeGenTy &MasterOpGen, SourceLocation Loc) override; /// Emits a masked region. /// \param MaskedOpGen Generator for the statement associated with the given /// masked region. void emitMaskedRegion(CodeGenFunction &CGF, const RegionCodeGenTy &MaskedOpGen, SourceLocation Loc, const Expr *Filter = nullptr) override; /// Emits a masked region. /// \param MaskedOpGen Generator for the statement associated with the given /// masked region. /// Emits code for a taskyield directive. void emitTaskyieldCall(CodeGenFunction &CGF, SourceLocation Loc) override; /// Emit a taskgroup region. /// \param TaskgroupOpGen Generator for the statement associated with the /// given taskgroup region. void emitTaskgroupRegion(CodeGenFunction &CGF, const RegionCodeGenTy &TaskgroupOpGen, SourceLocation Loc) override; /// Emits a single region. /// \param SingleOpGen Generator for the statement associated with the given /// single region. void emitSingleRegion(CodeGenFunction &CGF, const RegionCodeGenTy &SingleOpGen, SourceLocation Loc, ArrayRef<const Expr *> CopyprivateVars, ArrayRef<const Expr *> DestExprs, ArrayRef<const Expr *> SrcExprs, ArrayRef<const Expr *> AssignmentOps) override; /// Emit an ordered region. /// \param OrderedOpGen Generator for the statement associated with the given /// ordered region. void emitOrderedRegion(CodeGenFunction &CGF, const RegionCodeGenTy &OrderedOpGen, SourceLocation Loc, bool IsThreads) override; /// Emit an implicit/explicit barrier for OpenMP threads. /// \param Kind Directive for which this implicit barrier call must be /// generated. Must be OMPD_barrier for explicit barrier generation. /// \param EmitChecks true if need to emit checks for cancellation barriers. /// \param ForceSimpleCall true simple barrier call must be emitted, false if /// runtime class decides which one to emit (simple or with cancellation /// checks). /// void emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc, OpenMPDirectiveKind Kind, bool EmitChecks = true, bool ForceSimpleCall = false) override; /// This is used for non static scheduled types and when the ordered /// clause is present on the loop construct. /// Depending on the loop schedule, it is necessary to call some runtime /// routine before start of the OpenMP loop to get the loop upper / lower /// bounds \a LB and \a UB and stride \a ST. /// /// \param CGF Reference to current CodeGenFunction. /// \param Loc Clang source location. /// \param ScheduleKind Schedule kind, specified by the 'schedule' clause. /// \param IVSize Size of the iteration variable in bits. /// \param IVSigned Sign of the iteration variable. /// \param Ordered true if loop is ordered, false otherwise. /// \param DispatchValues struct containing llvm values for lower bound, upper /// bound, and chunk expression. /// For the default (nullptr) value, the chunk 1 will be used. /// void emitForDispatchInit(CodeGenFunction &CGF, SourceLocation Loc, const OpenMPScheduleTy &ScheduleKind, unsigned IVSize, bool IVSigned, bool Ordered, const DispatchRTInput &DispatchValues) override; /// Call the appropriate runtime routine to initialize it before start /// of loop. /// /// This is used only in case of static schedule, when the user did not /// specify a ordered clause on the loop construct. /// Depending on the loop schedule, it is necessary to call some runtime /// routine before start of the OpenMP loop to get the loop upper / lower /// bounds LB and UB and stride ST. /// /// \param CGF Reference to current CodeGenFunction. /// \param Loc Clang source location. /// \param DKind Kind of the directive. /// \param ScheduleKind Schedule kind, specified by the 'schedule' clause. /// \param Values Input arguments for the construct. /// void emitForStaticInit(CodeGenFunction &CGF, SourceLocation Loc, OpenMPDirectiveKind DKind, const OpenMPScheduleTy &ScheduleKind, const StaticRTInput &Values) override; /// /// \param CGF Reference to current CodeGenFunction. /// \param Loc Clang source location. /// \param SchedKind Schedule kind, specified by the 'dist_schedule' clause. /// \param Values Input arguments for the construct. /// void emitDistributeStaticInit(CodeGenFunction &CGF, SourceLocation Loc, OpenMPDistScheduleClauseKind SchedKind, const StaticRTInput &Values) override; /// Call the appropriate runtime routine to notify that we finished /// iteration of the ordered loop with the dynamic scheduling. /// /// \param CGF Reference to current CodeGenFunction. /// \param Loc Clang source location. /// \param IVSize Size of the iteration variable in bits. /// \param IVSigned Sign of the iteration variable. /// void emitForOrderedIterationEnd(CodeGenFunction &CGF, SourceLocation Loc, unsigned IVSize, bool IVSigned) override; /// Call the appropriate runtime routine to notify that we finished /// all the work with current loop. /// /// \param CGF Reference to current CodeGenFunction. /// \param Loc Clang source location. /// \param DKind Kind of the directive for which the static finish is emitted. /// void emitForStaticFinish(CodeGenFunction &CGF, SourceLocation Loc, OpenMPDirectiveKind DKind) override; /// Call __kmpc_dispatch_next( /// ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter, /// kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper, /// kmp_int[32|64] *p_stride); /// \param IVSize Size of the iteration variable in bits. /// \param IVSigned Sign of the iteration variable. /// \param IL Address of the output variable in which the flag of the /// last iteration is returned. /// \param LB Address of the output variable in which the lower iteration /// number is returned. /// \param UB Address of the output variable in which the upper iteration /// number is returned. /// \param ST Address of the output variable in which the stride value is /// returned. llvm::Value *emitForNext(CodeGenFunction &CGF, SourceLocation Loc, unsigned IVSize, bool IVSigned, Address IL, Address LB, Address UB, Address ST) override; /// Emits call to void __kmpc_push_num_threads(ident_t *loc, kmp_int32 /// global_tid, kmp_int32 num_threads) to generate code for 'num_threads' /// clause. /// \param NumThreads An integer value of threads. void emitNumThreadsClause(CodeGenFunction &CGF, llvm::Value *NumThreads, SourceLocation Loc) override; /// Emit call to void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 /// global_tid, int proc_bind) to generate code for 'proc_bind' clause. void emitProcBindClause(CodeGenFunction &CGF, llvm::omp::ProcBindKind ProcBind, SourceLocation Loc) override; /// Returns address of the threadprivate variable for the current /// thread. /// \param VD Threadprivate variable. /// \param VDAddr Address of the global variable \a VD. /// \param Loc Location of the reference to threadprivate var. /// \return Address of the threadprivate variable for the current thread. Address getAddrOfThreadPrivate(CodeGenFunction &CGF, const VarDecl *VD, Address VDAddr, SourceLocation Loc) override; /// Emit a code for initialization of threadprivate variable. It emits /// a call to runtime library which adds initial value to the newly created /// threadprivate variable (if it is not constant) and registers destructor /// for the variable (if any). /// \param VD Threadprivate variable. /// \param VDAddr Address of the global variable \a VD. /// \param Loc Location of threadprivate declaration. /// \param PerformInit true if initialization expression is not constant. llvm::Function * emitThreadPrivateVarDefinition(const VarDecl *VD, Address VDAddr, SourceLocation Loc, bool PerformInit, CodeGenFunction *CGF = nullptr) override; /// Creates artificial threadprivate variable with name \p Name and type \p /// VarType. /// \param VarType Type of the artificial threadprivate variable. /// \param Name Name of the artificial threadprivate variable. Address getAddrOfArtificialThreadPrivate(CodeGenFunction &CGF, QualType VarType, StringRef Name) override; /// Emit flush of the variables specified in 'omp flush' directive. /// \param Vars List of variables to flush. void emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *> Vars, SourceLocation Loc, llvm::AtomicOrdering AO) override; /// Emit task region for the task directive. The task region is /// emitted in several steps: /// 1. Emit a call to kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 /// gtid, kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds, /// kmp_routine_entry_t *task_entry). Here task_entry is a pointer to the /// function: /// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) { /// TaskFunction(gtid, tt->part_id, tt->shareds); /// return 0; /// } /// 2. Copy a list of shared variables to field shareds of the resulting /// structure kmp_task_t returned by the previous call (if any). /// 3. Copy a pointer to destructions function to field destructions of the /// resulting structure kmp_task_t. /// 4. Emit a call to kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, /// kmp_task_t *new_task), where new_task is a resulting structure from /// previous items. /// \param D Current task directive. /// \param TaskFunction An LLVM function with type void (*)(i32 /*gtid*/, i32 /// /*part_id*/, captured_struct */*__context*/); /// \param SharedsTy A type which contains references the shared variables. /// \param Shareds Context with the list of shared variables from the \p /// TaskFunction. /// \param IfCond Not a nullptr if 'if' clause was specified, nullptr /// otherwise. /// \param Data Additional data for task generation like tiednsee, final /// state, list of privates etc. void emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc, const OMPExecutableDirective &D, llvm::Function *TaskFunction, QualType SharedsTy, Address Shareds, const Expr *IfCond, const OMPTaskDataTy &Data) override; /// Emit task region for the taskloop directive. The taskloop region is /// emitted in several steps: /// 1. Emit a call to kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 /// gtid, kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds, /// kmp_routine_entry_t *task_entry). Here task_entry is a pointer to the /// function: /// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) { /// TaskFunction(gtid, tt->part_id, tt->shareds); /// return 0; /// } /// 2. Copy a list of shared variables to field shareds of the resulting /// structure kmp_task_t returned by the previous call (if any). /// 3. Copy a pointer to destructions function to field destructions of the /// resulting structure kmp_task_t. /// 4. Emit a call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t /// *task, int if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int /// nogroup, int sched, kmp_uint64 grainsize, void *task_dup ), where new_task /// is a resulting structure from /// previous items. /// \param D Current task directive. /// \param TaskFunction An LLVM function with type void (*)(i32 /*gtid*/, i32 /// /*part_id*/, captured_struct */*__context*/); /// \param SharedsTy A type which contains references the shared variables. /// \param Shareds Context with the list of shared variables from the \p /// TaskFunction. /// \param IfCond Not a nullptr if 'if' clause was specified, nullptr /// otherwise. /// \param Data Additional data for task generation like tiednsee, final /// state, list of privates etc. void emitTaskLoopCall(CodeGenFunction &CGF, SourceLocation Loc, const OMPLoopDirective &D, llvm::Function *TaskFunction, QualType SharedsTy, Address Shareds, const Expr *IfCond, const OMPTaskDataTy &Data) override; /// Emit a code for reduction clause. Next code should be emitted for /// reduction: /// \code /// /// static kmp_critical_name lock = { 0 }; /// /// void reduce_func(void *lhs[<n>], void *rhs[<n>]) { /// ... /// *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]); /// ... /// } /// /// ... /// void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]}; /// switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList), /// RedList, reduce_func, &<lock>)) { /// case 1: /// ... /// <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]); /// ... /// __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>); /// break; /// case 2: /// ... /// Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i])); /// ... /// break; /// default:; /// } /// \endcode /// /// \param Privates List of private copies for original reduction arguments. /// \param LHSExprs List of LHS in \a ReductionOps reduction operations. /// \param RHSExprs List of RHS in \a ReductionOps reduction operations. /// \param ReductionOps List of reduction operations in form 'LHS binop RHS' /// or 'operator binop(LHS, RHS)'. /// \param Options List of options for reduction codegen: /// WithNowait true if parent directive has also nowait clause, false /// otherwise. /// SimpleReduction Emit reduction operation only. Used for omp simd /// directive on the host. /// ReductionKind The kind of reduction to perform. void emitReduction(CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> Privates, ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs, ArrayRef<const Expr *> ReductionOps, ReductionOptionsTy Options) override; /// Emit a code for initialization of task reduction clause. Next code /// should be emitted for reduction: /// \code /// /// _taskred_item_t red_data[n]; /// ... /// red_data[i].shar = &shareds[i]; /// red_data[i].orig = &origs[i]; /// red_data[i].size = sizeof(origs[i]); /// red_data[i].f_init = (void*)RedInit<i>; /// red_data[i].f_fini = (void*)RedDest<i>; /// red_data[i].f_comb = (void*)RedOp<i>; /// red_data[i].flags = <Flag_i>; /// ... /// void* tg1 = __kmpc_taskred_init(gtid, n, red_data); /// \endcode /// For reduction clause with task modifier it emits the next call: /// \code /// /// _taskred_item_t red_data[n]; /// ... /// red_data[i].shar = &shareds[i]; /// red_data[i].orig = &origs[i]; /// red_data[i].size = sizeof(origs[i]); /// red_data[i].f_init = (void*)RedInit<i>; /// red_data[i].f_fini = (void*)RedDest<i>; /// red_data[i].f_comb = (void*)RedOp<i>; /// red_data[i].flags = <Flag_i>; /// ... /// void* tg1 = __kmpc_taskred_modifier_init(loc, gtid, is_worksharing, n, /// red_data); /// \endcode /// \param LHSExprs List of LHS in \a Data.ReductionOps reduction operations. /// \param RHSExprs List of RHS in \a Data.ReductionOps reduction operations. /// \param Data Additional data for task generation like tiedness, final /// state, list of privates, reductions etc. llvm::Value *emitTaskReductionInit(CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs, const OMPTaskDataTy &Data) override; /// Emits the following code for reduction clause with task modifier: /// \code /// __kmpc_task_reduction_modifier_fini(loc, gtid, is_worksharing); /// \endcode void emitTaskReductionFini(CodeGenFunction &CGF, SourceLocation Loc, bool IsWorksharingReduction) override; /// Required to resolve existing problems in the runtime. Emits threadprivate /// variables to store the size of the VLAs/array sections for /// initializer/combiner/finalizer functions + emits threadprivate variable to /// store the pointer to the original reduction item for the custom /// initializer defined by declare reduction construct. /// \param RCG Allows to reuse an existing data for the reductions. /// \param N Reduction item for which fixups must be emitted. void emitTaskReductionFixups(CodeGenFunction &CGF, SourceLocation Loc, ReductionCodeGen &RCG, unsigned N) override; /// Get the address of `void *` type of the privatue copy of the reduction /// item specified by the \p SharedLVal. /// \param ReductionsPtr Pointer to the reduction data returned by the /// emitTaskReductionInit function. /// \param SharedLVal Address of the original reduction item. Address getTaskReductionItem(CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *ReductionsPtr, LValue SharedLVal) override; /// Emit code for 'taskwait' directive. void emitTaskwaitCall(CodeGenFunction &CGF, SourceLocation Loc, const OMPTaskDataTy &Data) override; /// Emit code for 'cancellation point' construct. /// \param CancelRegion Region kind for which the cancellation point must be /// emitted. /// void emitCancellationPointCall(CodeGenFunction &CGF, SourceLocation Loc, OpenMPDirectiveKind CancelRegion) override; /// Emit code for 'cancel' construct. /// \param IfCond Condition in the associated 'if' clause, if it was /// specified, nullptr otherwise. /// \param CancelRegion Region kind for which the cancel must be emitted. /// void emitCancelCall(CodeGenFunction &CGF, SourceLocation Loc, const Expr *IfCond, OpenMPDirectiveKind CancelRegion) override; /// Emit outilined function for 'target' directive. /// \param D Directive to emit. /// \param ParentName Name of the function that encloses the target region. /// \param OutlinedFn Outlined function value to be defined by this call. /// \param OutlinedFnID Outlined function ID value to be defined by this call. /// \param IsOffloadEntry True if the outlined function is an offload entry. /// \param CodeGen Code generation sequence for the \a D directive. /// An outlined function may not be an entry if, e.g. the if clause always /// evaluates to false. void emitTargetOutlinedFunction(const OMPExecutableDirective &D, StringRef ParentName, llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID, bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) override; /// Emit the target offloading code associated with \a D. The emitted /// code attempts offloading the execution to the device, an the event of /// a failure it executes the host version outlined in \a OutlinedFn. /// \param D Directive to emit. /// \param OutlinedFn Host version of the code to be offloaded. /// \param OutlinedFnID ID of host version of the code to be offloaded. /// \param IfCond Expression evaluated in if clause associated with the target /// directive, or null if no if clause is used. /// \param Device Expression evaluated in device clause associated with the /// target directive, or null if no device clause is used and device modifier. void emitTargetCall( CodeGenFunction &CGF, const OMPExecutableDirective &D, llvm::Function *OutlinedFn, llvm::Value *OutlinedFnID, const Expr *IfCond, llvm::PointerIntPair<const Expr *, 2, OpenMPDeviceClauseModifier> Device, llvm::function_ref<llvm::Value *(CodeGenFunction &CGF, const OMPLoopDirective &D)> SizeEmitter) override; /// Emit the target regions enclosed in \a GD function definition or /// the function itself in case it is a valid device function. Returns true if /// \a GD was dealt with successfully. /// \param GD Function to scan. bool emitTargetFunctions(GlobalDecl GD) override; /// Emit the global variable if it is a valid device global variable. /// Returns true if \a GD was dealt with successfully. /// \param GD Variable declaration to emit. bool emitTargetGlobalVariable(GlobalDecl GD) override; /// Emit the global \a GD if it is meaningful for the target. Returns /// if it was emitted successfully. /// \param GD Global to scan. bool emitTargetGlobal(GlobalDecl GD) override; /// Emits code for teams call of the \a OutlinedFn with /// variables captured in a record which address is stored in \a /// CapturedStruct. /// \param OutlinedFn Outlined function to be run by team masters. Type of /// this function is void(*)(kmp_int32 *, kmp_int32, struct context_vars*). /// \param CapturedVars A pointer to the record with the references to /// variables used in \a OutlinedFn function. /// void emitTeamsCall(CodeGenFunction &CGF, const OMPExecutableDirective &D, SourceLocation Loc, llvm::Function *OutlinedFn, ArrayRef<llvm::Value *> CapturedVars) override; /// Emits call to void __kmpc_push_num_teams(ident_t *loc, kmp_int32 /// global_tid, kmp_int32 num_teams, kmp_int32 thread_limit) to generate code /// for num_teams clause. /// \param NumTeams An integer expression of teams. /// \param ThreadLimit An integer expression of threads. void emitNumTeamsClause(CodeGenFunction &CGF, const Expr *NumTeams, const Expr *ThreadLimit, SourceLocation Loc) override; /// Emit the target data mapping code associated with \a D. /// \param D Directive to emit. /// \param IfCond Expression evaluated in if clause associated with the /// target directive, or null if no device clause is used. /// \param Device Expression evaluated in device clause associated with the /// target directive, or null if no device clause is used. /// \param Info A record used to store information that needs to be preserved /// until the region is closed. void emitTargetDataCalls(CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond, const Expr *Device, const RegionCodeGenTy &CodeGen, TargetDataInfo &Info) override; /// Emit the data mapping/movement code associated with the directive /// \a D that should be of the form 'target [{enter|exit} data | update]'. /// \param D Directive to emit. /// \param IfCond Expression evaluated in if clause associated with the target /// directive, or null if no if clause is used. /// \param Device Expression evaluated in device clause associated with the /// target directive, or null if no device clause is used. void emitTargetDataStandAloneCall(CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond, const Expr *Device) override; /// Emit initialization for doacross loop nesting support. /// \param D Loop-based construct used in doacross nesting construct. void emitDoacrossInit(CodeGenFunction &CGF, const OMPLoopDirective &D, ArrayRef<Expr *> NumIterations) override; /// Emit code for doacross ordered directive with 'depend' clause. /// \param C 'depend' clause with 'sink|source' dependency kind. void emitDoacrossOrdered(CodeGenFunction &CGF, const OMPDependClause *C) override; /// Translates the native parameter of outlined function if this is required /// for target. /// \param FD Field decl from captured record for the parameter. /// \param NativeParam Parameter itself. const VarDecl *translateParameter(const FieldDecl *FD, const VarDecl *NativeParam) const override; /// Gets the address of the native argument basing on the address of the /// target-specific parameter. /// \param NativeParam Parameter itself. /// \param TargetParam Corresponding target-specific parameter. Address getParameterAddress(CodeGenFunction &CGF, const VarDecl *NativeParam, const VarDecl *TargetParam) const override; /// Gets the OpenMP-specific address of the local variable. Address getAddressOfLocalVariable(CodeGenFunction &CGF, const VarDecl *VD) override { return Address::invalid(); } }; } // namespace CodeGen } // namespace clang #endif
sparse.c
/* Copyright (c) 2013, Intel Corporation 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 Intel Corporation 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. */ /********************************************************************************* NAME: sparse PURPOSE: This program tests the efficiency with which a sparse matrix vector multiplication is carried out USAGE: The program takes as input the number of threads, the 2log of the linear size of the 2D grid (equalling the 2log of the square root of the order of the sparse matrix), the radius of the difference stencil, and the number of times the matrix-vector multiplication is carried out. <progname> <# threads> <# iterations> <2log root-of-matrix-order> <radius> The output consists of diagnostics to make sure the algorithm worked, and of timing statistics. FUNCTIONS CALLED: Other than OpenMP or standard C functions, the following functions are used in this program: wtime() bail_out() reverse() NOTES: HISTORY: Written by Rob Van der Wijngaart, August 2006. Updated by RvdW to parallelize matrix generation, March 2007. Updated by RvdW to fix verification bug, February 2013 Updated by RvdW to sort matrix elements to reflect traditional CSR storage, August 2013 ***********************************************************************************/ #include <par-res-kern_general.h> #include <par-res-kern_omp.h> /* linearize the grid index */ #define LIN(i,j) (i+((j)<<lsize)) /* if the scramble flag is set, convert all (linearized) grid indices by reversing their bits; if not, leave the grid indices alone */ #ifdef SCRAMBLE #define REVERSE(a,b) reverse((a),(b)) #else #define REVERSE(a,b) (a) #endif #define BITS_IN_BYTE 8 static u64Int reverse(register u64Int, int); static int compare(const void *el1, const void *el2); int main(int argc, char **argv){ int iter, r; /* dummies */ int lsize; /* logarithmic linear size of grid */ int lsize2; /* logarithmic size of grid */ int size; /* linear size of grid */ s64Int size2; /* matrix order (=total # points in grid) */ int radius, /* stencil parameters */ stencil_size; s64Int row, col, first, last; /* dummies */ s64Int i, j; /* dummies */ int iterations; /* number of times the multiplication is done */ s64Int elm; /* sequence number of matrix nonzero */ s64Int nent; /* number of nonzero entries */ double sparsity; /* fraction of non-zeroes in matrix */ double sparse_time,/* timing parameters */ avgtime = 0.0, maxtime = 0.0, mintime = 366.0*24.0*3600.0; /* set the minimum time to a large value; one leap year should be enough */ double * RESTRICT matrix; /* sparse matrix entries */ double * RESTRICT vector; /* vector multiplying the sparse matrix */ double * RESTRICT result; /* computed matrix-vector product */ double temp; /* temporary scalar storing reduction data */ double vector_sum; /* checksum of result */ double reference_sum; /* checksum of "rhs" */ double epsilon = 1.e-8; /* error tolerance */ s64Int * RESTRICT colIndex; /* column indices of sparse matrix entries */ int nthread_input, /* thread parameters */ nthread; int num_error=0; /* flag that signals that requested and obtained numbers of threads are the same */ size_t vector_space, /* variables used to hold malloc sizes */ matrix_space, index_space; if (argc != 5) { printf("Usage: %s <# threads> <# iterations> <2log grid size> <stencil radius>\n",*argv); exit(EXIT_FAILURE); } /* Take number of threads to request from command line */ nthread_input = atoi(*++argv); if ((nthread_input < 1) || (nthread_input > MAX_THREADS)) { printf("ERROR: Invalid number of threads: %d\n", nthread_input); exit(EXIT_FAILURE); } omp_set_num_threads(nthread_input); iterations = atoi(*++argv); if (iterations < 1){ printf("ERROR: Iterations must be positive : %d \n", iterations); exit(EXIT_FAILURE); } lsize = atoi(*++argv); lsize2 = 2*lsize; size = 1<<lsize; if (lsize <0) { printf("ERROR: Log of grid size must be greater than or equal to zero: %d\n", (int) lsize); exit(EXIT_FAILURE); } /* compute number of points in the grid */ size2 = size*size; radius = atoi(*++argv); if (radius <0) { printf("ERROR: Stencil radius must be non-negative: %d\n", (int) size); exit(EXIT_FAILURE); } /* emit error if (periodic) stencil overlaps with itself */ if (size <2*radius+1) { printf("ERROR: Grid extent %d smaller than stencil diameter 2*%d+1= %d\n", size, radius, radius*2+1); exit(EXIT_FAILURE); } /* compute total size of star stencil in 2D */ stencil_size = 4*radius+1; /* sparsity follows from number of non-zeroes per row */ sparsity = (double)(4*radius+1)/(double)size2; /* compute total number of non-zeroes */ nent = size2*stencil_size; matrix_space = nent*sizeof(double); if (matrix_space/sizeof(double) != nent) { printf("ERROR: Cannot represent space for matrix: %ul\n", matrix_space); exit(EXIT_FAILURE); } matrix = (double *) malloc(matrix_space); if (!matrix) { printf("ERROR: Could not allocate space for sparse matrix: "FSTR64U"\n", nent); exit(EXIT_FAILURE); } vector_space = 2*size2*sizeof(double); if (vector_space/sizeof(double) != 2*size2) { printf("ERROR: Cannot represent space for vectors: %ul\n", vector_space); exit(EXIT_FAILURE); } vector = (double *) malloc(vector_space); if (!vector) { printf("ERROR: Could not allocate space for vectors: %d\n", (int)(2*size2)); exit(EXIT_FAILURE); } result = vector + size2; index_space = nent*sizeof(s64Int); if (index_space/sizeof(s64Int) != nent) { printf("ERROR: Cannot represent space for column indices: %ul\n", index_space); exit(EXIT_FAILURE); } colIndex = (s64Int *) malloc(index_space); if (!colIndex) { printf("ERROR: Could not allocate space for column indices: "FSTR64U"\n", nent*sizeof(s64Int)); exit(EXIT_FAILURE); } #pragma omp parallel private (row, col, elm, first, last, iter) { #pragma omp master { nthread = omp_get_num_threads(); printf("OpenMP Sparse matrix-vector multiplication\n"); if (nthread != nthread_input) { num_error = 1; printf("ERROR: number of requested threads %d does not equal ", nthread_input); printf("number of spawned threads %d\n", nthread); } else { printf("Number of threads = %16d\n",nthread_input); printf("Matrix order = "FSTR64U"\n", size2); printf("Stencil diameter = %16d\n", 2*radius+1); printf("Sparsity = %16.10lf\n", sparsity); #ifdef SCRAMBLE printf("Using scrambled indexing\n"); #else printf("Using canonical indexing\n"); #endif printf("Number of iterations = %16d\n", iterations); } } bail_out(num_error); /* initialize the input and result vectors */ #pragma omp for for (row=0; row<size2; row++) result[row] = vector[row] = 0.0; /* fill matrix with nonzeroes corresponding to difference stencil. We use the scrambling for reordering the points in the grid. */ #pragma omp for private (i,j,r) for (row=0; row<size2; row++) { j = row/size; i=row%size; elm = row*stencil_size; colIndex[elm] = REVERSE(LIN(i,j),lsize2); for (r=1; r<=radius; r++, elm+=4) { colIndex[elm+1] = REVERSE(LIN((i+r)%size,j),lsize2); colIndex[elm+2] = REVERSE(LIN((i-r+size)%size,j),lsize2); colIndex[elm+3] = REVERSE(LIN(i,(j+r)%size),lsize2); colIndex[elm+4] = REVERSE(LIN(i,(j-r+size)%size),lsize2); } // sort colIndex to make sure the compressed row accesses // vector elements in increasing order qsort(&(colIndex[row*stencil_size]), stencil_size, sizeof(s64Int), compare); for (elm=row*stencil_size; elm<(row+1)*stencil_size; elm++) matrix[elm] = 1.0/(double)(colIndex[elm]+1); } for (iter=0; iter<iterations; iter++) { #pragma omp barrier #pragma omp master { sparse_time = wtime(); } /* fill vector */ #pragma omp for for (row=0; row<size2; row++) vector[row] += (double) (row+1); /* do the actual matrix-vector multiplication */ #pragma omp for for (row=0; row<size2; row++) { first = stencil_size*row; last = first+stencil_size-1; #pragma simd reduction(+:temp) for (temp=0.0,col=first; col<=last; col++) { temp += matrix[col]*vector[colIndex[col]]; } result[row] += temp; } #pragma omp master { sparse_time = wtime() - sparse_time; if (iter>0 || iterations==1) { /* skip the first iteration */ avgtime = avgtime + sparse_time; mintime = MIN(mintime, sparse_time); maxtime = MAX(maxtime, sparse_time); } } } } /* end of parallel region */ /* verification test */ reference_sum = 0.5 * (double) nent * (double) iterations * (double) (iterations +1); vector_sum = 0.0; for (row=0; row<size2; row++) vector_sum += result[row]; if (ABS(vector_sum-reference_sum) > epsilon) { printf("ERROR: Vector sum = %lf, Reference vector sum = %lf\n", vector_sum, reference_sum); exit(EXIT_FAILURE); } else { printf("Solution validates\n"); #ifdef VERBOSE printf("Reference sum = %lf, vector sum = %lf\n", reference_sum, vector_sum); #endif } avgtime = avgtime/(double)(MAX(iterations-1,1)); printf("Rate (MFlops/s): %lf, Avg time (s): %lf, Min time (s): %lf", 1.0E-06 * (2.0*nent)/mintime, avgtime, mintime); printf(", Max time (s): %lf\n", maxtime); exit(EXIT_SUCCESS); } /* Code below reverses bits in unsigned integer stored in a 64-bit word. Bit reversal is with respect to the largest integer that is going to be processed for the particular run of the code, to make sure the reversal constitutes a true permutation. Hence, the final result needs to be shifted to the right. Example: if largest integer being processed is 0x000000ff = 255 = 0000...0011111111 (binary), then the unshifted reversal of 0x00000006 = 6 = 0000...0000000110 (binary) would be 011000000...0000 = 3*2^61, which is outside the range of the original sequence 0-255. Setting shift_in_bits to 2log(256) = 8, the final result is shifted the the right by 64-8=56 bits, so we get 000...0001100000 (binary) = 96, which is within the proper range */ u64Int reverse(register u64Int x, int shift_in_bits){ x = ((x >> 1) & 0x5555555555555555) | ((x << 1) & 0xaaaaaaaaaaaaaaaa); x = ((x >> 2) & 0x3333333333333333) | ((x << 2) & 0xcccccccccccccccc); x = ((x >> 4) & 0x0f0f0f0f0f0f0f0f) | ((x << 4) & 0xf0f0f0f0f0f0f0f0); x = ((x >> 8) & 0x00ff00ff00ff00ff) | ((x << 8) & 0xff00ff00ff00ff00); x = ((x >> 16) & 0x0000ffff0000ffff) | ((x << 16) & 0xffff0000ffff0000); x = ((x >> 32) & 0x00000000ffffffff) | ((x << 32) & 0xffffffff00000000); return (x>>((sizeof(u64Int)*BITS_IN_BYTE-shift_in_bits))); } int compare(const void *el1, const void *el2) { s64Int v1 = *(s64Int *)el1; s64Int v2 = *(s64Int *)el2; return (v1<v2) ? -1 : (v1>v2) ? 1 : 0; }
ab758071d8e021266f07f078cf339d98655cede0.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 norm2(struct dataobj *restrict n_vec, struct dataobj *restrict u_vec, const int time_M, const int time_m, struct profiler * timers, const int x_M, const int x_m, const int y_M, const int y_m, const int z_M, const int z_m) { float (*restrict n) __attribute__ ((aligned (64))) = (float (*)) n_vec->data; float (*restrict u)[u_vec->size[1]][u_vec->size[2]][u_vec->size[3]] __attribute__ ((aligned (64))) = (float (*)[u_vec->size[1]][u_vec->size[2]][u_vec->size[3]]) u_vec->data; #pragma omp target enter data map(to: u[0:u_vec->size[0]][0:u_vec->size[1]][0:u_vec->size[2]][0:u_vec->size[3]]) float sum = 0.0F; struct timeval start_section0, end_section0; gettimeofday(&start_section0, NULL); /* Begin section0 */ for (int time = time_m, t0 = (time)%(3); time <= time_M; time += 1, t0 = (time)%(3)) { #pragma omp target teams distribute parallel for collapse(3) reduction(+:sum) for (int x = x_m; x <= x_M; x += 1) { for (int y = y_m; y <= y_M; y += 1) { for (int z = z_m; z <= z_M; z += 1) { sum += fabs(pow(u[t0][x + 12][y + 12][z + 12], 2)); } } } } /* 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; n[0] = sum; #pragma omp target exit data map(delete: u[0:u_vec->size[0]][0:u_vec->size[1]][0:u_vec->size[2]][0:u_vec->size[3]]) return 0; }
ctl_fragment.c
/********************************************************************[libaroma]* * Copyright (C) 2011-2015 Ahmad Amarullah (http://amarullz.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *______________________________________________________________________________ * * Filename : ctl_fragment.c * Description : Fragment Control Source * * + This is part of libaroma, an embedded ui toolkit. * + 27/06/15 - Author(s): Ahmad Amarullah * */ #ifndef __libaroma_ctl_fragment_c__ #define __libaroma_ctl_fragment_c__ #include <aroma_internal.h> #include "../ui/ui_internal.h" /*************************** CONTROL HANDLERS *********************************/ dword _libaroma_ctl_fragment_msg(LIBAROMA_CONTROLP, LIBAROMA_MSGP); void _libaroma_ctl_fragment_draw(LIBAROMA_CONTROLP, LIBAROMA_CANVASP); void _libaroma_ctl_fragment_destroy(LIBAROMA_CONTROLP); byte _libaroma_ctl_fragment_thread(LIBAROMA_CONTROLP); static LIBAROMA_CONTROL_HANDLER _libaroma_ctl_fragment_handler={ message:_libaroma_ctl_fragment_msg, draw:_libaroma_ctl_fragment_draw, focus:NULL, destroy:_libaroma_ctl_fragment_destroy, thread:_libaroma_ctl_fragment_thread }; /**************************** WINDOW HANDLERS *********************************/ byte _libaroma_ctl_fragment_window_invalidate(LIBAROMA_WINDOWP win, byte sync); byte _libaroma_ctl_fragment_window_sync(LIBAROMA_WINDOWP win, int x,int y,int w,int h); byte _libaroma_ctl_fragment_window_updatebg(LIBAROMA_WINDOWP win); byte _libaroma_ctl_fragment_window_control_isvisible( LIBAROMA_WINDOWP win,LIBAROMA_CONTROLP cctl ); LIBAROMA_CANVASP _libaroma_ctl_fragment_window_control_draw_begin( LIBAROMA_WINDOWP win,LIBAROMA_CONTROLP cctl ); void _libaroma_ctl_fragment_window_postfree(LIBAROMA_WINDOWP win); static LIBAROMA_WINDOW_HANDLER _libaroma_ctl_fragment_win_handler={ prefree:NULL, postfree:_libaroma_ctl_fragment_window_postfree, updatebg:_libaroma_ctl_fragment_window_updatebg, invalidate:_libaroma_ctl_fragment_window_invalidate, sync:_libaroma_ctl_fragment_window_sync, message_hooker:NULL, control_draw_flush:NULL, control_erasebg:NULL, control_isvisible:_libaroma_ctl_fragment_window_control_isvisible, control_draw_begin:_libaroma_ctl_fragment_window_control_draw_begin }; /************************** FRAGMENT STRUCTURE ********************************/ /* * Structure : __LIBAROMA_CTL_FRAGMENT * Typedef : _LIBAROMA_CTL_FRAGMENT, * _LIBAROMA_CTL_FRAGMENTP * Descriptions: button control internal structure */ typedef struct __LIBAROMA_CTL_FRAGMENT _LIBAROMA_CTL_FRAGMENT; typedef struct __LIBAROMA_CTL_FRAGMENT * _LIBAROMA_CTL_FRAGMENTP; struct __LIBAROMA_CTL_FRAGMENT{ LIBAROMA_WINDOWP * wins; int win_n; int win_pos; int win_pos_out; byte win_cleanup; long transition_start; long transition_duration; float transition_state; byte transition_type; byte transision_delprev; LIBAROMA_TRANSITION_CB transition_cb; LIBAROMA_RECTP transition_rs; LIBAROMA_RECTP transition_re; byte redraw; byte on_direct_canvas; byte need_direct_canvas; LIBAROMA_MUTEX mutex; LIBAROMA_MUTEX dmutex; int win_next_del_id; }; typedef struct{ int id; byte active_state; LIBAROMA_CONTROLP ctl; } _LIBAROMA_CTL_FRAGMENT_WIN, * _LIBAROMA_CTL_FRAGMENT_WINP; /************************** INTERNAL FUNCTIONS ********************************/ /* * Function : _libaroma_ctl_fragment_get_win_index * Return Value: int * Descriptions: get window index */ inline int _libaroma_ctl_fragment_get_win_index( _LIBAROMA_CTL_FRAGMENTP me, LIBAROMA_WINDOWP win){ int i; for (i=0;i<me->win_n;i++){ if (me->wins[i]==win){ return i; } } return -1; } /* End of _libaroma_ctl_fragment_get_win_index */ /* FRAGMENT VALIDATOR MACRO */ #define _VALIDATE_FRAGMENT(error_ret) \ _LIBAROMA_CTL_FRAGMENT_WINP wind = (_LIBAROMA_CTL_FRAGMENT_WINP) \ win->client_data; \ if (!wind){ return error_ret; } \ LIBAROMA_CONTROLP ctl=wind->ctl; \ _LIBAROMA_CTL_CHECK( \ _libaroma_ctl_fragment_handler, _LIBAROMA_CTL_FRAGMENTP, error_ret); \ int win_index = _libaroma_ctl_fragment_get_win_index(me,win); \ if (win_index==-1){ return error_ret; } /* * Function : _libaroma_ctl_fragment_direct_canvas * Return Value: byte * Descriptions: set as direct canvas */ byte _libaroma_ctl_fragment_direct_canvas(LIBAROMA_CONTROLP ctl, byte state){ _LIBAROMA_CTL_CHECK( _libaroma_ctl_fragment_handler, _LIBAROMA_CTL_FRAGMENTP, 0 ); libaroma_mutex_lock(me->dmutex); if ((me->win_n<1)||(me->win_pos==-1)) { libaroma_mutex_unlock(me->dmutex); return 0; } LIBAROMA_WINDOWP win = me->wins[me->win_pos]; if (state){ me->on_direct_canvas=1; } else{ if (me->on_direct_canvas){ LIBAROMA_CANVASP ccv = libaroma_control_draw_begin(ctl); if (ccv) { libaroma_draw(win->dc,ccv,0,0,0); libaroma_canvas_free(ccv); } } me->on_direct_canvas=0; } libaroma_mutex_unlock(me->dmutex); return 1; } /* End of _libaroma_ctl_fragment_direct_canvas */ /* * Function : _libaroma_ctl_fragment_window_invalidate * Return Value: byte * Descriptions: window invalidate */ byte _libaroma_ctl_fragment_window_invalidate(LIBAROMA_WINDOWP win, byte sync){ _VALIDATE_FRAGMENT(0); if ((win->dc)&&(win->bg)){ libaroma_draw(win->dc,win->bg,0,0,0); int i; #ifdef LIBAROMA_CONFIG_OPENMP #pragma omp parallel for #endif for (i=0;i<win->childn;i++){ /* draw no sync */ libaroma_control_draw(win->childs[i], 0); } } if (sync){ return _libaroma_ctl_fragment_window_sync(win,0,0,win->w,win->h); } return 1; } /* End of _libaroma_ctl_fragment_window_invalidate */ void _libaroma_ctl_fragment_measure(LIBAROMA_WINDOWP win){ _VALIDATE_FRAGMENT(); libaroma_mutex_lock(me->dmutex); win->x = 0; win->y = 0; win->ax=ctl->x; win->ay=ctl->y; win->w = ctl->w; win->h = ctl->h; if (win->dc){ if ((win->dc->w!=win->w)||(win->dc->h!=win->h)){ libaroma_canvas_free(win->dc); win->dc=NULL; } } if (!win->dc){ win->dc = libaroma_canvas( win->w, win->h ); } libaroma_mutex_unlock(me->dmutex); _libaroma_ctl_fragment_window_updatebg(win); libaroma_mutex_lock(me->dmutex); int i; #ifdef LIBAROMA_CONFIG_OPENMP #pragma omp parallel for #endif for (i=0;i<win->childn;i++){ libaroma_window_measure(win,win->childs[i]); } libaroma_mutex_unlock(me->dmutex); } /* send activate event */ void _libaroma_ctl_fragment_activate_win(LIBAROMA_WINDOWP win, byte active){ _VALIDATE_FRAGMENT(); LIBAROMA_MSG msg; if (!active){ if (win->active){ wind->active_state=0; libaroma_wm_compose( &msg, LIBAROMA_MSG_WIN_INACTIVE, NULL, 0, 0 ); win->active=0; int i; #ifdef LIBAROMA_CONFIG_OPENMP #pragma omp parallel for #endif for (i=0;i<win->childn;i++){ if (win->childs[i]->handler->message){ win->childs[i]->handler->message(win->childs[i], &msg); } } } } else{ if (!win->active){ wind->active_state=1; if (!win->dc){ _libaroma_ctl_fragment_measure(win); } libaroma_wm_compose( &msg, LIBAROMA_MSG_WIN_ACTIVE, NULL, 0, 0 ); int i; win->active=1; #ifdef LIBAROMA_CONFIG_OPENMP #pragma omp parallel for #endif for (i=0;i<win->childn;i++){ if (win->childs[i]->handler->message){ win->childs[i]->handler->message(win->childs[i], &msg); } } } } } /* * Function : _libaroma_ctl_fragment_window_postfree * Return Value: void * Descriptions: post free window */ void _libaroma_ctl_fragment_window_postfree(LIBAROMA_WINDOWP win){ _VALIDATE_FRAGMENT(); if (wind){ free(wind); win->client_data=NULL; } } /* End of _libaroma_ctl_fragment_window_postfree */ /* * Function : _libaroma_ctl_fragment_window_sync * Return Value: byte * Descriptions: window sync */ byte _libaroma_ctl_fragment_window_sync(LIBAROMA_WINDOWP win, int x,int y,int w,int h){ _VALIDATE_FRAGMENT(0); if (!wind->active_state){ return 0; } me->redraw=1; return 1; } /* End of _libaroma_ctl_fragment_window_sync */ /* * Function : _libaroma_ctl_fragment_window_control_isvisible * Return Value: byte * Descriptions: check if control is visible */ byte _libaroma_ctl_fragment_window_control_isvisible( LIBAROMA_WINDOWP win,LIBAROMA_CONTROLP cctl ){ _VALIDATE_FRAGMENT(0); if (!wind->active_state){ return 0; } return 1; } /* End of _libaroma_ctl_fragment_window_control_isvisible */ /* * Function : _libaroma_ctl_fragment_window_control_draw_begin * Return Value: LIBAROMA_CANVASP * Descriptions: get canvas for child control */ LIBAROMA_CANVASP _libaroma_ctl_fragment_window_control_draw_begin( LIBAROMA_WINDOWP win,LIBAROMA_CONTROLP cctl ){ _VALIDATE_FRAGMENT(NULL); if (!wind->active_state){ return NULL; } LIBAROMA_CANVASP c=NULL; libaroma_mutex_lock(me->dmutex); if (me->on_direct_canvas){ int x = cctl->x; int y = cctl->y; int w = cctl->w; int h = cctl->h; LIBAROMA_CANVASP ccv = libaroma_control_draw_begin(ctl); if (ccv){ if ((ccv->w>x)&&(ccv->h>y)){ c = libaroma_canvas_area(ccv,x,y,w,h); } libaroma_canvas_free(ccv); } } else { if (win->dc!=NULL){ c = libaroma_canvas_area( win->dc, cctl->x, cctl->y, cctl->w, cctl->h ); } } libaroma_mutex_unlock(me->dmutex); return c; } /* End of _libaroma_ctl_fragment_window_control_draw_begin */ /* * Function : _libaroma_ctl_fragment_window_updatebg * Return Value: byte * Descriptions: window update background */ byte _libaroma_ctl_fragment_window_updatebg(LIBAROMA_WINDOWP win){ _VALIDATE_FRAGMENT(0); libaroma_mutex_lock(me->dmutex); int w = win->w; int h = win->h; if (win->bg!=NULL){ if ((win->bg->w==w)&&(win->bg->h==h)){ libaroma_mutex_unlock(me->dmutex); return 1; } libaroma_canvas_free(win->bg); } win->bg = libaroma_canvas(w,h); libaroma_canvas_setcolor( win->bg, libaroma_colorget(ctl,NULL)->window_bg, 0xff ); libaroma_mutex_unlock(me->dmutex); return 1; } /* End of _libaroma_ctl_fragment_window_sync */ /* * Function : _libaroma_ctl_fragment_draw * Return Value: void * Descriptions: draw callback */ void _libaroma_ctl_fragment_draw( LIBAROMA_CONTROLP ctl, LIBAROMA_CANVASP c){ _LIBAROMA_CTL_CHECK( _libaroma_ctl_fragment_handler, _LIBAROMA_CTL_FRAGMENTP, ); libaroma_mutex_lock(me->mutex); if ((me->win_n<1)||(me->win_pos==-1)) { libaroma_control_erasebg(ctl,c); me->redraw=0; libaroma_mutex_unlock(me->mutex); return; } if (!me->redraw){ int i; #ifdef LIBAROMA_CONFIG_OPENMP #pragma omp parallel for #endif for (i=0;i<me->win_n;i++){ _LIBAROMA_CTL_FRAGMENT_WINP wind = (_LIBAROMA_CTL_FRAGMENT_WINP) me->wins[i]->client_data; if (wind->active_state){ if (!me->wins[i]->active){ _libaroma_ctl_fragment_window_invalidate(me->wins[i],0); } } } } /* draw window canvas */ libaroma_mutex_lock(me->dmutex); if (!me->on_direct_canvas){ if (me->win_pos_out==-1){ LIBAROMA_WINDOWP awin = me->wins[me->win_pos]; if (awin->dc){ libaroma_draw(c,awin->dc,0,0,0); } else{ libaroma_control_erasebg(ctl,c); } } else{ LIBAROMA_WINDOWP awin = me->wins[me->win_pos]; LIBAROMA_WINDOWP owin = me->wins[me->win_pos_out]; if (me->transition_state==1){ if (awin->dc){ libaroma_draw(c,awin->dc,0,0,0); } else{ libaroma_control_erasebg(ctl,c); } me->transition_state=0; } else if ((me->transition_cb)&&(owin->dc)&&(awin->dc)){ me->transition_cb( c, owin->dc, awin->dc, me->transition_state, me->transition_rs, me->transition_re ); } else{ /* simple alpha transition */ if (owin->dc){ libaroma_draw(c,owin->dc,0,0,0); } else{ libaroma_control_erasebg(ctl,c); } if (awin->dc){ libaroma_draw_opacity(c,awin->dc,0,0,0,0xff*me->transition_state); } } } } libaroma_mutex_unlock(me->dmutex); /* need revert to direct canvas */ if (me->need_direct_canvas){ me->need_direct_canvas=0; _libaroma_ctl_fragment_direct_canvas(ctl, 1); } me->redraw=0; libaroma_mutex_unlock(me->mutex); } /* End of _libaroma_ctl_fragment_draw */ byte libaroma_ctl_fragment_del_window_nomutex( LIBAROMA_CONTROLP ctl, int id); /* * Function : _libaroma_ctl_fragment_thread * Return Value: byte * Descriptions: control thread callback */ byte _libaroma_ctl_fragment_thread(LIBAROMA_CONTROLP ctl) { /* internal check */ _LIBAROMA_CTL_CHECK( _libaroma_ctl_fragment_handler, _LIBAROMA_CTL_FRAGMENTP, 0 ); if ((me->win_n<1)||(me->win_pos==-1)) { return 0; } libaroma_mutex_lock(me->mutex); if (me->win_next_del_id!=-1){ libaroma_ctl_fragment_del_window_nomutex(ctl,me->win_next_del_id); me->win_next_del_id=-1; } byte is_draw = me->redraw; { int j; #ifdef LIBAROMA_CONFIG_OPENMP #pragma omp parallel for #endif for (j=0;j<me->win_n;j++){ LIBAROMA_WINDOWP win = me->wins[j]; _LIBAROMA_CTL_FRAGMENT_WINP wind = (_LIBAROMA_CTL_FRAGMENT_WINP) win->client_data; if (wind->active_state){ if (win->active){ int i; #ifdef LIBAROMA_CONFIG_OPENMP #pragma omp parallel for #endif for (i=0;i<win->childn;i++){ LIBAROMA_CONTROLP c=win->childs[i]; if (c->handler->thread!=NULL){ if (c->handler->thread(c)){ if (libaroma_control_draw(c,0)){ is_draw=1; } } } } } } } } { if ((me->transition_start!=0)&&(me->win_pos_out!=-1)){ float nowstate=libaroma_duration_state( me->transition_start, me->transition_duration ); if (nowstate!=me->transition_state){ if (nowstate>=1){ me->transition_start=0; me->transition_state=1; me->need_direct_canvas=1; if (me->transision_delprev){ _LIBAROMA_CTL_FRAGMENT_WINP windd= (_LIBAROMA_CTL_FRAGMENT_WINP) me->wins[me->win_pos_out]->client_data; me->win_next_del_id=windd->id; } _libaroma_ctl_fragment_activate_win( me->wins[me->win_pos_out], 0 ); me->win_pos_out=-1; me->transision_delprev=0; } else{ me->transition_state=nowstate; } is_draw=1; } } } libaroma_mutex_unlock(me->mutex); return is_draw; } /* End of _libaroma_ctl_fragment_thread */ /* * Function : _libaroma_ctl_fragment_destroy * Return Value: void * Descriptions: destroy callback */ void _libaroma_ctl_fragment_destroy( LIBAROMA_CONTROLP ctl){ /* internal check */ _LIBAROMA_CTL_CHECK( _libaroma_ctl_fragment_handler, _LIBAROMA_CTL_FRAGMENTP, ); libaroma_mutex_lock(me->mutex); if (me->win_n>0){ int i; #ifdef LIBAROMA_CONFIG_OPENMP #pragma omp parallel for #endif for (i=0;i<me->win_n;i++){ libaroma_window_free(me->wins[i]); } free(me->wins); me->wins=NULL; me->win_n=0; } libaroma_mutex_unlock(me->mutex); libaroma_mutex_free(me->mutex); libaroma_mutex_free(me->dmutex); free(me); } /* End of _libaroma_ctl_fragment_destroy */ /* * Function : _libaroma_ctl_fragment_msg * Return Value: byte * Descriptions: message callback */ dword _libaroma_ctl_fragment_msg( LIBAROMA_CONTROLP ctl, LIBAROMA_MSGP msg){ /* internal check */ _LIBAROMA_CTL_CHECK( _libaroma_ctl_fragment_handler, _LIBAROMA_CTL_FRAGMENTP, 0 ); dword ret = 0; switch(msg->msg){ case LIBAROMA_MSG_WIN_ACTIVE: case LIBAROMA_MSG_WIN_INACTIVE: case LIBAROMA_MSG_WIN_RESIZE: { libaroma_mutex_lock(me->mutex); int z; for (z=0;z<me->win_n;z++){ LIBAROMA_WINDOWP win = me->wins[z]; _LIBAROMA_CTL_FRAGMENT_WINP windn = (_LIBAROMA_CTL_FRAGMENT_WINP) win->client_data; if (!windn->active_state){ continue; } int i; #ifdef LIBAROMA_CONFIG_OPENMP #pragma omp parallel for #endif for (i=0;i<win->childn;i++){ if (win->childs[i]->handler->message){ win->childs[i]->handler->message(win->childs[i], msg); } } } libaroma_mutex_unlock(me->mutex); } break; case LIBAROMA_MSG_WIN_MEASURED: { int z; libaroma_mutex_lock(me->mutex); for (z=0;z<me->win_n;z++){ LIBAROMA_WINDOWP win = me->wins[z]; _LIBAROMA_CTL_FRAGMENT_WINP windn = (_LIBAROMA_CTL_FRAGMENT_WINP) win->client_data; if (windn->active_state){ _libaroma_ctl_fragment_measure(win); } } libaroma_mutex_unlock(me->mutex); } break; case LIBAROMA_MSG_TOUCH: { libaroma_mutex_lock(me->mutex); if ((me->win_n<1)||(me->win_pos==-1)) { libaroma_mutex_unlock(me->mutex); return 0; } LIBAROMA_WINDOWP win = me->wins[me->win_pos]; if (me->win_pos_out!=-1){ me->win_cleanup=1; libaroma_mutex_unlock(me->mutex); return 0; } if ((msg->state!=LIBAROMA_HID_EV_STATE_DOWN)&&(me->win_cleanup)){ libaroma_mutex_unlock(me->mutex); return 0; } me->win_cleanup=0; int x = msg->x; int y = msg->y; libaroma_window_calculate_pos(NULL,ctl,&x,&y); msg->x = x; msg->y = y; /* touch handler */ if (msg->state==LIBAROMA_HID_EV_STATE_DOWN){ win->touched = NULL; int i; for (i=0;i<win->childn;i++){ if (_libaroma_window_is_inside(win->childs[i],x,y)){ win->touched = win->childs[i]; break; } } if (win->touched!=NULL){ if (win->touched->handler->message){ ret=win->touched->handler->message(win->touched, msg); } } } else if (win->touched!=NULL){ if (win->touched->handler->message){ ret=win->touched->handler->message(win->touched, msg); } if (msg->state==LIBAROMA_HID_EV_STATE_UP){ win->touched=NULL; } } libaroma_mutex_unlock(me->mutex); } break; } return ret; } /* End of _libaroma_ctl_fragment_msg */ /* * Function : libaroma_ctl_fragment * Return Value: LIBAROMA_CONTROLP * Descriptions: create button control */ LIBAROMA_CONTROLP libaroma_ctl_fragment( LIBAROMA_WINDOWP win, word id, int x, int y, int w, int h ){ if (!win){ ALOGW("pager need direct window attach"); return NULL; } /* init internal data */ _LIBAROMA_CTL_FRAGMENTP me = (_LIBAROMA_CTL_FRAGMENTP) calloc(sizeof(_LIBAROMA_CTL_FRAGMENT),1); if (!me){ ALOGW("libaroma_ctl_fragment alloc pager memory failed"); return NULL; } me->win_pos_out=-1; me->win_pos=-1; me->wins = NULL; me->on_direct_canvas = 1; me->win_next_del_id=-1; /* init control */ LIBAROMA_CONTROLP ctl = libaroma_control_new( id, x, y, w, h, libaroma_dp(48),libaroma_dp(48), /* min size */ (voidp) me, &_libaroma_ctl_fragment_handler, NULL ); if (!ctl){ free(me); return NULL; } libaroma_mutex_init(me->mutex); libaroma_mutex_init(me->dmutex); return libaroma_window_attach(win,ctl); } /* End of libaroma_ctl_fragment */ /* * Function : libaroma_ctl_fragment_new_window * Return Value: LIBAROMA_WINDOWP * Descriptions: new window */ LIBAROMA_WINDOWP libaroma_ctl_fragment_new_window( LIBAROMA_CONTROLP ctl, int id){ _LIBAROMA_CTL_CHECK( _libaroma_ctl_fragment_handler, _LIBAROMA_CTL_FRAGMENTP, NULL ); if (!ctl->window){ ALOGW("libaroma_ctl_fragment_new_window fragment should append to " "window first"); return NULL; } libaroma_mutex_lock(me->mutex); int new_pos = me->win_n; if (me->win_n==0){ me->wins=(LIBAROMA_WINDOWP *) calloc(sizeof(LIBAROMA_WINDOWP),1); if (!me->wins){ libaroma_mutex_unlock(me->mutex); ALOGW("libaroma_ctl_fragment_new_window calloc window holder failed"); return NULL; } me->win_n=1; } else{ int i; for (i=0;i<me->win_n;i++){ _LIBAROMA_CTL_FRAGMENT_WINP windn = (_LIBAROMA_CTL_FRAGMENT_WINP) me->wins[i]->client_data; if (id==windn->id){ ALOGW("libaroma_ctl_fragment_new_window id already exist"); return NULL; } } LIBAROMA_WINDOWP * newins =(LIBAROMA_WINDOWP *) realloc( me->wins, sizeof(LIBAROMA_WINDOWP)*(me->win_n+1)); if (newins){ me->wins=newins; me->win_n++; } else{ libaroma_mutex_unlock(me->mutex); ALOGW("libaroma_ctl_fragment_new_window realloc window holder failed"); return NULL; } } me->wins[new_pos] = (LIBAROMA_WINDOWP) calloc(sizeof(LIBAROMA_WINDOW),1); if (!me->wins[new_pos]){ ALOGW("libaroma_ctl_fragment_new_window alloc window data failed"); if (me->win_n==1){ free(me->wins); me->win_n=0; me->wins=NULL; } else{ me->wins =(LIBAROMA_WINDOWP *) realloc(me->wins, sizeof(LIBAROMA_WINDOWP)*(me->win_n-1)); me->win_n--; } libaroma_mutex_unlock(me->mutex); return NULL; } LIBAROMA_WINDOWP nwin = me->wins[new_pos]; nwin->handler=&_libaroma_ctl_fragment_win_handler; nwin->parent=ctl->window; _LIBAROMA_CTL_FRAGMENT_WINP wind = (_LIBAROMA_CTL_FRAGMENT_WINP) calloc( sizeof(_LIBAROMA_CTL_FRAGMENT_WIN), 1); wind->id = id; wind->active_state = 0; wind->ctl = ctl; nwin->client_data = (voidp) wind; libaroma_mutex_unlock(me->mutex); return me->wins[new_pos]; } /* End of libaroma_ctl_fragment_new_window */ /* * Function : libaroma_ctl_fragment_get_window * Return Value: LIBAROMA_WINDOWP * Descriptions: get window */ LIBAROMA_WINDOWP libaroma_ctl_fragment_get_window( LIBAROMA_CONTROLP ctl, int id){ _LIBAROMA_CTL_CHECK( _libaroma_ctl_fragment_handler, _LIBAROMA_CTL_FRAGMENTP, NULL ); int i; libaroma_mutex_lock(me->mutex); for (i=0;i<me->win_n;i++){ _LIBAROMA_CTL_FRAGMENT_WINP windn = (_LIBAROMA_CTL_FRAGMENT_WINP) me->wins[i]->client_data; if (id==windn->id){ libaroma_mutex_unlock(me->mutex); return me->wins[i]; } } libaroma_mutex_unlock(me->mutex); return NULL; } /* * Function : libaroma_ctl_fragment_del_window * Return Value: byte * Descriptions: delete window */ byte libaroma_ctl_fragment_del_window_nomutex( LIBAROMA_CONTROLP ctl, int id){ _LIBAROMA_CTL_CHECK( _libaroma_ctl_fragment_handler, _LIBAROMA_CTL_FRAGMENTP, 0 ); /* wait for transition */ while(me->win_pos_out!=-1){ libaroma_sleep(16); } int i; int did = -1; LIBAROMA_WINDOWP win=NULL; for (i=0;i<me->win_n;i++){ _LIBAROMA_CTL_FRAGMENT_WINP windn = (_LIBAROMA_CTL_FRAGMENT_WINP) me->wins[i]->client_data; if (id==windn->id){ win=me->wins[i]; did=i; break; } } byte ret=0; if (me->win_pos==did){ ALOGW("libaroma_ctl_fragment_del_window cannot delete active window"); } else if (win){ int newn = me->win_n-1; if (newn<1){ if (me->wins){ free(me->wins); me->wins=NULL; } me->win_n=0; } else{ LIBAROMA_WINDOWP * newins = calloc(sizeof(LIBAROMA_WINDOWP),newn); int n=0; for (i=0;i<me->win_n;i++){ if (i!=did){ newins[n++]=me->wins[i]; } } free(me->wins); me->wins=newins; me->win_n=newn; } libaroma_window_free(win); } else{ ALOGW("libaroma_ctl_fragment_del_window window id not found"); } return ret; } byte libaroma_ctl_fragment_del_window( LIBAROMA_CONTROLP ctl, int id){ _LIBAROMA_CTL_CHECK( _libaroma_ctl_fragment_handler, _LIBAROMA_CTL_FRAGMENTP, 0 ); libaroma_mutex_lock(me->mutex); byte ret=libaroma_ctl_fragment_del_window_nomutex(ctl,id); libaroma_mutex_unlock(me->mutex); return ret; } /* * Function : libaroma_ctl_fragment_set_active_window * Return Value: byte * Descriptions: set active page */ byte libaroma_ctl_fragment_set_active_window( LIBAROMA_CONTROLP ctl, int id, byte anitype, long duration, byte remove_prev, LIBAROMA_TRANSITION_CB transcb, LIBAROMA_RECTP rect_start, LIBAROMA_RECTP rect_end ){ _LIBAROMA_CTL_CHECK( _libaroma_ctl_fragment_handler, _LIBAROMA_CTL_FRAGMENTP, 0 ); /* wait for transition */ while(me->win_pos_out!=-1){ libaroma_sleep(16); } byte ret=0; int i; int did = -1; libaroma_mutex_lock(me->mutex); LIBAROMA_WINDOWP win=NULL; for (i=0;i<me->win_n;i++){ _LIBAROMA_CTL_FRAGMENT_WINP windn = (_LIBAROMA_CTL_FRAGMENT_WINP) me->wins[i]->client_data; if (id==windn->id){ win=me->wins[i]; did=i; break; } } if (did!=-1){ if (me->win_pos!=did){ _libaroma_ctl_fragment_activate_win(win,1); libaroma_sleep(120); if (me->win_pos!=-1){ me->transition_start=libaroma_tick(); me->transition_duration=duration; me->transition_type=anitype; me->transition_state=0; me->transision_delprev=remove_prev; me->transition_cb=transcb; me->transition_rs=rect_start; me->transition_re=rect_end; _LIBAROMA_CTL_FRAGMENT_WINP windid = (_LIBAROMA_CTL_FRAGMENT_WINP) me->wins[did]->client_data; windid->active_state=2; me->win_pos_out=me->win_pos; me->win_pos=did; _libaroma_ctl_fragment_direct_canvas(ctl,0); } else{ me->win_pos_out=me->win_pos; me->win_pos=did; } ret=1; me->redraw=1; } else{ ALOGW("libaroma_ctl_fragment_set_active_window " "cannot reactivate active window"); } } else{ ALOGW("libaroma_ctl_fragment_set_active_window window id not found"); } libaroma_mutex_unlock(me->mutex); return ret; } #endif /* __libaroma_ctl_fragment_c__ */
tree-vectorizer.h
/* Vectorizer Copyright (C) 2003-2019 Free Software Foundation, Inc. Contributed by Dorit Naishlos <dorit@il.ibm.com> This file is part of GCC. GCC 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. GCC 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 GCC; see the file COPYING3. If not see <http://www.gnu.org/licenses/>. */ #ifndef GCC_TREE_VECTORIZER_H #define GCC_TREE_VECTORIZER_H typedef struct _stmt_vec_info *stmt_vec_info; #include "tree-data-ref.h" #include "tree-hash-traits.h" #include "target.h" /* Used for naming of new temporaries. */ enum vect_var_kind { vect_simple_var, vect_pointer_var, vect_scalar_var, vect_mask_var }; /* Defines type of operation. */ enum operation_type { unary_op = 1, binary_op, ternary_op }; /* Define type of available alignment support. */ enum dr_alignment_support { dr_unaligned_unsupported, dr_unaligned_supported, dr_explicit_realign, dr_explicit_realign_optimized, dr_aligned }; /* Define type of def-use cross-iteration cycle. */ enum vect_def_type { vect_uninitialized_def = 0, vect_constant_def = 1, vect_external_def, vect_internal_def, vect_induction_def, vect_reduction_def, vect_double_reduction_def, vect_nested_cycle, vect_unknown_def_type }; /* Define type of reduction. */ enum vect_reduction_type { TREE_CODE_REDUCTION, COND_REDUCTION, INTEGER_INDUC_COND_REDUCTION, CONST_COND_REDUCTION, /* Retain a scalar phi and use a FOLD_EXTRACT_LAST within the loop to implement: for (int i = 0; i < VF; ++i) res = cond[i] ? val[i] : res; */ EXTRACT_LAST_REDUCTION, /* Use a folding reduction within the loop to implement: for (int i = 0; i < VF; ++i) res = res OP val[i]; (with no reassocation). */ FOLD_LEFT_REDUCTION }; #define VECTORIZABLE_CYCLE_DEF(D) (((D) == vect_reduction_def) \ || ((D) == vect_double_reduction_def) \ || ((D) == vect_nested_cycle)) /* Structure to encapsulate information about a group of like instructions to be presented to the target cost model. */ struct stmt_info_for_cost { int count; enum vect_cost_for_stmt kind; enum vect_cost_model_location where; stmt_vec_info stmt_info; int misalign; }; typedef vec<stmt_info_for_cost> stmt_vector_for_cost; /* Maps base addresses to an innermost_loop_behavior that gives the maximum known alignment for that base. */ typedef hash_map<tree_operand_hash, innermost_loop_behavior *> vec_base_alignments; /************************************************************************ SLP ************************************************************************/ typedef struct _slp_tree *slp_tree; /* A computation tree of an SLP instance. Each node corresponds to a group of stmts to be packed in a SIMD stmt. */ struct _slp_tree { /* Nodes that contain def-stmts of this node statements operands. */ vec<slp_tree> children; /* A group of scalar stmts to be vectorized together. */ vec<stmt_vec_info> stmts; /* Load permutation relative to the stores, NULL if there is no permutation. */ vec<unsigned> load_permutation; /* Vectorized stmt/s. */ vec<stmt_vec_info> vec_stmts; /* Number of vector stmts that are created to replace the group of scalar stmts. It is calculated during the transformation phase as the number of scalar elements in one scalar iteration (GROUP_SIZE) multiplied by VF divided by vector size. */ unsigned int vec_stmts_size; /* Reference count in the SLP graph. */ unsigned int refcnt; /* Whether the scalar computations use two different operators. */ bool two_operators; /* The DEF type of this node. */ enum vect_def_type def_type; }; /* SLP instance is a sequence of stmts in a loop that can be packed into SIMD stmts. */ typedef struct _slp_instance { /* The root of SLP tree. */ slp_tree root; /* Size of groups of scalar stmts that will be replaced by SIMD stmt/s. */ unsigned int group_size; /* The unrolling factor required to vectorized this SLP instance. */ poly_uint64 unrolling_factor; /* The group of nodes that contain loads of this SLP instance. */ vec<slp_tree> loads; /* The SLP node containing the reduction PHIs. */ slp_tree reduc_phis; } *slp_instance; /* Access Functions. */ #define SLP_INSTANCE_TREE(S) (S)->root #define SLP_INSTANCE_GROUP_SIZE(S) (S)->group_size #define SLP_INSTANCE_UNROLLING_FACTOR(S) (S)->unrolling_factor #define SLP_INSTANCE_LOADS(S) (S)->loads #define SLP_TREE_CHILDREN(S) (S)->children #define SLP_TREE_SCALAR_STMTS(S) (S)->stmts #define SLP_TREE_VEC_STMTS(S) (S)->vec_stmts #define SLP_TREE_NUMBER_OF_VEC_STMTS(S) (S)->vec_stmts_size #define SLP_TREE_LOAD_PERMUTATION(S) (S)->load_permutation #define SLP_TREE_TWO_OPERATORS(S) (S)->two_operators #define SLP_TREE_DEF_TYPE(S) (S)->def_type /* Describes two objects whose addresses must be unequal for the vectorized loop to be valid. */ typedef std::pair<tree, tree> vec_object_pair; /* Records that vectorization is only possible if abs (EXPR) >= MIN_VALUE. UNSIGNED_P is true if we can assume that abs (EXPR) == EXPR. */ struct vec_lower_bound { vec_lower_bound () {} vec_lower_bound (tree e, bool u, poly_uint64 m) : expr (e), unsigned_p (u), min_value (m) {} tree expr; bool unsigned_p; poly_uint64 min_value; }; /* Vectorizer state shared between different analyses like vector sizes of the same CFG region. */ struct vec_info_shared { vec_info_shared(); ~vec_info_shared(); void save_datarefs(); void check_datarefs(); /* All data references. Freed by free_data_refs, so not an auto_vec. */ vec<data_reference_p> datarefs; vec<data_reference> datarefs_copy; /* The loop nest in which the data dependences are computed. */ auto_vec<loop_p> loop_nest; /* All data dependences. Freed by free_dependence_relations, so not an auto_vec. */ vec<ddr_p> ddrs; }; /* Vectorizer state common between loop and basic-block vectorization. */ struct vec_info { enum vec_kind { bb, loop }; vec_info (vec_kind, void *, vec_info_shared *); ~vec_info (); stmt_vec_info add_stmt (gimple *); stmt_vec_info lookup_stmt (gimple *); stmt_vec_info lookup_def (tree); stmt_vec_info lookup_single_use (tree); struct dr_vec_info *lookup_dr (data_reference *); void move_dr (stmt_vec_info, stmt_vec_info); void remove_stmt (stmt_vec_info); void replace_stmt (gimple_stmt_iterator *, stmt_vec_info, gimple *); /* The type of vectorization. */ vec_kind kind; /* Shared vectorizer state. */ vec_info_shared *shared; /* The mapping of GIMPLE UID to stmt_vec_info. */ vec<stmt_vec_info> stmt_vec_infos; /* All SLP instances. */ auto_vec<slp_instance> slp_instances; /* Maps base addresses to an innermost_loop_behavior that gives the maximum known alignment for that base. */ vec_base_alignments base_alignments; /* All interleaving chains of stores, represented by the first stmt in the chain. */ auto_vec<stmt_vec_info> grouped_stores; /* Cost data used by the target cost model. */ void *target_cost_data; private: stmt_vec_info new_stmt_vec_info (gimple *stmt); void set_vinfo_for_stmt (gimple *, stmt_vec_info); void free_stmt_vec_infos (); void free_stmt_vec_info (stmt_vec_info); }; struct _loop_vec_info; struct _bb_vec_info; template<> template<> inline bool is_a_helper <_loop_vec_info *>::test (vec_info *i) { return i->kind == vec_info::loop; } template<> template<> inline bool is_a_helper <_bb_vec_info *>::test (vec_info *i) { return i->kind == vec_info::bb; } /* In general, we can divide the vector statements in a vectorized loop into related groups ("rgroups") and say that for each rgroup there is some nS such that the rgroup operates on nS values from one scalar iteration followed by nS values from the next. That is, if VF is the vectorization factor of the loop, the rgroup operates on a sequence: (1,1) (1,2) ... (1,nS) (2,1) ... (2,nS) ... (VF,1) ... (VF,nS) where (i,j) represents a scalar value with index j in a scalar iteration with index i. [ We use the term "rgroup" to emphasise that this grouping isn't necessarily the same as the grouping of statements used elsewhere. For example, if we implement a group of scalar loads using gather loads, we'll use a separate gather load for each scalar load, and thus each gather load will belong to its own rgroup. ] In general this sequence will occupy nV vectors concatenated together. If these vectors have nL lanes each, the total number of scalar values N is given by: N = nS * VF = nV * nL None of nS, VF, nV and nL are required to be a power of 2. nS and nV are compile-time constants but VF and nL can be variable (if the target supports variable-length vectors). In classical vectorization, each iteration of the vector loop would handle exactly VF iterations of the original scalar loop. However, in a fully-masked loop, a particular iteration of the vector loop might handle fewer than VF iterations of the scalar loop. The vector lanes that correspond to iterations of the scalar loop are said to be "active" and the other lanes are said to be "inactive". In a fully-masked loop, many rgroups need to be masked to ensure that they have no effect for the inactive lanes. Each such rgroup needs a sequence of booleans in the same order as above, but with each (i,j) replaced by a boolean that indicates whether iteration i is active. This sequence occupies nV vector masks that again have nL lanes each. Thus the mask sequence as a whole consists of VF independent booleans that are each repeated nS times. We make the simplifying assumption that if a sequence of nV masks is suitable for one (nS,nL) pair, we can reuse it for (nS/2,nL/2) by VIEW_CONVERTing it. This holds for all current targets that support fully-masked loops. For example, suppose the scalar loop is: float *f; double *d; for (int i = 0; i < n; ++i) { f[i * 2 + 0] += 1.0f; f[i * 2 + 1] += 2.0f; d[i] += 3.0; } and suppose that vectors have 256 bits. The vectorized f accesses will belong to one rgroup and the vectorized d access to another: f rgroup: nS = 2, nV = 1, nL = 8 d rgroup: nS = 1, nV = 1, nL = 4 VF = 4 [ In this simple example the rgroups do correspond to the normal SLP grouping scheme. ] If only the first three lanes are active, the masks we need are: f rgroup: 1 1 | 1 1 | 1 1 | 0 0 d rgroup: 1 | 1 | 1 | 0 Here we can use a mask calculated for f's rgroup for d's, but not vice versa. Thus for each value of nV, it is enough to provide nV masks, with the mask being calculated based on the highest nL (or, equivalently, based on the highest nS) required by any rgroup with that nV. We therefore represent the entire collection of masks as a two-level table, with the first level being indexed by nV - 1 (since nV == 0 doesn't exist) and the second being indexed by the mask index 0 <= i < nV. */ /* The masks needed by rgroups with nV vectors, according to the description above. */ struct rgroup_masks { /* The largest nS for all rgroups that use these masks. */ unsigned int max_nscalars_per_iter; /* The type of mask to use, based on the highest nS recorded above. */ tree mask_type; /* A vector of nV masks, in iteration order. */ vec<tree> masks; }; typedef auto_vec<rgroup_masks> vec_loop_masks; /*-----------------------------------------------------------------*/ /* Info on vectorized loops. */ /*-----------------------------------------------------------------*/ typedef struct _loop_vec_info : public vec_info { _loop_vec_info (struct loop *, vec_info_shared *); ~_loop_vec_info (); /* The loop to which this info struct refers to. */ struct loop *loop; /* The loop basic blocks. */ basic_block *bbs; /* Number of latch executions. */ tree num_itersm1; /* Number of iterations. */ tree num_iters; /* Number of iterations of the original loop. */ tree num_iters_unchanged; /* Condition under which this loop is analyzed and versioned. */ tree num_iters_assumptions; /* Threshold of number of iterations below which vectorzation will not be performed. It is calculated from MIN_PROFITABLE_ITERS and PARAM_MIN_VECT_LOOP_BOUND. */ unsigned int th; /* When applying loop versioning, the vector form should only be used if the number of scalar iterations is >= this value, on top of all the other requirements. Ignored when loop versioning is not being used. */ poly_uint64 versioning_threshold; /* Unrolling factor */ poly_uint64 vectorization_factor; /* Maximum runtime vectorization factor, or MAX_VECTORIZATION_FACTOR if there is no particular limit. */ unsigned HOST_WIDE_INT max_vectorization_factor; /* The masks that a fully-masked loop should use to avoid operating on inactive scalars. */ vec_loop_masks masks; /* If we are using a loop mask to align memory addresses, this variable contains the number of vector elements that we should skip in the first iteration of the vector loop (i.e. the number of leading elements that should be false in the first mask). */ tree mask_skip_niters; /* Type of the variables to use in the WHILE_ULT call for fully-masked loops. */ tree mask_compare_type; /* For #pragma omp simd if (x) loops the x expression. If constant 0, the loop should not be vectorized, if constant non-zero, simd_if_cond shouldn't be set and loop vectorized normally, if SSA_NAME, the loop should be versioned on that condition, using scalar loop if the condition is false and vectorized loop otherwise. */ tree simd_if_cond; /* Unknown DRs according to which loop was peeled. */ struct dr_vec_info *unaligned_dr; /* peeling_for_alignment indicates whether peeling for alignment will take place, and what the peeling factor should be: peeling_for_alignment = X means: If X=0: Peeling for alignment will not be applied. If X>0: Peel first X iterations. If X=-1: Generate a runtime test to calculate the number of iterations to be peeled, using the dataref recorded in the field unaligned_dr. */ int peeling_for_alignment; /* The mask used to check the alignment of pointers or arrays. */ int ptr_mask; /* Data Dependence Relations defining address ranges that are candidates for a run-time aliasing check. */ auto_vec<ddr_p> may_alias_ddrs; /* Data Dependence Relations defining address ranges together with segment lengths from which the run-time aliasing check is built. */ auto_vec<dr_with_seg_len_pair_t> comp_alias_ddrs; /* Check that the addresses of each pair of objects is unequal. */ auto_vec<vec_object_pair> check_unequal_addrs; /* List of values that are required to be nonzero. This is used to check whether things like "x[i * n] += 1;" are safe and eventually gets added to the checks for lower bounds below. */ auto_vec<tree> check_nonzero; /* List of values that need to be checked for a minimum value. */ auto_vec<vec_lower_bound> lower_bounds; /* Statements in the loop that have data references that are candidates for a runtime (loop versioning) misalignment check. */ auto_vec<stmt_vec_info> may_misalign_stmts; /* Reduction cycles detected in the loop. Used in loop-aware SLP. */ auto_vec<stmt_vec_info> reductions; /* All reduction chains in the loop, represented by the first stmt in the chain. */ auto_vec<stmt_vec_info> reduction_chains; /* Cost vector for a single scalar iteration. */ auto_vec<stmt_info_for_cost> scalar_cost_vec; /* Map of IV base/step expressions to inserted name in the preheader. */ hash_map<tree_operand_hash, tree> *ivexpr_map; /* The unrolling factor needed to SLP the loop. In case of that pure SLP is applied to the loop, i.e., no unrolling is needed, this is 1. */ poly_uint64 slp_unrolling_factor; /* Cost of a single scalar iteration. */ int single_scalar_iteration_cost; /* Is the loop vectorizable? */ bool vectorizable; /* Records whether we still have the option of using a fully-masked loop. */ bool can_fully_mask_p; /* True if have decided to use a fully-masked loop. */ bool fully_masked_p; /* When we have grouped data accesses with gaps, we may introduce invalid memory accesses. We peel the last iteration of the loop to prevent this. */ bool peeling_for_gaps; /* When the number of iterations is not a multiple of the vector size we need to peel off iterations at the end to form an epilogue loop. */ bool peeling_for_niter; /* Reductions are canonicalized so that the last operand is the reduction operand. If this places a constant into RHS1, this decanonicalizes GIMPLE for other phases, so we must track when this has occurred and fix it up. */ bool operands_swapped; /* True if there are no loop carried data dependencies in the loop. If loop->safelen <= 1, then this is always true, either the loop didn't have any loop carried data dependencies, or the loop is being vectorized guarded with some runtime alias checks, or couldn't be vectorized at all, but then this field shouldn't be used. For loop->safelen >= 2, the user has asserted that there are no backward dependencies, but there still could be loop carried forward dependencies in such loops. This flag will be false if normal vectorizer data dependency analysis would fail or require versioning for alias, but because of loop->safelen >= 2 it has been vectorized even without versioning for alias. E.g. in: #pragma omp simd for (int i = 0; i < m; i++) a[i] = a[i + k] * c; (or #pragma simd or #pragma ivdep) we can vectorize this and it will DTRT even for k > 0 && k < m, but without safelen we would not vectorize this, so this field would be false. */ bool no_data_dependencies; /* Mark loops having masked stores. */ bool has_mask_store; /* If if-conversion versioned this loop before conversion, this is the loop version without if-conversion. */ struct loop *scalar_loop; /* For loops being epilogues of already vectorized loops this points to the original vectorized loop. Otherwise NULL. */ _loop_vec_info *orig_loop_info; } *loop_vec_info; /* Access Functions. */ #define LOOP_VINFO_LOOP(L) (L)->loop #define LOOP_VINFO_BBS(L) (L)->bbs #define LOOP_VINFO_NITERSM1(L) (L)->num_itersm1 #define LOOP_VINFO_NITERS(L) (L)->num_iters /* Since LOOP_VINFO_NITERS and LOOP_VINFO_NITERSM1 can change after prologue peeling retain total unchanged scalar loop iterations for cost model. */ #define LOOP_VINFO_NITERS_UNCHANGED(L) (L)->num_iters_unchanged #define LOOP_VINFO_NITERS_ASSUMPTIONS(L) (L)->num_iters_assumptions #define LOOP_VINFO_COST_MODEL_THRESHOLD(L) (L)->th #define LOOP_VINFO_VERSIONING_THRESHOLD(L) (L)->versioning_threshold #define LOOP_VINFO_VECTORIZABLE_P(L) (L)->vectorizable #define LOOP_VINFO_CAN_FULLY_MASK_P(L) (L)->can_fully_mask_p #define LOOP_VINFO_FULLY_MASKED_P(L) (L)->fully_masked_p #define LOOP_VINFO_VECT_FACTOR(L) (L)->vectorization_factor #define LOOP_VINFO_MAX_VECT_FACTOR(L) (L)->max_vectorization_factor #define LOOP_VINFO_MASKS(L) (L)->masks #define LOOP_VINFO_MASK_SKIP_NITERS(L) (L)->mask_skip_niters #define LOOP_VINFO_MASK_COMPARE_TYPE(L) (L)->mask_compare_type #define LOOP_VINFO_PTR_MASK(L) (L)->ptr_mask #define LOOP_VINFO_LOOP_NEST(L) (L)->shared->loop_nest #define LOOP_VINFO_DATAREFS(L) (L)->shared->datarefs #define LOOP_VINFO_DDRS(L) (L)->shared->ddrs #define LOOP_VINFO_INT_NITERS(L) (TREE_INT_CST_LOW ((L)->num_iters)) #define LOOP_VINFO_PEELING_FOR_ALIGNMENT(L) (L)->peeling_for_alignment #define LOOP_VINFO_UNALIGNED_DR(L) (L)->unaligned_dr #define LOOP_VINFO_MAY_MISALIGN_STMTS(L) (L)->may_misalign_stmts #define LOOP_VINFO_MAY_ALIAS_DDRS(L) (L)->may_alias_ddrs #define LOOP_VINFO_COMP_ALIAS_DDRS(L) (L)->comp_alias_ddrs #define LOOP_VINFO_CHECK_UNEQUAL_ADDRS(L) (L)->check_unequal_addrs #define LOOP_VINFO_CHECK_NONZERO(L) (L)->check_nonzero #define LOOP_VINFO_LOWER_BOUNDS(L) (L)->lower_bounds #define LOOP_VINFO_GROUPED_STORES(L) (L)->grouped_stores #define LOOP_VINFO_SLP_INSTANCES(L) (L)->slp_instances #define LOOP_VINFO_SLP_UNROLLING_FACTOR(L) (L)->slp_unrolling_factor #define LOOP_VINFO_REDUCTIONS(L) (L)->reductions #define LOOP_VINFO_REDUCTION_CHAINS(L) (L)->reduction_chains #define LOOP_VINFO_TARGET_COST_DATA(L) (L)->target_cost_data #define LOOP_VINFO_PEELING_FOR_GAPS(L) (L)->peeling_for_gaps #define LOOP_VINFO_OPERANDS_SWAPPED(L) (L)->operands_swapped #define LOOP_VINFO_PEELING_FOR_NITER(L) (L)->peeling_for_niter #define LOOP_VINFO_NO_DATA_DEPENDENCIES(L) (L)->no_data_dependencies #define LOOP_VINFO_SCALAR_LOOP(L) (L)->scalar_loop #define LOOP_VINFO_HAS_MASK_STORE(L) (L)->has_mask_store #define LOOP_VINFO_SCALAR_ITERATION_COST(L) (L)->scalar_cost_vec #define LOOP_VINFO_SINGLE_SCALAR_ITERATION_COST(L) (L)->single_scalar_iteration_cost #define LOOP_VINFO_ORIG_LOOP_INFO(L) (L)->orig_loop_info #define LOOP_VINFO_SIMD_IF_COND(L) (L)->simd_if_cond #define LOOP_REQUIRES_VERSIONING_FOR_ALIGNMENT(L) \ ((L)->may_misalign_stmts.length () > 0) #define LOOP_REQUIRES_VERSIONING_FOR_ALIAS(L) \ ((L)->comp_alias_ddrs.length () > 0 \ || (L)->check_unequal_addrs.length () > 0 \ || (L)->lower_bounds.length () > 0) #define LOOP_REQUIRES_VERSIONING_FOR_NITERS(L) \ (LOOP_VINFO_NITERS_ASSUMPTIONS (L)) #define LOOP_REQUIRES_VERSIONING_FOR_SIMD_IF_COND(L) \ (LOOP_VINFO_SIMD_IF_COND (L)) #define LOOP_REQUIRES_VERSIONING(L) \ (LOOP_REQUIRES_VERSIONING_FOR_ALIGNMENT (L) \ || LOOP_REQUIRES_VERSIONING_FOR_ALIAS (L) \ || LOOP_REQUIRES_VERSIONING_FOR_NITERS (L) \ || LOOP_REQUIRES_VERSIONING_FOR_SIMD_IF_COND (L)) #define LOOP_VINFO_NITERS_KNOWN_P(L) \ (tree_fits_shwi_p ((L)->num_iters) && tree_to_shwi ((L)->num_iters) > 0) #define LOOP_VINFO_EPILOGUE_P(L) \ (LOOP_VINFO_ORIG_LOOP_INFO (L) != NULL) #define LOOP_VINFO_ORIG_MAX_VECT_FACTOR(L) \ (LOOP_VINFO_MAX_VECT_FACTOR (LOOP_VINFO_ORIG_LOOP_INFO (L))) /* Wrapper for loop_vec_info, for tracking success/failure, where a non-NULL value signifies success, and a NULL value signifies failure, supporting propagating an opt_problem * describing the failure back up the call stack. */ typedef opt_pointer_wrapper <loop_vec_info> opt_loop_vec_info; static inline loop_vec_info loop_vec_info_for_loop (struct loop *loop) { return (loop_vec_info) loop->aux; } typedef struct _bb_vec_info : public vec_info { _bb_vec_info (gimple_stmt_iterator, gimple_stmt_iterator, vec_info_shared *); ~_bb_vec_info (); basic_block bb; gimple_stmt_iterator region_begin; gimple_stmt_iterator region_end; } *bb_vec_info; #define BB_VINFO_BB(B) (B)->bb #define BB_VINFO_GROUPED_STORES(B) (B)->grouped_stores #define BB_VINFO_SLP_INSTANCES(B) (B)->slp_instances #define BB_VINFO_DATAREFS(B) (B)->shared->datarefs #define BB_VINFO_DDRS(B) (B)->shared->ddrs #define BB_VINFO_TARGET_COST_DATA(B) (B)->target_cost_data static inline bb_vec_info vec_info_for_bb (basic_block bb) { return (bb_vec_info) bb->aux; } /*-----------------------------------------------------------------*/ /* Info on vectorized defs. */ /*-----------------------------------------------------------------*/ enum stmt_vec_info_type { undef_vec_info_type = 0, load_vec_info_type, store_vec_info_type, shift_vec_info_type, op_vec_info_type, call_vec_info_type, call_simd_clone_vec_info_type, assignment_vec_info_type, condition_vec_info_type, comparison_vec_info_type, reduc_vec_info_type, induc_vec_info_type, type_promotion_vec_info_type, type_demotion_vec_info_type, type_conversion_vec_info_type, loop_exit_ctrl_vec_info_type }; /* Indicates whether/how a variable is used in the scope of loop/basic block. */ enum vect_relevant { vect_unused_in_scope = 0, /* The def is only used outside the loop. */ vect_used_only_live, /* The def is in the inner loop, and the use is in the outer loop, and the use is a reduction stmt. */ vect_used_in_outer_by_reduction, /* The def is in the inner loop, and the use is in the outer loop (and is not part of reduction). */ vect_used_in_outer, /* defs that feed computations that end up (only) in a reduction. These defs may be used by non-reduction stmts, but eventually, any computations/values that are affected by these defs are used to compute a reduction (i.e. don't get stored to memory, for example). We use this to identify computations that we can change the order in which they are computed. */ vect_used_by_reduction, vect_used_in_scope }; /* The type of vectorization that can be applied to the stmt: regular loop-based vectorization; pure SLP - the stmt is a part of SLP instances and does not have uses outside SLP instances; or hybrid SLP and loop-based - the stmt is a part of SLP instance and also must be loop-based vectorized, since it has uses outside SLP sequences. In the loop context the meanings of pure and hybrid SLP are slightly different. By saying that pure SLP is applied to the loop, we mean that we exploit only intra-iteration parallelism in the loop; i.e., the loop can be vectorized without doing any conceptual unrolling, cause we don't pack together stmts from different iterations, only within a single iteration. Loop hybrid SLP means that we exploit both intra-iteration and inter-iteration parallelism (e.g., number of elements in the vector is 4 and the slp-group-size is 2, in which case we don't have enough parallelism within an iteration, so we obtain the rest of the parallelism from subsequent iterations by unrolling the loop by 2). */ enum slp_vect_type { loop_vect = 0, pure_slp, hybrid }; /* Says whether a statement is a load, a store of a vectorized statement result, or a store of an invariant value. */ enum vec_load_store_type { VLS_LOAD, VLS_STORE, VLS_STORE_INVARIANT }; /* Describes how we're going to vectorize an individual load or store, or a group of loads or stores. */ enum vect_memory_access_type { /* An access to an invariant address. This is used only for loads. */ VMAT_INVARIANT, /* A simple contiguous access. */ VMAT_CONTIGUOUS, /* A contiguous access that goes down in memory rather than up, with no additional permutation. This is used only for stores of invariants. */ VMAT_CONTIGUOUS_DOWN, /* A simple contiguous access in which the elements need to be permuted after loading or before storing. Only used for loop vectorization; SLP uses separate permutes. */ VMAT_CONTIGUOUS_PERMUTE, /* A simple contiguous access in which the elements need to be reversed after loading or before storing. */ VMAT_CONTIGUOUS_REVERSE, /* An access that uses IFN_LOAD_LANES or IFN_STORE_LANES. */ VMAT_LOAD_STORE_LANES, /* An access in which each scalar element is loaded or stored individually. */ VMAT_ELEMENTWISE, /* A hybrid of VMAT_CONTIGUOUS and VMAT_ELEMENTWISE, used for grouped SLP accesses. Each unrolled iteration uses a contiguous load or store for the whole group, but the groups from separate iterations are combined in the same way as for VMAT_ELEMENTWISE. */ VMAT_STRIDED_SLP, /* The access uses gather loads or scatter stores. */ VMAT_GATHER_SCATTER }; struct dr_vec_info { /* The data reference itself. */ data_reference *dr; /* The statement that contains the data reference. */ stmt_vec_info stmt; /* The misalignment in bytes of the reference, or -1 if not known. */ int misalignment; /* The byte alignment that we'd ideally like the reference to have, and the value that misalignment is measured against. */ poly_uint64 target_alignment; /* If true the alignment of base_decl needs to be increased. */ bool base_misaligned; tree base_decl; }; typedef struct data_reference *dr_p; struct _stmt_vec_info { enum stmt_vec_info_type type; /* Indicates whether this stmts is part of a computation whose result is used outside the loop. */ bool live; /* Stmt is part of some pattern (computation idiom) */ bool in_pattern_p; /* True if the statement was created during pattern recognition as part of the replacement for RELATED_STMT. This implies that the statement isn't part of any basic block, although for convenience its gimple_bb is the same as for RELATED_STMT. */ bool pattern_stmt_p; /* Is this statement vectorizable or should it be skipped in (partial) vectorization. */ bool vectorizable; /* The stmt to which this info struct refers to. */ gimple *stmt; /* The vec_info with respect to which STMT is vectorized. */ vec_info *vinfo; /* The vector type to be used for the LHS of this statement. */ tree vectype; /* The vectorized version of the stmt. */ stmt_vec_info vectorized_stmt; /* The following is relevant only for stmts that contain a non-scalar data-ref (array/pointer/struct access). A GIMPLE stmt is expected to have at most one such data-ref. */ dr_vec_info dr_aux; /* Information about the data-ref relative to this loop nest (the loop that is being considered for vectorization). */ innermost_loop_behavior dr_wrt_vec_loop; /* For loop PHI nodes, the base and evolution part of it. This makes sure this information is still available in vect_update_ivs_after_vectorizer where we may not be able to re-analyze the PHI nodes evolution as peeling for the prologue loop can make it unanalyzable. The evolution part is still correct after peeling, but the base may have changed from the version here. */ tree loop_phi_evolution_base_unchanged; tree loop_phi_evolution_part; /* Used for various bookkeeping purposes, generally holding a pointer to some other stmt S that is in some way "related" to this stmt. Current use of this field is: If this stmt is part of a pattern (i.e. the field 'in_pattern_p' is true): S is the "pattern stmt" that represents (and replaces) the sequence of stmts that constitutes the pattern. Similarly, the related_stmt of the "pattern stmt" points back to this stmt (which is the last stmt in the original sequence of stmts that constitutes the pattern). */ stmt_vec_info related_stmt; /* Used to keep a sequence of def stmts of a pattern stmt if such exists. The sequence is attached to the original statement rather than the pattern statement. */ gimple_seq pattern_def_seq; /* List of datarefs that are known to have the same alignment as the dataref of this stmt. */ vec<dr_p> same_align_refs; /* Selected SIMD clone's function info. First vector element is SIMD clone's function decl, followed by a pair of trees (base + step) for linear arguments (pair of NULLs for other arguments). */ vec<tree> simd_clone_info; /* Classify the def of this stmt. */ enum vect_def_type def_type; /* Whether the stmt is SLPed, loop-based vectorized, or both. */ enum slp_vect_type slp_type; /* Interleaving and reduction chains info. */ /* First element in the group. */ stmt_vec_info first_element; /* Pointer to the next element in the group. */ stmt_vec_info next_element; /* The size of the group. */ unsigned int size; /* For stores, number of stores from this group seen. We vectorize the last one. */ unsigned int store_count; /* For loads only, the gap from the previous load. For consecutive loads, GAP is 1. */ unsigned int gap; /* The minimum negative dependence distance this stmt participates in or zero if none. */ unsigned int min_neg_dist; /* Not all stmts in the loop need to be vectorized. e.g, the increment of the loop induction variable and computation of array indexes. relevant indicates whether the stmt needs to be vectorized. */ enum vect_relevant relevant; /* For loads if this is a gather, for stores if this is a scatter. */ bool gather_scatter_p; /* True if this is an access with loop-invariant stride. */ bool strided_p; /* For both loads and stores. */ bool simd_lane_access_p; /* Classifies how the load or store is going to be implemented for loop vectorization. */ vect_memory_access_type memory_access_type; /* For reduction loops, this is the type of reduction. */ enum vect_reduction_type v_reduc_type; /* For CONST_COND_REDUCTION, record the reduc code. */ enum tree_code const_cond_reduc_code; /* On a reduction PHI the reduction type as detected by vect_force_simple_reduction. */ enum vect_reduction_type reduc_type; /* On a reduction PHI the def returned by vect_force_simple_reduction. On the def returned by vect_force_simple_reduction the corresponding PHI. */ stmt_vec_info reduc_def; /* The number of scalar stmt references from active SLP instances. */ unsigned int num_slp_uses; /* If nonzero, the lhs of the statement could be truncated to this many bits without affecting any users of the result. */ unsigned int min_output_precision; /* If nonzero, all non-boolean input operands have the same precision, and they could each be truncated to this many bits without changing the result. */ unsigned int min_input_precision; /* If OPERATION_BITS is nonzero, the statement could be performed on an integer with the sign and number of bits given by OPERATION_SIGN and OPERATION_BITS without changing the result. */ unsigned int operation_precision; signop operation_sign; }; /* Information about a gather/scatter call. */ struct gather_scatter_info { /* The internal function to use for the gather/scatter operation, or IFN_LAST if a built-in function should be used instead. */ internal_fn ifn; /* The FUNCTION_DECL for the built-in gather/scatter function, or null if an internal function should be used instead. */ tree decl; /* The loop-invariant base value. */ tree base; /* The original scalar offset, which is a non-loop-invariant SSA_NAME. */ tree offset; /* Each offset element should be multiplied by this amount before being added to the base. */ int scale; /* The definition type for the vectorized offset. */ enum vect_def_type offset_dt; /* The type of the vectorized offset. */ tree offset_vectype; /* The type of the scalar elements after loading or before storing. */ tree element_type; /* The type of the scalar elements being loaded or stored. */ tree memory_type; }; /* Access Functions. */ #define STMT_VINFO_TYPE(S) (S)->type #define STMT_VINFO_STMT(S) (S)->stmt inline loop_vec_info STMT_VINFO_LOOP_VINFO (stmt_vec_info stmt_vinfo) { if (loop_vec_info loop_vinfo = dyn_cast <loop_vec_info> (stmt_vinfo->vinfo)) return loop_vinfo; return NULL; } inline bb_vec_info STMT_VINFO_BB_VINFO (stmt_vec_info stmt_vinfo) { if (bb_vec_info bb_vinfo = dyn_cast <bb_vec_info> (stmt_vinfo->vinfo)) return bb_vinfo; return NULL; } #define STMT_VINFO_RELEVANT(S) (S)->relevant #define STMT_VINFO_LIVE_P(S) (S)->live #define STMT_VINFO_VECTYPE(S) (S)->vectype #define STMT_VINFO_VEC_STMT(S) (S)->vectorized_stmt #define STMT_VINFO_VECTORIZABLE(S) (S)->vectorizable #define STMT_VINFO_DATA_REF(S) ((S)->dr_aux.dr + 0) #define STMT_VINFO_GATHER_SCATTER_P(S) (S)->gather_scatter_p #define STMT_VINFO_STRIDED_P(S) (S)->strided_p #define STMT_VINFO_MEMORY_ACCESS_TYPE(S) (S)->memory_access_type #define STMT_VINFO_SIMD_LANE_ACCESS_P(S) (S)->simd_lane_access_p #define STMT_VINFO_VEC_REDUCTION_TYPE(S) (S)->v_reduc_type #define STMT_VINFO_VEC_CONST_COND_REDUC_CODE(S) (S)->const_cond_reduc_code #define STMT_VINFO_DR_WRT_VEC_LOOP(S) (S)->dr_wrt_vec_loop #define STMT_VINFO_DR_BASE_ADDRESS(S) (S)->dr_wrt_vec_loop.base_address #define STMT_VINFO_DR_INIT(S) (S)->dr_wrt_vec_loop.init #define STMT_VINFO_DR_OFFSET(S) (S)->dr_wrt_vec_loop.offset #define STMT_VINFO_DR_STEP(S) (S)->dr_wrt_vec_loop.step #define STMT_VINFO_DR_BASE_ALIGNMENT(S) (S)->dr_wrt_vec_loop.base_alignment #define STMT_VINFO_DR_BASE_MISALIGNMENT(S) \ (S)->dr_wrt_vec_loop.base_misalignment #define STMT_VINFO_DR_OFFSET_ALIGNMENT(S) \ (S)->dr_wrt_vec_loop.offset_alignment #define STMT_VINFO_DR_STEP_ALIGNMENT(S) \ (S)->dr_wrt_vec_loop.step_alignment #define STMT_VINFO_DR_INFO(S) \ (gcc_checking_assert ((S)->dr_aux.stmt == (S)), &(S)->dr_aux) #define STMT_VINFO_IN_PATTERN_P(S) (S)->in_pattern_p #define STMT_VINFO_RELATED_STMT(S) (S)->related_stmt #define STMT_VINFO_PATTERN_DEF_SEQ(S) (S)->pattern_def_seq #define STMT_VINFO_SAME_ALIGN_REFS(S) (S)->same_align_refs #define STMT_VINFO_SIMD_CLONE_INFO(S) (S)->simd_clone_info #define STMT_VINFO_DEF_TYPE(S) (S)->def_type #define STMT_VINFO_GROUPED_ACCESS(S) \ ((S)->dr_aux.dr && DR_GROUP_FIRST_ELEMENT(S)) #define STMT_VINFO_LOOP_PHI_EVOLUTION_BASE_UNCHANGED(S) (S)->loop_phi_evolution_base_unchanged #define STMT_VINFO_LOOP_PHI_EVOLUTION_PART(S) (S)->loop_phi_evolution_part #define STMT_VINFO_MIN_NEG_DIST(S) (S)->min_neg_dist #define STMT_VINFO_NUM_SLP_USES(S) (S)->num_slp_uses #define STMT_VINFO_REDUC_TYPE(S) (S)->reduc_type #define STMT_VINFO_REDUC_DEF(S) (S)->reduc_def #define DR_GROUP_FIRST_ELEMENT(S) \ (gcc_checking_assert ((S)->dr_aux.dr), (S)->first_element) #define DR_GROUP_NEXT_ELEMENT(S) \ (gcc_checking_assert ((S)->dr_aux.dr), (S)->next_element) #define DR_GROUP_SIZE(S) \ (gcc_checking_assert ((S)->dr_aux.dr), (S)->size) #define DR_GROUP_STORE_COUNT(S) \ (gcc_checking_assert ((S)->dr_aux.dr), (S)->store_count) #define DR_GROUP_GAP(S) \ (gcc_checking_assert ((S)->dr_aux.dr), (S)->gap) #define REDUC_GROUP_FIRST_ELEMENT(S) \ (gcc_checking_assert (!(S)->dr_aux.dr), (S)->first_element) #define REDUC_GROUP_NEXT_ELEMENT(S) \ (gcc_checking_assert (!(S)->dr_aux.dr), (S)->next_element) #define REDUC_GROUP_SIZE(S) \ (gcc_checking_assert (!(S)->dr_aux.dr), (S)->size) #define STMT_VINFO_RELEVANT_P(S) ((S)->relevant != vect_unused_in_scope) #define HYBRID_SLP_STMT(S) ((S)->slp_type == hybrid) #define PURE_SLP_STMT(S) ((S)->slp_type == pure_slp) #define STMT_SLP_TYPE(S) (S)->slp_type #define VECT_MAX_COST 1000 /* The maximum number of intermediate steps required in multi-step type conversion. */ #define MAX_INTERM_CVT_STEPS 3 #define MAX_VECTORIZATION_FACTOR INT_MAX /* Nonzero if TYPE represents a (scalar) boolean type or type in the middle-end compatible with it (unsigned precision 1 integral types). Used to determine which types should be vectorized as VECTOR_BOOLEAN_TYPE_P. */ #define VECT_SCALAR_BOOLEAN_TYPE_P(TYPE) \ (TREE_CODE (TYPE) == BOOLEAN_TYPE \ || ((TREE_CODE (TYPE) == INTEGER_TYPE \ || TREE_CODE (TYPE) == ENUMERAL_TYPE) \ && TYPE_PRECISION (TYPE) == 1 \ && TYPE_UNSIGNED (TYPE))) static inline bool nested_in_vect_loop_p (struct loop *loop, stmt_vec_info stmt_info) { return (loop->inner && (loop->inner == (gimple_bb (stmt_info->stmt))->loop_father)); } /* Return TRUE if a statement represented by STMT_INFO is a part of a pattern. */ static inline bool is_pattern_stmt_p (stmt_vec_info stmt_info) { return stmt_info->pattern_stmt_p; } /* If STMT_INFO is a pattern statement, return the statement that it replaces, otherwise return STMT_INFO itself. */ inline stmt_vec_info vect_orig_stmt (stmt_vec_info stmt_info) { if (is_pattern_stmt_p (stmt_info)) return STMT_VINFO_RELATED_STMT (stmt_info); return stmt_info; } /* Return the later statement between STMT1_INFO and STMT2_INFO. */ static inline stmt_vec_info get_later_stmt (stmt_vec_info stmt1_info, stmt_vec_info stmt2_info) { if (gimple_uid (vect_orig_stmt (stmt1_info)->stmt) > gimple_uid (vect_orig_stmt (stmt2_info)->stmt)) return stmt1_info; else return stmt2_info; } /* If STMT_INFO has been replaced by a pattern statement, return the replacement statement, otherwise return STMT_INFO itself. */ inline stmt_vec_info vect_stmt_to_vectorize (stmt_vec_info stmt_info) { if (STMT_VINFO_IN_PATTERN_P (stmt_info)) return STMT_VINFO_RELATED_STMT (stmt_info); return stmt_info; } /* Return true if BB is a loop header. */ static inline bool is_loop_header_bb_p (basic_block bb) { if (bb == (bb->loop_father)->header) return true; gcc_checking_assert (EDGE_COUNT (bb->preds) == 1); return false; } /* Return pow2 (X). */ static inline int vect_pow2 (int x) { int i, res = 1; for (i = 0; i < x; i++) res *= 2; return res; } /* Alias targetm.vectorize.builtin_vectorization_cost. */ static inline int builtin_vectorization_cost (enum vect_cost_for_stmt type_of_cost, tree vectype, int misalign) { return targetm.vectorize.builtin_vectorization_cost (type_of_cost, vectype, misalign); } /* Get cost by calling cost target builtin. */ static inline int vect_get_stmt_cost (enum vect_cost_for_stmt type_of_cost) { return builtin_vectorization_cost (type_of_cost, NULL, 0); } /* Alias targetm.vectorize.init_cost. */ static inline void * init_cost (struct loop *loop_info) { return targetm.vectorize.init_cost (loop_info); } extern void dump_stmt_cost (FILE *, void *, int, enum vect_cost_for_stmt, stmt_vec_info, int, unsigned, enum vect_cost_model_location); /* Alias targetm.vectorize.add_stmt_cost. */ static inline unsigned add_stmt_cost (void *data, int count, enum vect_cost_for_stmt kind, stmt_vec_info stmt_info, int misalign, enum vect_cost_model_location where) { unsigned cost = targetm.vectorize.add_stmt_cost (data, count, kind, stmt_info, misalign, where); if (dump_file && (dump_flags & TDF_DETAILS)) dump_stmt_cost (dump_file, data, count, kind, stmt_info, misalign, cost, where); return cost; } /* Alias targetm.vectorize.finish_cost. */ static inline void finish_cost (void *data, unsigned *prologue_cost, unsigned *body_cost, unsigned *epilogue_cost) { targetm.vectorize.finish_cost (data, prologue_cost, body_cost, epilogue_cost); } /* Alias targetm.vectorize.destroy_cost_data. */ static inline void destroy_cost_data (void *data) { targetm.vectorize.destroy_cost_data (data); } inline void add_stmt_costs (void *data, stmt_vector_for_cost *cost_vec) { stmt_info_for_cost *cost; unsigned i; FOR_EACH_VEC_ELT (*cost_vec, i, cost) add_stmt_cost (data, cost->count, cost->kind, cost->stmt_info, cost->misalign, cost->where); } /*-----------------------------------------------------------------*/ /* Info on data references alignment. */ /*-----------------------------------------------------------------*/ #define DR_MISALIGNMENT_UNKNOWN (-1) #define DR_MISALIGNMENT_UNINITIALIZED (-2) inline void set_dr_misalignment (dr_vec_info *dr_info, int val) { dr_info->misalignment = val; } inline int dr_misalignment (dr_vec_info *dr_info) { int misalign = dr_info->misalignment; gcc_assert (misalign != DR_MISALIGNMENT_UNINITIALIZED); return misalign; } /* Reflects actual alignment of first access in the vectorized loop, taking into account peeling/versioning if applied. */ #define DR_MISALIGNMENT(DR) dr_misalignment (DR) #define SET_DR_MISALIGNMENT(DR, VAL) set_dr_misalignment (DR, VAL) /* Only defined once DR_MISALIGNMENT is defined. */ #define DR_TARGET_ALIGNMENT(DR) ((DR)->target_alignment) /* Return true if data access DR_INFO is aligned to its target alignment (which may be less than a full vector). */ static inline bool aligned_access_p (dr_vec_info *dr_info) { return (DR_MISALIGNMENT (dr_info) == 0); } /* Return TRUE if the alignment of the data access is known, and FALSE otherwise. */ static inline bool known_alignment_for_access_p (dr_vec_info *dr_info) { return (DR_MISALIGNMENT (dr_info) != DR_MISALIGNMENT_UNKNOWN); } /* Return the minimum alignment in bytes that the vectorized version of DR_INFO is guaranteed to have. */ static inline unsigned int vect_known_alignment_in_bytes (dr_vec_info *dr_info) { if (DR_MISALIGNMENT (dr_info) == DR_MISALIGNMENT_UNKNOWN) return TYPE_ALIGN_UNIT (TREE_TYPE (DR_REF (dr_info->dr))); if (DR_MISALIGNMENT (dr_info) == 0) return known_alignment (DR_TARGET_ALIGNMENT (dr_info)); return DR_MISALIGNMENT (dr_info) & -DR_MISALIGNMENT (dr_info); } /* Return the behavior of DR_INFO with respect to the vectorization context (which for outer loop vectorization might not be the behavior recorded in DR_INFO itself). */ static inline innermost_loop_behavior * vect_dr_behavior (dr_vec_info *dr_info) { stmt_vec_info stmt_info = dr_info->stmt; loop_vec_info loop_vinfo = STMT_VINFO_LOOP_VINFO (stmt_info); if (loop_vinfo == NULL || !nested_in_vect_loop_p (LOOP_VINFO_LOOP (loop_vinfo), stmt_info)) return &DR_INNERMOST (dr_info->dr); else return &STMT_VINFO_DR_WRT_VEC_LOOP (stmt_info); } /* Return true if the vect cost model is unlimited. */ static inline bool unlimited_cost_model (loop_p loop) { if (loop != NULL && loop->force_vectorize && flag_simd_cost_model != VECT_COST_MODEL_DEFAULT) return flag_simd_cost_model == VECT_COST_MODEL_UNLIMITED; return (flag_vect_cost_model == VECT_COST_MODEL_UNLIMITED); } /* Return true if the loop described by LOOP_VINFO is fully-masked and if the first iteration should use a partial mask in order to achieve alignment. */ static inline bool vect_use_loop_mask_for_alignment_p (loop_vec_info loop_vinfo) { return (LOOP_VINFO_FULLY_MASKED_P (loop_vinfo) && LOOP_VINFO_PEELING_FOR_ALIGNMENT (loop_vinfo)); } /* Return the number of vectors of type VECTYPE that are needed to get NUNITS elements. NUNITS should be based on the vectorization factor, so it is always a known multiple of the number of elements in VECTYPE. */ static inline unsigned int vect_get_num_vectors (poly_uint64 nunits, tree vectype) { return exact_div (nunits, TYPE_VECTOR_SUBPARTS (vectype)).to_constant (); } /* Return the number of copies needed for loop vectorization when a statement operates on vectors of type VECTYPE. This is the vectorization factor divided by the number of elements in VECTYPE and is always known at compile time. */ static inline unsigned int vect_get_num_copies (loop_vec_info loop_vinfo, tree vectype) { return vect_get_num_vectors (LOOP_VINFO_VECT_FACTOR (loop_vinfo), vectype); } /* Update maximum unit count *MAX_NUNITS so that it accounts for the number of units in vector type VECTYPE. *MAX_NUNITS can be 1 if we haven't yet recorded any vector types. */ static inline void vect_update_max_nunits (poly_uint64 *max_nunits, tree vectype) { /* All unit counts have the form current_vector_size * X for some rational X, so two unit sizes must have a common multiple. Everything is a multiple of the initial value of 1. */ poly_uint64 nunits = TYPE_VECTOR_SUBPARTS (vectype); *max_nunits = force_common_multiple (*max_nunits, nunits); } /* Return the vectorization factor that should be used for costing purposes while vectorizing the loop described by LOOP_VINFO. Pick a reasonable estimate if the vectorization factor isn't known at compile time. */ static inline unsigned int vect_vf_for_cost (loop_vec_info loop_vinfo) { return estimated_poly_value (LOOP_VINFO_VECT_FACTOR (loop_vinfo)); } /* Estimate the number of elements in VEC_TYPE for costing purposes. Pick a reasonable estimate if the exact number isn't known at compile time. */ static inline unsigned int vect_nunits_for_cost (tree vec_type) { return estimated_poly_value (TYPE_VECTOR_SUBPARTS (vec_type)); } /* Return the maximum possible vectorization factor for LOOP_VINFO. */ static inline unsigned HOST_WIDE_INT vect_max_vf (loop_vec_info loop_vinfo) { unsigned HOST_WIDE_INT vf; if (LOOP_VINFO_VECT_FACTOR (loop_vinfo).is_constant (&vf)) return vf; return MAX_VECTORIZATION_FACTOR; } /* Return the size of the value accessed by unvectorized data reference DR_INFO. This is only valid once STMT_VINFO_VECTYPE has been calculated for the associated gimple statement, since that guarantees that DR_INFO accesses either a scalar or a scalar equivalent. ("Scalar equivalent" here includes things like V1SI, which can be vectorized in the same way as a plain SI.) */ inline unsigned int vect_get_scalar_dr_size (dr_vec_info *dr_info) { return tree_to_uhwi (TYPE_SIZE_UNIT (TREE_TYPE (DR_REF (dr_info->dr)))); } /* Source location + hotness information. */ extern dump_user_location_t vect_location; /* A macro for calling: dump_begin_scope (MSG, vect_location); via an RAII object, thus printing "=== MSG ===\n" to the dumpfile etc, and then calling dump_end_scope (); once the object goes out of scope, thus capturing the nesting of the scopes. These scopes affect dump messages within them: dump messages at the top level implicitly default to MSG_PRIORITY_USER_FACING, whereas those in a nested scope implicitly default to MSG_PRIORITY_INTERNALS. */ #define DUMP_VECT_SCOPE(MSG) \ AUTO_DUMP_SCOPE (MSG, vect_location) /* A sentinel class for ensuring that the "vect_location" global gets reset at the end of a scope. The "vect_location" global is used during dumping and contains a location_t, which could contain references to a tree block via the ad-hoc data. This data is used for tracking inlining information, but it's not a GC root; it's simply assumed that such locations never get accessed if the blocks are optimized away. Hence we need to ensure that such locations are purged at the end of any operations using them (e.g. via this class). */ class auto_purge_vect_location { public: ~auto_purge_vect_location (); }; /*-----------------------------------------------------------------*/ /* Function prototypes. */ /*-----------------------------------------------------------------*/ /* Simple loop peeling and versioning utilities for vectorizer's purposes - in tree-vect-loop-manip.c. */ extern void vect_set_loop_condition (struct loop *, loop_vec_info, tree, tree, tree, bool); extern bool slpeel_can_duplicate_loop_p (const struct loop *, const_edge); struct loop *slpeel_tree_duplicate_loop_to_edge_cfg (struct loop *, struct loop *, edge); struct loop *vect_loop_versioning (loop_vec_info, unsigned int, bool, poly_uint64); extern struct loop *vect_do_peeling (loop_vec_info, tree, tree, tree *, tree *, tree *, int, bool, bool); extern void vect_prepare_for_masked_peels (loop_vec_info); extern dump_user_location_t find_loop_location (struct loop *); extern bool vect_can_advance_ivs_p (loop_vec_info); /* In tree-vect-stmts.c. */ extern poly_uint64 current_vector_size; extern tree get_vectype_for_scalar_type (tree); extern tree get_vectype_for_scalar_type_and_size (tree, poly_uint64); extern tree get_mask_type_for_scalar_type (tree); extern tree get_same_sized_vectype (tree, tree); extern bool vect_get_loop_mask_type (loop_vec_info); extern bool vect_is_simple_use (tree, vec_info *, enum vect_def_type *, stmt_vec_info * = NULL, gimple ** = NULL); extern bool vect_is_simple_use (tree, vec_info *, enum vect_def_type *, tree *, stmt_vec_info * = NULL, gimple ** = NULL); extern bool supportable_widening_operation (enum tree_code, stmt_vec_info, tree, tree, enum tree_code *, enum tree_code *, int *, vec<tree> *); extern bool supportable_narrowing_operation (enum tree_code, tree, tree, enum tree_code *, int *, vec<tree> *); extern unsigned record_stmt_cost (stmt_vector_for_cost *, int, enum vect_cost_for_stmt, stmt_vec_info, int, enum vect_cost_model_location); extern stmt_vec_info vect_finish_replace_stmt (stmt_vec_info, gimple *); extern stmt_vec_info vect_finish_stmt_generation (stmt_vec_info, gimple *, gimple_stmt_iterator *); extern opt_result vect_mark_stmts_to_be_vectorized (loop_vec_info); extern tree vect_get_store_rhs (stmt_vec_info); extern tree vect_get_vec_def_for_operand_1 (stmt_vec_info, enum vect_def_type); extern tree vect_get_vec_def_for_operand (tree, stmt_vec_info, tree = NULL); extern void vect_get_vec_defs (tree, tree, stmt_vec_info, vec<tree> *, vec<tree> *, slp_tree); extern void vect_get_vec_defs_for_stmt_copy (vec_info *, vec<tree> *, vec<tree> *); extern tree vect_init_vector (stmt_vec_info, tree, tree, gimple_stmt_iterator *); extern tree vect_get_vec_def_for_stmt_copy (vec_info *, tree); extern bool vect_transform_stmt (stmt_vec_info, gimple_stmt_iterator *, slp_tree, slp_instance); extern void vect_remove_stores (stmt_vec_info); extern opt_result vect_analyze_stmt (stmt_vec_info, bool *, slp_tree, slp_instance, stmt_vector_for_cost *); extern bool vectorizable_condition (stmt_vec_info, gimple_stmt_iterator *, stmt_vec_info *, bool, slp_tree, stmt_vector_for_cost *); extern bool vectorizable_shift (stmt_vec_info, gimple_stmt_iterator *, stmt_vec_info *, slp_tree, stmt_vector_for_cost *); extern void vect_get_load_cost (stmt_vec_info, int, bool, unsigned int *, unsigned int *, stmt_vector_for_cost *, stmt_vector_for_cost *, bool); extern void vect_get_store_cost (stmt_vec_info, int, unsigned int *, stmt_vector_for_cost *); extern bool vect_supportable_shift (enum tree_code, tree); extern tree vect_gen_perm_mask_any (tree, const vec_perm_indices &); extern tree vect_gen_perm_mask_checked (tree, const vec_perm_indices &); extern void optimize_mask_stores (struct loop*); extern gcall *vect_gen_while (tree, tree, tree); extern tree vect_gen_while_not (gimple_seq *, tree, tree, tree); extern opt_result vect_get_vector_types_for_stmt (stmt_vec_info, tree *, tree *); extern opt_tree vect_get_mask_type_for_stmt (stmt_vec_info); /* In tree-vect-data-refs.c. */ extern bool vect_can_force_dr_alignment_p (const_tree, poly_uint64); extern enum dr_alignment_support vect_supportable_dr_alignment (dr_vec_info *, bool); extern tree vect_get_smallest_scalar_type (stmt_vec_info, HOST_WIDE_INT *, HOST_WIDE_INT *); extern opt_result vect_analyze_data_ref_dependences (loop_vec_info, unsigned int *); extern bool vect_slp_analyze_instance_dependence (slp_instance); extern opt_result vect_enhance_data_refs_alignment (loop_vec_info); extern opt_result vect_analyze_data_refs_alignment (loop_vec_info); extern opt_result vect_verify_datarefs_alignment (loop_vec_info); extern bool vect_slp_analyze_and_verify_instance_alignment (slp_instance); extern opt_result vect_analyze_data_ref_accesses (vec_info *); extern opt_result vect_prune_runtime_alias_test_list (loop_vec_info); extern bool vect_gather_scatter_fn_p (bool, bool, tree, tree, unsigned int, signop, int, internal_fn *, tree *); extern bool vect_check_gather_scatter (stmt_vec_info, loop_vec_info, gather_scatter_info *); extern opt_result vect_find_stmt_data_reference (loop_p, gimple *, vec<data_reference_p> *); extern opt_result vect_analyze_data_refs (vec_info *, poly_uint64 *); extern void vect_record_base_alignments (vec_info *); extern tree vect_create_data_ref_ptr (stmt_vec_info, tree, struct loop *, tree, tree *, gimple_stmt_iterator *, gimple **, bool, tree = NULL_TREE, tree = NULL_TREE); extern tree bump_vector_ptr (tree, gimple *, gimple_stmt_iterator *, stmt_vec_info, tree); extern void vect_copy_ref_info (tree, tree); extern tree vect_create_destination_var (tree, tree); extern bool vect_grouped_store_supported (tree, unsigned HOST_WIDE_INT); extern bool vect_store_lanes_supported (tree, unsigned HOST_WIDE_INT, bool); extern bool vect_grouped_load_supported (tree, bool, unsigned HOST_WIDE_INT); extern bool vect_load_lanes_supported (tree, unsigned HOST_WIDE_INT, bool); extern void vect_permute_store_chain (vec<tree> ,unsigned int, stmt_vec_info, gimple_stmt_iterator *, vec<tree> *); extern tree vect_setup_realignment (stmt_vec_info, gimple_stmt_iterator *, tree *, enum dr_alignment_support, tree, struct loop **); extern void vect_transform_grouped_load (stmt_vec_info, vec<tree> , int, gimple_stmt_iterator *); extern void vect_record_grouped_load_vectors (stmt_vec_info, vec<tree>); extern tree vect_get_new_vect_var (tree, enum vect_var_kind, const char *); extern tree vect_get_new_ssa_name (tree, enum vect_var_kind, const char * = NULL); extern tree vect_create_addr_base_for_vector_ref (stmt_vec_info, gimple_seq *, tree, tree = NULL_TREE); /* In tree-vect-loop.c. */ /* FORNOW: Used in tree-parloops.c. */ extern stmt_vec_info vect_force_simple_reduction (loop_vec_info, stmt_vec_info, bool *, bool); /* Used in gimple-loop-interchange.c. */ extern bool check_reduction_path (dump_user_location_t, loop_p, gphi *, tree, enum tree_code); /* Drive for loop analysis stage. */ extern opt_loop_vec_info vect_analyze_loop (struct loop *, loop_vec_info, vec_info_shared *); extern tree vect_build_loop_niters (loop_vec_info, bool * = NULL); extern void vect_gen_vector_loop_niters (loop_vec_info, tree, tree *, tree *, bool); extern tree vect_halve_mask_nunits (tree); extern tree vect_double_mask_nunits (tree); extern void vect_record_loop_mask (loop_vec_info, vec_loop_masks *, unsigned int, tree); extern tree vect_get_loop_mask (gimple_stmt_iterator *, vec_loop_masks *, unsigned int, tree, unsigned int); /* Drive for loop transformation stage. */ extern struct loop *vect_transform_loop (loop_vec_info); extern opt_loop_vec_info vect_analyze_loop_form (struct loop *, vec_info_shared *); extern bool vectorizable_live_operation (stmt_vec_info, gimple_stmt_iterator *, slp_tree, int, stmt_vec_info *, stmt_vector_for_cost *); extern bool vectorizable_reduction (stmt_vec_info, gimple_stmt_iterator *, stmt_vec_info *, slp_tree, slp_instance, stmt_vector_for_cost *); extern bool vectorizable_induction (stmt_vec_info, gimple_stmt_iterator *, stmt_vec_info *, slp_tree, stmt_vector_for_cost *); extern tree get_initial_def_for_reduction (stmt_vec_info, tree, tree *); extern bool vect_worthwhile_without_simd_p (vec_info *, tree_code); extern int vect_get_known_peeling_cost (loop_vec_info, int, int *, stmt_vector_for_cost *, stmt_vector_for_cost *, stmt_vector_for_cost *); extern tree cse_and_gimplify_to_preheader (loop_vec_info, tree); /* In tree-vect-slp.c. */ extern void vect_free_slp_instance (slp_instance, bool); extern bool vect_transform_slp_perm_load (slp_tree, vec<tree> , gimple_stmt_iterator *, poly_uint64, slp_instance, bool, unsigned *); extern bool vect_slp_analyze_operations (vec_info *); extern void vect_schedule_slp (vec_info *); extern opt_result vect_analyze_slp (vec_info *, unsigned); extern bool vect_make_slp_decision (loop_vec_info); extern void vect_detect_hybrid_slp (loop_vec_info); extern void vect_get_slp_defs (vec<tree> , slp_tree, vec<vec<tree> > *); extern bool vect_slp_bb (basic_block); extern stmt_vec_info vect_find_last_scalar_stmt_in_slp (slp_tree); extern bool is_simple_and_all_uses_invariant (stmt_vec_info, loop_vec_info); extern bool can_duplicate_and_interleave_p (unsigned int, machine_mode, unsigned int * = NULL, tree * = NULL, tree * = NULL); extern void duplicate_and_interleave (gimple_seq *, tree, vec<tree>, unsigned int, vec<tree> &); extern int vect_get_place_in_interleaving_chain (stmt_vec_info, stmt_vec_info); /* In tree-vect-patterns.c. */ /* Pattern recognition functions. Additional pattern recognition functions can (and will) be added in the future. */ void vect_pattern_recog (vec_info *); /* In tree-vectorizer.c. */ unsigned vectorize_loops (void); void vect_free_loop_info_assumptions (struct loop *); #endif /* GCC_TREE_VECTORIZER_H */
GB_binop__eq_fc32.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__eq_fc32) // A.*B function (eWiseMult): GB (_AemultB_08__eq_fc32) // A.*B function (eWiseMult): GB (_AemultB_02__eq_fc32) // A.*B function (eWiseMult): GB (_AemultB_04__eq_fc32) // A.*B function (eWiseMult): GB (_AemultB_bitmap__eq_fc32) // A*D function (colscale): GB ((none)) // D*A function (rowscale): GB ((none)) // C+=B function (dense accum): GB (_Cdense_accumB__eq_fc32) // C+=b function (dense accum): GB (_Cdense_accumb__eq_fc32) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__eq_fc32) // C=scalar+B GB (_bind1st__eq_fc32) // C=scalar+B' GB (_bind1st_tran__eq_fc32) // C=A+scalar GB (_bind2nd__eq_fc32) // C=A'+scalar GB (_bind2nd_tran__eq_fc32) // C type: bool // A type: GxB_FC32_t // A pattern? 0 // B type: GxB_FC32_t // B pattern? 0 // BinaryOp: cij = GB_FC32_eq (aij, bij) #define GB_ATYPE \ GxB_FC32_t #define GB_BTYPE \ GxB_FC32_t #define GB_CTYPE \ bool // 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 \ 0 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 0 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA,A_iso) \ GxB_FC32_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) \ GxB_FC32_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) \ bool t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \ cij = (crealf (GBX (Ax, pA, A_iso)) != 0) || (cimagf (GBX (Ax, pA, A_iso)) != 0) // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \ cij = (crealf (GBX (Bx, pB, B_iso)) != 0) || (cimagf (GBX (Bx, pB, B_iso)) != 0) #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z,x,y,i,j) \ z = GB_FC32_eq (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_EQ || GxB_NO_FC32 || GxB_NO_EQ_FC32) //------------------------------------------------------------------------------ // 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__eq_fc32) ( 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__eq_fc32) ( 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 #if 0 { #include "GB_dense_subassign_23_template.c" } #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__eq_fc32) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if 0 { // get the scalar b for C += b, of type GxB_FC32_t GxB_FC32_t bwork = (*((GxB_FC32_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } #endif 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 bool *restrict Cx = (bool *) 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 bool *restrict Cx = (bool *) 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__eq_fc32) ( 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) ; GxB_FC32_t alpha_scalar ; GxB_FC32_t beta_scalar ; if (is_eWiseUnion) { alpha_scalar = (*((GxB_FC32_t *) alpha_scalar_in)) ; beta_scalar = (*((GxB_FC32_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__eq_fc32) ( 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__eq_fc32) ( 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__eq_fc32) ( 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__eq_fc32) ( 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__eq_fc32) ( 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 bool *Cx = (bool *) Cx_output ; GxB_FC32_t x = (*((GxB_FC32_t *) x_input)) ; GxB_FC32_t *Bx = (GxB_FC32_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 ; GxB_FC32_t bij = GBX (Bx, p, false) ; Cx [p] = GB_FC32_eq (x, bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__eq_fc32) ( 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 ; bool *Cx = (bool *) Cx_output ; GxB_FC32_t *Ax = (GxB_FC32_t *) Ax_input ; GxB_FC32_t y = (*((GxB_FC32_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; GxB_FC32_t aij = GBX (Ax, p, false) ; Cx [p] = GB_FC32_eq (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) \ { \ GxB_FC32_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = GB_FC32_eq (x, aij) ; \ } GrB_Info GB (_bind1st_tran__eq_fc32) ( 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 \ GxB_FC32_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else GxB_FC32_t x = (*((const GxB_FC32_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ GxB_FC32_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) \ { \ GxB_FC32_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = GB_FC32_eq (aij, y) ; \ } GrB_Info GB (_bind2nd_tran__eq_fc32) ( 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 GxB_FC32_t y = (*((const GxB_FC32_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
boundary_matrix.h
/* Copyright 2013 IST Austria Contributed by: Ulrich Bauer, Michael Kerber, Jan Reininghaus This file is part of PHAT. PHAT 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 3 of the License, or (at your option) any later version. PHAT 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 PHAT. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include "helpers/misc.h" #include "representations/bit_tree_pivot_column.h" // interface class for the main data structure -- implementations of the interface can be found in ./representations namespace phat { template< class Representation = bit_tree_pivot_column > class boundary_matrix { protected: Representation rep; // interface functions -- actual implementation and complexity depends on chosen @Representation template public: // get overall number of columns in boundary_matrix index get_num_cols() const { return rep._get_num_cols(); } // set overall number of columns in boundary_matrix void set_num_cols( index nr_of_columns ) { rep._set_num_cols( nr_of_columns ); } // get dimension of given index dimension get_dim( index idx ) const { return rep._get_dim( idx ); } // set dimension of given index void set_dim( index idx, dimension dim ) { rep._set_dim( idx, dim ); } // replaces content of @col with boundary of given index void get_col( index idx, column& col ) const { col.clear(); rep._get_col( idx, col ); } // set column @idx to the values contained in @col void set_col( index idx, const column& col ) { rep._set_col( idx, col ); } // true iff boundary of given column is empty bool is_empty( index idx ) const { return rep._is_empty( idx ); } // largest index of given column (new name for lowestOne()) -- NOT thread-safe index get_max_index( index idx ) const { return rep._get_max_index( idx ); } // removes maximal index from given column void remove_max( index idx ) { rep._remove_max( idx ); } // adds column @source to column @target' void add_to( index source, index target ) { rep._add_to( source, target ); } // clears given column void clear( index idx ) { rep._clear( idx ); } // finalizes given column void finalize( index idx ) { rep._finalize( idx ); } // synchronizes all internal data structures -- has to be called before and after any multithreaded access! void sync() { rep._sync(); } // info functions -- independent of chosen 'Representation' public: // maximal dimension dimension get_max_dim() const { dimension cur_max_dim = 0; for( index idx = 0; idx < get_num_cols(); idx++ ) cur_max_dim = get_dim( idx ) > cur_max_dim ? get_dim( idx ) : cur_max_dim; return cur_max_dim; } // number of nonzero rows for given column @idx index get_num_rows( index idx ) const { column cur_col; get_col( idx, cur_col ); return cur_col.size(); } // maximal number of nonzero rows of all columns index get_max_col_entries() const { index max_col_entries = -1; const index nr_of_columns = get_num_cols(); for( index idx = 0; idx < nr_of_columns; idx++ ) max_col_entries = get_num_rows( idx ) > max_col_entries ? get_num_rows( idx ) : max_col_entries; return max_col_entries; } // maximal number of nonzero cols of all rows index get_max_row_entries() const { size_t max_row_entries = 0; const index nr_of_columns = get_num_cols(); std::vector< std::vector< index > > transposed_matrix( nr_of_columns ); column temp_col; for( index cur_col = 0; cur_col < nr_of_columns; cur_col++ ) { get_col( cur_col, temp_col ); for( index idx = 0; idx < (index)temp_col.size(); idx++) transposed_matrix[ temp_col[ idx ] ].push_back( cur_col ); } for( index idx = 0; idx < nr_of_columns; idx++ ) max_row_entries = transposed_matrix[ idx ].size() > max_row_entries ? transposed_matrix[ idx ].size() : max_row_entries; return max_row_entries; } // overall number of entries in the matrix index get_num_entries() const { index number_of_nonzero_entries = 0; const index nr_of_columns = get_num_cols(); for( index idx = 0; idx < nr_of_columns; idx++ ) number_of_nonzero_entries += get_num_rows( idx ); return number_of_nonzero_entries; } // operators / constructors public: boundary_matrix() {}; template< class OtherRepresentation > boundary_matrix( const boundary_matrix< OtherRepresentation >& other ) { *this = other; } template< typename OtherRepresentation > bool operator==( const boundary_matrix< OtherRepresentation >& other_boundary_matrix ) const { const index number_of_columns = this->get_num_cols(); if( number_of_columns != other_boundary_matrix.get_num_cols() ) return false; column temp_col; column other_temp_col; for( index idx = 0; idx < number_of_columns; idx++ ) { this->get_col( idx, temp_col ); other_boundary_matrix.get_col( idx, other_temp_col ); if( temp_col != other_temp_col || this->get_dim( idx ) != other_boundary_matrix.get_dim( idx ) ) return false; } return true; } template< typename OtherRepresentation > bool operator!=( const boundary_matrix< OtherRepresentation >& other_boundary_matrix ) const { return !( *this == other_boundary_matrix ); } template< typename OtherRepresentation > boundary_matrix< Representation >& operator=( const boundary_matrix< OtherRepresentation >& other ) { const index nr_of_columns = other.get_num_cols(); this->set_num_cols( nr_of_columns ); column temp_col; for( index cur_col = 0; cur_col < nr_of_columns; cur_col++ ) { this->set_dim( cur_col, other.get_dim( cur_col ) ); other.get_col( cur_col, temp_col ); this->set_col( cur_col, temp_col ); } // by convention, always return *this return *this; } // I/O -- independent of chosen 'Representation' public: // initializes boundary_matrix from (vector<vector>, vector) pair -- untested template< typename index_type, typename dimemsion_type > void load_vector_vector( const std::vector< std::vector< index_type > >& input_matrix, const std::vector< dimemsion_type >& input_dims ) { const index nr_of_columns = (index)input_matrix.size(); this->set_num_cols( nr_of_columns ); column temp_col; #pragma omp parallel for private( temp_col ) for( index cur_col = 0; cur_col < nr_of_columns; cur_col++ ) { this->set_dim( cur_col, (dimension)input_dims[ cur_col ] ); index num_rows = input_matrix[ cur_col ].size(); temp_col.resize( num_rows ); for( index cur_row = 0; cur_row < num_rows; cur_row++ ) temp_col[ cur_row ] = (index)input_matrix[ cur_col ][ cur_row ]; this->set_col( cur_col, temp_col ); } } template< typename index_type, typename dimemsion_type > void save_vector_vector( std::vector< std::vector< index_type > >& output_matrix, std::vector< dimemsion_type >& output_dims ) { const index nr_of_columns = get_num_cols(); output_matrix.resize( nr_of_columns ); output_dims.resize( nr_of_columns ); column temp_col; for( index cur_col = 0; cur_col < nr_of_columns; cur_col++ ) { output_dims[ cur_col ] = (dimemsion_type)get_dim( cur_col ); get_col( cur_col, temp_col ); index num_rows = temp_col.size(); output_matrix[ cur_col ].clear(); output_matrix[ cur_col ].resize( num_rows ); for( index cur_row = 0; cur_row < num_rows; cur_row++ ) output_matrix[ cur_col ][ cur_row ] = (index_type)temp_col[ cur_row ]; } } // Loads the boundary_matrix from given file in ascii format // Format: each line represents a column, first number is dimension, other numbers are the content of the column. // Ignores empty lines and lines starting with a '#'. bool load_ascii( std::string filename ) { // first count number of columns: std::string cur_line; std::ifstream dummy( filename .c_str() ); if( dummy.fail() ) return false; index number_of_columns = 0; while( getline( dummy, cur_line ) ) { cur_line.erase(cur_line.find_last_not_of(" \t\n\r\f\v") + 1); if( cur_line != "" && cur_line[ 0 ] != '#' ) number_of_columns++; } this->set_num_cols( number_of_columns ); dummy.close(); std::ifstream input_stream( filename.c_str() ); if( input_stream.fail() ) return false; column temp_col; index cur_col = -1; while( getline( input_stream, cur_line ) ) { cur_line.erase(cur_line.find_last_not_of(" \t\n\r\f\v") + 1); if( cur_line != "" && cur_line[ 0 ] != '#' ) { cur_col++; std::stringstream ss( cur_line ); int64_t temp_dim; ss >> temp_dim; this->set_dim( cur_col, (dimension) temp_dim ); int64_t temp_index; temp_col.clear(); while( ss.good() ) { ss >> temp_index; temp_col.push_back( (index)temp_index ); } std::sort( temp_col.begin(), temp_col.end() ); this->set_col( cur_col, temp_col ); } } input_stream.close(); return true; } // Saves the boundary_matrix to given file in ascii format // Format: each line represents a column, first number is dimension, other numbers are the content of the column bool save_ascii( std::string filename ) { std::ofstream output_stream( filename.c_str() ); if( output_stream.fail() ) return false; const index nr_columns = this->get_num_cols(); column tempCol; for( index cur_col = 0; cur_col < nr_columns; cur_col++ ) { output_stream << (int64_t)this->get_dim( cur_col ); this->get_col( cur_col, tempCol ); for( index cur_row_idx = 0; cur_row_idx < (index)tempCol.size(); cur_row_idx++ ) output_stream << " " << tempCol[ cur_row_idx ]; output_stream << std::endl; } output_stream.close(); return true; } // Loads boundary_matrix from given file // Format: nr_columns % dim1 % N1 % row1 row2 % ...% rowN1 % dim2 % N2 % ... bool load_binary(const std::string &filename ) { std::ifstream input_stream( filename.c_str( ), std::ios_base::binary | std::ios_base::in ); if( input_stream.fail( ) ) return false; //TODO Note that if you read a file that isn't actually a data file, you may get //a number of columns that is bigger than the available memory, which leads to crashes //with deeply confusing error messages. Consider ways to prevent this. //Magic number in the file header? Check for more columns than bytes in the file? int64_t nr_columns; input_stream.read( (char*)&nr_columns, sizeof( int64_t ) ); this->set_num_cols( (index)nr_columns ); column temp_col; for( index cur_col = 0; cur_col < nr_columns; cur_col++ ) { int64_t cur_dim; input_stream.read( (char*)&cur_dim, sizeof( int64_t ) ); this->set_dim( cur_col, (dimension)cur_dim ); int64_t nr_rows; input_stream.read( (char*)&nr_rows, sizeof( int64_t ) ); temp_col.resize( ( std::size_t )nr_rows ); for( index idx = 0; idx < nr_rows; idx++ ) { int64_t cur_row; input_stream.read( (char*)&cur_row, sizeof( int64_t ) ); temp_col[ idx ] = (index)cur_row; } this->set_col( cur_col, temp_col ); } input_stream.close( ); return true; } // Saves the boundary_matrix to given file in binary format // Format: nr_columns % dim1 % N1 % row1 row2 % ...% rowN1 % dim2 % N2 % ... bool save_binary( std::string filename ) { std::ofstream output_stream( filename.c_str( ), std::ios_base::binary | std::ios_base::out ); if( output_stream.fail( ) ) return false; const int64_t nr_columns = this->get_num_cols( ); output_stream.write( (char*)&nr_columns, sizeof( int64_t ) ); column tempCol; for( index cur_col = 0; cur_col < nr_columns; cur_col++ ) { int64_t cur_dim = this->get_dim( cur_col ); output_stream.write( (char*)&cur_dim, sizeof( int64_t ) ); this->get_col( cur_col, tempCol ); int64_t cur_nr_rows = tempCol.size( ); output_stream.write( (char*)&cur_nr_rows, sizeof( int64_t ) ); for( index cur_row_idx = 0; cur_row_idx < (index)tempCol.size( ); cur_row_idx++ ) { int64_t cur_row = tempCol[ cur_row_idx ]; output_stream.write( (char*)&cur_row, sizeof( int64_t ) ); } } output_stream.close( ); return true; } }; }
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] = 16; tile_size[1] = 16; tile_size[2] = 4; tile_size[3] = 32; 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,8);t1++) { lbp=max(ceild(t1,2),ceild(16*t1-Nt+3,16)); ubp=min(floord(Nt+Nz-4,16),floord(8*t1+Nz+5,16)); #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(16*t2-Nz,4)),2*t1);t3<=min(min(min(floord(Nt+Ny-4,4),floord(8*t1+Ny+13,4)),floord(16*t2+Ny+12,4)),floord(16*t1-16*t2+Nz+Ny+11,4));t3++) { for (t4=max(max(max(0,ceild(t1-3,4)),ceild(16*t2-Nz-28,32)),ceild(4*t3-Ny-28,32));t4<=min(min(min(min(floord(4*t3+Nx,32),floord(Nt+Nx-4,32)),floord(8*t1+Nx+13,32)),floord(16*t2+Nx+12,32)),floord(16*t1-16*t2+Nz+Nx+11,32));t4++) { for (t5=max(max(max(max(max(0,8*t1),16*t1-16*t2+1),16*t2-Nz+2),4*t3-Ny+2),32*t4-Nx+2);t5<=min(min(min(min(min(Nt-2,8*t1+15),16*t2+14),4*t3+2),32*t4+30),16*t1-16*t2+Nz+13);t5++) { for (t6=max(max(16*t2,t5+1),-16*t1+16*t2+2*t5-15);t6<=min(min(16*t2+15,-16*t1+16*t2+2*t5),t5+Nz-2);t6++) { for (t7=max(4*t3,t5+1);t7<=min(4*t3+3,t5+Ny-2);t7++) { lbv=max(32*t4,t5+1); ubv=min(32*t4+31,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; }
nestedFunc.c
// OpenMP Nested Functions Example #include <omp.h> #include <stdio.h> #include <stdlib.h> int main( int argc, char** argv ) { omp_set_nested( 1 ); // Enable Nested Parallelism omp_set_dynamic( 0 ); // Disable Dynamic Threads int num = 0; // Thread Number int threads = 0; // Current Threads int max = 0; // Maximum Threads // Master Report In num = omp_get_thread_num( ); // Get Thread Number threads = omp_get_num_threads( ); // Get Current Number of Threads max = omp_get_max_threads( ); // Get Maximum Number of Threads printf( "Master : Thread %d of %d (%d Max)\n\n", num, threads, max ); // Outer Level Parallel Region - 2 Threads #pragma omp parallel num_threads( 8 ) { num = omp_get_thread_num( ); // Get Thread Number threads = omp_get_num_threads( ); // Get Current Number of Threads max = omp_get_max_threads( ); // Get Maximum Number of Threads printf( "Outer : Thread %d of %d (%d Max)\n\n", num, threads, max ); // Inner Level Parallel Region - 2 Threads Each #pragma omp parallel num_threads( 4 ) { num = omp_get_thread_num( ); // Get Thread Number threads = omp_get_num_threads( ); // Get Current Number of Threads max = omp_get_max_threads( ); // Get Maximum Number of Threads printf( "Inner : Thread %d of %d (%d Max)\n", num, threads, max ); } } return 0; } // End nestedFunc.c - EWG SDG
Fig_12.21_ompTwoTarg.c
#include <omp.h> #include <stdlib.h> #include <stdio.h> #define N 1024 int main() { float *a, *b, *c, *d; int i; a = (float*) malloc(N * sizeof(float)); b = (float*) malloc(N * sizeof(float)); c = (float*) malloc(N * sizeof(float)); d = (float*) malloc(N * sizeof(float)); // initialize a, b, c, and d (code not shown) #pragma omp target map(to:a[0:N],b[0:N]) map(tofrom:c[0:N]) #pragma omp teams distribute parallel for simd for (i = 0; i < N;i++) c[i] += a[i] * b[i]; #pragma omp target map(to:a[0:N],c[0:N]) map(tofrom:d[0:N]) #pragma omp teams distribute parallel for simd for (i = 0; i < N; i++) d[i] += a[i] + c[i]; }
vacation.c
/* ============================================================================= * * vacation.c * * ============================================================================= * * Copyright (C) Stanford University, 2006. All Rights Reserved. * Author: Chi Cao Minh * * ============================================================================= * * For the license of bayes/sort.h and bayes/sort.c, please see the header * of the files. * * ------------------------------------------------------------------------ * * For the license of kmeans, please see kmeans/LICENSE.kmeans * * ------------------------------------------------------------------------ * * For the license of ssca2, please see ssca2/COPYRIGHT * * ------------------------------------------------------------------------ * * For the license of lib/mt19937ar.c and lib/mt19937ar.h, please see the * header of the files. * * ------------------------------------------------------------------------ * * For the license of lib/rbtree.h and lib/rbtree.c, please see * lib/LEGALNOTICE.rbtree and lib/LICENSE.rbtree * * ------------------------------------------------------------------------ * * Unless otherwise noted, the following license applies to STAMP files: * * Copyright (c) 2007, Stanford University * 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 Stanford 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 STANFORD UNIVERSITY ``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 STANFORD UNIVERSITY BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * * ============================================================================= */ #include <assert.h> #include <stdlib.h> #include <stdio.h> #include <getopt.h> #include "client.h" #include "customer.h" #include "list.h" #include "manager.h" #include "map.h" #include "memory.h" #include "operation.h" #include "random.h" #include "reservation.h" #include "thread.h" #include "timer.h" #include "tm.h" #include "types.h" #include "utility.h" enum param_types { PARAM_CLIENTS = (unsigned char)'c', PARAM_NUMBER = (unsigned char)'n', PARAM_QUERIES = (unsigned char)'q', PARAM_RELATIONS = (unsigned char)'r', PARAM_TRANSACTIONS = (unsigned char)'t', PARAM_USER = (unsigned char)'u', PARAM_SMALL = (unsigned char)'s', PARAM_MEDIUM = (unsigned char)'m', PARAM_BIG = (unsigned char)'b', }; #define PARAM_DEFAULT_CLIENTS (1) #define PARAM_DEFAULT_NUMBER (10) #define PARAM_DEFAULT_QUERIES (90) #define PARAM_DEFAULT_RELATIONS (1 << 16) #define PARAM_DEFAULT_TRANSACTIONS (1 << 26) #define PARAM_DEFAULT_USER (80) #define PARAM_DEFAULT_SMALL (33) #define PARAM_DEFAULT_MEDIUM (34) #define PARAM_DEFAULT_BIG (33) double global_params[256]; /* 256 = ascii limit */ /* ============================================================================= * displayUsage * ============================================================================= */ static void displayUsage (const char* appName) { printf("Usage: %s [options]\n", appName); puts("\nOptions: (defaults)\n"); printf(" c <UINT> Number of [c]lients (%i)\n", PARAM_DEFAULT_CLIENTS); printf(" n <UINT> [n]umber of user queries/transaction (%i)\n", PARAM_DEFAULT_NUMBER); printf(" q <UINT> Percentage of relations [q]ueried (%i)\n", PARAM_DEFAULT_QUERIES); printf(" r <UINT> Number of possible [r]elations (%i)\n", PARAM_DEFAULT_RELATIONS); printf(" t <UINT> Number of [t]ransactions (%i)\n", PARAM_DEFAULT_TRANSACTIONS); printf(" u <UINT> Percentage of [u]ser transactions (%i)\n", PARAM_DEFAULT_USER); printf(" s <UINT> Percentage of small transactions (%i)\n", PARAM_DEFAULT_USER); printf(" m <UINT> Percentage of medium transactions (%i)\n", PARAM_DEFAULT_USER); printf(" b <UINT> Percentage of large transactions (%i)\n", PARAM_DEFAULT_USER); exit(1); } /* ============================================================================= * setDefaultParams * ============================================================================= */ static void setDefaultParams () { global_params[PARAM_CLIENTS] = PARAM_DEFAULT_CLIENTS; global_params[PARAM_NUMBER] = PARAM_DEFAULT_NUMBER; global_params[PARAM_QUERIES] = PARAM_DEFAULT_QUERIES; global_params[PARAM_RELATIONS] = PARAM_DEFAULT_RELATIONS; global_params[PARAM_TRANSACTIONS] = PARAM_DEFAULT_TRANSACTIONS; global_params[PARAM_USER] = PARAM_DEFAULT_USER; global_params[PARAM_SMALL] = PARAM_DEFAULT_SMALL; global_params[PARAM_MEDIUM] = PARAM_DEFAULT_MEDIUM; global_params[PARAM_BIG] = PARAM_DEFAULT_BIG; } /* ============================================================================= * parseArgs * ============================================================================= */ static void parseArgs (long argc, char* const argv[]) { long i; long opt; opterr = 0; setDefaultParams(); while ((opt = getopt(argc, argv, "s:m:b:c:n:q:r:t:u:")) != -1) { switch (opt) { case 'c': case 'n': case 'q': case 'r': case 't': case 'u': case 's': case 'm': case 'b': global_params[(unsigned char)opt] = atol(optarg); break; case '?': default: opterr++; break; } } for (i = optind; i < argc; i++) { fprintf(stderr, "Non-option argument: %s\n", argv[i]); opterr++; } if (opterr) { displayUsage(argv[0]); } } /* ============================================================================= * addCustomer * -- Wrapper function * ============================================================================= */ static bool_t addCustomer (manager_t* managerPtr, long id, long num, long price) { return manager_addCustomer_seq(managerPtr, id); } /* ============================================================================= * initializeManager * ============================================================================= */ static manager_t* initializeManager () { manager_t* managerPtr; long i; long numRelation; random_t* randomPtr; long* ids; bool_t (*manager_add[])(manager_t*, long, long, long) = { &manager_addCar_seq, &manager_addFlight_seq, &manager_addRoom_seq, &addCustomer }; long t; long numTable = sizeof(manager_add) / sizeof(manager_add[0]); printf("Initializing manager... "); fflush(stdout); randomPtr = random_alloc(); assert(randomPtr != NULL); managerPtr = manager_alloc(); assert(managerPtr != NULL); numRelation = (long)global_params[PARAM_RELATIONS]; ids = (long*)malloc(numRelation * sizeof(long)); for (i = 0; i < numRelation; i++) { ids[i] = i + 1; } for (t = 0; t < numTable; t++) { /* Shuffle ids */ for (i = 0; i < numRelation; i++) { long x = random_generate(randomPtr) % numRelation; long y = random_generate(randomPtr) % numRelation; long tmp = ids[x]; ids[x] = ids[y]; ids[y] = tmp; } /* Populate table */ for (i = 0; i < numRelation; i++) { bool_t status; long id = ids[i]; long num = ((random_generate(randomPtr) % 5) + 1) * 100; long price = ((random_generate(randomPtr) % 5) * 10) + 50; status = manager_add[t](managerPtr, id, num, price); assert(status); } } /* for t */ puts("done."); fflush(stdout); random_free(randomPtr); free(ids); return managerPtr; } /* ============================================================================= * initializeClients * ============================================================================= */ static client_t** initializeClients (manager_t* managerPtr) { random_t* randomPtr; client_t** clients; long i; long numClient = (long)global_params[PARAM_CLIENTS]; long numTransaction = (long)global_params[PARAM_TRANSACTIONS]; long numTransactionPerClient; long numQueryPerTransaction = (long)global_params[PARAM_NUMBER]; long numRelation = (long)global_params[PARAM_RELATIONS]; long percentQuery = (long)global_params[PARAM_QUERIES]; long queryRange; long percentUser = (long)global_params[PARAM_USER]; long percentSmall = (long)global_params[PARAM_SMALL]; long percentMedium = (long)global_params[PARAM_MEDIUM]; long percentBig = (long)global_params[PARAM_BIG]; printf("Initializing clients... "); fflush(stdout); randomPtr = random_alloc(); assert(randomPtr != NULL); clients = (client_t**)malloc(numClient * sizeof(client_t*)); assert(clients != NULL); numTransactionPerClient = (long)((double)numTransaction / (double)numClient + 0.5); queryRange = (long)((double)percentQuery / 100.0 * (double)numRelation + 0.5); for (i = 0; i < numClient; i++) { clients[i] = client_alloc(i, managerPtr, numTransactionPerClient, numQueryPerTransaction, queryRange, percentUser, percentSmall, percentMedium, percentBig); assert(clients[i] != NULL); } puts("done."); printf(" Transactions = %li\n", numTransaction); printf(" Clients = %li\n", numClient); printf(" Transactions/client = %li\n", numTransactionPerClient); printf(" Queries/transaction = %li\n", numQueryPerTransaction); printf(" Relations = %li\n", numRelation); printf(" Query percent = %li\n", percentQuery); printf(" Query range = %li\n", queryRange); printf(" Percent user = %li\n", percentUser); printf(" Percent small = %li\n", percentSmall); printf(" Percent medium = %li\n", percentMedium); printf(" Percent big = %li\n", percentBig); fflush(stdout); random_free(randomPtr); return clients; } /* ============================================================================= * checkTables * -- some simple checks (not comprehensive) * -- dependent on tasks generated for clients in initializeClients() * ============================================================================= */ void checkTables (manager_t* managerPtr) { long i; long numRelation = (long)global_params[PARAM_RELATIONS]; MAP_T* customerTablePtr = managerPtr->customerTablePtr; MAP_T* tables[] = { managerPtr->carTablePtr, managerPtr->flightTablePtr, managerPtr->roomTablePtr, }; long numTable = sizeof(tables) / sizeof(tables[0]); bool_t (*manager_add[])(manager_t*, long, long, long) = { &manager_addCar_seq, &manager_addFlight_seq, &manager_addRoom_seq }; long t; printf("Checking tables... "); fflush(stdout); /* Check for unique customer IDs */ long percentQuery = (long)global_params[PARAM_QUERIES]; long queryRange = (long)((double)percentQuery / 100.0 * (double)numRelation + 0.5); long maxCustomerId = queryRange + 1; for (i = 1; i <= maxCustomerId; i++) { if (MAP_FIND(customerTablePtr, i)) { if (MAP_REMOVE(customerTablePtr, i)) { assert(!MAP_FIND(customerTablePtr, i)); } } } /* Check reservation tables for consistency and unique ids */ for (t = 0; t < numTable; t++) { MAP_T* tablePtr = tables[t]; for (i = 1; i <= numRelation; i++) { if (MAP_FIND(tablePtr, i)) { assert(manager_add[t](managerPtr, i, 0, 0)); /* validate entry */ if (MAP_REMOVE(tablePtr, i)) { assert(!MAP_REMOVE(tablePtr, i)); } } } } puts("done."); fflush(stdout); } /* ============================================================================= * freeClients * ============================================================================= */ static void freeClients (client_t** clients) { long i; long numClient = (long)global_params[PARAM_CLIENTS]; for (i = 0; i < numClient; i++) { client_t* clientPtr = clients[i]; client_free(clientPtr); } } /* ============================================================================= * main * ============================================================================= */ MAIN(argc, argv) { manager_t* managerPtr; client_t** clients; TIMER_T start; TIMER_T stop; char exitmsg[1024]; GOTO_REAL(); load_syncchar_map("sync_char.map.vacation"); /* Initialization */ parseArgs(argc, (char** const)argv); sprintf(exitmsg, "END BENCHMARK %s-parallel-phase\n", argv[0]); SIM_GET_NUM_CPU(global_params[PARAM_CLIENTS]); long numThread = global_params[PARAM_CLIENTS]; P_MEMORY_STARTUP(numThread); managerPtr = initializeManager(); assert(managerPtr != NULL); clients = initializeClients(managerPtr); assert(clients != NULL); TM_STARTUP(numThread); thread_startup(numThread); /* Run transactions */ printf("Running clients... "); fflush(stdout); TIMER_READ(start); OSA_PRINT("entering parallel phase\n",0); START_INSTRUMENTATION(); GOTO_SIM(); #ifdef OTM #pragma omp parallel { client_run(clients); } #else thread_start(client_run, (void*)clients); #endif GOTO_REAL(); OSA_PRINT("exiting parallel phase\n",0); OSA_PRINT(exitmsg,0); STOP_INSTRUMENTATION(); TIMER_READ(stop); puts("done."); printf("Time = %0.6lf\n", TIMER_DIFF_SECONDS(start, stop)); fflush(stdout); checkTables(managerPtr); /* Clean up */ printf("Deallocating memory... "); fflush(stdout); freeClients(clients); /* * TODO: The contents of the manager's table need to be deallocated. */ manager_free(managerPtr); puts("done."); fflush(stdout); TM_SHUTDOWN(); P_MEMORY_SHUTDOWN(); GOTO_SIM(); thread_shutdown(); MAIN_RETURN(0); } /* ============================================================================= * * End of vacation.c * * ============================================================================= */
aix_smd5_fmt_plug.c
/* AIX smd5 cracker patch for JtR. Hacked together during April of 2013 by Dhiru * Kholia <dhiru at openwall.com>. * * This software is Copyright (c) 2013 Dhiru Kholia <dhiru at openwall.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. */ #if FMT_EXTERNS_H extern struct fmt_main fmt_smd5; #elif FMT_REGISTERS_H john_register_one(&fmt_smd5); #else #include <string.h> #include <assert.h> #include <errno.h> #ifdef _OPENMP static int omp_t = 1; #include <omp.h> #ifndef OMP_SCALE #define OMP_SCALE 16 // tuned on i7 w/HT #endif #endif #include "md5.h" #include "arch.h" #include "misc.h" #include "common.h" #include "formats.h" #include "params.h" #include "options.h" #include "memdbg.h" #define FORMAT_LABEL "aix-smd5" #define FORMAT_NAME "AIX LPA {smd5} (modified crypt-md5)" #define ALGORITHM_NAME "MD5 32/" ARCH_BITS_STR #define BENCHMARK_COMMENT "" #define BENCHMARK_LENGTH -1 #define PLAINTEXT_LENGTH 125 #define BINARY_SIZE 16 #define BINARY_ALIGN 4 #define SALT_SIZE sizeof(struct custom_salt) #define SALT_ALIGN sizeof(int) #define MIN_KEYS_PER_CRYPT 1 #define MAX_KEYS_PER_CRYPT 1 static struct fmt_tests smd5_tests[] = { /* following hashes are AIX non-standard smd5 hashes */ {"{smd5}s8/xSJ/v$uGam4GB8hOjTLQqvBfxJ2/", "password"}, {"{smd5}alRJaSLb$aKM3H1.h1ycXl5GEVDH1e1", "aixsucks?"}, {"{smd5}eLB0QWeS$Eg.YfWY8clZuCxF0xNrKg.", "0123456789ABCDE"}, /* following hashes are AIX standard smd5 hashes (with corrected tag) * lpa_options = std_hash=true */ {"$1$JVDbGx8K$T9h8HK4LZxeLPMTAxCfpc1", "password"}, {"$1$1Cu6fEvv$42kuaJ5fMEqyVStPuFG040", "0123456789ABCDE"}, {"$1$ql5x.xXL$vYVDhExol2xUBBpERRWcn1", "jtr>hashcat"}, {NULL} }; static char (*saved_key)[PLAINTEXT_LENGTH + 1]; static ARCH_WORD_32 (*crypt_out)[BINARY_SIZE / sizeof(ARCH_WORD_32)]; static struct custom_salt { int is_standard; unsigned char salt[16]; } *cur_salt; static void init(struct fmt_main *self) { #ifdef _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(self->params.max_keys_per_crypt, sizeof(*saved_key)); crypt_out = mem_calloc(self->params.max_keys_per_crypt, sizeof(*crypt_out)); } static void done(void) { MEM_FREE(crypt_out); MEM_FREE(saved_key); } static int valid(char *ciphertext, struct fmt_main *self) { char *p; char *ctcopy; char *keeptr; if (strncmp(ciphertext, "{smd5}", 6) != 0 && strncmp(ciphertext, "$1$", 3)) return 0; ctcopy = strdup(ciphertext); keeptr = ctcopy; if (!strncmp(ciphertext, "{smd5}", 6)) ctcopy += 6; else ctcopy += 3; if ((p = strtokm(ctcopy, "$")) == NULL) /* salt */ goto err; if (strlen(p) != 8) goto err; if ((p = strtokm(NULL, "$")) == NULL) /* hash */ goto err; MEM_FREE(keeptr); return 1; err: MEM_FREE(keeptr); return 0; } static void *get_salt(char *ciphertext) { char *ctcopy = strdup(ciphertext); char *keeptr = ctcopy; char *p; static struct custom_salt cs; memset(&cs, 0, sizeof(cs)); keeptr = ctcopy; if (!strncmp(ciphertext, "{smd5}", 6)) { ctcopy += 6; cs.is_standard = 0; } else { ctcopy += 3; cs.is_standard = 1; } p = strtokm(ctcopy, "$"); strncpy((char*)cs.salt, p, 9); p = strtokm(NULL, "$"); MEM_FREE(keeptr); return (void *)&cs; } #define TO_BINARY(b1, b2, b3) \ value = \ (ARCH_WORD_32)atoi64[ARCH_INDEX(pos[0])] | \ ((ARCH_WORD_32)atoi64[ARCH_INDEX(pos[1])] << 6) | \ ((ARCH_WORD_32)atoi64[ARCH_INDEX(pos[2])] << 12) | \ ((ARCH_WORD_32)atoi64[ARCH_INDEX(pos[3])] << 18); \ pos += 4; \ out.b[b1] = value >> 16; \ out.b[b2] = value >> 8; \ out.b[b3] = value; static void* get_binary(char *ciphertext) { static union { char b[16]; ARCH_WORD w; } out; char *pos; ARCH_WORD_32 value; pos = ciphertext + 3; if (!strncmp(ciphertext, "{smd5}", 6)) pos = ciphertext + 6; while (*pos++ != '$'); TO_BINARY(0, 6, 12); TO_BINARY(1, 7, 13); TO_BINARY(2, 8, 14); TO_BINARY(3, 9, 15); TO_BINARY(4, 10, 5); out.b[11] = (ARCH_WORD_32)atoi64[ARCH_INDEX(pos[0])] | ((ARCH_WORD_32)atoi64[ARCH_INDEX(pos[1])] << 6); return out.b; } static int get_hash_0(int index) { return crypt_out[index][0] & PH_MASK_0; } static int get_hash_1(int index) { return crypt_out[index][0] & PH_MASK_1; } static int get_hash_2(int index) { return crypt_out[index][0] & PH_MASK_2; } static int get_hash_3(int index) { return crypt_out[index][0] & PH_MASK_3; } static int get_hash_4(int index) { return crypt_out[index][0] & PH_MASK_4; } static int get_hash_5(int index) { return crypt_out[index][0] & PH_MASK_5; } static int get_hash_6(int index) { return crypt_out[index][0] & PH_MASK_6; } static void set_salt(void *salt) { cur_salt = (struct custom_salt *)salt; } /* * $Id: md5_crypt.c,v 1.1 2002-05-11 14:42:35 cpbotha Exp $ * * ---------------------------------------------------------------------------- * "THE BEER-WARE LICENSE" (Revision 42): * <phk@login.dknet.dk> wrote this file. As long as you retain this notice you * can do whatever you want with this stuff. If we meet some day, and you think * this stuff is worth it, you can buy me a beer in return. Poul-Henning Kamp * ---------------------------------------------------------------------------- * * Origin: Id: crypt.c,v 1.3 1995/05/30 05:42:22 rgrimes Exp * */ static void crypt_md5(char *pw, char *salt, int is_standard, char *passwd) { char *magic = "$1$"; /* This string is magic for this algorithm. Having * it this way, we can get get better later on */ char *sp, *ep; unsigned char final[16]; int sl, pl, i, j; MD5_CTX ctx, ctx1; /* Refine the Salt first */ sp = salt; /* If it starts with the magic string, then skip that */ if (!strncmp(sp, magic, strlen(magic))) sp += strlen(magic); /* It stops at the first '$', max 8 chars */ for (ep = sp; *ep && *ep != '$' && ep < (sp + 8); ep++) continue; /* get the length of the true salt */ sl = ep - sp; MD5_Init(&ctx); /* The password first, since that is what is most unknown */ MD5_Update(&ctx,(unsigned char *)pw,strlen(pw)); // The following license text applies to the "if" code block // License: belongs to the PUBLIC DOMAIN, donated to hashcat, credits MUST go to atom // (hashcat) and philsmd for their hard work. Thx // Disclaimer: WE PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER // EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // Furthermore, NO GUARANTEES THAT IT WORKS FOR YOU AND WORKS CORRECTLY if (is_standard) { /* Then our magic string */ MD5_Update(&ctx,(unsigned char *)magic,strlen(magic)); /* Then the raw salt */ MD5_Update(&ctx,(unsigned char *)sp,sl); } else { MD5_Update(&ctx,(unsigned char *)sp,sl); } /* Then just as many characters of the MD5_(pw,salt,pw) */ MD5_Init(&ctx1); MD5_Update(&ctx1,(unsigned char *)pw,strlen(pw)); MD5_Update(&ctx1,(unsigned char *)sp,sl); MD5_Update(&ctx1,(unsigned char *)pw,strlen(pw)); MD5_Final(final,&ctx1); for (pl = strlen(pw); pl > 0; pl -= 16) MD5_Update(&ctx,(unsigned char *)final,pl>16 ? 16 : pl); memset(final, 0, sizeof final); /* Then something really weird... */ for (j = 0, i = strlen(pw); i; i >>= 1) if (i & 1) MD5_Update(&ctx, (unsigned char *)final+j, 1); else MD5_Update(&ctx, (unsigned char *)pw+j, 1); /* Now make the output string */ strcpy(passwd, magic); strncat(passwd, sp, sl); strcat(passwd, "$"); MD5_Final(final,&ctx); /* * and now, just to make sure things don't run too fast * On a 60 Mhz Pentium this takes 34 msec, so you would * need 30 seconds to build a 1000 entry dictionary... */ for (i = 0; i < 1000; i++) { MD5_Init(&ctx1); if (i & 1) MD5_Update(&ctx1,(unsigned char *)pw,strlen(pw)); else MD5_Update(&ctx1,(unsigned char *)final,16); if (i % 3) MD5_Update(&ctx1,(unsigned char *)sp,sl); if (i % 7) MD5_Update(&ctx1,(unsigned char *)pw,strlen(pw)); if (i & 1) MD5_Update(&ctx1,(unsigned char *)final,16); else MD5_Update(&ctx1,(unsigned char *)pw,strlen(pw)); MD5_Final(final,&ctx1); } memcpy(passwd, final, 16); } static int crypt_all(int *pcount, struct db_salt *salt) { const int count = *pcount; int index = 0; #ifdef _OPENMP #pragma omp parallel for for (index = 0; index < count; index++) #endif { crypt_md5(saved_key[index], (char*)cur_salt->salt, cur_salt->is_standard, (char *)crypt_out[index]); } return count; } static int cmp_all(void *binary, int count) { int index = 0; #ifdef _OPENMP for (; index < count; index++) #endif if (!memcmp(binary, crypt_out[index], ARCH_SIZE)) return 1; return 0; } static int cmp_one(void *binary, int index) { return !memcmp(binary, crypt_out[index], BINARY_SIZE); } static int cmp_exact(char *source, int index) { return 1; } static void smd5_set_key(char *key, int index) { int saved_len = strlen(key); if (saved_len > PLAINTEXT_LENGTH) saved_len = PLAINTEXT_LENGTH; memcpy(saved_key[index], key, saved_len); saved_key[index][saved_len] = 0; } static char *get_key(int index) { return saved_key[index]; } static int salt_hash(void *salt) { return *(unsigned int*)salt & (SALT_HASH_SIZE - 1); } struct fmt_main fmt_smd5 = { { 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, { NULL }, smd5_tests }, { init, done, fmt_default_reset, fmt_default_prepare, valid, fmt_default_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 }, salt_hash, NULL, set_salt, smd5_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 */
common.c
#include "common.h" bool IS_EDGE(const int e){ return (e >= 0)? true : false; } static void BE_EDGE(int *e) { *e = ((*e) + 1) * (-1); } static void BE_NOEDGE(int *e) { *e = -1 * (*e) - 1; } void REVERSE(int *e) { if(IS_EDGE(*e)) BE_NOEDGE(e); else BE_EDGE(e); } void printb(const uint64_t v) { uint64_t mask = 0x1ULL << (sizeof(v) * CHAR_BIT - 1); int sum = 0; do{ putchar(mask & v ? '1' : '0'); sum++; if(sum%8==0) putchar(','); } while (mask >>= 1); } void create_adjacency(const int nodes, const int lines, const int max_degree, const int edge[lines][2], int adjacency[nodes][max_degree], int *degree) { for(int i=0;i<nodes;i++) degree[i] = 0; for(int i=0;i<lines;i++){ int n1 = edge[i][0]; int n2 = edge[i][1]; if(IS_EDGE(n1) != IS_EDGE(n2)) ERROR("uga %d %d\n", n1, n2); if(IS_EDGE(n1)){ adjacency[n1][degree[n1]++] = n2; adjacency[n2][degree[n2]++] = n1; } } // For debug for(int i=0;i<nodes;i++) if(degree[i] > max_degree) ERROR("uga (%d)\n", degree[i]); } bool has_duplicated_vertex(const int e00, const int e01, const int e10, const int e11) { return (e00 == e10 || e01 == e11 || e00 == e11 || e01 == e10); } bool has_duplicated_edge(const int e00, const int e01, const int e10, const int e11) { return (e00 == e10 && e01 == e11) || (e00 == e11 && e01 == e10); } int getRandom(const int max) { return (int)(random()*((double)max)/(1.0+RAND_MAX)); } int DISTANCE(const int v, const int w, const int height) { int w0 = WIDTH (v, height); int h0 = HEIGHT(v, height); int w1 = WIDTH (w, height); int h1 = HEIGHT(w, height); return abs(w0 - w1) + abs(h0 - h1); } int WIDTH(const int v, const int height) { return v/height; } int HEIGHT(const int v, const int height) { return v%height; } int ROTATE(const int v, const int height, const int width, const int groups, const int degree) { if(groups != 2 && groups != 4) ERROR("Invalid groups\n"); int w = WIDTH (v, height); int h = HEIGHT(v, height); if(groups == 2){ if(degree != 180) ERROR("Invalid degree\n"); // degree == 180 return (width-w-1)*height + (height-h-1); } else{ // groups == 4 if(degree != 90 && degree != 180 && degree != 270) ERROR("Invalid degree\n"); if(degree == 90) return h*height + (height-w-1); else if(degree == 180) return (height-w-1)*height + (height-h-1); else return (height-h-1)*height + w; // degree == 270 } } bool check_symmetric_edge(const int lines, const int edge[lines][2], const int height, const int width, const int based_height, const int groups) { assert(lines%groups == 0); int tmp_edge[2], based_lines = lines / groups; if(groups == 2){ for(int i=0;i<based_lines;i++){ if(!IS_EDGE(edge[i][0])) continue; for(int j=0;j<2;j++) tmp_edge[j] = ROTATE(edge[i][j], height, width, groups, 180); if(!has_duplicated_edge(edge[based_lines+i][0], edge[based_lines+i][1], tmp_edge[0], tmp_edge[1])) if(!( WIDTH (edge[based_lines+i][0], height) + WIDTH (edge[based_lines+i][1], height) == (width-1) && HEIGHT(edge[based_lines+i][0], height) + HEIGHT(edge[based_lines+i][1], height) == (height-1))){ printf("i=%d: %d,%d - %d,%d %d,%d - %d,%d\n", i, WIDTH(edge[based_lines+i][0], height), HEIGHT(edge[based_lines+i][0], height), WIDTH(edge[based_lines+i][1], height), HEIGHT(edge[based_lines+i][1], height), WIDTH(tmp_edge[0], height), HEIGHT(tmp_edge[0], height), WIDTH(tmp_edge[1], height), HEIGHT(tmp_edge[1], height)); return false; } } } else if(groups == 4){ // 90 degrees for(int i=0;i<based_lines;i++){ if(!IS_EDGE(edge[i][0])) continue; for(int j=0;j<2;j++) tmp_edge[j] = ROTATE(edge[i][j], height, width, groups, 90); if(!has_duplicated_edge(tmp_edge[0], tmp_edge[1], edge[based_lines+i][0], edge[based_lines+i][1])){ if(!( WIDTH (edge[based_lines+i][0], height) + WIDTH (edge[based_lines+i][1], height) == (width-1) && HEIGHT(edge[based_lines+i][0], height) + HEIGHT(edge[based_lines+i][1], height) == (height-1))){ printf("A i=%d: %d,%d-%d,%d %d,%d-%d,%d\n", i, WIDTH(edge[based_lines+i][0], height), HEIGHT(edge[based_lines+i][0], height), WIDTH(edge[based_lines+i][1], height), HEIGHT(edge[based_lines+i][1], height), WIDTH(tmp_edge[0], height), HEIGHT(tmp_edge[0], height), WIDTH(tmp_edge[1], height), HEIGHT(tmp_edge[1], height)); return false; } } // 180 degrees for(int j=0;j<2;j++) tmp_edge[j] = ROTATE(edge[i][j], height, width, groups, 180); if(!has_duplicated_edge(tmp_edge[0], tmp_edge[1], edge[based_lines*2+i][0], edge[based_lines*2+i][1])){ if(!( WIDTH (edge[based_lines*2+i][0], height) + WIDTH (edge[based_lines*2+i][1], height) == (width-1) && HEIGHT(edge[based_lines*2+i][0], height) + HEIGHT(edge[based_lines*2+i][1], height) == (height-1))){ printf("B i=%d: %d,%d-%d,%d %d,%d-%d,%d\n", i, WIDTH(edge[based_lines*2+i][0], height), HEIGHT(edge[based_lines*2+i][0], height), WIDTH(edge[based_lines*2+i][1], height), HEIGHT(edge[based_lines*2+i][1], height), WIDTH(tmp_edge[0], height), HEIGHT(tmp_edge[0], height), WIDTH(tmp_edge[1], height), HEIGHT(tmp_edge[1], height)); return false; } } // 270 degrees for(int j=0;j<2;j++) tmp_edge[j] = ROTATE(edge[i][j], height, width, groups, 270); if(!has_duplicated_edge(tmp_edge[0], tmp_edge[1], edge[based_lines*3+i][0], edge[based_lines*3+i][1])){ if(!( WIDTH (edge[based_lines*3+i][0], height) + WIDTH (edge[based_lines*3+i][1], height) == (width-1) && HEIGHT(edge[based_lines*3+i][0], height) + HEIGHT(edge[based_lines*3+i][1], height) == (height-1))){ printf("C i=%d: %d,%d-%d,%d %d,%d-%d,%d\n", i, WIDTH(edge[based_lines*3+i][0], height), HEIGHT(edge[based_lines*3+i][0], height), WIDTH(edge[based_lines*3+i][1], height), HEIGHT(edge[based_lines*3+i][1], height), WIDTH(tmp_edge[0], height), HEIGHT(tmp_edge[0], height), WIDTH(tmp_edge[1], height), HEIGHT(tmp_edge[1], height)); return false; } } } } return true; } void output_edge(const int lines, const int edge[lines*2], const int height) { for(int i=0;i<lines;i++) printf("%d,%d %d,%d\n", WIDTH(edge[i*2], height), HEIGHT(edge[i*2], height), WIDTH(edge[i*2+1], height), HEIGHT(edge[i*2+1], height)); } void copy_edge(int *restrict buf1, const int *restrict buf2, const int n) { #ifdef _OPENMP #pragma omp parallel for #endif for(int i=0;i<n;i++) buf1[i] = buf2[i]; } void swap(int *a, int *b) { int tmp = *a; *a = *b; *b = tmp; } bool check_loop(const int lines, const int edge[lines][2]) { timer_start(TIMER_CHECK); bool flag = true; #ifdef _OPENMP #pragma omp parallel for #endif for(int i=0;i<lines;i++) if(edge[i][0] == edge[i][1]) flag = false; timer_stop(TIMER_CHECK); if(flag == false){ for(int i=0;i<lines;i++) if(edge[i][0] == edge[i][1]){ printf("%d: %d %d <--\n", i, edge[i][0], edge[i][1]); } else{ printf("%d: %d %d\n", i, edge[i][0], edge[i][1]); } } return flag; } bool check_duplicate_all_edge(const int lines, const int edge[lines][2]) { timer_start(TIMER_CHECK); bool flag = true; #ifdef _OPENMP #pragma omp parallel for #endif for(int i=0;i<lines;i++) for(int j=i+1;j<lines;j++) if(has_duplicated_edge(edge[i][0], edge[i][1], edge[j][0], edge[j][1])){ printf("%d %d %d %d\n", edge[i][0], edge[i][1], edge[j][0], edge[j][1]); flag = false; } timer_stop(TIMER_CHECK); return flag; } bool check_duplicate_tmp_edge(const int g_opt, const int groups, int tmp_edge[groups*g_opt][2]) { timer_start(TIMER_CHECK); bool flag = true; for(int i=0;i<g_opt;i++){ int tmp[2] = {tmp_edge[i][0], tmp_edge[i][1]}; for(int j=g_opt;j<groups*g_opt;j++) if(has_duplicated_edge(tmp[0], tmp[1], tmp_edge[j][0], tmp_edge[j][1])) flag = false; } timer_stop(TIMER_CHECK); return flag; } bool check_duplicate_current_edge(const int lines, const int edge[lines][2], const int tmp_lines, const int tmp_edge[tmp_lines][2], const int tmp_line[2], const int groups, const int g_opt, const bool is_center) { timer_start(TIMER_CHECK); int based_lines = lines/groups; bool flag = true; if(g_opt == D_2G_OPT){ int tmp_line0 = tmp_line[0]%based_lines; int tmp_line1 = tmp_line[1]%based_lines; #ifdef _OPENMP #pragma omp parallel for #endif for(int i=rank;i<based_lines;i+=procs) if(i != tmp_line0 && i != tmp_line1) for(int j=0;j<tmp_lines;j++) if(has_duplicated_edge(edge[i][0], edge[i][1], tmp_edge[j][0], tmp_edge[j][1])) flag = false; } else if(g_opt == D_1G_OPT){ int tmp_line0 = tmp_line[0]%based_lines; if(! is_center){ #ifdef _OPENMP #pragma omp parallel for #endif for(int i=rank;i<based_lines;i+=procs) if(i != tmp_line0) for(int j=0;j<tmp_lines;j++) if(has_duplicated_edge(edge[i][0], edge[i][1], tmp_edge[j][0], tmp_edge[j][1])) flag = false; } else{ #ifdef _OPENMP #pragma omp parallel for #endif for(int i=rank;i<lines;i+=procs) if(i%based_lines != tmp_line0) for(int j=0;j<tmp_lines;j++) if(has_duplicated_edge(edge[i][0], edge[i][1], tmp_edge[j][0], tmp_edge[j][1])) flag = false; } } MPI_Allreduce(MPI_IN_PLACE, &flag, 1, MPI_C_BOOL, MPI_LAND, MPI_COMM_WORLD); timer_stop(TIMER_CHECK); return flag; } void create_rotate_hash(const int nodes, const int height, const int width, const int groups, int *rotate_hash) { int based_nodes = nodes / groups; if(groups == 1){ for(int i=0;i<based_nodes;i++) rotate_hash[i] = i; } else if(groups == 2){ int based_height = height / 2; for(int i=0;i<based_nodes;i++){ int j = (i/based_height) * height + (i%based_height); rotate_hash[j] = i; rotate_hash[ROTATE(j, height, width, groups, 180)] = i + based_nodes; } } else{ int based_height = height / 2; for(int i=0;i<based_nodes;i++){ int j = (i/based_height) * height + (i%based_height); rotate_hash[j] = i; rotate_hash[ROTATE(j, height, width, groups, 90)] = i + based_nodes; rotate_hash[ROTATE(j, height, width, groups, 180)] = i + based_nodes * 2; rotate_hash[ROTATE(j, height, width, groups, 270)] = i + based_nodes * 3; } } }
udr-1.c
/* { dg-do compile } */ /* { dg-options "-fopenmp" } */ #pragma omp declare reduction (| : long int : omp_out |= omp_in) /* { dg-error "predeclared arithmetic type" } */ #pragma omp declare reduction (+ : char : omp_out += omp_in) /* { dg-error "predeclared arithmetic type" } */ typedef short T; #pragma omp declare reduction (min : T : omp_out += omp_in) /* { dg-error "predeclared arithmetic type" } */ #pragma omp declare reduction (* : _Complex double : omp_out *= omp_in) /* { dg-error "predeclared arithmetic type" } */ void foo (void) { #pragma omp declare reduction (| : long int : omp_out |= omp_in) /* { dg-error "predeclared arithmetic type" } */ #pragma omp declare reduction (+ : char : omp_out += omp_in) /* { dg-error "predeclared arithmetic type" } */ #pragma omp declare reduction (min : T : omp_out += omp_in) /* { dg-error "predeclared arithmetic type" } */ #pragma omp declare reduction (* : _Complex double : omp_out *= omp_in) /* { dg-error "predeclared arithmetic type" } */ } #pragma omp declare reduction (| : __typeof (foo) : omp_out |= omp_in) /* { dg-error "function or array" } */ #pragma omp declare reduction (+ : char () : omp_out += omp_in) /* { dg-error "function or array" } */ #pragma omp declare reduction (min : T[2] : omp_out += omp_in) /* { dg-error "function or array" } */ void bar (void) { #pragma omp declare reduction (| : __typeof (foo) : omp_out |= omp_in)/* { dg-error "function or array" } */ #pragma omp declare reduction (+ : char () : omp_out += omp_in) /* { dg-error "function or array" } */ #pragma omp declare reduction (min : T[2] : omp_out += omp_in) /* { dg-error "function or array" } */ } struct A { int a; }; #pragma omp declare reduction (| : const struct A : omp_out.a |= omp_in.a) /* { dg-error "const, volatile or restrict" } */ #pragma omp declare reduction (+ : __const struct A : omp_out.a += omp_in.a) /* { dg-error "const, volatile or restrict" } */ typedef volatile struct A T2; #pragma omp declare reduction (min : T2 : omp_out.a += omp_in.a) /* { dg-error "const, volatile or restrict" } */ #pragma omp declare reduction (* : struct A *__restrict : omp_out->a *= omp_in->a)/* { dg-error "const, volatile or restrict" } */ void baz (void) { #pragma omp declare reduction (| : const struct A : omp_out.a |= omp_in.a) /* { dg-error "const, volatile or restrict" } */ #pragma omp declare reduction (+ : __const struct A : omp_out.a += omp_in.a) /* { dg-error "const, volatile or restrict" } */ typedef volatile struct A T3; #pragma omp declare reduction (min : T3 : omp_out.a += omp_in.a) /* { dg-error "const, volatile or restrict" } */ #pragma omp declare reduction (* : struct A *__restrict : omp_out->a *= omp_in->a)/* { dg-error "const, volatile or restrict" } */ }
GB_unop__abs_int32_int32.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 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__abs_int32_int32) // op(A') function: GB (_unop_tran__abs_int32_int32) // C type: int32_t // A type: int32_t // cast: int32_t cij = aij // unaryop: cij = GB_IABS (aij) #define GB_ATYPE \ int32_t #define GB_CTYPE \ int32_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 = GB_IABS (x) ; // casting #define GB_CAST(z, aij) \ int32_t z = aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ int32_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ int32_t z = aij ; \ Cx [pC] = GB_IABS (z) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_ABS || GxB_NO_INT32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__abs_int32_int32) ( int32_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] ; int32_t z = aij ; Cx [p] = GB_IABS (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] ; int32_t z = aij ; Cx [p] = GB_IABS (z) ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__abs_int32_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
GB_binop__atan2_fp64.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__atan2_fp64) // A.*B function (eWiseMult): GB (_AemultB_08__atan2_fp64) // A.*B function (eWiseMult): GB (_AemultB_02__atan2_fp64) // A.*B function (eWiseMult): GB (_AemultB_04__atan2_fp64) // A.*B function (eWiseMult): GB (_AemultB_bitmap__atan2_fp64) // A*D function (colscale): GB ((none)) // D*A function (rowscale): GB ((none)) // C+=B function (dense accum): GB (_Cdense_accumB__atan2_fp64) // C+=b function (dense accum): GB (_Cdense_accumb__atan2_fp64) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__atan2_fp64) // C=scalar+B GB (_bind1st__atan2_fp64) // C=scalar+B' GB (_bind1st_tran__atan2_fp64) // C=A+scalar GB (_bind2nd__atan2_fp64) // C=A'+scalar GB (_bind2nd_tran__atan2_fp64) // C type: double // A type: double // A pattern? 0 // B type: double // B pattern? 0 // BinaryOp: cij = atan2 (aij, bij) #define GB_ATYPE \ double #define GB_BTYPE \ double #define GB_CTYPE \ double // 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) \ double 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) \ double 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) \ double 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 = atan2 (x, y) ; // 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_ATAN2 || GxB_NO_FP64 || GxB_NO_ATAN2_FP64) //------------------------------------------------------------------------------ // 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__atan2_fp64) ( 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__atan2_fp64) ( 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__atan2_fp64) ( 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 double double bwork = (*((double *) 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 double *restrict Cx = (double *) 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 double *restrict Cx = (double *) 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__atan2_fp64) ( 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) ; double alpha_scalar ; double beta_scalar ; if (is_eWiseUnion) { alpha_scalar = (*((double *) alpha_scalar_in)) ; beta_scalar = (*((double *) 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__atan2_fp64) ( 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__atan2_fp64) ( 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__atan2_fp64) ( 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__atan2_fp64) ( 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__atan2_fp64) ( 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 double *Cx = (double *) Cx_output ; double x = (*((double *) x_input)) ; double *Bx = (double *) 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 ; double bij = GBX (Bx, p, false) ; Cx [p] = atan2 (x, bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__atan2_fp64) ( 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 ; double *Cx = (double *) Cx_output ; double *Ax = (double *) Ax_input ; double y = (*((double *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; double aij = GBX (Ax, p, false) ; Cx [p] = atan2 (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) \ { \ double aij = GBX (Ax, pA, false) ; \ Cx [pC] = atan2 (x, aij) ; \ } GrB_Info GB (_bind1st_tran__atan2_fp64) ( 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 \ double #if GB_DISABLE return (GrB_NO_VALUE) ; #else double x = (*((const double *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ double } //------------------------------------------------------------------------------ // 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) \ { \ double aij = GBX (Ax, pA, false) ; \ Cx [pC] = atan2 (aij, y) ; \ } GrB_Info GB (_bind2nd_tran__atan2_fp64) ( 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 double y = (*((const double *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
softmax-inl.h
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * Copyright (c) 2017 by Contributors * \file softmax-inl.h * \brief */ #ifndef MXNET_OPERATOR_NN_SOFTMAX_INL_H_ #define MXNET_OPERATOR_NN_SOFTMAX_INL_H_ #include <algorithm> #include <string> #include <utility> #include <vector> #include <type_traits> #include "../mxnet_op.h" #include "../operator_common.h" #include "../tensor/broadcast_reduce_op.h" #include "../../common/cuda/utils.h" namespace mxnet { namespace op { namespace mxnet_op { struct softmax_fwd { template<typename AType> MSHADOW_XINLINE static AType Map(float a, AType b) { return AType(expf(a)/b); } template<typename AType> MSHADOW_XINLINE static AType Map(double a, AType b) { return AType(exp(a)/b); } }; struct log_softmax_fwd { template<typename DType> MSHADOW_XINLINE static float Map(DType a, float b) { return a - logf(b); } template<typename DType> MSHADOW_XINLINE static double Map(DType a, double b) { return a - log(b); } }; template<typename OP, bool negate, typename AType, typename DType, typename OType, typename IType, int ndim> inline void Softmax(Stream<cpu> *s, DType *in, OType *out, IType *length, Shape<ndim> shape, int axis, const DType temperature) { index_t M = shape[axis]; if (M == 0) return; index_t N = shape.Size()/M; Shape<ndim> stride = calc_stride(shape); Shape<ndim> sshape = shape; sshape[axis] = 1; index_t sa = stride[axis]; if (length == nullptr) { #pragma omp parallel for for (index_t i = 0; i < N; ++i) { index_t base = unravel_dot(i, sshape, stride); DType mmax = negate ? -in[base] : in[base]; DType val; for (index_t j = 1; j < M; ++j) { val = negate ? -in[base + j*sa] : in[base + j*sa]; if (mmax < val) mmax = val; } AType sum = AType(0); DType in_val; // By default temperature is 1.0. // Adding a branch here to save the CPU 'divide-by-1' computation at runtime if (temperature == 1.0) { for (index_t j = 0; j < M; ++j) { in_val = negate ? -in[base + j*sa] : in[base + j*sa]; sum += std::exp(in_val - mmax); } for (index_t j = 0; j < M; ++j) { in_val = negate ? -in[base + j*sa] : in[base + j*sa]; out[base + j*sa] = OP::Map(in_val - mmax, sum); } } else { for (index_t j = 0; j < M; ++j) { in_val = negate ? -in[base + j*sa] : in[base + j*sa]; sum += std::exp((in_val - mmax)/temperature); } for (index_t j = 0; j < M; ++j) { in_val = negate ? -in[base + j*sa] : in[base + j*sa]; out[base + j*sa] = OP::Map((in_val - mmax)/temperature, sum); } } } } else { #pragma omp parallel for for (index_t i = 0; i < N; ++i) { index_t len = static_cast<index_t>(length[i]); index_t base = unravel_dot(i, sshape, stride); DType mmax = negate ? -in[base] : in[base]; DType val; for (index_t j = 1; j < len; ++j) { val = negate ? -in[base + j*sa] : in[base + j*sa]; if (mmax < val) mmax = val; } for (index_t j = len; j < M; ++j) { out[base + j*sa] = OType(0.0f); } AType sum = AType(0); DType in_val; // By default temperature is 1.0. // Adding a branch here to save the CPU 'divide-by-1' computation at runtime if (temperature == 1.0) { for (index_t j = 0; j < len; ++j) { in_val = negate ? -in[base + j*sa] : in[base + j*sa]; sum += std::exp(in_val - mmax); } for (index_t j = 0; j < len; ++j) { in_val = negate ? -in[base + j*sa] : in[base + j*sa]; out[base + j*sa] = OP::Map(in_val - mmax, sum); } } else { for (index_t j = 0; j < len; ++j) { in_val = negate ? -in[base + j*sa] : in[base + j*sa]; sum += std::exp((in_val - mmax)/temperature); } for (index_t j = 0; j < len; ++j) { in_val = negate ? -in[base + j*sa] : in[base + j*sa]; out[base + j*sa] = OP::Map((in_val - mmax)/temperature, sum); } } } } } struct softmax_bwd { template<typename DType, typename AType> MSHADOW_XINLINE static AType Map(DType ograd, DType out, AType sum) { return AType(out * (ograd - sum)); } }; struct log_softmax_bwd { template<typename AType> MSHADOW_XINLINE static AType Map(float ograd, float out, AType sum) { return AType(ograd - expf(out)*sum); } template<typename AType> MSHADOW_XINLINE static AType Map(double ograd, double out, AType sum) { return AType(ograd - exp(out)*sum); } }; template<typename OP1, typename OP2, int Req, bool negate, typename AType, typename DType, typename OType, typename IType, int ndim> inline void SoftmaxGrad(Stream<cpu> *s, OType *out, OType *ograd, DType *igrad, IType *length, Shape<ndim> shape, int axis, const DType temperature) { index_t M = shape[axis]; if (M == 0) return; index_t N = shape.Size()/M; Shape<ndim> stride = calc_stride(shape); Shape<ndim> sshape = shape; sshape[axis] = 1; index_t sa = stride[axis]; if (length != nullptr) { #pragma omp parallel for for (index_t i = 0; i < N; ++i) { index_t base = unravel_dot(i, sshape, stride); index_t len = static_cast<index_t>(length[i]); AType sum = AType(0); for (index_t j = 0; j < len; ++j) { sum += OP1::Map(ograd[base + j*sa], out[base + j*sa]); } // By default temperature is 1.0. // Adding a branch here to save the CPU 'divide-by-1' computation at runtime DType final_result; if (temperature == 1.0) { for (index_t j = 0; j < M; ++j) { final_result = negate ? -OP2::Map(ograd[base + j*sa], out[base + j*sa], sum) : OP2::Map(ograd[base + j*sa], out[base + j*sa], sum); final_result = (j < len) ? final_result : DType(0.0f); KERNEL_ASSIGN(igrad[base + j*sa], Req, final_result); } } else { for (index_t j = 0; j < M; ++j) { final_result = negate ? -OP2::Map(ograd[base + j*sa], out[base + j*sa], sum) / temperature : OP2::Map(ograd[base + j*sa], out[base + j*sa], sum) / temperature; final_result = (j < len) ? final_result : DType(0.0f); KERNEL_ASSIGN(igrad[base + j*sa], Req, final_result); } } } } else { #pragma omp parallel for for (index_t i = 0; i < N; ++i) { index_t base = unravel_dot(i, sshape, stride); AType sum = AType(0); for (index_t j = 0; j < M; ++j) { sum += OP1::Map(ograd[base + j*sa], out[base + j*sa]); } // By default temperature is 1.0. // Adding a branch here to save the CPU 'divide-by-1' computation at runtime DType final_result; if (temperature == 1.0) { for (index_t j = 0; j < M; ++j) { final_result = negate ? -OP2::Map(ograd[base + j*sa], out[base + j*sa], sum) : OP2::Map(ograd[base + j*sa], out[base + j*sa], sum); KERNEL_ASSIGN(igrad[base + j*sa], Req, final_result); } } else { for (index_t j = 0; j < M; ++j) { final_result = negate ? -OP2::Map(ograd[base + j*sa], out[base + j*sa], sum) / temperature : OP2::Map(ograd[base + j*sa], out[base + j*sa], sum) / temperature; KERNEL_ASSIGN(igrad[base + j*sa], Req, final_result); } } } } } #ifdef __CUDACC__ template<int x_bits, typename OP, bool negate, typename AType, int ndim, typename DType, typename OType, typename IType> __global__ void softmax_compute_kernel(DType *in, OType *out, IType *length, index_t M, int axis, Shape<ndim> sshape, Shape<ndim> stride, const double temperature) { const unsigned x_size = 1 << x_bits; __shared__ AType smem[x_size]; index_t sa = stride[axis]; index_t base = unravel_dot(blockIdx.x, sshape, stride); index_t x = threadIdx.x; const index_t len = length == nullptr ? M : static_cast<index_t>(length[blockIdx.x]); red::maximum::SetInitValue(smem[x]); for (index_t i = x; i < len; i += x_size) { smem[x] = ::max(smem[x], negate ? -in[base + i*sa] : in[base + i*sa]); } __syncthreads(); cuda::Reduce1D<red::maximum, x_bits>(smem); __syncthreads(); DType smax = smem[0]; __syncthreads(); red::sum::SetInitValue(smem[x]); DType val; for (index_t i = x; i < len; i += x_size) { val = negate ? -in[base + i*sa]:in[base + i*sa]; smem[x] += static_cast<AType>(expf((val - smax) / static_cast<AType>(temperature))); } __syncthreads(); cuda::Reduce1D<red::sum, x_bits>(smem); __syncthreads(); AType ssum = smem[0]; __syncthreads(); for (index_t i = x; i < M; i += x_size) { val = negate ? -in[base + i*sa] : in[base + i*sa]; out[base + i*sa] = (i < len) ? OType(OP::Map((val - smax)/static_cast<DType>(temperature), ssum)) : OType(0.0f); } } const int softmax_threads_per_block = 512; template<typename OP, bool negate, typename AType, typename LType, typename DType, typename OType, typename IType> __global__ void softmax_stride1_compute_kernel(const DType *in, OType *out, IType *length, const index_t M, const double temperature, const int rows_per_block, const index_t total_rows) { __shared__ AType scratch[softmax_threads_per_block]; __shared__ LType persistent_storage[20 * 1024 / sizeof(LType)]; const int warp_size = 32; const int threads_per_row = softmax_threads_per_block / rows_per_block; const int my_local_row = threadIdx.x / threads_per_row; const int my_row = blockIdx.x * rows_per_block + my_local_row; if (my_row >= total_rows) return; const int my_id = threadIdx.x % threads_per_row; const int entries_per_load = sizeof(LType)/sizeof(DType); const index_t len = length == nullptr ? M : static_cast<index_t>(length[my_row]); // Due to usage of MSHADOW_TYPE_SWITCH macro we are generating // kernels where sizeof(LType) may be less than sizeof(DType), // resulting in entries_per_load being 0. // This is not a valid combination and is being checked against // in the launcher code. This switch here is just to silence // the division by zero warning generated for such invalid cases. const int row_length = entries_per_load > 0 ? M / entries_per_load : 0; const LType* in_aligned = reinterpret_cast<const LType*>(in); size_t base = my_row * row_length; for (index_t i = my_id; i < row_length; i += threads_per_row) { persistent_storage[my_local_row * row_length + i] = in_aligned[base + i]; } DType * row = reinterpret_cast<DType *>(persistent_storage + my_local_row * row_length); __syncthreads(); DType my_max_value; red::maximum::SetInitValue(my_max_value); for (index_t i = my_id; i < len; i += threads_per_row) { my_max_value = ::max(my_max_value, negate ? -row[i] : row[i]); } scratch[threadIdx.x] = my_max_value; __syncthreads(); for (int size = threads_per_row / 2; size >= warp_size; size /= 2) { if (my_id < size) { scratch[threadIdx.x] = ::max(scratch[threadIdx.x], scratch[threadIdx.x + size]); } __syncthreads(); } if (my_id < warp_size) { AType my_value = common::cuda::warp_reduce(scratch[threadIdx.x], [](AType x, AType y) { return ::max(x, y); }); scratch[threadIdx.x] = my_value; } __syncthreads(); DType smax = scratch[threadIdx.x - threadIdx.x % threads_per_row]; __syncthreads(); AType my_sum; red::sum::SetInitValue(my_sum); for (index_t i = my_id; i < len; i += threads_per_row) { const DType val = negate ? -row[i] : row[i]; my_sum += static_cast<AType>(expf((val - smax) / static_cast<AType>(temperature))); } scratch[threadIdx.x] = my_sum; __syncthreads(); for (int size = threads_per_row / 2; size >= warp_size; size /= 2) { if (my_id < size) { scratch[threadIdx.x] += scratch[threadIdx.x + size]; } __syncthreads(); } if (my_id < warp_size) { AType my_value = common::cuda::warp_reduce(scratch[threadIdx.x], [](AType x, AType y) { return x + y;}); scratch[threadIdx.x] = my_value; } __syncthreads(); AType ssum = scratch[threadIdx.x - threadIdx.x % threads_per_row]; __syncthreads(); for (index_t i = my_id; i < M; i += threads_per_row) { const DType val = negate ? -row[i] : row[i]; row[i] = (i < len) ? DType(OP::Map((val - smax)/static_cast<DType>(temperature), ssum)) : DType(0.0f); } __syncthreads(); LType* out_aligned = reinterpret_cast<LType*>(out); for (index_t i = my_id; i < row_length; i += threads_per_row) { out_aligned[base + i] = persistent_storage[my_local_row * row_length + i]; } } template<typename OP, bool negate, typename AType, typename DType, typename OType, typename IType, int ndim> inline void Softmax(Stream<gpu> *s, DType *in, OType *out, IType *length, Shape<ndim> shape, int axis, const double temperature) { const int x_bits = 7; const int x_size = 1 << x_bits; index_t M = shape[axis]; if (M == 0 || shape.Size() == 0) return; index_t N = shape.Size()/M; Shape<ndim> stride = calc_stride(shape); Shape<ndim> sshape = shape; sshape[axis] = 1; const size_t DSize = sizeof(DType); // Using 20 kB of shared memory for persistent storage in the optimized case const size_t max_opt_M = 20 * 1024 / DSize; if (stride[axis] == 1 && static_cast<size_t>(M) <= max_opt_M && std::is_same<DType, OType>::value) { int ltype = mxnet::common::cuda::get_load_type(M * sizeof(DType)); MXNET_LOAD_TYPE_SWITCH(ltype, LType, { int rows_per_block = mxnet::common::cuda::get_rows_per_block(M * sizeof(DType) / sizeof(LType), softmax_threads_per_block); int nblocks = (N + rows_per_block - 1) / rows_per_block; CHECK_LE(sizeof(DType), sizeof(LType)); softmax_stride1_compute_kernel<OP, negate, AType, LType> <<<nblocks, softmax_threads_per_block, 0, mshadow::Stream<gpu>::GetStream(s)>>>( in, out, length, M, temperature, rows_per_block, N); }); MSHADOW_CUDA_POST_KERNEL_CHECK(softmax_stride1_compute_kernel); } else { softmax_compute_kernel<x_bits, OP, negate, AType, ndim> <<<N, x_size, 0, mshadow::Stream<gpu>::GetStream(s)>>>( in, out, length, M, axis, sshape, stride, temperature); MSHADOW_CUDA_POST_KERNEL_CHECK(softmax_compute_kernel); } } template<typename OP1, typename OP2, int Req, bool negate, typename AType, typename LType, typename DType, typename OType, typename IType> __global__ void softmax_stride1_grad_kernel(const OType *out, const OType *ograd, DType *igrad, const IType *length, const index_t M, const double temperature, const int rows_per_block, const index_t total_rows) { __shared__ AType scratch[softmax_threads_per_block]; __shared__ LType persistent_storage[20 * 1024 / sizeof(LType)]; const int warp_size = 32; const int threads_per_row = softmax_threads_per_block / rows_per_block; const int my_local_row = threadIdx.x / threads_per_row; const int my_row = blockIdx.x * rows_per_block + my_local_row; if (my_row >= total_rows) return; const int my_id = threadIdx.x % threads_per_row; const int entries_per_load = sizeof(LType)/sizeof(DType); const index_t len = length == nullptr ? M : static_cast<index_t>(length[my_row]); // Due to usage of MSHADOW_TYPE_SWITCH macro we are generating // kernels where sizeof(LType) may be less than sizeof(DType), // resulting in entries_per_load being 0. // This is not a valid combination and is being checked against // in the launcher code. This switch here is just to silence // the division by zero warning generated for such invalid cases. const int row_length = entries_per_load > 0 ? M / entries_per_load : 0; const LType* out_aligned = reinterpret_cast<const LType*>(out); const LType* ograd_aligned = reinterpret_cast<const LType*>(ograd); size_t base = my_row * row_length; for (index_t i = my_id; i < row_length; i += threads_per_row) { persistent_storage[my_local_row * row_length * 2 + i] = out_aligned[base + i]; persistent_storage[my_local_row * row_length * 2 + row_length + i] = ograd_aligned[base + i]; } DType * row = reinterpret_cast<DType *>(persistent_storage + my_local_row * row_length * 2); __syncthreads(); AType my_sum_value; red::sum::SetInitValue(my_sum_value); for (index_t i = my_id; i < len; i += threads_per_row) { my_sum_value += OP1::Map(row[i + M], row[i]); } scratch[threadIdx.x] = my_sum_value; __syncthreads(); for (int size = threads_per_row / 2; size >= warp_size; size /= 2) { if (my_id < size) { scratch[threadIdx.x] = scratch[threadIdx.x] + scratch[threadIdx.x + size]; } __syncthreads(); } if (my_id < warp_size) { AType my_value = common::cuda::warp_reduce(scratch[threadIdx.x], [](AType x, AType y) { return x + y; }); scratch[threadIdx.x] = my_value; } __syncthreads(); AType ssum = scratch[threadIdx.x - threadIdx.x % threads_per_row]; __syncthreads(); for (index_t i = my_id; i < M; i += threads_per_row) { const DType val = negate ? -OP2::Map(row[i + M], row[i], ssum) : OP2::Map(row[i + M], row[i], ssum); row[i] = (i < len) ? DType(val / static_cast<DType>(temperature)) : DType(0.0f); if (Req == kAddTo) { row[i] += igrad[my_row * M + i]; } } __syncthreads(); LType* igrad_aligned = reinterpret_cast<LType*>(igrad); for (index_t i = my_id; i < row_length; i += threads_per_row) { igrad_aligned[base + i] = persistent_storage[my_local_row * row_length * 2 + i]; } } template<int x_bits, typename OP1, typename OP2, int Req, bool negate, typename AType, int ndim, typename DType, typename OType, typename IType> __global__ void softmax_grad_kernel(OType *out, OType *ograd, DType *igrad, const IType *length, index_t M, int axis, Shape<ndim> sshape, Shape<ndim> stride, const double temperature) { const unsigned x_size = 1 << x_bits; __shared__ AType smem[x_size]; index_t sa = stride[axis]; index_t base = unravel_dot(blockIdx.x, sshape, stride); index_t x = threadIdx.x; index_t len = length != nullptr ? static_cast<index_t>(length[blockIdx.x]) : M; red::sum::SetInitValue(smem[x]); for (index_t i = x; i < len; i += x_size) { smem[x] += OP1::Map(ograd[base + i*sa], out[base + i*sa]); } __syncthreads(); cuda::Reduce1D<red::sum, x_bits>(smem); __syncthreads(); AType ssum = smem[0]; __syncthreads(); DType final_result; for (index_t i = x; i < M; i += x_size) { final_result = negate ? -OP2::Map(ograd[base + i*sa], out[base + i*sa], ssum) : OP2::Map(ograd[base + i*sa], out[base + i*sa], ssum); final_result = (i < len) ? final_result : DType(0.0f); KERNEL_ASSIGN(igrad[base + i*sa], Req, final_result / static_cast<DType>(temperature)); } } template<typename OP1, typename OP2, int Req, bool negate, typename AType, int ndim, typename DType, typename OType, typename IType> inline void SoftmaxGrad(Stream<gpu> *s, OType *out, OType *ograd, DType *igrad, IType *length, Shape<ndim> shape, int axis, const double temperature) { const int x_bits = 7; const int x_size = 1 << x_bits; index_t M = shape[axis]; if (M == 0 || shape.Size() == 0) return; index_t N = shape.Size()/M; Shape<ndim> stride = calc_stride(shape); Shape<ndim> sshape = shape; sshape[axis] = 1; const size_t DSize = sizeof(DType); // Using 20 kB of shared memory for persistent storage in the optimized case // Need to store both out and ograd, so M can be only half compared to // forward pass. const size_t max_opt_M = 20 * 1024 / DSize / 2; if (stride[axis] == 1 && static_cast<size_t>(M) <= max_opt_M && std::is_same<DType, OType>::value) { int ltype = mxnet::common::cuda::get_load_type(M * sizeof(DType)); MXNET_LOAD_TYPE_SWITCH(ltype, LType, { int rows_per_block = mxnet::common::cuda::get_rows_per_block(M * sizeof(DType) / sizeof(LType), softmax_threads_per_block); int nblocks = (N + rows_per_block - 1) / rows_per_block; CHECK_LE(sizeof(DType), sizeof(LType)); softmax_stride1_grad_kernel<OP1, OP2, Req, negate, AType, LType> <<<nblocks, softmax_threads_per_block, 0, mshadow::Stream<gpu>::GetStream(s)>>>( out, ograd, igrad, length, M, temperature, rows_per_block, N); }); MSHADOW_CUDA_POST_KERNEL_CHECK(softmax_stride1_grad_kernel); } else { softmax_grad_kernel<x_bits, OP1, OP2, Req, negate, AType, ndim> <<<N, x_size, 0, mshadow::Stream<gpu>::GetStream(s)>>>( out, ograd, igrad, length, M, axis, sshape, stride, temperature); MSHADOW_CUDA_POST_KERNEL_CHECK(softmax_grad_kernel); } } #endif } // namespace mxnet_op struct SoftmaxParam : public dmlc::Parameter<SoftmaxParam> { int axis; dmlc::optional<double> temperature; dmlc::optional<int> dtype; dmlc::optional<bool> use_length; DMLC_DECLARE_PARAMETER(SoftmaxParam) { DMLC_DECLARE_FIELD(axis).set_default(-1) .describe("The axis along which to compute softmax."); DMLC_DECLARE_FIELD(temperature).set_default(dmlc::optional<double>()) .describe("Temperature parameter in softmax"); DMLC_DECLARE_FIELD(dtype) .add_enum("float16", mshadow::kFloat16) .add_enum("float32", mshadow::kFloat32) .add_enum("float64", mshadow::kFloat64) .set_default(dmlc::optional<int>()) .describe("DType of the output in case this can't be inferred. " "Defaults to the same as input's dtype if not defined (dtype=None)."); DMLC_DECLARE_FIELD(use_length) .set_default(dmlc::optional<bool>(false)) .describe("Whether to use the length input as a mask over the data input."); } bool operator==(const SoftmaxParam& other) const { return this->axis == other.axis && this->temperature == other.temperature && this->dtype == other.dtype && this->use_length == other.use_length; } }; static inline bool softmax_has_dtype_override(const nnvm::NodeAttrs& attrs) { const SoftmaxParam& param = nnvm::get<SoftmaxParam>(attrs.parsed); return param.dtype.has_value() && param.dtype.value() != -1; } static inline bool softmax_use_length(const nnvm::NodeAttrs& attrs) { const SoftmaxParam& param = nnvm::get<SoftmaxParam>(attrs.parsed); return param.use_length.value(); } static inline bool SoftmaxOpType(const nnvm::NodeAttrs& attrs, std::vector<int>* in_attrs, std::vector<int>* out_attrs) { CHECK_EQ(out_attrs->size(), 1); const SoftmaxParam& param = nnvm::get<SoftmaxParam>(attrs.parsed); CHECK_EQ(in_attrs->size(), softmax_use_length(attrs) ? 2U : 1U); if (softmax_has_dtype_override(attrs)) { TYPE_ASSIGN_CHECK(*out_attrs, 0, param.dtype.value()); type_assign(&(*in_attrs)[0], (*out_attrs)[0]); return true; } else { std::vector<int> tmp = {in_attrs->at(0)}; return ElemwiseType<1, 1>(attrs, &tmp, out_attrs); } } static inline bool SoftmaxOpShape(const nnvm::NodeAttrs& attrs, mxnet::ShapeVector *in_attrs, mxnet::ShapeVector *out_attrs) { CHECK_EQ(out_attrs->size(), 1U); const SoftmaxParam& param = nnvm::get<SoftmaxParam>(attrs.parsed); CHECK_EQ(in_attrs->size(), param.use_length.value() ? 2U : 1U); if (param.use_length.value()) { mxnet::TShape& dshape = in_attrs->at(0); mxnet::TShape tmp_shape((dshape.ndim() == 1) ? 1U : dshape.ndim() - 1, 1); int j = 0; int axis = param.axis != -1 ? param.axis : dshape.ndim() - 1; for (int i = 0; i < dshape.ndim(); ++i) { if (i != axis) { tmp_shape[j++] = dshape[i]; } } SHAPE_ASSIGN_CHECK(*in_attrs, 1, tmp_shape); } mxnet::ShapeVector tmp = {in_attrs->at(0)}; return ElemwiseShape<1, 1>(attrs, &tmp, out_attrs); } static inline bool SoftmaxGradOpShape(const nnvm::NodeAttrs& attrs, mxnet::ShapeVector *in_attrs, mxnet::ShapeVector *out_attrs) { if (softmax_has_dtype_override(attrs) || softmax_use_length(attrs)) { if (softmax_use_length(attrs)) { mxnet::ShapeVector ins = {in_attrs->at(0), in_attrs->at(1), in_attrs->at(3)}; mxnet::ShapeVector dgrad = {out_attrs->at(0)}; bool res = ElemwiseShape<3, 1>(attrs, &ins, &dgrad); SHAPE_ASSIGN_CHECK(*in_attrs, 0, ins[0]); SHAPE_ASSIGN_CHECK(*in_attrs, 1, ins[1]); SHAPE_ASSIGN_CHECK(*in_attrs, 3, ins[2]); SHAPE_ASSIGN_CHECK(*out_attrs, 0, dgrad[0]); mxnet::ShapeVector length = {in_attrs->at(2)}; mxnet::ShapeVector lgrad = {out_attrs->at(1)}; res = (res && ElemwiseShape<1, 1>(attrs, &length, &lgrad)); SHAPE_ASSIGN_CHECK(*in_attrs, 2, length[0]); SHAPE_ASSIGN_CHECK(*out_attrs, 1, lgrad[0]); return res; } else { return ElemwiseShape<3, 1>(attrs, in_attrs, out_attrs); } } else { return ElemwiseShape<2, 1>(attrs, in_attrs, out_attrs); } } static inline bool SoftmaxGradOpType(const nnvm::NodeAttrs& attrs, std::vector<int>* in_attrs, std::vector<int>* out_attrs) { CHECK_EQ(out_attrs->size(), softmax_use_length(attrs) ? 2U : 1U); if (softmax_has_dtype_override(attrs) || softmax_use_length(attrs)) { CHECK_EQ(in_attrs->size(), softmax_use_length(attrs) ? 4U : 3U); int in_dtype = (*in_attrs)[1]; int out_dtype = (*in_attrs)[softmax_use_length(attrs) ? 3 : 2]; TYPE_ASSIGN_CHECK(*in_attrs, 0, out_dtype); TYPE_ASSIGN_CHECK(*out_attrs, 0, in_dtype); if (softmax_use_length(attrs)) { TYPE_ASSIGN_CHECK(*out_attrs, 1, in_attrs->at(2)); } return (*out_attrs)[0] != -1 && (*in_attrs)[0] != -1 && (!softmax_use_length(attrs) || ((*out_attrs)[1] != -1 && (*in_attrs)[1] != -1)); } else { CHECK_EQ(in_attrs->size(), 2U); int out_dtype = (*in_attrs)[1]; TYPE_ASSIGN_CHECK(*out_attrs, 0, out_dtype); TYPE_ASSIGN_CHECK(*in_attrs, 0, out_dtype); return (*out_attrs)[0] != -1 && (*in_attrs)[0] != -1; } } static inline std::vector<std::pair<int, int> > SoftmaxGradOpInplaceOption(const nnvm::NodeAttrs& attrs) { if (softmax_has_dtype_override(attrs) || softmax_use_length(attrs)) { if (softmax_use_length(attrs)) { return std::vector<std::pair<int, int> >{{0, 0}, {1, 0}, {2, 1}, {3, 0}}; } else { return std::vector<std::pair<int, int> >{{0, 0}, {1, 0}, {2, 0}}; } } else { return std::vector<std::pair<int, int> >{{0, 0}, {1, 0}}; } } static inline uint32_t SoftmaxGradOpNumInputs(const nnvm::NodeAttrs& attrs) { if (softmax_has_dtype_override(attrs) || softmax_use_length(attrs)) { return softmax_use_length(attrs) ? 4 : 3; } return 2; } static inline std::vector<std::string> SoftmaxGradOpInputNames(const nnvm::NodeAttrs& attrs) { if (softmax_has_dtype_override(attrs) || softmax_use_length(attrs)) { if (softmax_use_length(attrs)) { return std::vector<std::string>{"ograd", "data", "length", "output"}; } else { return std::vector<std::string>{"ograd", "data", "output"}; } } else { return std::vector<std::string>{"ograd", "output"}; } } struct SoftmaxFGradient { const char *op_name; std::vector<nnvm::NodeEntry> operator()(const nnvm::ObjectPtr& n, const std::vector<nnvm::NodeEntry>& ograds) const { if (softmax_has_dtype_override(n->attrs) || softmax_use_length(n->attrs)) { return ElemwiseGradUseInOut {op_name}(n, ograds); } else { return ElemwiseGradUseOut {op_name}(n, ograds); } } }; template<typename xpu, typename OP, bool negate = false> void SoftmaxCompute(const nnvm::NodeAttrs& attrs, const OpContext& ctx, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs) { using namespace mxnet_op; if (req[0] == kNullOp || inputs[0].Size() == 0U) return; CHECK_NE(req[0], kAddTo); const SoftmaxParam& param = nnvm::get<SoftmaxParam>(attrs.parsed); int axis = CheckAxis(param.axis, inputs[0].ndim()); const double temperature = param.temperature.has_value() ? param.temperature.value() : 1.0; mxnet::TShape shape = AxisShapeCompact(inputs[0].shape_, &axis, true); bool safe_acc = dmlc::GetEnv("MXNET_SAFE_ACCUMULATION", true); if (!safe_acc && inputs[0].type_flag_ == mshadow::kFloat16) { common::LogOnce("MXNET_SAFE_ACCUMULATION=1 is recommended for softmax with float16 inputs. " "See https://mxnet.apache.org/api/faq/env_var " "for more details."); } MXNET_REAL_ACC_TYPE_SWITCH(inputs[0].type_flag_, DType, AType, { MSHADOW_REAL_TYPE_SWITCH(outputs[0].type_flag_, OType, { int type = kInt32; if (param.use_length.value()) { CHECK(inputs.size() > 1) << "Mask needs to be provided when using softmax with use_length=True."; type = inputs[1].type_flag_; } MXNET_INT32_INT64_TYPE_SWITCH(type, IType, { IType* mask_ptr = nullptr; if (param.use_length.value()) { mask_ptr = inputs[1].dptr<IType>(); } if (safe_acc) { if (shape.ndim() == 2) { Softmax<OP, negate, AType>( ctx.get_stream<xpu>(), inputs[0].dptr<DType>(), outputs[0].dptr<OType>(), mask_ptr, shape.get<2>(), axis, static_cast<DType>(temperature)); } else { Softmax<OP, negate, AType>( ctx.get_stream<xpu>(), inputs[0].dptr<DType>(), outputs[0].dptr<OType>(), mask_ptr, shape.get<3>(), axis, static_cast<DType>(temperature)); } } else { if (shape.ndim() == 2) { Softmax<OP, negate, DType>( ctx.get_stream<xpu>(), inputs[0].dptr<DType>(), outputs[0].dptr<OType>(), mask_ptr, shape.get<2>(), axis, static_cast<DType>(temperature)); } else { Softmax<OP, negate, DType>( ctx.get_stream<xpu>(), inputs[0].dptr<DType>(), outputs[0].dptr<OType>(), mask_ptr, shape.get<3>(), axis, static_cast<DType>(temperature)); } } }); }); }); } template<typename xpu, typename OP1, typename OP2, bool negate = false> void SoftmaxGradCompute(const nnvm::NodeAttrs& attrs, const OpContext& ctx, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs) { using namespace mxnet_op; if (softmax_use_length(attrs)) { MXNET_INT32_INT64_TYPE_SWITCH(inputs[2].type_flag_, IType, { if (req[1] != kNullOp) { mxnet_op::Kernel<mxnet_op::set_zero, xpu>::Launch( ctx.get_stream<xpu>(), outputs[1].Size(), outputs[1].dptr<IType>()); } }); } if (req[0] == kNullOp) return; const int itype = softmax_use_length(attrs) ? inputs[2].type_flag_ : kInt32; const SoftmaxParam& param = nnvm::get<SoftmaxParam>(attrs.parsed); int axis = CheckAxis(param.axis, inputs[0].ndim()); const double temperature = param.temperature.has_value() ? param.temperature.value() : 1.0; mxnet::TShape shape = AxisShapeCompact(inputs[0].shape_, &axis, true); int out_idx = softmax_has_dtype_override(attrs) ? 2 : 1; out_idx = softmax_use_length(attrs) ? 3 : out_idx; bool safe_acc = dmlc::GetEnv("MXNET_SAFE_ACCUMULATION", true); MXNET_REAL_ACC_TYPE_SWITCH(inputs[0].type_flag_, OType, AType, { MSHADOW_REAL_TYPE_SWITCH(outputs[0].type_flag_, DType, { MXNET_ASSIGN_REQ_SWITCH(req[0], Req, { MXNET_INT32_INT64_TYPE_SWITCH(itype, IType, { IType * length_ptr = nullptr; if (softmax_use_length(attrs)) { length_ptr = inputs[2].dptr<IType>(); } if (safe_acc) { if (shape.ndim() == 2) { SoftmaxGrad<OP1, OP2, Req, negate, AType>( ctx.get_stream<xpu>(), inputs[out_idx].dptr<OType>(), inputs[0].dptr<OType>(), outputs[0].dptr<DType>(), length_ptr, shape.get<2>(), axis, static_cast<DType>(temperature)); } else { SoftmaxGrad<OP1, OP2, Req, negate, AType>( ctx.get_stream<xpu>(), inputs[out_idx].dptr<OType>(), inputs[0].dptr<OType>(), outputs[0].dptr<DType>(), length_ptr, shape.get<3>(), axis, static_cast<DType>(temperature)); } } else { if (shape.ndim() == 2) { SoftmaxGrad<OP1, OP2, Req, negate, DType>( ctx.get_stream<xpu>(), inputs[out_idx].dptr<OType>(), inputs[0].dptr<OType>(), outputs[0].dptr<DType>(), length_ptr, shape.get<2>(), axis, static_cast<DType>(temperature)); } else { SoftmaxGrad<OP1, OP2, Req, negate, DType>( ctx.get_stream<xpu>(), inputs[out_idx].dptr<OType>(), inputs[0].dptr<OType>(), outputs[0].dptr<DType>(), length_ptr, shape.get<3>(), axis, static_cast<DType>(temperature)); } } }); }); }); }); } } // namespace op } // namespace mxnet namespace std { template<> struct hash<mxnet::op::SoftmaxParam> { size_t operator()(const mxnet::op::SoftmaxParam& val) { size_t ret = 0; ret = dmlc::HashCombine(ret, val.axis); ret = dmlc::HashCombine(ret, val.temperature); ret = dmlc::HashCombine(ret, val.dtype); ret = dmlc::HashCombine(ret, val.use_length); return ret; } }; } // namespace std #endif // MXNET_OPERATOR_NN_SOFTMAX_INL_H_
NAS_EP.c
//--------------------------------------------------------------------- // program EP //--------------------------------------------------------------------- #include <stdio.h> #include <stdlib.h> #include <math.h> #include <time.h> #include <sys/time.h> #if !defined(CLASS_W) && !defined(CLASS_S) && !defined(CLASS_A) && !defined(CLASS_B) && !defined(CLASS_C) && !defined(CLASS_D) && !defined(CLASS_E) # define CLASS_W #endif //---------- // Class S: //---------- #ifdef CLASS_S # define M 24 # define CLASS 'S' #endif //---------- // Class W: //---------- #ifdef CLASS_W # define M 25 # define CLASS 'W' #endif //---------- // Class A: //---------- #ifdef CLASS_A # define M 28 # define CLASS 'A' #endif //---------- // Class B: //---------- #ifdef CLASS_B # define M 30 # define CLASS 'B' #endif //---------- // Class C: //---------- #ifdef CLASS_C # define M 32 # define CLASS 'C' #endif //---------- // Class D: //---------- #ifdef CLASS_D # define M 36 # define CLASS 'D' #endif //---------- // Class E: //---------- #ifdef CLASS_E # define M 40 # define CLASS 'E' #endif typedef struct { double real; double imag; } dcomplex; #define min(x,y) ((x) < (y) ? (x) : (y)) #define max(x,y) ((x) > (y) ? (x) : (y)) #define MAX(X,Y) (((X) > (Y)) ? (X) : (Y)) #define MK 16 #define MM (M - MK) #define NN (1 << MM) #define NK (1 << MK) #define NQ 10 #define EPSILON 1.0e-8 #define A 1220703125.0 #define S 271828183.0 double randlc( double *x, double a ); void vranlc( int n, double *x, double a, double y[] ); void print_results(char *name, char class, int n1, int n2, int n3, int niter, double t, double mops, char *optype, int verified); double start[64], elapsed[64]; double elapsed_time( void ); void timer_clear( int n ); void timer_start( int n ); void timer_stop( int n ); double timer_read( int n ); void wtime(double *t); int main() { double Mops, t1, t2, t3, t4, x1, x2; double sx, sy, tm, an, tt, gc; double sx_verify_value, sy_verify_value, sx_err, sy_err; int np; int i, ik, kk, l, k, nit; int k_offset, j; int verified; double dum[3] = {1.0, 1.0, 1.0}; char size[16]; double x[2 * NK]; double q[NQ]; FILE *fp; //-------------------------------------------------------------------- // Because the size of the problem is too large to store in a 32-bit // integer for some classes, we put it into a string (for printing). // Have to strip off the decimal point put in there by the floating // point print statement (internal file) //-------------------------------------------------------------------- sprintf(size, "%15.0lf", pow(2.0, M + 1)); j = 14; if (size[j] == '.') j--; size[j + 1] = '\0'; printf("\n\n NAS Parallel Benchmarks (NPB3.3-SER-C) - EP Benchmark\n"); printf("\n Number of random numbers generated: %15s\n", size); verified = 0; //-------------------------------------------------------------------- // Compute the number of "batches" of random number pairs generated // per processor. Adjust if the number of processors does not evenly // divide the total number //-------------------------------------------------------------------- np = NN; //-------------------------------------------------------------------- // Call the random number generator functions and initialize // the x-array to reduce the effects of paging on the timings. // Also, call all mathematical functions that are used. Make // sure these initializations cannot be eliminated as dead code. //-------------------------------------------------------------------- vranlc(0, &dum[0], dum[1], &dum[2]); dum[0] = randlc(&dum[1], dum[2]); #pragma omp parallel for default(shared) private(i) for (i = 0; i < 2 * NK; i++) { x[i] = -1.0e99; } Mops = log(sqrt(fabs(MAX(1.0, 1.0)))); timer_clear(0); timer_clear(1); timer_clear(2); timer_start(0); t1 = A; vranlc(0, &t1, A, x); //-------------------------------------------------------------------- // Compute AN = A ^ (2 * NK) (mod 2^46). //-------------------------------------------------------------------- t1 = A; for (i = 0; i < MK + 1; i++) { t2 = randlc(&t1, t1); } an = t1; tt = S; gc = 0.0; sx = 0.0; sy = 0.0; for (i = 0; i < NQ; i++) { q[i] = 0.0; } //-------------------------------------------------------------------- // Each instance of this loop may be performed independently. We compute // the k offsets separately to take into account the fact that some nodes // have more numbers to generate than others //-------------------------------------------------------------------- k_offset = -1; for (k = 1; k <= np; k++) { kk = k_offset + k; t1 = S; t2 = an; // Find starting seed t1 for this kk. for (i = 1; i <= 100; i++) { ik = kk / 2; if ((2 * ik) != kk) t3 = randlc(&t1, t2); if (ik == 0) break; t3 = randlc(&t2, t2); kk = ik; } //-------------------------------------------------------------------- // Compute uniform pseudorandom numbers. //-------------------------------------------------------------------- vranlc(2 * NK, &t1, A, x); //-------------------------------------------------------------------- // Compute Gaussian deviates by acceptance-rejection method and // tally counts in concentri//square annuli. This loop is not // vectorizable. //-------------------------------------------------------------------- for (i = 0; i < NK; i++) { x1 = 2.0 * x[2 * i] - 1.0; x2 = 2.0 * x[2 * i + 1] - 1.0; t1 = x1 * x1 + x2 * x2; if (t1 <= 1.0) { t2 = sqrt(-2.0 * log(t1) / t1); t3 = (x1 * t2); t4 = (x2 * t2); l = MAX(fabs(t3), fabs(t4)); q[l] = q[l] + 1.0; sx = sx + t3; sy = sy + t4; } } } for (i = 0; i < NQ; i++) { gc = gc + q[i]; } timer_stop(0); tm = timer_read(0); nit = 0; verified = 1; if (M == 24) { sx_verify_value = -3.247834652034740e+3; sy_verify_value = -6.958407078382297e+3; } else if (M == 25) { sx_verify_value = -2.863319731645753e+3; sy_verify_value = -6.320053679109499e+3; } else if (M == 28) { sx_verify_value = -4.295875165629892e+3; sy_verify_value = -1.580732573678431e+4; } else if (M == 30) { sx_verify_value = 4.033815542441498e+4; sy_verify_value = -2.660669192809235e+4; } else if (M == 32) { sx_verify_value = 4.764367927995374e+4; sy_verify_value = -8.084072988043731e+4; } else if (M == 36) { sx_verify_value = 1.982481200946593e+5; sy_verify_value = -1.020596636361769e+5; } else if (M == 40) { sx_verify_value = -5.319717441530e+05; sy_verify_value = -3.688834557731e+05; } else { verified = 0; } if (verified) { sx_err = fabs((sx - sx_verify_value) / sx_verify_value); sy_err = fabs((sy - sy_verify_value) / sy_verify_value); verified = ((sx_err <= EPSILON) && (sy_err <= EPSILON)); } Mops = pow(2.0, M + 1) / tm / 1000000.0; printf("\nEP Benchmark Results:\n\n"); printf("CPU Time =%10.4lf\n", tm); printf("N = 2^%5d\n", M); printf("No. Gaussian Pairs = %15.0lf\n", gc); printf("Sums = %25.15lE %25.15lE\n", sx, sy); printf("Counts: \n"); for (i = 0; i < NQ; i++) { printf("%3d%15.0lf\n", i, q[i]); } print_results("EP", CLASS, M + 1, 0, 0, nit, tm, Mops, "Random numbers generated", verified); int exitValue = verified ? 0 : 1; return exitValue; } double randlc( double *x, double a ) { //-------------------------------------------------------------------- // // This routine returns a uniform pseudorandom double precision number in the // range (0, 1) by using the linear congruential generator // // x_{k+1} = a x_k (mod 2^46) // // where 0 < x_k < 2^46 and 0 < a < 2^46. This scheme generates 2^44 numbers // before repeating. The argument A is the same as 'a' in the above formula, // and X is the same as x_0. A and X must be odd double precision integers // in the range (1, 2^46). The returned value RANDLC is normalized to be // between 0 and 1, i.e. RANDLC = 2^(-46) * x_1. X is updated to contain // the new seed x_1, so that subsequent calls to RANDLC using the same // arguments will generate a continuous sequence. // // This routine should produce the same results on any computer with at least // 48 mantissa bits in double precision floating point data. On 64 bit // systems, double precision should be disabled. // // David H. Bailey October 26, 1990 // //-------------------------------------------------------------------- // r23 = pow(0.5, 23.0); //// pow(0.5, 23.0) = 1.1920928955078125e-07 // r46 = r23 * r23; // t23 = pow(2.0, 23.0); //// pow(2.0, 23.0) = 8.388608e+06 // t46 = t23 * t23; const double r23 = 1.1920928955078125e-07; const double r46 = r23 * r23; const double t23 = 8.388608e+06; const double t46 = t23 * t23; double t1, t2, t3, t4, a1, a2, x1, x2, z; double r; //-------------------------------------------------------------------- // Break A into two parts such that A = 2^23 * A1 + A2. //-------------------------------------------------------------------- t1 = r23 * a; a1 = (int) t1; a2 = a - t23 * a1; //-------------------------------------------------------------------- // Break X into two parts such that X = 2^23 * X1 + X2, compute // Z = A1 * X2 + A2 * X1 (mod 2^23), and then // X = 2^23 * Z + A2 * X2 (mod 2^46). //-------------------------------------------------------------------- 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; r = r46 * (*x); return r; } void vranlc( int n, double *x, double a, double y[] ) { //-------------------------------------------------------------------- // // This routine generates N uniform pseudorandom double precision numbers in // the range (0, 1) by using the linear congruential generator // // x_{k+1} = a x_k (mod 2^46) // // where 0 < x_k < 2^46 and 0 < a < 2^46. This scheme generates 2^44 numbers // before repeating. The argument A is the same as 'a' in the above formula, // and X is the same as x_0. A and X must be odd double precision integers // in the range (1, 2^46). The N results are placed in Y and are normalized // to be between 0 and 1. X is updated to contain the new seed, so that // subsequent calls to VRANLC using the same arguments will generate a // continuous sequence. If N is zero, only initialization is performed, and // the variables X, A and Y are ignored. // // This routine is the standard version designed for scalar or RISC systems. // However, it should produce the same results on any single processor // computer with at least 48 mantissa bits in double precision floating point // data. On 64 bit systems, double precision should be disabled. // //-------------------------------------------------------------------- // r23 = pow(0.5, 23.0); //// pow(0.5, 23.0) = 1.1920928955078125e-07 // r46 = r23 * r23; // t23 = pow(2.0, 23.0); //// pow(2.0, 23.0) = 8.388608e+06 // t46 = t23 * t23; const double r23 = 1.1920928955078125e-07; const double r46 = r23 * r23; const double t23 = 8.388608e+06; const double t46 = t23 * t23; double t1, t2, t3, t4, a1, a2, x1, x2, z; int i; //-------------------------------------------------------------------- // Break A into two parts such that A = 2^23 * A1 + A2. //-------------------------------------------------------------------- t1 = r23 * a; a1 = (int) t1; a2 = a - t23 * a1; //-------------------------------------------------------------------- // Generate N results. This loop is not vectorizable. //-------------------------------------------------------------------- for ( i = 0; i < n; i++ ) { //-------------------------------------------------------------------- // Break X into two parts such that X = 2^23 * X1 + X2, compute // Z = A1 * X2 + A2 * X1 (mod 2^23), and then // X = 2^23 * Z + A2 * X2 (mod 2^46). //-------------------------------------------------------------------- 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; y[i] = r46 * (*x); } return; } void print_results(char *name, char class, int n1, int n2, int n3, int niter, double t, double mops, char *optype, int verified) { char size[16]; int j; printf( "\n\n %s Benchmark Completed.\n", name ); printf( " Class = %12c\n", class ); // If this is not a grid-based problem (EP, FT, CG), then // we only print n1, which contains some measure of the // problem size. In that case, n2 and n3 are both zero. // Otherwise, we print the grid size n1xn2xn3 if ( ( n2 == 0 ) && ( n3 == 0 ) ) { if ( ( name[0] == 'E' ) && ( name[1] == 'P' ) ) { sprintf( size, "%15.0lf", pow(2.0, n1) ); j = 14; if ( size[j] == '.' ) { size[j] = ' '; j--; } size[j + 1] = '\0'; printf( " Size = %15s\n", size ); } else { printf( " Size = %12d\n", n1 ); } } else { printf( " Size = %4dx%4dx%4d\n", n1, n2, n3 ); } printf( " Iterations = %12d\n", niter ); printf( " Time in seconds = %12.2lf\n", t ); printf( " Mop/s total = %15.2lf\n", mops ); printf( " Operation type = %24s\n", optype ); if ( verified ) printf( " Verification = %12s\n", "SUCCESSFUL" ); else printf( " Verification = %12s\n", "UNSUCCESSFUL" ); } void wtime(double *t) { static int sec = -1; struct timeval tv; gettimeofday(&tv, (void *)0); if (sec < 0) sec = tv.tv_sec; *t = (tv.tv_sec - sec) + 1.0e-6 * tv.tv_usec; } /*****************************************************************/ /****** E L A P S E D _ T I M E ******/ /*****************************************************************/ double elapsed_time( void ) { double t; wtime( &t ); return ( t ); } /*****************************************************************/ /****** 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] ); }
ep.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <pthread.h> #include <math.h> #include <omp.h> #include "util.h" #define TRUE 1 #define FALSE 0 #define DEBUG 1 #define NMAX 1000 #define MAX_LINE 256 /*Intervalo [0, 255]*/ #define RGB_SIZE 256 #define PI 3.14159265359 long int x; int main(int argc, char **argv) { FILE *arq1, *arq2; char *infile, *outfile; char a[MAX_LINE]; int nr_inter, nr_proc/*, nr_threads*/; int i, j, k, cont, columns, lines, comp_max_val; double val, distribute; double gx, gy, g, angle; Pixel **M; /*Matriz de pixels*/ i = j = k = 0; /*Modo de usar*/ if (argc < 5) { printf("Modo de usar:\n\tArg1: nome do arquivo de entrada;\n\tArg2: nome do arquivo de saída\n\t"); printf("Arg3: número de iterações;\n\tArg4: número de processadores.\n\t"); exit(1); } infile = argv[1]; outfile = argv[2]; nr_inter = atoi(argv[3]); nr_proc = atoi(argv[4]); if (nr_proc <= 0) nr_proc = 1; arq1 = fopen(infile, "r"); if (arq1 == NULL) printf("Erro, não foi possível abrir o arquivo\n"); else { /*Read the input file*/ if (DEBUG) printf("Arquivo aberto!\n"); cont = 0; while ((a[0] = fgetc(arq1)) != EOF) { if (a[0] == '#' || a[0] == 'P') { fgets(a, MAX_LINE, arq1); } else if (cont == 0) { ungetc(a[0], arq1); fscanf(arq1,"%d %d\n", &columns, &lines); fscanf(arq1,"%d\n", &comp_max_val); cont++; /*Alocação das matrizes*/ M = (Pixel **) malloc(lines * sizeof(Pixel*)); for (i = 0; i < lines; i++) { M[i] = (Pixel *) malloc(columns * sizeof(Pixel)); } } else { ungetc(a[0], arq1); for (i = 0; i < lines; i++) { for (j = 0; j < columns; j++) { fscanf(arq1, "%lf %lf %lf", &M[i][j].R, &M[i][j].G, &M[i][j].B); M[i][j].R /= RGB_SIZE; M[i][j].G /= RGB_SIZE; /*M2[i][j].G = (2*PI * M2[i][j].G) / RGB_SIZE; */ M[i][j].B /= RGB_SIZE; M[i][j].ang = 2 * PI * M[i][j].G; /* Calcular Rx, Ry, Bx e By quando ler a entrada \/*/ M[i][j].Rx = horizontal_component(M[i][j].R, M[i][j].G); M[i][j].Bx = (-1) * horizontal_component(M[i][j].B, M[i][j].G); M[i][j].Ry = vertical_component(M[i][j].R, M[i][j].G); M[i][j].By = (-1) * vertical_component(M[i][j].B, M[i][j].G); } } break; } } } fclose(arq1); if (DEBUG) printf("Arquivo lido!\n"); /*IMPORTANTE: As bordas nunca se alteram.*/ for (k = 0; k < nr_inter; k++) { if (lines - 2 < nr_proc) nr_proc = 1; #pragma omp parallel firstprivate(lines, columns) private(i, j, val) num_threads(nr_proc) { int thread_num = omp_get_thread_num(); int num_threads = omp_get_num_threads(); int rest = (lines - 2) % num_threads; /*lines-2 porque elimina as bordas*/ int start, end; /*Divide os chunks para cada thread. O + 1 é para pular o zero, que é borda*/ /*Como sempre é menor estrito que end, não precisa se preocupar com a borda final*/ start = thread_num * (lines - 2) / num_threads + 1; if (thread_num != 0 && (thread_num - 1) < rest) start++; end = (thread_num + 1) * (lines - 2) / num_threads + 1; if (thread_num < rest) end++; for (i = start; i < end; i++) { /*Por causa da borda*/ for (j = 1; j < columns - 1; j++) { if (M[i][j].Rx > 0) { if (j != columns -1) { val = transfer(M[i][j+1].R, M[i][j].Rx); if (i != start && i != end) { M[i][j+1].Rx += val; M[i][j].Rx -= val; } else { #pragma omp critical { M[i][j+1].Rx += val; M[i][j].Rx -= val; } } } if (j != 1) { val = transfer(M[i][j-1].B, M[i][j].Bx); if (i != start && i != end) { /*Recebe no sentido oposto*/ M[i][j-1].Bx += val; M[i][j].Bx -= val; } else { #pragma omp critical { M[i][j-1].Bx += val; M[i][j].Bx -= val; } } } } else { /*Recebe um valor positivo*/ if (j != 1) { val = transfer(M[i][j-1].R, M[i][j].Rx); if (i != start && i != end) { M[i][j-1].Rx -= val; M[i][j].Rx += val; } else { #pragma omp critical { M[i][j-1].Rx -= val; M[i][j].Rx += val; } } } if (j != columns - 1) { val = transfer(M[i][j+1].B, M[i][j].Bx); if (i != start && i != end) { M[i][j+1].Bx -= val; /*Recebe no sentido oposto*/ M[i][j].Bx += val; } else { #pragma omp critical { M[i][j+1].Bx -= val; M[i][j].Bx += val; } } } } if (M[i][j].Ry > 0) { if (i != 1) { val = transfer(M[i-1][j].R, M[i][j].Ry); if (i != start && i != end) { M[i-1][j].Ry += val; M[i][j].Ry -= val; } else { #pragma omp critical { M[i-1][j].Ry += val; M[i][j].Ry -= val; } } } if (i != lines - 1) { val = transfer(M[i+1][j].B, M[i][j].By); if (i != start && i != end) { M[i+1][j].By += val; M[i][j].By -= val; } else { #pragma omp critical { M[i+1][j].By += val; M[i][j].By -= val; } } } } else { /*Recebe um valor positivo*/ if (i != lines - 1) { val = transfer(M[i+1][j].R, M[i][j].Ry); if (i != start && i != end) { M[i+1][j].Ry -= val; M[i][j].Ry += val; } else { #pragma omp critical { M[i+1][j].Ry -= val; M[i][j].Ry += val; } } } if (i != 1) { val = transfer(M[i-1][j].B, M[i][j].By); if (i != start && i != end) { M[i-1][j].By -= val; M[i][j].By += val; } else { #pragma omp critical { M[i-1][j].By -= val; M[i][j].By += val; } } } } } } } /*O bloco abaixo checa se os pixels vizinhos estouraram*/ for (i = 1; i < lines - 1; i++) { for (j = 1; j < columns - 1; j++) { /*Checa o R*/ if (M[i][j].R > 1) { distribute = (M[i][j].R - 1) / 4; M[i][j].R = 1; /*Os if's checam se os vizinhos não estão na borda e não serão estourados*/ if (i-1 > 0 && M[i-1][j].R + distribute < 1) M[i-1][j].R += distribute; if (i+1 < lines && M[i+1][j].R + distribute < 1) M[i+1][j].R += distribute; if (j-1 > 0 && M[i][j-1].R + distribute < 1) M[i][j-1].R += distribute; if (j+1 < columns && M[i][j+1].R + distribute < 1) M[i][j+1].R += distribute; } /*Checa o B*/ if (M[i][j].B > 1) { distribute = (M[i][j].B - 1) / 4; M[i][j].B = 1; /*Os if's checam se os vizinhos não estão na borda e não serão estourados*/ if (i-1 > 0 && M[i-1][j].B + distribute < 1) M[i-1][j].B += distribute; if (i+1 < lines && M[i+1][j].B + distribute < 1) M[i+1][j].B += distribute; if (j-1 > 0 && M[i][j-1].B + distribute < 1) M[i][j-1].B += distribute; if (j+1 < columns && M[i][j+1].B + distribute < 1) M[i][j+1].B += distribute; } } } /*Laço para atualizar G*/ for (i = 1; i < lines - 1; i++) { #pragma omp parallel for num_threads(nr_proc) schedule(dynamic) for (j = 1; j < columns - 1; j++) { gx = M[i][j].Rx + M[i][j].Bx; gy = M[i][j].Ry + M[i][j].By; g = sqrt((gx*gx) + (gy*gy)); angle = 2 * PI * g; M[i][j].ang += angle; M[i][j].G += g; if (M[i][j].ang > 2 * PI) M[i][j].ang -= 2*PI; } } } /*Escreve no arquivo de saída*/ arq2 = fopen(outfile, "w"); if (arq2 == NULL) printf("Erro, não foi possível abrir o arquivo\n"); else { fprintf(arq2, "P3\n%d %d\n255\n", columns, lines); for (i = 0; i < lines; i++) for (j = 0; j < columns; j++) fprintf(arq2, "%d %d %d \n", (int)(RGB_SIZE* M[i][j].R), (int)(RGB_SIZE* M[i][j].ang), (int)(RGB_SIZE* M[i][j].B)); fprintf(stdout, "A imagem foi salva no arquivo: %s\n", outfile); fclose(arq2); } for (i = 0; i < lines; i++) { free(M[i]); } free(M); return 0; }
sync.c
/** * \file * \brief BOMP barrier synchronization microbenchmark */ /* * Copyright (c) 2007, 2008, 2009, 2010, ETH Zurich. * All rights reserved. * * This file is distributed under the terms in the attached LICENSE file. * If you do not find this file, copies can be found by writing to: * ETH Zurich D-INFK, Haldeneggsteig 4, CH-8092 Zurich. Attn: Systems Group. */ #include <stdbool.h> #include <stdlib.h> #include <stdio.h> #include <stdint.h> #include <omp.h> #include <assert.h> #include <barrelfish/barrelfish.h> #include <trace/trace.h> #include <trace_definitions/trace_defs.h> #define PERIOD 2500000000UL #define ITERATIONS 10 #define STACK_SIZE (64 * 1024) struct workcnt { uint64_t cnt; } __attribute__ ((aligned (64))); int main(int argc, char *argv[]) { static struct workcnt workcnt[32]; static struct workcnt exittime[ITERATIONS]; int nthreads; int iterations = 0; uint64_t last; /* uint64_t last = rdtsc(); */ /* while(rdtsc() < last + PERIOD) { */ /* thread_yield(); */ /* } */ if(argc == 2) { nthreads = atoi(argv[1]); backend_span_domain(nthreads, STACK_SIZE); bomp_custom_init(); omp_set_num_threads(nthreads); } else { assert(!"Specify number of threads"); } #if CONFIG_TRACE errval_t err = trace_control(TRACE_EVENT(TRACE_SUBSYS_BOMP, TRACE_EVENT_BOMP_START, 0), TRACE_EVENT(TRACE_SUBSYS_BOMP, TRACE_EVENT_BOMP_STOP, 0), 0); assert(err_is_ok(err)); trace_event(TRACE_SUBSYS_BOMP, TRACE_EVENT_BOMP_START, 0); #endif /* bomp_synchronize(); */ last = rdtsc(); for(int iter = 0;; iter = (iter + 1) % ITERATIONS) { // Do some work #pragma omp parallel for(uint64_t i = 0;; i++) { #pragma omp barrier workcnt[omp_get_thread_num()].cnt++; #pragma omp master if(rdtsc() >= last + PERIOD) { #if CONFIG_TRACE trace_event(TRACE_SUBSYS_BOMP, TRACE_EVENT_BOMP_STOP, 0); char *buf = malloc(4096*4096); trace_dump(buf, 4096*4096, NULL); printf("%s\n", buf); abort(); #endif printf("%s, %lu: threads %d (%s), progress ", argv[0], rdtsc(), omp_get_num_threads(), omp_get_dynamic() ? "dynamic" : "static"); for(int n = 0; n < 32; n++) { printf("%lu ", workcnt[n].cnt); } printf("\n"); last += PERIOD; iterations++; if(iterations == 25) { printf("client done\n"); abort(); } if(exittime[iter].cnt == 0) { exittime[iter].cnt = i + 3; exittime[(iter + ITERATIONS - 2) % ITERATIONS].cnt = 0; } } if(exittime[iter].cnt != 0 && exittime[iter].cnt == i) { break; } } } }
par_amgdd_fac_cycle.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) ******************************************************************************/ #include "_hypre_parcsr_ls.h" HYPRE_Int hypre_BoomerAMGDD_FAC( void *amgdd_vdata, HYPRE_Int first_iteration ) { hypre_ParAMGDDData *amgdd_data = (hypre_ParAMGDDData*) amgdd_vdata; HYPRE_Int cycle_type = hypre_ParAMGDDDataFACCycleType(amgdd_data); HYPRE_Int start_level = hypre_ParAMGDDDataStartLevel(amgdd_data); if (cycle_type == 1 || cycle_type == 2) { hypre_BoomerAMGDD_FAC_Cycle(amgdd_vdata, start_level, cycle_type, first_iteration); } else if (cycle_type == 3) { hypre_BoomerAMGDD_FAC_FCycle(amgdd_vdata, first_iteration); } else { hypre_error_w_msg(HYPRE_ERROR_GENERIC, "WARNING: unknown AMG-DD FAC cycle type. Defaulting to 1 (V-cycle).\n"); hypre_ParAMGDDDataFACCycleType(amgdd_data) = 1; hypre_BoomerAMGDD_FAC_Cycle(amgdd_vdata, start_level, 1, first_iteration); } return hypre_error_flag; } HYPRE_Int hypre_BoomerAMGDD_FAC_Cycle( void *amgdd_vdata, HYPRE_Int level, HYPRE_Int cycle_type, HYPRE_Int first_iteration ) { hypre_ParAMGDDData *amgdd_data = (hypre_ParAMGDDData*) amgdd_vdata; hypre_ParAMGData *amg_data = hypre_ParAMGDDDataAMG(amgdd_data); hypre_AMGDDCompGrid **compGrid = hypre_ParAMGDDDataCompGrid(amgdd_data); HYPRE_Int num_levels = hypre_ParAMGDataNumLevels(amg_data); HYPRE_Int i; // Relax on the real nodes hypre_BoomerAMGDD_FAC_Relax(amgdd_vdata, level, 1); // Restrict the residual at all fine points (real and ghost) and set residual at coarse points not under the fine grid if (num_levels > 1) { hypre_BoomerAMGDD_FAC_Restrict(compGrid[level], compGrid[level + 1], first_iteration); hypre_AMGDDCompGridVectorSetConstantValues(hypre_AMGDDCompGridS(compGrid[level]), 0.0); hypre_AMGDDCompGridVectorSetConstantValues(hypre_AMGDDCompGridT(compGrid[level]), 0.0); // Either solve on the coarse level or recurse if (level + 1 == num_levels - 1) { hypre_BoomerAMGDD_FAC_Relax(amgdd_vdata, num_levels - 1, 3); } else for (i = 0; i < cycle_type; i++) { hypre_BoomerAMGDD_FAC_Cycle(amgdd_vdata, level + 1, cycle_type, first_iteration); first_iteration = 0; } // Interpolate up and relax hypre_BoomerAMGDD_FAC_Interpolate(compGrid[level], compGrid[level + 1]); } hypre_BoomerAMGDD_FAC_Relax(amgdd_vdata, level, 2); return hypre_error_flag; } HYPRE_Int hypre_BoomerAMGDD_FAC_FCycle( void *amgdd_vdata, HYPRE_Int first_iteration ) { hypre_ParAMGDDData *amgdd_data = (hypre_ParAMGDDData*) amgdd_vdata; hypre_ParAMGData *amg_data = hypre_ParAMGDDDataAMG(amgdd_data); hypre_AMGDDCompGrid **compGrid = hypre_ParAMGDDDataCompGrid(amgdd_data); HYPRE_Int num_levels = hypre_ParAMGDataNumLevels(amg_data); HYPRE_Int level; // ... work down to coarsest ... if (!first_iteration) { for (level = hypre_ParAMGDDDataStartLevel(amgdd_data); level < num_levels - 1; level++) { hypre_BoomerAMGDD_FAC_Restrict(compGrid[level], compGrid[level + 1], 0); hypre_AMGDDCompGridVectorSetConstantValues(hypre_AMGDDCompGridS(compGrid[level]), 0.0); hypre_AMGDDCompGridVectorSetConstantValues(hypre_AMGDDCompGridT(compGrid[level]), 0.0); } } // ... solve on coarsest level ... hypre_BoomerAMGDD_FAC_Relax(amgdd_vdata, num_levels - 1, 3); // ... and work back up to the finest for (level = num_levels - 2; level > -1; level--) { // Interpolate up and relax hypre_BoomerAMGDD_FAC_Interpolate(compGrid[level], compGrid[level + 1]); // V-cycle hypre_BoomerAMGDD_FAC_Cycle(amgdd_vdata, level, 1, 0); } return hypre_error_flag; } HYPRE_Int hypre_BoomerAMGDD_FAC_Interpolate( hypre_AMGDDCompGrid *compGrid_f, hypre_AMGDDCompGrid *compGrid_c ) { hypre_AMGDDCompGridMatvec(1.0, hypre_AMGDDCompGridP(compGrid_f), hypre_AMGDDCompGridU(compGrid_c), 1.0, hypre_AMGDDCompGridU(compGrid_f)); return hypre_error_flag; } HYPRE_Int hypre_BoomerAMGDD_FAC_Restrict( hypre_AMGDDCompGrid *compGrid_f, hypre_AMGDDCompGrid *compGrid_c, HYPRE_Int first_iteration ) { // Recalculate residual on coarse grid if (!first_iteration) { hypre_AMGDDCompGridMatvec(-1.0, hypre_AMGDDCompGridA(compGrid_c), hypre_AMGDDCompGridU(compGrid_c), 1.0, hypre_AMGDDCompGridF(compGrid_c)); } // Get update: s_l <- A_lt_l + s_l hypre_AMGDDCompGridMatvec(1.0, hypre_AMGDDCompGridA(compGrid_f), hypre_AMGDDCompGridT(compGrid_f), 1.0, hypre_AMGDDCompGridS(compGrid_f)); // If we need to preserve the updates on the next level if (hypre_AMGDDCompGridS(compGrid_c)) { hypre_AMGDDCompGridMatvec(1.0, hypre_AMGDDCompGridR(compGrid_f), hypre_AMGDDCompGridS(compGrid_f), 0.0, hypre_AMGDDCompGridS(compGrid_c)); // Subtract restricted update from recalculated residual: f_{l+1} <- f_{l+1} - s_{l+1} hypre_AMGDDCompGridVectorAxpy(-1.0, hypre_AMGDDCompGridS(compGrid_c), hypre_AMGDDCompGridF(compGrid_c)); } else { // Restrict and subtract update from recalculated residual: f_{l+1} <- f_{l+1} - P_l^Ts_l hypre_AMGDDCompGridMatvec(-1.0, hypre_AMGDDCompGridR(compGrid_f), hypre_AMGDDCompGridS(compGrid_f), 1.0, hypre_AMGDDCompGridF(compGrid_c)); } // Zero out initial guess on coarse grid hypre_AMGDDCompGridVectorSetConstantValues(hypre_AMGDDCompGridU(compGrid_c), 0.0); return hypre_error_flag; } HYPRE_Int hypre_BoomerAMGDD_FAC_Relax( void *amgdd_vdata, HYPRE_Int level, HYPRE_Int cycle_param ) { hypre_ParAMGDDData *amgdd_data = (hypre_ParAMGDDData*) amgdd_vdata; hypre_AMGDDCompGrid *compGrid = hypre_ParAMGDDDataCompGrid(amgdd_data)[level]; HYPRE_Int numRelax = hypre_ParAMGDDDataFACNumRelax(amgdd_data); HYPRE_Int i; if (hypre_AMGDDCompGridT(compGrid) || hypre_AMGDDCompGridQ(compGrid)) { hypre_AMGDDCompGridVectorCopy(hypre_AMGDDCompGridU(compGrid), hypre_AMGDDCompGridTemp(compGrid)); hypre_AMGDDCompGridVectorScale(-1.0, hypre_AMGDDCompGridTemp(compGrid)); } for (i = 0; i < numRelax; i++) { (*hypre_ParAMGDDDataUserFACRelaxation(amgdd_data))(amgdd_vdata, level, cycle_param); } if (hypre_AMGDDCompGridT(compGrid) || hypre_AMGDDCompGridQ(compGrid)) { hypre_AMGDDCompGridVectorAxpy(1.0, hypre_AMGDDCompGridU(compGrid), hypre_AMGDDCompGridTemp(compGrid)); if (hypre_AMGDDCompGridT(compGrid)) { hypre_AMGDDCompGridVectorAxpy(1.0, hypre_AMGDDCompGridTemp(compGrid), hypre_AMGDDCompGridT(compGrid)); } if (hypre_AMGDDCompGridQ(compGrid)) { hypre_AMGDDCompGridVectorAxpy(1.0, hypre_AMGDDCompGridTemp(compGrid), hypre_AMGDDCompGridQ(compGrid)); } } return hypre_error_flag; } HYPRE_Int hypre_BoomerAMGDD_FAC_Jacobi( void *amgdd_vdata, HYPRE_Int level, HYPRE_Int cycle_param ) { #if defined(HYPRE_USING_CUDA) || defined(HYPRE_USING_HIP) || defined(HYPRE_USING_SYCL) hypre_ParAMGDDData *amgdd_data = (hypre_ParAMGDDData*) amgdd_vdata; hypre_AMGDDCompGrid *compGrid = hypre_ParAMGDDDataCompGrid(amgdd_data)[level]; HYPRE_MemoryLocation memory_location = hypre_AMGDDCompGridMemoryLocation(compGrid); HYPRE_ExecutionPolicy exec = hypre_GetExecPolicy1(memory_location); if (exec == HYPRE_EXEC_DEVICE) { hypre_BoomerAMGDD_FAC_JacobiDevice(amgdd_vdata, level); } else #endif { hypre_BoomerAMGDD_FAC_JacobiHost(amgdd_vdata, level); } return hypre_error_flag; } HYPRE_Int hypre_BoomerAMGDD_FAC_JacobiHost( void *amgdd_vdata, HYPRE_Int level ) { hypre_ParAMGDDData *amgdd_data = (hypre_ParAMGDDData*) amgdd_vdata; hypre_AMGDDCompGrid *compGrid = hypre_ParAMGDDDataCompGrid(amgdd_data)[level]; HYPRE_Real relax_weight = hypre_ParAMGDDDataFACRelaxWeight(amgdd_data); HYPRE_MemoryLocation memory_location = hypre_AMGDDCompGridMemoryLocation(compGrid); hypre_AMGDDCompGridMatrix *A = hypre_AMGDDCompGridA(compGrid); hypre_AMGDDCompGridVector *f = hypre_AMGDDCompGridF(compGrid); hypre_AMGDDCompGridVector *u = hypre_AMGDDCompGridU(compGrid); hypre_CSRMatrix *diag; HYPRE_Int total_real_nodes; HYPRE_Int i, j; // Calculate l1_norms if necessary (right now, I'm just using this vector for the diagonal of A and doing straight ahead Jacobi) if (!hypre_AMGDDCompGridL1Norms(compGrid)) { total_real_nodes = hypre_AMGDDCompGridNumOwnedNodes(compGrid) + hypre_AMGDDCompGridNumNonOwnedRealNodes(compGrid); hypre_AMGDDCompGridL1Norms(compGrid) = hypre_CTAlloc(HYPRE_Real, total_real_nodes, memory_location); diag = hypre_AMGDDCompGridMatrixOwnedDiag(A); for (i = 0; i < hypre_AMGDDCompGridNumOwnedNodes(compGrid); i++) { for (j = hypre_CSRMatrixI(diag)[i]; j < hypre_CSRMatrixI(diag)[i + 1]; j++) { // hypre_AMGDDCompGridL1Norms(compGrid)[i] += fabs(hypre_CSRMatrixData(diag)[j]); if (hypre_CSRMatrixJ(diag)[j] == i) { hypre_AMGDDCompGridL1Norms(compGrid)[i] = hypre_CSRMatrixData(diag)[j]; } } } diag = hypre_AMGDDCompGridMatrixNonOwnedDiag(A); for (i = 0; i < hypre_AMGDDCompGridNumNonOwnedRealNodes(compGrid); i++) { for (j = hypre_CSRMatrixI(diag)[i]; j < hypre_CSRMatrixI(diag)[i + 1]; j++) { // hypre_AMGDDCompGridL1Norms(compGrid)[i + hypre_AMGDDCompGridNumOwnedNodes(compGrid)] += fabs(hypre_CSRMatrixData(diag)[j]); if (hypre_CSRMatrixJ(diag)[j] == i) { hypre_AMGDDCompGridL1Norms(compGrid)[i + hypre_AMGDDCompGridNumOwnedNodes( compGrid)] = hypre_CSRMatrixData(diag)[j]; } } } } // Allocate temporary vector if necessary if (!hypre_AMGDDCompGridTemp2(compGrid)) { hypre_AMGDDCompGridTemp2(compGrid) = hypre_AMGDDCompGridVectorCreate(); hypre_AMGDDCompGridVectorInitialize(hypre_AMGDDCompGridTemp2(compGrid), hypre_AMGDDCompGridNumOwnedNodes(compGrid), hypre_AMGDDCompGridNumNonOwnedNodes(compGrid), hypre_AMGDDCompGridNumNonOwnedRealNodes(compGrid)); } hypre_AMGDDCompGridVectorCopy(f, hypre_AMGDDCompGridTemp2(compGrid)); hypre_AMGDDCompGridMatvec(-relax_weight, A, u, relax_weight, hypre_AMGDDCompGridTemp2(compGrid)); for (i = 0; i < hypre_AMGDDCompGridNumOwnedNodes(compGrid); i++) { hypre_VectorData(hypre_AMGDDCompGridVectorOwned(u))[i] += hypre_VectorData(hypre_AMGDDCompGridVectorOwned(hypre_AMGDDCompGridTemp2(compGrid)))[i] / hypre_AMGDDCompGridL1Norms(compGrid)[i]; } for (i = 0; i < hypre_AMGDDCompGridNumNonOwnedRealNodes(compGrid); i++) { hypre_VectorData(hypre_AMGDDCompGridVectorNonOwned(u))[i] += hypre_VectorData(hypre_AMGDDCompGridVectorNonOwned(hypre_AMGDDCompGridTemp2(compGrid)))[i] / hypre_AMGDDCompGridL1Norms(compGrid)[i + hypre_AMGDDCompGridNumOwnedNodes(compGrid)]; } return hypre_error_flag; } HYPRE_Int hypre_BoomerAMGDD_FAC_GaussSeidel( void *amgdd_vdata, HYPRE_Int level, HYPRE_Int cycle_param ) { hypre_ParAMGDDData *amgdd_data = (hypre_ParAMGDDData*) amgdd_vdata; hypre_AMGDDCompGrid *compGrid = hypre_ParAMGDDDataCompGrid(amgdd_data)[level]; hypre_AMGDDCompGridMatrix *A = hypre_AMGDDCompGridA(compGrid); hypre_AMGDDCompGridVector *f = hypre_AMGDDCompGridF(compGrid); hypre_AMGDDCompGridVector *u = hypre_AMGDDCompGridU(compGrid); hypre_CSRMatrix *owned_diag = hypre_AMGDDCompGridMatrixOwnedDiag(A); hypre_CSRMatrix *owned_offd = hypre_AMGDDCompGridMatrixOwnedOffd(A); hypre_CSRMatrix *nonowned_diag = hypre_AMGDDCompGridMatrixNonOwnedDiag(A); hypre_CSRMatrix *nonowned_offd = hypre_AMGDDCompGridMatrixNonOwnedOffd(A); HYPRE_Complex *u_owned_data = hypre_VectorData(hypre_AMGDDCompGridVectorOwned(u)); HYPRE_Complex *u_nonowned_data = hypre_VectorData(hypre_AMGDDCompGridVectorNonOwned(u)); HYPRE_Complex *f_owned_data = hypre_VectorData(hypre_AMGDDCompGridVectorOwned(f)); HYPRE_Complex *f_nonowned_data = hypre_VectorData(hypre_AMGDDCompGridVectorNonOwned(f)); HYPRE_Int i, j; // loop variables HYPRE_Complex diagonal; // placeholder for the diagonal of A // Do Gauss-Seidel relaxation on the owned nodes for (i = 0; i < hypre_AMGDDCompGridNumOwnedNodes(compGrid); i++) { // Initialize u as RHS u_owned_data[i] = f_owned_data[i]; diagonal = 0.0; // Loop over diag entries for (j = hypre_CSRMatrixI(owned_diag)[i]; j < hypre_CSRMatrixI(owned_diag)[i + 1]; j++) { if (hypre_CSRMatrixJ(owned_diag)[j] == i) { diagonal = hypre_CSRMatrixData(owned_diag)[j]; } else { u_owned_data[i] -= hypre_CSRMatrixData(owned_diag)[j] * u_owned_data[ hypre_CSRMatrixJ( owned_diag)[j] ]; } } // Loop over offd entries for (j = hypre_CSRMatrixI(owned_offd)[i]; j < hypre_CSRMatrixI(owned_offd)[i + 1]; j++) { u_owned_data[i] -= hypre_CSRMatrixData(owned_offd)[j] * u_nonowned_data[ hypre_CSRMatrixJ( owned_offd)[j] ]; } // Divide by diagonal if (diagonal == 0.0) { hypre_error_w_msg(HYPRE_ERROR_GENERIC, "WARNING: Divide by zero diagonal in hypre_BoomerAMGDD_FAC_GaussSeidel().\n"); } u_owned_data[i] /= diagonal; } // Do Gauss-Seidel relaxation on the nonowned nodes for (i = 0; i < hypre_AMGDDCompGridNumNonOwnedRealNodes(compGrid); i++) { // Initialize u as RHS u_nonowned_data[i] = f_nonowned_data[i]; diagonal = 0.0; // Loop over diag entries for (j = hypre_CSRMatrixI(nonowned_diag)[i]; j < hypre_CSRMatrixI(nonowned_diag)[i + 1]; j++) { if (hypre_CSRMatrixJ(nonowned_diag)[j] == i) { diagonal = hypre_CSRMatrixData(nonowned_diag)[j]; } else { u_nonowned_data[i] -= hypre_CSRMatrixData(nonowned_diag)[j] * u_nonowned_data[ hypre_CSRMatrixJ( nonowned_diag)[j] ]; } } // Loop over offd entries for (j = hypre_CSRMatrixI(nonowned_offd)[i]; j < hypre_CSRMatrixI(nonowned_offd)[i + 1]; j++) { u_nonowned_data[i] -= hypre_CSRMatrixData(nonowned_offd)[j] * u_owned_data[ hypre_CSRMatrixJ( nonowned_offd)[j] ]; } // Divide by diagonal if (diagonal == 0.0) { hypre_error_w_msg(HYPRE_ERROR_GENERIC, "WARNING: Divide by zero diagonal in hypre_BoomerAMGDD_FAC_GaussSeidel().\n"); } u_nonowned_data[i] /= diagonal; } return hypre_error_flag; } HYPRE_Int hypre_BoomerAMGDD_FAC_OrderedGaussSeidel( void *amgdd_vdata, HYPRE_Int level, HYPRE_Int cycle_param ) { hypre_ParAMGDDData *amgdd_data = (hypre_ParAMGDDData*) amgdd_vdata; hypre_AMGDDCompGrid *compGrid = hypre_ParAMGDDDataCompGrid(amgdd_data)[level]; hypre_AMGDDCompGridMatrix *A = hypre_AMGDDCompGridA(compGrid); hypre_AMGDDCompGridVector *f = hypre_AMGDDCompGridF(compGrid); hypre_AMGDDCompGridVector *u = hypre_AMGDDCompGridU(compGrid); HYPRE_Int unordered_i, i, j; // loop variables HYPRE_Complex diagonal; // placeholder for the diagonal of A if (!hypre_AMGDDCompGridOwnedRelaxOrdering(compGrid)) { hypre_AMGDDCompGridOwnedRelaxOrdering(compGrid) = hypre_CTAlloc(HYPRE_Int, hypre_AMGDDCompGridNumOwnedNodes(compGrid), hypre_AMGDDCompGridMemoryLocation(compGrid)); hypre_topo_sort(hypre_CSRMatrixI(hypre_AMGDDCompGridMatrixOwnedDiag(hypre_AMGDDCompGridA( compGrid))), hypre_CSRMatrixJ(hypre_AMGDDCompGridMatrixOwnedDiag(hypre_AMGDDCompGridA(compGrid))), hypre_CSRMatrixData(hypre_AMGDDCompGridMatrixOwnedDiag(hypre_AMGDDCompGridA(compGrid))), hypre_AMGDDCompGridOwnedRelaxOrdering(compGrid), hypre_AMGDDCompGridNumOwnedNodes(compGrid)); } if (!hypre_AMGDDCompGridNonOwnedRelaxOrdering(compGrid)) { hypre_AMGDDCompGridNonOwnedRelaxOrdering(compGrid) = hypre_CTAlloc(HYPRE_Int, hypre_AMGDDCompGridNumNonOwnedNodes(compGrid), hypre_AMGDDCompGridMemoryLocation(compGrid)); hypre_topo_sort(hypre_CSRMatrixI(hypre_AMGDDCompGridMatrixNonOwnedDiag(hypre_AMGDDCompGridA( compGrid))), hypre_CSRMatrixJ(hypre_AMGDDCompGridMatrixNonOwnedDiag(hypre_AMGDDCompGridA(compGrid))), hypre_CSRMatrixData(hypre_AMGDDCompGridMatrixNonOwnedDiag(hypre_AMGDDCompGridA(compGrid))), hypre_AMGDDCompGridNonOwnedRelaxOrdering(compGrid), hypre_AMGDDCompGridNumNonOwnedNodes(compGrid)); } // Get all the info HYPRE_Complex *u_owned_data = hypre_VectorData(hypre_AMGDDCompGridVectorOwned(u)); HYPRE_Complex *u_nonowned_data = hypre_VectorData(hypre_AMGDDCompGridVectorNonOwned(u)); HYPRE_Complex *f_owned_data = hypre_VectorData(hypre_AMGDDCompGridVectorOwned(f)); HYPRE_Complex *f_nonowned_data = hypre_VectorData(hypre_AMGDDCompGridVectorNonOwned(f)); hypre_CSRMatrix *owned_diag = hypre_AMGDDCompGridMatrixOwnedDiag(A); hypre_CSRMatrix *owned_offd = hypre_AMGDDCompGridMatrixOwnedOffd(A); hypre_CSRMatrix *nonowned_diag = hypre_AMGDDCompGridMatrixNonOwnedDiag(A); hypre_CSRMatrix *nonowned_offd = hypre_AMGDDCompGridMatrixNonOwnedOffd(A); // Do Gauss-Seidel relaxation on the nonowned real nodes for (unordered_i = 0; unordered_i < hypre_AMGDDCompGridNumNonOwnedRealNodes(compGrid); unordered_i++) { i = hypre_AMGDDCompGridNonOwnedRelaxOrdering(compGrid)[unordered_i]; // Initialize u as RHS u_nonowned_data[i] = f_nonowned_data[i]; diagonal = 0.0; // Loop over diag entries for (j = hypre_CSRMatrixI(nonowned_diag)[i]; j < hypre_CSRMatrixI(nonowned_diag)[i + 1]; j++) { if (hypre_CSRMatrixJ(nonowned_diag)[j] == i) { diagonal = hypre_CSRMatrixData(nonowned_diag)[j]; } else { u_nonowned_data[i] -= hypre_CSRMatrixData(nonowned_diag)[j] * u_nonowned_data[ hypre_CSRMatrixJ( nonowned_diag)[j] ]; } } // Loop over offd entries for (j = hypre_CSRMatrixI(nonowned_offd)[i]; j < hypre_CSRMatrixI(nonowned_offd)[i + 1]; j++) { u_nonowned_data[i] -= hypre_CSRMatrixData(nonowned_offd)[j] * u_owned_data[ hypre_CSRMatrixJ( nonowned_offd)[j] ]; } // Divide by diagonal if (diagonal == 0.0) { hypre_error_w_msg(HYPRE_ERROR_GENERIC, "WARNING: Divide by zero diagonal in hypre_BoomerAMGDD_FAC_OrderedGaussSeidel().\n"); } u_nonowned_data[i] /= diagonal; } // Do Gauss-Seidel relaxation on the owned nodes for (unordered_i = 0; unordered_i < hypre_AMGDDCompGridNumOwnedNodes(compGrid); unordered_i++) { i = hypre_AMGDDCompGridOwnedRelaxOrdering(compGrid)[unordered_i]; // Initialize u as RHS u_owned_data[i] = f_owned_data[i]; diagonal = 0.0; // Loop over diag entries for (j = hypre_CSRMatrixI(owned_diag)[i]; j < hypre_CSRMatrixI(owned_diag)[i + 1]; j++) { if (hypre_CSRMatrixJ(owned_diag)[j] == i) { diagonal = hypre_CSRMatrixData(owned_diag)[j]; } else { u_owned_data[i] -= hypre_CSRMatrixData(owned_diag)[j] * u_owned_data[ hypre_CSRMatrixJ( owned_diag)[j] ]; } } // Loop over offd entries for (j = hypre_CSRMatrixI(owned_offd)[i]; j < hypre_CSRMatrixI(owned_offd)[i + 1]; j++) { u_owned_data[i] -= hypre_CSRMatrixData(owned_offd)[j] * u_nonowned_data[ hypre_CSRMatrixJ( owned_offd)[j] ]; } // Divide by diagonal if (diagonal == 0.0) { hypre_error_w_msg(HYPRE_ERROR_GENERIC, "WARNING: Divide by zero diagonal in hypre_BoomerAMGDD_FAC_OrderedGaussSeidel().\n"); } u_owned_data[i] /= diagonal; } return hypre_error_flag; } HYPRE_Int hypre_BoomerAMGDD_FAC_CFL1Jacobi( void *amgdd_vdata, HYPRE_Int level, HYPRE_Int cycle_param ) { #if defined(HYPRE_USING_CUDA) || defined(HYPRE_USING_HIP) || defined(HYPRE_USING_SYCL) hypre_ParAMGDDData *amgdd_data = (hypre_ParAMGDDData*) amgdd_vdata; hypre_AMGDDCompGrid *compGrid = hypre_ParAMGDDDataCompGrid(amgdd_data)[level]; HYPRE_MemoryLocation memory_location = hypre_AMGDDCompGridMemoryLocation(compGrid); HYPRE_ExecutionPolicy exec = hypre_GetExecPolicy1(memory_location); if (exec == HYPRE_EXEC_DEVICE) { if (cycle_param == 1) { hypre_BoomerAMGDD_FAC_CFL1JacobiDevice(amgdd_vdata, level, 1); hypre_BoomerAMGDD_FAC_CFL1JacobiDevice(amgdd_vdata, level, -1); } else if (cycle_param == 2) { hypre_BoomerAMGDD_FAC_CFL1JacobiDevice(amgdd_vdata, level, -1); hypre_BoomerAMGDD_FAC_CFL1JacobiDevice(amgdd_vdata, level, 1); } else { hypre_BoomerAMGDD_FAC_CFL1JacobiDevice(amgdd_vdata, level, -1); } } else #endif { if (cycle_param == 1) { hypre_BoomerAMGDD_FAC_CFL1JacobiHost(amgdd_vdata, level, 1); hypre_BoomerAMGDD_FAC_CFL1JacobiHost(amgdd_vdata, level, -1); } else if (cycle_param == 2) { hypre_BoomerAMGDD_FAC_CFL1JacobiHost(amgdd_vdata, level, -1); hypre_BoomerAMGDD_FAC_CFL1JacobiHost(amgdd_vdata, level, 1); } else { hypre_BoomerAMGDD_FAC_CFL1JacobiHost(amgdd_vdata, level, -1); } } return hypre_error_flag; } HYPRE_Int hypre_BoomerAMGDD_FAC_CFL1JacobiHost( void *amgdd_vdata, HYPRE_Int level, HYPRE_Int relax_set ) { hypre_ParAMGDDData *amgdd_data = (hypre_ParAMGDDData*) amgdd_vdata; hypre_AMGDDCompGrid *compGrid = hypre_ParAMGDDDataCompGrid(amgdd_data)[level]; HYPRE_Real relax_weight = hypre_ParAMGDDDataFACRelaxWeight(amgdd_data); hypre_CSRMatrix *owned_diag = hypre_AMGDDCompGridMatrixOwnedDiag(hypre_AMGDDCompGridA( compGrid)); hypre_CSRMatrix *owned_offd = hypre_AMGDDCompGridMatrixOwnedOffd(hypre_AMGDDCompGridA( compGrid)); hypre_CSRMatrix *nonowned_diag = hypre_AMGDDCompGridMatrixNonOwnedDiag(hypre_AMGDDCompGridA( compGrid)); hypre_CSRMatrix *nonowned_offd = hypre_AMGDDCompGridMatrixNonOwnedOffd(hypre_AMGDDCompGridA( compGrid)); HYPRE_Complex *owned_u = hypre_VectorData(hypre_AMGDDCompGridVectorOwned( hypre_AMGDDCompGridU(compGrid))); HYPRE_Complex *nonowned_u = hypre_VectorData(hypre_AMGDDCompGridVectorNonOwned( hypre_AMGDDCompGridU(compGrid))); HYPRE_Complex *owned_f = hypre_VectorData(hypre_AMGDDCompGridVectorOwned( hypre_AMGDDCompGridF(compGrid))); HYPRE_Complex *nonowned_f = hypre_VectorData(hypre_AMGDDCompGridVectorNonOwned( hypre_AMGDDCompGridF(compGrid))); HYPRE_Real *l1_norms = hypre_AMGDDCompGridL1Norms(compGrid); HYPRE_Int *cf_marker = hypre_AMGDDCompGridCFMarkerArray(compGrid); HYPRE_Complex *owned_tmp; HYPRE_Complex *nonowned_tmp; HYPRE_Int i, j; HYPRE_Real res; /*----------------------------------------------------------------- * Create and initialize Temp2 vector if not done before. *-----------------------------------------------------------------*/ if (!hypre_AMGDDCompGridTemp2(compGrid)) { hypre_AMGDDCompGridTemp2(compGrid) = hypre_AMGDDCompGridVectorCreate(); hypre_AMGDDCompGridVectorInitialize(hypre_AMGDDCompGridTemp2(compGrid), hypre_AMGDDCompGridNumOwnedNodes(compGrid), hypre_AMGDDCompGridNumNonOwnedNodes(compGrid), hypre_AMGDDCompGridNumNonOwnedRealNodes(compGrid)); } owned_tmp = hypre_VectorData(hypre_AMGDDCompGridVectorOwned(hypre_AMGDDCompGridTemp2(compGrid))); nonowned_tmp = hypre_VectorData(hypre_AMGDDCompGridVectorNonOwned(hypre_AMGDDCompGridTemp2( compGrid))); /*----------------------------------------------------------------- * Copy current approximation into temporary vector. *-----------------------------------------------------------------*/ #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < hypre_AMGDDCompGridNumOwnedNodes(compGrid); i++) { owned_tmp[i] = owned_u[i]; } #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < hypre_AMGDDCompGridNumNonOwnedNodes(compGrid); i++) { nonowned_tmp[i] = nonowned_u[i]; } /*----------------------------------------------------------------- * Relax only C or F points as determined by relax_points. *-----------------------------------------------------------------*/ #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i,j,res) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < hypre_AMGDDCompGridNumOwnedNodes(compGrid); i++) { if (cf_marker[i] == relax_set) { res = owned_f[i]; for (j = hypre_CSRMatrixI(owned_diag)[i]; j < hypre_CSRMatrixI(owned_diag)[i + 1]; j++) { res -= hypre_CSRMatrixData(owned_diag)[j] * owned_tmp[ hypre_CSRMatrixJ(owned_diag)[j] ]; } for (j = hypre_CSRMatrixI(owned_offd)[i]; j < hypre_CSRMatrixI(owned_offd)[i + 1]; j++) { res -= hypre_CSRMatrixData(owned_offd)[j] * nonowned_tmp[ hypre_CSRMatrixJ(owned_offd)[j] ]; } owned_u[i] += (relax_weight * res) / l1_norms[i]; } } for (i = 0; i < hypre_AMGDDCompGridNumNonOwnedRealNodes(compGrid); i++) { if (cf_marker[i + hypre_AMGDDCompGridNumOwnedNodes(compGrid)] == relax_set) { res = nonowned_f[i]; for (j = hypre_CSRMatrixI(nonowned_diag)[i]; j < hypre_CSRMatrixI(nonowned_diag)[i + 1]; j++) { res -= hypre_CSRMatrixData(nonowned_diag)[j] * nonowned_tmp[ hypre_CSRMatrixJ(nonowned_diag)[j] ]; } for (j = hypre_CSRMatrixI(nonowned_offd)[i]; j < hypre_CSRMatrixI(nonowned_offd)[i + 1]; j++) { res -= hypre_CSRMatrixData(nonowned_offd)[j] * owned_tmp[ hypre_CSRMatrixJ(nonowned_offd)[j] ]; } nonowned_u[i] += (relax_weight * res) / l1_norms[i + hypre_AMGDDCompGridNumOwnedNodes(compGrid)]; } } return hypre_error_flag; }
NALF-SFCM.h
// Fully normalized associated Legendre functions calculated by standard forward column methods // Holmes, S. A., & Featherstone, W. E. (2002). // A unified approach to the Clenshaw summation and the recursive computation of very high degree and order normalised associated Legendre functions. // Journal of Geodesy, 76(5), 279–299. https://doi.org/10.1007/s00190-002-0216-2 // Author: Yi Zhang (zhangyi.cugwuhan@gmail.com) #ifndef _NALF_SFCM_H #define _NALF_SFCM_H #include "sysDefine.h" //计算向前列推的系数 避免重复计算 这里不要使用vector at() 速度比较慢 直接使用[] 注意调用size()函数也会降低执行效率 _2dArray get_a_nm_array(int MaxOrder) { int i,j; _2dArray cs; cs.resize(MaxOrder); for (i = 0; i < MaxOrder; i++) cs[i].resize(i+1); //向下列推计算 #pragma omp parallel for private(i,j) schedule(guided) for (j = 0; j < MaxOrder; j++) { cs[j][j] = 0; //对角线上的值直接给0 反正用不到 for (i = j+1; i < MaxOrder; i++) { cs[i][j] = sqrt(((2.0*i-1)*(2.0*i+1))/((i-j)*(i+j))); } } return cs; } _2dArray get_b_nm_array(int MaxOrder) { int i,j; _2dArray cs; cs.resize(MaxOrder); for (i = 0; i < MaxOrder; i++) cs[i].resize(i+1); //向下列推计算 #pragma omp parallel for private(i,j) schedule(guided) for (j = 0; j < MaxOrder; j++) { cs[j][j] = 0; //对角线上的值直接给0 反正用不到 for (i = j+1; i < MaxOrder; i++) { cs[i][j] = sqrt(((2.0*i+1)*(i+j-1)*(i-j-1))/((i-j)*(i+j)*(2.0*i-3))); } } return cs; } // 计算标准前向列推法计算规格化的勒让德多项式 输入参数为需要计算的最大阶次MaxOrder 余纬度theta(度) 返回一个下半三角二维数组 // 最大维度为MaxOrder+1,二维数组中行数代表阶数列数为次数 _2dArray NALF_SFCM(int MaxOrder,_2dArray a_nm,_2dArray b_nm,double theta) { //声明数组 初始化一个下半三角二维数组 _2dArray nalf; nalf.resize(MaxOrder); for (int i = 0; i < MaxOrder; i++) nalf.at(i).resize(i+1); //赋初值给前两个对角线上的值 nalf.at(0).at(0) = 1.0; nalf.at(1).at(1) = sqrt(3.0)*sin(theta*pi/180.0); //计算对角线上的值 递归计算 不能并行 for (int i = 2; i < nalf.size(); i++) nalf.at(i).at(i) = sin(theta*pi/180.0)*sqrt(0.5*(2.0*i+1)/i)*nalf.at(i-1).at(i-1); //声明系数和迭代变量 int i,j; double Pn_2m,Pn_1m; //Pn-1,m Pn-2,m //这里可以使用并行加速计算外层循环 内层计算因为是递归计算因此不能并行 #pragma omp parallel for private(i,j,Pn_2m,Pn_1m) schedule(guided) for (j = 0; j < nalf.size()-1; j++) { Pn_2m = 0; Pn_1m = nalf.at(j).at(j); for (i = j+1; i < nalf.size(); i++) { nalf.at(i).at(j) = a_nm.at(i).at(j)*cos(theta*pi/180.0)*Pn_1m - b_nm.at(i).at(j)*Pn_2m; Pn_2m = nalf.at(i-1).at(j); Pn_1m = nalf.at(i).at(j); } } return nalf; } // 计算标准前向列推法计算规格化的勒让德多项式 输入参数 一个下半三角二维矩阵 余纬度theta(度) 无返回值 // 二维数组中行数代表阶数列数为次数 void NALF_SFCM2(_2dArray& nalf,_2dArray a_nm,_2dArray b_nm,double theta) { //赋初值给前两个对角线上的值 nalf.at(0).at(0) = 1.0; nalf.at(1).at(1) = sqrt(3.0)*sin(theta*pi/180.0); //计算对角线上的值 递归计算 不能并行 for (int i = 2; i < nalf.size(); i++) nalf.at(i).at(i) = sin(theta*pi/180.0)*sqrt(0.5*(2.0*i+1)/i)*nalf.at(i-1).at(i-1); //声明系数和迭代变量 int i,j; double Pn_2m,Pn_1m; //Pn-1,m Pn-2,m //这里可以使用并行加速计算外层循环 内层计算因为是递归计算因此不能并行 #pragma omp parallel for private(i,j,Pn_2m,Pn_1m) schedule(guided) for (j = 0; j < nalf.size()-1; j++) { Pn_2m = 0; Pn_1m = nalf.at(j).at(j); for (i = j+1; i < nalf.size(); i++) { nalf.at(i).at(j) = a_nm.at(i).at(j)*cos(theta*pi/180.0)*Pn_1m - b_nm.at(i).at(j)*Pn_2m; Pn_2m = nalf.at(i-1).at(j); Pn_1m = nalf.at(i).at(j); } } } void NALF_SFCM3(_2dArray& nalf,_2dArray a_nm,_2dArray b_nm,int maxOrder,double theta,double norSum) { //赋初值给前两个对角线上的值 //norSum为1时第一个值为1/sqrt(4.0*pi),归一化值为1, norSum为4.0*pi时第一个值为4.0*pi/sqrt(4.0*pi)=1,归一化值为4.0*pi nalf[0][0] = sqrt(norSum)/sqrt(4.0*pi); nalf[1][1] = sqrt(3.0)*sin(theta*pi/180.0); //计算对角线上的值 递归计算 不能并行 for (int i = 2; i < maxOrder; i++) nalf[i][i] = sin(theta*pi/180.0)*sqrt(0.5*(2.0*i+1)/i)*nalf[i-1][i-1]; //计算次对角线(m+1,m)上的值 递归计算 不能并行 for (int i = 0; i < maxOrder-1; i++) nalf[i+1][i] = cos(theta*pi/180.0)*sqrt(2.0*i+3)*nalf[i][i]; //声明系数和迭代变量 int i,j; //这里可以使用并行加速计算外层循环 内层计算因为是递归计算因此不能并行 #pragma omp parallel for private(i,j) schedule(guided) for (j = 0; j < maxOrder-1; j++) { for (i = j+2; i < maxOrder; i++) { nalf[i][j] = a_nm[i][j]*cos(theta*pi/180.0)*nalf[i-1][j] - b_nm[i][j]*nalf[i-2][j]; } } } #endif
GB_unaryop__minv_uint32_int16.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__minv_uint32_int16 // op(A') function: GB_tran__minv_uint32_int16 // C type: uint32_t // A type: int16_t // cast: uint32_t cij = (uint32_t) aij // unaryop: cij = GB_IMINV_UNSIGNED (aij, 32) #define GB_ATYPE \ int16_t #define GB_CTYPE \ uint32_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 = GB_IMINV_UNSIGNED (x, 32) ; // casting #define GB_CASTING(z, x) \ uint32_t z = (uint32_t) 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_MINV || GxB_NO_UINT32 || GxB_NO_INT16) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__minv_uint32_int16 ( uint32_t *restrict Cx, const int16_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__minv_uint32_int16 ( 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
DRB003-antidep2-orig-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: liao6@llnl.gov, lin32@llnl.gov, asplund1@llnl.gov, schordan1@llnl.gov, karlin1@llnl.gov) 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. */ /* A two-level loop nest with loop carried anti-dependence on the outer level. Data race pair: a[i][j]@67:7 vs. a[i+1][j]@67:18 */ #include <stdio.h> #include <omp.h> int main(int argc,char *argv[]) { int i; int j; int len = 20; double a[20][20]; #pragma omp parallel for private (i,j) for (i = 0; i <= len - 1; i += 1) { #pragma omp parallel for private (j) for (j = 0; j <= len - 1; j += 1) { a[i][j] = 0.5; } } for (i = 0; i <= len - 1 - 1; i += 1) { #pragma omp parallel for private (j) for (j = 0; j <= len - 1; j += 1) { a[i][j] += a[i + 1][j]; } } printf("a[10][10]=%lf\n",a[10][10]); return 0; }
kruskal.c
/****************************************************************************** * INCLUDES *****************************************************************************/ #include "kruskal.h" #include <math.h> #include <omp.h> /****************************************************************************** * PRIVATE FUNCTIONS *****************************************************************************/ /****************************************************************************** * API FUNCTIONS *****************************************************************************/ void splatt_free_kruskal( splatt_kruskal * factored) { free(factored->lambda); for(idx_t m=0; m < factored->nmodes; ++m) { free(factored->factors[m]); } } int splatt_kruskal_predict( splatt_kruskal const * const factored, splatt_idx_t const * const coords, splatt_val_t * const predicted) { /* check for out of bounds */ for(idx_t m=0; m < factored->nmodes; ++m) { if(coords[m] >= factored->dims[m]) { return SPLATT_ERROR_BADINPUT; } } /* initialize accumulation of each latent factor with lambda(r) */ idx_t const nfactors = factored->rank; val_t * restrict accum = splatt_malloc(nfactors * sizeof(*accum)); for(idx_t f=0; f < nfactors; ++f) { accum[f] = factored->lambda[f]; } /* now multiply each factor by A(i,:), B(j,:) ... */ for(idx_t m=0; m < factored->nmodes; ++m) { val_t const * const restrict row = factored->factors[m] + (coords[m] * nfactors); for(idx_t f=0; f < nfactors; ++f) { accum[f] *= row[f]; } } /* finally, sum the factors to form the final estimated value */ val_t est = 0; for(idx_t f=0; f < nfactors; ++f) { est += accum[f]; } splatt_free(accum); *predicted = est; return SPLATT_SUCCESS; } /****************************************************************************** * PUBLIC FUNCTIONS *****************************************************************************/ val_t kruskal_calc_fit( idx_t const nmodes, rank_info * const rinfo, thd_info * const thds, val_t const ttnormsq, val_t const * const restrict lambda, matrix_t ** mats, matrix_t const * const mttkrp, matrix_t ** aTa) { timer_start(&timers[TIMER_FIT]); /* First get norm of new model: lambda^T * (hada aTa) * lambda. */ val_t const norm_mats = kruskal_norm(nmodes, lambda, aTa); /* Compute inner product of tensor with new model */ val_t const inner = kruskal_mttkrp_inner(nmodes, rinfo, thds, lambda, mats, mttkrp); val_t const residual = sqrt(ttnormsq + norm_mats - (2 * inner)); timer_stop(&timers[TIMER_FIT]); return 1 - (residual / sqrt(ttnormsq)); } val_t kruskal_mttkrp_inner( idx_t const nmodes, rank_info * const rinfo, thd_info * const thds, val_t const * const restrict lambda, matrix_t ** mats, matrix_t const * const m1) { idx_t const rank = mats[0]->J; idx_t const lastm = nmodes - 1; idx_t const dim = m1->I; val_t const * const m0 = mats[lastm]->vals; val_t const * const mv = m1->vals; val_t myinner = 0; #pragma omp parallel reduction(+:myinner) { int const tid = omp_get_thread_num(); val_t * const restrict accumF = (val_t *) thds[tid].scratch[0]; for(idx_t r=0; r < rank; ++r) { accumF[r] = 0.; } #pragma omp for for(idx_t i=0; i < dim; ++i) { for(idx_t r=0; r < rank; ++r) { accumF[r] += m0[r+(i*rank)] * mv[r+(i*rank)]; } } /* accumulate everything into 'myinner' */ for(idx_t r=0; r < rank; ++r) { myinner += accumF[r] * lambda[r]; } } val_t inner = 0.; #ifdef SPLATT_USE_MPI timer_start(&timers[TIMER_MPI_FIT]); timer_start(&timers[TIMER_MPI_IDLE]); MPI_Barrier(rinfo->comm_3d); timer_stop(&timers[TIMER_MPI_IDLE]); MPI_Allreduce(&myinner, &inner, 1, SPLATT_MPI_VAL, MPI_SUM, rinfo->comm_3d); timer_stop(&timers[TIMER_MPI_FIT]); #else inner = myinner; #endif return inner; } val_t kruskal_norm( idx_t const nmodes, val_t const * const restrict lambda, matrix_t ** aTa) { idx_t const rank = aTa[0]->J; val_t * const restrict av = aTa[MAX_NMODES]->vals; val_t norm_mats = 0; /* use aTa[MAX_NMODES] as scratch space */ for(idx_t i=0; i < rank; ++i) { for(idx_t j=i; j < rank; ++j) { av[j + (i*rank)] = 1.; } } /* aTa[MAX_NMODES] = hada(aTa) */ for(idx_t m=0; m < nmodes; ++m) { val_t const * const restrict atavals = aTa[m]->vals; for(idx_t i=0; i < rank; ++i) { for(idx_t j=i; j < rank; ++j) { av[j + (i*rank)] *= atavals[j + (i*rank)]; } } } /* now compute lambda^T * aTa[MAX_NMODES] * lambda */ for(idx_t i=0; i < rank; ++i) { norm_mats += av[i+(i*rank)] * lambda[i] * lambda[i]; for(idx_t j=i+1; j < rank; ++j) { norm_mats += av[j+(i*rank)] * lambda[i] * lambda[j] * 2; } } return fabs(norm_mats); }
transposition_network_binary_alphabet.h
// // Created by nikita on 19.08.2020. // #ifndef CPU_TRANSPOSITION_NETWORK_BINARY_ALPHABET_H #define CPU_TRANSPOSITION_NETWORK_BINARY_ALPHABET_H #include <cstdlib> /** * Contains implementations of cell processing logic for bitwise algorithm based on semi-local iterative combing */ namespace cell_routines { namespace mpi_binary_naive { /** * Process upper triangles of squares of size sizeof(Input)*8 that lies on specific antidiagonal * First version */ template<class Input> inline void loop_upper_half_binary(int lower_bound, int upper_bound, int shift, int l_edge, int t_edge, Input active_bits, Input *l_strands, Input *t_strands, Input *a_reverse, Input *b) { for (int j = lower_bound; j < upper_bound; ++j) { Input l_strand = l_strands[l_edge + j]; Input t_strand = t_strands[t_edge + j]; Input l_strand_cap = l_strand >> shift; Input symbol_a = a_reverse[l_edge + j]; Input symbol_b = b[t_edge + j]; Input cond = active_bits & (((~(symbol_a >> shift)) ^ symbol_b) | (((~(l_strand_cap)) & t_strand))); Input inv_cond = ~cond; t_strands[t_edge + j] = (inv_cond & t_strand) | (cond & l_strand_cap); t_strand = t_strand << shift; cond = cond << shift; inv_cond = ~cond; l_strands[l_edge + j] = (inv_cond & l_strand) | (cond & t_strand); } } /** * Same as loop_upper_half_binary but without offset requirement */ template<class Input> inline void loop_center_half_binary(int lower_bound, int upper_bound, int l_edge, int t_edge, Input *l_strands, Input *t_strands, Input *a_reverse, Input *b) { for (int j = lower_bound; j < upper_bound; ++j) { Input l_strand = l_strands[l_edge + j]; Input t_strand = t_strands[t_edge + j]; Input cond = ((~(a_reverse[l_edge + j] ^ b[t_edge + j])) | ((~l_strand) & t_strand)); Input rev_combing_cond = ~cond; l_strands[l_edge + j] = (rev_combing_cond & l_strand) | (cond & t_strand); t_strands[t_edge + j] = (rev_combing_cond & t_strand) | (cond & l_strand); } } template<class Input> inline void loop_lower_half_binary(int lower_bound, int upper_bound, int shift, int l_edge, int t_edge, Input active_bits, Input *l_strands, Input *t_strands, Input *a_reverse, Input *b) { for (int j = lower_bound; j < upper_bound; ++j) { Input l_strand = l_strands[l_edge + j]; Input t_strand = t_strands[t_edge + j]; Input l_strand_cap = l_strand << (shift + 1); Input symbol_a = a_reverse[l_edge + j]; Input symbol_b = b[t_edge + j]; Input cond = active_bits & (((~(symbol_a << (shift + 1))) ^ symbol_b) | (((~(l_strand_cap)) & t_strand))); Input inv_cond = ~cond; t_strands[t_edge + j] = (inv_cond & t_strand) | (cond & l_strand_cap); t_strand = t_strand >> (shift + 1); cond = cond >> (shift + 1); inv_cond = ~cond; l_strands[l_edge + j] = (inv_cond & l_strand) | (cond & t_strand); } } /** * Process upper triangles of squares of size sizeof(Input)*8 that lies on specific antidiagonal */ template<class Input> inline void loop_upper_half_binary_mpi(int lower_bound, int upper_bound, int shift, int l_edge, int t_edge, Input active_bits, Input *l_strands, Input *t_strands, Input *a_reverse, Input *b) { #pragma omp for simd schedule(static) aligned(l_strands, t_strands, a_reverse, b:sizeof(Input)*8) for (int j = lower_bound; j < upper_bound; ++j) { Input l_strand = l_strands[l_edge + j]; Input t_strand = t_strands[t_edge + j]; Input l_strand_cap = l_strand >> shift; Input symbol_a = a_reverse[l_edge + j]; Input symbol_b = b[t_edge + j]; Input cond = active_bits & (((~(symbol_a >> shift)) ^ symbol_b) | (((~(l_strand_cap)) & t_strand))); Input inv_cond = ~cond; t_strands[t_edge + j] = (inv_cond & t_strand) | (cond & l_strand_cap); t_strand = t_strand << shift; cond = cond << shift; inv_cond = ~cond; l_strands[l_edge + j] = (inv_cond & l_strand) | (cond & t_strand); } } /** * Same as loop_upper_half_binary but without offset requirement */ template<class Input> inline void loop_center_half_binary_mpi(int lower_bound, int upper_bound, int l_edge, int t_edge, Input *l_strands, Input *t_strands, Input *a_reverse, Input *b) { #pragma omp for simd schedule(static) aligned(l_strands, t_strands, a_reverse, b:sizeof(Input)*8) for (int j = lower_bound; j < upper_bound; ++j) { Input l_strand = l_strands[l_edge + j]; Input t_strand = t_strands[t_edge + j]; Input cond = ((~(a_reverse[l_edge + j] ^ b[t_edge + j])) | ((~l_strand) & t_strand)); Input rev_combing_cond = ~cond; l_strands[l_edge + j] = (rev_combing_cond & l_strand) | (cond & t_strand); t_strands[t_edge + j] = (rev_combing_cond & t_strand) | (cond & l_strand); } } template<class Input> inline void loop_lower_half_binary_mpi(int lower_bound, int upper_bound, int shift, int l_edge, int t_edge, Input active_bits, Input *l_strands, Input *t_strands, Input *a_reverse, Input *b) { #pragma omp for simd schedule(static) aligned(l_strands, t_strands, a_reverse, b:sizeof(Input)*8) for (int j = lower_bound; j < upper_bound; ++j) { Input l_strand = l_strands[l_edge + j]; Input t_strand = t_strands[t_edge + j]; Input l_strand_cap = l_strand << (shift + 1); Input symbol_a = a_reverse[l_edge + j]; Input symbol_b = b[t_edge + j]; Input cond = active_bits & (((~(symbol_a << (shift + 1))) ^ symbol_b) | (((~(l_strand_cap)) & t_strand))); Input inv_cond = ~cond; t_strands[t_edge + j] = (inv_cond & t_strand) | (cond & l_strand_cap); t_strand = t_strand >> (shift + 1); cond = cond >> (shift + 1); inv_cond = ~cond; l_strands[l_edge + j] = (inv_cond & l_strand) | (cond & t_strand); } } } namespace mpi_binary_smart { template<class Input> inline void process_antidiag_formula1(int lower_bound, int upper_bound, int l_edge, int t_edge, Input *l_strands, Input *t_strands, Input const *a_reverse, Input const *b) { const int strands_per_word = sizeof(Input) * 8 - 1; /** * The idea is as follows. * to process some antidiagonal that have been built upon Input cells (that contains a batch of strands) we have to * process each such square (Input \times Input) in the antidiagonal fashion. * While processing each antidiagonal of such square, we need to implement the following logic: * in each iteration swap only those bit-strands that active in iteration & satisfy the combing condition. * This logic can be implemented by several formulas, here is presented one of it. * There is 20 operations inside cycle */ #pragma omp for simd schedule(static) aligned(l_strands, t_strands:sizeof(Input)*8) aligned(a_reverse, b:sizeof(Input)*8) for (int j = lower_bound; j < upper_bound; ++j) { Input l_strand_cap, cond, inv_cond, t_strand_shifted; //load phase Input l_strand = l_strands[l_edge + j]; Input t_strand = t_strands[t_edge + j]; Input symbol_a = a_reverse[l_edge + j]; Input symbol_b = b[t_edge + j]; Input mask = Input(1); // manual say 256 just for complete #pragma GCC unroll 256 for (int shift = strands_per_word; shift > 0; shift--) { l_strand_cap = l_strand >> shift; cond = mask & ((~(((symbol_a >> shift)) ^ symbol_b)) | (((~(l_strand_cap)) & t_strand))); inv_cond = ~cond; t_strand_shifted = t_strand << shift; t_strand = (inv_cond & t_strand) | (cond & l_strand_cap); cond <<= shift; inv_cond = ~cond; l_strand = (inv_cond & l_strand) | (cond & t_strand_shifted); mask = (mask << 1) | Input(1); } // center cond = (~(symbol_a ^ symbol_b)); cond = (cond | ((~l_strand) & t_strand)); inv_cond = ~cond; t_strand_shifted = t_strand; t_strand = (inv_cond & t_strand) | (cond & l_strand); l_strand = (inv_cond & l_strand) | (cond & t_strand_shifted); mask = ~Input(0); //lower half #pragma GCC unroll 256 for (int shift = 1; shift < strands_per_word + 1; shift++) { mask <<= 1; l_strand_cap = l_strand << (shift); cond = ~(((symbol_a << ((shift))) ^ symbol_b)); // NOT A XOR B = NOT (A XOR B)// ECONOMY cond = mask & (cond | (((~(l_strand_cap)) & t_strand))); inv_cond = ~cond; t_strand_shifted = t_strand >> shift; t_strand = (inv_cond & t_strand) | (cond & l_strand_cap); cond >>= shift; inv_cond = ~cond; l_strand = (inv_cond & l_strand) | (cond & t_strand_shifted); } l_strands[l_edge + j] = l_strand; t_strands[t_edge + j] = t_strand; } } template<class Input> inline void process_antidiag_formula2(int lower_bound, int upper_bound, int l_edge, int t_edge, Input *l_strands, Input *t_strands, Input const *a_reverse, Input const *b) { const int strands_per_word = sizeof(Input) * 8 - 1; /** * The idea is as follows. * to process some antidiagonal that have been built upon Input cells (that contains a batch of strands) we have to * process each such square (Input \times Input) in the antidiagonal fashion. * While processing each antidiagonal of such square, we need to implement the following logic: * in each iteration swap only those bit-strands that active in iteration & satisfy the combing condition. * This logic can be implemented by several formulas, here is presented one of it. * There is 15 operations inside cycle */ #pragma omp for simd schedule(static) aligned(l_strands, t_strands:sizeof(Input)*8) aligned(a_reverse, b:sizeof(Input)*8) for (int j = lower_bound; j < upper_bound; ++j) { Input t_strand_cap; Input l_strand_cap, cond; //load Input l_strand = l_strands[l_edge + j]; Input t_strand = t_strands[t_edge + j]; Input symbol_a = a_reverse[l_edge + j]; Input symbol_b = b[t_edge + j]; Input mask = Input(1); // manual say 256 just for complete #pragma GCC unroll 256 for (int shift = strands_per_word; shift > 0; shift--) { // 15 operations inside cycle // could be reduced to 14 if we store not a but ~a in memory l_strand_cap = l_strand >> shift; t_strand_cap = t_strand << shift; cond = ~((symbol_a >> shift) ^ symbol_b); t_strand = (l_strand_cap | (~mask)) & (t_strand | ( cond & mask)); l_strand = t_strand_cap ^ (t_strand << shift) ^ l_strand; mask = (mask << 1) | Input(1); } // center, no shifts cond = ~((symbol_a ^ symbol_b)); l_strand_cap = l_strand; t_strand_cap = t_strand; t_strand = (l_strand_cap | (~mask)) & (t_strand | ( cond & mask)); l_strand = t_strand_cap ^ (t_strand) ^ l_strand; mask = ~Input(0); //lower half #pragma GCC unroll 256 for (int shift = 1; shift < strands_per_word + 1; shift++) { mask <<= 1; l_strand_cap = l_strand << shift; t_strand_cap = t_strand >> shift; cond = ~(((symbol_a << (shift)) ^ symbol_b)); t_strand = (l_strand_cap | (~mask)) & (t_strand | ( cond & mask)); l_strand = t_strand_cap ^ (t_strand >> shift) ^ l_strand; } // store l_strands[l_edge + j] = l_strand; t_strands[t_edge + j] = t_strand; } } } namespace mpi_nary_size { template<class Input> inline void process_antidiagonal(int lower_bound, int upper_bound, int l_edge, int t_edge, Input *l_strands, Input *t_strands, Input const *a_reverse, Input const *b, int residue,int bits_per_strand, Input braid_ones) { Input single_strand = Input(1) << residue; int size = sizeof(Input) * 8 - residue - bits_per_strand; #pragma omp for simd schedule(static) aligned(l_strands, t_strands:sizeof(Input)*8) aligned(a_reverse, b:sizeof(Input)*8) for (int j = lower_bound; j < upper_bound; ++j) { Input l_strand_cap, cond, t_strand_cap,eq; //load phase Input l_strand = l_strands[l_edge + j]; Input t_strand = t_strands[t_edge + j]; Input symbol_a = a_reverse[l_edge + j]; Input symbol_b = b[t_edge + j]; Input mask = single_strand; // manual say 256 just for complete #pragma GCC unroll 256 for (int shift = size; shift > 0; shift -= bits_per_strand) { l_strand_cap = l_strand >> shift; t_strand_cap = t_strand << shift; //reduction block cond = ~( ((symbol_a >> shift) ) ^ symbol_b); eq = cond; #pragma GCC unroll 10 for(int i = 1; i < bits_per_strand; i++) { cond &= (eq >> i); } t_strand = (l_strand_cap | (braid_ones ^ mask)) & (t_strand | ( cond & mask)); l_strand = t_strand_cap ^ (t_strand << shift) ^ l_strand; mask = (mask << bits_per_strand) | single_strand; } cond = ~( (symbol_a) ^ symbol_b); eq = cond; #pragma GCC unroll 10 for(int i = 1; i < bits_per_strand; i++) cond &= (eq >> i); l_strand_cap = l_strand; t_strand_cap = t_strand; t_strand = (l_strand_cap | (braid_ones ^ braid_ones)) & (t_strand | ( cond & braid_ones)); l_strand = t_strand_cap ^ t_strand ^ l_strand; mask = braid_ones << bits_per_strand; //lower half #pragma GCC unroll 256 for (int shift = bits_per_strand; shift <= size ; shift += bits_per_strand) { //reduction block cond = ~((symbol_a << shift) ^ symbol_b); eq = cond; #pragma GCC unroll 10 for(int i = 1; i < bits_per_strand; i++) cond &= (eq >> i); l_strand_cap = l_strand << shift; t_strand_cap = t_strand >> shift; t_strand = (l_strand_cap | (braid_ones ^ mask)) & (t_strand | ( cond & mask)); l_strand = (t_strand_cap ^ (t_strand >> shift) ^ l_strand); mask <<= bits_per_strand; } l_strands[l_edge + j] = l_strand; t_strands[t_edge + j] = t_strand; } } } // generic } namespace prefix_lcs_via_semi_local { /** * Contains an bit-wise implementations of semi-local lcs that can compute length of LCS (llcs) of two binary string */ namespace binary { /** * This is the first non-optimized version of algorithm * Several condition should be satisfied: * 1) Since both strings are binary the elements should be compressed and stored in bits * 2) The first string assumed be less then the second one * 3) First string stored in reverse order to allow us to access elements in cell processing routine in sequential manner * 4) Input, that store pack of bits, should be unsigned to eliminate problem with signed shift * 5) Size of strings should be divisible by sizeof(Input)*8, if no, see details in paper or implementation * Algorithm follows the idea of iterative combing algorithm but strands have only 0 and 1 number. * To see cell processing routine see documentation of methods that used within the algorithm. * @tparam Input * @param a_reverse * @param a_size * @param b * @param b_size * @param a_total_symbols * @param threads_num * @return */ template<class Input> int llcs_2symbol_naive_combing(Input *a_reverse, int a_size, Input *b, int b_size, int a_total_symbols, int threads_num = 1) { using namespace cell_routines::mpi_binary_naive; // also stored in the reverse order Input *l_strands = static_cast<Input *> (aligned_alloc(sizeof(Input), sizeof(Input) * a_size)); Input *t_strands = static_cast<Input *> (aligned_alloc(sizeof(Input), sizeof(Input) * b_size)); auto m = a_size, n = b_size; // total amount of strands that at the end hit right border of grid int dis_braid = 0; auto num_diag = m + n - 1; auto total_same_length_diag = num_diag - (m) - (m - 1); #pragma omp parallel num_threads(threads_num) default(none) shared(l_strands, t_strands, a_reverse, b, m, n, dis_braid, total_same_length_diag) { Input mask; // Initialization step, strands that hit the left grid border all have number 1; strands that hit top grid border are 0. #pragma omp for simd schedule(static) aligned(l_strands:sizeof(Input)*8) for (int k = 0; k < m; ++k) l_strands[k] = ~Input(0); #pragma omp for simd schedule(static) aligned(t_strands:sizeof(Input)*8) for (int k = 0; k < n; ++k) t_strands[k] = Input(0); auto upper_bound = (sizeof(Input) * 8) - 1; //process first triangle in 0,0 cube mask = Input(1); Input mask_r = Input(1) << (sizeof(Input) * 8 - 1); int bits_shift = (sizeof(Input) * 8 - 1); //PHASE 0:Process first triangle #pragma omp single { for (int inside_diag_num = 0; inside_diag_num <= upper_bound; ++inside_diag_num, bits_shift--) { loop_upper_half_binary(0, 1, bits_shift, m - 1, 0, mask, l_strands, t_strands, a_reverse, b); mask = (mask << 1) | Input(1); } } //PHASE 1: Process diagonal till fill big left triangle, for (int cur_diag_cube_len = 1; cur_diag_cube_len < m; cur_diag_cube_len++) { //to process current bits_shift = (sizeof(Input) * 8 - 1); mask = Input(1); //to process previous Input mask_prev = ~static_cast<Input>(0); //process previous size/2 - 1 cubes and current size/2 -1 cubes for (int inside_diag_num = 0; inside_diag_num < upper_bound; ++inside_diag_num, bits_shift--) { //update mask of prev move mask_prev <<= 1; loop_upper_half_binary_mpi(0,cur_diag_cube_len + 1, bits_shift, m - 1 - cur_diag_cube_len, 0, mask, l_strands, t_strands, a_reverse, b); loop_lower_half_binary_mpi(0,cur_diag_cube_len,inside_diag_num,m-1-cur_diag_cube_len+1,0,mask_prev,l_strands,t_strands,a_reverse,b); //update mask of current move mask = (mask << 1) | Input(1); } loop_center_half_binary_mpi(0,cur_diag_cube_len+1,m-1-cur_diag_cube_len,0,l_strands,t_strands,a_reverse,b); } //PHASE 2 for (int k = 0; k < total_same_length_diag; ++k) { //to process current bits_shift = (sizeof(Input) * 8 - 1); mask = Input(1); //to process previous Input mask_prev = ~Input(0); for (int inside_diag_num = 0; inside_diag_num < upper_bound; ++inside_diag_num, bits_shift--) { //update mask of prev move mask_prev <<= 1; loop_upper_half_binary_mpi(0, m, bits_shift, 0, k + 1, mask, l_strands, t_strands, a_reverse, b); loop_lower_half_binary_mpi(0, m, inside_diag_num, 0, k, mask_prev, l_strands, t_strands, a_reverse, b); //update mask of current move mask = (mask << 1) | Input(1); } loop_center_half_binary_mpi(0, m, 0, k + 1, l_strands, t_strands, a_reverse, b); } auto start_j = total_same_length_diag + 1; for (int cur_diag_cube_len = m - 1; cur_diag_cube_len >= 1; cur_diag_cube_len--, start_j++) { //to process current bits_shift = (sizeof(Input) * 8 - 1); mask = Input(1); //to process previous Input mask_prev = ~Input(0); //process previous size/2 - 1 cubes and current size/2 -1 cubes for (int inside_diag_num = 0; inside_diag_num < upper_bound; ++inside_diag_num, bits_shift--) { //update mask of prev move mask_prev <<= 1; loop_upper_half_binary_mpi(0, cur_diag_cube_len, bits_shift, 0, start_j, mask, l_strands, t_strands, a_reverse, b); loop_lower_half_binary_mpi(0, cur_diag_cube_len + 1, inside_diag_num, 0, start_j - 1, mask_prev, l_strands, t_strands, a_reverse, b); //update mask of current move mask = (mask << 1) | Input(1); } loop_center_half_binary_mpi(0, cur_diag_cube_len, 0, start_j, l_strands, t_strands, a_reverse, b); } //process last triangle in position m-1, n-1 cube mask = ~Input(0); mask_r = mask; #pragma omp single { for (int inside_diag_num = 0; inside_diag_num < upper_bound; ++inside_diag_num) { mask = mask << 1; loop_lower_half_binary(0, 1, inside_diag_num, 0, n - 1, mask, l_strands, t_strands, a_reverse, b); } } #pragma omp for simd schedule(static) reduction(+:dis_braid) aligned(l_strands:sizeof(Input)*8) for (int i1 = 0; i1 < m; ++i1) { // Brian Kernighan’s Algorithm int counter = 0; Input number = l_strands[i1]; // LogNumber while (number) { number &= (number - 1); counter++; } dis_braid += counter; } } return a_total_symbols - dis_braid; } template<class Input> int llcs_2symbol_smart_combing(Input *a_reverse, int a_size, Input *b, int b_size, int a_total_symbols, int threads_num = 1, bool formula_one = false) { using namespace cell_routines::mpi_binary_smart; // also stored in the reverse order Input *l_strands = static_cast<Input *> (aligned_alloc(sizeof(Input), sizeof(Input) * a_size)); Input *t_strands = static_cast<Input *> (aligned_alloc(sizeof(Input), sizeof(Input) * b_size)); auto m = a_size, n = b_size; // total amount of strands that at the end hit right border of grid int dis_braid = 0; auto num_diag = m + n - 1; auto total_same_length_diag = num_diag - (m-1) - (m - 1); #pragma omp parallel num_threads(threads_num) default(none) shared(l_strands, t_strands, a_reverse, b, m, n, dis_braid, total_same_length_diag, formula_one) { // Initialization step, strands that hit the left grid border all have number 1; strands that hit top grid border are 0. #pragma omp for simd schedule(static) aligned(l_strands:sizeof(Input)*8) for (int k = 0; k < m; ++k) l_strands[k] = ~Input(0); #pragma omp for simd schedule(static) aligned(t_strands:sizeof(Input)*8) for (int k = 0; k < n; ++k) t_strands[k] = Input(0); // phase 1: process upper left triangle for (int diag_len = 0; diag_len < m - 1; diag_len++) { formula_one? process_antidiag_formula1(0,diag_len + 1,m - 1 - diag_len,0,l_strands,t_strands,a_reverse,b): process_antidiag_formula2(0,diag_len + 1,m - 1 - diag_len,0,l_strands,t_strands,a_reverse,b); } // phase2: process parallelogram for (int k = 0; k < total_same_length_diag; k++) { formula_one ? process_antidiag_formula1(0, m, 0, k, l_strands, t_strands, a_reverse, b) : process_antidiag_formula2(0, m, 0, k, l_strands, t_strands, a_reverse, b); } auto start_j = total_same_length_diag; // phase:3: lower-right triangle for (int diag_len = m - 1; diag_len >= 1; diag_len--) { formula_one ? process_antidiag_formula1(0, diag_len, 0, start_j, l_strands, t_strands, a_reverse, b) : process_antidiag_formula2(0, diag_len, 0, start_j, l_strands, t_strands, a_reverse, b); start_j++; } #pragma omp for simd schedule(static) reduction(+:dis_braid) aligned(l_strands:sizeof(Input)*8) for (int i1 = 0; i1 < m; ++i1) { // Brian Kernighan’s Algorithm int counter = 0; Input number = l_strands[i1]; // LogNumber while (number) { number &= (number - 1); counter++; } dis_braid += counter; } } return a_total_symbols - dis_braid; } } namespace nary { template<class Input> int llcs_nary_symbol_smart_combing(Input *a_reverse, int a_size, Input *b, int b_size, int a_total_symbols, int bits_per_symbol, int threads_num = 1) { using namespace cell_routines::mpi_nary_size; std::cout<<a_size<<','<<b_size<<std::endl; Input *l_strands = static_cast<Input *> (aligned_alloc(sizeof(Input), sizeof(Input) * a_size)); Input *t_strands = static_cast<Input *> (aligned_alloc(sizeof(Input), sizeof(Input) * b_size)); auto m = a_size, n = b_size; // total amount of strands that at the end hit right border of grid int dis_braid = 0; auto num_diag = m + n - 1; auto total_same_length_diag = num_diag - (m - 1) - (m - 1); int residue = (sizeof(Input) * 8) % bits_per_symbol; Input braid_ones = 1 << residue; for (int i = 0; i < sizeof(Input) * 8; i += bits_per_symbol) braid_ones |= (braid_ones << i); #pragma omp parallel num_threads(threads_num) default(none) shared(std::cout,residue,bits_per_symbol,braid_ones,l_strands, t_strands, a_reverse, b, m, n, dis_braid, total_same_length_diag) { // Initialization step, strands that hit the left grid border all have number 1; strands that hit top grid border are 0. #pragma omp for simd schedule(static) aligned(l_strands:sizeof(Input)*8) for (int k = 0; k < m; ++k) l_strands[k] = braid_ones; #pragma omp for simd schedule(static) aligned(t_strands:sizeof(Input)*8) for (int k = 0; k < n; ++k) t_strands[k] = Input(0); // phase 1: process upper left triangle for (int diag_len = 0; diag_len < m - 1; diag_len++) { process_antidiagonal(0, diag_len + 1, m - 1 - diag_len, 0, l_strands, t_strands, a_reverse, b, residue, bits_per_symbol,braid_ones); } // phase2: process parallelogram for (int k = 0; k < total_same_length_diag; k++) { process_antidiagonal(0, m, 0, k, l_strands, t_strands, a_reverse, b,residue,bits_per_symbol,braid_ones); } auto start_j = total_same_length_diag; // phase:3: lower-right triangle for (int diag_len = m - 1; diag_len >= 1; diag_len--) { process_antidiagonal(0, diag_len, 0, start_j, l_strands, t_strands, a_reverse, b, residue, bits_per_symbol, braid_ones); start_j++; } #pragma omp for simd schedule(static) reduction(+:dis_braid) aligned(l_strands:sizeof(Input)*8) for (int i1 = 0; i1 < m; ++i1) { // // Brian Kernighan’s Algorithm int counter = 0; Input number = l_strands[i1]; // LogNumber while (number) { number &= (number - 1); counter++; } dis_braid += counter; } } return a_total_symbols - dis_braid; } } } namespace lllcs_hyyro { /** * returns * @param str * @param size */ template <class Input> void preprocess(const int * str, int size, std::unordered_set<int> & alphabet, std::unordered_map<int,Input*> & lookup) { int word_size = (sizeof(Input)*8); int size_words = std::ceil(size * 1.0 / word_size); int mod = size % word_size; if (mod==0) mod = word_size; for(auto & symbol:alphabet) { auto vector_b = new Input[size_words]; auto ptr = 0; for(int i = 0; i < size_words - 1; i++) { Input word = Input(0); for(int j = 0; j < word_size; j++) { Input bit = Input(str[ptr] == symbol); word |= (bit<<j); ptr++; } vector_b[i] = word; } Input word = Input(0); for (int j = 0; j < mod; ++j) { Input bit = Input(str[ptr]==symbol); word |= (bit<<j); ptr++; } vector_b[size_words - 1] = word; lookup[symbol] = vector_b; } } template <class Input> int hyyro_magic(const int * str_a, int size_a_bits, int size_b_word, std::unordered_map<int,Input*> & lookup) { auto vector_v = new Input[size_b_word]; for (int i = 0; i < size_b_word; ++i) { vector_v[i] = ~Input(0); } auto bit_flag_sum = new Input[size_b_word]; bit_flag_sum[0] = Input(0); for (int i = 0; i < size_a_bits; ++i) { auto table = lookup[str_a[i]]; for (int j = 0; j < size_b_word - 1 ; ++j) { auto old_v = vector_v[j]; auto p = table[j] & old_v; auto with_offset = bit_flag_sum[j] + old_v + p; vector_v[j] = (old_v ^ p) | with_offset; bit_flag_sum[j + 1] = with_offset < old_v; } for (int j = size_b_word - 1; j < size_b_word; ++j) { auto old_v = vector_v[j]; auto p = table[j] & old_v; auto with_offset = bit_flag_sum[j] + old_v + p; vector_v[j] = (old_v ^ p) | with_offset; } } auto score = 0; for (int i1 = 0; i1 < size_b_word; ++i1) { // Brian Kernighan’s Algorithm int counter = 0; Input number = vector_v[i1]; // LogNumber while (number) { number &= (number - 1); counter++; } score += sizeof(Input)*8 - counter; } return score; } template <class Input> void hyyro_antidiag(int lower_bound, int upper_bound,int offset_a, int* str_a, std::unordered_map<int,Input*> &lookup, Input *vector_v, Input *shift_bits) { #pragma omp for schedule(static) for (int i = lower_bound; i < upper_bound; i++) {// b goes auto table = lookup[str_a[offset_a - i]]; auto shift_bit = shift_bits[offset_a - i]; auto old_v = vector_v[i]; auto p = table[i] & old_v; auto with_offset = shift_bit + old_v + p; vector_v[i] = (old_v ^ p) | with_offset; shift_bits[offset_a - i] = with_offset < old_v; } } /** * It is assumed that a > size_b_word * @tparam Input * @param str_a * @param size_a_bits * @param str_b * @param size_b_word * @param lookup * @param num_threads * @return */ template <class Input> int hyyro_magic_mpi_with_precalc(int * str_a, int size_a_bits, int size_b_word, std::unordered_map<int,Input*> & lookup, int num_threads = 1) { Input * vector_v = new Input[size_b_word]; Input * bit_flag_sum = new Input[size_a_bits]; for (int i = 0; i < size_b_word; ++i) vector_v[i] = ~Input(0); for (int i = 0; i < size_a_bits ; ++i) bit_flag_sum[i] = 0; auto score = 0; #pragma omp parallel num_threads(num_threads) default(none) shared(vector_v,bit_flag_sum,lookup,str_a,size_b_word,size_a_bits,score) { // 1st phase for (int i = 0; i < size_b_word - 1; ++i) hyyro_antidiag(0, i + 1, i, str_a, lookup, vector_v, bit_flag_sum); auto remains_full = (size_a_bits + size_b_word - 1) - (size_b_word - 1) - (size_b_word - 1); // 2rd phase auto offset = size_b_word - 1; for (int i = 0; i < remains_full; ++i) { hyyro_antidiag(0, size_b_word, offset, str_a, lookup, vector_v, bit_flag_sum); offset++; } // 3rd phase for (int i = 1; i < size_b_word; ++i) { hyyro_antidiag(i, size_b_word, offset, str_a, lookup, vector_v, bit_flag_sum); offset++; } #pragma omp for schedule(static) reduction(+:score) for (int i1 = 0; i1 < size_b_word; ++i1) { int counter = 0; Input number = vector_v[i1]; while (number) { number &= (number - 1); counter++; } score += sizeof(Input) * 8 - counter; } } return score; } } #endif //CPU_TRANSPOSITION_NETWORK_BINARY_ALPHABET_H
lsh_index.h
/*********************************************************************** * Software License Agreement (BSD License) * * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). 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. *************************************************************************/ /*********************************************************************** * Author: Vincent Rabaud *************************************************************************/ #ifndef FLANN_LSH_INDEX_H_ #define FLANN_LSH_INDEX_H_ #include <algorithm> #include <cassert> #include <cstring> #include <map> #include <vector> #include "flann/general.h" #include "flann/algorithms/nn_index.h" #include "flann/util/matrix.h" #include "flann/util/result_set.h" #include "flann/util/heap.h" #include "flann/util/lsh_table.h" #include "flann/util/allocator.h" #include "flann/util/random.h" #include "flann/util/saving.h" namespace flann { struct LshIndexParams : public IndexParams { LshIndexParams(unsigned int table_number = 12, unsigned int key_size = 20, unsigned int multi_probe_level = 2) { (* this)["algorithm"] = FLANN_INDEX_LSH; // The number of hash tables to use (*this)["table_number"] = table_number; // The length of the key in the hash tables (*this)["key_size"] = key_size; // Number of levels to use in multi-probe (0 for standard LSH) (*this)["multi_probe_level"] = multi_probe_level; } }; /** * 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 LshIndex : public NNIndex<Distance> { public: typedef typename Distance::ElementType ElementType; typedef typename Distance::ResultType DistanceType; typedef NNIndex<Distance> BaseClass; /** Constructor * @param params parameters passed to the LSH algorithm * @param d the distance used */ LshIndex(const IndexParams& params = LshIndexParams(), Distance d = Distance()) : BaseClass(params, d) { table_number_ = get_param<unsigned int>(index_params_,"table_number",12); key_size_ = get_param<unsigned int>(index_params_,"key_size",20); multi_probe_level_ = get_param<unsigned int>(index_params_,"multi_probe_level",2); fill_xor_mask(0, key_size_, multi_probe_level_, xor_masks_); } /** Constructor * @param input_data dataset with the input features * @param params parameters passed to the LSH algorithm * @param d the distance used */ LshIndex(const Matrix<ElementType>& input_data, const IndexParams& params = LshIndexParams(), Distance d = Distance()) : BaseClass(params, d) { table_number_ = get_param<unsigned int>(index_params_,"table_number",12); key_size_ = get_param<unsigned int>(index_params_,"key_size",20); multi_probe_level_ = get_param<unsigned int>(index_params_,"multi_probe_level",2); fill_xor_mask(0, key_size_, multi_probe_level_, xor_masks_); setDataset(input_data); } LshIndex(const LshIndex& other) : BaseClass(other), tables_(other.tables_), table_number_(other.table_number_), key_size_(other.key_size_), multi_probe_level_(other.multi_probe_level_), xor_masks_(other.xor_masks_) { } LshIndex& operator=(LshIndex other) { this->swap(other); return *this; } virtual ~LshIndex() { freeIndex(); } BaseClass* clone() const { return new LshIndex(*this); } using BaseClass::buildIndex; void addPoints(const Matrix<ElementType>& points, float rebuild_threshold = 2) { assert(points.cols==veclen_); size_t old_size = size_; extendDataset(points); if (rebuild_threshold>1 && size_at_build_*rebuild_threshold<size_) { buildIndex(); } else { for (unsigned int i = 0; i < table_number_; ++i) { lsh::LshTable<ElementType>& table = tables_[i]; for (size_t i=old_size; i<size_; ++i) { table.add(int(i), points_[i]); } } } } flann_algorithm_t getType() const { return FLANN_INDEX_LSH; } template<typename Archive> void serialize(Archive& ar) { ar.setObject(this); ar & *static_cast<NNIndex<Distance>*>(this); ar & table_number_; ar & key_size_; ar & multi_probe_level_; ar & xor_masks_; ar & tables_; if (Archive::is_loading::value) { index_params_["algorithm"] = getType(); index_params_["table_number"] = table_number_; index_params_["key_size"] = key_size_; index_params_["multi_probe_level"] = multi_probe_level_; } } void saveIndex(FILE* stream) { serialization::SaveArchive sa(stream); sa & *this; } void loadIndex(FILE* stream) { serialization::LoadArchive la(stream); la & *this; } /** * Computes the index memory usage * Returns: memory used by the index */ int usedMemory() const { return int(size_ * sizeof(int)); } /** * \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 */ 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); int count = 0; if (params.use_heap==FLANN_True) { #pragma omp parallel num_threads(params.cores) { KNNUniqueResultSet<DistanceType> resultSet((unsigned int)knn); #pragma omp for schedule(static) reduction(+:count) for (int i = 0; i < (int)queries.rows; i++) { resultSet.clear(); findNeighbors(resultSet, queries[i], params); size_t n = std::min(resultSet.size(), knn); resultSet.copy(indices[i], dists[i], int(n), params.sorted); indices_to_ids(indices[i], indices[i], n); count += int(n); } } } else { #pragma omp parallel num_threads(params.cores) { KNNResultSet<DistanceType> resultSet((int)knn); #pragma omp for schedule(static) reduction(+:count) for (int i = 0; i < (int)queries.rows; i++) { resultSet.clear(); findNeighbors(resultSet, queries[i], params); 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 += int(n); } } } 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 */ 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_); if (indices.size() < queries.rows ) indices.resize(queries.rows); if (dists.size() < queries.rows ) dists.resize(queries.rows); int count = 0; if (params.use_heap==FLANN_True) { #pragma omp parallel num_threads(params.cores) { KNNUniqueResultSet<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); 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) { KNNResultSet<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); 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; } } } return count; } /** * 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 { getNeighbors(vec, result); } protected: /** * Builds the index */ void buildIndexImpl() { tables_.resize(table_number_); std::vector<std::pair<size_t,ElementType*> > features; features.reserve(points_.size()); for (size_t i=0;i<points_.size();++i) { features.push_back(std::make_pair(i, points_[i])); } for (unsigned int i = 0; i < table_number_; ++i) { lsh::LshTable<ElementType>& table = tables_[i]; table = lsh::LshTable<ElementType>(int(veclen_), key_size_); // Add the features to the table table.add(features); } } void freeIndex() { /* nothing to do here */ } private: /** Defines the comparator on score and index */ typedef std::pair<float, unsigned int> ScoreIndexPair; struct SortScoreIndexPairOnSecond { bool operator()(const ScoreIndexPair& left, const ScoreIndexPair& right) const { return left.second < right.second; } }; /** Fills the different xor masks to use when getting the neighbors in multi-probe LSH * @param key the key we build neighbors from * @param lowest_index the lowest index of the bit set * @param level the multi-probe level we are at * @param xor_masks all the xor mask */ void fill_xor_mask(lsh::BucketKey key, int lowest_index, unsigned int level, std::vector<lsh::BucketKey>& xor_masks) { xor_masks.push_back(key); if (level == 0) return; for (int index = lowest_index - 1; index >= 0; --index) { // Create a new key lsh::BucketKey new_key = key | (1 << index); fill_xor_mask(new_key, index, level - 1, xor_masks); } } /** Performs the approximate nearest-neighbor search. * @param vec the feature to analyze * @param do_radius flag indicating if we check the radius too * @param radius the radius if it is a radius search * @param do_k flag indicating if we limit the number of nn * @param k_nn the number of nearest neighbors * @param checked_average used for debugging */ void getNeighbors(const ElementType* vec, bool do_radius, float radius, bool do_k, unsigned int k_nn, float& checked_average) { static std::vector<ScoreIndexPair> score_index_heap; if (do_k) { unsigned int worst_score = std::numeric_limits<unsigned int>::max(); typename std::vector<lsh::LshTable<ElementType> >::const_iterator table = tables_.begin(); typename std::vector<lsh::LshTable<ElementType> >::const_iterator table_end = tables_.end(); for (; table != table_end; ++table) { size_t key = table->getKey(vec); std::vector<lsh::BucketKey>::const_iterator xor_mask = xor_masks_.begin(); std::vector<lsh::BucketKey>::const_iterator xor_mask_end = xor_masks_.end(); for (; xor_mask != xor_mask_end; ++xor_mask) { size_t sub_key = key ^ (*xor_mask); const lsh::Bucket* bucket = table->getBucketFromKey(sub_key); if (bucket == 0) continue; // Go over each descriptor index std::vector<lsh::FeatureIndex>::const_iterator training_index = bucket->begin(); std::vector<lsh::FeatureIndex>::const_iterator last_training_index = bucket->end(); DistanceType hamming_distance; // Process the rest of the candidates for (; training_index < last_training_index; ++training_index) { if (removed_ && removed_points_.test(*training_index)) continue; hamming_distance = distance_(vec, points_[*training_index].point, veclen_); if (hamming_distance < worst_score) { // Insert the new element score_index_heap.push_back(ScoreIndexPair(hamming_distance, training_index)); std::push_heap(score_index_heap.begin(), score_index_heap.end()); if (score_index_heap.size() > (unsigned int)k_nn) { // Remove the highest distance value as we have too many elements std::pop_heap(score_index_heap.begin(), score_index_heap.end()); score_index_heap.pop_back(); // Keep track of the worst score worst_score = score_index_heap.front().first; } } } } } } else { typename std::vector<lsh::LshTable<ElementType> >::const_iterator table = tables_.begin(); typename std::vector<lsh::LshTable<ElementType> >::const_iterator table_end = tables_.end(); for (; table != table_end; ++table) { size_t key = table->getKey(vec); std::vector<lsh::BucketKey>::const_iterator xor_mask = xor_masks_.begin(); std::vector<lsh::BucketKey>::const_iterator xor_mask_end = xor_masks_.end(); for (; xor_mask != xor_mask_end; ++xor_mask) { size_t sub_key = key ^ (*xor_mask); const lsh::Bucket* bucket = table->getBucketFromKey(sub_key); if (bucket == 0) continue; // Go over each descriptor index std::vector<lsh::FeatureIndex>::const_iterator training_index = bucket->begin(); std::vector<lsh::FeatureIndex>::const_iterator last_training_index = bucket->end(); DistanceType hamming_distance; // Process the rest of the candidates for (; training_index < last_training_index; ++training_index) { if (removed_ && removed_points_.test(*training_index)) continue; // Compute the Hamming distance hamming_distance = distance_(vec, points_[*training_index].point, veclen_); if (hamming_distance < radius) score_index_heap.push_back(ScoreIndexPair(hamming_distance, training_index)); } } } } } /** Performs the approximate nearest-neighbor search. * This is a slower version than the above as it uses the ResultSet * @param vec the feature to analyze */ void getNeighbors(const ElementType* vec, ResultSet<DistanceType>& result) const { typename std::vector<lsh::LshTable<ElementType> >::const_iterator table = tables_.begin(); typename std::vector<lsh::LshTable<ElementType> >::const_iterator table_end = tables_.end(); for (; table != table_end; ++table) { size_t key = table->getKey(vec); std::vector<lsh::BucketKey>::const_iterator xor_mask = xor_masks_.begin(); std::vector<lsh::BucketKey>::const_iterator xor_mask_end = xor_masks_.end(); for (; xor_mask != xor_mask_end; ++xor_mask) { size_t sub_key = key ^ (*xor_mask); const lsh::Bucket* bucket = table->getBucketFromKey(flann::lsh::BucketKey(sub_key)); if (bucket == 0) continue; // Go over each descriptor index std::vector<lsh::FeatureIndex>::const_iterator training_index = bucket->begin(); std::vector<lsh::FeatureIndex>::const_iterator last_training_index = bucket->end(); DistanceType hamming_distance; // Process the rest of the candidates for (; training_index < last_training_index; ++training_index) { if (removed_ && removed_points_.test(*training_index)) continue; // Compute the Hamming distance hamming_distance = distance_(vec, points_[*training_index], veclen_); result.addPoint(hamming_distance, *training_index); } } } } void swap(LshIndex& other) { BaseClass::swap(other); std::swap(tables_, other.tables_); std::swap(size_at_build_, other.size_at_build_); std::swap(table_number_, other.table_number_); std::swap(key_size_, other.key_size_); std::swap(multi_probe_level_, other.multi_probe_level_); std::swap(xor_masks_, other.xor_masks_); } /** The different hash tables */ std::vector<lsh::LshTable<ElementType> > tables_; /** table number */ unsigned int table_number_; /** key size */ unsigned int key_size_; /** How far should we look for neighbors in multi-probe LSH */ unsigned int multi_probe_level_; /** The XOR masks to apply to a key to get the neighboring buckets */ std::vector<lsh::BucketKey> xor_masks_; USING_BASECLASS_SYMBOLS }; } #endif //FLANN_LSH_INDEX_H_
ssca2-locks.c
/* ============================================================================= * * ssca2.c * * ============================================================================= * * For the license of bayes/sort.h and bayes/sort.c, please see the header * of the files. * * ------------------------------------------------------------------------ * * For the license of kmeans, please see kmeans/LICENSE.kmeans * * ------------------------------------------------------------------------ * * For the license of ssca2, please see ssca2/COPYRIGHT * * ------------------------------------------------------------------------ * * For the license of lib/mt19937ar.c and lib/mt19937ar.h, please see the * header of the files. * * ------------------------------------------------------------------------ * * For the license of lib/rbtree.h and lib/rbtree.c, please see * lib/LEGALNOTICE.rbtree and lib/LICENSE.rbtree * * ------------------------------------------------------------------------ * * Unless otherwise noted, the following license applies to STAMP files: * * Copyright (c) 2007, Stanford University * 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 Stanford 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 STANFORD UNIVERSITY ``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 STANFORD UNIVERSITY BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * * ============================================================================= */ #include <assert.h> #include <stdlib.h> #include <stdio.h> #include "computeGraph.h" #include "cutClusters.h" #include "defs.h" #include "findSubGraphs.h" #include "genScalData.h" #include "getStartLists.h" #include "getUserParameters.h" #include "globals.h" #include "timer.h" #include "thread.h" #include "tm.h" MAIN(argc, argv) { GOTO_REAL(); /* * Tuple for Scalable Data Generation * stores startVertex, endVertex, long weight and other info */ graphSDG* SDGdata; /* * The graph data structure for this benchmark - see defs.h */ graph* G; #ifdef ENABLE_KERNEL2 /* * Kernel 2 */ edge* maxIntWtList; edge* soughtStrWtList; long maxIntWtListSize; long soughtStrWtListSize; #endif /* ENABLE_KERNEL2 */ #ifdef ENABLE_KERNEL3 # ifndef ENABLE_KERNEL2 # error KERNEL3 requires KERNEL2 # endif /* * Kernel 3 */ V* intWtVList = NULL; V* strWtVList = NULL; Vl** intWtVLList = NULL; Vl** strWtVLList = NULL; Vd* intWtVDList = NULL; Vd* strWtVDList = NULL; #endif /* ENABLE_KERNEL3 */ double totalTime = 0.0; /* ------------------------------------------------------------------------- * Preamble * ------------------------------------------------------------------------- */ /* * User Interface: Configurable parameters, and global program control */ printf("\nHPCS SSCA #2 Graph Analysis Executable Specification:"); printf("\nRunning...\n\n"); getUserParameters(argc, (char** const) argv); SIM_GET_NUM_CPU(THREADS); TM_STARTUP(THREADS); P_MEMORY_STARTUP(THREADS); thread_startup(THREADS); puts(""); printf("Number of processors: %ld\n", THREADS); printf("Problem Scale: %ld\n", SCALE); printf("Max parallel edges: %ld\n", MAX_PARAL_EDGES); printf("Percent int weights: %f\n", PERC_INT_WEIGHTS); printf("Probability unidirectional: %f\n", PROB_UNIDIRECTIONAL); printf("Probability inter-clique: %f\n", PROB_INTERCL_EDGES); printf("Subgraph edge length: %ld\n", SUBGR_EDGE_LENGTH); printf("Kernel 3 data structure: %ld\n", K3_DS); puts(""); /* * Scalable Data Generator */ printf("\nScalable Data Generator - genScalData() beginning execution...\n"); SDGdata = (graphSDG*)malloc(sizeof(graphSDG)); assert(SDGdata); TIMER_T start; TIMER_READ(start); #ifdef USE_PARALLEL_DATA_GENERATION GOTO_SIM(); #ifdef OTM #pragma omp parallel { genScalData((void*)SDGdata); } #else thread_start(genScalData, (void*)SDGdata); #endif GOTO_REAL(); #else /* !USE_PARALLEL_DATA_GENERATION */ genScalData_seq(SDGdata); #endif /* !USE_PARALLEL_DATA_GENERATION */ TIMER_T stop; TIMER_READ(stop); double time = TIMER_DIFF_SECONDS(start, stop); totalTime += time; printf("\n\tgenScalData() completed execution.\n"); #ifdef ENABLE_KERNEL1 /* ------------------------------------------------------------------------- * Kernel 1 - Graph Construction * * From the input edges, construct the graph 'G' * ------------------------------------------------------------------------- */ printf("\nKernel 1 - computeGraph() beginning execution...\n"); G = (graph*)malloc(sizeof(graph)); assert(G); computeGraph_arg_t computeGraphArgs; computeGraphArgs.GPtr = G; computeGraphArgs.SDGdataPtr = SDGdata; TIMER_READ(start); GOTO_SIM(); #ifdef OTM #pragma omp parallel { computeGraph((void*)&computeGraphArgs); } #else thread_start(computeGraph, (void*)&computeGraphArgs); #endif GOTO_REAL(); TIMER_READ(stop); time = TIMER_DIFF_SECONDS(start, stop); totalTime += time; printf("\n\tcomputeGraph() completed execution.\n"); #endif /* ENABLE_KERNEL1 */ #ifdef ENABLE_KERNEL2 /* ------------------------------------------------------------------------- * Kernel 2 - Find Max weight and sought string * ------------------------------------------------------------------------- */ printf("\nKernel 2 - getStartLists() beginning execution...\n"); maxIntWtListSize = 0; soughtStrWtListSize = 0; maxIntWtList = (edge*)malloc(sizeof(edge)); assert(maxIntWtList); soughtStrWtList = (edge*)malloc(sizeof(edge)); assert(soughtStrWtList); getStartLists_arg_t getStartListsArg; getStartListsArg.GPtr = G; getStartListsArg.maxIntWtListPtr = &maxIntWtList; getStartListsArg.maxIntWtListSize = &maxIntWtListSize; getStartListsArg.soughtStrWtListPtr = &soughtStrWtList; getStartListsArg.soughtStrWtListSize = &soughtStrWtListSize; TIMER_READ(start); GOTO_SIM(); #ifdef OTM #pragma omp parallel { getStartLists((void*)&getStartListsArg); } #else thread_start(getStartLists, (void*)&getStartListsArg); #endif GOTO_REAL(); TIMER_READ(stop); time = TIMER_DIFF_SECONDS(start, stop); totalTime += time; printf("\n\tgetStartLists() completed execution.\n"); #endif /* ENABLE_KERNEL2 */ #ifdef ENABLE_KERNEL3 /* ------------------------------------------------------------------------- * Kernel 3 - Graph Extraction * ------------------------------------------------------------------------- */ printf("\nKernel 3 - findSubGraphs() beginning execution...\n"); if (K3_DS == 0) { intWtVList = (V*)malloc(G->numVertices * maxIntWtListSize * sizeof(V)); assert(intWtVList); strWtVList = (V*)malloc(G->numVertices * soughtStrWtListSize * sizeof(V)); assert(strWtVList); findSubGraphs0_arg_t findSubGraphs0Arg; findSubGraphs0Arg.GPtr = G; findSubGraphs0Arg.intWtVList = intWtVList; findSubGraphs0Arg.strWtVList = strWtVList; findSubGraphs0Arg.maxIntWtList = maxIntWtList; findSubGraphs0Arg.maxIntWtListSize = maxIntWtListSize; findSubGraphs0Arg.soughtStrWtList = soughtStrWtList; findSubGraphs0Arg.soughtStrWtListSize = soughtStrWtListSize; TIMER_READ(start); GOTO_SIM(); #ifdef OTM #pragma omp parallel { findSubGraphs0((void*)&findSubGraphs0Arg); } #else thread_start(findSubGraphs0, (void*)&findSubGraphs0Arg); #endif GOTO_REAL(); TIMER_READ(stop); } else if (K3_DS == 1) { intWtVLList = (Vl**)malloc(maxIntWtListSize * sizeof(Vl*)); assert(intWtVLList); strWtVLList = (Vl**)malloc(soughtStrWtListSize * sizeof(Vl*)); assert(strWtVLList); findSubGraphs1_arg_t findSubGraphs1Arg; findSubGraphs1Arg.GPtr = G; findSubGraphs1Arg.intWtVLList = intWtVLList; findSubGraphs1Arg.strWtVLList = strWtVLList; findSubGraphs1Arg.maxIntWtList = maxIntWtList; findSubGraphs1Arg.maxIntWtListSize = maxIntWtListSize; findSubGraphs1Arg.soughtStrWtList = soughtStrWtList; findSubGraphs1Arg.soughtStrWtListSize = soughtStrWtListSize; TIMER_READ(start); GOTO_SIM(); #ifdef OTM #pragma omp parallel { findSubGraphs1((void*)&findSubGraphs1Arg); } #else thread_start(findSubGraphs1, (void*)&findSubGraphs1Arg); #endif GOTO_REAL(); TIMER_READ(stop); /* Verification on_one_thread { for (i=0; i<maxIntWtListSize; i++) { printf("%ld -- ", i); currV = intWtVLList[i]; while (currV != NULL) { printf("[%ld %ld] ", currV->num, currV->depth); currV = currV->next; } printf("\n"); } for (i=0; i<soughtStrWtListSize; i++) { printf("%ld -- ", i); currV = strWtVLList[i]; while (currV != NULL) { printf("[%ld %ld] ", currV->num, currV->depth); currV = currV->next; } printf("\n"); } } */ } else if (K3_DS == 2) { intWtVDList = (Vd *) malloc(maxIntWtListSize * sizeof(Vd)); assert(intWtVDList); strWtVDList = (Vd *) malloc(soughtStrWtListSize * sizeof(Vd)); assert(strWtVDList); findSubGraphs2_arg_t findSubGraphs2Arg; findSubGraphs2Arg.GPtr = G; findSubGraphs2Arg.intWtVDList = intWtVDList; findSubGraphs2Arg.strWtVDList = strWtVDList; findSubGraphs2Arg.maxIntWtList = maxIntWtList; findSubGraphs2Arg.maxIntWtListSize = maxIntWtListSize; findSubGraphs2Arg.soughtStrWtList = soughtStrWtList; findSubGraphs2Arg.soughtStrWtListSize = soughtStrWtListSize; TIMER_READ(start); GOTO_SIM(); #ifdef OTM #pragma omp parallel { findSubGraphs2((void*)&findSubGraphs2Arg); } #else thread_start(findSubGraphs2, (void*)&findSubGraphs2Arg); #endif GOTO_REAL(); TIMER_READ(stop); /* Verification */ /* on_one_thread { printf("\nInt weight sub-graphs \n"); for (i=0; i<maxIntWtListSize; i++) { printf("%ld -- ", i); for (j=0; j<intWtVDList[i].numArrays; j++) { printf("\n [Array %ld] - \n", j); for (k=0; k<intWtVDList[i].arraySize[j]; k++) { printf("[%ld %ld] ", intWtVDList[i].vList[j][k].num, intWtVDList[i].vList[j][k].depth); } } printf("\n"); } printf("\nStr weight sub-graphs \n"); for (i=0; i<soughtStrWtListSize; i++) { printf("%ld -- ", i); for (j=0; j<strWtVDList[i].numArrays; j++) { printf("\n [Array %ld] - \n", j); for (k=0; k<strWtVDList[i].arraySize[j]; k++) { printf("[%ld %ld] ", strWtVDList[i].vList[j][k].num, strWtVDList[i].vList[j][k].depth); } } printf("\n"); } } */ } else { assert(0); } time = TIMER_DIFF_SECONDS(start, stop); totalTime += time; printf("\n\tfindSubGraphs() completed execution.\n"); #endif /* ENABLE_KERNEL3 */ #ifdef ENABLE_KERNEL4 /* ------------------------------------------------------------------------- * Kernel 4 - Graph Clustering * ------------------------------------------------------------------------- */ printf("\nKernel 4 - cutClusters() beginning execution...\n"); TIMER_READ(start); GOTO_SIM(); #ifdef OTM #pragma omp parallel { cutClusters((void*)G); } #else thread_start(cutClusters, (void*)G); #endif GOTO_REAL(); TIMER_READ(stop); time = TIMER_DIFF_SECONDS(start, stop); totalTime += time; printf("\n\tcutClusters() completed execution.\n"); #endif /* ENABLE_KERNEL4 */ printf("\nTime = %9.6f\n\n", totalTime); /* ------------------------------------------------------------------------- * Cleanup * ------------------------------------------------------------------------- */ P_FREE(G->outDegree); P_FREE(G->outVertexIndex); P_FREE(G->outVertexList); P_FREE(G->paralEdgeIndex); P_FREE(G->inDegree); P_FREE(G->inVertexIndex); P_FREE(G->inVertexList); P_FREE(G->intWeight); P_FREE(G->strWeight); #ifdef ENABLE_KERNEL3 LONGINT_T i; LONGINT_T j; Vl* currV; Vl* tempV; if (K3_DS == 0) { P_FREE(strWtVList); P_FREE(intWtVList); } if (K3_DS == 1) { for (i = 0; i < maxIntWtListSize; i++) { currV = intWtVLList[i]; while (currV != NULL) { tempV = currV->next; P_FREE(currV); currV = tempV; } } for (i = 0; i < soughtStrWtListSize; i++) { currV = strWtVLList[i]; while (currV != NULL) { tempV = currV->next; P_FREE(currV); currV = tempV; } } P_FREE(strWtVLList); P_FREE(intWtVLList); } if (K3_DS == 2) { for (i = 0; i < maxIntWtListSize; i++) { for (j = 0; j < intWtVDList[i].numArrays; j++) { P_FREE(intWtVDList[i].vList[j]); } P_FREE(intWtVDList[i].vList); P_FREE(intWtVDList[i].arraySize); } for (i = 0; i < soughtStrWtListSize; i++) { for (j = 0; j < strWtVDList[i].numArrays; j++) { P_FREE(strWtVDList[i].vList[j]); } P_FREE(strWtVDList[i].vList); P_FREE(strWtVDList[i].arraySize); } P_FREE(strWtVDList); P_FREE(intWtVDList); } P_FREE(soughtStrWtList); P_FREE(maxIntWtList); #endif /* ENABLE_KERNEL2 */ P_FREE(SOUGHT_STRING); P_FREE(G); P_FREE(SDGdata); TM_SHUTDOWN(); P_MEMORY_SHUTDOWN(); GOTO_SIM(); thread_shutdown(); MAIN_RETURN(0); } /* ============================================================================= * * End of ssca2.c * * ============================================================================= */
DRB092-threadprivatemissing2-orig-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: liao6@llnl.gov, lin32@llnl.gov, asplund1@llnl.gov, schordan1@llnl.gov, karlin1@llnl.gov) 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. */ /* A file-scope variable used within a function called by a parallel region. No threadprivate is used to avoid data races. This is the case for a variable referenced within a construct. Data race pairs sum0@68:7 vs. sum0@68:12 sum0@68:7 vs. sum0@68:7 */ #include <stdio.h> #include <assert.h> int sum0=0, sum1=0; //#pragma omp threadprivate(sum0) int main() { int i, sum=0; #pragma omp parallel { #pragma omp for reduction(+:sum0) for (i=1;i<=1000;i++) { sum0=sum0+i; } } sum= sum+sum0; /* reference calculation */ #pragma omp parallel for reduction(+:sum1) for (i=1;i<=1000;i++) { sum1=sum1+i; } printf("sum=%d; sum1=%d\n",sum,sum1); // assert(sum==sum1); return 0; }
gemv.h
// Copyright 2018 Xiaomi, Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef MACE_OPS_ARM_FP16_GEMV_H_ #define MACE_OPS_ARM_FP16_GEMV_H_ #if defined(MACE_ENABLE_NEON) && \ defined(__ARM_FP16_FORMAT_IEEE) && (__ARM_FP & 2) // TODO(lichao): replace it with global macro #define MACE_ENABLE_FP16_NEON #endif #include "mace/core/types.h" #if defined(MACE_ENABLE_NEON) && defined(__ANDROID__) #include <arm_neon.h> #endif #if defined(MACE_ENABLE_NEON) && !defined(__aarch64__) && defined(__ANDROID__) #define vaddvq_f32(v) ((v)[0] + (v)[1] + (v)[2] + (v)[3]) #endif namespace mace { namespace ops { template<typename INPUT_TYPE_LEFT, typename INPUT_TYPE_RIGHT, typename OUTPUT_TYPE> void FP16Gemv(const INPUT_TYPE_LEFT *m_ptr, const INPUT_TYPE_RIGHT *v_ptr, const index_t height, const index_t width, OUTPUT_TYPE *result); #if defined(MACE_ENABLE_FP16_NEON) && defined(__ANDROID__) template<> void FP16Gemv<float16_t, float, float>(const float16_t *m_ptr, const float *v_ptr, const index_t height, const index_t width, float *out_ptr) { #pragma omp parallel for for (index_t h = 0; h < height; ++h) { const float16_t *m_ptr0 = m_ptr + h * width; const float *v_ptr0 = v_ptr; float *out_ptr0 = out_ptr + h; float sum0 = 0; float32x4_t vm0, vm1, vm2, vm3; float32x4_t vv0, vv1, vv2, vv3; float32x4_t vsum0 = vdupq_n_f32(0.f); float32x4_t vsum1 = vdupq_n_f32(0.f); float32x4_t vsum2 = vdupq_n_f32(0.f); float32x4_t vsum3 = vdupq_n_f32(0.f); index_t w; for (w = 0; w + 15 < width; w += 16) { vm0 = vcvt_f32_f16(vld1_f16(m_ptr0)); vv0 = vld1q_f32(v_ptr0); vm1 = vcvt_f32_f16(vld1_f16(m_ptr0 + 4)); vv1 = vld1q_f32(v_ptr0 + 4); vm2 = vcvt_f32_f16(vld1_f16(m_ptr0 + 8)); vv2 = vld1q_f32(v_ptr0 + 8); vm3 = vcvt_f32_f16(vld1_f16(m_ptr0 + 12)); vv3 = vld1q_f32(v_ptr0 + 12); vsum0 = vmlaq_f32(vsum0, vm0, vv0); vsum1 = vmlaq_f32(vsum1, vm1, vv1); vsum2 = vmlaq_f32(vsum2, vm2, vv2); vsum3 = vmlaq_f32(vsum3, vm3, vv3); m_ptr0 += 16; v_ptr0 += 16; } for (; w + 7 < width; w += 8) { vm0 = vcvt_f32_f16(vld1_f16(m_ptr0)); vv0 = vld1q_f32(v_ptr0); vm1 = vcvt_f32_f16(vld1_f16(m_ptr0 + 4)); vv1 = vld1q_f32(v_ptr0 + 4); vsum0 = vmlaq_f32(vsum0, vm0, vv0); vsum1 = vmlaq_f32(vsum1, vm1, vv1); m_ptr0 += 8; v_ptr0 += 8; } for (; w + 3 < width; w += 4) { vm0 = vcvt_f32_f16(vld1_f16(m_ptr0)); vv0 = vld1q_f32(v_ptr0); vsum0 = vmlaq_f32(vsum0, vm0, vv0); m_ptr0 += 4; v_ptr0 += 4; } vsum0 += vsum1; vsum2 += vsum3; vsum0 += vsum2; sum0 = vaddvq_f32(vsum0); for (; w < width; ++w) { sum0 += m_ptr0[0] * v_ptr0[0]; m_ptr0++; v_ptr0++; } *out_ptr0++ = sum0; } } #endif // MACE_ENABLE_FP16_NEON && __ANDROID__ } // namespace ops } // namespace mace #endif // MACE_OPS_ARM_FP16_GEMV_H_
unittest.h
/** * @file unittest.h * * @brief single-header unittesting framework for pure C99 codes * * @author Hajime Suzuki * @date 2016/3/1 * @license MIT * * @detail * latest version is found at https://github.com/ocxtal/unittest.h. * see README.md for the details. */ #pragma once /* instead of include guard */ #ifndef UNITTEST #define UNITTEST 1 #endif #ifndef UNITTEST_ALIAS_MAIN #define UNITTEST_ALIAS_MAIN 0 #endif /* for compatibility with -std=c99 (2016/4/26 by Hajime Suzuki) */ #if defined(__linux__) && !defined(_POSIX_C_SOURCE) # define _POSIX_C_SOURCE 200112L #endif #if defined(__darwin__) && !defined(_BSD_SOURCE) # define _BSD_SOURCE #endif /* end */ #include <alloca.h> #include <ctype.h> #include <getopt.h> #include <inttypes.h> #include <stdarg.h> #include <stddef.h> /* offsetof */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdint.h> #ifdef _OPENMP #include <omp.h> #endif #ifndef UNITTEST_UNIQUE_ID #define UNITTEST_UNIQUE_ID 0 #endif /** * from kvec.h in klib (https://github.com/attractivechaos/klib) * a little bit modified from the original */ #define utkv_roundup32(x) (--(x), (x)|=(x)>>1, (x)|=(x)>>2, (x)|=(x)>>4, (x)|=(x)>>8, (x)|=(x)>>16, ++(x)) #define UNITTEST_KV_INIT ( 64 ) /** * output coloring */ #define UT_RED "\x1b[31m" #define UT_GREEN "\x1b[32m" #define UT_YELLOW "\x1b[33m" #define UT_BLUE "\x1b[34m" #define UT_MAGENTA "\x1b[35m" #define UT_CYAN "\x1b[36m" #define UT_WHITE "\x1b[37m" #define UT_DEFAULT_COLOR "\x1b[39m" #define ut_color(c, x) c x UT_DEFAULT_COLOR /* static assertion macros */ #define ut_sa_cat_intl(x, y) x##y #define ut_sa_cat(x, y) ut_sa_cat_intl(x, y) #define ut_static_assert(expr) typedef char ut_sa_cat(ut_st, __LINE__)[(expr) ? 1 : -1] /** * basic vectors (utkv_*) */ #define utkvec_t(type) struct { uint64_t n, m; type *a; } #define utkv_init(v) ( (v).n = 0, (v).m = UNITTEST_KV_INIT, (v).a = (__typeof__((v).a))calloc((v).m, sizeof(*(v).a)) ) #define utkv_destroy(v) { free((v).a); (v).a = NULL; } // #define utkv_A(v, i) ( (v).a[(i)] ) #define utkv_pop(v) ( (v).a[--(v).n] ) #define utkv_size(v) ( (v).n ) #define utkv_max(v) ( (v).m ) #define utkv_clear(v) ( (v).n = 0 ) #define utkv_resize(v, s) ( \ (v).m = (s), (v).a = (__typeof__((v).a))realloc((v).a, sizeof(*(v).a) * (v).m) ) #define utkv_reserve(v, s) ( \ (v).m > (s) ? 0 : ((v).m = (s), (v).a = (__typeof__((v).a))realloc((v).a, sizeof(*(v).a) * (v).m), 0) ) #define utkv_copy(v1, v0) do { \ if ((v1).m < (v0).n) utkv_resize(v1, (v0).n); \ (v1).n = (v0).n; \ memcpy((v1).a, (v0).a, sizeof(*(v).a) * (v0).n); \ } while (0) \ #define utkv_push(v, x) do { \ if ((v).n == (v).m) { \ (v).m = (v).m * 2; \ (v).a = (__typeof__((v).a))realloc((v).a, sizeof(*(v).a) * (v).m); \ } \ (v).a[(v).n++] = (x); \ } while (0) #define utkv_pushp(v) ( \ ((v).n == (v).m) ? \ ((v).m = (v).m * 2, \ (v).a = realloc((v).a, sizeof(*(v).a) * (v).m), 0) \ : 0), ( (v).a + ((v).n++) ) #define utkv_a(v, i) ( \ ((v).m <= (size_t)(i) ? \ ((v).m = (v).n = (i) + 1, utkv_roundup32((v).m), \ (v).a = realloc((v).a, sizeof(*(v).a) * (v).m), 0) \ : (v).n <= (size_t)(i) ? (v).n = (i) + 1 \ : 0), (v).a[(i)]) /** bound-unchecked accessor */ #define utkv_at(v, i) ( (v).a[(i)] ) #define utkv_ptr(v) ( (v).a ) /** * forward declaration of the main function */ int main(int argc, char *argv[]); /** * @struct ut_result_s */ struct ut_result_s { int64_t cnt; int64_t succ; int64_t fail; }; struct ut_global_config_s; struct ut_group_config_s; struct ut_s; struct ut_result_s; struct ut_printer_s { /* printers */ void (*failed)( struct ut_s const *info, struct ut_global_config_s const *gconf, struct ut_group_config_s const *config, int64_t line, char const *func, char const *expr, char const *fmt, ...); void (*result)( struct ut_global_config_s const *gconf, struct ut_group_config_s const *config, struct ut_result_s const *result, int64_t file_cnt); }; /** * @struct ut_global_config_s */ struct ut_global_config_s { FILE *fp; struct ut_printer_s printer; uint64_t threads; }; /** * @struct ut_group_config_s * * @brief unittest scope config */ struct ut_group_config_s { /* internal use */ char const *file; int64_t unique_id; uint64_t line; int64_t exec; uint64_t _pad[4]; /* dependency resolution */ char const *name; char const *depends_on[16]; /* environment setup and cleanup */ void *(*init)(void *params); void (*clean)(void *context); void *params; }; /** * @struct ut_s * * @brief unittest function config */ struct ut_s { /* for internal use */ char const *file; int64_t unique_id; uint64_t line; int64_t exec; /* per-function config */ void (*fn)( void *ctx, void *gctx, struct ut_s *info, struct ut_global_config_s const *ut_gconf, struct ut_group_config_s const *config); /* internal use (cont'd) */ uint64_t index; uint64_t succ, fail; /* result: 1 when succeeded, 2 when failed */ /* dependency resolution */ char const *name; char const *depends_on[16]; /* environment setup and cleanup */ void *(*init)(void *params); void (*clean)(void *context); void *params; }; /* the two structs must be castable */ ut_static_assert(offsetof(struct ut_group_config_s, file) == offsetof(struct ut_s, file)); ut_static_assert(offsetof(struct ut_group_config_s, unique_id) == offsetof(struct ut_s, unique_id)); ut_static_assert(offsetof(struct ut_group_config_s, line) == offsetof(struct ut_s, line)); ut_static_assert(offsetof(struct ut_group_config_s, exec) == offsetof(struct ut_s, exec)); ut_static_assert(offsetof(struct ut_group_config_s, name) == offsetof(struct ut_s, name)); ut_static_assert(offsetof(struct ut_group_config_s, depends_on) == offsetof(struct ut_s, depends_on)); ut_static_assert(offsetof(struct ut_group_config_s, init) == offsetof(struct ut_s, init)); ut_static_assert(offsetof(struct ut_group_config_s, clean) == offsetof(struct ut_s, clean)); ut_static_assert(offsetof(struct ut_group_config_s, params) == offsetof(struct ut_s, params)); /** * @macro ut_unused * @brief declare the variable is unused in the function */ #define ut_unused(x) (void)(x); /** * @macro ut_null_replace * @brief replace pointer with "(null)" */ #define ut_null_replace(ptr, str) ( (ptr) == NULL ? (str) : (ptr) ) /** * @macro ut_build_name * * @brief an utility macro to make unique name */ #define ut_join_name(a, b, c) a##b##_##c #define ut_build_name(prefix, num, id) ut_join_name(prefix, num, id) /** * @macro unittest * * @brief instanciate a unittest object */ #define UNITTEST_ARG_DECL \ void *ctx, \ void *gctx, \ struct ut_s *ut_info, \ struct ut_global_config_s const *ut_gconf, \ struct ut_group_config_s const *ut_config #define UNITTEST_ARG_LIST ctx, gctx, ut_info, ut_gconf, ut_config #if UNITTEST != 0 #define unittest(...) \ static void ut_build_name(ut_body_, UNITTEST_UNIQUE_ID, __LINE__)(UNITTEST_ARG_DECL); \ static struct ut_s const ut_build_name(ut_info_, UNITTEST_UNIQUE_ID, __LINE__) = { \ /* file, unique_id, line, exec, fn, name, depends_on */ \ __FILE__, UNITTEST_UNIQUE_ID, __LINE__, 1, ut_build_name(ut_body_, UNITTEST_UNIQUE_ID, __LINE__), \ 0, 0, 0, __VA_ARGS__ \ }; \ struct ut_s ut_build_name(ut_get_info_, UNITTEST_UNIQUE_ID, __LINE__)(void) \ { \ return(ut_build_name(ut_info_, UNITTEST_UNIQUE_ID, __LINE__)); \ } \ static void ut_build_name(ut_body_, UNITTEST_UNIQUE_ID, __LINE__)(UNITTEST_ARG_DECL) #else /* UNITTEST != 0 */ #define unittest(...) \ static void ut_build_name(ut_body_, UNITTEST_UNIQUE_ID, __LINE__)(UNITTEST_ARG_DECL) #endif /* UNITTEST != 0 */ /** * @macro unittest_config * * @brief scope configuration */ #if UNITTEST != 0 #define unittest_config(...) \ static struct ut_group_config_s const ut_build_name(ut_config_, UNITTEST_UNIQUE_ID, __LINE__) = { \ .file = __FILE__, \ .line = __LINE__, \ .unique_id = UNITTEST_UNIQUE_ID, \ __VA_ARGS__ \ }; \ struct ut_group_config_s ut_build_name(ut_get_config_, UNITTEST_UNIQUE_ID, 0)(void) \ { \ return(ut_build_name(ut_config_, UNITTEST_UNIQUE_ID, __LINE__)); \ } #else /* UNITTEST != 0 */ #define unittest_config(...) #endif /* UNITTEST != 0 */ /* assertion failed message printers */ static void ut_print_assertion_failed( struct ut_s const *info, struct ut_global_config_s const *gconf, struct ut_group_config_s const *config, int64_t line, char const *func, char const *expr, char const *fmt, ...) { ut_unused(func); va_list l; va_start(l, fmt); fprintf(gconf->fp, ut_color(UT_YELLOW, "assertion failed") ": [%s] %s:" ut_color(UT_BLUE, "%" PRId64 "") " (%s) `" ut_color(UT_MAGENTA, "%s") "'", ut_null_replace(config->name, "no name"), ut_null_replace(info->file, "(unknown filename)"), line, ut_null_replace(info->name, "no name"), expr); if(strlen(fmt) != 0) { fprintf(gconf->fp, ", "); vfprintf(gconf->fp, fmt, l); } fprintf(gconf->fp, "\n"); va_end(l); return; } static void ut_print_assertion_failed_json( struct ut_s const *info, struct ut_global_config_s const *gconf, struct ut_group_config_s const *config, int64_t line, char const *func, char const *expr, char const *fmt, ...) { ut_unused(config); ut_unused(func); va_list l; va_start(l, fmt); fprintf(gconf->fp, "{ \"tag\": \"fail\", "); if(config->name != NULL) { fprintf(gconf->fp, "\"group\": \"%s\", ", config->name); } if(config->file != NULL) { fprintf(gconf->fp, "\"filename\": \"%s\", ", config->file); } fprintf(gconf->fp, "\"line\": %" PRId64 ", ", line); if(info->name != NULL) { fprintf(gconf->fp, "\"name\": \"%s\", ", info->name); } fprintf(gconf->fp, "\"expr\": \"%s\", ", expr); if(strlen(fmt) != 0) { fprintf(gconf->fp, "\"debugprint\": \""); vfprintf(gconf->fp, fmt, l); /* FIXME: escape */ fprintf(gconf->fp, "\", "); } fprintf(gconf->fp, "},\n"); va_end(l); return; } /* summary printers */ static void ut_print_results( struct ut_global_config_s const *gconf, struct ut_group_config_s const *config, struct ut_result_s const *result, int64_t file_cnt) { int64_t cnt = 0; int64_t succ = 0; int64_t fail = 0; for(int64_t i = 0, j = 0; i < file_cnt; i++) { if(config[i].exec == 0) { continue; } fprintf(gconf->fp, "%sGroup %s: %" PRId64 " succeeded, %" PRId64 " failed in total %" PRId64 " assertions in %" PRId64 " tests.%s\n", (result[j].fail == 0) ? UT_GREEN : UT_RED, ut_null_replace(config[i].name, "(no name)"), result[j].succ, result[j].fail, result[j].succ + result[j].fail, result[j].cnt, UT_DEFAULT_COLOR); cnt += result[j].cnt; succ += result[j].succ; fail += result[j].fail; j++; } fprintf(gconf->fp, "%sSummary: %" PRId64 " succeeded, %" PRId64 " failed in total %" PRId64 " assertions in %" PRId64 " tests.%s\n", (fail == 0) ? UT_GREEN : UT_RED, succ, fail, succ + fail, cnt, UT_DEFAULT_COLOR); return; } static void ut_print_results_json( struct ut_global_config_s const *gconf, struct ut_group_config_s const *config, struct ut_result_s const *result, int64_t file_cnt) { int64_t cnt = 0; int64_t succ = 0; int64_t fail = 0; fprintf(gconf->fp, "{ \"tag\": \"results\", [ "); for(int64_t i = 0, j = 0; i < file_cnt; i++) { if(config[i].exec == 0) { continue; } if(config->name != NULL) { fprintf(gconf->fp, "{ \"group\": \"%s\", ", config->name); } if(config->file != NULL) { fprintf(gconf->fp, "\"filename\": \"%s\", ", config->file); } fprintf(gconf->fp, "\"succeeded\": %" PRId64 ", ", result[j].succ); fprintf(gconf->fp, "\"failed\": %" PRId64 ", ", result[j].fail); fprintf(gconf->fp, "\"assertioncount\": %" PRId64 ", ", result[j].succ + result[j].fail); fprintf(gconf->fp, "\"testcount\": %" PRId64 ", ", result[j].cnt); fprintf(gconf->fp, "}, "); cnt += result[j].cnt; succ += result[j].succ; fail += result[j].fail; j++; } fprintf(gconf->fp, "] },\n"); fprintf(gconf->fp, "{ \"tag\": \"summary\", "); fprintf(gconf->fp, "\"succeeded\": %" PRId64 ", ", succ); fprintf(gconf->fp, "\"failed\": %" PRId64 ", ", fail); fprintf(gconf->fp, "\"assertioncount\": %" PRId64 ", ", succ + fail); fprintf(gconf->fp, "\"testcount\": %" PRId64 ", ", cnt); fprintf(gconf->fp, "},\n"); return; } static struct ut_printer_s ut_default_printer = { .failed = ut_print_assertion_failed, .result = ut_print_results }; static struct ut_printer_s ut_json_printer = { .failed = ut_print_assertion_failed_json, .result = ut_print_results_json }; /** * memory dump macro */ #define ut_dump(ptr, len) ({ \ uint64_t _size = (((len) + 15) / 16 + 1) * \ (strlen("0x0123456789abcdef:") + 16 * strlen(" 00a") + strlen(" \n+ margin")) \ + strlen(#ptr) + strlen("\n`' len: 100000000"); \ uint8_t *_ptr = (uint8_t *)(ptr); \ char *_str = alloca(_size); \ char *_s = _str; \ /* make header */ \ _s += sprintf(_s, "\n`%s' len: %" PRIu64 "\n", #ptr, (uint64_t)len); \ _s += sprintf(_s, " "); \ for(uint64_t i = 0; i < 16; i++) { \ _s += sprintf(_s, " %02x", (uint8_t)i); \ } \ _s += sprintf(_s, "\n"); \ for(uint64_t i = 0; i < ((len) + 15) / 16; i++) { \ _s += sprintf(_s, "0x%016" PRIx64 ":", (uint64_t)_ptr); \ for(uint64_t j = 0; j < 16; j++) { \ _s += sprintf(_s, " %02x", (uint8_t)_ptr[j]); \ } \ _s += sprintf(_s, " "); \ for(uint64_t j = 0; j < 16; j++) { \ _s += sprintf(_s, "%c", isprint(_ptr[j]) ? _ptr[j] : ' '); \ } \ _s += sprintf(_s, "\n"); \ _ptr += 16; \ } \ (char const *)_str; \ }) #ifndef dump // #define dump ut_dump #endif /** * assertion macro */ #define ut_assert(expr, ...) { \ if(expr) { \ ut_info->succ++; \ } else { \ ut_info->fail++; \ /* dump debug information */ \ ut_gconf->printer.failed(ut_info, ut_gconf, ut_config, __LINE__, __func__, #expr, "" __VA_ARGS__); \ } \ } #ifndef assert #define assert ut_assert #endif /** * @struct ut_nm_result_s * @brief parsed result container */ struct ut_nm_result_s { void *ptr; char type; char name[255]; }; static inline int ut_strcmp( char const *a, char const *b) { /* if both are NULL */ if(a == NULL && b == NULL) { return(0); } if(b == NULL) { return(1); } if(a == NULL) { return(-1); } return(strcmp(a, b)); } static inline char *ut_build_nm_cmd( char const *filename) { uint64_t const filename_len_limit = 1024; char const *cmd_base = "nm "; /* check the length of the filename */ if(strlen(filename) > filename_len_limit) { return(NULL); } /* cat name */ char *cmd = (char *)malloc(strlen(cmd_base) + strlen(filename) + 1); strcpy(cmd, cmd_base); strcat(cmd, filename); return(cmd); } static inline char *ut_dump_file( FILE *fp) { int c; utkvec_t(char) buf; utkv_init(buf); while((c = getc(fp)) != EOF) { utkv_push(buf, c); } /* push terminator */ utkv_push(buf, '\0'); return(utkv_ptr(buf)); } static inline char *ut_dump_nm_output( char const *filename) { char *cmd = NULL; FILE *fp = NULL; char *res = NULL; /* build command */ if((cmd = ut_build_nm_cmd(filename)) == NULL) { goto _ut_nm_error_handler; } /* open */ if((fp = popen(cmd, "r")) == NULL) { fprintf(stderr, ut_color(UT_RED, "ERROR") ": failed to open pipe.\n"); goto _ut_nm_error_handler; } /* dump */ if((res = ut_dump_file(fp)) == NULL) { fprintf(stderr, ut_color(UT_RED, "ERROR") ": failed to read nm output.\n"); goto _ut_nm_error_handler; } /* close file */ if(pclose(fp) != 0) { fprintf(stderr, ut_color(UT_RED, "ERROR") ": failed to close pipe.\n"); goto _ut_nm_error_handler; } free(cmd); cmd = NULL; return(res); _ut_nm_error_handler: if(cmd != NULL) { free(cmd); } if(fp != NULL) { pclose(fp); } if(res != NULL) { free(res); } return(NULL); } static inline struct ut_nm_result_s *ut_parse_nm_output( char const *str) { char const *p = str; utkvec_t(struct ut_nm_result_s) buf; utkv_init(buf); while(*p != '\0') { struct ut_nm_result_s r; /* check the sanity of the line */ char const *sp = p; while(*sp != '\r' && *sp != '\n' && *sp != '\0') { sp++; } // printf("%p, %p, %" PRId64 "\n", p, sp, (int64_t)(sp - p)); if((int64_t)(sp - p) < 1) { break; } /* if the first character of the line is space, pass the PTR state */ if(!isspace(*p)) { char *np; r.ptr = (void *)((uint64_t)strtoll(p, &np, 16)); /* advance pointer */ p = np; // printf("ptr field found: %p\n", r.ptr); } else { r.ptr = NULL; // printf("ptr field not found\n"); } /* parse type */ while(isspace(*p)) { p++; } r.type = *p++; // printf("type found %c\n", r.type); /* parse name */ while(isspace(*p)) { p++; } if(*p == '_') { p++; } int name_idx = 0; while(*p != '\n' && name_idx < 254) { r.name[name_idx++] = *p++; } r.name[name_idx] = '\0'; // printf("name found %s\n", r.name); /* adjust the pointer to the head of the next line */ while(*p == '\r' || *p == '\n') { p++; } /* push */ utkv_push(buf, r); } /* push terminator */ utkv_push(buf, (struct ut_nm_result_s){ 0 }); return(utkv_ptr(buf)); } static inline struct ut_nm_result_s *ut_nm( char const *filename) { char const *str = NULL; struct ut_nm_result_s *res = NULL; if((str = ut_dump_nm_output(filename)) == NULL) { return(NULL); } res = ut_parse_nm_output(str); free((void *)str); return(res); } static inline int ut_startswith(char const *str, char const *prefix) { while(*str != '\0' && *prefix != '\0') { if(*str++ != *prefix++) { return(1); } } return(*prefix == '\0' ? 0 : 1); } static inline struct ut_s *ut_get_unittest( struct ut_nm_result_s const *res) { /* extract offset */ uintptr_t offset = (uintptr_t)-1LL; struct ut_nm_result_s const *r = res; while(r->type != (char)0) { if(ut_strcmp("main", r->name) == 0) { offset = (uintptr_t)main - (uintptr_t)r->ptr; } r++; } if(offset == (uintptr_t)-1LL) { return(NULL); } #define ut_get_info_call_func(_ptr, _offset) ( \ (struct ut_s (*)(void))((uintptr_t)(_ptr) + (uintptr_t)(_offset)) \ ) /* get info */ utkvec_t(struct ut_s) buf; r = res; utkv_init(buf); while(r->type != (char)0) { if(ut_startswith(r->name, "ut_get_info_") == 0) { struct ut_s i = ut_get_info_call_func(r->ptr, offset)(); utkv_push(buf, i); } r++; } /* push terminator */ utkv_push(buf, (struct ut_s){ 0 }); return(utkv_ptr(buf)); } static inline struct ut_group_config_s *ut_get_ut_config( struct ut_nm_result_s const *res) { /* extract offset */ uintptr_t offset = (uintptr_t)-1LL; struct ut_nm_result_s const *r = res; while(r->type != (char)0) { if(ut_strcmp("main", r->name) == 0) { offset = (uintptr_t)main - (uintptr_t)r->ptr; } r++; } if(offset == (uintptr_t)-1LL) { return(NULL); } #define ut_get_config_call_func(_ptr, _offset) ( \ (struct ut_group_config_s (*)(void))((uintptr_t)(_ptr) + (uintptr_t)(_offset)) \ ) /* get info */ utkvec_t(struct ut_group_config_s) buf; r = res; utkv_init(buf); while(r->type != (char)0) { if(ut_startswith(r->name, "ut_get_config_") == 0) { struct ut_group_config_s i = ut_get_config_call_func(r->ptr, offset)(); utkv_push(buf, i); } r++; } /* push terminator */ utkv_push(buf, (struct ut_group_config_s){ 0 }); return(utkv_ptr(buf)); } static inline void ut_dump_test( struct ut_s const *test) { struct ut_s const *t = test; while(t->file != NULL) { printf("%s, %" PRIu64 ", %" PRId64 ", %s, %s, %p, %p\n", t->file, t->line, t->unique_id, t->name, t->depends_on[0], (void *)t->init, (void *)t->clean); t++; } return; } static inline void ut_dump_config( struct ut_group_config_s const *config) { struct ut_group_config_s const *c = config; while(c->file != NULL) { printf("%s, %" PRId64 ", %s, %s, %p, %p\n", c->file, c->unique_id, c->name, c->depends_on[0], (void *)c->init, (void *)c->clean); c++; } return; } static int ut_compare( void const *_a, void const *_b) { struct ut_s const *a = (struct ut_s const *)_a; struct ut_s const *b = (struct ut_s const *)_b; int64_t comp_res = 0; /* first sort by file name */ if((comp_res = ut_strcmp(a->file, b->file)) != 0) { return(comp_res); } #define sat(a) ( ((a) > INT32_MAX) ? INT32_MAX : (((a) < INT32_MIN) ? INT32_MIN : (a)) ) if((comp_res = (a->unique_id - b->unique_id)) != 0) { return(sat(comp_res)); } #undef sat /* third sort by name */ if((comp_res = ut_strcmp(a->name, b->name)) != 0) { return(comp_res); } /* last, sort by line number */ return((int)(a->line - b->line)); } static inline int ut_match( void const *_a, void const *_b) { struct ut_s const *a = (struct ut_s *)_a; struct ut_s const *b = (struct ut_s *)_b; return((ut_strcmp(a->file, b->file) == 0 && a->unique_id == b->unique_id) ? 0 : 1); } static inline uint64_t ut_get_total_test_count( struct ut_s const *test) { uint64_t cnt = 0; struct ut_s const *t = test; while(t->file != NULL) { t++; cnt++; } return(cnt); } static inline uint64_t ut_get_total_config_count( struct ut_group_config_s const *config) { uint64_t cnt = 0; struct ut_group_config_s const *c = config; while(c->file != NULL) { c++; cnt++; } return(cnt); } static inline uint64_t ut_get_total_file_count( struct ut_s const *sorted_test) { uint64_t cnt = 1; struct ut_s const *t = sorted_test; if(t++->file == NULL) { return(0); } while(t->file != NULL) { // printf("comp %s and %s\n", (t - 1)->file, t->file); if(ut_match((void *)(t - 1), (void *)t) != 0) { cnt++; } t++; } return(cnt); } static inline void ut_sort( struct ut_s *test, struct ut_group_config_s *config) { // ut_dump_test(test); qsort(test, ut_get_total_test_count(test), sizeof(struct ut_s), ut_compare); qsort(config, ut_get_total_config_count(config), sizeof(struct ut_group_config_s), ut_compare); // ut_dump_test(test); // printf("%" PRId64 "\n", ut_get_total_file_count(test)); return; } static inline uint64_t *ut_build_file_index( struct ut_s const *sorted_test) { uint64_t cnt = 1; utkvec_t(uint64_t) idx; struct ut_s const *t = sorted_test; utkv_init(idx); if(t++->file == NULL) { utkv_push(idx, 0); utkv_push(idx, -1); return(utkv_ptr(idx)); } utkv_push(idx, 0); while(t->file != NULL) { // printf("comp %s and %s\n", (t - 1)->name, t->name); if(ut_match((void *)(t - 1), (void *)t) != 0) { utkv_push(idx, cnt); } cnt++; t++; } utkv_push(idx, cnt); utkv_push(idx, -1); return(utkv_ptr(idx)); } static inline struct ut_group_config_s *ut_compensate_config( struct ut_s *sorted_test, struct ut_group_config_s *sorted_config) { // printf("compensate config\n"); // ut_dump_test(sorted_test); // ut_dump_config(sorted_config); uint64_t *file_idx = ut_build_file_index(sorted_test); utkvec_t(struct ut_group_config_s) compd_config; utkv_init(compd_config); int64_t i = 0; // printf("%" PRId64 "\n", file_idx[i]); struct ut_s const *t = &sorted_test[file_idx[i]]; struct ut_group_config_s const *c = sorted_config; while(c->file != NULL && t->file != NULL) { while(ut_match((void *)t, (void *)c) != 0) { // printf("filename does not match %s, %s\n", c->file, t->file); utkv_push(compd_config, (struct ut_group_config_s){ .file = t->file }); t = &sorted_test[file_idx[++i]]; } // printf("matched %s, %s\n", c->file, t->file); utkv_push(compd_config, *c); c++; t = &sorted_test[file_idx[++i]]; } free(file_idx); return(utkv_ptr(compd_config)); } static inline int ut_toposort_by_tag( struct ut_s *sorted_test, uint64_t test_cnt) { /* init dag */ utkvec_t(utkvec_t(uint64_t)) dag; utkv_init(dag); utkv_reserve(dag, test_cnt); for(uint64_t i = 0; i < test_cnt; i++) { utkv_init(utkv_at(dag, i)); } /* build dag */ for(uint64_t i = 0; i < test_cnt; i++) { /* enumerate depends_on */ char const *const *d = sorted_test[i].depends_on; while(*d != NULL) { /* enumerate tests */ for(uint64_t j = 0; j < test_cnt; j++) { if(i == j) { continue; } if(ut_strcmp(sorted_test[j].name, *d) == 0) { // printf("edge found from node %" PRId64 " to node %" PRId64 "\n", j, i); utkv_push(utkv_at(dag, i), j); } } d++; } } /* build mark */ utkvec_t(int8_t) mark; utkv_init(mark); for(uint64_t i = 0; i < test_cnt; i++) { // printf("incoming edge count %" PRId64 " : %" PRId64 "\n", i, utkv_size(utkv_at(dag, i))); utkv_push(mark, utkv_size(utkv_at(dag, i))); } /* sort */ utkvec_t(struct ut_s) res; utkv_init(res); for(uint64_t i = 0; i < test_cnt; i++) { uint64_t node_id = (uint64_t)-1LL; for(uint64_t j = 0; j < test_cnt; j++) { /* check if the node has incoming edges or is already pushed */ if(utkv_at(mark, j) == 0) { node_id = j; break; } } if(node_id == (uint64_t)-1LL) { fprintf(stderr, ut_color(UT_RED, "ERROR") ": detected circular dependency in the tests in `" ut_color(UT_MAGENTA, "%s") "'.\n", sorted_test[0].file); return(-1); } /* the node has no incoming edge */ // printf("the node %" PRId64 " has no incoming edge\n", node_id); utkv_push(res, sorted_test[node_id]); /* mark pushed */ utkv_at(mark, node_id) = -1; /* delete edges */ for(uint64_t j = 0; j < test_cnt; j++) { if(node_id == j) { continue; } for(uint64_t k = 0; k < utkv_size(utkv_at(dag, j)); k++) { if(utkv_at(utkv_at(dag, j), k) == node_id) { // printf("the node %" PRId64 " had edge from %" PRId64 "\n", j, node_id); utkv_at(utkv_at(dag, j), k) = -1; utkv_at(mark, j)--; // printf("and then node %" PRId64 " has %d incoming edges\n", j, utkv_at(mark, j)); } } } } if(utkv_size(res) != test_cnt) { fprintf(stderr, ut_color(UT_RED, "ERROR") ": detected circular dependency in the tests in `" ut_color(UT_MAGENTA, "%s") "'.\n", sorted_test[0].file); return(-1); } /* write back */ for(uint64_t i = 0; i < test_cnt; i++) { sorted_test[i] = utkv_at(res, i); } /* cleanup */ for(uint64_t i = 0; i < test_cnt; i++) { utkv_destroy(utkv_at(dag, i)); } utkv_destroy(dag); utkv_destroy(mark); utkv_destroy(res); return(0); } static inline int ut_toposort_by_group( struct ut_s *sorted_test, uint64_t test_cnt, struct ut_group_config_s *sorted_config, uint64_t *file_idx, uint64_t file_cnt) { /* init dag */ utkvec_t(utkvec_t(uint64_t)) dag; utkv_init(dag); utkv_reserve(dag, file_cnt); for(uint64_t i = 0; i < file_cnt; i++) { utkv_init(utkv_at(dag, i)); } /* build dag */ for(uint64_t i = 0; i < file_cnt; i++) { /* enumerate depends_on */ char const *const *d = sorted_config[i].depends_on; while(*d != NULL) { /* enumerate tests */ for(uint64_t j = 0; j < file_cnt; j++) { if(i == j) { continue; } if(ut_strcmp(sorted_config[j].name, *d) == 0) { // printf("edge found from group %" PRId64 " to group %" PRId64 "\n", j, i); utkv_push(utkv_at(dag, i), j); } } d++; } } /* build mark */ utkvec_t(int8_t) mark; utkv_init(mark); for(uint64_t i = 0; i < file_cnt; i++) { // printf("incoming edge count %" PRId64 " : %" PRId64 "\n", i, utkv_size(utkv_at(dag, i))); utkv_push(mark, utkv_size(utkv_at(dag, i))); } /* sort */ utkvec_t(struct ut_s) test_buf; utkvec_t(struct ut_group_config_s) config_buf; utkv_init(test_buf); utkv_init(config_buf); // utkvec_t(uint64_t) res; // utkv_init(res); for(uint64_t i = 0; i < file_cnt; i++) { uint64_t file_id = (uint64_t)-1LL; for(uint64_t j = 0; j < file_cnt; j++) { /* check if the node has incoming edges or is already pushed */ if(utkv_at(mark, j) == 0) { file_id = j; break; } } if(file_id == (uint64_t)-1LL) { fprintf(stderr, ut_color(UT_RED, "ERROR") ": detected circular dependency between groups.\n"); return(-1); } /* the node has no incoming edge */ // printf("the node %" PRId64 " has no incoming edge\n", file_id); // utkv_push(res, file_id); utkv_push(config_buf, sorted_config[file_id]); for(uint64_t j = file_idx[file_id]; j < file_idx[file_id + 1]; j++) { utkv_push(test_buf, sorted_test[j]); } /* mark pushed */ utkv_at(mark, file_id) = -1; /* delete edges */ for(uint64_t j = 0; j < file_cnt; j++) { if(file_id == j) { continue; } for(uint64_t k = 0; k < utkv_size(utkv_at(dag, j)); k++) { if(utkv_at(utkv_at(dag, j), k) == file_id) { // printf("the node %" PRId64 " had edge from %" PRId64 "\n", j, file_id); utkv_at(utkv_at(dag, j), k) = -1; utkv_at(mark, j)--; // printf("and then node %" PRId64 " has %d incoming edges\n", j, utkv_at(mark, j)); } } } } if(utkv_size(config_buf) != file_cnt) { fprintf(stderr, ut_color(UT_RED, "ERROR") ": detected circular dependency between groups.\n"); return(-1); } /* write back */ for(uint64_t i = 0; i < test_cnt; i++) { sorted_test[i] = utkv_at(test_buf, i); } for(uint64_t i = 0; i < file_cnt; i++) { sorted_config[i] = utkv_at(config_buf, i); } /* cleanup */ for(uint64_t i = 0; i < file_cnt; i++) { utkv_destroy(utkv_at(dag, i)); } utkv_destroy(dag); utkv_destroy(mark); utkv_destroy(test_buf); utkv_destroy(config_buf); return(0); } /** * @fn ut_build_short_option_string * @brief build short getopt string (i.e. "a:b:vVQ") from an array of struct option */ static inline char *ut_build_short_option_string(struct option const *opts) { char *str = NULL, *ps; uint64_t len = 0; struct option const *po = NULL; for(po = opts; po->name != NULL; po++) { len++; } str = ps = (char *)malloc(2 * len + 1); for(po = opts; po->name != NULL; po++) { *ps++ = (char)po->val; if(po->has_arg != no_argument) { *ps++ = ':'; } } *ps = '\0'; return(str); } /** * @fn ut_modify_test_config_mark */ static inline int ut_modify_test_config_mark( char const *arg, void *_test, int64_t cnt) { struct ut_s *test = (struct ut_s *)_test; char const *p = arg, *b = arg; while(*p != '\0') { /* parse with comma */ while(*p != '\0' && *p != ',') { p++; } /* copy string */ char buf[p - b + 1]; memcpy(buf, b, p - b); buf[p - b] = '\0'; /* linear search among tests */ int marked = 0; for(int64_t i = 0; i < cnt; i++) { if(ut_strcmp(test[i].name, buf) == 0) { test[i].exec = 2; marked = 1; } else { test[i].exec = 0; } } if(marked == 0) { fprintf(stderr, ut_color(UT_YELLOW, "Warning") ": group `%s' not found.\n", buf); } if(*p == '\0') { break; } b = ++p; } return(0); } /** * @fn ut_modify_test_config_all */ static inline int ut_modify_test_config_all( void *_test, int64_t cnt) { struct ut_s *test = (struct ut_s *)_test; for(int64_t i = 0; i < cnt; i++) { test[i].exec = 1; } return(0); } /** * @fn ut_print_help */ static inline void ut_print_help(void) { static char const *help_message = "\n" " unittest.h -- simple unittesting framework for C99\n" "\n" " Options:\n" " -g, --group [STR,...] specify group names\n" " -t, --test [STR,...] specify test names\n" " -s, --seed [INT invoke libc::srand with the seed\n" " -o, --stdout redirect to stdout\n" " -j, --json print result in json\n" " -n, --threads [INT] number of threads\n" " -h, --help show this message\n" "\n" " this is an auto-generated message from unittest.h\n" " the latest source is available at:\n" " https://github.com/ocxtal/unittest.h\n" "\n"; fprintf(stderr, "%s", help_message); return; } /** * @fn ut_modify_test_config */ static inline int ut_modify_test_config( int argc, char *const argv[], struct ut_global_config_s *params, struct ut_s *sorted_test, int64_t test_cnt, struct ut_group_config_s *sorted_config, int64_t file_cnt) { static struct option const opts_long[] = { { "group", required_argument, NULL, 'g' }, { "test", required_argument, NULL, 't' }, { "seed", required_argument, NULL, 's' }, { "stdout", no_argument, NULL, 'o' }, { "json", no_argument, NULL, 'j' }, { "threads", required_argument, NULL, 'n' }, { "help", no_argument, NULL, 'h' }, { NULL, 0, NULL, 0 } }; char *opts_short = ut_build_short_option_string(opts_long); int c, idx; char const *group_arg = NULL, *test_arg = NULL; while((c = getopt_long(argc, argv, opts_short, opts_long, &idx)) != -1) { switch(c) { case 'g': group_arg = optarg; break; case 't': test_arg = optarg; break; case 's': srand((unsigned int)atol(optarg)); break; case 'j': params->printer = ut_json_printer; break; case 'o': params->fp = stdout; break; case 'n': params->threads = atoi(optarg); break; case 'h': ut_print_help(); return(1); default: break; } } if(group_arg != NULL) { ut_modify_test_config_mark(group_arg, (void *)sorted_config, file_cnt); } else { ut_modify_test_config_all((void *)sorted_config, file_cnt); } if(test_arg != NULL) { ut_modify_test_config_mark(test_arg, (void *)sorted_test, test_cnt); } else { ut_modify_test_config_all((void *)sorted_test, test_cnt); } free(opts_short); return(0); } /** * @fn ut_propagate_config */ static inline void ut_propagate_config( struct ut_s *test, int64_t test_cnt, struct ut_group_config_s *compd_config, uint64_t *sorted_file_idx, int64_t file_cnt) { /* set index */ for(uint64_t i = 0; i < file_cnt; i++) { for(uint64_t j = sorted_file_idx[i]; j < sorted_file_idx[i + 1]; j++) { test[j].index = i; test[j].succ = 0; /* clear counters */ test[j].fail = 0; } } return; } /** * @fn ut_run_test */ static void ut_run_test( struct ut_s *test, struct ut_global_config_s const *gconf, struct ut_group_config_s const *compd_config) { if(test->exec == 0) { return; } uint64_t index = test->index; /* initialize group context */ void *gctx = NULL; if(compd_config[index].init != NULL && compd_config[index].clean != NULL) { gctx = compd_config[index].init(compd_config[index].params); } /* initialize local context */ void *ctx = NULL; if(test->init != NULL && test->clean != NULL) { ctx = test->init(test->params); } /* run a test */ test->fn(ctx, gctx, test, gconf, &compd_config[index]); /* cleanup contexts */ if(test->init != NULL && test->clean != NULL) { test->clean(ctx); } if(compd_config[index].init != NULL && compd_config[index].clean != NULL) { compd_config[index].clean(gctx); } return; } /** * @fn ut_main_impl */ static int ut_main_impl(int argc, char *argv[]) { /* dump symbol table */ struct ut_nm_result_s *nm = ut_nm(argv[0]); if(nm == NULL) { return(1); } /* dump tests and configs */ struct ut_s *test = ut_get_unittest(nm); struct ut_group_config_s *config = ut_get_ut_config(nm); /* sort by group, tag, line */ ut_sort(test, config); struct ut_group_config_s *compd_config = ut_compensate_config(test, config); uint64_t test_cnt = ut_get_total_test_count(test); uint64_t *file_idx = ut_build_file_index(test); uint64_t file_cnt = ut_get_total_file_count(test); // printf("%" PRId64 "\n", file_cnt); /* topological sort by tag */ for(uint64_t i = 0; i < file_cnt; i++) { // printf("toposort %" PRId64 ", %" PRId64 "\n", file_idx[i], file_idx[i + 1]); if(ut_toposort_by_tag(&test[file_idx[i]], file_idx[i + 1] - file_idx[i]) != 0) { fprintf(stderr, ut_color(UT_RED, "ERROR") ": failed to order tests. check if the depends_on options are sane.\n"); return(1); } } // ut_dump_test(test); /* topological sort by group */ if(ut_toposort_by_group(test, test_cnt, compd_config, file_idx, file_cnt) != 0) { fprintf(stderr, ut_color(UT_RED, "ERROR") ": failed to order tests. check if the depends_on options are sane.\n"); return(1); } /* rebuild file idx */ uint64_t *sorted_file_idx = ut_build_file_index(test); /* init default params */ struct ut_global_config_s gconf = { .fp = stderr, .printer = ut_default_printer }; /* modify config */ if(ut_modify_test_config(argc, argv, &gconf, test, test_cnt, compd_config, file_cnt)) { return 1; } /* copy exec flag */ ut_propagate_config(test, test_cnt, compd_config, sorted_file_idx, file_cnt); /* run tests */ #ifdef _OPENMP omp_set_num_threads(gconf.threads); #pragma omp parallel for #endif for(uint64_t i = 0; i < test_cnt; i++) { ut_run_test(&test[i], &gconf, compd_config); } /* collect results */ struct ut_result_s *res = calloc(sizeof(struct ut_result_s), file_cnt); for(uint64_t i = 0; i < test_cnt; i++) { uint64_t index = test[i].index; res[index].cnt++; res[index].succ += test[i].succ; res[index].fail += test[i].fail; } /* print results */ gconf.printer.result(&gconf, compd_config, res, file_cnt); free(res); free(sorted_file_idx); free(file_idx); free(compd_config); free(test); free(config); free(nm); return(0); } static int unittest_main(int argc, char *argv[]) { /* disable unittests if UNITTEST == 0 */ #if UNITTEST != 0 return(ut_main_impl(argc, argv)); #else return(0); #endif } #if UNITTEST_ALIAS_MAIN != 0 int main(int argc, char *argv[]) { return(unittest_main(argc, argv)); } #endif /** * end of unittest.h */
threshold.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % TTTTT H H RRRR EEEEE SSSSS H H OOO L DDDD % % T H H R R E SS H H O O L D D % % T HHHHH RRRR EEE SSS HHHHH O O L D D % % T H H R R E SS H H O O L D D % % T H H R R EEEEE SSSSS H H OOO LLLLL DDDD % % % % % % MagickCore Image Threshold Methods % % % % Software Design % % John Cristy % % October 1996 % % % % % % Copyright 1999-2012 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 "magick/studio.h" #include "magick/property.h" #include "magick/blob.h" #include "magick/cache-view.h" #include "magick/color.h" #include "magick/color-private.h" #include "magick/colormap.h" #include "magick/colorspace.h" #include "magick/configure.h" #include "magick/constitute.h" #include "magick/decorate.h" #include "magick/draw.h" #include "magick/enhance.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/effect.h" #include "magick/fx.h" #include "magick/gem.h" #include "magick/geometry.h" #include "magick/image-private.h" #include "magick/list.h" #include "magick/log.h" #include "magick/memory_.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/montage.h" #include "magick/option.h" #include "magick/pixel-private.h" #include "magick/quantize.h" #include "magick/quantum.h" #include "magick/random_.h" #include "magick/random-private.h" #include "magick/resize.h" #include "magick/resource_.h" #include "magick/segment.h" #include "magick/shear.h" #include "magick/signature-private.h" #include "magick/string_.h" #include "magick/string-private.h" #include "magick/thread-private.h" #include "magick/threshold.h" #include "magick/transform.h" #include "magick/xml-tree.h" /* Define declarations. */ #define ThresholdsFilename "thresholds.xml" /* Typedef declarations. */ struct _ThresholdMap { char *map_id, *description; size_t width, height; ssize_t divisor, *levels; }; /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A d a p t i v e T h r e s h o l d I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AdaptiveThresholdImage() selects an individual threshold for each pixel % based on the range of intensity values in its local neighborhood. This % allows for thresholding of an image whose global intensity histogram % doesn't contain distinctive peaks. % % The format of the AdaptiveThresholdImage method is: % % Image *AdaptiveThresholdImage(const Image *image, % const size_t width,const size_t height, % const ssize_t offset,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o width: the width of the local neighborhood. % % o height: the height of the local neighborhood. % % o offset: the mean offset. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *AdaptiveThresholdImage(const Image *image, const size_t width,const size_t height,const ssize_t offset, ExceptionInfo *exception) { #define ThresholdImageTag "Threshold/Image" CacheView *image_view, *threshold_view; Image *threshold_image; MagickBooleanType status; MagickOffsetType progress; MagickPixelPacket zero; MagickRealType number_pixels; ssize_t y; assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); threshold_image=CloneImage(image,0,0,MagickTrue,exception); if (threshold_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(threshold_image,DirectClass) == MagickFalse) { InheritException(exception,&threshold_image->exception); threshold_image=DestroyImage(threshold_image); return((Image *) NULL); } /* Local adaptive threshold. */ status=MagickTrue; progress=0; GetMagickPixelPacket(image,&zero); number_pixels=(MagickRealType) width*height; image_view=AcquireCacheView(image); threshold_view=AcquireCacheView(threshold_image); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) #endif for (y=0; y < (ssize_t) image->rows; y++) { MagickBooleanType sync; register const IndexPacket *restrict indexes; register const PixelPacket *restrict p; register IndexPacket *restrict threshold_indexes; register ssize_t x; register PixelPacket *restrict q; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,-((ssize_t) width/2L),y-(ssize_t) height/2L,image->columns+width,height,exception); q=GetCacheViewAuthenticPixels(threshold_view,0,y,threshold_image->columns,1, exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) { status=MagickFalse; continue; } indexes=GetCacheViewVirtualIndexQueue(image_view); threshold_indexes=GetCacheViewAuthenticIndexQueue(threshold_view); for (x=0; x < (ssize_t) image->columns; x++) { MagickPixelPacket mean, pixel; register const PixelPacket *r; register ssize_t u; ssize_t v; pixel=zero; mean=zero; r=p; for (v=0; v < (ssize_t) height; v++) { for (u=0; u < (ssize_t) width; u++) { pixel.red+=r[u].red; pixel.green+=r[u].green; pixel.blue+=r[u].blue; pixel.opacity+=r[u].opacity; if (image->colorspace == CMYKColorspace) pixel.index=(MagickRealType) GetPixelIndex(indexes+x+(r-p)+u); } r+=image->columns+width; } mean.red=(MagickRealType) (pixel.red/number_pixels+offset); mean.green=(MagickRealType) (pixel.green/number_pixels+offset); mean.blue=(MagickRealType) (pixel.blue/number_pixels+offset); mean.opacity=(MagickRealType) (pixel.opacity/number_pixels+offset); if (image->colorspace == CMYKColorspace) mean.index=(MagickRealType) (pixel.index/number_pixels+offset); SetPixelRed(q,((MagickRealType) GetPixelRed(q) <= mean.red) ? 0 : QuantumRange); SetPixelGreen(q,((MagickRealType) GetPixelGreen(q) <= mean.green) ? 0 : QuantumRange); SetPixelBlue(q,((MagickRealType) GetPixelBlue(q) <= mean.blue) ? 0 : QuantumRange); SetPixelOpacity(q,((MagickRealType) GetPixelOpacity(q) <= mean.opacity) ? 0 : QuantumRange); if (image->colorspace == CMYKColorspace) SetPixelIndex(threshold_indexes+x,(((MagickRealType) GetPixelIndex(threshold_indexes+x) <= mean.index) ? 0 : QuantumRange)); p++; q++; } sync=SyncCacheViewAuthenticPixels(threshold_view,exception); if (sync == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_AdaptiveThresholdImage) #endif proceed=SetImageProgress(image,ThresholdImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } threshold_view=DestroyCacheView(threshold_view); image_view=DestroyCacheView(image_view); if (status == MagickFalse) threshold_image=DestroyImage(threshold_image); return(threshold_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % B i l e v e l I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % BilevelImage() changes the value of individual pixels based on the % intensity of each pixel channel. The result is a high-contrast image. % % More precisely each channel value of the image is 'thresholded' so that if % it is equal to or less than the given value it is set to zero, while any % value greater than that give is set to it maximum or QuantumRange. % % This function is what is used to implement the "-threshold" operator for % the command line API. % % If the default channel setting is given the image is thresholded using just % the gray 'intensity' of the image, rather than the individual channels. % % The format of the BilevelImageChannel method is: % % MagickBooleanType BilevelImage(Image *image,const double threshold) % MagickBooleanType BilevelImageChannel(Image *image, % const ChannelType channel,const double threshold) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel type. % % o threshold: define the threshold values. % % Aside: You can get the same results as operator using LevelImageChannels() % with the 'threshold' value for both the black_point and the white_point. % */ MagickExport MagickBooleanType BilevelImage(Image *image,const double threshold) { MagickBooleanType status; status=BilevelImageChannel(image,DefaultChannels,threshold); return(status); } MagickExport MagickBooleanType BilevelImageChannel(Image *image, const ChannelType channel,const double threshold) { #define ThresholdImageTag "Threshold/Image" CacheView *image_view; ExceptionInfo *exception; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (SetImageStorageClass(image,DirectClass) == MagickFalse) return(MagickFalse); /* Bilevel threshold image. */ status=MagickTrue; progress=0; exception=(&image->exception); image_view=AcquireCacheView(image); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,8) shared(progress,status) #endif for (y=0; y < (ssize_t) image->rows; y++) { register IndexPacket *restrict indexes; register ssize_t x; register PixelPacket *restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); if (channel == DefaultChannels) { for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,(MagickRealType) PixelIntensityToQuantum(q) <= threshold ? 0 : QuantumRange); SetPixelGreen(q,GetPixelRed(q)); SetPixelBlue(q,GetPixelRed(q)); q++; } } else for (x=0; x < (ssize_t) image->columns; x++) { if ((channel & RedChannel) != 0) SetPixelRed(q,(MagickRealType) GetPixelRed(q) <= threshold ? 0 : QuantumRange); if ((channel & GreenChannel) != 0) SetPixelGreen(q,(MagickRealType) GetPixelGreen(q) <= threshold ? 0 : QuantumRange); if ((channel & BlueChannel) != 0) SetPixelBlue(q,(MagickRealType) GetPixelBlue(q) <= threshold ? 0 : QuantumRange); if ((channel & OpacityChannel) != 0) { if (image->matte == MagickFalse) SetPixelOpacity(q,(MagickRealType) GetPixelOpacity(q) <= threshold ? 0 : QuantumRange); else SetPixelOpacity(q,(MagickRealType) GetPixelOpacity(q) <= threshold ? OpaqueOpacity : TransparentOpacity); } if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) SetPixelIndex(indexes+x,(MagickRealType) GetPixelIndex(indexes+x) <= threshold ? 0 : QuantumRange); q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_BilevelImageChannel) #endif proceed=SetImageProgress(image,ThresholdImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % B l a c k T h r e s h o l d I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % BlackThresholdImage() is like ThresholdImage() but forces all pixels below % the threshold into black while leaving all pixels at or above the threshold % unchanged. % % The format of the BlackThresholdImage method is: % % MagickBooleanType BlackThresholdImage(Image *image,const char *threshold) % MagickBooleanType BlackThresholdImageChannel(Image *image, % const ChannelType channel,const char *threshold, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel or channels to be thresholded. % % o threshold: Define the threshold value. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType BlackThresholdImage(Image *image, const char *threshold) { MagickBooleanType status; status=BlackThresholdImageChannel(image,DefaultChannels,threshold, &image->exception); return(status); } MagickExport MagickBooleanType BlackThresholdImageChannel(Image *image, const ChannelType channel,const char *thresholds,ExceptionInfo *exception) { #define ThresholdImageTag "Threshold/Image" CacheView *image_view; GeometryInfo geometry_info; MagickBooleanType status; MagickOffsetType progress; MagickPixelPacket threshold; MagickStatusType flags; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (thresholds == (const char *) NULL) return(MagickTrue); if (SetImageStorageClass(image,DirectClass) == MagickFalse) return(MagickFalse); GetMagickPixelPacket(image,&threshold); flags=ParseGeometry(thresholds,&geometry_info); threshold.red=geometry_info.rho; threshold.green=geometry_info.sigma; if ((flags & SigmaValue) == 0) threshold.green=threshold.red; threshold.blue=geometry_info.xi; if ((flags & XiValue) == 0) threshold.blue=threshold.red; threshold.opacity=geometry_info.psi; if ((flags & PsiValue) == 0) threshold.opacity=threshold.red; threshold.index=geometry_info.chi; if ((flags & ChiValue) == 0) threshold.index=threshold.red; if ((flags & PercentValue) != 0) { threshold.red*=(QuantumRange/100.0); threshold.green*=(QuantumRange/100.0); threshold.blue*=(QuantumRange/100.0); threshold.opacity*=(QuantumRange/100.0); threshold.index*=(QuantumRange/100.0); } /* Black threshold image. */ status=MagickTrue; progress=0; image_view=AcquireCacheView(image); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,8) shared(progress,status) #endif for (y=0; y < (ssize_t) image->rows; y++) { register IndexPacket *restrict indexes; register ssize_t x; register PixelPacket *restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { if (channel == DefaultChannels) { if (PixelIntensity(q) < MagickPixelIntensity(&threshold)) { SetPixelRed(q,0); SetPixelGreen(q,0); SetPixelBlue(q,0); if (image->colorspace == CMYKColorspace) SetPixelIndex(indexes+x,0); } } else { if (((channel & RedChannel) != 0) && ((MagickRealType) GetPixelRed(q) < threshold.red)) SetPixelRed(q,0); if (((channel & GreenChannel) != 0) && ((MagickRealType) GetPixelGreen(q) < threshold.green)) SetPixelGreen(q,0); if (((channel & BlueChannel) != 0) && ((MagickRealType) GetPixelBlue(q) < threshold.blue)) SetPixelBlue(q,0); if (((channel & OpacityChannel) != 0) && ((MagickRealType) GetPixelOpacity(q) < threshold.opacity)) SetPixelOpacity(q,0); if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace) && ((MagickRealType) GetPixelIndex(indexes+x) < threshold.index)) SetPixelIndex(indexes+x,0); } q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_BlackThresholdImageChannel) #endif proceed=SetImageProgress(image,ThresholdImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C l a m p I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ClampImage() restricts the color range from 0 to the quantum depth. % % The format of the ClampImageChannel method is: % % MagickBooleanType ClampImage(Image *image) % MagickBooleanType ClampImageChannel(Image *image, % const ChannelType channel) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel type. % */ static inline Quantum ClampToUnsignedQuantum(const Quantum quantum) { #if defined(MAGICKCORE_HDRI_SUPPORT) if (quantum <= 0) return(0); if (quantum >= QuantumRange) return(QuantumRange); return(quantum); #else return(quantum); #endif } MagickExport MagickBooleanType ClampImage(Image *image) { MagickBooleanType status; status=ClampImageChannel(image,DefaultChannels); return(status); } MagickExport MagickBooleanType ClampImageChannel(Image *image, const ChannelType channel) { #define ClampImageTag "Clamp/Image" CacheView *image_view; ExceptionInfo *exception; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->storage_class == PseudoClass) { register ssize_t i; register PixelPacket *restrict q; q=image->colormap; for (i=0; i < (ssize_t) image->colors; i++) { SetPixelRed(q,ClampToUnsignedQuantum( GetPixelRed(q))); SetPixelGreen(q,ClampToUnsignedQuantum( GetPixelGreen(q))); SetPixelBlue(q,ClampToUnsignedQuantum( GetPixelBlue(q))); SetPixelOpacity(q,ClampToUnsignedQuantum( GetPixelOpacity(q))); q++; } return(SyncImage(image)); } /* Clamp image. */ status=MagickTrue; progress=0; exception=(&image->exception); image_view=AcquireCacheView(image); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,8) shared(progress,status) #endif for (y=0; y < (ssize_t) image->rows; y++) { register IndexPacket *restrict indexes; register ssize_t x; register PixelPacket *restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { if ((channel & RedChannel) != 0) SetPixelRed(q,ClampToUnsignedQuantum( GetPixelRed(q))); if ((channel & GreenChannel) != 0) SetPixelGreen(q,ClampToUnsignedQuantum( GetPixelGreen(q))); if ((channel & BlueChannel) != 0) SetPixelBlue(q,ClampToUnsignedQuantum( GetPixelBlue(q))); if ((channel & OpacityChannel) != 0) SetPixelOpacity(q,ClampToUnsignedQuantum( GetPixelOpacity(q))); if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) SetPixelIndex(indexes+x,ClampToUnsignedQuantum( GetPixelIndex(indexes+x))); q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_ClampImageChannel) #endif proceed=SetImageProgress(image,ClampImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e s t r o y T h r e s h o l d M a p % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyThresholdMap() de-allocate the given ThresholdMap % % The format of the ListThresholdMaps method is: % % ThresholdMap *DestroyThresholdMap(Threshold *map) % % A description of each parameter follows. % % o map: Pointer to the Threshold map to destroy % */ MagickExport ThresholdMap *DestroyThresholdMap(ThresholdMap *map) { assert(map != (ThresholdMap *) NULL); if (map->map_id != (char *) NULL) map->map_id=DestroyString(map->map_id); if (map->description != (char *) NULL) map->description=DestroyString(map->description); if (map->levels != (ssize_t *) NULL) map->levels=(ssize_t *) RelinquishMagickMemory(map->levels); map=(ThresholdMap *) RelinquishMagickMemory(map); return(map); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t T h r e s h o l d M a p F i l e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetThresholdMapFile() look for a given threshold map name or alias in the % given XML file data, and return the allocated the map when found. % % The format of the ListThresholdMaps method is: % % ThresholdMap *GetThresholdMap(const char *xml,const char *filename, % const char *map_id,ExceptionInfo *exception) % % A description of each parameter follows. % % o xml: The threshold map list in XML format. % % o filename: The threshold map XML filename. % % o map_id: ID of the map to look for in XML list. % % o exception: return any errors or warnings in this structure. % */ MagickExport ThresholdMap *GetThresholdMapFile(const char *xml, const char *filename,const char *map_id,ExceptionInfo *exception) { const char *attr, *content; double value; ThresholdMap *map; XMLTreeInfo *description, *levels, *threshold, *thresholds; map = (ThresholdMap *)NULL; (void) LogMagickEvent(ConfigureEvent,GetMagickModule(), "Loading threshold map file \"%s\" ...",filename); thresholds=NewXMLTree(xml,exception); if ( thresholds == (XMLTreeInfo *)NULL ) return(map); for( threshold = GetXMLTreeChild(thresholds,"threshold"); threshold != (XMLTreeInfo *)NULL; threshold = GetNextXMLTreeTag(threshold) ) { attr = GetXMLTreeAttribute(threshold, "map"); if ( (attr != (char *)NULL) && (LocaleCompare(map_id,attr) == 0) ) break; attr = GetXMLTreeAttribute(threshold, "alias"); if ( (attr != (char *)NULL) && (LocaleCompare(map_id,attr) == 0) ) break; } if ( threshold == (XMLTreeInfo *)NULL ) { return(map); } description = GetXMLTreeChild(threshold,"description"); if ( description == (XMLTreeInfo *)NULL ) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingElement", "<description>, map \"%s\"", map_id); thresholds = DestroyXMLTree(thresholds); return(map); } levels = GetXMLTreeChild(threshold,"levels"); if ( levels == (XMLTreeInfo *)NULL ) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingElement", "<levels>, map \"%s\"", map_id); thresholds = DestroyXMLTree(thresholds); return(map); } /* The map has been found -- Allocate a Threshold Map to return */ map = (ThresholdMap *)AcquireMagickMemory(sizeof(ThresholdMap)); if ( map == (ThresholdMap *)NULL ) ThrowFatalException(ResourceLimitFatalError,"UnableToAcquireThresholdMap"); map->map_id = (char *)NULL; map->description = (char *)NULL; map->levels = (ssize_t *) NULL; /* Assign Basic Attributes */ attr = GetXMLTreeAttribute(threshold, "map"); if ( attr != (char *)NULL ) map->map_id = ConstantString(attr); content = GetXMLTreeContent(description); if ( content != (char *)NULL ) map->description = ConstantString(content); attr = GetXMLTreeAttribute(levels, "width"); if ( attr == (char *)NULL ) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingAttribute", "<levels width>, map \"%s\"", map_id); thresholds = DestroyXMLTree(thresholds); map = DestroyThresholdMap(map); return(map); } map->width = StringToUnsignedLong(attr); if ( map->width == 0 ) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlInvalidAttribute", "<levels width>, map \"%s\"", map_id); thresholds = DestroyXMLTree(thresholds); map = DestroyThresholdMap(map); return(map); } attr = GetXMLTreeAttribute(levels, "height"); if ( attr == (char *)NULL ) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingAttribute", "<levels height>, map \"%s\"", map_id); thresholds = DestroyXMLTree(thresholds); map = DestroyThresholdMap(map); return(map); } map->height = StringToUnsignedLong(attr); if ( map->height == 0 ) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlInvalidAttribute", "<levels height>, map \"%s\"", map_id); thresholds = DestroyXMLTree(thresholds); map = DestroyThresholdMap(map); return(map); } attr = GetXMLTreeAttribute(levels, "divisor"); if ( attr == (char *)NULL ) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingAttribute", "<levels divisor>, map \"%s\"", map_id); thresholds = DestroyXMLTree(thresholds); map = DestroyThresholdMap(map); return(map); } map->divisor = (ssize_t) StringToLong(attr); if ( map->divisor < 2 ) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlInvalidAttribute", "<levels divisor>, map \"%s\"", map_id); thresholds = DestroyXMLTree(thresholds); map = DestroyThresholdMap(map); return(map); } /* Allocate theshold levels array */ content = GetXMLTreeContent(levels); if ( content == (char *)NULL ) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingContent", "<levels>, map \"%s\"", map_id); thresholds = DestroyXMLTree(thresholds); map = DestroyThresholdMap(map); return(map); } map->levels=(ssize_t *) AcquireQuantumMemory((size_t) map->width,map->height* sizeof(*map->levels)); if ( map->levels == (ssize_t *)NULL ) ThrowFatalException(ResourceLimitFatalError,"UnableToAcquireThresholdMap"); { /* parse levels into integer array */ ssize_t i; char *p; for( i=0; i< (ssize_t) (map->width*map->height); i++) { map->levels[i] = (ssize_t)strtol(content, &p, 10); if ( p == content ) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlInvalidContent", "<level> too few values, map \"%s\"", map_id); thresholds = DestroyXMLTree(thresholds); map = DestroyThresholdMap(map); return(map); } if ( map->levels[i] < 0 || map->levels[i] > map->divisor ) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlInvalidContent", "<level> %.20g out of range, map \"%s\"", (double) map->levels[i],map_id); thresholds = DestroyXMLTree(thresholds); map = DestroyThresholdMap(map); return(map); } content = p; } value=(double) strtol(content,&p,10); (void) value; if (p != content) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlInvalidContent", "<level> too many values, map \"%s\"", map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } } thresholds = DestroyXMLTree(thresholds); return(map); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t T h r e s h o l d M a p % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetThresholdMap() load and search one or more threshold map files for the % a map matching the given name or aliase. % % The format of the GetThresholdMap method is: % % ThresholdMap *GetThresholdMap(const char *map_id, % ExceptionInfo *exception) % % A description of each parameter follows. % % o map_id: ID of the map to look for. % % o exception: return any errors or warnings in this structure. % */ MagickExport ThresholdMap *GetThresholdMap(const char *map_id, ExceptionInfo *exception) { const StringInfo *option; LinkedListInfo *options; ThresholdMap *map; map=(ThresholdMap *)NULL; options=GetConfigureOptions(ThresholdsFilename,exception); while (( option=(const StringInfo *) GetNextValueInLinkedList(options) ) != (const StringInfo *) NULL && map == (ThresholdMap *)NULL ) map=GetThresholdMapFile((const char *) GetStringInfoDatum(option), GetStringInfoPath(option),map_id,exception); options=DestroyConfigureOptions(options); return(map); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + L i s t T h r e s h o l d M a p F i l e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ListThresholdMapFile() lists the threshold maps and their descriptions % in the given XML file data. % % The format of the ListThresholdMaps method is: % % MagickBooleanType ListThresholdMaps(FILE *file,const char*xml, % const char *filename,ExceptionInfo *exception) % % A description of each parameter follows. % % o file: An pointer to the output FILE. % % o xml: The threshold map list in XML format. % % o filename: The threshold map XML filename. % % o exception: return any errors or warnings in this structure. % */ MagickBooleanType ListThresholdMapFile(FILE *file,const char *xml, const char *filename,ExceptionInfo *exception) { XMLTreeInfo *thresholds,*threshold,*description; const char *map,*alias,*content; assert( xml != (char *)NULL ); assert( file != (FILE *)NULL ); (void) LogMagickEvent(ConfigureEvent,GetMagickModule(), "Loading threshold map file \"%s\" ...",filename); thresholds=NewXMLTree(xml,exception); if ( thresholds == (XMLTreeInfo *)NULL ) return(MagickFalse); (void) FormatLocaleFile(file,"%-16s %-12s %s\n","Map","Alias","Description"); (void) FormatLocaleFile(file, "----------------------------------------------------\n"); for( threshold = GetXMLTreeChild(thresholds,"threshold"); threshold != (XMLTreeInfo *)NULL; threshold = GetNextXMLTreeTag(threshold) ) { map = GetXMLTreeAttribute(threshold, "map"); if (map == (char *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingAttribute", "<map>"); thresholds=DestroyXMLTree(thresholds); return(MagickFalse); } alias = GetXMLTreeAttribute(threshold, "alias"); /* alias is optional, no if test needed */ description=GetXMLTreeChild(threshold,"description"); if ( description == (XMLTreeInfo *)NULL ) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingElement", "<description>, map \"%s\"", map); thresholds=DestroyXMLTree(thresholds); return(MagickFalse); } content=GetXMLTreeContent(description); if ( content == (char *)NULL ) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingContent", "<description>, map \"%s\"", map); thresholds=DestroyXMLTree(thresholds); return(MagickFalse); } (void) FormatLocaleFile(file,"%-16s %-12s %s\n",map,alias ? alias : "", content); } thresholds=DestroyXMLTree(thresholds); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % L i s t T h r e s h o l d M a p s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ListThresholdMaps() lists the threshold maps and their descriptions % as defined by "threshold.xml" to a file. % % The format of the ListThresholdMaps method is: % % MagickBooleanType ListThresholdMaps(FILE *file,ExceptionInfo *exception) % % A description of each parameter follows. % % o file: An pointer to the output FILE. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType ListThresholdMaps(FILE *file, ExceptionInfo *exception) { const StringInfo *option; LinkedListInfo *options; MagickStatusType status; status=MagickFalse; if ( file == (FILE *)NULL ) file = stdout; options=GetConfigureOptions(ThresholdsFilename,exception); (void) FormatLocaleFile(file, "\n Threshold Maps for Ordered Dither Operations\n"); while ( ( option=(const StringInfo *) GetNextValueInLinkedList(options) ) != (const StringInfo *) NULL) { (void) FormatLocaleFile(file,"\nPATH: %s\n\n",GetStringInfoPath(option)); status|=ListThresholdMapFile(file,(const char *) GetStringInfoDatum(option), GetStringInfoPath(option),exception); } options=DestroyConfigureOptions(options); return(status != 0 ? MagickTrue : MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % O r d e r e d D i t h e r I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % OrderedDitherImage() uses the ordered dithering technique of reducing color % images to monochrome using positional information to retain as much % information as possible. % % WARNING: This function is deprecated, and is now just a call to % the more more powerful OrderedPosterizeImage(); function. % % The format of the OrderedDitherImage method is: % % MagickBooleanType OrderedDitherImage(Image *image) % MagickBooleanType OrderedDitherImageChannel(Image *image, % const ChannelType channel,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel or channels to be thresholded. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType OrderedDitherImage(Image *image) { MagickBooleanType status; status=OrderedDitherImageChannel(image,DefaultChannels,&image->exception); return(status); } MagickExport MagickBooleanType OrderedDitherImageChannel(Image *image, const ChannelType channel,ExceptionInfo *exception) { MagickBooleanType status; /* Call the augumented function OrderedPosterizeImage() */ status=OrderedPosterizeImageChannel(image,channel,"o8x8",exception); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % O r d e r e d P o s t e r i z e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % OrderedPosterizeImage() will perform a ordered dither based on a number % of pre-defined dithering threshold maps, but over multiple intensity % levels, which can be different for different channels, according to the % input argument. % % The format of the OrderedPosterizeImage method is: % % MagickBooleanType OrderedPosterizeImage(Image *image, % const char *threshold_map,ExceptionInfo *exception) % MagickBooleanType OrderedPosterizeImageChannel(Image *image, % const ChannelType channel,const char *threshold_map, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel or channels to be thresholded. % % o threshold_map: A string containing the name of the threshold dither % map to use, followed by zero or more numbers representing the number % of color levels tho dither between. % % Any level number less than 2 will be equivalent to 2, and means only % binary dithering will be applied to each color channel. % % No numbers also means a 2 level (bitmap) dither will be applied to all % channels, while a single number is the number of levels applied to each % channel in sequence. More numbers will be applied in turn to each of % the color channels. % % For example: "o3x3,6" will generate a 6 level posterization of the % image with a ordered 3x3 diffused pixel dither being applied between % each level. While checker,8,8,4 will produce a 332 colormaped image % with only a single checkerboard hash pattern (50% grey) between each % color level, to basically double the number of color levels with % a bare minimim of dithering. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType OrderedPosterizeImage(Image *image, const char *threshold_map,ExceptionInfo *exception) { MagickBooleanType status; status=OrderedPosterizeImageChannel(image,DefaultChannels,threshold_map, exception); return(status); } MagickExport MagickBooleanType OrderedPosterizeImageChannel(Image *image, const ChannelType channel,const char *threshold_map,ExceptionInfo *exception) { #define DitherImageTag "Dither/Image" CacheView *image_view; LongPixelPacket levels; MagickBooleanType status; MagickOffsetType progress; ssize_t y; ThresholdMap *map; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); if (threshold_map == (const char *) NULL) return(MagickTrue); { char token[MaxTextExtent]; register const char *p; p=(char *)threshold_map; while (((isspace((int) ((unsigned char) *p)) != 0) || (*p == ',')) && (*p != '\0')) p++; threshold_map=p; while (((isspace((int) ((unsigned char) *p)) == 0) && (*p != ',')) && (*p != '\0')) { if ((p-threshold_map) >= (MaxTextExtent-1)) break; token[p-threshold_map] = *p; p++; } token[p-threshold_map] = '\0'; map = GetThresholdMap(token, exception); if ( map == (ThresholdMap *)NULL ) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "InvalidArgument","%s : '%s'","ordered-dither",threshold_map); return(MagickFalse); } } /* Set channel levels from extra comma separated arguments Default to 2, the single value given, or individual channel values */ #if 1 { /* parse directly as a comma separated list of integers */ char *p; p = strchr((char *) threshold_map,','); if ( p != (char *)NULL && isdigit((int) ((unsigned char) *(++p))) ) levels.index = (unsigned int) strtoul(p, &p, 10); else levels.index = 2; levels.red = ((channel & RedChannel ) != 0) ? levels.index : 0; levels.green = ((channel & GreenChannel) != 0) ? levels.index : 0; levels.blue = ((channel & BlueChannel) != 0) ? levels.index : 0; levels.opacity = ((channel & OpacityChannel) != 0) ? levels.index : 0; levels.index = ((channel & IndexChannel) != 0 && (image->colorspace == CMYKColorspace)) ? levels.index : 0; /* if more than a single number, each channel has a separate value */ if ( p != (char *) NULL && *p == ',' ) { p=strchr((char *) threshold_map,','); p++; if ((channel & RedChannel) != 0) levels.red = (unsigned int) strtoul(p, &p, 10), (void)(*p == ',' && p++); if ((channel & GreenChannel) != 0) levels.green = (unsigned int) strtoul(p, &p, 10), (void)(*p == ',' && p++); if ((channel & BlueChannel) != 0) levels.blue = (unsigned int) strtoul(p, &p, 10), (void)(*p == ',' && p++); if ((channel & IndexChannel) != 0 && image->colorspace == CMYKColorspace) levels.index=(unsigned int) strtoul(p, &p, 10), (void)(*p == ',' && p++); if ((channel & OpacityChannel) != 0) levels.opacity = (unsigned int) strtoul(p, &p, 10), (void)(*p == ',' && p++); } } #else /* Parse level values as a geometry */ /* This difficult! * How to map GeometryInfo structure elements into * LongPixelPacket structure elements, but according to channel? * Note the channels list may skip elements!!!! * EG -channel BA -ordered-dither map,2,3 * will need to map g.rho -> l.blue, and g.sigma -> l.opacity * A simpler way is needed, probably converting geometry to a temporary * array, then using channel to advance the index into ssize_t pixel packet. */ #endif #if 0 printf("DEBUG levels r=%u g=%u b=%u a=%u i=%u\n", levels.red, levels.green, levels.blue, levels.opacity, levels.index); #endif { /* Do the posterized ordered dithering of the image */ ssize_t d; /* d = number of psuedo-level divisions added between color levels */ d = map->divisor-1; /* reduce levels to levels - 1 */ levels.red = levels.red ? levels.red-1 : 0; levels.green = levels.green ? levels.green-1 : 0; levels.blue = levels.blue ? levels.blue-1 : 0; levels.opacity = levels.opacity ? levels.opacity-1 : 0; levels.index = levels.index ? levels.index-1 : 0; if (SetImageStorageClass(image,DirectClass) == MagickFalse) { InheritException(exception,&image->exception); return(MagickFalse); } status=MagickTrue; progress=0; image_view=AcquireCacheView(image); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,8) shared(progress,status) #endif for (y=0; y < (ssize_t) image->rows; y++) { register IndexPacket *restrict indexes; register ssize_t x; register PixelPacket *restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t threshold, t, l; /* Figure out the dither threshold for this pixel This must be a integer from 1 to map->divisor-1 */ threshold = map->levels[(x%map->width) +map->width*(y%map->height)]; /* Dither each channel in the image as appropriate Notes on the integer Math... total number of divisions = (levels-1)*(divisor-1)+1) t1 = this colors psuedo_level = q->red * total_divisions / (QuantumRange+1) l = posterization level 0..levels t = dither threshold level 0..divisor-1 NB: 0 only on last Each color_level is of size QuantumRange / (levels-1) NB: All input levels and divisor are already had 1 subtracted Opacity is inverted so 'off' represents transparent. */ if (levels.red) { t = (ssize_t) (QuantumScale*GetPixelRed(q)*(levels.red*d+1)); l = t/d; t = t-l*d; SetPixelRed(q,RoundToQuantum((MagickRealType) ((l+(t >= threshold))*(MagickRealType) QuantumRange/levels.red))); } if (levels.green) { t = (ssize_t) (QuantumScale*GetPixelGreen(q)* (levels.green*d+1)); l = t/d; t = t-l*d; SetPixelGreen(q,RoundToQuantum((MagickRealType) ((l+(t >= threshold))*(MagickRealType) QuantumRange/levels.green))); } if (levels.blue) { t = (ssize_t) (QuantumScale*GetPixelBlue(q)* (levels.blue*d+1)); l = t/d; t = t-l*d; SetPixelBlue(q,RoundToQuantum((MagickRealType) ((l+(t >= threshold))*(MagickRealType) QuantumRange/levels.blue))); } if (levels.opacity) { t = (ssize_t) ((1.0-QuantumScale*GetPixelOpacity(q))* (levels.opacity*d+1)); l = t/d; t = t-l*d; SetPixelOpacity(q,RoundToQuantum((MagickRealType) ((1.0-l-(t >= threshold))*(MagickRealType) QuantumRange/ levels.opacity))); } if (levels.index) { t = (ssize_t) (QuantumScale*GetPixelIndex(indexes+x)* (levels.index*d+1)); l = t/d; t = t-l*d; SetPixelIndex(indexes+x,RoundToQuantum((MagickRealType) ((l+ (t>=threshold))*(MagickRealType) QuantumRange/levels.index))); } q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_OrderedPosterizeImageChannel) #endif proceed=SetImageProgress(image,DitherImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); } map=DestroyThresholdMap(map); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R a n d o m T h r e s h o l d I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RandomThresholdImage() changes the value of individual pixels based on the % intensity of each pixel compared to a random threshold. The result is a % low-contrast, two color image. % % The format of the RandomThresholdImage method is: % % MagickBooleanType RandomThresholdImageChannel(Image *image, % const char *thresholds,ExceptionInfo *exception) % MagickBooleanType RandomThresholdImageChannel(Image *image, % const ChannelType channel,const char *thresholds, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel or channels to be thresholded. % % o thresholds: a geometry string containing low,high thresholds. If the % string contains 2x2, 3x3, or 4x4, an ordered dither of order 2, 3, or 4 % is performed instead. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType RandomThresholdImage(Image *image, const char *thresholds,ExceptionInfo *exception) { MagickBooleanType status; status=RandomThresholdImageChannel(image,DefaultChannels,thresholds, exception); return(status); } MagickExport MagickBooleanType RandomThresholdImageChannel(Image *image, const ChannelType channel,const char *thresholds,ExceptionInfo *exception) { #define ThresholdImageTag "Threshold/Image" CacheView *image_view; GeometryInfo geometry_info; MagickStatusType flags; MagickBooleanType status; MagickOffsetType progress; MagickPixelPacket threshold; MagickRealType min_threshold, max_threshold; RandomInfo **restrict random_info; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); if (thresholds == (const char *) NULL) return(MagickTrue); GetMagickPixelPacket(image,&threshold); min_threshold=0.0; max_threshold=(MagickRealType) QuantumRange; flags=ParseGeometry(thresholds,&geometry_info); min_threshold=geometry_info.rho; max_threshold=geometry_info.sigma; if ((flags & SigmaValue) == 0) max_threshold=min_threshold; if (strchr(thresholds,'%') != (char *) NULL) { max_threshold*=(MagickRealType) (0.01*QuantumRange); min_threshold*=(MagickRealType) (0.01*QuantumRange); } else if (((max_threshold == min_threshold) || (max_threshold == 1)) && (min_threshold <= 8)) { /* Backward Compatibility -- ordered-dither -- IM v 6.2.9-6. */ status=OrderedPosterizeImageChannel(image,channel,thresholds,exception); return(status); } /* Random threshold image. */ status=MagickTrue; progress=0; if (channel == CompositeChannels) { if (AcquireImageColormap(image,2) == MagickFalse) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); random_info=AcquireRandomInfoThreadSet(); image_view=AcquireCacheView(image); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,8) shared(progress,status) #endif for (y=0; y < (ssize_t) image->rows; y++) { const int id = GetOpenMPThreadId(); MagickBooleanType sync; register IndexPacket *restrict indexes; register ssize_t x; register PixelPacket *restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { IndexPacket index; MagickRealType intensity; intensity=(MagickRealType) PixelIntensityToQuantum(q); if (intensity < min_threshold) threshold.index=min_threshold; else if (intensity > max_threshold) threshold.index=max_threshold; else threshold.index=(MagickRealType)(QuantumRange* GetPseudoRandomValue(random_info[id])); index=(IndexPacket) (intensity <= threshold.index ? 0 : 1); SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); q++; } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_RandomThresholdImageChannel) #endif proceed=SetImageProgress(image,ThresholdImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); random_info=DestroyRandomInfoThreadSet(random_info); return(status); } if (SetImageStorageClass(image,DirectClass) == MagickFalse) { InheritException(exception,&image->exception); return(MagickFalse); } random_info=AcquireRandomInfoThreadSet(); image_view=AcquireCacheView(image); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,8) shared(progress,status) #endif for (y=0; y < (ssize_t) image->rows; y++) { const int id = GetOpenMPThreadId(); register IndexPacket *restrict indexes; register PixelPacket *restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { if ((channel & RedChannel) != 0) { if ((MagickRealType) GetPixelRed(q) < min_threshold) threshold.red=min_threshold; else if ((MagickRealType) GetPixelRed(q) > max_threshold) threshold.red=max_threshold; else threshold.red=(MagickRealType) (QuantumRange* GetPseudoRandomValue(random_info[id])); } if ((channel & GreenChannel) != 0) { if ((MagickRealType) GetPixelGreen(q) < min_threshold) threshold.green=min_threshold; else if ((MagickRealType) GetPixelGreen(q) > max_threshold) threshold.green=max_threshold; else threshold.green=(MagickRealType) (QuantumRange* GetPseudoRandomValue(random_info[id])); } if ((channel & BlueChannel) != 0) { if ((MagickRealType) GetPixelBlue(q) < min_threshold) threshold.blue=min_threshold; else if ((MagickRealType) GetPixelBlue(q) > max_threshold) threshold.blue=max_threshold; else threshold.blue=(MagickRealType) (QuantumRange* GetPseudoRandomValue(random_info[id])); } if ((channel & OpacityChannel) != 0) { if ((MagickRealType) GetPixelOpacity(q) < min_threshold) threshold.opacity=min_threshold; else if ((MagickRealType) GetPixelOpacity(q) > max_threshold) threshold.opacity=max_threshold; else threshold.opacity=(MagickRealType) (QuantumRange* GetPseudoRandomValue(random_info[id])); } if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) { if ((MagickRealType) GetPixelIndex(indexes+x) < min_threshold) threshold.index=min_threshold; else if ((MagickRealType) GetPixelIndex(indexes+x) > max_threshold) threshold.index=max_threshold; else threshold.index=(MagickRealType) (QuantumRange* GetPseudoRandomValue(random_info[id])); } if ((channel & RedChannel) != 0) SetPixelRed(q,(MagickRealType) GetPixelRed(q) <= threshold.red ? 0 : QuantumRange); if ((channel & GreenChannel) != 0) SetPixelGreen(q,(MagickRealType) GetPixelGreen(q) <= threshold.green ? 0 : QuantumRange); if ((channel & BlueChannel) != 0) SetPixelBlue(q,(MagickRealType) GetPixelBlue(q) <= threshold.blue ? 0 : QuantumRange); if ((channel & OpacityChannel) != 0) SetPixelOpacity(q,(MagickRealType) GetPixelOpacity(q) <= threshold.opacity ? 0 : QuantumRange); if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) SetPixelIndex(indexes+x,(MagickRealType) GetPixelIndex(indexes+x) <= threshold.index ? 0 : QuantumRange); q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_RandomThresholdImageChannel) #endif proceed=SetImageProgress(image,ThresholdImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); random_info=DestroyRandomInfoThreadSet(random_info); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W h i t e T h r e s h o l d I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WhiteThresholdImage() is like ThresholdImage() but forces all pixels above % the threshold into white while leaving all pixels at or below the threshold % unchanged. % % The format of the WhiteThresholdImage method is: % % MagickBooleanType WhiteThresholdImage(Image *image,const char *threshold) % MagickBooleanType WhiteThresholdImageChannel(Image *image, % const ChannelType channel,const char *threshold, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel or channels to be thresholded. % % o threshold: Define the threshold value. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType WhiteThresholdImage(Image *image, const char *threshold) { MagickBooleanType status; status=WhiteThresholdImageChannel(image,DefaultChannels,threshold, &image->exception); return(status); } MagickExport MagickBooleanType WhiteThresholdImageChannel(Image *image, const ChannelType channel,const char *thresholds,ExceptionInfo *exception) { #define ThresholdImageTag "Threshold/Image" CacheView *image_view; GeometryInfo geometry_info; MagickBooleanType status; MagickPixelPacket threshold; MagickOffsetType progress; MagickStatusType flags; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (thresholds == (const char *) NULL) return(MagickTrue); if (SetImageStorageClass(image,DirectClass) == MagickFalse) return(MagickFalse); flags=ParseGeometry(thresholds,&geometry_info); GetMagickPixelPacket(image,&threshold); threshold.red=geometry_info.rho; threshold.green=geometry_info.sigma; if ((flags & SigmaValue) == 0) threshold.green=threshold.red; threshold.blue=geometry_info.xi; if ((flags & XiValue) == 0) threshold.blue=threshold.red; threshold.opacity=geometry_info.psi; if ((flags & PsiValue) == 0) threshold.opacity=threshold.red; threshold.index=geometry_info.chi; if ((flags & ChiValue) == 0) threshold.index=threshold.red; if ((flags & PercentValue) != 0) { threshold.red*=(QuantumRange/100.0); threshold.green*=(QuantumRange/100.0); threshold.blue*=(QuantumRange/100.0); threshold.opacity*=(QuantumRange/100.0); threshold.index*=(QuantumRange/100.0); } /* White threshold image. */ status=MagickTrue; progress=0; image_view=AcquireCacheView(image); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,8) shared(progress,status) #endif for (y=0; y < (ssize_t) image->rows; y++) { register IndexPacket *restrict indexes; register ssize_t x; register PixelPacket *restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { if (channel == DefaultChannels) { if (PixelIntensity(q) > MagickPixelIntensity(&threshold)) { SetPixelRed(q,QuantumRange); SetPixelGreen(q,QuantumRange); SetPixelBlue(q,QuantumRange); if (image->colorspace == CMYKColorspace) SetPixelIndex(indexes+x,QuantumRange); } } else { if (((channel & RedChannel) != 0) && ((MagickRealType) GetPixelRed(q) > threshold.red)) SetPixelRed(q,QuantumRange); if (((channel & GreenChannel) != 0) && ((MagickRealType) GetPixelGreen(q) > threshold.green)) SetPixelGreen(q,QuantumRange); if (((channel & BlueChannel) != 0) && ((MagickRealType) GetPixelBlue(q) > threshold.blue)) SetPixelBlue(q,QuantumRange); if (((channel & OpacityChannel) != 0) && ((MagickRealType) GetPixelOpacity(q) > threshold.opacity)) SetPixelOpacity(q,QuantumRange); if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace) && ((MagickRealType) GetPixelIndex(indexes+x)) > threshold.index) SetPixelIndex(indexes+x,QuantumRange); } q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_WhiteThresholdImageChannel) #endif proceed=SetImageProgress(image,ThresholdImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); }
5115.c
/* * Compile using the command: * `cc 27Stencil.c -o oa -fopenmp -lm` */ #include <math.h> #include <omp.h> #include <stdint.h> #include <string.h> #include <stdio.h> #include <stdlib.h> #ifdef _OPENACC #include <openacc.h> #endif #define DEFAULT_DATASIZE 1048576 /* Default datasize. */ #define DEFAULT_REPS 10 /* Default repetitions. */ #define CONF95 1.96 #define ITERATIONS 10 #define FAC (1./26) #define TOLERANCE 1.0e-15 extern int reps; /* Repetitions. */ extern double *times; /* Array to store results in. */ extern int flag; /* Flag to set CPU or GPU invocation. */ extern unsigned int datasize; /* Datasize passed to benchmark functions. */ unsigned int datasize = -1; /* Datasize for tests in bytes. */ int reps = -1; /* Repetitions. */ double *times; /* Array of doubles storing the benchmark times in microseconds. */ double testtime; /* The average test time in microseconds for reps runs. */ double testsd; /* The standard deviation in the test time in microseconds for reps runs. */ int flag = 0; /* 0 indicates CPU. */ /* * Function prototypes for common functions. */ void init(int argc, char **argv); void finalisetest(char *); void finalise(void); void benchmark(char *, double (*test)(void)); void print_results(char *, double, double); /* Forward Declarations of utility functions*/ double max_diff(double *, double *, int); void wul(); void usage(char *argv[]) { printf("Usage: %s \n" "\t--reps <repetitions> (default %d)\n" "\t--datasize <datasize> (default %d bytes)\n", argv[0], DEFAULT_REPS, DEFAULT_DATASIZE); } /* * This function parses the parameters from the command line. */ void parse_args(int argc, char *argv[]) { int arg; for (arg = 1; arg < argc; arg++) { if (strcmp(argv[arg], "--reps") == 0) { reps = atoi(argv[++arg]); if (reps == 0) { printf("Invalid integer:--reps: %s\n", argv[arg]); usage(argv); exit(EXIT_FAILURE); } } else if (strcmp(argv[arg], "--datasize") == 0) { datasize = atoi(argv[++arg]); if (datasize == 0) { printf("Invalid integer:--datasize: %s\n", argv[arg]); usage(argv); exit(EXIT_FAILURE); } } else if (strcmp(argv[arg], "-h") == 0) { usage(argv); exit(EXIT_SUCCESS); } else { printf("Invalid parameters: %s\n", argv[arg]); usage(argv); exit(EXIT_FAILURE); } } } void stats(double *mtp, double *sdp) { double meantime, totaltime, sumsq, mintime, maxtime, sd; int i, good_reps; mintime = 1.0e10; maxtime = 0.; totaltime = 0.; good_reps = 0; for (i = 0; i < reps; i++) { /* Skip entries where times is 0, this indicates an error occured */ if (times[i] != 0){ mintime = (mintime < times[i]) ? mintime : times[i]; maxtime = (maxtime > times[i]) ? maxtime : times[i]; totaltime += times[i]; good_reps++; } } meantime = totaltime / good_reps; sumsq = 0; for (i = 0; i < reps; i++) { if (times[i] != 0){ sumsq += (times[i] - meantime) * (times[i] - meantime); } } sd = sqrt(sumsq / good_reps); *mtp = meantime; *sdp = sd; } /* * This function prints the results of the tests. * If you use a compiler which sets a different preprocessor flag * you may wish to add it here. */ void print_results(char *name, double testtime, double testsd) { char compiler[20]; /* Set default compiler idetifier. */ sprintf(compiler, "COMPILER"); /* Set compiler identifier based on known preprocessor flags. */ #ifdef __PGI sprintf(compiler, "PGI"); #endif #ifdef __HMPP sprintf(compiler, "CAPS"); #endif //printf("%s %s %d %f %f\n", compiler, name, datasize, testtime*1e6, CONF95*testsd*1e6); printf("%f\n", testtime*1e6); } /* * This function initialises the storage for the test results and set the defaults. */ void init(int argc, char **argv) { parse_args(argc, argv); if (reps == -1) { reps = DEFAULT_REPS; } if (datasize == (unsigned int)-1) { datasize = DEFAULT_DATASIZE; } times = (double *)malloc((reps) * sizeof(double)); /* #ifdef __PGI acc_init(acc_device_nvidia); // printf("PGI INIT\n"); #endif #ifdef __HMPP int a[5] = {1,2,3,4,5}; #pragma acc data copyin(a[0:5]) {} #endif #ifdef _CRAYC int a[5] = {1,2,3,4,5}; #pragma acc data copyin(a[0:5]) {} #endif */ } void finalise(void) { free(times); } /* * This function runs the benchmark specified. */ void benchmark(char *name, double (*test)(void)) { int i = 0; double tmp = 0; for (i=0; i<reps; i++) { tmp = test(); if (tmp == -10000){ printf("Memory allocation failure in %s\n", name); times[i] = 0; } else if (tmp == -11000){ printf("CPU/GPU mismatch in %s\n", name); times[i] = 0; } else{ times[i] = tmp; } } stats(&testtime, &testsd); //printf("in benchmark\n"); print_results(name, testtime, testsd); //printf("printed result\n"); } double stencil() { extern unsigned int datasize; int sz = cbrt((datasize/sizeof(double))/2); int i, j, k, iter; int n = sz-2; double fac = FAC; double t1, t2; double md; //printf("size = %d\n", sz); /* Work buffers, with halos */ double *a0 = (double*)malloc(sizeof(double)*sz*sz*sz); double *device_result = (double*)malloc(sizeof(double)*sz*sz*sz); double *a1 = (double*)malloc(sizeof(double)*sz*sz*sz); double *host_result = (double*)malloc(sizeof(double)*sz*sz*sz); double *a0_init = (double*)malloc(sizeof(double)*sz*sz*sz); if(a0==NULL||device_result==NULL||a1==NULL||host_result==NULL||a0_init==NULL){ /* Something went wrong in the memory allocation here, fail gracefully */ return(-10000); } /* initialize input array a0 */ /* zero all of array (including halos) */ //printf("size = %d\n", sz); for (i = 0; i < sz; i++) { for (j = 0; j < sz; j++) { for (k = 0; k < sz; k++) { a0[i*sz*sz+j*sz+k] = 0.0; //printf("%d\t", (i*sz*sz+j*sz+k)); } } } //printf("\n"); //int size_of_a0 = sizeof(a0) / sizeof(*a0); //printf("size of a0 = %d\n", size_of_a0); /* use random numbers to fill interior */ for (i = 1; i < n+1; i++) { for (j = 1; j < n+1; j++) { for (k = 1; k < n+1; k++) { a0[i*sz*sz+j*sz+k] = (double) rand()/ (double)(1.0 + RAND_MAX); } } } /* memcpy(&a0_init[0], &a0[0], sizeof(double)*sz*sz*sz); */ /* save initial input array for later GPU run */ for (i = 0; i < sz; i++) { for (j = 0; j < sz; j++) { for (k = 0; k < sz; k++) { a0_init[i*sz*sz+j*sz+k] = a0[i*sz*sz+j*sz+k]; } } } //printf("Host computation\n"); /* run main computation on host */ for (iter = 0; iter < ITERATIONS; iter++) { for (i = 1; i < n+1; i++) { for (j = 1; j < n+1; j++) { for (k = 1; k < n+1; k++) { a1[i*sz*sz+j*sz+k] = ( a0[i*sz*sz+(j-1)*sz+k] + a0[i*sz*sz+(j+1)*sz+k] + a0[(i-1)*sz*sz+j*sz+k] + a0[(i+1)*sz*sz+j*sz+k] + a0[(i-1)*sz*sz+(j-1)*sz+k] + a0[(i-1)*sz*sz+(j+1)*sz+k] + a0[(i+1)*sz*sz+(j-1)*sz+k] + a0[(i+1)*sz*sz+(j+1)*sz+k] + a0[i*sz*sz+(j-1)*sz+(k-1)] + a0[i*sz*sz+(j+1)*sz+(k-1)] + a0[(i-1)*sz*sz+j*sz+(k-1)] + a0[(i+1)*sz*sz+j*sz+(k-1)] + a0[(i-1)*sz*sz+(j-1)*sz+(k-1)] + a0[(i-1)*sz*sz+(j+1)*sz+(k-1)] + a0[(i+1)*sz*sz+(j-1)*sz+(k-1)] + a0[(i+1)*sz*sz+(j+1)*sz+(k-1)] + a0[i*sz*sz+(j-1)*sz+(k+1)] + a0[i*sz*sz+(j+1)*sz+(k+1)] + a0[(i-1)*sz*sz+j*sz+(k+1)] + a0[(i+1)*sz*sz+j*sz+(k+1)] + a0[(i-1)*sz*sz+(j-1)*sz+(k+1)] + a0[(i-1)*sz*sz+(j+1)*sz+(k+1)] + a0[(i+1)*sz*sz+(j-1)*sz+(k+1)] + a0[(i+1)*sz*sz+(j+1)*sz+(k+1)] + a0[i*sz*sz+j*sz+(k-1)] + a0[i*sz*sz+j*sz+(k+1)] ) * fac; } } } for (i = 1; i < n+1; i++) { for (j = 1; j < n+1; j++) { for (k = 1; k < n+1; k++) { a0[i*sz*sz+j*sz+k] = a1[i*sz*sz+j*sz+k]; } } } } /* end iteration loop */ /* save result */ /* memcpy(&host_result[0], &a0[0], sizeof(double)*sz*sz*sz); */ for (i = 0; i < sz; i++) { for (j = 0; j < sz; j++) { for (k = 0; k < sz; k++) { host_result[i*sz*sz+j*sz+k] = a0[i*sz*sz+j*sz+k]; // printf("%lf\t", a0[i*sz*sz+j*sz+k]); } } } //int size = sizeof(host_result)/sizeof(host_result[0]); //for(i = 0; i < size; i++) { // printf("%lf\t", host_result[i]); //} //printf("\n"); /* copy initial array back to a0 */ /* memcpy(&a0[0], &a0_init[0], sizeof(double)*sz*sz*sz); */ for (i = 0; i < sz; i++) { for (j = 0; j < sz; j++) { for (k = 0; k < sz; k++) { a0[i*sz*sz+j*sz+k] = a0_init[i*sz*sz+j*sz+k]; } } } //printf("Starting acc pragma code\n"); t1 = omp_get_wtime(); #pragma acc data copy(a0[0:sz*sz*sz]), create(a1[0:sz*sz*sz], i,j,k,iter), copyin(sz,fac,n) { for (iter = 0; iter < ITERATIONS; iter++) { #pragma omp target teams distribute for (i = 1; i < n+1; i++) { #LOOP2 for (j = 1; j < n+1; j++) { #LOOP3 for (k = 1; k < n+1; k++) { a1[i*sz*sz+j*sz+k] = ( a0[i*sz*sz+(j-1)*sz+k] + a0[i*sz*sz+(j+1)*sz+k] + a0[(i-1)*sz*sz+j*sz+k] + a0[(i+1)*sz*sz+j*sz+k] + a0[(i-1)*sz*sz+(j-1)*sz+k] + a0[(i-1)*sz*sz+(j+1)*sz+k] + a0[(i+1)*sz*sz+(j-1)*sz+k] + a0[(i+1)*sz*sz+(j+1)*sz+k] + a0[i*sz*sz+(j-1)*sz+(k-1)] + a0[i*sz*sz+(j+1)*sz+(k-1)] + a0[(i-1)*sz*sz+j*sz+(k-1)] + a0[(i+1)*sz*sz+j*sz+(k-1)] + a0[(i-1)*sz*sz+(j-1)*sz+(k-1)] + a0[(i-1)*sz*sz+(j+1)*sz+(k-1)] + a0[(i+1)*sz*sz+(j-1)*sz+(k-1)] + a0[(i+1)*sz*sz+(j+1)*sz+(k-1)] + a0[i*sz*sz+(j-1)*sz+(k+1)] + a0[i*sz*sz+(j+1)*sz+(k+1)] + a0[(i-1)*sz*sz+j*sz+(k+1)] + a0[(i+1)*sz*sz+j*sz+(k+1)] + a0[(i-1)*sz*sz+(j-1)*sz+(k+1)] + a0[(i-1)*sz*sz+(j+1)*sz+(k+1)] + a0[(i+1)*sz*sz+(j-1)*sz+(k+1)] + a0[(i+1)*sz*sz+(j+1)*sz+(k+1)] + a0[i*sz*sz+j*sz+(k-1)] + a0[i*sz*sz+j*sz+(k+1)] ) * fac; } } } #pragma acc parallel loop for (i = 1; i < n+1; i++) { #pragma acc loop for (j = 1; j < n+1; j++) { #pragma acc loop for (k = 1; k < n+1; k++) { a0[i*sz*sz+j*sz+k] = a1[i*sz*sz+j*sz+k]; } } } } /* end iteration loop */ } /* end data region */ #pragma acc wait t2 = omp_get_wtime(); memcpy(&device_result[0], &a0[0], sizeof(double)*sz*sz*sz); md = max_diff(&host_result[0],&device_result[0], sz); /* Free malloc'd memory to prevent leaks */ free(a0); free(a0_init); free(a1); free(host_result); free(device_result); //printf("md: %lf \t tolerance: %lf", md, TOLERANCE); if (md < TOLERANCE ){ //printf ("GPU matches host to within tolerance of %1.1e\n\n", TOLERANCE); return(t2 - t1); } else{ // printf ("WARNING: GPU does not match to within tolerance of %1.1e\nIt is %lf\n", TOLERANCE, md); return(-11000); } } /* Utility Functions */ double max_diff(double *array1,double *array2, int sz) { double tmpdiff, diff; int i,j,k; int n = sz-2; diff=0.0; for (i = 1; i < n+1; i++) { for (j = 1; j < n+1; j++) { for (k = 1; k < n+1; k++) { tmpdiff = fabs(array1[i*sz*sz+j*sz+k] - array2[i*sz*sz+j*sz+k]); //printf("diff: %lf", tmpdiff); if (tmpdiff > diff) diff = tmpdiff; } } } return diff; } /* * This function ensures the device is awake. * It is more portable than acc_init(). */ void wul(){ int data = 8192; double *arr_a = (double *)malloc(sizeof(double) * data); double *arr_b = (double *)malloc(sizeof(double) * data); int i = 0; if (arr_a==NULL||arr_b==NULL) { printf("Unable to allocate memory in wul.\n"); } for (i=0;i<data;i++){ arr_a[i] = (double) (rand()/(1.0+RAND_MAX)); } #pragma acc data copy(arr_b[0:data]), copyin(arr_a[0:data]) { #pragma acc parallel loop for (i=0;i<data;i++){ arr_b[i] = arr_a[i] * 2; } } if (arr_a[0] < 0){ printf("Error in WUL\n"); /* * This should never be called as rands should be in the range (0,1]. * This stops clever optimizers. */ } free(arr_a); free(arr_b); } int main(int argc, char **argv) { char testName[32]; //printf("compiler name datasize testtime*1e6 CONF95*testsd*1e6\n"); /* Initialise storage for test results & parse input arguements. */ init(argc, argv); /* Ensure device is awake. */ wul(); sprintf(testName, "27S"); benchmark(testName, &stencil); /* Print results & free results storage */ finalise(); return EXIT_SUCCESS; }
convolution.h
// // Created by agibsonccc on 3/9/16. // #ifndef NATIVEOPERATIONS_CONVOLUTION_H #define NATIVEOPERATIONS_CONVOLUTION_H #include <omp.h> template <typename T> class Im2col { private: T *img; T *out; int kernelWidth; int kernelHeight; int strideY; int strideX; int padHeight; int padWidth; int exampleFrom; int exampleTo; int depthFrom; int depthTo; int yOutFrom; int yOutTo; int xOutFrom; int xOutTo; bool coverAll; int opSize() { return (exampleTo - exampleFrom) * (depthTo - depthFrom) * (xOutTo - xOutFrom) * (yOutTo - yOutFrom) * kernelHeight * kernelWidth; } void exec() { T * dbIn = img; T * dbOut = out; int outArrayOffset = out.offset(); int * outShape = out.shape(); int * outStride = out.stride(); int inArrayOffset = img.offset(); int * inShape = img.shape(); int * inStride = img.stride(); int * outIndices = new int[6]; int * inIndices = new int[4]; int inStride2 = inStride[2]; int inStride3 = inStride[3]; int outStride2 = outStride[2]; int outStride3 = outStride[3]; int inShape2 = inShape[2]; int inShape3 = inShape[3]; boolean padding = padHeight > 0 || padWidth > 0; T dIn = dbIn; T dOut = dbOut; #pragma omp parallel for simd collapse(4) for (int ex = exampleFrom; ex < exampleTo; ex++) { for (int d = depthFrom; d < depthTo; d++) { inIndices[0] = ex; inIndices[1] = d; outIndices[0] = ex; outIndices[1] = d; for (int x = xOutFrom; x < xOutTo; x++) { //Along width for (int y = yOutFrom; y < yOutTo; y++) { //along height outIndices[4] = y; outIndices[5] = x; int baseOffsetOut = getOffsetUnsafe6(outArrayOffset, outShape, outStride, outIndices); if(padding) { int i = y * strideY - padHeight; //index along height of first element of patch in original img int j = x * strideX - padWidth; //index along width of first element in patch in original img inIndices[2] = i; //along height inIndices[3] = j; //along width int baseOffsetIn = getOffsetUnsafe4(inArrayOffset, inShape, inStride, inIndices); if (outStride2 <= outStride3) { //Want dimension 2 (along height) in inner loop for cache reasons for (int patchX = 0; patchX < kernelWidth; patchX++) { int outBufferIdxX = baseOffsetOut + patchX * outStride3; int inBufferIdxX = baseOffsetIn + patchX * inStride3; for (int patchY = 0; patchY < kernelHeight; patchY++) { if (i + patchY < 0 || j + patchX < 0 || i + patchY >= inShape2 || j + patchX >= inShape3) dOut[outBufferIdxX + patchY * outStride2] = 0; //padding else { dOut[outBufferIdxX + patchY * outStride2] = dIn[inBufferIdxX + patchY * inStride2]; } } } } else { //Want dimension 3 in inner loop for cache reasons for (int patchY = 0; patchY < kernelHeight; patchY++) { int outBufferIdxY = baseOffsetOut + patchY * outStride2; int inBufferIdxY = baseOffsetIn + patchY * inStride2; for (int patchX = 0; patchX < kernelWidth; patchX++) { if (i + patchY < 0 || j + patchX < 0 || i + patchY >= inShape[2] || j + patchX >= inShape[3]) dOut[outBufferIdxY + patchX * outStride3] = 0f; //padding else { dOut[outBufferIdxY + patchX * outStride3] = dIn[inBufferIdxY + patchX * inStride3]; } } } } } else { //No padding int i = y * strideY; //index along height of first element of patch in original img int j = x * strideX; //index along width of first element in patch in original img inIndices[2] = i; //along height inIndices[3] = j; //along width int baseOffsetIn = getOffsetUnsafe4(inArrayOffset, inShape, inStride, inIndices); if (outStride2 <= outStride3) { //Want dimension 2 (along height) in inner loop for cache reasons for (int patchX = 0; patchX < kernelWidth; patchX++) { int outBufferIdxX = baseOffsetOut + patchX * outStride3; int inBufferIdxX = baseOffsetIn + patchX * inStride3; for (int patchY = 0; patchY < kernelHeight; patchY++) { dOut[outBufferIdxX + patchY * outStride2] = dIn[inBufferIdxX + patchY * inStride2]; } } } else { //Want dimension 3 in inner loop for cache reasons for (int patchY = 0; patchY < kernelHeight; patchY++) { int outBufferIdxY = baseOffsetOut + patchY * outStride2; int inBufferIdxY = baseOffsetIn + patchY * inStride2; for (int patchX = 0; patchX < kernelWidth; patchX++) { dOut[outBufferIdxY + patchX*outStride3] = dIn[inBufferIdxY + patchX*inStride3]; } } } } } } } } } /** * A version of Shape.getOffset without checking on input for negative indices etc * normally negative indices are bad, OK here because of other checks on input indices * Uses unrolled loop specifically for length 6, where indices[2] and indices[3] are zero (always are here) */ int getOffsetUnsafe6(int baseOffset, int* shape, int* stride, int* indices) { int offset = baseOffset; if(shape[0] != 1) offset += indices[0] * stride[0]; if(shape[1] != 1) offset += indices[1] * stride[1]; if(shape[4] != 1) offset += indices[4] * stride[4]; if(shape[5] != 1) offset += indices[5] * stride[5]; return offset; } }; template <typename T> class Col2Im { private: T *col; T *imgOut; int kernelHeight; int kernelWidth; int strideY; int strideX; int padHeight; int padWidth; int imgHeight; int imgWidth; int parallelThreshold; int exampleFrom; int exampleTo; int depthFrom; int depthTo; void exec() { T * dbCol = col; T * dbOut = imgOut; int outArrayOffset = 0; int* outShape = imgOut.shape(); int* outStride = imgOut.stride(); int inOffset = 0; int* inShape = col.shape(); int* inStride = col.stride(); int* outIndices = new int[4]; int* inIndices = new int[6]; int inStride2 = inStride[2]; int inStride3 = inStride[3]; int outStride2 = outStride[2]; int outStride3 = outStride[3]; int outShape2 = outShape[2]; int outShape3 = outShape[3]; int yOutTo = inShape[4]; int xOutTo = inShape[5]; boolean padding = padHeight > 0 || padWidth > 0; T * fIn = dbCol; T * fOut = dbOut; #pragma omp parallel for for (int ex = exampleFrom; ex < exampleTo; ex++) { for (int d = depthFrom; d < depthTo; d++) { inIndices[0] = ex; inIndices[1] = d; outIndices[0] = ex; outIndices[1] = d; for (int x = 0; x < xOutTo; x++) { //Patch number along width for (int y = 0; y < yOutTo; y++) { //Patch number along height inIndices[4] = y; //patch number (along height) inIndices[5] = x; //patch number (along width) int baseOffsetIn = getOffsetUnsafe6(inOffset, inShape, inStride, inIndices); if(padding){ int i = y * strideY - padHeight; //index along height of first element of patch in original img int j = x * strideX - padWidth; //index along width of first element in patch in original img outIndices[2] = i; //along height outIndices[3] = j; //along width int baseOffsetOut = getOffsetUnsafe4(outArrayOffset, outShape, outStride, outIndices); if (inStride2 <= inStride3) { //Want dimension 2 (along height) in inner loop for cache efficiency for (int patchX = 0; patchX < kernelWidth; patchX++) { if( j + patchX < 0 || j + patchX >= outShape3 ) continue; for (int patchY = 0; patchY < kernelHeight; patchY++) { if (i + patchY < 0 || i + patchY >= outShape2 ) continue; fOut[baseOffsetOut + patchY * outStride2 + patchX * outStride3] += fIn[baseOffsetIn + patchY * inStride2 + patchX * inStride3]; } } } else { //Want dimension 3 (along width) in inner loop for cache efficiency for (int patchY = 0; patchY < kernelHeight; patchY++) { if(i + patchY < 0 || i + patchY >= outShape2) continue; for (int patchX = 0; patchX < kernelWidth; patchX++) { if (j + patchX < 0 || j + patchX >= outShape3) continue; fOut[baseOffsetOut + patchY * outStride2 + patchX * outStride3] += fIn[baseOffsetIn + patchY * inStride2 + patchX * inStride3]; } } } } else { //No padding int i = y * strideY; //index along height of first element of patch in output img int j = x * strideX; //index along width of first element in patch in output img outIndices[2] = i; outIndices[3] = j; int baseOffsetOut = getOffsetUnsafe4(outArrayOffset, outShape, outStride, outIndices); if (inStride2 <= inStride3) { //Want dimension 2 (along height) in inner loop for cache efficiency for (int patchX = 0; patchX < kernelWidth; patchX++) { for (int patchY = 0; patchY < kernelHeight; patchY++) { fOut[baseOffsetOut + patchY * outStride2 + patchX * outStride3] += fIn[baseOffsetIn + patchY * inStride2 + patchX * inStride3]; } } } else { //Want dimension 3 (along width) in inner loop for cache efficiency for (int patchY = 0; patchY < kernelHeight; patchY++) { for (int patchX = 0; patchX < kernelWidth; patchX++) { fOut[baseOffsetOut + patchY * outStride2 + patchX * outStride3] += fIn[baseOffsetIn + patchY * inStride2 + patchX * inStride3]; } } } } } } } } } /** Calculate buffer offset (like Shape.getOffset) without checking on input for negative indices etc * normally negative indices are bad, OK here because of other checks on input indices * Uses unrolled loop specifically for length 4 */ getOffsetUnsafe4(int baseOffset, int* shape, int* stride, int* indices) { int offset = baseOffset; if(shape[0] != 1) offset += indices[0] * stride[0]; if(shape[1] != 1) offset += indices[1] * stride[1]; if(shape[2] != 1) offset += indices[2] * stride[2]; if(shape[3] != 1) offset += indices[3] * stride[3]; return offset; } /** A version of Shape.getOffset without checking on input for negative indices etc * normally negative indices are bad, OK here because of other checks on input indices * Uses unrolled loop specifically for length 6, where indices[2] and indices[3] are zero (always are here) */ int getOffsetUnsafe6(int baseOffset, int* shape, int* stride, int* indices) { int offset = baseOffset; if(shape[0] != 1) offset += indices[0] * stride[0]; if(shape[1] != 1) offset += indices[1] * stride[1]; if(shape[4] != 1) offset += indices[4] * stride[4]; if(shape[5] != 1) offset += indices[5] * stride[5]; return offset; } }; #endif //NATIVEOPERATIONS_CONVOLUTION_H
index.c
#include <stdio.h> #include <stdlib.h> #include <omp.h> typedef unsigned int uint; #define LIMIT 500 #define XCHG(i, j) {uint t = i; i = j; j = t;} static void imerge_(uint * b, uint * l1, uint * h1, uint * l2, uint * h2, uint * l_) { for(;(l1 != h1) && (l2 != h2);) { if(*(b + *(l2)) < *(b + *(l1))) memcpy(l_++, l2++, sizeof(uint)); else memcpy(l_++, l1++, sizeof(uint)); } memcpy(l_, l1, (h1 - l1) * sizeof(uint)); memcpy(l_, l2, (h2 - l2) * sizeof(uint)); } static void isort_(uint * b, uint * l, uint * h) { uint * i; for(i = l; i < h; i++) { uint * elm = b + *(i); uint * j; for(j = (i+1); j < h; j++) { if(*(elm) > *(b + *(j))) { XCHG(*(i), *(j)); elm = b + *(i); } } } } static void isort(uint * b, uint * l, uint * h, uint * l_, uint is_in_place) { if((h - l) <= LIMIT) { isort_(b, l, h); if(!is_in_place) memcpy(l_, l, (h - l) * sizeof(uint)); } else { uint* m = l + (h - l) / 2; uint* m_ = l_ + (m - l); uint* h_ = l_ + (h - l); #pragma omp task isort(b, l, m, l_, !is_in_place); isort(b, m, h, m_, !is_in_place); #pragma omp taskwait if(is_in_place) imerge_(b, l_, m_, m_, h_, l); else imerge_(b, l, m, m, h, l_); } } uint imain(uint sz, uint * b, uint * l) { uint i; for(i = 0; i < sz; i++) l[i] = i; uint * l_ = (uint *) _mm_malloc(sz * sizeof(uint), 64); #pragma omp parallel { #pragma omp single { isort(b, l, (l + sz), l_, 1); } } _mm_free(l_); return 1; }
darts-hybrid.c
/* Compute pi using hybrid MPI/OpenMP */ #include "lcgenerator.h" #include <mpi.h> #include <omp.h> #include <stdio.h> 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 < my_trials; i++) { #pragma omp critical (randoms) { 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 \t Computing pi using hybrid MPI/OpenMP: \n"); printf("\t For %ld trials, pi = %f\n", num_trials, pi); printf("\n"); } MPI_Finalize(); return 0; }
core_zgemm.c
/** * * @file * * PLASMA is a software package provided by: * University of Tennessee, US, * University of Manchester, UK. * * @precisions normal z -> c d s * **/ #include "core_blas.h" #include "plasma_types.h" #include "core_lapack.h" /***************************************************************************//** * * @ingroup core_gemm * * Performs one of the matrix-matrix operations * * \f[ C = \alpha [op( A )\times op( B )] + \beta C, \f] * * where op( X ) is one of: * \f[ op( X ) = X, \f] * \f[ op( X ) = X^T, \f] * \f[ op( X ) = X^H, \f] * * alpha and beta are scalars, and A, B and C are matrices, with op( A ) * an m-by-k matrix, op( B ) a k-by-n matrix and C an m-by-n matrix. * ******************************************************************************* * * @param[in] transa * - PlasmaNoTrans: A is not transposed, * - PlasmaTrans: A is transposed, * - PlasmaConjTrans: A is conjugate transposed. * * @param[in] transb * - PlasmaNoTrans: B is not transposed, * - PlasmaTrans: B is transposed, * - PlasmaConjTrans: B is conjugate transposed. * * @param[in] m * The number of rows of the matrix op( A ) and of the matrix C. * m >= 0. * * @param[in] n * The number of columns of the matrix op( B ) and of the matrix C. * n >= 0. * * @param[in] k * The number of columns of the matrix op( A ) and the number of rows * of the matrix op( B ). k >= 0. * * @param[in] alpha * The scalar alpha. * * @param[in] A * An lda-by-ka matrix, where ka is k when transa = PlasmaNoTrans, * and is m otherwise. * * @param[in] lda * The leading dimension of the array A. * When transa = PlasmaNoTrans, lda >= max(1,m), * otherwise, lda >= max(1,k). * * @param[in] B * An ldb-by-kb matrix, where kb is n when transb = PlasmaNoTrans, * and is k otherwise. * * @param[in] ldb * The leading dimension of the array B. * When transb = PlasmaNoTrans, ldb >= max(1,k), * otherwise, ldb >= max(1,n). * * @param[in] beta * The scalar beta. * * @param[in,out] C * An ldc-by-n matrix. On exit, the array is overwritten by the m-by-n * matrix ( alpha*op( A )*op( B ) + beta*C ). * * @param[in] ldc * The leading dimension of the array C. ldc >= max(1,m). * ******************************************************************************/ void core_zgemm(plasma_enum_t transa, plasma_enum_t transb, int m, int n, int k, plasma_complex64_t alpha, const plasma_complex64_t *A, int lda, const plasma_complex64_t *B, int ldb, plasma_complex64_t beta, plasma_complex64_t *C, int ldc) { cblas_zgemm(CblasColMajor, (CBLAS_TRANSPOSE)transa, (CBLAS_TRANSPOSE)transb, m, n, k, CBLAS_SADDR(alpha), A, lda, B, ldb, CBLAS_SADDR(beta), C, ldc); } /******************************************************************************/ void core_omp_zgemm( plasma_enum_t transa, plasma_enum_t transb, int m, int n, int k, plasma_complex64_t alpha, const plasma_complex64_t *A, int lda, const plasma_complex64_t *B, int ldb, plasma_complex64_t beta, plasma_complex64_t *C, int ldc, plasma_sequence_t *sequence, plasma_request_t *request) { int ak; if (transa == PlasmaNoTrans) ak = k; else ak = m; int bk; if (transb == PlasmaNoTrans) bk = n; else bk = k; #pragma omp task depend(in:A[0:lda*ak]) \ depend(in:B[0:ldb*bk]) \ depend(inout:C[0:ldc*n]) { if (sequence->status == PlasmaSuccess) core_zgemm(transa, transb, m, n, k, alpha, A, lda, B, ldb, beta, C, ldc); } }
Example_declare_target.4.c
/* * @@name: declare_target.4c * @@type: C * @@compilable: yes * @@linkable: no * @@expect: success * @@version: omp_4.0 */ #define N 10000 #pragma omp declare target float Q[N][N]; float Pfun(const int i, const int k) { return Q[i][k] * Q[k][i]; } #pragma omp end declare target float accum(int k) { float tmp = 0.0; #pragma omp target update to(Q) #pragma omp target map(tofrom: tmp) #pragma omp parallel for reduction(+:tmp) for(int i=0; i < N; i++) tmp += Pfun(i,k); return tmp; } /* Note: The variable tmp is now mapped with tofrom, for correct execution with 4.5 (and pre-4.5) compliant compilers. See Devices Intro. */
ktensor.c
/* This file is part of ParTI!. ParTI! 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 3 of the License, or (at your option) any later version. ParTI! 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 Lesser General Public License along with ParTI!. If not, see <http://www.gnu.org/licenses/>. */ #include <ParTI.h> #include <stdlib.h> #include <string.h> #include "../error/error.h" /** * Assign a new Kruskal tensor. * * @param[out] ktsr Kruskal tensor * @param[in] nmodes the number of dimensions/modes/tensor order * @param[in] ndims the mode sizes * @param[in] rank tensor rank or the number of columns of factor matrices * */ int sptNewKruskalTensor(sptKruskalTensor *ktsr, sptIndex nmodes, const sptIndex ndims[], sptIndex rank) { ktsr->nmodes = nmodes; ktsr->rank = rank; ktsr->ndims = (sptIndex*)malloc(nmodes*sizeof(sptIndex)); for(sptIndex i=0; i<nmodes; ++i) ktsr->ndims[i] = ndims[i]; ktsr->lambda = (sptValue*)malloc(rank*sizeof(sptValue)); ktsr->fit = 0.0; return 0; } /** * Shuffle factor matrices row indices. * * @param[out] map_inds is the renumbering mapping * @param[in] ktsr Kruskal tensor to be shuffled * */ void sptKruskalTensorInverseShuffleIndices(sptKruskalTensor * ktsr, sptIndex ** map_inds) { /* Renumber factor matrices rows */ sptIndex new_i; for(sptIndex m=0; m < ktsr->nmodes; ++m) { sptMatrix * mtx = ktsr->factors[m]; sptIndex * mode_map_inds = map_inds[m]; sptValue * tmp_values = malloc(mtx->cap * mtx->stride * sizeof (sptValue)); for(sptIndex i=0; i<mtx->nrows; ++i) { new_i = mode_map_inds[i]; for(sptIndex j=0; j<mtx->ncols; ++j) { tmp_values[i * mtx->stride + j] = mtx->values[new_i * mtx->stride + j]; } } free(mtx->values); mtx->values = tmp_values; } } /** * Free a new Kruskal tensor. * * @param[in] ktsr Kruskal tensor * */ void sptFreeKruskalTensor(sptKruskalTensor *ktsr) { ktsr->rank = 0; ktsr->fit = 0.0; free(ktsr->ndims); free(ktsr->lambda); for(sptIndex i=0; i<ktsr->nmodes; ++i) sptFreeMatrix(ktsr->factors[i]); free(ktsr->factors); ktsr->nmodes = 0; } /** * Compute the fit of a Kruskal tensor to a sparse tensor. * * @param[in] spten a COO sparse tensor. * @param[in] lambda the weight array * @param[in] mats factor matrices * @param[in] ata the results of ATA, A is a factor matrix * @return fit a double-precision float-point value * */ double sptKruskalTensorFit( sptSparseTensor const * const spten, sptValue const * const __restrict lambda, sptMatrix ** mats, sptMatrix ** ata) { sptIndex const nmodes = spten->nmodes; double spten_normsq = SparseTensorFrobeniusNormSquared(spten); double const norm_mats = sptKruskalTensorFrobeniusNormSquared(nmodes, lambda, ata); double const inner = sptSparseKruskalTensorInnerProduct(nmodes, lambda, mats); double residual = spten_normsq + norm_mats - 2 * inner; if (residual > 0.0) { residual = sqrt(residual); } double fit = 1 - (residual / sqrt(spten_normsq)); return fit; } // Column-major. /* Compute a Kruskal tensor's norm is compute on "ata"s. Check Tammy's sparse */ double sptKruskalTensorFrobeniusNormSquared( sptIndex const nmodes, sptValue const * const __restrict lambda, sptMatrix ** ata) // ata: column-major { sptIndex const rank = ata[0]->ncols; sptIndex const stride = ata[0]->stride; sptValue * const __restrict tmp_atavals = ata[nmodes]->values; // Column-major double norm_mats = 0; #ifdef PARTI_USE_OPENMP #pragma omp parallel for #endif for(sptIndex x=0; x < rank*stride; ++x) { tmp_atavals[x] = 1.; } /* Compute Hadamard product for all "ata"s */ for(sptIndex m=0; m < nmodes; ++m) { sptValue const * const __restrict atavals = ata[m]->values; #ifdef PARTI_USE_OPENMP #pragma omp parallel for #endif for(sptIndex i=0; i < rank; ++i) { for(sptIndex j=i; j < rank; ++j) { tmp_atavals[j * stride + i] *= atavals[j * stride + i]; } } } /* compute lambda^T * aTa[MAX_NMODES] * lambda, only compute a half of them because of its symmetric */ #ifdef PARTI_USE_OPENMP #pragma omp parallel for reduction(+:norm_mats) #endif for(sptIndex i=0; i < rank; ++i) { norm_mats += tmp_atavals[i+(i*stride)] * lambda[i] * lambda[i]; for(sptIndex j=i+1; j < rank; ++j) { norm_mats += tmp_atavals[i+(j*stride)] * lambda[i] * lambda[j] * 2; } } return fabs(norm_mats); } // Row-major, compute via MTTKRP result (mats[nmodes]) and mats[nmodes-1]. double sptSparseKruskalTensorInnerProduct( sptIndex const nmodes, sptValue const * const __restrict lambda, sptMatrix ** mats) { sptIndex const rank = mats[0]->ncols; sptIndex const stride = mats[0]->stride; sptIndex const last_mode = nmodes - 1; sptIndex const I = mats[last_mode]->nrows; sptValue const * const last_vals = mats[last_mode]->values; sptValue const * const tmp_vals = mats[nmodes]->values; sptValue * buffer_accum; double inner = 0; double * const __restrict accum = (double *) malloc(rank*sizeof(*accum)); #ifdef PARTI_USE_OPENMP #pragma omp parallel for #endif for(sptIndex r=0; r < rank; ++r) { accum[r] = 0.0; } #ifdef PARTI_USE_OPENMP #pragma omp parallel { int const nthreads = omp_get_num_threads(); #pragma omp master { buffer_accum = (sptValue *)malloc(nthreads * rank * sizeof(sptValue)); for(sptIndex j=0; j < nthreads * rank; ++j) buffer_accum[j] = 0.0; } } #endif #ifdef PARTI_USE_OPENMP #pragma omp parallel { int const tid = omp_get_thread_num(); int const nthreads = omp_get_num_threads(); sptValue * loc_accum = buffer_accum + tid * rank; #pragma omp for for(sptIndex i=0; i < I; ++i) { for(sptIndex r=0; r < rank; ++r) { loc_accum[r] += last_vals[r+(i*stride)] * tmp_vals[r+(i*stride)]; } } #pragma omp for for(sptIndex j=0; j < rank; ++j) { for(int i=0; i < nthreads; ++i) { accum[j] += buffer_accum[i*rank + j]; } } } #else for(sptIndex i=0; i < I; ++i) { for(sptIndex r=0; r < rank; ++r) { accum[r] += last_vals[r+(i*stride)] * tmp_vals[r+(i*stride)]; } } #endif #ifdef PARTI_USE_OPENMP #pragma omp parallel for reduction(+:inner) #endif for(sptIndex r=0; r < rank; ++r) { inner += accum[r] * lambda[r]; } #ifdef PARTI_USE_OPENMP free(buffer_accum); #endif free(accum); return inner; }
ast-dump-openmp-master.c
// RUN: %clang_cc1 -triple x86_64-unknown-unknown -fopenmp -ast-dump %s | FileCheck --match-full-lines -implicit-check-not=openmp_structured_block %s void test() { #pragma omp master ; } // CHECK: TranslationUnitDecl {{.*}} <<invalid sloc>> <invalid sloc> // CHECK: `-FunctionDecl {{.*}} <{{.*}}ast-dump-openmp-master.c:3:1, line:6:1> line:3:6 test 'void ()' // CHECK-NEXT: `-CompoundStmt {{.*}} <col:13, line:6:1> // CHECK-NEXT: `-OMPMasterDirective {{.*}} <line:4:1, col:19> // CHECK-NEXT: `-CapturedStmt {{.*}} <line:5:3> // CHECK-NEXT: `-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> // CHECK-NEXT: |-NullStmt {{.*}} <col:3> openmp_structured_block // CHECK-NEXT: `-ImplicitParamDecl {{.*}} <line:4:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-master.c:4:1) *const restrict'
observables.h
/*************************************************************************** * Copyright (C) 2009-2013 by Florian Goth * * fgoth@wthp095 * * * * 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 <ORGANIZATION> nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ***************************************************************************/ #ifndef OBSERVABLES_H #define OBSERVABLES_H #include "AverageSign.h" #include "ObservableBase.h" #include "ObservableContainer.h" #include "Parameters.h" #include "Greensfunction.h" #include "libFourier.h" #include <valarray> #ifdef _OPENMP #include <omp.h> #endif #define TWOPI 2.0*M_PIl template <class C, class S, class Communication> struct Observable_Parameters { typedef C Configuration; typedef S SignType; typedef Communication Comm; }; template <class Configuration> void densitydensityCorrelation_dry(DryRun<typename Configuration::value_type, typename Configuration::DetType>& func, int site_i, const typename DryRun<typename Configuration::value_type, typename Configuration::DetType>::FPType s_i, int spin_i, int site_j, const typename DryRun<typename Configuration::value_type, typename Configuration::DetType>::FPType s_j, int spin_j) { const typename DryRun<typename Configuration::value_type, typename Configuration::DetType>::FPType tiny = 0.00000001; if (spin_i == UP) { if (spin_j == DOWN) { //UP-DOWN func.template onSector<UP>(site_i, s_i, site_i, s_i); func.template onSector<DOWN>(site_j, s_j, site_j, s_j); } else { //UP-UP if ((site_i != site_j) || !fpequal(s_i, s_j)) { func.template onSector<UP>(site_i, s_i, site_i, s_i); func.template onSector<UP>(site_j, s_j, site_j, s_j); func.template onSector<UP>(site_j, s_j, site_i, s_i); func.template onSector<UP>(site_i, s_i, site_j, s_j); } else { func.template onSector<UP>(site_i, s_i, site_i, s_i); } } } else { if (spin_j == DOWN) { if ((site_i != site_j) || !fpequal(s_i, s_j)) { //DOWN-DOWN func.template onSector<DOWN>(site_i, s_i, site_i, s_i); func.template onSector<DOWN>(site_j, s_j, site_j, s_j); func.template onSector<DOWN>(site_j, s_j, site_i, s_i); func.template onSector<DOWN>(site_i, s_i, site_j, s_j); } else { func.template onSector<DOWN>(site_i, s_i, site_i, s_i); } } else { //DOWN - UP func.template onSector<DOWN>(site_i, s_i, site_i, s_i); func.template onSector<UP>(site_j, s_j, site_j, s_j); } } return; } template <class Configuration> inline typename Configuration::DetType densitydensityCorrelation(const DoWick<typename Configuration::value_type, typename Configuration::DetType>& dowick, int site_i, typename DoWick<typename Configuration::value_type, typename Configuration::DetType>::FPType s_i, int spin_i, int site_j, typename DoWick<typename Configuration::value_type, typename Configuration::DetType>::FPType s_j, int spin_j) { typename Configuration::DetType retval; const typename DoWick<typename Configuration::value_type, typename Configuration::DetType>::FPType tiny = 0.00000001; if (spin_i == UP) { if (spin_j == DOWN) { //UP-DOWN retval = dowick.template onSector<UP>(site_i, s_i, site_i, s_i) * dowick.template onSector<DOWN>(site_j, s_j, site_j, s_j); } else { //UP-UP if ((site_i != site_j) || !fpequal(s_i, s_j)) { retval = (dowick.template onSector<UP>(site_i, s_i, site_i, s_i) * dowick.template onSector<UP>(site_j, s_j, site_j, s_j) - dowick.template onSector<UP>(site_j, s_j, site_i, s_i) * dowick.template onSector<UP>(site_i, s_i, site_j, s_j)); } else {//special care for equaltime greensfunction retval = dowick.template onSector<UP>(site_i, s_i, site_i, s_i); } } } else { if (spin_j == DOWN) { if ((site_i != site_j) || !fpequal(s_i, s_j)) { //DOWN-DOWN retval = (dowick.template onSector<DOWN>(site_i, s_i, site_i, s_i) * dowick.template onSector<DOWN>(site_j, s_j, site_j, s_j) - dowick.template onSector<DOWN>(site_j, s_j, site_i, s_i) * dowick.template onSector<DOWN>(site_i, s_i, site_j, s_j) ); } else {//special care for equaltime greensfunction retval = dowick.template onSector<DOWN>(site_i, s_i, site_i, s_i); } } else { //DOWN - UP retval = dowick.template onSector<DOWN>(site_i, s_i, site_i, s_i) * dowick.template onSector<UP>(site_j, s_j, site_j, s_j); } } return retval; } /** A "generic" twoparticle Greensfunction of this form: G = <c^dagger_a c_b c^dagger_c c_d > */ template <class Configuration> void genericTwoParticleGreensfunction_dry(DryRun<typename Configuration::value_type, typename Configuration::DetType>& func, const typename Configuration::value_type& va, const typename Configuration::value_type& vb, const typename Configuration::value_type& vc, const typename Configuration::value_type& vd) { if((vb == vc) && (va == vb) && (vc == vd)) func(va, va); else { func(va, vb); func(va, vd); func(vc, vb); func(vc, vd); } return; } /** A "generic" twoparticle Greensfunction: It is like that: G = <c^dagger_a c_b c^dagger_c c_d > */ template <class Configuration> typename Configuration::DetType genericTwoParticleGreensfunction(const DoWick<typename Configuration::value_type, typename Configuration::DetType>& dowick, typename Configuration::value_type va, typename Configuration::value_type vb, typename Configuration::value_type vc, typename Configuration::value_type vd) { typename Configuration::DetType retval; if((vb == vc) && (va == vb) && (vc == vd)) { retval = dowick(va, va); } else { retval = dowick(va, vb) * dowick(vc, vd) - dowick(va, vd) * dowick(vc, vb); } return retval; } /** A class for measuring the average Order. */ template <class Config> class AverageOrder : public Network_Cache<Config, typename Config::SignType> { public: typedef typename Config::Configuration Configuration; typedef typename Config::Configuration::FPType FPType; typedef typename Config::SignType SignType; typedef typename Config::SignType ObservableType;///< the AverageOrder is essentially a floating Point type, but during calculations it can be complex /** The Constructor for the Average Order */ AverageOrder(typename Config::Comm& n) throw() : Network_Cache<Config, typename Config::SignType>(n, "AverageOrder"), averageorder(0.0), configurationLength(0.0) { } inline void dryrun(DryRun<typename Configuration::value_type, SignType>&) {} /** This determines the Average Order for the given configuration @param configuration the configuration */ inline void evaluate(const Configuration&, const DoWick<typename Configuration::value_type, SignType>&); private: SignType averageorder;///< here we store the physical AverageOrder FPType configurationLength;///< this is the real Average Order of the Data Structure }; template <class Config> void AverageOrder<Config>::evaluate(const Configuration& configuration, const DoWick<typename Configuration::value_type, SignType>&) { FPType currentorder = static_cast<FPType>(configuration.size()); //now update the average order configurationLength += currentorder; SignType obs = currentorder * configuration.phase;//as for every other observable, account for the sign of the Configuration averageorder += obs; this->add_bin(obs); return; } /** A class for measuring the ParticleNumber at a certain hardcoded time */ template <class Config> class ParticleNumber : public Network_Cache<Config, typename Config::SignType> { public: typedef typename Config::Configuration Configuration; typedef typename Configuration::FPType FPType; typedef typename Config::SignType SignType; typedef SignType ObservableType;///< the ParticleNumber is essentially a floating point type, but during calculations it can be complex /** The Constructor for the Average Order */ ParticleNumber(typename Config::Comm& n, const Parameters& params) throw() : Network_Cache<Config, typename Config::SignType>(n, "ParticleNumber"), t_M(params.t_exp), len(params.N) { } void dryrun(DryRun<typename Configuration::value_type, SignType>&); /** This determines the Average Order for the given Configuration @param configuration the configuration */ inline void evaluate(const Configuration&, const DoWick<typename Configuration::value_type, SignType>&); private: const double& t_M; const uint32_t& len; }; template <class Config> void ParticleNumber<Config>::evaluate(const Configuration& configuration, const DoWick<typename Configuration::value_type, SignType>& func) { ObservableType obs(func.template onSector<UP>(0, t_M, 0, t_M)); obs += func.template onSector<DOWN>(0, t_M, 0, t_M); for (unsigned int k = 1; k < len; ++k) { obs += func.template onSector<UP>(k, t_M, k, t_M); obs += func.template onSector<DOWN>(k, t_M, k, t_M); } obs *= configuration.phase; this->add_bin(obs); return; } template <class Config> void ParticleNumber<Config>::dryrun(DryRun<typename Configuration::value_type, SignType>& func) { typedef typename Configuration::value_type Vertex; for (unsigned int k = 0; k < len; ++k) { func.template onSector<UP>(k, t_M, k, t_M); func.template onSector<DOWN>(k, t_M, k, t_M); } } /** A class for measuring the Total Double Occupancy at a certain hardcoded time */ template <class Config> class TotalDoubleOccupancy : public Network_Cache<Config, typename Config::SignType> { public: typedef typename Config::Configuration Configuration; typedef typename Configuration::FPType FPType; typedef typename Config::SignType GFRetVal; typedef GFRetVal ObservableType;///< the ParticleNumber is essentially a floating Point type, but during calculations it can be complex /** The Constructor for the Average Order */ TotalDoubleOccupancy(typename Config::Comm& n, const Parameters& params) throw() : Network_Cache<Config, typename Config::SignType>(n, "TotalDoubleOccupancy"), t_M(params.t_exp), len(params.N) { } void dryrun(DryRun<typename Configuration::value_type, GFRetVal>&); /** This determines the Average Order for the given Configuration @param configuration the configuration */ inline void evaluate(const Configuration&, const DoWick<typename Configuration::value_type, GFRetVal>&); private: const double& t_M; const uint32_t& len; }; template <class Config> void TotalDoubleOccupancy<Config>::dryrun(DryRun<typename Configuration::value_type, GFRetVal>& func) { typedef typename Configuration::value_type Vertex; Vertex v0u(0, 0, UP); Vertex v0d(0, 0, DOWN); genericTwoParticleGreensfunction_dry<Configuration>(func, v0u, v0u, v0d, v0d); for (unsigned int k = 1; k < len; ++k) { Vertex vu(k, 0, UP); Vertex vd(k, 0, DOWN); genericTwoParticleGreensfunction_dry<Configuration>(func, vu, vu, vd, vd); } } template <class Config> void TotalDoubleOccupancy<Config>::evaluate(const Configuration& configuration, const DoWick<typename Configuration::value_type, GFRetVal>& func) { typename Configuration::value_type v0u(0, 0, UP); typename Configuration::value_type v0d(0, 0, DOWN); ObservableType obs(genericTwoParticleGreensfunction<Configuration>(func, v0u, v0u, v0d, v0d)); for (unsigned int k = 1; k < len; ++k) { typename Configuration::value_type vu(k, 0, UP); typename Configuration::value_type vd(k, 0, DOWN); obs += genericTwoParticleGreensfunction<Configuration>(func, vu, vu, vd, vd); } // obs += func.template onSector<UP>(k, t_M, k, t_M) * func.template onSector<DOWN>(k, t_M, k, t_M); obs *= configuration.phase; this->add_bin(obs); return; } /** A class for measuring the time dependency of the kinetic energy as defined in the Hubbard model */ template <class Config> class KineticEnergy : public Network_Cache<Config, std::valarray<typename Config::SignType> > { public: typedef typename Config::Configuration Configuration; typedef typename Configuration::FPType FPType; typedef typename Config::SignType GFRetVal; typedef std::valarray<GFRetVal> ObservableType;///< Kinetic Energy is a function-like observable in realtime evolution /** The Constructor for the Average Order */ KineticEnergy(typename Config::Comm& n, const Parameters& params) throw() : Network_Cache<Config, ObservableType>(n, "KineticEnergy"), len(params.N), functionpoints(params.functionpoints), t(params.t), delta_s(params.delta_s) {} void dryrun(DryRun<typename Configuration::value_type, GFRetVal>&); /** This determines the Average Order for the given Configuration @param configuration the configuration */ inline void evaluate(const Configuration&, const DoWick<typename Configuration::value_type, GFRetVal>&); private: const uint32_t& len; const uint32_t& functionpoints; const double& t; const double delta_s; }; template <class Config> void KineticEnergy<Config>::dryrun(DryRun<typename Configuration::value_type, GFRetVal>& func) { typedef typename Configuration::value_type Vertex; for (unsigned int j = 0; j < functionpoints; ++j) { const FPType s = j * delta_s; for (unsigned int k = 0; k < len; ++k) { func.template onSector<UP>(k, s, (k + 1)%len, s); func.template onSector<UP>(k, s, (len + k - 1)%len, s); func.template onSector<DOWN>(k, s, (k + 1)%len, s); func.template onSector<DOWN>(k, s, (len + k - 1)%len, s); } } } template <class Config> void KineticEnergy<Config>::evaluate(const Configuration& configuration, const DoWick<typename Configuration::value_type, GFRetVal>& dowick) { std::valarray<GFRetVal> vals(functionpoints); for (unsigned int j = 0; j < functionpoints; ++j) { FPType s = j * delta_s; GFRetVal obs = 0; for (unsigned int k = 0; k < len; ++k) { obs += dowick.template onSector<UP>(k, s, (k + 1)%len, s); obs += dowick.template onSector<UP>(k, s, (len + k - 1)%len, s); obs += dowick.template onSector<DOWN>(k, s, (k + 1)%len, s); obs += dowick.template onSector<DOWN>(k, s, (len + k - 1)%len, s); } obs *= static_cast<FPType>(-t) * configuration.phase; vals[j] = obs; } //add to measurement this->add_bin(vals); return; } /** A class for measuring the time dependency of the Magnetization */ template <class Config> class Magnetization : public Network_Cache<Config, std::valarray<typename Config::SignType> > { public: typedef typename Config::Configuration Configuration; typedef typename Configuration::FPType FPType; typedef typename Config::SignType GFRetVal; typedef std::valarray<GFRetVal> ObservableType;///< the Magnetization is a function of the time /** The Constructor for the Magnetization */ Magnetization(typename Config::Comm& n, const Parameters& params) throw() : Network_Cache<Config, ObservableType>(n, "Magnetization"), len(params.N), functionpoints(params.functionpoints), delta_s(params.delta_s) { } void dryrun(DryRun<typename Configuration::value_type, GFRetVal>&); /** this determines the Magnetization for a given order @param configuration the configuration */ inline void evaluate(const Configuration&, const DoWick<typename Configuration::value_type, GFRetVal>&); private: const uint32_t& len; const uint32_t& functionpoints; const double delta_s; }; template <class Config> void Magnetization<Config>::dryrun(DryRun<typename Configuration::value_type, GFRetVal>& func) { typedef typename Configuration::value_type Vertex; for (unsigned int j = 0; j < functionpoints; ++j) { FPType s = j * delta_s; for (unsigned int k = 0; k < len; ++k) { func.template onSector<UP>(k, s, k, s); func.template onSector<DOWN>(k, s, k, s); } } } template <class Config> void Magnetization<Config>::evaluate(const Configuration& configuration, const DoWick<typename Configuration::value_type, GFRetVal>& dowick) { std::valarray<GFRetVal> vals(functionpoints); for (unsigned int j = 0; j < functionpoints; ++j) { FPType s = j * delta_s; GFRetVal obs = 0; for (unsigned int k = 0; k < len; ++k) { obs += dowick.template onSector<UP>(k, s, k, s) - dowick.template onSector<DOWN>(k, s, k, s); } obs *= configuration.phase; vals[j] = obs; } //add to measurement this->add_bin(vals); return; } /** A class for measuring the time dependency of the Eta-Pairing */ template <class Config> class EtaPairing : public Network_Cache<Config, std::valarray<std::valarray<std::complex<typename Config::Configuration::FPType> > > > { public: typedef typename Config::Configuration Configuration; typedef typename Configuration::FPType FPType; typedef typename Config::SignType GFRetVal; typedef std::valarray<std::complex<FPType> > Function;//Eta-Pairing in k-space can be complex typedef std::valarray<Function> ObservableType;///< The Eta-Pairing is a time-dependent /** The Constructor for the Eta-Pairing */ EtaPairing(typename Config::Comm& n, const Parameters& params) throw() : Network_Cache<Config, ObservableType>(n, "EtaPairing"), len(params.N), functionpoints(params.functionpoints), delta_s(params.delta_s) { } void dryrun(DryRun<typename Configuration::value_type, GFRetVal>&); /** this determines the Eta-Pairing for a given order @param configuration the configuration */ inline void evaluate(const Configuration&, const DoWick<typename Configuration::value_type, GFRetVal>&); private: const uint32_t& len; const uint32_t& functionpoints; const double delta_s; }; template <class Config> void EtaPairing<Config>::dryrun(DryRun<typename Configuration::value_type, GFRetVal>& func) { for (int q = 0; q < static_cast<int>(len); ++q)//for every k-space-value q { for (unsigned int j = 0; j < functionpoints; ++j)//for every timeslice { const FPType s = j * delta_s;//the realtime for (int a = 0; a < static_cast<int>(len); ++a) for (int d = 0; d < static_cast<int>(len); ++d) { func.template onSector<UP>(a, s, d, s); func.template onSector<DOWN>(a, s, d, s); } } } return; } template <class Config> void EtaPairing<Config>::evaluate(const Configuration& configuration, const DoWick<typename Configuration::value_type, GFRetVal>& dowick) { ObservableType func(len); for (int q = 0; q < static_cast<int>(len); ++q)//for every k-space-value q { func[q].resize(functionpoints); for (unsigned int j = 0; j < functionpoints; ++j)//for every timeslice { const FPType s = j * delta_s;//the realtime std::complex<FPType> t1 = 0; FPType lenf = static_cast<FPType>(len); for (int a = 0; a < static_cast<int>(len); ++a) for (int d = 0; d < static_cast<int>(len); ++d) { std::complex<FPType> pref = std::exp(std::complex<FPType>(0.0, static_cast<FPType>(TWOPI*q)/lenf*(d-a)) ); t1 += pref * dowick.template onSector<UP>(a, s, d, s) * dowick.template onSector<DOWN>(a, s, d, s); } //add to measurement func[q][j] = t1; } func[q] *= configuration.phase; } this->add_bin(func); return; } /** A class for measuring the time dependency of the Eta-Pairing */ template <class Config> class EtaPairing_Real : public Network_Cache<Config, std::valarray<std::valarray<typename Config::SignType> > > { public: typedef typename Config::Configuration Configuration; typedef typename Configuration::FPType FPType; typedef typename Config::SignType GFRetVal; typedef std::valarray<GFRetVal> Function; typedef std::valarray<Function> ObservableType;///< The Eta-Pairing is a time-dependent observable /** The Constructor for the Eta-Pairing */ EtaPairing_Real(typename Config::Comm& n, const Parameters& params) throw() : Network_Cache<Config, ObservableType>(n, "EtaPairing_Real"), len(params.N), functionpoints(params.functionpoints), delta_s(params.delta_s) { } void dryrun(DryRun<typename Configuration::value_type, GFRetVal>&); /** this determines the Eta-Pairing for a given order @param configuration the configuration */ inline void evaluate(const Configuration&, const DoWick<typename Configuration::value_type, GFRetVal>&); private: const uint32_t& len; const uint32_t& functionpoints; const double delta_s; }; template <class Config> void EtaPairing_Real<Config>::dryrun(DryRun<typename Configuration::value_type, GFRetVal>& func) { for (int q = 0; q < static_cast<int>(len); ++q)//for every lattice site q { for (unsigned int j = 0; j < functionpoints; ++j)//for every timeslice { const FPType s = j * delta_s;//the realtime func.template onSector<UP>(q, s, 0, s); func.template onSector<DOWN>(q, s, 0, s); } } return; } template <class Config> void EtaPairing_Real<Config>::evaluate(const Configuration& configuration, const DoWick<typename Configuration::value_type, GFRetVal>& dowick) { ObservableType func(len); for (uint32_t q = 0; q < len; ++q) { func[q].resize(functionpoints); for (unsigned int j = 0; j < functionpoints; ++j)//for every timeslice { const FPType s = j * delta_s;//the realtime GFRetVal t1 = dowick.template onSector<UP>(q, s, 0, s) * dowick.template onSector<DOWN>(q, s, 0, s); //add to measurement func[q][j] = t1; } func[q] *= configuration.phase; } this->add_bin(func); return; } /** A class for measuring the time dependency of the Spin-Spin-Correlation */ template <class Config> class SpinSpinCorrelation : public Network_Cache<Config, std::valarray<std::valarray<typename Config::SignType> > > { public: typedef typename Config::Configuration Configuration; typedef typename Configuration::FPType FPType; typedef typename Config::Comm Net; typedef typename Config::SignType GFRetVal; typedef std::valarray<GFRetVal> Function; typedef std::valarray<Function> ObservableType;///< Spin-Spin-Correlations are spatially resolved time-dependent observables /** The Constructor for the Spin-Spin-Correlation */ SpinSpinCorrelation(typename Config::Comm& n, const Parameters& params) throw() : Network_Cache<Config, ObservableType>(n, "SpinSpinCorrelation"), len(params.N), functionpoints(params.functionpoints), delta_s(params.delta_s) { } void dryrun(DryRun<typename Configuration::value_type, GFRetVal>&); /** this determines the Spin-Spin-Correlation for a given order @param configuration the configuration */ inline void evaluate(const Configuration&, const DoWick<typename Configuration::value_type, GFRetVal>&); private: const uint32_t& len; const uint32_t& functionpoints; const double delta_s; }; template <class Config> void SpinSpinCorrelation<Config>::dryrun(DryRun<typename Configuration::value_type, GFRetVal>& func) { for (unsigned int k = 0; k < len; ++k)//for each site { for (unsigned int j = 0; j < functionpoints; ++j)//for every time-slice { const FPType s = j * delta_s; densitydensityCorrelation_dry<Configuration>(func, 0, s, UP, k, s, UP); densitydensityCorrelation_dry<Configuration>(func, 0, s, UP, k, s, DOWN); densitydensityCorrelation_dry<Configuration>(func, 0, s, DOWN, k, s, UP); densitydensityCorrelation_dry<Configuration>(func, 0, s, DOWN, k, s, DOWN); } } return; } template <class Config> void SpinSpinCorrelation<Config>::evaluate(const Configuration& configuration, const DoWick<typename Configuration::value_type, GFRetVal>& dowick) { ObservableType func(len); for (unsigned int k = 0; k < len; ++k) { func[k].resize(functionpoints); for (unsigned int j = 0; j < functionpoints; ++j) { const FPType s = j * delta_s; GFRetVal t1 = densitydensityCorrelation<Configuration>(dowick, 0, s, UP, k, s, UP) - densitydensityCorrelation<Configuration>(dowick, 0, s, UP, k, s, DOWN) - densitydensityCorrelation<Configuration>(dowick, 0, s, DOWN, k, s, UP) + densitydensityCorrelation<Configuration>(dowick, 0, s, DOWN, k, s, DOWN); //add to measurement func[k][j] = t1 * configuration.phase/ static_cast<FPType>(4.0); } } this->add_bin(func); return; } /** A class for measuring the time dependency of the correlated part of the Spin-Spin-Correlation */ template <class Config> class SpinSpinCorrelatedPart : public Network_Cache<Config, std::valarray<std::valarray<typename Config::SignType> > > { public: typedef typename Config::Configuration Configuration; typedef typename Configuration::FPType FPType; typedef typename Config::Comm Net; typedef typename Config::SignType GFRetVal; typedef std::valarray<GFRetVal> Function; typedef std::valarray<Function> ObservableType;///< Spin-Spin-Correlations are spatially resolved time-dependent observables /** The Constructor for the correlated part Spin-Spin-Correlation */ inline SpinSpinCorrelatedPart(typename Config::Comm& n, const Parameters& params) throw() : Network_Cache<Config, ObservableType>(n, "SpinSpinCorrelatedPart"), len(params.N), functionpoints(params.functionpoints), delta_s(params.delta_s) { } void dryrun(DryRun<typename Configuration::value_type, GFRetVal>&); /** this determines the Spin-Spin-Correlation for a given order @param configuration the configuration */ inline void evaluate(const Configuration&, const DoWick<typename Configuration::value_type, GFRetVal>&); private: const uint32_t& len; const uint32_t& functionpoints; const double delta_s; }; template <class Config> void SpinSpinCorrelatedPart<Config>::dryrun(DryRun<typename Configuration::value_type, GFRetVal>& func) { for (unsigned int k = 0; k < len; ++k)//for each site { for (unsigned int j = 0; j < functionpoints; ++j)//for every time-slice { const FPType s = j * delta_s; densitydensityCorrelation_dry<Configuration>(func, 0, s, UP, k, s, UP); densitydensityCorrelation_dry<Configuration>(func, 0, s, UP, k, s, DOWN); densitydensityCorrelation_dry<Configuration>(func, 0, s, DOWN, k, s, UP); densitydensityCorrelation_dry<Configuration>(func, 0, s, DOWN, k, s, DOWN); func.template onSector<UP>(0, s, 0, s); func.template onSector<DOWN>(k, s, k, s); } } return; } template <class Config> void SpinSpinCorrelatedPart<Config>::evaluate(const Configuration& configuration, const DoWick<typename Configuration::value_type, GFRetVal>& dowick) { ObservableType func(len); for (unsigned int k = 0; k < len; ++k) { func[k].resize(functionpoints); for (unsigned int j = 0; j < functionpoints; ++j) { const FPType s = j * delta_s; GFRetVal au = dowick.template onSector<UP>(0, s, 0, s); GFRetVal ad = dowick.template onSector<DOWN>(0, s, 0, s); GFRetVal bu = dowick.template onSector<UP>(k, s, k, s); GFRetVal bd = dowick.template onSector<DOWN>(k, s, k, s); GFRetVal t1 = densitydensityCorrelation<Configuration>(dowick, 0, s, UP, k, s, UP) - densitydensityCorrelation<Configuration>(dowick, 0, s, UP, k, s, DOWN) - densitydensityCorrelation<Configuration>(dowick, 0, s, DOWN, k, s, UP) + densitydensityCorrelation<Configuration>(dowick, 0, s, DOWN, k, s, DOWN) -au*bu + au*bd + ad * bu - ad * bd; //add to measurement func[k][j] = t1 * configuration.phase/ static_cast<FPType>(4.0); } } this->add_bin(func); return; } /** A class for measuring the time dependency of the Charge-Charge-Correlation */ template <class Config> class ChargeChargeCorrelation : public Network_Cache<Config, std::valarray<std::valarray<typename Config::SignType> > > { public: typedef typename Config::Configuration Configuration; typedef typename Configuration::FPType FPType; typedef typename Config::SignType GFRetVal; typedef std::valarray<GFRetVal> Function; typedef std::valarray<Function> ObservableType;///< Charge-Charge-Correlations are spatially resolved time-dependent observables /** The Constructor for the Charge-Charge-Correlation */ ChargeChargeCorrelation(typename Config::Comm& n, const Parameters& params) throw() : Network_Cache<Config, ObservableType>(n, "ChargeChargeCorrelation"), len(params.N), functionpoints(params.functionpoints), delta_s(params.delta_s) { } void dryrun(DryRun<typename Configuration::value_type, GFRetVal>&); /** this determines the Charge-Charge-Correlation for a given order @param configuration the configuration */ inline void evaluate(const Configuration&, const DoWick<typename Configuration::value_type, GFRetVal>&); private: const uint32_t& len; const uint32_t& functionpoints; const double delta_s; }; template <class Config> void ChargeChargeCorrelation<Config>::dryrun(DryRun<typename Configuration::value_type, GFRetVal>& func) { for (unsigned int k = 0; k < len; ++k)//for each site { for (unsigned int j = 0; j < functionpoints; ++j)//for every time-slice { const FPType s = j * delta_s; densitydensityCorrelation_dry<Configuration>(func, 0, s, UP, k, s, UP); densitydensityCorrelation_dry<Configuration>(func, 0, s, UP, k, s, DOWN); densitydensityCorrelation_dry<Configuration>(func, 0, s, DOWN, k, s, UP); densitydensityCorrelation_dry<Configuration>(func, 0, s, DOWN, k, s, DOWN); } } return; } template <class Config> void ChargeChargeCorrelation<Config>::evaluate(const Configuration& configuration, const DoWick<typename Configuration::value_type, GFRetVal>& dowick) { ObservableType func(len); for (unsigned int k = 0; k < len; ++k) { func[k].resize(functionpoints); for (unsigned int j = 0; j < functionpoints; ++j) { const FPType s = j * delta_s; GFRetVal t1 = densitydensityCorrelation<Configuration>(dowick, 0, s, UP, k, s, UP) + densitydensityCorrelation<Configuration>(dowick, 0, s, UP, k, s, DOWN) + densitydensityCorrelation<Configuration>(dowick, 0, s, DOWN, k, s, UP) + densitydensityCorrelation<Configuration>(dowick, 0, s, DOWN, k, s, DOWN); //add to measurement func[k][j] = t1 * configuration.phase; } } this->add_bin(func); return; } /** A class for measuring the time dependency of the correlated part of the Charge-Charge-Correlation */ template <class Config> class ChargeChargeCorrelatedPart : public Network_Cache<Config, std::valarray<std::valarray<typename Config::SignType> > > { public: typedef typename Config::Configuration Configuration; typedef typename Configuration::FPType FPType; typedef typename Config::Comm Net; typedef typename Config::SignType GFRetVal; typedef std::valarray<GFRetVal> Function; typedef std::valarray<Function> ObservableType;///< Charge-Charge-Correlations are spatially resolved time-dependent observables /** The Constructor for the correlated part of the Charge-Charge-Correlation */ ChargeChargeCorrelatedPart(typename Config::Comm& n, const Parameters& params) throw() : Network_Cache<Config, ObservableType>(n, "ChargeChargeCorrelatedPart"), len(params.N), functionpoints(params.functionpoints), delta_s(params.delta_s) { } void dryrun(DryRun<typename Configuration::value_type, GFRetVal>&); /** this determines the correlated part of the Charge-Charge-Correlation for a given order @param configuration the configuration */ inline void evaluate(const Configuration&, const DoWick<typename Configuration::value_type, GFRetVal>&); private: const uint32_t& len; const uint32_t& functionpoints; const double delta_s; }; template <class Config> void ChargeChargeCorrelatedPart<Config>::dryrun(DryRun<typename Configuration::value_type, GFRetVal>& func) { for (unsigned int k = 0; k < len; ++k)//for each site { for (unsigned int j = 0; j < functionpoints; ++j)//for every time-slice { const FPType s = j * delta_s; densitydensityCorrelation_dry<Configuration>(func, 0, s, UP, k, s, UP); densitydensityCorrelation_dry<Configuration>(func, 0, s, UP, k, s, DOWN); densitydensityCorrelation_dry<Configuration>(func, 0, s, DOWN, k, s, UP); densitydensityCorrelation_dry<Configuration>(func, 0, s, DOWN, k, s, DOWN); func.template onSector<UP>(0, s, 0, s); func.template onSector<DOWN>(k, s, k, s); } } return; } template <class Config> void ChargeChargeCorrelatedPart<Config>::evaluate(const Configuration& configuration, const DoWick<typename Configuration::value_type, GFRetVal>& dowick) { ObservableType func(len); for (unsigned int k = 0; k < len; ++k) { func[k].resize(functionpoints); for (unsigned int j = 0; j < functionpoints; ++j) { const FPType s = j * delta_s; GFRetVal au = dowick.template onSector<UP>(0, s, 0, s); GFRetVal ad = dowick.template onSector<DOWN>(0, s, 0, s); GFRetVal bu = dowick.template onSector<UP>(k, s, k, s); GFRetVal bd = dowick.template onSector<DOWN>(k, s, k, s); GFRetVal t1 = densitydensityCorrelation<Configuration>(dowick, 0, s, UP, k, s, UP) + densitydensityCorrelation<Configuration>(dowick, 0, s, UP, k, s, DOWN) + densitydensityCorrelation<Configuration>(dowick, 0, s, DOWN, k, s, UP) + densitydensityCorrelation<Configuration>(dowick, 0, s, DOWN, k, s, DOWN) - au*bu - ad*bu - au*bd - ad*bd; //add to measurement func[k][j] = t1 * configuration.phase; } } this->add_bin(func); return; } /** A class for measuring the time dependency of the k-space resolved particle density. the dependency on the spin is summed out. It measures \sum_r <c_r^\dagger c_0 > */ template <class Config> class kSpaceDensity : public Network_Cache<Config, std::valarray<std::valarray<std::complex<typename Config::Configuration::FPType> > > > { public: typedef typename Config::Configuration Configuration; typedef typename Configuration::FPType FPType; typedef typename Config::Comm Net; typedef typename Config::SignType GFRetVal; typedef std::valarray<std::complex<FPType> > Function; typedef std::valarray<Function> ObservableType;///< Charge-Charge-Correlations are spatially resolved time-dependent observables /** The Constructor for the Charge-Charge-Correlation */ kSpaceDensity(typename Config::Comm& n, const Parameters& params) throw() : Network_Cache<Config, ObservableType>(n, "kSpaceDensity"), len(params.N), functionpoints(params.functionpoints), delta_s(params.delta_s) { } void dryrun(DryRun<typename Configuration::value_type, GFRetVal>&); /** this determines the Charge-Charge-Correlation for a given order @param configuration the configuration */ inline void evaluate(const Configuration&, const DoWick<typename Configuration::value_type, GFRetVal>&); private: const uint32_t& len; const uint32_t& functionpoints; const double delta_s; }; template <class Config> void kSpaceDensity<Config>::dryrun(DryRun<typename Configuration::value_type, GFRetVal>& func) { for (unsigned int r = 0; r < len; ++r)//for each site { for (unsigned int j = 0; j < functionpoints; ++j)//for every time-slice { const FPType s = j * delta_s; func.template onSector<UP>(r, s, 0, s); func.template onSector<DOWN>(r, s, 0, s); } } return; } template <class Config> void kSpaceDensity<Config>::evaluate(const Configuration& configuration, const DoWick<typename Configuration::value_type, GFRetVal>& dowick) { ObservableType func(len); for (unsigned int k = 0; k < len; ++k) { func[k].resize(functionpoints); for (unsigned int j = 0; j < functionpoints; ++j) { const FPType s = j * delta_s; std::complex<FPType> t1 = 0; for (unsigned int r = 0; r < len; ++r) { std::complex<FPType> t2 = dowick.template onSector<UP>(r, s, 0, s) + dowick.template onSector<DOWN>(r, s, 0, s); t2 = t2 * std::exp(std::complex<FPType>(0.0, static_cast<FPType>(2.0 * M_PIl/len) * k * r) ); t1 += t2; } //add to measurement func[k][j] = t1 * configuration.phase; } } this->add_bin(func); return; } /** A class for measuring the time dependency of the LocalDensityVariance */ template <class Config> class LocalDensityVariance : public Network_Cache<Config, std::valarray<std::valarray<typename Config::SignType> > > { public: typedef typename Config::Configuration Configuration; typedef typename Configuration::FPType FPType; typedef typename Config::SignType GFRetVal; typedef std::valarray<GFRetVal> Function; typedef std::valarray<Function> ObservableType;///< LocalDensityVariance is a spatially resolved time-dependent observable /** The Constructor for the LocalDensityVariance */ LocalDensityVariance(typename Config::Comm& n, const Parameters& params) throw() : Network_Cache<Config, ObservableType>(n, "LocalDensityVariance"), len(params.N), functionpoints(params.functionpoints), delta_s(params.delta_s) { } void dryrun(DryRun<typename Configuration::value_type, GFRetVal>&); /** this determines the LocalDensityVariance for a given order @param configuration the configuration */ inline void evaluate(const Configuration&, const DoWick<typename Configuration::value_type, GFRetVal>&); private: const uint32_t& len; const uint32_t& functionpoints; const double delta_s; }; template <class Config> void LocalDensityVariance<Config>::dryrun(DryRun<typename Configuration::value_type, GFRetVal>& func) { for (unsigned int k = 0; k < len; ++k)//for each site { for (unsigned int j = 0; j < functionpoints; ++j)//for every time-slice { const FPType s = j * delta_s; func.template onSector<UP>(k, s, k, s); func.template onSector<DOWN>(k, s, k, s); densitydensityCorrelation_dry<Configuration>(func, k, s, UP, k, s, DOWN); } } return; } template <class Config> void LocalDensityVariance<Config>::evaluate(const Configuration& configuration, const DoWick<typename Configuration::value_type, GFRetVal>& dowick) { ObservableType func(len); for (unsigned int k = 0; k < len; ++k) { func[k].resize(functionpoints); for (unsigned int j = 0; j < functionpoints; ++j) { const FPType s = j * delta_s; GFRetVal nup = dowick.template onSector<UP>(k, s, k, s); GFRetVal ndown = dowick.template onSector<UP>(k, s, k, s); GFRetVal nupndown = densitydensityCorrelation<Configuration>(dowick, k, s, UP, k, s, DOWN); //add to measurement func[k][j] = configuration.phase * (nup*(static_cast<FPType>(1.0) - nup) + ndown*(static_cast<FPType>(1.0) - ndown) + static_cast<FPType>(2.0) * (nupndown - nup*ndown)); } } this->add_bin(func); return; } /** A class for measuring the time dependency of the Greensfunctions, thus <c_0(0)^\dagger c_r(s)>, WE MEASURE THE UP-SECTOR! */ template <class Config> class Greensfunction : public Network_Cache<Config, std::valarray<std::valarray<typename Config::SignType> > > { public: typedef typename Config::Configuration Configuration; typedef typename Configuration::FPType FPType; typedef typename Config::SignType GFRetVal; typedef std::valarray<GFRetVal> Function; typedef std::valarray<Function> ObservableType;///< The Greensfunction contains an array of functions /** The Constructor for the Greensfunction */ Greensfunction(typename Config::Comm& n, const Parameters& params) throw() : Network_Cache<Config, ObservableType> (n, "Greensfunction"), len(params.N), functionpoints(params.functionpoints), delta_s(params.delta_s) { } void dryrun(DryRun<typename Configuration::value_type, GFRetVal>&); /** Here we evaluate for a given order the values of all Greensfunctions @param configuration the configuration */ inline void evaluate(const Configuration&, const DoWick<typename Configuration::value_type, GFRetVal>&); private: const uint32_t& len; const uint32_t& functionpoints; const double delta_s; }; template <class Config> void Greensfunction<Config>::dryrun(DryRun<typename Configuration::value_type, GFRetVal>& func) { for (unsigned int k = 0; k < len; ++k)//for each site { for (unsigned int j = 0; j < functionpoints; ++j)//for every time-slice { const FPType s = j * delta_s; /* typename Configuration::value_type v1(k, s, UP); typename Configuration::value_type v2(0, 0, DOWN); func(v1, v2);*/ func.template onSector<UP>(k, s, 0, 0); // func.template onSector<DOWN>(k, s, 0, 0); } } return; } template <class Config> void Greensfunction<Config>::evaluate(const Configuration& configuration, const DoWick<typename Configuration::value_type, GFRetVal>& dowick) { ObservableType func(len); for (unsigned int k = 0; k < len; ++k) { func[k].resize(functionpoints); for (unsigned int j = 0; j < functionpoints; ++j) { const FPType s = j * delta_s; /* typename Configuration::value_type v1(k, s, UP); typename Configuration::value_type v2(0, 0, DOWN); GFRetVal t1 = dowick(v1, v2);*/ GFRetVal t1 = dowick.template onSector<UP>(k, s, 0, 0) //+dowick.template onSector<DOWN>(k, s, 0, 0) ; //add to measurement func[k][j] = configuration.phase * t1; } } this->add_bin(func); return; } /** A class for measuring the Diagonal Green's function <c_ks(tau)^\dagger c_ks(0)>, We employ Time-reversal symmetry to enhance the measurement. In theory it is always a real quantity */ template <class Config> class DiagonalGreensfunction_kspace : public Network_Cache<Config, std::valarray<std::valarray<std::complex<typename Config::Configuration::FPType> > > > { public: typedef typename Config::Configuration Configuration; typedef typename Configuration::FPType FPType; typedef typename Config::SignType GFRetVal; typedef std::valarray<std::complex<FPType> > Function; typedef std::valarray<Function> ObservableType;///< The Greensfunction contains an array of functions /** The Constructor for the Greensfunction */ DiagonalGreensfunction_kspace(typename Config::Comm& n, const Parameters& params) throw() : Network_Cache<Config, ObservableType> (n, "Greensfunction"), len(params.N), functionpoints(params.functionpoints), delta_s(params.delta_s) { } void dryrun(DryRun<typename Configuration::value_type, GFRetVal>&); /** Here we evaluate for a given order the values of all Greensfunctions @param configuration the configuration */ inline void evaluate(const Configuration&, const DoWick<typename Configuration::value_type, GFRetVal>&); private: const uint32_t& len; const uint32_t& functionpoints; const double delta_s; }; template <class Config> void DiagonalGreensfunction_kspace<Config>::dryrun(DryRun<typename Configuration::value_type, GFRetVal>& func) { for (unsigned int r = 0; r < len; ++r)//for each site { for (unsigned int j = 0; j < functionpoints; ++j)//for every time-slice { const FPType s = j * delta_s; func.template onSector<UP>(r, s, 0, 0); func.template onSector<DOWN>(r, s, 0, 0); } } return; } template <class Config> void DiagonalGreensfunction_kspace<Config>::evaluate(const Configuration& configuration, const DoWick<typename Configuration::value_type, GFRetVal>& dowick) { ObservableType func(len); FPType invlen = static_cast<FPType>(1.0)/len; for (unsigned int k = 0; k < len; ++k) { func[k].resize(functionpoints); for (unsigned int j = 0; j < functionpoints; ++j) { const FPType s = j * delta_s; std::complex<FPType> sum = 0; for(uint r = 0; r < len; ++r) { std::complex<FPType> a = std::exp(std::complex<FPType>(0.0, -static_cast<FPType>(TWOPI*k*r)*invlen)); GFRetVal t1 = dowick.template onSector<UP>(r, s, 0, 0) + dowick.template onSector<DOWN>((len-r)%len, s, 0, 0); sum += a * t1; } func[k][j] = 0.5*configuration.phase * sum /* invlen*/;//not sure about that invlen here... } } this->add_bin(func); return; } /** A class for measuring the TRI Diagonal Green's function <c_ks(tau)^\dagger c_ks(0)>, s = +- */ template <class Config, int sign> class TRI_Greensfunction_kspace : public Network_Cache<Config, std::valarray<std::valarray< //typename Config::Configuration::FPType typename Config::SignType > > > { public: typedef typename Config::Configuration Configuration; typedef typename Configuration::FPType FPType; typedef typename Config::SignType GFRetVal; typedef std::valarray<GFRetVal> Function;//G++ and G-- are real typedef std::valarray<Function> ObservableType;///< The Greensfunction contains an array of functions /** The Constructor for the Greensfunction */ TRI_Greensfunction_kspace(typename Config::Comm& n, const Parameters& params) throw() : Network_Cache<Config, ObservableType> (n, "TRI_Greensfunction_kspace"), len(params.N), functionpoints(params.functionpoints), delta_s(params.delta_s) { } void dryrun(DryRun<typename Configuration::value_type, GFRetVal>&); /** Here we evaluate for a given order the values of all Greensfunctions @param configuration the configuration */ inline void evaluate(const Configuration&, const DoWick<typename Configuration::value_type, GFRetVal>&); private: const uint32_t& len; const uint32_t& functionpoints; const double delta_s; }; template <class Config, int sign> void TRI_Greensfunction_kspace<Config, sign>::dryrun(DryRun<typename Configuration::value_type, GFRetVal>& func) { typename Configuration::value_type v2(0, 0, DOWN); typename Configuration::value_type v4(0, 0, UP); for (unsigned int j = 0; j < functionpoints; ++j) { const FPType s = j * delta_s; for(uint r = 0; r < len; ++r) { typename Configuration::value_type v1(r, s, UP); typename Configuration::value_type v3(r, s, DOWN); func.template onSector<UP>(r, s, 0, 0); // func.template onSector<DOWN>(r, s, 0, 0); func(v1, v2); // func(v3, v4); } } return; } template <class Config, int sign> void TRI_Greensfunction_kspace<Config, sign>::evaluate(const Configuration& configuration, const DoWick<typename Configuration::value_type, GFRetVal>& dowick) { ObservableType func(len); FPType invlen = static_cast<FPType>(1.0)/len; typename Configuration::value_type v2(0, 0, DOWN); typename Configuration::value_type v4(0, 0, UP); for (unsigned int k = 0; k < len; ++k) { func[k].resize(functionpoints); for (unsigned int j = 0; j < functionpoints; ++j) { const FPType s = j * delta_s; GFRetVal sum = 0; for(uint r = 0; r < len; ++r) { std::complex<FPType> a = std::exp(std::complex<FPType>(0.0, -static_cast<FPType>(TWOPI*k*r)*invlen)); typename Configuration::value_type v1(r, s, UP); typename Configuration::value_type v3(r, s, DOWN); // std::complex<FPType> t1 = dowick.template onSector<UP>(r, s, 0, 0) + dowick.template onSector<DOWN>(r, s, 0, 0) // + std::complex<FPType>(0.0, sign)*( dowick(v1, v2) - dowick(v3, v4)); //the next line is equivalent down to the Monte-Carlo level it seems... // std::complex<FPType> t1 = dowick.template onSector<UP>(r, s, 0, 0) + std::complex<FPType>(0.0, sign)*dowick(v1,v2); GFRetVal gd = dowick.template onSector<UP>(r, s, 0, 0);//measure diagonal GFRetVal go = dowick(v1, v2);//measure offdiagonal sum += real(a)*gd - sign * imag(a) * go; } func[k][j] = configuration.phase * sum; } } this->add_bin(func); return; } /** A class for measuring the Diagonal Green's function <c_ks(tau)^\dagger c_k(-s)(0)>, We employ Time-reversal symmetry to enhance the measurement. */ template <class Config> class OffDiagonalGreensfunction_kspace : public Network_Cache<Config, std::valarray<std::valarray<std::complex<typename Config::Configuration::FPType> > > > { public: typedef typename Config::Configuration Configuration; typedef typename Configuration::FPType FPType; typedef typename Config::SignType GFRetVal; typedef std::valarray<std::complex<FPType> > Function; typedef std::valarray<Function> ObservableType;///< The Greensfunction contains an array of functions /** The Constructor for the Greensfunction */ OffDiagonalGreensfunction_kspace(typename Config::Comm& n, const Parameters& params) throw() : Network_Cache<Config, ObservableType> (n, "Greensfunction"), len(params.N), functionpoints(params.functionpoints), delta_s(params.delta_s) { } void dryrun(DryRun<typename Configuration::value_type, GFRetVal>&); /** Here we evaluate for a given order the values of all Greensfunctions @param configuration the configuration */ inline void evaluate(const Configuration&, const DoWick<typename Configuration::value_type, GFRetVal>&); private: const uint32_t& len; const uint32_t& functionpoints; const double delta_s; }; template <class Config> void OffDiagonalGreensfunction_kspace<Config>::dryrun(DryRun<typename Configuration::value_type, GFRetVal>& func) { typename Configuration::value_type v2(0, 0, DOWN); typename Configuration::value_type v4(0, 0, UP); for (unsigned int r = 0; r < len; ++r)//for each site { for (unsigned int j = 0; j < functionpoints; ++j)//for every time-slice { const FPType s = j * delta_s; typename Configuration::value_type v1(r, s, UP); func(v1, v2); typename Configuration::value_type v3(r, s, DOWN); func(v3, v4); } } return; } template <class Config> void OffDiagonalGreensfunction_kspace<Config>::evaluate(const Configuration& configuration, const DoWick<typename Configuration::value_type, GFRetVal>& dowick) { ObservableType func(len); FPType invlen = static_cast<FPType>(1.0)/len; typename Configuration::value_type v2(0, 0, DOWN); typename Configuration::value_type v4(0, 0, UP); const FPType fac = TWOPI * invlen; for (unsigned int k = 0; k < len; ++k) { func[k].resize(functionpoints); for (unsigned int j = 0; j < functionpoints; ++j) { const FPType s = j * delta_s; std::complex<FPType> sum = 0; for(uint r = 0; r < len; ++r) { std::complex<FPType> pref = std::exp(std::complex<FPType>(0.0, -fac * (k*r))); typename Configuration::value_type v1(r, s, UP); typename Configuration::value_type v3((len - r)%len, s, DOWN); GFRetVal t1 = dowick(v1, v2) + dowick(v3, v4); sum += pref * t1; } func[k][j] = 0.5*configuration.phase * sum;//normalization not necessary since the 1/N factor is already in the definition of G_0 } } this->add_bin(func); return; } /** A class for measuring the time dependency of the Greensfunctions, thus <c_0(0)^\dagger c_r(s)>. This Greensfunction only has sense for imaginary time measurements, because we use David's smoothing trick. WE MEASURE THE DOWN-SECTOR! */ template <class Config> class SmoothImaginaryGreensfunction : public Network_Cache<Config, std::valarray<std::valarray<typename Config::SignType> > > { public: typedef typename Config::Configuration Configuration; typedef typename Configuration::FPType FPType; typedef typename Config::SignType GFRetVal; typedef std::valarray<GFRetVal> Function; typedef std::valarray<Function> ObservableType;///< The Greensfunction contains an array of functions /** The Constructor for the Greensfunction */ SmoothImaginaryGreensfunction(typename Config::Comm& n, const Parameters& params) throw() : Network_Cache<Config, ObservableType>(n, "SmoothImaginaryGreensfunction"), len(params.N), functionpoints(params.functionpoints), delta_s(params.delta_s), beta(params.beta) { } void dryrun(DryRun<typename Configuration::value_type, GFRetVal>&); /** Here we evaluate for a given order the values of all Greensfunctions @param configuration the configuration */ inline void evaluate(const Configuration&, const DoWick<typename Configuration::value_type, GFRetVal>&); private: const uint32_t& len; const uint32_t& functionpoints; const double delta_s; const double beta; }; template <class Config> void SmoothImaginaryGreensfunction<Config>::dryrun(DryRun<typename Configuration::value_type, GFRetVal>& func) { for (unsigned int k = 0; k < len; ++k)//for each site { for (unsigned int j = 0; j < functionpoints; ++j)//for every time-slice { for (unsigned int i = 0; i < trunc(beta/delta_s); ++i) { // func.template onSector<UP>(k, s, 0, 0); func.template onSector<DOWN>(0, static_cast<FPType>(i+j)*delta_s, k, i * delta_s); } } } return; } template <class Config> void SmoothImaginaryGreensfunction<Config>::evaluate(const Configuration& configuration, const DoWick<typename Configuration::value_type, GFRetVal>& dowick) { ObservableType func(len); for (unsigned int k = 0; k < len; ++k) { func[k].resize(functionpoints); for (unsigned int j = 0; j < functionpoints; ++j) { GFRetVal sum = 0; for (unsigned int i = 0; i < trunc(beta/delta_s); ++i) { sum += /*dowick.template onSector<UP>(k, s, 0, 0) +*/ dowick.template onSector<DOWN>(0, static_cast<FPType>(i+j)*delta_s, k, i * delta_s) * delta_s ; } //add to measurement func[k][j] = configuration.phase * sum/beta; } } this->add_bin(func); return; } /** A class for measuring the time dependency of the Greensfunctions, thus <c_0(0)^\dagger c_r(s)>. This Greensfunction only has sense for imaginary time measurements, because we use David's smoothing trick. Here we average over both Spin sectors */ template <class Config> class SmoothImaginaryGreensfunction_averaged : public Network_Cache<Config, std::valarray<std::valarray<typename Config::SignType> > > { public: typedef typename Config::Configuration Configuration; typedef typename Configuration::FPType FPType; typedef typename Config::SignType GFRetVal; typedef std::valarray<GFRetVal> Function; typedef std::valarray<Function> ObservableType;///< The Greensfunction contains an array of functions /** The Constructor for the Greensfunction */ SmoothImaginaryGreensfunction_averaged(typename Config::Comm& n, const Parameters& params) throw() : Network_Cache<Config, ObservableType>(n, "SmoothImaginaryGreensfunction_averaged"), len(params.N), functionpoints(params.functionpoints), delta_s(params.delta_s), beta(params.beta) { } void dryrun(DryRun<typename Configuration::value_type, GFRetVal>&); /** Here we evaluate for a given order the values of all Greensfunctions @param configuration the configuration */ inline void evaluate(const Configuration&, const DoWick<typename Configuration::value_type, GFRetVal>&); private: const uint32_t& len; const uint32_t& functionpoints; const double delta_s; const double beta; }; template <class Config> void SmoothImaginaryGreensfunction_averaged<Config>::dryrun(DryRun<typename Configuration::value_type, GFRetVal>& func) { for (unsigned int k = 0; k < len; ++k)//for each site { for (unsigned int j = 0; j < functionpoints; ++j)//for every time-slice { for (unsigned int i = 0; i < trunc(beta/delta_s); ++i) { func.template onSector<DOWN>(0, static_cast<FPType>(i+j)*delta_s, k, i * delta_s); func.template onSector<UP>(0, static_cast<FPType>(i+j)*delta_s, k, i * delta_s); } } } return; } template <class Config> void SmoothImaginaryGreensfunction_averaged<Config>::evaluate(const Configuration& configuration, const DoWick<typename Configuration::value_type, GFRetVal>& dowick) { ObservableType func(len); for (unsigned int k = 0; k < len; ++k) { func[k].resize(functionpoints); for (unsigned int j = 0; j < functionpoints; ++j) { GFRetVal sum = 0; for (unsigned int i = 0; i < trunc(beta/delta_s); ++i) { sum += (dowick.template onSector<DOWN>(0, static_cast<FPType>(i+j)*delta_s, k, i * delta_s) + dowick.template onSector<UP>(0, static_cast<FPType>(i+j)*delta_s, k, i * delta_s)) * delta_s; } //add to measurement func[k][j] = configuration.phase * sum/beta/2.0; } } this->add_bin(func); return; } /** A class for measuring the Matsubarafrequency Greensfunction thus <c_0(0)^\dagger c_r(i omega)>, WE MEASURE THE UP-SECTOR! */ template <class Config, class Greensfunction> class MatsubaraFrequencyGreensfunction : public Network_Cache<Config, std::valarray<std::valarray<std::complex<typename Config::Configuration::FPType> > > > { public: typedef typename Config::Configuration Configuration; typedef typename Configuration::FPType FPType; typedef typename Config::SignType GFRetVal; typedef std::valarray<std::complex<FPType> > Function; typedef std::valarray<Function> ObservableType;///< The Matsubarafrequency dependent Greensfunction contains an array of functions /** The Constructor for the Greensfunction */ MatsubaraFrequencyGreensfunction(typename Config::Comm& n, const Parameters& params) throw() : Network_Cache<Config, ObservableType>(n, "MatsubaraFrequencyGreensfunction"), len(params.N), functionpoints(params.functionpoints), delta_s(params.delta_s), beta(params.beta) { } void dryrun(DryRun<typename Configuration::value_type, GFRetVal>&) MTL_CONST_FUNCTION; /** Here we evaluate for a given order the values of all Greensfunctions @param configuration the configuration */ inline void evaluate(const Configuration&, const DoWick<typename Configuration::value_type, GFRetVal>&); private: const uint32_t& len; const uint32_t& functionpoints; const FPType delta_s; const FPType beta; }; template <class Config, class Greensfunction> void MatsubaraFrequencyGreensfunction<Config, Greensfunction>::dryrun(DryRun<typename Configuration::value_type, GFRetVal>&) { } template <class Config, class Greensfunction> void MatsubaraFrequencyGreensfunction<Config, Greensfunction>::evaluate(const Configuration& configuration, const DoWick<typename Configuration::value_type, GFRetVal>&) { ObservableType func(len); typename Greensfunction::Vertex v; v.spin = UP; for (unsigned int k = 0; k < len; ++k) { func[k].resize(functionpoints); for (unsigned int r = 0; r < configuration.size(); ++r) for (unsigned int s = 0; s < configuration.size(); ++s) { const FPType deltars = configuration[r].tau - configuration[s].tau; std::complex<FPType> inc = std::exp(std::complex<FPType>(0.0, deltars * M_PI / beta)); const std::complex<FPType> fac = inc * inc; inc *= configuration.matcont(r, s, UP, UP); for (unsigned int n = 0; n < functionpoints; ++n) { func[k][n] += inc; inc *= fac; } } for (unsigned int n = 0; n < functionpoints; ++n) { FPType omegan = M_PI/beta*static_cast<FPType>(2*n+1); std::complex<FPType> gomegan = Greensfunction::gomega(omegan, v, v); func[k][n] = configuration.phase * gomegan * (static_cast<FPType>(1.0) - gomegan*func[k][n]/beta); } } this->add_bin(func); return; } /** A class for measuring the averaged Matsubarafrequency Greensfunction thus sum_\sigma <c_0(0)^\dagger c_r(i omega)>, */ template <class Config, class Greensfunction> class MatsubaraFrequencyGreensfunction_averaged : public Network_Cache<Config, std::valarray<std::valarray<std::complex<typename Config::Configuration::FPType> > > > { public: typedef typename Config::Configuration Configuration; typedef typename Configuration::FPType FPType; typedef typename Config::SignType GFRetVal; typedef std::valarray<std::complex<FPType> > Function; typedef std::valarray<Function> ObservableType;///< The Matsubarafrequency dependent Greensfunction contains an array of functions /** The Constructor for the Greensfunction */ MatsubaraFrequencyGreensfunction_averaged(typename Config::Comm& n, const Parameters& params) throw() : Network_Cache<Config, ObservableType>(n, "MatsubaraFrequencyGreensfunction_averaged"), len(params.N), functionpoints(params.functionpoints), delta_s(params.delta_s), beta(params.beta) { } void dryrun(DryRun<typename Configuration::value_type, GFRetVal>&) MTL_CONST_FUNCTION; /** Here we evaluate for a given order the values of all Greensfunctions @param configuration the configuration */ inline void evaluate(const Configuration&, const DoWick<typename Configuration::value_type, GFRetVal>&); private: const uint32_t& len; const uint32_t& functionpoints; const FPType delta_s; const FPType beta; }; template <class Config, class Greensfunction> void MatsubaraFrequencyGreensfunction_averaged<Config, Greensfunction>::dryrun(DryRun<typename Configuration::value_type, GFRetVal>&) { } template <class Config, class Greensfunction> void MatsubaraFrequencyGreensfunction_averaged<Config, Greensfunction>::evaluate(const Configuration& configuration, const DoWick<typename Configuration::value_type, GFRetVal>&) { ObservableType func(len); typename Greensfunction::Vertex vup; typename Greensfunction::Vertex vdown; vup.spin = UP; vdown.spin = DOWN; for (unsigned int k = 0; k < len; ++k) { func[k].resize(functionpoints); std::complex<FPType> gup[functionpoints]; std::complex<FPType> gdown[functionpoints]; for (unsigned int n = 0; n < functionpoints; ++n) { FPType omegan = M_PI/beta*static_cast<FPType>(2*n+1); std::complex<FPType> gomeganup = Greensfunction::gomega(omegan, vup, vup); std::complex<FPType> gomegandown = Greensfunction::gomega(omegan, vdown, vdown); gup[n] = gomeganup; gdown[n] = gomegandown; } for (unsigned int r = 0; r < configuration.size(); ++r) for (unsigned int s = 0; s < configuration.size(); ++s) { const FPType deltars = configuration[r].tau - configuration[s].tau; std::complex<FPType> inc = std::exp(std::complex<FPType>(0.0, deltars * M_PI / beta)); const std::complex<FPType> fac = inc * inc; // inc *= configuration.matcont.mat(2*r, 2*s); for (unsigned int n = 0; n < functionpoints; ++n) { func[k][n] += (gup[n]*gup[n]*configuration.matcont.mat(2*r, 2*s) + gdown[n]*gdown[n]*configuration.matcont.mat(2*r+1, 2*s+1))*inc; inc *= fac; } } for (unsigned int n = 0; n < functionpoints; ++n) { func[k][n] = configuration.phase * (gup[n] + gdown[n] - func[k][n]/beta); } } this->add_bin(func); return; } /** A class for measuring the derivative with respect to omega of the Matsubarafrequency Greensfunction thus d/domega <c_0(0)^\dagger c_r(i omega)>, WE MEASURE THE UP-SECTOR! */ template <class Config, class Greensfunction> class MatsubaraFrequencyGreensfunctionDerivative : public Network_Cache<Config, std::valarray<std::valarray<std::complex<typename Config::Configuration::FPType> > > > { public: typedef typename Config::Configuration Configuration; typedef typename Configuration::FPType FPType; typedef typename Config::SignType GFRetVal; typedef std::valarray<std::complex<FPType> > Function; typedef std::valarray<Function> ObservableType;///< The Matsubarafrequency dependent Greensfunction contains an array of functions /** The Constructor for the Greensfunction */ MatsubaraFrequencyGreensfunctionDerivative(typename Config::Comm& n, const Parameters& params) throw() : Network_Cache<Config, ObservableType>(n, "MatsubaraFrequencyGreensfunctionDerivative"), len(params.N), functionpoints(params.functionpoints), delta_s(params.delta_s), beta(params.beta) { } void dryrun(DryRun<typename Configuration::value_type, GFRetVal>&) MTL_CONST_FUNCTION; /** Here we evaluate for a given order the values of all Greensfunctions @param configuration the configuration */ inline void evaluate(const Configuration&, const DoWick<typename Configuration::value_type, GFRetVal>&); private: const uint32_t& len; const uint32_t& functionpoints; const FPType delta_s; const FPType beta; }; template <class Config, class Greensfunction> void MatsubaraFrequencyGreensfunctionDerivative<Config, Greensfunction>::dryrun(DryRun<typename Configuration::value_type, GFRetVal>&) { } template <class Config, class Greensfunction> void MatsubaraFrequencyGreensfunctionDerivative<Config, Greensfunction>::evaluate(const Configuration& configuration, const DoWick<typename Configuration::value_type, GFRetVal>&) { ObservableType func(len); for (unsigned int k = 0; k < len; ++k) { func[k].resize(functionpoints); Function temp(functionpoints); /* for (unsigned int n = 0; n < functionpoints; ++n) { const FPType omegan = M_PI/beta*static_cast<FPType>(2*n+1); const std::complex<FPType> gomegan = CRAPPY_Make_compile_Helper<Greensfunction, Configuration>::measure(omegan, beta, v, w, ed, mu); for(unsigned int r = 0; r < configuration.size(); ++r) { for(unsigned int s = 0; s < configuration.size(); ++s) func[k][n] += std::exp(std::complex<FPType>(0.0, omegan * (configuration[r].tau - configuration[s].tau))) * configuration.up.inverse(r,s); } func[k][n] /= beta; func[k][n] *= gomegan; func[k][n] = configuration.phase * gomegan * (1.0 - func[k][n]); }*/ for (unsigned int r = 0; r < configuration.size(); ++r) for (unsigned int s = 0; s < configuration.size(); ++s) { const FPType deltars = configuration[r].tau - configuration[s].tau; std::complex<FPType> inc1 = std::exp(std::complex<FPType>(0.0, deltars * M_PI / beta)); const std::complex<FPType> fac = inc1 * inc1; inc1 *= configuration.matcont.up(r, s); std::complex<FPType> inc2 = inc1 * std::complex<FPType>(0.0, deltars); for (unsigned int n = 0; n < functionpoints; ++n) { func[k][n] += inc1;//func[k][n] is the sum, that is the same as in the plain Matsubara Greensfunction temp[n] += inc2; inc1 *= fac; inc2 *= fac; } } for (unsigned int n = 0; n < functionpoints; ++n) { FPType omegan = M_PI/beta*static_cast<FPType>(2*n+1); const FPType tiny = 0.00000001;//same as in the greensfunctions const FPType h = pow(tiny, 1.0/3.0) * 0.707 * omegan;//an optimal choice of h for the symmetric derivative derived for a function that behaves as 1/x... see NR 5.7 std::complex<FPType> gomegan = Greensfunction::gomega(omegan, UP); std::complex<FPType> gomeganplush = Greensfunction::gomega(omegan + h, UP); std::complex<FPType> gomeganminush = Greensfunction::gomega(omegan - h, UP); std::complex<FPType> derivative = (gomeganplush - gomeganminush)/(static_cast<FPType>(2.0)*h); func[k][n] = configuration.phase * (derivative - static_cast<FPType>(2.0)/beta * gomegan * derivative * func[k][n] - static_cast<FPType>(1.0)/beta* gomegan * gomegan * temp[n]); } } this->add_bin(func); return; } /** A class for measuring the time dependency of the Density-Density-StructureFactor */ template <class Config> class DensityDensityStructureFactor : public Network_Cache<Config, std::valarray<std::valarray<std::complex<typename Config::Configuration::FPType> > > > { public: typedef typename Config::Configuration Configuration; typedef typename Configuration::FPType FPType; typedef typename Config::SignType GFRetVal; typedef std::valarray<std::complex<FPType> > Function;//the density-density structure factor is determined by a Fourier-transform. Therefore it can be a complex type typedef std::valarray<Function> ObservableType;///< the density-density-structure-factor is a k-space resolved time-dependent observables /** The Constructor for the DensityDensityStructureFactor */ DensityDensityStructureFactor(typename Config::Comm& n, const Parameters& params) throw() : Network_Cache<Config, ObservableType>(n, "DensityDensityStructureFactor"), len(params.N), functionpoints(params.functionpoints), delta_s(params.delta_s) { } void dryrun(DryRun<typename Configuration::value_type, GFRetVal>&); /** This determines the DensityDensityStructureFactor for a given order @param configuration the configuration */ inline void evaluate(const Configuration&, const DoWick<typename Configuration::value_type, GFRetVal>&); private: const uint32_t& len; const uint32_t& functionpoints; const double delta_s; }; template <class Config> void DensityDensityStructureFactor<Config>::dryrun(DryRun<typename Configuration::value_type, GFRetVal>& func) { for (unsigned int k = 0; k < len; ++k) { for (unsigned int a = 0; a < len; ++a) { for (unsigned int j = 0; j < functionpoints; ++j) { const FPType s = j * delta_s; densitydensityCorrelation_dry<Configuration>(func, a, s, UP, k, s, UP); densitydensityCorrelation_dry<Configuration>(func, a, s, UP, k, s, DOWN); densitydensityCorrelation_dry<Configuration>(func, a, s, DOWN, k, s, UP); densitydensityCorrelation_dry<Configuration>(func, a, s, DOWN, k, s, DOWN); } } } return; } template <class Config> void DensityDensityStructureFactor<Config>::evaluate(const Configuration& configuration, const DoWick<typename Configuration::value_type, GFRetVal>& dowick) { ObservableType func(len); for (unsigned int k = 0; k < len; ++k) { func[k].resize(functionpoints); for (unsigned int j = 0; j < functionpoints; ++j) { const FPType s = j * delta_s; std::complex<FPType> t1 = 0; FPType lenf = static_cast<FPType>(len); for (int a = 0; a < static_cast<int>(len); ++a) for (int d = 0; d < static_cast<int>(len); ++d) { std::complex<FPType> pref = std::exp(std::complex<FPType>(0.0, static_cast<FPType>(TWOPI*k)/lenf*(d-a)) ); t1 += pref * (densitydensityCorrelation<Configuration>(dowick, a, s, UP, d, s, UP) + densitydensityCorrelation<Configuration>(dowick, a, s, UP, d, s, DOWN) + densitydensityCorrelation<Configuration>(dowick, a, s, DOWN, d, s, UP) + densitydensityCorrelation<Configuration>(dowick, a, s, DOWN, d, s, DOWN)); } //add to measurement func[k][j] = t1 * configuration.phase/lenf; } } this->add_bin(func); return; } /** A class for measuring the time dependency of the DoubleOccupancy */ template <class Config> class DoubleOccupancy : public Network_Cache<Config, std::valarray<std::valarray<typename Config::SignType> > > { public: typedef typename Config::Configuration Configuration; typedef typename Configuration::FPType FPType; typedef typename Config::SignType GFRetVal; typedef std::valarray<GFRetVal> Function; typedef std::valarray<Function> ObservableType;///< DoubleOccupancy is a spatially resolved time-dependent observable /** The Constructor for the DoubleOccupancy */ DoubleOccupancy(typename Config::Comm& n, const Parameters& params) throw() : Network_Cache<Config,ObservableType>(n, "DoubleOccupancy"), len(params.N), functionpoints(params.functionpoints), delta_s(params.delta_s) { } void dryrun(DryRun<typename Configuration::value_type, GFRetVal>&); /** this determines the DoubleOccupancy for a given order @param configuration the configuration */ inline void evaluate(const Configuration&, const DoWick<typename Configuration::value_type, GFRetVal>&); private: const uint32_t& len; const uint32_t& functionpoints; const double delta_s; }; template <class Config> void DoubleOccupancy<Config>::dryrun(DryRun<typename Configuration::value_type, GFRetVal>& func) { for (unsigned int k = 0; k < len; ++k)//for each site { for (unsigned int j = 0; j < functionpoints; ++j)//for every time-slice { const FPType s = j * delta_s; densitydensityCorrelation_dry<Configuration>(func, k, s, DOWN, k, s, UP); } } return; } template <class Configuration> void DoubleOccupancy<Configuration>::evaluate(const Configuration& configuration, const DoWick<typename Configuration::value_type, GFRetVal>& dowick) { ObservableType func(len); for (unsigned int k = 0; k < len; ++k) { func[k].resize(functionpoints); for (unsigned int j = 0; j < functionpoints; ++j) { const FPType s = j * delta_s; GFRetVal t1 = densitydensityCorrelation<Configuration>(dowick, k, s, DOWN, k, s, UP); //add to measurement func[k][j] = t1 * configuration.phase; } } this->add_bin(func); return; } /** A class for measuring the Conductance in an imaginary time simulation */ #include "conductance_grid.h" template <class Config, class Greensfunction> class Conductance : public Network_Cache<Config, typename Config::SignType> { public: typedef typename Config::Configuration Configuration; typedef typename Configuration::FPType FPType; typedef typename Config::SignType GFRetVal; typedef std::valarray<GFRetVal> Function; typedef GFRetVal ObservableType; Conductance(typename Config::Comm& n, const Parameters& params) throw() : Network_Cache<Config, ObservableType>(n, "Conductance"), len(params.N), functionpoints(params.functionpoints), delta_s(params.delta_s), beta(params.beta), alpha_max(sizeof(grid)/sizeof(Point2)), gamma(params.V*params.V*M_PI/params.W) { } void dryrun(DryRun<typename Configuration::value_type, GFRetVal>&) MTL_CONST_FUNCTION; /** @param configuration the configuration */ inline void evaluate(const Configuration&, const DoWick<typename Configuration::value_type, GFRetVal>&); private: const uint32_t& len; const uint32_t& functionpoints; const double delta_s; const FPType beta; const unsigned int alpha_max; const FPType gamma; }; template <class Configuration, class Greensfunction> void Conductance<Configuration, Greensfunction>::dryrun(DryRun<typename Configuration::value_type, GFRetVal>& func) { return; } template <class Configuration, class Greensfunction> void Conductance<Configuration, Greensfunction>::evaluate(const Configuration& configuration, const DoWick<typename Configuration::value_type, GFRetVal>& dowick) { ObservableType ret = 0.0; for (unsigned int alpha = 0; alpha < alpha_max; ++alpha) { const FPType omega_alpha = 1.0/(grid[alpha].gp*beta); const std::complex<FPType> gomega = Greensfunction::gomega(omega_alpha, UP); const FPType tiny = 0.00000001;//same as in the greensfunctions const FPType h = pow(tiny, 1.0/3.0) * 0.707 * omega_alpha;//an optimal choice of h for the symmetric derivative, derived for a function that behaves as 1/x... see NR 5.7. the choice of x_c= 0.707*x is reasonable as we always evaluate the function for x > 0 std::complex<FPType> gomegaplush = Greensfunction::gomega(omega_alpha + h, UP); std::complex<FPType> gomegaminush = Greensfunction::gomega(omega_alpha - h, UP); std::complex<FPType> derivative = (gomegaplush - gomegaminush)/(static_cast<FPType>(2.0)*h); std::complex<FPType> sum1 = 0.0; std::complex<FPType> sum2 = 0.0; for (unsigned int r = 0; r < configuration.size(); ++r) { for (unsigned int s = 0; s < configuration.size(); ++s) { std::complex<FPType> expfac = std::exp(std::complex<FPType>(0.0, omega_alpha * (configuration[r].tau - configuration[s].tau))); GFRetVal mat = configuration.matcont.up(r,s); sum1 += mat*expfac; sum2 += mat*expfac * std::complex<FPType>(0.0, (configuration[r].tau - configuration[s].tau)); } } std::complex<FPType> factor = gomega / beta; std::complex<FPType> dga = derivative - static_cast<FPType>(2.0) * factor * derivative * sum1 - factor *gomega * sum2; ret += imag(dga) * grid[alpha].weight; } this->add_bin(-configuration.phase * 2.0*gamma*ret/beta); } /** A class for measuring the time dependency of the correlated part of the Spin-Spin-Correlation */ template <class Config> class SpinSpinCorrelatedPart_Y : public Network_Cache<Config, std::valarray<std::valarray<typename Config::SignType> > > { public: typedef typename Config::Configuration Configuration; typedef typename Configuration::FPType FPType; typedef typename Config::Comm Net; typedef typename Config::SignType GFRetVal; typedef std::valarray<GFRetVal> Function; typedef std::valarray<Function> ObservableType;///< Spin-Spin-Correlations are spatially resolved time-dependent observables /** The Constructor for the correlated part Spin-Spin-Correlation */ inline SpinSpinCorrelatedPart_Y(typename Config::Comm& n, const Parameters& params) throw() : Network_Cache<Config, ObservableType>(n, "SpinSpinCorrelatedPart_Y"), len(params.N), functionpoints(params.functionpoints), delta_s(params.delta_s) { } void dryrun(DryRun<typename Configuration::value_type, GFRetVal>&); /** this determines the Spin-Spin-Correlation for a given order @param configuration the configuration */ inline void evaluate(const Configuration&, const DoWick<typename Configuration::value_type, GFRetVal>&); private: const uint32_t& len; const uint32_t& functionpoints; const double delta_s; }; template <class Config> void SpinSpinCorrelatedPart_Y<Config>::dryrun(DryRun<typename Configuration::value_type, GFRetVal>& func) { typedef typename Configuration::value_type Vertex; for (unsigned int j = 0; j < functionpoints; ++j)//for every time-slice { for (unsigned int k = 0; k < len; ++k)//for each site { const FPType s = j * delta_s; genericTwoParticleGreensfunction_dry<Configuration>(func, Vertex(k, s, UP), Vertex(k, s, DOWN), Vertex(0, 0, UP), Vertex(0, 0, DOWN)); genericTwoParticleGreensfunction_dry<Configuration>(func, Vertex(k, s, DOWN), Vertex(k, s, UP), Vertex(0, 0, UP), Vertex(0, 0, DOWN)); genericTwoParticleGreensfunction_dry<Configuration>(func, Vertex(k, s, UP), Vertex(k, s, DOWN), Vertex(0, 0, DOWN), Vertex(0, 0, UP)); genericTwoParticleGreensfunction_dry<Configuration>(func, Vertex(k, s, DOWN), Vertex(k, s, UP), Vertex(0, 0, DOWN), Vertex(0, 0, UP)); func(Vertex(k, s, UP), Vertex(k, s, DOWN)); func(Vertex(k, s, DOWN), Vertex(k, s, UP)); func(Vertex(0, 0, UP), Vertex(0, 0, DOWN)); func(Vertex(0, 0, DOWN), Vertex(0, 0, UP)); } } return; } template <class Config> void SpinSpinCorrelatedPart_Y<Config>::evaluate(const Configuration& configuration, const DoWick<typename Configuration::value_type, GFRetVal>& dowick) { typedef typename Configuration::value_type Vertex; ObservableType func(len); for (unsigned int k = 0; k < len; ++k) { func[k].resize(functionpoints); for (unsigned int j = 0; j < functionpoints; ++j) { const FPType s = j * delta_s; GFRetVal retval = -(genericTwoParticleGreensfunction<Configuration>(dowick, Vertex(k, s, UP), Vertex(k, s, DOWN), Vertex(0, 0, UP), Vertex(0, 0, DOWN)) -genericTwoParticleGreensfunction<Configuration>(dowick, Vertex(k, s, DOWN), Vertex(k, s, UP), Vertex(0, 0, UP), Vertex(0, 0, DOWN)) -genericTwoParticleGreensfunction<Configuration>(dowick, Vertex(k, s, UP), Vertex(k, s, DOWN), Vertex(0, 0, DOWN), Vertex(0, 0, UP)) +genericTwoParticleGreensfunction<Configuration>(dowick, Vertex(k, s, DOWN), Vertex(k, s, UP), Vertex(0, 0, DOWN), Vertex(0, 0, UP))) +/*subtract correlated part, additional minus sign due to i^2*/ (dowick(Vertex(k, s, UP), Vertex(k, s, DOWN))- dowick(Vertex(k, s, DOWN), Vertex(k, s, UP)))* (dowick(Vertex(0, 0, UP), Vertex(0, 0, DOWN))- dowick(Vertex(0, 0, DOWN), Vertex(0, 0, UP))); //add to measurement func[k][j] = retval * configuration.phase/ static_cast<FPType>(4.0); } } this->add_bin(func); return; } /** A class for measuring the time dependency of the correlated part of the Spin-Spin-Correlation */ template <class Config> class SpinSpinCorrelatedPart_X : public Network_Cache<Config, std::valarray<std::valarray<typename Config::SignType> > > { public: typedef typename Config::Configuration Configuration; typedef typename Configuration::FPType FPType; typedef typename Config::Comm Net; typedef typename Config::SignType GFRetVal; typedef std::valarray<GFRetVal> Function; typedef std::valarray<Function> ObservableType;///< Spin-Spin-Correlations are spatially resolved time-dependent observables /** The Constructor for the correlated part Spin-Spin-Correlation */ inline SpinSpinCorrelatedPart_X(typename Config::Comm& n, const Parameters& params) throw() : Network_Cache<Config, ObservableType>(n, "SpinSpinCorrelatedPart_X"), len(params.N), functionpoints(params.functionpoints), delta_s(params.delta_s) { } void dryrun(DryRun<typename Configuration::value_type, GFRetVal>&); /** this determines the Spin-Spin-Correlation for a given order @param configuration the configuration */ inline void evaluate(const Configuration&, const DoWick<typename Configuration::value_type, GFRetVal>&); private: const uint32_t& len; const uint32_t& functionpoints; const double delta_s; }; template <class Config> void SpinSpinCorrelatedPart_X<Config>::dryrun(DryRun<typename Configuration::value_type, GFRetVal>& func) { typedef typename Configuration::value_type Vertex; for (unsigned int j = 0; j < functionpoints; ++j)//for every time-slice { for (unsigned int k = 0; k < len; ++k)//for each site { const FPType s = j * delta_s; genericTwoParticleGreensfunction_dry<Configuration>(func, Vertex(k, s, UP), Vertex(k, s, DOWN), Vertex(0, 0, UP), Vertex(0, 0, DOWN)); genericTwoParticleGreensfunction_dry<Configuration>(func, Vertex(k, s, DOWN), Vertex(k, s, UP), Vertex(0, 0, UP), Vertex(0, 0, DOWN)); genericTwoParticleGreensfunction_dry<Configuration>(func, Vertex(k, s, UP), Vertex(k, s, DOWN), Vertex(0, 0, DOWN), Vertex(0, 0, UP)); genericTwoParticleGreensfunction_dry<Configuration>(func, Vertex(k, s, DOWN), Vertex(k, s, UP), Vertex(0, 0, DOWN), Vertex(0, 0, UP)); func(Vertex(k, s, UP), Vertex(k, s, DOWN)); func(Vertex(k, s, DOWN), Vertex(k, s, UP)); func(Vertex(0, 0, UP), Vertex(0, 0, DOWN)); func(Vertex(0, 0, DOWN), Vertex(0, 0, UP)); } } return; } template <class Config> void SpinSpinCorrelatedPart_X<Config>::evaluate(const Configuration& configuration, const DoWick<typename Configuration::value_type, GFRetVal>& dowick) { typedef typename Configuration::value_type Vertex; ObservableType func(len); for (unsigned int k = 0; k < len; ++k) { func[k].resize(functionpoints); for (unsigned int j = 0; j < functionpoints; ++j) { const FPType s = j * delta_s; /* std::cout<<genericTwoParticleGreensfunction<Configuration>(dowick, Vertex(k, s, UP), Vertex(k, s, DOWN), Vertex(0, 0, UP), Vertex(0, 0, DOWN)) <<" "<<genericTwoParticleGreensfunction<Configuration>(dowick, Vertex(k, s, DOWN), Vertex(k, s, UP), Vertex(0, 0, UP), Vertex(0, 0, DOWN))<<" " <<genericTwoParticleGreensfunction<Configuration>(dowick, Vertex(k, s, UP), Vertex(k, s, DOWN), Vertex(0, 0, DOWN), Vertex(0, 0, UP))<<" " <<genericTwoParticleGreensfunction<Configuration>(dowick, Vertex(k, s, DOWN), Vertex(k, s, UP), Vertex(0, 0, DOWN), Vertex(0, 0, UP))<<std::endl;*/ //simplified measurement in case of spin-diagonal measurement. GFRetVal retval = dowick(Vertex(k,s,UP), Vertex(k,0,UP)) * dowick(Vertex(k,0,DOWN), Vertex(k, s, DOWN)) + dowick(Vertex(k, s, DOWN), Vertex(k, 0, DOWN)) * dowick(Vertex(k, 0, UP), Vertex(k, s, UP)) /*( genericTwoParticleGreensfunction<Configuration>(dowick, Vertex(k, s, UP), Vertex(k, s, DOWN), Vertex(0, 0, UP), Vertex(0, 0, DOWN)) +genericTwoParticleGreensfunction<Configuration>(dowick, Vertex(k, s, DOWN), Vertex(k, s, UP), Vertex(0, 0, UP), Vertex(0, 0, DOWN)) +genericTwoParticleGreensfunction<Configuration>(dowick, Vertex(k, s, UP), Vertex(k, s, DOWN), Vertex(0, 0, DOWN), Vertex(0, 0, UP)) +genericTwoParticleGreensfunction<Configuration>(dowick, Vertex(k, s, DOWN), Vertex(k, s, UP), Vertex(0, 0, DOWN), Vertex(0, 0, UP)) )*/ //subtract correlated part /* -(dowick(Vertex(k, s, UP), Vertex(k, s, DOWN))+ dowick(Vertex(k, s, DOWN), Vertex(k, s, UP)))* (dowick(Vertex(0, 0, UP), Vertex(0, 0, DOWN))+ dowick(Vertex(0, 0, DOWN), Vertex(0, 0, UP)))*/; //add to measurement // std::cout<<retval<<std::endl; func[k][j] = retval * configuration.phase/ static_cast<FPType>(4.0); } } this->add_bin(func); return; } /** A class for measuring the time dependency of the correlated part of the Spin-Spin-Correlation */ template <class Config> class ImaginarySpinSpinCorrelation_Z : public Network_Cache<Config, std::valarray<std::valarray<typename Config::SignType> > > { public: typedef typename Config::Configuration Configuration; typedef typename Configuration::FPType FPType; typedef typename Config::Comm Net; typedef typename Config::SignType GFRetVal; typedef std::valarray<GFRetVal> Function; typedef std::valarray<Function> ObservableType;///< Spin-Spin-Correlations are spatially resolved time-dependent observables /** The Constructor for the correlated part Spin-Spin-Correlation */ inline ImaginarySpinSpinCorrelation_Z(typename Config::Comm& n, const Parameters& params) throw() : Network_Cache<Config, ObservableType>(n, "ImaginarySpinSpinCorrelation_Z"), len(params.N), functionpoints(params.functionpoints), delta_s(params.delta_s) { } void dryrun(DryRun<typename Configuration::value_type, GFRetVal>&); /** this determines the Spin-Spin-Correlation for a given order @param configuration the configuration */ inline void evaluate(const Configuration&, const DoWick<typename Configuration::value_type, GFRetVal>&); private: const uint32_t& len; const uint32_t& functionpoints; const double delta_s; }; template <class Config> void ImaginarySpinSpinCorrelation_Z<Config>::dryrun(DryRun<typename Configuration::value_type, GFRetVal>& func) { typedef typename Configuration::value_type Vertex; for (unsigned int j = 0; j < functionpoints; ++j)//for every time-slice { for (unsigned int k = 0; k < len; ++k)//for each site { const FPType s = j * delta_s; densitydensityCorrelation_dry<Configuration>(func, k, s, UP, 0, 0, UP); densitydensityCorrelation_dry<Configuration>(func, k, s, DOWN, 0, 0, DOWN); densitydensityCorrelation_dry<Configuration>(func, k, s, UP, 0, 0, DOWN); densitydensityCorrelation_dry<Configuration>(func, k, s, DOWN, 0, 0, UP); } } return; } template <class Config> void ImaginarySpinSpinCorrelation_Z<Config>::evaluate(const Configuration& configuration, const DoWick<typename Configuration::value_type, GFRetVal>& dowick) { typedef typename Configuration::value_type Vertex; ObservableType func(len); for (unsigned int k = 0; k < len; ++k) { func[k].resize(functionpoints); for (unsigned int j = 0; j < functionpoints; ++j) { const FPType s = j * delta_s; GFRetVal retval = densitydensityCorrelation<Configuration>(dowick, k, s, UP, 0, 0, UP) + densitydensityCorrelation<Configuration>(dowick, k, s, DOWN, 0, 0, DOWN) - densitydensityCorrelation<Configuration>(dowick, k, s, UP, 0, 0, DOWN) - densitydensityCorrelation<Configuration>(dowick, k, s, DOWN, 0, 0, UP); //add to measurement func[k][j] = retval * configuration.phase/ static_cast<FPType>(4.0); } } this->add_bin(func); return; } /** The Spin-Susceptiblity in X direction */ template <class Config, class Greensfunction> class SpinSusceptibility_X : public Network_Cache<Config, typename Greensfunction::GOmegaRetType> { public: typedef typename Config::Configuration Configuration; typedef typename Configuration::FPType FPType; typedef typename Config::Comm Net; typedef typename Config::SignType GFRetVal; typedef typename Greensfunction::GOmegaRetType GOmegaRetType; typedef GOmegaRetType ObservableType; /** */ inline SpinSusceptibility_X(typename Config::Comm& n, const Parameters& params) throw() : Network_Cache<Config, ObservableType>(n, "SpinSusceptibility_X"), len(params.N), beta(params.beta) { myf = new GOmegaRetType*[8]; delta_tau = beta/points; const uint tablesize = 2 * points; for (uint k = 0; k < 8; ++k) { myf[k] = new GOmegaRetType[tablesize]; memset(myf[k], 0, tablesize * sizeof(GOmegaRetType)); } for (uint n = 0; n < points; ++n) { FPType omegan = M_PI/beta*(2*n+1); for (int s = 0; s < 8; ++s) { SPINS sigma = (s>>2&1? DOWN: UP); SPINS sigma_r = (s>>1&1? DOWN: UP); SPINS sigma_s = (s&1? DOWN: UP); typename Greensfunction::Vertex v1; typename Greensfunction::Vertex v2; v1.spin = sigma_r; v2.spin = !sigma; GOmegaRetType goma = Greensfunction::gomega(omegan, v1, v2); GOmegaRetType gomam = Greensfunction::gomega(-omegan, v1, v2); v1.spin = sigma; v2.spin = sigma_s; GOmegaRetType gomb = Greensfunction::gomega(omegan, v1, v2); GOmegaRetType gombm = Greensfunction::gomega(-omegan, v1, v2); for (uint k = 0; k < points; ++k) { FPType tau = k*delta_tau; std::complex<FPType> expt = exp(std::complex<FPType>(0.0, omegan * tau)); std::complex<FPType> expmt = std::conj(expt); accessphi(sigma, sigma_r, sigma_s, k) += goma * gomb * expmt + gomam*gombm*expt; accessphi(sigma, sigma_r, sigma_s, points + k) += goma * gomb * expt + gomam*gombm*expmt; } } } for (uint s = 0; s < 8; ++s) for (uint k = 0; k < tablesize; ++k) myf[s][k] /= beta; } void dryrun(DryRun<typename Configuration::value_type, GFRetVal>&); /** this determines the Spin-Susceptiblity for a given order @param configuration the configuration */ inline void evaluate(const Configuration&, const DoWick<typename Configuration::value_type, GFRetVal>&); private: #if defined(__GXX_EXPERIMENTAL_CXX0X__) && (GCC_VERSION > GCC_VER(4,5,0)) static constexpr uint points = 1000; #else static const uint points = 1000; #endif const uint32_t& len; FPType beta; FPType delta_tau; GOmegaRetType** myf; GOmegaRetType& accessphi(SPINS sigma, SPINS sigma_r, SPINS sigma_s, uint tau_idx) { return myf[ (sigma == UP ? 0: 4) + (sigma_r == UP ? 0: 2) + (sigma_s == UP ? 0 : 1) ][tau_idx]; } GOmegaRetType contrib(SPINS sigma, SPINS sigmaprime, const Configuration& config, const DoWick<typename Configuration::value_type, GFRetVal>& dowick) { typename Greensfunction::Vertex v1; v1.spin = sigmaprime; v1.tau = 0; typename Greensfunction::Vertex v2; v2.spin = !sigmaprime; v2.tau = 0; GOmegaRetType sum1 = dowick(v1, v2); v1.spin = sigma; v2.spin = !sigma; GFRetVal gf1 = beta * Greensfunction::eval(v1, v2); GOmegaRetType suma = 0.0; for (uint r = 0; r < config.size(); ++r) for (uint s = 0; s < config.size(); ++s) { FPType taurs = config[r].tau - config[s].tau; uint tau_idx = 0; if (taurs < 0) { tau_idx += points; taurs = -taurs; } tau_idx += static_cast<uint>(trunc(taurs/delta_tau)); suma += config.matcont(r, s, UP, UP) * accessphi(sigma, UP, UP, tau_idx); suma += config.matcont(r, s, DOWN, UP) * accessphi(sigma, DOWN, UP, tau_idx); suma += config.matcont(r, s, UP, DOWN) * accessphi(sigma, UP, DOWN, tau_idx); suma += config.matcont(r, s, DOWN, DOWN) * accessphi(sigma, DOWN, DOWN, tau_idx); } sum1 *= (GOmegaRetType(gf1) - suma); GOmegaRetType sum2 = accessphi(sigma, sigmaprime, !sigmaprime, 0); uint twosize = static_cast<unsigned int>(2 * config.size()); typename Configuration::MatConf::MatType psi(1, twosize); for (uint k = 0; k < config.size(); ++k) { v1.tau = config[k].tau; v2.tau = 0; v1.spin = UP; v2.spin = !sigmaprime; psi(0,2*k) = Greensfunction::eval(v1, v2); v1.spin = DOWN; psi(0, 2*k + 1) = Greensfunction::eval(v1, v2); } config.matcont.multiplyVectorbyConfiguration_right(psi); // psi = psi * config.matcont.mat; GOmegaRetType sum3 = 0.0; for (uint k = 0; k < config.size(); ++k) { FPType tau = config[k].tau; uint tau_idx = points + static_cast<uint>(trunc(tau/delta_tau));/*see formula. that way we take the negative sign into consideration*/ sum3 += psi(0, 2*k) * accessphi(sigma, UP, sigmaprime, tau_idx); sum3 += psi(0, 2*k + 1) * accessphi(sigma, DOWN, sigmaprime, tau_idx); } GOmegaRetType sum4 = 0.0; typename Configuration::MatConf::MatType chi(twosize, 1); for (uint k = 0; k < static_cast<uint>(config.size()); ++k) { v1.tau = 0; v2.tau = config[k].tau; v2.spin = UP; v1.spin = sigmaprime; chi(2*k, 0) = Greensfunction::eval(v1, v2); v2.spin = DOWN; chi(2*k + 1, 0) = Greensfunction::eval(v1, v2); } config.matcont.multiplyVectorbyConfiguration_left(chi); // chi = config.matcont.mat * chi; for (uint k = 0; k < static_cast<uint>(config.size()); ++k) { FPType tau = config[k].tau; uint tau_idx = static_cast<uint>(trunc(tau/delta_tau));//tau should be positive being straight from a vertex sum4 += chi(2*k, 0) * accessphi(sigma, !sigmaprime, UP, tau_idx); sum4 += chi(2*k + 1, 0) * accessphi(sigma, !sigmaprime, DOWN, tau_idx); } GOmegaRetType sum5 = 0;//we can reuse psi and chi for (uint r = 0; r < static_cast<uint>(config.size()); ++r) for (uint s = 0; s < static_cast<uint>(config.size()); ++s) { FPType taurs = config[s].tau - config[r].tau; uint tau_idx = 0; if (taurs < 0) { tau_idx += points; taurs = -taurs; } tau_idx += static_cast<uint>(trunc(taurs/delta_tau)); sum5 += psi(0, 2*r) * chi(2*s, 0)*accessphi(sigma, UP, UP, tau_idx); sum5 += psi(0, 2*r+1) * chi(2*s, 0)*accessphi(sigma, DOWN, UP, tau_idx); sum5 += psi(0, 2*r) * chi(2*s+1, 0)*accessphi(sigma, UP, DOWN, tau_idx); sum5 += psi(0, 2*r+1) * chi(2*s+1, 0)*accessphi(sigma, DOWN, DOWN, tau_idx); } return sum1 - sum2 /*+*/- sum3 /*+*/- sum4 - sum5; } void contrib_dry(SPINS sigma, SPINS sigmaprime, DryRun<typename Configuration::value_type, GFRetVal>& func) { typename Greensfunction::Vertex v1; v1.spin = sigmaprime; v1.tau = 0; typename Greensfunction::Vertex v2; v2.spin = !sigmaprime; v2.tau = 0; func(v1, v2); } }; template <class Config, class Greensfunction> void SpinSusceptibility_X<Config, Greensfunction>::dryrun(DryRun<typename Configuration::value_type, GFRetVal>& func) { contrib_dry(UP, UP, func); contrib_dry(UP, DOWN, func); contrib_dry(DOWN, UP, func); contrib_dry(DOWN, DOWN, func); return; } template <class Config, class Greensfunction> void SpinSusceptibility_X<Config, Greensfunction>::evaluate(const Configuration& configuration, const DoWick<typename Configuration::value_type, GFRetVal>& dowick) { GOmegaRetType retval = contrib(UP, UP, configuration, dowick) + contrib(UP, DOWN, configuration, dowick) + contrib(DOWN, UP, configuration, dowick) + contrib(DOWN, DOWN, configuration, dowick); this->add_bin(retval/ 4.0); return; } /** The Spin-Susceptiblity in Z direction */ template <class Config, class Greensfunction> class SpinSusceptibility_Z : public Network_Cache<Config, typename Greensfunction::GOmegaRetType> { public: typedef typename Config::Configuration Configuration; typedef typename Configuration::FPType FPType; typedef typename Config::Comm Net; typedef typename Config::SignType GFRetVal; typedef std::valarray<GFRetVal> Function; typedef typename Greensfunction::GOmegaRetType GOmegaRetType; typedef GOmegaRetType ObservableType; /** */ inline SpinSusceptibility_Z(typename Config::Comm& n, const Parameters& params) throw() : Network_Cache<Config, ObservableType>(n, "SpinSusceptibility_Z"), len(params.N), beta(params.beta) { myf = new GOmegaRetType*[8]; delta_tau = beta/points; const uint tablesize = 2 * points; for (uint k = 0; k < 8; ++k) { myf[k] = new GOmegaRetType[tablesize]; memset(myf[k], 0, tablesize * sizeof(GOmegaRetType)); } for (uint n = 0; n < points; ++n) { FPType omegan = M_PI/beta*(2*n+1); for (int s = 0; s < 8; ++s) { SPINS sigma = (s>>2&1? DOWN: UP); SPINS sigma_r = (s>>1&1? DOWN: UP); SPINS sigma_s = (s&1? DOWN: UP); typename Greensfunction::Vertex v1; typename Greensfunction::Vertex v2; v1.spin = sigma_r; v2.spin = sigma; GOmegaRetType goma = Greensfunction::gomega(omegan, v1, v2); GOmegaRetType gomam = Greensfunction::gomega(-omegan, v1, v2); v1.spin = sigma; v2.spin = sigma_s; GOmegaRetType gomb = Greensfunction::gomega(omegan, v1, v2); GOmegaRetType gombm = Greensfunction::gomega(-omegan, v1, v2); for (uint k = 0; k < points; ++k) { FPType tau = k*delta_tau; std::complex<FPType> expt = exp(std::complex<FPType>(0.0, omegan * tau)); std::complex<FPType> expmt = std::conj(expt); accessphi(sigma, sigma_r, sigma_s, k) += goma * gomb * expmt + gomam*gombm*expt; accessphi(sigma, sigma_r, sigma_s, points + k) += goma * gomb * expt + gomam*gombm*expmt; } } } for (uint s = 0; s < 8; ++s) for (uint k = 0; k < tablesize; ++k) myf[s][k] /= beta; } void dryrun(DryRun<typename Configuration::value_type, GFRetVal>&); /** This determines the Spin-Susceptiblity for a given order @param configuration the configuration */ inline void evaluate(const Configuration&, const DoWick<typename Configuration::value_type, GFRetVal>&); private: #if defined(__GXX_EXPERIMENTAL_CXX0X__) && (GCC_VERSION > GCC_VER(4,5,0)) static constexpr uint points = 1000; #else static const uint points = 1000; #endif const uint32_t& len; FPType beta; FPType delta_tau; GOmegaRetType** myf; GOmegaRetType& accessphi(SPINS sigma, SPINS sigma_r, SPINS sigma_s, int tau_idx) { return myf[ (sigma == UP ? 0: 4) + (sigma_r == UP ? 0: 2) + (sigma_s == UP ? 0 : 1) ][tau_idx]; } GOmegaRetType contrib(const SPINS sigma, const SPINS sigmaprime, const Configuration& config, const DoWick<typename Configuration::value_type, GFRetVal>& dowick) { typename Greensfunction::Vertex v1; v1.spin = sigmaprime; v1.tau = 0; typename Greensfunction::Vertex v2; v2.spin = sigmaprime; v2.tau = 0; GOmegaRetType sum1 = dowick(v1, v2); v1.spin = sigma; v2.spin = sigma; GFRetVal gf1 = beta * Greensfunction::eval(v1, v2); GOmegaRetType suma = 0.0; for (uint r = 0; r < config.size(); ++r) for (uint s = 0; s < config.size(); ++s) { FPType taurs = config[r].tau - config[s].tau; int tau_idx = 0; if (taurs < 0) { tau_idx += points; taurs = -taurs; } tau_idx += static_cast<int>(trunc(taurs/delta_tau)); suma += config.matcont(r, s, UP, UP) * accessphi(sigma, UP, UP, tau_idx); suma += config.matcont(r, s, DOWN, UP) * accessphi(sigma, DOWN, UP, tau_idx); suma += config.matcont(r, s, UP, DOWN) * accessphi(sigma, UP, DOWN, tau_idx); suma += config.matcont(r, s, DOWN, DOWN) * accessphi(sigma, DOWN, DOWN, tau_idx); } sum1 *= (gf1 - suma); GOmegaRetType sum2 = accessphi(sigma, sigmaprime, sigmaprime, 0); typename Configuration::MatConf::MatType psi(1, static_cast<unsigned int>(2 * config.size())); for (uint k = 0; k < config.size(); ++k) { v1.tau = config[k].tau; v2.tau = 0; v1.spin = UP; v2.spin = sigmaprime; psi(0,2*k) = Greensfunction::eval(v1, v2); v1.spin = DOWN; psi(0, 2*k + 1) = Greensfunction::eval(v1, v2); } config.matcont.multiplyVectorbyConfiguration_right(psi); // psi = psi * config.matcont.mat; GOmegaRetType sum3 = 0.0; for (uint k = 0; k < config.size(); ++k) { FPType tau = config[k].tau; int tau_idx = points + static_cast<int>(trunc(tau/delta_tau));/*see formula. that way we take the negative sign into consideration*/ sum3 += psi(0, 2*k) * accessphi(sigma, UP, sigmaprime, tau_idx); sum3 += psi(0, 2*k + 1) * accessphi(sigma, DOWN, sigmaprime, tau_idx); } GOmegaRetType sum4 = 0.0; typename Configuration::MatConf::MatType chi(static_cast<unsigned int>(2 * config.size()), 1); for (uint k = 0; k < config.size(); ++k) { v1.tau = 0; v2.tau = config[k].tau; v2.spin = UP; v1.spin = sigmaprime; chi(2*k, 0) = Greensfunction::eval(v1, v2); v2.spin = DOWN; chi(2*k + 1, 0) = Greensfunction::eval(v1, v2); } config.matcont.multiplyVectorbyConfiguration_left(chi); // chi = config.matcont.mat * chi; for (uint k = 0; k < static_cast<uint>(config.size()); ++k) { FPType tau = config[k].tau; int tau_idx = static_cast<int>(trunc(tau/delta_tau));//tau should be positive being straight from a vertex sum4 += chi(2*k, 0) * accessphi(sigma, sigmaprime, UP, tau_idx); sum4 += chi(2*k + 1, 0) * accessphi(sigma, sigmaprime, DOWN, tau_idx); } GOmegaRetType sum5 = 0;//we can reuse psi and chi for (uint r = 0; r < static_cast<uint>(config.size()); ++r) for (uint s = 0; s < static_cast<uint>(config.size()); ++s) { FPType taurs = config[s].tau - config[r].tau; int tau_idx = 0; if (taurs < 0) { tau_idx += points; taurs = -taurs; } tau_idx += static_cast<int>(trunc(taurs/delta_tau)); sum5 += psi(0, 2*r) * chi(2*s, 0)*accessphi(sigma, UP, UP, tau_idx); sum5 += psi(0, 2*r+1) * chi(2*s, 0)*accessphi(sigma, DOWN, UP, tau_idx); sum5 += psi(0, 2*r) * chi(2*s+1, 0)*accessphi(sigma, UP, DOWN, tau_idx); sum5 += psi(0, 2*r+1) * chi(2*s+1, 0)*accessphi(sigma, DOWN, DOWN, tau_idx); } return sum1 - sum2 - sum3 - sum4 - sum5;//although Davids thesis states this formula differently careful testing reveals this choice of signs(with sum 3 and sum4 negative) to be the right one. Note that the signs of David's thesis can be reestablished by giving psi and chi an additional sign, or by exchanging the order in which the vertices are evaluated. This shouldn't change the sign of sum5 since there's a product of psi and chi and hence any sign cancels. } void contrib_dry(SPINS sigma, SPINS sigmaprime, DryRun<typename Configuration::value_type, GFRetVal>& func) {//yes, the only thing that we don't derive from tables only depends on sigmaprime typename Greensfunction::Vertex v1; v1.spin = sigmaprime; v1.tau = 0; func(v1, v1); } }; template <class Config, class Greensfunction> void SpinSusceptibility_Z<Config, Greensfunction>::dryrun(DryRun<typename Configuration::value_type, GFRetVal>& func) { contrib_dry(UP, UP, func); contrib_dry(UP, DOWN, func); contrib_dry(DOWN, UP, func); contrib_dry(DOWN, DOWN, func); return; } template <class Config, class Greensfunction> void SpinSusceptibility_Z<Config, Greensfunction>::evaluate(const Configuration& configuration, const DoWick<typename Configuration::value_type, GFRetVal>& dowick) { GOmegaRetType retval = contrib(UP, UP, configuration, dowick) - contrib(UP, DOWN, configuration, dowick) - contrib(DOWN, UP, configuration, dowick) + contrib(DOWN, DOWN, configuration, dowick); this->add_bin(retval/ 4.0); return; } template <typename FPType> struct Omegadata { FPType omega; FPType omegasq; FPType invomega; }; /** A class for measuring the local Greensfunctions on the impurity surrounding bath sites */ template <class Config, class GreensFunction, SPINS Spin> class LocalBathGreensfunctions : public Network_Cache<Config, std::valarray<std::valarray<typename Config::SignType> > > { public: typedef typename Config::Configuration Configuration; typedef typename Configuration::FPType FPType; typedef typename Config::SignType GFRetVal; typedef GreensFunction GF; typedef std::valarray<GFRetVal> Function; typedef std::valarray<Function> ObservableType;///<we pack all 80000 functions into a single valarray... /** The Constructor for the LocalBathGreensfunctions. Notice that in unmixed[] we tabulate <d^\dagger c> */ LocalBathGreensfunctions(typename Config::Comm& n, const Parameters& params) throw() : Network_Cache<Config, ObservableType>(n, "LocalBathGreensfunctions"), functionpoints(params.functionpoints), delta_s(params.delta_s), beta(params.beta), Ny(params.Nb*2), Nx(params.Nx), Nt(300 + 1), delta_beta(params.beta/static_cast<FPType>(Nt - 1)), Nw(4*Nt), Nyt(Nt * Ny), Nxyt(Nyt*params.Nx), functions(Ny*params.Nx) { #ifdef _OPENMP double start2 = omp_get_wtime(); #endif std::cout<<"Creating Local Bath Greensfunction"<<std::endl; const GOmegaData<FPType> *const updata = GF::gomegaup->data; const GOmegaData<FPType> *const downdata = GF::gomegadown->data; //let's set up the Q(r,n,omega_n) data Omegadata<FPType>* omega = new Omegadata<FPType>[Nw/2]; std::complex<FPType>* gup = new std::complex<FPType>[Nw]; std::complex<FPType>* gdown = new std::complex<FPType>[Nw]; for (int t = 0; t < Nw/2; ++t) { gup[2*t] = conj((*GF::gomegaup)(t)); gup[2*t + 1] = conj((*GF::gomegaup)( -t - 1)); gdown[2*t] = conj((*GF::gomegadown)(t)); gdown[2*t + 1] = conj((*GF::gomegadown)( -t - 1)); omega[t].omega = M_PI/params.beta*(2*t + 1); omega[t].omegasq = omega[t].omega*omega[t].omega; omega[t].invomega = 1.0/omega[t].omega; } FPType pref = GF::gethybridization() / std::sqrt(params.Nx); unmixeddata = new std::complex<float>[2*Nxyt]; //Since we have a simple, analytical expression for the tau dependence of the offset of the unmixed greensfunctions //we write that one out first to the unmixeddata array FPType* cosharrayup = new FPType[functions]; FPType* cosharraydown = new FPType[functions]; for(uint k = 0; k < params.Nx; ++k) for(uint m = 0; m < Ny; ++m) { cosharrayup[k*Ny + m] = 1.0/std::cosh(params.beta*updata[k*Ny + m].lambda/2.0)/2.0/static_cast<FPType>(params.Nx); cosharraydown[k*Ny + m] = 1.0/std::cosh(params.beta*downdata[k*Ny + m].lambda/2.0)/2.0/static_cast<FPType>(params.Nx); } #pragma omp parallel for for(uint n = 0; n < Ny; ++n) { FPType* tempup = new FPType[functions]; FPType* tempdown = new FPType[functions]; for(uint k = 0; k < params.Nx; ++k) for(uint m = 0; m < Ny; ++m) { tempup[k*Ny + m] = cosharrayup[k*Ny + m] * norm(updata[k*Ny + /*n*/m].evec[/*m*/n]); tempdown[k*Ny + m] = cosharraydown[k*Ny + m] * norm(downdata[k*Ny + /*n*/m].evec[/*m*/n]); } for(uint t = 0; t < Nt; ++t) { FPType ftup = 0.0; FPType ftdown = 0.0; FPType arg = t * delta_beta - params.beta/2.0; FPType cup = 0.0; FPType cdown = 0.0; for(uint k = 0; k < params.Nx; ++k)//being careful we employ Kahan summation for(uint m = 0; m < Ny; ++m) { FPType argup = tempup[k*Ny + m] * std::exp(updata[k*Ny + m].lambda*arg); FPType argdown = tempdown[k*Ny + m] * std::exp(downdata[k*Ny + m].lambda*arg); FPType y = argup - cup; FPType t = ftup + y; cup = (t - ftup) - y; ftup = t; y = argdown - cdown; t = ftdown + y; cdown = (t - ftdown) - y; ftdown = t; } for(uint r = 0; r < params.Nx; ++r) { (unmixeddata + n*Nt*params.Nx + r*Nt)[t] = static_cast<float>(ftup); (unmixeddata + Nxyt + n*Nt*params.Nx + r*Nt)[t] = static_cast<float>(ftdown); } } delete [] tempup; delete [] tempdown; } delete [] cosharrayup; delete [] cosharraydown; const uint Nxw = Nw*params.Nx; const std::complex<FPType> expNt = std::exp(std::complex<FPType>(0.0, -M_PI/(Nt-1))); const FPType normierungunmixed = 1.0/params.beta / params.Nx; const FPType normierungmixed = 1.0/params.beta / std::sqrt(params.Nx); mixeddata = new std::complex<float>[2*Nxyt]; std::ofstream gimag("gimag.txt"); //#pragma omp parallel for for (uint n = 0; n < Ny; ++n) { std::complex<FPType>* Qup = new std::complex<FPType>[Nxw]; std::complex<FPType>* Qdown = new std::complex<FPType>[Nxw]; std::complex<FPType>* funup = new std::complex<FPType>[Nxw]; std::complex<FPType>* fundown = new std::complex<FPType>[Nxw]; memset(funup, 0, Nxw*sizeof(std::complex<FPType>)); memset(fundown, 0, Nxw*sizeof(std::complex<FPType>)); // double start = omp_get_wtime(); for (uint k = 0; k < params.Nx; ++k) { for (uint m = 0; m < Ny; ++m) { std::complex<FPType> facup = conj(updata [k*Ny + m].u) * updata[k*Ny + m].evec[n]; std::complex<FPType> facdown = conj(downdata[k*Ny + m].u) * downdata[k*Ny + m].evec[n]; for (int omega_idx = 0; omega_idx < Nw/2; ++omega_idx) {//the layout of the frequencies is now (w_n, -w_n) , that is every negative frequency is stored next to its positive counterpart. //Hopefully this gives a better data locality funup[2*omega_idx*params.Nx + k] += facup/std::complex<FPType>(-updata[k*Ny + m].lambda, -omega[omega_idx].omega); funup[(2*omega_idx + 1)*params.Nx + k] += facup/std::complex<FPType>(-updata[k*Ny + m].lambda, omega[omega_idx].omega); fundown[2*omega_idx*params.Nx + k] += facdown/std::complex<FPType>(-downdata[k*Ny + m].lambda, -omega[omega_idx].omega); fundown[(2*omega_idx + 1)*params.Nx + k] += facdown/std::complex<FPType>(-downdata[k*Ny + m].lambda, omega[omega_idx].omega); } } } // std::cout<<"time now: "<<omp_get_wtime() - start<<std::endl; for (uint w = 0; w < Nw; ++w) { fourier1(reinterpret_cast<FPType*>(funup + w*params.Nx), params.Nx, 1); fourier1(reinterpret_cast<FPType*>(fundown + w*params.Nx), params.Nx, 1); //funup as well as fundown now contain Q(r, i omega) for a particular value of the orbital n for (uint r = 0; r < params.Nx; ++r) { funup[w*params.Nx + r] *= pref; // == Q. pref == V/sqrt(L) fundown[w*params.Nx + r] *= pref; // == Q. pref == V/sqrt(L) (Qup + r*Nw)[w] = funup[w*params.Nx + r];//norm(funup[w*params.Nx + r]); (Qdown + r*Nw)[w] = fundown[w*params.Nx + r];//norm(fundown[w*params.Nx + r]); // funup[w*params.Nx + r] = funup[w*params.Nx + r]; // fundown[w*params.Nx + r] = fundown[w*params.Nx + r]; } } /* for(uint r = 0; r < params.Nx; ++r) { for(uint w = 0; w < Nw/2; ++w) { gimag<<omega[w].omega<<" "<<real(funup[2*w*params.Nx + r]*gup[2*w])<<std::endl; } gimag<<"&"<<std::endl; }*/ for(uint r = 0; r < params.Nx; ++r) for(uint w = 0; w < Nw/2; ++w) { std::complex<FPType> temp = conj((Qup + r*Nw)[2*w]); (Qup + r*Nw)[2*w] *= conj((Qup + r*Nw)[2*w+1]); (Qup + r*Nw)[2*w+1] *= temp; temp = conj((Qdown + r*Nw)[2*w]); (Qdown + r*Nw)[2*w] *= conj((Qdown + r*Nw)[2*w+1]); (Qdown + r*Nw)[2*w+1] *= temp; } // std::cout<<"time now: "<<omp_get_wtime() - start<<std::endl; for (uint r = 0; r < params.Nx; ++r) { std::complex<FPType> expt = 1; for (uint t = 0; t < Nt; ++t)//here is the final Matsubara transform { std::complex<FPType> tempup = 0; std::complex<FPType> tempdown = 0; std::complex<FPType> tempupmixed = 0; std::complex<FPType> tempdownmixed = 0; FPType tau = t*delta_beta; std::complex<FPType> expiom = expt;//std::exp(tau * std::complex<FPType>(0.0, omega[0].omega)); std::complex<FPType> expfac = expiom * expiom; for (int omega_idx = 0; omega_idx < Nw/2; ++omega_idx) { std::complex<FPType> gupp = gup[2*omega_idx]; std::complex<FPType> gupm = gup[2*omega_idx + 1]; std::complex<FPType> gdownp = gdown[2*omega_idx]; std::complex<FPType> gdownm = gdown[2*omega_idx + 1]; std::complex<FPType> cexpiom = conj(expiom); tempup += cexpiom * (Qup + r * Nw)[2*omega_idx] * gupp + /*c*/expiom * (Qup + r * Nw)[2*omega_idx + 1] * gupm; tempdown += cexpiom * (Qdown + r * Nw)[2*omega_idx] * gdownp +/*c*/expiom*(Qdown + r * Nw)[2*omega_idx + 1] * gdownm; tempupmixed += cexpiom*(funup[(2*omega_idx)*params.Nx + r] * gupp) + /*c*/expiom * (funup[(2*omega_idx + 1)*params.Nx + r] * gupm); tempdownmixed += cexpiom*(fundown[(2*omega_idx)*params.Nx + r] * gdownp) + /*c*/expiom * (fundown[(2*omega_idx + 1)*params.Nx + r] * gdownm); expiom *= expfac; } // test<<tempupmixed*normierungmixed<<std::endl; //The unmixeddata has been debugged in comparison to a straightforward calculation from the real-space Hamiltonian (unmixeddata + n*Nt*params.Nx + r*Nt)[t] += tempup*normierungunmixed; (unmixeddata + Nxyt + n*Nt*params.Nx + r*Nt)[t] += tempdown*normierungunmixed; //the sign of the mixeddata is wrong. But since for now mixeddata is only accessed as some squared quantity it doesn't hurt. (mixeddata + n*Nt*params.Nx + r*Nt)[t] = tempupmixed*normierungmixed; (mixeddata + Nxyt + n*Nt*params.Nx + r*Nt)[t] = tempdownmixed*normierungmixed; expt *= expNt; } } delete [] funup; delete [] fundown; delete [] Qup; delete [] Qdown; } // exit(-1); #ifdef _OPENMP std::cout<<"Initialization took "<<omp_get_wtime() - start2<<" seconds"<<std::endl; #endif delete [] gup; delete [] gdown; delete [] omega; std::cout<<"Local Bath GreensFunction done"<<std::endl; } void dryrun(DryRun<typename Configuration::value_type, GFRetVal>&) {} /** this determines the LocalBathGreensfunctions for a given order @param configuration the configuration */ inline void evaluate(const Configuration&, const DoWick<typename Configuration::value_type, GFRetVal>&); private: const uint32_t& functionpoints; const FPType delta_s; const FPType beta; std::complex<float>* mixeddata;///< here we store <d^+ gamma>. We use floats to keep the memory footprint small std::complex<float>* unmixeddata;///< here we store <gamma^+ gamma> const uint Ny; const uint Nx; const uint Nt; const FPType delta_beta; const uint Nw; const uint Nyt; const uint Nxyt; const uint32_t functions; std::complex<FPType> accessmixed(uint r, uint n, SPINS spin, FPType tau1, FPType tau2 ) const { const FPType tiny = std::numeric_limits<FPType>::epsilon(); FPType delta_tau = tau1 - tau2; FPType sign = 1.0; std::complex<float>* dataptr = mixeddata; if (spin == DOWN) dataptr += Nxyt; dataptr = dataptr + n*Nt*Nx + r*Nt; if (std::abs(delta_tau) < tiny) { //return only the particle number return std::complex<FPType>(dataptr[0]); } if(delta_tau < 0) { sign = -1.0; delta_tau += beta; } FPType fptau_idx0; FPType rem = std::modf(delta_tau/delta_beta, &fptau_idx0);//round to the smaller index and determine how far we're of std::size_t tau_idx0 = lround(fptau_idx0); // std::cout<<"tau_0: "<<tau_idx0<<" "<<g[tau_idx0]<<std::endl; return std::complex<FPType>(lerp(float(rem), dataptr[tau_idx0], dataptr[tau_idx0 + 1]))*sign; } std::complex<FPType> accessunmixed(uint r, uint n, SPINS spin, FPType tau) const { std::complex<float>* dataptr = unmixeddata; if (spin == DOWN) dataptr += Nxyt; dataptr = dataptr + n*Nt*Nx + r*Nt; FPType fptau_idx0; FPType rem = std::modf(tau/delta_beta, &fptau_idx0);//round to the smaller index and determine how far we're of std::size_t tau_idx0 = static_cast<std::size_t>(lround(fptau_idx0)); // std::cout<<"tau_0: "<<tau_idx0<<" "<<g[tau_idx0]<<std::endl; //if(tau_idx0 == Nt) return dataptr[tau_idx0]; return std::complex<FPType>(lerp(float(rem), dataptr[tau_idx0], dataptr[tau_idx0 + 1])); } }; template <class Config, class GreensFunction, SPINS Spin> void LocalBathGreensfunctions<Config, GreensFunction, Spin>::evaluate(const Configuration& config, const DoWick<typename Configuration::value_type, GFRetVal>& dowick) { ObservableType func(functions); #pragma omp parallel for for (unsigned int k = 0; k < func.size(); ++k) { func[k].resize(functionpoints); uint n = k / Nx; uint r = k % Nx; for (unsigned int j = 0; j < functionpoints/*-1*/; ++j) { const FPType tau = j * delta_s; // uint unmixedidx = trunc(tau/delta_beta); GFRetVal t1 = accessunmixed(r, n, Spin, tau); // (unmixeddata + k*Nt + r*Nt)[unmixedidx];//access the up-sector GFRetVal t2 = 0; for (uint q = 0; q < config.size(); ++q) for (uint s = 0; s < config.size(); ++s) { if(Spin == UP) t2 += config.matcont.mat(2*q, 2*s) * accessmixed(r, n, UP, config[q].tau, 0) * conj(accessmixed(r, n, UP, tau, config[s].tau)); t2 += config.matcont.mat(2*q, 2*s + 1) * static_cast<FPType>(0.0);//For now disabled t2 += config.matcont.mat(2*q + 1, 2*s) * static_cast<FPType>(0.0);//For now disabled if(Spin == DOWN) t2 += config.matcont.mat(2*q + 1, 2*s + 1) * accessmixed(r, n, DOWN, config[q].tau, 0) * conj(accessmixed(r, n, DOWN, tau, config[s].tau)); } //add to measurement func[k][j] = (t1 - t2)* config.phase; } /* const FPType tau = beta-0.001; // uint unmixedidx = trunc(tau/delta_beta); GFRetVal t1 = accessunmixed(r, n, UP, tau); // (unmixeddata + k*Nt + r*Nt)[unmixedidx];//access the up-sector GFRetVal t2 = 0; for (uint r = 0; r < config.size(); ++r) for (uint s = 0; s < config.size(); ++s) { t2 += config.matcont.mat(2*r, 2*s) * accessmixed(r, n, UP, config[r].tau, 0) * conj(accessmixed(r, n, UP, tau, config[s].tau)); t2 += config.matcont.mat(2*r, 2*s + 1) * static_cast<FPType>(0.0);//For now disabled t2 += config.matcont.mat(2*r + 1, 2*s) * static_cast<FPType>(0.0);//For now disabled t2 += config.matcont.mat(2*r + 1, 2*s + 1) * accessmixed(r, n, DOWN, config[r].tau, 0) * conj(accessmixed(r, n, DOWN, tau, config[s].tau)); } //add to measurement func[k][functionpoints - 1] = (t1 - t2)* config.phase;*/ } this->add_bin(func); return; } /** A class for measuring the local Greensfunctions on the impurity surrounding bath sites, averaged over both spin sectors */ template <class Config, class GreensFunction> class LocalBathGreensfunctions_averaged : public Network_Cache<Config, std::valarray<std::valarray<typename Config::SignType> > > { public: typedef typename Config::Configuration Configuration; typedef typename Configuration::FPType FPType; typedef typename Config::SignType GFRetVal; typedef GreensFunction GF; typedef std::valarray<GFRetVal> Function; typedef std::valarray<Function> ObservableType;///<we pack all 80000 functions into a single valarray... /** The Constructor for the LocalBathGreensfunctions. Notice that in unmixed[] we tabulate <d^\dagger c> */ LocalBathGreensfunctions_averaged(typename Config::Comm& n, const Parameters& params) throw() : Network_Cache<Config, ObservableType>(n, "LocalBathGreensfunctions_averaged"), functionpoints(params.functionpoints), delta_s(params.delta_s), beta(params.beta), Ny(params.Nb*2), Nx(params.Nx), Nt(300 + 1), delta_beta(params.beta/static_cast<FPType>(Nt - 1)), Nw(4*Nt), Nyt(Nt * Ny), Nxyt(Nyt*params.Nx), functions(Ny*params.Nx) { #ifdef _OPENMP double start2 = omp_get_wtime(); #endif std::cout<<"Creating Local Bath Greensfunction(the averaged one...)"<<std::endl; const GOmegaData<FPType> *const updata = GF::gomegaup->data; const GOmegaData<FPType> *const downdata = GF::gomegadown->data; //let's set up the Q(r,n,omega_n) data Omegadata<FPType>* omega = new Omegadata<FPType>[Nw/2]; std::complex<FPType>* gup = new std::complex<FPType>[Nw]; std::complex<FPType>* gdown = new std::complex<FPType>[Nw]; for (int t = 0; t < Nw/2; ++t) { gup[2*t] = conj((*GF::gomegaup)(t)); gup[2*t + 1] = conj((*GF::gomegaup)( -t - 1)); gdown[2*t] = conj((*GF::gomegadown)(t)); gdown[2*t + 1] = conj((*GF::gomegadown)( -t - 1)); omega[t].omega = M_PI/params.beta*(2*t + 1); omega[t].omegasq = omega[t].omega*omega[t].omega; omega[t].invomega = 1.0/omega[t].omega; } FPType pref = GF::gethybridization() / std::sqrt(params.Nx); unmixeddata = new std::complex<float>[2*Nxyt]; //Since we have a simple, analytical expression for the tau dependence of the offset of the unmixed greensfunctions //we write that one out first to the unmixeddata array FPType* cosharrayup = new FPType[functions]; FPType* cosharraydown = new FPType[functions]; for(uint k = 0; k < params.Nx; ++k) for(uint m = 0; m < Ny; ++m) { cosharrayup[k*Ny + m] = 1.0/std::cosh(params.beta*updata[k*Ny + m].lambda/2.0)/2.0/static_cast<FPType>(params.Nx); cosharraydown[k*Ny + m] = 1.0/std::cosh(params.beta*downdata[k*Ny + m].lambda/2.0)/2.0/static_cast<FPType>(params.Nx); } #pragma omp parallel for for(uint n = 0; n < Ny; ++n) { FPType* tempup = new FPType[functions]; FPType* tempdown = new FPType[functions]; for(uint k = 0; k < params.Nx; ++k) for(uint m = 0; m < Ny; ++m) { tempup[k*Ny + m] = cosharrayup[k*Ny + m] * norm(updata[k*Ny + /*n*/m].evec[/*m*/n]); tempdown[k*Ny + m] = cosharraydown[k*Ny + m] * norm(downdata[k*Ny + /*n*/m].evec[/*m*/n]); } for(uint t = 0; t < Nt; ++t) { FPType ftup = 0.0; FPType ftdown = 0.0; FPType arg = t * delta_beta - params.beta/2.0; FPType cup = 0.0; FPType cdown = 0.0; for(uint k = 0; k < params.Nx; ++k)//being careful we employ Kahan summation for(uint m = 0; m < Ny; ++m) { FPType argup = tempup[k*Ny + m] * std::exp(updata[k*Ny + m].lambda*arg); FPType argdown = tempdown[k*Ny + m] * std::exp(downdata[k*Ny + m].lambda*arg); FPType y = argup - cup; FPType t = ftup + y; cup = (t - ftup) - y; ftup = t; y = argdown - cdown; t = ftdown + y; cdown = (t - ftdown) - y; ftdown = t; } for(uint r = 0; r < params.Nx; ++r) { (unmixeddata + n*Nt*params.Nx + r*Nt)[t] = static_cast<float>(ftup); (unmixeddata + Nxyt + n*Nt*params.Nx + r*Nt)[t] = static_cast<float>(ftdown); } } delete [] tempup; delete [] tempdown; } delete [] cosharrayup; delete [] cosharraydown; const uint Nxw = Nw*params.Nx; const std::complex<FPType> expNt = std::exp(std::complex<FPType>(0.0, -M_PI/(Nt-1))); const FPType normierungunmixed = 1.0/params.beta / params.Nx; const FPType normierungmixed = 1.0/params.beta / std::sqrt(params.Nx); mixeddata = new std::complex<float>[2*Nxyt]; #pragma omp parallel for for (uint n = 0; n < Ny; ++n) { std::complex<FPType>* Qup = new std::complex<FPType>[Nxw]; std::complex<FPType>* Qdown = new std::complex<FPType>[Nxw]; std::complex<FPType>* funup = new std::complex<FPType>[Nxw]; std::complex<FPType>* fundown = new std::complex<FPType>[Nxw]; memset(funup, 0, Nxw*sizeof(std::complex<FPType>)); memset(fundown, 0, Nxw*sizeof(std::complex<FPType>)); // double start = omp_get_wtime(); for (uint k = 0; k < params.Nx; ++k) { for (uint m = 0; m < Ny; ++m) { std::complex<FPType> facup = conj(updata [k*Ny + m].u) * updata[k*Ny + m].evec[n]; std::complex<FPType> facdown = conj(downdata[k*Ny + m].u) * downdata[k*Ny + m].evec[n]; for (int omega_idx = 0; omega_idx < Nw/2; ++omega_idx) {//the layout of the frequencies is now (w_n, -w_n) , that is every negative frequency is stored next to its positive counterpart. //Hopefully this gives a better data locality funup[2*omega_idx*params.Nx + k] += facup/std::complex<FPType>(-updata[k*Ny + m].lambda, -omega[omega_idx].omega); funup[(2*omega_idx + 1)*params.Nx + k] += facup/std::complex<FPType>(-updata[k*Ny + m].lambda, omega[omega_idx].omega); fundown[2*omega_idx*params.Nx + k] += facdown/std::complex<FPType>(-downdata[k*Ny + m].lambda, -omega[omega_idx].omega); fundown[(2*omega_idx + 1)*params.Nx + k] += facdown/std::complex<FPType>(-downdata[k*Ny + m].lambda, omega[omega_idx].omega); } } } // std::cout<<"time now: "<<omp_get_wtime() - start<<std::endl; for (uint w = 0; w < Nw; ++w) { fourier1(reinterpret_cast<FPType*>(funup + w*params.Nx), params.Nx, 1); fourier1(reinterpret_cast<FPType*>(fundown + w*params.Nx), params.Nx, 1); //funup as well as fundown now contain Q(r, i omega) for a particular value of the orbital n for (uint r = 0; r < params.Nx; ++r) { funup[w*params.Nx + r] *= pref; // == Q. pref == V/sqrt(L) fundown[w*params.Nx + r] *= pref; // == Q. pref == V/sqrt(L) (Qup + r*Nw)[w] = funup[w*params.Nx + r];//norm(funup[w*params.Nx + r]); (Qdown + r*Nw)[w] = fundown[w*params.Nx + r];//norm(fundown[w*params.Nx + r]); // funup[w*params.Nx + r] = funup[w*params.Nx + r]; // fundown[w*params.Nx + r] = fundown[w*params.Nx + r]; } } for(uint r = 0; r < params.Nx; ++r) for(uint w = 0; w < Nw/2; ++w) { std::complex<FPType> temp = conj((Qup + r*Nw)[2*w]); (Qup + r*Nw)[2*w] *= conj((Qup + r*Nw)[2*w+1]); (Qup + r*Nw)[2*w+1] *= temp; temp = conj((Qdown + r*Nw)[2*w]); (Qdown + r*Nw)[2*w] *= conj((Qdown + r*Nw)[2*w+1]); (Qdown + r*Nw)[2*w+1] *= temp; } // std::cout<<"time now: "<<omp_get_wtime() - start<<std::endl; for (uint r = 0; r < params.Nx; ++r) { std::complex<FPType> expt = 1; for (uint t = 0; t < Nt; ++t)//here is the final Matsubara transform { std::complex<FPType> tempup = 0; std::complex<FPType> tempdown = 0; std::complex<FPType> tempupmixed = 0; std::complex<FPType> tempdownmixed = 0; FPType tau = t*delta_beta; std::complex<FPType> expiom = expt;//std::exp(tau * std::complex<FPType>(0.0, omega[0].omega)); std::complex<FPType> expfac = expiom * expiom; for (int omega_idx = 0; omega_idx < Nw/2; ++omega_idx) { std::complex<FPType> gupp = gup[2*omega_idx]; std::complex<FPType> gupm = gup[2*omega_idx + 1]; std::complex<FPType> gdownp = gdown[2*omega_idx]; std::complex<FPType> gdownm = gdown[2*omega_idx + 1]; std::complex<FPType> cexpiom = conj(expiom); tempup += cexpiom * (Qup + r * Nw)[2*omega_idx] * gupp + /*c*/expiom * (Qup + r * Nw)[2*omega_idx + 1] * gupm; tempdown += cexpiom * (Qdown + r * Nw)[2*omega_idx] * gdownp +/*c*/expiom*(Qdown + r * Nw)[2*omega_idx + 1] * gdownm; tempupmixed += cexpiom*(funup[(2*omega_idx)*params.Nx + r] * gupp) + /*c*/expiom * (funup[(2*omega_idx + 1)*params.Nx + r] * gupm); tempdownmixed += cexpiom*(fundown[(2*omega_idx)*params.Nx + r] * gdownp) + /*c*/expiom * (fundown[(2*omega_idx + 1)*params.Nx + r] * gdownm); expiom *= expfac; } // test<<tempupmixed*normierungmixed<<std::endl; //The unmixeddata has been debugged in comparison to a straightforward calculation from the real-space Hamiltonian (unmixeddata + n*Nt*params.Nx + r*Nt)[t] += tempup*normierungunmixed; (unmixeddata + Nxyt + n*Nt*params.Nx + r*Nt)[t] += tempdown*normierungunmixed; //the sign of the mixeddata is wrong. But since for now mixeddata is only accessed as some squared quantity it doesn't hurt. (mixeddata + n*Nt*params.Nx + r*Nt)[t] = tempupmixed*normierungmixed; (mixeddata + Nxyt + n*Nt*params.Nx + r*Nt)[t] = tempdownmixed*normierungmixed; expt *= expNt; } } delete [] funup; delete [] fundown; delete [] Qup; delete [] Qdown; } #ifdef _OPENMP std::cout<<"Initialization took "<<omp_get_wtime() - start2<<" seconds"<<std::endl; #endif delete [] gup; delete [] gdown; delete [] omega; std::cout<<"Local Bath GreensFunction done"<<std::endl; } void dryrun(DryRun<typename Configuration::value_type, GFRetVal>&) {} /** This determines the LocalBathGreensfunctions for a given order @param configuration the configuration */ inline void evaluate(const Configuration&, const DoWick<typename Configuration::value_type, GFRetVal>&); private: const uint32_t& functionpoints; const FPType delta_s; const FPType beta; std::complex<float>* mixeddata;///< here we store <d^+ gamma>. We use floats to keep the memory footprint small std::complex<float>* unmixeddata;///< here we store <gamma^+ gamma> const uint Ny; const uint Nx; const uint Nt; const FPType delta_beta; const uint Nw; const uint Nyt; const uint Nxyt; const uint32_t functions; std::complex<FPType> accessmixed(uint r, uint n, SPINS spin, FPType tau1, FPType tau2 ) const { const FPType tiny = std::numeric_limits<FPType>::epsilon(); FPType delta_tau = tau1 - tau2; FPType sign = 1.0; std::complex<float>* dataptr = mixeddata; if (spin == DOWN) dataptr += Nxyt; dataptr = dataptr + n*Nt*Nx + r*Nt; if (std::abs(delta_tau) < tiny) { //return only the particle number return std::complex<FPType>(dataptr[0]); } if(delta_tau < 0) { sign = -1.0; delta_tau += beta; } FPType fptau_idx0; FPType rem = std::modf(delta_tau/delta_beta, &fptau_idx0);//round to the smaller index and determine how far we're of std::size_t tau_idx0 = lround(fptau_idx0); // std::cout<<"tau_0: "<<tau_idx0<<" "<<g[tau_idx0]<<std::endl; return std::complex<FPType>(lerp(float(rem), dataptr[tau_idx0], dataptr[tau_idx0 + 1]))*sign; } std::complex<FPType> accessunmixed(uint r, uint n, SPINS spin, FPType tau) const { std::complex<float>* dataptr = unmixeddata; if (spin == DOWN) dataptr += Nxyt; dataptr = dataptr + n*Nt*Nx + r*Nt; FPType fptau_idx0; FPType rem = std::modf(tau/delta_beta, &fptau_idx0);//round to the smaller index and determine how far we're of std::size_t tau_idx0 = static_cast<std::size_t>(lround(fptau_idx0)); // std::cout<<"tau_0: "<<tau_idx0<<" "<<g[tau_idx0]<<std::endl; //if(tau_idx0 == Nt) return dataptr[tau_idx0]; return std::complex<FPType>(lerp(float(rem), dataptr[tau_idx0], dataptr[tau_idx0 + 1])); } }; template <class Config, class GreensFunction> void LocalBathGreensfunctions_averaged<Config, GreensFunction>::evaluate(const Configuration& config, const DoWick<typename Configuration::value_type, GFRetVal>& dowick) { ObservableType func(functions); // ofstream file("t2.txt"); //#pragma omp parallel for for (unsigned int k = 0; k < func.size(); ++k) { func[k].resize(functionpoints); uint n = k / Nx; uint r = k % Nx; for (unsigned int j = 0; j < functionpoints/*-1*/; ++j) { const FPType tau = j * delta_s; // uint unmixedidx = trunc(tau/delta_beta); GFRetVal t1 = accessunmixed(r, n, UP, tau) + accessunmixed(r, n, DOWN, tau); // (unmixeddata + k*Nt + r*Nt)[unmixedidx];//access the up-sector GFRetVal t2 = 0; for (uint q = 0; q < config.size(); ++q) for (uint s = 0; s < config.size(); ++s) { t2 += config.matcont.mat(2*q, 2*s) * accessmixed(r, n, UP, config[q].tau, 0) * conj(accessmixed(r, n, UP, config[s].tau, tau)); // t2 += config.matcont.mat(2*q, 2*s + 1) * static_cast<FPType>(0.0);//For now disabled // t2 += config.matcont.mat(2*q + 1, 2*s) * static_cast<FPType>(0.0);//For now disabled t2 += config.matcont.mat(2*q + 1, 2*s + 1) * accessmixed(r, n, DOWN, config[q].tau, 0) * conj(accessmixed(r, n, DOWN, config[s].tau, tau)); } // file<<j<<" "<<real(t2)<<std::endl; //add to measurement func[k][j] = (t1 + t2)* config.phase/2.0; } // file<<"&"<<std::endl; } // exit(-1); this->add_bin(func); return; } /** A class for measuring the Kondo-cloud as evidenced by the correlation function <S^z_d S^z_c (x)> where d denotes the dot electron and c the bath electron. All this as a function of distance from the dot. */ template <class Config, class GreensFunction, SPINS Spin> class KondoCloud_Z : public Network_Cache<Config, std::valarray<typename Config::SignType> > { public: typedef typename Config::Configuration Configuration; typedef typename Configuration::FPType FPType; typedef typename Config::SignType GFRetVal; typedef GreensFunction GF; typedef std::valarray<GFRetVal> Function; typedef std::valarray<GFRetVal> ObservableType;///<the Kondo Cloud has no time-dependence. it depends only on the position /** The Constructor for the KondoCloud */ KondoCloud_Z(typename Config::Comm& n, const Parameters& params)/* throw()*/ : Network_Cache<Config, ObservableType>(n, "KondoCloud_Z"), functionpoints(params.functionpoints), beta(params.beta), Ny(params.Nb*2), Nx(params.Nx), Nt(300 + 1), Nw(4*Nt), delta_beta(params.beta/static_cast<FPType>(Nt-1)), sites(Ny*params.Nx), Nxyt(sites*Nt) { #ifdef _OPENMP double start2 = omp_get_wtime(); #endif std::cout<<"Creating KondoCloud_Z"<<std::endl; const GOmegaData<FPType> *const updata = GF::gomegaup->data; const GOmegaData<FPType> *const downdata = GF::gomegadown->data; //let's set up the Q(r, n, omega_n) data Omegadata<FPType>* omega = new Omegadata<FPType>[Nw/2]; std::complex<FPType>* gup = new std::complex<FPType>[Nw]; std::complex<FPType>* gdown = new std::complex<FPType>[Nw]; for (int t = 0; t < static_cast<int>(Nw/2); ++t) { gup[2*t] = conj((*GF::gomegaup)(t)); gup[2*t + 1] = conj((*GF::gomegaup)( -t - 1)); gdown[2*t] = conj((*GF::gomegadown)(t)); gdown[2*t + 1] = conj((*GF::gomegadown)( -t - 1)); omega[t].omega = M_PI/params.beta*(2*t + 1); omega[t].omegasq = omega[t].omega*omega[t].omega; omega[t].invomega = 1.0/omega[t].omega; } FPType pref = GF::gethybridization() / std::sqrt(params.Nx); unmixeddata = new std::complex<FPType>[2*sites]; //Since we have a simple, analytical expression for the tau dependence of the offset of the unmixed greensfunctions //we write that one out first to the unmixeddata array FPType* cosharrayup = new FPType[sites]; FPType* cosharraydown = new FPType[sites]; for(uint k = 0; k < params.Nx; ++k) for(uint m = 0; m < Ny; ++m) { cosharrayup[k*Ny + m] = 1.0/std::cosh(params.beta*updata[k*Ny + m].lambda/2.0)/2.0/static_cast<FPType>(params.Nx); cosharraydown[k*Ny + m] = 1.0/std::cosh(params.beta*downdata[k*Ny + m].lambda/2.0)/2.0/static_cast<FPType>(params.Nx); } #pragma omp parallel for for(uint n = 0; n < Ny; ++n) { FPType* tempup = new FPType[sites]; FPType* tempdown = new FPType[sites]; for(uint k = 0; k < params.Nx; ++k) for(uint m = 0; m < Ny; ++m) { tempup[k*Ny + m] = cosharrayup[k*Ny + m] * norm(updata[k*Ny + /*n*/m].evec[/*m*/n]); tempdown[k*Ny + m] = cosharraydown[k*Ny + m] * norm(downdata[k*Ny + /*n*/m].evec[/*m*/n]); } FPType ftup = 0.0; FPType ftdown = 0.0; FPType arg = - params.beta/2.0;//from that we only need a tau == 0 quantity FPType cup = 0.0; FPType cdown = 0.0; for(uint k = 0; k < params.Nx; ++k)//being careful we employ Kahan summation for(uint m = 0; m < Ny; ++m) { FPType argup = tempup[k*Ny + m] * std::exp(updata[k*Ny + m].lambda*arg); FPType argdown = tempdown[k*Ny + m] * std::exp(downdata[k*Ny + m].lambda*arg); FPType y = argup - cup; FPType t = ftup + y; cup = (t - ftup) - y; ftup = t; y = argdown - cdown; t = ftdown + y; cdown = (t - ftdown) - y; ftdown = t; } for(uint r = 0; r < params.Nx; ++r) { (unmixeddata + n*params.Nx)[r] = static_cast<float>(ftup); (unmixeddata + sites + n*params.Nx)[r] = static_cast<float>(ftdown); } delete [] tempup; delete [] tempdown; } delete [] cosharrayup; delete [] cosharraydown; const unsigned int Nxw = Nw*params.Nx; FPType normierungunmixed = 1.0/params.beta / params.Nx; FPType normierungmixed = 1.0/params.beta / std::sqrt(params.Nx); const std::complex<FPType> expNt = std::exp(std::complex<FPType>(0.0, -M_PI/(Nt-1))); mixeddata = new std::complex<FPType>[2*Nxyt]; #pragma omp parallel for for (uint n = 0; n < Ny; ++n) { std::complex<FPType>* Qup = new std::complex<FPType>[Nxw]; std::complex<FPType>* Qdown = new std::complex<FPType>[Nxw]; std::complex<FPType>* funup = new std::complex<FPType>[Nxw]; std::complex<FPType>* fundown = new std::complex<FPType>[Nxw]; memset(funup, 0, Nxw*sizeof(std::complex<FPType>)); memset(fundown, 0, Nxw*sizeof(std::complex<FPType>)); // double start = omp_get_wtime(); // std::cout<<"n = "<<n<<std::endl; for (uint k = 0; k < params.Nx; ++k) { for (uint m = 0; m < Ny; ++m) { std::complex<FPType> facup = conj(updata [k*Ny + m].u) * updata[k*Ny + m].evec[n]; std::complex<FPType> facdown = conj(downdata[k*Ny + m].u) * downdata[k*Ny + m].evec[n]; for (int omega_idx = 0; omega_idx < static_cast<int>(Nw/2); ++omega_idx) {//the layout of the frequencies is now (w_n, -w_n) , that is every negative frequency is stored next to its positive counterpart. //Hopefully this gives a better data locality funup[2*omega_idx*params.Nx + k] += facup/std::complex<FPType>(-updata[k*Ny + m].lambda, -omega[omega_idx].omega); funup[(2*omega_idx + 1)*params.Nx + k] += facup/std::complex<FPType>(-updata[k*Ny + m].lambda, omega[omega_idx].omega); fundown[2*omega_idx*params.Nx + k] += facdown/std::complex<FPType>(-downdata[k*Ny + m].lambda, -omega[omega_idx].omega); fundown[(2*omega_idx + 1)*params.Nx + k] += facdown/std::complex<FPType>(-downdata[k*Ny + m].lambda, omega[omega_idx].omega); } } } // std::cout<<"time now: "<<omp_get_wtime() - start<<std::endl; for (uint w = 0; w < Nw; ++w) { fourier1(reinterpret_cast<FPType*>(funup + w*params.Nx), params.Nx, 1); fourier1(reinterpret_cast<FPType*>(fundown + w*params.Nx), params.Nx, 1); //funup as well as fundown now contain Q(r, i omega) for a particular value of the orbital n for (uint r = 0; r < params.Nx; ++r) { funup[w*params.Nx + r] *= pref; // == Q. pref == V/sqrt(L) fundown[w*params.Nx + r] *= pref; // == Q. pref == V/sqrt(L) (Qup + r*Nw)[w] = funup[w*params.Nx + r];//norm(funup[w*params.Nx + r]); (Qdown + r*Nw)[w] = fundown[w*params.Nx + r];//norm(fundown[w*params.Nx + r]); // funup[w*params.Nx + r] = funup[w*params.Nx + r]; // fundown[w*params.Nx + r] = fundown[w*params.Nx + r]; } } for(uint r = 0; r < params.Nx; ++r) for(uint w = 0; w < Nw/2; ++w) { std::complex<FPType> temp = conj((Qup + r*Nw)[2*w]); (Qup + r*Nw)[2*w] *= conj((Qup + r*Nw)[2*w+1]); (Qup + r*Nw)[2*w+1] *= temp; temp = conj((Qdown + r*Nw)[2*w]); (Qdown + r*Nw)[2*w] *= conj((Qdown + r*Nw)[2*w+1]); (Qdown + r*Nw)[2*w+1] *= temp; } // std::cout<<"time now: "<<omp_get_wtime() - start<<std::endl; for (uint r = 0; r < params.Nx; ++r) { std::complex<FPType> expt = 1; {//an empty block for the unmixeddata std::complex<FPType> tempup = 0; std::complex<FPType> tempdown = 0; for (int omega_idx = 0; omega_idx < static_cast<int>(Nw/2); ++omega_idx) { std::complex<FPType> gupp = gup[2*omega_idx]; std::complex<FPType> gupm = gup[2*omega_idx + 1]; std::complex<FPType> gdownp = gdown[2*omega_idx]; std::complex<FPType> gdownm = gdown[2*omega_idx + 1]; tempup += (Qup + r * Nw)[2*omega_idx] * gupp + (Qup + r * Nw)[2*omega_idx + 1] * gupm; tempdown += (Qdown + r * Nw)[2*omega_idx] * gdownp + (Qdown + r * Nw)[2*omega_idx + 1] * gdownm; } (unmixeddata + n*params.Nx)[r] += tempup*normierungunmixed; (unmixeddata + sites + n*params.Nx)[r] += tempdown*normierungunmixed; } for(uint t = 0; t < Nt; ++t)// here is the final Matsubara transform { std::complex<FPType> tempupmixed = 0; std::complex<FPType> tempdownmixed = 0; std::complex<FPType> expiom = expt; std::complex<FPType> expfac = expiom*expiom; for (int omega_idx = 0; omega_idx < static_cast<int>(Nw/2); ++omega_idx) { std::complex<FPType> gupp = gup[2*omega_idx]; std::complex<FPType> gupm = gup[2*omega_idx + 1]; std::complex<FPType> gdownp = gdown[2*omega_idx]; std::complex<FPType> gdownm = gdown[2*omega_idx + 1]; std::complex<FPType> cexpiom = conj(expiom); tempupmixed += cexpiom * funup[(2*omega_idx)*params.Nx + r] * gupp + expiom * funup[(2*omega_idx + 1)*params.Nx + r] * gupm; tempdownmixed += cexpiom * fundown[(2*omega_idx)*params.Nx + r] * gdownp + expiom * fundown[(2*omega_idx + 1)*params.Nx + r] * gdownm; expiom *= expfac; } (mixeddata + n*params.Nx*Nt + r*Nt)[t] = tempupmixed*normierungmixed; (mixeddata + Nxyt + n*params.Nx*Nt + r*Nt)[t] = tempdownmixed*normierungmixed; expt *= expNt; } // if (r > 3 )exit(-1); // test<<"&"<<std::endl; } // std::cout<<"Initialization took "<<omp_get_wtime() - start<<" seconds"<<std::endl; delete [] funup; delete [] fundown; delete [] Qup; delete [] Qdown; } #ifdef _OPENMP std::cout<<"Initialization took "<<omp_get_wtime() - start2<<" seconds"<<std::endl; #endif delete [] gup; delete [] gdown; delete [] omega; std::cout<<"KondoCloud_Z done"<<std::endl; } void dryrun(DryRun<typename Configuration::value_type, GFRetVal>& func) { contrib_dry(UP, UP, func); contrib_dry(UP, DOWN, func); contrib_dry(DOWN, UP, func); contrib_dry(DOWN, DOWN, func); } /** this determines the KondoCloud for a given order @param configuration the configuration */ inline void evaluate(const Configuration&, const DoWick<typename Configuration::value_type, GFRetVal>&); private: const uint32_t& functionpoints; const FPType beta; std::complex<FPType>* mixeddata;///< here we store <d^+ gamma>. std::complex<FPType>* unmixeddata;///< here we store <gamma^+ gamma> const uint Ny; const uint Nx; const uint Nt; const uint Nw; const FPType delta_beta; const uint32_t sites; const uint Nxyt; std::complex<FPType> accessmixed(uint r, uint n, SPINS spin1, FPType tau1 , SPINS spin2, FPType tau2) const { FPType delta_tau = tau1 - tau2; FPType sign = 1.0; std::complex<FPType>* dataptr = mixeddata; if(spin1 != spin2) return 0.0;//FIXME!!!!!!!!!!!!!!!!!!!! only the case for the spin symmetric case! if (spin1 == DOWN) dataptr += Nxyt; dataptr = dataptr + n*Nx*Nt + r*Nt; //if(std::abs(delta_tau) < std::numeric_limits<FPType>::epsilon()) if(fpequal(tau1, tau2)) return std::complex<FPType>(dataptr[0]); if(delta_tau < 0) { sign = -1.0; delta_tau += beta; } FPType fptau_idx0; FPType rem = std::modf(delta_tau/delta_beta, &fptau_idx0);//round to the smaller index and determine how far we're off. std::size_t tau_idx0 = lround(fptau_idx0); return std::complex<FPType>(lerp(rem, dataptr[tau_idx0], dataptr[tau_idx0 + 1]))*sign; } std::complex<FPType> accessunmixed(uint r, uint n, SPINS spin) const { std::complex<FPType>* dataptr = unmixeddata; if (spin == DOWN) dataptr += sites; dataptr = dataptr + n*Nx + r; return dataptr[0]; } void contrib_dry(SPINS sigma, SPINS sigmaprime, DryRun<typename Configuration::value_type, GFRetVal>& func) const {//yes, the only thing that we don't derive from tables only depends on sigmaprime typename GreensFunction::Vertex v1; v1.spin = sigmaprime; v1.tau = 0; func(v1, v1); } GFRetVal dotghelper(FPType tau1, SPINS spin1, FPType tau2, SPINS spin2, const Configuration& config) { // auto gdot = [](FPType tau1, SPINS spin1, FPType tau2, SPINS spin2){return GreensFunction::eval(typename GreensFunction::Vertex(tau1, spin1), typename GreensFunction::Vertex(tau2, spin2));}; struct GDot{GFRetVal operator() (FPType tau1, SPINS spin1, FPType tau2, SPINS spin2){return GreensFunction::eval(typename GreensFunction::Vertex(tau1, spin1), typename GreensFunction::Vertex(tau2, spin2));} } gdot; GFRetVal retval = gdot(tau1, spin1, tau2, spin2); for(uint r = 0; r < config.size(); ++r) { FPType taur = config[r].tau; GFRetVal gtaur_tau1_up = gdot(taur, UP, tau1, spin1); GFRetVal gtaur_tau1_down = gdot(taur, DOWN, tau1, spin1); for(uint s = 0; s < config.size(); ++s) { FPType taus = config[s].tau; GFRetVal gtau2_taus_up = gdot(tau2, spin2, taus, UP); GFRetVal gtau2_taus_down = gdot(tau2, spin2, taus, DOWN); retval -= gtaur_tau1_up * config.matcont.mat(2*r, 2*s) * gtau2_taus_up; retval -= gtaur_tau1_down * config.matcont.mat(2*r+1, 2*s) * gtau2_taus_up; retval -= gtaur_tau1_up * config.matcont.mat(2*r, 2*s+1) * gtau2_taus_down; retval -= gtaur_tau1_down * config.matcont.mat(2*r+1, 2*s+1) * gtau2_taus_down; } } return retval; } }; template <class Config, class GreensFunction, SPINS Spin> void KondoCloud_Z<Config, GreensFunction, Spin>::evaluate(const Configuration& config, const DoWick<typename Configuration::value_type, GFRetVal>& dowick) { ObservableType func(sites); typename GreensFunction::Vertex v1(0.0, UP); typename GreensFunction::Vertex v2(0.0, DOWN); GFRetVal dotcontrib = dowick(v1, v1) - dowick(v2,v2); GFRetVal *const dotgf = new GFRetVal[config.size()*2*2*2]; for(uint i = 0; i < config.size(); ++i)//here we sum up < d^+ d(t) > { FPType taui = config[i].tau; dotgf[4*i + 0] = dotghelper(0, UP, taui, UP, config); dotgf[4*i + 1] = dotghelper(0, UP, taui, DOWN, config); dotgf[4*i + 2] = dotghelper(0, DOWN, taui, UP, config); dotgf[4*i + 3] = dotghelper(0, DOWN, taui, DOWN, config); dotgf[4*(i+config.size()) + 0] = dotghelper(taui, UP, 0, UP, config); dotgf[4*(i+config.size()) + 1] = dotghelper(taui, UP, 0, DOWN, config); dotgf[4*(i+config.size()) + 2] = dotghelper(taui, DOWN, 0, UP, config); dotgf[4*(i+config.size()) + 3] = dotghelper(taui, DOWN, 0, DOWN, config); } // std::ofstream kc("kc.txt"); #pragma omp parallel for for (unsigned int k = 0; k < func.size(); ++k) { uint n = k / Nx; uint r = k % Nx; GFRetVal unmixedup = accessunmixed(r, n, UP); GFRetVal unmixeddown = accessunmixed(r, n, DOWN); GFRetVal mixedupup = accessmixed(r, n, UP, 0.0, UP, 0.0); GFRetVal mixedupdown = accessmixed(r, n, UP, 0.0, DOWN, 0.0); GFRetVal mixeddownup = accessmixed(r, n, DOWN, 0.0, UP, 0.0); GFRetVal mixeddowndown = accessmixed(r, n, DOWN, 0.0, DOWN, 0.0); GFRetVal mixedupupconj = conj(accessmixed(r, n, UP, 0.0, UP, 0.0)); GFRetVal mixedupdownconj = conj(accessmixed(r, n, UP, 0.0, DOWN, 0.0)); GFRetVal mixeddownupconj = conj(accessmixed(r, n, DOWN, 0.0, UP, 0.0)); GFRetVal mixeddowndownconj = conj(accessmixed(r, n, DOWN, 0.0, DOWN, 0.0)); for(uint q = 0; q < config.size(); ++q) { FPType tauq = config[q].tau; GFRetVal gmixed_rn_tauq_UP_UP = accessmixed(r, n, UP, tauq, UP, 0.0); GFRetVal gmixed_rn_tauq_DOWN_UP = accessmixed(r, n, DOWN, tauq, UP, 0.0); GFRetVal gmixed_rn_tauq_UP_DOWN = accessmixed(r, n, UP, tauq, DOWN, 0.0); GFRetVal gmixed_rn_tauq_DOWN_DOWN = accessmixed(r, n, DOWN, tauq, DOWN, 0.0); GFRetVal dotq0 = dotgf[4*(q+config.size()) + 0]; GFRetVal dotq1 = dotgf[4*(q+config.size()) + 1]; GFRetVal dotq2 = dotgf[4*(q+config.size()) + 2]; GFRetVal dotq3 = dotgf[4*(q+config.size()) + 3]; for(uint s = 0; s < config.size(); ++s) { FPType taus = config[s].tau; GFRetVal gmixed_rn_taus_UP_UP = conj(accessmixed(r, n, UP, taus, UP, 0.0)); GFRetVal gmixed_rn_taus_UP_DOWN = conj(accessmixed(r, n, UP, taus, DOWN, 0.0)); GFRetVal gmixed_rn_taus_DOWN_UP = conj(accessmixed(r, n, DOWN, taus, UP, 0.0)); GFRetVal gmixed_rn_taus_DOWN_DOWN = conj(accessmixed(r, n, DOWN, taus, DOWN, 0.0)); GFRetVal matqs = config.matcont.mat(2*q, 2*s); GFRetVal matqsp = config.matcont.mat(2*q, 2*s + 1); GFRetVal matqps = config.matcont.mat(2*q + 1, 2*s); GFRetVal matqpsp = config.matcont.mat(2*q + 1, 2*s + 1); GFRetVal dots0 = dotgf[4*s+0]; GFRetVal dots1 = dotgf[4*s+1]; GFRetVal dots2 = dotgf[4*s+2]; GFRetVal dots3 = dotgf[4*s+3]; unmixedup -= ( matqs * gmixed_rn_tauq_UP_UP * gmixed_rn_taus_UP_UP +matqsp* gmixed_rn_tauq_UP_UP * gmixed_rn_taus_UP_DOWN +matqps* gmixed_rn_tauq_DOWN_UP* gmixed_rn_taus_UP_UP +matqpsp *gmixed_rn_tauq_DOWN_UP* gmixed_rn_taus_UP_DOWN ); unmixeddown -= ( matqs * gmixed_rn_tauq_UP_DOWN * gmixed_rn_taus_DOWN_UP +matqsp* gmixed_rn_tauq_UP_DOWN * gmixed_rn_taus_DOWN_DOWN +matqps* gmixed_rn_tauq_DOWN_DOWN* gmixed_rn_taus_DOWN_UP +matqpsp *gmixed_rn_tauq_DOWN_DOWN* gmixed_rn_taus_DOWN_DOWN ); mixedupup -= ( matqs * gmixed_rn_tauq_UP_UP * dots0 +matqsp* gmixed_rn_tauq_UP_UP * dots1 +matqps* gmixed_rn_tauq_DOWN_UP* dots0 +matqpsp *gmixed_rn_tauq_DOWN_UP* dots1 ); mixedupdown -= ( matqs * gmixed_rn_tauq_UP_DOWN * dots0 +matqsp* gmixed_rn_tauq_UP_DOWN * dots1 +matqps* gmixed_rn_tauq_DOWN_DOWN* dots0 +matqpsp *gmixed_rn_tauq_DOWN_DOWN* dots1 ); mixeddownup -= ( matqs * gmixed_rn_tauq_UP_UP * dots2 +matqsp* gmixed_rn_tauq_UP_UP * dots3 +matqps* gmixed_rn_tauq_DOWN_UP* dots2 +matqpsp *gmixed_rn_tauq_DOWN_UP* dots3 ); mixeddowndown -= ( matqs * gmixed_rn_tauq_UP_DOWN * dots2 +matqsp* gmixed_rn_tauq_UP_DOWN * dots3 +matqps* gmixed_rn_tauq_DOWN_DOWN* dots2 +matqpsp *gmixed_rn_tauq_DOWN_DOWN* dots3 ); GFRetVal gmixed_rn_UP_UP_taus = conj(accessmixed(r, n, UP, 0.0, UP, taus)); GFRetVal gmixed_rn_UP_DOWN_taus = conj(accessmixed(r, n, UP, 0.0, DOWN, taus)); mixedupupconj -= ( matqs * gmixed_rn_UP_UP_taus * dotq0 +matqsp * gmixed_rn_UP_DOWN_taus * dotq0 +matqps * gmixed_rn_UP_UP_taus* dotq2 +matqpsp * gmixed_rn_UP_DOWN_taus* dotq2 ); mixedupdownconj -= ( matqs * gmixed_rn_UP_UP_taus * dotq1 +matqsp * gmixed_rn_UP_DOWN_taus * dotq1 +matqps * gmixed_rn_UP_UP_taus* dotq3 +matqpsp * gmixed_rn_UP_DOWN_taus* dotq3 ); GFRetVal gmixed_rn_DOWN_DOWN_taus = conj(accessmixed(r, n, DOWN, 0.0, DOWN, taus)); GFRetVal gmixed_rn_DOWN_UP_taus = conj(accessmixed(r, n, DOWN, 0.0, UP, taus)); mixeddownupconj -= ( matqs * gmixed_rn_DOWN_UP_taus * dotq0 +matqsp * gmixed_rn_DOWN_DOWN_taus * dotq0 +matqps * gmixed_rn_DOWN_UP_taus* dotq2 +matqpsp * gmixed_rn_DOWN_DOWN_taus* dotq2 ); mixeddowndownconj -= ( matqs * gmixed_rn_DOWN_UP_taus * dotq1 +matqsp * gmixed_rn_DOWN_DOWN_taus * dotq1 +matqps * gmixed_rn_DOWN_UP_taus* dotq3 +matqpsp * gmixed_rn_DOWN_DOWN_taus* dotq3 ); } } //add to measurement func[k] = (dotcontrib * (unmixedup - unmixeddown) - mixedupup*mixedupupconj /*+ mixedupdown*mixedupdownconj + mixeddownup*mixeddownupconj*/ - mixeddowndown*mixeddowndownconj)* config.phase/4.0; //kc<<dotcontrib <<" "<< (unmixedup - unmixeddown)<<" "<<mixedupup<<" "<<mixedupupconj<<" "<< mixedupdown<<" "<<mixedupdownconj <<" "<< mixeddownup<<" "<<mixeddownupconj <<" "<< mixeddowndown<<" "<<mixeddowndownconj<<std::endl; } // exit(-1); this->add_bin(func); delete [] dotgf; return; } /** A class for measuring the Kondo-cloud as evidenced by the correlation function <S^x_d S^x_c (r)> where d denotes the dot electron and c the bath electron. All this as a function of distance r from the dot. */ template <class Config, class GreensFunction, SPINS Spin> class KondoCloud_X : public Network_Cache<Config, std::valarray<typename Config::SignType> > { public: typedef typename Config::Configuration Configuration; typedef typename Configuration::FPType FPType; typedef typename Config::SignType GFRetVal; typedef GreensFunction GF; typedef std::valarray<GFRetVal> Function; typedef std::valarray<GFRetVal> ObservableType;///<the Kondo Cloud has no time-dependence. it depends only on the position /** The Constructor for the KondoCloud measured along the X- direction */ KondoCloud_X(typename Config::Comm& n, const Parameters& params)/* throw()*/ : Network_Cache<Config, ObservableType>(n, "KondoCloud_X"), functionpoints(params.functionpoints), beta(params.beta), Ny(params.Nb*2), Nx(params.Nx), Nt(300 + 1), Nw(4*Nt), delta_beta(params.beta/static_cast<FPType>(Nt-1)), sites(Ny*params.Nx), Nxyt(sites*Nt) { #ifdef _OPENMP double start2 = omp_get_wtime(); #endif std::cout<<"Creating KondoCloud_X"<<std::endl; const GOmegaData<FPType> *const updata = GF::gomegaup->data; const GOmegaData<FPType> *const downdata = GF::gomegadown->data; //let's set up the Q(r, n, omega_n) data Omegadata<FPType>* omega = new Omegadata<FPType>[Nw/2]; std::complex<FPType>* gup = new std::complex<FPType>[Nw]; std::complex<FPType>* gdown = new std::complex<FPType>[Nw]; for (int t = 0; t < static_cast<int>(Nw/2); ++t) { gup[2*t] = conj((*GF::gomegaup)(t)); gup[2*t + 1] = conj((*GF::gomegaup)( -t - 1)); gdown[2*t] = conj((*GF::gomegadown)(t)); gdown[2*t + 1] = conj((*GF::gomegadown)( -t - 1)); omega[t].omega = M_PI/params.beta*(2*t + 1); omega[t].omegasq = omega[t].omega*omega[t].omega; omega[t].invomega = 1.0/omega[t].omega; } FPType pref = GF::gethybridization() / std::sqrt(params.Nx); unmixeddata = new std::complex<FPType>[2*sites]; //Since we have a simple, analytical expression for the tau dependence of the offset of the unmixed greensfunctions //we write that one out first to the unmixeddata array FPType* cosharrayup = new FPType[sites]; FPType* cosharraydown = new FPType[sites]; for(uint k = 0; k < params.Nx; ++k) for(uint m = 0; m < Ny; ++m) { cosharrayup[k*Ny + m] = 1.0/std::cosh(params.beta*updata[k*Ny + m].lambda/2.0)/2.0/static_cast<FPType>(params.Nx); cosharraydown[k*Ny + m] = 1.0/std::cosh(params.beta*downdata[k*Ny + m].lambda/2.0)/2.0/static_cast<FPType>(params.Nx); } #pragma omp parallel for for(uint n = 0; n < Ny; ++n) { FPType* tempup = new FPType[sites]; FPType* tempdown = new FPType[sites]; for(uint k = 0; k < params.Nx; ++k) for(uint m = 0; m < Ny; ++m) { tempup[k*Ny + m] = cosharrayup[k*Ny + m] * norm(updata[k*Ny + /*n*/m].evec[/*m*/n]); tempdown[k*Ny + m] = cosharraydown[k*Ny + m] * norm(downdata[k*Ny + /*n*/m].evec[/*m*/n]); } FPType ftup = 0.0; FPType ftdown = 0.0; FPType arg = - params.beta/2.0;//from that we only need a tau == 0 quantity FPType cup = 0.0; FPType cdown = 0.0; for(uint k = 0; k < params.Nx; ++k)//being careful we employ Kahan summation for(uint m = 0; m < Ny; ++m) { FPType argup = tempup[k*Ny + m] * std::exp(updata[k*Ny + m].lambda*arg); FPType argdown = tempdown[k*Ny + m] * std::exp(downdata[k*Ny + m].lambda*arg); FPType y = argup - cup; FPType t = ftup + y; cup = (t - ftup) - y; ftup = t; y = argdown - cdown; t = ftdown + y; cdown = (t - ftdown) - y; ftdown = t; } for(uint r = 0; r < params.Nx; ++r) { (unmixeddata + n*params.Nx)[r] = static_cast<float>(ftup); (unmixeddata + sites + n*params.Nx)[r] = static_cast<float>(ftdown); } delete [] tempup; delete [] tempdown; } delete [] cosharrayup; delete [] cosharraydown; const unsigned int Nxw = Nw*params.Nx; FPType normierungunmixed = 1.0/params.beta / params.Nx; FPType normierungmixed = 1.0/params.beta / std::sqrt(params.Nx); const std::complex<FPType> expNt = std::exp(std::complex<FPType>(0.0, -M_PI/(Nt-1))); mixeddata = new std::complex<FPType>[2*Nxyt]; #pragma omp parallel for for (uint n = 0; n < Ny; ++n) { std::complex<FPType>* Qup = new std::complex<FPType>[Nxw]; std::complex<FPType>* Qdown = new std::complex<FPType>[Nxw]; std::complex<FPType>* funup = new std::complex<FPType>[Nxw]; std::complex<FPType>* fundown = new std::complex<FPType>[Nxw]; memset(funup, 0, Nxw*sizeof(std::complex<FPType>)); memset(fundown, 0, Nxw*sizeof(std::complex<FPType>)); // double start = omp_get_wtime(); // std::cout<<"n = "<<n<<std::endl; for (uint k = 0; k < params.Nx; ++k) { for (uint m = 0; m < Ny; ++m) { std::complex<FPType> facup = conj(updata [k*Ny + m].u) * updata[k*Ny + m].evec[n]; std::complex<FPType> facdown = conj(downdata[k*Ny + m].u) * downdata[k*Ny + m].evec[n]; for (int omega_idx = 0; omega_idx < static_cast<int>(Nw/2); ++omega_idx) {//the layout of the frequencies is now (w_n, -w_n) , that is every negative frequency is stored next to its positive counterpart. //Hopefully this gives a better data locality funup[2*omega_idx*params.Nx + k] += facup/std::complex<FPType>(-updata[k*Ny + m].lambda, -omega[omega_idx].omega); funup[(2*omega_idx + 1)*params.Nx + k] += facup/std::complex<FPType>(-updata[k*Ny + m].lambda, omega[omega_idx].omega); fundown[2*omega_idx*params.Nx + k] += facdown/std::complex<FPType>(-downdata[k*Ny + m].lambda, -omega[omega_idx].omega); fundown[(2*omega_idx + 1)*params.Nx + k] += facdown/std::complex<FPType>(-downdata[k*Ny + m].lambda, omega[omega_idx].omega); } } } // std::cout<<"time now: "<<omp_get_wtime() - start<<std::endl; for (uint w = 0; w < Nw; ++w) { fourier1(reinterpret_cast<FPType*>(funup + w*params.Nx), params.Nx, 1); fourier1(reinterpret_cast<FPType*>(fundown + w*params.Nx), params.Nx, 1); //funup as well as fundown now contain Q(r, i omega) for a particular value of the orbital n for (uint r = 0; r < params.Nx; ++r) { funup[w*params.Nx + r] *= pref; // == Q. pref == V/sqrt(L) fundown[w*params.Nx + r] *= pref; // == Q. pref == V/sqrt(L) (Qup + r*Nw)[w] = funup[w*params.Nx + r];//norm(funup[w*params.Nx + r]); (Qdown + r*Nw)[w] = fundown[w*params.Nx + r];//norm(fundown[w*params.Nx + r]); // funup[w*params.Nx + r] = funup[w*params.Nx + r]; // fundown[w*params.Nx + r] = fundown[w*params.Nx + r]; } } for(uint r = 0; r < params.Nx; ++r) for(uint w = 0; w < Nw/2; ++w) { std::complex<FPType> temp = conj((Qup + r*Nw)[2*w]); (Qup + r*Nw)[2*w] *= conj((Qup + r*Nw)[2*w+1]); (Qup + r*Nw)[2*w+1] *= temp; temp = conj((Qdown + r*Nw)[2*w]); (Qdown + r*Nw)[2*w] *= conj((Qdown + r*Nw)[2*w+1]); (Qdown + r*Nw)[2*w+1] *= temp; } // std::cout<<"time now: "<<omp_get_wtime() - start<<std::endl; for (uint r = 0; r < params.Nx; ++r) { std::complex<FPType> expt = 1; {//an empty block for the unmixeddata std::complex<FPType> tempup = 0; std::complex<FPType> tempdown = 0; for (int omega_idx = 0; omega_idx < static_cast<int>(Nw/2); ++omega_idx) { std::complex<FPType> gupp = gup[2*omega_idx]; std::complex<FPType> gupm = gup[2*omega_idx + 1]; std::complex<FPType> gdownp = gdown[2*omega_idx]; std::complex<FPType> gdownm = gdown[2*omega_idx + 1]; tempup += (Qup + r * Nw)[2*omega_idx] * gupp + (Qup + r * Nw)[2*omega_idx + 1] * gupm; tempdown += (Qdown + r * Nw)[2*omega_idx] * gdownp + (Qdown + r * Nw)[2*omega_idx + 1] * gdownm; } (unmixeddata + n*params.Nx)[r] += tempup*normierungunmixed; (unmixeddata + sites + n*params.Nx)[r] += tempdown*normierungunmixed; } for(uint t = 0; t < Nt; ++t)// here is the final Matsubara transform { std::complex<FPType> tempupmixed = 0; std::complex<FPType> tempdownmixed = 0; std::complex<FPType> expiom = expt; std::complex<FPType> expfac = expiom*expiom; for (int omega_idx = 0; omega_idx < static_cast<int>(Nw/2); ++omega_idx) { std::complex<FPType> gupp = gup[2*omega_idx]; std::complex<FPType> gupm = gup[2*omega_idx + 1]; std::complex<FPType> gdownp = gdown[2*omega_idx]; std::complex<FPType> gdownm = gdown[2*omega_idx + 1]; std::complex<FPType> cexpiom = conj(expiom); tempupmixed += cexpiom * funup[(2*omega_idx)*params.Nx + r] * gupp + expiom * funup[(2*omega_idx + 1)*params.Nx + r] * gupm; tempdownmixed += cexpiom * fundown[(2*omega_idx)*params.Nx + r] * gdownp + expiom * fundown[(2*omega_idx + 1)*params.Nx + r] * gdownm; expiom *= expfac; } (mixeddata + n*params.Nx*Nt + r*Nt)[t] = tempupmixed*normierungmixed; (mixeddata + Nxyt + n*params.Nx*Nt + r*Nt)[t] = tempdownmixed*normierungmixed; expt *= expNt; } // if (r > 3 )exit(-1); // test<<"&"<<std::endl; } // std::cout<<"Initialization took "<<omp_get_wtime() - start<<" seconds"<<std::endl; delete [] funup; delete [] fundown; delete [] Qup; delete [] Qdown; } #ifdef _OPENMP std::cout<<"Initialization took "<<omp_get_wtime() - start2<<" seconds"<<std::endl; #endif delete [] gup; delete [] gdown; delete [] omega; std::cout<<"KondoCloud_X done"<<std::endl; } void dryrun(DryRun<typename Configuration::value_type, GFRetVal>& func) { contrib_dry(UP, UP, func); contrib_dry(UP, DOWN, func); contrib_dry(DOWN, UP, func); contrib_dry(DOWN, DOWN, func); } /** this determines the KondoCloud_X for a given order @param configuration the configuration */ inline void evaluate(const Configuration&, const DoWick<typename Configuration::value_type, GFRetVal>&); private: const uint32_t& functionpoints; const FPType beta; std::complex<FPType>* mixeddata;///< here we store <d^+ gamma>. std::complex<FPType>* unmixeddata;///< here we store <gamma^+ gamma> const uint Ny; const uint Nx; const uint Nt; const uint Nw; const FPType delta_beta; const uint32_t sites; const uint Nxyt; std::complex<FPType> accessmixed(uint r, uint n, SPINS spin1, FPType tau1 , SPINS spin2, FPType tau2) const { FPType delta_tau = tau1 - tau2; FPType sign = 1.0; std::complex<FPType>* dataptr = mixeddata; if(spin1 != spin2) return 0.0;//FIXME!!!!!!!!!!!!!!!!!!!! only the case for the spin symmetric case! if (spin1 == DOWN) dataptr += Nxyt; dataptr = dataptr + n*Nx*Nt + r*Nt; // if(std::abs(delta_tau) < std::numeric_limits<FPType>::epsilon()) if(fpequal(tau1, tau2)) return std::complex<FPType>(dataptr[0]); if(delta_tau < 0) { sign = -1.0; delta_tau += beta; } FPType fptau_idx0; FPType rem = std::modf(delta_tau/delta_beta, &fptau_idx0);//round to the smaller index and determine how far we're off. std::size_t tau_idx0 = lround(fptau_idx0); return std::complex<FPType>(lerp(rem, dataptr[tau_idx0], dataptr[tau_idx0 + 1]))*sign; } std::complex<FPType> accessunmixed(uint r, uint n, SPINS spin) const { std::complex<FPType>* dataptr = unmixeddata; if (spin == DOWN) dataptr += sites; dataptr = dataptr + n*Nx + r; return dataptr[0]; } void contrib_dry(SPINS sigma, SPINS sigmaprime, DryRun<typename Configuration::value_type, GFRetVal>& func) {//yes, the only thing that we don't derive from tables only depends on sigmaprime typename GreensFunction::Vertex v1; v1.spin = sigmaprime; v1.tau = 0; func(v1, v1); } GFRetVal dotghelper(FPType tau1, SPINS spin1, FPType tau2, SPINS spin2, const Configuration config) { // auto gdot = [](FPType tau1, SPINS spin1, FPType tau2, SPINS spin2){return GreensFunction::eval(typename GreensFunction::Vertex(tau1, spin1), typename GreensFunction::Vertex(tau2, spin2));}; struct GDot{GFRetVal operator() (FPType tau1, SPINS spin1, FPType tau2, SPINS spin2){return GreensFunction::eval(typename GreensFunction::Vertex(tau1, spin1), typename GreensFunction::Vertex(tau2, spin2));} } gdot; GFRetVal retval = gdot(tau1, spin1, tau2, spin2); for(uint r = 0; r < config.size(); ++r) for(uint s = 0; s < config.size(); ++s) { retval -= gdot(config[r].tau, UP, tau1, spin1) * config.matcont.mat(2*r, 2*s) * gdot(tau2, spin2, config[s].tau, UP); retval -= gdot(config[r].tau, DOWN, tau1, spin1) * config.matcont.mat(2*r+1, 2*s) * gdot(tau2, spin2, config[s].tau, UP); retval -= gdot(config[r].tau, UP, tau1, spin1) * config.matcont.mat(2*r, 2*s+1) * gdot(tau2, spin2, config[s].tau, DOWN); retval -= gdot(config[r].tau, DOWN, tau1, spin1) * config.matcont.mat(2*r+1, 2*s+1) * gdot(tau2, spin2, config[s].tau, DOWN); } return retval; } }; template <class Config, class GreensFunction, SPINS Spin> void KondoCloud_X<Config, GreensFunction, Spin>::evaluate(const Configuration& config, const DoWick<typename Configuration::value_type, GFRetVal>& dowick) { ObservableType func(sites); typename GreensFunction::Vertex v1(0.0, UP); typename GreensFunction::Vertex v2(0.0, DOWN); GFRetVal dotcontrib = dowick(v1, v1) - dowick(v2,v2); GFRetVal *const dotgf = new GFRetVal[config.size()*2*2*2]; for(uint i = 0; i < config.size(); ++i)//here we sum up < d^+ d(t) > { dotgf[4*i + 0] = dotghelper(0, UP, config[i].tau, UP, config); dotgf[4*i + 1] = dotghelper(0, UP, config[i].tau, DOWN, config); dotgf[4*i + 2] = dotghelper(0, DOWN, config[i].tau, UP, config); dotgf[4*i + 3] = dotghelper(0, DOWN, config[i].tau, DOWN, config); } for(uint i = 0; i < config.size(); ++i)//here we sum up < d^+ d(t) > { dotgf[4*(i+config.size()) + 0] = dotghelper(config[i].tau, UP, 0, UP, config); dotgf[4*(i+config.size()) + 1] = dotghelper(config[i].tau, UP, 0, DOWN, config); dotgf[4*(i+config.size()) + 2] = dotghelper(config[i].tau, DOWN, 0, UP, config); dotgf[4*(i+config.size()) + 3] = dotghelper(config[i].tau, DOWN, 0, DOWN, config); } // std::ofstream kc("kc.txt"); #pragma omp parallel for for (unsigned int k = 0; k < func.size(); ++k) { uint n = k / Nx; uint r = k % Nx; // GFRetVal unmixedup = accessunmixed(r, n, UP); // GFRetVal unmixeddown = accessunmixed(r, n, DOWN); GFRetVal mixedupup = accessmixed(r, n, UP, 0.0, UP, 0.0); // GFRetVal mixedupdown = accessmixed(r, n, UP, 0.0, DOWN, 0.0); // GFRetVal mixeddownup = accessmixed(r, n, DOWN, 0.0, UP, 0.0); GFRetVal mixeddowndown = accessmixed(r, n, DOWN, 0.0, DOWN, 0.0); GFRetVal mixedupupconj = conj(accessmixed(r, n, UP, 0.0, UP, 0.0)); // GFRetVal mixedupdownconj = conj(accessmixed(r, n, UP, 0.0, DOWN, 0.0)); // GFRetVal mixeddownupconj = conj(accessmixed(r, n, DOWN, 0.0, UP, 0.0)); GFRetVal mixeddowndownconj = conj(accessmixed(r, n, DOWN, 0.0, DOWN, 0.0)); for(uint q = 0; q < config.size(); ++q) for(uint s = 0; s < config.size(); ++s) { // unmixedup -= ( // config.matcont.mat(2*q, 2*s) * accessmixed(r, n, UP, config[q].tau, UP, 0.0) *conj(accessmixed(r, n, UP, config[s].tau, UP, 0.0)) // +config.matcont.mat(2*q, 2*s+1)* accessmixed(r, n, UP, config[q].tau, UP, 0.0) *conj(accessmixed(r, n, UP, config[s].tau, DOWN, 0.0)) // +config.matcont.mat(2*q+1, 2*s)* accessmixed(r, n, DOWN, config[q].tau, UP, 0.0)*conj(accessmixed(r, n, UP, config[s].tau, UP, 0.0)) // +config.matcont.mat(2*q+1, 2*s+1) *accessmixed(r, n, DOWN, config[q].tau, UP, 0.0)*conj(accessmixed(r, n, UP, config[s].tau, DOWN, 0.0)) // ); // unmixeddown -= ( // config.matcont.mat(2*q, 2*s) * accessmixed(r, n, UP, config[q].tau, DOWN, 0.0) *conj(accessmixed(r, n, DOWN, config[s].tau, UP, 0.0)) // +config.matcont.mat(2*q, 2*s+1)* accessmixed(r, n, UP, config[q].tau, DOWN, 0.0) *conj(accessmixed(r, n, DOWN, config[s].tau, DOWN, 0.0)) // +config.matcont.mat(2*q+1, 2*s)* accessmixed(r, n, DOWN, config[q].tau, DOWN, 0.0)*conj(accessmixed(r, n, DOWN, config[s].tau, UP, 0.0)) // +config.matcont.mat(2*q+1, 2*s+1) *accessmixed(r, n, DOWN, config[q].tau, DOWN, 0.0)*conj(accessmixed(r, n, DOWN, config[s].tau, DOWN, 0.0)) // ); typename GreensFunction::Vertex v1u(0.0, UP); typename GreensFunction::Vertex v2su(config[s].tau, UP); typename GreensFunction::Vertex v1d(0.0, DOWN); typename GreensFunction::Vertex v2sd(config[s].tau, DOWN); mixedupup -= ( config.matcont.mat(2*q, 2*s) * accessmixed(r, n, UP, config[q].tau, UP, 0.0) * dotgf[4*s+0] +config.matcont.mat(2*q, 2*s+1)* accessmixed(r, n, UP, config[q].tau, UP, 0.0) * dotgf[4*s+1] +config.matcont.mat(2*q+1, 2*s)* accessmixed(r, n, DOWN, config[q].tau, UP, 0.0)* dotgf[4*s+0] +config.matcont.mat(2*q+1, 2*s+1) *accessmixed(r, n, DOWN, config[q].tau, UP, 0.0)* dotgf[4*s+1] ); // mixedupdown -= ( // config.matcont.mat(2*q, 2*s) * accessmixed(r, n, UP, config[q].tau, DOWN, 0.0) * dotgf[4*s+0] // +config.matcont.mat(2*q, 2*s+1)* accessmixed(r, n, UP, config[q].tau, DOWN, 0.0) * dotgf[4*s+1] // +config.matcont.mat(2*q+1, 2*s)* accessmixed(r, n, DOWN, config[q].tau, DOWN, 0.0)* dotgf[4*s+0] // +config.matcont.mat(2*q+1, 2*s+1) *accessmixed(r, n, DOWN, config[q].tau, DOWN, 0.0)* dotgf[4*s+1] // ); // // mixeddownup -= ( // config.matcont.mat(2*q, 2*s) * accessmixed(r, n, UP, config[q].tau, UP, 0.0) * dotgf[4*s+2] // +config.matcont.mat(2*q, 2*s+1)* accessmixed(r, n, UP, config[q].tau, UP, 0.0) * dotgf[4*s+3] // +config.matcont.mat(2*q+1, 2*s)* accessmixed(r, n, DOWN, config[q].tau, UP, 0.0)* dotgf[4*s+2] // +config.matcont.mat(2*q+1, 2*s+1) *accessmixed(r, n, DOWN, config[q].tau, UP, 0.0)* dotgf[4*s+3] // ); mixeddowndown -= ( config.matcont.mat(2*q, 2*s) * accessmixed(r, n, UP, config[q].tau, DOWN, 0.0) * dotgf[4*s+2] +config.matcont.mat(2*q, 2*s+1)* accessmixed(r, n, UP, config[q].tau, DOWN, 0.0) * dotgf[4*s+3] +config.matcont.mat(2*q+1, 2*s)* accessmixed(r, n, DOWN, config[q].tau, DOWN, 0.0)* dotgf[4*s+2] +config.matcont.mat(2*q+1, 2*s+1) *accessmixed(r, n, DOWN, config[q].tau, DOWN, 0.0)* dotgf[4*s+3] ); typename GreensFunction::Vertex v2qu(config[q].tau, UP); typename GreensFunction::Vertex v2qd(config[q].tau, DOWN); mixedupupconj -= ( config.matcont.mat(2*q, 2*s) * conj(accessmixed(r, n, UP, 0.0, UP, config[s].tau)) * dotgf[4*(q+config.size()) + 0] +config.matcont.mat(2*q, 2*s+1)* conj(accessmixed(r, n, UP, 0.0, DOWN, config[s].tau)) * dotgf[4*(q+config.size()) + 0] +config.matcont.mat(2*q+1, 2*s)* conj(accessmixed(r, n, UP, 0.0, UP, config[s].tau))* dotgf[4*(q+config.size()) + 2] +config.matcont.mat(2*q+1, 2*s+1) *conj(accessmixed(r, n, UP, 0.0, DOWN, config[s].tau))* dotgf[4*(q+config.size()) + 2] ); // mixedupdownconj -= ( // config.matcont.mat(2*q, 2*s) * conj(accessmixed(r, n, UP, 0.0, UP, config[s].tau)) * dotgf[4*(q+config.size()) + 1] // +config.matcont.mat(2*q, 2*s+1)* conj(accessmixed(r, n, UP, 0.0, DOWN, config[s].tau)) * dotgf[4*(q+config.size()) + 1] // +config.matcont.mat(2*q+1, 2*s)* conj(accessmixed(r, n, UP, 0.0, UP, config[s].tau))* dotgf[4*(q+config.size()) + 3] // +config.matcont.mat(2*q+1, 2*s+1) *conj(accessmixed(r, n, UP, 0.0, DOWN, config[s].tau))* dotgf[4*(q+config.size()) + 3] // ); // // mixeddownupconj -= ( // config.matcont.mat(2*q, 2*s) * conj(accessmixed(r, n, DOWN, 0.0, UP, config[s].tau)) * dotgf[4*(q+config.size()) + 0] // +config.matcont.mat(2*q, 2*s+1)* conj(accessmixed(r, n, DOWN, 0.0, DOWN, config[s].tau)) * dotgf[4*(q+config.size()) + 0] // +config.matcont.mat(2*q+1, 2*s)* conj(accessmixed(r, n, DOWN, 0.0, UP, config[s].tau))* dotgf[4*(q+config.size()) + 2] // +config.matcont.mat(2*q+1, 2*s+1) *conj(accessmixed(r, n, DOWN, 0.0, DOWN, config[s].tau))* dotgf[4*(q+config.size()) + 2] // ); mixeddowndownconj -= ( config.matcont.mat(2*q, 2*s) * conj(accessmixed(r, n, DOWN, 0.0, UP, config[s].tau)) * dotgf[4*(q+config.size()) + 1] +config.matcont.mat(2*q, 2*s+1)* conj(accessmixed(r, n, DOWN, 0.0, DOWN, config[s].tau)) * dotgf[4*(q+config.size()) + 1] +config.matcont.mat(2*q+1, 2*s)* conj(accessmixed(r, n, DOWN, 0.0, UP, config[s].tau))* dotgf[4*(q+config.size()) + 3] +config.matcont.mat(2*q+1, 2*s+1) *conj(accessmixed(r, n, DOWN, 0.0, DOWN, config[s].tau))* dotgf[4*(q+config.size()) + 3] ); } //add to measurement //note that this formula is the relevant one if the dot greens function and the mixed <dc> greensfunctions are spin diagonal func[k] = ( - mixedupup*mixeddowndownconj - mixeddowndown*mixedupupconj)* config.phase/4.0; //kc<<dotcontrib <<" "<< (unmixedup - unmixeddown)<<" "<<mixedupup<<" "<<mixedupupconj<<" "<< mixedupdown<<" "<<mixedupdownconj <<" "<< mixeddownup<<" "<<mixeddownupconj <<" "<< mixeddowndown<<" "<<mixeddowndownconj<<std::endl; } // exit(-1); this->add_bin(func); delete [] dotgf; return; } /** A class for measuring the hybridization: <d^\dagger_{-\sigma} a_{0,-sigma}> */ template <class Config, class GreensFunction, SPINS Spin> class Hybridization : public Network_Cache<Config, typename Config::SignType> { public: typedef typename Config::Configuration Configuration; typedef typename Configuration::FPType FPType; typedef typename Config::SignType GFRetVal; typedef GreensFunction GF; typedef std::valarray<GFRetVal> Function; typedef GFRetVal ObservableType;///<the Hybridization is only a complex number /** The Constructor for the Hybrization */ Hybridization(typename Config::Comm& net, const Parameters& params)/* throw()*/ : Network_Cache<Config, ObservableType>(net, "Hybridization"), beta(params.beta), Ny(params.Nb*2), Nx(params.Nx), Nt(400 + 1), Nw(4*Nt), delta_beta(params.beta/static_cast<FPType>(Nt-1)) { #ifdef _OPENMP double start2 = omp_get_wtime(); #endif std::cout<<"Creating Data for Hybridization"<<std::endl; const GOmegaData<FPType> *const updata = GF::gomegaup->data; const GOmegaData<FPType> *const downdata = GF::gomegadown->data; Omegadata<FPType>* omega = new Omegadata<FPType>[Nw/2]; std::complex<FPType>* gup = new std::complex<FPType>[Nw]; std::complex<FPType>* gdown = new std::complex<FPType>[Nw]; for (int t = 0; t < static_cast<int>(Nw/2); ++t) { gup[2*t] = conj((*GF::gomegaup)(t)); gup[2*t + 1] = conj((*GF::gomegaup)( -t - 1)); gdown[2*t] = conj((*GF::gomegadown)(t)); gdown[2*t + 1] = conj((*GF::gomegadown)( -t - 1)); omega[t].omega = M_PI/params.beta*(2*t + 1); omega[t].omegasq = omega[t].omega*omega[t].omega; omega[t].invomega = 1.0/omega[t].omega; } FPType pref = GF::gethybridization() / std::sqrt(params.Nx); const unsigned int Nxw = Nw*params.Nx; FPType normierungmixed = 1.0/params.beta / std::sqrt(params.Nx); const std::complex<FPType> expNt = std::exp(std::complex<FPType>(0.0, -M_PI/(Nt-1))); mixeddata = new std::complex<FPType>[2*Nt]; std::complex<FPType>* funup = new std::complex<FPType>[Nxw]; std::complex<FPType>* fundown = new std::complex<FPType>[Nxw]; memset(funup, 0, Nxw*sizeof(std::complex<FPType>)); memset(fundown, 0, Nxw*sizeof(std::complex<FPType>)); // double start = omp_get_wtime(); for (uint k = 0; k < params.Nx; ++k) { for (uint m = 0; m < Ny; ++m) { std::complex<FPType> facup = conj(updata [k*Ny + m].u) * updata[k*Ny + m].evec[0]; std::complex<FPType> facdown = conj(downdata[k*Ny + m].u) * downdata[k*Ny + m].evec[0]; for (int omega_idx = 0; omega_idx < static_cast<int>(Nw/2); ++omega_idx) {//the layout of the frequencies is now (w_n, -w_n) , that is every negative frequency is stored next to its positive counterpart. //Hopefully this gives a better data locality funup[2*omega_idx*params.Nx + k] += facup/std::complex<FPType>(-updata[k*Ny + m].lambda, -omega[omega_idx].omega); funup[(2*omega_idx + 1)*params.Nx + k] += facup/std::complex<FPType>(-updata[k*Ny + m].lambda, omega[omega_idx].omega); fundown[2*omega_idx*params.Nx + k] += facdown/std::complex<FPType>(-downdata[k*Ny + m].lambda, -omega[omega_idx].omega); fundown[(2*omega_idx + 1)*params.Nx + k] += facdown/std::complex<FPType>(-downdata[k*Ny + m].lambda, omega[omega_idx].omega); } } } // std::cout<<"time now: "<<omp_get_wtime() - start<<std::endl; for (uint w = 0; w < Nw; ++w) { fourier1(reinterpret_cast<FPType*>(funup + w*params.Nx), params.Nx, 1); fourier1(reinterpret_cast<FPType*>(fundown + w*params.Nx), params.Nx, 1); //funup as well as fundown now contain Q(r, i omega) for for n = 0 funup[w*params.Nx] *= pref; // == Q. pref == V/sqrt(L) fundown[w*params.Nx] *= pref; // == Q. pref == V/sqrt(L) } std::complex<FPType> expt = 1; for(uint t = 0; t < Nt; ++t)// here is the final Matsubara transform { std::complex<FPType> tempupmixed = 0; std::complex<FPType> tempdownmixed = 0; std::complex<FPType> expiom = expt; std::complex<FPType> expfac = expiom*expiom; for (int omega_idx = 0; omega_idx < static_cast<int>(Nw/2); ++omega_idx) { std::complex<FPType> gupp = gup[2*omega_idx]; std::complex<FPType> gupm = gup[2*omega_idx + 1]; std::complex<FPType> gdownp = gdown[2*omega_idx]; std::complex<FPType> gdownm = gdown[2*omega_idx + 1]; std::complex<FPType> cexpiom = conj(expiom); tempupmixed += cexpiom * funup[(2*omega_idx)*params.Nx] * gupp + expiom * funup[(2*omega_idx + 1)*params.Nx] * gupm; tempdownmixed += cexpiom * fundown[(2*omega_idx)*params.Nx] * gdownp + expiom * fundown[(2*omega_idx + 1)*params.Nx] * gdownm; expiom *= expfac; } mixeddata[t] = tempupmixed*normierungmixed; (mixeddata + Nt)[t] = tempdownmixed*normierungmixed; expt *= expNt; } // std::cout<<"Initialization took "<<omp_get_wtime() - start<<" seconds"<<std::endl; delete [] funup; delete [] fundown; #ifdef _OPENMP std::cout<<"Initialization took "<<omp_get_wtime() - start2<<" seconds"<<std::endl; #endif std::ofstream file("goff.txt"); for(uint k = 0; k < Nt; ++k) file<<mixeddata[k]<<std::endl; delete [] gup; delete [] gdown; delete [] omega; std::cout<<"Hybridization done"<<std::endl; } void dryrun(DryRun<typename Configuration::value_type, GFRetVal>& func) { } /** this determines the Hybridization for a given order @param configuration the configuration */ inline void evaluate(const Configuration&, const DoWick<typename Configuration::value_type, GFRetVal>&); private: const FPType beta; std::complex<FPType>* mixeddata;///< here we store <d^+ gamma>. const uint Ny; const uint Nx; const uint Nt; const uint Nw; const FPType delta_beta; std::complex<FPType> accessmixed(SPINS spin1, FPType tau1 , SPINS spin2, FPType tau2) const { FPType delta_tau = tau1 - tau2; FPType sign = 1.0; std::complex<FPType>* dataptr = mixeddata; if(spin1 != spin2) return 0.0;//FIXME!!!!!!!!!!!!!!!!!!!! only the case for the spin symmetric case! if (spin1 == DOWN) dataptr += Nt; if(std::abs(delta_tau) < std::numeric_limits<FPType>::epsilon()) return std::complex<FPType>(dataptr[0]); if(delta_tau < 0) { sign = -1.0; delta_tau += beta; } FPType fptau_idx0; FPType rem = std::modf(delta_tau/delta_beta, &fptau_idx0);//round to the smaller index and determine how far we're off. std::size_t tau_idx0 = lround(fptau_idx0); return std::complex<FPType>(lerp(rem, dataptr[tau_idx0], dataptr[tau_idx0 + 1]))*sign; } }; template <class Config, class GreensFunction, SPINS Spin> void Hybridization<Config, GreensFunction, Spin>::evaluate(const Configuration& config, const DoWick<typename Configuration::value_type, GFRetVal>& dowick) { ObservableType retval = accessmixed(!Spin, 0, !Spin, 0); struct GDot{GFRetVal operator() (FPType tau2, SPINS spin2){return GreensFunction::eval(typename GreensFunction::Vertex(0, !Spin), typename GreensFunction::Vertex(tau2, spin2));} } gdot; for(uint q = 0; q < config.size(); ++q) for(uint s = 0; s < config.size(); ++s) { retval -= ( config.matcont.mat(2*q, 2*s) * accessmixed(UP, config[q].tau, !Spin, 0.0) * gdot(config[s].tau, UP) +config.matcont.mat(2*q, 2*s+1)* accessmixed(UP, config[q].tau, !Spin, 0.0) * gdot(config[s].tau, DOWN) +config.matcont.mat(2*q+1, 2*s)* accessmixed(DOWN, config[q].tau, !Spin, 0.0)* gdot(config[s].tau, UP) +config.matcont.mat(2*q+1, 2*s+1)*accessmixed(DOWN, config[q].tau, !Spin, 0.0)* gdot(config[s].tau, DOWN) ); } //add to measurement this->add_bin(retval*config.phase); return; } /** * Depending on s this measures the charge charge( s=1) correlation function or the spin-spin (s=-1) correlation function * Note also that by its bare definition it is a real quantity. * */ template <class Config, int s> class SpinChargeParent : public Network_Cache<Config, std::valarray<std::valarray<typename Config::Configuration::FPType> > > { public: typedef typename Config::Configuration Configuration; typedef typename Configuration::FPType FPType; typedef typename Config::SignType GFRetVal; typedef std::valarray<FPType> Function; typedef std::valarray<Function> ObservableType;///< spin and charge correlations are potentially complex in kspace and are spatially resolved time-dependent observable /** The Constructor */ SpinChargeParent(typename Config::Comm& n, const Parameters& params) throw() : Network_Cache<Config,ObservableType>(n, (s==1)?"CharcheChargeCorrelation":"SpinSpinCorrelation"), len(params.N), functionpoints(params.functionpoints), delta_s(params.delta_s) { } void dryrun(DryRun<typename Configuration::value_type, GFRetVal>&); /** this determines the observable for a given order @param configuration the configuration */ inline void evaluate(const Configuration&, const DoWick<typename Configuration::value_type, GFRetVal>&); private: const uint32_t& len; const uint32_t& functionpoints; const double delta_s; }; template <class Config, int cs> void SpinChargeParent<Config, cs>::dryrun(DryRun<typename Configuration::value_type, GFRetVal>& func) { const typename Configuration::value_type v2(0, 0, UP); const typename Configuration::value_type v4(0, 0, DOWN); for (unsigned int j = 0; j < functionpoints; ++j) { FPType s = j * delta_s; if(j == 0) s = 0.000001;//seems to be necessary here... for(uint r = 0; r < len; ++r) { const typename Configuration::value_type v1(r, s, UP); const typename Configuration::value_type v3(r, s, DOWN); genericTwoParticleGreensfunction_dry<Configuration>(func, v1, v1, v2, v2); genericTwoParticleGreensfunction_dry<Configuration>(func, v3, v3, v4, v4); genericTwoParticleGreensfunction_dry<Configuration>(func, v1, v1, v4, v4); genericTwoParticleGreensfunction_dry<Configuration>(func, v3, v3, v2, v2); } } return; } template <typename T> struct Help { typedef T RetType; static inline RetType toreal(T a) { return a; } }; template <typename FPType> struct Help<std::complex<FPType> > { typedef FPType RetType; static inline RetType toreal(std::complex<FPType> a) { return a.real(); } }; template <class Config, int cs> void SpinChargeParent<Config, cs>::evaluate(const Configuration& configuration, const DoWick<typename Configuration::value_type, GFRetVal>& dowick) { ObservableType func(len); const FPType fac = static_cast<FPType>(TWOPI / len); const FPType csfac = (cs == 1? 1.0: 0.25);//switch prefactors const typename Config::SignType phase_factor = configuration.phase * csfac; const typename Configuration::value_type v2(0, 0, UP); const typename Configuration::value_type v4(0, 0, DOWN); for (unsigned int k = 0; k < len; ++k) { func[k].resize(functionpoints); for (unsigned int j = 0; j < functionpoints; ++j) { FPType s = j * delta_s; if(j == 0) s = 0.000001;//seems to be necessary here, to get the correct function value at tau=0... GFRetVal sum = 0; for(uint r = 0; r < len; ++r) { FPType pref = std::cos(fac * (k*r)); const typename Configuration::value_type v1(r, s, UP); const typename Configuration::value_type v3(r, s, DOWN); auto sum2 = genericTwoParticleGreensfunction<Configuration>(dowick, v1, v1, v2, v2);//to deduce type sum2 += genericTwoParticleGreensfunction<Configuration>(dowick, v3, v3, v4, v4) + FPType(cs)*(genericTwoParticleGreensfunction<Configuration>(dowick, v1, v1, v4, v4) + genericTwoParticleGreensfunction<Configuration>(dowick, v3, v3, v2, v2)); sum += pref * sum2; } func[k][j] = Help<GFRetVal>::toreal(phase_factor * sum);//normalization not necessary since the 1/N factor is already in the definition of G_0 } } this->add_bin(func); return; } /** * This measures <S^+(k, tau) S^-(0,0)> which is due to translation symmetry the same as <S^+(k,tau), S^-(k,0)> * Note also that by its bare definition it is a real quantity. * */ template <class Config> class SplusSminus : public Network_Cache<Config, std::valarray<std::valarray<typename Config::Configuration::FPType> > > { public: typedef typename Config::Configuration Configuration; typedef typename Configuration::FPType FPType; typedef typename Config::SignType GFRetVal; typedef std::valarray<FPType> Function;///< SplusSminus is a real quantity typedef std::valarray<Function> ObservableType;///< spin and charge correlations are potentially complex in kspace and are spatially resolved time-dependent observable /** The Constructor */ SplusSminus(typename Config::Comm& n, const Parameters& params) throw() : Network_Cache<Config,ObservableType>(n, "SplusSminus"), len(params.N), functionpoints(params.functionpoints), delta_s(params.delta_s) { } void dryrun(DryRun<typename Configuration::value_type, GFRetVal>&); /** this determines the observable for a given order @param configuration the configuration */ inline void evaluate(const Configuration&, const DoWick<typename Configuration::value_type, GFRetVal>&); private: const uint32_t& len; const uint32_t& functionpoints; const double delta_s; }; template <class Config> void SplusSminus<Config>::dryrun(DryRun<typename Configuration::value_type, GFRetVal>& func) { const typename Configuration::value_type v2(0, 0, UP); const typename Configuration::value_type v4(0, 0, DOWN); // func(v4, v2); for (unsigned int j = 0; j < functionpoints; ++j) { FPType s = j * delta_s; if(j == 0) s = 0.000001; for(uint r = 0; r < len; ++r) { const typename Configuration::value_type v1(r, s, UP); const typename Configuration::value_type v3(r, s, DOWN); // func.template onSector<UP>(r, s, 0,0); // func.template onSector<DOWN>(0, 0, r, s); /*func(v1, v3); func(v1, v2); func(v4, v3);*/ genericTwoParticleGreensfunction_dry<Configuration>(func, v1, v3, v4, v2); } } return; } template <class Config> void SplusSminus<Config>::evaluate(const Configuration& configuration, const DoWick<typename Configuration::value_type, GFRetVal>& dowick) { ObservableType func(len); FPType invlen = 1.0/len; const FPType fac = TWOPI * invlen; const typename Configuration::value_type v2(0, 0, UP); const typename Configuration::value_type v4(0, 0, DOWN); // auto constres = dowick(v4, v2); for (unsigned int k = 0; k < len; ++k) { func[k].resize(functionpoints); for (unsigned int j = 0; j < functionpoints; ++j) { FPType s = j * delta_s; if(j == 0) s = 0.000001;//seems to be necessary here... GFRetVal sum = 0; for(uint r = 0; r < len; ++r) { FPType pref = std::cos(fac * (k*r)); const typename Configuration::value_type v1(r, s, UP); const typename Configuration::value_type v3(r, s, DOWN); auto sum2 = // dowick(v1, v3) * constres - dowick(v1, v2) * dowick(v4, v3); //dowick.template onSector<UP>(r, s, 0,0) * dowick.template onSector<DOWN>(0, 0, r, s); genericTwoParticleGreensfunction<Configuration>(dowick, v1, v3, v4, v2); sum += pref * sum2; } func[k][j] = Help<GFRetVal>::toreal(configuration.phase * sum);//normalization not necessary since the 1/N factor is already in the definition of G_0 } } this->add_bin(func); return; } #endif
r_numint.c
/* * Author: Qiming Sun <osirpt.sun@gmail.com> */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <complex.h> #include "cint.h" #include "gto/grid_ao_drv.h" #include "np_helper/np_helper.h" #include "vhf/fblas.h" #include <assert.h> #define BOXSIZE 56 int VXCao_empty_blocks(char *empty, unsigned char *non0table, int *shls_slice, int *ao_loc); static void dot_ao_dm(double complex *vm, double complex *ao, double complex *dm, int nao, int nocc, int ngrids, int bgrids, unsigned char *non0table, int *shls_slice, int *ao_loc) { int nbox = (nao+BOXSIZE-1) / BOXSIZE; char empty[nbox]; int has0 = VXCao_empty_blocks(empty, non0table, shls_slice, ao_loc); const char TRANS_T = 'T'; const char TRANS_N = 'N'; const double complex Z1 = 1; double complex beta = 0; if (has0) { int box_id, bas_id, b0, blen, i, j; for (box_id = 0; box_id < nbox; box_id++) { if (!empty[box_id]) { b0 = box_id * BOXSIZE; blen = MIN(nao-b0, BOXSIZE); zgemm_(&TRANS_N, &TRANS_T, &bgrids, &nocc, &blen, &Z1, ao+b0*ngrids, &ngrids, dm+b0*nocc, &nocc, &beta, vm, &ngrids); beta = 1.0; } } if (beta == 0) { // all empty for (i = 0; i < nocc; i++) { for (j = 0; j < bgrids; j++) { vm[i*ngrids+j] = 0; } } } } else { zgemm_(&TRANS_N, &TRANS_T, &bgrids, &nocc, &nao, &Z1, ao, &ngrids, dm, &nocc, &beta, vm, &ngrids); } } /* vm[nocc,ngrids] = ao[i,ngrids] * dm[i,nocc] */ void VXCzdot_ao_dm(double complex *vm, double complex *ao, double complex *dm, int nao, int nocc, int ngrids, int nbas, unsigned char *non0table, int *shls_slice, int *ao_loc) { const int nblk = (ngrids+BLKSIZE-1) / BLKSIZE; #pragma omp parallel default(none) \ shared(vm, ao, dm, nao, nocc, ngrids, nbas, \ non0table, shls_slice, ao_loc) { int ip, ib; #pragma omp for nowait schedule(static) for (ib = 0; ib < nblk; ib++) { ip = ib * BLKSIZE; dot_ao_dm(vm+ip, ao+ip, dm, nao, nocc, ngrids, MIN(ngrids-ip, BLKSIZE), non0table+ib*nbas, shls_slice, ao_loc); } } } /* conj(vv[n,m]) = ao1[n,ngrids] * conj(ao2[m,ngrids]) */ static void dot_ao_ao(double complex *vv, double complex *ao1, double complex *ao2, int nao, int ngrids, int bgrids, int hermi, unsigned char *non0table, int *shls_slice, int *ao_loc) { int nbox = (nao+BOXSIZE-1) / BOXSIZE; char empty[nbox]; int has0 = VXCao_empty_blocks(empty, non0table, shls_slice, ao_loc); const char TRANS_C = 'C'; const char TRANS_N = 'N'; const double complex Z1 = 1; if (has0) { int ib, jb, b0i, b0j, leni, lenj; int j1 = nbox; for (ib = 0; ib < nbox; ib++) { if (!empty[ib]) { b0i = ib * BOXSIZE; leni = MIN(nao-b0i, BOXSIZE); if (hermi) { j1 = ib + 1; } for (jb = 0; jb < j1; jb++) { if (!empty[jb]) { b0j = jb * BOXSIZE; lenj = MIN(nao-b0j, BOXSIZE); zgemm_(&TRANS_C, &TRANS_N, &lenj, &leni, &bgrids, &Z1, ao2+b0j*ngrids, &ngrids, ao1+b0i*ngrids, &ngrids, &Z1, vv+b0i*nao+b0j, &nao); } } } } } else { zgemm_(&TRANS_C, &TRANS_N, &nao, &nao, &bgrids, &Z1, ao2, &ngrids, ao1, &ngrids, &Z1, vv, &nao); } } /* vv[nao,nao] = conj(ao1[i,nao]) * ao2[i,nao] */ void VXCzdot_ao_ao(double complex *vv, double complex *ao1, double complex *ao2, int nao, int ngrids, int nbas, int hermi, unsigned char *non0table, int *shls_slice, int *ao_loc) { const int nblk = (ngrids+BLKSIZE-1) / BLKSIZE; memset(vv, 0, sizeof(double complex) * nao * nao); #pragma omp parallel default(none) \ shared(vv, ao1, ao2, nao, ngrids, nbas, hermi, \ non0table, shls_slice, ao_loc) { int ip, ib; double complex *v_priv = calloc(nao*nao, sizeof(double complex)); #pragma omp for nowait schedule(static) for (ib = 0; ib < nblk; ib++) { ip = ib * BLKSIZE; dot_ao_ao(v_priv, ao1+ip, ao2+ip, nao, ngrids, MIN(ngrids-ip, BLKSIZE), hermi, non0table+ib*nbas, shls_slice, ao_loc); } #pragma omp critical { for (ip = 0; ip < nao*nao; ip++) { vv[ip] += conj(v_priv[ip]); } } free(v_priv); } if (hermi != 0) { NPzhermi_triu(nao, vv, hermi); } }