source stringlengths 3 92 | c stringlengths 26 2.25M |
|---|---|
vdi_fmt_plug.c | /* VirtualBox (VDI) volume support to John The Ripper
*
* Written by JimF <jfoug at openwall.net> in 2015. No copyright
* is claimed, and the software is hereby placed in the public domain.
* In case this attempt to disclaim copyright and place the software in the
* public domain is deemed null and void, then the software is
* Copyright (c) 2015 JimF 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.
*
* There's ABSOLUTELY NO WARRANTY, express or implied.
*
* information about this algorithm taken from:
* http://www.sinfocol.org/archivos/2015/07/VBOXDIECracker.phps
*/
#include "arch.h"
#if FMT_EXTERNS_H
extern struct fmt_main fmt_vdi;
#elif FMT_REGISTERS_H
john_register_one(&fmt_vdi);
#else
#include "aes_xts.h"
#include <string.h>
#include "misc.h"
#include "memory.h"
#include "common.h"
#include "formats.h"
#include "crc32.h"
#include "johnswap.h"
#include "base64_convert.h"
#include "pbkdf2_hmac_sha256.h"
#ifdef _OPENMP
#include <omp.h>
#ifndef OMP_SCALE
#ifdef __MIC__
#define OMP_SCALE 16
#else
#define OMP_SCALE 4
#endif // __MIC__
#endif // OMP_SCALE
#endif // _OPENMP
#include "memdbg.h"
#define PLAINTEXT_LENGTH 125
#define SALT_SIZE sizeof(struct vdi_salt)
#define SALT_ALIGN 4
#define BINARY_SIZE 32
#define BINARY_ALIGN 4
#define MAX_SALT_LEN 32
#define MAX_KEY_LEN 64
#define FORMAT_LABEL "vdi"
#define FORMAT_NAME "VirtualBox-VDI AES_XTS"
#define FORMAT_TAG "$vdi$"
#define FORMAT_TAG_LEN (sizeof(FORMAT_TAG)-1)
#define ALGORITHM_NAME "PBKDF2-SHA256 " SHA256_ALGORITHM_NAME " + AES_XTS"
#if SSE_GROUP_SZ_SHA256
#define MIN_KEYS_PER_CRYPT SSE_GROUP_SZ_SHA256
#define MAX_KEYS_PER_CRYPT SSE_GROUP_SZ_SHA256
#else
#define MIN_KEYS_PER_CRYPT 1
#define MAX_KEYS_PER_CRYPT 1
#endif
static unsigned char (*key_buffer)[PLAINTEXT_LENGTH + 1];
static unsigned char (*crypt_out)[MAX_SALT_LEN];
static struct fmt_tests tests[] = {
// The 'jtr' test hashed were made with VirtualBox. The others were made with pass_gen.pl
{"$vdi$aes-xts256$sha256$2000$2000$64$32$709f6df123f1ccb126ea1f3e565beb78d39cafdc98e0daa2e42cc43cef11f786$0340f137136ad54f59f4b24ef0bf35240e140dfd56bbc19ce70aee6575f0aabf$0a27e178f47a0b05a752d6e917b89ef4205c6ae76705c34858390f8afa6cf03a45d98fab53b76d8d1c68507e7810633db4b83501a2496b7e443eccb53dbc8473$7ac5f4ad6286406e84af31fd36881cf558d375ae29085b08e6f65ebfd15376ca", "jtr"},
{"$vdi$aes-xts256$sha256$2000$2000$64$32$d72ee0aecd496b084117bb8d87f5e37de71973518a2ef992c895907a09b73b83$afb33e56a7f81b1e3db70f599b62ecf3d223405abb63bcf569bb29acab9c81a6$3b3769fd3cfaf8e11f67fdc9d54aed8c8962a769f3f66cb2b9cb8700c01a66e6b1c996fdee9727188c765bde224047b8ced7a9b5f5381e7ad7271a9cbf049fde$1c5bca64cbedd76802eddc3e6ffd834e8c1f1ff1157de6ae6feb3740051e2cfa", "password"},
{"$vdi$aes-xts256$sha256$2000$2000$64$32$a4e4480927153ecbb7509afb8d49468e62c8bb22aaab458f4115bff63364de41$c69605220d1ed03618f0236a88e225db1ec69e7a95dbe63ee00778cc8b91424e$0a1de9c85452fafd19ceb0821a115c7fec6fab4ef51fc57fabc25bf973417684a78683267513923f88231a6efd2442ce9279f2a5614d4cfcb930b5ef413f34c3$d79ea5522ad79fc409bbcd1e8a2bb75e16a53e1eef940b4fe954cee1c2491fd2", "ripper"},
{"$vdi$aes-xts256$sha256$2000$2000$64$32$450ce441592003821931e73ea314dcd0effff1b74b61a8fc4046573d0f448057$18c48e3d7677bc9471607cec83d036b963f23f7bb16f09ea438395b61dcf14d5$c4893bce14fa3a1f915004b9ec0fd6a7215ddebdd2ca4bc2b4ec164253c2f2319685a8f8245ec8e2d9e7a53c6aec5fd2d4ca7ba510ffc7456a72285d40ce7d35$793e58317b9bf6318d1b4cef1e05f5a8579a50fb7efde884ea68b096b7043aad", "john"},
{"$vdi$aes-xts256$sha256$2000$2000$64$32$472476df7d16f80d612d4c9ff35678a2011605dc98b76b6d78632859c259d5d0$aa89f9bea1139da6ace97e13c823d713030fda0c8c55ad2fcea358746cc0b4cc$507aaf7c9e00b492042072a17b3975fc88e30e1d5927e63cb335c630b7b873e4c9af2df63c95b42896e15bb33c37c9f572a65f97441b3707ce5d81c521dfd30e$111004a8d9167b55ff5db510cc136f2bceacf4a9f50807742e2bbc110847174e", "really long password with ! stuff!!! ;)"},
// some aes-128 samples They run exactly same speed as the AES-256 hashes.
{"$vdi$aes-xts128$sha256$2000$2000$32$32$d3fd2bb27734f25918ac726717b192091253441c4bc71a814d0a6483e73325ea$ef560858b4c068bd8d994cdf038f51cb1b9f59335d72cb874e79a13c5b6aa84a$79ff000f7638d39b0d02ad08dfcede8740087e334e98022465a380bdf78fff13$302f4c4f58c0dee9676dfdaf3ada9e3d7ec4b5bfc7e6565c941f4ec7337368d4", "jtr"},
{"$vdi$aes-xts128$sha256$2000$2000$32$32$16894e7496bac97bc467faa3efe5a3ba009e1591990c9422e4352bfb39ead4d6$00780af3703680b63239b61d0395e9ff673ee843d7a77d61541e0fdc096c49d1$72434a81a27bb1cd85be529600c3620e4eeed45d12f8ef337cc51c040306be7d$4a5b2129577289a8a0f6a93d7a578cd248d158bc70d6ab89f5ccf31704812e85", "blowhard"},
{"$vdi$aes-xts128$sha256$2000$2000$32$32$4e9d103c944479a4e2b2e33d4757e11fc1a7263ba3b2e99d9ad4bc9aeb7f9337$ade43b6eb1d878f0a5532070fb81697a8164ff7b9798e35649df465068ae7e81$f1e443252c872e305eda848d05676a20af8df405262984b39baf0f0aa1b48247$2601e9e08d19ca20745a6a33f74259bdca06014455370b0bb6b79eb0c5e60581", "foobar"},
{NULL}
};
static struct vdi_salt {
unsigned char salt1[MAX_SALT_LEN];
unsigned char salt2[MAX_SALT_LEN];
unsigned char encr[MAX_KEY_LEN];
int crypt_type; // 1, 256, 384, 512 for the pbkdf2 algo (currently ONLY 256 implemented, so that is all we handle right now).
int evp_type; // 128 or 256 for AES-128XTS or AES-256XTS
int rounds1;
int rounds2;
int keylen;
int saltlen;
} *psalt;
static void init(struct fmt_main *self)
{
#ifdef _OPENMP
int 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
key_buffer = mem_calloc(self->params.max_keys_per_crypt,
sizeof(*key_buffer));
crypt_out = mem_calloc(self->params.max_keys_per_crypt,
sizeof(*crypt_out));
}
static void done(void)
{
MEM_FREE(key_buffer);
MEM_FREE(crypt_out);
}
static int valid(char* ciphertext, struct fmt_main *self)
{
char *ctcopy, *keeptr;
int keylen;
int saltlen;
char *p;
if (strncmp(ciphertext, FORMAT_TAG, FORMAT_TAG_LEN))
return 0;
ctcopy = strdup(ciphertext + FORMAT_TAG_LEN);
keeptr = ctcopy;
if ((p = strtokm(ctcopy, "$")) == NULL) /* decr type*/
goto err;
if (strcmp(p, "aes-xts256") && strcmp(p, "aes-xts128"))
goto err;
if ((p = strtokm(NULL, "$")) == NULL) /* pbkdf2 algo */
goto err;
//if (strcmp(p, "sha1") && strcmp(p, "sha256") && strcmp(p, "sha384") && strcmp(p, "sha512"))
if (strcmp(p, "sha256"))
goto err;
if ((p = strtokm(NULL, "$")) == NULL) /* pbkdf2-1 iterations */
goto err;
if (!isdec(p))
goto err;
if ((p = strtokm(NULL, "$")) == NULL) /* pbkdf2-2 iterations */
goto err;
if (!isdec(p))
goto err;
if ((p = strtokm(NULL, "$")) == NULL) /* key length */
goto err;
if (!isdec(p))
goto err;
keylen = atoi(p);
if(keylen > MAX_KEY_LEN)
goto err;
if ((p = strtokm(NULL, "$")) == NULL) /* salt length */
goto err;
if (!isdec(p))
goto err;
saltlen = atoi(p);
if(saltlen > MAX_SALT_LEN)
goto err;
if ((p = strtokm(NULL, "$")) == NULL) /* salt1 */
goto err;
if(strlen(p) != saltlen * 2)
goto err;
if(!ishexlc(p))
goto err;
if ((p = strtokm(NULL, "$")) == NULL) /* salt2 */
goto err;
if(strlen(p) != saltlen * 2)
goto err;
if(!ishexlc(p))
goto err;
if ((p = strtokm(NULL, "$")) == NULL) /* encr_key */
goto err;
if(strlen(p) != keylen * 2)
goto err;
if(!ishexlc(p))
goto err;
if ((p = strtokm(NULL, "$")) == NULL) /* final_result */
goto err;
if(strlen(p) != saltlen * 2)
goto err;
if(!ishexlc(p))
goto err;
if ((p = strtokm(NULL, "$")) != NULL)
goto err;
MEM_FREE(keeptr);
return 1;
err:
MEM_FREE(keeptr);
return 0;
}
static void set_salt(void *salt)
{
psalt = salt;
}
static void* get_salt(char *ciphertext)
{
static char buf[sizeof(struct vdi_salt)+4];
struct vdi_salt *s = (struct vdi_salt *)mem_align(buf, 4);
char *ctcopy, *keeptr;
char *p;
memset(buf, 0, sizeof(buf));
ctcopy = strdup(ciphertext + FORMAT_TAG_LEN);
keeptr = ctcopy;
p = strtokm(ctcopy, "$"); /* decr type*/
s->evp_type = !strcmp(p, "aes-xts128") ? 128 : 256;
p = strtokm(NULL, "$"); /* pbkdf2 algo */
s->crypt_type = 256; /* right now, we ONLY handle pbkdf2-sha256 */
p = strtokm(NULL, "$"); /* pbkdf2-1 iterations */
s->rounds1 = atoi(p);
p = strtokm(NULL, "$"); /* pbkdf2-2 iterations */
s->rounds2 = atoi(p);
p = strtokm(NULL, "$"); /* key length */
s->keylen = atoi(p);
p = strtokm(NULL, "$"); /* salt length */
s->saltlen = atoi(p);
p = strtokm(NULL, "$"); /* salt1 */
base64_convert(p, e_b64_hex, s->saltlen*2, s->salt1, e_b64_raw, s->saltlen, 0, 0);
p = strtokm(NULL, "$"); /* salt2 */
base64_convert(p, e_b64_hex, s->saltlen*2, s->salt2, e_b64_raw, s->saltlen, 0, 0);
p = strtokm(NULL, "$"); /* encr_key */
base64_convert(p, e_b64_hex, s->keylen*2, s->encr, e_b64_raw, s->keylen, 0, 0);
MEM_FREE(keeptr);
return s;
}
static int crypt_all(int *pcount, struct db_salt *salt)
{
int i;
int inc=1;
const int count = *pcount;
#if SSE_GROUP_SZ_SHA256
inc = SSE_GROUP_SZ_SHA256;
#endif
#ifdef _OPENMP
#pragma omp parallel for
#endif
for(i = 0; i < count; i += inc)
{
unsigned char key[MAX_KEY_LEN];
#if SSE_GROUP_SZ_SHA256
unsigned char Keys[SSE_GROUP_SZ_SHA256][MAX_KEY_LEN];
unsigned char Decr[SSE_GROUP_SZ_SHA256][MAX_KEY_LEN];
#else
unsigned char Decr[1][MAX_KEY_LEN];
int ksz = strlen((char *)key_buffer[i]);
#endif
int j;
#if SSE_GROUP_SZ_SHA256
int lens[SSE_GROUP_SZ_SHA256];
unsigned char *pin[SSE_GROUP_SZ_SHA256];
union {
unsigned char *pout[SSE_GROUP_SZ_SHA256];
unsigned char *poutc;
} x;
for (j = 0; j < SSE_GROUP_SZ_SHA256; ++j) {
lens[j] = strlen((char*)(key_buffer[i+j]));
pin[j] = key_buffer[i+j];
x.pout[j] = Keys[j];
}
pbkdf2_sha256_sse((const unsigned char **)pin, lens, psalt->salt1, psalt->saltlen, psalt->rounds1, &(x.poutc), psalt->keylen, 0);
#else
pbkdf2_sha256((const unsigned char*)key_buffer[i], ksz, psalt->salt1, psalt->saltlen, psalt->rounds1, key, psalt->keylen, 0);
#endif
for (j = 0; j < inc; ++j) {
#if SSE_GROUP_SZ_SHA256
memcpy(key, Keys[j], sizeof(key));
#endif
// Try to decrypt using AES
AES_XTS_decrypt(key, Decr[j], psalt->encr, psalt->keylen, psalt->evp_type);
}
#if SSE_GROUP_SZ_SHA256
for (j = 0; j < SSE_GROUP_SZ_SHA256; ++j) {
lens[j] = psalt->keylen;
pin[j] = Decr[j];
x.pout[j] = crypt_out[i+j];
}
pbkdf2_sha256_sse((const unsigned char **)pin, lens, psalt->salt2, psalt->saltlen, psalt->rounds2, &(x.poutc), psalt->saltlen, 0);
#else
pbkdf2_sha256(Decr[0], psalt->keylen, psalt->salt2, psalt->saltlen, psalt->rounds2, crypt_out[i], psalt->saltlen, 0);
#endif
}
return count;
}
static int cmp_all(void *binary, int count)
{
int index = 0;
for (; index < count; index++)
if (!memcmp(binary, crypt_out[index], 4))
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 set_key(char* key, int index)
{
strcpy((char*)(key_buffer[index]), key);
}
static char *get_key(int index)
{
return (char*)(key_buffer[index]);
}
static int salt_hash(void *salt)
{
unsigned v=0, i;
unsigned char *psalt = (unsigned char *)salt;
psalt += 40; // skips us to the salt stuff.
for (i = 0; i < 64; ++i) {
v *= 11;
v += psalt[i];
}
return v & (SALT_HASH_SIZE - 1);
}
static void *binary(char *ciphertext) {
static ARCH_WORD_32 full[MAX_SALT_LEN / 4];
unsigned char *realcipher = (unsigned char*)full;
ciphertext = strrchr(ciphertext, '$') + 1;
base64_convert(ciphertext, e_b64_hex, strlen(ciphertext), realcipher, e_b64_raw, MAX_SALT_LEN, 0, 0);
return (void*)realcipher;
}
struct fmt_main fmt_vdi = {
{
FORMAT_LABEL,
FORMAT_NAME,
ALGORITHM_NAME,
"", // BENCHMARK_COMMENT
-1, // 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 },
{ FORMAT_TAG },
tests
}, {
init,
done,
fmt_default_reset,
fmt_default_prepare,
valid,
fmt_default_split,
binary,
get_salt,
{ NULL },
fmt_default_source,
{
fmt_default_binary_hash
},
salt_hash,
NULL,
set_salt,
set_key,
get_key,
fmt_default_clear_keys,
crypt_all,
{
fmt_default_get_hash
},
cmp_all,
cmp_one,
cmp_exact
}
};
#endif /* plugin stanza */
|
stream.c | // Copyright 2009-2018 NTESS. Under the terms
// of Contract DE-NA0003525 with NTESS, the U.S.
// Government retains certain rights in this software.
//
// Copyright (c) 2009-2018, NTESS
// All rights reserved.
//
// Portions are copyright of other developers:
// See the file CONTRIBUTORS.TXT in the top level directory
// the distribution for more information.
//
// This file is part of the SST software package. For license
// information, see the LICENSE file in the top level directory of the
// distribution.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char* argv[]) {
const int LENGTH = 2000;
printf("\n\n\nHello CramSim!!!!\n");
printf("Run a stream application with ariel and cramsim\n");
printf("------------------------------------------------------\n");
printf("Allocating arrays of size %d elements.\n", LENGTH);
double* a = (double*) malloc(sizeof(double) * LENGTH);
double* b = (double*) malloc(sizeof(double) * LENGTH);
double* c = (double*) malloc(sizeof(double) * LENGTH);
printf("Done allocating arrays.\n");
int i;
for(i = 0; i < LENGTH; ++i) {
a[i] = i;
b[i] = LENGTH - i;
c[i] = 0;
}
printf("Perfoming the fast_c compute loop...\n");
#pragma omp parallel for
for(i = 0; i < LENGTH; ++i) {
//printf("issuing a write to: %llu (fast_c)\n", ((unsigned long long int) &fast_c[i]));
c[i] = 2.0 * a[i] + 1.5 * b[i];
}
double sum = 0;
for(i = 0; i < LENGTH; ++i) {
sum += c[i];
}
printf("Sum of arrays is: %f\n", sum);
printf("Freeing arrays...\n");
free(a);
free(b);
free(c);
printf("Done.\n");
}
|
ab-totient-omp-2.c | // Distributed and parallel technologies, Andrew Beveridge, 03/03/2014
// To Compile: gcc -Wall -O -o ab-totient-omp -fopenmp ab-totient-omp.c
// To Run / Time: /usr/bin/time -v ./ab-totient-omp range_start range_end
#include <stdio.h>
#include <omp.h>
/* When input is a prime number, the totient is simply the prime number - 1. Totient is always even (except for 1).
If n is a positive integer, then φ(n) is the number of integers k in the range 1 ≤ k ≤ n for which gcd(n, k) = 1 */
long getTotient (long number) {
long result = number;
// Check every prime number below the square root for divisibility
if(number % 2 == 0){
result -= result / 2;
do
number /= 2;
while(number %2 == 0);
}
// Primitive replacement for a list of primes, looping through every odd number
long prime;
for(prime = 3; prime * prime <= number; prime += 2){
if(number %prime == 0){
result -= result / prime;
do
number /= prime;
while(number % prime == 0);
}
}
// Last common factor
if(number > 1)
result -= result / number;
// Return the result.
return result;
}
// Main method.
int main(int argc, char ** argv) {
// Load inputs
long lower, upper;
sscanf(argv[1], "%ld", &lower);
sscanf(argv[2], "%ld", &upper);
int i;
long result = 0.0;
// We know the answer if it's 1; no need to execute the function
if(lower == 1) {
result = 1.0;
lower = 2;
}
#pragma omp parallel for default(shared) private(i) schedule(auto) reduction(+:result) num_threads(2)
// Sum all totients in the specified range
for (i = lower; i <= upper; i++) {
result = result + getTotient(i);
}
// Print the result
printf("Sum of Totients between [%ld..%ld] is %ld \n", lower, upper, result);
// A-OK!
return 0;
}
|
GB_unaryop__minv_int8_bool.c | //------------------------------------------------------------------------------
// GB_unaryop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved.
// http://suitesparse.com See GraphBLAS/Doc/License.txt for license.
//------------------------------------------------------------------------------
// If this file is in the Generated/ folder, do not edit it (auto-generated).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_iterator.h"
#include "GB_unaryop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB_unop__minv_int8_bool
// op(A') function: GB_tran__minv_int8_bool
// C type: int8_t
// A type: bool
// cast: int8_t cij = (int8_t) aij
// unaryop: cij = GB_IMINV_SIGNED (aij, 8)
#define GB_ATYPE \
bool
#define GB_CTYPE \
int8_t
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
bool aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = GB_IMINV_SIGNED (x, 8) ;
// casting
#define GB_CASTING(z, aij) \
int8_t z = (int8_t) aij ;
// cij = op (cast (aij))
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
GB_GETA (aij, Ax, pA) ; \
/* Cx [pC] = op (cast (aij)) */ \
GB_CASTING (z, aij) ; \
GB_OP (GB_CX (pC), z) ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_MINV || GxB_NO_INT8 || GxB_NO_BOOL)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop__minv_int8_bool
(
int8_t *Cx, // Cx and Ax may be aliased
bool *Ax,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
GB_CAST_OP (p, p) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_tran__minv_int8_bool
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t *GB_RESTRICT *Rowcounts,
GBI_single_iterator Iter,
const int64_t *GB_RESTRICT A_slice,
int naslice
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#define GB_PHASE_2_OF_2
#include "GB_unaryop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
openmp_sendrecv.c | /*
(C) 2007 by Argonne National Laboratory.
See COPYRIGHT in top-level directory.
*/
#include "mpi.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFLEN 512
#define NTIMES 50
#define MAX_THREADS 10
/*
Concurrent send and recv by multiple threads on each process.
*/
void *thd_sendrecv( void * );
void *thd_sendrecv( void *comm_ptr )
{
MPI_Comm comm;
int my_rank, num_procs, next, buffer_size, namelen, idx;
char buffer[BUFLEN], processor_name[MPI_MAX_PROCESSOR_NAME];
MPI_Status status;
comm = *(MPI_Comm *) comm_ptr;
MPI_Comm_size( comm, &num_procs );
MPI_Comm_rank( comm, &my_rank );
MPI_Get_processor_name( processor_name, &namelen );
fprintf( stdout, "Process %d on %s\n", my_rank, processor_name );
strcpy( buffer, "hello there" );
buffer_size = strlen(buffer)+1;
if ( my_rank == num_procs-1 )
next = 0;
else
next = my_rank+1;
for ( idx = 0; idx < NTIMES; idx++ ) {
if (my_rank == 0) {
/*
printf("%d sending '%s' \n",my_rank,buffer);
*/
MPI_Send(buffer, buffer_size, MPI_CHAR, next, 99, comm);
MPI_Send(buffer, buffer_size, MPI_CHAR, MPI_PROC_NULL, 299, comm);
/*
printf("%d receiving \n",my_rank);
*/
MPI_Recv(buffer, BUFLEN, MPI_CHAR, MPI_ANY_SOURCE, 99,
comm, &status);
/*
printf("%d received '%s' \n",my_rank,buffer);
*/
}
else {
/*
printf("%d receiving \n",my_rank);
*/
MPI_Recv(buffer, BUFLEN, MPI_CHAR, MPI_ANY_SOURCE, 99,
comm, &status);
MPI_Recv(buffer, BUFLEN, MPI_CHAR, MPI_PROC_NULL, 299,
comm, &status);
/*
printf("%d received '%s' \n",my_rank,buffer);
*/
MPI_Send(buffer, buffer_size, MPI_CHAR, next, 99, comm);
/*
printf("%d sent '%s' \n",my_rank,buffer);
*/
}
/* MPI_Barrier(comm); */
}
return 0;
}
int main( int argc,char *argv[] )
{
MPI_Comm comm[ MAX_THREADS ];
int my_rank, ii, provided;
int num_threads;
MPI_Init_thread( &argc, &argv, MPI_THREAD_MULTIPLE, &provided );
if ( provided != MPI_THREAD_MULTIPLE ) {
fprintf( stderr, "Aborting, MPI_THREAD_MULTIPLE is needed...\n" );
fflush( stderr );
MPI_Abort( MPI_COMM_WORLD, 1 );
}
MPI_Comm_rank( MPI_COMM_WORLD, &my_rank );
if ( my_rank == 0 ) {
if ( argc != 2 ) {
fprintf( stderr, "Error: %s num_threads\n", argv[0] );
fflush( stderr );
MPI_Abort( MPI_COMM_WORLD, 1 );
}
num_threads = atoi( argv[1] );
if ( num_threads < 1 ) {
fprintf( stderr, "Error: Input num_threads=%d < 1 \n",
num_threads );
fflush( stderr );
MPI_Abort( MPI_COMM_WORLD, 1 );
}
if ( num_threads > MAX_THREADS ) {
fprintf( stderr, "Error: Input num_threads=%d < %d \n",
num_threads, MAX_THREADS );
fflush( stderr );
MPI_Abort( MPI_COMM_WORLD, 1 );
}
MPI_Bcast( &num_threads, 1, MPI_INT, 0, MPI_COMM_WORLD );
}
else
MPI_Bcast( &num_threads, 1, MPI_INT, 0, MPI_COMM_WORLD );
MPI_Barrier( MPI_COMM_WORLD );
for ( ii=0; ii < num_threads; ii++ ) {
MPI_Comm_dup( MPI_COMM_WORLD, &comm[ii] );
}
#pragma omp parallel shared( num_threads ) private( ii )
#pragma omp for
for ( ii=0; ii < num_threads; ii++ ) {
thd_sendrecv( (void *) &comm[ii] );
}
MPI_Finalize();
return 0;
}
|
single-modificado.c | #include <stdio.h>
#include <omp.h>
int main() {
int n = 9, i, a, b[n];
for (i=0; i<n; i++)
b[i] = -1;
#pragma omp parallel
{
#pragma omp single
{
printf("Dentro de la región parallel:\n");
}
#pragma omp single
{
printf("Introduce valor de inicialización a:");
scanf("%d", &a );
printf("Single ejecutada por el thread %d\n", omp_get_thread_num());
}
#pragma omp for
for (i=0; i<n; i++)
b[i] = a;
}
#pragma omp single
{
for (i=0; i<n; i++)
printf("b[%d] = %d\t",i,b[i]);
printf("\n");
printf("Single ejecutada por el thread %d\n", omp_get_thread_num());
}
printf("Después de la región parallel:\n");
printf("Single ejecutada por el thread %d\n", omp_get_thread_num());
for (i=0; i<n; i++)
printf("b[%d] = %d\t",i,b[i]);
printf("\n");
}
|
3d25pt_var.c | /*
* Order-1, 3D 25 point stencil with axis-symmetric ariable coefficients
* Adapted from PLUTO and Pochoir test bench
*
* Tareq Malas
*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#ifdef LIKWID_PERFMON
#include <likwid.h>
#endif
#include "print_utils.h"
#define TESTS 2
#define MAX(a,b) ((a) > (b) ? a : b)
#define MIN(a,b) ((a) < (b) ? a : b)
/* Subtract the `struct timeval' values X and Y,
* storing the result in RESULT.
*
* Return 1 if the difference is negative, otherwise 0.
*/
int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y)
{
/* Perform the carry for the later subtraction by updating y. */
if (x->tv_usec < y->tv_usec)
{
int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1;
y->tv_usec -= 1000000 * nsec;
y->tv_sec += nsec;
}
if (x->tv_usec - y->tv_usec > 1000000)
{
int nsec = (x->tv_usec - y->tv_usec) / 1000000;
y->tv_usec += 1000000 * nsec;
y->tv_sec -= nsec;
}
/* Compute the time remaining to wait.
* tv_usec is certainly positive.
*/
result->tv_sec = x->tv_sec - y->tv_sec;
result->tv_usec = x->tv_usec - y->tv_usec;
/* Return 1 if result is negative. */
return x->tv_sec < y->tv_sec;
}
int main(int argc, char *argv[])
{
int t, i, j, k, m, test;
int Nx, Ny, Nz, Nt;
if (argc > 3) {
Nx = atoi(argv[1])+8;
Ny = atoi(argv[2])+8;
Nz = atoi(argv[3])+8;
}
if (argc > 4)
Nt = atoi(argv[4]);
// allocate the arrays
double ****A = (double ****) malloc(sizeof(double***)*2);
for(m=0; m<2;m++){
A[m] = (double ***) malloc(sizeof(double**)*Nz);
for(i=0; i<Nz; i++){
A[m][i] = (double**) malloc(sizeof(double*)*Ny);
for(j=0;j<Ny;j++){
A[m][i][j] = (double*) malloc(sizeof(double)*Nx);
}
}
}
double ****coef = (double ****) malloc(sizeof(double***)*13);
for(m=0; m<13;m++){
coef[m] = (double ***) malloc(sizeof(double**)*Nz);
for(i=0; i<Nz; i++){
coef[m][i] = (double**) malloc(sizeof(double*)*Ny);
for(j=0;j<Ny;j++){
coef[m][i][j] = (double*) malloc(sizeof(double)*Nx);
}
}
}
// tile size information, including extra element to decide the list length
int *tile_size = (int*) malloc(sizeof(int));
tile_size[0] = -1;
// The list is modified here before source-to-source transformations
tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5);
tile_size[0] = 8;
tile_size[1] = 8;
tile_size[2] = 16;
tile_size[3] = 1024;
tile_size[4] = -1;
// for timekeeping
int ts_return = -1;
struct timeval start, end, result;
double tdiff = 0.0, min_tdiff=1.e100;
const int BASE = 1024;
// initialize variables
//
srand(42);
for (i = 1; i < Nz; i++) {
for (j = 1; j < Ny; j++) {
for (k = 1; k < Nx; k++) {
A[0][i][j][k] = 1.0 * (rand() % BASE);
}
}
}
for (m=0; m<13; m++) {
for (i=1; i<Nz; i++) {
for (j=1; j<Ny; j++) {
for (k=1; k<Nx; k++) {
coef[m][i][j][k] = 1.0 * (rand() % BASE);
}
}
}
}
#ifdef LIKWID_PERFMON
LIKWID_MARKER_INIT;
#pragma omp parallel
{
LIKWID_MARKER_THREADINIT;
#pragma omp barrier
LIKWID_MARKER_START("calc");
}
#endif
int num_threads = 1;
#if defined(_OPENMP)
num_threads = omp_get_max_threads();
#endif
for(test=0; test<TESTS; test++){
gettimeofday(&start, 0);
// serial execution - Addition: 6 && Multiplication: 2
#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] =
coef[0][i][j][k] * A[(t)%2][i ][j ][k ] +
coef[1][i][j][k] * (A[(t)%2][i-1][j ][k ] + A[(t)%2][i+1][j ][k ]) +
coef[2][i][j][k] * (A[(t)%2][i ][j-1][k ] + A[(t)%2][i ][j+1][k ]) +
coef[3][i][j][k] * (A[(t)%2][i ][j ][k-1] + A[(t)%2][i ][j ][k+1]) +
coef[4][i][j][k] * (A[(t)%2][i-2][j ][k ] + A[(t)%2][i+2][j ][k ]) +
coef[5][i][j][k] * (A[(t)%2][i ][j-2][k ] + A[(t)%2][i ][j+2][k ]) +
coef[6][i][j][k] * (A[(t)%2][i ][j ][k-2] + A[(t)%2][i ][j ][k+2]) +
coef[7][i][j][k] * (A[(t)%2][i-3][j ][k ] + A[(t)%2][i+3][j ][k ]) +
coef[8][i][j][k] * (A[(t)%2][i ][j-3][k ] + A[(t)%2][i ][j+3][k ]) +
coef[9][i][j][k] * (A[(t)%2][i ][j ][k-3] + A[(t)%2][i ][j ][k+3]) +
coef[10][i][j][k]* (A[(t)%2][i-4][j ][k ] + A[(t)%2][i+4][j ][k ]) +
coef[11][i][j][k]* (A[(t)%2][i ][j-4][k ] + A[(t)%2][i ][j+4][k ]) +
coef[12][i][j][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, "variable axis-symmetric")
#ifdef LIKWID_PERFMON
#pragma omp parallel
{
LIKWID_MARKER_STOP("calc");
}
LIKWID_MARKER_CLOSE;
#endif
// Free allocated arrays
for(i=0; i<Nz; i++){
for(j=0;j<Ny;j++){
free(A[0][i][j]);
free(A[1][i][j]);
}
free(A[0][i]);
free(A[1][i]);
}
free(A[0]);
free(A[1]);
for(m=0; m<13;m++){
for(i=0; i<Nz; i++){
for(j=0;j<Ny;j++){
free(coef[m][i][j]);
}
free(coef[m][i]);
}
free(coef[m]);
}
return 0;
}
|
bml_trace_ellpack_typed.c | #include "../../macros.h"
#include "../../typed.h"
#include "../bml_allocate.h"
#include "../bml_logger.h"
#include "../bml_parallel.h"
#include "../bml_submatrix.h"
#include "../bml_trace.h"
#include "../bml_types.h"
#include "bml_submatrix_ellpack.h"
#include "bml_trace_ellpack.h"
#include "bml_types_ellpack.h"
#include <complex.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#ifdef _OPENMP
#include <omp.h>
#endif
/** Calculate the trace of a matrix.
*
* \ingroup trace_group
*
* \param A The matrix to calculate a trace for
* \return the trace of A
*/
double TYPED_FUNC(
bml_trace_ellpack) (
bml_matrix_ellpack_t * A)
{
int N = A->N;
int M = A->M;
int *A_index = (int *) A->index;
int *A_nnz = (int *) A->nnz;
int *A_localRowMin = (int *) A->domain->localRowMin;
int *A_localRowMax = (int *) A->domain->localRowMax;
REAL_T trace = 0.0;
REAL_T *A_value = (REAL_T *) A->value;
int myRank = bml_getMyRank();
#pragma omp parallel for \
shared(N, M, A_value, A_index, A_nnz) \
shared(A_localRowMin, A_localRowMax, myRank) \
reduction(+:trace)
//for (int i = 0; i < N; i++)
for (int i = A_localRowMin[myRank]; i < A_localRowMax[myRank]; i++)
{
for (int j = 0; j < A_nnz[i]; j++)
{
if (i == A_index[ROWMAJOR(i, j, N, M)])
{
trace += A_value[ROWMAJOR(i, j, N, M)];
break;
}
}
}
return (double) REAL_PART(trace);
}
/** Calculate the trace of a matrix multiplication.
* Both matrices must have the same size.
*
* \ingroup trace_group
*
* \param A The matrix A
* \param A The matrix B
* \return the trace of A*B
*/
double TYPED_FUNC(
bml_trace_mult_ellpack) (
bml_matrix_ellpack_t * A,
bml_matrix_ellpack_t * B)
{
int A_N = A->N;
int A_M = A->M;
int *A_index = (int *) A->index;
int *A_nnz = (int *) A->nnz;
int *A_localRowMin = (int *) A->domain->localRowMin;
int *A_localRowMax = (int *) A->domain->localRowMax;
REAL_T trace = 0.0;
REAL_T *A_value = (REAL_T *) A->value;
REAL_T *rvalue;
int myRank = bml_getMyRank();
if (A_N != B->N || A_M != B->M)
{
LOG_ERROR
("bml_trace_mult_ellpack: Matrices A and B have different sizes.");
}
#pragma omp parallel for \
private(rvalue) \
shared(B, A_N, A_M, A_value, A_index, A_nnz) \
shared(A_localRowMin, A_localRowMax, myRank) \
reduction(+:trace)
//for (int i = 0; i < A_N; i++)
for (int i = A_localRowMin[myRank]; i < A_localRowMax[myRank]; i++)
{
rvalue =
TYPED_FUNC(bml_getVector_ellpack) (B,
&A_index[ROWMAJOR
(i, 0, A_N, A_M)], i,
A_nnz[i]);
for (int j = 0; j < A_nnz[i]; j++)
{
trace += A_value[ROWMAJOR(i, j, A_N, A_M)] * rvalue[j];
}
bml_free_memory(rvalue);
}
return (double) REAL_PART(trace);
}
|
GB_unop__identity_uint32_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__identity_uint32_int32)
// op(A') function: GB (_unop_tran__identity_uint32_int32)
// C type: uint32_t
// A type: int32_t
// cast: uint32_t cij = (uint32_t) aij
// unaryop: cij = aij
#define GB_ATYPE \
int32_t
#define GB_CTYPE \
uint32_t
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
int32_t aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = x ;
// casting
#define GB_CAST(z, aij) \
uint32_t z = (uint32_t) aij ;
// cij = op (aij)
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
int32_t aij = Ax [pA] ; \
/* Cx [pC] = op (cast (aij)) */ \
uint32_t z = (uint32_t) aij ; \
Cx [pC] = z ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_IDENTITY || GxB_NO_UINT32 || GxB_NO_INT32)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_apply__identity_uint32_int32)
(
uint32_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] ;
uint32_t z = (uint32_t) aij ;
Cx [p] = z ;
}
}
else
{
// bitmap case, no transpose; A->b already memcpy'd into C->b
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!Ab [p]) continue ;
int32_t aij = Ax [p] ;
uint32_t z = (uint32_t) aij ;
Cx [p] = z ;
}
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_tran__identity_uint32_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
|
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;
}
|
tree.h | /*!
* Copyright (c) 2016 Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See LICENSE file in the project root for license information.
*/
#ifndef LIGHTGBM_TREE_H_
#define LIGHTGBM_TREE_H_
#include <LightGBM/dataset.h>
#include <LightGBM/meta.h>
#include <string>
#include <map>
#include <memory>
#include <unordered_map>
#include <vector>
namespace LightGBM {
#define kCategoricalMask (1)
#define kDefaultLeftMask (2)
/*!
* \brief Tree model
*/
class Tree {
public:
/*!
* \brief Constructor
* \param max_leaves The number of max leaves
*/
explicit Tree(int max_leaves);
/*!
* \brief Constructor, from a string
* \param str Model string
* \param used_len used count of str
*/
Tree(const char* str, size_t* used_len);
~Tree();
/*!
* \brief Performing a split on tree leaves.
* \param leaf Index of leaf to be split
* \param feature Index of feature; the converted index after removing useless features
* \param real_feature Index of feature, the original index on data
* \param threshold_bin Threshold(bin) of split
* \param threshold_double Threshold on feature value
* \param left_value Model Left child output
* \param right_value Model Right child output
* \param left_cnt Count of left child
* \param right_cnt Count of right child
* \param left_weight Weight of left child
* \param right_weight Weight of right child
* \param gain Split gain
* \param missing_type missing type
* \param default_left default direction for missing value
* \return The index of new leaf.
*/
int Split(int leaf, int feature, int real_feature, uint32_t threshold_bin,
double threshold_double, double left_value, double right_value,
int left_cnt, int right_cnt, double left_weight, double right_weight,
float gain, MissingType missing_type, bool default_left);
/*!
* \brief Performing a split on tree leaves, with categorical feature
* \param leaf Index of leaf to be split
* \param feature Index of feature; the converted index after removing useless features
* \param real_feature Index of feature, the original index on data
* \param threshold_bin Threshold(bin) of split, use bitset to represent
* \param num_threshold_bin size of threshold_bin
* \param threshold Thresholds of real feature value, use bitset to represent
* \param num_threshold size of threshold
* \param left_value Model Left child output
* \param right_value Model Right child output
* \param left_cnt Count of left child
* \param right_cnt Count of right child
* \param left_weight Weight of left child
* \param right_weight Weight of right child
* \param gain Split gain
* \return The index of new leaf.
*/
int SplitCategorical(int leaf, int feature, int real_feature, const uint32_t* threshold_bin, int num_threshold_bin,
const uint32_t* threshold, int num_threshold, double left_value, double right_value,
int left_cnt, int right_cnt, double left_weight, double right_weight, float gain, MissingType missing_type);
/*! \brief Get the output of one leaf */
inline double LeafOutput(int leaf) const { return leaf_value_[leaf]; }
/*! \brief Set the output of one leaf */
inline void SetLeafOutput(int leaf, double output) {
leaf_value_[leaf] = MaybeRoundToZero(output);
}
/*!
* \brief Adding prediction value of this tree model to scores
* \param data The dataset
* \param num_data Number of total data
* \param score Will add prediction to score
*/
void AddPredictionToScore(const Dataset* data,
data_size_t num_data,
double* score) const;
/*!
* \brief Adding prediction value of this tree model to scores
* \param data The dataset
* \param used_data_indices Indices of used data
* \param num_data Number of total data
* \param score Will add prediction to score
*/
void AddPredictionToScore(const Dataset* data,
const data_size_t* used_data_indices,
data_size_t num_data, double* score) const;
/*!
* \brief Get upper bound leaf value of this tree model
*/
double GetUpperBoundValue() const;
/*!
* \brief Get lower bound leaf value of this tree model
*/
double GetLowerBoundValue() const;
/*!
* \brief Prediction on one record
* \param feature_values Feature value of this record
* \return Prediction result
*/
inline double Predict(const double* feature_values) const;
inline double PredictByMap(const std::unordered_map<int, double>& feature_values) const;
inline int PredictLeafIndex(const double* feature_values) const;
inline int PredictLeafIndexByMap(const std::unordered_map<int, double>& feature_values) const;
inline void PredictContrib(const double* feature_values, int num_features, double* output);
/*! \brief Get Number of leaves*/
inline int num_leaves() const { return num_leaves_; }
/*! \brief Get depth of specific leaf*/
inline int leaf_depth(int leaf_idx) const { return leaf_depth_[leaf_idx]; }
/*! \brief Get feature of specific split*/
inline int split_feature(int split_idx) const { return split_feature_[split_idx]; }
inline double split_gain(int split_idx) const { return split_gain_[split_idx]; }
/*! \brief Get the number of data points that fall at or below this node*/
inline int data_count(int node) const { return node >= 0 ? internal_count_[node] : leaf_count_[~node]; }
/*!
* \brief Shrinkage for the tree's output
* shrinkage rate (a.k.a learning rate) is used to tune the training process
* \param rate The factor of shrinkage
*/
inline void Shrinkage(double rate) {
#pragma omp parallel for schedule(static, 1024) if (num_leaves_ >= 2048)
for (int i = 0; i < num_leaves_ - 1; ++i) {
leaf_value_[i] = MaybeRoundToZero(leaf_value_[i] * rate);
internal_value_[i] = MaybeRoundToZero(internal_value_[i] * rate);
}
leaf_value_[num_leaves_ - 1] =
MaybeRoundToZero(leaf_value_[num_leaves_ - 1] * rate);
shrinkage_ *= rate;
}
inline double shrinkage() const { return shrinkage_; }
inline void AddBias(double val) {
#pragma omp parallel for schedule(static, 1024) if (num_leaves_ >= 2048)
for (int i = 0; i < num_leaves_ - 1; ++i) {
leaf_value_[i] = MaybeRoundToZero(leaf_value_[i] + val);
internal_value_[i] = MaybeRoundToZero(internal_value_[i] + val);
}
leaf_value_[num_leaves_ - 1] =
MaybeRoundToZero(leaf_value_[num_leaves_ - 1] + val);
// force to 1.0
shrinkage_ = 1.0f;
}
inline void AsConstantTree(double val) {
num_leaves_ = 1;
shrinkage_ = 1.0f;
leaf_value_[0] = val;
}
/*! \brief Serialize this object to string*/
std::string ToString() const;
/*! \brief Serialize this object to json*/
std::string ToJSON() const;
/*! \brief Serialize this object to if-else statement*/
std::string ToIfElse(int index, bool predict_leaf_index) const;
inline static bool IsZero(double fval) {
if (fval > -kZeroThreshold && fval <= kZeroThreshold) {
return true;
} else {
return false;
}
}
inline static double MaybeRoundToZero(double fval) {
if (fval > -kZeroThreshold && fval <= kZeroThreshold) {
return 0;
} else {
return fval;
}
}
inline static bool GetDecisionType(int8_t decision_type, int8_t mask) {
return (decision_type & mask) > 0;
}
inline static void SetDecisionType(int8_t* decision_type, bool input, int8_t mask) {
if (input) {
(*decision_type) |= mask;
} else {
(*decision_type) &= (127 - mask);
}
}
inline static int8_t GetMissingType(int8_t decision_type) {
return (decision_type >> 2) & 3;
}
inline static void SetMissingType(int8_t* decision_type, int8_t input) {
(*decision_type) &= 3;
(*decision_type) |= (input << 2);
}
void RecomputeMaxDepth();
int NextLeafId() const { return num_leaves_; }
private:
std::string NumericalDecisionIfElse(int node) const;
std::string CategoricalDecisionIfElse(int node) const;
inline int NumericalDecision(double fval, int node) const {
uint8_t missing_type = GetMissingType(decision_type_[node]);
if (std::isnan(fval)) {
if (missing_type != 2) {
fval = 0.0f;
}
}
if ((missing_type == 1 && IsZero(fval))
|| (missing_type == 2 && std::isnan(fval))) {
if (GetDecisionType(decision_type_[node], kDefaultLeftMask)) {
return left_child_[node];
} else {
return right_child_[node];
}
}
if (fval <= threshold_[node]) {
return left_child_[node];
} else {
return right_child_[node];
}
}
inline int NumericalDecisionInner(uint32_t fval, int node, uint32_t default_bin, uint32_t max_bin) const {
uint8_t missing_type = GetMissingType(decision_type_[node]);
if ((missing_type == 1 && fval == default_bin)
|| (missing_type == 2 && fval == max_bin)) {
if (GetDecisionType(decision_type_[node], kDefaultLeftMask)) {
return left_child_[node];
} else {
return right_child_[node];
}
}
if (fval <= threshold_in_bin_[node]) {
return left_child_[node];
} else {
return right_child_[node];
}
}
inline int CategoricalDecision(double fval, int node) const {
uint8_t missing_type = GetMissingType(decision_type_[node]);
int int_fval = static_cast<int>(fval);
if (int_fval < 0) {
return right_child_[node];;
} else if (std::isnan(fval)) {
// NaN is always in the right
if (missing_type == 2) {
return right_child_[node];
}
int_fval = 0;
}
int cat_idx = static_cast<int>(threshold_[node]);
if (Common::FindInBitset(cat_threshold_.data() + cat_boundaries_[cat_idx],
cat_boundaries_[cat_idx + 1] - cat_boundaries_[cat_idx], int_fval)) {
return left_child_[node];
}
return right_child_[node];
}
inline int CategoricalDecisionInner(uint32_t fval, int node) const {
int cat_idx = static_cast<int>(threshold_in_bin_[node]);
if (Common::FindInBitset(cat_threshold_inner_.data() + cat_boundaries_inner_[cat_idx],
cat_boundaries_inner_[cat_idx + 1] - cat_boundaries_inner_[cat_idx], fval)) {
return left_child_[node];
}
return right_child_[node];
}
inline int Decision(double fval, int node) const {
if (GetDecisionType(decision_type_[node], kCategoricalMask)) {
return CategoricalDecision(fval, node);
} else {
return NumericalDecision(fval, node);
}
}
inline int DecisionInner(uint32_t fval, int node, uint32_t default_bin, uint32_t max_bin) const {
if (GetDecisionType(decision_type_[node], kCategoricalMask)) {
return CategoricalDecisionInner(fval, node);
} else {
return NumericalDecisionInner(fval, node, default_bin, max_bin);
}
}
inline void Split(int leaf, int feature, int real_feature, double left_value, double right_value, int left_cnt, int right_cnt,
double left_weight, double right_weight, float gain);
/*!
* \brief Find leaf index of which record belongs by features
* \param feature_values Feature value of this record
* \return Leaf index
*/
inline int GetLeaf(const double* feature_values) const;
inline int GetLeafByMap(const std::unordered_map<int, double>& feature_values) const;
/*! \brief Serialize one node to json*/
std::string NodeToJSON(int index) const;
/*! \brief Serialize one node to if-else statement*/
std::string NodeToIfElse(int index, bool predict_leaf_index) const;
std::string NodeToIfElseByMap(int index, bool predict_leaf_index) const;
double ExpectedValue() const;
/*! \brief This is used fill in leaf_depth_ after reloading a model*/
inline void RecomputeLeafDepths(int node = 0, int depth = 0);
/*!
* \brief Used by TreeSHAP for data we keep about our decision path
*/
struct PathElement {
int feature_index;
double zero_fraction;
double one_fraction;
// note that pweight is included for convenience and is not tied with the other attributes,
// the pweight of the i'th path element is the permutation weight of paths with i-1 ones in them
double pweight;
PathElement() {}
PathElement(int i, double z, double o, double w) : feature_index(i), zero_fraction(z), one_fraction(o), pweight(w) {}
};
/*! \brief Polynomial time algorithm for SHAP values (arXiv:1706.06060)*/
void TreeSHAP(const double *feature_values, double *phi,
int node, int unique_depth,
PathElement *parent_unique_path, double parent_zero_fraction,
double parent_one_fraction, int parent_feature_index) const;
/*! \brief Extend our decision path with a fraction of one and zero extensions for TreeSHAP*/
static void ExtendPath(PathElement *unique_path, int unique_depth,
double zero_fraction, double one_fraction, int feature_index);
/*! \brief Undo a previous extension of the decision path for TreeSHAP*/
static void UnwindPath(PathElement *unique_path, int unique_depth, int path_index);
/*! determine what the total permutation weight would be if we unwound a previous extension in the decision path*/
static double UnwoundPathSum(const PathElement *unique_path, int unique_depth, int path_index);
/*! \brief Number of max leaves*/
int max_leaves_;
/*! \brief Number of current leaves*/
int num_leaves_;
// following values used for non-leaf node
/*! \brief A non-leaf node's left child */
std::vector<int> left_child_;
/*! \brief A non-leaf node's right child */
std::vector<int> right_child_;
/*! \brief A non-leaf node's split feature */
std::vector<int> split_feature_inner_;
/*! \brief A non-leaf node's split feature, the original index */
std::vector<int> split_feature_;
/*! \brief A non-leaf node's split threshold in bin */
std::vector<uint32_t> threshold_in_bin_;
/*! \brief A non-leaf node's split threshold in feature value */
std::vector<double> threshold_;
int num_cat_;
std::vector<int> cat_boundaries_inner_;
std::vector<uint32_t> cat_threshold_inner_;
std::vector<int> cat_boundaries_;
std::vector<uint32_t> cat_threshold_;
/*! \brief Store the information for categorical feature handle and missing value handle. */
std::vector<int8_t> decision_type_;
/*! \brief A non-leaf node's split gain */
std::vector<float> split_gain_;
// used for leaf node
/*! \brief The parent of leaf */
std::vector<int> leaf_parent_;
/*! \brief Output of leaves */
std::vector<double> leaf_value_;
/*! \brief weight of leaves */
std::vector<double> leaf_weight_;
/*! \brief DataCount of leaves */
std::vector<int> leaf_count_;
/*! \brief Output of non-leaf nodes */
std::vector<double> internal_value_;
/*! \brief weight of non-leaf nodes */
std::vector<double> internal_weight_;
/*! \brief DataCount of non-leaf nodes */
std::vector<int> internal_count_;
/*! \brief Depth for leaves */
std::vector<int> leaf_depth_;
double shrinkage_;
int max_depth_;
};
inline void Tree::Split(int leaf, int feature, int real_feature,
double left_value, double right_value, int left_cnt, int right_cnt,
double left_weight, double right_weight, float gain) {
int new_node_idx = num_leaves_ - 1;
// update parent info
int parent = leaf_parent_[leaf];
if (parent >= 0) {
// if cur node is left child
if (left_child_[parent] == ~leaf) {
left_child_[parent] = new_node_idx;
} else {
right_child_[parent] = new_node_idx;
}
}
// add new node
split_feature_inner_[new_node_idx] = feature;
split_feature_[new_node_idx] = real_feature;
split_gain_[new_node_idx] = gain;
// add two new leaves
left_child_[new_node_idx] = ~leaf;
right_child_[new_node_idx] = ~num_leaves_;
// update new leaves
leaf_parent_[leaf] = new_node_idx;
leaf_parent_[num_leaves_] = new_node_idx;
// save current leaf value to internal node before change
internal_weight_[new_node_idx] = leaf_weight_[leaf];
internal_value_[new_node_idx] = leaf_value_[leaf];
internal_count_[new_node_idx] = left_cnt + right_cnt;
leaf_value_[leaf] = std::isnan(left_value) ? 0.0f : left_value;
leaf_weight_[leaf] = left_weight;
leaf_count_[leaf] = left_cnt;
leaf_value_[num_leaves_] = std::isnan(right_value) ? 0.0f : right_value;
leaf_weight_[num_leaves_] = right_weight;
leaf_count_[num_leaves_] = right_cnt;
// update leaf depth
leaf_depth_[num_leaves_] = leaf_depth_[leaf] + 1;
leaf_depth_[leaf]++;
}
inline double Tree::Predict(const double* feature_values) const {
if (num_leaves_ > 1) {
int leaf = GetLeaf(feature_values);
return LeafOutput(leaf);
} else {
return leaf_value_[0];
}
}
inline double Tree::PredictByMap(const std::unordered_map<int, double>& feature_values) const {
if (num_leaves_ > 1) {
int leaf = GetLeafByMap(feature_values);
return LeafOutput(leaf);
} else {
return leaf_value_[0];
}
}
inline int Tree::PredictLeafIndex(const double* feature_values) const {
if (num_leaves_ > 1) {
int leaf = GetLeaf(feature_values);
return leaf;
} else {
return 0;
}
}
inline int Tree::PredictLeafIndexByMap(const std::unordered_map<int, double>& feature_values) const {
if (num_leaves_ > 1) {
int leaf = GetLeafByMap(feature_values);
return leaf;
} else {
return 0;
}
}
inline void Tree::PredictContrib(const double* feature_values, int num_features, double* output) {
output[num_features] += ExpectedValue();
// Run the recursion with preallocated space for the unique path data
if (num_leaves_ > 1) {
CHECK_GE(max_depth_, 0);
const int max_path_len = max_depth_ + 1;
std::vector<PathElement> unique_path_data(max_path_len*(max_path_len + 1) / 2);
TreeSHAP(feature_values, output, 0, 0, unique_path_data.data(), 1, 1, -1);
}
}
inline void Tree::RecomputeLeafDepths(int node, int depth) {
if (node == 0) leaf_depth_.resize(num_leaves());
if (node < 0) {
leaf_depth_[~node] = depth;
} else {
RecomputeLeafDepths(left_child_[node], depth + 1);
RecomputeLeafDepths(right_child_[node], depth + 1);
}
}
inline int Tree::GetLeaf(const double* feature_values) const {
int node = 0;
if (num_cat_ > 0) {
while (node >= 0) {
node = Decision(feature_values[split_feature_[node]], node);
}
} else {
while (node >= 0) {
node = NumericalDecision(feature_values[split_feature_[node]], node);
}
}
return ~node;
}
inline int Tree::GetLeafByMap(const std::unordered_map<int, double>& feature_values) const {
int node = 0;
if (num_cat_ > 0) {
while (node >= 0) {
node = Decision(feature_values.count(split_feature_[node]) > 0 ? feature_values.at(split_feature_[node]) : 0.0f, node);
}
} else {
while (node >= 0) {
node = NumericalDecision(feature_values.count(split_feature_[node]) > 0 ? feature_values.at(split_feature_[node]) : 0.0f, node);
}
}
return ~node;
}
} // namespace LightGBM
#endif // LightGBM_TREE_H_
|
target-18.c | extern void abort (void);
void
foo (int n)
{
int a[4] = { 0, 1, 2, 3 }, b[n];
int *p = a + 1, i, err;
for (i = 0; i < n; i++)
b[i] = 9 + i;
#pragma omp target data map(to:a)
#pragma omp target data use_device_ptr(p) map(from:err)
#pragma omp target is_device_ptr(p) private(i) map(from:err)
{
err = 0;
for (i = 0; i < 4; i++)
if (p[i - 1] != i)
err = 1;
}
if (err)
abort ();
for (i = 0; i < 4; i++)
a[i] = 23 + i;
#pragma omp target data map(to:a)
#pragma omp target data use_device_ptr(a) map(from:err)
#pragma omp target is_device_ptr(a) private(i) map(from:err)
{
err = 0;
for (i = 0; i < 4; i++)
if (a[i] != 23 + i)
err = 1;
}
if (err)
abort ();
#pragma omp target data map(to:b)
#pragma omp target data use_device_ptr(b) map(from:err)
#pragma omp target is_device_ptr(b) private(i) map(from:err)
{
err = 0;
for (i = 0; i < 4; i++)
if (b[i] != 9 + i)
err = 1;
}
if (err)
abort ();
}
int
main ()
{
foo (9);
return 0;
}
|
numint_uniform_grid.c | /* Copyright 2014-2018 The PySCF Developers. 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.
*
* Fast numerical integration on uniform grids.
* (See also cp2k multigrid algorithm)
*
* Author: Qiming Sun <osirpt.sun@gmail.com>
*/
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <assert.h>
#include <complex.h>
#include "config.h"
#include "cint.h"
#include "np_helper/np_helper.h"
#include "gto/grid_ao_drv.h"
#include "vhf/fblas.h"
#ifndef __USE_ISOC99
#define rint(x) (int)round(x)
#endif
#define PLAIN 0
#define HERMITIAN 1
#define ANTIHERMI 2
#define SYMMETRIC 3
#define OF_CMPLX 2
#define EIJCUTOFF 60
#define EXPMAX 700
#define EXPMIN -700
#define MAX_THREADS 256
#define PTR_EXPDROP 16
#define SQUARE(x) (*(x) * *(x) + *(x+1) * *(x+1) + *(x+2) * *(x+2))
double CINTsquare_dist(const double *r1, const double *r2);
double CINTcommon_fac_sp(int l);
static const int _LEN_CART[] = {
1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 66, 78, 91, 105, 120, 136
};
static const int _CUM_LEN_CART[] = {
1, 4, 10, 20, 35, 56, 84, 120, 165, 220, 286, 364, 455, 560, 680, 816,
};
static int _MAX_RR_SIZE[] = {
1, 4, 12, 30, 60, 120, 210, 350, 560, 840, 1260, 1800, 2520, 3465, 4620,
6160, 8008, 10296, 13104, 16380, 20475,
};
/*
* WHEREX_IF_L_INC1 = [xyz2addr(x,y,z) for x,y,z in loopcart(L_MAX) if x > 0]
* WHEREY_IF_L_INC1 = [xyz2addr(x,y,z) for x,y,z in loopcart(L_MAX) if y > 0]
* WHEREZ_IF_L_INC1 = [xyz2addr(x,y,z) for x,y,z in loopcart(L_MAX) if z > 0]
*/
static const int _UPIDY[] = {
1,
3, 4,
6, 7, 8,
10, 11, 12, 13,
15, 16, 17, 18, 19,
21, 22, 23, 24, 25, 26,
28, 29, 30, 31, 32, 33, 34,
36, 37, 38, 39, 40, 41, 42, 43,
45, 46, 47, 48, 49, 50, 51, 52, 53,
55, 56, 57, 58, 59, 60, 61, 62, 63, 64,
66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76,
78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89,
91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,
105,106,107,108,109,110,111,112,113,114,115,116,117,118,
120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,
};
static const int _UPIDZ[] = {
2,
4, 5,
7, 8, 9,
11, 12, 13, 14,
16, 17, 18, 19, 20,
22, 23, 24, 25, 26, 27,
29, 30, 31, 32, 33, 34, 35,
37, 38, 39, 40, 41, 42, 43, 44,
46, 47, 48, 49, 50, 51, 52, 53, 54,
56, 57, 58, 59, 60, 61, 62, 63, 64, 65,
67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77,
79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90,
92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,
106,107,108,109,110,111,112,113,114,115,116,117,118,119,
121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,
};
#define WHEREX_IF_L_INC1(i) i
#define WHEREY_IF_L_INC1(i) _UPIDY[i]
#define WHEREZ_IF_L_INC1(i) _UPIDZ[i]
#define STARTX_IF_L_DEC1(l) 0
#define STARTY_IF_L_DEC1(l) (((l)<2)?0:_LEN_CART[(l)-2])
#define STARTZ_IF_L_DEC1(l) (_LEN_CART[(l)-1]-1)
void GTOplain_vrr2d_ket_inc1(double *out, const double *g,
double *rirj, int li, int lj);
/* (li+lj,0) => (li,lj) */
// Input g is used as buffer in the iterations.
// Ensure size of g > _MAX_RR_SIZE[li+lj]
static void _plain_vrr2d(double *out, double *g, double *gbuf2, int li, int lj,
double *ri, double *rj)
{
const int nmax = li + lj;
double *g00, *g01, *gswap, *pg00, *pg01;
int row_01, col_01, row_00, col_00;
int i, j;
double rirj[3];
rirj[0] = ri[0] - rj[0];
rirj[1] = ri[1] - rj[1];
rirj[2] = ri[2] - rj[2];
g00 = gbuf2;
g01 = g;
for (j = 1; j < lj; j++) {
gswap = g00;
g00 = g01;
g01 = gswap;
pg00 = g00;
pg01 = g01;
for (i = li; i <= nmax-j; i++) {
GTOplain_vrr2d_ket_inc1(pg01, pg00, rirj, i, j);
row_01 = _LEN_CART[i];
col_01 = _LEN_CART[j];
row_00 = _LEN_CART[i ];
col_00 = _LEN_CART[j-1];
pg00 += row_00*col_00;
pg01 += row_01*col_01;
}
}
GTOplain_vrr2d_ket_inc1(out, g01, rirj, li, lj);
}
/*
* rcut is the distance over which the integration (from rcut to infty) is
* smaller than the required precision
* integral ~= \int_{rcut}^infty r^{l+2} exp(-alpha r^2) dr
*
* * if l is odd:
* integral = \sum_n (l+1)!!/(l+3-2n)!! * rcut^{l+3-2n}/(2 alpha)^n
* * exp(-alpha {rcut}^2)
*
* * elif l is even and rcut > 1:
* integral < [\sum_{n<=l/2+1} (l+1)!!/(l+3-2n)!! * rcut^{l+3-2n}/(2 alpha)^n
* + 1/(2 alpha)^(l/2+2)] * exp(-alpha {rcut}^2)
*
* * elif l is even and rcut < 1:
* integral < [\sum_{n<=l/2+1} (l+1)!!/(l+3-2n)!! * rcut^{l+3-2n}/(2 alpha)^n] * exp(-alpha {rcut}^2)
* + (l+1)!! / (2 alpha)^{l/2+1} * \sqrt(pi/alpha)/2
*/
static double gto_rcut(double alpha, int l, double c, double log_prec)
{
double log_c = log(fabs(c));
double prod = 0;
double r = 10.;
double log_2a = log(2*alpha);
double log_r = log(r);
if (2*log_r + log_2a > 1) { // r^2 >~ 3/(2a)
prod = (l+1) * log_r - log_2a;
} else {
prod = -(l+4)/2 * log_2a;
}
//log_r = .5 * (prod / alpha);
//if (2*log_r + log_2a > 1) {
// prod = (l+1) * log_r - log_2a;
//} else {
// prod = -(l+4)/2 * log_2a;
//}
prod += log_c - log_prec;
if (prod < alpha) {
// if rcut < 1, estimating based on exp^{-a*rcut^2}
prod = log_c - log_prec;
}
if (prod > 0) {
r = sqrt(prod / alpha);
} else {
r = 0;
}
return r;
}
static int _has_overlap(int nx0, int nx1, int nx_per_cell)
{
return nx0 < nx1 + 3;
}
static int _num_grids_on_x(int nimgx, int nx0, int nx1, int nx_per_cell)
{
int ngridx;
if (nimgx == 1) {
ngridx = nx1 - nx0;
} else if (nimgx == 2 && !_has_overlap(nx0, nx1, nx_per_cell)) {
ngridx = nx1 - nx0 + nx_per_cell;
} else {
ngridx = nx_per_cell;
}
return ngridx;
}
static int _orth_components(double *xs_exp, int *img_slice, int *grid_slice,
double a, double b, double cutoff,
double xi, double xj, double ai, double aj,
int periodic, int nx_per_cell, int topl,
int offset, int submesh, double *cache)
{
double aij = ai + aj;
double xij = (ai * xi + aj * xj) / aij;
double heights_inv = b;
double xij_frac = xij * heights_inv;
double edge0 = xij_frac - cutoff * heights_inv;
double edge1 = xij_frac + cutoff * heights_inv;
if (edge0 == edge1) {
// cutoff may be so small that it does not provide difference to edge0 and
// edge1. When edge0 and edge1 are right on the edge of the box (== integer),
// nimg0 may be equal to nimg1 and nimg can be 0. Skip this extreme condition.
return 0;
}
int nimg0 = 0;
int nimg1 = 1;
// If submesh is not identical to mesh, it means the product of the basis
// functions should be completely inside the unit cell. Only one image needs to
// be considered.
if (offset != 0 || submesh != nx_per_cell) {
// |i> is the steep function and centered inside image 0. Moving |j> all around
// will not change the center of |ij>. The periodic system can be treated as
// non-periodic system so that only one image needs to be considered.
nimg0 = (int)floor(xij_frac);
nimg1 = nimg0 + 1;
edge0 = MAX(edge0, nimg0);
edge1 = MIN(edge1, nimg1);
} else if (periodic) {
nimg0 = (int)floor(edge0);
nimg1 = (int)ceil (edge1);
}
int nimg = nimg1 - nimg0;
int nmx0 = nimg0 * nx_per_cell;
int nmx1 = nimg1 * nx_per_cell;
int nmx = nmx1 - nmx0;
int nx0 = (int)floor(edge0 * nx_per_cell);
int nx1 = (int)ceil (edge1 * nx_per_cell);
int nx0_edge;
int nx1_edge;
// to ensure nx0, nx1 being inside the unit cell
if (periodic) {
nx0 = (nx0 - nmx0) % nx_per_cell;
nx1 = (nx1 - nmx0) % nx_per_cell;
if (nx1 == 0) {
nx1 = nx_per_cell;
}
}
// If only 1 image is required, after drawing the grids to the unit cell
// as above, the periodic system can be treated as a non-periodic
// system, which requires [nx0:nx1] being inside submesh. It is
// necessary because xij+/-cutoff may be out of the submesh for periodic
// systems when offset and submesh are specified.
if (nimg == 1) {
nx0 = MIN(nx0, offset + submesh);
nx0 = MAX(nx0, offset);
nx1 = MIN(nx1, offset + submesh);
nx1 = MAX(nx1, offset);
nx0_edge = nx0;
nx1_edge = nx1;
} else {
nx0_edge = 0;
nx1_edge = nmx;
}
img_slice[0] = nimg0;
img_slice[1] = nimg1;
grid_slice[0] = nx0;
grid_slice[1] = nx1;
int ngridx = _num_grids_on_x(nimg, nx0, nx1, nx_per_cell);
if (ngridx == 0) {
return 0;
}
int i, m, l;
double *px0;
double *gridx = cache;
double *xs_all = cache + nmx;
if (nimg == 1) {
xs_all = xs_exp;
}
int grid_close_to_xij = rint(xij_frac * nx_per_cell) - nmx0;
grid_close_to_xij = MIN(grid_close_to_xij, nx1_edge);
grid_close_to_xij = MAX(grid_close_to_xij, nx0_edge);
double img0_x = a * nimg0;
double dx = a / nx_per_cell;
double base_x = img0_x + dx * grid_close_to_xij;
double x0xij = base_x - xij;
double _x0x0 = -aij * x0xij * x0xij;
if (_x0x0 < EXPMIN) {
return 0;
}
double _dxdx = -aij * dx * dx;
double _x0dx = -2 * aij * x0xij * dx;
double exp_dxdx = exp(_dxdx);
double exp_2dxdx = exp_dxdx * exp_dxdx;
double exp_x0dx = exp(_x0dx + _dxdx);
double exp_x0x0 = exp(_x0x0);
for (i = grid_close_to_xij; i < nx1_edge; i++) {
xs_all[i] = exp_x0x0;
exp_x0x0 *= exp_x0dx;
exp_x0dx *= exp_2dxdx;
}
exp_x0dx = exp(_dxdx - _x0dx);
exp_x0x0 = exp(_x0x0);
for (i = grid_close_to_xij-1; i >= nx0_edge; i--) {
exp_x0x0 *= exp_x0dx;
exp_x0dx *= exp_2dxdx;
xs_all[i] = exp_x0x0;
}
if (topl > 0) {
double x0xi = img0_x - xi;
for (i = nx0_edge; i < nx1_edge; i++) {
gridx[i] = x0xi + i * dx;
}
for (l = 1; l <= topl; l++) {
px0 = xs_all + (l-1) * nmx;
for (i = nx0_edge; i < nx1_edge; i++) {
px0[nmx+i] = px0[i] * gridx[i];
}
}
}
if (nimg > 1) {
for (l = 0; l <= topl; l++) {
px0 = xs_all + l * nmx;
for (i = 0; i < nx_per_cell; i++) {
xs_exp[l*nx_per_cell+i] = px0[i];
}
for (m = 1; m < nimg; m++) {
px0 = xs_all + l * nmx + m*nx_per_cell;
for (i = 0; i < nx_per_cell; i++) {
xs_exp[l*nx_per_cell+i] += px0[i];
}
}
}
}
return ngridx;
}
static int _init_orth_data(double **xs_exp, double **ys_exp, double **zs_exp,
int *img_slice, int *grid_slice,
int *offset, int *submesh, int *mesh,
int topl, int dimension, double cutoff,
double ai, double aj, double *ri, double *rj,
double *a, double *b, double *cache)
{
int l1 = topl + 1;
*xs_exp = cache;
*ys_exp = *xs_exp + l1 * mesh[0];
*zs_exp = *ys_exp + l1 * mesh[1];
int data_size = l1 * (mesh[0] + mesh[1] + mesh[2]);
cache += data_size;
int ngridx = _orth_components(*xs_exp, img_slice, grid_slice,
a[0], b[0], cutoff, ri[0], rj[0], ai, aj,
(dimension>=1), mesh[0], topl,
offset[0], submesh[0], cache);
if (ngridx == 0) {
return 0;
}
int ngridy = _orth_components(*ys_exp, img_slice+2, grid_slice+2,
a[4], b[4], cutoff, ri[1], rj[1], ai, aj,
(dimension>=2), mesh[1], topl,
offset[1], submesh[1], cache);
if (ngridy == 0) {
return 0;
}
int ngridz = _orth_components(*zs_exp, img_slice+4, grid_slice+4,
a[8], b[8], cutoff, ri[2], rj[2], ai, aj,
(dimension>=3), mesh[2], topl,
offset[2], submesh[2], cache);
if (ngridz == 0) {
return 0;
}
return data_size;
}
static void _orth_ints(double *out, double *weights,
int floorl, int topl, double fac,
double *xs_exp, double *ys_exp, double *zs_exp,
int *img_slice, int *grid_slice,
int *offset, int *submesh, int *mesh, double *cache)
{
int l1 = topl + 1;
int nimgx0 = img_slice[0];
int nimgx1 = img_slice[1];
int nimgy0 = img_slice[2];
int nimgy1 = img_slice[3];
int nimgz0 = img_slice[4];
int nimgz1 = img_slice[5];
int nimgx = nimgx1 - nimgx0;
int nimgy = nimgy1 - nimgy0;
int nimgz = nimgz1 - nimgz0;
int nx0 = grid_slice[0];
int nx1 = grid_slice[1];
int ny0 = grid_slice[2];
int ny1 = grid_slice[3];
int nz0 = grid_slice[4];
int nz1 = grid_slice[5];
int ngridx = _num_grids_on_x(nimgx, nx0, nx1, mesh[0]);
int ngridy = _num_grids_on_x(nimgy, ny0, ny1, mesh[1]);
//int ngridz = _num_grids_on_x(nimgz, nz0, nz1, mesh[2]);
const char TRANS_N = 'N';
const double D0 = 0;
const double D1 = 1;
int xcols = mesh[1] * mesh[2];
int ycols = mesh[2];
double *weightyz = cache;
double *weightz = weightyz + l1*xcols;
double *pz, *pweightz;
double val;
int lx, ly, lz;
int l, i, n;
//TODO: optimize the case in which nimgy << mesh[1] and nimgz << mesh[2]
if (nimgx == 1) {
dgemm_(&TRANS_N, &TRANS_N, &xcols, &l1, &ngridx,
&fac, weights+nx0*xcols, &xcols, xs_exp+nx0, mesh,
&D0, weightyz, &xcols);
} else if (nimgx == 2 && !_has_overlap(nx0, nx1, mesh[0])) {
dgemm_(&TRANS_N, &TRANS_N, &xcols, &l1, &nx1,
&fac, weights, &xcols, xs_exp, mesh,
&D0, weightyz, &xcols);
ngridx = mesh[0] - nx0;
dgemm_(&TRANS_N, &TRANS_N, &xcols, &l1, &ngridx,
&fac, weights+nx0*xcols, &xcols, xs_exp+nx0, mesh,
&D1, weightyz, &xcols);
} else {
dgemm_(&TRANS_N, &TRANS_N, &xcols, &l1, mesh,
&fac, weights, &xcols, xs_exp, mesh,
&D0, weightyz, &xcols);
}
if (nimgy == 1) {
for (lx = 0; lx <= topl; lx++) {
dgemm_(&TRANS_N, &TRANS_N, &ycols, &l1, &ngridy,
&D1, weightyz+lx*xcols+ny0*ycols, &ycols, ys_exp+ny0, mesh+1,
&D0, weightz+lx*l1*ycols, &ycols);
// call _orth_dot_z if ngridz << nimgz
}
} else if (nimgy == 2 && !_has_overlap(ny0, ny1, mesh[1])) {
ngridy = mesh[1] - ny0;
for (lx = 0; lx <= topl; lx++) {
dgemm_(&TRANS_N, &TRANS_N, &ycols, &l1, &ny1,
&D1, weightyz+lx*xcols, &ycols, ys_exp, mesh+1,
&D0, weightz+lx*l1*ycols, &ycols);
dgemm_(&TRANS_N, &TRANS_N, &ycols, &l1, &ngridy,
&D1, weightyz+lx*xcols+ny0*ycols, &ycols, ys_exp+ny0, mesh+1,
&D1, weightz+lx*l1*ycols, &ycols);
// call _orth_dot_z if ngridz << nimgz
}
} else {
for (lx = 0; lx <= topl; lx++) {
dgemm_(&TRANS_N, &TRANS_N, &ycols, &l1, mesh+1,
&D1, weightyz+lx*xcols, &ycols, ys_exp, mesh+1,
&D0, weightz+lx*l1*ycols, &ycols);
}
}
if (nimgz == 1) {
for (n = 0, l = floorl; l <= topl; l++) {
for (lx = l; lx >= 0; lx--) {
for (ly = l - lx; ly >= 0; ly--, n++) {
lz = l - lx - ly;
pz = zs_exp + lz * mesh[2];
pweightz = weightz + (lx * l1 + ly) * mesh[2];
val = 0;
for (i = nz0; i < nz1; i++) {
val += pweightz[i] * pz[i];
}
out[n] = val;
} } }
} else if (nimgz == 2 && !_has_overlap(nz0, nz1, mesh[2])) {
for (n = 0, l = floorl; l <= topl; l++) {
for (lx = l; lx >= 0; lx--) {
for (ly = l - lx; ly >= 0; ly--, n++) {
lz = l - lx - ly;
pz = zs_exp + lz * mesh[2];
pweightz = weightz + (lx * l1 + ly) * mesh[2];
val = 0;
for (i = 0; i < nz1; i++) {
val += pweightz[i] * pz[i];
}
for (i = nz0; i < mesh[2]; i++) {
val += pweightz[i] * pz[i];
}
out[n] = val;
} } }
} else {
for (n = 0, l = floorl; l <= topl; l++) {
for (lx = l; lx >= 0; lx--) {
for (ly = l - lx; ly >= 0; ly--, n++) {
lz = l - lx - ly;
pz = zs_exp + lz * mesh[2];
pweightz = weightz + (lx * l1 + ly) * mesh[2];
val = 0;
for (i = 0; i < mesh[2]; i++) {
val += pweightz[i] * pz[i];
}
out[n] = val;
} } }
}
}
int NUMINTeval_lda_orth(double *weights, double *out, int comp,
int li, int lj, double ai, double aj,
double *ri, double *rj, double fac, double log_prec,
int dimension, double *a, double *b,
int *offset, int *submesh, int *mesh, double *cache)
{
int floorl = li;
int topl = li + lj;
int offset_g1d = _CUM_LEN_CART[floorl] - _LEN_CART[floorl];
int len_g3d = _CUM_LEN_CART[topl] - offset_g1d;
double cutoff = gto_rcut(ai+aj, topl, fac, log_prec);
double *g3d = cache;
cache += len_g3d;
int img_slice[6];
int grid_slice[6];
double *xs_exp, *ys_exp, *zs_exp;
int data_size = _init_orth_data(&xs_exp, &ys_exp, &zs_exp, img_slice,
grid_slice, offset, submesh, mesh,
topl, dimension, cutoff,
ai, aj, ri, rj, a, b, cache);
if (data_size == 0) {
return 0;
}
cache += data_size;
_orth_ints(g3d, weights, floorl, topl, fac, xs_exp, ys_exp, zs_exp,
img_slice, grid_slice, offset, submesh, mesh, cache);
cache = g3d + _MAX_RR_SIZE[topl];
_plain_vrr2d(out, g3d, cache, li, lj, ri, rj);
return 1;
}
static void _rr_nablax_i(double *out, double *li_up, double *li_down,
int li, int lj, double ai)
{
int di = _LEN_CART[li];
int di1 = _LEN_CART[li+1];
int dj = _LEN_CART[lj];
int li_1 = li - 1;
int i, j, lx, ly;
double fac = -2 * ai;
for (i = 0; i < di; i++) {
for (j = 0; j < dj; j++) {
out[di*j+i] += li_up[di1*j+WHEREX_IF_L_INC1(i)] * fac;
}
}
if (li_1 >= 0) {
di1 = _LEN_CART[li_1];
for (i = 0, lx = li_1; lx >= 0; lx--) {
for (ly = li_1 - lx; ly >= 0; ly--, i++) {
//lz = li_1 - lx - ly;
fac = lx + 1;
for (j = 0; j < dj; j++) {
out[di*j+WHEREX_IF_L_INC1(i)] += li_down[di1*j+i] * fac;
}
} }
}
}
static void _rr_nablay_i(double *out, double *li_up, double *li_down,
int li, int lj, double ai)
{
int di = _LEN_CART[li];
int di1 = _LEN_CART[li+1];
int dj = _LEN_CART[lj];
int li_1 = li - 1;
int i, j, lx, ly;
double fac = -2 * ai;
for (i = 0; i < di; i++) {
for (j = 0; j < dj; j++) {
out[di*j+i] += li_up[di1*j+WHEREY_IF_L_INC1(i)] * fac;
}
}
if (li_1 >= 0) {
di1 = _LEN_CART[li_1];
for (i = 0, lx = li_1; lx >= 0; lx--) {
for (ly = li_1 - lx; ly >= 0; ly--, i++) {
//lz = li_1 - lx - ly;
fac = ly + 1;
for (j = 0; j < dj; j++) {
out[di*j+WHEREY_IF_L_INC1(i)] += li_down[di1*j+i] * fac;
}
} }
}
}
static void _rr_nablaz_i(double *out, double *li_up, double *li_down,
int li, int lj, double ai)
{
int di = _LEN_CART[li];
int di1 = _LEN_CART[li+1];
int dj = _LEN_CART[lj];
int li_1 = li - 1;
int i, j, lx, ly, lz;
double fac = -2 * ai;
for (i = 0; i < di; i++) {
for (j = 0; j < dj; j++) {
out[di*j+i] += li_up[di1*j+WHEREZ_IF_L_INC1(i)] * fac;
}
}
if (li_1 >= 0) {
di1 = _LEN_CART[li_1];
for (i = 0, lx = li_1; lx >= 0; lx--) {
for (ly = li_1 - lx; ly >= 0; ly--, i++) {
lz = li_1 - lx - ly;
fac = lz + 1;
for (j = 0; j < dj; j++) {
out[di*j+WHEREZ_IF_L_INC1(i)] += li_down[di1*j+i] * fac;
}
} }
}
}
static void _plain_vrr2d_updown(double *out_up, double *out_down,
double *g, double *gbuf2, int li, int lj,
double *ri, double *rj)
{
int nmax = li + 1 + lj;
int li_1 = MAX(li - 1, 0);
double *g00, *g01, *gswap, *pg00, *pg01;
int row_01, col_01, row_00, col_00;
int i, j;
double rirj[3];
rirj[0] = ri[0] - rj[0];
rirj[1] = ri[1] - rj[1];
rirj[2] = ri[2] - rj[2];
g00 = gbuf2;
g01 = g;
for (j = 1; j < lj; j++) {
gswap = g00;
g00 = g01;
g01 = gswap;
pg00 = g00;
pg01 = g01;
for (i = li_1; i <= nmax-j; i++) {
GTOplain_vrr2d_ket_inc1(pg01, pg00, rirj, i, j);
row_01 = _LEN_CART[i];
col_01 = _LEN_CART[j];
row_00 = _LEN_CART[i ];
col_00 = _LEN_CART[j-1];
pg00 += row_00*col_00;
pg01 += row_01*col_01;
}
}
if (li == 0) {
g01 += _LEN_CART[MAX(lj-1, 0)];
} else {
GTOplain_vrr2d_ket_inc1(out_down, g01, rirj, li_1, lj);
g01 += (_LEN_CART[li_1] + _LEN_CART[li]) * _LEN_CART[MAX(lj-1, 0)];
}
GTOplain_vrr2d_ket_inc1(out_up, g01, rirj, li+1, lj);
}
int NUMINTeval_gga_orth(double *weights, double *out, int comp,
int li, int lj, double ai, double aj,
double *ri, double *rj, double fac, double log_prec,
int dimension, double *a, double *b,
int *offset, int *submesh, int *mesh, double *cache)
{
int floorl = MAX(li - 1, 0);
int topl = li + 1 + lj;
int di = _LEN_CART[li];
int dj = _LEN_CART[lj];
double cutoff = gto_rcut(ai+aj, topl, fac, log_prec);
double *out_up = cache;
double *out_down = out_up + _LEN_CART[li+1] * dj;
double *g3d = out_down + di * dj;
cache = g3d + _MAX_RR_SIZE[topl];
int img_slice[6];
int grid_slice[6];
double *xs_exp, *ys_exp, *zs_exp;
int data_size = _init_orth_data(&xs_exp, &ys_exp, &zs_exp, img_slice,
grid_slice, offset, submesh, mesh,
topl, dimension, cutoff,
ai, aj, ri, rj, a, b, cache);
if (data_size == 0) {
return 0;
}
cache += data_size;
size_t ngrids = ((size_t)mesh[0]) * mesh[1] * mesh[2];
double *vx = weights + ngrids;
double *vy = vx + ngrids;
double *vz = vy + ngrids;
_orth_ints(g3d, weights, li, li+lj, fac, xs_exp, ys_exp, zs_exp,
img_slice, grid_slice, offset, submesh, mesh, cache);
_plain_vrr2d(out, g3d, cache, li, lj, ri, rj);
_orth_ints(g3d, vx, floorl, topl, fac, xs_exp, ys_exp, zs_exp,
img_slice, grid_slice, offset, submesh, mesh, cache);
_plain_vrr2d_updown(out_up, out_down, g3d, cache, li, lj, ri, rj);
_rr_nablax_i(out, out_up, out_down, li, lj, ai);
_orth_ints(g3d, vy, floorl, topl, fac, xs_exp, ys_exp, zs_exp,
img_slice, grid_slice, offset, submesh, mesh, cache);
_plain_vrr2d_updown(out_up, out_down, g3d, cache, li, lj, ri, rj);
_rr_nablay_i(out, out_up, out_down, li, lj, ai);
_orth_ints(g3d, vz, floorl, topl, fac, xs_exp, ys_exp, zs_exp,
img_slice, grid_slice, offset, submesh, mesh, cache);
_plain_vrr2d_updown(out_up, out_down, g3d, cache, li, lj, ri, rj);
_rr_nablaz_i(out, out_up, out_down, li, lj, ai);
return 1;
}
static int _MAX_AFFINE_SIZE[] = {
1, 8, 32, 108, 270, 640, 1280, 2500, 4375, 7560, 12096, 19208, 28812,
43008, 61440, 87480,
};
/*
* x = a00 x' + a10 y' + a20 z'
* y = a01 x' + a11 y' + a21 z'
* z = a02 x' + a12 y' + a22 z'
* Given f(x',y',z') use the above equations to evaluate f(x,y,z)
*/
static void _affine_trans(double *out, double *int3d, double *a,
int floorl, int topl, double *cache)
{
if (topl == 0) {
out[0] = int3d[0];
return;
}
int lx, ly, lz, l, m, n, i;
int l1, l1l1, l1l1l1, lll;
double *old = int3d;
double *new = cache + _MAX_AFFINE_SIZE[topl];
double *oldx, *oldy, *oldz, *newx, *tmp;
double vx, vy, vz;
if (floorl == 0) {
out[0] = int3d[0];
out += 1;
}
for (m = 1, l = topl; m <= topl; m++, l--) {
l1 = l + 1;
l1l1 = l1 * l1;
lll = l * l * l;
l1l1l1 = l1l1 * l1;
newx = new;
// attach x
for (i = STARTX_IF_L_DEC1(m); i < _LEN_CART[m-1]; i++) {
oldx = old + i * l1l1l1 + l1l1;
oldy = old + i * l1l1l1 + l1;
oldz = old + i * l1l1l1 + 1;
for (n = 0, lx = 0; lx < l; lx++) {
for (ly = 0; ly < l; ly++) {
for (lz = 0; lz < l; lz++, n++) {
vx = oldx[lx*l1l1+ly*l1+lz];
vy = oldy[lx*l1l1+ly*l1+lz];
vz = oldz[lx*l1l1+ly*l1+lz];
newx[n] = vx * a[0] + vy * a[3] + vz * a[6];
} } }
newx += lll;
}
// attach y
for (i = STARTY_IF_L_DEC1(m); i < _LEN_CART[m-1]; i++) {
oldx = old + i * l1l1l1 + l1l1;
oldy = old + i * l1l1l1 + l1;
oldz = old + i * l1l1l1 + 1;
for (n = 0, lx = 0; lx < l; lx++) {
for (ly = 0; ly < l; ly++) {
for (lz = 0; lz < l; lz++, n++) {
vx = oldx[lx*l1l1+ly*l1+lz];
vy = oldy[lx*l1l1+ly*l1+lz];
vz = oldz[lx*l1l1+ly*l1+lz];
newx[n] = vx * a[1] + vy * a[4] + vz * a[7];
} } }
newx += lll;
}
// attach z
i = STARTZ_IF_L_DEC1(m);
oldx = old + i * l1l1l1 + l1l1;
oldy = old + i * l1l1l1 + l1;
oldz = old + i * l1l1l1 + 1;
for (n = 0, lx = 0; lx < l; lx++) {
for (ly = 0; ly < l; ly++) {
for (lz = 0; lz < l; lz++, n++) {
vx = oldx[lx*l1l1+ly*l1+lz];
vy = oldy[lx*l1l1+ly*l1+lz];
vz = oldz[lx*l1l1+ly*l1+lz];
newx[n] = vx * a[2] + vy * a[5] + vz * a[8];
} } }
if (floorl <= m) {
for (i = 0; i < _LEN_CART[m]; i++) {
out[i] = new[i * lll];
}
out += _LEN_CART[m];
}
if (m == 1) {
old = new;
new = cache;
} else {
tmp = old;
old = new;
new = tmp;
}
}
}
static void _reverse_affine_trans(double *out3d, double *in, double *a,
int floorl, int topl, double *cache)
{
if (topl == 0) {
out3d[0] = in[0];
return;
}
int lx, ly, lz, l, m, n, i;
int l1, l1l1, l1l1l1, lll;
double *cart = in;
double *old = cache;
double *new = cache + _MAX_AFFINE_SIZE[topl];
double *oldx, *newx, *newy, *newz, *tmp;
for (l = floorl; l <= topl; l++) {
cart += _LEN_CART[l];
}
for (l = 1, m = topl; l <= topl; l++, m--) {
l1 = l + 1;
l1l1 = l1 * l1;
lll = l * l * l;
l1l1l1 = l1l1 * l1;
if (l == topl) {
new = out3d;
}
for (n = 0; n < l1l1l1*_LEN_CART[m-1]; n++) {
new[n] = 0;
}
if (floorl <= m) {
cart -= _LEN_CART[m];
for (i = 0; i < _LEN_CART[m]; i++) {
old[i * lll] = cart[i];
}
}
oldx = old;
// attach x
for (i = STARTX_IF_L_DEC1(m); i < _LEN_CART[m-1]; i++) {
newx = new + i * l1l1l1 + l1l1;
newy = new + i * l1l1l1 + l1;
newz = new + i * l1l1l1 + 1;
for (n = 0, lx = 0; lx < l; lx++) {
for (ly = 0; ly < l; ly++) {
for (lz = 0; lz < l; lz++, n++) {
newx[lx*l1l1+ly*l1+lz] += a[0] * oldx[n];
newy[lx*l1l1+ly*l1+lz] += a[3] * oldx[n];
newz[lx*l1l1+ly*l1+lz] += a[6] * oldx[n];
} } }
oldx += lll;
}
// attach y
for (i = STARTY_IF_L_DEC1(m); i < _LEN_CART[m-1]; i++) {
newx = new + i * l1l1l1 + l1l1;
newy = new + i * l1l1l1 + l1;
newz = new + i * l1l1l1 + 1;
for (n = 0, lx = 0; lx < l; lx++) {
for (ly = 0; ly < l; ly++) {
for (lz = 0; lz < l; lz++, n++) {
newx[lx*l1l1+ly*l1+lz] += a[1] * oldx[n];
newy[lx*l1l1+ly*l1+lz] += a[4] * oldx[n];
newz[lx*l1l1+ly*l1+lz] += a[7] * oldx[n];
} } }
oldx += lll;
}
// attach z
i = STARTZ_IF_L_DEC1(m);
newx = new + i * l1l1l1 + l1l1;
newy = new + i * l1l1l1 + l1;
newz = new + i * l1l1l1 + 1;
for (n = 0, lx = 0; lx < l; lx++) {
for (ly = 0; ly < l; ly++) {
for (lz = 0; lz < l; lz++, n++) {
newx[lx*l1l1+ly*l1+lz] += a[2] * oldx[n];
newy[lx*l1l1+ly*l1+lz] += a[5] * oldx[n];
newz[lx*l1l1+ly*l1+lz] += a[8] * oldx[n];
} } }
tmp = new;
new = old;
old = tmp;
}
if (floorl == 0) {
out3d[0] = in[0];
}
}
static int _nonorth_components(double *xs_exp, int *img_slice, int *grid_slice,
double *b, int periodic, int nx_per_cell,
int topl, int offset, int submesh,
double xi_frac, double xij_frac, double cutoff)
{
double heights_inv = sqrt(SQUARE(b));
double edge0 = xij_frac - cutoff * heights_inv;
double edge1 = xij_frac + cutoff * heights_inv;
if (edge0 == edge1) {
// cutoff may be so small that it does not provide difference to edge0 and
// edge1. When edge0 and edge1 are right on the edge of the box (== integer),
// nimg0 may be equal to nimg1 and nimg can be 0. Skip this extreme condition.
return 0;
}
int nimg0 = 0;
int nimg1 = 1;
// If submesh is not identical to mesh, it means the product of the basis
// functions should be completely inside the unit cell. Only one image needs to
// be considered.
if (offset != 0 || submesh != nx_per_cell) {
// |i> is the steep function and centered inside image 0. Moving |j> all around
// will not change the center of |ij>. The periodic system can be treated as
// non-periodic system so that only one image needs to be considered.
nimg0 = (int)floor(xij_frac);
nimg1 = nimg0 + 1;
edge0 = MAX(edge0, nimg0);
edge1 = MIN(edge1, nimg1);
} else if (periodic) {
nimg0 = (int)floor(edge0);
nimg1 = (int)ceil (edge1);
}
int nimg = nimg1 - nimg0;
int nmx0 = nimg0 * nx_per_cell;
int nx0 = (int)floor(edge0 * nx_per_cell);
int nx1 = (int)ceil (edge1 * nx_per_cell);
if (nimg == 1) {
nx0 = MIN(nx0, nmx0 + offset + submesh);
nx0 = MAX(nx0, nmx0 + offset);
nx1 = MIN(nx1, nmx0 + offset + submesh);
nx1 = MAX(nx1, nmx0 + offset);
}
img_slice[0] = nimg0;
img_slice[1] = nimg1;
grid_slice[0] = nx0;
grid_slice[1] = nx1;
int nx = nx1 - nx0;
if (nx <= 0) {
return 0;
}
int i, l;
double x0;
double dx = 1. / nx_per_cell;
double *pxs_exp;
for (i = 0; i < nx; i++) {
xs_exp[i] = 1;
}
for (l = 1; l <= topl; l++) {
pxs_exp = xs_exp + (l-1) * nx;
x0 = nx0 * dx - xi_frac;
for (i = 0; i < nx; i++, x0+=dx) {
xs_exp[l*nx+i] = x0 * pxs_exp[i];
}
}
return nx;
}
static void _nonorth_dot_z(double *val, double *weights, int meshz,
int nz0, int nz1, int grid_close_to_zij,
double e_z0z0, double e_z0dz, double e_dzdz,
double _z0dz, double _dzdz)
{
int iz, iz1;
if (e_z0z0 == 0) {
for (iz = 0; iz < nz1-nz0; iz++) {
val[iz] = 0;
}
return;
}
double exp_2dzdz = e_dzdz * e_dzdz;
double exp_z0z0, exp_z0dz;
exp_z0z0 = e_z0z0;
exp_z0dz = e_z0dz * e_dzdz;
//:iz1 = grid_close_to_zij % meshz + meshz;
//:for (iz = grid_close_to_zij-nz0; iz < nz1-nz0; iz++, iz1++) {
//: if (iz1 >= meshz) {
//: iz1 -= meshz;
//: }
//: val[iz] = weights[iz1] * exp_z0z0;
//: exp_z0z0 *= exp_z0dz;
//: exp_z0dz *= exp_2dzdz;
//:}
iz1 = grid_close_to_zij % meshz;
if (iz1 < 0) {
iz1 += meshz;
}
iz = grid_close_to_zij-nz0;
while (iz+meshz-iz1 < nz1-nz0) {
for (; iz1 < meshz; iz1++, iz++) {
val[iz] = weights[iz1] * exp_z0z0;
exp_z0z0 *= exp_z0dz;
exp_z0dz *= exp_2dzdz;
}
iz1 = 0;
}
for (; iz < nz1-nz0; iz++, iz1++) {
val[iz] = weights[iz1] * exp_z0z0;
exp_z0z0 *= exp_z0dz;
exp_z0dz *= exp_2dzdz;
}
exp_z0z0 = e_z0z0;
if (e_z0dz != 0) {
exp_z0dz = e_dzdz / e_z0dz;
} else {
exp_z0dz = exp(_dzdz - _z0dz);
}
//:iz1 = (grid_close_to_zij-1) % meshz;
//:for (iz = grid_close_to_zij-nz0-1; iz >= 0; iz--, iz1--) {
//: if (iz1 < 0) {
//: iz1 += meshz;
//: }
//: exp_z0z0 *= exp_z0dz;
//: exp_z0dz *= exp_2dzdz;
//: val[iz] = weights[iz1] * exp_z0z0;
//:}
iz1 = (grid_close_to_zij-1) % meshz;
if (iz1 < 0) {
iz1 += meshz;
}
iz = grid_close_to_zij-nz0 - 1;
while (iz-iz1 >= 0) {
for (; iz1 >= 0; iz1--, iz--) {
exp_z0z0 *= exp_z0dz;
exp_z0dz *= exp_2dzdz;
val[iz] = weights[iz1] * exp_z0z0;
}
iz1 = meshz - 1;
}
for (; iz >= 0; iz--, iz1--) {
exp_z0z0 *= exp_z0dz;
exp_z0dz *= exp_2dzdz;
val[iz] = weights[iz1] * exp_z0z0;
}
}
static void _nonorth_dot_z_1img(double *val, double *weights, int meshz,
int nz0, int nz1, int grid_close_to_zij,
double e_z0z0, double e_z0dz, double e_dzdz,
double _z0dz, double _dzdz)
{
int iz, iz1;
if (e_z0z0 == 0) {
for (iz = 0; iz < nz1-nz0; iz++) {
val[iz] = 0;
}
return;
}
double exp_2dzdz = e_dzdz * e_dzdz;
double exp_z0z0, exp_z0dz;
exp_z0z0 = e_z0z0;
exp_z0dz = e_z0dz * e_dzdz;
iz1 = grid_close_to_zij % meshz;
if (iz1 < 0) {
iz1 += meshz;
}
for (iz = grid_close_to_zij-nz0; iz < nz1-nz0; iz++, iz1++) {
val[iz] = weights[iz1] * exp_z0z0;
exp_z0z0 *= exp_z0dz;
exp_z0dz *= exp_2dzdz;
}
exp_z0z0 = e_z0z0;
if (e_z0dz != 0) {
exp_z0dz = e_dzdz / e_z0dz;
} else {
exp_z0dz = exp(_dzdz - _z0dz);
}
iz1 = (grid_close_to_zij-1) % meshz;
if (iz1 < 0) {
iz1 += meshz;
}
for (iz = grid_close_to_zij-nz0-1; iz >= 0; iz--, iz1--) {
exp_z0z0 *= exp_z0dz;
exp_z0dz *= exp_2dzdz;
val[iz] = weights[iz1] * exp_z0z0;
}
}
static void _nonorth_ints(double *out, double *weights, double fac, double aij,
int topl, int dimension,
double *a, double *rij_frac,
int *mesh, int *img_slice, int *grid_slice,
double *xs_exp, double *ys_exp, double *zs_exp,
double *cache)
{
int l1 = topl + 1;
int l1l1 = l1 * l1;
int l1l1l1 = l1l1 * l1;
int nx0 = grid_slice[0];
int nx1 = grid_slice[1];
int ny0 = grid_slice[2];
int ny1 = grid_slice[3];
int nz0 = grid_slice[4];
int nz1 = grid_slice[5];
int ngridx = nx1 - nx0;
int ngridy = ny1 - ny0;
int ngridz = nz1 - nz0;
//int nimgx0 = img_slice[0];
//int nimgx1 = img_slice[1];
//int nimgy0 = img_slice[2];
//int nimgy1 = img_slice[3];
int nimgz0 = img_slice[4];
int nimgz1 = img_slice[5];
//int nimgx = nimgx1 - nimgx0;
//int nimgy = nimgy1 - nimgy0;
int nimgz = nimgz1 - nimgz0;
const char TRANS_T = 'T';
const char TRANS_N = 'N';
const double D0 = 0;
const double D1 = 1;
// aa = einsum('ij,kj->ik', a, a)
//double aa[9];
//int n3 = 3;
//dgemm_(&TRANS_T, &TRANS_N, &n3, &n3, &n3,
// &aij, a, &n3, a, &n3, &D0, aa, &n3);
double aa_xx = aij * (a[0] * a[0] + a[1] * a[1] + a[2] * a[2]);
double aa_xy = aij * (a[0] * a[3] + a[1] * a[4] + a[2] * a[5]);
double aa_xz = aij * (a[0] * a[6] + a[1] * a[7] + a[2] * a[8]);
double aa_yy = aij * (a[3] * a[3] + a[4] * a[4] + a[5] * a[5]);
double aa_yz = aij * (a[3] * a[6] + a[4] * a[7] + a[5] * a[8]);
double aa_zz = aij * (a[6] * a[6] + a[7] * a[7] + a[8] * a[8]);
int ix, iy, ix1, iy1, n;
double dx = 1. / mesh[0];
double dy = 1. / mesh[1];
double dz = 1. / mesh[2];
double *cache_xyz = cache;
double *weight_x = cache_xyz + l1l1l1;
double *weight_z = weight_x + l1l1 * ngridx;
double *weight_yz = weight_z + l1 * ngridz;
double *pweights;
//int grid_close_to_xij = rint(rij_frac[0] * mesh[0]);
int grid_close_to_yij = rint(rij_frac[1] * mesh[1]);
int grid_close_to_zij = rint(rij_frac[2] * mesh[2]);
//grid_close_to_xij = MIN(grid_close_to_xij, nx1);
//grid_close_to_xij = MAX(grid_close_to_xij, nx0);
grid_close_to_yij = MIN(grid_close_to_yij, ny1);
grid_close_to_yij = MAX(grid_close_to_yij, ny0);
grid_close_to_zij = MIN(grid_close_to_zij, nz1);
grid_close_to_zij = MAX(grid_close_to_zij, nz0);
double img0_x = 0;
double img0_y = 0;
double img0_z = 0;
double base_x = img0_x;// + dx * grid_close_to_xij;
double base_y = img0_y + dy * grid_close_to_yij;
double base_z = img0_z + dz * grid_close_to_zij;
double x0xij = base_x - rij_frac[0];
double y0yij = base_y - rij_frac[1];
double z0zij = base_z - rij_frac[2];
double _dydy = -dy * dy * aa_yy;
double _dzdz = -dz * dz * aa_zz;
double _dydz = -dy * dz * aa_yz * 2;
double exp_dydy = exp(_dydy);
double exp_2dydy = exp_dydy * exp_dydy;
double exp_dzdz = exp(_dzdz);
double exp_dydz = exp(_dydz);
double exp_dydz_i = (exp_dydz == 0) ? 0 : 1./exp_dydz;
double x1xij, tmpx, tmpy, tmpz;
double _xyz0xyz0, _xyz0dy, _xyz0dz, _z0dz;
double exp_xyz0xyz0, exp_xyz0dz;
double exp_y0dy, exp_z0z0, exp_z0dz;
ix1 = nx0 % mesh[0] + mesh[0];
for (ix = nx0; ix < nx1; ix++, ix1++) {
if (ix1 >= mesh[0]) {
ix1 -= mesh[0];
}
x1xij = x0xij + ix*dx;
tmpx = x1xij * aa_xx + y0yij * aa_xy + z0zij * aa_xz;
tmpy = x1xij * aa_xy + y0yij * aa_yy + z0zij * aa_yz;
tmpz = x1xij * aa_xz + y0yij * aa_yz + z0zij * aa_zz;
_xyz0xyz0 = -x1xij * tmpx - y0yij * tmpy - z0zij * tmpz;
if (_xyz0xyz0 < EXPMIN) {
// _xyz0dy (and _xyz0dz) can be very big, even greater than the effective range
// of exp function (and produce inf). When exp_xyz0xyz0 is 0 and exp_xyz0dy is
// inf, the product will be ill-defined. |_xyz0dy| should be smaller than
// |_xyz0xyz0| in any situations. exp_xyz0xyz0 should dominate the product
// exp_xyz0xyz0 * exp_xyz0dy. When exp_xyz0xyz0 is 0, the product should be 0.
// All the rest exp products should be smaller than exp_xyz0xyz0 and can be
// neglected.
pweights = weight_x + (ix-nx0)*l1l1;
for (n = 0; n < l1l1; n++) {
pweights[n] = 0;
}
continue;
}
_xyz0dy = -2 * dy * tmpy;
_xyz0dz = -2 * dz * tmpz;
exp_xyz0xyz0 = fac * exp(_xyz0xyz0);
exp_xyz0dz = exp(_xyz0dz);
//exp_xyz0dy = exp(_xyz0dy);
//exp_y0dy = exp_xyz0dy * exp_dydy;
exp_y0dy = exp(_xyz0dy + _dydy);
exp_z0z0 = exp_xyz0xyz0;
exp_z0dz = exp_xyz0dz;
_z0dz = _xyz0dz;
iy1 = grid_close_to_yij % mesh[1] + mesh[1];
for (iy = grid_close_to_yij; iy < ny1; iy++, iy1++) {
if (iy1 >= mesh[1]) {
iy1 -= mesh[1];
}
pweights = weights + (ix1 * mesh[1] + iy1) * mesh[2];
if (nimgz == 1) {
_nonorth_dot_z_1img(weight_yz+(iy-ny0)*ngridz, pweights,
mesh[2], nz0, nz1, grid_close_to_zij,
exp_z0z0, exp_z0dz, exp_dzdz, _z0dz, _dzdz);
} else {
_nonorth_dot_z(weight_yz+(iy-ny0)*ngridz, pweights,
mesh[2], nz0, nz1, grid_close_to_zij,
exp_z0z0, exp_z0dz, exp_dzdz, _z0dz, _dzdz);
}
_z0dz += _dydz;
exp_z0z0 *= exp_y0dy;
exp_z0dz *= exp_dydz;
exp_y0dy *= exp_2dydy;
}
exp_y0dy = exp(_dydy - _xyz0dy);
exp_z0z0 = exp_xyz0xyz0;
exp_z0dz = exp_xyz0dz;
_z0dz = _xyz0dz;
iy1 = (grid_close_to_yij-1) % mesh[1];
for (iy = grid_close_to_yij-1; iy >= ny0; iy--, iy1--) {
if (iy1 < 0) {
iy1 += mesh[1];
}
exp_z0z0 *= exp_y0dy;
exp_y0dy *= exp_2dydy;
_z0dz -= _dydz;
if (exp_dydz != 0) {
exp_z0dz *= exp_dydz_i;
} else {
exp_z0dz = exp(_z0dz);
}
pweights = weights + (ix1 * mesh[1] + iy1) * mesh[2];
if (nimgz == 1) {
_nonorth_dot_z_1img(weight_yz+(iy-ny0)*ngridz, pweights,
mesh[2], nz0, nz1, grid_close_to_zij,
exp_z0z0, exp_z0dz, exp_dzdz, _z0dz, _dzdz);
} else {
_nonorth_dot_z(weight_yz+(iy-ny0)*ngridz, pweights,
mesh[2], nz0, nz1, grid_close_to_zij,
exp_z0z0, exp_z0dz, exp_dzdz, _z0dz, _dzdz);
}
}
dgemm_(&TRANS_N, &TRANS_N, &ngridz, &l1, &ngridy,
&D1, weight_yz, &ngridz, ys_exp, &ngridy,
&D0, weight_z, &ngridz);
dgemm_(&TRANS_T, &TRANS_N, &l1, &l1, &ngridz,
&D1, zs_exp, &ngridz, weight_z, &ngridz,
&D0, weight_x+(ix-nx0)*l1l1, &l1);
}
dgemm_(&TRANS_N, &TRANS_N, &l1l1, &l1, &ngridx,
&D1, weight_x, &l1l1, xs_exp, &ngridx,
&D0, out, &l1l1);
}
static void _make_rij_frac(double *ri_frac, double *rij_frac,
double *ri, double *rj, double ai, double aj,
double *a, double *b)
{
double aij = ai + aj;
double rij[3];
rij[0] = (ai * ri[0] + aj * rj[0]) / aij;
rij[1] = (ai * ri[1] + aj * rj[1]) / aij;
rij[2] = (ai * ri[2] + aj * rj[2]) / aij;
// rij_frac = einsum('ij,j->ik', b, rij)
rij_frac[0] = rij[0] * b[0] + rij[1] * b[1] + rij[2] * b[2];
rij_frac[1] = rij[0] * b[3] + rij[1] * b[4] + rij[2] * b[5];
rij_frac[2] = rij[0] * b[6] + rij[1] * b[7] + rij[2] * b[8];
ri_frac[0] = ri[0] * b[0] + ri[1] * b[1] + ri[2] * b[2];
ri_frac[1] = ri[0] * b[3] + ri[1] * b[4] + ri[2] * b[5];
ri_frac[2] = ri[0] * b[6] + ri[1] * b[7] + ri[2] * b[8];
}
static int _init_nonorth_data(double **xs_exp, double **ys_exp, double **zs_exp,
int *img_slice, int *grid_slice,
int *offset, int *submesh, int *mesh,
int topl, int dimension, double cutoff,
double *a, double *b,
double *ri_frac, double *rij_frac, double *cache)
{
int l1 = topl + 1;
*xs_exp = cache;
int ngridx = _nonorth_components(*xs_exp, img_slice, grid_slice,
b, (dimension>=1), mesh[0], topl,
offset[0], submesh[0], ri_frac[0],
rij_frac[0], cutoff);
if (ngridx == 0) {
return 0;
}
*ys_exp = *xs_exp + l1 * ngridx;
int ngridy = _nonorth_components(*ys_exp, img_slice+2, grid_slice+2,
b+3, (dimension>=2), mesh[1], topl,
offset[1], submesh[1], ri_frac[1],
rij_frac[1], cutoff);
if (ngridy == 0) {
return 0;
}
*zs_exp = *ys_exp + l1 * ngridy;
int ngridz = _nonorth_components(*zs_exp, img_slice+4, grid_slice+4,
b+6, (dimension>=3), mesh[2], topl,
offset[2], submesh[2], ri_frac[2],
rij_frac[2], cutoff);
if (ngridz == 0) {
return 0;
}
int data_size = l1 * (ngridx + ngridy + ngridz);
return data_size;
}
int NUMINTeval_lda_nonorth(double *weights, double *out, int comp,
int li, int lj, double ai, double aj,
double *ri, double *rj, double fac, double log_prec,
int dimension, double *a, double *b,
int *offset, int *submesh, int *mesh, double *cache)
{
int floorl = li;
int topl = li + lj;
int l1 = topl + 1;
double aij = ai + aj;
double cutoff = gto_rcut(aij, topl, fac, log_prec);
int img_slice[6];
int grid_slice[6];
double ri_frac[3];
double rij_frac[3];
double *xs_exp, *ys_exp, *zs_exp;
_make_rij_frac(ri_frac, rij_frac, ri, rj, ai, aj, a, b);
int data_size = _init_nonorth_data(&xs_exp, &ys_exp, &zs_exp,
img_slice, grid_slice,
offset, mesh, mesh,
topl, dimension, cutoff, a, b,
ri_frac, rij_frac, cache);
if (data_size == 0) {
return 0;
}
cache += data_size;
double *g3d = cache;
double *buf = g3d + l1 * l1 * l1;
cache = buf + _MAX_RR_SIZE[topl];
_nonorth_ints(g3d, weights, fac, aij, topl, dimension,
a, rij_frac, mesh, img_slice, grid_slice,
xs_exp, ys_exp, zs_exp, cache);
_affine_trans(buf, g3d, a, floorl, topl, cache);
_plain_vrr2d(out, buf, cache, li, lj, ri, rj);
return 1;
}
int NUMINTeval_gga_nonorth(double *weights, double *out, int comp,
int li, int lj, double ai, double aj,
double *ri, double *rj, double fac, double log_prec,
int dimension, double *a, double *b,
int *offset, int *submesh, int *mesh, double *cache)
{
int floorl = MAX(li - 1, 0);
int topl = li + 1 + lj;
int l1 = topl + 1;
double aij = ai + aj;
double cutoff = gto_rcut(aij, topl, fac, log_prec);
int img_slice[6];
int grid_slice[6];
double ri_frac[3];
double rij_frac[3];
double *xs_exp, *ys_exp, *zs_exp;
_make_rij_frac(ri_frac, rij_frac, ri, rj, ai, aj, a, b);
int data_size = _init_nonorth_data(&xs_exp, &ys_exp, &zs_exp,
img_slice, grid_slice,
offset, mesh, mesh,
topl, dimension, cutoff, a, b,
ri_frac, rij_frac, cache);
if (data_size == 0) {
return 0;
}
cache += data_size;
int dj = _LEN_CART[lj];
double *g3d = cache;
double *buf = g3d + l1 * l1 * l1;
double *out_up = cache;
double *out_down = out_up + _LEN_CART[li+1] * dj;
cache = buf + _MAX_RR_SIZE[topl];
size_t ngrids = ((size_t)mesh[0]) * mesh[1] * mesh[2];
double *vx = weights + ngrids;
double *vy = vx + ngrids;
double *vz = vy + ngrids;
_nonorth_ints(g3d, weights, fac, aij, li+lj, dimension,
a, rij_frac, mesh, img_slice, grid_slice,
xs_exp, ys_exp, zs_exp, cache);
_affine_trans(buf, g3d, a, li, li+lj, cache);
_plain_vrr2d(out, buf, cache, li, lj, ri, rj);
_nonorth_ints(g3d, vx, fac, aij, topl, dimension,
a, rij_frac, mesh, img_slice, grid_slice,
xs_exp, ys_exp, zs_exp, cache);
_affine_trans(buf, g3d, a, floorl, topl, cache);
_plain_vrr2d_updown(out_up, out_down, buf, cache, li, lj, ri, rj);
_rr_nablax_i(out, out_up, out_down, li, lj, ai);
_nonorth_ints(g3d, vy, fac, aij, topl, dimension,
a, rij_frac, mesh, img_slice, grid_slice,
xs_exp, ys_exp, zs_exp, cache);
_affine_trans(buf, g3d, a, floorl, topl, cache);
_plain_vrr2d_updown(out_up, out_down, buf, cache, li, lj, ri, rj);
_rr_nablay_i(out, out_up, out_down, li, lj, ai);
_nonorth_ints(g3d, vz, fac, aij, topl, dimension,
a, rij_frac, mesh, img_slice, grid_slice,
xs_exp, ys_exp, zs_exp, cache);
_affine_trans(buf, g3d, a, floorl, topl, cache);
_plain_vrr2d_updown(out_up, out_down, buf, cache, li, lj, ri, rj);
_rr_nablaz_i(out, out_up, out_down, li, lj, ai);
return 1;
}
static void _apply_ints(int (*eval_ints)(), double *weights, double *mat,
size_t *dims, int comp, double fac,
double log_prec, int dimension, double *a, double *b,
int *offset, int *submesh, int *mesh, int *shls,
int *atm, int *bas, double *env, double *cache)
{
int i_sh = shls[0];
int j_sh = shls[1];
int li = bas(ANG_OF, i_sh);
int lj = bas(ANG_OF, j_sh);
double *ri = env + atm(PTR_COORD, bas(ATOM_OF, i_sh));
double *rj = env + atm(PTR_COORD, bas(ATOM_OF, j_sh));
double ai = env[bas(PTR_EXP, i_sh)];
double aj = env[bas(PTR_EXP, j_sh)];
double ci = env[bas(PTR_COEFF, i_sh)];
double cj = env[bas(PTR_COEFF, j_sh)];
double aij = ai + aj;
double rrij = CINTsquare_dist(ri, rj);
double eij = (ai * aj / aij) * rrij;
if (eij > EIJCUTOFF) {
return;
}
fac *= exp(-eij) * ci * cj * CINTcommon_fac_sp(li) * CINTcommon_fac_sp(lj);
if (fac < env[PTR_EXPDROP]) {
return;
}
int di = _LEN_CART[li];
int dj = _LEN_CART[lj];
double *out = cache;
cache += comp * di * dj;
int value = (*eval_ints)(weights, out, comp, li, lj, ai, aj, ri, rj,
fac, log_prec, dimension, a, b,
offset, submesh, mesh, cache);
if (value != 0) {
size_t naoi = dims[0];
size_t naoj = dims[1];
int i, j, ic;
for (ic = 0; ic < comp; ic++) {
for (j = 0; j < dj; j++) {
for (i = 0; i < di; i++) {
mat[j*naoi+i] += out[j*di+i];
} }
mat += naoi * naoj;
out += di * dj;
}
}
}
static int _nonorth_cache_size(int *mesh, int l)
{
int dcart = _LEN_CART[l];
int deriv = 1;
int topl = l + l + deriv;
int l1 = topl + 1;
const int nimgs = 1;
int cache_size = 0;
cache_size += l1 * (mesh[0] + mesh[1] + mesh[2]) * nimgs;
cache_size += mesh[1] * mesh[2]; // * nimgs * nimgs
cache_size += l1 * mesh[2] * nimgs;
cache_size += l1 * l1 * mesh[0];
cache_size = MAX(cache_size, _MAX_AFFINE_SIZE[topl]*2);
cache_size += l1 * l1 * l1;
cache_size += _MAX_RR_SIZE[topl];
return dcart*dcart + cache_size;
}
static int _max_cache_size(int (*fsize)(), int *shls_slice, int *bas, int *mesh)
{
int i, n;
int i0 = MIN(shls_slice[0], shls_slice[2]);
int i1 = MAX(shls_slice[1], shls_slice[3]);
int cache_size = 0;
for (i = i0; i < i1; i++) {
n = (*fsize)(mesh, bas(ANG_OF, i));
cache_size = MAX(cache_size, n);
}
return cache_size+1000000;
}
static void shift_bas(double *env_loc, double *env, double *Ls, int ptr, int iL)
{
env_loc[ptr+0] = env[ptr+0] + Ls[iL*3+0];
env_loc[ptr+1] = env[ptr+1] + Ls[iL*3+1];
env_loc[ptr+2] = env[ptr+2] + Ls[iL*3+2];
}
// Numerical integration for uncontracted Cartesian basis
// F_mat needs to be initialized as 0
void NUMINT_fill2c(int (*eval_ints)(), double *weights, double *F_mat,
int comp, int hermi, int *shls_slice, int *ao_loc,
double log_prec, int dimension, int nimgs, double *Ls,
double *a, double *b, int *offset, int *submesh, int *mesh,
int *atm, int natm, int *bas, int nbas, double *env,
int nenv)
{
const int ish0 = shls_slice[0];
const int ish1 = shls_slice[1];
const int jsh0 = shls_slice[2];
const int jsh1 = shls_slice[3];
const int nish = ish1 - ish0;
const int njsh = jsh1 - jsh0;
const size_t naoi = ao_loc[ish1] - ao_loc[ish0];
const size_t naoj = ao_loc[jsh1] - ao_loc[jsh0];
const int cache_size = _max_cache_size(_nonorth_cache_size, shls_slice,
bas, mesh);
if (dimension == 0) {
nimgs = 1;
}
#pragma omp parallel
{
size_t ncij = comp * naoi * naoj;
size_t nijsh = nish * njsh;
size_t dims[] = {naoi, naoj};
size_t ijm;
int ish, jsh, ij, m, i0, j0;
int shls[2];
double *cache = malloc(sizeof(double) * cache_size);
double *env_loc = malloc(sizeof(double)*nenv);
NPdcopy(env_loc, env, nenv);
int ptrxyz;
#pragma omp for schedule(dynamic)
for (ijm = 0; ijm < nimgs*nijsh; ijm++) {
m = ijm / nijsh;
ij = ijm % nijsh;
ish = ij / njsh;
jsh = ij % njsh;
if (hermi != PLAIN && ish > jsh) {
// fill up only upper triangle of F_mat
continue;
}
ish += ish0;
jsh += jsh0;
shls[0] = ish;
shls[1] = jsh;
i0 = ao_loc[ish] - ao_loc[ish0];
j0 = ao_loc[jsh] - ao_loc[jsh0];
if (dimension != 0) {
ptrxyz = atm(PTR_COORD, bas(ATOM_OF,jsh));
shift_bas(env_loc, env, Ls, ptrxyz, m);
}
_apply_ints(eval_ints, weights, F_mat+m*ncij+j0*naoi+i0,
dims, comp, 1., log_prec, dimension, a, b,
offset, submesh, mesh,
shls, atm, bas, env_loc, cache);
}
free(cache);
free(env_loc);
}
}
/*************************************************
*
* rho
*
*************************************************/
void GTOreverse_vrr2d_ket_inc1(double *g01, double *g00,
double *rirj, int li, int lj);
/* (li,lj) => (li+lj,0) */
void GTOreverse_vrr2d_ket(double *g00, double *g01,
int li, int lj, double *ri, double *rj)
{
int nmax = li + lj;
double *out = g00;
double *gswap, *pg00, *pg01;
int row_01, col_01, row_00, col_00, row_g;
int i, j, n;
double rirj[3];
rirj[0] = ri[0] - rj[0];
rirj[1] = ri[1] - rj[1];
rirj[2] = ri[2] - rj[2];
for (j = lj; j > 0; j--) {
col_01 = _LEN_CART[j];
col_00 = _LEN_CART[j-1];
row_g = _CUM_LEN_CART[nmax+1-j] - _CUM_LEN_CART[li] + _LEN_CART[li];
for (n = 0; n < row_g*col_00; n++) {
g00[n] = 0;
}
pg00 = g00;
pg01 = g01;
for (i = li; i <= nmax-j; i++) {
GTOreverse_vrr2d_ket_inc1(pg01, pg00, rirj, i, j);
row_01 = _LEN_CART[i];
row_00 = _LEN_CART[i];
pg00 += row_00 * col_00;
pg01 += row_01 * col_01;
}
gswap = g00;
g00 = g01;
g01 = gswap;
}
if (out != g01) {
row_g = _CUM_LEN_CART[nmax] - _CUM_LEN_CART[li] + _LEN_CART[li];
for (n = 0; n < row_g; n++) {
out[n] = g01[n];
}
}
}
static void _cart_to_xyz(double *dm_xyz, double *dm_cart,
int floorl, int topl, int l1)
{
int l1l1 = l1 * l1;
int l, lx, ly, lz, n;
for (n = 0, l = floorl; l <= topl; l++) {
for (lx = l; lx >= 0; lx--) {
for (ly = l - lx; ly >= 0; ly--, n++) {
lz = l - lx - ly;
dm_xyz[lx*l1l1+ly*l1+lz] += dm_cart[n];
} } }
}
static void _orth_rho(double *rho, double *dm_xyz,
double fac, int topl, int *offset, int *submesh,
int *mesh, int *img_slice, int *grid_slice,
double *xs_exp, double *ys_exp, double *zs_exp,
double *cache)
{
int l1 = topl + 1;
int l1l1 = l1 * l1;
int nimgx0 = img_slice[0];
int nimgx1 = img_slice[1];
int nimgy0 = img_slice[2];
int nimgy1 = img_slice[3];
int nimgz0 = img_slice[4];
int nimgz1 = img_slice[5];
int nimgx = nimgx1 - nimgx0;
int nimgy = nimgy1 - nimgy0;
int nimgz = nimgz1 - nimgz0;
int nx0 = MAX(grid_slice[0], offset[0]);
int nx1 = MIN(grid_slice[1], offset[0]+submesh[0]);
int ny0 = MAX(grid_slice[2], offset[1]);
int ny1 = MIN(grid_slice[3], offset[1]+submesh[1]);
int nz0 = MAX(grid_slice[4], offset[2]);
int nz1 = MIN(grid_slice[5], offset[2]+submesh[2]);
int ngridx = _num_grids_on_x(nimgx, nx0, nx1, mesh[0]);
int ngridy = _num_grids_on_x(nimgy, ny0, ny1, mesh[1]);
int ngridz = _num_grids_on_x(nimgz, nz0, nz1, mesh[2]);
if (ngridx == 0 || ngridy == 0 || ngridz == 0) {
return;
}
const char TRANS_N = 'N';
const char TRANS_T = 'T';
const double D0 = 0;
const double D1 = 1;
int xcols = submesh[1] * submesh[2];
double *xyr = cache;
double *xqr = xyr + l1l1 * submesh[2];
int i, l;
if (nimgz == 1) {
for (l = 0; l <= topl; l++) {
for (i = offset[2]; i < nz0; i++) {
zs_exp[l*mesh[2]+i] = 0;
}
for (i = nz1; i < offset[2]+submesh[2]; i++) {
zs_exp[l*mesh[2]+i] = 0;
}
}
} else if (nimgz == 2 && !_has_overlap(nz0, nz1, mesh[2])) {
for (l = 0; l <= topl; l++) {
for (i = nz1; i < nz0; i++) {
zs_exp[l*mesh[2]+i] = 0;
}
}
}
dgemm_(&TRANS_N, &TRANS_N, submesh+2, &l1l1, &l1,
&fac, zs_exp+offset[2], mesh+2, dm_xyz, &l1,
&D0, xyr, submesh+2);
if (nimgy == 1) {
for (l = 0; l <= topl; l++) {
for (i = 0; i < (ny0-offset[1])*submesh[2]; i++) {
xqr[l*xcols+i] = 0;
}
for (i = (ny1-offset[1])*submesh[2]; i < xcols; i++) {
xqr[l*xcols+i] = 0;
}
dgemm_(&TRANS_N, &TRANS_T, submesh+2, &ngridy, &l1,
&D1, xyr+l*l1*submesh[2], submesh+2, ys_exp+ny0, mesh+1,
&D0, xqr+l*xcols+(ny0-offset[1])*submesh[2], submesh+2);
}
} else if (nimgy == 2 && !_has_overlap(ny0, ny1, mesh[1])) {
for (l = 0; l <= topl; l++) {
ngridy = ny1 - offset[1];
dgemm_(&TRANS_N, &TRANS_T, submesh+2, &ngridy, &l1,
&D1, xyr+l*l1*submesh[2], submesh+2, ys_exp+offset[1], mesh+1,
&D0, xqr+l*xcols, submesh+2);
for (i = (ny1-offset[1])*submesh[2]; i < (ny0-offset[1])*submesh[2]; i++) {
xqr[l*xcols+i] = 0;
}
ngridy = offset[1] + submesh[1] - ny0;
dgemm_(&TRANS_N, &TRANS_T, submesh+2, &ngridy, &l1,
&D1, xyr+l*l1*submesh[2], submesh+2, ys_exp+ny0, mesh+1,
&D0, xqr+l*xcols+(ny0-offset[1])*submesh[2], submesh+2);
}
} else {
for (l = 0; l <= topl; l++) {
dgemm_(&TRANS_N, &TRANS_T, submesh+2, submesh+1, &l1,
&D1, xyr+l*l1*submesh[2], submesh+2, ys_exp+offset[1], mesh+1,
&D0, xqr+l*xcols, submesh+2);
}
}
if (nimgx == 1) {
dgemm_(&TRANS_N, &TRANS_T, &xcols, &ngridx, &l1,
&D1, xqr, &xcols, xs_exp+nx0, mesh,
&D1, rho+(nx0-offset[0])*xcols, &xcols);
} else if (nimgx == 2 && !_has_overlap(nx0, nx1, mesh[0])) {
ngridx = nx1 - offset[2];
dgemm_(&TRANS_N, &TRANS_T, &xcols, &ngridx, &l1,
&D1, xqr, &xcols, xs_exp+offset[0], mesh,
&D1, rho, &xcols);
ngridx = offset[0] + submesh[0] - nx0;
dgemm_(&TRANS_N, &TRANS_T, &xcols, &ngridx, &l1,
&D1, xqr, &xcols, xs_exp+nx0, mesh,
&D1, rho+(nx0-offset[0])*xcols, &xcols);
} else {
dgemm_(&TRANS_N, &TRANS_T, &xcols, submesh, &l1,
&D1, xqr, &xcols, xs_exp+offset[0], mesh,
&D1, rho, &xcols);
}
}
static void _dm_vrr6d(double *dm_cart, double *dm, size_t naoi,
int li, int lj, double *ri, double *rj, double *cache)
{
int di = _LEN_CART[li];
int dj = _LEN_CART[lj];
double *dm_6d = cache;
int i, j;
for (j = 0; j < dj; j++) {
for (i = 0; i < di; i++) {
dm_6d[j*di+i] = dm[j*naoi+i];
}
}
GTOreverse_vrr2d_ket(dm_cart, dm_6d, li, lj, ri, rj);
}
void NUMINTrho_lda_orth(double *rho, double *dm, int comp, size_t naoi,
int li, int lj, double ai, double aj,
double *ri, double *rj, double fac, double log_prec,
int dimension, double *a, double *b,
int *offset, int *submesh, int *mesh, double *cache)
{
int topl = li + lj;
int l1 = topl + 1;
int l1l1l1 = l1 * l1 * l1;
double cutoff = gto_rcut(ai+aj, topl, fac, log_prec);
int img_slice[6];
int grid_slice[6];
double *xs_exp, *ys_exp, *zs_exp;
int data_size = _init_orth_data(&xs_exp, &ys_exp, &zs_exp, img_slice,
grid_slice, offset, submesh, mesh,
topl, dimension, cutoff,
ai, aj, ri, rj, a, b, cache);
if (data_size == 0) {
return;
}
cache += data_size;
double *dm_xyz = cache;
cache += l1l1l1;
double *dm_cart = cache;
double *dm_6d = dm_cart + _MAX_RR_SIZE[topl];
_dm_vrr6d(dm_cart, dm, naoi, li, lj, ri, rj, dm_6d);
NPdset0(dm_xyz, l1l1l1);
_cart_to_xyz(dm_xyz, dm_cart, li, topl, l1);
_orth_rho(rho, dm_xyz, fac, topl, offset, submesh, mesh,
img_slice, grid_slice, xs_exp, ys_exp, zs_exp, cache);
}
void NUMINTrho_gga_orth(double *rho, double *dm, int comp, size_t naoi,
int li, int lj, double ai, double aj,
double *ri, double *rj, double fac, double log_prec,
int dimension, double *a, double *b,
int *offset, int *submesh, int *mesh, double *cache)
{
int topl = li + 1 + lj;
int l1 = topl + 1;
int l1l1l1 = l1 * l1 * l1;
double cutoff = gto_rcut(ai+aj, topl, fac, log_prec);
int img_slice[6];
int grid_slice[6];
double *xs_exp, *ys_exp, *zs_exp;
int data_size = _init_orth_data(&xs_exp, &ys_exp, &zs_exp, img_slice,
grid_slice, offset, submesh, mesh,
topl, dimension, cutoff,
ai, aj, ri, rj, a, b, cache);
if (data_size == 0) {
return;
}
cache += data_size;
size_t ngrids = ((size_t)submesh[0]) * submesh[1] * submesh[2];
double *rhox = rho + ngrids;
double *rhoy = rhox + ngrids;
double *rhoz = rhoy + ngrids;
double *dm_xyz = cache;
cache += l1l1l1;
double *dm_cart = cache;
double *dm_6d = dm_cart + _MAX_RR_SIZE[topl];
int di = _LEN_CART[li];
int dj = _LEN_CART[lj];
int i, j, lx, ly, lz;
_dm_vrr6d(dm_cart, dm, naoi, li, lj, ri, rj, dm_6d);
lx = l1 - 1;
NPdset0(dm_xyz, lx * lx * lx);
_cart_to_xyz(dm_xyz, dm_cart, li, topl-1, lx);
_orth_rho(rho, dm_xyz, fac, li+lj, offset, submesh, mesh,
img_slice, grid_slice, xs_exp, ys_exp, zs_exp, cache);
int di1 = _LEN_CART[li+1];
int li_1 = li - 1;
int di_1 = _LEN_CART[MAX(0, li_1)];
double ai2 = -2 * ai;
double fac_li;
NPdset0(dm_6d, di1*dj);
for (i = 0; i < di; i++) {
for (j = 0; j < dj; j++) {
dm_6d[di1*j+WHEREX_IF_L_INC1(i)] = dm[naoi*j+i] * ai2;
}
}
GTOreverse_vrr2d_ket(dm_cart, dm_6d, li+1, lj, ri, rj);
NPdset0(dm_xyz, l1l1l1);
_cart_to_xyz(dm_xyz, dm_cart, li+1, topl, l1);
if (li_1 >= 0) {
for (i = 0, lx = li_1; lx >= 0; lx--) {
for (ly = li_1 - lx; ly >= 0; ly--, i++) {
fac_li = lx + 1;
for (j = 0; j < dj; j++) {
dm_6d[di_1*j+i] = dm[naoi*j+WHEREX_IF_L_INC1(i)] * fac_li;
}
} }
GTOreverse_vrr2d_ket(dm_cart, dm_6d, li_1, lj, ri, rj);
_cart_to_xyz(dm_xyz, dm_cart, li_1, topl-2, l1);
}
_orth_rho(rhox, dm_xyz, fac, topl, offset, submesh, mesh,
img_slice, grid_slice, xs_exp, ys_exp, zs_exp, cache);
NPdset0(dm_6d, _LEN_CART[li+1] * dj);
for (i = 0; i < di; i++) {
for (j = 0; j < dj; j++) {
dm_6d[di1*j+WHEREY_IF_L_INC1(i)] = dm[naoi*j+i] * ai2;
}
}
GTOreverse_vrr2d_ket(dm_cart, dm_6d, li+1, lj, ri, rj);
NPdset0(dm_xyz, l1l1l1);
_cart_to_xyz(dm_xyz, dm_cart, li+1, topl, l1);
if (li_1 >= 0) {
for (i = 0, lx = li_1; lx >= 0; lx--) {
for (ly = li_1 - lx; ly >= 0; ly--, i++) {
fac_li = ly + 1;
for (j = 0; j < dj; j++) {
dm_6d[di_1*j+i] = dm[naoi*j+WHEREY_IF_L_INC1(i)] * fac_li;
}
} }
GTOreverse_vrr2d_ket(dm_cart, dm_6d, li_1, lj, ri, rj);
_cart_to_xyz(dm_xyz, dm_cart, li_1, topl-2, l1);
}
_orth_rho(rhoy, dm_xyz, fac, topl, offset, submesh, mesh,
img_slice, grid_slice, xs_exp, ys_exp, zs_exp, cache);
NPdset0(dm_6d, _LEN_CART[li+1] * dj);
for (i = 0; i < di; i++) {
for (j = 0; j < dj; j++) {
dm_6d[di1*j+WHEREZ_IF_L_INC1(i)] = dm[naoi*j+i] * ai2;
}
}
GTOreverse_vrr2d_ket(dm_cart, dm_6d, li+1, lj, ri, rj);
NPdset0(dm_xyz, l1l1l1);
_cart_to_xyz(dm_xyz, dm_cart, li+1, topl, l1);
if (li_1 >= 0) {
for (i = 0, lx = li_1; lx >= 0; lx--) {
for (ly = li_1 - lx; ly >= 0; ly--, i++) {
lz = li_1 - lx - ly;
fac_li = lz + 1;
for (j = 0; j < dj; j++) {
dm_6d[di_1*j+i] = dm[naoi*j+WHEREZ_IF_L_INC1(i)] * fac_li;
}
} }
GTOreverse_vrr2d_ket(dm_cart, dm_6d, li_1, lj, ri, rj);
_cart_to_xyz(dm_xyz, dm_cart, li_1, topl-2, l1);
}
_orth_rho(rhoz, dm_xyz, fac, topl, offset, submesh, mesh,
img_slice, grid_slice, xs_exp, ys_exp, zs_exp, cache);
}
static void _nonorth_rho_z(double *rho, double *rhoz, int offset, int meshz,
int nz0, int nz1, int grid_close_to_zij,
double e_z0z0, double e_z0dz, double e_dzdz,
double _z0dz, double _dzdz)
{
if (e_z0z0 == 0) {
return;
}
double exp_2dzdz = e_dzdz * e_dzdz;
double exp_z0z0, exp_z0dz;
int iz, iz1;
rho -= offset; // for the original indexing rho[iz1-offset]
exp_z0z0 = e_z0z0;
exp_z0dz = e_z0dz * e_dzdz;
iz1 = grid_close_to_zij % meshz + meshz;
for (iz = grid_close_to_zij-nz0; iz < nz1-nz0; iz++, iz1++) {
if (iz1 >= meshz) {
iz1 -= meshz;
}
rho[iz1] += rhoz[iz] * exp_z0z0;
exp_z0z0 *= exp_z0dz;
exp_z0dz *= exp_2dzdz;
}
exp_z0z0 = e_z0z0;
if (e_z0dz != 0) {
exp_z0dz = e_dzdz / e_z0dz;
} else {
exp_z0dz = exp(_dzdz - _z0dz);
}
iz1 = (grid_close_to_zij-1) % meshz;
for (iz = grid_close_to_zij-nz0-1; iz >= 0; iz--, iz1--) {
if (iz1 < 0) {
iz1 += meshz;
}
exp_z0z0 *= exp_z0dz;
exp_z0dz *= exp_2dzdz;
rho[iz1] += rhoz[iz] * exp_z0z0;
}
}
static void _nonorth_rho_z_1img(double *rho, double *rhoz, int offset, int meshz,
int nz0, int nz1, int grid_close_to_zij,
double e_z0z0, double e_z0dz, double e_dzdz,
double _z0dz, double _dzdz)
{
if (e_z0z0 == 0) {
return;
}
double exp_2dzdz = e_dzdz * e_dzdz;
double exp_z0z0, exp_z0dz;
int iz, iz1;
rho -= offset; // for the original indexing rho[iz1-offset]
exp_z0z0 = e_z0z0;
exp_z0dz = e_z0dz * e_dzdz;
iz1 = grid_close_to_zij % meshz;
if (iz1 < 0) {
iz1 += meshz;
}
for (iz = grid_close_to_zij-nz0; iz < nz1-nz0; iz++, iz1++) {
rho[iz1] += rhoz[iz] * exp_z0z0;
exp_z0z0 *= exp_z0dz;
exp_z0dz *= exp_2dzdz;
}
exp_z0z0 = e_z0z0;
if (e_z0dz != 0) {
exp_z0dz = e_dzdz / e_z0dz;
} else {
exp_z0dz = exp(_dzdz - _z0dz);
}
iz1 = (grid_close_to_zij-1) % meshz;
if (iz1 < 0) {
iz1 += meshz;
}
for (iz = grid_close_to_zij-nz0-1; iz >= 0; iz--, iz1--) {
exp_z0z0 *= exp_z0dz;
exp_z0dz *= exp_2dzdz;
rho[iz1] += rhoz[iz] * exp_z0z0;
}
}
static void _nonorth_rho_z_with_mask(double *rho, double *rhoz, int8_t *skip,
int offset, int submeshz, int meshz,
int nz0, int nz1, int grid_close_to_zij,
double e_z0z0, double e_z0dz, double e_dzdz,
double _z0dz, double _dzdz)
{
if (e_z0z0 == 0) {
return;
}
double exp_2dzdz = e_dzdz * e_dzdz;
double exp_z0z0, exp_z0dz;
int iz, iz1;
rho -= offset; // for the original indexing rho[iz1-offset]
exp_z0z0 = e_z0z0;
exp_z0dz = e_z0dz * e_dzdz;
iz1 = grid_close_to_zij % meshz + meshz;
for (iz = grid_close_to_zij-nz0; iz < nz1-nz0; iz++, iz1++) {
if (iz1 >= meshz) {
iz1 -= meshz;
}
if (!skip[iz]) {
rho[iz1] += rhoz[iz] * exp_z0z0;
}
exp_z0z0 *= exp_z0dz;
exp_z0dz *= exp_2dzdz;
}
exp_z0z0 = e_z0z0;
if (e_z0dz != 0) {
exp_z0dz = e_dzdz / e_z0dz;
} else {
exp_z0dz = exp(_dzdz - _z0dz);
}
iz1 = (grid_close_to_zij-1) % meshz;
for (iz = grid_close_to_zij-nz0-1; iz >= 0; iz--, iz1--) {
if (iz1 < 0) {
iz1 += meshz;
}
exp_z0z0 *= exp_z0dz;
exp_z0dz *= exp_2dzdz;
if (!skip[iz]) {
rho[iz1] += rhoz[iz] * exp_z0z0;
}
}
}
static int _make_grid_mask(int8_t *skip, int nx0, int nx1, int mesh,
int offset, int submesh)
{
if (offset == 0 && submesh == mesh) { // allows nimg > 1
return 0;
} else if (offset <= nx0 && nx1 <= offset+submesh) { // requires nimg == 1
return 0;
}
int i, i1;
i1 = nx0 % mesh + mesh;
for (i = 0; i < nx1-nx0; i++, i1++) {
if (i1 >= mesh) {
i1 -= mesh;
}
if (offset <= i1 && i1 < offset+submesh) {
skip[i] = 0;
} else {
skip[i] = 1;
}
}
return 1;
}
static void _nonorth_rho(double *rho, double *dm_xyz,
double fac, double aij, int topl, int dimension,
double *a, double *rij_frac,
double *xs_exp, double *ys_exp, double *zs_exp,
int *img_slice, int *grid_slice,
int *offset, int *submesh, int *mesh, double *cache)
{
int l1 = topl + 1;
int l1l1 = l1 * l1;
int nx0 = grid_slice[0];
int nx1 = grid_slice[1];
int ny0 = grid_slice[2];
int ny1 = grid_slice[3];
int nz0 = grid_slice[4];
int nz1 = grid_slice[5];
int ngridx = nx1 - nx0;
int ngridy = ny1 - ny0;
int ngridz = nz1 - nz0;
//int nimgx0 = img_slice[0];
//int nimgx1 = img_slice[1];
//int nimgy0 = img_slice[2];
//int nimgy1 = img_slice[3];
int nimgz0 = img_slice[4];
int nimgz1 = img_slice[5];
//int nimgx = nimgx1 - nimgx0;
//int nimgy = nimgy1 - nimgy0;
int nimgz = nimgz1 - nimgz0;
const char TRANS_T = 'T';
const char TRANS_N = 'N';
const double D0 = 0;
const double D1 = 1;
const int inc1 = 1;
// aa = einsum('ij,kj->ik', a, a)
//double aa[9];
//int n3 = 3;
//dgemm_(&TRANS_T, &TRANS_N, &n3, &n3, &n3,
// &aij, a, &n3, a, &n3, &D0, aa, &n3);
double aa_xx = aij * (a[0] * a[0] + a[1] * a[1] + a[2] * a[2]);
double aa_xy = aij * (a[0] * a[3] + a[1] * a[4] + a[2] * a[5]);
double aa_xz = aij * (a[0] * a[6] + a[1] * a[7] + a[2] * a[8]);
double aa_yy = aij * (a[3] * a[3] + a[4] * a[4] + a[5] * a[5]);
double aa_yz = aij * (a[3] * a[6] + a[4] * a[7] + a[5] * a[8]);
double aa_zz = aij * (a[6] * a[6] + a[7] * a[7] + a[8] * a[8]);
int ix, iy, ix1, iy1;
double dx = 1. / mesh[0];
double dy = 1. / mesh[1];
double dz = 1. / mesh[2];
//int grid_close_to_xij = rint(rij_frac[0] * mesh[0]);
int grid_close_to_yij = rint(rij_frac[1] * mesh[1]);
int grid_close_to_zij = rint(rij_frac[2] * mesh[2]);
//grid_close_to_xij = MIN(grid_close_to_xij, nx1);
//grid_close_to_xij = MAX(grid_close_to_xij, nx0);
grid_close_to_yij = MIN(grid_close_to_yij, ny1);
grid_close_to_yij = MAX(grid_close_to_yij, ny0);
grid_close_to_zij = MIN(grid_close_to_zij, nz1);
grid_close_to_zij = MAX(grid_close_to_zij, nz0);
double img0_x = 0;
double img0_y = 0;
double img0_z = 0;
double base_x = img0_x;// + dx * grid_close_to_xij;
double base_y = img0_y + dy * grid_close_to_yij;
double base_z = img0_z + dz * grid_close_to_zij;
double x0xij = base_x - rij_frac[0];
double y0yij = base_y - rij_frac[1];
double z0zij = base_z - rij_frac[2];
double _dydy = -dy * dy * aa_yy;
double _dzdz = -dz * dz * aa_zz;
double _dydz = -dy * dz * aa_yz * 2;
double exp_dydy = exp(_dydy);
double exp_2dydy = exp_dydy * exp_dydy;
double exp_dzdz = exp(_dzdz);
double exp_dydz = exp(_dydz);
double exp_dydz_i = (exp_dydz == 0) ? 0 : 1./exp_dydz;
double x1xij, tmpx, tmpy, tmpz;
double _xyz0xyz0, _xyz0dy, _xyz0dz, _z0dz;
double exp_xyz0xyz0, exp_xyz0dz;
double exp_y0dy, exp_z0z0, exp_z0dz;
int xcols = ngridy * ngridz;
double *xyr = cache;
double *xqr = xyr + l1l1 * ngridz;
double *rhoz = xqr + l1 * ngridy * ngridz;
double *prho;
int l;
int8_t x_skip[ngridx];
int8_t y_skip[ngridy];
int8_t z_skip[ngridz];
int with_x_mask = _make_grid_mask(x_skip, nx0, nx1, mesh[0], offset[0], submesh[0]);
int with_y_mask = _make_grid_mask(y_skip, ny0, ny1, mesh[1], offset[1], submesh[1]);
int with_z_mask = _make_grid_mask(z_skip, nz0, nz1, mesh[2], offset[2], submesh[2]);
dgemm_(&TRANS_N, &TRANS_N, &ngridz, &l1l1, &l1,
&D1, zs_exp, &ngridz, dm_xyz, &l1, &D0, xyr, &ngridz);
for (l = 0; l <= topl; l++) {
dgemm_(&TRANS_N, &TRANS_T, &ngridz, &ngridy, &l1,
&D1, xyr+l*l1*ngridz, &ngridz, ys_exp, &ngridy,
&D0, xqr+l*xcols, &ngridz);
}
ix1 = nx0 % mesh[0] + mesh[0];
for (ix = 0; ix < nx1-nx0; ix++, ix1++) {
if (ix1 >= mesh[0]) {
ix1 -= mesh[0];
}
if (with_x_mask && x_skip[ix]) {
continue;
}
x1xij = x0xij + (nx0+ix)*dx;
tmpx = x1xij * aa_xx + y0yij * aa_xy + z0zij * aa_xz;
tmpy = x1xij * aa_xy + y0yij * aa_yy + z0zij * aa_yz;
tmpz = x1xij * aa_xz + y0yij * aa_yz + z0zij * aa_zz;
_xyz0xyz0 = -x1xij * tmpx - y0yij * tmpy - z0zij * tmpz;
if (_xyz0xyz0 < EXPMIN) {
continue;
}
_xyz0dy = -2 * dy * tmpy;
_xyz0dz = -2 * dz * tmpz;
exp_xyz0xyz0 = fac * exp(_xyz0xyz0);
exp_xyz0dz = exp(_xyz0dz);
//exp_xyz0dy = exp(_xyz0dy);
//exp_y0dy = exp_xyz0dy * exp_dydy;
exp_y0dy = exp(_xyz0dy + _dydy);
exp_z0z0 = exp_xyz0xyz0;
exp_z0dz = exp_xyz0dz;
_z0dz = _xyz0dz;
iy1 = grid_close_to_yij % mesh[1] + mesh[1];
for (iy = grid_close_to_yij-ny0; iy < ny1-ny0; iy++, iy1++) {
if (exp_z0z0 == 0) {
break;
}
if (iy1 >= mesh[1]) {
iy1 -= mesh[1];
}
if (!with_y_mask || !y_skip[iy]) {
dgemm_(&TRANS_N, &TRANS_T, &ngridz, &inc1, &l1,
&D1, xqr+iy*ngridz, &xcols, xs_exp+ix, &ngridx,
&D0, rhoz, &ngridz);
prho = rho + ((ix1-offset[0])*submesh[1] + iy1-offset[1]) * submesh[2];
if (nimgz == 1) {
_nonorth_rho_z_1img(prho, rhoz, offset[2], mesh[2],
nz0, nz1, grid_close_to_zij,
exp_z0z0, exp_z0dz, exp_dzdz, _z0dz, _dzdz);
} else if (with_z_mask) {
_nonorth_rho_z_with_mask(prho, rhoz, z_skip,
offset[2], submesh[2], mesh[2],
nz0, nz1, grid_close_to_zij,
exp_z0z0, exp_z0dz, exp_dzdz,
_z0dz, _dzdz);
} else {
_nonorth_rho_z(prho, rhoz, offset[2], mesh[2],
nz0, nz1, grid_close_to_zij,
exp_z0z0, exp_z0dz, exp_dzdz, _z0dz, _dzdz);
}
}
_z0dz += _dydz;
exp_z0z0 *= exp_y0dy;
exp_z0dz *= exp_dydz;
exp_y0dy *= exp_2dydy;
}
exp_y0dy = exp(_dydy - _xyz0dy);
exp_z0z0 = exp_xyz0xyz0;
exp_z0dz = exp_xyz0dz;
_z0dz = _xyz0dz;
iy1 = (grid_close_to_yij-1) % mesh[1];
for (iy = grid_close_to_yij-ny0-1; iy >= 0; iy--, iy1--) {
exp_z0z0 *= exp_y0dy;
if (exp_z0z0 == 0) {
break;
}
_z0dz -= _dydz;
if (exp_dydz != 0) {
exp_z0dz *= exp_dydz_i;
} else {
exp_z0dz = exp(_z0dz);
}
exp_y0dy *= exp_2dydy;
if (iy1 < 0) {
iy1 += mesh[1];
}
if (!with_y_mask || !y_skip[iy]) {
dgemm_(&TRANS_N, &TRANS_T, &ngridz, &inc1, &l1,
&D1, xqr+iy*ngridz, &xcols, xs_exp+ix, &ngridx,
&D0, rhoz, &ngridz);
prho = rho + ((ix1-offset[0])*submesh[1] + iy1-offset[1]) * submesh[2];
if (nimgz == 1) {
_nonorth_rho_z_1img(prho, rhoz, offset[2], mesh[2],
nz0, nz1, grid_close_to_zij,
exp_z0z0, exp_z0dz, exp_dzdz, _z0dz, _dzdz);
} else if (with_z_mask) {
_nonorth_rho_z_with_mask(prho, rhoz, z_skip,
offset[2], submesh[2], mesh[2],
nz0, nz1, grid_close_to_zij,
exp_z0z0, exp_z0dz, exp_dzdz,
_z0dz, _dzdz);
} else {
_nonorth_rho_z(prho, rhoz, offset[2], mesh[2],
nz0, nz1, grid_close_to_zij,
exp_z0z0, exp_z0dz, exp_dzdz, _z0dz, _dzdz);
}
}
}
}
}
void NUMINTrho_lda_nonorth(double *rho, double *dm, int comp, size_t naoi,
int li, int lj, double ai, double aj,
double *ri, double *rj, double fac, double log_prec,
int dimension, double *a, double *b,
int *offset, int *submesh, int *mesh, double *cache)
{
int floorl = li;
int topl = li + lj;
int l1 = topl + 1;
double aij = ai + aj;
double cutoff = gto_rcut(aij, topl, fac, log_prec);
int img_slice[6];
int grid_slice[6];
double ri_frac[3];
double rij_frac[3];
double *xs_exp, *ys_exp, *zs_exp;
_make_rij_frac(ri_frac, rij_frac, ri, rj, ai, aj, a, b);
int data_size = _init_nonorth_data(&xs_exp, &ys_exp, &zs_exp,
img_slice, grid_slice,
offset, submesh, mesh,
topl, dimension, cutoff, a, b,
ri_frac, rij_frac, cache);
if (data_size == 0) {
return;
}
cache += data_size;
double *dm_xyz = cache;
cache += l1 * l1 * l1;
double *dm_cart = cache;
double *dm_cache = dm_cart + _CUM_LEN_CART[topl];
_dm_vrr6d(dm_cart, dm, naoi, li, lj, ri, rj, dm_cart+_MAX_RR_SIZE[topl]);
_reverse_affine_trans(dm_xyz, dm_cart, a, floorl, topl, dm_cache);
_nonorth_rho(rho, dm_xyz, fac, aij, topl, dimension,
a, rij_frac, xs_exp, ys_exp, zs_exp,
img_slice, grid_slice, offset, submesh, mesh, cache);
}
static void _merge_dm_xyz_updown(double *dm_xyz, double *dm_xyz1, int l1)
{
int l0 = l1 - 2;
int l1l1 = l1 * l1;
int l0l0 = l0 * l0;
int i, j, k;
for (i = 0; i < l0; i++) {
for (j = 0; j < l0; j++) {
for (k = 0; k < l0; k++) {
dm_xyz[i*l1l1+j*l1+k] += dm_xyz1[i*l0l0+j*l0+k];
} } }
}
void NUMINTrho_gga_nonorth(double *rho, double *dm, int comp, size_t naoi,
int li, int lj, double ai, double aj,
double *ri, double *rj, double fac, double log_prec,
int dimension, double *a, double *b,
int *offset, int *submesh, int *mesh, double *cache)
{
int topl = li + 1 + lj;
int l1 = topl + 1;
int l1l1 = l1 * l1;
double aij = ai + aj;
double cutoff = gto_rcut(aij, topl, fac, log_prec);
int img_slice[6];
int grid_slice[6];
double ri_frac[3];
double rij_frac[3];
double *xs_exp, *ys_exp, *zs_exp;
_make_rij_frac(ri_frac, rij_frac, ri, rj, ai, aj, a, b);
int data_size = _init_nonorth_data(&xs_exp, &ys_exp, &zs_exp,
img_slice, grid_slice,
offset, submesh, mesh,
topl, dimension, cutoff, a, b,
ri_frac, rij_frac, cache);
if (data_size == 0) {
return;
}
cache += data_size;
size_t ngrids = ((size_t)submesh[0]) * submesh[1] * submesh[2];
double *rhox = rho + ngrids;
double *rhoy = rhox + ngrids;
double *rhoz = rhoy + ngrids;
double *dm_xyz = cache;
double *dm_xyz1 = dm_xyz + l1l1 * l1;
cache += l1l1 * l1 * 2;
double *dm_cart = cache;
double *dm_6d = dm_cart + _MAX_RR_SIZE[topl];
int di = _LEN_CART[li];
int dj = _LEN_CART[lj];
int i, j, lx, ly, lz;
_dm_vrr6d(dm_cart, dm, naoi, li, lj, ri, rj, dm_6d);
lx = l1 - 1;
_reverse_affine_trans(dm_xyz, dm_cart, a, li, li+lj, dm_6d);
_nonorth_rho(rho, dm_xyz, fac, aij, li+lj, dimension,
a, rij_frac, xs_exp, ys_exp, zs_exp,
img_slice, grid_slice, offset, submesh, mesh, cache);
int di1 = _LEN_CART[li+1];
int li_1 = li - 1;
int di_1 = _LEN_CART[MAX(0, li_1)];
double ai2 = -2 * ai;
double fac_li;
NPdset0(dm_6d, _LEN_CART[li+1] * dj);
for (i = 0; i < di; i++) {
for (j = 0; j < dj; j++) {
dm_6d[di1*j+WHEREX_IF_L_INC1(i)] = dm[naoi*j+i] * ai2;
}
}
GTOreverse_vrr2d_ket(dm_cart, dm_6d, li+1, lj, ri, rj);
_reverse_affine_trans(dm_xyz, dm_cart, a, li+1, topl, dm_6d);
if (li_1 >= 0) {
for (i = 0, lx = li_1; lx >= 0; lx--) {
for (ly = li_1 - lx; ly >= 0; ly--, i++) {
fac_li = lx + 1;
for (j = 0; j < dj; j++) {
dm_6d[di_1*j+i] = dm[naoi*j+WHEREX_IF_L_INC1(i)] * fac_li;
}
} }
GTOreverse_vrr2d_ket(dm_cart, dm_6d, li_1, lj, ri, rj);
_reverse_affine_trans(dm_xyz1, dm_cart, a, li_1, topl-2, dm_6d);
_merge_dm_xyz_updown(dm_xyz, dm_xyz1, l1);
}
_nonorth_rho(rhox, dm_xyz, fac, aij, topl, dimension,
a, rij_frac, xs_exp, ys_exp, zs_exp,
img_slice, grid_slice, offset, submesh, mesh, cache);
NPdset0(dm_6d, _LEN_CART[li+1] * dj);
for (i = 0; i < di; i++) {
for (j = 0; j < dj; j++) {
dm_6d[di1*j+WHEREY_IF_L_INC1(i)] = dm[naoi*j+i] * ai2;
}
}
GTOreverse_vrr2d_ket(dm_cart, dm_6d, li+1, lj, ri, rj);
_reverse_affine_trans(dm_xyz, dm_cart, a, li+1, topl, dm_6d);
if (li_1 >= 0) {
for (i = 0, lx = li_1; lx >= 0; lx--) {
for (ly = li_1 - lx; ly >= 0; ly--, i++) {
fac_li = ly + 1;
for (j = 0; j < dj; j++) {
dm_6d[di_1*j+i] = dm[naoi*j+WHEREY_IF_L_INC1(i)] * fac_li;
}
} }
GTOreverse_vrr2d_ket(dm_cart, dm_6d, li_1, lj, ri, rj);
_reverse_affine_trans(dm_xyz1, dm_cart, a, li_1, topl-2, dm_6d);
_merge_dm_xyz_updown(dm_xyz, dm_xyz1, l1);
}
_nonorth_rho(rhoy, dm_xyz, fac, aij, topl, dimension,
a, rij_frac, xs_exp, ys_exp, zs_exp,
img_slice, grid_slice, offset, submesh, mesh, cache);
NPdset0(dm_6d, _LEN_CART[li+1] * dj);
for (i = 0; i < di; i++) {
for (j = 0; j < dj; j++) {
dm_6d[di1*j+WHEREZ_IF_L_INC1(i)] = dm[naoi*j+i] * ai2;
}
}
GTOreverse_vrr2d_ket(dm_cart, dm_6d, li+1, lj, ri, rj);
_reverse_affine_trans(dm_xyz, dm_cart, a, li+1, topl, dm_6d);
if (li_1 >= 0) {
for (i = 0, lx = li_1; lx >= 0; lx--) {
for (ly = li_1 - lx; ly >= 0; ly--, i++) {
lz = li_1 - lx - ly;
fac_li = lz + 1;
for (j = 0; j < dj; j++) {
dm_6d[di_1*j+i] = dm[naoi*j+WHEREZ_IF_L_INC1(i)] * fac_li;
}
} }
GTOreverse_vrr2d_ket(dm_cart, dm_6d, li_1, lj, ri, rj);
_reverse_affine_trans(dm_xyz1, dm_cart, a, li_1, topl-2, dm_6d);
_merge_dm_xyz_updown(dm_xyz, dm_xyz1, l1);
}
_nonorth_rho(rhoz, dm_xyz, fac, aij, topl, dimension,
a, rij_frac, xs_exp, ys_exp, zs_exp,
img_slice, grid_slice, offset, submesh, mesh, cache);
}
static void _apply_rho(void (*eval_rho)(), double *rho, double *dm,
size_t *dims, int comp,
double log_prec, int dimension, double *a, double *b,
int *offset, int *submesh, int *mesh, int *shls,
int *atm, int natm, int *bas, int nbas, double *env,
double *cache)
{
const size_t naoi = dims[0];
const int i_sh = shls[0];
const int j_sh = shls[1];
const int li = bas(ANG_OF, i_sh);
const int lj = bas(ANG_OF, j_sh);
double *ri = env + atm(PTR_COORD, bas(ATOM_OF, i_sh));
double *rj = env + atm(PTR_COORD, bas(ATOM_OF, j_sh));
double ai = env[bas(PTR_EXP, i_sh)];
double aj = env[bas(PTR_EXP, j_sh)];
double ci = env[bas(PTR_COEFF, i_sh)];
double cj = env[bas(PTR_COEFF, j_sh)];
double aij = ai + aj;
double rrij = CINTsquare_dist(ri, rj);
double eij = (ai * aj / aij) * rrij;
if (eij > EIJCUTOFF) {
return;
}
double fac = exp(-eij) * ci * cj * CINTcommon_fac_sp(li) * CINTcommon_fac_sp(lj);
if (fac < env[PTR_EXPDROP]) {
return;
}
(*eval_rho)(rho, dm, comp, naoi, li, lj, ai, aj, ri, rj,
fac, log_prec, dimension, a, b,
offset, submesh, mesh, cache);
}
static int _rho_cache_size(int l, int comp, int *mesh)
{
int l1 = l * 2 + 1;
int cache_size = 0;
cache_size += l1 * mesh[1] * mesh[2];
cache_size += l1 * l1 * mesh[2] * 2;
cache_size = MAX(cache_size, 3*_MAX_RR_SIZE[l*2]);
cache_size = MAX(cache_size, _CUM_LEN_CART[l*2]+2*_MAX_AFFINE_SIZE[l*2]);
cache_size += l1 * (mesh[0] + mesh[1] + mesh[2]);
cache_size += l1 * l1 * l1;
return cache_size + 1000000;
}
/*
* F_dm are a set of uncontracted cartesian density matrices
* Note rho is updated inplace.
*/
void NUMINT_rho_drv(void (*eval_rho)(), double *rho, double *F_dm,
int comp, int hermi, int *shls_slice, int *ao_loc,
double log_prec, int dimension, int nimgs, double *Ls,
double *a, double *b, int *offset, int *submesh, int *mesh,
int *atm, int natm, int *bas, int nbas, double *env,
int nenv)
{
int ish0 = shls_slice[0];
int ish1 = shls_slice[1];
int jsh0 = shls_slice[2];
int jsh1 = shls_slice[3];
int nish = ish1 - ish0;
int njsh = jsh1 - jsh0;
size_t naoi = ao_loc[ish1] - ao_loc[ish0];
size_t naoj = ao_loc[jsh1] - ao_loc[jsh0];
size_t nao2 = naoi * naoi;
int lmax = 0;
int ib;
for (ib = 0; ib < nbas; ib++) {
lmax = MAX(lmax, bas(ANG_OF, ib));
}
int cache_size = _rho_cache_size(lmax, comp, submesh);
size_t ngrids = ((size_t)submesh[0]) * submesh[1] * submesh[2];
if (dimension == 0) {
nimgs = 1;
}
double *rhobufs[MAX_THREADS];
#pragma omp parallel
{
size_t ncij = naoi * naoj;
size_t nijsh = nish * njsh;
size_t dims[] = {naoi, naoj};
size_t ijm;
int ish, jsh, ij, m, i0, j0;
int shls[2];
double *cache = malloc(sizeof(double) * cache_size);
double *env_loc = malloc(sizeof(double)*nenv);
NPdcopy(env_loc, env, nenv);
int ptrxyz;
int thread_id = omp_get_thread_num();
double *rho_priv, *pdm;
if (thread_id == 0) {
rho_priv = rho;
} else {
rho_priv = calloc(comp*ngrids, sizeof(double));
}
rhobufs[thread_id] = rho_priv;
if (hermi) {
// Note hermitian character of the density matrices can only be found by
// rearranging the repeated images:
// dmR - dmR[::-1].transpose(0,2,1) == 0
#pragma omp for schedule(static)
for (m = 0; m < nimgs; m++) {
pdm = F_dm + m * nao2;
for (j0 = 1; j0 < naoi; j0++) {
for (i0 = 0; i0 < j0; i0++) {
pdm[j0*naoi+i0] *= 2;
pdm[i0*naoi+j0] = 0;
}
}
}
}
#pragma omp for schedule(dynamic)
for (ijm = 0; ijm < nimgs*nijsh; ijm++) {
m = ijm / nijsh;
ij = ijm % nijsh;
ish = ij / njsh;
jsh = ij % njsh;
if (hermi != PLAIN && ish > jsh) {
continue;
}
ish += ish0;
jsh += jsh0;
shls[0] = ish;
shls[1] = jsh;
i0 = ao_loc[ish] - ao_loc[ish0];
j0 = ao_loc[jsh] - ao_loc[jsh0];
if (dimension != 0) {
ptrxyz = atm(PTR_COORD, bas(ATOM_OF,ish));
shift_bas(env_loc, env, Ls, ptrxyz, m);
}
_apply_rho(eval_rho, rho_priv, F_dm+m*ncij+j0*naoi+i0,
dims, comp, log_prec, dimension, a, b,
offset, submesh, mesh, shls,
atm, natm, bas, nbas, env_loc, cache);
}
NPomp_dsum_reduce_inplace(rhobufs, comp*ngrids);
free(cache);
free(env_loc);
if (thread_id != 0) {
free(rho_priv);
}
}
}
|
algorithm.h | #ifndef RCLUSTERP_ALGORITHM_H
#define RCLUSTERP_ALGORITHM_H
#include <limits>
#include <utility>
#include <algorithm>
#include <functional>
#include <stack>
#include <Rclusterpp/cluster.h>
#include <Rclusterpp/util.h>
namespace Rclusterpp {
template<class RandomIterator, class Distancer>
std::pair<RandomIterator, typename Distancer::result_type> nearest_neighbor(
const RandomIterator& first,
const RandomIterator& last,
Distancer distancer,
typename Distancer::result_type max_dist=std::numeric_limits<typename Distancer::result_type>::max()
) {
typedef typename Distancer::result_type Dist_t;
RandomIterator min_i = last;
Dist_t min_d = max_dist;
#ifdef _OPENMP
#pragma omp parallel shared(min_i, min_d, distancer)
#endif
{
RandomIterator min_i_l;
Dist_t min_d_l = min_d;
#ifdef _OPENMP
#pragma omp for nowait
#endif
for (ssize_t i=0; i<(last-first); i++) {
Dist_t dist = distancer(*(first+i), min_d_l);
if (dist < min_d_l) {
min_i_l = first + i;
min_d_l = dist;
}
}
#ifdef _OPENMP
#pragma omp critical
#endif
{
if (min_d_l < min_d) {
min_i = min_i_l;
min_d = min_d_l;
}
}
}
return std::make_pair(min_i, min_d);
}
template<class ClusteringMethod, class ClusterVector>
void cluster_via_rnn(ClusteringMethod method, ClusterVector& clusters) {
typedef ClusterVector clusters_type;
typedef typename clusters_type::cluster_type cluster_type;
typedef typename ClusteringMethod::distance_type distance_type;
// Result from nearest neighbor scan
typedef std::pair<typename clusters_type::iterator, distance_type> nearn_type;
#define nn_cluster(x) (x).first
#define distance_to_nn(x) (x).second
// Nearest neighbor chain
typedef std::pair<typename clusters_type::value_type, distance_type> entry_type;
std::stack<entry_type> chain;
#define cluster_at_tip(x) (x).top().first
#define distance_to_tip(x) (x).top().second
// Expand the size of clusters vector to the contain exactly the newly created clusters
size_t initial_clusters = clusters.size(), result_clusters = (initial_clusters * 2) - 1;
clusters.reserve(result_clusters);
// List of valid clusters (used in mer
Util::IndexList valid(initial_clusters);
typename clusters_type::iterator next_unchained = clusters.begin();
while (clusters.size() != result_clusters) {
if (chain.empty()) {
// Pick next "unchained" cluster as default
chain.push( entry_type(*next_unchained, std::numeric_limits<distance_type>::max()) );
++next_unchained;
} else {
// Find next nearest neighbor from remaining "unchained" clusters
nearn_type nn = nearest_neighbor(
next_unchained,
clusters.end(),
Util::cluster_bind(method.distancer, cluster_at_tip(chain)), // Bind tip into distance function for computing nearest neighbor
distance_to_tip(chain)
);
if (nn.first != clusters.end()) {
std::iter_swap(next_unchained, nn_cluster(nn));
chain.push( entry_type(*next_unchained, distance_to_nn(nn)) );
++next_unchained;
} else {
// Tip of chain is recursive nearest neighbor
cluster_type* r = cluster_at_tip(chain);
distance_type d = distance_to_tip(chain);
chain.pop();
cluster_type* l = cluster_at_tip(chain);
chain.pop();
// Remove "tip" and "next tip" from chain and merge into new cluster appended to "unchained" clusters
cluster_type* cn = ClusterVector::make_cluster(std::min(l->idx(), r->idx()), l, r, d);
valid.remove(std::max(r->idx(), l->idx()));
method.merger(*cn, *(cn->parent1()), *(cn->parent2()), valid);
clusters.push_back(cn);
}
}
}
// Cleanup cluster listing
// Re-order the clusters, with initial clusters in the beginning, ordered by id
// from -1 .. -initial_clusters, followed by the agglomerated clusters sorted by
// increasing disimilarity. Stable partition and stable sorting is required for
// the latter to ensure merge order is maintaining for clusters with identical
// dissimilarity.
// Note, sort requires strict weak ordering and will fail in a data dependent way
// if the comparison function does not satisfy that requirement
typename clusters_type::iterator part = std::stable_partition(clusters.begin(), clusters.end(), std::mem_fun(&cluster_type::initial));
std::sort(clusters.begin(), part, &compare_id<cluster_type>);
std::stable_sort(part, clusters.end(), std::ptr_fun(&compare_disimilarity<cluster_type>));
for (size_t i=initial_clusters; i<result_clusters; i++) {
clusters[i]->set_id(i - initial_clusters + 1); // Use R hclust 1-indexed convention for Id's
}
}
namespace {
typedef std::pair<size_t, size_t> Merge_t;
inline Merge_t make_merge(size_t from, size_t into) { return std::make_pair(from, into); }
inline size_t from(const Merge_t& m) { return m.first; }
inline size_t into(const Merge_t& m) { return m.second; }
template<class Distance>
struct MergeCMP {
const Distance& height;
MergeCMP(const Distance& height_) : height(height_) {}
bool operator()(const Merge_t& a, const Merge_t& b) const {
return height[from(a)] < height[from(b)];
}
};
} // end of anonymous namespace
template<class Distancer, class ClusterVector>
void cluster_via_slink(const Distancer& distancer, ClusterVector& clusters) {
typedef typename Distancer::result_type distance_type;
size_t initial_clusters = clusters.size(), result_clusters = (initial_clusters * 2) - 1;
clusters.reserve(result_clusters);
std::vector<size_t> P = std::vector<size_t>(initial_clusters);
std::vector<distance_type> L = std::vector<distance_type>(initial_clusters);
std::vector<distance_type> M = std::vector<distance_type>(initial_clusters);
for (size_t i=0; i<initial_clusters; i++) {
// Step 1: Initialize
P[i] = i;
L[i] = std::numeric_limits<distance_type>::max();
// Step 2: Build out pairwise distances from objects in pointer
// represenation to the new object
#ifdef _OPENMP
#pragma omp parallel for shared(i, M)
#endif
for (ssize_t j=0; j<(ssize_t)i; j++) {
M[j] = distancer(i, j);
}
// Step 3: Update M, P, L
for (size_t j=0; j<i; j++) {
distance_type l = L[j], m = M[j];
if (l >= m) {
M[P[j]] = std::min(M[P[j]], l);
L[j] = m;
P[j] = i;
} else {
M[P[j]] = std::min(M[P[j]], m);
}
}
// Step 4: Actualize the clusters
for (size_t j=0; j<i; j++) {
if (L[j] >= L[P[j]])
P[j] = i;
}
}
// Convert the pointer representation to dendogram
std::vector<Merge_t> merges = std::vector<Merge_t>(initial_clusters-1);
for (size_t i=0; i<(initial_clusters-1); i++) {
merges[i] = make_merge(i, P[i]); // from, into
}
std::sort(merges.begin(), merges.end(), MergeCMP<std::vector<distance_type> >(L));
for (size_t i=0; i<initial_clusters; i++) {
P[i] = i;
}
for (size_t i=0; i<(initial_clusters-1); i++) {
size_t f = from(merges[i]), t = into(merges[i]);
clusters.push_back(ClusterVector::make_cluster( 0, clusters[P[f]], clusters[P[t]], L[f] ));
P[t] = i + initial_clusters;
}
for (size_t i=initial_clusters; i<result_clusters; i++) {
clusters[i]->set_id(i - initial_clusters + 1); // Use R hclust 1-indexed convention for Id's
}
}
} // end of Rclustercpp namespace
#endif
|
zero_omp.c | /*
* File: zero_omp.c
* Author: Philip Mucci
* mucci@cs.utk.edu
* Mods: Nils Smeds
* smeds@pdc.kth.se
* Anders Nilsson
* anni@pdc.kth.se
*/
/* This file performs the following test: start, stop and timer
functionality for 2 slave OMP threads
- It attempts to use the following two counters. It may use less
depending on hardware counter resource limitations. These are counted
in the default counting domain and default granularity, depending on
the platform. Usually this is the user domain (PAPI_DOM_USER) and
thread context (PAPI_GRN_THR).
+ PAPI_FP_INS
+ PAPI_TOT_CYC
Each thread inside the Thread routine:
- Get cyc.
- Get us.
- Start counters
- Do flops
- Stop and read counters
- Get us.
- Get cyc.
Master serial thread:
- Get us.
- Get cyc.
- Run parallel for loop
- Get us.
- Get cyc.
*/
#include <stdio.h>
#include <stdlib.h>
#include "papi.h"
#include "papi_test.h"
#include "do_loops.h"
#ifdef _OPENMP
#include <omp.h>
#else
#error "This compiler does not understand OPENMP"
#endif
const PAPI_hw_info_t *hw_info = NULL;
void
Thread( int n )
{
int retval, num_tests = 1;
int EventSet1 = PAPI_NULL;
int PAPI_event, mask1;
int num_events1;
long long **values;
long long elapsed_us, elapsed_cyc;
char event_name[PAPI_MAX_STR_LEN];
if (!TESTS_QUIET) {
printf( "Thread %#x started\n", omp_get_thread_num( ) );
}
/* add PAPI_TOT_CYC and one of the events in
PAPI_FP_INS, PAPI_FP_OPS or PAPI_TOT_INS,
depending on the availability of the event
on the platform */
EventSet1 = add_two_events( &num_events1, &PAPI_event, &mask1 );
if (num_events1==0) {
if (!TESTS_QUIET) printf("No events added!\n");
test_fail(__FILE__,__LINE__,"No events",0);
}
retval = PAPI_event_code_to_name( PAPI_event, event_name );
if ( retval != PAPI_OK )
test_fail( __FILE__, __LINE__, "PAPI_event_code_to_name", retval );
values = allocate_test_space( num_tests, num_events1 );
elapsed_us = PAPI_get_real_usec( );
elapsed_cyc = PAPI_get_real_cyc( );
retval = PAPI_start( EventSet1 );
if ( retval != PAPI_OK )
test_fail( __FILE__, __LINE__, "PAPI_start", retval );
do_flops( n );
retval = PAPI_stop( EventSet1, values[0] );
if ( retval != PAPI_OK )
test_fail( __FILE__, __LINE__, "PAPI_stop", retval );
elapsed_us = PAPI_get_real_usec( ) - elapsed_us;
elapsed_cyc = PAPI_get_real_cyc( ) - elapsed_cyc;
remove_test_events( &EventSet1, mask1 );
if ( !TESTS_QUIET ) {
printf( "Thread %#x %-12s : \t%lld\n", omp_get_thread_num( ),
event_name, values[0][1] );
printf( "Thread %#x PAPI_TOT_CYC: \t%lld\n", omp_get_thread_num( ),
values[0][0] );
printf( "Thread %#x Real usec : \t%lld\n", omp_get_thread_num( ),
elapsed_us );
printf( "Thread %#x Real cycles : \t%lld\n", omp_get_thread_num( ),
elapsed_cyc );
}
/* It is illegal for the threads to exit in OpenMP */
/* test_pass(__FILE__,0,0); */
free_test_space( values, num_tests );
PAPI_unregister_thread( );
if (!TESTS_QUIET) {
printf( "Thread %#x finished\n", omp_get_thread_num( ) );
}
}
int
main( int argc, char **argv )
{
int retval;
long long elapsed_us, elapsed_cyc;
int quiet;
/* Set TESTS_QUIET variable */
quiet = tests_quiet( argc, argv );
retval = PAPI_library_init( PAPI_VER_CURRENT );
if ( retval != PAPI_VER_CURRENT ) {
test_fail( __FILE__, __LINE__, "PAPI_library_init", retval );
}
hw_info = PAPI_get_hardware_info( );
if ( hw_info == NULL ) {
test_fail( __FILE__, __LINE__, "PAPI_get_hardware_info", 2 );
}
if (PAPI_query_event(PAPI_TOT_INS)!=PAPI_OK) {
if (!quiet) printf("Can't find PAPI_TOT_INS\n");
test_skip(__FILE__,__LINE__,"Event missing",1);
}
if (PAPI_query_event(PAPI_TOT_CYC)!=PAPI_OK) {
if (!quiet) printf("Can't find PAPI_TOT_CYC\n");
test_skip(__FILE__,__LINE__,"Event missing",1);
}
elapsed_us = PAPI_get_real_usec( );
elapsed_cyc = PAPI_get_real_cyc( );
retval = PAPI_thread_init( ( unsigned long ( * )( void ) )
( omp_get_thread_num ) );
if ( retval != PAPI_OK ) {
if ( retval == PAPI_ECMP ) {
if (!quiet) printf("Trouble init threads\n");
test_skip( __FILE__, __LINE__, "PAPI_thread_init", retval );
}
else {
test_fail( __FILE__, __LINE__, "PAPI_thread_init", retval );
}
}
#pragma omp parallel
{
Thread( 1000000 * ( omp_get_thread_num( ) + 1 ) );
}
omp_set_num_threads( 1 );
Thread( 1000000 * ( omp_get_thread_num( ) + 1 ) );
omp_set_num_threads( omp_get_max_threads( ) );
#pragma omp parallel
{
Thread( 1000000 * ( omp_get_thread_num( ) + 1 ) );
}
elapsed_cyc = PAPI_get_real_cyc( ) - elapsed_cyc;
elapsed_us = PAPI_get_real_usec( ) - elapsed_us;
if ( !TESTS_QUIET ) {
printf( "Master real usec : \t%lld\n", elapsed_us );
printf( "Master real cycles : \t%lld\n", elapsed_cyc );
}
test_pass( __FILE__ );
return 0;
}
|
ac_surface_meta_address_test.c | /*
* Copyright © 2021 Advanced Micro Devices, Inc.
* All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sub license, 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 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
* NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS, AUTHORS
* AND/OR ITS SUPPLIERS 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.
*
* The above copyright notice and this permission notice (including the
* next paragraph) shall be included in all copies or substantial portions
* of the Software.
*/
/* Make the test not meaningless when asserts are disabled. */
#undef NDEBUG
#include <assert.h>
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
#include <amdgpu.h>
#include "drm-uapi/amdgpu_drm.h"
#include "drm-uapi/drm_fourcc.h"
#include "ac_surface.h"
#include "util/macros.h"
#include "util/u_atomic.h"
#include "util/u_math.h"
#include "util/u_vector.h"
#include "util/mesa-sha1.h"
#include "addrlib/inc/addrinterface.h"
#include "ac_surface_test_common.h"
/*
* The main goal of this test is to validate that our dcc/htile addressing
* functions match addrlib behavior.
*/
/* DCC address computation without mipmapping.
* CMASK address computation without mipmapping and without multisampling.
*/
static unsigned gfx9_meta_addr_from_coord(const struct radeon_info *info,
/* Shader key inputs: */
/* equation varies with resource_type, swizzle_mode,
* bpp, number of fragments, pipe_aligned, rb_aligned */
const struct gfx9_addr_meta_equation *eq,
unsigned meta_block_width, unsigned meta_block_height,
unsigned meta_block_depth,
/* Shader inputs: */
unsigned meta_pitch, unsigned meta_height,
unsigned x, unsigned y, unsigned z,
unsigned sample, unsigned pipe_xor,
/* Shader outputs (CMASK only): */
unsigned *bit_position)
{
/* The compiled shader shouldn't be complicated considering there are a lot of constants here. */
unsigned meta_block_width_log2 = util_logbase2(meta_block_width);
unsigned meta_block_height_log2 = util_logbase2(meta_block_height);
unsigned meta_block_depth_log2 = util_logbase2(meta_block_depth);
unsigned m_pipeInterleaveLog2 = 8 + G_0098F8_PIPE_INTERLEAVE_SIZE_GFX9(info->gb_addr_config);
unsigned numPipeBits = eq->numPipeBits;
unsigned pitchInBlock = meta_pitch >> meta_block_width_log2;
unsigned sliceSizeInBlock = (meta_height >> meta_block_height_log2) * pitchInBlock;
unsigned xb = x >> meta_block_width_log2;
unsigned yb = y >> meta_block_height_log2;
unsigned zb = z >> meta_block_depth_log2;
unsigned blockIndex = zb * sliceSizeInBlock + yb * pitchInBlock + xb;
unsigned coords[] = {x, y, z, sample, blockIndex};
unsigned address = 0;
unsigned num_bits = eq->num_bits;
assert(num_bits <= 32);
/* Compute the address up until the last bit that doesn't use the block index. */
for (unsigned b = 0; b < num_bits - 1; b++) {
unsigned xor = 0;
for (unsigned c = 0; c < 5; c++) {
if (eq->bit[b].coord[c].dim >= 5)
continue;
assert(eq->bit[b].coord[c].ord < 32);
unsigned ison = (coords[eq->bit[b].coord[c].dim] >>
eq->bit[b].coord[c].ord) & 0x1;
xor ^= ison;
}
address |= xor << b;
}
/* Fill the remaining bits with the block index. */
unsigned last = num_bits - 1;
address |= (blockIndex >> eq->bit[last].coord[0].ord) << last;
if (bit_position)
*bit_position = (address & 1) << 2;
unsigned pipeXor = pipe_xor & ((1 << numPipeBits) - 1);
return (address >> 1) ^ (pipeXor << m_pipeInterleaveLog2);
}
/* DCC/CMASK/HTILE address computation for GFX10. */
static unsigned gfx10_meta_addr_from_coord(const struct radeon_info *info,
/* Shader key inputs: */
const uint16_t *equation,
unsigned meta_block_width, unsigned meta_block_height,
unsigned blkSizeLog2,
/* Shader inputs: */
unsigned meta_pitch, unsigned meta_slice_size,
unsigned x, unsigned y, unsigned z,
unsigned pipe_xor,
/* Shader outputs: (CMASK only) */
unsigned *bit_position)
{
/* The compiled shader shouldn't be complicated considering there are a lot of constants here. */
unsigned meta_block_width_log2 = util_logbase2(meta_block_width);
unsigned meta_block_height_log2 = util_logbase2(meta_block_height);
unsigned coord[] = {x, y, z, 0};
unsigned address = 0;
for (unsigned i = 0; i < blkSizeLog2 + 1; i++) {
unsigned v = 0;
for (unsigned c = 0; c < 4; c++) {
if (equation[i*4+c] != 0) {
unsigned mask = equation[i*4+c];
unsigned bits = coord[c];
while (mask)
v ^= (bits >> u_bit_scan(&mask)) & 0x1;
}
}
address |= v << i;
}
unsigned blkMask = (1 << blkSizeLog2) - 1;
unsigned pipeMask = (1 << G_0098F8_NUM_PIPES(info->gb_addr_config)) - 1;
unsigned m_pipeInterleaveLog2 = 8 + G_0098F8_PIPE_INTERLEAVE_SIZE_GFX9(info->gb_addr_config);
unsigned xb = x >> meta_block_width_log2;
unsigned yb = y >> meta_block_height_log2;
unsigned pb = meta_pitch >> meta_block_width_log2;
unsigned blkIndex = (yb * pb) + xb;
unsigned pipeXor = ((pipe_xor & pipeMask) << m_pipeInterleaveLog2) & blkMask;
if (bit_position)
*bit_position = (address & 1) << 2;
return (meta_slice_size * z) +
(blkIndex * (1 << blkSizeLog2)) +
((address >> 1) ^ pipeXor);
}
/* DCC address computation without mipmapping and MSAA. */
static unsigned gfx10_dcc_addr_from_coord(const struct radeon_info *info,
/* Shader key inputs: */
/* equation varies with bpp and pipe_aligned */
const uint16_t *equation, unsigned bpp,
unsigned meta_block_width, unsigned meta_block_height,
/* Shader inputs: */
unsigned dcc_pitch, unsigned dcc_slice_size,
unsigned x, unsigned y, unsigned z,
unsigned pipe_xor)
{
unsigned bpp_log2 = util_logbase2(bpp >> 3);
unsigned meta_block_width_log2 = util_logbase2(meta_block_width);
unsigned meta_block_height_log2 = util_logbase2(meta_block_height);
unsigned blkSizeLog2 = meta_block_width_log2 + meta_block_height_log2 + bpp_log2 - 8;
return gfx10_meta_addr_from_coord(info, equation,
meta_block_width, meta_block_height,
blkSizeLog2,
dcc_pitch, dcc_slice_size,
x, y, z, pipe_xor, NULL);
}
static bool one_dcc_address_test(const char *name, const char *test, ADDR_HANDLE addrlib,
const struct radeon_info *info, unsigned width, unsigned height,
unsigned depth, unsigned samples, unsigned bpp,
unsigned swizzle_mode, bool pipe_aligned, bool rb_aligned,
unsigned mrt_index,
unsigned start_x, unsigned start_y, unsigned start_z,
unsigned start_sample)
{
ADDR2_COMPUTE_PIPEBANKXOR_INPUT xin = {sizeof(ADDR2_COMPUTE_PIPEBANKXOR_INPUT)};
ADDR2_COMPUTE_PIPEBANKXOR_OUTPUT xout = {sizeof(ADDR2_COMPUTE_PIPEBANKXOR_OUTPUT)};
ADDR2_COMPUTE_DCCINFO_INPUT din = {sizeof(din)};
ADDR2_COMPUTE_DCCINFO_OUTPUT dout = {sizeof(dout)};
ADDR2_COMPUTE_DCC_ADDRFROMCOORD_INPUT in = {sizeof(in)};
ADDR2_COMPUTE_DCC_ADDRFROMCOORD_OUTPUT out = {sizeof(out)};
ADDR2_META_MIP_INFO meta_mip_info[RADEON_SURF_MAX_LEVELS] = {0};
dout.pMipInfo = meta_mip_info;
/* Compute DCC info. */
in.dccKeyFlags.pipeAligned = din.dccKeyFlags.pipeAligned = pipe_aligned;
in.dccKeyFlags.rbAligned = din.dccKeyFlags.rbAligned = rb_aligned;
xin.resourceType = in.resourceType = din.resourceType = ADDR_RSRC_TEX_2D;
xin.swizzleMode = in.swizzleMode = din.swizzleMode = swizzle_mode;
in.bpp = din.bpp = bpp;
xin.numFrags = xin.numSamples = in.numFrags = din.numFrags = samples;
in.numMipLevels = din.numMipLevels = 1; /* addrlib can't do DccAddrFromCoord with mipmapping */
din.unalignedWidth = width;
din.unalignedHeight = height;
din.numSlices = depth;
din.firstMipIdInTail = 1;
int ret = Addr2ComputeDccInfo(addrlib, &din, &dout);
assert(ret == ADDR_OK);
/* Compute xor. */
static AddrFormat format[] = {
ADDR_FMT_8,
ADDR_FMT_16,
ADDR_FMT_32,
ADDR_FMT_32_32,
ADDR_FMT_32_32_32_32,
};
xin.flags.color = 1;
xin.flags.texture = 1;
xin.flags.opt4space = 1;
xin.flags.metaRbUnaligned = !rb_aligned;
xin.flags.metaPipeUnaligned = !pipe_aligned;
xin.format = format[util_logbase2(bpp / 8)];
xin.surfIndex = mrt_index;
ret = Addr2ComputePipeBankXor(addrlib, &xin, &xout);
assert(ret == ADDR_OK);
/* Compute addresses */
in.compressBlkWidth = dout.compressBlkWidth;
in.compressBlkHeight = dout.compressBlkHeight;
in.compressBlkDepth = dout.compressBlkDepth;
in.metaBlkWidth = dout.metaBlkWidth;
in.metaBlkHeight = dout.metaBlkHeight;
in.metaBlkDepth = dout.metaBlkDepth;
in.dccRamSliceSize = dout.dccRamSliceSize;
in.mipId = 0;
in.pitch = dout.pitch;
in.height = dout.height;
in.pipeXor = xout.pipeBankXor;
/* Validate that the packed gfx9_meta_equation structure can fit all fields. */
const struct gfx9_meta_equation eq;
if (info->chip_class == GFX9) {
/* The bit array is smaller in gfx9_meta_equation than in addrlib. */
assert(dout.equation.gfx9.num_bits <= ARRAY_SIZE(eq.u.gfx9.bit));
} else {
/* gfx9_meta_equation doesn't store the first 4 and the last 8 elements. They must be 0. */
for (unsigned i = 0; i < 4; i++)
assert(dout.equation.gfx10_bits[i] == 0);
for (unsigned i = ARRAY_SIZE(eq.u.gfx10_bits) + 4; i < 68; i++)
assert(dout.equation.gfx10_bits[i] == 0);
}
for (in.x = start_x; in.x < in.pitch; in.x += dout.compressBlkWidth) {
for (in.y = start_y; in.y < in.height; in.y += dout.compressBlkHeight) {
for (in.slice = start_z; in.slice < depth; in.slice += dout.compressBlkDepth) {
for (in.sample = start_sample; in.sample < samples; in.sample++) {
int r = Addr2ComputeDccAddrFromCoord(addrlib, &in, &out);
if (r != ADDR_OK) {
printf("%s addrlib error: %s\n", name, test);
abort();
}
unsigned addr;
if (info->chip_class == GFX9) {
addr = gfx9_meta_addr_from_coord(info, &dout.equation.gfx9, dout.metaBlkWidth, dout.metaBlkHeight,
dout.metaBlkDepth, dout.pitch, dout.height,
in.x, in.y, in.slice, in.sample, in.pipeXor, NULL);
if (in.sample == 1) {
/* Sample 0 should be one byte before sample 1. The DCC MSAA clear relies on it. */
assert(addr - 1 ==
gfx9_meta_addr_from_coord(info, &dout.equation.gfx9, dout.metaBlkWidth, dout.metaBlkHeight,
dout.metaBlkDepth, dout.pitch, dout.height,
in.x, in.y, in.slice, 0, in.pipeXor, NULL));
}
} else {
addr = gfx10_dcc_addr_from_coord(info, dout.equation.gfx10_bits,
in.bpp, dout.metaBlkWidth, dout.metaBlkHeight,
dout.pitch, dout.dccRamSliceSize,
in.x, in.y, in.slice, in.pipeXor);
}
if (out.addr != addr) {
printf("%s fail (%s) at %ux%ux%u@%u: expected = %llu, got = %u\n",
name, test, in.x, in.y, in.slice, in.sample, out.addr, addr);
return false;
}
}
}
}
}
return true;
}
static void run_dcc_address_test(const char *name, const struct radeon_info *info, bool full)
{
unsigned total = 0;
unsigned fails = 0;
unsigned swizzle_mode = info->chip_class == GFX9 ? ADDR_SW_64KB_S_X : ADDR_SW_64KB_R_X;
unsigned last_size, max_samples, min_bpp, max_bpp;
if (full) {
last_size = 6*6 - 1;
max_samples = 8;
min_bpp = 8;
max_bpp = 128;
} else {
/* The test coverage is reduced for Gitlab CI because it timeouts. */
last_size = 0;
max_samples = 2;
min_bpp = 32;
max_bpp = 64;
}
#ifdef HAVE_OPENMP
#pragma omp parallel for
#endif
for (unsigned size = 0; size <= last_size; size++) {
unsigned width = 8 + 379 * (size % 6);
unsigned height = 8 + 379 * ((size / 6) % 6);
struct ac_addrlib *ac_addrlib = ac_addrlib_create(info, NULL);
ADDR_HANDLE addrlib = ac_addrlib_get_handle(ac_addrlib);
unsigned local_fails = 0;
unsigned local_total = 0;
for (unsigned bpp = min_bpp; bpp <= max_bpp; bpp *= 2) {
/* addrlib can do DccAddrFromCoord with MSAA images only on gfx9 */
for (unsigned samples = 1; samples <= (info->chip_class == GFX9 ? max_samples : 1); samples *= 2) {
for (int rb_aligned = true; rb_aligned >= (samples > 1 ? true : false); rb_aligned--) {
for (int pipe_aligned = true; pipe_aligned >= (samples > 1 ? true : false); pipe_aligned--) {
for (unsigned mrt_index = 0; mrt_index < 2; mrt_index++) {
unsigned depth = 2;
char test[256];
snprintf(test, sizeof(test), "%ux%ux%u %ubpp %u samples rb:%u pipe:%u",
width, height, depth, bpp, samples, rb_aligned, pipe_aligned);
if (one_dcc_address_test(name, test, addrlib, info, width, height, depth, samples,
bpp, swizzle_mode, pipe_aligned, rb_aligned, mrt_index,
0, 0, 0, 0)) {
} else {
local_fails++;
}
local_total++;
}
}
}
}
}
ac_addrlib_destroy(ac_addrlib);
p_atomic_add(&fails, local_fails);
p_atomic_add(&total, local_total);
}
printf("%16s total: %u, fail: %u\n", name, total, fails);
}
/* HTILE address computation without mipmapping. */
static unsigned gfx10_htile_addr_from_coord(const struct radeon_info *info,
const uint16_t *equation,
unsigned meta_block_width,
unsigned meta_block_height,
unsigned htile_pitch, unsigned htile_slice_size,
unsigned x, unsigned y, unsigned z,
unsigned pipe_xor)
{
unsigned meta_block_width_log2 = util_logbase2(meta_block_width);
unsigned meta_block_height_log2 = util_logbase2(meta_block_height);
unsigned blkSizeLog2 = meta_block_width_log2 + meta_block_height_log2 - 4;
return gfx10_meta_addr_from_coord(info, equation,
meta_block_width, meta_block_height,
blkSizeLog2,
htile_pitch, htile_slice_size,
x, y, z, pipe_xor, NULL);
}
static bool one_htile_address_test(const char *name, const char *test, ADDR_HANDLE addrlib,
const struct radeon_info *info,
unsigned width, unsigned height, unsigned depth,
unsigned bpp, unsigned swizzle_mode,
unsigned start_x, unsigned start_y, unsigned start_z)
{
ADDR2_COMPUTE_PIPEBANKXOR_INPUT xin = {0};
ADDR2_COMPUTE_PIPEBANKXOR_OUTPUT xout = {0};
ADDR2_COMPUTE_HTILE_INFO_INPUT hin = {0};
ADDR2_COMPUTE_HTILE_INFO_OUTPUT hout = {0};
ADDR2_COMPUTE_HTILE_ADDRFROMCOORD_INPUT in = {0};
ADDR2_COMPUTE_HTILE_ADDRFROMCOORD_OUTPUT out = {0};
ADDR2_META_MIP_INFO meta_mip_info[RADEON_SURF_MAX_LEVELS] = {0};
hout.pMipInfo = meta_mip_info;
/* Compute HTILE info. */
hin.hTileFlags.pipeAligned = 1;
hin.hTileFlags.rbAligned = 1;
hin.depthFlags.depth = 1;
hin.depthFlags.texture = 1;
hin.depthFlags.opt4space = 1;
hin.swizzleMode = in.swizzleMode = xin.swizzleMode = swizzle_mode;
hin.unalignedWidth = in.unalignedWidth = width;
hin.unalignedHeight = in.unalignedHeight = height;
hin.numSlices = in.numSlices = depth;
hin.numMipLevels = in.numMipLevels = 1; /* addrlib can't do HtileAddrFromCoord with mipmapping. */
hin.firstMipIdInTail = 1;
int ret = Addr2ComputeHtileInfo(addrlib, &hin, &hout);
assert(ret == ADDR_OK);
/* Compute xor. */
static AddrFormat format[] = {
ADDR_FMT_8, /* unused */
ADDR_FMT_16,
ADDR_FMT_32,
};
xin.flags = hin.depthFlags;
xin.resourceType = ADDR_RSRC_TEX_2D;
xin.format = format[util_logbase2(bpp / 8)];
xin.numFrags = xin.numSamples = in.numSamples = 1;
ret = Addr2ComputePipeBankXor(addrlib, &xin, &xout);
assert(ret == ADDR_OK);
in.hTileFlags = hin.hTileFlags;
in.depthflags = xin.flags;
in.bpp = bpp;
in.pipeXor = xout.pipeBankXor;
for (in.x = start_x; in.x < width; in.x++) {
for (in.y = start_y; in.y < height; in.y++) {
for (in.slice = start_z; in.slice < depth; in.slice++) {
int r = Addr2ComputeHtileAddrFromCoord(addrlib, &in, &out);
if (r != ADDR_OK) {
printf("%s addrlib error: %s\n", name, test);
abort();
}
unsigned addr =
gfx10_htile_addr_from_coord(info, hout.equation.gfx10_bits,
hout.metaBlkWidth, hout.metaBlkHeight,
hout.pitch, hout.sliceSize,
in.x, in.y, in.slice, in.pipeXor);
if (out.addr != addr) {
printf("%s fail (%s) at %ux%ux%u: expected = %llu, got = %u\n",
name, test, in.x, in.y, in.slice, out.addr, addr);
return false;
}
}
}
}
return true;
}
static void run_htile_address_test(const char *name, const struct radeon_info *info, bool full)
{
unsigned total = 0;
unsigned fails = 0;
unsigned first_size = 0, last_size = 6*6 - 1, max_bpp = 32;
/* The test coverage is reduced for Gitlab CI because it timeouts. */
if (!full) {
first_size = last_size = 0;
}
#ifdef HAVE_OPENMP
#pragma omp parallel for
#endif
for (unsigned size = first_size; size <= last_size; size++) {
unsigned width = 8 + 379 * (size % 6);
unsigned height = 8 + 379 * (size / 6);
struct ac_addrlib *ac_addrlib = ac_addrlib_create(info, NULL);
ADDR_HANDLE addrlib = ac_addrlib_get_handle(ac_addrlib);
for (unsigned depth = 1; depth <= 2; depth *= 2) {
for (unsigned bpp = 16; bpp <= max_bpp; bpp *= 2) {
if (one_htile_address_test(name, name, addrlib, info, width, height, depth,
bpp, ADDR_SW_64KB_Z_X, 0, 0, 0)) {
} else {
p_atomic_inc(&fails);
}
p_atomic_inc(&total);
}
}
ac_addrlib_destroy(ac_addrlib);
}
printf("%16s total: %u, fail: %u\n", name, total, fails);
}
/* CMASK address computation without mipmapping and MSAA. */
static unsigned gfx10_cmask_addr_from_coord(const struct radeon_info *info,
/* Shader key inputs: */
/* equation varies with bpp and pipe_aligned */
const uint16_t *equation, unsigned bpp,
unsigned meta_block_width, unsigned meta_block_height,
/* Shader inputs: */
unsigned cmask_pitch, unsigned cmask_slice_size,
unsigned x, unsigned y, unsigned z,
unsigned pipe_xor,
/* Shader outputs: */
unsigned *bit_position)
{
unsigned meta_block_width_log2 = util_logbase2(meta_block_width);
unsigned meta_block_height_log2 = util_logbase2(meta_block_height);
unsigned blkSizeLog2 = meta_block_width_log2 + meta_block_height_log2 - 7;
return gfx10_meta_addr_from_coord(info, equation,
meta_block_width, meta_block_height,
blkSizeLog2,
cmask_pitch, cmask_slice_size,
x, y, z, pipe_xor, bit_position);
}
static bool one_cmask_address_test(const char *name, const char *test, ADDR_HANDLE addrlib,
const struct radeon_info *info,
unsigned width, unsigned height, unsigned depth,
unsigned bpp, unsigned swizzle_mode,
bool pipe_aligned, bool rb_aligned, unsigned mrt_index,
unsigned start_x, unsigned start_y, unsigned start_z)
{
ADDR2_COMPUTE_PIPEBANKXOR_INPUT xin = {sizeof(xin)};
ADDR2_COMPUTE_PIPEBANKXOR_OUTPUT xout = {sizeof(xout)};
ADDR2_COMPUTE_CMASK_INFO_INPUT cin = {sizeof(cin)};
ADDR2_COMPUTE_CMASK_INFO_OUTPUT cout = {sizeof(cout)};
ADDR2_COMPUTE_CMASK_ADDRFROMCOORD_INPUT in = {sizeof(in)};
ADDR2_COMPUTE_CMASK_ADDRFROMCOORD_OUTPUT out = {sizeof(out)};
/* Compute CMASK info. */
cin.resourceType = xin.resourceType = in.resourceType = ADDR_RSRC_TEX_2D;
cin.swizzleMode = xin.swizzleMode = in.swizzleMode = swizzle_mode;
cin.unalignedWidth = in.unalignedWidth = width;
cin.unalignedHeight = in.unalignedHeight = height;
cin.numSlices = in.numSlices = depth;
cin.numMipLevels = 1;
cin.firstMipIdInTail = 1;
cin.cMaskFlags.pipeAligned = pipe_aligned;
cin.cMaskFlags.rbAligned = rb_aligned;
cin.cMaskFlags.linear = false;
cin.colorFlags.color = 1;
cin.colorFlags.texture = 1;
cin.colorFlags.opt4space = 1;
cin.colorFlags.metaRbUnaligned = !rb_aligned;
cin.colorFlags.metaPipeUnaligned = !pipe_aligned;
int ret = Addr2ComputeCmaskInfo(addrlib, &cin, &cout);
assert(ret == ADDR_OK);
/* Compute xor. */
static AddrFormat format[] = {
ADDR_FMT_8,
ADDR_FMT_16,
ADDR_FMT_32,
ADDR_FMT_32_32,
ADDR_FMT_32_32_32_32,
};
xin.flags = cin.colorFlags;
xin.format = format[util_logbase2(bpp / 8)];
xin.surfIndex = mrt_index;
xin.numSamples = in.numSamples = xin.numFrags = in.numFrags = 1;
ret = Addr2ComputePipeBankXor(addrlib, &xin, &xout);
assert(ret == ADDR_OK);
in.cMaskFlags = cin.cMaskFlags;
in.colorFlags = cin.colorFlags;
in.pipeXor = xout.pipeBankXor;
for (in.x = start_x; in.x < width; in.x++) {
for (in.y = start_y; in.y < height; in.y++) {
for (in.slice = start_z; in.slice < depth; in.slice++) {
int r = Addr2ComputeCmaskAddrFromCoord(addrlib, &in, &out);
if (r != ADDR_OK) {
printf("%s addrlib error: %s\n", name, test);
abort();
}
unsigned addr, bit_position;
if (info->chip_class == GFX9) {
addr = gfx9_meta_addr_from_coord(info, &cout.equation.gfx9,
cout.metaBlkWidth, cout.metaBlkHeight, 1,
cout.pitch, cout.height,
in.x, in.y, in.slice, 0, in.pipeXor,
&bit_position);
} else {
addr = gfx10_cmask_addr_from_coord(info, cout.equation.gfx10_bits,
bpp, cout.metaBlkWidth,
cout.metaBlkHeight,
cout.pitch, cout.sliceSize,
in.x, in.y, in.slice,
in.pipeXor,
&bit_position);
}
if (out.addr != addr || out.bitPosition != bit_position) {
printf("%s fail (%s) at %ux%ux%u: expected (addr) = %llu, got = %u, "
"expected (bit_position) = %u, got = %u\n",
name, test, in.x, in.y, in.slice, out.addr, addr,
out.bitPosition, bit_position);
return false;
}
}
}
}
return true;
}
static void run_cmask_address_test(const char *name, const struct radeon_info *info, bool full)
{
unsigned total = 0;
unsigned fails = 0;
unsigned swizzle_mode = info->chip_class == GFX9 ? ADDR_SW_64KB_S_X : ADDR_SW_64KB_Z_X;
unsigned first_size = 0, last_size = 6*6 - 1, max_bpp = 32;
/* The test coverage is reduced for Gitlab CI because it timeouts. */
if (!full) {
first_size = last_size = 0;
}
#ifdef HAVE_OPENMP
#pragma omp parallel for
#endif
for (unsigned size = first_size; size <= last_size; size++) {
unsigned width = 8 + 379 * (size % 6);
unsigned height = 8 + 379 * (size / 6);
struct ac_addrlib *ac_addrlib = ac_addrlib_create(info, NULL);
ADDR_HANDLE addrlib = ac_addrlib_get_handle(ac_addrlib);
for (unsigned depth = 1; depth <= 2; depth *= 2) {
for (unsigned bpp = 16; bpp <= max_bpp; bpp *= 2) {
for (int rb_aligned = true; rb_aligned >= true; rb_aligned--) {
for (int pipe_aligned = true; pipe_aligned >= true; pipe_aligned--) {
if (one_cmask_address_test(name, name, addrlib, info,
width, height, depth, bpp,
swizzle_mode,
pipe_aligned, rb_aligned,
0, 0, 0, 0)) {
} else {
p_atomic_inc(&fails);
}
p_atomic_inc(&total);
}
}
}
}
ac_addrlib_destroy(ac_addrlib);
}
printf("%16s total: %u, fail: %u\n", name, total, fails);
}
int main(int argc, char **argv)
{
bool full = false;
if (argc == 2 && !strcmp(argv[1], "--full"))
full = true;
else
puts("Specify --full to run the full test.");
puts("DCC:");
for (unsigned i = 0; i < ARRAY_SIZE(testcases); ++i) {
struct radeon_info info = get_radeon_info(&testcases[i]);
run_dcc_address_test(testcases[i].name, &info, full);
}
puts("HTILE:");
for (unsigned i = 0; i < ARRAY_SIZE(testcases); ++i) {
struct radeon_info info = get_radeon_info(&testcases[i]);
/* Only GFX10+ is currently supported. */
if (info.chip_class < GFX10)
continue;
run_htile_address_test(testcases[i].name, &info, full);
}
puts("CMASK:");
for (unsigned i = 0; i < ARRAY_SIZE(testcases); ++i) {
struct radeon_info info = get_radeon_info(&testcases[i]);
run_cmask_address_test(testcases[i].name, &info, full);
}
return 0;
}
|
GB_unop__identity_fc64_uint64.c | //------------------------------------------------------------------------------
// GB_unop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated/ folder, do not edit it (auto-generated).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_atomics.h"
#include "GB_unop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB (_unop_apply__identity_fc64_uint64)
// op(A') function: GB (_unop_tran__identity_fc64_uint64)
// C type: GxB_FC64_t
// A type: uint64_t
// cast: GxB_FC64_t cij = GxB_CMPLX ((double) (aij), 0)
// unaryop: cij = aij
#define GB_ATYPE \
uint64_t
#define GB_CTYPE \
GxB_FC64_t
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
uint64_t aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = x ;
// casting
#define GB_CAST(z, aij) \
GxB_FC64_t z = GxB_CMPLX ((double) (aij), 0) ;
// cij = op (aij)
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
uint64_t aij = Ax [pA] ; \
/* Cx [pC] = op (cast (aij)) */ \
GxB_FC64_t z = GxB_CMPLX ((double) (aij), 0) ; \
Cx [pC] = z ; \
}
// true if operator is the identity op with no typecasting
#define GB_OP_IS_IDENTITY_WITH_NO_TYPECAST \
0
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_IDENTITY || GxB_NO_FC64 || GxB_NO_UINT64)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_apply__identity_fc64_uint64)
(
GxB_FC64_t *Cx, // Cx and Ax may be aliased
const uint64_t *Ax,
const int8_t *restrict Ab, // A->b if A is bitmap
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
// TODO: if OP is ONE and uniform-valued matrices are exploited, then
// do this in O(1) time
if (Ab == NULL)
{
#if ( GB_OP_IS_IDENTITY_WITH_NO_TYPECAST )
GB_memcpy (Cx, Ax, anz * sizeof (uint64_t), nthreads) ;
#else
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
uint64_t aij = Ax [p] ;
GxB_FC64_t z = GxB_CMPLX ((double) (aij), 0) ;
Cx [p] = z ;
}
#endif
}
else
{
// bitmap case, no transpose; A->b already memcpy'd into C->b
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!Ab [p]) continue ;
uint64_t aij = Ax [p] ;
GxB_FC64_t z = GxB_CMPLX ((double) (aij), 0) ;
Cx [p] = z ;
}
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_tran__identity_fc64_uint64)
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
GB_binop__rdiv_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 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__rdiv_fp64)
// A.*B function (eWiseMult): GB (_AemultB_08__rdiv_fp64)
// A.*B function (eWiseMult): GB (_AemultB_02__rdiv_fp64)
// A.*B function (eWiseMult): GB (_AemultB_04__rdiv_fp64)
// A.*B function (eWiseMult): GB (_AemultB_bitmap__rdiv_fp64)
// A*D function (colscale): GB (_AxD__rdiv_fp64)
// D*A function (rowscale): GB (_DxB__rdiv_fp64)
// C+=B function (dense accum): GB (_Cdense_accumB__rdiv_fp64)
// C+=b function (dense accum): GB (_Cdense_accumb__rdiv_fp64)
// C+=A+B function (dense ewise3): GB (_Cdense_ewise3_accum__rdiv_fp64)
// C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__rdiv_fp64)
// C=scalar+B GB (_bind1st__rdiv_fp64)
// C=scalar+B' GB (_bind1st_tran__rdiv_fp64)
// C=A+scalar GB (_bind2nd__rdiv_fp64)
// C=A'+scalar GB (_bind2nd_tran__rdiv_fp64)
// C type: double
// A type: double
// A pattern? 0
// B type: double
// B pattern? 0
// BinaryOp: cij = (bij / aij)
#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 = (y / x) ;
// 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_RDIV || GxB_NO_FP64 || GxB_NO_RDIV_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__rdiv_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
//------------------------------------------------------------------------------
void GB (_Cdense_ewise3_noaccum__rdiv_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__rdiv_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__rdiv_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__rdiv_fp64)
(
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
}
//------------------------------------------------------------------------------
// C = D*B, row scale with diagonal D matrix
//------------------------------------------------------------------------------
GrB_Info GB (_DxB__rdiv_fp64)
(
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
}
//------------------------------------------------------------------------------
// eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B
//------------------------------------------------------------------------------
GrB_Info GB (_AaddB__rdiv_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__rdiv_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__rdiv_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__rdiv_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__rdiv_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__rdiv_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] = (bij / x) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd
//------------------------------------------------------------------------------
GrB_Info GB (_bind2nd__rdiv_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] = (y / aij) ;
}
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] = (aij / x) ; \
}
GrB_Info GB (_bind1st_tran__rdiv_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] = (y / aij) ; \
}
GrB_Info GB (_bind2nd_tran__rdiv_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
|
convolution_1x1_packnto1.h | // Tencent is pleased to support the open source community by making ncnn available.
//
// Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// https://opensource.org/licenses/BSD-3-Clause
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
static void conv1x1s1_sgemm_packnto1_rvv(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel, const Mat& _bias, const Option& opt)
{
int w = bottom_blob.w;
int h = bottom_blob.h;
const int size = w * h;
Mat bottom_im2col = bottom_blob;
bottom_im2col.w = size;
bottom_im2col.h = 1;
im2col_sgemm_packnto1_rvv(bottom_im2col, top_blob, kernel, _bias, opt);
}
static void conv1x1s2_sgemm_packnto1_rvv(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel, const Mat& _bias, const Option& opt)
{
const int packn = csrr_vlenb() / 4;
const word_type vl = vsetvl_e32m1(packn);
int w = bottom_blob.w;
int channels = bottom_blob.c;
size_t elemsize = bottom_blob.elemsize;
int elempack = bottom_blob.elempack;
int outw = top_blob.w;
int outh = top_blob.h;
const int tailstep = (w - 2 * outw + w) * packn;
Mat bottom_blob_shrinked;
bottom_blob_shrinked.create(outw, outh, channels, elemsize, elempack, opt.workspace_allocator);
#pragma omp parallel for num_threads(opt.num_threads)
for (int p = 0; p < channels; p++)
{
const float* r0 = bottom_blob.channel(p);
float* outptr = bottom_blob_shrinked.channel(p);
for (int i = 0; i < outh; i++)
{
for (int j = 0; j < outw; j++)
{
vfloat32m1_t _val = vle32_v_f32m1(r0, vl);
vse32_v_f32m1(outptr, _val, vl);
r0 += packn * 2;
outptr += packn;
}
r0 += tailstep;
}
}
conv1x1s1_sgemm_packnto1_rvv(bottom_blob_shrinked, top_blob, kernel, _bias, opt);
}
|
parallel_extrapolation_utilities.h | //
// Project Name: Kratos
// Last Modified by: $Author: pooyan $
// Date: $Date: 2006-11-27 16:07:33 $
// Revision: $Revision: 1.1.1.1 $
//
//
#if !defined(KRATOS_PARALLEL_EXTRAPOLATION_UTILITIES_H_INCLUDED )
#define KRATOS_PARALLEL_EXTRAPOLATION_UTILITIES_H_INCLUDED
// System includes
#include <string>
#include <iostream>
// External includes
// Project includes
#include "includes/define.h"
#include "utilities/geometry_utilities.h"
#include "includes/deprecated_variables.h"
namespace Kratos
{
///@name Kratos Globals
///@{
///@}
///@name Type Definitions
///@{
///@}
///@name Enum's
///@{
///@}
///@name Functions
///@{
///@}
///@name Kratos Classes
///@{
/// Short class definition.
/** Detail class definition.
*/
template< unsigned int TDim>
class ParallelExtrapolationUtilities
{
public:
///@name Type Definitions
///@{
/// Pointer definition of ParallelExtrapolationUtilities
KRATOS_CLASS_POINTER_DEFINITION(ParallelExtrapolationUtilities);
///@}
///@name Life Cycle
///@{
/// Default constructor.
ParallelExtrapolationUtilities()
{
};
/// Destructor.
virtual ~ParallelExtrapolationUtilities()
{
};
///Function to extrapolate the velocity from the interior of the level set domain.
///the extrapolation velocity is taken from the first layer of nodes INSIDE the level set domain
///@param rmodel_part is the ModelPart on which we will operate
///@param rDistanceVar is the Variable that we will use in calculating the distance
///@param rVelocityVar is the Variable being extrapolated
///@param rAreaVar is the Variable that we will use for L2 projections
///@param max_levels is the number of maximum "layers" of element that will be used in the calculation of the distances
void ExtrapolateVelocity(ModelPart& rmodel_part,
const Variable<double>& rDistanceVar,
const Variable< array_1d<double, 3 > >& rVelocityVar,
const Variable<double>& rAreaVar,
const unsigned int max_levels)
{
KRATOS_TRY
bool is_distributed = false;
if (rmodel_part.GetCommunicator().TotalProcesses() > 1)
is_distributed = true;
//check that variables needed are in the model part
if (!(rmodel_part.NodesBegin()->SolutionStepsDataHas(rDistanceVar)))
KRATOS_THROW_ERROR(std::logic_error, "distance Variable is not in the model part", "")
if (!(rmodel_part.NodesBegin()->SolutionStepsDataHas(rVelocityVar)))
KRATOS_THROW_ERROR(std::logic_error, "velocity Variable is not in the model part", "")
if (!(rmodel_part.NodesBegin()->SolutionStepsDataHas(rAreaVar)))
KRATOS_THROW_ERROR(std::logic_error, "Area Variable is not in the model part", "")
if (is_distributed == true)
if (!(rmodel_part.NodesBegin()->SolutionStepsDataHas(PARTITION_INDEX)))
KRATOS_THROW_ERROR(std::logic_error, "PARTITION_INDEX Variable is not in the model part", "")
//set as active the internal nodes
int node_size = rmodel_part.Nodes().size();
#pragma omp parallel for
for (int i = 0; i < node_size; i++)
{
ModelPart::NodesContainerType::iterator it = rmodel_part.NodesBegin() + i;
it->FastGetSolutionStepValue(rAreaVar) = 0.0;
const double& dist = it->FastGetSolutionStepValue(rDistanceVar);
if (dist < 0.0)
it->SetValue(IS_VISITED, 1.0);
else
it->SetValue(IS_VISITED, 0.0);
}
//now extrapolate the velocity var from all of the nodes that have at least one internal node_size
array_1d<double, TDim + 1 > visited;
array_1d<double, TDim + 1 > N;
array_1d<double, TDim> avg;
double lumping_factor = 1.0 / double(TDim + 1);
boost::numeric::ublas::bounded_matrix <double, TDim + 1, TDim> DN_DX;
int elem_size = rmodel_part.Elements().size();
for (unsigned int level = 0; level < max_levels; level++)
{
#pragma omp parallel for private(DN_DX,N,visited,avg) firstprivate(lumping_factor,elem_size)
for (int i = 0; i < elem_size; i++)
{
PointerVector< Element>::iterator it = rmodel_part.ElementsBegin() + i;
Geometry<Node < 3 > >&geom = it->GetGeometry();
for (unsigned int k = 0; k < TDim + 1; k++)
visited[k] = geom[k].GetValue(IS_VISITED);
if (IsActive(visited))
{
double Volume;
GeometryUtils::CalculateGeometryData(geom, DN_DX, N, Volume);
//calculated average value of "velocity"
noalias(avg) = ZeroVector(3);
double counter = 0.0;
for (unsigned int k = 0; k < TDim + 1; k++)
{
if (visited[k] > 0.0)
{
noalias(avg) += geom[k].FastGetSolutionStepValue(rVelocityVar);
counter += 1.0;
}
}
avg /= counter;
for (unsigned int k = 0; k < TDim + 1; k++)
{
if (visited[k] == 0.0)
{
geom[k].SetLock();
geom[k].FastGetSolutionStepValue(rVelocityVar) += avg * Volume*lumping_factor;
geom[k].FastGetSolutionStepValue(rAreaVar) += Volume*lumping_factor;
geom[k].UnSetLock();
}
}
}
}
//mpi sync variables
if (is_distributed == true)
{
int my_rank = rmodel_part.GetCommunicator().MyPID();
#pragma omp parallel for firstprivate(node_size,my_rank)
for (int i = 0; i < node_size; i++)
{
ModelPart::NodesContainerType::iterator it = rmodel_part.NodesBegin() + i;
if (it->GetValue(IS_VISITED) == 1.0 && my_rank != it->FastGetSolutionStepValue(PARTITION_INDEX))
{
it->FastGetSolutionStepValue(rAreaVar) = 0.0;
noalias(it->FastGetSolutionStepValue(rVelocityVar)) = ZeroVector(3);
}
}
rmodel_part.GetCommunicator().AssembleCurrentData(rAreaVar);
rmodel_part.GetCommunicator().AssembleCurrentData(rVelocityVar);
}
#pragma omp parallel for firstprivate(node_size)
for (int i = 0; i < node_size; i++)
{
ModelPart::NodesContainerType::iterator it = rmodel_part.NodesBegin() + i;
const double& area = it->FastGetSolutionStepValue(rAreaVar);
if (area > 1e-20 && it->GetValue(IS_VISITED) == 0.0) //this implies that node was computed
{
it->FastGetSolutionStepValue(rVelocityVar) /= area;
it->SetValue(IS_VISITED, 1.0); //node is marked as already visitedz
}
}
}
KRATOS_CATCH("")
}
///Function to extrapolate the temperature from the interior of the level set domain.
///the extrapolation temperature is taken from the first layer of nodes INSIDE the level set domain
///@param rmodel_part is the ModelPart on which we will operate
///@param rDistanceVar is the Variable that we will use in calculating the distance
///@param rVelocityVar is the Variable being extrapolated
///@param rAreaVar is the Variable that we will use for L2 projections
///@param max_levels is the number of maximum "layers" of element that will be used in the calculation of the distances
static void ExtrapolateTemperature(ModelPart& rmodel_part,
const Variable<double>& rDistanceVar,
const Variable<double>& rTemperatureVar,
const Variable<double>& rAreaVar,
const unsigned int max_levels)
{
KRATOS_TRY
bool is_distributed = false;
if (rmodel_part.GetCommunicator().TotalProcesses() > 1)
is_distributed = true;
//check that variables needed are in the model part
if (!(rmodel_part.NodesBegin()->SolutionStepsDataHas(rDistanceVar)))
KRATOS_THROW_ERROR(std::logic_error, "distance Variable is not in the model part", "")
if (!(rmodel_part.NodesBegin()->SolutionStepsDataHas(rTemperatureVar)))
KRATOS_THROW_ERROR(std::logic_error, "velocity Variable is not in the model part", "")
if (!(rmodel_part.NodesBegin()->SolutionStepsDataHas(rAreaVar)))
KRATOS_THROW_ERROR(std::logic_error, "Area Variable is not in the model part", "")
if (is_distributed == true)
if (!(rmodel_part.NodesBegin()->SolutionStepsDataHas(PARTITION_INDEX)))
KRATOS_THROW_ERROR(std::logic_error, "PARTITION_INDEX Variable is not in the model part", "")
//set as active the internal nodes
int node_size = rmodel_part.Nodes().size();
#pragma omp parallel for
for (int i = 0; i < node_size; i++)
{
ModelPart::NodesContainerType::iterator it = rmodel_part.NodesBegin() + i;
it->FastGetSolutionStepValue(rAreaVar) = 0.0;
const double& dist = it->FastGetSolutionStepValue(rDistanceVar);
if (dist < 0.0)
it->SetValue(IS_VISITED, 1.0);
else{
it->SetValue(IS_VISITED, 0.0);
double real_temp = it->FastGetSolutionStepValue(rTemperatureVar);
it->SetValue(rTemperatureVar, real_temp);
it->FastGetSolutionStepValue(rTemperatureVar) = 0.0;
}
}
//now extrapolate the velocity var from all of the nodes that have at least one internal node_size
array_1d<double, TDim + 1 > visited;
array_1d<double, TDim + 1 > N;
double avg;
double lumping_factor = 1.0 / double(TDim + 1);
boost::numeric::ublas::bounded_matrix <double, TDim + 1, TDim> DN_DX;
int elem_size = rmodel_part.Elements().size();
for (unsigned int level = 0; level < max_levels; level++)
{
#pragma omp parallel for private(DN_DX,N,visited,avg) firstprivate(lumping_factor,elem_size)
for (int i = 0; i < elem_size; i++)
{
PointerVector< Element>::iterator it = rmodel_part.ElementsBegin() + i;
Geometry<Node < 3 > >&geom = it->GetGeometry();
for (unsigned int k = 0; k < TDim + 1; k++)
visited[k] = geom[k].GetValue(IS_VISITED);
if (IsActive(visited))
{
double Volume;
GeometryUtils::CalculateGeometryData(geom, DN_DX, N, Volume);
//calculated average value of "velocity"
avg = 0.0;
double counter = 0.0;
for (unsigned int k = 0; k < TDim + 1; k++)
{
if (visited[k] > 0.0)
{
avg += geom[k].FastGetSolutionStepValue(rTemperatureVar);
counter += 1.0;
}
}
avg /= counter;
for (unsigned int k = 0; k < TDim + 1; k++)
{
if (visited[k] == 0.0)
{
geom[k].SetLock();
geom[k].FastGetSolutionStepValue(rTemperatureVar) += avg * Volume*lumping_factor;
geom[k].FastGetSolutionStepValue(rAreaVar) += Volume*lumping_factor;
geom[k].UnSetLock();
}
}
}
}
//mpi sync variables
if (is_distributed == true)
{
int my_rank = rmodel_part.GetCommunicator().MyPID();
#pragma omp parallel for firstprivate(node_size,my_rank)
for (int i = 0; i < node_size; i++)
{
ModelPart::NodesContainerType::iterator it = rmodel_part.NodesBegin() + i;
if (it->GetValue(IS_VISITED) == 1.0 && my_rank != it->FastGetSolutionStepValue(PARTITION_INDEX))
{
it->FastGetSolutionStepValue(rAreaVar) = 0.0;
it->FastGetSolutionStepValue(rTemperatureVar) = 0.0;
}
}
rmodel_part.GetCommunicator().AssembleCurrentData(rAreaVar);
rmodel_part.GetCommunicator().AssembleCurrentData(rTemperatureVar);
}
#pragma omp parallel for firstprivate(node_size)
for (int i = 0; i < node_size; i++)
{
ModelPart::NodesContainerType::iterator it = rmodel_part.NodesBegin() + i;
const double& area = it->FastGetSolutionStepValue(rAreaVar);
if (area > 1e-20 && it->GetValue(IS_VISITED) == 0.0) //this implies that node was computed
{
it->FastGetSolutionStepValue(rTemperatureVar) /= area;
it->SetValue(IS_VISITED, 1.0); //node is marked as already visitedz
}
}
}
//Rewrite the old value on non-updated temp
#pragma omp parallel for firstprivate(node_size)
for (int i = 0; i < node_size; i++)
{
ModelPart::NodesContainerType::iterator it = rmodel_part.NodesBegin() + i;
if(it->GetValue(IS_VISITED) == 0.0)
it->FastGetSolutionStepValue(rTemperatureVar) = it->GetValue(rTemperatureVar);
}
KRATOS_CATCH("")
}
///Function to extrapolate the pressure projection from the interior of the level set domain.
///the extrapolation velocity is taken from the SECOND layer of nodes INSIDE the level set domain,
///that is, the nodes that correspond to elements cut by the free surface ARE NOT used as a source for the extrapolation
///note that the body force is assigned to the pressure projection in all of the nodes which are not calculated otherwise
///@param rmodel_part is the ModelPart on which we will operate
///@param rDistanceVar is the Variable that we will use in calculating the distance
///@param rProjVar is the Variable being extrapolated
///@param rAreaVar is the Variable that we will use for L2 projections
///@param max_levels is the number of maximum "layers" of element that will be used in the calculation of the distances
void ExtrapolatePressureProjection(ModelPart& rmodel_part,
const Variable<double>& rDistanceVar,
const Variable<array_1d<double, 3 > >& rProjVar,
const Variable<double>& rPressureVar,
const Variable<double>& rAreaVar,
const unsigned int max_levels)
{
KRATOS_TRY
bool is_distributed = false;
if (rmodel_part.GetCommunicator().TotalProcesses() > 1)
is_distributed = true;
//check that variables needed are in the model part
if (!(rmodel_part.NodesBegin()->SolutionStepsDataHas(rDistanceVar)))
KRATOS_THROW_ERROR(std::logic_error, "distance Variable is not in the model part", "")
if (!(rmodel_part.NodesBegin()->SolutionStepsDataHas(rProjVar)))
KRATOS_THROW_ERROR(std::logic_error, "Pressure Projection Variable is not in the model part", "")
if (!(rmodel_part.NodesBegin()->SolutionStepsDataHas(BODY_FORCE)))
KRATOS_THROW_ERROR(std::logic_error, "BODY_FORCE Variable is not in the model part", "")
if (!(rmodel_part.NodesBegin()->SolutionStepsDataHas(rAreaVar)))
KRATOS_THROW_ERROR(std::logic_error, "Area Variable is not in the model part", "")
if (!(rmodel_part.NodesBegin()->SolutionStepsDataHas(rPressureVar)))
KRATOS_THROW_ERROR(std::logic_error, "rPressureVar Variable is not in the model part", "")
if (is_distributed == true)
if (!(rmodel_part.NodesBegin()->SolutionStepsDataHas(PARTITION_INDEX)))
KRATOS_THROW_ERROR(std::logic_error, "PARTITION_INDEX Variable is not in the model part", "")
//set as active the internal nodes
int node_size = rmodel_part.Nodes().size();
int elem_size = rmodel_part.Elements().size();
#pragma omp parallel for firstprivate(node_size)
for (int i = 0; i < node_size; i++)
{
ModelPart::NodesContainerType::iterator it = rmodel_part.NodesBegin() + i;
it->FastGetSolutionStepValue(rAreaVar) = 0.0;
const double& dist = it->FastGetSolutionStepValue(rDistanceVar);
if (dist < 0.0)
it->SetValue(IS_VISITED, 1.0);
else
{
it->SetValue(IS_VISITED, 0.0);
noalias(it->FastGetSolutionStepValue(rProjVar)) = ZeroVector(3);
it->FastGetSolutionStepValue(rPressureVar) = 0.0;
}
}
array_1d<double, TDim + 1 > dist;
//now deselect all of the nodes of the divided elements
#pragma omp parallel for private(dist)
for (int i = 0; i < elem_size; i++)
{
PointerVector< Element>::iterator it = rmodel_part.ElementsBegin() + i;
Geometry<Node < 3 > >&geom = it->GetGeometry();
for (unsigned int k = 0; k < TDim + 1; k++)
dist[k] = geom[k].FastGetSolutionStepValue(rDistanceVar);
if (IsDivided(dist))
{
for (unsigned int k = 0; k < TDim + 1; k++)
{
geom[k].SetLock();
geom[k].SetValue(IS_VISITED, 0.0);
geom[k].UnSetLock();
}
}
}
//now extrapolate the pressure projection var from all of the nodes that have at least one internal node_size
array_1d<double, TDim + 1 > visited;
array_1d<double, TDim + 1 > N;
array_1d<double, TDim> avg;
double lumping_factor = 1.0 / double(TDim + 1);
boost::numeric::ublas::bounded_matrix <double, TDim + 1, TDim> DN_DX;
for (unsigned int level = 0; level < max_levels; level++)
{
#pragma omp parallel for private(DN_DX,N,visited,avg) firstprivate(lumping_factor,elem_size)
for (int i = 0; i < elem_size; i++)
{
PointerVector< Element>::iterator it = rmodel_part.ElementsBegin() + i;
Geometry<Node < 3 > >&geom = it->GetGeometry();
for (unsigned int k = 0; k < TDim + 1; k++)
visited[k] = geom[k].GetValue(IS_VISITED);
if (IsActive(visited))
{
double Volume;
GeometryUtils::CalculateGeometryData(geom, DN_DX, N, Volume);
//calculated average value of "velocity"
noalias(avg) = ZeroVector(3);
double counter = 0.0;
for (unsigned int k = 0; k < TDim + 1; k++)
{
if (visited[k] > 0.0)
{
noalias(avg) += geom[k].FastGetSolutionStepValue(rProjVar);
counter += 1.0;
}
}
avg /= counter;
for (unsigned int k = 0; k < TDim + 1; k++)
{
if (visited[k] == 0.0)
{
geom[k].SetLock();
geom[k].FastGetSolutionStepValue(rProjVar) += avg * Volume*lumping_factor;
geom[k].FastGetSolutionStepValue(rAreaVar) += Volume*lumping_factor;
geom[k].UnSetLock();
}
}
}
}
//mpi sync variables
if (is_distributed == true)
{
int my_rank = rmodel_part.GetCommunicator().MyPID();
#pragma omp parallel for firstprivate(node_size,my_rank)
for (int i = 0; i < node_size; i++)
{
ModelPart::NodesContainerType::iterator it = rmodel_part.NodesBegin() + i;
if (it->GetValue(IS_VISITED) == 1.0 && my_rank != it->FastGetSolutionStepValue(PARTITION_INDEX))
{
it->FastGetSolutionStepValue(rAreaVar) = 0.0;
noalias(it->FastGetSolutionStepValue(rProjVar)) = ZeroVector(3);
}
}
rmodel_part.GetCommunicator().AssembleCurrentData(rAreaVar);
rmodel_part.GetCommunicator().AssembleCurrentData(rProjVar);
}
//finish the computation of the nodal pressure gradient
#pragma omp parallel for firstprivate(node_size)
for (int i = 0; i < node_size; i++)
{
ModelPart::NodesContainerType::iterator it = rmodel_part.NodesBegin() + i;
const double& area = it->FastGetSolutionStepValue(rAreaVar);
if (area > 1e-20 && it->GetValue(IS_VISITED) == 0.0) //this implies that node was computed
{
it->FastGetSolutionStepValue(rProjVar) /= area;
}
}
//now compute a nodal pressure which corresponds to the pressure gradient
array_1d<double, 3 > xorigin, auxiliary_dist;
#pragma omp parallel for private(DN_DX,N,visited,xorigin,avg,auxiliary_dist) firstprivate(lumping_factor,elem_size)
for (int i = 0; i < elem_size; i++)
{
PointerVector< Element>::iterator it = rmodel_part.ElementsBegin() + i;
Geometry<Node < 3 > >&geom = it->GetGeometry();
for (unsigned int k = 0; k < TDim + 1; k++)
visited[k] = geom[k].GetValue(IS_VISITED);
if (IsActive(visited))
{
double Volume;
GeometryUtils::CalculateGeometryData(geom, DN_DX, N, Volume);
// //calculated average value of "velocity"
// noalias(xorigin) = ZeroVector(3);
// noalias(avg) = ZeroVector(3);
// double porigin = 0.0;
// double counter = 0.0;
// for(unsigned int k=0; k<TDim+1; k++)
// {
// if(visited[k]>0.0)
// {
// noalias(xorigin) += geom[k].Coordinates();
// porigin += geom[k].FastGetSolutionStepValue(rPressureVar);
// noalias(avg) += geom[k].FastGetSolutionStepValue(rProjVar);
// counter += 1.0;
// }
// }
// xorigin /= counter;
// avg /= counter;
// porigin /= counter;
for (unsigned int k = 0; k < TDim + 1; k++)
{
if (visited[k] == 0.0)
{
noalias(auxiliary_dist) = ZeroVector(3);
double peff = 0.0;
double counter = 0.0;
for (unsigned int j = 0; j < TDim + 1; j++)
{
if (visited[j] != 0.0)
{
noalias(auxiliary_dist) = geom[k].Coordinates();
noalias(auxiliary_dist) -= geom[j].Coordinates();
array_1d<double, 3 > proj = geom[j].FastGetSolutionStepValue(rProjVar);
// double deltap = inner_prod(auxiliary_dist, proj);
peff += geom[j].FastGetSolutionStepValue(rPressureVar);
counter += 1.0;
}
}
peff /= counter;
geom[k].SetLock();
geom[k].FastGetSolutionStepValue(rPressureVar) += (peff) * Volume*lumping_factor;
geom[k].UnSetLock();
}
}
}
}
//mpi sync variables
if (is_distributed == true)
{
int my_rank = rmodel_part.GetCommunicator().MyPID();
#pragma omp parallel for firstprivate(node_size,my_rank)
for (int i = 0; i < node_size; i++)
{
ModelPart::NodesContainerType::iterator it = rmodel_part.NodesBegin() + i;
if (it->GetValue(IS_VISITED) == 1.0 && my_rank != it->FastGetSolutionStepValue(PARTITION_INDEX))
it->FastGetSolutionStepValue(rPressureVar) = 0.0;
}
rmodel_part.GetCommunicator().AssembleCurrentData(rPressureVar);
}
//finish the computation of the nodal pressure
#pragma omp parallel for firstprivate(node_size)
for (int i = 0; i < node_size; i++)
{
ModelPart::NodesContainerType::iterator it = rmodel_part.NodesBegin() + i;
const double& area = it->FastGetSolutionStepValue(rAreaVar);
if (area > 1e-20 && it->GetValue(IS_VISITED) == 0.0) //this implies that node was computed
{
it->FastGetSolutionStepValue(rPressureVar) /= area;
it->SetValue(IS_VISITED, 1.0); //node is marked as already visitedz
}
}
}
//assign to the body force the projection var for the nodes on which the PRESS_PROJ was not estimated otherwise
#pragma omp parallel for firstprivate(node_size)
for (int i = 0; i < node_size; i++)
{
ModelPart::NodesContainerType::iterator it = rmodel_part.NodesBegin() + i;
const double& dist = it->FastGetSolutionStepValue(rDistanceVar);
if (dist > 0.0 && it->GetValue(IS_VISITED) == 0.0) //this implies that node was computed
{
it->FastGetSolutionStepValue(rProjVar) = it->FastGetSolutionStepValue(BODY_FORCE);
}
}
KRATOS_CATCH("")
}
///Function to assign a pressure to the first layer of nodes outside of the fluid.
///Pressure is assigned in such a way that the pressure gradient is mantained, but the pressure is 0 where the distance is 0
///the exact distance from the free surface is recalculated here
///@param rmodel_part is the ModelPart on which we will operate
///@param rDistanceVar is the Variable that we will use in calculating the distance
///@param rProjVar is the Variable being extrapolated
///@param rPressureVar is the Variable that we will use for L2 projections
///@param rAreaVar is the Variable that we will use for L2 projections
void AssignFreeSurfacePressure(ModelPart& rmodel_part,
const Variable<double>& rDistanceVar,
const Variable<array_1d<double, 3 > >& rProjVar,
const Variable<double>& rPressureVar,
const Variable<double>& rAreaVar
)
{
KRATOS_TRY
bool is_distributed = false;
if (rmodel_part.GetCommunicator().TotalProcesses() > 1)
is_distributed = true;
//check that variables needed are in the model part
if (!(rmodel_part.NodesBegin()->SolutionStepsDataHas(rDistanceVar)))
KRATOS_THROW_ERROR(std::logic_error, "distance Variable is not in the model part", "")
if (!(rmodel_part.NodesBegin()->SolutionStepsDataHas(rProjVar)))
KRATOS_THROW_ERROR(std::logic_error, "Pressure Projection Variable is not in the model part", "")
if (!(rmodel_part.NodesBegin()->SolutionStepsDataHas(rPressureVar)))
KRATOS_THROW_ERROR(std::logic_error, "rPressureVar Variable is not in the model part", "")
if (!(rmodel_part.NodesBegin()->SolutionStepsDataHas(rAreaVar)))
KRATOS_THROW_ERROR(std::logic_error, "rAreaVar Variable is not in the model part", "")
if (is_distributed == true)
if (!(rmodel_part.NodesBegin()->SolutionStepsDataHas(PARTITION_INDEX)))
KRATOS_THROW_ERROR(std::logic_error, "PARTITION_INDEX Variable is not in the model part", "")
//set as active the internal nodes
int node_size = rmodel_part.Nodes().size();
int elem_size = rmodel_part.Elements().size();
#pragma omp parallel for firstprivate(node_size)
for (int i = 0; i < node_size; i++)
{
ModelPart::NodesContainerType::iterator it = rmodel_part.NodesBegin() + i;
it->FastGetSolutionStepValue(rAreaVar) = 0.0;
const double& dist = it->FastGetSolutionStepValue(rDistanceVar);
if (dist < 0.0)
{
it->SetValue(IS_VISITED, 1.0);
}
else
{
it->SetValue(IS_VISITED, 0.0);
it->FastGetSolutionStepValue(rPressureVar) = 0.0;
}
}
array_1d<double, TDim + 1 > dist, exact_dist;
array_1d<double, TDim> grad_d;
array_1d<double, TDim + 1 > N;
double lumping_factor = 1.0 / double(TDim + 1);
boost::numeric::ublas::bounded_matrix <double, TDim + 1, TDim> DN_DX;
//now deselect all of the nodes of the divided elements
#pragma omp parallel for private(dist,N,DN_DX)
for (int i = 0; i < elem_size; i++)
{
PointerVector< Element>::iterator it = rmodel_part.ElementsBegin() + i;
Geometry<Node < 3 > >&geom = it->GetGeometry();
for (unsigned int k = 0; k < TDim + 1; k++)
dist[k] = geom[k].FastGetSolutionStepValue(rDistanceVar);
if (IsDivided(dist))
{
//calculate exact distance
double Volume;
GeometryUtils::CalculateGeometryData(geom, DN_DX, N, Volume);
ComputeExactDistances(DN_DX, Volume, geom, dist, exact_dist);
//compute the direction of the gradient of the distances
for (unsigned int iii = 0; iii < TDim; iii++)
grad_d[iii] = DN_DX(0, iii) * dist[0];
for (unsigned int k = 1; k < TDim + 1; k++)
for (unsigned int iii = 0; iii < TDim; iii++)
grad_d[iii] += DN_DX(k, iii) * dist[k];
double norm_grad = norm_2(grad_d);
grad_d /= norm_grad;
//assign pressure contribution
for (unsigned int k = 0; k < TDim + 1; k++)
{
if (dist[k] >= 0.0)
{
const array_1d<double, 3 > & press_proj = geom[k].FastGetSolutionStepValue(rProjVar);
double pouter = 0.0;
for (unsigned int iii = 0; iii < TDim; iii++)
pouter += grad_d[iii] * press_proj[iii];
pouter *= exact_dist[k];
geom[k].SetLock();
geom[k].FastGetSolutionStepValue(rPressureVar) += pouter * Volume*lumping_factor;
geom[k].FastGetSolutionStepValue(rAreaVar) += Volume*lumping_factor;
geom[k].UnSetLock();
}
}
}
}
rmodel_part.GetCommunicator().AssembleCurrentData(rAreaVar);
rmodel_part.GetCommunicator().AssembleCurrentData(rPressureVar);
//finish the computation of the nodal pressure gradient
#pragma omp parallel for firstprivate(node_size)
for (int i = 0; i < node_size; i++)
{
ModelPart::NodesContainerType::iterator it = rmodel_part.NodesBegin() + i;
const double& area = it->FastGetSolutionStepValue(rAreaVar);
const double& dist = it->FastGetSolutionStepValue(rDistanceVar);
if (area > 1e-20 && it->GetValue(IS_VISITED) == 0.0) //this implies that node was computed
{
it->SetValue(IS_VISITED, 1.0);
it->FastGetSolutionStepValue(rPressureVar) /= area;
}
else if (dist >= 0.0)
it->FastGetSolutionStepValue(rPressureVar) = -0.000001;
}
KRATOS_CATCH("")
}
///@}
///@name Operators
///@{
///@}
///@name Operations
///@{
///@}
///@name Access
///@{
///@}
///@name Inquiry
///@{
///@}
///@name Input and output
///@{
/// Turn back information as a string.
virtual std::string Info() const
{
std::stringstream buffer;
buffer << "ParallelExtrapolationUtilities" << TDim << "D";
return buffer.str();
};
/// Print information about this object.
virtual void PrintInfo(std::ostream& rOStream) const
{
rOStream << "ParallelExtrapolationUtilities" << TDim << "D";
};
/// Print object's data.
virtual void PrintData(std::ostream& rOStream) const
{
};
///@}
///@name Friends
///@{
///@}
protected:
///@name Protected static Member Variables
///@{
///@}
///@name Protected member Variables
///@{
///@}
///@name Protected Operators
///@{
//*******************************************************************
bool IsDivided(array_1d<double, TDim + 1 > & dist)
{
unsigned int positive = 0;
unsigned int negative = 0;
for (unsigned int i = 0; i < TDim + 1; i++)
{
if (dist[i] >= 0)
positive++;
else
negative++;
}
bool is_divided = false;
if (positive > 0 && negative > 0)
is_divided = true;
return is_divided;
}
//*******************************************************************
static bool IsActive(array_1d<double, TDim + 1 > & visited)
{
unsigned int positive = 0;
for (unsigned int i = 0; i < TDim + 1; i++)
if (visited[i] > 0.9999999999) //node was considered
positive++;
bool is_active = false;
if (positive >= 1)
is_active = true;
return is_active;
}
//*******************************************************************
void ComputeExactDistances(const boost::numeric::ublas::bounded_matrix <double, TDim + 1, TDim>& DN_DX,
const double& Area,
Geometry<Node < 3 > >& geom,
const array_1d<double, TDim + 1 > & distances,
array_1d<double, TDim + 1 > & exact_dist
)
{
array_1d<double, TDim> grad_d;
array_1d<double, 3 > coord_on_0;
coord_on_0[0] = -100000000000.0;
coord_on_0[1] = -100000000000.0;
coord_on_0[2] = -100000000000.0;
array_1d<double, 3 > temp;
//compute the gradient of the distance and normalize it
noalias(grad_d) = prod(trans(DN_DX), distances);
double norm = norm_2(grad_d);
grad_d /= norm;
//find one division point on one edge
for (unsigned int i = 1; i < TDim + 1; i++)
{
if (distances[0] * distances[i] <= 0.0) //if the edge is divided
{
double delta_d = fabs(distances[i]) + fabs(distances[0]);
if (delta_d > 1e-20)
{
double Ni = fabs(distances[0]) / delta_d;
double N0 = fabs(distances[i]) / delta_d;
noalias(coord_on_0) = N0 * geom[0].Coordinates();
noalias(coord_on_0) += Ni * geom[i].Coordinates();
}
else
noalias(coord_on_0) = geom[0].Coordinates();
break;
}
}
//double nodal_area_factor = Area/static_cast<double>(TDim+1);
//now calculate the distance of all the nodes from the elemental free surface
for (unsigned int i = 0; i < TDim + 1; i++)
{
noalias(temp) = geom[i].Coordinates();
noalias(temp) -= coord_on_0;
double real_distance = 0.0;
for (unsigned int k = 0; k < TDim; k++)
real_distance += temp[k] * grad_d[k];
real_distance = fabs(real_distance);
exact_dist[i] = real_distance;
}
}
///@}
///@name Protected Operations
///@{
///@}
///@name Protected Access
///@{
///@}
///@name Protected Inquiry
///@{
///@}
///@name Protected LifeCycle
///@{
///@}
private:
///@name Static Member Variables
///@{
///@}
///@name Member Variables
///@{
///@}
///@name Private Operators
///@{
///@}
///@name Private Operations
///@{
///@}
///@name Private Access
///@{
///@}
///@name Private Inquiry
///@{
///@}
///@name Un accessible methods
///@{
/// Assignment operator.
ParallelExtrapolationUtilities<TDim> & operator=(ParallelExtrapolationUtilities<TDim> const& rOther)
{
};
/// Copy constructor.
ParallelExtrapolationUtilities(ParallelExtrapolationUtilities<TDim> const& rOther)
{
};
///@}
}; // Class ParallelExtrapolationUtilities
///@}
///@name Type Definitions
///@{
///@}
///@name Input and output
///@{
/// input stream function
template<unsigned int TDim>
inline std::istream & operator >>(std::istream& rIStream,
ParallelExtrapolationUtilities<TDim>& rThis)
{
return rIStream;
}
/// output stream function
template<unsigned int TDim>
inline std::ostream & operator <<(std::ostream& rOStream,
const ParallelExtrapolationUtilities<TDim>& rThis)
{
rThis.PrintInfo(rOStream);
rOStream << std::endl;
rThis.PrintData(rOStream);
return rOStream;
}
///@}
} // namespace Kratos.
#endif // KRATOS_PARALLEL_EXTRAPOLATION_UTILITIES_H_INCLUDED defined
|
tsp_ant04.c | /*
Description:
This program is my implementation of the "Ant Colony" algorithm to solve the "Travelling Salesman Problem"
Author:
Georgios Evangelou (1046900)
Year: 5
Parallel Programming in Machine Learning Problems
Electrical and Computer Engineering Department, University of Patras
System Specifications:
CPU: AMD Ryzen 2600 (6 cores/12 threads, @3.8 GHz, 6786.23 bogomips)
GPU: Nvidia GTX 1050 (dual-fan, overclocked)
RAM: 8GB (dual-channel, @2666 MHz)
Version Notes:
Compiles/Runs/Debugs with: gcc tsp_ant04.c -o tsp_ant04 -lm -O3 -fopt-info -fopenmp -pg && time ./tsp_ant04 && gprof ./tsp_ant04
Inherits all settings of the previous version unless stated otherwise
Improved speed and parallelism
*/
// ****************************************************************************************************************
#pragma GCC optimize("O3","unroll-loops","omit-frame-pointer","inline") //Apply O3 and extra optimizations
#pragma GCC option("arch=native","tune=native","no-zero-upper") //Adapt to the current system
#pragma GCC target("avx") //Enable AVX
// ****************************************************************************************************************
#include "stdio.h"
#include "stdlib.h"
#include "math.h"
#include "stdbool.h"
#include "omp.h"
// ****************************************************************************************************************
#define N 1000
#define Nx 1000
#define Ny 1000
#define nonExist -999999
#define ALPHA 0.50 //0.50 // Affects pherormone dependency
#define BETA 2.00 //0.50 // Affects path length dependency
#define RHO 0.50 //0.50
#define TAU_INITIAL_VALUE 0.50 //0.50
#define ANTS 100
#define REPETITIONS 8
#define DEBUG 0
#define THREADS 12
// ****************************************************************************************************************
float CitiesX[N];
float CitiesY[N];
double CalculatedDistances[N][N];
double CalculatedDistances_to_mBETA[N][N];
double TauValues_to_A[N][N]; // Pherormone values between all city pair
double DistanceTravelled[ANTS]; // The total length of each ant's path
int AntsPaths[ANTS][N+1]; // The paths of all ants
bool PathIsVisited[N][N];
// ****************************************************************************************************************
// Initialize paths' state
// ****************************************************************************************************************
void InitializeVisitedPaths() {
if (DEBUG==1) printf("Now initializing paths...");
for (int i=0; i<N; i++) {
for (int j=i+1; j<N; j++) {
PathIsVisited[i][j] = false;
PathIsVisited[j][i] = false;
}
}
if (DEBUG==1) printf(" ===> COMPLETED\n");
}
// ****************************************************************************************************************
// Prints an int array
// ****************************************************************************************************************
void PrintIntArray(int ARRAY[], const int SIZE) {
for (int i=0; i<SIZE; i++) {
printf("%3d ", ARRAY[i]);
}
printf("\n");
}
// ****************************************************************************************************************
// Find min of an double array
// ****************************************************************************************************************
double MinOfDoubleArray(double ARRAY[], const int SIZE) {
double min = INFINITY;
for (int i=0; i<SIZE; i++)
if (ARRAY[i] < min)
min = ARRAY[i];
return min;
}
// ****************************************************************************************************************
// Find average of an double array
// ****************************************************************************************************************
double AvgOfDoubleArray(double ARRAY[], const int SIZE) {
double avg = 0.0;
for (int i=0; i<SIZE; i++) avg += ARRAY[i];
return avg/SIZE;
}
// ****************************************************************************************************************
// Prints the cities' positions
// ****************************************************************************************************************
void PrintCities() {
printf("> The cities are:\n");
for (int i=0; i<N; i++) {
printf(">> City: %6d X:%5.2f Y:%5.2f\n", i, CitiesX[i], CitiesY[i] );
}
printf("\n");
}
// ****************************************************************************************************************
// Prints the travelling sequence of given path
// ****************************************************************************************************************
void PrintPath_2(int Path[N+1]) {
printf("> The path is:\n");
for (int i=0; i<N+1; i++) {
printf(">> %d ", Path[i]);
}
printf("\n");
}
// ****************************************************************************************************************
// Visually maps the cities' positions
// ****************************************************************************************************************
void MapCities() {
int Map[Ny+1][Nx+1];
printf("Now creating a visual map of the cities...\n");
for (int i=0; i<Nx+1; i++)
for (int j=0; j<Ny+1; j++)
Map[j][i] = (float) nonExist;
//printf("Quantized coordinates are:\n");
for (int c=0; c<N; c++) {
int x = (int) CitiesX[c] ;
int y = (int) CitiesY[c] ;
//printf(" City:%d y=%d and x=%d\n",c,y,x);
if (Map[y][x] == nonExist) Map[y][x] = c;
else Map[y][x] = -1;
}
printf("This is the cities' map:\n");
printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n");
for (int y=0; y<Ny+1; y++){
for (int x=0; x<Nx+1; x++)
printf("%8d ", Map[y][x]);
printf("\n");
}
printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n");
printf("\n");
}
// ****************************************************************************************************************
// Finds Euclidean distance between two cities
// ****************************************************************************************************************
double Distance(int A, int B) {
return (double) sqrt( (CitiesX[A]-CitiesX[B])*(CitiesX[A]-CitiesX[B]) + (CitiesY[A]-CitiesY[B])*(CitiesY[A]-CitiesY[B]) );
}
// ****************************************************************************************************************
// Calculates the possibility that an ant <ant> located at city I travels to city J
// ****************************************************************************************************************
double Possibility(int ant, int I, int J, int ant_path_length, bool TheAntHasVisitiedCity[N]) {
double summation = 0.0;
for (int j=0; j<N; j++)
if (!TheAntHasVisitiedCity[j])
summation += TauValues_to_A[I][j] * CalculatedDistances_to_mBETA[I][j];
//if (isnan(summation)) {printf("\nFATAL ERROR: <summation> IS NAN\nTHE PROGRAM WILL BE TERMINATED.\n"); exit(1);}
return (TauValues_to_A[I][J] * CalculatedDistances_to_mBETA[I][J] / summation);
}
// ****************************************************************************************************************
// Calculates new Tau of path between cities <I> and <J>
// ****************************************************************************************************************
double CalculateNewTau(int I, int J) {
if (DEBUG==2) printf("Calculating new tau value between %d and %d...\n", I, J);
double DeltaTau = 0.0;
// For each ant
if (PathIsVisited[I][J]==false) return ( ((1-RHO) * pow(TauValues_to_A[I][J], 1.0/(float) ALPHA) ) );
for (int ant=0; ant<ANTS; ant++) {
if (DEBUG==2) printf("\r> Progress: %.2f%%", 100*(ant+1)/((float)ANTS));
// ...run through its path
for (int city=0; city<N; city++) {
// ...and check if path from <I> to <J> was used
if ( ((AntsPaths[ant][city]==I)||(AntsPaths[ant][city]==J)) && ((AntsPaths[ant][city+1]==I)||(AntsPaths[ant][city+1]==J)) ) {
DeltaTau += 1.0 / DistanceTravelled[ant];
break;
}
}
}
if (DEBUG==2) printf(" ===> Completed.\n");
return ( ((1-RHO) * pow(TauValues_to_A[I][J], 1.0/(float) ALPHA) ) + DeltaTau );
}
// ****************************************************************************************************************
// Calculates new Tau values of all pairs of cities
// ****************************************************************************************************************
void CalculateNewTaus() {
printf("Now calculating new tau values of all pairs of cities...\n");
#pragma omp parallel for schedule(dynamic, 10) num_threads(THREADS)
for (int i=0; i<N; i++) {
for (int j=i+1; j<N; j++) {
double newTau = pow(CalculateNewTau(i, j), ALPHA);
TauValues_to_A[i][j] = newTau;
TauValues_to_A[j][i] = newTau;
}
}
#pragma barrier
//printf(" ===> Completed.\n");
}
// ****************************************************************************************************************
// Initializes the Tau to the power of ALPHA values
// ****************************************************************************************************************
void InitializeTauValues_2() {
printf("Now initializing the tau values...\n");
for (int i=0; i<N; i++) {
printf("\r> Progress: %.2f%%", 100*(i+1)/((float)N));
for (int j=0; j<N; j++) {
TauValues_to_A[i][j] = pow(TAU_INITIAL_VALUE, ALPHA); //(float) rand() / RAND_MAX;
}
}
printf(" ===> Completed.\n");
}
// ****************************************************************************************************************
// Finds all Eucleidian distances between all pairs of cities (real, and real^(-BETA) )
// ****************************************************************************************************************
void CalculateAllDistances_2() {
printf("Now calculating distances and hetas^(BETA) between all pairs of cities...\n");
for (int i=0; i<N; i++) {
printf("\r> Progress: %.2f%%", 100*(i+1)/((float)N));
for (int j=i+1; j<N; j++) {
double temp = Distance(i, j); double temp_to_mBETA = pow(temp, -BETA);
CalculatedDistances[i][j] = temp;
CalculatedDistances[j][i] = temp;
CalculatedDistances_to_mBETA[i][j] = temp_to_mBETA;
CalculatedDistances_to_mBETA[j][i] = temp_to_mBETA;
}
}
printf(" ===> Completed.\n");
}
// ****************************************************************************************************************
// Initializes the cities' positions
// ****************************************************************************************************************
void SetCities() {
printf("Now initializing the positions of the cities...\n");
for (int i=0; i<N; i++) {
CitiesX[i] = Nx * (float) rand() / RAND_MAX;
CitiesY[i] = Ny * (float) rand() / RAND_MAX;
}
}
// ****************************************************************************************************************
// Ant <ant> starts finding a path, starting from <starting_city>
// ****************************************************************************************************************
void AntRun(int ant, int starting_city, int repetitions) {
if (DEBUG==1) printf(">> Ant #%d is now running...\n", ant);
double totDist = 0.0;
int visited_cities = 1, current_city = starting_city;
AntsPaths[ant][0] = starting_city; AntsPaths[ant][N] = starting_city;
bool TheAntHasVisitiedCity[N];
for (int i=0; i<N; i++) TheAntHasVisitiedCity[i] = false;
TheAntHasVisitiedCity[starting_city] = true;
do {
if (DEBUG==1) printf("\r>> Progress: %.2f%%", 100*(visited_cities+1)/((float) N) );
TheAntHasVisitiedCity[current_city] = true;
double highest_decision_value = 0.0;
int next_city = -1;
// For every city set a decision value and choose the one with the highest
for (int i=0; i<N; i++) {
if (TheAntHasVisitiedCity[i]) continue; //...if we are trying to access current city or a visited one, go to next
unsigned seed = 3*ant + 17*omp_get_thread_num() + 22*repetitions + 1112*omp_get_wtime();
double random_number = ((float) rand_r(&seed) )/((float)RAND_MAX);
double decision_value = random_number * Possibility(ant, current_city, i, visited_cities, TheAntHasVisitiedCity);
if (decision_value > highest_decision_value) {
next_city = i;
highest_decision_value = decision_value;
}
}
PathIsVisited[current_city][next_city] = true; PathIsVisited[next_city][current_city] = true; //Mark path as visited by some ant/ants
AntsPaths[ant][visited_cities++] = next_city; //Add decided city to current ant's path
totDist += CalculatedDistances[current_city][next_city]; //...add the distance to it
current_city = next_city; //...and make it the current city
} while (visited_cities < N);
totDist += CalculatedDistances[current_city][starting_city];
DistanceTravelled[ant] = totDist;
if (DEBUG==1) printf(" ===> Finished\n");
}
// ****************************************************************************************************************
// The main program
// ****************************************************************************************************************
int main( int argc, const char* argv[] ) {
printf("------------------------------------------------------------------------------\n");
printf("This program searches for the optimal traveling distance between %d cities,\n", N);
printf("spanning in an area of X=(0,%d) and Y=(0,%d)\n", Nx, Ny);
printf("------------------------------------------------------------------------------\n");
srand(1046900);
SetCities();
CalculateAllDistances_2();
InitializeTauValues_2();
int repetitions = 0;
printf("\n~~~~ NOW RUNNING THE MAIN SEQUENCE ~~~~\n==================================================\n");
do {
InitializeVisitedPaths();
printf("Now the ants are running...\n");
#pragma omp parallel for schedule(dynamic, 5) num_threads(THREADS)
for (int ant=0; ant<ANTS; ant++) {
unsigned seed = ant + 83*omp_get_thread_num() + 1297*repetitions + 11*omp_get_wtime();
int starting_city = (int)( ((float) rand_r(&seed) )*(N-1)/((float)RAND_MAX) );
if (starting_city<0 || starting_city>N-1) exit(1);
AntRun(ant, starting_city, repetitions);
}
#pragma barrier
CalculateNewTaus();
printf("REPETITION: %9d AVERAGE_PATH_LENGTH: %8.3lf\n", ++repetitions, AvgOfDoubleArray(DistanceTravelled, ANTS));
printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n");
if (DEBUG==1) printf("\n");
} while (repetitions < REPETITIONS);
printf("\nCalculations completed. Results:\n");
printf("Optimal path distance found is: %.2lf\n", MinOfDoubleArray(DistanceTravelled, ANTS));
printf("Average path distance found is: %.2lf\n", AvgOfDoubleArray(DistanceTravelled, ANTS));
return 0 ;
}
|
Reduce.h | // --------------------------------------------------------------------------
// Binary Brain -- binary neural net framework
//
// Copyright (C) 2018-2019 by Ryuji Fuchikami
// https://github.com/ryuz
// ryuji.fuchikami@nifty.com
// --------------------------------------------------------------------------
#pragma once
#include <random>
#include "bb/Model.h"
namespace bb {
/**
* @brief バイナリ変調したデータを積算して実数に戻す
* @details バイナリ変調したデータを積算して実数に戻す
* 出力に対して入力は frame_mux_size 倍のフレーム数を必要とする
* BinaryToReal と組み合わせて使う想定
*
* @tparam BinType バイナリ型 (x)
* @tparam RealType 実数型 (y, dy, dx)
*/
template <typename BinType = float, typename RealType = float>
class Reduce : public Model
{
using _super = Model;
public:
static inline std::string ModelName(void) { return "Reduce"; }
static inline std::string ObjectName(void){ return ModelName() + "_" + DataType<BinType>::Name() + "_" + DataType<RealType>::Name(); }
std::string GetModelName(void) const override { return ModelName(); }
std::string GetObjectName(void) const override { return ObjectName(); }
protected:
bool m_host_only = false;
indices_t m_input_shape;
indices_t m_output_shape;
index_t m_integration_size = 0;
public:
struct create_t
{
indices_t output_shape;
index_t integration_size = 0;
};
protected:
Reduce(create_t const &create)
{
m_output_shape = create.output_shape;
m_integration_size = create.integration_size;
}
/**
* @brief コマンド処理
* @detail コマンド処理
* @param args コマンド
*/
void CommandProc(std::vector<std::string> args)
{
// HostOnlyモード設定
if (args.size() == 2 && args[0] == "host_only")
{
m_host_only = EvalBool(args[1]);
}
}
public:
~Reduce() {}
static std::shared_ptr<Reduce> Create(create_t const &create)
{
return std::shared_ptr<Reduce>(new Reduce(create));
}
static std::shared_ptr<Reduce> Create(index_t output_node, index_t integration_size=0)
{
create_t create;
create.output_shape = indices_t({output_node});
create.integration_size = integration_size;
return Create(create);
}
static std::shared_ptr<Reduce> Create(indices_t output_shape, index_t integration_size=0)
{
create_t create;
create.output_shape = output_shape;
create.integration_size = integration_size;
return Create(create);
}
static std::shared_ptr<Reduce> Create(void)
{
return Create(create_t());
}
#ifdef BB_PYBIND11
static std::shared_ptr<Reduce> CreatePy(indices_t output_shape, index_t integration_size=0)
{
create_t create;
create.output_shape = output_shape;
create.integration_size = integration_size;
return Create(create);
}
#endif
/**
* @brief 入力のshape設定
* @detail 入力のshape設定
* @param shape 新しいshape
* @return なし
*/
indices_t SetInputShape(indices_t shape) override
{
// 設定済みなら何もしない
if ( shape == this->GetInputShape() ) {
return this->GetOutputShape();
}
// 形状設定
m_input_shape = shape;
// 倍率指定があるなら従う
if ( m_integration_size > 0 ) {
m_output_shape = shape;
BB_ASSERT(m_output_shape[0] % m_integration_size == 0);
m_output_shape[0] /= m_integration_size;
}
// 整数倍の縮退のみ許容
BB_ASSERT(CalcShapeSize(m_input_shape) >= CalcShapeSize(m_output_shape));
BB_ASSERT(CalcShapeSize(m_input_shape) % CalcShapeSize(m_output_shape) == 0);
return m_output_shape;
}
/**
* @brief 入力形状取得
* @detail 入力形状を取得する
* @return 入力形状を返す
*/
indices_t GetInputShape(void) const override
{
return m_input_shape;
}
/**
* @brief 出力形状取得
* @detail 出力形状を取得する
* @return 出力形状を返す
*/
indices_t GetOutputShape(void) const override
{
return m_output_shape;
}
FrameBuffer Forward(FrameBuffer x_buf, bool train = true) override
{
BB_ASSERT(x_buf.GetType() == DataType<BinType>::type);
// SetInputShpaeされていなければ初回に設定
if (x_buf.GetShape() != m_input_shape) {
SetInputShape(x_buf.GetShape());
}
// 戻り値の型を設定
FrameBuffer y_buf(x_buf.GetFrameSize(), m_output_shape, DataType<RealType>::type);
#if 0 // #ifdef BB_WITH_CUDA
if ( DataType<BinType>::type == BB_TYPE_FP32 && !m_host_only && DataType<RealType>::type == BB_TYPE_FP32
&& x_buf.IsDeviceAvailable() && y_buf.IsDeviceAvailable() && Manager::IsDeviceAvailable() ) {
auto x_ptr = x_buf.LockDeviceMemoryConst();
auto y_ptr = y_buf.LockDeviceMemory(true);
bbcu_fp32_BinaryToReal_Forward
(
(float const *)x_ptr.GetAddr(),
(float *)y_ptr.GetAddr(),
(int )(CalcShapeSize(m_input_shape) / CalcShapeSize(m_output_shape)),
(int )m_frame_mux_size,
(int )GetOutputNodeSize(),
(int )(x.GetFrameStride() / sizeof(float)),
(int )y_buf.GetFrameSize(),
(int )(y_buf.GetFrameStride() / sizeof(float))
);
return y_buf;
}
#endif
{
// 汎用版
auto x_ptr = x_buf.LockConst<BinType>();
auto y_ptr = y_buf.Lock<RealType>(true);
index_t input_node_size = GetInputNodeSize();
index_t output_node_size = GetOutputNodeSize();
index_t frame_size = y_buf.GetFrameSize();
index_t mux_size = input_node_size / output_node_size;
// index_t node_size = std::max(input_node_size, output_node_size);
#pragma omp parallel for
for (index_t output_node = 0; output_node < output_node_size; ++output_node) {
for (index_t frame = 0; frame < frame_size; ++frame) {
RealType sum = 0;
for (index_t i = 0; i < mux_size; ++i) {
sum += (RealType)x_ptr.Get(frame, output_node_size * i + output_node);
}
y_ptr.Set(frame, output_node, sum / (RealType)mux_size);
}
}
return y_buf;
}
}
FrameBuffer Backward(FrameBuffer dy_buf) override
{
if (dy_buf.Empty()) {
return FrameBuffer();
}
BB_ASSERT(dy_buf.GetType() == DataType<RealType>::type);
// 戻り値の型を設定
FrameBuffer dx_buf(dy_buf.GetFrameSize(), m_input_shape, DataType<RealType>::type);
#if 0 // #ifdef BB_WITH_CUDA
if ( DataType<BT>::type == BB_TYPE_FP32 && !m_host_only
&& dy_buf.IsDeviceAvailable() && dx_buf.IsDeviceAvailable() && Manager::IsDeviceAvailable() ) {
auto dy_ptr = dy_buf.LockDeviceMemoryConst();
auto dx_ptr = dx_buf.LockDeviceMemory(true);
bbcu_fp32_BinaryToReal_Backward
(
(float const *)dy_ptr.GetAddr(),
(float *)dx_ptr.GetAddr(),
(int )(CalcShapeSize(m_input_shape) / CalcShapeSize(m_output_shape)),
(int )m_frame_mux_size,
(int )GetOutputNodeSize(),
(int )(dx_buf.GetFrameStride() / sizeof(float)),
(int )dy.GetFrameSize(),
(int )(dy.GetFrameStride() / sizeof(float))
);
return dx_buf;
}
#endif
{
// 汎用版
index_t input_node_size = GetInputNodeSize();
index_t output_node_size = GetOutputNodeSize();
index_t frame_size = dy_buf.GetFrameSize();
index_t mux_size = input_node_size / output_node_size;
auto dy_ptr = dy_buf.LockConst<RealType>();
auto dx_ptr = dx_buf.Lock<RealType>();
#pragma omp parallel for
for (index_t output_node = 0; output_node < output_node_size; ++output_node) {
for (index_t frame = 0; frame < frame_size; ++frame) {
RealType dy = dy_ptr.Get(frame, output_node);
RealType dx = dy / (RealType)mux_size;
for (index_t i = 0; i < mux_size; i++) {
dx_ptr.Set(frame, output_node_size * i + output_node, dx);
}
}
}
return dx_buf;
}
}
// シリアライズ
protected:
void DumpObjectData(std::ostream &os) const override
{
// バージョン
std::int64_t ver = 1;
bb::SaveValue(os, ver);
// 親クラス
_super::DumpObjectData(os);
// メンバ
bb::SaveValue(os, m_host_only);
bb::SaveValue(os, m_input_shape);
bb::SaveValue(os, m_output_shape);
bb::SaveValue(os, m_integration_size);
}
void LoadObjectData(std::istream &is) override
{
// バージョン
std::int64_t ver;
bb::LoadValue(is, ver);
BB_ASSERT(ver == 1);
// 親クラス
_super::LoadObjectData(is);
// メンバ
bb::LoadValue(is, m_host_only);
bb::LoadValue(is, m_input_shape);
bb::LoadValue(is, m_output_shape);
bb::LoadValue(is, m_integration_size);
}
};
}
// end of file
|
DRB094-doall2-ordered-orig-no.c | /*
Copyright (c) 2017, Lawrence Livermore National Security, LLC.
Produced at the Lawrence Livermore National Laboratory
Written by Chunhua Liao, Pei-Hung Lin, Joshua Asplund,
Markus Schordan, and Ian Karlin
(email: 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.
*/
/*
Two-dimensional array computation:
ordered(2) is used to associate two loops with omp for.
The corresponding loop iteration variables are private.
ordered(n) is an OpenMP 4.5 addition.
*/
#if (_OPENMP<201511)
#error "An OpenMP 4.5 compiler is needed to compile this test."
#endif
#include <stdio.h>
int a[100][100];
int main()
{
int i, j;
#pragma omp parallel for ordered(2) schedule(dynamic)
for (i = 0; i < 100; i++)
for (j = 0; j < 100; j++)
{
a[i][j] = a[i][j] + 1;
#pragma omp ordered depend(sink:i-1,j) depend (sink:i,j-1)
printf ("test i=%d j=%d\n",i,j);
#pragma omp ordered depend(source)
}
return 0;
}
|
sum.c | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <omp.h>
#include <sys/time.h>
enum {
N = 1000000
};
double wtime()
{
struct timeval t;
gettimeofday(&t, NULL);
return (double)t.tv_sec + (double)t.tv_usec * 1E-6;
}
double sum(double *v, int low, int high)
{
if (low == high)
return v[low];
int mid = (low + high) / 2;
return sum(v, low, mid) + sum(v, mid + 1, high);
}
/* sum_omp: OpenMP-limited nested parallelism -- ineffective version */
double sum_omp(double *v, int low, int high)
{
if (low == high)
return v[low];
double sum_left, sum_right;
int mid = (low + high) / 2;
#pragma omp parallel num_threads(2)
{
#pragma omp sections
{
#pragma omp section
{
sum_left = sum_omp(v, low, mid);
//printf("L: Level %d / %d, thread %d / %d range [%d..%d] = %f\n",
// omp_get_active_level(), omp_get_level(), omp_get_thread_num(), omp_get_num_threads(), low, mid, sum_left);
}
#pragma omp section
{
sum_right = sum_omp(v, mid + 1, high);
//printf("R: Level %d / %d, thread %d / %d range [%d..%d] = %f\n",
// omp_get_active_level(), omp_get_level(), omp_get_thread_num(), omp_get_num_threads(), mid + 1, high, sum_right);
}
}
}
return sum_left + sum_right;
}
/* sum_omp_fixed_depth: Limited nested parallelism */
double sum_omp_fixed_depth(double *v, int low, int high)
{
if (low == high)
return v[low];
double sum_left, sum_right;
int mid = (low + high) / 2;
if (omp_get_active_level() >= omp_get_max_active_levels()) {
// We have now about omp_get_active_level() * 2 threads
// Switch off to serial version
return sum(v, low, high);
}
#pragma omp parallel num_threads(2)
{
#pragma omp sections
{
#pragma omp section
sum_left = sum_omp_fixed_depth(v, low, mid);
#pragma omp section
sum_right = sum_omp_fixed_depth(v, mid + 1, high);
}
}
return sum_left + sum_right;
}
int ilog2(int x)
{
return log(x) / log(2.0);
}
double run_serial()
{
double *v = malloc(sizeof(*v) * N);
for (int i = 0; i < N; i++)
v[i] = i + 1.0;
double t = wtime();
double res = sum(v, 0, N - 1);
t = wtime() - t;
printf("Result (serial): %.4f; error %.12f\n", res, fabs(res - (1.0 + N) / 2.0 * N));
free(v);
return t;
}
double run_parallel()
{
double *v = malloc(sizeof(*v) * N);
for (int i = 0; i < N; i++)
v[i] = i + 1.0;
int maxthreads = atoi(getenv("OMP_NUM_THREADS"));
int maxlevels = ilog2(maxthreads);
omp_set_nested(1);
omp_set_max_active_levels(maxlevels);
printf("Parallel version: max_threads = %d, max_levels = %d, \n", 1 << maxlevels, maxlevels);
double t = wtime();
double res = sum_omp_fixed_depth(v, 0, N - 1);
t = wtime() - t;
printf("Result (parallel): %.4f; error %.12f\n", res, fabs(res - (1.0 + N) / 2.0 * N));
free(v);
return t;
}
int main(int argc, char **argv)
{
printf("Recursive summation N = %d\n", N);
double tserial = run_serial();
double tparallel = run_parallel();
printf("Execution time (serial): %.6f\n", tserial);
printf("Execution time (parallel): %.6f\n", tparallel);
printf("Speedup: %.2f\n", tserial / tparallel);
return 0;
}
|
bml_allocate_dense_typed.c | #include "../../macros.h"
#include "../../typed.h"
#include "../bml_allocate.h"
#include "../bml_logger.h"
#include "../bml_types.h"
#include "bml_allocate_dense.h"
#include "bml_types_dense.h"
#include "bml_utilities_dense.h"
#ifdef BML_USE_MAGMA
#include "magma_v2.h"
#endif
#include <complex.h>
#include <string.h>
#include <stdio.h>
#ifdef _OPENMP
#include <omp.h>
#endif
/** Clear the matrix.
*
* All values are zeroed.
*
* \ingroup allocate_group
*
* \param A The matrix.
*/
void TYPED_FUNC(
bml_clear_dense) (
bml_matrix_dense_t * A)
{
#ifdef BML_USE_MAGMA
MAGMA_T zero = MAGMACOMPLEX(MAKE) (0., 0.);
MAGMABLAS(laset) (MagmaFull, A->N, A->N, zero, zero, A->matrix, A->ld,
bml_queue());
#else
memset(A->matrix, 0.0, A->N * A->ld * sizeof(REAL_T));
#endif
}
/** Allocate the zero matrix.
*
* Note that the matrix \f$ a \f$ will be newly allocated. If it is
* already allocated then the matrix will be deallocated in the
* process.
*
* \ingroup allocate_group
*
* \param matrix_dimension The matrix size.
* \param distrib_mode The distribution mode.
* \return The matrix.
*/
bml_matrix_dense_t *TYPED_FUNC(
bml_zero_matrix_dense) (
bml_matrix_dimension_t matrix_dimension,
bml_distribution_mode_t distrib_mode)
{
bml_matrix_dense_t *A = NULL;
A = bml_allocate_memory(sizeof(bml_matrix_dense_t));
A->matrix_type = dense;
A->matrix_precision = MATRIX_PRECISION;
A->N = matrix_dimension.N_rows;
A->distribution_mode = distrib_mode;
#ifdef BML_USE_MAGMA
A->ld = magma_roundup(matrix_dimension.N_rows, 32);
int device;
magma_getdevice(&device);
bml_queue_create(device);
magma_int_t ret = MAGMA(malloc) ((MAGMA_T **) & A->matrix,
A->ld * matrix_dimension.N_rows);
assert(ret == MAGMA_SUCCESS);
bml_clear_dense(A);
#else
A->ld = matrix_dimension.N_rows;
A->matrix =
bml_allocate_memory(sizeof(REAL_T) * matrix_dimension.N_rows *
matrix_dimension.N_rows);
#endif
A->domain =
bml_default_domain(matrix_dimension.N_rows, matrix_dimension.N_rows,
distrib_mode);
A->domain2 =
bml_default_domain(matrix_dimension.N_rows, matrix_dimension.N_rows,
distrib_mode);
return A;
}
/** Allocate a banded matrix.
*
* Note that the matrix \f$ a \f$ will be newly allocated. If it is
* already allocated then the matrix will be deallocated in the
* process.
*
* \ingroup allocate_group
*
* \param N The matrix size.
* \param M The bandwidth (the number of non-zero elements per row).
* \param distrib_mode The distribution mode.
* \return The matrix.
*/
bml_matrix_dense_t *TYPED_FUNC(
bml_banded_matrix_dense) (
int N,
int M,
bml_distribution_mode_t distrib_mode)
{
bml_matrix_dimension_t matrix_dimension = { N, N, M };
bml_matrix_dense_t *A =
TYPED_FUNC(bml_zero_matrix_dense) (matrix_dimension, distrib_mode);
#ifdef BML_USE_MAGMA
MAGMA_T *A_dense = bml_allocate_memory(N * N * sizeof(REAL_T));
#else
REAL_T *A_dense = A->matrix;
#endif
#pragma omp parallel for shared(A_dense)
for (int i = 0; i < N; i++)
{
for (int j = (i - M / 2 >= 0 ? i - M / 2 : 0);
j < (i - M / 2 + M <= N ? i - M / 2 + M : N); j++)
{
#ifdef BML_USE_MAGMA
A_dense[ROWMAJOR(i, j, N, N)] =
MAGMACOMPLEX(MAKE) (rand() / (double) RAND_MAX, 0.);
#else
A_dense[ROWMAJOR(i, j, N, N)] = rand() / (double) RAND_MAX;
#endif
}
}
#ifdef BML_USE_MAGMA
MAGMA(setmatrix) (N, N, A_dense, N, A->matrix, A->ld, bml_queue());
bml_free_memory(A_dense);
#endif
return A;
}
/** Allocate a random matrix.
*
* Note that the matrix \f$ a \f$ will be newly allocated. If it is
* already allocated then the matrix will be deallocated in the
* process.
*
* \ingroup allocate_group
*
* \param N The matrix size.
* \param distrib_mode The distribution mode.
* \return The matrix.
*
* Note: Do not use OpenMP when setting values for a random matrix,
* this makes the operation non-repeatable.
*/
bml_matrix_dense_t *TYPED_FUNC(
bml_random_matrix_dense) (
int N,
bml_distribution_mode_t distrib_mode)
{
bml_matrix_dimension_t matrix_dimension = { N, N, N };
bml_matrix_dense_t *A =
TYPED_FUNC(bml_zero_matrix_dense) (matrix_dimension, distrib_mode);
#ifdef BML_USE_MAGMA
MAGMA_T *A_dense = bml_noinit_allocate_memory(N * N * sizeof(REAL_T));
#else
REAL_T *A_dense = A->matrix;
#endif
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
#ifdef BML_USE_MAGMA
A_dense[ROWMAJOR(i, j, N, N)] =
MAGMACOMPLEX(MAKE) (rand() / (double) RAND_MAX, 0.);
#else
A_dense[ROWMAJOR(i, j, N, N)] = rand() / (double) RAND_MAX;
#endif
}
}
#ifdef BML_USE_MAGMA
MAGMA(setmatrix) (N, N, A_dense, N, A->matrix, A->ld, bml_queue());
bml_free_memory(A_dense);
#endif
return A;
}
/** Allocate the identity matrix.
*
* Note that the matrix \f$ a \f$ will be newly allocated. If it is
* already allocated then the matrix will be deallocated in the
* process.
*
* \ingroup allocate_group
*
* \param N The matrix size.
* \param distrib_mode The distribution mode.
* \return The matrix.
*/
bml_matrix_dense_t *TYPED_FUNC(
bml_identity_matrix_dense) (
int N,
bml_distribution_mode_t distrib_mode)
{
bml_matrix_dimension_t matrix_dimension = { N, N, N };
bml_matrix_dense_t *A =
TYPED_FUNC(bml_zero_matrix_dense) (matrix_dimension, distrib_mode);
#ifdef BML_USE_MAGMA
MAGMA_T *A_dense = bml_allocate_memory(N * N * sizeof(REAL_T));
#else
REAL_T *A_dense = A->matrix;
#endif
#pragma omp parallel for shared(A_dense)
for (int i = 0; i < N; i++)
{
#ifdef BML_USE_MAGMA
A_dense[ROWMAJOR(i, i, N, N)] = MAGMACOMPLEX(MAKE) (1, 0);
#else
A_dense[ROWMAJOR(i, i, N, N)] = 1;
#endif
}
#ifdef BML_USE_MAGMA
MAGMA(setmatrix) (N, N, A_dense, N, A->matrix, A->ld, bml_queue());
bml_free_memory(A_dense);
#endif
return A;
}
|
palshop_fmt_plug.c | /* This format is reverse engineered from InsidePro Hash Manager!
*
* This software is Copyright (c) 2016, Dhiru Kholia <dhiru.kholia at gmail.com>,
* and it is hereby released to the general public under the following terms:
* Redistribution and use in source and binary forms, with or without modification,
* are permitted.
*
* improved speed, JimF. Reduced amount of hex encoding.
*/
#if FMT_EXTERNS_H
extern struct fmt_main fmt_palshop;
#elif FMT_REGISTERS_H
john_register_one(&fmt_palshop);
#else
#include "arch.h"
#include "sha.h"
#include "md5.h"
#include <string.h>
#include "misc.h"
#include "common.h"
#include "formats.h"
#include "params.h"
#include "options.h"
#include "base64_convert.h"
#ifdef _OPENMP
#include <omp.h>
#ifndef OMP_SCALE
#define OMP_SCALE 1024
#endif
#endif
#include "memdbg.h"
#define FORMAT_LABEL "Palshop"
#define FORMAT_NAME "MD5(Palshop)"
#define ALGORITHM_NAME "MD5 + SHA1 32/" ARCH_BITS_STR
#define BENCHMARK_COMMENT ""
#define BENCHMARK_LENGTH -1
#define PLAINTEXT_LENGTH 125
#define BINARY_SIZE 10 /* 20 characters of "m2", now 10 binary bytes. */
#define CIPHERTEXT_LENGTH 51
#define SALT_SIZE 0
#define BINARY_ALIGN sizeof(uint32_t)
#define SALT_ALIGN sizeof(int)
#define MIN_KEYS_PER_CRYPT 1
#define MAX_KEYS_PER_CRYPT 1
#define FORMAT_TAG "$palshop$"
#define TAG_LENGTH (sizeof(FORMAT_TAG) - 1)
static struct fmt_tests palshop_tests[] = {
{"$palshop$68b11ee90ed17ef14aa0f51af494c2c63ad7d281a9888cb593e", "123"},
{"ea3a8d0f4cd9e5e22ccede1ad59dd2c5c7e839348a8a519d505", "ABC"},
// http://leopard.500mb.net/HashGenerator/
{"$palshop$f2e3babc50b316e6e886f3062a37cead6d1bd16dd2bed49f7bc", "long password"},
{NULL}
};
static char (*saved_key)[PLAINTEXT_LENGTH + 1];
static uint32_t (*crypt_out)[ (BINARY_SIZE+sizeof(uint32_t)-1) / sizeof(uint32_t)];
static size_t *saved_len;
static void init(struct fmt_main *self)
{
#ifdef _OPENMP
static int omp_t = 1;
omp_t = omp_get_max_threads();
self->params.min_keys_per_crypt *= omp_t;
omp_t *= OMP_SCALE;
self->params.max_keys_per_crypt *= omp_t;
#endif
saved_key = mem_calloc(self->params.max_keys_per_crypt,
sizeof(*saved_key));
crypt_out = mem_calloc(self->params.max_keys_per_crypt,
sizeof(*crypt_out));
saved_len = mem_calloc(self->params.max_keys_per_crypt,
sizeof(*saved_len));
}
static void done(void)
{
MEM_FREE(saved_len);
MEM_FREE(crypt_out);
MEM_FREE(saved_key);
}
static int valid(char *ciphertext, struct fmt_main *self)
{
char *p = ciphertext;
if (!strncmp(ciphertext, FORMAT_TAG, TAG_LENGTH))
p = ciphertext + TAG_LENGTH;
if (!p)
return 0;
if (!ishex_oddOK(p))
return 0;
if (strlen(p) != CIPHERTEXT_LENGTH)
return 0;
return 1;
}
static char *split(char *ciphertext, int index, struct fmt_main *self)
{
static char out[TAG_LENGTH + CIPHERTEXT_LENGTH + 1];
if (!strncmp(ciphertext, FORMAT_TAG, TAG_LENGTH))
return ciphertext;
strcpy(out, FORMAT_TAG);
strcpy(&out[TAG_LENGTH], ciphertext);
return out;
}
static void *get_binary(char *ciphertext)
{
static union {
unsigned char c[BINARY_SIZE+1];
ARCH_WORD dummy;
} buf;
unsigned char *out = buf.c;
char *p = ciphertext + TAG_LENGTH;
++p; // skip the first 'nibble'. Take next 10 bytes.
base64_convert(p, e_b64_hex, 20, out, e_b64_raw, 10, 0, 0);
return out;
}
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 int crypt_all(int *pcount, struct db_salt *salt)
{
const int count = *pcount;
int index = 0;
#ifdef _OPENMP
#pragma omp parallel for
#endif
for (index = 0; index < count; index++)
{
unsigned char m1[53], buffer[16+20], *cp;
int i;
MD5_CTX mctx;
SHA_CTX sctx;
// m1 = md5($p)
MD5_Init(&mctx);
MD5_Update(&mctx, saved_key[index], saved_len[index]);
MD5_Final(buffer, &mctx);
// s1 = sha1($p)
SHA1_Init(&sctx);
SHA1_Update(&sctx, saved_key[index], saved_len[index]);
SHA1_Final(buffer+16, &sctx);
// data = m1[11:] + s1[:29] + m1[0:1] // 51 bytes!
cp = m1;
*cp++ = itoa16[buffer[5]&0xF];
for (i = 6; i < 25+6; ++i) {
cp[0] = itoa16[buffer[i]>>4];
cp[1] = itoa16[buffer[i]&0xF];
cp += 2;
}
cp[-1] = itoa16[buffer[0]>>4];
// m2
MD5_Init(&mctx);
MD5_Update(&mctx, m1, 51);
MD5_Final(buffer, &mctx);
// s2 = sha1(data)
// SHA1_Init(&sctx);
// SHA1_Update(&sctx, data, 51);
// SHA1_Final((unsigned char*)crypt_out[index], &sctx);
// hex_encode((unsigned char*)crypt_out[index], 20, s1);
// hash = m2[11:] + s2[:29] + m2[0], but starting 20 bytes should be enough!
//memcpy((unsigned char*)crypt_out[index], m2 + 11, 20);
// we actually take m2[12:32] (skipping that first 'odd' byte.0
// in binary now, skipping the unneeded hex conversion.
memcpy((unsigned char*)crypt_out[index], buffer+6, 10);
}
return count;
}
static int cmp_all(void *binary, int count)
{
int index = 0;
for (; index < count; index++)
if (*((uint32_t*)binary) == crypt_out[index][0])
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 palshop_set_key(char *key, int index)
{
saved_len[index] =
strnzcpyn(saved_key[index], key, sizeof(saved_key[index]));
}
static char *get_key(int index)
{
return saved_key[index];
}
struct fmt_main fmt_palshop = {
{
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,
#if FMT_MAIN_VERSION > 11
{ NULL },
#endif
{ FORMAT_TAG },
palshop_tests
}, {
init,
done,
fmt_default_reset,
fmt_default_prepare,
valid,
split,
get_binary,
fmt_default_salt,
#if FMT_MAIN_VERSION > 11
{ NULL },
#endif
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,
fmt_default_set_salt,
palshop_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 */
|
GB_binop__bshift_int64.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__bshift_int64)
// A.*B function (eWiseMult): GB (_AemultB_08__bshift_int64)
// A.*B function (eWiseMult): GB (_AemultB_02__bshift_int64)
// A.*B function (eWiseMult): GB (_AemultB_04__bshift_int64)
// A.*B function (eWiseMult): GB (_AemultB_bitmap__bshift_int64)
// A*D function (colscale): GB ((none))
// D*A function (rowscale): GB ((none))
// C+=B function (dense accum): GB (_Cdense_accumB__bshift_int64)
// C+=b function (dense accum): GB (_Cdense_accumb__bshift_int64)
// C+=A+B function (dense ewise3): GB ((none))
// C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__bshift_int64)
// C=scalar+B GB (_bind1st__bshift_int64)
// C=scalar+B' GB (_bind1st_tran__bshift_int64)
// C=A+scalar GB (_bind2nd__bshift_int64)
// C=A'+scalar GB (_bind2nd_tran__bshift_int64)
// C type: int64_t
// A type: int64_t
// A pattern? 0
// B type: int8_t
// B pattern? 0
// BinaryOp: cij = GB_bitshift_int64 (aij, bij)
#define GB_ATYPE \
int64_t
#define GB_BTYPE \
int8_t
#define GB_CTYPE \
int64_t
// true if the types of A and B are identical
#define GB_ATYPE_IS_BTYPE \
0
// 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 \
0
// 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) \
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) \
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 = GB_bitshift_int64 (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_BSHIFT || GxB_NO_INT64 || GxB_NO_BSHIFT_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__bshift_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__bshift_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__bshift_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 int8_t
int8_t bwork = (*((int8_t *) p_bwork)) ;
#include "GB_dense_subassign_22_template.c"
return (GrB_SUCCESS) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = A*D, column scale with diagonal D matrix
//------------------------------------------------------------------------------
#if 0
GrB_Info GB ((none))
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix D,
const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t *restrict Cx = (int64_t *) C->x ;
#include "GB_AxB_colscale_template.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
//------------------------------------------------------------------------------
// C = D*B, row scale with diagonal D matrix
//------------------------------------------------------------------------------
#if 0
GrB_Info GB ((none))
(
GrB_Matrix C,
const GrB_Matrix D,
const GrB_Matrix B,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t *restrict Cx = (int64_t *) C->x ;
#include "GB_AxB_rowscale_template.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
//------------------------------------------------------------------------------
// eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B
//------------------------------------------------------------------------------
GrB_Info GB (_AaddB__bshift_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 ;
int8_t beta_scalar ;
if (is_eWiseUnion)
{
alpha_scalar = (*((int64_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__bshift_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__bshift_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__bshift_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__bshift_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__bshift_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)) ;
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] = GB_bitshift_int64 (x, bij) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd
//------------------------------------------------------------------------------
GrB_Info GB (_bind2nd__bshift_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 ;
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 ;
int64_t aij = GBX (Ax, p, false) ;
Cx [p] = GB_bitshift_int64 (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] = GB_bitshift_int64 (x, aij) ; \
}
GrB_Info GB (_bind1st_tran__bshift_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 \
int8_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] = GB_bitshift_int64 (aij, y) ; \
}
GrB_Info GB (_bind2nd_tran__bshift_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
int8_t y = (*((const int8_t *) y_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
pcptdesdecryptecbcaomp.c | /*******************************************************************************
* Copyright 2002-2018 Intel Corporation
* All Rights Reserved.
*
* If this software was obtained under the Intel Simplified Software License,
* the following terms apply:
*
* The source code, information and material ("Material") contained herein is
* owned by Intel Corporation or its suppliers or licensors, and title to such
* Material remains with Intel Corporation or its suppliers or licensors. The
* Material contains proprietary information of Intel or its suppliers and
* licensors. The Material is protected by worldwide copyright laws and treaty
* provisions. No part of the Material may be used, copied, reproduced,
* modified, published, uploaded, posted, transmitted, distributed or disclosed
* in any way without Intel's prior express written permission. No license under
* any patent, copyright or other intellectual property rights in the Material
* is granted to or conferred upon you, either expressly, by implication,
* inducement, estoppel or otherwise. Any license under such intellectual
* property rights must be express and approved by Intel in writing.
*
* Unless otherwise agreed by Intel in writing, you may not remove or alter this
* notice or any other notice embedded in Materials by Intel or Intel's
* suppliers or licensors in any way.
*
*
* If this software was obtained under the Apache License, Version 2.0 (the
* "License"), the following terms apply:
*
* 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.
*******************************************************************************/
/*
// Name:
// ippsTDESDecryptECB
//
// Purpose:
// Cryptography Primitives.
// Decrypt byte data stream according to TDES.
//
//
*/
#include "owndefs.h"
#if defined ( _OPENMP )
#include "owncp.h"
#include "pcpdes.h"
#include "pcptool.h"
#include "omp.h"
/*F*
// Name:
// ippsTDESDecryptECB
//
// Purpose:
// Decrypt byte data stream according to TDES in EBC mode.
//
// Returns:
// ippStsNoErr No errors, it's OK.
// ippStsNullPtrErr ( pCtx1 == NULL ) || ( pCtx2 == NULL ) ||
// ( pCtx3 == NULL ) || ( pSrc == NULL ) ||
// ( pDst == NULL )
// ippStsLengthErr srcLen < 1
// ippStsContextMatchErr ( pCtx1->idCtx != idCtxDES ) ||
// ( pCtx2->idCtx != idCtxDES ) ||
// ( pCtx3->idCtx != idCtxDES )
// ippStsUnderRunErr srcLen % 8
//
// Parameters:
// pSrc Pointer to the input ciphertext byte data stream.
// pDst Pointer to the output plaintext byte data stream.
// srcLen Ciphertext data stream length in bytes.
// pCtx1 Pointer to the IppsDESSpec context.
// pCtx2 Pointer to the IppsDESSpec context.
// pCtx3 Pointer to the IppsDESSpec context.
// padding Padding scheme indicator
*F*/
static
void TDES_DecECB_processing(const Ipp8u* pSrc, Ipp8u* pDst, int nBlocks,
const RoundKeyDES* pRKey[3])
{
/*
// decrypt block-by-block aligned streams
*/
if( !(IPP_UINT_PTR(pSrc) & 0x7) && !(IPP_UINT_PTR(pDst) & 0x7)) {
ECB_TDES((const Ipp64u*)pSrc, (Ipp64u*)pDst, nBlocks, pRKey, DESspbox);
}
/*
// decrypt block-by-block misaligned streams
*/
else {
Ipp64u block;
while(nBlocks) {
CopyBlock8(pSrc, &block);
block = Cipher_DES(block, pRKey[0], DESspbox);
block = Cipher_DES(block, pRKey[1], DESspbox);
block = Cipher_DES(block, pRKey[2], DESspbox);
CopyBlock8(&block, pDst);
pSrc += MBS_DES;
pDst += MBS_DES;
nBlocks--;
}
}
}
IPPFUN(IppStatus, ippsTDESDecryptECB,(const Ipp8u* pSrc, Ipp8u* pDst, int srcLen,
const IppsDESSpec* pCtx1,
const IppsDESSpec* pCtx2,
const IppsDESSpec* pCtx3,
IppsPadding padding))
{
/* test the pointers */
IPP_BAD_PTR2_RET(pSrc, pDst);
IPP_BAD_PTR3_RET(pCtx1, pCtx2, pCtx3);
/* align the contexts */
pCtx1 = (IppsDESSpec*)(IPP_ALIGNED_PTR(pCtx1, DES_ALIGNMENT));
pCtx2 = (IppsDESSpec*)(IPP_ALIGNED_PTR(pCtx2, DES_ALIGNMENT));
pCtx3 = (IppsDESSpec*)(IPP_ALIGNED_PTR(pCtx3, DES_ALIGNMENT));
/* test the contexts */
IPP_BADARG_RET(!DES_ID_TEST(pCtx1), ippStsContextMatchErr);
IPP_BADARG_RET(!DES_ID_TEST(pCtx2), ippStsContextMatchErr);
IPP_BADARG_RET(!DES_ID_TEST(pCtx3), ippStsContextMatchErr);
/* test the data stream length */
IPP_BADARG_RET((srcLen<1), ippStsLengthErr);
/* test the data stream integrity */
IPP_BADARG_RET((srcLen&(MBS_DES-1)), ippStsUnderRunErr);
UNREFERENCED_PARAMETER(padding);
{
int nBlocks = srcLen / MBS_DES;
int nThreads = IPP_MIN(IPPCP_GET_NUM_THREADS(), IPP_MAX(nBlocks/TDES_MIN_BLK_PER_THREAD, 1));
const RoundKeyDES* pRKey[3];
pRKey[0] = DES_DKEYS(pCtx3);
pRKey[1] = DES_EKEYS(pCtx2);
pRKey[2] = DES_DKEYS(pCtx1);
if(1==nThreads)
TDES_DecECB_processing(pSrc, pDst, nBlocks, pRKey);
else {
int blksThreadReg;
int blksThreadTail;
#pragma omp parallel IPPCP_OMP_LIMIT_MAX_NUM_THREADS(nThreads)
{
#pragma omp master
{
nThreads = omp_get_num_threads();
blksThreadReg = nBlocks / nThreads;
blksThreadTail = blksThreadReg + nBlocks % nThreads;
}
#pragma omp barrier
{
int id = omp_get_thread_num();
Ipp8u* pThreadSrc = (Ipp8u*)pSrc + id*blksThreadReg * MBS_DES;
Ipp8u* pThreadDst = (Ipp8u*)pDst + id*blksThreadReg * MBS_DES;
int blkThread = (id==(nThreads-1))? blksThreadTail : blksThreadReg;
TDES_DecECB_processing(pThreadSrc, pThreadDst, blkThread, pRKey);
}
}
}
return ippStsNoErr;
}
}
#endif /* #ifdef _OPENMP */
|
sw3d_tstile.h | void sw_tstile(){
printf("- traco tstile [1x16x16x16] - \n\n");
int c0,c1,c2,c3,c4,c5,c6,c7,c8,c9,c11,c10,c12,c13,c14,c15;
// spaces 3, 1x16x16x16
for( c0 = 0; c0 < N + floord(N - 1, 8); c0 += 1)
#pragma omp parallel for schedule(dynamic, 1) shared(c0,N) private(c1,c2,c3,c4,c5,c6,c7,c8,c9,c11,c10,c12,c13,c14,c15)
for( c1 = max(0, c0 - (N + 7) / 8 + 1); c1 <= min(N - 1, c0); c1 += 1)
for( c2 = max(0, c0 - c1 - (N + 15) / 16 + 1); c2 <= min(c0 - c1, (N - 1) / 16); c2 += 1) {
for( c4 = 16 * c0 - 16 * c1 + 2; c4 <= min(min(min(min(2 * N, 16 * c0 - 15 * c1 + 2), 16 * c0 - 16 * c1 + 32), N + 16 * c2 + 16), N + 16 * c0 - 16 * c1 - 16 * c2 + 16); c4 += 1)
for( c9 = max(max(16 * c2 + 1, -16 * c0 + 16 * c1 + 16 * c2 + c4 - 16), -N + c4); c9 <= min(min(N, 16 * c2 + 16), -16 * c0 + 16 * c1 + 16 * c2 + c4 - 1); c9 += 1) {
m1[(c1+1)][c9][(c4-c9)] = INT_MIN;
m2[(c1+1)][c9][(c4-c9)] = INT_MIN;
m3[(c1+1)][c9][(c4-c9)] = INT_MIN;
m6[(c1+1)][c9][(c4-c9)] = INT_MIN;
}
for( c4 = 16 * c0 - 15 * c1 + 3; c4 <= min(min(min(min(2 * N + c1 + 1, 16 * c0 - 15 * c1 + 33), 16 * c0 - 15 * c1 + 16 * c2 + 3), N + c1 + 16 * c2 + 17), N + 16 * c0 - 15 * c1 - 16 * c2 + 17); c4 += 1) {
if (16 * c0 >= 17 * c1 + 16 * c2 + 2)
for( c9 = max(max(16 * c2 + 1, -16 * c0 + 16 * c1 + 16 * c2 + c4 - 16), -N + c4); c9 <= min(min(N, 16 * c2 + 16), -16 * c0 + 16 * c1 + 16 * c2 + c4 - 1); c9 += 1) {
m1[(c1+1)][c9][(c4-c9)] = INT_MIN;
m2[(c1+1)][c9][(c4-c9)] = INT_MIN;
m3[(c1+1)][c9][(c4-c9)] = INT_MIN;
m6[(c1+1)][c9][(c4-c9)] = INT_MIN;
}
for( c5 = max(max(c0 - c1 - c2, floord(-N - c1 + c4 - 1, 16)), -c2 + (-c1 + c4 - 1) / 16 - 1); c5 <= min(N / 16, -c2 + (-c1 + c4 - 2) / 16); c5 += 1) {
for( c9 = max(max(max(16 * c2 + 1, -16 * c0 + 15 * c1 + 16 * c2 + c4 - 17), -N - c1 + c4 - 1), -c1 + c4 - 16 * c5 - 16); c9 <= min(min(min(N, 16 * c2 + 16), -16 * c0 + 15 * c1 + 16 * c2 + c4 - 2), -c1 + c4 - 16 * c5 - 1); c9 += 1) {
m4[(c1+1)][c9][(-c1+c4-c9-1)] = INT_MIN;
if (c1 + c2 == c0 && c5 == 0 && N + c9 >= c4 && c9 + 16 >= c4) {
m1[(c1+1)][c9][(c4-c9)] = INT_MIN;
m2[(c1+1)][c9][(c4-c9)] = INT_MIN;
m3[(c1+1)][c9][(c4-c9)] = INT_MIN;
m6[(c1+1)][c9][(c4-c9)] = INT_MIN;
}
}
if (17 * c1 + 16 * c2 + 1 >= 16 * c0 && 16 * c0 + 14 >= 17 * c1 + 16 * c2)
for( c9 = max(max(-16 * c0 + 16 * c1 + 16 * c2 + c4 - 16, -16 * c0 + 15 * c1 + 16 * c2 + c4 - 1), -N + c4); c9 <= min(min(N, 16 * c2 + 16), -16 * c0 + 16 * c1 + 16 * c2 + c4 - 1); c9 += 1) {
m1[(c1+1)][c9][(c4-c9)] = INT_MIN;
m2[(c1+1)][c9][(c4-c9)] = INT_MIN;
m3[(c1+1)][c9][(c4-c9)] = INT_MIN;
m6[(c1+1)][c9][(c4-c9)] = INT_MIN;
}
}
if (c1 >= 15 && c1 + c2 == c0)
for( c9 = c4 - 16; c9 <= min(N, 16 * c0 - 16 * c1 + 16); c9 += 1) {
m1[(c1+1)][c9][(c4-c9)] = INT_MIN;
m2[(c1+1)][c9][(c4-c9)] = INT_MIN;
m3[(c1+1)][c9][(c4-c9)] = INT_MIN;
m6[(c1+1)][c9][(c4-c9)] = INT_MIN;
}
}
for( c4 = 16 * c0 - 15 * c1 + 16 * c2 + 4; c4 <= min(min(min(min(3 * N + c1 + 1, 2 * N + 16 * c0 - 15 * c1 + 2), 2 * N + 16 * c0 - 15 * c1 - 16 * c2 + 17), N + c1 + 32 * c2 + 33), 16 * c0 - 15 * c1 + 16 * c2 + 49); c4 += 1) {
for( c5 = max(max(c0 - c1 - c2, floord(-2 * N - c1 + c4 - 1, 16)), -2 * c2 + (-c1 + c4 - 1) / 16 - 2); c5 <= min(min(c0 - c1 - c2 + 1, (c1 + 1) / 16 - 1), -2 * c2 + (-c1 + c4 - 3) / 16); c5 += 1) {
for( c9 = max(max(16 * c2 + 1, -8 * c0 + 7 * c1 + 8 * c2 + (c1 + c4) / 2 - 8), -c1 - 8 * c5 + (c1 + c4 + 1) / 2 - 8); c9 <= min(min(min(N, 16 * c2 + 16), -8 * c0 + 7 * c1 + 8 * c2 + (c1 + c4) / 2 - 1), -c1 - 8 * c5 + (c1 + c4 + 1) / 2 - 1); c9 += 1) {
m5[(c1+1)][c9][(-c1+c4-2*c9-1)] = INT_MIN;
if (c2 == 0 && c1 + c5 == c0 && 16 * c0 + c9 + 16 >= 15 * c1 + c4)
m4[(c1+1)][c9][(-c1+c4-c9-1)] = INT_MIN;
}
if (c2 == 0 && 16 * c0 + 32 >= 15 * c1 + c4 && c1 + c5 == c0 + 1)
m4[(c1+1)][(-16*c0+15*c1+c4-17)][(16*c0-16*c1+16)] = INT_MIN;
for( c9 = max(max(-16 * c0 + 15 * c1 + 16 * c2 + c4 - 17, -c1 + c4 - 16 * c5 - 16), -8 * c0 + 7 * c1 + 8 * c2 + (c1 + c4) / 2); c9 <= min(min(min(N, 16 * c2 + 16), -16 * c0 + 15 * c1 + 16 * c2 + c4 - 2), -c1 + c4 - 16 * c5 - 1); c9 += 1)
m4[(c1+1)][c9][(-c1+c4-c9-1)] = INT_MIN;
}
if (17 * c1 + 16 * c2 >= 16 * c0 + 15 && 16 * c0 + 30 >= 17 * c1 + 16 * c2 && 15 * c1 + c4 >= 16 * c0 + 18 && N + 16 * c0 + 17 >= 15 * c1 + 16 * c2 + c4 && 16 * c0 + 16 * c2 + 18 >= 15 * c1 + c4 && 16 * c0 + 33 >= 15 * c1 + c4) {
m4[(c1+1)][(-16*c0+15*c1+16*c2+c4-17)][(16*c0-16*c1-16*c2+16)] = INT_MIN;
} else if (17 * c1 + 16 * c2 >= 16 * c0 + 31 && 15 * c1 + c4 >= 16 * c0 + 18 && 16 * c0 + 16 * c2 + 18 >= 15 * c1 + c4 && 16 * c0 + 33 >= 15 * c1 + c4) {
m4[(c1+1)][(-16*c0+15*c1+16*c2+c4-17)][(16*c0-16*c1-16*c2+16)] = INT_MIN;
} else if (17 * c1 + 16 * c2 + 1 >= 16 * c0 && 16 * c0 + 30 >= 17 * c1 + 16 * c2 && 16 * c1 + c4 >= 16 * c0 + 33 && ((c1 + 1) % 16) + c4 >= 2 * c1 + 32 * c2 + 4 && 2 * N + 2 * c1 + 17 >= ((c1 + 1) % 16) + c4 && 2 * c1 + 32 * c2 + 49 >= ((c1 + 1) % 16) + c4) {
for( c9 = max(max(max(16 * c2 + 1, -8 * c0 + 7 * c1 + 8 * c2 + (c1 + c4) / 2 - 8), -N - c1 + (N + c1 + c4) / 2), -c1 - 8 * ((c1 + 1) / 16) + (c1 + c4 + 1) / 2 - 8); c9 <= min(min(min(N, 16 * c2 + 16), -8 * c0 + 7 * c1 + 8 * c2 + (c1 + c4) / 2 - 1), -c1 - 8 * ((c1 + 1) / 16) + (c1 + c4 + 1) / 2 - 1); c9 += 1) {
m5[(c1+1)][c9][(-c1+c4-2*c9-1)] = INT_MIN;
if (c2 == 0 && N + c1 + c9 + 1 >= c4 && 16 * c0 + c9 + 16 >= 15 * c1 + c4)
m4[(c1+1)][c9][(-c1+c4-c9-1)] = INT_MIN;
}
if (17 * c1 >= 16 * c0 + 15 && c2 == 0 && 16 * c0 + 32 >= 15 * c1 + c4)
m4[(c1+1)][(-16*c0+15*c1+c4-17)][(16*c0-16*c1+16)] = INT_MIN;
for( c9 = max(max(max(-16 * c0 + 15 * c1 + 16 * c2 + c4 - 17, -N - c1 + c4 - 1), ((c1 + 1) % 16) - 2 * c1 + c4 - 17), -8 * c0 + 7 * c1 + 8 * c2 + (c1 + c4) / 2); c9 <= min(min(min(N, 16 * c2 + 16), -16 * c0 + 15 * c1 + 16 * c2 + c4 - 2), ((c1 + 1) % 16) - 2 * c1 + c4 - 2); c9 += 1)
m4[(c1+1)][c9][(-c1+c4-c9-1)] = INT_MIN;
} else if (c1 + 1 == c0 && c2 == 1 && c4 >= N + 17 && c4 <= 48) {
for( c9 = 17; c9 <= min(N, -c0 + (c0 + c4 + 1) / 2 - 1); c9 += 1)
m5[c0][c9][(-c0+c4-2*c9)] = INT_MIN;
for( c9 = -c0 + c4 - 15; c9 <= N; c9 += 1)
m4[c0][c9][(-c0+c4-c9)] = INT_MIN;
} else if (2 * N >= c4 && N + 16 * c2 + 16 >= c4 && N + 16 * c0 + 16 >= 16 * c1 + 16 * c2 + c4 && 16 * c0 + 32 >= 16 * c1 + c4) {
if (17 * c1 + 16 * c2 + 1 >= 16 * c0 && 16 * c0 + 14 >= 17 * c1 + 16 * c2) {
for( c9 = max(max(16 * c2 + 1, -N - c1 + (N + c1 + c4) / 2), -8 * c0 + 7 * c1 + 8 * c2 + (c1 + c4 + 1) / 2 - 8); c9 < min(-16 * c0 + 16 * c1 + 16 * c2 + c4 - 16, -8 * c0 + 7 * c1 + 8 * c2 + (c1 + c4) / 2); c9 += 1) {
m5[(c1+1)][c9][(-c1+c4-2*c9-1)] = INT_MIN;
if (c2 == 0 && N + c1 + c9 + 1 >= c4 && 16 * c0 + c9 + 16 >= 15 * c1 + c4)
m4[(c1+1)][c9][(-c1+c4-c9-1)] = INT_MIN;
}
for( c9 = max(-16 * c0 + 15 * c1 + 16 * c2 + c4 - 16, -8 * c0 + 7 * c1 + 8 * c2 + (c1 + c4) / 2); c9 < min(-16 * c0 + 16 * c1 + 16 * c2 + c4 - 16, -16 * c0 + 15 * c1 + 16 * c2 + c4 - 1); c9 += 1)
m4[(c1+1)][c9][(-c1+c4-c9-1)] = INT_MIN;
}
for( c9 = max(max(1, c4 - 16), -N - c0 + (N + c0 + c4) / 2); c9 < min(-N + c4, -c0 + (c0 + c4) / 2); c9 += 1) {
m5[(c0+1)][c9][(-c0+c4-2*c9-1)] = INT_MIN;
if (N + c0 + c9 + 1 >= c4)
m4[(c0+1)][c9][(-c0+c4-c9-1)] = INT_MIN;
}
for( c9 = max(c4 - 16, -c0 + (c0 + c4) / 2); c9 < -N + c4; c9 += 1)
m4[(c0+1)][c9][(-c0+c4-c9-1)] = INT_MIN;
for( c9 = max(max(16 * c2 + 1, -16 * c0 + 16 * c1 + 16 * c2 + c4 - 16), -N + c4); c9 <= min(min(N, 16 * c2 + 16), -16 * c0 + 16 * c1 + 16 * c2 + c4 - 1); c9 += 1) {
if (c1 == c0 && c2 == 0 && c4 >= c0 + 2 * c9 + 2)
m5[(c0+1)][c9][(-c0+c4-2*c9-1)] = INT_MIN;
if (c1 + c2 == c0 && c4 >= c1 + c9 + 2)
m4[(c1+1)][c9][(-c1+c4-c9-1)] = INT_MIN;
m1[(c1+1)][c9][(c4-c9)] = INT_MIN;
m2[(c1+1)][c9][(c4-c9)] = INT_MIN;
m3[(c1+1)][c9][(c4-c9)] = INT_MIN;
m6[(c1+1)][c9][(c4-c9)] = INT_MIN;
}
}
for( c5 = max(max(max(c0 - c1 - c2, (c1 + 1) / 16 + 1), floord(-2 * N - c1 + c4 - 1, 16)), -2 * c2 + (-c1 + c4 - 1) / 16 - 2); c5 <= min(min(c0 - c1 - c2 + 1, N / 16), -2 * c2 + (-c1 + c4 - 3) / 16); c5 += 1) {
for( c9 = max(max(max(16 * c2 + 1, -8 * c0 + 7 * c1 + 8 * c2 + (c1 + c4) / 2 - 8), -N - c1 + (N + c1 + c4) / 2), -c1 - 8 * c5 + (c1 + c4 + 1) / 2 - 8); c9 <= min(min(min(N, 16 * c2 + 16), -8 * c0 + 7 * c1 + 8 * c2 + (c1 + c4) / 2 - 1), -c1 - 8 * c5 + (c1 + c4 + 1) / 2 - 1); c9 += 1) {
m5[(c1+1)][c9][(-c1+c4-2*c9-1)] = INT_MIN;
if (c2 == 0 && c1 + c5 == c0 && N + c1 + c9 + 1 >= c4 && 16 * c0 + c9 + 16 >= 15 * c1 + c4)
m4[(c1+1)][c9][(-c1+c4-c9-1)] = INT_MIN;
}
if (c2 == 0 && 16 * c0 + 32 >= 15 * c1 + c4 && c1 + c5 == c0 + 1)
m4[(c1+1)][(-16*c0+15*c1+c4-17)][(16*c0-16*c1+16)] = INT_MIN;
for( c9 = max(max(max(-16 * c0 + 15 * c1 + 16 * c2 + c4 - 17, -N - c1 + c4 - 1), -c1 + c4 - 16 * c5 - 16), -8 * c0 + 7 * c1 + 8 * c2 + (c1 + c4) / 2); c9 <= min(min(min(N, 16 * c2 + 16), -16 * c0 + 15 * c1 + 16 * c2 + c4 - 2), -c1 + c4 - 16 * c5 - 1); c9 += 1)
m4[(c1+1)][c9][(-c1+c4-c9-1)] = INT_MIN;
}
if (N + 16 * c1 + 16 * c2 >= 16 * c0 + 16 && 16 * c0 + 14 >= 17 * c1 + 16 * c2 && 15 * c1 + c4 >= 16 * c0 + 18 && N + 16 * c0 + 17 >= 15 * c1 + 16 * c2 + c4 && 16 * c0 + 16 * c2 + 18 >= 15 * c1 + c4 && 16 * c0 + 33 >= 15 * c1 + c4)
m4[(c1+1)][(-16*c0+15*c1+16*c2+c4-17)][(16*c0-16*c1-16*c2+16)] = INT_MIN;
if (17 * c1 + 1 >= 16 * c0 && c2 == 0 && c4 >= N + 17 && 16 * c0 + 32 >= 16 * c1 + c4) {
for( c9 = max(1, -N - c1 + (N + c1 + c4) / 2); c9 < -8 * c0 + 7 * c1 + (c1 + c4) / 2; c9 += 1) {
m5[(c1+1)][c9][(-c1+c4-2*c9-1)] = INT_MIN;
if (N + c1 + c9 + 1 >= c4)
m4[(c1+1)][c9][(-c1+c4-c9-1)] = INT_MIN;
}
for( c9 = max(-N - c1 + c4 - 1, -8 * c0 + 7 * c1 + (c1 + c4) / 2); c9 <= min(N, -16 * c0 + 15 * c1 + c4 - 2); c9 += 1)
m4[(c1+1)][c9][(-c1+c4-c9-1)] = INT_MIN;
} else if (c1 == c0 && c2 == 0 && c4 >= 2 * N + 1 && N + 16 >= c4) {
for( c9 = -N - c0 + (N + c0 + c4) / 2; c9 < -c0 + (c0 + c4) / 2; c9 += 1) {
m5[(c0+1)][c9][(-c0+c4-2*c9-1)] = INT_MIN;
if (N + c0 + c9 + 1 >= c4)
m4[(c0+1)][c9][(-c0+c4-c9-1)] = INT_MIN;
}
for( c9 = -c0 + (c0 + c4) / 2; c9 <= N; c9 += 1)
m4[(c0+1)][c9][(-c0+c4-c9-1)] = INT_MIN;
}
}
for( c4 = 2 * N + 16 * c0 - 15 * c1 + 3; c4 <= min(min(min(4 * N + c1 + 1, 2 * N + 16 * c0 - 15 * c1 + 33), 3 * N + c1 + 16 * c2 + 17), 3 * N + 16 * c0 - 15 * c1 - 16 * c2 + 17); c4 += 1) {
for( c5 = max(max(-c0 + c1 + c2 - 1, -((N + 14) / 16)), c2 - (-2 * N - c1 + c4 + 12) / 16); c5 < min(-((c1 + 15) / 16), c0 - c1 - c2 - (-2 * N - c1 + c4 + 12) / 16); c5 += 1)
for( c9 = max(max(16 * c2 + 1, -2 * N - 16 * c0 + 15 * c1 + 16 * c2 + c4 - 17), -3 * N - c1 + c4 - 1); c9 <= min(min(16 * c2 + 16, -2 * N - 16 * c0 + 15 * c1 + 16 * c2 + c4 - 2), -2 * N - c1 + c4 + 16 * c5 + 13); c9 += 1) {
for( c13 = max(1, -2 * N - c1 + c4 + 16 * c5 - c9 - 1); c13 <= -2 * N - c1 + c4 + 16 * c5 - c9 + 14; c13 += 1)
m3[(c1+1)][c9][(-2*N-c1+c4-c9-1)] = MAX(m3[(c1+1)][c9][(-2*N-c1+c4-c9-1)], H[(c1+1)][c9][(-2*N-c1+c4-c9-1)-c13] - 2*W[c13]);
for( c13 = max(1, -2 * N - c1 + c4 + 16 * c5 - c9 - 1); c13 <= min(c9, -2 * N - c1 + c4 + 16 * c5 - c9 + 14); c13 += 1)
m5[(c1+1)][c9][(-2*N-c1+c4-c9-1)] = MAX(m5[(c1+1)][c9][(-2*N-c1+c4-c9-1)], H[(c1+1)][c9-c13][(-2*N-c1+c4-c9-1)-c13] - W[c13] + s(b[c9], c[(-2*N-c1+c4-c9-1)]));
for( c13 = max(1, -2 * N - c1 + c4 + 16 * c5 - c9 - 1); c13 <= min(c1 + 1, -2 * N - c1 + c4 + 16 * c5 - c9 + 14); c13 += 1)
m6[(c1+1)][c9][(-2*N-c1+c4-c9-1)] = MAX(m6[(c1+1)][c9][(-2*N-c1+c4-c9-1)], H[(c1+1)-c13][c9][(-2*N-c1+c4-c9-1)-c13] - W[c13] + s(a[(c1+1)], c[(-2*N-c1+c4-c9-1)]));
}
if (c0 >= c1 + 2 * c2 + 1 && 16 * c2 + 16 >= c1 && 15 * c1 + c4 >= 2 * N + 16 * c0 + 20) {
for( c9 = max(-2 * N - 16 * c0 + 15 * c1 + 16 * c2 + c4 - 17, -3 * N - c1 + c4 - 1); c9 <= 16 * c2 + 16; c9 += 1) {
for( c13 = max(1, -2 * N - c1 - 16 * c2 + c4 - c9 - 33); c13 < -2 * N - c1 - 16 * c2 + c4 - c9 - 17; c13 += 1)
m3[(c1+1)][c9][(-2*N-c1+c4-c9-1)] = MAX(m3[(c1+1)][c9][(-2*N-c1+c4-c9-1)], H[(c1+1)][c9][(-2*N-c1+c4-c9-1)-c13] - 2*W[c13]);
for( c13 = max(1, -2 * N - c1 - 16 * c2 + c4 - c9 - 33); c13 <= min(-2 * N - c1 - 16 * c2 + c4 - c9 - 18, c9); c13 += 1)
m5[(c1+1)][c9][(-2*N-c1+c4-c9-1)] = MAX(m5[(c1+1)][c9][(-2*N-c1+c4-c9-1)], H[(c1+1)][c9-c13][(-2*N-c1+c4-c9-1)-c13] - W[c13] + s(b[c9], c[(-2*N-c1+c4-c9-1)]));
for( c13 = max(1, -2 * N - c1 - 16 * c2 + c4 - c9 - 33); c13 <= min(c1 + 1, -2 * N - c1 - 16 * c2 + c4 - c9 - 18); c13 += 1)
m6[(c1+1)][c9][(-2*N-c1+c4-c9-1)] = MAX(m6[(c1+1)][c9][(-2*N-c1+c4-c9-1)], H[(c1+1)-c13][c9][(-2*N-c1+c4-c9-1)-c13] - W[c13] + s(a[(c1+1)], c[(-2*N-c1+c4-c9-1)]));
}
} else if (N <= 14 && c1 == c0 && c2 == 0 && c4 == 2 * N + c0 + 3) {
for( c13 = 1; c13 <= c0; c13 += 1)
m1[(c0+1)][1][1] = MAX(m1[(c0+1)][1][1] ,H[(c0+1)-c13][1][1] - 2*W[c13]);
}
for( c5 = -((c1 + 15) / 16); c5 < min((-c0 + c4 - 1) / 16 - 2, c0 - c1 - c2 - (-2 * N - c1 + c4 + 12) / 16); c5 += 1)
for( c9 = max(max(16 * c2 + 1, -2 * N - 16 * c0 + 15 * c1 + 16 * c2 + c4 - 17), -3 * N - c1 + c4 - 1); c9 <= min(16 * c2 + 16, -2 * N - 16 * c0 + 15 * c1 + 16 * c2 + c4 - 2); c9 += 1) {
for( c13 = max(1, c1 + 16 * c5 + 1); c13 <= c1 + 16 * c5 + 16; c13 += 1)
m1[(c1+1)][c9][(-2*N-c1+c4-c9-1)] = MAX(m1[(c1+1)][c9][(-2*N-c1+c4-c9-1)] ,H[(c1+1)-c13][c9][(-2*N-c1+c4-c9-1)] - 2*W[c13]);
for( c13 = max(1, -2 * N - c1 + c4 + 16 * c5 - c9 - 1); c13 <= -2 * N - c1 + c4 + 16 * c5 - c9 + 14; c13 += 1)
m3[(c1+1)][c9][(-2*N-c1+c4-c9-1)] = MAX(m3[(c1+1)][c9][(-2*N-c1+c4-c9-1)], H[(c1+1)][c9][(-2*N-c1+c4-c9-1)-c13] - 2*W[c13]);
for( c13 = max(1, -2 * N - c1 + c4 + 16 * c5 - c9 - 1); c13 <= min(c9, -2 * N - c1 + c4 + 16 * c5 - c9 + 14); c13 += 1)
m5[(c1+1)][c9][(-2*N-c1+c4-c9-1)] = MAX(m5[(c1+1)][c9][(-2*N-c1+c4-c9-1)], H[(c1+1)][c9-c13][(-2*N-c1+c4-c9-1)-c13] - W[c13] + s(b[c9], c[(-2*N-c1+c4-c9-1)]));
for( c13 = max(1, -2 * N - c1 + c4 + 16 * c5 - c9 - 1); c13 <= min(c1 + 1, -2 * N - c1 + c4 + 16 * c5 - c9 + 14); c13 += 1)
m6[(c1+1)][c9][(-2*N-c1+c4-c9-1)] = MAX(m6[(c1+1)][c9][(-2*N-c1+c4-c9-1)], H[(c1+1)-c13][c9][(-2*N-c1+c4-c9-1)-c13] - W[c13] + s(a[(c1+1)], c[(-2*N-c1+c4-c9-1)]));
}
if (c1 >= 16 * c2 + 17 && 15 * c1 + c4 >= 2 * N + 16 * c0 + 20)
for( c9 = max(-2 * N - 16 * c0 + 15 * c1 + 16 * c2 + c4 - 17, -3 * N - c1 + c4 - 1); c9 <= 16 * c2 + 16; c9 += 1) {
for( c13 = max(1, c1 - 16 * c2 - 31); c13 < c1 - 16 * c2 - 15; c13 += 1)
m1[(c1+1)][c9][(-2*N-c1+c4-c9-1)] = MAX(m1[(c1+1)][c9][(-2*N-c1+c4-c9-1)] ,H[(c1+1)-c13][c9][(-2*N-c1+c4-c9-1)] - 2*W[c13]);
for( c13 = max(1, -2 * N - c1 - 16 * c2 + c4 - c9 - 33); c13 < -2 * N - c1 - 16 * c2 + c4 - c9 - 17; c13 += 1)
m3[(c1+1)][c9][(-2*N-c1+c4-c9-1)] = MAX(m3[(c1+1)][c9][(-2*N-c1+c4-c9-1)], H[(c1+1)][c9][(-2*N-c1+c4-c9-1)-c13] - 2*W[c13]);
for( c13 = max(1, -2 * N - c1 - 16 * c2 + c4 - c9 - 33); c13 <= min(-2 * N - c1 - 16 * c2 + c4 - c9 - 18, c9); c13 += 1)
m5[(c1+1)][c9][(-2*N-c1+c4-c9-1)] = MAX(m5[(c1+1)][c9][(-2*N-c1+c4-c9-1)], H[(c1+1)][c9-c13][(-2*N-c1+c4-c9-1)-c13] - W[c13] + s(b[c9], c[(-2*N-c1+c4-c9-1)]));
for( c13 = max(1, -2 * N - c1 - 16 * c2 + c4 - c9 - 33); c13 <= min(c1 + 1, -2 * N - c1 - 16 * c2 + c4 - c9 - 18); c13 += 1)
m6[(c1+1)][c9][(-2*N-c1+c4-c9-1)] = MAX(m6[(c1+1)][c9][(-2*N-c1+c4-c9-1)], H[(c1+1)-c13][c9][(-2*N-c1+c4-c9-1)-c13] - W[c13] + s(a[(c1+1)], c[(-2*N-c1+c4-c9-1)]));
}
for( c5 = max(max(-c2 - 1, -((N + 14) / 16)), c0 - c1 - c2 - (-2 * N - c1 + c4 + 12) / 16); c5 <= min(0, (-c0 + c4 - 1) / 16 - 3); c5 += 1) {
if (c1 + 16 * c5 <= -16) {
if (3 * N + c1 + 16 * c2 + 2 >= c4 && 2 * N + 16 * c0 + 18 >= 15 * c1 + c4 && c2 + c5 == -1) {
for( c13 = max(1, -2 * N - c1 - 32 * c2 + c4 - 18); c13 < -2 * N - c1 - 32 * c2 + c4 - 2; c13 += 1)
m3[(c1+1)][(16*c2+1)][(-2*N-c1-16*c2+c4-2)] = MAX(m3[(c1+1)][(16*c2+1)][(-2*N-c1-16*c2+c4-2)], H[(c1+1)][(16*c2+1)][(-2*N-c1-16*c2+c4-2)-c13] - 2*W[c13]);
for( c13 = max(1, -2 * N - c1 - 32 * c2 + c4 - 18); c13 <= min(16 * c2 + 1, -2 * N - c1 - 32 * c2 + c4 - 3); c13 += 1)
m5[(c1+1)][(16*c2+1)][(-2*N-c1-16*c2+c4-2)] = MAX(m5[(c1+1)][(16*c2+1)][(-2*N-c1-16*c2+c4-2)], H[(c1+1)][(16*c2+1)-c13][(-2*N-c1-16*c2+c4-2)-c13] - W[c13] + s(b[(16*c2+1)], c[(-2*N-c1-16*c2+c4-2)]));
for( c13 = max(1, -2 * N - c1 - 32 * c2 + c4 - 18); c13 <= min(c1 + 1, -2 * N - c1 - 32 * c2 + c4 - 3); c13 += 1)
m6[(c1+1)][(16*c2+1)][(-2*N-c1-16*c2+c4-2)] = MAX(m6[(c1+1)][(16*c2+1)][(-2*N-c1-16*c2+c4-2)], H[(c1+1)-c13][(16*c2+1)][(-2*N-c1-16*c2+c4-2)-c13] - W[c13] + s(a[(c1+1)], c[(-2*N-c1-16*c2+c4-2)]));
}
for( c9 = max(max(max(16 * c2 + 1, -2 * N - 16 * c0 + 15 * c1 + 16 * c2 + c4 - 17), -3 * N - c1 + c4 - 1), -16 * c5 - 14); c9 <= min(min(N, 16 * c2 + 16), -2 * N - 16 * c0 + 15 * c1 + 16 * c2 + c4 - 2); c9 += 1) {
for( c13 = max(1, 16 * c5 + c9); c13 <= 16 * c5 + c9 + 15; c13 += 1)
m2[(c1+1)][c9][(-2*N-c1+c4-c9-1)] = MAX(m2[(c1+1)][c9][(-2*N-c1+c4-c9-1)], H[(c1+1)][c9-c13][(-2*N-c1+c4-c9-1)] - 2*W[c13]);
for( c13 = max(1, -2 * N - c1 + c4 + 16 * c5 - c9 - 1); c13 <= -2 * N - c1 + c4 + 16 * c5 - c9 + 14; c13 += 1)
m3[(c1+1)][c9][(-2*N-c1+c4-c9-1)] = MAX(m3[(c1+1)][c9][(-2*N-c1+c4-c9-1)], H[(c1+1)][c9][(-2*N-c1+c4-c9-1)-c13] - 2*W[c13]);
for( c13 = max(1, 16 * c5 + c9); c13 <= min(c1 + 1, 16 * c5 + c9 + 15); c13 += 1)
m4[(c1+1)][c9][(-2*N-c1+c4-c9-1)] = MAX(m4[(c1+1)][c9][(-2*N-c1+c4-c9-1)], H[(c1+1)-c13][c9-c13][(-2*N-c1+c4-c9-1)] - W[c13] + s(a[(c1+1)], b[c9]));
for( c13 = max(1, -2 * N - c1 + c4 + 16 * c5 - c9 - 1); c13 <= min(c9, -2 * N - c1 + c4 + 16 * c5 - c9 + 14); c13 += 1)
m5[(c1+1)][c9][(-2*N-c1+c4-c9-1)] = MAX(m5[(c1+1)][c9][(-2*N-c1+c4-c9-1)], H[(c1+1)][c9-c13][(-2*N-c1+c4-c9-1)-c13] - W[c13] + s(b[c9], c[(-2*N-c1+c4-c9-1)]));
for( c13 = max(1, -2 * N - c1 + c4 + 16 * c5 - c9 - 1); c13 <= min(c1 + 1, -2 * N - c1 + c4 + 16 * c5 - c9 + 14); c13 += 1)
m6[(c1+1)][c9][(-2*N-c1+c4-c9-1)] = MAX(m6[(c1+1)][c9][(-2*N-c1+c4-c9-1)], H[(c1+1)-c13][c9][(-2*N-c1+c4-c9-1)-c13] - W[c13] + s(a[(c1+1)], c[(-2*N-c1+c4-c9-1)]));
}
} else {
for( c9 = max(max(16 * c2 + 1, -2 * N - 16 * c0 + 15 * c1 + 16 * c2 + c4 - 17), -3 * N - c1 + c4 - 1); c9 <= min(min(N, 16 * c2 + 16), -2 * N - 16 * c0 + 15 * c1 + 16 * c2 + c4 - 2); c9 += 1) {
for( c13 = max(1, c1 + 16 * c5 + 1); c13 <= min(c1 + 1, c1 + 16 * c5 + 16); c13 += 1)
m1[(c1+1)][c9][(-2*N-c1+c4-c9-1)] = MAX(m1[(c1+1)][c9][(-2*N-c1+c4-c9-1)] ,H[(c1+1)-c13][c9][(-2*N-c1+c4-c9-1)] - 2*W[c13]);
for( c13 = max(1, 16 * c5 + c9); c13 <= min(c9, 16 * c5 + c9 + 15); c13 += 1)
m2[(c1+1)][c9][(-2*N-c1+c4-c9-1)] = MAX(m2[(c1+1)][c9][(-2*N-c1+c4-c9-1)], H[(c1+1)][c9-c13][(-2*N-c1+c4-c9-1)] - 2*W[c13]);
for( c13 = max(1, -2 * N - c1 + c4 + 16 * c5 - c9 - 1); c13 <= min(-2 * N - c1 + c4 - c9 - 1, -2 * N - c1 + c4 + 16 * c5 - c9 + 14); c13 += 1)
m3[(c1+1)][c9][(-2*N-c1+c4-c9-1)] = MAX(m3[(c1+1)][c9][(-2*N-c1+c4-c9-1)], H[(c1+1)][c9][(-2*N-c1+c4-c9-1)-c13] - 2*W[c13]);
for( c13 = max(1, 16 * c5 + c9); c13 <= min(min(c1 + 1, c9), 16 * c5 + c9 + 15); c13 += 1)
m4[(c1+1)][c9][(-2*N-c1+c4-c9-1)] = MAX(m4[(c1+1)][c9][(-2*N-c1+c4-c9-1)], H[(c1+1)-c13][c9-c13][(-2*N-c1+c4-c9-1)] - W[c13] + s(a[(c1+1)], b[c9]));
for( c13 = max(1, -2 * N - c1 + c4 + 16 * c5 - c9 - 1); c13 <= min(min(-2 * N - c1 + c4 - c9 - 1, c9), -2 * N - c1 + c4 + 16 * c5 - c9 + 14); c13 += 1)
m5[(c1+1)][c9][(-2*N-c1+c4-c9-1)] = MAX(m5[(c1+1)][c9][(-2*N-c1+c4-c9-1)], H[(c1+1)][c9-c13][(-2*N-c1+c4-c9-1)-c13] - W[c13] + s(b[c9], c[(-2*N-c1+c4-c9-1)]));
for( c13 = max(1, -2 * N - c1 + c4 + 16 * c5 - c9 - 1); c13 <= min(min(c1 + 1, -2 * N - c1 + c4 - c9 - 1), -2 * N - c1 + c4 + 16 * c5 - c9 + 14); c13 += 1)
m6[(c1+1)][c9][(-2*N-c1+c4-c9-1)] = MAX(m6[(c1+1)][c9][(-2*N-c1+c4-c9-1)], H[(c1+1)-c13][c9][(-2*N-c1+c4-c9-1)-c13] - W[c13] + s(a[(c1+1)], c[(-2*N-c1+c4-c9-1)]));
}
}
}
if ((c4 >= N + c0 + 19 && ((c0 + 15 * c4) % 16) + 2 * N <= 31) || (N + c0 + 18 >= c4 && 2 * c4 >= ((14 * N + 15 * c0 + c4 + 12) % 16) + 4 * N + 2 * c0 + 5)) {
int c5 = N + c0 + 18 >= c4 ? -1 : c4 - (c0 + 15 * c4) / 16 - 3;
if (c0 == 0 && 3 * N + 2 >= c4 && c5 == -1) {
for( c13 = 1; c13 < -2 * N + c4 - 2; c13 += 1)
m3[1][1][(-2*N+c4-2)] = MAX(m3[1][1][(-2*N+c4-2)], H[1][1][(-2*N+c4-2)-c13] - 2*W[c13]);
m5[1][1][(-2*N+c4-2)] = MAX(m5[1][1][(-2*N+c4-2)], H[1][1-1][(-2*N+c4-2)-1] - W[1] + s(b[1], c[(-2*N+c4-2)]));
m6[1][1][(-2*N+c4-2)] = MAX(m6[1][1][(-2*N+c4-2)], H[1-1][1][(-2*N+c4-2)-1] - W[1] + s(a[1], c[(-2*N+c4-2)]));
} else if (c0 >= 1 && 3 * N + c0 + 2 >= c4 && c5 == -1) {
for( c13 = 1; c13 <= c0; c13 += 1)
m1[(c0+1)][1][(-2*N-c0+c4-2)] = MAX(m1[(c0+1)][1][(-2*N-c0+c4-2)] ,H[(c0+1)-c13][1][(-2*N-c0+c4-2)] - 2*W[c13]);
for( c13 = 1; c13 < -2 * N - c0 + c4 - 2; c13 += 1)
m3[(c0+1)][1][(-2*N-c0+c4-2)] = MAX(m3[(c0+1)][1][(-2*N-c0+c4-2)], H[(c0+1)][1][(-2*N-c0+c4-2)-c13] - 2*W[c13]);
m5[(c0+1)][1][(-2*N-c0+c4-2)] = MAX(m5[(c0+1)][1][(-2*N-c0+c4-2)], H[(c0+1)][1-1][(-2*N-c0+c4-2)-1] - W[1] + s(b[1], c[(-2*N-c0+c4-2)]));
for( c13 = 1; c13 <= min(c0 + 1, -2 * N - c0 + c4 - 3); c13 += 1)
m6[(c0+1)][1][(-2*N-c0+c4-2)] = MAX(m6[(c0+1)][1][(-2*N-c0+c4-2)], H[(c0+1)-c13][1][(-2*N-c0+c4-2)-c13] - W[c13] + s(a[(c0+1)], c[(-2*N-c0+c4-2)]));
}
for( c9 = max(-3 * N - c0 + c4 - 1, -16 * c5 - 14); c9 <= min(N, -2 * N - c0 + c4 - 2); c9 += 1) {
for( c13 = max(1, c0 + 16 * c5 + 1); c13 <= min(c0 + 1, c0 + 16 * c5 + 16); c13 += 1)
m1[(c0+1)][c9][(-2*N-c0+c4-c9-1)] = MAX(m1[(c0+1)][c9][(-2*N-c0+c4-c9-1)] ,H[(c0+1)-c13][c9][(-2*N-c0+c4-c9-1)] - 2*W[c13]);
for( c13 = max(1, 16 * c5 + c9); c13 <= min(c9, 16 * c5 + c9 + 15); c13 += 1)
m2[(c0+1)][c9][(-2*N-c0+c4-c9-1)] = MAX(m2[(c0+1)][c9][(-2*N-c0+c4-c9-1)], H[(c0+1)][c9-c13][(-2*N-c0+c4-c9-1)] - 2*W[c13]);
for( c13 = max(1, -2 * N - c0 + c4 + 16 * c5 - c9 - 1); c13 <= min(-2 * N - c0 + c4 - c9 - 1, -2 * N - c0 + c4 + 16 * c5 - c9 + 14); c13 += 1)
m3[(c0+1)][c9][(-2*N-c0+c4-c9-1)] = MAX(m3[(c0+1)][c9][(-2*N-c0+c4-c9-1)], H[(c0+1)][c9][(-2*N-c0+c4-c9-1)-c13] - 2*W[c13]);
for( c13 = max(1, 16 * c5 + c9); c13 <= min(min(c0 + 1, c9), 16 * c5 + c9 + 15); c13 += 1)
m4[(c0+1)][c9][(-2*N-c0+c4-c9-1)] = MAX(m4[(c0+1)][c9][(-2*N-c0+c4-c9-1)], H[(c0+1)-c13][c9-c13][(-2*N-c0+c4-c9-1)] - W[c13] + s(a[(c0+1)], b[c9]));
for( c13 = max(1, -2 * N - c0 + c4 + 16 * c5 - c9 - 1); c13 <= min(min(-2 * N - c0 + c4 - c9 - 1, c9), -2 * N - c0 + c4 + 16 * c5 - c9 + 14); c13 += 1)
m5[(c0+1)][c9][(-2*N-c0+c4-c9-1)] = MAX(m5[(c0+1)][c9][(-2*N-c0+c4-c9-1)], H[(c0+1)][c9-c13][(-2*N-c0+c4-c9-1)-c13] - W[c13] + s(b[c9], c[(-2*N-c0+c4-c9-1)]));
for( c13 = max(1, -2 * N - c0 + c4 + 16 * c5 - c9 - 1); c13 <= min(min(c0 + 1, -2 * N - c0 + c4 - c9 - 1), -2 * N - c0 + c4 + 16 * c5 - c9 + 14); c13 += 1)
m6[(c0+1)][c9][(-2*N-c0+c4-c9-1)] = MAX(m6[(c0+1)][c9][(-2*N-c0+c4-c9-1)], H[(c0+1)-c13][c9][(-2*N-c0+c4-c9-1)-c13] - W[c13] + s(a[(c0+1)], c[(-2*N-c0+c4-c9-1)]));
}
}
if (c1 == c0 && c2 == 0 && c4 >= 16 && c4 >= 3 * N + c0 + 2 && 2 * N + c0 + 16 >= c4) {
for( c9 = -3 * N - c0 + c4 - 1; c9 <= N; c9 += 1) {
m1[(c0+1)][c9][(-2*N-c0+c4-c9-1)] = MAX(m1[(c0+1)][c9][(-2*N-c0+c4-c9-1)] ,H[(c0+1)-(c0+1)][c9][(-2*N-c0+c4-c9-1)] - 2*W[(c0+1)]);
m2[(c0+1)][c9][(-2*N-c0+c4-c9-1)] = MAX(m2[(c0+1)][c9][(-2*N-c0+c4-c9-1)], H[(c0+1)][c9-c9][(-2*N-c0+c4-c9-1)] - 2*W[c9]);
m3[(c0+1)][c9][(-2*N-c0+c4-c9-1)] = MAX(m3[(c0+1)][c9][(-2*N-c0+c4-c9-1)], H[(c0+1)][c9][(-2*N-c0+c4-c9-1)-(-2*N-c0+c4-c9-1)] - 2*W[(-2*N-c0+c4-c9-1)]);
if (c0 + 1 >= c9)
m4[(c0+1)][c9][(-2*N-c0+c4-c9-1)] = MAX(m4[(c0+1)][c9][(-2*N-c0+c4-c9-1)], H[(c0+1)-c9][c9-c9][(-2*N-c0+c4-c9-1)] - W[c9] + s(a[(c0+1)], b[c9]));
if (2 * N + c0 + 2 * c9 + 1 >= c4)
m5[(c0+1)][c9][(-2*N-c0+c4-c9-1)] = MAX(m5[(c0+1)][c9][(-2*N-c0+c4-c9-1)], H[(c0+1)][c9-(-2*N-c0+c4-c9-1)][(-2*N-c0+c4-c9-1)-(-2*N-c0+c4-c9-1)] - W[(-2*N-c0+c4-c9-1)] + s(b[c9], c[(-2*N-c0+c4-c9-1)]));
if (2 * N + 2 * c0 + c9 + 2 >= c4)
m6[(c0+1)][c9][(-2*N-c0+c4-c9-1)] = MAX(m6[(c0+1)][c9][(-2*N-c0+c4-c9-1)], H[(c0+1)-(-2*N-c0+c4-c9-1)][c9][(-2*N-c0+c4-c9-1)-(-2*N-c0+c4-c9-1)] - W[(-2*N-c0+c4-c9-1)] + s(a[(c0+1)], c[(-2*N-c0+c4-c9-1)]));
}
} else if (c1 == c0 && c2 == 0 && 3 * N + c0 + 1 >= c4 && c0 + 49 >= c4) {
for( c5 = max(0, (-c0 + c4 - 1) / 16 - 2); c5 <= min(N / 16, c4 / 16 - 1); c5 += 1) {
if (c5 == 0)
for( c9 = 1; c9 < -2 * N - c0 + c4 - 1; c9 += 1) {
m1[(c0+1)][c9][(-2*N-c0+c4-c9-1)] = MAX(m1[(c0+1)][c9][(-2*N-c0+c4-c9-1)] ,H[(c0+1)-(c0+1)][c9][(-2*N-c0+c4-c9-1)] - 2*W[(c0+1)]);
m2[(c0+1)][c9][(-2*N-c0+c4-c9-1)] = MAX(m2[(c0+1)][c9][(-2*N-c0+c4-c9-1)], H[(c0+1)][c9-c9][(-2*N-c0+c4-c9-1)] - 2*W[c9]);
m3[(c0+1)][c9][(-2*N-c0+c4-c9-1)] = MAX(m3[(c0+1)][c9][(-2*N-c0+c4-c9-1)], H[(c0+1)][c9][(-2*N-c0+c4-c9-1)-(-2*N-c0+c4-c9-1)] - 2*W[(-2*N-c0+c4-c9-1)]);
if (c0 + 1 >= c9)
m4[(c0+1)][c9][(-2*N-c0+c4-c9-1)] = MAX(m4[(c0+1)][c9][(-2*N-c0+c4-c9-1)], H[(c0+1)-c9][c9-c9][(-2*N-c0+c4-c9-1)] - W[c9] + s(a[(c0+1)], b[c9]));
if (2 * N + c0 + 2 * c9 + 1 >= c4)
m5[(c0+1)][c9][(-2*N-c0+c4-c9-1)] = MAX(m5[(c0+1)][c9][(-2*N-c0+c4-c9-1)], H[(c0+1)][c9-(-2*N-c0+c4-c9-1)][(-2*N-c0+c4-c9-1)-(-2*N-c0+c4-c9-1)] - W[(-2*N-c0+c4-c9-1)] + s(b[c9], c[(-2*N-c0+c4-c9-1)]));
if (2 * N + 2 * c0 + c9 + 2 >= c4)
m6[(c0+1)][c9][(-2*N-c0+c4-c9-1)] = MAX(m6[(c0+1)][c9][(-2*N-c0+c4-c9-1)], H[(c0+1)-(-2*N-c0+c4-c9-1)][c9][(-2*N-c0+c4-c9-1)-(-2*N-c0+c4-c9-1)] - W[(-2*N-c0+c4-c9-1)] + s(a[(c0+1)], c[(-2*N-c0+c4-c9-1)]));
}
for( c9 = max(max(-c0 + (c0 + c4) / 2 - 8, -N - c0 + (N + c0 + c4) / 2), -c0 - 8 * c5 + (c0 + c4 + 1) / 2 - 8); c9 <= min(min(16, N), -c0 - 8 * c5 + (c0 + c4 + 1) / 2 - 1); c9 += 1)
m5[(c0+1)][c9][(-c0+c4-2*c9-1)] = INT_MIN;
}
}
for( c9 = max(max(16 * c2 + 1, -2 * N - 16 * c0 + 15 * c1 + 16 * c2 + c4 - 17), -3 * N - c1 + c4 - 1); c9 <= min(min(N, 16 * c2 + 16), -2 * N - 16 * c0 + 15 * c1 + 16 * c2 + c4 - 2); c9 += 1) {
if (c1 == c0 && c2 == 0 && c4 <= 15) {
m1[(c0+1)][c9][(-2*N-c0+c4-c9-1)] = MAX(m1[(c0+1)][c9][(-2*N-c0+c4-c9-1)] ,H[(c0+1)-(c0+1)][c9][(-2*N-c0+c4-c9-1)] - 2*W[(c0+1)]);
m2[(c0+1)][c9][(-2*N-c0+c4-c9-1)] = MAX(m2[(c0+1)][c9][(-2*N-c0+c4-c9-1)], H[(c0+1)][c9-c9][(-2*N-c0+c4-c9-1)] - 2*W[c9]);
m3[(c0+1)][c9][(-2*N-c0+c4-c9-1)] = MAX(m3[(c0+1)][c9][(-2*N-c0+c4-c9-1)], H[(c0+1)][c9][(-2*N-c0+c4-c9-1)-(-2*N-c0+c4-c9-1)] - 2*W[(-2*N-c0+c4-c9-1)]);
if (c0 + 1 >= c9)
m4[(c0+1)][c9][(-2*N-c0+c4-c9-1)] = MAX(m4[(c0+1)][c9][(-2*N-c0+c4-c9-1)], H[(c0+1)-c9][c9-c9][(-2*N-c0+c4-c9-1)] - W[c9] + s(a[(c0+1)], b[c9]));
if (2 * N + c0 + 2 * c9 + 1 >= c4)
m5[(c0+1)][c9][(-2*N-c0+c4-c9-1)] = MAX(m5[(c0+1)][c9][(-2*N-c0+c4-c9-1)], H[(c0+1)][c9-(-2*N-c0+c4-c9-1)][(-2*N-c0+c4-c9-1)-(-2*N-c0+c4-c9-1)] - W[(-2*N-c0+c4-c9-1)] + s(b[c9], c[(-2*N-c0+c4-c9-1)]));
if (2 * N + 2 * c0 + c9 + 2 >= c4)
m6[(c0+1)][c9][(-2*N-c0+c4-c9-1)] = MAX(m6[(c0+1)][c9][(-2*N-c0+c4-c9-1)], H[(c0+1)-(-2*N-c0+c4-c9-1)][c9][(-2*N-c0+c4-c9-1)-(-2*N-c0+c4-c9-1)] - W[(-2*N-c0+c4-c9-1)] + s(a[(c0+1)], c[(-2*N-c0+c4-c9-1)]));
}
H[(c1+1)][c9][(-2*N-c1+c4-c9-1)] = MAX(0, MAX( H[(c1+1)-1][c9-1][(-2*N-c1+c4-c9-1)-1] + s(a[(c1+1)], b[c9]) + s(a[(c1+1)], c[(-2*N-c1+c4-c9-1)]) + s(b[c9], c[(-2*N-c1+c4-c9-1)]), MAX(m1[(c1+1)][c9][(-2*N-c1+c4-c9-1)], MAX(m2[(c1+1)][c9][(-2*N-c1+c4-c9-1)], MAX(m3[(c1+1)][c9][(-2*N-c1+c4-c9-1)], MAX(m4[(c1+1)][c9][(-2*N-c1+c4-c9-1)], MAX(m5[(c1+1)][c9][(-2*N-c1+c4-c9-1)], m6[(c1+1)][c9][(-2*N-c1+c4-c9-1)])))))));
}
if (c1 == c0 && c2 == 0 && c4 <= 15)
for( c9 = -N - c0 + (N + c0 + c4) / 2; c9 <= N; c9 += 1)
m5[(c0+1)][c9][(-c0+c4-2*c9-1)] = INT_MIN;
}
}
// ---------------------------------------
}
|
declare_reduction_codegen.c | // RUN: %clang_cc1 -verify -fopenmp -x c -emit-llvm %s -triple %itanium_abi_triple -o - -femit-all-decls -disable-llvm-passes | FileCheck %s
// RUN: %clang_cc1 -fopenmp -x c -triple %itanium_abi_triple -emit-pch -o %t %s -femit-all-decls -disable-llvm-passes
// RUN: %clang_cc1 -fopenmp -x c -triple %itanium_abi_triple -include-pch %t -verify %s -emit-llvm -o - -femit-all-decls -disable-llvm-passes | FileCheck --check-prefix=CHECK-LOAD %s
// RUN: %clang_cc1 -verify -fopenmp-simd -x c -emit-llvm %s -triple %itanium_abi_triple -o - -femit-all-decls -disable-llvm-passes | FileCheck --check-prefix SIMD-ONLY0 %s
// RUN: %clang_cc1 -fopenmp-simd -x c -triple %itanium_abi_triple -emit-pch -o %t %s -femit-all-decls -disable-llvm-passes
// RUN: %clang_cc1 -fopenmp-simd -x c -triple %itanium_abi_triple -include-pch %t -verify %s -emit-llvm -o - -femit-all-decls -disable-llvm-passes | FileCheck --check-prefix SIMD-ONLY0 %s
// SIMD-ONLY0-NOT: {{__kmpc|__tgt}}
// expected-no-diagnostics
#ifndef HEADER
#define HEADER
// CHECK: [[SSS_INT:.+]] = type { i32 }
// CHECK-LOAD: [[SSS_INT:.+]] = type { i32 }
#pragma omp declare reduction(+ : int, char : omp_out *= omp_in)
// CHECK: define internal {{.*}}void @{{[^(]+}}(i32* noalias, i32* noalias)
// CHECK: [[MUL:%.+]] = mul nsw i32
// CHECK-NEXT: store i32 [[MUL]], i32*
// CHECK-NEXT: ret void
// CHECK-NEXT: }
// CHECK-LOAD: define internal {{.*}}void @{{[^(]+}}(i32* noalias, i32* noalias)
// CHECK-LOAD: [[MUL:%.+]] = mul nsw i32
// CHECK-LOAD-NEXT: store i32 [[MUL]], i32*
// CHECK-LOAD-NEXT: ret void
// CHECK-LOAD-NEXT: }
// CHECK: define internal {{.*}}void @{{[^(]+}}(i8* noalias, i8* noalias)
// CHECK: sext i8
// CHECK: sext i8
// CHECK: [[MUL:%.+]] = mul nsw i32
// CHECK-NEXT: [[TRUNC:%.+]] = trunc i32 [[MUL]] to i8
// CHECK-NEXT: store i8 [[TRUNC]], i8*
// CHECK-NEXT: ret void
// CHECK-NEXT: }
// CHECK-LOAD: define internal {{.*}}void @{{[^(]+}}(i8* noalias, i8* noalias)
// CHECK-LOAD: sext i8
// CHECK-LOAD: sext i8
// CHECK-LOAD: [[MUL:%.+]] = mul nsw i32
// CHECK-LOAD-NEXT: [[TRUNC:%.+]] = trunc i32 [[MUL]] to i8
// CHECK-LOAD-NEXT: store i8 [[TRUNC]], i8*
// CHECK-LOAD-NEXT: ret void
// CHECK-LOAD-NEXT: }
#pragma omp declare reduction(fun : float : omp_out += omp_in) initializer(omp_priv = 15 + omp_orig)
// CHECK: define internal {{.*}}void @{{[^(]+}}(float* noalias, float* noalias)
// CHECK: [[ADD:%.+]] = fadd float
// CHECK-NEXT: store float [[ADD]], float*
// CHECK-NEXT: ret void
// CHECK-NEXT: }
// CHECK: define internal {{.*}}void @{{[^(]+}}(float* noalias, float* noalias)
// CHECK: [[ADD:%.+]] = fadd float 1.5
// CHECK-NEXT: store float [[ADD]], float*
// CHECK-NEXT: ret void
// CHECK-NEXT: }
// CHECK-LOAD: define internal {{.*}}void @{{[^(]+}}(float* noalias, float* noalias)
// CHECK-LOAD: [[ADD:%.+]] = fadd float
// CHECK-LOAD-NEXT: store float [[ADD]], float*
// CHECK-LOAD-NEXT: ret void
// CHECK-LOAD-NEXT: }
// CHECK-LOAD: define internal {{.*}}void @{{[^(]+}}(float* noalias, float* noalias)
// CHECK-LOAD: [[ADD:%.+]] = fadd float 1.5
// CHECK-LOAD-NEXT: store float [[ADD]], float*
// CHECK-LOAD-NEXT: ret void
// CHECK-LOAD-NEXT: }
struct SSS {
int field;
#pragma omp declare reduction(+ : int, char : omp_out *= omp_in)
// CHECK: define internal {{.*}}void @{{[^(]+}}(i32* noalias, i32* noalias)
// CHECK: [[MUL:%.+]] = mul nsw i32
// CHECK-NEXT: store i32 [[MUL]], i32*
// CHECK-NEXT: ret void
// CHECK-NEXT: }
// CHECK: define internal {{.*}}void @{{[^(]+}}(i8* noalias, i8* noalias)
// CHECK: sext i8
// CHECK: sext i8
// CHECK: [[MUL:%.+]] = mul nsw i32
// CHECK-NEXT: [[TRUNC:%.+]] = trunc i32 [[MUL]] to i8
// CHECK-NEXT: store i8 [[TRUNC]], i8*
// CHECK-NEXT: ret void
// CHECK-NEXT: }
};
void init(struct SSS *priv, struct SSS orig);
#pragma omp declare reduction(fun : struct SSS : omp_out = omp_in) initializer(init(&omp_priv, omp_orig))
// CHECK: define internal {{.*}}void @{{[^(]+}}([[SSS_INT]]* noalias, [[SSS_INT]]* noalias)
// CHECK: call void @llvm.memcpy
// CHECK-NEXT: ret void
// CHECK-NEXT: }
// CHECK: define internal {{.*}}void @{{[^(]+}}([[SSS_INT]]* noalias, [[SSS_INT]]* noalias)
// CHECK: call void @init(
// CHECK-NEXT: ret void
// CHECK-NEXT: }
// CHECK-LOAD: define internal {{.*}}void @{{[^(]+}}([[SSS_INT]]* noalias, [[SSS_INT]]* noalias)
// CHECK-LOAD: call void @llvm.memcpy
// CHECK-LOAD-NEXT: ret void
// CHECK-LOAD-NEXT: }
// CHECK-LOAD: define internal {{.*}}void @{{[^(]+}}([[SSS_INT]]* noalias, [[SSS_INT]]* noalias)
// CHECK-LOAD: call void @init(
// CHECK-LOAD-NEXT: ret void
// CHECK-LOAD-NEXT: }
// CHECK-LABEL: @main
// CHECK-LOAD-LABEL: @main
int main() {
#pragma omp declare reduction(fun : struct SSS : omp_out = omp_in) initializer(init(&omp_priv, omp_orig))
// CHECK: define internal {{.*}}void @{{[^(]+}}([[SSS_INT]]* noalias, [[SSS_INT]]* noalias)
// CHECK: call void @llvm.memcpy
// CHECK-NEXT: ret void
// CHECK-NEXT: }
// CHECK: define internal {{.*}}void @{{[^(]+}}([[SSS_INT]]* noalias, [[SSS_INT]]* noalias)
// CHECK: call void @init(
// CHECK-NEXT: ret void
// CHECK-NEXT: }
// CHECK-LOAD: define internal {{.*}}void @{{[^(]+}}([[SSS_INT]]* noalias, [[SSS_INT]]* noalias)
// CHECK-LOAD: call void @llvm.memcpy
// CHECK-LOAD-NEXT: ret void
// CHECK-LOAD-NEXT: }
// CHECK-LOAD: define internal {{.*}}void @{{[^(]+}}([[SSS_INT]]* noalias, [[SSS_INT]]* noalias)
// CHECK-LOAD: call void @init(
// CHECK-LOAD-NEXT: ret void
// CHECK-LOAD-NEXT: }
{
#pragma omp declare reduction(fun : struct SSS : omp_out = omp_in) initializer(init(&omp_priv, omp_orig))
// CHECK: define internal {{.*}}void @{{[^(]+}}([[SSS_INT]]* noalias, [[SSS_INT]]* noalias)
// CHECK: call void @llvm.memcpy
// CHECK-NEXT: ret void
// CHECK-NEXT: }
// CHECK: define internal {{.*}}void @{{[^(]+}}([[SSS_INT]]* noalias, [[SSS_INT]]* noalias)
// CHECK: call void @init(
// CHECK-NEXT: ret void
// CHECK-NEXT: }
// CHECK-LOAD: define internal {{.*}}void @{{[^(]+}}([[SSS_INT]]* noalias, [[SSS_INT]]* noalias)
// CHECK-LOAD: call void @llvm.memcpy
// CHECK-LOAD-NEXT: ret void
// CHECK-LOAD-NEXT: }
// CHECK-LOAD: define internal {{.*}}void @{{[^(]+}}([[SSS_INT]]* noalias, [[SSS_INT]]* noalias)
// CHECK-LOAD: call void @init(
// CHECK-LOAD-NEXT: ret void
// CHECK-LOAD-NEXT: }
}
return 0;
}
// CHECK-LOAD: define internal {{.*}}void @{{[^(]+}}(i32* noalias, i32* noalias)
// CHECK-LOAD: [[MUL:%.+]] = mul nsw i32
// CHECK-LOAD-NEXT: store i32 [[MUL]], i32*
// CHECK-LOAD-NEXT: ret void
// CHECK-LOAD-NEXT: }
// CHECK-LOAD: define internal {{.*}}void @{{[^(]+}}(i8* noalias, i8* noalias)
// CHECK-LOAD: sext i8
// CHECK-LOAD: sext i8
// CHECK-LOAD: [[MUL:%.+]] = mul nsw i32
// CHECK-LOAD-NEXT: [[TRUNC:%.+]] = trunc i32 [[MUL]] to i8
// CHECK-LOAD-NEXT: store i8 [[TRUNC]], i8*
// CHECK-LOAD-NEXT: ret void
// CHECK-LOAD-NEXT: }
#endif
|
GB_unaryop__minv_uint32_int32.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_int32
// op(A') function: GB_tran__minv_uint32_int32
// C type: uint32_t
// A type: int32_t
// cast: uint32_t cij = (uint32_t) aij
// unaryop: cij = GB_IMINV_UNSIGNED (aij, 32)
#define GB_ATYPE \
int32_t
#define GB_CTYPE \
uint32_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_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_INT32)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop__minv_uint32_int32
(
uint32_t *restrict Cx,
const int32_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_int32
(
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
|
aggregation_move_generator.h | /*****************************************************************************/
// Copyright (c) 2020-2021 Yuji KOGUMA
// Released under the MIT license
// https://opensource.org/licenses/mit-license.php
/*****************************************************************************/
#ifndef PRINTEMPS_NEIGHBORHOOD_AGGREGATION_MOVE_GENERATOR_H__
#define PRINTEMPS_NEIGHBORHOOD_AGGREGATION_MOVE_GENERATOR_H__
#include "abstract_move_generator.h"
namespace printemps {
namespace neighborhood {
/*****************************************************************************/
template <class T_Variable, class T_Expression>
class AggregationMoveGenerator
: public AbstractMoveGenerator<T_Variable, T_Expression> {
private:
public:
/*************************************************************************/
AggregationMoveGenerator(void) {
/// nothing to do
}
/*************************************************************************/
virtual ~AggregationMoveGenerator(void) {
/// nothing to do
}
/*************************************************************************/
void setup(const std::vector<model_component::Constraint<
T_Variable, T_Expression> *> &a_RAW_CONSTRAINT_PTRS) {
/**
* Exclude constraints which contain fixed variables or selection
* variables.
*/
auto constraint_ptrs =
extract_effective_constraint_ptrs(a_RAW_CONSTRAINT_PTRS);
/**
* Convert constraint objects to BinomialConstraint objects.
*/
auto binomials = convert_to_binomial_constraints(constraint_ptrs);
/**
* Setup move objects.
*/
const int BINOMIALS_SIZE = binomials.size();
this->m_moves.resize(4 * BINOMIALS_SIZE);
this->m_flags.resize(4 * BINOMIALS_SIZE);
for (auto i = 0; i < BINOMIALS_SIZE; i++) {
this->m_moves[4 * i].sense = MoveSense::Aggregation;
this->m_moves[4 * i].alterations.emplace_back(
binomials[i].variable_ptr_first, 0);
this->m_moves[4 * i].alterations.emplace_back(
binomials[i].variable_ptr_second, 0);
this->m_moves[4 * i].is_univariable_move = false;
utility::update_union_set(
&(this->m_moves[4 * i].related_constraint_ptrs),
binomials[i].variable_ptr_first->related_constraint_ptrs());
utility::update_union_set(
&(this->m_moves[4 * i].related_constraint_ptrs),
binomials[i].variable_ptr_second->related_constraint_ptrs());
this->m_moves[4 * i].is_special_neighborhood_move = true;
this->m_moves[4 * i].is_available = true;
this->m_moves[4 * i].overlap_rate = 0.0;
this->m_moves[4 * i + 1] = this->m_moves[4 * i];
this->m_moves[4 * i + 2] = this->m_moves[4 * i];
this->m_moves[4 * i + 3] = this->m_moves[4 * i];
}
/**
* Setup move updater.
*/
auto move_updater = //
[this, binomials, BINOMIALS_SIZE](
auto * a_moves, //
auto * a_flags, //
const bool a_ACCEPT_ALL, //
const bool a_ACCEPT_OBJECTIVE_IMPROVABLE, //
const bool a_ACCEPT_FEASIBILITY_IMPROVABLE, //
[[maybe_unused]] const bool a_IS_ENABLED_PARALLEL) {
#ifdef _OPENMP
#pragma omp parallel for if (a_IS_ENABLED_PARALLEL) schedule(static)
#endif
for (auto i = 0; i < BINOMIALS_SIZE; i++) {
{
auto index = 4 * i;
auto &alterations = (*a_moves)[index].alterations;
alterations[0].second =
binomials[i].variable_ptr_first->value() + 1;
alterations[1].second =
static_cast<T_Variable>(std::floor(
(-binomials[i].constant_value -
binomials[i].sensitivity_first *
(binomials[i].variable_ptr_first->value() +
1)) /
binomials[i].sensitivity_second +
0.5));
}
{
auto index = 4 * i + 1;
auto &alterations = (*a_moves)[index].alterations;
alterations[0].second =
binomials[i].variable_ptr_first->value() - 1;
alterations[1].second =
static_cast<T_Variable>(std::floor(
(-binomials[i].constant_value -
binomials[i].sensitivity_first *
(binomials[i].variable_ptr_first->value() -
1)) /
binomials[i].sensitivity_second +
0.5));
}
{
auto index = 4 * i + 2;
auto &alterations = (*a_moves)[index].alterations;
alterations[0]
.second = static_cast<T_Variable>(std::floor(
(-binomials[i].constant_value -
binomials[i].sensitivity_second *
(binomials[i].variable_ptr_second->value() +
1)) /
binomials[i].sensitivity_first +
0.5));
alterations[1].second =
binomials[i].variable_ptr_second->value() + 1;
}
{
auto index = 4 * i + 3;
auto &alterations = (*a_moves)[index].alterations;
alterations[0]
.second = static_cast<T_Variable>(std::floor(
(-binomials[i].constant_value -
binomials[i].sensitivity_second *
(binomials[i].variable_ptr_second->value() -
1)) /
binomials[i].sensitivity_first +
0.5));
alterations[1].second =
binomials[i].variable_ptr_second->value() - 1;
}
}
const int MOVES_SIZE = a_moves->size();
#ifdef _OPENMP
#pragma omp parallel for if (a_IS_ENABLED_PARALLEL) schedule(static)
#endif
for (auto i = 0; i < MOVES_SIZE; i++) {
(*a_flags)[i] = 1;
if (!(*a_moves)[i].is_available) {
(*a_flags)[i] = 0;
continue;
}
if (neighborhood::has_fixed_variable((*a_moves)[i])) {
(*a_flags)[i] = 0;
continue;
}
if (neighborhood::has_bound_violation((*a_moves)[i])) {
(*a_flags)[i] = 0;
continue;
}
if (a_ACCEPT_ALL) {
/** nothing to do */
} else {
if (a_ACCEPT_OBJECTIVE_IMPROVABLE &&
neighborhood::has_objective_improvable_variable(
(*a_moves)[i])) {
continue;
}
if (a_ACCEPT_FEASIBILITY_IMPROVABLE &&
neighborhood::has_feasibility_improvable_variable(
(*a_moves)[i])) {
continue;
}
(*a_flags)[i] = 0;
}
}
};
this->m_move_updater = move_updater;
}
};
} // namespace neighborhood
} // namespace printemps
#endif
/*****************************************************************************/
// END
/*****************************************************************************/ |
HYPRE_IJMatrix.c | /******************************************************************************
* Copyright 1998-2019 Lawrence Livermore National Security, LLC and other
* HYPRE Project Developers. See the top-level COPYRIGHT file for details.
*
* SPDX-License-Identifier: (Apache-2.0 OR MIT)
******************************************************************************/
/******************************************************************************
*
* HYPRE_IJMatrix interface
*
*****************************************************************************/
#include "./_hypre_IJ_mv.h"
#include "../HYPRE.h"
/*--------------------------------------------------------------------------
* HYPRE_IJMatrixCreate
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_IJMatrixCreate( MPI_Comm comm,
HYPRE_BigInt ilower,
HYPRE_BigInt iupper,
HYPRE_BigInt jlower,
HYPRE_BigInt jupper,
HYPRE_IJMatrix *matrix )
{
HYPRE_BigInt *row_partitioning;
HYPRE_BigInt *col_partitioning;
HYPRE_BigInt *info;
HYPRE_Int num_procs;
HYPRE_Int myid;
hypre_IJMatrix *ijmatrix;
HYPRE_BigInt row0, col0, rowN, colN;
ijmatrix = hypre_CTAlloc(hypre_IJMatrix, 1, HYPRE_MEMORY_HOST);
hypre_IJMatrixComm(ijmatrix) = comm;
hypre_IJMatrixObject(ijmatrix) = NULL;
hypre_IJMatrixTranslator(ijmatrix) = NULL;
hypre_IJMatrixAssumedPart(ijmatrix) = NULL;
hypre_IJMatrixObjectType(ijmatrix) = HYPRE_UNITIALIZED;
hypre_IJMatrixAssembleFlag(ijmatrix) = 0;
hypre_IJMatrixPrintLevel(ijmatrix) = 0;
hypre_IJMatrixOMPFlag(ijmatrix) = 0;
hypre_MPI_Comm_size(comm,&num_procs);
hypre_MPI_Comm_rank(comm, &myid);
if (ilower > iupper+1 || ilower < 0)
{
hypre_error_in_arg(2);
hypre_TFree(ijmatrix, HYPRE_MEMORY_HOST);
return hypre_error_flag;
}
if (iupper < -1)
{
hypre_error_in_arg(3);
hypre_TFree(ijmatrix, HYPRE_MEMORY_HOST);
return hypre_error_flag;
}
if (jlower > jupper+1 || jlower < 0)
{
hypre_error_in_arg(4);
hypre_TFree(ijmatrix, HYPRE_MEMORY_HOST);
return hypre_error_flag;
}
if (jupper < -1)
{
hypre_error_in_arg(5);
hypre_TFree(ijmatrix, HYPRE_MEMORY_HOST);
return hypre_error_flag;
}
info = hypre_CTAlloc(HYPRE_BigInt, 2, HYPRE_MEMORY_HOST);
row_partitioning = hypre_CTAlloc(HYPRE_BigInt, 2, HYPRE_MEMORY_HOST);
col_partitioning = hypre_CTAlloc(HYPRE_BigInt, 2, HYPRE_MEMORY_HOST);
row_partitioning[0] = ilower;
row_partitioning[1] = iupper+1;
col_partitioning[0] = jlower;
col_partitioning[1] = jupper+1;
/* now we need the global number of rows and columns as well
as the global first row and column index */
/* proc 0 has the first row and col */
if (myid == 0)
{
info[0] = ilower;
info[1] = jlower;
}
hypre_MPI_Bcast(info, 2, HYPRE_MPI_BIG_INT, 0, comm);
row0 = info[0];
col0 = info[1];
/* proc (num_procs-1) has the last row and col */
if (myid == (num_procs-1))
{
info[0] = iupper;
info[1] = jupper;
}
hypre_MPI_Bcast(info, 2, HYPRE_MPI_BIG_INT, num_procs-1, comm);
rowN = info[0];
colN = info[1];
hypre_IJMatrixGlobalFirstRow(ijmatrix) = row0;
hypre_IJMatrixGlobalFirstCol(ijmatrix) = col0;
hypre_IJMatrixGlobalNumRows(ijmatrix) = rowN - row0 + 1;
hypre_IJMatrixGlobalNumCols(ijmatrix) = colN - col0 + 1;
hypre_TFree(info, HYPRE_MEMORY_HOST);
hypre_IJMatrixRowPartitioning(ijmatrix) = row_partitioning;
hypre_IJMatrixColPartitioning(ijmatrix) = col_partitioning;
*matrix = (HYPRE_IJMatrix) ijmatrix;
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_IJMatrixDestroy( HYPRE_IJMatrix matrix )
{
hypre_IJMatrix *ijmatrix = (hypre_IJMatrix *) matrix;
if (!ijmatrix)
{
hypre_error_in_arg(1);
return hypre_error_flag;
}
if (ijmatrix)
{
if (hypre_IJMatrixRowPartitioning(ijmatrix) ==
hypre_IJMatrixColPartitioning(ijmatrix))
{
hypre_TFree(hypre_IJMatrixRowPartitioning(ijmatrix), HYPRE_MEMORY_HOST);
}
else
{
hypre_TFree(hypre_IJMatrixRowPartitioning(ijmatrix), HYPRE_MEMORY_HOST);
hypre_TFree(hypre_IJMatrixColPartitioning(ijmatrix), HYPRE_MEMORY_HOST);
}
if hypre_IJMatrixAssumedPart(ijmatrix)
{
hypre_AssumedPartitionDestroy((hypre_IJAssumedPart*)hypre_IJMatrixAssumedPart(ijmatrix));
}
if ( hypre_IJMatrixObjectType(ijmatrix) == HYPRE_PARCSR )
{
hypre_IJMatrixDestroyParCSR( ijmatrix );
}
else if ( hypre_IJMatrixObjectType(ijmatrix) != -1 )
{
hypre_error_in_arg(1);
return hypre_error_flag;
}
}
hypre_TFree(ijmatrix, HYPRE_MEMORY_HOST);
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_IJMatrixInitialize( HYPRE_IJMatrix matrix )
{
hypre_IJMatrix *ijmatrix = (hypre_IJMatrix *) matrix;
if (!ijmatrix)
{
hypre_error_in_arg(1);
return hypre_error_flag;
}
if ( hypre_IJMatrixObjectType(ijmatrix) == HYPRE_PARCSR )
{
hypre_IJMatrixInitializeParCSR( ijmatrix ) ;
}
else
{
hypre_error_in_arg(1);
}
return hypre_error_flag;
}
HYPRE_Int
HYPRE_IJMatrixInitialize_v2( HYPRE_IJMatrix matrix, HYPRE_MemoryLocation memory_location )
{
hypre_IJMatrix *ijmatrix = (hypre_IJMatrix *) matrix;
if (!ijmatrix)
{
hypre_error_in_arg(1);
return hypre_error_flag;
}
if ( hypre_IJMatrixObjectType(ijmatrix) == HYPRE_PARCSR )
{
hypre_IJMatrixInitializeParCSR_v2( ijmatrix, memory_location ) ;
}
else
{
hypre_error_in_arg(1);
}
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_IJMatrixSetPrintLevel( HYPRE_IJMatrix matrix,
HYPRE_Int print_level )
{
hypre_IJMatrix *ijmatrix = (hypre_IJMatrix *) matrix;
if (!ijmatrix)
{
hypre_error_in_arg(1);
return hypre_error_flag;
}
hypre_IJMatrixPrintLevel(ijmatrix) = 1;
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
* This is a helper routine to compute a prefix sum of integer values.
*
* The current implementation is okay for modest numbers of threads.
*--------------------------------------------------------------------------*/
HYPRE_Int
hypre_PrefixSumInt(HYPRE_Int nvals,
HYPRE_Int *vals,
HYPRE_Int *sums)
{
HYPRE_Int j, nthreads, bsize;
nthreads = hypre_NumThreads();
bsize = (nvals + nthreads - 1) / nthreads; /* This distributes the remainder */
if (nvals < nthreads || bsize == 1)
{
sums[0] = 0;
for (j=1; j < nvals; j++)
sums[j] += sums[j-1] + vals[j-1];
}
else
{
/* Compute preliminary partial sums (in parallel) within each interval */
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(j) HYPRE_SMP_SCHEDULE
#endif
for (j = 0; j < nvals; j += bsize)
{
HYPRE_Int i, n = hypre_min((j+bsize), nvals);
sums[0] = 0;
for (i = j+1; i < n; i++)
{
sums[i] = sums[i-1] + vals[i-1];
}
}
/* Compute final partial sums (in serial) for the first entry of every interval */
for (j = bsize; j < nvals; j += bsize)
{
sums[j] = sums[j-bsize] + sums[j-1] + vals[j-1];
}
/* Compute final partial sums (in parallel) for the remaining entries */
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(j) HYPRE_SMP_SCHEDULE
#endif
for (j = bsize; j < nvals; j += bsize)
{
HYPRE_Int i, n = hypre_min((j+bsize), nvals);
for (i = j+1; i < n; i++)
{
sums[i] += sums[j];
}
}
}
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_IJMatrixSetValues( HYPRE_IJMatrix matrix,
HYPRE_Int nrows,
HYPRE_Int *ncols,
const HYPRE_BigInt *rows,
const HYPRE_BigInt *cols,
const HYPRE_Complex *values )
{
hypre_IJMatrix *ijmatrix = (hypre_IJMatrix *) matrix;
if (nrows == 0)
{
return hypre_error_flag;
}
if (!ijmatrix)
{
hypre_error_in_arg(1);
return hypre_error_flag;
}
/*
if (!ncols)
{
hypre_error_in_arg(3);
return hypre_error_flag;
}
*/
if (!rows)
{
hypre_error_in_arg(4);
return hypre_error_flag;
}
if (!cols)
{
hypre_error_in_arg(5);
return hypre_error_flag;
}
if (!values)
{
hypre_error_in_arg(6);
return hypre_error_flag;
}
if ( hypre_IJMatrixObjectType(ijmatrix) != HYPRE_PARCSR )
{
hypre_error_in_arg(1);
return hypre_error_flag;
}
HYPRE_IJMatrixSetValues2(matrix, nrows, ncols, rows, NULL, cols, values);
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_IJMatrixSetValues2( HYPRE_IJMatrix matrix,
HYPRE_Int nrows,
HYPRE_Int *ncols,
const HYPRE_BigInt *rows,
const HYPRE_Int *row_indexes,
const HYPRE_BigInt *cols,
const HYPRE_Complex *values )
{
hypre_IJMatrix *ijmatrix = (hypre_IJMatrix *) matrix;
if (nrows == 0)
{
return hypre_error_flag;
}
if (!ijmatrix)
{
hypre_error_in_arg(1);
return hypre_error_flag;
}
if (nrows < 0)
{
hypre_error_in_arg(2);
return hypre_error_flag;
}
/*
if (!ncols)
{
hypre_error_in_arg(3);
return hypre_error_flag;
}
*/
if (!rows)
{
hypre_error_in_arg(4);
return hypre_error_flag;
}
if (!cols)
{
hypre_error_in_arg(6);
return hypre_error_flag;
}
if (!values)
{
hypre_error_in_arg(7);
return hypre_error_flag;
}
if ( hypre_IJMatrixObjectType(ijmatrix) != HYPRE_PARCSR )
{
hypre_error_in_arg(1);
return hypre_error_flag;
}
#if defined(HYPRE_USING_CUDA) || defined(HYPRE_USING_HIP)
HYPRE_ExecutionPolicy exec = hypre_GetExecPolicy1( hypre_IJMatrixMemoryLocation(matrix) );
if (exec == HYPRE_EXEC_DEVICE)
{
hypre_IJMatrixSetAddValuesParCSRDevice(ijmatrix, nrows, ncols, rows, row_indexes, cols, values, "set");
}
else
#endif
{
HYPRE_Int *row_indexes_tmp = (HYPRE_Int *) row_indexes;
HYPRE_Int *ncols_tmp = ncols;
if (!ncols_tmp)
{
HYPRE_Int i;
ncols_tmp = hypre_TAlloc(HYPRE_Int, nrows, HYPRE_MEMORY_HOST);
for (i = 0; i < nrows; i++)
{
ncols_tmp[i] = 1;
}
}
if (!row_indexes)
{
row_indexes_tmp = hypre_CTAlloc(HYPRE_Int, nrows, HYPRE_MEMORY_HOST);
hypre_PrefixSumInt(nrows, ncols_tmp, row_indexes_tmp);
}
if (hypre_IJMatrixOMPFlag(ijmatrix))
{
hypre_IJMatrixSetValuesOMPParCSR(ijmatrix, nrows, ncols_tmp, rows, row_indexes_tmp, cols, values);
}
else
{
hypre_IJMatrixSetValuesParCSR(ijmatrix, nrows, ncols_tmp, rows, row_indexes_tmp, cols, values);
}
if (!ncols)
{
hypre_TFree(ncols_tmp, HYPRE_MEMORY_HOST);
}
if (!row_indexes)
{
hypre_TFree(row_indexes_tmp, HYPRE_MEMORY_HOST);
}
}
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_IJMatrixSetConstantValues( HYPRE_IJMatrix matrix, HYPRE_Complex value)
{
hypre_IJMatrix *ijmatrix = (hypre_IJMatrix *) matrix;
if (!ijmatrix)
{
hypre_error_in_arg(1);
return hypre_error_flag;
}
if ( hypre_IJMatrixObjectType(ijmatrix) == HYPRE_PARCSR )
{
return( hypre_IJMatrixSetConstantValuesParCSR( ijmatrix, value));
}
else
{
hypre_error_in_arg(1);
}
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_IJMatrixAddToValues( HYPRE_IJMatrix matrix,
HYPRE_Int nrows,
HYPRE_Int *ncols,
const HYPRE_BigInt *rows,
const HYPRE_BigInt *cols,
const HYPRE_Complex *values )
{
hypre_IJMatrix *ijmatrix = (hypre_IJMatrix *) matrix;
if (nrows == 0)
{
return hypre_error_flag;
}
if (!ijmatrix)
{
hypre_error_in_arg(1);
return hypre_error_flag;
}
if (nrows < 0)
{
hypre_error_in_arg(2);
return hypre_error_flag;
}
/*
if (!ncols)
{
hypre_error_in_arg(3);
return hypre_error_flag;
}
*/
if (!rows)
{
hypre_error_in_arg(4);
return hypre_error_flag;
}
if (!cols)
{
hypre_error_in_arg(5);
return hypre_error_flag;
}
if (!values)
{
hypre_error_in_arg(6);
return hypre_error_flag;
}
if ( hypre_IJMatrixObjectType(ijmatrix) != HYPRE_PARCSR )
{
hypre_error_in_arg(1);
return hypre_error_flag;
}
HYPRE_IJMatrixAddToValues2(matrix, nrows, ncols, rows, NULL, cols, values);
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_IJMatrixAddToValues2( HYPRE_IJMatrix matrix,
HYPRE_Int nrows,
HYPRE_Int *ncols,
const HYPRE_BigInt *rows,
const HYPRE_Int *row_indexes,
const HYPRE_BigInt *cols,
const HYPRE_Complex *values )
{
hypre_IJMatrix *ijmatrix = (hypre_IJMatrix *) matrix;
if (nrows == 0)
{
return hypre_error_flag;
}
if (!ijmatrix)
{
hypre_error_in_arg(1);
return hypre_error_flag;
}
if (nrows < 0)
{
hypre_error_in_arg(2);
return hypre_error_flag;
}
/*
if (!ncols)
{
hypre_error_in_arg(3);
return hypre_error_flag;
}
*/
if (!rows)
{
hypre_error_in_arg(4);
return hypre_error_flag;
}
if (!cols)
{
hypre_error_in_arg(6);
return hypre_error_flag;
}
if (!values)
{
hypre_error_in_arg(7);
return hypre_error_flag;
}
if ( hypre_IJMatrixObjectType(ijmatrix) != HYPRE_PARCSR )
{
hypre_error_in_arg(1);
return hypre_error_flag;
}
#if defined(HYPRE_USING_CUDA) || defined(HYPRE_USING_HIP)
HYPRE_ExecutionPolicy exec = hypre_GetExecPolicy1( hypre_IJMatrixMemoryLocation(matrix) );
if (exec == HYPRE_EXEC_DEVICE)
{
hypre_IJMatrixSetAddValuesParCSRDevice(ijmatrix, nrows, ncols, rows, row_indexes, cols, values, "add");
}
else
#endif
{
HYPRE_Int *row_indexes_tmp = (HYPRE_Int *) row_indexes;
HYPRE_Int *ncols_tmp = ncols;
if (!ncols_tmp)
{
HYPRE_Int i;
ncols_tmp = hypre_TAlloc(HYPRE_Int, nrows, HYPRE_MEMORY_HOST);
for (i = 0; i < nrows; i++)
{
ncols_tmp[i] = 1;
}
}
if (!row_indexes)
{
row_indexes_tmp = hypre_CTAlloc(HYPRE_Int, nrows, HYPRE_MEMORY_HOST);
hypre_PrefixSumInt(nrows, ncols_tmp, row_indexes_tmp);
}
if (hypre_IJMatrixOMPFlag(ijmatrix))
{
hypre_IJMatrixAddToValuesOMPParCSR(ijmatrix, nrows, ncols_tmp, rows, row_indexes_tmp, cols, values);
}
else
{
hypre_IJMatrixAddToValuesParCSR(ijmatrix, nrows, ncols_tmp, rows, row_indexes_tmp, cols, values);
}
if (!ncols)
{
hypre_TFree(ncols_tmp, HYPRE_MEMORY_HOST);
}
if (!row_indexes)
{
hypre_TFree(row_indexes_tmp, HYPRE_MEMORY_HOST);
}
}
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_IJMatrixAssemble( HYPRE_IJMatrix matrix )
{
hypre_IJMatrix *ijmatrix = (hypre_IJMatrix *) matrix;
if (!ijmatrix)
{
hypre_error_in_arg(1);
return hypre_error_flag;
}
if ( hypre_IJMatrixObjectType(ijmatrix) == HYPRE_PARCSR )
{
#if defined(HYPRE_USING_CUDA) || defined(HYPRE_USING_HIP)
HYPRE_ExecutionPolicy exec = hypre_GetExecPolicy1( hypre_IJMatrixMemoryLocation(matrix) );
if (exec == HYPRE_EXEC_DEVICE)
{
return( hypre_IJMatrixAssembleParCSRDevice( ijmatrix ) );
}
else
#endif
{
return( hypre_IJMatrixAssembleParCSR( ijmatrix ) );
}
}
else
{
hypre_error_in_arg(1);
}
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_IJMatrixGetRowCounts( HYPRE_IJMatrix matrix,
HYPRE_Int nrows,
HYPRE_BigInt *rows,
HYPRE_Int *ncols )
{
hypre_IJMatrix *ijmatrix = (hypre_IJMatrix *) matrix;
if (nrows == 0)
{
return hypre_error_flag;
}
if (!ijmatrix)
{
hypre_error_in_arg(1);
return hypre_error_flag;
}
if (nrows < 0)
{
hypre_error_in_arg(2);
return hypre_error_flag;
}
if (!rows)
{
hypre_error_in_arg(3);
return hypre_error_flag;
}
if (!ncols)
{
hypre_error_in_arg(4);
return hypre_error_flag;
}
if ( hypre_IJMatrixObjectType(ijmatrix) == HYPRE_PARCSR )
{
hypre_IJMatrixGetRowCountsParCSR( ijmatrix, nrows, rows, ncols );
}
else
{
hypre_error_in_arg(1);
}
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_IJMatrixGetValues( HYPRE_IJMatrix matrix,
HYPRE_Int nrows,
HYPRE_Int *ncols,
HYPRE_BigInt *rows,
HYPRE_BigInt *cols,
HYPRE_Complex *values )
{
hypre_IJMatrix *ijmatrix = (hypre_IJMatrix *) matrix;
if (nrows == 0)
{
return hypre_error_flag;
}
if (!ijmatrix)
{
hypre_error_in_arg(1);
return hypre_error_flag;
}
if (!ncols)
{
hypre_error_in_arg(3);
return hypre_error_flag;
}
if (!rows)
{
hypre_error_in_arg(4);
return hypre_error_flag;
}
if (!cols)
{
hypre_error_in_arg(5);
return hypre_error_flag;
}
if (!values)
{
hypre_error_in_arg(6);
return hypre_error_flag;
}
if ( hypre_IJMatrixObjectType(ijmatrix) == HYPRE_PARCSR )
{
hypre_IJMatrixGetValuesParCSR( ijmatrix, nrows, ncols,
rows, cols, values );
}
else
{
hypre_error_in_arg(1);
}
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_IJMatrixSetObjectType( HYPRE_IJMatrix matrix,
HYPRE_Int type )
{
hypre_IJMatrix *ijmatrix = (hypre_IJMatrix *) matrix;
if (!ijmatrix)
{
hypre_error_in_arg(1);
return hypre_error_flag;
}
hypre_IJMatrixObjectType(ijmatrix) = type;
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_IJMatrixGetObjectType( HYPRE_IJMatrix matrix,
HYPRE_Int *type )
{
hypre_IJMatrix *ijmatrix = (hypre_IJMatrix *) matrix;
if (!ijmatrix)
{
hypre_error_in_arg(1);
return hypre_error_flag;
}
*type = hypre_IJMatrixObjectType(ijmatrix);
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_IJMatrixGetLocalRange( HYPRE_IJMatrix matrix,
HYPRE_BigInt *ilower,
HYPRE_BigInt *iupper,
HYPRE_BigInt *jlower,
HYPRE_BigInt *jupper )
{
hypre_IJMatrix *ijmatrix = (hypre_IJMatrix *) matrix;
MPI_Comm comm;
HYPRE_BigInt *row_partitioning;
HYPRE_BigInt *col_partitioning;
HYPRE_Int my_id;
if (!ijmatrix)
{
hypre_error_in_arg(1);
return hypre_error_flag;
}
comm = hypre_IJMatrixComm(ijmatrix);
row_partitioning = hypre_IJMatrixRowPartitioning(ijmatrix);
col_partitioning = hypre_IJMatrixColPartitioning(ijmatrix);
hypre_MPI_Comm_rank(comm, &my_id);
*ilower = row_partitioning[0];
*iupper = row_partitioning[1]-1;
*jlower = col_partitioning[0];
*jupper = col_partitioning[1]-1;
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
*--------------------------------------------------------------------------*/
/**
Returns a pointer to an underlying ijmatrix type used to implement IJMatrix.
Assumes that the implementation has an underlying matrix, so it would not
work with a direct implementation of IJMatrix.
@return integer error code
@param IJMatrix [IN]
The ijmatrix to be pointed to.
*/
HYPRE_Int
HYPRE_IJMatrixGetObject( HYPRE_IJMatrix matrix,
void **object )
{
hypre_IJMatrix *ijmatrix = (hypre_IJMatrix *) matrix;
if (!ijmatrix)
{
hypre_error_in_arg(1);
return hypre_error_flag;
}
*object = hypre_IJMatrixObject( ijmatrix );
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_IJMatrixSetRowSizes( HYPRE_IJMatrix matrix,
const HYPRE_Int *sizes )
{
hypre_IJMatrix *ijmatrix = (hypre_IJMatrix *) matrix;
if (!ijmatrix)
{
hypre_error_in_arg(1);
return hypre_error_flag;
}
if ( hypre_IJMatrixObjectType(ijmatrix) == HYPRE_PARCSR )
{
return( hypre_IJMatrixSetRowSizesParCSR( ijmatrix , sizes ) );
}
else
{
hypre_error_in_arg(1);
}
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_IJMatrixSetDiagOffdSizes( HYPRE_IJMatrix matrix,
const HYPRE_Int *diag_sizes,
const HYPRE_Int *offdiag_sizes )
{
hypre_IJMatrix *ijmatrix = (hypre_IJMatrix *) matrix;
if (!ijmatrix)
{
hypre_error_in_arg(1);
return hypre_error_flag;
}
if ( hypre_IJMatrixObjectType(ijmatrix) == HYPRE_PARCSR )
{
hypre_IJMatrixSetDiagOffdSizesParCSR( ijmatrix, diag_sizes, offdiag_sizes );
}
else
{
hypre_error_in_arg(1);
}
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_IJMatrixSetMaxOffProcElmts( HYPRE_IJMatrix matrix,
HYPRE_Int max_off_proc_elmts)
{
hypre_IJMatrix *ijmatrix = (hypre_IJMatrix *) matrix;
if (!ijmatrix)
{
hypre_error_in_arg(1);
return hypre_error_flag;
}
if ( hypre_IJMatrixObjectType(ijmatrix) == HYPRE_PARCSR )
{
return( hypre_IJMatrixSetMaxOffProcElmtsParCSR(ijmatrix,
max_off_proc_elmts) );
}
else
{
hypre_error_in_arg(1);
}
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
* HYPRE_IJMatrixRead
* create IJMatrix on host memory
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_IJMatrixRead( const char *filename,
MPI_Comm comm,
HYPRE_Int type,
HYPRE_IJMatrix *matrix_ptr )
{
HYPRE_IJMatrix matrix;
HYPRE_BigInt ilower, iupper, jlower, jupper;
HYPRE_BigInt I, J;
HYPRE_Int ncols;
HYPRE_Complex value;
HYPRE_Int myid, ret;
char new_filename[255];
FILE *file;
hypre_MPI_Comm_rank(comm, &myid);
hypre_sprintf(new_filename,"%s.%05d", filename, myid);
if ((file = fopen(new_filename, "r")) == NULL)
{
hypre_error_in_arg(1);
return hypre_error_flag;
}
hypre_fscanf(file, "%b %b %b %b", &ilower, &iupper, &jlower, &jupper);
HYPRE_IJMatrixCreate(comm, ilower, iupper, jlower, jupper, &matrix);
HYPRE_IJMatrixSetObjectType(matrix, type);
HYPRE_IJMatrixInitialize_v2(matrix, HYPRE_MEMORY_HOST);
/* It is important to ensure that whitespace follows the index value to help
* catch mistakes in the input file. See comments in IJVectorRead(). */
ncols = 1;
while ( (ret = hypre_fscanf(file, "%b %b%*[ \t]%le", &I, &J, &value)) != EOF )
{
if (ret != 3)
{
hypre_error_w_msg(HYPRE_ERROR_GENERIC, "Error in IJ matrix input file.");
return hypre_error_flag;
}
if (I < ilower || I > iupper)
{
HYPRE_IJMatrixAddToValues(matrix, 1, &ncols, &I, &J, &value);
}
else
{
HYPRE_IJMatrixSetValues(matrix, 1, &ncols, &I, &J, &value);
}
}
HYPRE_IJMatrixAssemble(matrix);
fclose(file);
*matrix_ptr = matrix;
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
* HYPRE_IJMatrixPrint
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_IJMatrixPrint( HYPRE_IJMatrix matrix,
const char *filename )
{
if (!matrix)
{
hypre_error_in_arg(1);
return hypre_error_flag;
}
if ( (hypre_IJMatrixObjectType(matrix) != HYPRE_PARCSR) )
{
hypre_error_in_arg(1);
return hypre_error_flag;
}
void *object;
HYPRE_IJMatrixGetObject(matrix, &object);
HYPRE_ParCSRMatrix par_csr = (HYPRE_ParCSRMatrix) object;
HYPRE_MemoryLocation memory_location = hypre_IJMatrixMemoryLocation(matrix);
if ( hypre_GetActualMemLocation(memory_location) == hypre_MEMORY_HOST )
{
hypre_ParCSRMatrixPrintIJ(par_csr, 0, 0, filename);
}
else
{
HYPRE_ParCSRMatrix par_csr2 = hypre_ParCSRMatrixClone_v2(par_csr, 1, HYPRE_MEMORY_HOST);
hypre_ParCSRMatrixPrintIJ(par_csr2, 0, 0, filename);
hypre_ParCSRMatrixDestroy(par_csr2);
}
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
* HYPRE_IJMatrixSetOMPFlag
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_IJMatrixSetOMPFlag( HYPRE_IJMatrix matrix,
HYPRE_Int omp_flag )
{
hypre_IJMatrix *ijmatrix = (hypre_IJMatrix *) matrix;
if (!ijmatrix)
{
hypre_error_in_arg(1);
return hypre_error_flag;
}
hypre_IJMatrixOMPFlag(ijmatrix) = omp_flag;
return hypre_error_flag;
}
|
main.c | #include <stdio.h>
#include <stdlib.h>
#include <omp.h>
#include <time.h>
#include "../examples/openmp_dot_product/scalar/runner.h"
int getMove(double p, unsigned int* seed) {
return (rand_r(seed) / (double) RAND_MAX) < p ? -1 : 1;
}
struct context {
int a, b, x, N, P;
double p;
int result, lifetime;
};
void not_parallel_walk(void* ctx_void) {
struct context* ctx = (struct context*) ctx_void;
int result = 0;
int lifetime = 0;
unsigned int seed = (unsigned int) omp_get_thread_num() + (unsigned int) time(NULL);
printf("seed: %u\n", seed);
for (int j = 0; j < ctx->N; ++j) {
int S = ctx->x;
for (int i = 0;; ++i) {
S += getMove(ctx->p, &seed);
//printf("%d ", S);
if (S == ctx->a || S == ctx->b) {
lifetime += i;
if (S == ctx->a) {
result -= 1;
} else if (S == ctx->b) {
result += 1;
}
break;
}
}
}
ctx->result = result;
ctx->lifetime = lifetime;
}
void parallel_walk(void* ctx_void) {
struct context* ctx = (struct context*) ctx_void;
int result = 0;
int lifetime = 0;
#pragma omp parallel num_threads(ctx->P)
{
//omp_set_num_threads(ctx->P);
unsigned int seed = (unsigned int) omp_get_thread_num() + (unsigned int) time(NULL);
printf("seed: %u\n", seed);
#pragma omp for reduction(+:result) reduction(+:lifetime)
for (int j = 0; j < ctx->N; ++j) {
int S = ctx->x;
for (int i = 0;; ++i) {
S += getMove(ctx->p, &seed);
if (S == ctx->a || S == ctx->b) {
lifetime += i;
if (S == ctx->a) {
result -= 1;
} else if (S == ctx->b) {
result += 1;
}
break;
}
}
}
}
ctx->result = result;
ctx->lifetime = lifetime;
}
int main(int args, char* argv[]) {
struct context ctx;
ctx.a = atoi(argv[1]);
ctx.b = atoi(argv[2]);
ctx.x = atoi(argv[3]);
ctx.N = atoi(argv[4]);
ctx.p = atof(argv[5]);
ctx.P = atoi(argv[6]);
double time;
if (ctx.P != 0) {
time = runner_run(parallel_walk, &ctx, "parallel walk");
} else {
time = runner_run(not_parallel_walk, &ctx, "not parallel walk");
}
FILE* out = fopen("stats.txt", "a+");
fprintf(out,
"%f %f %lfs %d %d %d %d %lf %d\n",
(ctx.result + ctx.N) / (double) (2 * ctx.N),
ctx.lifetime / (double) ctx.N,
time,
ctx.a,
ctx.b,
ctx.x,
ctx.N,
ctx.p,
ctx.P);
fclose(out);
return 0;
}
|
IcgL2Norm.c | // Copyright (C) 2016 Gernot Riegler
// Institute for Computer Graphics and Vision (ICG)
// Graz University of Technology (TU GRAZ)
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// 3. All advertising materials mentioning features or use of this software
// must display the following acknowledgement:
// This product includes software developed by the ICG, TU GRAZ.
// 4. Neither the name of the ICG, TU GRAZ 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 ''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 PROVIDER 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 TH_GENERIC_FILE
#define TH_GENERIC_FILE "generic/IcgL2Norm.c"
#else
static int icgnn_(IcgL2Norm_updateOutput)(lua_State *L) {
THTensor* in = luaT_checkudata(L, 2, torch_Tensor);
int spatial = luaT_getfieldcheckboolean(L, 1, "spatial");
THTensor* out = luaT_getfieldcheckudata(L, 1, "output", torch_Tensor);
long n_dim = in->nDimension;
luaL_argcheck(L, n_dim == 3 || n_dim == 4, 2, "3D or 4D(batch mode) tensor expected");
in = THTensor_(newContiguous)(in);
real* in_data = THTensor_(data)(in);
long num, channels, height, width, out_channels;
if(n_dim == 3) {
num = 1;
channels = in->size[0];
height = in->size[1];
width = in->size[2];
out_channels = spatial ? channels : 1;
THTensor_(resize3d)(out, out_channels, height, width);
}
else if(n_dim == 4) {
num = in->size[0];
channels = in->size[1];
height = in->size[2];
width = in->size[3];
out_channels = spatial ? channels : 1;
THTensor_(resize4d)(out, num, out_channels, height, width);
}
real* out_data = THTensor_(data)(out);
long n=0;
#pragma omp parallel for private(n)
for(n = 0; n < num; ++n) {
long h;
for(h = 0; h < height; ++h) {
long w;
for(w = 0; w < width; ++w) {
long c;
float out_val = 0;
for(c = 0; c < channels; ++c) {
long idx = ((n * channels + c) * height + h) * width + w;
real in_val = in_data[idx];
out_val = out_val + in_val * in_val;
}
out_val = sqrt(out_val);
for(c = 0; c < out_channels; ++c) {
long idx = ((n * out_channels + c) * height + h) * width + w;
out_data[idx] = out_val;
}
}
}
}
THTensor_(free)(in);
return 1;
}
static int icgnn_(IcgL2Norm_updateGradInput)(lua_State *L) {
THTensor *in = luaT_checkudata(L, 2, torch_Tensor);
THTensor *grad_out = luaT_checkudata(L, 3, torch_Tensor);
THTensor *out = luaT_getfieldcheckudata(L, 1, "output", torch_Tensor);
int spatial = luaT_getfieldcheckboolean(L, 1, "spatial");
real dft = luaT_getfieldchecknumber(L, 1, "dft");
THTensor *grad_in = luaT_getfieldcheckudata(L, 1, "gradInput", torch_Tensor);
THTensor_(resizeAs)(grad_in, in);
real* in_data = THTensor_(data)(in);
real* out_data = THTensor_(data)(out);
real* grad_in_data = THTensor_(data)(grad_in);
real* grad_out_data = THTensor_(data)(grad_out);
long n_dim = in->nDimension;
long num, channels, height, width;
if(n_dim == 3) {
num = 1;
channels = in->size[0];
height = in->size[1];
width = in->size[2];
}
else if(n_dim == 4) {
num = in->size[0];
channels = in->size[1];
height = in->size[2];
width = in->size[3];
}
long out_channels = spatial ? channels : 1;
long n;
#pragma omp parallel for private(n)
for(n = 0; n < num; ++n) {
long h;
for(h = 0; h < height; ++h) {
long w;
for(w = 0; w < width; ++w) {
long ci;
// float out_val = 0;
// for(ci = 0; ci < channels; ++ci) {
// long idx = ((n * channels + ci) * height + h) * width + w;
// real in_val = in_data[idx];
// out_val = out_val + in_val * in_val;
// }
// out_val = sqrt(out_val);
// out_val = out_val == 0 ? dft : out_val;
for(ci = 0; ci < channels; ++ci) {
long in_idx = ((n * channels + ci) * height + h) * width + w;
float grad_in_val = 0;
// printf("-------- %d/%d|%d/%d/%d --------\n", num, channels, out_channels, height, width);
long co;
for(co = 0; co < out_channels; ++co) {
long out_idx = ((n * out_channels + co) * height + h) * width + w;
real out_val = out_data[out_idx];
out_val = out_val == 0 ? dft : out_val;
grad_in_val = grad_in_val + (grad_out_data[out_idx] * in_data[in_idx] / out_val);
// printf(" @%d/%d|%d/%d/%d - %d/%d: %f * %f / %f \n",
// n, ci, co, h, w, in_idx, out_idx, grad_out_data[out_idx], in_data[in_idx], out_val);
}
grad_in_data[in_idx] = grad_in_val;
// printf(" = %f\n", grad_in_val);
}
}
}
}
return 1;
}
static const struct luaL_Reg icgnn_(IcgL2Norm__) [] = {
{"IcgL2Norm_updateOutput", icgnn_(IcgL2Norm_updateOutput)},
{"IcgL2Norm_updateGradInput", icgnn_(IcgL2Norm_updateGradInput)},
{NULL, NULL}
};
static void icgnn_(IcgL2Norm_init)(lua_State *L) {
luaT_pushmetatable(L, torch_Tensor);
luaT_registeratname(L, icgnn_(IcgL2Norm__), "icgnn");
lua_pop(L,1);
}
#endif
|
GB_binop__rminus_fp32.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__rminus_fp32)
// A.*B function (eWiseMult): GB (_AemultB_08__rminus_fp32)
// A.*B function (eWiseMult): GB (_AemultB_02__rminus_fp32)
// A.*B function (eWiseMult): GB (_AemultB_04__rminus_fp32)
// A.*B function (eWiseMult): GB (_AemultB_bitmap__rminus_fp32)
// A*D function (colscale): GB (_AxD__rminus_fp32)
// D*A function (rowscale): GB (_DxB__rminus_fp32)
// C+=B function (dense accum): GB (_Cdense_accumB__rminus_fp32)
// C+=b function (dense accum): GB (_Cdense_accumb__rminus_fp32)
// C+=A+B function (dense ewise3): GB (_Cdense_ewise3_accum__rminus_fp32)
// C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__rminus_fp32)
// C=scalar+B GB (_bind1st__rminus_fp32)
// C=scalar+B' GB (_bind1st_tran__rminus_fp32)
// C=A+scalar GB (_bind2nd__rminus_fp32)
// C=A'+scalar GB (_bind2nd_tran__rminus_fp32)
// C type: float
// A type: float
// A pattern? 0
// B type: float
// B pattern? 0
// BinaryOp: cij = (bij - aij)
#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,A_iso) \
float 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) \
float 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) \
float t
// cij = Ax [pA]
#define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \
cij = GBX (Ax, pA, A_iso)
// cij = Bx [pB]
#define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \
cij = GBX (Bx, pB, B_iso)
#define GB_CX(p) Cx [p]
// binary operator
#define GB_BINOP(z,x,y,i,j) \
z = (y - x) ;
// 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_RMINUS || GxB_NO_FP32 || GxB_NO_RMINUS_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__rminus_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
//------------------------------------------------------------------------------
void GB (_Cdense_ewise3_noaccum__rminus_fp32)
(
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__rminus_fp32)
(
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__rminus_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__rminus_fp32)
(
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
float *restrict Cx = (float *) 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__rminus_fp32)
(
GrB_Matrix C,
const GrB_Matrix D,
const GrB_Matrix B,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
float *restrict Cx = (float *) 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__rminus_fp32)
(
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) ;
float alpha_scalar ;
float beta_scalar ;
if (is_eWiseUnion)
{
alpha_scalar = (*((float *) alpha_scalar_in)) ;
beta_scalar = (*((float *) 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__rminus_fp32)
(
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__rminus_fp32)
(
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__rminus_fp32)
(
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__rminus_fp32)
(
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__rminus_fp32)
(
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
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 < bnz ; p++)
{
if (!GBB (Bb, p)) continue ;
float bij = GBX (Bx, p, false) ;
Cx [p] = (bij - x) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd
//------------------------------------------------------------------------------
GrB_Info GB (_bind2nd__rminus_fp32)
(
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 ;
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++)
{
if (!GBB (Ab, p)) continue ;
float aij = GBX (Ax, p, false) ;
Cx [p] = (y - aij) ;
}
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) \
{ \
float aij = GBX (Ax, pA, false) ; \
Cx [pC] = (aij - x) ; \
}
GrB_Info GB (_bind1st_tran__rminus_fp32)
(
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 \
float
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
float x = (*((const float *) x_input)) ;
#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 typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
float aij = GBX (Ax, pA, false) ; \
Cx [pC] = (y - aij) ; \
}
GrB_Info GB (_bind2nd_tran__rminus_fp32)
(
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
float y = (*((const float *) y_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
add.c | #include <stdio.h>
#include <omp.h>
int main(){
int A[10], B[10] = {0,1,2,3,4,5,6,7,8,9}, C[10] = {0,1,2,3,4,5,6,7,8,9}, i, m, k;
omp_set_dynamic(0);
m = omp_get_num_procs();
omp_set_num_threads(m);
printf("Parallel\n------------");
#pragma omp parallel for shared(A, B, C) private(i)
for(i = 0; i < 10; i++){
A[i] = B[i] + C[i];
printf("\nB[%d] + C[%d] = %d + %d = %d = A[%d] from thread %d of %d", i, i, B[i], C[i], A[i], i, omp_get_thread_num(), omp_get_num_threads());
}
return 0;
} |
alipfold.c | /* Last changed Time-stamp: <2009-02-24 14:37:05 ivo> */
/*
partiton function and base pair probabilities
for RNA secvondary structures
of a set of aligned sequences
Ivo L Hofacker
Vienna RNA package
*/
/**
*** \file alipfold.c
**/
#include <config.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <float.h> /* #defines FLT_MIN */
#include <limits.h>
#include "utils.h"
#include "energy_par.h"
#include "fold_vars.h"
#include "pair_mat.h"
#include "PS_dot.h"
#include "ribo.h"
#include "params.h"
#include "loop_energies.h"
#include "part_func.h"
#include "alifold.h"
#ifdef _OPENMP
#include <omp.h>
#endif
/*@unused@*/
static char rcsid[] = "$Id: alipfold.c,v 1.17 2009/02/24 14:21:33 ivo Exp $";
#define STACK_BULGE1 1 /* stacking energies for bulges of size 1 */
#define NEW_NINIO 1 /* new asymetry penalty */
#define ISOLATED 256.0
#define UNIT 100
#define MINPSCORE -2 * UNIT
#define PMIN 0.0008
/*
#################################
# PUBLIC GLOBAL VARIABLES #
#################################
*/
/*
#################################
# PRIVATE GLOBAL VARIABLES #
#################################
*/
PRIVATE FLT_OR_DBL *expMLbase=NULL;
PRIVATE FLT_OR_DBL *q=NULL, *qb=NULL, *qm=NULL, *qm1=NULL, *qqm=NULL, *qqm1=NULL, *qq=NULL, *qq1=NULL;
PRIVATE FLT_OR_DBL *prml=NULL, *prm_l=NULL, *prm_l1=NULL, *q1k=NULL, *qln=NULL;
PRIVATE FLT_OR_DBL *probs=NULL;
PRIVATE FLT_OR_DBL *scale=NULL;
PRIVATE short *pscore=NULL; /* precomputed array of covariance bonus/malus */
/* some additional things for circfold */
PRIVATE int circular=0;
PRIVATE FLT_OR_DBL qo, qho, qio, qmo, *qm2=NULL;
PRIVATE int *jindx=NULL;
PRIVATE int *my_iindx=NULL;
PRIVATE int do_bppm = 1; /* do backtracking per default */
PRIVATE short **S=NULL;
PRIVATE short **S5=NULL; /*S5[s][i] holds next base 5' of i in sequence s*/
PRIVATE short **S3=NULL; /*S3[s][i] holds next base 3' of i in sequence s*/
PRIVATE char **Ss=NULL;
PRIVATE unsigned short **a2s=NULL;
PRIVATE int N_seq = 0;
PRIVATE pf_paramT *pf_params = NULL;
PRIVATE char *pstruc=NULL;
PRIVATE double alpha = 1.0;
PRIVATE int struct_constrained = 0;
#ifdef _OPENMP
/* NOTE: all variables are assumed to be uninitialized if they are declared as threadprivate
*/
#pragma omp threadprivate(expMLbase, q, qb, qm, qm1, qqm, qqm1, qq, qq1,\
probs, prml, prm_l, prm_l1, q1k, qln,\
scale, pscore, circular,\
qo, qho, qio, qmo, qm2, jindx, my_iindx,\
S, S5, S3, Ss, a2s, N_seq, pf_params, pstruc, alpha, struct_constrained)
#endif
/*
#################################
# PRIVATE FUNCTION DECLARATIONS #
#################################
*/
PRIVATE void init_alipf_fold(int length, int n_seq, pf_paramT *parameters);
PRIVATE void scale_pf_params(unsigned int length, int n_seq, pf_paramT *parameters);
PRIVATE void get_arrays(unsigned int length);
PRIVATE void make_pscores(const short *const *S, const char **AS, int n_seq, const char *structure);
PRIVATE pair_info *make_pairinfo(const short *const* S, const char **AS, int n_seq);
PRIVATE void alipf_circ(const char **sequences, char *structure);
PRIVATE void alipf_linear(const char **sequences, char *structure);
PRIVATE void alipf_create_bppm(const char **sequences, char *structure, struct plist **pl);
PRIVATE void backtrack(int i, int j, int n_seq, double *prob);
PRIVATE void backtrack_qm1(int i,int j, int n_seq, double *prob);
/*
#################################
# BEGIN OF FUNCTION DEFINITIONS #
#################################
*/
PRIVATE void init_alipf_fold(int length, int n_seq, pf_paramT *parameters){
if (length<1) nrerror("init_alipf_fold: length must be greater 0");
#ifdef _OPENMP
/* Explicitly turn off dynamic threads */
omp_set_dynamic(0);
#endif
#ifdef SUN4
nonstandard_arithmetic();
#else
#ifdef HP9
fpsetfastmode(1);
#endif
#endif
make_pair_matrix();
free_alipf_arrays(); /* free previous allocation */
get_arrays((unsigned) length);
scale_pf_params((unsigned) length, n_seq, parameters);
}
/**
*** Allocate memory for all matrices and other stuff
**/
PRIVATE void get_arrays(unsigned int length){
unsigned int size,i;
if((length+1) >= (unsigned int)sqrt((double)INT_MAX))
nrerror("get_arrays@alipfold.c: sequence length exceeds addressable range");
size = sizeof(FLT_OR_DBL) * ((length+1)*(length+2)/2);
q = (FLT_OR_DBL *) space(size);
qb = (FLT_OR_DBL *) space(size);
qm = (FLT_OR_DBL *) space(size);
qm1 = (FLT_OR_DBL *) space(size);
qm2 = (circular) ? (FLT_OR_DBL *) space(sizeof(FLT_OR_DBL)*(length+2)) : NULL;
pscore = (short *) space(sizeof(short)*((length+1)*(length+2)/2));
q1k = (FLT_OR_DBL *) space(sizeof(FLT_OR_DBL)*(length+1));
qln = (FLT_OR_DBL *) space(sizeof(FLT_OR_DBL)*(length+2));
qq = (FLT_OR_DBL *) space(sizeof(FLT_OR_DBL)*(length+2));
qq1 = (FLT_OR_DBL *) space(sizeof(FLT_OR_DBL)*(length+2));
qqm = (FLT_OR_DBL *) space(sizeof(FLT_OR_DBL)*(length+2));
qqm1 = (FLT_OR_DBL *) space(sizeof(FLT_OR_DBL)*(length+2));
prm_l = (FLT_OR_DBL *) space(sizeof(FLT_OR_DBL)*(length+2));
prm_l1 = (FLT_OR_DBL *) space(sizeof(FLT_OR_DBL)*(length+2));
prml = (FLT_OR_DBL *) space(sizeof(FLT_OR_DBL)*(length+2));
expMLbase = (FLT_OR_DBL *) space(sizeof(FLT_OR_DBL)*(length+1));
scale = (FLT_OR_DBL *) space(sizeof(FLT_OR_DBL)*(length+1));
my_iindx = get_iindx(length);
iindx = get_iindx(length); /* for backward compatibility and Perl wrapper */
jindx = get_indx(length);
}
/*----------------------------------------------------------------------*/
PUBLIC void free_alipf_arrays(void){
if(q) free(q);
if(qb) free(qb);
if(qm) free(qm);
if(qm1) free(qm1);
if(qm2) free(qm2);
if(pscore) free(pscore);
if(qq) free(qq);
if(qq1) free(qq1);
if(qqm) free(qqm);
if(qqm1) free(qqm1);
if(q1k) free(q1k);
if(qln) free(qln);
if(prm_l) free(prm_l);
if(prm_l1) free(prm_l1);
if(prml) free(prml);
if(expMLbase) free(expMLbase);
if(scale) free(scale);
if(my_iindx) free(my_iindx);
if(iindx) free(iindx); /* for backward compatibility and Perl wrapper */
if(jindx) free(jindx);
if(S){
free_sequence_arrays(N_seq, &S, &S5, &S3, &a2s, &Ss);
N_seq = 0;
S = NULL;
}
pr = NULL; /* ? */
q = probs = qb = qm = qm1 = qm2 = qq = qq1 = qqm = qqm1 = q1k = qln = prml = prm_l = prm_l1 = expMLbase = scale = NULL;
my_iindx = jindx = iindx = NULL;
pscore = NULL;
#ifdef SUN4
standard_arithmetic();
#else
#ifdef HP9
fpsetfastmode(0);
#endif
#endif
}
/*-----------------------------------------------------------------*/
PUBLIC float alipf_fold(const char **sequences, char *structure, plist **pl){
return alipf_fold_par(sequences, structure, pl, NULL, do_backtrack, fold_constrained, 0);
}
PUBLIC float alipf_circ_fold(const char **sequences, char *structure, plist **pl){
return alipf_fold_par(sequences, structure, pl, NULL, do_backtrack, fold_constrained, 1);
}
PUBLIC float alipf_fold_par(const char **sequences,
char *structure,
plist **pl,
pf_paramT *parameters,
int calculate_bppm,
int is_constrained,
int is_circular){
int n, s, n_seq;
FLT_OR_DBL Q;
float free_energy;
circular = is_circular;
do_bppm = calculate_bppm;
struct_constrained = is_constrained;
if(circular)
oldAliEn = 1; /* may be removed if circular alipf fold works with gapfree stuff */
n = (int) strlen(sequences[0]);
for (s=0; sequences[s]!=NULL; s++);
n_seq = N_seq = s;
init_alipf_fold(n, n_seq, parameters);
alloc_sequence_arrays(sequences, &S, &S5, &S3, &a2s, &Ss, circular);
make_pscores((const short *const*)S, sequences, n_seq, structure);
alipf_linear(sequences, structure);
/* calculate post processing step for circular */
/* RNAs */
if(circular)
alipf_circ(sequences, structure);
if (backtrack_type=='C') Q = qb[my_iindx[1]-n];
else if (backtrack_type=='M') Q = qm[my_iindx[1]-n];
else Q = (circular) ? qo : q[my_iindx[1]-n];
/* ensemble free energy in Kcal/mol */
if (Q<=FLT_MIN) fprintf(stderr, "pf_scale too large\n");
free_energy = (-log(Q)-n*log(pf_params->pf_scale))*pf_params->kT/(1000.0 * n_seq);
/* in case we abort because of floating point errors */
if (n>1600) fprintf(stderr, "free energy = %8.2f\n", free_energy);
/* backtracking to construct binding probabilities of pairs*/
if(do_bppm){
alipf_create_bppm(sequences, structure, pl);
/*
* Backward compatibility:
* This block may be removed if deprecated functions
* relying on the global variable "pr" vanish from within the package!
*/
pr = probs;
}
return free_energy;
}
PUBLIC FLT_OR_DBL *alipf_export_bppm(void){
return probs;
}
PRIVATE void alipf_linear(const char **sequences, char *structure)
{
int s, n, n_seq, i,j,k,l, ij, u, u1, d, ii, *type, type_2, tt;
FLT_OR_DBL temp, Qmax=0;
FLT_OR_DBL qbt1, *tmp;
double kTn;
FLT_OR_DBL expMLclosing = pf_params->expMLclosing;
for(s=0; sequences[s]!=NULL; s++);
n_seq = s;
n = (int) strlen(sequences[0]);
kTn = pf_params->kT/10.; /* kT in cal/mol */
type = (int *)space(sizeof(int) * n_seq);
/* array initialization ; qb,qm,q
qb,qm,q (i,j) are stored as ((n+1-i)*(n-i) div 2 + n+1-j */
for (d=0; d<=TURN; d++)
for (i=1; i<=n-d; i++) {
j=i+d;
ij = my_iindx[i]-j;
q[ij]=1.0*scale[d+1];
qb[ij]=qm[ij]=0.0;
}
for (i=1; i<=n; i++)
qq[i]=qq1[i]=qqm[i]=qqm1[i]=0;
for (j=TURN+2;j<=n; j++) {
for (i=j-TURN-1; i>=1; i--) {
int ij, psc;
/* construction of partition function for segment i,j */
/* calculate pf given that i and j pair: qb(i,j) */
ij = my_iindx[i]-j;
for (s=0; s<n_seq; s++) {
type[s] = pair[S[s][i]][S[s][j]];
if (type[s]==0) type[s]=7;
}
psc = pscore[ij];
if (psc>=cv_fact*MINPSCORE) { /* otherwise ignore this pair */
/* hairpin contribution */
for (qbt1=1,s=0; s<n_seq; s++) {
u = a2s[s][j-1]-a2s[s][i];
if (a2s[s][i]<1) continue;
char loopseq[10];
if (u<7){
strncpy(loopseq, Ss[s]+a2s[s][i]-1, 10);
}
qbt1 *= exp_E_Hairpin(u, type[s], S3[s][i], S5[s][j], loopseq, pf_params);
}
qbt1 *= scale[j-i+1];
/* interior loops with interior pair k,l */
for (k=i+1; k<=MIN2(i+MAXLOOP+1,j-TURN-2); k++){
for (l=MAX2(k+TURN+1,j-1-MAXLOOP+k-i-1); l<=j-1; l++){
double qloop=1;
if (qb[my_iindx[k]-l]==0) {qloop=0; continue;}
for (s=0; s<n_seq; s++) {
u1 = a2s[s][k-1]-a2s[s][i]/*??*/;
type_2 = pair[S[s][l]][S[s][k]]; if (type_2 == 0) type_2 = 7;
qloop *= exp_E_IntLoop( u1, a2s[s][j-1]-a2s[s][l],
type[s], type_2, S3[s][i],
S5[s][j], S5[s][k], S3[s][l],
pf_params
);
}
qbt1 += qb[my_iindx[k]-l] * qloop * scale[k-i+j-l];
}
}
/* multi-loop loop contribution */
ii = my_iindx[i+1]; /* ii-k=[i+1,k-1] */
temp = 0.0;
for (k=i+2; k<=j-1; k++) temp += qm[ii-(k-1)]*qqm1[k];
for (s=0; s<n_seq; s++) {
tt = rtype[type[s]];
temp *= exp_E_MLstem(tt, S5[s][j], S3[s][i], pf_params)* expMLclosing;
}
temp *= scale[2] ;
qbt1 += temp;
qb[ij] = qbt1;
qb[ij] *= exp(psc/kTn);
} /* end if (type!=0) */
else qb[ij] = 0.0;
/* construction of qqm matrix containing final stem
contributions to multiple loop partition function
from segment i,j */
qqm[i] = qqm1[i]*expMLbase[1]; /* expMLbase[1]^n_seq */
for (qbt1=1, s=0; s<n_seq; s++) {
qbt1 *= exp_E_MLstem(type[s], (i>1) || circular ? S5[s][i] : -1, (j<n) || circular ? S3[s][j] : -1, pf_params);
}
qqm[i] += qb[ij]*qbt1;
qm1[jindx[j]+i] = qqm[i]; /* for circ folding and stochBT */
/* construction of qm matrix containing multiple loop
partition function contributions from segment i,j */
temp = 0.0;
ii = my_iindx[i]; /* ii-k=[i,k-1] */
for (k=i+1; k<=j; k++)
temp += (qm[ii-(k-1)]+expMLbase[k-i])*qqm[k];
qm[ij] = (temp + qqm[i]);
/* auxiliary matrix qq for cubic order q calculation below */
qbt1 = qb[ij];
if (qbt1>0)
for (s=0; s<n_seq; s++) {
qbt1 *= exp_E_ExtLoop(type[s], (i>1) || circular ? S5[s][i] : -1, (j<n) || circular ? S3[s][j] : -1, pf_params);
}
qq[i] = qq1[i]*scale[1] + qbt1;
/* construction of partition function for segment i,j */
temp = 1.0*scale[1+j-i] + qq[i];
for (k=i; k<=j-1; k++) temp += q[ii-k]*qq[k+1];
q[ij] = temp;
#ifndef LARGE_PF
if (temp>Qmax) {
Qmax = temp;
if (Qmax>FLT_MAX/10.)
fprintf(stderr, "%d %d %g\n", i,j,temp);
}
if (temp>FLT_MAX) {
PRIVATE char msg[128];
sprintf(msg, "overflow in pf_fold while calculating q[%d,%d]\n"
"use larger pf_scale", i,j);
nrerror(msg);
}
#endif
}
tmp = qq1; qq1 =qq; qq =tmp;
tmp = qqm1; qqm1=qqm; qqm=tmp;
}
free(type);
}
PRIVATE void alipf_create_bppm(const char **sequences, char *structure, plist **pl)
{
int s;
int n, n_seq, i,j,k,l, ij, kl, ii, ll, tt, *type, ov=0;
FLT_OR_DBL temp, Qmax=0, prm_MLb;
FLT_OR_DBL prmt,prmt1;
FLT_OR_DBL qbt1, *tmp, tmp2, tmp3;
FLT_OR_DBL expMLclosing = pf_params->expMLclosing;
double kTn;
n = (int) strlen(sequences[0]);
for (s=0; sequences[s]!=NULL; s++);
n_seq = s;
type = (int *)space(sizeof(int) * n_seq);
kTn = pf_params->kT/10.; /* kT in cal/mol */
for (i=0; i<=n; i++)
prm_l[i]=prm_l1[i]=prml[i]=0;
/* backtracking to construct binding probabilities of pairs*/
Qmax=0;
for (k=1; k<=n; k++) {
q1k[k] = q[my_iindx[1] - k];
qln[k] = q[my_iindx[k] -n];
}
q1k[0] = 1.0;
qln[n+1] = 1.0;
probs = q; /* recycling */
/* 1. exterior pair i,j and initialization of pr array */
if(circular){
for (i=1; i<=n; i++) {
for (j=i; j<=MIN2(i+TURN,n); j++) probs[my_iindx[i]-j] = 0;
for (j=i+TURN+1; j<=n; j++) {
ij = my_iindx[i]-j;
if (qb[ij]>0.) {
probs[ij] = exp(pscore[ij]/kTn)/qo;
/* get pair types */
for (s=0; s<n_seq; s++) {
type[s] = pair[S[s][j]][S[s][i]];
if (type[s]==0) type[s]=7;
}
int rt;
/* 1.1. Exterior Hairpin Contribution */
int u = i + n - j -1;
for (qbt1=1.,s=0; s<n_seq; s++) {
char loopseq[10];
char *ts;
if (u<7){
strcpy(loopseq , sequences[s]+j-1);
strncat(loopseq, sequences[s], i);
}
qbt1 *= exp_E_Hairpin(u, type[s], S[s][j+1], S[s][(i>1) ? i-1 : n], loopseq, pf_params);
}
tmp2 = qbt1 * scale[u];
/* 1.2. Exterior Interior Loop Contribution */
/* recycling of k and l... */
/* 1.2.1. first we calc exterior loop energy with constraint, that i,j */
/* delimtis the "left" part of the interior loop */
/* (j,i) is "outer pair" */
for(k=1; k < i-TURN-1; k++){
/* so first, lets calc the length of loop between j and k */
int ln1, lstart;
ln1 = k + n - j - 1;
if(ln1>MAXLOOP) break;
lstart = ln1+i-1-MAXLOOP;
if(lstart<k+TURN+1) lstart = k + TURN + 1;
for(l=lstart; l < i; l++){
int ln2,ln2a,ln1a, type_2;
ln2 = i - l - 1;
if(ln1+ln2>MAXLOOP) continue;
double qloop=1.;
if (qb[my_iindx[k]-l]==0.){ qloop=0.; continue;}
for (s=0; s<n_seq; s++){
ln2a= a2s[s][i-1];
ln2a-=a2s[s][l];
ln1a= a2s[s][n]-a2s[s][j];
ln1a+=a2s[s][k-1];
type_2 = pair[S[s][l]][S[s][k]];
if (type_2 == 0) type_2 = 7;
qloop *= exp_E_IntLoop(ln1a, ln2a, type[s], type_2,
S[s][j+1],
S[s][i-1],
S[s][(k>1) ? k-1 : n],
S[s][l+1], pf_params);
}
tmp2 += qb[my_iindx[k] - l] * qloop * scale[ln1+ln2];
}
}
/* 1.2.2. second we calc exterior loop energy with constraint, that i,j */
/* delimtis the "right" part of the interior loop */
/* (l,k) is "outer pair" */
for(k=j+1; k < n-TURN; k++){
/* so first, lets calc the length of loop between l and i */
int ln1, lstart;
ln1 = k - j - 1;
if((ln1 + i - 1)>MAXLOOP) break;
lstart = ln1+i-1+n-MAXLOOP;
if(lstart<k+TURN+1) lstart = k + TURN + 1;
for(l=lstart; l <= n; l++){
int ln2, type_2;
ln2 = i - 1 + n - l;
if(ln1+ln2>MAXLOOP) continue;
double qloop=1.;
if (qb[my_iindx[k]-l]==0.){ qloop=0.; continue;}
for (s=0; s<n_seq; s++){
ln1 = a2s[s][k] - a2s[s][j+1];
ln2 = a2s[s][i-1] + a2s[s][n] - a2s[s][l];
type_2 = pair[S[s][l]][S[s][k]];
if (type_2 == 0) type_2 = 7;
qloop *= exp_E_IntLoop(ln2, ln1, type_2, type[s],
S3[s][l],
S5[s][k],
S5[s][i],
S3[s][j], pf_params);
}
tmp2 += qb[my_iindx[k] - l] * qloop * scale[(k-j-1)+(i-1+n-l)];
}
}
/* 1.3 Exterior multiloop decomposition */
/* 1.3.1 Middle part */
if((i>TURN+2) && (j<n-TURN-1)){
for (tmp3=1, s=0; s<n_seq; s++){
tmp3 *= exp_E_MLstem(rtype[type[s]], S5[s][i], S3[s][j], pf_params);
}
tmp2 += qm[my_iindx[1]-i+1] * qm[my_iindx[j+1]-n] * tmp3 * pow(expMLclosing,n_seq);
}
/* 1.3.2 Left part */
for(k=TURN+2; k < i-TURN-2; k++){
for (tmp3=1, s=0; s<n_seq; s++){
tmp3 *= exp_E_MLstem(rtype[type[s]], S5[s][i], S3[s][j], pf_params);
}
tmp2 += qm[my_iindx[1]-k] * qm1[jindx[i-1]+k+1] * tmp3 * expMLbase[n-j] * pow(expMLclosing,n_seq);
}
/* 1.3.3 Right part */
for(k=j+TURN+2; k < n-TURN-1;k++){
for (tmp3=1, s=0; s<n_seq; s++){
tmp3 *= exp_E_MLstem(rtype[type[s]], S5[s][i], S3[s][j], pf_params);
}
tmp2 += qm[my_iindx[j+1]-k] * qm1[jindx[n]+k+1] * tmp3 * expMLbase[i-1] * pow(expMLclosing,n_seq);
}
probs[ij] *= tmp2;
}
else probs[ij] = 0;
} /* end for j=..*/
} /* end or i=... */
} /* end if(circular) */
else{
for (i=1; i<=n; i++) {
for (j=i; j<=MIN2(i+TURN,n); j++) probs[my_iindx[i]-j] = 0;
for (j=i+TURN+1; j<=n; j++) {
ij = my_iindx[i]-j;
if (qb[ij]>0.){
probs[ij] = q1k[i-1]*qln[j+1]/q1k[n] * exp(pscore[ij]/kTn);
for (s=0; s<n_seq; s++) {
int typ;
typ = pair[S[s][i]][S[s][j]]; if (typ==0) typ=7;
probs[ij] *= exp_E_ExtLoop(typ, (i>1) ? S5[s][i] : -1, (j<n) ? S3[s][j] : -1, pf_params);
}
} else
probs[ij] = 0;
}
}
} /* end if(!circular) */
for (l=n; l>TURN+1; l--) {
/* 2. bonding k,l as substem of 2:loop enclosed by i,j */
for (k=1; k<l-TURN; k++) {
double pp = 0;
kl = my_iindx[k]-l;
if (qb[kl]==0) continue;
for (s=0; s<n_seq; s++) {
type[s] = pair[S[s][l]][S[s][k]];
if (type[s]==0) type[s]=7;
}
for (i=MAX2(1,k-MAXLOOP-1); i<=k-1; i++)
for (j=l+1; j<=MIN2(l+ MAXLOOP -k+i+2,n); j++) {
ij = my_iindx[i] - j;
if ((probs[ij]>0.)) {
double qloop=1;
for (s=0; s<n_seq; s++) {
int typ;
typ = pair[S[s][i]][S[s][j]]; if (typ==0) typ=7;
qloop *= exp_E_IntLoop(a2s[s][k-1]-a2s[s][i], a2s[s][j-1]-a2s[s][l], typ, type[s], S3[s][i], S5[s][j], S5[s][k], S3[s][l], pf_params);
}
pp += probs[ij]*qloop*scale[k-i + j-l];
}
}
probs[kl] += pp * exp(pscore[kl]/kTn);
}
/* 3. bonding k,l as substem of multi-loop enclosed by i,j */
prm_MLb = 0.;
if (l<n) for (k=2; k<l-TURN; k++) {
i = k-1;
prmt = prmt1 = 0.0;
ii = my_iindx[i]; /* ii-j=[i,j] */
ll = my_iindx[l+1]; /* ll-j=[l+1,j-1] */
prmt1 = probs[ii-(l+1)];
for (s=0; s<n_seq; s++) {
tt = pair[S[s][l+1]][S[s][i]]; if (tt==0) tt=7;
prmt1 *= exp_E_MLstem(tt, S5[s][l+1], S3[s][i], pf_params) * expMLclosing;
}
for (j=l+2; j<=n; j++) {
double pp=1;
if (probs[ii-j]==0) continue;
for (s=0; s<n_seq; s++) {
tt=pair[S[s][j]][S[s][i]]; if (tt==0) tt=7;
pp *= exp_E_MLstem(tt, S5[s][j], S3[s][i], pf_params)*expMLclosing;
}
prmt += probs[ii-j]*pp*qm[ll-(j-1)];
}
kl = my_iindx[k]-l;
prml[ i] = prmt;
prm_l[i] = prm_l1[i]*expMLbase[1]+prmt1; /* expMLbase[1]^n_seq */
prm_MLb = prm_MLb*expMLbase[1] + prml[i];
/* same as: prm_MLb = 0;
for (i=1; i<=k-1; i++) prm_MLb += prml[i]*expMLbase[k-i-1]; */
prml[i] = prml[ i] + prm_l[i];
if (qb[kl] == 0.) continue;
temp = prm_MLb;
for (i=1;i<=k-2; i++)
temp += prml[i]*qm[my_iindx[i+1] - (k-1)];
for (s=0; s<n_seq; s++) {
tt=pair[S[s][k]][S[s][l]]; if (tt==0) tt=7;
temp *= exp_E_MLstem(tt, S5[s][k], S3[s][l], pf_params);
}
probs[kl] += temp * scale[2] * exp(pscore[kl]/kTn);
#ifndef LARGE_PF
if (probs[kl]>Qmax) {
Qmax = probs[kl];
if (Qmax>FLT_MAX/10.)
fprintf(stderr, "%d %d %g %g\n", i,j,probs[kl],qb[kl]);
}
if (probs[kl]>FLT_MAX) {
ov++;
probs[kl]=FLT_MAX;
}
#endif
} /* end for (k=2..) */
tmp = prm_l1; prm_l1=prm_l; prm_l=tmp;
} /* end for (l=..) */
for (i=1; i<=n; i++)
for (j=i+TURN+1; j<=n; j++) {
ij = my_iindx[i]-j;
probs[ij] *= qb[ij] *exp(-pscore[ij]/kTn);
}
/* did we get an adress where to save a pair-list? */
if (pl != NULL)
assign_plist_from_pr(pl, probs, n, /*cut_off:*/ 1e-6);
if (structure!=NULL)
bppm_to_structure(structure, probs, n);
if (ov>0) fprintf(stderr, "%d overflows occurred while backtracking;\n"
"you might try a smaller pf_scale than %g\n",
ov, pf_params->pf_scale);
free(type);
}
PRIVATE void scale_pf_params(unsigned int length, int n_seq, pf_paramT *parameters){
unsigned int i;
double kT, scaling_factor;
if(pf_params) free(pf_params);
if(parameters){
pf_params = get_boltzmann_factor_copy(parameters);
} else {
model_detailsT md;
set_model_details(&md);
pf_params = get_boltzmann_factors_ali(n_seq, temperature, alpha, md, pf_scale);
}
scaling_factor = pf_params->pf_scale;
kT = pf_params->kT / n_seq;
/* scaling factors (to avoid overflows) */
if (scaling_factor == -1) { /* mean energy for random sequences: 184.3*length cal */
scaling_factor = exp(-(-185+(pf_params->temperature-37.)*7.27)/kT);
if (scaling_factor<1) scaling_factor=1;
pf_params->pf_scale = scaling_factor;
}
scale[0] = 1.;
scale[1] = 1./scaling_factor;
expMLbase[0] = 1;
expMLbase[1] = pf_params->expMLbase/scaling_factor;
for (i=2; i<=length; i++) {
scale[i] = scale[i/2]*scale[i-(i/2)];
expMLbase[i] = pow(pf_params->expMLbase, (double)i) * scale[i];
}
}
/*---------------------------------------------------------------------------*/
PRIVATE int compare_pair_info(const void *pi1, const void *pi2) {
pair_info *p1, *p2;
int i, nc1, nc2;
p1 = (pair_info *)pi1; p2 = (pair_info *)pi2;
for (nc1=nc2=0, i=1; i<=6; i++) {
if (p1->bp[i]>0) nc1++;
if (p2->bp[i]>0) nc2++;
}
/* sort mostly by probability, add
epsilon * comp_mutations/(non-compatible+1) to break ties */
return (p1->p + 0.01*nc1/(p1->bp[0]+1.)) <
(p2->p + 0.01*nc2/(p2->bp[0]+1.)) ? 1 : -1;
}
pair_info *make_pairinfo(const short *const* S, const char **AS, int n_seq) {
int i,j,n, num_p=0, max_p = 64;
pair_info *pi;
double *duck, p;
n = S[0][0];
max_p = 64; pi = space(max_p*sizeof(pair_info));
duck = (double *) space((n+1)*sizeof(double));
for (i=1; i<n; i++)
for (j=i+TURN+1; j<=n; j++)
if ((p=probs[my_iindx[i]-j])>0) {
duck[i] -= p * log(p);
duck[j] -= p * log(p);
}
for (i=1; i<n; i++)
for (j=i+TURN+1; j<=n; j++) {
if ((p=probs[my_iindx[i]-j])>=PMIN) {
int type, s;
pi[num_p].i = i;
pi[num_p].j = j;
pi[num_p].p = p;
pi[num_p].ent = duck[i]+duck[j]-p*log(p);
for (type=0; type<8; type++) pi[num_p].bp[type]=0;
for (s=0; s<n_seq; s++) {
if (S[s][i]==0 && S[s][j]==0) type = 7; /* gap-gap */
else {
if ((AS[s][i] == '~')||(AS[s][j] == '~')) type = 7;
else type = pair[S[s][i]][S[s][j]];
}
pi[num_p].bp[type]++;
}
num_p++;
if (num_p>=max_p) {
max_p *= 2;
pi = xrealloc(pi, max_p * sizeof(pair_info));
}
}
}
free(duck);
pi = xrealloc(pi, (num_p+1)*sizeof(pair_info));
pi[num_p].i=0;
qsort(pi, num_p, sizeof(pair_info), compare_pair_info );
return pi;
}
/*---------------------------------------------------------------------------*/
PRIVATE void make_pscores(const short *const* S, const char **AS,
int n_seq, const char *structure) {
/* calculate co-variance bonus for each pair depending on */
/* compensatory/consistent mutations and incompatible seqs */
/* should be 0 for conserved pairs, >0 for good pairs */
#define NONE -10000 /* score for forbidden pairs */
int n,i,j,k,l,s,score;
int olddm[7][7]={{0,0,0,0,0,0,0}, /* hamming distance between pairs */
{0,0,2,2,1,2,2} /* CG */,
{0,2,0,1,2,2,2} /* GC */,
{0,2,1,0,2,1,2} /* GU */,
{0,1,2,2,0,2,1} /* UG */,
{0,2,2,1,2,0,2} /* AU */,
{0,2,2,2,1,2,0} /* UA */};
float **dm;
int noLP = pf_params->model_details.noLP;
n=S[0][0]; /* length of seqs */
if (ribo) {
if (RibosumFile !=NULL) dm=readribosum(RibosumFile);
else dm=get_ribosum(AS,n_seq,n);
}
else { /*use usual matrix*/
dm=(float **)space(7*sizeof(float*));
for (i=0; i<7;i++) {
dm[i]=(float *)space(7*sizeof(float));
for (j=0; j<7; j++)
dm[i][j] = olddm[i][j];
}
}
n=S[0][0]; /* length of seqs */
for (i=1; i<n; i++) {
for (j=i+1; (j<i+TURN+1) && (j<=n); j++)
pscore[my_iindx[i]-j] = NONE;
for (j=i+TURN+1; j<=n; j++) {
int pfreq[8]={0,0,0,0,0,0,0,0};
for (s=0; s<n_seq; s++) {
int type;
if (S[s][i]==0 && S[s][j]==0) type = 7; /* gap-gap */
else {
if ((AS[s][i] == '~')||(AS[s][j] == '~')) type = 7;
else type = pair[S[s][i]][S[s][j]];
}
pfreq[type]++;
}
if (pfreq[0]*2+pfreq[7]>n_seq) { pscore[my_iindx[i]-j] = NONE; continue;}
for (k=1,score=0; k<=6; k++) /* ignore pairtype 7 (gap-gap) */
for (l=k; l<=6; l++)
/* scores for replacements between pairtypes */
/* consistent or compensatory mutations score 1 or 2 */
score += pfreq[k]*pfreq[l]*dm[k][l];
/* counter examples score -1, gap-gap scores -0.25 */
pscore[my_iindx[i]-j] = cv_fact *
((UNIT*score)/n_seq - nc_fact*UNIT*(pfreq[0] + pfreq[7]*0.25));
}
}
if (noLP) /* remove unwanted pairs */
for (k=1; k<=n-TURN-1; k++)
for (l=1; l<=2; l++) {
int type,ntype=0,otype=0;
i=k; j = i+TURN+l;
type = pscore[my_iindx[i]-j];
while ((i>=1)&&(j<=n)) {
if ((i>1)&&(j<n)) ntype = pscore[my_iindx[i-1]-j-1];
if ((otype<cv_fact*MINPSCORE)&&(ntype<cv_fact*MINPSCORE))
/* too many counterexamples */
pscore[my_iindx[i]-j] = NONE; /* i.j can only form isolated pairs */
otype = type;
type = ntype;
i--; j++;
}
}
if (struct_constrained&&(structure!=NULL)) {
int psij, hx, *stack;
stack = (int *) space(sizeof(int)*(n+1));
for(hx=0, j=1; j<=n; j++) {
switch (structure[j-1]) {
case 'x': /* j can't pair */
for (l=1; l<j-TURN; l++) pscore[my_iindx[l]-j] = NONE;
for (l=j+TURN+1; l<=n; l++) pscore[my_iindx[j]-l] = NONE;
break;
case '(':
stack[hx++]=j;
/* fallthrough */
case '<': /* j pairs upstream */
for (l=1; l<j-TURN; l++) pscore[my_iindx[l]-j] = NONE;
break;
case ')': /* j pairs with i */
if (hx<=0) {
fprintf(stderr, "%s\n", structure);
nrerror("unbalanced brackets in constraints");
}
i = stack[--hx];
psij = pscore[my_iindx[i]-j]; /* store for later */
for (l=i; l<=j; l++)
for (k=j; k<=n; k++) pscore[my_iindx[l]-k] = NONE;
for (k=1; k<=i; k++)
for (l=i; l<=j; l++) pscore[my_iindx[k]-l] = NONE;
for (k=i+1; k<j; k++)
pscore[my_iindx[k]-j] = pscore[my_iindx[i]-k] = NONE;
pscore[my_iindx[i]-j] = (psij>0) ? psij : 0;
/* fallthrough */
case '>': /* j pairs downstream */
for (l=j+TURN+1; l<=n; l++) pscore[my_iindx[j]-l] = NONE;
break;
}
}
if (hx!=0) {
fprintf(stderr, "%s\n", structure);
nrerror("unbalanced brackets in constraint string");
}
free(stack);
}
for (i=0; i<7;i++) {
free(dm[i]);
}
free(dm);
}
/* calculate partition function for circular case */
/* NOTE: this is the postprocessing step ONLY */
/* You have to call alipf_linear first to calculate */
/* circular case!!! */
PUBLIC void alipf_circ(const char **sequences, char *structure){
int u, p, q, k, l, n_seq, s, *type;
FLT_OR_DBL expMLclosing = pf_params->expMLclosing;
int n = (int) strlen(sequences[0]);
for (s=0; sequences[s]!=NULL; s++);
n_seq = s;
double kTn;
FLT_OR_DBL qbt1, qot;
kTn = pf_params->kT/10.; /* kT in cal/mol */
type = (int *)space(sizeof(int) * n_seq);
qo = qho = qio = qmo = 0.;
/* calculate the qm2 matrix */
for(k=1; k<n-TURN; k++){
qot = 0.;
for (u=k+TURN+1; u<n-TURN-1; u++)
qot += qm1[jindx[u]+k]*qm1[jindx[n]+(u+1)];
qm2[k] = qot;
}
for(p=1;p<n;p++){
for(q=p+TURN+1;q<=n;q++){
int psc;
u = n-q + p-1;
if (u<TURN) continue;
psc = pscore[my_iindx[p]-q];
if(psc<cv_fact*MINPSCORE) continue;
/* 1. exterior hairpin contribution */
/* Note, that we do not scale Hairpin Energy by u+2 but by u cause the scale */
/* for the closing pair was already done in the forward recursion */
for (qbt1=1,s=0; s<n_seq; s++) {
char loopseq[10];
type[s] = pair[S[s][q]][S[s][p]];
if (type[s]==0) type[s]=7;
if (u<7){
strcpy(loopseq , sequences[s]+q-1);
strncat(loopseq, sequences[s], p);
}
qbt1 *= exp_E_Hairpin(u, type[s], S[s][q+1], S[s][(p>1) ? p-1 : n], loopseq, pf_params);
}
qho += qb[my_iindx[p]-q] * qbt1 * scale[u];
/* 2. exterior interior loop contribution*/
for(k=q+1; k < n; k++){
int ln1, lstart;
ln1 = k - q - 1;
if(ln1+p-1>MAXLOOP) break;
lstart = ln1+p-1+n-MAXLOOP;
if(lstart<k+TURN+1) lstart = k + TURN + 1;
for(l=lstart;l <= n; l++){
int ln2, type_2;
ln2 = (p - 1) + (n - l);
if((ln1+ln2) > MAXLOOP) continue;
double qloop=1.;
if (qb[my_iindx[k]-l]==0.){ qloop=0.; continue;}
for (s=0; s<n_seq; s++){
int ln1a=a2s[s][k-1]-a2s[s][q];
int ln2a=a2s[s][n]-a2s[s][l]+a2s[s][p-1];
type_2 = pair[S[s][l]][S[s][k]];
if (type_2 == 0) type_2 = 7;
qloop *= exp_E_IntLoop(ln2a, ln1a, type_2, type[s], S3[s][l], S5[s][k], S5[s][p], S3[s][q], pf_params);
}
qio += qb[my_iindx[p]-q] * qb[my_iindx[k]-l] * qloop * scale[ln1+ln2];
}
} /* end of kl double loop */
}
} /* end of pq double loop */
/* 3. exterior multiloop contribution */
for(k=TURN+2; k<n-2*TURN-3; k++)
qmo += qm[my_iindx[1]-k] * qm2[k+1] * pow(expMLclosing,n_seq);
/* add additional pf of 1.0 to take open chain into account */
qo = qho + qio + qmo + 1.0*scale[n];
free(type);
}
/*brauch ma nurnoch pscores!*/
PUBLIC char *alipbacktrack(double *prob) {
double r, gr, qt, kTn;
int k,i,j, start,s,n, n_seq;
double probs=1;
if (q == NULL)
nrerror("can't backtrack without pf arrays.\n"
"Call pf_fold() before pbacktrack()");
n = S[0][0];
n_seq = N_seq;
kTn = pf_params->kT/10.;
/*sequence = seq;*/
if (do_bppm==0) {
for (k=1; k<=n; k++) {
qln[k] = q[my_iindx[k] -n];
}
qln[n+1] = 1.0;
}
pstruc = space((n+1)*sizeof(char));
for (i=0; i<n; i++) pstruc[i] = '.';
start = 1;
while (start<n) {
/* find i position of first pair */
probs=1.;
for (i=start; i<n; i++) {
gr = urn() * qln[i];
if (gr > qln[i+1]*scale[1]) {
*prob=*prob*probs*(1-qln[i+1]*scale[1]/qln[i]);
break; /* i is paired */
}
probs*=qln[i+1]*scale[1]/qln[i];
}
if (i>=n) {
*prob=*prob*probs;
break; /* no more pairs */
}
/* now find the pairing partner j */
r = urn() * (qln[i] - qln[i+1]*scale[1]);
for (qt=0, j=i+1; j<=n; j++) {
int xtype;
/* type = ptype[my_iindx[i]-j];
if (type) {*/
double qkl;
if (qb[my_iindx[i]-j]>0) {
qkl = qb[my_iindx[i]-j]*qln[j+1]; /*if psc too small qb=0!*/
for (s=0; s< n_seq; s++) {
xtype=pair[S[s][i]][S[s][j]];
if (xtype==0) xtype=7;
qkl *= exp_E_ExtLoop(xtype, (i>1) ? S5[s][i] : -1, (j<n) ? S3[s][j] : -1, pf_params);
}
qt += qkl; /*?*exp(pscore[my_iindx[i]-j]/kTn)*/
if (qt > r) {
*prob=*prob*(qkl/(qln[i] - qln[i+1]*scale[1]));/*probs*=qkl;*/
break; /* j is paired */
}
}
}
if (j==n+1) nrerror("backtracking failed in ext loop");
start = j+1;
backtrack(i,j, n_seq, prob); /*?*/
}
return pstruc;
}
PRIVATE void backtrack(int i, int j, int n_seq, double *prob) {
/*backtrack given i,j basepair!*/
double kTn = pf_params->kT/10.;
double tempwert;
int *type = (int *)space(sizeof(int) * n_seq);
do {
double r, qbt1;
int k, l, u, u1,s;
pstruc[i-1] = '('; pstruc[j-1] = ')';
for (s=0; s<n_seq; s++) {
type[s] = pair[S[s][i]][S[s][j]];
if (type[s]==0) type[s]=7;
}
r = urn() * (qb[my_iindx[i]-j]/exp(pscore[my_iindx[i]-j]/kTn)); /*?*exp(pscore[my_iindx[i]-j]/kTn)*/
qbt1=1.;
for (s=0; s<n_seq; s++){
u = a2s[s][j-1]-a2s[s][i];
if (a2s[s][i]<1) continue;
char loopseq[10];
if(u < 7){
strncpy(loopseq, Ss[s]+a2s[s][i]-1, 10);
}
qbt1 *= exp_E_Hairpin(u, type[s], S3[s][i], S5[s][j], loopseq, pf_params);
}
qbt1 *= scale[j-i+1];
if (qbt1>r) {
*prob=*prob*qbt1/(qb[my_iindx[i]-j]/exp(pscore[my_iindx[i]-j]/kTn));/*probs*=qbt1;*/
free(type);
return; /* found the hairpin we're done */
}
for (k=i+1; k<=MIN2(i+MAXLOOP+1,j-TURN-2); k++){
for (l=MAX2(k+TURN+1,j-1-MAXLOOP+k-i-1); l<j; l++){
double qloop=1;
int type_2;
if (qb[my_iindx[k]-l]==0) {qloop=0; continue;}
for (s=0; s<n_seq; s++) {
u1 = a2s[s][k-1]-a2s[s][i]/*??*/;
type_2 = pair[S[s][l]][S[s][k]]; if (type_2 == 0) type_2 = 7;
qloop *= exp_E_IntLoop(u1, a2s[s][j-1]-a2s[s][l], type[s], type_2,
S3[s][i], S5[s][j],S5[s][k], S3[s][l], pf_params);
}
qbt1 += qb[my_iindx[k]-l] * qloop * scale[k-i+j-l];
if (qbt1 > r) {
*prob=*prob*qb[my_iindx[k]-l] * qloop * scale[k-i+j-l]/(qb[my_iindx[i]-j]/exp(pscore[my_iindx[i]-j]/kTn));
/*
prob*=qb[my_iindx[k]-l] * qloop * scale[k-i+j-l];
*/
break;
}
}
if (qbt1 > r) break;
}
if (l<j) {
i=k; j=l;
}
else {
*prob=*prob*(1-qbt1/(qb[my_iindx[i]-j]/exp(pscore[my_iindx[i]-j]/kTn)));
break;
}
} while (1);
/* backtrack in multi-loop */
tempwert=(qb[my_iindx[i]-j]/exp(pscore[my_iindx[i]-j]/kTn));
{
double r, qt;
int k, ii, jj;
double qttemp=0;;
i++; j--;
/* find the first split index */
ii = my_iindx[i]; /* ii-j=[i,j] */
jj = jindx[j]; /* jj+i=[j,i] */
for (qt=0., k=i+1; k<j; k++) qttemp += qm[ii-(k-1)]*qm1[jj+k];
r = urn() * qttemp;
for (qt=0., k=i+1; k<j; k++) {
qt += qm[ii-(k-1)]*qm1[jj+k];
if (qt>=r){
*prob=*prob*qm[ii-(k-1)]*qm1[jj+k]/qttemp;/*qttemp;tempwert*/
/* prob*=qm[ii-(k-1)]*qm1[jj+k];*/
break;
}
}
if (k>=j) nrerror("backtrack failed, can't find split index ");
backtrack_qm1(k, j, n_seq, prob);
j = k-1;
while (j>i) {
/* now backtrack [i ... j] in qm[] */
jj = jindx[j];/*habides??*/
ii = my_iindx[i];
r = urn() * qm[ii - j];
qt = qm1[jj+i]; k=i;
if (qt<r)
for (k=i+1; k<=j; k++) {
qt += (qm[ii-(k-1)]+expMLbase[k-i]/*n_seq??*/)*qm1[jj+k];
if (qt >= r) {
*prob=*prob*(qm[ii-(k-1)]+expMLbase[k-i])*qm1[jj+k]/qm[ii - j];/*???*/
/* probs*=qt;*/
break;
}
}
else {
*prob=*prob*qt/qm[ii - j];/*??*/
}
if (k>j) nrerror("backtrack failed in qm");
backtrack_qm1(k,j, n_seq, prob);
if (k<i+TURN) break; /* no more pairs */
r = urn() * (qm[ii-(k-1)] + expMLbase[k-i]);
if (expMLbase[k-i] >= r) {
break; /* no more pairs */
*prob=*prob*expMLbase[k-i]/(qm[ii-(k-1)] + expMLbase[k-i]);
}
j = k-1;
/* whatishere?? */
}
}
free(type);
}
PRIVATE void backtrack_qm1(int i,int j, int n_seq, double *prob) {
/* i is paired to l, i<l<j; backtrack in qm1 to find l */
int ii, l, xtype,s;
double qt, r, tempz;
r = urn() * qm1[jindx[j]+i];
ii = my_iindx[i];
for (qt=0., l=i+TURN+1; l<=j; l++) {
if (qb[ii-l]==0) continue;
tempz=1.;
for (s=0; s<n_seq; s++) {
xtype = pair[S[s][i]][S[s][l]];
if (xtype==0) xtype=7;
tempz*=exp_E_MLstem(xtype, S5[s][i], S3[s][l], pf_params);
}
qt += qb[ii-l]*tempz*expMLbase[j-l];
if (qt>=r) {
*prob=*prob*qb[ii-l]*tempz*expMLbase[j-l]/qm1[jindx[j]+i];
/* probs*=qb[ii-l]*tempz*expMLbase[j-l];*/
break;
}
}
if (l>j) nrerror("backtrack failed in qm1");
backtrack(i,l, n_seq, prob);
}
PUBLIC FLT_OR_DBL *export_ali_bppm(void){
return probs;
}
/*-------------------------------------------------------------------------*/
/* make arrays used for alipf_fold available to other routines */
PUBLIC int get_alipf_arrays( short ***S_p,
short ***S5_p,
short ***S3_p,
unsigned short ***a2s_p,
char ***Ss_p,
FLT_OR_DBL **qb_p,
FLT_OR_DBL **qm_p,
FLT_OR_DBL **q1k_p,
FLT_OR_DBL **qln_p,
short **pscore_p) {
if(qb == NULL) return(0); /* check if alipf_fold() has been called */
*S_p = S; *S5_p = S5; *S3_p = S3;
*a2s_p=a2s;
*Ss_p=Ss;
*qb_p = qb; *qm_p = qm;
*q1k_p = q1k; *qln_p = qln;
*pscore_p = pscore;
return(1); /* success */
}
|
subopt.c | /*
$Log: subopt.c,v $
Revision 2.0 2010/12/06 20:04:20 ronny
repaired subopt for cofolding
Revision 1.24 2008/11/01 21:10:20 ivo
avoid rounding errors when computing DoS
Revision 1.23 2008/03/31 15:06:49 ivo
Add cofolding support in subopt
Revision 1.22 2008/02/23 09:42:35 ivo
fix circular folding bugs with dangles that cross the origin
Revision 1.21 2008/01/08 15:08:51 ivo
circular fold would fail for open chain
Revision 1.20 2008/01/08 14:08:20 ivo
add an option to compute the density of state
Revision 1.19 2007/12/05 13:04:04 ivo
add various circfold variants from Ronny
Revision 1.18 2003/10/06 08:56:45 ivo
use P->TerminalAU
Revision 1.17 2003/08/26 09:26:08 ivo
don't modify print_energy in subopt(); use doubles instead of floats
Revision 1.16 2001/10/01 13:50:00 ivo
sorted -> subopt_sorted
Revision 1.15 2001/09/17 10:30:42 ivo
move scale_parameters() into params.c
returns pointer to paramT structure
Revision 1.14 2001/08/31 15:02:19 ivo
Let subopt either write to file pointer or return a list of structures,
so we can nicely integrate it into the library
Revision 1.13 2001/04/05 07:35:08 ivo
remove uneeded declaration of TETRA_ENERGY
Revision 1.12 2000/10/10 08:53:20 ivo
adapted for new Turner energy parameters
supports all constraints that forbid pairs
Revision 1.11 2000/04/08 15:56:18 ivo
with noLonelyPairs=1 will produce no structures with isolated base pairs
(Giegerich's canonical structures)
Revision 1.10 1999/05/06 10:13:35 ivo
recalculte energies before printing if logML is set
+ cosmetic changes
Revision 1.9 1998/05/19 16:31:52 ivo
added support for constrained folding
Revision 1.8 1998/03/30 14:44:54 ivo
cleanup of make_printout etc.
Revision 1.7 1998/03/30 14:39:31 ivo
replaced BasePairs list with structure string in STATE
save memory by not storing (and sorting) structures
modified for use with ViennaRNA-1.2.1
Revision 1.6 1997/10/21 11:34:09 walter
steve update
Revision 1.1 1997/08/04 21:05:32 walter
Initial revision
*/
/*
suboptimal folding - Stefan Wuchty, Walter Fontana & Ivo Hofacker
Vienna RNA package
*/
#include <config.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <math.h>
#include "fold.h"
#include "utils.h"
#include "energy_par.h"
#include "fold_vars.h"
#include "pair_mat.h"
#include "list.h"
#include "params.h"
#include "loop_energies.h"
#include "cofold.h"
#include "gquad.h"
#include "subopt.h"
#ifdef _OPENMP
#include <omp.h>
#endif
#define true 1
#define false 0
#define SAME_STRAND(I,J) (((I)>=cut_point)||((J)<cut_point))
#define NEW_NINIO 1 /* use new asymetry penalty */
#define STACK_BULGE1 1 /* stacking energies for bulges of size 1 */
#define MAXALPHA 20 /* maximal length of alphabet */
/*
#################################
# GLOBAL VARIABLES #
#################################
*/
PUBLIC int subopt_sorted=0; /* output sorted by energy */
PUBLIC int density_of_states[MAXDOS+1];
PUBLIC double print_energy = 9999; /* printing threshold for use with logML */
typedef struct {
char *structure;
LIST *Intervals;
int partial_energy;
int is_duplex;
/* int best_energy; */ /* best attainable energy */
} STATE;
/*
#################################
# PRIVATE VARIABLES #
#################################
*/
PRIVATE int turn;
PRIVATE LIST *Stack = NULL;
PRIVATE int nopush;
PRIVATE int best_energy; /* best_energy = remaining energy */
PRIVATE int *f5 = NULL; /* energy of 5 end */
PRIVATE int *c = NULL; /* energy array, given that i-j pair */
PRIVATE int *fML = NULL; /* multi-loop auxiliary energy array */
PRIVATE int *fM1 = NULL; /* another multi-loop auxiliary energy array */
PRIVATE int *fc = NULL; /*energy array, from i (j) to cut*/
PRIVATE int *indx = NULL; /* index for moving in the triangle matrices c[] and f[] */
PRIVATE short *S=NULL, *S1=NULL;
PRIVATE char *ptype=NULL;
PRIVATE paramT *P = NULL;
PRIVATE int length;
PRIVATE int minimal_energy; /* minimum free energy */
PRIVATE int element_energy; /* internal energy of a structural element */
PRIVATE int threshold; /* minimal_energy + delta */
PRIVATE char *sequence = NULL;
PRIVATE int circular = 0;
PRIVATE int struct_constrained = 0;
PRIVATE int *fM2 = NULL; /* energies of M2 */
PRIVATE int Fc, FcH, FcI, FcM; /* parts of the exterior loop energies */
PRIVATE int with_gquad = 0;
PRIVATE int *ggg = NULL;
#ifdef _OPENMP
#pragma omp threadprivate(turn, Stack, nopush, best_energy, f5, c, fML, fM1, fc, indx, S, S1,\
ptype, P, length, minimal_energy, element_energy, threshold, sequence,\
fM2, Fc, FcH, FcI, FcM, circular, struct_constrained,\
ggg, with_gquad)
#endif
/*
#################################
# PRIVATE FUNCTION DECLARATIONS #
#################################
*/
PRIVATE void make_pair(int i, int j, STATE *state);
/* mark a gquadruplex in the resulting dot-bracket structure */
PRIVATE void make_gquad(int i, int L, int l[3], STATE *state);
PRIVATE INTERVAL *make_interval (int i, int j, int ml);
/*@out@*/ PRIVATE STATE *make_state(/*@only@*/LIST *Intervals,
/*@only@*/ /*@null@*/ char *structure,
int partial_energy, int is_duplex);
PRIVATE STATE *copy_state(STATE * state);
PRIVATE void print_state(STATE * state);
PRIVATE void UNUSED print_stack(LIST * list);
/*@only@*/ PRIVATE LIST *make_list(void);
PRIVATE void push(LIST * list, /*@only@*/ void *data);
PRIVATE void *pop(LIST * list);
PRIVATE int best_attainable_energy(STATE * state);
PRIVATE void scan_interval(int i, int j, int array_flag, STATE * state);
PRIVATE void free_interval_node(/*@only@*/ INTERVAL * node);
PRIVATE void free_state_node(/*@only@*/ STATE * node);
PRIVATE void push_back(STATE * state);
PRIVATE char* get_structure(STATE * state);
PRIVATE int compare(const void *solution1, const void *solution2);
PRIVATE void make_output(SOLUTION *SL, FILE *fp);
PRIVATE char *costring(char *string);
PRIVATE void repeat(int i, int j, STATE * state, int part_energy, int temp_energy);
PRIVATE void repeat_gquad( int i, int j, STATE *state, int part_energy, int temp_energy);
/*
#################################
# BEGIN OF FUNCTION DEFINITIONS #
#################################
*/
/*---------------------------------------------------------------------------*/
/*List routines--------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
PRIVATE void
make_pair(int i, int j, STATE *state)
{
state->structure[i-1] = '(';
state->structure[j-1] = ')';
}
PRIVATE void
make_gquad(int i, int L, int l[3], STATE *state)
{
int x;
for(x = 0; x < L; x++){
state->structure[i - 1 + x] = '+';
state->structure[i - 1 + x + L + l[0]] = '+';
state->structure[i - 1 + x + 2*L + l[0] + l[1]] = '+';
state->structure[i - 1 + x + 3*L + l[0] + l[1] + l[2]] = '+';
}
}
/*---------------------------------------------------------------------------*/
PRIVATE INTERVAL *
make_interval(int i, int j, int array_flag)
{
INTERVAL *interval;
interval = lst_newnode(sizeof(INTERVAL));
interval->i = i;
interval->j = j;
interval->array_flag = array_flag;
return interval;
}
/*---------------------------------------------------------------------------*/
PRIVATE void
free_interval_node(INTERVAL * node)
{
lst_freenode(node);
}
/*---------------------------------------------------------------------------*/
PRIVATE void
free_state_node(STATE * node)
{
free(node->structure);
if (node->Intervals)
lst_kill(node->Intervals, lst_freenode);
lst_freenode(node);
}
/*---------------------------------------------------------------------------*/
PRIVATE STATE *
make_state(LIST * Intervals,
char *structure,
int partial_energy,
int is_duplex)
{
STATE *state;
state = lst_newnode(sizeof(STATE));
if (Intervals)
state->Intervals = Intervals;
else
state->Intervals = lst_init();
if (structure)
state->structure = structure;
else {
int i;
state->structure = (char *) space(length+1);
for (i=0; i<length; i++)
state->structure[i] = '.';
}
state->partial_energy = partial_energy;
return state;
}
/*---------------------------------------------------------------------------*/
PRIVATE STATE *
copy_state(STATE * state)
{
STATE *new_state;
void *after;
INTERVAL *new_interval, *next;
new_state = lst_newnode(sizeof(STATE));
new_state->Intervals = lst_init();
new_state->partial_energy = state->partial_energy;
/* new_state->best_energy = state->best_energy; */
if (state->Intervals->count) {
after = LST_HEAD(new_state->Intervals);
for ( next = lst_first(state->Intervals); next; next = lst_next(next))
{
new_interval = lst_newnode(sizeof(INTERVAL));
*new_interval = *next;
lst_insertafter(new_state->Intervals, new_interval, after);
after = new_interval;
}
}
new_state->structure = strdup(state->structure);
if (!new_state->structure) nrerror("out of memory");
return new_state;
}
/*---------------------------------------------------------------------------*/
/*@unused @*/ PRIVATE void
print_state(STATE * state)
{
INTERVAL *next;
if (state->Intervals->count)
{
printf("%d intervals:\n", state->Intervals->count);
for (next = lst_first(state->Intervals); next; next = lst_next(next))
{
printf("[%d,%d],%d ", next->i, next->j, next->array_flag);
}
printf("\n");
}
printf("partial structure: %s\n", state->structure);
printf("\n");
printf(" partial_energy: %d\n", state->partial_energy);
/* printf(" best_energy: %d\n", state->best_energy); */
(void) fflush(stdout);
}
/*---------------------------------------------------------------------------*/
/*@unused @*/ PRIVATE void
print_stack(LIST * list)
{
void *rec;
printf("================\n");
printf("%d states\n", list->count);
for (rec = lst_first(list); rec; rec = lst_next(rec))
{
printf("state-----------\n");
print_state(rec);
}
printf("================\n");
}
/*---------------------------------------------------------------------------*/
PRIVATE LIST *
make_list(void)
{
return lst_init();
}
/*---------------------------------------------------------------------------*/
PRIVATE void
push(LIST * list, void *data)
{
nopush = false;
lst_insertafter(list, data, LST_HEAD(list));
}
/* PRIVATE void */
/* push_stack(STATE *state) { */ /* keep the stack sorted by energy */
/* STATE *after, *next; */
/* nopush = false; */
/* next = after = LST_HEAD(Stack); */
/* while ( next = lst_next(next)) { */
/* if ( next->best_energy >= state->best_energy ) break; */
/* after = next; */
/* } */
/* lst_insertafter(Stack, state, after); */
/* } */
/*---------------------------------------------------------------------------*/
PRIVATE void *
pop(LIST * list)
{
void *data;
data = lst_deletenext(list, LST_HEAD(list));
return data;
}
/*---------------------------------------------------------------------------*/
/*auxiliary routines---------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
PRIVATE int
best_attainable_energy(STATE * state)
{
/* evaluation of best possible energy attainable within remaining intervals */
register int sum;
INTERVAL *next;
sum = state->partial_energy; /* energy of already found elements */
for (next = lst_first(state->Intervals); next; next = lst_next(next))
{
if (next->array_flag == 0)
sum += (circular) ? Fc : f5[next->j];
else if (next->array_flag == 1)
sum += fML[indx[next->j] + next->i];
else if (next->array_flag == 2)
sum += c[indx[next->j] + next->i];
else if (next->array_flag == 3)
sum += fM1[indx[next->j] + next->i];
else if (next->array_flag == 4)
sum += fc[next->i];
else if (next->array_flag == 5)
sum += fc[next->j];
else if (next->array_flag == 6)
sum += ggg[indx[next->j] + next->i];
}
return sum;
}
/*---------------------------------------------------------------------------*/
PRIVATE void
push_back(STATE * state)
{
push(Stack, copy_state(state));
return;
}
/*---------------------------------------------------------------------------*/
PRIVATE char*
get_structure(STATE * state)
{
char* structure;
structure = strdup(state->structure);
return structure;
}
/*---------------------------------------------------------------------------*/
PRIVATE int
compare(const void *solution1, const void *solution2)
{
if (((SOLUTION *) solution1)->energy > ((SOLUTION *) solution2)->energy)
return 1;
if (((SOLUTION *) solution1)->energy < ((SOLUTION *) solution2)->energy)
return -1;
return strcmp(((SOLUTION *) solution1)->structure,
((SOLUTION *) solution2)->structure);
}
/*---------------------------------------------------------------------------*/
PRIVATE void make_output(SOLUTION *SL, FILE *fp) /* prints stuff */
{
SOLUTION *sol;
for (sol = SL; sol->structure!=NULL; sol++)
if (cut_point<0) fprintf(fp, "%s %6.2f\n", sol->structure, sol->energy);
else {
char *tStruc;
tStruc=costring(sol->structure);
fprintf(fp, "%s %6.2f\n", tStruc, sol->energy);
free(tStruc);
}
}
/*---------------------------------------------------------------------------*/
/* start of subopt backtracking ---------------------------------------------*/
/*---------------------------------------------------------------------------*/
PUBLIC SOLUTION *subopt(char *seq, char *structure, int delta, FILE *fp){
return subopt_par(seq, structure, NULL, delta, fold_constrained, 0, fp);
}
PUBLIC SOLUTION *subopt_circ(char *seq, char *structure, int delta, FILE *fp){
return subopt_par(seq, structure, NULL, delta, fold_constrained, 1, fp);
}
PUBLIC SOLUTION *subopt_par(char *seq,
char *structure,
paramT *parameters,
int delta,
int is_constrained,
int is_circular,
FILE *fp){
STATE *state;
LIST *Intervals;
INTERVAL *interval;
SOLUTION *SolutionList;
unsigned long max_sol, n_sol;
int maxlevel, count, partial_energy, old_dangles, logML, dangle_model;
double structure_energy, min_en, eprint;
char *struc;
max_sol = 128;
n_sol = 0;
sequence = seq;
length = strlen(sequence);
circular = is_circular;
struct_constrained = is_constrained;
struc = (char *) space(sizeof(char)*(length+1));
if (struct_constrained) strncpy(struc, structure, length);
/* do mfe folding to get fill arrays and get ground state energy */
/* in case dangles is neither 0 or 2, set dangles=2 while folding */
if(P) free(P);
if(parameters){
P = get_parameter_copy(parameters);
} else {
model_detailsT md;
set_model_details(&md);
P = get_scaled_parameters(temperature, md);
}
logML = P->model_details.logML;
old_dangles = dangle_model = P->model_details.dangles;
with_gquad = P->model_details.gquad;
/* temporarily set dangles to 2 if necessary */
if((P->model_details.dangles != 0) && (P->model_details.dangles != 2))
P->model_details.dangles = 2;
turn = (cut_point<0) ? 3 : 0;
uniq_ML = 1;
if(circular){
min_en = fold_par(sequence, struc, P, struct_constrained, circular);
export_circfold_arrays(&Fc, &FcH, &FcI, &FcM, &fM2, &f5, &c, &fML, &fM1, &indx, &ptype);
/* restore dangle model */
P->model_details.dangles = old_dangles;
/* re-evaluate in case we're using logML etc */
min_en = energy_of_circ_struct_par(sequence, struc, P, 0);
} else {
min_en = cofold_par(sequence, struc, P, struct_constrained);
if(with_gquad){
export_cofold_arrays_gq(&f5, &c, &fML, &fM1, &fc, &ggg, &indx, &ptype);
} else {
export_cofold_arrays(&f5, &c, &fML, &fM1, &fc, &indx, &ptype);
}
/* restore dangle model */
P->model_details.dangles = old_dangles;
/* re-evaluate in case we're using logML etc */
min_en = energy_of_struct_par(sequence, struc, P, 0);
}
free(struc);
eprint = print_energy + min_en;
if (fp) {
char *SeQ;
SeQ=costring(sequence);
fprintf(fp, "%s %6d %6d\n", SeQ, (int) (-0.1+100*min_en), delta);
free(SeQ);
}
make_pair_matrix();
S = encode_sequence(sequence, 0);
S1 = encode_sequence(sequence, 1);
/* Initialize ------------------------------------------------------------ */
maxlevel = 0;
count = 0;
partial_energy = 0;
/* Initialize the stack ------------------------------------------------- */
minimal_energy = (circular) ? Fc : f5[length];
threshold = minimal_energy + delta;
if(threshold > INF){
warn_user("energy range too high, limiting to reasonable value");
threshold = INF-EMAX;
}
Stack = make_list(); /* anchor */
Intervals = make_list(); /* initial state: */
interval = make_interval(1, length, 0); /* interval [1,length,0] */
push(Intervals, interval);
state = make_state(Intervals, NULL, partial_energy,0);
/* state->best_energy = minimal_energy; */
push(Stack, state);
/* SolutionList stores the suboptimal structures found */
SolutionList = (SOLUTION *) space(max_sol*sizeof(SOLUTION));
/* end initialize ------------------------------------------------------- */
while (1) { /* forever, til nothing remains on stack */
maxlevel = (Stack->count > maxlevel ? Stack->count : maxlevel);
if (LST_EMPTY (Stack)) /* we are done! clean up and quit */
{
/* fprintf(stderr, "maxlevel: %d\n", maxlevel); */
lst_kill(Stack, free_state_node);
SolutionList[n_sol].structure = NULL; /* NULL terminate list */
if (subopt_sorted) {
/* sort structures by energy */
qsort(SolutionList, n_sol, sizeof(SOLUTION), compare);
if (fp) make_output(SolutionList, fp);
}
break;
}
/* pop the last element ---------------------------------------------- */
state = pop(Stack); /* current state to work with */
if (LST_EMPTY(state->Intervals))
{
int e;
/* state has no intervals left: we got a solution */
count++;
structure = get_structure(state);
structure_energy = state->partial_energy / 100.;
#ifdef CHECK_ENERGY
structure_energy = (circular) ? energy_of_circ_struct_par(sequence, structure, P, 0) : (with_gquad) ? energy_of_gquad_struct_par(sequence, structure, P, 0) : energy_of_struct_par(sequence, structure, P, 0);
if (!logML)
if ((double) (state->partial_energy / 100.) != structure_energy) {
fprintf(stderr, "%s %6.2f %6.2f\n", structure,
state->partial_energy / 100., structure_energy );
exit(1);
}
#endif
if (logML || (dangle_model==1) || (dangle_model==3)) { /* recalc energy */
structure_energy = (circular) ? energy_of_circ_struct_par(sequence, structure, P, 0) : (with_gquad) ? energy_of_gquad_struct_par(sequence, structure, P, 0) : energy_of_struct_par(sequence, structure, P, 0);
}
e = (int) ((structure_energy-min_en)*10. + 0.1); /* avoid rounding errors */
if (e>MAXDOS) e=MAXDOS;
density_of_states[e]++;
if (structure_energy>eprint) {
free(structure);
} else {
if (!subopt_sorted && fp) {
/* print and forget */
if (cut_point<0)
fprintf(fp, "%s %6.2f\n", structure, structure_energy);
else {
char * outstruc;
/*make ampersand seperated output if 2 sequences*/
outstruc=costring(structure);
fprintf(fp, "%s %6.2f\n", outstruc, structure_energy);
free(outstruc);
}
free(structure);
}
else {
/* store solution */
if (n_sol+1 == max_sol) {
max_sol *= 2;
SolutionList = (SOLUTION *)
xrealloc(SolutionList, max_sol*sizeof(SOLUTION));
}
SolutionList[n_sol].energy = structure_energy;
SolutionList[n_sol++].structure = structure;
}
}
}
else {
/* get (and remove) next interval of state to analyze */
interval = pop(state->Intervals);
scan_interval(interval->i, interval->j, interval->array_flag, state);
free_interval_node(interval); /* free the current interval */
}
free_state_node(state); /* free the current state */
} /* end of while (1) */
/* free arrays left over from cofold() */
free(S); free(S1);
(circular) ? free_arrays():free_co_arrays();
if (fp) { /* we've printed everything -- free solutions */
SOLUTION *sol;
for (sol=SolutionList; sol->structure != NULL; sol++)
free(sol->structure);
free(SolutionList);
SolutionList = NULL;
}
return SolutionList;
}
PRIVATE void
scan_interval(int i, int j, int array_flag, STATE * state)
{
/* real backtrack routine */
/* array_flag = 0: trace back in f5-array */
/* array_flag = 1: trace back in fML-array */
/* array_flag = 2: trace back in repeat() */
/* array_flag = 3: trace back in fM1-array */
STATE *new_state, *temp_state;
INTERVAL *new_interval;
register int k, fi, cij;
register int type;
register int dangle_model = P->model_details.dangles;
register int noGUclosure = P->model_details.noGUclosure;
register int noLP = P->model_details.noLP;
best_energy = best_attainable_energy(state); /* .. on remaining intervals */
nopush = true;
if ((i > 1) && (!array_flag))
nrerror ("Error while backtracking!");
if (j < i + turn + 1 && SAME_STRAND(i,j)) { /* minimal structure element */
if (nopush)
push_back(state);
return;
}
/* 13131313131313131313131313131313131313131313131313131313131313131313131 */
if (array_flag == 3 || array_flag == 1) {
/* array_flag = 3: interval i,j was generated during */
/* a multiloop decomposition using array fM1 in repeat() */
/* or in this block */
/* array_flag = 1: interval i,j was generated from a */
/* stack, bulge, or internal loop in repeat() */
/* or in this block */
if (array_flag == 3)
fi = fM1[indx[j-1] + i] + P->MLbase;
else
fi = fML[indx[j-1] + i] + P->MLbase;
if ((fi + best_energy <= threshold)&&(SAME_STRAND(j-1,j))) {
/* no basepair, nibbling of 3'-end */
new_state = copy_state(state);
new_interval = make_interval(i, j-1, array_flag);
push(new_state->Intervals, new_interval);
new_state->partial_energy += P->MLbase;
/* new_state->best_energy = fi + best_energy; */
push(Stack, new_state);
}
type = ptype[indx[j]+i];
if (type) { /* i,j may pair */
if(dangle_model)
element_energy = E_MLstem(type,
(((i > 1)&&(SAME_STRAND(i-1,i))) || circular) ? S1[i-1] : -1,
(((j < length)&&(SAME_STRAND(j,j+1))) || circular) ? S1[j+1] : -1,
P);
else
element_energy = E_MLstem(type, -1, -1, P);
cij = c[indx[j] + i] + element_energy;
if (cij + best_energy <= threshold)
repeat(i, j, state, element_energy, 0);
} else if (with_gquad){
element_energy = E_MLstem(0, -1, -1, P);
cij = ggg[indx[j] + i] + element_energy;
if(cij + best_energy <= threshold)
repeat_gquad(i, j, state, element_energy, 0);
}
} /* array_flag == 3 || array_flag == 1 */
/* 11111111111111111111111111111111111111111111111111111111111111111111111 */
if (array_flag == 1) {
/* array_flag = 1: interval i,j was generated from a */
/* stack, bulge, or internal loop in repeat() */
/* or in this block */
int stopp;
if ((SAME_STRAND(i-1,i))&&(SAME_STRAND(j,j+1))) { /*backtrack in FML only if multiloop is possible*/
for ( k = i+turn+1 ; k <= j-1-turn ; k++) {
/* Multiloop decomposition if i,j contains more than 1 stack */
if(with_gquad){
if(SAME_STRAND(k, k+1)){
element_energy = E_MLstem(0, -1, -1, P);
if(fML[indx[k]+i] + ggg[indx[j] + k + 1] + element_energy + best_energy <= threshold){
temp_state = copy_state (state);
new_interval = make_interval (i, k, 1);
push (temp_state->Intervals, new_interval);
repeat_gquad(k+1, j, temp_state, element_energy, fML[indx[k]+i]);
free_state_node(temp_state);
}
}
}
type = ptype[indx[j]+k+1];
if (type==0) continue;
if(dangle_model)
element_energy = E_MLstem(type,
(SAME_STRAND(i-1,i)) ? S1[k] : -1,
(SAME_STRAND(j,j+1)) ? S1[j+1] : -1,
P);
else
element_energy = E_MLstem(type, -1, -1, P);
if (SAME_STRAND(k,k+1)) {
if (fML[indx[k]+i] + c[indx[j] + k+1] +
element_energy + best_energy <= threshold) {
temp_state = copy_state (state);
new_interval = make_interval (i, k, 1);
push (temp_state->Intervals, new_interval);
repeat(k+1, j, temp_state, element_energy, fML[indx[k]+i]);
free_state_node(temp_state);
}
}
}
}
stopp=(cut_point>0)? (cut_point-2):(length); /*if cut_point -1: k on cut, => no ml*/
stopp=MIN2(stopp, j-1-turn);
if (i>cut_point) stopp=j-1-turn;
else if (i==cut_point) stopp=0; /*not a multi loop*/
for (k = i ; k <= stopp; k++) {
/* Multiloop decomposition if i,j contains only 1 stack */
if(with_gquad){
element_energy = E_MLstem(0, -1, -1, P) + P->MLbase*(k-i+1);
if(ggg[indx[j] + k + 1] + element_energy + best_energy <= threshold)
repeat_gquad(k+1, j, state, element_energy, 0);
}
type = ptype[indx[j]+k+1];
if (type==0) continue;
if(dangle_model)
element_energy = E_MLstem(type,
(SAME_STRAND(k-1,k)) ? S1[k] : -1,
(SAME_STRAND(j,j+1)) ? S1[j+1] : -1,
P);
else
element_energy = E_MLstem(type, -1, -1, P);
element_energy += P->MLbase*(k-i+1);
if (c[indx[j]+k+1] + element_energy + best_energy <= threshold)
repeat(k+1, j, state, element_energy, 0);
}
} /* array_flag == 1 */
/* 2222222222222222222222222222222222222222222222222222222222222222222222 */
if (array_flag == 2)
{
/* array_flag = 2: interval i,j was generated from a */
/* stack, bulge, or internal loop in repeat() */
repeat(i, j, state, 0, 0);
if (nopush){
if (!noLP){
fprintf(stderr, "%d,%d", i, j);
fprintf(stderr, "Oops, no solution in repeat!\n");
}
}
return;
}
/* 0000000000000000000000000000000000000000000000000000000000000000000000 */
if ((array_flag == 0) && !circular)
{
/* array_flag = 0: interval i,j was found while */
/* tracing back through f5-array and c-array */
/* or within this block */
if (f5[j-1] + best_energy <= threshold) {
/* no basepair, nibbling of 3'-end */
new_state = copy_state(state);
new_interval = make_interval(i, j-1 , 0);
push(new_state->Intervals, new_interval);
/* new_state->best_energy = f5[j-1] + best_energy; */
push(Stack, new_state);
}
for (k = j-turn-1; k > 1; k--) {
if(with_gquad){
if(SAME_STRAND(k,j)){
element_energy = 0;
if(f5[k-1] + ggg[indx[j]+k] + element_energy + best_energy <= threshold){
temp_state = copy_state(state);
new_interval = make_interval(1,k-1,0);
push(temp_state->Intervals, new_interval);
/* backtrace the quadruplex */
repeat_gquad(k, j, temp_state, element_energy, f5[k-1]);
free_state_node(temp_state);
}
}
}
type = ptype[indx[j]+k];
if (type==0) continue;
/* k and j pair */
if(dangle_model)
element_energy = E_ExtLoop(type,
(SAME_STRAND(k-1,k)) ? S1[k-1] : -1,
((j < length)&&(SAME_STRAND(j,j+1))) ? S1[j+1] : -1,
P);
else
element_energy = E_ExtLoop(type, -1, -1, P);
if (!(SAME_STRAND(k,j)))/*&&(state->is_duplex==0))*/ {
element_energy+=P->DuplexInit;
/*state->is_duplex=1;*/
}
if (f5[k-1] + c[indx[j]+k] + element_energy + best_energy <= threshold)
{
temp_state = copy_state(state);
new_interval = make_interval(1, k-1, 0);
push(temp_state->Intervals, new_interval);
repeat(k, j, temp_state, element_energy, f5[k-1]);
free_state_node(temp_state);
}
}
type = ptype[indx[j]+1];
if (type) {
if (dangle_model && (j < length)&&(SAME_STRAND(j,j+1)))
element_energy = E_ExtLoop(type, -1, S1[j+1], P);
else
element_energy = E_ExtLoop(type, -1, -1, P);
if (!(SAME_STRAND(1,j))) element_energy+=P->DuplexInit;
if (c[indx[j]+1] + element_energy + best_energy <= threshold)
repeat(1, j, state, element_energy, 0);
} else if (with_gquad){
if(SAME_STRAND(k,j)){
element_energy = 0;
if(ggg[indx[j]+1] + element_energy + best_energy <= threshold){
/* backtrace the quadruplex */
repeat_gquad(1, j, state, element_energy, 0);
}
}
}
}/* end array_flag == 0 && !circular*/
/* or do we subopt circular? */
else if(array_flag == 0){
int k, l, p, q;
/* if we've done everything right, we will never reach this case more than once */
/* right after the initilization of the stack with ([1,n], empty, 0) */
/* lets check, if we can have an open chain without breaking the threshold */
/* this is an ugly work-arround cause in case of an open chain we do not have to */
/* backtrack anything further... */
if(0 <= threshold){
new_state = copy_state(state);
new_interval = make_interval(1,2,0);
push(new_state->Intervals, new_interval);
new_state->partial_energy = 0;
push(Stack, new_state);
}
/* ok, lets check if we can do an exterior hairpin without breaking the threshold */
/* best energy should be 0 if we are here */
if(FcH + best_energy <= threshold){
/* lets search for all exterior hairpin cases, that fit into our threshold barrier */
/* we use index k,l to avoid confusion with i,j index of our state... */
/* if we reach here, i should be 1 and j should be n respectively */
for(k=i; k<j; k++)
for (l=k+turn+1; l <= j; l++){
int kl, type, u, tmpE, no_close;
u = j-l + k-1; /* get the hairpin loop length */
if(u<turn) continue;
kl = indx[l]+k; /* just confusing these indices ;-) */
type = ptype[kl];
no_close = ((type==3)||(type==4))&&noGUclosure;
type=rtype[type];
if (!type) continue;
if (!no_close){
/* now lets have a look at the hairpin energy */
char loopseq[10];
if (u<7){
strcpy(loopseq , sequence+l-1);
strncat(loopseq, sequence, k);
}
tmpE = E_Hairpin(u, type, S1[l+1], S1[k-1], loopseq, P);
}
if(c[kl] + tmpE + best_energy <= threshold){
/* what we really have to do is something like this, isn't it? */
/* we have to create a new state, with interval [k,l], then we */
/* add our loop energy as initial energy of this state and put */
/* the state onto the stack R... for further refinement... */
/* we also denote this new interval to be scanned in C */
new_state = copy_state(state);
new_interval = make_interval(k,l,2);
push(new_state->Intervals, new_interval);
/* hopefully we add this energy in the right way... */
new_state->partial_energy += tmpE;
push(Stack, new_state);
}
}
}
/* now lets see, if we can do an exterior interior loop without breaking the threshold */
if(FcI + best_energy <= threshold){
/* now we search for our exterior interior loop possibilities */
for(k=i; k<j; k++)
for (l=k+turn+1; l <= j; l++){
int kl, type, tmpE;
kl = indx[l]+k; /* just confusing these indices ;-) */
type = ptype[kl];
type=rtype[type];
if (!type) continue;
for (p = l+1; p < j ; p++){
int u1, qmin;
u1 = p-l-1;
if (u1+k-1>MAXLOOP) break;
qmin = u1+k-1+j-MAXLOOP;
if(qmin<p+turn+1) qmin = p+turn+1;
for(q = qmin; q <=j; q++){
int u2, type_2;
type_2 = rtype[ptype[indx[q]+p]];
if(!type_2) continue;
u2 = k-1 + j-q;
if(u1+u2>MAXLOOP) continue;
tmpE = E_IntLoop(u1, u2, type, type_2, S1[l+1], S1[k-1], S1[p-1], S1[q+1], P);
if(c[kl] + c[indx[q]+p] + tmpE + best_energy <= threshold){
/* ok, similar to the hairpin stuff, we add new states onto the stack R */
/* but in contrast to the hairpin decomposition, we have to add two new */
/* intervals, enclosed by k,l and p,q respectively and we also have to */
/* add the partial energy, that comes from the exterior interior loop */
new_state = copy_state(state);
new_interval = make_interval(k, l, 2);
push(new_state->Intervals, new_interval);
new_interval = make_interval(p,q,2);
push(new_state->Intervals, new_interval);
new_state->partial_energy += tmpE;
push(Stack, new_state);
}
}
}
}
}
/* and last but not least, we have a look, if we can do an exterior multiloop within the energy threshold */
if(FcM <= threshold){
/* this decomposition will be somehow more complicated...so lets see what we do here... */
/* first we want to find out which split inidices we can use without exceeding the threshold */
int tmpE2;
for (k=turn+1; k<j-2*turn; k++){
tmpE2 = fML[indx[k]+1]+fM2[k+1]+P->MLclosing;
if(tmpE2 + best_energy <= threshold){
/* grmpfh, we have found a possible split index k so we have to split fM2 and fML now */
/* lets do it first in fM2 anyway */
for(l=k+turn+2; l<j-turn-1; l++){
tmpE2 = fM1[indx[l]+k+1] + fM1[indx[j]+l+1];
if(tmpE2 + fML[indx[k]+1] + P->MLclosing <= threshold){
/* we've (hopefully) found a valid decomposition of fM2 and therefor we have all */
/* three intervals for our new state to be pushed on stack R */
new_state = copy_state(state);
/* first interval leads for search in fML array */
new_interval = make_interval(1, k, 1);
push(new_state->Intervals, new_interval);
/* next, we have the first interval that has to be traced in fM1 */
new_interval = make_interval(k+1, l, 3);
push(new_state->Intervals, new_interval);
/* and the last of our three intervals is also one to be traced within fM1 array... */
new_interval = make_interval(l+1, j, 3);
push(new_state->Intervals, new_interval);
/* mmh, we add the energy for closing the multiloop now... */
new_state->partial_energy += P->MLclosing;
/* next we push our state onto the R stack */
push(Stack, new_state);
}
/* else we search further... */
}
/* ok, we have to decompose fML now... */
}
}
}
} /* thats all folks for the circular case... */
/* 44444444444444444444444444444444444444444444444444444444444444 */
if (array_flag == 4) {
/* array_flag = 4: interval i,j was found while */
/* tracing back through fc-array smaller than than cut_point*/
/* or within this block */
if (fc[i+1] + best_energy <= threshold) {
/* no basepair, nibbling of 5'-end */
new_state = copy_state(state);
new_interval = make_interval(i+1, j , 4);
push(new_state->Intervals, new_interval);
push(Stack, new_state);
}
for (k = i+TURN+1; k < j; k++) {
if(with_gquad){
if(fc[k+1] + ggg[indx[k]+i] + best_energy <= threshold){
temp_state = copy_state(state);
new_interval = make_interval(k+1,j, 4);
push(temp_state->Intervals, new_interval);
repeat_gquad(i, k, temp_state, 0, fc[k+1]);
free_state_node(temp_state);
}
}
type = ptype[indx[k]+i];
if (type==0) continue;
/* k and j pair */
if (dangle_model)
element_energy = E_ExtLoop(type, (i > 1) ? S1[i-1]: -1, S1[k+1], P);
else /* no dangles */
element_energy = E_ExtLoop(type, -1, -1, P);
if (fc[k+1] + c[indx[k]+i] + element_energy + best_energy <= threshold) {
temp_state = copy_state(state);
new_interval = make_interval(k+1,j, 4);
push(temp_state->Intervals, new_interval);
repeat(i, k, temp_state, element_energy, fc[k+1]);
free_state_node(temp_state);
}
}
type = ptype[indx[j]+i];
if (type) {
if (dangle_model)
element_energy = E_ExtLoop(type, (i>1) ? S1[i-1] : -1, -1, P);
else
element_energy = E_ExtLoop(type, -1, -1, P);
if (c[indx[cut_point-1]+i] + element_energy + best_energy <= threshold)
repeat(i, cut_point-1, state, element_energy, 0);
} else if(with_gquad){
if(ggg[indx[cut_point -1] + i] + best_energy <= threshold)
repeat_gquad(i, cut_point - 1, state, 0, 0);
}
} /* array_flag == 4 */
/*55555555555555555555555555555555555555555555555555555555555555555555555*/
if (array_flag == 5) {
/* array_flag = 5: interval cut_point=i,j was found while */
/* tracing back through fc-array greater than cut_point */
/* or within this block */
if (fc[j-1] + best_energy <= threshold) {
/* no basepair, nibbling of 3'-end */
new_state = copy_state(state);
new_interval = make_interval(i, j-1 , 5);
push(new_state->Intervals, new_interval);
push(Stack, new_state);
}
for (k = j-TURN-1; k > i; k--) {
if(with_gquad){
if(fc[k-1] + ggg[indx[j] + k] + best_energy <= threshold){
temp_state = copy_state(state);
new_interval = make_interval(i, k-1, 5);
push(temp_state->Intervals, new_interval);
repeat_gquad(k, j, temp_state, 0, fc[k-1]);
free_state_node(temp_state);
}
}
type = ptype[indx[j]+k];
if (type==0) continue;
element_energy = 0;
/* k and j pair */
if (dangle_model)
element_energy = E_ExtLoop(type, S1[k-1], (j < length) ? S1[j+1] : -1, P);
else
element_energy = E_ExtLoop(type, -1, -1, P);
if (fc[k-1] + c[indx[j]+k] + element_energy + best_energy <= threshold) {
temp_state = copy_state(state);
new_interval = make_interval(i, k-1, 5);
push(temp_state->Intervals, new_interval);
repeat(k, j, temp_state, element_energy, fc[k-1]);
free_state_node(temp_state);
}
}
type = ptype[indx[j]+i];
if (type) {
if(dangle_model)
element_energy = E_ExtLoop(type, -1, (j<length) ? S1[j+1] : -1, P);
if (c[indx[j]+cut_point] + element_energy + best_energy <= threshold)
repeat(cut_point, j, state, element_energy, 0);
} else if (with_gquad){
if(ggg[indx[j] + cut_point] + best_energy <= threshold)
repeat_gquad(cut_point, j, state, 0, 0);
}
} /* array_flag == 5 */
if (array_flag == 6) { /* we have a gquad */
repeat_gquad(i, j, state, 0, 0);
if (nopush){
fprintf(stderr, "%d,%d", i, j);
fprintf(stderr, "Oops, no solution in gquad-repeat!\n");
}
return;
}
if (nopush)
push_back(state);
return;
}
/*---------------------------------------------------------------------------*/
PRIVATE void
repeat_gquad( int i,
int j,
STATE *state,
int part_energy,
int temp_energy){
/* find all gquads that fit into the energy range and the interval [i,j] */
STATE *new_state;
best_energy += part_energy; /* energy of current structural element */
best_energy += temp_energy; /* energy from unpushed interval */
if(SAME_STRAND(i,j)){
element_energy = ggg[indx[j] + i];
if(element_energy + best_energy <= threshold){
int cnt;
int *L;
int *l;
/* find out how many gquads we might expect in the interval [i,j] */
int num_gquads = get_gquad_count(S1, i, j);
num_gquads++;
L = (int *)space(sizeof(int) * num_gquads);
l = (int *)space(sizeof(int) * num_gquads * 3);
L[0] = -1;
get_gquad_pattern_exhaustive(S1, i, j, P, L, l, threshold - best_energy);
for(cnt = 0; L[cnt] != -1; cnt++){
new_state = copy_state(state);
make_gquad(i, L[cnt], &(l[3*cnt]), new_state);
new_state->partial_energy += part_energy;
new_state->partial_energy += element_energy;
/* new_state->best_energy =
hairpin[unpaired] + element_energy + best_energy; */
push(Stack, new_state);
}
free(L);
free(l);
}
}
best_energy -= part_energy;
best_energy -= temp_energy;
return;
}
PRIVATE void
repeat(int i, int j, STATE * state, int part_energy, int temp_energy)
{
/* routine to find stacks, bulges, internal loops and multiloops */
/* within interval closed by basepair i,j */
STATE *new_state;
INTERVAL *new_interval;
register int k, p, q, energy, new;
register int mm;
register int no_close, type, type_2;
int rt;
int dangle_model = P->model_details.dangles;
int noLP = P->model_details.noLP;
int noGUclosure = P->model_details.noGUclosure;
type = ptype[indx[j]+i];
if (type==0) fprintf(stderr, "repeat: Warning: %d %d can't pair\n", i,j);
no_close = (((type == 3) || (type == 4)) && noGUclosure);
if (noLP) /* always consider the structure with additional stack */
if ((i+turn+2<j) && ((type_2 = ptype[indx[j-1]+i+1]))) {
new_state = copy_state(state);
make_pair(i, j, new_state);
make_pair(i+1, j-1, new_state);
new_interval = make_interval(i+1, j-1, 2);
push(new_state->Intervals, new_interval);
if(SAME_STRAND(i,i+1) && SAME_STRAND(j-1,j))
energy = E_IntLoop(0, 0, type, rtype[type_2],S1[i+1],S1[j-1],S1[i+1],S1[j-1], P);
new_state->partial_energy += part_energy;
new_state->partial_energy += energy;
/* new_state->best_energy = new + best_energy; */
push(Stack, new_state);
if (i==1 || state->structure[i-2]!='(' || state->structure[j]!=')')
/* adding a stack is the only possible structure */
return;
}
best_energy += part_energy; /* energy of current structural element */
best_energy += temp_energy; /* energy from unpushed interval */
for (p = i + 1; p <= MIN2 (j-2-turn, i+MAXLOOP+1); p++) {
int minq = j-i+p-MAXLOOP-2;
if (minq<p+1+turn) minq = p+1+turn;
for (q = j - 1; q >= minq; q--) {
if ((noLP) && (p==i+1) && (q==j-1)) continue;
type_2 = ptype[indx[q]+p];
if (type_2==0) continue;
if (noGUclosure)
if (no_close||(type_2==3)||(type_2==4))
if ((p>i+1)||(q<j-1)) continue; /* continue unless stack */
if (SAME_STRAND(i,p) && SAME_STRAND(q,j)) {
energy = E_IntLoop(p-i-1, j-q-1, type, rtype[type_2],
S1[i+1],S1[j-1],S1[p-1],S1[q+1], P);
new = energy + c[indx[q]+p];
if (new + best_energy <= threshold) {
/* stack, bulge, or interior loop */
new_state = copy_state(state);
make_pair(i, j, new_state);
make_pair(p, q, new_state);
new_interval = make_interval(p, q, 2);
push(new_state->Intervals, new_interval);
new_state->partial_energy += part_energy;
new_state->partial_energy += energy;
/* new_state->best_energy = new + best_energy; */
push(Stack, new_state);
}
}/*end of if block */
} /* end of q-loop */
} /* end of p-loop */
if (!SAME_STRAND(i,j)) { /*look in fc*/
rt = rtype[type];
element_energy=0;
if (dangle_model)
element_energy = E_ExtLoop(rt, (SAME_STRAND(j-1,j)) ? S1[j-1] : -1, (SAME_STRAND(i,i+1)) ? S1[i+1] : -1, P);
else
element_energy = E_ExtLoop(rt, -1, -1, P);
if (fc[i+1] + fc[j-1] +element_energy + best_energy <= threshold)
{
INTERVAL *interval1, *interval2;
new_state = copy_state(state);
interval1 = make_interval(i+1, cut_point-1, 4);
interval2 = make_interval(cut_point, j-1, 5);
if (cut_point-i < j-cut_point) { /* push larger interval first */
push(new_state->Intervals, interval1);
push(new_state->Intervals, interval2);
} else {
push(new_state->Intervals, interval2);
push(new_state->Intervals, interval1);
}
make_pair(i, j, new_state);
new_state->partial_energy += part_energy;
new_state->partial_energy += element_energy;
push(Stack, new_state);
}
}
mm = P->MLclosing;
rt = rtype[type];
for (k = i + 1 + turn; k <= j - 2 - turn; k++) {
/* multiloop decomposition */
element_energy = mm;
if (dangle_model)
element_energy = E_MLstem(rt, S1[j-1], S1[i+1], P) + mm;
else
element_energy = E_MLstem(rt, -1, -1, P) + mm;
if ((fML[indx[k] + i+1] + fM1[indx[j-1] + k+1] +
element_energy + best_energy) <= threshold)
{
INTERVAL *interval1, *interval2;
new_state = copy_state(state);
interval1 = make_interval(i+1, k, 1);
interval2 = make_interval(k+1, j-1, 3);
if (k-i+1 < j-k-2) { /* push larger interval first */
push(new_state->Intervals, interval1);
push(new_state->Intervals, interval2);
} else {
push(new_state->Intervals, interval2);
push(new_state->Intervals, interval1);
}
make_pair(i, j, new_state);
new_state->partial_energy += part_energy;
new_state->partial_energy += element_energy;
/* new_state->best_energy = fML[indx[k] + i+1] + fM1[indx[j-1] + k+1]
+ element_energy + best_energy; */
push(Stack, new_state);
}
} /* end of k-loop */
if (SAME_STRAND(i,j)) {
if (no_close) element_energy = FORBIDDEN;
else
element_energy = E_Hairpin(j-i-1, type, S1[i+1], S1[j-1], sequence+i-1, P);
if (element_energy + best_energy <= threshold) {
/* hairpin structure */
new_state = copy_state(state);
make_pair(i, j, new_state);
new_state->partial_energy += part_energy;
new_state->partial_energy += element_energy;
/* new_state->best_energy =
hairpin[unpaired] + element_energy + best_energy; */
push(Stack, new_state);
}
if(with_gquad){
/* now we have to find all loops where (i,j) encloses a gquad in an interior loops style */
int cnt, *p, *q, *en;
p = q = en = NULL;
en = E_GQuad_IntLoop_exhaustive(i, j, &p, &q, type, S1, ggg, threshold - best_energy, indx, P);
for(cnt = 0; p[cnt] != -1; cnt++){
new_state = copy_state(state);
make_pair(i, j, new_state);
new_interval = make_interval(p[cnt], q[cnt], 6);
push(new_state->Intervals, new_interval);
new_state->partial_energy += part_energy;
new_state->partial_energy += en[cnt];
/* new_state->best_energy = new + best_energy; */
push(Stack, new_state);
}
free(en);
free(p);
free(q);
}
}
best_energy -= part_energy;
best_energy -= temp_energy;
return;
}
PRIVATE char *costring(char *string)
{
char *ctmp;
int len;
len = strlen(string);
ctmp = (char *)space((len+2) * sizeof(char));
/* first sequence */
if (cut_point<=0) {
(void) strncpy(ctmp, string, len);
return ctmp;
}
(void) strncpy(ctmp, string, cut_point-1);
/* spacer */
ctmp[cut_point-1] = '&';
/* second sequence */
(void) strcat(ctmp, string+cut_point-1);
return ctmp;
}
/*---------------------------------------------------------------------------*/
/* Well, that is the end!----------------------------------------------------*/
/*---------------------------------------------------------------------------*/
|
irbuilder_for_unsigned_dynamic_chunked.c | // NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py UTC_ARGS: --function-signature --include-generated-funcs
// RUN: %clang_cc1 -fopenmp-enable-irbuilder -verify -fopenmp -fopenmp-version=45 -x c++ -triple x86_64-unknown-unknown -emit-llvm %s -o - | FileCheck %s
// expected-no-diagnostics
#ifndef HEADER
#define HEADER
// CHECK-LABEL: define {{.*}}@workshareloop_unsigned_dynamic_chunked(
// CHECK-NEXT: [[ENTRY:.*]]:
// CHECK-NEXT: %[[A_ADDR:.+]] = alloca float*, align 8
// CHECK-NEXT: %[[B_ADDR:.+]] = alloca float*, align 8
// CHECK-NEXT: %[[C_ADDR:.+]] = alloca float*, align 8
// CHECK-NEXT: %[[D_ADDR:.+]] = alloca float*, align 8
// CHECK-NEXT: %[[I:.+]] = alloca i32, align 4
// CHECK-NEXT: %[[AGG_CAPTURED:.+]] = alloca %struct.anon, align 8
// CHECK-NEXT: %[[AGG_CAPTURED1:.+]] = alloca %struct.anon.0, align 4
// CHECK-NEXT: %[[DOTCOUNT_ADDR:.+]] = alloca i32, align 4
// CHECK-NEXT: %[[P_LASTITER:.+]] = alloca i32, align 4
// CHECK-NEXT: %[[P_LOWERBOUND:.+]] = alloca i32, align 4
// CHECK-NEXT: %[[P_UPPERBOUND:.+]] = alloca i32, align 4
// CHECK-NEXT: %[[P_STRIDE:.+]] = alloca i32, align 4
// CHECK-NEXT: store float* %[[A:.+]], float** %[[A_ADDR]], align 8
// CHECK-NEXT: store float* %[[B:.+]], float** %[[B_ADDR]], align 8
// CHECK-NEXT: store float* %[[C:.+]], float** %[[C_ADDR]], align 8
// CHECK-NEXT: store float* %[[D:.+]], float** %[[D_ADDR]], align 8
// CHECK-NEXT: store i32 33, i32* %[[I]], align 4
// CHECK-NEXT: %[[TMP0:.+]] = getelementptr inbounds %struct.anon, %struct.anon* %[[AGG_CAPTURED]], i32 0, i32 0
// CHECK-NEXT: store i32* %[[I]], i32** %[[TMP0]], align 8
// CHECK-NEXT: %[[TMP1:.+]] = getelementptr inbounds %struct.anon.0, %struct.anon.0* %[[AGG_CAPTURED1]], i32 0, i32 0
// CHECK-NEXT: %[[TMP2:.+]] = load i32, i32* %[[I]], align 4
// CHECK-NEXT: store i32 %[[TMP2]], i32* %[[TMP1]], align 4
// CHECK-NEXT: call void @__captured_stmt(i32* %[[DOTCOUNT_ADDR]], %struct.anon* %[[AGG_CAPTURED]])
// CHECK-NEXT: %[[DOTCOUNT:.+]] = load i32, i32* %[[DOTCOUNT_ADDR]], align 4
// CHECK-NEXT: br label %[[OMP_LOOP_PREHEADER:.+]]
// CHECK-EMPTY:
// CHECK-NEXT: [[OMP_LOOP_PREHEADER]]:
// CHECK-NEXT: store i32 1, i32* %[[P_LOWERBOUND]], align 4
// CHECK-NEXT: store i32 %[[DOTCOUNT]], i32* %[[P_UPPERBOUND]], align 4
// CHECK-NEXT: store i32 1, i32* %[[P_STRIDE]], align 4
// CHECK-NEXT: %[[OMP_GLOBAL_THREAD_NUM:.+]] = call i32 @__kmpc_global_thread_num(%struct.ident_t* @1)
// CHECK-NEXT: call void @__kmpc_dispatch_init_4u(%struct.ident_t* @1, i32 %[[OMP_GLOBAL_THREAD_NUM]], i32 35, i32 1, i32 %[[DOTCOUNT]], i32 1, i32 5)
// CHECK-NEXT: br label %[[OMP_LOOP_PREHEADER_OUTER_COND:.+]]
// CHECK-EMPTY:
// CHECK-NEXT: [[OMP_LOOP_HEADER:.*]]:
// CHECK-NEXT: %[[OMP_LOOP_IV:.+]] = phi i32 [ %[[LB:.+]], %[[OMP_LOOP_PREHEADER_OUTER_COND]] ], [ %[[OMP_LOOP_NEXT:.+]], %[[OMP_LOOP_INC:.+]] ]
// CHECK-NEXT: br label %[[OMP_LOOP_COND:.+]]
// CHECK-EMPTY:
// CHECK-NEXT: [[OMP_LOOP_COND]]:
// CHECK-NEXT: %[[UB:.+]] = load i32, i32* %[[P_UPPERBOUND]], align 4
// CHECK-NEXT: %[[OMP_LOOP_CMP:.+]] = icmp ult i32 %[[OMP_LOOP_IV]], %[[UB]]
// CHECK-NEXT: br i1 %[[OMP_LOOP_CMP]], label %[[OMP_LOOP_BODY:.+]], label %[[OMP_LOOP_PREHEADER_OUTER_COND]]
// CHECK-EMPTY:
// CHECK-NEXT: [[OMP_LOOP_BODY]]:
// CHECK-NEXT: call void @__captured_stmt.1(i32* %[[I]], i32 %[[OMP_LOOP_IV]], %struct.anon.0* %[[AGG_CAPTURED1]])
// CHECK-NEXT: %[[TMP3:.+]] = load float*, float** %[[B_ADDR]], align 8
// CHECK-NEXT: %[[TMP4:.+]] = load i32, i32* %[[I]], align 4
// CHECK-NEXT: %[[IDXPROM:.+]] = zext i32 %[[TMP4]] to i64
// CHECK-NEXT: %[[ARRAYIDX:.+]] = getelementptr inbounds float, float* %[[TMP3]], i64 %[[IDXPROM]]
// CHECK-NEXT: %[[TMP5:.+]] = load float, float* %[[ARRAYIDX]], align 4
// CHECK-NEXT: %[[TMP6:.+]] = load float*, float** %[[C_ADDR]], align 8
// CHECK-NEXT: %[[TMP7:.+]] = load i32, i32* %[[I]], align 4
// CHECK-NEXT: %[[IDXPROM2:.+]] = zext i32 %[[TMP7]] to i64
// CHECK-NEXT: %[[ARRAYIDX3:.+]] = getelementptr inbounds float, float* %[[TMP6]], i64 %[[IDXPROM2]]
// CHECK-NEXT: %[[TMP8:.+]] = load float, float* %[[ARRAYIDX3]], align 4
// CHECK-NEXT: %[[MUL:.+]] = fmul float %[[TMP5]], %[[TMP8]]
// CHECK-NEXT: %[[TMP9:.+]] = load float*, float** %[[D_ADDR]], align 8
// CHECK-NEXT: %[[TMP10:.+]] = load i32, i32* %[[I]], align 4
// CHECK-NEXT: %[[IDXPROM4:.+]] = zext i32 %[[TMP10]] to i64
// CHECK-NEXT: %[[ARRAYIDX5:.+]] = getelementptr inbounds float, float* %[[TMP9]], i64 %[[IDXPROM4]]
// CHECK-NEXT: %[[TMP11:.+]] = load float, float* %[[ARRAYIDX5]], align 4
// CHECK-NEXT: %[[MUL6:.+]] = fmul float %[[MUL]], %[[TMP11]]
// CHECK-NEXT: %[[TMP12:.+]] = load float*, float** %[[A_ADDR]], align 8
// CHECK-NEXT: %[[TMP13:.+]] = load i32, i32* %[[I]], align 4
// CHECK-NEXT: %[[IDXPROM7:.+]] = zext i32 %[[TMP13]] to i64
// CHECK-NEXT: %[[ARRAYIDX8:.+]] = getelementptr inbounds float, float* %[[TMP12]], i64 %[[IDXPROM7]]
// CHECK-NEXT: store float %[[MUL6]], float* %[[ARRAYIDX8]], align 4
// CHECK-NEXT: br label %[[OMP_LOOP_INC]]
// CHECK-EMPTY:
// CHECK-NEXT: [[OMP_LOOP_INC]]:
// CHECK-NEXT: %[[OMP_LOOP_NEXT]] = add nuw i32 %[[OMP_LOOP_IV]], 1
// CHECK-NEXT: br label %[[OMP_LOOP_HEADER]]
// CHECK-EMPTY:
// CHECK-NEXT: [[OMP_LOOP_EXIT:.*]]:
// CHECK-NEXT: %[[OMP_GLOBAL_THREAD_NUM9:.+]] = call i32 @__kmpc_global_thread_num(%struct.ident_t* @1)
// CHECK-NEXT: call void @__kmpc_barrier(%struct.ident_t* @2, i32 %[[OMP_GLOBAL_THREAD_NUM9]])
// CHECK-NEXT: br label %[[OMP_LOOP_AFTER:.+]]
// CHECK-EMPTY:
// CHECK-NEXT: [[OMP_LOOP_AFTER]]:
// CHECK-NEXT: ret void
// CHECK-EMPTY:
// CHECK-NEXT: [[OMP_LOOP_PREHEADER_OUTER_COND]]:
// CHECK-NEXT: %[[TMP14:.+]] = call i32 @__kmpc_dispatch_next_4u(%struct.ident_t* @1, i32 %[[OMP_GLOBAL_THREAD_NUM]], i32* %[[P_LASTITER]], i32* %[[P_LOWERBOUND]], i32* %[[P_UPPERBOUND]], i32* %[[P_STRIDE]])
// CHECK-NEXT: %[[TMP15:.+]] = icmp ne i32 %[[TMP14]], 0
// CHECK-NEXT: %[[TMP16:.+]] = load i32, i32* %[[P_LOWERBOUND]], align 4
// CHECK-NEXT: %[[LB]] = sub i32 %[[TMP16]], 1
// CHECK-NEXT: br i1 %[[TMP15]], label %[[OMP_LOOP_HEADER]], label %[[OMP_LOOP_EXIT]]
// CHECK-NEXT: }
extern "C" void workshareloop_unsigned_dynamic_chunked(float *a, float *b, float *c, float *d) {
#pragma omp for schedule(dynamic, 5)
for (unsigned i = 33; i < 32000000; i += 7) {
a[i] = b[i] * c[i] * d[i];
}
}
#endif // HEADER
// CHECK-LABEL: define {{.*}}@__captured_stmt(
// CHECK-NEXT: [[ENTRY:.*]]:
// CHECK-NEXT: %[[DISTANCE_ADDR:.+]] = alloca i32*, align 8
// CHECK-NEXT: %[[__CONTEXT_ADDR:.+]] = alloca %struct.anon*, align 8
// CHECK-NEXT: %[[DOTSTART:.+]] = alloca i32, align 4
// CHECK-NEXT: %[[DOTSTOP:.+]] = alloca i32, align 4
// CHECK-NEXT: %[[DOTSTEP:.+]] = alloca i32, align 4
// CHECK-NEXT: store i32* %[[DISTANCE:.+]], i32** %[[DISTANCE_ADDR]], align 8
// CHECK-NEXT: store %struct.anon* %[[__CONTEXT:.+]], %struct.anon** %[[__CONTEXT_ADDR]], align 8
// CHECK-NEXT: %[[TMP0:.+]] = load %struct.anon*, %struct.anon** %[[__CONTEXT_ADDR]], align 8
// CHECK-NEXT: %[[TMP1:.+]] = getelementptr inbounds %struct.anon, %struct.anon* %[[TMP0]], i32 0, i32 0
// CHECK-NEXT: %[[TMP2:.+]] = load i32*, i32** %[[TMP1]], align 8
// CHECK-NEXT: %[[TMP3:.+]] = load i32, i32* %[[TMP2]], align 4
// CHECK-NEXT: store i32 %[[TMP3]], i32* %[[DOTSTART]], align 4
// CHECK-NEXT: store i32 32000000, i32* %[[DOTSTOP]], align 4
// CHECK-NEXT: store i32 7, i32* %[[DOTSTEP]], align 4
// CHECK-NEXT: %[[TMP4:.+]] = load i32, i32* %[[DOTSTART]], align 4
// CHECK-NEXT: %[[TMP5:.+]] = load i32, i32* %[[DOTSTOP]], align 4
// CHECK-NEXT: %[[CMP:.+]] = icmp ult i32 %[[TMP4]], %[[TMP5]]
// CHECK-NEXT: br i1 %[[CMP]], label %[[COND_TRUE:.+]], label %[[COND_FALSE:.+]]
// CHECK-EMPTY:
// CHECK-NEXT: [[COND_TRUE]]:
// CHECK-NEXT: %[[TMP6:.+]] = load i32, i32* %[[DOTSTOP]], align 4
// CHECK-NEXT: %[[TMP7:.+]] = load i32, i32* %[[DOTSTART]], align 4
// CHECK-NEXT: %[[SUB:.+]] = sub i32 %[[TMP6]], %[[TMP7]]
// CHECK-NEXT: %[[TMP8:.+]] = load i32, i32* %[[DOTSTEP]], align 4
// CHECK-NEXT: %[[SUB1:.+]] = sub i32 %[[TMP8]], 1
// CHECK-NEXT: %[[ADD:.+]] = add i32 %[[SUB]], %[[SUB1]]
// CHECK-NEXT: %[[TMP9:.+]] = load i32, i32* %[[DOTSTEP]], align 4
// CHECK-NEXT: %[[DIV:.+]] = udiv i32 %[[ADD]], %[[TMP9]]
// CHECK-NEXT: br label %[[COND_END:.+]]
// CHECK-EMPTY:
// CHECK-NEXT: [[COND_FALSE]]:
// CHECK-NEXT: br label %[[COND_END]]
// CHECK-EMPTY:
// CHECK-NEXT: [[COND_END]]:
// CHECK-NEXT: %[[COND:.+]] = phi i32 [ %[[DIV]], %[[COND_TRUE]] ], [ 0, %[[COND_FALSE]] ]
// CHECK-NEXT: %[[TMP10:.+]] = load i32*, i32** %[[DISTANCE_ADDR]], align 8
// CHECK-NEXT: store i32 %[[COND]], i32* %[[TMP10]], align 4
// CHECK-NEXT: ret void
// CHECK-NEXT: }
// CHECK-LABEL: define {{.*}}@__captured_stmt.1(
// CHECK-NEXT: [[ENTRY:.*]]:
// CHECK-NEXT: %[[LOOPVAR_ADDR:.+]] = alloca i32*, align 8
// CHECK-NEXT: %[[LOGICAL_ADDR:.+]] = alloca i32, align 4
// CHECK-NEXT: %[[__CONTEXT_ADDR:.+]] = alloca %struct.anon.0*, align 8
// CHECK-NEXT: store i32* %[[LOOPVAR:.+]], i32** %[[LOOPVAR_ADDR]], align 8
// CHECK-NEXT: store i32 %[[LOGICAL:.+]], i32* %[[LOGICAL_ADDR]], align 4
// CHECK-NEXT: store %struct.anon.0* %[[__CONTEXT:.+]], %struct.anon.0** %[[__CONTEXT_ADDR]], align 8
// CHECK-NEXT: %[[TMP0:.+]] = load %struct.anon.0*, %struct.anon.0** %[[__CONTEXT_ADDR]], align 8
// CHECK-NEXT: %[[TMP1:.+]] = getelementptr inbounds %struct.anon.0, %struct.anon.0* %[[TMP0]], i32 0, i32 0
// CHECK-NEXT: %[[TMP2:.+]] = load i32, i32* %[[TMP1]], align 4
// CHECK-NEXT: %[[TMP3:.+]] = load i32, i32* %[[LOGICAL_ADDR]], align 4
// CHECK-NEXT: %[[MUL:.+]] = mul i32 7, %[[TMP3]]
// CHECK-NEXT: %[[ADD:.+]] = add i32 %[[TMP2]], %[[MUL]]
// CHECK-NEXT: %[[TMP4:.+]] = load i32*, i32** %[[LOOPVAR_ADDR]], align 8
// CHECK-NEXT: store i32 %[[ADD]], i32* %[[TMP4]], align 4
// CHECK-NEXT: ret void
// CHECK-NEXT: }
// CHECK: ![[META0:[0-9]+]] = !{i32 1, !"wchar_size", i32 4}
// CHECK: ![[META1:[0-9]+]] = !{i32 7, !"openmp", i32 45}
// CHECK: ![[META2:[0-9]+]] =
|
tinyexr.h | #ifndef TINYEXR_H_
#define TINYEXR_H_
/*
Copyright (c) 2014 - 2020, Syoyo Fujita and many contributors.
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 Syoyo Fujita 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 <COPYRIGHT HOLDER> 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.
*/
// TinyEXR contains some OpenEXR code, which is licensed under ------------
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2002, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// 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 Industrial Light & Magic 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.
//
///////////////////////////////////////////////////////////////////////////
// End of OpenEXR license -------------------------------------------------
//
//
// Do this:
// #define TINYEXR_IMPLEMENTATION
// before you include this file in *one* C or C++ file to create the
// implementation.
//
// // i.e. it should look like this:
// #include ...
// #include ...
// #include ...
// #define TINYEXR_IMPLEMENTATION
// #include "tinyexr.h"
//
//
#include <stddef.h> // for size_t
#include <stdint.h> // guess stdint.h is available(C99)
#ifdef __cplusplus
extern "C" {
#endif
// Use embedded miniz or not to decode ZIP format pixel. Linking with zlib
// required if this flas is 0.
#ifndef TINYEXR_USE_MINIZ
#define TINYEXR_USE_MINIZ (1)
#endif
// Disable PIZ comporession when applying cpplint.
#ifndef TINYEXR_USE_PIZ
#define TINYEXR_USE_PIZ (1)
#endif
#ifndef TINYEXR_USE_ZFP
#define TINYEXR_USE_ZFP (0) // TinyEXR extension.
// http://computation.llnl.gov/projects/floating-point-compression
#endif
#ifndef TINYEXR_USE_THREAD
#define TINYEXR_USE_THREAD (0) // No threaded loading.
// http://computation.llnl.gov/projects/floating-point-compression
#endif
#ifndef TINYEXR_USE_OPENMP
#ifdef _OPENMP
#define TINYEXR_USE_OPENMP (1)
#else
#define TINYEXR_USE_OPENMP (0)
#endif
#endif
#define TINYEXR_SUCCESS (0)
#define TINYEXR_ERROR_INVALID_MAGIC_NUMBER (-1)
#define TINYEXR_ERROR_INVALID_EXR_VERSION (-2)
#define TINYEXR_ERROR_INVALID_ARGUMENT (-3)
#define TINYEXR_ERROR_INVALID_DATA (-4)
#define TINYEXR_ERROR_INVALID_FILE (-5)
#define TINYEXR_ERROR_INVALID_PARAMETER (-6)
#define TINYEXR_ERROR_CANT_OPEN_FILE (-7)
#define TINYEXR_ERROR_UNSUPPORTED_FORMAT (-8)
#define TINYEXR_ERROR_INVALID_HEADER (-9)
#define TINYEXR_ERROR_UNSUPPORTED_FEATURE (-10)
#define TINYEXR_ERROR_CANT_WRITE_FILE (-11)
#define TINYEXR_ERROR_SERIALZATION_FAILED (-12)
#define TINYEXR_ERROR_LAYER_NOT_FOUND (-13)
// @note { OpenEXR file format: http://www.openexr.com/openexrfilelayout.pdf }
// pixel type: possible values are: UINT = 0 HALF = 1 FLOAT = 2
#define TINYEXR_PIXELTYPE_UINT (0)
#define TINYEXR_PIXELTYPE_HALF (1)
#define TINYEXR_PIXELTYPE_FLOAT (2)
#define TINYEXR_MAX_HEADER_ATTRIBUTES (1024)
#define TINYEXR_MAX_CUSTOM_ATTRIBUTES (128)
#define TINYEXR_COMPRESSIONTYPE_NONE (0)
#define TINYEXR_COMPRESSIONTYPE_RLE (1)
#define TINYEXR_COMPRESSIONTYPE_ZIPS (2)
#define TINYEXR_COMPRESSIONTYPE_ZIP (3)
#define TINYEXR_COMPRESSIONTYPE_PIZ (4)
#define TINYEXR_COMPRESSIONTYPE_ZFP (128) // TinyEXR extension
#define TINYEXR_ZFP_COMPRESSIONTYPE_RATE (0)
#define TINYEXR_ZFP_COMPRESSIONTYPE_PRECISION (1)
#define TINYEXR_ZFP_COMPRESSIONTYPE_ACCURACY (2)
#define TINYEXR_TILE_ONE_LEVEL (0)
#define TINYEXR_TILE_MIPMAP_LEVELS (1)
#define TINYEXR_TILE_RIPMAP_LEVELS (2)
#define TINYEXR_TILE_ROUND_DOWN (0)
#define TINYEXR_TILE_ROUND_UP (1)
typedef struct _EXRVersion {
int version; // this must be 2
// tile format image;
// not zero for only a single-part "normal" tiled file (according to spec.)
int tiled;
int long_name; // long name attribute
// deep image(EXR 2.0);
// for a multi-part file, indicates that at least one part is of type deep* (according to spec.)
int non_image;
int multipart; // multi-part(EXR 2.0)
} EXRVersion;
typedef struct _EXRAttribute {
char name[256]; // name and type are up to 255 chars long.
char type[256];
unsigned char *value; // uint8_t*
int size;
int pad0;
} EXRAttribute;
typedef struct _EXRChannelInfo {
char name[256]; // less than 255 bytes long
int pixel_type;
int x_sampling;
int y_sampling;
unsigned char p_linear;
unsigned char pad[3];
} EXRChannelInfo;
typedef struct _EXRTile {
int offset_x;
int offset_y;
int level_x;
int level_y;
int width; // actual width in a tile.
int height; // actual height int a tile.
unsigned char **images; // image[channels][pixels]
} EXRTile;
typedef struct _EXRBox2i {
int min_x;
int min_y;
int max_x;
int max_y;
} EXRBox2i;
typedef struct _EXRHeader {
float pixel_aspect_ratio;
int line_order;
EXRBox2i data_window;
EXRBox2i display_window;
float screen_window_center[2];
float screen_window_width;
int chunk_count;
// Properties for tiled format(`tiledesc`).
int tiled;
int tile_size_x;
int tile_size_y;
int tile_level_mode;
int tile_rounding_mode;
int long_name;
// for a single-part file, agree with the version field bit 11
// for a multi-part file, it is consistent with the type of part
int non_image;
int multipart;
unsigned int header_len;
// Custom attributes(exludes required attributes(e.g. `channels`,
// `compression`, etc)
int num_custom_attributes;
EXRAttribute *custom_attributes; // array of EXRAttribute. size =
// `num_custom_attributes`.
EXRChannelInfo *channels; // [num_channels]
int *pixel_types; // Loaded pixel type(TINYEXR_PIXELTYPE_*) of `images` for
// each channel. This is overwritten with `requested_pixel_types` when
// loading.
int num_channels;
int compression_type; // compression type(TINYEXR_COMPRESSIONTYPE_*)
int *requested_pixel_types; // Filled initially by
// ParseEXRHeaderFrom(Meomory|File), then users
// can edit it(only valid for HALF pixel type
// channel)
// name attribute required for multipart files;
// must be unique and non empty (according to spec.);
// use EXRSetNameAttr for setting value;
// max 255 character allowed - excluding terminating zero
char name[256];
} EXRHeader;
typedef struct _EXRMultiPartHeader {
int num_headers;
EXRHeader *headers;
} EXRMultiPartHeader;
typedef struct _EXRImage {
EXRTile *tiles; // Tiled pixel data. The application must reconstruct image
// from tiles manually. NULL if scanline format.
struct _EXRImage* next_level; // NULL if scanline format or image is the last level.
int level_x; // x level index
int level_y; // y level index
unsigned char **images; // image[channels][pixels]. NULL if tiled format.
int width;
int height;
int num_channels;
// Properties for tile format.
int num_tiles;
} EXRImage;
typedef struct _EXRMultiPartImage {
int num_images;
EXRImage *images;
} EXRMultiPartImage;
typedef struct _DeepImage {
const char **channel_names;
float ***image; // image[channels][scanlines][samples]
int **offset_table; // offset_table[scanline][offsets]
int num_channels;
int width;
int height;
int pad0;
} DeepImage;
// @deprecated { For backward compatibility. Not recommended to use. }
// Loads single-frame OpenEXR image. Assume EXR image contains A(single channel
// alpha) or RGB(A) channels.
// Application must free image data as returned by `out_rgba`
// Result image format is: float x RGBA x width x hight
// Returns negative value and may set error string in `err` when there's an
// error
extern int LoadEXR(float **out_rgba, int *width, int *height,
const char *filename, const char **err);
// Loads single-frame OpenEXR image by specifying layer name. Assume EXR image
// contains A(single channel alpha) or RGB(A) channels. Application must free
// image data as returned by `out_rgba` Result image format is: float x RGBA x
// width x hight Returns negative value and may set error string in `err` when
// there's an error When the specified layer name is not found in the EXR file,
// the function will return `TINYEXR_ERROR_LAYER_NOT_FOUND`.
extern int LoadEXRWithLayer(float **out_rgba, int *width, int *height,
const char *filename, const char *layer_name,
const char **err);
//
// Get layer infos from EXR file.
//
// @param[out] layer_names List of layer names. Application must free memory
// after using this.
// @param[out] num_layers The number of layers
// @param[out] err Error string(will be filled when the function returns error
// code). Free it using FreeEXRErrorMessage after using this value.
//
// @return TINYEXR_SUCCEES upon success.
//
extern int EXRLayers(const char *filename, const char **layer_names[],
int *num_layers, const char **err);
// @deprecated { to be removed. }
// Simple wrapper API for ParseEXRHeaderFromFile.
// checking given file is a EXR file(by just look up header)
// @return TINYEXR_SUCCEES for EXR image, TINYEXR_ERROR_INVALID_HEADER for
// others
extern int IsEXR(const char *filename);
// @deprecated { to be removed. }
// Saves single-frame OpenEXR image. Assume EXR image contains RGB(A) channels.
// components must be 1(Grayscale), 3(RGB) or 4(RGBA).
// Input image format is: `float x width x height`, or `float x RGB(A) x width x
// hight`
// Save image as fp16(HALF) format when `save_as_fp16` is positive non-zero
// value.
// Save image as fp32(FLOAT) format when `save_as_fp16` is 0.
// Use ZIP compression by default.
// Returns negative value and may set error string in `err` when there's an
// error
extern int SaveEXR(const float *data, const int width, const int height,
const int components, const int save_as_fp16,
const char *filename, const char **err);
// Returns the number of resolution levels of the image (including the base)
extern int EXRNumLevels(const EXRImage* exr_image);
// Initialize EXRHeader struct
extern void InitEXRHeader(EXRHeader *exr_header);
// Set name attribute of EXRHeader struct (it makes a copy)
extern void EXRSetNameAttr(EXRHeader *exr_header, const char* name);
// Initialize EXRImage struct
extern void InitEXRImage(EXRImage *exr_image);
// Frees internal data of EXRHeader struct
extern int FreeEXRHeader(EXRHeader *exr_header);
// Frees internal data of EXRImage struct
extern int FreeEXRImage(EXRImage *exr_image);
// Frees error message
extern void FreeEXRErrorMessage(const char *msg);
// Parse EXR version header of a file.
extern int ParseEXRVersionFromFile(EXRVersion *version, const char *filename);
// Parse EXR version header from memory-mapped EXR data.
extern int ParseEXRVersionFromMemory(EXRVersion *version,
const unsigned char *memory, size_t size);
// Parse single-part OpenEXR header from a file and initialize `EXRHeader`.
// When there was an error message, Application must free `err` with
// FreeEXRErrorMessage()
extern int ParseEXRHeaderFromFile(EXRHeader *header, const EXRVersion *version,
const char *filename, const char **err);
// Parse single-part OpenEXR header from a memory and initialize `EXRHeader`.
// When there was an error message, Application must free `err` with
// FreeEXRErrorMessage()
extern int ParseEXRHeaderFromMemory(EXRHeader *header,
const EXRVersion *version,
const unsigned char *memory, size_t size,
const char **err);
// Parse multi-part OpenEXR headers from a file and initialize `EXRHeader*`
// array.
// When there was an error message, Application must free `err` with
// FreeEXRErrorMessage()
extern int ParseEXRMultipartHeaderFromFile(EXRHeader ***headers,
int *num_headers,
const EXRVersion *version,
const char *filename,
const char **err);
// Parse multi-part OpenEXR headers from a memory and initialize `EXRHeader*`
// array
// When there was an error message, Application must free `err` with
// FreeEXRErrorMessage()
extern int ParseEXRMultipartHeaderFromMemory(EXRHeader ***headers,
int *num_headers,
const EXRVersion *version,
const unsigned char *memory,
size_t size, const char **err);
// Loads single-part OpenEXR image from a file.
// Application must setup `ParseEXRHeaderFromFile` before calling this function.
// Application can free EXRImage using `FreeEXRImage`
// Returns negative value and may set error string in `err` when there's an
// error
// When there was an error message, Application must free `err` with
// FreeEXRErrorMessage()
extern int LoadEXRImageFromFile(EXRImage *image, const EXRHeader *header,
const char *filename, const char **err);
// Loads single-part OpenEXR image from a memory.
// Application must setup `EXRHeader` with
// `ParseEXRHeaderFromMemory` before calling this function.
// Application can free EXRImage using `FreeEXRImage`
// Returns negative value and may set error string in `err` when there's an
// error
// When there was an error message, Application must free `err` with
// FreeEXRErrorMessage()
extern int LoadEXRImageFromMemory(EXRImage *image, const EXRHeader *header,
const unsigned char *memory,
const size_t size, const char **err);
// Loads multi-part OpenEXR image from a file.
// Application must setup `ParseEXRMultipartHeaderFromFile` before calling this
// function.
// Application can free EXRImage using `FreeEXRImage`
// Returns negative value and may set error string in `err` when there's an
// error
// When there was an error message, Application must free `err` with
// FreeEXRErrorMessage()
extern int LoadEXRMultipartImageFromFile(EXRImage *images,
const EXRHeader **headers,
unsigned int num_parts,
const char *filename,
const char **err);
// Loads multi-part OpenEXR image from a memory.
// Application must setup `EXRHeader*` array with
// `ParseEXRMultipartHeaderFromMemory` before calling this function.
// Application can free EXRImage using `FreeEXRImage`
// Returns negative value and may set error string in `err` when there's an
// error
// When there was an error message, Application must free `err` with
// FreeEXRErrorMessage()
extern int LoadEXRMultipartImageFromMemory(EXRImage *images,
const EXRHeader **headers,
unsigned int num_parts,
const unsigned char *memory,
const size_t size, const char **err);
// Saves multi-channel, single-frame OpenEXR image to a file.
// Returns negative value and may set error string in `err` when there's an
// error
// When there was an error message, Application must free `err` with
// FreeEXRErrorMessage()
extern int SaveEXRImageToFile(const EXRImage *image,
const EXRHeader *exr_header, const char *filename,
const char **err);
// Saves multi-channel, single-frame OpenEXR image to a memory.
// Image is compressed using EXRImage.compression value.
// Return the number of bytes if success.
// Return zero and will set error string in `err` when there's an
// error.
// When there was an error message, Application must free `err` with
// FreeEXRErrorMessage()
extern size_t SaveEXRImageToMemory(const EXRImage *image,
const EXRHeader *exr_header,
unsigned char **memory, const char **err);
// Saves multi-channel, multi-frame OpenEXR image to a memory.
// Image is compressed using EXRImage.compression value.
// File global attributes (eg. display_window) must be set in the first header.
// Returns negative value and may set error string in `err` when there's an
// error
// When there was an error message, Application must free `err` with
// FreeEXRErrorMessage()
extern int SaveEXRMultipartImageToFile(const EXRImage *images,
const EXRHeader **exr_headers,
unsigned int num_parts,
const char *filename, const char **err);
// Saves multi-channel, multi-frame OpenEXR image to a memory.
// Image is compressed using EXRImage.compression value.
// File global attributes (eg. display_window) must be set in the first header.
// Return the number of bytes if success.
// Return zero and will set error string in `err` when there's an
// error.
// When there was an error message, Application must free `err` with
// FreeEXRErrorMessage()
extern size_t SaveEXRMultipartImageToMemory(const EXRImage *images,
const EXRHeader **exr_headers,
unsigned int num_parts,
unsigned char **memory, const char **err);
// Loads single-frame OpenEXR deep image.
// Application must free memory of variables in DeepImage(image, offset_table)
// Returns negative value and may set error string in `err` when there's an
// error
// When there was an error message, Application must free `err` with
// FreeEXRErrorMessage()
extern int LoadDeepEXR(DeepImage *out_image, const char *filename,
const char **err);
// NOT YET IMPLEMENTED:
// Saves single-frame OpenEXR deep image.
// Returns negative value and may set error string in `err` when there's an
// error
// extern int SaveDeepEXR(const DeepImage *in_image, const char *filename,
// const char **err);
// NOT YET IMPLEMENTED:
// Loads multi-part OpenEXR deep image.
// Application must free memory of variables in DeepImage(image, offset_table)
// extern int LoadMultiPartDeepEXR(DeepImage **out_image, int num_parts, const
// char *filename,
// const char **err);
// For emscripten.
// Loads single-frame OpenEXR image from memory. Assume EXR image contains
// RGB(A) channels.
// Returns negative value and may set error string in `err` when there's an
// error
// When there was an error message, Application must free `err` with
// FreeEXRErrorMessage()
extern int LoadEXRFromMemory(float **out_rgba, int *width, int *height,
const unsigned char *memory, size_t size,
const char **err);
#ifdef __cplusplus
}
#endif
#endif // TINYEXR_H_
#ifdef TINYEXR_IMPLEMENTATION
#ifndef TINYEXR_IMPLEMENTATION_DEFINED
#define TINYEXR_IMPLEMENTATION_DEFINED
#ifdef _WIN32
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <windows.h> // for UTF-8
#endif
#include <algorithm>
#include <cassert>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <sstream>
// #include <iostream> // debug
#include <limits>
#include <string>
#include <vector>
#include <set>
// https://stackoverflow.com/questions/5047971/how-do-i-check-for-c11-support
#if __cplusplus > 199711L || (defined(_MSC_VER) && _MSC_VER >= 1900)
#define TINYEXR_HAS_CXX11 (1)
// C++11
#include <cstdint>
#if TINYEXR_USE_THREAD
#include <atomic>
#include <thread>
#endif
#endif // __cplusplus > 199711L
#if TINYEXR_USE_OPENMP
#include <omp.h>
#endif
#if TINYEXR_USE_MINIZ
#else
// Issue #46. Please include your own zlib-compatible API header before
// including `tinyexr.h`
//#include "zlib.h"
#endif
#if TINYEXR_USE_ZFP
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Weverything"
#endif
#include "zfp.h"
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif
namespace tinyexr {
#if __cplusplus > 199711L
// C++11
typedef uint64_t tinyexr_uint64;
typedef int64_t tinyexr_int64;
#else
// Although `long long` is not a standard type pre C++11, assume it is defined
// as a compiler's extension.
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wc++11-long-long"
#endif
typedef unsigned long long tinyexr_uint64;
typedef long long tinyexr_int64;
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif
#if TINYEXR_USE_MINIZ
namespace miniz {
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wc++11-long-long"
#pragma clang diagnostic ignored "-Wold-style-cast"
#pragma clang diagnostic ignored "-Wpadded"
#pragma clang diagnostic ignored "-Wsign-conversion"
#pragma clang diagnostic ignored "-Wc++11-extensions"
#pragma clang diagnostic ignored "-Wconversion"
#pragma clang diagnostic ignored "-Wunused-function"
#pragma clang diagnostic ignored "-Wc++98-compat-pedantic"
#pragma clang diagnostic ignored "-Wundef"
#if __has_warning("-Wcomma")
#pragma clang diagnostic ignored "-Wcomma"
#endif
#if __has_warning("-Wmacro-redefined")
#pragma clang diagnostic ignored "-Wmacro-redefined"
#endif
#if __has_warning("-Wcast-qual")
#pragma clang diagnostic ignored "-Wcast-qual"
#endif
#if __has_warning("-Wzero-as-null-pointer-constant")
#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant"
#endif
#if __has_warning("-Wtautological-constant-compare")
#pragma clang diagnostic ignored "-Wtautological-constant-compare"
#endif
#if __has_warning("-Wextra-semi-stmt")
#pragma clang diagnostic ignored "-Wextra-semi-stmt"
#endif
#endif
/* miniz.c v1.15 - public domain deflate/inflate, zlib-subset, ZIP
reading/writing/appending, PNG writing
See "unlicense" statement at the end of this file.
Rich Geldreich <richgel99@gmail.com>, last updated Oct. 13, 2013
Implements RFC 1950: http://www.ietf.org/rfc/rfc1950.txt and RFC 1951:
http://www.ietf.org/rfc/rfc1951.txt
Most API's defined in miniz.c are optional. For example, to disable the
archive related functions just define
MINIZ_NO_ARCHIVE_APIS, or to get rid of all stdio usage define MINIZ_NO_STDIO
(see the list below for more macros).
* Change History
10/13/13 v1.15 r4 - Interim bugfix release while I work on the next major
release with Zip64 support (almost there!):
- Critical fix for the MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY bug
(thanks kahmyong.moon@hp.com) which could cause locate files to not find
files. This bug
would only have occurred in earlier versions if you explicitly used this
flag, OR if you used mz_zip_extract_archive_file_to_heap() or
mz_zip_add_mem_to_archive_file_in_place()
(which used this flag). If you can't switch to v1.15 but want to fix
this bug, just remove the uses of this flag from both helper funcs (and of
course don't use the flag).
- Bugfix in mz_zip_reader_extract_to_mem_no_alloc() from kymoon when
pUser_read_buf is not NULL and compressed size is > uncompressed size
- Fixing mz_zip_reader_extract_*() funcs so they don't try to extract
compressed data from directory entries, to account for weird zipfiles which
contain zero-size compressed data on dir entries.
Hopefully this fix won't cause any issues on weird zip archives,
because it assumes the low 16-bits of zip external attributes are DOS
attributes (which I believe they always are in practice).
- Fixing mz_zip_reader_is_file_a_directory() so it doesn't check the
internal attributes, just the filename and external attributes
- mz_zip_reader_init_file() - missing MZ_FCLOSE() call if the seek failed
- Added cmake support for Linux builds which builds all the examples,
tested with clang v3.3 and gcc v4.6.
- Clang fix for tdefl_write_image_to_png_file_in_memory() from toffaletti
- Merged MZ_FORCEINLINE fix from hdeanclark
- Fix <time.h> include before config #ifdef, thanks emil.brink
- Added tdefl_write_image_to_png_file_in_memory_ex(): supports Y flipping
(super useful for OpenGL apps), and explicit control over the compression
level (so you can
set it to 1 for real-time compression).
- Merged in some compiler fixes from paulharris's github repro.
- Retested this build under Windows (VS 2010, including static analysis),
tcc 0.9.26, gcc v4.6 and clang v3.3.
- Added example6.c, which dumps an image of the mandelbrot set to a PNG
file.
- Modified example2 to help test the
MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY flag more.
- In r3: Bugfix to mz_zip_writer_add_file() found during merge: Fix
possible src file fclose() leak if alignment bytes+local header file write
faiiled
- In r4: Minor bugfix to mz_zip_writer_add_from_zip_reader():
Was pushing the wrong central dir header offset, appears harmless in this
release, but it became a problem in the zip64 branch
5/20/12 v1.14 - MinGW32/64 GCC 4.6.1 compiler fixes: added MZ_FORCEINLINE,
#include <time.h> (thanks fermtect).
5/19/12 v1.13 - From jason@cornsyrup.org and kelwert@mtu.edu - Fix
mz_crc32() so it doesn't compute the wrong CRC-32's when mz_ulong is 64-bit.
- Temporarily/locally slammed in "typedef unsigned long mz_ulong" and
re-ran a randomized regression test on ~500k files.
- Eliminated a bunch of warnings when compiling with GCC 32-bit/64.
- Ran all examples, miniz.c, and tinfl.c through MSVC 2008's /analyze
(static analysis) option and fixed all warnings (except for the silly
"Use of the comma-operator in a tested expression.." analysis warning,
which I purposely use to work around a MSVC compiler warning).
- Created 32-bit and 64-bit Codeblocks projects/workspace. Built and
tested Linux executables. The codeblocks workspace is compatible with
Linux+Win32/x64.
- Added miniz_tester solution/project, which is a useful little app
derived from LZHAM's tester app that I use as part of the regression test.
- Ran miniz.c and tinfl.c through another series of regression testing on
~500,000 files and archives.
- Modified example5.c so it purposely disables a bunch of high-level
functionality (MINIZ_NO_STDIO, etc.). (Thanks to corysama for the
MINIZ_NO_STDIO bug report.)
- Fix ftell() usage in examples so they exit with an error on files which
are too large (a limitation of the examples, not miniz itself).
4/12/12 v1.12 - More comments, added low-level example5.c, fixed a couple
minor level_and_flags issues in the archive API's.
level_and_flags can now be set to MZ_DEFAULT_COMPRESSION. Thanks to Bruce
Dawson <bruced@valvesoftware.com> for the feedback/bug report.
5/28/11 v1.11 - Added statement from unlicense.org
5/27/11 v1.10 - Substantial compressor optimizations:
- Level 1 is now ~4x faster than before. The L1 compressor's throughput
now varies between 70-110MB/sec. on a
- Core i7 (actual throughput varies depending on the type of data, and x64
vs. x86).
- Improved baseline L2-L9 compression perf. Also, greatly improved
compression perf. issues on some file types.
- Refactored the compression code for better readability and
maintainability.
- Added level 10 compression level (L10 has slightly better ratio than
level 9, but could have a potentially large
drop in throughput on some files).
5/15/11 v1.09 - Initial stable release.
* Low-level Deflate/Inflate implementation notes:
Compression: Use the "tdefl" API's. The compressor supports raw, static,
and dynamic blocks, lazy or
greedy parsing, match length filtering, RLE-only, and Huffman-only streams.
It performs and compresses
approximately as well as zlib.
Decompression: Use the "tinfl" API's. The entire decompressor is
implemented as a single function
coroutine: see tinfl_decompress(). It supports decompression into a 32KB
(or larger power of 2) wrapping buffer, or into a memory
block large enough to hold the entire file.
The low-level tdefl/tinfl API's do not make any use of dynamic memory
allocation.
* zlib-style API notes:
miniz.c implements a fairly large subset of zlib. There's enough
functionality present for it to be a drop-in
zlib replacement in many apps:
The z_stream struct, optional memory allocation callbacks
deflateInit/deflateInit2/deflate/deflateReset/deflateEnd/deflateBound
inflateInit/inflateInit2/inflate/inflateEnd
compress, compress2, compressBound, uncompress
CRC-32, Adler-32 - Using modern, minimal code size, CPU cache friendly
routines.
Supports raw deflate streams or standard zlib streams with adler-32
checking.
Limitations:
The callback API's are not implemented yet. No support for gzip headers or
zlib static dictionaries.
I've tried to closely emulate zlib's various flavors of stream flushing
and return status codes, but
there are no guarantees that miniz.c pulls this off perfectly.
* PNG writing: See the tdefl_write_image_to_png_file_in_memory() function,
originally written by
Alex Evans. Supports 1-4 bytes/pixel images.
* ZIP archive API notes:
The ZIP archive API's where designed with simplicity and efficiency in
mind, with just enough abstraction to
get the job done with minimal fuss. There are simple API's to retrieve file
information, read files from
existing archives, create new archives, append new files to existing
archives, or clone archive data from
one archive to another. It supports archives located in memory or the heap,
on disk (using stdio.h),
or you can specify custom file read/write callbacks.
- Archive reading: Just call this function to read a single file from a
disk archive:
void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const
char *pArchive_name,
size_t *pSize, mz_uint zip_flags);
For more complex cases, use the "mz_zip_reader" functions. Upon opening an
archive, the entire central
directory is located and read as-is into memory, and subsequent file access
only occurs when reading individual files.
- Archives file scanning: The simple way is to use this function to scan a
loaded archive for a specific file:
int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName,
const char *pComment, mz_uint flags);
The locate operation can optionally check file comments too, which (as one
example) can be used to identify
multiple versions of the same file in an archive. This function uses a
simple linear search through the central
directory, so it's not very fast.
Alternately, you can iterate through all the files in an archive (using
mz_zip_reader_get_num_files()) and
retrieve detailed info on each file by calling mz_zip_reader_file_stat().
- Archive creation: Use the "mz_zip_writer" functions. The ZIP writer
immediately writes compressed file data
to disk and builds an exact image of the central directory in memory. The
central directory image is written
all at once at the end of the archive file when the archive is finalized.
The archive writer can optionally align each file's local header and file
data to any power of 2 alignment,
which can be useful when the archive will be read from optical media. Also,
the writer supports placing
arbitrary data blobs at the very beginning of ZIP archives. Archives
written using either feature are still
readable by any ZIP tool.
- Archive appending: The simple way to add a single file to an archive is
to call this function:
mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename,
const char *pArchive_name,
const void *pBuf, size_t buf_size, const void *pComment, mz_uint16
comment_size, mz_uint level_and_flags);
The archive will be created if it doesn't already exist, otherwise it'll be
appended to.
Note the appending is done in-place and is not an atomic operation, so if
something goes wrong
during the operation it's possible the archive could be left without a
central directory (although the local
file headers and file data will be fine, so the archive will be
recoverable).
For more complex archive modification scenarios:
1. The safest way is to use a mz_zip_reader to read the existing archive,
cloning only those bits you want to
preserve into a new archive using using the
mz_zip_writer_add_from_zip_reader() function (which compiles the
compressed file data as-is). When you're done, delete the old archive and
rename the newly written archive, and
you're done. This is safe but requires a bunch of temporary disk space or
heap memory.
2. Or, you can convert an mz_zip_reader in-place to an mz_zip_writer using
mz_zip_writer_init_from_reader(),
append new files as needed, then finalize the archive which will write an
updated central directory to the
original archive. (This is basically what
mz_zip_add_mem_to_archive_file_in_place() does.) There's a
possibility that the archive's central directory could be lost with this
method if anything goes wrong, though.
- ZIP archive support limitations:
No zip64 or spanning support. Extraction functions can only handle
unencrypted, stored or deflated files.
Requires streams capable of seeking.
* This is a header file library, like stb_image.c. To get only a header file,
either cut and paste the
below header, or create miniz.h, #define MINIZ_HEADER_FILE_ONLY, and then
include miniz.c from it.
* Important: For best perf. be sure to customize the below macros for your
target platform:
#define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1
#define MINIZ_LITTLE_ENDIAN 1
#define MINIZ_HAS_64BIT_REGISTERS 1
* On platforms using glibc, Be sure to "#define _LARGEFILE64_SOURCE 1" before
including miniz.c to ensure miniz
uses the 64-bit variants: fopen64(), stat64(), etc. Otherwise you won't be
able to process large files
(i.e. 32-bit stat() fails for me on files > 0x7FFFFFFF bytes).
*/
#ifndef MINIZ_HEADER_INCLUDED
#define MINIZ_HEADER_INCLUDED
//#include <stdlib.h>
// Defines to completely disable specific portions of miniz.c:
// If all macros here are defined the only functionality remaining will be
// CRC-32, adler-32, tinfl, and tdefl.
// Define MINIZ_NO_STDIO to disable all usage and any functions which rely on
// stdio for file I/O.
//#define MINIZ_NO_STDIO
// If MINIZ_NO_TIME is specified then the ZIP archive functions will not be able
// to get the current time, or
// get/set file times, and the C run-time funcs that get/set times won't be
// called.
// The current downside is the times written to your archives will be from 1979.
#define MINIZ_NO_TIME
// Define MINIZ_NO_ARCHIVE_APIS to disable all ZIP archive API's.
#define MINIZ_NO_ARCHIVE_APIS
// Define MINIZ_NO_ARCHIVE_APIS to disable all writing related ZIP archive
// API's.
//#define MINIZ_NO_ARCHIVE_WRITING_APIS
// Define MINIZ_NO_ZLIB_APIS to remove all ZLIB-style compression/decompression
// API's.
//#define MINIZ_NO_ZLIB_APIS
// Define MINIZ_NO_ZLIB_COMPATIBLE_NAME to disable zlib names, to prevent
// conflicts against stock zlib.
//#define MINIZ_NO_ZLIB_COMPATIBLE_NAMES
// Define MINIZ_NO_MALLOC to disable all calls to malloc, free, and realloc.
// Note if MINIZ_NO_MALLOC is defined then the user must always provide custom
// user alloc/free/realloc
// callbacks to the zlib and archive API's, and a few stand-alone helper API's
// which don't provide custom user
// functions (such as tdefl_compress_mem_to_heap() and
// tinfl_decompress_mem_to_heap()) won't work.
//#define MINIZ_NO_MALLOC
#if defined(__TINYC__) && (defined(__linux) || defined(__linux__))
// TODO: Work around "error: include file 'sys\utime.h' when compiling with tcc
// on Linux
#define MINIZ_NO_TIME
#endif
#if !defined(MINIZ_NO_TIME) && !defined(MINIZ_NO_ARCHIVE_APIS)
//#include <time.h>
#endif
#if defined(_M_IX86) || defined(_M_X64) || defined(__i386__) || \
defined(__i386) || defined(__i486__) || defined(__i486) || \
defined(i386) || defined(__ia64__) || defined(__x86_64__)
// MINIZ_X86_OR_X64_CPU is only used to help set the below macros.
#define MINIZ_X86_OR_X64_CPU 1
#endif
#if defined(__sparcv9)
// Big endian
#else
#if (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) || MINIZ_X86_OR_X64_CPU
// Set MINIZ_LITTLE_ENDIAN to 1 if the processor is little endian.
#define MINIZ_LITTLE_ENDIAN 1
#endif
#endif
#if MINIZ_X86_OR_X64_CPU
// Set MINIZ_USE_UNALIGNED_LOADS_AND_STORES to 1 on CPU's that permit efficient
// integer loads and stores from unaligned addresses.
//#define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1
#define MINIZ_USE_UNALIGNED_LOADS_AND_STORES \
0 // disable to suppress compiler warnings
#endif
#if defined(_M_X64) || defined(_WIN64) || defined(__MINGW64__) || \
defined(_LP64) || defined(__LP64__) || defined(__ia64__) || \
defined(__x86_64__)
// Set MINIZ_HAS_64BIT_REGISTERS to 1 if operations on 64-bit integers are
// reasonably fast (and don't involve compiler generated calls to helper
// functions).
#define MINIZ_HAS_64BIT_REGISTERS 1
#endif
#ifdef __cplusplus
extern "C" {
#endif
// ------------------- zlib-style API Definitions.
// For more compatibility with zlib, miniz.c uses unsigned long for some
// parameters/struct members. Beware: mz_ulong can be either 32 or 64-bits!
typedef unsigned long mz_ulong;
// mz_free() internally uses the MZ_FREE() macro (which by default calls free()
// unless you've modified the MZ_MALLOC macro) to release a block allocated from
// the heap.
void mz_free(void *p);
#define MZ_ADLER32_INIT (1)
// mz_adler32() returns the initial adler-32 value to use when called with
// ptr==NULL.
mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len);
#define MZ_CRC32_INIT (0)
// mz_crc32() returns the initial CRC-32 value to use when called with
// ptr==NULL.
mz_ulong mz_crc32(mz_ulong crc, const unsigned char *ptr, size_t buf_len);
// Compression strategies.
enum {
MZ_DEFAULT_STRATEGY = 0,
MZ_FILTERED = 1,
MZ_HUFFMAN_ONLY = 2,
MZ_RLE = 3,
MZ_FIXED = 4
};
// Method
#define MZ_DEFLATED 8
#ifndef MINIZ_NO_ZLIB_APIS
// Heap allocation callbacks.
// Note that mz_alloc_func parameter types purpsosely differ from zlib's:
// items/size is size_t, not unsigned long.
typedef void *(*mz_alloc_func)(void *opaque, size_t items, size_t size);
typedef void (*mz_free_func)(void *opaque, void *address);
typedef void *(*mz_realloc_func)(void *opaque, void *address, size_t items,
size_t size);
#define MZ_VERSION "9.1.15"
#define MZ_VERNUM 0x91F0
#define MZ_VER_MAJOR 9
#define MZ_VER_MINOR 1
#define MZ_VER_REVISION 15
#define MZ_VER_SUBREVISION 0
// Flush values. For typical usage you only need MZ_NO_FLUSH and MZ_FINISH. The
// other values are for advanced use (refer to the zlib docs).
enum {
MZ_NO_FLUSH = 0,
MZ_PARTIAL_FLUSH = 1,
MZ_SYNC_FLUSH = 2,
MZ_FULL_FLUSH = 3,
MZ_FINISH = 4,
MZ_BLOCK = 5
};
// Return status codes. MZ_PARAM_ERROR is non-standard.
enum {
MZ_OK = 0,
MZ_STREAM_END = 1,
MZ_NEED_DICT = 2,
MZ_ERRNO = -1,
MZ_STREAM_ERROR = -2,
MZ_DATA_ERROR = -3,
MZ_MEM_ERROR = -4,
MZ_BUF_ERROR = -5,
MZ_VERSION_ERROR = -6,
MZ_PARAM_ERROR = -10000
};
// Compression levels: 0-9 are the standard zlib-style levels, 10 is best
// possible compression (not zlib compatible, and may be very slow),
// MZ_DEFAULT_COMPRESSION=MZ_DEFAULT_LEVEL.
enum {
MZ_NO_COMPRESSION = 0,
MZ_BEST_SPEED = 1,
MZ_BEST_COMPRESSION = 9,
MZ_UBER_COMPRESSION = 10,
MZ_DEFAULT_LEVEL = 6,
MZ_DEFAULT_COMPRESSION = -1
};
// Window bits
#define MZ_DEFAULT_WINDOW_BITS 15
struct mz_internal_state;
// Compression/decompression stream struct.
typedef struct mz_stream_s {
const unsigned char *next_in; // pointer to next byte to read
unsigned int avail_in; // number of bytes available at next_in
mz_ulong total_in; // total number of bytes consumed so far
unsigned char *next_out; // pointer to next byte to write
unsigned int avail_out; // number of bytes that can be written to next_out
mz_ulong total_out; // total number of bytes produced so far
char *msg; // error msg (unused)
struct mz_internal_state *state; // internal state, allocated by zalloc/zfree
mz_alloc_func
zalloc; // optional heap allocation function (defaults to malloc)
mz_free_func zfree; // optional heap free function (defaults to free)
void *opaque; // heap alloc function user pointer
int data_type; // data_type (unused)
mz_ulong adler; // adler32 of the source or uncompressed data
mz_ulong reserved; // not used
} mz_stream;
typedef mz_stream *mz_streamp;
// Returns the version string of miniz.c.
const char *mz_version(void);
// mz_deflateInit() initializes a compressor with default options:
// Parameters:
// pStream must point to an initialized mz_stream struct.
// level must be between [MZ_NO_COMPRESSION, MZ_BEST_COMPRESSION].
// level 1 enables a specially optimized compression function that's been
// optimized purely for performance, not ratio.
// (This special func. is currently only enabled when
// MINIZ_USE_UNALIGNED_LOADS_AND_STORES and MINIZ_LITTLE_ENDIAN are defined.)
// Return values:
// MZ_OK on success.
// MZ_STREAM_ERROR if the stream is bogus.
// MZ_PARAM_ERROR if the input parameters are bogus.
// MZ_MEM_ERROR on out of memory.
int mz_deflateInit(mz_streamp pStream, int level);
// mz_deflateInit2() is like mz_deflate(), except with more control:
// Additional parameters:
// method must be MZ_DEFLATED
// window_bits must be MZ_DEFAULT_WINDOW_BITS (to wrap the deflate stream with
// zlib header/adler-32 footer) or -MZ_DEFAULT_WINDOW_BITS (raw deflate/no
// header or footer)
// mem_level must be between [1, 9] (it's checked but ignored by miniz.c)
int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits,
int mem_level, int strategy);
// Quickly resets a compressor without having to reallocate anything. Same as
// calling mz_deflateEnd() followed by mz_deflateInit()/mz_deflateInit2().
int mz_deflateReset(mz_streamp pStream);
// mz_deflate() compresses the input to output, consuming as much of the input
// and producing as much output as possible.
// Parameters:
// pStream is the stream to read from and write to. You must initialize/update
// the next_in, avail_in, next_out, and avail_out members.
// flush may be MZ_NO_FLUSH, MZ_PARTIAL_FLUSH/MZ_SYNC_FLUSH, MZ_FULL_FLUSH, or
// MZ_FINISH.
// Return values:
// MZ_OK on success (when flushing, or if more input is needed but not
// available, and/or there's more output to be written but the output buffer
// is full).
// MZ_STREAM_END if all input has been consumed and all output bytes have been
// written. Don't call mz_deflate() on the stream anymore.
// MZ_STREAM_ERROR if the stream is bogus.
// MZ_PARAM_ERROR if one of the parameters is invalid.
// MZ_BUF_ERROR if no forward progress is possible because the input and/or
// output buffers are empty. (Fill up the input buffer or free up some output
// space and try again.)
int mz_deflate(mz_streamp pStream, int flush);
// mz_deflateEnd() deinitializes a compressor:
// Return values:
// MZ_OK on success.
// MZ_STREAM_ERROR if the stream is bogus.
int mz_deflateEnd(mz_streamp pStream);
// mz_deflateBound() returns a (very) conservative upper bound on the amount of
// data that could be generated by deflate(), assuming flush is set to only
// MZ_NO_FLUSH or MZ_FINISH.
mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len);
// Single-call compression functions mz_compress() and mz_compress2():
// Returns MZ_OK on success, or one of the error codes from mz_deflate() on
// failure.
int mz_compress(unsigned char *pDest, mz_ulong *pDest_len,
const unsigned char *pSource, mz_ulong source_len);
int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len,
const unsigned char *pSource, mz_ulong source_len, int level);
// mz_compressBound() returns a (very) conservative upper bound on the amount of
// data that could be generated by calling mz_compress().
mz_ulong mz_compressBound(mz_ulong source_len);
// Initializes a decompressor.
int mz_inflateInit(mz_streamp pStream);
// mz_inflateInit2() is like mz_inflateInit() with an additional option that
// controls the window size and whether or not the stream has been wrapped with
// a zlib header/footer:
// window_bits must be MZ_DEFAULT_WINDOW_BITS (to parse zlib header/footer) or
// -MZ_DEFAULT_WINDOW_BITS (raw deflate).
int mz_inflateInit2(mz_streamp pStream, int window_bits);
// Decompresses the input stream to the output, consuming only as much of the
// input as needed, and writing as much to the output as possible.
// Parameters:
// pStream is the stream to read from and write to. You must initialize/update
// the next_in, avail_in, next_out, and avail_out members.
// flush may be MZ_NO_FLUSH, MZ_SYNC_FLUSH, or MZ_FINISH.
// On the first call, if flush is MZ_FINISH it's assumed the input and output
// buffers are both sized large enough to decompress the entire stream in a
// single call (this is slightly faster).
// MZ_FINISH implies that there are no more source bytes available beside
// what's already in the input buffer, and that the output buffer is large
// enough to hold the rest of the decompressed data.
// Return values:
// MZ_OK on success. Either more input is needed but not available, and/or
// there's more output to be written but the output buffer is full.
// MZ_STREAM_END if all needed input has been consumed and all output bytes
// have been written. For zlib streams, the adler-32 of the decompressed data
// has also been verified.
// MZ_STREAM_ERROR if the stream is bogus.
// MZ_DATA_ERROR if the deflate stream is invalid.
// MZ_PARAM_ERROR if one of the parameters is invalid.
// MZ_BUF_ERROR if no forward progress is possible because the input buffer is
// empty but the inflater needs more input to continue, or if the output
// buffer is not large enough. Call mz_inflate() again
// with more input data, or with more room in the output buffer (except when
// using single call decompression, described above).
int mz_inflate(mz_streamp pStream, int flush);
// Deinitializes a decompressor.
int mz_inflateEnd(mz_streamp pStream);
// Single-call decompression.
// Returns MZ_OK on success, or one of the error codes from mz_inflate() on
// failure.
int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len,
const unsigned char *pSource, mz_ulong source_len);
// Returns a string description of the specified error code, or NULL if the
// error code is invalid.
const char *mz_error(int err);
// Redefine zlib-compatible names to miniz equivalents, so miniz.c can be used
// as a drop-in replacement for the subset of zlib that miniz.c supports.
// Define MINIZ_NO_ZLIB_COMPATIBLE_NAMES to disable zlib-compatibility if you
// use zlib in the same project.
#ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES
typedef unsigned char Byte;
typedef unsigned int uInt;
typedef mz_ulong uLong;
typedef Byte Bytef;
typedef uInt uIntf;
typedef char charf;
typedef int intf;
typedef void *voidpf;
typedef uLong uLongf;
typedef void *voidp;
typedef void *const voidpc;
#define Z_NULL 0
#define Z_NO_FLUSH MZ_NO_FLUSH
#define Z_PARTIAL_FLUSH MZ_PARTIAL_FLUSH
#define Z_SYNC_FLUSH MZ_SYNC_FLUSH
#define Z_FULL_FLUSH MZ_FULL_FLUSH
#define Z_FINISH MZ_FINISH
#define Z_BLOCK MZ_BLOCK
#define Z_OK MZ_OK
#define Z_STREAM_END MZ_STREAM_END
#define Z_NEED_DICT MZ_NEED_DICT
#define Z_ERRNO MZ_ERRNO
#define Z_STREAM_ERROR MZ_STREAM_ERROR
#define Z_DATA_ERROR MZ_DATA_ERROR
#define Z_MEM_ERROR MZ_MEM_ERROR
#define Z_BUF_ERROR MZ_BUF_ERROR
#define Z_VERSION_ERROR MZ_VERSION_ERROR
#define Z_PARAM_ERROR MZ_PARAM_ERROR
#define Z_NO_COMPRESSION MZ_NO_COMPRESSION
#define Z_BEST_SPEED MZ_BEST_SPEED
#define Z_BEST_COMPRESSION MZ_BEST_COMPRESSION
#define Z_DEFAULT_COMPRESSION MZ_DEFAULT_COMPRESSION
#define Z_DEFAULT_STRATEGY MZ_DEFAULT_STRATEGY
#define Z_FILTERED MZ_FILTERED
#define Z_HUFFMAN_ONLY MZ_HUFFMAN_ONLY
#define Z_RLE MZ_RLE
#define Z_FIXED MZ_FIXED
#define Z_DEFLATED MZ_DEFLATED
#define Z_DEFAULT_WINDOW_BITS MZ_DEFAULT_WINDOW_BITS
#define alloc_func mz_alloc_func
#define free_func mz_free_func
#define internal_state mz_internal_state
#define z_stream mz_stream
#define deflateInit mz_deflateInit
#define deflateInit2 mz_deflateInit2
#define deflateReset mz_deflateReset
#define deflate mz_deflate
#define deflateEnd mz_deflateEnd
#define deflateBound mz_deflateBound
#define compress mz_compress
#define compress2 mz_compress2
#define compressBound mz_compressBound
#define inflateInit mz_inflateInit
#define inflateInit2 mz_inflateInit2
#define inflate mz_inflate
#define inflateEnd mz_inflateEnd
#define uncompress mz_uncompress
#define crc32 mz_crc32
#define adler32 mz_adler32
#define MAX_WBITS 15
#define MAX_MEM_LEVEL 9
#define zError mz_error
#define ZLIB_VERSION MZ_VERSION
#define ZLIB_VERNUM MZ_VERNUM
#define ZLIB_VER_MAJOR MZ_VER_MAJOR
#define ZLIB_VER_MINOR MZ_VER_MINOR
#define ZLIB_VER_REVISION MZ_VER_REVISION
#define ZLIB_VER_SUBREVISION MZ_VER_SUBREVISION
#define zlibVersion mz_version
#define zlib_version mz_version()
#endif // #ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES
#endif // MINIZ_NO_ZLIB_APIS
// ------------------- Types and macros
typedef unsigned char mz_uint8;
typedef signed short mz_int16;
typedef unsigned short mz_uint16;
typedef unsigned int mz_uint32;
typedef unsigned int mz_uint;
typedef long long mz_int64;
typedef unsigned long long mz_uint64;
typedef int mz_bool;
#define MZ_FALSE (0)
#define MZ_TRUE (1)
// An attempt to work around MSVC's spammy "warning C4127: conditional
// expression is constant" message.
#ifdef _MSC_VER
#define MZ_MACRO_END while (0, 0)
#else
#define MZ_MACRO_END while (0)
#endif
// ------------------- ZIP archive reading/writing
#ifndef MINIZ_NO_ARCHIVE_APIS
enum {
MZ_ZIP_MAX_IO_BUF_SIZE = 64 * 1024,
MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE = 260,
MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE = 256
};
typedef struct {
mz_uint32 m_file_index;
mz_uint32 m_central_dir_ofs;
mz_uint16 m_version_made_by;
mz_uint16 m_version_needed;
mz_uint16 m_bit_flag;
mz_uint16 m_method;
#ifndef MINIZ_NO_TIME
time_t m_time;
#endif
mz_uint32 m_crc32;
mz_uint64 m_comp_size;
mz_uint64 m_uncomp_size;
mz_uint16 m_internal_attr;
mz_uint32 m_external_attr;
mz_uint64 m_local_header_ofs;
mz_uint32 m_comment_size;
char m_filename[MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE];
char m_comment[MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE];
} mz_zip_archive_file_stat;
typedef size_t (*mz_file_read_func)(void *pOpaque, mz_uint64 file_ofs,
void *pBuf, size_t n);
typedef size_t (*mz_file_write_func)(void *pOpaque, mz_uint64 file_ofs,
const void *pBuf, size_t n);
struct mz_zip_internal_state_tag;
typedef struct mz_zip_internal_state_tag mz_zip_internal_state;
typedef enum {
MZ_ZIP_MODE_INVALID = 0,
MZ_ZIP_MODE_READING = 1,
MZ_ZIP_MODE_WRITING = 2,
MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED = 3
} mz_zip_mode;
typedef struct mz_zip_archive_tag {
mz_uint64 m_archive_size;
mz_uint64 m_central_directory_file_ofs;
mz_uint m_total_files;
mz_zip_mode m_zip_mode;
mz_uint m_file_offset_alignment;
mz_alloc_func m_pAlloc;
mz_free_func m_pFree;
mz_realloc_func m_pRealloc;
void *m_pAlloc_opaque;
mz_file_read_func m_pRead;
mz_file_write_func m_pWrite;
void *m_pIO_opaque;
mz_zip_internal_state *m_pState;
} mz_zip_archive;
typedef enum {
MZ_ZIP_FLAG_CASE_SENSITIVE = 0x0100,
MZ_ZIP_FLAG_IGNORE_PATH = 0x0200,
MZ_ZIP_FLAG_COMPRESSED_DATA = 0x0400,
MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY = 0x0800
} mz_zip_flags;
// ZIP archive reading
// Inits a ZIP archive reader.
// These functions read and validate the archive's central directory.
mz_bool mz_zip_reader_init(mz_zip_archive *pZip, mz_uint64 size,
mz_uint32 flags);
mz_bool mz_zip_reader_init_mem(mz_zip_archive *pZip, const void *pMem,
size_t size, mz_uint32 flags);
#ifndef MINIZ_NO_STDIO
mz_bool mz_zip_reader_init_file(mz_zip_archive *pZip, const char *pFilename,
mz_uint32 flags);
#endif
// Returns the total number of files in the archive.
mz_uint mz_zip_reader_get_num_files(mz_zip_archive *pZip);
// Returns detailed information about an archive file entry.
mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip, mz_uint file_index,
mz_zip_archive_file_stat *pStat);
// Determines if an archive file entry is a directory entry.
mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip,
mz_uint file_index);
mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive *pZip,
mz_uint file_index);
// Retrieves the filename of an archive file entry.
// Returns the number of bytes written to pFilename, or if filename_buf_size is
// 0 this function returns the number of bytes needed to fully store the
// filename.
mz_uint mz_zip_reader_get_filename(mz_zip_archive *pZip, mz_uint file_index,
char *pFilename, mz_uint filename_buf_size);
// Attempts to locates a file in the archive's central directory.
// Valid flags: MZ_ZIP_FLAG_CASE_SENSITIVE, MZ_ZIP_FLAG_IGNORE_PATH
// Returns -1 if the file cannot be found.
int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName,
const char *pComment, mz_uint flags);
// Extracts a archive file to a memory buffer using no memory allocation.
mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip,
mz_uint file_index, void *pBuf,
size_t buf_size, mz_uint flags,
void *pUser_read_buf,
size_t user_read_buf_size);
mz_bool mz_zip_reader_extract_file_to_mem_no_alloc(
mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size,
mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size);
// Extracts a archive file to a memory buffer.
mz_bool mz_zip_reader_extract_to_mem(mz_zip_archive *pZip, mz_uint file_index,
void *pBuf, size_t buf_size,
mz_uint flags);
mz_bool mz_zip_reader_extract_file_to_mem(mz_zip_archive *pZip,
const char *pFilename, void *pBuf,
size_t buf_size, mz_uint flags);
// Extracts a archive file to a dynamically allocated heap buffer.
void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip, mz_uint file_index,
size_t *pSize, mz_uint flags);
void *mz_zip_reader_extract_file_to_heap(mz_zip_archive *pZip,
const char *pFilename, size_t *pSize,
mz_uint flags);
// Extracts a archive file using a callback function to output the file's data.
mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip,
mz_uint file_index,
mz_file_write_func pCallback,
void *pOpaque, mz_uint flags);
mz_bool mz_zip_reader_extract_file_to_callback(mz_zip_archive *pZip,
const char *pFilename,
mz_file_write_func pCallback,
void *pOpaque, mz_uint flags);
#ifndef MINIZ_NO_STDIO
// Extracts a archive file to a disk file and sets its last accessed and
// modified times.
// This function only extracts files, not archive directory records.
mz_bool mz_zip_reader_extract_to_file(mz_zip_archive *pZip, mz_uint file_index,
const char *pDst_filename, mz_uint flags);
mz_bool mz_zip_reader_extract_file_to_file(mz_zip_archive *pZip,
const char *pArchive_filename,
const char *pDst_filename,
mz_uint flags);
#endif
// Ends archive reading, freeing all allocations, and closing the input archive
// file if mz_zip_reader_init_file() was used.
mz_bool mz_zip_reader_end(mz_zip_archive *pZip);
// ZIP archive writing
#ifndef MINIZ_NO_ARCHIVE_WRITING_APIS
// Inits a ZIP archive writer.
mz_bool mz_zip_writer_init(mz_zip_archive *pZip, mz_uint64 existing_size);
mz_bool mz_zip_writer_init_heap(mz_zip_archive *pZip,
size_t size_to_reserve_at_beginning,
size_t initial_allocation_size);
#ifndef MINIZ_NO_STDIO
mz_bool mz_zip_writer_init_file(mz_zip_archive *pZip, const char *pFilename,
mz_uint64 size_to_reserve_at_beginning);
#endif
// Converts a ZIP archive reader object into a writer object, to allow efficient
// in-place file appends to occur on an existing archive.
// For archives opened using mz_zip_reader_init_file, pFilename must be the
// archive's filename so it can be reopened for writing. If the file can't be
// reopened, mz_zip_reader_end() will be called.
// For archives opened using mz_zip_reader_init_mem, the memory block must be
// growable using the realloc callback (which defaults to realloc unless you've
// overridden it).
// Finally, for archives opened using mz_zip_reader_init, the mz_zip_archive's
// user provided m_pWrite function cannot be NULL.
// Note: In-place archive modification is not recommended unless you know what
// you're doing, because if execution stops or something goes wrong before
// the archive is finalized the file's central directory will be hosed.
mz_bool mz_zip_writer_init_from_reader(mz_zip_archive *pZip,
const char *pFilename);
// Adds the contents of a memory buffer to an archive. These functions record
// the current local time into the archive.
// To add a directory entry, call this method with an archive name ending in a
// forwardslash with empty buffer.
// level_and_flags - compression level (0-10, see MZ_BEST_SPEED,
// MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or
// just set to MZ_DEFAULT_COMPRESSION.
mz_bool mz_zip_writer_add_mem(mz_zip_archive *pZip, const char *pArchive_name,
const void *pBuf, size_t buf_size,
mz_uint level_and_flags);
mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive *pZip,
const char *pArchive_name, const void *pBuf,
size_t buf_size, const void *pComment,
mz_uint16 comment_size,
mz_uint level_and_flags, mz_uint64 uncomp_size,
mz_uint32 uncomp_crc32);
#ifndef MINIZ_NO_STDIO
// Adds the contents of a disk file to an archive. This function also records
// the disk file's modified time into the archive.
// level_and_flags - compression level (0-10, see MZ_BEST_SPEED,
// MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or
// just set to MZ_DEFAULT_COMPRESSION.
mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name,
const char *pSrc_filename, const void *pComment,
mz_uint16 comment_size, mz_uint level_and_flags);
#endif
// Adds a file to an archive by fully cloning the data from another archive.
// This function fully clones the source file's compressed data (no
// recompression), along with its full filename, extra data, and comment fields.
mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip,
mz_zip_archive *pSource_zip,
mz_uint file_index);
// Finalizes the archive by writing the central directory records followed by
// the end of central directory record.
// After an archive is finalized, the only valid call on the mz_zip_archive
// struct is mz_zip_writer_end().
// An archive must be manually finalized by calling this function for it to be
// valid.
mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip);
mz_bool mz_zip_writer_finalize_heap_archive(mz_zip_archive *pZip, void **pBuf,
size_t *pSize);
// Ends archive writing, freeing all allocations, and closing the output file if
// mz_zip_writer_init_file() was used.
// Note for the archive to be valid, it must have been finalized before ending.
mz_bool mz_zip_writer_end(mz_zip_archive *pZip);
// Misc. high-level helper functions:
// mz_zip_add_mem_to_archive_file_in_place() efficiently (but not atomically)
// appends a memory blob to a ZIP archive.
// level_and_flags - compression level (0-10, see MZ_BEST_SPEED,
// MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or
// just set to MZ_DEFAULT_COMPRESSION.
mz_bool mz_zip_add_mem_to_archive_file_in_place(
const char *pZip_filename, const char *pArchive_name, const void *pBuf,
size_t buf_size, const void *pComment, mz_uint16 comment_size,
mz_uint level_and_flags);
// Reads a single file from an archive into a heap block.
// Returns NULL on failure.
void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename,
const char *pArchive_name,
size_t *pSize, mz_uint zip_flags);
#endif // #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS
#endif // #ifndef MINIZ_NO_ARCHIVE_APIS
// ------------------- Low-level Decompression API Definitions
// Decompression flags used by tinfl_decompress().
// TINFL_FLAG_PARSE_ZLIB_HEADER: If set, the input has a valid zlib header and
// ends with an adler32 checksum (it's a valid zlib stream). Otherwise, the
// input is a raw deflate stream.
// TINFL_FLAG_HAS_MORE_INPUT: If set, there are more input bytes available
// beyond the end of the supplied input buffer. If clear, the input buffer
// contains all remaining input.
// TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF: If set, the output buffer is large
// enough to hold the entire decompressed stream. If clear, the output buffer is
// at least the size of the dictionary (typically 32KB).
// TINFL_FLAG_COMPUTE_ADLER32: Force adler-32 checksum computation of the
// decompressed bytes.
enum {
TINFL_FLAG_PARSE_ZLIB_HEADER = 1,
TINFL_FLAG_HAS_MORE_INPUT = 2,
TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF = 4,
TINFL_FLAG_COMPUTE_ADLER32 = 8
};
// High level decompression functions:
// tinfl_decompress_mem_to_heap() decompresses a block in memory to a heap block
// allocated via malloc().
// On entry:
// pSrc_buf, src_buf_len: Pointer and size of the Deflate or zlib source data
// to decompress.
// On return:
// Function returns a pointer to the decompressed data, or NULL on failure.
// *pOut_len will be set to the decompressed data's size, which could be larger
// than src_buf_len on uncompressible data.
// The caller must call mz_free() on the returned block when it's no longer
// needed.
void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len,
size_t *pOut_len, int flags);
// tinfl_decompress_mem_to_mem() decompresses a block in memory to another block
// in memory.
// Returns TINFL_DECOMPRESS_MEM_TO_MEM_FAILED on failure, or the number of bytes
// written on success.
#define TINFL_DECOMPRESS_MEM_TO_MEM_FAILED ((size_t)(-1))
size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len,
const void *pSrc_buf, size_t src_buf_len,
int flags);
// tinfl_decompress_mem_to_callback() decompresses a block in memory to an
// internal 32KB buffer, and a user provided callback function will be called to
// flush the buffer.
// Returns 1 on success or 0 on failure.
typedef int (*tinfl_put_buf_func_ptr)(const void *pBuf, int len, void *pUser);
int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size,
tinfl_put_buf_func_ptr pPut_buf_func,
void *pPut_buf_user, int flags);
struct tinfl_decompressor_tag;
typedef struct tinfl_decompressor_tag tinfl_decompressor;
// Max size of LZ dictionary.
#define TINFL_LZ_DICT_SIZE 32768
// Return status.
typedef enum {
TINFL_STATUS_BAD_PARAM = -3,
TINFL_STATUS_ADLER32_MISMATCH = -2,
TINFL_STATUS_FAILED = -1,
TINFL_STATUS_DONE = 0,
TINFL_STATUS_NEEDS_MORE_INPUT = 1,
TINFL_STATUS_HAS_MORE_OUTPUT = 2
} tinfl_status;
// Initializes the decompressor to its initial state.
#define tinfl_init(r) \
do { \
(r)->m_state = 0; \
} \
MZ_MACRO_END
#define tinfl_get_adler32(r) (r)->m_check_adler32
// Main low-level decompressor coroutine function. This is the only function
// actually needed for decompression. All the other functions are just
// high-level helpers for improved usability.
// This is a universal API, i.e. it can be used as a building block to build any
// desired higher level decompression API. In the limit case, it can be called
// once per every byte input or output.
tinfl_status tinfl_decompress(tinfl_decompressor *r,
const mz_uint8 *pIn_buf_next,
size_t *pIn_buf_size, mz_uint8 *pOut_buf_start,
mz_uint8 *pOut_buf_next, size_t *pOut_buf_size,
const mz_uint32 decomp_flags);
// Internal/private bits follow.
enum {
TINFL_MAX_HUFF_TABLES = 3,
TINFL_MAX_HUFF_SYMBOLS_0 = 288,
TINFL_MAX_HUFF_SYMBOLS_1 = 32,
TINFL_MAX_HUFF_SYMBOLS_2 = 19,
TINFL_FAST_LOOKUP_BITS = 10,
TINFL_FAST_LOOKUP_SIZE = 1 << TINFL_FAST_LOOKUP_BITS
};
typedef struct {
mz_uint8 m_code_size[TINFL_MAX_HUFF_SYMBOLS_0];
mz_int16 m_look_up[TINFL_FAST_LOOKUP_SIZE],
m_tree[TINFL_MAX_HUFF_SYMBOLS_0 * 2];
} tinfl_huff_table;
#if MINIZ_HAS_64BIT_REGISTERS
#define TINFL_USE_64BIT_BITBUF 1
#endif
#if TINFL_USE_64BIT_BITBUF
typedef mz_uint64 tinfl_bit_buf_t;
#define TINFL_BITBUF_SIZE (64)
#else
typedef mz_uint32 tinfl_bit_buf_t;
#define TINFL_BITBUF_SIZE (32)
#endif
struct tinfl_decompressor_tag {
mz_uint32 m_state, m_num_bits, m_zhdr0, m_zhdr1, m_z_adler32, m_final, m_type,
m_check_adler32, m_dist, m_counter, m_num_extra,
m_table_sizes[TINFL_MAX_HUFF_TABLES];
tinfl_bit_buf_t m_bit_buf;
size_t m_dist_from_out_buf_start;
tinfl_huff_table m_tables[TINFL_MAX_HUFF_TABLES];
mz_uint8 m_raw_header[4],
m_len_codes[TINFL_MAX_HUFF_SYMBOLS_0 + TINFL_MAX_HUFF_SYMBOLS_1 + 137];
};
// ------------------- Low-level Compression API Definitions
// Set TDEFL_LESS_MEMORY to 1 to use less memory (compression will be slightly
// slower, and raw/dynamic blocks will be output more frequently).
#define TDEFL_LESS_MEMORY 0
// tdefl_init() compression flags logically OR'd together (low 12 bits contain
// the max. number of probes per dictionary search):
// TDEFL_DEFAULT_MAX_PROBES: The compressor defaults to 128 dictionary probes
// per dictionary search. 0=Huffman only, 1=Huffman+LZ (fastest/crap
// compression), 4095=Huffman+LZ (slowest/best compression).
enum {
TDEFL_HUFFMAN_ONLY = 0,
TDEFL_DEFAULT_MAX_PROBES = 128,
TDEFL_MAX_PROBES_MASK = 0xFFF
};
// TDEFL_WRITE_ZLIB_HEADER: If set, the compressor outputs a zlib header before
// the deflate data, and the Adler-32 of the source data at the end. Otherwise,
// you'll get raw deflate data.
// TDEFL_COMPUTE_ADLER32: Always compute the adler-32 of the input data (even
// when not writing zlib headers).
// TDEFL_GREEDY_PARSING_FLAG: Set to use faster greedy parsing, instead of more
// efficient lazy parsing.
// TDEFL_NONDETERMINISTIC_PARSING_FLAG: Enable to decrease the compressor's
// initialization time to the minimum, but the output may vary from run to run
// given the same input (depending on the contents of memory).
// TDEFL_RLE_MATCHES: Only look for RLE matches (matches with a distance of 1)
// TDEFL_FILTER_MATCHES: Discards matches <= 5 chars if enabled.
// TDEFL_FORCE_ALL_STATIC_BLOCKS: Disable usage of optimized Huffman tables.
// TDEFL_FORCE_ALL_RAW_BLOCKS: Only use raw (uncompressed) deflate blocks.
// The low 12 bits are reserved to control the max # of hash probes per
// dictionary lookup (see TDEFL_MAX_PROBES_MASK).
enum {
TDEFL_WRITE_ZLIB_HEADER = 0x01000,
TDEFL_COMPUTE_ADLER32 = 0x02000,
TDEFL_GREEDY_PARSING_FLAG = 0x04000,
TDEFL_NONDETERMINISTIC_PARSING_FLAG = 0x08000,
TDEFL_RLE_MATCHES = 0x10000,
TDEFL_FILTER_MATCHES = 0x20000,
TDEFL_FORCE_ALL_STATIC_BLOCKS = 0x40000,
TDEFL_FORCE_ALL_RAW_BLOCKS = 0x80000
};
// High level compression functions:
// tdefl_compress_mem_to_heap() compresses a block in memory to a heap block
// allocated via malloc().
// On entry:
// pSrc_buf, src_buf_len: Pointer and size of source block to compress.
// flags: The max match finder probes (default is 128) logically OR'd against
// the above flags. Higher probes are slower but improve compression.
// On return:
// Function returns a pointer to the compressed data, or NULL on failure.
// *pOut_len will be set to the compressed data's size, which could be larger
// than src_buf_len on uncompressible data.
// The caller must free() the returned block when it's no longer needed.
void *tdefl_compress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len,
size_t *pOut_len, int flags);
// tdefl_compress_mem_to_mem() compresses a block in memory to another block in
// memory.
// Returns 0 on failure.
size_t tdefl_compress_mem_to_mem(void *pOut_buf, size_t out_buf_len,
const void *pSrc_buf, size_t src_buf_len,
int flags);
// Compresses an image to a compressed PNG file in memory.
// On entry:
// pImage, w, h, and num_chans describe the image to compress. num_chans may be
// 1, 2, 3, or 4.
// The image pitch in bytes per scanline will be w*num_chans. The leftmost
// pixel on the top scanline is stored first in memory.
// level may range from [0,10], use MZ_NO_COMPRESSION, MZ_BEST_SPEED,
// MZ_BEST_COMPRESSION, etc. or a decent default is MZ_DEFAULT_LEVEL
// If flip is true, the image will be flipped on the Y axis (useful for OpenGL
// apps).
// On return:
// Function returns a pointer to the compressed data, or NULL on failure.
// *pLen_out will be set to the size of the PNG image file.
// The caller must mz_free() the returned heap block (which will typically be
// larger than *pLen_out) when it's no longer needed.
void *tdefl_write_image_to_png_file_in_memory_ex(const void *pImage, int w,
int h, int num_chans,
size_t *pLen_out,
mz_uint level, mz_bool flip);
void *tdefl_write_image_to_png_file_in_memory(const void *pImage, int w, int h,
int num_chans, size_t *pLen_out);
// Output stream interface. The compressor uses this interface to write
// compressed data. It'll typically be called TDEFL_OUT_BUF_SIZE at a time.
typedef mz_bool (*tdefl_put_buf_func_ptr)(const void *pBuf, int len,
void *pUser);
// tdefl_compress_mem_to_output() compresses a block to an output stream. The
// above helpers use this function internally.
mz_bool tdefl_compress_mem_to_output(const void *pBuf, size_t buf_len,
tdefl_put_buf_func_ptr pPut_buf_func,
void *pPut_buf_user, int flags);
enum {
TDEFL_MAX_HUFF_TABLES = 3,
TDEFL_MAX_HUFF_SYMBOLS_0 = 288,
TDEFL_MAX_HUFF_SYMBOLS_1 = 32,
TDEFL_MAX_HUFF_SYMBOLS_2 = 19,
TDEFL_LZ_DICT_SIZE = 32768,
TDEFL_LZ_DICT_SIZE_MASK = TDEFL_LZ_DICT_SIZE - 1,
TDEFL_MIN_MATCH_LEN = 3,
TDEFL_MAX_MATCH_LEN = 258
};
// TDEFL_OUT_BUF_SIZE MUST be large enough to hold a single entire compressed
// output block (using static/fixed Huffman codes).
#if TDEFL_LESS_MEMORY
enum {
TDEFL_LZ_CODE_BUF_SIZE = 24 * 1024,
TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13) / 10,
TDEFL_MAX_HUFF_SYMBOLS = 288,
TDEFL_LZ_HASH_BITS = 12,
TDEFL_LEVEL1_HASH_SIZE_MASK = 4095,
TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3,
TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS
};
#else
enum {
TDEFL_LZ_CODE_BUF_SIZE = 64 * 1024,
TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13) / 10,
TDEFL_MAX_HUFF_SYMBOLS = 288,
TDEFL_LZ_HASH_BITS = 15,
TDEFL_LEVEL1_HASH_SIZE_MASK = 4095,
TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3,
TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS
};
#endif
// The low-level tdefl functions below may be used directly if the above helper
// functions aren't flexible enough. The low-level functions don't make any heap
// allocations, unlike the above helper functions.
typedef enum {
TDEFL_STATUS_BAD_PARAM = -2,
TDEFL_STATUS_PUT_BUF_FAILED = -1,
TDEFL_STATUS_OKAY = 0,
TDEFL_STATUS_DONE = 1
} tdefl_status;
// Must map to MZ_NO_FLUSH, MZ_SYNC_FLUSH, etc. enums
typedef enum {
TDEFL_NO_FLUSH = 0,
TDEFL_SYNC_FLUSH = 2,
TDEFL_FULL_FLUSH = 3,
TDEFL_FINISH = 4
} tdefl_flush;
// tdefl's compression state structure.
typedef struct {
tdefl_put_buf_func_ptr m_pPut_buf_func;
void *m_pPut_buf_user;
mz_uint m_flags, m_max_probes[2];
int m_greedy_parsing;
mz_uint m_adler32, m_lookahead_pos, m_lookahead_size, m_dict_size;
mz_uint8 *m_pLZ_code_buf, *m_pLZ_flags, *m_pOutput_buf, *m_pOutput_buf_end;
mz_uint m_num_flags_left, m_total_lz_bytes, m_lz_code_buf_dict_pos, m_bits_in,
m_bit_buffer;
mz_uint m_saved_match_dist, m_saved_match_len, m_saved_lit,
m_output_flush_ofs, m_output_flush_remaining, m_finished, m_block_index,
m_wants_to_finish;
tdefl_status m_prev_return_status;
const void *m_pIn_buf;
void *m_pOut_buf;
size_t *m_pIn_buf_size, *m_pOut_buf_size;
tdefl_flush m_flush;
const mz_uint8 *m_pSrc;
size_t m_src_buf_left, m_out_buf_ofs;
mz_uint8 m_dict[TDEFL_LZ_DICT_SIZE + TDEFL_MAX_MATCH_LEN - 1];
mz_uint16 m_huff_count[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS];
mz_uint16 m_huff_codes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS];
mz_uint8 m_huff_code_sizes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS];
mz_uint8 m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE];
mz_uint16 m_next[TDEFL_LZ_DICT_SIZE];
mz_uint16 m_hash[TDEFL_LZ_HASH_SIZE];
mz_uint8 m_output_buf[TDEFL_OUT_BUF_SIZE];
} tdefl_compressor;
// Initializes the compressor.
// There is no corresponding deinit() function because the tdefl API's do not
// dynamically allocate memory.
// pBut_buf_func: If NULL, output data will be supplied to the specified
// callback. In this case, the user should call the tdefl_compress_buffer() API
// for compression.
// If pBut_buf_func is NULL the user should always call the tdefl_compress()
// API.
// flags: See the above enums (TDEFL_HUFFMAN_ONLY, TDEFL_WRITE_ZLIB_HEADER,
// etc.)
tdefl_status tdefl_init(tdefl_compressor *d,
tdefl_put_buf_func_ptr pPut_buf_func,
void *pPut_buf_user, int flags);
// Compresses a block of data, consuming as much of the specified input buffer
// as possible, and writing as much compressed data to the specified output
// buffer as possible.
tdefl_status tdefl_compress(tdefl_compressor *d, const void *pIn_buf,
size_t *pIn_buf_size, void *pOut_buf,
size_t *pOut_buf_size, tdefl_flush flush);
// tdefl_compress_buffer() is only usable when the tdefl_init() is called with a
// non-NULL tdefl_put_buf_func_ptr.
// tdefl_compress_buffer() always consumes the entire input buffer.
tdefl_status tdefl_compress_buffer(tdefl_compressor *d, const void *pIn_buf,
size_t in_buf_size, tdefl_flush flush);
tdefl_status tdefl_get_prev_return_status(tdefl_compressor *d);
mz_uint32 tdefl_get_adler32(tdefl_compressor *d);
// Can't use tdefl_create_comp_flags_from_zip_params if MINIZ_NO_ZLIB_APIS isn't
// defined, because it uses some of its macros.
#ifndef MINIZ_NO_ZLIB_APIS
// Create tdefl_compress() flags given zlib-style compression parameters.
// level may range from [0,10] (where 10 is absolute max compression, but may be
// much slower on some files)
// window_bits may be -15 (raw deflate) or 15 (zlib)
// strategy may be either MZ_DEFAULT_STRATEGY, MZ_FILTERED, MZ_HUFFMAN_ONLY,
// MZ_RLE, or MZ_FIXED
mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits,
int strategy);
#endif // #ifndef MINIZ_NO_ZLIB_APIS
#ifdef __cplusplus
}
#endif
#endif // MINIZ_HEADER_INCLUDED
// ------------------- End of Header: Implementation follows. (If you only want
// the header, define MINIZ_HEADER_FILE_ONLY.)
#ifndef MINIZ_HEADER_FILE_ONLY
typedef unsigned char mz_validate_uint16[sizeof(mz_uint16) == 2 ? 1 : -1];
typedef unsigned char mz_validate_uint32[sizeof(mz_uint32) == 4 ? 1 : -1];
typedef unsigned char mz_validate_uint64[sizeof(mz_uint64) == 8 ? 1 : -1];
//#include <assert.h>
//#include <string.h>
#define MZ_ASSERT(x) assert(x)
#ifdef MINIZ_NO_MALLOC
#define MZ_MALLOC(x) NULL
#define MZ_FREE(x) (void)x, ((void)0)
#define MZ_REALLOC(p, x) NULL
#else
#define MZ_MALLOC(x) malloc(x)
#define MZ_FREE(x) free(x)
#define MZ_REALLOC(p, x) realloc(p, x)
#endif
#define MZ_MAX(a, b) (((a) > (b)) ? (a) : (b))
#define MZ_MIN(a, b) (((a) < (b)) ? (a) : (b))
#define MZ_CLEAR_OBJ(obj) memset(&(obj), 0, sizeof(obj))
#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN
#define MZ_READ_LE16(p) *((const mz_uint16 *)(p))
#define MZ_READ_LE32(p) *((const mz_uint32 *)(p))
#else
#define MZ_READ_LE16(p) \
((mz_uint32)(((const mz_uint8 *)(p))[0]) | \
((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U))
#define MZ_READ_LE32(p) \
((mz_uint32)(((const mz_uint8 *)(p))[0]) | \
((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U) | \
((mz_uint32)(((const mz_uint8 *)(p))[2]) << 16U) | \
((mz_uint32)(((const mz_uint8 *)(p))[3]) << 24U))
#endif
#ifdef _MSC_VER
#define MZ_FORCEINLINE __forceinline
#elif defined(__GNUC__)
#define MZ_FORCEINLINE inline __attribute__((__always_inline__))
#else
#define MZ_FORCEINLINE inline
#endif
#ifdef __cplusplus
extern "C" {
#endif
// ------------------- zlib-style API's
mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len) {
mz_uint32 i, s1 = (mz_uint32)(adler & 0xffff), s2 = (mz_uint32)(adler >> 16);
size_t block_len = buf_len % 5552;
if (!ptr) return MZ_ADLER32_INIT;
while (buf_len) {
for (i = 0; i + 7 < block_len; i += 8, ptr += 8) {
s1 += ptr[0], s2 += s1;
s1 += ptr[1], s2 += s1;
s1 += ptr[2], s2 += s1;
s1 += ptr[3], s2 += s1;
s1 += ptr[4], s2 += s1;
s1 += ptr[5], s2 += s1;
s1 += ptr[6], s2 += s1;
s1 += ptr[7], s2 += s1;
}
for (; i < block_len; ++i) s1 += *ptr++, s2 += s1;
s1 %= 65521U, s2 %= 65521U;
buf_len -= block_len;
block_len = 5552;
}
return (s2 << 16) + s1;
}
// Karl Malbrain's compact CRC-32. See "A compact CCITT crc16 and crc32 C
// implementation that balances processor cache usage against speed":
// http://www.geocities.com/malbrain/
mz_ulong mz_crc32(mz_ulong crc, const mz_uint8 *ptr, size_t buf_len) {
static const mz_uint32 s_crc32[16] = {
0, 0x1db71064, 0x3b6e20c8, 0x26d930ac, 0x76dc4190, 0x6b6b51f4,
0x4db26158, 0x5005713c, 0xedb88320, 0xf00f9344, 0xd6d6a3e8, 0xcb61b38c,
0x9b64c2b0, 0x86d3d2d4, 0xa00ae278, 0xbdbdf21c};
mz_uint32 crcu32 = (mz_uint32)crc;
if (!ptr) return MZ_CRC32_INIT;
crcu32 = ~crcu32;
while (buf_len--) {
mz_uint8 b = *ptr++;
crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b & 0xF)];
crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b >> 4)];
}
return ~crcu32;
}
void mz_free(void *p) { MZ_FREE(p); }
#ifndef MINIZ_NO_ZLIB_APIS
static void *def_alloc_func(void *opaque, size_t items, size_t size) {
(void)opaque, (void)items, (void)size;
return MZ_MALLOC(items * size);
}
static void def_free_func(void *opaque, void *address) {
(void)opaque, (void)address;
MZ_FREE(address);
}
// static void *def_realloc_func(void *opaque, void *address, size_t items,
// size_t size) {
// (void)opaque, (void)address, (void)items, (void)size;
// return MZ_REALLOC(address, items * size);
//}
const char *mz_version(void) { return MZ_VERSION; }
int mz_deflateInit(mz_streamp pStream, int level) {
return mz_deflateInit2(pStream, level, MZ_DEFLATED, MZ_DEFAULT_WINDOW_BITS, 9,
MZ_DEFAULT_STRATEGY);
}
int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits,
int mem_level, int strategy) {
tdefl_compressor *pComp;
mz_uint comp_flags =
TDEFL_COMPUTE_ADLER32 |
tdefl_create_comp_flags_from_zip_params(level, window_bits, strategy);
if (!pStream) return MZ_STREAM_ERROR;
if ((method != MZ_DEFLATED) || ((mem_level < 1) || (mem_level > 9)) ||
((window_bits != MZ_DEFAULT_WINDOW_BITS) &&
(-window_bits != MZ_DEFAULT_WINDOW_BITS)))
return MZ_PARAM_ERROR;
pStream->data_type = 0;
pStream->adler = MZ_ADLER32_INIT;
pStream->msg = NULL;
pStream->reserved = 0;
pStream->total_in = 0;
pStream->total_out = 0;
if (!pStream->zalloc) pStream->zalloc = def_alloc_func;
if (!pStream->zfree) pStream->zfree = def_free_func;
pComp = (tdefl_compressor *)pStream->zalloc(pStream->opaque, 1,
sizeof(tdefl_compressor));
if (!pComp) return MZ_MEM_ERROR;
pStream->state = (struct mz_internal_state *)pComp;
if (tdefl_init(pComp, NULL, NULL, comp_flags) != TDEFL_STATUS_OKAY) {
mz_deflateEnd(pStream);
return MZ_PARAM_ERROR;
}
return MZ_OK;
}
int mz_deflateReset(mz_streamp pStream) {
if ((!pStream) || (!pStream->state) || (!pStream->zalloc) ||
(!pStream->zfree))
return MZ_STREAM_ERROR;
pStream->total_in = pStream->total_out = 0;
tdefl_init((tdefl_compressor *)pStream->state, NULL, NULL,
((tdefl_compressor *)pStream->state)->m_flags);
return MZ_OK;
}
int mz_deflate(mz_streamp pStream, int flush) {
size_t in_bytes, out_bytes;
mz_ulong orig_total_in, orig_total_out;
int mz_status = MZ_OK;
if ((!pStream) || (!pStream->state) || (flush < 0) || (flush > MZ_FINISH) ||
(!pStream->next_out))
return MZ_STREAM_ERROR;
if (!pStream->avail_out) return MZ_BUF_ERROR;
if (flush == MZ_PARTIAL_FLUSH) flush = MZ_SYNC_FLUSH;
if (((tdefl_compressor *)pStream->state)->m_prev_return_status ==
TDEFL_STATUS_DONE)
return (flush == MZ_FINISH) ? MZ_STREAM_END : MZ_BUF_ERROR;
orig_total_in = pStream->total_in;
orig_total_out = pStream->total_out;
for (;;) {
tdefl_status defl_status;
in_bytes = pStream->avail_in;
out_bytes = pStream->avail_out;
defl_status = tdefl_compress((tdefl_compressor *)pStream->state,
pStream->next_in, &in_bytes, pStream->next_out,
&out_bytes, (tdefl_flush)flush);
pStream->next_in += (mz_uint)in_bytes;
pStream->avail_in -= (mz_uint)in_bytes;
pStream->total_in += (mz_uint)in_bytes;
pStream->adler = tdefl_get_adler32((tdefl_compressor *)pStream->state);
pStream->next_out += (mz_uint)out_bytes;
pStream->avail_out -= (mz_uint)out_bytes;
pStream->total_out += (mz_uint)out_bytes;
if (defl_status < 0) {
mz_status = MZ_STREAM_ERROR;
break;
} else if (defl_status == TDEFL_STATUS_DONE) {
mz_status = MZ_STREAM_END;
break;
} else if (!pStream->avail_out)
break;
else if ((!pStream->avail_in) && (flush != MZ_FINISH)) {
if ((flush) || (pStream->total_in != orig_total_in) ||
(pStream->total_out != orig_total_out))
break;
return MZ_BUF_ERROR; // Can't make forward progress without some input.
}
}
return mz_status;
}
int mz_deflateEnd(mz_streamp pStream) {
if (!pStream) return MZ_STREAM_ERROR;
if (pStream->state) {
pStream->zfree(pStream->opaque, pStream->state);
pStream->state = NULL;
}
return MZ_OK;
}
mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len) {
(void)pStream;
// This is really over conservative. (And lame, but it's actually pretty
// tricky to compute a true upper bound given the way tdefl's blocking works.)
return MZ_MAX(128 + (source_len * 110) / 100,
128 + source_len + ((source_len / (31 * 1024)) + 1) * 5);
}
int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len,
const unsigned char *pSource, mz_ulong source_len, int level) {
int status;
mz_stream stream;
memset(&stream, 0, sizeof(stream));
// In case mz_ulong is 64-bits (argh I hate longs).
if ((source_len | *pDest_len) > 0xFFFFFFFFU) return MZ_PARAM_ERROR;
stream.next_in = pSource;
stream.avail_in = (mz_uint32)source_len;
stream.next_out = pDest;
stream.avail_out = (mz_uint32)*pDest_len;
status = mz_deflateInit(&stream, level);
if (status != MZ_OK) return status;
status = mz_deflate(&stream, MZ_FINISH);
if (status != MZ_STREAM_END) {
mz_deflateEnd(&stream);
return (status == MZ_OK) ? MZ_BUF_ERROR : status;
}
*pDest_len = stream.total_out;
return mz_deflateEnd(&stream);
}
int mz_compress(unsigned char *pDest, mz_ulong *pDest_len,
const unsigned char *pSource, mz_ulong source_len) {
return mz_compress2(pDest, pDest_len, pSource, source_len,
MZ_DEFAULT_COMPRESSION);
}
mz_ulong mz_compressBound(mz_ulong source_len) {
return mz_deflateBound(NULL, source_len);
}
typedef struct {
tinfl_decompressor m_decomp;
mz_uint m_dict_ofs, m_dict_avail, m_first_call, m_has_flushed;
int m_window_bits;
mz_uint8 m_dict[TINFL_LZ_DICT_SIZE];
tinfl_status m_last_status;
} inflate_state;
int mz_inflateInit2(mz_streamp pStream, int window_bits) {
inflate_state *pDecomp;
if (!pStream) return MZ_STREAM_ERROR;
if ((window_bits != MZ_DEFAULT_WINDOW_BITS) &&
(-window_bits != MZ_DEFAULT_WINDOW_BITS))
return MZ_PARAM_ERROR;
pStream->data_type = 0;
pStream->adler = 0;
pStream->msg = NULL;
pStream->total_in = 0;
pStream->total_out = 0;
pStream->reserved = 0;
if (!pStream->zalloc) pStream->zalloc = def_alloc_func;
if (!pStream->zfree) pStream->zfree = def_free_func;
pDecomp = (inflate_state *)pStream->zalloc(pStream->opaque, 1,
sizeof(inflate_state));
if (!pDecomp) return MZ_MEM_ERROR;
pStream->state = (struct mz_internal_state *)pDecomp;
tinfl_init(&pDecomp->m_decomp);
pDecomp->m_dict_ofs = 0;
pDecomp->m_dict_avail = 0;
pDecomp->m_last_status = TINFL_STATUS_NEEDS_MORE_INPUT;
pDecomp->m_first_call = 1;
pDecomp->m_has_flushed = 0;
pDecomp->m_window_bits = window_bits;
return MZ_OK;
}
int mz_inflateInit(mz_streamp pStream) {
return mz_inflateInit2(pStream, MZ_DEFAULT_WINDOW_BITS);
}
int mz_inflate(mz_streamp pStream, int flush) {
inflate_state *pState;
mz_uint n, first_call, decomp_flags = TINFL_FLAG_COMPUTE_ADLER32;
size_t in_bytes, out_bytes, orig_avail_in;
tinfl_status status;
if ((!pStream) || (!pStream->state)) return MZ_STREAM_ERROR;
if (flush == MZ_PARTIAL_FLUSH) flush = MZ_SYNC_FLUSH;
if ((flush) && (flush != MZ_SYNC_FLUSH) && (flush != MZ_FINISH))
return MZ_STREAM_ERROR;
pState = (inflate_state *)pStream->state;
if (pState->m_window_bits > 0) decomp_flags |= TINFL_FLAG_PARSE_ZLIB_HEADER;
orig_avail_in = pStream->avail_in;
first_call = pState->m_first_call;
pState->m_first_call = 0;
if (pState->m_last_status < 0) return MZ_DATA_ERROR;
if (pState->m_has_flushed && (flush != MZ_FINISH)) return MZ_STREAM_ERROR;
pState->m_has_flushed |= (flush == MZ_FINISH);
if ((flush == MZ_FINISH) && (first_call)) {
// MZ_FINISH on the first call implies that the input and output buffers are
// large enough to hold the entire compressed/decompressed file.
decomp_flags |= TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF;
in_bytes = pStream->avail_in;
out_bytes = pStream->avail_out;
status = tinfl_decompress(&pState->m_decomp, pStream->next_in, &in_bytes,
pStream->next_out, pStream->next_out, &out_bytes,
decomp_flags);
pState->m_last_status = status;
pStream->next_in += (mz_uint)in_bytes;
pStream->avail_in -= (mz_uint)in_bytes;
pStream->total_in += (mz_uint)in_bytes;
pStream->adler = tinfl_get_adler32(&pState->m_decomp);
pStream->next_out += (mz_uint)out_bytes;
pStream->avail_out -= (mz_uint)out_bytes;
pStream->total_out += (mz_uint)out_bytes;
if (status < 0)
return MZ_DATA_ERROR;
else if (status != TINFL_STATUS_DONE) {
pState->m_last_status = TINFL_STATUS_FAILED;
return MZ_BUF_ERROR;
}
return MZ_STREAM_END;
}
// flush != MZ_FINISH then we must assume there's more input.
if (flush != MZ_FINISH) decomp_flags |= TINFL_FLAG_HAS_MORE_INPUT;
if (pState->m_dict_avail) {
n = MZ_MIN(pState->m_dict_avail, pStream->avail_out);
memcpy(pStream->next_out, pState->m_dict + pState->m_dict_ofs, n);
pStream->next_out += n;
pStream->avail_out -= n;
pStream->total_out += n;
pState->m_dict_avail -= n;
pState->m_dict_ofs = (pState->m_dict_ofs + n) & (TINFL_LZ_DICT_SIZE - 1);
return ((pState->m_last_status == TINFL_STATUS_DONE) &&
(!pState->m_dict_avail))
? MZ_STREAM_END
: MZ_OK;
}
for (;;) {
in_bytes = pStream->avail_in;
out_bytes = TINFL_LZ_DICT_SIZE - pState->m_dict_ofs;
status = tinfl_decompress(
&pState->m_decomp, pStream->next_in, &in_bytes, pState->m_dict,
pState->m_dict + pState->m_dict_ofs, &out_bytes, decomp_flags);
pState->m_last_status = status;
pStream->next_in += (mz_uint)in_bytes;
pStream->avail_in -= (mz_uint)in_bytes;
pStream->total_in += (mz_uint)in_bytes;
pStream->adler = tinfl_get_adler32(&pState->m_decomp);
pState->m_dict_avail = (mz_uint)out_bytes;
n = MZ_MIN(pState->m_dict_avail, pStream->avail_out);
memcpy(pStream->next_out, pState->m_dict + pState->m_dict_ofs, n);
pStream->next_out += n;
pStream->avail_out -= n;
pStream->total_out += n;
pState->m_dict_avail -= n;
pState->m_dict_ofs = (pState->m_dict_ofs + n) & (TINFL_LZ_DICT_SIZE - 1);
if (status < 0)
return MZ_DATA_ERROR; // Stream is corrupted (there could be some
// uncompressed data left in the output dictionary -
// oh well).
else if ((status == TINFL_STATUS_NEEDS_MORE_INPUT) && (!orig_avail_in))
return MZ_BUF_ERROR; // Signal caller that we can't make forward progress
// without supplying more input or by setting flush
// to MZ_FINISH.
else if (flush == MZ_FINISH) {
// The output buffer MUST be large to hold the remaining uncompressed data
// when flush==MZ_FINISH.
if (status == TINFL_STATUS_DONE)
return pState->m_dict_avail ? MZ_BUF_ERROR : MZ_STREAM_END;
// status here must be TINFL_STATUS_HAS_MORE_OUTPUT, which means there's
// at least 1 more byte on the way. If there's no more room left in the
// output buffer then something is wrong.
else if (!pStream->avail_out)
return MZ_BUF_ERROR;
} else if ((status == TINFL_STATUS_DONE) || (!pStream->avail_in) ||
(!pStream->avail_out) || (pState->m_dict_avail))
break;
}
return ((status == TINFL_STATUS_DONE) && (!pState->m_dict_avail))
? MZ_STREAM_END
: MZ_OK;
}
int mz_inflateEnd(mz_streamp pStream) {
if (!pStream) return MZ_STREAM_ERROR;
if (pStream->state) {
pStream->zfree(pStream->opaque, pStream->state);
pStream->state = NULL;
}
return MZ_OK;
}
int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len,
const unsigned char *pSource, mz_ulong source_len) {
mz_stream stream;
int status;
memset(&stream, 0, sizeof(stream));
// In case mz_ulong is 64-bits (argh I hate longs).
if ((source_len | *pDest_len) > 0xFFFFFFFFU) return MZ_PARAM_ERROR;
stream.next_in = pSource;
stream.avail_in = (mz_uint32)source_len;
stream.next_out = pDest;
stream.avail_out = (mz_uint32)*pDest_len;
status = mz_inflateInit(&stream);
if (status != MZ_OK) return status;
status = mz_inflate(&stream, MZ_FINISH);
if (status != MZ_STREAM_END) {
mz_inflateEnd(&stream);
return ((status == MZ_BUF_ERROR) && (!stream.avail_in)) ? MZ_DATA_ERROR
: status;
}
*pDest_len = stream.total_out;
return mz_inflateEnd(&stream);
}
const char *mz_error(int err) {
static struct {
int m_err;
const char *m_pDesc;
} s_error_descs[] = {{MZ_OK, ""},
{MZ_STREAM_END, "stream end"},
{MZ_NEED_DICT, "need dictionary"},
{MZ_ERRNO, "file error"},
{MZ_STREAM_ERROR, "stream error"},
{MZ_DATA_ERROR, "data error"},
{MZ_MEM_ERROR, "out of memory"},
{MZ_BUF_ERROR, "buf error"},
{MZ_VERSION_ERROR, "version error"},
{MZ_PARAM_ERROR, "parameter error"}};
mz_uint i;
for (i = 0; i < sizeof(s_error_descs) / sizeof(s_error_descs[0]); ++i)
if (s_error_descs[i].m_err == err) return s_error_descs[i].m_pDesc;
return NULL;
}
#endif // MINIZ_NO_ZLIB_APIS
// ------------------- Low-level Decompression (completely independent from all
// compression API's)
#define TINFL_MEMCPY(d, s, l) memcpy(d, s, l)
#define TINFL_MEMSET(p, c, l) memset(p, c, l)
#define TINFL_CR_BEGIN \
switch (r->m_state) { \
case 0:
#define TINFL_CR_RETURN(state_index, result) \
do { \
status = result; \
r->m_state = state_index; \
goto common_exit; \
case state_index:; \
} \
MZ_MACRO_END
#define TINFL_CR_RETURN_FOREVER(state_index, result) \
do { \
for (;;) { \
TINFL_CR_RETURN(state_index, result); \
} \
} \
MZ_MACRO_END
#define TINFL_CR_FINISH }
// TODO: If the caller has indicated that there's no more input, and we attempt
// to read beyond the input buf, then something is wrong with the input because
// the inflator never
// reads ahead more than it needs to. Currently TINFL_GET_BYTE() pads the end of
// the stream with 0's in this scenario.
#define TINFL_GET_BYTE(state_index, c) \
do { \
if (pIn_buf_cur >= pIn_buf_end) { \
for (;;) { \
if (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) { \
TINFL_CR_RETURN(state_index, TINFL_STATUS_NEEDS_MORE_INPUT); \
if (pIn_buf_cur < pIn_buf_end) { \
c = *pIn_buf_cur++; \
break; \
} \
} else { \
c = 0; \
break; \
} \
} \
} else \
c = *pIn_buf_cur++; \
} \
MZ_MACRO_END
#define TINFL_NEED_BITS(state_index, n) \
do { \
mz_uint c; \
TINFL_GET_BYTE(state_index, c); \
bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); \
num_bits += 8; \
} while (num_bits < (mz_uint)(n))
#define TINFL_SKIP_BITS(state_index, n) \
do { \
if (num_bits < (mz_uint)(n)) { \
TINFL_NEED_BITS(state_index, n); \
} \
bit_buf >>= (n); \
num_bits -= (n); \
} \
MZ_MACRO_END
#define TINFL_GET_BITS(state_index, b, n) \
do { \
if (num_bits < (mz_uint)(n)) { \
TINFL_NEED_BITS(state_index, n); \
} \
b = bit_buf & ((1 << (n)) - 1); \
bit_buf >>= (n); \
num_bits -= (n); \
} \
MZ_MACRO_END
// TINFL_HUFF_BITBUF_FILL() is only used rarely, when the number of bytes
// remaining in the input buffer falls below 2.
// It reads just enough bytes from the input stream that are needed to decode
// the next Huffman code (and absolutely no more). It works by trying to fully
// decode a
// Huffman code by using whatever bits are currently present in the bit buffer.
// If this fails, it reads another byte, and tries again until it succeeds or
// until the
// bit buffer contains >=15 bits (deflate's max. Huffman code size).
#define TINFL_HUFF_BITBUF_FILL(state_index, pHuff) \
do { \
temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]; \
if (temp >= 0) { \
code_len = temp >> 9; \
if ((code_len) && (num_bits >= code_len)) break; \
} else if (num_bits > TINFL_FAST_LOOKUP_BITS) { \
code_len = TINFL_FAST_LOOKUP_BITS; \
do { \
temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; \
} while ((temp < 0) && (num_bits >= (code_len + 1))); \
if (temp >= 0) break; \
} \
TINFL_GET_BYTE(state_index, c); \
bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); \
num_bits += 8; \
} while (num_bits < 15);
// TINFL_HUFF_DECODE() decodes the next Huffman coded symbol. It's more complex
// than you would initially expect because the zlib API expects the decompressor
// to never read
// beyond the final byte of the deflate stream. (In other words, when this macro
// wants to read another byte from the input, it REALLY needs another byte in
// order to fully
// decode the next Huffman code.) Handling this properly is particularly
// important on raw deflate (non-zlib) streams, which aren't followed by a byte
// aligned adler-32.
// The slow path is only executed at the very end of the input buffer.
#define TINFL_HUFF_DECODE(state_index, sym, pHuff) \
do { \
int temp; \
mz_uint code_len, c; \
if (num_bits < 15) { \
if ((pIn_buf_end - pIn_buf_cur) < 2) { \
TINFL_HUFF_BITBUF_FILL(state_index, pHuff); \
} else { \
bit_buf |= (((tinfl_bit_buf_t)pIn_buf_cur[0]) << num_bits) | \
(((tinfl_bit_buf_t)pIn_buf_cur[1]) << (num_bits + 8)); \
pIn_buf_cur += 2; \
num_bits += 16; \
} \
} \
if ((temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= \
0) \
code_len = temp >> 9, temp &= 511; \
else { \
code_len = TINFL_FAST_LOOKUP_BITS; \
do { \
temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; \
} while (temp < 0); \
} \
sym = temp; \
bit_buf >>= code_len; \
num_bits -= code_len; \
} \
MZ_MACRO_END
tinfl_status tinfl_decompress(tinfl_decompressor *r,
const mz_uint8 *pIn_buf_next,
size_t *pIn_buf_size, mz_uint8 *pOut_buf_start,
mz_uint8 *pOut_buf_next, size_t *pOut_buf_size,
const mz_uint32 decomp_flags) {
static const int s_length_base[31] = {
3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
static const int s_length_extra[31] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1,
1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4,
4, 4, 5, 5, 5, 5, 0, 0, 0};
static const int s_dist_base[32] = {
1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33,
49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537,
2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577, 0, 0};
static const int s_dist_extra[32] = {0, 0, 0, 0, 1, 1, 2, 2, 3, 3,
4, 4, 5, 5, 6, 6, 7, 7, 8, 8,
9, 9, 10, 10, 11, 11, 12, 12, 13, 13};
static const mz_uint8 s_length_dezigzag[19] = {
16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
static const int s_min_table_sizes[3] = {257, 1, 4};
tinfl_status status = TINFL_STATUS_FAILED;
mz_uint32 num_bits, dist, counter, num_extra;
tinfl_bit_buf_t bit_buf;
const mz_uint8 *pIn_buf_cur = pIn_buf_next, *const pIn_buf_end =
pIn_buf_next + *pIn_buf_size;
mz_uint8 *pOut_buf_cur = pOut_buf_next, *const pOut_buf_end =
pOut_buf_next + *pOut_buf_size;
size_t out_buf_size_mask =
(decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)
? (size_t)-1
: ((pOut_buf_next - pOut_buf_start) + *pOut_buf_size) - 1,
dist_from_out_buf_start;
// Ensure the output buffer's size is a power of 2, unless the output buffer
// is large enough to hold the entire output file (in which case it doesn't
// matter).
if (((out_buf_size_mask + 1) & out_buf_size_mask) ||
(pOut_buf_next < pOut_buf_start)) {
*pIn_buf_size = *pOut_buf_size = 0;
return TINFL_STATUS_BAD_PARAM;
}
num_bits = r->m_num_bits;
bit_buf = r->m_bit_buf;
dist = r->m_dist;
counter = r->m_counter;
num_extra = r->m_num_extra;
dist_from_out_buf_start = r->m_dist_from_out_buf_start;
TINFL_CR_BEGIN
bit_buf = num_bits = dist = counter = num_extra = r->m_zhdr0 = r->m_zhdr1 = 0;
r->m_z_adler32 = r->m_check_adler32 = 1;
if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) {
TINFL_GET_BYTE(1, r->m_zhdr0);
TINFL_GET_BYTE(2, r->m_zhdr1);
counter = (((r->m_zhdr0 * 256 + r->m_zhdr1) % 31 != 0) ||
(r->m_zhdr1 & 32) || ((r->m_zhdr0 & 15) != 8));
if (!(decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF))
counter |= (((1U << (8U + (r->m_zhdr0 >> 4))) > 32768U) ||
((out_buf_size_mask + 1) <
(size_t)(1ULL << (8U + (r->m_zhdr0 >> 4)))));
if (counter) {
TINFL_CR_RETURN_FOREVER(36, TINFL_STATUS_FAILED);
}
}
do {
TINFL_GET_BITS(3, r->m_final, 3);
r->m_type = r->m_final >> 1;
if (r->m_type == 0) {
TINFL_SKIP_BITS(5, num_bits & 7);
for (counter = 0; counter < 4; ++counter) {
if (num_bits)
TINFL_GET_BITS(6, r->m_raw_header[counter], 8);
else
TINFL_GET_BYTE(7, r->m_raw_header[counter]);
}
if ((counter = (r->m_raw_header[0] | (r->m_raw_header[1] << 8))) !=
(mz_uint)(0xFFFF ^
(r->m_raw_header[2] | (r->m_raw_header[3] << 8)))) {
TINFL_CR_RETURN_FOREVER(39, TINFL_STATUS_FAILED);
}
while ((counter) && (num_bits)) {
TINFL_GET_BITS(51, dist, 8);
while (pOut_buf_cur >= pOut_buf_end) {
TINFL_CR_RETURN(52, TINFL_STATUS_HAS_MORE_OUTPUT);
}
*pOut_buf_cur++ = (mz_uint8)dist;
counter--;
}
while (counter) {
size_t n;
while (pOut_buf_cur >= pOut_buf_end) {
TINFL_CR_RETURN(9, TINFL_STATUS_HAS_MORE_OUTPUT);
}
while (pIn_buf_cur >= pIn_buf_end) {
if (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) {
TINFL_CR_RETURN(38, TINFL_STATUS_NEEDS_MORE_INPUT);
} else {
TINFL_CR_RETURN_FOREVER(40, TINFL_STATUS_FAILED);
}
}
n = MZ_MIN(MZ_MIN((size_t)(pOut_buf_end - pOut_buf_cur),
(size_t)(pIn_buf_end - pIn_buf_cur)),
counter);
TINFL_MEMCPY(pOut_buf_cur, pIn_buf_cur, n);
pIn_buf_cur += n;
pOut_buf_cur += n;
counter -= (mz_uint)n;
}
} else if (r->m_type == 3) {
TINFL_CR_RETURN_FOREVER(10, TINFL_STATUS_FAILED);
} else {
if (r->m_type == 1) {
mz_uint8 *p = r->m_tables[0].m_code_size;
mz_uint i;
r->m_table_sizes[0] = 288;
r->m_table_sizes[1] = 32;
TINFL_MEMSET(r->m_tables[1].m_code_size, 5, 32);
for (i = 0; i <= 143; ++i) *p++ = 8;
for (; i <= 255; ++i) *p++ = 9;
for (; i <= 279; ++i) *p++ = 7;
for (; i <= 287; ++i) *p++ = 8;
} else {
for (counter = 0; counter < 3; counter++) {
TINFL_GET_BITS(11, r->m_table_sizes[counter], "\05\05\04"[counter]);
r->m_table_sizes[counter] += s_min_table_sizes[counter];
}
MZ_CLEAR_OBJ(r->m_tables[2].m_code_size);
for (counter = 0; counter < r->m_table_sizes[2]; counter++) {
mz_uint s;
TINFL_GET_BITS(14, s, 3);
r->m_tables[2].m_code_size[s_length_dezigzag[counter]] = (mz_uint8)s;
}
r->m_table_sizes[2] = 19;
}
for (; (int)r->m_type >= 0; r->m_type--) {
int tree_next, tree_cur;
tinfl_huff_table *pTable;
mz_uint i, j, used_syms, total, sym_index, next_code[17],
total_syms[16];
pTable = &r->m_tables[r->m_type];
MZ_CLEAR_OBJ(total_syms);
MZ_CLEAR_OBJ(pTable->m_look_up);
MZ_CLEAR_OBJ(pTable->m_tree);
for (i = 0; i < r->m_table_sizes[r->m_type]; ++i)
total_syms[pTable->m_code_size[i]]++;
used_syms = 0, total = 0;
next_code[0] = next_code[1] = 0;
for (i = 1; i <= 15; ++i) {
used_syms += total_syms[i];
next_code[i + 1] = (total = ((total + total_syms[i]) << 1));
}
if ((65536 != total) && (used_syms > 1)) {
TINFL_CR_RETURN_FOREVER(35, TINFL_STATUS_FAILED);
}
for (tree_next = -1, sym_index = 0;
sym_index < r->m_table_sizes[r->m_type]; ++sym_index) {
mz_uint rev_code = 0, l, cur_code,
code_size = pTable->m_code_size[sym_index];
if (!code_size) continue;
cur_code = next_code[code_size]++;
for (l = code_size; l > 0; l--, cur_code >>= 1)
rev_code = (rev_code << 1) | (cur_code & 1);
if (code_size <= TINFL_FAST_LOOKUP_BITS) {
mz_int16 k = (mz_int16)((code_size << 9) | sym_index);
while (rev_code < TINFL_FAST_LOOKUP_SIZE) {
pTable->m_look_up[rev_code] = k;
rev_code += (1 << code_size);
}
continue;
}
if (0 ==
(tree_cur = pTable->m_look_up[rev_code &
(TINFL_FAST_LOOKUP_SIZE - 1)])) {
pTable->m_look_up[rev_code & (TINFL_FAST_LOOKUP_SIZE - 1)] =
(mz_int16)tree_next;
tree_cur = tree_next;
tree_next -= 2;
}
rev_code >>= (TINFL_FAST_LOOKUP_BITS - 1);
for (j = code_size; j > (TINFL_FAST_LOOKUP_BITS + 1); j--) {
tree_cur -= ((rev_code >>= 1) & 1);
if (!pTable->m_tree[-tree_cur - 1]) {
pTable->m_tree[-tree_cur - 1] = (mz_int16)tree_next;
tree_cur = tree_next;
tree_next -= 2;
} else
tree_cur = pTable->m_tree[-tree_cur - 1];
}
tree_cur -= ((rev_code >>= 1) & 1);
pTable->m_tree[-tree_cur - 1] = (mz_int16)sym_index;
}
if (r->m_type == 2) {
for (counter = 0;
counter < (r->m_table_sizes[0] + r->m_table_sizes[1]);) {
mz_uint s;
TINFL_HUFF_DECODE(16, dist, &r->m_tables[2]);
if (dist < 16) {
r->m_len_codes[counter++] = (mz_uint8)dist;
continue;
}
if ((dist == 16) && (!counter)) {
TINFL_CR_RETURN_FOREVER(17, TINFL_STATUS_FAILED);
}
num_extra = "\02\03\07"[dist - 16];
TINFL_GET_BITS(18, s, num_extra);
s += "\03\03\013"[dist - 16];
TINFL_MEMSET(r->m_len_codes + counter,
(dist == 16) ? r->m_len_codes[counter - 1] : 0, s);
counter += s;
}
if ((r->m_table_sizes[0] + r->m_table_sizes[1]) != counter) {
TINFL_CR_RETURN_FOREVER(21, TINFL_STATUS_FAILED);
}
TINFL_MEMCPY(r->m_tables[0].m_code_size, r->m_len_codes,
r->m_table_sizes[0]);
TINFL_MEMCPY(r->m_tables[1].m_code_size,
r->m_len_codes + r->m_table_sizes[0],
r->m_table_sizes[1]);
}
}
for (;;) {
mz_uint8 *pSrc;
for (;;) {
if (((pIn_buf_end - pIn_buf_cur) < 4) ||
((pOut_buf_end - pOut_buf_cur) < 2)) {
TINFL_HUFF_DECODE(23, counter, &r->m_tables[0]);
if (counter >= 256) break;
while (pOut_buf_cur >= pOut_buf_end) {
TINFL_CR_RETURN(24, TINFL_STATUS_HAS_MORE_OUTPUT);
}
*pOut_buf_cur++ = (mz_uint8)counter;
} else {
int sym2;
mz_uint code_len;
#if TINFL_USE_64BIT_BITBUF
if (num_bits < 30) {
bit_buf |=
(((tinfl_bit_buf_t)MZ_READ_LE32(pIn_buf_cur)) << num_bits);
pIn_buf_cur += 4;
num_bits += 32;
}
#else
if (num_bits < 15) {
bit_buf |=
(((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits);
pIn_buf_cur += 2;
num_bits += 16;
}
#endif
if ((sym2 =
r->m_tables[0]
.m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >=
0)
code_len = sym2 >> 9;
else {
code_len = TINFL_FAST_LOOKUP_BITS;
do {
sym2 = r->m_tables[0]
.m_tree[~sym2 + ((bit_buf >> code_len++) & 1)];
} while (sym2 < 0);
}
counter = sym2;
bit_buf >>= code_len;
num_bits -= code_len;
if (counter & 256) break;
#if !TINFL_USE_64BIT_BITBUF
if (num_bits < 15) {
bit_buf |=
(((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits);
pIn_buf_cur += 2;
num_bits += 16;
}
#endif
if ((sym2 =
r->m_tables[0]
.m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >=
0)
code_len = sym2 >> 9;
else {
code_len = TINFL_FAST_LOOKUP_BITS;
do {
sym2 = r->m_tables[0]
.m_tree[~sym2 + ((bit_buf >> code_len++) & 1)];
} while (sym2 < 0);
}
bit_buf >>= code_len;
num_bits -= code_len;
pOut_buf_cur[0] = (mz_uint8)counter;
if (sym2 & 256) {
pOut_buf_cur++;
counter = sym2;
break;
}
pOut_buf_cur[1] = (mz_uint8)sym2;
pOut_buf_cur += 2;
}
}
if ((counter &= 511) == 256) break;
num_extra = s_length_extra[counter - 257];
counter = s_length_base[counter - 257];
if (num_extra) {
mz_uint extra_bits;
TINFL_GET_BITS(25, extra_bits, num_extra);
counter += extra_bits;
}
TINFL_HUFF_DECODE(26, dist, &r->m_tables[1]);
num_extra = s_dist_extra[dist];
dist = s_dist_base[dist];
if (num_extra) {
mz_uint extra_bits;
TINFL_GET_BITS(27, extra_bits, num_extra);
dist += extra_bits;
}
dist_from_out_buf_start = pOut_buf_cur - pOut_buf_start;
if ((dist > dist_from_out_buf_start) &&
(decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)) {
TINFL_CR_RETURN_FOREVER(37, TINFL_STATUS_FAILED);
}
pSrc = pOut_buf_start +
((dist_from_out_buf_start - dist) & out_buf_size_mask);
if ((MZ_MAX(pOut_buf_cur, pSrc) + counter) > pOut_buf_end) {
while (counter--) {
while (pOut_buf_cur >= pOut_buf_end) {
TINFL_CR_RETURN(53, TINFL_STATUS_HAS_MORE_OUTPUT);
}
*pOut_buf_cur++ =
pOut_buf_start[(dist_from_out_buf_start++ - dist) &
out_buf_size_mask];
}
continue;
}
#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES
else if ((counter >= 9) && (counter <= dist)) {
const mz_uint8 *pSrc_end = pSrc + (counter & ~7);
do {
((mz_uint32 *)pOut_buf_cur)[0] = ((const mz_uint32 *)pSrc)[0];
((mz_uint32 *)pOut_buf_cur)[1] = ((const mz_uint32 *)pSrc)[1];
pOut_buf_cur += 8;
} while ((pSrc += 8) < pSrc_end);
if ((counter &= 7) < 3) {
if (counter) {
pOut_buf_cur[0] = pSrc[0];
if (counter > 1) pOut_buf_cur[1] = pSrc[1];
pOut_buf_cur += counter;
}
continue;
}
}
#endif
do {
pOut_buf_cur[0] = pSrc[0];
pOut_buf_cur[1] = pSrc[1];
pOut_buf_cur[2] = pSrc[2];
pOut_buf_cur += 3;
pSrc += 3;
} while ((int)(counter -= 3) > 2);
if ((int)counter > 0) {
pOut_buf_cur[0] = pSrc[0];
if ((int)counter > 1) pOut_buf_cur[1] = pSrc[1];
pOut_buf_cur += counter;
}
}
}
} while (!(r->m_final & 1));
if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) {
TINFL_SKIP_BITS(32, num_bits & 7);
for (counter = 0; counter < 4; ++counter) {
mz_uint s;
if (num_bits)
TINFL_GET_BITS(41, s, 8);
else
TINFL_GET_BYTE(42, s);
r->m_z_adler32 = (r->m_z_adler32 << 8) | s;
}
}
TINFL_CR_RETURN_FOREVER(34, TINFL_STATUS_DONE);
TINFL_CR_FINISH
common_exit:
r->m_num_bits = num_bits;
r->m_bit_buf = bit_buf;
r->m_dist = dist;
r->m_counter = counter;
r->m_num_extra = num_extra;
r->m_dist_from_out_buf_start = dist_from_out_buf_start;
*pIn_buf_size = pIn_buf_cur - pIn_buf_next;
*pOut_buf_size = pOut_buf_cur - pOut_buf_next;
if ((decomp_flags &
(TINFL_FLAG_PARSE_ZLIB_HEADER | TINFL_FLAG_COMPUTE_ADLER32)) &&
(status >= 0)) {
const mz_uint8 *ptr = pOut_buf_next;
size_t buf_len = *pOut_buf_size;
mz_uint32 i, s1 = r->m_check_adler32 & 0xffff,
s2 = r->m_check_adler32 >> 16;
size_t block_len = buf_len % 5552;
while (buf_len) {
for (i = 0; i + 7 < block_len; i += 8, ptr += 8) {
s1 += ptr[0], s2 += s1;
s1 += ptr[1], s2 += s1;
s1 += ptr[2], s2 += s1;
s1 += ptr[3], s2 += s1;
s1 += ptr[4], s2 += s1;
s1 += ptr[5], s2 += s1;
s1 += ptr[6], s2 += s1;
s1 += ptr[7], s2 += s1;
}
for (; i < block_len; ++i) s1 += *ptr++, s2 += s1;
s1 %= 65521U, s2 %= 65521U;
buf_len -= block_len;
block_len = 5552;
}
r->m_check_adler32 = (s2 << 16) + s1;
if ((status == TINFL_STATUS_DONE) &&
(decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) &&
(r->m_check_adler32 != r->m_z_adler32))
status = TINFL_STATUS_ADLER32_MISMATCH;
}
return status;
}
// Higher level helper functions.
void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len,
size_t *pOut_len, int flags) {
tinfl_decompressor decomp;
void *pBuf = NULL, *pNew_buf;
size_t src_buf_ofs = 0, out_buf_capacity = 0;
*pOut_len = 0;
tinfl_init(&decomp);
for (;;) {
size_t src_buf_size = src_buf_len - src_buf_ofs,
dst_buf_size = out_buf_capacity - *pOut_len, new_out_buf_capacity;
tinfl_status status = tinfl_decompress(
&decomp, (const mz_uint8 *)pSrc_buf + src_buf_ofs, &src_buf_size,
(mz_uint8 *)pBuf, pBuf ? (mz_uint8 *)pBuf + *pOut_len : NULL,
&dst_buf_size,
(flags & ~TINFL_FLAG_HAS_MORE_INPUT) |
TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF);
if ((status < 0) || (status == TINFL_STATUS_NEEDS_MORE_INPUT)) {
MZ_FREE(pBuf);
*pOut_len = 0;
return NULL;
}
src_buf_ofs += src_buf_size;
*pOut_len += dst_buf_size;
if (status == TINFL_STATUS_DONE) break;
new_out_buf_capacity = out_buf_capacity * 2;
if (new_out_buf_capacity < 128) new_out_buf_capacity = 128;
pNew_buf = MZ_REALLOC(pBuf, new_out_buf_capacity);
if (!pNew_buf) {
MZ_FREE(pBuf);
*pOut_len = 0;
return NULL;
}
pBuf = pNew_buf;
out_buf_capacity = new_out_buf_capacity;
}
return pBuf;
}
size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len,
const void *pSrc_buf, size_t src_buf_len,
int flags) {
tinfl_decompressor decomp;
tinfl_status status;
tinfl_init(&decomp);
status =
tinfl_decompress(&decomp, (const mz_uint8 *)pSrc_buf, &src_buf_len,
(mz_uint8 *)pOut_buf, (mz_uint8 *)pOut_buf, &out_buf_len,
(flags & ~TINFL_FLAG_HAS_MORE_INPUT) |
TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF);
return (status != TINFL_STATUS_DONE) ? TINFL_DECOMPRESS_MEM_TO_MEM_FAILED
: out_buf_len;
}
int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size,
tinfl_put_buf_func_ptr pPut_buf_func,
void *pPut_buf_user, int flags) {
int result = 0;
tinfl_decompressor decomp;
mz_uint8 *pDict = (mz_uint8 *)MZ_MALLOC(TINFL_LZ_DICT_SIZE);
size_t in_buf_ofs = 0, dict_ofs = 0;
if (!pDict) return TINFL_STATUS_FAILED;
tinfl_init(&decomp);
for (;;) {
size_t in_buf_size = *pIn_buf_size - in_buf_ofs,
dst_buf_size = TINFL_LZ_DICT_SIZE - dict_ofs;
tinfl_status status =
tinfl_decompress(&decomp, (const mz_uint8 *)pIn_buf + in_buf_ofs,
&in_buf_size, pDict, pDict + dict_ofs, &dst_buf_size,
(flags & ~(TINFL_FLAG_HAS_MORE_INPUT |
TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)));
in_buf_ofs += in_buf_size;
if ((dst_buf_size) &&
(!(*pPut_buf_func)(pDict + dict_ofs, (int)dst_buf_size, pPut_buf_user)))
break;
if (status != TINFL_STATUS_HAS_MORE_OUTPUT) {
result = (status == TINFL_STATUS_DONE);
break;
}
dict_ofs = (dict_ofs + dst_buf_size) & (TINFL_LZ_DICT_SIZE - 1);
}
MZ_FREE(pDict);
*pIn_buf_size = in_buf_ofs;
return result;
}
// ------------------- Low-level Compression (independent from all decompression
// API's)
// Purposely making these tables static for faster init and thread safety.
static const mz_uint16 s_tdefl_len_sym[256] = {
257, 258, 259, 260, 261, 262, 263, 264, 265, 265, 266, 266, 267, 267, 268,
268, 269, 269, 269, 269, 270, 270, 270, 270, 271, 271, 271, 271, 272, 272,
272, 272, 273, 273, 273, 273, 273, 273, 273, 273, 274, 274, 274, 274, 274,
274, 274, 274, 275, 275, 275, 275, 275, 275, 275, 275, 276, 276, 276, 276,
276, 276, 276, 276, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277,
277, 277, 277, 277, 277, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278,
278, 278, 278, 278, 278, 278, 279, 279, 279, 279, 279, 279, 279, 279, 279,
279, 279, 279, 279, 279, 279, 279, 280, 280, 280, 280, 280, 280, 280, 280,
280, 280, 280, 280, 280, 280, 280, 280, 281, 281, 281, 281, 281, 281, 281,
281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281,
281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 282, 282, 282, 282, 282,
282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282,
282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 283, 283, 283,
283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283,
283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 284,
284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284,
284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284,
285};
static const mz_uint8 s_tdefl_len_extra[256] = {
0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 0};
static const mz_uint8 s_tdefl_small_dist_sym[512] = {
0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8,
8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11,
11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
12, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14,
14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
15, 15, 15, 15, 15, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,
16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,
16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,
16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,
16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,
16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,
16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,
16, 16, 16, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17,
17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17,
17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17,
17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17,
17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17,
17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17,
17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17};
static const mz_uint8 s_tdefl_small_dist_extra[512] = {
0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7};
static const mz_uint8 s_tdefl_large_dist_sym[128] = {
0, 0, 18, 19, 20, 20, 21, 21, 22, 22, 22, 22, 23, 23, 23, 23, 24, 24, 24,
24, 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26,
26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27,
27, 27, 27, 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29};
static const mz_uint8 s_tdefl_large_dist_extra[128] = {
0, 0, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11,
11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12,
12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13};
// Radix sorts tdefl_sym_freq[] array by 16-bit key m_key. Returns ptr to sorted
// values.
typedef struct {
mz_uint16 m_key, m_sym_index;
} tdefl_sym_freq;
static tdefl_sym_freq *tdefl_radix_sort_syms(mz_uint num_syms,
tdefl_sym_freq *pSyms0,
tdefl_sym_freq *pSyms1) {
mz_uint32 total_passes = 2, pass_shift, pass, i, hist[256 * 2];
tdefl_sym_freq *pCur_syms = pSyms0, *pNew_syms = pSyms1;
MZ_CLEAR_OBJ(hist);
for (i = 0; i < num_syms; i++) {
mz_uint freq = pSyms0[i].m_key;
hist[freq & 0xFF]++;
hist[256 + ((freq >> 8) & 0xFF)]++;
}
while ((total_passes > 1) && (num_syms == hist[(total_passes - 1) * 256]))
total_passes--;
for (pass_shift = 0, pass = 0; pass < total_passes; pass++, pass_shift += 8) {
const mz_uint32 *pHist = &hist[pass << 8];
mz_uint offsets[256], cur_ofs = 0;
for (i = 0; i < 256; i++) {
offsets[i] = cur_ofs;
cur_ofs += pHist[i];
}
for (i = 0; i < num_syms; i++)
pNew_syms[offsets[(pCur_syms[i].m_key >> pass_shift) & 0xFF]++] =
pCur_syms[i];
{
tdefl_sym_freq *t = pCur_syms;
pCur_syms = pNew_syms;
pNew_syms = t;
}
}
return pCur_syms;
}
// tdefl_calculate_minimum_redundancy() originally written by: Alistair Moffat,
// alistair@cs.mu.oz.au, Jyrki Katajainen, jyrki@diku.dk, November 1996.
static void tdefl_calculate_minimum_redundancy(tdefl_sym_freq *A, int n) {
int root, leaf, next, avbl, used, dpth;
if (n == 0)
return;
else if (n == 1) {
A[0].m_key = 1;
return;
}
A[0].m_key += A[1].m_key;
root = 0;
leaf = 2;
for (next = 1; next < n - 1; next++) {
if (leaf >= n || A[root].m_key < A[leaf].m_key) {
A[next].m_key = A[root].m_key;
A[root++].m_key = (mz_uint16)next;
} else
A[next].m_key = A[leaf++].m_key;
if (leaf >= n || (root < next && A[root].m_key < A[leaf].m_key)) {
A[next].m_key = (mz_uint16)(A[next].m_key + A[root].m_key);
A[root++].m_key = (mz_uint16)next;
} else
A[next].m_key = (mz_uint16)(A[next].m_key + A[leaf++].m_key);
}
A[n - 2].m_key = 0;
for (next = n - 3; next >= 0; next--)
A[next].m_key = A[A[next].m_key].m_key + 1;
avbl = 1;
used = dpth = 0;
root = n - 2;
next = n - 1;
while (avbl > 0) {
while (root >= 0 && (int)A[root].m_key == dpth) {
used++;
root--;
}
while (avbl > used) {
A[next--].m_key = (mz_uint16)(dpth);
avbl--;
}
avbl = 2 * used;
dpth++;
used = 0;
}
}
// Limits canonical Huffman code table's max code size.
enum { TDEFL_MAX_SUPPORTED_HUFF_CODESIZE = 32 };
static void tdefl_huffman_enforce_max_code_size(int *pNum_codes,
int code_list_len,
int max_code_size) {
int i;
mz_uint32 total = 0;
if (code_list_len <= 1) return;
for (i = max_code_size + 1; i <= TDEFL_MAX_SUPPORTED_HUFF_CODESIZE; i++)
pNum_codes[max_code_size] += pNum_codes[i];
for (i = max_code_size; i > 0; i--)
total += (((mz_uint32)pNum_codes[i]) << (max_code_size - i));
while (total != (1UL << max_code_size)) {
pNum_codes[max_code_size]--;
for (i = max_code_size - 1; i > 0; i--)
if (pNum_codes[i]) {
pNum_codes[i]--;
pNum_codes[i + 1] += 2;
break;
}
total--;
}
}
static void tdefl_optimize_huffman_table(tdefl_compressor *d, int table_num,
int table_len, int code_size_limit,
int static_table) {
int i, j, l, num_codes[1 + TDEFL_MAX_SUPPORTED_HUFF_CODESIZE];
mz_uint next_code[TDEFL_MAX_SUPPORTED_HUFF_CODESIZE + 1];
MZ_CLEAR_OBJ(num_codes);
if (static_table) {
for (i = 0; i < table_len; i++)
num_codes[d->m_huff_code_sizes[table_num][i]]++;
} else {
tdefl_sym_freq syms0[TDEFL_MAX_HUFF_SYMBOLS], syms1[TDEFL_MAX_HUFF_SYMBOLS],
*pSyms;
int num_used_syms = 0;
const mz_uint16 *pSym_count = &d->m_huff_count[table_num][0];
for (i = 0; i < table_len; i++)
if (pSym_count[i]) {
syms0[num_used_syms].m_key = (mz_uint16)pSym_count[i];
syms0[num_used_syms++].m_sym_index = (mz_uint16)i;
}
pSyms = tdefl_radix_sort_syms(num_used_syms, syms0, syms1);
tdefl_calculate_minimum_redundancy(pSyms, num_used_syms);
for (i = 0; i < num_used_syms; i++) num_codes[pSyms[i].m_key]++;
tdefl_huffman_enforce_max_code_size(num_codes, num_used_syms,
code_size_limit);
MZ_CLEAR_OBJ(d->m_huff_code_sizes[table_num]);
MZ_CLEAR_OBJ(d->m_huff_codes[table_num]);
for (i = 1, j = num_used_syms; i <= code_size_limit; i++)
for (l = num_codes[i]; l > 0; l--)
d->m_huff_code_sizes[table_num][pSyms[--j].m_sym_index] = (mz_uint8)(i);
}
next_code[1] = 0;
for (j = 0, i = 2; i <= code_size_limit; i++)
next_code[i] = j = ((j + num_codes[i - 1]) << 1);
for (i = 0; i < table_len; i++) {
mz_uint rev_code = 0, code, code_size;
if ((code_size = d->m_huff_code_sizes[table_num][i]) == 0) continue;
code = next_code[code_size]++;
for (l = code_size; l > 0; l--, code >>= 1)
rev_code = (rev_code << 1) | (code & 1);
d->m_huff_codes[table_num][i] = (mz_uint16)rev_code;
}
}
#define TDEFL_PUT_BITS(b, l) \
do { \
mz_uint bits = b; \
mz_uint len = l; \
MZ_ASSERT(bits <= ((1U << len) - 1U)); \
d->m_bit_buffer |= (bits << d->m_bits_in); \
d->m_bits_in += len; \
while (d->m_bits_in >= 8) { \
if (d->m_pOutput_buf < d->m_pOutput_buf_end) \
*d->m_pOutput_buf++ = (mz_uint8)(d->m_bit_buffer); \
d->m_bit_buffer >>= 8; \
d->m_bits_in -= 8; \
} \
} \
MZ_MACRO_END
#define TDEFL_RLE_PREV_CODE_SIZE() \
{ \
if (rle_repeat_count) { \
if (rle_repeat_count < 3) { \
d->m_huff_count[2][prev_code_size] = (mz_uint16)( \
d->m_huff_count[2][prev_code_size] + rle_repeat_count); \
while (rle_repeat_count--) \
packed_code_sizes[num_packed_code_sizes++] = prev_code_size; \
} else { \
d->m_huff_count[2][16] = (mz_uint16)(d->m_huff_count[2][16] + 1); \
packed_code_sizes[num_packed_code_sizes++] = 16; \
packed_code_sizes[num_packed_code_sizes++] = \
(mz_uint8)(rle_repeat_count - 3); \
} \
rle_repeat_count = 0; \
} \
}
#define TDEFL_RLE_ZERO_CODE_SIZE() \
{ \
if (rle_z_count) { \
if (rle_z_count < 3) { \
d->m_huff_count[2][0] = \
(mz_uint16)(d->m_huff_count[2][0] + rle_z_count); \
while (rle_z_count--) packed_code_sizes[num_packed_code_sizes++] = 0; \
} else if (rle_z_count <= 10) { \
d->m_huff_count[2][17] = (mz_uint16)(d->m_huff_count[2][17] + 1); \
packed_code_sizes[num_packed_code_sizes++] = 17; \
packed_code_sizes[num_packed_code_sizes++] = \
(mz_uint8)(rle_z_count - 3); \
} else { \
d->m_huff_count[2][18] = (mz_uint16)(d->m_huff_count[2][18] + 1); \
packed_code_sizes[num_packed_code_sizes++] = 18; \
packed_code_sizes[num_packed_code_sizes++] = \
(mz_uint8)(rle_z_count - 11); \
} \
rle_z_count = 0; \
} \
}
static mz_uint8 s_tdefl_packed_code_size_syms_swizzle[] = {
16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
static void tdefl_start_dynamic_block(tdefl_compressor *d) {
int num_lit_codes, num_dist_codes, num_bit_lengths;
mz_uint i, total_code_sizes_to_pack, num_packed_code_sizes, rle_z_count,
rle_repeat_count, packed_code_sizes_index;
mz_uint8
code_sizes_to_pack[TDEFL_MAX_HUFF_SYMBOLS_0 + TDEFL_MAX_HUFF_SYMBOLS_1],
packed_code_sizes[TDEFL_MAX_HUFF_SYMBOLS_0 + TDEFL_MAX_HUFF_SYMBOLS_1],
prev_code_size = 0xFF;
d->m_huff_count[0][256] = 1;
tdefl_optimize_huffman_table(d, 0, TDEFL_MAX_HUFF_SYMBOLS_0, 15, MZ_FALSE);
tdefl_optimize_huffman_table(d, 1, TDEFL_MAX_HUFF_SYMBOLS_1, 15, MZ_FALSE);
for (num_lit_codes = 286; num_lit_codes > 257; num_lit_codes--)
if (d->m_huff_code_sizes[0][num_lit_codes - 1]) break;
for (num_dist_codes = 30; num_dist_codes > 1; num_dist_codes--)
if (d->m_huff_code_sizes[1][num_dist_codes - 1]) break;
memcpy(code_sizes_to_pack, &d->m_huff_code_sizes[0][0], num_lit_codes);
memcpy(code_sizes_to_pack + num_lit_codes, &d->m_huff_code_sizes[1][0],
num_dist_codes);
total_code_sizes_to_pack = num_lit_codes + num_dist_codes;
num_packed_code_sizes = 0;
rle_z_count = 0;
rle_repeat_count = 0;
memset(&d->m_huff_count[2][0], 0,
sizeof(d->m_huff_count[2][0]) * TDEFL_MAX_HUFF_SYMBOLS_2);
for (i = 0; i < total_code_sizes_to_pack; i++) {
mz_uint8 code_size = code_sizes_to_pack[i];
if (!code_size) {
TDEFL_RLE_PREV_CODE_SIZE();
if (++rle_z_count == 138) {
TDEFL_RLE_ZERO_CODE_SIZE();
}
} else {
TDEFL_RLE_ZERO_CODE_SIZE();
if (code_size != prev_code_size) {
TDEFL_RLE_PREV_CODE_SIZE();
d->m_huff_count[2][code_size] =
(mz_uint16)(d->m_huff_count[2][code_size] + 1);
packed_code_sizes[num_packed_code_sizes++] = code_size;
} else if (++rle_repeat_count == 6) {
TDEFL_RLE_PREV_CODE_SIZE();
}
}
prev_code_size = code_size;
}
if (rle_repeat_count) {
TDEFL_RLE_PREV_CODE_SIZE();
} else {
TDEFL_RLE_ZERO_CODE_SIZE();
}
tdefl_optimize_huffman_table(d, 2, TDEFL_MAX_HUFF_SYMBOLS_2, 7, MZ_FALSE);
TDEFL_PUT_BITS(2, 2);
TDEFL_PUT_BITS(num_lit_codes - 257, 5);
TDEFL_PUT_BITS(num_dist_codes - 1, 5);
for (num_bit_lengths = 18; num_bit_lengths >= 0; num_bit_lengths--)
if (d->m_huff_code_sizes
[2][s_tdefl_packed_code_size_syms_swizzle[num_bit_lengths]])
break;
num_bit_lengths = MZ_MAX(4, (num_bit_lengths + 1));
TDEFL_PUT_BITS(num_bit_lengths - 4, 4);
for (i = 0; (int)i < num_bit_lengths; i++)
TDEFL_PUT_BITS(
d->m_huff_code_sizes[2][s_tdefl_packed_code_size_syms_swizzle[i]], 3);
for (packed_code_sizes_index = 0;
packed_code_sizes_index < num_packed_code_sizes;) {
mz_uint code = packed_code_sizes[packed_code_sizes_index++];
MZ_ASSERT(code < TDEFL_MAX_HUFF_SYMBOLS_2);
TDEFL_PUT_BITS(d->m_huff_codes[2][code], d->m_huff_code_sizes[2][code]);
if (code >= 16)
TDEFL_PUT_BITS(packed_code_sizes[packed_code_sizes_index++],
"\02\03\07"[code - 16]);
}
}
static void tdefl_start_static_block(tdefl_compressor *d) {
mz_uint i;
mz_uint8 *p = &d->m_huff_code_sizes[0][0];
for (i = 0; i <= 143; ++i) *p++ = 8;
for (; i <= 255; ++i) *p++ = 9;
for (; i <= 279; ++i) *p++ = 7;
for (; i <= 287; ++i) *p++ = 8;
memset(d->m_huff_code_sizes[1], 5, 32);
tdefl_optimize_huffman_table(d, 0, 288, 15, MZ_TRUE);
tdefl_optimize_huffman_table(d, 1, 32, 15, MZ_TRUE);
TDEFL_PUT_BITS(1, 2);
}
static const mz_uint mz_bitmasks[17] = {
0x0000, 0x0001, 0x0003, 0x0007, 0x000F, 0x001F, 0x003F, 0x007F, 0x00FF,
0x01FF, 0x03FF, 0x07FF, 0x0FFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF};
#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN && \
MINIZ_HAS_64BIT_REGISTERS
static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d) {
mz_uint flags;
mz_uint8 *pLZ_codes;
mz_uint8 *pOutput_buf = d->m_pOutput_buf;
mz_uint8 *pLZ_code_buf_end = d->m_pLZ_code_buf;
mz_uint64 bit_buffer = d->m_bit_buffer;
mz_uint bits_in = d->m_bits_in;
#define TDEFL_PUT_BITS_FAST(b, l) \
{ \
bit_buffer |= (((mz_uint64)(b)) << bits_in); \
bits_in += (l); \
}
flags = 1;
for (pLZ_codes = d->m_lz_code_buf; pLZ_codes < pLZ_code_buf_end;
flags >>= 1) {
if (flags == 1) flags = *pLZ_codes++ | 0x100;
if (flags & 1) {
mz_uint s0, s1, n0, n1, sym, num_extra_bits;
mz_uint match_len = pLZ_codes[0],
match_dist = *(const mz_uint16 *)(pLZ_codes + 1);
pLZ_codes += 3;
MZ_ASSERT(d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]);
TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][s_tdefl_len_sym[match_len]],
d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]);
TDEFL_PUT_BITS_FAST(match_len & mz_bitmasks[s_tdefl_len_extra[match_len]],
s_tdefl_len_extra[match_len]);
// This sequence coaxes MSVC into using cmov's vs. jmp's.
s0 = s_tdefl_small_dist_sym[match_dist & 511];
n0 = s_tdefl_small_dist_extra[match_dist & 511];
s1 = s_tdefl_large_dist_sym[match_dist >> 8];
n1 = s_tdefl_large_dist_extra[match_dist >> 8];
sym = (match_dist < 512) ? s0 : s1;
num_extra_bits = (match_dist < 512) ? n0 : n1;
MZ_ASSERT(d->m_huff_code_sizes[1][sym]);
TDEFL_PUT_BITS_FAST(d->m_huff_codes[1][sym],
d->m_huff_code_sizes[1][sym]);
TDEFL_PUT_BITS_FAST(match_dist & mz_bitmasks[num_extra_bits],
num_extra_bits);
} else {
mz_uint lit = *pLZ_codes++;
MZ_ASSERT(d->m_huff_code_sizes[0][lit]);
TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit],
d->m_huff_code_sizes[0][lit]);
if (((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end)) {
flags >>= 1;
lit = *pLZ_codes++;
MZ_ASSERT(d->m_huff_code_sizes[0][lit]);
TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit],
d->m_huff_code_sizes[0][lit]);
if (((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end)) {
flags >>= 1;
lit = *pLZ_codes++;
MZ_ASSERT(d->m_huff_code_sizes[0][lit]);
TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit],
d->m_huff_code_sizes[0][lit]);
}
}
}
if (pOutput_buf >= d->m_pOutput_buf_end) return MZ_FALSE;
*(mz_uint64 *)pOutput_buf = bit_buffer;
pOutput_buf += (bits_in >> 3);
bit_buffer >>= (bits_in & ~7);
bits_in &= 7;
}
#undef TDEFL_PUT_BITS_FAST
d->m_pOutput_buf = pOutput_buf;
d->m_bits_in = 0;
d->m_bit_buffer = 0;
while (bits_in) {
mz_uint32 n = MZ_MIN(bits_in, 16);
TDEFL_PUT_BITS((mz_uint)bit_buffer & mz_bitmasks[n], n);
bit_buffer >>= n;
bits_in -= n;
}
TDEFL_PUT_BITS(d->m_huff_codes[0][256], d->m_huff_code_sizes[0][256]);
return (d->m_pOutput_buf < d->m_pOutput_buf_end);
}
#else
static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d) {
mz_uint flags;
mz_uint8 *pLZ_codes;
flags = 1;
for (pLZ_codes = d->m_lz_code_buf; pLZ_codes < d->m_pLZ_code_buf;
flags >>= 1) {
if (flags == 1) flags = *pLZ_codes++ | 0x100;
if (flags & 1) {
mz_uint sym, num_extra_bits;
mz_uint match_len = pLZ_codes[0],
match_dist = (pLZ_codes[1] | (pLZ_codes[2] << 8));
pLZ_codes += 3;
MZ_ASSERT(d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]);
TDEFL_PUT_BITS(d->m_huff_codes[0][s_tdefl_len_sym[match_len]],
d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]);
TDEFL_PUT_BITS(match_len & mz_bitmasks[s_tdefl_len_extra[match_len]],
s_tdefl_len_extra[match_len]);
if (match_dist < 512) {
sym = s_tdefl_small_dist_sym[match_dist];
num_extra_bits = s_tdefl_small_dist_extra[match_dist];
} else {
sym = s_tdefl_large_dist_sym[match_dist >> 8];
num_extra_bits = s_tdefl_large_dist_extra[match_dist >> 8];
}
MZ_ASSERT(d->m_huff_code_sizes[1][sym]);
TDEFL_PUT_BITS(d->m_huff_codes[1][sym], d->m_huff_code_sizes[1][sym]);
TDEFL_PUT_BITS(match_dist & mz_bitmasks[num_extra_bits], num_extra_bits);
} else {
mz_uint lit = *pLZ_codes++;
MZ_ASSERT(d->m_huff_code_sizes[0][lit]);
TDEFL_PUT_BITS(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]);
}
}
TDEFL_PUT_BITS(d->m_huff_codes[0][256], d->m_huff_code_sizes[0][256]);
return (d->m_pOutput_buf < d->m_pOutput_buf_end);
}
#endif // MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN &&
// MINIZ_HAS_64BIT_REGISTERS
static mz_bool tdefl_compress_block(tdefl_compressor *d, mz_bool static_block) {
if (static_block)
tdefl_start_static_block(d);
else
tdefl_start_dynamic_block(d);
return tdefl_compress_lz_codes(d);
}
static int tdefl_flush_block(tdefl_compressor *d, int flush) {
mz_uint saved_bit_buf, saved_bits_in;
mz_uint8 *pSaved_output_buf;
mz_bool comp_block_succeeded = MZ_FALSE;
int n, use_raw_block =
((d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS) != 0) &&
(d->m_lookahead_pos - d->m_lz_code_buf_dict_pos) <= d->m_dict_size;
mz_uint8 *pOutput_buf_start =
((d->m_pPut_buf_func == NULL) &&
((*d->m_pOut_buf_size - d->m_out_buf_ofs) >= TDEFL_OUT_BUF_SIZE))
? ((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs)
: d->m_output_buf;
d->m_pOutput_buf = pOutput_buf_start;
d->m_pOutput_buf_end = d->m_pOutput_buf + TDEFL_OUT_BUF_SIZE - 16;
MZ_ASSERT(!d->m_output_flush_remaining);
d->m_output_flush_ofs = 0;
d->m_output_flush_remaining = 0;
*d->m_pLZ_flags = (mz_uint8)(*d->m_pLZ_flags >> d->m_num_flags_left);
d->m_pLZ_code_buf -= (d->m_num_flags_left == 8);
if ((d->m_flags & TDEFL_WRITE_ZLIB_HEADER) && (!d->m_block_index)) {
TDEFL_PUT_BITS(0x78, 8);
TDEFL_PUT_BITS(0x01, 8);
}
TDEFL_PUT_BITS(flush == TDEFL_FINISH, 1);
pSaved_output_buf = d->m_pOutput_buf;
saved_bit_buf = d->m_bit_buffer;
saved_bits_in = d->m_bits_in;
if (!use_raw_block)
comp_block_succeeded =
tdefl_compress_block(d, (d->m_flags & TDEFL_FORCE_ALL_STATIC_BLOCKS) ||
(d->m_total_lz_bytes < 48));
// If the block gets expanded, forget the current contents of the output
// buffer and send a raw block instead.
if (((use_raw_block) ||
((d->m_total_lz_bytes) && ((d->m_pOutput_buf - pSaved_output_buf + 1U) >=
d->m_total_lz_bytes))) &&
((d->m_lookahead_pos - d->m_lz_code_buf_dict_pos) <= d->m_dict_size)) {
mz_uint i;
d->m_pOutput_buf = pSaved_output_buf;
d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in;
TDEFL_PUT_BITS(0, 2);
if (d->m_bits_in) {
TDEFL_PUT_BITS(0, 8 - d->m_bits_in);
}
for (i = 2; i; --i, d->m_total_lz_bytes ^= 0xFFFF) {
TDEFL_PUT_BITS(d->m_total_lz_bytes & 0xFFFF, 16);
}
for (i = 0; i < d->m_total_lz_bytes; ++i) {
TDEFL_PUT_BITS(
d->m_dict[(d->m_lz_code_buf_dict_pos + i) & TDEFL_LZ_DICT_SIZE_MASK],
8);
}
}
// Check for the extremely unlikely (if not impossible) case of the compressed
// block not fitting into the output buffer when using dynamic codes.
else if (!comp_block_succeeded) {
d->m_pOutput_buf = pSaved_output_buf;
d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in;
tdefl_compress_block(d, MZ_TRUE);
}
if (flush) {
if (flush == TDEFL_FINISH) {
if (d->m_bits_in) {
TDEFL_PUT_BITS(0, 8 - d->m_bits_in);
}
if (d->m_flags & TDEFL_WRITE_ZLIB_HEADER) {
mz_uint i, a = d->m_adler32;
for (i = 0; i < 4; i++) {
TDEFL_PUT_BITS((a >> 24) & 0xFF, 8);
a <<= 8;
}
}
} else {
mz_uint i, z = 0;
TDEFL_PUT_BITS(0, 3);
if (d->m_bits_in) {
TDEFL_PUT_BITS(0, 8 - d->m_bits_in);
}
for (i = 2; i; --i, z ^= 0xFFFF) {
TDEFL_PUT_BITS(z & 0xFFFF, 16);
}
}
}
MZ_ASSERT(d->m_pOutput_buf < d->m_pOutput_buf_end);
memset(&d->m_huff_count[0][0], 0,
sizeof(d->m_huff_count[0][0]) * TDEFL_MAX_HUFF_SYMBOLS_0);
memset(&d->m_huff_count[1][0], 0,
sizeof(d->m_huff_count[1][0]) * TDEFL_MAX_HUFF_SYMBOLS_1);
d->m_pLZ_code_buf = d->m_lz_code_buf + 1;
d->m_pLZ_flags = d->m_lz_code_buf;
d->m_num_flags_left = 8;
d->m_lz_code_buf_dict_pos += d->m_total_lz_bytes;
d->m_total_lz_bytes = 0;
d->m_block_index++;
if ((n = (int)(d->m_pOutput_buf - pOutput_buf_start)) != 0) {
if (d->m_pPut_buf_func) {
*d->m_pIn_buf_size = d->m_pSrc - (const mz_uint8 *)d->m_pIn_buf;
if (!(*d->m_pPut_buf_func)(d->m_output_buf, n, d->m_pPut_buf_user))
return (d->m_prev_return_status = TDEFL_STATUS_PUT_BUF_FAILED);
} else if (pOutput_buf_start == d->m_output_buf) {
int bytes_to_copy = (int)MZ_MIN(
(size_t)n, (size_t)(*d->m_pOut_buf_size - d->m_out_buf_ofs));
memcpy((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs, d->m_output_buf,
bytes_to_copy);
d->m_out_buf_ofs += bytes_to_copy;
if ((n -= bytes_to_copy) != 0) {
d->m_output_flush_ofs = bytes_to_copy;
d->m_output_flush_remaining = n;
}
} else {
d->m_out_buf_ofs += n;
}
}
return d->m_output_flush_remaining;
}
#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES
#define TDEFL_READ_UNALIGNED_WORD(p) *(const mz_uint16 *)(p)
static MZ_FORCEINLINE void tdefl_find_match(
tdefl_compressor *d, mz_uint lookahead_pos, mz_uint max_dist,
mz_uint max_match_len, mz_uint *pMatch_dist, mz_uint *pMatch_len) {
mz_uint dist, pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK,
match_len = *pMatch_len, probe_pos = pos, next_probe_pos,
probe_len;
mz_uint num_probes_left = d->m_max_probes[match_len >= 32];
const mz_uint16 *s = (const mz_uint16 *)(d->m_dict + pos), *p, *q;
mz_uint16 c01 = TDEFL_READ_UNALIGNED_WORD(&d->m_dict[pos + match_len - 1]),
s01 = TDEFL_READ_UNALIGNED_WORD(s);
MZ_ASSERT(max_match_len <= TDEFL_MAX_MATCH_LEN);
if (max_match_len <= match_len) return;
for (;;) {
for (;;) {
if (--num_probes_left == 0) return;
#define TDEFL_PROBE \
next_probe_pos = d->m_next[probe_pos]; \
if ((!next_probe_pos) || \
((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) \
return; \
probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \
if (TDEFL_READ_UNALIGNED_WORD(&d->m_dict[probe_pos + match_len - 1]) == c01) \
break;
TDEFL_PROBE;
TDEFL_PROBE;
TDEFL_PROBE;
}
if (!dist) break;
q = (const mz_uint16 *)(d->m_dict + probe_pos);
if (TDEFL_READ_UNALIGNED_WORD(q) != s01) continue;
p = s;
probe_len = 32;
do {
} while (
(TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) &&
(TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) &&
(TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) &&
(TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) &&
(--probe_len > 0));
if (!probe_len) {
*pMatch_dist = dist;
*pMatch_len = MZ_MIN(max_match_len, TDEFL_MAX_MATCH_LEN);
break;
} else if ((probe_len = ((mz_uint)(p - s) * 2) +
(mz_uint)(*(const mz_uint8 *)p ==
*(const mz_uint8 *)q)) > match_len) {
*pMatch_dist = dist;
if ((*pMatch_len = match_len = MZ_MIN(max_match_len, probe_len)) ==
max_match_len)
break;
c01 = TDEFL_READ_UNALIGNED_WORD(&d->m_dict[pos + match_len - 1]);
}
}
}
#else
static MZ_FORCEINLINE void tdefl_find_match(
tdefl_compressor *d, mz_uint lookahead_pos, mz_uint max_dist,
mz_uint max_match_len, mz_uint *pMatch_dist, mz_uint *pMatch_len) {
mz_uint dist, pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK,
match_len = *pMatch_len, probe_pos = pos, next_probe_pos,
probe_len;
mz_uint num_probes_left = d->m_max_probes[match_len >= 32];
const mz_uint8 *s = d->m_dict + pos, *p, *q;
mz_uint8 c0 = d->m_dict[pos + match_len], c1 = d->m_dict[pos + match_len - 1];
MZ_ASSERT(max_match_len <= TDEFL_MAX_MATCH_LEN);
if (max_match_len <= match_len) return;
for (;;) {
for (;;) {
if (--num_probes_left == 0) return;
#define TDEFL_PROBE \
next_probe_pos = d->m_next[probe_pos]; \
if ((!next_probe_pos) || \
((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) \
return; \
probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \
if ((d->m_dict[probe_pos + match_len] == c0) && \
(d->m_dict[probe_pos + match_len - 1] == c1)) \
break;
TDEFL_PROBE;
TDEFL_PROBE;
TDEFL_PROBE;
}
if (!dist) break;
p = s;
q = d->m_dict + probe_pos;
for (probe_len = 0; probe_len < max_match_len; probe_len++)
if (*p++ != *q++) break;
if (probe_len > match_len) {
*pMatch_dist = dist;
if ((*pMatch_len = match_len = probe_len) == max_match_len) return;
c0 = d->m_dict[pos + match_len];
c1 = d->m_dict[pos + match_len - 1];
}
}
}
#endif // #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES
#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN
static mz_bool tdefl_compress_fast(tdefl_compressor *d) {
// Faster, minimally featured LZRW1-style match+parse loop with better
// register utilization. Intended for applications where raw throughput is
// valued more highly than ratio.
mz_uint lookahead_pos = d->m_lookahead_pos,
lookahead_size = d->m_lookahead_size, dict_size = d->m_dict_size,
total_lz_bytes = d->m_total_lz_bytes,
num_flags_left = d->m_num_flags_left;
mz_uint8 *pLZ_code_buf = d->m_pLZ_code_buf, *pLZ_flags = d->m_pLZ_flags;
mz_uint cur_pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK;
while ((d->m_src_buf_left) || ((d->m_flush) && (lookahead_size))) {
const mz_uint TDEFL_COMP_FAST_LOOKAHEAD_SIZE = 4096;
mz_uint dst_pos =
(lookahead_pos + lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK;
mz_uint num_bytes_to_process = (mz_uint)MZ_MIN(
d->m_src_buf_left, TDEFL_COMP_FAST_LOOKAHEAD_SIZE - lookahead_size);
d->m_src_buf_left -= num_bytes_to_process;
lookahead_size += num_bytes_to_process;
while (num_bytes_to_process) {
mz_uint32 n = MZ_MIN(TDEFL_LZ_DICT_SIZE - dst_pos, num_bytes_to_process);
memcpy(d->m_dict + dst_pos, d->m_pSrc, n);
if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1))
memcpy(d->m_dict + TDEFL_LZ_DICT_SIZE + dst_pos, d->m_pSrc,
MZ_MIN(n, (TDEFL_MAX_MATCH_LEN - 1) - dst_pos));
d->m_pSrc += n;
dst_pos = (dst_pos + n) & TDEFL_LZ_DICT_SIZE_MASK;
num_bytes_to_process -= n;
}
dict_size = MZ_MIN(TDEFL_LZ_DICT_SIZE - lookahead_size, dict_size);
if ((!d->m_flush) && (lookahead_size < TDEFL_COMP_FAST_LOOKAHEAD_SIZE))
break;
while (lookahead_size >= 4) {
mz_uint cur_match_dist, cur_match_len = 1;
mz_uint8 *pCur_dict = d->m_dict + cur_pos;
mz_uint first_trigram = (*(const mz_uint32 *)pCur_dict) & 0xFFFFFF;
mz_uint hash =
(first_trigram ^ (first_trigram >> (24 - (TDEFL_LZ_HASH_BITS - 8)))) &
TDEFL_LEVEL1_HASH_SIZE_MASK;
mz_uint probe_pos = d->m_hash[hash];
d->m_hash[hash] = (mz_uint16)lookahead_pos;
if (((cur_match_dist = (mz_uint16)(lookahead_pos - probe_pos)) <=
dict_size) &&
((*(const mz_uint32 *)(d->m_dict +
(probe_pos &= TDEFL_LZ_DICT_SIZE_MASK)) &
0xFFFFFF) == first_trigram)) {
const mz_uint16 *p = (const mz_uint16 *)pCur_dict;
const mz_uint16 *q = (const mz_uint16 *)(d->m_dict + probe_pos);
mz_uint32 probe_len = 32;
do {
} while ((TDEFL_READ_UNALIGNED_WORD(++p) ==
TDEFL_READ_UNALIGNED_WORD(++q)) &&
(TDEFL_READ_UNALIGNED_WORD(++p) ==
TDEFL_READ_UNALIGNED_WORD(++q)) &&
(TDEFL_READ_UNALIGNED_WORD(++p) ==
TDEFL_READ_UNALIGNED_WORD(++q)) &&
(TDEFL_READ_UNALIGNED_WORD(++p) ==
TDEFL_READ_UNALIGNED_WORD(++q)) &&
(--probe_len > 0));
cur_match_len = ((mz_uint)(p - (const mz_uint16 *)pCur_dict) * 2) +
(mz_uint)(*(const mz_uint8 *)p == *(const mz_uint8 *)q);
if (!probe_len)
cur_match_len = cur_match_dist ? TDEFL_MAX_MATCH_LEN : 0;
if ((cur_match_len < TDEFL_MIN_MATCH_LEN) ||
((cur_match_len == TDEFL_MIN_MATCH_LEN) &&
(cur_match_dist >= 8U * 1024U))) {
cur_match_len = 1;
*pLZ_code_buf++ = (mz_uint8)first_trigram;
*pLZ_flags = (mz_uint8)(*pLZ_flags >> 1);
d->m_huff_count[0][(mz_uint8)first_trigram]++;
} else {
mz_uint32 s0, s1;
cur_match_len = MZ_MIN(cur_match_len, lookahead_size);
MZ_ASSERT((cur_match_len >= TDEFL_MIN_MATCH_LEN) &&
(cur_match_dist >= 1) &&
(cur_match_dist <= TDEFL_LZ_DICT_SIZE));
cur_match_dist--;
pLZ_code_buf[0] = (mz_uint8)(cur_match_len - TDEFL_MIN_MATCH_LEN);
*(mz_uint16 *)(&pLZ_code_buf[1]) = (mz_uint16)cur_match_dist;
pLZ_code_buf += 3;
*pLZ_flags = (mz_uint8)((*pLZ_flags >> 1) | 0x80);
s0 = s_tdefl_small_dist_sym[cur_match_dist & 511];
s1 = s_tdefl_large_dist_sym[cur_match_dist >> 8];
d->m_huff_count[1][(cur_match_dist < 512) ? s0 : s1]++;
d->m_huff_count[0][s_tdefl_len_sym[cur_match_len -
TDEFL_MIN_MATCH_LEN]]++;
}
} else {
*pLZ_code_buf++ = (mz_uint8)first_trigram;
*pLZ_flags = (mz_uint8)(*pLZ_flags >> 1);
d->m_huff_count[0][(mz_uint8)first_trigram]++;
}
if (--num_flags_left == 0) {
num_flags_left = 8;
pLZ_flags = pLZ_code_buf++;
}
total_lz_bytes += cur_match_len;
lookahead_pos += cur_match_len;
dict_size = MZ_MIN(dict_size + cur_match_len, TDEFL_LZ_DICT_SIZE);
cur_pos = (cur_pos + cur_match_len) & TDEFL_LZ_DICT_SIZE_MASK;
MZ_ASSERT(lookahead_size >= cur_match_len);
lookahead_size -= cur_match_len;
if (pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) {
int n;
d->m_lookahead_pos = lookahead_pos;
d->m_lookahead_size = lookahead_size;
d->m_dict_size = dict_size;
d->m_total_lz_bytes = total_lz_bytes;
d->m_pLZ_code_buf = pLZ_code_buf;
d->m_pLZ_flags = pLZ_flags;
d->m_num_flags_left = num_flags_left;
if ((n = tdefl_flush_block(d, 0)) != 0)
return (n < 0) ? MZ_FALSE : MZ_TRUE;
total_lz_bytes = d->m_total_lz_bytes;
pLZ_code_buf = d->m_pLZ_code_buf;
pLZ_flags = d->m_pLZ_flags;
num_flags_left = d->m_num_flags_left;
}
}
while (lookahead_size) {
mz_uint8 lit = d->m_dict[cur_pos];
total_lz_bytes++;
*pLZ_code_buf++ = lit;
*pLZ_flags = (mz_uint8)(*pLZ_flags >> 1);
if (--num_flags_left == 0) {
num_flags_left = 8;
pLZ_flags = pLZ_code_buf++;
}
d->m_huff_count[0][lit]++;
lookahead_pos++;
dict_size = MZ_MIN(dict_size + 1, TDEFL_LZ_DICT_SIZE);
cur_pos = (cur_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK;
lookahead_size--;
if (pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) {
int n;
d->m_lookahead_pos = lookahead_pos;
d->m_lookahead_size = lookahead_size;
d->m_dict_size = dict_size;
d->m_total_lz_bytes = total_lz_bytes;
d->m_pLZ_code_buf = pLZ_code_buf;
d->m_pLZ_flags = pLZ_flags;
d->m_num_flags_left = num_flags_left;
if ((n = tdefl_flush_block(d, 0)) != 0)
return (n < 0) ? MZ_FALSE : MZ_TRUE;
total_lz_bytes = d->m_total_lz_bytes;
pLZ_code_buf = d->m_pLZ_code_buf;
pLZ_flags = d->m_pLZ_flags;
num_flags_left = d->m_num_flags_left;
}
}
}
d->m_lookahead_pos = lookahead_pos;
d->m_lookahead_size = lookahead_size;
d->m_dict_size = dict_size;
d->m_total_lz_bytes = total_lz_bytes;
d->m_pLZ_code_buf = pLZ_code_buf;
d->m_pLZ_flags = pLZ_flags;
d->m_num_flags_left = num_flags_left;
return MZ_TRUE;
}
#endif // MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN
static MZ_FORCEINLINE void tdefl_record_literal(tdefl_compressor *d,
mz_uint8 lit) {
d->m_total_lz_bytes++;
*d->m_pLZ_code_buf++ = lit;
*d->m_pLZ_flags = (mz_uint8)(*d->m_pLZ_flags >> 1);
if (--d->m_num_flags_left == 0) {
d->m_num_flags_left = 8;
d->m_pLZ_flags = d->m_pLZ_code_buf++;
}
d->m_huff_count[0][lit]++;
}
static MZ_FORCEINLINE void tdefl_record_match(tdefl_compressor *d,
mz_uint match_len,
mz_uint match_dist) {
mz_uint32 s0, s1;
MZ_ASSERT((match_len >= TDEFL_MIN_MATCH_LEN) && (match_dist >= 1) &&
(match_dist <= TDEFL_LZ_DICT_SIZE));
d->m_total_lz_bytes += match_len;
d->m_pLZ_code_buf[0] = (mz_uint8)(match_len - TDEFL_MIN_MATCH_LEN);
match_dist -= 1;
d->m_pLZ_code_buf[1] = (mz_uint8)(match_dist & 0xFF);
d->m_pLZ_code_buf[2] = (mz_uint8)(match_dist >> 8);
d->m_pLZ_code_buf += 3;
*d->m_pLZ_flags = (mz_uint8)((*d->m_pLZ_flags >> 1) | 0x80);
if (--d->m_num_flags_left == 0) {
d->m_num_flags_left = 8;
d->m_pLZ_flags = d->m_pLZ_code_buf++;
}
s0 = s_tdefl_small_dist_sym[match_dist & 511];
s1 = s_tdefl_large_dist_sym[(match_dist >> 8) & 127];
d->m_huff_count[1][(match_dist < 512) ? s0 : s1]++;
if (match_len >= TDEFL_MIN_MATCH_LEN)
d->m_huff_count[0][s_tdefl_len_sym[match_len - TDEFL_MIN_MATCH_LEN]]++;
}
static mz_bool tdefl_compress_normal(tdefl_compressor *d) {
const mz_uint8 *pSrc = d->m_pSrc;
size_t src_buf_left = d->m_src_buf_left;
tdefl_flush flush = d->m_flush;
while ((src_buf_left) || ((flush) && (d->m_lookahead_size))) {
mz_uint len_to_move, cur_match_dist, cur_match_len, cur_pos;
// Update dictionary and hash chains. Keeps the lookahead size equal to
// TDEFL_MAX_MATCH_LEN.
if ((d->m_lookahead_size + d->m_dict_size) >= (TDEFL_MIN_MATCH_LEN - 1)) {
mz_uint dst_pos = (d->m_lookahead_pos + d->m_lookahead_size) &
TDEFL_LZ_DICT_SIZE_MASK,
ins_pos = d->m_lookahead_pos + d->m_lookahead_size - 2;
mz_uint hash = (d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK]
<< TDEFL_LZ_HASH_SHIFT) ^
d->m_dict[(ins_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK];
mz_uint num_bytes_to_process = (mz_uint)MZ_MIN(
src_buf_left, TDEFL_MAX_MATCH_LEN - d->m_lookahead_size);
const mz_uint8 *pSrc_end = pSrc + num_bytes_to_process;
src_buf_left -= num_bytes_to_process;
d->m_lookahead_size += num_bytes_to_process;
while (pSrc != pSrc_end) {
mz_uint8 c = *pSrc++;
d->m_dict[dst_pos] = c;
if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1))
d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c;
hash = ((hash << TDEFL_LZ_HASH_SHIFT) ^ c) & (TDEFL_LZ_HASH_SIZE - 1);
d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = d->m_hash[hash];
d->m_hash[hash] = (mz_uint16)(ins_pos);
dst_pos = (dst_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK;
ins_pos++;
}
} else {
while ((src_buf_left) && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN)) {
mz_uint8 c = *pSrc++;
mz_uint dst_pos = (d->m_lookahead_pos + d->m_lookahead_size) &
TDEFL_LZ_DICT_SIZE_MASK;
src_buf_left--;
d->m_dict[dst_pos] = c;
if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1))
d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c;
if ((++d->m_lookahead_size + d->m_dict_size) >= TDEFL_MIN_MATCH_LEN) {
mz_uint ins_pos = d->m_lookahead_pos + (d->m_lookahead_size - 1) - 2;
mz_uint hash = ((d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK]
<< (TDEFL_LZ_HASH_SHIFT * 2)) ^
(d->m_dict[(ins_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK]
<< TDEFL_LZ_HASH_SHIFT) ^
c) &
(TDEFL_LZ_HASH_SIZE - 1);
d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = d->m_hash[hash];
d->m_hash[hash] = (mz_uint16)(ins_pos);
}
}
}
d->m_dict_size =
MZ_MIN(TDEFL_LZ_DICT_SIZE - d->m_lookahead_size, d->m_dict_size);
if ((!flush) && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN)) break;
// Simple lazy/greedy parsing state machine.
len_to_move = 1;
cur_match_dist = 0;
cur_match_len =
d->m_saved_match_len ? d->m_saved_match_len : (TDEFL_MIN_MATCH_LEN - 1);
cur_pos = d->m_lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK;
if (d->m_flags & (TDEFL_RLE_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS)) {
if ((d->m_dict_size) && (!(d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS))) {
mz_uint8 c = d->m_dict[(cur_pos - 1) & TDEFL_LZ_DICT_SIZE_MASK];
cur_match_len = 0;
while (cur_match_len < d->m_lookahead_size) {
if (d->m_dict[cur_pos + cur_match_len] != c) break;
cur_match_len++;
}
if (cur_match_len < TDEFL_MIN_MATCH_LEN)
cur_match_len = 0;
else
cur_match_dist = 1;
}
} else {
tdefl_find_match(d, d->m_lookahead_pos, d->m_dict_size,
d->m_lookahead_size, &cur_match_dist, &cur_match_len);
}
if (((cur_match_len == TDEFL_MIN_MATCH_LEN) &&
(cur_match_dist >= 8U * 1024U)) ||
(cur_pos == cur_match_dist) ||
((d->m_flags & TDEFL_FILTER_MATCHES) && (cur_match_len <= 5))) {
cur_match_dist = cur_match_len = 0;
}
if (d->m_saved_match_len) {
if (cur_match_len > d->m_saved_match_len) {
tdefl_record_literal(d, (mz_uint8)d->m_saved_lit);
if (cur_match_len >= 128) {
tdefl_record_match(d, cur_match_len, cur_match_dist);
d->m_saved_match_len = 0;
len_to_move = cur_match_len;
} else {
d->m_saved_lit = d->m_dict[cur_pos];
d->m_saved_match_dist = cur_match_dist;
d->m_saved_match_len = cur_match_len;
}
} else {
tdefl_record_match(d, d->m_saved_match_len, d->m_saved_match_dist);
len_to_move = d->m_saved_match_len - 1;
d->m_saved_match_len = 0;
}
} else if (!cur_match_dist)
tdefl_record_literal(d,
d->m_dict[MZ_MIN(cur_pos, sizeof(d->m_dict) - 1)]);
else if ((d->m_greedy_parsing) || (d->m_flags & TDEFL_RLE_MATCHES) ||
(cur_match_len >= 128)) {
tdefl_record_match(d, cur_match_len, cur_match_dist);
len_to_move = cur_match_len;
} else {
d->m_saved_lit = d->m_dict[MZ_MIN(cur_pos, sizeof(d->m_dict) - 1)];
d->m_saved_match_dist = cur_match_dist;
d->m_saved_match_len = cur_match_len;
}
// Move the lookahead forward by len_to_move bytes.
d->m_lookahead_pos += len_to_move;
MZ_ASSERT(d->m_lookahead_size >= len_to_move);
d->m_lookahead_size -= len_to_move;
d->m_dict_size =
MZ_MIN(d->m_dict_size + len_to_move, (mz_uint)TDEFL_LZ_DICT_SIZE);
// Check if it's time to flush the current LZ codes to the internal output
// buffer.
if ((d->m_pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) ||
((d->m_total_lz_bytes > 31 * 1024) &&
(((((mz_uint)(d->m_pLZ_code_buf - d->m_lz_code_buf) * 115) >> 7) >=
d->m_total_lz_bytes) ||
(d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS)))) {
int n;
d->m_pSrc = pSrc;
d->m_src_buf_left = src_buf_left;
if ((n = tdefl_flush_block(d, 0)) != 0)
return (n < 0) ? MZ_FALSE : MZ_TRUE;
}
}
d->m_pSrc = pSrc;
d->m_src_buf_left = src_buf_left;
return MZ_TRUE;
}
static tdefl_status tdefl_flush_output_buffer(tdefl_compressor *d) {
if (d->m_pIn_buf_size) {
*d->m_pIn_buf_size = d->m_pSrc - (const mz_uint8 *)d->m_pIn_buf;
}
if (d->m_pOut_buf_size) {
size_t n = MZ_MIN(*d->m_pOut_buf_size - d->m_out_buf_ofs,
d->m_output_flush_remaining);
memcpy((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs,
d->m_output_buf + d->m_output_flush_ofs, n);
d->m_output_flush_ofs += (mz_uint)n;
d->m_output_flush_remaining -= (mz_uint)n;
d->m_out_buf_ofs += n;
*d->m_pOut_buf_size = d->m_out_buf_ofs;
}
return (d->m_finished && !d->m_output_flush_remaining) ? TDEFL_STATUS_DONE
: TDEFL_STATUS_OKAY;
}
tdefl_status tdefl_compress(tdefl_compressor *d, const void *pIn_buf,
size_t *pIn_buf_size, void *pOut_buf,
size_t *pOut_buf_size, tdefl_flush flush) {
if (!d) {
if (pIn_buf_size) *pIn_buf_size = 0;
if (pOut_buf_size) *pOut_buf_size = 0;
return TDEFL_STATUS_BAD_PARAM;
}
d->m_pIn_buf = pIn_buf;
d->m_pIn_buf_size = pIn_buf_size;
d->m_pOut_buf = pOut_buf;
d->m_pOut_buf_size = pOut_buf_size;
d->m_pSrc = (const mz_uint8 *)(pIn_buf);
d->m_src_buf_left = pIn_buf_size ? *pIn_buf_size : 0;
d->m_out_buf_ofs = 0;
d->m_flush = flush;
if (((d->m_pPut_buf_func != NULL) ==
((pOut_buf != NULL) || (pOut_buf_size != NULL))) ||
(d->m_prev_return_status != TDEFL_STATUS_OKAY) ||
(d->m_wants_to_finish && (flush != TDEFL_FINISH)) ||
(pIn_buf_size && *pIn_buf_size && !pIn_buf) ||
(pOut_buf_size && *pOut_buf_size && !pOut_buf)) {
if (pIn_buf_size) *pIn_buf_size = 0;
if (pOut_buf_size) *pOut_buf_size = 0;
return (d->m_prev_return_status = TDEFL_STATUS_BAD_PARAM);
}
d->m_wants_to_finish |= (flush == TDEFL_FINISH);
if ((d->m_output_flush_remaining) || (d->m_finished))
return (d->m_prev_return_status = tdefl_flush_output_buffer(d));
#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN
if (((d->m_flags & TDEFL_MAX_PROBES_MASK) == 1) &&
((d->m_flags & TDEFL_GREEDY_PARSING_FLAG) != 0) &&
((d->m_flags & (TDEFL_FILTER_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS |
TDEFL_RLE_MATCHES)) == 0)) {
if (!tdefl_compress_fast(d)) return d->m_prev_return_status;
} else
#endif // #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN
{
if (!tdefl_compress_normal(d)) return d->m_prev_return_status;
}
if ((d->m_flags & (TDEFL_WRITE_ZLIB_HEADER | TDEFL_COMPUTE_ADLER32)) &&
(pIn_buf))
d->m_adler32 =
(mz_uint32)mz_adler32(d->m_adler32, (const mz_uint8 *)pIn_buf,
d->m_pSrc - (const mz_uint8 *)pIn_buf);
if ((flush) && (!d->m_lookahead_size) && (!d->m_src_buf_left) &&
(!d->m_output_flush_remaining)) {
if (tdefl_flush_block(d, flush) < 0) return d->m_prev_return_status;
d->m_finished = (flush == TDEFL_FINISH);
if (flush == TDEFL_FULL_FLUSH) {
MZ_CLEAR_OBJ(d->m_hash);
MZ_CLEAR_OBJ(d->m_next);
d->m_dict_size = 0;
}
}
return (d->m_prev_return_status = tdefl_flush_output_buffer(d));
}
tdefl_status tdefl_compress_buffer(tdefl_compressor *d, const void *pIn_buf,
size_t in_buf_size, tdefl_flush flush) {
MZ_ASSERT(d->m_pPut_buf_func);
return tdefl_compress(d, pIn_buf, &in_buf_size, NULL, NULL, flush);
}
tdefl_status tdefl_init(tdefl_compressor *d,
tdefl_put_buf_func_ptr pPut_buf_func,
void *pPut_buf_user, int flags) {
d->m_pPut_buf_func = pPut_buf_func;
d->m_pPut_buf_user = pPut_buf_user;
d->m_flags = (mz_uint)(flags);
d->m_max_probes[0] = 1 + ((flags & 0xFFF) + 2) / 3;
d->m_greedy_parsing = (flags & TDEFL_GREEDY_PARSING_FLAG) != 0;
d->m_max_probes[1] = 1 + (((flags & 0xFFF) >> 2) + 2) / 3;
if (!(flags & TDEFL_NONDETERMINISTIC_PARSING_FLAG)) MZ_CLEAR_OBJ(d->m_hash);
d->m_lookahead_pos = d->m_lookahead_size = d->m_dict_size =
d->m_total_lz_bytes = d->m_lz_code_buf_dict_pos = d->m_bits_in = 0;
d->m_output_flush_ofs = d->m_output_flush_remaining = d->m_finished =
d->m_block_index = d->m_bit_buffer = d->m_wants_to_finish = 0;
d->m_pLZ_code_buf = d->m_lz_code_buf + 1;
d->m_pLZ_flags = d->m_lz_code_buf;
d->m_num_flags_left = 8;
d->m_pOutput_buf = d->m_output_buf;
d->m_pOutput_buf_end = d->m_output_buf;
d->m_prev_return_status = TDEFL_STATUS_OKAY;
d->m_saved_match_dist = d->m_saved_match_len = d->m_saved_lit = 0;
d->m_adler32 = 1;
d->m_pIn_buf = NULL;
d->m_pOut_buf = NULL;
d->m_pIn_buf_size = NULL;
d->m_pOut_buf_size = NULL;
d->m_flush = TDEFL_NO_FLUSH;
d->m_pSrc = NULL;
d->m_src_buf_left = 0;
d->m_out_buf_ofs = 0;
memset(&d->m_huff_count[0][0], 0,
sizeof(d->m_huff_count[0][0]) * TDEFL_MAX_HUFF_SYMBOLS_0);
memset(&d->m_huff_count[1][0], 0,
sizeof(d->m_huff_count[1][0]) * TDEFL_MAX_HUFF_SYMBOLS_1);
return TDEFL_STATUS_OKAY;
}
tdefl_status tdefl_get_prev_return_status(tdefl_compressor *d) {
return d->m_prev_return_status;
}
mz_uint32 tdefl_get_adler32(tdefl_compressor *d) { return d->m_adler32; }
mz_bool tdefl_compress_mem_to_output(const void *pBuf, size_t buf_len,
tdefl_put_buf_func_ptr pPut_buf_func,
void *pPut_buf_user, int flags) {
tdefl_compressor *pComp;
mz_bool succeeded;
if (((buf_len) && (!pBuf)) || (!pPut_buf_func)) return MZ_FALSE;
pComp = (tdefl_compressor *)MZ_MALLOC(sizeof(tdefl_compressor));
if (!pComp) return MZ_FALSE;
succeeded = (tdefl_init(pComp, pPut_buf_func, pPut_buf_user, flags) ==
TDEFL_STATUS_OKAY);
succeeded =
succeeded && (tdefl_compress_buffer(pComp, pBuf, buf_len, TDEFL_FINISH) ==
TDEFL_STATUS_DONE);
MZ_FREE(pComp);
return succeeded;
}
typedef struct {
size_t m_size, m_capacity;
mz_uint8 *m_pBuf;
mz_bool m_expandable;
} tdefl_output_buffer;
static mz_bool tdefl_output_buffer_putter(const void *pBuf, int len,
void *pUser) {
tdefl_output_buffer *p = (tdefl_output_buffer *)pUser;
size_t new_size = p->m_size + len;
if (new_size > p->m_capacity) {
size_t new_capacity = p->m_capacity;
mz_uint8 *pNew_buf;
if (!p->m_expandable) return MZ_FALSE;
do {
new_capacity = MZ_MAX(128U, new_capacity << 1U);
} while (new_size > new_capacity);
pNew_buf = (mz_uint8 *)MZ_REALLOC(p->m_pBuf, new_capacity);
if (!pNew_buf) return MZ_FALSE;
p->m_pBuf = pNew_buf;
p->m_capacity = new_capacity;
}
memcpy((mz_uint8 *)p->m_pBuf + p->m_size, pBuf, len);
p->m_size = new_size;
return MZ_TRUE;
}
void *tdefl_compress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len,
size_t *pOut_len, int flags) {
tdefl_output_buffer out_buf;
MZ_CLEAR_OBJ(out_buf);
if (!pOut_len)
return MZ_FALSE;
else
*pOut_len = 0;
out_buf.m_expandable = MZ_TRUE;
if (!tdefl_compress_mem_to_output(
pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags))
return NULL;
*pOut_len = out_buf.m_size;
return out_buf.m_pBuf;
}
size_t tdefl_compress_mem_to_mem(void *pOut_buf, size_t out_buf_len,
const void *pSrc_buf, size_t src_buf_len,
int flags) {
tdefl_output_buffer out_buf;
MZ_CLEAR_OBJ(out_buf);
if (!pOut_buf) return 0;
out_buf.m_pBuf = (mz_uint8 *)pOut_buf;
out_buf.m_capacity = out_buf_len;
if (!tdefl_compress_mem_to_output(
pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags))
return 0;
return out_buf.m_size;
}
#ifndef MINIZ_NO_ZLIB_APIS
static const mz_uint s_tdefl_num_probes[11] = {0, 1, 6, 32, 16, 32,
128, 256, 512, 768, 1500};
// level may actually range from [0,10] (10 is a "hidden" max level, where we
// want a bit more compression and it's fine if throughput to fall off a cliff
// on some files).
mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits,
int strategy) {
mz_uint comp_flags =
s_tdefl_num_probes[(level >= 0) ? MZ_MIN(10, level) : MZ_DEFAULT_LEVEL] |
((level <= 3) ? TDEFL_GREEDY_PARSING_FLAG : 0);
if (window_bits > 0) comp_flags |= TDEFL_WRITE_ZLIB_HEADER;
if (!level)
comp_flags |= TDEFL_FORCE_ALL_RAW_BLOCKS;
else if (strategy == MZ_FILTERED)
comp_flags |= TDEFL_FILTER_MATCHES;
else if (strategy == MZ_HUFFMAN_ONLY)
comp_flags &= ~TDEFL_MAX_PROBES_MASK;
else if (strategy == MZ_FIXED)
comp_flags |= TDEFL_FORCE_ALL_STATIC_BLOCKS;
else if (strategy == MZ_RLE)
comp_flags |= TDEFL_RLE_MATCHES;
return comp_flags;
}
#endif // MINIZ_NO_ZLIB_APIS
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable : 4204) // nonstandard extension used : non-constant
// aggregate initializer (also supported by GNU
// C and C99, so no big deal)
#pragma warning(disable : 4244) // 'initializing': conversion from '__int64' to
// 'int', possible loss of data
#pragma warning(disable : 4267) // 'argument': conversion from '__int64' to
// 'int', possible loss of data
#pragma warning(disable : 4996) // 'strdup': The POSIX name for this item is
// deprecated. Instead, use the ISO C and C++
// conformant name: _strdup.
#endif
// Simple PNG writer function by Alex Evans, 2011. Released into the public
// domain: https://gist.github.com/908299, more context at
// http://altdevblogaday.org/2011/04/06/a-smaller-jpg-encoder/.
// This is actually a modification of Alex's original code so PNG files
// generated by this function pass pngcheck.
void *tdefl_write_image_to_png_file_in_memory_ex(const void *pImage, int w,
int h, int num_chans,
size_t *pLen_out,
mz_uint level, mz_bool flip) {
// Using a local copy of this array here in case MINIZ_NO_ZLIB_APIS was
// defined.
static const mz_uint s_tdefl_png_num_probes[11] = {
0, 1, 6, 32, 16, 32, 128, 256, 512, 768, 1500};
tdefl_compressor *pComp =
(tdefl_compressor *)MZ_MALLOC(sizeof(tdefl_compressor));
tdefl_output_buffer out_buf;
int i, bpl = w * num_chans, y, z;
mz_uint32 c;
*pLen_out = 0;
if (!pComp) return NULL;
MZ_CLEAR_OBJ(out_buf);
out_buf.m_expandable = MZ_TRUE;
out_buf.m_capacity = 57 + MZ_MAX(64, (1 + bpl) * h);
if (NULL == (out_buf.m_pBuf = (mz_uint8 *)MZ_MALLOC(out_buf.m_capacity))) {
MZ_FREE(pComp);
return NULL;
}
// write dummy header
for (z = 41; z; --z) tdefl_output_buffer_putter(&z, 1, &out_buf);
// compress image data
tdefl_init(
pComp, tdefl_output_buffer_putter, &out_buf,
s_tdefl_png_num_probes[MZ_MIN(10, level)] | TDEFL_WRITE_ZLIB_HEADER);
for (y = 0; y < h; ++y) {
tdefl_compress_buffer(pComp, &z, 1, TDEFL_NO_FLUSH);
tdefl_compress_buffer(pComp,
(mz_uint8 *)pImage + (flip ? (h - 1 - y) : y) * bpl,
bpl, TDEFL_NO_FLUSH);
}
if (tdefl_compress_buffer(pComp, NULL, 0, TDEFL_FINISH) !=
TDEFL_STATUS_DONE) {
MZ_FREE(pComp);
MZ_FREE(out_buf.m_pBuf);
return NULL;
}
// write real header
*pLen_out = out_buf.m_size - 41;
{
static const mz_uint8 chans[] = {0x00, 0x00, 0x04, 0x02, 0x06};
mz_uint8 pnghdr[41] = {0x89,
0x50,
0x4e,
0x47,
0x0d,
0x0a,
0x1a,
0x0a,
0x00,
0x00,
0x00,
0x0d,
0x49,
0x48,
0x44,
0x52,
0,
0,
(mz_uint8)(w >> 8),
(mz_uint8)w,
0,
0,
(mz_uint8)(h >> 8),
(mz_uint8)h,
8,
chans[num_chans],
0,
0,
0,
0,
0,
0,
0,
(mz_uint8)(*pLen_out >> 24),
(mz_uint8)(*pLen_out >> 16),
(mz_uint8)(*pLen_out >> 8),
(mz_uint8)*pLen_out,
0x49,
0x44,
0x41,
0x54};
c = (mz_uint32)mz_crc32(MZ_CRC32_INIT, pnghdr + 12, 17);
for (i = 0; i < 4; ++i, c <<= 8)
((mz_uint8 *)(pnghdr + 29))[i] = (mz_uint8)(c >> 24);
memcpy(out_buf.m_pBuf, pnghdr, 41);
}
// write footer (IDAT CRC-32, followed by IEND chunk)
if (!tdefl_output_buffer_putter(
"\0\0\0\0\0\0\0\0\x49\x45\x4e\x44\xae\x42\x60\x82", 16, &out_buf)) {
*pLen_out = 0;
MZ_FREE(pComp);
MZ_FREE(out_buf.m_pBuf);
return NULL;
}
c = (mz_uint32)mz_crc32(MZ_CRC32_INIT, out_buf.m_pBuf + 41 - 4,
*pLen_out + 4);
for (i = 0; i < 4; ++i, c <<= 8)
(out_buf.m_pBuf + out_buf.m_size - 16)[i] = (mz_uint8)(c >> 24);
// compute final size of file, grab compressed data buffer and return
*pLen_out += 57;
MZ_FREE(pComp);
return out_buf.m_pBuf;
}
void *tdefl_write_image_to_png_file_in_memory(const void *pImage, int w, int h,
int num_chans, size_t *pLen_out) {
// Level 6 corresponds to TDEFL_DEFAULT_MAX_PROBES or MZ_DEFAULT_LEVEL (but we
// can't depend on MZ_DEFAULT_LEVEL being available in case the zlib API's
// where #defined out)
return tdefl_write_image_to_png_file_in_memory_ex(pImage, w, h, num_chans,
pLen_out, 6, MZ_FALSE);
}
// ------------------- .ZIP archive reading
#ifndef MINIZ_NO_ARCHIVE_APIS
#error "No arvhive APIs"
#ifdef MINIZ_NO_STDIO
#define MZ_FILE void *
#else
#include <stdio.h>
#include <sys/stat.h>
#if defined(_MSC_VER) || defined(__MINGW64__)
static FILE *mz_fopen(const char *pFilename, const char *pMode) {
FILE *pFile = NULL;
fopen_s(&pFile, pFilename, pMode);
return pFile;
}
static FILE *mz_freopen(const char *pPath, const char *pMode, FILE *pStream) {
FILE *pFile = NULL;
if (freopen_s(&pFile, pPath, pMode, pStream)) return NULL;
return pFile;
}
#ifndef MINIZ_NO_TIME
#include <sys/utime.h>
#endif
#define MZ_FILE FILE
#define MZ_FOPEN mz_fopen
#define MZ_FCLOSE fclose
#define MZ_FREAD fread
#define MZ_FWRITE fwrite
#define MZ_FTELL64 _ftelli64
#define MZ_FSEEK64 _fseeki64
#define MZ_FILE_STAT_STRUCT _stat
#define MZ_FILE_STAT _stat
#define MZ_FFLUSH fflush
#define MZ_FREOPEN mz_freopen
#define MZ_DELETE_FILE remove
#elif defined(__MINGW32__)
#ifndef MINIZ_NO_TIME
#include <sys/utime.h>
#endif
#define MZ_FILE FILE
#define MZ_FOPEN(f, m) fopen(f, m)
#define MZ_FCLOSE fclose
#define MZ_FREAD fread
#define MZ_FWRITE fwrite
#define MZ_FTELL64 ftello64
#define MZ_FSEEK64 fseeko64
#define MZ_FILE_STAT_STRUCT _stat
#define MZ_FILE_STAT _stat
#define MZ_FFLUSH fflush
#define MZ_FREOPEN(f, m, s) freopen(f, m, s)
#define MZ_DELETE_FILE remove
#elif defined(__TINYC__)
#ifndef MINIZ_NO_TIME
#include <sys/utime.h>
#endif
#define MZ_FILE FILE
#define MZ_FOPEN(f, m) fopen(f, m)
#define MZ_FCLOSE fclose
#define MZ_FREAD fread
#define MZ_FWRITE fwrite
#define MZ_FTELL64 ftell
#define MZ_FSEEK64 fseek
#define MZ_FILE_STAT_STRUCT stat
#define MZ_FILE_STAT stat
#define MZ_FFLUSH fflush
#define MZ_FREOPEN(f, m, s) freopen(f, m, s)
#define MZ_DELETE_FILE remove
#elif defined(__GNUC__) && defined(_LARGEFILE64_SOURCE) && _LARGEFILE64_SOURCE
#ifndef MINIZ_NO_TIME
#include <utime.h>
#endif
#define MZ_FILE FILE
#define MZ_FOPEN(f, m) fopen64(f, m)
#define MZ_FCLOSE fclose
#define MZ_FREAD fread
#define MZ_FWRITE fwrite
#define MZ_FTELL64 ftello64
#define MZ_FSEEK64 fseeko64
#define MZ_FILE_STAT_STRUCT stat64
#define MZ_FILE_STAT stat64
#define MZ_FFLUSH fflush
#define MZ_FREOPEN(p, m, s) freopen64(p, m, s)
#define MZ_DELETE_FILE remove
#else
#ifndef MINIZ_NO_TIME
#include <utime.h>
#endif
#define MZ_FILE FILE
#define MZ_FOPEN(f, m) fopen(f, m)
#define MZ_FCLOSE fclose
#define MZ_FREAD fread
#define MZ_FWRITE fwrite
#define MZ_FTELL64 ftello
#define MZ_FSEEK64 fseeko
#define MZ_FILE_STAT_STRUCT stat
#define MZ_FILE_STAT stat
#define MZ_FFLUSH fflush
#define MZ_FREOPEN(f, m, s) freopen(f, m, s)
#define MZ_DELETE_FILE remove
#endif // #ifdef _MSC_VER
#endif // #ifdef MINIZ_NO_STDIO
#define MZ_TOLOWER(c) ((((c) >= 'A') && ((c) <= 'Z')) ? ((c) - 'A' + 'a') : (c))
// Various ZIP archive enums. To completely avoid cross platform compiler
// alignment and platform endian issues, miniz.c doesn't use structs for any of
// this stuff.
enum {
// ZIP archive identifiers and record sizes
MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG = 0x06054b50,
MZ_ZIP_CENTRAL_DIR_HEADER_SIG = 0x02014b50,
MZ_ZIP_LOCAL_DIR_HEADER_SIG = 0x04034b50,
MZ_ZIP_LOCAL_DIR_HEADER_SIZE = 30,
MZ_ZIP_CENTRAL_DIR_HEADER_SIZE = 46,
MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE = 22,
// Central directory header record offsets
MZ_ZIP_CDH_SIG_OFS = 0,
MZ_ZIP_CDH_VERSION_MADE_BY_OFS = 4,
MZ_ZIP_CDH_VERSION_NEEDED_OFS = 6,
MZ_ZIP_CDH_BIT_FLAG_OFS = 8,
MZ_ZIP_CDH_METHOD_OFS = 10,
MZ_ZIP_CDH_FILE_TIME_OFS = 12,
MZ_ZIP_CDH_FILE_DATE_OFS = 14,
MZ_ZIP_CDH_CRC32_OFS = 16,
MZ_ZIP_CDH_COMPRESSED_SIZE_OFS = 20,
MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS = 24,
MZ_ZIP_CDH_FILENAME_LEN_OFS = 28,
MZ_ZIP_CDH_EXTRA_LEN_OFS = 30,
MZ_ZIP_CDH_COMMENT_LEN_OFS = 32,
MZ_ZIP_CDH_DISK_START_OFS = 34,
MZ_ZIP_CDH_INTERNAL_ATTR_OFS = 36,
MZ_ZIP_CDH_EXTERNAL_ATTR_OFS = 38,
MZ_ZIP_CDH_LOCAL_HEADER_OFS = 42,
// Local directory header offsets
MZ_ZIP_LDH_SIG_OFS = 0,
MZ_ZIP_LDH_VERSION_NEEDED_OFS = 4,
MZ_ZIP_LDH_BIT_FLAG_OFS = 6,
MZ_ZIP_LDH_METHOD_OFS = 8,
MZ_ZIP_LDH_FILE_TIME_OFS = 10,
MZ_ZIP_LDH_FILE_DATE_OFS = 12,
MZ_ZIP_LDH_CRC32_OFS = 14,
MZ_ZIP_LDH_COMPRESSED_SIZE_OFS = 18,
MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS = 22,
MZ_ZIP_LDH_FILENAME_LEN_OFS = 26,
MZ_ZIP_LDH_EXTRA_LEN_OFS = 28,
// End of central directory offsets
MZ_ZIP_ECDH_SIG_OFS = 0,
MZ_ZIP_ECDH_NUM_THIS_DISK_OFS = 4,
MZ_ZIP_ECDH_NUM_DISK_CDIR_OFS = 6,
MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS = 8,
MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS = 10,
MZ_ZIP_ECDH_CDIR_SIZE_OFS = 12,
MZ_ZIP_ECDH_CDIR_OFS_OFS = 16,
MZ_ZIP_ECDH_COMMENT_SIZE_OFS = 20,
};
typedef struct {
void *m_p;
size_t m_size, m_capacity;
mz_uint m_element_size;
} mz_zip_array;
struct mz_zip_internal_state_tag {
mz_zip_array m_central_dir;
mz_zip_array m_central_dir_offsets;
mz_zip_array m_sorted_central_dir_offsets;
MZ_FILE *m_pFile;
void *m_pMem;
size_t m_mem_size;
size_t m_mem_capacity;
};
#define MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(array_ptr, element_size) \
(array_ptr)->m_element_size = element_size
#define MZ_ZIP_ARRAY_ELEMENT(array_ptr, element_type, index) \
((element_type *)((array_ptr)->m_p))[index]
static MZ_FORCEINLINE void mz_zip_array_clear(mz_zip_archive *pZip,
mz_zip_array *pArray) {
pZip->m_pFree(pZip->m_pAlloc_opaque, pArray->m_p);
memset(pArray, 0, sizeof(mz_zip_array));
}
static mz_bool mz_zip_array_ensure_capacity(mz_zip_archive *pZip,
mz_zip_array *pArray,
size_t min_new_capacity,
mz_uint growing) {
void *pNew_p;
size_t new_capacity = min_new_capacity;
MZ_ASSERT(pArray->m_element_size);
if (pArray->m_capacity >= min_new_capacity) return MZ_TRUE;
if (growing) {
new_capacity = MZ_MAX(1, pArray->m_capacity);
while (new_capacity < min_new_capacity) new_capacity *= 2;
}
if (NULL == (pNew_p = pZip->m_pRealloc(pZip->m_pAlloc_opaque, pArray->m_p,
pArray->m_element_size, new_capacity)))
return MZ_FALSE;
pArray->m_p = pNew_p;
pArray->m_capacity = new_capacity;
return MZ_TRUE;
}
static MZ_FORCEINLINE mz_bool mz_zip_array_reserve(mz_zip_archive *pZip,
mz_zip_array *pArray,
size_t new_capacity,
mz_uint growing) {
if (new_capacity > pArray->m_capacity) {
if (!mz_zip_array_ensure_capacity(pZip, pArray, new_capacity, growing))
return MZ_FALSE;
}
return MZ_TRUE;
}
static MZ_FORCEINLINE mz_bool mz_zip_array_resize(mz_zip_archive *pZip,
mz_zip_array *pArray,
size_t new_size,
mz_uint growing) {
if (new_size > pArray->m_capacity) {
if (!mz_zip_array_ensure_capacity(pZip, pArray, new_size, growing))
return MZ_FALSE;
}
pArray->m_size = new_size;
return MZ_TRUE;
}
static MZ_FORCEINLINE mz_bool mz_zip_array_ensure_room(mz_zip_archive *pZip,
mz_zip_array *pArray,
size_t n) {
return mz_zip_array_reserve(pZip, pArray, pArray->m_size + n, MZ_TRUE);
}
static MZ_FORCEINLINE mz_bool mz_zip_array_push_back(mz_zip_archive *pZip,
mz_zip_array *pArray,
const void *pElements,
size_t n) {
size_t orig_size = pArray->m_size;
if (!mz_zip_array_resize(pZip, pArray, orig_size + n, MZ_TRUE))
return MZ_FALSE;
memcpy((mz_uint8 *)pArray->m_p + orig_size * pArray->m_element_size,
pElements, n * pArray->m_element_size);
return MZ_TRUE;
}
#ifndef MINIZ_NO_TIME
static time_t mz_zip_dos_to_time_t(int dos_time, int dos_date) {
struct tm tm;
memset(&tm, 0, sizeof(tm));
tm.tm_isdst = -1;
tm.tm_year = ((dos_date >> 9) & 127) + 1980 - 1900;
tm.tm_mon = ((dos_date >> 5) & 15) - 1;
tm.tm_mday = dos_date & 31;
tm.tm_hour = (dos_time >> 11) & 31;
tm.tm_min = (dos_time >> 5) & 63;
tm.tm_sec = (dos_time << 1) & 62;
return mktime(&tm);
}
static void mz_zip_time_to_dos_time(time_t time, mz_uint16 *pDOS_time,
mz_uint16 *pDOS_date) {
#ifdef _MSC_VER
struct tm tm_struct;
struct tm *tm = &tm_struct;
errno_t err = localtime_s(tm, &time);
if (err) {
*pDOS_date = 0;
*pDOS_time = 0;
return;
}
#else
struct tm *tm = localtime(&time);
#endif
*pDOS_time = (mz_uint16)(((tm->tm_hour) << 11) + ((tm->tm_min) << 5) +
((tm->tm_sec) >> 1));
*pDOS_date = (mz_uint16)(((tm->tm_year + 1900 - 1980) << 9) +
((tm->tm_mon + 1) << 5) + tm->tm_mday);
}
#endif
#ifndef MINIZ_NO_STDIO
static mz_bool mz_zip_get_file_modified_time(const char *pFilename,
mz_uint16 *pDOS_time,
mz_uint16 *pDOS_date) {
#ifdef MINIZ_NO_TIME
(void)pFilename;
*pDOS_date = *pDOS_time = 0;
#else
struct MZ_FILE_STAT_STRUCT file_stat;
// On Linux with x86 glibc, this call will fail on large files (>= 0x80000000
// bytes) unless you compiled with _LARGEFILE64_SOURCE. Argh.
if (MZ_FILE_STAT(pFilename, &file_stat) != 0) return MZ_FALSE;
mz_zip_time_to_dos_time(file_stat.st_mtime, pDOS_time, pDOS_date);
#endif // #ifdef MINIZ_NO_TIME
return MZ_TRUE;
}
#ifndef MINIZ_NO_TIME
static mz_bool mz_zip_set_file_times(const char *pFilename, time_t access_time,
time_t modified_time) {
struct utimbuf t;
t.actime = access_time;
t.modtime = modified_time;
return !utime(pFilename, &t);
}
#endif // #ifndef MINIZ_NO_TIME
#endif // #ifndef MINIZ_NO_STDIO
static mz_bool mz_zip_reader_init_internal(mz_zip_archive *pZip,
mz_uint32 flags) {
(void)flags;
if ((!pZip) || (pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_INVALID))
return MZ_FALSE;
if (!pZip->m_pAlloc) pZip->m_pAlloc = def_alloc_func;
if (!pZip->m_pFree) pZip->m_pFree = def_free_func;
if (!pZip->m_pRealloc) pZip->m_pRealloc = def_realloc_func;
pZip->m_zip_mode = MZ_ZIP_MODE_READING;
pZip->m_archive_size = 0;
pZip->m_central_directory_file_ofs = 0;
pZip->m_total_files = 0;
if (NULL == (pZip->m_pState = (mz_zip_internal_state *)pZip->m_pAlloc(
pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_internal_state))))
return MZ_FALSE;
memset(pZip->m_pState, 0, sizeof(mz_zip_internal_state));
MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir,
sizeof(mz_uint8));
MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir_offsets,
sizeof(mz_uint32));
MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_sorted_central_dir_offsets,
sizeof(mz_uint32));
return MZ_TRUE;
}
static MZ_FORCEINLINE mz_bool
mz_zip_reader_filename_less(const mz_zip_array *pCentral_dir_array,
const mz_zip_array *pCentral_dir_offsets,
mz_uint l_index, mz_uint r_index) {
const mz_uint8 *pL = &MZ_ZIP_ARRAY_ELEMENT(
pCentral_dir_array, mz_uint8,
MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32,
l_index)),
*pE;
const mz_uint8 *pR = &MZ_ZIP_ARRAY_ELEMENT(
pCentral_dir_array, mz_uint8,
MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, r_index));
mz_uint l_len = MZ_READ_LE16(pL + MZ_ZIP_CDH_FILENAME_LEN_OFS),
r_len = MZ_READ_LE16(pR + MZ_ZIP_CDH_FILENAME_LEN_OFS);
mz_uint8 l = 0, r = 0;
pL += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE;
pR += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE;
pE = pL + MZ_MIN(l_len, r_len);
while (pL < pE) {
if ((l = MZ_TOLOWER(*pL)) != (r = MZ_TOLOWER(*pR))) break;
pL++;
pR++;
}
return (pL == pE) ? (l_len < r_len) : (l < r);
}
#define MZ_SWAP_UINT32(a, b) \
do { \
mz_uint32 t = a; \
a = b; \
b = t; \
} \
MZ_MACRO_END
// Heap sort of lowercased filenames, used to help accelerate plain central
// directory searches by mz_zip_reader_locate_file(). (Could also use qsort(),
// but it could allocate memory.)
static void mz_zip_reader_sort_central_dir_offsets_by_filename(
mz_zip_archive *pZip) {
mz_zip_internal_state *pState = pZip->m_pState;
const mz_zip_array *pCentral_dir_offsets = &pState->m_central_dir_offsets;
const mz_zip_array *pCentral_dir = &pState->m_central_dir;
mz_uint32 *pIndices = &MZ_ZIP_ARRAY_ELEMENT(
&pState->m_sorted_central_dir_offsets, mz_uint32, 0);
const int size = pZip->m_total_files;
int start = (size - 2) >> 1, end;
while (start >= 0) {
int child, root = start;
for (;;) {
if ((child = (root << 1) + 1) >= size) break;
child +=
(((child + 1) < size) &&
(mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets,
pIndices[child], pIndices[child + 1])));
if (!mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets,
pIndices[root], pIndices[child]))
break;
MZ_SWAP_UINT32(pIndices[root], pIndices[child]);
root = child;
}
start--;
}
end = size - 1;
while (end > 0) {
int child, root = 0;
MZ_SWAP_UINT32(pIndices[end], pIndices[0]);
for (;;) {
if ((child = (root << 1) + 1) >= end) break;
child +=
(((child + 1) < end) &&
mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets,
pIndices[child], pIndices[child + 1]));
if (!mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets,
pIndices[root], pIndices[child]))
break;
MZ_SWAP_UINT32(pIndices[root], pIndices[child]);
root = child;
}
end--;
}
}
static mz_bool mz_zip_reader_read_central_dir(mz_zip_archive *pZip,
mz_uint32 flags) {
mz_uint cdir_size, num_this_disk, cdir_disk_index;
mz_uint64 cdir_ofs;
mz_int64 cur_file_ofs;
const mz_uint8 *p;
mz_uint32 buf_u32[4096 / sizeof(mz_uint32)];
mz_uint8 *pBuf = (mz_uint8 *)buf_u32;
mz_bool sort_central_dir =
((flags & MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY) == 0);
// Basic sanity checks - reject files which are too small, and check the first
// 4 bytes of the file to make sure a local header is there.
if (pZip->m_archive_size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE)
return MZ_FALSE;
// Find the end of central directory record by scanning the file from the end
// towards the beginning.
cur_file_ofs =
MZ_MAX((mz_int64)pZip->m_archive_size - (mz_int64)sizeof(buf_u32), 0);
for (;;) {
int i,
n = (int)MZ_MIN(sizeof(buf_u32), pZip->m_archive_size - cur_file_ofs);
if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, n) != (mz_uint)n)
return MZ_FALSE;
for (i = n - 4; i >= 0; --i)
if (MZ_READ_LE32(pBuf + i) == MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG) break;
if (i >= 0) {
cur_file_ofs += i;
break;
}
if ((!cur_file_ofs) || ((pZip->m_archive_size - cur_file_ofs) >=
(0xFFFF + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE)))
return MZ_FALSE;
cur_file_ofs = MZ_MAX(cur_file_ofs - (sizeof(buf_u32) - 3), 0);
}
// Read and verify the end of central directory record.
if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf,
MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) !=
MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE)
return MZ_FALSE;
if ((MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_SIG_OFS) !=
MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG) ||
((pZip->m_total_files =
MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS)) !=
MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS)))
return MZ_FALSE;
num_this_disk = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_NUM_THIS_DISK_OFS);
cdir_disk_index = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_NUM_DISK_CDIR_OFS);
if (((num_this_disk | cdir_disk_index) != 0) &&
((num_this_disk != 1) || (cdir_disk_index != 1)))
return MZ_FALSE;
if ((cdir_size = MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_CDIR_SIZE_OFS)) <
pZip->m_total_files * MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)
return MZ_FALSE;
cdir_ofs = MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_CDIR_OFS_OFS);
if ((cdir_ofs + (mz_uint64)cdir_size) > pZip->m_archive_size) return MZ_FALSE;
pZip->m_central_directory_file_ofs = cdir_ofs;
if (pZip->m_total_files) {
mz_uint i, n;
// Read the entire central directory into a heap block, and allocate another
// heap block to hold the unsorted central dir file record offsets, and
// another to hold the sorted indices.
if ((!mz_zip_array_resize(pZip, &pZip->m_pState->m_central_dir, cdir_size,
MZ_FALSE)) ||
(!mz_zip_array_resize(pZip, &pZip->m_pState->m_central_dir_offsets,
pZip->m_total_files, MZ_FALSE)))
return MZ_FALSE;
if (sort_central_dir) {
if (!mz_zip_array_resize(pZip,
&pZip->m_pState->m_sorted_central_dir_offsets,
pZip->m_total_files, MZ_FALSE))
return MZ_FALSE;
}
if (pZip->m_pRead(pZip->m_pIO_opaque, cdir_ofs,
pZip->m_pState->m_central_dir.m_p,
cdir_size) != cdir_size)
return MZ_FALSE;
// Now create an index into the central directory file records, do some
// basic sanity checking on each record, and check for zip64 entries (which
// are not yet supported).
p = (const mz_uint8 *)pZip->m_pState->m_central_dir.m_p;
for (n = cdir_size, i = 0; i < pZip->m_total_files; ++i) {
mz_uint total_header_size, comp_size, decomp_size, disk_index;
if ((n < MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) ||
(MZ_READ_LE32(p) != MZ_ZIP_CENTRAL_DIR_HEADER_SIG))
return MZ_FALSE;
MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32,
i) =
(mz_uint32)(p - (const mz_uint8 *)pZip->m_pState->m_central_dir.m_p);
if (sort_central_dir)
MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_sorted_central_dir_offsets,
mz_uint32, i) = i;
comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS);
decomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS);
if (((!MZ_READ_LE32(p + MZ_ZIP_CDH_METHOD_OFS)) &&
(decomp_size != comp_size)) ||
(decomp_size && !comp_size) || (decomp_size == 0xFFFFFFFF) ||
(comp_size == 0xFFFFFFFF))
return MZ_FALSE;
disk_index = MZ_READ_LE16(p + MZ_ZIP_CDH_DISK_START_OFS);
if ((disk_index != num_this_disk) && (disk_index != 1)) return MZ_FALSE;
if (((mz_uint64)MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS) +
MZ_ZIP_LOCAL_DIR_HEADER_SIZE + comp_size) > pZip->m_archive_size)
return MZ_FALSE;
if ((total_header_size = MZ_ZIP_CENTRAL_DIR_HEADER_SIZE +
MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS) +
MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS) +
MZ_READ_LE16(p + MZ_ZIP_CDH_COMMENT_LEN_OFS)) >
n)
return MZ_FALSE;
n -= total_header_size;
p += total_header_size;
}
}
if (sort_central_dir)
mz_zip_reader_sort_central_dir_offsets_by_filename(pZip);
return MZ_TRUE;
}
mz_bool mz_zip_reader_init(mz_zip_archive *pZip, mz_uint64 size,
mz_uint32 flags) {
if ((!pZip) || (!pZip->m_pRead)) return MZ_FALSE;
if (!mz_zip_reader_init_internal(pZip, flags)) return MZ_FALSE;
pZip->m_archive_size = size;
if (!mz_zip_reader_read_central_dir(pZip, flags)) {
mz_zip_reader_end(pZip);
return MZ_FALSE;
}
return MZ_TRUE;
}
static size_t mz_zip_mem_read_func(void *pOpaque, mz_uint64 file_ofs,
void *pBuf, size_t n) {
mz_zip_archive *pZip = (mz_zip_archive *)pOpaque;
size_t s = (file_ofs >= pZip->m_archive_size)
? 0
: (size_t)MZ_MIN(pZip->m_archive_size - file_ofs, n);
memcpy(pBuf, (const mz_uint8 *)pZip->m_pState->m_pMem + file_ofs, s);
return s;
}
mz_bool mz_zip_reader_init_mem(mz_zip_archive *pZip, const void *pMem,
size_t size, mz_uint32 flags) {
if (!mz_zip_reader_init_internal(pZip, flags)) return MZ_FALSE;
pZip->m_archive_size = size;
pZip->m_pRead = mz_zip_mem_read_func;
pZip->m_pIO_opaque = pZip;
#ifdef __cplusplus
pZip->m_pState->m_pMem = const_cast<void *>(pMem);
#else
pZip->m_pState->m_pMem = (void *)pMem;
#endif
pZip->m_pState->m_mem_size = size;
if (!mz_zip_reader_read_central_dir(pZip, flags)) {
mz_zip_reader_end(pZip);
return MZ_FALSE;
}
return MZ_TRUE;
}
#ifndef MINIZ_NO_STDIO
static size_t mz_zip_file_read_func(void *pOpaque, mz_uint64 file_ofs,
void *pBuf, size_t n) {
mz_zip_archive *pZip = (mz_zip_archive *)pOpaque;
mz_int64 cur_ofs = MZ_FTELL64(pZip->m_pState->m_pFile);
if (((mz_int64)file_ofs < 0) ||
(((cur_ofs != (mz_int64)file_ofs)) &&
(MZ_FSEEK64(pZip->m_pState->m_pFile, (mz_int64)file_ofs, SEEK_SET))))
return 0;
return MZ_FREAD(pBuf, 1, n, pZip->m_pState->m_pFile);
}
mz_bool mz_zip_reader_init_file(mz_zip_archive *pZip, const char *pFilename,
mz_uint32 flags) {
mz_uint64 file_size;
MZ_FILE *pFile = MZ_FOPEN(pFilename, "rb");
if (!pFile) return MZ_FALSE;
if (MZ_FSEEK64(pFile, 0, SEEK_END)) {
MZ_FCLOSE(pFile);
return MZ_FALSE;
}
file_size = MZ_FTELL64(pFile);
if (!mz_zip_reader_init_internal(pZip, flags)) {
MZ_FCLOSE(pFile);
return MZ_FALSE;
}
pZip->m_pRead = mz_zip_file_read_func;
pZip->m_pIO_opaque = pZip;
pZip->m_pState->m_pFile = pFile;
pZip->m_archive_size = file_size;
if (!mz_zip_reader_read_central_dir(pZip, flags)) {
mz_zip_reader_end(pZip);
return MZ_FALSE;
}
return MZ_TRUE;
}
#endif // #ifndef MINIZ_NO_STDIO
mz_uint mz_zip_reader_get_num_files(mz_zip_archive *pZip) {
return pZip ? pZip->m_total_files : 0;
}
static MZ_FORCEINLINE const mz_uint8 *mz_zip_reader_get_cdh(
mz_zip_archive *pZip, mz_uint file_index) {
if ((!pZip) || (!pZip->m_pState) || (file_index >= pZip->m_total_files) ||
(pZip->m_zip_mode != MZ_ZIP_MODE_READING))
return NULL;
return &MZ_ZIP_ARRAY_ELEMENT(
&pZip->m_pState->m_central_dir, mz_uint8,
MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32,
file_index));
}
mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive *pZip,
mz_uint file_index) {
mz_uint m_bit_flag;
const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index);
if (!p) return MZ_FALSE;
m_bit_flag = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS);
return (m_bit_flag & 1);
}
mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip,
mz_uint file_index) {
mz_uint filename_len, external_attr;
const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index);
if (!p) return MZ_FALSE;
// First see if the filename ends with a '/' character.
filename_len = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS);
if (filename_len) {
if (*(p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_len - 1) == '/')
return MZ_TRUE;
}
// Bugfix: This code was also checking if the internal attribute was non-zero,
// which wasn't correct.
// Most/all zip writers (hopefully) set DOS file/directory attributes in the
// low 16-bits, so check for the DOS directory flag and ignore the source OS
// ID in the created by field.
// FIXME: Remove this check? Is it necessary - we already check the filename.
external_attr = MZ_READ_LE32(p + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS);
if ((external_attr & 0x10) != 0) return MZ_TRUE;
return MZ_FALSE;
}
mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip, mz_uint file_index,
mz_zip_archive_file_stat *pStat) {
mz_uint n;
const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index);
if ((!p) || (!pStat)) return MZ_FALSE;
// Unpack the central directory record.
pStat->m_file_index = file_index;
pStat->m_central_dir_ofs = MZ_ZIP_ARRAY_ELEMENT(
&pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index);
pStat->m_version_made_by = MZ_READ_LE16(p + MZ_ZIP_CDH_VERSION_MADE_BY_OFS);
pStat->m_version_needed = MZ_READ_LE16(p + MZ_ZIP_CDH_VERSION_NEEDED_OFS);
pStat->m_bit_flag = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS);
pStat->m_method = MZ_READ_LE16(p + MZ_ZIP_CDH_METHOD_OFS);
#ifndef MINIZ_NO_TIME
pStat->m_time =
mz_zip_dos_to_time_t(MZ_READ_LE16(p + MZ_ZIP_CDH_FILE_TIME_OFS),
MZ_READ_LE16(p + MZ_ZIP_CDH_FILE_DATE_OFS));
#endif
pStat->m_crc32 = MZ_READ_LE32(p + MZ_ZIP_CDH_CRC32_OFS);
pStat->m_comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS);
pStat->m_uncomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS);
pStat->m_internal_attr = MZ_READ_LE16(p + MZ_ZIP_CDH_INTERNAL_ATTR_OFS);
pStat->m_external_attr = MZ_READ_LE32(p + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS);
pStat->m_local_header_ofs = MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS);
// Copy as much of the filename and comment as possible.
n = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS);
n = MZ_MIN(n, MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE - 1);
memcpy(pStat->m_filename, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n);
pStat->m_filename[n] = '\0';
n = MZ_READ_LE16(p + MZ_ZIP_CDH_COMMENT_LEN_OFS);
n = MZ_MIN(n, MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE - 1);
pStat->m_comment_size = n;
memcpy(pStat->m_comment,
p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE +
MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS) +
MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS),
n);
pStat->m_comment[n] = '\0';
return MZ_TRUE;
}
mz_uint mz_zip_reader_get_filename(mz_zip_archive *pZip, mz_uint file_index,
char *pFilename, mz_uint filename_buf_size) {
mz_uint n;
const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index);
if (!p) {
if (filename_buf_size) pFilename[0] = '\0';
return 0;
}
n = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS);
if (filename_buf_size) {
n = MZ_MIN(n, filename_buf_size - 1);
memcpy(pFilename, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n);
pFilename[n] = '\0';
}
return n + 1;
}
static MZ_FORCEINLINE mz_bool mz_zip_reader_string_equal(const char *pA,
const char *pB,
mz_uint len,
mz_uint flags) {
mz_uint i;
if (flags & MZ_ZIP_FLAG_CASE_SENSITIVE) return 0 == memcmp(pA, pB, len);
for (i = 0; i < len; ++i)
if (MZ_TOLOWER(pA[i]) != MZ_TOLOWER(pB[i])) return MZ_FALSE;
return MZ_TRUE;
}
static MZ_FORCEINLINE int mz_zip_reader_filename_compare(
const mz_zip_array *pCentral_dir_array,
const mz_zip_array *pCentral_dir_offsets, mz_uint l_index, const char *pR,
mz_uint r_len) {
const mz_uint8 *pL = &MZ_ZIP_ARRAY_ELEMENT(
pCentral_dir_array, mz_uint8,
MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32,
l_index)),
*pE;
mz_uint l_len = MZ_READ_LE16(pL + MZ_ZIP_CDH_FILENAME_LEN_OFS);
mz_uint8 l = 0, r = 0;
pL += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE;
pE = pL + MZ_MIN(l_len, r_len);
while (pL < pE) {
if ((l = MZ_TOLOWER(*pL)) != (r = MZ_TOLOWER(*pR))) break;
pL++;
pR++;
}
return (pL == pE) ? (int)(l_len - r_len) : (l - r);
}
static int mz_zip_reader_locate_file_binary_search(mz_zip_archive *pZip,
const char *pFilename) {
mz_zip_internal_state *pState = pZip->m_pState;
const mz_zip_array *pCentral_dir_offsets = &pState->m_central_dir_offsets;
const mz_zip_array *pCentral_dir = &pState->m_central_dir;
mz_uint32 *pIndices = &MZ_ZIP_ARRAY_ELEMENT(
&pState->m_sorted_central_dir_offsets, mz_uint32, 0);
const int size = pZip->m_total_files;
const mz_uint filename_len = (mz_uint)strlen(pFilename);
int l = 0, h = size - 1;
while (l <= h) {
int m = (l + h) >> 1, file_index = pIndices[m],
comp =
mz_zip_reader_filename_compare(pCentral_dir, pCentral_dir_offsets,
file_index, pFilename, filename_len);
if (!comp)
return file_index;
else if (comp < 0)
l = m + 1;
else
h = m - 1;
}
return -1;
}
int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName,
const char *pComment, mz_uint flags) {
mz_uint file_index;
size_t name_len, comment_len;
if ((!pZip) || (!pZip->m_pState) || (!pName) ||
(pZip->m_zip_mode != MZ_ZIP_MODE_READING))
return -1;
if (((flags & (MZ_ZIP_FLAG_IGNORE_PATH | MZ_ZIP_FLAG_CASE_SENSITIVE)) == 0) &&
(!pComment) && (pZip->m_pState->m_sorted_central_dir_offsets.m_size))
return mz_zip_reader_locate_file_binary_search(pZip, pName);
name_len = strlen(pName);
if (name_len > 0xFFFF) return -1;
comment_len = pComment ? strlen(pComment) : 0;
if (comment_len > 0xFFFF) return -1;
for (file_index = 0; file_index < pZip->m_total_files; file_index++) {
const mz_uint8 *pHeader = &MZ_ZIP_ARRAY_ELEMENT(
&pZip->m_pState->m_central_dir, mz_uint8,
MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32,
file_index));
mz_uint filename_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_FILENAME_LEN_OFS);
const char *pFilename =
(const char *)pHeader + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE;
if (filename_len < name_len) continue;
if (comment_len) {
mz_uint file_extra_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_EXTRA_LEN_OFS),
file_comment_len =
MZ_READ_LE16(pHeader + MZ_ZIP_CDH_COMMENT_LEN_OFS);
const char *pFile_comment = pFilename + filename_len + file_extra_len;
if ((file_comment_len != comment_len) ||
(!mz_zip_reader_string_equal(pComment, pFile_comment,
file_comment_len, flags)))
continue;
}
if ((flags & MZ_ZIP_FLAG_IGNORE_PATH) && (filename_len)) {
int ofs = filename_len - 1;
do {
if ((pFilename[ofs] == '/') || (pFilename[ofs] == '\\') ||
(pFilename[ofs] == ':'))
break;
} while (--ofs >= 0);
ofs++;
pFilename += ofs;
filename_len -= ofs;
}
if ((filename_len == name_len) &&
(mz_zip_reader_string_equal(pName, pFilename, filename_len, flags)))
return file_index;
}
return -1;
}
mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip,
mz_uint file_index, void *pBuf,
size_t buf_size, mz_uint flags,
void *pUser_read_buf,
size_t user_read_buf_size) {
int status = TINFL_STATUS_DONE;
mz_uint64 needed_size, cur_file_ofs, comp_remaining,
out_buf_ofs = 0, read_buf_size, read_buf_ofs = 0, read_buf_avail;
mz_zip_archive_file_stat file_stat;
void *pRead_buf;
mz_uint32
local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) /
sizeof(mz_uint32)];
mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32;
tinfl_decompressor inflator;
if ((buf_size) && (!pBuf)) return MZ_FALSE;
if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) return MZ_FALSE;
// Empty file, or a directory (but not always a directory - I've seen odd zips
// with directories that have compressed data which inflates to 0 bytes)
if (!file_stat.m_comp_size) return MZ_TRUE;
// Entry is a subdirectory (I've seen old zips with dir entries which have
// compressed deflate data which inflates to 0 bytes, but these entries claim
// to uncompress to 512 bytes in the headers).
// I'm torn how to handle this case - should it fail instead?
if (mz_zip_reader_is_file_a_directory(pZip, file_index)) return MZ_TRUE;
// Encryption and patch files are not supported.
if (file_stat.m_bit_flag & (1 | 32)) return MZ_FALSE;
// This function only supports stored and deflate.
if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (file_stat.m_method != 0) &&
(file_stat.m_method != MZ_DEFLATED))
return MZ_FALSE;
// Ensure supplied output buffer is large enough.
needed_size = (flags & MZ_ZIP_FLAG_COMPRESSED_DATA) ? file_stat.m_comp_size
: file_stat.m_uncomp_size;
if (buf_size < needed_size) return MZ_FALSE;
// Read and parse the local directory entry.
cur_file_ofs = file_stat.m_local_header_ofs;
if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pLocal_header,
MZ_ZIP_LOCAL_DIR_HEADER_SIZE) !=
MZ_ZIP_LOCAL_DIR_HEADER_SIZE)
return MZ_FALSE;
if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG)
return MZ_FALSE;
cur_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE +
MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) +
MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS);
if ((cur_file_ofs + file_stat.m_comp_size) > pZip->m_archive_size)
return MZ_FALSE;
if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!file_stat.m_method)) {
// The file is stored or the caller has requested the compressed data.
if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf,
(size_t)needed_size) != needed_size)
return MZ_FALSE;
return ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) != 0) ||
(mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf,
(size_t)file_stat.m_uncomp_size) == file_stat.m_crc32);
}
// Decompress the file either directly from memory or from a file input
// buffer.
tinfl_init(&inflator);
if (pZip->m_pState->m_pMem) {
// Read directly from the archive in memory.
pRead_buf = (mz_uint8 *)pZip->m_pState->m_pMem + cur_file_ofs;
read_buf_size = read_buf_avail = file_stat.m_comp_size;
comp_remaining = 0;
} else if (pUser_read_buf) {
// Use a user provided read buffer.
if (!user_read_buf_size) return MZ_FALSE;
pRead_buf = (mz_uint8 *)pUser_read_buf;
read_buf_size = user_read_buf_size;
read_buf_avail = 0;
comp_remaining = file_stat.m_comp_size;
} else {
// Temporarily allocate a read buffer.
read_buf_size =
MZ_MIN(file_stat.m_comp_size, (mz_uint)MZ_ZIP_MAX_IO_BUF_SIZE);
#ifdef _MSC_VER
if (((0, sizeof(size_t) == sizeof(mz_uint32))) &&
(read_buf_size > 0x7FFFFFFF))
#else
if (((sizeof(size_t) == sizeof(mz_uint32))) && (read_buf_size > 0x7FFFFFFF))
#endif
return MZ_FALSE;
if (NULL == (pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1,
(size_t)read_buf_size)))
return MZ_FALSE;
read_buf_avail = 0;
comp_remaining = file_stat.m_comp_size;
}
do {
size_t in_buf_size,
out_buf_size = (size_t)(file_stat.m_uncomp_size - out_buf_ofs);
if ((!read_buf_avail) && (!pZip->m_pState->m_pMem)) {
read_buf_avail = MZ_MIN(read_buf_size, comp_remaining);
if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf,
(size_t)read_buf_avail) != read_buf_avail) {
status = TINFL_STATUS_FAILED;
break;
}
cur_file_ofs += read_buf_avail;
comp_remaining -= read_buf_avail;
read_buf_ofs = 0;
}
in_buf_size = (size_t)read_buf_avail;
status = tinfl_decompress(
&inflator, (mz_uint8 *)pRead_buf + read_buf_ofs, &in_buf_size,
(mz_uint8 *)pBuf, (mz_uint8 *)pBuf + out_buf_ofs, &out_buf_size,
TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF |
(comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0));
read_buf_avail -= in_buf_size;
read_buf_ofs += in_buf_size;
out_buf_ofs += out_buf_size;
} while (status == TINFL_STATUS_NEEDS_MORE_INPUT);
if (status == TINFL_STATUS_DONE) {
// Make sure the entire file was decompressed, and check its CRC.
if ((out_buf_ofs != file_stat.m_uncomp_size) ||
(mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf,
(size_t)file_stat.m_uncomp_size) != file_stat.m_crc32))
status = TINFL_STATUS_FAILED;
}
if ((!pZip->m_pState->m_pMem) && (!pUser_read_buf))
pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf);
return status == TINFL_STATUS_DONE;
}
mz_bool mz_zip_reader_extract_file_to_mem_no_alloc(
mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size,
mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size) {
int file_index = mz_zip_reader_locate_file(pZip, pFilename, NULL, flags);
if (file_index < 0) return MZ_FALSE;
return mz_zip_reader_extract_to_mem_no_alloc(pZip, file_index, pBuf, buf_size,
flags, pUser_read_buf,
user_read_buf_size);
}
mz_bool mz_zip_reader_extract_to_mem(mz_zip_archive *pZip, mz_uint file_index,
void *pBuf, size_t buf_size,
mz_uint flags) {
return mz_zip_reader_extract_to_mem_no_alloc(pZip, file_index, pBuf, buf_size,
flags, NULL, 0);
}
mz_bool mz_zip_reader_extract_file_to_mem(mz_zip_archive *pZip,
const char *pFilename, void *pBuf,
size_t buf_size, mz_uint flags) {
return mz_zip_reader_extract_file_to_mem_no_alloc(pZip, pFilename, pBuf,
buf_size, flags, NULL, 0);
}
void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip, mz_uint file_index,
size_t *pSize, mz_uint flags) {
mz_uint64 comp_size, uncomp_size, alloc_size;
const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index);
void *pBuf;
if (pSize) *pSize = 0;
if (!p) return NULL;
comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS);
uncomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS);
alloc_size = (flags & MZ_ZIP_FLAG_COMPRESSED_DATA) ? comp_size : uncomp_size;
#ifdef _MSC_VER
if (((0, sizeof(size_t) == sizeof(mz_uint32))) && (alloc_size > 0x7FFFFFFF))
#else
if (((sizeof(size_t) == sizeof(mz_uint32))) && (alloc_size > 0x7FFFFFFF))
#endif
return NULL;
if (NULL ==
(pBuf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)alloc_size)))
return NULL;
if (!mz_zip_reader_extract_to_mem(pZip, file_index, pBuf, (size_t)alloc_size,
flags)) {
pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf);
return NULL;
}
if (pSize) *pSize = (size_t)alloc_size;
return pBuf;
}
void *mz_zip_reader_extract_file_to_heap(mz_zip_archive *pZip,
const char *pFilename, size_t *pSize,
mz_uint flags) {
int file_index = mz_zip_reader_locate_file(pZip, pFilename, NULL, flags);
if (file_index < 0) {
if (pSize) *pSize = 0;
return MZ_FALSE;
}
return mz_zip_reader_extract_to_heap(pZip, file_index, pSize, flags);
}
mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip,
mz_uint file_index,
mz_file_write_func pCallback,
void *pOpaque, mz_uint flags) {
int status = TINFL_STATUS_DONE;
mz_uint file_crc32 = MZ_CRC32_INIT;
mz_uint64 read_buf_size, read_buf_ofs = 0, read_buf_avail, comp_remaining,
out_buf_ofs = 0, cur_file_ofs;
mz_zip_archive_file_stat file_stat;
void *pRead_buf = NULL;
void *pWrite_buf = NULL;
mz_uint32
local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) /
sizeof(mz_uint32)];
mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32;
if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) return MZ_FALSE;
// Empty file, or a directory (but not always a directory - I've seen odd zips
// with directories that have compressed data which inflates to 0 bytes)
if (!file_stat.m_comp_size) return MZ_TRUE;
// Entry is a subdirectory (I've seen old zips with dir entries which have
// compressed deflate data which inflates to 0 bytes, but these entries claim
// to uncompress to 512 bytes in the headers).
// I'm torn how to handle this case - should it fail instead?
if (mz_zip_reader_is_file_a_directory(pZip, file_index)) return MZ_TRUE;
// Encryption and patch files are not supported.
if (file_stat.m_bit_flag & (1 | 32)) return MZ_FALSE;
// This function only supports stored and deflate.
if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (file_stat.m_method != 0) &&
(file_stat.m_method != MZ_DEFLATED))
return MZ_FALSE;
// Read and parse the local directory entry.
cur_file_ofs = file_stat.m_local_header_ofs;
if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pLocal_header,
MZ_ZIP_LOCAL_DIR_HEADER_SIZE) !=
MZ_ZIP_LOCAL_DIR_HEADER_SIZE)
return MZ_FALSE;
if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG)
return MZ_FALSE;
cur_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE +
MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) +
MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS);
if ((cur_file_ofs + file_stat.m_comp_size) > pZip->m_archive_size)
return MZ_FALSE;
// Decompress the file either directly from memory or from a file input
// buffer.
if (pZip->m_pState->m_pMem) {
pRead_buf = (mz_uint8 *)pZip->m_pState->m_pMem + cur_file_ofs;
read_buf_size = read_buf_avail = file_stat.m_comp_size;
comp_remaining = 0;
} else {
read_buf_size =
MZ_MIN(file_stat.m_comp_size, (mz_uint)MZ_ZIP_MAX_IO_BUF_SIZE);
if (NULL == (pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1,
(size_t)read_buf_size)))
return MZ_FALSE;
read_buf_avail = 0;
comp_remaining = file_stat.m_comp_size;
}
if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!file_stat.m_method)) {
// The file is stored or the caller has requested the compressed data.
if (pZip->m_pState->m_pMem) {
#ifdef _MSC_VER
if (((0, sizeof(size_t) == sizeof(mz_uint32))) &&
(file_stat.m_comp_size > 0xFFFFFFFF))
#else
if (((sizeof(size_t) == sizeof(mz_uint32))) &&
(file_stat.m_comp_size > 0xFFFFFFFF))
#endif
return MZ_FALSE;
if (pCallback(pOpaque, out_buf_ofs, pRead_buf,
(size_t)file_stat.m_comp_size) != file_stat.m_comp_size)
status = TINFL_STATUS_FAILED;
else if (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA))
file_crc32 =
(mz_uint32)mz_crc32(file_crc32, (const mz_uint8 *)pRead_buf,
(size_t)file_stat.m_comp_size);
cur_file_ofs += file_stat.m_comp_size;
out_buf_ofs += file_stat.m_comp_size;
comp_remaining = 0;
} else {
while (comp_remaining) {
read_buf_avail = MZ_MIN(read_buf_size, comp_remaining);
if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf,
(size_t)read_buf_avail) != read_buf_avail) {
status = TINFL_STATUS_FAILED;
break;
}
if (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA))
file_crc32 = (mz_uint32)mz_crc32(
file_crc32, (const mz_uint8 *)pRead_buf, (size_t)read_buf_avail);
if (pCallback(pOpaque, out_buf_ofs, pRead_buf,
(size_t)read_buf_avail) != read_buf_avail) {
status = TINFL_STATUS_FAILED;
break;
}
cur_file_ofs += read_buf_avail;
out_buf_ofs += read_buf_avail;
comp_remaining -= read_buf_avail;
}
}
} else {
tinfl_decompressor inflator;
tinfl_init(&inflator);
if (NULL == (pWrite_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1,
TINFL_LZ_DICT_SIZE)))
status = TINFL_STATUS_FAILED;
else {
do {
mz_uint8 *pWrite_buf_cur =
(mz_uint8 *)pWrite_buf + (out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1));
size_t in_buf_size,
out_buf_size =
TINFL_LZ_DICT_SIZE - (out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1));
if ((!read_buf_avail) && (!pZip->m_pState->m_pMem)) {
read_buf_avail = MZ_MIN(read_buf_size, comp_remaining);
if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf,
(size_t)read_buf_avail) != read_buf_avail) {
status = TINFL_STATUS_FAILED;
break;
}
cur_file_ofs += read_buf_avail;
comp_remaining -= read_buf_avail;
read_buf_ofs = 0;
}
in_buf_size = (size_t)read_buf_avail;
status = tinfl_decompress(
&inflator, (const mz_uint8 *)pRead_buf + read_buf_ofs, &in_buf_size,
(mz_uint8 *)pWrite_buf, pWrite_buf_cur, &out_buf_size,
comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0);
read_buf_avail -= in_buf_size;
read_buf_ofs += in_buf_size;
if (out_buf_size) {
if (pCallback(pOpaque, out_buf_ofs, pWrite_buf_cur, out_buf_size) !=
out_buf_size) {
status = TINFL_STATUS_FAILED;
break;
}
file_crc32 =
(mz_uint32)mz_crc32(file_crc32, pWrite_buf_cur, out_buf_size);
if ((out_buf_ofs += out_buf_size) > file_stat.m_uncomp_size) {
status = TINFL_STATUS_FAILED;
break;
}
}
} while ((status == TINFL_STATUS_NEEDS_MORE_INPUT) ||
(status == TINFL_STATUS_HAS_MORE_OUTPUT));
}
}
if ((status == TINFL_STATUS_DONE) &&
(!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA))) {
// Make sure the entire file was decompressed, and check its CRC.
if ((out_buf_ofs != file_stat.m_uncomp_size) ||
(file_crc32 != file_stat.m_crc32))
status = TINFL_STATUS_FAILED;
}
if (!pZip->m_pState->m_pMem) pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf);
if (pWrite_buf) pZip->m_pFree(pZip->m_pAlloc_opaque, pWrite_buf);
return status == TINFL_STATUS_DONE;
}
mz_bool mz_zip_reader_extract_file_to_callback(mz_zip_archive *pZip,
const char *pFilename,
mz_file_write_func pCallback,
void *pOpaque, mz_uint flags) {
int file_index = mz_zip_reader_locate_file(pZip, pFilename, NULL, flags);
if (file_index < 0) return MZ_FALSE;
return mz_zip_reader_extract_to_callback(pZip, file_index, pCallback, pOpaque,
flags);
}
#ifndef MINIZ_NO_STDIO
static size_t mz_zip_file_write_callback(void *pOpaque, mz_uint64 ofs,
const void *pBuf, size_t n) {
(void)ofs;
return MZ_FWRITE(pBuf, 1, n, (MZ_FILE *)pOpaque);
}
mz_bool mz_zip_reader_extract_to_file(mz_zip_archive *pZip, mz_uint file_index,
const char *pDst_filename,
mz_uint flags) {
mz_bool status;
mz_zip_archive_file_stat file_stat;
MZ_FILE *pFile;
if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) return MZ_FALSE;
pFile = MZ_FOPEN(pDst_filename, "wb");
if (!pFile) return MZ_FALSE;
status = mz_zip_reader_extract_to_callback(
pZip, file_index, mz_zip_file_write_callback, pFile, flags);
if (MZ_FCLOSE(pFile) == EOF) return MZ_FALSE;
#ifndef MINIZ_NO_TIME
if (status)
mz_zip_set_file_times(pDst_filename, file_stat.m_time, file_stat.m_time);
#endif
return status;
}
#endif // #ifndef MINIZ_NO_STDIO
mz_bool mz_zip_reader_end(mz_zip_archive *pZip) {
if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) ||
(pZip->m_zip_mode != MZ_ZIP_MODE_READING))
return MZ_FALSE;
if (pZip->m_pState) {
mz_zip_internal_state *pState = pZip->m_pState;
pZip->m_pState = NULL;
mz_zip_array_clear(pZip, &pState->m_central_dir);
mz_zip_array_clear(pZip, &pState->m_central_dir_offsets);
mz_zip_array_clear(pZip, &pState->m_sorted_central_dir_offsets);
#ifndef MINIZ_NO_STDIO
if (pState->m_pFile) {
MZ_FCLOSE(pState->m_pFile);
pState->m_pFile = NULL;
}
#endif // #ifndef MINIZ_NO_STDIO
pZip->m_pFree(pZip->m_pAlloc_opaque, pState);
}
pZip->m_zip_mode = MZ_ZIP_MODE_INVALID;
return MZ_TRUE;
}
#ifndef MINIZ_NO_STDIO
mz_bool mz_zip_reader_extract_file_to_file(mz_zip_archive *pZip,
const char *pArchive_filename,
const char *pDst_filename,
mz_uint flags) {
int file_index =
mz_zip_reader_locate_file(pZip, pArchive_filename, NULL, flags);
if (file_index < 0) return MZ_FALSE;
return mz_zip_reader_extract_to_file(pZip, file_index, pDst_filename, flags);
}
#endif
// ------------------- .ZIP archive writing
#ifndef MINIZ_NO_ARCHIVE_WRITING_APIS
static void mz_write_le16(mz_uint8 *p, mz_uint16 v) {
p[0] = (mz_uint8)v;
p[1] = (mz_uint8)(v >> 8);
}
static void mz_write_le32(mz_uint8 *p, mz_uint32 v) {
p[0] = (mz_uint8)v;
p[1] = (mz_uint8)(v >> 8);
p[2] = (mz_uint8)(v >> 16);
p[3] = (mz_uint8)(v >> 24);
}
#define MZ_WRITE_LE16(p, v) mz_write_le16((mz_uint8 *)(p), (mz_uint16)(v))
#define MZ_WRITE_LE32(p, v) mz_write_le32((mz_uint8 *)(p), (mz_uint32)(v))
mz_bool mz_zip_writer_init(mz_zip_archive *pZip, mz_uint64 existing_size) {
if ((!pZip) || (pZip->m_pState) || (!pZip->m_pWrite) ||
(pZip->m_zip_mode != MZ_ZIP_MODE_INVALID))
return MZ_FALSE;
if (pZip->m_file_offset_alignment) {
// Ensure user specified file offset alignment is a power of 2.
if (pZip->m_file_offset_alignment & (pZip->m_file_offset_alignment - 1))
return MZ_FALSE;
}
if (!pZip->m_pAlloc) pZip->m_pAlloc = def_alloc_func;
if (!pZip->m_pFree) pZip->m_pFree = def_free_func;
if (!pZip->m_pRealloc) pZip->m_pRealloc = def_realloc_func;
pZip->m_zip_mode = MZ_ZIP_MODE_WRITING;
pZip->m_archive_size = existing_size;
pZip->m_central_directory_file_ofs = 0;
pZip->m_total_files = 0;
if (NULL == (pZip->m_pState = (mz_zip_internal_state *)pZip->m_pAlloc(
pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_internal_state))))
return MZ_FALSE;
memset(pZip->m_pState, 0, sizeof(mz_zip_internal_state));
MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir,
sizeof(mz_uint8));
MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir_offsets,
sizeof(mz_uint32));
MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_sorted_central_dir_offsets,
sizeof(mz_uint32));
return MZ_TRUE;
}
static size_t mz_zip_heap_write_func(void *pOpaque, mz_uint64 file_ofs,
const void *pBuf, size_t n) {
mz_zip_archive *pZip = (mz_zip_archive *)pOpaque;
mz_zip_internal_state *pState = pZip->m_pState;
mz_uint64 new_size = MZ_MAX(file_ofs + n, pState->m_mem_size);
#ifdef _MSC_VER
if ((!n) ||
((0, sizeof(size_t) == sizeof(mz_uint32)) && (new_size > 0x7FFFFFFF)))
#else
if ((!n) ||
((sizeof(size_t) == sizeof(mz_uint32)) && (new_size > 0x7FFFFFFF)))
#endif
return 0;
if (new_size > pState->m_mem_capacity) {
void *pNew_block;
size_t new_capacity = MZ_MAX(64, pState->m_mem_capacity);
while (new_capacity < new_size) new_capacity *= 2;
if (NULL == (pNew_block = pZip->m_pRealloc(
pZip->m_pAlloc_opaque, pState->m_pMem, 1, new_capacity)))
return 0;
pState->m_pMem = pNew_block;
pState->m_mem_capacity = new_capacity;
}
memcpy((mz_uint8 *)pState->m_pMem + file_ofs, pBuf, n);
pState->m_mem_size = (size_t)new_size;
return n;
}
mz_bool mz_zip_writer_init_heap(mz_zip_archive *pZip,
size_t size_to_reserve_at_beginning,
size_t initial_allocation_size) {
pZip->m_pWrite = mz_zip_heap_write_func;
pZip->m_pIO_opaque = pZip;
if (!mz_zip_writer_init(pZip, size_to_reserve_at_beginning)) return MZ_FALSE;
if (0 != (initial_allocation_size = MZ_MAX(initial_allocation_size,
size_to_reserve_at_beginning))) {
if (NULL == (pZip->m_pState->m_pMem = pZip->m_pAlloc(
pZip->m_pAlloc_opaque, 1, initial_allocation_size))) {
mz_zip_writer_end(pZip);
return MZ_FALSE;
}
pZip->m_pState->m_mem_capacity = initial_allocation_size;
}
return MZ_TRUE;
}
#ifndef MINIZ_NO_STDIO
static size_t mz_zip_file_write_func(void *pOpaque, mz_uint64 file_ofs,
const void *pBuf, size_t n) {
mz_zip_archive *pZip = (mz_zip_archive *)pOpaque;
mz_int64 cur_ofs = MZ_FTELL64(pZip->m_pState->m_pFile);
if (((mz_int64)file_ofs < 0) ||
(((cur_ofs != (mz_int64)file_ofs)) &&
(MZ_FSEEK64(pZip->m_pState->m_pFile, (mz_int64)file_ofs, SEEK_SET))))
return 0;
return MZ_FWRITE(pBuf, 1, n, pZip->m_pState->m_pFile);
}
mz_bool mz_zip_writer_init_file(mz_zip_archive *pZip, const char *pFilename,
mz_uint64 size_to_reserve_at_beginning) {
MZ_FILE *pFile;
pZip->m_pWrite = mz_zip_file_write_func;
pZip->m_pIO_opaque = pZip;
if (!mz_zip_writer_init(pZip, size_to_reserve_at_beginning)) return MZ_FALSE;
if (NULL == (pFile = MZ_FOPEN(pFilename, "wb"))) {
mz_zip_writer_end(pZip);
return MZ_FALSE;
}
pZip->m_pState->m_pFile = pFile;
if (size_to_reserve_at_beginning) {
mz_uint64 cur_ofs = 0;
char buf[4096];
MZ_CLEAR_OBJ(buf);
do {
size_t n = (size_t)MZ_MIN(sizeof(buf), size_to_reserve_at_beginning);
if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_ofs, buf, n) != n) {
mz_zip_writer_end(pZip);
return MZ_FALSE;
}
cur_ofs += n;
size_to_reserve_at_beginning -= n;
} while (size_to_reserve_at_beginning);
}
return MZ_TRUE;
}
#endif // #ifndef MINIZ_NO_STDIO
mz_bool mz_zip_writer_init_from_reader(mz_zip_archive *pZip,
const char *pFilename) {
mz_zip_internal_state *pState;
if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING))
return MZ_FALSE;
// No sense in trying to write to an archive that's already at the support max
// size
if ((pZip->m_total_files == 0xFFFF) ||
((pZip->m_archive_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE +
MZ_ZIP_LOCAL_DIR_HEADER_SIZE) > 0xFFFFFFFF))
return MZ_FALSE;
pState = pZip->m_pState;
if (pState->m_pFile) {
#ifdef MINIZ_NO_STDIO
pFilename;
return MZ_FALSE;
#else
// Archive is being read from stdio - try to reopen as writable.
if (pZip->m_pIO_opaque != pZip) return MZ_FALSE;
if (!pFilename) return MZ_FALSE;
pZip->m_pWrite = mz_zip_file_write_func;
if (NULL ==
(pState->m_pFile = MZ_FREOPEN(pFilename, "r+b", pState->m_pFile))) {
// The mz_zip_archive is now in a bogus state because pState->m_pFile is
// NULL, so just close it.
mz_zip_reader_end(pZip);
return MZ_FALSE;
}
#endif // #ifdef MINIZ_NO_STDIO
} else if (pState->m_pMem) {
// Archive lives in a memory block. Assume it's from the heap that we can
// resize using the realloc callback.
if (pZip->m_pIO_opaque != pZip) return MZ_FALSE;
pState->m_mem_capacity = pState->m_mem_size;
pZip->m_pWrite = mz_zip_heap_write_func;
}
// Archive is being read via a user provided read function - make sure the
// user has specified a write function too.
else if (!pZip->m_pWrite)
return MZ_FALSE;
// Start writing new files at the archive's current central directory
// location.
pZip->m_archive_size = pZip->m_central_directory_file_ofs;
pZip->m_zip_mode = MZ_ZIP_MODE_WRITING;
pZip->m_central_directory_file_ofs = 0;
return MZ_TRUE;
}
mz_bool mz_zip_writer_add_mem(mz_zip_archive *pZip, const char *pArchive_name,
const void *pBuf, size_t buf_size,
mz_uint level_and_flags) {
return mz_zip_writer_add_mem_ex(pZip, pArchive_name, pBuf, buf_size, NULL, 0,
level_and_flags, 0, 0);
}
typedef struct {
mz_zip_archive *m_pZip;
mz_uint64 m_cur_archive_file_ofs;
mz_uint64 m_comp_size;
} mz_zip_writer_add_state;
static mz_bool mz_zip_writer_add_put_buf_callback(const void *pBuf, int len,
void *pUser) {
mz_zip_writer_add_state *pState = (mz_zip_writer_add_state *)pUser;
if ((int)pState->m_pZip->m_pWrite(pState->m_pZip->m_pIO_opaque,
pState->m_cur_archive_file_ofs, pBuf,
len) != len)
return MZ_FALSE;
pState->m_cur_archive_file_ofs += len;
pState->m_comp_size += len;
return MZ_TRUE;
}
static mz_bool mz_zip_writer_create_local_dir_header(
mz_zip_archive *pZip, mz_uint8 *pDst, mz_uint16 filename_size,
mz_uint16 extra_size, mz_uint64 uncomp_size, mz_uint64 comp_size,
mz_uint32 uncomp_crc32, mz_uint16 method, mz_uint16 bit_flags,
mz_uint16 dos_time, mz_uint16 dos_date) {
(void)pZip;
memset(pDst, 0, MZ_ZIP_LOCAL_DIR_HEADER_SIZE);
MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_SIG_OFS, MZ_ZIP_LOCAL_DIR_HEADER_SIG);
MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_VERSION_NEEDED_OFS, method ? 20 : 0);
MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_BIT_FLAG_OFS, bit_flags);
MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_METHOD_OFS, method);
MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILE_TIME_OFS, dos_time);
MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILE_DATE_OFS, dos_date);
MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_CRC32_OFS, uncomp_crc32);
MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_COMPRESSED_SIZE_OFS, comp_size);
MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS, uncomp_size);
MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILENAME_LEN_OFS, filename_size);
MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_EXTRA_LEN_OFS, extra_size);
return MZ_TRUE;
}
static mz_bool mz_zip_writer_create_central_dir_header(
mz_zip_archive *pZip, mz_uint8 *pDst, mz_uint16 filename_size,
mz_uint16 extra_size, mz_uint16 comment_size, mz_uint64 uncomp_size,
mz_uint64 comp_size, mz_uint32 uncomp_crc32, mz_uint16 method,
mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date,
mz_uint64 local_header_ofs, mz_uint32 ext_attributes) {
(void)pZip;
memset(pDst, 0, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE);
MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_SIG_OFS, MZ_ZIP_CENTRAL_DIR_HEADER_SIG);
MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_VERSION_NEEDED_OFS, method ? 20 : 0);
MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_BIT_FLAG_OFS, bit_flags);
MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_METHOD_OFS, method);
MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILE_TIME_OFS, dos_time);
MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILE_DATE_OFS, dos_date);
MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_CRC32_OFS, uncomp_crc32);
MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS, comp_size);
MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS, uncomp_size);
MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILENAME_LEN_OFS, filename_size);
MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_EXTRA_LEN_OFS, extra_size);
MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_COMMENT_LEN_OFS, comment_size);
MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS, ext_attributes);
MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_LOCAL_HEADER_OFS, local_header_ofs);
return MZ_TRUE;
}
static mz_bool mz_zip_writer_add_to_central_dir(
mz_zip_archive *pZip, const char *pFilename, mz_uint16 filename_size,
const void *pExtra, mz_uint16 extra_size, const void *pComment,
mz_uint16 comment_size, mz_uint64 uncomp_size, mz_uint64 comp_size,
mz_uint32 uncomp_crc32, mz_uint16 method, mz_uint16 bit_flags,
mz_uint16 dos_time, mz_uint16 dos_date, mz_uint64 local_header_ofs,
mz_uint32 ext_attributes) {
mz_zip_internal_state *pState = pZip->m_pState;
mz_uint32 central_dir_ofs = (mz_uint32)pState->m_central_dir.m_size;
size_t orig_central_dir_size = pState->m_central_dir.m_size;
mz_uint8 central_dir_header[MZ_ZIP_CENTRAL_DIR_HEADER_SIZE];
// No zip64 support yet
if ((local_header_ofs > 0xFFFFFFFF) ||
(((mz_uint64)pState->m_central_dir.m_size +
MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_size + extra_size +
comment_size) > 0xFFFFFFFF))
return MZ_FALSE;
if (!mz_zip_writer_create_central_dir_header(
pZip, central_dir_header, filename_size, extra_size, comment_size,
uncomp_size, comp_size, uncomp_crc32, method, bit_flags, dos_time,
dos_date, local_header_ofs, ext_attributes))
return MZ_FALSE;
if ((!mz_zip_array_push_back(pZip, &pState->m_central_dir, central_dir_header,
MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)) ||
(!mz_zip_array_push_back(pZip, &pState->m_central_dir, pFilename,
filename_size)) ||
(!mz_zip_array_push_back(pZip, &pState->m_central_dir, pExtra,
extra_size)) ||
(!mz_zip_array_push_back(pZip, &pState->m_central_dir, pComment,
comment_size)) ||
(!mz_zip_array_push_back(pZip, &pState->m_central_dir_offsets,
¢ral_dir_ofs, 1))) {
// Try to push the central directory array back into its original state.
mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size,
MZ_FALSE);
return MZ_FALSE;
}
return MZ_TRUE;
}
static mz_bool mz_zip_writer_validate_archive_name(const char *pArchive_name) {
// Basic ZIP archive filename validity checks: Valid filenames cannot start
// with a forward slash, cannot contain a drive letter, and cannot use
// DOS-style backward slashes.
if (*pArchive_name == '/') return MZ_FALSE;
while (*pArchive_name) {
if ((*pArchive_name == '\\') || (*pArchive_name == ':')) return MZ_FALSE;
pArchive_name++;
}
return MZ_TRUE;
}
static mz_uint mz_zip_writer_compute_padding_needed_for_file_alignment(
mz_zip_archive *pZip) {
mz_uint32 n;
if (!pZip->m_file_offset_alignment) return 0;
n = (mz_uint32)(pZip->m_archive_size & (pZip->m_file_offset_alignment - 1));
return (pZip->m_file_offset_alignment - n) &
(pZip->m_file_offset_alignment - 1);
}
static mz_bool mz_zip_writer_write_zeros(mz_zip_archive *pZip,
mz_uint64 cur_file_ofs, mz_uint32 n) {
char buf[4096];
memset(buf, 0, MZ_MIN(sizeof(buf), n));
while (n) {
mz_uint32 s = MZ_MIN(sizeof(buf), n);
if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_file_ofs, buf, s) != s)
return MZ_FALSE;
cur_file_ofs += s;
n -= s;
}
return MZ_TRUE;
}
mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive *pZip,
const char *pArchive_name, const void *pBuf,
size_t buf_size, const void *pComment,
mz_uint16 comment_size,
mz_uint level_and_flags, mz_uint64 uncomp_size,
mz_uint32 uncomp_crc32) {
mz_uint16 method = 0, dos_time = 0, dos_date = 0;
mz_uint level, ext_attributes = 0, num_alignment_padding_bytes;
mz_uint64 local_dir_header_ofs = pZip->m_archive_size,
cur_archive_file_ofs = pZip->m_archive_size, comp_size = 0;
size_t archive_name_size;
mz_uint8 local_dir_header[MZ_ZIP_LOCAL_DIR_HEADER_SIZE];
tdefl_compressor *pComp = NULL;
mz_bool store_data_uncompressed;
mz_zip_internal_state *pState;
if ((int)level_and_flags < 0) level_and_flags = MZ_DEFAULT_LEVEL;
level = level_and_flags & 0xF;
store_data_uncompressed =
((!level) || (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA));
if ((!pZip) || (!pZip->m_pState) ||
(pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || ((buf_size) && (!pBuf)) ||
(!pArchive_name) || ((comment_size) && (!pComment)) ||
(pZip->m_total_files == 0xFFFF) || (level > MZ_UBER_COMPRESSION))
return MZ_FALSE;
pState = pZip->m_pState;
if ((!(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (uncomp_size))
return MZ_FALSE;
// No zip64 support yet
if ((buf_size > 0xFFFFFFFF) || (uncomp_size > 0xFFFFFFFF)) return MZ_FALSE;
if (!mz_zip_writer_validate_archive_name(pArchive_name)) return MZ_FALSE;
#ifndef MINIZ_NO_TIME
{
time_t cur_time;
time(&cur_time);
mz_zip_time_to_dos_time(cur_time, &dos_time, &dos_date);
}
#endif // #ifndef MINIZ_NO_TIME
archive_name_size = strlen(pArchive_name);
if (archive_name_size > 0xFFFF) return MZ_FALSE;
num_alignment_padding_bytes =
mz_zip_writer_compute_padding_needed_for_file_alignment(pZip);
// no zip64 support yet
if ((pZip->m_total_files == 0xFFFF) ||
((pZip->m_archive_size + num_alignment_padding_bytes +
MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE +
comment_size + archive_name_size) > 0xFFFFFFFF))
return MZ_FALSE;
if ((archive_name_size) && (pArchive_name[archive_name_size - 1] == '/')) {
// Set DOS Subdirectory attribute bit.
ext_attributes |= 0x10;
// Subdirectories cannot contain data.
if ((buf_size) || (uncomp_size)) return MZ_FALSE;
}
// Try to do any allocations before writing to the archive, so if an
// allocation fails the file remains unmodified. (A good idea if we're doing
// an in-place modification.)
if ((!mz_zip_array_ensure_room(
pZip, &pState->m_central_dir,
MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + archive_name_size + comment_size)) ||
(!mz_zip_array_ensure_room(pZip, &pState->m_central_dir_offsets, 1)))
return MZ_FALSE;
if ((!store_data_uncompressed) && (buf_size)) {
if (NULL == (pComp = (tdefl_compressor *)pZip->m_pAlloc(
pZip->m_pAlloc_opaque, 1, sizeof(tdefl_compressor))))
return MZ_FALSE;
}
if (!mz_zip_writer_write_zeros(
pZip, cur_archive_file_ofs,
num_alignment_padding_bytes + sizeof(local_dir_header))) {
pZip->m_pFree(pZip->m_pAlloc_opaque, pComp);
return MZ_FALSE;
}
local_dir_header_ofs += num_alignment_padding_bytes;
if (pZip->m_file_offset_alignment) {
MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) ==
0);
}
cur_archive_file_ofs +=
num_alignment_padding_bytes + sizeof(local_dir_header);
MZ_CLEAR_OBJ(local_dir_header);
if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name,
archive_name_size) != archive_name_size) {
pZip->m_pFree(pZip->m_pAlloc_opaque, pComp);
return MZ_FALSE;
}
cur_archive_file_ofs += archive_name_size;
if (!(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) {
uncomp_crc32 =
(mz_uint32)mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, buf_size);
uncomp_size = buf_size;
if (uncomp_size <= 3) {
level = 0;
store_data_uncompressed = MZ_TRUE;
}
}
if (store_data_uncompressed) {
if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pBuf,
buf_size) != buf_size) {
pZip->m_pFree(pZip->m_pAlloc_opaque, pComp);
return MZ_FALSE;
}
cur_archive_file_ofs += buf_size;
comp_size = buf_size;
if (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA) method = MZ_DEFLATED;
} else if (buf_size) {
mz_zip_writer_add_state state;
state.m_pZip = pZip;
state.m_cur_archive_file_ofs = cur_archive_file_ofs;
state.m_comp_size = 0;
if ((tdefl_init(pComp, mz_zip_writer_add_put_buf_callback, &state,
tdefl_create_comp_flags_from_zip_params(
level, -15, MZ_DEFAULT_STRATEGY)) !=
TDEFL_STATUS_OKAY) ||
(tdefl_compress_buffer(pComp, pBuf, buf_size, TDEFL_FINISH) !=
TDEFL_STATUS_DONE)) {
pZip->m_pFree(pZip->m_pAlloc_opaque, pComp);
return MZ_FALSE;
}
comp_size = state.m_comp_size;
cur_archive_file_ofs = state.m_cur_archive_file_ofs;
method = MZ_DEFLATED;
}
pZip->m_pFree(pZip->m_pAlloc_opaque, pComp);
pComp = NULL;
// no zip64 support yet
if ((comp_size > 0xFFFFFFFF) || (cur_archive_file_ofs > 0xFFFFFFFF))
return MZ_FALSE;
if (!mz_zip_writer_create_local_dir_header(
pZip, local_dir_header, (mz_uint16)archive_name_size, 0, uncomp_size,
comp_size, uncomp_crc32, method, 0, dos_time, dos_date))
return MZ_FALSE;
if (pZip->m_pWrite(pZip->m_pIO_opaque, local_dir_header_ofs, local_dir_header,
sizeof(local_dir_header)) != sizeof(local_dir_header))
return MZ_FALSE;
if (!mz_zip_writer_add_to_central_dir(
pZip, pArchive_name, (mz_uint16)archive_name_size, NULL, 0, pComment,
comment_size, uncomp_size, comp_size, uncomp_crc32, method, 0,
dos_time, dos_date, local_dir_header_ofs, ext_attributes))
return MZ_FALSE;
pZip->m_total_files++;
pZip->m_archive_size = cur_archive_file_ofs;
return MZ_TRUE;
}
#ifndef MINIZ_NO_STDIO
mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name,
const char *pSrc_filename, const void *pComment,
mz_uint16 comment_size,
mz_uint level_and_flags) {
mz_uint uncomp_crc32 = MZ_CRC32_INIT, level, num_alignment_padding_bytes;
mz_uint16 method = 0, dos_time = 0, dos_date = 0, ext_attributes = 0;
mz_uint64 local_dir_header_ofs = pZip->m_archive_size,
cur_archive_file_ofs = pZip->m_archive_size, uncomp_size = 0,
comp_size = 0;
size_t archive_name_size;
mz_uint8 local_dir_header[MZ_ZIP_LOCAL_DIR_HEADER_SIZE];
MZ_FILE *pSrc_file = NULL;
if ((int)level_and_flags < 0) level_and_flags = MZ_DEFAULT_LEVEL;
level = level_and_flags & 0xF;
if ((!pZip) || (!pZip->m_pState) ||
(pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || (!pArchive_name) ||
((comment_size) && (!pComment)) || (level > MZ_UBER_COMPRESSION))
return MZ_FALSE;
if (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA) return MZ_FALSE;
if (!mz_zip_writer_validate_archive_name(pArchive_name)) return MZ_FALSE;
archive_name_size = strlen(pArchive_name);
if (archive_name_size > 0xFFFF) return MZ_FALSE;
num_alignment_padding_bytes =
mz_zip_writer_compute_padding_needed_for_file_alignment(pZip);
// no zip64 support yet
if ((pZip->m_total_files == 0xFFFF) ||
((pZip->m_archive_size + num_alignment_padding_bytes +
MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE +
comment_size + archive_name_size) > 0xFFFFFFFF))
return MZ_FALSE;
if (!mz_zip_get_file_modified_time(pSrc_filename, &dos_time, &dos_date))
return MZ_FALSE;
pSrc_file = MZ_FOPEN(pSrc_filename, "rb");
if (!pSrc_file) return MZ_FALSE;
MZ_FSEEK64(pSrc_file, 0, SEEK_END);
uncomp_size = MZ_FTELL64(pSrc_file);
MZ_FSEEK64(pSrc_file, 0, SEEK_SET);
if (uncomp_size > 0xFFFFFFFF) {
// No zip64 support yet
MZ_FCLOSE(pSrc_file);
return MZ_FALSE;
}
if (uncomp_size <= 3) level = 0;
if (!mz_zip_writer_write_zeros(
pZip, cur_archive_file_ofs,
num_alignment_padding_bytes + sizeof(local_dir_header))) {
MZ_FCLOSE(pSrc_file);
return MZ_FALSE;
}
local_dir_header_ofs += num_alignment_padding_bytes;
if (pZip->m_file_offset_alignment) {
MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) ==
0);
}
cur_archive_file_ofs +=
num_alignment_padding_bytes + sizeof(local_dir_header);
MZ_CLEAR_OBJ(local_dir_header);
if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name,
archive_name_size) != archive_name_size) {
MZ_FCLOSE(pSrc_file);
return MZ_FALSE;
}
cur_archive_file_ofs += archive_name_size;
if (uncomp_size) {
mz_uint64 uncomp_remaining = uncomp_size;
void *pRead_buf =
pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, MZ_ZIP_MAX_IO_BUF_SIZE);
if (!pRead_buf) {
MZ_FCLOSE(pSrc_file);
return MZ_FALSE;
}
if (!level) {
while (uncomp_remaining) {
mz_uint n =
(mz_uint)MZ_MIN((mz_uint)MZ_ZIP_MAX_IO_BUF_SIZE, uncomp_remaining);
if ((MZ_FREAD(pRead_buf, 1, n, pSrc_file) != n) ||
(pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pRead_buf,
n) != n)) {
pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf);
MZ_FCLOSE(pSrc_file);
return MZ_FALSE;
}
uncomp_crc32 =
(mz_uint32)mz_crc32(uncomp_crc32, (const mz_uint8 *)pRead_buf, n);
uncomp_remaining -= n;
cur_archive_file_ofs += n;
}
comp_size = uncomp_size;
} else {
mz_bool result = MZ_FALSE;
mz_zip_writer_add_state state;
tdefl_compressor *pComp = (tdefl_compressor *)pZip->m_pAlloc(
pZip->m_pAlloc_opaque, 1, sizeof(tdefl_compressor));
if (!pComp) {
pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf);
MZ_FCLOSE(pSrc_file);
return MZ_FALSE;
}
state.m_pZip = pZip;
state.m_cur_archive_file_ofs = cur_archive_file_ofs;
state.m_comp_size = 0;
if (tdefl_init(pComp, mz_zip_writer_add_put_buf_callback, &state,
tdefl_create_comp_flags_from_zip_params(
level, -15, MZ_DEFAULT_STRATEGY)) !=
TDEFL_STATUS_OKAY) {
pZip->m_pFree(pZip->m_pAlloc_opaque, pComp);
pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf);
MZ_FCLOSE(pSrc_file);
return MZ_FALSE;
}
for (;;) {
size_t in_buf_size = (mz_uint32)MZ_MIN(uncomp_remaining,
(mz_uint)MZ_ZIP_MAX_IO_BUF_SIZE);
tdefl_status status;
if (MZ_FREAD(pRead_buf, 1, in_buf_size, pSrc_file) != in_buf_size)
break;
uncomp_crc32 = (mz_uint32)mz_crc32(
uncomp_crc32, (const mz_uint8 *)pRead_buf, in_buf_size);
uncomp_remaining -= in_buf_size;
status = tdefl_compress_buffer(
pComp, pRead_buf, in_buf_size,
uncomp_remaining ? TDEFL_NO_FLUSH : TDEFL_FINISH);
if (status == TDEFL_STATUS_DONE) {
result = MZ_TRUE;
break;
} else if (status != TDEFL_STATUS_OKAY)
break;
}
pZip->m_pFree(pZip->m_pAlloc_opaque, pComp);
if (!result) {
pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf);
MZ_FCLOSE(pSrc_file);
return MZ_FALSE;
}
comp_size = state.m_comp_size;
cur_archive_file_ofs = state.m_cur_archive_file_ofs;
method = MZ_DEFLATED;
}
pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf);
}
MZ_FCLOSE(pSrc_file);
pSrc_file = NULL;
// no zip64 support yet
if ((comp_size > 0xFFFFFFFF) || (cur_archive_file_ofs > 0xFFFFFFFF))
return MZ_FALSE;
if (!mz_zip_writer_create_local_dir_header(
pZip, local_dir_header, (mz_uint16)archive_name_size, 0, uncomp_size,
comp_size, uncomp_crc32, method, 0, dos_time, dos_date))
return MZ_FALSE;
if (pZip->m_pWrite(pZip->m_pIO_opaque, local_dir_header_ofs, local_dir_header,
sizeof(local_dir_header)) != sizeof(local_dir_header))
return MZ_FALSE;
if (!mz_zip_writer_add_to_central_dir(
pZip, pArchive_name, (mz_uint16)archive_name_size, NULL, 0, pComment,
comment_size, uncomp_size, comp_size, uncomp_crc32, method, 0,
dos_time, dos_date, local_dir_header_ofs, ext_attributes))
return MZ_FALSE;
pZip->m_total_files++;
pZip->m_archive_size = cur_archive_file_ofs;
return MZ_TRUE;
}
#endif // #ifndef MINIZ_NO_STDIO
mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip,
mz_zip_archive *pSource_zip,
mz_uint file_index) {
mz_uint n, bit_flags, num_alignment_padding_bytes;
mz_uint64 comp_bytes_remaining, local_dir_header_ofs;
mz_uint64 cur_src_file_ofs, cur_dst_file_ofs;
mz_uint32
local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) /
sizeof(mz_uint32)];
mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32;
mz_uint8 central_header[MZ_ZIP_CENTRAL_DIR_HEADER_SIZE];
size_t orig_central_dir_size;
mz_zip_internal_state *pState;
void *pBuf;
const mz_uint8 *pSrc_central_header;
if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING))
return MZ_FALSE;
if (NULL ==
(pSrc_central_header = mz_zip_reader_get_cdh(pSource_zip, file_index)))
return MZ_FALSE;
pState = pZip->m_pState;
num_alignment_padding_bytes =
mz_zip_writer_compute_padding_needed_for_file_alignment(pZip);
// no zip64 support yet
if ((pZip->m_total_files == 0xFFFF) ||
((pZip->m_archive_size + num_alignment_padding_bytes +
MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) >
0xFFFFFFFF))
return MZ_FALSE;
cur_src_file_ofs =
MZ_READ_LE32(pSrc_central_header + MZ_ZIP_CDH_LOCAL_HEADER_OFS);
cur_dst_file_ofs = pZip->m_archive_size;
if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs,
pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) !=
MZ_ZIP_LOCAL_DIR_HEADER_SIZE)
return MZ_FALSE;
if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG)
return MZ_FALSE;
cur_src_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE;
if (!mz_zip_writer_write_zeros(pZip, cur_dst_file_ofs,
num_alignment_padding_bytes))
return MZ_FALSE;
cur_dst_file_ofs += num_alignment_padding_bytes;
local_dir_header_ofs = cur_dst_file_ofs;
if (pZip->m_file_offset_alignment) {
MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) ==
0);
}
if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pLocal_header,
MZ_ZIP_LOCAL_DIR_HEADER_SIZE) !=
MZ_ZIP_LOCAL_DIR_HEADER_SIZE)
return MZ_FALSE;
cur_dst_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE;
n = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) +
MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS);
comp_bytes_remaining =
n + MZ_READ_LE32(pSrc_central_header + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS);
if (NULL == (pBuf = pZip->m_pAlloc(
pZip->m_pAlloc_opaque, 1,
(size_t)MZ_MAX(sizeof(mz_uint32) * 4,
MZ_MIN((mz_uint)MZ_ZIP_MAX_IO_BUF_SIZE,
comp_bytes_remaining)))))
return MZ_FALSE;
while (comp_bytes_remaining) {
n = (mz_uint)MZ_MIN((mz_uint)MZ_ZIP_MAX_IO_BUF_SIZE, comp_bytes_remaining);
if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf,
n) != n) {
pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf);
return MZ_FALSE;
}
cur_src_file_ofs += n;
if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pBuf, n) != n) {
pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf);
return MZ_FALSE;
}
cur_dst_file_ofs += n;
comp_bytes_remaining -= n;
}
bit_flags = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_BIT_FLAG_OFS);
if (bit_flags & 8) {
// Copy data descriptor
if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf,
sizeof(mz_uint32) * 4) != sizeof(mz_uint32) * 4) {
pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf);
return MZ_FALSE;
}
n = sizeof(mz_uint32) * ((MZ_READ_LE32(pBuf) == 0x08074b50) ? 4 : 3);
if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pBuf, n) != n) {
pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf);
return MZ_FALSE;
}
cur_src_file_ofs += n;
cur_dst_file_ofs += n;
}
pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf);
// no zip64 support yet
if (cur_dst_file_ofs > 0xFFFFFFFF) return MZ_FALSE;
orig_central_dir_size = pState->m_central_dir.m_size;
memcpy(central_header, pSrc_central_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE);
MZ_WRITE_LE32(central_header + MZ_ZIP_CDH_LOCAL_HEADER_OFS,
local_dir_header_ofs);
if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, central_header,
MZ_ZIP_CENTRAL_DIR_HEADER_SIZE))
return MZ_FALSE;
n = MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_FILENAME_LEN_OFS) +
MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_EXTRA_LEN_OFS) +
MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_COMMENT_LEN_OFS);
if (!mz_zip_array_push_back(
pZip, &pState->m_central_dir,
pSrc_central_header + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n)) {
mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size,
MZ_FALSE);
return MZ_FALSE;
}
if (pState->m_central_dir.m_size > 0xFFFFFFFF) return MZ_FALSE;
n = (mz_uint32)orig_central_dir_size;
if (!mz_zip_array_push_back(pZip, &pState->m_central_dir_offsets, &n, 1)) {
mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size,
MZ_FALSE);
return MZ_FALSE;
}
pZip->m_total_files++;
pZip->m_archive_size = cur_dst_file_ofs;
return MZ_TRUE;
}
mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip) {
mz_zip_internal_state *pState;
mz_uint64 central_dir_ofs, central_dir_size;
mz_uint8 hdr[MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE];
if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING))
return MZ_FALSE;
pState = pZip->m_pState;
// no zip64 support yet
if ((pZip->m_total_files > 0xFFFF) ||
((pZip->m_archive_size + pState->m_central_dir.m_size +
MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) > 0xFFFFFFFF))
return MZ_FALSE;
central_dir_ofs = 0;
central_dir_size = 0;
if (pZip->m_total_files) {
// Write central directory
central_dir_ofs = pZip->m_archive_size;
central_dir_size = pState->m_central_dir.m_size;
pZip->m_central_directory_file_ofs = central_dir_ofs;
if (pZip->m_pWrite(pZip->m_pIO_opaque, central_dir_ofs,
pState->m_central_dir.m_p,
(size_t)central_dir_size) != central_dir_size)
return MZ_FALSE;
pZip->m_archive_size += central_dir_size;
}
// Write end of central directory record
MZ_CLEAR_OBJ(hdr);
MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_SIG_OFS,
MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG);
MZ_WRITE_LE16(hdr + MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS,
pZip->m_total_files);
MZ_WRITE_LE16(hdr + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS, pZip->m_total_files);
MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_CDIR_SIZE_OFS, central_dir_size);
MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_CDIR_OFS_OFS, central_dir_ofs);
if (pZip->m_pWrite(pZip->m_pIO_opaque, pZip->m_archive_size, hdr,
sizeof(hdr)) != sizeof(hdr))
return MZ_FALSE;
#ifndef MINIZ_NO_STDIO
if ((pState->m_pFile) && (MZ_FFLUSH(pState->m_pFile) == EOF)) return MZ_FALSE;
#endif // #ifndef MINIZ_NO_STDIO
pZip->m_archive_size += sizeof(hdr);
pZip->m_zip_mode = MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED;
return MZ_TRUE;
}
mz_bool mz_zip_writer_finalize_heap_archive(mz_zip_archive *pZip, void **pBuf,
size_t *pSize) {
if ((!pZip) || (!pZip->m_pState) || (!pBuf) || (!pSize)) return MZ_FALSE;
if (pZip->m_pWrite != mz_zip_heap_write_func) return MZ_FALSE;
if (!mz_zip_writer_finalize_archive(pZip)) return MZ_FALSE;
*pBuf = pZip->m_pState->m_pMem;
*pSize = pZip->m_pState->m_mem_size;
pZip->m_pState->m_pMem = NULL;
pZip->m_pState->m_mem_size = pZip->m_pState->m_mem_capacity = 0;
return MZ_TRUE;
}
mz_bool mz_zip_writer_end(mz_zip_archive *pZip) {
mz_zip_internal_state *pState;
mz_bool status = MZ_TRUE;
if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) ||
((pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) &&
(pZip->m_zip_mode != MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED)))
return MZ_FALSE;
pState = pZip->m_pState;
pZip->m_pState = NULL;
mz_zip_array_clear(pZip, &pState->m_central_dir);
mz_zip_array_clear(pZip, &pState->m_central_dir_offsets);
mz_zip_array_clear(pZip, &pState->m_sorted_central_dir_offsets);
#ifndef MINIZ_NO_STDIO
if (pState->m_pFile) {
MZ_FCLOSE(pState->m_pFile);
pState->m_pFile = NULL;
}
#endif // #ifndef MINIZ_NO_STDIO
if ((pZip->m_pWrite == mz_zip_heap_write_func) && (pState->m_pMem)) {
pZip->m_pFree(pZip->m_pAlloc_opaque, pState->m_pMem);
pState->m_pMem = NULL;
}
pZip->m_pFree(pZip->m_pAlloc_opaque, pState);
pZip->m_zip_mode = MZ_ZIP_MODE_INVALID;
return status;
}
#ifndef MINIZ_NO_STDIO
mz_bool mz_zip_add_mem_to_archive_file_in_place(
const char *pZip_filename, const char *pArchive_name, const void *pBuf,
size_t buf_size, const void *pComment, mz_uint16 comment_size,
mz_uint level_and_flags) {
mz_bool status, created_new_archive = MZ_FALSE;
mz_zip_archive zip_archive;
struct MZ_FILE_STAT_STRUCT file_stat;
MZ_CLEAR_OBJ(zip_archive);
if ((int)level_and_flags < 0) level_and_flags = MZ_DEFAULT_LEVEL;
if ((!pZip_filename) || (!pArchive_name) || ((buf_size) && (!pBuf)) ||
((comment_size) && (!pComment)) ||
((level_and_flags & 0xF) > MZ_UBER_COMPRESSION))
return MZ_FALSE;
if (!mz_zip_writer_validate_archive_name(pArchive_name)) return MZ_FALSE;
if (MZ_FILE_STAT(pZip_filename, &file_stat) != 0) {
// Create a new archive.
if (!mz_zip_writer_init_file(&zip_archive, pZip_filename, 0))
return MZ_FALSE;
created_new_archive = MZ_TRUE;
} else {
// Append to an existing archive.
if (!mz_zip_reader_init_file(
&zip_archive, pZip_filename,
level_and_flags | MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY))
return MZ_FALSE;
if (!mz_zip_writer_init_from_reader(&zip_archive, pZip_filename)) {
mz_zip_reader_end(&zip_archive);
return MZ_FALSE;
}
}
status =
mz_zip_writer_add_mem_ex(&zip_archive, pArchive_name, pBuf, buf_size,
pComment, comment_size, level_and_flags, 0, 0);
// Always finalize, even if adding failed for some reason, so we have a valid
// central directory. (This may not always succeed, but we can try.)
if (!mz_zip_writer_finalize_archive(&zip_archive)) status = MZ_FALSE;
if (!mz_zip_writer_end(&zip_archive)) status = MZ_FALSE;
if ((!status) && (created_new_archive)) {
// It's a new archive and something went wrong, so just delete it.
int ignoredStatus = MZ_DELETE_FILE(pZip_filename);
(void)ignoredStatus;
}
return status;
}
void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename,
const char *pArchive_name,
size_t *pSize, mz_uint flags) {
int file_index;
mz_zip_archive zip_archive;
void *p = NULL;
if (pSize) *pSize = 0;
if ((!pZip_filename) || (!pArchive_name)) return NULL;
MZ_CLEAR_OBJ(zip_archive);
if (!mz_zip_reader_init_file(
&zip_archive, pZip_filename,
flags | MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY))
return NULL;
if ((file_index = mz_zip_reader_locate_file(&zip_archive, pArchive_name, NULL,
flags)) >= 0)
p = mz_zip_reader_extract_to_heap(&zip_archive, file_index, pSize, flags);
mz_zip_reader_end(&zip_archive);
return p;
}
#endif // #ifndef MINIZ_NO_STDIO
#endif // #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS
#endif // #ifndef MINIZ_NO_ARCHIVE_APIS
#ifdef __cplusplus
}
#endif
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#endif // MINIZ_HEADER_FILE_ONLY
/*
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
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 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.
For more information, please refer to <http://unlicense.org/>
*/
// ---------------------- end of miniz ----------------------------------------
#ifdef __clang__
#pragma clang diagnostic pop
#endif
} // namespace miniz
#else
// Reuse MINIZ_LITTE_ENDIAN macro
#if defined(_M_IX86) || defined(_M_X64) || defined(__i386__) || \
defined(__i386) || defined(__i486__) || defined(__i486) || \
defined(i386) || defined(__ia64__) || defined(__x86_64__)
// MINIZ_X86_OR_X64_CPU is only used to help set the below macros.
#define MINIZ_X86_OR_X64_CPU 1
#endif
#if defined(__sparcv9)
// Big endian
#else
#if (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) || MINIZ_X86_OR_X64_CPU
// Set MINIZ_LITTLE_ENDIAN to 1 if the processor is little endian.
#define MINIZ_LITTLE_ENDIAN 1
#endif
#endif
#endif // TINYEXR_USE_MINIZ
// static bool IsBigEndian(void) {
// union {
// unsigned int i;
// char c[4];
// } bint = {0x01020304};
//
// return bint.c[0] == 1;
//}
static void SetErrorMessage(const std::string &msg, const char **err) {
if (err) {
#ifdef _WIN32
(*err) = _strdup(msg.c_str());
#else
(*err) = strdup(msg.c_str());
#endif
}
}
static const int kEXRVersionSize = 8;
static void cpy2(unsigned short *dst_val, const unsigned short *src_val) {
unsigned char *dst = reinterpret_cast<unsigned char *>(dst_val);
const unsigned char *src = reinterpret_cast<const unsigned char *>(src_val);
dst[0] = src[0];
dst[1] = src[1];
}
static void swap2(unsigned short *val) {
#ifdef MINIZ_LITTLE_ENDIAN
(void)val;
#else
unsigned short tmp = *val;
unsigned char *dst = reinterpret_cast<unsigned char *>(val);
unsigned char *src = reinterpret_cast<unsigned char *>(&tmp);
dst[0] = src[1];
dst[1] = src[0];
#endif
}
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-function"
#endif
#ifdef __GNUC__
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-function"
#endif
static void cpy4(int *dst_val, const int *src_val) {
unsigned char *dst = reinterpret_cast<unsigned char *>(dst_val);
const unsigned char *src = reinterpret_cast<const unsigned char *>(src_val);
dst[0] = src[0];
dst[1] = src[1];
dst[2] = src[2];
dst[3] = src[3];
}
static void cpy4(unsigned int *dst_val, const unsigned int *src_val) {
unsigned char *dst = reinterpret_cast<unsigned char *>(dst_val);
const unsigned char *src = reinterpret_cast<const unsigned char *>(src_val);
dst[0] = src[0];
dst[1] = src[1];
dst[2] = src[2];
dst[3] = src[3];
}
static void cpy4(float *dst_val, const float *src_val) {
unsigned char *dst = reinterpret_cast<unsigned char *>(dst_val);
const unsigned char *src = reinterpret_cast<const unsigned char *>(src_val);
dst[0] = src[0];
dst[1] = src[1];
dst[2] = src[2];
dst[3] = src[3];
}
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#ifdef __GNUC__
#pragma GCC diagnostic pop
#endif
static void swap4(unsigned int *val) {
#ifdef MINIZ_LITTLE_ENDIAN
(void)val;
#else
unsigned int tmp = *val;
unsigned char *dst = reinterpret_cast<unsigned char *>(val);
unsigned char *src = reinterpret_cast<unsigned char *>(&tmp);
dst[0] = src[3];
dst[1] = src[2];
dst[2] = src[1];
dst[3] = src[0];
#endif
}
static void swap4(int *val) {
#ifdef MINIZ_LITTLE_ENDIAN
(void)val;
#else
int tmp = *val;
unsigned char *dst = reinterpret_cast<unsigned char *>(val);
unsigned char *src = reinterpret_cast<unsigned char *>(&tmp);
dst[0] = src[3];
dst[1] = src[2];
dst[2] = src[1];
dst[3] = src[0];
#endif
}
static void swap4(float *val) {
#ifdef MINIZ_LITTLE_ENDIAN
(void)val;
#else
float tmp = *val;
unsigned char *dst = reinterpret_cast<unsigned char *>(val);
unsigned char *src = reinterpret_cast<unsigned char *>(&tmp);
dst[0] = src[3];
dst[1] = src[2];
dst[2] = src[1];
dst[3] = src[0];
#endif
}
#if 0
static void cpy8(tinyexr::tinyexr_uint64 *dst_val, const tinyexr::tinyexr_uint64 *src_val) {
unsigned char *dst = reinterpret_cast<unsigned char *>(dst_val);
const unsigned char *src = reinterpret_cast<const unsigned char *>(src_val);
dst[0] = src[0];
dst[1] = src[1];
dst[2] = src[2];
dst[3] = src[3];
dst[4] = src[4];
dst[5] = src[5];
dst[6] = src[6];
dst[7] = src[7];
}
#endif
static void swap8(tinyexr::tinyexr_uint64 *val) {
#ifdef MINIZ_LITTLE_ENDIAN
(void)val;
#else
tinyexr::tinyexr_uint64 tmp = (*val);
unsigned char *dst = reinterpret_cast<unsigned char *>(val);
unsigned char *src = reinterpret_cast<unsigned char *>(&tmp);
dst[0] = src[7];
dst[1] = src[6];
dst[2] = src[5];
dst[3] = src[4];
dst[4] = src[3];
dst[5] = src[2];
dst[6] = src[1];
dst[7] = src[0];
#endif
}
// https://gist.github.com/rygorous/2156668
// Reuse MINIZ_LITTLE_ENDIAN flag from miniz.
union FP32 {
unsigned int u;
float f;
struct {
#if MINIZ_LITTLE_ENDIAN
unsigned int Mantissa : 23;
unsigned int Exponent : 8;
unsigned int Sign : 1;
#else
unsigned int Sign : 1;
unsigned int Exponent : 8;
unsigned int Mantissa : 23;
#endif
} s;
};
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wpadded"
#endif
union FP16 {
unsigned short u;
struct {
#if MINIZ_LITTLE_ENDIAN
unsigned int Mantissa : 10;
unsigned int Exponent : 5;
unsigned int Sign : 1;
#else
unsigned int Sign : 1;
unsigned int Exponent : 5;
unsigned int Mantissa : 10;
#endif
} s;
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
static FP32 half_to_float(FP16 h) {
static const FP32 magic = {113 << 23};
static const unsigned int shifted_exp = 0x7c00
<< 13; // exponent mask after shift
FP32 o;
o.u = (h.u & 0x7fffU) << 13U; // exponent/mantissa bits
unsigned int exp_ = shifted_exp & o.u; // just the exponent
o.u += (127 - 15) << 23; // exponent adjust
// handle exponent special cases
if (exp_ == shifted_exp) // Inf/NaN?
o.u += (128 - 16) << 23; // extra exp adjust
else if (exp_ == 0) // Zero/Denormal?
{
o.u += 1 << 23; // extra exp adjust
o.f -= magic.f; // renormalize
}
o.u |= (h.u & 0x8000U) << 16U; // sign bit
return o;
}
static FP16 float_to_half_full(FP32 f) {
FP16 o = {0};
// Based on ISPC reference code (with minor modifications)
if (f.s.Exponent == 0) // Signed zero/denormal (which will underflow)
o.s.Exponent = 0;
else if (f.s.Exponent == 255) // Inf or NaN (all exponent bits set)
{
o.s.Exponent = 31;
o.s.Mantissa = f.s.Mantissa ? 0x200 : 0; // NaN->qNaN and Inf->Inf
} else // Normalized number
{
// Exponent unbias the single, then bias the halfp
int newexp = f.s.Exponent - 127 + 15;
if (newexp >= 31) // Overflow, return signed infinity
o.s.Exponent = 31;
else if (newexp <= 0) // Underflow
{
if ((14 - newexp) <= 24) // Mantissa might be non-zero
{
unsigned int mant = f.s.Mantissa | 0x800000; // Hidden 1 bit
o.s.Mantissa = mant >> (14 - newexp);
if ((mant >> (13 - newexp)) & 1) // Check for rounding
o.u++; // Round, might overflow into exp bit, but this is OK
}
} else {
o.s.Exponent = static_cast<unsigned int>(newexp);
o.s.Mantissa = f.s.Mantissa >> 13;
if (f.s.Mantissa & 0x1000) // Check for rounding
o.u++; // Round, might overflow to inf, this is OK
}
}
o.s.Sign = f.s.Sign;
return o;
}
// NOTE: From OpenEXR code
// #define IMF_INCREASING_Y 0
// #define IMF_DECREASING_Y 1
// #define IMF_RAMDOM_Y 2
//
// #define IMF_NO_COMPRESSION 0
// #define IMF_RLE_COMPRESSION 1
// #define IMF_ZIPS_COMPRESSION 2
// #define IMF_ZIP_COMPRESSION 3
// #define IMF_PIZ_COMPRESSION 4
// #define IMF_PXR24_COMPRESSION 5
// #define IMF_B44_COMPRESSION 6
// #define IMF_B44A_COMPRESSION 7
#ifdef __clang__
#pragma clang diagnostic push
#if __has_warning("-Wzero-as-null-pointer-constant")
#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant"
#endif
#endif
static const char *ReadString(std::string *s, const char *ptr, size_t len) {
// Read untile NULL(\0).
const char *p = ptr;
const char *q = ptr;
while ((size_t(q - ptr) < len) && (*q) != 0) {
q++;
}
if (size_t(q - ptr) >= len) {
(*s) = std::string();
return NULL;
}
(*s) = std::string(p, q);
return q + 1; // skip '\0'
}
static bool ReadAttribute(std::string *name, std::string *type,
std::vector<unsigned char> *data, size_t *marker_size,
const char *marker, size_t size) {
size_t name_len = strnlen(marker, size);
if (name_len == size) {
// String does not have a terminating character.
return false;
}
*name = std::string(marker, name_len);
marker += name_len + 1;
size -= name_len + 1;
size_t type_len = strnlen(marker, size);
if (type_len == size) {
return false;
}
*type = std::string(marker, type_len);
marker += type_len + 1;
size -= type_len + 1;
if (size < sizeof(uint32_t)) {
return false;
}
uint32_t data_len;
memcpy(&data_len, marker, sizeof(uint32_t));
tinyexr::swap4(reinterpret_cast<unsigned int *>(&data_len));
if (data_len == 0) {
if ((*type).compare("string") == 0) {
// Accept empty string attribute.
marker += sizeof(uint32_t);
size -= sizeof(uint32_t);
*marker_size = name_len + 1 + type_len + 1 + sizeof(uint32_t);
data->resize(1);
(*data)[0] = '\0';
return true;
} else {
return false;
}
}
marker += sizeof(uint32_t);
size -= sizeof(uint32_t);
if (size < data_len) {
return false;
}
data->resize(static_cast<size_t>(data_len));
memcpy(&data->at(0), marker, static_cast<size_t>(data_len));
*marker_size = name_len + 1 + type_len + 1 + sizeof(uint32_t) + data_len;
return true;
}
static void WriteAttributeToMemory(std::vector<unsigned char> *out,
const char *name, const char *type,
const unsigned char *data, int len) {
out->insert(out->end(), name, name + strlen(name) + 1);
out->insert(out->end(), type, type + strlen(type) + 1);
int outLen = len;
tinyexr::swap4(&outLen);
out->insert(out->end(), reinterpret_cast<unsigned char *>(&outLen),
reinterpret_cast<unsigned char *>(&outLen) + sizeof(int));
out->insert(out->end(), data, data + len);
}
typedef struct {
std::string name; // less than 255 bytes long
int pixel_type;
int requested_pixel_type;
int x_sampling;
int y_sampling;
unsigned char p_linear;
unsigned char pad[3];
} ChannelInfo;
typedef struct {
int min_x;
int min_y;
int max_x;
int max_y;
} Box2iInfo;
struct HeaderInfo {
std::vector<tinyexr::ChannelInfo> channels;
std::vector<EXRAttribute> attributes;
Box2iInfo data_window;
int line_order;
Box2iInfo display_window;
float screen_window_center[2];
float screen_window_width;
float pixel_aspect_ratio;
int chunk_count;
// Tiled format
int tiled; // Non-zero if the part is tiled.
int tile_size_x;
int tile_size_y;
int tile_level_mode;
int tile_rounding_mode;
unsigned int header_len;
int compression_type;
// required for multi-part or non-image files
std::string name;
// required for multi-part or non-image files
std::string type;
void clear() {
channels.clear();
attributes.clear();
data_window.min_x = 0;
data_window.min_y = 0;
data_window.max_x = 0;
data_window.max_y = 0;
line_order = 0;
display_window.min_x = 0;
display_window.min_y = 0;
display_window.max_x = 0;
display_window.max_y = 0;
screen_window_center[0] = 0.0f;
screen_window_center[1] = 0.0f;
screen_window_width = 0.0f;
pixel_aspect_ratio = 0.0f;
chunk_count = 0;
// Tiled format
tiled = 0;
tile_size_x = 0;
tile_size_y = 0;
tile_level_mode = 0;
tile_rounding_mode = 0;
header_len = 0;
compression_type = 0;
name.clear();
type.clear();
}
};
static bool ReadChannelInfo(std::vector<ChannelInfo> &channels,
const std::vector<unsigned char> &data) {
const char *p = reinterpret_cast<const char *>(&data.at(0));
for (;;) {
if ((*p) == 0) {
break;
}
ChannelInfo info;
tinyexr_int64 data_len = static_cast<tinyexr_int64>(data.size()) -
(p - reinterpret_cast<const char *>(data.data()));
if (data_len < 0) {
return false;
}
p = ReadString(&info.name, p, size_t(data_len));
if ((p == NULL) && (info.name.empty())) {
// Buffer overrun. Issue #51.
return false;
}
const unsigned char *data_end =
reinterpret_cast<const unsigned char *>(p) + 16;
if (data_end >= (data.data() + data.size())) {
return false;
}
memcpy(&info.pixel_type, p, sizeof(int));
p += 4;
info.p_linear = static_cast<unsigned char>(p[0]); // uchar
p += 1 + 3; // reserved: uchar[3]
memcpy(&info.x_sampling, p, sizeof(int)); // int
p += 4;
memcpy(&info.y_sampling, p, sizeof(int)); // int
p += 4;
tinyexr::swap4(&info.pixel_type);
tinyexr::swap4(&info.x_sampling);
tinyexr::swap4(&info.y_sampling);
channels.push_back(info);
}
return true;
}
static void WriteChannelInfo(std::vector<unsigned char> &data,
const std::vector<ChannelInfo> &channels) {
size_t sz = 0;
// Calculate total size.
for (size_t c = 0; c < channels.size(); c++) {
sz += strlen(channels[c].name.c_str()) + 1; // +1 for \0
sz += 16; // 4 * int
}
data.resize(sz + 1);
unsigned char *p = &data.at(0);
for (size_t c = 0; c < channels.size(); c++) {
memcpy(p, channels[c].name.c_str(), strlen(channels[c].name.c_str()));
p += strlen(channels[c].name.c_str());
(*p) = '\0';
p++;
int pixel_type = channels[c].requested_pixel_type;
int x_sampling = channels[c].x_sampling;
int y_sampling = channels[c].y_sampling;
tinyexr::swap4(&pixel_type);
tinyexr::swap4(&x_sampling);
tinyexr::swap4(&y_sampling);
memcpy(p, &pixel_type, sizeof(int));
p += sizeof(int);
(*p) = channels[c].p_linear;
p += 4;
memcpy(p, &x_sampling, sizeof(int));
p += sizeof(int);
memcpy(p, &y_sampling, sizeof(int));
p += sizeof(int);
}
(*p) = '\0';
}
static void CompressZip(unsigned char *dst,
tinyexr::tinyexr_uint64 &compressedSize,
const unsigned char *src, unsigned long src_size) {
std::vector<unsigned char> tmpBuf(src_size);
//
// Apply EXR-specific? postprocess. Grabbed from OpenEXR's
// ImfZipCompressor.cpp
//
//
// Reorder the pixel data.
//
const char *srcPtr = reinterpret_cast<const char *>(src);
{
char *t1 = reinterpret_cast<char *>(&tmpBuf.at(0));
char *t2 = reinterpret_cast<char *>(&tmpBuf.at(0)) + (src_size + 1) / 2;
const char *stop = srcPtr + src_size;
for (;;) {
if (srcPtr < stop)
*(t1++) = *(srcPtr++);
else
break;
if (srcPtr < stop)
*(t2++) = *(srcPtr++);
else
break;
}
}
//
// Predictor.
//
{
unsigned char *t = &tmpBuf.at(0) + 1;
unsigned char *stop = &tmpBuf.at(0) + src_size;
int p = t[-1];
while (t < stop) {
int d = int(t[0]) - p + (128 + 256);
p = t[0];
t[0] = static_cast<unsigned char>(d);
++t;
}
}
#if TINYEXR_USE_MINIZ
//
// Compress the data using miniz
//
miniz::mz_ulong outSize = miniz::mz_compressBound(src_size);
int ret = miniz::mz_compress(
dst, &outSize, static_cast<const unsigned char *>(&tmpBuf.at(0)),
src_size);
assert(ret == miniz::MZ_OK);
(void)ret;
compressedSize = outSize;
#else
uLong outSize = compressBound(static_cast<uLong>(src_size));
int ret = compress(dst, &outSize, static_cast<const Bytef *>(&tmpBuf.at(0)),
src_size);
assert(ret == Z_OK);
compressedSize = outSize;
#endif
// Use uncompressed data when compressed data is larger than uncompressed.
// (Issue 40)
if (compressedSize >= src_size) {
compressedSize = src_size;
memcpy(dst, src, src_size);
}
}
static bool DecompressZip(unsigned char *dst,
unsigned long *uncompressed_size /* inout */,
const unsigned char *src, unsigned long src_size) {
if ((*uncompressed_size) == src_size) {
// Data is not compressed(Issue 40).
memcpy(dst, src, src_size);
return true;
}
std::vector<unsigned char> tmpBuf(*uncompressed_size);
#if TINYEXR_USE_MINIZ
int ret =
miniz::mz_uncompress(&tmpBuf.at(0), uncompressed_size, src, src_size);
if (miniz::MZ_OK != ret) {
return false;
}
#else
int ret = uncompress(&tmpBuf.at(0), uncompressed_size, src, src_size);
if (Z_OK != ret) {
return false;
}
#endif
//
// Apply EXR-specific? postprocess. Grabbed from OpenEXR's
// ImfZipCompressor.cpp
//
// Predictor.
{
unsigned char *t = &tmpBuf.at(0) + 1;
unsigned char *stop = &tmpBuf.at(0) + (*uncompressed_size);
while (t < stop) {
int d = int(t[-1]) + int(t[0]) - 128;
t[0] = static_cast<unsigned char>(d);
++t;
}
}
// Reorder the pixel data.
{
const char *t1 = reinterpret_cast<const char *>(&tmpBuf.at(0));
const char *t2 = reinterpret_cast<const char *>(&tmpBuf.at(0)) +
(*uncompressed_size + 1) / 2;
char *s = reinterpret_cast<char *>(dst);
char *stop = s + (*uncompressed_size);
for (;;) {
if (s < stop)
*(s++) = *(t1++);
else
break;
if (s < stop)
*(s++) = *(t2++);
else
break;
}
}
return true;
}
// RLE code from OpenEXR --------------------------------------
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wsign-conversion"
#if __has_warning("-Wextra-semi-stmt")
#pragma clang diagnostic ignored "-Wextra-semi-stmt"
#endif
#endif
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable : 4204) // nonstandard extension used : non-constant
// aggregate initializer (also supported by GNU
// C and C99, so no big deal)
#pragma warning(disable : 4244) // 'initializing': conversion from '__int64' to
// 'int', possible loss of data
#pragma warning(disable : 4267) // 'argument': conversion from '__int64' to
// 'int', possible loss of data
#pragma warning(disable : 4996) // 'strdup': The POSIX name for this item is
// deprecated. Instead, use the ISO C and C++
// conformant name: _strdup.
#endif
const int MIN_RUN_LENGTH = 3;
const int MAX_RUN_LENGTH = 127;
//
// Compress an array of bytes, using run-length encoding,
// and return the length of the compressed data.
//
static int rleCompress(int inLength, const char in[], signed char out[]) {
const char *inEnd = in + inLength;
const char *runStart = in;
const char *runEnd = in + 1;
signed char *outWrite = out;
while (runStart < inEnd) {
while (runEnd < inEnd && *runStart == *runEnd &&
runEnd - runStart - 1 < MAX_RUN_LENGTH) {
++runEnd;
}
if (runEnd - runStart >= MIN_RUN_LENGTH) {
//
// Compressible run
//
*outWrite++ = static_cast<char>(runEnd - runStart) - 1;
*outWrite++ = *(reinterpret_cast<const signed char *>(runStart));
runStart = runEnd;
} else {
//
// Uncompressable run
//
while (runEnd < inEnd &&
((runEnd + 1 >= inEnd || *runEnd != *(runEnd + 1)) ||
(runEnd + 2 >= inEnd || *(runEnd + 1) != *(runEnd + 2))) &&
runEnd - runStart < MAX_RUN_LENGTH) {
++runEnd;
}
*outWrite++ = static_cast<char>(runStart - runEnd);
while (runStart < runEnd) {
*outWrite++ = *(reinterpret_cast<const signed char *>(runStart++));
}
}
++runEnd;
}
return static_cast<int>(outWrite - out);
}
//
// Uncompress an array of bytes compressed with rleCompress().
// Returns the length of the oncompressed data, or 0 if the
// length of the uncompressed data would be more than maxLength.
//
static int rleUncompress(int inLength, int maxLength, const signed char in[],
char out[]) {
char *outStart = out;
while (inLength > 0) {
if (*in < 0) {
int count = -(static_cast<int>(*in++));
inLength -= count + 1;
// Fixes #116: Add bounds check to in buffer.
if ((0 > (maxLength -= count)) || (inLength < 0)) return 0;
memcpy(out, in, count);
out += count;
in += count;
} else {
int count = *in++;
inLength -= 2;
if (0 > (maxLength -= count + 1)) return 0;
memset(out, *reinterpret_cast<const char *>(in), count + 1);
out += count + 1;
in++;
}
}
return static_cast<int>(out - outStart);
}
#ifdef __clang__
#pragma clang diagnostic pop
#endif
// End of RLE code from OpenEXR -----------------------------------
static void CompressRle(unsigned char *dst,
tinyexr::tinyexr_uint64 &compressedSize,
const unsigned char *src, unsigned long src_size) {
std::vector<unsigned char> tmpBuf(src_size);
//
// Apply EXR-specific? postprocess. Grabbed from OpenEXR's
// ImfRleCompressor.cpp
//
//
// Reorder the pixel data.
//
const char *srcPtr = reinterpret_cast<const char *>(src);
{
char *t1 = reinterpret_cast<char *>(&tmpBuf.at(0));
char *t2 = reinterpret_cast<char *>(&tmpBuf.at(0)) + (src_size + 1) / 2;
const char *stop = srcPtr + src_size;
for (;;) {
if (srcPtr < stop)
*(t1++) = *(srcPtr++);
else
break;
if (srcPtr < stop)
*(t2++) = *(srcPtr++);
else
break;
}
}
//
// Predictor.
//
{
unsigned char *t = &tmpBuf.at(0) + 1;
unsigned char *stop = &tmpBuf.at(0) + src_size;
int p = t[-1];
while (t < stop) {
int d = int(t[0]) - p + (128 + 256);
p = t[0];
t[0] = static_cast<unsigned char>(d);
++t;
}
}
// outSize will be (srcSiz * 3) / 2 at max.
int outSize = rleCompress(static_cast<int>(src_size),
reinterpret_cast<const char *>(&tmpBuf.at(0)),
reinterpret_cast<signed char *>(dst));
assert(outSize > 0);
compressedSize = static_cast<tinyexr::tinyexr_uint64>(outSize);
// Use uncompressed data when compressed data is larger than uncompressed.
// (Issue 40)
if (compressedSize >= src_size) {
compressedSize = src_size;
memcpy(dst, src, src_size);
}
}
static bool DecompressRle(unsigned char *dst,
const unsigned long uncompressed_size,
const unsigned char *src, unsigned long src_size) {
if (uncompressed_size == src_size) {
// Data is not compressed(Issue 40).
memcpy(dst, src, src_size);
return true;
}
// Workaround for issue #112.
// TODO(syoyo): Add more robust out-of-bounds check in `rleUncompress`.
if (src_size <= 2) {
return false;
}
std::vector<unsigned char> tmpBuf(uncompressed_size);
int ret = rleUncompress(static_cast<int>(src_size),
static_cast<int>(uncompressed_size),
reinterpret_cast<const signed char *>(src),
reinterpret_cast<char *>(&tmpBuf.at(0)));
if (ret != static_cast<int>(uncompressed_size)) {
return false;
}
//
// Apply EXR-specific? postprocess. Grabbed from OpenEXR's
// ImfRleCompressor.cpp
//
// Predictor.
{
unsigned char *t = &tmpBuf.at(0) + 1;
unsigned char *stop = &tmpBuf.at(0) + uncompressed_size;
while (t < stop) {
int d = int(t[-1]) + int(t[0]) - 128;
t[0] = static_cast<unsigned char>(d);
++t;
}
}
// Reorder the pixel data.
{
const char *t1 = reinterpret_cast<const char *>(&tmpBuf.at(0));
const char *t2 = reinterpret_cast<const char *>(&tmpBuf.at(0)) +
(uncompressed_size + 1) / 2;
char *s = reinterpret_cast<char *>(dst);
char *stop = s + uncompressed_size;
for (;;) {
if (s < stop)
*(s++) = *(t1++);
else
break;
if (s < stop)
*(s++) = *(t2++);
else
break;
}
}
return true;
}
#if TINYEXR_USE_PIZ
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wc++11-long-long"
#pragma clang diagnostic ignored "-Wold-style-cast"
#pragma clang diagnostic ignored "-Wpadded"
#pragma clang diagnostic ignored "-Wsign-conversion"
#pragma clang diagnostic ignored "-Wc++11-extensions"
#pragma clang diagnostic ignored "-Wconversion"
#pragma clang diagnostic ignored "-Wc++98-compat-pedantic"
#if __has_warning("-Wcast-qual")
#pragma clang diagnostic ignored "-Wcast-qual"
#endif
#if __has_warning("-Wextra-semi-stmt")
#pragma clang diagnostic ignored "-Wextra-semi-stmt"
#endif
#endif
//
// PIZ compress/uncompress, based on OpenEXR's ImfPizCompressor.cpp
//
// -----------------------------------------------------------------
// Copyright (c) 2004, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC)
// (3 clause BSD license)
//
struct PIZChannelData {
unsigned short *start;
unsigned short *end;
int nx;
int ny;
int ys;
int size;
};
//-----------------------------------------------------------------------------
//
// 16-bit Haar Wavelet encoding and decoding
//
// The source code in this file is derived from the encoding
// and decoding routines written by Christian Rouet for his
// PIZ image file format.
//
//-----------------------------------------------------------------------------
//
// Wavelet basis functions without modulo arithmetic; they produce
// the best compression ratios when the wavelet-transformed data are
// Huffman-encoded, but the wavelet transform works only for 14-bit
// data (untransformed data values must be less than (1 << 14)).
//
inline void wenc14(unsigned short a, unsigned short b, unsigned short &l,
unsigned short &h) {
short as = static_cast<short>(a);
short bs = static_cast<short>(b);
short ms = (as + bs) >> 1;
short ds = as - bs;
l = static_cast<unsigned short>(ms);
h = static_cast<unsigned short>(ds);
}
inline void wdec14(unsigned short l, unsigned short h, unsigned short &a,
unsigned short &b) {
short ls = static_cast<short>(l);
short hs = static_cast<short>(h);
int hi = hs;
int ai = ls + (hi & 1) + (hi >> 1);
short as = static_cast<short>(ai);
short bs = static_cast<short>(ai - hi);
a = static_cast<unsigned short>(as);
b = static_cast<unsigned short>(bs);
}
//
// Wavelet basis functions with modulo arithmetic; they work with full
// 16-bit data, but Huffman-encoding the wavelet-transformed data doesn't
// compress the data quite as well.
//
const int NBITS = 16;
const int A_OFFSET = 1 << (NBITS - 1);
const int M_OFFSET = 1 << (NBITS - 1);
const int MOD_MASK = (1 << NBITS) - 1;
inline void wenc16(unsigned short a, unsigned short b, unsigned short &l,
unsigned short &h) {
int ao = (a + A_OFFSET) & MOD_MASK;
int m = ((ao + b) >> 1);
int d = ao - b;
if (d < 0) m = (m + M_OFFSET) & MOD_MASK;
d &= MOD_MASK;
l = static_cast<unsigned short>(m);
h = static_cast<unsigned short>(d);
}
inline void wdec16(unsigned short l, unsigned short h, unsigned short &a,
unsigned short &b) {
int m = l;
int d = h;
int bb = (m - (d >> 1)) & MOD_MASK;
int aa = (d + bb - A_OFFSET) & MOD_MASK;
b = static_cast<unsigned short>(bb);
a = static_cast<unsigned short>(aa);
}
//
// 2D Wavelet encoding:
//
static void wav2Encode(
unsigned short *in, // io: values are transformed in place
int nx, // i : x size
int ox, // i : x offset
int ny, // i : y size
int oy, // i : y offset
unsigned short mx) // i : maximum in[x][y] value
{
bool w14 = (mx < (1 << 14));
int n = (nx > ny) ? ny : nx;
int p = 1; // == 1 << level
int p2 = 2; // == 1 << (level+1)
//
// Hierarchical loop on smaller dimension n
//
while (p2 <= n) {
unsigned short *py = in;
unsigned short *ey = in + oy * (ny - p2);
int oy1 = oy * p;
int oy2 = oy * p2;
int ox1 = ox * p;
int ox2 = ox * p2;
unsigned short i00, i01, i10, i11;
//
// Y loop
//
for (; py <= ey; py += oy2) {
unsigned short *px = py;
unsigned short *ex = py + ox * (nx - p2);
//
// X loop
//
for (; px <= ex; px += ox2) {
unsigned short *p01 = px + ox1;
unsigned short *p10 = px + oy1;
unsigned short *p11 = p10 + ox1;
//
// 2D wavelet encoding
//
if (w14) {
wenc14(*px, *p01, i00, i01);
wenc14(*p10, *p11, i10, i11);
wenc14(i00, i10, *px, *p10);
wenc14(i01, i11, *p01, *p11);
} else {
wenc16(*px, *p01, i00, i01);
wenc16(*p10, *p11, i10, i11);
wenc16(i00, i10, *px, *p10);
wenc16(i01, i11, *p01, *p11);
}
}
//
// Encode (1D) odd column (still in Y loop)
//
if (nx & p) {
unsigned short *p10 = px + oy1;
if (w14)
wenc14(*px, *p10, i00, *p10);
else
wenc16(*px, *p10, i00, *p10);
*px = i00;
}
}
//
// Encode (1D) odd line (must loop in X)
//
if (ny & p) {
unsigned short *px = py;
unsigned short *ex = py + ox * (nx - p2);
for (; px <= ex; px += ox2) {
unsigned short *p01 = px + ox1;
if (w14)
wenc14(*px, *p01, i00, *p01);
else
wenc16(*px, *p01, i00, *p01);
*px = i00;
}
}
//
// Next level
//
p = p2;
p2 <<= 1;
}
}
//
// 2D Wavelet decoding:
//
static void wav2Decode(
unsigned short *in, // io: values are transformed in place
int nx, // i : x size
int ox, // i : x offset
int ny, // i : y size
int oy, // i : y offset
unsigned short mx) // i : maximum in[x][y] value
{
bool w14 = (mx < (1 << 14));
int n = (nx > ny) ? ny : nx;
int p = 1;
int p2;
//
// Search max level
//
while (p <= n) p <<= 1;
p >>= 1;
p2 = p;
p >>= 1;
//
// Hierarchical loop on smaller dimension n
//
while (p >= 1) {
unsigned short *py = in;
unsigned short *ey = in + oy * (ny - p2);
int oy1 = oy * p;
int oy2 = oy * p2;
int ox1 = ox * p;
int ox2 = ox * p2;
unsigned short i00, i01, i10, i11;
//
// Y loop
//
for (; py <= ey; py += oy2) {
unsigned short *px = py;
unsigned short *ex = py + ox * (nx - p2);
//
// X loop
//
for (; px <= ex; px += ox2) {
unsigned short *p01 = px + ox1;
unsigned short *p10 = px + oy1;
unsigned short *p11 = p10 + ox1;
//
// 2D wavelet decoding
//
if (w14) {
wdec14(*px, *p10, i00, i10);
wdec14(*p01, *p11, i01, i11);
wdec14(i00, i01, *px, *p01);
wdec14(i10, i11, *p10, *p11);
} else {
wdec16(*px, *p10, i00, i10);
wdec16(*p01, *p11, i01, i11);
wdec16(i00, i01, *px, *p01);
wdec16(i10, i11, *p10, *p11);
}
}
//
// Decode (1D) odd column (still in Y loop)
//
if (nx & p) {
unsigned short *p10 = px + oy1;
if (w14)
wdec14(*px, *p10, i00, *p10);
else
wdec16(*px, *p10, i00, *p10);
*px = i00;
}
}
//
// Decode (1D) odd line (must loop in X)
//
if (ny & p) {
unsigned short *px = py;
unsigned short *ex = py + ox * (nx - p2);
for (; px <= ex; px += ox2) {
unsigned short *p01 = px + ox1;
if (w14)
wdec14(*px, *p01, i00, *p01);
else
wdec16(*px, *p01, i00, *p01);
*px = i00;
}
}
//
// Next level
//
p2 = p;
p >>= 1;
}
}
//-----------------------------------------------------------------------------
//
// 16-bit Huffman compression and decompression.
//
// The source code in this file is derived from the 8-bit
// Huffman compression and decompression routines written
// by Christian Rouet for his PIZ image file format.
//
//-----------------------------------------------------------------------------
// Adds some modification for tinyexr.
const int HUF_ENCBITS = 16; // literal (value) bit length
const int HUF_DECBITS = 14; // decoding bit size (>= 8)
const int HUF_ENCSIZE = (1 << HUF_ENCBITS) + 1; // encoding table size
const int HUF_DECSIZE = 1 << HUF_DECBITS; // decoding table size
const int HUF_DECMASK = HUF_DECSIZE - 1;
struct HufDec { // short code long code
//-------------------------------
unsigned int len : 8; // code length 0
unsigned int lit : 24; // lit p size
unsigned int *p; // 0 lits
};
inline long long hufLength(long long code) { return code & 63; }
inline long long hufCode(long long code) { return code >> 6; }
inline void outputBits(int nBits, long long bits, long long &c, int &lc,
char *&out) {
c <<= nBits;
lc += nBits;
c |= bits;
while (lc >= 8) *out++ = static_cast<char>((c >> (lc -= 8)));
}
inline long long getBits(int nBits, long long &c, int &lc, const char *&in) {
while (lc < nBits) {
c = (c << 8) | *(reinterpret_cast<const unsigned char *>(in++));
lc += 8;
}
lc -= nBits;
return (c >> lc) & ((1 << nBits) - 1);
}
//
// ENCODING TABLE BUILDING & (UN)PACKING
//
//
// Build a "canonical" Huffman code table:
// - for each (uncompressed) symbol, hcode contains the length
// of the corresponding code (in the compressed data)
// - canonical codes are computed and stored in hcode
// - the rules for constructing canonical codes are as follows:
// * shorter codes (if filled with zeroes to the right)
// have a numerically higher value than longer codes
// * for codes with the same length, numerical values
// increase with numerical symbol values
// - because the canonical code table can be constructed from
// symbol lengths alone, the code table can be transmitted
// without sending the actual code values
// - see http://www.compressconsult.com/huffman/
//
static void hufCanonicalCodeTable(long long hcode[HUF_ENCSIZE]) {
long long n[59];
//
// For each i from 0 through 58, count the
// number of different codes of length i, and
// store the count in n[i].
//
for (int i = 0; i <= 58; ++i) n[i] = 0;
for (int i = 0; i < HUF_ENCSIZE; ++i) n[hcode[i]] += 1;
//
// For each i from 58 through 1, compute the
// numerically lowest code with length i, and
// store that code in n[i].
//
long long c = 0;
for (int i = 58; i > 0; --i) {
long long nc = ((c + n[i]) >> 1);
n[i] = c;
c = nc;
}
//
// hcode[i] contains the length, l, of the
// code for symbol i. Assign the next available
// code of length l to the symbol and store both
// l and the code in hcode[i].
//
for (int i = 0; i < HUF_ENCSIZE; ++i) {
int l = static_cast<int>(hcode[i]);
if (l > 0) hcode[i] = l | (n[l]++ << 6);
}
}
//
// Compute Huffman codes (based on frq input) and store them in frq:
// - code structure is : [63:lsb - 6:msb] | [5-0: bit length];
// - max code length is 58 bits;
// - codes outside the range [im-iM] have a null length (unused values);
// - original frequencies are destroyed;
// - encoding tables are used by hufEncode() and hufBuildDecTable();
//
struct FHeapCompare {
bool operator()(long long *a, long long *b) { return *a > *b; }
};
static void hufBuildEncTable(
long long *frq, // io: input frequencies [HUF_ENCSIZE], output table
int *im, // o: min frq index
int *iM) // o: max frq index
{
//
// This function assumes that when it is called, array frq
// indicates the frequency of all possible symbols in the data
// that are to be Huffman-encoded. (frq[i] contains the number
// of occurrences of symbol i in the data.)
//
// The loop below does three things:
//
// 1) Finds the minimum and maximum indices that point
// to non-zero entries in frq:
//
// frq[im] != 0, and frq[i] == 0 for all i < im
// frq[iM] != 0, and frq[i] == 0 for all i > iM
//
// 2) Fills array fHeap with pointers to all non-zero
// entries in frq.
//
// 3) Initializes array hlink such that hlink[i] == i
// for all array entries.
//
std::vector<int> hlink(HUF_ENCSIZE);
std::vector<long long *> fHeap(HUF_ENCSIZE);
*im = 0;
while (!frq[*im]) (*im)++;
int nf = 0;
for (int i = *im; i < HUF_ENCSIZE; i++) {
hlink[i] = i;
if (frq[i]) {
fHeap[nf] = &frq[i];
nf++;
*iM = i;
}
}
//
// Add a pseudo-symbol, with a frequency count of 1, to frq;
// adjust the fHeap and hlink array accordingly. Function
// hufEncode() uses the pseudo-symbol for run-length encoding.
//
(*iM)++;
frq[*iM] = 1;
fHeap[nf] = &frq[*iM];
nf++;
//
// Build an array, scode, such that scode[i] contains the number
// of bits assigned to symbol i. Conceptually this is done by
// constructing a tree whose leaves are the symbols with non-zero
// frequency:
//
// Make a heap that contains all symbols with a non-zero frequency,
// with the least frequent symbol on top.
//
// Repeat until only one symbol is left on the heap:
//
// Take the two least frequent symbols off the top of the heap.
// Create a new node that has first two nodes as children, and
// whose frequency is the sum of the frequencies of the first
// two nodes. Put the new node back into the heap.
//
// The last node left on the heap is the root of the tree. For each
// leaf node, the distance between the root and the leaf is the length
// of the code for the corresponding symbol.
//
// The loop below doesn't actually build the tree; instead we compute
// the distances of the leaves from the root on the fly. When a new
// node is added to the heap, then that node's descendants are linked
// into a single linear list that starts at the new node, and the code
// lengths of the descendants (that is, their distance from the root
// of the tree) are incremented by one.
//
std::make_heap(&fHeap[0], &fHeap[nf], FHeapCompare());
std::vector<long long> scode(HUF_ENCSIZE);
memset(scode.data(), 0, sizeof(long long) * HUF_ENCSIZE);
while (nf > 1) {
//
// Find the indices, mm and m, of the two smallest non-zero frq
// values in fHeap, add the smallest frq to the second-smallest
// frq, and remove the smallest frq value from fHeap.
//
int mm = fHeap[0] - frq;
std::pop_heap(&fHeap[0], &fHeap[nf], FHeapCompare());
--nf;
int m = fHeap[0] - frq;
std::pop_heap(&fHeap[0], &fHeap[nf], FHeapCompare());
frq[m] += frq[mm];
std::push_heap(&fHeap[0], &fHeap[nf], FHeapCompare());
//
// The entries in scode are linked into lists with the
// entries in hlink serving as "next" pointers and with
// the end of a list marked by hlink[j] == j.
//
// Traverse the lists that start at scode[m] and scode[mm].
// For each element visited, increment the length of the
// corresponding code by one bit. (If we visit scode[j]
// during the traversal, then the code for symbol j becomes
// one bit longer.)
//
// Merge the lists that start at scode[m] and scode[mm]
// into a single list that starts at scode[m].
//
//
// Add a bit to all codes in the first list.
//
for (int j = m;; j = hlink[j]) {
scode[j]++;
assert(scode[j] <= 58);
if (hlink[j] == j) {
//
// Merge the two lists.
//
hlink[j] = mm;
break;
}
}
//
// Add a bit to all codes in the second list
//
for (int j = mm;; j = hlink[j]) {
scode[j]++;
assert(scode[j] <= 58);
if (hlink[j] == j) break;
}
}
//
// Build a canonical Huffman code table, replacing the code
// lengths in scode with (code, code length) pairs. Copy the
// code table from scode into frq.
//
hufCanonicalCodeTable(scode.data());
memcpy(frq, scode.data(), sizeof(long long) * HUF_ENCSIZE);
}
//
// Pack an encoding table:
// - only code lengths, not actual codes, are stored
// - runs of zeroes are compressed as follows:
//
// unpacked packed
// --------------------------------
// 1 zero 0 (6 bits)
// 2 zeroes 59
// 3 zeroes 60
// 4 zeroes 61
// 5 zeroes 62
// n zeroes (6 or more) 63 n-6 (6 + 8 bits)
//
const int SHORT_ZEROCODE_RUN = 59;
const int LONG_ZEROCODE_RUN = 63;
const int SHORTEST_LONG_RUN = 2 + LONG_ZEROCODE_RUN - SHORT_ZEROCODE_RUN;
const int LONGEST_LONG_RUN = 255 + SHORTEST_LONG_RUN;
static void hufPackEncTable(
const long long *hcode, // i : encoding table [HUF_ENCSIZE]
int im, // i : min hcode index
int iM, // i : max hcode index
char **pcode) // o: ptr to packed table (updated)
{
char *p = *pcode;
long long c = 0;
int lc = 0;
for (; im <= iM; im++) {
int l = hufLength(hcode[im]);
if (l == 0) {
int zerun = 1;
while ((im < iM) && (zerun < LONGEST_LONG_RUN)) {
if (hufLength(hcode[im + 1]) > 0) break;
im++;
zerun++;
}
if (zerun >= 2) {
if (zerun >= SHORTEST_LONG_RUN) {
outputBits(6, LONG_ZEROCODE_RUN, c, lc, p);
outputBits(8, zerun - SHORTEST_LONG_RUN, c, lc, p);
} else {
outputBits(6, SHORT_ZEROCODE_RUN + zerun - 2, c, lc, p);
}
continue;
}
}
outputBits(6, l, c, lc, p);
}
if (lc > 0) *p++ = (unsigned char)(c << (8 - lc));
*pcode = p;
}
//
// Unpack an encoding table packed by hufPackEncTable():
//
static bool hufUnpackEncTable(
const char **pcode, // io: ptr to packed table (updated)
int ni, // i : input size (in bytes)
int im, // i : min hcode index
int iM, // i : max hcode index
long long *hcode) // o: encoding table [HUF_ENCSIZE]
{
memset(hcode, 0, sizeof(long long) * HUF_ENCSIZE);
const char *p = *pcode;
long long c = 0;
int lc = 0;
for (; im <= iM; im++) {
if (p - *pcode >= ni) {
return false;
}
long long l = hcode[im] = getBits(6, c, lc, p); // code length
if (l == (long long)LONG_ZEROCODE_RUN) {
if (p - *pcode > ni) {
return false;
}
int zerun = getBits(8, c, lc, p) + SHORTEST_LONG_RUN;
if (im + zerun > iM + 1) {
return false;
}
while (zerun--) hcode[im++] = 0;
im--;
} else if (l >= (long long)SHORT_ZEROCODE_RUN) {
int zerun = l - SHORT_ZEROCODE_RUN + 2;
if (im + zerun > iM + 1) {
return false;
}
while (zerun--) hcode[im++] = 0;
im--;
}
}
*pcode = const_cast<char *>(p);
hufCanonicalCodeTable(hcode);
return true;
}
//
// DECODING TABLE BUILDING
//
//
// Clear a newly allocated decoding table so that it contains only zeroes.
//
static void hufClearDecTable(HufDec *hdecod) // io: (allocated by caller)
// decoding table [HUF_DECSIZE]
{
for (int i = 0; i < HUF_DECSIZE; i++) {
hdecod[i].len = 0;
hdecod[i].lit = 0;
hdecod[i].p = NULL;
}
// memset(hdecod, 0, sizeof(HufDec) * HUF_DECSIZE);
}
//
// Build a decoding hash table based on the encoding table hcode:
// - short codes (<= HUF_DECBITS) are resolved with a single table access;
// - long code entry allocations are not optimized, because long codes are
// unfrequent;
// - decoding tables are used by hufDecode();
//
static bool hufBuildDecTable(const long long *hcode, // i : encoding table
int im, // i : min index in hcode
int iM, // i : max index in hcode
HufDec *hdecod) // o: (allocated by caller)
// decoding table [HUF_DECSIZE]
{
//
// Init hashtable & loop on all codes.
// Assumes that hufClearDecTable(hdecod) has already been called.
//
for (; im <= iM; im++) {
long long c = hufCode(hcode[im]);
int l = hufLength(hcode[im]);
if (c >> l) {
//
// Error: c is supposed to be an l-bit code,
// but c contains a value that is greater
// than the largest l-bit number.
//
// invalidTableEntry();
return false;
}
if (l > HUF_DECBITS) {
//
// Long code: add a secondary entry
//
HufDec *pl = hdecod + (c >> (l - HUF_DECBITS));
if (pl->len) {
//
// Error: a short code has already
// been stored in table entry *pl.
//
// invalidTableEntry();
return false;
}
pl->lit++;
if (pl->p) {
unsigned int *p = pl->p;
pl->p = new unsigned int[pl->lit];
for (int i = 0; i < pl->lit - 1; ++i) pl->p[i] = p[i];
delete[] p;
} else {
pl->p = new unsigned int[1];
}
pl->p[pl->lit - 1] = im;
} else if (l) {
//
// Short code: init all primary entries
//
HufDec *pl = hdecod + (c << (HUF_DECBITS - l));
for (long long i = 1ULL << (HUF_DECBITS - l); i > 0; i--, pl++) {
if (pl->len || pl->p) {
//
// Error: a short code or a long code has
// already been stored in table entry *pl.
//
// invalidTableEntry();
return false;
}
pl->len = l;
pl->lit = im;
}
}
}
return true;
}
//
// Free the long code entries of a decoding table built by hufBuildDecTable()
//
static void hufFreeDecTable(HufDec *hdecod) // io: Decoding table
{
for (int i = 0; i < HUF_DECSIZE; i++) {
if (hdecod[i].p) {
delete[] hdecod[i].p;
hdecod[i].p = 0;
}
}
}
//
// ENCODING
//
inline void outputCode(long long code, long long &c, int &lc, char *&out) {
outputBits(hufLength(code), hufCode(code), c, lc, out);
}
inline void sendCode(long long sCode, int runCount, long long runCode,
long long &c, int &lc, char *&out) {
//
// Output a run of runCount instances of the symbol sCount.
// Output the symbols explicitly, or if that is shorter, output
// the sCode symbol once followed by a runCode symbol and runCount
// expressed as an 8-bit number.
//
if (hufLength(sCode) + hufLength(runCode) + 8 < hufLength(sCode) * runCount) {
outputCode(sCode, c, lc, out);
outputCode(runCode, c, lc, out);
outputBits(8, runCount, c, lc, out);
} else {
while (runCount-- >= 0) outputCode(sCode, c, lc, out);
}
}
//
// Encode (compress) ni values based on the Huffman encoding table hcode:
//
static int hufEncode // return: output size (in bits)
(const long long *hcode, // i : encoding table
const unsigned short *in, // i : uncompressed input buffer
const int ni, // i : input buffer size (in bytes)
int rlc, // i : rl code
char *out) // o: compressed output buffer
{
char *outStart = out;
long long c = 0; // bits not yet written to out
int lc = 0; // number of valid bits in c (LSB)
int s = in[0];
int cs = 0;
//
// Loop on input values
//
for (int i = 1; i < ni; i++) {
//
// Count same values or send code
//
if (s == in[i] && cs < 255) {
cs++;
} else {
sendCode(hcode[s], cs, hcode[rlc], c, lc, out);
cs = 0;
}
s = in[i];
}
//
// Send remaining code
//
sendCode(hcode[s], cs, hcode[rlc], c, lc, out);
if (lc) *out = (c << (8 - lc)) & 0xff;
return (out - outStart) * 8 + lc;
}
//
// DECODING
//
//
// In order to force the compiler to inline them,
// getChar() and getCode() are implemented as macros
// instead of "inline" functions.
//
#define getChar(c, lc, in) \
{ \
c = (c << 8) | *(unsigned char *)(in++); \
lc += 8; \
}
#if 0
#define getCode(po, rlc, c, lc, in, out, ob, oe) \
{ \
if (po == rlc) { \
if (lc < 8) getChar(c, lc, in); \
\
lc -= 8; \
\
unsigned char cs = (c >> lc); \
\
if (out + cs > oe) return false; \
\
/* TinyEXR issue 78 */ \
unsigned short s = out[-1]; \
\
while (cs-- > 0) *out++ = s; \
} else if (out < oe) { \
*out++ = po; \
} else { \
return false; \
} \
}
#else
static bool getCode(int po, int rlc, long long &c, int &lc, const char *&in,
const char *in_end, unsigned short *&out,
const unsigned short *ob, const unsigned short *oe) {
(void)ob;
if (po == rlc) {
if (lc < 8) {
/* TinyEXR issue 78 */
if ((in + 1) >= in_end) {
return false;
}
getChar(c, lc, in);
}
lc -= 8;
unsigned char cs = (c >> lc);
if (out + cs > oe) return false;
// Bounds check for safety
// Issue 100.
if ((out - 1) < ob) return false;
unsigned short s = out[-1];
while (cs-- > 0) *out++ = s;
} else if (out < oe) {
*out++ = po;
} else {
return false;
}
return true;
}
#endif
//
// Decode (uncompress) ni bits based on encoding & decoding tables:
//
static bool hufDecode(const long long *hcode, // i : encoding table
const HufDec *hdecod, // i : decoding table
const char *in, // i : compressed input buffer
int ni, // i : input size (in bits)
int rlc, // i : run-length code
int no, // i : expected output size (in bytes)
unsigned short *out) // o: uncompressed output buffer
{
long long c = 0;
int lc = 0;
unsigned short *outb = out; // begin
unsigned short *oe = out + no; // end
const char *ie = in + (ni + 7) / 8; // input byte size
//
// Loop on input bytes
//
while (in < ie) {
getChar(c, lc, in);
//
// Access decoding table
//
while (lc >= HUF_DECBITS) {
const HufDec pl = hdecod[(c >> (lc - HUF_DECBITS)) & HUF_DECMASK];
if (pl.len) {
//
// Get short code
//
lc -= pl.len;
// std::cout << "lit = " << pl.lit << std::endl;
// std::cout << "rlc = " << rlc << std::endl;
// std::cout << "c = " << c << std::endl;
// std::cout << "lc = " << lc << std::endl;
// std::cout << "in = " << in << std::endl;
// std::cout << "out = " << out << std::endl;
// std::cout << "oe = " << oe << std::endl;
if (!getCode(pl.lit, rlc, c, lc, in, ie, out, outb, oe)) {
return false;
}
} else {
if (!pl.p) {
return false;
}
// invalidCode(); // wrong code
//
// Search long code
//
int j;
for (j = 0; j < pl.lit; j++) {
int l = hufLength(hcode[pl.p[j]]);
while (lc < l && in < ie) // get more bits
getChar(c, lc, in);
if (lc >= l) {
if (hufCode(hcode[pl.p[j]]) ==
((c >> (lc - l)) & (((long long)(1) << l) - 1))) {
//
// Found : get long code
//
lc -= l;
if (!getCode(pl.p[j], rlc, c, lc, in, ie, out, outb, oe)) {
return false;
}
break;
}
}
}
if (j == pl.lit) {
return false;
// invalidCode(); // Not found
}
}
}
}
//
// Get remaining (short) codes
//
int i = (8 - ni) & 7;
c >>= i;
lc -= i;
while (lc > 0) {
const HufDec pl = hdecod[(c << (HUF_DECBITS - lc)) & HUF_DECMASK];
if (pl.len) {
lc -= pl.len;
if (!getCode(pl.lit, rlc, c, lc, in, ie, out, outb, oe)) {
return false;
}
} else {
return false;
// invalidCode(); // wrong (long) code
}
}
if (out - outb != no) {
return false;
}
// notEnoughData ();
return true;
}
static void countFrequencies(std::vector<long long> &freq,
const unsigned short data[/*n*/], int n) {
for (int i = 0; i < HUF_ENCSIZE; ++i) freq[i] = 0;
for (int i = 0; i < n; ++i) ++freq[data[i]];
}
static void writeUInt(char buf[4], unsigned int i) {
unsigned char *b = (unsigned char *)buf;
b[0] = i;
b[1] = i >> 8;
b[2] = i >> 16;
b[3] = i >> 24;
}
static unsigned int readUInt(const char buf[4]) {
const unsigned char *b = (const unsigned char *)buf;
return (b[0] & 0x000000ff) | ((b[1] << 8) & 0x0000ff00) |
((b[2] << 16) & 0x00ff0000) | ((b[3] << 24) & 0xff000000);
}
//
// EXTERNAL INTERFACE
//
static int hufCompress(const unsigned short raw[], int nRaw,
char compressed[]) {
if (nRaw == 0) return 0;
std::vector<long long> freq(HUF_ENCSIZE);
countFrequencies(freq, raw, nRaw);
int im = 0;
int iM = 0;
hufBuildEncTable(freq.data(), &im, &iM);
char *tableStart = compressed + 20;
char *tableEnd = tableStart;
hufPackEncTable(freq.data(), im, iM, &tableEnd);
int tableLength = tableEnd - tableStart;
char *dataStart = tableEnd;
int nBits = hufEncode(freq.data(), raw, nRaw, iM, dataStart);
int data_length = (nBits + 7) / 8;
writeUInt(compressed, im);
writeUInt(compressed + 4, iM);
writeUInt(compressed + 8, tableLength);
writeUInt(compressed + 12, nBits);
writeUInt(compressed + 16, 0); // room for future extensions
return dataStart + data_length - compressed;
}
static bool hufUncompress(const char compressed[], int nCompressed,
std::vector<unsigned short> *raw) {
if (nCompressed == 0) {
if (raw->size() != 0) return false;
return false;
}
int im = readUInt(compressed);
int iM = readUInt(compressed + 4);
// int tableLength = readUInt (compressed + 8);
int nBits = readUInt(compressed + 12);
if (im < 0 || im >= HUF_ENCSIZE || iM < 0 || iM >= HUF_ENCSIZE) return false;
const char *ptr = compressed + 20;
//
// Fast decoder needs at least 2x64-bits of compressed data, and
// needs to be run-able on this platform. Otherwise, fall back
// to the original decoder
//
// if (FastHufDecoder::enabled() && nBits > 128)
//{
// FastHufDecoder fhd (ptr, nCompressed - (ptr - compressed), im, iM, iM);
// fhd.decode ((unsigned char*)ptr, nBits, raw, nRaw);
//}
// else
{
std::vector<long long> freq(HUF_ENCSIZE);
std::vector<HufDec> hdec(HUF_DECSIZE);
hufClearDecTable(&hdec.at(0));
hufUnpackEncTable(&ptr, nCompressed - (ptr - compressed), im, iM,
&freq.at(0));
{
if (nBits > 8 * (nCompressed - (ptr - compressed))) {
return false;
}
hufBuildDecTable(&freq.at(0), im, iM, &hdec.at(0));
hufDecode(&freq.at(0), &hdec.at(0), ptr, nBits, iM, raw->size(),
raw->data());
}
// catch (...)
//{
// hufFreeDecTable (hdec);
// throw;
//}
hufFreeDecTable(&hdec.at(0));
}
return true;
}
//
// Functions to compress the range of values in the pixel data
//
const int USHORT_RANGE = (1 << 16);
const int BITMAP_SIZE = (USHORT_RANGE >> 3);
static void bitmapFromData(const unsigned short data[/*nData*/], int nData,
unsigned char bitmap[BITMAP_SIZE],
unsigned short &minNonZero,
unsigned short &maxNonZero) {
for (int i = 0; i < BITMAP_SIZE; ++i) bitmap[i] = 0;
for (int i = 0; i < nData; ++i) bitmap[data[i] >> 3] |= (1 << (data[i] & 7));
bitmap[0] &= ~1; // zero is not explicitly stored in
// the bitmap; we assume that the
// data always contain zeroes
minNonZero = BITMAP_SIZE - 1;
maxNonZero = 0;
for (int i = 0; i < BITMAP_SIZE; ++i) {
if (bitmap[i]) {
if (minNonZero > i) minNonZero = i;
if (maxNonZero < i) maxNonZero = i;
}
}
}
static unsigned short forwardLutFromBitmap(
const unsigned char bitmap[BITMAP_SIZE], unsigned short lut[USHORT_RANGE]) {
int k = 0;
for (int i = 0; i < USHORT_RANGE; ++i) {
if ((i == 0) || (bitmap[i >> 3] & (1 << (i & 7))))
lut[i] = k++;
else
lut[i] = 0;
}
return k - 1; // maximum value stored in lut[],
} // i.e. number of ones in bitmap minus 1
static unsigned short reverseLutFromBitmap(
const unsigned char bitmap[BITMAP_SIZE], unsigned short lut[USHORT_RANGE]) {
int k = 0;
for (int i = 0; i < USHORT_RANGE; ++i) {
if ((i == 0) || (bitmap[i >> 3] & (1 << (i & 7)))) lut[k++] = i;
}
int n = k - 1;
while (k < USHORT_RANGE) lut[k++] = 0;
return n; // maximum k where lut[k] is non-zero,
} // i.e. number of ones in bitmap minus 1
static void applyLut(const unsigned short lut[USHORT_RANGE],
unsigned short data[/*nData*/], int nData) {
for (int i = 0; i < nData; ++i) data[i] = lut[data[i]];
}
#ifdef __clang__
#pragma clang diagnostic pop
#endif // __clang__
#ifdef _MSC_VER
#pragma warning(pop)
#endif
static bool CompressPiz(unsigned char *outPtr, unsigned int *outSize,
const unsigned char *inPtr, size_t inSize,
const std::vector<ChannelInfo> &channelInfo,
int data_width, int num_lines) {
std::vector<unsigned char> bitmap(BITMAP_SIZE);
unsigned short minNonZero;
unsigned short maxNonZero;
#if !MINIZ_LITTLE_ENDIAN
// @todo { PIZ compression on BigEndian architecture. }
assert(0);
return false;
#endif
// Assume `inSize` is multiple of 2 or 4.
std::vector<unsigned short> tmpBuffer(inSize / sizeof(unsigned short));
std::vector<PIZChannelData> channelData(channelInfo.size());
unsigned short *tmpBufferEnd = &tmpBuffer.at(0);
for (size_t c = 0; c < channelData.size(); c++) {
PIZChannelData &cd = channelData[c];
cd.start = tmpBufferEnd;
cd.end = cd.start;
cd.nx = data_width;
cd.ny = num_lines;
// cd.ys = c.channel().ySampling;
size_t pixelSize = sizeof(int); // UINT and FLOAT
if (channelInfo[c].requested_pixel_type == TINYEXR_PIXELTYPE_HALF) {
pixelSize = sizeof(short);
}
cd.size = static_cast<int>(pixelSize / sizeof(short));
tmpBufferEnd += cd.nx * cd.ny * cd.size;
}
const unsigned char *ptr = inPtr;
for (int y = 0; y < num_lines; ++y) {
for (size_t i = 0; i < channelData.size(); ++i) {
PIZChannelData &cd = channelData[i];
// if (modp (y, cd.ys) != 0)
// continue;
size_t n = static_cast<size_t>(cd.nx * cd.size);
memcpy(cd.end, ptr, n * sizeof(unsigned short));
ptr += n * sizeof(unsigned short);
cd.end += n;
}
}
bitmapFromData(&tmpBuffer.at(0), static_cast<int>(tmpBuffer.size()),
bitmap.data(), minNonZero, maxNonZero);
std::vector<unsigned short> lut(USHORT_RANGE);
unsigned short maxValue = forwardLutFromBitmap(bitmap.data(), lut.data());
applyLut(lut.data(), &tmpBuffer.at(0), static_cast<int>(tmpBuffer.size()));
//
// Store range compression info in _outBuffer
//
char *buf = reinterpret_cast<char *>(outPtr);
memcpy(buf, &minNonZero, sizeof(unsigned short));
buf += sizeof(unsigned short);
memcpy(buf, &maxNonZero, sizeof(unsigned short));
buf += sizeof(unsigned short);
if (minNonZero <= maxNonZero) {
memcpy(buf, reinterpret_cast<char *>(&bitmap[0] + minNonZero),
maxNonZero - minNonZero + 1);
buf += maxNonZero - minNonZero + 1;
}
//
// Apply wavelet encoding
//
for (size_t i = 0; i < channelData.size(); ++i) {
PIZChannelData &cd = channelData[i];
for (int j = 0; j < cd.size; ++j) {
wav2Encode(cd.start + j, cd.nx, cd.size, cd.ny, cd.nx * cd.size,
maxValue);
}
}
//
// Apply Huffman encoding; append the result to _outBuffer
//
// length header(4byte), then huff data. Initialize length header with zero,
// then later fill it by `length`.
char *lengthPtr = buf;
int zero = 0;
memcpy(buf, &zero, sizeof(int));
buf += sizeof(int);
int length =
hufCompress(&tmpBuffer.at(0), static_cast<int>(tmpBuffer.size()), buf);
memcpy(lengthPtr, &length, sizeof(int));
(*outSize) = static_cast<unsigned int>(
(reinterpret_cast<unsigned char *>(buf) - outPtr) +
static_cast<unsigned int>(length));
// Use uncompressed data when compressed data is larger than uncompressed.
// (Issue 40)
if ((*outSize) >= inSize) {
(*outSize) = static_cast<unsigned int>(inSize);
memcpy(outPtr, inPtr, inSize);
}
return true;
}
static bool DecompressPiz(unsigned char *outPtr, const unsigned char *inPtr,
size_t tmpBufSize, size_t inLen, int num_channels,
const EXRChannelInfo *channels, int data_width,
int num_lines) {
if (inLen == tmpBufSize) {
// Data is not compressed(Issue 40).
memcpy(outPtr, inPtr, inLen);
return true;
}
std::vector<unsigned char> bitmap(BITMAP_SIZE);
unsigned short minNonZero;
unsigned short maxNonZero;
#if !MINIZ_LITTLE_ENDIAN
// @todo { PIZ compression on BigEndian architecture. }
assert(0);
return false;
#endif
memset(bitmap.data(), 0, BITMAP_SIZE);
const unsigned char *ptr = inPtr;
// minNonZero = *(reinterpret_cast<const unsigned short *>(ptr));
tinyexr::cpy2(&minNonZero, reinterpret_cast<const unsigned short *>(ptr));
// maxNonZero = *(reinterpret_cast<const unsigned short *>(ptr + 2));
tinyexr::cpy2(&maxNonZero, reinterpret_cast<const unsigned short *>(ptr + 2));
ptr += 4;
if (maxNonZero >= BITMAP_SIZE) {
return false;
}
if (minNonZero <= maxNonZero) {
memcpy(reinterpret_cast<char *>(&bitmap[0] + minNonZero), ptr,
maxNonZero - minNonZero + 1);
ptr += maxNonZero - minNonZero + 1;
}
std::vector<unsigned short> lut(USHORT_RANGE);
memset(lut.data(), 0, sizeof(unsigned short) * USHORT_RANGE);
unsigned short maxValue = reverseLutFromBitmap(bitmap.data(), lut.data());
//
// Huffman decoding
//
int length;
// length = *(reinterpret_cast<const int *>(ptr));
tinyexr::cpy4(&length, reinterpret_cast<const int *>(ptr));
ptr += sizeof(int);
if (size_t((ptr - inPtr) + length) > inLen) {
return false;
}
std::vector<unsigned short> tmpBuffer(tmpBufSize);
hufUncompress(reinterpret_cast<const char *>(ptr), length, &tmpBuffer);
//
// Wavelet decoding
//
std::vector<PIZChannelData> channelData(static_cast<size_t>(num_channels));
unsigned short *tmpBufferEnd = &tmpBuffer.at(0);
for (size_t i = 0; i < static_cast<size_t>(num_channels); ++i) {
const EXRChannelInfo &chan = channels[i];
size_t pixelSize = sizeof(int); // UINT and FLOAT
if (chan.pixel_type == TINYEXR_PIXELTYPE_HALF) {
pixelSize = sizeof(short);
}
channelData[i].start = tmpBufferEnd;
channelData[i].end = channelData[i].start;
channelData[i].nx = data_width;
channelData[i].ny = num_lines;
// channelData[i].ys = 1;
channelData[i].size = static_cast<int>(pixelSize / sizeof(short));
tmpBufferEnd += channelData[i].nx * channelData[i].ny * channelData[i].size;
}
for (size_t i = 0; i < channelData.size(); ++i) {
PIZChannelData &cd = channelData[i];
for (int j = 0; j < cd.size; ++j) {
wav2Decode(cd.start + j, cd.nx, cd.size, cd.ny, cd.nx * cd.size,
maxValue);
}
}
//
// Expand the pixel data to their original range
//
applyLut(lut.data(), &tmpBuffer.at(0), static_cast<int>(tmpBufSize));
for (int y = 0; y < num_lines; y++) {
for (size_t i = 0; i < channelData.size(); ++i) {
PIZChannelData &cd = channelData[i];
// if (modp (y, cd.ys) != 0)
// continue;
size_t n = static_cast<size_t>(cd.nx * cd.size);
memcpy(outPtr, cd.end, static_cast<size_t>(n * sizeof(unsigned short)));
outPtr += n * sizeof(unsigned short);
cd.end += n;
}
}
return true;
}
#endif // TINYEXR_USE_PIZ
#if TINYEXR_USE_ZFP
struct ZFPCompressionParam {
double rate;
unsigned int precision;
unsigned int __pad0;
double tolerance;
int type; // TINYEXR_ZFP_COMPRESSIONTYPE_*
unsigned int __pad1;
ZFPCompressionParam() {
type = TINYEXR_ZFP_COMPRESSIONTYPE_RATE;
rate = 2.0;
precision = 0;
tolerance = 0.0;
}
};
static bool FindZFPCompressionParam(ZFPCompressionParam *param,
const EXRAttribute *attributes,
int num_attributes, std::string *err) {
bool foundType = false;
for (int i = 0; i < num_attributes; i++) {
if ((strcmp(attributes[i].name, "zfpCompressionType") == 0)) {
if (attributes[i].size == 1) {
param->type = static_cast<int>(attributes[i].value[0]);
foundType = true;
break;
} else {
if (err) {
(*err) +=
"zfpCompressionType attribute must be uchar(1 byte) type.\n";
}
return false;
}
}
}
if (!foundType) {
if (err) {
(*err) += "`zfpCompressionType` attribute not found.\n";
}
return false;
}
if (param->type == TINYEXR_ZFP_COMPRESSIONTYPE_RATE) {
for (int i = 0; i < num_attributes; i++) {
if ((strcmp(attributes[i].name, "zfpCompressionRate") == 0) &&
(attributes[i].size == 8)) {
param->rate = *(reinterpret_cast<double *>(attributes[i].value));
return true;
}
}
if (err) {
(*err) += "`zfpCompressionRate` attribute not found.\n";
}
} else if (param->type == TINYEXR_ZFP_COMPRESSIONTYPE_PRECISION) {
for (int i = 0; i < num_attributes; i++) {
if ((strcmp(attributes[i].name, "zfpCompressionPrecision") == 0) &&
(attributes[i].size == 4)) {
param->rate = *(reinterpret_cast<int *>(attributes[i].value));
return true;
}
}
if (err) {
(*err) += "`zfpCompressionPrecision` attribute not found.\n";
}
} else if (param->type == TINYEXR_ZFP_COMPRESSIONTYPE_ACCURACY) {
for (int i = 0; i < num_attributes; i++) {
if ((strcmp(attributes[i].name, "zfpCompressionTolerance") == 0) &&
(attributes[i].size == 8)) {
param->tolerance = *(reinterpret_cast<double *>(attributes[i].value));
return true;
}
}
if (err) {
(*err) += "`zfpCompressionTolerance` attribute not found.\n";
}
} else {
if (err) {
(*err) += "Unknown value specified for `zfpCompressionType`.\n";
}
}
return false;
}
// Assume pixel format is FLOAT for all channels.
static bool DecompressZfp(float *dst, int dst_width, int dst_num_lines,
size_t num_channels, const unsigned char *src,
unsigned long src_size,
const ZFPCompressionParam ¶m) {
size_t uncompressed_size =
size_t(dst_width) * size_t(dst_num_lines) * num_channels;
if (uncompressed_size == src_size) {
// Data is not compressed(Issue 40).
memcpy(dst, src, src_size);
}
zfp_stream *zfp = NULL;
zfp_field *field = NULL;
assert((dst_width % 4) == 0);
assert((dst_num_lines % 4) == 0);
if ((size_t(dst_width) & 3U) || (size_t(dst_num_lines) & 3U)) {
return false;
}
field =
zfp_field_2d(reinterpret_cast<void *>(const_cast<unsigned char *>(src)),
zfp_type_float, static_cast<unsigned int>(dst_width),
static_cast<unsigned int>(dst_num_lines) *
static_cast<unsigned int>(num_channels));
zfp = zfp_stream_open(NULL);
if (param.type == TINYEXR_ZFP_COMPRESSIONTYPE_RATE) {
zfp_stream_set_rate(zfp, param.rate, zfp_type_float, /* dimension */ 2,
/* write random access */ 0);
} else if (param.type == TINYEXR_ZFP_COMPRESSIONTYPE_PRECISION) {
zfp_stream_set_precision(zfp, param.precision);
} else if (param.type == TINYEXR_ZFP_COMPRESSIONTYPE_ACCURACY) {
zfp_stream_set_accuracy(zfp, param.tolerance);
} else {
assert(0);
}
size_t buf_size = zfp_stream_maximum_size(zfp, field);
std::vector<unsigned char> buf(buf_size);
memcpy(&buf.at(0), src, src_size);
bitstream *stream = stream_open(&buf.at(0), buf_size);
zfp_stream_set_bit_stream(zfp, stream);
zfp_stream_rewind(zfp);
size_t image_size = size_t(dst_width) * size_t(dst_num_lines);
for (size_t c = 0; c < size_t(num_channels); c++) {
// decompress 4x4 pixel block.
for (size_t y = 0; y < size_t(dst_num_lines); y += 4) {
for (size_t x = 0; x < size_t(dst_width); x += 4) {
float fblock[16];
zfp_decode_block_float_2(zfp, fblock);
for (size_t j = 0; j < 4; j++) {
for (size_t i = 0; i < 4; i++) {
dst[c * image_size + ((y + j) * size_t(dst_width) + (x + i))] =
fblock[j * 4 + i];
}
}
}
}
}
zfp_field_free(field);
zfp_stream_close(zfp);
stream_close(stream);
return true;
}
// Assume pixel format is FLOAT for all channels.
static bool CompressZfp(std::vector<unsigned char> *outBuf,
unsigned int *outSize, const float *inPtr, int width,
int num_lines, int num_channels,
const ZFPCompressionParam ¶m) {
zfp_stream *zfp = NULL;
zfp_field *field = NULL;
assert((width % 4) == 0);
assert((num_lines % 4) == 0);
if ((size_t(width) & 3U) || (size_t(num_lines) & 3U)) {
return false;
}
// create input array.
field = zfp_field_2d(reinterpret_cast<void *>(const_cast<float *>(inPtr)),
zfp_type_float, static_cast<unsigned int>(width),
static_cast<unsigned int>(num_lines * num_channels));
zfp = zfp_stream_open(NULL);
if (param.type == TINYEXR_ZFP_COMPRESSIONTYPE_RATE) {
zfp_stream_set_rate(zfp, param.rate, zfp_type_float, 2, 0);
} else if (param.type == TINYEXR_ZFP_COMPRESSIONTYPE_PRECISION) {
zfp_stream_set_precision(zfp, param.precision);
} else if (param.type == TINYEXR_ZFP_COMPRESSIONTYPE_ACCURACY) {
zfp_stream_set_accuracy(zfp, param.tolerance);
} else {
assert(0);
}
size_t buf_size = zfp_stream_maximum_size(zfp, field);
outBuf->resize(buf_size);
bitstream *stream = stream_open(&outBuf->at(0), buf_size);
zfp_stream_set_bit_stream(zfp, stream);
zfp_field_free(field);
size_t image_size = size_t(width) * size_t(num_lines);
for (size_t c = 0; c < size_t(num_channels); c++) {
// compress 4x4 pixel block.
for (size_t y = 0; y < size_t(num_lines); y += 4) {
for (size_t x = 0; x < size_t(width); x += 4) {
float fblock[16];
for (size_t j = 0; j < 4; j++) {
for (size_t i = 0; i < 4; i++) {
fblock[j * 4 + i] =
inPtr[c * image_size + ((y + j) * size_t(width) + (x + i))];
}
}
zfp_encode_block_float_2(zfp, fblock);
}
}
}
zfp_stream_flush(zfp);
(*outSize) = static_cast<unsigned int>(zfp_stream_compressed_size(zfp));
zfp_stream_close(zfp);
return true;
}
#endif
//
// -----------------------------------------------------------------
//
// heuristics
#define TINYEXR_DIMENSION_THRESHOLD (1024 * 8192)
// TODO(syoyo): Refactor function arguments.
static bool DecodePixelData(/* out */ unsigned char **out_images,
const int *requested_pixel_types,
const unsigned char *data_ptr, size_t data_len,
int compression_type, int line_order, int width,
int height, int x_stride, int y, int line_no,
int num_lines, size_t pixel_data_size,
size_t num_attributes,
const EXRAttribute *attributes, size_t num_channels,
const EXRChannelInfo *channels,
const std::vector<size_t> &channel_offset_list) {
if (compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) { // PIZ
#if TINYEXR_USE_PIZ
if ((width == 0) || (num_lines == 0) || (pixel_data_size == 0)) {
// Invalid input #90
return false;
}
// Allocate original data size.
std::vector<unsigned char> outBuf(static_cast<size_t>(
static_cast<size_t>(width * num_lines) * pixel_data_size));
size_t tmpBufLen = outBuf.size();
bool ret = tinyexr::DecompressPiz(
reinterpret_cast<unsigned char *>(&outBuf.at(0)), data_ptr, tmpBufLen,
data_len, static_cast<int>(num_channels), channels, width, num_lines);
if (!ret) {
return false;
}
// For PIZ_COMPRESSION:
// pixel sample data for channel 0 for scanline 0
// pixel sample data for channel 1 for scanline 0
// pixel sample data for channel ... for scanline 0
// pixel sample data for channel n for scanline 0
// pixel sample data for channel 0 for scanline 1
// pixel sample data for channel 1 for scanline 1
// pixel sample data for channel ... for scanline 1
// pixel sample data for channel n for scanline 1
// ...
for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) {
if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) {
for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) {
const unsigned short *line_ptr = reinterpret_cast<unsigned short *>(
&outBuf.at(v * pixel_data_size * static_cast<size_t>(width) +
channel_offset_list[c] * static_cast<size_t>(width)));
for (size_t u = 0; u < static_cast<size_t>(width); u++) {
FP16 hf;
// hf.u = line_ptr[u];
// use `cpy` to avoid unaligned memory access when compiler's
// optimization is on.
tinyexr::cpy2(&(hf.u), line_ptr + u);
tinyexr::swap2(reinterpret_cast<unsigned short *>(&hf.u));
if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) {
unsigned short *image =
reinterpret_cast<unsigned short **>(out_images)[c];
if (line_order == 0) {
image += (static_cast<size_t>(line_no) + v) *
static_cast<size_t>(x_stride) +
u;
} else {
image += static_cast<size_t>(
(height - 1 - (line_no + static_cast<int>(v)))) *
static_cast<size_t>(x_stride) +
u;
}
*image = hf.u;
} else { // HALF -> FLOAT
FP32 f32 = half_to_float(hf);
float *image = reinterpret_cast<float **>(out_images)[c];
size_t offset = 0;
if (line_order == 0) {
offset = (static_cast<size_t>(line_no) + v) *
static_cast<size_t>(x_stride) +
u;
} else {
offset = static_cast<size_t>(
(height - 1 - (line_no + static_cast<int>(v)))) *
static_cast<size_t>(x_stride) +
u;
}
image += offset;
*image = f32.f;
}
}
}
} else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) {
assert(requested_pixel_types[c] == TINYEXR_PIXELTYPE_UINT);
for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) {
const unsigned int *line_ptr = reinterpret_cast<unsigned int *>(
&outBuf.at(v * pixel_data_size * static_cast<size_t>(width) +
channel_offset_list[c] * static_cast<size_t>(width)));
for (size_t u = 0; u < static_cast<size_t>(width); u++) {
unsigned int val;
// val = line_ptr[u];
tinyexr::cpy4(&val, line_ptr + u);
tinyexr::swap4(&val);
unsigned int *image =
reinterpret_cast<unsigned int **>(out_images)[c];
if (line_order == 0) {
image += (static_cast<size_t>(line_no) + v) *
static_cast<size_t>(x_stride) +
u;
} else {
image += static_cast<size_t>(
(height - 1 - (line_no + static_cast<int>(v)))) *
static_cast<size_t>(x_stride) +
u;
}
*image = val;
}
}
} else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) {
assert(requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT);
for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) {
const float *line_ptr = reinterpret_cast<float *>(&outBuf.at(
v * pixel_data_size * static_cast<size_t>(x_stride) +
channel_offset_list[c] * static_cast<size_t>(x_stride)));
for (size_t u = 0; u < static_cast<size_t>(width); u++) {
float val;
// val = line_ptr[u];
tinyexr::cpy4(&val, line_ptr + u);
tinyexr::swap4(reinterpret_cast<unsigned int *>(&val));
float *image = reinterpret_cast<float **>(out_images)[c];
if (line_order == 0) {
image += (static_cast<size_t>(line_no) + v) *
static_cast<size_t>(x_stride) +
u;
} else {
image += static_cast<size_t>(
(height - 1 - (line_no + static_cast<int>(v)))) *
static_cast<size_t>(x_stride) +
u;
}
*image = val;
}
}
} else {
assert(0);
}
}
#else
assert(0 && "PIZ is enabled in this build");
return false;
#endif
} else if (compression_type == TINYEXR_COMPRESSIONTYPE_ZIPS ||
compression_type == TINYEXR_COMPRESSIONTYPE_ZIP) {
// Allocate original data size.
std::vector<unsigned char> outBuf(static_cast<size_t>(width) *
static_cast<size_t>(num_lines) *
pixel_data_size);
unsigned long dstLen = static_cast<unsigned long>(outBuf.size());
assert(dstLen > 0);
if (!tinyexr::DecompressZip(
reinterpret_cast<unsigned char *>(&outBuf.at(0)), &dstLen, data_ptr,
static_cast<unsigned long>(data_len))) {
return false;
}
// For ZIP_COMPRESSION:
// pixel sample data for channel 0 for scanline 0
// pixel sample data for channel 1 for scanline 0
// pixel sample data for channel ... for scanline 0
// pixel sample data for channel n for scanline 0
// pixel sample data for channel 0 for scanline 1
// pixel sample data for channel 1 for scanline 1
// pixel sample data for channel ... for scanline 1
// pixel sample data for channel n for scanline 1
// ...
for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) {
if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) {
for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) {
const unsigned short *line_ptr = reinterpret_cast<unsigned short *>(
&outBuf.at(v * static_cast<size_t>(pixel_data_size) *
static_cast<size_t>(width) +
channel_offset_list[c] * static_cast<size_t>(width)));
for (size_t u = 0; u < static_cast<size_t>(width); u++) {
tinyexr::FP16 hf;
// hf.u = line_ptr[u];
tinyexr::cpy2(&(hf.u), line_ptr + u);
tinyexr::swap2(reinterpret_cast<unsigned short *>(&hf.u));
if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) {
unsigned short *image =
reinterpret_cast<unsigned short **>(out_images)[c];
if (line_order == 0) {
image += (static_cast<size_t>(line_no) + v) *
static_cast<size_t>(x_stride) +
u;
} else {
image += (static_cast<size_t>(height) - 1U -
(static_cast<size_t>(line_no) + v)) *
static_cast<size_t>(x_stride) +
u;
}
*image = hf.u;
} else { // HALF -> FLOAT
tinyexr::FP32 f32 = half_to_float(hf);
float *image = reinterpret_cast<float **>(out_images)[c];
size_t offset = 0;
if (line_order == 0) {
offset = (static_cast<size_t>(line_no) + v) *
static_cast<size_t>(x_stride) +
u;
} else {
offset = (static_cast<size_t>(height) - 1U -
(static_cast<size_t>(line_no) + v)) *
static_cast<size_t>(x_stride) +
u;
}
image += offset;
*image = f32.f;
}
}
}
} else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) {
assert(requested_pixel_types[c] == TINYEXR_PIXELTYPE_UINT);
for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) {
const unsigned int *line_ptr = reinterpret_cast<unsigned int *>(
&outBuf.at(v * pixel_data_size * static_cast<size_t>(width) +
channel_offset_list[c] * static_cast<size_t>(width)));
for (size_t u = 0; u < static_cast<size_t>(width); u++) {
unsigned int val;
// val = line_ptr[u];
tinyexr::cpy4(&val, line_ptr + u);
tinyexr::swap4(&val);
unsigned int *image =
reinterpret_cast<unsigned int **>(out_images)[c];
if (line_order == 0) {
image += (static_cast<size_t>(line_no) + v) *
static_cast<size_t>(x_stride) +
u;
} else {
image += (static_cast<size_t>(height) - 1U -
(static_cast<size_t>(line_no) + v)) *
static_cast<size_t>(x_stride) +
u;
}
*image = val;
}
}
} else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) {
assert(requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT);
for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) {
const float *line_ptr = reinterpret_cast<float *>(
&outBuf.at(v * pixel_data_size * static_cast<size_t>(width) +
channel_offset_list[c] * static_cast<size_t>(width)));
for (size_t u = 0; u < static_cast<size_t>(width); u++) {
float val;
// val = line_ptr[u];
tinyexr::cpy4(&val, line_ptr + u);
tinyexr::swap4(reinterpret_cast<unsigned int *>(&val));
float *image = reinterpret_cast<float **>(out_images)[c];
if (line_order == 0) {
image += (static_cast<size_t>(line_no) + v) *
static_cast<size_t>(x_stride) +
u;
} else {
image += (static_cast<size_t>(height) - 1U -
(static_cast<size_t>(line_no) + v)) *
static_cast<size_t>(x_stride) +
u;
}
*image = val;
}
}
} else {
assert(0);
return false;
}
}
} else if (compression_type == TINYEXR_COMPRESSIONTYPE_RLE) {
// Allocate original data size.
std::vector<unsigned char> outBuf(static_cast<size_t>(width) *
static_cast<size_t>(num_lines) *
pixel_data_size);
unsigned long dstLen = static_cast<unsigned long>(outBuf.size());
if (dstLen == 0) {
return false;
}
if (!tinyexr::DecompressRle(
reinterpret_cast<unsigned char *>(&outBuf.at(0)), dstLen, data_ptr,
static_cast<unsigned long>(data_len))) {
return false;
}
// For RLE_COMPRESSION:
// pixel sample data for channel 0 for scanline 0
// pixel sample data for channel 1 for scanline 0
// pixel sample data for channel ... for scanline 0
// pixel sample data for channel n for scanline 0
// pixel sample data for channel 0 for scanline 1
// pixel sample data for channel 1 for scanline 1
// pixel sample data for channel ... for scanline 1
// pixel sample data for channel n for scanline 1
// ...
for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) {
if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) {
for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) {
const unsigned short *line_ptr = reinterpret_cast<unsigned short *>(
&outBuf.at(v * static_cast<size_t>(pixel_data_size) *
static_cast<size_t>(width) +
channel_offset_list[c] * static_cast<size_t>(width)));
for (size_t u = 0; u < static_cast<size_t>(width); u++) {
tinyexr::FP16 hf;
// hf.u = line_ptr[u];
tinyexr::cpy2(&(hf.u), line_ptr + u);
tinyexr::swap2(reinterpret_cast<unsigned short *>(&hf.u));
if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) {
unsigned short *image =
reinterpret_cast<unsigned short **>(out_images)[c];
if (line_order == 0) {
image += (static_cast<size_t>(line_no) + v) *
static_cast<size_t>(x_stride) +
u;
} else {
image += (static_cast<size_t>(height) - 1U -
(static_cast<size_t>(line_no) + v)) *
static_cast<size_t>(x_stride) +
u;
}
*image = hf.u;
} else { // HALF -> FLOAT
tinyexr::FP32 f32 = half_to_float(hf);
float *image = reinterpret_cast<float **>(out_images)[c];
if (line_order == 0) {
image += (static_cast<size_t>(line_no) + v) *
static_cast<size_t>(x_stride) +
u;
} else {
image += (static_cast<size_t>(height) - 1U -
(static_cast<size_t>(line_no) + v)) *
static_cast<size_t>(x_stride) +
u;
}
*image = f32.f;
}
}
}
} else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) {
assert(requested_pixel_types[c] == TINYEXR_PIXELTYPE_UINT);
for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) {
const unsigned int *line_ptr = reinterpret_cast<unsigned int *>(
&outBuf.at(v * pixel_data_size * static_cast<size_t>(width) +
channel_offset_list[c] * static_cast<size_t>(width)));
for (size_t u = 0; u < static_cast<size_t>(width); u++) {
unsigned int val;
// val = line_ptr[u];
tinyexr::cpy4(&val, line_ptr + u);
tinyexr::swap4(&val);
unsigned int *image =
reinterpret_cast<unsigned int **>(out_images)[c];
if (line_order == 0) {
image += (static_cast<size_t>(line_no) + v) *
static_cast<size_t>(x_stride) +
u;
} else {
image += (static_cast<size_t>(height) - 1U -
(static_cast<size_t>(line_no) + v)) *
static_cast<size_t>(x_stride) +
u;
}
*image = val;
}
}
} else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) {
assert(requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT);
for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) {
const float *line_ptr = reinterpret_cast<float *>(
&outBuf.at(v * pixel_data_size * static_cast<size_t>(width) +
channel_offset_list[c] * static_cast<size_t>(width)));
for (size_t u = 0; u < static_cast<size_t>(width); u++) {
float val;
// val = line_ptr[u];
tinyexr::cpy4(&val, line_ptr + u);
tinyexr::swap4(reinterpret_cast<unsigned int *>(&val));
float *image = reinterpret_cast<float **>(out_images)[c];
if (line_order == 0) {
image += (static_cast<size_t>(line_no) + v) *
static_cast<size_t>(x_stride) +
u;
} else {
image += (static_cast<size_t>(height) - 1U -
(static_cast<size_t>(line_no) + v)) *
static_cast<size_t>(x_stride) +
u;
}
*image = val;
}
}
} else {
assert(0);
return false;
}
}
} else if (compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) {
#if TINYEXR_USE_ZFP
tinyexr::ZFPCompressionParam zfp_compression_param;
std::string e;
if (!tinyexr::FindZFPCompressionParam(&zfp_compression_param, attributes,
int(num_attributes), &e)) {
// This code path should not be reachable.
assert(0);
return false;
}
// Allocate original data size.
std::vector<unsigned char> outBuf(static_cast<size_t>(width) *
static_cast<size_t>(num_lines) *
pixel_data_size);
unsigned long dstLen = outBuf.size();
assert(dstLen > 0);
tinyexr::DecompressZfp(reinterpret_cast<float *>(&outBuf.at(0)), width,
num_lines, num_channels, data_ptr,
static_cast<unsigned long>(data_len),
zfp_compression_param);
// For ZFP_COMPRESSION:
// pixel sample data for channel 0 for scanline 0
// pixel sample data for channel 1 for scanline 0
// pixel sample data for channel ... for scanline 0
// pixel sample data for channel n for scanline 0
// pixel sample data for channel 0 for scanline 1
// pixel sample data for channel 1 for scanline 1
// pixel sample data for channel ... for scanline 1
// pixel sample data for channel n for scanline 1
// ...
for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) {
assert(channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT);
if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) {
assert(requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT);
for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) {
const float *line_ptr = reinterpret_cast<float *>(
&outBuf.at(v * pixel_data_size * static_cast<size_t>(width) +
channel_offset_list[c] * static_cast<size_t>(width)));
for (size_t u = 0; u < static_cast<size_t>(width); u++) {
float val;
tinyexr::cpy4(&val, line_ptr + u);
tinyexr::swap4(reinterpret_cast<unsigned int *>(&val));
float *image = reinterpret_cast<float **>(out_images)[c];
if (line_order == 0) {
image += (static_cast<size_t>(line_no) + v) *
static_cast<size_t>(x_stride) +
u;
} else {
image += (static_cast<size_t>(height) - 1U -
(static_cast<size_t>(line_no) + v)) *
static_cast<size_t>(x_stride) +
u;
}
*image = val;
}
}
} else {
assert(0);
return false;
}
}
#else
(void)attributes;
(void)num_attributes;
(void)num_channels;
assert(0);
return false;
#endif
} else if (compression_type == TINYEXR_COMPRESSIONTYPE_NONE) {
for (size_t c = 0; c < num_channels; c++) {
for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) {
if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) {
const unsigned short *line_ptr =
reinterpret_cast<const unsigned short *>(
data_ptr + v * pixel_data_size * size_t(width) +
channel_offset_list[c] * static_cast<size_t>(width));
if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) {
unsigned short *outLine =
reinterpret_cast<unsigned short *>(out_images[c]);
if (line_order == 0) {
outLine += (size_t(y) + v) * size_t(x_stride);
} else {
outLine +=
(size_t(height) - 1 - (size_t(y) + v)) * size_t(x_stride);
}
for (int u = 0; u < width; u++) {
tinyexr::FP16 hf;
// hf.u = line_ptr[u];
tinyexr::cpy2(&(hf.u), line_ptr + u);
tinyexr::swap2(reinterpret_cast<unsigned short *>(&hf.u));
outLine[u] = hf.u;
}
} else if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT) {
float *outLine = reinterpret_cast<float *>(out_images[c]);
if (line_order == 0) {
outLine += (size_t(y) + v) * size_t(x_stride);
} else {
outLine +=
(size_t(height) - 1 - (size_t(y) + v)) * size_t(x_stride);
}
if (reinterpret_cast<const unsigned char *>(line_ptr + width) >
(data_ptr + data_len)) {
// Insufficient data size
return false;
}
for (int u = 0; u < width; u++) {
tinyexr::FP16 hf;
// address may not be aliged. use byte-wise copy for safety.#76
// hf.u = line_ptr[u];
tinyexr::cpy2(&(hf.u), line_ptr + u);
tinyexr::swap2(reinterpret_cast<unsigned short *>(&hf.u));
tinyexr::FP32 f32 = half_to_float(hf);
outLine[u] = f32.f;
}
} else {
assert(0);
return false;
}
} else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) {
const float *line_ptr = reinterpret_cast<const float *>(
data_ptr + v * pixel_data_size * size_t(width) +
channel_offset_list[c] * static_cast<size_t>(width));
float *outLine = reinterpret_cast<float *>(out_images[c]);
if (line_order == 0) {
outLine += (size_t(y) + v) * size_t(x_stride);
} else {
outLine +=
(size_t(height) - 1 - (size_t(y) + v)) * size_t(x_stride);
}
if (reinterpret_cast<const unsigned char *>(line_ptr + width) >
(data_ptr + data_len)) {
// Insufficient data size
return false;
}
for (int u = 0; u < width; u++) {
float val;
tinyexr::cpy4(&val, line_ptr + u);
tinyexr::swap4(reinterpret_cast<unsigned int *>(&val));
outLine[u] = val;
}
} else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) {
const unsigned int *line_ptr = reinterpret_cast<const unsigned int *>(
data_ptr + v * pixel_data_size * size_t(width) +
channel_offset_list[c] * static_cast<size_t>(width));
unsigned int *outLine =
reinterpret_cast<unsigned int *>(out_images[c]);
if (line_order == 0) {
outLine += (size_t(y) + v) * size_t(x_stride);
} else {
outLine +=
(size_t(height) - 1 - (size_t(y) + v)) * size_t(x_stride);
}
for (int u = 0; u < width; u++) {
if (reinterpret_cast<const unsigned char *>(line_ptr + u) >=
(data_ptr + data_len)) {
// Corrupsed data?
return false;
}
unsigned int val;
tinyexr::cpy4(&val, line_ptr + u);
tinyexr::swap4(reinterpret_cast<unsigned int *>(&val));
outLine[u] = val;
}
}
}
}
}
return true;
}
static bool DecodeTiledPixelData(
unsigned char **out_images, int *width, int *height,
const int *requested_pixel_types, const unsigned char *data_ptr,
size_t data_len, int compression_type, int line_order, int data_width,
int data_height, int tile_offset_x, int tile_offset_y, int tile_size_x,
int tile_size_y, size_t pixel_data_size, size_t num_attributes,
const EXRAttribute *attributes, size_t num_channels,
const EXRChannelInfo *channels,
const std::vector<size_t> &channel_offset_list) {
// Here, data_width and data_height are the dimensions of the current (sub)level.
if (tile_size_x * tile_offset_x > data_width ||
tile_size_y * tile_offset_y > data_height) {
return false;
}
// Compute actual image size in a tile.
if ((tile_offset_x + 1) * tile_size_x >= data_width) {
(*width) = data_width - (tile_offset_x * tile_size_x);
} else {
(*width) = tile_size_x;
}
if ((tile_offset_y + 1) * tile_size_y >= data_height) {
(*height) = data_height - (tile_offset_y * tile_size_y);
} else {
(*height) = tile_size_y;
}
// Image size = tile size.
return DecodePixelData(out_images, requested_pixel_types, data_ptr, data_len,
compression_type, line_order, (*width), tile_size_y,
/* stride */ tile_size_x, /* y */ 0, /* line_no */ 0,
(*height), pixel_data_size, num_attributes, attributes,
num_channels, channels, channel_offset_list);
}
static bool ComputeChannelLayout(std::vector<size_t> *channel_offset_list,
int *pixel_data_size, size_t *channel_offset,
int num_channels,
const EXRChannelInfo *channels) {
channel_offset_list->resize(static_cast<size_t>(num_channels));
(*pixel_data_size) = 0;
(*channel_offset) = 0;
for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) {
(*channel_offset_list)[c] = (*channel_offset);
if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) {
(*pixel_data_size) += sizeof(unsigned short);
(*channel_offset) += sizeof(unsigned short);
} else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) {
(*pixel_data_size) += sizeof(float);
(*channel_offset) += sizeof(float);
} else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) {
(*pixel_data_size) += sizeof(unsigned int);
(*channel_offset) += sizeof(unsigned int);
} else {
// ???
return false;
}
}
return true;
}
static unsigned char **AllocateImage(int num_channels,
const EXRChannelInfo *channels,
const int *requested_pixel_types,
int data_width, int data_height) {
unsigned char **images =
reinterpret_cast<unsigned char **>(static_cast<float **>(
malloc(sizeof(float *) * static_cast<size_t>(num_channels))));
for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) {
size_t data_len =
static_cast<size_t>(data_width) * static_cast<size_t>(data_height);
if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) {
// pixel_data_size += sizeof(unsigned short);
// channel_offset += sizeof(unsigned short);
// Alloc internal image for half type.
if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) {
images[c] =
reinterpret_cast<unsigned char *>(static_cast<unsigned short *>(
malloc(sizeof(unsigned short) * data_len)));
} else if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT) {
images[c] = reinterpret_cast<unsigned char *>(
static_cast<float *>(malloc(sizeof(float) * data_len)));
} else {
assert(0);
}
} else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) {
// pixel_data_size += sizeof(float);
// channel_offset += sizeof(float);
images[c] = reinterpret_cast<unsigned char *>(
static_cast<float *>(malloc(sizeof(float) * data_len)));
} else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) {
// pixel_data_size += sizeof(unsigned int);
// channel_offset += sizeof(unsigned int);
images[c] = reinterpret_cast<unsigned char *>(
static_cast<unsigned int *>(malloc(sizeof(unsigned int) * data_len)));
} else {
assert(0);
}
}
return images;
}
#ifdef _WIN32
static inline std::wstring UTF8ToWchar(const std::string &str) {
int wstr_size =
MultiByteToWideChar(CP_UTF8, 0, str.data(), (int)str.size(), NULL, 0);
std::wstring wstr(wstr_size, 0);
MultiByteToWideChar(CP_UTF8, 0, str.data(), (int)str.size(), &wstr[0],
(int)wstr.size());
return wstr;
}
#endif
static int ParseEXRHeader(HeaderInfo *info, bool *empty_header,
const EXRVersion *version, std::string *err,
const unsigned char *buf, size_t size) {
const char *marker = reinterpret_cast<const char *>(&buf[0]);
if (empty_header) {
(*empty_header) = false;
}
if (version->multipart) {
if (size > 0 && marker[0] == '\0') {
// End of header list.
if (empty_header) {
(*empty_header) = true;
}
return TINYEXR_SUCCESS;
}
}
// According to the spec, the header of every OpenEXR file must contain at
// least the following attributes:
//
// channels chlist
// compression compression
// dataWindow box2i
// displayWindow box2i
// lineOrder lineOrder
// pixelAspectRatio float
// screenWindowCenter v2f
// screenWindowWidth float
bool has_channels = false;
bool has_compression = false;
bool has_data_window = false;
bool has_display_window = false;
bool has_line_order = false;
bool has_pixel_aspect_ratio = false;
bool has_screen_window_center = false;
bool has_screen_window_width = false;
bool has_name = false;
bool has_type = false;
info->name.clear();
info->type.clear();
info->data_window.min_x = 0;
info->data_window.min_y = 0;
info->data_window.max_x = 0;
info->data_window.max_y = 0;
info->line_order = 0; // @fixme
info->display_window.min_x = 0;
info->display_window.min_y = 0;
info->display_window.max_x = 0;
info->display_window.max_y = 0;
info->screen_window_center[0] = 0.0f;
info->screen_window_center[1] = 0.0f;
info->screen_window_width = -1.0f;
info->pixel_aspect_ratio = -1.0f;
info->tiled = 0;
info->tile_size_x = -1;
info->tile_size_y = -1;
info->tile_level_mode = -1;
info->tile_rounding_mode = -1;
info->attributes.clear();
// Read attributes
size_t orig_size = size;
for (size_t nattr = 0; nattr < TINYEXR_MAX_HEADER_ATTRIBUTES; nattr++) {
if (0 == size) {
if (err) {
(*err) += "Insufficient data size for attributes.\n";
}
return TINYEXR_ERROR_INVALID_DATA;
} else if (marker[0] == '\0') {
size--;
break;
}
std::string attr_name;
std::string attr_type;
std::vector<unsigned char> data;
size_t marker_size;
if (!tinyexr::ReadAttribute(&attr_name, &attr_type, &data, &marker_size,
marker, size)) {
if (err) {
(*err) += "Failed to read attribute.\n";
}
return TINYEXR_ERROR_INVALID_DATA;
}
marker += marker_size;
size -= marker_size;
// For a multipart file, the version field 9th bit is 0.
if ((version->tiled || version->multipart || version->non_image) && attr_name.compare("tiles") == 0) {
unsigned int x_size, y_size;
unsigned char tile_mode;
assert(data.size() == 9);
memcpy(&x_size, &data.at(0), sizeof(int));
memcpy(&y_size, &data.at(4), sizeof(int));
tile_mode = data[8];
tinyexr::swap4(&x_size);
tinyexr::swap4(&y_size);
if (x_size > static_cast<unsigned int>(std::numeric_limits<int>::max()) ||
y_size > static_cast<unsigned int>(std::numeric_limits<int>::max())) {
if (err) {
(*err) = "Tile sizes were invalid.";
}
return TINYEXR_ERROR_UNSUPPORTED_FORMAT;
}
info->tile_size_x = static_cast<int>(x_size);
info->tile_size_y = static_cast<int>(y_size);
// mode = levelMode + roundingMode * 16
info->tile_level_mode = tile_mode & 0x3;
info->tile_rounding_mode = (tile_mode >> 4) & 0x1;
info->tiled = 1;
} else if (attr_name.compare("compression") == 0) {
bool ok = false;
if (data[0] < TINYEXR_COMPRESSIONTYPE_PIZ) {
ok = true;
}
if (data[0] == TINYEXR_COMPRESSIONTYPE_PIZ) {
#if TINYEXR_USE_PIZ
ok = true;
#else
if (err) {
(*err) = "PIZ compression is not supported.";
}
return TINYEXR_ERROR_UNSUPPORTED_FORMAT;
#endif
}
if (data[0] == TINYEXR_COMPRESSIONTYPE_ZFP) {
#if TINYEXR_USE_ZFP
ok = true;
#else
if (err) {
(*err) = "ZFP compression is not supported.";
}
return TINYEXR_ERROR_UNSUPPORTED_FORMAT;
#endif
}
if (!ok) {
if (err) {
(*err) = "Unknown compression type.";
}
return TINYEXR_ERROR_UNSUPPORTED_FORMAT;
}
info->compression_type = static_cast<int>(data[0]);
has_compression = true;
} else if (attr_name.compare("channels") == 0) {
// name: zero-terminated string, from 1 to 255 bytes long
// pixel type: int, possible values are: UINT = 0 HALF = 1 FLOAT = 2
// pLinear: unsigned char, possible values are 0 and 1
// reserved: three chars, should be zero
// xSampling: int
// ySampling: int
if (!ReadChannelInfo(info->channels, data)) {
if (err) {
(*err) += "Failed to parse channel info.\n";
}
return TINYEXR_ERROR_INVALID_DATA;
}
if (info->channels.size() < 1) {
if (err) {
(*err) += "# of channels is zero.\n";
}
return TINYEXR_ERROR_INVALID_DATA;
}
has_channels = true;
} else if (attr_name.compare("dataWindow") == 0) {
if (data.size() >= 16) {
memcpy(&info->data_window.min_x, &data.at(0), sizeof(int));
memcpy(&info->data_window.min_y, &data.at(4), sizeof(int));
memcpy(&info->data_window.max_x, &data.at(8), sizeof(int));
memcpy(&info->data_window.max_y, &data.at(12), sizeof(int));
tinyexr::swap4(&info->data_window.min_x);
tinyexr::swap4(&info->data_window.min_y);
tinyexr::swap4(&info->data_window.max_x);
tinyexr::swap4(&info->data_window.max_y);
has_data_window = true;
}
} else if (attr_name.compare("displayWindow") == 0) {
if (data.size() >= 16) {
memcpy(&info->display_window.min_x, &data.at(0), sizeof(int));
memcpy(&info->display_window.min_y, &data.at(4), sizeof(int));
memcpy(&info->display_window.max_x, &data.at(8), sizeof(int));
memcpy(&info->display_window.max_y, &data.at(12), sizeof(int));
tinyexr::swap4(&info->display_window.min_x);
tinyexr::swap4(&info->display_window.min_y);
tinyexr::swap4(&info->display_window.max_x);
tinyexr::swap4(&info->display_window.max_y);
has_display_window = true;
}
} else if (attr_name.compare("lineOrder") == 0) {
if (data.size() >= 1) {
info->line_order = static_cast<int>(data[0]);
has_line_order = true;
}
} else if (attr_name.compare("pixelAspectRatio") == 0) {
if (data.size() >= sizeof(float)) {
memcpy(&info->pixel_aspect_ratio, &data.at(0), sizeof(float));
tinyexr::swap4(&info->pixel_aspect_ratio);
has_pixel_aspect_ratio = true;
}
} else if (attr_name.compare("screenWindowCenter") == 0) {
if (data.size() >= 8) {
memcpy(&info->screen_window_center[0], &data.at(0), sizeof(float));
memcpy(&info->screen_window_center[1], &data.at(4), sizeof(float));
tinyexr::swap4(&info->screen_window_center[0]);
tinyexr::swap4(&info->screen_window_center[1]);
has_screen_window_center = true;
}
} else if (attr_name.compare("screenWindowWidth") == 0) {
if (data.size() >= sizeof(float)) {
memcpy(&info->screen_window_width, &data.at(0), sizeof(float));
tinyexr::swap4(&info->screen_window_width);
has_screen_window_width = true;
}
} else if (attr_name.compare("chunkCount") == 0) {
if (data.size() >= sizeof(int)) {
memcpy(&info->chunk_count, &data.at(0), sizeof(int));
tinyexr::swap4(&info->chunk_count);
}
} else if (attr_name.compare("name") == 0) {
if (!data.empty() && data[0]) {
data.push_back(0);
size_t len = strlen(reinterpret_cast<const char*>(&data[0]));
info->name.resize(len);
info->name.assign(reinterpret_cast<const char*>(&data[0]), len);
has_name = true;
}
} else if (attr_name.compare("type") == 0) {
if (!data.empty() && data[0]) {
data.push_back(0);
size_t len = strlen(reinterpret_cast<const char*>(&data[0]));
info->type.resize(len);
info->type.assign(reinterpret_cast<const char*>(&data[0]), len);
has_type = true;
}
} else {
// Custom attribute(up to TINYEXR_MAX_CUSTOM_ATTRIBUTES)
if (info->attributes.size() < TINYEXR_MAX_CUSTOM_ATTRIBUTES) {
EXRAttribute attrib;
#ifdef _MSC_VER
strncpy_s(attrib.name, attr_name.c_str(), 255);
strncpy_s(attrib.type, attr_type.c_str(), 255);
#else
strncpy(attrib.name, attr_name.c_str(), 255);
strncpy(attrib.type, attr_type.c_str(), 255);
#endif
attrib.name[255] = '\0';
attrib.type[255] = '\0';
attrib.size = static_cast<int>(data.size());
attrib.value = static_cast<unsigned char *>(malloc(data.size()));
memcpy(reinterpret_cast<char *>(attrib.value), &data.at(0),
data.size());
info->attributes.push_back(attrib);
}
}
}
// Check if required attributes exist
{
std::stringstream ss_err;
if (!has_compression) {
ss_err << "\"compression\" attribute not found in the header."
<< std::endl;
}
if (!has_channels) {
ss_err << "\"channels\" attribute not found in the header." << std::endl;
}
if (!has_line_order) {
ss_err << "\"lineOrder\" attribute not found in the header." << std::endl;
}
if (!has_display_window) {
ss_err << "\"displayWindow\" attribute not found in the header."
<< std::endl;
}
if (!has_data_window) {
ss_err << "\"dataWindow\" attribute not found in the header or invalid."
<< std::endl;
}
if (!has_pixel_aspect_ratio) {
ss_err << "\"pixelAspectRatio\" attribute not found in the header."
<< std::endl;
}
if (!has_screen_window_width) {
ss_err << "\"screenWindowWidth\" attribute not found in the header."
<< std::endl;
}
if (!has_screen_window_center) {
ss_err << "\"screenWindowCenter\" attribute not found in the header."
<< std::endl;
}
if (version->multipart || version->non_image) {
if (!has_name) {
ss_err << "\"name\" attribute not found in the header."
<< std::endl;
}
if (!has_type) {
ss_err << "\"type\" attribute not found in the header."
<< std::endl;
}
}
if (!(ss_err.str().empty())) {
if (err) {
(*err) += ss_err.str();
}
return TINYEXR_ERROR_INVALID_HEADER;
}
}
info->header_len = static_cast<unsigned int>(orig_size - size);
return TINYEXR_SUCCESS;
}
// C++ HeaderInfo to C EXRHeader conversion.
static void ConvertHeader(EXRHeader *exr_header, const HeaderInfo &info) {
exr_header->pixel_aspect_ratio = info.pixel_aspect_ratio;
exr_header->screen_window_center[0] = info.screen_window_center[0];
exr_header->screen_window_center[1] = info.screen_window_center[1];
exr_header->screen_window_width = info.screen_window_width;
exr_header->chunk_count = info.chunk_count;
exr_header->display_window.min_x = info.display_window.min_x;
exr_header->display_window.min_y = info.display_window.min_y;
exr_header->display_window.max_x = info.display_window.max_x;
exr_header->display_window.max_y = info.display_window.max_y;
exr_header->data_window.min_x = info.data_window.min_x;
exr_header->data_window.min_y = info.data_window.min_y;
exr_header->data_window.max_x = info.data_window.max_x;
exr_header->data_window.max_y = info.data_window.max_y;
exr_header->line_order = info.line_order;
exr_header->compression_type = info.compression_type;
exr_header->tiled = info.tiled;
exr_header->tile_size_x = info.tile_size_x;
exr_header->tile_size_y = info.tile_size_y;
exr_header->tile_level_mode = info.tile_level_mode;
exr_header->tile_rounding_mode = info.tile_rounding_mode;
EXRSetNameAttr(exr_header, info.name.c_str());
if (!info.type.empty()) {
if (info.type == "scanlineimage") {
assert(!exr_header->tiled);
} else if (info.type == "tiledimage") {
assert(exr_header->tiled);
} else if (info.type == "deeptile") {
exr_header->non_image = 1;
assert(exr_header->tiled);
} else if (info.type == "deepscanline") {
exr_header->non_image = 1;
assert(!exr_header->tiled);
} else {
assert(false);
}
}
exr_header->num_channels = static_cast<int>(info.channels.size());
exr_header->channels = static_cast<EXRChannelInfo *>(malloc(
sizeof(EXRChannelInfo) * static_cast<size_t>(exr_header->num_channels)));
for (size_t c = 0; c < static_cast<size_t>(exr_header->num_channels); c++) {
#ifdef _MSC_VER
strncpy_s(exr_header->channels[c].name, info.channels[c].name.c_str(), 255);
#else
strncpy(exr_header->channels[c].name, info.channels[c].name.c_str(), 255);
#endif
// manually add '\0' for safety.
exr_header->channels[c].name[255] = '\0';
exr_header->channels[c].pixel_type = info.channels[c].pixel_type;
exr_header->channels[c].p_linear = info.channels[c].p_linear;
exr_header->channels[c].x_sampling = info.channels[c].x_sampling;
exr_header->channels[c].y_sampling = info.channels[c].y_sampling;
}
exr_header->pixel_types = static_cast<int *>(
malloc(sizeof(int) * static_cast<size_t>(exr_header->num_channels)));
for (size_t c = 0; c < static_cast<size_t>(exr_header->num_channels); c++) {
exr_header->pixel_types[c] = info.channels[c].pixel_type;
}
// Initially fill with values of `pixel_types`
exr_header->requested_pixel_types = static_cast<int *>(
malloc(sizeof(int) * static_cast<size_t>(exr_header->num_channels)));
for (size_t c = 0; c < static_cast<size_t>(exr_header->num_channels); c++) {
exr_header->requested_pixel_types[c] = info.channels[c].pixel_type;
}
exr_header->num_custom_attributes = static_cast<int>(info.attributes.size());
if (exr_header->num_custom_attributes > 0) {
// TODO(syoyo): Report warning when # of attributes exceeds
// `TINYEXR_MAX_CUSTOM_ATTRIBUTES`
if (exr_header->num_custom_attributes > TINYEXR_MAX_CUSTOM_ATTRIBUTES) {
exr_header->num_custom_attributes = TINYEXR_MAX_CUSTOM_ATTRIBUTES;
}
exr_header->custom_attributes = static_cast<EXRAttribute *>(malloc(
sizeof(EXRAttribute) * size_t(exr_header->num_custom_attributes)));
for (size_t i = 0; i < info.attributes.size(); i++) {
memcpy(exr_header->custom_attributes[i].name, info.attributes[i].name,
256);
memcpy(exr_header->custom_attributes[i].type, info.attributes[i].type,
256);
exr_header->custom_attributes[i].size = info.attributes[i].size;
// Just copy pointer
exr_header->custom_attributes[i].value = info.attributes[i].value;
}
} else {
exr_header->custom_attributes = NULL;
}
exr_header->header_len = info.header_len;
}
struct OffsetData {
OffsetData() : num_x_levels(0), num_y_levels(0) {}
std::vector<std::vector<std::vector <tinyexr::tinyexr_uint64> > > offsets;
int num_x_levels;
int num_y_levels;
};
int LevelIndex(int lx, int ly, int tile_level_mode, int num_x_levels) {
switch (tile_level_mode) {
case TINYEXR_TILE_ONE_LEVEL:
return 0;
case TINYEXR_TILE_MIPMAP_LEVELS:
return lx;
case TINYEXR_TILE_RIPMAP_LEVELS:
return lx + ly * num_x_levels;
default:
assert(false);
}
return 0;
}
static int LevelSize(int toplevel_size, int level, int tile_rounding_mode) {
assert(level >= 0);
int b = (int)(1u << (unsigned)level);
int level_size = toplevel_size / b;
if (tile_rounding_mode == TINYEXR_TILE_ROUND_UP && level_size * b < toplevel_size)
level_size += 1;
return std::max(level_size, 1);
}
static int DecodeTiledLevel(EXRImage* exr_image, const EXRHeader* exr_header,
const OffsetData& offset_data,
const std::vector<size_t>& channel_offset_list,
int pixel_data_size,
const unsigned char* head, const size_t size,
std::string* err) {
int num_channels = exr_header->num_channels;
int level_index = LevelIndex(exr_image->level_x, exr_image->level_y, exr_header->tile_level_mode, offset_data.num_x_levels);
int num_y_tiles = (int)offset_data.offsets[level_index].size();
assert(num_y_tiles);
int num_x_tiles = (int)offset_data.offsets[level_index][0].size();
assert(num_x_tiles);
int num_tiles = num_x_tiles * num_y_tiles;
int err_code = TINYEXR_SUCCESS;
enum {
EF_SUCCESS = 0,
EF_INVALID_DATA = 1,
EF_INSUFFICIENT_DATA = 2,
EF_FAILED_TO_DECODE = 4
};
#if TINYEXR_HAS_CXX11 && (TINYEXR_USE_THREAD > 0)
std::atomic<unsigned> error_flag(EF_SUCCESS);
#else
unsigned error_flag(EF_SUCCESS);
#endif
// Although the spec says : "...the data window is subdivided into an array of smaller rectangles...",
// the IlmImf library allows the dimensions of the tile to be larger (or equal) than the dimensions of the data window.
#if 0
if ((exr_header->tile_size_x > exr_image->width || exr_header->tile_size_y > exr_image->height) &&
exr_image->level_x == 0 && exr_image->level_y == 0) {
if (err) {
(*err) += "Failed to decode tile data.\n";
}
err_code = TINYEXR_ERROR_INVALID_DATA;
}
#endif
exr_image->tiles = static_cast<EXRTile*>(
calloc(sizeof(EXRTile), static_cast<size_t>(num_tiles)));
#if TINYEXR_HAS_CXX11 && (TINYEXR_USE_THREAD > 0)
std::vector<std::thread> workers;
std::atomic<int> tile_count(0);
int num_threads = std::max(1, int(std::thread::hardware_concurrency()));
if (num_threads > int(num_tiles)) {
num_threads = int(num_tiles);
}
for (int t = 0; t < num_threads; t++) {
workers.emplace_back(std::thread([&]()
{
int tile_idx = 0;
while ((tile_idx = tile_count++) < num_tiles) {
#else
#if TINYEXR_USE_OPENMP
#pragma omp parallel for
#endif
for (int tile_idx = 0; tile_idx < num_tiles; tile_idx++) {
#endif
// Allocate memory for each tile.
exr_image->tiles[tile_idx].images = tinyexr::AllocateImage(
num_channels, exr_header->channels,
exr_header->requested_pixel_types, exr_header->tile_size_x,
exr_header->tile_size_y);
int x_tile = tile_idx % num_x_tiles;
int y_tile = tile_idx / num_x_tiles;
// 16 byte: tile coordinates
// 4 byte : data size
// ~ : data(uncompressed or compressed)
tinyexr::tinyexr_uint64 offset = offset_data.offsets[level_index][y_tile][x_tile];
if (offset + sizeof(int) * 5 > size) {
// Insufficient data size.
error_flag |= EF_INSUFFICIENT_DATA;
continue;
}
size_t data_size =
size_t(size - (offset + sizeof(int) * 5));
const unsigned char* data_ptr =
reinterpret_cast<const unsigned char*>(head + offset);
int tile_coordinates[4];
memcpy(tile_coordinates, data_ptr, sizeof(int) * 4);
tinyexr::swap4(&tile_coordinates[0]);
tinyexr::swap4(&tile_coordinates[1]);
tinyexr::swap4(&tile_coordinates[2]);
tinyexr::swap4(&tile_coordinates[3]);
if (tile_coordinates[2] != exr_image->level_x) {
// Invalid data.
error_flag |= EF_INVALID_DATA;
continue;
}
if (tile_coordinates[3] != exr_image->level_y) {
// Invalid data.
error_flag |= EF_INVALID_DATA;
continue;
}
int data_len;
memcpy(&data_len, data_ptr + 16,
sizeof(int)); // 16 = sizeof(tile_coordinates)
tinyexr::swap4(&data_len);
if (data_len < 2 || size_t(data_len) > data_size) {
// Insufficient data size.
error_flag |= EF_INSUFFICIENT_DATA;
continue;
}
// Move to data addr: 20 = 16 + 4;
data_ptr += 20;
bool ret = tinyexr::DecodeTiledPixelData(
exr_image->tiles[tile_idx].images,
&(exr_image->tiles[tile_idx].width),
&(exr_image->tiles[tile_idx].height),
exr_header->requested_pixel_types, data_ptr,
static_cast<size_t>(data_len), exr_header->compression_type,
exr_header->line_order,
exr_image->width, exr_image->height,
tile_coordinates[0], tile_coordinates[1], exr_header->tile_size_x,
exr_header->tile_size_y, static_cast<size_t>(pixel_data_size),
static_cast<size_t>(exr_header->num_custom_attributes),
exr_header->custom_attributes,
static_cast<size_t>(exr_header->num_channels),
exr_header->channels, channel_offset_list);
if (!ret) {
// Failed to decode tile data.
error_flag |= EF_FAILED_TO_DECODE;
}
exr_image->tiles[tile_idx].offset_x = tile_coordinates[0];
exr_image->tiles[tile_idx].offset_y = tile_coordinates[1];
exr_image->tiles[tile_idx].level_x = tile_coordinates[2];
exr_image->tiles[tile_idx].level_y = tile_coordinates[3];
#if TINYEXR_HAS_CXX11 && (TINYEXR_USE_THREAD > 0)
}
}));
} // num_thread loop
for (auto& t : workers) {
t.join();
}
#else
} // parallel for
#endif
// Even in the event of an error, the reserved memory may be freed.
exr_image->num_channels = num_channels;
exr_image->num_tiles = static_cast<int>(num_tiles);
if (error_flag) err_code = TINYEXR_ERROR_INVALID_DATA;
if (err) {
if (error_flag & EF_INSUFFICIENT_DATA) {
(*err) += "Insufficient data length.\n";
}
if (error_flag & EF_FAILED_TO_DECODE) {
(*err) += "Failed to decode tile data.\n";
}
}
return err_code;
}
static int DecodeChunk(EXRImage *exr_image, const EXRHeader *exr_header,
const OffsetData& offset_data,
const unsigned char *head, const size_t size,
std::string *err) {
int num_channels = exr_header->num_channels;
int num_scanline_blocks = 1;
if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZIP) {
num_scanline_blocks = 16;
} else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) {
num_scanline_blocks = 32;
} else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) {
num_scanline_blocks = 16;
#if TINYEXR_USE_ZFP
tinyexr::ZFPCompressionParam zfp_compression_param;
if (!FindZFPCompressionParam(&zfp_compression_param,
exr_header->custom_attributes,
int(exr_header->num_custom_attributes), err)) {
return TINYEXR_ERROR_INVALID_HEADER;
}
#endif
}
if (exr_header->data_window.max_x < exr_header->data_window.min_x ||
exr_header->data_window.max_y < exr_header->data_window.min_y) {
if (err) {
(*err) += "Invalid data window.\n";
}
return TINYEXR_ERROR_INVALID_DATA;
}
int data_width =
exr_header->data_window.max_x - exr_header->data_window.min_x + 1;
int data_height =
exr_header->data_window.max_y - exr_header->data_window.min_y + 1;
// Do not allow too large data_width and data_height. header invalid?
{
if ((data_width > TINYEXR_DIMENSION_THRESHOLD) || (data_height > TINYEXR_DIMENSION_THRESHOLD)) {
if (err) {
std::stringstream ss;
ss << "data_with or data_height too large. data_width: " << data_width
<< ", "
<< "data_height = " << data_height << std::endl;
(*err) += ss.str();
}
return TINYEXR_ERROR_INVALID_DATA;
}
if (exr_header->tiled) {
if ((exr_header->tile_size_x > TINYEXR_DIMENSION_THRESHOLD) || (exr_header->tile_size_y > TINYEXR_DIMENSION_THRESHOLD)) {
if (err) {
std::stringstream ss;
ss << "tile with or tile height too large. tile width: " << exr_header->tile_size_x
<< ", "
<< "tile height = " << exr_header->tile_size_y << std::endl;
(*err) += ss.str();
}
return TINYEXR_ERROR_INVALID_DATA;
}
}
}
const std::vector<tinyexr::tinyexr_uint64>& offsets = offset_data.offsets[0][0];
size_t num_blocks = offsets.size();
std::vector<size_t> channel_offset_list;
int pixel_data_size = 0;
size_t channel_offset = 0;
if (!tinyexr::ComputeChannelLayout(&channel_offset_list, &pixel_data_size,
&channel_offset, num_channels,
exr_header->channels)) {
if (err) {
(*err) += "Failed to compute channel layout.\n";
}
return TINYEXR_ERROR_INVALID_DATA;
}
#if TINYEXR_HAS_CXX11 && (TINYEXR_USE_THREAD > 0)
std::atomic<bool> invalid_data(false);
#else
bool invalid_data(false);
#endif
if (exr_header->tiled) {
// value check
if (exr_header->tile_size_x < 0) {
if (err) {
std::stringstream ss;
ss << "Invalid tile size x : " << exr_header->tile_size_x << "\n";
(*err) += ss.str();
}
return TINYEXR_ERROR_INVALID_HEADER;
}
if (exr_header->tile_size_y < 0) {
if (err) {
std::stringstream ss;
ss << "Invalid tile size y : " << exr_header->tile_size_y << "\n";
(*err) += ss.str();
}
return TINYEXR_ERROR_INVALID_HEADER;
}
if (exr_header->tile_level_mode != TINYEXR_TILE_RIPMAP_LEVELS) {
EXRImage* level_image = NULL;
for (int level = 0; level < offset_data.num_x_levels; ++level) {
if (!level_image) {
level_image = exr_image;
} else {
level_image->next_level = new EXRImage;
InitEXRImage(level_image->next_level);
level_image = level_image->next_level;
}
level_image->width =
LevelSize(exr_header->data_window.max_x - exr_header->data_window.min_x + 1, level, exr_header->tile_rounding_mode);
level_image->height =
LevelSize(exr_header->data_window.max_y - exr_header->data_window.min_y + 1, level, exr_header->tile_rounding_mode);
level_image->level_x = level;
level_image->level_y = level;
int ret = DecodeTiledLevel(level_image, exr_header,
offset_data,
channel_offset_list,
pixel_data_size,
head, size,
err);
if (ret != TINYEXR_SUCCESS) return ret;
}
} else {
EXRImage* level_image = NULL;
for (int level_y = 0; level_y < offset_data.num_y_levels; ++level_y)
for (int level_x = 0; level_x < offset_data.num_x_levels; ++level_x) {
if (!level_image) {
level_image = exr_image;
} else {
level_image->next_level = new EXRImage;
InitEXRImage(level_image->next_level);
level_image = level_image->next_level;
}
level_image->width =
LevelSize(exr_header->data_window.max_x - exr_header->data_window.min_x + 1, level_x, exr_header->tile_rounding_mode);
level_image->height =
LevelSize(exr_header->data_window.max_y - exr_header->data_window.min_y + 1, level_y, exr_header->tile_rounding_mode);
level_image->level_x = level_x;
level_image->level_y = level_y;
int ret = DecodeTiledLevel(level_image, exr_header,
offset_data,
channel_offset_list,
pixel_data_size,
head, size,
err);
if (ret != TINYEXR_SUCCESS) return ret;
}
}
} else { // scanline format
// Don't allow too large image(256GB * pixel_data_size or more). Workaround
// for #104.
size_t total_data_len =
size_t(data_width) * size_t(data_height) * size_t(num_channels);
const bool total_data_len_overflown =
sizeof(void *) == 8 ? (total_data_len >= 0x4000000000) : false;
if ((total_data_len == 0) || total_data_len_overflown) {
if (err) {
std::stringstream ss;
ss << "Image data size is zero or too large: width = " << data_width
<< ", height = " << data_height << ", channels = " << num_channels
<< std::endl;
(*err) += ss.str();
}
return TINYEXR_ERROR_INVALID_DATA;
}
exr_image->images = tinyexr::AllocateImage(
num_channels, exr_header->channels, exr_header->requested_pixel_types,
data_width, data_height);
#if TINYEXR_HAS_CXX11 && (TINYEXR_USE_THREAD > 0)
std::vector<std::thread> workers;
std::atomic<int> y_count(0);
int num_threads = std::max(1, int(std::thread::hardware_concurrency()));
if (num_threads > int(num_blocks)) {
num_threads = int(num_blocks);
}
for (int t = 0; t < num_threads; t++) {
workers.emplace_back(std::thread([&]() {
int y = 0;
while ((y = y_count++) < int(num_blocks)) {
#else
#if TINYEXR_USE_OPENMP
#pragma omp parallel for
#endif
for (int y = 0; y < static_cast<int>(num_blocks); y++) {
#endif
size_t y_idx = static_cast<size_t>(y);
if (offsets[y_idx] + sizeof(int) * 2 > size) {
invalid_data = true;
} else {
// 4 byte: scan line
// 4 byte: data size
// ~ : pixel data(uncompressed or compressed)
size_t data_size =
size_t(size - (offsets[y_idx] + sizeof(int) * 2));
const unsigned char *data_ptr =
reinterpret_cast<const unsigned char *>(head + offsets[y_idx]);
int line_no;
memcpy(&line_no, data_ptr, sizeof(int));
int data_len;
memcpy(&data_len, data_ptr + 4, sizeof(int));
tinyexr::swap4(&line_no);
tinyexr::swap4(&data_len);
if (size_t(data_len) > data_size) {
invalid_data = true;
} else if ((line_no > (2 << 20)) || (line_no < -(2 << 20))) {
// Too large value. Assume this is invalid
// 2**20 = 1048576 = heuristic value.
invalid_data = true;
} else if (data_len == 0) {
// TODO(syoyo): May be ok to raise the threshold for example
// `data_len < 4`
invalid_data = true;
} else {
// line_no may be negative.
int end_line_no = (std::min)(line_no + num_scanline_blocks,
(exr_header->data_window.max_y + 1));
int num_lines = end_line_no - line_no;
if (num_lines <= 0) {
invalid_data = true;
} else {
// Move to data addr: 8 = 4 + 4;
data_ptr += 8;
// Adjust line_no with data_window.bmin.y
// overflow check
tinyexr_int64 lno =
static_cast<tinyexr_int64>(line_no) -
static_cast<tinyexr_int64>(exr_header->data_window.min_y);
if (lno > std::numeric_limits<int>::max()) {
line_no = -1; // invalid
} else if (lno < -std::numeric_limits<int>::max()) {
line_no = -1; // invalid
} else {
line_no -= exr_header->data_window.min_y;
}
if (line_no < 0) {
invalid_data = true;
} else {
if (!tinyexr::DecodePixelData(
exr_image->images, exr_header->requested_pixel_types,
data_ptr, static_cast<size_t>(data_len),
exr_header->compression_type, exr_header->line_order,
data_width, data_height, data_width, y, line_no,
num_lines, static_cast<size_t>(pixel_data_size),
static_cast<size_t>(
exr_header->num_custom_attributes),
exr_header->custom_attributes,
static_cast<size_t>(exr_header->num_channels),
exr_header->channels, channel_offset_list)) {
invalid_data = true;
}
}
}
}
}
#if TINYEXR_HAS_CXX11 && (TINYEXR_USE_THREAD > 0)
}
}));
}
for (auto &t : workers) {
t.join();
}
#else
} // omp parallel
#endif
}
if (invalid_data) {
if (err) {
std::stringstream ss;
(*err) += "Invalid data found when decoding pixels.\n";
}
return TINYEXR_ERROR_INVALID_DATA;
}
// Overwrite `pixel_type` with `requested_pixel_type`.
{
for (int c = 0; c < exr_header->num_channels; c++) {
exr_header->pixel_types[c] = exr_header->requested_pixel_types[c];
}
}
{
exr_image->num_channels = num_channels;
exr_image->width = data_width;
exr_image->height = data_height;
}
return TINYEXR_SUCCESS;
}
static bool ReconstructLineOffsets(
std::vector<tinyexr::tinyexr_uint64> *offsets, size_t n,
const unsigned char *head, const unsigned char *marker, const size_t size) {
assert(head < marker);
assert(offsets->size() == n);
for (size_t i = 0; i < n; i++) {
size_t offset = static_cast<size_t>(marker - head);
// Offset should not exceed whole EXR file/data size.
if ((offset + sizeof(tinyexr::tinyexr_uint64)) >= size) {
return false;
}
int y;
unsigned int data_len;
memcpy(&y, marker, sizeof(int));
memcpy(&data_len, marker + 4, sizeof(unsigned int));
if (data_len >= size) {
return false;
}
tinyexr::swap4(&y);
tinyexr::swap4(&data_len);
(*offsets)[i] = offset;
marker += data_len + 8; // 8 = 4 bytes(y) + 4 bytes(data_len)
}
return true;
}
static int FloorLog2(unsigned x) {
//
// For x > 0, floorLog2(y) returns floor(log(x)/log(2)).
//
int y = 0;
while (x > 1) {
y += 1;
x >>= 1u;
}
return y;
}
static int CeilLog2(unsigned x) {
//
// For x > 0, ceilLog2(y) returns ceil(log(x)/log(2)).
//
int y = 0;
int r = 0;
while (x > 1) {
if (x & 1)
r = 1;
y += 1;
x >>= 1u;
}
return y + r;
}
static int RoundLog2(int x, int tile_rounding_mode) {
return (tile_rounding_mode == TINYEXR_TILE_ROUND_DOWN) ? FloorLog2(static_cast<unsigned>(x)) : CeilLog2(static_cast<unsigned>(x));
}
static int CalculateNumXLevels(const EXRHeader* exr_header) {
int min_x = exr_header->data_window.min_x;
int max_x = exr_header->data_window.max_x;
int min_y = exr_header->data_window.min_y;
int max_y = exr_header->data_window.max_y;
int num = 0;
switch (exr_header->tile_level_mode) {
case TINYEXR_TILE_ONE_LEVEL:
num = 1;
break;
case TINYEXR_TILE_MIPMAP_LEVELS:
{
int w = max_x - min_x + 1;
int h = max_y - min_y + 1;
num = RoundLog2(std::max(w, h), exr_header->tile_rounding_mode) + 1;
}
break;
case TINYEXR_TILE_RIPMAP_LEVELS:
{
int w = max_x - min_x + 1;
num = RoundLog2(w, exr_header->tile_rounding_mode) + 1;
}
break;
default:
assert(false);
}
return num;
}
static int CalculateNumYLevels(const EXRHeader* exr_header) {
int min_x = exr_header->data_window.min_x;
int max_x = exr_header->data_window.max_x;
int min_y = exr_header->data_window.min_y;
int max_y = exr_header->data_window.max_y;
int num = 0;
switch (exr_header->tile_level_mode) {
case TINYEXR_TILE_ONE_LEVEL:
num = 1;
break;
case TINYEXR_TILE_MIPMAP_LEVELS:
{
int w = max_x - min_x + 1;
int h = max_y - min_y + 1;
num = RoundLog2(std::max(w, h), exr_header->tile_rounding_mode) + 1;
}
break;
case TINYEXR_TILE_RIPMAP_LEVELS:
{
int h = max_y - min_y + 1;
num = RoundLog2(h, exr_header->tile_rounding_mode) + 1;
}
break;
default:
assert(false);
}
return num;
}
static void CalculateNumTiles(std::vector<int>& numTiles,
int toplevel_size,
int size,
int tile_rounding_mode) {
for (unsigned i = 0; i < numTiles.size(); i++) {
int l = LevelSize(toplevel_size, i, tile_rounding_mode);
assert(l <= std::numeric_limits<int>::max() - size + 1);
numTiles[i] = (l + size - 1) / size;
}
}
static void PrecalculateTileInfo(std::vector<int>& num_x_tiles,
std::vector<int>& num_y_tiles,
const EXRHeader* exr_header) {
int min_x = exr_header->data_window.min_x;
int max_x = exr_header->data_window.max_x;
int min_y = exr_header->data_window.min_y;
int max_y = exr_header->data_window.max_y;
int num_x_levels = CalculateNumXLevels(exr_header);
int num_y_levels = CalculateNumYLevels(exr_header);
num_x_tiles.resize(num_x_levels);
num_y_tiles.resize(num_y_levels);
CalculateNumTiles(num_x_tiles,
max_x - min_x + 1,
exr_header->tile_size_x,
exr_header->tile_rounding_mode);
CalculateNumTiles(num_y_tiles,
max_y - min_y + 1,
exr_header->tile_size_y,
exr_header->tile_rounding_mode);
}
static void InitSingleResolutionOffsets(OffsetData& offset_data, size_t num_blocks) {
offset_data.offsets.resize(1);
offset_data.offsets[0].resize(1);
offset_data.offsets[0][0].resize(num_blocks);
offset_data.num_x_levels = 1;
offset_data.num_y_levels = 1;
}
// Return sum of tile blocks.
static int InitTileOffsets(OffsetData& offset_data,
const EXRHeader* exr_header,
const std::vector<int>& num_x_tiles,
const std::vector<int>& num_y_tiles) {
int num_tile_blocks = 0;
offset_data.num_x_levels = static_cast<int>(num_x_tiles.size());
offset_data.num_y_levels = static_cast<int>(num_y_tiles.size());
switch (exr_header->tile_level_mode) {
case TINYEXR_TILE_ONE_LEVEL:
case TINYEXR_TILE_MIPMAP_LEVELS:
assert(offset_data.num_x_levels == offset_data.num_y_levels);
offset_data.offsets.resize(offset_data.num_x_levels);
for (unsigned int l = 0; l < offset_data.offsets.size(); ++l) {
offset_data.offsets[l].resize(num_y_tiles[l]);
for (unsigned int dy = 0; dy < offset_data.offsets[l].size(); ++dy) {
offset_data.offsets[l][dy].resize(num_x_tiles[l]);
num_tile_blocks += num_x_tiles[l];
}
}
break;
case TINYEXR_TILE_RIPMAP_LEVELS:
offset_data.offsets.resize(static_cast<size_t>(offset_data.num_x_levels) * static_cast<size_t>(offset_data.num_y_levels));
for (int ly = 0; ly < offset_data.num_y_levels; ++ly) {
for (int lx = 0; lx < offset_data.num_x_levels; ++lx) {
int l = ly * offset_data.num_x_levels + lx;
offset_data.offsets[l].resize(num_y_tiles[ly]);
for (size_t dy = 0; dy < offset_data.offsets[l].size(); ++dy) {
offset_data.offsets[l][dy].resize(num_x_tiles[lx]);
num_tile_blocks += num_x_tiles[lx];
}
}
}
break;
default:
assert(false);
}
return num_tile_blocks;
}
static bool IsAnyOffsetsAreInvalid(const OffsetData& offset_data) {
for (unsigned int l = 0; l < offset_data.offsets.size(); ++l)
for (unsigned int dy = 0; dy < offset_data.offsets[l].size(); ++dy)
for (unsigned int dx = 0; dx < offset_data.offsets[l][dy].size(); ++dx)
if (reinterpret_cast<const tinyexr::tinyexr_int64&>(offset_data.offsets[l][dy][dx]) <= 0)
return true;
return false;
}
static bool isValidTile(const EXRHeader* exr_header,
const OffsetData& offset_data,
int dx, int dy, int lx, int ly) {
if (lx < 0 || ly < 0 || dx < 0 || dy < 0) return false;
int num_x_levels = offset_data.num_x_levels;
int num_y_levels = offset_data.num_y_levels;
switch (exr_header->tile_level_mode) {
case TINYEXR_TILE_ONE_LEVEL:
if (lx == 0 &&
ly == 0 &&
offset_data.offsets.size() > 0 &&
offset_data.offsets[0].size() > static_cast<size_t>(dy) &&
offset_data.offsets[0][dy].size() > static_cast<size_t>(dx)) {
return true;
}
break;
case TINYEXR_TILE_MIPMAP_LEVELS:
if (lx < num_x_levels &&
ly < num_y_levels &&
offset_data.offsets.size() > static_cast<size_t>(lx) &&
offset_data.offsets[lx].size() > static_cast<size_t>(dy) &&
offset_data.offsets[lx][dy].size() > static_cast<size_t>(dx)) {
return true;
}
break;
case TINYEXR_TILE_RIPMAP_LEVELS:
{
size_t idx = static_cast<size_t>(lx) + static_cast<size_t>(ly)* static_cast<size_t>(num_x_levels);
if (lx < num_x_levels &&
ly < num_y_levels &&
(offset_data.offsets.size() > idx) &&
offset_data.offsets[idx].size() > static_cast<size_t>(dy) &&
offset_data.offsets[idx][dy].size() > static_cast<size_t>(dx)) {
return true;
}
}
break;
default:
return false;
}
return false;
}
static void ReconstructTileOffsets(OffsetData& offset_data,
const EXRHeader* exr_header,
const unsigned char* head, const unsigned char* marker, const size_t /*size*/,
bool isMultiPartFile,
bool isDeep) {
int numXLevels = offset_data.num_x_levels;
for (unsigned int l = 0; l < offset_data.offsets.size(); ++l) {
for (unsigned int dy = 0; dy < offset_data.offsets[l].size(); ++dy) {
for (unsigned int dx = 0; dx < offset_data.offsets[l][dy].size(); ++dx) {
tinyexr::tinyexr_uint64 tileOffset = marker - head;
if (isMultiPartFile) {
//int partNumber;
marker += sizeof(int);
}
int tileX;
memcpy(&tileX, marker, sizeof(int));
tinyexr::swap4(&tileX);
marker += sizeof(int);
int tileY;
memcpy(&tileY, marker, sizeof(int));
tinyexr::swap4(&tileY);
marker += sizeof(int);
int levelX;
memcpy(&levelX, marker, sizeof(int));
tinyexr::swap4(&levelX);
marker += sizeof(int);
int levelY;
memcpy(&levelY, marker, sizeof(int));
tinyexr::swap4(&levelY);
marker += sizeof(int);
if (isDeep) {
tinyexr::tinyexr_int64 packed_offset_table_size;
memcpy(&packed_offset_table_size, marker, sizeof(tinyexr::tinyexr_int64));
tinyexr::swap8(reinterpret_cast<tinyexr::tinyexr_uint64*>(&packed_offset_table_size));
marker += sizeof(tinyexr::tinyexr_int64);
tinyexr::tinyexr_int64 packed_sample_size;
memcpy(&packed_sample_size, marker, sizeof(tinyexr::tinyexr_int64));
tinyexr::swap8(reinterpret_cast<tinyexr::tinyexr_uint64*>(&packed_sample_size));
marker += sizeof(tinyexr::tinyexr_int64);
// next Int64 is unpacked sample size - skip that too
marker += packed_offset_table_size + packed_sample_size + 8;
} else {
int dataSize;
memcpy(&dataSize, marker, sizeof(int));
tinyexr::swap4(&dataSize);
marker += sizeof(int);
marker += dataSize;
}
if (!isValidTile(exr_header, offset_data,
tileX, tileY, levelX, levelY))
return;
int level_idx = LevelIndex(levelX, levelY, exr_header->tile_level_mode, numXLevels);
offset_data.offsets[level_idx][tileY][tileX] = tileOffset;
}
}
}
}
// marker output is also
static int ReadOffsets(OffsetData& offset_data,
const unsigned char* head,
const unsigned char*& marker,
const size_t size,
const char** err) {
for (unsigned int l = 0; l < offset_data.offsets.size(); ++l) {
for (unsigned int dy = 0; dy < offset_data.offsets[l].size(); ++dy) {
for (unsigned int dx = 0; dx < offset_data.offsets[l][dy].size(); ++dx) {
tinyexr::tinyexr_uint64 offset;
if ((marker + sizeof(tinyexr_uint64)) >= (head + size)) {
tinyexr::SetErrorMessage("Insufficient data size in offset table.", err);
return TINYEXR_ERROR_INVALID_DATA;
}
memcpy(&offset, marker, sizeof(tinyexr::tinyexr_uint64));
tinyexr::swap8(&offset);
if (offset >= size) {
tinyexr::SetErrorMessage("Invalid offset value in DecodeEXRImage.", err);
return TINYEXR_ERROR_INVALID_DATA;
}
marker += sizeof(tinyexr::tinyexr_uint64); // = 8
offset_data.offsets[l][dy][dx] = offset;
}
}
}
return TINYEXR_SUCCESS;
}
static int DecodeEXRImage(EXRImage *exr_image, const EXRHeader *exr_header,
const unsigned char *head,
const unsigned char *marker, const size_t size,
const char **err) {
if (exr_image == NULL || exr_header == NULL || head == NULL ||
marker == NULL || (size <= tinyexr::kEXRVersionSize)) {
tinyexr::SetErrorMessage("Invalid argument for DecodeEXRImage().", err);
return TINYEXR_ERROR_INVALID_ARGUMENT;
}
int num_scanline_blocks = 1;
if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZIP) {
num_scanline_blocks = 16;
} else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) {
num_scanline_blocks = 32;
} else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) {
num_scanline_blocks = 16;
}
if (exr_header->data_window.max_x < exr_header->data_window.min_x ||
exr_header->data_window.max_x - exr_header->data_window.min_x ==
std::numeric_limits<int>::max()) {
// Issue 63
tinyexr::SetErrorMessage("Invalid data width value", err);
return TINYEXR_ERROR_INVALID_DATA;
}
int data_width =
exr_header->data_window.max_x - exr_header->data_window.min_x + 1;
if (exr_header->data_window.max_y < exr_header->data_window.min_y ||
exr_header->data_window.max_y - exr_header->data_window.min_y ==
std::numeric_limits<int>::max()) {
tinyexr::SetErrorMessage("Invalid data height value", err);
return TINYEXR_ERROR_INVALID_DATA;
}
int data_height =
exr_header->data_window.max_y - exr_header->data_window.min_y + 1;
// Do not allow too large data_width and data_height. header invalid?
{
if (data_width > TINYEXR_DIMENSION_THRESHOLD) {
tinyexr::SetErrorMessage("data width too large.", err);
return TINYEXR_ERROR_INVALID_DATA;
}
if (data_height > TINYEXR_DIMENSION_THRESHOLD) {
tinyexr::SetErrorMessage("data height too large.", err);
return TINYEXR_ERROR_INVALID_DATA;
}
}
if (exr_header->tiled) {
if (exr_header->tile_size_x > TINYEXR_DIMENSION_THRESHOLD) {
tinyexr::SetErrorMessage("tile width too large.", err);
return TINYEXR_ERROR_INVALID_DATA;
}
if (exr_header->tile_size_y > TINYEXR_DIMENSION_THRESHOLD) {
tinyexr::SetErrorMessage("tile height too large.", err);
return TINYEXR_ERROR_INVALID_DATA;
}
}
// Read offset tables.
OffsetData offset_data;
size_t num_blocks = 0;
// For a multi-resolution image, the size of the offset table will be calculated from the other attributes of the header.
// If chunk_count > 0 then chunk_count must be equal to the calculated tile count.
if (exr_header->tiled) {
{
std::vector<int> num_x_tiles, num_y_tiles;
PrecalculateTileInfo(num_x_tiles, num_y_tiles, exr_header);
num_blocks = InitTileOffsets(offset_data, exr_header, num_x_tiles, num_y_tiles);
if (exr_header->chunk_count > 0) {
if (exr_header->chunk_count != static_cast<int>(num_blocks)) {
tinyexr::SetErrorMessage("Invalid offset table size.", err);
return TINYEXR_ERROR_INVALID_DATA;
}
}
}
int ret = ReadOffsets(offset_data, head, marker, size, err);
if (ret != TINYEXR_SUCCESS) return ret;
if (IsAnyOffsetsAreInvalid(offset_data)) {
ReconstructTileOffsets(offset_data, exr_header,
head, marker, size,
exr_header->multipart, exr_header->non_image);
}
} else if (exr_header->chunk_count > 0) {
// Use `chunkCount` attribute.
num_blocks = static_cast<size_t>(exr_header->chunk_count);
InitSingleResolutionOffsets(offset_data, num_blocks);
} else {
num_blocks = static_cast<size_t>(data_height) /
static_cast<size_t>(num_scanline_blocks);
if (num_blocks * static_cast<size_t>(num_scanline_blocks) <
static_cast<size_t>(data_height)) {
num_blocks++;
}
InitSingleResolutionOffsets(offset_data, num_blocks);
}
if (!exr_header->tiled) {
std::vector<tinyexr::tinyexr_uint64>& offsets = offset_data.offsets[0][0];
for (size_t y = 0; y < num_blocks; y++) {
tinyexr::tinyexr_uint64 offset;
// Issue #81
if ((marker + sizeof(tinyexr_uint64)) >= (head + size)) {
tinyexr::SetErrorMessage("Insufficient data size in offset table.", err);
return TINYEXR_ERROR_INVALID_DATA;
}
memcpy(&offset, marker, sizeof(tinyexr::tinyexr_uint64));
tinyexr::swap8(&offset);
if (offset >= size) {
tinyexr::SetErrorMessage("Invalid offset value in DecodeEXRImage.", err);
return TINYEXR_ERROR_INVALID_DATA;
}
marker += sizeof(tinyexr::tinyexr_uint64); // = 8
offsets[y] = offset;
}
// If line offsets are invalid, we try to reconstruct it.
// See OpenEXR/IlmImf/ImfScanLineInputFile.cpp::readLineOffsets() for details.
for (size_t y = 0; y < num_blocks; y++) {
if (offsets[y] <= 0) {
// TODO(syoyo) Report as warning?
// if (err) {
// stringstream ss;
// ss << "Incomplete lineOffsets." << std::endl;
// (*err) += ss.str();
//}
bool ret =
ReconstructLineOffsets(&offsets, num_blocks, head, marker, size);
if (ret) {
// OK
break;
} else {
tinyexr::SetErrorMessage(
"Cannot reconstruct lineOffset table in DecodeEXRImage.", err);
return TINYEXR_ERROR_INVALID_DATA;
}
}
}
}
{
std::string e;
int ret = DecodeChunk(exr_image, exr_header, offset_data, head, size, &e);
if (ret != TINYEXR_SUCCESS) {
if (!e.empty()) {
tinyexr::SetErrorMessage(e, err);
}
#if 1
FreeEXRImage(exr_image);
#else
// release memory(if exists)
if ((exr_header->num_channels > 0) && exr_image && exr_image->images) {
for (size_t c = 0; c < size_t(exr_header->num_channels); c++) {
if (exr_image->images[c]) {
free(exr_image->images[c]);
exr_image->images[c] = NULL;
}
}
free(exr_image->images);
exr_image->images = NULL;
}
#endif
}
return ret;
}
}
static void GetLayers(const EXRHeader &exr_header,
std::vector<std::string> &layer_names) {
// Naive implementation
// Group channels by layers
// go over all channel names, split by periods
// collect unique names
layer_names.clear();
for (int c = 0; c < exr_header.num_channels; c++) {
std::string full_name(exr_header.channels[c].name);
const size_t pos = full_name.find_last_of('.');
if (pos != std::string::npos && pos != 0 && pos + 1 < full_name.size()) {
full_name.erase(pos);
if (std::find(layer_names.begin(), layer_names.end(), full_name) ==
layer_names.end())
layer_names.push_back(full_name);
}
}
}
struct LayerChannel {
explicit LayerChannel(size_t i, std::string n) : index(i), name(n) {}
size_t index;
std::string name;
};
static void ChannelsInLayer(const EXRHeader &exr_header,
const std::string layer_name,
std::vector<LayerChannel> &channels) {
channels.clear();
for (int c = 0; c < exr_header.num_channels; c++) {
std::string ch_name(exr_header.channels[c].name);
if (layer_name.empty()) {
const size_t pos = ch_name.find_last_of('.');
if (pos != std::string::npos && pos < ch_name.size()) {
ch_name = ch_name.substr(pos + 1);
}
} else {
const size_t pos = ch_name.find(layer_name + '.');
if (pos == std::string::npos) continue;
if (pos == 0) {
ch_name = ch_name.substr(layer_name.size() + 1);
}
}
LayerChannel ch(size_t(c), ch_name);
channels.push_back(ch);
}
}
} // namespace tinyexr
int EXRLayers(const char *filename, const char **layer_names[], int *num_layers,
const char **err) {
EXRVersion exr_version;
EXRHeader exr_header;
InitEXRHeader(&exr_header);
{
int ret = ParseEXRVersionFromFile(&exr_version, filename);
if (ret != TINYEXR_SUCCESS) {
tinyexr::SetErrorMessage("Invalid EXR header.", err);
return ret;
}
if (exr_version.multipart || exr_version.non_image) {
tinyexr::SetErrorMessage(
"Loading multipart or DeepImage is not supported in LoadEXR() API",
err);
return TINYEXR_ERROR_INVALID_DATA; // @fixme.
}
}
int ret = ParseEXRHeaderFromFile(&exr_header, &exr_version, filename, err);
if (ret != TINYEXR_SUCCESS) {
FreeEXRHeader(&exr_header);
return ret;
}
std::vector<std::string> layer_vec;
tinyexr::GetLayers(exr_header, layer_vec);
(*num_layers) = int(layer_vec.size());
(*layer_names) = static_cast<const char **>(
malloc(sizeof(const char *) * static_cast<size_t>(layer_vec.size())));
for (size_t c = 0; c < static_cast<size_t>(layer_vec.size()); c++) {
#ifdef _MSC_VER
(*layer_names)[c] = _strdup(layer_vec[c].c_str());
#else
(*layer_names)[c] = strdup(layer_vec[c].c_str());
#endif
}
FreeEXRHeader(&exr_header);
return TINYEXR_SUCCESS;
}
int LoadEXR(float **out_rgba, int *width, int *height, const char *filename,
const char **err) {
return LoadEXRWithLayer(out_rgba, width, height, filename,
/* layername */ NULL, err);
}
int LoadEXRWithLayer(float **out_rgba, int *width, int *height,
const char *filename, const char *layername,
const char **err) {
if (out_rgba == NULL) {
tinyexr::SetErrorMessage("Invalid argument for LoadEXR()", err);
return TINYEXR_ERROR_INVALID_ARGUMENT;
}
EXRVersion exr_version;
EXRImage exr_image;
EXRHeader exr_header;
InitEXRHeader(&exr_header);
InitEXRImage(&exr_image);
{
int ret = ParseEXRVersionFromFile(&exr_version, filename);
if (ret != TINYEXR_SUCCESS) {
std::stringstream ss;
ss << "Failed to open EXR file or read version info from EXR file. code("
<< ret << ")";
tinyexr::SetErrorMessage(ss.str(), err);
return ret;
}
if (exr_version.multipart || exr_version.non_image) {
tinyexr::SetErrorMessage(
"Loading multipart or DeepImage is not supported in LoadEXR() API",
err);
return TINYEXR_ERROR_INVALID_DATA; // @fixme.
}
}
{
int ret = ParseEXRHeaderFromFile(&exr_header, &exr_version, filename, err);
if (ret != TINYEXR_SUCCESS) {
FreeEXRHeader(&exr_header);
return ret;
}
}
// Read HALF channel as FLOAT.
for (int i = 0; i < exr_header.num_channels; i++) {
if (exr_header.pixel_types[i] == TINYEXR_PIXELTYPE_HALF) {
exr_header.requested_pixel_types[i] = TINYEXR_PIXELTYPE_FLOAT;
}
}
// TODO: Probably limit loading to layers (channels) selected by layer index
{
int ret = LoadEXRImageFromFile(&exr_image, &exr_header, filename, err);
if (ret != TINYEXR_SUCCESS) {
FreeEXRHeader(&exr_header);
return ret;
}
}
// RGBA
int idxR = -1;
int idxG = -1;
int idxB = -1;
int idxA = -1;
std::vector<std::string> layer_names;
tinyexr::GetLayers(exr_header, layer_names);
std::vector<tinyexr::LayerChannel> channels;
tinyexr::ChannelsInLayer(
exr_header, layername == NULL ? "" : std::string(layername), channels);
if (channels.size() < 1) {
tinyexr::SetErrorMessage("Layer Not Found", err);
FreeEXRHeader(&exr_header);
FreeEXRImage(&exr_image);
return TINYEXR_ERROR_LAYER_NOT_FOUND;
}
size_t ch_count = channels.size() < 4 ? channels.size() : 4;
for (size_t c = 0; c < ch_count; c++) {
const tinyexr::LayerChannel &ch = channels[c];
if (ch.name == "R") {
idxR = int(ch.index);
} else if (ch.name == "G") {
idxG = int(ch.index);
} else if (ch.name == "B") {
idxB = int(ch.index);
} else if (ch.name == "A") {
idxA = int(ch.index);
}
}
if (channels.size() == 1) {
int chIdx = int(channels.front().index);
// Grayscale channel only.
(*out_rgba) = reinterpret_cast<float *>(
malloc(4 * sizeof(float) * static_cast<size_t>(exr_image.width) *
static_cast<size_t>(exr_image.height)));
if (exr_header.tiled) {
for (int it = 0; it < exr_image.num_tiles; it++) {
for (int j = 0; j < exr_header.tile_size_y; j++) {
for (int i = 0; i < exr_header.tile_size_x; i++) {
const int ii = exr_image.tiles[it].offset_x *
static_cast<int>(exr_header.tile_size_x) +
i;
const int jj = exr_image.tiles[it].offset_y *
static_cast<int>(exr_header.tile_size_y) +
j;
const int idx = ii + jj * static_cast<int>(exr_image.width);
// out of region check.
if (ii >= exr_image.width) {
continue;
}
if (jj >= exr_image.height) {
continue;
}
const int srcIdx = i + j * exr_header.tile_size_x;
unsigned char **src = exr_image.tiles[it].images;
(*out_rgba)[4 * idx + 0] =
reinterpret_cast<float **>(src)[chIdx][srcIdx];
(*out_rgba)[4 * idx + 1] =
reinterpret_cast<float **>(src)[chIdx][srcIdx];
(*out_rgba)[4 * idx + 2] =
reinterpret_cast<float **>(src)[chIdx][srcIdx];
(*out_rgba)[4 * idx + 3] =
reinterpret_cast<float **>(src)[chIdx][srcIdx];
}
}
}
} else {
for (int i = 0; i < exr_image.width * exr_image.height; i++) {
const float val =
reinterpret_cast<float **>(exr_image.images)[chIdx][i];
(*out_rgba)[4 * i + 0] = val;
(*out_rgba)[4 * i + 1] = val;
(*out_rgba)[4 * i + 2] = val;
(*out_rgba)[4 * i + 3] = val;
}
}
} else {
// Assume RGB(A)
if (idxR == -1) {
tinyexr::SetErrorMessage("R channel not found", err);
FreeEXRHeader(&exr_header);
FreeEXRImage(&exr_image);
return TINYEXR_ERROR_INVALID_DATA;
}
if (idxG == -1) {
tinyexr::SetErrorMessage("G channel not found", err);
FreeEXRHeader(&exr_header);
FreeEXRImage(&exr_image);
return TINYEXR_ERROR_INVALID_DATA;
}
if (idxB == -1) {
tinyexr::SetErrorMessage("B channel not found", err);
FreeEXRHeader(&exr_header);
FreeEXRImage(&exr_image);
return TINYEXR_ERROR_INVALID_DATA;
}
(*out_rgba) = reinterpret_cast<float *>(
malloc(4 * sizeof(float) * static_cast<size_t>(exr_image.width) *
static_cast<size_t>(exr_image.height)));
if (exr_header.tiled) {
for (int it = 0; it < exr_image.num_tiles; it++) {
for (int j = 0; j < exr_header.tile_size_y; j++) {
for (int i = 0; i < exr_header.tile_size_x; i++) {
const int ii =
exr_image.tiles[it].offset_x * exr_header.tile_size_x + i;
const int jj =
exr_image.tiles[it].offset_y * exr_header.tile_size_y + j;
const int idx = ii + jj * exr_image.width;
// out of region check.
if (ii >= exr_image.width) {
continue;
}
if (jj >= exr_image.height) {
continue;
}
const int srcIdx = i + j * exr_header.tile_size_x;
unsigned char **src = exr_image.tiles[it].images;
(*out_rgba)[4 * idx + 0] =
reinterpret_cast<float **>(src)[idxR][srcIdx];
(*out_rgba)[4 * idx + 1] =
reinterpret_cast<float **>(src)[idxG][srcIdx];
(*out_rgba)[4 * idx + 2] =
reinterpret_cast<float **>(src)[idxB][srcIdx];
if (idxA != -1) {
(*out_rgba)[4 * idx + 3] =
reinterpret_cast<float **>(src)[idxA][srcIdx];
} else {
(*out_rgba)[4 * idx + 3] = 1.0;
}
}
}
}
} else {
for (int i = 0; i < exr_image.width * exr_image.height; i++) {
(*out_rgba)[4 * i + 0] =
reinterpret_cast<float **>(exr_image.images)[idxR][i];
(*out_rgba)[4 * i + 1] =
reinterpret_cast<float **>(exr_image.images)[idxG][i];
(*out_rgba)[4 * i + 2] =
reinterpret_cast<float **>(exr_image.images)[idxB][i];
if (idxA != -1) {
(*out_rgba)[4 * i + 3] =
reinterpret_cast<float **>(exr_image.images)[idxA][i];
} else {
(*out_rgba)[4 * i + 3] = 1.0;
}
}
}
}
(*width) = exr_image.width;
(*height) = exr_image.height;
FreeEXRHeader(&exr_header);
FreeEXRImage(&exr_image);
return TINYEXR_SUCCESS;
}
int IsEXR(const char *filename) {
EXRVersion exr_version;
int ret = ParseEXRVersionFromFile(&exr_version, filename);
if (ret != TINYEXR_SUCCESS) {
return ret;
}
return TINYEXR_SUCCESS;
}
int ParseEXRHeaderFromMemory(EXRHeader *exr_header, const EXRVersion *version,
const unsigned char *memory, size_t size,
const char **err) {
if (memory == NULL || exr_header == NULL) {
tinyexr::SetErrorMessage(
"Invalid argument. `memory` or `exr_header` argument is null in "
"ParseEXRHeaderFromMemory()",
err);
// Invalid argument
return TINYEXR_ERROR_INVALID_ARGUMENT;
}
if (size < tinyexr::kEXRVersionSize) {
tinyexr::SetErrorMessage("Insufficient header/data size.\n", err);
return TINYEXR_ERROR_INVALID_DATA;
}
const unsigned char *marker = memory + tinyexr::kEXRVersionSize;
size_t marker_size = size - tinyexr::kEXRVersionSize;
tinyexr::HeaderInfo info;
info.clear();
std::string err_str;
int ret = ParseEXRHeader(&info, NULL, version, &err_str, marker, marker_size);
if (ret != TINYEXR_SUCCESS) {
if (err && !err_str.empty()) {
tinyexr::SetErrorMessage(err_str, err);
}
}
ConvertHeader(exr_header, info);
exr_header->multipart = version->multipart ? 1 : 0;
exr_header->non_image = version->non_image ? 1 : 0;
return ret;
}
int LoadEXRFromMemory(float **out_rgba, int *width, int *height,
const unsigned char *memory, size_t size,
const char **err) {
if (out_rgba == NULL || memory == NULL) {
tinyexr::SetErrorMessage("Invalid argument for LoadEXRFromMemory", err);
return TINYEXR_ERROR_INVALID_ARGUMENT;
}
EXRVersion exr_version;
EXRImage exr_image;
EXRHeader exr_header;
InitEXRHeader(&exr_header);
int ret = ParseEXRVersionFromMemory(&exr_version, memory, size);
if (ret != TINYEXR_SUCCESS) {
std::stringstream ss;
ss << "Failed to parse EXR version. code(" << ret << ")";
tinyexr::SetErrorMessage(ss.str(), err);
return ret;
}
ret = ParseEXRHeaderFromMemory(&exr_header, &exr_version, memory, size, err);
if (ret != TINYEXR_SUCCESS) {
return ret;
}
// Read HALF channel as FLOAT.
for (int i = 0; i < exr_header.num_channels; i++) {
if (exr_header.pixel_types[i] == TINYEXR_PIXELTYPE_HALF) {
exr_header.requested_pixel_types[i] = TINYEXR_PIXELTYPE_FLOAT;
}
}
InitEXRImage(&exr_image);
ret = LoadEXRImageFromMemory(&exr_image, &exr_header, memory, size, err);
if (ret != TINYEXR_SUCCESS) {
return ret;
}
// RGBA
int idxR = -1;
int idxG = -1;
int idxB = -1;
int idxA = -1;
for (int c = 0; c < exr_header.num_channels; c++) {
if (strcmp(exr_header.channels[c].name, "R") == 0) {
idxR = c;
} else if (strcmp(exr_header.channels[c].name, "G") == 0) {
idxG = c;
} else if (strcmp(exr_header.channels[c].name, "B") == 0) {
idxB = c;
} else if (strcmp(exr_header.channels[c].name, "A") == 0) {
idxA = c;
}
}
// TODO(syoyo): Refactor removing same code as used in LoadEXR().
if (exr_header.num_channels == 1) {
// Grayscale channel only.
(*out_rgba) = reinterpret_cast<float *>(
malloc(4 * sizeof(float) * static_cast<size_t>(exr_image.width) *
static_cast<size_t>(exr_image.height)));
if (exr_header.tiled) {
for (int it = 0; it < exr_image.num_tiles; it++) {
for (int j = 0; j < exr_header.tile_size_y; j++) {
for (int i = 0; i < exr_header.tile_size_x; i++) {
const int ii =
exr_image.tiles[it].offset_x * exr_header.tile_size_x + i;
const int jj =
exr_image.tiles[it].offset_y * exr_header.tile_size_y + j;
const int idx = ii + jj * exr_image.width;
// out of region check.
if (ii >= exr_image.width) {
continue;
}
if (jj >= exr_image.height) {
continue;
}
const int srcIdx = i + j * exr_header.tile_size_x;
unsigned char **src = exr_image.tiles[it].images;
(*out_rgba)[4 * idx + 0] =
reinterpret_cast<float **>(src)[0][srcIdx];
(*out_rgba)[4 * idx + 1] =
reinterpret_cast<float **>(src)[0][srcIdx];
(*out_rgba)[4 * idx + 2] =
reinterpret_cast<float **>(src)[0][srcIdx];
(*out_rgba)[4 * idx + 3] =
reinterpret_cast<float **>(src)[0][srcIdx];
}
}
}
} else {
for (int i = 0; i < exr_image.width * exr_image.height; i++) {
const float val = reinterpret_cast<float **>(exr_image.images)[0][i];
(*out_rgba)[4 * i + 0] = val;
(*out_rgba)[4 * i + 1] = val;
(*out_rgba)[4 * i + 2] = val;
(*out_rgba)[4 * i + 3] = val;
}
}
} else {
// TODO(syoyo): Support non RGBA image.
if (idxR == -1) {
tinyexr::SetErrorMessage("R channel not found", err);
// @todo { free exr_image }
return TINYEXR_ERROR_INVALID_DATA;
}
if (idxG == -1) {
tinyexr::SetErrorMessage("G channel not found", err);
// @todo { free exr_image }
return TINYEXR_ERROR_INVALID_DATA;
}
if (idxB == -1) {
tinyexr::SetErrorMessage("B channel not found", err);
// @todo { free exr_image }
return TINYEXR_ERROR_INVALID_DATA;
}
(*out_rgba) = reinterpret_cast<float *>(
malloc(4 * sizeof(float) * static_cast<size_t>(exr_image.width) *
static_cast<size_t>(exr_image.height)));
if (exr_header.tiled) {
for (int it = 0; it < exr_image.num_tiles; it++) {
for (int j = 0; j < exr_header.tile_size_y; j++)
for (int i = 0; i < exr_header.tile_size_x; i++) {
const int ii =
exr_image.tiles[it].offset_x * exr_header.tile_size_x + i;
const int jj =
exr_image.tiles[it].offset_y * exr_header.tile_size_y + j;
const int idx = ii + jj * exr_image.width;
// out of region check.
if (ii >= exr_image.width) {
continue;
}
if (jj >= exr_image.height) {
continue;
}
const int srcIdx = i + j * exr_header.tile_size_x;
unsigned char **src = exr_image.tiles[it].images;
(*out_rgba)[4 * idx + 0] =
reinterpret_cast<float **>(src)[idxR][srcIdx];
(*out_rgba)[4 * idx + 1] =
reinterpret_cast<float **>(src)[idxG][srcIdx];
(*out_rgba)[4 * idx + 2] =
reinterpret_cast<float **>(src)[idxB][srcIdx];
if (idxA != -1) {
(*out_rgba)[4 * idx + 3] =
reinterpret_cast<float **>(src)[idxA][srcIdx];
} else {
(*out_rgba)[4 * idx + 3] = 1.0;
}
}
}
} else {
for (int i = 0; i < exr_image.width * exr_image.height; i++) {
(*out_rgba)[4 * i + 0] =
reinterpret_cast<float **>(exr_image.images)[idxR][i];
(*out_rgba)[4 * i + 1] =
reinterpret_cast<float **>(exr_image.images)[idxG][i];
(*out_rgba)[4 * i + 2] =
reinterpret_cast<float **>(exr_image.images)[idxB][i];
if (idxA != -1) {
(*out_rgba)[4 * i + 3] =
reinterpret_cast<float **>(exr_image.images)[idxA][i];
} else {
(*out_rgba)[4 * i + 3] = 1.0;
}
}
}
}
(*width) = exr_image.width;
(*height) = exr_image.height;
FreeEXRHeader(&exr_header);
FreeEXRImage(&exr_image);
return TINYEXR_SUCCESS;
}
int LoadEXRImageFromFile(EXRImage *exr_image, const EXRHeader *exr_header,
const char *filename, const char **err) {
if (exr_image == NULL) {
tinyexr::SetErrorMessage("Invalid argument for LoadEXRImageFromFile", err);
return TINYEXR_ERROR_INVALID_ARGUMENT;
}
FILE *fp = NULL;
#ifdef _WIN32
#if defined(_MSC_VER) || defined(__MINGW32__) // MSVC, MinGW gcc or clang
errno_t errcode =
_wfopen_s(&fp, tinyexr::UTF8ToWchar(filename).c_str(), L"rb");
if (errcode != 0) {
tinyexr::SetErrorMessage("Cannot read file " + std::string(filename), err);
// TODO(syoyo): return wfopen_s erro code
return TINYEXR_ERROR_CANT_OPEN_FILE;
}
#else
// Unknown compiler
fp = fopen(filename, "rb");
#endif
#else
fp = fopen(filename, "rb");
#endif
if (!fp) {
tinyexr::SetErrorMessage("Cannot read file " + std::string(filename), err);
return TINYEXR_ERROR_CANT_OPEN_FILE;
}
size_t filesize;
// Compute size
fseek(fp, 0, SEEK_END);
filesize = static_cast<size_t>(ftell(fp));
fseek(fp, 0, SEEK_SET);
if (filesize < 16) {
tinyexr::SetErrorMessage("File size too short " + std::string(filename),
err);
return TINYEXR_ERROR_INVALID_FILE;
}
std::vector<unsigned char> buf(filesize); // @todo { use mmap }
{
size_t ret;
ret = fread(&buf[0], 1, filesize, fp);
assert(ret == filesize);
fclose(fp);
(void)ret;
}
return LoadEXRImageFromMemory(exr_image, exr_header, &buf.at(0), filesize,
err);
}
int LoadEXRImageFromMemory(EXRImage *exr_image, const EXRHeader *exr_header,
const unsigned char *memory, const size_t size,
const char **err) {
if (exr_image == NULL || memory == NULL ||
(size < tinyexr::kEXRVersionSize)) {
tinyexr::SetErrorMessage("Invalid argument for LoadEXRImageFromMemory",
err);
return TINYEXR_ERROR_INVALID_ARGUMENT;
}
if (exr_header->header_len == 0) {
tinyexr::SetErrorMessage("EXRHeader variable is not initialized.", err);
return TINYEXR_ERROR_INVALID_ARGUMENT;
}
const unsigned char *head = memory;
const unsigned char *marker = reinterpret_cast<const unsigned char *>(
memory + exr_header->header_len +
8); // +8 for magic number + version header.
return tinyexr::DecodeEXRImage(exr_image, exr_header, head, marker, size,
err);
}
namespace tinyexr
{
// out_data must be allocated initially with the block-header size
// of the current image(-part) type
static bool EncodePixelData(/* out */ std::vector<unsigned char>& out_data,
const unsigned char* const* images,
int compression_type,
int /*line_order*/,
int width, // for tiled : tile.width
int /*height*/, // for tiled : header.tile_size_y
int x_stride, // for tiled : header.tile_size_x
int line_no, // for tiled : 0
int num_lines, // for tiled : tile.height
size_t pixel_data_size,
const std::vector<ChannelInfo>& channels,
const std::vector<size_t>& channel_offset_list,
const void* compression_param = 0) // zfp compression param
{
size_t buf_size = static_cast<size_t>(width) *
static_cast<size_t>(num_lines) *
static_cast<size_t>(pixel_data_size);
//int last2bit = (buf_size & 3);
// buf_size must be multiple of four
//if(last2bit) buf_size += 4 - last2bit;
std::vector<unsigned char> buf(buf_size);
size_t start_y = static_cast<size_t>(line_no);
for (size_t c = 0; c < channels.size(); c++) {
if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) {
if (channels[c].requested_pixel_type == TINYEXR_PIXELTYPE_FLOAT) {
for (int y = 0; y < num_lines; y++) {
// Assume increasing Y
float *line_ptr = reinterpret_cast<float *>(&buf.at(
static_cast<size_t>(pixel_data_size * y * width) +
channel_offset_list[c] *
static_cast<size_t>(width)));
for (int x = 0; x < width; x++) {
tinyexr::FP16 h16;
h16.u = reinterpret_cast<const unsigned short * const *>(
images)[c][(y + start_y) * x_stride + x];
tinyexr::FP32 f32 = half_to_float(h16);
tinyexr::swap4(&f32.f);
// line_ptr[x] = f32.f;
tinyexr::cpy4(line_ptr + x, &(f32.f));
}
}
} else if (channels[c].requested_pixel_type == TINYEXR_PIXELTYPE_HALF) {
for (int y = 0; y < num_lines; y++) {
// Assume increasing Y
unsigned short *line_ptr = reinterpret_cast<unsigned short *>(
&buf.at(static_cast<size_t>(pixel_data_size * y *
width) +
channel_offset_list[c] *
static_cast<size_t>(width)));
for (int x = 0; x < width; x++) {
unsigned short val = reinterpret_cast<const unsigned short * const *>(
images)[c][(y + start_y) * x_stride + x];
tinyexr::swap2(&val);
// line_ptr[x] = val;
tinyexr::cpy2(line_ptr + x, &val);
}
}
} else {
assert(0);
}
} else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) {
if (channels[c].requested_pixel_type == TINYEXR_PIXELTYPE_HALF) {
for (int y = 0; y < num_lines; y++) {
// Assume increasing Y
unsigned short *line_ptr = reinterpret_cast<unsigned short *>(
&buf.at(static_cast<size_t>(pixel_data_size * y *
width) +
channel_offset_list[c] *
static_cast<size_t>(width)));
for (int x = 0; x < width; x++) {
tinyexr::FP32 f32;
f32.f = reinterpret_cast<const float * const *>(
images)[c][(y + start_y) * x_stride + x];
tinyexr::FP16 h16;
h16 = float_to_half_full(f32);
tinyexr::swap2(reinterpret_cast<unsigned short *>(&h16.u));
// line_ptr[x] = h16.u;
tinyexr::cpy2(line_ptr + x, &(h16.u));
}
}
} else if (channels[c].requested_pixel_type == TINYEXR_PIXELTYPE_FLOAT) {
for (int y = 0; y < num_lines; y++) {
// Assume increasing Y
float *line_ptr = reinterpret_cast<float *>(&buf.at(
static_cast<size_t>(pixel_data_size * y * width) +
channel_offset_list[c] *
static_cast<size_t>(width)));
for (int x = 0; x < width; x++) {
float val = reinterpret_cast<const float * const *>(
images)[c][(y + start_y) * x_stride + x];
tinyexr::swap4(&val);
// line_ptr[x] = val;
tinyexr::cpy4(line_ptr + x, &val);
}
}
} else {
assert(0);
}
} else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) {
for (int y = 0; y < num_lines; y++) {
// Assume increasing Y
unsigned int *line_ptr = reinterpret_cast<unsigned int *>(&buf.at(
static_cast<size_t>(pixel_data_size * y * width) +
channel_offset_list[c] * static_cast<size_t>(width)));
for (int x = 0; x < width; x++) {
unsigned int val = reinterpret_cast<const unsigned int * const *>(
images)[c][(y + start_y) * x_stride + x];
tinyexr::swap4(&val);
// line_ptr[x] = val;
tinyexr::cpy4(line_ptr + x, &val);
}
}
}
}
if (compression_type == TINYEXR_COMPRESSIONTYPE_NONE) {
// 4 byte: scan line
// 4 byte: data size
// ~ : pixel data(uncompressed)
out_data.insert(out_data.end(), buf.begin(), buf.end());
} else if ((compression_type == TINYEXR_COMPRESSIONTYPE_ZIPS) ||
(compression_type == TINYEXR_COMPRESSIONTYPE_ZIP)) {
#if TINYEXR_USE_MINIZ
std::vector<unsigned char> block(tinyexr::miniz::mz_compressBound(
static_cast<unsigned long>(buf.size())));
#else
std::vector<unsigned char> block(
compressBound(static_cast<uLong>(buf.size())));
#endif
tinyexr::tinyexr_uint64 outSize = block.size();
tinyexr::CompressZip(&block.at(0), outSize,
reinterpret_cast<const unsigned char *>(&buf.at(0)),
static_cast<unsigned long>(buf.size()));
// 4 byte: scan line
// 4 byte: data size
// ~ : pixel data(compressed)
unsigned int data_len = static_cast<unsigned int>(outSize); // truncate
out_data.insert(out_data.end(), block.begin(), block.begin() + data_len);
} else if (compression_type == TINYEXR_COMPRESSIONTYPE_RLE) {
// (buf.size() * 3) / 2 would be enough.
std::vector<unsigned char> block((buf.size() * 3) / 2);
tinyexr::tinyexr_uint64 outSize = block.size();
tinyexr::CompressRle(&block.at(0), outSize,
reinterpret_cast<const unsigned char *>(&buf.at(0)),
static_cast<unsigned long>(buf.size()));
// 4 byte: scan line
// 4 byte: data size
// ~ : pixel data(compressed)
unsigned int data_len = static_cast<unsigned int>(outSize); // truncate
out_data.insert(out_data.end(), block.begin(), block.begin() + data_len);
} else if (compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) {
#if TINYEXR_USE_PIZ
unsigned int bufLen =
8192 + static_cast<unsigned int>(
2 * static_cast<unsigned int>(
buf.size())); // @fixme { compute good bound. }
std::vector<unsigned char> block(bufLen);
unsigned int outSize = static_cast<unsigned int>(block.size());
CompressPiz(&block.at(0), &outSize,
reinterpret_cast<const unsigned char *>(&buf.at(0)),
buf.size(), channels, width, num_lines);
// 4 byte: scan line
// 4 byte: data size
// ~ : pixel data(compressed)
unsigned int data_len = outSize;
out_data.insert(out_data.end(), block.begin(), block.begin() + data_len);
#else
assert(0);
#endif
} else if (compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) {
#if TINYEXR_USE_ZFP
const ZFPCompressionParam* zfp_compression_param = reinterpret_cast<const ZFPCompressionParam*>(compression_param);
std::vector<unsigned char> block;
unsigned int outSize;
tinyexr::CompressZfp(
&block, &outSize, reinterpret_cast<const float *>(&buf.at(0)),
width, num_lines, static_cast<int>(channels.size()), *zfp_compression_param);
// 4 byte: scan line
// 4 byte: data size
// ~ : pixel data(compressed)
unsigned int data_len = outSize;
out_data.insert(out_data.end(), block.begin(), block.begin() + data_len);
#else
(void)compression_param;
assert(0);
#endif
} else {
assert(0);
return false;
}
return true;
}
static int EncodeTiledLevel(const EXRImage* level_image, const EXRHeader* exr_header,
const std::vector<tinyexr::ChannelInfo>& channels,
std::vector<std::vector<unsigned char> >& data_list,
size_t start_index, // for data_list
int num_x_tiles, int num_y_tiles,
const std::vector<size_t>& channel_offset_list,
int pixel_data_size,
const void* compression_param, // must be set if zfp compression is enabled
std::string* err) {
int num_tiles = num_x_tiles * num_y_tiles;
assert(num_tiles == level_image->num_tiles);
if ((exr_header->tile_size_x > level_image->width || exr_header->tile_size_y > level_image->height) &&
level_image->level_x == 0 && level_image->level_y == 0) {
if (err) {
(*err) += "Failed to encode tile data.\n";
}
return TINYEXR_ERROR_INVALID_DATA;
}
#if TINYEXR_HAS_CXX11 && (TINYEXR_USE_THREAD > 0)
std::atomic<bool> invalid_data(false);
#else
bool invalid_data(false);
#endif
#if TINYEXR_HAS_CXX11 && (TINYEXR_USE_THREAD > 0)
std::vector<std::thread> workers;
std::atomic<int> tile_count(0);
int num_threads = std::max(1, int(std::thread::hardware_concurrency()));
if (num_threads > int(num_tiles)) {
num_threads = int(num_tiles);
}
for (int t = 0; t < num_threads; t++) {
workers.emplace_back(std::thread([&]() {
int i = 0;
while ((i = tile_count++) < num_tiles) {
#else
// Use signed int since some OpenMP compiler doesn't allow unsigned type for
// `parallel for`
#if TINYEXR_USE_OPENMP
#pragma omp parallel for
#endif
for (int i = 0; i < num_tiles; i++) {
#endif
size_t tile_idx = static_cast<size_t>(i);
size_t data_idx = tile_idx + start_index;
int x_tile = i % num_x_tiles;
int y_tile = i / num_x_tiles;
EXRTile& tile = level_image->tiles[tile_idx];
const unsigned char* const* images =
static_cast<const unsigned char* const*>(tile.images);
data_list[data_idx].resize(5*sizeof(int));
size_t data_header_size = data_list[data_idx].size();
bool ret = EncodePixelData(data_list[data_idx],
images,
exr_header->compression_type,
0, // increasing y
tile.width,
exr_header->tile_size_y,
exr_header->tile_size_x,
0,
tile.height,
pixel_data_size,
channels,
channel_offset_list,
compression_param);
if (!ret) {
invalid_data = true;
continue;
}
assert(data_list[data_idx].size() > data_header_size);
int data_len = static_cast<int>(data_list[data_idx].size() - data_header_size);
//tileX, tileY, levelX, levelY // pixel_data_size(int)
memcpy(&data_list[data_idx][0], &x_tile, sizeof(int));
memcpy(&data_list[data_idx][4], &y_tile, sizeof(int));
memcpy(&data_list[data_idx][8], &level_image->level_x, sizeof(int));
memcpy(&data_list[data_idx][12], &level_image->level_y, sizeof(int));
memcpy(&data_list[data_idx][16], &data_len, sizeof(int));
swap4(reinterpret_cast<int*>(&data_list[data_idx][0]));
swap4(reinterpret_cast<int*>(&data_list[data_idx][4]));
swap4(reinterpret_cast<int*>(&data_list[data_idx][8]));
swap4(reinterpret_cast<int*>(&data_list[data_idx][12]));
swap4(reinterpret_cast<int*>(&data_list[data_idx][16]));
#if TINYEXR_HAS_CXX11 && (TINYEXR_USE_THREAD > 0)
}
}));
}
for (auto &t : workers) {
t.join();
}
#else
} // omp parallel
#endif
if (invalid_data) {
if (err) {
(*err) += "Failed to encode tile data.\n";
}
return TINYEXR_ERROR_INVALID_DATA;
}
return TINYEXR_SUCCESS;
}
static int NumScanlines(int compression_type) {
int num_scanlines = 1;
if (compression_type == TINYEXR_COMPRESSIONTYPE_ZIP) {
num_scanlines = 16;
} else if (compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) {
num_scanlines = 32;
} else if (compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) {
num_scanlines = 16;
}
return num_scanlines;
}
static int EncodeChunk(const EXRImage* exr_image, const EXRHeader* exr_header,
const std::vector<ChannelInfo>& channels,
int num_blocks,
tinyexr_uint64 chunk_offset, // starting offset of current chunk
bool is_multipart,
OffsetData& offset_data, // output block offsets, must be initialized
std::vector<std::vector<unsigned char> >& data_list, // output
tinyexr_uint64& total_size, // output: ending offset of current chunk
std::string* err) {
int num_scanlines = NumScanlines(exr_header->compression_type);
data_list.resize(num_blocks);
std::vector<size_t> channel_offset_list(
static_cast<size_t>(exr_header->num_channels));
int pixel_data_size = 0;
{
size_t channel_offset = 0;
for (size_t c = 0; c < static_cast<size_t>(exr_header->num_channels); c++) {
channel_offset_list[c] = channel_offset;
if (channels[c].requested_pixel_type == TINYEXR_PIXELTYPE_HALF) {
pixel_data_size += sizeof(unsigned short);
channel_offset += sizeof(unsigned short);
} else if (channels[c].requested_pixel_type ==
TINYEXR_PIXELTYPE_FLOAT) {
pixel_data_size += sizeof(float);
channel_offset += sizeof(float);
} else if (channels[c].requested_pixel_type == TINYEXR_PIXELTYPE_UINT) {
pixel_data_size += sizeof(unsigned int);
channel_offset += sizeof(unsigned int);
} else {
assert(0);
}
}
}
const void* compression_param = 0;
#if TINYEXR_USE_ZFP
tinyexr::ZFPCompressionParam zfp_compression_param;
// Use ZFP compression parameter from custom attributes(if such a parameter
// exists)
{
std::string e;
bool ret = tinyexr::FindZFPCompressionParam(
&zfp_compression_param, exr_header->custom_attributes,
exr_header->num_custom_attributes, &e);
if (!ret) {
// Use predefined compression parameter.
zfp_compression_param.type = 0;
zfp_compression_param.rate = 2;
}
compression_param = &zfp_compression_param;
}
#endif
tinyexr_uint64 offset = chunk_offset;
tinyexr_uint64 doffset = is_multipart ? 4u : 0u;
if (exr_image->tiles) {
const EXRImage* level_image = exr_image;
size_t block_idx = 0;
tinyexr::tinyexr_uint64 block_data_size = 0;
int num_levels = (exr_header->tile_level_mode != TINYEXR_TILE_RIPMAP_LEVELS) ?
offset_data.num_x_levels : (offset_data.num_x_levels * offset_data.num_y_levels);
for (int level_index = 0; level_index < num_levels; ++level_index) {
if (!level_image) {
if (err) {
(*err) += "Invalid number of tiled levels for EncodeChunk\n";
}
return TINYEXR_ERROR_INVALID_DATA;
}
int level_index_from_image = LevelIndex(level_image->level_x, level_image->level_y,
exr_header->tile_level_mode, offset_data.num_x_levels);
if (level_index_from_image != level_index) {
if (err) {
(*err) += "Incorrect level ordering in tiled image\n";
}
return TINYEXR_ERROR_INVALID_DATA;
}
int num_y_tiles = (int)offset_data.offsets[level_index].size();
assert(num_y_tiles);
int num_x_tiles = (int)offset_data.offsets[level_index][0].size();
assert(num_x_tiles);
std::string e;
int ret = EncodeTiledLevel(level_image,
exr_header,
channels,
data_list,
block_idx,
num_x_tiles,
num_y_tiles,
channel_offset_list,
pixel_data_size,
compression_param,
&e);
if (ret != TINYEXR_SUCCESS) {
if (!e.empty() && err) {
(*err) += e;
}
return ret;
}
for (size_t j = 0; j < static_cast<size_t>(num_y_tiles); ++j)
for (size_t i = 0; i < static_cast<size_t>(num_x_tiles); ++i) {
offset_data.offsets[level_index][j][i] = offset;
swap8(reinterpret_cast<tinyexr_uint64*>(&offset_data.offsets[level_index][j][i]));
offset += data_list[block_idx].size() + doffset;
block_data_size += data_list[block_idx].size();
++block_idx;
}
level_image = level_image->next_level;
}
assert(static_cast<int>(block_idx) == num_blocks);
total_size = offset;
} else { // scanlines
std::vector<tinyexr::tinyexr_uint64>& offsets = offset_data.offsets[0][0];
#if TINYEXR_HAS_CXX11 && (TINYEXR_USE_THREAD > 0)
std::atomic<bool> invalid_data(false);
std::vector<std::thread> workers;
std::atomic<int> block_count(0);
int num_threads = std::min(std::max(1, int(std::thread::hardware_concurrency())), num_blocks);
for (int t = 0; t < num_threads; t++) {
workers.emplace_back(std::thread([&]() {
int i = 0;
while ((i = block_count++) < num_blocks) {
#else
bool invalid_data(false);
#if TINYEXR_USE_OPENMP
#pragma omp parallel for
#endif
for (int i = 0; i < num_blocks; i++) {
#endif
int start_y = num_scanlines * i;
int end_Y = (std::min)(num_scanlines * (i + 1), exr_image->height);
int num_lines = end_Y - start_y;
const unsigned char* const* images =
static_cast<const unsigned char* const*>(exr_image->images);
data_list[i].resize(2*sizeof(int));
size_t data_header_size = data_list[i].size();
bool ret = EncodePixelData(data_list[i],
images,
exr_header->compression_type,
0, // increasing y
exr_image->width,
exr_image->height,
exr_image->width,
start_y,
num_lines,
pixel_data_size,
channels,
channel_offset_list,
compression_param);
if (!ret) {
invalid_data = true;
continue; // "break" cannot be used with OpenMP
}
assert(data_list[i].size() > data_header_size);
int data_len = static_cast<int>(data_list[i].size() - data_header_size);
memcpy(&data_list[i][0], &start_y, sizeof(int));
memcpy(&data_list[i][4], &data_len, sizeof(int));
swap4(reinterpret_cast<int*>(&data_list[i][0]));
swap4(reinterpret_cast<int*>(&data_list[i][4]));
#if TINYEXR_HAS_CXX11 && (TINYEXR_USE_THREAD > 0)
}
}));
}
for (auto &t : workers) {
t.join();
}
#else
} // omp parallel
#endif
if (invalid_data) {
if (err) {
(*err) += "Failed to encode scanline data.\n";
}
return TINYEXR_ERROR_INVALID_DATA;
}
for (size_t i = 0; i < static_cast<size_t>(num_blocks); i++) {
offsets[i] = offset;
tinyexr::swap8(reinterpret_cast<tinyexr::tinyexr_uint64 *>(&offsets[i]));
offset += data_list[i].size() + doffset;
}
total_size = static_cast<size_t>(offset);
}
return TINYEXR_SUCCESS;
}
// can save a single or multi-part image (no deep* formats)
static size_t SaveEXRNPartImageToMemory(const EXRImage* exr_images,
const EXRHeader** exr_headers,
unsigned int num_parts,
unsigned char** memory_out, const char** err) {
if (exr_images == NULL || exr_headers == NULL || num_parts == 0 ||
memory_out == NULL) {
SetErrorMessage("Invalid argument for SaveEXRNPartImageToMemory",
err);
return 0;
}
{
for (unsigned int i = 0; i < num_parts; ++i) {
if (exr_headers[i]->compression_type < 0) {
SetErrorMessage("Invalid argument for SaveEXRNPartImageToMemory",
err);
return 0;
}
#if !TINYEXR_USE_PIZ
if (exr_headers[i]->compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) {
SetErrorMessage("PIZ compression is not supported in this build",
err);
return 0;
}
#endif
#if !TINYEXR_USE_ZFP
if (exr_headers[i]->compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) {
SetErrorMessage("ZFP compression is not supported in this build",
err);
return 0;
}
#else
for (int c = 0; c < exr_header->num_channels; ++c) {
if (exr_headers[i]->requested_pixel_types[c] != TINYEXR_PIXELTYPE_FLOAT) {
SetErrorMessage("Pixel type must be FLOAT for ZFP compression",
err);
return 0;
}
}
#endif
}
}
std::vector<unsigned char> memory;
// Header
{
const char header[] = { 0x76, 0x2f, 0x31, 0x01 };
memory.insert(memory.end(), header, header + 4);
}
// Version
// using value from the first header
int long_name = exr_headers[0]->long_name;
{
char marker[] = { 2, 0, 0, 0 };
/* @todo
if (exr_header->non_image) {
marker[1] |= 0x8;
}
*/
// tiled
if (num_parts == 1 && exr_images[0].tiles) {
marker[1] |= 0x2;
}
// long_name
if (long_name) {
marker[1] |= 0x4;
}
// multipart
if (num_parts > 1) {
marker[1] |= 0x10;
}
memory.insert(memory.end(), marker, marker + 4);
}
int total_chunk_count = 0;
std::vector<int> chunk_count(num_parts);
std::vector<OffsetData> offset_data(num_parts);
for (unsigned int i = 0; i < num_parts; ++i) {
if (!exr_images[i].tiles) {
int num_scanlines = NumScanlines(exr_headers[i]->compression_type);
chunk_count[i] =
(exr_images[i].height + num_scanlines - 1) / num_scanlines;
InitSingleResolutionOffsets(offset_data[i], chunk_count[i]);
total_chunk_count += chunk_count[i];
} else {
{
std::vector<int> num_x_tiles, num_y_tiles;
PrecalculateTileInfo(num_x_tiles, num_y_tiles, exr_headers[i]);
chunk_count[i] =
InitTileOffsets(offset_data[i], exr_headers[i], num_x_tiles, num_y_tiles);
total_chunk_count += chunk_count[i];
}
}
}
// Write attributes to memory buffer.
std::vector< std::vector<tinyexr::ChannelInfo> > channels(num_parts);
{
std::set<std::string> partnames;
for (unsigned int i = 0; i < num_parts; ++i) {
//channels
{
std::vector<unsigned char> data;
for (int c = 0; c < exr_headers[i]->num_channels; c++) {
tinyexr::ChannelInfo info;
info.p_linear = 0;
info.pixel_type = exr_headers[i]->pixel_types[c];
info.requested_pixel_type = exr_headers[i]->requested_pixel_types[c];
info.x_sampling = 1;
info.y_sampling = 1;
info.name = std::string(exr_headers[i]->channels[c].name);
channels[i].push_back(info);
}
tinyexr::WriteChannelInfo(data, channels[i]);
tinyexr::WriteAttributeToMemory(&memory, "channels", "chlist", &data.at(0),
static_cast<int>(data.size()));
}
{
int comp = exr_headers[i]->compression_type;
swap4(&comp);
WriteAttributeToMemory(
&memory, "compression", "compression",
reinterpret_cast<const unsigned char*>(&comp), 1);
}
{
int data[4] = { 0, 0, exr_images[i].width - 1, exr_images[i].height - 1 };
swap4(&data[0]);
swap4(&data[1]);
swap4(&data[2]);
swap4(&data[3]);
WriteAttributeToMemory(
&memory, "dataWindow", "box2i",
reinterpret_cast<const unsigned char*>(data), sizeof(int) * 4);
int data0[4] = { 0, 0, exr_images[0].width - 1, exr_images[0].height - 1 };
swap4(&data0[0]);
swap4(&data0[1]);
swap4(&data0[2]);
swap4(&data0[3]);
// Note: must be the same across parts (currently, using value from the first header)
WriteAttributeToMemory(
&memory, "displayWindow", "box2i",
reinterpret_cast<const unsigned char*>(data0), sizeof(int) * 4);
}
{
unsigned char line_order = 0; // @fixme { read line_order from EXRHeader }
WriteAttributeToMemory(&memory, "lineOrder", "lineOrder",
&line_order, 1);
}
{
// Note: must be the same across parts
float aspectRatio = 1.0f;
swap4(&aspectRatio);
WriteAttributeToMemory(
&memory, "pixelAspectRatio", "float",
reinterpret_cast<const unsigned char*>(&aspectRatio), sizeof(float));
}
{
float center[2] = { 0.0f, 0.0f };
swap4(¢er[0]);
swap4(¢er[1]);
WriteAttributeToMemory(
&memory, "screenWindowCenter", "v2f",
reinterpret_cast<const unsigned char*>(center), 2 * sizeof(float));
}
{
float w = 1.0f;
swap4(&w);
WriteAttributeToMemory(&memory, "screenWindowWidth", "float",
reinterpret_cast<const unsigned char*>(&w),
sizeof(float));
}
if (exr_images[i].tiles) {
unsigned char tile_mode = static_cast<unsigned char>(exr_headers[i]->tile_level_mode & 0x3);
if (exr_headers[i]->tile_rounding_mode) tile_mode |= (1u << 4u);
//unsigned char data[9] = { 0, 0, 0, 0, 0, 0, 0, 0, 0 };
unsigned int datai[3] = { 0, 0, 0 };
unsigned char* data = reinterpret_cast<unsigned char*>(&datai[0]);
datai[0] = static_cast<unsigned int>(exr_headers[i]->tile_size_x);
datai[1] = static_cast<unsigned int>(exr_headers[i]->tile_size_y);
data[8] = tile_mode;
swap4(reinterpret_cast<unsigned int*>(&data[0]));
swap4(reinterpret_cast<unsigned int*>(&data[4]));
WriteAttributeToMemory(
&memory, "tiles", "tiledesc",
reinterpret_cast<const unsigned char*>(data), 9);
}
// must be present for multi-part files - according to spec.
if (num_parts > 1) {
// name
{
size_t len = 0;
if ((len = strlen(exr_headers[i]->name)) > 0) {
partnames.insert(std::string(exr_headers[i]->name));
if (partnames.size() != i + 1) {
SetErrorMessage("'name' attributes must be unique for a multi-part file", err);
return 0;
}
WriteAttributeToMemory(
&memory, "name", "string",
reinterpret_cast<const unsigned char*>(exr_headers[i]->name),
static_cast<int>(len));
} else {
SetErrorMessage("Invalid 'name' attribute for a multi-part file", err);
return 0;
}
}
// type
{
const char* type = "scanlineimage";
if (exr_images[i].tiles) type = "tiledimage";
WriteAttributeToMemory(
&memory, "type", "string",
reinterpret_cast<const unsigned char*>(type),
static_cast<int>(strlen(type)));
}
// chunkCount
{
WriteAttributeToMemory(
&memory, "chunkCount", "int",
reinterpret_cast<const unsigned char*>(&chunk_count[i]),
4);
}
}
// Custom attributes
if (exr_headers[i]->num_custom_attributes > 0) {
for (int j = 0; j < exr_headers[i]->num_custom_attributes; j++) {
tinyexr::WriteAttributeToMemory(
&memory, exr_headers[i]->custom_attributes[j].name,
exr_headers[i]->custom_attributes[j].type,
reinterpret_cast<const unsigned char*>(
exr_headers[i]->custom_attributes[j].value),
exr_headers[i]->custom_attributes[j].size);
}
}
{ // end of header
memory.push_back(0);
}
}
}
if (num_parts > 1) {
// end of header list
memory.push_back(0);
}
tinyexr_uint64 chunk_offset = memory.size() + size_t(total_chunk_count) * sizeof(tinyexr_uint64);
tinyexr_uint64 total_size = 0;
std::vector< std::vector< std::vector<unsigned char> > > data_lists(num_parts);
for (unsigned int i = 0; i < num_parts; ++i) {
std::string e;
int ret = EncodeChunk(&exr_images[i], exr_headers[i],
channels[i],
chunk_count[i],
// starting offset of current chunk after part-number
chunk_offset,
num_parts > 1,
offset_data[i], // output: block offsets, must be initialized
data_lists[i], // output
total_size, // output
&e);
if (ret != TINYEXR_SUCCESS) {
if (!e.empty()) {
tinyexr::SetErrorMessage(e, err);
}
return 0;
}
chunk_offset = total_size;
}
// Allocating required memory
if (total_size == 0) { // something went wrong
tinyexr::SetErrorMessage("Output memory size is zero", err);
return 0;
}
(*memory_out) = static_cast<unsigned char*>(malloc(total_size));
// Writing header
memcpy((*memory_out), &memory[0], memory.size());
unsigned char* memory_ptr = *memory_out + memory.size();
size_t sum = memory.size();
// Writing offset data for chunks
for (unsigned int i = 0; i < num_parts; ++i) {
if (exr_images[i].tiles) {
const EXRImage* level_image = &exr_images[i];
int num_levels = (exr_headers[i]->tile_level_mode != TINYEXR_TILE_RIPMAP_LEVELS) ?
offset_data[i].num_x_levels : (offset_data[i].num_x_levels * offset_data[i].num_y_levels);
for (int level_index = 0; level_index < num_levels; ++level_index) {
for (size_t j = 0; j < offset_data[i].offsets[level_index].size(); ++j) {
size_t num_bytes = sizeof(tinyexr_uint64) * offset_data[i].offsets[level_index][j].size();
sum += num_bytes;
assert(sum <= total_size);
memcpy(memory_ptr,
reinterpret_cast<unsigned char*>(&offset_data[i].offsets[level_index][j][0]),
num_bytes);
memory_ptr += num_bytes;
}
level_image = level_image->next_level;
}
} else {
size_t num_bytes = sizeof(tinyexr::tinyexr_uint64) * static_cast<size_t>(chunk_count[i]);
sum += num_bytes;
assert(sum <= total_size);
std::vector<tinyexr::tinyexr_uint64>& offsets = offset_data[i].offsets[0][0];
memcpy(memory_ptr, reinterpret_cast<unsigned char*>(&offsets[0]), num_bytes);
memory_ptr += num_bytes;
}
}
// Writing chunk data
for (unsigned int i = 0; i < num_parts; ++i) {
for (size_t j = 0; j < static_cast<size_t>(chunk_count[i]); ++j) {
if (num_parts > 1) {
sum += 4;
assert(sum <= total_size);
unsigned int part_number = i;
swap4(&part_number);
memcpy(memory_ptr, &part_number, 4);
memory_ptr += 4;
}
sum += data_lists[i][j].size();
assert(sum <= total_size);
memcpy(memory_ptr, &data_lists[i][j][0], data_lists[i][j].size());
memory_ptr += data_lists[i][j].size();
}
}
assert(sum == total_size);
return total_size; // OK
}
} // tinyexr
size_t SaveEXRImageToMemory(const EXRImage* exr_image,
const EXRHeader* exr_header,
unsigned char** memory_out, const char** err) {
return tinyexr::SaveEXRNPartImageToMemory(exr_image, &exr_header, 1, memory_out, err);
}
int SaveEXRImageToFile(const EXRImage *exr_image, const EXRHeader *exr_header,
const char *filename, const char **err) {
if (exr_image == NULL || filename == NULL ||
exr_header->compression_type < 0) {
tinyexr::SetErrorMessage("Invalid argument for SaveEXRImageToFile", err);
return TINYEXR_ERROR_INVALID_ARGUMENT;
}
#if !TINYEXR_USE_PIZ
if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) {
tinyexr::SetErrorMessage("PIZ compression is not supported in this build",
err);
return TINYEXR_ERROR_UNSUPPORTED_FEATURE;
}
#endif
#if !TINYEXR_USE_ZFP
if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) {
tinyexr::SetErrorMessage("ZFP compression is not supported in this build",
err);
return TINYEXR_ERROR_UNSUPPORTED_FEATURE;
}
#endif
FILE *fp = NULL;
#ifdef _WIN32
#if defined(_MSC_VER) || defined(__MINGW32__) // MSVC, MinGW gcc or clang
errno_t errcode =
_wfopen_s(&fp, tinyexr::UTF8ToWchar(filename).c_str(), L"wb");
if (errcode != 0) {
tinyexr::SetErrorMessage("Cannot write a file: " + std::string(filename),
err);
return TINYEXR_ERROR_CANT_WRITE_FILE;
}
#else
// Unknown compiler
fp = fopen(filename, "wb");
#endif
#else
fp = fopen(filename, "wb");
#endif
if (!fp) {
tinyexr::SetErrorMessage("Cannot write a file: " + std::string(filename),
err);
return TINYEXR_ERROR_CANT_WRITE_FILE;
}
unsigned char *mem = NULL;
size_t mem_size = SaveEXRImageToMemory(exr_image, exr_header, &mem, err);
if (mem_size == 0) {
return TINYEXR_ERROR_SERIALZATION_FAILED;
}
size_t written_size = 0;
if ((mem_size > 0) && mem) {
written_size = fwrite(mem, 1, mem_size, fp);
}
free(mem);
fclose(fp);
if (written_size != mem_size) {
tinyexr::SetErrorMessage("Cannot write a file", err);
return TINYEXR_ERROR_CANT_WRITE_FILE;
}
return TINYEXR_SUCCESS;
}
size_t SaveEXRMultipartImageToMemory(const EXRImage* exr_images,
const EXRHeader** exr_headers,
unsigned int num_parts,
unsigned char** memory_out, const char** err) {
if (exr_images == NULL || exr_headers == NULL || num_parts < 2 ||
memory_out == NULL) {
tinyexr::SetErrorMessage("Invalid argument for SaveEXRNPartImageToMemory",
err);
return 0;
}
return tinyexr::SaveEXRNPartImageToMemory(exr_images, exr_headers, num_parts, memory_out, err);
}
int SaveEXRMultipartImageToFile(const EXRImage* exr_images,
const EXRHeader** exr_headers,
unsigned int num_parts,
const char* filename,
const char** err) {
if (exr_images == NULL || exr_headers == NULL || num_parts < 2) {
tinyexr::SetErrorMessage("Invalid argument for SaveEXRMultipartImageToFile",
err);
return TINYEXR_ERROR_INVALID_ARGUMENT;
}
FILE *fp = NULL;
#ifdef _WIN32
#if defined(_MSC_VER) || defined(__MINGW32__) // MSVC, MinGW gcc or clang
errno_t errcode =
_wfopen_s(&fp, tinyexr::UTF8ToWchar(filename).c_str(), L"wb");
if (errcode != 0) {
tinyexr::SetErrorMessage("Cannot write a file: " + std::string(filename),
err);
return TINYEXR_ERROR_CANT_WRITE_FILE;
}
#else
// Unknown compiler
fp = fopen(filename, "wb");
#endif
#else
fp = fopen(filename, "wb");
#endif
if (!fp) {
tinyexr::SetErrorMessage("Cannot write a file: " + std::string(filename),
err);
return TINYEXR_ERROR_CANT_WRITE_FILE;
}
unsigned char *mem = NULL;
size_t mem_size = SaveEXRMultipartImageToMemory(exr_images, exr_headers, num_parts, &mem, err);
if (mem_size == 0) {
return TINYEXR_ERROR_SERIALZATION_FAILED;
}
size_t written_size = 0;
if ((mem_size > 0) && mem) {
written_size = fwrite(mem, 1, mem_size, fp);
}
free(mem);
fclose(fp);
if (written_size != mem_size) {
tinyexr::SetErrorMessage("Cannot write a file", err);
return TINYEXR_ERROR_CANT_WRITE_FILE;
}
return TINYEXR_SUCCESS;
}
int LoadDeepEXR(DeepImage *deep_image, const char *filename, const char **err) {
if (deep_image == NULL) {
tinyexr::SetErrorMessage("Invalid argument for LoadDeepEXR", err);
return TINYEXR_ERROR_INVALID_ARGUMENT;
}
#ifdef _WIN32
FILE *fp = NULL;
#if defined(_MSC_VER) || defined(__MINGW32__) // MSVC, MinGW gcc or clang
errno_t errcode =
_wfopen_s(&fp, tinyexr::UTF8ToWchar(filename).c_str(), L"rb");
if (errcode != 0) {
tinyexr::SetErrorMessage("Cannot read a file " + std::string(filename),
err);
return TINYEXR_ERROR_CANT_OPEN_FILE;
}
#else
// Unknown compiler
fp = fopen(filename, "rb");
#endif
if (!fp) {
tinyexr::SetErrorMessage("Cannot read a file " + std::string(filename),
err);
return TINYEXR_ERROR_CANT_OPEN_FILE;
}
#else
FILE *fp = fopen(filename, "rb");
if (!fp) {
tinyexr::SetErrorMessage("Cannot read a file " + std::string(filename),
err);
return TINYEXR_ERROR_CANT_OPEN_FILE;
}
#endif
size_t filesize;
// Compute size
fseek(fp, 0, SEEK_END);
filesize = static_cast<size_t>(ftell(fp));
fseek(fp, 0, SEEK_SET);
if (filesize == 0) {
fclose(fp);
tinyexr::SetErrorMessage("File size is zero : " + std::string(filename),
err);
return TINYEXR_ERROR_INVALID_FILE;
}
std::vector<char> buf(filesize); // @todo { use mmap }
{
size_t ret;
ret = fread(&buf[0], 1, filesize, fp);
assert(ret == filesize);
(void)ret;
}
fclose(fp);
const char *head = &buf[0];
const char *marker = &buf[0];
// Header check.
{
const char header[] = {0x76, 0x2f, 0x31, 0x01};
if (memcmp(marker, header, 4) != 0) {
tinyexr::SetErrorMessage("Invalid magic number", err);
return TINYEXR_ERROR_INVALID_MAGIC_NUMBER;
}
marker += 4;
}
// Version, scanline.
{
// ver 2.0, scanline, deep bit on(0x800)
// must be [2, 0, 0, 0]
if (marker[0] != 2 || marker[1] != 8 || marker[2] != 0 || marker[3] != 0) {
tinyexr::SetErrorMessage("Unsupported version or scanline", err);
return TINYEXR_ERROR_UNSUPPORTED_FORMAT;
}
marker += 4;
}
int dx = -1;
int dy = -1;
int dw = -1;
int dh = -1;
int num_scanline_blocks = 1; // 16 for ZIP compression.
int compression_type = -1;
int num_channels = -1;
std::vector<tinyexr::ChannelInfo> channels;
// Read attributes
size_t size = filesize - tinyexr::kEXRVersionSize;
for (;;) {
if (0 == size) {
return TINYEXR_ERROR_INVALID_DATA;
} else if (marker[0] == '\0') {
marker++;
size--;
break;
}
std::string attr_name;
std::string attr_type;
std::vector<unsigned char> data;
size_t marker_size;
if (!tinyexr::ReadAttribute(&attr_name, &attr_type, &data, &marker_size,
marker, size)) {
std::stringstream ss;
ss << "Failed to parse attribute\n";
tinyexr::SetErrorMessage(ss.str(), err);
return TINYEXR_ERROR_INVALID_DATA;
}
marker += marker_size;
size -= marker_size;
if (attr_name.compare("compression") == 0) {
compression_type = data[0];
if (compression_type > TINYEXR_COMPRESSIONTYPE_PIZ) {
std::stringstream ss;
ss << "Unsupported compression type : " << compression_type;
tinyexr::SetErrorMessage(ss.str(), err);
return TINYEXR_ERROR_UNSUPPORTED_FORMAT;
}
if (compression_type == TINYEXR_COMPRESSIONTYPE_ZIP) {
num_scanline_blocks = 16;
}
} else if (attr_name.compare("channels") == 0) {
// name: zero-terminated string, from 1 to 255 bytes long
// pixel type: int, possible values are: UINT = 0 HALF = 1 FLOAT = 2
// pLinear: unsigned char, possible values are 0 and 1
// reserved: three chars, should be zero
// xSampling: int
// ySampling: int
if (!tinyexr::ReadChannelInfo(channels, data)) {
tinyexr::SetErrorMessage("Failed to parse channel info", err);
return TINYEXR_ERROR_INVALID_DATA;
}
num_channels = static_cast<int>(channels.size());
if (num_channels < 1) {
tinyexr::SetErrorMessage("Invalid channels format", err);
return TINYEXR_ERROR_INVALID_DATA;
}
} else if (attr_name.compare("dataWindow") == 0) {
memcpy(&dx, &data.at(0), sizeof(int));
memcpy(&dy, &data.at(4), sizeof(int));
memcpy(&dw, &data.at(8), sizeof(int));
memcpy(&dh, &data.at(12), sizeof(int));
tinyexr::swap4(&dx);
tinyexr::swap4(&dy);
tinyexr::swap4(&dw);
tinyexr::swap4(&dh);
} else if (attr_name.compare("displayWindow") == 0) {
int x;
int y;
int w;
int h;
memcpy(&x, &data.at(0), sizeof(int));
memcpy(&y, &data.at(4), sizeof(int));
memcpy(&w, &data.at(8), sizeof(int));
memcpy(&h, &data.at(12), sizeof(int));
tinyexr::swap4(&x);
tinyexr::swap4(&y);
tinyexr::swap4(&w);
tinyexr::swap4(&h);
}
}
assert(dx >= 0);
assert(dy >= 0);
assert(dw >= 0);
assert(dh >= 0);
assert(num_channels >= 1);
int data_width = dw - dx + 1;
int data_height = dh - dy + 1;
std::vector<float> image(
static_cast<size_t>(data_width * data_height * 4)); // 4 = RGBA
// Read offset tables.
int num_blocks = data_height / num_scanline_blocks;
if (num_blocks * num_scanline_blocks < data_height) {
num_blocks++;
}
std::vector<tinyexr::tinyexr_int64> offsets(static_cast<size_t>(num_blocks));
for (size_t y = 0; y < static_cast<size_t>(num_blocks); y++) {
tinyexr::tinyexr_int64 offset;
memcpy(&offset, marker, sizeof(tinyexr::tinyexr_int64));
tinyexr::swap8(reinterpret_cast<tinyexr::tinyexr_uint64 *>(&offset));
marker += sizeof(tinyexr::tinyexr_int64); // = 8
offsets[y] = offset;
}
#if TINYEXR_USE_PIZ
if ((compression_type == TINYEXR_COMPRESSIONTYPE_NONE) ||
(compression_type == TINYEXR_COMPRESSIONTYPE_RLE) ||
(compression_type == TINYEXR_COMPRESSIONTYPE_ZIPS) ||
(compression_type == TINYEXR_COMPRESSIONTYPE_ZIP) ||
(compression_type == TINYEXR_COMPRESSIONTYPE_PIZ)) {
#else
if ((compression_type == TINYEXR_COMPRESSIONTYPE_NONE) ||
(compression_type == TINYEXR_COMPRESSIONTYPE_RLE) ||
(compression_type == TINYEXR_COMPRESSIONTYPE_ZIPS) ||
(compression_type == TINYEXR_COMPRESSIONTYPE_ZIP)) {
#endif
// OK
} else {
tinyexr::SetErrorMessage("Unsupported compression format", err);
return TINYEXR_ERROR_UNSUPPORTED_FORMAT;
}
deep_image->image = static_cast<float ***>(
malloc(sizeof(float **) * static_cast<size_t>(num_channels)));
for (int c = 0; c < num_channels; c++) {
deep_image->image[c] = static_cast<float **>(
malloc(sizeof(float *) * static_cast<size_t>(data_height)));
for (int y = 0; y < data_height; y++) {
}
}
deep_image->offset_table = static_cast<int **>(
malloc(sizeof(int *) * static_cast<size_t>(data_height)));
for (int y = 0; y < data_height; y++) {
deep_image->offset_table[y] = static_cast<int *>(
malloc(sizeof(int) * static_cast<size_t>(data_width)));
}
for (size_t y = 0; y < static_cast<size_t>(num_blocks); y++) {
const unsigned char *data_ptr =
reinterpret_cast<const unsigned char *>(head + offsets[y]);
// int: y coordinate
// int64: packed size of pixel offset table
// int64: packed size of sample data
// int64: unpacked size of sample data
// compressed pixel offset table
// compressed sample data
int line_no;
tinyexr::tinyexr_int64 packedOffsetTableSize;
tinyexr::tinyexr_int64 packedSampleDataSize;
tinyexr::tinyexr_int64 unpackedSampleDataSize;
memcpy(&line_no, data_ptr, sizeof(int));
memcpy(&packedOffsetTableSize, data_ptr + 4,
sizeof(tinyexr::tinyexr_int64));
memcpy(&packedSampleDataSize, data_ptr + 12,
sizeof(tinyexr::tinyexr_int64));
memcpy(&unpackedSampleDataSize, data_ptr + 20,
sizeof(tinyexr::tinyexr_int64));
tinyexr::swap4(&line_no);
tinyexr::swap8(
reinterpret_cast<tinyexr::tinyexr_uint64 *>(&packedOffsetTableSize));
tinyexr::swap8(
reinterpret_cast<tinyexr::tinyexr_uint64 *>(&packedSampleDataSize));
tinyexr::swap8(
reinterpret_cast<tinyexr::tinyexr_uint64 *>(&unpackedSampleDataSize));
std::vector<int> pixelOffsetTable(static_cast<size_t>(data_width));
// decode pixel offset table.
{
unsigned long dstLen =
static_cast<unsigned long>(pixelOffsetTable.size() * sizeof(int));
if (!tinyexr::DecompressZip(
reinterpret_cast<unsigned char *>(&pixelOffsetTable.at(0)),
&dstLen, data_ptr + 28,
static_cast<unsigned long>(packedOffsetTableSize))) {
return false;
}
assert(dstLen == pixelOffsetTable.size() * sizeof(int));
for (size_t i = 0; i < static_cast<size_t>(data_width); i++) {
deep_image->offset_table[y][i] = pixelOffsetTable[i];
}
}
std::vector<unsigned char> sample_data(
static_cast<size_t>(unpackedSampleDataSize));
// decode sample data.
{
unsigned long dstLen = static_cast<unsigned long>(unpackedSampleDataSize);
if (dstLen) {
if (!tinyexr::DecompressZip(
reinterpret_cast<unsigned char *>(&sample_data.at(0)), &dstLen,
data_ptr + 28 + packedOffsetTableSize,
static_cast<unsigned long>(packedSampleDataSize))) {
return false;
}
assert(dstLen == static_cast<unsigned long>(unpackedSampleDataSize));
}
}
// decode sample
int sampleSize = -1;
std::vector<int> channel_offset_list(static_cast<size_t>(num_channels));
{
int channel_offset = 0;
for (size_t i = 0; i < static_cast<size_t>(num_channels); i++) {
channel_offset_list[i] = channel_offset;
if (channels[i].pixel_type == TINYEXR_PIXELTYPE_UINT) { // UINT
channel_offset += 4;
} else if (channels[i].pixel_type == TINYEXR_PIXELTYPE_HALF) { // half
channel_offset += 2;
} else if (channels[i].pixel_type ==
TINYEXR_PIXELTYPE_FLOAT) { // float
channel_offset += 4;
} else {
assert(0);
}
}
sampleSize = channel_offset;
}
assert(sampleSize >= 2);
assert(static_cast<size_t>(
pixelOffsetTable[static_cast<size_t>(data_width - 1)] *
sampleSize) == sample_data.size());
int samples_per_line = static_cast<int>(sample_data.size()) / sampleSize;
//
// Alloc memory
//
//
// pixel data is stored as image[channels][pixel_samples]
//
{
tinyexr::tinyexr_uint64 data_offset = 0;
for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) {
deep_image->image[c][y] = static_cast<float *>(
malloc(sizeof(float) * static_cast<size_t>(samples_per_line)));
if (channels[c].pixel_type == 0) { // UINT
for (size_t x = 0; x < static_cast<size_t>(samples_per_line); x++) {
unsigned int ui;
unsigned int *src_ptr = reinterpret_cast<unsigned int *>(
&sample_data.at(size_t(data_offset) + x * sizeof(int)));
tinyexr::cpy4(&ui, src_ptr);
deep_image->image[c][y][x] = static_cast<float>(ui); // @fixme
}
data_offset +=
sizeof(unsigned int) * static_cast<size_t>(samples_per_line);
} else if (channels[c].pixel_type == 1) { // half
for (size_t x = 0; x < static_cast<size_t>(samples_per_line); x++) {
tinyexr::FP16 f16;
const unsigned short *src_ptr = reinterpret_cast<unsigned short *>(
&sample_data.at(size_t(data_offset) + x * sizeof(short)));
tinyexr::cpy2(&(f16.u), src_ptr);
tinyexr::FP32 f32 = half_to_float(f16);
deep_image->image[c][y][x] = f32.f;
}
data_offset += sizeof(short) * static_cast<size_t>(samples_per_line);
} else { // float
for (size_t x = 0; x < static_cast<size_t>(samples_per_line); x++) {
float f;
const float *src_ptr = reinterpret_cast<float *>(
&sample_data.at(size_t(data_offset) + x * sizeof(float)));
tinyexr::cpy4(&f, src_ptr);
deep_image->image[c][y][x] = f;
}
data_offset += sizeof(float) * static_cast<size_t>(samples_per_line);
}
}
}
} // y
deep_image->width = data_width;
deep_image->height = data_height;
deep_image->channel_names = static_cast<const char **>(
malloc(sizeof(const char *) * static_cast<size_t>(num_channels)));
for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) {
#ifdef _WIN32
deep_image->channel_names[c] = _strdup(channels[c].name.c_str());
#else
deep_image->channel_names[c] = strdup(channels[c].name.c_str());
#endif
}
deep_image->num_channels = num_channels;
return TINYEXR_SUCCESS;
}
void InitEXRImage(EXRImage *exr_image) {
if (exr_image == NULL) {
return;
}
exr_image->width = 0;
exr_image->height = 0;
exr_image->num_channels = 0;
exr_image->images = NULL;
exr_image->tiles = NULL;
exr_image->next_level = NULL;
exr_image->level_x = 0;
exr_image->level_y = 0;
exr_image->num_tiles = 0;
}
void FreeEXRErrorMessage(const char *msg) {
if (msg) {
free(reinterpret_cast<void *>(const_cast<char *>(msg)));
}
return;
}
void InitEXRHeader(EXRHeader *exr_header) {
if (exr_header == NULL) {
return;
}
memset(exr_header, 0, sizeof(EXRHeader));
}
int FreeEXRHeader(EXRHeader *exr_header) {
if (exr_header == NULL) {
return TINYEXR_ERROR_INVALID_ARGUMENT;
}
if (exr_header->channels) {
free(exr_header->channels);
}
if (exr_header->pixel_types) {
free(exr_header->pixel_types);
}
if (exr_header->requested_pixel_types) {
free(exr_header->requested_pixel_types);
}
for (int i = 0; i < exr_header->num_custom_attributes; i++) {
if (exr_header->custom_attributes[i].value) {
free(exr_header->custom_attributes[i].value);
}
}
if (exr_header->custom_attributes) {
free(exr_header->custom_attributes);
}
EXRSetNameAttr(exr_header, NULL);
return TINYEXR_SUCCESS;
}
void EXRSetNameAttr(EXRHeader* exr_header, const char* name) {
if (exr_header == NULL) {
return;
}
memset(exr_header->name, 0, 256);
if (name != NULL) {
size_t len = std::min(strlen(name), (size_t)255);
if (len) {
memcpy(exr_header->name, name, len);
}
}
}
int EXRNumLevels(const EXRImage* exr_image) {
if (exr_image == NULL) return 0;
if(exr_image->images) return 1; // scanlines
int levels = 1;
const EXRImage* level_image = exr_image;
while((level_image = level_image->next_level)) ++levels;
return levels;
}
int FreeEXRImage(EXRImage *exr_image) {
if (exr_image == NULL) {
return TINYEXR_ERROR_INVALID_ARGUMENT;
}
if (exr_image->next_level) {
FreeEXRImage(exr_image->next_level);
delete exr_image->next_level;
}
for (int i = 0; i < exr_image->num_channels; i++) {
if (exr_image->images && exr_image->images[i]) {
free(exr_image->images[i]);
}
}
if (exr_image->images) {
free(exr_image->images);
}
if (exr_image->tiles) {
for (int tid = 0; tid < exr_image->num_tiles; tid++) {
for (int i = 0; i < exr_image->num_channels; i++) {
if (exr_image->tiles[tid].images && exr_image->tiles[tid].images[i]) {
free(exr_image->tiles[tid].images[i]);
}
}
if (exr_image->tiles[tid].images) {
free(exr_image->tiles[tid].images);
}
}
free(exr_image->tiles);
}
return TINYEXR_SUCCESS;
}
int ParseEXRHeaderFromFile(EXRHeader *exr_header, const EXRVersion *exr_version,
const char *filename, const char **err) {
if (exr_header == NULL || exr_version == NULL || filename == NULL) {
tinyexr::SetErrorMessage("Invalid argument for ParseEXRHeaderFromFile",
err);
return TINYEXR_ERROR_INVALID_ARGUMENT;
}
FILE *fp = NULL;
#ifdef _WIN32
#if defined(_MSC_VER) || defined(__MINGW32__) // MSVC, MinGW gcc or clang
errno_t errcode =
_wfopen_s(&fp, tinyexr::UTF8ToWchar(filename).c_str(), L"rb");
if (errcode != 0) {
tinyexr::SetErrorMessage("Cannot read file " + std::string(filename), err);
return TINYEXR_ERROR_INVALID_FILE;
}
#else
// Unknown compiler
fp = fopen(filename, "rb");
#endif
#else
fp = fopen(filename, "rb");
#endif
if (!fp) {
tinyexr::SetErrorMessage("Cannot read file " + std::string(filename), err);
return TINYEXR_ERROR_CANT_OPEN_FILE;
}
size_t filesize;
// Compute size
fseek(fp, 0, SEEK_END);
filesize = static_cast<size_t>(ftell(fp));
fseek(fp, 0, SEEK_SET);
std::vector<unsigned char> buf(filesize); // @todo { use mmap }
{
size_t ret;
ret = fread(&buf[0], 1, filesize, fp);
assert(ret == filesize);
fclose(fp);
if (ret != filesize) {
tinyexr::SetErrorMessage("fread() error on " + std::string(filename),
err);
return TINYEXR_ERROR_INVALID_FILE;
}
}
return ParseEXRHeaderFromMemory(exr_header, exr_version, &buf.at(0), filesize,
err);
}
int ParseEXRMultipartHeaderFromMemory(EXRHeader ***exr_headers,
int *num_headers,
const EXRVersion *exr_version,
const unsigned char *memory, size_t size,
const char **err) {
if (memory == NULL || exr_headers == NULL || num_headers == NULL ||
exr_version == NULL) {
// Invalid argument
tinyexr::SetErrorMessage(
"Invalid argument for ParseEXRMultipartHeaderFromMemory", err);
return TINYEXR_ERROR_INVALID_ARGUMENT;
}
if (size < tinyexr::kEXRVersionSize) {
tinyexr::SetErrorMessage("Data size too short", err);
return TINYEXR_ERROR_INVALID_DATA;
}
const unsigned char *marker = memory + tinyexr::kEXRVersionSize;
size_t marker_size = size - tinyexr::kEXRVersionSize;
std::vector<tinyexr::HeaderInfo> infos;
for (;;) {
tinyexr::HeaderInfo info;
info.clear();
std::string err_str;
bool empty_header = false;
int ret = ParseEXRHeader(&info, &empty_header, exr_version, &err_str,
marker, marker_size);
if (ret != TINYEXR_SUCCESS) {
tinyexr::SetErrorMessage(err_str, err);
return ret;
}
if (empty_header) {
marker += 1; // skip '\0'
break;
}
// `chunkCount` must exist in the header.
if (info.chunk_count == 0) {
tinyexr::SetErrorMessage(
"`chunkCount' attribute is not found in the header.", err);
return TINYEXR_ERROR_INVALID_DATA;
}
infos.push_back(info);
// move to next header.
marker += info.header_len;
size -= info.header_len;
}
// allocate memory for EXRHeader and create array of EXRHeader pointers.
(*exr_headers) =
static_cast<EXRHeader **>(malloc(sizeof(EXRHeader *) * infos.size()));
for (size_t i = 0; i < infos.size(); i++) {
EXRHeader *exr_header = static_cast<EXRHeader *>(malloc(sizeof(EXRHeader)));
memset(exr_header, 0, sizeof(EXRHeader));
ConvertHeader(exr_header, infos[i]);
exr_header->multipart = exr_version->multipart ? 1 : 0;
(*exr_headers)[i] = exr_header;
}
(*num_headers) = static_cast<int>(infos.size());
return TINYEXR_SUCCESS;
}
int ParseEXRMultipartHeaderFromFile(EXRHeader ***exr_headers, int *num_headers,
const EXRVersion *exr_version,
const char *filename, const char **err) {
if (exr_headers == NULL || num_headers == NULL || exr_version == NULL ||
filename == NULL) {
tinyexr::SetErrorMessage(
"Invalid argument for ParseEXRMultipartHeaderFromFile()", err);
return TINYEXR_ERROR_INVALID_ARGUMENT;
}
FILE *fp = NULL;
#ifdef _WIN32
#if defined(_MSC_VER) || defined(__MINGW32__) // MSVC, MinGW gcc or clang
errno_t errcode =
_wfopen_s(&fp, tinyexr::UTF8ToWchar(filename).c_str(), L"rb");
if (errcode != 0) {
tinyexr::SetErrorMessage("Cannot read file " + std::string(filename), err);
return TINYEXR_ERROR_INVALID_FILE;
}
#else
// Unknown compiler
fp = fopen(filename, "rb");
#endif
#else
fp = fopen(filename, "rb");
#endif
if (!fp) {
tinyexr::SetErrorMessage("Cannot read file " + std::string(filename), err);
return TINYEXR_ERROR_CANT_OPEN_FILE;
}
size_t filesize;
// Compute size
fseek(fp, 0, SEEK_END);
filesize = static_cast<size_t>(ftell(fp));
fseek(fp, 0, SEEK_SET);
std::vector<unsigned char> buf(filesize); // @todo { use mmap }
{
size_t ret;
ret = fread(&buf[0], 1, filesize, fp);
assert(ret == filesize);
fclose(fp);
if (ret != filesize) {
tinyexr::SetErrorMessage("`fread' error. file may be corrupted.", err);
return TINYEXR_ERROR_INVALID_FILE;
}
}
return ParseEXRMultipartHeaderFromMemory(
exr_headers, num_headers, exr_version, &buf.at(0), filesize, err);
}
int ParseEXRVersionFromMemory(EXRVersion *version, const unsigned char *memory,
size_t size) {
if (version == NULL || memory == NULL) {
return TINYEXR_ERROR_INVALID_ARGUMENT;
}
if (size < tinyexr::kEXRVersionSize) {
return TINYEXR_ERROR_INVALID_DATA;
}
const unsigned char *marker = memory;
// Header check.
{
const char header[] = {0x76, 0x2f, 0x31, 0x01};
if (memcmp(marker, header, 4) != 0) {
return TINYEXR_ERROR_INVALID_MAGIC_NUMBER;
}
marker += 4;
}
version->tiled = false;
version->long_name = false;
version->non_image = false;
version->multipart = false;
// Parse version header.
{
// must be 2
if (marker[0] != 2) {
return TINYEXR_ERROR_INVALID_EXR_VERSION;
}
if (version == NULL) {
return TINYEXR_SUCCESS; // May OK
}
version->version = 2;
if (marker[1] & 0x2) { // 9th bit
version->tiled = true;
}
if (marker[1] & 0x4) { // 10th bit
version->long_name = true;
}
if (marker[1] & 0x8) { // 11th bit
version->non_image = true; // (deep image)
}
if (marker[1] & 0x10) { // 12th bit
version->multipart = true;
}
}
return TINYEXR_SUCCESS;
}
int ParseEXRVersionFromFile(EXRVersion *version, const char *filename) {
if (filename == NULL) {
return TINYEXR_ERROR_INVALID_ARGUMENT;
}
FILE *fp = NULL;
#ifdef _WIN32
#if defined(_MSC_VER) || defined(__MINGW32__) // MSVC, MinGW gcc or clang
errno_t err = _wfopen_s(&fp, tinyexr::UTF8ToWchar(filename).c_str(), L"rb");
if (err != 0) {
// TODO(syoyo): return wfopen_s erro code
return TINYEXR_ERROR_CANT_OPEN_FILE;
}
#else
// Unknown compiler
fp = fopen(filename, "rb");
#endif
#else
fp = fopen(filename, "rb");
#endif
if (!fp) {
return TINYEXR_ERROR_CANT_OPEN_FILE;
}
size_t file_size;
// Compute size
fseek(fp, 0, SEEK_END);
file_size = static_cast<size_t>(ftell(fp));
fseek(fp, 0, SEEK_SET);
if (file_size < tinyexr::kEXRVersionSize) {
return TINYEXR_ERROR_INVALID_FILE;
}
unsigned char buf[tinyexr::kEXRVersionSize];
size_t ret = fread(&buf[0], 1, tinyexr::kEXRVersionSize, fp);
fclose(fp);
if (ret != tinyexr::kEXRVersionSize) {
return TINYEXR_ERROR_INVALID_FILE;
}
return ParseEXRVersionFromMemory(version, buf, tinyexr::kEXRVersionSize);
}
int LoadEXRMultipartImageFromMemory(EXRImage *exr_images,
const EXRHeader **exr_headers,
unsigned int num_parts,
const unsigned char *memory,
const size_t size, const char **err) {
if (exr_images == NULL || exr_headers == NULL || num_parts == 0 ||
memory == NULL || (size <= tinyexr::kEXRVersionSize)) {
tinyexr::SetErrorMessage(
"Invalid argument for LoadEXRMultipartImageFromMemory()", err);
return TINYEXR_ERROR_INVALID_ARGUMENT;
}
// compute total header size.
size_t total_header_size = 0;
for (unsigned int i = 0; i < num_parts; i++) {
if (exr_headers[i]->header_len == 0) {
tinyexr::SetErrorMessage("EXRHeader variable is not initialized.", err);
return TINYEXR_ERROR_INVALID_ARGUMENT;
}
total_header_size += exr_headers[i]->header_len;
}
const char *marker = reinterpret_cast<const char *>(
memory + total_header_size + 4 +
4); // +8 for magic number and version header.
marker += 1; // Skip empty header.
// NOTE 1:
// In multipart image, There is 'part number' before chunk data.
// 4 byte : part number
// 4+ : chunk
//
// NOTE 2:
// EXR spec says 'part number' is 'unsigned long' but actually this is
// 'unsigned int(4 bytes)' in OpenEXR implementation...
// http://www.openexr.com/openexrfilelayout.pdf
// Load chunk offset table.
std::vector<tinyexr::OffsetData> chunk_offset_table_list;
chunk_offset_table_list.reserve(num_parts);
for (size_t i = 0; i < static_cast<size_t>(num_parts); i++) {
chunk_offset_table_list.resize(chunk_offset_table_list.size() + 1);
tinyexr::OffsetData& offset_data = chunk_offset_table_list.back();
if (!exr_headers[i]->tiled || exr_headers[i]->tile_level_mode == TINYEXR_TILE_ONE_LEVEL) {
tinyexr::InitSingleResolutionOffsets(offset_data, exr_headers[i]->chunk_count);
std::vector<tinyexr::tinyexr_uint64>& offset_table = offset_data.offsets[0][0];
for (size_t c = 0; c < offset_table.size(); c++) {
tinyexr::tinyexr_uint64 offset;
memcpy(&offset, marker, 8);
tinyexr::swap8(&offset);
if (offset >= size) {
tinyexr::SetErrorMessage("Invalid offset size in EXR header chunks.",
err);
return TINYEXR_ERROR_INVALID_DATA;
}
offset_table[c] = offset + 4; // +4 to skip 'part number'
marker += 8;
}
} else {
{
std::vector<int> num_x_tiles, num_y_tiles;
tinyexr::PrecalculateTileInfo(num_x_tiles, num_y_tiles, exr_headers[i]);
int num_blocks = InitTileOffsets(offset_data, exr_headers[i], num_x_tiles, num_y_tiles);
if (num_blocks != exr_headers[i]->chunk_count) {
tinyexr::SetErrorMessage("Invalid offset table size.", err);
return TINYEXR_ERROR_INVALID_DATA;
}
}
for (unsigned int l = 0; l < offset_data.offsets.size(); ++l) {
for (unsigned int dy = 0; dy < offset_data.offsets[l].size(); ++dy) {
for (unsigned int dx = 0; dx < offset_data.offsets[l][dy].size(); ++dx) {
tinyexr::tinyexr_uint64 offset;
memcpy(&offset, marker, sizeof(tinyexr::tinyexr_uint64));
tinyexr::swap8(&offset);
if (offset >= size) {
tinyexr::SetErrorMessage("Invalid offset size in EXR header chunks.",
err);
return TINYEXR_ERROR_INVALID_DATA;
}
offset_data.offsets[l][dy][dx] = offset + 4; // +4 to skip 'part number'
marker += sizeof(tinyexr::tinyexr_uint64); // = 8
}
}
}
}
}
// Decode image.
for (size_t i = 0; i < static_cast<size_t>(num_parts); i++) {
tinyexr::OffsetData &offset_data = chunk_offset_table_list[i];
// First check 'part number' is identitical to 'i'
for (unsigned int l = 0; l < offset_data.offsets.size(); ++l)
for (unsigned int dy = 0; dy < offset_data.offsets[l].size(); ++dy)
for (unsigned int dx = 0; dx < offset_data.offsets[l][dy].size(); ++dx) {
const unsigned char *part_number_addr =
memory + offset_data.offsets[l][dy][dx] - 4; // -4 to move to 'part number' field.
unsigned int part_no;
memcpy(&part_no, part_number_addr, sizeof(unsigned int)); // 4
tinyexr::swap4(&part_no);
if (part_no != i) {
tinyexr::SetErrorMessage("Invalid `part number' in EXR header chunks.",
err);
return TINYEXR_ERROR_INVALID_DATA;
}
}
std::string e;
int ret = tinyexr::DecodeChunk(&exr_images[i], exr_headers[i], offset_data,
memory, size, &e);
if (ret != TINYEXR_SUCCESS) {
if (!e.empty()) {
tinyexr::SetErrorMessage(e, err);
}
return ret;
}
}
return TINYEXR_SUCCESS;
}
int LoadEXRMultipartImageFromFile(EXRImage *exr_images,
const EXRHeader **exr_headers,
unsigned int num_parts, const char *filename,
const char **err) {
if (exr_images == NULL || exr_headers == NULL || num_parts == 0) {
tinyexr::SetErrorMessage(
"Invalid argument for LoadEXRMultipartImageFromFile", err);
return TINYEXR_ERROR_INVALID_ARGUMENT;
}
FILE *fp = NULL;
#ifdef _WIN32
#if defined(_MSC_VER) || defined(__MINGW32__) // MSVC, MinGW gcc or clang
errno_t errcode =
_wfopen_s(&fp, tinyexr::UTF8ToWchar(filename).c_str(), L"rb");
if (errcode != 0) {
tinyexr::SetErrorMessage("Cannot read file " + std::string(filename), err);
return TINYEXR_ERROR_CANT_OPEN_FILE;
}
#else
// Unknown compiler
fp = fopen(filename, "rb");
#endif
#else
fp = fopen(filename, "rb");
#endif
if (!fp) {
tinyexr::SetErrorMessage("Cannot read file " + std::string(filename), err);
return TINYEXR_ERROR_CANT_OPEN_FILE;
}
size_t filesize;
// Compute size
fseek(fp, 0, SEEK_END);
filesize = static_cast<size_t>(ftell(fp));
fseek(fp, 0, SEEK_SET);
std::vector<unsigned char> buf(filesize); // @todo { use mmap }
{
size_t ret;
ret = fread(&buf[0], 1, filesize, fp);
assert(ret == filesize);
fclose(fp);
(void)ret;
}
return LoadEXRMultipartImageFromMemory(exr_images, exr_headers, num_parts,
&buf.at(0), filesize, err);
}
int SaveEXR(const float *data, int width, int height, int components,
const int save_as_fp16, const char *outfilename, const char **err) {
if ((components == 1) || components == 3 || components == 4) {
// OK
} else {
std::stringstream ss;
ss << "Unsupported component value : " << components << std::endl;
tinyexr::SetErrorMessage(ss.str(), err);
return TINYEXR_ERROR_INVALID_ARGUMENT;
}
EXRHeader header;
InitEXRHeader(&header);
if ((width < 16) && (height < 16)) {
// No compression for small image.
header.compression_type = TINYEXR_COMPRESSIONTYPE_NONE;
} else {
header.compression_type = TINYEXR_COMPRESSIONTYPE_ZIP;
}
EXRImage image;
InitEXRImage(&image);
image.num_channels = components;
std::vector<float> images[4];
if (components == 1) {
images[0].resize(static_cast<size_t>(width * height));
memcpy(images[0].data(), data, sizeof(float) * size_t(width * height));
} else {
images[0].resize(static_cast<size_t>(width * height));
images[1].resize(static_cast<size_t>(width * height));
images[2].resize(static_cast<size_t>(width * height));
images[3].resize(static_cast<size_t>(width * height));
// Split RGB(A)RGB(A)RGB(A)... into R, G and B(and A) layers
for (size_t i = 0; i < static_cast<size_t>(width * height); i++) {
images[0][i] = data[static_cast<size_t>(components) * i + 0];
images[1][i] = data[static_cast<size_t>(components) * i + 1];
images[2][i] = data[static_cast<size_t>(components) * i + 2];
if (components == 4) {
images[3][i] = data[static_cast<size_t>(components) * i + 3];
}
}
}
float *image_ptr[4] = {0, 0, 0, 0};
if (components == 4) {
image_ptr[0] = &(images[3].at(0)); // A
image_ptr[1] = &(images[2].at(0)); // B
image_ptr[2] = &(images[1].at(0)); // G
image_ptr[3] = &(images[0].at(0)); // R
} else if (components == 3) {
image_ptr[0] = &(images[2].at(0)); // B
image_ptr[1] = &(images[1].at(0)); // G
image_ptr[2] = &(images[0].at(0)); // R
} else if (components == 1) {
image_ptr[0] = &(images[0].at(0)); // A
}
image.images = reinterpret_cast<unsigned char **>(image_ptr);
image.width = width;
image.height = height;
header.num_channels = components;
header.channels = static_cast<EXRChannelInfo *>(malloc(
sizeof(EXRChannelInfo) * static_cast<size_t>(header.num_channels)));
// Must be (A)BGR order, since most of EXR viewers expect this channel order.
if (components == 4) {
#ifdef _MSC_VER
strncpy_s(header.channels[0].name, "A", 255);
strncpy_s(header.channels[1].name, "B", 255);
strncpy_s(header.channels[2].name, "G", 255);
strncpy_s(header.channels[3].name, "R", 255);
#else
strncpy(header.channels[0].name, "A", 255);
strncpy(header.channels[1].name, "B", 255);
strncpy(header.channels[2].name, "G", 255);
strncpy(header.channels[3].name, "R", 255);
#endif
header.channels[0].name[strlen("A")] = '\0';
header.channels[1].name[strlen("B")] = '\0';
header.channels[2].name[strlen("G")] = '\0';
header.channels[3].name[strlen("R")] = '\0';
} else if (components == 3) {
#ifdef _MSC_VER
strncpy_s(header.channels[0].name, "B", 255);
strncpy_s(header.channels[1].name, "G", 255);
strncpy_s(header.channels[2].name, "R", 255);
#else
strncpy(header.channels[0].name, "B", 255);
strncpy(header.channels[1].name, "G", 255);
strncpy(header.channels[2].name, "R", 255);
#endif
header.channels[0].name[strlen("B")] = '\0';
header.channels[1].name[strlen("G")] = '\0';
header.channels[2].name[strlen("R")] = '\0';
} else {
#ifdef _MSC_VER
strncpy_s(header.channels[0].name, "A", 255);
#else
strncpy(header.channels[0].name, "A", 255);
#endif
header.channels[0].name[strlen("A")] = '\0';
}
header.pixel_types = static_cast<int *>(
malloc(sizeof(int) * static_cast<size_t>(header.num_channels)));
header.requested_pixel_types = static_cast<int *>(
malloc(sizeof(int) * static_cast<size_t>(header.num_channels)));
for (int i = 0; i < header.num_channels; i++) {
header.pixel_types[i] =
TINYEXR_PIXELTYPE_FLOAT; // pixel type of input image
if (save_as_fp16 > 0) {
header.requested_pixel_types[i] =
TINYEXR_PIXELTYPE_HALF; // save with half(fp16) pixel format
} else {
header.requested_pixel_types[i] =
TINYEXR_PIXELTYPE_FLOAT; // save with float(fp32) pixel format(i.e.
// no precision reduction)
}
}
int ret = SaveEXRImageToFile(&image, &header, outfilename, err);
if (ret != TINYEXR_SUCCESS) {
return ret;
}
free(header.channels);
free(header.pixel_types);
free(header.requested_pixel_types);
return ret;
}
#ifdef __clang__
// zero-as-null-ppinter-constant
#pragma clang diagnostic pop
#endif
#endif // TINYEXR_IMPLEMENTATION_DEFINED
#endif // TINYEXR_IMPLEMENTATION
|
merge_sort_parallel.c | #include <omp.h>
#include <stdlib.h>
#include <stdio.h>
/* Parallel Merge sort algorithm implemented straight out of CLRS without much
* thought to speeding it up. The parallel version with openmp is
* monstrously slower than the version compilied without the -fopenmp flag.
* Use of openmp here is extremely likely not worth it. Likely no use in
* optomizing this further other than practice.
*/
#define LIST_SIZE 10000
void P_Merge_Sort(int *A, int p, int r, int *B, int s);
void P_Merge(int *T, int p1, int r1, int p2, int r2, int *A, int p3);
int bin_search(int x, int *T, int start, int end);
main() {
int i;
int *A, *B;
A = malloc(sizeof(int)*LIST_SIZE);
B = malloc(sizeof(int)*LIST_SIZE);
for (i=0; i<LIST_SIZE; i++) {
A[i] = (int) rand();
}
#pragma omp parallel
#pragma omp single
P_Merge_Sort(A, 0, LIST_SIZE-1, B, 0);
for (i=1; i<LIST_SIZE; i++) {
if (B[i] < B[i-1]) {
printf("Sorting was incorrect!\n");
break;
}
}
if (i == LIST_SIZE) printf("Success!\n");
free(A);
free(B);
}
void P_Merge_Sort(int *A, int p, int r, int *B, int s) {
int mid;
int n;
int *T;
n = r-p+1;
if (n == 1) {
B[s] = A[p];
return;
}
T = (int *) malloc(sizeof(int)*n);
mid = (r+p)/2;
int left_n = mid - p+1;
#pragma omp task untied
P_Merge_Sort(A, p, mid, T, 0);
#pragma omp task untied
P_Merge_Sort(A, mid+1, r, T, left_n);
#pragma omp taskwait
P_Merge(T, 0, left_n-1, left_n, n-1, B, s);
free(T);
}
void P_Merge(int *T, int p1, int r1, int p2, int r2, int *A, int p3) {
int q1, q2, q3;
int n1 = r1 - p1 + 1;
int n2 = r2 - p2 + 1;
if (n2 > n1) {
int temp;
temp = p1; p1 = p2; p2 = temp;
temp = r1; r1 = r2; r2 = temp;
temp = n1; n1 = n2; n2 = temp;
}
if (n1 <= 0) return;
q1 = (r1 + p1)/2;
q2 = bin_search(T[q1], T, p2, r2);
q3 = p3 + (q1 - p1) + (q2 - p2);
A[q3] = T[q1];
#pragma omp task untied
P_Merge(T, p1, q1-1, p2, q2-1, A, p3);
#pragma omp task untied
P_Merge(T, q1+1, r1, q2, r2, A, q3+1);
#pragma omp taskwait
}
int bin_search(int x, int *T, int start, int end) {
int mid;
int low = start;
int hi = end+1 > start ? end+1: start; //max(start,end+1)
while(low < hi) {
mid = (hi+low)/2;
if (x <= T[mid]) hi = mid;
else low = mid+1;
}
return low;
}
|
omp-simple-task.c | #include <stdio.h>
int main() {
int var_i = 0, var_j = 1;
#pragma omp parallel
{
#pragma omp task shared(var_i) firstprivate(var_j)
{
printf("hello tasks %d, %d\n", var_i, var_j);
}
}
return 0;
}
|
mgl.h | /***************************************************************************
* mgl.h is part of Math Graphic Library
* Copyright (C) 2007-2014 Alexey Balakin <mathgl.abalakin@gmail.ru> *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#ifndef _MGL_H_
#define _MGL_H_
#include "mgl2/mgl_cf.h"
#ifdef __cplusplus
#include "mgl2/data.h"
#include "mgl2/datac.h"
#include <sys/stat.h>
//-----------------------------------------------------------------------------
/// Wrapper class for all graphics
class MGL_EXPORT mglGraph
{
mglGraph(const mglGraph &t) {} // copying is not allowed
const mglGraph &operator=(const mglGraph &t) { return t; }
protected:
HMGL gr;
public:
mglGraph(int kind=0, int width=600, int height=400)
{
if(kind==-1) gr=NULL;
#if MGL_HAVE_OPENGL
else if(kind==1) gr=mgl_create_graph_gl();
#else
else if(kind==1)
{ gr=mgl_create_graph(width, height);
SetGlobalWarn("OpenGL support was disabled. Please, enable it and rebuild MathGL."); }
#endif
else gr=mgl_create_graph(width, height);
}
mglGraph(HMGL graph)
{ gr = graph; mgl_use_graph(gr,1); }
virtual ~mglGraph()
{ if(mgl_use_graph(gr,-1)<1) mgl_delete_graph(gr); }
/// Get pointer to internal HMGL object
inline HMGL Self() { return gr; }
/// Set default parameters for plotting
inline void DefaultPlotParam() { mgl_set_def_param(gr); }
/// Set name of plot for saving filename
inline void SetPlotId(const char *id) { mgl_set_plotid(gr,id); }
/// Get name of plot for saving filename
inline const char *GetPlotId() { return mgl_get_plotid(gr); }
/// Ask to stop drawing
inline void Stop(bool stop=true) { mgl_ask_stop(gr, stop); }
/// Check if plot termination is asked
inline bool NeedStop() { return mgl_need_stop(gr); }
/// Set callback function for event processing
inline void SetEventFunc(void (*func)(void *), void *par=NULL)
{ mgl_set_event_func(gr, func, par); }
/// Set the transparency on/off.
inline void Alpha(bool enable) { mgl_set_alpha(gr, enable); }
/// Set default value of alpha-channel
inline void SetAlphaDef(double alpha) { mgl_set_alpha_default(gr, alpha); }
/// Set the transparency type (0 - usual, 1 - glass, 2 - lamp)
inline void SetTranspType(int type) { mgl_set_transp_type(gr, type); }
/// Set the using of light on/off.
inline void Light(bool enable) { mgl_set_light(gr, enable); }
/// Switch on/off the specified light source.
inline void Light(int n,bool enable) { mgl_set_light_n(gr, n, enable); }
/// Use diffusive light (only for local light sources) -- OBSOLETE
inline void SetDifLight(bool dif) { mgl_set_light_dif(gr, dif); }
/// Add a light source.
inline void AddLight(int n, mglPoint p, char col='w', double bright=0.5, double ap=0)
{ mgl_add_light_ext(gr, n, p.x, p.y, p.z, col, bright, ap); }
inline void AddLight(int n, mglPoint r, mglPoint p, char col='w', double bright=0.5, double ap=0)
{ mgl_add_light_loc(gr, n, r.x, r.y, r.z, p.x, p.y, p.z, col, bright, ap); }
/// Set ambient light brightness
inline void SetAmbient(double i) { mgl_set_ambbr(gr, i); }
/// Set diffusive light brightness
inline void SetDiffuse(double i) { mgl_set_difbr(gr, i); }
/// Set the fog distance or switch it off (if d=0).
inline void Fog(double d, double dz=0.25) { mgl_set_fog(gr, d, dz); }
/// Set relative width of rectangles in Bars, Barh, BoxPlot
inline void SetBarWidth(double width) { mgl_set_bar_width(gr, width); }
/// Set default size of marks (locally you can use "size" option)
inline void SetMarkSize(double size) { mgl_set_mark_size(gr, size); }
/// Set default size of arrows (locally you can use "size" option)
inline void SetArrowSize(double size) { mgl_set_arrow_size(gr, size); }
/// Set number of mesh lines (use 0 to draw all of them)
inline void SetMeshNum(int num) { mgl_set_meshnum(gr, num); }
/// Set number of visible faces (use 0 to draw all of them)
inline void SetFaceNum(int num) { mgl_set_facenum(gr, num); }
/// Set cutting for points outside of bounding box
inline void SetCut(bool cut) { mgl_set_cut(gr, cut); }
/// Set additional cutting box
inline void SetCutBox(mglPoint p1, mglPoint p2)
{ mgl_set_cut_box(gr, p1.x, p1.y, p1.z, p2.x, p2.y, p2.z); }
/// Set the cutting off condition (formula)
inline void CutOff(const char *EqC) { mgl_set_cutoff(gr, EqC); }
/// Set default font size
inline void SetFontSize(double size) { mgl_set_font_size(gr, size); }
/// Set default font style and color
inline void SetFontDef(const char *fnt) { mgl_set_font_def(gr, fnt); }
/// Set FontSize by size in pt and picture DPI (default is 16 pt for dpi=72)
virtual void SetFontSizePT(double pt, int dpi=72){ SetFontSize(pt*27.f/dpi); }
/// Set FontSize by size in centimeters and picture DPI (default is 0.56 cm = 16 pt)
inline void SetFontSizeCM(double cm, int dpi=72) { SetFontSizePT(cm*28.45f,dpi); }
/// Set FontSize by size in inch and picture DPI (default is 0.22 in = 16 pt)
inline void SetFontSizeIN(double in, int dpi=72) { SetFontSizePT(in*72.27f,dpi); }
/// Load font from file
inline void LoadFont(const char *name, const char *path=NULL)
{ mgl_load_font(gr, name, path); }
/// Copy font from another mglGraph instance
inline void CopyFont(const mglGraph *GR) { mgl_copy_font(gr, GR->gr);}
/// Restore font (load default font for new HMGL objects)
inline void RestoreFont() { mgl_restore_font(gr); }
/// Set to use or not text rotation
inline void SetRotatedText(bool rotated) { mgl_set_rotated_text(gr, rotated); }
/// Set default font for all new HMGL and mglGraph objects
static inline void SetDefFont(const char *name, const char *path=NULL) { mgl_def_font(name,path); }
/// Set default palette
inline void SetPalette(const char *colors) { mgl_set_palette(gr, colors); }
/// Set default color scheme
inline void SetDefScheme(const char *sch) { mgl_set_def_sch(gr, sch); }
/// Sets RGB values for color with given id
static inline void SetColor(char id, double r, double g, double b) { mgl_set_color(id, r, g, b); }
/// Set mask for face coloring as array of type 'unsigned char[8]'
static inline void SetMask(char id, const char *mask) { mgl_set_mask(id, mask); }
/// Set mask for face coloring as uint64_t number
static inline void SetMask(char id, uint64_t mask) { mgl_set_mask_val(id, mask); }
/// Set default mask rotation angle
inline void SetMaskAngle(int angle) { mgl_set_mask_angle(gr, angle); }
/// Get last warning code
inline int GetWarn() { return mgl_get_warn(gr);}
/// Set warning code ant fill message
inline void SetWarn(int code, const char *info) { mgl_set_warn(gr,code,info); }
/// Get text of warning message(s)
inline const char *Message() { return mgl_get_mess(gr); }
/// Set global warning message
static inline void SetGlobalWarn(const char *text) { mgl_set_global_warn(text); }
/// Get text of global warning message(s)
static inline const char *GlobalWarn() { return mgl_get_global_warn(); }
/// Suppress printing warnings to stderr
static inline void SuppressWarn(bool on) { mgl_suppress_warn(on); }
/// Check if MathGL version is valid (return false) or not (return true)
static inline bool CheckVersion(const char *ver) { return mgl_check_version(ver); }
/// Set axis range scaling -- simplified way to shift/zoom axis range -- need to replot whole image!
inline void ZoomAxis(mglPoint p1=mglPoint(0,0,0,0), mglPoint p2=mglPoint(1,1,1,1))
{ mgl_zoom_axis(gr, p1.x,p1.y,p1.z,p1.c, p2.x,p2.y,p2.z,p2.c); }
/// Add [v1, v2] to the current range in direction dir
inline void AddRange(char dir, double v1, double v2)
{ mgl_add_range_val(gr, dir, v1, v2); }
/// Set range in direction dir as [v1, v2]
inline void SetRange(char dir, double v1, double v2)
{ mgl_set_range_val(gr, dir, v1, v2); }
/// Set range in direction dir as minimal and maximal values of data a
inline void SetRange(char dir, const mglDataA &dat, bool add=false)
{ mgl_set_range_dat(gr, dir, &dat, add); }
/// Set values of axis range as minimal and maximal values of datas
inline void SetRanges(const mglDataA &xx, const mglDataA &yy, const mglDataA &zz, const mglDataA &cc)
{ mgl_set_range_dat(gr,'x',&xx,0); mgl_set_range_dat(gr,'y',&yy,0);
mgl_set_range_dat(gr,'z',&zz,0); mgl_set_range_dat(gr,'c',&cc,0); }
/// Set values of axis range as minimal and maximal values of datas
inline void SetRanges(const mglDataA &xx, const mglDataA &yy, const mglDataA &zz)
{ mgl_set_range_dat(gr,'x',&xx,0); mgl_set_range_dat(gr,'y',&yy,0);
mgl_set_range_dat(gr,'z',&zz,0); mgl_set_range_dat(gr,'c',&zz,0); }
/// Set values of axis range as minimal and maximal values of datas
inline void SetRanges(const mglDataA &xx, const mglDataA &yy)
{ mgl_set_range_dat(gr,'x',&xx,0); mgl_set_range_dat(gr,'y',&yy,0); }
/// Set values of axis ranges
inline void SetRanges(double x1, double x2, double y1, double y2, double z1=0, double z2=0)
{ mgl_set_ranges(gr, x1, x2, y1, y2, z1, z2); }
/// Set values of axis ranges
inline void SetRanges(mglPoint p1, mglPoint p2)
{ mgl_set_ranges(gr, p1.x, p2.x, p1.y, p2.y, p1.z, p2.z); }
/// Set ranges for automatic variables
inline void SetAutoRanges(double x1, double x2, double y1=0, double y2=0, double z1=0, double z2=0, double c1=0, double c2=0)
{ mgl_set_auto_ranges(gr, x1, x2, y1, y2, z1, z2, c1, c2); }
/// Set ranges for automatic variables
inline void SetAutoRanges(mglPoint p1, mglPoint p2)
{ mgl_set_auto_ranges(gr, p1.x, p2.x, p1.y, p2.y, p1.z, p2.z, p1.c, p2.c); }
/// Set axis origin
inline void SetOrigin(mglPoint p)
{ mgl_set_origin(gr, p.x, p.y, p.z); }
inline void SetOrigin(double x0, double y0, double z0=mglNaN)
{ mgl_set_origin(gr, x0, y0, z0); }
/// Set the transformation formulas for coordinate
inline void SetFunc(const char *EqX, const char *EqY, const char *EqZ=NULL, const char *EqA=NULL)
{ mgl_set_func(gr, EqX, EqY, EqZ, EqA); }
/// Set one of predefined transformation rule
inline void SetCoor(int how) { mgl_set_coor(gr, how); }
/// Set to draw Ternary axis (triangle like axis, grid and so on)
inline void Ternary(int val) { mgl_set_ternary(gr, val); }
/// Set to use or not tick labels rotation
inline void SetTickRotate(bool val) { mgl_set_tick_rotate(gr,val); }
/// Set to use or not tick labels skipping
inline void SetTickSkip(bool val) { mgl_set_tick_skip(gr,val); }
/// Set tick length
inline void SetTickLen(double len, double stt=1)
{ mgl_set_tick_len(gr, len, stt); }
/// Set axis and ticks style
inline void SetAxisStl(const char *stl="k", const char *tck=0, const char *sub=0)
{ mgl_set_axis_stl(gr, stl, tck, sub); }
/// Set time templates for ticks
inline void SetTicksTime(char dir, double d=0, const char *t="")
{ mgl_set_ticks_time(gr,dir,d,t); }
/// Set ticks text (\n separated). Use "" to disable this feature.
inline void SetTicksVal(char dir, const char *lbl, bool add=false)
{ mgl_set_ticks_str(gr,dir,lbl,add); }
inline void SetTicksVal(char dir, const wchar_t *lbl, bool add=false)
{ mgl_set_ticks_wcs(gr,dir,lbl,add); }
/// Set ticks position and text (\n separated). Use "" to disable this feature.
inline void SetTicksVal(char dir, const mglDataA &v, const char *lbl, bool add=false)
{ mgl_set_ticks_val(gr,dir,&v,lbl,add); }
inline void SetTicksVal(char dir, const mglDataA &v, const wchar_t *lbl, bool add=false)
{ mgl_set_ticks_valw(gr,dir,&v,lbl,add); }
/// Add manual tick at given position. Use "" to disable this feature.
inline void AddTick(char dir, double val, const char *lbl)
{ mgl_add_tick(gr,dir,val,lbl); }
inline void AddTick(char dir, double val, const wchar_t *lbl)
{ mgl_add_tickw(gr,dir,val,lbl); }
/// Set the ticks parameters and string for its factor
inline void SetTicks(char dir, double d=0, int ns=0, double org=mglNaN, const char *factor="")
{ mgl_set_ticks_fact(gr, dir, d, ns, org, factor); }
inline void SetTicks(char dir, double d, int ns, double org, const wchar_t *factor)
{ mgl_set_ticks_factw(gr, dir, d, ns, org, factor); }
/// Auto adjust ticks
inline void Adjust(const char *dir="xyzc")
{ mgl_adjust_ticks(gr, dir); }
/// Set templates for ticks
inline void SetTickTempl(char dir, const char *t)
{ mgl_set_tick_templ(gr,dir,t); }
inline void SetTickTempl(char dir, const wchar_t *t)
{ mgl_set_tick_templw(gr,dir,t); }
/// Tune ticks
inline void SetTuneTicks(int tune, double fact_pos=1.15)
{ mgl_tune_ticks(gr, tune, fact_pos); }
/// Set additional shift of tick labels
inline void SetTickShift(mglPoint p)
{ mgl_set_tick_shift(gr,p.x,p.y,p.z,p.c); }
/// Set to use UTC time instead of local time
inline void SetTimeUTC(bool enable)
{ mgl_set_flag(gr,enable, MGL_USE_GMTIME); }
/// Set to draw tick labels at axis origin
inline void SetOriginTick(bool enable=true)
{ mgl_set_flag(gr,!enable, MGL_NO_ORIGIN); }
/// Put further plotting in some region of whole frame.
inline void SubPlot(int nx,int ny,int m,const char *style="<>_^", double dx=0, double dy=0)
{ mgl_subplot_d(gr, nx, ny, m, style, dx, dy); }
/// Like SubPlot() but "join" several cells
inline void MultiPlot(int nx,int ny,int m, int dx, int dy, const char *style="<>_^")
{ mgl_multiplot(gr, nx, ny, m, dx, dy, style); }
/// Put further plotting in a region of whole frame.
inline void InPlot(double x1,double x2,double y1,double y2, bool rel=true)
{ if(rel) mgl_relplot(gr, x1, x2, y1, y2);
else mgl_inplot(gr, x1, x2, y1, y2); }
/// Put further plotting in column cell of previous subplot
inline void ColumnPlot(int num, int ind, double d=0)
{ mgl_columnplot(gr,num,ind,d); }
/// Put further plotting in matrix cell of previous subplot
inline void GridPlot(int nx, int ny, int ind, double d=0)
{ mgl_gridplot(gr,nx,ny,ind,d); }
/// Put further plotting in cell of stick rotated on angles tet, phi
inline void StickPlot(int num, int i, double tet, double phi)
{ mgl_stickplot(gr,num,i,tet,phi); }
/// Set factor of plot size
inline void SetPlotFactor(double val)
{ mgl_set_plotfactor(gr,val); }
/// Push transformation matrix into stack
inline void Push() { mgl_mat_push(gr); }
/// Pop transformation matrix from stack
inline void Pop() { mgl_mat_pop(gr); }
/// Add title for current subplot/inplot
inline void Title(const char *title,const char *stl="",double size=-2)
{ mgl_title(gr,title,stl,size); }
inline void Title(const wchar_t *title,const char *stl="",double size=-2)
{ mgl_titlew(gr,title,stl,size); }
/// Set aspect ratio for further plotting.
inline void Aspect(double Ax,double Ay,double Az=1)
{ mgl_aspect(gr, Ax, Ay, Az); }
/// Rotate a further plotting.
inline void Rotate(double TetX,double TetZ=0,double TetY=0)
{ mgl_rotate(gr, TetX, TetZ, TetY); }
/// Rotate a further plotting around vector {x,y,z}.
inline void RotateN(double Tet,double x,double y,double z)
{ mgl_rotate_vector(gr, Tet, x, y, z); }
/// Set perspective (in range [0,1)) for plot. Set to zero for switching off.
inline void Perspective(double val)
{ mgl_perspective(gr, val); }
/// Set angle of view independently from Rotate().
inline void View(double TetX,double TetZ=0,double TetY=0)
{ mgl_view(gr, TetX, TetZ, TetY); }
/// Set angle of view independently from Rotate().
inline void ViewAsRotate(double TetZ,double TetX,double TetY=0)
{ mgl_view(gr, -TetX, -TetZ, -TetY); }
/// Zoom in/out a part of picture (use Zoom(0, 0, 1, 1) for restore default)
inline void Zoom(double x1, double y1, double x2, double y2)
{ mgl_zoom(gr, x1, y1, x2, y2); }
/// Set size of frame in pixels. Normally this function is called internally.
inline void SetSize(int width, int height) { mgl_set_size(gr, width, height); }
/// Set plot quality
inline void SetQuality(int qual=MGL_DRAW_NORM) { mgl_set_quality(gr, qual); }
/// Get plot quality
inline int GetQuality() { return mgl_get_quality(gr); }
/// Set drawing region for Quality&4
inline void SetDrawReg(long nx=1, long ny=1, long m=0) { mgl_set_draw_reg(gr,nx,ny,m); }
/// Start group of objects
inline void StartGroup(const char *name) { mgl_start_group(gr, name); }
/// End group of objects
inline void EndGroup() { mgl_end_group(gr); }
/// Highlight objects with given id
inline void Highlight(int id) { mgl_highlight(gr, id); }
/// Show current image
inline void ShowImage(const char *viewer, bool keep=0)
{ mgl_show_image(gr, viewer, keep); }
/// Write the frame in file (depending extension, write current frame if fname is empty)
inline void WriteFrame(const char *fname=0,const char *descr="")
{ mgl_write_frame(gr, fname, descr); }
/// Write the frame in file using JPEG format
inline void WriteJPEG(const char *fname,const char *descr="")
{ mgl_write_jpg(gr, fname, descr); }
/// Write the frame in file using PNG format with transparency
inline void WritePNG(const char *fname,const char *descr="", bool alpha=true)
{ if(alpha) mgl_write_png(gr, fname, descr);
else mgl_write_png_solid(gr, fname, descr); }
/// Write the frame in file using BMP format
inline void WriteBMP(const char *fname,const char *descr="")
{ mgl_write_bmp(gr, fname, descr); }
/// Write the frame in file using BMP format
inline void WriteTGA(const char *fname,const char *descr="")
{ mgl_write_tga(gr, fname, descr); }
/// Write the frame in file using PostScript format
inline void WriteEPS(const char *fname,const char *descr="")
{ mgl_write_eps(gr, fname, descr); }
/// Write the frame in file using LaTeX format
inline void WriteTEX(const char *fname,const char *descr="")
{ mgl_write_tex(gr, fname, descr); }
/// Write the frame in file using PostScript format as bitmap
inline void WriteBPS(const char *fname,const char *descr="")
{ mgl_write_bps(gr, fname, descr); }
/// Write the frame in file using SVG format
inline void WriteSVG(const char *fname,const char *descr="")
{ mgl_write_svg(gr, fname, descr); }
/// Write the frame in file using GIF format (only for current frame!)
inline void WriteGIF(const char *fname,const char *descr="")
{ mgl_write_gif(gr, fname, descr); }
/// Write the frame in file using OBJ format
inline void WriteOBJ(const char *fname,const char *descr="",bool use_png=true)
{ mgl_write_obj(gr, fname, descr, use_png); }
/// Write the frame in file using OBJ format - Balakin way
inline void WriteOBJold(const char *fname,const char *descr="",bool use_png=true)
{ mgl_write_obj_old(gr, fname, descr, use_png); }
/// Write the frame in file using XYZ format
inline void WriteXYZ(const char *fname,const char *descr="")
{ mgl_write_xyz(gr, fname, descr); }
/// Write the frame in file using STL format (faces only)
inline void WriteSTL(const char *fname,const char *descr="")
{ mgl_write_stl(gr, fname, descr); }
/// Write the frame in file using OFF format
inline void WriteOFF(const char *fname,const char *descr="", bool colored=false)
{ mgl_write_off(gr, fname, descr,colored); }
// /// Write the frame in file using X3D format
// inline void WriteX3D(const char *fname,const char *descr="")
// { mgl_write_x3d(gr, fname, descr); }
/// Write the frame in file using PRC format
inline void WritePRC(const char *fname,const char *descr="",bool make_pdf=true)
{ mgl_write_prc(gr, fname, descr, make_pdf); }
/// Export in JSON format suitable for later drawing by JavaScript
inline void WriteJSON(const char *fname,const char *descr="",bool force_z=false)
{ if(force_z) mgl_write_json_z(gr, fname, descr);
else mgl_write_json(gr, fname, descr); }
/// Return string of JSON data suitable for later drawing by JavaScript
inline const char *GetJSON() { return mgl_get_json(gr); }
/// Force preparing the image. It can be useful for OpenGL mode mostly.
inline void Finish() { mgl_finish(gr); }
/// Create new frame.
inline void NewFrame() { mgl_new_frame(gr); }
/// Finish frame drawing
inline void EndFrame() { mgl_end_frame(gr); }
/// Get the number of created frames
inline int GetNumFrame() { return mgl_get_num_frame(gr); }
/// Reset frames counter (start it from zero)
inline void ResetFrames() { mgl_reset_frames(gr); }
/// Delete primitives for i-th frame (work if MGL_VECT_FRAME is set on)
inline void DelFrame(int i) { mgl_del_frame(gr, i); }
/// Get drawing data for i-th frame (work if MGL_VECT_FRAME is set on)
inline void GetFrame(int i) { mgl_get_frame(gr, i); }
/// Set drawing data for i-th frame (work if MGL_VECT_FRAME is set on). Work as EndFrame() but don't add frame to GIF image.
inline void SetFrame(int i) { mgl_set_frame(gr, i); }
/// Append drawing data from i-th frame (work if MGL_VECT_FRAME is set on)
inline void ShowFrame(int i){ mgl_show_frame(gr, i); }
/// Clear list of primitives for current drawing
inline void ClearFrame() { mgl_clear_frame(gr); }
/// Start write frames to cinema using GIF format
inline void StartGIF(const char *fname, int ms=100)
{ mgl_start_gif(gr, fname,ms); }
/// Stop writing cinema using GIF format
inline void CloseGIF() { mgl_close_gif(gr); }
/// Export points and primitives in file using MGLD format
inline void ExportMGLD(const char *fname, const char *descr=0)
{ mgl_export_mgld(gr, fname, descr); }
/// Import points and primitives from file using MGLD format
inline void ImportMGLD(const char *fname, bool add=false)
{ mgl_import_mgld(gr, fname, add); }
/// Copy RGB values into array which is allocated by user
inline bool GetRGB(char *imgdata, int imglen)
{
long w=mgl_get_width(gr), h=mgl_get_height(gr);
if(imglen>=3*w*h) memcpy(imgdata, mgl_get_rgb(gr),3*w*h);
return imglen>=3*w*h;
}
inline const unsigned char *GetRGB() { return mgl_get_rgb(gr); }
/// Copy RGBA values into array which is allocated by user
inline bool GetRGBA(char *imgdata, int imglen)
{
long w=mgl_get_width(gr), h=mgl_get_height(gr);
if(imglen>=4*w*h) memcpy(imgdata, mgl_get_rgba(gr),4*w*h);
return imglen>=4*w*h;
}
inline const unsigned char *GetRGBA() { return mgl_get_rgba(gr); }
/// Copy BGRN values into array which is allocated by user
inline bool GetBGRN(unsigned char *imgdata, int imglen)
{
long w=mgl_get_width(gr), h=mgl_get_height(gr), i;
const unsigned char *buf=mgl_get_rgb(gr);
if(imglen>=4*w*h) for(i=0;i<w*h;i++)
{
imgdata[4*i] = buf[3*i+2];
imgdata[4*i+1] = buf[3*i+1];
imgdata[4*i+2] = buf[3*i];
imgdata[4*i+3] = 255;
}
return imglen>=4*w*h;
}
/// Copy RGBA values of background image into array which is allocated by user
inline bool GetBackground(char *imgdata, int imglen)
{
long w=mgl_get_width(gr), h=mgl_get_height(gr);
if(imglen>=4*w*h) memcpy(imgdata, mgl_get_background(gr),4*w*h);
return imglen>=4*w*h;
}
inline const unsigned char *GetBackground() { return mgl_get_background(gr); }
/// Get width of the image
inline int GetWidth() { return mgl_get_width(gr); }
/// Get height of the image
inline int GetHeight() { return mgl_get_height(gr);}
/// Calculate 3D coordinate {x,y,z} for screen point {xs,ys}
inline mglPoint CalcXYZ(int xs, int ys)
{
mreal x,y,z;
mgl_calc_xyz(gr,xs,ys,&x,&y,&z);
return mglPoint(x,y,z);
}
/// Calculate screen point {xs,ys} for 3D coordinate {x,y,z}
inline mglPoint CalcScr(mglPoint p)
{
int xs,ys;
mgl_calc_scr(gr,p.x,p.y,p.z,&xs,&ys);
return mglPoint(xs,ys);
}
/// Set object/subplot id
inline void SetObjId(int id) { mgl_set_obj_id(gr,id); }
/// Get object id
inline int GetObjId(long x,long y) { return mgl_get_obj_id(gr,x,y); }
/// Get subplot id
inline int GetSplId(long x,long y) { return mgl_get_spl_id(gr,x,y); }
/// Check if {\a xs,\a ys} is close to active point with accuracy d, and return its position or -1
inline long IsActive(int xs, int ys, int d=1) { return mgl_is_active(gr,xs,ys,d); }
/// Combine plots from 2 canvases. Result will be saved into this
inline void Combine(const mglGraph *g) { mgl_combine_gr(gr,g->gr); }
/// Clear up the frame
inline void Clf(double r, double g, double b) { mgl_clf_rgb(gr, r, g, b); }
inline void Clf(const char *col) { mgl_clf_str(gr, col); }
inline void Clf(char col) { mgl_clf_chr(gr, col); }
inline void Clf() { mgl_clf(gr); }
/// Clear unused points and primitives. Useful only in combination with SetFaceNum().
inline void ClearUnused() { mgl_clear_unused(gr); }
/// Load background image
inline void LoadBackground(const char *fname, double alpha=1)
{ mgl_load_background(gr,fname,alpha); }
/// Force drawing the image and use it as background one
inline void Rasterize() { mgl_rasterize(gr); }
/// Draws the point (ball) at position {x,y,z} with color c
inline void Ball(mglPoint p, char c='r')
{ char s[3]={'.',c,0}; mgl_mark(gr, p.x, p.y, p.z, s); }
/// Draws the mark at position p
inline void Mark(mglPoint p, const char *mark)
{ mgl_mark(gr, p.x, p.y, p.z, mark); }
/// Draws the line between points by specified pen
inline void Line(mglPoint p1, mglPoint p2, const char *pen="B",int n=2)
{ mgl_line(gr, p1.x, p1.y, p1.z, p2.x, p2.y, p2.z, pen, n); }
/// Draws the spline curve between points by specified pen
inline void Curve(mglPoint p1, mglPoint d1, mglPoint p2, mglPoint d2, const char *pen="B", int n=100)
{ mgl_curve(gr, p1.x, p1.y, p1.z, d1.x, d1.y, d1.z, p2.x, p2.y, p2.z, d2.x, d2.y, d2.z, pen, n); }
/// Draws the 3d error box e for point p
inline void Error(mglPoint p, mglPoint e, const char *pen="k")
{ mgl_error_box(gr, p.x, p.y, p.z, e.x, e.y, e.z, pen); }
/// Draws the face between points with color stl (include interpolation up to 4 colors).
inline void Face(mglPoint p1, mglPoint p2, mglPoint p3, mglPoint p4, const char *stl="r")
{ mgl_face(gr, p1.x, p1.y, p1.z, p2.x, p2.y, p2.z, p3.x, p3.y, p3.z, p4.x, p4.y, p4.z, stl); }
/// Draws the face in y-z plane at point p with color stl (include interpolation up to 4 colors).
inline void FaceX(mglPoint p, double wy, double wz, const char *stl="w", double dx=0, double dy=0)
{ mgl_facex(gr, p.x, p.y, p.z, wy, wz, stl, dx, dy); }
/// Draws the face in x-z plane at point p with color stl (include interpolation up to 4 colors).
inline void FaceY(mglPoint p, double wx, double wz, const char *stl="w", double dx=0, double dy=0)
{ mgl_facey(gr, p.x, p.y, p.z, wx, wz, stl, dx, dy); }
/// Draws the face in x-y plane at point p with color stl (include interpolation up to 4 colors).
inline void FaceZ(mglPoint p, double wx, double wy, const char *stl="w", double dx=0, double dy=0)
{ mgl_facez(gr, p.x, p.y, p.z, wx, wy, stl, dx, dy); }
/// Draws the drop at point p in direction d with color col and radius r
inline void Drop(mglPoint p, mglPoint d, double r, const char *col="r", double shift=1, double ap=1)
{ mgl_drop(gr, p.x, p.y, p.z, d.x, d.y, d.z, r, col, shift, ap); }
/// Draws the sphere at point p with color col and radius r
inline void Sphere(mglPoint p, double r, const char *col="r")
{ mgl_sphere(gr, p.x, p.y, p.z, r, col); }
/// Draws the cone between points p1,p2 with radius r1,r2 and with style stl
inline void Cone(mglPoint p1, mglPoint p2, double r1, double r2=-1, const char *stl="r@")
{ mgl_cone(gr, p1.x, p1.y, p1.z, p2.x, p2.y, p2.z,r1,r2,stl); }
/// Draws the ellipse between points p1,p2 with color stl and width r
inline void Ellipse(mglPoint p1, mglPoint p2, double r, const char *stl="r")
{ mgl_ellipse(gr, p1.x, p1.y, p1.z, p2.x, p2.y, p2.z, r,stl); }
/// Draws the circle at point p with color stl and radius r
inline void Circle(mglPoint p, double r, const char *stl="r")
{ mgl_ellipse(gr, p.x, p.y, p.z, p.x, p.y, p.z, r,stl); }
/// Draws the rhomb between points p1,p2 with color stl and width r
inline void Rhomb(mglPoint p1, mglPoint p2, double r, const char *stl="r")
{ mgl_rhomb(gr, p1.x, p1.y, p1.z, p2.x, p2.y, p2.z, r,stl); }
/// Draws the polygon based on points p1,p2 with color stl
inline void Polygon(mglPoint p1, mglPoint p2, int n, const char *stl="r")
{ mgl_polygon(gr, p1.x, p1.y, p1.z, p2.x, p2.y, p2.z, n,stl); }
/// Draws the arc around axis pr with center at p0 and starting from p1, by color stl and angle a (in degrees)
inline void Arc(mglPoint p0, mglPoint pr, mglPoint p1, double a, const char *stl="r")
{ mgl_arc_ext(gr, p0.x,p0.y,p0.z, pr.x,pr.y,pr.z, p1.x,p1.y,p1.z, a,stl); }
/// Draws the arc around axis 'z' with center at p0 and starting from p1, by color stl and angle a (in degrees)
inline void Arc(mglPoint p0, mglPoint p1, double a, const char *stl="r")
{ mgl_arc_ext(gr, p0.x,p0.y,p0.z, 0,0,1, p1.x,p1.y,p0.z, a,stl); }
/// Draws bitmap (logo) which is stretched along whole axis range
inline void Logo(long w, long h, const unsigned char *rgba, bool smooth=false, const char *opt="")
{ mgl_logo(gr, w, h, rgba, smooth, opt); }
inline void Logo(const char *fname, bool smooth=false, const char *opt="")
{ mgl_logo_file(gr, fname, smooth, opt); }
/// Print text in position p with specified font
inline void Putsw(mglPoint p,const wchar_t *text,const char *font=":C",double size=-1)
{ mgl_putsw(gr, p.x, p.y, p.z, text, font, size); }
inline void Puts(mglPoint p,const char *text,const char *font=":C",double size=-1)
{ mgl_puts(gr, p.x, p.y, p.z, text, font, size); }
inline void Putsw(double x, double y,const wchar_t *text,const char *font=":AC",double size=-1)
{ mgl_putsw(gr, x, y, 0, text, font, size); }
inline void Puts(double x, double y,const char *text,const char *font=":AC",double size=-1)
{ mgl_puts(gr, x, y, 0, text, font, size); }
/// Print text in position p along direction d with specified font
inline void Putsw(mglPoint p, mglPoint d, const wchar_t *text, const char *font=":L", double size=-1)
{ mgl_putsw_dir(gr, p.x, p.y, p.z, d.x, d.y, d.z, text, font, size); }
inline void Puts(mglPoint p, mglPoint d, const char *text, const char *font=":L", double size=-1)
{ mgl_puts_dir(gr, p.x, p.y, p.z, d.x, d.y, d.z, text, font, size); }
/// Print text along the curve
inline void Text(const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *text, const char *font="", const char *opt="")
{ mgl_text_xyz(gr, &x, &y, &z, text, font, opt); }
inline void Text(const mglDataA &x, const mglDataA &y, const char *text, const char *font="", const char *opt="")
{ mgl_text_xy(gr, &x, &y, text, font, opt); }
inline void Text(const mglDataA &y, const char *text, const char *font="", const char *opt="")
{ mgl_text_y(gr, &y, text, font, opt); }
inline void Text(const mglDataA &x, const mglDataA &y, const mglDataA &z, const wchar_t *text, const char *font="", const char *opt="")
{ mgl_textw_xyz(gr, &x, &y, &z, text, font, opt); }
inline void Text(const mglDataA &x, const mglDataA &y, const wchar_t *text, const char *font="", const char *opt="")
{ mgl_textw_xy(gr, &x, &y, text, font, opt); }
inline void Text(const mglDataA &y, const wchar_t *text, const char *font="", const char *opt="")
{ mgl_textw_y(gr, &y, text, font, opt); }
/// Draws bounding box outside the plotting volume with color c.
inline void Box(const char *col="", bool ticks=true)
{ mgl_box_str(gr, col, ticks); }
/// Draw axises with ticks in direction(s) dir.
inline void Axis(const char *dir="xyzt", const char *stl="", const char *opt="")
{ mgl_axis(gr, dir,stl,opt); }
/// Draw grid lines perpendicular to direction(s) dir.
inline void Grid(const char *dir="xyzt",const char *pen="B", const char *opt="")
{ mgl_axis_grid(gr, dir, pen, opt); }
/// Print the label text for axis dir.
inline void Label(char dir, const char *text, double pos=+1, const char *opt="")
{ mgl_label(gr, dir, text, pos, opt); }
inline void Label(char dir, const wchar_t *text, double pos=+1, const char *opt="")
{ mgl_labelw(gr, dir, text, pos, opt); }
/// Draw colorbar at edge of axis
inline void Colorbar(const char *sch="")
{ mgl_colorbar(gr, sch); }
inline void Colorbar(const char *sch,double x,double y,double w=1,double h=1)
{ mgl_colorbar_ext(gr, sch, x,y,w,h); }
/// Draw colorbar with manual colors at edge of axis
inline void Colorbar(const mglDataA &val, const char *sch="")
{ mgl_colorbar_val(gr, &val, sch); }
inline void Colorbar(const mglDataA &val, const char *sch,double x,double y,double w=1,double h=1)
{ mgl_colorbar_val_ext(gr, &val, sch, x,y,w,h); }
/// Add string to legend
inline void AddLegend(const char *text,const char *style)
{ mgl_add_legend(gr, text, style); }
inline void AddLegend(const wchar_t *text,const char *style)
{ mgl_add_legendw(gr, text, style); }
/// Clear saved legend string
inline void ClearLegend()
{ mgl_clear_legend(gr); }
/// Draw legend of accumulated strings at position {x,y}
inline void Legend(double x, double y, const char *font="#", const char *opt="")
{ mgl_legend_pos(gr, x, y, font, opt); }
/// Draw legend of accumulated strings
inline void Legend(int where=3, const char *font="#", const char *opt="")
{ mgl_legend(gr, where, font, opt); }
/// Set number of marks in legend sample
inline void SetLegendMarks(int num) { mgl_set_legend_marks(gr, num); }
/// Draw usual curve {x,y,z}
inline void Plot(const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *pen="", const char *opt="")
{ mgl_plot_xyz(gr, &x, &y, &z, pen, opt); }
inline void Plot(const mglDataA &x, const mglDataA &y, const char *pen="", const char *opt="")
{ mgl_plot_xy(gr, &x, &y, pen,opt); }
inline void Plot(const mglDataA &y, const char *pen="", const char *opt="")
{ mgl_plot(gr, &y, pen,opt); }
/// Draw tape(s) which rotates as (bi-)normales of curve {x,y,z}
inline void Tape(const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *pen="", const char *opt="")
{ mgl_tape_xyz(gr, &x, &y, &z, pen, opt); }
inline void Tape(const mglDataA &x, const mglDataA &y, const char *pen="", const char *opt="")
{ mgl_tape_xy(gr, &x, &y, pen,opt); }
inline void Tape(const mglDataA &y, const char *pen="", const char *opt="")
{ mgl_tape(gr, &y, pen,opt); }
/// Draw radar chart (plot in curved coordinates)
inline void Radar(const mglDataA &a, const char *pen="", const char *opt="")
{ mgl_radar(gr, &a, pen, opt); }
/// Draw stairs for points in arrays {x,y,z}
inline void Step(const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *pen="", const char *opt="")
{ mgl_step_xyz(gr, &x, &y, &z, pen, opt); }
inline void Step(const mglDataA &x, const mglDataA &y, const char *pen="", const char *opt="")
{ mgl_step_xy(gr, &x, &y, pen, opt); }
inline void Step(const mglDataA &y, const char *pen="", const char *opt="")
{ mgl_step(gr, &y, pen, opt); }
/// Draw curve {x,y,z} which is colored by c (like tension plot)
inline void Tens(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &c, const char *pen="", const char *opt="")
{ mgl_tens_xyz(gr, &x, &y, &z, &c, pen, opt); }
inline void Tens(const mglDataA &x, const mglDataA &y, const mglDataA &c, const char *pen="", const char *opt="")
{ mgl_tens_xy(gr, &x, &y, &c, pen, opt); }
inline void Tens(const mglDataA &y, const mglDataA &c, const char *pen="", const char *opt="")
{ mgl_tens(gr, &y, &c, pen, opt); }
/// Fill area between curve {x,y,z} and axis plane
inline void Area(const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *pen="", const char *opt="")
{ mgl_area_xyz(gr, &x, &y, &z, pen, opt); }
inline void Area(const mglDataA &x, const mglDataA &y, const char *pen="", const char *opt="")
{ mgl_area_xy(gr, &x, &y, pen, opt); }
inline void Area(const mglDataA &y, const char *pen="", const char *opt="")
{ mgl_area(gr, &y, pen, opt); }
/// Fill area between curves y1 and y2 specified parametrically
inline void Region(const mglDataA &y1, const mglDataA &y2, const char *pen="", const char *opt="")
{ mgl_region(gr, &y1, &y2, pen, opt); }
inline void Region(const mglDataA &x, const mglDataA &y1, const mglDataA &y2, const char *pen="", const char *opt="")
{ mgl_region_xy(gr, &x, &y1, &y2, pen, opt); }
/// Fill area (draw ribbon) between curves {x1,y1,z1} and {x2,y2,z2}
inline void Region(const mglDataA &x1, const mglDataA &y1, const mglDataA &z1, const mglDataA &x2, const mglDataA &y2, const mglDataA &z2, const char *pen="", const char *opt="")
{ mgl_region_3d(gr, &x1, &y1, &z1, &x2, &y2, &z2, pen, opt); }
inline void Region(const mglDataA &x1, const mglDataA &y1, const mglDataA &x2, const mglDataA &y2, const char *pen="", const char *opt="")
{ mgl_region_3d(gr, &x1, &y1, NULL, &x2, &y2, NULL, pen, opt); }
/// Draw vertical lines from points {x,y,z} to axis plane
inline void Stem(const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *pen="", const char *opt="")
{ mgl_stem_xyz(gr, &x, &y, &z, pen, opt); }
inline void Stem(const mglDataA &x, const mglDataA &y, const char *pen="", const char *opt="")
{ mgl_stem_xy(gr, &x, &y, pen, opt); }
inline void Stem(const mglDataA &y, const char *pen="", const char *opt="")
{ mgl_stem(gr, &y, pen, opt); }
/// Draw vertical bars from points {x,y,z} to axis plane
inline void Bars(const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *pen="", const char *opt="")
{ mgl_bars_xyz(gr, &x, &y, &z, pen, opt); }
inline void Bars(const mglDataA &x, const mglDataA &y, const char *pen="", const char *opt="")
{ mgl_bars_xy(gr, &x, &y, pen, opt); }
inline void Bars(const mglDataA &y, const char *pen="", const char *opt="")
{ mgl_bars(gr, &y, pen, opt); }
/// Draw horizontal bars from points {x,y} to axis plane
inline void Barh(const mglDataA &y, const mglDataA &v, const char *pen="", const char *opt="")
{ mgl_barh_yx(gr, &y, &v, pen, opt); }
inline void Barh(const mglDataA &v, const char *pen="", const char *opt="")
{ mgl_barh(gr, &v, pen, opt); }
/// Draw chart for data a
inline void Chart(const mglDataA &a, const char *colors="", const char *opt="")
{ mgl_chart(gr, &a, colors,opt); }
/// Draw Open-High-Low-Close (OHLC) diagram
inline void OHLC(const mglDataA &x, const mglDataA &open, const mglDataA &high, const mglDataA &low, const mglDataA &close, const char *pen="", const char *opt="")
{ mgl_ohlc_x(gr, &x, &open,&high,&low,&close,pen,opt); }
inline void OHLC(const mglDataA &open, const mglDataA &high, const mglDataA &low, const mglDataA &close, const char *pen="", const char *opt="")
{ mgl_ohlc(gr, &open,&high,&low,&close,pen,opt); }
/// Draw box-plot (special 5-value plot used in statistic)
inline void BoxPlot(const mglDataA &x, const mglDataA &y, const char *pen="", const char *opt="")
{ mgl_boxplot_xy(gr, &x, &y, pen,opt); }
inline void BoxPlot(const mglDataA &y, const char *pen="", const char *opt="")
{ mgl_boxplot(gr, &y, pen,opt); }
/// Draw candle plot
inline void Candle(const mglDataA &x, const mglDataA &v1, const mglDataA &v2, const mglDataA &y1, const mglDataA &y2, const char *pen="", const char *opt="")
{ mgl_candle_xyv(gr, &x, &v1, &v2, &y1, &y2, pen, opt); }
inline void Candle(const mglDataA &v1, const mglDataA &v2, const mglDataA &y1, const mglDataA &y2, const char *pen="", const char *opt="")
{ mgl_candle_yv(gr, &v1, &v2, &y1, &y2, pen, opt); }
inline void Candle(const mglDataA &v1, const mglDataA &v2, const char *pen="", const char *opt="")
{ mgl_candle_yv(gr, &v1, &v2, NULL, NULL, pen, opt); }
inline void Candle(const mglDataA &y, const mglDataA &y1, const mglDataA &y2, const char *pen="", const char *opt="")
{ mgl_candle(gr, &y, &y1, &y2, pen, opt); }
inline void Candle(const mglDataA &y, const char *pen="", const char *opt="")
{ mgl_candle(gr, &y, NULL, NULL, pen, opt); }
/// Draw cones from points {x,y,z} to axis plane
inline void Cones(const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *pen="@", const char *opt="")
{ mgl_cones_xyz(gr, &x, &y, &z, pen, opt); }
inline void Cones(const mglDataA &x, const mglDataA &z, const char *pen="@", const char *opt="")
{ mgl_cones_xz(gr, &x, &z, pen, opt); }
inline void Cones(const mglDataA &z, const char *pen="@", const char *opt="")
{ mgl_cones(gr, &z, pen, opt); }
/// Draw error boxes {ex,ey} at points {x,y}
inline void Error(const mglDataA &y, const mglDataA &ey, const char *pen="", const char *opt="")
{ mgl_error(gr, &y, &ey, pen, opt); }
inline void Error(const mglDataA &x, const mglDataA &y, const mglDataA &ey, const char *pen="", const char *opt="")
{ mgl_error_xy(gr, &x, &y, &ey, pen, opt); }
inline void Error(const mglDataA &x, const mglDataA &y, const mglDataA &ex, const mglDataA &ey, const char *pen="", const char *opt="")
{ mgl_error_exy(gr, &x, &y, &ex, &ey, pen, opt); }
/// Draw marks with size r at points {x,y,z}
inline void Mark(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &r, const char *pen, const char *opt="")
{ mgl_mark_xyz(gr, &x, &y, &z, &r, pen, opt); }
inline void Mark(const mglDataA &x, const mglDataA &y, const mglDataA &r, const char *pen, const char *opt="")
{ mgl_mark_xy(gr, &x, &y, &r, pen, opt); }
inline void Mark(const mglDataA &y, const mglDataA &r, const char *pen, const char *opt="")
{ mgl_mark_y(gr, &y, &r, pen, opt); }
/// Draw textual marks with size r at points {x,y,z}
inline void TextMark(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &r, const char *text, const char *fnt="", const char *opt="")
{ mgl_textmark_xyzr(gr, &x, &y, &z, &r, text, fnt, opt); }
inline void TextMark(const mglDataA &x, const mglDataA &y, const mglDataA &r, const char *text, const char *fnt="", const char *opt="")
{ mgl_textmark_xyr(gr, &x, &y, &r, text, fnt, opt); }
inline void TextMark(const mglDataA &y, const mglDataA &r, const char *text, const char *fnt="", const char *opt="")
{ mgl_textmark_yr(gr, &y, &r, text, fnt, opt); }
inline void TextMark(const mglDataA &y, const char *text, const char *fnt="", const char *opt="")
{ mgl_textmark(gr, &y, text, fnt, opt); }
inline void TextMark(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &r, const wchar_t *text, const char *fnt="", const char *opt="")
{ mgl_textmarkw_xyzr(gr, &x, &y, &z, &r, text, fnt, opt); }
inline void TextMark(const mglDataA &x, const mglDataA &y, const mglDataA &r, const wchar_t *text, const char *fnt="", const char *opt="")
{ mgl_textmarkw_xyr(gr, &x, &y, &r, text, fnt, opt); }
inline void TextMark(const mglDataA &y, const mglDataA &r, const wchar_t *text, const char *fnt="", const char *opt="")
{ mgl_textmarkw_yr(gr, &y, &r, text, fnt, opt); }
inline void TextMark(const mglDataA &y, const wchar_t *text, const char *fnt="", const char *opt="")
{ mgl_textmarkw(gr, &y, text, fnt, opt); }
/// Draw labels for points coordinate(s) at points {x,y,z}
inline void Label(const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *text, const char *fnt="", const char *opt="")
{ mgl_label_xyz(gr, &x, &y, &z, text, fnt, opt); }
inline void Label(const mglDataA &x, const mglDataA &y, const char *text, const char *fnt="", const char *opt="")
{ mgl_label_xy(gr, &x, &y, text, fnt, opt); }
inline void Label(const mglDataA &y, const char *text, const char *fnt="", const char *opt="")
{ mgl_label_y(gr, &y, text, fnt, opt); }
inline void Label(const mglDataA &x, const mglDataA &y, const mglDataA &z, const wchar_t *text, const char *fnt="", const char *opt="")
{ mgl_labelw_xyz(gr, &x, &y, &z, text, fnt, opt); }
inline void Label(const mglDataA &x, const mglDataA &y, const wchar_t *text, const char *fnt="", const char *opt="")
{ mgl_labelw_xy(gr, &x, &y, text, fnt, opt); }
inline void Label(const mglDataA &y, const wchar_t *text, const char *fnt="", const char *opt="")
{ mgl_labelw_y(gr, &y, text, fnt, opt); }
/// Draw table for values val along given direction with row labels text
inline void Table(const mglDataA &val, const char *text, const char *fnt="#|", const char *opt="")
{ mgl_table(gr, 0, 0, &val, text, fnt, opt); }
inline void Table(const mglDataA &val, const wchar_t *text, const char *fnt="#|", const char *opt="")
{ mgl_tablew(gr, 0, 0, &val, text, fnt, opt); }
/// Draw table for values val along given direction with row labels text at given position
inline void Table(double x, double y, const mglDataA &val, const char *text, const char *fnt="#|", const char *opt="")
{ mgl_table(gr, x, y, &val, text, fnt, opt); }
inline void Table(double x, double y, const mglDataA &val, const wchar_t *text, const char *fnt="#|", const char *opt="")
{ mgl_tablew(gr, x, y, &val, text, fnt, opt); }
/// Draw tube with radius r around curve {x,y,z}
inline void Tube(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &r, const char *pen="", const char *opt="")
{ mgl_tube_xyzr(gr, &x, &y, &z, &r, pen, opt); }
inline void Tube(const mglDataA &x, const mglDataA &y, const mglDataA &z, double r, const char *pen="", const char *opt="")
{ mgl_tube_xyz(gr, &x, &y, &z, r, pen, opt); }
inline void Tube(const mglDataA &x, const mglDataA &y, const mglDataA &r, const char *pen="", const char *opt="")
{ mgl_tube_xyr(gr, &x, &y, &r, pen, opt); }
inline void Tube(const mglDataA &x, const mglDataA &y, double r, const char *pen="", const char *opt="")
{ mgl_tube_xy(gr, &x, &y, r, pen, opt); }
inline void Tube(const mglDataA &y, const mglDataA &r, const char *pen="", const char *opt="")
{ mgl_tube_r(gr, &y, &r, pen, opt); }
inline void Tube(const mglDataA &y, double r, const char *pen="", const char *opt="")
{ mgl_tube(gr, &y, r, pen, opt); }
/// Draw surface of curve {r,z} rotatation around axis
inline void Torus(const mglDataA &r, const mglDataA &z, const char *pen="", const char *opt="")
{ mgl_torus(gr, &r, &z, pen,opt); }
/// Draw mesh lines for 2d data specified parametrically
inline void Mesh(const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *stl="", const char *opt="")
{ mgl_mesh_xy(gr, &x, &y, &z, stl, opt); }
inline void Mesh(const mglDataA &z, const char *stl="", const char *opt="")
{ mgl_mesh(gr, &z, stl, opt); }
/// Draw mesh lines for 2d data specified parametrically
inline void Fall(const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *stl="", const char *opt="")
{ mgl_fall_xy(gr, &x, &y, &z, stl, opt); }
inline void Fall(const mglDataA &z, const char *stl="", const char *opt="")
{ mgl_fall(gr, &z, stl, opt); }
/// Draw belts for 2d data specified parametrically
inline void Belt(const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *stl="", const char *opt="")
{ mgl_belt_xy(gr, &x, &y, &z, stl, opt); }
inline void Belt(const mglDataA &z, const char *stl="", const char *opt="")
{ mgl_belt(gr, &z, stl, opt); }
/// Draw surface for 2d data specified parametrically with color proportional to z
inline void Surf(const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *stl="", const char *opt="")
{ mgl_surf_xy(gr, &x, &y, &z, stl, opt); }
inline void Surf(const mglDataA &z, const char *stl="", const char *opt="")
{ mgl_surf(gr, &z, stl, opt); }
/// Draw grid lines for density plot of 2d data specified parametrically
inline void Grid(const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *stl="", const char *opt="")
{ mgl_grid_xy(gr, &x, &y, &z, stl, opt); }
inline void Grid(const mglDataA &z, const char *stl="", const char *opt="")
{ mgl_grid(gr, &z, stl, opt); }
/// Draw vertical tiles for 2d data specified parametrically
inline void Tile(const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *stl="", const char *opt="")
{ mgl_tile_xy(gr, &x, &y, &z, stl, opt); }
inline void Tile(const mglDataA &z, const char *stl="", const char *opt="")
{ mgl_tile(gr, &z, stl, opt); }
/// Draw density plot for 2d data specified parametrically
inline void Dens(const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *stl="", const char *opt="")
{ mgl_dens_xy(gr, &x, &y, &z, stl, opt); }
inline void Dens(const mglDataA &z, const char *stl="", const char *opt="")
{ mgl_dens(gr, &z, stl, opt); }
/// Draw vertical boxes for 2d data specified parametrically
inline void Boxs(const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *stl="", const char *opt="")
{ mgl_boxs_xy(gr, &x, &y, &z, stl, opt); }
inline void Boxs(const mglDataA &z, const char *stl="", const char *opt="")
{ mgl_boxs(gr, &z, stl, opt); }
/// Draw contour lines for 2d data specified parametrically
inline void Cont(const mglDataA &v, const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *sch="", const char *opt="")
{ mgl_cont_xy_val(gr, &v, &x, &y, &z, sch, opt); }
inline void Cont(const mglDataA &v, const mglDataA &z, const char *sch="", const char *opt="")
{ mgl_cont_val(gr, &v, &z, sch, opt); }
inline void Cont(const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *sch="", const char *opt="")
{ mgl_cont_xy(gr, &x, &y, &z, sch, opt); }
inline void Cont(const mglDataA &z, const char *sch="", const char *opt="")
{ mgl_cont(gr, &z, sch, opt); }
/// Draw solid contours for 2d data specified parametrically
inline void ContF(const mglDataA &v, const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *sch="", const char *opt="")
{ mgl_contf_xy_val(gr, &v, &x, &y, &z, sch, opt); }
inline void ContF(const mglDataA &v, const mglDataA &z, const char *sch="", const char *opt="")
{ mgl_contf_val(gr, &v, &z, sch, opt); }
inline void ContF(const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *sch="", const char *opt="")
{ mgl_contf_xy(gr, &x, &y, &z, sch, opt); }
inline void ContF(const mglDataA &z, const char *sch="", const char *opt="")
{ mgl_contf(gr, &z, sch, opt); }
/// Draw solid contours for 2d data specified parametrically with manual colors
inline void ContD(const mglDataA &v, const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *sch="", const char *opt="")
{ mgl_contd_xy_val(gr, &v, &x, &y, &z, sch, opt); }
inline void ContD(const mglDataA &v, const mglDataA &z, const char *sch="", const char *opt="")
{ mgl_contd_val(gr, &v, &z, sch, opt); }
inline void ContD(const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *sch="", const char *opt="")
{ mgl_contd_xy(gr, &x, &y, &z, sch, opt); }
inline void ContD(const mglDataA &z, const char *sch="", const char *opt="")
{ mgl_contd(gr, &z, sch, opt); }
/// Draw contour tubes for 2d data specified parametrically
inline void ContV(const mglDataA &v, const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *sch="", const char *opt="")
{ mgl_contv_xy_val(gr, &v, &x, &y, &z, sch, opt); }
inline void ContV(const mglDataA &v, const mglDataA &z, const char *sch="", const char *opt="")
{ mgl_contv_val(gr, &v, &z, sch, opt); }
inline void ContV(const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *sch="", const char *opt="")
{ mgl_contv_xy(gr, &x, &y, &z, sch, opt); }
inline void ContV(const mglDataA &z, const char *sch="", const char *opt="")
{ mgl_contv(gr, &z, sch, opt); }
/// Draw axial-symmetric isosurfaces for 2d data specified parametrically
inline void Axial(const mglDataA &v, const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *sch="", const char *opt="")
{ mgl_axial_xy_val(gr, &v, &x, &y, &z, sch,opt); }
inline void Axial(const mglDataA &v, const mglDataA &z, const char *sch="", const char *opt="")
{ mgl_axial_val(gr, &v, &z, sch, opt); }
inline void Axial(const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *sch="", const char *opt="")
{ mgl_axial_xy(gr, &x, &y, &z, sch, opt); }
inline void Axial(const mglDataA &z, const char *sch="", const char *opt="")
{ mgl_axial(gr, &z, sch, opt); }
/// Draw grid lines for density plot at slice for 3d data specified parametrically
inline void Grid3(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &a, const char *stl="", double sVal=-1, const char *opt="")
{ mgl_grid3_xyz(gr, &x, &y, &z, &a, stl, sVal, opt); }
inline void Grid3(const mglDataA &a, const char *stl="", double sVal=-1, const char *opt="")
{ mgl_grid3(gr, &a, stl, sVal, opt); }
/// Draw density plot at slice for 3d data specified parametrically
inline void Dens3(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &a, const char *stl="", double sVal=-1, const char *opt="")
{ mgl_dens3_xyz(gr, &x, &y, &z, &a, stl, sVal, opt); }
inline void Dens3(const mglDataA &a, const char *stl="", double sVal=-1, const char *opt="")
{ mgl_dens3(gr, &a, stl, sVal, opt); }
/// Draw isosurface(s) for 3d data specified parametrically
inline void Surf3(double Val, const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &a, const char *stl="", const char *opt="")
{ mgl_surf3_xyz_val(gr, Val, &x, &y, &z, &a, stl, opt); }
inline void Surf3(double Val, const mglDataA &a, const char *stl="", const char *opt="")
{ mgl_surf3_val(gr, Val, &a, stl, opt); }
inline void Surf3(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &a, const char *stl="", const char *opt="")
{ mgl_surf3_xyz(gr, &x, &y, &z, &a, stl, opt); }
inline void Surf3(const mglDataA &a, const char *stl="", const char *opt="")
{ mgl_surf3(gr, &a, stl, opt); }
/// Draw a semi-transparent cloud for 3d data
inline void Cloud(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &a, const char *stl="", const char *opt="")
{ mgl_cloud_xyz(gr, &x, &y, &z, &a, stl, opt); }
inline void Cloud(const mglDataA &a, const char *stl="", const char *opt="")
{ mgl_cloud(gr, &a, stl, opt); }
/// Draw contour lines at slice for 3d data specified parametrically
inline void Cont3(const mglDataA &v, const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &a, const char *sch="", double sVal=-1, const char *opt="")
{ mgl_cont3_xyz_val(gr, &v, &x, &y, &z, &a, sch, sVal, opt); }
inline void Cont3(const mglDataA &v, const mglDataA &a, const char *sch="", double sVal=-1, const char *opt="")
{ mgl_cont3_val(gr, &v, &a, sch, sVal, opt); }
inline void Cont3(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &a, const char *sch="", double sVal=-1, const char *opt="")
{ mgl_cont3_xyz(gr, &x, &y, &z, &a, sch, sVal, opt); }
inline void Cont3(const mglDataA &a, const char *sch="", double sVal=-1, const char *opt="")
{ mgl_cont3(gr, &a, sch, sVal, opt); }
/// Draw solid contours at slice for 3d data specified parametrically
inline void ContF3(const mglDataA &v, const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &a, const char *sch="", double sVal=-1, const char *opt="")
{ mgl_contf3_xyz_val(gr, &v, &x, &y, &z, &a, sch, sVal, opt); }
inline void ContF3(const mglDataA &v, const mglDataA &a, const char *sch="", double sVal=-1, const char *opt="")
{ mgl_contf3_val(gr, &v, &a, sch, sVal, opt); }
inline void ContF3(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &a, const char *sch="", double sVal=-1, const char *opt="")
{ mgl_contf3_xyz(gr, &x, &y, &z, &a, sch, sVal, opt); }
inline void ContF3(const mglDataA &a, const char *sch="", double sVal=-1, const char *opt="")
{ mgl_contf3(gr, &a, sch, sVal, opt); }
/// Draw several isosurfaces for 3d beam in curvilinear coordinates
inline void Beam(const mglDataA &tr, const mglDataA &g1, const mglDataA &g2, const mglDataA &a, double r, const char *stl=0, int flag=0, int num=3)
{ mgl_beam(gr, &tr,&g1,&g2,&a,r,stl,flag,num); }
inline void Beam(double val, const mglDataA &tr, const mglDataA &g1, const mglDataA &g2, const mglDataA &a, double r, const char *stl=NULL, int flag=0)
{ mgl_beam_val(gr,val,&tr,&g1,&g2,&a,r,stl,flag); }
/// Draw vertical tiles with variable size r for 2d data specified parametrically
inline void TileS(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &r, const char *stl="", const char *opt="")
{ mgl_tiles_xy(gr, &x, &y, &z, &r, stl, opt); }
inline void TileS(const mglDataA &z, const mglDataA &r, const char *stl="", const char *opt="")
{ mgl_tiles(gr, &z, &r, stl, opt); }
/// Draw surface for 2d data specified parametrically with color proportional to c
inline void SurfC(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &c, const char *sch="", const char *opt="")
{ mgl_surfc_xy(gr, &x, &y, &z, &c, sch,opt); }
inline void SurfC(const mglDataA &z, const mglDataA &c, const char *sch="", const char *opt="")
{ mgl_surfc(gr, &z, &c, sch,opt); }
/// Draw surface for 2d data specified parametrically with alpha proportional to c
inline void SurfA(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &c, const char *sch="", const char *opt="")
{ mgl_surfa_xy(gr, &x, &y, &z, &c, sch,opt); }
inline void SurfA(const mglDataA &z, const mglDataA &c, const char *sch="", const char *opt="")
{ mgl_surfa(gr, &z, &c, sch,opt); }
/// Color map of matrix a to matrix b, both matrix can parametrically depend on coordinates
inline void Map(const mglDataA &x, const mglDataA &y, const mglDataA &a, const mglDataA &b, const char *sch="", const char *opt="")
{ mgl_map_xy(gr, &x, &y, &a, &b, sch, opt); }
inline void Map(const mglDataA &a, const mglDataA &b, const char *sch="", const char *opt="")
{ mgl_map(gr, &a, &b, sch, opt); }
/// Draw density plot for spectra-gramm specified parametrically
inline void STFA(const mglDataA &x, const mglDataA &y, const mglDataA &re, const mglDataA &im, int dn, const char *sch="", const char *opt="")
{ mgl_stfa_xy(gr, &x, &y, &re, &im, dn, sch, opt); }
inline void STFA(const mglDataA &re, const mglDataA &im, int dn, const char *sch="", const char *opt="")
{ mgl_stfa(gr, &re, &im, dn, sch, opt); }
/// Draw isosurface(s) for 3d data specified parametrically with alpha proportional to b
inline void Surf3A(double Val, const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &a, const mglDataA &b, const char *stl="", const char *opt="")
{ mgl_surf3a_xyz_val(gr, Val, &x, &y, &z, &a, &b, stl, opt); }
inline void Surf3A(double Val, const mglDataA &a, const mglDataA &b, const char *stl="", const char *opt="")
{ mgl_surf3a_val(gr, Val, &a, &b, stl, opt); }
inline void Surf3A(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &a, const mglDataA &b, const char *stl="", const char *opt="")
{ mgl_surf3a_xyz(gr, &x, &y, &z, &a, &b, stl, opt); }
inline void Surf3A(const mglDataA &a, const mglDataA &b, const char *stl="", const char *opt="")
{ mgl_surf3a(gr, &a, &b, stl, opt); }
/// Draw isosurface(s) for 3d data specified parametrically with color proportional to b
inline void Surf3C(double Val, const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &a, const mglDataA &b, const char *stl="", const char *opt="")
{ mgl_surf3c_xyz_val(gr, Val, &x, &y, &z, &a, &b, stl,opt); }
inline void Surf3C(double Val, const mglDataA &a, const mglDataA &b, const char *stl="", const char *opt="")
{ mgl_surf3c_val(gr, Val, &a, &b, stl, opt); }
inline void Surf3C(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &a, const mglDataA &b, const char *stl="", const char *opt="")
{ mgl_surf3c_xyz(gr, &x, &y, &z, &a, &b, stl, opt); }
inline void Surf3C(const mglDataA &a, const mglDataA &b, const char *stl="", const char *opt="")
{ mgl_surf3c(gr, &a, &b, stl, opt); }
/// Plot dew drops for vector field {ax,ay} parametrically depended on coordinate {x,y}
inline void Dew(const mglDataA &x, const mglDataA &y, const mglDataA &ax, const mglDataA &ay, const char *sch="", const char *opt="")
{ mgl_dew_xy(gr, &x, &y, &ax, &ay, sch, opt); }
inline void Dew(const mglDataA &ax, const mglDataA &ay, const char *sch="", const char *opt="")
{ mgl_dew_2d(gr, &ax, &ay, sch, opt); }
/// Plot vectors at position {x,y,z} along {ax,ay,az} with length/color proportional to |a|
inline void Traj(const mglDataA &x, const mglDataA &y, const mglDataA &ax, const mglDataA &ay, const char *sch="", const char *opt="")
{ mgl_traj_xy(gr, &x, &y, &ax, &ay, sch, opt); }
inline void Traj(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &ax, const mglDataA &ay, const mglDataA &az, const char *sch="", const char *opt="")
{ mgl_traj_xyz(gr, &x, &y, &z, &ax, &ay, &az, sch, opt); }
/// Plot vector field {ax,ay,az} parametrically depended on coordinate {x,y,z} with length/color proportional to |a|
inline void Vect(const mglDataA &x, const mglDataA &y, const mglDataA &ax, const mglDataA &ay, const char *sch="", const char *opt="")
{ mgl_vect_xy(gr, &x, &y, &ax, &ay, sch, opt); }
inline void Vect(const mglDataA &ax, const mglDataA &ay, const char *sch="", const char *opt="")
{ mgl_vect_2d(gr, &ax, &ay, sch, opt); }
inline void Vect(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &ax, const mglDataA &ay, const mglDataA &az, const char *sch="", const char *opt="")
{ mgl_vect_xyz(gr, &x, &y, &z, &ax, &ay, &az, sch, opt); }
inline void Vect(const mglDataA &ax, const mglDataA &ay, const mglDataA &az, const char *sch="", const char *opt="")
{ mgl_vect_3d(gr, &ax, &ay, &az, sch, opt); }
/// Draw vector plot at slice for 3d data specified parametrically
inline void Vect3(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &ax, const mglDataA &ay, const mglDataA &az, const char *stl="", double sVal=-1, const char *opt="")
{ mgl_vect3_xyz(gr, &x, &y, &z, &ax,&ay,&az, stl, sVal, opt); }
inline void Vect3(const mglDataA &ax, const mglDataA &ay, const mglDataA &az, const char *stl="", double sVal=-1, const char *opt="")
{ mgl_vect3(gr, &ax,&ay,&az, stl, sVal, opt); }
/// Plot flows for vector field {ax,ay,az} parametrically depended on coordinate {x,y,z} with color proportional to |a|
inline void Flow(const mglDataA &x, const mglDataA &y, const mglDataA &ax, const mglDataA &ay, const char *sch="", const char *opt="")
{ mgl_flow_xy(gr, &x, &y, &ax, &ay, sch, opt); }
inline void Flow(const mglDataA &ax, const mglDataA &ay, const char *sch="", const char *opt="")
{ mgl_flow_2d(gr, &ax, &ay, sch, opt); }
inline void Flow(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &ax, const mglDataA &ay, const mglDataA &az, const char *sch="", const char *opt="")
{ mgl_flow_xyz(gr, &x, &y, &z, &ax, &ay, &az, sch, opt); }
inline void Flow(const mglDataA &ax, const mglDataA &ay, const mglDataA &az, const char *sch="", const char *opt="")
{ mgl_flow_3d(gr, &ax, &ay, &az, sch, opt); }
/// Plot flow from point p for vector field {ax,ay,az} parametrically depended on coordinate {x,y,z} with color proportional to |a|
inline void FlowP(mglPoint p, const mglDataA &x, const mglDataA &y, const mglDataA &ax, const mglDataA &ay, const char *sch="", const char *opt="")
{ mgl_flowp_xy(gr, p.x, p.y, p.z, &x, &y, &ax, &ay, sch, opt); }
inline void FlowP(mglPoint p, const mglDataA &ax, const mglDataA &ay, const char *sch="", const char *opt="")
{ mgl_flowp_2d(gr, p.x, p.y, p.z, &ax, &ay, sch, opt); }
inline void FlowP(mglPoint p, const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &ax, const mglDataA &ay, const mglDataA &az, const char *sch="", const char *opt="")
{ mgl_flowp_xyz(gr, p.x, p.y, p.z, &x, &y, &z, &ax, &ay, &az, sch, opt); }
inline void FlowP(mglPoint p, const mglDataA &ax, const mglDataA &ay, const mglDataA &az, const char *sch="", const char *opt="")
{ mgl_flowp_3d(gr, p.x, p.y, p.z, &ax, &ay, &az, sch, opt); }
/// Plot flows for gradient of scalar field phi parametrically depended on coordinate {x,y,z}
inline void Grad(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &phi, const char *sch="", const char *opt="")
{ mgl_grad_xyz(gr,&x,&y,&z,&phi,sch,opt); }
inline void Grad(const mglDataA &x, const mglDataA &y, const mglDataA &phi, const char *sch="", const char *opt="")
{ mgl_grad_xy(gr,&x,&y,&phi,sch,opt); }
inline void Grad(const mglDataA &phi, const char *sch="", const char *opt="")
{ mgl_grad(gr,&phi,sch,opt); }
/// Plot flow pipes for vector field {ax,ay,az} parametrically depended on coordinate {x,y,z} with color and radius proportional to |a|
inline void Pipe(const mglDataA &x, const mglDataA &y, const mglDataA &ax, const mglDataA &ay, const char *sch="", double r0=0.05, const char *opt="")
{ mgl_pipe_xy(gr, &x, &y, &ax, &ay, sch, r0, opt); }
inline void Pipe(const mglDataA &ax, const mglDataA &ay, const char *sch="", double r0=0.05, const char *opt="")
{ mgl_pipe_2d(gr, &ax, &ay, sch, r0, opt); }
inline void Pipe(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &ax, const mglDataA &ay, const mglDataA &az, const char *sch="", double r0=0.05, const char *opt="")
{ mgl_pipe_xyz(gr, &x, &y, &z, &ax, &ay, &az, sch, r0, opt); }
inline void Pipe(const mglDataA &ax, const mglDataA &ay, const mglDataA &az, const char *sch="", double r0=0.05, const char *opt="")
{ mgl_pipe_3d(gr, &ax, &ay, &az, sch, r0, opt); }
/// Draw density plot for data at x = sVal
inline void DensX(const mglDataA &a, const char *stl="", double sVal=mglNaN, const char *opt="")
{ mgl_dens_x(gr, &a, stl, sVal, opt); }
/// Draw density plot for data at y = sVal
inline void DensY(const mglDataA &a, const char *stl="", double sVal=mglNaN, const char *opt="")
{ mgl_dens_y(gr, &a, stl, sVal, opt); }
/// Draw density plot for data at z = sVal
inline void DensZ(const mglDataA &a, const char *stl="", double sVal=mglNaN, const char *opt="")
{ mgl_dens_z(gr, &a, stl, sVal, opt); }
/// Draw contour lines for data at x = sVal
inline void ContX(const mglDataA &a, const char *stl="", double sVal=mglNaN, const char *opt="")
{ mgl_cont_x(gr, &a, stl, sVal, opt); }
inline void ContX(const mglDataA &v, const mglDataA &a, const char *stl="", double sVal=mglNaN, const char *opt="")
{ mgl_cont_x_val(gr, &v, &a, stl, sVal, opt); }
/// Draw contour lines for data at y = sVal
inline void ContY(const mglDataA &a, const char *stl="", double sVal=mglNaN, const char *opt="")
{ mgl_cont_y(gr, &a, stl, sVal, opt); }
inline void ContY(const mglDataA &v, const mglDataA &a, const char *stl="", double sVal=mglNaN, const char *opt="")
{ mgl_cont_y_val(gr, &v, &a, stl, sVal, opt); }
/// Draw contour lines for data at z = sVal
inline void ContZ(const mglDataA &a, const char *stl="", double sVal=mglNaN, const char *opt="")
{ mgl_cont_z(gr, &a, stl, sVal, opt); }
inline void ContZ(const mglDataA &v, const mglDataA &a, const char *stl="", double sVal=mglNaN, const char *opt="")
{ mgl_cont_z_val(gr, &v, &a, stl, sVal, opt); }
/// Draw solid contours for data at x = sVal
inline void ContFX(const mglDataA &a, const char *stl="", double sVal=mglNaN, const char *opt="")
{ mgl_contf_x(gr, &a, stl, sVal, opt); }
inline void ContFX(const mglDataA &v, const mglDataA &a, const char *stl="", double sVal=mglNaN, const char *opt="")
{ mgl_contf_x_val(gr, &v, &a, stl, sVal, opt); }
/// Draw solid contours for data at y = sVal
inline void ContFY(const mglDataA &a, const char *stl="", double sVal=mglNaN, const char *opt="")
{ mgl_contf_y(gr, &a, stl, sVal, opt); }
inline void ContFY(const mglDataA &v, const mglDataA &a, const char *stl="", double sVal=mglNaN, const char *opt="")
{ mgl_contf_y_val(gr, &v, &a, stl, sVal, opt); }
/// Draw solid contours for data at z = sVal
inline void ContFZ(const mglDataA &a, const char *stl="", double sVal=mglNaN, const char *opt="")
{ mgl_contf_z(gr, &a, stl, sVal, opt); }
inline void ContFZ(const mglDataA &v, const mglDataA &a, const char *stl="", double sVal=mglNaN, const char *opt="")
{ mgl_contf_z_val(gr, &v, &a, stl, sVal, opt); }
/// Draw curve for formula with x in x-axis range
inline void FPlot(const char *fy, const char *stl="", const char *opt="")
{ mgl_fplot(gr, fy, stl, opt); }
/// Draw curve for formulas parametrically depended on t in range [0,1]
inline void FPlot(const char *fx, const char *fy, const char *fz, const char *stl, const char *opt="")
{ mgl_fplot_xyz(gr, fx, fy, fz, stl, opt); }
/// Draw surface by formula with x,y in axis range
inline void FSurf(const char *fz, const char *stl="", const char *opt="")
{ mgl_fsurf(gr, fz, stl, opt); }
/// Draw surface by formulas parametrically depended on u,v in range [0,1]
inline void FSurf(const char *fx, const char *fy, const char *fz, const char *stl, const char *opt="")
{ mgl_fsurf_xyz(gr, fx, fy, fz, stl, opt); }
/// Draw triangle mesh for points in arrays {x,y,z} with specified color c.
inline void TriPlot(const mglDataA &nums, const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &c, const char *sch="", const char *opt="")
{ mgl_triplot_xyzc(gr, &nums, &x, &y, &z, &c, sch, opt); }
inline void TriPlot(const mglDataA &nums, const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *sch="", const char *opt="")
{ mgl_triplot_xyz(gr, &nums, &x, &y, &z, sch, opt); }
inline void TriPlot(const mglDataA &nums, const mglDataA &x, const mglDataA &y, const char *sch="", const char *opt="")
{ mgl_triplot_xy(gr, &nums, &x, &y, sch, opt); }
/// Draw quad mesh for points in arrays {x,y,z} with specified color c.
inline void QuadPlot(const mglDataA &nums, const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &c, const char *sch="", const char *opt="")
{ mgl_quadplot_xyzc(gr, &nums, &x, &y, &z, &c, sch, opt); }
inline void QuadPlot(const mglDataA &nums, const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *sch="", const char *opt="")
{ mgl_quadplot_xyz(gr, &nums, &x, &y, &z, sch, opt); }
inline void QuadPlot(const mglDataA &nums, const mglDataA &x, const mglDataA &y, const char *sch="", const char *opt="")
{ mgl_quadplot_xy(gr, &nums, &x, &y, sch, opt); }
/// Draw contour lines for triangle mesh for points in arrays {x,y,z} with specified color c.
inline void TriCont(const mglDataA &nums, const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *sch="", const char *opt="")
{ mgl_tricont_xyc(gr, &nums, &x, &y, &z, sch, opt); }
inline void TriContV(const mglDataA &v, const mglDataA &nums, const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *sch="", const char *opt="")
{ mgl_tricont_xycv(gr, &v, &nums, &x, &y, &z, sch, opt); }
inline void TriCont(const mglDataA &nums, const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &a, const char *sch="", const char *opt="")
{ mgl_tricont_xyzc(gr, &nums, &x, &y, &z, &a, sch, opt); }
inline void TriContV(const mglDataA &v, const mglDataA &nums, const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &a, const char *sch="", const char *opt="")
{ mgl_tricont_xyzcv(gr, &v, &nums, &x, &y, &z, &a, sch, opt); }
inline void TriCont(const mglDataA &v, const mglDataA &nums, const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &a, const char *sch="", const char *opt="")
{ mgl_tricont_xyzcv(gr, &v, &nums, &x, &y, &z, &a, sch, opt); }
/// Draw contour tubes for triangle mesh for points in arrays {x,y,z} with specified color c.
inline void TriContVt(const mglDataA &nums, const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *sch="", const char *opt="")
{ mgl_tricontv_xyc(gr, &nums, &x, &y, &z, sch, opt); }
inline void TriContVt(const mglDataA &nums, const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &a, const char *sch="", const char *opt="")
{ mgl_tricontv_xyzc(gr, &nums, &x, &y, &z, &a, sch, opt); }
inline void TriContVt(const mglDataA &v, const mglDataA &nums, const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &a, const char *sch="", const char *opt="")
{ mgl_tricontv_xyzcv(gr, &v, &nums, &x, &y, &z, &a, sch, opt); }
/// Draw dots in points {x,y,z}.
inline void Dots(const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *sch="", const char *opt="")
{ mgl_dots(gr, &x, &y, &z, sch, opt); }
/// Draw semitransparent dots in points {x,y,z} with specified alpha a.
inline void Dots(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &a, const char *sch="", const char *opt="")
{ mgl_dots_a(gr, &x, &y, &z, &a, sch, opt); }
/// Draw semitransparent dots in points {x,y,z} with specified color c and alpha a.
inline void Dots(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &c, const mglDataA &a, const char *sch="", const char *opt="")
{ mgl_dots_ca(gr, &x, &y, &z, &c, &a, sch, opt); }
/// Draw surface reconstructed for points in arrays {x,y,z}.
inline void Crust(const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *sch="", const char *opt="")
{ mgl_crust(gr, &x, &y, &z, sch, opt); }
/// Fit data along x-direction for each data row. Return array with values for found formula.
inline mglData Fit(const mglDataA &y, const char *eq, const char *vars, const char *opt="")
{ return mglData(true,mgl_fit_1(gr, &y, eq,vars,0, opt)); }
inline mglData Fit(const mglDataA &y, const char *eq, const char *vars, mglData &ini, const char *opt="")
{ return mglData(true,mgl_fit_1(gr, &y, eq, vars, &ini, opt)); }
/// Fit data along x-, y-directions for each data slice. Return array with values for found formula.
inline mglData Fit2(const mglDataA &z, const char *eq, const char *vars, const char *opt="")
{ return mglData(true,mgl_fit_2(gr, &z, eq, vars,0, opt)); }
inline mglData Fit2(const mglDataA &z, const char *eq, const char *vars, mglData &ini, const char *opt="")
{ return mglData(true,mgl_fit_2(gr, &z, eq, vars, &ini, opt)); }
/// Fit data along along all directions. Return array with values for found formula.
inline mglData Fit3(const mglDataA &a, const char *eq, const char *vars, const char *opt="")
{ return mglData(true,mgl_fit_3(gr, &a, eq, vars,0, opt)); }
inline mglData Fit3(const mglDataA &a, const char *eq, const char *vars, mglData &ini, const char *opt="")
{ return mglData(true,mgl_fit_3(gr, &a, eq, vars, &ini, opt)); }
/// Fit data along x-direction for each data row. Return array with values for found formula.
inline mglData Fit(const mglDataA &x, const mglDataA &y, const char *eq, const char *vars, const char *opt="")
{ return mglData(true,mgl_fit_xy(gr, &x, &y, eq, vars,0, opt)); }
inline mglData Fit(const mglDataA &x, const mglDataA &y, const char *eq, const char *vars, mglData &ini, const char *opt="")
{ return mglData(true,mgl_fit_xy(gr, &x, &y, eq, vars, &ini, opt)); }
/// Fit data along x-, y-directions for each data slice. Return array with values for found formula.
inline mglData Fit(const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *eq, const char *vars, const char *opt="")
{ return mglData(true,mgl_fit_xyz(gr, &x, &y, &z, eq, vars,0, opt)); }
inline mglData Fit(const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *eq, const char *vars, mglData &ini, const char *opt="")
{ return mglData(true,mgl_fit_xyz(gr, &x, &y, &z, eq, vars, &ini, opt)); }
/// Fit data along along all directions. Return array with values for found formula.
inline mglData Fit(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &a, const char *eq, const char *vars, const char *opt="")
{ return mglData(true,mgl_fit_xyza(gr, &x, &y, &z, &a, eq, vars,0, opt)); }
inline mglData Fit(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &a, const char *eq, const char *vars, mglData &ini, const char *opt="")
{ return mglData(true,mgl_fit_xyza(gr, &x, &y, &z, &a, eq,vars, &ini, opt)); }
/// Fit data with dispersion s along x-direction for each data row. Return array with values for found formula.
inline mglData FitS(const mglDataA &y, const mglDataA &s, const char *eq, const char *vars, const char *opt="")
{ return mglData(true,mgl_fit_ys(gr, &y, &s, eq, vars,0, opt)); }
inline mglData FitS(const mglDataA &y, const mglDataA &s, const char *eq, const char *vars, mglData &ini, const char *opt="")
{ return mglData(true,mgl_fit_ys(gr, &y, &s, eq, vars, &ini, opt)); }
inline mglData FitS(const mglDataA &x, const mglDataA &y, const mglDataA &s, const char *eq, const char *vars, const char *opt="")
{ return mglData(true,mgl_fit_xys(gr, &x, &y, &s, eq, vars,0, opt)); }
inline mglData FitS(const mglDataA &x, const mglDataA &y, const mglDataA &s, const char *eq, const char *vars, mglData &ini, const char *opt="")
{ return mglData(true,mgl_fit_xys(gr, &x, &y, &s, eq, vars, &ini, opt)); }
/// Fit data with dispersion s along x-, y-directions for each data slice. Return array with values for found formula.
inline mglData FitS(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &s, const char *eq, const char *vars, const char *opt="")
{ return mglData(true,mgl_fit_xyzs(gr, &x, &y, &z, &s, eq, vars,0, opt)); }
inline mglData FitS(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &s, const char *eq, const char *vars, mglData &ini, const char *opt="")
{ return mglData(true,mgl_fit_xyzs(gr, &x, &y, &z, &s, eq, vars, &ini, opt)); }
/// Fit data with dispersion s along all directions. Return array with values for found formula.
inline mglData FitS(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &a, const mglDataA &s, const char *eq, const char *vars, const char *opt="")
{ return mglData(true,mgl_fit_xyzas(gr, &x, &y, &z, &a, &s, eq, vars,0, opt)); }
inline mglData FitS(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &a, const mglDataA &s, const char *eq, const char *vars, mglData &ini, const char *opt="")
{ return mglData(true,mgl_fit_xyzas(gr, &x, &y, &z, &a, &s, eq, vars, &ini, opt)); }
/// Print fitted last formula (with coefficients)
inline void PutsFit(mglPoint p, const char *prefix=0, const char *font="", double size=-1)
{ mgl_puts_fit(gr, p.x, p.y, p.z, prefix, font, size); }
/// Get last fitted formula
inline const char *GetFit() const
{ return mgl_get_fit(gr); }
/// Get chi for last fitted formula
static inline mreal GetFitChi()
{ return mgl_get_fit_chi(); }
/// Solve PDE with x,y,z in range [Min, Max]
inline mglData PDE(const char *ham, const mglDataA &ini_re, const mglDataA &ini_im, double dz=0.1, double k0=100, const char *opt="")
{ return mglData(true,mgl_pde_solve(gr,ham,&ini_re,&ini_im,dz,k0, opt)); }
/// Fill data by formula with x,y,z in range [Min, Max]
inline void Fill(mglData &u, const char *eq, const char *opt="")
{ mgl_data_fill_eq(gr, &u, eq, 0, 0, opt); }
inline void Fill(mglData &u, const char *eq, const mglDataA &v, const char *opt="")
{ mgl_data_fill_eq(gr, &u, eq, &v, 0, opt); }
inline void Fill(mglData &u, const char *eq, const mglDataA &v, const mglDataA &w, const char *opt="")
{ mgl_data_fill_eq(gr, &u, eq, &v, &w, opt); }
/// Fill data by formula with x,y,z in range [Min, Max]
inline void Fill(mglDataC &u, const char *eq, const char *opt="")
{ mgl_datac_fill_eq(gr, &u, eq, 0, 0, opt); }
inline void Fill(mglDataC &u, const char *eq, const mglDataA &v, const char *opt="")
{ mgl_datac_fill_eq(gr, &u, eq, &v, 0, opt); }
inline void Fill(mglDataC &u, const char *eq, const mglDataA &v, const mglDataA &w, const char *opt="")
{ mgl_datac_fill_eq(gr, &u, eq, &v, &w, opt); }
/// Fill dat by interpolated values of vdat parametrically depended on xdat,ydat,zdat for x,y,z in axis range
inline void Refill(mglData &dat, const mglDataA &xdat, const mglDataA &vdat, long sl=-1, const char *opt="")
{ mgl_data_refill_gr(gr,&dat,&xdat,0,0,&vdat,sl,opt); }
inline void Refill(mglData &dat, const mglDataA &xdat, const mglDataA &ydat, const mglDataA &vdat, long sl=-1, const char *opt="")
{ mgl_data_refill_gr(gr,&dat,&xdat,&ydat,0,&vdat,sl,opt); }
inline void Refill(mglData &dat, const mglDataA &xdat, const mglDataA &ydat, const mglDataA &zdat, const mglDataA &vdat, const char *opt="")
{ mgl_data_refill_gr(gr,&dat,&xdat,&ydat,&zdat,&vdat,-1,opt); }
/// Set the data by triangulated surface values assuming x,y,z in range [Min, Max]
inline void DataGrid(mglData &d, const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *opt="")
{ mgl_data_grid(gr,&d,&x,&y,&z,opt); }
/// Make histogram (distribution) of data. This function do not plot data.
inline mglData Hist(const mglDataA &x, const mglDataA &a, const char *opt="")
{ return mglData(true, mgl_hist_x(gr, &x, &a, opt)); }
inline mglData Hist(const mglDataA &x, const mglDataA &y, const mglDataA &a, const char *opt="")
{ return mglData(true, mgl_hist_xy(gr, &x, &y, &a, opt)); }
inline mglData Hist(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &a, const char *opt="")
{ return mglData(true, mgl_hist_xyz(gr, &x, &y, &z, &a, opt)); }
inline void Compression(bool){} // NOTE: Add later -- IDTF
/// Set the preference for vertex color on/off (for formats that support it, now only PRC does).
inline void VertexColor(bool enable) { mgl_set_flag(gr,enable, MGL_PREFERVC); }
/// Render only front side of surfaces for dubugging purposes (for formats that support it, now only PRC does).
inline void DoubleSided(bool enable) { mgl_set_flag(gr,!enable, MGL_ONESIDED); }
// inline void TextureColor(bool){} // NOTE: Add later -- IDTF
};
//-----------------------------------------------------------------------------
/// Wrapper class for MGL parsing
class MGL_EXPORT mglParse
{
HMPR pr;
public:
mglParse(HMPR p) { pr = p; mgl_use_parser(pr,1); }
mglParse(mglParse &p) { pr = p.pr; mgl_use_parser(pr,1); }
mglParse(bool setsize=false)
{ pr=mgl_create_parser(); mgl_parser_allow_setsize(pr, setsize); }
virtual ~mglParse()
{
#pragma omp critical
if(mgl_use_parser(pr,-1)<1) mgl_delete_parser(pr);
}
/// Get pointer to internal mglParser object
inline HMPR Self() { return pr; }
/// Parse and draw single line of the MGL script
inline int Parse(mglGraph *gr, const char *str, int pos)
{ return mgl_parse_line(gr->Self(), pr, str, pos); }
inline int Parse(mglGraph *gr, const wchar_t *str, int pos)
{ return mgl_parse_linew(gr->Self(), pr, str, pos); }
/// Execute MGL script text with '\n' separated lines
inline void Execute(mglGraph *gr, const char *str)
{ mgl_parse_text(gr->Self(), pr, str); }
inline void Execute(mglGraph *gr, const wchar_t *str)
{ mgl_parse_textw(gr->Self(), pr, str); }
/// Execute and draw script from the file
inline void Execute(mglGraph *gr, FILE *fp, bool print=false)
{ mgl_parse_file(gr->Self(), pr, fp, print); }
/// Return type of command: 0 - not found, 1 - other data plot, 2 - func plot,
/// 3 - setup, 4 - data handle, 5 - data create, 6 - subplot, 7 - program
/// 8 - 1d plot, 9 - 2d plot, 10 - 3d plot, 11 - dd plot, 12 - vector plot
/// 13 - axis, 14 - primitives, 15 - axis setup, 16 - text/legend, 17 - data transform
inline int CmdType(const char *name)
{ return mgl_parser_cmd_type(pr, name); }
/// Return string of command format (command name and its argument[s])
inline const char *CmdFormat(const char *name)
{ return mgl_parser_cmd_frmt(pr, name); }
/// Return description of MGL command
inline const char *CmdDesc(const char *name)
{ return mgl_parser_cmd_desc(pr, name); }
/// Get name of command with nmber n
inline const char *GetCmdName(long n)
{ return mgl_parser_cmd_name(pr,n); }
/// Get number of defined commands
inline long GetCmdNum()
{ return mgl_parser_cmd_num(pr); }
/// Load new commands from external dynamic Library (must have "const mglCommand *mgl_cmd_extra" variable)
inline void LoadDLL(const char *fname)
{ mgl_parser_load(pr, fname); }
/// Set value for parameter $N
inline void AddParam(int id, const char *str)
{ mgl_parser_add_param(pr, id, str); }
inline void AddParam(int id, const wchar_t *str)
{ mgl_parser_add_paramw(pr, id, str); }
/// Restore once flag
inline void RestoreOnce() { mgl_parser_restore_once(pr); }
/// Allow changing size of the picture
inline void AllowSetSize(bool allow) { mgl_parser_allow_setsize(pr, allow); }
/// Allow reading/saving files
inline void AllowFileIO(bool allow) { mgl_parser_allow_file_io(pr, allow); }
/// Allow loading commands from external libraries
inline void AllowDllCall(bool allow) { mgl_parser_allow_dll_call(pr, allow); }
/// Set flag to stop script parsing
inline void Stop() { mgl_parser_stop(pr); }
/// Return result of formula evaluation
inline mglData Calc(const char *formula)
{ return mglData(true,mgl_parser_calc(pr,formula)); }
inline mglData Calc(const wchar_t *formula)
{ return mglData(true,mgl_parser_calcw(pr,formula)); }
/// Find variable with given name or add a new one
/// NOTE !!! You must not delete obtained data arrays !!!
inline mglData *AddVar(const char *name)
{ return mgl_parser_add_var(pr, name); }
inline mglData *AddVar(const wchar_t *name)
{ return mgl_parser_add_varw(pr, name); }
/// Find variable with given name or return NULL if no one
/// NOTE !!! You must not delete obtained data arrays !!!
inline mglDataA *FindVar(const char *name)
{ return mgl_parser_find_var(pr, name); }
inline mglDataA *FindVar(const wchar_t *name)
{ return mgl_parser_find_varw(pr, name); }
/// Get variable with given id. Can be NULL for temporary ones.
/// NOTE !!! You must not delete obtained data arrays !!!
inline mglDataA *GetVar(unsigned long id)
{ return mgl_parser_get_var(pr,id); }
/// Get number of variables
inline long GetNumVar()
{ return mgl_parser_num_var(pr); }
/// Delete variable with name
inline void DeleteVar(const char *name) { mgl_parser_del_var(pr, name); }
inline void DeleteVar(const wchar_t *name) { mgl_parser_del_varw(pr, name); }
/// Delete all data variables
void DeleteAll() { mgl_parser_del_all(pr); }
};
//-----------------------------------------------------------------------------
#endif
#endif
|
a7.c | #include "omp.h"
void axpy(int N, float *Y, float *X, float a) {
int i;
#pragma omp declare target to(X)
#pragma omp parallel for
for (i = 0; i < N; ++i)
Y[i] += a * X[i];
}
|
DRB053-inneronly1-orig-no.c | /*
Copyright (C) 1991-2018 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it andor
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 Unicode 10.0.0. Version 10.0 of the Unicode Standard is
synchronized with ISOIEC 10646:2017, fifth edition, plus
the following additions from Amendment 1 to the fifth edition:
- 56 emoji characters
- 285 hentaigana
- 3 additional Zanabazar Square characters
*/
/*
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.comLLNL/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.
*/
/*
Example with loop-carried data dependence at the outer level loop.
But the inner level loop can be parallelized.
*/
#include <string.h>
int main(int argc, char * argv[])
{
int i;
int j;
double a[20][20];
int _ret_val_0;
memset(a, 0, sizeof a);
#pragma cetus private(i, j)
#pragma loop name main#0
#pragma cetus parallel
#pragma omp parallel for private(i, j)
for (i=0; i<20; i+=1)
{
#pragma cetus private(j)
#pragma loop name main#0#0
#pragma cetus parallel
#pragma omp parallel for private(j)
for (j=0; j<20; j+=1)
{
a[i][j]+=((i+j)+0.1);
}
}
#pragma cetus private(i, j)
#pragma loop name main#1
for (i=0; i<(20-1); i+=1)
{
#pragma cetus private(j)
#pragma loop name main#1#0
#pragma cetus parallel
#pragma omp parallel for private(j)
for (j=0; j<20; j+=1)
{
a[i][j]+=a[i+1][j];
}
}
#pragma cetus private(i, j)
#pragma loop name main#2
for (i=0; i<20; i+=1)
{
#pragma cetus private(j)
#pragma loop name main#2#0
for (j=0; j<20; j+=1)
{
printf("%lf\n", a[i][j]);
}
}
_ret_val_0=0;
return _ret_val_0;
}
|
agilekeychain_fmt_plug.c | /* 1Password Agile Keychain cracker patch for JtR. Hacked together during
* July of 2012 by Dhiru Kholia <dhiru.kholia at gmail.com>.
*
* This software is Copyright (c) 2012, Dhiru Kholia <dhiru.kholia at gmail.com>,
* and it is hereby released to the general public under the following terms:
* Redistribution and use in source and binary forms, with or without
* modification, are permitted.
*
* This software is based on "agilekeychain" project but no actual code is
* borrowed from it.
*
* "agilekeychain" project is at https://bitbucket.org/gwik/agilekeychain
*/
#if FMT_EXTERNS_H
extern struct fmt_main fmt_agile_keychain;
#elif FMT_REGISTERS_H
john_register_one(&fmt_agile_keychain);
#else
#include <string.h>
#include <errno.h>
#ifdef _OPENMP
#include <omp.h>
#ifndef OMP_SCALE
#define OMP_SCALE 1 // tuned on core i7
#endif
#endif
#include "arch.h"
#include "misc.h"
#include "common.h"
#include "formats.h"
#include "params.h"
#include "johnswap.h"
#include "options.h"
#include "pbkdf2_hmac_sha1.h"
#include "aes.h"
#include "jumbo.h"
#include "memdbg.h"
#define FORMAT_LABEL "agilekeychain"
#define FORMAT_NAME "1Password Agile Keychain"
#ifdef SIMD_COEF_32
#define ALGORITHM_NAME "PBKDF2-SHA1 AES " SHA1_ALGORITHM_NAME
#else
#define ALGORITHM_NAME "PBKDF2-SHA1 AES 32/" ARCH_BITS_STR
#endif
#define BENCHMARK_COMMENT ""
#define BENCHMARK_LENGTH -1
#define BINARY_SIZE 0
#define BINARY_ALIGN 1
#define SALT_ALIGN sizeof(int)
#define PLAINTEXT_LENGTH 125
#define SALT_SIZE sizeof(struct custom_salt)
#ifdef SIMD_COEF_32
#define MIN_KEYS_PER_CRYPT SSE_GROUP_SZ_SHA1
#define MAX_KEYS_PER_CRYPT SSE_GROUP_SZ_SHA1
#else
#define MIN_KEYS_PER_CRYPT 1
#define MAX_KEYS_PER_CRYPT 1
#endif
#define SALTLEN 8
#define IVLEN 8
#define CTLEN 1040
static struct fmt_tests agile_keychain_tests[] = {
{"$agilekeychain$2*1000*8*7146eaa1cca395e5*1040*e7eb81496717d35f12b83024bb055dec00ea82843886cbb8d0d77302a85d89b1d2c0b5b8275dca44c168cba310344be6eea3a79d559d0846a9501f4a012d32b655047673ef66215fc2eb4e944a9856130ee7cd44523017bbbe2957e6a81d1fd128434e7b83b49b8a014a3e413a1d76b109746468070f03f19d361a21c712ef88e05b04f8359f6dd96c1c4487ea2c9df22ea9029e9bc8406d37850a5ead03062283a42218c134d05ba40cddfe46799c931291ec238ee4c11dc71d2b7e018617d4a2bf95a0c3c1f98ea14f886d94ee2a65871418c7c237f1fe52d3e176f8ddab6dfd4bc039b6af36ab1bc9981689c391e71703e31979f732110b84d5fccccf59c918dfcf848fcd80c6da62ced6e231497b9cbef22d5edca439888556bae5e7b05571ac34ea54fafc03fb93e4bc17264e50a1d04b688fcc8bc715dd237086c2537c32de34bbb8a29de0208800af2a9b561551ae6561099beb61045f22dbe871fab5350e40577dd58b4c8fb1232f3f85b8d2e028e5535fd131988a5df4c0408929b8eac6d751dcc698aa1d79603251d90a216ae5e28bffc0610f61fefe0a23148dcc65ab88b117dd3b8d311157424867eb0261b8b8c5b11def85d434dd4c6dc7036822a279a77ec640b28da164bea7abf8b634ba0e4a13d9a31fdcfebbdbe53adcdf2564d656e64923f76bc2619428abdb0056ce20f47f3ece7d4d11dc55d2969684ca336725561cb27ce0504d57c88a2782daccefb7862b385d494ce70fef93d68e673b12a68ba5b8c93702be832d588ac935dbf0a7b332e42d1b6da5f87aed03498a37bb41fc78fcdbe8fe1f999fe756edf3a375beb54dd508ec45af07985f1430a105e552d9817106ae12d09906c4c28af575d270308a950d05c07da348f59571184088d46bbef3e7a2ad03713e90b435547b23f340f0f5d00149838d9919d40dac9b337920c7e577647fe4e2811f05b8e888e3211d9987cf922883aa6e53a756e579f7dff91c297fcc5cda7d10344545f64099cfd2f8fd59ee5c580ca97cf8b17e0222b764df25a2a52b81ee9db41b3c296fcea1203b367e55d321c3504aeda8913b0cae106ccf736991030088d581468264b8486968e868a44172ad904d97e3e52e8370aaf52732e6ee6cc46eb33a901afc6b7c687b8f6ce0b2b4cdfe19c7139615195a052051becf39383ab83699a383a26f8a36c78887fe27ea7588c0ea21a27357ff9923a3d23ca2fb04ad671b63f8a8ec9b7fc969d3bece0f5ff19a40bc327b9905a6de2193ffe3aa1997e9266205d083776e3b94869164abcdb88d64b8ee5465f7165b75e1632abd364a24bb1426889955b8f0354f75c6fb40e254f7de53d8ef7fee9644bf2ebccd934a72bb1cc9c19d354d66996acbddd60d1241657359d9074a4b313b21af2ee4f10cf20f4122a5fad4ee4f37a682ffb7234bea61985d1ad130bfb9f4714461fb574dbf851c*1000*8*c05f3bc3e7f3cad7*1040*f3e3d091b64da1529b04b2795898b717faad59f7dae4bda25e6e267c28a56a7702e51991b2a3fb034cdda2d9bfd531dfd2c3af00f39fdfe8bcbdde02ab790415bcf071d133b15f647f55ff512730ae4914ce20b72184c827f6350ac768b00c9eab0e3322e084bb3e9e9439a10030950f5504dcc4f7ba614b27fde99bd0d743a58341e90ec313395486eb8068df205b7bdf25134ed97dd2e2883d7eb3e63b659602ada765084a69d7ed8fc55b60aa67718cc9e5bf31ab8f3029b32a4b001071848d2b76b5f4b921d2169ca287e9e78ecd904d040c817c7c7cde4ba8510b462e139c16519962ca0adb7d5f89d431cd4541a9a7aaec8d799697f4d3947d87884bed32ada13db725c72ab6450ac8fe989a94917cca784bcf6ffbe756f19d4e8897e0f80d8c318e13e5b30fc356646aaf038a952b0781f12dfef1f4bd6922ae05a573eeff4dbb064cfbb0fd62962a6a53a8de308da2b8e83baebfe261cb127f874a5eff3f05cda123ab2ba559cf444ce33b6845f4c902733b8982044151a8aa1859769082ade5928f2d4f616ce972ae8dde1f2be37d496ad16057008dfe678c75cbdc53db25ed311edbcf8b2a73bcd2809f6bd1d389aaeed82a75fa15676d08aa5390efdc189c180be6a52ec5a7371304d26e477039197671377d1ea3d6ee41e68a42348a4fe9a1d2400eaeba8ed0a7419b9694d780456d96378c00318a5be0f41afa887476b3bebb7cf30d61ca8fc77de35671a3053a517aa39444e01e1752da3146dc97eec5849d6f025c3d4bc6e0499b901f629d8a081ad35ed33602cbef5e9a68f090170fcc1f285eb094e3dc619740a067fd2aeeb20abbb17926c3ad097f3f0bad4de540d1829a985cd7e700100622ec47da046071c11a1597e5f093268b4ed79ffcf2450b9ba2b649b932fbce912bdb4da010581bd9c731be792c8f75177f6c8c4e1756d63a1491a8aae4bb11beeca118e7d08073b500dd82b81e4bdbeb15625afca8f1c8e06b2360da972587516ef62e91d1d9aad90e62226d53363bff318f5af21f69c234731ac22b09506a1b807d2366e88905668d960c7963daa93046e9a56db1d7a437e9a37aa7a2945197265478b264ec14d383030ef73504fd26d4be9e72ebddb14a00bf6bd66a3adaa1d17cada378a2b0bc852f961af52333f7966f8a60738dfd47e79ce537082f187117ffd31f54f53356b671154dfa245671c4cd054c1a8d303a202fccfae6d3f9e3646838cef38703b5e660b5ce7679f5898d801908f90092dbec335c98e4002041287fe9bfa7d7828a29ab240ec2cedc9fa12cfd7c3ef7b61dad4fbf2ef9c0a904dbde1b3792fb5178607608dc9fc2fbc85addf89fa3df94317e729810b508356b5bb176cdb022afb0ec5eeff4d5081b66733d1be1b54cc4f080bfc33187663b5ab185472b35dc8812e201472e6af376c43ee23aa2db6cd04bddd79b99b0c28c48a5ae", "openwall"},
{"$agilekeychain$1*1000*8*54434b3047723444*1040*316539685a36617546544a61466e35743970356559624464304467394a4a41615459594a6b66454c5462417a7a694b5751474e4748595036344f3945374b414b676b6b7278673658794e63734a316c48656b496a3156346a544c6861797537347032466b4d6b416d31704a6b5063547a44703152544f72696e6e38347732597672774f6476414c70346462595a7678656b6e5958716b7a61746d5874514e575965564735627a437578584e4a573050567939413073306c377a4d726e6d576a6655424455394f4934696c48454f4d536e635567393950686d4171364f76747749446130454c6d74783069704d30456d45374f56736e486a5534667877327a526e52596e55454452393544437042646e6739355938714836584968664c4d7a726a4f63544c6858385141464c71565463664270493761664d633055447879613169456a72664479346438305641417054754775477a475266766c4774543668673848624d31636c37624e73743549634457655375507138535139396c4c39364c4f6f757a43305535586161364b47676a61713971394459526a78744e547459797a6a57715a3575534364487a4430306d4e4e39483277674c733238726463616d4f5146467957374234727252774b6d6161664b6d67414d5854496444665848684c376c6c776d47477a4b57566d5a3646346e775441446f3659745038646d336b6370494d50676742797a41325630716e794833793237494152496477556e4d6c4751497367346672635364486e6e71504f6e6264575953584462586c6e573947347a567163535333366e3253504d65656b45483841544f6952384d6170724471706c4a307863713653707265624f544a4d5139377562454a334b776e4879746a37704e37694557484d69696d436f484973613443754d484b4f51484833545a364654694a6d31783061665536796c444f7257666964397243444f684d305a324c6b75693953716664354b435963703559354978757a64354a755158394136663744435a674e4c73484a7935737a707739724c783077316631637349757a6d696252576244396a537730593143633348385a775734534b646569684f634f4c35323364734b7179625750364b76344a4a56626c4f727069366f575a386432745375684c464e42643173445a6a50745743696e666a4458325058644d57654c596d326f5763516a7951524a566372354d4d58435877765172596b734c59354476455156746d75504830444a4e47624e31524f4d544b4a6b4d675835305a7a56736758794c475057714e78496452725269484c75424f4d6d793550677277727453597045566e304c5642764c5a6732504c7a4e71584c4c67634979637369554a3446497655795a78583547306b365a4e337477786c7961796b4d787463796971596f516fcb3584235d7ecde5f8b7bc2b8f1e9e2e*46c3b75f6e4cf139e92f683f32107271", "123"},
{"$agilekeychain$1*1000*8*7a697868444e7458*1040*773954704874444d4d523043546b44375135544f74675a754532624a45794848305949436e4e724d336c524c39316247426a7843317131614152736d50724c6474586a4d4d445954786c31376d363155437130777a414d36586c7045555457424a5a436a657541456742417961654472745a73576e4b7a7a344d547043567846526655524b4339573631756f3850465a3878306b7176644c4253787071764c58376e716a50674f526d4a4e4b546e3359575175614b304a3964756f756935675a77544f4e6770654855776f79553465786e41364d6376496b7651624762424d62756746796a6753514c37793069783869683773454c533559365946584f545246616d48495730464e634d42466e51367856797a4368517335674a755972434b545944633270764e54775879563542776675386b6e4462506b743138694a756d63447134745361526a32373167366e787375514e346a73574e77796b4b49376d3677653448754c364b5a41514633626e71786130634458544e484a436551386e7679304b786d73346f774a383268665167596b466e39317a307269714434546d4d6173416e344b6a74455a584846526a6659746742504262495958386336755241386c496633417666696d7a5036425745757461736b684574794a5230436d50466d4b536375764674674562315679766a43453077356e614b476d345849395a726b7037626153496b6a66634f355261795157645941487731516f564c6764516d4e3074394b3839526341626f6b6b38324465497068624553646f4177786e6f68347779523338394f4e6561315271635236374d424d695978304b336b4a6966776e74614f4b43483237434b596a6630774e79394a4b7153714a48616b4b364455596a454b31433767786a72303450706d44666373574c5a61324f335852474b756c456b76483349754e3156654f417342324d6f75346d4b78774e43424863566e344c4c6c6c6d4e446b617550415a6f3337764f55484b4156344d4769336267344f4737794c354c5567636a565a6b7369616730383377744d69513431333032305a4a3747794944714d67396a5651444132424e79507a34726d346c333552757a764b6c543073437562534376714f346a5939784a546f683358517348623378716677313231383261685357743236455a6a6b6674365870554642386436574c374430635177347278736a744a6e463530756365684c7779497557366550356936514e704e4863353863437165397163496146794a726555714c623438543235396371416154326c66375276746e3550727453306b7042335961364239586c3359384b464865564e677636537234414e4d6c55583867456376686e43646e6e776a6f656d7152613453725148503462744b4a334565714f6e624a774a65623258552fff2bf0505a0bc88b9cbc9073a74586*a6f6556c971bd3ad40b52751ba025713", ""},
{"$agilekeychain$1*1000*8*7a65613743636950*1040*524a397449393859696b4a576e437763716a574947544a6d306e32474442343355764a7a6948517a45686d7569636631514745347448424e4e6b32564239656a55596f724671547638736d4e66783949504b6f38746b6f49426d4d6b794c7a6d3077327639365a4b515934357774664a477247366b5539486135495863766845714146317458356b725a6a50376f726e55734b3136533756706a4b42516165656a50336e4558616450794f59506f4771347268454730784555485a4f5a4772526a76354f45417470616258375a386436474b366f7653583257335939516d4f5364446a414b674e467a31374f716d73516b3362795776305a414a314f63324d616a6c6472413939443879414c523733794c47467654734d7a6a4734733461674353357a4456527841486233646d446e797448696837377364784344704831784f6a5975666168626b5534796678576c59584d4b3448704a784a4f675a6d7672636b5a4b567071445a345a376648624b55414b7262694972384531336c7a6875725a6f44627571775361774b66417743336230614e4166564954334a6c3477666b4254374f747565394b32667266566d3263416a656c79416c45724b3035504a4e42307a33303632483466664272705765415a4f3552416a36544e5a54415a5976666a4b53675a68493071394a6563426964544a4f564d304a773976394944444339516e564a78587539366974586c4f6132717937354c554b65384b7638585132596832417a5271314e4b5653766d4d50506d3554463762763961554e45695a51436e79504f6e7146617a755231373574455365305446624c636450424a43526a49384b32365967496a734c324e525574526e36714c533065694f536c6c37795a456945476d4a6e327262646942416c485046616e384e4d7869427571777355714e7638305267537752726245696c734d68664b53793836684b39445a716b47546d4b59747176474c6b6a6d52513368796b367a356449706c64385541614236546e426a6b4f64766d33493972763941765a71776345686b734c594a7254446c796f46444b6d557441305a636b414e437245587a63487a30304c50564e4e73694d634d5a6f4f74414534424f53685879374e62545734487a555054774a7056686f6a7453666a664e696d354548345631374c61396862586659666332304e465a5678656a304b4d59586d586547634d67474c6d31794a4b546473474c755a697579625779503259726d6d5248544f6f704b575046556e3438415a48474168396d787136327230367248774e73493439693049794b3765314b4f74547265556c564b6e6d594a5959355a7476334b546f75375a6a676c755a557a39744b54747745583948314a37366e6c6d5a53345079555856696438336876596141617a394438711ee66b990b013609582733309b01df00*444f4656a5ec58e8a75204fb25fd5ae5", "PASSWORD"},
{NULL}
};
static char (*saved_key)[PLAINTEXT_LENGTH + 1];
static int *cracked;
static struct custom_salt {
unsigned int nkeys;
unsigned int iterations[2];
unsigned int saltlen[2];
unsigned char salt[2][SALTLEN];
unsigned int ctlen[2];
unsigned char ct[2][CTLEN];
} *cur_salt;
static void init(struct fmt_main *self)
{
#if defined (_OPENMP)
int omp_t = 1;
omp_t = omp_get_max_threads();
self->params.min_keys_per_crypt *= omp_t;
omp_t *= OMP_SCALE;
self->params.max_keys_per_crypt *= omp_t;
#endif
saved_key = mem_calloc_align(sizeof(*saved_key),
self->params.max_keys_per_crypt, MEM_ALIGN_WORD);
cracked = mem_calloc_align(sizeof(*cracked),
self->params.max_keys_per_crypt, MEM_ALIGN_WORD);
}
static void done(void)
{
MEM_FREE(cracked);
MEM_FREE(saved_key);
}
static int valid(char *ciphertext, struct fmt_main *self)
{
char *ctcopy, *keeptr;
int ctlen;
int saltlen;
char *p;
if (strncmp(ciphertext, "$agilekeychain$", 15) != 0)
return 0;
/* handle 'chopped' .pot lines */
if (ldr_isa_pot_source(ciphertext))
return 1;
ctcopy = strdup(ciphertext);
keeptr = ctcopy;
ctcopy += 15;
if ((p = strtokm(ctcopy, "*")) == NULL) /* nkeys */
goto err;
if (!isdec(p))
goto err;
if (atoi(p) > 2)
goto err;
if ((p = strtokm(NULL, "*")) == NULL) /* iterations */
goto err;
if (!isdec(p))
goto err;
if ((p = strtokm(NULL, "*")) == NULL) /* salt length */
goto err;
if (!isdec(p))
goto err;
saltlen = atoi(p);
if(saltlen > SALTLEN)
goto err;
if ((p = strtokm(NULL, "*")) == NULL) /* salt */
goto err;
if(strlen(p) != saltlen * 2)
goto err;
if(!ishexlc(p))
goto err;
if ((p = strtokm(NULL, "*")) == NULL) /* ct length */
goto err;
if (!isdec(p))
goto err;
ctlen = atoi(p);
if (ctlen > CTLEN)
goto err;
if ((p = strtokm(NULL, "*")) == NULL) /* ciphertext */
goto err;
if(strlen(p) != ctlen * 2)
goto err;
if(!ishexlc(p))
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));
ctcopy += 15; /* skip over "$agilekeychain$" */
p = strtokm(ctcopy, "*");
cs.nkeys = atoi(p);
p = strtokm(NULL, "*");
cs.iterations[0] = atoi(p);
p = strtokm(NULL, "*");
cs.saltlen[0] = atoi(p);
p = strtokm(NULL, "*");
for (i = 0; i < cs.saltlen[0]; i++)
cs.salt[0][i] = atoi16[ARCH_INDEX(p[i * 2])] * 16
+ atoi16[ARCH_INDEX(p[i * 2 + 1])];
p = strtokm(NULL, "*");
cs.ctlen[0] = atoi(p);
p = strtokm(NULL, "*");
for (i = 0; i < cs.ctlen[0]; i++)
cs.ct[0][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;
}
static int akcdecrypt(unsigned char *derived_key, unsigned char *data)
{
unsigned char out[CTLEN];
int n, key_size;
AES_KEY akey;
unsigned char iv[16];
memcpy(iv, data + CTLEN - 32, 16);
if (AES_set_decrypt_key(derived_key, 128, &akey) < 0)
fprintf(stderr, "AES_set_decrypt_key failed in crypt!\n");
AES_cbc_encrypt(data + CTLEN - 16, out + CTLEN - 16, 16, &akey, iv, AES_DECRYPT);
n = check_pkcs_pad(out, CTLEN, 16);
if (n < 0)
return -1;
key_size = n / 8;
if (key_size != 128 && key_size != 192 && key_size != 256)
// "invalid key size"
return -1;
return 0;
}
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 += MAX_KEYS_PER_CRYPT)
#endif
{
#ifdef SIMD_COEF_32
unsigned char master[MAX_KEYS_PER_CRYPT][32];
int lens[MAX_KEYS_PER_CRYPT], i;
unsigned char *pin[MAX_KEYS_PER_CRYPT], *pout[MAX_KEYS_PER_CRYPT];
for (i = 0; i < MAX_KEYS_PER_CRYPT; ++i) {
lens[i] = strlen(saved_key[i+index]);
pin[i] = (unsigned char*)saved_key[i+index];
pout[i] = master[i];
}
pbkdf2_sha1_sse((const unsigned char **)pin, lens, cur_salt->salt[0], cur_salt->saltlen[0], cur_salt->iterations[0], pout, 16, 0);
for (i = 0; i < MAX_KEYS_PER_CRYPT; ++i) {
if(akcdecrypt(master[i], cur_salt->ct[0]) == 0)
cracked[i+index] = 1;
else
cracked[i+index] = 0;
}
#else
unsigned char master[32];
pbkdf2_sha1((unsigned char *)saved_key[index],
strlen(saved_key[index]),
cur_salt->salt[0], cur_salt->saltlen[0],
cur_salt->iterations[0], master, 16, 0);
if(akcdecrypt(master, cur_salt->ct[0]) == 0)
cracked[index] = 1;
else
cracked[index] = 0;
#endif
}
return count;
}
static int cmp_all(void *binary, int count)
{
int index;
for (index = 0; index < count; index++)
if (cracked[index])
return 1;
return 0;
}
static int cmp_one(void *binary, int index)
{
return cracked[index];
}
static int cmp_exact(char *source, int index)
{
return 1;
}
static void agile_keychain_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 unsigned int iteration_count(void *salt)
{
struct custom_salt *my_salt;
my_salt = salt;
return (unsigned int) my_salt->iterations[0];
}
struct fmt_main fmt_agile_keychain = {
{
FORMAT_LABEL,
FORMAT_NAME,
ALGORITHM_NAME,
BENCHMARK_COMMENT,
BENCHMARK_LENGTH,
0,
PLAINTEXT_LENGTH,
BINARY_SIZE,
BINARY_ALIGN,
SALT_SIZE,
SALT_ALIGN,
MIN_KEYS_PER_CRYPT,
MAX_KEYS_PER_CRYPT,
FMT_CASE | FMT_8_BIT | FMT_OMP | FMT_NOT_EXACT,
{
"iteration count",
},
agile_keychain_tests
}, {
init,
done,
fmt_default_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,
agile_keychain_set_key,
get_key,
fmt_default_clear_keys,
crypt_all,
{
fmt_default_get_hash
},
cmp_all,
cmp_one,
cmp_exact
}
};
#endif /* plugin stanza */
|
ic0_csc_executor.h |
#include <algorithm>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <cmath>
using namespace std;
extern double sqrt(int);
void ic0_csc_executor(int n, double *val, int * colPtr, int *rowIdx,
int levels, int *levelPtr, int *levelSet, int chunk){
int li=0;
// for (i = 0; i < n - 1; i++){
for (int l = 0; l < levels; ++l) {
#pragma omp parallel for default(shared) private(li) schedule(static)
for (li = levelPtr[l]; li < levelPtr[l + 1]; ++li) {
int i = levelSet[li];
val[colPtr[i]] = sqrt(val[colPtr[i]]);//S1
for (int m = colPtr[i] + 1; m < colPtr[i+1]; m++){
val[m] = val[m] / val[colPtr[i]];//S2
}
for (int m = colPtr[i] + 1; m < colPtr[i+1]; m++) {
for (int k = colPtr[rowIdx[m]] ; k < colPtr[rowIdx[m]+1]; k++){
for (int l = m; l < colPtr[i+1] ; l++){
if (rowIdx[l] == rowIdx[k] && rowIdx[l+1] <= rowIdx[k]){
#pragma omp atomic
val[k] -= val[m]* val[l]; //S3
}
}
}
}
}
}
}
|
GB_unop__identity_fp32_fc64.c | //------------------------------------------------------------------------------
// GB_unop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved.
// http://suitesparse.com See GraphBLAS/Doc/License.txt for license.
//------------------------------------------------------------------------------
// If this file is in the Generated/ folder, do not edit it (auto-generated).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_unop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB_unop_apply__identity_fp32_fc64
// op(A') function: GB_unop_tran__identity_fp32_fc64
// C type: float
// A type: GxB_FC64_t
// cast: float cij = (float) creal (aij)
// unaryop: cij = aij
#define GB_ATYPE \
GxB_FC64_t
#define GB_CTYPE \
float
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
GxB_FC64_t aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = x ;
// casting
#define GB_CAST(z, aij) \
float z = (float) creal (aij) ;
// cij = op (aij)
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
GxB_FC64_t aij = Ax [pA] ; \
/* Cx [pC] = op (cast (aij)) */ \
float z = (float) creal (aij) ; \
Cx [pC] = z ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_IDENTITY || GxB_NO_FP32 || GxB_NO_FC64)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop_apply__identity_fp32_fc64
(
float *Cx, // Cx and Ax may be aliased
const GxB_FC64_t *Ax,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
GxB_FC64_t aij = Ax [p] ;
float z = (float) creal (aij) ;
Cx [p] = z ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop_tran__identity_fp32_fc64
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t *GB_RESTRICT *Rowcounts,
GBI_single_iterator Iter,
const int64_t *GB_RESTRICT A_slice,
int naslice
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#define GB_PHASE_2_OF_2
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
convolution_sgemm_pack4.h | // Tencent is pleased to support the open source community by making ncnn available.
//
// Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// https://opensource.org/licenses/BSD-3-Clause
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
static void im2col_sgemm_pack4_neon(const Mat& bottom_im2col, Mat& top_blob, const Mat& kernel, const Mat& _bias, const Option& opt)
{
// Mat bottom_im2col(size, maxk, inch, 16u, 4, opt.workspace_allocator);
const int size = bottom_im2col.w;
const int maxk = bottom_im2col.h;
const int inch = bottom_im2col.c;
const int outch = top_blob.c;
const float* bias = _bias;
// permute
Mat tmp;
#if __aarch64__
if (size >= 12)
tmp.create(12 * maxk, inch, size / 12 + (size % 12) / 8 + (size % 12 % 8) / 4 + (size % 12 % 4) / 2 + size % 12 % 2, 16u, 4, opt.workspace_allocator);
else if (size >= 8)
tmp.create(8 * maxk, inch, size / 8 + (size % 8) / 4 + (size % 4) / 2 + size % 2, 16u, 4, opt.workspace_allocator);
else if (size >= 4)
tmp.create(4 * maxk, inch, size / 4 + (size % 4) / 2 + size % 2, 16u, 4, opt.workspace_allocator);
else if (size >= 2)
tmp.create(2 * maxk, inch, size / 2 + size % 2, 16u, 4, opt.workspace_allocator);
else
tmp.create(maxk, inch, size, 16u, 4, opt.workspace_allocator);
#else
if (size >= 8)
tmp.create(8 * maxk, inch, size / 8 + (size % 8) / 4 + (size % 4) / 2 + size % 2, 16u, 4, opt.workspace_allocator);
else if (size >= 4)
tmp.create(4 * maxk, inch, size / 4 + (size % 4) / 2 + size % 2, 16u, 4, opt.workspace_allocator);
else if (size >= 2)
tmp.create(2 * maxk, inch, size / 2 + size % 2, 16u, 4, opt.workspace_allocator);
else
tmp.create(maxk, inch, size, 16u, 4, opt.workspace_allocator);
#endif
{
#if __aarch64__
int nn_size = size / 12;
int remain_size_start = 0;
#pragma omp parallel for num_threads(opt.num_threads)
for (int ii = 0; ii < nn_size; ii++)
{
int i = remain_size_start + ii * 12;
float* tmpptr = tmp.channel(i / 12);
for (int q = 0; q < inch; q++)
{
const float* img0 = (const float*)bottom_im2col.channel(q) + i * 4;
for (int k = 0; k < maxk; k++)
{
asm volatile(
"prfm pldl1keep, [%0, #512] \n"
"ld4 {v0.4s, v1.4s, v2.4s, v3.4s}, [%0], #64 \n"
"prfm pldl1keep, [%0, #512] \n"
"ld4 {v4.4s, v5.4s, v6.4s, v7.4s}, [%0], #64 \n"
"prfm pldl1keep, [%0, #512] \n"
"ld4 {v8.4s, v9.4s, v10.4s, v11.4s}, [%0] \n"
"st1 {v0.4s}, [%1], #16 \n"
"st1 {v4.4s}, [%1], #16 \n"
"st1 {v8.4s}, [%1], #16 \n"
"sub %0, %0, #128 \n"
"st1 {v1.4s}, [%1], #16 \n"
"st1 {v5.4s}, [%1], #16 \n"
"st1 {v9.4s}, [%1], #16 \n"
"st1 {v2.4s}, [%1], #16 \n"
"st1 {v6.4s}, [%1], #16 \n"
"st1 {v10.4s}, [%1], #16 \n"
"st1 {v3.4s}, [%1], #16 \n"
"st1 {v7.4s}, [%1], #16 \n"
"st1 {v11.4s}, [%1], #16 \n"
: "=r"(img0), // %0
"=r"(tmpptr) // %1
: "0"(img0),
"1"(tmpptr)
: "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11");
img0 += size * 4;
}
}
}
remain_size_start += nn_size * 12;
nn_size = (size - remain_size_start) >> 3;
#else
int nn_size = size >> 3;
int remain_size_start = 0;
#endif
#pragma omp parallel for num_threads(opt.num_threads)
for (int ii = 0; ii < nn_size; ii++)
{
int i = remain_size_start + ii * 8;
#if __aarch64__
float* tmpptr = tmp.channel(i / 12 + (i % 12) / 8);
#else
float* tmpptr = tmp.channel(i / 8);
#endif
for (int q = 0; q < inch; q++)
{
const float* img0 = (const float*)bottom_im2col.channel(q) + i * 4;
for (int k = 0; k < maxk; k++)
{
#if __aarch64__
asm volatile(
"prfm pldl1keep, [%0, #512] \n"
"ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%0], #64 \n"
"prfm pldl1keep, [%0, #512] \n"
"ld1 {v4.4s, v5.4s, v6.4s, v7.4s}, [%0] \n"
"st1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%1], #64 \n"
"sub %0, %0, #64 \n"
"st1 {v4.4s, v5.4s, v6.4s, v7.4s}, [%1], #64 \n"
: "=r"(img0), // %0
"=r"(tmpptr) // %1
: "0"(img0),
"1"(tmpptr)
: "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7");
#else
asm volatile(
"pld [%0, #512] \n"
"vldm %0!, {d0-d7} \n"
"pld [%0, #512] \n"
"vldm %0, {d16-d23} \n"
// transpose 8x4
"vtrn.32 q0, q1 \n"
"vtrn.32 q2, q3 \n"
"vtrn.32 q8, q9 \n"
"vtrn.32 q10, q11 \n"
"vswp d1, d4 \n"
"vswp d3, d6 \n"
"vswp d17, d20 \n"
"vswp d19, d22 \n"
"vswp q1, q8 \n"
"vswp q3, q10 \n"
"vst1.f32 {d0-d3}, [%1 :128]! \n"
"vst1.f32 {d16-d19}, [%1 :128]! \n"
"sub %0, %0, #64 \n"
"vst1.f32 {d4-d7}, [%1 :128]! \n"
"vst1.f32 {d20-d23}, [%1 :128]! \n"
: "=r"(img0), // %0
"=r"(tmpptr) // %1
: "0"(img0),
"1"(tmpptr)
: "memory", "q0", "q1", "q2", "q3", "q8", "q9", "q10", "q11");
#endif // __aarch64__
img0 += size * 4;
}
}
}
remain_size_start += nn_size << 3;
nn_size = (size - remain_size_start) >> 2;
#pragma omp parallel for num_threads(opt.num_threads)
for (int ii = 0; ii < nn_size; ii++)
{
int i = remain_size_start + ii * 4;
#if __aarch64__
float* tmpptr = tmp.channel(i / 12 + (i % 12) / 8 + (i % 12 % 8) / 4);
#else
float* tmpptr = tmp.channel(i / 8 + (i % 8) / 4);
#endif
for (int q = 0; q < inch; q++)
{
const float* img0 = (const float*)bottom_im2col.channel(q) + i * 4;
for (int k = 0; k < maxk; k++)
{
#if __aarch64__
asm volatile(
"prfm pldl1keep, [%0, #512] \n"
"ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%0] \n"
"st1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%1], #64 \n"
: "=r"(img0), // %0
"=r"(tmpptr) // %1
: "0"(img0),
"1"(tmpptr)
: "memory", "v0", "v1", "v2", "v3");
#else
asm volatile(
"pld [%0, #512] \n"
"vldm %0, {d0-d7} \n"
"vstm %1!, {d0-d7} \n"
: "=r"(img0), // %0
"=r"(tmpptr) // %1
: "0"(img0),
"1"(tmpptr)
: "memory", "q0", "q1", "q2", "q3");
#endif // __aarch64__
img0 += size * 4;
}
}
}
remain_size_start += nn_size << 2;
nn_size = (size - remain_size_start) >> 1;
#pragma omp parallel for num_threads(opt.num_threads)
for (int ii = 0; ii < nn_size; ii++)
{
int i = remain_size_start + ii * 2;
#if __aarch64__
float* tmpptr = tmp.channel(i / 12 + (i % 12) / 8 + (i % 12 % 8) / 4 + (i % 12 % 4) / 2);
#else
float* tmpptr = tmp.channel(i / 8 + (i % 8) / 4 + (i % 4) / 2);
#endif
for (int q = 0; q < inch; q++)
{
const float* img0 = (const float*)bottom_im2col.channel(q) + i * 4;
for (int k = 0; k < maxk; k++)
{
#if __aarch64__
asm volatile(
"prfm pldl1keep, [%0, #256] \n"
"ld1 {v0.4s, v1.4s}, [%0] \n"
"st1 {v0.4s, v1.4s}, [%1], #32 \n"
: "=r"(img0), // %0
"=r"(tmpptr) // %1
: "0"(img0),
"1"(tmpptr)
: "memory", "v0", "v1");
#else
asm volatile(
"pld [%0, #256] \n"
"vld1.f32 {d0-d3}, [%0 :128] \n"
"vst1.f32 {d0-d3}, [%1 :128]! \n"
: "=r"(img0), // %0
"=r"(tmpptr) // %1
: "0"(img0),
"1"(tmpptr)
: "memory", "q0", "q1");
#endif // __aarch64__
img0 += size * 4;
}
}
}
remain_size_start += nn_size << 1;
#pragma omp parallel for num_threads(opt.num_threads)
for (int i = remain_size_start; i < size; i++)
{
#if __aarch64__
float* tmpptr = tmp.channel(i / 12 + (i % 12) / 8 + (i % 12 % 8) / 4 + (i % 12 % 4) / 2 + i % 12 % 2);
#else
float* tmpptr = tmp.channel(i / 8 + (i % 8) / 4 + (i % 4) / 2 + i % 2);
#endif
for (int q = 0; q < inch; q++)
{
const float* img0 = (const float*)bottom_im2col.channel(q) + i * 4;
for (int k = 0; k < maxk; k++)
{
#if __aarch64__
asm volatile(
"prfm pldl1keep, [%0, #128] \n"
"ld1 {v0.4s}, [%0] \n"
"st1 {v0.4s}, [%1], #16 \n"
: "=r"(img0), // %0
"=r"(tmpptr) // %1
: "0"(img0),
"1"(tmpptr)
: "memory", "v0");
#else
asm volatile(
"pld [%0, #128] \n"
"vld1.f32 {d0-d1}, [%0 :128] \n"
"vst1.f32 {d0-d1}, [%1 :128]! \n"
: "=r"(img0), // %0
"=r"(tmpptr) // %1
: "0"(img0),
"1"(tmpptr)
: "memory", "q0");
#endif // __aarch64__
img0 += size * 4;
}
}
}
}
int remain_outch_start = 0;
#if __aarch64__
int nn_outch = outch >> 1;
remain_outch_start = nn_outch << 1;
#pragma omp parallel for num_threads(opt.num_threads)
for (int pp = 0; pp < nn_outch; pp++)
{
int p = pp * 2;
float* outptr0 = top_blob.channel(p);
float* outptr1 = top_blob.channel(p + 1);
const float zeros[8] = {0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f};
const float* biasptr = bias ? bias + p * 4 : zeros;
int i = 0;
for (; i + 11 < size; i += 12)
{
const float* tmpptr = tmp.channel(i / 12);
const float* kptr0 = kernel.channel(p / 2);
int nn = inch * maxk; // inch always > 0
asm volatile(
"ld1 {v0.4s, v1.4s}, [%10] \n"
"mov v8.16b, v0.16b \n"
"mov v9.16b, v0.16b \n"
"mov v10.16b, v0.16b \n"
"mov v11.16b, v0.16b \n"
"mov v12.16b, v0.16b \n"
"mov v13.16b, v0.16b \n"
"mov v14.16b, v0.16b \n"
"mov v15.16b, v0.16b \n"
"mov v16.16b, v0.16b \n"
"mov v17.16b, v0.16b \n"
"mov v18.16b, v0.16b \n"
"mov v19.16b, v0.16b \n"
"mov v20.16b, v1.16b \n"
"mov v21.16b, v1.16b \n"
"mov v22.16b, v1.16b \n"
"mov v23.16b, v1.16b \n"
"mov v24.16b, v1.16b \n"
"mov v25.16b, v1.16b \n"
"mov v26.16b, v1.16b \n"
"mov v27.16b, v1.16b \n"
"mov v28.16b, v1.16b \n"
"mov v29.16b, v1.16b \n"
"mov v30.16b, v1.16b \n"
"mov v31.16b, v1.16b \n"
"0: \n"
"prfm pldl1keep, [%3, #512] \n"
"ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%3], #64 \n"
"prfm pldl1keep, [%4, #512] \n"
"ld1 {v4.4s, v5.4s, v6.4s, v7.4s}, [%4], #64 \n" // w0011_01
"fmla v8.4s, v4.4s, v0.s[0] \n"
"fmla v9.4s, v4.4s, v0.s[1] \n"
"fmla v10.4s, v4.4s, v0.s[2] \n"
"fmla v11.4s, v4.4s, v0.s[3] \n"
"fmla v12.4s, v4.4s, v1.s[0] \n"
"fmla v13.4s, v4.4s, v1.s[1] \n"
"fmla v14.4s, v4.4s, v1.s[2] \n"
"fmla v15.4s, v4.4s, v1.s[3] \n"
"fmla v16.4s, v4.4s, v2.s[0] \n"
"fmla v17.4s, v4.4s, v2.s[1] \n"
"fmla v18.4s, v4.4s, v2.s[2] \n"
"fmla v19.4s, v4.4s, v2.s[3] \n"
"fmla v20.4s, v5.4s, v0.s[0] \n"
"fmla v21.4s, v5.4s, v0.s[1] \n"
"fmla v22.4s, v5.4s, v0.s[2] \n"
"fmla v23.4s, v5.4s, v0.s[3] \n"
"fmla v24.4s, v5.4s, v1.s[0] \n"
"fmla v25.4s, v5.4s, v1.s[1] \n"
"fmla v26.4s, v5.4s, v1.s[2] \n"
"fmla v27.4s, v5.4s, v1.s[3] \n"
"fmla v28.4s, v5.4s, v2.s[0] \n"
"fmla v29.4s, v5.4s, v2.s[1] \n"
"fmla v30.4s, v5.4s, v2.s[2] \n"
"fmla v31.4s, v5.4s, v2.s[3] \n"
"fmla v8.4s, v6.4s, v3.s[0] \n"
"fmla v9.4s, v6.4s, v3.s[1] \n"
"fmla v10.4s, v6.4s, v3.s[2] \n"
"fmla v11.4s, v6.4s, v3.s[3] \n"
"fmla v20.4s, v7.4s, v3.s[0] \n"
"fmla v21.4s, v7.4s, v3.s[1] \n"
"fmla v22.4s, v7.4s, v3.s[2] \n"
"fmla v23.4s, v7.4s, v3.s[3] \n"
"prfm pldl1keep, [%3, #512] \n"
"ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%3], #64 \n"
"fmla v12.4s, v6.4s, v0.s[0] \n"
"fmla v13.4s, v6.4s, v0.s[1] \n"
"fmla v14.4s, v6.4s, v0.s[2] \n"
"fmla v15.4s, v6.4s, v0.s[3] \n"
"fmla v16.4s, v6.4s, v1.s[0] \n"
"fmla v17.4s, v6.4s, v1.s[1] \n"
"fmla v18.4s, v6.4s, v1.s[2] \n"
"fmla v19.4s, v6.4s, v1.s[3] \n"
"fmla v24.4s, v7.4s, v0.s[0] \n"
"fmla v25.4s, v7.4s, v0.s[1] \n"
"fmla v26.4s, v7.4s, v0.s[2] \n"
"fmla v27.4s, v7.4s, v0.s[3] \n"
"fmla v28.4s, v7.4s, v1.s[0] \n"
"fmla v29.4s, v7.4s, v1.s[1] \n"
"fmla v30.4s, v7.4s, v1.s[2] \n"
"fmla v31.4s, v7.4s, v1.s[3] \n"
"prfm pldl1keep, [%4, #512] \n"
"ld1 {v4.4s, v5.4s, v6.4s, v7.4s}, [%4], #64 \n" // w2233_01
"fmla v8.4s, v4.4s, v2.s[0] \n"
"fmla v9.4s, v4.4s, v2.s[1] \n"
"fmla v10.4s, v4.4s, v2.s[2] \n"
"fmla v11.4s, v4.4s, v2.s[3] \n"
"fmla v12.4s, v4.4s, v3.s[0] \n"
"fmla v13.4s, v4.4s, v3.s[1] \n"
"fmla v14.4s, v4.4s, v3.s[2] \n"
"fmla v15.4s, v4.4s, v3.s[3] \n"
"fmla v20.4s, v5.4s, v2.s[0] \n"
"fmla v21.4s, v5.4s, v2.s[1] \n"
"fmla v22.4s, v5.4s, v2.s[2] \n"
"fmla v23.4s, v5.4s, v2.s[3] \n"
"fmla v24.4s, v5.4s, v3.s[0] \n"
"fmla v25.4s, v5.4s, v3.s[1] \n"
"fmla v26.4s, v5.4s, v3.s[2] \n"
"fmla v27.4s, v5.4s, v3.s[3] \n"
"prfm pldl1keep, [%3, #512] \n"
"ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%3], #64 \n"
"fmla v16.4s, v4.4s, v0.s[0] \n"
"fmla v17.4s, v4.4s, v0.s[1] \n"
"fmla v18.4s, v4.4s, v0.s[2] \n"
"fmla v19.4s, v4.4s, v0.s[3] \n"
"fmla v28.4s, v5.4s, v0.s[0] \n"
"fmla v29.4s, v5.4s, v0.s[1] \n"
"fmla v30.4s, v5.4s, v0.s[2] \n"
"fmla v31.4s, v5.4s, v0.s[3] \n"
"fmla v8.4s, v6.4s, v1.s[0] \n"
"fmla v9.4s, v6.4s, v1.s[1] \n"
"fmla v10.4s, v6.4s, v1.s[2] \n"
"fmla v11.4s, v6.4s, v1.s[3] \n"
"fmla v12.4s, v6.4s, v2.s[0] \n"
"fmla v13.4s, v6.4s, v2.s[1] \n"
"fmla v14.4s, v6.4s, v2.s[2] \n"
"fmla v15.4s, v6.4s, v2.s[3] \n"
"fmla v16.4s, v6.4s, v3.s[0] \n"
"fmla v17.4s, v6.4s, v3.s[1] \n"
"fmla v18.4s, v6.4s, v3.s[2] \n"
"fmla v19.4s, v6.4s, v3.s[3] \n"
"subs %w0, %w0, #1 \n"
"fmla v20.4s, v7.4s, v1.s[0] \n"
"fmla v21.4s, v7.4s, v1.s[1] \n"
"fmla v22.4s, v7.4s, v1.s[2] \n"
"fmla v23.4s, v7.4s, v1.s[3] \n"
"fmla v24.4s, v7.4s, v2.s[0] \n"
"fmla v25.4s, v7.4s, v2.s[1] \n"
"fmla v26.4s, v7.4s, v2.s[2] \n"
"fmla v27.4s, v7.4s, v2.s[3] \n"
"fmla v28.4s, v7.4s, v3.s[0] \n"
"fmla v29.4s, v7.4s, v3.s[1] \n"
"fmla v30.4s, v7.4s, v3.s[2] \n"
"fmla v31.4s, v7.4s, v3.s[3] \n"
"bne 0b \n"
"st1 {v8.4s, v9.4s, v10.4s, v11.4s}, [%1], #64 \n"
"st1 {v20.4s, v21.4s, v22.4s, v23.4s}, [%2], #64 \n"
"st1 {v12.4s, v13.4s, v14.4s, v15.4s}, [%1], #64 \n"
"st1 {v24.4s, v25.4s, v26.4s, v27.4s}, [%2], #64 \n"
"st1 {v16.4s, v17.4s, v18.4s, v19.4s}, [%1], #64 \n"
"st1 {v28.4s, v29.4s, v30.4s, v31.4s}, [%2], #64 \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(outptr1), // %2
"=r"(tmpptr), // %3
"=r"(kptr0) // %4
: "0"(nn),
"1"(outptr0),
"2"(outptr1),
"3"(tmpptr),
"4"(kptr0),
"r"(biasptr) // %10
: "cc", "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23", "v24", "v25", "v26", "v27", "v28", "v29", "v30", "v31");
}
for (; i + 7 < size; i += 8)
{
const float* tmpptr = tmp.channel(i / 12 + (i % 12) / 8);
const float* kptr0 = kernel.channel(p / 2);
int nn = inch * maxk; // inch always > 0
asm volatile(
"ld1 {v0.4s, v1.4s}, [%10] \n"
"mov v16.16b, v0.16b \n"
"mov v17.16b, v0.16b \n"
"mov v18.16b, v0.16b \n"
"mov v19.16b, v0.16b \n"
"mov v20.16b, v0.16b \n"
"mov v21.16b, v0.16b \n"
"mov v22.16b, v0.16b \n"
"mov v23.16b, v0.16b \n"
"mov v24.16b, v1.16b \n"
"mov v25.16b, v1.16b \n"
"mov v26.16b, v1.16b \n"
"mov v27.16b, v1.16b \n"
"mov v28.16b, v1.16b \n"
"mov v29.16b, v1.16b \n"
"mov v30.16b, v1.16b \n"
"mov v31.16b, v1.16b \n"
"0: \n"
"prfm pldl1keep, [%3, #512] \n"
"ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%3], #64 \n" // r0 r1 r2 r3
"prfm pldl1keep, [%4, #512] \n"
"ld1 {v8.4s, v9.4s, v10.4s, v11.4s}, [%4], #64 \n" // w0011_01
"fmla v16.4s, v8.4s, v0.s[0] \n"
"fmla v17.4s, v8.4s, v1.s[0] \n"
"fmla v18.4s, v8.4s, v2.s[0] \n"
"fmla v19.4s, v8.4s, v3.s[0] \n"
"prfm pldl1keep, [%3, #512] \n"
"ld1 {v4.4s, v5.4s, v6.4s, v7.4s}, [%3], #64 \n" // r4 r5 r6 r7
"fmla v20.4s, v8.4s, v4.s[0] \n"
"fmla v21.4s, v8.4s, v5.s[0] \n"
"fmla v22.4s, v8.4s, v6.s[0] \n"
"fmla v23.4s, v8.4s, v7.s[0] \n"
"fmla v24.4s, v9.4s, v0.s[0] \n"
"fmla v25.4s, v9.4s, v1.s[0] \n"
"fmla v26.4s, v9.4s, v2.s[0] \n"
"fmla v27.4s, v9.4s, v3.s[0] \n"
"fmla v28.4s, v9.4s, v4.s[0] \n"
"fmla v29.4s, v9.4s, v5.s[0] \n"
"fmla v30.4s, v9.4s, v6.s[0] \n"
"fmla v31.4s, v9.4s, v7.s[0] \n"
"fmla v16.4s, v10.4s, v0.s[1] \n"
"fmla v17.4s, v10.4s, v1.s[1] \n"
"fmla v18.4s, v10.4s, v2.s[1] \n"
"fmla v19.4s, v10.4s, v3.s[1] \n"
"fmla v20.4s, v10.4s, v4.s[1] \n"
"fmla v21.4s, v10.4s, v5.s[1] \n"
"fmla v22.4s, v10.4s, v6.s[1] \n"
"fmla v23.4s, v10.4s, v7.s[1] \n"
"fmla v24.4s, v11.4s, v0.s[1] \n"
"fmla v25.4s, v11.4s, v1.s[1] \n"
"fmla v26.4s, v11.4s, v2.s[1] \n"
"fmla v27.4s, v11.4s, v3.s[1] \n"
"fmla v28.4s, v11.4s, v4.s[1] \n"
"fmla v29.4s, v11.4s, v5.s[1] \n"
"fmla v30.4s, v11.4s, v6.s[1] \n"
"fmla v31.4s, v11.4s, v7.s[1] \n"
"prfm pldl1keep, [%4, #512] \n"
"ld1 {v12.4s, v13.4s, v14.4s, v15.4s}, [%4], #64 \n" // w2233_01
"fmla v16.4s, v12.4s, v0.s[2] \n"
"fmla v17.4s, v12.4s, v1.s[2] \n"
"fmla v18.4s, v12.4s, v2.s[2] \n"
"fmla v19.4s, v12.4s, v3.s[2] \n"
"fmla v20.4s, v12.4s, v4.s[2] \n"
"fmla v21.4s, v12.4s, v5.s[2] \n"
"fmla v22.4s, v12.4s, v6.s[2] \n"
"fmla v23.4s, v12.4s, v7.s[2] \n"
"fmla v24.4s, v13.4s, v0.s[2] \n"
"fmla v25.4s, v13.4s, v1.s[2] \n"
"fmla v26.4s, v13.4s, v2.s[2] \n"
"fmla v27.4s, v13.4s, v3.s[2] \n"
"fmla v28.4s, v13.4s, v4.s[2] \n"
"fmla v29.4s, v13.4s, v5.s[2] \n"
"fmla v30.4s, v13.4s, v6.s[2] \n"
"fmla v31.4s, v13.4s, v7.s[2] \n"
"fmla v16.4s, v14.4s, v0.s[3] \n"
"fmla v17.4s, v14.4s, v1.s[3] \n"
"fmla v18.4s, v14.4s, v2.s[3] \n"
"fmla v19.4s, v14.4s, v3.s[3] \n"
"fmla v20.4s, v14.4s, v4.s[3] \n"
"fmla v21.4s, v14.4s, v5.s[3] \n"
"fmla v22.4s, v14.4s, v6.s[3] \n"
"fmla v23.4s, v14.4s, v7.s[3] \n"
"subs %w0, %w0, #1 \n"
"fmla v24.4s, v15.4s, v0.s[3] \n"
"fmla v25.4s, v15.4s, v1.s[3] \n"
"fmla v26.4s, v15.4s, v2.s[3] \n"
"fmla v27.4s, v15.4s, v3.s[3] \n"
"fmla v28.4s, v15.4s, v4.s[3] \n"
"fmla v29.4s, v15.4s, v5.s[3] \n"
"fmla v30.4s, v15.4s, v6.s[3] \n"
"fmla v31.4s, v15.4s, v7.s[3] \n"
"bne 0b \n"
"st1 {v16.4s, v17.4s, v18.4s, v19.4s}, [%1], #64 \n"
"st1 {v24.4s, v25.4s, v26.4s, v27.4s}, [%2], #64 \n"
"st1 {v20.4s, v21.4s, v22.4s, v23.4s}, [%1], #64 \n"
"st1 {v28.4s, v29.4s, v30.4s, v31.4s}, [%2], #64 \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(outptr1), // %2
"=r"(tmpptr), // %3
"=r"(kptr0) // %4
: "0"(nn),
"1"(outptr0),
"2"(outptr1),
"3"(tmpptr),
"4"(kptr0),
"r"(biasptr) // %10
: "cc", "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23", "v24", "v25", "v26", "v27", "v28", "v29", "v30", "v31");
}
for (; i + 3 < size; i += 4)
{
const float* tmpptr = tmp.channel(i / 12 + (i % 12) / 8 + (i % 12 % 8) / 4);
const float* kptr0 = kernel.channel(p / 2);
int nn = inch * maxk; // inch always > 0
asm volatile(
"ld1 {v0.4s, v1.4s}, [%10] \n"
"mov v16.16b, v0.16b \n"
"mov v17.16b, v0.16b \n"
"mov v18.16b, v0.16b \n"
"mov v19.16b, v0.16b \n"
"mov v20.16b, v1.16b \n"
"mov v21.16b, v1.16b \n"
"mov v22.16b, v1.16b \n"
"mov v23.16b, v1.16b \n"
"0: \n"
"prfm pldl1keep, [%3, #512] \n"
"ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%3], #64 \n" // r0 r1 r2 r3
"prfm pldl1keep, [%4, #512] \n"
"ld1 {v8.4s, v9.4s, v10.4s, v11.4s}, [%4], #64 \n" // w0011_01
"fmla v16.4s, v8.4s, v0.s[0] \n"
"fmla v17.4s, v8.4s, v1.s[0] \n"
"fmla v18.4s, v8.4s, v2.s[0] \n"
"fmla v19.4s, v8.4s, v3.s[0] \n"
"fmla v20.4s, v9.4s, v0.s[0] \n"
"fmla v21.4s, v9.4s, v1.s[0] \n"
"fmla v22.4s, v9.4s, v2.s[0] \n"
"fmla v23.4s, v9.4s, v3.s[0] \n"
"prfm pldl1keep, [%4, #512] \n"
"ld1 {v12.4s, v13.4s, v14.4s, v15.4s}, [%4], #64 \n" // w2233_01
"fmla v16.4s, v10.4s, v0.s[1] \n"
"fmla v17.4s, v10.4s, v1.s[1] \n"
"fmla v18.4s, v10.4s, v2.s[1] \n"
"fmla v19.4s, v10.4s, v3.s[1] \n"
"fmla v20.4s, v11.4s, v0.s[1] \n"
"fmla v21.4s, v11.4s, v1.s[1] \n"
"fmla v22.4s, v11.4s, v2.s[1] \n"
"fmla v23.4s, v11.4s, v3.s[1] \n"
"fmla v16.4s, v12.4s, v0.s[2] \n"
"fmla v17.4s, v12.4s, v1.s[2] \n"
"fmla v18.4s, v12.4s, v2.s[2] \n"
"fmla v19.4s, v12.4s, v3.s[2] \n"
"fmla v20.4s, v13.4s, v0.s[2] \n"
"fmla v21.4s, v13.4s, v1.s[2] \n"
"fmla v22.4s, v13.4s, v2.s[2] \n"
"fmla v23.4s, v13.4s, v3.s[2] \n"
"subs %w0, %w0, #1 \n"
"fmla v16.4s, v14.4s, v0.s[3] \n"
"fmla v17.4s, v14.4s, v1.s[3] \n"
"fmla v18.4s, v14.4s, v2.s[3] \n"
"fmla v19.4s, v14.4s, v3.s[3] \n"
"fmla v20.4s, v15.4s, v0.s[3] \n"
"fmla v21.4s, v15.4s, v1.s[3] \n"
"fmla v22.4s, v15.4s, v2.s[3] \n"
"fmla v23.4s, v15.4s, v3.s[3] \n"
"bne 0b \n"
"st1 {v16.4s, v17.4s, v18.4s, v19.4s}, [%1], #64 \n"
"st1 {v20.4s, v21.4s, v22.4s, v23.4s}, [%2], #64 \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(outptr1), // %2
"=r"(tmpptr), // %3
"=r"(kptr0) // %4
: "0"(nn),
"1"(outptr0),
"2"(outptr1),
"3"(tmpptr),
"4"(kptr0),
"r"(biasptr) // %10
: "cc", "memory", "v0", "v1", "v2", "v3", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23");
}
for (; i + 1 < size; i += 2)
{
const float* tmpptr = tmp.channel(i / 12 + (i % 12) / 8 + (i % 12 % 8) / 4 + (i % 12 % 4) / 2);
const float* kptr0 = kernel.channel(p / 2);
int nn = inch * maxk; // inch always > 0
asm volatile(
"ld1 {v0.4s, v1.4s}, [%10] \n"
"mov v16.16b, v0.16b \n"
"mov v17.16b, v0.16b \n"
"mov v18.16b, v1.16b \n"
"mov v19.16b, v1.16b \n"
"0: \n"
"prfm pldl1keep, [%3, #256] \n"
"ld1 {v0.4s, v1.4s}, [%3], #32 \n" // r0 r1
"prfm pldl1keep, [%4, #512] \n"
"ld1 {v8.4s, v9.4s, v10.4s, v11.4s}, [%4], #64 \n" // w0011_01
"fmla v16.4s, v8.4s, v0.s[0] \n"
"fmla v17.4s, v8.4s, v1.s[0] \n"
"fmla v18.4s, v9.4s, v0.s[0] \n"
"fmla v19.4s, v9.4s, v1.s[0] \n"
"prfm pldl1keep, [%4, #512] \n"
"ld1 {v12.4s, v13.4s, v14.4s, v15.4s}, [%4], #64 \n" // w2233_01
"fmla v16.4s, v10.4s, v0.s[1] \n"
"fmla v17.4s, v10.4s, v1.s[1] \n"
"fmla v18.4s, v11.4s, v0.s[1] \n"
"fmla v19.4s, v11.4s, v1.s[1] \n"
"fmla v16.4s, v12.4s, v0.s[2] \n"
"fmla v17.4s, v12.4s, v1.s[2] \n"
"fmla v18.4s, v13.4s, v0.s[2] \n"
"fmla v19.4s, v13.4s, v1.s[2] \n"
"subs %w0, %w0, #1 \n"
"fmla v16.4s, v14.4s, v0.s[3] \n"
"fmla v17.4s, v14.4s, v1.s[3] \n"
"fmla v18.4s, v15.4s, v0.s[3] \n"
"fmla v19.4s, v15.4s, v1.s[3] \n"
"bne 0b \n"
"st1 {v16.4s, v17.4s}, [%1], #32 \n"
"st1 {v18.4s, v19.4s}, [%2], #32 \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(outptr1), // %2
"=r"(tmpptr), // %3
"=r"(kptr0) // %4
: "0"(nn),
"1"(outptr0),
"2"(outptr1),
"3"(tmpptr),
"4"(kptr0),
"r"(biasptr) // %10
: "cc", "memory", "v0", "v1", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19");
}
for (; i < size; i++)
{
const float* tmpptr = tmp.channel(i / 12 + (i % 12) / 8 + (i % 12 % 8) / 4 + (i % 12 % 4) / 2 + i % 12 % 2);
const float* kptr0 = kernel.channel(p / 2);
int nn = inch * maxk; // inch always > 0
asm volatile(
"ld1 {v16.4s, v17.4s}, [%10] \n"
"0: \n"
"prfm pldl1keep, [%3, #128] \n"
"ld1 {v0.4s}, [%3], #16 \n" // r0
"prfm pldl1keep, [%4, #512] \n"
"ld1 {v8.4s, v9.4s, v10.4s, v11.4s}, [%4], #64 \n" // w0011_01
"fmla v16.4s, v8.4s, v0.s[0] \n"
"fmla v17.4s, v9.4s, v0.s[0] \n"
"prfm pldl1keep, [%4, #512] \n"
"ld1 {v12.4s, v13.4s, v14.4s, v15.4s}, [%4], #64 \n" // w2233_01
"fmla v16.4s, v10.4s, v0.s[1] \n"
"fmla v17.4s, v11.4s, v0.s[1] \n"
"fmla v16.4s, v12.4s, v0.s[2] \n"
"fmla v17.4s, v13.4s, v0.s[2] \n"
"subs %w0, %w0, #1 \n"
"fmla v16.4s, v14.4s, v0.s[3] \n"
"fmla v17.4s, v15.4s, v0.s[3] \n"
"bne 0b \n"
"st1 {v16.4s}, [%1], #16 \n"
"st1 {v17.4s}, [%2], #16 \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(outptr1), // %2
"=r"(tmpptr), // %3
"=r"(kptr0) // %4
: "0"(nn),
"1"(outptr0),
"2"(outptr1),
"3"(tmpptr),
"4"(kptr0),
"r"(biasptr) // %10
: "cc", "memory", "v0", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17");
}
}
#endif // __aarch64__
#pragma omp parallel for num_threads(opt.num_threads)
for (int p = remain_outch_start; p < outch; p++)
{
float* outptr0 = top_blob.channel(p);
const float zeros[4] = {0.f, 0.f, 0.f, 0.f};
const float* biasptr = bias ? bias + p * 4 : zeros;
int i = 0;
#if __aarch64__
for (; i + 11 < size; i += 12)
{
const float* tmpptr = tmp.channel(i / 12);
const float* kptr0 = kernel.channel(p / 2 + p % 2);
int nn = inch * maxk; // inch always > 0
asm volatile(
"ld1 {v0.4s}, [%8] \n"
"mov v8.16b, v0.16b \n"
"mov v9.16b, v0.16b \n"
"mov v10.16b, v0.16b \n"
"mov v11.16b, v0.16b \n"
"mov v12.16b, v0.16b \n"
"mov v13.16b, v0.16b \n"
"mov v14.16b, v0.16b \n"
"mov v15.16b, v0.16b \n"
"mov v16.16b, v0.16b \n"
"mov v17.16b, v0.16b \n"
"mov v18.16b, v0.16b \n"
"mov v19.16b, v0.16b \n"
"0: \n"
"prfm pldl1keep, [%2, #512] \n"
"ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%2], #64 \n"
"prfm pldl1keep, [%3, #512] \n"
"ld1 {v4.4s, v5.4s, v6.4s, v7.4s}, [%3], #64 \n" // w0123_0
"fmla v8.4s, v4.4s, v0.s[0] \n"
"fmla v9.4s, v4.4s, v0.s[1] \n"
"fmla v10.4s, v4.4s, v0.s[2] \n"
"fmla v11.4s, v4.4s, v0.s[3] \n"
"fmla v12.4s, v4.4s, v1.s[0] \n"
"fmla v13.4s, v4.4s, v1.s[1] \n"
"fmla v14.4s, v4.4s, v1.s[2] \n"
"fmla v15.4s, v4.4s, v1.s[3] \n"
"fmla v16.4s, v4.4s, v2.s[0] \n"
"fmla v17.4s, v4.4s, v2.s[1] \n"
"fmla v18.4s, v4.4s, v2.s[2] \n"
"fmla v19.4s, v4.4s, v2.s[3] \n"
"prfm pldl1keep, [%2, #512] \n"
"ld1 {v20.4s, v21.4s, v22.4s, v23.4s}, [%2], #64 \n"
"fmla v8.4s, v5.4s, v3.s[0] \n"
"fmla v9.4s, v5.4s, v3.s[1] \n"
"fmla v10.4s, v5.4s, v3.s[2] \n"
"fmla v11.4s, v5.4s, v3.s[3] \n"
"fmla v12.4s, v5.4s, v20.s[0] \n"
"fmla v13.4s, v5.4s, v20.s[1] \n"
"fmla v14.4s, v5.4s, v20.s[2] \n"
"fmla v15.4s, v5.4s, v20.s[3] \n"
"fmla v16.4s, v5.4s, v21.s[0] \n"
"fmla v17.4s, v5.4s, v21.s[1] \n"
"fmla v18.4s, v5.4s, v21.s[2] \n"
"fmla v19.4s, v5.4s, v21.s[3] \n"
"prfm pldl1keep, [%2, #512] \n"
"ld1 {v24.4s, v25.4s, v26.4s, v27.4s}, [%2], #64 \n"
"fmla v8.4s, v6.4s, v22.s[0] \n"
"fmla v9.4s, v6.4s, v22.s[1] \n"
"fmla v10.4s, v6.4s, v22.s[2] \n"
"fmla v11.4s, v6.4s, v22.s[3] \n"
"fmla v12.4s, v6.4s, v23.s[0] \n"
"fmla v13.4s, v6.4s, v23.s[1] \n"
"fmla v14.4s, v6.4s, v23.s[2] \n"
"fmla v15.4s, v6.4s, v23.s[3] \n"
"fmla v16.4s, v6.4s, v24.s[0] \n"
"fmla v17.4s, v6.4s, v24.s[1] \n"
"fmla v18.4s, v6.4s, v24.s[2] \n"
"fmla v19.4s, v6.4s, v24.s[3] \n"
"subs %w0, %w0, #1 \n"
"fmla v8.4s, v7.4s, v25.s[0] \n"
"fmla v9.4s, v7.4s, v25.s[1] \n"
"fmla v10.4s, v7.4s, v25.s[2] \n"
"fmla v11.4s, v7.4s, v25.s[3] \n"
"fmla v12.4s, v7.4s, v26.s[0] \n"
"fmla v13.4s, v7.4s, v26.s[1] \n"
"fmla v14.4s, v7.4s, v26.s[2] \n"
"fmla v15.4s, v7.4s, v26.s[3] \n"
"fmla v16.4s, v7.4s, v27.s[0] \n"
"fmla v17.4s, v7.4s, v27.s[1] \n"
"fmla v18.4s, v7.4s, v27.s[2] \n"
"fmla v19.4s, v7.4s, v27.s[3] \n"
"bne 0b \n"
"st1 {v8.4s, v9.4s, v10.4s, v11.4s}, [%1], #64 \n"
"st1 {v12.4s, v13.4s, v14.4s, v15.4s}, [%1], #64 \n"
"st1 {v16.4s, v17.4s, v18.4s, v19.4s}, [%1], #64 \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(tmpptr), // %2
"=r"(kptr0) // %3
: "0"(nn),
"1"(outptr0),
"2"(tmpptr),
"3"(kptr0),
"r"(biasptr) // %8
: "cc", "memory", "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");
}
#endif // __aarch64__
for (; i + 7 < size; i += 8)
{
#if __aarch64__
const float* tmpptr = tmp.channel(i / 12 + (i % 12) / 8);
const float* kptr0 = kernel.channel(p / 2 + p % 2);
#else
const float* tmpptr = tmp.channel(i / 8);
const float* kptr0 = kernel.channel(p);
#endif
int nn = inch * maxk; // inch always > 0
#if __aarch64__
asm volatile(
"ld1 {v0.4s}, [%8] \n"
"mov v16.16b, v0.16b \n"
"mov v17.16b, v0.16b \n"
"mov v18.16b, v0.16b \n"
"mov v19.16b, v0.16b \n"
"mov v20.16b, v0.16b \n"
"mov v21.16b, v0.16b \n"
"mov v22.16b, v0.16b \n"
"mov v23.16b, v0.16b \n"
"0: \n"
"prfm pldl1keep, [%2, #512] \n"
"ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%2], #64 \n" // r0 r1 r2 r3
"prfm pldl1keep, [%3, #512] \n"
"ld1 {v8.4s, v9.4s, v10.4s, v11.4s}, [%3], #64 \n" // w0123
"fmla v16.4s, v8.4s, v0.s[0] \n"
"fmla v17.4s, v8.4s, v1.s[0] \n"
"fmla v18.4s, v8.4s, v2.s[0] \n"
"fmla v19.4s, v8.4s, v3.s[0] \n"
"prfm pldl1keep, [%2, #512] \n"
"ld1 {v4.4s, v5.4s, v6.4s, v7.4s}, [%2], #64 \n" // r4 r5 r6 r7
"fmla v20.4s, v8.4s, v4.s[0] \n"
"fmla v21.4s, v8.4s, v5.s[0] \n"
"fmla v22.4s, v8.4s, v6.s[0] \n"
"fmla v23.4s, v8.4s, v7.s[0] \n"
"fmla v16.4s, v9.4s, v0.s[1] \n"
"fmla v17.4s, v9.4s, v1.s[1] \n"
"fmla v18.4s, v9.4s, v2.s[1] \n"
"fmla v19.4s, v9.4s, v3.s[1] \n"
"fmla v20.4s, v9.4s, v4.s[1] \n"
"fmla v21.4s, v9.4s, v5.s[1] \n"
"fmla v22.4s, v9.4s, v6.s[1] \n"
"fmla v23.4s, v9.4s, v7.s[1] \n"
"fmla v16.4s, v10.4s, v0.s[2] \n"
"fmla v17.4s, v10.4s, v1.s[2] \n"
"fmla v18.4s, v10.4s, v2.s[2] \n"
"fmla v19.4s, v10.4s, v3.s[2] \n"
"fmla v20.4s, v10.4s, v4.s[2] \n"
"fmla v21.4s, v10.4s, v5.s[2] \n"
"fmla v22.4s, v10.4s, v6.s[2] \n"
"fmla v23.4s, v10.4s, v7.s[2] \n"
"subs %w0, %w0, #1 \n"
"fmla v16.4s, v11.4s, v0.s[3] \n"
"fmla v17.4s, v11.4s, v1.s[3] \n"
"fmla v18.4s, v11.4s, v2.s[3] \n"
"fmla v19.4s, v11.4s, v3.s[3] \n"
"fmla v20.4s, v11.4s, v4.s[3] \n"
"fmla v21.4s, v11.4s, v5.s[3] \n"
"fmla v22.4s, v11.4s, v6.s[3] \n"
"fmla v23.4s, v11.4s, v7.s[3] \n"
"bne 0b \n"
"st1 {v16.4s, v17.4s, v18.4s, v19.4s}, [%1], #64 \n"
"st1 {v20.4s, v21.4s, v22.4s, v23.4s}, [%1], #64 \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(tmpptr), // %2
"=r"(kptr0) // %3
: "0"(nn),
"1"(outptr0),
"2"(tmpptr),
"3"(kptr0),
"r"(biasptr) // %8
: "cc", "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23");
#else
asm volatile(
"vld1.f32 {d0-d1}, [%8] \n"
"vmov q8, q0 \n"
"vmov q9, q0 \n"
"vmov q10, q0 \n"
"vmov q11, q0 \n"
"vmov q12, q0 \n"
"vmov q13, q0 \n"
"vmov q14, q0 \n"
"vmov q15, q0 \n"
"0: \n"
"pld [%2, #512] \n"
"vldm %2!, {d0-d7} \n"
"pld [%3, #512] \n"
"vldm %3!, {d8-d15} \n"
"vmla.f32 q8, q4, d0[0] \n"
"vmla.f32 q9, q4, d0[1] \n"
"vmla.f32 q10, q4, d1[0] \n"
"vmla.f32 q11, q4, d1[1] \n"
"vmla.f32 q12, q4, d2[0] \n"
"vmla.f32 q13, q4, d2[1] \n"
"vmla.f32 q14, q4, d3[0] \n"
"vmla.f32 q15, q4, d3[1] \n"
"vmla.f32 q8, q5, d4[0] \n"
"vmla.f32 q9, q5, d4[1] \n"
"vmla.f32 q10, q5, d5[0] \n"
"vmla.f32 q11, q5, d5[1] \n"
"vmla.f32 q12, q5, d6[0] \n"
"vmla.f32 q13, q5, d6[1] \n"
"vmla.f32 q14, q5, d7[0] \n"
"vmla.f32 q15, q5, d7[1] \n"
"pld [%2, #512] \n"
"vldm %2!, {d0-d7} \n"
"vmla.f32 q8, q6, d0[0] \n"
"vmla.f32 q9, q6, d0[1] \n"
"vmla.f32 q10, q6, d1[0] \n"
"vmla.f32 q11, q6, d1[1] \n"
"vmla.f32 q12, q6, d2[0] \n"
"vmla.f32 q13, q6, d2[1] \n"
"vmla.f32 q14, q6, d3[0] \n"
"vmla.f32 q15, q6, d3[1] \n"
"subs %0, %0, #1 \n"
"vmla.f32 q8, q7, d4[0] \n"
"vmla.f32 q9, q7, d4[1] \n"
"vmla.f32 q10, q7, d5[0] \n"
"vmla.f32 q11, q7, d5[1] \n"
"vmla.f32 q12, q7, d6[0] \n"
"vmla.f32 q13, q7, d6[1] \n"
"vmla.f32 q14, q7, d7[0] \n"
"vmla.f32 q15, q7, d7[1] \n"
"bne 0b \n"
"vstm %1!, {d16-d23} \n"
"vstm %1!, {d24-d31} \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(tmpptr), // %2
"=r"(kptr0) // %3
: "0"(nn),
"1"(outptr0),
"2"(tmpptr),
"3"(kptr0),
"r"(biasptr) // %8
: "cc", "memory", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15");
#endif
}
for (; i + 3 < size; i += 4)
{
#if __aarch64__
const float* tmpptr = tmp.channel(i / 12 + (i % 12) / 8 + (i % 12 % 8) / 4);
const float* kptr0 = kernel.channel(p / 2 + p % 2);
#else
const float* tmpptr = tmp.channel(i / 8 + (i % 8) / 4);
const float* kptr0 = kernel.channel(p);
#endif
int nn = inch * maxk; // inch always > 0
#if __aarch64__
asm volatile(
"ld1 {v0.4s}, [%8] \n"
"mov v16.16b, v0.16b \n"
"mov v17.16b, v0.16b \n"
"mov v18.16b, v0.16b \n"
"mov v19.16b, v0.16b \n"
"0: \n"
"prfm pldl1keep, [%2, #512] \n"
"ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%2], #64 \n" // r0 r1 r2 r3
"prfm pldl1keep, [%3, #512] \n"
"ld1 {v8.4s, v9.4s, v10.4s, v11.4s}, [%3], #64 \n" // w0123
"fmla v16.4s, v8.4s, v0.s[0] \n"
"fmla v17.4s, v8.4s, v1.s[0] \n"
"fmla v18.4s, v8.4s, v2.s[0] \n"
"fmla v19.4s, v8.4s, v3.s[0] \n"
"fmla v16.4s, v9.4s, v0.s[1] \n"
"fmla v17.4s, v9.4s, v1.s[1] \n"
"fmla v18.4s, v9.4s, v2.s[1] \n"
"fmla v19.4s, v9.4s, v3.s[1] \n"
"fmla v16.4s, v10.4s, v0.s[2] \n"
"fmla v17.4s, v10.4s, v1.s[2] \n"
"fmla v18.4s, v10.4s, v2.s[2] \n"
"fmla v19.4s, v10.4s, v3.s[2] \n"
"subs %w0, %w0, #1 \n"
"fmla v16.4s, v11.4s, v0.s[3] \n"
"fmla v17.4s, v11.4s, v1.s[3] \n"
"fmla v18.4s, v11.4s, v2.s[3] \n"
"fmla v19.4s, v11.4s, v3.s[3] \n"
"bne 0b \n"
"st1 {v16.4s, v17.4s, v18.4s, v19.4s}, [%1], #64 \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(tmpptr), // %2
"=r"(kptr0) // %3
: "0"(nn),
"1"(outptr0),
"2"(tmpptr),
"3"(kptr0),
"r"(biasptr) // %8
: "cc", "memory", "v0", "v1", "v2", "v3", "v8", "v9", "v10", "v11", "v16", "v17", "v18", "v19");
#else
asm volatile(
"vld1.f32 {d0-d1}, [%8] \n"
"vmov q8, q0 \n"
"vmov q9, q0 \n"
"vmov q10, q0 \n"
"vmov q11, q0 \n"
"0: \n"
"pld [%2, #512] \n"
"vldm %2!, {d0-d7} \n"
"pld [%3, #512] \n"
"vldm %3!, {d8-d15} \n"
"vmla.f32 q8, q4, d0[0] \n"
"vmla.f32 q9, q4, d2[0] \n"
"vmla.f32 q10, q4, d4[0] \n"
"vmla.f32 q11, q4, d6[0] \n"
"vmla.f32 q8, q5, d0[1] \n"
"vmla.f32 q9, q5, d2[1] \n"
"vmla.f32 q10, q5, d4[1] \n"
"vmla.f32 q11, q5, d6[1] \n"
"vmla.f32 q8, q6, d1[0] \n"
"vmla.f32 q9, q6, d3[0] \n"
"vmla.f32 q10, q6, d5[0] \n"
"vmla.f32 q11, q6, d7[0] \n"
"subs %0, %0, #1 \n"
"vmla.f32 q8, q7, d1[1] \n"
"vmla.f32 q9, q7, d3[1] \n"
"vmla.f32 q10, q7, d5[1] \n"
"vmla.f32 q11, q7, d7[1] \n"
"bne 0b \n"
"vstm %1!, {d16-d23} \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(tmpptr), // %2
"=r"(kptr0) // %3
: "0"(nn),
"1"(outptr0),
"2"(tmpptr),
"3"(kptr0),
"r"(biasptr) // %8
: "cc", "memory", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11");
#endif
}
for (; i + 1 < size; i += 2)
{
#if __aarch64__
const float* tmpptr = tmp.channel(i / 12 + (i % 12) / 8 + (i % 12 % 8) / 4 + (i % 12 % 4) / 2);
const float* kptr0 = kernel.channel(p / 2 + p % 2);
#else
const float* tmpptr = tmp.channel(i / 8 + (i % 8) / 4 + (i % 4) / 2);
const float* kptr0 = kernel.channel(p);
#endif
int nn = inch * maxk; // inch always > 0
#if __aarch64__
asm volatile(
"ld1 {v0.4s}, [%8] \n"
"mov v16.16b, v0.16b \n"
"mov v17.16b, v0.16b \n"
"0: \n"
"prfm pldl1keep, [%2, #256] \n"
"ld1 {v0.4s, v1.4s}, [%2], #32 \n" // r0 r1
"prfm pldl1keep, [%3, #512] \n"
"ld1 {v8.4s, v9.4s, v10.4s, v11.4s}, [%3], #64 \n" // w0123
"fmla v16.4s, v8.4s, v0.s[0] \n"
"fmla v17.4s, v8.4s, v1.s[0] \n"
"fmla v16.4s, v9.4s, v0.s[1] \n"
"fmla v17.4s, v9.4s, v1.s[1] \n"
"fmla v16.4s, v10.4s, v0.s[2] \n"
"fmla v17.4s, v10.4s, v1.s[2] \n"
"subs %w0, %w0, #1 \n"
"fmla v16.4s, v11.4s, v0.s[3] \n"
"fmla v17.4s, v11.4s, v1.s[3] \n"
"bne 0b \n"
"st1 {v16.4s, v17.4s}, [%1], #32 \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(tmpptr), // %2
"=r"(kptr0) // %3
: "0"(nn),
"1"(outptr0),
"2"(tmpptr),
"3"(kptr0),
"r"(biasptr) // %8
: "cc", "memory", "v0", "v1", "v8", "v9", "v10", "v11", "v16", "v17");
#else
asm volatile(
"vld1.f32 {d0-d1}, [%8] \n"
"vmov q8, q0 \n"
"vmov q9, q0 \n"
"0: \n"
"pld [%2, #256] \n"
"vld1.f32 {d0-d3}, [%2 :128]! \n"
"pld [%3, #512] \n"
"vldm %3!, {d8-d15} \n"
"vmla.f32 q8, q4, d0[0] \n"
"vmla.f32 q9, q4, d2[0] \n"
"vmla.f32 q8, q5, d0[1] \n"
"vmla.f32 q9, q5, d2[1] \n"
"vmla.f32 q8, q6, d1[0] \n"
"vmla.f32 q9, q6, d3[0] \n"
"subs %0, %0, #1 \n"
"vmla.f32 q8, q7, d1[1] \n"
"vmla.f32 q9, q7, d3[1] \n"
"bne 0b \n"
"vst1.f32 {d16-d19}, [%1 :128]! \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(tmpptr), // %2
"=r"(kptr0) // %3
: "0"(nn),
"1"(outptr0),
"2"(tmpptr),
"3"(kptr0),
"r"(biasptr) // %8
: "cc", "memory", "q0", "q1", "q4", "q5", "q6", "q7", "q8", "q9");
#endif
}
for (; i < size; i++)
{
#if __aarch64__
const float* tmpptr = tmp.channel(i / 12 + (i % 12) / 8 + (i % 12 % 8) / 4 + (i % 12 % 4) / 2 + i % 12 % 2);
const float* kptr0 = kernel.channel(p / 2 + p % 2);
#else
const float* tmpptr = tmp.channel(i / 8 + (i % 8) / 4 + (i % 4) / 2 + i % 2);
const float* kptr0 = kernel.channel(p);
#endif
int nn = inch * maxk; // inch always > 0
#if __aarch64__
asm volatile(
"ld1 {v16.4s}, [%8] \n"
"0: \n"
"prfm pldl1keep, [%2, #128] \n"
"ld1 {v0.4s}, [%2], #16 \n" // r0
"prfm pldl1keep, [%3, #512] \n"
"ld1 {v8.4s, v9.4s, v10.4s, v11.4s}, [%3], #64 \n" // w0123
"fmla v16.4s, v8.4s, v0.s[0] \n"
"fmla v16.4s, v9.4s, v0.s[1] \n"
"subs %w0, %w0, #1 \n"
"fmla v16.4s, v10.4s, v0.s[2] \n"
"fmla v16.4s, v11.4s, v0.s[3] \n"
"bne 0b \n"
"st1 {v16.4s}, [%1], #16 \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(tmpptr), // %2
"=r"(kptr0) // %3
: "0"(nn),
"1"(outptr0),
"2"(tmpptr),
"3"(kptr0),
"r"(biasptr) // %8
: "cc", "memory", "v0", "v8", "v9", "v10", "v11", "v16");
#else
asm volatile(
"vld1.f32 {d16-d17}, [%8] \n"
"0: \n"
"pld [%2, #128] \n"
"vld1.f32 {d0-d1}, [%2 :128]! \n"
"pld [%3, #512] \n"
"vldm %3!, {d8-d15} \n"
"vmla.f32 q8, q4, d0[0] \n"
"vmla.f32 q8, q5, d0[1] \n"
"subs %0, %0, #1 \n"
"vmla.f32 q8, q6, d1[0] \n"
"vmla.f32 q8, q7, d1[1] \n"
"bne 0b \n"
"vst1.f32 {d16-d17}, [%1 :128]! \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(tmpptr), // %2
"=r"(kptr0) // %3
: "0"(nn),
"1"(outptr0),
"2"(tmpptr),
"3"(kptr0),
"r"(biasptr) // %8
: "cc", "memory", "q0", "q4", "q5", "q6", "q7", "q8");
#endif
}
}
}
static void convolution_im2col_sgemm_transform_kernel_pack4_neon(const Mat& _kernel, Mat& kernel_tm, int inch, int outch, int kernel_w, int kernel_h)
{
const int maxk = kernel_w * kernel_h;
// interleave
// src = maxk-inch-outch
// dst = 4b-4a-maxk-inch/4a-outch/4b
Mat kernel = _kernel.reshape(maxk, inch, outch);
#if __aarch64__
kernel_tm.create(32 * maxk, inch / 4, outch / 8 + (outch % 8) / 4);
#else
kernel_tm.create(16 * maxk, inch / 4, outch / 4);
#endif
int q = 0;
#if __aarch64__
for (; q + 7 < outch; q += 8)
{
const Mat k0 = kernel.channel(q);
const Mat k1 = kernel.channel(q + 1);
const Mat k2 = kernel.channel(q + 2);
const Mat k3 = kernel.channel(q + 3);
const Mat k4 = kernel.channel(q + 4);
const Mat k5 = kernel.channel(q + 5);
const Mat k6 = kernel.channel(q + 6);
const Mat k7 = kernel.channel(q + 7);
float* g00 = kernel_tm.channel(q / 8);
for (int p = 0; p + 3 < inch; p += 4)
{
const float* k00 = k0.row(p);
const float* k01 = k0.row(p + 1);
const float* k02 = k0.row(p + 2);
const float* k03 = k0.row(p + 3);
const float* k10 = k1.row(p);
const float* k11 = k1.row(p + 1);
const float* k12 = k1.row(p + 2);
const float* k13 = k1.row(p + 3);
const float* k20 = k2.row(p);
const float* k21 = k2.row(p + 1);
const float* k22 = k2.row(p + 2);
const float* k23 = k2.row(p + 3);
const float* k30 = k3.row(p);
const float* k31 = k3.row(p + 1);
const float* k32 = k3.row(p + 2);
const float* k33 = k3.row(p + 3);
const float* k40 = k4.row(p);
const float* k41 = k4.row(p + 1);
const float* k42 = k4.row(p + 2);
const float* k43 = k4.row(p + 3);
const float* k50 = k5.row(p);
const float* k51 = k5.row(p + 1);
const float* k52 = k5.row(p + 2);
const float* k53 = k5.row(p + 3);
const float* k60 = k6.row(p);
const float* k61 = k6.row(p + 1);
const float* k62 = k6.row(p + 2);
const float* k63 = k6.row(p + 3);
const float* k70 = k7.row(p);
const float* k71 = k7.row(p + 1);
const float* k72 = k7.row(p + 2);
const float* k73 = k7.row(p + 3);
for (int k = 0; k < maxk; k++)
{
g00[0] = k00[k];
g00[1] = k10[k];
g00[2] = k20[k];
g00[3] = k30[k];
g00[4] = k40[k];
g00[5] = k50[k];
g00[6] = k60[k];
g00[7] = k70[k];
g00[8] = k01[k];
g00[9] = k11[k];
g00[10] = k21[k];
g00[11] = k31[k];
g00[12] = k41[k];
g00[13] = k51[k];
g00[14] = k61[k];
g00[15] = k71[k];
g00[16] = k02[k];
g00[17] = k12[k];
g00[18] = k22[k];
g00[19] = k32[k];
g00[20] = k42[k];
g00[21] = k52[k];
g00[22] = k62[k];
g00[23] = k72[k];
g00[24] = k03[k];
g00[25] = k13[k];
g00[26] = k23[k];
g00[27] = k33[k];
g00[28] = k43[k];
g00[29] = k53[k];
g00[30] = k63[k];
g00[31] = k73[k];
g00 += 32;
}
}
}
#endif // __aarch64__
for (; q + 3 < outch; q += 4)
{
const Mat k0 = kernel.channel(q);
const Mat k1 = kernel.channel(q + 1);
const Mat k2 = kernel.channel(q + 2);
const Mat k3 = kernel.channel(q + 3);
#if __aarch64__
float* g00 = kernel_tm.channel(q / 8 + (q % 8) / 4);
#else
float* g00 = kernel_tm.channel(q / 4);
#endif
for (int p = 0; p + 3 < inch; p += 4)
{
const float* k00 = k0.row(p);
const float* k01 = k0.row(p + 1);
const float* k02 = k0.row(p + 2);
const float* k03 = k0.row(p + 3);
const float* k10 = k1.row(p);
const float* k11 = k1.row(p + 1);
const float* k12 = k1.row(p + 2);
const float* k13 = k1.row(p + 3);
const float* k20 = k2.row(p);
const float* k21 = k2.row(p + 1);
const float* k22 = k2.row(p + 2);
const float* k23 = k2.row(p + 3);
const float* k30 = k3.row(p);
const float* k31 = k3.row(p + 1);
const float* k32 = k3.row(p + 2);
const float* k33 = k3.row(p + 3);
for (int k = 0; k < maxk; k++)
{
g00[0] = k00[k];
g00[1] = k10[k];
g00[2] = k20[k];
g00[3] = k30[k];
g00[4] = k01[k];
g00[5] = k11[k];
g00[6] = k21[k];
g00[7] = k31[k];
g00[8] = k02[k];
g00[9] = k12[k];
g00[10] = k22[k];
g00[11] = k32[k];
g00[12] = k03[k];
g00[13] = k13[k];
g00[14] = k23[k];
g00[15] = k33[k];
g00 += 16;
}
}
}
}
static void convolution_im2col_sgemm_pack4_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel, const Mat& _bias, int kernel_w, int kernel_h, int dilation_w, int dilation_h, int stride_w, 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;
const int size = outw * outh;
const int maxk = kernel_w * kernel_h;
// im2col
Mat bottom_im2col(size, maxk, inch, 16u, 4, opt.workspace_allocator);
{
const int gap = (w * stride_h - outw * stride_w) * 4;
#pragma omp parallel for num_threads(opt.num_threads)
for (int p = 0; p < inch; p++)
{
const Mat img = bottom_blob.channel(p);
float* ptr = bottom_im2col.channel(p);
for (int u = 0; u < kernel_h; u++)
{
for (int v = 0; v < kernel_w; v++)
{
const float* sptr = img.row<const float>(dilation_h * u) + dilation_w * v * 4;
for (int i = 0; i < outh; i++)
{
int j = 0;
for (; j + 3 < outw; j += 4)
{
float32x4_t _val0 = vld1q_f32(sptr);
float32x4_t _val1 = vld1q_f32(sptr + stride_w * 4);
float32x4_t _val2 = vld1q_f32(sptr + stride_w * 8);
float32x4_t _val3 = vld1q_f32(sptr + stride_w * 12);
vst1q_f32(ptr, _val0);
vst1q_f32(ptr + 4, _val1);
vst1q_f32(ptr + 8, _val2);
vst1q_f32(ptr + 12, _val3);
sptr += stride_w * 16;
ptr += 16;
}
for (; j + 1 < outw; j += 2)
{
float32x4_t _val0 = vld1q_f32(sptr);
float32x4_t _val1 = vld1q_f32(sptr + stride_w * 4);
vst1q_f32(ptr, _val0);
vst1q_f32(ptr + 4, _val1);
sptr += stride_w * 8;
ptr += 8;
}
for (; j < outw; j++)
{
float32x4_t _val = vld1q_f32(sptr);
vst1q_f32(ptr, _val);
sptr += stride_w * 4;
ptr += 4;
}
sptr += gap;
}
}
}
}
}
im2col_sgemm_pack4_neon(bottom_im2col, top_blob, kernel, _bias, opt);
}
|
morphology.c | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% M M OOO RRRR PPPP H H OOO L OOO GGGG Y Y %
% MM MM O O R R P P H H O O L O O G Y Y %
% M M M O O RRRR PPPP HHHHH O O L O O G GGG Y %
% M M O O R R P H H O O L O O G G Y %
% M M OOO R R P H H OOO LLLLL OOO GGG Y %
% %
% %
% MagickCore Morphology Methods %
% %
% Software Design %
% Anthony Thyssen %
% January 2010 %
% %
% %
% Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% https://www.imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Morphology is the application of various kernels, of any size or shape, to an
% image in various ways (typically binary, but not always).
%
% Convolution (weighted sum or average) is just one specific type of
% morphology. Just one that is very common for image bluring and sharpening
% effects. Not only 2D Gaussian blurring, but also 2-pass 1D Blurring.
%
% This module provides not only a general morphology function, and the ability
% to apply more advanced or iterative morphologies, but also functions for the
% generation of many different types of kernel arrays from user supplied
% arguments. Prehaps even the generation of a kernel from a small image.
*/
/*
Include declarations.
*/
#include "MagickCore/studio.h"
#include "MagickCore/artifact.h"
#include "MagickCore/cache-view.h"
#include "MagickCore/channel.h"
#include "MagickCore/color-private.h"
#include "MagickCore/enhance.h"
#include "MagickCore/exception.h"
#include "MagickCore/exception-private.h"
#include "MagickCore/gem.h"
#include "MagickCore/gem-private.h"
#include "MagickCore/image.h"
#include "MagickCore/image-private.h"
#include "MagickCore/linked-list.h"
#include "MagickCore/list.h"
#include "MagickCore/magick.h"
#include "MagickCore/memory_.h"
#include "MagickCore/memory-private.h"
#include "MagickCore/monitor-private.h"
#include "MagickCore/morphology.h"
#include "MagickCore/morphology-private.h"
#include "MagickCore/option.h"
#include "MagickCore/pixel-accessor.h"
#include "MagickCore/pixel-private.h"
#include "MagickCore/prepress.h"
#include "MagickCore/quantize.h"
#include "MagickCore/resource_.h"
#include "MagickCore/registry.h"
#include "MagickCore/semaphore.h"
#include "MagickCore/splay-tree.h"
#include "MagickCore/statistic.h"
#include "MagickCore/string_.h"
#include "MagickCore/string-private.h"
#include "MagickCore/thread-private.h"
#include "MagickCore/token.h"
#include "MagickCore/utility.h"
#include "MagickCore/utility-private.h"
/*
Other global definitions used by module.
*/
#define Minimize(assign,value) assign=MagickMin(assign,value)
#define Maximize(assign,value) assign=MagickMax(assign,value)
/* Integer Factorial Function - for a Binomial kernel */
#if 1
static inline size_t fact(size_t n)
{
size_t f,l;
for(f=1, l=2; l <= n; f=f*l, l++);
return(f);
}
#elif 1 /* glibc floating point alternatives */
#define fact(n) ((size_t)tgamma((double)n+1))
#else
#define fact(n) ((size_t)lgamma((double)n+1))
#endif
/* Currently these are only internal to this module */
static void
CalcKernelMetaData(KernelInfo *),
ExpandMirrorKernelInfo(KernelInfo *),
ExpandRotateKernelInfo(KernelInfo *, const double),
RotateKernelInfo(KernelInfo *, double);
/* Quick function to find last kernel in a kernel list */
static inline KernelInfo *LastKernelInfo(KernelInfo *kernel)
{
while (kernel->next != (KernelInfo *) NULL)
kernel=kernel->next;
return(kernel);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% A c q u i r e K e r n e l I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AcquireKernelInfo() takes the given string (generally supplied by the
% user) and converts it into a Morphology/Convolution Kernel. This allows
% users to specify a kernel from a number of pre-defined kernels, or to fully
% specify their own kernel for a specific Convolution or Morphology
% Operation.
%
% The kernel so generated can be any rectangular array of floating point
% values (doubles) with the 'control point' or 'pixel being affected'
% anywhere within that array of values.
%
% Previously IM was restricted to a square of odd size using the exact
% center as origin, this is no longer the case, and any rectangular kernel
% with any value being declared the origin. This in turn allows the use of
% highly asymmetrical kernels.
%
% The floating point values in the kernel can also include a special value
% known as 'nan' or 'not a number' to indicate that this value is not part
% of the kernel array. This allows you to shaped the kernel within its
% rectangular area. That is 'nan' values provide a 'mask' for the kernel
% shape. However at least one non-nan value must be provided for correct
% working of a kernel.
%
% The returned kernel should be freed using the DestroyKernelInfo() when you
% are finished with it. Do not free this memory yourself.
%
% Input kernel defintion strings can consist of any of three types.
%
% "name:args[[@><]"
% Select from one of the built in kernels, using the name and
% geometry arguments supplied. See AcquireKernelBuiltIn()
%
% "WxH[+X+Y][@><]:num, num, num ..."
% a kernel of size W by H, with W*H floating point numbers following.
% the 'center' can be optionally be defined at +X+Y (such that +0+0
% is top left corner). If not defined the pixel in the center, for
% odd sizes, or to the immediate top or left of center for even sizes
% is automatically selected.
%
% "num, num, num, num, ..."
% list of floating point numbers defining an 'old style' odd sized
% square kernel. At least 9 values should be provided for a 3x3
% square kernel, 25 for a 5x5 square kernel, 49 for 7x7, etc.
% Values can be space or comma separated. This is not recommended.
%
% You can define a 'list of kernels' which can be used by some morphology
% operators A list is defined as a semi-colon separated list kernels.
%
% " kernel ; kernel ; kernel ; "
%
% Any extra ';' characters, at start, end or between kernel defintions are
% simply ignored.
%
% The special flags will expand a single kernel, into a list of rotated
% kernels. A '@' flag will expand a 3x3 kernel into a list of 45-degree
% cyclic rotations, while a '>' will generate a list of 90-degree rotations.
% The '<' also exands using 90-degree rotates, but giving a 180-degree
% reflected kernel before the +/- 90-degree rotations, which can be important
% for Thinning operations.
%
% Note that 'name' kernels will start with an alphabetic character while the
% new kernel specification has a ':' character in its specification string.
% If neither is the case, it is assumed an old style of a simple list of
% numbers generating a odd-sized square kernel has been given.
%
% The format of the AcquireKernal method is:
%
% KernelInfo *AcquireKernelInfo(const char *kernel_string)
%
% A description of each parameter follows:
%
% o kernel_string: the Morphology/Convolution kernel wanted.
%
*/
/* This was separated so that it could be used as a separate
** array input handling function, such as for -color-matrix
*/
static KernelInfo *ParseKernelArray(const char *kernel_string)
{
KernelInfo
*kernel;
char
token[MagickPathExtent];
const char
*p,
*end;
register ssize_t
i;
double
nan = sqrt((double)-1.0); /* Special Value : Not A Number */
MagickStatusType
flags;
GeometryInfo
args;
kernel=(KernelInfo *) AcquireQuantumMemory(1,sizeof(*kernel));
if (kernel == (KernelInfo *) NULL)
return(kernel);
(void) ResetMagickMemory(kernel,0,sizeof(*kernel));
kernel->minimum = kernel->maximum = kernel->angle = 0.0;
kernel->negative_range = kernel->positive_range = 0.0;
kernel->type = UserDefinedKernel;
kernel->next = (KernelInfo *) NULL;
kernel->signature=MagickCoreSignature;
if (kernel_string == (const char *) NULL)
return(kernel);
/* find end of this specific kernel definition string */
end = strchr(kernel_string, ';');
if ( end == (char *) NULL )
end = strchr(kernel_string, '\0');
/* clear flags - for Expanding kernel lists thorugh rotations */
flags = NoValue;
/* Has a ':' in argument - New user kernel specification
FUTURE: this split on ':' could be done by StringToken()
*/
p = strchr(kernel_string, ':');
if ( p != (char *) NULL && p < end)
{
/* ParseGeometry() needs the geometry separated! -- Arrgghh */
memcpy(token, kernel_string, (size_t) (p-kernel_string));
token[p-kernel_string] = '\0';
SetGeometryInfo(&args);
flags = ParseGeometry(token, &args);
/* Size handling and checks of geometry settings */
if ( (flags & WidthValue) == 0 ) /* if no width then */
args.rho = args.sigma; /* then width = height */
if ( args.rho < 1.0 ) /* if width too small */
args.rho = 1.0; /* then width = 1 */
if ( args.sigma < 1.0 ) /* if height too small */
args.sigma = args.rho; /* then height = width */
kernel->width = (size_t)args.rho;
kernel->height = (size_t)args.sigma;
/* Offset Handling and Checks */
if ( args.xi < 0.0 || args.psi < 0.0 )
return(DestroyKernelInfo(kernel));
kernel->x = ((flags & XValue)!=0) ? (ssize_t)args.xi
: (ssize_t) (kernel->width-1)/2;
kernel->y = ((flags & YValue)!=0) ? (ssize_t)args.psi
: (ssize_t) (kernel->height-1)/2;
if ( kernel->x >= (ssize_t) kernel->width ||
kernel->y >= (ssize_t) kernel->height )
return(DestroyKernelInfo(kernel));
p++; /* advance beyond the ':' */
}
else
{ /* ELSE - Old old specification, forming odd-square kernel */
/* count up number of values given */
p=(const char *) kernel_string;
while ((isspace((int) ((unsigned char) *p)) != 0) || (*p == '\''))
p++; /* ignore "'" chars for convolve filter usage - Cristy */
for (i=0; p < end; i++)
{
GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
GetNextToken(p,&p,MagickPathExtent,token);
}
/* set the size of the kernel - old sized square */
kernel->width = kernel->height= (size_t) sqrt((double) i+1.0);
kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2;
p=(const char *) kernel_string;
while ((isspace((int) ((unsigned char) *p)) != 0) || (*p == '\''))
p++; /* ignore "'" chars for convolve filter usage - Cristy */
}
/* Read in the kernel values from rest of input string argument */
kernel->values=(MagickRealType *) MagickAssumeAligned(AcquireAlignedMemory(
kernel->width,kernel->height*sizeof(*kernel->values)));
if (kernel->values == (MagickRealType *) NULL)
return(DestroyKernelInfo(kernel));
kernel->minimum=MagickMaximumValue;
kernel->maximum=(-MagickMaximumValue);
kernel->negative_range = kernel->positive_range = 0.0;
for (i=0; (i < (ssize_t) (kernel->width*kernel->height)) && (p < end); i++)
{
GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
GetNextToken(p,&p,MagickPathExtent,token);
if ( LocaleCompare("nan",token) == 0
|| LocaleCompare("-",token) == 0 ) {
kernel->values[i] = nan; /* this value is not part of neighbourhood */
}
else {
kernel->values[i] = StringToDouble(token,(char **) NULL);
( kernel->values[i] < 0)
? ( kernel->negative_range += kernel->values[i] )
: ( kernel->positive_range += kernel->values[i] );
Minimize(kernel->minimum, kernel->values[i]);
Maximize(kernel->maximum, kernel->values[i]);
}
}
/* sanity check -- no more values in kernel definition */
GetNextToken(p,&p,MagickPathExtent,token);
if ( *token != '\0' && *token != ';' && *token != '\'' )
return(DestroyKernelInfo(kernel));
#if 0
/* this was the old method of handling a incomplete kernel */
if ( i < (ssize_t) (kernel->width*kernel->height) ) {
Minimize(kernel->minimum, kernel->values[i]);
Maximize(kernel->maximum, kernel->values[i]);
for ( ; i < (ssize_t) (kernel->width*kernel->height); i++)
kernel->values[i]=0.0;
}
#else
/* Number of values for kernel was not enough - Report Error */
if ( i < (ssize_t) (kernel->width*kernel->height) )
return(DestroyKernelInfo(kernel));
#endif
/* check that we recieved at least one real (non-nan) value! */
if (kernel->minimum == MagickMaximumValue)
return(DestroyKernelInfo(kernel));
if ( (flags & AreaValue) != 0 ) /* '@' symbol in kernel size */
ExpandRotateKernelInfo(kernel, 45.0); /* cyclic rotate 3x3 kernels */
else if ( (flags & GreaterValue) != 0 ) /* '>' symbol in kernel args */
ExpandRotateKernelInfo(kernel, 90.0); /* 90 degree rotate of kernel */
else if ( (flags & LessValue) != 0 ) /* '<' symbol in kernel args */
ExpandMirrorKernelInfo(kernel); /* 90 degree mirror rotate */
return(kernel);
}
static KernelInfo *ParseKernelName(const char *kernel_string,
ExceptionInfo *exception)
{
char
token[MagickPathExtent];
const char
*p,
*end;
GeometryInfo
args;
KernelInfo
*kernel;
MagickStatusType
flags;
ssize_t
type;
/* Parse special 'named' kernel */
GetNextToken(kernel_string,&p,MagickPathExtent,token);
type=ParseCommandOption(MagickKernelOptions,MagickFalse,token);
if ( type < 0 || type == UserDefinedKernel )
return((KernelInfo *) NULL); /* not a valid named kernel */
while (((isspace((int) ((unsigned char) *p)) != 0) ||
(*p == ',') || (*p == ':' )) && (*p != '\0') && (*p != ';'))
p++;
end = strchr(p, ';'); /* end of this kernel defintion */
if ( end == (char *) NULL )
end = strchr(p, '\0');
/* ParseGeometry() needs the geometry separated! -- Arrgghh */
memcpy(token, p, (size_t) (end-p));
token[end-p] = '\0';
SetGeometryInfo(&args);
flags = ParseGeometry(token, &args);
#if 0
/* For Debugging Geometry Input */
(void) FormatLocaleFile(stderr, "Geometry = 0x%04X : %lg x %lg %+lg %+lg\n",
flags, args.rho, args.sigma, args.xi, args.psi );
#endif
/* special handling of missing values in input string */
switch( type ) {
/* Shape Kernel Defaults */
case UnityKernel:
if ( (flags & WidthValue) == 0 )
args.rho = 1.0; /* Default scale = 1.0, zero is valid */
break;
case SquareKernel:
case DiamondKernel:
case OctagonKernel:
case DiskKernel:
case PlusKernel:
case CrossKernel:
if ( (flags & HeightValue) == 0 )
args.sigma = 1.0; /* Default scale = 1.0, zero is valid */
break;
case RingKernel:
if ( (flags & XValue) == 0 )
args.xi = 1.0; /* Default scale = 1.0, zero is valid */
break;
case RectangleKernel: /* Rectangle - set size defaults */
if ( (flags & WidthValue) == 0 ) /* if no width then */
args.rho = args.sigma; /* then width = height */
if ( args.rho < 1.0 ) /* if width too small */
args.rho = 3; /* then width = 3 */
if ( args.sigma < 1.0 ) /* if height too small */
args.sigma = args.rho; /* then height = width */
if ( (flags & XValue) == 0 ) /* center offset if not defined */
args.xi = (double)(((ssize_t)args.rho-1)/2);
if ( (flags & YValue) == 0 )
args.psi = (double)(((ssize_t)args.sigma-1)/2);
break;
/* Distance Kernel Defaults */
case ChebyshevKernel:
case ManhattanKernel:
case OctagonalKernel:
case EuclideanKernel:
if ( (flags & HeightValue) == 0 ) /* no distance scale */
args.sigma = 100.0; /* default distance scaling */
else if ( (flags & AspectValue ) != 0 ) /* '!' flag */
args.sigma = QuantumRange/(args.sigma+1); /* maximum pixel distance */
else if ( (flags & PercentValue ) != 0 ) /* '%' flag */
args.sigma *= QuantumRange/100.0; /* percentage of color range */
break;
default:
break;
}
kernel = AcquireKernelBuiltIn((KernelInfoType)type, &args, exception);
if ( kernel == (KernelInfo *) NULL )
return(kernel);
/* global expand to rotated kernel list - only for single kernels */
if ( kernel->next == (KernelInfo *) NULL ) {
if ( (flags & AreaValue) != 0 ) /* '@' symbol in kernel args */
ExpandRotateKernelInfo(kernel, 45.0);
else if ( (flags & GreaterValue) != 0 ) /* '>' symbol in kernel args */
ExpandRotateKernelInfo(kernel, 90.0);
else if ( (flags & LessValue) != 0 ) /* '<' symbol in kernel args */
ExpandMirrorKernelInfo(kernel);
}
return(kernel);
}
MagickExport KernelInfo *AcquireKernelInfo(const char *kernel_string,
ExceptionInfo *exception)
{
KernelInfo
*kernel,
*new_kernel;
char
*kernel_cache,
token[MagickPathExtent];
const char
*p;
if (kernel_string == (const char *) NULL)
return(ParseKernelArray(kernel_string));
p=kernel_string;
kernel_cache=(char *) NULL;
if (*kernel_string == '@')
{
kernel_cache=FileToString(kernel_string+1,~0UL,exception);
if (kernel_cache == (char *) NULL)
return((KernelInfo *) NULL);
p=(const char *) kernel_cache;
}
kernel=NULL;
while (GetNextToken(p,(const char **) NULL,MagickPathExtent,token), *token != '\0')
{
/* ignore extra or multiple ';' kernel separators */
if (*token != ';')
{
/* tokens starting with alpha is a Named kernel */
if (isalpha((int) ((unsigned char) *token)) != 0)
new_kernel=ParseKernelName(p,exception);
else /* otherwise a user defined kernel array */
new_kernel=ParseKernelArray(p);
/* Error handling -- this is not proper error handling! */
if (new_kernel == (KernelInfo *) NULL)
{
if (kernel != (KernelInfo *) NULL)
kernel=DestroyKernelInfo(kernel);
return((KernelInfo *) NULL);
}
/* initialise or append the kernel list */
if (kernel == (KernelInfo *) NULL)
kernel=new_kernel;
else
LastKernelInfo(kernel)->next=new_kernel;
}
/* look for the next kernel in list */
p=strchr(p,';');
if (p == (char *) NULL)
break;
p++;
}
if (kernel_cache != (char *) NULL)
kernel_cache=DestroyString(kernel_cache);
return(kernel);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% A c q u i r e K e r n e l B u i l t I n %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AcquireKernelBuiltIn() returned one of the 'named' built-in types of
% kernels used for special purposes such as gaussian blurring, skeleton
% pruning, and edge distance determination.
%
% They take a KernelType, and a set of geometry style arguments, which were
% typically decoded from a user supplied string, or from a more complex
% Morphology Method that was requested.
%
% The format of the AcquireKernalBuiltIn method is:
%
% KernelInfo *AcquireKernelBuiltIn(const KernelInfoType type,
% const GeometryInfo args)
%
% A description of each parameter follows:
%
% o type: the pre-defined type of kernel wanted
%
% o args: arguments defining or modifying the kernel
%
% Convolution Kernels
%
% Unity
% The a No-Op or Scaling single element kernel.
%
% Gaussian:{radius},{sigma}
% Generate a two-dimensional gaussian kernel, as used by -gaussian.
% The sigma for the curve is required. The resulting kernel is
% normalized,
%
% If 'sigma' is zero, you get a single pixel on a field of zeros.
%
% NOTE: that the 'radius' is optional, but if provided can limit (clip)
% the final size of the resulting kernel to a square 2*radius+1 in size.
% The radius should be at least 2 times that of the sigma value, or
% sever clipping and aliasing may result. If not given or set to 0 the
% radius will be determined so as to produce the best minimal error
% result, which is usally much larger than is normally needed.
%
% LoG:{radius},{sigma}
% "Laplacian of a Gaussian" or "Mexician Hat" Kernel.
% The supposed ideal edge detection, zero-summing kernel.
%
% An alturnative to this kernel is to use a "DoG" with a sigma ratio of
% approx 1.6 (according to wikipedia).
%
% DoG:{radius},{sigma1},{sigma2}
% "Difference of Gaussians" Kernel.
% As "Gaussian" but with a gaussian produced by 'sigma2' subtracted
% from the gaussian produced by 'sigma1'. Typically sigma2 > sigma1.
% The result is a zero-summing kernel.
%
% Blur:{radius},{sigma}[,{angle}]
% Generates a 1 dimensional or linear gaussian blur, at the angle given
% (current restricted to orthogonal angles). If a 'radius' is given the
% kernel is clipped to a width of 2*radius+1. Kernel can be rotated
% by a 90 degree angle.
%
% If 'sigma' is zero, you get a single pixel on a field of zeros.
%
% Note that two convolutions with two "Blur" kernels perpendicular to
% each other, is equivalent to a far larger "Gaussian" kernel with the
% same sigma value, However it is much faster to apply. This is how the
% "-blur" operator actually works.
%
% Comet:{width},{sigma},{angle}
% Blur in one direction only, much like how a bright object leaves
% a comet like trail. The Kernel is actually half a gaussian curve,
% Adding two such blurs in opposite directions produces a Blur Kernel.
% Angle can be rotated in multiples of 90 degrees.
%
% Note that the first argument is the width of the kernel and not the
% radius of the kernel.
%
% Binomial:[{radius}]
% Generate a discrete kernel using a 2 dimentional Pascel's Triangle
% of values. Used for special forma of image filters.
%
% # Still to be implemented...
% #
% # Filter2D
% # Filter1D
% # Set kernel values using a resize filter, and given scale (sigma)
% # Cylindrical or Linear. Is this possible with an image?
% #
%
% Named Constant Convolution Kernels
%
% All these are unscaled, zero-summing kernels by default. As such for
% non-HDRI version of ImageMagick some form of normalization, user scaling,
% and biasing the results is recommended, to prevent the resulting image
% being 'clipped'.
%
% The 3x3 kernels (most of these) can be circularly rotated in multiples of
% 45 degrees to generate the 8 angled varients of each of the kernels.
%
% Laplacian:{type}
% Discrete Lapacian Kernels, (without normalization)
% Type 0 : 3x3 with center:8 surounded by -1 (8 neighbourhood)
% Type 1 : 3x3 with center:4 edge:-1 corner:0 (4 neighbourhood)
% Type 2 : 3x3 with center:4 edge:1 corner:-2
% Type 3 : 3x3 with center:4 edge:-2 corner:1
% Type 5 : 5x5 laplacian
% Type 7 : 7x7 laplacian
% Type 15 : 5x5 LoG (sigma approx 1.4)
% Type 19 : 9x9 LoG (sigma approx 1.4)
%
% Sobel:{angle}
% Sobel 'Edge' convolution kernel (3x3)
% | -1, 0, 1 |
% | -2, 0,-2 |
% | -1, 0, 1 |
%
% Roberts:{angle}
% Roberts convolution kernel (3x3)
% | 0, 0, 0 |
% | -1, 1, 0 |
% | 0, 0, 0 |
%
% Prewitt:{angle}
% Prewitt Edge convolution kernel (3x3)
% | -1, 0, 1 |
% | -1, 0, 1 |
% | -1, 0, 1 |
%
% Compass:{angle}
% Prewitt's "Compass" convolution kernel (3x3)
% | -1, 1, 1 |
% | -1,-2, 1 |
% | -1, 1, 1 |
%
% Kirsch:{angle}
% Kirsch's "Compass" convolution kernel (3x3)
% | -3,-3, 5 |
% | -3, 0, 5 |
% | -3,-3, 5 |
%
% FreiChen:{angle}
% Frei-Chen Edge Detector is based on a kernel that is similar to
% the Sobel Kernel, but is designed to be isotropic. That is it takes
% into account the distance of the diagonal in the kernel.
%
% | 1, 0, -1 |
% | sqrt(2), 0, -sqrt(2) |
% | 1, 0, -1 |
%
% FreiChen:{type},{angle}
%
% Frei-Chen Pre-weighted kernels...
%
% Type 0: default un-nomalized version shown above.
%
% Type 1: Orthogonal Kernel (same as type 11 below)
% | 1, 0, -1 |
% | sqrt(2), 0, -sqrt(2) | / 2*sqrt(2)
% | 1, 0, -1 |
%
% Type 2: Diagonal form of Kernel...
% | 1, sqrt(2), 0 |
% | sqrt(2), 0, -sqrt(2) | / 2*sqrt(2)
% | 0, -sqrt(2) -1 |
%
% However this kernel is als at the heart of the FreiChen Edge Detection
% Process which uses a set of 9 specially weighted kernel. These 9
% kernels not be normalized, but directly applied to the image. The
% results is then added together, to produce the intensity of an edge in
% a specific direction. The square root of the pixel value can then be
% taken as the cosine of the edge, and at least 2 such runs at 90 degrees
% from each other, both the direction and the strength of the edge can be
% determined.
%
% Type 10: All 9 of the following pre-weighted kernels...
%
% Type 11: | 1, 0, -1 |
% | sqrt(2), 0, -sqrt(2) | / 2*sqrt(2)
% | 1, 0, -1 |
%
% Type 12: | 1, sqrt(2), 1 |
% | 0, 0, 0 | / 2*sqrt(2)
% | 1, sqrt(2), 1 |
%
% Type 13: | sqrt(2), -1, 0 |
% | -1, 0, 1 | / 2*sqrt(2)
% | 0, 1, -sqrt(2) |
%
% Type 14: | 0, 1, -sqrt(2) |
% | -1, 0, 1 | / 2*sqrt(2)
% | sqrt(2), -1, 0 |
%
% Type 15: | 0, -1, 0 |
% | 1, 0, 1 | / 2
% | 0, -1, 0 |
%
% Type 16: | 1, 0, -1 |
% | 0, 0, 0 | / 2
% | -1, 0, 1 |
%
% Type 17: | 1, -2, 1 |
% | -2, 4, -2 | / 6
% | -1, -2, 1 |
%
% Type 18: | -2, 1, -2 |
% | 1, 4, 1 | / 6
% | -2, 1, -2 |
%
% Type 19: | 1, 1, 1 |
% | 1, 1, 1 | / 3
% | 1, 1, 1 |
%
% The first 4 are for edge detection, the next 4 are for line detection
% and the last is to add a average component to the results.
%
% Using a special type of '-1' will return all 9 pre-weighted kernels
% as a multi-kernel list, so that you can use them directly (without
% normalization) with the special "-set option:morphology:compose Plus"
% setting to apply the full FreiChen Edge Detection Technique.
%
% If 'type' is large it will be taken to be an actual rotation angle for
% the default FreiChen (type 0) kernel. As such FreiChen:45 will look
% like a Sobel:45 but with 'sqrt(2)' instead of '2' values.
%
% WARNING: The above was layed out as per
% http://www.math.tau.ac.il/~turkel/notes/edge_detectors.pdf
% But rotated 90 degrees so direction is from left rather than the top.
% I have yet to find any secondary confirmation of the above. The only
% other source found was actual source code at
% http://ltswww.epfl.ch/~courstiv/exos_labos/sol3.pdf
% Neigher paper defineds the kernels in a way that looks locical or
% correct when taken as a whole.
%
% Boolean Kernels
%
% Diamond:[{radius}[,{scale}]]
% Generate a diamond shaped kernel with given radius to the points.
% Kernel size will again be radius*2+1 square and defaults to radius 1,
% generating a 3x3 kernel that is slightly larger than a square.
%
% Square:[{radius}[,{scale}]]
% Generate a square shaped kernel of size radius*2+1, and defaulting
% to a 3x3 (radius 1).
%
% Octagon:[{radius}[,{scale}]]
% Generate octagonal shaped kernel of given radius and constant scale.
% Default radius is 3 producing a 7x7 kernel. A radius of 1 will result
% in "Diamond" kernel.
%
% Disk:[{radius}[,{scale}]]
% Generate a binary disk, thresholded at the radius given, the radius
% may be a float-point value. Final Kernel size is floor(radius)*2+1
% square. A radius of 5.3 is the default.
%
% NOTE: That a low radii Disk kernels produce the same results as
% many of the previously defined kernels, but differ greatly at larger
% radii. Here is a table of equivalences...
% "Disk:1" => "Diamond", "Octagon:1", or "Cross:1"
% "Disk:1.5" => "Square"
% "Disk:2" => "Diamond:2"
% "Disk:2.5" => "Octagon"
% "Disk:2.9" => "Square:2"
% "Disk:3.5" => "Octagon:3"
% "Disk:4.5" => "Octagon:4"
% "Disk:5.4" => "Octagon:5"
% "Disk:6.4" => "Octagon:6"
% All other Disk shapes are unique to this kernel, but because a "Disk"
% is more circular when using a larger radius, using a larger radius is
% preferred over iterating the morphological operation.
%
% Rectangle:{geometry}
% Simply generate a rectangle of 1's with the size given. You can also
% specify the location of the 'control point', otherwise the closest
% pixel to the center of the rectangle is selected.
%
% Properly centered and odd sized rectangles work the best.
%
% Symbol Dilation Kernels
%
% These kernel is not a good general morphological kernel, but is used
% more for highlighting and marking any single pixels in an image using,
% a "Dilate" method as appropriate.
%
% For the same reasons iterating these kernels does not produce the
% same result as using a larger radius for the symbol.
%
% Plus:[{radius}[,{scale}]]
% Cross:[{radius}[,{scale}]]
% Generate a kernel in the shape of a 'plus' or a 'cross' with
% a each arm the length of the given radius (default 2).
%
% NOTE: "plus:1" is equivalent to a "Diamond" kernel.
%
% Ring:{radius1},{radius2}[,{scale}]
% A ring of the values given that falls between the two radii.
% Defaults to a ring of approximataly 3 radius in a 7x7 kernel.
% This is the 'edge' pixels of the default "Disk" kernel,
% More specifically, "Ring" -> "Ring:2.5,3.5,1.0"
%
% Hit and Miss Kernels
%
% Peak:radius1,radius2
% Find any peak larger than the pixels the fall between the two radii.
% The default ring of pixels is as per "Ring".
% Edges
% Find flat orthogonal edges of a binary shape
% Corners
% Find 90 degree corners of a binary shape
% Diagonals:type
% A special kernel to thin the 'outside' of diagonals
% LineEnds:type
% Find end points of lines (for pruning a skeletion)
% Two types of lines ends (default to both) can be searched for
% Type 0: All line ends
% Type 1: single kernel for 4-conneected line ends
% Type 2: single kernel for simple line ends
% LineJunctions
% Find three line junctions (within a skeletion)
% Type 0: all line junctions
% Type 1: Y Junction kernel
% Type 2: Diagonal T Junction kernel
% Type 3: Orthogonal T Junction kernel
% Type 4: Diagonal X Junction kernel
% Type 5: Orthogonal + Junction kernel
% Ridges:type
% Find single pixel ridges or thin lines
% Type 1: Fine single pixel thick lines and ridges
% Type 2: Find two pixel thick lines and ridges
% ConvexHull
% Octagonal Thickening Kernel, to generate convex hulls of 45 degrees
% Skeleton:type
% Traditional skeleton generating kernels.
% Type 1: Tradional Skeleton kernel (4 connected skeleton)
% Type 2: HIPR2 Skeleton kernel (8 connected skeleton)
% Type 3: Thinning skeleton based on a ressearch paper by
% Dan S. Bloomberg (Default Type)
% ThinSE:type
% A huge variety of Thinning Kernels designed to preserve conectivity.
% many other kernel sets use these kernels as source definitions.
% Type numbers are 41-49, 81-89, 481, and 482 which are based on
% the super and sub notations used in the source research paper.
%
% Distance Measuring Kernels
%
% Different types of distance measuring methods, which are used with the
% a 'Distance' morphology method for generating a gradient based on
% distance from an edge of a binary shape, though there is a technique
% for handling a anti-aliased shape.
%
% See the 'Distance' Morphological Method, for information of how it is
% applied.
%
% Chebyshev:[{radius}][x{scale}[%!]]
% Chebyshev Distance (also known as Tchebychev or Chessboard distance)
% is a value of one to any neighbour, orthogonal or diagonal. One why
% of thinking of it is the number of squares a 'King' or 'Queen' in
% chess needs to traverse reach any other position on a chess board.
% It results in a 'square' like distance function, but one where
% diagonals are given a value that is closer than expected.
%
% Manhattan:[{radius}][x{scale}[%!]]
% Manhattan Distance (also known as Rectilinear, City Block, or the Taxi
% Cab distance metric), it is the distance needed when you can only
% travel in horizontal or vertical directions only. It is the
% distance a 'Rook' in chess would have to travel, and results in a
% diamond like distances, where diagonals are further than expected.
%
% Octagonal:[{radius}][x{scale}[%!]]
% An interleving of Manhatten and Chebyshev metrics producing an
% increasing octagonally shaped distance. Distances matches those of
% the "Octagon" shaped kernel of the same radius. The minimum radius
% and default is 2, producing a 5x5 kernel.
%
% Euclidean:[{radius}][x{scale}[%!]]
% Euclidean distance is the 'direct' or 'as the crow flys' distance.
% However by default the kernel size only has a radius of 1, which
% limits the distance to 'Knight' like moves, with only orthogonal and
% diagonal measurements being correct. As such for the default kernel
% you will get octagonal like distance function.
%
% However using a larger radius such as "Euclidean:4" you will get a
% much smoother distance gradient from the edge of the shape. Especially
% if the image is pre-processed to include any anti-aliasing pixels.
% Of course a larger kernel is slower to use, and not always needed.
%
% The first three Distance Measuring Kernels will only generate distances
% of exact multiples of {scale} in binary images. As such you can use a
% scale of 1 without loosing any information. However you also need some
% scaling when handling non-binary anti-aliased shapes.
%
% The "Euclidean" Distance Kernel however does generate a non-integer
% fractional results, and as such scaling is vital even for binary shapes.
%
*/
MagickExport KernelInfo *AcquireKernelBuiltIn(const KernelInfoType type,
const GeometryInfo *args,ExceptionInfo *exception)
{
KernelInfo
*kernel;
register ssize_t
i;
register ssize_t
u,
v;
double
nan = sqrt((double)-1.0); /* Special Value : Not A Number */
/* Generate a new empty kernel if needed */
kernel=(KernelInfo *) NULL;
switch(type) {
case UndefinedKernel: /* These should not call this function */
case UserDefinedKernel:
assert("Should not call this function" != (char *) NULL);
break;
case LaplacianKernel: /* Named Descrete Convolution Kernels */
case SobelKernel: /* these are defined using other kernels */
case RobertsKernel:
case PrewittKernel:
case CompassKernel:
case KirschKernel:
case FreiChenKernel:
case EdgesKernel: /* Hit and Miss kernels */
case CornersKernel:
case DiagonalsKernel:
case LineEndsKernel:
case LineJunctionsKernel:
case RidgesKernel:
case ConvexHullKernel:
case SkeletonKernel:
case ThinSEKernel:
break; /* A pre-generated kernel is not needed */
#if 0
/* set to 1 to do a compile-time check that we haven't missed anything */
case UnityKernel:
case GaussianKernel:
case DoGKernel:
case LoGKernel:
case BlurKernel:
case CometKernel:
case BinomialKernel:
case DiamondKernel:
case SquareKernel:
case RectangleKernel:
case OctagonKernel:
case DiskKernel:
case PlusKernel:
case CrossKernel:
case RingKernel:
case PeaksKernel:
case ChebyshevKernel:
case ManhattanKernel:
case OctangonalKernel:
case EuclideanKernel:
#else
default:
#endif
/* Generate the base Kernel Structure */
kernel=(KernelInfo *) AcquireMagickMemory(sizeof(*kernel));
if (kernel == (KernelInfo *) NULL)
return(kernel);
(void) ResetMagickMemory(kernel,0,sizeof(*kernel));
kernel->minimum = kernel->maximum = kernel->angle = 0.0;
kernel->negative_range = kernel->positive_range = 0.0;
kernel->type = type;
kernel->next = (KernelInfo *) NULL;
kernel->signature=MagickCoreSignature;
break;
}
switch(type) {
/*
Convolution Kernels
*/
case UnityKernel:
{
kernel->height = kernel->width = (size_t) 1;
kernel->x = kernel->y = (ssize_t) 0;
kernel->values=(MagickRealType *) MagickAssumeAligned(
AcquireAlignedMemory(1,sizeof(*kernel->values)));
if (kernel->values == (MagickRealType *) NULL)
return(DestroyKernelInfo(kernel));
kernel->maximum = kernel->values[0] = args->rho;
break;
}
break;
case GaussianKernel:
case DoGKernel:
case LoGKernel:
{ double
sigma = fabs(args->sigma),
sigma2 = fabs(args->xi),
A, B, R;
if ( args->rho >= 1.0 )
kernel->width = (size_t)args->rho*2+1;
else if ( (type != DoGKernel) || (sigma >= sigma2) )
kernel->width = GetOptimalKernelWidth2D(args->rho,sigma);
else
kernel->width = GetOptimalKernelWidth2D(args->rho,sigma2);
kernel->height = kernel->width;
kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2;
kernel->values=(MagickRealType *) MagickAssumeAligned(
AcquireAlignedMemory(kernel->width,kernel->height*
sizeof(*kernel->values)));
if (kernel->values == (MagickRealType *) NULL)
return(DestroyKernelInfo(kernel));
/* WARNING: The following generates a 'sampled gaussian' kernel.
* What we really want is a 'discrete gaussian' kernel.
*
* How to do this is I don't know, but appears to be basied on the
* Error Function 'erf()' (intergral of a gaussian)
*/
if ( type == GaussianKernel || type == DoGKernel )
{ /* Calculate a Gaussian, OR positive half of a DoG */
if ( sigma > MagickEpsilon )
{ A = 1.0/(2.0*sigma*sigma); /* simplify loop expressions */
B = (double) (1.0/(Magick2PI*sigma*sigma));
for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++)
for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++)
kernel->values[i] = exp(-((double)(u*u+v*v))*A)*B;
}
else /* limiting case - a unity (normalized Dirac) kernel */
{ (void) ResetMagickMemory(kernel->values,0, (size_t)
kernel->width*kernel->height*sizeof(*kernel->values));
kernel->values[kernel->x+kernel->y*kernel->width] = 1.0;
}
}
if ( type == DoGKernel )
{ /* Subtract a Negative Gaussian for "Difference of Gaussian" */
if ( sigma2 > MagickEpsilon )
{ sigma = sigma2; /* simplify loop expressions */
A = 1.0/(2.0*sigma*sigma);
B = (double) (1.0/(Magick2PI*sigma*sigma));
for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++)
for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++)
kernel->values[i] -= exp(-((double)(u*u+v*v))*A)*B;
}
else /* limiting case - a unity (normalized Dirac) kernel */
kernel->values[kernel->x+kernel->y*kernel->width] -= 1.0;
}
if ( type == LoGKernel )
{ /* Calculate a Laplacian of a Gaussian - Or Mexician Hat */
if ( sigma > MagickEpsilon )
{ A = 1.0/(2.0*sigma*sigma); /* simplify loop expressions */
B = (double) (1.0/(MagickPI*sigma*sigma*sigma*sigma));
for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++)
for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++)
{ R = ((double)(u*u+v*v))*A;
kernel->values[i] = (1-R)*exp(-R)*B;
}
}
else /* special case - generate a unity kernel */
{ (void) ResetMagickMemory(kernel->values,0, (size_t)
kernel->width*kernel->height*sizeof(*kernel->values));
kernel->values[kernel->x+kernel->y*kernel->width] = 1.0;
}
}
/* Note the above kernels may have been 'clipped' by a user defined
** radius, producing a smaller (darker) kernel. Also for very small
** sigma's (> 0.1) the central value becomes larger than one, and thus
** producing a very bright kernel.
**
** Normalization will still be needed.
*/
/* Normalize the 2D Gaussian Kernel
**
** NB: a CorrelateNormalize performs a normal Normalize if
** there are no negative values.
*/
CalcKernelMetaData(kernel); /* the other kernel meta-data */
ScaleKernelInfo(kernel, 1.0, CorrelateNormalizeValue);
break;
}
case BlurKernel:
{ double
sigma = fabs(args->sigma),
alpha, beta;
if ( args->rho >= 1.0 )
kernel->width = (size_t)args->rho*2+1;
else
kernel->width = GetOptimalKernelWidth1D(args->rho,sigma);
kernel->height = 1;
kernel->x = (ssize_t) (kernel->width-1)/2;
kernel->y = 0;
kernel->negative_range = kernel->positive_range = 0.0;
kernel->values=(MagickRealType *) MagickAssumeAligned(
AcquireAlignedMemory(kernel->width,kernel->height*
sizeof(*kernel->values)));
if (kernel->values == (MagickRealType *) NULL)
return(DestroyKernelInfo(kernel));
#if 1
#define KernelRank 3
/* Formula derived from GetBlurKernel() in "effect.c" (plus bug fix).
** It generates a gaussian 3 times the width, and compresses it into
** the expected range. This produces a closer normalization of the
** resulting kernel, especially for very low sigma values.
** As such while wierd it is prefered.
**
** I am told this method originally came from Photoshop.
**
** A properly normalized curve is generated (apart from edge clipping)
** even though we later normalize the result (for edge clipping)
** to allow the correct generation of a "Difference of Blurs".
*/
/* initialize */
v = (ssize_t) (kernel->width*KernelRank-1)/2; /* start/end points to fit range */
(void) ResetMagickMemory(kernel->values,0, (size_t)
kernel->width*kernel->height*sizeof(*kernel->values));
/* Calculate a Positive 1D Gaussian */
if ( sigma > MagickEpsilon )
{ sigma *= KernelRank; /* simplify loop expressions */
alpha = 1.0/(2.0*sigma*sigma);
beta= (double) (1.0/(MagickSQ2PI*sigma ));
for ( u=-v; u <= v; u++) {
kernel->values[(u+v)/KernelRank] +=
exp(-((double)(u*u))*alpha)*beta;
}
}
else /* special case - generate a unity kernel */
kernel->values[kernel->x+kernel->y*kernel->width] = 1.0;
#else
/* Direct calculation without curve averaging
This is equivelent to a KernelRank of 1 */
/* Calculate a Positive Gaussian */
if ( sigma > MagickEpsilon )
{ alpha = 1.0/(2.0*sigma*sigma); /* simplify loop expressions */
beta = 1.0/(MagickSQ2PI*sigma);
for ( i=0, u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++)
kernel->values[i] = exp(-((double)(u*u))*alpha)*beta;
}
else /* special case - generate a unity kernel */
{ (void) ResetMagickMemory(kernel->values,0, (size_t)
kernel->width*kernel->height*sizeof(*kernel->values));
kernel->values[kernel->x+kernel->y*kernel->width] = 1.0;
}
#endif
/* Note the above kernel may have been 'clipped' by a user defined
** radius, producing a smaller (darker) kernel. Also for very small
** sigma's (> 0.1) the central value becomes larger than one, as a
** result of not generating a actual 'discrete' kernel, and thus
** producing a very bright 'impulse'.
**
** Becuase of these two factors Normalization is required!
*/
/* Normalize the 1D Gaussian Kernel
**
** NB: a CorrelateNormalize performs a normal Normalize if
** there are no negative values.
*/
CalcKernelMetaData(kernel); /* the other kernel meta-data */
ScaleKernelInfo(kernel, 1.0, CorrelateNormalizeValue);
/* rotate the 1D kernel by given angle */
RotateKernelInfo(kernel, args->xi );
break;
}
case CometKernel:
{ double
sigma = fabs(args->sigma),
A;
if ( args->rho < 1.0 )
kernel->width = (GetOptimalKernelWidth1D(args->rho,sigma)-1)/2+1;
else
kernel->width = (size_t)args->rho;
kernel->x = kernel->y = 0;
kernel->height = 1;
kernel->negative_range = kernel->positive_range = 0.0;
kernel->values=(MagickRealType *) MagickAssumeAligned(
AcquireAlignedMemory(kernel->width,kernel->height*
sizeof(*kernel->values)));
if (kernel->values == (MagickRealType *) NULL)
return(DestroyKernelInfo(kernel));
/* A comet blur is half a 1D gaussian curve, so that the object is
** blurred in one direction only. This may not be quite the right
** curve to use so may change in the future. The function must be
** normalised after generation, which also resolves any clipping.
**
** As we are normalizing and not subtracting gaussians,
** there is no need for a divisor in the gaussian formula
**
** It is less comples
*/
if ( sigma > MagickEpsilon )
{
#if 1
#define KernelRank 3
v = (ssize_t) kernel->width*KernelRank; /* start/end points */
(void) ResetMagickMemory(kernel->values,0, (size_t)
kernel->width*sizeof(*kernel->values));
sigma *= KernelRank; /* simplify the loop expression */
A = 1.0/(2.0*sigma*sigma);
/* B = 1.0/(MagickSQ2PI*sigma); */
for ( u=0; u < v; u++) {
kernel->values[u/KernelRank] +=
exp(-((double)(u*u))*A);
/* exp(-((double)(i*i))/2.0*sigma*sigma)/(MagickSQ2PI*sigma); */
}
for (i=0; i < (ssize_t) kernel->width; i++)
kernel->positive_range += kernel->values[i];
#else
A = 1.0/(2.0*sigma*sigma); /* simplify the loop expression */
/* B = 1.0/(MagickSQ2PI*sigma); */
for ( i=0; i < (ssize_t) kernel->width; i++)
kernel->positive_range +=
kernel->values[i] = exp(-((double)(i*i))*A);
/* exp(-((double)(i*i))/2.0*sigma*sigma)/(MagickSQ2PI*sigma); */
#endif
}
else /* special case - generate a unity kernel */
{ (void) ResetMagickMemory(kernel->values,0, (size_t)
kernel->width*kernel->height*sizeof(*kernel->values));
kernel->values[kernel->x+kernel->y*kernel->width] = 1.0;
kernel->positive_range = 1.0;
}
kernel->minimum = 0.0;
kernel->maximum = kernel->values[0];
kernel->negative_range = 0.0;
ScaleKernelInfo(kernel, 1.0, NormalizeValue); /* Normalize */
RotateKernelInfo(kernel, args->xi); /* Rotate by angle */
break;
}
case BinomialKernel:
{
size_t
order_f;
if (args->rho < 1.0)
kernel->width = kernel->height = 3; /* default radius = 1 */
else
kernel->width = kernel->height = ((size_t)args->rho)*2+1;
kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2;
order_f = fact(kernel->width-1);
kernel->values=(MagickRealType *) MagickAssumeAligned(
AcquireAlignedMemory(kernel->width,kernel->height*
sizeof(*kernel->values)));
if (kernel->values == (MagickRealType *) NULL)
return(DestroyKernelInfo(kernel));
/* set all kernel values within diamond area to scale given */
for ( i=0, v=0; v < (ssize_t)kernel->height; v++)
{ size_t
alpha = order_f / ( fact((size_t) v) * fact(kernel->height-v-1) );
for ( u=0; u < (ssize_t)kernel->width; u++, i++)
kernel->positive_range += kernel->values[i] = (double)
(alpha * order_f / ( fact((size_t) u) * fact(kernel->height-u-1) ));
}
kernel->minimum = 1.0;
kernel->maximum = kernel->values[kernel->x+kernel->y*kernel->width];
kernel->negative_range = 0.0;
break;
}
/*
Convolution Kernels - Well Known Named Constant Kernels
*/
case LaplacianKernel:
{ switch ( (int) args->rho ) {
case 0:
default: /* laplacian square filter -- default */
kernel=ParseKernelArray("3: -1,-1,-1 -1,8,-1 -1,-1,-1");
break;
case 1: /* laplacian diamond filter */
kernel=ParseKernelArray("3: 0,-1,0 -1,4,-1 0,-1,0");
break;
case 2:
kernel=ParseKernelArray("3: -2,1,-2 1,4,1 -2,1,-2");
break;
case 3:
kernel=ParseKernelArray("3: 1,-2,1 -2,4,-2 1,-2,1");
break;
case 5: /* a 5x5 laplacian */
kernel=ParseKernelArray(
"5: -4,-1,0,-1,-4 -1,2,3,2,-1 0,3,4,3,0 -1,2,3,2,-1 -4,-1,0,-1,-4");
break;
case 7: /* a 7x7 laplacian */
kernel=ParseKernelArray(
"7:-10,-5,-2,-1,-2,-5,-10 -5,0,3,4,3,0,-5 -2,3,6,7,6,3,-2 -1,4,7,8,7,4,-1 -2,3,6,7,6,3,-2 -5,0,3,4,3,0,-5 -10,-5,-2,-1,-2,-5,-10" );
break;
case 15: /* a 5x5 LoG (sigma approx 1.4) */
kernel=ParseKernelArray(
"5: 0,0,-1,0,0 0,-1,-2,-1,0 -1,-2,16,-2,-1 0,-1,-2,-1,0 0,0,-1,0,0");
break;
case 19: /* a 9x9 LoG (sigma approx 1.4) */
/* http://www.cscjournals.org/csc/manuscript/Journals/IJIP/volume3/Issue1/IJIP-15.pdf */
kernel=ParseKernelArray(
"9: 0,-1,-1,-2,-2,-2,-1,-1,0 -1,-2,-4,-5,-5,-5,-4,-2,-1 -1,-4,-5,-3,-0,-3,-5,-4,-1 -2,-5,-3,12,24,12,-3,-5,-2 -2,-5,-0,24,40,24,-0,-5,-2 -2,-5,-3,12,24,12,-3,-5,-2 -1,-4,-5,-3,-0,-3,-5,-4,-1 -1,-2,-4,-5,-5,-5,-4,-2,-1 0,-1,-1,-2,-2,-2,-1,-1,0");
break;
}
if (kernel == (KernelInfo *) NULL)
return(kernel);
kernel->type = type;
break;
}
case SobelKernel:
{ /* Simple Sobel Kernel */
kernel=ParseKernelArray("3: 1,0,-1 2,0,-2 1,0,-1");
if (kernel == (KernelInfo *) NULL)
return(kernel);
kernel->type = type;
RotateKernelInfo(kernel, args->rho);
break;
}
case RobertsKernel:
{
kernel=ParseKernelArray("3: 0,0,0 1,-1,0 0,0,0");
if (kernel == (KernelInfo *) NULL)
return(kernel);
kernel->type = type;
RotateKernelInfo(kernel, args->rho);
break;
}
case PrewittKernel:
{
kernel=ParseKernelArray("3: 1,0,-1 1,0,-1 1,0,-1");
if (kernel == (KernelInfo *) NULL)
return(kernel);
kernel->type = type;
RotateKernelInfo(kernel, args->rho);
break;
}
case CompassKernel:
{
kernel=ParseKernelArray("3: 1,1,-1 1,-2,-1 1,1,-1");
if (kernel == (KernelInfo *) NULL)
return(kernel);
kernel->type = type;
RotateKernelInfo(kernel, args->rho);
break;
}
case KirschKernel:
{
kernel=ParseKernelArray("3: 5,-3,-3 5,0,-3 5,-3,-3");
if (kernel == (KernelInfo *) NULL)
return(kernel);
kernel->type = type;
RotateKernelInfo(kernel, args->rho);
break;
}
case FreiChenKernel:
/* Direction is set to be left to right positive */
/* http://www.math.tau.ac.il/~turkel/notes/edge_detectors.pdf -- RIGHT? */
/* http://ltswww.epfl.ch/~courstiv/exos_labos/sol3.pdf -- WRONG? */
{ switch ( (int) args->rho ) {
default:
case 0:
kernel=ParseKernelArray("3: 1,0,-1 2,0,-2 1,0,-1");
if (kernel == (KernelInfo *) NULL)
return(kernel);
kernel->type = type;
kernel->values[3] = +(MagickRealType) MagickSQ2;
kernel->values[5] = -(MagickRealType) MagickSQ2;
CalcKernelMetaData(kernel); /* recalculate meta-data */
break;
case 2:
kernel=ParseKernelArray("3: 1,2,0 2,0,-2 0,-2,-1");
if (kernel == (KernelInfo *) NULL)
return(kernel);
kernel->type = type;
kernel->values[1] = kernel->values[3]= +(MagickRealType) MagickSQ2;
kernel->values[5] = kernel->values[7]= -(MagickRealType) MagickSQ2;
CalcKernelMetaData(kernel); /* recalculate meta-data */
ScaleKernelInfo(kernel, (double) (1.0/2.0*MagickSQ2), NoValue);
break;
case 10:
{
kernel=AcquireKernelInfo("FreiChen:11;FreiChen:12;FreiChen:13;FreiChen:14;FreiChen:15;FreiChen:16;FreiChen:17;FreiChen:18;FreiChen:19",exception);
if (kernel == (KernelInfo *) NULL)
return(kernel);
break;
}
case 1:
case 11:
kernel=ParseKernelArray("3: 1,0,-1 2,0,-2 1,0,-1");
if (kernel == (KernelInfo *) NULL)
return(kernel);
kernel->type = type;
kernel->values[3] = +(MagickRealType) MagickSQ2;
kernel->values[5] = -(MagickRealType) MagickSQ2;
CalcKernelMetaData(kernel); /* recalculate meta-data */
ScaleKernelInfo(kernel, (double) (1.0/2.0*MagickSQ2), NoValue);
break;
case 12:
kernel=ParseKernelArray("3: 1,2,1 0,0,0 1,2,1");
if (kernel == (KernelInfo *) NULL)
return(kernel);
kernel->type = type;
kernel->values[1] = +(MagickRealType) MagickSQ2;
kernel->values[7] = +(MagickRealType) MagickSQ2;
CalcKernelMetaData(kernel);
ScaleKernelInfo(kernel, (double) (1.0/2.0*MagickSQ2), NoValue);
break;
case 13:
kernel=ParseKernelArray("3: 2,-1,0 -1,0,1 0,1,-2");
if (kernel == (KernelInfo *) NULL)
return(kernel);
kernel->type = type;
kernel->values[0] = +(MagickRealType) MagickSQ2;
kernel->values[8] = -(MagickRealType) MagickSQ2;
CalcKernelMetaData(kernel);
ScaleKernelInfo(kernel, (double) (1.0/2.0*MagickSQ2), NoValue);
break;
case 14:
kernel=ParseKernelArray("3: 0,1,-2 -1,0,1 2,-1,0");
if (kernel == (KernelInfo *) NULL)
return(kernel);
kernel->type = type;
kernel->values[2] = -(MagickRealType) MagickSQ2;
kernel->values[6] = +(MagickRealType) MagickSQ2;
CalcKernelMetaData(kernel);
ScaleKernelInfo(kernel, (double) (1.0/2.0*MagickSQ2), NoValue);
break;
case 15:
kernel=ParseKernelArray("3: 0,-1,0 1,0,1 0,-1,0");
if (kernel == (KernelInfo *) NULL)
return(kernel);
kernel->type = type;
ScaleKernelInfo(kernel, 1.0/2.0, NoValue);
break;
case 16:
kernel=ParseKernelArray("3: 1,0,-1 0,0,0 -1,0,1");
if (kernel == (KernelInfo *) NULL)
return(kernel);
kernel->type = type;
ScaleKernelInfo(kernel, 1.0/2.0, NoValue);
break;
case 17:
kernel=ParseKernelArray("3: 1,-2,1 -2,4,-2 -1,-2,1");
if (kernel == (KernelInfo *) NULL)
return(kernel);
kernel->type = type;
ScaleKernelInfo(kernel, 1.0/6.0, NoValue);
break;
case 18:
kernel=ParseKernelArray("3: -2,1,-2 1,4,1 -2,1,-2");
if (kernel == (KernelInfo *) NULL)
return(kernel);
kernel->type = type;
ScaleKernelInfo(kernel, 1.0/6.0, NoValue);
break;
case 19:
kernel=ParseKernelArray("3: 1,1,1 1,1,1 1,1,1");
if (kernel == (KernelInfo *) NULL)
return(kernel);
kernel->type = type;
ScaleKernelInfo(kernel, 1.0/3.0, NoValue);
break;
}
if ( fabs(args->sigma) >= MagickEpsilon )
/* Rotate by correctly supplied 'angle' */
RotateKernelInfo(kernel, args->sigma);
else if ( args->rho > 30.0 || args->rho < -30.0 )
/* Rotate by out of bounds 'type' */
RotateKernelInfo(kernel, args->rho);
break;
}
/*
Boolean or Shaped Kernels
*/
case DiamondKernel:
{
if (args->rho < 1.0)
kernel->width = kernel->height = 3; /* default radius = 1 */
else
kernel->width = kernel->height = ((size_t)args->rho)*2+1;
kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2;
kernel->values=(MagickRealType *) MagickAssumeAligned(
AcquireAlignedMemory(kernel->width,kernel->height*
sizeof(*kernel->values)));
if (kernel->values == (MagickRealType *) NULL)
return(DestroyKernelInfo(kernel));
/* set all kernel values within diamond area to scale given */
for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++)
for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++)
if ( (labs((long) u)+labs((long) v)) <= (long) kernel->x)
kernel->positive_range += kernel->values[i] = args->sigma;
else
kernel->values[i] = nan;
kernel->minimum = kernel->maximum = args->sigma; /* a flat shape */
break;
}
case SquareKernel:
case RectangleKernel:
{ double
scale;
if ( type == SquareKernel )
{
if (args->rho < 1.0)
kernel->width = kernel->height = 3; /* default radius = 1 */
else
kernel->width = kernel->height = (size_t) (2*args->rho+1);
kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2;
scale = args->sigma;
}
else {
/* NOTE: user defaults set in "AcquireKernelInfo()" */
if ( args->rho < 1.0 || args->sigma < 1.0 )
return(DestroyKernelInfo(kernel)); /* invalid args given */
kernel->width = (size_t)args->rho;
kernel->height = (size_t)args->sigma;
if ( args->xi < 0.0 || args->xi > (double)kernel->width ||
args->psi < 0.0 || args->psi > (double)kernel->height )
return(DestroyKernelInfo(kernel)); /* invalid args given */
kernel->x = (ssize_t) args->xi;
kernel->y = (ssize_t) args->psi;
scale = 1.0;
}
kernel->values=(MagickRealType *) MagickAssumeAligned(
AcquireAlignedMemory(kernel->width,kernel->height*
sizeof(*kernel->values)));
if (kernel->values == (MagickRealType *) NULL)
return(DestroyKernelInfo(kernel));
/* set all kernel values to scale given */
u=(ssize_t) (kernel->width*kernel->height);
for ( i=0; i < u; i++)
kernel->values[i] = scale;
kernel->minimum = kernel->maximum = scale; /* a flat shape */
kernel->positive_range = scale*u;
break;
}
case OctagonKernel:
{
if (args->rho < 1.0)
kernel->width = kernel->height = 5; /* default radius = 2 */
else
kernel->width = kernel->height = ((size_t)args->rho)*2+1;
kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2;
kernel->values=(MagickRealType *) MagickAssumeAligned(
AcquireAlignedMemory(kernel->width,kernel->height*
sizeof(*kernel->values)));
if (kernel->values == (MagickRealType *) NULL)
return(DestroyKernelInfo(kernel));
for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++)
for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++)
if ( (labs((long) u)+labs((long) v)) <=
((long)kernel->x + (long)(kernel->x/2)) )
kernel->positive_range += kernel->values[i] = args->sigma;
else
kernel->values[i] = nan;
kernel->minimum = kernel->maximum = args->sigma; /* a flat shape */
break;
}
case DiskKernel:
{
ssize_t
limit = (ssize_t)(args->rho*args->rho);
if (args->rho < 0.4) /* default radius approx 4.3 */
kernel->width = kernel->height = 9L, limit = 18L;
else
kernel->width = kernel->height = (size_t)fabs(args->rho)*2+1;
kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2;
kernel->values=(MagickRealType *) MagickAssumeAligned(
AcquireAlignedMemory(kernel->width,kernel->height*
sizeof(*kernel->values)));
if (kernel->values == (MagickRealType *) NULL)
return(DestroyKernelInfo(kernel));
for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++)
for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++)
if ((u*u+v*v) <= limit)
kernel->positive_range += kernel->values[i] = args->sigma;
else
kernel->values[i] = nan;
kernel->minimum = kernel->maximum = args->sigma; /* a flat shape */
break;
}
case PlusKernel:
{
if (args->rho < 1.0)
kernel->width = kernel->height = 5; /* default radius 2 */
else
kernel->width = kernel->height = ((size_t)args->rho)*2+1;
kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2;
kernel->values=(MagickRealType *) MagickAssumeAligned(
AcquireAlignedMemory(kernel->width,kernel->height*
sizeof(*kernel->values)));
if (kernel->values == (MagickRealType *) NULL)
return(DestroyKernelInfo(kernel));
/* set all kernel values along axises to given scale */
for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++)
for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++)
kernel->values[i] = (u == 0 || v == 0) ? args->sigma : nan;
kernel->minimum = kernel->maximum = args->sigma; /* a flat shape */
kernel->positive_range = args->sigma*(kernel->width*2.0 - 1.0);
break;
}
case CrossKernel:
{
if (args->rho < 1.0)
kernel->width = kernel->height = 5; /* default radius 2 */
else
kernel->width = kernel->height = ((size_t)args->rho)*2+1;
kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2;
kernel->values=(MagickRealType *) MagickAssumeAligned(
AcquireAlignedMemory(kernel->width,kernel->height*
sizeof(*kernel->values)));
if (kernel->values == (MagickRealType *) NULL)
return(DestroyKernelInfo(kernel));
/* set all kernel values along axises to given scale */
for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++)
for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++)
kernel->values[i] = (u == v || u == -v) ? args->sigma : nan;
kernel->minimum = kernel->maximum = args->sigma; /* a flat shape */
kernel->positive_range = args->sigma*(kernel->width*2.0 - 1.0);
break;
}
/*
HitAndMiss Kernels
*/
case RingKernel:
case PeaksKernel:
{
ssize_t
limit1,
limit2,
scale;
if (args->rho < args->sigma)
{
kernel->width = ((size_t)args->sigma)*2+1;
limit1 = (ssize_t)(args->rho*args->rho);
limit2 = (ssize_t)(args->sigma*args->sigma);
}
else
{
kernel->width = ((size_t)args->rho)*2+1;
limit1 = (ssize_t)(args->sigma*args->sigma);
limit2 = (ssize_t)(args->rho*args->rho);
}
if ( limit2 <= 0 )
kernel->width = 7L, limit1 = 7L, limit2 = 11L;
kernel->height = kernel->width;
kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2;
kernel->values=(MagickRealType *) MagickAssumeAligned(
AcquireAlignedMemory(kernel->width,kernel->height*
sizeof(*kernel->values)));
if (kernel->values == (MagickRealType *) NULL)
return(DestroyKernelInfo(kernel));
/* set a ring of points of 'scale' ( 0.0 for PeaksKernel ) */
scale = (ssize_t) (( type == PeaksKernel) ? 0.0 : args->xi);
for ( i=0, v= -kernel->y; v <= (ssize_t)kernel->y; v++)
for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++)
{ ssize_t radius=u*u+v*v;
if (limit1 < radius && radius <= limit2)
kernel->positive_range += kernel->values[i] = (double) scale;
else
kernel->values[i] = nan;
}
kernel->minimum = kernel->maximum = (double) scale;
if ( type == PeaksKernel ) {
/* set the central point in the middle */
kernel->values[kernel->x+kernel->y*kernel->width] = 1.0;
kernel->positive_range = 1.0;
kernel->maximum = 1.0;
}
break;
}
case EdgesKernel:
{
kernel=AcquireKernelInfo("ThinSE:482",exception);
if (kernel == (KernelInfo *) NULL)
return(kernel);
kernel->type = type;
ExpandMirrorKernelInfo(kernel); /* mirror expansion of kernels */
break;
}
case CornersKernel:
{
kernel=AcquireKernelInfo("ThinSE:87",exception);
if (kernel == (KernelInfo *) NULL)
return(kernel);
kernel->type = type;
ExpandRotateKernelInfo(kernel, 90.0); /* Expand 90 degree rotations */
break;
}
case DiagonalsKernel:
{
switch ( (int) args->rho ) {
case 0:
default:
{ KernelInfo
*new_kernel;
kernel=ParseKernelArray("3: 0,0,0 0,-,1 1,1,-");
if (kernel == (KernelInfo *) NULL)
return(kernel);
kernel->type = type;
new_kernel=ParseKernelArray("3: 0,0,1 0,-,1 0,1,-");
if (new_kernel == (KernelInfo *) NULL)
return(DestroyKernelInfo(kernel));
new_kernel->type = type;
LastKernelInfo(kernel)->next = new_kernel;
ExpandMirrorKernelInfo(kernel);
return(kernel);
}
case 1:
kernel=ParseKernelArray("3: 0,0,0 0,-,1 1,1,-");
break;
case 2:
kernel=ParseKernelArray("3: 0,0,1 0,-,1 0,1,-");
break;
}
if (kernel == (KernelInfo *) NULL)
return(kernel);
kernel->type = type;
RotateKernelInfo(kernel, args->sigma);
break;
}
case LineEndsKernel:
{ /* Kernels for finding the end of thin lines */
switch ( (int) args->rho ) {
case 0:
default:
/* set of kernels to find all end of lines */
return(AcquireKernelInfo("LineEnds:1>;LineEnds:2>",exception));
case 1:
/* kernel for 4-connected line ends - no rotation */
kernel=ParseKernelArray("3: 0,0,- 0,1,1 0,0,-");
break;
case 2:
/* kernel to add for 8-connected lines - no rotation */
kernel=ParseKernelArray("3: 0,0,0 0,1,0 0,0,1");
break;
case 3:
/* kernel to add for orthogonal line ends - does not find corners */
kernel=ParseKernelArray("3: 0,0,0 0,1,1 0,0,0");
break;
case 4:
/* traditional line end - fails on last T end */
kernel=ParseKernelArray("3: 0,0,0 0,1,- 0,0,-");
break;
}
if (kernel == (KernelInfo *) NULL)
return(kernel);
kernel->type = type;
RotateKernelInfo(kernel, args->sigma);
break;
}
case LineJunctionsKernel:
{ /* kernels for finding the junctions of multiple lines */
switch ( (int) args->rho ) {
case 0:
default:
/* set of kernels to find all line junctions */
return(AcquireKernelInfo("LineJunctions:1@;LineJunctions:2>",exception));
case 1:
/* Y Junction */
kernel=ParseKernelArray("3: 1,-,1 -,1,- -,1,-");
break;
case 2:
/* Diagonal T Junctions */
kernel=ParseKernelArray("3: 1,-,- -,1,- 1,-,1");
break;
case 3:
/* Orthogonal T Junctions */
kernel=ParseKernelArray("3: -,-,- 1,1,1 -,1,-");
break;
case 4:
/* Diagonal X Junctions */
kernel=ParseKernelArray("3: 1,-,1 -,1,- 1,-,1");
break;
case 5:
/* Orthogonal X Junctions - minimal diamond kernel */
kernel=ParseKernelArray("3: -,1,- 1,1,1 -,1,-");
break;
}
if (kernel == (KernelInfo *) NULL)
return(kernel);
kernel->type = type;
RotateKernelInfo(kernel, args->sigma);
break;
}
case RidgesKernel:
{ /* Ridges - Ridge finding kernels */
KernelInfo
*new_kernel;
switch ( (int) args->rho ) {
case 1:
default:
kernel=ParseKernelArray("3x1:0,1,0");
if (kernel == (KernelInfo *) NULL)
return(kernel);
kernel->type = type;
ExpandRotateKernelInfo(kernel, 90.0); /* 2 rotated kernels (symmetrical) */
break;
case 2:
kernel=ParseKernelArray("4x1:0,1,1,0");
if (kernel == (KernelInfo *) NULL)
return(kernel);
kernel->type = type;
ExpandRotateKernelInfo(kernel, 90.0); /* 4 rotated kernels */
/* Kernels to find a stepped 'thick' line, 4 rotates + mirrors */
/* Unfortunatally we can not yet rotate a non-square kernel */
/* But then we can't flip a non-symetrical kernel either */
new_kernel=ParseKernelArray("4x3+1+1:0,1,1,- -,1,1,- -,1,1,0");
if (new_kernel == (KernelInfo *) NULL)
return(DestroyKernelInfo(kernel));
new_kernel->type = type;
LastKernelInfo(kernel)->next = new_kernel;
new_kernel=ParseKernelArray("4x3+2+1:0,1,1,- -,1,1,- -,1,1,0");
if (new_kernel == (KernelInfo *) NULL)
return(DestroyKernelInfo(kernel));
new_kernel->type = type;
LastKernelInfo(kernel)->next = new_kernel;
new_kernel=ParseKernelArray("4x3+1+1:-,1,1,0 -,1,1,- 0,1,1,-");
if (new_kernel == (KernelInfo *) NULL)
return(DestroyKernelInfo(kernel));
new_kernel->type = type;
LastKernelInfo(kernel)->next = new_kernel;
new_kernel=ParseKernelArray("4x3+2+1:-,1,1,0 -,1,1,- 0,1,1,-");
if (new_kernel == (KernelInfo *) NULL)
return(DestroyKernelInfo(kernel));
new_kernel->type = type;
LastKernelInfo(kernel)->next = new_kernel;
new_kernel=ParseKernelArray("3x4+1+1:0,-,- 1,1,1 1,1,1 -,-,0");
if (new_kernel == (KernelInfo *) NULL)
return(DestroyKernelInfo(kernel));
new_kernel->type = type;
LastKernelInfo(kernel)->next = new_kernel;
new_kernel=ParseKernelArray("3x4+1+2:0,-,- 1,1,1 1,1,1 -,-,0");
if (new_kernel == (KernelInfo *) NULL)
return(DestroyKernelInfo(kernel));
new_kernel->type = type;
LastKernelInfo(kernel)->next = new_kernel;
new_kernel=ParseKernelArray("3x4+1+1:-,-,0 1,1,1 1,1,1 0,-,-");
if (new_kernel == (KernelInfo *) NULL)
return(DestroyKernelInfo(kernel));
new_kernel->type = type;
LastKernelInfo(kernel)->next = new_kernel;
new_kernel=ParseKernelArray("3x4+1+2:-,-,0 1,1,1 1,1,1 0,-,-");
if (new_kernel == (KernelInfo *) NULL)
return(DestroyKernelInfo(kernel));
new_kernel->type = type;
LastKernelInfo(kernel)->next = new_kernel;
break;
}
break;
}
case ConvexHullKernel:
{
KernelInfo
*new_kernel;
/* first set of 8 kernels */
kernel=ParseKernelArray("3: 1,1,- 1,0,- 1,-,0");
if (kernel == (KernelInfo *) NULL)
return(kernel);
kernel->type = type;
ExpandRotateKernelInfo(kernel, 90.0);
/* append the mirror versions too - no flip function yet */
new_kernel=ParseKernelArray("3: 1,1,1 1,0,- -,-,0");
if (new_kernel == (KernelInfo *) NULL)
return(DestroyKernelInfo(kernel));
new_kernel->type = type;
ExpandRotateKernelInfo(new_kernel, 90.0);
LastKernelInfo(kernel)->next = new_kernel;
break;
}
case SkeletonKernel:
{
switch ( (int) args->rho ) {
case 1:
default:
/* Traditional Skeleton...
** A cyclically rotated single kernel
*/
kernel=AcquireKernelInfo("ThinSE:482",exception);
if (kernel == (KernelInfo *) NULL)
return(kernel);
kernel->type = type;
ExpandRotateKernelInfo(kernel, 45.0); /* 8 rotations */
break;
case 2:
/* HIPR Variation of the cyclic skeleton
** Corners of the traditional method made more forgiving,
** but the retain the same cyclic order.
*/
kernel=AcquireKernelInfo("ThinSE:482; ThinSE:87x90;",exception);
if (kernel == (KernelInfo *) NULL)
return(kernel);
if (kernel->next == (KernelInfo *) NULL)
return(DestroyKernelInfo(kernel));
kernel->type = type;
kernel->next->type = type;
ExpandRotateKernelInfo(kernel, 90.0); /* 4 rotations of the 2 kernels */
break;
case 3:
/* Dan Bloomberg Skeleton, from his paper on 3x3 thinning SE's
** "Connectivity-Preserving Morphological Image Thransformations"
** by Dan S. Bloomberg, available on Leptonica, Selected Papers,
** http://www.leptonica.com/papers/conn.pdf
*/
kernel=AcquireKernelInfo("ThinSE:41; ThinSE:42; ThinSE:43",
exception);
if (kernel == (KernelInfo *) NULL)
return(kernel);
kernel->type = type;
kernel->next->type = type;
kernel->next->next->type = type;
ExpandMirrorKernelInfo(kernel); /* 12 kernels total */
break;
}
break;
}
case ThinSEKernel:
{ /* Special kernels for general thinning, while preserving connections
** "Connectivity-Preserving Morphological Image Thransformations"
** by Dan S. Bloomberg, available on Leptonica, Selected Papers,
** http://www.leptonica.com/papers/conn.pdf
** And
** http://tpgit.github.com/Leptonica/ccthin_8c_source.html
**
** Note kernels do not specify the origin pixel, allowing them
** to be used for both thickening and thinning operations.
*/
switch ( (int) args->rho ) {
/* SE for 4-connected thinning */
case 41: /* SE_4_1 */
kernel=ParseKernelArray("3: -,-,1 0,-,1 -,-,1");
break;
case 42: /* SE_4_2 */
kernel=ParseKernelArray("3: -,-,1 0,-,1 -,0,-");
break;
case 43: /* SE_4_3 */
kernel=ParseKernelArray("3: -,0,- 0,-,1 -,-,1");
break;
case 44: /* SE_4_4 */
kernel=ParseKernelArray("3: -,0,- 0,-,1 -,0,-");
break;
case 45: /* SE_4_5 */
kernel=ParseKernelArray("3: -,0,1 0,-,1 -,0,-");
break;
case 46: /* SE_4_6 */
kernel=ParseKernelArray("3: -,0,- 0,-,1 -,0,1");
break;
case 47: /* SE_4_7 */
kernel=ParseKernelArray("3: -,1,1 0,-,1 -,0,-");
break;
case 48: /* SE_4_8 */
kernel=ParseKernelArray("3: -,-,1 0,-,1 0,-,1");
break;
case 49: /* SE_4_9 */
kernel=ParseKernelArray("3: 0,-,1 0,-,1 -,-,1");
break;
/* SE for 8-connected thinning - negatives of the above */
case 81: /* SE_8_0 */
kernel=ParseKernelArray("3: -,1,- 0,-,1 -,1,-");
break;
case 82: /* SE_8_2 */
kernel=ParseKernelArray("3: -,1,- 0,-,1 0,-,-");
break;
case 83: /* SE_8_3 */
kernel=ParseKernelArray("3: 0,-,- 0,-,1 -,1,-");
break;
case 84: /* SE_8_4 */
kernel=ParseKernelArray("3: 0,-,- 0,-,1 0,-,-");
break;
case 85: /* SE_8_5 */
kernel=ParseKernelArray("3: 0,-,1 0,-,1 0,-,-");
break;
case 86: /* SE_8_6 */
kernel=ParseKernelArray("3: 0,-,- 0,-,1 0,-,1");
break;
case 87: /* SE_8_7 */
kernel=ParseKernelArray("3: -,1,- 0,-,1 0,0,-");
break;
case 88: /* SE_8_8 */
kernel=ParseKernelArray("3: -,1,- 0,-,1 0,1,-");
break;
case 89: /* SE_8_9 */
kernel=ParseKernelArray("3: 0,1,- 0,-,1 -,1,-");
break;
/* Special combined SE kernels */
case 423: /* SE_4_2 , SE_4_3 Combined Kernel */
kernel=ParseKernelArray("3: -,-,1 0,-,- -,0,-");
break;
case 823: /* SE_8_2 , SE_8_3 Combined Kernel */
kernel=ParseKernelArray("3: -,1,- -,-,1 0,-,-");
break;
case 481: /* SE_48_1 - General Connected Corner Kernel */
kernel=ParseKernelArray("3: -,1,1 0,-,1 0,0,-");
break;
default:
case 482: /* SE_48_2 - General Edge Kernel */
kernel=ParseKernelArray("3: 0,-,1 0,-,1 0,-,1");
break;
}
if (kernel == (KernelInfo *) NULL)
return(kernel);
kernel->type = type;
RotateKernelInfo(kernel, args->sigma);
break;
}
/*
Distance Measuring Kernels
*/
case ChebyshevKernel:
{
if (args->rho < 1.0)
kernel->width = kernel->height = 3; /* default radius = 1 */
else
kernel->width = kernel->height = ((size_t)args->rho)*2+1;
kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2;
kernel->values=(MagickRealType *) MagickAssumeAligned(
AcquireAlignedMemory(kernel->width,kernel->height*
sizeof(*kernel->values)));
if (kernel->values == (MagickRealType *) NULL)
return(DestroyKernelInfo(kernel));
for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++)
for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++)
kernel->positive_range += ( kernel->values[i] =
args->sigma*MagickMax(fabs((double)u),fabs((double)v)) );
kernel->maximum = kernel->values[0];
break;
}
case ManhattanKernel:
{
if (args->rho < 1.0)
kernel->width = kernel->height = 3; /* default radius = 1 */
else
kernel->width = kernel->height = ((size_t)args->rho)*2+1;
kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2;
kernel->values=(MagickRealType *) MagickAssumeAligned(
AcquireAlignedMemory(kernel->width,kernel->height*
sizeof(*kernel->values)));
if (kernel->values == (MagickRealType *) NULL)
return(DestroyKernelInfo(kernel));
for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++)
for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++)
kernel->positive_range += ( kernel->values[i] =
args->sigma*(labs((long) u)+labs((long) v)) );
kernel->maximum = kernel->values[0];
break;
}
case OctagonalKernel:
{
if (args->rho < 2.0)
kernel->width = kernel->height = 5; /* default/minimum radius = 2 */
else
kernel->width = kernel->height = ((size_t)args->rho)*2+1;
kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2;
kernel->values=(MagickRealType *) MagickAssumeAligned(
AcquireAlignedMemory(kernel->width,kernel->height*
sizeof(*kernel->values)));
if (kernel->values == (MagickRealType *) NULL)
return(DestroyKernelInfo(kernel));
for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++)
for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++)
{
double
r1 = MagickMax(fabs((double)u),fabs((double)v)),
r2 = floor((double)(labs((long)u)+labs((long)v)+1)/1.5);
kernel->positive_range += kernel->values[i] =
args->sigma*MagickMax(r1,r2);
}
kernel->maximum = kernel->values[0];
break;
}
case EuclideanKernel:
{
if (args->rho < 1.0)
kernel->width = kernel->height = 3; /* default radius = 1 */
else
kernel->width = kernel->height = ((size_t)args->rho)*2+1;
kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2;
kernel->values=(MagickRealType *) MagickAssumeAligned(
AcquireAlignedMemory(kernel->width,kernel->height*
sizeof(*kernel->values)));
if (kernel->values == (MagickRealType *) NULL)
return(DestroyKernelInfo(kernel));
for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++)
for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++)
kernel->positive_range += ( kernel->values[i] =
args->sigma*sqrt((double)(u*u+v*v)) );
kernel->maximum = kernel->values[0];
break;
}
default:
{
/* No-Op Kernel - Basically just a single pixel on its own */
kernel=ParseKernelArray("1:1");
if (kernel == (KernelInfo *) NULL)
return(kernel);
kernel->type = UndefinedKernel;
break;
}
break;
}
return(kernel);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C l o n e K e r n e l I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% CloneKernelInfo() creates a new clone of the given Kernel List so that its
% can be modified without effecting the original. The cloned kernel should
% be destroyed using DestoryKernelInfo() when no longer needed.
%
% The format of the CloneKernelInfo method is:
%
% KernelInfo *CloneKernelInfo(const KernelInfo *kernel)
%
% A description of each parameter follows:
%
% o kernel: the Morphology/Convolution kernel to be cloned
%
*/
MagickExport KernelInfo *CloneKernelInfo(const KernelInfo *kernel)
{
register ssize_t
i;
KernelInfo
*new_kernel;
assert(kernel != (KernelInfo *) NULL);
new_kernel=(KernelInfo *) AcquireMagickMemory(sizeof(*kernel));
if (new_kernel == (KernelInfo *) NULL)
return(new_kernel);
*new_kernel=(*kernel); /* copy values in structure */
/* replace the values with a copy of the values */
new_kernel->values=(MagickRealType *) MagickAssumeAligned(
AcquireAlignedMemory(kernel->width,kernel->height*sizeof(*kernel->values)));
if (new_kernel->values == (MagickRealType *) NULL)
return(DestroyKernelInfo(new_kernel));
for (i=0; i < (ssize_t) (kernel->width*kernel->height); i++)
new_kernel->values[i]=kernel->values[i];
/* Also clone the next kernel in the kernel list */
if ( kernel->next != (KernelInfo *) NULL ) {
new_kernel->next = CloneKernelInfo(kernel->next);
if ( new_kernel->next == (KernelInfo *) NULL )
return(DestroyKernelInfo(new_kernel));
}
return(new_kernel);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D e s t r o y K e r n e l I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DestroyKernelInfo() frees the memory used by a Convolution/Morphology
% kernel.
%
% The format of the DestroyKernelInfo method is:
%
% KernelInfo *DestroyKernelInfo(KernelInfo *kernel)
%
% A description of each parameter follows:
%
% o kernel: the Morphology/Convolution kernel to be destroyed
%
*/
MagickExport KernelInfo *DestroyKernelInfo(KernelInfo *kernel)
{
assert(kernel != (KernelInfo *) NULL);
if (kernel->next != (KernelInfo *) NULL)
kernel->next=DestroyKernelInfo(kernel->next);
kernel->values=(MagickRealType *) RelinquishAlignedMemory(kernel->values);
kernel=(KernelInfo *) RelinquishMagickMemory(kernel);
return(kernel);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ E x p a n d M i r r o r K e r n e l I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ExpandMirrorKernelInfo() takes a single kernel, and expands it into a
% sequence of 90-degree rotated kernels but providing a reflected 180
% rotatation, before the -/+ 90-degree rotations.
%
% This special rotation order produces a better, more symetrical thinning of
% objects.
%
% The format of the ExpandMirrorKernelInfo method is:
%
% void ExpandMirrorKernelInfo(KernelInfo *kernel)
%
% A description of each parameter follows:
%
% o kernel: the Morphology/Convolution kernel
%
% This function is only internel to this module, as it is not finalized,
% especially with regard to non-orthogonal angles, and rotation of larger
% 2D kernels.
*/
#if 0
static void FlopKernelInfo(KernelInfo *kernel)
{ /* Do a Flop by reversing each row. */
size_t
y;
register ssize_t
x,r;
register double
*k,t;
for ( y=0, k=kernel->values; y < kernel->height; y++, k+=kernel->width)
for ( x=0, r=kernel->width-1; x<kernel->width/2; x++, r--)
t=k[x], k[x]=k[r], k[r]=t;
kernel->x = kernel->width - kernel->x - 1;
angle = fmod(angle+180.0, 360.0);
}
#endif
static void ExpandMirrorKernelInfo(KernelInfo *kernel)
{
KernelInfo
*clone,
*last;
last = kernel;
clone = CloneKernelInfo(last);
RotateKernelInfo(clone, 180); /* flip */
LastKernelInfo(last)->next = clone;
last = clone;
clone = CloneKernelInfo(last);
RotateKernelInfo(clone, 90); /* transpose */
LastKernelInfo(last)->next = clone;
last = clone;
clone = CloneKernelInfo(last);
RotateKernelInfo(clone, 180); /* flop */
LastKernelInfo(last)->next = clone;
return;
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ E x p a n d R o t a t e K e r n e l I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ExpandRotateKernelInfo() takes a kernel list, and expands it by rotating
% incrementally by the angle given, until the kernel repeats.
%
% WARNING: 45 degree rotations only works for 3x3 kernels.
% While 90 degree roatations only works for linear and square kernels
%
% The format of the ExpandRotateKernelInfo method is:
%
% void ExpandRotateKernelInfo(KernelInfo *kernel, double angle)
%
% A description of each parameter follows:
%
% o kernel: the Morphology/Convolution kernel
%
% o angle: angle to rotate in degrees
%
% This function is only internel to this module, as it is not finalized,
% especially with regard to non-orthogonal angles, and rotation of larger
% 2D kernels.
*/
/* Internal Routine - Return true if two kernels are the same */
static MagickBooleanType SameKernelInfo(const KernelInfo *kernel1,
const KernelInfo *kernel2)
{
register size_t
i;
/* check size and origin location */
if ( kernel1->width != kernel2->width
|| kernel1->height != kernel2->height
|| kernel1->x != kernel2->x
|| kernel1->y != kernel2->y )
return MagickFalse;
/* check actual kernel values */
for (i=0; i < (kernel1->width*kernel1->height); i++) {
/* Test for Nan equivalence */
if ( IsNaN(kernel1->values[i]) && !IsNaN(kernel2->values[i]) )
return MagickFalse;
if ( IsNaN(kernel2->values[i]) && !IsNaN(kernel1->values[i]) )
return MagickFalse;
/* Test actual values are equivalent */
if ( fabs(kernel1->values[i] - kernel2->values[i]) >= MagickEpsilon )
return MagickFalse;
}
return MagickTrue;
}
static void ExpandRotateKernelInfo(KernelInfo *kernel, const double angle)
{
KernelInfo
*clone,
*last;
last = kernel;
DisableMSCWarning(4127)
while(1) {
RestoreMSCWarning
clone = CloneKernelInfo(last);
RotateKernelInfo(clone, angle);
if ( SameKernelInfo(kernel, clone) != MagickFalse )
break;
LastKernelInfo(last)->next = clone;
last = clone;
}
clone = DestroyKernelInfo(clone); /* kernel has repeated - junk the clone */
return;
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ C a l c M e t a K e r n a l I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% CalcKernelMetaData() recalculate the KernelInfo meta-data of this kernel only,
% using the kernel values. This should only ne used if it is not possible to
% calculate that meta-data in some easier way.
%
% It is important that the meta-data is correct before ScaleKernelInfo() is
% used to perform kernel normalization.
%
% The format of the CalcKernelMetaData method is:
%
% void CalcKernelMetaData(KernelInfo *kernel, const double scale )
%
% A description of each parameter follows:
%
% o kernel: the Morphology/Convolution kernel to modify
%
% WARNING: Minimum and Maximum values are assumed to include zero, even if
% zero is not part of the kernel (as in Gaussian Derived kernels). This
% however is not true for flat-shaped morphological kernels.
%
% WARNING: Only the specific kernel pointed to is modified, not a list of
% multiple kernels.
%
% This is an internal function and not expected to be useful outside this
% module. This could change however.
*/
static void CalcKernelMetaData(KernelInfo *kernel)
{
register size_t
i;
kernel->minimum = kernel->maximum = 0.0;
kernel->negative_range = kernel->positive_range = 0.0;
for (i=0; i < (kernel->width*kernel->height); i++)
{
if ( fabs(kernel->values[i]) < MagickEpsilon )
kernel->values[i] = 0.0;
( kernel->values[i] < 0)
? ( kernel->negative_range += kernel->values[i] )
: ( kernel->positive_range += kernel->values[i] );
Minimize(kernel->minimum, kernel->values[i]);
Maximize(kernel->maximum, kernel->values[i]);
}
return;
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% M o r p h o l o g y A p p l y %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% MorphologyApply() applies a morphological method, multiple times using
% a list of multiple kernels. This is the method that should be called by
% other 'operators' that internally use morphology operations as part of
% their processing.
%
% It is basically equivalent to as MorphologyImage() (see below) but without
% any user controls. This allows internel programs to use this method to
% perform a specific task without possible interference by any API user
% supplied settings.
%
% It is MorphologyImage() task to extract any such user controls, and
% pass them to this function for processing.
%
% More specifically all given kernels should already be scaled, normalised,
% and blended appropriatally before being parred to this routine. The
% appropriate bias, and compose (typically 'UndefinedComposeOp') given.
%
% The format of the MorphologyApply method is:
%
% Image *MorphologyApply(const Image *image,MorphologyMethod method,
% const ssize_t iterations,const KernelInfo *kernel,
% const CompositeMethod compose,const double bias,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the source image
%
% o method: the morphology method to be applied.
%
% o iterations: apply the operation this many times (or no change).
% A value of -1 means loop until no change found.
% How this is applied may depend on the morphology method.
% Typically this is a value of 1.
%
% o channel: the channel type.
%
% o kernel: An array of double representing the morphology kernel.
%
% o compose: How to handle or merge multi-kernel results.
% If 'UndefinedCompositeOp' use default for the Morphology method.
% If 'NoCompositeOp' force image to be re-iterated by each kernel.
% Otherwise merge the results using the compose method given.
%
% o bias: Convolution Output Bias.
%
% o exception: return any errors or warnings in this structure.
%
*/
static ssize_t MorphologyPrimitive(const Image *image,Image *morphology_image,
const MorphologyMethod method,const KernelInfo *kernel,const double bias,
ExceptionInfo *exception)
{
#define MorphologyTag "Morphology/Image"
CacheView
*image_view,
*morphology_view;
OffsetInfo
offset;
register ssize_t
j,
y;
size_t
*changes,
changed,
width;
MagickBooleanType
status;
MagickOffsetType
progress;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
assert(morphology_image != (Image *) NULL);
assert(morphology_image->signature == MagickCoreSignature);
assert(kernel != (KernelInfo *) NULL);
assert(kernel->signature == MagickCoreSignature);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
status=MagickTrue;
progress=0;
image_view=AcquireVirtualCacheView(image,exception);
morphology_view=AcquireAuthenticCacheView(morphology_image,exception);
width=image->columns+kernel->width-1;
offset.x=0;
offset.y=0;
switch (method)
{
case ConvolveMorphology:
case DilateMorphology:
case DilateIntensityMorphology:
case IterativeDistanceMorphology:
{
/*
Kernel needs to used with reflection about origin.
*/
offset.x=(ssize_t) kernel->width-kernel->x-1;
offset.y=(ssize_t) kernel->height-kernel->y-1;
break;
}
case ErodeMorphology:
case ErodeIntensityMorphology:
case HitAndMissMorphology:
case ThinningMorphology:
case ThickenMorphology:
{
offset.x=kernel->x;
offset.y=kernel->y;
break;
}
default:
{
assert("Not a Primitive Morphology Method" != (char *) NULL);
break;
}
}
changed=0;
changes=(size_t *) AcquireQuantumMemory(GetOpenMPMaximumThreads(),
sizeof(*changes));
if (changes == (size_t *) NULL)
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
for (j=0; j < (ssize_t) GetOpenMPMaximumThreads(); j++)
changes[j]=0;
if ((method == ConvolveMorphology) && (kernel->width == 1))
{
register ssize_t
x;
/*
Special handling (for speed) of vertical (blur) kernels. This performs
its handling in columns rather than in rows. This is only done
for convolve as it is the only method that generates very large 1-D
vertical kernels (such as a 'BlurKernel')
*/
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(progress,status) \
magick_threads(image,morphology_image,image->columns,1)
#endif
for (x=0; x < (ssize_t) image->columns; x++)
{
const int
id = GetOpenMPThreadId();
register const Quantum
*magick_restrict p;
register Quantum
*magick_restrict q;
register ssize_t
r;
ssize_t
center;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,x,-offset.y,1,image->rows+
kernel->height-1,exception);
q=GetCacheViewAuthenticPixels(morphology_view,x,0,1,
morphology_image->rows,exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
center=(ssize_t) GetPixelChannels(image)*offset.y;
for (r=0; r < (ssize_t) image->rows; r++)
{
register ssize_t
i;
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
double
alpha,
gamma,
pixel;
PixelChannel
channel;
PixelTrait
morphology_traits,
traits;
register const MagickRealType
*magick_restrict k;
register const Quantum
*magick_restrict pixels;
register ssize_t
v;
size_t
count;
channel=GetPixelChannelChannel(image,i);
traits=GetPixelChannelTraits(image,channel);
morphology_traits=GetPixelChannelTraits(morphology_image,channel);
if ((traits == UndefinedPixelTrait) ||
(morphology_traits == UndefinedPixelTrait))
continue;
if (((traits & CopyPixelTrait) != 0) ||
(GetPixelWriteMask(image,p+center) <= (QuantumRange/2)))
{
SetPixelChannel(morphology_image,channel,p[center+i],q);
continue;
}
k=(&kernel->values[kernel->height-1]);
pixels=p;
pixel=bias;
gamma=0.0;
count=0;
if ((morphology_traits & BlendPixelTrait) == 0)
for (v=0; v < (ssize_t) kernel->height; v++)
{
if (!IsNaN(*k))
{
pixel+=(*k)*pixels[i];
gamma+=(*k);
count++;
}
k--;
pixels+=GetPixelChannels(image);
}
else
for (v=0; v < (ssize_t) kernel->height; v++)
{
if (!IsNaN(*k))
{
alpha=(double) (QuantumScale*GetPixelAlpha(image,pixels));
pixel+=alpha*(*k)*pixels[i];
gamma+=alpha*(*k);
count++;
}
k--;
pixels+=GetPixelChannels(image);
}
if (fabs(pixel-p[center+i]) > MagickEpsilon)
changes[id]++;
gamma=PerceptibleReciprocal(gamma);
if (count != 0)
gamma*=(double) kernel->height/count;
SetPixelChannel(morphology_image,channel,ClampToQuantum(gamma*
pixel),q);
}
p+=GetPixelChannels(image);
q+=GetPixelChannels(morphology_image);
}
if (SyncCacheViewAuthenticPixels(morphology_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_MorphologyPrimitive)
#endif
proceed=SetImageProgress(image,MorphologyTag,progress++,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
morphology_image->type=image->type;
morphology_view=DestroyCacheView(morphology_view);
image_view=DestroyCacheView(image_view);
for (j=0; j < (ssize_t) GetOpenMPMaximumThreads(); j++)
changed+=changes[j];
changes=(size_t *) RelinquishMagickMemory(changes);
return(status ? (ssize_t) changed : 0);
}
/*
Normal handling of horizontal or rectangular kernels (row by row).
*/
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(progress,status) \
magick_threads(image,morphology_image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
const int
id = GetOpenMPThreadId();
register const Quantum
*magick_restrict p;
register Quantum
*magick_restrict q;
register ssize_t
x;
ssize_t
center;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,-offset.x,y-offset.y,width,
kernel->height,exception);
q=GetCacheViewAuthenticPixels(morphology_view,0,y,morphology_image->columns,
1,exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
center=(ssize_t) (GetPixelChannels(image)*width*offset.y+
GetPixelChannels(image)*offset.x);
for (x=0; x < (ssize_t) image->columns; x++)
{
register ssize_t
i;
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
double
alpha,
gamma,
intensity,
maximum,
minimum,
pixel;
PixelChannel
channel;
PixelTrait
morphology_traits,
traits;
register const MagickRealType
*magick_restrict k;
register const Quantum
*magick_restrict pixels;
register ssize_t
u;
size_t
count;
ssize_t
v;
channel=GetPixelChannelChannel(image,i);
traits=GetPixelChannelTraits(image,channel);
morphology_traits=GetPixelChannelTraits(morphology_image,channel);
if ((traits == UndefinedPixelTrait) ||
(morphology_traits == UndefinedPixelTrait))
continue;
if (((traits & CopyPixelTrait) != 0) ||
(GetPixelWriteMask(image,p+center) <= (QuantumRange/2)))
{
SetPixelChannel(morphology_image,channel,p[center+i],q);
continue;
}
pixels=p;
maximum=0.0;
minimum=(double) QuantumRange;
count=kernel->width*kernel->height;
switch (method)
{
case ConvolveMorphology: pixel=bias; break;
case DilateMorphology:
case ErodeIntensityMorphology:
{
pixel=0.0;
break;
}
default:
{
pixel=(double) p[center+i];
break;
}
}
gamma=1.0;
switch (method)
{
case ConvolveMorphology:
{
/*
Weighted Average of pixels using reflected kernel
For correct working of this operation for asymetrical kernels,
the kernel needs to be applied in its reflected form. That is
its values needs to be reversed.
Correlation is actually the same as this but without reflecting
the kernel, and thus 'lower-level' that Convolution. However as
Convolution is the more common method used, and it does not
really cost us much in terms of processing to use a reflected
kernel, so it is Convolution that is implemented.
Correlation will have its kernel reflected before calling this
function to do a Convolve.
For more details of Correlation vs Convolution see
http://www.cs.umd.edu/~djacobs/CMSC426/Convolution.pdf
*/
k=(&kernel->values[kernel->width*kernel->height-1]);
count=0;
if ((morphology_traits & BlendPixelTrait) == 0)
{
/*
No alpha blending.
*/
for (v=0; v < (ssize_t) kernel->height; v++)
{
for (u=0; u < (ssize_t) kernel->width; u++)
{
if (!IsNaN(*k))
{
pixel+=(*k)*pixels[i];
count++;
}
k--;
pixels+=GetPixelChannels(image);
}
pixels+=(image->columns-1)*GetPixelChannels(image);
}
break;
}
/*
Alpha blending.
*/
gamma=0.0;
for (v=0; v < (ssize_t) kernel->height; v++)
{
for (u=0; u < (ssize_t) kernel->width; u++)
{
if (!IsNaN(*k))
{
alpha=(double) (QuantumScale*GetPixelAlpha(image,pixels));
pixel+=alpha*(*k)*pixels[i];
gamma+=alpha*(*k);
count++;
}
k--;
pixels+=GetPixelChannels(image);
}
pixels+=(image->columns-1)*GetPixelChannels(image);
}
break;
}
case ErodeMorphology:
{
/*
Minimum value within kernel neighbourhood.
The kernel is not reflected for this operation. In normal
Greyscale Morphology, the kernel value should be added
to the real value, this is currently not done, due to the
nature of the boolean kernels being used.
*/
k=kernel->values;
for (v=0; v < (ssize_t) kernel->height; v++)
{
for (u=0; u < (ssize_t) kernel->width; u++)
{
if (!IsNaN(*k) && (*k >= 0.5))
{
if ((double) pixels[i] < pixel)
pixel=(double) pixels[i];
}
k++;
pixels+=GetPixelChannels(image);
}
pixels+=(image->columns-1)*GetPixelChannels(image);
}
break;
}
case DilateMorphology:
{
/*
Maximum value within kernel neighbourhood.
For correct working of this operation for asymetrical kernels,
the kernel needs to be applied in its reflected form. That is
its values needs to be reversed.
In normal Greyscale Morphology, the kernel value should be
added to the real value, this is currently not done, due to the
nature of the boolean kernels being used.
*/
count=0;
k=(&kernel->values[kernel->width*kernel->height-1]);
for (v=0; v < (ssize_t) kernel->height; v++)
{
for (u=0; u < (ssize_t) kernel->width; u++)
{
if (!IsNaN(*k) && (*k > 0.5))
{
if ((double) pixels[i] > pixel)
pixel=(double) pixels[i];
}
k--;
pixels+=GetPixelChannels(image);
}
pixels+=(image->columns-1)*GetPixelChannels(image);
}
break;
}
case HitAndMissMorphology:
case ThinningMorphology:
case ThickenMorphology:
{
/*
Minimum of foreground pixel minus maxumum of background pixels.
The kernel is not reflected for this operation, and consists
of both foreground and background pixel neighbourhoods, 0.0 for
background, and 1.0 for foreground with either Nan or 0.5 values
for don't care.
This never produces a meaningless negative result. Such results
cause Thinning/Thicken to not work correctly when used against a
greyscale image.
*/
count=0;
k=kernel->values;
for (v=0; v < (ssize_t) kernel->height; v++)
{
for (u=0; u < (ssize_t) kernel->width; u++)
{
if (!IsNaN(*k))
{
if (*k > 0.7)
{
if ((double) pixels[i] < pixel)
pixel=(double) pixels[i];
}
else
if (*k < 0.3)
{
if ((double) pixels[i] > maximum)
maximum=(double) pixels[i];
}
count++;
}
k++;
pixels+=GetPixelChannels(image);
}
pixels+=(image->columns-1)*GetPixelChannels(image);
}
pixel-=maximum;
if (pixel < 0.0)
pixel=0.0;
if (method == ThinningMorphology)
pixel=(double) p[center+i]-pixel;
else
if (method == ThickenMorphology)
pixel+=(double) p[center+i]+pixel;
break;
}
case ErodeIntensityMorphology:
{
/*
Select pixel with minimum intensity within kernel neighbourhood.
The kernel is not reflected for this operation.
*/
count=0;
k=kernel->values;
for (v=0; v < (ssize_t) kernel->height; v++)
{
for (u=0; u < (ssize_t) kernel->width; u++)
{
if (!IsNaN(*k) && (*k >= 0.5))
{
intensity=(double) GetPixelIntensity(image,pixels);
if (intensity < minimum)
{
pixel=(double) pixels[i];
minimum=intensity;
}
count++;
}
k++;
pixels+=GetPixelChannels(image);
}
pixels+=(image->columns-1)*GetPixelChannels(image);
}
break;
}
case DilateIntensityMorphology:
{
/*
Select pixel with maximum intensity within kernel neighbourhood.
The kernel is not reflected for this operation.
*/
count=0;
k=(&kernel->values[kernel->width*kernel->height-1]);
for (v=0; v < (ssize_t) kernel->height; v++)
{
for (u=0; u < (ssize_t) kernel->width; u++)
{
if (!IsNaN(*k) && (*k >= 0.5))
{
intensity=(double) GetPixelIntensity(image,pixels);
if (intensity > maximum)
{
pixel=(double) pixels[i];
maximum=intensity;
}
count++;
}
k--;
pixels+=GetPixelChannels(image);
}
pixels+=(image->columns-1)*GetPixelChannels(image);
}
break;
}
case IterativeDistanceMorphology:
{
/*
Compute th iterative distance from black edge of a white image
shape. Essentually white values are decreased to the smallest
'distance from edge' it can find.
It works by adding kernel values to the neighbourhood, and and
select the minimum value found. The kernel is rotated before
use, so kernel distances match resulting distances, when a user
provided asymmetric kernel is applied.
This code is nearly identical to True GrayScale Morphology but
not quite.
GreyDilate Kernel values added, maximum value found Kernel is
rotated before use.
GrayErode: Kernel values subtracted and minimum value found No
kernel rotation used.
Note the the Iterative Distance method is essentially a
GrayErode, but with negative kernel values, and kernel rotation
applied.
*/
count=0;
k=(&kernel->values[kernel->width*kernel->height-1]);
for (v=0; v < (ssize_t) kernel->height; v++)
{
for (u=0; u < (ssize_t) kernel->width; u++)
{
if (!IsNaN(*k))
{
if ((pixels[i]+(*k)) < pixel)
pixel=(double) pixels[i]+(*k);
count++;
}
k--;
pixels+=GetPixelChannels(image);
}
pixels+=(image->columns-1)*GetPixelChannels(image);
}
break;
}
case UndefinedMorphology:
default:
break;
}
if (fabs(pixel-p[center+i]) > MagickEpsilon)
changes[id]++;
gamma=PerceptibleReciprocal(gamma);
if (count != 0)
gamma*=(double) kernel->height*kernel->width/count;
SetPixelChannel(morphology_image,channel,ClampToQuantum(gamma*pixel),q);
}
p+=GetPixelChannels(image);
q+=GetPixelChannels(morphology_image);
}
if (SyncCacheViewAuthenticPixels(morphology_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_MorphologyPrimitive)
#endif
proceed=SetImageProgress(image,MorphologyTag,progress++,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
morphology_view=DestroyCacheView(morphology_view);
image_view=DestroyCacheView(image_view);
for (j=0; j < (ssize_t) GetOpenMPMaximumThreads(); j++)
changed+=changes[j];
changes=(size_t *) RelinquishMagickMemory(changes);
return(status ? (ssize_t) changed : -1);
}
/*
This is almost identical to the MorphologyPrimative() function above, but
applies the primitive directly to the actual image using two passes, once in
each direction, with the results of the previous (and current) row being
re-used.
That is after each row is 'Sync'ed' into the image, the next row makes use of
those values as part of the calculation of the next row. It repeats, but
going in the oppisite (bottom-up) direction.
Because of this 're-use of results' this function can not make use of multi-
threaded, parellel processing.
*/
static ssize_t MorphologyPrimitiveDirect(Image *image,
const MorphologyMethod method,const KernelInfo *kernel,
ExceptionInfo *exception)
{
CacheView
*morphology_view,
*image_view;
MagickBooleanType
status;
MagickOffsetType
progress;
OffsetInfo
offset;
size_t
width,
changed;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
assert(kernel != (KernelInfo *) NULL);
assert(kernel->signature == MagickCoreSignature);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
status=MagickTrue;
changed=0;
progress=0;
switch(method)
{
case DistanceMorphology:
case VoronoiMorphology:
{
/*
Kernel reflected about origin.
*/
offset.x=(ssize_t) kernel->width-kernel->x-1;
offset.y=(ssize_t) kernel->height-kernel->y-1;
break;
}
default:
{
offset.x=kernel->x;
offset.y=kernel->y;
break;
}
}
/*
Two views into same image, do not thread.
*/
image_view=AcquireVirtualCacheView(image,exception);
morphology_view=AcquireAuthenticCacheView(image,exception);
width=image->columns+kernel->width-1;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
register Quantum
*magick_restrict q;
register ssize_t
x;
ssize_t
center;
/*
Read virtual pixels, and authentic pixels, from the same image! We read
using virtual to get virtual pixel handling, but write back into the same
image.
Only top half of kernel is processed as we do a single pass downward
through the image iterating the distance function as we go.
*/
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,-offset.x,y-offset.y,width,(size_t)
offset.y+1,exception);
q=GetCacheViewAuthenticPixels(morphology_view,0,y,image->columns,1,
exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
center=(ssize_t) (GetPixelChannels(image)*width*offset.y+
GetPixelChannels(image)*offset.x);
for (x=0; x < (ssize_t) image->columns; x++)
{
register ssize_t
i;
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
double
pixel;
PixelTrait
traits;
register const MagickRealType
*magick_restrict k;
register const Quantum
*magick_restrict pixels;
register ssize_t
u;
ssize_t
v;
traits=GetPixelChannelTraits(image,(PixelChannel) i);
if (traits == UndefinedPixelTrait)
continue;
if (((traits & CopyPixelTrait) != 0) ||
(GetPixelWriteMask(image,p+center) <= (QuantumRange/2)))
continue;
pixels=p;
pixel=(double) QuantumRange;
switch (method)
{
case DistanceMorphology:
{
k=(&kernel->values[kernel->width*kernel->height-1]);
for (v=0; v <= offset.y; v++)
{
for (u=0; u < (ssize_t) kernel->width; u++)
{
if (!IsNaN(*k))
{
if ((pixels[i]+(*k)) < pixel)
pixel=(double) pixels[i]+(*k);
}
k--;
pixels+=GetPixelChannels(image);
}
pixels+=(image->columns-1)*GetPixelChannels(image);
}
k=(&kernel->values[kernel->width*(kernel->y+1)-1]);
pixels=q-offset.x*GetPixelChannels(image);
for (u=0; u < offset.x; u++)
{
if (!IsNaN(*k) && ((x+u-offset.x) >= 0))
{
if ((pixels[i]+(*k)) < pixel)
pixel=(double) pixels[i]+(*k);
}
k--;
pixels+=GetPixelChannels(image);
}
break;
}
case VoronoiMorphology:
{
k=(&kernel->values[kernel->width*kernel->height-1]);
for (v=0; v < offset.y; v++)
{
for (u=0; u < (ssize_t) kernel->width; u++)
{
if (!IsNaN(*k))
{
if ((pixels[i]+(*k)) < pixel)
pixel=(double) pixels[i]+(*k);
}
k--;
pixels+=GetPixelChannels(image);
}
pixels+=(image->columns-1)*GetPixelChannels(image);
}
k=(&kernel->values[kernel->width*(kernel->y+1)-1]);
pixels=q-offset.x*GetPixelChannels(image);
for (u=0; u < offset.x; u++)
{
if (!IsNaN(*k) && ((x+u-offset.x) >= 0))
{
if ((pixels[i]+(*k)) < pixel)
pixel=(double) pixels[i]+(*k);
}
k--;
pixels+=GetPixelChannels(image);
}
break;
}
default:
break;
}
if (fabs(pixel-q[i]) > MagickEpsilon)
changed++;
q[i]=ClampToQuantum(pixel);
}
p+=GetPixelChannels(image);
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(morphology_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,MorphologyTag,progress++,2*image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
morphology_view=DestroyCacheView(morphology_view);
image_view=DestroyCacheView(image_view);
/*
Do the reverse pass through the image.
*/
image_view=AcquireVirtualCacheView(image,exception);
morphology_view=AcquireAuthenticCacheView(image,exception);
for (y=(ssize_t) image->rows-1; y >= 0; y--)
{
register const Quantum
*magick_restrict p;
register Quantum
*magick_restrict q;
register ssize_t
x;
ssize_t
center;
/*
Read virtual pixels, and authentic pixels, from the same image. We
read using virtual to get virtual pixel handling, but write back
into the same image.
Only the bottom half of the kernel is processed as we up the image.
*/
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,-offset.x,y,width,(size_t)
kernel->y+1,exception);
q=GetCacheViewAuthenticPixels(morphology_view,0,y,image->columns,1,
exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
p+=(image->columns-1)*GetPixelChannels(image);
q+=(image->columns-1)*GetPixelChannels(image);
center=(ssize_t) (offset.x*GetPixelChannels(image));
for (x=(ssize_t) image->columns-1; x >= 0; x--)
{
register ssize_t
i;
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
double
pixel;
PixelTrait
traits;
register const MagickRealType
*magick_restrict k;
register const Quantum
*magick_restrict pixels;
register ssize_t
u;
ssize_t
v;
traits=GetPixelChannelTraits(image,(PixelChannel) i);
if (traits == UndefinedPixelTrait)
continue;
if (((traits & CopyPixelTrait) != 0) ||
(GetPixelWriteMask(image,p+center) <= (QuantumRange/2)))
continue;
pixels=p;
pixel=(double) QuantumRange;
switch (method)
{
case DistanceMorphology:
{
k=(&kernel->values[kernel->width*(kernel->y+1)-1]);
for (v=offset.y; v < (ssize_t) kernel->height; v++)
{
for (u=0; u < (ssize_t) kernel->width; u++)
{
if (!IsNaN(*k))
{
if ((pixels[i]+(*k)) < pixel)
pixel=(double) pixels[i]+(*k);
}
k--;
pixels+=GetPixelChannels(image);
}
pixels+=(image->columns-1)*GetPixelChannels(image);
}
k=(&kernel->values[kernel->width*kernel->y+kernel->x-1]);
pixels=q;
for (u=offset.x+1; u < (ssize_t) kernel->width; u++)
{
pixels+=GetPixelChannels(image);
if (!IsNaN(*k) && ((x+u-offset.x) < (ssize_t) image->columns))
{
if ((pixels[i]+(*k)) < pixel)
pixel=(double) pixels[i]+(*k);
}
k--;
}
break;
}
case VoronoiMorphology:
{
k=(&kernel->values[kernel->width*(kernel->y+1)-1]);
for (v=offset.y; v < (ssize_t) kernel->height; v++)
{
for (u=0; u < (ssize_t) kernel->width; u++)
{
if (!IsNaN(*k))
{
if ((pixels[i]+(*k)) < pixel)
pixel=(double) pixels[i]+(*k);
}
k--;
pixels+=GetPixelChannels(image);
}
pixels+=(image->columns-1)*GetPixelChannels(image);
}
k=(&kernel->values[kernel->width*(kernel->y+1)-1]);
pixels=q;
for (u=offset.x+1; u < (ssize_t) kernel->width; u++)
{
pixels+=GetPixelChannels(image);
if (!IsNaN(*k) && ((x+u-offset.x) < (ssize_t) image->columns))
{
if ((pixels[i]+(*k)) < pixel)
pixel=(double) pixels[i]+(*k);
}
k--;
}
break;
}
default:
break;
}
if (fabs(pixel-q[i]) > MagickEpsilon)
changed++;
q[i]=ClampToQuantum(pixel);
}
p-=GetPixelChannels(image);
q-=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(morphology_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,MorphologyTag,progress++,2*image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
morphology_view=DestroyCacheView(morphology_view);
image_view=DestroyCacheView(image_view);
return(status ? (ssize_t) changed : -1);
}
/*
Apply a Morphology by calling one of the above low level primitive
application functions. This function handles any iteration loops,
composition or re-iteration of results, and compound morphology methods that
is based on multiple low-level (staged) morphology methods.
Basically this provides the complex glue between the requested morphology
method and raw low-level implementation (above).
*/
MagickPrivate Image *MorphologyApply(const Image *image,
const MorphologyMethod method, const ssize_t iterations,
const KernelInfo *kernel, const CompositeOperator compose,const double bias,
ExceptionInfo *exception)
{
CompositeOperator
curr_compose;
Image
*curr_image, /* Image we are working with or iterating */
*work_image, /* secondary image for primitive iteration */
*save_image, /* saved image - for 'edge' method only */
*rslt_image; /* resultant image - after multi-kernel handling */
KernelInfo
*reflected_kernel, /* A reflected copy of the kernel (if needed) */
*norm_kernel, /* the current normal un-reflected kernel */
*rflt_kernel, /* the current reflected kernel (if needed) */
*this_kernel; /* the kernel being applied */
MorphologyMethod
primitive; /* the current morphology primitive being applied */
CompositeOperator
rslt_compose; /* multi-kernel compose method for results to use */
MagickBooleanType
special, /* do we use a direct modify function? */
verbose; /* verbose output of results */
size_t
method_loop, /* Loop 1: number of compound method iterations (norm 1) */
method_limit, /* maximum number of compound method iterations */
kernel_number, /* Loop 2: the kernel number being applied */
stage_loop, /* Loop 3: primitive loop for compound morphology */
stage_limit, /* how many primitives are in this compound */
kernel_loop, /* Loop 4: iterate the kernel over image */
kernel_limit, /* number of times to iterate kernel */
count, /* total count of primitive steps applied */
kernel_changed, /* total count of changed using iterated kernel */
method_changed; /* total count of changed over method iteration */
ssize_t
changed; /* number pixels changed by last primitive operation */
char
v_info[MagickPathExtent];
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
assert(kernel != (KernelInfo *) NULL);
assert(kernel->signature == MagickCoreSignature);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
count = 0; /* number of low-level morphology primitives performed */
if ( iterations == 0 )
return((Image *) NULL); /* null operation - nothing to do! */
kernel_limit = (size_t) iterations;
if ( iterations < 0 ) /* negative interations = infinite (well alomst) */
kernel_limit = image->columns>image->rows ? image->columns : image->rows;
verbose = IsStringTrue(GetImageArtifact(image,"debug"));
/* initialise for cleanup */
curr_image = (Image *) image;
curr_compose = image->compose;
(void) curr_compose;
work_image = save_image = rslt_image = (Image *) NULL;
reflected_kernel = (KernelInfo *) NULL;
/* Initialize specific methods
* + which loop should use the given iteratations
* + how many primitives make up the compound morphology
* + multi-kernel compose method to use (by default)
*/
method_limit = 1; /* just do method once, unless otherwise set */
stage_limit = 1; /* assume method is not a compound */
special = MagickFalse; /* assume it is NOT a direct modify primitive */
rslt_compose = compose; /* and we are composing multi-kernels as given */
switch( method ) {
case SmoothMorphology: /* 4 primitive compound morphology */
stage_limit = 4;
break;
case OpenMorphology: /* 2 primitive compound morphology */
case OpenIntensityMorphology:
case TopHatMorphology:
case CloseMorphology:
case CloseIntensityMorphology:
case BottomHatMorphology:
case EdgeMorphology:
stage_limit = 2;
break;
case HitAndMissMorphology:
rslt_compose = LightenCompositeOp; /* Union of multi-kernel results */
/* FALL THUR */
case ThinningMorphology:
case ThickenMorphology:
method_limit = kernel_limit; /* iterate the whole method */
kernel_limit = 1; /* do not do kernel iteration */
break;
case DistanceMorphology:
case VoronoiMorphology:
special = MagickTrue; /* use special direct primative */
break;
default:
break;
}
/* Apply special methods with special requirments
** For example, single run only, or post-processing requirements
*/
if ( special != MagickFalse )
{
rslt_image=CloneImage(image,0,0,MagickTrue,exception);
if (rslt_image == (Image *) NULL)
goto error_cleanup;
if (SetImageStorageClass(rslt_image,DirectClass,exception) == MagickFalse)
goto error_cleanup;
changed=MorphologyPrimitiveDirect(rslt_image,method,kernel,exception);
if (verbose != MagickFalse)
(void) (void) FormatLocaleFile(stderr,
"%s:%.20g.%.20g #%.20g => Changed %.20g\n",
CommandOptionToMnemonic(MagickMorphologyOptions, method),
1.0,0.0,1.0, (double) changed);
if ( changed < 0 )
goto error_cleanup;
if ( method == VoronoiMorphology ) {
/* Preserve the alpha channel of input image - but turned it off */
(void) SetImageAlphaChannel(rslt_image, DeactivateAlphaChannel,
exception);
(void) CompositeImage(rslt_image,image,CopyAlphaCompositeOp,
MagickTrue,0,0,exception);
(void) SetImageAlphaChannel(rslt_image, DeactivateAlphaChannel,
exception);
}
goto exit_cleanup;
}
/* Handle user (caller) specified multi-kernel composition method */
if ( compose != UndefinedCompositeOp )
rslt_compose = compose; /* override default composition for method */
if ( rslt_compose == UndefinedCompositeOp )
rslt_compose = NoCompositeOp; /* still not defined! Then re-iterate */
/* Some methods require a reflected kernel to use with primitives.
* Create the reflected kernel for those methods. */
switch ( method ) {
case CorrelateMorphology:
case CloseMorphology:
case CloseIntensityMorphology:
case BottomHatMorphology:
case SmoothMorphology:
reflected_kernel = CloneKernelInfo(kernel);
if (reflected_kernel == (KernelInfo *) NULL)
goto error_cleanup;
RotateKernelInfo(reflected_kernel,180);
break;
default:
break;
}
/* Loops around more primitive morpholgy methods
** erose, dilate, open, close, smooth, edge, etc...
*/
/* Loop 1: iterate the compound method */
method_loop = 0;
method_changed = 1;
while ( method_loop < method_limit && method_changed > 0 ) {
method_loop++;
method_changed = 0;
/* Loop 2: iterate over each kernel in a multi-kernel list */
norm_kernel = (KernelInfo *) kernel;
this_kernel = (KernelInfo *) kernel;
rflt_kernel = reflected_kernel;
kernel_number = 0;
while ( norm_kernel != NULL ) {
/* Loop 3: Compound Morphology Staging - Select Primative to apply */
stage_loop = 0; /* the compound morphology stage number */
while ( stage_loop < stage_limit ) {
stage_loop++; /* The stage of the compound morphology */
/* Select primitive morphology for this stage of compound method */
this_kernel = norm_kernel; /* default use unreflected kernel */
primitive = method; /* Assume method is a primitive */
switch( method ) {
case ErodeMorphology: /* just erode */
case EdgeInMorphology: /* erode and image difference */
primitive = ErodeMorphology;
break;
case DilateMorphology: /* just dilate */
case EdgeOutMorphology: /* dilate and image difference */
primitive = DilateMorphology;
break;
case OpenMorphology: /* erode then dialate */
case TopHatMorphology: /* open and image difference */
primitive = ErodeMorphology;
if ( stage_loop == 2 )
primitive = DilateMorphology;
break;
case OpenIntensityMorphology:
primitive = ErodeIntensityMorphology;
if ( stage_loop == 2 )
primitive = DilateIntensityMorphology;
break;
case CloseMorphology: /* dilate, then erode */
case BottomHatMorphology: /* close and image difference */
this_kernel = rflt_kernel; /* use the reflected kernel */
primitive = DilateMorphology;
if ( stage_loop == 2 )
primitive = ErodeMorphology;
break;
case CloseIntensityMorphology:
this_kernel = rflt_kernel; /* use the reflected kernel */
primitive = DilateIntensityMorphology;
if ( stage_loop == 2 )
primitive = ErodeIntensityMorphology;
break;
case SmoothMorphology: /* open, close */
switch ( stage_loop ) {
case 1: /* start an open method, which starts with Erode */
primitive = ErodeMorphology;
break;
case 2: /* now Dilate the Erode */
primitive = DilateMorphology;
break;
case 3: /* Reflect kernel a close */
this_kernel = rflt_kernel; /* use the reflected kernel */
primitive = DilateMorphology;
break;
case 4: /* Finish the Close */
this_kernel = rflt_kernel; /* use the reflected kernel */
primitive = ErodeMorphology;
break;
}
break;
case EdgeMorphology: /* dilate and erode difference */
primitive = DilateMorphology;
if ( stage_loop == 2 ) {
save_image = curr_image; /* save the image difference */
curr_image = (Image *) image;
primitive = ErodeMorphology;
}
break;
case CorrelateMorphology:
/* A Correlation is a Convolution with a reflected kernel.
** However a Convolution is a weighted sum using a reflected
** kernel. It may seem stange to convert a Correlation into a
** Convolution as the Correlation is the simplier method, but
** Convolution is much more commonly used, and it makes sense to
** implement it directly so as to avoid the need to duplicate the
** kernel when it is not required (which is typically the
** default).
*/
this_kernel = rflt_kernel; /* use the reflected kernel */
primitive = ConvolveMorphology;
break;
default:
break;
}
assert( this_kernel != (KernelInfo *) NULL );
/* Extra information for debugging compound operations */
if (verbose != MagickFalse) {
if ( stage_limit > 1 )
(void) FormatLocaleString(v_info,MagickPathExtent,"%s:%.20g.%.20g -> ",
CommandOptionToMnemonic(MagickMorphologyOptions,method),(double)
method_loop,(double) stage_loop);
else if ( primitive != method )
(void) FormatLocaleString(v_info, MagickPathExtent, "%s:%.20g -> ",
CommandOptionToMnemonic(MagickMorphologyOptions, method),(double)
method_loop);
else
v_info[0] = '\0';
}
/* Loop 4: Iterate the kernel with primitive */
kernel_loop = 0;
kernel_changed = 0;
changed = 1;
while ( kernel_loop < kernel_limit && changed > 0 ) {
kernel_loop++; /* the iteration of this kernel */
/* Create a clone as the destination image, if not yet defined */
if ( work_image == (Image *) NULL )
{
work_image=CloneImage(image,0,0,MagickTrue,exception);
if (work_image == (Image *) NULL)
goto error_cleanup;
if (SetImageStorageClass(work_image,DirectClass,exception) == MagickFalse)
goto error_cleanup;
}
/* APPLY THE MORPHOLOGICAL PRIMITIVE (curr -> work) */
count++;
changed = MorphologyPrimitive(curr_image, work_image, primitive,
this_kernel, bias, exception);
if (verbose != MagickFalse) {
if ( kernel_loop > 1 )
(void) FormatLocaleFile(stderr, "\n"); /* add end-of-line from previous */
(void) (void) FormatLocaleFile(stderr,
"%s%s%s:%.20g.%.20g #%.20g => Changed %.20g",
v_info,CommandOptionToMnemonic(MagickMorphologyOptions,
primitive),(this_kernel == rflt_kernel ) ? "*" : "",
(double) (method_loop+kernel_loop-1),(double) kernel_number,
(double) count,(double) changed);
}
if ( changed < 0 )
goto error_cleanup;
kernel_changed += changed;
method_changed += changed;
/* prepare next loop */
{ Image *tmp = work_image; /* swap images for iteration */
work_image = curr_image;
curr_image = tmp;
}
if ( work_image == image )
work_image = (Image *) NULL; /* replace input 'image' */
} /* End Loop 4: Iterate the kernel with primitive */
if (verbose != MagickFalse && kernel_changed != (size_t)changed)
(void) FormatLocaleFile(stderr, " Total %.20g",(double) kernel_changed);
if (verbose != MagickFalse && stage_loop < stage_limit)
(void) FormatLocaleFile(stderr, "\n"); /* add end-of-line before looping */
#if 0
(void) FormatLocaleFile(stderr, "--E-- image=0x%lx\n", (unsigned long)image);
(void) FormatLocaleFile(stderr, " curr =0x%lx\n", (unsigned long)curr_image);
(void) FormatLocaleFile(stderr, " work =0x%lx\n", (unsigned long)work_image);
(void) FormatLocaleFile(stderr, " save =0x%lx\n", (unsigned long)save_image);
(void) FormatLocaleFile(stderr, " union=0x%lx\n", (unsigned long)rslt_image);
#endif
} /* End Loop 3: Primative (staging) Loop for Coumpound Methods */
/* Final Post-processing for some Compound Methods
**
** The removal of any 'Sync' channel flag in the Image Compositon
** below ensures the methematical compose method is applied in a
** purely mathematical way, and only to the selected channels.
** Turn off SVG composition 'alpha blending'.
*/
switch( method ) {
case EdgeOutMorphology:
case EdgeInMorphology:
case TopHatMorphology:
case BottomHatMorphology:
if (verbose != MagickFalse)
(void) FormatLocaleFile(stderr,
"\n%s: Difference with original image",CommandOptionToMnemonic(
MagickMorphologyOptions, method) );
(void) CompositeImage(curr_image,image,DifferenceCompositeOp,
MagickTrue,0,0,exception);
break;
case EdgeMorphology:
if (verbose != MagickFalse)
(void) FormatLocaleFile(stderr,
"\n%s: Difference of Dilate and Erode",CommandOptionToMnemonic(
MagickMorphologyOptions, method) );
(void) CompositeImage(curr_image,save_image,DifferenceCompositeOp,
MagickTrue,0,0,exception);
save_image = DestroyImage(save_image); /* finished with save image */
break;
default:
break;
}
/* multi-kernel handling: re-iterate, or compose results */
if ( kernel->next == (KernelInfo *) NULL )
rslt_image = curr_image; /* just return the resulting image */
else if ( rslt_compose == NoCompositeOp )
{ if (verbose != MagickFalse) {
if ( this_kernel->next != (KernelInfo *) NULL )
(void) FormatLocaleFile(stderr, " (re-iterate)");
else
(void) FormatLocaleFile(stderr, " (done)");
}
rslt_image = curr_image; /* return result, and re-iterate */
}
else if ( rslt_image == (Image *) NULL)
{ if (verbose != MagickFalse)
(void) FormatLocaleFile(stderr, " (save for compose)");
rslt_image = curr_image;
curr_image = (Image *) image; /* continue with original image */
}
else
{ /* Add the new 'current' result to the composition
**
** The removal of any 'Sync' channel flag in the Image Compositon
** below ensures the methematical compose method is applied in a
** purely mathematical way, and only to the selected channels.
** IE: Turn off SVG composition 'alpha blending'.
*/
if (verbose != MagickFalse)
(void) FormatLocaleFile(stderr, " (compose \"%s\")",
CommandOptionToMnemonic(MagickComposeOptions, rslt_compose) );
(void) CompositeImage(rslt_image,curr_image,rslt_compose,MagickTrue,
0,0,exception);
curr_image = DestroyImage(curr_image);
curr_image = (Image *) image; /* continue with original image */
}
if (verbose != MagickFalse)
(void) FormatLocaleFile(stderr, "\n");
/* loop to the next kernel in a multi-kernel list */
norm_kernel = norm_kernel->next;
if ( rflt_kernel != (KernelInfo *) NULL )
rflt_kernel = rflt_kernel->next;
kernel_number++;
} /* End Loop 2: Loop over each kernel */
} /* End Loop 1: compound method interation */
goto exit_cleanup;
/* Yes goto's are bad, but it makes cleanup lot more efficient */
error_cleanup:
if ( curr_image == rslt_image )
curr_image = (Image *) NULL;
if ( rslt_image != (Image *) NULL )
rslt_image = DestroyImage(rslt_image);
exit_cleanup:
if ( curr_image == rslt_image || curr_image == image )
curr_image = (Image *) NULL;
if ( curr_image != (Image *) NULL )
curr_image = DestroyImage(curr_image);
if ( work_image != (Image *) NULL )
work_image = DestroyImage(work_image);
if ( save_image != (Image *) NULL )
save_image = DestroyImage(save_image);
if ( reflected_kernel != (KernelInfo *) NULL )
reflected_kernel = DestroyKernelInfo(reflected_kernel);
return(rslt_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% M o r p h o l o g y I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% MorphologyImage() applies a user supplied kernel to the image according to
% the given mophology method.
%
% This function applies any and all user defined settings before calling
% the above internal function MorphologyApply().
%
% User defined settings include...
% * Output Bias for Convolution and correlation ("-define convolve:bias=??")
% * Kernel Scale/normalize settings ("-define convolve:scale=??")
% This can also includes the addition of a scaled unity kernel.
% * Show Kernel being applied ("-define morphology:showkernel=1")
%
% Other operators that do not want user supplied options interfering,
% especially "convolve:bias" and "morphology:showkernel" should use
% MorphologyApply() directly.
%
% The format of the MorphologyImage method is:
%
% Image *MorphologyImage(const Image *image,MorphologyMethod method,
% const ssize_t iterations,KernelInfo *kernel,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o method: the morphology method to be applied.
%
% o iterations: apply the operation this many times (or no change).
% A value of -1 means loop until no change found.
% How this is applied may depend on the morphology method.
% Typically this is a value of 1.
%
% o kernel: An array of double representing the morphology kernel.
% Warning: kernel may be normalized for the Convolve method.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *MorphologyImage(const Image *image,
const MorphologyMethod method,const ssize_t iterations,
const KernelInfo *kernel,ExceptionInfo *exception)
{
const char
*artifact;
CompositeOperator
compose;
double
bias;
Image
*morphology_image;
KernelInfo
*curr_kernel;
curr_kernel = (KernelInfo *) kernel;
bias=0.0;
compose = UndefinedCompositeOp; /* use default for method */
/* Apply Convolve/Correlate Normalization and Scaling Factors.
* This is done BEFORE the ShowKernelInfo() function is called so that
* users can see the results of the 'option:convolve:scale' option.
*/
if ( method == ConvolveMorphology || method == CorrelateMorphology ) {
/* Get the bias value as it will be needed */
artifact = GetImageArtifact(image,"convolve:bias");
if ( artifact != (const char *) NULL) {
if (IsGeometry(artifact) == MagickFalse)
(void) ThrowMagickException(exception,GetMagickModule(),
OptionWarning,"InvalidSetting","'%s' '%s'",
"convolve:bias",artifact);
else
bias=StringToDoubleInterval(artifact,(double) QuantumRange+1.0);
}
/* Scale kernel according to user wishes */
artifact = GetImageArtifact(image,"convolve:scale");
if ( artifact != (const char *) NULL ) {
if (IsGeometry(artifact) == MagickFalse)
(void) ThrowMagickException(exception,GetMagickModule(),
OptionWarning,"InvalidSetting","'%s' '%s'",
"convolve:scale",artifact);
else {
if ( curr_kernel == kernel )
curr_kernel = CloneKernelInfo(kernel);
if (curr_kernel == (KernelInfo *) NULL)
return((Image *) NULL);
ScaleGeometryKernelInfo(curr_kernel, artifact);
}
}
}
/* display the (normalized) kernel via stderr */
artifact=GetImageArtifact(image,"morphology:showkernel");
if (IsStringTrue(artifact) != MagickFalse)
ShowKernelInfo(curr_kernel);
/* Override the default handling of multi-kernel morphology results
* If 'Undefined' use the default method
* If 'None' (default for 'Convolve') re-iterate previous result
* Otherwise merge resulting images using compose method given.
* Default for 'HitAndMiss' is 'Lighten'.
*/
{
ssize_t
parse;
artifact = GetImageArtifact(image,"morphology:compose");
if ( artifact != (const char *) NULL) {
parse=ParseCommandOption(MagickComposeOptions,
MagickFalse,artifact);
if ( parse < 0 )
(void) ThrowMagickException(exception,GetMagickModule(),
OptionWarning,"UnrecognizedComposeOperator","'%s' '%s'",
"morphology:compose",artifact);
else
compose=(CompositeOperator)parse;
}
}
/* Apply the Morphology */
morphology_image = MorphologyApply(image,method,iterations,
curr_kernel,compose,bias,exception);
/* Cleanup and Exit */
if ( curr_kernel != kernel )
curr_kernel=DestroyKernelInfo(curr_kernel);
return(morphology_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ R o t a t e K e r n e l I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RotateKernelInfo() rotates the kernel by the angle given.
%
% Currently it is restricted to 90 degree angles, of either 1D kernels
% or square kernels. And 'circular' rotations of 45 degrees for 3x3 kernels.
% It will ignore usless rotations for specific 'named' built-in kernels.
%
% The format of the RotateKernelInfo method is:
%
% void RotateKernelInfo(KernelInfo *kernel, double angle)
%
% A description of each parameter follows:
%
% o kernel: the Morphology/Convolution kernel
%
% o angle: angle to rotate in degrees
%
% This function is currently internal to this module only, but can be exported
% to other modules if needed.
*/
static void RotateKernelInfo(KernelInfo *kernel, double angle)
{
/* angle the lower kernels first */
if ( kernel->next != (KernelInfo *) NULL)
RotateKernelInfo(kernel->next, angle);
/* WARNING: Currently assumes the kernel (rightly) is horizontally symetrical
**
** TODO: expand beyond simple 90 degree rotates, flips and flops
*/
/* Modulus the angle */
angle = fmod(angle, 360.0);
if ( angle < 0 )
angle += 360.0;
if ( 337.5 < angle || angle <= 22.5 )
return; /* Near zero angle - no change! - At least not at this time */
/* Handle special cases */
switch (kernel->type) {
/* These built-in kernels are cylindrical kernels, rotating is useless */
case GaussianKernel:
case DoGKernel:
case LoGKernel:
case DiskKernel:
case PeaksKernel:
case LaplacianKernel:
case ChebyshevKernel:
case ManhattanKernel:
case EuclideanKernel:
return;
/* These may be rotatable at non-90 angles in the future */
/* but simply rotating them in multiples of 90 degrees is useless */
case SquareKernel:
case DiamondKernel:
case PlusKernel:
case CrossKernel:
return;
/* These only allows a +/-90 degree rotation (by transpose) */
/* A 180 degree rotation is useless */
case BlurKernel:
if ( 135.0 < angle && angle <= 225.0 )
return;
if ( 225.0 < angle && angle <= 315.0 )
angle -= 180;
break;
default:
break;
}
/* Attempt rotations by 45 degrees -- 3x3 kernels only */
if ( 22.5 < fmod(angle,90.0) && fmod(angle,90.0) <= 67.5 )
{
if ( kernel->width == 3 && kernel->height == 3 )
{ /* Rotate a 3x3 square by 45 degree angle */
double t = kernel->values[0];
kernel->values[0] = kernel->values[3];
kernel->values[3] = kernel->values[6];
kernel->values[6] = kernel->values[7];
kernel->values[7] = kernel->values[8];
kernel->values[8] = kernel->values[5];
kernel->values[5] = kernel->values[2];
kernel->values[2] = kernel->values[1];
kernel->values[1] = t;
/* rotate non-centered origin */
if ( kernel->x != 1 || kernel->y != 1 ) {
ssize_t x,y;
x = (ssize_t) kernel->x-1;
y = (ssize_t) kernel->y-1;
if ( x == y ) x = 0;
else if ( x == 0 ) x = -y;
else if ( x == -y ) y = 0;
else if ( y == 0 ) y = x;
kernel->x = (ssize_t) x+1;
kernel->y = (ssize_t) y+1;
}
angle = fmod(angle+315.0, 360.0); /* angle reduced 45 degrees */
kernel->angle = fmod(kernel->angle+45.0, 360.0);
}
else
perror("Unable to rotate non-3x3 kernel by 45 degrees");
}
if ( 45.0 < fmod(angle, 180.0) && fmod(angle,180.0) <= 135.0 )
{
if ( kernel->width == 1 || kernel->height == 1 )
{ /* Do a transpose of a 1 dimensional kernel,
** which results in a fast 90 degree rotation of some type.
*/
ssize_t
t;
t = (ssize_t) kernel->width;
kernel->width = kernel->height;
kernel->height = (size_t) t;
t = kernel->x;
kernel->x = kernel->y;
kernel->y = t;
if ( kernel->width == 1 ) {
angle = fmod(angle+270.0, 360.0); /* angle reduced 90 degrees */
kernel->angle = fmod(kernel->angle+90.0, 360.0);
} else {
angle = fmod(angle+90.0, 360.0); /* angle increased 90 degrees */
kernel->angle = fmod(kernel->angle+270.0, 360.0);
}
}
else if ( kernel->width == kernel->height )
{ /* Rotate a square array of values by 90 degrees */
{ register ssize_t
i,j,x,y;
register MagickRealType
*k,t;
k=kernel->values;
for( i=0, x=(ssize_t) kernel->width-1; i<=x; i++, x--)
for( j=0, y=(ssize_t) kernel->height-1; j<y; j++, y--)
{ t = k[i+j*kernel->width];
k[i+j*kernel->width] = k[j+x*kernel->width];
k[j+x*kernel->width] = k[x+y*kernel->width];
k[x+y*kernel->width] = k[y+i*kernel->width];
k[y+i*kernel->width] = t;
}
}
/* rotate the origin - relative to center of array */
{ register ssize_t x,y;
x = (ssize_t) (kernel->x*2-kernel->width+1);
y = (ssize_t) (kernel->y*2-kernel->height+1);
kernel->x = (ssize_t) ( -y +(ssize_t) kernel->width-1)/2;
kernel->y = (ssize_t) ( +x +(ssize_t) kernel->height-1)/2;
}
angle = fmod(angle+270.0, 360.0); /* angle reduced 90 degrees */
kernel->angle = fmod(kernel->angle+90.0, 360.0);
}
else
perror("Unable to rotate a non-square, non-linear kernel 90 degrees");
}
if ( 135.0 < angle && angle <= 225.0 )
{
/* For a 180 degree rotation - also know as a reflection
* This is actually a very very common operation!
* Basically all that is needed is a reversal of the kernel data!
* And a reflection of the origon
*/
MagickRealType
t;
register MagickRealType
*k;
ssize_t
i,
j;
k=kernel->values;
j=(ssize_t) (kernel->width*kernel->height-1);
for (i=0; i < j; i++, j--)
t=k[i], k[i]=k[j], k[j]=t;
kernel->x = (ssize_t) kernel->width - kernel->x - 1;
kernel->y = (ssize_t) kernel->height - kernel->y - 1;
angle = fmod(angle-180.0, 360.0); /* angle+180 degrees */
kernel->angle = fmod(kernel->angle+180.0, 360.0);
}
/* At this point angle should at least between -45 (315) and +45 degrees
* In the future some form of non-orthogonal angled rotates could be
* performed here, posibily with a linear kernel restriction.
*/
return;
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S c a l e G e o m e t r y K e r n e l I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ScaleGeometryKernelInfo() takes a geometry argument string, typically
% provided as a "-set option:convolve:scale {geometry}" user setting,
% and modifies the kernel according to the parsed arguments of that setting.
%
% The first argument (and any normalization flags) are passed to
% ScaleKernelInfo() to scale/normalize the kernel. The second argument
% is then passed to UnityAddKernelInfo() to add a scled unity kernel
% into the scaled/normalized kernel.
%
% The format of the ScaleGeometryKernelInfo method is:
%
% void ScaleGeometryKernelInfo(KernelInfo *kernel,
% const double scaling_factor,const MagickStatusType normalize_flags)
%
% A description of each parameter follows:
%
% o kernel: the Morphology/Convolution kernel to modify
%
% o geometry:
% The geometry string to parse, typically from the user provided
% "-set option:convolve:scale {geometry}" setting.
%
*/
MagickExport void ScaleGeometryKernelInfo (KernelInfo *kernel,
const char *geometry)
{
MagickStatusType
flags;
GeometryInfo
args;
SetGeometryInfo(&args);
flags = ParseGeometry(geometry, &args);
#if 0
/* For Debugging Geometry Input */
(void) FormatLocaleFile(stderr, "Geometry = 0x%04X : %lg x %lg %+lg %+lg\n",
flags, args.rho, args.sigma, args.xi, args.psi );
#endif
if ( (flags & PercentValue) != 0 ) /* Handle Percentage flag*/
args.rho *= 0.01, args.sigma *= 0.01;
if ( (flags & RhoValue) == 0 ) /* Set Defaults for missing args */
args.rho = 1.0;
if ( (flags & SigmaValue) == 0 )
args.sigma = 0.0;
/* Scale/Normalize the input kernel */
ScaleKernelInfo(kernel, args.rho, (GeometryFlags) flags);
/* Add Unity Kernel, for blending with original */
if ( (flags & SigmaValue) != 0 )
UnityAddKernelInfo(kernel, args.sigma);
return;
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S c a l e K e r n e l I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ScaleKernelInfo() scales the given kernel list by the given amount, with or
% without normalization of the sum of the kernel values (as per given flags).
%
% By default (no flags given) the values within the kernel is scaled
% directly using given scaling factor without change.
%
% If either of the two 'normalize_flags' are given the kernel will first be
% normalized and then further scaled by the scaling factor value given.
%
% Kernel normalization ('normalize_flags' given) is designed to ensure that
% any use of the kernel scaling factor with 'Convolve' or 'Correlate'
% morphology methods will fall into -1.0 to +1.0 range. Note that for
% non-HDRI versions of IM this may cause images to have any negative results
% clipped, unless some 'bias' is used.
%
% More specifically. Kernels which only contain positive values (such as a
% 'Gaussian' kernel) will be scaled so that those values sum to +1.0,
% ensuring a 0.0 to +1.0 output range for non-HDRI images.
%
% For Kernels that contain some negative values, (such as 'Sharpen' kernels)
% the kernel will be scaled by the absolute of the sum of kernel values, so
% that it will generally fall within the +/- 1.0 range.
%
% For kernels whose values sum to zero, (such as 'Laplician' kernels) kernel
% will be scaled by just the sum of the postive values, so that its output
% range will again fall into the +/- 1.0 range.
%
% For special kernels designed for locating shapes using 'Correlate', (often
% only containing +1 and -1 values, representing foreground/brackground
% matching) a special normalization method is provided to scale the positive
% values separately to those of the negative values, so the kernel will be
% forced to become a zero-sum kernel better suited to such searches.
%
% WARNING: Correct normalization of the kernel assumes that the '*_range'
% attributes within the kernel structure have been correctly set during the
% kernels creation.
%
% NOTE: The values used for 'normalize_flags' have been selected specifically
% to match the use of geometry options, so that '!' means NormalizeValue, '^'
% means CorrelateNormalizeValue. All other GeometryFlags values are ignored.
%
% The format of the ScaleKernelInfo method is:
%
% void ScaleKernelInfo(KernelInfo *kernel, const double scaling_factor,
% const MagickStatusType normalize_flags )
%
% A description of each parameter follows:
%
% o kernel: the Morphology/Convolution kernel
%
% o scaling_factor:
% multiply all values (after normalization) by this factor if not
% zero. If the kernel is normalized regardless of any flags.
%
% o normalize_flags:
% GeometryFlags defining normalization method to use.
% specifically: NormalizeValue, CorrelateNormalizeValue,
% and/or PercentValue
%
*/
MagickExport void ScaleKernelInfo(KernelInfo *kernel,
const double scaling_factor,const GeometryFlags normalize_flags)
{
register double
pos_scale,
neg_scale;
register ssize_t
i;
/* do the other kernels in a multi-kernel list first */
if ( kernel->next != (KernelInfo *) NULL)
ScaleKernelInfo(kernel->next, scaling_factor, normalize_flags);
/* Normalization of Kernel */
pos_scale = 1.0;
if ( (normalize_flags&NormalizeValue) != 0 ) {
if ( fabs(kernel->positive_range + kernel->negative_range) >= MagickEpsilon )
/* non-zero-summing kernel (generally positive) */
pos_scale = fabs(kernel->positive_range + kernel->negative_range);
else
/* zero-summing kernel */
pos_scale = kernel->positive_range;
}
/* Force kernel into a normalized zero-summing kernel */
if ( (normalize_flags&CorrelateNormalizeValue) != 0 ) {
pos_scale = ( fabs(kernel->positive_range) >= MagickEpsilon )
? kernel->positive_range : 1.0;
neg_scale = ( fabs(kernel->negative_range) >= MagickEpsilon )
? -kernel->negative_range : 1.0;
}
else
neg_scale = pos_scale;
/* finialize scaling_factor for positive and negative components */
pos_scale = scaling_factor/pos_scale;
neg_scale = scaling_factor/neg_scale;
for (i=0; i < (ssize_t) (kernel->width*kernel->height); i++)
if (!IsNaN(kernel->values[i]))
kernel->values[i] *= (kernel->values[i] >= 0) ? pos_scale : neg_scale;
/* convolution output range */
kernel->positive_range *= pos_scale;
kernel->negative_range *= neg_scale;
/* maximum and minimum values in kernel */
kernel->maximum *= (kernel->maximum >= 0.0) ? pos_scale : neg_scale;
kernel->minimum *= (kernel->minimum >= 0.0) ? pos_scale : neg_scale;
/* swap kernel settings if user's scaling factor is negative */
if ( scaling_factor < MagickEpsilon ) {
double t;
t = kernel->positive_range;
kernel->positive_range = kernel->negative_range;
kernel->negative_range = t;
t = kernel->maximum;
kernel->maximum = kernel->minimum;
kernel->minimum = 1;
}
return;
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S h o w K e r n e l I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ShowKernelInfo() outputs the details of the given kernel defination to
% standard error, generally due to a users 'morphology:showkernel' option
% request.
%
% The format of the ShowKernel method is:
%
% void ShowKernelInfo(const KernelInfo *kernel)
%
% A description of each parameter follows:
%
% o kernel: the Morphology/Convolution kernel
%
*/
MagickPrivate void ShowKernelInfo(const KernelInfo *kernel)
{
const KernelInfo
*k;
size_t
c, i, u, v;
for (c=0, k=kernel; k != (KernelInfo *) NULL; c++, k=k->next ) {
(void) FormatLocaleFile(stderr, "Kernel");
if ( kernel->next != (KernelInfo *) NULL )
(void) FormatLocaleFile(stderr, " #%lu", (unsigned long) c );
(void) FormatLocaleFile(stderr, " \"%s",
CommandOptionToMnemonic(MagickKernelOptions, k->type) );
if ( fabs(k->angle) >= MagickEpsilon )
(void) FormatLocaleFile(stderr, "@%lg", k->angle);
(void) FormatLocaleFile(stderr, "\" of size %lux%lu%+ld%+ld",(unsigned long)
k->width,(unsigned long) k->height,(long) k->x,(long) k->y);
(void) FormatLocaleFile(stderr,
" with values from %.*lg to %.*lg\n",
GetMagickPrecision(), k->minimum,
GetMagickPrecision(), k->maximum);
(void) FormatLocaleFile(stderr, "Forming a output range from %.*lg to %.*lg",
GetMagickPrecision(), k->negative_range,
GetMagickPrecision(), k->positive_range);
if ( fabs(k->positive_range+k->negative_range) < MagickEpsilon )
(void) FormatLocaleFile(stderr, " (Zero-Summing)\n");
else if ( fabs(k->positive_range+k->negative_range-1.0) < MagickEpsilon )
(void) FormatLocaleFile(stderr, " (Normalized)\n");
else
(void) FormatLocaleFile(stderr, " (Sum %.*lg)\n",
GetMagickPrecision(), k->positive_range+k->negative_range);
for (i=v=0; v < k->height; v++) {
(void) FormatLocaleFile(stderr, "%2lu:", (unsigned long) v );
for (u=0; u < k->width; u++, i++)
if (IsNaN(k->values[i]))
(void) FormatLocaleFile(stderr," %*s", GetMagickPrecision()+3, "nan");
else
(void) FormatLocaleFile(stderr," %*.*lg", GetMagickPrecision()+3,
GetMagickPrecision(), (double) k->values[i]);
(void) FormatLocaleFile(stderr,"\n");
}
}
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n i t y A d d K e r n a l I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnityAddKernelInfo() Adds a given amount of the 'Unity' Convolution Kernel
% to the given pre-scaled and normalized Kernel. This in effect adds that
% amount of the original image into the resulting convolution kernel. This
% value is usually provided by the user as a percentage value in the
% 'convolve:scale' setting.
%
% The resulting effect is to convert the defined kernels into blended
% soft-blurs, unsharp kernels or into sharpening kernels.
%
% The format of the UnityAdditionKernelInfo method is:
%
% void UnityAdditionKernelInfo(KernelInfo *kernel, const double scale )
%
% A description of each parameter follows:
%
% o kernel: the Morphology/Convolution kernel
%
% o scale:
% scaling factor for the unity kernel to be added to
% the given kernel.
%
*/
MagickExport void UnityAddKernelInfo(KernelInfo *kernel,
const double scale)
{
/* do the other kernels in a multi-kernel list first */
if ( kernel->next != (KernelInfo *) NULL)
UnityAddKernelInfo(kernel->next, scale);
/* Add the scaled unity kernel to the existing kernel */
kernel->values[kernel->x+kernel->y*kernel->width] += scale;
CalcKernelMetaData(kernel); /* recalculate the meta-data */
return;
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% Z e r o K e r n e l N a n s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ZeroKernelNans() replaces any special 'nan' value that may be present in
% the kernel with a zero value. This is typically done when the kernel will
% be used in special hardware (GPU) convolution processors, to simply
% matters.
%
% The format of the ZeroKernelNans method is:
%
% void ZeroKernelNans (KernelInfo *kernel)
%
% A description of each parameter follows:
%
% o kernel: the Morphology/Convolution kernel
%
*/
MagickPrivate void ZeroKernelNans(KernelInfo *kernel)
{
register size_t
i;
/* do the other kernels in a multi-kernel list first */
if (kernel->next != (KernelInfo *) NULL)
ZeroKernelNans(kernel->next);
for (i=0; i < (kernel->width*kernel->height); i++)
if (IsNaN(kernel->values[i]))
kernel->values[i]=0.0;
return;
}
|
GB_unop__exp_fp64_fp64.c | //------------------------------------------------------------------------------
// GB_unop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved.
// http://suitesparse.com See GraphBLAS/Doc/License.txt for license.
//------------------------------------------------------------------------------
// If this file is in the Generated/ folder, do not edit it (auto-generated).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_unop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB_unop_apply__exp_fp64_fp64
// op(A') function: GB_unop_tran__exp_fp64_fp64
// C type: double
// A type: double
// cast: double cij = aij
// unaryop: cij = exp (aij)
#define GB_ATYPE \
double
#define GB_CTYPE \
double
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
double aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = exp (x) ;
// casting
#define GB_CAST(z, aij) \
double z = aij ;
// cij = op (aij)
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
double aij = Ax [pA] ; \
/* Cx [pC] = op (cast (aij)) */ \
double z = aij ; \
Cx [pC] = exp (z) ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_EXP || GxB_NO_FP64)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop_apply__exp_fp64_fp64
(
double *Cx, // Cx and Ax may be aliased
const double *Ax,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
double aij = Ax [p] ;
double z = aij ;
Cx [p] = exp (z) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop_tran__exp_fp64_fp64
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t *GB_RESTRICT *Rowcounts,
GBI_single_iterator Iter,
const int64_t *GB_RESTRICT A_slice,
int naslice
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#define GB_PHASE_2_OF_2
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
convolution_sgemm_pack8to4_int8.h | // Tencent is pleased to support the open source community by making ncnn available.
//
// Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// https://opensource.org/licenses/BSD-3-Clause
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
static void im2col_sgemm_pack8to4_int8_sse(const Mat& bottom_im2col, Mat& top_blob, const Mat& kernel, const Option& opt)
{
// Mat bottom_im2col(size, maxk, inch, 8u, 8, opt.workspace_allocator);
const int size = bottom_im2col.w;
const int maxk = bottom_im2col.h;
const int inch = bottom_im2col.c;
const int outch = top_blob.c;
// permute
Mat tmp;
if (size >= 2)
tmp.create(2 * maxk, inch, size / 2 + size % 2, 8u, 8, opt.workspace_allocator);
else
tmp.create(maxk, inch, size, 8u, 8, opt.workspace_allocator);
{
int remain_size_start = 0;
int nn_size = size >> 1;
#pragma omp parallel for num_threads(opt.num_threads)
for (int ii = 0; ii < nn_size; ii++)
{
int i = remain_size_start + ii * 2;
int64_t* tmpptr = tmp.channel(i / 2);
for (int q = 0; q < inch; q++)
{
const int64_t* img0 = (const int64_t*)bottom_im2col.channel(q) + i;
for (int k = 0; k < maxk; k++)
{
__m128i _v = _mm_loadu_si128((const __m128i*)img0);
_mm_storeu_si128((__m128i*)tmpptr, _v);
tmpptr += 2;
img0 += size;
}
}
}
remain_size_start += nn_size << 1;
#pragma omp parallel for num_threads(opt.num_threads)
for (int i = remain_size_start; i < size; i++)
{
int64_t* tmpptr = tmp.channel(i / 2 + i % 2);
for (int q = 0; q < inch; q++)
{
const int64_t* img0 = (const int64_t*)bottom_im2col.channel(q) + i;
for (int k = 0; k < maxk; k++)
{
tmpptr[0] = img0[0];
tmpptr += 1;
img0 += size;
}
}
}
}
#pragma omp parallel for num_threads(opt.num_threads)
for (int p = 0; p < outch; p++)
{
int* outptr0 = top_blob.channel(p);
int i = 0;
for (; i + 1 < size; i += 2)
{
const signed char* tmpptr = tmp.channel(i / 2);
const signed char* kptr0 = kernel.channel(p);
int nn = inch * maxk; // inch always > 0
__m128i _sum00 = _mm_setzero_si128();
__m128i _sum01 = _mm_setzero_si128();
__m128i _sum02 = _mm_setzero_si128();
__m128i _sum03 = _mm_setzero_si128();
__m128i _sum10 = _mm_setzero_si128();
__m128i _sum11 = _mm_setzero_si128();
__m128i _sum12 = _mm_setzero_si128();
__m128i _sum13 = _mm_setzero_si128();
int j = 0;
for (; j < nn; j++)
{
// TODO use _mm_cvtepi8_epi16 on sse4.1
__m128i _val01 = _mm_loadu_si128((const __m128i*)tmpptr);
__m128i _extval01 = _mm_cmpgt_epi8(_mm_setzero_si128(), _val01);
__m128i _val0 = _mm_unpacklo_epi8(_val01, _extval01);
__m128i _val1 = _mm_unpackhi_epi8(_val01, _extval01);
// TODO use _mm_cvtepi8_epi16 on sse4.1
__m128i _w01 = _mm_loadu_si128((const __m128i*)kptr0);
__m128i _w23 = _mm_loadu_si128((const __m128i*)(kptr0 + 16));
__m128i _extw01 = _mm_cmpgt_epi8(_mm_setzero_si128(), _w01);
__m128i _extw23 = _mm_cmpgt_epi8(_mm_setzero_si128(), _w23);
__m128i _w0 = _mm_unpacklo_epi8(_w01, _extw01);
__m128i _w1 = _mm_unpackhi_epi8(_w01, _extw01);
__m128i _w2 = _mm_unpacklo_epi8(_w23, _extw23);
__m128i _w3 = _mm_unpackhi_epi8(_w23, _extw23);
__m128i _sl00 = _mm_mullo_epi16(_val0, _w0);
__m128i _sh00 = _mm_mulhi_epi16(_val0, _w0);
__m128i _sl01 = _mm_mullo_epi16(_val0, _w1);
__m128i _sh01 = _mm_mulhi_epi16(_val0, _w1);
__m128i _sl02 = _mm_mullo_epi16(_val0, _w2);
__m128i _sh02 = _mm_mulhi_epi16(_val0, _w2);
__m128i _sl03 = _mm_mullo_epi16(_val0, _w3);
__m128i _sh03 = _mm_mulhi_epi16(_val0, _w3);
__m128i _sl10 = _mm_mullo_epi16(_val1, _w0);
__m128i _sh10 = _mm_mulhi_epi16(_val1, _w0);
__m128i _sl11 = _mm_mullo_epi16(_val1, _w1);
__m128i _sh11 = _mm_mulhi_epi16(_val1, _w1);
__m128i _sl12 = _mm_mullo_epi16(_val1, _w2);
__m128i _sh12 = _mm_mulhi_epi16(_val1, _w2);
__m128i _sl13 = _mm_mullo_epi16(_val1, _w3);
__m128i _sh13 = _mm_mulhi_epi16(_val1, _w3);
_sum00 = _mm_add_epi32(_sum00, _mm_unpacklo_epi16(_sl00, _sh00));
_sum01 = _mm_add_epi32(_sum01, _mm_unpacklo_epi16(_sl01, _sh01));
_sum02 = _mm_add_epi32(_sum02, _mm_unpacklo_epi16(_sl02, _sh02));
_sum03 = _mm_add_epi32(_sum03, _mm_unpacklo_epi16(_sl03, _sh03));
_sum00 = _mm_add_epi32(_sum00, _mm_unpackhi_epi16(_sl00, _sh00));
_sum01 = _mm_add_epi32(_sum01, _mm_unpackhi_epi16(_sl01, _sh01));
_sum02 = _mm_add_epi32(_sum02, _mm_unpackhi_epi16(_sl02, _sh02));
_sum03 = _mm_add_epi32(_sum03, _mm_unpackhi_epi16(_sl03, _sh03));
_sum10 = _mm_add_epi32(_sum10, _mm_unpacklo_epi16(_sl10, _sh10));
_sum11 = _mm_add_epi32(_sum11, _mm_unpacklo_epi16(_sl11, _sh11));
_sum12 = _mm_add_epi32(_sum12, _mm_unpacklo_epi16(_sl12, _sh12));
_sum13 = _mm_add_epi32(_sum13, _mm_unpacklo_epi16(_sl13, _sh13));
_sum10 = _mm_add_epi32(_sum10, _mm_unpackhi_epi16(_sl10, _sh10));
_sum11 = _mm_add_epi32(_sum11, _mm_unpackhi_epi16(_sl11, _sh11));
_sum12 = _mm_add_epi32(_sum12, _mm_unpackhi_epi16(_sl12, _sh12));
_sum13 = _mm_add_epi32(_sum13, _mm_unpackhi_epi16(_sl13, _sh13));
tmpptr += 16;
kptr0 += 32;
}
// transpose 4x4
{
__m128i _tmp0, _tmp1, _tmp2, _tmp3;
_tmp0 = _mm_unpacklo_epi32(_sum00, _sum01);
_tmp1 = _mm_unpacklo_epi32(_sum02, _sum03);
_tmp2 = _mm_unpackhi_epi32(_sum00, _sum01);
_tmp3 = _mm_unpackhi_epi32(_sum02, _sum03);
_sum00 = _mm_unpacklo_epi64(_tmp0, _tmp1);
_sum01 = _mm_unpackhi_epi64(_tmp0, _tmp1);
_sum02 = _mm_unpacklo_epi64(_tmp2, _tmp3);
_sum03 = _mm_unpackhi_epi64(_tmp2, _tmp3);
}
{
__m128i _tmp0, _tmp1, _tmp2, _tmp3;
_tmp0 = _mm_unpacklo_epi32(_sum10, _sum11);
_tmp1 = _mm_unpacklo_epi32(_sum12, _sum13);
_tmp2 = _mm_unpackhi_epi32(_sum10, _sum11);
_tmp3 = _mm_unpackhi_epi32(_sum12, _sum13);
_sum10 = _mm_unpacklo_epi64(_tmp0, _tmp1);
_sum11 = _mm_unpackhi_epi64(_tmp0, _tmp1);
_sum12 = _mm_unpacklo_epi64(_tmp2, _tmp3);
_sum13 = _mm_unpackhi_epi64(_tmp2, _tmp3);
}
_sum00 = _mm_add_epi32(_sum00, _sum01);
_sum02 = _mm_add_epi32(_sum02, _sum03);
_sum10 = _mm_add_epi32(_sum10, _sum11);
_sum12 = _mm_add_epi32(_sum12, _sum13);
_sum00 = _mm_add_epi32(_sum00, _sum02);
_sum10 = _mm_add_epi32(_sum10, _sum12);
_mm_storeu_si128((__m128i*)outptr0, _sum00);
_mm_storeu_si128((__m128i*)(outptr0 + 4), _sum10);
outptr0 += 8;
}
for (; i < size; i++)
{
const signed char* tmpptr = tmp.channel(i / 2 + i % 2);
const signed char* kptr0 = kernel.channel(p);
int nn = inch * maxk; // inch always > 0
__m128i _sum0 = _mm_setzero_si128();
__m128i _sum1 = _mm_setzero_si128();
__m128i _sum2 = _mm_setzero_si128();
__m128i _sum3 = _mm_setzero_si128();
int j = 0;
for (; j < nn; j++)
{
// TODO use _mm_cvtepi8_epi16 on sse4.1
__m128i _val = _mm_loadl_epi64((const __m128i*)tmpptr);
_val = _mm_unpacklo_epi8(_val, _mm_cmpgt_epi8(_mm_setzero_si128(), _val));
// TODO use _mm_cvtepi8_epi16 on sse4.1
__m128i _w01 = _mm_loadu_si128((const __m128i*)kptr0);
__m128i _w23 = _mm_loadu_si128((const __m128i*)(kptr0 + 16));
__m128i _extw01 = _mm_cmpgt_epi8(_mm_setzero_si128(), _w01);
__m128i _extw23 = _mm_cmpgt_epi8(_mm_setzero_si128(), _w23);
__m128i _w0 = _mm_unpacklo_epi8(_w01, _extw01);
__m128i _w1 = _mm_unpackhi_epi8(_w01, _extw01);
__m128i _w2 = _mm_unpacklo_epi8(_w23, _extw23);
__m128i _w3 = _mm_unpackhi_epi8(_w23, _extw23);
__m128i _sl0 = _mm_mullo_epi16(_val, _w0);
__m128i _sh0 = _mm_mulhi_epi16(_val, _w0);
__m128i _sl1 = _mm_mullo_epi16(_val, _w1);
__m128i _sh1 = _mm_mulhi_epi16(_val, _w1);
__m128i _sl2 = _mm_mullo_epi16(_val, _w2);
__m128i _sh2 = _mm_mulhi_epi16(_val, _w2);
__m128i _sl3 = _mm_mullo_epi16(_val, _w3);
__m128i _sh3 = _mm_mulhi_epi16(_val, _w3);
_sum0 = _mm_add_epi32(_sum0, _mm_unpacklo_epi16(_sl0, _sh0));
_sum1 = _mm_add_epi32(_sum1, _mm_unpacklo_epi16(_sl1, _sh1));
_sum2 = _mm_add_epi32(_sum2, _mm_unpacklo_epi16(_sl2, _sh2));
_sum3 = _mm_add_epi32(_sum3, _mm_unpacklo_epi16(_sl3, _sh3));
_sum0 = _mm_add_epi32(_sum0, _mm_unpackhi_epi16(_sl0, _sh0));
_sum1 = _mm_add_epi32(_sum1, _mm_unpackhi_epi16(_sl1, _sh1));
_sum2 = _mm_add_epi32(_sum2, _mm_unpackhi_epi16(_sl2, _sh2));
_sum3 = _mm_add_epi32(_sum3, _mm_unpackhi_epi16(_sl3, _sh3));
tmpptr += 8;
kptr0 += 32;
}
// transpose 4x4
{
__m128i _tmp0, _tmp1, _tmp2, _tmp3;
_tmp0 = _mm_unpacklo_epi32(_sum0, _sum1);
_tmp1 = _mm_unpacklo_epi32(_sum2, _sum3);
_tmp2 = _mm_unpackhi_epi32(_sum0, _sum1);
_tmp3 = _mm_unpackhi_epi32(_sum2, _sum3);
_sum0 = _mm_unpacklo_epi64(_tmp0, _tmp1);
_sum1 = _mm_unpackhi_epi64(_tmp0, _tmp1);
_sum2 = _mm_unpacklo_epi64(_tmp2, _tmp3);
_sum3 = _mm_unpackhi_epi64(_tmp2, _tmp3);
}
_sum0 = _mm_add_epi32(_sum0, _sum1);
_sum2 = _mm_add_epi32(_sum2, _sum3);
_sum0 = _mm_add_epi32(_sum0, _sum2);
_mm_storeu_si128((__m128i*)outptr0, _sum0);
outptr0 += 4;
}
}
}
static void convolution_im2col_sgemm_transform_kernel_pack8to4_int8_sse(const Mat& _kernel, Mat& kernel_tm, int inch, int outch, int kernel_w, int kernel_h)
{
const int maxk = kernel_w * kernel_h;
// interleave
// src = maxk-inch-outch
// dst = 8a-4b-maxk-inch/8a-outch/4b
Mat kernel = _kernel.reshape(maxk, inch, outch);
kernel_tm.create(32 * maxk, inch / 8, outch / 4, (size_t)1u);
for (int q = 0; q + 3 < outch; q += 4)
{
signed char* g00 = kernel_tm.channel(q / 4);
for (int p = 0; p + 7 < inch; p += 8)
{
for (int k = 0; k < maxk; k++)
{
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 8; j++)
{
const signed char* k00 = kernel.channel(q + i).row<const signed char>(p + j);
g00[0] = k00[k];
g00++;
}
}
}
}
}
}
static void convolution_im2col_sgemm_pack8to4_int8_sse(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel, int kernel_w, int kernel_h, int dilation_w, int dilation_h, int stride_w, 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;
const int size = outw * outh;
const int maxk = kernel_w * kernel_h;
// im2col
Mat bottom_im2col(size, maxk, inch, 8u, 8, opt.workspace_allocator);
{
const int gap = w * stride_h - outw * stride_w;
#pragma omp parallel for num_threads(opt.num_threads)
for (int p = 0; p < inch; p++)
{
const Mat img = bottom_blob.channel(p);
int64_t* ptr = bottom_im2col.channel(p);
for (int u = 0; u < kernel_h; u++)
{
for (int v = 0; v < kernel_w; v++)
{
const int64_t* sptr = img.row<const int64_t>(dilation_h * u) + dilation_w * v;
for (int i = 0; i < outh; i++)
{
int j = 0;
for (; j < outw; j++)
{
ptr[0] = sptr[0];
sptr += stride_w;
ptr += 1;
}
sptr += gap;
}
}
}
}
}
im2col_sgemm_pack8to4_int8_sse(bottom_im2col, top_blob, kernel, opt);
}
|
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-2011 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(dynamic,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) GetIndexPixelComponent(
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);
SetRedPixelComponent(q,((MagickRealType) GetRedPixelComponent(q) <=
mean.red) ? 0 : QuantumRange);
SetGreenPixelComponent(q,((MagickRealType) GetGreenPixelComponent(q) <=
mean.green) ? 0 : QuantumRange);
SetBluePixelComponent(q,((MagickRealType) GetBluePixelComponent(q) <=
mean.blue) ? 0 : QuantumRange);
SetOpacityPixelComponent(q,((MagickRealType) GetOpacityPixelComponent(q)
<= mean.opacity) ? 0 : QuantumRange);
if (image->colorspace == CMYKColorspace)
SetIndexPixelComponent(threshold_indexes+x,(((MagickRealType)
GetIndexPixelComponent(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(dynamic,4) 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++)
{
SetRedPixelComponent(q,(MagickRealType) PixelIntensityToQuantum(q) <=
threshold ? 0 : QuantumRange);
SetGreenPixelComponent(q,GetRedPixelComponent(q));
SetBluePixelComponent(q,GetRedPixelComponent(q));
q++;
}
}
else
for (x=0; x < (ssize_t) image->columns; x++)
{
if ((channel & RedChannel) != 0)
SetRedPixelComponent(q,(MagickRealType) GetRedPixelComponent(q) <=
threshold ? 0 : QuantumRange);
if ((channel & GreenChannel) != 0)
SetGreenPixelComponent(q,(MagickRealType) GetGreenPixelComponent(q) <=
threshold ? 0 : QuantumRange);
if ((channel & BlueChannel) != 0)
SetBluePixelComponent(q,(MagickRealType) GetBluePixelComponent(q) <=
threshold ? 0 : QuantumRange);
if ((channel & OpacityChannel) != 0)
{
if (image->matte == MagickFalse)
SetOpacityPixelComponent(q,(MagickRealType)
GetOpacityPixelComponent(q) <= threshold ? 0 : QuantumRange);
else
SetOpacityPixelComponent(q,(MagickRealType)
GetOpacityPixelComponent(q) <= threshold ? OpaqueOpacity :
TransparentOpacity);
}
if (((channel & IndexChannel) != 0) &&
(image->colorspace == CMYKColorspace))
SetIndexPixelComponent(indexes+x,(MagickRealType)
GetIndexPixelComponent(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(dynamic,4) 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))
{
SetRedPixelComponent(q,0);
SetGreenPixelComponent(q,0);
SetBluePixelComponent(q,0);
if (image->colorspace == CMYKColorspace)
SetIndexPixelComponent(indexes+x,0);
}
}
else
{
if (((channel & RedChannel) != 0) &&
((MagickRealType) GetRedPixelComponent(q) < threshold.red))
SetRedPixelComponent(q,0);
if (((channel & GreenChannel) != 0) &&
((MagickRealType) GetGreenPixelComponent(q) < threshold.green))
SetGreenPixelComponent(q,0);
if (((channel & BlueChannel) != 0) &&
((MagickRealType) GetBluePixelComponent(q) < threshold.blue))
SetBluePixelComponent(q,0);
if (((channel & OpacityChannel) != 0) &&
((MagickRealType) GetOpacityPixelComponent(q) < threshold.opacity))
SetOpacityPixelComponent(q,0);
if (((channel & IndexChannel) != 0) &&
(image->colorspace == CMYKColorspace) &&
((MagickRealType) GetIndexPixelComponent(indexes+x) <
threshold.index))
SetIndexPixelComponent(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++)
{
SetRedPixelComponent(q,ClampToUnsignedQuantum(
GetRedPixelComponent(q)));
SetGreenPixelComponent(q,ClampToUnsignedQuantum(
GetGreenPixelComponent(q)));
SetBluePixelComponent(q,ClampToUnsignedQuantum(
GetBluePixelComponent(q)));
SetOpacityPixelComponent(q,ClampToUnsignedQuantum(
GetOpacityPixelComponent(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(dynamic,4) 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)
SetRedPixelComponent(q,ClampToUnsignedQuantum(
GetRedPixelComponent(q)));
if ((channel & GreenChannel) != 0)
SetGreenPixelComponent(q,ClampToUnsignedQuantum(
GetGreenPixelComponent(q)));
if ((channel & BlueChannel) != 0)
SetBluePixelComponent(q,ClampToUnsignedQuantum(
GetBluePixelComponent(q)));
if ((channel & OpacityChannel) != 0)
SetOpacityPixelComponent(q,ClampToUnsignedQuantum(
GetOpacityPixelComponent(q)));
if (((channel & IndexChannel) != 0) &&
(image->colorspace == CMYKColorspace))
SetIndexPixelComponent(indexes+x,ClampToUnsignedQuantum(
GetIndexPixelComponent(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(dynamic,4) 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*GetRedPixelComponent(q)*(levels.red*d+1));
l = t/d; t = t-l*d;
SetRedPixelComponent(q,RoundToQuantum((MagickRealType)
((l+(t >= threshold))*(MagickRealType) QuantumRange/levels.red)));
}
if (levels.green) {
t = (ssize_t) (QuantumScale*GetGreenPixelComponent(q)*
(levels.green*d+1));
l = t/d; t = t-l*d;
SetGreenPixelComponent(q,RoundToQuantum((MagickRealType)
((l+(t >= threshold))*(MagickRealType) QuantumRange/levels.green)));
}
if (levels.blue) {
t = (ssize_t) (QuantumScale*GetBluePixelComponent(q)*
(levels.blue*d+1));
l = t/d; t = t-l*d;
SetBluePixelComponent(q,RoundToQuantum((MagickRealType)
((l+(t >= threshold))*(MagickRealType) QuantumRange/levels.blue)));
}
if (levels.opacity) {
t = (ssize_t) ((1.0-QuantumScale*GetOpacityPixelComponent(q))*
(levels.opacity*d+1));
l = t/d; t = t-l*d;
SetOpacityPixelComponent(q,RoundToQuantum((MagickRealType)
((1.0-l-(t >= threshold))*(MagickRealType) QuantumRange/
levels.opacity)));
}
if (levels.index) {
t = (ssize_t) (QuantumScale*GetIndexPixelComponent(indexes+x)*
(levels.index*d+1));
l = t/d; t = t-l*d;
SetIndexPixelComponent(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(dynamic,4) 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);
SetIndexPixelComponent(indexes+x,index);
SetRGBOPixelComponents(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(dynamic,4) 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) GetRedPixelComponent(q) < min_threshold)
threshold.red=min_threshold;
else
if ((MagickRealType) GetRedPixelComponent(q) > max_threshold)
threshold.red=max_threshold;
else
threshold.red=(MagickRealType) (QuantumRange*
GetPseudoRandomValue(random_info[id]));
}
if ((channel & GreenChannel) != 0)
{
if ((MagickRealType) GetGreenPixelComponent(q) < min_threshold)
threshold.green=min_threshold;
else
if ((MagickRealType) GetGreenPixelComponent(q) > max_threshold)
threshold.green=max_threshold;
else
threshold.green=(MagickRealType) (QuantumRange*
GetPseudoRandomValue(random_info[id]));
}
if ((channel & BlueChannel) != 0)
{
if ((MagickRealType) GetBluePixelComponent(q) < min_threshold)
threshold.blue=min_threshold;
else
if ((MagickRealType) GetBluePixelComponent(q) > max_threshold)
threshold.blue=max_threshold;
else
threshold.blue=(MagickRealType) (QuantumRange*
GetPseudoRandomValue(random_info[id]));
}
if ((channel & OpacityChannel) != 0)
{
if ((MagickRealType) GetOpacityPixelComponent(q) < min_threshold)
threshold.opacity=min_threshold;
else
if ((MagickRealType) GetOpacityPixelComponent(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) GetIndexPixelComponent(indexes+x) < min_threshold)
threshold.index=min_threshold;
else
if ((MagickRealType) GetIndexPixelComponent(indexes+x) > max_threshold)
threshold.index=max_threshold;
else
threshold.index=(MagickRealType) (QuantumRange*
GetPseudoRandomValue(random_info[id]));
}
if ((channel & RedChannel) != 0)
SetRedPixelComponent(q,(MagickRealType) GetRedPixelComponent(q) <=
threshold.red ? 0 : QuantumRange);
if ((channel & GreenChannel) != 0)
SetGreenPixelComponent(q,(MagickRealType) GetGreenPixelComponent(q) <=
threshold.green ? 0 : QuantumRange);
if ((channel & BlueChannel) != 0)
SetBluePixelComponent(q,(MagickRealType) GetBluePixelComponent(q) <=
threshold.blue ? 0 : QuantumRange);
if ((channel & OpacityChannel) != 0)
SetOpacityPixelComponent(q,(MagickRealType) GetOpacityPixelComponent(q)
<= threshold.opacity ? 0 : QuantumRange);
if (((channel & IndexChannel) != 0) &&
(image->colorspace == CMYKColorspace))
SetIndexPixelComponent(indexes+x,(MagickRealType)
GetIndexPixelComponent(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(dynamic,4) 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))
{
SetRedPixelComponent(q,QuantumRange);
SetGreenPixelComponent(q,QuantumRange);
SetBluePixelComponent(q,QuantumRange);
if (image->colorspace == CMYKColorspace)
SetIndexPixelComponent(indexes+x,QuantumRange);
}
}
else
{
if (((channel & RedChannel) != 0) &&
((MagickRealType) GetRedPixelComponent(q) > threshold.red))
SetRedPixelComponent(q,QuantumRange);
if (((channel & GreenChannel) != 0) &&
((MagickRealType) GetGreenPixelComponent(q) > threshold.green))
SetGreenPixelComponent(q,QuantumRange);
if (((channel & BlueChannel) != 0) &&
((MagickRealType) GetBluePixelComponent(q) > threshold.blue))
SetBluePixelComponent(q,QuantumRange);
if (((channel & OpacityChannel) != 0) &&
((MagickRealType) GetOpacityPixelComponent(q) > threshold.opacity))
SetOpacityPixelComponent(q,QuantumRange);
if (((channel & IndexChannel) != 0) &&
(image->colorspace == CMYKColorspace) &&
((MagickRealType) GetIndexPixelComponent(indexes+x)) >
threshold.index)
SetIndexPixelComponent(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);
}
|
invert.c | /* Copyright 2016. The Regents of the University of California.
* All rights reserved. Use of this source code is governed by
* a BSD-style license which can be found in the LICENSE file.
*
* Authors:
* 2016 Jon Tamir <jtamir@eecs.berkeley.edu>
*/
#include <stdlib.h>
#include <assert.h>
#include <complex.h>
#include <stdio.h>
#include "num/multind.h"
#include "num/init.h"
#include "misc/mmio.h"
#include "misc/misc.h"
#ifndef DIMS
#define DIMS 16
#endif
static const char usage_str[] = "<input> <output>";
static const char help_str[] = "Invert array (1 / <input>). The output is set to zero in case of divide by zero.\n";
int main_invert(int argc, char* argv[argc])
{
mini_cmdline(&argc, argv, 2, usage_str, help_str);
num_init();
long dims[DIMS];
complex float* idata = load_cfl(argv[1], DIMS, dims);
complex float* odata = create_cfl(argv[2], DIMS, dims);
#pragma omp parallel for
for (long i = 0; i < md_calc_size(DIMS, dims); i++)
odata[i] = idata[i] == 0 ? 0. : 1. / idata[i];
unmap_cfl(DIMS, dims, idata);
unmap_cfl(DIMS, dims, odata);
return 0;
}
|
GB_binop__rminus_fc64.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__rminus_fc64)
// A.*B function (eWiseMult): GB (_AemultB)
// A.*B function (eWiseMult): GB (_AemultB_02__rminus_fc64)
// A.*B function (eWiseMult): GB (_AemultB_03__rminus_fc64)
// A.*B function (eWiseMult): GB (_AemultB_bitmap__rminus_fc64)
// A*D function (colscale): GB (_AxD__rminus_fc64)
// D*A function (rowscale): GB (_DxB__rminus_fc64)
// C+=B function (dense accum): GB (_Cdense_accumB__rminus_fc64)
// C+=b function (dense accum): GB (_Cdense_accumb__rminus_fc64)
// C+=A+B function (dense ewise3): GB (_Cdense_ewise3_accum__rminus_fc64)
// C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__rminus_fc64)
// C=scalar+B GB (_bind1st__rminus_fc64)
// C=scalar+B' GB (_bind1st_tran__rminus_fc64)
// C=A+scalar GB (_bind2nd__rminus_fc64)
// C=A'+scalar GB (_bind2nd_tran__rminus_fc64)
// C type: GxB_FC64_t
// A type: GxB_FC64_t
// B,b type: GxB_FC64_t
// BinaryOp: cij = GB_FC64_minus (bij, aij)
#define GB_ATYPE \
GxB_FC64_t
#define GB_BTYPE \
GxB_FC64_t
#define GB_CTYPE \
GxB_FC64_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) \
GxB_FC64_t aij = Ax [pA]
// bij = Bx [pB]
#define GB_GETB(bij,Bx,pB) \
GxB_FC64_t bij = Bx [pB]
// declare scalar of the same type as C
#define GB_CTYPE_SCALAR(t) \
GxB_FC64_t 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 = GB_FC64_minus (y, x) ;
// 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_RMINUS || GxB_NO_FC64 || GxB_NO_RMINUS_FC64)
//------------------------------------------------------------------------------
// 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__rminus_fc64)
(
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__rminus_fc64)
(
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__rminus_fc64)
(
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__rminus_fc64)
(
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 GxB_FC64_t
GxB_FC64_t bwork = (*((GxB_FC64_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__rminus_fc64)
(
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
GxB_FC64_t *restrict Cx = (GxB_FC64_t *) 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__rminus_fc64)
(
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
GxB_FC64_t *restrict Cx = (GxB_FC64_t *) 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__rminus_fc64)
(
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__rminus_fc64)
(
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__rminus_fc64)
(
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__rminus_fc64)
(
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__rminus_fc64)
(
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__rminus_fc64)
(
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
GxB_FC64_t *Cx = (GxB_FC64_t *) Cx_output ;
GxB_FC64_t x = (*((GxB_FC64_t *) x_input)) ;
GxB_FC64_t *Bx = (GxB_FC64_t *) 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 ;
GxB_FC64_t bij = Bx [p] ;
Cx [p] = GB_FC64_minus (bij, x) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd
//------------------------------------------------------------------------------
GrB_Info GB (_bind2nd__rminus_fc64)
(
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 ;
GxB_FC64_t *Cx = (GxB_FC64_t *) Cx_output ;
GxB_FC64_t *Ax = (GxB_FC64_t *) Ax_input ;
GxB_FC64_t y = (*((GxB_FC64_t *) y_input)) ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!GBB (Ab, p)) continue ;
GxB_FC64_t aij = Ax [p] ;
Cx [p] = GB_FC64_minus (y, aij) ;
}
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_FC64_t aij = Ax [pA] ; \
Cx [pC] = GB_FC64_minus (aij, x) ; \
}
GrB_Info GB (_bind1st_tran__rminus_fc64)
(
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_FC64_t
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
GxB_FC64_t x = (*((const GxB_FC64_t *) x_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
#undef GB_ATYPE
#define GB_ATYPE \
GxB_FC64_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_FC64_t aij = Ax [pA] ; \
Cx [pC] = GB_FC64_minus (y, aij) ; \
}
GrB_Info GB (_bind2nd_tran__rminus_fc64)
(
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_FC64_t y = (*((const GxB_FC64_t *) y_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
targc-generic.c | #include <omp.h>
#include <stdio.h>
int main (){
#define N 1024
double x_d[N];
for (size_t i = 0; i < N; ++i)
x_d[i] = -1;
printf("x_d = %p\n",x_d);
#pragma omp target
{
int lower = 0;
printf("hello\n");
x_d[1] = 1;
}
printf("x_d[1] = %f\n", x_d[1]);
if (x_d[1] != 1.0) {printf("Failed\n"); return 1;}
return 0;
}
|
calculate_octree_signed_distance_to_3d_skin_process.h | // | / |
// ' / __| _` | __| _ \ __|
// . \ | ( | | ( |\__ `
// _|\_\_| \__,_|\__|\___/ ____/
// Multi-Physics
//
// License: BSD License
// Kratos default license: kratos/license.txt
//
// Main authors: Pooyan Dadvand
//
#if !defined(KRATOS_CALCULATE_DISTANCE_PROCESS_H_INCLUDED )
#define KRATOS_CALCULATE_DISTANCE_PROCESS_H_INCLUDED
// System includes
#include <string>
#include <iostream>
// External includes
// Project includes
#include "includes/define.h"
#include "processes/process.h"
#include "includes/model_part.h"
#include "spatial_containers/octree_binary.h"
#include "utilities/spatial_containers_configure.h"
#include "utilities/timer.h"
#include "utilities/math_utils.h"
#include "utilities/geometry_utilities.h"
#include "utilities/parallel_utilities.h"
#include "utilities/variable_utils.h"
namespace Kratos
{
class DistanceSpatialContainersConfigure
{
public:
class CellNodeData
{
double mDistance;
double mCoordinates[3];
std::size_t mId;
public:
double& Distance(){return mDistance;}
double& X() {return mCoordinates[0];}
double& Y() {return mCoordinates[1];}
double& Z() {return mCoordinates[2];}
double& operator[](int i) {return mCoordinates[i];}
std::size_t& Id(){return mId;}
};
///@name Type Definitions
///@{
enum { Dimension = 3,
DIMENSION = 3,
MAX_LEVEL = 12,
MIN_LEVEL = 2
};
typedef Point PointType; /// always the point 3D
typedef std::vector<double>::iterator DistanceIteratorType;
typedef ModelPart::ElementsContainerType::ContainerType ContainerType;
typedef ContainerType::value_type PointerType;
typedef ContainerType::iterator IteratorType;
typedef ModelPart::ElementsContainerType::ContainerType ResultContainerType;
typedef ResultContainerType::value_type ResultPointerType;
typedef ResultContainerType::iterator ResultIteratorType;
typedef Element::Pointer pointer_type;
typedef std::vector<CellNodeData*> data_type;
typedef std::vector<PointerType>::iterator PointerTypeIterator;
/// Pointer definition of DistanceSpatialContainersConfigure
KRATOS_CLASS_POINTER_DEFINITION(DistanceSpatialContainersConfigure);
///@}
///@name Life Cycle
///@{
/// Default constructor.
DistanceSpatialContainersConfigure() {}
/// Destructor.
virtual ~DistanceSpatialContainersConfigure() {}
///@}
///@name Operators
///@{
///@}
///@name Operations
///@{
static data_type* AllocateData() {
return new data_type(27, NULL);
}
static void CopyData(data_type* source, data_type* destination) {
destination = source;
}
static void DeleteData(data_type* data) {
delete data;
}
static inline void CalculateBoundingBox(const PointerType& rObject, PointType& rLowPoint, PointType& rHighPoint)
{
rHighPoint = rObject->GetGeometry().GetPoint(0);
rLowPoint = rObject->GetGeometry().GetPoint(0);
for (unsigned int point = 0; point<rObject->GetGeometry().PointsNumber(); point++)
{
for(std::size_t i = 0; i<3; i++)
{
rLowPoint[i] = (rLowPoint[i] > rObject->GetGeometry().GetPoint(point)[i] ) ? rObject->GetGeometry().GetPoint(point)[i] : rLowPoint[i];
rHighPoint[i] = (rHighPoint[i] < rObject->GetGeometry().GetPoint(point)[i] ) ? rObject->GetGeometry().GetPoint(point)[i] : rHighPoint[i];
}
}
}
static inline void GetBoundingBox(const PointerType rObject, double* rLowPoint, double* rHighPoint)
{
for(std::size_t i = 0; i<3; i++)
{
rLowPoint[i] = rObject->GetGeometry().GetPoint(0)[i];
rHighPoint[i] = rObject->GetGeometry().GetPoint(0)[i];
}
for (unsigned int point = 0; point<rObject->GetGeometry().PointsNumber(); point++)
{
for(std::size_t i = 0; i<3; i++)
{
rLowPoint[i] = (rLowPoint[i] > rObject->GetGeometry().GetPoint(point)[i] ) ? rObject->GetGeometry().GetPoint(point)[i] : rLowPoint[i];
rHighPoint[i] = (rHighPoint[i] < rObject->GetGeometry().GetPoint(point)[i] ) ? rObject->GetGeometry().GetPoint(point)[i] : rHighPoint[i];
}
}
}
static inline bool Intersection(const PointerType& rObj_1, const PointerType& rObj_2)
{
Element::GeometryType& geom_1 = rObj_1->GetGeometry();
Element::GeometryType& geom_2 = rObj_2->GetGeometry();
return geom_1.HasIntersection(geom_2);
}
static inline bool IntersectionBox(const PointerType& rObject, const PointType& rLowPoint, const PointType& rHighPoint)
{
return rObject->GetGeometry().HasIntersection(rLowPoint, rHighPoint);
}
static inline bool IsIntersected(const PointerType& rObject, const double& tolerance, const double rLowPoint[], const double rHighPoint[])
{
Kratos::Element::GeometryType& geom_1 = rObject->GetGeometry();
Kratos::Point rLowPointTolerance;
Kratos::Point rHighPointTolerance;
for(std::size_t i = 0; i<3; i++)
{
rLowPointTolerance[i] = rLowPoint[i] * 1+tolerance;
rHighPointTolerance[i] = rHighPoint[i] * 1+tolerance;
}
return geom_1.HasIntersection(rLowPointTolerance,rHighPointTolerance);
}
///@}
///@name Access
///@{
///@}
///@name Inquiry
///@{
///@}
///@name Input and output
///@{
/// Turn back information as a string.
virtual std::string Info() const
{
return " Spatial Containers Configure";
}
/// Print information about this object.
virtual void PrintInfo(std::ostream& rOStream) const {}
/// Print object's data.
virtual void PrintData(std::ostream& rOStream) const {}
///@}
protected:
private:
/// Assignment operator.
DistanceSpatialContainersConfigure& operator=(DistanceSpatialContainersConfigure const& rOther);
/// Copy constructor.
DistanceSpatialContainersConfigure(DistanceSpatialContainersConfigure const& rOther);
}; // Class DistanceSpatialContainersConfigure
///@name Kratos Globals
///@{
///@}
///@name Type Definitions
///@{
///@}
///@name Enum's
///@{
///@}
///@name Functions
///@{
///@}
///@name Kratos Classes
///@{
/// Short class definition.
/** Detail class definition.
*/
class CalculateSignedDistanceTo3DSkinProcess
: public Process
{
public:
///@name Type Definitions
///@{
/// Pointer definition of CalculateSignedDistanceTo3DSkinProcess
KRATOS_CLASS_POINTER_DEFINITION(CalculateSignedDistanceTo3DSkinProcess);
typedef DistanceSpatialContainersConfigure ConfigurationType;
typedef OctreeBinaryCell<ConfigurationType> CellType;
typedef OctreeBinary<CellType> OctreeType;
///@}
///@name Life Cycle
///@{
/// Constructor.
CalculateSignedDistanceTo3DSkinProcess(ModelPart& rThisModelPart)
: mrSkinModelPart(rThisModelPart), mrBodyModelPart(rThisModelPart)
{
}
/// Destructor.
virtual ~CalculateSignedDistanceTo3DSkinProcess()
{
}
///@}
///@name Operators
///@{
void operator()()
{
Execute();
}
///@}
///@name Operations
///@{
virtual void Execute()
{
KRATOS_TRY
//std::cout << "Generating the Octree..." << std::endl;
GenerateOctree();
//std::cout << "Generating the Octree finished" << std::endl;
GenerateCellNodalData();
CalculateDistance();
CalculateDistance2();
std::ofstream mesh_file1("octree1.post.msh");
std::ofstream res_file("octree1.post.res");
Timer::Start("Writing Gid conform Mesh");
PrintGiDMesh(mesh_file1);
PrintGiDResults(res_file);
// mOctree.PrintGiDMeshNew(mesh_file1);
Timer::Stop("Writing Gid conform Mesh");
KRATOS_WATCH(mrBodyModelPart);
KRATOS_CATCH("");
}
void GenerateOctree()
{
Timer::Start("Generating Octree");
for(ModelPart::NodeIterator i_node = mrSkinModelPart.NodesBegin() ; i_node != mrSkinModelPart.NodesEnd() ; i_node++)
{
double temp_point[3];
const Node<3>& r_node = *i_node;
temp_point[0] = r_node[0];
temp_point[1] = r_node[1];
temp_point[2] = r_node[2];
mOctree.Insert(temp_point);
}
mOctree.Constrain2To1();
for(ModelPart::ElementIterator i_element = mrSkinModelPart.ElementsBegin() ; i_element != mrSkinModelPart.ElementsEnd() ; i_element++)
{
mOctree.Insert(*(i_element).base());
}
Timer::Stop("Generating Octree");
// octree.Insert(*(mrSkinModelPart.ElementsBegin().base()));
KRATOS_WATCH(mOctree);
}
void GenerateCellNodalData()
{
Timer::Start("Generating Cell Nodal Data");
std::vector<OctreeType::cell_type*> all_leaves;
mOctree.GetAllLeavesVector(all_leaves);
IndexPartition<std::size_t>(all_leaves.size()).for_each([&](std::size_t Index){
*(all_leaves[Index]->pGetDataPointer()) = ConfigurationType::AllocateData();
});
std::size_t last_id = mrBodyModelPart.NumberOfNodes() + 1;
for (std::size_t i = 0; i < all_leaves.size(); i++)
{
CellType* cell = all_leaves[i];
GenerateCellNode(cell,last_id);
}
Timer::Stop("Generating Cell Nodal Data");
}
void GenerateCellNode(CellType* pCell, std::size_t& LastId)
{
for (int i_pos=0; i_pos < 8; i_pos++) // position 8 is for center
{
ConfigurationType::CellNodeData* p_node = (*(pCell->pGetData()))[i_pos];
if(p_node == 0)
{
CellType::key_type keys[3];
pCell->GetKey(i_pos,keys);
double new_point[3];
(*(pCell->pGetData()))[i_pos] = new ConfigurationType::CellNodeData;
(*(pCell->pGetData()))[i_pos]->Id() = LastId++;
(*(pCell->pGetData()))[i_pos]->X() = pCell->GetCoordinate(keys[0]);
(*(pCell->pGetData()))[i_pos]->Y() = pCell->GetCoordinate(keys[1]);
(*(pCell->pGetData()))[i_pos]->Z() = pCell->GetCoordinate(keys[2]);
mOctreeNodes.push_back((*(pCell->pGetData()))[i_pos]);
SetNodeInNeighbours(pCell,i_pos,(*(pCell->pGetData()))[i_pos]);
}
}
}
// void GenerateCellNode(CellType* pCell, std::size_t& LastId)
// {
// for (int i_pos=0; i_pos < 8; i_pos++) // position 8 is for center
// {
// Node<3>* p_node = (*(pCell->pGetData()))[i_pos];
// if(p_node == 0)
// {
// CellType::key_type keys[3];
// pCell->GetKey(i_pos,keys);
//
// double new_point[3];
//
// new_point[0] = pCell->GetCoordinate(keys[0]);
// new_point[1] = pCell->GetCoordinate(keys[1]);
// new_point[2] = pCell->GetCoordinate(keys[2]);
//
//
// (*(pCell->pGetData()))[i_pos] = (mrBodyModelPart.CreateNewNode(++LastId, new_point[0], new_point[1], new_point[2])).get();
//
// SetNodeInNeighbours(pCell,i_pos,(*(pCell->pGetData()))[i_pos]);
// }
//
// }
// }
void SetNodeInNeighbours(CellType* pCell, int Position, ConfigurationType::CellNodeData* pNode)
{
CellType::key_type point_key[3];
pCell->GetKey(Position, point_key);
for (std::size_t i_direction = 0; i_direction < 8; i_direction++) {
CellType::key_type neighbour_key[3];
if (pCell->GetNeighbourKey(Position, i_direction, neighbour_key)) {
CellType* neighbour_cell = mOctree.pGetCell(neighbour_key);
if (!neighbour_cell || (neighbour_cell == pCell))
continue;
std::size_t position = neighbour_cell->GetLocalPosition(point_key);
if((*neighbour_cell->pGetData())[position])
{
//std::cout << "ERROR!! Bad Position calculated!!!!!!!!!!! position :" << position << std::endl;
continue;
}
(*neighbour_cell->pGetData())[position] = pNode;
}
}
}
void CalculateDistance()
{
Timer::Start("Calculate Distances");
ModelPart::NodesContainerType::ContainerType& nodes = mrBodyModelPart.NodesArray();
int nodes_size = nodes.size();
// first of all we reset the node distance to 1.00 which is the maximum distnace in our normalized space.
VariableUtils().SetVariable(DISTANCE, 1.00, nodes);
std::vector<CellType*> leaves;
mOctree.GetAllLeavesVector(leaves);
int leaves_size = leaves.size();
for(int i = 0 ; i < leaves_size ; i++)
CalculateNotEmptyLeavesDistance(leaves[i]);
IndexPartition<std::size_t>(nodes_size).for_each([&](std::size_t Index){
CalculateNodeDistance(*(nodes[Index]));
});
Timer::Stop("Calculate Distances");
}
void CalculateDistance2()
{
Timer::Start("Calculate Distances 2");
ModelPart::NodesContainerType::ContainerType& nodes = mrBodyModelPart.NodesArray();
int nodes_size = nodes.size();
// first of all we reste the node distance to 1.00 which is the maximum distnace in our normalized space.
VariableUtils().SetVariable(DISTANCE, 1.00, nodes);
std::vector<CellType*> leaves;
mOctree.GetAllLeavesVector(leaves);
int leaves_size = leaves.size();
for(int i = 0 ; i < leaves_size ; i++)
CalculateNotEmptyLeavesDistance(leaves[i]);
for(int i_direction = 0 ; i_direction < 1 ; i_direction++)
{
//#pragma omp parallel for firstprivate(nodes_size)
for(int i = 0 ; i < nodes_size ; i++)
{
if(nodes[i]->X() < 1.00 && nodes[i]->Y() < 1.00 && nodes[i]->Z() < 1.00)
// if((*nodes[i])[i_direction] == 0.00)
CalculateDistance(*(nodes[i]), i_direction);
}
}
Timer::Stop("Calculate Distances 2");
}
void CalculateDistance(Node<3>& rNode, int i_direction)
{
// double coords[3] = {rNode.X(), rNode.Y(), rNode.Z()};
// // KRATOS_WATCH_3(coords);
//
// //This function must color the positions in space defined by 'coords'.
// //coords is of dimension (3) normalized in (0,1)^3 space
//
// typedef Element::GeometryType triangle_type;
// typedef std::vector<std::pair<double, triangle_type*> > intersections_container_type;
//
// intersections_container_type intersections;
// std::vector<Node<3>*> nodes_array;
//
//
// const double epsilon = 1e-12;
//
// double distance = 1.0;
//
// // Creating the ray
// double ray[3] = {coords[0], coords[1], coords[2]};
// ray[i_direction] = 0; // starting from the lower extreme
//
// // KRATOS_WATCH_3(ray)
// GetIntersectionsAndNodes(ray, i_direction, intersections, nodes_array);
// // KRATOS_WATCH(nodes_array.size())
// for (int i_node = 0; i_node < nodes_array.size() ; i_node++)
// {
// double coord = nodes_array[i_node]->Coordinates()[i_direction];
// // KRATOS_WATCH(intersections.size());
//
// int ray_color= 1;
// std::vector<std::pair<double, Element::GeometryType*> >::iterator i_intersection = intersections.begin();
// while (i_intersection != intersections.end()) {
// double d = coord - i_intersection->first;
// if (d > epsilon) {
//
// ray_color = -ray_color;
// distance = d;
// } else if (d > -epsilon) {//interface
// distance = 0.00;
// break;
// } else {
// if(distance > -d)
// distance = -d;
// break;
// }
//
// i_intersection++;
// }
//
// distance *= ray_color;
//
// double& node_distance = nodes_array[i_node]->GetSolutionStepValue(DISTANCE);
// if(fabs(distance) < fabs(node_distance))
// node_distance = distance;
// else if (distance*node_distance < 0.00) // assigning the correct sign
// node_distance = -node_distance;
//
//
// }
}
void CalculateNotEmptyLeavesDistance(CellType* pCell)
{
typedef Element::GeometryType triangle_type;
typedef OctreeType::cell_type::object_container_type object_container_type;
object_container_type* objects = (pCell->pGetObjects());
// There are no intersection in empty cells
if (objects->empty())
return;
for (int i_pos=0; i_pos < 8; i_pos++) // position 8 is for center
{
double distance = 1.00; // maximum distance is 1.00
for(object_container_type::iterator i_object = objects->begin(); i_object != objects->end(); i_object++)
{
CellType::key_type keys[3];
pCell->GetKey(i_pos,keys);
double cell_point[3];
//cell_point[0] = pCell->GetCoordinate(keys[0]);
//cell_point[1] = pCell->GetCoordinate(keys[1]);
//cell_point[2] = pCell->GetCoordinate(keys[2]);
double d = GeometryUtils::PointDistanceToTriangle3D((*i_object)->GetGeometry()[0], (*i_object)->GetGeometry()[1], (*i_object)->GetGeometry()[2], Point(cell_point[0], cell_point[1], cell_point[2]));
if(d < distance)
distance = d;
}
double& node_distance = (*(pCell->pGetData()))[i_pos]->Distance();
if(distance < node_distance)
node_distance = distance;
}
}
void CalculateNodeDistance(Node<3>& rNode)
{
double coord[3] = {rNode.X(), rNode.Y(), rNode.Z()};
double distance = DistancePositionInSpace(coord);
double& node_distance = rNode.GetSolutionStepValue(DISTANCE);
const double epsilon = 1.00e-12;
if(fabs(node_distance) > fabs(distance))
node_distance = distance;
else if (distance*node_distance < 0.00) // assigning the correct sign
node_distance = -node_distance;
}
double DistancePositionInSpace(double* coords)
{
//This function must color the positions in space defined by 'coords'.
//coords is of dimension (3) normalized in (0,1)^3 space
typedef Element::GeometryType triangle_type;
typedef std::vector<std::pair<double, triangle_type*> > intersections_container_type;
intersections_container_type intersections;
const int dimension = 3;
const double epsilon = 1e-12;
double distances[3] = {1.0, 1.0, 1.0};
for (int i_direction = 0; i_direction < dimension; i_direction++)
{
// Creating the ray
double ray[3] = {coords[0], coords[1], coords[2]};
ray[i_direction] = 0; // starting from the lower extreme
GetIntersections(ray, i_direction, intersections);
// if(intersections.size() == 1)
// KRATOS_WATCH_3(ray)
// KRATOS_WATCH(intersections.size());
int ray_color= 1;
std::vector<std::pair<double, Element::GeometryType*> >::iterator i_intersection = intersections.begin();
while (i_intersection != intersections.end()) {
double d = coords[i_direction] - i_intersection->first;
if (d > epsilon) {
ray_color = -ray_color;
distances[i_direction] = d;
// if(distances[i_direction] > d) // I think this is redundunt. Pooyan.
// {
// if(ray_color > 0.00)
// distances[i_direction] = d;
// else
// distances[i_direction] = -d;
// }
} else if (d > -epsilon) {//interface
distances[i_direction] = 0.00;
break;
} else {
if(distances[i_direction] > -d)
distances[i_direction] = -d;
break;
}
i_intersection++;
}
distances[i_direction] *= ray_color;
}
// if(distances[0]*distances[1] < 0.00 || distances[2]*distances[1] < 0.00)
// KRATOS_WATCH_3(distances);
#ifdef _DEBUG
std::cout << "colors : " << colors[0] << ", " << colors[1] << ", " << colors[2] << std::endl;
#endif
double distance = (fabs(distances[0]) > fabs(distances[1])) ? distances[1] : distances[0];
distance = (fabs(distance) > fabs(distances[2])) ? distances[2] : distance;
return distance;
}
void GetIntersectionsAndNodes(double* ray, int direction, std::vector<std::pair<double,Element::GeometryType*> >& intersections, std::vector<Node<3>*>& rNodesArray)
{
// //This function passes the ray through the model and gives the hit point to all objects in its way
// //ray is of dimension (3) normalized in (0,1)^3 space
// // direction can be 0,1,2 which are x,y and z respectively
//
// const double epsilon = 1.00e-12;
//
// // first clearing the intersections points vector
// intersections.clear();
//
// OctreeType* octree = &mOctree;
//
// OctreeType::key_type ray_key[3] = {octree->Key(ray[0]), octree->Key(ray[1]), octree->Key(ray[2])}; //ASK_TOKEN
// OctreeType::key_type cell_key[3];
//
// // getting the entrance cell from lower extreme
// ray_key[direction] = 0;
// OctreeType::cell_type* cell = octree->pGetCell(ray_key);
//
// while (cell) {
// std::size_t position = cell->GetLocalPosition(ray_key); // Is this the local position!?!?!?!
// OctreeType::key_type node_key[3];
// cell->GetKey(position, node_key);
// if((node_key[0] == ray_key[0]) && (node_key[1] == ray_key[1]) && (node_key[2] == ray_key[2]))
// {
// if(cell->pGetData())
// {
// if(cell->pGetData()->size() > position)
// {
// Node<3>* p_node = (*cell->pGetData())[position];
// if(p_node)
// {
// //KRATOS_WATCH(p_node->Id())
// rNodesArray.push_back(p_node);
// }
// }
// else
// KRATOS_WATCH(cell->pGetData()->size())
// }
// }
//
//
// // std::cout << ".";
// GetCellIntersections(cell, ray, ray_key, direction, intersections);
//
// // Add the cell's middle node if existed
// // cell->GetKey(8, cell_key); // 8 is the central position
// // ray_key[direction]=cell_key[direction]; // positioning the ray in the middle of cell in its direction
//
// // position = cell->GetLocalPosition(ray_key);
// // if(position < 27) // principal nodes
// // {
// // if(cell->pGetData())
// // {
// // if(cell->pGetData()->size() > position)
// // {
// // Node<3>* p_node = (*cell->pGetData())[position];
// // if(p_node)
// // {
// // //KRATOS_WATCH(p_node->Id())
// // rNodesArray.push_back(p_node);
// // }
// // }
// // else
// // KRATOS_WATCH(cell->pGetData()->size())
// // }
// // }
// // else
// // {
// // KRATOS_WATCH(position);
// // KRATOS_WATCH(*cell);
// // }
//
//
// // go to the next cell
// if (cell->GetNeighbourKey(1 + direction * 2, cell_key)) {
// ray_key[direction] = cell_key[direction];
// cell = octree->pGetCell(ray_key);
// ray_key[direction] -= 1 ;//the key returned by GetNeighbourKey is inside the cell (minkey +1), to ensure that the corresponding
// //cell get in pGetCell is the right one.
// #ifdef _DEBUG
// Octree_Pooyan::key_type min_key[3];
// cell->GetMinKey(min_key[0],min_key[1],min_key[2]);
// Octree_Pooyan::key_type tmp;
// tmp= min_key[direction];
// assert(ray_key[direction]==tmp);
// #endif
// } else
// cell = NULL;
// }
//
//
//
// // KRATOS_WATCH(rNodesArray.size());
// // now eliminating the repeated objects
// if (!intersections.empty()) {
// //sort
// std::sort(intersections.begin(), intersections.end());
// // unique
// std::vector<std::pair<double, Element::GeometryType*> >::iterator i_begin = intersections.begin();
// std::vector<std::pair<double, Element::GeometryType*> >::iterator i_intersection = intersections.begin();
// while (++i_begin != intersections.end()) {
// // considering the very near points as the same points
// if (fabs(i_begin->first - i_intersection->first) > epsilon) // if the hit points are far enough they are not the same
// *(++i_intersection) = *i_begin;
// }
// intersections.resize((++i_intersection) - intersections.begin());
//
// }
}
void GetIntersections(double* ray, int direction, std::vector<std::pair<double,Element::GeometryType*> >& intersections)
{
// //This function passes the ray through the model and gives the hit point to all objects in its way
// //ray is of dimension (3) normalized in (0,1)^3 space
// // direction can be 0,1,2 which are x,y and z respectively
//
// const double epsilon = 1.00e-12;
//
// // first clearing the intersections points vector
// intersections.clear();
//
// OctreeType* octree = &mOctree;
//
// OctreeType::key_type ray_key[3] = {octree->Key(ray[0]), octree->Key(ray[1]), octree->Key(ray[2])};
// OctreeType::key_type cell_key[3];
//
// // getting the entrance cell from lower extreme
// OctreeType::cell_type* cell = octree->pGetCell(ray_key);
//
// while (cell) {
// // std::cout << ".";
// GetCellIntersections(cell, ray, ray_key, direction, intersections);
// // go to the next cell
// if (cell->GetNeighbourKey(1 + direction * 2, cell_key)) {
// ray_key[direction] = cell_key[direction];
// cell = octree->pGetCell(ray_key);
// ray_key[direction] -= 1 ;//the key returned by GetNeighbourKey is inside the cell (minkey +1), to ensure that the corresponding
// //cell get in pGetCell is the right one.
// #ifdef _DEBUG
// Octree_Pooyan::key_type min_key[3];
// cell->GetMinKey(min_key[0],min_key[1],min_key[2]);
// Octree_Pooyan::key_type tmp;
// tmp= min_key[direction];
// assert(ray_key[direction]==tmp);
// #endif
// } else
// cell = NULL;
// }
//
//
// // now eliminating the repeated objects
// if (!intersections.empty()) {
// //sort
// std::sort(intersections.begin(), intersections.end());
// // unique
// std::vector<std::pair<double, Element::GeometryType*> >::iterator i_begin = intersections.begin();
// std::vector<std::pair<double, Element::GeometryType*> >::iterator i_intersection = intersections.begin();
// while (++i_begin != intersections.end()) {
// // considering the very near points as the same points
// if (fabs(i_begin->first - i_intersection->first) > epsilon) // if the hit points are far enough they are not the same
// *(++i_intersection) = *i_begin;
// }
// intersections.resize((++i_intersection) - intersections.begin());
//
// }
}
int GetCellIntersections(OctreeType::cell_type* cell, double* ray,
OctreeType::key_type* ray_key, int direction,
std::vector<std::pair<double, Element::GeometryType*> >& intersections) {
// //This function passes the ray through the cell and gives the hit point to all objects in its way
// //ray is of dimension (3) normalized in (0,1)^3 space
// // direction can be 0,1,2 which are x,y and z respectively
//
// typedef Element::GeometryType triangle_type;
// typedef OctreeType::cell_type::object_container_type object_container_type;
//
// object_container_type* objects = (cell->pGetObjects());
//
// // There are no intersection in empty cells
// if (objects->empty())
// return 0;
//
// // std::cout << "X";
// // calculating the two extreme of the ray segment inside the cell
// double ray_point1[3] = {ray[0], ray[1], ray[2]};
// double ray_point2[3] = {ray[0], ray[1], ray[2]};
// ray_point1[direction] = cell->GetCoordinate(ray_key[direction]);
// ray_point2[direction] = ray_point1[direction] + cell->GetSize();
//
// for (object_container_type::iterator i_object = objects->begin(); i_object != objects->end(); i_object++) {
// double intersection[3]={0.00,0.00,0.00};
//
// int is_intersected = IntersectionTriangleSegment((*i_object)->GetGeometry(), ray_point1, ray_point2, intersection); // This intersection has to be optimized for axis aligned rays
//
// if (is_intersected == 1) // There is an intersection but not coplanar
// intersections.push_back(std::pair<double, Element::GeometryType*>(intersection[direction], &((*i_object)->GetGeometry())));
// //else if(is_intersected == 2) // coplanar case
// }
//
// return 0;
}
int IntersectionTriangleSegment(Element::GeometryType& rGeometry, double* RayPoint1, double* RayPoint2, double* IntersectionPoint)
{
// This is the adaption of the implemnetation provided in:
// http://www.softsurfer.com/Archive/algorithm_0105/algorithm_0105.htm#intersect_RayTriangle()
const double epsilon = 1.00e-12;
array_1d<double,3> u, v, n; // triangle vectors
array_1d<double,3> dir, w0, w; // ray vectors
double r, a, b; // params to calc ray-plane intersect
// get triangle edge vectors and plane normal
u = rGeometry[1] - rGeometry[0];
v = rGeometry[2] - rGeometry[0];
MathUtils<double>::CrossProduct(n, u, v); // cross product
if (norm_2(n) == 0) // triangle is degenerate
return -1; // do not deal with this case
for(int i = 0 ; i < 3 ; i++)
{
dir[i] = RayPoint2[i] - RayPoint1[i]; // ray direction vector
w0[i] = RayPoint1[i] - rGeometry[0][i];
}
a = -inner_prod(n,w0);
b = inner_prod(n,dir);
if (fabs(b) < epsilon) { // ray is parallel to triangle plane
if (a == 0) // ray lies in triangle plane
return 2;
else return 0; // ray disjoint from plane
}
// get intersect point of ray with triangle plane
r = a / b;
if (r < 0.0) // ray goes away from triangle
return 0; // => no intersect
// for a segment, also test if (r > 1.0) => no intersect
for(int i = 0 ; i < 3 ; i++)
IntersectionPoint[i] = RayPoint1[i] + r * dir[i]; // intersect point of ray and plane
// is I inside T?
double uu, uv, vv, wu, wv, D;
uu = inner_prod(u,u);
uv = inner_prod(u,v);
vv = inner_prod(v,v);
for(int i = 0 ; i < 3 ; i++)
w[i] = IntersectionPoint[i] - rGeometry[0][i];
wu = inner_prod(w,u);
wv = inner_prod(w,v);
D = uv * uv - uu * vv;
// get and test parametric coords
double s, t;
s = (uv * wv - vv * wu) / D;
if (s < 0.0 - epsilon || s > 1.0 + epsilon) // I is outside T
return 0;
t = (uv * wu - uu * wv) / D;
if (t < 0.0 - epsilon || (s + t) > 1.0 + epsilon) // I is outside T
return 0;
return 1; // I is in T
}
///@}
///@name Access
///@{
///@}
///@name Inquiry
///@{
///@}
///@name Input and output
///@{
/// Turn back information as a string.
virtual std::string Info() const
{
return "CalculateSignedDistanceTo3DSkinProcess";
}
/// Print information about this object.
virtual void PrintInfo(std::ostream& rOStream) const
{
rOStream << "CalculateSignedDistanceTo3DSkinProcess";
}
/// Print object's data.
virtual void PrintData(std::ostream& rOStream) const
{
}
void PrintGiDMesh(std::ostream & rOStream) const {
std::vector<CellType*> leaves;
mOctree.GetAllLeavesVector(leaves);
std::cout << "writing " << leaves.size() << " leaves" << std::endl;
rOStream << "MESH \"leaves\" dimension 3 ElemType Hexahedra Nnode 8" << std::endl;
rOStream << "# color 96 96 96" << std::endl;
rOStream << "Coordinates" << std::endl;
rOStream << "# node_number coordinate_x coordinate_y coordinate_z " << std::endl;
for(DistanceSpatialContainersConfigure::data_type::const_iterator i_node = mOctreeNodes.begin() ; i_node != mOctreeNodes.end() ; i_node++)
{
rOStream << (*i_node)->Id() << " " << (*i_node)->X() << " " << (*i_node)->Y() << " " << (*i_node)->Z() << std::endl;
}
std::cout << "Nodes written..." << std::endl;
rOStream << "end coordinates" << std::endl;
rOStream << "Elements" << std::endl;
rOStream << "# element n1 n2 n3 n4 n5 n6 n7 n8" << std::endl;
for (std::size_t i = 0; i < leaves.size(); i++)
{
if ((leaves[i]->pGetData()))
{
DistanceSpatialContainersConfigure::data_type& nodes = (*(leaves[i]->pGetData()));
// std::cout << "Leave - Level: " << nodes[0]->Id() << " " << nodes[1]->Id() << " " << nodes[2]->Id() << " etc... " << std::endl;
rOStream << i + 1;
for(int j = 0 ; j < 8 ; j++)
rOStream << " " << nodes[j]->Id();
rOStream << std::endl;
}
}
rOStream << "end elements" << std::endl;
}
void PrintGiDResults(std::ostream & rOStream) const {
std::vector<CellType*> leaves;
mOctree.GetAllLeavesVector(leaves);
rOStream << "GiD Post Results File 1.0" << std::endl << std::endl;
rOStream << "Result \"Distance\" \"Kratos\" 1 Scalar OnNodes" << std::endl;
rOStream << "Values" << std::endl;
for(ModelPart::NodeIterator i_node = mrBodyModelPart.NodesBegin() ; i_node != mrBodyModelPart.NodesEnd() ; i_node++)
{
rOStream << i_node->Id() << " " << i_node->GetSolutionStepValue(DISTANCE) << std::endl;
}
rOStream << "End Values" << std::endl;
}
///@}
///@name Friends
///@{
///@}
protected:
///@name Protected static Member Variables
///@{
///@}
///@name Protected member Variables
///@{
///@}
///@name Protected Operators
///@{
///@}
///@name Protected Operations
///@{
///@}
///@name Protected Access
///@{
///@}
///@name Protected Inquiry
///@{
///@}
///@name Protected LifeCycle
///@{
///@}
private:
///@name Static Member Variables
///@{
///@}
///@name Member Variables
///@{
ModelPart& mrSkinModelPart;
ModelPart& mrBodyModelPart;
DistanceSpatialContainersConfigure::data_type mOctreeNodes;
OctreeType mOctree;
///@}
///@name Private Operators
///@{
///@}
///@name Private Operations
///@{
///@}
///@name Private Access
///@{
///@}
///@name Private Inquiry
///@{
///@}
///@name Un accessible methods
///@{
/// Assignment operator.
CalculateSignedDistanceTo3DSkinProcess& operator=(CalculateSignedDistanceTo3DSkinProcess const& rOther);
/// Copy constructor.
//CalculateSignedDistanceTo3DSkinProcess(CalculateSignedDistanceTo3DSkinProcess const& rOther);
///@}
}; // Class CalculateSignedDistanceTo3DSkinProcess
///@}
///@name Type Definitions
///@{
///@}
///@name Input and output
///@{
/// input stream function
inline std::istream& operator >> (std::istream& rIStream,
CalculateSignedDistanceTo3DSkinProcess& rThis);
/// output stream function
inline std::ostream& operator << (std::ostream& rOStream,
const CalculateSignedDistanceTo3DSkinProcess& rThis)
{
rThis.PrintInfo(rOStream);
rOStream << std::endl;
rThis.PrintData(rOStream);
return rOStream;
}
///@}
} // namespace Kratos.
#endif // KRATOS_CALCULATE_DISTANCE_PROCESS_H_INCLUDED defined
|
esa.c | #include <stdio.h>
#include <math.h>
void esa_corr(double * source, double * target, size_t nmem, size_t nsrc, double * corr) {
// Mean value of target
double target_avg = 0.;
for (size_t j = 0; j < nmem; ++j) {
target_avg += target[j];
}
target_avg /= (double) nmem;
// Standard deviation of target
double target_term[nmem];
double target_std = 0.;
for (size_t j = 0; j < nmem; ++j) {
target_term[j] = target[j] - target_avg;
target_std += target_term[j] * target_term[j];
}
// The normalizations for std and cov cancel in the correlation
// coefficient, omit them
target_std = sqrt(target_std);
#pragma omp parallel for
for (size_t i = 0; i < nsrc; ++i) {
// Mean value of source
double source_avg = 0.;
for (size_t j = 0; j < nmem; ++j) {
source_avg += source[j * nsrc + i];
}
source_avg /= (double) nmem;
// Covariance and variance of source
double covariance = 0.;
double source_var = 0.;
for (size_t j = 0; j < nmem; ++j) {
double source_term = source[j * nsrc + i] - source_avg;
covariance += source_term * target_term[j];
source_var += source_term * source_term;
}
// Correlation coefficient
corr[i] = covariance / target_std / sqrt(source_var);
}
}
|
displacement_lagrangemultiplier_mixed_frictional_contact_criteria.h | // KRATOS ___| | | |
// \___ \ __| __| | | __| __| | | __| _` | |
// | | | | | ( | | | | ( | |
// _____/ \__|_| \__,_|\___|\__|\__,_|_| \__,_|_| MECHANICS
//
// License: BSD License
// license: StructuralMechanicsApplication/license.txt
//
// Main authors: Vicente Mataix Ferrandiz
//
#if !defined(KRATOS_DISPLACEMENT_LAGRANGE_MULTIPLIER_MIXED_FRICTIONAL_CONTACT_CRITERIA_H)
#define KRATOS_DISPLACEMENT_LAGRANGE_MULTIPLIER_MIXED_FRICTIONAL_CONTACT_CRITERIA_H
/* System includes */
/* External includes */
/* Project includes */
#include "utilities/table_stream_utility.h"
#include "utilities/color_utilities.h"
#include "solving_strategies/convergencecriterias/convergence_criteria.h"
#include "custom_utilities/active_set_utilities.h"
#include "custom_utilities/contact_utilities.h"
#include "utilities/constraint_utilities.h"
namespace Kratos
{
///@addtogroup ContactStructuralMechanicsApplication
///@{
///@name Kratos Globals
///@{
///@}
///@name Type Definitions
///@{
///@}
///@name Enum's
///@{
///@}
///@name Functions
///@{
///@name Kratos Classes
///@{
/**
* @class DisplacementLagrangeMultiplierMixedFrictionalContactCriteria
* @ingroup ContactStructuralMechanicsApplication
* @brief Convergence criteria for contact problems
* @details This class implements a convergence control based on nodal displacement and
* lagrange multiplier values. The error is evaluated separately for each of them, and
* relative and absolute tolerances for both must be specified.
* @author Vicente Mataix Ferrandiz
*/
template< class TSparseSpace,
class TDenseSpace >
class DisplacementLagrangeMultiplierMixedFrictionalContactCriteria
: public ConvergenceCriteria< TSparseSpace, TDenseSpace >
{
public:
///@name Type Definitions
///@{
/// Pointer definition of DisplacementLagrangeMultiplierMixedFrictionalContactCriteria
KRATOS_CLASS_POINTER_DEFINITION( DisplacementLagrangeMultiplierMixedFrictionalContactCriteria );
/// Local Flags
KRATOS_DEFINE_LOCAL_FLAG( ENSURE_CONTACT );
KRATOS_DEFINE_LOCAL_FLAG( PRINTING_OUTPUT );
KRATOS_DEFINE_LOCAL_FLAG( TABLE_IS_INITIALIZED );
KRATOS_DEFINE_LOCAL_FLAG( ROTATION_DOF_IS_CONSIDERED );
KRATOS_DEFINE_LOCAL_FLAG( PURE_SLIP );
KRATOS_DEFINE_LOCAL_FLAG( INITIAL_RESIDUAL_IS_SET );
/// The base class definition (and it subclasses)
typedef ConvergenceCriteria< TSparseSpace, TDenseSpace > BaseType;
typedef typename BaseType::TDataType TDataType;
typedef typename BaseType::DofsArrayType DofsArrayType;
typedef typename BaseType::TSystemMatrixType TSystemMatrixType;
typedef typename BaseType::TSystemVectorType TSystemVectorType;
/// The sparse space used
typedef TSparseSpace SparseSpaceType;
/// The r_table stream definition TODO: Replace by logger
typedef TableStreamUtility::Pointer TablePrinterPointerType;
/// The index type definition
typedef std::size_t IndexType;
/// The key type definition
typedef std::size_t KeyType;
/// The epsilon tolerance definition
static constexpr double Tolerance = std::numeric_limits<double>::epsilon();
///@}
///@name Life Cycle
///@{
/**
* @brief Default constructor.
* @param DispRatioTolerance Relative tolerance for displacement residual error
* @param DispAbsTolerance Absolute tolerance for displacement residual error
* @param RotRatioTolerance Relative tolerance for rotation residual error
* @param RotAbsTolerance Absolute tolerance for rotation residual error
* @param LMRatioTolerance Relative tolerance for lagrange multiplier residual error
* @param LMAbsTolerance Absolute tolerance for lagrange multiplier residual error
* @param NormalTangentRatio Ratio between the normal and tangent that will accepted as converged
* @param EnsureContact To check if the contact is lost
* @param pTable The pointer to the output r_table
* @param PrintingOutput If the output is going to be printed in a txt file
*/
explicit DisplacementLagrangeMultiplierMixedFrictionalContactCriteria(
const TDataType DispRatioTolerance,
const TDataType DispAbsTolerance,
const TDataType RotRatioTolerance,
const TDataType RotAbsTolerance,
const TDataType LMNormalRatioTolerance,
const TDataType LMNormalAbsTolerance,
const TDataType LMTangentStickRatioTolerance,
const TDataType LMTangentStickAbsTolerance,
const TDataType LMTangentSlipRatioTolerance,
const TDataType LMTangentSlipAbsTolerance,
const TDataType NormalTangentRatio,
const bool EnsureContact = false,
const bool PureSlip = false,
const bool PrintingOutput = false
)
: BaseType()
{
// Set local flags
mOptions.Set(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::ENSURE_CONTACT, EnsureContact);
mOptions.Set(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::PRINTING_OUTPUT, PrintingOutput);
mOptions.Set(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::TABLE_IS_INITIALIZED, false);
mOptions.Set(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::ROTATION_DOF_IS_CONSIDERED, false);
mOptions.Set(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::PURE_SLIP, PureSlip);
mOptions.Set(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::INITIAL_RESIDUAL_IS_SET, false);
// The displacement residual
mDispRatioTolerance = DispRatioTolerance;
mDispAbsTolerance = DispAbsTolerance;
// The rotation residual
mRotRatioTolerance = RotRatioTolerance;
mRotAbsTolerance = RotAbsTolerance;
// The normal contact residual
mLMNormalRatioTolerance = LMNormalRatioTolerance;
mLMNormalAbsTolerance = LMNormalAbsTolerance;
// The tangent contact residual
mLMTangentStickRatioTolerance = LMTangentStickRatioTolerance;
mLMTangentStickAbsTolerance = LMTangentStickAbsTolerance;
mLMTangentSlipRatioTolerance = LMTangentSlipRatioTolerance;
mLMTangentSlipAbsTolerance = LMTangentSlipAbsTolerance;
// We get the ratio between the normal and tangent that will accepted as converged
mNormalTangentRatio = NormalTangentRatio;
}
/**
* @brief Default constructor (parameters)
* @param ThisParameters The configuration parameters
*/
explicit DisplacementLagrangeMultiplierMixedFrictionalContactCriteria( Parameters ThisParameters = Parameters(R"({})"))
: BaseType()
{
// Validate and assign defaults
ThisParameters = this->ValidateAndAssignParameters(ThisParameters, this->GetDefaultParameters());
this->AssignSettings(ThisParameters);
}
//* Copy constructor.
DisplacementLagrangeMultiplierMixedFrictionalContactCriteria( DisplacementLagrangeMultiplierMixedFrictionalContactCriteria const& rOther )
:BaseType(rOther)
,mOptions(rOther.mOptions)
,mDispRatioTolerance(rOther.mDispRatioTolerance)
,mDispAbsTolerance(rOther.mDispAbsTolerance)
,mDispInitialResidualNorm(rOther.mDispInitialResidualNorm)
,mDispCurrentResidualNorm(rOther.mDispCurrentResidualNorm)
,mRotRatioTolerance(rOther.mRotRatioTolerance)
,mRotAbsTolerance(rOther.mRotAbsTolerance)
,mRotInitialResidualNorm(rOther.mRotInitialResidualNorm)
,mRotCurrentResidualNorm(rOther.mRotCurrentResidualNorm)
,mLMNormalRatioTolerance(rOther.mLMNormalRatioTolerance)
,mLMNormalAbsTolerance(rOther.mLMNormalAbsTolerance)
,mLMTangentStickRatioTolerance(rOther.mLMTangentStickRatioTolerance)
,mLMTangentStickAbsTolerance(rOther.mLMTangentStickAbsTolerance)
,mLMTangentSlipRatioTolerance(rOther.mLMTangentSlipRatioTolerance)
,mLMTangentSlipAbsTolerance(rOther.mLMTangentSlipAbsTolerance)
,mNormalTangentRatio(rOther.mNormalTangentRatio)
{
}
/// Destructor.
~DisplacementLagrangeMultiplierMixedFrictionalContactCriteria() override = default;
///@}
///@name Operators
///@{
/**
* @brief Compute relative and absolute error.
* @param rModelPart Reference to the ModelPart containing the contact problem.
* @param rDofSet Reference to the container of the problem's degrees of freedom (stored by the BuilderAndSolver)
* @param rA System matrix (unused)
* @param rDx Vector of results (variations on nodal variables)
* @param rb RHS vector (residual)
* @return true if convergence is achieved, false otherwise
*/
bool PostCriteria(
ModelPart& rModelPart,
DofsArrayType& rDofSet,
const TSystemMatrixType& rA,
const TSystemVectorType& rDx,
const TSystemVectorType& rb
) override
{
if (SparseSpaceType::Size(rb) != 0) { //if we are solving for something
// Getting process info
ProcessInfo& r_process_info = rModelPart.GetProcessInfo();
// Initialize
TDataType disp_residual_solution_norm = 0.0, rot_residual_solution_norm = 0.0,normal_lm_solution_norm = 0.0, normal_lm_increase_norm = 0.0, tangent_lm_stick_solution_norm = 0.0, tangent_lm_slip_solution_norm = 0.0, tangent_lm_stick_increase_norm = 0.0, tangent_lm_slip_increase_norm = 0.0;
IndexType disp_dof_num(0),rot_dof_num(0),lm_dof_num(0),lm_stick_dof_num(0),lm_slip_dof_num(0);
// The nodes array
auto& r_nodes_array = rModelPart.Nodes();
// First iterator
const auto it_dof_begin = rDofSet.begin();
// Auxiliar values
std::size_t dof_id = 0;
TDataType residual_dof_value = 0.0, dof_value = 0.0, dof_incr = 0.0;
// The number of active dofs
const std::size_t number_active_dofs = rb.size();
// Auxiliar displacement DoF check
const std::function<bool(const VariableData&)> check_without_rot =
[](const VariableData& rCurrVar) -> bool {return true;};
const std::function<bool(const VariableData&)> check_with_rot =
[](const VariableData& rCurrVar) -> bool {return ((rCurrVar == DISPLACEMENT_X) || (rCurrVar == DISPLACEMENT_Y) || (rCurrVar == DISPLACEMENT_Z));};
const auto* p_check_disp = (mOptions.Is(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::ROTATION_DOF_IS_CONSIDERED)) ? &check_with_rot : &check_without_rot;
// Loop over Dofs
#pragma omp parallel for firstprivate(dof_id, residual_dof_value, dof_value, dof_incr) reduction(+:disp_residual_solution_norm,rot_residual_solution_norm,normal_lm_solution_norm,normal_lm_increase_norm,disp_dof_num,rot_dof_num,lm_dof_num, lm_stick_dof_num, lm_slip_dof_num)
for (int i = 0; i < static_cast<int>(rDofSet.size()); i++) {
auto it_dof = it_dof_begin + i;
dof_id = it_dof->EquationId();
// Check dof id is solved
if (dof_id < number_active_dofs) {
if (mActiveDofs[dof_id] == 1) {
const auto& r_curr_var = it_dof->GetVariable();
if (r_curr_var == VECTOR_LAGRANGE_MULTIPLIER_X || r_curr_var == VECTOR_LAGRANGE_MULTIPLIER_Y || r_curr_var == VECTOR_LAGRANGE_MULTIPLIER_Z) {
// The normal of the node (TODO: how to solve this without accesing all the time to the database?)
const auto it_node = r_nodes_array.find(it_dof->Id());
dof_value = it_dof->GetSolutionStepValue(0);
dof_incr = rDx[dof_id];
const double mu = it_node->GetValue(FRICTION_COEFFICIENT);
if (mu < std::numeric_limits<double>::epsilon()) {
normal_lm_solution_norm += std::pow(dof_value, 2);
normal_lm_increase_norm += std::pow(dof_incr, 2);
} else {
const double normal = it_node->FastGetSolutionStepValue(NORMAL)[r_curr_var.GetComponentIndex()];
const TDataType normal_dof_value = dof_value * normal;
const TDataType normal_dof_incr = dof_incr * normal;
normal_lm_solution_norm += std::pow(normal_dof_value, 2);
normal_lm_increase_norm += std::pow(normal_dof_incr, 2);
if (it_node->Is(SLIP) || mOptions.Is(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::PURE_SLIP)) {
tangent_lm_slip_solution_norm += std::pow(dof_value - normal_dof_value, 2);
tangent_lm_slip_increase_norm += std::pow(dof_incr - normal_dof_incr, 2);
++lm_slip_dof_num;
} else {
tangent_lm_stick_solution_norm += std::pow(dof_value - normal_dof_value, 2);
tangent_lm_stick_increase_norm += std::pow(dof_incr - normal_dof_incr, 2);
++lm_stick_dof_num;
}
}
++lm_dof_num;
} else if ((*p_check_disp)(r_curr_var)) {
residual_dof_value = rb[dof_id];
disp_residual_solution_norm += std::pow(residual_dof_value, 2);
++disp_dof_num;
} else { // We will assume is rotation dof
KRATOS_DEBUG_ERROR_IF_NOT((r_curr_var == ROTATION_X) || (r_curr_var == ROTATION_Y) || (r_curr_var == ROTATION_Z)) << "Variable must be a ROTATION and it is: " << r_curr_var.Name() << std::endl;
residual_dof_value = rb[dof_id];
rot_residual_solution_norm += std::pow(residual_dof_value, 2);
++rot_dof_num;
}
}
}
}
if(normal_lm_increase_norm < Tolerance) normal_lm_increase_norm = 1.0;
if(tangent_lm_stick_increase_norm < Tolerance) tangent_lm_stick_increase_norm = 1.0;
if(tangent_lm_slip_increase_norm < Tolerance) tangent_lm_slip_increase_norm = 1.0;
KRATOS_ERROR_IF(mOptions.Is(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::ENSURE_CONTACT) && normal_lm_solution_norm < Tolerance) << "ERROR::CONTACT LOST::ARE YOU SURE YOU ARE SUPPOSED TO HAVE CONTACT?" << std::endl;
mDispCurrentResidualNorm = disp_residual_solution_norm;
mRotCurrentResidualNorm = rot_residual_solution_norm;
const TDataType normal_lm_ratio = std::sqrt(normal_lm_increase_norm/normal_lm_solution_norm);
const TDataType tangent_lm_slip_ratio = tangent_lm_slip_solution_norm > Tolerance ? std::sqrt(tangent_lm_slip_increase_norm/tangent_lm_slip_solution_norm) : 0.0;
const TDataType tangent_lm_stick_ratio = tangent_lm_stick_solution_norm > Tolerance ? std::sqrt(tangent_lm_stick_increase_norm/tangent_lm_stick_solution_norm) : 0.0;
const TDataType normal_lm_abs = std::sqrt(normal_lm_increase_norm)/static_cast<TDataType>(lm_dof_num);
const TDataType tangent_lm_stick_abs = lm_stick_dof_num > 0 ? std::sqrt(tangent_lm_stick_increase_norm)/ static_cast<TDataType>(lm_stick_dof_num) : 0.0;
const TDataType tangent_lm_slip_abs = lm_slip_dof_num > 0 ? std::sqrt(tangent_lm_slip_increase_norm)/ static_cast<TDataType>(lm_slip_dof_num) : 0.0;
const TDataType normal_tangent_stick_ratio = tangent_lm_stick_abs/normal_lm_abs;
const TDataType normal_tangent_slip_ratio = tangent_lm_slip_abs/normal_lm_abs;
TDataType residual_disp_ratio, residual_rot_ratio;
// We initialize the solution
if (mOptions.IsNot(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::INITIAL_RESIDUAL_IS_SET)) {
mDispInitialResidualNorm = (disp_residual_solution_norm < Tolerance) ? 1.0 : disp_residual_solution_norm;
residual_disp_ratio = 1.0;
if (mOptions.Is(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::ROTATION_DOF_IS_CONSIDERED)) {
mRotInitialResidualNorm = (rot_residual_solution_norm < Tolerance) ? 1.0 : rot_residual_solution_norm;
residual_rot_ratio = 1.0;
}
mOptions.Set(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::INITIAL_RESIDUAL_IS_SET, true);
}
// We calculate the ratio of the displacements
residual_disp_ratio = mDispCurrentResidualNorm/mDispInitialResidualNorm;
// We calculate the ratio of the rotations
residual_rot_ratio = mRotCurrentResidualNorm/mRotInitialResidualNorm;
// We calculate the absolute norms
TDataType residual_disp_abs = mDispCurrentResidualNorm/disp_dof_num;
TDataType residual_rot_abs = mRotCurrentResidualNorm/rot_dof_num;
// We print the results // TODO: Replace for the new log
if (rModelPart.GetCommunicator().MyPID() == 0 && this->GetEchoLevel() > 0) {
if (r_process_info.Has(TABLE_UTILITY)) {
std::cout.precision(4);
TablePrinterPointerType p_table = r_process_info[TABLE_UTILITY];
auto& r_table = p_table->GetTable();
if (mOptions.Is(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::ROTATION_DOF_IS_CONSIDERED)) {
if (mOptions.IsNot(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::PURE_SLIP)) {
r_table << residual_disp_ratio << mDispRatioTolerance << residual_disp_abs << mDispAbsTolerance << residual_rot_ratio << mRotRatioTolerance << residual_rot_abs << mRotAbsTolerance << normal_lm_ratio << mLMNormalRatioTolerance << normal_lm_abs << mLMNormalAbsTolerance << tangent_lm_stick_ratio << mLMTangentStickRatioTolerance << tangent_lm_stick_abs << mLMTangentSlipAbsTolerance << tangent_lm_slip_ratio << mLMTangentSlipRatioTolerance << tangent_lm_slip_abs << mLMTangentStickAbsTolerance;
} else {
r_table << residual_disp_ratio << mDispRatioTolerance << residual_disp_abs << mDispAbsTolerance << residual_rot_ratio << mRotRatioTolerance << residual_rot_abs << mRotAbsTolerance << normal_lm_ratio << mLMNormalRatioTolerance << normal_lm_abs << mLMNormalAbsTolerance << tangent_lm_slip_ratio << mLMTangentSlipRatioTolerance << tangent_lm_slip_abs << mLMTangentSlipAbsTolerance;
}
} else {
if (mOptions.IsNot(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::PURE_SLIP)) {
r_table << residual_disp_ratio << mDispRatioTolerance << residual_disp_abs << mDispAbsTolerance << normal_lm_ratio << mLMNormalRatioTolerance << normal_lm_abs << mLMNormalAbsTolerance << tangent_lm_stick_ratio << mLMTangentStickRatioTolerance << tangent_lm_stick_abs << mLMTangentSlipAbsTolerance << tangent_lm_slip_ratio << mLMTangentSlipRatioTolerance << tangent_lm_slip_abs << mLMTangentStickAbsTolerance;
} else {
r_table << residual_disp_ratio << mDispRatioTolerance << residual_disp_abs << mDispAbsTolerance << normal_lm_ratio << mLMNormalRatioTolerance << normal_lm_abs << mLMNormalAbsTolerance << tangent_lm_slip_ratio << mLMTangentSlipRatioTolerance << tangent_lm_slip_abs << mLMTangentSlipAbsTolerance;
}
}
} else {
std::cout.precision(4);
if (mOptions.IsNot(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::PRINTING_OUTPUT)) {
KRATOS_INFO("DisplacementLagrangeMultiplierMixedFrictionalContactCriteria") << BOLDFONT("MIXED CONVERGENCE CHECK") << "\tSTEP: " << r_process_info[STEP] << "\tNL ITERATION: " << r_process_info[NL_ITERATION_NUMBER] << std::endl << std::scientific;
KRATOS_INFO("DisplacementLagrangeMultiplierMixedFrictionalContactCriteria") << BOLDFONT("\tDISPLACEMENT: RATIO = ") << residual_disp_ratio << BOLDFONT(" EXP.RATIO = ") << mDispRatioTolerance << BOLDFONT(" ABS = ") << residual_disp_abs << BOLDFONT(" EXP.ABS = ") << mDispAbsTolerance << std::endl;
if (mOptions.Is(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::ROTATION_DOF_IS_CONSIDERED)) {
KRATOS_INFO("DisplacementLagrangeMultiplierMixedFrictionalContactCriteria") << BOLDFONT("\tROTATION: RATIO = ") << residual_rot_ratio << BOLDFONT(" EXP.RATIO = ") << mRotRatioTolerance << BOLDFONT(" ABS = ") << residual_rot_abs << BOLDFONT(" EXP.ABS = ") << mRotAbsTolerance << std::endl;
}
KRATOS_INFO("DisplacementLagrangeMultiplierMixedFrictionalContactCriteria") << BOLDFONT("\tNORMAL LAGRANGE MUL: RATIO = ") << normal_lm_ratio << BOLDFONT(" EXP.RATIO = ") << mLMNormalRatioTolerance << BOLDFONT(" ABS = ") << normal_lm_abs << BOLDFONT(" EXP.ABS = ") << mLMNormalAbsTolerance << std::endl;
KRATOS_INFO_IF("DisplacementLagrangeMultiplierMixedFrictionalContactCriteria", mOptions.IsNot(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::PURE_SLIP)) << BOLDFONT(" STICK LAGRANGE MUL:\tRATIO = ") << tangent_lm_stick_ratio << BOLDFONT(" EXP.RATIO = ") << mLMTangentStickRatioTolerance << BOLDFONT(" ABS = ") << tangent_lm_stick_abs << BOLDFONT(" EXP.ABS = ") << mLMTangentStickAbsTolerance << std::endl;
KRATOS_INFO("DisplacementLagrangeMultiplierMixedFrictionalContactCriteria") << BOLDFONT(" SLIP LAGRANGE MUL:\tRATIO = ") << tangent_lm_slip_ratio << BOLDFONT(" EXP.RATIO = ") << mLMTangentSlipRatioTolerance << BOLDFONT(" ABS = ") << tangent_lm_slip_abs << BOLDFONT(" EXP.ABS = ") << mLMTangentSlipAbsTolerance << std::endl;
} else {
KRATOS_INFO("DisplacementLagrangeMultiplierMixedFrictionalContactCriteria") << "MIXED CONVERGENCE CHECK" << "\tSTEP: " << r_process_info[STEP] << "\tNL ITERATION: " << r_process_info[NL_ITERATION_NUMBER] << std::endl << std::scientific;
KRATOS_INFO("DisplacementLagrangeMultiplierMixedFrictionalContactCriteria") << "\tDISPLACEMENT: RATIO = " << residual_disp_ratio << " EXP.RATIO = " << mDispRatioTolerance << " ABS = " << residual_disp_abs << " EXP.ABS = " << mDispAbsTolerance << std::endl;
if (mOptions.Is(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::ROTATION_DOF_IS_CONSIDERED)) {
KRATOS_INFO("DisplacementLagrangeMultiplierMixedFrictionalContactCriteria") << "\tROTATION: RATIO = " << residual_rot_ratio << " EXP.RATIO = " << mRotRatioTolerance << " ABS = " << residual_rot_abs << " EXP.ABS = " << mRotAbsTolerance << std::endl;
}
KRATOS_INFO("DisplacementLagrangeMultiplierMixedFrictionalContactCriteria") << "\tNORMAL LAGRANGE MUL: RATIO = " << normal_lm_ratio << " EXP.RATIO = " << mLMNormalRatioTolerance << " ABS = " << normal_lm_abs << " EXP.ABS = " << mLMNormalAbsTolerance << std::endl;
KRATOS_INFO_IF("DisplacementLagrangeMultiplierMixedFrictionalContactCriteria", mOptions.IsNot(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::PURE_SLIP)) << " STICK LAGRANGE MUL:\tRATIO = " << tangent_lm_stick_ratio << " EXP.RATIO = " << mLMTangentStickRatioTolerance << " ABS = " << tangent_lm_stick_abs << " EXP.ABS = " << mLMTangentStickAbsTolerance << std::endl;
KRATOS_INFO("DisplacementLagrangeMultiplierMixedFrictionalContactCriteria") << " SLIP LAGRANGE MUL:\tRATIO = " << tangent_lm_slip_ratio << " EXP.RATIO = " << mLMTangentSlipRatioTolerance << " ABS = " << tangent_lm_slip_abs << " EXP.ABS = " << mLMTangentSlipAbsTolerance << std::endl;
}
}
}
// NOTE: Here we don't include the tangent counter part
r_process_info[CONVERGENCE_RATIO] = (residual_disp_ratio > normal_lm_ratio) ? residual_disp_ratio : normal_lm_ratio;
r_process_info[RESIDUAL_NORM] = (normal_lm_abs > mLMNormalAbsTolerance) ? normal_lm_abs : mLMNormalAbsTolerance;
// We check if converged
const bool disp_converged = (residual_disp_ratio <= mDispRatioTolerance || residual_disp_abs <= mDispAbsTolerance);
const bool rot_converged = (mOptions.Is(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::ROTATION_DOF_IS_CONSIDERED)) ? (residual_rot_ratio <= mRotRatioTolerance || residual_rot_abs <= mRotAbsTolerance) : true;
const bool lm_converged = (mOptions.IsNot(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::ENSURE_CONTACT) && normal_lm_solution_norm < Tolerance) ? true : (normal_lm_ratio <= mLMNormalRatioTolerance || normal_lm_abs <= mLMNormalAbsTolerance) && (tangent_lm_stick_ratio <= mLMTangentStickRatioTolerance || tangent_lm_stick_abs <= mLMTangentStickAbsTolerance || normal_tangent_stick_ratio <= mNormalTangentRatio) && (tangent_lm_slip_ratio <= mLMTangentSlipRatioTolerance || tangent_lm_slip_abs <= mLMTangentSlipAbsTolerance || normal_tangent_slip_ratio <= mNormalTangentRatio);
if ( disp_converged && rot_converged && lm_converged ) {
if (rModelPart.GetCommunicator().MyPID() == 0 && this->GetEchoLevel() > 0) {
if (r_process_info.Has(TABLE_UTILITY)) {
TablePrinterPointerType p_table = r_process_info[TABLE_UTILITY];
auto& r_table = p_table->GetTable();
if (mOptions.IsNot(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::PRINTING_OUTPUT))
r_table << BOLDFONT(FGRN(" Achieved"));
else
r_table << "Achieved";
} else {
if (mOptions.IsNot(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::PRINTING_OUTPUT))
KRATOS_INFO("DisplacementLagrangeMultiplierMixedFrictionalContactCriteria") << BOLDFONT("\tConvergence") << " is " << BOLDFONT(FGRN("achieved")) << std::endl;
else
KRATOS_INFO("DisplacementLagrangeMultiplierMixedFrictionalContactCriteria") << "\tConvergence is achieved" << std::endl;
}
}
return true;
} else {
if (rModelPart.GetCommunicator().MyPID() == 0 && this->GetEchoLevel() > 0) {
if (r_process_info.Has(TABLE_UTILITY)) {
TablePrinterPointerType p_table = r_process_info[TABLE_UTILITY];
auto& r_table = p_table->GetTable();
if (mOptions.IsNot(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::PRINTING_OUTPUT))
r_table << BOLDFONT(FRED(" Not achieved"));
else
r_table << "Not achieved";
} else {
if (mOptions.IsNot(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::PRINTING_OUTPUT))
KRATOS_INFO("DisplacementLagrangeMultiplierMixedFrictionalContactCriteria") << BOLDFONT("\tConvergence") << " is " << BOLDFONT(FRED(" not achieved")) << std::endl;
else
KRATOS_INFO("DisplacementLagrangeMultiplierMixedFrictionalContactCriteria") << "\tConvergence is not achieved" << std::endl;
}
}
return false;
}
} else // In this case all the displacements are imposed!
return true;
}
/**
* @brief This function initialize the convergence criteria
* @param rModelPart Reference to the ModelPart containing the contact problem. (unused)
*/
void Initialize( ModelPart& rModelPart) override
{
// Initialize
BaseType::mConvergenceCriteriaIsInitialized = true;
// Check rotation dof
mOptions.Set(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::ROTATION_DOF_IS_CONSIDERED, ContactUtilities::CheckModelPartHasRotationDoF(rModelPart));
// Initialize header
ProcessInfo& r_process_info = rModelPart.GetProcessInfo();
if (r_process_info.Has(TABLE_UTILITY) && mOptions.IsNot(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::TABLE_IS_INITIALIZED)) {
TablePrinterPointerType p_table = r_process_info[TABLE_UTILITY];
auto& r_table = p_table->GetTable();
r_table.AddColumn("DP RATIO", 10);
r_table.AddColumn("EXP. RAT", 10);
r_table.AddColumn("ABS", 10);
r_table.AddColumn("EXP. ABS", 10);
if (mOptions.Is(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::ROTATION_DOF_IS_CONSIDERED)) {
r_table.AddColumn("RT RATIO", 10);
r_table.AddColumn("EXP. RAT", 10);
r_table.AddColumn("ABS", 10);
r_table.AddColumn("EXP. ABS", 10);
}
r_table.AddColumn("N.LM RATIO", 10);
r_table.AddColumn("EXP. RAT", 10);
r_table.AddColumn("ABS", 10);
r_table.AddColumn("EXP. ABS", 10);
if (mOptions.IsNot(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::PURE_SLIP)) {
r_table.AddColumn("STI. RATIO", 10);
r_table.AddColumn("EXP. RAT", 10);
r_table.AddColumn("ABS", 10);
r_table.AddColumn("EXP. ABS", 10);
}
r_table.AddColumn("SLIP RATIO", 10);
r_table.AddColumn("EXP. RAT", 10);
r_table.AddColumn("ABS", 10);
r_table.AddColumn("EXP. ABS", 10);
r_table.AddColumn("CONVERGENCE", 15);
mOptions.Set(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::TABLE_IS_INITIALIZED, true);
}
}
/**
* @brief This function initializes the solution step
* @param rModelPart Reference to the ModelPart containing the contact problem.
* @param rDofSet Reference to the container of the problem's degrees of freedom (stored by the BuilderAndSolver)
* @param rA System matrix (unused)
* @param rDx Vector of results (variations on nodal variables)
* @param rb RHS vector (residual)
*/
void InitializeSolutionStep(
ModelPart& rModelPart,
DofsArrayType& rDofSet,
const TSystemMatrixType& rA,
const TSystemVectorType& rDx,
const TSystemVectorType& rb
) override
{
// Initialize flags
mOptions.Set(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::INITIAL_RESIDUAL_IS_SET, false);
// Filling mActiveDofs when MPC exist
ConstraintUtilities::ComputeActiveDofs(rModelPart, mActiveDofs, rDofSet);
}
/**
* @brief This function finalizes the non-linear iteration
* @param rModelPart Reference to the ModelPart containing the problem.
* @param rDofSet Reference to the container of the problem's degrees of freedom (stored by the BuilderAndSolver)
* @param rA System matrix (unused)
* @param rDx Vector of results (variations on nodal variables)
* @param rb RHS vector (residual + reactions)
*/
void FinalizeNonLinearIteration(
ModelPart& rModelPart,
DofsArrayType& rDofSet,
const TSystemMatrixType& rA,
const TSystemVectorType& rDx,
const TSystemVectorType& rb
) override
{
// Calling base criteria
BaseType::FinalizeNonLinearIteration(rModelPart, rDofSet, rA, rDx, rb);
// The current process info
ProcessInfo& r_process_info = rModelPart.GetProcessInfo();
r_process_info.SetValue(ACTIVE_SET_COMPUTED, false);
}
/**
* @brief This method provides the defaults parameters to avoid conflicts between the different constructors
* @return The default parameters
*/
Parameters GetDefaultParameters() const override
{
Parameters default_parameters = Parameters(R"(
{
"name" : "displacement_lagrangemultiplier_mixed_frictional_contact_criteria",
"ensure_contact" : false,
"pure_slip" : false,
"print_convergence_criterion" : false,
"residual_relative_tolerance" : 1.0e-4,
"residual_absolute_tolerance" : 1.0e-9,
"rotation_residual_relative_tolerance" : 1.0e-4,
"rotation_residual_absolute_tolerance" : 1.0e-9,
"contact_displacement_relative_tolerance" : 1.0e-4,
"contact_displacement_absolute_tolerance" : 1.0e-9,
"frictional_stick_contact_displacement_relative_tolerance" : 1.0e-4,
"frictional_stick_contact_residual_relative_tolerance" : 1.0e-9,
"frictional_slip_contact_displacement_relative_tolerance" : 1.0e-4,
"frictional_slip_contact_residual_relative_tolerance" : 1.0e-9,
"ratio_normal_tangent_threshold" : 1.0e-4
})");
// 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 "displacement_lagrangemultiplier_mixed_frictional_contact_criteria";
}
///@}
///@name Operations
///@{
///@}
///@name Acces
///@{
///@}
///@name Inquiry
///@{
///@}
///@name Friends
///@{
protected:
///@name Protected static Member Variables
///@{
///@}
///@name Protected member Variables
///@{
///@}
///@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);
// The displacement residual
mDispRatioTolerance = ThisParameters["residual_relative_tolerance"].GetDouble();
mDispAbsTolerance = ThisParameters["residual_absolute_tolerance"].GetDouble();
// The rotation residual
mRotRatioTolerance = ThisParameters["rotation_residual_relative_tolerance"].GetDouble();
mRotAbsTolerance = ThisParameters["rotation_residual_absolute_tolerance"].GetDouble();
// The normal contact solution
mLMNormalRatioTolerance = ThisParameters["contact_displacement_relative_tolerance"].GetDouble();
mLMNormalAbsTolerance = ThisParameters["contact_displacement_absolute_tolerance"].GetDouble();
// The tangent contact solution
mLMTangentStickRatioTolerance = ThisParameters["frictional_stick_contact_displacement_relative_tolerance"].GetDouble();
mLMTangentStickAbsTolerance = ThisParameters["frictional_stick_contact_residual_relative_tolerance"].GetDouble();
mLMTangentSlipRatioTolerance = ThisParameters["frictional_slip_contact_displacement_relative_tolerance"].GetDouble();
mLMTangentSlipAbsTolerance = ThisParameters["frictional_slip_contact_residual_relative_tolerance"].GetDouble();
// We get the ratio between the normal and tangent that will accepted as converged
mNormalTangentRatio = ThisParameters["ratio_normal_tangent_threshold"].GetDouble();
// Set local flags
mOptions.Set(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::ENSURE_CONTACT, ThisParameters["ensure_contact"].GetBool());
mOptions.Set(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::PRINTING_OUTPUT, ThisParameters["print_convergence_criterion"].GetBool());
mOptions.Set(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::TABLE_IS_INITIALIZED, false);
mOptions.Set(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::ROTATION_DOF_IS_CONSIDERED, false);
mOptions.Set(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::PURE_SLIP, ThisParameters["pure_slip"].GetBool());
mOptions.Set(DisplacementLagrangeMultiplierMixedFrictionalContactCriteria::INITIAL_RESIDUAL_IS_SET, false);
}
///@}
///@name Protected Access
///@{
///@}
///@name Protected Inquiry
///@{
///@}
///@name Protected LifeCycle
///@{
///@}
private:
///@name Static Member Variables
///@{
///@}
///@name Member Variables
///@{
Flags mOptions; /// Local flags
TDataType mDispRatioTolerance; /// The ratio threshold for the norm of the displacement residual
TDataType mDispAbsTolerance; /// The absolute value threshold for the norm of the displacement residual
TDataType mDispInitialResidualNorm; /// The reference norm of the displacement residual
TDataType mDispCurrentResidualNorm; /// The current norm of the displacement residual
TDataType mRotRatioTolerance; /// The ratio threshold for the norm of the rotation residual
TDataType mRotAbsTolerance; /// The absolute value threshold for the norm of the rotation residual
TDataType mRotInitialResidualNorm; /// The reference norm of the rotation residual
TDataType mRotCurrentResidualNorm; /// The current norm of the rotation residual
TDataType mLMNormalRatioTolerance; /// The ratio threshold for the norm of the LM (normal)
TDataType mLMNormalAbsTolerance; /// The absolute value threshold for the norm of the LM (normal)
TDataType mLMTangentStickRatioTolerance; /// The ratio threshold for the norm of the LM (tangent-stick)
TDataType mLMTangentStickAbsTolerance; /// The absolute value threshold for the norm of the LM (tangent-stick)
TDataType mLMTangentSlipRatioTolerance; /// The ratio threshold for the norm of the LM (tangent-slip)
TDataType mLMTangentSlipAbsTolerance; /// The absolute value threshold for the norm of the LM (tangent-slip)
TDataType mNormalTangentRatio; /// The ratio to accept a non converged tangent component in case
std::vector<int> mActiveDofs; /// This vector contains the dofs that are active
///@}
///@name Private Operators
///@{
///@}
///@name Private Operations
///@{
///@}
///@name Private Access
///@{
///@}
///@}
///@name Serialization
///@{
///@name Private Inquiry
///@{
///@}
///@name Unaccessible methods
///@{
///@}
}; // Kratos DisplacementLagrangeMultiplierMixedFrictionalContactCriteria
///@name Local flags creation
///@{
/// Local Flags
template<class TSparseSpace, class TDenseSpace>
const Kratos::Flags DisplacementLagrangeMultiplierMixedFrictionalContactCriteria<TSparseSpace, TDenseSpace>::ENSURE_CONTACT(Kratos::Flags::Create(0));
template<class TSparseSpace, class TDenseSpace>
const Kratos::Flags DisplacementLagrangeMultiplierMixedFrictionalContactCriteria<TSparseSpace, TDenseSpace>::PRINTING_OUTPUT(Kratos::Flags::Create(1));
template<class TSparseSpace, class TDenseSpace>
const Kratos::Flags DisplacementLagrangeMultiplierMixedFrictionalContactCriteria<TSparseSpace, TDenseSpace>::TABLE_IS_INITIALIZED(Kratos::Flags::Create(2));
template<class TSparseSpace, class TDenseSpace>
const Kratos::Flags DisplacementLagrangeMultiplierMixedFrictionalContactCriteria<TSparseSpace, TDenseSpace>::ROTATION_DOF_IS_CONSIDERED(Kratos::Flags::Create(3));
template<class TSparseSpace, class TDenseSpace>
const Kratos::Flags DisplacementLagrangeMultiplierMixedFrictionalContactCriteria<TSparseSpace, TDenseSpace>::PURE_SLIP(Kratos::Flags::Create(4));
template<class TSparseSpace, class TDenseSpace>
const Kratos::Flags DisplacementLagrangeMultiplierMixedFrictionalContactCriteria<TSparseSpace, TDenseSpace>::INITIAL_RESIDUAL_IS_SET(Kratos::Flags::Create(5));
}
#endif /* KRATOS_DISPLACEMENT_LAGRANGE_MULTIPLIER_MIXED_FRICTIONAL_CONTACT_CRITERIA_H */
|
GB_binop__islt_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_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__islt_fp64
// A.*B function (eWiseMult): GB_AemultB__islt_fp64
// A*D function (colscale): GB_AxD__islt_fp64
// D*A function (rowscale): GB_DxB__islt_fp64
// C+=B function (dense accum): GB_Cdense_accumB__islt_fp64
// C+=b function (dense accum): GB_Cdense_accumb__islt_fp64
// C+=A+B function (dense ewise3): (none)
// C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__islt_fp64
// C=scalar+B GB_bind1st__islt_fp64
// C=scalar+B' GB_bind1st_tran__islt_fp64
// C=A+scalar GB_bind2nd__islt_fp64
// C=A'+scalar GB_bind2nd_tran__islt_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) ;
// 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_ISLT || GxB_NO_FP64 || GxB_NO_ISLT_FP64)
//------------------------------------------------------------------------------
// C += A+B, all 3 matrices dense
//------------------------------------------------------------------------------
#if 0
// The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV.
void (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__islt_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__islt_fp64
(
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__islt_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__islt_fp64
(
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
double *GB_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__islt_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 *GB_RESTRICT Cx = (double *) C->x ;
#include "GB_AxB_rowscale_meta.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseAdd: C = A+B or C<M> = A+B
//------------------------------------------------------------------------------
#undef GB_FREE_ALL
#define GB_FREE_ALL \
{ \
GB_ek_slice_free (&pstart_Mslice, &kfirst_Mslice, &klast_Mslice) ; \
GB_ek_slice_free (&pstart_Aslice, &kfirst_Aslice, &klast_Aslice) ; \
GB_ek_slice_free (&pstart_Bslice, &kfirst_Bslice, &klast_Bslice) ; \
}
GrB_Info GB_AaddB__islt_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 *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 C_ntasks,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t *pstart_Mslice = NULL, *kfirst_Mslice = NULL, *klast_Mslice = NULL ;
int64_t *pstart_Aslice = NULL, *kfirst_Aslice = NULL, *klast_Aslice = NULL ;
int64_t *pstart_Bslice = NULL, *kfirst_Bslice = NULL, *klast_Bslice = NULL ;
#include "GB_add_template.c"
GB_FREE_ALL ;
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C = A.*B or C<M> = A.*B
//------------------------------------------------------------------------------
GrB_Info GB_AemultB__islt_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 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 C_ntasks,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t *pstart_Mslice = NULL, *kfirst_Mslice = NULL, *klast_Mslice = NULL ;
int64_t *pstart_Aslice = NULL, *kfirst_Aslice = NULL, *klast_Aslice = NULL ;
int64_t *pstart_Bslice = NULL, *kfirst_Bslice = NULL, *klast_Bslice = NULL ;
#include "GB_emult_template.c"
GB_FREE_ALL ;
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st
//------------------------------------------------------------------------------
GrB_Info GB_bind1st__islt_fp64
(
GB_void *Cx_output, // Cx and Bx may be aliased
const GB_void *x_input,
const GB_void *Bx_input,
const int8_t *GB_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__islt_fp64
(
GB_void *Cx_output, // Cx and Ax may be aliased
const GB_void *Ax_input,
const GB_void *y_input,
const int8_t *GB_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__islt_fp64
(
GrB_Matrix C,
const GB_void *x_input,
const GrB_Matrix A,
int64_t *GB_RESTRICT *Workspaces,
const int64_t *GB_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__islt_fp64
(
GrB_Matrix C,
const GrB_Matrix A,
const GB_void *y_input,
int64_t *GB_RESTRICT *Workspaces,
const int64_t *GB_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
|
zeroslike_ref.c | /*
* 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) 2020, OPEN AI LAB
* Author: qtang@openailab.com
*/
#include "sys_port.h"
#include "module.h"
#include "tengine_errno.h"
#include "tengine_log.h"
#include "tengine_ir.h"
#include "../../cpu_node_ops.h"
#include "tengine_op.h"
#include <math.h>
int ref_zeroslike_fp32(struct ir_tensor* input_tensor, struct ir_tensor* output_tensor, int num_thread)
{
// dims size = 2 or 3
if (input_tensor->dim_num < 4)
{
float* input_data = input_tensor->data;
float* out_data = output_tensor->data;
int total_size = input_tensor->elem_num;
for (int i = 0; i < total_size; i++)
{
input_data[i] = 0;
}
return 0;
}
// dims size 3
else if (input_tensor->dim_num == 4)
{
int w = input_tensor->dims[3];
int h = output_tensor->dims[2];
int channels = input_tensor->dims[1];
int size = h * w;
int c_step = h * w;
float* input_data = input_tensor->data;
float* out_data = output_tensor->data;
#pragma omp parallel for num_threads(num_thread)
for (int q = 0; q < channels; q++)
{
float* src = input_data + c_step * q;
float* dst = out_data + c_step * q;
for (int i = 0; i < size; i++)
{
dst[i] = 0.f;
}
}
return 0;
}
return -1;
}
static int init_node(struct node_ops* node_ops, struct exec_node* exec_node, struct exec_graph* exec_graph)
{
// exec_node->inplace_map[0] = 0;
// exec_node->inplace_map[1] = 0;
// exec_node->inplace_map_num = 1;
return 0;
}
static int release_node(struct node_ops* node_ops, struct exec_node* exec_node, struct exec_graph* exec_graph)
{
// exec_node->inplace_map_num = 0;
return 0;
}
static int prerun(struct node_ops* node_ops, struct exec_node* exec_node, struct exec_graph* exec_graph)
{
return 0;
}
static int run(struct node_ops* node_ops, struct exec_node* exec_node, struct exec_graph* exec_graph)
{
struct ir_node* ir_node = exec_node->ir_node;
struct ir_graph* ir_graph = ir_node->graph;
struct ir_tensor* input_tensor;
struct ir_tensor* output_tensor;
int layout = ir_graph->graph_layout;
input_tensor = get_ir_graph_tensor(ir_graph, ir_node->input_tensors[0]);
output_tensor = get_ir_graph_tensor(ir_graph, ir_node->output_tensors[0]);
// inplace inference
// if(input_tensor->data != output_tensor->data)
// {
// TLOG_ERR("input and output are not the same mem\n");
// set_tengine_errno(EFAULT);
// return -1;
// }
int ret = ref_zeroslike_fp32(input_tensor, output_tensor, exec_graph->num_thread);
if (ret != 0)
return -1;
return 0;
}
static int score(struct node_ops* node_ops, struct exec_graph* exec_graph, struct ir_node* exec_node)
{
return OPS_SCORE_CANDO;
}
static struct node_ops hcl_node_ops = {.prerun = prerun,
.run = run,
.reshape = NULL,
.postrun = NULL,
.init_node = init_node,
.release_node = release_node,
.score = score};
static int reg_zeroslike_hcl_ops(void* arg)
{
return register_builtin_node_ops(OP_ZEROSLIKE, &hcl_node_ops);
}
static int unreg_zeroslike_hcl_ops(void* arg)
{
return unregister_builtin_node_ops(OP_ZEROSLIKE, &hcl_node_ops);
}
AUTO_REGISTER_OPS(reg_zeroslike_hcl_ops);
AUTO_UNREGISTER_OPS(unreg_zeroslike_hcl_ops);
|
target_data_messages.c | // RUN: %clang_cc1 -triple x86_64-apple-macos10.7.0 -verify -fopenmp -ferror-limit 100 -o - %s -Wuninitialized
// RUN: %clang_cc1 -triple x86_64-apple-macos10.7.0 -verify -fopenmp-simd -ferror-limit 100 -o - %s -Wuninitialized
void foo() { }
void xxx(int argc) {
int map; // expected-note {{initialize the variable 'map' to silence this warning}}
#pragma omp target data map(map) // expected-warning {{variable 'map' is uninitialized when used here}}
for (int i = 0; i < 10; ++i)
;
}
int main(int argc, char **argv) {
int a;
#pragma omp target data // expected-error {{expected at least one 'map' or 'use_device_ptr' clause for '#pragma omp target data'}}
{}
L1:
foo();
#pragma omp target data map(a) allocate(a) // expected-error {{unexpected OpenMP clause 'allocate' in directive '#pragma omp target data'}}
{
foo();
goto L1; // expected-error {{use of undeclared label 'L1'}}
}
goto L2; // expected-error {{use of undeclared label 'L2'}}
#pragma omp target data map(a)
L2:
foo();
#pragma omp target data map(a)(i) // expected-warning {{extra tokens at the end of '#pragma omp target data' are ignored}}
{
foo();
}
#pragma omp target unknown // expected-warning {{extra tokens at the end of '#pragma omp target' are ignored}}
{
foo();
}
return 0;
}
|
primitives.h | #pragma once
#include <cassert>
#include <vector>
#include <cstdint>
#include <omp.h>
#include "local_buffer.h"
#include "util/timer.h"
#include "util/log/log.h"
using namespace std;
#define CACHE_LINE_ENTRY (16)
#define LOCAL_BUDGET (8*1024*1024)
//#define FOR_LOOP_MEMSET
//#define FOR_LOOP_MEMCPY
template<typename T>
void MemSetOMP(T *arr, int val, size_t size) {
size_t tid = omp_get_thread_num();
size_t max_omp_threads = omp_get_num_threads();
size_t task_num = size;
size_t avg = (task_num + max_omp_threads - 1) / max_omp_threads;
auto it_beg = avg * tid;
auto it_end = min(avg * (tid + 1), task_num);
#ifndef FOR_LOOP_MEMSET
if (it_beg < it_end) {
memset(arr + it_beg, val, sizeof(T) * (it_end - it_beg));
}
#else
T bits = 0;
for (auto i = 0; i < sizeof(T); i++) {
bits |= static_cast<T>(val) << (8 * i);
}
for (auto i = it_beg; i < it_end; i++) {
arr[i] = bits;
}
#endif
#pragma omp barrier
}
template<typename T>
void MemCpyOMP(T *dst, T *src, size_t size) {
size_t tid = omp_get_thread_num();
size_t max_omp_threads = omp_get_num_threads();
size_t task_num = size;
size_t avg = (task_num + max_omp_threads - 1) / max_omp_threads;
auto it_beg = avg * tid;
auto it_end = min(avg * (tid + 1), task_num);
if (it_beg >= it_end) return;
#ifndef FOR_LOOP_MEMCPY
if (it_beg < it_end) {
memcpy(dst + it_beg, src + it_beg, sizeof(T) * (it_end - it_beg));
}
#else
for (auto i = it_beg; i < it_end; i++) {
dst[i] = src[i];
}
#endif
#pragma omp barrier
}
/*
* InclusivePrefixSumOMP: General Case Inclusive Prefix Sum
* histogram: is for cache-aware thread-local histogram purpose
* output: should be different from the variables captured in function object f
* size: is the original size for the flagged prefix sum
* f: requires it as the parameter, f(it) return the histogram value of that it
*/
template<typename H, typename T, typename F>
void InclusivePrefixSumOMP(vector<H> &histogram, T *output, size_t size, F f) {
int omp_num_threads = omp_get_num_threads();
#pragma omp single
{
histogram = vector<H>((omp_num_threads + 1) * CACHE_LINE_ENTRY, 0);
}
static thread_local int tid = omp_get_thread_num();
// 1st Pass: Histogram.
auto avg = size / omp_num_threads;
auto it_beg = avg * tid;
auto histogram_idx = (tid + 1) * CACHE_LINE_ENTRY;
histogram[histogram_idx] = 0;
auto it_end = tid == omp_num_threads - 1 ? size : avg * (tid + 1);
size_t prev = 0u;
for (auto it = it_beg; it < it_end; it++) {
auto value = f(it);
histogram[histogram_idx] += value;
prev += value;
output[it] = prev;
}
#pragma omp barrier
// 2nd Pass: single-prefix-sum & Add previous sum.
#pragma omp single
{
for (auto local_tid = 0; local_tid < omp_num_threads; local_tid++) {
auto local_histogram_idx = (local_tid + 1) * CACHE_LINE_ENTRY;
auto prev_histogram_idx = (local_tid) * CACHE_LINE_ENTRY;
histogram[local_histogram_idx] += histogram[prev_histogram_idx];
}
}
{
auto prev_sum = histogram[tid * CACHE_LINE_ENTRY];
for (auto it = it_beg; it < it_end; it++) {
output[it] += prev_sum;
}
#pragma omp barrier
}
}
/*
* FlagPrefixSumOMP: special case of InclusivePrefixSumOMP
*/
template<typename H, typename T, typename F>
void FlagPrefixSumOMP(vector<H> &histogram, T *output, size_t size, F f) {
InclusivePrefixSumOMP(histogram, output, size, [&f](size_t it) {
return f(it) ? 1 : 0;
});
}
template<typename T>
void InitIdentity(T *identity, size_t size) {
#pragma omp for
for (size_t i = 0; i < size; i++) {
identity[i] = i;
}
}
/*
* SelectNotFOMP: selection primitive
* !f(it) returns selected
*/
template<typename H, typename T, typename OFF, typename F>
void SelectNotFOMP(vector<H> &histogram, T *output, T *input,
OFF *relative_off, size_t size, F f) {
FlagPrefixSumOMP(histogram, relative_off, size, f);
#pragma omp for
for (size_t i = 0u; i < size; i++) {
if (!(f(i))) {
auto off = i - relative_off[i];
output[off] = input[i];
}
}
#pragma omp single
{
if (size >= 1) {
log_info("Selected: %zu", size - relative_off[size - 1]);
}
}
}
/*
* SelectNotFOMP: selection primitive
* !f(it) returns selected
*/
template<typename H, typename T, typename OFF, typename F, typename P>
void SelectNotFOMP(vector<H> &histogram, T *output, T *input,
OFF *relative_off, size_t size, F f, P p) {
FlagPrefixSumOMP(histogram, relative_off, size, f);
#pragma omp for
for (size_t i = 0u; i < size; i++) {
if (!(p(i))) {
auto off = i - relative_off[i];
output[off] = input[i];
}
}
#pragma omp single
{
if (size >= 1) {
log_info("Selected: %zu", size - relative_off[size - 1]);
}
}
}
template<typename OFF, typename F>
void Histogram(size_t size, OFF *&bucket_ptrs, int32_t num_buckets, F f, Timer *timer = nullptr) {
// Histogram.
auto local_buf = (uint8_t *) calloc(num_buckets, sizeof(uint8_t));
#pragma omp for
for (size_t i = 0u; i < size; i++) {
auto src = f(i);
local_buf[src]++;
if (local_buf[src] == 0xff) {
__sync_fetch_and_add(&bucket_ptrs[src], 0xff);
local_buf[src] = 0;
}
}
#pragma omp single
if (timer != nullptr)log_info("[%s]: Local Comp Time: %.9lfs", __FUNCTION__, timer->elapsed());
for (size_t i = 0; i < num_buckets; i++) {
if (local_buf[i] != 0) {
__sync_fetch_and_add(&bucket_ptrs[i], local_buf[i]);
}
}
#pragma omp barrier
free(local_buf);
}
template<typename OFF, typename F>
void HistogramAtomic(size_t size, OFF *&bucket_ptrs, int32_t num_buckets, F f) {
// Histogram.
#pragma omp for
for (size_t i = 0u; i < size; i++) {
auto src = f(i);
__sync_fetch_and_add(&bucket_ptrs[src], 1);
}
}
/*
* Require an output array,
* f: is the property for the bucket ID, given an index on the input array
* Inefficient when there are lots of contentions because of atomic operations
*/
template<typename H, typename T, typename OFF, typename F>
void BucketSort(vector<H> &histogram, T *&input, T *&output,
OFF *&cur_write_off, OFF *&bucket_ptrs,
size_t size, int32_t num_buckets, F f, Timer *timer = nullptr) {
// Populate.
#pragma omp single
{
bucket_ptrs = (OFF *) malloc(sizeof(OFF) * (num_buckets + 1));
cur_write_off = (OFF *) malloc(sizeof(OFF) * (num_buckets + 1));
cur_write_off[0] = 0;
}
MemSetOMP(bucket_ptrs, 0, num_buckets + 1);
Histogram(size, bucket_ptrs, num_buckets, f, timer);
// HistogramAtomic(size, bucket_ptrs, num_buckets, f);
#pragma omp single
if (timer != nullptr)log_info("[%s]: Histogram, Time: %.9lfs", __FUNCTION__, timer->elapsed());
InclusivePrefixSumOMP(histogram, cur_write_off + 1, num_buckets, [&bucket_ptrs](uint32_t it) {
return bucket_ptrs[it];
});
MemCpyOMP(bucket_ptrs, cur_write_off, num_buckets + 1);
#pragma omp single
{
if (timer != nullptr)log_info("[%s]: Before Scatter, Time: %.9lfs", __FUNCTION__, timer->elapsed());
}
// Scatter.
#pragma omp for
for (size_t i = 0u; i < size; i++) {
auto element = input[i];
auto bucket_id = f(i);
auto old_offset = __sync_fetch_and_add(&(cur_write_off[bucket_id]), 1);
output[old_offset] = element;
}
#pragma omp single
{
if (timer != nullptr)log_info("[%s]: Before Sort, Time: %.9lfs", __FUNCTION__, timer->elapsed());
}
#pragma omp barrier
}
template<typename H, typename T, typename OFF, typename F>
void BucketSortSmallBuckets(vector<H> &histogram, T *&input, T *&output,
OFF *&cur_write_off, OFF *&bucket_ptrs,
size_t size, int32_t num_buckets, F f, Timer *timer = nullptr) {
using BufT= LocalWriteBuffer<T, uint32_t>;
auto cap = max<int>(CACHE_LINE_ENTRY, LOCAL_BUDGET / num_buckets / sizeof(T));
auto bucket_write_buffers = (BufT *) malloc(num_buckets * sizeof(BufT));
auto bucket_buffers = (T *) malloc(cap * num_buckets * sizeof(T));
// Populate.
#pragma omp single
{
int max_omp_threads = omp_get_num_threads();
log_info("[%s]: Mem Size Buckets: %zu, Bucket#: %d",
__FUNCTION__,
cap * num_buckets * sizeof(T) * max_omp_threads, num_buckets);
bucket_ptrs = (uint32_t *) malloc(sizeof(OFF) * (num_buckets + 1));
cur_write_off = (uint32_t *) malloc(sizeof(OFF) * (num_buckets + 1));
cur_write_off[0] = 0;
}
MemSetOMP(bucket_ptrs, 0, num_buckets + 1);
Histogram(size, bucket_ptrs, num_buckets, f);
#pragma omp barrier
InclusivePrefixSumOMP(histogram, cur_write_off + 1, num_buckets, [&bucket_ptrs](uint32_t it) {
return bucket_ptrs[it];
});
MemCpyOMP(bucket_ptrs, cur_write_off, num_buckets + 1);
#pragma omp single
{
if (timer != nullptr)log_info("[%s]: Before Scatter, Time: %.9lfs", __FUNCTION__, timer->elapsed());
}
for (auto i = 0; i < num_buckets; i++) {
bucket_write_buffers[i] = BufT(bucket_buffers + cap * i, cap, output, &cur_write_off[i]);
}
#pragma omp barrier
// Scatter.
#pragma omp for
for (size_t i = 0u; i < size; i++) {
auto element = input[i];
auto bucket_id = f(i);
bucket_write_buffers[bucket_id].push(element);
}
for (auto i = 0; i < num_buckets; i++) {
bucket_write_buffers[i].submit_if_possible();
}
#pragma omp barrier
#pragma omp single
{
if (timer != nullptr)log_info("[%s]: Before Sort, Time: %.9lfs", __FUNCTION__, timer->elapsed());
}
free(bucket_buffers);
free(bucket_write_buffers);
#pragma omp barrier
} |
FeatureLPPooling.c | #ifndef TH_GENERIC_FILE
#define TH_GENERIC_FILE "generic/FeatureLPPooling.c"
#else
#ifndef FEATURE_LP_DEFS
#define FEATURE_LP_DEFS
#ifdef _MSC_VER
#define FEATURE_LP_SIZE_TYPE int64_t
#define FEATURE_LP_CAST_TYPE (int64_t)
#else
#define FEATURE_LP_SIZE_TYPE size_t
#define FEATURE_LP_CAST_TYPE
#endif
typedef struct {
size_t size[4];
size_t stride[4];
} FeatureLPPoolingSizes;
static inline size_t flpGetOffset(FeatureLPPoolingSizes* s,
FEATURE_LP_SIZE_TYPE batch,
FEATURE_LP_SIZE_TYPE feature,
FEATURE_LP_SIZE_TYPE opt1,
FEATURE_LP_SIZE_TYPE opt2) {
return s->stride[0] * batch +
s->stride[1] * feature +
s->stride[2] * opt1 +
s->stride[3] * opt2;
}
static inline size_t flpOutputSize(FEATURE_LP_SIZE_TYPE inputSize,
FEATURE_LP_SIZE_TYPE width,
FEATURE_LP_SIZE_TYPE stride) {
return ((inputSize - width) / stride) + 1;
}
#endif // FEATURE_LP_DEFS
FeatureLPPoolingSizes
THNN_(FeatureLPPooling_upcastCPU)(THTensor* t, bool batchMode) {
int dim = THTensor_(nDimension)(t);
// Upcast to [batch dim][feature dim][opt dim 1][opt dim 2]
FeatureLPPoolingSizes s;
for (int i = 0; i < 4; ++i) {
s.size[i] = 1;
s.stride[i] = 1;
}
if (dim == 1) {
THAssert(!batchMode);
// [feature dim]
s.size[1] = THTensor_(size)(t, 0);
s.stride[1] = THTensor_(stride)(t, 0);
} else if (dim == 2) {
if (batchMode) {
// [batch dim][feature dim]
for (int i = 0; i < 2; ++i) {
s.size[i] = THTensor_(size)(t, i);
s.stride[i] = THTensor_(stride)(t, i);
}
} else {
// [feature dim][opt dim 1]
s.size[1] = THTensor_(size)(t, 0);
s.stride[1] = THTensor_(stride)(t, 0);
s.size[2] = THTensor_(size)(t, 1);
s.stride[2] = THTensor_(stride)(t, 1);
}
} else if (dim == 3) {
if (batchMode) {
// [batch dim][feature dim][opt dim 1]
for (int i = 0; i < 3; ++i) {
s.size[i] = THTensor_(size)(t, i);
s.stride[i] = THTensor_(stride)(t, i);
}
} else {
// [feature dim][opt dim 1][opt dim 2]
for (int i = 1; i < 4; ++i) {
s.size[i] = THTensor_(size)(t, i - 1);
s.stride[i] = THTensor_(stride)(t, i - 1);
}
}
} else if (dim == 4) {
// [batch dim][feature dim][opt dim 1][opt dim 2]
THAssert(batchMode);
for (int i = 0; i < 4; ++i) {
s.size[i] = THTensor_(size)(t, i);
s.stride[i] = THTensor_(stride)(t, i);
}
}
return s;
}
void
THNN_(FeatureLPPooling_resizeForOutputCPU)(THTensor* toResize,
THTensor* input,
bool batchMode,
int width,
int stride) {
int inputDim = THTensor_(nDimension)(input);
THAssert(inputDim >= 1 && inputDim <= 4);
int64_t outSize =
flpOutputSize(THTensor_(size)(input, 0), width, stride);
if (batchMode) {
THAssert(inputDim > 1);
outSize =
flpOutputSize(THTensor_(size)(input, 1), width, stride);
} else {
THAssert(inputDim < 4);
}
if (inputDim == 1) {
THTensor_(resize1d)(toResize, outSize);
} else if (inputDim == 2) {
if (batchMode) {
THTensor_(resize2d)(toResize,
THTensor_(size)(input, 0),
outSize);
} else {
THTensor_(resize2d)(toResize,
outSize,
THTensor_(size)(input, 1));
}
} else if (inputDim == 3) {
if (batchMode) {
THTensor_(resize3d)(toResize,
THTensor_(size)(input, 0), outSize,
THTensor_(size)(input, 2));
} else {
THTensor_(resize3d)(toResize,
outSize, THTensor_(size)(input, 1),
THTensor_(size)(input, 2));
}
} else if (inputDim == 4) {
THTensor_(resize4d)(toResize,
THTensor_(size)(input, 0),
outSize,
THTensor_(size)(input, 2),
THTensor_(size)(input, 3));
}
}
// Makes `toResize` the same size/dimensionality as `src`
void
THNN_(FeatureLPPooling_resizeCPU)(THTensor* toResize,
THTensor* src) {
int inputDim = THTensor_(nDimension)(src);
THAssert(inputDim >= 1 && inputDim <= 4);
if (inputDim == 1) {
THTensor_(resize1d)(toResize,
THTensor_(size)(src, 0));
} else if (inputDim == 2) {
THTensor_(resize2d)(
toResize,
THTensor_(size)(src, 0),
THTensor_(size)(src, 1));
} else if (inputDim == 3) {
THTensor_(resize3d)(
toResize,
THTensor_(size)(src, 0),
THTensor_(size)(src, 1),
THTensor_(size)(src, 2));
} else if (inputDim == 4) {
THTensor_(resize4d)(
toResize,
THTensor_(size)(src, 0),
THTensor_(size)(src, 1),
THTensor_(size)(src, 2),
THTensor_(size)(src, 3));
}
}
void
THNN_(FeatureLPPooling_updateOutput)(
THNNState *state,
THTensor *input,
THTensor *output,
accreal power,
int width,
int stride,
bool batchMode) {
int inputDim = THTensor_(nDimension)(input);
if (batchMode) {
THArgCheck(inputDim >= 2 && inputDim <= 4, 2,
"input must be 2-4 dimensions for batch mode");
} else {
THArgCheck(inputDim >= 1 && inputDim <= 3, 2,
"input must be 1-3 dimensions for non-batch mode");
}
FeatureLPPoolingSizes inputDesc =
THNN_(FeatureLPPooling_upcastCPU)(input, batchMode);
// Make sure the feature dimension is properly sized
THArgCheck(inputDesc.size[1] >= width, 3,
"input: feature dimension must be >= width");
// Make sure that width and stride are within range
THArgCheck(width >= 2 && width <= 16, 5,
"width must be between 2 - 16");
THArgCheck(stride >= 1 && stride <= 4, 6,
"stride must be between 1 - 4");
// Resize output
THNN_(FeatureLPPooling_resizeForOutputCPU)(
output, input, batchMode, width, stride);
FeatureLPPoolingSizes outputDesc =
THNN_(FeatureLPPooling_upcastCPU)(output, batchMode);
real* inputP = THTensor_(data)(input);
real* outputP = THTensor_(data)(output);
FEATURE_LP_SIZE_TYPE batch, opt1, opt2, outputFeature, i;
#pragma omp parallel for
for (batch = 0; batch < FEATURE_LP_CAST_TYPE inputDesc.size[0]; ++batch) {
for (opt1 = 0; opt1 < FEATURE_LP_CAST_TYPE inputDesc.size[2]; ++opt1) {
for (opt2 = 0; opt2 < FEATURE_LP_CAST_TYPE inputDesc.size[3]; ++opt2) {
for (outputFeature = 0;
outputFeature < FEATURE_LP_CAST_TYPE outputDesc.size[1]; ++outputFeature) {
accreal v = (accreal) 0;
for (i = 0; i < width; ++i) {
FEATURE_LP_SIZE_TYPE inputFeature = outputFeature * stride + i;
if (inputFeature >= FEATURE_LP_CAST_TYPE inputDesc.size[1]) {
break;
}
v +=
pow(inputP[flpGetOffset(&inputDesc,
batch,
inputFeature,
opt1,
opt2)], power);
}
outputP[flpGetOffset(&outputDesc, batch, outputFeature, opt1, opt2)] =
pow(v, (accreal) 1 / power);
}
}
}
}
}
void
THNN_(FeatureLPPooling_updateGradInput)(
THNNState *state,
THTensor* gradOutput,
THTensor* input,
THTensor* output,
THTensor* gradInput,
accreal power,
int width,
int stride,
bool batchMode) {
int inputDim = THTensor_(nDimension)(input);
if (batchMode) {
THArgCheck(inputDim >= 2 && inputDim <= 4, 3,
"input must be 2-4 dimensions for batch mode");
} else {
THArgCheck(inputDim >= 1 && inputDim <= 3, 3,
"input must be 1-3 dimensions for non-batch mode");
}
FeatureLPPoolingSizes inputDesc =
THNN_(FeatureLPPooling_upcastCPU)(input, batchMode);
FeatureLPPoolingSizes gradOutputDesc =
THNN_(FeatureLPPooling_upcastCPU)(gradOutput, batchMode);
FeatureLPPoolingSizes outputDesc =
THNN_(FeatureLPPooling_upcastCPU)(output, batchMode);
// Make sure the feature dimension is properly sized
THArgCheck(inputDesc.size[1] >= width, 3,
"input: feature dimension must be >= width");
// Make sure that width and stride are within range
THArgCheck(width >= 2 && width <= 16, 7,
"width must be between 2 - 16");
THArgCheck(stride >= 1 && stride <= 4, 8,
"stride must be between 1 - 4");
for (int i = 0; i < 4; ++i) {
THAssertMsg(outputDesc.size[i] == gradOutputDesc.size[i],
"output and gradOutput sizes do not match");
}
// Make sure that the input sizes produce the output sizes
THArgCheck(flpOutputSize(FEATURE_LP_CAST_TYPE inputDesc.size[1], width, stride) ==
outputDesc.size[1], 3,
"input and output sizes do not match with respect to "
"width and stride");
// Resize `gradInput` based on `input`
THNN_(FeatureLPPooling_resizeCPU)(gradInput, input);
// Zero gradInput for accumulation
THTensor_(zero)(gradInput);
FeatureLPPoolingSizes gradInputDesc =
THNN_(FeatureLPPooling_upcastCPU)(gradInput, batchMode);
real* gradOutputP = THTensor_(data)(gradOutput);
real* gradInputP = THTensor_(data)(gradInput);
real* outputP = THTensor_(data)(output);
real* inputP = THTensor_(data)(input);
FEATURE_LP_SIZE_TYPE batch, opt1, opt2, outputFeature, i;
#pragma omp parallel for
for (batch = 0; batch < FEATURE_LP_CAST_TYPE inputDesc.size[0]; ++batch) {
for (opt1 = 0; opt1 < FEATURE_LP_CAST_TYPE inputDesc.size[2]; ++opt1) {
for (opt2 = 0; opt2 < FEATURE_LP_CAST_TYPE inputDesc.size[3]; ++opt2) {
for (outputFeature = 0;
outputFeature < FEATURE_LP_CAST_TYPE outputDesc.size[1]; ++outputFeature) {
// Load output (f(x_is)). It is possible that this is zero, in
// which case we'll ignore this point.
real outputV =
outputP[
flpGetOffset(&outputDesc, batch, outputFeature, opt1, opt2)];
if (outputV == (real) 0) {
continue;
}
for (i = 0; i < width; ++i) {
FEATURE_LP_SIZE_TYPE inputFeature = outputFeature * stride + i;
THAssert(inputFeature < inputDesc.size[1]);
real gradOutputV =
gradOutputP[
flpGetOffset(&gradOutputDesc, batch, outputFeature, opt1, opt2)];
real inputV =
inputP[
flpGetOffset(&inputDesc, batch, inputFeature, opt1, opt2)];
// Calculate grad * (x_i / f(x_is))^(p - 1)
real v = gradOutputV * pow(inputV / outputV, power - (accreal) 1);
gradInputP[
flpGetOffset(&gradInputDesc, batch, inputFeature, opt1, opt2)]
+= v;
}
}
}
}
}
}
#endif
|
TaskEndLink.c | int x;
int main() {
#pragma omp task
{
{
int x;
}
}
#pragma omp task
{
int x;
}
}
|
stream.c | /*-----------------------------------------------------------------------*/
/* Program: STREAM */
/* Revision: $Id: stream.c,v 5.10 2013/01/17 16:01:06 mccalpin Exp mccalpin $ */
/* Original code developed by John D. McCalpin */
/* Programmers: John D. McCalpin */
/* Joe R. Zagar */
/* */
/* This program measures memory transfer rates in MB/s for simple */
/* computational kernels coded in C. */
/*-----------------------------------------------------------------------*/
/* Copyright 1991-2013: John D. McCalpin */
/*-----------------------------------------------------------------------*/
/* License: */
/* 1. You are free to use this program and/or to redistribute */
/* this program. */
/* 2. You are free to modify this program for your own use, */
/* including commercial use, subject to the publication */
/* restrictions in item 3. */
/* 3. You are free to publish results obtained from running this */
/* program, or from works that you derive from this program, */
/* with the following limitations: */
/* 3a. In order to be referred to as "STREAM benchmark results", */
/* published results must be in conformance to the STREAM */
/* Run Rules, (briefly reviewed below) published at */
/* http://www.cs.virginia.edu/stream/ref.html */
/* and incorporated herein by reference. */
/* As the copyright holder, John McCalpin retains the */
/* right to determine conformity with the Run Rules. */
/* 3b. Results based on modified source code or on runs not in */
/* accordance with the STREAM Run Rules must be clearly */
/* labelled whenever they are published. Examples of */
/* proper labelling include: */
/* "tuned STREAM benchmark results" */
/* "based on a variant of the STREAM benchmark code" */
/* Other comparable, clear, and reasonable labelling is */
/* acceptable. */
/* 3c. Submission of results to the STREAM benchmark web site */
/* is encouraged, but not required. */
/* 4. Use of this program or creation of derived works based on this */
/* program constitutes acceptance of these licensing restrictions. */
/* 5. Absolutely no warranty is expressed or implied. */
/*-----------------------------------------------------------------------*/
#include "readHPM.h"
# include <math.h>
# include <float.h>
# include <limits.h>
/*-----------------------------------------------------------------------
* INSTRUCTIONS:
*
* 1) STREAM requires different amounts of memory to run on different
* systems, depending on both the system cache size(s) and the
* granularity of the system timer.
* You should adjust the value of 'STREAM_ARRAY_SIZE' (below)
* to meet *both* of the following criteria:
* (a) Each array must be at least 4 times the size of the
* available cache memory. I don't worry about the difference
* between 10^6 and 2^20, so in practice the minimum array size
* is about 3.8 times the cache size.
* Example 1: One Xeon E3 with 8 MB L3 cache
* STREAM_ARRAY_SIZE should be >= 4 million, giving
* an array size of 30.5 MB and a total memory requirement
* of 91.5 MB.
* Example 2: Two Xeon E5's with 20 MB L3 cache each (using OpenMP)
* STREAM_ARRAY_SIZE should be >= 20 million, giving
* an array size of 153 MB and a total memory requirement
* of 458 MB.
* (b) The size should be large enough so that the 'timing calibration'
* output by the program is at least 20 clock-ticks.
* Example: most versions of Windows have a 10 millisecond timer
* granularity. 20 "ticks" at 10 ms/tic is 200 milliseconds.
* If the chip is capable of 10 GB/s, it moves 2 GB in 200 msec.
* This means the each array must be at least 1 GB, or 128M elements.
*
* Version 5.10 increases the default array size from 2 million
* elements to 10 million elements in response to the increasing
* size of L3 caches. The new default size is large enough for caches
* up to 20 MB.
* Version 5.10 changes the loop index variables from "register int"
* to "ssize_t", which allows array indices >2^32 (4 billion)
* on properly configured 64-bit systems. Additional compiler options
* (such as "-mcmodel=medium") may be required for large memory runs.
*
* Array size can be set at compile time without modifying the source
* code for the (many) compilers that support preprocessor definitions
* on the compile line. E.g.,
* gcc -O -DSTREAM_ARRAY_SIZE=100000000 stream.c -o stream.100M
* will override the default size of 10M with a new size of 100M elements
* per array.
*/
#ifndef STREAM_ARRAY_SIZE
# define STREAM_ARRAY_SIZE 50000
#endif
/* 2) STREAM runs each kernel "NTIMES" times and reports the *best* result
* for any iteration after the first, therefore the minimum value
* for NTIMES is 2.
* There are no rules on maximum allowable values for NTIMES, but
* values larger than the default are unlikely to noticeably
* increase the reported performance.
* NTIMES can also be set on the compile line without changing the source
* code using, for example, "-DNTIMES=7".
*/
#ifdef NTIMES
#if NTIMES<=1
# define NTIMES 1
#endif
#endif
#ifndef NTIMES
# define NTIMES 1
#endif
/* Users are allowed to modify the "OFFSET" variable, which *may* change the
* relative alignment of the arrays (though compilers may change the
* effective offset by making the arrays non-contiguous on some systems).
* Use of non-zero values for OFFSET can be especially helpful if the
* STREAM_ARRAY_SIZE is set to a value close to a large power of 2.
* OFFSET can also be set on the compile line without changing the source
* code using, for example, "-DOFFSET=56".
*/
#ifndef OFFSET
# define OFFSET 0
#endif
/*
* 3) Compile the code with optimization. Many compilers generate
* unreasonably bad code before the optimizer tightens things up.
* If the results are unreasonably good, on the other hand, the
* optimizer might be too smart for me!
*
* For a simple single-core version, try compiling with:
* cc -O stream.c -o stream
* This is known to work on many, many systems....
*
* To use multiple cores, you need to tell the compiler to obey the OpenMP
* directives in the code. This varies by compiler, but a common example is
* gcc -O -fopenmp stream.c -o stream_omp
* The environment variable OMP_NUM_THREADS allows runtime control of the
* number of threads/cores used when the resulting "stream_omp" program
* is executed.
*
* To run with single-precision variables and arithmetic, simply add
* -DSTREAM_TYPE=float
* to the compile line.
* Note that this changes the minimum array sizes required --- see (1) above.
*
* The preprocessor directive "TUNED" does not do much -- it simply causes the
* code to call separate functions to execute each kernel. Trivial versions
* of these functions are provided, but they are *not* tuned -- they just
* provide predefined interfaces to be replaced with tuned code.
*
*
* 4) Optional: Mail the results to mccalpin@cs.virginia.edu
* Be sure to include info that will help me understand:
* a) the computer hardware configuration (e.g., processor model, memory type)
* b) the compiler name/version and compilation flags
* c) any run-time information (such as OMP_NUM_THREADS)
* d) all of the output from the test case.
*
* Thanks!
*
*-----------------------------------------------------------------------*/
# define HLINE "-------------------------------------------------------------\n"
# ifndef MIN
# define MIN(x,y) ((x)<(y)?(x):(y))
# endif
# ifndef MAX
# define MAX(x,y) ((x)>(y)?(x):(y))
# endif
#ifndef STREAM_TYPE
#define STREAM_TYPE int
#endif
static STREAM_TYPE a[STREAM_ARRAY_SIZE+OFFSET],
b[STREAM_ARRAY_SIZE+OFFSET],
c[STREAM_ARRAY_SIZE+OFFSET];
static char *label[4] = {"Copy: ", "Scale: ",
"Add: ", "Triad: "};
static double bytes[4] = {
2 * sizeof(STREAM_TYPE) * STREAM_ARRAY_SIZE,
2 * sizeof(STREAM_TYPE) * STREAM_ARRAY_SIZE,
3 * sizeof(STREAM_TYPE) * STREAM_ARRAY_SIZE,
3 * sizeof(STREAM_TYPE) * STREAM_ARRAY_SIZE
};
#ifdef TUNED
extern void tuned_STREAM_Copy();
extern void tuned_STREAM_Scale(STREAM_TYPE scalar);
extern void tuned_STREAM_Add();
extern void tuned_STREAM_Triad(STREAM_TYPE scalar);
#endif
int
main()
{
int BytesPerWord;
int k;
size_t j;
STREAM_TYPE scalar;
double t, times[4][NTIMES];
/* --- SETUP --- determine precision and check timing --- */
printf(HLINE);
printf("STREAM start, initializing data\n");
printf(HLINE);
BytesPerWord = sizeof(STREAM_TYPE);
setupCSR();
readCSR(INIT);
for (j=0; j<STREAM_ARRAY_SIZE; j++) {
a[j] = 1.0;
}
for (j=0; j<STREAM_ARRAY_SIZE; j++) {
b[j] = 2.0;
}
for (j=0; j<STREAM_ARRAY_SIZE; j++) {
c[j] = 0.0;
}
for (j = 0; j < STREAM_ARRAY_SIZE; j++)
a[j] = 2.0E0 * a[j];
printf("Setup complete\n");
scalar = 3.0;
for (k=0; k<NTIMES; k++)
{
printf(HLINE);
printf("iter %d\n", k);
printf("Stream copy\n");
#ifdef TUNED
tuned_STREAM_Copy();
#else
for (j=0; j<STREAM_ARRAY_SIZE; j++)
c[j] = a[j];
#endif
printf("Stream scale\n");
#ifdef TUNED
tuned_STREAM_Scale(scalar);
#else
for (j=0; j<STREAM_ARRAY_SIZE; j++)
b[j] = scalar*c[j];
#endif
printf("Stream add\n");
#ifdef TUNED
tuned_STREAM_Add();
#else
for (j=0; j<STREAM_ARRAY_SIZE; j++)
c[j] = a[j]+b[j];
#endif
printf("Stream triad\n");
#ifdef TUNED
tuned_STREAM_Triad(scalar);
#else
for (j=0; j<STREAM_ARRAY_SIZE; j++)
a[j] = b[j]+scalar*c[j];
#endif
}
readCSR(FINAL);
printf(HLINE);
printCSR();
return 0;
}
# define M 20
#ifndef abs
#define abs(a) ((a) >= 0 ? (a) : -(a))
#endif
#ifdef TUNED
/* stubs for "tuned" versions of the kernels */
void tuned_STREAM_Copy()
{
ssize_t j;
#pragma omp parallel for
for (j=0; j<STREAM_ARRAY_SIZE; j++)
c[j] = a[j];
}
void tuned_STREAM_Scale(STREAM_TYPE scalar)
{
ssize_t j;
#pragma omp parallel for
for (j=0; j<STREAM_ARRAY_SIZE; j++)
b[j] = scalar*c[j];
}
void tuned_STREAM_Add()
{
ssize_t j;
#pragma omp parallel for
for (j=0; j<STREAM_ARRAY_SIZE; j++)
c[j] = a[j]+b[j];
}
void tuned_STREAM_Triad(STREAM_TYPE scalar)
{
ssize_t j;
#pragma omp parallel for
for (j=0; j<STREAM_ARRAY_SIZE; j++)
a[j] = b[j]+scalar*c[j];
}
/* end of stubs for the "tuned" versions of the kernels */
#endif
|
RecordTable.h | /*
* Souffle - A Datalog Compiler
* Copyright (c) 2020, The Souffle Developers. All rights reserved.
* Licensed under the Universal Permissive License v 1.0 as shown at:
* - https://opensource.org/licenses/UPL
* - <souffle root>/licenses/SOUFFLE-UPL.txt
*/
/************************************************************************
*
* @file RecordTable.h
*
* Data container implementing a map between records and their references.
* Records are separated by arity, i.e., stored in different RecordMaps.
*
***********************************************************************/
#pragma once
#include "souffle/CompiledTuple.h"
#include "souffle/RamTypes.h"
#include <cassert>
#include <cstddef>
#include <limits>
#include <memory>
#include <unordered_map>
#include <utility>
#include <vector>
namespace souffle {
/** @brief Bidirectional mappping between records and record references */
class RecordMap {
/** arity of record */
const size_t arity;
/** hash function for unordered record map */
struct RecordHash {
std::size_t operator()(std::vector<RamDomain> record) const {
std::size_t seed = 0;
std::hash<RamDomain> domainHash;
for (RamDomain value : record) {
seed ^= domainHash(value) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
}
return seed;
}
};
/** map from records to references */
// TODO (b-scholz): replace vector<RamDomain> with something more memory-frugal
std::unordered_map<std::vector<RamDomain>, RamDomain, RecordHash> recordToIndex;
/** array of records; index represents record reference */
// TODO (b-scholz): replace vector<RamDomain> with something more memory-frugal
std::vector<std::vector<RamDomain>> indexToRecord;
public:
explicit RecordMap(size_t arity) : arity(arity), indexToRecord(1) {} // note: index 0 element left free
/** @brief converts record to a record reference */
// TODO (b-scholz): replace vector<RamDomain> with something more memory-frugal
RamDomain pack(const std::vector<RamDomain>& vector) {
RamDomain index;
#pragma omp critical(record_pack)
{
auto pos = recordToIndex.find(vector);
if (pos != recordToIndex.end()) {
index = pos->second;
} else {
#pragma omp critical(record_unpack)
{
indexToRecord.push_back(vector);
index = static_cast<RamDomain>(indexToRecord.size()) - 1;
recordToIndex[vector] = index;
// assert that new index is smaller than the range
assert(index != std::numeric_limits<RamDomain>::max());
}
}
}
return index;
}
/** @brief convert record pointer to a record reference */
RamDomain pack(const RamDomain* tuple) {
// TODO (b-scholz): data is unnecessarily copied
// for a successful lookup. To avoid this, we should
// compute a hash of the pointer-array and traverse through
// the bucket list of the unordered map finding the record.
// Note that in case of non-existence, the record still needs to be
// copied for the newly created entry but this will be the less
// frequent case.
std::vector<RamDomain> tmp(arity);
for (size_t i = 0; i < arity; i++) {
tmp[i] = tuple[i];
}
return pack(tmp);
}
/** @brief convert record reference to a record pointer */
const RamDomain* unpack(RamDomain index) const {
const RamDomain* res;
#pragma omp critical(record_unpack)
res = indexToRecord[index].data();
return res;
}
};
class RecordTable {
public:
RecordTable() = default;
virtual ~RecordTable() = default;
/** @brief convert record to record reference */
RamDomain pack(RamDomain* tuple, size_t arity) {
return lookupArity(arity).pack(tuple);
}
/** @brief convert record reference to a record */
const RamDomain* unpack(RamDomain ref, size_t arity) const {
std::unordered_map<size_t, RecordMap>::const_iterator iter;
#pragma omp critical(RecordTableGetForArity)
{
// Find a previously emplaced map
iter = maps.find(arity);
}
assert(iter != maps.end() && "Attempting to unpack record for non-existing arity");
return (iter->second).unpack(ref);
}
private:
/** @brief lookup RecordMap for a given arity; if it does not exist, create new RecordMap */
RecordMap& lookupArity(size_t arity) {
std::unordered_map<size_t, RecordMap>::iterator mapsIterator;
#pragma omp critical(RecordTableGetForArity)
{
// This will create a new map if it doesn't exist yet.
mapsIterator = maps.emplace(arity, arity).first;
}
return mapsIterator->second;
}
/** Arity/RecordMap association */
std::unordered_map<size_t, RecordMap> maps;
};
/** @brief helper to convert tuple to record reference for the synthesiser */
template <std::size_t Arity>
inline RamDomain pack(RecordTable& recordTab, Tuple<RamDomain, Arity> tuple) {
return recordTab.pack(static_cast<RamDomain*>(tuple.data), Arity);
}
} // namespace souffle
|
core_zgessq.c | /**
*
* @file
*
* PLASMA is a software package provided by:
* University of Tennessee, US,
* University of Manchester, UK.
*
* @precisions normal z -> c d s
*
**/
#include <math.h>
#include <plasma_core_blas.h>
#include "plasma_types.h"
#include "core_lapack.h"
/******************************************************************************/
__attribute__((weak))
void plasma_core_zgessq(int m, int n,
const plasma_complex64_t *A, int lda,
double *scale, double *sumsq)
{
int ione = 1;
for (int j = 0; j < n; j++) {
// TODO: Inline this operation.
LAPACK_zlassq(&m, &A[j*lda], &ione, scale, sumsq);
}
}
/******************************************************************************/
void plasma_core_omp_zgessq(int m, int n,
const plasma_complex64_t *A, int lda,
double *scale, double *sumsq,
plasma_sequence_t *sequence, plasma_request_t *request)
{
#pragma omp task depend(in:A[0:lda*n]) \
depend(out:scale[0:n]) \
depend(out:sumsq[0:n])
{
if (sequence->status == PlasmaSuccess) {
*scale = 0.0;
*sumsq = 1.0;
plasma_core_zgessq(m, n, A, lda, scale, sumsq);
}
}
}
/******************************************************************************/
void plasma_core_omp_zgessq_aux(int n,
const double *scale, const double *sumsq,
double *value,
plasma_sequence_t *sequence, plasma_request_t *request)
{
#pragma omp task depend(in:scale[0:n]) \
depend(in:sumsq[0:n]) \
depend(out:value[0:1])
{
if (sequence->status == PlasmaSuccess) {
double scl = 0.0;
double sum = 1.0;
for (int i = 0; i < n; i++) {
if (scl < scale[i]) {
sum = sumsq[i] + sum*((scl/scale[i])*(scl/scale[i]));
scl = scale[i];
}
else if (scl > 0.) {
sum = sum + sumsq[i]*(scale[i]/scl)*(scale[i]/scl);
}
}
*value = scl*sqrt(sum);
}
}
}
|
conv3x3s1_winograd23_sse_dot.h | // Tencent is pleased to support the open source community by making ncnn available.
//
// Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved.
// 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.
//
#include "option.h"
#include "mat.h"
namespace ncnn{
static void conv3x3s1_winograd23_sse_dot(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel_tm, const Option& opt,
int inch, int outch, int outh, int outw)
{
// BEGIN dot
Mat top_blob_tm = top_blob;;
Mat bottom_blob_tm = bottom_blob;;
{
int w_tm = outw / 2 * 4;
int h_tm = outh / 2 * 4;
int nColBlocks = h_tm/4; // may be the block num in Feathercnn
int nRowBlocks = w_tm/4;
const int tiles = nColBlocks * nRowBlocks;
top_blob_tm.create(16, tiles, outch, 4u, opt.workspace_allocator);
int nn_outch = outch >> 2;
int remain_outch_start = nn_outch << 2;
#pragma omp parallel for num_threads(opt.num_threads)
for (int pp=0; pp<nn_outch; pp++)
{
int p = pp * 4;
Mat out0_tm = top_blob_tm.channel(p);
Mat out1_tm = top_blob_tm.channel(p+1);
Mat out2_tm = top_blob_tm.channel(p+2);
Mat out3_tm = top_blob_tm.channel(p+3);
const Mat kernel0_tm = kernel_tm.channel(p);
const Mat kernel1_tm = kernel_tm.channel(p+1);
const Mat kernel2_tm = kernel_tm.channel(p+2);
const Mat kernel3_tm = kernel_tm.channel(p+3);
for (int i=0; i<tiles; i++)
{
float* output0_tm = out0_tm.row(i);
float* output1_tm = out1_tm.row(i);
float* output2_tm = out2_tm.row(i);
float* output3_tm = out3_tm.row(i);
#if __AVX__
float zero_val = 0.f;
__m256 _sum0 = _mm256_broadcast_ss(&zero_val);
__m256 _sum0n = _mm256_broadcast_ss(&zero_val);
__m256 _sum1 = _mm256_broadcast_ss(&zero_val);
__m256 _sum1n = _mm256_broadcast_ss(&zero_val);
__m256 _sum2 = _mm256_broadcast_ss(&zero_val);
__m256 _sum2n = _mm256_broadcast_ss(&zero_val);
__m256 _sum3 = _mm256_broadcast_ss(&zero_val);
__m256 _sum3n = _mm256_broadcast_ss(&zero_val);
int q = 0;
for (; q+3<inch; q+=4)
{
const float* r0 = bottom_blob_tm.channel(q).row(i);
const float* r1 = bottom_blob_tm.channel(q+1).row(i);
const float* r2 = bottom_blob_tm.channel(q+2).row(i);
const float* r3 = bottom_blob_tm.channel(q+3).row(i);
const float* k0 = kernel0_tm.row(q);
const float* k1 = kernel1_tm.row(q);
const float* k2 = kernel2_tm.row(q);
const float* k3 = kernel3_tm.row(q);
__m256 _r0 = _mm256_loadu_ps(r0);
__m256 _r0n = _mm256_loadu_ps(r0+8);
// k0
__m256 _k0 = _mm256_loadu_ps(k0);
__m256 _k0n = _mm256_loadu_ps(k0+8);
__m256 _k1 = _mm256_loadu_ps(k1);
__m256 _k1n = _mm256_loadu_ps(k1+8);
__m256 _k2 = _mm256_loadu_ps(k2);
__m256 _k2n = _mm256_loadu_ps(k2+8);
__m256 _k3 = _mm256_loadu_ps(k3);
__m256 _k3n = _mm256_loadu_ps(k3+8);
_sum0 = _mm256_fmadd_ps(_r0, _k0, _sum0);
_sum0n = _mm256_fmadd_ps(_r0n, _k0n, _sum0n);
_sum1 = _mm256_fmadd_ps(_r0, _k1, _sum1);
_sum1n = _mm256_fmadd_ps(_r0n, _k1n, _sum1n);
_sum2 = _mm256_fmadd_ps(_r0, _k2, _sum2);
_sum2n = _mm256_fmadd_ps(_r0n, _k2n, _sum2n);
_sum3 = _mm256_fmadd_ps(_r0, _k3, _sum3);
_sum3n = _mm256_fmadd_ps(_r0n, _k3n, _sum3n);
// k1
_r0 = _mm256_loadu_ps(r1);
_r0n = _mm256_loadu_ps(r1+8);
_k0 = _mm256_loadu_ps(k0+16);
_k0n = _mm256_loadu_ps(k0+24);
_k1 = _mm256_loadu_ps(k1+16);
_k1n = _mm256_loadu_ps(k1+24);
_k2 = _mm256_loadu_ps(k2+16);
_k2n = _mm256_loadu_ps(k2+24);
_k3 = _mm256_loadu_ps(k3+16);
_k3n = _mm256_loadu_ps(k3+24);
_sum0 = _mm256_fmadd_ps(_r0, _k0, _sum0);
_sum0n = _mm256_fmadd_ps(_r0n, _k0n, _sum0n);
_sum1 = _mm256_fmadd_ps(_r0, _k1, _sum1);
_sum1n = _mm256_fmadd_ps(_r0n, _k1n, _sum1n);
_sum2 = _mm256_fmadd_ps(_r0, _k2, _sum2);
_sum2n = _mm256_fmadd_ps(_r0n, _k2n, _sum2n);
_sum3 = _mm256_fmadd_ps(_r0, _k3, _sum3);
_sum3n = _mm256_fmadd_ps(_r0n, _k3n, _sum3n);
// k2
_r0 = _mm256_loadu_ps(r2);
_r0n = _mm256_loadu_ps(r2+8);
_k0 = _mm256_loadu_ps(k0+32);
_k0n = _mm256_loadu_ps(k0+40);
_k1 = _mm256_loadu_ps(k1+32);
_k1n = _mm256_loadu_ps(k1+40);
_k2 = _mm256_loadu_ps(k2+32);
_k2n = _mm256_loadu_ps(k2+40);
_k3 = _mm256_loadu_ps(k3+32);
_k3n = _mm256_loadu_ps(k3+40);
_sum0 = _mm256_fmadd_ps(_r0, _k0, _sum0);
_sum0n = _mm256_fmadd_ps(_r0n, _k0n, _sum0n);
_sum1 = _mm256_fmadd_ps(_r0, _k1, _sum1);
_sum1n = _mm256_fmadd_ps(_r0n, _k1n, _sum1n);
_sum2 = _mm256_fmadd_ps(_r0, _k2, _sum2);
_sum2n = _mm256_fmadd_ps(_r0n, _k2n, _sum2n);
_sum3 = _mm256_fmadd_ps(_r0, _k3, _sum3);
_sum3n = _mm256_fmadd_ps(_r0n, _k3n, _sum3n);
// k3
_r0 = _mm256_loadu_ps(r3);
_r0n = _mm256_loadu_ps(r3+8);
_k0 = _mm256_loadu_ps(k0+48);
_k0n = _mm256_loadu_ps(k0+56);
_k1 = _mm256_loadu_ps(k1+48);
_k1n = _mm256_loadu_ps(k1+56);
_k2 = _mm256_loadu_ps(k2+48);
_k2n = _mm256_loadu_ps(k2+56);
_k3 = _mm256_loadu_ps(k3+48);
_k3n = _mm256_loadu_ps(k3+56);
_sum0 = _mm256_fmadd_ps(_r0, _k0, _sum0);
_sum0n = _mm256_fmadd_ps(_r0n, _k0n, _sum0n);
_sum1 = _mm256_fmadd_ps(_r0, _k1, _sum1);
_sum1n = _mm256_fmadd_ps(_r0n, _k1n, _sum1n);
_sum2 = _mm256_fmadd_ps(_r0, _k2, _sum2);
_sum2n = _mm256_fmadd_ps(_r0n, _k2n, _sum2n);
_sum3 = _mm256_fmadd_ps(_r0, _k3, _sum3);
_sum3n = _mm256_fmadd_ps(_r0n, _k3n, _sum3n);
}
for (; q<inch; q++)
{
const float* r0 = bottom_blob_tm.channel(q).row(i);
const float* k0 = kernel0_tm.row(q);
const float* k1 = kernel1_tm.row(q);
const float* k2 = kernel2_tm.row(q);
const float* k3 = kernel3_tm.row(q);
__m256 _r0 = _mm256_loadu_ps(r0);
__m256 _r0n = _mm256_loadu_ps(r0+8);
__m256 _k0 = _mm256_loadu_ps(k0);
__m256 _k0n = _mm256_loadu_ps(k0+8);
__m256 _k1 = _mm256_loadu_ps(k1);
__m256 _k1n = _mm256_loadu_ps(k1+8);
__m256 _k2 = _mm256_loadu_ps(k2);
__m256 _k2n = _mm256_loadu_ps(k2+8);
__m256 _k3 = _mm256_loadu_ps(k3);
__m256 _k3n = _mm256_loadu_ps(k3+8);
_sum0 = _mm256_fmadd_ps(_r0, _k0, _sum0);
_sum0n = _mm256_fmadd_ps(_r0n, _k0n, _sum0n);
_sum1 = _mm256_fmadd_ps(_r0, _k1, _sum1);
_sum1n = _mm256_fmadd_ps(_r0n, _k1n, _sum1n);
_sum2 = _mm256_fmadd_ps(_r0, _k2, _sum2);
_sum2n = _mm256_fmadd_ps(_r0n, _k2n, _sum2n);
_sum3 = _mm256_fmadd_ps(_r0, _k3, _sum3);
_sum3n = _mm256_fmadd_ps(_r0n, _k3n, _sum3n);
}
_mm256_storeu_ps(output0_tm, _sum0);
_mm256_storeu_ps(output0_tm+8, _sum0n);
_mm256_storeu_ps(output1_tm, _sum1);
_mm256_storeu_ps(output1_tm+8, _sum1n);
_mm256_storeu_ps(output2_tm, _sum2);
_mm256_storeu_ps(output2_tm+8, _sum2n);
_mm256_storeu_ps(output3_tm, _sum3);
_mm256_storeu_ps(output3_tm+8, _sum3n);
#else
float sum0[16] = {0.0f};
float sum1[16] = {0.0f};
float sum2[16] = {0.0f};
float sum3[16] = {0.0f};
int q = 0;
for (; q+3<inch; q+=4)
{
const float* r0 = bottom_blob_tm.channel(q).row(i);
const float* r1 = bottom_blob_tm.channel(q+1).row(i);
const float* r2 = bottom_blob_tm.channel(q+2).row(i);
const float* r3 = bottom_blob_tm.channel(q+3).row(i);
const float* k0 = kernel0_tm.row(q);
const float* k1 = kernel1_tm.row(q);
const float* k2 = kernel2_tm.row(q);
const float* k3 = kernel3_tm.row(q);
for (int n=0; n<16; n++)
{
sum0[n] += r0[n] * k0[n];
k0 += 16;
sum0[n] += r1[n] * k0[n];
k0 += 16;
sum0[n] += r2[n] * k0[n];
k0 += 16;
sum0[n] += r3[n] * k0[n];
k0 -= 16 * 3;
sum1[n] += r0[n] * k1[n];
k1 += 16;
sum1[n] += r1[n] * k1[n];
k1 += 16;
sum1[n] += r2[n] * k1[n];
k1 += 16;
sum1[n] += r3[n] * k1[n];
k1 -= 16 * 3;
sum2[n] += r0[n] * k2[n];
k2 += 16;
sum2[n] += r1[n] * k2[n];
k2 += 16;
sum2[n] += r2[n] * k2[n];
k2 += 16;
sum2[n] += r3[n] * k2[n];
k2 -= 16 * 3;
sum3[n] += r0[n] * k3[n];
k3 += 16;
sum3[n] += r1[n] * k3[n];
k3 += 16;
sum3[n] += r2[n] * k3[n];
k3 += 16;
sum3[n] += r3[n] * k3[n];
k3 -= 16 * 3;
}
}
for (; q<inch; q++)
{
const float* r0 = bottom_blob_tm.channel(q).row(i);
const float* k0 = kernel0_tm.row(q);
const float* k1 = kernel1_tm.row(q);
const float* k2 = kernel2_tm.row(q);
const float* k3 = kernel3_tm.row(q);
for (int n=0; n<16; n++)
{
sum0[n] += r0[n] * k0[n];
sum1[n] += r0[n] * k1[n];
sum2[n] += r0[n] * k2[n];
sum3[n] += r0[n] * k3[n];
}
}
for (int n=0; n<16; n++)
{
output0_tm[n] = sum0[n];
output1_tm[n] = sum1[n];
output2_tm[n] = sum2[n];
output3_tm[n] = sum3[n];
}
#endif
}
}
#pragma omp parallel for num_threads(opt.num_threads)
for (int p=remain_outch_start; p<outch; p++)
{
Mat out0_tm = top_blob_tm.channel(p);
const Mat kernel0_tm = kernel_tm.channel(p);
for (int i=0; i<tiles; i++)
{
float* output0_tm = out0_tm.row(i);
float sum0[16] = {0.0f};
int q = 0;
for (; q+3<inch; q+=4)
{
const float* r0 = bottom_blob_tm.channel(q).row(i);
const float* r1 = bottom_blob_tm.channel(q+1).row(i);
const float* r2 = bottom_blob_tm.channel(q+2).row(i);
const float* r3 = bottom_blob_tm.channel(q+3).row(i);
const float* k0 = kernel0_tm.row(q);
const float* k1 = kernel0_tm.row(q+1);
const float* k2 = kernel0_tm.row(q+2);
const float* k3 = kernel0_tm.row(q+3);
for (int n=0; n<16; n++)
{
sum0[n] += r0[n] * k0[n];
sum0[n] += r1[n] * k1[n];
sum0[n] += r2[n] * k2[n];
sum0[n] += r3[n] * k3[n];
}
}
for (; q<inch; q++)
{
const float* r0 = bottom_blob_tm.channel(q).row(i);
const float* k0 = kernel0_tm.row(q);
for (int n=0; n<16; n++)
{
sum0[n] += r0[n] * k0[n];
}
}
for (int n=0; n<16; n++)
{
output0_tm[n] = sum0[n];
}
}
}
}
}
}
|
cg.20190417_static1.c | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <unistd.h>
#include "globals.h"
#include "randdp.h"
#include "timers.h"
#include <omp.h>
//---------------------------------------------------------------------
#define CACHE_LINE_SIZE_PAD 128
#define INT_PAD_SIZE CACHE_LINE_SIZE_PAD/sizeof(int)
#define DOUBLE_PAD_SIZE CACHE_LINE_SIZE_PAD/sizeof(double)
/* common / main_int_mem / */
static int colidx[NZ];
static int rowstr[NA+1];
static int iv[NA];
static int arow[NA];
static int acol[NAZ];
/* common / main_flt_mem / */
static double aelt[NAZ];
static double a[NZ];
static double x[NA+2];
static double z[NA+2];
static double p[NA+2];
static double q[NA+2];
static double r[NA+2];
/* common / partit_size / */
static int naa;
static int nzz;
static int firstrow;
static int lastrow;
static int firstcol;
static int lastcol;
/* common /urando/ */
static double amult;
static double tran;
/* common /timers/ */
static logical timeron;
//---------------------------------------------------------------------
//---------------------------------------------------------------------
static void conj_grad(int colidx[],
int rowstr[],
double x[],
double z[],
double a[],
double p[],
double q[],
double r[],
double *rnorm);
static void makea(int n,
int nz,
double a[],
int colidx[],
int rowstr[],
int firstrow,
int lastrow,
int firstcol,
int lastcol,
int arow[],
int acol[][NONZER+1],
double aelt[][NONZER+1],
int iv[]);
static void sparse(double a[],
int colidx[],
int rowstr[],
int n,
int nz,
int nozer,
int arow[],
int acol[][NONZER+1],
double aelt[][NONZER+1],
int firstrow,
int lastrow,
int nzloc[],
double rcond,
double shift);
static void sprnvc(int n, int nz, int nn1, double v[], int iv[]);
static int icnvrt(double x, int ipwr2);
static void vecset(int n, double v[], int iv[], int *nzv, int i, double val);
//---------------------------------------------------------------------
int main(int argc, char *argv[])
{
omp_set_num_threads(omp_get_num_procs());
int i, j, k, it;
double zeta;
double rnorm;
double norm_temp1, norm_temp2;
double t, mflops, tmax;
//char Class;
logical verified;
double zeta_verify_value, epsilon, err;
char *t_names[T_last];
for (i = 0; i < T_last; i++) {
timer_clear(i);
}
timer_start(T_init);
firstrow = 0;
lastrow = NA-1;
firstcol = 0;
lastcol = NA-1;
zeta_verify_value = VALID_RESULT;
printf("\nCG start...\n\n");
printf(" Size: %11d\n", NA);
printf(" Iterations: %5d\n", NITER);
printf("\n");
naa = NA;
nzz = NZ;
//---------------------------------------------------------------------
// Inialize random number generator
//---------------------------------------------------------------------
tran = 314159265.0;
amult = 1220703125.0;
zeta = randlc(&tran, amult);
//---------------------------------------------------------------------
//
//---------------------------------------------------------------------
makea(naa, nzz, a, colidx, rowstr,
firstrow, lastrow, firstcol, lastcol,
arow,
(int (*)[NONZER+1])(void*)acol,
(double (*)[NONZER+1])(void*)aelt,
iv);
//---------------------------------------------------------------------
// Note: as a result of the above call to makea:
// values of j used in indexing rowstr go from 0 --> lastrow-firstrow
// values of colidx which are col indexes go from firstcol --> lastcol
// So:
// Shift the col index vals from actual (firstcol --> lastcol )
// to local, i.e., (0 --> lastcol-firstcol)
//---------------------------------------------------------------------
int j0, j1, j2, j3, j4;
int k0, k1;
int total_num = lastcol-firstcol+1;
int residue = total_num%8;
int total_num_NA = NA+1;
int residue_NA = total_num_NA%8;
#pragma omp parallel default(shared) private(i, j, k, j0, j1, j2, j3, j4, k0, k1)
{
#pragma omp for nowait schedule(static, 1)
for (j = 0; j < lastrow - firstrow + 1; j++) {
for (k = rowstr[j]; k < rowstr[j+1]; k++) {
colidx[k] = colidx[k] - firstcol;
}
}
//---------------------------------------------------------------------
// set starting vector to (1, 1, .... 1)
//---------------------------------------------------------------------
#pragma omp for nowait schedule(static, 1)
for (k0 = 0; k0 < residue_NA; k0++) {
x[k0] = 1;
}
#pragma omp for nowait schedule(static, 1)
for (j4 = residue_NA; j4 < total_num_NA; j4=j4+8) {
x[j4] = 1;
x[j4+1] = 1;
x[j4+2] = 1;
x[j4+3] = 1;
x[j4+4] = 1;
x[j4+5] = 1;
x[j4+6] = 1;
x[j4+7] = 1;
}
#pragma omp for nowait schedule(static, 1)
for (k1 = 0; k1 < residue; k1++) {
q[k1] = 0.0;
z[k1] = 0.0;
r[k1] = 0.0;
p[k1] = 0.0;
}
#pragma omp for nowait schedule(static, 1)
for (j2 = residue; j2 < total_num; j2=j2+8) {
r[j2] = 0.0;
r[j2+1] = 0.0;
r[j2+2] = 0.0;
r[j2+3] = 0.0;
r[j2+4] = 0.0;
r[j2+5] = 0.0;
r[j2+6] = 0.0;
r[j2+7] = 0.0;
}
#pragma omp for nowait schedule(static, 1)
for (j0 = residue; j0 < total_num; j0=j0+8) {
q[j0] = 0.0;
q[j0+1] = 0.0;
q[j0+2] = 0.0;
q[j0+3] = 0.0;
q[j0+4] = 0.0;
q[j0+5] = 0.0;
q[j0+6] = 0.0;
q[j0+7] = 0.0;
}
#pragma omp for nowait schedule(static, 1)
for (j1 = residue; j1 < total_num; j1=j1+8) {
z[j1] = 0.0;
z[j1+1] = 0.0;
z[j1+2] = 0.0;
z[j1+3] = 0.0;
z[j1+4] = 0.0;
z[j1+5] = 0.0;
z[j1+6] = 0.0;
z[j1+7] = 0.0;
}
#pragma omp for schedule(static, 1)
for (j3 = residue; j3 < total_num; j3=j3+8) {
p[j3] = 0.0;
p[j3+1] = 0.0;
p[j3+2] = 0.0;
p[j3+3] = 0.0;
p[j3+4] = 0.0;
p[j3+5] = 0.0;
p[j3+6] = 0.0;
p[j3+7] = 0.0;
}
/*
#pragma omp for nowait
for (i = 0; i < NA+1; i++) {
x[i] = 1.0;
}
#pragma omp for nowait
for (j = 0; j < lastcol - firstcol + 1; j++) {
q[j] = 0.0;
z[j] = 0.0;
r[j] = 0.0;
p[j] = 0.0;
}
*/
}
/*
memset(x, 1, (NA+1) * sizeof(double));
memset(q, 0, (lastcol-firstcol+1) * sizeof(double));
memset(z, 0, (lastcol-firstcol+1) * sizeof(double));
memset(r, 0, (lastcol-firstcol+1) * sizeof(double));
memset(p, 0, (lastcol-firstcol+1) * sizeof(double));
*/
zeta = 0.0;
//---------------------------------------------------------------------
//---->
// Do one iteration untimed to init all code and data page tables
//----> (then reinit, start timing, to niter its)
//---------------------------------------------------------------------
for (it = 1; it <= 1; it++) {
//---------------------------------------------------------------------
// The call to the conjugate gradient routine:
//---------------------------------------------------------------------
conj_grad(colidx, rowstr, x, z, a, p, q, r, &rnorm);
//---------------------------------------------------------------------
// zeta = shift + 1/(x.z)
// So, first: (x.z)
// Also, find norm of z
// So, first: (z.z)
//---------------------------------------------------------------------
norm_temp1 = 0.0;
norm_temp2 = 0.0;
#pragma omp parallel for default(shared) private(j) schedule(static, 1) reduction(+:norm_temp1,norm_temp2)
for (j = 0; j < total_num; j++) {
norm_temp1 = norm_temp1 + x[j] * z[j];
norm_temp2 = norm_temp2 + z[j] * z[j];
}
norm_temp2 = 1.0 / sqrt(norm_temp2);
//---------------------------------------------------------------------
// Normalize z to obtain x
//---------------------------------------------------------------------
/*
#pragma omp parallel default(shared) private(j, k)
{
#pragma omp for nowait
for (k = 0; k < residue; k++) {
x[k] = norm_temp2 * z[k];
}
#pragma omp for
for (j = residue; j < total_num; j=j+8) {
x[j] = norm_temp2 * z[j];
}
}
*/
/*
#pragma omp parallel for default(shared) private(j)
for (j = 0; j < lastcol - firstcol + 1; j++) {
x[j] = norm_temp2 * z[j];
}
*/
} // end of do one iteration untimed
//---------------------------------------------------------------------
// set starting vector to (1, 1, .... 1)
//---------------------------------------------------------------------
#pragma omp parallel default(shared) private(j, k)
{
#pragma omp for nowait schedule(static, 1)
for (k = 0; k < residue_NA; k++) {
x[k] = 1;
}
#pragma omp for schedule(static, 1)
for (j = residue_NA; j < total_num_NA; j=j+8) {
x[j] = 1;
x[j+1] = 1;
x[j+2] = 1;
x[j+3] = 1;
x[j+4] = 1;
x[j+5] = 1;
x[j+6] = 1;
x[j+7] = 1;
}
}
/*
#pragma omp parallel for default(shared) private(i)
for (i = 0; i < NA+1; i++) {
x[i] = 1.0;
}
*/
//memset(x, 1, (NA+1) * sizeof(double));
zeta = 0.0;
timer_stop(T_init);
printf(" Initialization time = %15.3f seconds\n", timer_read(T_init));
timer_start(T_bench);
//---------------------------------------------------------------------
//---->
// Main Iteration for inverse power method
//---->
//---------------------------------------------------------------------
for (it = 1; it <= NITER; it++) {
//---------------------------------------------------------------------
// The call to the conjugate gradient routine:
//---------------------------------------------------------------------
if (timeron) timer_start(T_conj_grad);
conj_grad(colidx, rowstr, x, z, a, p, q, r, &rnorm);
if (timeron) timer_stop(T_conj_grad);
//---------------------------------------------------------------------
// zeta = shift + 1/(x.z)
// So, first: (x.z)
// Also, find norm of z
// So, first: (z.z)
//---------------------------------------------------------------------
norm_temp1 = 0.0;
norm_temp2 = 0.0;
#pragma omp parallel for default(shared) private(j) schedule(static, 1) reduction(+:norm_temp1,norm_temp2)
for (j = 0; j < lastcol - firstcol + 1; j++) {
norm_temp1 = norm_temp1 + x[j]*z[j];
norm_temp2 = norm_temp2 + z[j]*z[j];
}
norm_temp2 = 1.0 / sqrt(norm_temp2);
zeta = SHIFT + 1.0 / norm_temp1;
if (it == 1)
printf("\n iteration ||r|| zeta\n");
printf(" %5d %20.14E%20.13f\n", it, rnorm, zeta);
//---------------------------------------------------------------------
// Normalize z to obtain x
//---------------------------------------------------------------------
#pragma omp parallel default(shared) private(j, k)
{
#pragma omp for nowait schedule(static, 1)
for (k = 0; k < residue; k++) {
x[k] = norm_temp2 * z[k];
}
#pragma omp for schedule(static, 1)
for (j = residue; j < total_num; j=j+8) {
x[j] = norm_temp2 * z[j];
x[j+1] = norm_temp2 * z[j+1];
x[j+2] = norm_temp2 * z[j+2];
x[j+3] = norm_temp2 * z[j+3];
x[j+4] = norm_temp2 * z[j+4];
x[j+5] = norm_temp2 * z[j+5];
x[j+6] = norm_temp2 * z[j+6];
x[j+7] = norm_temp2 * z[j+7];
}
}
/*
#pragma omp parallel for default(shared) private(j)
for (j = 0; j < lastcol - firstcol + 1; j++) {
x[j] = norm_temp2 * z[j];
}
*/
} // end of main iter inv pow meth
timer_stop(T_bench);
//---------------------------------------------------------------------
// End of timed section
//---------------------------------------------------------------------
t = timer_read(T_bench);
printf("\nComplete...\n");
epsilon = 1.0e-10;
err = fabs(zeta - zeta_verify_value) / zeta_verify_value;
if (err <= epsilon) {
verified = true;
printf(" VERIFICATION SUCCESSFUL\n");
printf(" Zeta is %20.13E\n", zeta);
printf(" Error is %20.13E\n", err);
} else {
verified = false;
printf(" VERIFICATION FAILED\n");
printf(" Zeta %20.13E\n", zeta);
printf(" The correct zeta is %20.13E\n", zeta_verify_value);
}
printf("\n\nExecution time : %lf seconds\n\n", t);
return 0;
}
//---------------------------------------------------------------------
// Floaging point arrays here are named as in spec discussion of
// CG algorithm
//---------------------------------------------------------------------
static void conj_grad(int colidx[],
int rowstr[],
double x[],
double z[],
double a[],
double p[],
double q[],
double r[],
double *rnorm)
{
int j, k, j0, j1, j2, j3, j4;
int cgit, cgitmax = 25;
double d, sum, rho, rho0, alpha, beta;
int total_num = naa+1;
int residue = (total_num)%8;
int rho_num = lastcol-firstcol+1;
int residue2 = (rho_num)%8;
rho = 0.0;
//---------------------------------------------------------------------
// Initialize the CG algorithm:
//---------------------------------------------------------------------
/*
memset(q, 0, total_num*sizeof(double));
memset(z, 0, total_num*sizeof(double));
memcpy(r, x, total_num*sizeof(double));
memcpy(p, x, total_num*sizeof(double));
*/
#pragma omp parallel default(shared) private(j, k, j0, j1, j2, j3, j4)
{
#pragma omp for nowait schedule(static, 1)
for (k = 0; k < residue; k++) {
q[k] = 0.0;
z[k] = 0.0;
r[k] = x[k];
p[k] = x[k];
}
#pragma omp for nowait schedule(static, 1)
for (j2 = residue; j2 < total_num; j2=j2+8) {
r[j2] = x[j2];
r[j2+1] = x[j2+1];
r[j2+2] = x[j2+2];
r[j2+3] = x[j2+3];
r[j2+4] = x[j2+4];
r[j2+5] = x[j2+5];
r[j2+6] = x[j2+6];
r[j2+7] = x[j2+7];
}
#pragma omp for nowait schedule(static, 1)
for (j0 = residue; j0 < total_num; j0=j0+8) {
q[j0] = 0.0;
q[j0+1] = 0.0;
q[j0+2] = 0.0;
q[j0+3] = 0.0;
q[j0+4] = 0.0;
q[j0+5] = 0.0;
q[j0+6] = 0.0;
q[j0+7] = 0.0;
}
#pragma omp for nowait schedule(static, 1)
for (j1 = residue; j1 < total_num; j1=j1+8) {
z[j1] = 0.0;
z[j1+1] = 0.0;
z[j1+2] = 0.0;
z[j1+3] = 0.0;
z[j1+4] = 0.0;
z[j1+5] = 0.0;
z[j1+6] = 0.0;
z[j1+7] = 0.0;
}
#pragma omp for nowait schedule(static, 1)
for (j3 = residue; j3 < total_num; j3=j3+8) {
p[j3] = x[j3];
p[j3+1] = x[j3+1];
p[j3+2] = x[j3+2];
p[j3+3] = x[j3+3];
p[j3+4] = x[j3+4];
p[j3+5] = x[j3+5];
p[j3+6] = x[j3+6];
p[j3+7] = x[j3+7];
}
//---------------------------------------------------------------------
// rho = r.r
// Now, obtain the norm of r: First, sum squares of r elements locally...
//---------------------------------------------------------------------
//#pragma omp for reduction(+:rho)
#pragma omp for schedule(static, 1) reduction(+:rho)
for (j4 = 0; j4 < residue2; j4++) {
rho = rho + r[j4]*r[j4];
}
#pragma omp for schedule(static, 1) reduction(+:rho)
for(j=residue2; j<rho_num; j+=8){
rho = rho + r[j]*r[j]
+ r[j+1]*r[j+1]
+ r[j+2]*r[j+2]
+ r[j+3]*r[j+3]
+ r[j+4]*r[j+4]
+ r[j+5]*r[j+5]
+ r[j+6]*r[j+6]
+ r[j+7]*r[j+7];
}
}
//---------------------------------------------------------------------
//---->
// The conj grad iteration loop
//---->
//---------------------------------------------------------------------
for (cgit = 1; cgit <= cgitmax; cgit++) {
//---------------------------------------------------------------------
// q = A.p
// The partition submatrix-vector multiply: use workspace w
//---------------------------------------------------------------------
//
// NOTE: this version of the multiply is actually (slightly: maybe %5)
// faster on the sp2 on 16 nodes than is the unrolled-by-2 version
// below. On the Cray t3d, the reverse is true, i.e., the
// unrolled-by-two version is some 10% faster.
// The unrolled-by-8 version below is significantly faster
// on the Cray t3d - overall speed of code is 1.5 times faster.
rho0 = rho;
d = 0.0;
rho = 0.0;
#pragma omp parallel default(shared)
{
#pragma omp for private(sum, j, k) schedule(static, 1)
for (j = 0; j < lastrow - firstrow + 1; j++) {
sum = 0.0;
for (k = rowstr[j]; k < rowstr[j+1]; k++) {
sum = sum + a[k]*p[colidx[k]];
}
q[j] = sum;
}
//---------------------------------------------------------------------
// Obtain p.q
//---------------------------------------------------------------------
#pragma omp for private(j) schedule(static, 1) reduction(+:d)
for (j = 0; j < lastcol - firstcol + 1; j++) {
d = d + p[j]*q[j];
}
//---------------------------------------------------------------------
// Obtain alpha = rho / (p.q)
//---------------------------------------------------------------------
#pragma omp single
alpha = rho0 / d;
//---------------------------------------------------------------------
// Obtain z = z + alpha*p
// and r = r - alpha*q
//---------------------------------------------------------------------
#pragma omp for private(j) schedule(static, 1)
for (j = 0; j < lastcol - firstcol + 1; j++) {
z[j] = z[j] + alpha*p[j];
r[j] = r[j] - alpha*q[j];
}
//---------------------------------------------------------------------
// rho = r.r
// Now, obtain the norm of r: First, sum squares of r elements locally...
//---------------------------------------------------------------------
#pragma omp for private(j) schedule(static, 1) reduction(+:rho)
for (j = 0; j < lastcol - firstcol + 1; j++) {
rho = rho + r[j]*r[j];
}
//---------------------------------------------------------------------
// Obtain beta:
//---------------------------------------------------------------------
#pragma omp single
beta = rho / rho0;
//---------------------------------------------------------------------
// p = r + beta*p
//---------------------------------------------------------------------
#pragma omp for private(j) schedule(static, 1)
for (j = 0; j < lastcol - firstcol + 1; j++) {
p[j] = r[j] + beta*p[j];
}
}
} // end of do cgit=1,cgitmax
//---------------------------------------------------------------------
// Compute residual norm explicitly: ||r|| = ||x - A.z||
// First, form A.z
// The partition submatrix-vector multiply
//---------------------------------------------------------------------
/*
for (j = 0; j < lastrow - firstrow + 1; j++) {
printf("j = %d, colidx[%d] = %d, z[%d] = %lf\n", j, j, colidx[j], colidx[j], z[colidx[j]][0]);
}
*/
sum = 0.0;
#pragma omp parallel default(shared) private(j, d) shared(sum)
{
#pragma omp for schedule(static, 1)
for (j = 0; j < lastrow - firstrow + 1; j++) {
d = 0.0;
for (k = rowstr[j]; k < rowstr[j+1]; k++) {
d = d + a[k]*z[colidx[k]];
}
r[j] = d;
}
//---------------------------------------------------------------------
// At this point, r contains A.z
//---------------------------------------------------------------------
#pragma omp for schedule(static, 1) reduction(+:sum)
for (j = 0; j < lastcol-firstcol+1; j++) {
double d_tmp = x[j] - r[j];
sum = sum + d_tmp*d_tmp;
}
}
*rnorm = sqrt(sum);
}
//---------------------------------------------------------------------
// generate the test problem for benchmark 6
// makea generates a sparse matrix with a
// prescribed sparsity distribution
//
// parameter type usage
//
// input
//
// n i number of cols/rows of matrix
// nz i nonzeros as declared array size
// rcond r*8 condition number
// shift r*8 main diagonal shift
//
// output
//
// a r*8 array for nonzeros
// colidx i col indices
// rowstr i row pointers
//
// workspace
//
// iv, arow, acol i
// aelt r*8
//---------------------------------------------------------------------
static void makea(int n,
int nz,
double a[],
int colidx[],
int rowstr[],
int firstrow,
int lastrow,
int firstcol,
int lastcol,
int arow[],
int acol[][NONZER+1],
double aelt[][NONZER+1],
int iv[])
{
int iouter, ivelt, nzv, nn1;
int ivc[NONZER+1];
double vc[NONZER+1];
//---------------------------------------------------------------------
// nonzer is approximately (int(sqrt(nnza /n)));
//---------------------------------------------------------------------
//---------------------------------------------------------------------
// nn1 is the smallest power of two not less than n
//---------------------------------------------------------------------
nn1 = 1;
do {
nn1 = 2 * nn1;
} while (nn1 < n);
//---------------------------------------------------------------------
// Generate nonzero positions and save for the use in sparse.
//---------------------------------------------------------------------
for (iouter = 0; iouter < n; iouter++) {
nzv = NONZER;
sprnvc(n, nzv, nn1, vc, ivc);
vecset(n, vc, ivc, &nzv, iouter+1, 0.5);
arow[iouter] = nzv;
for (ivelt = 0; ivelt < nzv; ivelt++) {
acol[iouter][ivelt] = ivc[ivelt] - 1;
aelt[iouter][ivelt] = vc[ivelt];
}
}
//---------------------------------------------------------------------
// ... make the sparse matrix from list of elements with duplicates
// (iv is used as workspace)
//---------------------------------------------------------------------
sparse(a, colidx, rowstr, n, nz, NONZER, arow, acol,
aelt, firstrow, lastrow,
iv, RCOND, SHIFT);
}
//---------------------------------------------------------------------
// rows range from firstrow to lastrow
// the rowstr pointers are defined for nrows = lastrow-firstrow+1 values
//---------------------------------------------------------------------
static void sparse(double a[],
int colidx[],
int rowstr[],
int n,
int nz,
int nozer,
int arow[],
int acol[][NONZER+1],
double aelt[][NONZER+1],
int firstrow,
int lastrow,
int nzloc[],
double rcond,
double shift)
{
int nrows;
//---------------------------------------------------
// generate a sparse matrix from a list of
// [col, row, element] tri
//---------------------------------------------------
int i, j, j1, j2, nza, k, kk, nzrow, jcol;
double size, scale, ratio, va;
logical cont40;
//---------------------------------------------------------------------
// how many rows of result
//---------------------------------------------------------------------
nrows = lastrow - firstrow + 1;
//---------------------------------------------------------------------
// ...count the number of triples in each row
//---------------------------------------------------------------------
//memset(rowstr, 0, (nrows+1)*sizeof(int));
#pragma omp parallel for default(shared) private(j) schedule(static, 1)
for (j = 0; j < nrows+1; j++) {
rowstr[j] = 0;
}
for (i = 0; i < n; i++) {
for (nza = 0; nza < arow[i]; nza++) {
j = acol[i][nza] + 1;
rowstr[j] = rowstr[j] + arow[i];
}
}
rowstr[0] = 0;
for (j = 1; j < nrows+1; j++) {
rowstr[j] = rowstr[j] + rowstr[j-1];
}
nza = rowstr[nrows] - 1;
//---------------------------------------------------------------------
// ... rowstr(j) now is the location of the first nonzero
// of row j of a
//---------------------------------------------------------------------
if (nza > nz) {
printf("Space for matrix elements exceeded in sparse\n");
printf("nza, nzmax = %d, %d\n", nza, nz);
exit(EXIT_FAILURE);
}
//---------------------------------------------------------------------
// ... preload data pages
//---------------------------------------------------------------------
#pragma omp parallel for default(shared) private(j, k) schedule(static, 1)
for (j = 0; j < nrows; j++) {
for (k = rowstr[j]; k < rowstr[j+1]; k++) {
a[k] = 0.0;
colidx[k] = -1;
}
nzloc[j] = 0;
}
//---------------------------------------------------------------------
// ... generate actual values by summing duplicates
//---------------------------------------------------------------------
size = 1.0;
ratio = pow(rcond, (1.0 / (double)(n)));
for (i = 0; i < n; i++) {
for (nza = 0; nza < arow[i]; nza++) {
j = acol[i][nza];
scale = size * aelt[i][nza];
for (nzrow = 0; nzrow < arow[i]; nzrow++) {
jcol = acol[i][nzrow];
va = aelt[i][nzrow] * scale;
//--------------------------------------------------------------------
// ... add the identity * rcond to the generated matrix to bound
// the smallest eigenvalue from below by rcond
//--------------------------------------------------------------------
if (jcol == j && j == i) {
va = va + rcond - shift;
}
cont40 = false;
for (k = rowstr[j]; k < rowstr[j+1]; k++) {
if (colidx[k] > jcol) {
//----------------------------------------------------------------
// ... insert colidx here orderly
//----------------------------------------------------------------
for (kk = rowstr[j+1]-2; kk >= k; kk--) {
if (colidx[kk] > -1) {
a[kk+1] = a[kk];
colidx[kk+1] = colidx[kk];
}
}
colidx[k] = jcol;
a[k] = 0.0;
cont40 = true;
break;
} else if (colidx[k] == -1) {
colidx[k] = jcol;
cont40 = true;
break;
} else if (colidx[k] == jcol) {
//--------------------------------------------------------------
// ... mark the duplicated entry
//--------------------------------------------------------------
nzloc[j] = nzloc[j] + 1;
cont40 = true;
break;
}
}
if (cont40 == false) {
printf("internal error in sparse: i=%d\n", i);
exit(EXIT_FAILURE);
}
a[k] = a[k] + va;
}
}
size = size * ratio;
}
//---------------------------------------------------------------------
// ... remove empty entries and generate final results
//---------------------------------------------------------------------
for (j = 1; j < nrows; j++) {
nzloc[j] = nzloc[j] + nzloc[j-1];
}
for (j = 0; j < nrows; j++) {
if (j > 0) {
j1 = rowstr[j] - nzloc[j-1];
} else {
j1 = 0;
}
j2 = rowstr[j+1] - nzloc[j];
nza = rowstr[j];
for (k = j1; k < j2; k++) {
a[k] = a[nza];
colidx[k] = colidx[nza];
nza = nza + 1;
}
}
#pragma omp parallel for default(shared) private(j) schedule(static, 1)
for (j = 1; j < nrows+1; j++) {
rowstr[j] = rowstr[j] - nzloc[j-1];
}
nza = rowstr[nrows] - 1;
}
//---------------------------------------------------------------------
// generate a sparse n-vector (v, iv)
// having nzv nonzeros
//
// mark(i) is set to 1 if position i is nonzero.
// mark is all zero on entry and is reset to all zero before exit
// this corrects a performance bug found by John G. Lewis, caused by
// reinitialization of mark on every one of the n calls to sprnvc
//---------------------------------------------------------------------
static void sprnvc(int n, int nz, int nn1, double v[], int iv[])
{
int nzv, ii, i;
double vecelt, vecloc;
nzv = 0;
while (nzv < nz) {
vecelt = randlc(&tran, amult);
//---------------------------------------------------------------------
// generate an integer between 1 and n in a portable manner
//---------------------------------------------------------------------
vecloc = randlc(&tran, amult);
i = icnvrt(vecloc, nn1) + 1;
if (i > n) continue;
//---------------------------------------------------------------------
// was this integer generated already?
//---------------------------------------------------------------------
logical was_gen = false;
for (ii = 0; ii < nzv; ii++) {
if (iv[ii] == i) {
was_gen = true;
break;
}
}
if (was_gen) continue;
v[nzv] = vecelt;
iv[nzv] = i;
nzv = nzv + 1;
}
}
//---------------------------------------------------------------------
// scale a double precision number x in (0,1) by a power of 2 and chop it
//---------------------------------------------------------------------
static int icnvrt(double x, int ipwr2)
{
return (int)(ipwr2 * x);
}
//---------------------------------------------------------------------
// set ith element of sparse vector (v, iv) with
// nzv nonzeros to val
//---------------------------------------------------------------------
static void vecset(int n, double v[], int iv[], int *nzv, int i, double val)
{
int k;
logical set;
set = false;
for (k = 0; k < *nzv; k++) {
if (iv[k] == i) {
v[k] = val;
set = true;
}
}
if (set == false) {
v[*nzv] = val;
iv[*nzv] = i;
*nzv = *nzv + 1;
}
}
|
pi-v21.c | /*
* Compute pi by approximating the area under the curve f(x) = 4 / (1 + x*x)
* between 0 and 1.
*
* parallel version using OpenMP
*/
#include <stdio.h>
#include <stdlib.h>
#include <omp.h> /* OpenMP */
#if _DEBUG_
#define _DEBUG_ 1
#else
#define _DEBUG_ 0
#include "extrae_user_events.h"
#define PROGRAM 1000
#define PI_COMPUTATION 1
#define FINAL_PI 2
#define END 0
#endif
int main(int argc, char *argv[]) {
double x, sum=0.0, pi=0.0;
#if _DEBUG_
double start,end;
#endif
int i;
const char Usage[] = "Usage: pi <num_steps> (try 1000000000)\n";
if (argc < 2) {
fprintf(stderr, Usage);
exit(1);
}
int num_steps = atoi(argv[1]);
double step = 1.0/(double) num_steps;
#if _DEBUG_
start= omp_get_wtime();
#endif
/* do computation -- using just two threads */
// WARNING : correct code
#pragma omp parallel
#pragma omp single
{
#if _DEBUG_
int id = omp_get_thread_num();
#endif
for (i=0; i < num_steps; i++) {
#pragma omp task private(x) firstprivate(i) shared(sum)
{
#if !_DEBUG_
Extrae_event (PROGRAM, PI_COMPUTATION);
#endif
x = (i+0.5)*step;
#pragma omp atomic
sum += 4.0/(1.0+x*x);
#if _DEBUG_
printf("thread id:%d it:%d\n",id,i);
#else
Extrae_event (PROGRAM, END);
#endif
}
}
#pragma omp taskwait
#pragma omp task
#if !_DEBUG_
{
Extrae_event (PROGRAM, FINAL_PI);
#endif
pi = step * sum;
#if !_DEBUG_
Extrae_event (PROGRAM, END);
}
#endif
}
#if _DEBUG_
end = omp_get_wtime();
printf("Wall clock execution time = %.9f seconds\n", end-start);
#endif
/* print results */
printf("Value of pi = %12.10f\n", pi);
return EXIT_SUCCESS;
}
|
GridInit.c | #include "XSbench_header.h"
#ifdef MPI
#include<mpi.h>
#endif
// Generates randomized energy grid for each nuclide
// Note that this is done as part of initialization (serial), so
// rand() is used.
void generate_grids( NuclideGridPoint ** nuclide_grids,
long n_isotopes, long n_gridpoints ) {
for( long i = 0; i < n_isotopes; i++ )
for( long j = 0; j < n_gridpoints; j++ )
{
nuclide_grids[i][j].energy =((double)rand()/(double)RAND_MAX);
nuclide_grids[i][j].total_xs =((double)rand()/(double)RAND_MAX);
nuclide_grids[i][j].elastic_xs =((double)rand()/(double)RAND_MAX);
nuclide_grids[i][j].absorbtion_xs=((double)rand()/(double)RAND_MAX);
nuclide_grids[i][j].fission_xs =((double)rand()/(double)RAND_MAX);
nuclide_grids[i][j].nu_fission_xs=((double)rand()/(double)RAND_MAX);
}
}
// Verification version of this function (tighter control over RNG)
void generate_grids_v( NuclideGridPoint ** nuclide_grids,
long n_isotopes, long n_gridpoints ) {
for( long i = 0; i < n_isotopes; i++ )
for( long j = 0; j < n_gridpoints; j++ )
{
nuclide_grids[i][j].energy = rn_v();
nuclide_grids[i][j].total_xs = rn_v();
nuclide_grids[i][j].elastic_xs = rn_v();
nuclide_grids[i][j].absorbtion_xs= rn_v();
nuclide_grids[i][j].fission_xs = rn_v();
nuclide_grids[i][j].nu_fission_xs= rn_v();
}
}
// Sorts the nuclide grids by energy (lowest -> highest)
void sort_nuclide_grids( NuclideGridPoint ** nuclide_grids, long n_isotopes,
long n_gridpoints )
{
int (*cmp) (const void *, const void *);
cmp = NGP_compare;
for( long i = 0; i < n_isotopes; i++ )
qsort( nuclide_grids[i], n_gridpoints, sizeof(NuclideGridPoint),
cmp );
// error debug check
/*
for( int i = 0; i < n_isotopes; i++ )
{
printf("NUCLIDE %d ==============================\n", i);
for( int j = 0; j < n_gridpoints; j++ )
printf("E%d = %lf\n", j, nuclide_grids[i][j].energy);
}
*/
}
// Allocates unionized energy grid, and assigns union of energy levels
// from nuclide grids to it.
GridPoint * generate_energy_grid( long n_isotopes, long n_gridpoints,
NuclideGridPoint ** nuclide_grids) {
int mype = 0;
#ifdef MPI
MPI_Comm_rank(MPI_COMM_WORLD, &mype);
#endif
if( mype == 0 ) printf("Generating Unionized Energy Grid...\n");
long n_unionized_grid_points = n_isotopes*n_gridpoints;
int (*cmp) (const void *, const void *);
cmp = NGP_compare;
GridPoint * energy_grid = (GridPoint *)malloc( n_unionized_grid_points
* sizeof( GridPoint ) );
if( mype == 0 ) printf("Copying and Sorting all nuclide grids...\n");
NuclideGridPoint ** n_grid_sorted = gpmatrix( n_isotopes, n_gridpoints );
memcpy( n_grid_sorted[0], nuclide_grids[0], n_isotopes*n_gridpoints*
sizeof( NuclideGridPoint ) );
qsort( &n_grid_sorted[0][0], n_unionized_grid_points,
sizeof(NuclideGridPoint), cmp);
if( mype == 0 ) printf("Assigning energies to unionized grid...\n");
for( long i = 0; i < n_unionized_grid_points; i++ )
energy_grid[i].energy = n_grid_sorted[0][i].energy;
gpmatrix_free(n_grid_sorted);
int * full = (int *) malloc( n_isotopes * n_unionized_grid_points
* sizeof(int) );
for( long i = 0; i < n_unionized_grid_points; i++ )
energy_grid[i].xs_ptrs = &full[n_isotopes * i];
// debug error checking
/*
for( int i = 0; i < n_unionized_grid_points; i++ )
printf("E%d = %lf\n", i, energy_grid[i].energy);
*/
return energy_grid;
}
// Searches each nuclide grid for the closest energy level and assigns
// pointer from unionized grid to the correct spot in the nuclide grid.
// This process is time consuming, as the number of binary searches
// required is: binary searches = n_gridpoints * n_isotopes^2
void set_grid_ptrs( GridPoint * energy_grid, NuclideGridPoint ** nuclide_grids,
long n_isotopes, long n_gridpoints )
{
int mype = 0;
#ifdef MPI
MPI_Comm_rank(MPI_COMM_WORLD, &mype);
#endif
if( mype == 0 ) printf("Assigning pointers to Unionized Energy Grid...\n");
#pragma omp parallel for default(none) \
shared( energy_grid, nuclide_grids, n_isotopes, n_gridpoints, mype )
for( long i = 0; i < n_isotopes * n_gridpoints ; i++ )
{
double quarry = energy_grid[i].energy;
if( INFO && mype == 0 && omp_get_thread_num() == 0 && i % 200 == 0 )
printf("\rAligning Unionized Grid...(%.0lf%% complete)",
100.0 * (double) i / (n_isotopes*n_gridpoints /
omp_get_num_threads()) );
for( long j = 0; j < n_isotopes; j++ )
{
// j is the nuclide i.d.
// log n binary search
energy_grid[i].xs_ptrs[j] =
binary_search( nuclide_grids[j], quarry, n_gridpoints);
}
}
if( mype == 0 ) printf("\n");
//test
/*
for( int i=0; i < n_isotopes * n_gridpoints; i++ )
for( int j = 0; j < n_isotopes; j++ )
printf("E = %.4lf\tNuclide %d->%p->%.4lf\n",
energy_grid[i].energy,
j,
energy_grid[i].xs_ptrs[j],
(energy_grid[i].xs_ptrs[j])->energy
);
*/
}
|
csr_matvec.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)
******************************************************************************/
/******************************************************************************
*
* Matvec functions for hypre_CSRMatrix class.
*
*****************************************************************************/
#include "../krylov/krylov.h"
#include "seq_mv.h"
#include <ftrace.h>
#include <sblas.h>
/*--------------------------------------------------------------------------
* hypre_CSRMatrixMatvec
*--------------------------------------------------------------------------*/
/* y[offset:end] = alpha*A[offset:end,:]*x + beta*b[offset:end] */
HYPRE_Int hypre_CSRMatrixMatvecOutOfPlaceHost(
HYPRE_Complex alpha, hypre_CSRMatrix *A, hypre_Vector *x,
HYPRE_Complex beta, hypre_Vector *b, hypre_Vector *y, HYPRE_Int offset) {
HYPRE_Complex *A_data = hypre_CSRMatrixData(A);
HYPRE_Int *A_i = hypre_CSRMatrixI(A) + offset;
HYPRE_Int *A_j = hypre_CSRMatrixJ(A);
HYPRE_Int num_rows = hypre_CSRMatrixNumRows(A) - offset;
HYPRE_Int num_cols = hypre_CSRMatrixNumCols(A);
/*HYPRE_Int num_nnz = hypre_CSRMatrixNumNonzeros(A);*/
HYPRE_Int *A_rownnz = hypre_CSRMatrixRownnz(A);
HYPRE_Int num_rownnz = hypre_CSRMatrixNumRownnz(A);
HYPRE_Complex *x_data = hypre_VectorData(x);
HYPRE_Complex *b_data = hypre_VectorData(b) + offset;
HYPRE_Complex *y_data = hypre_VectorData(y) + offset;
HYPRE_Int x_size = hypre_VectorSize(x);
HYPRE_Int b_size = hypre_VectorSize(b) - offset;
HYPRE_Int y_size = hypre_VectorSize(y) - offset;
HYPRE_Int num_vectors = hypre_VectorNumVectors(x);
HYPRE_Int idxstride_y = hypre_VectorIndexStride(y);
HYPRE_Int vecstride_y = hypre_VectorVectorStride(y);
/*HYPRE_Int idxstride_b = hypre_VectorIndexStride(b);
HYPRE_Int vecstride_b = hypre_VectorVectorStride(b);*/
HYPRE_Int idxstride_x = hypre_VectorIndexStride(x);
HYPRE_Int vecstride_x = hypre_VectorVectorStride(x);
HYPRE_Complex temp, tempx;
HYPRE_Int i, j, jj, m, ierr = 0;
HYPRE_Real xpar = 0.7;
hypre_Vector *x_tmp = NULL;
/*---------------------------------------------------------------------
* Check for size compatibility. Matvec returns ierr = 1 if
* length of X doesn't equal the number of columns of A,
* ierr = 2 if the length of Y doesn't equal the number of rows
* of A, and ierr = 3 if both are true.
*
* Because temporary vectors are often used in Matvec, none of
* these conditions terminates processing, and the ierr flag
* is informational only.
*--------------------------------------------------------------------*/
hypre_assert(num_vectors == hypre_VectorNumVectors(y));
hypre_assert(num_vectors == hypre_VectorNumVectors(b));
if (num_cols != x_size)
ierr = 1;
if (num_rows != y_size || num_rows != b_size)
ierr = 2;
if (num_cols != x_size && (num_rows != y_size || num_rows != b_size))
ierr = 3;
/*-----------------------------------------------------------------------
* Do (alpha == 0.0) computation - RDF: USE MACHINE EPS
*-----------------------------------------------------------------------*/
if (alpha == 0.0) {
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE
#endif
for (i = 0; i < num_rows * num_vectors; i++)
y_data[i] = beta * b_data[i];
#ifdef HYPRE_PROFILE
hypre_profile_times[HYPRE_TIMER_ID_MATVEC] +=
hypre_MPI_Wtime() - time_begin;
#endif
return ierr;
}
if (x == y) {
x_tmp = hypre_SeqVectorCloneDeep(x);
x_data = hypre_VectorData(x_tmp);
}
/*-----------------------------------------------------------------------
* y = (beta/alpha)*y
*-----------------------------------------------------------------------*/
temp = beta / alpha;
/* use rownnz pointer to do the A*x multiplication when num_rownnz is smaller
* than num_rows */
if (num_rownnz < xpar * (num_rows) || num_vectors > 1) {
/*-----------------------------------------------------------------------
* y = (beta/alpha)*y
*-----------------------------------------------------------------------*/
if (temp != 1.0) {
if (temp == 0.0) {
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE
#endif
for (i = 0; i < num_rows * num_vectors; i++)
y_data[i] = 0.0;
} else {
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE
#endif
for (i = 0; i < num_rows * num_vectors; i++)
y_data[i] = b_data[i] * temp;
}
} else {
for (i = 0; i < num_rows * num_vectors; i++)
y_data[i] = b_data[i];
}
/*-----------------------------------------------------------------
* y += A*x
*-----------------------------------------------------------------*/
if (num_rownnz < xpar * (num_rows)) {
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i, j, jj, m, tempx) HYPRE_SMP_SCHEDULE
#endif
for (i = 0; i < num_rownnz; i++) {
m = A_rownnz[i];
/*
* for (jj = A_i[m]; jj < A_i[m+1]; jj++)
* {
* j = A_j[jj];
* y_data[m] += A_data[jj] * x_data[j];
* } */
if (num_vectors == 1) {
tempx = 0;
for (jj = A_i[m]; jj < A_i[m + 1]; jj++)
tempx += A_data[jj] * x_data[A_j[jj]];
y_data[m] += tempx;
} else
for (j = 0; j < num_vectors; ++j) {
tempx = 0;
for (jj = A_i[m]; jj < A_i[m + 1]; jj++)
tempx +=
A_data[jj] * x_data[j * vecstride_x + A_j[jj] * idxstride_x];
y_data[j * vecstride_y + m * idxstride_y] += tempx;
}
}
} else // num_vectors > 1
{
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i, j, jj, tempx) HYPRE_SMP_SCHEDULE
#endif
for (i = 0; i < num_rows; i++) {
for (j = 0; j < num_vectors; ++j) {
tempx = 0;
for (jj = A_i[i]; jj < A_i[i + 1]; jj++) {
tempx +=
A_data[jj] * x_data[j * vecstride_x + A_j[jj] * idxstride_x];
}
y_data[j * vecstride_y + i * idxstride_y] += tempx;
}
}
}
/*-----------------------------------------------------------------
* y = alpha*y
*-----------------------------------------------------------------*/
if (alpha != 1.0) {
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE
#endif
for (i = 0; i < num_rows * num_vectors; i++)
y_data[i] *= alpha;
}
} else { // JSP: this is currently the only path optimized
#ifndef __ve__
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel private(i, jj, tempx)
#endif
{
HYPRE_Int iBegin = hypre_CSRMatrixGetLoadBalancedPartitionBegin(A);
HYPRE_Int iEnd = hypre_CSRMatrixGetLoadBalancedPartitionEnd(A);
hypre_assert(iBegin <= iEnd);
hypre_assert(iBegin >= 0 && iBegin <= num_rows);
hypre_assert(iEnd >= 0 && iEnd <= num_rows);
if (0 == temp) {
if (1 == alpha) // JSP: a common path
{
for (i = iBegin; i < iEnd; i++) {
tempx = 0.0;
for (jj = A_i[i]; jj < A_i[i + 1]; jj++) {
tempx += A_data[jj] * x_data[A_j[jj]];
}
y_data[i] = tempx;
}
} // y = A*x
else if (-1 == alpha) {
for (i = iBegin; i < iEnd; i++) {
tempx = 0.0;
for (jj = A_i[i]; jj < A_i[i + 1]; jj++) {
tempx -= A_data[jj] * x_data[A_j[jj]];
}
y_data[i] = tempx;
}
} // y = -A*x
else {
for (i = iBegin; i < iEnd; i++) {
tempx = 0.0;
for (jj = A_i[i]; jj < A_i[i + 1]; jj++) {
tempx += A_data[jj] * x_data[A_j[jj]];
}
y_data[i] = alpha * tempx;
}
} // y = alpha*A*x
} // temp == 0
else if (-1 == temp) // beta == -alpha
{
if (1 == alpha) // JSP: a common path
{
for (i = iBegin; i < iEnd; i++) {
tempx = -b_data[i];
for (jj = A_i[i]; jj < A_i[i + 1]; jj++) {
tempx += A_data[jj] * x_data[A_j[jj]];
}
y_data[i] = tempx;
}
} // y = A*x - y
else if (-1 == alpha) // JSP: a common path
{
for (i = iBegin; i < iEnd; i++) {
tempx = b_data[i];
for (jj = A_i[i]; jj < A_i[i + 1]; jj++) {
tempx -= A_data[jj] * x_data[A_j[jj]];
}
y_data[i] = tempx;
}
} // y = -A*x + y
else {
for (i = iBegin; i < iEnd; i++) {
tempx = -b_data[i];
for (jj = A_i[i]; jj < A_i[i + 1]; jj++) {
tempx += A_data[jj] * x_data[A_j[jj]];
}
y_data[i] = alpha * tempx;
}
} // y = alpha*(A*x - y)
} // temp == -1
else if (1 == temp) {
if (1 == alpha) // JSP: a common path
{
for (i = iBegin; i < iEnd; i++) {
tempx = b_data[i];
for (jj = A_i[i]; jj < A_i[i + 1]; jj++) {
tempx += A_data[jj] * x_data[A_j[jj]];
}
y_data[i] = tempx;
}
} // y = A*x + y
else if (-1 == alpha) {
for (i = iBegin; i < iEnd; i++) {
tempx = -b_data[i];
for (jj = A_i[i]; jj < A_i[i + 1]; jj++) {
tempx -= A_data[jj] * x_data[A_j[jj]];
}
y_data[i] = tempx;
}
} // y = -A*x - y
else {
for (i = iBegin; i < iEnd; i++) {
tempx = b_data[i];
for (jj = A_i[i]; jj < A_i[i + 1]; jj++) {
tempx += A_data[jj] * x_data[A_j[jj]];
}
y_data[i] = alpha * tempx;
}
} // y = alpha*(A*x + y)
} else {
if (1 == alpha) // JSP: a common path
{
for (i = iBegin; i < iEnd; i++) {
tempx = b_data[i] * temp;
for (jj = A_i[i]; jj < A_i[i + 1]; jj++) {
tempx += A_data[jj] * x_data[A_j[jj]];
}
y_data[i] = tempx;
}
} // y = A*x + temp*y
else if (-1 == alpha) {
for (i = iBegin; i < iEnd; i++) {
tempx = -b_data[i] * temp;
for (jj = A_i[i]; jj < A_i[i + 1]; jj++) {
tempx -= A_data[jj] * x_data[A_j[jj]];
}
y_data[i] = tempx;
}
} // y = -A*x - temp*y
else {
for (i = iBegin; i < iEnd; i++) {
tempx = b_data[i] * temp;
for (jj = A_i[i]; jj < A_i[i + 1]; jj++) {
tempx += A_data[jj] * x_data[A_j[jj]];
}
y_data[i] = alpha * tempx;
}
} // y = alpha*(A*x + temp*y)
} // temp != 0 && temp != -1 && temp != 1
} // omp parallel
#else
sblas_int_t mrow = (sblas_int_t)num_rows;
sblas_int_t ncol = (sblas_int_t)num_cols;
sblas_int_t ierr;
#ifdef _FTRACE
ftrace_region_begin("SBLAS_HYPRE");
#endif
if (!A->hnd) {
// HYPRE_Complex *A_data = hypre_CSRMatrixData(A);
sblas_int_t *iaptr = A_i;
sblas_int_t *iaind = A_j;
double *avals = A_data;
ierr = sblas_create_matrix_handle_from_csr_rd(
mrow, ncol, iaptr, iaind, avals, SBLAS_INDEXING_0, SBLAS_GENERAL,
&A->hnd); // handler
ierr = sblas_analyze_mv_rd(SBLAS_NON_TRANSPOSE, A->hnd);
// fprintf(stderr, "create !!\n");
}
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i, j) HYPRE_SMP_SCHEDULE
#endif
for (i = 0; i < num_rows; i++) {
y_data[i] = b_data[i];
}
ierr = sblas_execute_mv_rd(SBLAS_NON_TRANSPOSE, A->hnd, alpha, x_data,
alpha * temp, y_data);
#ifdef _FTRACE
ftrace_region_end("SBLAS_HYPRE");
#endif
#endif
}
if (x == y) {
hypre_SeqVectorDestroy(x_tmp);
}
return ierr;
}
HYPRE_Int hypre_CSRMatrixMatvecOutOfPlace(HYPRE_Complex alpha,
hypre_CSRMatrix *A, hypre_Vector *x,
HYPRE_Complex beta, hypre_Vector *b,
hypre_Vector *y, HYPRE_Int offset) {
#ifdef HYPRE_PROFILE
HYPRE_Real time_begin = hypre_MPI_Wtime();
#endif
HYPRE_Int ierr = 0;
#if defined(HYPRE_USING_CUDA) || defined(HYPRE_USING_DEVICE_OPENMP)
// HYPRE_ExecutionPolicy exec = hypre_GetExecPolicy1(
// hypre_ParCSRMatrixMemoryLocation(A) ); RL: TODO back to
// hypre_GetExecPolicy1 later
HYPRE_ExecutionPolicy exec = HYPRE_EXEC_DEVICE;
if (exec == HYPRE_EXEC_DEVICE) {
ierr = hypre_CSRMatrixMatvecDevice(0, alpha, A, x, beta, b, y, offset);
} else
#endif
{
ierr = hypre_CSRMatrixMatvecOutOfPlaceHost(alpha, A, x, beta, b, y, offset);
}
#ifdef HYPRE_PROFILE
hypre_profile_times[HYPRE_TIMER_ID_MATVEC] += hypre_MPI_Wtime() - time_begin;
#endif
return ierr;
}
HYPRE_Int hypre_CSRMatrixMatvec(HYPRE_Complex alpha, hypre_CSRMatrix *A,
hypre_Vector *x, HYPRE_Complex beta,
hypre_Vector *y) {
return hypre_CSRMatrixMatvecOutOfPlace(alpha, A, x, beta, y, y, 0);
}
/*--------------------------------------------------------------------------
* hypre_CSRMatrixMatvecT
*
* This version is using a different (more efficient) threading scheme
* Performs y <- alpha * A^T * x + beta * y
*
* From Van Henson's modification of hypre_CSRMatrixMatvec.
*--------------------------------------------------------------------------*/
HYPRE_Int hypre_CSRMatrixMatvecTHost(HYPRE_Complex alpha, hypre_CSRMatrix *A,
hypre_Vector *x, HYPRE_Complex beta,
hypre_Vector *y) {
HYPRE_Complex *A_data = hypre_CSRMatrixData(A);
HYPRE_Int *A_i = hypre_CSRMatrixI(A);
HYPRE_Int *A_j = hypre_CSRMatrixJ(A);
HYPRE_Int num_rows = hypre_CSRMatrixNumRows(A);
HYPRE_Int num_cols = hypre_CSRMatrixNumCols(A);
HYPRE_Complex *x_data = hypre_VectorData(x);
HYPRE_Complex *y_data = hypre_VectorData(y);
HYPRE_Int x_size = hypre_VectorSize(x);
HYPRE_Int y_size = hypre_VectorSize(y);
HYPRE_Int num_vectors = hypre_VectorNumVectors(x);
HYPRE_Int idxstride_y = hypre_VectorIndexStride(y);
HYPRE_Int vecstride_y = hypre_VectorVectorStride(y);
HYPRE_Int idxstride_x = hypre_VectorIndexStride(x);
HYPRE_Int vecstride_x = hypre_VectorVectorStride(x);
HYPRE_Complex temp;
HYPRE_Complex *y_data_expand;
HYPRE_Int my_thread_num = 0, offset = 0;
HYPRE_Int i, j, jv, jj;
HYPRE_Int num_threads;
HYPRE_Int ierr = 0;
hypre_Vector *x_tmp = NULL;
/*---------------------------------------------------------------------
* Check for size compatibility. MatvecT returns ierr = 1 if
* length of X doesn't equal the number of rows of A,
* ierr = 2 if the length of Y doesn't equal the number of
* columns of A, and ierr = 3 if both are true.
*
* Because temporary vectors are often used in MatvecT, none of
* these conditions terminates processing, and the ierr flag
* is informational only.
*--------------------------------------------------------------------*/
hypre_assert(num_vectors == hypre_VectorNumVectors(y));
if (num_rows != x_size)
ierr = 1;
if (num_cols != y_size)
ierr = 2;
if (num_rows != x_size && num_cols != y_size)
ierr = 3;
/*-----------------------------------------------------------------------
* Do (alpha == 0.0) computation - RDF: USE MACHINE EPS
*-----------------------------------------------------------------------*/
if (alpha == 0.0) {
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE
#endif
for (i = 0; i < num_cols * num_vectors; i++)
y_data[i] *= beta;
return ierr;
}
if (x == y) {
x_tmp = hypre_SeqVectorCloneDeep(x);
x_data = hypre_VectorData(x_tmp);
}
/*-----------------------------------------------------------------------
* y = (beta/alpha)*y
*-----------------------------------------------------------------------*/
temp = beta / alpha;
HYPRE_Complex mult = 0;
if (temp != 1.0) {
if (temp == 0.0) {
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE
#endif
for (i = 0; i < num_cols * num_vectors; i++)
y_data[i] = 0.0;
} else {
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE
#endif
for (i = 0; i < num_cols * num_vectors; i++)
y_data[i] *= temp;
mult = 1.0;
}
}
/*-----------------------------------------------------------------
* y += A^T*x
*-----------------------------------------------------------------*/
num_threads = hypre_NumThreads();
#ifdef __ve__
if (num_threads >= 1) {
#else
if (num_threads > 1) {
#endif
#ifndef __ve__
y_data_expand =
hypre_CTAlloc(HYPRE_Complex, num_threads * y_size, HYPRE_MEMORY_HOST);
#endif
if (num_vectors == 1) {
#ifndef __ve__
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel private(i, jj, j, my_thread_num, offset)
#endif
{
my_thread_num = hypre_GetThreadNum();
offset = y_size * my_thread_num;
#ifdef HYPRE_USING_OPENMP
#pragma omp for HYPRE_SMP_SCHEDULE
#endif
for (i = 0; i < num_rows; i++) {
for (jj = A_i[i]; jj < A_i[i + 1]; jj++) {
j = A_j[jj];
y_data_expand[offset + j] += A_data[jj] * x_data[i];
}
}
/* implied barrier (for threads)*/
#ifdef HYPRE_USING_OPENMP
#pragma omp for HYPRE_SMP_SCHEDULE
#endif
for (i = 0; i < y_size; i++) {
for (j = 0; j < num_threads; j++) {
y_data[i] += y_data_expand[j * y_size + i];
}
}
} /* end parallel threaded region */
#else
sblas_int_t s_ierr;
if (!A->hnd) {
sblas_int_t mrow = (sblas_int_t)num_rows;
sblas_int_t ncol = (sblas_int_t)num_cols;
sblas_int_t *iaptr = A_i;
sblas_int_t *iaind = A_j;
double *avals = A_data;
s_ierr = sblas_create_matrix_handle_from_csr_rd(
mrow, ncol, iaptr, iaind, avals, SBLAS_INDEXING_0, SBLAS_GENERAL,
&A->hnd); // handler
s_ierr = sblas_analyze_mv_rd(SBLAS_TRANSPOSE, A->hnd);
// fprintf(stderr, "create !!\n");
}
s_ierr = sblas_execute_mv_rd(SBLAS_TRANSPOSE, A->hnd, 1.0, x_data, mult,
y_data);
#endif
} else {
/* multiple vector case is not threaded */
for (i = 0; i < num_rows; i++) {
for (jv = 0; jv < num_vectors; ++jv) {
for (jj = A_i[i]; jj < A_i[i + 1]; jj++) {
j = A_j[jj];
y_data[j * idxstride_y + jv * vecstride_y] +=
A_data[jj] * x_data[i * idxstride_x + jv * vecstride_x];
}
}
}
}
#ifndef __ve__
hypre_TFree(y_data_expand, HYPRE_MEMORY_HOST);
#endif
} else {
for (i = 0; i < num_rows; i++) {
if (num_vectors == 1) {
for (jj = A_i[i]; jj < A_i[i + 1]; jj++) {
j = A_j[jj];
y_data[j] += A_data[jj] * x_data[i];
}
} else {
for (jv = 0; jv < num_vectors; ++jv) {
for (jj = A_i[i]; jj < A_i[i + 1]; jj++) {
j = A_j[jj];
y_data[j * idxstride_y + jv * vecstride_y] +=
A_data[jj] * x_data[i * idxstride_x + jv * vecstride_x];
}
}
}
}
}
/*-----------------------------------------------------------------
* y = alpha*y
*-----------------------------------------------------------------*/
if (alpha != 1.0) {
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE
#endif
for (i = 0; i < num_cols * num_vectors; i++) {
y_data[i] *= alpha;
}
}
if (x == y) {
hypre_SeqVectorDestroy(x_tmp);
}
return ierr;
}
HYPRE_Int hypre_CSRMatrixMatvecT(HYPRE_Complex alpha, hypre_CSRMatrix *A,
hypre_Vector *x, HYPRE_Complex beta,
hypre_Vector *y) {
#ifdef HYPRE_PROFILE
HYPRE_Real time_begin = hypre_MPI_Wtime();
#endif
HYPRE_Int ierr = 0;
#if defined(HYPRE_USING_CUDA) || defined(HYPRE_USING_DEVICE_OPENMP)
// HYPRE_ExecutionPolicy exec = hypre_GetExecPolicy1(
// hypre_ParCSRMatrixMemoryLocation(A) ); RL: TODO back to
// hypre_GetExecPolicy1 later
HYPRE_ExecutionPolicy exec = HYPRE_EXEC_DEVICE;
if (exec == HYPRE_EXEC_DEVICE) {
ierr = hypre_CSRMatrixMatvecDevice(1, alpha, A, x, beta, y, y, 0);
} else
#endif
{
ierr = hypre_CSRMatrixMatvecTHost(alpha, A, x, beta, y);
}
#ifdef HYPRE_PROFILE
hypre_profile_times[HYPRE_TIMER_ID_MATVEC] += hypre_MPI_Wtime() - time_begin;
#endif
return ierr;
}
/*--------------------------------------------------------------------------
* hypre_CSRMatrixMatvec_FF
*--------------------------------------------------------------------------*/
HYPRE_Int hypre_CSRMatrixMatvec_FF(HYPRE_Complex alpha, hypre_CSRMatrix *A,
hypre_Vector *x, HYPRE_Complex beta,
hypre_Vector *y, HYPRE_Int *CF_marker_x,
HYPRE_Int *CF_marker_y, HYPRE_Int fpt) {
HYPRE_Complex *A_data = hypre_CSRMatrixData(A);
HYPRE_Int *A_i = hypre_CSRMatrixI(A);
HYPRE_Int *A_j = hypre_CSRMatrixJ(A);
HYPRE_Int num_rows = hypre_CSRMatrixNumRows(A);
HYPRE_Int num_cols = hypre_CSRMatrixNumCols(A);
HYPRE_Complex *x_data = hypre_VectorData(x);
HYPRE_Complex *y_data = hypre_VectorData(y);
HYPRE_Int x_size = hypre_VectorSize(x);
HYPRE_Int y_size = hypre_VectorSize(y);
HYPRE_Complex temp;
HYPRE_Int i, jj;
HYPRE_Int ierr = 0;
/*---------------------------------------------------------------------
* Check for size compatibility. Matvec returns ierr = 1 if
* length of X doesn't equal the number of columns of A,
* ierr = 2 if the length of Y doesn't equal the number of rows
* of A, and ierr = 3 if both are true.
*
* Because temporary vectors are often used in Matvec, none of
* these conditions terminates processing, and the ierr flag
* is informational only.
*--------------------------------------------------------------------*/
if (num_cols != x_size)
ierr = 1;
if (num_rows != y_size)
ierr = 2;
if (num_cols != x_size && num_rows != y_size)
ierr = 3;
/*-----------------------------------------------------------------------
* Do (alpha == 0.0) computation - RDF: USE MACHINE EPS
*-----------------------------------------------------------------------*/
if (alpha == 0.0) {
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE
#endif
for (i = 0; i < num_rows; i++)
if (CF_marker_x[i] == fpt)
y_data[i] *= beta;
return ierr;
}
/*-----------------------------------------------------------------------
* y = (beta/alpha)*y
*-----------------------------------------------------------------------*/
temp = beta / alpha;
if (temp != 1.0) {
if (temp == 0.0) {
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE
#endif
for (i = 0; i < num_rows; i++)
if (CF_marker_x[i] == fpt)
y_data[i] = 0.0;
} else {
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE
#endif
for (i = 0; i < num_rows; i++)
if (CF_marker_x[i] == fpt)
y_data[i] *= temp;
}
}
/*-----------------------------------------------------------------
* y += A*x
*-----------------------------------------------------------------*/
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i, jj) HYPRE_SMP_SCHEDULE
#endif
for (i = 0; i < num_rows; i++) {
if (CF_marker_x[i] == fpt) {
temp = y_data[i];
for (jj = A_i[i]; jj < A_i[i + 1]; jj++)
if (CF_marker_y[A_j[jj]] == fpt)
temp += A_data[jj] * x_data[A_j[jj]];
y_data[i] = temp;
}
}
/*-----------------------------------------------------------------
* y = alpha*y
*-----------------------------------------------------------------*/
if (alpha != 1.0) {
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE
#endif
for (i = 0; i < num_rows; i++)
if (CF_marker_x[i] == fpt)
y_data[i] *= alpha;
}
return ierr;
}
|
GB_unaryop__lnot_uint32_fp64.c | //------------------------------------------------------------------------------
// GB_unaryop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved.
// http://suitesparse.com See GraphBLAS/Doc/License.txt for license.
//------------------------------------------------------------------------------
// If this file is in the Generated/ folder, do not edit it (auto-generated).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_iterator.h"
#include "GB_unaryop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB_unop__lnot_uint32_fp64
// op(A') function: GB_tran__lnot_uint32_fp64
// C type: uint32_t
// A type: double
// cast: uint32_t cij ; GB_CAST_UNSIGNED(cij,aij,32)
// unaryop: cij = !(aij != 0)
#define GB_ATYPE \
double
#define GB_CTYPE \
uint32_t
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
double aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = !(x != 0) ;
// casting
#define GB_CASTING(z, x) \
uint32_t z ; GB_CAST_UNSIGNED(z,x,32) ;
// cij = op (cast (aij))
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
GB_GETA (aij, Ax, pA) ; \
/* Cx [pC] = op (cast (aij)) */ \
GB_CASTING (x, aij) ; \
GB_OP (GB_CX (pC), x) ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_LNOT || GxB_NO_UINT32 || GxB_NO_FP64)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop__lnot_uint32_fp64
(
uint32_t *restrict Cx,
const double *restrict Ax,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (int64_t p = 0 ; p < anz ; p++)
{
GB_CAST_OP (p, p) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_tran__lnot_uint32_fp64
(
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
|
ejercicio8.c | /*Para compilar usar (-lrt: real time library): gcc -O2 Sumavectores.c -o SumaVectores -lrt
Para ejecutar use: SumaVectores longitud
*/
#include <stdlib.h>
#include <stdio.h>
#include <omp.h>
#include <time.h>
#define PRINTF_ALL
//Sólo puede estar definida una de las tres constantes VECTOR_ (sólo uno de los ...
//tres defines siguientes puede estar descomentado):
//#define VECTOR_LOCAL
// descomentar para que los vectores sean variables ...
// locales (si se supera el tamaño de la pila se ...
// generará el error "Violación de Segmento")
//#define VECTOR_GLOBAL // descomentar para que los vectores sean variables ...
// globales (su longitud no estará limitada por el ...
// tamaño de la pila del programa)
#define VECTOR_DYNAMIC //descomentar para que los vectores sean variables ...
//dinámicas (memoria reautilizable durante la ejecución)
#ifdef VECTOR_GLOBAL
#define MAX 33554432
double v1[MAX], v2[MAX], v3[MAX];
#endif
int main(int argc, char** argv){
int i;
struct timespec cgt1,cgt2;
double ncgt; //para tiempo de ejecución
if(argc<2){
printf("Faltan nº componentes del vector\n");
exit(-1);
}
unsigned int N=atoi(argv[1]);
#ifdef VECTOR_LOCAL
double v1[N], v2[N], v3[N];
#endif
#ifdef VECTOR_GLOBAL
if(N>MAX) N=MAX;
#endif
#ifdef VECTOR_DYNAMIC
double *v1, *v2, *v3;
v1= (double*) malloc(N*sizeof(double));
v2= (double*) malloc(N*sizeof(double));
v3= (double*) malloc(N*sizeof(double));
if((v1==NULL) || (v2==NULL) || (v3==NULL)){
printf("Error en la reserva de espacio para los vectores\n");
exit(-2);
}
#endif
//Inicializar vectores
#pragma omp parallel private (i)
{
for(i=0;i<N;i++)
{
#pragma omp sections //Por un lado inicializamos el vector
{
#pragma omp section
{
v1[i]= N*0.1+i*0.1; v2[i]=N*0.1-i*0.1; //los valores dependen de N
printf("Inicialización: La hebra %d ejecuta iteración %d\n",omp_get_thread_num(),i);
}
}
}
}
double a= omp_get_wtime();
//Calcular suma de vectores
#pragma omp parallel private (i)
{
for(i=0;i<N;i++){
#pragma omp sections //Por otro calculamos la suma
{
#pragma omp section
{
v3[i]=v1[i] + v2[i];
printf("Suma: La hebra %d ejecuta iteración %d\n",omp_get_thread_num(),i);
}
}
ncgt=(double) (cgt2.tv_sec-cgt1.tv_sec)+ (double) ((cgt2.tv_nsec-cgt1.tv_nsec)/(1.e+9));
}
}
//Imprimir resultado de la suma y el tiempo de ejecución
#ifdef PRINTF_ALL
printf("Tiempo(seg.): %11.9f\t / Tamaño Vectores:%u\n",omp_get_wtime()/*ncgt*/,N);
for(i=0;i<N;i++){
printf("thread %d ejecuta la iteración %d del bucle\n",omp_get_thread_num(),i);
printf("Elapsed time: %11.9f\t\n",omp_get_wtime()-a);
printf("/V1[%d]+V2[%d](%8.6f+%8.6f=%8.6f)/\n", i,i,i,v1[i],v2[i],v3[i]);
}
#else
printf("Tiempo: %11.9f\t / Tamaño Vectores:%u\n",
ncgt,N,v1[0],v2[0],v3[0],N-1,N-1,N-1,v1[N-1],v2[N-1],v3[N-1]);
#endif
#ifdef VECTOR_DYNAMIC
free(v1); //libera el espacio reservado para v1
free(v2); //libera el espacio reservado para v2
free(v3); //libera el espacio reservado para v3
#endif
return 0;
} |
GB_unop__identity_fp64_int16.c | //------------------------------------------------------------------------------
// GB_unop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved.
// http://suitesparse.com See GraphBLAS/Doc/License.txt for license.
//------------------------------------------------------------------------------
// If this file is in the Generated/ folder, do not edit it (auto-generated).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_unop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB_unop_apply__identity_fp64_int16
// op(A') function: GB_unop_tran__identity_fp64_int16
// C type: double
// A type: int16_t
// cast: double cij = (double) aij
// unaryop: cij = aij
#define GB_ATYPE \
int16_t
#define GB_CTYPE \
double
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
int16_t aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = x ;
// casting
#define GB_CAST(z, aij) \
double z = (double) aij ;
// cij = op (aij)
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
int16_t aij = Ax [pA] ; \
/* Cx [pC] = op (cast (aij)) */ \
double z = (double) aij ; \
Cx [pC] = z ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_IDENTITY || GxB_NO_FP64 || GxB_NO_INT16)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop_apply__identity_fp64_int16
(
double *Cx, // Cx and Ax may be aliased
const int16_t *Ax,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
int16_t aij = Ax [p] ;
double z = (double) aij ;
Cx [p] = z ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop_tran__identity_fp64_int16
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t *GB_RESTRICT *Rowcounts,
GBI_single_iterator Iter,
const int64_t *GB_RESTRICT A_slice,
int naslice
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#define GB_PHASE_2_OF_2
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
6755.c | /* POLYBENCH/GPU-OPENMP
*
* This file is a part of the Polybench/GPU-OpenMP suite
*
* Contact:
* William Killian <killian@udel.edu>
*
* Copyright 2013, The University of Delaware
*/
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <math.h>
/* Include polybench common header. */
#include <polybench.h>
/* Include benchmark-specific header. */
/* Default data type is double, default size is 4000. */
#include "atax.h"
/* Array initialization. */
static
void init_array (int nx, int ny,
DATA_TYPE POLYBENCH_2D(A,NX,NY,nx,ny),
DATA_TYPE POLYBENCH_1D(x,NY,ny))
{
int i, j;
for (i = 0; i < ny; i++)
x[i] = i * M_PI;
for (i = 0; i < nx; i++)
for (j = 0; j < ny; j++)
A[i][j] = ((DATA_TYPE) i*(j+1)) / nx;
}
/* DCE code. Must scan the entire live-out data.
Can be used also to check the correctness of the output. */
static
void print_array(int nx,
DATA_TYPE POLYBENCH_1D(y,NX,nx))
{
int i;
for (i = 0; i < nx; i++) {
fprintf (stderr, DATA_PRINTF_MODIFIER, y[i]);
if (i % 20 == 0) fprintf (stderr, "\n");
}
fprintf (stderr, "\n");
}
/* Main computational kernel. The whole function will be timed,
including the call and return. */
static
void kernel_atax(int nx, int ny,
DATA_TYPE POLYBENCH_2D(A,NX,NY,nx,ny),
DATA_TYPE POLYBENCH_1D(x,NY,ny),
DATA_TYPE POLYBENCH_1D(y,NY,ny),
DATA_TYPE POLYBENCH_1D(tmp,NX,nx))
{
int i, j;
#pragma scop
{
#pragma omp parallel for simd schedule(static, 2) num_threads(2)
for (i = 0; i < _PB_NY; i++)
{
y[i] = 0;
}
#pragma omp parallel for simd schedule(static, 2) num_threads(2)
for (i = 0; i < _PB_NX; i++)
{
tmp[i] = 0;
for (j = 0; j < _PB_NY; j++)
tmp[i] = tmp[i] + A[i][j] * x[j];
for (j = 0; j < _PB_NY; j++)
y[j] = y[j] + A[i][j] * tmp[i];
}
}
#pragma endscop
}
int main(int argc, char** argv)
{
/* Retrieve problem size. */
int nx = NX;
int ny = NY;
/* Variable declaration/allocation. */
POLYBENCH_2D_ARRAY_DECL(A, DATA_TYPE, NX, NY, nx, ny);
POLYBENCH_1D_ARRAY_DECL(x, DATA_TYPE, NY, ny);
POLYBENCH_1D_ARRAY_DECL(y, DATA_TYPE, NY, ny);
POLYBENCH_1D_ARRAY_DECL(tmp, DATA_TYPE, NX, nx);
/* Initialize array(s). */
init_array (nx, ny, POLYBENCH_ARRAY(A), POLYBENCH_ARRAY(x));
/* Start timer. */
polybench_start_instruments;
/* Run kernel. */
kernel_atax (nx, ny,
POLYBENCH_ARRAY(A),
POLYBENCH_ARRAY(x),
POLYBENCH_ARRAY(y),
POLYBENCH_ARRAY(tmp));
/* Stop and print timer. */
polybench_stop_instruments;
polybench_print_instruments;
/* Prevent dead-code elimination. All live-out data must be printed
by the function call in argument. */
polybench_prevent_dce(print_array(nx, POLYBENCH_ARRAY(y)));
/* Be clean. */
POLYBENCH_FREE_ARRAY(A);
POLYBENCH_FREE_ARRAY(x);
POLYBENCH_FREE_ARRAY(y);
POLYBENCH_FREE_ARRAY(tmp);
return 0;
}
|
par_csr_matvec.c | /*BHEADER**********************************************************************
* Copyright (c) 2017, Lawrence Livermore National Security, LLC.
* Produced at the Lawrence Livermore National Laboratory.
* Written by Ulrike Yang (yang11@llnl.gov) et al. CODE-LLNL-738-322.
* This file is part of AMG. See files README and COPYRIGHT for details.
*
* AMG 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.
*
* This software is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the
* GNU General Public License for more details.
*
***********************************************************************EHEADER*/
/******************************************************************************
*
* Matvec functions for hypre_CSRMatrix class.
*
*****************************************************************************/
#include "_hypre_parcsr_mv.h"
#include <assert.h>
/*--------------------------------------------------------------------------
* hypre_ParCSRMatrixMatvec
*--------------------------------------------------------------------------*/
// y = alpha*A*x + beta*b
HYPRE_Int
hypre_ParCSRMatrixMatvecOutOfPlace( HYPRE_Complex alpha,
hypre_ParCSRMatrix *A,
hypre_ParVector *x,
HYPRE_Complex beta,
hypre_ParVector *b,
hypre_ParVector *y )
{
hypre_ParCSRCommHandle **comm_handle;
hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(A);
hypre_CSRMatrix *diag = hypre_ParCSRMatrixDiag(A);
hypre_CSRMatrix *offd = hypre_ParCSRMatrixOffd(A);
hypre_Vector *x_local = hypre_ParVectorLocalVector(x);
hypre_Vector *b_local = hypre_ParVectorLocalVector(b);
hypre_Vector *y_local = hypre_ParVectorLocalVector(y);
HYPRE_Int num_rows = hypre_ParCSRMatrixGlobalNumRows(A);
HYPRE_Int num_cols = hypre_ParCSRMatrixGlobalNumCols(A);
hypre_Vector *x_tmp;
HYPRE_Int x_size = hypre_ParVectorGlobalSize(x);
HYPRE_Int b_size = hypre_ParVectorGlobalSize(b);
HYPRE_Int y_size = hypre_ParVectorGlobalSize(y);
HYPRE_Int num_vectors = hypre_VectorNumVectors(x_local);
HYPRE_Int num_cols_offd = hypre_CSRMatrixNumCols(offd);
HYPRE_Int ierr = 0;
HYPRE_Int num_sends, i, j, jv, index, start;
HYPRE_Int vecstride = hypre_VectorVectorStride( x_local );
HYPRE_Int idxstride = hypre_VectorIndexStride( x_local );
HYPRE_Complex *x_tmp_data, **x_buf_data;
HYPRE_Complex *x_local_data = hypre_VectorData(x_local);
/*---------------------------------------------------------------------
* Check for size compatibility. ParMatvec returns ierr = 11 if
* length of X doesn't equal the number of columns of A,
* ierr = 12 if the length of Y doesn't equal the number of rows
* of A, and ierr = 13 if both are true.
*
* Because temporary vectors are often used in ParMatvec, none of
* these conditions terminates processing, and the ierr flag
* is informational only.
*--------------------------------------------------------------------*/
hypre_assert( idxstride>0 );
if (num_cols != x_size)
ierr = 11;
if (num_rows != y_size || num_rows != b_size)
ierr = 12;
if (num_cols != x_size && (num_rows != y_size || num_rows != b_size))
ierr = 13;
hypre_assert( hypre_VectorNumVectors(b_local)==num_vectors );
hypre_assert( hypre_VectorNumVectors(y_local)==num_vectors );
if ( num_vectors==1 )
x_tmp = hypre_SeqVectorCreate( num_cols_offd );
else
{
hypre_assert( num_vectors>1 );
x_tmp = hypre_SeqMultiVectorCreate( num_cols_offd, num_vectors );
}
/*---------------------------------------------------------------------
* 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);
}
#ifdef HYPRE_PROFILE
hypre_profile_times[HYPRE_TIMER_ID_PACK_UNPACK] -= hypre_MPI_Wtime();
#endif
HYPRE_Int use_persistent_comm = 0;
#ifdef HYPRE_USING_PERSISTENT_COMM
use_persistent_comm = num_vectors == 1;
// JSP TODO: we can use persistent communication for multi-vectors,
// but then we need different communication handles for different
// num_vectors.
hypre_ParCSRPersistentCommHandle *persistent_comm_handle;
#endif
if ( use_persistent_comm )
{
#ifdef HYPRE_USING_PERSISTENT_COMM
persistent_comm_handle = hypre_ParCSRCommPkgGetPersistentCommHandle(1, comm_pkg);
HYPRE_Int num_recvs = hypre_ParCSRCommPkgNumRecvs(comm_pkg);
hypre_assert(num_cols_offd == hypre_ParCSRCommPkgRecvVecStart(comm_pkg, num_recvs));
hypre_VectorData(x_tmp) = (HYPRE_Complex *)persistent_comm_handle->recv_data;
hypre_SeqVectorSetDataOwner(x_tmp, 0);
#endif
}
else
{
comm_handle = hypre_CTAlloc(hypre_ParCSRCommHandle*,num_vectors);
}
hypre_SeqVectorInitialize(x_tmp);
x_tmp_data = hypre_VectorData(x_tmp);
num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg);
if (!use_persistent_comm)
{
x_buf_data = hypre_CTAlloc( HYPRE_Complex*, num_vectors );
for ( jv=0; jv<num_vectors; ++jv )
x_buf_data[jv] = hypre_CTAlloc(HYPRE_Complex, hypre_ParCSRCommPkgSendMapStart
(comm_pkg, num_sends));
}
if ( num_vectors==1 )
{
HYPRE_Int begin = hypre_ParCSRCommPkgSendMapStart(comm_pkg, 0);
HYPRE_Int end = hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends);
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for HYPRE_SMP_SCHEDULE
#endif
for (i = begin; i < end; i++)
{
#ifdef HYPRE_USING_PERSISTENT_COMM
((HYPRE_Complex *)persistent_comm_handle->send_data)[i - begin]
#else
x_buf_data[0][i - begin]
#endif
= x_local_data[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,i)];
}
}
else
for ( jv=0; jv<num_vectors; ++jv )
{
index = 0;
for (i = 0; i < num_sends; i++)
{
start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i);
for (j = start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i+1); j++)
x_buf_data[jv][index++]
= x_local_data[
jv*vecstride +
idxstride*hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j) ];
}
}
hypre_assert( idxstride==1 );
/* ... The assert is because the following loop only works for 'column'
storage of a multivector. This needs to be fixed to work more generally,
at least for 'row' storage. This in turn, means either change CommPkg so
num_sends is no.zones*no.vectors (not no.zones) or, less dangerously, put
a stride in the logic of CommHandleCreate (stride either from a new arg or
a new variable inside CommPkg). Or put the num_vector iteration inside
CommHandleCreate (perhaps a new multivector variant of it).
*/
#ifdef HYPRE_PROFILE
hypre_profile_times[HYPRE_TIMER_ID_PACK_UNPACK] += hypre_MPI_Wtime();
hypre_profile_times[HYPRE_TIMER_ID_HALO_EXCHANGE] -= hypre_MPI_Wtime();
#endif
if (use_persistent_comm)
{
#ifdef HYPRE_USING_PERSISTENT_COMM
hypre_ParCSRPersistentCommHandleStart(persistent_comm_handle);
#endif
}
else
{
for ( jv=0; jv<num_vectors; ++jv )
{
comm_handle[jv] = hypre_ParCSRCommHandleCreate
( 1, comm_pkg, x_buf_data[jv], &(x_tmp_data[jv*num_cols_offd]) );
}
}
#ifdef HYPRE_PROFILE
hypre_profile_times[HYPRE_TIMER_ID_HALO_EXCHANGE] += hypre_MPI_Wtime();
#endif
hypre_CSRMatrixMatvecOutOfPlace( alpha, diag, x_local, beta, b_local, y_local, 0);
#ifdef HYPRE_PROFILE
hypre_profile_times[HYPRE_TIMER_ID_HALO_EXCHANGE] -= hypre_MPI_Wtime();
#endif
if (use_persistent_comm)
{
#ifdef HYPRE_USING_PERSISTENT_COMM
hypre_ParCSRPersistentCommHandleWait(persistent_comm_handle);
#endif
}
else
{
for ( jv=0; jv<num_vectors; ++jv )
{
hypre_ParCSRCommHandleDestroy(comm_handle[jv]);
comm_handle[jv] = NULL;
}
hypre_TFree(comm_handle);
}
#ifdef HYPRE_PROFILE
hypre_profile_times[HYPRE_TIMER_ID_HALO_EXCHANGE] += hypre_MPI_Wtime();
#endif
if (num_cols_offd) hypre_CSRMatrixMatvec( alpha, offd, x_tmp, 1.0, y_local);
#ifdef HYPRE_PROFILE
hypre_profile_times[HYPRE_TIMER_ID_PACK_UNPACK] -= hypre_MPI_Wtime();
#endif
hypre_SeqVectorDestroy(x_tmp);
x_tmp = NULL;
if (!use_persistent_comm)
{
for ( jv=0; jv<num_vectors; ++jv ) hypre_TFree(x_buf_data[jv]);
hypre_TFree(x_buf_data);
}
#ifdef HYPRE_PROFILE
hypre_profile_times[HYPRE_TIMER_ID_PACK_UNPACK] += hypre_MPI_Wtime();
#endif
return ierr;
}
HYPRE_Int
hypre_ParCSRMatrixMatvec( HYPRE_Complex alpha,
hypre_ParCSRMatrix *A,
hypre_ParVector *x,
HYPRE_Complex beta,
hypre_ParVector *y )
{
return hypre_ParCSRMatrixMatvecOutOfPlace(alpha, A, x, beta, y, y);
}
/*--------------------------------------------------------------------------
* hypre_ParCSRMatrixMatvecT
*
* Performs y <- alpha * A^T * x + beta * y
*
*--------------------------------------------------------------------------*/
HYPRE_Int
hypre_ParCSRMatrixMatvecT( HYPRE_Complex alpha,
hypre_ParCSRMatrix *A,
hypre_ParVector *x,
HYPRE_Complex beta,
hypre_ParVector *y )
{
hypre_ParCSRCommHandle **comm_handle;
hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(A);
hypre_CSRMatrix *diag = hypre_ParCSRMatrixDiag(A);
hypre_CSRMatrix *offd = hypre_ParCSRMatrixOffd(A);
hypre_Vector *x_local = hypre_ParVectorLocalVector(x);
hypre_Vector *y_local = hypre_ParVectorLocalVector(y);
hypre_Vector *y_tmp;
HYPRE_Int vecstride = hypre_VectorVectorStride( y_local );
HYPRE_Int idxstride = hypre_VectorIndexStride( y_local );
HYPRE_Complex *y_tmp_data, **y_buf_data;
HYPRE_Complex *y_local_data = hypre_VectorData(y_local);
HYPRE_Int num_rows = hypre_ParCSRMatrixGlobalNumRows(A);
HYPRE_Int num_cols = hypre_ParCSRMatrixGlobalNumCols(A);
HYPRE_Int num_cols_offd = hypre_CSRMatrixNumCols(offd);
HYPRE_Int x_size = hypre_ParVectorGlobalSize(x);
HYPRE_Int y_size = hypre_ParVectorGlobalSize(y);
HYPRE_Int num_vectors = hypre_VectorNumVectors(y_local);
HYPRE_Int i, j, jv, index, start, num_sends;
HYPRE_Int ierr = 0;
/*---------------------------------------------------------------------
* Check for size compatibility. MatvecT returns ierr = 1 if
* length of X doesn't equal the number of rows of A,
* ierr = 2 if the length of Y doesn't equal the number of
* columns of A, and ierr = 3 if both are true.
*
* Because temporary vectors are often used in MatvecT, none of
* these conditions terminates processing, and the ierr flag
* is informational only.
*--------------------------------------------------------------------*/
if (num_rows != x_size)
ierr = 1;
if (num_cols != y_size)
ierr = 2;
if (num_rows != x_size && num_cols != y_size)
ierr = 3;
/*-----------------------------------------------------------------------
*-----------------------------------------------------------------------*/
if ( num_vectors==1 )
{
y_tmp = hypre_SeqVectorCreate(num_cols_offd);
}
else
{
y_tmp = hypre_SeqMultiVectorCreate(num_cols_offd,num_vectors);
}
/*---------------------------------------------------------------------
* 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);
}
#ifdef HYPRE_PROFILE
hypre_profile_times[HYPRE_TIMER_ID_PACK_UNPACK] -= hypre_MPI_Wtime();
#endif
HYPRE_Int use_persistent_comm = 0;
#ifdef HYPRE_USING_PERSISTENT_COMM
use_persistent_comm = num_vectors == 1;
// JSP TODO: we can use persistent communication for multi-vectors,
// but then we need different communication handles for different
// num_vectors.
hypre_ParCSRPersistentCommHandle *persistent_comm_handle;
#endif
if (use_persistent_comm)
{
#ifdef HYPRE_USING_PERSISTENT_COMM
// JSP TODO: we should be also able to use persistent communication for multiple vectors
persistent_comm_handle = hypre_ParCSRCommPkgGetPersistentCommHandle(2, comm_pkg);
HYPRE_Int num_recvs = hypre_ParCSRCommPkgNumRecvs(comm_pkg);
hypre_assert(num_cols_offd == hypre_ParCSRCommPkgRecvVecStart(comm_pkg, num_recvs));
hypre_VectorData(y_tmp) = (HYPRE_Complex *)persistent_comm_handle->send_data;
hypre_SeqVectorSetDataOwner(y_tmp, 0);
#endif
}
else
{
comm_handle = hypre_CTAlloc(hypre_ParCSRCommHandle*,num_vectors);
}
hypre_SeqVectorInitialize(y_tmp);
num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg);
if (!use_persistent_comm)
{
y_buf_data = hypre_CTAlloc( HYPRE_Complex*, num_vectors );
for ( jv=0; jv<num_vectors; ++jv )
y_buf_data[jv] = hypre_CTAlloc(HYPRE_Complex, hypre_ParCSRCommPkgSendMapStart
(comm_pkg, num_sends));
}
y_tmp_data = hypre_VectorData(y_tmp);
y_local_data = hypre_VectorData(y_local);
hypre_assert( idxstride==1 ); /* only 'column' storage of multivectors
* implemented so far */
#ifdef HYPRE_PROFILE
hypre_profile_times[HYPRE_TIMER_ID_PACK_UNPACK] += hypre_MPI_Wtime();
#endif
if (num_cols_offd)
{
if (A->offdT)
{
// offdT is optional. Used only if it's present.
hypre_CSRMatrixMatvec(alpha, A->offdT, x_local, 0.0, y_tmp);
}
else
{
hypre_CSRMatrixMatvecT(alpha, offd, x_local, 0.0, y_tmp);
}
}
#ifdef HYPRE_PROFILE
hypre_profile_times[HYPRE_TIMER_ID_HALO_EXCHANGE] -= hypre_MPI_Wtime();
#endif
if (use_persistent_comm)
{
#ifdef HYPRE_USING_PERSISTENT_COMM
hypre_ParCSRPersistentCommHandleStart(persistent_comm_handle);
#endif
}
else
{
for ( jv=0; jv<num_vectors; ++jv )
{
/* this is where we assume multivectors are 'column' storage */
comm_handle[jv] = hypre_ParCSRCommHandleCreate
( 2, comm_pkg, &(y_tmp_data[jv*num_cols_offd]), y_buf_data[jv] );
}
}
#ifdef HYPRE_PROFILE
hypre_profile_times[HYPRE_TIMER_ID_HALO_EXCHANGE] += hypre_MPI_Wtime();
#endif
if (A->diagT)
{
// diagT is optional. Used only if it's present.
hypre_CSRMatrixMatvec(alpha, A->diagT, x_local, beta, y_local);
}
else
{
hypre_CSRMatrixMatvecT(alpha, diag, x_local, beta, y_local);
}
#ifdef HYPRE_PROFILE
hypre_profile_times[HYPRE_TIMER_ID_HALO_EXCHANGE] -= hypre_MPI_Wtime();
#endif
if (use_persistent_comm)
{
#ifdef HYPRE_USING_PERSISTENT_COMM
hypre_ParCSRPersistentCommHandleWait(persistent_comm_handle);
#endif
}
else
{
for ( jv=0; jv<num_vectors; ++jv )
{
hypre_ParCSRCommHandleDestroy(comm_handle[jv]);
comm_handle[jv] = NULL;
}
hypre_TFree(comm_handle);
}
#ifdef HYPRE_PROFILE
hypre_profile_times[HYPRE_TIMER_ID_HALO_EXCHANGE] += hypre_MPI_Wtime();
hypre_profile_times[HYPRE_TIMER_ID_PACK_UNPACK] -= hypre_MPI_Wtime();
#endif
if ( num_vectors==1 )
{
index = 0;
for (i = 0; i < num_sends; i++)
{
start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i);
for (j = start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i+1); j++)
y_local_data[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j)]
#ifdef HYPRE_USING_PERSISTENT_COMM
+= ((HYPRE_Complex *)persistent_comm_handle->recv_data)[index++];
#else
+= y_buf_data[0][index++];
#endif
}
}
else
for ( jv=0; jv<num_vectors; ++jv )
{
index = 0;
for (i = 0; i < num_sends; i++)
{
start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i);
for (j = start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i+1); j++)
y_local_data[ jv*vecstride +
idxstride*hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j) ]
+= y_buf_data[jv][index++];
}
}
hypre_SeqVectorDestroy(y_tmp);
y_tmp = NULL;
if (!use_persistent_comm)
{
for ( jv=0; jv<num_vectors; ++jv ) hypre_TFree(y_buf_data[jv]);
hypre_TFree(y_buf_data);
}
#ifdef HYPRE_PROFILE
hypre_profile_times[HYPRE_TIMER_ID_PACK_UNPACK] += hypre_MPI_Wtime();
#endif
return ierr;
}
/*--------------------------------------------------------------------------
* hypre_ParCSRMatrixMatvec_FF
*--------------------------------------------------------------------------*/
HYPRE_Int
hypre_ParCSRMatrixMatvec_FF( HYPRE_Complex alpha,
hypre_ParCSRMatrix *A,
hypre_ParVector *x,
HYPRE_Complex beta,
hypre_ParVector *y,
HYPRE_Int *CF_marker,
HYPRE_Int fpt )
{
MPI_Comm comm = hypre_ParCSRMatrixComm(A);
hypre_ParCSRCommHandle *comm_handle;
hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(A);
hypre_CSRMatrix *diag = hypre_ParCSRMatrixDiag(A);
hypre_CSRMatrix *offd = hypre_ParCSRMatrixOffd(A);
hypre_Vector *x_local = hypre_ParVectorLocalVector(x);
hypre_Vector *y_local = hypre_ParVectorLocalVector(y);
HYPRE_Int num_rows = hypre_ParCSRMatrixGlobalNumRows(A);
HYPRE_Int num_cols = hypre_ParCSRMatrixGlobalNumCols(A);
hypre_Vector *x_tmp;
HYPRE_Int x_size = hypre_ParVectorGlobalSize(x);
HYPRE_Int y_size = hypre_ParVectorGlobalSize(y);
HYPRE_Int num_cols_offd = hypre_CSRMatrixNumCols(offd);
HYPRE_Int ierr = 0;
HYPRE_Int num_sends, i, j, index, start, num_procs;
HYPRE_Int *int_buf_data = NULL;
HYPRE_Int *CF_marker_offd = NULL;
HYPRE_Complex *x_tmp_data = NULL;
HYPRE_Complex *x_buf_data = NULL;
HYPRE_Complex *x_local_data = hypre_VectorData(x_local);
/*---------------------------------------------------------------------
* Check for size compatibility. ParMatvec returns ierr = 11 if
* length of X doesn't equal the number of columns of A,
* ierr = 12 if the length of Y doesn't equal the number of rows
* of A, and ierr = 13 if both are true.
*
* Because temporary vectors are often used in ParMatvec, none of
* these conditions terminates processing, and the ierr flag
* is informational only.
*--------------------------------------------------------------------*/
hypre_MPI_Comm_size(comm,&num_procs);
if (num_cols != x_size)
ierr = 11;
if (num_rows != y_size)
ierr = 12;
if (num_cols != x_size && num_rows != y_size)
ierr = 13;
if (num_procs > 1)
{
if (num_cols_offd)
{
x_tmp = hypre_SeqVectorCreate( num_cols_offd );
hypre_SeqVectorInitialize(x_tmp);
x_tmp_data = hypre_VectorData(x_tmp);
}
/*---------------------------------------------------------------------
* 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);
}
num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg);
if (num_sends)
x_buf_data = hypre_CTAlloc(HYPRE_Complex, hypre_ParCSRCommPkgSendMapStart
(comm_pkg, num_sends));
index = 0;
for (i = 0; i < num_sends; i++)
{
start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i);
for (j = start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i+1); j++)
x_buf_data[index++]
= x_local_data[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j)];
}
comm_handle =
hypre_ParCSRCommHandleCreate ( 1, comm_pkg, x_buf_data, x_tmp_data );
}
hypre_CSRMatrixMatvec_FF( alpha, diag, x_local, beta, y_local, CF_marker,
CF_marker, fpt);
if (num_procs > 1)
{
hypre_ParCSRCommHandleDestroy(comm_handle);
comm_handle = NULL;
if (num_sends)
int_buf_data = hypre_CTAlloc(HYPRE_Int, hypre_ParCSRCommPkgSendMapStart
(comm_pkg, num_sends));
if (num_cols_offd) CF_marker_offd = hypre_CTAlloc(HYPRE_Int, num_cols_offd);
index = 0;
for (i = 0; i < num_sends; i++)
{
start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i);
for (j = start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i+1); j++)
int_buf_data[index++]
= CF_marker[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j)];
}
comm_handle =
hypre_ParCSRCommHandleCreate(11,comm_pkg,int_buf_data,CF_marker_offd );
hypre_ParCSRCommHandleDestroy(comm_handle);
comm_handle = NULL;
if (num_cols_offd) hypre_CSRMatrixMatvec_FF( alpha, offd, x_tmp, 1.0, y_local,
CF_marker, CF_marker_offd, fpt);
hypre_SeqVectorDestroy(x_tmp);
x_tmp = NULL;
hypre_TFree(x_buf_data);
hypre_TFree(int_buf_data);
hypre_TFree(CF_marker_offd);
}
return ierr;
}
|
GB_unaryop__ainv_int32_int8.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__ainv_int32_int8
// op(A') function: GB_tran__ainv_int32_int8
// C type: int32_t
// A type: int8_t
// cast: int32_t cij = (int32_t) aij
// unaryop: cij = -aij
#define GB_ATYPE \
int8_t
#define GB_CTYPE \
int32_t
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
int8_t aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = -x ;
// casting
#define GB_CASTING(z, x) \
int32_t z = (int32_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_AINV || GxB_NO_INT32 || GxB_NO_INT8)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop__ainv_int32_int8
(
int32_t *restrict Cx,
const int8_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__ainv_int32_int8
(
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
|
pslansy.c | /**
*
* @file
*
* PLASMA is a software package provided by:
* University of Tennessee, US,
* University of Manchester, UK.
*
* @generated from /home/luszczek/workspace/plasma/bitbucket/plasma/compute/pzlansy.c, normal z -> s, Fri Sep 28 17:38:13 2018
*
**/
#include "plasma_async.h"
#include "plasma_context.h"
#include "plasma_descriptor.h"
#include "plasma_internal.h"
#include "plasma_types.h"
#include "plasma_workspace.h"
#include <plasma_core_blas.h>
#define A(m, n) (float*)plasma_tile_addr(A, m, n)
/***************************************************************************//**
* Parallel tile calculation of max, one, infinity or Frobenius matrix norm
* for a symmetric matrix.
******************************************************************************/
void plasma_pslansy(plasma_enum_t norm, plasma_enum_t uplo,
plasma_desc_t A, float *work, float *value,
plasma_sequence_t *sequence, plasma_request_t *request)
{
// Return if failed sequence.
if (sequence->status != PlasmaSuccess)
return;
switch (norm) {
float stub;
float *workspace;
float *scale;
float *sumsq;
//================
// PlasmaMaxNorm
//================
case PlasmaMaxNorm:
for (int m = 0; m < A.mt; m++) {
int mvam = plasma_tile_mview(A, m);
int ldam = plasma_tile_mmain(A, m);
if (uplo == PlasmaLower) {
for (int n = 0; n < m; n++) {
int nvan = plasma_tile_nview(A, n);
plasma_core_omp_slange(PlasmaMaxNorm,
mvam, nvan,
A(m, n), ldam,
&stub, &work[A.mt*n+m],
sequence, request);
}
}
else { // PlasmaUpper
for (int n = m+1; n < A.nt; n++) {
int nvan = plasma_tile_nview(A, n);
plasma_core_omp_slange(PlasmaMaxNorm,
mvam, nvan,
A(m, n), ldam,
&stub, &work[A.mt*n+m],
sequence, request);
}
}
plasma_core_omp_slansy(PlasmaMaxNorm, uplo,
mvam,
A(m, m), ldam,
&stub, &work[A.mt*m+m],
sequence, request);
}
#pragma omp taskwait
plasma_core_omp_slansy(PlasmaMaxNorm, uplo,
A.nt,
work, A.mt,
&stub, value,
sequence, request);
break;
//================
// PlasmaOneNorm
//================
case PlasmaOneNorm:
case PlasmaInfNorm:
for (int m = 0; m < A.mt; m++) {
int mvam = plasma_tile_mview(A, m);
int ldam = plasma_tile_mmain(A, m);
if (uplo == PlasmaLower) {
for (int n = 0; n < m; n++) {
int nvan = plasma_tile_nview(A, n);
plasma_core_omp_slange_aux(PlasmaOneNorm,
mvam, nvan,
A(m, n), ldam,
&work[A.n*m+n*A.nb],
sequence, request);
plasma_core_omp_slange_aux(PlasmaInfNorm,
mvam, nvan,
A(m, n), ldam,
&work[A.n*n+m*A.nb],
sequence, request);
}
}
else { // PlasmaUpper
for (int n = m+1; n < A.nt; n++) {
int nvan = plasma_tile_nview(A, n);
plasma_core_omp_slange_aux(PlasmaOneNorm,
mvam, nvan,
A(m, n), ldam,
&work[A.n*m+n*A.nb],
sequence, request);
plasma_core_omp_slange_aux(PlasmaInfNorm,
mvam, nvan,
A(m, n), ldam,
&work[A.n*n+m*A.nb],
sequence, request);
}
}
plasma_core_omp_slansy_aux(PlasmaOneNorm, uplo,
mvam,
A(m, m), ldam,
&work[A.n*m+m*A.nb],
sequence, request);
}
#pragma omp taskwait
workspace = work + A.mt*A.n;
plasma_core_omp_slange(PlasmaInfNorm,
A.n, A.mt,
work, A.n,
workspace, value,
sequence, request);
break;
//======================
// PlasmaFrobeniusNorm
//======================
case PlasmaFrobeniusNorm:
scale = work;
sumsq = work + A.mt*A.nt;
for (int m = 0; m < A.mt; m++) {
int mvam = plasma_tile_mview(A, m);
int ldam = plasma_tile_mmain(A, m);
if (uplo == PlasmaLower) {
for (int n = 0; n < m; n++) {
int nvan = plasma_tile_nview(A, n);
plasma_core_omp_sgessq(mvam, nvan,
A(m, n), ldam,
&scale[A.mt*n+m], &sumsq[A.mt*n+m],
sequence, request);
}
}
else { // PlasmaUpper
for (int n = m+1; n < A.nt; n++) {
int nvan = plasma_tile_nview(A, n);
plasma_core_omp_sgessq(mvam, nvan,
A(m, n), ldam,
&scale[A.mt*m+n], &sumsq[A.mt*m+n],
sequence, request);
}
}
plasma_core_omp_ssyssq(uplo,
mvam,
A(m, m), ldam,
&scale[A.mt*m+m], &sumsq[A.mt*m+m],
sequence, request);
}
#pragma omp taskwait
plasma_core_omp_ssyssq_aux(A.mt, A.nt,
scale, sumsq,
value,
sequence, request);
break;
}
}
|
galaxy_openmp.c | #include <omp.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <sys/time.h>
#include "../common/galaxy_utils.h"
float *real_rasc, *real_decl, *rand_rasc, *rand_decl;
long int numberOfGalaxies = 100000;
int main(int argc, char* argv[])
{
struct timeval _ttime;
struct timezone _tzone;
float radian_to_angle = 180 / acosf(-1.0f);
gettimeofday(&_ttime, &_tzone);
double time_start = (double)_ttime.tv_sec + (double)_ttime.tv_usec/1000000.;
real_rasc = (float *)calloc(numberOfGalaxies, sizeof(float));
real_decl = (float *)calloc(numberOfGalaxies, sizeof(float));
// store right ascension and declination for synthetic random galaxies here
rand_rasc = (float *)calloc(numberOfGalaxies, sizeof(float));
rand_decl = (float *)calloc(numberOfGalaxies, sizeof(float));
// read input data from files given on the command line
if ( parseargs_readinput(argc, argv, numberOfGalaxies, real_rasc, real_decl, rand_rasc, rand_decl) != 0 ) {printf(" Program stopped.\n");return(0);}
printf(" Input data read, now calculating histograms\n");
long int histogram_DD[360] = {0L};
long int histogram_DR[360] = {0L};
long int histogram_RR[360] = {0L};
// galaxie distance of itself will be 0
histogram_DD[0] = numberOfGalaxies;
histogram_RR[0] = numberOfGalaxies;
float quantum_reciprocal = 4;
/* Fork a team of threads */
int i, tid, nthreads;
float angle;
#pragma omp parallel private(tid, i, angle) shared(numberOfGalaxies,real_rasc,real_decl, rand_rasc, rand_decl)
{
tid = omp_get_thread_num();
/* Only master thread does this */
if (tid == 0)
{
nthreads = omp_get_num_threads();
printf(" Number of threads = %d\n", nthreads);
}
// compute DR
#pragma omp for
for(int i=0; i<numberOfGalaxies; ++i)
for(int j=0; j<numberOfGalaxies; ++j){
angle = angle_between(real_rasc[i], real_decl[i], rand_rasc[j], rand_decl[j]) * radian_to_angle;
#pragma omp atomic
++histogram_DR[ (int)(angle*quantum_reciprocal)];
}
// compute DD
#pragma omp for
for(int i=0; i<numberOfGalaxies; ++i)
for(int j=i+1; j<numberOfGalaxies; ++j){
float angle = angle_between(real_rasc[i], real_decl[i], real_rasc[j], real_decl[j]) * radian_to_angle;
#pragma omp atomic
//printf("%d - %d - %d\n", i, j, (int)floor(angle/quantum));
histogram_DD[(int)(angle*quantum_reciprocal)] += 2;
}
// compute RR
#pragma omp for
for(int i=0; i<numberOfGalaxies; ++i)
for(int j=i+1; j<numberOfGalaxies; ++j){
angle = angle_between(rand_rasc[i], rand_decl[i], rand_rasc[j], rand_decl[j]) * radian_to_angle;
#pragma omp atomic
histogram_RR[(int)(angle*quantum_reciprocal)] += 2;
}
}
// check point: the sum of all historgram entries should be galaxy_num**2
long int histsum = 0L;
int correct_value=1;
for ( int i = 0; i < 360; ++i ) histsum += histogram_DD[i];
printf(" Histogram DD : sum = %ld\n",histsum);
if ( histsum != (numberOfGalaxies*numberOfGalaxies)) {printf(" Histogram sums should be %ld. Ending program prematurely\n", numberOfGalaxies*numberOfGalaxies);return(0);}
histsum = 0L;
for ( int i = 0; i < 360; ++i ) histsum += histogram_DR[i];
printf(" Histogram DR : sum = %ld\n",histsum);
if ( histsum != numberOfGalaxies*numberOfGalaxies ) {printf(" Histogram sums should be %ld. Ending program prematurely\n", numberOfGalaxies*numberOfGalaxies);return(0);}
histsum = 0L;
for ( int i = 0; i < 360; ++i ) histsum += histogram_RR[i];
printf(" Histogram RR : sum = %ld\n",histsum);
if ( histsum != (numberOfGalaxies*numberOfGalaxies)) {printf(" Histogram sums should be %ld. Ending program prematurely\n", numberOfGalaxies*numberOfGalaxies);return(0);}
printf(" Omega values for the histograms:\n");
float omega[360];
for ( int i = 0; i < 10; ++i )
if ( histogram_RR[i] != 0L )
{
omega[i] = (histogram_DD[i] - 2L*histogram_DR[i] + histogram_RR[i])/((float)(histogram_RR[i]));
if ( i < 10 ) printf(" angle %.2f deg. -> %.2f deg. : %.3f\n", i*0.25, (i+1)*0.25, omega[i]);
}
FILE *out_file = fopen(argv[3],"w");
if ( out_file == NULL ) printf(" ERROR: Cannot open output file %s\n",argv[3]);
else
{
for ( int i = 0; i < 360; ++i )
if ( histogram_RR[i] != 0L )
fprintf(out_file,"%.2f : %.3f\n", i*0.25, omega[i] );
fclose(out_file);
printf(" Omega values written to file %s\n",argv[3]);
}
free(real_rasc); free(real_decl);
free(rand_rasc); free(rand_decl);
gettimeofday(&_ttime, &_tzone);
double time_end = (double)_ttime.tv_sec + (double)_ttime.tv_usec/1000000.;
printf(" Wall clock run time = %.1lf secs\n",time_end - time_start);
return(0);
}
|
parallelStriped.c | #include <stdio.h>
#include <math.h>
#include <complex.h>
#include <sys/time.h>
#include <omp.h>
#define M_PI 3.14159265358979323846
/************************************* image variables ********************************************/
int pX, pY;
const int pXmax = 1280; // 2 billion+ px each side should be enough resolution right???????
const int pYmax = 1280; // for main antenna
const int iterationMax = 1000;
/**************************************************************************************************/
/****************************** coordinate plane to be rendered ***********************************/
const double CxMin = -2.2;
const double CxMax = 0.8;
const double CyMin = -1.5;
const double CyMax = 1.5;
/**************************************************************************************************/
/**************************************** file stuff **********************************************/
double pixelWidth; //=(CxMax-CxMin)/pXmax;
double pixelHeight; // =(CyMax-CyMin)/pYmax;
const int maxColorComponentValue = 255; // rgb - SDR colorspace (8 bits per color)
FILE * fp;
char * filename = "..\\..\\output\\mandelbrotC.ppm";
// char * comment = "# "; // comment should start with #
/**************************************************************************************************/
/************************************* render parameters ******************************************/
unsigned char stripeDensity = 7; // higher is more dense
int i_skip = 1; // exclude (i_skip+1) elements from average
const double escapeRadius = 1000000; // big! (bail-out value)
double lnER;
/**************************************************************************************************/
/**
* Function: get_c
* ---------------
* Gets the corresponding coordinate point for the location of a pixel.
*
* Inputs:
* iX: number of x-iteration
* iY: number of y-iteration
*
* Returns:
* Complex double form of the coordinate.
*/
double _Complex get_c(int iX, int iY) {
double Cx, Cy;
Cy = CyMax - iY * pixelHeight;
//if (fabs(Cy)< pixelHeight/3.0) Cy=0.0; // main antenna
Cx = CxMin + iX * pixelWidth;
return Cx + Cy * I;
}
/**
* Function: c_dot
* ---------------
* Computes the dot product of 2 complex double vectors.
*
* Inputs:
* a: vector 1
* b: vector 2
*
* Returns:
* The dot product in double form.
*/
double c_dot(double _Complex a, double _Complex b) {
return creal(a) * creal(b) + cimag(a) * cimag(b);
}
/**
* Function: get_t
* ---------------
* Addend function used to get the value of A for stripe-average coloring method.
* https://en.wikibooks.org/wiki/Fractals/Iterations_in_the_complex_plane/stripeAC
*
* Inputs:
* z: complex number
*
* Returns:
* Double number
*/
double getT(double _Complex z){
return 0.5+0.5*sin(stripeDensity*carg(z));
}
/**
* Function: colorize
* ------------------
* The bread and butter of this program; determines if point is within set by escape-time
* algorithm and performs the colorization of the corresponding pixel.
*
* Inputs:
* c: the current coordinate point
* *row: the array of 1 row's pixel data
* iX: current pixel within the row
* iMax: maximum number of iterations
*
* Returns:
* 0 if completed.
*/
int colorize(double _Complex c, unsigned char *row, int iX, int iMax) {
/** global **/
unsigned char b; // color
int i; // iteration
/** normal map **/
double _Complex Z = 0.0; // initial value for iteration Z0
double _Complex dC = 0.0; // derivative with respect to c
double reflection = FP_ZERO; // inside
double h2 = 1.5; // height factor of the incoming light
double angle = 45.0 / 360.0; // incoming direction of light in turns (change 1st #)
double _Complex v = cexp(2.0 * angle * M_PI * I); // unit 2D vector in this direction
double _Complex u; // normal
/** arg vars **/
double A = 0.0; // A(n)
double prevA = 0.0; // A(n-1)
double R;
double d; // smooth iteration count
double de; // boundary descriptor
/** do the compute **/
for (i = 0; i < iMax; i++) {
dC = 2.0 * dC * Z + 1.0;
Z = Z * Z + c;
if (i>i_skip) A += getT(Z);
R = cabs(Z);
/* shape checking algorithm
skips iterating points within the main cardioid and secondary bulb, otherwise these
would all hit the max iterations
removes about 91% of the set from iteration
REMOVE THIS IF NOT RENDERING THE ENTIRE SET - more computation per iteration if the main
cardioid and secondary bulb are not shown onscreen */
double q = ((creal(c) - 0.25) * (creal(c) - 0.25)) + (cimag(c) * cimag(c));
double cardioid = 0.25 * cimag(c) * cimag(c);
double bulb = 0.0625;
if ((creal(c) * creal(c) + 2 * creal(c) + 1 + cimag(c) * cimag(c)) < bulb || (q * (q +
(creal(c) - 0.25)) < cardioid)) {
break;
}
/** get normal map **/
if (R > escapeRadius) { // exterior of M set
u = Z / dC;
u = u / cabs(u);
reflection = c_dot(u, v) + h2;
reflection = reflection / (1.0 + h2); // rescale so that t does not get bigger than 1
if (reflection < 0.0) reflection = 0.0;
break;
}
prevA = A; // save value for interpolation
}
/** get striping **/
if (i == iMax)
A = -1.0; // interior
else { // exterior
de = 2 * R * log(R) / cabs(dC);
int thin = 3; // thinness of the border
if (de < (pixelWidth / thin)) A = FP_ZERO; // boundary
else {
// computing interpolated average
A /= (i - i_skip) ; // A(n)
prevA /= (i - i_skip - 1) ; // A(n-1)
// smooth iteration count
d = i + 1 + log(lnER/log(R))/M_LN2;
d = d - (int)d; // only fractional part = interpolation coefficient
// linear interpolation
A = d*A + (1.0-d)*prevA;
}
}
/** assign pixel color values **/
int subPixel = 3 * iX;
if (reflection == FP_ZERO) { // interior of Mandelbrot set = black
/* ppm files have pixels situated as groups of 3 ASCII chars in a row; the columns of the
image file will be 3x as numerous as the rows
attempting to store the image rows as a vector in memory and write to the file 1 row
at a time */
row[subPixel] = 0;
row[subPixel+1] = 0;
row[subPixel+2] = 0;
}
// exterior of Mandelbrot set -> normal
else { // multiply the underlying stripe gradient by the reflectivity map
if (A == FP_ZERO) b = 255; // boundary
else b = (unsigned char) ((254-(100*A)) * reflection); // set color bounds for striping
row[subPixel] = b;
row[subPixel+1] = b;
row[subPixel+2] = b;
}
return 0;
}
/**
* Function: setup
* ---------------
* Sets up the .ppm file stream and parameters.
*
* Inputs:
* NULL
*
* Returns:
* NULL
*/
void setup() {
pixelWidth = (CxMax - CxMin) / pXmax;
pixelHeight = (CyMax - CyMin) / pYmax;
lnER = log(escapeRadius);
// create new ppm6 file, give it a name, and open it in binary mode
fp = fopen(filename, "wb");
// write ASCII header to the file
fprintf(fp, "P6\n %d\n %d\n %d\n", pXmax, pYmax, maxColorComponentValue);
}
/**
* Function: info
* --------------
* Provides debugging information from the file.
*
* Inputs:
* NULL
*
* Returns:
* NULL
*/
void info() {
double distortion;
// width/height
double pixelsAspectRatio = (double) pXmax / pYmax;
double worldAspectRatio = (CxMax - CxMin) / (CyMax - CyMin);
// printf("pixelsAspectRatio = %.16f \n", pixelsAspectRatio);
// printf("worldAspectRatio = %.16f \n", worldAspectRatio);
distortion = pixelsAspectRatio - worldAspectRatio;
printf("distortion = %.16f (should be zero!)\n", distortion);
// printf("bailout value = Escape Radius = %.0f \n", escapeRadius);
// printf("iterationMax = %d \n", iterationMax);
// printf("i_skip = %d = number of skipped elements ( including t0 )= %d \n", i_skip, i_skip+1);
printf("file %s saved.\n", filename);
}
/**
* Function: close
* ---------------
* Closes file stream and calls debugging info function.
*
* Inputs:
* NULL
*
* Returns:
* NULL
*/
void close() {
fclose(fp);
info();
}
/********************************************** main **********************************************/
int main() {
struct timeval begin, end;
gettimeofday(&begin, 0);
double _Complex c;
unsigned char row[pXmax * 3];
setup();
printf("Rendering row by row:\n");
for (pY = 0; pY < pYmax; pY++)
{
//#pragma omp parallel for schedule(dynamic)
for (pX = 0; pX < pXmax; pX++)
{
// compute pixel coordinate
c = get_c(pX, pY);
// compute pixel color (24 bit = 3 bytes)
colorize(c, row, pX, iterationMax);
}
// write the cached row of pixels
fwrite(row, 1, (size_t)sizeof(row), fp);
//fwrite("\n", 1, 1, fp); // unnecessary
}
close();
gettimeofday(&end, 0);
long seconds = end.tv_sec - begin.tv_sec;
long microseconds = end.tv_usec - begin.tv_usec;
double execTime = seconds + microseconds*1e-6;
printf("Time elapsed: %f seconds", execTime);
return 0;
}
|
hypre_hopscotch_hash.c | #include "hypre_hopscotch_hash.h"
static HYPRE_Int NearestPowerOfTwo( HYPRE_Int value )
{
HYPRE_Int rc = 1;
while (rc < value) {
rc <<= 1;
}
return rc;
}
static void InitBucket(hypre_HopscotchBucket *b)
{
b->hopInfo = 0;
b->hash = HYPRE_HOPSCOTCH_HASH_EMPTY;
}
#ifdef HYPRE_CONCURRENT_HOPSCOTCH
static void InitSegment(hypre_HopscotchSegment *s)
{
s->timestamp = 0;
omp_init_lock(&s->lock);
}
static void DestroySegment(hypre_HopscotchSegment *s)
{
omp_destroy_lock(&s->lock);
}
#endif
void hypre_UnorderedIntSetCreate( hypre_UnorderedIntSet *s,
HYPRE_Int inCapacity,
HYPRE_Int concurrencyLevel)
{
s->segmentMask = NearestPowerOfTwo(concurrencyLevel) - 1;
if (inCapacity < s->segmentMask + 1)
{
inCapacity = s->segmentMask + 1;
}
//ADJUST INPUT ............................
HYPRE_Int adjInitCap = NearestPowerOfTwo(inCapacity+4096);
HYPRE_Int num_buckets = adjInitCap + HYPRE_HOPSCOTCH_HASH_INSERT_RANGE + 1;
s->bucketMask = adjInitCap - 1;
HYPRE_Int i;
//ALLOCATE THE SEGMENTS ...................
#ifdef HYPRE_CONCURRENT_HOPSCOTCH
s->segments = hypre_TAlloc(hypre_HopscotchSegment, s->segmentMask + 1);
for (i = 0; i <= s->segmentMask; ++i)
{
InitSegment(&s->segments[i]);
}
#endif
s->hopInfo = hypre_TAlloc(hypre_uint, num_buckets);
s->key = hypre_TAlloc(HYPRE_Int, num_buckets);
s->hash = hypre_TAlloc(HYPRE_Int, num_buckets);
#ifdef HYPRE_CONCURRENT_HOPSCOTCH
#pragma omp parallel for
#endif
for (i = 0; i < num_buckets; ++i)
{
s->hopInfo[i] = 0;
s->hash[i] = HYPRE_HOPSCOTCH_HASH_EMPTY;
}
}
void hypre_UnorderedIntMapCreate( hypre_UnorderedIntMap *m,
HYPRE_Int inCapacity,
HYPRE_Int concurrencyLevel)
{
m->segmentMask = NearestPowerOfTwo(concurrencyLevel) - 1;
if (inCapacity < m->segmentMask + 1)
{
inCapacity = m->segmentMask + 1;
}
//ADJUST INPUT ............................
HYPRE_Int adjInitCap = NearestPowerOfTwo(inCapacity+4096);
HYPRE_Int num_buckets = adjInitCap + HYPRE_HOPSCOTCH_HASH_INSERT_RANGE + 1;
m->bucketMask = adjInitCap - 1;
HYPRE_Int i;
//ALLOCATE THE SEGMENTS ...................
#ifdef HYPRE_CONCURRENT_HOPSCOTCH
m->segments = hypre_TAlloc(hypre_HopscotchSegment, m->segmentMask + 1);
for (i = 0; i <= m->segmentMask; i++)
{
InitSegment(&m->segments[i]);
}
#endif
m->table = hypre_TAlloc(hypre_HopscotchBucket, num_buckets);
#ifdef HYPRE_CONCURRENT_HOPSCOTCH
#pragma omp parallel for
#endif
for (i = 0; i < num_buckets; i++)
{
InitBucket(&m->table[i]);
}
}
void hypre_UnorderedIntSetDestroy( hypre_UnorderedIntSet *s )
{
hypre_TFree(s->hopInfo);
hypre_TFree(s->key);
hypre_TFree(s->hash);
#ifdef HYPRE_CONCURRENT_HOPSCOTCH
HYPRE_Int i;
for (i = 0; i <= s->segmentMask; i++)
{
DestroySegment(&s->segments[i]);
}
hypre_TFree(s->segments);
#endif
}
void hypre_UnorderedIntMapDestroy( hypre_UnorderedIntMap *m)
{
hypre_TFree(m->table);
#ifdef HYPRE_CONCURRENT_HOPSCOTCH
HYPRE_Int i;
for (i = 0; i <= m->segmentMask; i++)
{
DestroySegment(&m->segments[i]);
}
hypre_TFree(m->segments);
#endif
}
HYPRE_Int *hypre_UnorderedIntSetCopyToArray( hypre_UnorderedIntSet *s, HYPRE_Int *len )
{
/*HYPRE_Int prefix_sum_workspace[hypre_NumThreads() + 1];*/
HYPRE_Int *prefix_sum_workspace;
HYPRE_Int *ret_array = NULL;
prefix_sum_workspace = hypre_TAlloc(HYPRE_Int, hypre_NumThreads() + 1);
#ifdef HYPRE_CONCURRENT_HOPSCOTCH
#pragma omp parallel
#endif
{
HYPRE_Int n = s->bucketMask + HYPRE_HOPSCOTCH_HASH_INSERT_RANGE;
HYPRE_Int i_begin, i_end;
hypre_GetSimpleThreadPartition(&i_begin, &i_end, n);
HYPRE_Int cnt = 0;
HYPRE_Int i;
for (i = i_begin; i < i_end; i++)
{
if (HYPRE_HOPSCOTCH_HASH_EMPTY != s->hash[i]) cnt++;
}
hypre_prefix_sum(&cnt, len, prefix_sum_workspace);
#ifdef HYPRE_CONCURRENT_HOPSCOTCH
#pragma omp barrier
#pragma omp master
#endif
{
ret_array = hypre_TAlloc(HYPRE_Int, *len);
}
#ifdef HYPRE_CONCURRENT_HOPSCOTCH
#pragma omp barrier
#endif
for (i = i_begin; i < i_end; i++)
{
if (HYPRE_HOPSCOTCH_HASH_EMPTY != s->hash[i]) ret_array[cnt++] = s->key[i];
}
}
hypre_TFree(prefix_sum_workspace);
return ret_array;
}
|
ch_common.c |
#define MAIN
#include "ch_common.h"
#include "cholesky.h"
#include "../timing.h"
#if (defined(DEBUG) || defined(USE_TIMING))
_Atomic int cnt_pdotrf = 0;
_Atomic int cnt_trsm = 0;
_Atomic int cnt_gemm = 0;
_Atomic int cnt_syrk = 0;
#endif
#if defined(USE_TIMING)
void helper_start_timing(int tt) {
if (tt == TIME_POTRF) {
cnt_pdotrf++;
} else if (tt == TIME_TRSM) {
cnt_trsm++;
} else if (tt == TIME_GEMM) {
cnt_gemm++;
} else if (tt == TIME_SYRK) {
cnt_syrk++;
}
}
void helper_end_timing(int tt, double elapsed) {
__timing[THREAD_NUM].ts[tt] += elapsed;
}
#endif
static void get_block_rank(int *block_rank, int nt);
#ifdef CHAMELEON_TARGET
#pragma omp declare target
#endif
void omp_potrf(double * SPEC_RESTRICT const A, int ts, int ld)
{
#ifdef TRACE
static int event_potrf = -1;
char* event_name = "potrf";
if(event_potrf == -1) {
int ierr;
ierr = VT_funcdef(event_name, VT_NOCLASS, &event_potrf);
}
VT_begin(event_potrf);
#endif
#if (defined(DEBUG) || defined(USE_TIMING))
START_TIMING(TIME_POTRF);
#endif
static int INFO;
static const char L = 'L';
dpotrf_(&L, &ts, A, &ld, &INFO);
#if (defined(DEBUG) || defined(USE_TIMING))
END_TIMING(TIME_POTRF);
#endif
#ifdef TRACE
VT_end(event_potrf);
#endif
}
#ifdef CHAMELEON_TARGET
#pragma omp end declare target
#pragma omp declare target
#endif
void omp_trsm(double * SPEC_RESTRICT A, double * SPEC_RESTRICT B, int ts, int ld)
{
#ifdef TRACE
static int event_trsm = -1;
char* event_name = "trsm";
if(event_trsm == -1) {
int ierr;
ierr = VT_funcdef(event_name, VT_NOCLASS, &event_trsm);
}
VT_begin(event_trsm);
#endif
#if (defined(DEBUG) || defined(USE_TIMING))
START_TIMING(TIME_TRSM);
#endif
static char LO = 'L', TR = 'T', NU = 'N', RI = 'R';
static double DONE = 1.0;
dtrsm_(&RI, &LO, &TR, &NU, &ts, &ts, &DONE, A, &ld, B, &ld );
#if (defined(DEBUG) || defined(USE_TIMING))
END_TIMING(TIME_TRSM);
#endif
#ifdef TRACE
VT_end(event_trsm);
#endif
}
#ifdef CHAMELEON_TARGET
#pragma omp end declare target
#pragma omp declare target
#endif
void omp_gemm(double * SPEC_RESTRICT A, double * SPEC_RESTRICT B, double * SPEC_RESTRICT C, int ts, int ld)
{
#ifdef TRACE
static int event_gemm = -1;
char* event_name = "gemm";
if(event_gemm == -1) {
int ierr;
ierr = VT_funcdef(event_name, VT_NOCLASS, &event_gemm);
}
VT_begin(event_gemm);
#endif
#if (defined(DEBUG) || defined(USE_TIMING))
START_TIMING(TIME_GEMM);
#endif
static const char TR = 'T', NT = 'N';
static double DONE = 1.0, DMONE = -1.0;
dgemm_(&NT, &TR, &ts, &ts, &ts, &DMONE, A, &ld, B, &ld, &DONE, C, &ld);
#if (defined(DEBUG) || defined(USE_TIMING))
END_TIMING(TIME_GEMM);
#endif
#ifdef TRACE
VT_end(event_gemm);
#endif
}
#ifdef CHAMELEON_TARGET
#pragma omp end declare target
#pragma omp declare target
#endif
void omp_syrk(double * SPEC_RESTRICT A, double * SPEC_RESTRICT B, int ts, int ld)
{
#ifdef TRACE
static int event_syrk = -1;
char* event_name = "syrk";
if(event_syrk == -1) {
int ierr;
ierr = VT_funcdef(event_name, VT_NOCLASS, &event_syrk);
}
VT_begin(event_syrk);
#endif
#if (defined(DEBUG) || defined(USE_TIMING))
cnt_syrk++;
START_TIMING(TIME_SYRK);
#endif
static char LO = 'L', NT = 'N';
static double DONE = 1.0, DMONE = -1.0;
dsyrk_(&LO, &NT, &ts, &ts, &DMONE, A, &ld, &DONE, B, &ld );
#if (defined(DEBUG) || defined(USE_TIMING))
END_TIMING(TIME_SYRK);
#endif
#ifdef TRACE
VT_end(event_syrk);
#endif
}
#ifdef CHAMELEON_TARGET
#pragma omp end declare target
#endif
void cholesky_single(const int ts, const int nt, double* A[nt][nt])
{
// speed up "serial" verification with only a single rank
#pragma omp parallel
{
#pragma omp single
{
for (int k = 0; k < nt; k++) {
#pragma omp task depend(out: A[k][k])
{
omp_potrf(A[k][k], ts, ts);
#ifdef DEBUG
if (mype == 0) printf("potrf:out:A[%d][%d]\n", k, k);
#endif
}
for (int i = k + 1; i < nt; i++) {
#pragma omp task depend(in: A[k][k]) depend(out: A[k][i])
{
omp_trsm(A[k][k], A[k][i], ts, ts);
#ifdef DEBUG
if (mype == 0) printf("trsm :in:A[%d][%d]:out:A[%d][%d]\n", k, k, k, i);
#endif
}
}
for (int i = k + 1; i < nt; i++) {
for (int j = k + 1; j < i; j++) {
#pragma omp task depend(in: A[k][i], A[k][j]) depend(out: A[j][i])
{
omp_gemm(A[k][i], A[k][j], A[j][i], ts, ts);
#ifdef DEBUG
if (mype == 0) printf("gemm :in:A[%d][%d]:A[%d][%d]:out:A[%d][%d]\n", k, i, k, j, j, i);
#endif
}
}
#pragma omp task depend(in: A[k][i]) depend(out: A[i][i])
{
omp_syrk(A[k][i], A[i][i], ts, ts);
#ifdef DEBUG
if (mype == 0) printf("syrk :in:A[%d][%d]:out:A[%d][%d]\n", k, i, i, i);
#endif
}
}
}
#pragma omp taskwait
}
}
}
inline void wait(MPI_Request *comm_req)
{
// #ifdef TRACE
// static int event_wait = -1;
// char* event_name = "wait";
// if(event_wait == -1) {
// int ierr;
// ierr = VT_funcdef(event_name, VT_NOCLASS, &event_wait);
// }
// VT_begin(event_wait);
// #endif
int comm_comp = 0;
MPI_Test(comm_req, &comm_comp, MPI_STATUS_IGNORE);
while (!comm_comp) {
#if defined(CHAMELEON) || defined(CHAMELEON_TARGET)
int32_t res = chameleon_taskyield();
#else
#pragma omp taskyield
#endif
MPI_Test(comm_req, &comm_comp, MPI_STATUS_IGNORE);
}
// MPI_Wait(comm_req, MPI_STATUS_IGNORE);
// #ifdef TRACE
// VT_end(event_wait);
// #endif
}
inline void reset_send_flags(char *send_flags)
{
for (int i = 0; i < np; i++) send_flags[i] = 0;
}
inline int get_send_flags(char *send_flags, int *block_rank, int itr1_str, int itr1_end, int itr2_str, int itr2_end, int n)
{
int send_cnt = 0;
for (int i = itr1_str; i <= itr1_end; i++) {
for (int j = itr2_str; j <= itr2_end; j++) {
if (!send_flags[block_rank[i*n+j]]) {
send_flags[block_rank[i*n+j]] = 1;
send_cnt++;
}
}
}
return send_cnt;
}
inline void get_recv_flag(char *recv_flag, int *block_rank, int itr1_str, int itr1_end, int itr2_str, int itr2_end, int n)
{
if (*recv_flag == 1) return;
for (int i = itr1_str; i <= itr1_end; i++) {
for (int j = itr2_str; j <= itr2_end; j++) {
if (block_rank[i*n+j] == mype) {
*recv_flag = 1;
return;
}
}
}
}
int main(int argc, char *argv[])
{
/* MPI Initialize */
int provided;
MPI_Init_thread(&argc, &argv, MPI_THREAD_MULTIPLE, &provided);
if (provided != MPI_THREAD_MULTIPLE) {
printf("This Compiler does not support MPI_THREAD_MULTIPLE\n");
exit(0);
}
MPI_Comm_rank(MPI_COMM_WORLD, &mype);
MPI_Comm_size(MPI_COMM_WORLD, &np);
/* cholesky init */
const char *result[3] = {"n/a","successful","UNSUCCESSFUL"};
const double eps = BLAS_dfpinfo(blas_eps);
if (argc < 4) {
printf("cholesky matrix_size block_size check\n");
exit(-1);
}
const int n = atoi(argv[1]); // matrix size
const int ts = atoi(argv[2]); // tile size
int check = atoi(argv[3]); // check result?
const int nt = n / ts;
if (mype == 0) printf("R#%d, n = %d, nt = %d, ts = %d\n", mype, n, nt, ts);
/* Set block rank */
int *block_rank = malloc(nt * nt * sizeof(int));
get_block_rank(block_rank, nt);
#if (defined(DEBUG) || defined(USE_TIMING))
if (mype == 0) {
for (int i = 0; i < nt; i++) {
for (int j = 0; j < nt; j++) {
printf("%d ", block_rank[i * nt + j]);
}
printf("\n");
}
}
MPI_Barrier(MPI_COMM_WORLD);
// calculate how many tiles are assigned to the speicifc ranks and how many diagonals
int nr_tiles = 0;
int nr_tiles_diag = 0;
for (int i = 0; i < nt; i++) {
for (int j = i; j < nt; j++) {
if(block_rank[i * nt + j] == mype)
{
nr_tiles++;
if(i == j)
nr_tiles_diag++;
}
}
}
printf("[%d] has %d tiles in total and %d tiles on the diagonal\n", mype, nr_tiles, nr_tiles_diag);
#endif
double * SPEC_RESTRICT A[nt][nt], * SPEC_RESTRICT B, * SPEC_RESTRICT C[nt], * SPEC_RESTRICT Ans[nt][nt];
#pragma omp parallel
{
#pragma omp single
{
for (int i = 0; i < nt; i++) {
for (int j = 0; j < nt; j++) {
#pragma omp task shared(Ans, A)
{
int error;
if (check) {
Ans[i][j] = (double*) malloc(ts * ts * sizeof(double));
initialize_tile(ts, Ans[i][j]);
}
if (block_rank[i*nt+j] == mype) {
A[i][j] = (double*) malloc(ts * ts * sizeof(double));
if (!check) {
initialize_tile(ts, A[i][j]);
} else {
for (int k = 0; k < ts * ts; k++) {
A[i][j][k] = Ans[i][j][k];
}
}
}
}
}
}
} // omp single
} // omp parallel
for (int i = 0; i < nt; i++) {
// add to diagonal
if (check) {
Ans[i][i][i*ts+i] = (double)nt;
}
if (block_rank[i*nt+i] == mype) {
A[i][i][i*ts+i] = (double)nt;
}
}
B = (double*) malloc(ts * ts * sizeof(double));
for (int i = 0; i < nt; i++) {
C[i] = (double*) malloc(ts * ts * sizeof(double));
}
#pragma omp parallel
#pragma omp single
num_threads = omp_get_num_threads();
INIT_TIMING(num_threads);
RESET_TIMINGS(num_threads);
const float t3 = get_time();
if (check) cholesky_single(ts, nt, (double* (*)[nt]) Ans);
const float t4 = get_time() - t3;
MPI_Barrier(MPI_COMM_WORLD);
RESET_TIMINGS(num_threads);
if (mype == 0)
printf("Starting parallel computation\n");
const float t1 = get_time();
cholesky_mpi(ts, nt, (double* SPEC_RESTRICT (*)[nt])A, B, C, block_rank);
const float t2 = get_time() - t1;
if (mype == 0)
printf("Finished parallel computation\n");
MPI_Barrier(MPI_COMM_WORLD);
/* Verification */
if (check) {
for (int i = 0; i < nt; i++) {
for (int j = 0; j < nt; j++) {
if (block_rank[i * nt + j] == mype) {
for (int k = 0; k < ts*ts; k++) {
// if (Ans[i][j][k] != A[i][j][k]) check = 2;
if (Ans[i][j][k] != A[i][j][k]) {
check = 2;
printf("Expected: %f Value: %f Diff: %f\n", Ans[i][j][k], A[i][j][k], abs(Ans[i][j][k]-A[i][j][k]));
break;
}
}
}
if(check == 2) break;
}
if(check == 2) break;
}
}
float time_mpi = t2;
float gflops_mpi = (((1.0 / 3.0) * n * n * n) / ((time_mpi) * 1.0e+9));
float time_ser = t4;
float gflops_ser = (((1.0 / 3.0) * n * n * n) / ((time_ser) * 1.0e+9));
if(mype == 0 || check == 2)
printf("test:%s-%d-%d-%d:mype:%2d:np:%2d:threads:%2d:result:%s:gflops:%f:time:%f:gflops_ser:%f:time_ser:%f\n", argv[0], n, ts, num_threads, mype, np, num_threads, result[check], gflops_mpi, t2, gflops_ser, t4);
#if (defined(DEBUG) || defined(USE_TIMING))
printf("[%d] count#pdotrf:%d:count#trsm:%d:count#gemm:%d:count#syrk:%d\n", mype, cnt_pdotrf, cnt_trsm, cnt_gemm, cnt_syrk);
#endif
for (int i = 0; i < nt; i++) {
for (int j = 0; j < nt; j++) {
if (block_rank[i*nt+j] == mype) {
free(A[i][j]);
}
if (check)
free(Ans[i][j]);
}
free(C[i]);
}
free(B);
free(block_rank);
MPI_Finalize();
return 0;
}
static void get_block_rank(int *block_rank, int nt)
{
int row, col;
row = col = np;
if (np != 1) {
while (1) {
row = row / 2;
if (row * col == np) break;
col = col / 2;
if (row * col == np) break;
}
}
if (mype == 0) printf("row = %d, col = %d\n", row, col);
int i, j, tmp_rank = 0, offset = 0;
for (i = 0; i < nt; i++) {
for (j = 0; j < nt; j++) {
block_rank[i*nt + j] = tmp_rank + offset;
tmp_rank++;
if (tmp_rank >= col) tmp_rank = 0;
}
tmp_rank = 0;
offset = (offset + col >= np) ? 0 : offset + col;
}
}
|
core_chessq.c | /**
*
* @file
*
* PLASMA is a software package provided by:
* University of Tennessee, US,
* University of Manchester, UK.
*
* @generated from /home/luszczek/workspace/plasma/bitbucket/plasma/core_blas/core_zhessq.c, normal z -> c, Fri Sep 28 17:38:21 2018
*
**/
#include <plasma_core_blas.h>
#include "plasma_types.h"
#include "core_lapack.h"
#include <math.h>
/******************************************************************************/
__attribute__((weak))
void plasma_core_chessq(plasma_enum_t uplo,
int n,
const plasma_complex32_t *A, int lda,
float *scale, float *sumsq)
{
int ione = 1;
if (uplo == PlasmaUpper) {
for (int j = 1; j < n; j++)
// TODO: Inline this operation.
LAPACK_classq(&j, &A[lda*j], &ione, scale, sumsq);
}
else { // PlasmaLower
for (int j = 0; j < n-1; j++) {
int len = n-j-1;
// TODO: Inline this operation.
LAPACK_classq(&len, &A[lda*j+j+1], &ione, scale, sumsq);
}
}
*sumsq *= 2.0;
for (int i = 0; i < n; i++) {
// diagonal is real, ignore imaginary part
if (creal(A[lda*i+i]) != 0.0) { // != propagates nan
float absa = fabsf(creal(A[lda*i+i]));
if (*scale < absa) {
*sumsq = 1.0 + *sumsq*((*scale/absa)*(*scale/absa));
*scale = absa;
}
else {
*sumsq = *sumsq + ((absa/(*scale))*(absa/(*scale)));
}
}
}
}
/******************************************************************************/
void plasma_core_omp_chessq(plasma_enum_t uplo,
int n,
const plasma_complex32_t *A, int lda,
float *scale, float *sumsq,
plasma_sequence_t *sequence, plasma_request_t *request)
{
#pragma omp task depend(in:A[0:lda*n]) \
depend(out:scale[0:n]) \
depend(out:sumsq[0:n])
{
if (sequence->status == PlasmaSuccess) {
*scale = 0.0;
*sumsq = 1.0;
plasma_core_chessq(uplo, n, A, lda, scale, sumsq);
}
}
}
|
fft3d.h | /*
* fft3d.h
*
* Copyright (C) 2014 Diamond Light Source
*
* Author: Richard Gildea
*
* This code is distributed under the BSD license, a copy of which is
* included in the root directory of this package.
*/
#ifndef DIALS_ALGORITHMS_INTEGRATION_FFT3D_H
#define DIALS_ALGORITHMS_INTEGRATION_FFT3D_H
#include <stdio.h>
#include <iostream>
#include <cmath>
#include <scitbx/vec2.h>
#include <scitbx/array_family/flex_types.h>
#include <scitbx/math/utils.h>
#include <cstdlib>
#include <scitbx/array_family/versa_matrix.h>
#include <dials/array_family/scitbx_shared_and_versa.h>
#include <dials/algorithms/spot_prediction/rotation_angles.h>
#include <dxtbx/model/scan_helpers.h>
namespace dials { namespace algorithms {
using dxtbx::model::is_angle_in_range;
// helper function for sampling_volume_map
bool are_angles_in_range(af::ref<vec2<double> > const& angle_ranges,
vec2<double> const& angles) {
for (std::size_t i = 0; i < 2; i++) {
double angle = angles[i];
for (std::size_t j = 0; j < angle_ranges.size(); j++) {
if (is_angle_in_range(angle_ranges[j], angle)) {
return true;
}
}
}
return false;
}
// compute a map of the sampling volume of a scan
void sampling_volume_map(af::ref<double, af::c_grid<3> > const& data,
af::ref<vec2<double> > const& angle_ranges,
vec3<double> s0,
vec3<double> m2,
double const& rl_grid_spacing,
double d_min,
double b_iso) {
typedef af::c_grid<3>::index_type index_t;
index_t const gridding_n_real = index_t(data.accessor());
RotationAngles calculate_rotation_angles_(s0, m2);
double one_over_d_sq_min = 1 / (d_min * d_min);
for (std::size_t i = 0; i < gridding_n_real[0]; i++) {
double i_rl = (double(i) - double(gridding_n_real[0] / 2.0)) * rl_grid_spacing;
double i_rl_sq = i_rl * i_rl;
for (std::size_t j = 0; j < gridding_n_real[1]; j++) {
double j_rl = (double(j) - double(gridding_n_real[1] / 2.0)) * rl_grid_spacing;
double j_rl_sq = j_rl * j_rl;
for (std::size_t k = 0; k < gridding_n_real[2]; k++) {
double k_rl =
(double(k) - double(gridding_n_real[2] / 2.0)) * rl_grid_spacing;
double k_rl_sq = k_rl * k_rl;
double reciprocal_length_sq = (i_rl_sq + j_rl_sq + k_rl_sq);
if (reciprocal_length_sq > one_over_d_sq_min) {
continue;
}
vec3<double> pstar0(i_rl, j_rl, k_rl);
// Try to calculate the diffracting rotation angles
vec2<double> phi;
try {
phi = calculate_rotation_angles_(pstar0);
} catch (error const&) {
continue;
}
// Check that the angles are within the rotation range
if (are_angles_in_range(angle_ranges, phi)) {
double T;
if (b_iso != 0) {
T = std::exp(-b_iso * reciprocal_length_sq / 4);
} else {
T = 1;
}
data(i, j, k) = T;
}
}
}
}
}
/*
Peak-finding algorithm inspired by the CLEAN algorithm of
Högbom, J. A. 1974, A&AS, 15, 417.
See also:
https://doi.org/10.1051/0004-6361/200912148
*/
af::shared<vec3<int> > clean_3d(
af::const_ref<double, af::c_grid<3> > const& dirty_beam,
af::ref<double, af::c_grid<3> > const& dirty_map,
std::size_t n_peaks,
double gamma = 1) {
af::shared<vec3<int> > peaks;
typedef af::c_grid<3>::index_type index_t;
index_t const gridding_n_real = index_t(dirty_map.accessor());
DIALS_ASSERT(dirty_map.size() == dirty_beam.size());
double max_db = af::max(dirty_beam);
af::c_grid<3> accessor(dirty_map.accessor()); // index_type conversion
const int height = int(gridding_n_real[0]);
const int depth = int(gridding_n_real[1]);
const int width = int(gridding_n_real[2]);
const long height_depth = height * depth;
int max_idx = af::max_index(dirty_map);
for (std::size_t i_peak = 0; i_peak < n_peaks; i_peak++) {
// Find the maximum value in the map - this is the next "peak"
const index_t shift = accessor.index_nd(max_idx);
peaks.push_back(vec3<int>(shift));
// reposition the dirty beam on the current peak and subtract from
// the dirty map
const double max_value = dirty_map[max_idx];
const double scale = max_value / max_db * gamma;
max_idx = 0; // reset for next cycle
#pragma omp parallel for
for (int i = 0; i < width; i++) {
int i_db = i - shift[0];
if (i_db < 0) {
i_db += width;
} else if (i_db >= width) {
i_db -= width;
}
// DIALS_ASSERT(i_db >= 0 && i_db < width);
const long ipart_dm = i * height_depth;
const long ipart_db = i_db * height_depth;
for (int j = 0; j < height; j++) {
int j_db = j - shift[1];
if (j_db < 0) {
j_db += height;
} else if (j_db >= height) {
j_db -= height;
}
// DIALS_ASSERT(j_db >= 0 && j_db < height);
const long ijpart_dm = ipart_dm + j * depth;
const long ijpart_db = ipart_db + j_db * depth;
for (int k = 0; k < depth; k++) {
int k_db = k - shift[2];
if (k_db < 0) {
k_db += depth;
} else if (k_db >= depth) {
k_db -= depth;
}
// DIALS_ASSERT(k_db >= 0 && k_db < depth);
const long idx_dm = ijpart_dm + k;
const long idx_db = ijpart_db + k_db;
dirty_map[idx_dm] -= dirty_beam[idx_db] * scale;
if (dirty_map[max_idx] < dirty_map[idx_dm])
#pragma omp critical(max_idx)
{
max_idx = idx_dm;
}
}
}
}
}
return peaks;
}
void map_centroids_to_reciprocal_space_grid(
af::ref<double, af::c_grid<3> > const& grid,
af::const_ref<vec3<double> > const& reciprocal_space_vectors,
af::ref<bool> const& selection,
double d_min,
double b_iso = 0) {
typedef af::c_grid<3>::index_type index_t;
index_t const gridding_n_real = index_t(grid.accessor());
DIALS_ASSERT(d_min >= 0);
DIALS_ASSERT(gridding_n_real[0] == gridding_n_real[1]);
DIALS_ASSERT(gridding_n_real[0] == gridding_n_real[2]);
const int n_points = gridding_n_real[0];
const double rlgrid = 2 / (d_min * n_points);
const double one_over_rlgrid = 1 / rlgrid;
const int half_n_points = n_points / 2;
for (int i = 0; i < reciprocal_space_vectors.size(); i++) {
if (!selection[i]) {
continue;
}
const vec3<double> v = reciprocal_space_vectors[i];
const double v_length = v.length();
const double d_spacing = 1 / v_length;
if (d_spacing < d_min) {
selection[i] = false;
continue;
}
vec3<int> coord;
for (int j = 0; j < 3; j++) {
coord[j] = scitbx::math::iround(v[j] * one_over_rlgrid) + half_n_points;
}
if ((coord.max() >= n_points) || coord.min() < 0) {
selection[i] = false;
continue;
}
double T;
if (b_iso != 0) {
T = std::exp(-b_iso * v_length * v_length / 4.0);
} else {
T = 1;
}
grid(coord) = T;
}
}
}} // namespace dials::algorithms
#endif
|
GB_ijsort.c | //------------------------------------------------------------------------------
// GB_ijsort: sort an index array I and remove duplicates
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// Sort an index array and remove duplicates. In MATLAB notation:
/*
[I1 I1k] = sort (I) ;
Iduplicate = [(I1 (1:end-1) == I1 (2:end)), false] ;
I2 = I1 (~Iduplicate) ;
I2k = I1k (~Iduplicate) ;
*/
#include "GB_ij.h"
#include "GB_sort.h"
#define GB_FREE_WORK \
{ \
GB_FREE (Count) ; \
GB_FREE (I1) ; \
GB_FREE (I1k) ; \
}
GrB_Info GB_ijsort
(
const GrB_Index *GB_RESTRICT I, // size ni, where ni > 1 always holds
int64_t *GB_RESTRICT p_ni, // : size of I, output: # of indices in I2
GrB_Index *GB_RESTRICT *p_I2, // size ni2, where I2 [0..ni2-1]
// contains the sorted indices with duplicates removed.
GrB_Index *GB_RESTRICT *p_I2k, // output array of size ni2
GB_Context Context
)
{
//--------------------------------------------------------------------------
// check inputs
//--------------------------------------------------------------------------
ASSERT (I != NULL) ;
ASSERT (p_ni != NULL) ;
ASSERT (p_I2 != NULL) ;
ASSERT (p_I2k != NULL) ;
//--------------------------------------------------------------------------
// get inputs
//--------------------------------------------------------------------------
GrB_Index *GB_RESTRICT I1 = NULL ;
GrB_Index *GB_RESTRICT I1k = NULL ;
GrB_Index *GB_RESTRICT I2 = NULL ;
GrB_Index *GB_RESTRICT I2k = NULL ;
int64_t ni = *p_ni ;
ASSERT (ni > 1) ;
int64_t *GB_RESTRICT Count = NULL ; // size ntasks+1
int ntasks = 0 ;
//--------------------------------------------------------------------------
// determine the number of threads to use
//--------------------------------------------------------------------------
GB_GET_NTHREADS_MAX (nthreads_max, chunk, Context) ;
int nthreads = GB_nthreads (ni, chunk, nthreads_max) ;
//--------------------------------------------------------------------------
// allocate workspace
//--------------------------------------------------------------------------
I1 = GB_MALLOC (ni, GrB_Index) ;
I1k = GB_MALLOC (ni, GrB_Index) ;
if (I1 == NULL || I1k == NULL)
{
// out of memory
GB_FREE_WORK ;
return (GrB_OUT_OF_MEMORY) ;
}
//--------------------------------------------------------------------------
// copy I into I1 and construct I1k
//--------------------------------------------------------------------------
GB_memcpy (I1, I, ni * sizeof (GrB_Index), nthreads) ;
int64_t k ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (k = 0 ; k < ni ; k++)
{
// the key is selected so that the last duplicate entry comes first in
// the sorted result. It must be adjusted later, so that the kth entry
// has a key equal to k.
I1k [k] = (ni-k) ;
}
//--------------------------------------------------------------------------
// sort [I1 I1k]
//--------------------------------------------------------------------------
GB_msort_2b ((int64_t *) I1, (int64_t *) I1k, ni, nthreads) ;
//--------------------------------------------------------------------------
// determine number of tasks to create
//--------------------------------------------------------------------------
ntasks = (nthreads == 1) ? 1 : (32 * nthreads) ;
ntasks = GB_IMIN (ntasks, ni) ;
ntasks = GB_IMAX (ntasks, 1) ;
//--------------------------------------------------------------------------
// allocate workspace
//--------------------------------------------------------------------------
Count = GB_MALLOC (ntasks+1, int64_t) ;
if (Count == NULL)
{
// out of memory
GB_FREE_WORK ;
return (GrB_OUT_OF_MEMORY) ;
}
//--------------------------------------------------------------------------
// count unique entries in I1
//--------------------------------------------------------------------------
int tid ;
#pragma omp parallel for num_threads(nthreads) schedule(dynamic,1)
for (tid = 0 ; tid < ntasks ; tid++)
{
int64_t kfirst, klast, my_count = (tid == 0) ? 1 : 0 ;
GB_PARTITION (kfirst, klast, ni, tid, ntasks) ;
for (int64_t k = GB_IMAX (kfirst,1) ; k < klast ; k++)
{
if (I1 [k-1] != I1 [k])
{
my_count++ ;
}
}
Count [tid] = my_count ;
}
GB_cumsum (Count, ntasks, NULL, 1) ;
int64_t ni2 = Count [ntasks] ;
//--------------------------------------------------------------------------
// allocate the result I2
//--------------------------------------------------------------------------
I2 = GB_MALLOC (ni2, GrB_Index) ;
I2k = GB_MALLOC (ni2, GrB_Index) ;
if (I2 == NULL || I2k == NULL)
{
// out of memory
GB_FREE_WORK ;
GB_FREE (I2) ;
GB_FREE (I2k) ;
return (GrB_OUT_OF_MEMORY) ;
}
//--------------------------------------------------------------------------
// construct the new list I2 from I1, removing duplicates
//--------------------------------------------------------------------------
#pragma omp parallel for num_threads(nthreads) schedule(dynamic,1)
for (tid = 0 ; tid < ntasks ; tid++)
{
int64_t kfirst, klast, k2 = Count [tid] ;
GB_PARTITION (kfirst, klast, ni, tid, ntasks) ;
if (tid == 0)
{
// the first entry in I1 is never a duplicate
I2 [k2] = I1 [0] ;
I2k [k2] = (ni - I1k [0]) ;
k2++ ;
}
for (int64_t k = GB_IMAX (kfirst,1) ; k < klast ; k++)
{
if (I1 [k-1] != I1 [k])
{
I2 [k2] = I1 [k] ;
I2k [k2] = ni - I1k [k] ;
k2++ ;
}
}
}
//--------------------------------------------------------------------------
// check result: compare with single-pass, single-threaded algorithm
//--------------------------------------------------------------------------
#ifdef GB_DEBUG
{
int64_t ni1 = 1 ;
I1k [0] = ni - I1k [0] ;
for (int64_t k = 1 ; k < ni ; k++)
{
if (I1 [ni1-1] != I1 [k])
{
I1 [ni1] = I1 [k] ;
I1k [ni1] = ni - I1k [k] ;
ni1++ ;
}
}
ASSERT (ni1 == ni2) ;
for (int64_t k = 0 ; k < ni1 ; k++)
{
ASSERT (I1 [k] == I2 [k]) ;
ASSERT (I1k [k] == I2k [k]) ;
}
}
#endif
//--------------------------------------------------------------------------
// free workspace and return the new sorted list
//--------------------------------------------------------------------------
GB_FREE_WORK ;
*(p_I2 ) = (GrB_Index *) I2 ;
*(p_I2k) = (GrB_Index *) I2k ;
*(p_ni ) = (int64_t ) ni2 ;
return (GrB_SUCCESS) ;
}
|
GB_unop__floor_fc32_fc32.c | //------------------------------------------------------------------------------
// GB_unop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the 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__floor_fc32_fc32)
// op(A') function: GB (_unop_tran__floor_fc32_fc32)
// C type: GxB_FC32_t
// A type: GxB_FC32_t
// cast: GxB_FC32_t cij = aij
// unaryop: cij = GB_cfloorf (aij)
#define GB_ATYPE \
GxB_FC32_t
#define GB_CTYPE \
GxB_FC32_t
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
GxB_FC32_t aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = GB_cfloorf (x) ;
// casting
#define GB_CAST(z, aij) \
GxB_FC32_t z = aij ;
// cij = op (aij)
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
GxB_FC32_t aij = Ax [pA] ; \
/* Cx [pC] = op (cast (aij)) */ \
GxB_FC32_t z = aij ; \
Cx [pC] = GB_cfloorf (z) ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_FLOOR || GxB_NO_FC32)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_apply__floor_fc32_fc32)
(
GxB_FC32_t *Cx, // Cx and Ax may be aliased
const GxB_FC32_t *Ax,
const int8_t *restrict Ab, // A->b if A is bitmap
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
if (Ab == NULL)
{
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
GxB_FC32_t aij = Ax [p] ;
GxB_FC32_t z = aij ;
Cx [p] = GB_cfloorf (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 ;
GxB_FC32_t aij = Ax [p] ;
GxB_FC32_t z = aij ;
Cx [p] = GB_cfloorf (z) ;
}
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_tran__floor_fc32_fc32)
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
test.c | #include <stdio.h>
#pragma omp requires unified_shared_memory
#include "../utilities/check.h"
#define N 100
int test_aligned(){
int a[N], aa[N];
int i, error = 0;
// initialize
for(i=0; i<N; i++)
aa[i] = a[i] = -1;
int *b = a;
// offload
#pragma omp target data map(tofrom: b[0:100])
#pragma omp target parallel for simd aligned(b: 8*sizeof(int))
for(int k=0; k<N; k++) {
b[k] = k;
}
// host
for(i=0; i<N; i++)
aa[i] = i;
// check
for(i=0; i<N; i++) {
if (a[i] != aa[i])
printf("%d: a %d != %d (error %d)\n", i, a[i], aa[i], ++error);
if (error > 10) {
printf("abort\n");
return error;
}
}
return error;
}
int test_collapsed(){
int a[N], aa[N];
int i, error = 0;
// initialize
for(i=0; i<N; i++)
aa[i] = a[i] = -1;
// offload
#pragma omp target data map(tofrom: a[0:100])
{
#pragma omp target parallel for simd collapse(2)
for(int k=0; k<N/4; k++)
for(int l=0; l<4; l++)
a[k*4+l] = k*4+l;
}
// host
for(i=0; i<N; i++)
aa[i] = i;
// check
for(i=0; i<N; i++) {
if (a[i] != aa[i])
printf("%d: a %d != %d (error %d)\n", i, a[i], aa[i], ++error);
if (error > 10) {
printf("abort\n");
return error;
}
}
return error;
}
int test_lastprivate(){
int a[N], aa[N];
int i, error = 0;
// initialize
for(i=0; i<N; i++)
aa[i] = a[i] = -1;
int n;
// offload
#pragma omp target parallel for simd map(tofrom: a[0:100], n) lastprivate(n)
for(int k=0; k<N; k++) {
a[k] = k;
n = k;
}
a[0] = n;
// host
for(i=0; i<N; i++)
aa[i] = i;
aa[0] = N-1;
// check
for(i=0; i<N; i++) {
if (a[i] != aa[i])
printf("%d: a %d != %d (error %d)\n", i, a[i], aa[i], ++error);
if (error > 10) {
printf("abort\n");
return error;
}
}
return error;
}
int test_linear(){
int a[N], aa[N];
int i, error = 0;
// initialize
for(i=0; i<N; i++)
aa[i] = a[i] = -1;
int l = 0;
// offload
#pragma omp target data map(tofrom: a[0:100])
{
#pragma omp target parallel for simd linear(l: 2)
for(int k=0; k<N; k++) {
l = 2*k;
a[k] = l;
}
}
// host
for(i=0; i<N; i++)
aa[i] = 2*i;
// check
for(i=0; i<N; i++) {
if (a[i] != aa[i])
printf("%d: a %d != %d (error %d)\n", i, a[i], aa[i], ++error);
if (error > 10) {
printf("abort\n");
return error;;
}
}
return error;
}
int test_private(){
int a[N], aa[N];
int i, error = 0;
// initialize
for(i=0; i<N; i++)
aa[i] = a[i] = -1;
int n;
// offload
#pragma omp target data map(tofrom: a[0:100])
{
#pragma omp target parallel for simd private(n)
for(int k=0; k<N; k++) {
n = k;
a[k] = n;
}
}
// host
for(i=0; i<N; i++)
aa[i] = i;
// check
for(i=0; i<N; i++) {
if (a[i] != aa[i])
printf("%d: a %d != %d (error %d)\n", i, a[i], aa[i], ++error);
if (error > 10) {
printf("abort\n");
return error;
}
}
return error;
}
int test_safelen(){
int a[N], aa[N];
int i, error = 0, k;
// initialize
for(i=0; i<N; i++)
aa[i] = a[i] = -1;
// offload
// TODO: Write a better test for safelen
// Not really a good test for safelen in this case. This works for now.
#pragma omp target parallel for simd map(tofrom: a[0:100]) schedule(static, 100) safelen(2)
for(k=0; k<100; k++) {
if (k > 1){
a[k] = a[k-2] + 2;
}
else{
a[k] = k;
}
}
// host
for(i=0; i<N; i++)
aa[i] = i;
// check
for(i=0; i<N; i++) {
if (a[i] != aa[i])
printf("%d: a %d != %d (error %d)\n", i, a[i], aa[i], ++error);
if (error > 10) {
printf("abort\n");
return error;
}
}
return error;
}
int main()
{
int error = 0;
check_offloading();
// Clauses
error += test_aligned();
error += test_collapsed();
error += test_lastprivate();
error += test_linear();
error += test_private();
error += test_safelen();
// report
printf("done with %d errors\n", error);
return error;
}
|
GB_unaryop__lnot_int8_fp64.c | //------------------------------------------------------------------------------
// GB_unaryop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved.
// http://suitesparse.com See GraphBLAS/Doc/License.txt for license.
//------------------------------------------------------------------------------
// If this file is in the Generated/ folder, do not edit it (auto-generated).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_iterator.h"
#include "GB_unaryop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB_unop__lnot_int8_fp64
// op(A') function: GB_tran__lnot_int8_fp64
// C type: int8_t
// A type: double
// cast: int8_t cij ; GB_CAST_SIGNED(cij,aij,8)
// unaryop: cij = !(aij != 0)
#define GB_ATYPE \
double
#define GB_CTYPE \
int8_t
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
double aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = !(x != 0) ;
// casting
#define GB_CASTING(z, aij) \
int8_t z ; GB_CAST_SIGNED(z,aij,8) ;
// cij = op (cast (aij))
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
GB_GETA (aij, Ax, pA) ; \
/* Cx [pC] = op (cast (aij)) */ \
GB_CASTING (z, aij) ; \
GB_OP (GB_CX (pC), z) ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_LNOT || GxB_NO_INT8 || GxB_NO_FP64)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop__lnot_int8_fp64
(
int8_t *Cx, // Cx and Ax may be aliased
double *Ax,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
GB_CAST_OP (p, p) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_tran__lnot_int8_fp64
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t *GB_RESTRICT *Rowcounts,
GBI_single_iterator Iter,
const int64_t *GB_RESTRICT A_slice,
int naslice
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#define GB_PHASE_2_OF_2
#include "GB_unaryop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
fx.c | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% FFFFF X X %
% F X X %
% FFF X %
% F X X %
% F X X %
% %
% %
% MagickCore Image Special Effects Methods %
% %
% Software Design %
% Cristy %
% October 1996 %
% %
% %
% 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://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/accelerate-private.h"
#include "magick/annotate.h"
#include "magick/artifact.h"
#include "magick/attribute.h"
#include "magick/cache.h"
#include "magick/cache-view.h"
#include "magick/channel.h"
#include "magick/color.h"
#include "magick/color-private.h"
#include "magick/colorspace.h"
#include "magick/colorspace-private.h"
#include "magick/composite.h"
#include "magick/decorate.h"
#include "magick/distort.h"
#include "magick/draw.h"
#include "magick/effect.h"
#include "magick/enhance.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/fx.h"
#include "magick/fx-private.h"
#include "magick/gem.h"
#include "magick/geometry.h"
#include "magick/layer.h"
#include "magick/list.h"
#include "magick/log.h"
#include "magick/image.h"
#include "magick/image-private.h"
#include "magick/magick.h"
#include "magick/memory_.h"
#include "magick/monitor.h"
#include "magick/monitor-private.h"
#include "magick/opencl-private.h"
#include "magick/option.h"
#include "magick/pixel-accessor.h"
#include "magick/pixel-private.h"
#include "magick/property.h"
#include "magick/quantum.h"
#include "magick/quantum-private.h"
#include "magick/random_.h"
#include "magick/random-private.h"
#include "magick/resample.h"
#include "magick/resample-private.h"
#include "magick/resize.h"
#include "magick/resource_.h"
#include "magick/splay-tree.h"
#include "magick/statistic.h"
#include "magick/string_.h"
#include "magick/string-private.h"
#include "magick/thread-private.h"
#include "magick/transform.h"
#include "magick/utility.h"
/*
Define declarations.
*/
#define LeftShiftOperator 0xf5U
#define RightShiftOperator 0xf6U
#define LessThanEqualOperator 0xf7U
#define GreaterThanEqualOperator 0xf8U
#define EqualOperator 0xf9U
#define NotEqualOperator 0xfaU
#define LogicalAndOperator 0xfbU
#define LogicalOrOperator 0xfcU
#define ExponentialNotation 0xfdU
struct _FxInfo
{
const Image
*images;
char
*expression;
FILE
*file;
SplayTreeInfo
*colors,
*symbols;
CacheView
**view;
RandomInfo
*random_info;
ExceptionInfo
*exception;
};
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ A c q u i r e F x I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AcquireFxInfo() allocates the FxInfo structure.
%
% The format of the AcquireFxInfo method is:
%
% FxInfo *AcquireFxInfo(Image *image,const char *expression)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o expression: the expression.
%
*/
MagickExport FxInfo *AcquireFxInfo(const Image *image,const char *expression)
{
char
fx_op[2];
const Image
*next;
FxInfo
*fx_info;
register ssize_t
i;
fx_info=(FxInfo *) AcquireMagickMemory(sizeof(*fx_info));
if (fx_info == (FxInfo *) NULL)
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
(void) memset(fx_info,0,sizeof(*fx_info));
fx_info->exception=AcquireExceptionInfo();
fx_info->images=image;
fx_info->colors=NewSplayTree(CompareSplayTreeString,RelinquishMagickMemory,
RelinquishAlignedMemory);
fx_info->symbols=NewSplayTree(CompareSplayTreeString,RelinquishMagickMemory,
RelinquishMagickMemory);
fx_info->view=(CacheView **) AcquireQuantumMemory(GetImageListLength(
fx_info->images),sizeof(*fx_info->view));
if (fx_info->view == (CacheView **) NULL)
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
i=0;
next=GetFirstImageInList(fx_info->images);
for ( ; next != (Image *) NULL; next=next->next)
{
fx_info->view[i]=AcquireVirtualCacheView(next,fx_info->exception);
i++;
}
fx_info->random_info=AcquireRandomInfo();
fx_info->expression=ConstantString(expression);
fx_info->file=stderr;
(void) SubstituteString(&fx_info->expression," ",""); /* compact string */
/*
Force right-to-left associativity for unary negation.
*/
(void) SubstituteString(&fx_info->expression,"-","-1.0*");
(void) SubstituteString(&fx_info->expression,"^-1.0*","^-");
(void) SubstituteString(&fx_info->expression,"E-1.0*","E-");
(void) SubstituteString(&fx_info->expression,"e-1.0*","e-");
/*
Convert compound to simple operators.
*/
fx_op[1]='\0';
*fx_op=(char) LeftShiftOperator;
(void) SubstituteString(&fx_info->expression,"<<",fx_op);
*fx_op=(char) RightShiftOperator;
(void) SubstituteString(&fx_info->expression,">>",fx_op);
*fx_op=(char) LessThanEqualOperator;
(void) SubstituteString(&fx_info->expression,"<=",fx_op);
*fx_op=(char) GreaterThanEqualOperator;
(void) SubstituteString(&fx_info->expression,">=",fx_op);
*fx_op=(char) EqualOperator;
(void) SubstituteString(&fx_info->expression,"==",fx_op);
*fx_op=(char) NotEqualOperator;
(void) SubstituteString(&fx_info->expression,"!=",fx_op);
*fx_op=(char) LogicalAndOperator;
(void) SubstituteString(&fx_info->expression,"&&",fx_op);
*fx_op=(char) LogicalOrOperator;
(void) SubstituteString(&fx_info->expression,"||",fx_op);
*fx_op=(char) ExponentialNotation;
(void) SubstituteString(&fx_info->expression,"**",fx_op);
return(fx_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% A d d N o i s e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AddNoiseImage() adds random noise to the image.
%
% The format of the AddNoiseImage method is:
%
% Image *AddNoiseImage(const Image *image,const NoiseType noise_type,
% ExceptionInfo *exception)
% Image *AddNoiseImageChannel(const Image *image,const ChannelType channel,
% const NoiseType noise_type,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o channel: the channel type.
%
% o noise_type: The type of noise: Uniform, Gaussian, Multiplicative,
% Impulse, Laplacian, or Poisson.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *AddNoiseImage(const Image *image,const NoiseType noise_type,
ExceptionInfo *exception)
{
Image
*noise_image;
noise_image=AddNoiseImageChannel(image,DefaultChannels,noise_type,exception);
return(noise_image);
}
MagickExport Image *AddNoiseImageChannel(const Image *image,
const ChannelType channel,const NoiseType noise_type,ExceptionInfo *exception)
{
#define AddNoiseImageTag "AddNoise/Image"
CacheView
*image_view,
*noise_view;
const char
*option;
double
attenuate;
Image
*noise_image;
MagickBooleanType
status;
MagickOffsetType
progress;
RandomInfo
**magick_restrict random_info;
ssize_t
y;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
unsigned long
key;
#endif
/*
Initialize noise 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);
#if defined(MAGICKCORE_OPENCL_SUPPORT)
noise_image=AccelerateAddNoiseImage(image,channel,noise_type,exception);
if (noise_image != (Image *) NULL)
return(noise_image);
#endif
noise_image=CloneImage(image,0,0,MagickTrue,exception);
if (noise_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(noise_image,DirectClass) == MagickFalse)
{
InheritException(exception,&noise_image->exception);
noise_image=DestroyImage(noise_image);
return((Image *) NULL);
}
/*
Add noise in each row.
*/
attenuate=1.0;
option=GetImageArtifact(image,"attenuate");
if (option != (char *) NULL)
attenuate=StringToDouble(option,(char **) NULL);
status=MagickTrue;
progress=0;
random_info=AcquireRandomInfoThreadSet();
image_view=AcquireVirtualCacheView(image,exception);
noise_view=AcquireAuthenticCacheView(noise_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
key=GetRandomSecretKey(random_info[0]);
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,noise_image,image->rows,key == ~0UL)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
const int
id = GetOpenMPThreadId();
MagickBooleanType
sync;
register const IndexPacket
*magick_restrict indexes;
register const PixelPacket
*magick_restrict p;
register IndexPacket
*magick_restrict noise_indexes;
register ssize_t
x;
register PixelPacket
*magick_restrict q;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
q=GetCacheViewAuthenticPixels(noise_view,0,y,noise_image->columns,1,
exception);
if ((p == (PixelPacket *) NULL) || (q == (PixelPacket *) NULL))
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewVirtualIndexQueue(image_view);
noise_indexes=GetCacheViewAuthenticIndexQueue(noise_view);
for (x=0; x < (ssize_t) image->columns; x++)
{
if ((channel & RedChannel) != 0)
SetPixelRed(q,ClampToQuantum(GenerateDifferentialNoise(random_info[id],
GetPixelRed(p),noise_type,attenuate)));
if (IsGrayColorspace(image->colorspace) != MagickFalse)
{
SetPixelGreen(q,GetPixelRed(q));
SetPixelBlue(q,GetPixelRed(q));
}
else
{
if ((channel & GreenChannel) != 0)
SetPixelGreen(q,ClampToQuantum(GenerateDifferentialNoise(
random_info[id],GetPixelGreen(p),noise_type,attenuate)));
if ((channel & BlueChannel) != 0)
SetPixelBlue(q,ClampToQuantum(GenerateDifferentialNoise(
random_info[id],GetPixelBlue(p),noise_type,attenuate)));
}
if ((channel & OpacityChannel) != 0)
SetPixelOpacity(q,ClampToQuantum(GenerateDifferentialNoise(
random_info[id],GetPixelOpacity(p),noise_type,attenuate)));
if (((channel & IndexChannel) != 0) &&
(image->colorspace == CMYKColorspace))
SetPixelIndex(noise_indexes+x,ClampToQuantum(
GenerateDifferentialNoise(random_info[id],GetPixelIndex(
indexes+x),noise_type,attenuate)));
p++;
q++;
}
sync=SyncCacheViewAuthenticPixels(noise_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,AddNoiseImageTag,progress++,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
noise_view=DestroyCacheView(noise_view);
image_view=DestroyCacheView(image_view);
random_info=DestroyRandomInfoThreadSet(random_info);
if (status == MagickFalse)
noise_image=DestroyImage(noise_image);
return(noise_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% B l u e S h i f t I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% BlueShiftImage() mutes the colors of the image to simulate a scene at
% nighttime in the moonlight.
%
% The format of the BlueShiftImage method is:
%
% Image *BlueShiftImage(const Image *image,const double factor,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o factor: the shift factor.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *BlueShiftImage(const Image *image,const double factor,
ExceptionInfo *exception)
{
#define BlueShiftImageTag "BlueShift/Image"
CacheView
*image_view,
*shift_view;
Image
*shift_image;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
/*
Allocate blue shift image.
*/
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);
shift_image=CloneImage(image,0,0,MagickTrue,exception);
if (shift_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(shift_image,DirectClass) == MagickFalse)
{
InheritException(exception,&shift_image->exception);
shift_image=DestroyImage(shift_image);
return((Image *) NULL);
}
/*
Blue-shift DirectClass image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireVirtualCacheView(image,exception);
shift_view=AcquireAuthenticCacheView(shift_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,shift_image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
MagickBooleanType
sync;
MagickPixelPacket
pixel;
Quantum
quantum;
register const PixelPacket
*magick_restrict p;
register ssize_t
x;
register PixelPacket
*magick_restrict q;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
q=QueueCacheViewAuthenticPixels(shift_view,0,y,shift_image->columns,1,
exception);
if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
quantum=GetPixelRed(p);
if (GetPixelGreen(p) < quantum)
quantum=GetPixelGreen(p);
if (GetPixelBlue(p) < quantum)
quantum=GetPixelBlue(p);
pixel.red=0.5*(GetPixelRed(p)+factor*quantum);
pixel.green=0.5*(GetPixelGreen(p)+factor*quantum);
pixel.blue=0.5*(GetPixelBlue(p)+factor*quantum);
quantum=GetPixelRed(p);
if (GetPixelGreen(p) > quantum)
quantum=GetPixelGreen(p);
if (GetPixelBlue(p) > quantum)
quantum=GetPixelBlue(p);
pixel.red=0.5*(pixel.red+factor*quantum);
pixel.green=0.5*(pixel.green+factor*quantum);
pixel.blue=0.5*(pixel.blue+factor*quantum);
SetPixelRed(q,ClampToQuantum(pixel.red));
SetPixelGreen(q,ClampToQuantum(pixel.green));
SetPixelBlue(q,ClampToQuantum(pixel.blue));
p++;
q++;
}
sync=SyncCacheViewAuthenticPixels(shift_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,BlueShiftImageTag,progress++,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
shift_view=DestroyCacheView(shift_view);
if (status == MagickFalse)
shift_image=DestroyImage(shift_image);
return(shift_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C h a r c o a l I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% CharcoalImage() creates a new image that is a copy of an existing one with
% the edge highlighted. It allocates the memory necessary for the new Image
% structure and returns a pointer to the new image.
%
% The format of the CharcoalImage method is:
%
% Image *CharcoalImage(const Image *image,const double radius,
% const double sigma,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o radius: the radius of the pixel neighborhood.
%
% o sigma: the standard deviation of the Gaussian, in pixels.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *CharcoalImage(const Image *image,const double radius,
const double sigma,ExceptionInfo *exception)
{
Image
*charcoal_image,
*clone_image,
*edge_image;
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);
clone_image=CloneImage(image,0,0,MagickTrue,exception);
if (clone_image == (Image *) NULL)
return((Image *) NULL);
edge_image=EdgeImage(clone_image,radius,exception);
clone_image=DestroyImage(clone_image);
if (edge_image == (Image *) NULL)
return((Image *) NULL);
charcoal_image=BlurImage(edge_image,radius,sigma,exception);
edge_image=DestroyImage(edge_image);
if (charcoal_image == (Image *) NULL)
return((Image *) NULL);
(void) NormalizeImage(charcoal_image);
(void) NegateImage(charcoal_image,MagickFalse);
(void) GrayscaleImage(charcoal_image,image->intensity);
return(charcoal_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C o l o r i z e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ColorizeImage() blends the fill color with each pixel in the image.
% A percentage blend is specified with opacity. Control the application
% of different color components by specifying a different percentage for
% each component (e.g. 90/100/10 is 90% red, 100% green, and 10% blue).
%
% The format of the ColorizeImage method is:
%
% Image *ColorizeImage(const Image *image,const char *opacity,
% const PixelPacket colorize,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o opacity: A character string indicating the level of opacity as a
% percentage.
%
% o colorize: A color value.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *ColorizeImage(const Image *image,const char *opacity,
const PixelPacket colorize,ExceptionInfo *exception)
{
#define ColorizeImageTag "Colorize/Image"
CacheView
*colorize_view,
*image_view;
GeometryInfo
geometry_info;
Image
*colorize_image;
MagickBooleanType
status;
MagickOffsetType
progress;
MagickPixelPacket
pixel;
MagickStatusType
flags;
ssize_t
y;
/*
Allocate colorized image.
*/
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);
colorize_image=CloneImage(image,0,0,MagickTrue,exception);
if (colorize_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(colorize_image,DirectClass) == MagickFalse)
{
InheritException(exception,&colorize_image->exception);
colorize_image=DestroyImage(colorize_image);
return((Image *) NULL);
}
if ((IsGrayColorspace(image->colorspace) != MagickFalse) ||
(IsPixelGray(&colorize) != MagickFalse))
(void) SetImageColorspace(colorize_image,sRGBColorspace);
if ((colorize_image->matte == MagickFalse) &&
(colorize.opacity != OpaqueOpacity))
(void) SetImageAlphaChannel(colorize_image,OpaqueAlphaChannel);
if (opacity == (const char *) NULL)
return(colorize_image);
/*
Determine RGB values of the pen color.
*/
flags=ParseGeometry(opacity,&geometry_info);
pixel.red=geometry_info.rho;
pixel.green=geometry_info.rho;
pixel.blue=geometry_info.rho;
pixel.opacity=(MagickRealType) OpaqueOpacity;
if ((flags & SigmaValue) != 0)
pixel.green=geometry_info.sigma;
if ((flags & XiValue) != 0)
pixel.blue=geometry_info.xi;
if ((flags & PsiValue) != 0)
pixel.opacity=geometry_info.psi;
/*
Colorize DirectClass image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireVirtualCacheView(image,exception);
colorize_view=AcquireAuthenticCacheView(colorize_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,colorize_image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
MagickBooleanType
sync;
register const PixelPacket
*magick_restrict p;
register ssize_t
x;
register PixelPacket
*magick_restrict q;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
q=QueueCacheViewAuthenticPixels(colorize_view,0,y,colorize_image->columns,1,
exception);
if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(q,((GetPixelRed(p)*(100.0-pixel.red)+
colorize.red*pixel.red)/100.0));
SetPixelGreen(q,((GetPixelGreen(p)*(100.0-pixel.green)+
colorize.green*pixel.green)/100.0));
SetPixelBlue(q,((GetPixelBlue(p)*(100.0-pixel.blue)+
colorize.blue*pixel.blue)/100.0));
if (colorize_image->matte == MagickFalse)
SetPixelOpacity(q,GetPixelOpacity(p));
else
SetPixelOpacity(q,((GetPixelOpacity(p)*(100.0-pixel.opacity)+
colorize.opacity*pixel.opacity)/100.0));
p++;
q++;
}
sync=SyncCacheViewAuthenticPixels(colorize_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,ColorizeImageTag,progress++,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
colorize_view=DestroyCacheView(colorize_view);
if (status == MagickFalse)
colorize_image=DestroyImage(colorize_image);
return(colorize_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C o l o r M a t r i x I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ColorMatrixImage() applies color transformation to an image. This method
% permits saturation changes, hue rotation, luminance to alpha, and various
% other effects. Although variable-sized transformation matrices can be used,
% typically one uses a 5x5 matrix for an RGBA image and a 6x6 for CMYKA
% (or RGBA with offsets). The matrix is similar to those used by Adobe Flash
% except offsets are in column 6 rather than 5 (in support of CMYKA images)
% and offsets are normalized (divide Flash offset by 255).
%
% The format of the ColorMatrixImage method is:
%
% Image *ColorMatrixImage(const Image *image,
% const KernelInfo *color_matrix,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o color_matrix: the color matrix.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *ColorMatrixImage(const Image *image,
const KernelInfo *color_matrix,ExceptionInfo *exception)
{
#define ColorMatrixImageTag "ColorMatrix/Image"
CacheView
*color_view,
*image_view;
double
ColorMatrix[6][6] =
{
{ 1.0, 0.0, 0.0, 0.0, 0.0, 0.0 },
{ 0.0, 1.0, 0.0, 0.0, 0.0, 0.0 },
{ 0.0, 0.0, 1.0, 0.0, 0.0, 0.0 },
{ 0.0, 0.0, 0.0, 1.0, 0.0, 0.0 },
{ 0.0, 0.0, 0.0, 0.0, 1.0, 0.0 },
{ 0.0, 0.0, 0.0, 0.0, 0.0, 1.0 }
};
Image
*color_image;
MagickBooleanType
status;
MagickOffsetType
progress;
register ssize_t
i;
ssize_t
u,
v,
y;
/*
Create color matrix.
*/
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);
i=0;
for (v=0; v < (ssize_t) color_matrix->height; v++)
for (u=0; u < (ssize_t) color_matrix->width; u++)
{
if ((v < 6) && (u < 6))
ColorMatrix[v][u]=color_matrix->values[i];
i++;
}
/*
Initialize color image.
*/
color_image=CloneImage(image,0,0,MagickTrue,exception);
if (color_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(color_image,DirectClass) == MagickFalse)
{
InheritException(exception,&color_image->exception);
color_image=DestroyImage(color_image);
return((Image *) NULL);
}
if (image->debug != MagickFalse)
{
char
format[MaxTextExtent],
*message;
(void) LogMagickEvent(TransformEvent,GetMagickModule(),
" ColorMatrix image with color matrix:");
message=AcquireString("");
for (v=0; v < 6; v++)
{
*message='\0';
(void) FormatLocaleString(format,MaxTextExtent,"%.20g: ",(double) v);
(void) ConcatenateString(&message,format);
for (u=0; u < 6; u++)
{
(void) FormatLocaleString(format,MaxTextExtent,"%+f ",
ColorMatrix[v][u]);
(void) ConcatenateString(&message,format);
}
(void) LogMagickEvent(TransformEvent,GetMagickModule(),"%s",message);
}
message=DestroyString(message);
}
/*
ColorMatrix image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireVirtualCacheView(image,exception);
color_view=AcquireAuthenticCacheView(color_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,color_image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
MagickRealType
pixel;
register const IndexPacket
*magick_restrict indexes;
register const PixelPacket
*magick_restrict p;
register ssize_t
x;
register IndexPacket
*magick_restrict color_indexes;
register PixelPacket
*magick_restrict q;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
q=GetCacheViewAuthenticPixels(color_view,0,y,color_image->columns,1,
exception);
if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL))
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewVirtualIndexQueue(image_view);
color_indexes=GetCacheViewAuthenticIndexQueue(color_view);
for (x=0; x < (ssize_t) image->columns; x++)
{
register ssize_t
v;
size_t
height;
height=color_matrix->height > 6 ? 6UL : color_matrix->height;
for (v=0; v < (ssize_t) height; v++)
{
pixel=ColorMatrix[v][0]*GetPixelRed(p)+ColorMatrix[v][1]*
GetPixelGreen(p)+ColorMatrix[v][2]*GetPixelBlue(p);
if (image->matte != MagickFalse)
pixel+=ColorMatrix[v][3]*(QuantumRange-GetPixelOpacity(p));
if (image->colorspace == CMYKColorspace)
pixel+=ColorMatrix[v][4]*GetPixelIndex(indexes+x);
pixel+=QuantumRange*ColorMatrix[v][5];
switch (v)
{
case 0: SetPixelRed(q,ClampToQuantum(pixel)); break;
case 1: SetPixelGreen(q,ClampToQuantum(pixel)); break;
case 2: SetPixelBlue(q,ClampToQuantum(pixel)); break;
case 3:
{
if (image->matte != MagickFalse)
SetPixelAlpha(q,ClampToQuantum(pixel));
break;
}
case 4:
{
if (image->colorspace == CMYKColorspace)
SetPixelIndex(color_indexes+x,ClampToQuantum(pixel));
break;
}
}
}
p++;
q++;
}
if (SyncCacheViewAuthenticPixels(color_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,ColorMatrixImageTag,progress++,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
color_view=DestroyCacheView(color_view);
image_view=DestroyCacheView(image_view);
if (status == MagickFalse)
color_image=DestroyImage(color_image);
return(color_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ D e s t r o y F x I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DestroyFxInfo() deallocates memory associated with an FxInfo structure.
%
% The format of the DestroyFxInfo method is:
%
% ImageInfo *DestroyFxInfo(ImageInfo *fx_info)
%
% A description of each parameter follows:
%
% o fx_info: the fx info.
%
*/
MagickExport FxInfo *DestroyFxInfo(FxInfo *fx_info)
{
register ssize_t
i;
fx_info->exception=DestroyExceptionInfo(fx_info->exception);
fx_info->expression=DestroyString(fx_info->expression);
fx_info->symbols=DestroySplayTree(fx_info->symbols);
fx_info->colors=DestroySplayTree(fx_info->colors);
for (i=(ssize_t) GetImageListLength(fx_info->images)-1; i >= 0; i--)
fx_info->view[i]=DestroyCacheView(fx_info->view[i]);
fx_info->view=(CacheView **) RelinquishMagickMemory(fx_info->view);
fx_info->random_info=DestroyRandomInfo(fx_info->random_info);
fx_info=(FxInfo *) RelinquishMagickMemory(fx_info);
return(fx_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ F x E v a l u a t e C h a n n e l E x p r e s s i o n %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% FxEvaluateChannelExpression() evaluates an expression and returns the
% results.
%
% The format of the FxEvaluateExpression method is:
%
% MagickBooleanType FxEvaluateChannelExpression(FxInfo *fx_info,
% const ChannelType channel,const ssize_t x,const ssize_t y,
% double *alpha,Exceptioninfo *exception)
% MagickBooleanType FxEvaluateExpression(FxInfo *fx_info,double *alpha,
% Exceptioninfo *exception)
%
% A description of each parameter follows:
%
% o fx_info: the fx info.
%
% o channel: the channel.
%
% o x,y: the pixel position.
%
% o alpha: the result.
%
% o exception: return any errors or warnings in this structure.
%
*/
static double FxChannelStatistics(FxInfo *fx_info,const Image *image,
ChannelType channel,const char *symbol,ExceptionInfo *exception)
{
char
channel_symbol[MaxTextExtent],
key[MaxTextExtent],
statistic[MaxTextExtent];
const char
*value;
register const char
*p;
for (p=symbol; (*p != '.') && (*p != '\0'); p++) ;
*channel_symbol='\0';
if (*p == '.')
{
ssize_t
option;
(void) CopyMagickString(channel_symbol,p+1,MaxTextExtent);
option=ParseCommandOption(MagickChannelOptions,MagickTrue,channel_symbol);
if (option >= 0)
channel=(ChannelType) option;
}
(void) FormatLocaleString(key,MaxTextExtent,"%p.%.20g.%s",(void *) image,
(double) channel,symbol);
value=(const char *) GetValueFromSplayTree(fx_info->symbols,key);
if (value != (const char *) NULL)
return(QuantumScale*StringToDouble(value,(char **) NULL));
(void) DeleteNodeFromSplayTree(fx_info->symbols,key);
if (LocaleNCompare(symbol,"depth",5) == 0)
{
size_t
depth;
depth=GetImageChannelDepth(image,channel,exception);
(void) FormatLocaleString(statistic,MaxTextExtent,"%.20g",(double) depth);
}
if (LocaleNCompare(symbol,"kurtosis",8) == 0)
{
double
kurtosis,
skewness;
(void) GetImageChannelKurtosis(image,channel,&kurtosis,&skewness,
exception);
(void) FormatLocaleString(statistic,MaxTextExtent,"%.20g",kurtosis);
}
if (LocaleNCompare(symbol,"maxima",6) == 0)
{
double
maxima,
minima;
(void) GetImageChannelRange(image,channel,&minima,&maxima,exception);
(void) FormatLocaleString(statistic,MaxTextExtent,"%.20g",maxima);
}
if (LocaleNCompare(symbol,"mean",4) == 0)
{
double
mean,
standard_deviation;
(void) GetImageChannelMean(image,channel,&mean,&standard_deviation,
exception);
(void) FormatLocaleString(statistic,MaxTextExtent,"%.20g",mean);
}
if (LocaleNCompare(symbol,"minima",6) == 0)
{
double
maxima,
minima;
(void) GetImageChannelRange(image,channel,&minima,&maxima,exception);
(void) FormatLocaleString(statistic,MaxTextExtent,"%.20g",minima);
}
if (LocaleNCompare(symbol,"skewness",8) == 0)
{
double
kurtosis,
skewness;
(void) GetImageChannelKurtosis(image,channel,&kurtosis,&skewness,
exception);
(void) FormatLocaleString(statistic,MaxTextExtent,"%.20g",skewness);
}
if (LocaleNCompare(symbol,"standard_deviation",18) == 0)
{
double
mean,
standard_deviation;
(void) GetImageChannelMean(image,channel,&mean,&standard_deviation,
exception);
(void) FormatLocaleString(statistic,MaxTextExtent,"%.20g",
standard_deviation);
}
(void) AddValueToSplayTree(fx_info->symbols,ConstantString(key),
ConstantString(statistic));
return(QuantumScale*StringToDouble(statistic,(char **) NULL));
}
static double
FxEvaluateSubexpression(FxInfo *,const ChannelType,const ssize_t,
const ssize_t,const char *,const size_t,double *,ExceptionInfo *);
static MagickOffsetType FxGCD(MagickOffsetType alpha,MagickOffsetType beta)
{
if (beta != 0)
return(FxGCD(beta,alpha % beta));
return(alpha);
}
static inline const char *FxSubexpression(const char *expression,
ExceptionInfo *exception)
{
const char
*subexpression;
register ssize_t
level;
level=0;
subexpression=expression;
while ((*subexpression != '\0') &&
((level != 1) || (strchr(")",(int) *subexpression) == (char *) NULL)))
{
if (strchr("(",(int) *subexpression) != (char *) NULL)
level++;
else
if (strchr(")",(int) *subexpression) != (char *) NULL)
level--;
subexpression++;
}
if (*subexpression == '\0')
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"UnbalancedParenthesis","`%s'",expression);
return(subexpression);
}
static double FxGetSymbol(FxInfo *fx_info,const ChannelType channel,
const ssize_t x,const ssize_t y,const char *expression,const size_t depth,
ExceptionInfo *exception)
{
char
*q,
symbol[MaxTextExtent];
const char
*p,
*value;
double
alpha,
beta;
Image
*image;
MagickBooleanType
status;
MagickPixelPacket
pixel;
PointInfo
point;
register ssize_t
i;
size_t
level;
p=expression;
i=GetImageIndexInList(fx_info->images);
level=0;
point.x=(double) x;
point.y=(double) y;
if (isalpha((int) ((unsigned char) *(p+1))) == 0)
{
char
*subexpression;
subexpression=AcquireString(expression);
if (strchr("suv",(int) *p) != (char *) NULL)
{
switch (*p)
{
case 's':
default:
{
i=GetImageIndexInList(fx_info->images);
break;
}
case 'u': i=0; break;
case 'v': i=1; break;
}
p++;
if (*p == '[')
{
level++;
q=subexpression;
for (p++; *p != '\0'; )
{
if (*p == '[')
level++;
else
if (*p == ']')
{
level--;
if (level == 0)
break;
}
*q++=(*p++);
}
*q='\0';
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,subexpression,
depth,&beta,exception);
i=(ssize_t) alpha;
if (*p != '\0')
p++;
}
if (*p == '.')
p++;
}
if ((*p == 'p') && (isalpha((int) ((unsigned char) *(p+1))) == 0))
{
p++;
if (*p == '{')
{
level++;
q=subexpression;
for (p++; *p != '\0'; )
{
if (*p == '{')
level++;
else
if (*p == '}')
{
level--;
if (level == 0)
break;
}
*q++=(*p++);
}
*q='\0';
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,subexpression,
depth,&beta,exception);
point.x=alpha;
point.y=beta;
if (*p != '\0')
p++;
}
else
if (*p == '[')
{
level++;
q=subexpression;
for (p++; *p != '\0'; )
{
if (*p == '[')
level++;
else
if (*p == ']')
{
level--;
if (level == 0)
break;
}
*q++=(*p++);
}
*q='\0';
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,subexpression,
depth,&beta,exception);
point.x+=alpha;
point.y+=beta;
if (*p != '\0')
p++;
}
if (*p == '.')
p++;
}
subexpression=DestroyString(subexpression);
}
image=GetImageFromList(fx_info->images,i);
if (image == (Image *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"NoSuchImage","`%s'",expression);
return(0.0);
}
i=GetImageIndexInList(image);
GetMagickPixelPacket(image,&pixel);
status=InterpolateMagickPixelPacket(image,fx_info->view[i],image->interpolate,
point.x,point.y,&pixel,exception);
(void) status;
if ((strlen(p) > 2) &&
(LocaleCompare(p,"intensity") != 0) &&
(LocaleCompare(p,"luma") != 0) &&
(LocaleCompare(p,"luminance") != 0) &&
(LocaleCompare(p,"hue") != 0) &&
(LocaleCompare(p,"saturation") != 0) &&
(LocaleCompare(p,"lightness") != 0))
{
char
name[MaxTextExtent];
(void) CopyMagickString(name,p,MaxTextExtent);
for (q=name+(strlen(name)-1); q > name; q--)
{
if (*q == ')')
break;
if (*q == '.')
{
*q='\0';
break;
}
}
if ((strlen(name) > 2) &&
(GetValueFromSplayTree(fx_info->symbols,name) == (const char *) NULL))
{
MagickPixelPacket
*color;
color=(MagickPixelPacket *) GetValueFromSplayTree(fx_info->colors,
name);
if (color != (MagickPixelPacket *) NULL)
{
pixel=(*color);
p+=strlen(name);
}
else
if (QueryMagickColor(name,&pixel,fx_info->exception) != MagickFalse)
{
(void) AddValueToSplayTree(fx_info->colors,ConstantString(name),
CloneMagickPixelPacket(&pixel));
p+=strlen(name);
}
}
}
(void) CopyMagickString(symbol,p,MaxTextExtent);
StripString(symbol);
if (*symbol == '\0')
{
switch (channel)
{
case RedChannel: return(QuantumScale*pixel.red);
case GreenChannel: return(QuantumScale*pixel.green);
case BlueChannel: return(QuantumScale*pixel.blue);
case OpacityChannel:
{
double
alpha;
if (pixel.matte == MagickFalse)
return(1.0);
alpha=(double) (QuantumScale*GetPixelAlpha(&pixel));
return(alpha);
}
case IndexChannel:
{
if (image->colorspace != CMYKColorspace)
{
(void) ThrowMagickException(exception,GetMagickModule(),
ImageError,"ColorSeparatedImageRequired","`%s'",
image->filename);
return(0.0);
}
return(QuantumScale*pixel.index);
}
case DefaultChannels:
return(QuantumScale*GetMagickPixelIntensity(image,&pixel));
default:
break;
}
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"UnableToParseExpression","`%s'",p);
return(0.0);
}
switch (*symbol)
{
case 'A':
case 'a':
{
if (LocaleCompare(symbol,"a") == 0)
return((double) (QuantumScale*GetPixelAlpha(&pixel)));
break;
}
case 'B':
case 'b':
{
if (LocaleCompare(symbol,"b") == 0)
return(QuantumScale*pixel.blue);
break;
}
case 'C':
case 'c':
{
if (LocaleNCompare(symbol,"channel",7) == 0)
{
GeometryInfo
channel_info;
MagickStatusType
flags;
flags=ParseGeometry(symbol+7,&channel_info);
if (image->colorspace == CMYKColorspace)
switch (channel)
{
case CyanChannel:
{
if ((flags & RhoValue) == 0)
return(0.0);
return(channel_info.rho);
}
case MagentaChannel:
{
if ((flags & SigmaValue) == 0)
return(0.0);
return(channel_info.sigma);
}
case YellowChannel:
{
if ((flags & XiValue) == 0)
return(0.0);
return(channel_info.xi);
}
case BlackChannel:
{
if ((flags & PsiValue) == 0)
return(0.0);
return(channel_info.psi);
}
case OpacityChannel:
{
if ((flags & ChiValue) == 0)
return(0.0);
return(channel_info.chi);
}
default:
return(0.0);
}
switch (channel)
{
case RedChannel:
{
if ((flags & RhoValue) == 0)
return(0.0);
return(channel_info.rho);
}
case GreenChannel:
{
if ((flags & SigmaValue) == 0)
return(0.0);
return(channel_info.sigma);
}
case BlueChannel:
{
if ((flags & XiValue) == 0)
return(0.0);
return(channel_info.xi);
}
case OpacityChannel:
{
if ((flags & PsiValue) == 0)
return(0.0);
return(channel_info.psi);
}
case IndexChannel:
{
if ((flags & ChiValue) == 0)
return(0.0);
return(channel_info.chi);
}
default:
return(0.0);
}
}
if (LocaleCompare(symbol,"c") == 0)
return(QuantumScale*pixel.red);
break;
}
case 'D':
case 'd':
{
if (LocaleNCompare(symbol,"depth",5) == 0)
return(FxChannelStatistics(fx_info,image,channel,symbol,exception));
break;
}
case 'E':
case 'e':
{
if (LocaleCompare(symbol,"extent") == 0)
{
if (image->extent != 0)
return((double) image->extent);
return((double) GetBlobSize(image));
}
break;
}
case 'G':
case 'g':
{
if (LocaleCompare(symbol,"g") == 0)
return(QuantumScale*pixel.green);
break;
}
case 'K':
case 'k':
{
if (LocaleNCompare(symbol,"kurtosis",8) == 0)
return(FxChannelStatistics(fx_info,image,channel,symbol,exception));
if (LocaleCompare(symbol,"k") == 0)
{
if (image->colorspace != CMYKColorspace)
{
(void) ThrowMagickException(exception,GetMagickModule(),
OptionError,"ColorSeparatedImageRequired","`%s'",
image->filename);
return(0.0);
}
return(QuantumScale*pixel.index);
}
break;
}
case 'H':
case 'h':
{
if (LocaleCompare(symbol,"h") == 0)
return((double) image->rows);
if (LocaleCompare(symbol,"hue") == 0)
{
double
hue,
lightness,
saturation;
ConvertRGBToHSL(ClampToQuantum(pixel.red),ClampToQuantum(pixel.green),
ClampToQuantum(pixel.blue),&hue,&saturation,&lightness);
return(hue);
}
break;
}
case 'I':
case 'i':
{
if ((LocaleCompare(symbol,"image.depth") == 0) ||
(LocaleCompare(symbol,"image.minima") == 0) ||
(LocaleCompare(symbol,"image.maxima") == 0) ||
(LocaleCompare(symbol,"image.mean") == 0) ||
(LocaleCompare(symbol,"image.kurtosis") == 0) ||
(LocaleCompare(symbol,"image.skewness") == 0) ||
(LocaleCompare(symbol,"image.standard_deviation") == 0))
return(FxChannelStatistics(fx_info,image,channel,symbol+6,exception));
if (LocaleCompare(symbol,"image.resolution.x") == 0)
return(image->x_resolution);
if (LocaleCompare(symbol,"image.resolution.y") == 0)
return(image->y_resolution);
if (LocaleCompare(symbol,"intensity") == 0)
return(QuantumScale*GetMagickPixelIntensity(image,&pixel));
if (LocaleCompare(symbol,"i") == 0)
return((double) x);
break;
}
case 'J':
case 'j':
{
if (LocaleCompare(symbol,"j") == 0)
return((double) y);
break;
}
case 'L':
case 'l':
{
if (LocaleCompare(symbol,"lightness") == 0)
{
double
hue,
lightness,
saturation;
ConvertRGBToHSL(ClampToQuantum(pixel.red),ClampToQuantum(pixel.green),
ClampToQuantum(pixel.blue),&hue,&saturation,&lightness);
return(lightness);
}
if (LocaleCompare(symbol,"luma") == 0)
{
double
luma;
luma=0.212656*pixel.red+0.715158*pixel.green+0.072186*pixel.blue;
return(QuantumScale*luma);
}
if (LocaleCompare(symbol,"luminance") == 0)
{
double
luminance;
luminance=0.212656*pixel.red+0.715158*pixel.green+0.072186*pixel.blue;
return(QuantumScale*luminance);
}
break;
}
case 'M':
case 'm':
{
if (LocaleNCompare(symbol,"maxima",6) == 0)
return(FxChannelStatistics(fx_info,image,channel,symbol,exception));
if (LocaleNCompare(symbol,"mean",4) == 0)
return(FxChannelStatistics(fx_info,image,channel,symbol,exception));
if (LocaleNCompare(symbol,"minima",6) == 0)
return(FxChannelStatistics(fx_info,image,channel,symbol,exception));
if (LocaleCompare(symbol,"m") == 0)
return(QuantumScale*pixel.green);
break;
}
case 'N':
case 'n':
{
if (LocaleCompare(symbol,"n") == 0)
return((double) GetImageListLength(fx_info->images));
break;
}
case 'O':
case 'o':
{
if (LocaleCompare(symbol,"o") == 0)
return(QuantumScale*pixel.opacity);
break;
}
case 'P':
case 'p':
{
if (LocaleCompare(symbol,"page.height") == 0)
return((double) image->page.height);
if (LocaleCompare(symbol,"page.width") == 0)
return((double) image->page.width);
if (LocaleCompare(symbol,"page.x") == 0)
return((double) image->page.x);
if (LocaleCompare(symbol,"page.y") == 0)
return((double) image->page.y);
if (LocaleCompare(symbol,"printsize.x") == 0)
return(PerceptibleReciprocal(image->x_resolution)*image->columns);
if (LocaleCompare(symbol,"printsize.y") == 0)
return(PerceptibleReciprocal(image->y_resolution)*image->rows);
break;
}
case 'Q':
case 'q':
{
if (LocaleCompare(symbol,"quality") == 0)
return((double) image->quality);
break;
}
case 'R':
case 'r':
{
if (LocaleCompare(symbol,"resolution.x") == 0)
return(image->x_resolution);
if (LocaleCompare(symbol,"resolution.y") == 0)
return(image->y_resolution);
if (LocaleCompare(symbol,"r") == 0)
return(QuantumScale*pixel.red);
break;
}
case 'S':
case 's':
{
if (LocaleCompare(symbol,"saturation") == 0)
{
double
hue,
lightness,
saturation;
ConvertRGBToHSL(ClampToQuantum(pixel.red),ClampToQuantum(pixel.green),
ClampToQuantum(pixel.blue),&hue,&saturation,&lightness);
return(saturation);
}
if (LocaleNCompare(symbol,"skewness",8) == 0)
return(FxChannelStatistics(fx_info,image,channel,symbol,exception));
if (LocaleNCompare(symbol,"standard_deviation",18) == 0)
return(FxChannelStatistics(fx_info,image,channel,symbol,exception));
break;
}
case 'T':
case 't':
{
if (LocaleCompare(symbol,"t") == 0)
return((double) GetImageIndexInList(fx_info->images));
break;
}
case 'W':
case 'w':
{
if (LocaleCompare(symbol,"w") == 0)
return((double) image->columns);
break;
}
case 'Y':
case 'y':
{
if (LocaleCompare(symbol,"y") == 0)
return(QuantumScale*pixel.blue);
break;
}
case 'Z':
case 'z':
{
if (LocaleCompare(symbol,"z") == 0)
{
double
depth;
depth=(double) GetImageChannelDepth(image,channel,fx_info->exception);
return(depth);
}
break;
}
default:
break;
}
value=(const char *) GetValueFromSplayTree(fx_info->symbols,symbol);
if (value != (const char *) NULL)
return(StringToDouble(value,(char **) NULL));
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"UnableToParseExpression","`%s'",symbol);
return(0.0);
}
static const char *FxOperatorPrecedence(const char *expression,
ExceptionInfo *exception)
{
typedef enum
{
UndefinedPrecedence,
NullPrecedence,
BitwiseComplementPrecedence,
ExponentPrecedence,
ExponentialNotationPrecedence,
MultiplyPrecedence,
AdditionPrecedence,
ShiftPrecedence,
RelationalPrecedence,
EquivalencyPrecedence,
BitwiseAndPrecedence,
BitwiseOrPrecedence,
LogicalAndPrecedence,
LogicalOrPrecedence,
TernaryPrecedence,
AssignmentPrecedence,
CommaPrecedence,
SeparatorPrecedence
} FxPrecedence;
FxPrecedence
precedence,
target;
register const char
*subexpression;
register int
c;
size_t
level;
c=(-1);
level=0;
subexpression=(const char *) NULL;
target=NullPrecedence;
while ((c != '\0') && (*expression != '\0'))
{
precedence=UndefinedPrecedence;
if ((isspace((int) ((unsigned char) *expression)) != 0) || (c == (int) '@'))
{
expression++;
continue;
}
switch (*expression)
{
case 'A':
case 'a':
{
#if defined(MAGICKCORE_HAVE_ACOSH)
if (LocaleNCompare(expression,"acosh",5) == 0)
{
expression+=5;
break;
}
#endif
#if defined(MAGICKCORE_HAVE_ASINH)
if (LocaleNCompare(expression,"asinh",5) == 0)
{
expression+=5;
break;
}
#endif
#if defined(MAGICKCORE_HAVE_ATANH)
if (LocaleNCompare(expression,"atanh",5) == 0)
{
expression+=5;
break;
}
#endif
if (LocaleNCompare(expression,"atan2",5) == 0)
{
expression+=5;
break;
}
break;
}
case 'E':
case 'e':
{
if ((isdigit(c) != 0) &&
((LocaleNCompare(expression,"E+",2) == 0) ||
(LocaleNCompare(expression,"E-",2) == 0)))
{
expression+=2; /* scientific notation */
break;
}
}
case 'J':
case 'j':
{
if ((LocaleNCompare(expression,"j0",2) == 0) ||
(LocaleNCompare(expression,"j1",2) == 0))
{
expression+=2;
break;
}
break;
}
case '#':
{
while (isxdigit((int) ((unsigned char) *(expression+1))) != 0)
expression++;
break;
}
default:
break;
}
if ((c == (int) '{') || (c == (int) '['))
level++;
else
if ((c == (int) '}') || (c == (int) ']'))
level--;
if (level == 0)
switch ((unsigned char) *expression)
{
case '~':
case '!':
{
precedence=BitwiseComplementPrecedence;
break;
}
case '^':
case '@':
{
precedence=ExponentPrecedence;
break;
}
default:
{
if (((c != 0) && ((isdigit(c) != 0) ||
(strchr(")",c) != (char *) NULL))) &&
(((islower((int) ((unsigned char) *expression)) != 0) ||
(strchr("(",(int) ((unsigned char) *expression)) != (char *) NULL)) ||
((isdigit(c) == 0) &&
(isdigit((int) ((unsigned char) *expression)) != 0))) &&
(strchr("xy",(int) ((unsigned char) *expression)) == (char *) NULL))
precedence=MultiplyPrecedence;
break;
}
case '*':
case '/':
case '%':
{
precedence=MultiplyPrecedence;
break;
}
case '+':
case '-':
{
if ((strchr("(+-/*%:&^|<>~,",c) == (char *) NULL) ||
(isalpha(c) != 0))
precedence=AdditionPrecedence;
break;
}
case LeftShiftOperator:
case RightShiftOperator:
{
precedence=ShiftPrecedence;
break;
}
case '<':
case LessThanEqualOperator:
case GreaterThanEqualOperator:
case '>':
{
precedence=RelationalPrecedence;
break;
}
case EqualOperator:
case NotEqualOperator:
{
precedence=EquivalencyPrecedence;
break;
}
case '&':
{
precedence=BitwiseAndPrecedence;
break;
}
case '|':
{
precedence=BitwiseOrPrecedence;
break;
}
case LogicalAndOperator:
{
precedence=LogicalAndPrecedence;
break;
}
case LogicalOrOperator:
{
precedence=LogicalOrPrecedence;
break;
}
case ExponentialNotation:
{
precedence=ExponentialNotationPrecedence;
break;
}
case ':':
case '?':
{
precedence=TernaryPrecedence;
break;
}
case '=':
{
precedence=AssignmentPrecedence;
break;
}
case ',':
{
precedence=CommaPrecedence;
break;
}
case ';':
{
precedence=SeparatorPrecedence;
break;
}
}
if ((precedence == BitwiseComplementPrecedence) ||
(precedence == TernaryPrecedence) ||
(precedence == AssignmentPrecedence))
{
if (precedence > target)
{
/*
Right-to-left associativity.
*/
target=precedence;
subexpression=expression;
}
}
else
if (precedence >= target)
{
/*
Left-to-right associativity.
*/
target=precedence;
subexpression=expression;
}
if (strchr("(",(int) *expression) != (char *) NULL)
expression=FxSubexpression(expression,exception);
c=(int) (*expression++);
}
return(subexpression);
}
static double FxEvaluateSubexpression(FxInfo *fx_info,const ChannelType channel,
const ssize_t x,const ssize_t y,const char *expression,const size_t depth,
double *beta,ExceptionInfo *exception)
{
#define FxMaxParenthesisDepth 58
#define FxMaxSubexpressionDepth 200
#define FxReturn(value) \
{ \
subexpression=DestroyString(subexpression); \
return(value); \
}
char
*q,
*subexpression;
double
alpha,
gamma;
register const char
*p;
*beta=0.0;
subexpression=AcquireString(expression);
*subexpression='\0';
if (depth > FxMaxSubexpressionDepth)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"UnableToParseExpression","`%s'",expression);
FxReturn(0.0);
}
if (exception->severity >= ErrorException)
FxReturn(0.0);
while (isspace((int) ((unsigned char) *expression)) != 0)
expression++;
if (*expression == '\0')
FxReturn(0.0);
p=FxOperatorPrecedence(expression,exception);
if (p != (const char *) NULL)
{
(void) CopyMagickString(subexpression,expression,(size_t)
(p-expression+1));
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,subexpression,depth+1,
beta,exception);
switch ((unsigned char) *p)
{
case '~':
{
*beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta,
exception);
*beta=(double) (~(size_t) *beta);
FxReturn(*beta);
}
case '!':
{
*beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta,
exception);
FxReturn(*beta == 0.0 ? 1.0 : 0.0);
}
case '^':
{
*beta=pow(alpha,FxEvaluateSubexpression(fx_info,channel,x,y,++p,
depth+1,beta,exception));
FxReturn(*beta);
}
case '*':
case ExponentialNotation:
{
*beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta,
exception);
FxReturn(alpha*(*beta));
}
case '/':
{
*beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta,
exception);
if (*beta == 0.0)
{
(void) ThrowMagickException(exception,GetMagickModule(),
OptionError,"DivideByZero","`%s'",expression);
FxReturn(0.0);
}
FxReturn(alpha/(*beta));
}
case '%':
{
*beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta,
exception);
*beta=fabs(floor((*beta)+0.5));
if (*beta == 0.0)
{
(void) ThrowMagickException(exception,GetMagickModule(),
OptionError,"DivideByZero","`%s'",expression);
FxReturn(0.0);
}
FxReturn(fmod(alpha,(double) *beta));
}
case '+':
{
*beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta,
exception);
FxReturn(alpha+(*beta));
}
case '-':
{
*beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta,
exception);
FxReturn(alpha-(*beta));
}
case LeftShiftOperator:
{
gamma=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta,
exception);
if ((size_t) (gamma+0.5) > (8*sizeof(size_t)))
{
(void) ThrowMagickException(exception,GetMagickModule(),
OptionError,"ShiftCountOverflow","`%s'",subexpression);
FxReturn(0.0);
}
*beta=(double) ((size_t) (alpha+0.5) << (size_t) (gamma+0.5));
FxReturn(*beta);
}
case RightShiftOperator:
{
gamma=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta,
exception);
if ((size_t) (gamma+0.5) > (8*sizeof(size_t)))
{
(void) ThrowMagickException(exception,GetMagickModule(),
OptionError,"ShiftCountOverflow","`%s'",subexpression);
FxReturn(0.0);
}
*beta=(double) ((size_t) (alpha+0.5) >> (size_t) (gamma+0.5));
FxReturn(*beta);
}
case '<':
{
*beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta,
exception);
FxReturn(alpha < *beta ? 1.0 : 0.0);
}
case LessThanEqualOperator:
{
*beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta,
exception);
FxReturn(alpha <= *beta ? 1.0 : 0.0);
}
case '>':
{
*beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta,
exception);
FxReturn(alpha > *beta ? 1.0 : 0.0);
}
case GreaterThanEqualOperator:
{
*beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta,
exception);
FxReturn(alpha >= *beta ? 1.0 : 0.0);
}
case EqualOperator:
{
*beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta,
exception);
FxReturn(fabs(alpha-(*beta)) < MagickEpsilon ? 1.0 : 0.0);
}
case NotEqualOperator:
{
*beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta,
exception);
FxReturn(fabs(alpha-(*beta)) >= MagickEpsilon ? 1.0 : 0.0);
}
case '&':
{
gamma=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta,
exception);
*beta=(double) ((size_t) (alpha+0.5) & (size_t) (gamma+0.5));
FxReturn(*beta);
}
case '|':
{
gamma=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta,
exception);
*beta=(double) ((size_t) (alpha+0.5) | (size_t) (gamma+0.5));
FxReturn(*beta);
}
case LogicalAndOperator:
{
p++;
if (alpha <= 0.0)
{
*beta=0.0;
FxReturn(*beta);
}
gamma=FxEvaluateSubexpression(fx_info,channel,x,y,p,depth+1,beta,
exception);
*beta=(gamma > 0.0) ? 1.0 : 0.0;
FxReturn(*beta);
}
case LogicalOrOperator:
{
p++;
if (alpha > 0.0)
{
*beta=1.0;
FxReturn(*beta);
}
gamma=FxEvaluateSubexpression(fx_info,channel,x,y,p,depth+1,beta,
exception);
*beta=(gamma > 0.0) ? 1.0 : 0.0;
FxReturn(*beta);
}
case '?':
{
double
gamma;
(void) CopyMagickString(subexpression,++p,MaxTextExtent);
q=subexpression;
p=StringToken(":",&q);
if (q == (char *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
OptionError,"UnableToParseExpression","`%s'",subexpression);
FxReturn(0.0);
}
if (fabs(alpha) >= MagickEpsilon)
gamma=FxEvaluateSubexpression(fx_info,channel,x,y,p,depth+1,beta,
exception);
else
gamma=FxEvaluateSubexpression(fx_info,channel,x,y,q,depth+1,beta,
exception);
FxReturn(gamma);
}
case '=':
{
char
numeric[MaxTextExtent];
q=subexpression;
while (isalpha((int) ((unsigned char) *q)) != 0)
q++;
if (*q != '\0')
{
(void) ThrowMagickException(exception,GetMagickModule(),
OptionError,"UnableToParseExpression","`%s'",subexpression);
FxReturn(0.0);
}
ClearMagickException(exception);
*beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta,
exception);
(void) FormatLocaleString(numeric,MaxTextExtent,"%.20g",(double)
*beta);
(void) DeleteNodeFromSplayTree(fx_info->symbols,subexpression);
(void) AddValueToSplayTree(fx_info->symbols,ConstantString(
subexpression),ConstantString(numeric));
FxReturn(*beta);
}
case ',':
{
*beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta,
exception);
FxReturn(alpha);
}
case ';':
{
*beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta,
exception);
FxReturn(*beta);
}
default:
{
gamma=alpha*FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,
beta,exception);
FxReturn(gamma);
}
}
}
if (strchr("(",(int) *expression) != (char *) NULL)
{
if (depth >= FxMaxParenthesisDepth)
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"ParenthesisNestedTooDeeply","`%s'",expression);
(void) CopyMagickString(subexpression,expression+1,MaxTextExtent);
if (strlen(subexpression) != 0)
subexpression[strlen(subexpression)-1]='\0';
gamma=FxEvaluateSubexpression(fx_info,channel,x,y,subexpression,depth+1,
beta,exception);
FxReturn(gamma);
}
switch (*expression)
{
case '+':
{
gamma=FxEvaluateSubexpression(fx_info,channel,x,y,expression+1,depth+1,
beta,exception);
FxReturn(1.0*gamma);
}
case '-':
{
gamma=FxEvaluateSubexpression(fx_info,channel,x,y,expression+1,depth+1,
beta,exception);
FxReturn(-1.0*gamma);
}
case '~':
{
gamma=FxEvaluateSubexpression(fx_info,channel,x,y,expression+1,depth+1,
beta,exception);
FxReturn((double) (~(size_t) (gamma+0.5)));
}
case 'A':
case 'a':
{
if (LocaleNCompare(expression,"abs",3) == 0)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,
depth+1,beta,exception);
FxReturn(fabs(alpha));
}
#if defined(MAGICKCORE_HAVE_ACOSH)
if (LocaleNCompare(expression,"acosh",5) == 0)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5,
depth+1,beta,exception);
FxReturn(acosh(alpha));
}
#endif
if (LocaleNCompare(expression,"acos",4) == 0)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4,
depth+1,beta,exception);
FxReturn(acos(alpha));
}
#if defined(MAGICKCORE_HAVE_J1)
if (LocaleNCompare(expression,"airy",4) == 0)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4,
depth+1,beta,exception);
if (alpha == 0.0)
FxReturn(1.0);
gamma=2.0*j1((MagickPI*alpha))/(MagickPI*alpha);
FxReturn(gamma*gamma);
}
#endif
#if defined(MAGICKCORE_HAVE_ASINH)
if (LocaleNCompare(expression,"asinh",5) == 0)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5,
depth+1,beta,exception);
FxReturn(asinh(alpha));
}
#endif
if (LocaleNCompare(expression,"asin",4) == 0)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4,
depth+1,beta,exception);
FxReturn(asin(alpha));
}
if (LocaleNCompare(expression,"alt",3) == 0)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,
depth+1,beta,exception);
FxReturn(((ssize_t) alpha) & 0x01 ? -1.0 : 1.0);
}
if (LocaleNCompare(expression,"atan2",5) == 0)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5,
depth+1,beta,exception);
FxReturn(atan2(alpha,*beta));
}
#if defined(MAGICKCORE_HAVE_ATANH)
if (LocaleNCompare(expression,"atanh",5) == 0)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5,
depth+1,beta,exception);
FxReturn(atanh(alpha));
}
#endif
if (LocaleNCompare(expression,"atan",4) == 0)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4,
depth+1,beta,exception);
FxReturn(atan(alpha));
}
if (LocaleCompare(expression,"a") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
break;
}
case 'B':
case 'b':
{
if (LocaleCompare(expression,"b") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
break;
}
case 'C':
case 'c':
{
if (LocaleNCompare(expression,"ceil",4) == 0)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4,
depth+1,beta,exception);
FxReturn(ceil(alpha));
}
if (LocaleNCompare(expression,"clamp",5) == 0)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5,
depth+1,beta,exception);
if (alpha < 0.0)
FxReturn(0.0);
if (alpha > 1.0)
FxReturn(1.0);
FxReturn(alpha);
}
if (LocaleNCompare(expression,"cosh",4) == 0)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4,
depth+1,beta,exception);
FxReturn(cosh(alpha));
}
if (LocaleNCompare(expression,"cos",3) == 0)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,
depth+1,beta,exception);
FxReturn(cos(alpha));
}
if (LocaleCompare(expression,"c") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
break;
}
case 'D':
case 'd':
{
if (LocaleNCompare(expression,"debug",5) == 0)
{
const char
*type;
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5,
depth+1,beta,exception);
if (fx_info->images->colorspace == CMYKColorspace)
switch (channel)
{
case CyanChannel: type="cyan"; break;
case MagentaChannel: type="magenta"; break;
case YellowChannel: type="yellow"; break;
case OpacityChannel: type="opacity"; break;
case BlackChannel: type="black"; break;
default: type="unknown"; break;
}
else
switch (channel)
{
case RedChannel: type="red"; break;
case GreenChannel: type="green"; break;
case BlueChannel: type="blue"; break;
case OpacityChannel: type="opacity"; break;
default: type="unknown"; break;
}
*subexpression='\0';
if (strlen(subexpression) > 1)
(void) CopyMagickString(subexpression,expression+6,MaxTextExtent);
if (strlen(subexpression) > 1)
subexpression[strlen(subexpression)-1]='\0';
if (fx_info->file != (FILE *) NULL)
(void) FormatLocaleFile(fx_info->file,
"%s[%.20g,%.20g].%s: %s=%.*g\n",fx_info->images->filename,
(double) x,(double) y,type,subexpression,GetMagickPrecision(),
(double) alpha);
FxReturn(0.0);
}
if (LocaleNCompare(expression,"drc",3) == 0)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,
depth+1,beta,exception);
FxReturn((alpha/(*beta*(alpha-1.0)+1.0)));
}
break;
}
case 'E':
case 'e':
{
if (LocaleCompare(expression,"epsilon") == 0)
FxReturn(MagickEpsilon);
#if defined(MAGICKCORE_HAVE_ERF)
if (LocaleNCompare(expression,"erp",3) == 0)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,
depth+1,beta,exception);
FxReturn(erf(alpha));
}
#endif
if (LocaleNCompare(expression,"exp",3) == 0)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,
depth+1,beta,exception);
FxReturn(exp(alpha));
}
if (LocaleCompare(expression,"e") == 0)
FxReturn(2.7182818284590452354);
break;
}
case 'F':
case 'f':
{
if (LocaleNCompare(expression,"floor",5) == 0)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5,
depth+1,beta,exception);
FxReturn(floor(alpha));
}
break;
}
case 'G':
case 'g':
{
if (LocaleNCompare(expression,"gauss",5) == 0)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5,
depth+1,beta,exception);
gamma=exp((-alpha*alpha/2.0))/sqrt(2.0*MagickPI);
FxReturn(gamma);
}
if (LocaleNCompare(expression,"gcd",3) == 0)
{
MagickOffsetType
gcd;
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,
depth+1,beta,exception);
gcd=FxGCD((MagickOffsetType) (alpha+0.5),(MagickOffsetType)
(*beta+0.5));
FxReturn((double) gcd);
}
if (LocaleCompare(expression,"g") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
break;
}
case 'H':
case 'h':
{
if (LocaleCompare(expression,"h") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
if (LocaleCompare(expression,"hue") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
if (LocaleNCompare(expression,"hypot",5) == 0)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5,
depth+1,beta,exception);
FxReturn(hypot(alpha,*beta));
}
break;
}
case 'K':
case 'k':
{
if (LocaleCompare(expression,"k") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
break;
}
case 'I':
case 'i':
{
if (LocaleCompare(expression,"intensity") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
if (LocaleNCompare(expression,"int",3) == 0)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,
depth+1,beta,exception);
FxReturn(floor(alpha));
}
if (LocaleNCompare(expression,"isnan",5) == 0)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5,
depth+1,beta,exception);
FxReturn((double) !!IsNaN(alpha));
}
if (LocaleCompare(expression,"i") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
break;
}
case 'J':
case 'j':
{
if (LocaleCompare(expression,"j") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
#if defined(MAGICKCORE_HAVE_J0)
if (LocaleNCompare(expression,"j0",2) == 0)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+2,
depth+1,beta,exception);
FxReturn(j0(alpha));
}
#endif
#if defined(MAGICKCORE_HAVE_J1)
if (LocaleNCompare(expression,"j1",2) == 0)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+2,
depth+1,beta,exception);
FxReturn(j1(alpha));
}
#endif
#if defined(MAGICKCORE_HAVE_J1)
if (LocaleNCompare(expression,"jinc",4) == 0)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4,
depth+1,beta,exception);
if (alpha == 0.0)
FxReturn(1.0);
gamma=(2.0*j1((MagickPI*alpha))/(MagickPI*alpha));
FxReturn(gamma);
}
#endif
break;
}
case 'L':
case 'l':
{
if (LocaleNCompare(expression,"ln",2) == 0)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+2,
depth+1,beta,exception);
FxReturn(log(alpha));
}
if (LocaleNCompare(expression,"logtwo",6) == 0)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+6,
depth+1,beta,exception);
FxReturn(log10(alpha)/log10(2.0));
}
if (LocaleNCompare(expression,"log",3) == 0)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,
depth+1,beta,exception);
FxReturn(log10(alpha));
}
if (LocaleCompare(expression,"lightness") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
break;
}
case 'M':
case 'm':
{
if (LocaleCompare(expression,"MaxRGB") == 0)
FxReturn((double) QuantumRange);
if (LocaleNCompare(expression,"maxima",6) == 0)
break;
if (LocaleNCompare(expression,"max",3) == 0)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,
depth+1,beta,exception);
FxReturn(alpha > *beta ? alpha : *beta);
}
if (LocaleNCompare(expression,"minima",6) == 0)
break;
if (LocaleNCompare(expression,"min",3) == 0)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,
depth+1,beta,exception);
FxReturn(alpha < *beta ? alpha : *beta);
}
if (LocaleNCompare(expression,"mod",3) == 0)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,
depth+1,beta,exception);
gamma=alpha-floor((alpha*PerceptibleReciprocal(*beta)))*(*beta);
FxReturn(gamma);
}
if (LocaleCompare(expression,"m") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
break;
}
case 'N':
case 'n':
{
if (LocaleNCompare(expression,"not",3) == 0)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,
depth+1,beta,exception);
FxReturn((double) (alpha < MagickEpsilon));
}
if (LocaleCompare(expression,"n") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
break;
}
case 'O':
case 'o':
{
if (LocaleCompare(expression,"Opaque") == 0)
FxReturn(1.0);
if (LocaleCompare(expression,"o") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
break;
}
case 'P':
case 'p':
{
if (LocaleCompare(expression,"phi") == 0)
FxReturn(MagickPHI);
if (LocaleCompare(expression,"pi") == 0)
FxReturn(MagickPI);
if (LocaleNCompare(expression,"pow",3) == 0)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,
depth+1,beta,exception);
FxReturn(pow(alpha,*beta));
}
if (LocaleCompare(expression,"p") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
break;
}
case 'Q':
case 'q':
{
if (LocaleCompare(expression,"QuantumRange") == 0)
FxReturn((double) QuantumRange);
if (LocaleCompare(expression,"QuantumScale") == 0)
FxReturn(QuantumScale);
break;
}
case 'R':
case 'r':
{
if (LocaleNCompare(expression,"rand",4) == 0)
{
double
alpha;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_FxEvaluateSubexpression)
#endif
alpha=GetPseudoRandomValue(fx_info->random_info);
FxReturn(alpha);
}
if (LocaleNCompare(expression,"round",5) == 0)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5,
depth+1,beta,exception);
FxReturn(floor(alpha+0.5));
}
if (LocaleCompare(expression,"r") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
break;
}
case 'S':
case 's':
{
if (LocaleCompare(expression,"saturation") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
if (LocaleNCompare(expression,"sign",4) == 0)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4,
depth+1,beta,exception);
FxReturn(alpha < 0.0 ? -1.0 : 1.0);
}
if (LocaleNCompare(expression,"sinc",4) == 0)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4,
depth+1,beta,exception);
if (alpha == 0)
FxReturn(1.0);
gamma=(sin((MagickPI*alpha))/(MagickPI*alpha));
FxReturn(gamma);
}
if (LocaleNCompare(expression,"sinh",4) == 0)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4,
depth+1,beta,exception);
FxReturn(sinh(alpha));
}
if (LocaleNCompare(expression,"sin",3) == 0)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,
depth+1,beta,exception);
FxReturn(sin(alpha));
}
if (LocaleNCompare(expression,"sqrt",4) == 0)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4,
depth+1,beta,exception);
FxReturn(sqrt(alpha));
}
if (LocaleNCompare(expression,"squish",6) == 0)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+6,
depth+1,beta,exception);
FxReturn((1.0/(1.0+exp(-alpha))));
}
if (LocaleCompare(expression,"s") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
break;
}
case 'T':
case 't':
{
if (LocaleNCompare(expression,"tanh",4) == 0)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4,
depth+1,beta,exception);
FxReturn(tanh(alpha));
}
if (LocaleNCompare(expression,"tan",3) == 0)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,
depth+1,beta,exception);
FxReturn(tan(alpha));
}
if (LocaleCompare(expression,"Transparent") == 0)
FxReturn(0.0);
if (LocaleNCompare(expression,"trunc",5) == 0)
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5,
depth+1,beta,exception);
if (alpha >= 0.0)
FxReturn(floor(alpha));
FxReturn(ceil(alpha));
}
if (LocaleCompare(expression,"t") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
break;
}
case 'U':
case 'u':
{
if (LocaleCompare(expression,"u") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
break;
}
case 'V':
case 'v':
{
if (LocaleCompare(expression,"v") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
break;
}
case 'W':
case 'w':
{
if (LocaleNCompare(expression,"while",5) == 0)
{
do
{
alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5,
depth+1,beta,exception);
} while (fabs(alpha) >= MagickEpsilon);
FxReturn(*beta);
}
if (LocaleCompare(expression,"w") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
break;
}
case 'Y':
case 'y':
{
if (LocaleCompare(expression,"y") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
break;
}
case 'Z':
case 'z':
{
if (LocaleCompare(expression,"z") == 0)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
break;
}
default:
break;
}
q=(char *) expression;
alpha=InterpretSiPrefixValue(expression,&q);
if (q == expression)
FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception));
FxReturn(alpha);
}
MagickExport MagickBooleanType FxEvaluateExpression(FxInfo *fx_info,
double *alpha,ExceptionInfo *exception)
{
MagickBooleanType
status;
status=FxEvaluateChannelExpression(fx_info,GrayChannel,0,0,alpha,exception);
return(status);
}
MagickExport MagickBooleanType FxPreprocessExpression(FxInfo *fx_info,
double *alpha,ExceptionInfo *exception)
{
FILE
*file;
MagickBooleanType
status;
file=fx_info->file;
fx_info->file=(FILE *) NULL;
status=FxEvaluateChannelExpression(fx_info,GrayChannel,0,0,alpha,exception);
fx_info->file=file;
return(status);
}
MagickExport MagickBooleanType FxEvaluateChannelExpression(FxInfo *fx_info,
const ChannelType channel,const ssize_t x,const ssize_t y,double *alpha,
ExceptionInfo *exception)
{
double
beta;
beta=0.0;
*alpha=FxEvaluateSubexpression(fx_info,channel,x,y,fx_info->expression,0,
&beta,exception);
return(exception->severity == OptionError ? MagickFalse : MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% F x I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% FxImage() applies a mathematical expression to the specified image.
%
% The format of the FxImage method is:
%
% Image *FxImage(const Image *image,const char *expression,
% ExceptionInfo *exception)
% Image *FxImageChannel(const Image *image,const ChannelType channel,
% const char *expression,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o channel: the channel.
%
% o expression: A mathematical expression.
%
% o exception: return any errors or warnings in this structure.
%
*/
static FxInfo **DestroyFxThreadSet(FxInfo **fx_info)
{
register ssize_t
i;
assert(fx_info != (FxInfo **) NULL);
for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++)
if (fx_info[i] != (FxInfo *) NULL)
fx_info[i]=DestroyFxInfo(fx_info[i]);
fx_info=(FxInfo **) RelinquishMagickMemory(fx_info);
return(fx_info);
}
static FxInfo **AcquireFxThreadSet(const Image *image,const char *expression,
ExceptionInfo *exception)
{
char
*fx_expression;
double
alpha;
FxInfo
**fx_info;
register ssize_t
i;
size_t
number_threads;
number_threads=(size_t) GetMagickResourceLimit(ThreadResource);
fx_info=(FxInfo **) AcquireQuantumMemory(number_threads,sizeof(*fx_info));
if (fx_info == (FxInfo **) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
return((FxInfo **) NULL);
}
(void) memset(fx_info,0,number_threads*sizeof(*fx_info));
if (*expression != '@')
fx_expression=ConstantString(expression);
else
fx_expression=FileToString(expression+1,~0UL,exception);
for (i=0; i < (ssize_t) number_threads; i++)
{
MagickBooleanType
status;
fx_info[i]=AcquireFxInfo(image,fx_expression);
if (fx_info[i] == (FxInfo *) NULL)
break;
status=FxPreprocessExpression(fx_info[i],&alpha,exception);
if (status == MagickFalse)
break;
}
fx_expression=DestroyString(fx_expression);
if (i < (ssize_t) number_threads)
fx_info=DestroyFxThreadSet(fx_info);
return(fx_info);
}
MagickExport Image *FxImage(const Image *image,const char *expression,
ExceptionInfo *exception)
{
Image
*fx_image;
fx_image=FxImageChannel(image,GrayChannel,expression,exception);
return(fx_image);
}
MagickExport Image *FxImageChannel(const Image *image,const ChannelType channel,
const char *expression,ExceptionInfo *exception)
{
#define FxImageTag "Fx/Image"
CacheView
*fx_view;
FxInfo
**magick_restrict fx_info;
Image
*fx_image;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (expression == (const char *) NULL)
return(CloneImage(image,0,0,MagickTrue,exception));
fx_info=AcquireFxThreadSet(image,expression,exception);
if (fx_info == (FxInfo **) NULL)
return((Image *) NULL);
fx_image=CloneImage(image,0,0,MagickTrue,exception);
if (fx_image == (Image *) NULL)
{
fx_info=DestroyFxThreadSet(fx_info);
return((Image *) NULL);
}
if (SetImageStorageClass(fx_image,DirectClass) == MagickFalse)
{
InheritException(exception,&fx_image->exception);
fx_info=DestroyFxThreadSet(fx_info);
fx_image=DestroyImage(fx_image);
return((Image *) NULL);
}
/*
Fx image.
*/
status=MagickTrue;
progress=0;
fx_view=AcquireAuthenticCacheView(fx_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,fx_image,fx_image->rows,1)
#endif
for (y=0; y < (ssize_t) fx_image->rows; y++)
{
const int
id = GetOpenMPThreadId();
double
alpha;
register IndexPacket
*magick_restrict fx_indexes;
register ssize_t
x;
register PixelPacket
*magick_restrict q;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(fx_view,0,y,fx_image->columns,1,exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
fx_indexes=GetCacheViewAuthenticIndexQueue(fx_view);
alpha=0.0;
for (x=0; x < (ssize_t) fx_image->columns; x++)
{
if ((channel & RedChannel) != 0)
{
(void) FxEvaluateChannelExpression(fx_info[id],RedChannel,x,y,
&alpha,exception);
SetPixelRed(q,ClampToQuantum((MagickRealType) QuantumRange*alpha));
}
if ((channel & GreenChannel) != 0)
{
(void) FxEvaluateChannelExpression(fx_info[id],GreenChannel,x,y,
&alpha,exception);
SetPixelGreen(q,ClampToQuantum((MagickRealType) QuantumRange*alpha));
}
if ((channel & BlueChannel) != 0)
{
(void) FxEvaluateChannelExpression(fx_info[id],BlueChannel,x,y,
&alpha,exception);
SetPixelBlue(q,ClampToQuantum((MagickRealType) QuantumRange*alpha));
}
if ((channel & OpacityChannel) != 0)
{
(void) FxEvaluateChannelExpression(fx_info[id],OpacityChannel,x,y,
&alpha,exception);
if (image->matte == MagickFalse)
SetPixelOpacity(q,ClampToQuantum((MagickRealType) QuantumRange*
alpha));
else
SetPixelOpacity(q,ClampToQuantum((MagickRealType) (QuantumRange-
QuantumRange*alpha)));
}
if (((channel & IndexChannel) != 0) &&
(fx_image->colorspace == CMYKColorspace))
{
(void) FxEvaluateChannelExpression(fx_info[id],IndexChannel,x,y,
&alpha,exception);
SetPixelIndex(fx_indexes+x,ClampToQuantum((MagickRealType)
QuantumRange*alpha));
}
q++;
}
if (SyncCacheViewAuthenticPixels(fx_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,FxImageTag,progress++,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
fx_view=DestroyCacheView(fx_view);
fx_info=DestroyFxThreadSet(fx_info);
if (status == MagickFalse)
fx_image=DestroyImage(fx_image);
return(fx_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I m p l o d e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ImplodeImage() creates a new image that is a copy of an existing
% one with the image pixels "implode" by the specified percentage. It
% allocates the memory necessary for the new Image structure and returns a
% pointer to the new image.
%
% The format of the ImplodeImage method is:
%
% Image *ImplodeImage(const Image *image,const double amount,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o implode_image: Method ImplodeImage returns a pointer to the image
% after it is implode. A null image is returned if there is a memory
% shortage.
%
% o image: the image.
%
% o amount: Define the extent of the implosion.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *ImplodeImage(const Image *image,const double amount,
ExceptionInfo *exception)
{
#define ImplodeImageTag "Implode/Image"
CacheView
*image_view,
*implode_view;
double
radius;
Image
*implode_image;
MagickBooleanType
status;
MagickOffsetType
progress;
MagickPixelPacket
zero;
PointInfo
center,
scale;
ssize_t
y;
/*
Initialize implode image attributes.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
implode_image=CloneImage(image,0,0,MagickTrue,exception);
if (implode_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(implode_image,DirectClass) == MagickFalse)
{
InheritException(exception,&implode_image->exception);
implode_image=DestroyImage(implode_image);
return((Image *) NULL);
}
if (implode_image->background_color.opacity != OpaqueOpacity)
implode_image->matte=MagickTrue;
/*
Compute scaling factor.
*/
scale.x=1.0;
scale.y=1.0;
center.x=0.5*image->columns;
center.y=0.5*image->rows;
radius=center.x;
if (image->columns > image->rows)
scale.y=(double) image->columns/(double) image->rows;
else
if (image->columns < image->rows)
{
scale.x=(double) image->rows/(double) image->columns;
radius=center.y;
}
/*
Implode image.
*/
status=MagickTrue;
progress=0;
GetMagickPixelPacket(implode_image,&zero);
image_view=AcquireVirtualCacheView(image,exception);
implode_view=AcquireAuthenticCacheView(implode_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,implode_image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
double
distance;
MagickPixelPacket
pixel;
PointInfo
delta;
register IndexPacket
*magick_restrict implode_indexes;
register ssize_t
x;
register PixelPacket
*magick_restrict q;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(implode_view,0,y,implode_image->columns,1,
exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
implode_indexes=GetCacheViewAuthenticIndexQueue(implode_view);
delta.y=scale.y*(double) (y-center.y);
pixel=zero;
for (x=0; x < (ssize_t) image->columns; x++)
{
/*
Determine if the pixel is within an ellipse.
*/
delta.x=scale.x*(double) (x-center.x);
distance=delta.x*delta.x+delta.y*delta.y;
if (distance < (radius*radius))
{
double
factor;
/*
Implode the pixel.
*/
factor=1.0;
if (distance > 0.0)
factor=pow(sin((double) (MagickPI*sqrt((double) distance)/
radius/2)),-amount);
status=InterpolateMagickPixelPacket(image,image_view,
UndefinedInterpolatePixel,(double) (factor*delta.x/scale.x+
center.x),(double) (factor*delta.y/scale.y+center.y),&pixel,
exception);
if (status == MagickFalse)
break;
SetPixelPacket(implode_image,&pixel,q,implode_indexes+x);
}
q++;
}
if (SyncCacheViewAuthenticPixels(implode_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,ImplodeImageTag,progress++,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
implode_view=DestroyCacheView(implode_view);
image_view=DestroyCacheView(image_view);
if (status == MagickFalse)
implode_image=DestroyImage(implode_image);
return(implode_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% M o r p h I m a g e s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% The MorphImages() method requires a minimum of two images. The first
% image is transformed into the second by a number of intervening images
% as specified by frames.
%
% The format of the MorphImage method is:
%
% Image *MorphImages(const Image *image,const size_t number_frames,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o number_frames: Define the number of in-between image to generate.
% The more in-between frames, the smoother the morph.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *MorphImages(const Image *image,
const size_t number_frames,ExceptionInfo *exception)
{
#define MorphImageTag "Morph/Image"
double
alpha,
beta;
Image
*morph_image,
*morph_images;
MagickBooleanType
status;
MagickOffsetType
scene;
register const Image
*next;
register ssize_t
i;
ssize_t
y;
/*
Clone first frame in sequence.
*/
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);
morph_images=CloneImage(image,0,0,MagickTrue,exception);
if (morph_images == (Image *) NULL)
return((Image *) NULL);
if (GetNextImageInList(image) == (Image *) NULL)
{
/*
Morph single image.
*/
for (i=1; i < (ssize_t) number_frames; i++)
{
morph_image=CloneImage(image,0,0,MagickTrue,exception);
if (morph_image == (Image *) NULL)
{
morph_images=DestroyImageList(morph_images);
return((Image *) NULL);
}
AppendImageToList(&morph_images,morph_image);
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,MorphImageTag,(MagickOffsetType) i,
number_frames);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
return(GetFirstImageInList(morph_images));
}
/*
Morph image sequence.
*/
status=MagickTrue;
scene=0;
next=image;
for ( ; GetNextImageInList(next) != (Image *) NULL; next=GetNextImageInList(next))
{
for (i=0; i < (ssize_t) number_frames; i++)
{
CacheView
*image_view,
*morph_view;
beta=(double) (i+1.0)/(double) (number_frames+1.0);
alpha=1.0-beta;
morph_image=ResizeImage(next,(size_t) (alpha*next->columns+beta*
GetNextImageInList(next)->columns+0.5),(size_t) (alpha*
next->rows+beta*GetNextImageInList(next)->rows+0.5),
next->filter,next->blur,exception);
if (morph_image == (Image *) NULL)
{
morph_images=DestroyImageList(morph_images);
return((Image *) NULL);
}
if (SetImageStorageClass(morph_image,DirectClass) == MagickFalse)
{
InheritException(exception,&morph_image->exception);
morph_image=DestroyImage(morph_image);
return((Image *) NULL);
}
AppendImageToList(&morph_images,morph_image);
morph_images=GetLastImageInList(morph_images);
morph_image=ResizeImage(GetNextImageInList(next),morph_images->columns,
morph_images->rows,GetNextImageInList(next)->filter,
GetNextImageInList(next)->blur,exception);
if (morph_image == (Image *) NULL)
{
morph_images=DestroyImageList(morph_images);
return((Image *) NULL);
}
image_view=AcquireVirtualCacheView(morph_image,exception);
morph_view=AcquireAuthenticCacheView(morph_images,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(morph_image,morph_image,morph_image->rows,1)
#endif
for (y=0; y < (ssize_t) morph_images->rows; y++)
{
MagickBooleanType
sync;
register const PixelPacket
*magick_restrict p;
register ssize_t
x;
register PixelPacket
*magick_restrict q;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,morph_image->columns,1,
exception);
q=GetCacheViewAuthenticPixels(morph_view,0,y,morph_images->columns,1,
exception);
if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) morph_images->columns; x++)
{
SetPixelRed(q,ClampToQuantum(alpha*
GetPixelRed(q)+beta*GetPixelRed(p)));
SetPixelGreen(q,ClampToQuantum(alpha*
GetPixelGreen(q)+beta*GetPixelGreen(p)));
SetPixelBlue(q,ClampToQuantum(alpha*
GetPixelBlue(q)+beta*GetPixelBlue(p)));
SetPixelOpacity(q,ClampToQuantum(alpha*
GetPixelOpacity(q)+beta*GetPixelOpacity(p)));
p++;
q++;
}
sync=SyncCacheViewAuthenticPixels(morph_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
}
morph_view=DestroyCacheView(morph_view);
image_view=DestroyCacheView(image_view);
morph_image=DestroyImage(morph_image);
}
if (i < (ssize_t) number_frames)
break;
/*
Clone last frame in sequence.
*/
morph_image=CloneImage(GetNextImageInList(next),0,0,MagickTrue,exception);
if (morph_image == (Image *) NULL)
{
morph_images=DestroyImageList(morph_images);
return((Image *) NULL);
}
AppendImageToList(&morph_images,morph_image);
morph_images=GetLastImageInList(morph_images);
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,MorphImageTag,scene,
GetImageListLength(image));
if (proceed == MagickFalse)
status=MagickFalse;
}
scene++;
}
if (GetNextImageInList(next) != (Image *) NULL)
{
morph_images=DestroyImageList(morph_images);
return((Image *) NULL);
}
return(GetFirstImageInList(morph_images));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% P l a s m a I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% PlasmaImage() initializes an image with plasma fractal values. The image
% must be initialized with a base color and the random number generator
% seeded before this method is called.
%
% The format of the PlasmaImage method is:
%
% MagickBooleanType PlasmaImage(Image *image,const SegmentInfo *segment,
% size_t attenuate,size_t depth)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o segment: Define the region to apply plasma fractals values.
%
% o attenuate: Define the plasma attenuation factor.
%
% o depth: Limit the plasma recursion depth.
%
*/
static inline Quantum PlasmaPixel(RandomInfo *random_info,
const MagickRealType pixel,const double noise)
{
Quantum
plasma;
plasma=ClampToQuantum(pixel+noise*GetPseudoRandomValue(random_info)-
noise/2.0);
if (plasma <= 0)
return((Quantum) 0);
if (plasma >= QuantumRange)
return(QuantumRange);
return(plasma);
}
MagickExport MagickBooleanType PlasmaImageProxy(Image *image,
CacheView *image_view,CacheView *u_view,CacheView *v_view,
RandomInfo *random_info,const SegmentInfo *segment,size_t attenuate,
size_t depth)
{
ExceptionInfo
*exception;
double
plasma;
PixelPacket
u,
v;
ssize_t
x,
x_mid,
y,
y_mid;
if ((fabs(segment->x2-segment->x1) <= MagickEpsilon) &&
(fabs(segment->y2-segment->y1) <= MagickEpsilon))
return(MagickTrue);
if (depth != 0)
{
MagickBooleanType
status;
SegmentInfo
local_info;
/*
Divide the area into quadrants and recurse.
*/
depth--;
attenuate++;
x_mid=(ssize_t) ceil((segment->x1+segment->x2)/2-0.5);
y_mid=(ssize_t) ceil((segment->y1+segment->y2)/2-0.5);
local_info=(*segment);
local_info.x2=(double) x_mid;
local_info.y2=(double) y_mid;
(void) PlasmaImageProxy(image,image_view,u_view,v_view,random_info,
&local_info,attenuate,depth);
local_info=(*segment);
local_info.y1=(double) y_mid;
local_info.x2=(double) x_mid;
(void) PlasmaImageProxy(image,image_view,u_view,v_view,random_info,
&local_info,attenuate,depth);
local_info=(*segment);
local_info.x1=(double) x_mid;
local_info.y2=(double) y_mid;
(void) PlasmaImageProxy(image,image_view,u_view,v_view,random_info,
&local_info,attenuate,depth);
local_info=(*segment);
local_info.x1=(double) x_mid;
local_info.y1=(double) y_mid;
status=PlasmaImageProxy(image,image_view,u_view,v_view,random_info,
&local_info,attenuate,depth);
return(status);
}
x_mid=(ssize_t) ceil((segment->x1+segment->x2)/2-0.5);
y_mid=(ssize_t) ceil((segment->y1+segment->y2)/2-0.5);
if ((fabs(segment->x1-x_mid) < MagickEpsilon) &&
(fabs(segment->x2-x_mid) < MagickEpsilon) &&
(fabs(segment->y1-y_mid) < MagickEpsilon) &&
(fabs(segment->y2-y_mid) < MagickEpsilon))
return(MagickFalse);
/*
Average pixels and apply plasma.
*/
exception=(&image->exception);
plasma=(double) QuantumRange/(2.0*attenuate);
if ((fabs(segment->x1-x_mid) > MagickEpsilon) ||
(fabs(segment->x2-x_mid) > MagickEpsilon))
{
register PixelPacket
*magick_restrict q;
/*
Left pixel.
*/
x=(ssize_t) ceil(segment->x1-0.5);
(void) GetOneCacheViewVirtualPixel(u_view,x,(ssize_t)
ceil(segment->y1-0.5),&u,exception);
(void) GetOneCacheViewVirtualPixel(v_view,x,(ssize_t)
ceil(segment->y2-0.5),&v,exception);
q=QueueCacheViewAuthenticPixels(image_view,x,y_mid,1,1,exception);
if (q == (PixelPacket *) NULL)
return(MagickTrue);
SetPixelRed(q,PlasmaPixel(random_info,(MagickRealType) (u.red+v.red)/2.0,
plasma));
SetPixelGreen(q,PlasmaPixel(random_info,(MagickRealType) (u.green+
v.green)/2.0,plasma));
SetPixelBlue(q,PlasmaPixel(random_info,(MagickRealType) (u.blue+v.blue)/
2.0,plasma));
(void) SyncCacheViewAuthenticPixels(image_view,exception);
if (fabs(segment->x1-segment->x2) > MagickEpsilon)
{
/*
Right pixel.
*/
x=(ssize_t) ceil(segment->x2-0.5);
(void) GetOneCacheViewVirtualPixel(u_view,x,(ssize_t)
ceil(segment->y1-0.5),&u,exception);
(void) GetOneCacheViewVirtualPixel(v_view,x,(ssize_t)
ceil(segment->y2-0.5),&v,exception);
q=QueueCacheViewAuthenticPixels(image_view,x,y_mid,1,1,exception);
if (q == (PixelPacket *) NULL)
return(MagickTrue);
SetPixelRed(q,PlasmaPixel(random_info,(MagickRealType) (u.red+v.red)/
2.0,plasma));
SetPixelGreen(q,PlasmaPixel(random_info,(MagickRealType) (u.green+
v.green)/2.0,plasma));
SetPixelBlue(q,PlasmaPixel(random_info,(MagickRealType) (u.blue+
v.blue)/2.0,plasma));
(void) SyncCacheViewAuthenticPixels(image_view,exception);
}
}
if ((fabs(segment->y1-y_mid) > MagickEpsilon) ||
(fabs(segment->y2-y_mid) > MagickEpsilon))
{
if ((fabs(segment->x1-x_mid) > MagickEpsilon) ||
(fabs(segment->y2-y_mid) > MagickEpsilon))
{
register PixelPacket
*magick_restrict q;
/*
Bottom pixel.
*/
y=(ssize_t) ceil(segment->y2-0.5);
(void) GetOneCacheViewVirtualPixel(u_view,(ssize_t)
ceil(segment->x1-0.5),y,&u,exception);
(void) GetOneCacheViewVirtualPixel(v_view,(ssize_t)
ceil(segment->x2-0.5),y,&v,exception);
q=QueueCacheViewAuthenticPixels(image_view,x_mid,y,1,1,exception);
if (q == (PixelPacket *) NULL)
return(MagickTrue);
SetPixelRed(q,PlasmaPixel(random_info,(MagickRealType) (u.red+v.red)/
2.0,plasma));
SetPixelGreen(q,PlasmaPixel(random_info,(MagickRealType) (u.green+
v.green)/2.0,plasma));
SetPixelBlue(q,PlasmaPixel(random_info,(MagickRealType) (u.blue+
v.blue)/2.0,plasma));
(void) SyncCacheViewAuthenticPixels(image_view,exception);
}
if (fabs(segment->y1-segment->y2) > MagickEpsilon)
{
register PixelPacket
*magick_restrict q;
/*
Top pixel.
*/
y=(ssize_t) ceil(segment->y1-0.5);
(void) GetOneCacheViewVirtualPixel(u_view,(ssize_t)
ceil(segment->x1-0.5),y,&u,exception);
(void) GetOneCacheViewVirtualPixel(v_view,(ssize_t)
ceil(segment->x2-0.5),y,&v,exception);
q=QueueCacheViewAuthenticPixels(image_view,x_mid,y,1,1,exception);
if (q == (PixelPacket *) NULL)
return(MagickTrue);
SetPixelRed(q,PlasmaPixel(random_info,(MagickRealType) (u.red+
v.red)/2.0,plasma));
SetPixelGreen(q,PlasmaPixel(random_info,(MagickRealType) (u.green+
v.green)/2.0,plasma));
SetPixelBlue(q,PlasmaPixel(random_info,(MagickRealType) (u.blue+
v.blue)/2.0,plasma));
(void) SyncCacheViewAuthenticPixels(image_view,exception);
}
}
if ((fabs(segment->x1-segment->x2) > MagickEpsilon) ||
(fabs(segment->y1-segment->y2) > MagickEpsilon))
{
register PixelPacket
*magick_restrict q;
/*
Middle pixel.
*/
x=(ssize_t) ceil(segment->x1-0.5);
y=(ssize_t) ceil(segment->y1-0.5);
(void) GetOneCacheViewVirtualPixel(u_view,x,y,&u,exception);
x=(ssize_t) ceil(segment->x2-0.5);
y=(ssize_t) ceil(segment->y2-0.5);
(void) GetOneCacheViewVirtualPixel(v_view,x,y,&v,exception);
q=QueueCacheViewAuthenticPixels(image_view,x_mid,y_mid,1,1,exception);
if (q == (PixelPacket *) NULL)
return(MagickTrue);
SetPixelRed(q,PlasmaPixel(random_info,(MagickRealType) (u.red+v.red)/2.0,
plasma));
SetPixelGreen(q,PlasmaPixel(random_info,(MagickRealType) (u.green+
v.green)/2.0,plasma));
SetPixelBlue(q,PlasmaPixel(random_info,(MagickRealType) (u.blue+v.blue)/
2.0,plasma));
(void) SyncCacheViewAuthenticPixels(image_view,exception);
}
if ((fabs(segment->x2-segment->x1) < 3.0) &&
(fabs(segment->y2-segment->y1) < 3.0))
return(MagickTrue);
return(MagickFalse);
}
MagickExport MagickBooleanType PlasmaImage(Image *image,
const SegmentInfo *segment,size_t attenuate,size_t depth)
{
CacheView
*image_view,
*u_view,
*v_view;
MagickBooleanType
status;
RandomInfo
*random_info;
assert(image != (Image *) NULL);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
if (SetImageStorageClass(image,DirectClass) == MagickFalse)
return(MagickFalse);
image_view=AcquireAuthenticCacheView(image,&image->exception);
u_view=AcquireVirtualCacheView(image,&image->exception);
v_view=AcquireVirtualCacheView(image,&image->exception);
random_info=AcquireRandomInfo();
status=PlasmaImageProxy(image,image_view,u_view,v_view,random_info,segment,
attenuate,depth);
random_info=DestroyRandomInfo(random_info);
v_view=DestroyCacheView(v_view);
u_view=DestroyCacheView(u_view);
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% P o l a r o i d I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% PolaroidImage() simulates a Polaroid picture.
%
% The format of the AnnotateImage method is:
%
% Image *PolaroidImage(const Image *image,const DrawInfo *draw_info,
% const double angle,ExceptionInfo exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o draw_info: the draw info.
%
% o angle: Apply the effect along this angle.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *PolaroidImage(const Image *image,const DrawInfo *draw_info,
const double angle,ExceptionInfo *exception)
{
const char
*value;
Image
*bend_image,
*caption_image,
*flop_image,
*picture_image,
*polaroid_image,
*rotate_image,
*trim_image;
size_t
height;
ssize_t
quantum;
/*
Simulate a Polaroid picture.
*/
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);
quantum=(ssize_t) MagickMax(MagickMax((double) image->columns,(double)
image->rows)/25.0,10.0);
height=image->rows+2*quantum;
caption_image=(Image *) NULL;
value=GetImageProperty(image,"Caption");
if (value != (const char *) NULL)
{
char
*caption;
/*
Generate caption image.
*/
caption_image=CloneImage(image,image->columns,1,MagickTrue,exception);
if (caption_image == (Image *) NULL)
return((Image *) NULL);
caption=InterpretImageProperties((ImageInfo *) NULL,(Image *) image,
value);
if (caption != (char *) NULL)
{
char
geometry[MaxTextExtent];
DrawInfo
*annotate_info;
MagickBooleanType
status;
ssize_t
count;
TypeMetric
metrics;
annotate_info=CloneDrawInfo((const ImageInfo *) NULL,draw_info);
(void) CloneString(&annotate_info->text,caption);
count=FormatMagickCaption(caption_image,annotate_info,MagickTrue,
&metrics,&caption);
status=SetImageExtent(caption_image,image->columns,(size_t)
((count+1)*(metrics.ascent-metrics.descent)+0.5));
if (status == MagickFalse)
caption_image=DestroyImage(caption_image);
else
{
caption_image->background_color=image->border_color;
(void) SetImageBackgroundColor(caption_image);
(void) CloneString(&annotate_info->text,caption);
(void) FormatLocaleString(geometry,MaxTextExtent,"+0+%.20g",
metrics.ascent);
if (annotate_info->gravity == UndefinedGravity)
(void) CloneString(&annotate_info->geometry,AcquireString(
geometry));
(void) AnnotateImage(caption_image,annotate_info);
height+=caption_image->rows;
}
annotate_info=DestroyDrawInfo(annotate_info);
caption=DestroyString(caption);
}
}
picture_image=CloneImage(image,image->columns+2*quantum,height,MagickTrue,
exception);
if (picture_image == (Image *) NULL)
{
if (caption_image != (Image *) NULL)
caption_image=DestroyImage(caption_image);
return((Image *) NULL);
}
picture_image->background_color=image->border_color;
(void) SetImageBackgroundColor(picture_image);
(void) CompositeImage(picture_image,OverCompositeOp,image,quantum,quantum);
if (caption_image != (Image *) NULL)
{
(void) CompositeImage(picture_image,OverCompositeOp,caption_image,
quantum,(ssize_t) (image->rows+3*quantum/2));
caption_image=DestroyImage(caption_image);
}
(void) QueryColorDatabase("none",&picture_image->background_color,exception);
(void) SetImageAlphaChannel(picture_image,OpaqueAlphaChannel);
rotate_image=RotateImage(picture_image,90.0,exception);
picture_image=DestroyImage(picture_image);
if (rotate_image == (Image *) NULL)
return((Image *) NULL);
picture_image=rotate_image;
bend_image=WaveImage(picture_image,0.01*picture_image->rows,2.0*
picture_image->columns,exception);
picture_image=DestroyImage(picture_image);
if (bend_image == (Image *) NULL)
return((Image *) NULL);
InheritException(&bend_image->exception,exception);
picture_image=bend_image;
rotate_image=RotateImage(picture_image,-90.0,exception);
picture_image=DestroyImage(picture_image);
if (rotate_image == (Image *) NULL)
return((Image *) NULL);
picture_image=rotate_image;
picture_image->background_color=image->background_color;
polaroid_image=ShadowImage(picture_image,80.0,2.0,quantum/3,quantum/3,
exception);
if (polaroid_image == (Image *) NULL)
{
picture_image=DestroyImage(picture_image);
return(picture_image);
}
flop_image=FlopImage(polaroid_image,exception);
polaroid_image=DestroyImage(polaroid_image);
if (flop_image == (Image *) NULL)
{
picture_image=DestroyImage(picture_image);
return(picture_image);
}
polaroid_image=flop_image;
(void) CompositeImage(polaroid_image,OverCompositeOp,picture_image,
(ssize_t) (-0.01*picture_image->columns/2.0),0L);
picture_image=DestroyImage(picture_image);
(void) QueryColorDatabase("none",&polaroid_image->background_color,exception);
rotate_image=RotateImage(polaroid_image,angle,exception);
polaroid_image=DestroyImage(polaroid_image);
if (rotate_image == (Image *) NULL)
return((Image *) NULL);
polaroid_image=rotate_image;
trim_image=TrimImage(polaroid_image,exception);
polaroid_image=DestroyImage(polaroid_image);
if (trim_image == (Image *) NULL)
return((Image *) NULL);
polaroid_image=trim_image;
return(polaroid_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e p i a T o n e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% MagickSepiaToneImage() applies a special effect to the image, similar to the
% effect achieved in a photo darkroom by sepia toning. Threshold ranges from
% 0 to QuantumRange and is a measure of the extent of the sepia toning. A
% threshold of 80% is a good starting point for a reasonable tone.
%
% The format of the SepiaToneImage method is:
%
% Image *SepiaToneImage(const Image *image,const double threshold,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o threshold: the tone threshold.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *SepiaToneImage(const Image *image,const double threshold,
ExceptionInfo *exception)
{
#define SepiaToneImageTag "SepiaTone/Image"
CacheView
*image_view,
*sepia_view;
Image
*sepia_image;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
/*
Initialize sepia-toned 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);
sepia_image=CloneImage(image,0,0,MagickTrue,exception);
if (sepia_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(sepia_image,DirectClass) == MagickFalse)
{
InheritException(exception,&sepia_image->exception);
sepia_image=DestroyImage(sepia_image);
return((Image *) NULL);
}
/*
Tone each row of the image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireVirtualCacheView(image,exception);
sepia_view=AcquireAuthenticCacheView(sepia_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,sepia_image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
register ssize_t
x;
register PixelPacket
*magick_restrict q;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
q=QueueCacheViewAuthenticPixels(sepia_view,0,y,sepia_image->columns,1,
exception);
if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
double
intensity,
tone;
intensity=GetPixelIntensity(image,p);
tone=intensity > threshold ? (double) QuantumRange : intensity+
(double) QuantumRange-threshold;
SetPixelRed(q,ClampToQuantum(tone));
tone=intensity > (7.0*threshold/6.0) ? (double) QuantumRange :
intensity+(double) QuantumRange-7.0*threshold/6.0;
SetPixelGreen(q,ClampToQuantum(tone));
tone=intensity < (threshold/6.0) ? 0 : intensity-threshold/6.0;
SetPixelBlue(q,ClampToQuantum(tone));
tone=threshold/7.0;
if ((double) GetPixelGreen(q) < tone)
SetPixelGreen(q,ClampToQuantum(tone));
if ((double) GetPixelBlue(q) < tone)
SetPixelBlue(q,ClampToQuantum(tone));
SetPixelOpacity(q,GetPixelOpacity(p));
p++;
q++;
}
if (SyncCacheViewAuthenticPixels(sepia_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,SepiaToneImageTag,progress++,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
sepia_view=DestroyCacheView(sepia_view);
image_view=DestroyCacheView(image_view);
(void) NormalizeImage(sepia_image);
(void) ContrastImage(sepia_image,MagickTrue);
if (status == MagickFalse)
sepia_image=DestroyImage(sepia_image);
return(sepia_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S h a d o w I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ShadowImage() simulates a shadow from the specified image and returns it.
%
% The format of the ShadowImage method is:
%
% Image *ShadowImage(const Image *image,const double opacity,
% const double sigma,const ssize_t x_offset,const ssize_t y_offset,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o opacity: percentage transparency.
%
% o sigma: the standard deviation of the Gaussian, in pixels.
%
% o x_offset: the shadow x-offset.
%
% o y_offset: the shadow y-offset.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *ShadowImage(const Image *image,const double opacity,
const double sigma,const ssize_t x_offset,const ssize_t y_offset,
ExceptionInfo *exception)
{
#define ShadowImageTag "Shadow/Image"
CacheView
*image_view;
Image
*border_image,
*clone_image,
*shadow_image;
MagickBooleanType
status;
MagickOffsetType
progress;
RectangleInfo
border_info;
ssize_t
y;
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);
clone_image=CloneImage(image,0,0,MagickTrue,exception);
if (clone_image == (Image *) NULL)
return((Image *) NULL);
if (IsGrayColorspace(image->colorspace) != MagickFalse)
(void) SetImageColorspace(clone_image,sRGBColorspace);
(void) SetImageVirtualPixelMethod(clone_image,EdgeVirtualPixelMethod);
clone_image->compose=OverCompositeOp;
border_info.width=(size_t) floor(2.0*sigma+0.5);
border_info.height=(size_t) floor(2.0*sigma+0.5);
border_info.x=0;
border_info.y=0;
(void) QueryColorDatabase("none",&clone_image->border_color,exception);
border_image=BorderImage(clone_image,&border_info,exception);
clone_image=DestroyImage(clone_image);
if (border_image == (Image *) NULL)
return((Image *) NULL);
if (border_image->matte == MagickFalse)
(void) SetImageAlphaChannel(border_image,OpaqueAlphaChannel);
/*
Shadow image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireAuthenticCacheView(border_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(border_image,border_image,border_image->rows,1)
#endif
for (y=0; y < (ssize_t) border_image->rows; y++)
{
register PixelPacket
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,border_image->columns,1,
exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) border_image->columns; x++)
{
SetPixelRed(q,border_image->background_color.red);
SetPixelGreen(q,border_image->background_color.green);
SetPixelBlue(q,border_image->background_color.blue);
if (border_image->matte == MagickFalse)
SetPixelOpacity(q,border_image->background_color.opacity);
else
SetPixelOpacity(q,ClampToQuantum((double) (QuantumRange-
GetPixelAlpha(q)*opacity/100.0)));
q++;
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,ShadowImageTag,progress++,
border_image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
shadow_image=BlurImageChannel(border_image,AlphaChannel,0.0,sigma,exception);
border_image=DestroyImage(border_image);
if (shadow_image == (Image *) NULL)
return((Image *) NULL);
if (shadow_image->page.width == 0)
shadow_image->page.width=shadow_image->columns;
if (shadow_image->page.height == 0)
shadow_image->page.height=shadow_image->rows;
shadow_image->page.width+=x_offset-(ssize_t) border_info.width;
shadow_image->page.height+=y_offset-(ssize_t) border_info.height;
shadow_image->page.x+=x_offset-(ssize_t) border_info.width;
shadow_image->page.y+=y_offset-(ssize_t) border_info.height;
return(shadow_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S k e t c h I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SketchImage() simulates a pencil sketch. We convolve the image with a
% Gaussian operator of the given radius and standard deviation (sigma). For
% reasonable results, radius should be larger than sigma. Use a radius of 0
% and SketchImage() selects a suitable radius for you. Angle gives the angle
% of the sketch.
%
% The format of the SketchImage method is:
%
% Image *SketchImage(const Image *image,const double radius,
% const double sigma,const double angle,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o radius: the radius of the Gaussian, in pixels, not counting
% the center pixel.
%
% o sigma: the standard deviation of the Gaussian, in pixels.
%
% o angle: Apply the effect along this angle.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *SketchImage(const Image *image,const double radius,
const double sigma,const double angle,ExceptionInfo *exception)
{
CacheView
*random_view;
Image
*blend_image,
*blur_image,
*dodge_image,
*random_image,
*sketch_image;
MagickBooleanType
status;
MagickPixelPacket
zero;
RandomInfo
**magick_restrict random_info;
ssize_t
y;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
unsigned long
key;
#endif
/*
Sketch image.
*/
random_image=CloneImage(image,image->columns << 1,image->rows << 1,
MagickTrue,exception);
if (random_image == (Image *) NULL)
return((Image *) NULL);
random_view=AcquireAuthenticCacheView(random_image,exception);
status=MagickTrue;
GetMagickPixelPacket(random_image,&zero);
random_info=AcquireRandomInfoThreadSet();
random_view=AcquireAuthenticCacheView(random_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
key=GetRandomSecretKey(random_info[0]);
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(random_image,random_image,random_image->rows,key == ~0UL)
#endif
for (y=0; y < (ssize_t) random_image->rows; y++)
{
const int
id = GetOpenMPThreadId();
MagickPixelPacket
pixel;
register IndexPacket
*magick_restrict indexes;
register ssize_t
x;
register PixelPacket
*magick_restrict q;
if (status == MagickFalse)
continue;
q=QueueCacheViewAuthenticPixels(random_view,0,y,random_image->columns,1,
exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewAuthenticIndexQueue(random_view);
pixel=zero;
for (x=0; x < (ssize_t) random_image->columns; x++)
{
pixel.red=(MagickRealType) (QuantumRange*
GetPseudoRandomValue(random_info[id]));
pixel.green=pixel.red;
pixel.blue=pixel.red;
if (image->colorspace == CMYKColorspace)
pixel.index=pixel.red;
SetPixelPacket(random_image,&pixel,q,indexes+x);
q++;
}
if (SyncCacheViewAuthenticPixels(random_view,exception) == MagickFalse)
status=MagickFalse;
}
random_info=DestroyRandomInfoThreadSet(random_info);
if (status == MagickFalse)
{
random_view=DestroyCacheView(random_view);
random_image=DestroyImage(random_image);
return(random_image);
}
random_view=DestroyCacheView(random_view);
blur_image=MotionBlurImage(random_image,radius,sigma,angle,exception);
random_image=DestroyImage(random_image);
if (blur_image == (Image *) NULL)
return((Image *) NULL);
dodge_image=EdgeImage(blur_image,radius,exception);
blur_image=DestroyImage(blur_image);
if (dodge_image == (Image *) NULL)
return((Image *) NULL);
(void) NormalizeImage(dodge_image);
(void) NegateImage(dodge_image,MagickFalse);
(void) TransformImage(&dodge_image,(char *) NULL,"50%");
sketch_image=CloneImage(image,0,0,MagickTrue,exception);
if (sketch_image == (Image *) NULL)
{
dodge_image=DestroyImage(dodge_image);
return((Image *) NULL);
}
(void) CompositeImage(sketch_image,ColorDodgeCompositeOp,dodge_image,0,0);
dodge_image=DestroyImage(dodge_image);
blend_image=CloneImage(image,0,0,MagickTrue,exception);
if (blend_image == (Image *) NULL)
{
sketch_image=DestroyImage(sketch_image);
return((Image *) NULL);
}
(void) SetImageArtifact(blend_image,"compose:args","20x80");
(void) CompositeImage(sketch_image,BlendCompositeOp,blend_image,0,0);
blend_image=DestroyImage(blend_image);
return(sketch_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S o l a r i z e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SolarizeImage() applies a special effect to the image, similar to the effect
% achieved in a photo darkroom by selectively exposing areas of photo
% sensitive paper to light. Threshold ranges from 0 to QuantumRange and is a
% measure of the extent of the solarization.
%
% The format of the SolarizeImage method is:
%
% MagickBooleanType SolarizeImage(Image *image,const double threshold)
% MagickBooleanType SolarizeImageChannel(Image *image,
% const ChannelType channel,const double threshold,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o channel: the channel type.
%
% o threshold: Define the extent of the solarization.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType SolarizeImage(Image *image,
const double threshold)
{
MagickBooleanType
status;
status=SolarizeImageChannel(image,DefaultChannels,threshold,
&image->exception);
return(status);
}
MagickExport MagickBooleanType SolarizeImageChannel(Image *image,
const ChannelType channel,const double threshold,ExceptionInfo *exception)
{
#define SolarizeImageTag "Solarize/Image"
CacheView
*image_view;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (IsGrayColorspace(image->colorspace) != MagickFalse)
(void) SetImageColorspace(image,sRGBColorspace);
if (image->storage_class == PseudoClass)
{
register ssize_t
i;
/*
Solarize colormap.
*/
for (i=0; i < (ssize_t) image->colors; i++)
{
if ((channel & RedChannel) != 0)
if ((double) image->colormap[i].red > threshold)
image->colormap[i].red=QuantumRange-image->colormap[i].red;
if ((channel & GreenChannel) != 0)
if ((double) image->colormap[i].green > threshold)
image->colormap[i].green=QuantumRange-image->colormap[i].green;
if ((channel & BlueChannel) != 0)
if ((double) image->colormap[i].blue > threshold)
image->colormap[i].blue=QuantumRange-image->colormap[i].blue;
}
}
/*
Solarize image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register ssize_t
x;
register PixelPacket
*magick_restrict q;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
if ((channel & RedChannel) != 0)
if ((double) GetPixelRed(q) > threshold)
SetPixelRed(q,QuantumRange-GetPixelRed(q));
if ((channel & GreenChannel) != 0)
if ((double) GetPixelGreen(q) > threshold)
SetPixelGreen(q,QuantumRange-GetPixelGreen(q));
if ((channel & BlueChannel) != 0)
if ((double) GetPixelBlue(q) > threshold)
SetPixelBlue(q,QuantumRange-GetPixelBlue(q));
q++;
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,SolarizeImageTag,progress++,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S t e g a n o I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SteganoImage() hides a digital watermark within the image. Recover
% the hidden watermark later to prove that the authenticity of an image.
% Offset defines the start position within the image to hide the watermark.
%
% The format of the SteganoImage method is:
%
% Image *SteganoImage(const Image *image,Image *watermark,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o watermark: the watermark image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *SteganoImage(const Image *image,const Image *watermark,
ExceptionInfo *exception)
{
#define GetBit(alpha,i) ((((size_t) (alpha) >> (size_t) (i)) & 0x01) != 0)
#define SetBit(alpha,i,set) (alpha)=(Quantum) ((set) != 0 ? (size_t) (alpha) \
| (one << (size_t) (i)) : (size_t) (alpha) & ~(one << (size_t) (i)))
#define SteganoImageTag "Stegano/Image"
CacheView
*stegano_view,
*watermark_view;
Image
*stegano_image;
int
c;
MagickBooleanType
status;
PixelPacket
pixel;
register PixelPacket
*q;
register ssize_t
x;
size_t
depth,
one;
ssize_t
i,
j,
k,
y;
/*
Initialize steganographic image attributes.
*/
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(watermark != (const Image *) NULL);
assert(watermark->signature == MagickCoreSignature);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
one=1UL;
stegano_image=CloneImage(image,0,0,MagickTrue,exception);
if (stegano_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(stegano_image,DirectClass) == MagickFalse)
{
InheritException(exception,&stegano_image->exception);
stegano_image=DestroyImage(stegano_image);
return((Image *) NULL);
}
stegano_image->depth=MAGICKCORE_QUANTUM_DEPTH;
/*
Hide watermark in low-order bits of image.
*/
c=0;
i=0;
j=0;
depth=stegano_image->depth;
k=image->offset;
status=MagickTrue;
watermark_view=AcquireVirtualCacheView(watermark,exception);
stegano_view=AcquireAuthenticCacheView(stegano_image,exception);
for (i=(ssize_t) depth-1; (i >= 0) && (j < (ssize_t) depth); i--)
{
for (y=0; (y < (ssize_t) watermark->rows) && (j < (ssize_t) depth); y++)
{
for (x=0; (x < (ssize_t) watermark->columns) && (j < (ssize_t) depth); x++)
{
(void) GetOneCacheViewVirtualPixel(watermark_view,x,y,&pixel,exception);
if ((k/(ssize_t) stegano_image->columns) >= (ssize_t) stegano_image->rows)
break;
q=GetCacheViewAuthenticPixels(stegano_view,k % (ssize_t)
stegano_image->columns,k/(ssize_t) stegano_image->columns,1,1,
exception);
if (q == (PixelPacket *) NULL)
break;
switch (c)
{
case 0:
{
SetBit(GetPixelRed(q),j,GetBit(ClampToQuantum(GetPixelIntensity(
image,&pixel)),i));
break;
}
case 1:
{
SetBit(GetPixelGreen(q),j,GetBit(ClampToQuantum(GetPixelIntensity(
image,&pixel)),i));
break;
}
case 2:
{
SetBit(GetPixelBlue(q),j,GetBit(ClampToQuantum(GetPixelIntensity(
image,&pixel)),i));
break;
}
}
if (SyncCacheViewAuthenticPixels(stegano_view,exception) == MagickFalse)
break;
c++;
if (c == 3)
c=0;
k++;
if (k == (ssize_t) (stegano_image->columns*stegano_image->columns))
k=0;
if (k == image->offset)
j++;
}
}
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,SteganoImageTag,(MagickOffsetType)
(depth-i),depth);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
stegano_view=DestroyCacheView(stegano_view);
watermark_view=DestroyCacheView(watermark_view);
if (stegano_image->storage_class == PseudoClass)
(void) SyncImage(stegano_image);
if (status == MagickFalse)
stegano_image=DestroyImage(stegano_image);
return(stegano_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S t e r e o A n a g l y p h I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% StereoAnaglyphImage() combines two images and produces a single image that
% is the composite of a left and right image of a stereo pair. Special
% red-green stereo glasses are required to view this effect.
%
% The format of the StereoAnaglyphImage method is:
%
% Image *StereoImage(const Image *left_image,const Image *right_image,
% ExceptionInfo *exception)
% Image *StereoAnaglyphImage(const Image *left_image,
% const Image *right_image,const ssize_t x_offset,const ssize_t y_offset,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o left_image: the left image.
%
% o right_image: the right image.
%
% o exception: return any errors or warnings in this structure.
%
% o x_offset: amount, in pixels, by which the left image is offset to the
% right of the right image.
%
% o y_offset: amount, in pixels, by which the left image is offset to the
% bottom of the right image.
%
%
*/
MagickExport Image *StereoImage(const Image *left_image,
const Image *right_image,ExceptionInfo *exception)
{
return(StereoAnaglyphImage(left_image,right_image,0,0,exception));
}
MagickExport Image *StereoAnaglyphImage(const Image *left_image,
const Image *right_image,const ssize_t x_offset,const ssize_t y_offset,
ExceptionInfo *exception)
{
#define StereoImageTag "Stereo/Image"
const Image
*image;
Image
*stereo_image;
MagickBooleanType
status;
ssize_t
y;
assert(left_image != (const Image *) NULL);
assert(left_image->signature == MagickCoreSignature);
if (left_image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
left_image->filename);
assert(right_image != (const Image *) NULL);
assert(right_image->signature == MagickCoreSignature);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=left_image;
if ((left_image->columns != right_image->columns) ||
(left_image->rows != right_image->rows))
ThrowImageException(ImageError,"LeftAndRightImageSizesDiffer");
/*
Initialize stereo image attributes.
*/
stereo_image=CloneImage(left_image,left_image->columns,left_image->rows,
MagickTrue,exception);
if (stereo_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(stereo_image,DirectClass) == MagickFalse)
{
InheritException(exception,&stereo_image->exception);
stereo_image=DestroyImage(stereo_image);
return((Image *) NULL);
}
(void) SetImageColorspace(stereo_image,sRGBColorspace);
/*
Copy left image to red channel and right image to blue channel.
*/
status=MagickTrue;
for (y=0; y < (ssize_t) stereo_image->rows; y++)
{
register const PixelPacket
*magick_restrict p,
*magick_restrict q;
register ssize_t
x;
register PixelPacket
*magick_restrict r;
p=GetVirtualPixels(left_image,-x_offset,y-y_offset,image->columns,1,
exception);
q=GetVirtualPixels(right_image,0,y,right_image->columns,1,exception);
r=QueueAuthenticPixels(stereo_image,0,y,stereo_image->columns,1,exception);
if ((p == (PixelPacket *) NULL) || (q == (PixelPacket *) NULL) ||
(r == (PixelPacket *) NULL))
break;
for (x=0; x < (ssize_t) stereo_image->columns; x++)
{
SetPixelRed(r,GetPixelRed(p));
SetPixelGreen(r,GetPixelGreen(q));
SetPixelBlue(r,GetPixelBlue(q));
SetPixelOpacity(r,(GetPixelOpacity(p)+q->opacity)/2);
p++;
q++;
r++;
}
if (SyncAuthenticPixels(stereo_image,exception) == MagickFalse)
break;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,StereoImageTag,(MagickOffsetType) y,
stereo_image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
if (status == MagickFalse)
stereo_image=DestroyImage(stereo_image);
return(stereo_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S w i r l I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SwirlImage() swirls the pixels about the center of the image, where
% degrees indicates the sweep of the arc through which each pixel is moved.
% You get a more dramatic effect as the degrees move from 1 to 360.
%
% The format of the SwirlImage method is:
%
% Image *SwirlImage(const Image *image,double degrees,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o degrees: Define the tightness of the swirling effect.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *SwirlImage(const Image *image,double degrees,
ExceptionInfo *exception)
{
#define SwirlImageTag "Swirl/Image"
CacheView
*image_view,
*swirl_view;
double
radius;
Image
*swirl_image;
MagickBooleanType
status;
MagickOffsetType
progress;
MagickPixelPacket
zero;
PointInfo
center,
scale;
ssize_t
y;
/*
Initialize swirl 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);
swirl_image=CloneImage(image,0,0,MagickTrue,exception);
if (swirl_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(swirl_image,DirectClass) == MagickFalse)
{
InheritException(exception,&swirl_image->exception);
swirl_image=DestroyImage(swirl_image);
return((Image *) NULL);
}
if (swirl_image->background_color.opacity != OpaqueOpacity)
swirl_image->matte=MagickTrue;
/*
Compute scaling factor.
*/
center.x=(double) image->columns/2.0;
center.y=(double) image->rows/2.0;
radius=MagickMax(center.x,center.y);
scale.x=1.0;
scale.y=1.0;
if (image->columns > image->rows)
scale.y=(double) image->columns/(double) image->rows;
else
if (image->columns < image->rows)
scale.x=(double) image->rows/(double) image->columns;
degrees=(double) DegreesToRadians(degrees);
/*
Swirl image.
*/
status=MagickTrue;
progress=0;
GetMagickPixelPacket(swirl_image,&zero);
image_view=AcquireVirtualCacheView(image,exception);
swirl_view=AcquireAuthenticCacheView(swirl_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,swirl_image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
double
distance;
MagickPixelPacket
pixel;
PointInfo
delta;
register IndexPacket
*magick_restrict swirl_indexes;
register ssize_t
x;
register PixelPacket
*magick_restrict q;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(swirl_view,0,y,swirl_image->columns,1,
exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
swirl_indexes=GetCacheViewAuthenticIndexQueue(swirl_view);
delta.y=scale.y*(double) (y-center.y);
pixel=zero;
for (x=0; x < (ssize_t) image->columns; x++)
{
/*
Determine if the pixel is within an ellipse.
*/
delta.x=scale.x*(double) (x-center.x);
distance=delta.x*delta.x+delta.y*delta.y;
if (distance < (radius*radius))
{
double
cosine,
factor,
sine;
/*
Swirl the pixel.
*/
factor=1.0-sqrt(distance)/radius;
sine=sin((double) (degrees*factor*factor));
cosine=cos((double) (degrees*factor*factor));
status=InterpolateMagickPixelPacket(image,image_view,
UndefinedInterpolatePixel,(double) ((cosine*delta.x-sine*delta.y)/
scale.x+center.x),(double) ((sine*delta.x+cosine*delta.y)/scale.y+
center.y),&pixel,exception);
if (status == MagickFalse)
break;
SetPixelPacket(swirl_image,&pixel,q,swirl_indexes+x);
}
q++;
}
if (SyncCacheViewAuthenticPixels(swirl_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,SwirlImageTag,progress++,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
swirl_view=DestroyCacheView(swirl_view);
image_view=DestroyCacheView(image_view);
if (status == MagickFalse)
swirl_image=DestroyImage(swirl_image);
return(swirl_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% T i n t I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% TintImage() applies a color vector to each pixel in the image. The length
% of the vector is 0 for black and white and at its maximum for the midtones.
% The vector weighting function is f(x)=(1-(4.0*((x-0.5)*(x-0.5))))
%
% The format of the TintImage method is:
%
% Image *TintImage(const Image *image,const char *opacity,
% const PixelPacket tint,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o opacity: A color value used for tinting.
%
% o tint: A color value used for tinting.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *TintImage(const Image *image,const char *opacity,
const PixelPacket tint,ExceptionInfo *exception)
{
#define TintImageTag "Tint/Image"
CacheView
*image_view,
*tint_view;
GeometryInfo
geometry_info;
Image
*tint_image;
MagickBooleanType
status;
MagickOffsetType
progress;
MagickPixelPacket
color_vector,
pixel;
MagickStatusType
flags;
ssize_t
y;
/*
Allocate tint image.
*/
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);
tint_image=CloneImage(image,0,0,MagickTrue,exception);
if (tint_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(tint_image,DirectClass) == MagickFalse)
{
InheritException(exception,&tint_image->exception);
tint_image=DestroyImage(tint_image);
return((Image *) NULL);
}
if ((IsGrayColorspace(image->colorspace) != MagickFalse) &&
(IsPixelGray(&tint) == MagickFalse))
(void) SetImageColorspace(tint_image,sRGBColorspace);
if (opacity == (const char *) NULL)
return(tint_image);
/*
Determine RGB values of the tint color.
*/
flags=ParseGeometry(opacity,&geometry_info);
pixel.red=geometry_info.rho;
pixel.green=geometry_info.rho;
pixel.blue=geometry_info.rho;
pixel.opacity=(MagickRealType) OpaqueOpacity;
if ((flags & SigmaValue) != 0)
pixel.green=geometry_info.sigma;
if ((flags & XiValue) != 0)
pixel.blue=geometry_info.xi;
if ((flags & PsiValue) != 0)
pixel.opacity=geometry_info.psi;
color_vector.red=(MagickRealType) (pixel.red*tint.red/100.0-
PixelPacketIntensity(&tint));
color_vector.green=(MagickRealType) (pixel.green*tint.green/100.0-
PixelPacketIntensity(&tint));
color_vector.blue=(MagickRealType) (pixel.blue*tint.blue/100.0-
PixelPacketIntensity(&tint));
/*
Tint image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireVirtualCacheView(image,exception);
tint_view=AcquireAuthenticCacheView(tint_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,tint_image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
register PixelPacket
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
q=QueueCacheViewAuthenticPixels(tint_view,0,y,tint_image->columns,1,
exception);
if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
double
weight;
MagickPixelPacket
pixel;
weight=QuantumScale*GetPixelRed(p)-0.5;
pixel.red=(MagickRealType) GetPixelRed(p)+color_vector.red*(1.0-(4.0*
(weight*weight)));
SetPixelRed(q,ClampToQuantum(pixel.red));
weight=QuantumScale*GetPixelGreen(p)-0.5;
pixel.green=(MagickRealType) GetPixelGreen(p)+color_vector.green*(1.0-
(4.0*(weight*weight)));
SetPixelGreen(q,ClampToQuantum(pixel.green));
weight=QuantumScale*GetPixelBlue(p)-0.5;
pixel.blue=(MagickRealType) GetPixelBlue(p)+color_vector.blue*(1.0-(4.0*
(weight*weight)));
SetPixelBlue(q,ClampToQuantum(pixel.blue));
SetPixelOpacity(q,GetPixelOpacity(p));
p++;
q++;
}
if (SyncCacheViewAuthenticPixels(tint_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,TintImageTag,progress++,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
tint_view=DestroyCacheView(tint_view);
image_view=DestroyCacheView(image_view);
if (status == MagickFalse)
tint_image=DestroyImage(tint_image);
return(tint_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% V i g n e t t e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% VignetteImage() softens the edges of the image in vignette style.
%
% The format of the VignetteImage method is:
%
% Image *VignetteImage(const Image *image,const double radius,
% const double sigma,const ssize_t x,const ssize_t y,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o radius: the radius of the pixel neighborhood.
%
% o sigma: the standard deviation of the Gaussian, in pixels.
%
% o x, y: Define the x and y ellipse offset.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *VignetteImage(const Image *image,const double radius,
const double sigma,const ssize_t x,const ssize_t y,ExceptionInfo *exception)
{
char
ellipse[MaxTextExtent];
DrawInfo
*draw_info;
Image
*blur_image,
*canvas_image,
*oval_image,
*vignette_image;
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);
canvas_image=CloneImage(image,0,0,MagickTrue,exception);
if (canvas_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(canvas_image,DirectClass) == MagickFalse)
{
InheritException(exception,&canvas_image->exception);
canvas_image=DestroyImage(canvas_image);
return((Image *) NULL);
}
canvas_image->matte=MagickTrue;
oval_image=CloneImage(canvas_image,canvas_image->columns,canvas_image->rows,
MagickTrue,exception);
if (oval_image == (Image *) NULL)
{
canvas_image=DestroyImage(canvas_image);
return((Image *) NULL);
}
(void) QueryColorDatabase("#000000",&oval_image->background_color,exception);
(void) SetImageBackgroundColor(oval_image);
draw_info=CloneDrawInfo((const ImageInfo *) NULL,(const DrawInfo *) NULL);
(void) QueryColorDatabase("#ffffff",&draw_info->fill,exception);
(void) QueryColorDatabase("#ffffff",&draw_info->stroke,exception);
(void) FormatLocaleString(ellipse,MaxTextExtent,
"ellipse %g,%g,%g,%g,0.0,360.0",image->columns/2.0,
image->rows/2.0,image->columns/2.0-x,image->rows/2.0-y);
draw_info->primitive=AcquireString(ellipse);
(void) DrawImage(oval_image,draw_info);
draw_info=DestroyDrawInfo(draw_info);
blur_image=BlurImage(oval_image,radius,sigma,exception);
oval_image=DestroyImage(oval_image);
if (blur_image == (Image *) NULL)
{
canvas_image=DestroyImage(canvas_image);
return((Image *) NULL);
}
blur_image->matte=MagickFalse;
(void) CompositeImage(canvas_image,CopyOpacityCompositeOp,blur_image,0,0);
blur_image=DestroyImage(blur_image);
vignette_image=MergeImageLayers(canvas_image,FlattenLayer,exception);
canvas_image=DestroyImage(canvas_image);
if (vignette_image != (Image *) NULL)
(void) TransformImageColorspace(vignette_image,image->colorspace);
return(vignette_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W a v e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WaveImage() creates a "ripple" effect in the image by shifting the pixels
% vertically along a sine wave whose amplitude and wavelength is specified
% by the given parameters.
%
% The format of the WaveImage method is:
%
% Image *WaveImage(const Image *image,const double amplitude,
% const double wave_length,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o amplitude, wave_length: Define the amplitude and wave length of the
% sine wave.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *WaveImage(const Image *image,const double amplitude,
const double wave_length,ExceptionInfo *exception)
{
#define WaveImageTag "Wave/Image"
CacheView
*image_view,
*wave_view;
Image
*wave_image;
MagickBooleanType
status;
MagickOffsetType
progress;
MagickPixelPacket
zero;
MagickRealType
*sine_map;
register ssize_t
i;
ssize_t
y;
/*
Initialize wave image attributes.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
wave_image=CloneImage(image,image->columns,(size_t) (image->rows+2.0*
fabs(amplitude)),MagickTrue,exception);
if (wave_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(wave_image,DirectClass) == MagickFalse)
{
InheritException(exception,&wave_image->exception);
wave_image=DestroyImage(wave_image);
return((Image *) NULL);
}
if (wave_image->background_color.opacity != OpaqueOpacity)
wave_image->matte=MagickTrue;
/*
Allocate sine map.
*/
sine_map=(MagickRealType *) AcquireQuantumMemory((size_t) wave_image->columns,
sizeof(*sine_map));
if (sine_map == (MagickRealType *) NULL)
{
wave_image=DestroyImage(wave_image);
ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
}
for (i=0; i < (ssize_t) wave_image->columns; i++)
sine_map[i]=fabs(amplitude)+amplitude*sin((double) ((2.0*MagickPI*i)/
wave_length));
/*
Wave image.
*/
status=MagickTrue;
progress=0;
GetMagickPixelPacket(wave_image,&zero);
image_view=AcquireVirtualCacheView(image,exception);
wave_view=AcquireAuthenticCacheView(wave_image,exception);
(void) SetCacheViewVirtualPixelMethod(image_view,
BackgroundVirtualPixelMethod);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,wave_image,wave_image->rows,1)
#endif
for (y=0; y < (ssize_t) wave_image->rows; y++)
{
MagickPixelPacket
pixel;
register IndexPacket
*magick_restrict indexes;
register PixelPacket
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=QueueCacheViewAuthenticPixels(wave_view,0,y,wave_image->columns,1,
exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewAuthenticIndexQueue(wave_view);
pixel=zero;
for (x=0; x < (ssize_t) wave_image->columns; x++)
{
status=InterpolateMagickPixelPacket(image,image_view,
UndefinedInterpolatePixel,(double) x,(double) (y-sine_map[x]),&pixel,
exception);
if (status == MagickFalse)
break;
SetPixelPacket(wave_image,&pixel,q,indexes+x);
q++;
}
if (SyncCacheViewAuthenticPixels(wave_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,WaveImageTag,progress++,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
wave_view=DestroyCacheView(wave_view);
image_view=DestroyCacheView(image_view);
sine_map=(MagickRealType *) RelinquishMagickMemory(sine_map);
if (status == MagickFalse)
wave_image=DestroyImage(wave_image);
return(wave_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W a v e l e t D e n o i s e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WaveletDenoiseImage() removes noise from the image using a wavelet
% transform. The wavelet transform is a fast hierarchical scheme for
% processing an image using a set of consecutive lowpass and high_pass filters,
% followed by a decimation. This results in a decomposition into different
% scales which can be regarded as different “frequency bands”, determined by
% the mother wavelet. Adapted from dcraw.c by David Coffin.
%
% The format of the WaveletDenoiseImage method is:
%
% Image *WaveletDenoiseImage(const Image *image,const double threshold,
% const double softness,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o threshold: set the threshold for smoothing.
%
% o softness: attenuate the smoothing threshold.
%
% o exception: return any errors or warnings in this structure.
%
*/
static inline void HatTransform(const float *magick_restrict pixels,
const size_t stride,const size_t extent,const size_t scale,float *kernel)
{
const float
*magick_restrict p,
*magick_restrict q,
*magick_restrict r;
register ssize_t
i;
p=pixels;
q=pixels+scale*stride,
r=pixels+scale*stride;
for (i=0; i < (ssize_t) scale; i++)
{
kernel[i]=0.25f*(*p+(*p)+(*q)+(*r));
p+=stride;
q-=stride;
r+=stride;
}
for ( ; i < (ssize_t) (extent-scale); i++)
{
kernel[i]=0.25f*(2.0f*(*p)+*(p-scale*stride)+*(p+scale*stride));
p+=stride;
}
q=p-scale*stride;
r=pixels+stride*(extent-2);
for ( ; i < (ssize_t) extent; i++)
{
kernel[i]=0.25f*(*p+(*p)+(*q)+(*r));
p+=stride;
q+=stride;
r-=stride;
}
}
MagickExport Image *WaveletDenoiseImage(const Image *image,
const double threshold,const double softness,ExceptionInfo *exception)
{
CacheView
*image_view,
*noise_view;
float
*kernel,
*pixels;
Image
*noise_image;
MagickBooleanType
status;
MagickSizeType
number_pixels;
MemoryInfo
*pixels_info;
size_t
max_channels;
ssize_t
channel;
static const double
noise_levels[]= {
0.8002, 0.2735, 0.1202, 0.0585, 0.0291, 0.0152, 0.0080, 0.0044 };
/*
Initialize noise 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);
noise_image=(Image *) NULL;
#if defined(MAGICKCORE_OPENCL_SUPPORT)
noise_image=AccelerateWaveletDenoiseImage(image,threshold,exception);
if (noise_image != (Image *) NULL)
return(noise_image);
#endif
noise_image=CloneImage(image,0,0,MagickTrue,exception);
if (noise_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(noise_image,DirectClass) == MagickFalse)
{
noise_image=DestroyImage(noise_image);
return((Image *) NULL);
}
if (AcquireMagickResource(WidthResource,3*image->columns) == MagickFalse)
ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
pixels_info=AcquireVirtualMemory(3*image->columns,image->rows*
sizeof(*pixels));
kernel=(float *) AcquireQuantumMemory(MagickMax(image->rows,image->columns)+1,
GetOpenMPMaximumThreads()*sizeof(*kernel));
if ((pixels_info == (MemoryInfo *) NULL) || (kernel == (float *) NULL))
{
if (kernel != (float *) NULL)
kernel=(float *) RelinquishMagickMemory(kernel);
if (pixels_info != (MemoryInfo *) NULL)
pixels_info=RelinquishVirtualMemory(pixels_info);
ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
}
pixels=(float *) GetVirtualMemoryBlob(pixels_info);
status=MagickTrue;
number_pixels=image->columns*image->rows;
max_channels=(size_t) (image->colorspace == CMYKColorspace ? 4 : 3);
image_view=AcquireAuthenticCacheView(image,exception);
noise_view=AcquireAuthenticCacheView(noise_image,exception);
for (channel=0; channel < (ssize_t) max_channels; channel++)
{
register ssize_t
i;
size_t
high_pass,
low_pass;
ssize_t
level,
y;
if (status == MagickFalse)
continue;
/*
Copy channel from image to wavelet pixel array.
*/
i=0;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const IndexPacket
*magick_restrict indexes;
register const PixelPacket
*magick_restrict p;
ssize_t
x;
p=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (p == (const PixelPacket *) NULL)
{
status=MagickFalse;
break;
}
indexes=GetCacheViewVirtualIndexQueue(image_view);
for (x=0; x < (ssize_t) image->columns; x++)
{
switch (channel)
{
case 0: pixels[i]=(float) GetPixelRed(p); break;
case 1: pixels[i]=(float) GetPixelGreen(p); break;
case 2: pixels[i]=(float) GetPixelBlue(p); break;
case 3: pixels[i]=(float) indexes[x]; break;
default: break;
}
i++;
p++;
}
}
/*
Low pass filter outputs are called approximation kernel & high pass
filters are referred to as detail kernel. The detail kernel
have high values in the noisy parts of the signal.
*/
high_pass=0;
for (level=0; level < 5; level++)
{
double
magnitude;
ssize_t
x,
y;
low_pass=(size_t) (number_pixels*((level & 0x01)+1));
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,1) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
const int
id = GetOpenMPThreadId();
register float
*magick_restrict p,
*magick_restrict q;
register ssize_t
x;
p=kernel+id*image->columns;
q=pixels+y*image->columns;
HatTransform(q+high_pass,1,image->columns,(size_t) (1UL << level),p);
q+=low_pass;
for (x=0; x < (ssize_t) image->columns; x++)
*q++=(*p++);
}
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,1) \
magick_number_threads(image,image,image->columns,1)
#endif
for (x=0; x < (ssize_t) image->columns; x++)
{
const int
id = GetOpenMPThreadId();
register float
*magick_restrict p,
*magick_restrict q;
register ssize_t
y;
p=kernel+id*image->rows;
q=pixels+x+low_pass;
HatTransform(q,image->columns,image->rows,(size_t) (1UL << level),p);
for (y=0; y < (ssize_t) image->rows; y++)
{
*q=(*p++);
q+=image->columns;
}
}
/*
To threshold, each coefficient is compared to a threshold value and
attenuated / shrunk by some factor.
*/
magnitude=threshold*noise_levels[level];
for (i=0; i < (ssize_t) number_pixels; ++i)
{
pixels[high_pass+i]-=pixels[low_pass+i];
if (pixels[high_pass+i] < -magnitude)
pixels[high_pass+i]+=magnitude-softness*magnitude;
else
if (pixels[high_pass+i] > magnitude)
pixels[high_pass+i]-=magnitude-softness*magnitude;
else
pixels[high_pass+i]*=softness;
if (high_pass != 0)
pixels[i]+=pixels[high_pass+i];
}
high_pass=low_pass;
}
/*
Reconstruct image from the thresholded wavelet kernel.
*/
i=0;
for (y=0; y < (ssize_t) image->rows; y++)
{
MagickBooleanType
sync;
register IndexPacket
*magick_restrict noise_indexes;
register PixelPacket
*magick_restrict q;
register ssize_t
x;
q=GetCacheViewAuthenticPixels(noise_view,0,y,noise_image->columns,1,
exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
break;
}
noise_indexes=GetCacheViewAuthenticIndexQueue(noise_view);
for (x=0; x < (ssize_t) image->columns; x++)
{
float
pixel;
pixel=pixels[i]+pixels[low_pass+i];
switch (channel)
{
case 0: SetPixelRed(q,ClampToQuantum(pixel)); break;
case 1: SetPixelGreen(q,ClampToQuantum(pixel)); break;
case 2: SetPixelBlue(q,ClampToQuantum(pixel)); break;
case 3: SetPixelIndex(noise_indexes+x,ClampToQuantum(pixel)); break;
default: break;
}
i++;
q++;
}
sync=SyncCacheViewAuthenticPixels(noise_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
}
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,AddNoiseImageTag,(MagickOffsetType)
channel,max_channels);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
noise_view=DestroyCacheView(noise_view);
image_view=DestroyCacheView(image_view);
kernel=(float *) RelinquishMagickMemory(kernel);
pixels_info=RelinquishVirtualMemory(pixels_info);
return(noise_image);
}
|
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] = 24;
tile_size[1] = 24;
tile_size[2] = 16;
tile_size[3] = 64;
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;
}
|
fourier.c | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% FFFFF OOO U U RRRR IIIII EEEEE RRRR %
% F O O U U R R I E R R %
% FFF O O U U RRRR I EEE RRRR %
% F O O U U R R I E R R %
% F OOO UUU R R IIIII EEEEE R R %
% %
% %
% MagickCore Discrete Fourier Transform Methods %
% %
% Software Design %
% Sean Burke %
% Fred Weinhaus %
% Cristy %
% July 2009 %
% %
% %
% 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://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/attribute.h"
#include "MagickCore/blob.h"
#include "MagickCore/cache.h"
#include "MagickCore/image.h"
#include "MagickCore/image-private.h"
#include "MagickCore/list.h"
#include "MagickCore/fourier.h"
#include "MagickCore/log.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/property.h"
#include "MagickCore/quantum-private.h"
#include "MagickCore/resource_.h"
#include "MagickCore/string-private.h"
#include "MagickCore/thread-private.h"
#if defined(MAGICKCORE_FFTW_DELEGATE)
#if defined(MAGICKCORE_HAVE_COMPLEX_H)
#include <complex.h>
#endif
#include <fftw3.h>
#if !defined(MAGICKCORE_HAVE_CABS)
#define cabs(z) (sqrt(z[0]*z[0]+z[1]*z[1]))
#endif
#if !defined(MAGICKCORE_HAVE_CARG)
#define carg(z) (atan2(cimag(z),creal(z)))
#endif
#if !defined(MAGICKCORE_HAVE_CIMAG)
#define cimag(z) (z[1])
#endif
#if !defined(MAGICKCORE_HAVE_CREAL)
#define creal(z) (z[0])
#endif
#endif
/*
Typedef declarations.
*/
typedef struct _FourierInfo
{
PixelChannel
channel;
MagickBooleanType
modulus;
size_t
width,
height;
ssize_t
center;
} FourierInfo;
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C o m p l e x I m a g e s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ComplexImages() performs complex mathematics on an image sequence.
%
% The format of the ComplexImages method is:
%
% MagickBooleanType ComplexImages(Image *images,const ComplexOperator op,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o op: A complex operator.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *ComplexImages(const Image *images,const ComplexOperator op,
ExceptionInfo *exception)
{
#define ComplexImageTag "Complex/Image"
CacheView
*Ai_view,
*Ar_view,
*Bi_view,
*Br_view,
*Ci_view,
*Cr_view;
const char
*artifact;
const Image
*Ai_image,
*Ar_image,
*Bi_image,
*Br_image;
double
snr;
Image
*Ci_image,
*complex_images,
*Cr_image,
*image;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
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);
if (images->next == (Image *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),ImageError,
"ImageSequenceRequired","`%s'",images->filename);
return((Image *) NULL);
}
image=CloneImage(images,0,0,MagickTrue,exception);
if (image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
{
image=DestroyImageList(image);
return(image);
}
image->depth=32UL;
complex_images=NewImageList();
AppendImageToList(&complex_images,image);
image=CloneImage(images,0,0,MagickTrue,exception);
if (image == (Image *) NULL)
{
complex_images=DestroyImageList(complex_images);
return(complex_images);
}
AppendImageToList(&complex_images,image);
/*
Apply complex mathematics to image pixels.
*/
artifact=GetImageArtifact(image,"complex:snr");
snr=0.0;
if (artifact != (const char *) NULL)
snr=StringToDouble(artifact,(char **) NULL);
Ar_image=images;
Ai_image=images->next;
Br_image=images;
Bi_image=images->next;
if ((images->next->next != (Image *) NULL) &&
(images->next->next->next != (Image *) NULL))
{
Br_image=images->next->next;
Bi_image=images->next->next->next;
}
Cr_image=complex_images;
Ci_image=complex_images->next;
Ar_view=AcquireVirtualCacheView(Ar_image,exception);
Ai_view=AcquireVirtualCacheView(Ai_image,exception);
Br_view=AcquireVirtualCacheView(Br_image,exception);
Bi_view=AcquireVirtualCacheView(Bi_image,exception);
Cr_view=AcquireAuthenticCacheView(Cr_image,exception);
Ci_view=AcquireAuthenticCacheView(Ci_image,exception);
status=MagickTrue;
progress=0;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(images,complex_images,images->rows,1L)
#endif
for (y=0; y < (ssize_t) images->rows; y++)
{
register const Quantum
*magick_restrict Ai,
*magick_restrict Ar,
*magick_restrict Bi,
*magick_restrict Br;
register Quantum
*magick_restrict Ci,
*magick_restrict Cr;
register ssize_t
x;
if (status == MagickFalse)
continue;
Ar=GetCacheViewVirtualPixels(Ar_view,0,y,Ar_image->columns,1,exception);
Ai=GetCacheViewVirtualPixels(Ai_view,0,y,Ai_image->columns,1,exception);
Br=GetCacheViewVirtualPixels(Br_view,0,y,Br_image->columns,1,exception);
Bi=GetCacheViewVirtualPixels(Bi_view,0,y,Bi_image->columns,1,exception);
Cr=QueueCacheViewAuthenticPixels(Cr_view,0,y,Cr_image->columns,1,exception);
Ci=QueueCacheViewAuthenticPixels(Ci_view,0,y,Ci_image->columns,1,exception);
if ((Ar == (const Quantum *) NULL) || (Ai == (const Quantum *) NULL) ||
(Br == (const Quantum *) NULL) || (Bi == (const Quantum *) NULL) ||
(Cr == (Quantum *) NULL) || (Ci == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) images->columns; x++)
{
register ssize_t
i;
for (i=0; i < (ssize_t) GetPixelChannels(images); i++)
{
switch (op)
{
case AddComplexOperator:
{
Cr[i]=Ar[i]+Br[i];
Ci[i]=Ai[i]+Bi[i];
break;
}
case ConjugateComplexOperator:
default:
{
Cr[i]=Ar[i];
Ci[i]=(-Bi[i]);
break;
}
case DivideComplexOperator:
{
double
gamma;
gamma=PerceptibleReciprocal(Br[i]*Br[i]+Bi[i]*Bi[i]+snr);
Cr[i]=gamma*(Ar[i]*Br[i]+Ai[i]*Bi[i]);
Ci[i]=gamma*(Ai[i]*Br[i]-Ar[i]*Bi[i]);
break;
}
case MagnitudePhaseComplexOperator:
{
Cr[i]=sqrt(Ar[i]*Ar[i]+Ai[i]*Ai[i]);
Ci[i]=atan2(Ai[i],Ar[i])/(2.0*MagickPI)+0.5;
break;
}
case MultiplyComplexOperator:
{
Cr[i]=QuantumScale*(Ar[i]*Br[i]-Ai[i]*Bi[i]);
Ci[i]=QuantumScale*(Ai[i]*Br[i]+Ar[i]*Bi[i]);
break;
}
case RealImaginaryComplexOperator:
{
Cr[i]=Ar[i]*cos(2.0*MagickPI*(Ai[i]-0.5));
Ci[i]=Ar[i]*sin(2.0*MagickPI*(Ai[i]-0.5));
break;
}
case SubtractComplexOperator:
{
Cr[i]=Ar[i]-Br[i];
Ci[i]=Ai[i]-Bi[i];
break;
}
}
}
Ar+=GetPixelChannels(Ar_image);
Ai+=GetPixelChannels(Ai_image);
Br+=GetPixelChannels(Br_image);
Bi+=GetPixelChannels(Bi_image);
Cr+=GetPixelChannels(Cr_image);
Ci+=GetPixelChannels(Ci_image);
}
if (SyncCacheViewAuthenticPixels(Ci_view,exception) == MagickFalse)
status=MagickFalse;
if (SyncCacheViewAuthenticPixels(Cr_view,exception) == MagickFalse)
status=MagickFalse;
if (images->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
proceed=SetImageProgress(images,ComplexImageTag,progress++,
images->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
Cr_view=DestroyCacheView(Cr_view);
Ci_view=DestroyCacheView(Ci_view);
Br_view=DestroyCacheView(Br_view);
Bi_view=DestroyCacheView(Bi_view);
Ar_view=DestroyCacheView(Ar_view);
Ai_view=DestroyCacheView(Ai_view);
if (status == MagickFalse)
complex_images=DestroyImageList(complex_images);
return(complex_images);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% F o r w a r d F o u r i e r T r a n s f o r m I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ForwardFourierTransformImage() implements the discrete Fourier transform
% (DFT) of the image either as a magnitude / phase or real / imaginary image
% pair.
%
% The format of the ForwadFourierTransformImage method is:
%
% Image *ForwardFourierTransformImage(const Image *image,
% const MagickBooleanType modulus,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o modulus: if true, return as transform as a magnitude / phase pair
% otherwise a real / imaginary image pair.
%
% o exception: return any errors or warnings in this structure.
%
*/
#if defined(MAGICKCORE_FFTW_DELEGATE)
static MagickBooleanType RollFourier(const size_t width,const size_t height,
const ssize_t x_offset,const ssize_t y_offset,double *roll_pixels)
{
double
*source_pixels;
MemoryInfo
*source_info;
register ssize_t
i,
x;
ssize_t
u,
v,
y;
/*
Move zero frequency (DC, average color) from (0,0) to (width/2,height/2).
*/
source_info=AcquireVirtualMemory(width,height*sizeof(*source_pixels));
if (source_info == (MemoryInfo *) NULL)
return(MagickFalse);
source_pixels=(double *) GetVirtualMemoryBlob(source_info);
i=0L;
for (y=0L; y < (ssize_t) height; y++)
{
if (y_offset < 0L)
v=((y+y_offset) < 0L) ? y+y_offset+(ssize_t) height : y+y_offset;
else
v=((y+y_offset) > ((ssize_t) height-1L)) ? y+y_offset-(ssize_t) height :
y+y_offset;
for (x=0L; x < (ssize_t) width; x++)
{
if (x_offset < 0L)
u=((x+x_offset) < 0L) ? x+x_offset+(ssize_t) width : x+x_offset;
else
u=((x+x_offset) > ((ssize_t) width-1L)) ? x+x_offset-(ssize_t) width :
x+x_offset;
source_pixels[v*width+u]=roll_pixels[i++];
}
}
(void) memcpy(roll_pixels,source_pixels,height*width*
sizeof(*source_pixels));
source_info=RelinquishVirtualMemory(source_info);
return(MagickTrue);
}
static MagickBooleanType ForwardQuadrantSwap(const size_t width,
const size_t height,double *source_pixels,double *forward_pixels)
{
MagickBooleanType
status;
register ssize_t
x;
ssize_t
center,
y;
/*
Swap quadrants.
*/
center=(ssize_t) (width/2L)+1L;
status=RollFourier((size_t) center,height,0L,(ssize_t) height/2L,
source_pixels);
if (status == MagickFalse)
return(MagickFalse);
for (y=0L; y < (ssize_t) height; y++)
for (x=0L; x < (ssize_t) (width/2L); x++)
forward_pixels[y*width+x+width/2L]=source_pixels[y*center+x];
for (y=1; y < (ssize_t) height; y++)
for (x=0L; x < (ssize_t) (width/2L); x++)
forward_pixels[(height-y)*width+width/2L-x-1L]=
source_pixels[y*center+x+1L];
for (x=0L; x < (ssize_t) (width/2L); x++)
forward_pixels[width/2L-x-1L]=source_pixels[x+1L];
return(MagickTrue);
}
static void CorrectPhaseLHS(const size_t width,const size_t height,
double *fourier_pixels)
{
register ssize_t
x;
ssize_t
y;
for (y=0L; y < (ssize_t) height; y++)
for (x=0L; x < (ssize_t) (width/2L); x++)
fourier_pixels[y*width+x]*=(-1.0);
}
static MagickBooleanType ForwardFourier(const FourierInfo *fourier_info,
Image *image,double *magnitude,double *phase,ExceptionInfo *exception)
{
CacheView
*magnitude_view,
*phase_view;
double
*magnitude_pixels,
*phase_pixels;
Image
*magnitude_image,
*phase_image;
MagickBooleanType
status;
MemoryInfo
*magnitude_info,
*phase_info;
register Quantum
*q;
register ssize_t
x;
ssize_t
i,
y;
magnitude_image=GetFirstImageInList(image);
phase_image=GetNextImageInList(image);
if (phase_image == (Image *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),ImageError,
"ImageSequenceRequired","`%s'",image->filename);
return(MagickFalse);
}
/*
Create "Fourier Transform" image from constituent arrays.
*/
magnitude_info=AcquireVirtualMemory((size_t) fourier_info->width,
fourier_info->height*sizeof(*magnitude_pixels));
phase_info=AcquireVirtualMemory((size_t) fourier_info->width,
fourier_info->height*sizeof(*phase_pixels));
if ((magnitude_info == (MemoryInfo *) NULL) ||
(phase_info == (MemoryInfo *) NULL))
{
if (phase_info != (MemoryInfo *) NULL)
phase_info=RelinquishVirtualMemory(phase_info);
if (magnitude_info != (MemoryInfo *) NULL)
magnitude_info=RelinquishVirtualMemory(magnitude_info);
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
return(MagickFalse);
}
magnitude_pixels=(double *) GetVirtualMemoryBlob(magnitude_info);
(void) memset(magnitude_pixels,0,fourier_info->width*
fourier_info->height*sizeof(*magnitude_pixels));
phase_pixels=(double *) GetVirtualMemoryBlob(phase_info);
(void) memset(phase_pixels,0,fourier_info->width*
fourier_info->height*sizeof(*phase_pixels));
status=ForwardQuadrantSwap(fourier_info->width,fourier_info->height,
magnitude,magnitude_pixels);
if (status != MagickFalse)
status=ForwardQuadrantSwap(fourier_info->width,fourier_info->height,phase,
phase_pixels);
CorrectPhaseLHS(fourier_info->width,fourier_info->height,phase_pixels);
if (fourier_info->modulus != MagickFalse)
{
i=0L;
for (y=0L; y < (ssize_t) fourier_info->height; y++)
for (x=0L; x < (ssize_t) fourier_info->width; x++)
{
phase_pixels[i]/=(2.0*MagickPI);
phase_pixels[i]+=0.5;
i++;
}
}
magnitude_view=AcquireAuthenticCacheView(magnitude_image,exception);
i=0L;
for (y=0L; y < (ssize_t) fourier_info->height; y++)
{
q=GetCacheViewAuthenticPixels(magnitude_view,0L,y,fourier_info->width,1UL,
exception);
if (q == (Quantum *) NULL)
break;
for (x=0L; x < (ssize_t) fourier_info->width; x++)
{
switch (fourier_info->channel)
{
case RedPixelChannel:
default:
{
SetPixelRed(magnitude_image,ClampToQuantum(QuantumRange*
magnitude_pixels[i]),q);
break;
}
case GreenPixelChannel:
{
SetPixelGreen(magnitude_image,ClampToQuantum(QuantumRange*
magnitude_pixels[i]),q);
break;
}
case BluePixelChannel:
{
SetPixelBlue(magnitude_image,ClampToQuantum(QuantumRange*
magnitude_pixels[i]),q);
break;
}
case BlackPixelChannel:
{
SetPixelBlack(magnitude_image,ClampToQuantum(QuantumRange*
magnitude_pixels[i]),q);
break;
}
case AlphaPixelChannel:
{
SetPixelAlpha(magnitude_image,ClampToQuantum(QuantumRange*
magnitude_pixels[i]),q);
break;
}
}
i++;
q+=GetPixelChannels(magnitude_image);
}
status=SyncCacheViewAuthenticPixels(magnitude_view,exception);
if (status == MagickFalse)
break;
}
magnitude_view=DestroyCacheView(magnitude_view);
i=0L;
phase_view=AcquireAuthenticCacheView(phase_image,exception);
for (y=0L; y < (ssize_t) fourier_info->height; y++)
{
q=GetCacheViewAuthenticPixels(phase_view,0L,y,fourier_info->width,1UL,
exception);
if (q == (Quantum *) NULL)
break;
for (x=0L; x < (ssize_t) fourier_info->width; x++)
{
switch (fourier_info->channel)
{
case RedPixelChannel:
default:
{
SetPixelRed(phase_image,ClampToQuantum(QuantumRange*
phase_pixels[i]),q);
break;
}
case GreenPixelChannel:
{
SetPixelGreen(phase_image,ClampToQuantum(QuantumRange*
phase_pixels[i]),q);
break;
}
case BluePixelChannel:
{
SetPixelBlue(phase_image,ClampToQuantum(QuantumRange*
phase_pixels[i]),q);
break;
}
case BlackPixelChannel:
{
SetPixelBlack(phase_image,ClampToQuantum(QuantumRange*
phase_pixels[i]),q);
break;
}
case AlphaPixelChannel:
{
SetPixelAlpha(phase_image,ClampToQuantum(QuantumRange*
phase_pixels[i]),q);
break;
}
}
i++;
q+=GetPixelChannels(phase_image);
}
status=SyncCacheViewAuthenticPixels(phase_view,exception);
if (status == MagickFalse)
break;
}
phase_view=DestroyCacheView(phase_view);
phase_info=RelinquishVirtualMemory(phase_info);
magnitude_info=RelinquishVirtualMemory(magnitude_info);
return(status);
}
static MagickBooleanType ForwardFourierTransform(FourierInfo *fourier_info,
const Image *image,double *magnitude_pixels,double *phase_pixels,
ExceptionInfo *exception)
{
CacheView
*image_view;
const char
*value;
double
*source_pixels;
fftw_complex
*forward_pixels;
fftw_plan
fftw_r2c_plan;
MemoryInfo
*forward_info,
*source_info;
register const Quantum
*p;
register ssize_t
i,
x;
ssize_t
y;
/*
Generate the forward Fourier transform.
*/
source_info=AcquireVirtualMemory((size_t) fourier_info->width,
fourier_info->height*sizeof(*source_pixels));
if (source_info == (MemoryInfo *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
return(MagickFalse);
}
source_pixels=(double *) GetVirtualMemoryBlob(source_info);
memset(source_pixels,0,fourier_info->width*fourier_info->height*
sizeof(*source_pixels));
i=0L;
image_view=AcquireVirtualCacheView(image,exception);
for (y=0L; y < (ssize_t) fourier_info->height; y++)
{
p=GetCacheViewVirtualPixels(image_view,0L,y,fourier_info->width,1UL,
exception);
if (p == (const Quantum *) NULL)
break;
for (x=0L; x < (ssize_t) fourier_info->width; x++)
{
switch (fourier_info->channel)
{
case RedPixelChannel:
default:
{
source_pixels[i]=QuantumScale*GetPixelRed(image,p);
break;
}
case GreenPixelChannel:
{
source_pixels[i]=QuantumScale*GetPixelGreen(image,p);
break;
}
case BluePixelChannel:
{
source_pixels[i]=QuantumScale*GetPixelBlue(image,p);
break;
}
case BlackPixelChannel:
{
source_pixels[i]=QuantumScale*GetPixelBlack(image,p);
break;
}
case AlphaPixelChannel:
{
source_pixels[i]=QuantumScale*GetPixelAlpha(image,p);
break;
}
}
i++;
p+=GetPixelChannels(image);
}
}
image_view=DestroyCacheView(image_view);
forward_info=AcquireVirtualMemory((size_t) fourier_info->width,
(fourier_info->height/2+1)*sizeof(*forward_pixels));
if (forward_info == (MemoryInfo *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
source_info=(MemoryInfo *) RelinquishVirtualMemory(source_info);
return(MagickFalse);
}
forward_pixels=(fftw_complex *) GetVirtualMemoryBlob(forward_info);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_ForwardFourierTransform)
#endif
fftw_r2c_plan=fftw_plan_dft_r2c_2d(fourier_info->width,fourier_info->height,
source_pixels,forward_pixels,FFTW_ESTIMATE);
fftw_execute_dft_r2c(fftw_r2c_plan,source_pixels,forward_pixels);
fftw_destroy_plan(fftw_r2c_plan);
source_info=(MemoryInfo *) RelinquishVirtualMemory(source_info);
value=GetImageArtifact(image,"fourier:normalize");
if ((value == (const char *) NULL) || (LocaleCompare(value,"forward") == 0))
{
double
gamma;
/*
Normalize fourier transform.
*/
i=0L;
gamma=PerceptibleReciprocal((double) fourier_info->width*
fourier_info->height);
for (y=0L; y < (ssize_t) fourier_info->height; y++)
for (x=0L; x < (ssize_t) fourier_info->center; x++)
{
#if defined(MAGICKCORE_HAVE_COMPLEX_H)
forward_pixels[i]*=gamma;
#else
forward_pixels[i][0]*=gamma;
forward_pixels[i][1]*=gamma;
#endif
i++;
}
}
/*
Generate magnitude and phase (or real and imaginary).
*/
i=0L;
if (fourier_info->modulus != MagickFalse)
for (y=0L; y < (ssize_t) fourier_info->height; y++)
for (x=0L; x < (ssize_t) fourier_info->center; x++)
{
magnitude_pixels[i]=cabs(forward_pixels[i]);
phase_pixels[i]=carg(forward_pixels[i]);
i++;
}
else
for (y=0L; y < (ssize_t) fourier_info->height; y++)
for (x=0L; x < (ssize_t) fourier_info->center; x++)
{
magnitude_pixels[i]=creal(forward_pixels[i]);
phase_pixels[i]=cimag(forward_pixels[i]);
i++;
}
forward_info=(MemoryInfo *) RelinquishVirtualMemory(forward_info);
return(MagickTrue);
}
static MagickBooleanType ForwardFourierTransformChannel(const Image *image,
const PixelChannel channel,const MagickBooleanType modulus,
Image *fourier_image,ExceptionInfo *exception)
{
double
*magnitude_pixels,
*phase_pixels;
FourierInfo
fourier_info;
MagickBooleanType
status;
MemoryInfo
*magnitude_info,
*phase_info;
fourier_info.width=image->columns;
fourier_info.height=image->rows;
if ((image->columns != image->rows) || ((image->columns % 2) != 0) ||
((image->rows % 2) != 0))
{
size_t extent=image->columns < image->rows ? image->rows : image->columns;
fourier_info.width=(extent & 0x01) == 1 ? extent+1UL : extent;
}
fourier_info.height=fourier_info.width;
fourier_info.center=(ssize_t) (fourier_info.width/2L)+1L;
fourier_info.channel=channel;
fourier_info.modulus=modulus;
magnitude_info=AcquireVirtualMemory((size_t) fourier_info.width,
(fourier_info.height/2+1)*sizeof(*magnitude_pixels));
phase_info=AcquireVirtualMemory((size_t) fourier_info.width,
(fourier_info.height/2+1)*sizeof(*phase_pixels));
if ((magnitude_info == (MemoryInfo *) NULL) ||
(phase_info == (MemoryInfo *) NULL))
{
if (phase_info != (MemoryInfo *) NULL)
phase_info=RelinquishVirtualMemory(phase_info);
if (magnitude_info == (MemoryInfo *) NULL)
magnitude_info=RelinquishVirtualMemory(magnitude_info);
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
return(MagickFalse);
}
magnitude_pixels=(double *) GetVirtualMemoryBlob(magnitude_info);
phase_pixels=(double *) GetVirtualMemoryBlob(phase_info);
status=ForwardFourierTransform(&fourier_info,image,magnitude_pixels,
phase_pixels,exception);
if (status != MagickFalse)
status=ForwardFourier(&fourier_info,fourier_image,magnitude_pixels,
phase_pixels,exception);
phase_info=RelinquishVirtualMemory(phase_info);
magnitude_info=RelinquishVirtualMemory(magnitude_info);
return(status);
}
#endif
MagickExport Image *ForwardFourierTransformImage(const Image *image,
const MagickBooleanType modulus,ExceptionInfo *exception)
{
Image
*fourier_image;
fourier_image=NewImageList();
#if !defined(MAGICKCORE_FFTW_DELEGATE)
(void) modulus;
(void) ThrowMagickException(exception,GetMagickModule(),
MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn","`%s' (FFTW)",
image->filename);
#else
{
Image
*magnitude_image;
size_t
height,
width;
width=image->columns;
height=image->rows;
if ((image->columns != image->rows) || ((image->columns % 2) != 0) ||
((image->rows % 2) != 0))
{
size_t extent=image->columns < image->rows ? image->rows :
image->columns;
width=(extent & 0x01) == 1 ? extent+1UL : extent;
}
height=width;
magnitude_image=CloneImage(image,width,height,MagickTrue,exception);
if (magnitude_image != (Image *) NULL)
{
Image
*phase_image;
magnitude_image->storage_class=DirectClass;
magnitude_image->depth=32UL;
phase_image=CloneImage(image,width,height,MagickTrue,exception);
if (phase_image == (Image *) NULL)
magnitude_image=DestroyImage(magnitude_image);
else
{
MagickBooleanType
is_gray,
status;
phase_image->storage_class=DirectClass;
phase_image->depth=32UL;
AppendImageToList(&fourier_image,magnitude_image);
AppendImageToList(&fourier_image,phase_image);
status=MagickTrue;
is_gray=IsImageGray(image);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel sections
#endif
{
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp section
#endif
{
MagickBooleanType
thread_status;
if (is_gray != MagickFalse)
thread_status=ForwardFourierTransformChannel(image,
GrayPixelChannel,modulus,fourier_image,exception);
else
thread_status=ForwardFourierTransformChannel(image,
RedPixelChannel,modulus,fourier_image,exception);
if (thread_status == MagickFalse)
status=thread_status;
}
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp section
#endif
{
MagickBooleanType
thread_status;
thread_status=MagickTrue;
if (is_gray == MagickFalse)
thread_status=ForwardFourierTransformChannel(image,
GreenPixelChannel,modulus,fourier_image,exception);
if (thread_status == MagickFalse)
status=thread_status;
}
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp section
#endif
{
MagickBooleanType
thread_status;
thread_status=MagickTrue;
if (is_gray == MagickFalse)
thread_status=ForwardFourierTransformChannel(image,
BluePixelChannel,modulus,fourier_image,exception);
if (thread_status == MagickFalse)
status=thread_status;
}
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp section
#endif
{
MagickBooleanType
thread_status;
thread_status=MagickTrue;
if (image->colorspace == CMYKColorspace)
thread_status=ForwardFourierTransformChannel(image,
BlackPixelChannel,modulus,fourier_image,exception);
if (thread_status == MagickFalse)
status=thread_status;
}
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp section
#endif
{
MagickBooleanType
thread_status;
thread_status=MagickTrue;
if (image->alpha_trait != UndefinedPixelTrait)
thread_status=ForwardFourierTransformChannel(image,
AlphaPixelChannel,modulus,fourier_image,exception);
if (thread_status == MagickFalse)
status=thread_status;
}
}
if (status == MagickFalse)
fourier_image=DestroyImageList(fourier_image);
fftw_cleanup();
}
}
}
#endif
return(fourier_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I n v e r s e F o u r i e r T r a n s f o r m I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% InverseFourierTransformImage() implements the inverse discrete Fourier
% transform (DFT) of the image either as a magnitude / phase or real /
% imaginary image pair.
%
% The format of the InverseFourierTransformImage method is:
%
% Image *InverseFourierTransformImage(const Image *magnitude_image,
% const Image *phase_image,const MagickBooleanType modulus,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o magnitude_image: the magnitude or real image.
%
% o phase_image: the phase or imaginary image.
%
% o modulus: if true, return transform as a magnitude / phase pair
% otherwise a real / imaginary image pair.
%
% o exception: return any errors or warnings in this structure.
%
*/
#if defined(MAGICKCORE_FFTW_DELEGATE)
static MagickBooleanType InverseQuadrantSwap(const size_t width,
const size_t height,const double *source,double *destination)
{
register ssize_t
x;
ssize_t
center,
y;
/*
Swap quadrants.
*/
center=(ssize_t) (width/2L)+1L;
for (y=1L; y < (ssize_t) height; y++)
for (x=0L; x < (ssize_t) (width/2L+1L); x++)
destination[(height-y)*center-x+width/2L]=source[y*width+x];
for (y=0L; y < (ssize_t) height; y++)
destination[y*center]=source[y*width+width/2L];
for (x=0L; x < center; x++)
destination[x]=source[center-x-1L];
return(RollFourier(center,height,0L,(ssize_t) height/-2L,destination));
}
static MagickBooleanType InverseFourier(FourierInfo *fourier_info,
const Image *magnitude_image,const Image *phase_image,
fftw_complex *fourier_pixels,ExceptionInfo *exception)
{
CacheView
*magnitude_view,
*phase_view;
double
*inverse_pixels,
*magnitude_pixels,
*phase_pixels;
MagickBooleanType
status;
MemoryInfo
*inverse_info,
*magnitude_info,
*phase_info;
register const Quantum
*p;
register ssize_t
i,
x;
ssize_t
y;
/*
Inverse fourier - read image and break down into a double array.
*/
magnitude_info=AcquireVirtualMemory((size_t) fourier_info->width,
fourier_info->height*sizeof(*magnitude_pixels));
phase_info=AcquireVirtualMemory((size_t) fourier_info->width,
fourier_info->height*sizeof(*phase_pixels));
inverse_info=AcquireVirtualMemory((size_t) fourier_info->width,
(fourier_info->height/2+1)*sizeof(*inverse_pixels));
if ((magnitude_info == (MemoryInfo *) NULL) ||
(phase_info == (MemoryInfo *) NULL) ||
(inverse_info == (MemoryInfo *) NULL))
{
if (magnitude_info != (MemoryInfo *) NULL)
magnitude_info=RelinquishVirtualMemory(magnitude_info);
if (phase_info != (MemoryInfo *) NULL)
phase_info=RelinquishVirtualMemory(phase_info);
if (inverse_info != (MemoryInfo *) NULL)
inverse_info=RelinquishVirtualMemory(inverse_info);
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",
magnitude_image->filename);
return(MagickFalse);
}
magnitude_pixels=(double *) GetVirtualMemoryBlob(magnitude_info);
phase_pixels=(double *) GetVirtualMemoryBlob(phase_info);
inverse_pixels=(double *) GetVirtualMemoryBlob(inverse_info);
i=0L;
magnitude_view=AcquireVirtualCacheView(magnitude_image,exception);
for (y=0L; y < (ssize_t) fourier_info->height; y++)
{
p=GetCacheViewVirtualPixels(magnitude_view,0L,y,fourier_info->width,1UL,
exception);
if (p == (const Quantum *) NULL)
break;
for (x=0L; x < (ssize_t) fourier_info->width; x++)
{
switch (fourier_info->channel)
{
case RedPixelChannel:
default:
{
magnitude_pixels[i]=QuantumScale*GetPixelRed(magnitude_image,p);
break;
}
case GreenPixelChannel:
{
magnitude_pixels[i]=QuantumScale*GetPixelGreen(magnitude_image,p);
break;
}
case BluePixelChannel:
{
magnitude_pixels[i]=QuantumScale*GetPixelBlue(magnitude_image,p);
break;
}
case BlackPixelChannel:
{
magnitude_pixels[i]=QuantumScale*GetPixelBlack(magnitude_image,p);
break;
}
case AlphaPixelChannel:
{
magnitude_pixels[i]=QuantumScale*GetPixelAlpha(magnitude_image,p);
break;
}
}
i++;
p+=GetPixelChannels(magnitude_image);
}
}
magnitude_view=DestroyCacheView(magnitude_view);
status=InverseQuadrantSwap(fourier_info->width,fourier_info->height,
magnitude_pixels,inverse_pixels);
(void) memcpy(magnitude_pixels,inverse_pixels,fourier_info->height*
fourier_info->center*sizeof(*magnitude_pixels));
i=0L;
phase_view=AcquireVirtualCacheView(phase_image,exception);
for (y=0L; y < (ssize_t) fourier_info->height; y++)
{
p=GetCacheViewVirtualPixels(phase_view,0,y,fourier_info->width,1,
exception);
if (p == (const Quantum *) NULL)
break;
for (x=0L; x < (ssize_t) fourier_info->width; x++)
{
switch (fourier_info->channel)
{
case RedPixelChannel:
default:
{
phase_pixels[i]=QuantumScale*GetPixelRed(phase_image,p);
break;
}
case GreenPixelChannel:
{
phase_pixels[i]=QuantumScale*GetPixelGreen(phase_image,p);
break;
}
case BluePixelChannel:
{
phase_pixels[i]=QuantumScale*GetPixelBlue(phase_image,p);
break;
}
case BlackPixelChannel:
{
phase_pixels[i]=QuantumScale*GetPixelBlack(phase_image,p);
break;
}
case AlphaPixelChannel:
{
phase_pixels[i]=QuantumScale*GetPixelAlpha(phase_image,p);
break;
}
}
i++;
p+=GetPixelChannels(phase_image);
}
}
if (fourier_info->modulus != MagickFalse)
{
i=0L;
for (y=0L; y < (ssize_t) fourier_info->height; y++)
for (x=0L; x < (ssize_t) fourier_info->width; x++)
{
phase_pixels[i]-=0.5;
phase_pixels[i]*=(2.0*MagickPI);
i++;
}
}
phase_view=DestroyCacheView(phase_view);
CorrectPhaseLHS(fourier_info->width,fourier_info->height,phase_pixels);
if (status != MagickFalse)
status=InverseQuadrantSwap(fourier_info->width,fourier_info->height,
phase_pixels,inverse_pixels);
(void) memcpy(phase_pixels,inverse_pixels,fourier_info->height*
fourier_info->center*sizeof(*phase_pixels));
inverse_info=RelinquishVirtualMemory(inverse_info);
/*
Merge two sets.
*/
i=0L;
if (fourier_info->modulus != MagickFalse)
for (y=0L; y < (ssize_t) fourier_info->height; y++)
for (x=0L; x < (ssize_t) fourier_info->center; x++)
{
#if defined(MAGICKCORE_HAVE_COMPLEX_H)
fourier_pixels[i]=magnitude_pixels[i]*cos(phase_pixels[i])+I*
magnitude_pixels[i]*sin(phase_pixels[i]);
#else
fourier_pixels[i][0]=magnitude_pixels[i]*cos(phase_pixels[i]);
fourier_pixels[i][1]=magnitude_pixels[i]*sin(phase_pixels[i]);
#endif
i++;
}
else
for (y=0L; y < (ssize_t) fourier_info->height; y++)
for (x=0L; x < (ssize_t) fourier_info->center; x++)
{
#if defined(MAGICKCORE_HAVE_COMPLEX_H)
fourier_pixels[i]=magnitude_pixels[i]+I*phase_pixels[i];
#else
fourier_pixels[i][0]=magnitude_pixels[i];
fourier_pixels[i][1]=phase_pixels[i];
#endif
i++;
}
magnitude_info=RelinquishVirtualMemory(magnitude_info);
phase_info=RelinquishVirtualMemory(phase_info);
return(status);
}
static MagickBooleanType InverseFourierTransform(FourierInfo *fourier_info,
fftw_complex *fourier_pixels,Image *image,ExceptionInfo *exception)
{
CacheView
*image_view;
const char
*value;
double
*source_pixels;
fftw_plan
fftw_c2r_plan;
MemoryInfo
*source_info;
register Quantum
*q;
register ssize_t
i,
x;
ssize_t
y;
source_info=AcquireVirtualMemory((size_t) fourier_info->width,
fourier_info->height*sizeof(*source_pixels));
if (source_info == (MemoryInfo *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
return(MagickFalse);
}
source_pixels=(double *) GetVirtualMemoryBlob(source_info);
value=GetImageArtifact(image,"fourier:normalize");
if (LocaleCompare(value,"inverse") == 0)
{
double
gamma;
/*
Normalize inverse transform.
*/
i=0L;
gamma=PerceptibleReciprocal((double) fourier_info->width*
fourier_info->height);
for (y=0L; y < (ssize_t) fourier_info->height; y++)
for (x=0L; x < (ssize_t) fourier_info->center; x++)
{
#if defined(MAGICKCORE_HAVE_COMPLEX_H)
fourier_pixels[i]*=gamma;
#else
fourier_pixels[i][0]*=gamma;
fourier_pixels[i][1]*=gamma;
#endif
i++;
}
}
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_InverseFourierTransform)
#endif
fftw_c2r_plan=fftw_plan_dft_c2r_2d(fourier_info->width,fourier_info->height,
fourier_pixels,source_pixels,FFTW_ESTIMATE);
fftw_execute_dft_c2r(fftw_c2r_plan,fourier_pixels,source_pixels);
fftw_destroy_plan(fftw_c2r_plan);
i=0L;
image_view=AcquireAuthenticCacheView(image,exception);
for (y=0L; y < (ssize_t) fourier_info->height; y++)
{
if (y >= (ssize_t) image->rows)
break;
q=GetCacheViewAuthenticPixels(image_view,0L,y,fourier_info->width >
image->columns ? image->columns : fourier_info->width,1UL,exception);
if (q == (Quantum *) NULL)
break;
for (x=0L; x < (ssize_t) fourier_info->width; x++)
{
if (x < (ssize_t) image->columns)
switch (fourier_info->channel)
{
case RedPixelChannel:
default:
{
SetPixelRed(image,ClampToQuantum(QuantumRange*source_pixels[i]),q);
break;
}
case GreenPixelChannel:
{
SetPixelGreen(image,ClampToQuantum(QuantumRange*source_pixels[i]),
q);
break;
}
case BluePixelChannel:
{
SetPixelBlue(image,ClampToQuantum(QuantumRange*source_pixels[i]),
q);
break;
}
case BlackPixelChannel:
{
SetPixelBlack(image,ClampToQuantum(QuantumRange*source_pixels[i]),
q);
break;
}
case AlphaPixelChannel:
{
SetPixelAlpha(image,ClampToQuantum(QuantumRange*source_pixels[i]),
q);
break;
}
}
i++;
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
break;
}
image_view=DestroyCacheView(image_view);
source_info=RelinquishVirtualMemory(source_info);
return(MagickTrue);
}
static MagickBooleanType InverseFourierTransformChannel(
const Image *magnitude_image,const Image *phase_image,
const PixelChannel channel,const MagickBooleanType modulus,
Image *fourier_image,ExceptionInfo *exception)
{
fftw_complex
*inverse_pixels;
FourierInfo
fourier_info;
MagickBooleanType
status;
MemoryInfo
*inverse_info;
fourier_info.width=magnitude_image->columns;
fourier_info.height=magnitude_image->rows;
if ((magnitude_image->columns != magnitude_image->rows) ||
((magnitude_image->columns % 2) != 0) ||
((magnitude_image->rows % 2) != 0))
{
size_t extent=magnitude_image->columns < magnitude_image->rows ?
magnitude_image->rows : magnitude_image->columns;
fourier_info.width=(extent & 0x01) == 1 ? extent+1UL : extent;
}
fourier_info.height=fourier_info.width;
fourier_info.center=(ssize_t) (fourier_info.width/2L)+1L;
fourier_info.channel=channel;
fourier_info.modulus=modulus;
inverse_info=AcquireVirtualMemory((size_t) fourier_info.width,
(fourier_info.height/2+1)*sizeof(*inverse_pixels));
if (inverse_info == (MemoryInfo *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",
magnitude_image->filename);
return(MagickFalse);
}
inverse_pixels=(fftw_complex *) GetVirtualMemoryBlob(inverse_info);
status=InverseFourier(&fourier_info,magnitude_image,phase_image,
inverse_pixels,exception);
if (status != MagickFalse)
status=InverseFourierTransform(&fourier_info,inverse_pixels,fourier_image,
exception);
inverse_info=RelinquishVirtualMemory(inverse_info);
return(status);
}
#endif
MagickExport Image *InverseFourierTransformImage(const Image *magnitude_image,
const Image *phase_image,const MagickBooleanType modulus,
ExceptionInfo *exception)
{
Image
*fourier_image;
assert(magnitude_image != (Image *) NULL);
assert(magnitude_image->signature == MagickCoreSignature);
if (magnitude_image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
magnitude_image->filename);
if (phase_image == (Image *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),ImageError,
"ImageSequenceRequired","`%s'",magnitude_image->filename);
return((Image *) NULL);
}
#if !defined(MAGICKCORE_FFTW_DELEGATE)
fourier_image=(Image *) NULL;
(void) modulus;
(void) ThrowMagickException(exception,GetMagickModule(),
MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn","`%s' (FFTW)",
magnitude_image->filename);
#else
{
fourier_image=CloneImage(magnitude_image,magnitude_image->columns,
magnitude_image->rows,MagickTrue,exception);
if (fourier_image != (Image *) NULL)
{
MagickBooleanType
is_gray,
status;
status=MagickTrue;
is_gray=IsImageGray(magnitude_image);
if (is_gray != MagickFalse)
is_gray=IsImageGray(phase_image);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel sections
#endif
{
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp section
#endif
{
MagickBooleanType
thread_status;
if (is_gray != MagickFalse)
thread_status=InverseFourierTransformChannel(magnitude_image,
phase_image,GrayPixelChannel,modulus,fourier_image,exception);
else
thread_status=InverseFourierTransformChannel(magnitude_image,
phase_image,RedPixelChannel,modulus,fourier_image,exception);
if (thread_status == MagickFalse)
status=thread_status;
}
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp section
#endif
{
MagickBooleanType
thread_status;
thread_status=MagickTrue;
if (is_gray == MagickFalse)
thread_status=InverseFourierTransformChannel(magnitude_image,
phase_image,GreenPixelChannel,modulus,fourier_image,exception);
if (thread_status == MagickFalse)
status=thread_status;
}
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp section
#endif
{
MagickBooleanType
thread_status;
thread_status=MagickTrue;
if (is_gray == MagickFalse)
thread_status=InverseFourierTransformChannel(magnitude_image,
phase_image,BluePixelChannel,modulus,fourier_image,exception);
if (thread_status == MagickFalse)
status=thread_status;
}
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp section
#endif
{
MagickBooleanType
thread_status;
thread_status=MagickTrue;
if (magnitude_image->colorspace == CMYKColorspace)
thread_status=InverseFourierTransformChannel(magnitude_image,
phase_image,BlackPixelChannel,modulus,fourier_image,exception);
if (thread_status == MagickFalse)
status=thread_status;
}
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp section
#endif
{
MagickBooleanType
thread_status;
thread_status=MagickTrue;
if (magnitude_image->alpha_trait != UndefinedPixelTrait)
thread_status=InverseFourierTransformChannel(magnitude_image,
phase_image,AlphaPixelChannel,modulus,fourier_image,exception);
if (thread_status == MagickFalse)
status=thread_status;
}
}
if (status == MagickFalse)
fourier_image=DestroyImage(fourier_image);
}
fftw_cleanup();
}
#endif
return(fourier_image);
}
|
GB_unop__identity_uint32_uint16.c | //------------------------------------------------------------------------------
// GB_unop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated/ folder, do not edit it (auto-generated).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_atomics.h"
#include "GB_unop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB (_unop_apply__identity_uint32_uint16)
// op(A') function: GB (_unop_tran__identity_uint32_uint16)
// C type: uint32_t
// A type: uint16_t
// cast: uint32_t cij = (uint32_t) aij
// unaryop: cij = aij
#define GB_ATYPE \
uint16_t
#define GB_CTYPE \
uint32_t
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
uint16_t aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = x ;
// casting
#define GB_CAST(z, aij) \
uint32_t z = (uint32_t) aij ;
// cij = op (aij)
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
uint16_t aij = Ax [pA] ; \
/* Cx [pC] = op (cast (aij)) */ \
uint32_t z = (uint32_t) aij ; \
Cx [pC] = z ; \
}
// true if operator is the identity op with no typecasting
#define GB_OP_IS_IDENTITY_WITH_NO_TYPECAST \
0
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_IDENTITY || GxB_NO_UINT32 || GxB_NO_UINT16)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_apply__identity_uint32_uint16)
(
uint32_t *Cx, // Cx and Ax may be aliased
const uint16_t *Ax,
const int8_t *restrict Ab, // A->b if A is bitmap
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
// TODO: if OP is ONE and uniform-valued matrices are exploited, then
// do this in O(1) time
if (Ab == NULL)
{
#if ( GB_OP_IS_IDENTITY_WITH_NO_TYPECAST )
GB_memcpy (Cx, Ax, anz * sizeof (uint16_t), nthreads) ;
#else
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
uint16_t aij = Ax [p] ;
uint32_t z = (uint32_t) aij ;
Cx [p] = z ;
}
#endif
}
else
{
// bitmap case, no transpose; A->b already memcpy'd into C->b
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!Ab [p]) continue ;
uint16_t aij = Ax [p] ;
uint32_t z = (uint32_t) aij ;
Cx [p] = z ;
}
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_tran__identity_uint32_uint16)
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
kernel_metropolis.h | //////////////////////////////////////////////////////////////////////////////////
// //
// trueke //
// A multi-GPU implementation of the exchange Monte Carlo method. //
// //
//////////////////////////////////////////////////////////////////////////////////
// //
// Copyright © 2015 Cristobal A. Navarro, Wei Huang. //
// //
// This file is part of trueke. //
// trueke is free software: you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation, either version 3 of the License, or //
// (at your option) any later version. //
// //
// trueke 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 trueke. If not, see <http://www.gnu.org/licenses/>. //
// //
//////////////////////////////////////////////////////////////////////////////////
#ifndef _KERNEL_MONTECARLO_CUH_
#define _KERNEL_MONTECARLO_CUH_
// GPU-related definitions
#define sLx (BX+2)
#define sLy (BY+2)
#define sLz (BZ+2)
#define SVOLUME ((sLx)*(sLy)*(sLz))
#define BVOLUME ((BX)*((BY)/2)*(BZ))
#define BLOCKSIZE 8
#define BLOCK_STEPS 1
#define EPSILON 0.00000000001f
#define C(x,y,z,L) ((z)*(L)*(L)+(y)*(L)+(x))
#define sC(x,y,z,Lx,Ly) ((z+1)*(Ly)*(Lx)+(y+1)*(Lx)+(x+1))
void
kernel_metropolis(const int N, const int L, int *s, const int *H,
const float h, const float B, uint64_t *state, uint64_t *inc, int alt)
{
const int gridDim_x = (L + BX - 1) / BX;
const int gridDim_y = (L + BY - 1) / (2*BY);
const int gridDim_z = (L + BZ - 1) / BZ;
const int numTeams = gridDim_x * gridDim_y * gridDim_z ;
const int numThreads = BX * BY / 2 * BZ;
#pragma omp target teams num_teams(numTeams) thread_limit(numThreads)
{
int ss[SVOLUME];
#pragma omp parallel
{
const int team = omp_get_team_num();
const int thread = omp_get_thread_num();
const int blockIdx_x = team % gridDim_x;
const int blockIdx_y = team / gridDim_x % gridDim_y;
const int blockIdx_z = team / gridDim_x / gridDim_y % gridDim_z;
const int threadIdx_x = thread % BX;
const int threadIdx_y = thread / BX % (BY/2);
const int threadIdx_z = (thread * 2) / (BX * BY) % BZ;
// offsets
const int offx = blockIdx_x * BX;
const int offy = (2*blockIdx_y + ((blockIdx_x + blockIdx_z + alt) & 1)) * BY;
const int offz = blockIdx_z * BZ;
// halo shared memory coords
const int sx = threadIdx_x;
const int sy1 = 2*threadIdx_y;
const int sy2 = 2*threadIdx_y + 1;
const int sz = threadIdx_z;
// global coords
const int x = offx + sx;
const int y1 = offy + sy1;
const int y2 = offy + sy2;
const int z = offz + sz;
//if(x >= N || y1 >= N || y2 >= N || z >= N)
//return;
// global and local and block id in soc
const int tid = z*L*L/4 + (blockIdx_y * BY/2 + threadIdx_y)*L + x;
// load the spins into shared memory
ss[sC(sx, sy1, sz, sLx, sLy)] = s[C(x, y1, z, L)];
ss[sC(sx, sy2, sz, sLx, sLy)] = s[C(x, y2, z, L)];
// get the h1,h2 values for y1 y2_
const int h1 = H[C(x, y1, z, L)];
const int h2 = H[C(x, y2, z, L)];
//printf("thread %i h1=%i h2=%i\n", tid, h1, h2);
// ------------------------------------------------
// halo
// ------------------------------------------------
// Y boundary
if(threadIdx_y == 0){
// we also check if we are on the limit of the lattice
ss[sC(sx, -1, sz, sLx, sLy)] = (offy == 0) ? s[C(x, L-1, z, L)] : s[C(x, offy-1, z, L)];
}
if(threadIdx_y == BY/2-1){
ss[sC(sx, BY, sz, sLx, sLy)] = (offy == L-BY) ? s[C(x, 0, z, L)] : s[C(x, offy+BY, z, L)];
}
// X boundary
if(threadIdx_x == 0){
if(blockIdx_x == 0){
ss[sC(-1, sy1, sz, sLx, sLy)] = s[C(L-1, y1, z, L)];
ss[sC(-1, sy2, sz, sLx, sLy)] = s[C(L-1, y2, z, L)];
}
else{
ss[sC(-1, sy1, sz, sLx, sLy)] = s[C(offx-1, y1, z, L)];
ss[sC(-1, sy2, sz, sLx, sLy)] = s[C(offx-1, y2, z, L)];
}
}
if(threadIdx_x == BX-1){
if(blockIdx_x == gridDim_x-1){
ss[sC(BX, sy1, sz, sLx, sLy)] = s[C(0, y1, z, L)];
ss[sC(BX, sy2, sz, sLx, sLy)] = s[C(0, y2, z, L)];
}
else{
ss[sC(BX, sy1, sz, sLx, sLy)] = s[C(offx+BX, y1, z, L)];
ss[sC(BX, sy2, sz, sLx, sLy)] = s[C(offx+BX, y2, z, L)];
}
}
// Z boundary
if(threadIdx_z == 0){
if(blockIdx_z == 0){
ss[sC(sx, sy1, -1, sLx, sLy)] = s[C(x, y1, L-1, L)];
ss[sC(sx, sy2, -1, sLx, sLy)] = s[C(x, y2, L-1, L)];
}
else{
ss[sC(sx, sy1, -1, sLx, sLy)] = s[C(x, y1, offz-1, L)];
ss[sC(sx, sy2, -1, sLx, sLy)] = s[C(x, y2, offz-1, L)];
}
}
if(threadIdx_z == BZ-1){
if(blockIdx_z == gridDim_z-1){
ss[sC(sx, sy1, BZ, sLx, sLy)] = s[C(x, y1, 0, L)];
ss[sC(sx, sy2, BZ, sLx, sLy)] = s[C(x, y2, 0, L)];
}
else{
ss[sC(sx, sy1, BZ, sLx, sLy)] = s[C(x, y1, offz+BZ, L)];
ss[sC(sx, sy2, BZ, sLx, sLy)] = s[C(x, y2, offz+BZ, L)];
}
}
// get random number state
uint64_t lstate = state[tid];
uint64_t linc = inc[tid];
// the white and black y
int wy = ((sx + sz) & 1) + 2*threadIdx_y;
int by = ((sx + sz + 1) & 1) + 2*threadIdx_y;
float dh;
int c;
#pragma omp barrier
//#pragma unroll
for(int i = 0; i < BLOCK_STEPS; ++i){
/* -------- white update -------- */
dh = (float)(ss[sC(sx, wy, sz, sLx, sLy)] * (
(float)(ss[sC(sx-1,wy,sz, sLx, sLy)] + ss[sC(sx+1, wy, sz, sLx, sLy)] +
ss[sC(sx,wy-1,sz, sLx, sLy)] + ss[sC(sx, wy+1, sz, sLx, sLy)] +
ss[sC(sx,wy,sz-1, sLx, sLy)] + ss[sC(sx, wy, sz+1, sLx, sLy)]) + h*h1));
c = signbit(dh-EPSILON) | signbit(gpu_rand01(&lstate, &linc) - expf(dh * B));
ss[sC(sx, wy, sz, sLx, sLy)] *= (1 - 2*c);
#pragma omp barrier
/* -------- black update -------- */
dh = (float)(ss[sC(sx, by, sz, sLx, sLy)] * (
(float)(ss[sC(sx-1,by,sz, sLx, sLy)] + ss[sC(sx+1, by, sz, sLx, sLy)] +
ss[sC(sx,by-1,sz, sLx, sLy)] + ss[sC(sx, by+1, sz, sLx, sLy)] +
ss[sC(sx,by,sz-1, sLx, sLy)] + ss[sC(sx, by, sz+1, sLx, sLy)]) + h*h2));
c = signbit(dh-EPSILON) | signbit(gpu_rand01(&lstate, &linc) - expf(dh * B));
ss[sC(sx, by, sz, sLx, sLy)] *= (1 - 2*c);
#pragma omp barrier
}
/* copy data back to gmem */
s[C(x, y1, z, L)] = ss[sC(sx, sy1, sz, sLx, sLy)];
s[C(x, y2, z, L)] = ss[sC(sx, sy2, sz, sLx, sLy)];
/* update random number state */
state[tid] = lstate;
inc[tid] = linc;
}
}
}
// NOTE: the space of computation is 1/4 of N, so that is why each thread does quadruple work.
void kernel_reset_random_gpupcg(int *s, int N, uint64_t *state, uint64_t *inc)
{
/* Each thread gets same seed, a different sequence number, no offset */
#pragma omp target teams distribute parallel for thread_limit(BLOCKSIZE1D)
for (int x = 0; x < N/4; x++) {
/* get the prng state in register memory */
uint64_t lstate = state[x];
uint64_t linc = inc[x];
// first random
float v = (int) (gpu_rand01(&lstate, &linc) + 0.5f);
s[x] = 1-2*v;
// second random
v = (int) (gpu_rand01(&lstate, &linc) + 0.5f);
s[x + N/4] = 1-2*v;
// third random
v = (int) (gpu_rand01(&lstate, &linc) + 0.5f);
s[x + N/2 ] = 1-2*v;
// fourth random
v = (int) (gpu_rand01(&lstate, &linc) + 0.5f);
s[x + 3*N/4] = 1-2*v;
/* save the state back to global memory */
state[x] = lstate;
inc[x] = linc;
}
}
template<typename T>
void kernel_reset(T *a, int N, T val){
#pragma omp target teams distribute parallel for thread_limit(BLOCKSIZE1D)
for (int idx = 0; idx < N; idx++) a[idx] = val;
}
#endif
|
interpolation_p1.c | //------------------------------------------------------------------------------------------------------------------------------
// Samuel Williams
// SWWilliams@lbl.gov
// Lawrence Berkeley National Lab
//------------------------------------------------------------------------------------------------------------------------------
#include <math.h>
//------------------------------------------------------------------------------------------------------------------------------
static inline void interpolation_p1_block(level_type *level_f, int id_f, double prescale_f, level_type *level_c, int id_c, blockCopy_type *block){
// interpolate 3D array from read_i,j,k of read[] to write_i,j,k in write[]
int write_dim_i = block->dim.i<<1; // calculate the dimensions of the resultant fine block
int write_dim_j = block->dim.j<<1;
int write_dim_k = block->dim.k<<1;
int read_i = block->read.i;
int read_j = block->read.j;
int read_k = block->read.k;
int read_jStride = block->read.jStride;
int read_kStride = block->read.kStride;
int write_i = block->write.i;
int write_j = block->write.j;
int write_k = block->write.k;
int write_jStride = block->write.jStride;
int write_kStride = block->write.kStride;
double * __restrict__ read = block->read.ptr;
double * __restrict__ write = block->write.ptr;
if(block->read.box >=0){
read = level_c->my_boxes[ block->read.box].vectors[id_c] + level_c->my_boxes[ block->read.box].ghosts*(1+level_c->my_boxes[ block->read.box].jStride+level_c->my_boxes[ block->read.box].kStride);
read_jStride = level_c->my_boxes[block->read.box ].jStride;
read_kStride = level_c->my_boxes[block->read.box ].kStride;
}
if(block->write.box>=0){
write = level_f->my_boxes[block->write.box].vectors[id_f] + level_f->my_boxes[block->write.box].ghosts*(1+level_f->my_boxes[block->write.box].jStride+level_f->my_boxes[block->write.box].kStride);
write_jStride = level_f->my_boxes[block->write.box].jStride;
write_kStride = level_f->my_boxes[block->write.box].kStride;
}
int i,j,k;
for(k=0;k<write_dim_k;k++){int delta_k=-read_kStride;if(k&0x1)delta_k=read_kStride;
for(j=0;j<write_dim_j;j++){int delta_j=-read_jStride;if(j&0x1)delta_j=read_jStride;
for(i=0;i<write_dim_i;i++){int delta_i= -1;if(i&0x1)delta_i= 1; // i.e. even points look backwards while odd points look forward
int write_ijk = ((i )+write_i) + (((j )+write_j)*write_jStride) + (((k )+write_k)*write_kStride);
int read_ijk = ((i>>1)+ read_i) + (((j>>1)+ read_j)* read_jStride) + (((k>>1)+ read_k)* read_kStride);
//
// | o | o |
// +---+---+---+---+
// | | x | x | |
//
// CAREFUL !!! you must guarantee you zero'd the MPI buffers(write[]) and destination boxes at some point to avoid 0.0*NaN or 0.0*inf
// piecewise linear interpolation... NOTE, BC's must have been previously applied
write[write_ijk] = prescale_f*write[write_ijk] +
0.421875*read[read_ijk ] +
0.140625*read[read_ijk +delta_k] +
0.140625*read[read_ijk +delta_j ] +
0.046875*read[read_ijk +delta_j+delta_k] +
0.140625*read[read_ijk+delta_i ] +
0.046875*read[read_ijk+delta_i +delta_k] +
0.046875*read[read_ijk+delta_i+delta_j ] +
0.015625*read[read_ijk+delta_i+delta_j+delta_k];
}}}
}
//------------------------------------------------------------------------------------------------------------------------------
// perform a (inter-level) piecewise linear interpolation
void interpolation_p1(level_type * level_f, int id_f, double prescale_f, level_type *level_c, int id_c){
exchange_boundary(level_c,id_c,STENCIL_SHAPE_BOX);
apply_BCs_p1(level_c,id_c,STENCIL_SHAPE_BOX);
double _timeCommunicationStart = getTime();
double _timeStart,_timeEnd;
int buffer=0;
int n;
int my_tag = (level_f->tag<<4) | 0x7;
#ifdef USE_MPI
// by convention, level_f allocates a combined array of requests for both level_f recvs and level_c sends...
int nMessages = level_c->interpolation.num_sends + level_f->interpolation.num_recvs;
MPI_Request *recv_requests = level_f->interpolation.requests;
MPI_Request *send_requests = level_f->interpolation.requests + level_f->interpolation.num_recvs;
// loop through packed list of MPI receives and prepost Irecv's...
if(level_f->interpolation.num_recvs>0){
_timeStart = getTime();
#ifdef USE_MPI_THREAD_MULTIPLE
#pragma omp parallel for schedule(dynamic,1)
#endif
for(n=0;n<level_f->interpolation.num_recvs;n++){
MPI_Irecv(level_f->interpolation.recv_buffers[n],
level_f->interpolation.recv_sizes[n],
MPI_DOUBLE,
level_f->interpolation.recv_ranks[n],
my_tag,
MPI_COMM_WORLD,
&recv_requests[n]
);
}
_timeEnd = getTime();
level_f->timers.interpolation_recv += (_timeEnd-_timeStart);
}
// pack MPI send buffers...
if(level_c->interpolation.num_blocks[0]>0){
_timeStart = getTime();
PRAGMA_THREAD_ACROSS_BLOCKS(level_f,buffer,level_c->interpolation.num_blocks[0])
for(buffer=0;buffer<level_c->interpolation.num_blocks[0];buffer++){
// !!! prescale==0 because you don't want to increment the MPI buffer
interpolation_p1_block(level_f,id_f,0.0,level_c,id_c,&level_c->interpolation.blocks[0][buffer]);
}
_timeEnd = getTime();
level_f->timers.interpolation_pack += (_timeEnd-_timeStart);
}
// loop through MPI send buffers and post Isend's...
if(level_c->interpolation.num_sends>0){
_timeStart = getTime();
#ifdef USE_MPI_THREAD_MULTIPLE
#pragma omp parallel for schedule(dynamic,1)
#endif
for(n=0;n<level_c->interpolation.num_sends;n++){
MPI_Isend(level_c->interpolation.send_buffers[n],
level_c->interpolation.send_sizes[n],
MPI_DOUBLE,
level_c->interpolation.send_ranks[n],
my_tag,
MPI_COMM_WORLD,
&send_requests[n]
);
}
_timeEnd = getTime();
level_f->timers.interpolation_send += (_timeEnd-_timeStart);
}
#endif
// perform local interpolation... try and hide within Isend latency...
if(level_c->interpolation.num_blocks[1]>0){
_timeStart = getTime();
PRAGMA_THREAD_ACROSS_BLOCKS(level_f,buffer,level_c->interpolation.num_blocks[1])
for(buffer=0;buffer<level_c->interpolation.num_blocks[1];buffer++){
interpolation_p1_block(level_f,id_f,prescale_f,level_c,id_c,&level_c->interpolation.blocks[1][buffer]);
}
_timeEnd = getTime();
level_f->timers.interpolation_local += (_timeEnd-_timeStart);
}
// wait for MPI to finish...
#ifdef USE_MPI
if(nMessages>0){
_timeStart = getTime();
MPI_Waitall(nMessages,level_f->interpolation.requests,level_f->interpolation.status);
_timeEnd = getTime();
level_f->timers.interpolation_wait += (_timeEnd-_timeStart);
}
// unpack MPI receive buffers
if(level_f->interpolation.num_blocks[2]>0){
_timeStart = getTime();
PRAGMA_THREAD_ACROSS_BLOCKS(level_f,buffer,level_f->interpolation.num_blocks[2])
for(buffer=0;buffer<level_f->interpolation.num_blocks[2];buffer++){
IncrementBlock(level_f,id_f,prescale_f,&level_f->interpolation.blocks[2][buffer]);
}
_timeEnd = getTime();
level_f->timers.interpolation_unpack += (_timeEnd-_timeStart);
}
#endif
level_f->timers.interpolation_total += (double)(getTime()-_timeCommunicationStart);
}
|
parallel_section_reduction.c | #include <stdio.h>
#include <math.h>
#include "omp_testsuite.h"
int
check_parallel_section_reduction (FILE * logFile)
{
int sum = 7;
int known_sum;
double dpt, dsum = 0;
double dknown_sum;
double dt = 0.5; /* base of geometric row for + and - test */
double rounding_error = 1.E-5;
int diff;
double ddiff;
int product = 1;
int known_product;
int logic_and = 1;
int bit_and = 1;
int logic_or = 0;
int bit_or = 0;
int exclusiv_bit_or = 0;
int logics[1000];
int i;
int result = 0;
/* int my_islarger; */
/*int is_larger=1; */
dt = 1. / 3.;
known_sum = (999 * 1000) / 2 + 7;
#pragma omp parallel sections private(i) reduction(+:sum)
{
#pragma omp section
{
for (i = 1; i < 300; i++)
{
sum = sum + i;
}
}
#pragma omp section
{
for (i = 300; i < 700; i++)
{
sum = sum + i;
}
}
#pragma omp section
{
for (i = 700; i < 1000; i++)
{
sum = sum + i;
}
}
}
if (known_sum != sum)
{
++result;
fprintf (logFile,
"Error in sum with integers: Result was %d instead of %d\n",
sum, known_sum);
}
diff = (999 * 1000) / 2;
#pragma omp parallel sections private(i) reduction(-:diff)
{
#pragma omp section
{
for (i = 1; i < 300; i++)
{
diff = diff - i;
}
}
#pragma omp section
{
for (i = 300; i < 700; i++)
{
diff = diff - i;
}
}
#pragma omp section
{
for (i = 700; i < 1000; i++)
{
diff = diff - i;
}
}
}
if (diff != 0)
{
result++;
fprintf (logFile,
"Error in Difference with integers: Result was %d instead of 0.\n",
diff);
}
for (i = 0; i < 20; ++i)
{
dpt *= dt;
}
dknown_sum = (1 - dpt) / (1 - dt);
#pragma omp parallel sections private(i) reduction(+:dsum)
{
#pragma omp section
{
for (i = 0; i < 6; ++i)
{
dsum += pow (dt, i);
}
}
#pragma omp section
{
for (i = 6; i < 12; ++i)
{
dsum += pow (dt, i);
}
}
#pragma omp section
{
for (i = 12; i < 20; ++i)
{
dsum += pow (dt, i);
}
}
}
if (fabs (dsum - dknown_sum) > rounding_error)
{
result++;
fprintf (logFile,
"Error in sum with doubles: Result was %f instead of %f (Difference: %E)\n",
dsum, dknown_sum, dsum - dknown_sum);
}
dpt = 1;
for (i = 0; i < 20; ++i)
{
dpt *= dt;
}
fprintf (logFile, "\n");
ddiff = (1 - dpt) / (1 - dt);
#pragma omp parallel sections private(i) reduction(-:ddiff)
{
#pragma omp section
{
for (i = 0; i < 6; ++i)
{
ddiff -= pow (dt, i);
}
}
#pragma omp section
{
for (i = 6; i < 12; ++i)
{
ddiff -= pow (dt, i);
}
}
#pragma omp section
{
for (i = 12; i < 20; ++i)
{
ddiff -= pow (dt, i);
}
}
}
if (fabs (ddiff) > rounding_error)
{
result++;
fprintf (logFile,
"Error in Difference with doubles: Result was %E instead of 0.0\n",
ddiff);
}
known_product = 3628800;
#pragma omp parallel sections private(i) reduction(*:product)
{
#pragma omp section
{
for (i = 1; i < 3; i++)
{
product *= i;
}
}
#pragma omp section
{
for (i = 3; i < 7; i++)
{
product *= i;
}
}
#pragma omp section
{
for (i = 7; i < 11; i++)
{
product *= i;
}
}
}
if (known_product != product)
{
result++;
fprintf (logFile,
"Error in Product with integers: Result was %d instead of %d\n",
product, known_product);
}
for (i = 0; i < 1000; i++)
{
logics[i] = 1;
}
#pragma omp parallel sections private(i) reduction(&&:logic_and)
{
#pragma omp section
{
for (i = 1; i < 300; i++)
{
logic_and = (logic_and && logics[i]);
}
}
#pragma omp section
{
for (i = 300; i < 700; i++)
{
logic_and = (logic_and && logics[i]);
}
}
#pragma omp section
{
for (i = 700; i < 1000; i++)
{
logic_and = (logic_and && logics[i]);
}
}
}
if (!logic_and)
{
result++;
fprintf (logFile, "Error in logic AND part 1\n");
}
logic_and = 1;
logics[501] = 0;
#pragma omp parallel sections private(i) reduction(&&:logic_and)
{
#pragma omp section
{
for (i = 1; i < 300; i++)
{
logic_and = (logic_and && logics[i]);
}
}
#pragma omp section
{
for (i = 300; i < 700; i++)
{
logic_and = (logic_and && logics[i]);
}
}
#pragma omp section
{
for (i = 700; i < 1000; i++)
{
logic_and = (logic_and && logics[i]);
}
}
}
if (logic_and)
{
result++;
fprintf (logFile, "Error in logic AND part 2\n");
}
for (i = 0; i < 1000; i++)
{
logics[i] = 0;
}
#pragma omp parallel sections private(i) reduction(||:logic_or)
{
#pragma omp section
{
for (i = 1; i < 300; i++)
{
logic_or = (logic_or || logics[i]);
}
}
#pragma omp section
{
for (i = 300; i < 700; i++)
{
logic_or = (logic_or || logics[i]);
}
}
#pragma omp section
{
for (i = 700; i < 1000; i++)
{
logic_or = (logic_or || logics[i]);
}
}
}
if (logic_or)
{
result++;
fprintf (logFile, "\nError in logic OR part 1\n");
}
logic_or = 0;
logics[501] = 1;
#pragma omp parallel sections private(i) reduction(||:logic_or)
{
#pragma omp section
{
for (i = 1; i < 300; i++)
{
logic_or = (logic_or || logics[i]);
}
}
#pragma omp section
{
for (i = 300; i < 700; i++)
{
logic_or = (logic_or || logics[i]);
}
}
#pragma omp section
{
for (i = 700; i < 1000; i++)
{
logic_or = (logic_or || logics[i]);
}
}
}
if (!logic_or)
{
result++;
fprintf (logFile, "Error in logic OR part 2\n");
}
for (i = 0; i < 1000; ++i)
{
logics[i] = 1;
}
#pragma omp parallel sections private(i) reduction(&:bit_and)
{
#pragma omp section
{
for (i = 0; i < 300; ++i)
{
bit_and = (bit_and & logics[i]);
}
}
#pragma omp section
{
for (i = 300; i < 700; ++i)
{
bit_and = (bit_and & logics[i]);
}
}
#pragma omp section
{
for (i = 700; i < 1000; ++i)
{
bit_and = (bit_and & logics[i]);
}
}
}
if (!bit_and)
{
result++;
fprintf (logFile, "Error in BIT AND part 1\n");
}
bit_and = 1;
logics[501] = 0;
#pragma omp parallel sections private(i) reduction(&:bit_and)
{
#pragma omp section
{
for (i = 0; i < 300; ++i)
{
bit_and = bit_and & logics[i];
}
}
#pragma omp section
{
for (i = 300; i < 700; ++i)
{
bit_and = bit_and & logics[i];
}
}
#pragma omp section
{
for (i = 700; i < 1000; ++i)
{
bit_and = bit_and & logics[i];
}
}
}
if (bit_and)
{
result++;
fprintf (logFile, "Error in BIT AND part 2\n");
}
for (i = 0; i < 1000; i++)
{
logics[i] = 0;
}
#pragma omp parallel sections private(i) reduction(|:bit_or)
{
#pragma omp section
{
for (i = 0; i < 300; ++i)
{
bit_or = bit_or | logics[i];
}
}
#pragma omp section
{
for (i = 300; i < 700; ++i)
{
bit_or = bit_or | logics[i];
}
}
#pragma omp section
{
for (i = 700; i < 1000; ++i)
{
bit_or = bit_or | logics[i];
}
}
}
if (bit_or)
{
result++;
fprintf (logFile, "Error in BIT OR part 1\n");
}
bit_or = 0;
logics[501] = 1;
#pragma omp parallel sections private(i) reduction(|:bit_or)
{
#pragma omp section
{
for (i = 0; i < 300; ++i)
{
bit_or = bit_or | logics[i];
}
}
#pragma omp section
{
for (i = 300; i < 700; ++i)
{
bit_or = bit_or | logics[i];
}
}
#pragma omp section
{
for (i = 700; i < 1000; ++i)
{
bit_or = bit_or | logics[i];
}
}
}
if (!bit_or)
{
result++;
fprintf (logFile, "Error in BIT OR part 2\n");
}
for (i = 0; i < 1000; i++)
{
logics[i] = 0;
}
#pragma omp parallel sections private(i) reduction(^:exclusiv_bit_or)
{
#pragma omp section
{
for (i = 0; i < 300; ++i)
{
exclusiv_bit_or = exclusiv_bit_or ^ logics[i];
}
}
#pragma omp section
{
for (i = 300; i < 700; ++i)
{
exclusiv_bit_or = exclusiv_bit_or ^ logics[i];
}
}
#pragma omp section
{
for (i = 700; i < 1000; ++i)
{
exclusiv_bit_or = exclusiv_bit_or ^ logics[i];
}
}
}
if (exclusiv_bit_or)
{
result++;
fprintf (logFile, "Error in EXCLUSIV BIT OR part 1\n");
}
exclusiv_bit_or = 0;
logics[501] = 1;
#pragma omp parallel sections private(i) reduction(^:exclusiv_bit_or)
{
#pragma omp section
{
for (i = 0; i < 300; ++i)
{
exclusiv_bit_or = exclusiv_bit_or ^ logics[i];
}
}
#pragma omp section
{
for (i = 300; i < 700; ++i)
{
exclusiv_bit_or = exclusiv_bit_or ^ logics[i];
}
}
#pragma omp section
{
for (i = 700; i < 1000; ++i)
{
exclusiv_bit_or = exclusiv_bit_or ^ logics[i];
}
}
}
if (!exclusiv_bit_or)
{
result++;
fprintf (logFile, "Error in EXCLUSIV BIT OR part 2\n");
}
/*printf("\nResult:%d\n",result); */
return (result == 0);
}
int
crosscheck_parallel_section_reduction (FILE * logFile)
{
int sum = 7;
int known_sum;
double dpt, dsum = 0;
double dknown_sum;
double dt = 0.5; /* base of geometric row for + and - test */
double rounding_error = 1.E-5;
int diff;
double ddiff;
int product = 1;
int known_product;
int logic_and = 1;
int bit_and = 1;
int logic_or = 0;
int bit_or = 0;
int exclusiv_bit_or;
int logics[1000];
int i;
int result = 0;
/* int my_islarger; */
/*int is_larger=1; */
known_sum = (999 * 1000) / 2 + 7;
dt = 1. / 3.;
#pragma omp parallel sections private(i)
{
#pragma omp section
{
for (i = 1; i < 300; i++)
{
sum = sum + i;
}
}
#pragma omp section
{
for (i = 300; i < 700; i++)
{
sum = sum + i;
}
}
#pragma omp section
{
for (i = 700; i < 1000; i++)
{
sum = sum + i;
}
}
}
if (known_sum != sum)
{
++result;
/*printf("\nError in Sum with integers\n"); */
}
diff = (999 * 1000) / 2;
#pragma omp parallel sections private(i)
{
#pragma omp section
{
for (i = 1; i < 300; i++)
{
diff = diff - i;
}
}
#pragma omp section
{
for (i = 300; i < 700; i++)
{
diff = diff - i;
}
}
#pragma omp section
{
for (i = 700; i < 1000; i++)
{
diff = diff - i;
}
}
}
if (diff != 0)
{
result++;
/*printf("\nError in Difference: Result was %d instead of 0.\n",diff); */
}
for (i = 0; i < 20; ++i)
{
dpt *= dt;
}
dknown_sum = (1 - dpt) / (1 - dt);
#pragma omp parallel sections private(i)
{
#pragma omp section
{
for (i = 0; i < 6; ++i)
{
dsum += pow (dt, i);
}
}
#pragma omp section
{
for (i = 6; i < 12; ++i)
{
dsum += pow (dt, i);
}
}
#pragma omp section
{
for (i = 12; i < 20; ++i)
{
dsum += pow (dt, i);
}
}
}
if (fabs (dsum - dknown_sum) > rounding_error)
{
result++;
fprintf (logFile,
"Error in sum with doubles: Result was %f instead of %f (Difference: %E)\n",
dsum, dknown_sum, dsum - dknown_sum);
}
dpt = 1;
for (i = 0; i < 20; ++i)
{
dpt *= dt;
}
fprintf (logFile, "\n");
ddiff = (1 - dpt) / (1 - dt);
#pragma omp parallel sections private(i)
{
#pragma omp section
{
for (i = 0; i < 6; ++i)
{
ddiff -= pow (dt, i);
}
}
#pragma omp section
{
for (i = 6; i < 12; ++i)
{
ddiff -= pow (dt, i);
}
}
#pragma omp section
{
for (i = 12; i < 20; ++i)
{
ddiff -= pow (dt, i);
}
}
}
if (fabs (ddiff) > rounding_error)
{
result++;
fprintf (logFile,
"Error in Difference with doubles: Result was %E instead of 0.0\n",
ddiff);
}
known_product = 3628800;
#pragma omp parallel sections private(i)
{
#pragma omp section
{
for (i = 1; i < 3; i++)
{
product *= i;
}
}
#pragma omp section
{
for (i = 3; i < 7; i++)
{
product *= i;
}
}
#pragma omp section
{
for (i = 7; i < 11; i++)
{
product *= i;
}
}
}
if (known_product != product)
{
result++;
/*printf("\nError in Product: Known Product: %d\tcalculated Product: %d\n\n",known_product,product); */
}
for (i = 0; i < 1000; i++)
{
logics[i] = 1;
}
#pragma omp parallel sections private(i)
{
#pragma omp section
{
for (i = 1; i < 300; i++)
{
logic_and = (logic_and && logics[i]);
}
}
#pragma omp section
{
for (i = 300; i < 700; i++)
{
logic_and = (logic_and && logics[i]);
}
}
#pragma omp section
{
for (i = 700; i < 1000; i++)
{
logic_and = (logic_and && logics[i]);
}
}
}
if (!logic_and)
{
result++;
/*printf("Error in AND part 1\n"); */
}
logic_and = 1;
logics[501] = 0;
#pragma omp parallel sections private(i)
{
#pragma omp section
{
for (i = 1; i < 300; i++)
{
logic_and = (logic_and && logics[i]);
}
}
#pragma omp section
{
for (i = 300; i < 700; i++)
{
logic_and = (logic_and && logics[i]);
}
}
#pragma omp section
{
for (i = 700; i < 1000; i++)
{
logic_and = (logic_and && logics[i]);
}
}
}
if (logic_and)
{
result++;
/*printf("Error in AND part 2"); */
}
for (i = 0; i < 1000; i++)
{
logics[i] = 0;
}
#pragma omp parallel sections private(i)
{
#pragma omp section
{
for (i = 1; i < 300; i++)
{
logic_or = (logic_or && logics[i]);
}
}
#pragma omp section
{
for (i = 300; i < 700; i++)
{
logic_or = (logic_or && logics[i]);
}
}
#pragma omp section
{
for (i = 700; i < 1000; i++)
{
logic_or = (logic_or && logics[i]);
}
}
}
if (logic_or)
{
result++;
/*printf("\nError in OR part 1\n"); */
}
logic_or = 0;
logics[501] = 1;
#pragma omp parallel sections private(i)
{
#pragma omp section
{
for (i = 1; i < 300; i++)
{
logic_or = (logic_or || logics[i]);
}
}
#pragma omp section
{
for (i = 300; i < 700; i++)
{
logic_or = (logic_or || logics[i]);
}
}
#pragma omp section
{
for (i = 700; i < 1000; i++)
{
logic_or = (logic_or || logics[i]);
}
}
}
if (!logic_or)
{
result++;
/*printf("\nError in OR part 2\n"); */
}
for (i = 0; i < 1000; ++i)
{
logics[i] = 1;
}
#pragma omp parallel sections private(i)
{
#pragma omp section
{
for (i = 0; i < 300; ++i)
{
bit_and = (bit_and & logics[i]);
}
}
#pragma omp section
{
for (i = 300; i < 700; ++i)
{
bit_and = (bit_and & logics[i]);
}
}
#pragma omp section
{
for (i = 700; i < 1000; ++i)
{
bit_and = (bit_and & logics[i]);
}
}
}
if (!bit_and)
{
result++;
/*printf("Error in BIT AND part 1\n"); */
}
bit_and = 1;
logics[501] = 0;
#pragma omp parallel sections private(i)
{
#pragma omp section
{
for (i = 0; i < 300; ++i)
{
bit_and = bit_and & logics[i];
}
}
#pragma omp section
{
for (i = 300; i < 700; ++i)
{
bit_and = bit_and & logics[i];
}
}
#pragma omp section
{
for (i = 700; i < 1000; ++i)
{
bit_and = bit_and & logics[i];
}
}
}
if (bit_and)
{
result++;
/*printf("Error in BIT AND part 2"); */
}
for (i = 0; i < 1000; i++)
{
logics[i] = 0;
}
#pragma omp parallel sections private(i)
{
#pragma omp section
{
for (i = 0; i < 300; ++i)
{
bit_or = bit_or | logics[i];
}
}
#pragma omp section
{
for (i = 300; i < 700; ++i)
{
bit_or = bit_or | logics[i];
}
}
#pragma omp section
{
for (i = 700; i < 1000; ++i)
{
bit_or = bit_or | logics[i];
}
}
}
if (bit_or)
{
result++;
/*printf("Error in BIT OR part 1\n"); */
}
bit_or = 0;
logics[501] = 1;
#pragma omp parallel sections private(i)
{
#pragma omp section
{
for (i = 0; i < 300; ++i)
{
bit_or = bit_or | logics[i];
}
}
#pragma omp section
{
for (i = 300; i < 700; ++i)
{
bit_or = bit_or | logics[i];
}
}
#pragma omp section
{
for (i = 700; i < 1000; ++i)
{
bit_or = bit_or | logics[i];
}
}
}
if (!bit_or)
{
result++;
/*printf("Error in BIT OR part 2\n"); */
}
for (i = 0; i < 1000; i++)
{
logics[i] = 0;
}
#pragma omp parallel sections private(i)
{
#pragma omp section
{
for (i = 0; i < 300; ++i)
{
exclusiv_bit_or = exclusiv_bit_or | logics[i];
}
}
#pragma omp section
{
for (i = 300; i < 700; ++i)
{
exclusiv_bit_or = exclusiv_bit_or | logics[i];
}
}
#pragma omp section
{
for (i = 700; i < 1000; ++i)
{
exclusiv_bit_or = exclusiv_bit_or | logics[i];
}
}
}
if (exclusiv_bit_or)
{
result++;
/*printf("Error in EXCLUSIV BIT OR part 1\n"); */
}
exclusiv_bit_or = 0;
logics[501] = 1;
#pragma omp parallel sections private(i)
{
#pragma omp section
{
for (i = 0; i < 300; ++i)
{
exclusiv_bit_or = exclusiv_bit_or | logics[i];
}
}
#pragma omp section
{
for (i = 300; i < 700; ++i)
{
exclusiv_bit_or = exclusiv_bit_or | logics[i];
}
}
#pragma omp section
{
for (i = 700; i < 1000; ++i)
{
exclusiv_bit_or = exclusiv_bit_or | logics[i];
}
}
}
if (!exclusiv_bit_or)
{
result++;
/*printf("Error in EXCLUSIV BIT OR part 2\n"); */
}
/*printf("\nResult:%d\n",result); */
return (result == 0);
}
|
opencl_strip_fmt_plug.c | /* STRIP Password Manager cracker patch for JtR. Hacked together during
* September of 2012 by Dhiru Kholia <dhiru.kholia at gmail.com>.
*
* This software is Copyright (c) 2012 Lukas Odzioba <ukasz@openwall.net>
* and it is hereby released to the general public under the following terms:
* Redistribution and use in source and binary forms, with or without
* modification, are permitted.
*
* This software is Copyright (c) 2012, Dhiru Kholia <dhiru.kholia at gmail.com> */
#ifdef HAVE_OPENCL
#if FMT_EXTERNS_H
extern struct fmt_main fmt_opencl_strip;
#elif FMT_REGISTERS_H
john_register_one(&fmt_opencl_strip);
#else
#include <string.h>
#include <stdint.h>
#ifdef _OPENMP
#include <omp.h>
#endif
#include "arch.h"
#include "aes.h"
#include "formats.h"
#include "options.h"
#include "common.h"
#include "misc.h"
#include "common-opencl.h"
#define FORMAT_LABEL "strip-opencl"
#define FORMAT_NAME "STRIP Password Manager"
#define FORMAT_TAG "$strip$*"
#define FORMAT_TAG_LEN (sizeof(FORMAT_TAG)-1)
#define ALGORITHM_NAME "PBKDF2-SHA1 OpenCL"
#define BENCHMARK_COMMENT ""
#define BENCHMARK_LENGTH -1
#define MIN_KEYS_PER_CRYPT 1
#define MAX_KEYS_PER_CRYPT 1
#define BINARY_SIZE 0
#define PLAINTEXT_LENGTH 64
#define SALT_SIZE sizeof(struct custom_salt)
#define BINARY_ALIGN 1
#define SALT_ALIGN 4
#define ITERATIONS 4000
#define FILE_HEADER_SZ 16
#define SQLITE_FILE_HEADER "SQLite format 3"
#define HMAC_SALT_MASK 0x3a
#define FAST_PBKDF2_ITER 2
#define SQLITE_MAX_PAGE_SIZE 65536
static struct fmt_tests strip_tests[] = {
/* test vector created by STRIP for Windows */
{"$strip$*66cd7a4ff7716f7b86cf587ce18eb39518e096eb152615ada8d007d9f035c20c711e62cbde96d8c3aad2a4658497a6119addc97ed3c970580cd666f301c63ce041a1748ee5c3861ada3cd6ee75b5d68891f731b3c2e3294b08e10ce3c23c2bfac158f8c45d0332791f64d1e3ad55e936d17a42fef5228e713b8188050c9a61c7f026af6203172cf2fc54c8b439e2260d7a00a4156713f92f8466de5c05cd8701e0d3d9cb3f392ae918e6900d5363886d4e1ed7e90da76b180ef9555c1cd358f6d1ee3755a208fee4d5aa1c776a0888200b21a3da6614d5fe2303e78c09563d862d19deecdc9f0ec7fbc015689a74f4eb477d9f22298b1b3f866ca4cb772d74821a1f8d03fd5fd0d020ffd41dd449b431ddf3bbfba3399311d9827be428202ee56e2c2a4e91f3415b4282c691f16cd447cf877b576ab963ea4ea3dc7d8c433febdc36607fd2372c4165abb59e3e75c28142f1f2575ecca6d97a9f782c3410151f8bbcbc65a42fdc59fdc4ecd8214a2bbd3a4562fac21c48f7fc69a4ecbcf664b4e435d7734fde5494e4d80019a0302e22565ed6a49b29cecf81077fd92f0105d18a421e04ee0deaca6389214abc7182db7003da7e267816531010b236eadfea20509718ff743ed5ad2828b6501dd84a371feed26f0514bbda69118a69048ebb71e3e2c54fb918422f1320724a353fe8d81a562197454d2c67443be8a4008a756aec0998386a5fd48e379befe966b42dfa6684ff049a61b51de5f874a12ab7d9ab33dc84738e036e294c22a07bebcc95be9999ab988a1fa1c944ab95be970045accb661249be8cc34fcc0680cb1aff8dfee21f586c571b1d09bf370c6fc131418201e0414acb2e4005b0b6fda1f3d73b7865823a008d1d3f45492a960dbdd6331d78d9e2e6a368f08ee3456b6d78df1d5630f825c536fff60bad23fb164d151d80a03b0c78edbfdee5c7183d7527e289428cf554ad05c9d75011f6b233744f12cd85fbb62f5d1ae22f43946f24a483a64377bf3fa16bf32cea1ab4363ef36206a5989e97ff847e5d645791571b9ecd1db194119b7663897b9175dd9cc123bcc7192eaf56d4a2779c502700e88c5c20b962943084bcdf024dc4f19ca649a860bdbd8f8f9b4a9d03027ae80f4a3168fc030859acb08a871950b024d27306cdc1a408b2b3799bb8c1f4b6ac3593aab42c962c979cd9e6f59d029f8d392315830cfcf4066bf03e0fc5c0f3630e9c796ddb38f51a2992b0a61d6ef115cb34d36c7d94b6c9d49dfe8d064d92b483f12c14fa10bf1170a575e4571836cef0a1fbf9f8b6968abda5e964bb16fd62fde1d1df0f5ee9c68ce568014f46f1717b6cd948b0da9a6f4128da338960dbbcbc9c9c3b486859c06e5e2338db3458646054ccd59bb940c7fc60cda34f633c26dde83bb717b75fefcbd09163f147d59a6524752a47cd94", "openwall"},
/* test vector created by STRIP Password Manager (for Android) */
{"$strip$*78adb0052203efa1bd1b02cac098cc9af1bf7e84ee2eaebaaba156bdcfe729ab12ee7ba8a84e79d11dbd67eee82bcb24be99dbd5db7f4c3a62f188ce4b48edf4ebf6cbf5a5869a61f83fbdb3cb4bf79b3c2c898f422d71eab31afdf3a8d4e97204dedbe7bd8b5e4c891f4880ca917c8b2f67ca06035e7f8db1fae91c45db6a08adf96ec5ddcb9e60b648acf883a7550ea5b67e2d27623e8de315f29cba48b8b1d1bde62283615ab88293b29ad73ae404a42b13e35a95770a504d81e335c00328a6290e411fa2708a697fab7c2d17ff5d0a3fe508118bb43c3d5e72ef563e0ffd337f559085a1373651ca2b8444f4437d8ac0c19aa0a24b248d1d283062afbc3b4ccc9b1861f59518eba771f1d9707affe0222ff946da7c014265ab4ba1f6417dd22d92e4adf5b7e462588f0a42e061a3dad041cbb312d8862aed3cf490df50b710a695517b0c8771a01f82db09231d392d825f5667012e349d2ed787edf8448bbb1ff548bee3a33392cd209e8b6c1de8202f6527d354c3858b5e93790c4807a8967b4c0321ed3a1d09280921650ac33308bd04f35fb72d12ff64a05300053358c5d018a62841290f600f7df0a7371b6fac9b41133e2509cb90f774d02e7202185b9641d063ed38535afb81590bfd5ad9a90107e4ff6d097ac8f35435f307a727f5021f190fc157956414bfce4818a1e5c6af187485683498dcc1d56c074c534a99125c6cfbf5242087c6b0ae10971b0ff6114a93616e1a346a22fcac4c8f6e5c4a19f049bbc7a02d2a31d39548f12440c36dbb253299a11b630e8fd88e7bfe58545d60dce5e8566a0a190d816cb775bd859b8623a7b076bce82c52e9cff6a2d221f9d3fd888ac30c7e3000ba8ed326881ffe911e27bb8982b56caa9a12065721269976517d2862e4a486b7ed143ee42c6566bba04c41c3371220f4843f26e328c33a5fb8450dadc466202ffc5c49cc95827916771e49e0602c3f8468537a81cf2fa1db34c090fccab6254436c05657cf29c3c415bb22a42adeac7870858bf96039b81c42c3d772509fdbe9a94eaf99ee9c59bac3ea97da31e9feac14ed53a0af5c5ebd2e81e40a5140da4f8a44048d5f414b0ba9bfb8024c7abaf5346fde6368162a045d1196f81d55ed746cc6cbd7a7c9cdbfa392279169626437da15a62730c2990772e106a5b84a60edaa6c5b8030e1840aa6361f39a12121a1e33b9e63fb2867d6241de1fb6e2cd1bd9a78c7122258d052ea53a4bff4e097ed49fc17b9ec196780f4c6506e74a5abb10c2545e6f7608d2eefad179d54ad31034576be517affeb3964c65562538dd6ea7566a52c75e4df593895539609a44097cb6d31f438e8f7717ce2bf777c76c22d60b15affeb89f08084e8f316be3f4aefa4fba8ec2cc1dc845c7affbc0ce5ebccdbfde5ebab080a285f02bdfb76c6dbd243e5ee1e5d", "p@$$w0rD"},
{NULL}
};
typedef struct {
uint32_t length;
uint8_t v[PLAINTEXT_LENGTH];
} strip_password;
typedef struct {
uint32_t v[32/4];
} strip_hash;
typedef struct {
uint32_t iterations;
uint32_t outlen;
uint32_t skip_bytes;
uint8_t length;
uint8_t salt[64];
} strip_salt;
static int *cracked;
static int any_cracked;
static struct custom_salt {
unsigned char salt[16];
unsigned char data[1024];
} *cur_salt;
static cl_int cl_error;
static strip_password *inbuffer;
static strip_hash *outbuffer;
static strip_salt currentsalt;
static cl_mem mem_in, mem_out, mem_setting;
static struct fmt_main *self;
static size_t insize, outsize, settingsize, cracked_size;
#define STEP 0
#define SEED 256
// This file contains auto-tuning routine(s). Has to be included after formats definitions.
#include "opencl_autotune.h"
#include "memdbg.h"
static const char * warn[] = {
"xfer: ", ", crypt: ", ", xfer: "
};
/* ------- 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 gws, struct fmt_main *self)
{
insize = sizeof(strip_password) * gws;
outsize = sizeof(strip_hash) * gws;
settingsize = sizeof(strip_salt);
cracked_size = sizeof(*cracked) * gws;
inbuffer = mem_calloc(1, insize);
outbuffer = 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 (inbuffer) {
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];
snprintf(build_opts, sizeof(build_opts),
"-DKEYLEN=%d -DSALTLEN=%d -DOUTLEN=%d",
PLAINTEXT_LENGTH,
(int)sizeof(currentsalt.salt),
(int)sizeof(outbuffer->v));
opencl_init("$JOHN/kernels/pbkdf2_hmac_sha1_unsplit_kernel.cl",
gpu_id, build_opts);
crypt_kernel = clCreateKernel(program[gpu_id], "derive_key", &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(strip_password), 0, db);
// Auto tune execution from shared/included code.
autotune_run(self, 1, 0, 1000);
}
}
static int valid(char *ciphertext, struct fmt_main *self)
{
char *ctcopy;
char *keeptr;
char *p;
int extra;
if (strncmp(ciphertext, FORMAT_TAG, FORMAT_TAG_LEN))
return 0;
ctcopy = strdup(ciphertext);
keeptr = ctcopy;
ctcopy += FORMAT_TAG_LEN; /* skip over "$strip$" and first '*' */
if ((p = strtokm(ctcopy, "*")) == NULL) /* salt + data */
goto err;
if (hexlenl(p, &extra) != 2048 || extra)
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;
int i;
static struct custom_salt *cs;
if (!cs)
cs = mem_alloc_tiny(sizeof(struct custom_salt), 4);
memset(cs, 0, sizeof(struct custom_salt));
ctcopy += FORMAT_TAG_LEN; /* skip over "$strip$" and first '*' */
p = strtokm(ctcopy, "*");
for (i = 0; i < 16; i++)
cs->salt[i] = atoi16[ARCH_INDEX(p[i * 2])] * 16
+ atoi16[ARCH_INDEX(p[i * 2 + 1])];
for (; i < 1024; i++)
cs->data[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, 16);
currentsalt.length = 16;
currentsalt.iterations = ITERATIONS;
currentsalt.outlen = 32;
currentsalt.skip_bytes = 0;
HANDLE_CLERROR(clEnqueueWriteBuffer(queue[gpu_id], mem_setting,
CL_FALSE, 0, settingsize, ¤tsalt, 0, NULL, NULL),
"Copy salt to gpu");
}
#undef set_key
static void 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;
}
/* verify validity of page */
static int verify_page(unsigned char *page1)
{
uint32_t pageSize;
uint32_t usableSize;
//if (memcmp(page1, SQLITE_FILE_HEADER, 16) != 0) {
// return -1;
//}
if (page1[19] > 2) {
return -1;
}
if (memcmp(&page1[21], "\100\040\040", 3) != 0) {
return -1;
}
pageSize = (page1[16] << 8) | (page1[17] << 16);
if (((pageSize - 1) & pageSize) != 0 || pageSize > SQLITE_MAX_PAGE_SIZE || pageSize <= 256) {
return -1;
}
if ((pageSize & 7) != 0) {
return -1;
}
usableSize = pageSize - page1[20];
if (usableSize < 480) {
return -1;
}
return 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");
/// Read the result back
BENCH_CLERROR(clEnqueueReadBuffer(queue[gpu_id], mem_out, CL_TRUE, 0,
outsize, outbuffer, 0, NULL, multi_profilingEvent[2]), "Copy result back");
if (ocl_autotune_running)
return count;
#ifdef _OPENMP
#pragma omp parallel for
#endif
for (index = 0; index < count; index++)
{
unsigned char master[32];
unsigned char output[24];
unsigned char *iv_in;
unsigned char iv_out[16];
int size;
int page_sz = 1008; /* 1024 - strlen(SQLITE_FILE_HEADER) */
int reserve_sz = 16; /* for HMAC off case */
AES_KEY akey;
memcpy(master, outbuffer[index].v, 32);
//memcpy(output, SQLITE_FILE_HEADER, FILE_HEADER_SZ);
size = page_sz - reserve_sz;
iv_in = cur_salt->data + size + 16;
memcpy(iv_out, iv_in, 16);
AES_set_decrypt_key(master, 256, &akey);
/*
* decrypting 8 bytes from offset 16 is enough since the
* verify_page function looks at output[16..23] only.
*/
AES_cbc_encrypt(cur_salt->data + 16, output + 16, 8, &akey, iv_out, AES_DECRYPT);
if (verify_page(output) == 0)
{
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;
}
struct fmt_main fmt_opencl_strip = {
{
FORMAT_LABEL,
FORMAT_NAME,
ALGORITHM_NAME,
BENCHMARK_COMMENT,
BENCHMARK_LENGTH,
0,
PLAINTEXT_LENGTH,
BINARY_SIZE,
BINARY_ALIGN,
SALT_SIZE,
SALT_ALIGN,
MIN_KEYS_PER_CRYPT,
MAX_KEYS_PER_CRYPT,
FMT_CASE | FMT_8_BIT | FMT_OMP | FMT_NOT_EXACT | FMT_HUGE_INPUT,
{ NULL },
{ FORMAT_TAG },
strip_tests
}, {
init,
done,
reset,
fmt_default_prepare,
valid,
fmt_default_split,
fmt_default_binary,
get_salt,
{ NULL },
fmt_default_source,
{
fmt_default_binary_hash
},
fmt_default_salt_hash,
NULL,
set_salt,
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 */
|
convolution_3x3_fp16.c | /*
* Copyright (C) 2016-2022 T-Head Semiconductor Co., Ltd. All rights reserved.
*
* SPDX-License-Identifier: Apache-2.0
*
* 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
*
* 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.
*/
/* CSI-NN2 version 1.12.x */
/*
the conditions for using winograd convolution
in_channel >= 16
out_channel >= 16
input_height <= 120
input_width <= 120
*/
#include "csi_c906.h"
/*
padding input for winograd input transform , and change memory layout to [n c/8 h w 8]
input layout: [n c h w]
input_padded layout: [n c/8 h w 8]
constrain: input channel % 8 = 0
*/
void csi_c906_pad_input_pack1to8_fp16(const __fp16 *input, __fp16 *input_padded, int inc, int inh, int inw,
int padded_h, int padded_w, int pad_top, int pad_left)
{
int inc8 = inc / 8;
int padded_hw = padded_h * padded_w;
__fp16 *pad_ptr = input_padded;
__fp16 *inp_ptr = (__fp16 *)input;
int resi_h = padded_h - pad_top - inh; // remain to pad on h (pad_down)
int resi_w = padded_w - pad_left - inw; // remain to pad on w (pad_right)
asm volatile(
"vsetvli zero, zero, e16, m1\n\t"
"vmv.v.x v2, zero\n\t" // clear v2, for memset value 0
"mulw t1, %6, %7\n\t" // pad_top * padded_w
"mulw t2, %6, %9\n\t" // pad_down * padded_w
"mulw t0, %3, %4\n\t" // input_size per_channel
"slli t0, t0, 1\n\t" // load stride = input_size * 2
"slli t6, t0, 3\n\t" // t6 = input_size * 8 * 2
"1:\n\t" // channel loop [inc/8]
"mv a0, %0\n\t" // update input_addr
"mv t5, %3\n\t" // t5 = in_h
"beqz %7, 3f\n\t" // if pad_top = 0
"mv t3, t1\n\t" // t3 = num to memset
"2:\n\t" // pad h_top
"vse.v v2, (%1)\n\t"
"addi %1, %1, 16\n\t"
"addi t3, t3, -1\n\t"
"bnez t3, 2b\n\t"
"3:\n\t" // pad h_mid
"mv t4, %4\n\t" // t4 = in_w
"beqz %8, 5f\n\t" // if pad_left = 0
"mv t3, %8\n\t" // t3 = pad_left
"4:\n\t" // pad w_left
"vse.v v2, (%1)\n\t"
"addi %1, %1, 16\n\t"
"addi t3, t3, -1\n\t"
"bnez t3, 4b\n\t"
"5:\n\t" // pad w_mid
"vlse.v v4, (a0), t0\n\t"
"addi a0, a0, 2\n\t"
"vse.v v4, (%1)\n\t"
"addi %1, %1, 16\n\t"
"addi t4, t4, -1\n\t"
"bnez t4, 5b\n\t"
"beqz %10, 7f\n\t" // if pad_right = 0
"mv t3, %10\n\t" // t3 = pad_right
"6:\n\t" // pad w_right
"vse.v v2, (%1)\n\t"
"addi %1, %1, 16\n\t"
"addi t3, t3, -1\n\t"
"bnez t3, 6b\n\t"
"7:\n\t"
"addi t5, t5, -1\n\t"
"bnez t5, 3b\n\t"
"beqz %9, 9f\n\t" // if pad_down = 0
"mv t3, t2\n\t" // t3 = num to memset 0
"8:\n\t" // pad h_down
"vse.v v2, (%1)\n\t"
"addi %1, %1, 16\n\t"
"addi t3, t3, -1\n\t"
"bnez t3, 8b\n\t"
"9:\n\t"
"add %0, %0, t6\n\t" // input_data jump to next 8 channel
"addi %2, %2, -1\n\t"
"bnez %2, 1b\n\t"
:"=r"(inp_ptr), // %0
"=r"(pad_ptr), // %1
"=r"(inc8), // %2
"=r"(inh), // %3
"=r"(inw), // %4
"=r"(padded_hw), // %5
"=r"(padded_w), // %6
"=r"(pad_top), // %7
"=r"(pad_left), // %8
"=r"(resi_h), // %9
"=r"(resi_w) // %10
:"0"(inp_ptr),
"1"(pad_ptr),
"2"(inc8),
"3"(inh),
"4"(inw),
"5"(padded_hw),
"6"(padded_w),
"7"(pad_top),
"8"(pad_left),
"9"(resi_h),
"10"(resi_w)
:"cc", "memory", "v2", "v4",
"a0", "t0", "t1", "t2", "t3", "t4", "t5", "t6"
);
}
void csi_c906_crop_output_pack8to1_fp16(const __fp16 *output_trans, __fp16 *output, int out_c, int out_h, int out_w,
int wino_h, int wino_w)
{
int out_c8 = out_c / 8;
__fp16 *out_tm_ptr = (__fp16 *)output_trans;
__fp16 *out_ptr = output;
asm volatile(
"vsetvli zero, zero, e16, m1\n\t"
"mulw t0, %3, %4\n\t" // output_size per_channel
"slli t0, t0, 1\n\t" // store_stride = output_size * 2
"slli t3, t0, 3\n\t" // t3 = output_size * 8 * 2
"slli t4, %6, 4\n\t" // t4 = wino_w * 8 * 2
"mulw t5, %5, %6\n\t" // crop_size per_channel
"slli t5, t5, 4\n\t" // t5 = crop_size * 8 * 2
"1:\n\t" // channel loop [out_ch / 8]
"mv a1, %1\n\t" // update output_addr
"mv a0, %0\n\t" // update crop_addr per-channel
"mv t1, %3\n\t" // t1 = out_h
"2:\n\t" // crop h
"mv t2, %4\n\t" // t2 = out_w
"mv s1, a0\n\t" // update crop_addr per-row
"3:\n\t" // crop w
"vle.v v2, (s1)\n\t"
"addi s1, s1, 16\n\t"
"vsse.v v2, (a1), t0\n\t"
"addi a1, a1, 2\n\t"
"addi t2, t2, -1\n\t"
"bnez t2, 3b\n\t"
"add a0, a0, t4\n\t" // crop-data jump to next row
"addi t1, t1, -1\n\t"
"bnez t1, 2b\n\t"
"4:\n\t"
"add %1, %1, t3\n\t" // output_data jump to next 8 channel
"add %0, %0, t5\n\t" // crop-data jump to next 8 channel
"addi %2, %2, -1\n\t"
"bnez %2, 1b\n\t"
:"=r"(out_tm_ptr), // %0
"=r"(out_ptr), // %1
"=r"(out_c8), // %2
"=r"(out_h), // %3
"=r"(out_w), // %4
"=r"(wino_h), // %5
"=r"(wino_w) // %6
:"0"(out_tm_ptr),
"1"(out_ptr),
"2"(out_c8),
"3"(out_h),
"4"(out_w),
"5"(wino_h),
"6"(wino_w)
:"cc", "memory", "v2", "v3", "a0", "a1", "s1",
"t0", "t1", "t2", "t3", "t4", "t5"
);
}
/*
constrain: output channel % 8 = 0
input channel % 8 = 0
kernel before: [O I 3*3]
kernel after : [O/8 8*8 I 8]
*/
void csi_c906_conv3x3s1_winograd64_transform_kernel_pack8_fp16(struct csi_tensor *o_kernel,
struct csi_tensor *t_kernel)
{
int32_t outch = o_kernel->dim[0];
int32_t inch = o_kernel->dim[1];
__fp16 *kernel_data = (__fp16 *)o_kernel->data;
// for kernel transform buf, 3x3 --> 8x8
__fp16 *kernel_tm = (__fp16 *)csi_mem_alloc(outch * inch * 8 * 8 * sizeof(__fp16));
// kernel transform matrix: G
const __fp16 ktm[8][3] = {
{1.0f, 0.0f, 0.0f},
{-2.0f / 9, -2.0f / 9, -2.0f / 9},
{-2.0f / 9, 2.0f / 9, -2.0f / 9},
{1.0f / 90, 1.0f / 45, 2.0f / 45},
{1.0f / 90, -1.0f / 45, 2.0f / 45},
{1.0f / 45, 1.0f / 90, 1.0f / 180},
{1.0f / 45, -1.0f / 90, 1.0f / 180},
{0.0f, 0.0f, 1.0f}
};
// const __fp16 ktm[8][3] = {
// {1.0f, 0.0f, 0.0f},
// {-2.0f / 9, -2.0f / 9, -2.0f / 9},
// {-2.0f / 9, 2.0f / 9, -2.0f / 9},
// {1.0f / 90, 1.0f / 45, 2.0f / 45},
// {1.0f / 90, -1.0f / 45, 2.0f / 45},
// {32.0f / 45, 16.0f / 45, 8.0f / 45},
// {32.0f / 45, -16.0f / 45, 8.0f / 45},
// {0.0f, 0.0f, 1.0f}
// };
csi_tensor_copy(t_kernel, o_kernel);
for (int p = 0; p < outch; p++) {
for (int q = 0; q < inch; q++) {
const __fp16* kernel0 = kernel_data + p * inch * 9 + q * 9;
__fp16* kernel_tmp = kernel_tm + p * inch * 64 + q * 64;
// transform kernel
const __fp16 *k0 = kernel0;
const __fp16 *k1 = kernel0 + 3;
const __fp16 *k2 = kernel0 + 6;
// h : first compute the transport matrix tmp = (g * GT)T
__fp16 tmp[8][3];
for (int i = 0; i < 8; i++) {
tmp[i][0] = k0[0] * ktm[i][0] + k0[1] * ktm[i][1] + k0[2] * ktm[i][2];
tmp[i][1] = k1[0] * ktm[i][0] + k1[1] * ktm[i][1] + k1[2] * ktm[i][2];
tmp[i][2] = k2[0] * ktm[i][0] + k2[1] * ktm[i][1] + k2[2] * ktm[i][2];
}
// U
for (int j = 0; j < 8; j++) {
__fp16* tmpp = &tmp[j][0];
for (int i = 0; i < 8; i++) {
kernel_tmp[j * 8 + i] = tmpp[0] * ktm[i][0] + tmpp[1] * ktm[i][1] + tmpp[2] * ktm[i][2];
}
}
}
}
// optimized layout for winograd64
__fp16 *kernel_tm_pack8 = (__fp16 *)csi_mem_alloc(outch * inch * 8 * 8 * sizeof(__fp16));
t_kernel->data = kernel_tm_pack8;
for (int oc = 0; oc < outch / 8; oc++) {
__fp16 *g0 = kernel_tm_pack8 + oc * 64 * inch * 8;
const __fp16 *k0 = kernel_tm + oc * 64 * inch * 8;
const __fp16 *k1 = k0 + 64 * inch;
const __fp16 *k2 = k1 + 64 * inch;
const __fp16 *k3 = k2 + 64 * inch;
const __fp16 *k4 = k3 + 64 * inch;
const __fp16 *k5 = k4 + 64 * inch;
const __fp16 *k6 = k5 + 64 * inch;
const __fp16 *k7 = k6 + 64 * inch;
for (int k = 0; k < 64; k++) {
__fp16 *g00 = g0 + k * inch * 8;
for (int ic = 0; ic < inch / 8; ic++) {
for (int i = 0; i < 8; i++) {
const __fp16 *k00 = k0 + (ic * 8 + i) * 64;
const __fp16 *k10 = k1 + (ic * 8 + i) * 64;
const __fp16 *k20 = k2 + (ic * 8 + i) * 64;
const __fp16 *k30 = k3 + (ic * 8 + i) * 64;
const __fp16 *k40 = k4 + (ic * 8 + i) * 64;
const __fp16 *k50 = k5 + (ic * 8 + i) * 64;
const __fp16 *k60 = k6 + (ic * 8 + i) * 64;
const __fp16 *k70 = k7 + (ic * 8 + i) * 64;
g00[0] = k00[k];
g00[1] = k10[k];
g00[2] = k20[k];
g00[3] = k30[k];
g00[4] = k40[k];
g00[5] = k50[k];
g00[6] = k60[k];
g00[7] = k70[k];
g00 += 8;
}
}
}
}
csi_mem_free(kernel_tm);
}
/*
constrain: output channel % 8 = 0
input channel % 8 = 0
*/
int csi_c906_conv3x3s1_winograd64_pack8_fp16(struct csi_tensor *input,
struct csi_tensor *output,
struct csi_tensor *kernel,
struct csi_tensor *bias,
struct conv2d_params *params)
{
// uint64_t start_time, end_time;
// start_time = csi_get_timespec();
__fp16 *input_data = (__fp16 *)input->data;
__fp16 *output_data = (__fp16 *)output->data;
__fp16 *kernel_data = (__fp16 *)params->conv_extra.kernel_tm->data;
__fp16 *bias_data = (__fp16 *)bias->data;
// param
int kernel_h = kernel->dim[2];
int kernel_w = kernel->dim[3];
int stride_h = params->stride_height;
int stride_w = params->stride_width;
int dilation_h = params->dilation_height;
int dilation_w = params->dilation_width;
int pad_left = params->pad_left;
int pad_top = params->pad_top;
int batch = input->dim[0];
int in_c = input->dim[1];
int in_h = input->dim[2];
int in_w = input->dim[3];
int input_size = in_c * in_h * in_w;
int kernel_size = in_c * kernel_h * kernel_w;
int out_c = kernel->dim[0];
int out_h = output->dim[2];
int out_w = output->dim[3];
int output_size = out_c * out_h * out_w;
// winograd param
int block_h = (out_h + 5) / 6;
int block_w = (out_w + 5) / 6;
int padded_in_h = block_h * 6 + 2; // block * 4 for alignment with 4,kernel = 3 * 3 ,stride = 1,thus input_size + 2
int padded_in_w = block_w * 6 + 2;
int padded_in_hw = padded_in_h * padded_in_w; // element size after padding per channel
/****************************** bias *****************************/
bool flag_bias = 1; // default: conv2d layer include bias
if (bias_data == NULL) {
flag_bias = 0;
bias_data = (__fp16 *)csi_mem_alloc(out_c * sizeof(__fp16));
}
for(int n = 0; n < batch; n++) {
// pad buffer: [in_c/8 h w 8]
__fp16 *input_padd_buf = (__fp16 *)csi_mem_alloc(in_c * padded_in_hw * sizeof(__fp16));
// pad input
csi_c906_pad_input_pack1to8_fp16(input_data, input_padd_buf, in_c, in_h, in_w, padded_in_h, padded_in_w, pad_top, pad_left);
input_data += input_size;
// input transform buffer1: [in_ch/8, 64, blocks, 8]
__fp16 *input_tm1_buf = (__fp16 *)csi_mem_alloc(in_c * block_h * block_w * 8 * 8 * sizeof(__fp16));
/****************************** transform input *****************************/
/*
BT = {
{ 1 0 -5.25 0 5.25 0 -1 0 };
{ 0 1 1 -4.25 -4.25 1 1 0 };
{ 0 -1 1 4.25 -4.25 -1 1 0 };
{ 0 0.5 0.25 -2.5 -1.25 2 1 0 };
{ 0 -0.5 0.25 2.5 -1.25 -2 1 0 };
{ 0 2 4 -2.5 -5 0.5 1 0 };
{ 0 -2 4 2.5 -5 -0.5 1 0 };
{ 0 -1 0 5.25 0 -5.25 0 1 }
};
*/
// int in_h_tm = block_h * 8; // input height after transform
// int in_w_tm = block_w * 8;
int tiles = block_h * block_w;
#pragma omp parallel for num_threads(1)
for(int q = 0; q < in_c / 8; q++) {
__fp16 *img0 = input_padd_buf + q * padded_in_h * padded_in_w * 8; // feature map after padding - q channel
__fp16 *img0_tm = input_tm1_buf + q * 64 * tiles * 8; // transform and interleave - q channel
__fp16 *tmp = (__fp16 *)csi_mem_alloc(8 * 8 * 8 * sizeof(__fp16));
// __fp16 tmp[512] = {0.0}; // ??????
for(int i = 0; i < block_h; i++) {
for(int j = 0; j < block_w; j++) {
__fp16 *r0 = img0 + (i * padded_in_w * 6 + j * 6) * 8; // feature map after padding 8*8 start addr
__fp16 *r0_tm = img0_tm + (i * block_w + j) * 8; // input_tm1 8*8 block start addr
__fp16 ratio[] = {5.25, -4.25, 0.25, -1.25, 4.0, 0.5, -2.5, 2.0}; // note: in fact cannot be output constrain
__fp16 *ratio_ptr = ratio;
asm volatile(
"vsetvli zero, zero, e16, m1\n\t"
"li t0, 8\n\t" // m = 8
"mv t5, %2\n\t" // t5 = tmp start addr
"slli t1, %4, 4\n\t" // t1 = padded_in_w * 8 * 2bytes
"flh fa0, 0(%3)\n\t" // fa0 = 5.25
"flh fa1, 2(%3)\n\t" // fa1 = -4.25
"flh fa2, 4(%3)\n\t" // fa2 = 0.25
"flh fa3, 6(%3)\n\t" // fa3 = -1.25
"flh fa4, 8(%3)\n\t" // fa4 = 4.0
"flh fa5, 10(%3)\n\t" // fa5 = 0.5
"flh fa6, 12(%3)\n\t" // fa6 = -2.5
"flh fa7, 14(%3)\n\t" // fa7 = 2.0
"1:\n\t"
"mv s1, %0\n\t" // s1 = r00 addr
"mv a0, t5\n\t" // tmp[0][m]
"addi a1, a0, 128\n\t" // tmp[1][m]
"addi a2, a1, 128\n\t" // tmp[2][m]
"addi a3, a2, 128\n\t" // tmp[3][m]
"addi a4, a3, 128\n\t" // tmp[4][m]
"addi a5, a4, 128\n\t" // tmp[5][m]
"addi a6, a5, 128\n\t" // tmp[6][m]
"addi a7, a6, 128\n\t" // tmp[7][m]
"vle.v v0, (s1)\n\t" // r00
"addi s1, s1, 16\n\t"
"vle.v v1, (s1)\n\t" // r01
"addi s1, s1, 16\n\t"
"vle.v v2, (s1)\n\t" // r02
"addi s1, s1, 16\n\t"
"vle.v v3, (s1)\n\t" // r03
"addi s1, s1, 16\n\t"
"vle.v v4, (s1)\n\t" // r04
"addi s1, s1, 16\n\t"
"vle.v v5, (s1)\n\t" // r05
"addi s1, s1, 16\n\t"
"vle.v v6, (s1)\n\t" // r06
"addi s1, s1, 16\n\t"
"vle.v v7, (s1)\n\t" // r07
"addi s1, s1, 16\n\t"
"vmv.v.v v10, v6\n\t"
//---------------------------------------------
"vfsub.vv v8, v4, v2\n\t" // r04 - r02
"vfsub.vv v9, v3, v5\n\t" // r03 - r05
"vfsub.vv v24, v0, v6\n\t" // r00 - r06
"vfsub.vv v31, v7, v1\n\t" // r07 - r01
"vfmacc.vf v10, fa2, v2\n\t" // r06 + r02 * 0.25f
"vfmul.vf v11, v1, fa5\n\t" // r01 * 0.5f
"vfmul.vf v12, v1, fa7\n\t" // r01 * 2.0f
"vfmacc.vf v24, fa0, v8\n\t" // r00 - r06 + 5.25 * (r04 - r02) = tmp[0][m]
"vfmacc.vf v31, fa0, v9\n\t" // r07 - r01 + 5.25 * (r03 - r05) = tmp[7][m]
//---------------------------------------------
"vfadd.vv v8, v2, v6\n\t" // r02 + r06
"vfadd.vv v9, v1, v5\n\t" // r01 + r05
"vfmacc.vf v11, fa6, v3\n\t" // r01 * 0.5f - r03 * 2.5f
"vfmacc.vf v12, fa6, v3\n\t" // r01 * 2.f - r03 * 2.5f
"vfmacc.vf v2, fa3, v4\n\t" // r02 - r04 * 1.25f 注意
"vfmacc.vf v10, fa3, v4\n\t" // r06 + r02 * 0.25f - r04 * 1.25f = tmp34a
"vfmacc.vf v8, fa1, v4\n\t" // r02 + r06 - r04 * 4.25f = tmp12a
"vfmacc.vf v9, fa1, v3\n\t" // r01 + r05 - r03 * 4.25f = tmp12b
"vfmacc.vf v11, fa7, v5\n\t" // r01 * 0.5f - r03 * 2.5f + r05 * 2.0 = tmp34b
"vfmacc.vf v12, fa5, v5\n\t" // r01 * 2.f - r03 * 2.5f + r05 * 0.5 = tmp56b
"vse.v v24, (a0)\n\t"
"vse.v v31, (a7)\n\t"
"vfadd.vv v25, v8, v9\n\t" // tmp12a + tmp12b = tmp[1][m]
"vfsub.vv v26, v8, v9\n\t" // tmp12a - tmp12b = tmp[2][m]
//---------------------------------------------
"vfmacc.vf v6, fa4, v2\n\t" // r06 + (r02 - r04 * 1.25f) * 4 = tmp56a
"vfadd.vv v27, v10, v11\n\t" // tmp34a + tmp34b = tmp[3][m]
"vfsub.vv v28, v10, v11\n\t" // tmp34a - tmp34b = tmp[4][m]
"vfadd.vv v29, v6, v12\n\t" // tmp56a + tmp56b = tmp[5][m]
"vfsub.vv v30, v6, v12\n\t" // tmp56a - tmp56b = tmp[6][m]
"vse.v v25, (a1)\n\t"
"vse.v v26, (a2)\n\t"
"vse.v v27, (a3)\n\t"
"vse.v v28, (a4)\n\t"
"vse.v v29, (a5)\n\t"
"vse.v v30, (a6)\n\t"
//---------------------------------------------
"add %0, %0, t1\n\t" // padding feature map 8*8 next line addr
"addi t5, t5, 16\n\t" // tmp[0][0] --> tmp[0][1]
"addi t0, t0, -1\n\t"
"bnez t0, 1b\n\t"
"2:\n\t"
"mv t5, %2\n\t" // tmp start addr
"li t0, 8\n\t" // m = 8
"slli t1, %5, 4\n\t" // t1 = tiles * 8 * 2 bytes
"slli t2, %5, 7\n\t" // t2 = tiles * 8 * 8 * 2 bytes
"3:\n\t"
"mv a0, %1\n\t" // r0_tm_0
"add a1, a0, t1\n\t" // r0_tm_1
"add a2, a1, t1\n\t" // r0_tm_2
"add a3, a2, t1\n\t" // r0_tm_3
"add a4, a3, t1\n\t" // r0_tm_4
"add a5, a4, t1\n\t" // r0_tm_5
"add a6, a5, t1\n\t" // r0_tm_6
"add a7, a6, t1\n\t" // r0_tm_7
"vle.v v0, (t5)\n\t" // tmp[m][0]
"addi t5, t5, 16\n\t"
"vle.v v1, (t5)\n\t" // tmp[m][1]
"addi t5, t5, 16\n\t"
"vle.v v2, (t5)\n\t" // tmp[m][2]
"addi t5, t5, 16\n\t"
"vle.v v3, (t5)\n\t" // tmp[m][3]
"addi t5, t5, 16\n\t"
"vle.v v4, (t5)\n\t" // tmp[m][4]
"addi t5, t5, 16\n\t"
"vle.v v5, (t5)\n\t" // tmp[m][5]
"addi t5, t5, 16\n\t"
"vle.v v6, (t5)\n\t" // tmp[m][6]
"addi t5, t5, 16\n\t"
"vle.v v7, (t5)\n\t" // tmp[m][7]
"addi t5, t5, 16\n\t"
"vmv.v.v v10, v6\n\t"
//---------------------------------------------
"vfsub.vv v8, v4, v2\n\t" // tmp04 - tmp02 (tmp[m][4] - tmp[m][2])
"vfsub.vv v9, v3, v5\n\t" // tmp03 - tmp05
"vfsub.vv v24, v0, v6\n\t" // tmp00 - tmp06
"vfsub.vv v31, v7, v1\n\t" // tmp07 - tmp01
"vfmacc.vf v10, fa2, v2\n\t" // tmp06 + tmp02 * 0.25f
"vfmul.vf v11, v1, fa5\n\t" // tmp01 * 0.5f
"vfmul.vf v12, v1, fa7\n\t" // tmp01 * 2.0f
"vfmacc.vf v24, fa0, v8\n\t" // tmp00 - tmp06 + 5.25 * (tmp04 - tmp02) = r0_tm_0[m]
"vfmacc.vf v31, fa0, v9\n\t" // tmp07 - tmp01 + 5.25 * (tmp03 - tmp05) = r0_tm_7[m]
//---------------------------------------------
"vfadd.vv v8, v2, v6\n\t" // tmp02 + tmp06
"vfadd.vv v9, v1, v5\n\t" // tmp01 + tmp05
"vfmacc.vf v11, fa6, v3\n\t" // tmp01 * 0.5f - tmp03 * 2.5f
"vfmacc.vf v12, fa6, v3\n\t" // tmp01 * 2.f - tmp03 * 2.5f
"vfmacc.vf v2, fa3, v4\n\t" // tmp02 - tmp04 * 1.25f
"vfmacc.vf v10, fa3, v4\n\t" // tmp06 + tmp02 * 0.25f - tmp04 * 1.25f = tmp34a
"vfmacc.vf v8, fa1, v4\n\t" // tmp02 + tmp06 - tmp04 * 4.25f = tmp12a
"vfmacc.vf v9, fa1, v3\n\t" // tmp01 + tmp05 - tmp03 * 4.25f = tmp12b
"vfmacc.vf v11, fa7, v5\n\t" // tmp01 * 0.5f - tmp03 * 2.5f + tmp05 * 2.0 = tmp34b
"vfmacc.vf v12, fa5, v5\n\t" // tmp01 * 2.f - tmp03 * 2.5f + tmp05 * 0.5 = tmp56b
"vse.v v24, (a0)\n\t"
"vse.v v31, (a7)\n\t"
"vfadd.vv v25, v8, v9\n\t" // tmp12a + tmp12b = r0_tm_1[m]
"vfsub.vv v26, v8, v9\n\t" // tmp12a - tmp12b = r0_tm_2[m]
//---------------------------------------------
"vfmacc.vf v6, fa4, v2\n\t" // tmp06 + (tmp02 - tmp04 * 1.25f) * 4 = tmp56a
"vfadd.vv v27, v10, v11\n\t" // tmp34a + tmp34b = r0_tm_3[m]
"vfsub.vv v28, v10, v11\n\t" // tmp34a - tmp34b = r0_tm_4[m]
"vfadd.vv v29, v6, v12\n\t" // tmp56a + tmp56b = r0_tm_5[m]
"vfsub.vv v30, v6, v12\n\t" // tmp56a - tmp56b = r0_tm_6[m]
"vse.v v25, (a1)\n\t"
"vse.v v26, (a2)\n\t"
"vse.v v27, (a3)\n\t"
"vse.v v28, (a4)\n\t"
"vse.v v29, (a5)\n\t"
"vse.v v30, (a6)\n\t"
"add %1, %1, t2\n\t"
"addi t0, t0, -1\n\t"
"bnez t0, 3b"
:"=r"(r0), // %0
"=r"(r0_tm), // %1
"=r"(tmp), // %2
"=r"(ratio_ptr), // %3
"=r"(padded_in_w), // %4
"=r"(tiles) // %5
:"0"(r0),
"1"(r0_tm),
"2"(tmp),
"3"(ratio_ptr),
"4"(padded_in_w),
"5"(tiles)
:"cc", "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v24", "v25", "v26", "v27", "v28", "v29", "v30", "v31",
"t0", "t1", "t2", "t5", "s1", "a0", "a1", "a2", "a3", "a4", "a5", "a6", "a7",
"fa0", "fa1", "fa2", "fa3", "fa4", "fa5", "fa6", "fa7"
);
}
}
csi_mem_free(tmp);
}
csi_mem_free(input_padd_buf);
/*********************************** dot ***************************************/
// reorder input_tm1_buf
__fp16 *input_tm2_buf = (__fp16 *)csi_mem_alloc(64 * tiles * in_c * sizeof(__fp16));
#pragma omp parallel for num_threads(1)
for (int r = 0; r < 64; r++) {
__fp16 *img_tm2 = input_tm2_buf + r * tiles * in_c; // input_tm2 r channel data
int t = 0;
for (; t + 7 < tiles; t += 8) {
__fp16 *tm2 = img_tm2 + t * in_c; // img_tm2 row data
__fp16 *tm1 = input_tm1_buf;
tm1 += (r * tiles + t) * 8;
//----------------------------
// for (int q = 0; q < in_c / 8; q++) {
// for (int l = 0; l < 8; l++) {
// tm2[0] = tm1[l];
// tm2[1] = tm1[l + 8 * 1];
// tm2[2] = tm1[l + 8 * 2];
// tm2[3] = tm1[l + 8 * 3];
// tm2[4] = tm1[l + 8 * 4];
// tm2[5] = tm1[l + 8 * 5];
// tm2[6] = tm1[l + 8 * 6];
// tm2[7] = tm1[l + 8 * 7];
// tm2 += 8;
// }
// tm1 += 64 * tiles * 8;
// }
//-----------------------------
asm volatile(
"vsetvli zero, zero, e16, m1\n\t"
"slli t1, %2, 10\n\t" // 64 * tiles * 8 * 2 bytes
"srai t2, %3, 3\n\t" // in_ch8
"1:\n\t" // in_ch loop8
"mv a0, %1\n\t" // updata tm1 addr
"vle.v v0, (a0)\n\t"
"addi a0, a0, 16\n\t"
"vle.v v1, (a0)\n\t"
"addi a0, a0, 16\n\t"
"vle.v v2, (a0)\n\t"
"addi a0, a0, 16\n\t"
"vle.v v3, (a0)\n\t"
"addi a0, a0, 16\n\t"
"vle.v v4, (a0)\n\t"
"addi a0, a0, 16\n\t"
"vle.v v5, (a0)\n\t"
"addi a0, a0, 16\n\t"
"vle.v v6, (a0)\n\t"
"addi a0, a0, 16\n\t"
"vle.v v7, (a0)\n\t"
"vsseg8e.v v0, (%0)\n\t"
"add %1, %1, t1\n\t"
"addi %0, %0, 128\n\t"
"addi t2, t2, -1\n\t"
"bnez t2, 1b\n\t"
:"=r"(tm2), // %0
"=r"(tm1), // %1
"=r"(tiles), // %2
"=r"(in_c) // %3
:"0"(tm2),
"1"(tm1),
"2"(tiles),
"3"(in_c)
:"cc", "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7",
"a0", "t1", "t2"
);
}
for (; t + 3 < tiles; t += 4) {
__fp16 *tm2 = img_tm2 + t * in_c; // img_tm2 row data
__fp16 *tm1 = input_tm1_buf;
tm1 += (r * tiles + t) * 8;
// for (int q = 0; q < in_c / 8; q++) {
// for (int l = 0; l < 8; l++) {
// tm2[0] = tm1[l];
// tm2[1] = tm1[l + 8 * 1];
// tm2[2] = tm1[l + 8 * 2];
// tm2[3] = tm1[l + 8 * 3];
// tm2 += 4;
// }
// tm1 += 64 * tiles * 8;
// }
asm volatile(
"vsetvli zero, zero, e16, m1\n\t"
"slli t1, %2, 10\n\t" // 64 * tiles * 8 * 2 bytes
"srai t2, %3, 3\n\t" // in_ch8
"1:\n\t" // in_ch loop8
"mv a0, %1\n\t" // updata tm1 addr
"vle.v v0, (a0)\n\t"
"addi a0, a0, 16\n\t"
"vle.v v1, (a0)\n\t"
"addi a0, a0, 16\n\t"
"vle.v v2, (a0)\n\t"
"addi a0, a0, 16\n\t"
"vle.v v3, (a0)\n\t"
"vsseg4e.v v0, (%0)\n\t"
"add %1, %1, t1\n\t"
"addi %0, %0, 64\n\t"
"addi t2, t2, -1\n\t"
"bnez t2, 1b\n\t"
:"=r"(tm2), // %0
"=r"(tm1), // %1
"=r"(tiles), // %2
"=r"(in_c) // %3
:"0"(tm2),
"1"(tm1),
"2"(tiles),
"3"(in_c)
:"cc", "memory", "v0", "v1", "v2", "v3",
"a0", "t1", "t2"
);
}
for (; t + 1 < tiles; t += 2) {
__fp16 *tm2 = img_tm2 + t * in_c; // img_tm2 row data
__fp16 *tm1 = input_tm1_buf;
tm1 += (r * tiles + t) * 8;
// for (int q = 0; q < in_c / 8; q++) {
// for (int l = 0; l < 8; l++) {
// tm2[0] = tm1[l];
// tm2[1] = tm1[l + 8];
// tm2 += 2;
// }
// tm1 += 64 * tiles * 8;
// }
asm volatile(
"vsetvli zero, zero, e16, m1\n\t"
"slli t1, %2, 10\n\t" // 64 * tiles * 8 * 2 bytes
"srai t2, %3, 3\n\t" // in_ch8
"1:\n\t" // in_ch loop8
"mv a0, %1\n\t" // updata tm1 addr
"vle.v v0, (a0)\n\t"
"addi a0, a0, 16\n\t"
"vle.v v1, (a0)\n\t"
"vsseg2e.v v0, (%0)\n\t"
"add %1, %1, t1\n\t"
"addi %0, %0, 32\n\t"
"addi t2, t2, -1\n\t"
"bnez t2, 1b\n\t"
:"=r"(tm2), // %0
"=r"(tm1), // %1
"=r"(tiles), // %2
"=r"(in_c) // %3
:"0"(tm2),
"1"(tm1),
"2"(tiles),
"3"(in_c)
:"cc", "memory", "v0", "v1",
"a0", "t1", "t2"
);
}
for (; t < tiles; t++) {
__fp16 *tm2 = img_tm2 + t * in_c; // img_tm2 row data
__fp16 *tm1 = input_tm1_buf;
tm1 += (r * tiles + t) * 8;
// for (int q = 0; q < in_c / 8; q++) {
// for (int l = 0; l < 8; l++) {
// tm2[0] = tm1[l];
// tm2++;
// }
// tm1 += 64 * tiles * 8;
// }
asm volatile(
"vsetvli zero, zero, e16, m1\n\t"
"slli t1, %2, 10\n\t" // 64 * tiles * 8 * 2 bytes
"srai t2, %3, 3\n\t" // in_ch8
"1:\n\t" // in_ch loop8
"mv a0, %1\n\t" // updata tm1 addr
"vle.v v0, (a0)\n\t"
"addi a0, a0, 16\n\t"
"vse.v v0, (%0)\n\t"
"add %1, %1, t1\n\t"
"addi %0, %0, 16\n\t"
"addi t2, t2, -1\n\t"
"bnez t2, 1b\n\t"
:"=r"(tm2), // %0
"=r"(tm1), // %1
"=r"(tiles), // %2
"=r"(in_c) // %3
:"0"(tm2),
"1"(tm1),
"2"(tiles),
"3"(in_c)
:"cc", "memory", "v0",
"a0", "t1", "t2"
);
}
}
csi_mem_free(input_tm1_buf);
// output_dot_buf: [out_c/8, 64, blocks, 8]
__fp16 *output_dot_buf = (__fp16 *)csi_mem_alloc(out_c * block_h * block_w * 8 * 8 * sizeof(__fp16));
#pragma omp parallel for num_threads(1)
for (int p = 0; p < out_c / 8; p++) {
__fp16 *output0_tm = output_dot_buf + p * 64 * tiles * 8;
__fp16 *kernel0_tm = kernel_data + p * 64 * in_c * 8;
for (int r = 0; r < 64; r++) {
__fp16 *img_tm2 = input_tm2_buf + r * tiles * in_c; // img_tm2 第r个channel
int t = 0;
for (; t + 7 < tiles; t += 8) {
__fp16 *r0 = img_tm2 + t * in_c;
__fp16 *k0 = kernel0_tm + r * in_c * 8;
asm volatile(
"vsetvli zero, zero, e16, m1\n\t"
"mv t0, %3\n\t" // t0 = in_c
"vmv.v.x v0, zero\n\t"
"vmv.v.x v1, zero\n\t"
"vmv.v.x v2, zero\n\t"
"vmv.v.x v3, zero\n\t"
"vmv.v.x v4, zero\n\t"
"vmv.v.x v5, zero\n\t"
"vmv.v.x v6, zero\n\t"
"vmv.v.x v7, zero\n\t" // clear
"1:\n\t"
"vle.v v8, (%1)\n\t"
"addi %1, %1, 16\n\t"
"flh fa0, (%0)\n\t"
"flh fa1, 2(%0)\n\t"
"flh fa2, 4(%0)\n\t"
"flh fa3, 6(%0)\n\t"
"flh fa4, 8(%0)\n\t"
"flh fa5, 10(%0)\n\t"
"flh fa6, 12(%0)\n\t"
"flh fa7, 14(%0)\n\t"
"addi %0, %0, 16\n\t"
"vfmacc.vf v0, fa0, v8\n\t"
"vfmacc.vf v1, fa1, v8\n\t"
"vfmacc.vf v2, fa2, v8\n\t"
"vfmacc.vf v3, fa3, v8\n\t"
"vfmacc.vf v4, fa4, v8\n\t"
"vfmacc.vf v5, fa5, v8\n\t"
"vfmacc.vf v6, fa6, v8\n\t"
"vfmacc.vf v7, fa7, v8\n\t"
"addi t0, t0, -1\n\t"
"bnez t0, 1b\n\t"
"vse.v v0, (%2)\n\t"
"addi %2, %2, 16\n\t"
"vse.v v1, (%2)\n\t"
"addi %2, %2, 16\n\t"
"vse.v v2, (%2)\n\t"
"addi %2, %2, 16\n\t"
"vse.v v3, (%2)\n\t"
"addi %2, %2, 16\n\t"
"vse.v v4, (%2)\n\t"
"addi %2, %2, 16\n\t"
"vse.v v5, (%2)\n\t"
"addi %2, %2, 16\n\t"
"vse.v v6, (%2)\n\t"
"addi %2, %2, 16\n\t"
"vse.v v7, (%2)\n\t"
"addi %2, %2, 16\n\t"
:"=r"(r0), // %0
"=r"(k0), // %1
"=r"(output0_tm), // %2
"=r"(in_c) // %3
:"0"(r0),
"1"(k0),
"2"(output0_tm),
"3"(in_c)
:"cc", "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8",
"fa0", "fa1", "fa2", "fa3", "fa4", "fa5", "fa6", "fa7", "t0"
);
}
for (; t + 3 < tiles; t += 4) {
__fp16 *r0 = img_tm2 + t * in_c;
__fp16 *k0 = kernel0_tm + r * in_c * 8;
asm volatile(
"vsetvli zero, zero, e16, m1\n\t"
"mv t0, %3\n\t" // t0 = in_c
"vmv.v.x v0, zero\n\t"
"vmv.v.x v1, zero\n\t"
"vmv.v.x v2, zero\n\t"
"vmv.v.x v3, zero\n\t" // clear
"1:\n\t"
"vle.v v4, (%1)\n\t"
"addi %1, %1, 16\n\t"
"flh fa0, (%0)\n\t"
"flh fa1, 2(%0)\n\t"
"flh fa2, 4(%0)\n\t"
"flh fa3, 6(%0)\n\t"
"addi %0, %0, 8\n\t"
"vfmacc.vf v0, fa0, v4\n\t"
"vfmacc.vf v1, fa1, v4\n\t"
"vfmacc.vf v2, fa2, v4\n\t"
"vfmacc.vf v3, fa3, v4\n\t"
"addi t0, t0, -1\n\t"
"bnez t0, 1b\n\t"
"vse.v v0, (%2)\n\t"
"addi %2, %2, 16\n\t"
"vse.v v1, (%2)\n\t"
"addi %2, %2, 16\n\t"
"vse.v v2, (%2)\n\t"
"addi %2, %2, 16\n\t"
"vse.v v3, (%2)\n\t"
"addi %2, %2, 16\n\t"
:"=r"(r0), // %0
"=r"(k0), // %1
"=r"(output0_tm), // %2
"=r"(in_c) // %3
:"0"(r0),
"1"(k0),
"2"(output0_tm),
"3"(in_c)
:"cc", "memory", "v0", "v1", "v2", "v3", "v4", "fa0", "fa1", "fa2", "fa3", "t0"
);
}
for (; t + 1 < tiles; t += 2) {
__fp16 *r0 = img_tm2 + t * in_c;
__fp16 *k0 = kernel0_tm + r * in_c * 8;
asm volatile(
"vsetvli zero, zero, e16, m1\n\t"
"mv t0, %3\n\t" // t0 = in_c
"vmv.v.x v0, zero\n\t"
"vmv.v.x v1, zero\n\t" // clear
"1:\n\t"
"vle.v v2, (%1)\n\t"
"addi %1, %1, 16\n\t"
"flh fa0, (%0)\n\t"
"flh fa1, 2(%0)\n\t"
"addi %0, %0, 4\n\t"
"vfmacc.vf v0, fa0, v2\n\t"
"vfmacc.vf v1, fa1, v2\n\t"
"addi t0, t0, -1\n\t"
"bnez t0, 1b\n\t"
"vse.v v0, (%2)\n\t"
"addi %2, %2, 16\n\t"
"vse.v v1, (%2)\n\t"
"addi %2, %2, 16\n\t"
:"=r"(r0), // %0
"=r"(k0), // %1
"=r"(output0_tm), // %2
"=r"(in_c) // %3
:"0"(r0),
"1"(k0),
"2"(output0_tm),
"3"(in_c)
:"cc", "memory", "v0", "v1", "v2", "fa0", "fa1", "t0"
);
}
for (; t < tiles; t++) {
__fp16 *r0 = img_tm2 + t * in_c;
__fp16 *k0 = kernel0_tm + r * in_c * 8;
asm volatile(
"vsetvli zero, zero, e16, m1\n\t"
"mv t0, %3\n\t" // t0 = in_c=
"vmv.v.x v0, zero\n\t" // clear
"1:\n\t"
"vle.v v1, (%1)\n\t"
"addi %1, %1, 16\n\t"
"flh fa0, (%0)\n\t"
"addi %0, %0, 2\n\t"
"vfmacc.vf v0, fa0, v1\n\t"
"addi t0, t0, -1\n\t"
"bnez t0, 1b\n\t"
"vse.v v0, (%2)\n\t"
"addi %2, %2, 16\n\t"
:"=r"(r0), // %0
"=r"(k0), // %1
"=r"(output0_tm), // %2
"=r"(in_c) // %3
:"0"(r0),
"1"(k0),
"2"(output0_tm),
"3"(in_c)
:"cc", "memory", "v0", "v1", "fa0", "t0"
);
}
}
}
csi_mem_free(input_tm2_buf);
/*************************** transform output ****************************/
// output_tm1_buf: [out_c/8, out_h6, out_w6, 8]
__fp16 *output_tm1_buf = (__fp16 *)csi_mem_alloc(out_c * block_h * block_w * 6 * 6 * sizeof(__fp16));
/*
AT = {
{ 1 1 1 1 1 1 1 0 };
{ 0 1 -1 2 -2 1/2 -1/2 0 };
{ 0 1 1 4 4 1/4 1/4 0 };
{ 0 1 -1 8 -8 1/8 -1/8 0 };
{ 0 1 1 16 16 1/16 1/16 0 };
{ 0 1 -1 32 -32 1/32 -1/32 1 }
};
AT = {
{ 1 1 1 1 1 32 32 0 };
{ 0 1 -1 2 -2 16 -16 0 };
{ 0 1 1 4 4 8 8 0 };
{ 0 1 -1 8 -8 4 -4 0 };
{ 0 1 1 16 16 2 2 0 };
{ 0 1 -1 32 -32 1 -1 1 }
};
*/
#pragma omp parallel for num_threads(1)
for (int p = 0; p < out_c / 8; p++)
{
__fp16 *bias_tmp = bias_data + p * 8;
__fp16 *out0_tm = output_dot_buf + p * 64 * block_h * block_w * 8; // 输出转换前/dot后 第p个channel
__fp16 *out0 = output_tm1_buf + p * 6*block_h * 6*block_w * 8; // 转换后输出 第p个channel
__fp16 *tmp1 = (__fp16 *)csi_mem_alloc(6 * 8 * 8 * sizeof(__fp16));
// __fp16 tmp[6][8][8];
int out_w6 = block_w * 6;
for (int i = 0; i < block_h; i++) {
for (int j = 0; j < block_w; j++) {
__fp16 *output0_tm_0 = out0_tm + (i * block_w + j) * 8; // 8*8 起始地址
__fp16 *output0 = out0 + (i * block_w * 6 * 6 + j * 6) * 8; // 输出 6*6 的起始地址
__fp16 ratio[] = {2.0, 4.0, 8.0, 16.0, 32.0};
__fp16 *ratio_ptr = ratio;
asm volatile(
"vsetvli zero, zero, e16, m1\n\t"
"li t0, 8\n\t" // m = 8
"mv t5, %2\n\t" // t5 = tmp start addr
"slli t1, %4, 4\n\t" // t1 = tiles * 8 * 2
"slli t2, %4, 7\n\t" // t2 = tiles * 8 * 8 * 2 bytes
"flh fa0, 0(%3)\n\t" // fa0 = 2
"flh fa1, 2(%3)\n\t" // fa1 = 4
"flh fa2, 4(%3)\n\t" // fa2 = 8
"flh fa3, 6(%3)\n\t" // fa3 = 16
"flh fa4, 8(%3)\n\t" // fa4 = 32
"mv s1, %0\n\t"
"1:\n\t" // shape : [6 * 8] * [8 * 8] = [6 * 8]
"mv a0, t5\n\t" // tmp[0][m]
"addi a1, a0, 128\n\t" // tmp[1][m]
"addi a2, a1, 128\n\t" // tmp[2][m]
"addi a3, a2, 128\n\t" // tmp[3][m]
"addi a4, a3, 128\n\t" // tmp[4][m]
"addi a5, a4, 128\n\t" // tmp[5][m]
"vle.v v0, (s1)\n\t" // r00
"add s1, s1, t1\n\t"
"vle.v v1, (s1)\n\t" // r01
"add s1, s1, t1\n\t"
"vle.v v2, (s1)\n\t" // r02
"add s1, s1, t1\n\t"
"vle.v v3, (s1)\n\t" // r03
"add s1, s1, t1\n\t"
"vle.v v4, (s1)\n\t" // r04
"add s1, s1, t1\n\t"
"vle.v v5, (s1)\n\t" // r05
"add s1, s1, t1\n\t"
"vle.v v6, (s1)\n\t" // r06
"add s1, s1, t1\n\t"
"vle.v v7, (s1)\n\t" // r07
"add s1, s1, t1\n\t"
//---------------------------------------------
"vfadd.vv v8, v1, v2\n\t" // r01 + r02 = tmp024a
"vfsub.vv v9, v1, v2\n\t" // r01 - r02 = tmp135a
"vfadd.vv v10, v3, v4\n\t" // r03 + r04 = tmp024b
"vfsub.vv v11, v3, v4\n\t" // r03 - r04 = tmp135b
"vfadd.vv v12, v5, v6\n\t" // r05 + r06 = tmp024c
"vfsub.vv v13, v5, v6\n\t" // r05 - r06 = tmp135c
"vfadd.vv v0, v0, v8\n\t" // r00 + tmp024a
"vfadd.vv v7, v7, v9\n\t" // r07 + tmp135a
"vmv.v.v v14, v10\n\t" // v14 = tmp024b
"vmv.v.v v26, v8\n\t" // v26 = tmp024a
"vmv.v.v v28, v8\n\t" // v28 = tmp024a
"vfmacc.vf v26, fa1, v10\n\t" // tmp024a + tmp024b * 4
"vfmacc.vf v14, fa4, v12\n\t" // tmp024b + tmp024c * 32
"vfmacc.vf v28, fa3, v10\n\t" // tmp024a + tmp024b * 16
"vmv.v.v v15, v13\n\t" // v15 = tmp135c
"vmv.v.v v25, v9\n\t" // v25 = tmp135a
"vmv.v.v v27, v9\n\t" // v27 = tmp135a
"vfadd.vv v24, v0, v14\n\t" // r00 + tmp024a + tmp024b + tmp024c * 32 = tmp[0][m]
"vfmacc.vf v25, fa0, v11\n\t" // tmp135a + tmp135b * 2
"vfmacc.vf v27, fa2, v11\n\t" // tmp135a + tmp135b * 8
//---------------------------------------------
"vse.v v24, (a0)\n\t"
"vfmacc.vf v26, fa2, v12\n\t" // tmp024a + tmp024b * 4 + tmp024c * 8 = tmp[2][m]
"vfmacc.vf v28, fa0, v12\n\t" // tmp024a + tmp024b * 16 + tmp024c + tmp024c = tmp[4][m]
"vfmacc.vf v15, fa4, v11\n\t" // tmp135b * 32 + tmp135c
"vse.v v26, (a2)\n\t"
"vse.v v28, (a4)\n\t"
//---------------------------------------------
"vfmacc.vf v25, fa3, v13\n\t" // tmp135a + tmp135b * 2 + tmp135c * 16 = tmp[1][m]
"vfmacc.vf v27, fa1, v13\n\t" // tmp135a + tmp135b * 8 + tmp135c * 4 = tmp[3][m]
"vfadd.vv v29, v7, v15\n\t" // r07 + tmp135a + tmp135b * 32 + tmp135c
"vse.v v25, (a1)\n\t"
"vse.v v27, (a3)\n\t"
"vse.v v29, (a5)\n\t"
"addi t5, t5, 16\n\t" // tmp[0][0] --> tmp[0][1]
"addi t0, t0, -1\n\t"
"bnez t0, 1b\n\t"
"2:\n\t"
"mv t5, %2\n\t" // tmp start addr
"li t0, 6\n\t" // m = 6
"slli t1, %5, 4\n\t" // t1 = out_w6 * 8 * 2bytes
"vle.v v16, (%6)\n\t" // load 8 channel bias data
"3:\n\t" // shape : [6 * 8] * [6 * 8] = [6 * 6]
"mv a0, %1\n\t"
"addi a1, a0, 16\n\t"
"addi a2, a1, 16\n\t"
"addi a3, a2, 16\n\t"
"addi a4, a3, 16\n\t"
"addi a5, a4, 16\n\t"
"vle.v v0, (t5)\n\t" // tmp[m][0]
"addi t5, t5, 16\n\t"
"vle.v v1, (t5)\n\t" // tmp[m][1]
"addi t5, t5, 16\n\t"
"vle.v v2, (t5)\n\t" // tmp[m][2]
"addi t5, t5, 16\n\t"
"vle.v v3, (t5)\n\t" // tmp[m][3]
"addi t5, t5, 16\n\t"
"vle.v v4, (t5)\n\t" // tmp[m][4]
"addi t5, t5, 16\n\t"
"vle.v v5, (t5)\n\t" // tmp[m][5]
"addi t5, t5, 16\n\t"
"vle.v v6, (t5)\n\t" // tmp[m][6]
"addi t5, t5, 16\n\t"
"vle.v v7, (t5)\n\t" // tmp[m][7]
"addi t5, t5, 16\n\t"
//---------------------------------------------
"vfadd.vv v8, v1, v2\n\t" // tmp[m][1] + tmp[m][2] = tmp024a
"vfsub.vv v9, v1, v2\n\t" // tmp[m][1] - tmp[m][2] = tmp135a
"vfadd.vv v10, v3, v4\n\t" // tmp[m][3] + tmp[m][4] = tmp024b
"vfsub.vv v11, v3, v4\n\t" // tmp[m][3] - tmp[m][4] = tmp135b
"vfadd.vv v12, v5, v6\n\t" // tmp[m][5] + tmp[m][6] = tmp024c
"vfsub.vv v13, v5, v6\n\t" // tmp[m][5] - tmp[m][6] = tmp135c
"vfadd.vv v0, v0, v8\n\t" // tmp[m][0] + tmp024a
"vfadd.vv v7, v7, v9\n\t" // tmp[m][7] + tmp135a
"vmv.v.v v14, v10\n\t" // v14 = tmp024b
"vmv.v.v v26, v8\n\t" // v26 = tmp024a
"vmv.v.v v28, v8\n\t" // v28 = tmp024a
"vfmacc.vf v26, fa1, v10\n\t" // tmp024a + tmp024b * 4
"vfmacc.vf v14, fa4, v12\n\t" // tmp024b + tmp024c * 32
"vfmacc.vf v28, fa3, v10\n\t" // tmp024a + tmp024b * 16
"vmv.v.v v15, v13\n\t" // v15 = tmp135c
"vmv.v.v v25, v9\n\t" // v25 = tmp135a
"vmv.v.v v27, v9\n\t" // v27 = tmp135a
"vfadd.vv v24, v0, v14\n\t" // tmp[m][0] + tmp024a + tmp024b + tmp024c * 32 = tmp[0][m]
"vfmacc.vf v25, fa0, v11\n\t" // tmp135a + tmp135b * 2
"vfmacc.vf v27, fa2, v11\n\t" // tmp135a + tmp135b * 8
//---------------------------------------------
"vfadd.vv v24, v24, v16\n\t" // + bias
"vfmacc.vf v26, fa2, v12\n\t" // tmp024a + tmp024b * 4 + tmp024c * 8 = tmp[2][m]
"vfmacc.vf v28, fa0, v12\n\t" // tmp024a + tmp024b * 16 + tmp024c + tmp024c = tmp[4][m]
"vfmacc.vf v15, fa4, v11\n\t" // tmp135b * 32 + tmp135c
"vse.v v24, (a0)\n\t"
"vfmacc.vf v25, fa3, v13\n\t" // tmp135a + tmp135b * 2 + tmp135c * 16 = tmp[1][m]
"vfmacc.vf v27, fa1, v13\n\t" // tmp135a + tmp135b * 8 + tmp135c * 4 = tmp[3][m]
"vfadd.vv v26, v26, v16\n\t" // + bias
"vfadd.vv v28, v28, v16\n\t" // + bias
"vfadd.vv v29, v7, v15\n\t" // tmp[m][7] + tmp135a + tmp135b * 32 + tmp135c
"vse.v v26, (a2)\n\t"
"vse.v v28, (a4)\n\t"
//---------------------------------------------
"vfadd.vv v25, v25, v16\n\t" // + bias
"vfadd.vv v27, v27, v16\n\t" // + bias
"vfadd.vv v29, v29, v16\n\t" // + bias
"vse.v v25, (a1)\n\t"
"vse.v v27, (a3)\n\t"
"vse.v v29, (a5)\n\t"
"add %1, %1, t1\n\t"
"addi t0, t0, -1\n\t"
"bnez t0, 3b"
:"=r"(output0_tm_0), // %0
"=r"(output0), // %1
"=r"(tmp1), // %2
"=r"(ratio_ptr), // %3
"=r"(tiles), // %4
"=r"(out_w6), // %5
"=r"(bias_tmp) // %6
:"0"(output0_tm_0),
"1"(output0),
"2"(tmp1),
"3"(ratio_ptr),
"4"(tiles),
"5"(out_w6),
"6"(bias_tmp)
:"cc", "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v24", "v25", "v26", "v27", "v28", "v29",
"t0", "t1", "t2", "t5", "s1", "a0", "a1", "a2", "a3", "a4", "a5",
"fa0", "fa1", "fa2", "fa3", "fa4"
);
}
}
csi_mem_free(tmp1);
}
csi_mem_free(output_dot_buf);
// crop the output after transform: cut extra part (right , bottom)
csi_c906_crop_output_pack8to1_fp16(output_tm1_buf, output_data, out_c, out_h, out_w, block_h * 6, block_w * 6);
output_data += output_size;
csi_mem_free(output_tm1_buf);
}
if (!flag_bias) {
csi_mem_free(bias_data);
bias_data = NULL;
}
return CSINN_TRUE;
}
void csi_c906_conv3x3s1_winograd43_transform_kernel_pack8_fp16(struct csi_tensor *o_kernel,
struct csi_tensor *t_kernel)
{
int32_t outch = o_kernel->dim[0];
int32_t inch = o_kernel->dim[1];
__fp16 *kernel_data = (__fp16 *)o_kernel->data;
// for kernel transform buf, 3x3 --> 6x6
__fp16 *kernel_tm = (__fp16 *)csi_mem_alloc(outch * inch * 6 * 6 * sizeof(__fp16));
// kernel transform matrix: G
const __fp16 ktm[6][3] = {
{ 1.0f/4, 0.0f, 0.0f},
{ -1.0f/6, -1.0f/6, -1.0f/6},
{ -1.0f/6, 1.0f/6, -1.0f/6},
{ 1.0f/24, 1.0f/12, 1.0f/6},
{ 1.0f/24, -1.0f/12, 1.0f/6},
{ 0.0f, 0.0f, 1.0f}
};
csi_tensor_copy(t_kernel, o_kernel);
for (int p = 0; p < outch; p++) {
for (int q = 0; q < inch; q++) {
const __fp16* kernel0 = kernel_data + p * inch * 9 + q * 9;
__fp16* kernel_tm0 = kernel_tm + p * inch * 36 + q * 36;
// transform kernel
const __fp16 *k0 = kernel0;
const __fp16 *k1 = kernel0 + 3;
const __fp16 *k2 = kernel0 + 6;
// h : first compute the transport matrix tmp = (g * GT)T
__fp16 tmp[6][3];
for (int i = 0; i < 6; i++) {
tmp[i][0] = k0[0] * ktm[i][0] + k0[1] * ktm[i][1] + k0[2] * ktm[i][2];
tmp[i][1] = k1[0] * ktm[i][0] + k1[1] * ktm[i][1] + k1[2] * ktm[i][2];
tmp[i][2] = k2[0] * ktm[i][0] + k2[1] * ktm[i][1] + k2[2] * ktm[i][2];
}
// U
for (int j = 0; j < 6; j++) {
__fp16* tmpp = &tmp[j][0];
for (int i = 0; i < 6; i++) {
kernel_tm0[j * 6 + i] = tmpp[0] * ktm[i][0] + tmpp[1] * ktm[i][1] + tmpp[2] * ktm[i][2];
}
}
}
}
// [O, I, 6, 6] --> [O/4, 6*6, I, 4]
__fp16 *kernel_tm_pack4 = (__fp16 *)csi_mem_alloc(outch * inch * 6 * 6 * sizeof(__fp16));
t_kernel->data = kernel_tm_pack4;
for (int oc = 0; oc < outch / 8; oc++) {
__fp16 *g0 = kernel_tm_pack4 + oc * 36 * inch * 8;
const __fp16 *k0 = kernel_tm + oc * 36 * inch * 8;
const __fp16 *k1 = k0 + 36 * inch;
const __fp16 *k2 = k1 + 36 * inch;
const __fp16 *k3 = k2 + 36 * inch;
const __fp16 *k4 = k3 + 36 * inch;
const __fp16 *k5 = k4 + 36 * inch;
const __fp16 *k6 = k5 + 36 * inch;
const __fp16 *k7 = k6 + 36 * inch;
for (int k = 0; k < 36; k++) {
__fp16 *g00 = g0 + k * inch * 8;
for (int ic = 0; ic < inch / 8; ic++) {
for (int i = 0; i < 8; i++) {
const __fp16 *k00 = k0 + (ic * 8 + i) * 36;
const __fp16 *k10 = k1 + (ic * 8 + i) * 36;
const __fp16 *k20 = k2 + (ic * 8 + i) * 36;
const __fp16 *k30 = k3 + (ic * 8 + i) * 36;
const __fp16 *k40 = k4 + (ic * 8 + i) * 36;
const __fp16 *k50 = k5 + (ic * 8 + i) * 36;
const __fp16 *k60 = k6 + (ic * 8 + i) * 36;
const __fp16 *k70 = k7 + (ic * 8 + i) * 36;
g00[0] = k00[k];
g00[1] = k10[k];
g00[2] = k20[k];
g00[3] = k30[k];
g00[4] = k40[k];
g00[5] = k50[k];
g00[6] = k60[k];
g00[7] = k70[k];
g00 += 8;
}
}
}
}
csi_mem_free(kernel_tm);
}
int csi_c906_conv3x3s1_winograd43_pack8_fp16(struct csi_tensor *input,
struct csi_tensor *output,
struct csi_tensor *kernel,
struct csi_tensor *bias,
struct conv2d_params *params)
{
__fp16 *input_data = (__fp16 *)input->data;
__fp16 *output_data = (__fp16 *)output->data;
__fp16 *kernel_data = (__fp16 *)params->conv_extra.kernel_tm->data;
__fp16 *bias_data = (__fp16 *)bias->data;
// param
int kernel_h = kernel->dim[2];
int kernel_w = kernel->dim[3];
int stride_h = params->stride_height;
int stride_w = params->stride_width;
int dilation_h = params->dilation_height;
int dilation_w = params->dilation_width;
int pad_left = params->pad_left;
int pad_top = params->pad_top;
int batch = input->dim[0];
int in_c = input->dim[1];
int in_h = input->dim[2];
int in_w = input->dim[3];
int input_size = in_c * in_h * in_w;
int kernel_size = in_c * kernel_h * kernel_w;
int out_c = kernel->dim[0];
int out_h = output->dim[2];
int out_w = output->dim[3];
int output_size = out_c * out_h * out_w;
// winograd param
int block_h = (out_h + 3) / 4;
int block_w = (out_w + 3) / 4;
int padded_in_h = block_h * 4 + 2; // block * 4 for alignment with 4,kernel = 3 * 3, stride = 1,thus input_size + 2
int padded_in_w = block_w * 4 + 2;
int padded_in_hw = padded_in_h * padded_in_w; // element size after padding per channel
/****************************** bias *****************************/
bool flag_bias = 1; // default: conv2d layer include bias
if (bias_data == NULL) {
flag_bias = 0;
bias_data = (__fp16 *)csi_mem_alloc(out_c * sizeof(__fp16));
}
for(int n = 0; n < batch; n++) {
// pad buffer: [in_c/4 h w 4]
__fp16 *input_padd_buf = (__fp16 *)csi_mem_alloc(in_c * padded_in_hw * sizeof(__fp16));
// pad input
csi_c906_pad_input_pack1to8_fp16(input_data, input_padd_buf, in_c, in_h, in_w, padded_in_h, padded_in_w, pad_top, pad_left);
input_data += input_size;
// input transform buffer1: [in_ch/4, 36, blocks, 6]
__fp16 *input_tm1_buf = (__fp16 *)csi_mem_alloc(in_c * block_h * block_w * 6 * 6 * sizeof(__fp16));
/****************************** transform input *****************************/
/*
BT = {
{ 4 0 -5 0 1 0 };
{ 0 -4 -4 1 1 0 };
{ 0 4 -4 -1 1 0 };
{ 0 -2 -1 2 1 0 };
{ 0 2 -1 -2 1 0 };
{ 0 4 0 -5 0 1 }
};
*/
int tiles = block_h * block_w;
#pragma omp parallel for num_threads(1)
for(int q = 0; q < in_c / 4; q++) {
__fp16 *img0 = input_padd_buf + q * padded_in_h * padded_in_w * 8; // feature map after padding - q channel
__fp16 *img0_tm = input_tm1_buf + q * 36 * tiles * 8; // transform and interleave - q channel
__fp16 *tmp = (__fp16 *)csi_mem_alloc(6 * 6 * 8 * sizeof(__fp16));
for(int i = 0; i < block_h; i++) {
for(int j = 0; j < block_w; j++) {
__fp16 *r0 = img0 + (i * padded_in_w * 4 + j * 4) * 8; // feature map after padding 6*6 start addr
__fp16 *r0_tm = img0_tm + (i * block_w + j) * 8; // input_tm1 6*6 block start addr
__fp16 ratio[] = {4, -4, 2, -2, -5}; // note: in fact cannot be output constrain
__fp16 *ratio_ptr = ratio;
asm volatile(
"vsetvli zero, zero, e16, m1\n\t"
"li t0, 6\n\t" // m = 6
"mv t5, %2\n\t" // t5 = tmp start addr
"slli t1, %4, 4\n\t" // t1 = padded_in_w * 8 * 2 bytes
"flh fa0, 0(%3)\n\t" // fa0 = 4
"flh fa1, 2(%3)\n\t" // fa1 = -4
"flh fa2, 4(%3)\n\t" // fa2 = 2
"flh fa3, 6(%3)\n\t" // fa3 = -2
"flh fa4, 8(%3)\n\t" // fa4 = -5
"1:\n\t"
"mv s1, %0\n\t" // s1 = r00 addr
"mv a0, t5\n\t" // tmp[0][m]
"addi a1, a0, 96\n\t" // tmp[1][m]
"addi a2, a1, 96\n\t" // tmp[2][m]
"addi a3, a2, 96\n\t" // tmp[3][m]
"addi a4, a3, 96\n\t" // tmp[4][m]
"addi a5, a4, 96\n\t" // tmp[5][m]
"vle.v v0, (s1)\n\t" // r00
"addi s1, s1, 16\n\t"
"vle.v v1, (s1)\n\t" // r01
"addi s1, s1, 16\n\t"
"vle.v v2, (s1)\n\t" // r02
"addi s1, s1, 16\n\t"
"vle.v v3, (s1)\n\t" // r03
"addi s1, s1, 16\n\t"
"vle.v v4, (s1)\n\t" // r04
"addi s1, s1, 16\n\t"
"vle.v v5, (s1)\n\t" // r05
"addi s1, s1, 16\n\t"
"vmv.v.v v24, v4\n\t"
"vmv.v.v v29, v5\n\t"
//---------------------------------------------
"vfmacc.vf v24, fa0, v0\n\t" // r04 + 4 * r00
"vfmacc.vf v24, fa4, v2\n\t" // r04 + 4 * r00 - 5 * r02
"vse.v v24, (a0)\n\t"
//---------------------------------------------
"vfadd.vv v25, v3, v4\n\t" // r03 + r04
"vfadd.vv v6, v1, v2\n\t" // r01 + r02
"vfmacc.vf v25, fa1, v6\n\t" // r03 + r04 - 4 * (r01 - r02)
"vse.v v25, (a1)\n\t"
//---------------------------------------------
"vfsub.vv v26, v4, v3\n\t" // r04 - r03
"vfsub.vv v7, v1, v2\n\t" // r01 - r02
"vfmacc.vf v26, fa0, v7\n\t" // r04 - r03 + 4 * (r01 - r02)
"vse.v v26, (a2)\n\t"
//---------------------------------------------
"vfsub.vv v8, v1, v3\n\t" // r01 - r03
"vfsub.vv v27, v4, v2\n\t" // r04 - r02
"vfsub.vv v28, v4, v2\n\t" // r04 - r02
"vfmacc.vf v27, fa3, v8\n\t" // r04 - r02 - 2 * (r01 - r03)
"vse.v v27, (a3)\n\t"
"vfmacc.vf v28, fa2, v8\n\t" // r04 - r02 + 2 * (r01 - r03)
"vse.v v28, (a4)\n\t"
//---------------------------------------------
"vfmacc.vf v29, fa0, v1\n\t" // r05 + 4 * r01
"vfmacc.vf v29, fa4, v3\n\t" // r05 + 4 * r01 - 5 * r03
"vse.v v29, (a5)\n\t"
//---------------------------------------------
"add %0, %0, t1\n\t" // padding feature map 6*6 next line addr
"addi t5, t5, 16\n\t" // tmp[0][0] --> tmp[0][1]
"addi t0, t0, -1\n\t"
"bnez t0, 1b\n\t"
"2:\n\t"
"mv t5, %2\n\t" // tmp start addr
"li t0, 6\n\t" // m = 6
"slli t1, %5, 4\n\t" // t1 = tiles * 8 * 2 bytes
"mulw t2, t0, t1\n\t" // t2 = tiles * 6 blocks * 8 channels * 2 bytes
"3:\n\t"
"mv a0, %1\n\t" // r0_tm_0
"add a1, a0, t1\n\t" // r0_tm_1
"add a2, a1, t1\n\t" // r0_tm_2
"add a3, a2, t1\n\t" // r0_tm_3
"add a4, a3, t1\n\t" // r0_tm_4
"add a5, a4, t1\n\t" // r0_tm_5
"vle.v v0, (t5)\n\t" // tmp[m][0]
"addi t5, t5, 16\n\t"
"vle.v v1, (t5)\n\t" // tmp[m][1]
"addi t5, t5, 16\n\t"
"vle.v v2, (t5)\n\t" // tmp[m][2]
"addi t5, t5, 16\n\t"
"vle.v v3, (t5)\n\t" // tmp[m][3]
"addi t5, t5, 16\n\t"
"vle.v v4, (t5)\n\t" // tmp[m][4]
"addi t5, t5, 16\n\t"
"vle.v v5, (t5)\n\t" // tmp[m][5]
"addi t5, t5, 16\n\t"
"vmv.v.v v24, v4\n\t"
"vmv.v.v v29, v5\n\t"
//---------------------------------------------
"vfmacc.vf v24, fa0, v0\n\t" // r04 + 4 * r00
"vfmacc.vf v24, fa4, v2\n\t" // r04 * 4 * r00 - 5 * r02
"vse.v v24, (a0)\n\t"
//---------------------------------------------
"vfadd.vv v25, v3, v4\n\t" // r03 + r04
"vfadd.vv v6, v1, v2\n\t" // r01 + r02
"vfmacc.vf v25, fa1, v6\n\t" // r03 + r04 - 4 * (r01 - r02)
"vse.v v25, (a1)\n\t"
//---------------------------------------------
"vfsub.vv v26, v4, v3\n\t" // r04 - r03
"vfsub.vv v7, v1, v2\n\t" // r01 - r02
"vfmacc.vf v26, fa0, v7\n\t" // r04 - r03 + 4 * (r01 - r02)
"vse.v v26, (a2)\n\t"
//---------------------------------------------
"vfsub.vv v8, v1, v3\n\t" // r01 - r03
"vfsub.vv v27, v4, v2\n\t" // r04 - r02
"vfsub.vv v28, v4, v2\n\t" // r04 - r02
"vfmacc.vf v27, fa3, v8\n\t" // r04 - r02 - 2 * (r01 - r03)
"vse.v v27, (a3)\n\t"
"vfmacc.vf v28, fa2, v8\n\t" // r04 - r02 + 2 * (r01 - r03)
"vse.v v28, (a4)\n\t"
//---------------------------------------------
"vfmacc.vf v29, fa0, v1\n\t" // r05 + 4 * r01
"vfmacc.vf v29, fa4, v3\n\t" // r05 + 4 * r01 - 5 * r03
"vse.v v29, (a5)\n\t"
//---------------------------------------------
"add %1, %1, t2\n\t"
"addi t0, t0, -1\n\t"
"bnez t0, 3b"
:"=r"(r0), // %0
"=r"(r0_tm), // %1
"=r"(tmp), // %2
"=r"(ratio_ptr), // %3
"=r"(padded_in_w), // %4
"=r"(tiles) // %5
:"0"(r0),
"1"(r0_tm),
"2"(tmp),
"3"(ratio_ptr),
"4"(padded_in_w),
"5"(tiles)
:"cc", "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v24", "v25", "v26", "v27", "v28", "v29",
"t0", "t1", "t2", "t5", "s1", "a0", "a1", "a2", "a3", "a4", "a5",
"fa0", "fa1", "fa2", "fa3", "fa4", "fa5"
);
}
}
csi_mem_free(tmp);
}
csi_mem_free(input_padd_buf);
/*********************************** dot ***************************************/
// reorder input_tm1_buf
__fp16 *input_tm2_buf = (__fp16 *)csi_mem_alloc(36 * tiles * in_c * sizeof(__fp16));
#pragma omp parallel for num_threads(1)
for (int r = 0; r < 36; r++) {
__fp16 *img_tm2 = input_tm2_buf + r * tiles * in_c; // input_tm2 r channel data
int t = 0;
for (; t + 7 < tiles; t += 8) {
__fp16 *tm2 = img_tm2 + t * in_c; // img_tm2 row data
__fp16 *tm1 = input_tm1_buf;
tm1 += (r * tiles + t) * 8;
//-----------------
for (int q = 0; q < in_c / 8; q++) {
for (int l = 0; l < 8; l++) {
tm2[0] = tm1[l];
tm2[1] = tm1[l + 8 * 1];
tm2[2] = tm1[l + 8 * 2];
tm2[3] = tm1[l + 8 * 3];
tm2[4] = tm1[l + 8 * 4];
tm2[5] = tm1[l + 8 * 5];
tm2[6] = tm1[l + 8 * 6];
tm2[7] = tm1[l + 8 * 7];
tm2 += 8;
}
tm1 += 36 * tiles * 8;
}
}
for (; t + 3 < tiles; t += 4) {
__fp16 *tm2 = img_tm2 + t * in_c; // img_tm2 row data
__fp16 *tm1 = input_tm1_buf;
tm1 += (r * tiles + t) * 8;
for (int q = 0; q < in_c / 8; q++) {
for (int l = 0; l < 8; l++) {
tm2[0] = tm1[l];
tm2[1] = tm1[l + 8 * 1];
tm2[2] = tm1[l + 8 * 2];
tm2[3] = tm1[l + 8 * 3];
tm2 += 4;
}
tm1 += 36 * tiles * 8;
}
}
for (; t + 1 < tiles; t += 2) {
__fp16 *tm2 = img_tm2 + t * in_c; // img_tm2 row data
__fp16 *tm1 = input_tm1_buf;
tm1 += (r * tiles + t) * 8;
for (int q = 0; q < in_c / 8; q++) {
for (int l = 0; l < 8; l++) {
tm2[0] = tm1[l];
tm2[1] = tm1[l + 8];
tm2 += 2;
}
tm1 += 36 * tiles * 8;
}
}
for (; t < tiles; t++) {
__fp16 *tm2 = img_tm2 + t * in_c; // img_tm2 row data
__fp16 *tm1 = input_tm1_buf;
tm1 += (r * tiles + t) * 8;
for (int q = 0; q < in_c / 8; q++) {
for (int l = 0; l < 8; l++) {
tm2[0] = tm1[l];
tm2++;
}
tm1 += 36 * tiles * 8;
}
}
}
csi_mem_free(input_tm1_buf);
// output_dot_buf: [out_c/4, 36, blocks, 4]
__fp16 *output_dot_buf = (__fp16 *)csi_mem_alloc(out_c * block_h * block_w * 6 * 6 * sizeof(__fp16));
#pragma omp parallel for num_threads(1)
for (int p = 0; p < out_c / 8; p++) {
__fp16 *output0_tm = output_dot_buf + p * 36 * tiles * 8; // 8 channel dot output
__fp16 *kernel0_tm = kernel_data + p * 36 * in_c * 8; // 8 channel kernel
for (int r = 0; r < 36; r++) {
__fp16 *img_tm2 = input_tm2_buf + r * tiles * in_c; // img_tm2 第r个channel
int t = 0;
for (; t + 7 < tiles; t += 8) {
__fp16 *r0 = img_tm2 + t * in_c;
__fp16 *k0 = kernel0_tm + r * in_c * 8;
asm volatile(
"vsetvli zero, zero, e16, m1\n\t"
"mv t0, %3\n\t" // t0 = in_c
"vmv.v.x v0, zero\n\t"
"vmv.v.x v1, zero\n\t"
"vmv.v.x v2, zero\n\t"
"vmv.v.x v3, zero\n\t"
"vmv.v.x v4, zero\n\t"
"vmv.v.x v5, zero\n\t"
"vmv.v.x v6, zero\n\t"
"vmv.v.x v7, zero\n\t" // clear
"1:\n\t"
"flh fa0, (%0)\n\t"
"flh fa1, 2(%0)\n\t"
"flh fa2, 4(%0)\n\t"
"flh fa3, 6(%0)\n\t"
"flh fa4, 8(%0)\n\t"
"flh fa5, 10(%0)\n\t"
"flh fa6, 12(%0)\n\t"
"flh fa7, 14(%0)\n\t"
"addi %0, %0, 16\n\t"
"vle.v v8, (%1)\n\t"
"addi %1, %1, 16\n\t"
"vfmacc.vf v0, fa0, v8\n\t"
"vfmacc.vf v1, fa1, v8\n\t"
"vfmacc.vf v2, fa2, v8\n\t"
"vfmacc.vf v3, fa3, v8\n\t"
"vfmacc.vf v4, fa4, v8\n\t"
"vfmacc.vf v5, fa5, v8\n\t"
"vfmacc.vf v6, fa6, v8\n\t"
"vfmacc.vf v7, fa7, v8\n\t"
"addi t0, t0, -1\n\t"
"bnez t0, 1b\n\t"
"vse.v v0, (%2)\n\t"
"addi %2, %2, 16\n\t"
"vse.v v1, (%2)\n\t"
"addi %2, %2, 16\n\t"
"vse.v v2, (%2)\n\t"
"addi %2, %2, 16\n\t"
"vse.v v3, (%2)\n\t"
"addi %2, %2, 16\n\t"
"vse.v v4, (%2)\n\t"
"addi %2, %2, 16\n\t"
"vse.v v5, (%2)\n\t"
"addi %2, %2, 16\n\t"
"vse.v v6, (%2)\n\t"
"addi %2, %2, 16\n\t"
"vse.v v7, (%2)\n\t"
"addi %2, %2, 16\n\t"
:"=r"(r0), // %0
"=r"(k0), // %1
"=r"(output0_tm), // %2
"=r"(in_c) // %3
:"0"(r0),
"1"(k0),
"2"(output0_tm),
"3"(in_c)
:"cc", "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8",
"fa0", "fa1", "fa2", "fa3", "fa4", "fa5", "fa6", "fa7", "t0"
);
}
for (; t + 3 < tiles; t += 4) {
__fp16 *r0 = img_tm2 + t * in_c;
__fp16 *k0 = kernel0_tm + r * in_c * 8;
asm volatile(
"vsetvli zero, zero, e16, m1\n\t"
"mv t0, %3\n\t" // t0 = in_c
"vmv.v.x v0, zero\n\t"
"vmv.v.x v1, zero\n\t"
"vmv.v.x v2, zero\n\t"
"vmv.v.x v3, zero\n\t" // clear
"1:\n\t"
"flh fa0, (%0)\n\t"
"flh fa1, 2(%0)\n\t"
"flh fa2, 4(%0)\n\t"
"flh fa3, 6(%0)\n\t"
"addi %0, %0, 8\n\t"
"vle.v v4, (%1)\n\t"
"addi %1, %1, 16\n\t"
"vfmacc.vf v0, fa0, v4\n\t"
"vfmacc.vf v1, fa1, v4\n\t"
"vfmacc.vf v2, fa2, v4\n\t"
"vfmacc.vf v3, fa3, v4\n\t"
"addi t0, t0, -1\n\t"
"bnez t0, 1b\n\t"
"vse.v v0, (%2)\n\t"
"addi %2, %2, 16\n\t"
"vse.v v1, (%2)\n\t"
"addi %2, %2, 16\n\t"
"vse.v v2, (%2)\n\t"
"addi %2, %2, 16\n\t"
"vse.v v3, (%2)\n\t"
"addi %2, %2, 16\n\t"
:"=r"(r0), // %0
"=r"(k0), // %1
"=r"(output0_tm), // %2
"=r"(in_c) // %3
:"0"(r0),
"1"(k0),
"2"(output0_tm),
"3"(in_c)
:"cc", "memory", "v0", "v1", "v2", "v3", "v4", "fa0", "fa1", "fa2", "fa3", "t0"
);
}
for (; t + 1 < tiles; t += 2) {
__fp16 *r0 = img_tm2 + t * in_c;
__fp16 *k0 = kernel0_tm + r * in_c * 8;
asm volatile(
"vsetvli zero, zero, e16, m1\n\t"
"mv t0, %3\n\t" // t0 = in_c
"vmv.v.x v0, zero\n\t"
"vmv.v.x v1, zero\n\t" // clear
"1:\n\t"
"flh fa0, (%0)\n\t"
"flh fa1, 2(%0)\n\t"
"addi %0, %0, 4\n\t"
"vle.v v2, (%1)\n\t"
"addi %1, %1, 16\n\t"
"vfmacc.vf v0, fa0, v2\n\t"
"vfmacc.vf v1, fa1, v2\n\t"
"addi t0, t0, -1\n\t"
"bnez t0, 1b\n\t"
"vse.v v0, (%2)\n\t"
"addi %2, %2, 16\n\t"
"vse.v v1, (%2)\n\t"
"addi %2, %2, 16\n\t"
:"=r"(r0), // %0
"=r"(k0), // %1
"=r"(output0_tm), // %2
"=r"(in_c) // %3
:"0"(r0),
"1"(k0),
"2"(output0_tm),
"3"(in_c)
:"cc", "memory", "v0", "v1", "v2", "fa0", "fa1", "t0"
);
}
for (; t < tiles; t++) {
__fp16 *r0 = img_tm2 + t * in_c;
__fp16 *k0 = kernel0_tm + r * in_c * 8;
asm volatile(
"vsetvli zero, zero, e16, m1\n\t"
"mv t0, %3\n\t" // t0 = in_c
"vmv.v.x v0, zero\n\t" // clear
"1:\n\t"
"flw fa0, (%0)\n\t"
"addi %0, %0, 2\n\t"
"vle.v v1, (%1)\n\t"
"addi %1, %1, 16\n\t"
"vfmacc.vf v0, fa0, v1\n\t"
"addi t0, t0, -1\n\t"
"bnez t0, 1b\n\t"
"vse.v v0, (%2)\n\t"
"addi %2, %2, 16\n\t"
:"=r"(r0), // %0
"=r"(k0), // %1
"=r"(output0_tm), // %2
"=r"(in_c) // %3
:"0"(r0),
"1"(k0),
"2"(output0_tm),
"3"(in_c)
:"cc", "memory", "v0", "v1", "fa0", "t0"
);
}
}
}
csi_mem_free(input_tm2_buf);
/*************************** transform output ****************************/
// output_tm1_buf: [out_c/4, out_h4, out_w4, 4]
__fp16 *output_tm1_buf = (__fp16 *)csi_mem_alloc(out_c * block_h * block_w * 4 * 4 * sizeof(__fp16));
/*
AT = {
{ 1 1 1 1 1 0 },
{ 0 1 -1 2 -2 0 },
{ 0 1 1 4 4 0 },
{ 0 1 -1 8 -8 1 }
};
*/
#pragma omp parallel for num_threads(1)
for (int p = 0; p < out_c / 8; p++)
{
__fp16 *bias_tmp = bias_data + p * 8;
__fp16 *out0_tm = output_dot_buf + p * 36 * block_h * block_w * 8; // 输出转换前/dot后 第p个channel
__fp16 *out0 = output_tm1_buf + p * 4*block_h * 4*block_w * 8; // 转换后输出 第p个channel
__fp16 *tmp1 = (__fp16 *)csi_mem_alloc(4 * 6 * 8 * sizeof(__fp16));
int out_w4 = block_w * 4;
for (int i = 0; i < block_h; i++) {
for (int j = 0; j < block_w; j++) {
__fp16 *output0_tm_0 = out0_tm + (i * block_w + j) * 8; // 6*6 起始地址
__fp16 *output0 = out0 + (i * block_w * 4 * 4 + j * 4) * 8; // 输出 4*4 的起始地址
__fp16 ratio[] = {2.0, 4.0, 8.0};
__fp16 *ratio_ptr = ratio;
asm volatile(
"vsetvli zero, zero, e16, m1\n\t"
"li t0, 6\n\t" // m = 6
"mv t5, %2\n\t" // t5 = tmp start addr
"slli t1, %4, 4\n\t" // t1 = tiles * 8 * 2
"mulw t2, t0, t1\n\t" // t2 = tiles * 6 blocks * 8 channels * 2 bytes
"flh fa0, 0(%3)\n\t" // fa0 = 2
"flh fa1, 2(%3)\n\t" // fa1 = 4
"flh fa2, 4(%3)\n\t" // fa2 = 8
"mv s1, %0\n\t"
"1:\n\t" // shape : [4 * 6] * [6 * 6] = [4 * 6]
"mv a0, t5\n\t" // tmp[0][m]
"addi a1, a0, 96\n\t" // tmp[1][m]
"addi a2, a1, 96\n\t" // tmp[2][m]
"addi a3, a2, 96\n\t" // tmp[3][m]
"vle.v v0, (s1)\n\t" // r00
"add s1, s1, t1\n\t"
"vle.v v1, (s1)\n\t" // r01
"add s1, s1, t1\n\t"
"vle.v v2, (s1)\n\t" // r02
"add s1, s1, t1\n\t"
"vle.v v3, (s1)\n\t" // r03
"add s1, s1, t1\n\t"
"vle.v v4, (s1)\n\t" // r04
"add s1, s1, t1\n\t"
"vle.v v5, (s1)\n\t" // r05
"add s1, s1, t1\n\t"
//---------------------------------------------
"vfadd.vv v26, v1, v2\n\t" // r01 + r02 = tmp02a
"vfsub.vv v6, v1, v2\n\t" // r01 - r02 = tmp13a
"vfadd.vv v7, v3, v4\n\t" // r03 + r04 = tmp02b
"vfsub.vv v8, v3, v4\n\t" // r03 - r04 = tmp13b
"vmv.v.v v25, v6\n\t" // v25 = tmp13a
//---------------------------------------------
"vfadd.vv v24, v0, v26\n\t" // r00 + tmp02a
"vfadd.vv v24, v24, v7\n\t" // r00 + tmp02a + tmp02b
"vse.v v24, (a0)\n\t"
"vfmacc.vf v25, fa0, v8\n\t" // tmp13a + 2 * tmp13b
"vse.v v25, (a1)\n\t"
"vfmacc.vf v26, fa1, v7\n\t" // tmp02a + 4 * tmp02b
"vse.v v26, (a2)\n\t"
"vfadd.vv v27, v5, v6\n\t" // r05 + tmp13a
"vfmacc.vf v27, fa2, v8\n\t" // r05 + tmp13a * 8 tmp13b
"vse.v v27, (a3)\n\t"
//---------------------------------------------
"addi t5, t5, 16\n\t" // tmp[0][0] --> tmp[0][1]
"addi t0, t0, -1\n\t"
"bnez t0, 1b\n\t"
"2:\n\t"
"mv t5, %2\n\t" // tmp start addr
"li t0, 4\n\t" // m = 4
"slli t1, %5, 4\n\t" // t1 = out_w4 * 8 * 2 bytes
"vle.v v16, (%6)\n\t" // load 8 channel bias data
"3:\n\t" // shape : [4 * 6] * [6 * 4] = [4 * 4]
"mv a0, %1\n\t"
"addi a1, a0, 16\n\t"
"addi a2, a1, 16\n\t"
"addi a3, a2, 16\n\t"
"vle.v v0, (t5)\n\t" // tmp[m][0]
"addi t5, t5, 16\n\t"
"vle.v v1, (t5)\n\t" // tmp[m][1]
"addi t5, t5, 16\n\t"
"vle.v v2, (t5)\n\t" // tmp[m][2]
"addi t5, t5, 16\n\t"
"vle.v v3, (t5)\n\t" // tmp[m][3]
"addi t5, t5, 16\n\t"
"vle.v v4, (t5)\n\t" // tmp[m][4]
"addi t5, t5, 16\n\t"
"vle.v v5, (t5)\n\t" // tmp[m][5]
"addi t5, t5, 16\n\t"
//---------------------------------------------
"vfadd.vv v26, v1, v2\n\t" // r01 + r02 = tmp02a
"vfsub.vv v6, v1, v2\n\t" // r01 - r02 = tmp13a
"vfadd.vv v7, v3, v4\n\t" // r03 + r04 = tmp02b
"vfsub.vv v8, v3, v4\n\t" // r03 - r04 = tmp13b
"vmv.v.v v25, v6\n\t" // v25 = tmp13a
//---------------------------------------------
"vfadd.vv v24, v0, v26\n\t" // r00 + tmp02a
"vfadd.vv v24, v24, v7\n\t" // r00 + tmp02a + tmp02b
"vfadd.vv v24, v24, v16\n\t" // add bias
"vse.v v24, (a0)\n\t"
"vfmacc.vf v25, fa0, v8\n\t" // tmp13a + 2 * tmp13b
"vfadd.vv v25, v25, v16\n\t" // add bias
"vse.v v25, (a1)\n\t"
"vfmacc.vf v26, fa1, v7\n\t" // tmp02a + 4 * tmp02b
"vfadd.vv v26, v26, v16\n\t" // add bias
"vse.v v26, (a2)\n\t"
"vfadd.vv v27, v5, v6\n\t" // r05 + tmp13a
"vfmacc.vf v27, fa2, v8\n\t" // r05 + tmp13a * 8 tmp13b
"vfadd.vv v27, v27, v16\n\t" // add bias
"vse.v v27, (a3)\n\t"
"add %1, %1, t1\n\t"
"addi t0, t0, -1\n\t"
"bnez t0, 3b"
:"=r"(output0_tm_0), // %0
"=r"(output0), // %1
"=r"(tmp1), // %2
"=r"(ratio_ptr), // %3
"=r"(tiles), // %4
"=r"(out_w4), // %5
"=r"(bias_tmp) // %6
:"0"(output0_tm_0),
"1"(output0),
"2"(tmp1),
"3"(ratio_ptr),
"4"(tiles),
"5"(out_w4),
"6"(bias_tmp)
:"cc", "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v16", "v24", "v25", "v26", "v27",
"t0", "t1", "t2", "t5", "s1", "a0", "a1", "a2", "a3",
"fa0", "fa1", "fa2"
);
}
}
csi_mem_free(tmp1);
}
csi_mem_free(output_dot_buf);
// crop the output after transform: cut extra part (right , bottom)
csi_c906_crop_output_pack8to1_fp16(output_tm1_buf, output_data, out_c, out_h, out_w, block_h * 4, block_w * 4);
output_data += output_size;
csi_mem_free(output_tm1_buf);
}
if (!flag_bias) {
csi_mem_free(bias_data);
bias_data = NULL;
}
return CSINN_TRUE;
}
void csi_c906_conv3x3s1_fp16(struct csi_tensor *input,
struct csi_tensor *output,
struct csi_tensor *kernel,
struct csi_tensor *bias,
struct conv2d_params *params)
{
/* to do */
}
void csi_c906_conv3x3s2_fp16(struct csi_tensor *input,
struct csi_tensor *output,
struct csi_tensor *kernel,
struct csi_tensor *bias,
struct conv2d_params *params)
{
/* to do */
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.