index
int64
0
0
repo_id
stringclasses
93 values
file_path
stringlengths
15
128
content
stringlengths
14
7.05M
0
ALLM/M3/octopus
ALLM/M3/octopus/liboct_parser/gsl_userdef.c
/* Copyright (C) 2002 M. Marques, A. Castro, A. Rubio, G. Bertsch 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, 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <gsl/gsl_complex_math.h> #include <gsl/gsl_sf_erf.h> #include <math.h> #include <stdlib.h> /* ------------------------------------------------------ */ gsl_complex gsl_complex_step_real (gsl_complex a) { gsl_complex z; if (GSL_REAL(a) < 0) { GSL_SET_COMPLEX (&z, 0, 0); } else { GSL_SET_COMPLEX (&z, 1, 0); } return z; } /* ------------------------------------------------------ */ gsl_complex gsl_complex_min_real (gsl_complex a, gsl_complex b) { gsl_complex z; double min; /* just consider real parts */ min = GSL_REAL(a) < GSL_REAL(b) ? GSL_REAL(a) : GSL_REAL(b); GSL_SET_COMPLEX (&z, min, 0); return z; } /* ------------------------------------------------------ */ gsl_complex gsl_complex_max_real (gsl_complex a, gsl_complex b) { gsl_complex z; double max; /* just consider real parts */ max = GSL_REAL(a) > GSL_REAL(b) ? GSL_REAL(a) : GSL_REAL(b); GSL_SET_COMPLEX (&z, max, 0); return z; } /* ------------------------------------------------------ */ gsl_complex gsl_complex_carg (gsl_complex a) { gsl_complex z; GSL_SET_COMPLEX (&z, gsl_complex_arg(a), 0); return z; } /* ------------------------------------------------------ */ gsl_complex gsl_complex_cabs (gsl_complex a) { gsl_complex z; GSL_SET_COMPLEX (&z, gsl_complex_abs(a), 0); return z; } /* ------------------------------------------------------ */ gsl_complex gsl_complex_cabs2 (gsl_complex a) { gsl_complex z; GSL_SET_COMPLEX (&z, gsl_complex_abs2(a), 0); return z; } /* ------------------------------------------------------ */ gsl_complex gsl_complex_clogabs (gsl_complex a) { gsl_complex z; GSL_SET_COMPLEX (&z, gsl_complex_logabs(a), 0); return z; } /* ------------------------------------------------------ */ gsl_complex gsl_complex_erf (gsl_complex a) { gsl_complex z; GSL_SET_COMPLEX (&z, gsl_sf_erf(GSL_REAL(a)), 0); return z; } /* ------------------------------------------------------ */ gsl_complex gsl_complex_arctan2 (gsl_complex a, gsl_complex b) { gsl_complex z, p; if(GSL_REAL(b) != 0.0) { z = gsl_complex_arctan(gsl_complex_div(a, b)); if(GSL_REAL(b) < 0.0){ GSL_SET_COMPLEX (&p, M_PI, 0); if(GSL_REAL(a) >= 0.0) z = gsl_complex_add(z, p); else z = gsl_complex_sub(z, p); } } else { if(GSL_REAL(a) >= 0.0) { GSL_SET_COMPLEX (&z, M_PI/2.0, 0.0); } else { GSL_SET_COMPLEX (&z, -M_PI/2.0, 0.0); } } return z; } /* ------------------------------------------------------ */ gsl_complex gsl_complex_realpart (gsl_complex a) { gsl_complex z; GSL_SET_COMPLEX (&z, GSL_REAL(a), 0); return z; } /* ------------------------------------------------------ */ gsl_complex gsl_complex_imagpart (gsl_complex a) { gsl_complex z; GSL_SET_COMPLEX (&z, GSL_IMAG(a), 0); return z; } /* ------------------------------------------------------ */ gsl_complex gsl_complex_round (gsl_complex a) { gsl_complex z; GSL_SET_COMPLEX (&z, trunc(GSL_REAL(a)), 0); return z; } /* ------------------------------------------------------ */ gsl_complex gsl_complex_ceiling (gsl_complex a) { gsl_complex z; GSL_SET_COMPLEX (&z, ceil(GSL_REAL(a)), 0); return z; } /* ------------------------------------------------------ */ gsl_complex gsl_complex_floor (gsl_complex a) { gsl_complex z; GSL_SET_COMPLEX (&z, floor(GSL_REAL(a)), 0); return z; } /* ------------------------------------------------------ */ void gsl_complex_rand_seed(long a) { srandom(a); } /* ------------------------------------------------------ */ gsl_complex gsl_complex_rand (gsl_complex a) { double r = random()/((double) RAND_MAX); return gsl_complex_rect(r, 0.0); }
0
ALLM/M3/octopus
ALLM/M3/octopus/liboct_parser/gsl_userdef.h
/* Copyright (C) 2002 M. Marques, A. Castro, A. Rubio, G. Bertsch 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, 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __GSL_USERDEF_H__ #define __GSL_USERDEF_H__ /* Heaviside step function */ gsl_complex gsl_complex_step_real (double a); /* Minimum and maximum of two arguments (comparing real parts) */ gsl_complex gsl_complex_min_real (gsl_complex a, gsl_complex b); gsl_complex gsl_complex_max_real (gsl_complex a, gsl_complex b); /* arg, abs, abs2 and logabs with complex return values for consistency */ gsl_complex gsl_complex_carg (gsl_complex a); gsl_complex gsl_complex_cabs (gsl_complex a); gsl_complex gsl_complex_cabs2 (gsl_complex a); gsl_complex gsl_complex_clogabs (gsl_complex a); /* error function */ gsl_complex gsl_complex_erf(gsl_complex a); /* atan2 function */ gsl_complex gsl_complex_arctan2 (gsl_complex a, gsl_complex b); gsl_complex gsl_complex_realpart (gsl_complex a); gsl_complex gsl_complex_imagpart (gsl_complex a); gsl_complex gsl_complex_round (gsl_complex a); gsl_complex gsl_complex_ceiling (gsl_complex a); gsl_complex gsl_complex_floor (gsl_complex a); void gsl_complex_rand_seed(long a); gsl_complex gsl_complex_rand(); #endif /* __GSL_USERDEF_H__ */
0
ALLM/M3/octopus
ALLM/M3/octopus/liboct_parser/liboct_parser.h
/* Copyright (C) 2002 M. Marques, A. Castro, A. Rubio, G. Bertsch 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, 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef _LIB_OCT_H #define _LIB_OCT_H #include <gsl/gsl_complex.h> #include <stdint.h> int parse_init (const char *file_out, const int *mpiv_node); int parse_input (const char *file_in, int set_used); int parse_input_string (const char *file_in, int set_used); void parse_environment (const char *file_in); void parse_end (void); int parse_isdef (const char *name); int64_t parse_int (const char *name, int64_t def); double parse_double (const char *name, double def); gsl_complex parse_complex(const char *name, gsl_complex def); char *parse_string (const char *name, char *def); /* Now comes stuff for the blocks */ typedef struct sym_block_line{ int n; } sym_block_line; typedef struct sym_block{ int n; sym_block_line *lines; char* name; } sym_block; int parse_block (const char *name, sym_block **blk); int parse_block_end (sym_block **blk); int parse_block_n (const sym_block *blk); int parse_block_cols (const sym_block *blk, int l); int parse_block_int (const sym_block *blk, int l, int col, int *r); int parse_block_int8 (const sym_block *blk, int l, int col, int64_t *r); int parse_block_double (const sym_block *blk, int l, int col, double *r); int parse_block_complex(const sym_block *blk, int l, int col, gsl_complex *r); int parse_block_string (const sym_block *blk, int l, int col, char **r); /* from parse_exp.c */ enum pr_type {PR_NONE,PR_CMPLX, PR_STR}; typedef struct parse_result{ union { gsl_complex c; char *s; } value; enum pr_type type; } parse_result; void parse_result_free(parse_result *t); int parse_exp(char *exp, parse_result *t); void parse_putsym_int(const char *s, int i); void parse_putsym_double(const char *s, double d); void parse_putsym_complex(const char *s, gsl_complex c); #endif
0
ALLM/M3/octopus
ALLM/M3/octopus/liboct_parser/parse.c
/* Copyright (C) 2002 - 2024 M. Marques, A. Castro, A. Rubio, G. Bertsch, D. Strubbe, A. Buccheri 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, 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <math.h> #include <assert.h> extern char ** environ; #include "error_handling.h" #include "liboct_parser.h" #include "symbols.h" #include "gsl_userdef.h" #define ROUND(x) ((x)<0 ? (int64_t)(x-0.5) : (int64_t)(x+0.5)) static FILE *fout; static int disable_write; const static char block_delimiter = '%'; void str_trim(char *in) { char *c, *s = in; for(c=s; isspace(*c); c++); for(; *c != '\0'; *s++=*c++); for(s--; s>=in && isspace(*s); s--); *(s+1) = '\0'; } static int parse_get_line(FILE *f, char **s, int *length) { int i, c; i = 0; do{ c = getc(f); if(c == '#') /* skip comments */ while(c!=EOF && c!='\n') c = getc(f); else if(c != EOF){ if (i == *length - 1){ *length *= 2; *s = (char *)realloc(*s, *length + 1); } /* check for continuation lines */ if(i > 0 && c == '\n' && (*s)[i-1] == '\\'){ c = 'd'; /* dummy */ i--; }else (*s)[i++] = (char)c; } }while(c != EOF && c != '\n'); (*s)[i] = '\0'; str_trim(*s); return c; } int parse_init(const char *file_out, const int *mpiv_node) { sym_init_table(); /* only enable writes for node 0 */ disable_write = *mpiv_node; if(disable_write) return 0; if(strcmp(file_out, "-") == 0) fout = stdout; else { fout = fopen(file_out, "w"); if(!fout) return -1; /* error opening file */ setvbuf(fout, NULL, _IONBF, 0); } fprintf(fout, "# Octopus parser started\n"); return 0; } /** * @brief Parses a data block from the input file. * * This function reads lines from the input file until a block delimiter is encountered. * It then parses each line within the block, splitting it into columns delimited by '|' or '\t'. * The parsed data is stored as a matrix-like structure in the symbol table. * If the block is already defined in the symbol table, it skips the block and moves the file pointer on. * * @param f A pointer to the input file. * @param s A pointer to a pointer to the current line buffer. The function may implicitly * reallocate this buffer if needed to accommodate longer lines, via `parse_get_line`. * @param length A pointer to an integer representing the current size of the line buffer. * This value is updated if the buffer is reallocated, via `parse_get_line`. * @param pc A pointer to a parse_result structure. * * @warning This function modifies the `*s` buffer and the `length` variable. The caller must ensure * that the `*s` buffer is properly allocated and freed after use. */ int parse_input_block(FILE *f, char **s, int *length, parse_result *pc) { int c; **s = ' '; str_trim(*s); // If the block is already defined in the symbol table, skip it if (getsym(*s) != NULL) { fprintf(stderr, "Parser warning: Block \"%s\" already defined.\n", *s); do { c = parse_get_line(f, s, length); } while (c != EOF && **s != block_delimiter); return c; } symrec *rec = putsym(*s, S_BLOCK); rec->value.block = (sym_block *) malloc(sizeof(sym_block)); if (!rec->value.block) { error_return(-1, "malloc failed to allocate rec->value.block"); } rec->value.block->n = 0; rec->value.block->lines = NULL; do { c = parse_get_line(f, s, length); // If line is not empty, and not a block delimiter if (**s && **s != block_delimiter) { char *s1, *tok; int l, col; l = rec->value.block->n; rec->value.block->n++; rec->value.block->lines = (sym_block_line *) realloc((void *) rec->value.block->lines, sizeof(sym_block_line) * (l + 1)); rec->value.block->lines[l].n = 0; /* parse columns */ for (s1 = *s; (tok = strtok(s1, "|\t")) != NULL; s1 = NULL) { char *tok2 = strdup(tok); #ifndef NDEBUG if (!tok2) { // Likely an error with the parsed line *s error_abort("String tokenize failed parsing inp block"); } #endif str_trim(tok2); col = rec->value.block->lines[l].n; char *mtxel = (char *) malloc(strlen(tok2) + strlen(rec->name) + 20); assert(mtxel); sprintf(mtxel, "%s[%i][%i] = %s", rec->name, l, col, tok2); parse_exp(mtxel, pc); free(mtxel); free(tok2); rec->value.block->lines[l].n++; } } } while (c != EOF && **s != block_delimiter); return c; } /** * @brief Parses an input file to extract and set a random seed value, if present. * * This function scans the input file, searching for a line that begins with the keyword "RandomSeed". * If found, the function parses the rest of the line to extract a numerical value, which is then used * to seed the GNU Scientific Library's (GSL) complex random number generator. * * @param f A pointer to the input file to be parsed. * @param s A pointer to a character pointer that stores the line read from the file. * @param length A pointer to an integer representing the length of the line buffer. * * @warning This function has limited error handling. It does not validate the seed value's format * or check if it's within the valid range for the GSL random number generator. * * @see parse_get_line * @see parse_exp * @see gsl_complex_rand_seed */ void parse_and_set_random_seed(FILE *f, char **s, int *length) { int c; do { c = parse_get_line(f, s, length); if (strncmp("RandomSeed", *s, 10) == 0) { parse_result rs; parse_exp(*s, &rs); printf("value %ld\n", lround(GSL_REAL(rs.value.c))); gsl_complex_rand_seed(lround(GSL_REAL(rs.value.c))); return; } } while (c != EOF); } /** * @brief Parse an input file. * * This function parses an input file and stores the data as a matrix-like structure in the symbol * table. It is capable of handling recursive nesting of files if a line begins with `include`. * * @param f A pointer to a FILE object. * @param set_used A integer indicating whether to mark symbols in the symbol table as used. * **/ int parse_file_stream(FILE *f, const int set_used) { char *s; int c, length = 0; parse_result pc; const int initial_length = 40; // initial_length is just a starter length, not the maximum length = initial_length; s = (char *) malloc(length + 1); if (!s) { error_return(-1, "malloc failed to allocate initial length for line char"); } // Parse the file once, for RandomSeed long start_pos = ftell(f); parse_and_set_random_seed(f, &s, &length); fseek(f, start_pos, SEEK_SET); // Parse the file do { c = parse_get_line(f, &s, &length); if (!*s) { continue; } // Include another file if (strncmp("include ", s, 8) == 0) { /* wipe out leading 'include' with blanks */ memcpy(s, " ", 7); str_trim(s); if (!disable_write) { fprintf(fout, "# including file '%s'\n", s); } c = parse_input(s, 0); if (c != 0) { fprintf(stderr, "Parser error: cannot open included file '%s'.\n", s); exit(1); } } else if (*s == block_delimiter) { // Parse a block c = parse_input_block(f, &s, &length, &pc); } else { // Parse a single line that does not start with include parse_exp(s, &pc); } } while (c != EOF); free(s); if (f != stdin) { fclose(f); } if (set_used == 1) { sym_mark_table_used(); } return 0; } /** * @brief Parse an input file. * * This function parses an input file and stores the data as a matrix-like structure in the symbol * table. It is capable of handling recursive nesting of files, via the `include` key. * * @param file_in File name. * @param set_used An integer indicating whether to mark symbols in the symbol table as used. * **/ int parse_input(const char *file_in, int set_used) { FILE *f = (strcmp(file_in, "-") == 0) ? stdin : fopen(file_in, "r"); if (!f) { error_return(-1, "There was an error reading \"%s\"", file_in); } return parse_file_stream(f, set_used); } /** * @brief Parse an input string. * * This function parses an input string and stores the data as a matrix-like structure in the symbol * table. It is capable of handling recursive nesting of files, via the `include` key. * * @param file_contents Contents of the input file. * @param set_used An integer indicating whether to mark symbols in the symbol table as used. * **/ int parse_input_string(const char *file_contents, int set_used) { FILE *f = fmemopen((void *)file_contents, strlen(file_contents), "r"); if (!f) { error_return(-1, "There was an error reading an input string"); } return parse_file_stream(f, set_used); } /* If *_PARSE_ENV is set, then environment variables beginning with prefix are read and set, overriding input file if defined there too. */ void parse_environment(const char* prefix) { char* flag; parse_result pc; flag = (char *)malloc(strlen(prefix) + 11); strcpy(flag, prefix); strcat(flag, "PARSE_ENV"); if( getenv(flag)!=NULL ) { if(!disable_write) fprintf(fout, "# %s is set, parsing environment variables\n", flag); /* environ is an array of C strings with all the environment variables, the format of the string is NAME=VALUE, which is directly recognized by parse_exp */ char **env = environ; while(*env) { /* Only consider variables that begin with the prefix, except the PARSE_ENV flag */ if( strncmp(flag, *env, strlen(flag)) != 0 && strncmp(prefix, *env, strlen(prefix)) == 0 ){ if(!disable_write) fprintf(fout, "# parsed from environment: %s\n", (*env) + strlen(prefix)); parse_exp( (*env) + strlen(prefix), &pc); } env++; } } free(flag); } char* get_mtxel_name(const char* block, int l, int col) { char *mtxel = (char *)malloc(strlen(block) + 20); sprintf(mtxel, "%s[%i][%i]", block, l, col); return mtxel; } void parse_end() { sym_end_table(); if(!disable_write) { fprintf(fout, "# Octopus parser ended\n"); if(fout != stdout) fclose(fout); } } int parse_isdef(const char *name) { if(getsym(name) == NULL) return 0; return 1; } static void check_is_numerical(const char * name, const symrec * ptr){ if( ptr->type != S_CMPLX){ fprintf(stderr, "Parser error: expecting a numerical value for variable '%s' and found a string.\n", name); exit(1); } } int64_t parse_int(const char *name, int64_t def) { symrec *ptr; int64_t ret; ptr = getsym(name); if(ptr){ check_is_numerical(name, ptr); ret = ROUND(GSL_REAL(ptr->value.c)); if(!disable_write) { fprintf(fout, "%s = %ld\n", name, ret); } if(fabs(GSL_IMAG(ptr->value.c)) > 1e-10) { fprintf(stderr, "Parser error: complex value passed for integer variable '%s'.\n", name); exit(1); } if(fabs(ret - GSL_REAL(ptr->value.c)) > 1e-10) { fprintf(stderr, "Parser error: non-integer value passed for integer variable '%s'.\n", name); exit(1); } }else{ ret = def; if(!disable_write) { fprintf(fout, "%s = %ld\t\t# default\n", name, ret); } } return ret; } double parse_double(const char *name, double def) { symrec *ptr; double ret; ptr = getsym(name); if(ptr){ check_is_numerical(name, ptr); ret = GSL_REAL(ptr->value.c); if(!disable_write) { fprintf(fout, "%s = %g\n", name, ret); } if(fabs(GSL_IMAG(ptr->value.c)) > 1e-10) { fprintf(stderr, "Parser error: complex value passed for real variable '%s'.\n", name); exit(1); } }else{ ret = def; if(!disable_write) { fprintf(fout, "%s = %g\t\t# default\n", name, ret); } } return ret; } gsl_complex parse_complex(const char *name, gsl_complex def) { symrec *ptr; gsl_complex ret; ptr = getsym(name); if(ptr){ check_is_numerical(name, ptr); ret = ptr->value.c; if(!disable_write) { fprintf(fout, "%s = (%g, %g)\n", name, GSL_REAL(ret), GSL_IMAG(ret)); } }else{ ret = def; if(!disable_write) { fprintf(fout, "%s = (%g, %g)\t\t# default\n", name, GSL_REAL(ret), GSL_IMAG(ret)); } } return ret; } char *parse_string(const char *name, char *def) { symrec *ptr; char *ret; ptr = getsym(name); if(ptr){ if( ptr->type != S_STR){ fprintf(stderr, "Parser error: expecting a string for variable '%s'.\n", name); exit(1); } ret = (char *)malloc(strlen(ptr->value.str) + 1); strcpy(ret, ptr->value.str); if(!disable_write) { fprintf(fout, "%s = \"%s\"\n", name, ret); } }else{ ret = (char *)malloc(strlen(def) + 1); strcpy(ret, def); if(!disable_write) { fprintf(fout, "%s = \"%s\"\t\t# default\n", name, ret); } } return ret; } int parse_block (const char *name, sym_block **blk) { symrec *ptr; ptr = getsym(name); if(ptr && ptr->type == S_BLOCK){ *blk = ptr->value.block; (*blk)->name = (char *)malloc(strlen(name) + 1); strcpy((*blk)->name, name); if(!disable_write) { fprintf(fout, "Opened block '%s'\n", name); } return 0; }else{ *blk = NULL; return -1; } } int parse_block_end (sym_block **blk) { if(!disable_write) { fprintf(fout, "Closed block '%s'\n", (*blk)->name); } free((*blk)->name); *blk = NULL; return 0; } int parse_block_n(const sym_block *blk) { assert(blk != NULL); return blk->n; } int parse_block_cols(const sym_block *blk, int l) { assert(blk!=NULL); if(l < 0 || l >= blk->n){ fprintf(stderr, "Parser error: row %i out of range [0,%i] when parsing block '%s'.\n", l, blk->n-1, blk->name); exit(1); } return blk->lines[l].n; } int parse_block_int(const sym_block *blk, int l, int col, int *r) { char *mtxel_name = get_mtxel_name(blk->name, l, col); *r = parse_int(mtxel_name, 0); free(mtxel_name); return 0; } int parse_block_int8(const sym_block *blk, int l, int col, int64_t *r) { char *mtxel_name = get_mtxel_name(blk->name, l, col); *r = parse_int(mtxel_name, 0); free(mtxel_name); return 0; } int parse_block_double(const sym_block *blk, int l, int col, double *r) { char *mtxel_name = get_mtxel_name(blk->name, l, col); *r = parse_double(mtxel_name, 0.0); free(mtxel_name); return 0; } int parse_block_complex(const sym_block *blk, int l, int col, gsl_complex *r) { char *mtxel_name = get_mtxel_name(blk->name, l, col); gsl_complex zero; GSL_SET_COMPLEX(&zero, 0.0, 0.0); *r = parse_complex(mtxel_name, zero); free(mtxel_name); return 0; } int parse_block_string(const sym_block *blk, int l, int col, char **r) { char *mtxel_name = get_mtxel_name(blk->name, l, col); *r = parse_string(mtxel_name, ""); free(mtxel_name); return 0; } void parse_result_free(parse_result *t) { if(t->type == PR_STR) free(t->value.s); t->type = PR_NONE; } void parse_putsym_int(const char *s, int i) { symrec *rec = putsym(s, S_CMPLX); GSL_SET_COMPLEX(&rec->value.c, (double)i, 0); rec->def = 1; rec->used = 1; } void parse_putsym_double(const char *s, double d) { symrec *rec = putsym(s, S_CMPLX); GSL_SET_COMPLEX(&rec->value.c, d, 0); rec->def = 1; rec->used = 1; } void parse_putsym_complex(const char *s, gsl_complex c) { symrec *rec = putsym(s, S_CMPLX); rec->value.c = c; rec->def = 1; rec->used = 1; }
0
ALLM/M3/octopus
ALLM/M3/octopus/liboct_parser/parse_exp.c
/* Copyright (C) 2002 M. Marques, A. Castro, A. Rubio, G. Bertsch 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, 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <stdio.h> #include <string.h> #include <strings.h> #include <stdlib.h> #include <ctype.h> #include <gsl/gsl_complex.h> #include <gsl/gsl_complex_math.h> #include "liboct_parser.h" #include "symbols.h" static char *par_string; static int par_pos; parse_result par_res; static int oct_parser_lex(void); static int oct_parser_error (char *s) /* Called by oct_parser_parse on error */ { /* Do nothing */ /* printf("%s\n", s); */ return 0; } /* include the parser */ #include "grammar.c" int parse_exp(char *exp, parse_result *r) { int o; par_string = exp; par_pos = 0; o = oct_parser_parse(); if(o == 0){ r->type = par_res.type; if(r->type == PR_CMPLX) r->value.c = par_res.value.c; else r->value.s = par_res.value.s; } return o; } int get_real(char *s, double *d) { int n=0; sscanf(s, "%lg", d); while(*s && (isdigit(*s) || *s=='.' || *s=='e' || *s=='E')){ if((*s=='e' || *s=='E') && (*(s+1)=='+' || *(s+1)=='-')) {s++; n++;} s++; n++; } return n; } static int oct_parser_lex (){ int c; char *symbuf = 0, *symbuf2 = 0; int length = 0; /* Ignore whitespace, get first nonwhite character. */ while ((c = par_string[par_pos++]) == ' ' || c == '\t'); if (c == '\0') return '\n'; /* Char starts a number => parse the number. */ if (c == '.' || isdigit (c)){ par_pos--; par_pos += get_real(&par_string[par_pos], &GSL_REAL(yylval.val)); return NUM; } /* get the logical operators */ if (c == '<' && par_string[par_pos] == '='){ par_pos++; return LE; } if (c == '>' && par_string[par_pos] == '='){ par_pos++; return GE; } if (c == '=' && par_string[par_pos] == '='){ par_pos++; return EQUAL; } /* if (c == ':' && par_string[par_pos] == '='){ par_pos++; return SET; } */ if (c == '&' && par_string[par_pos] == '&'){ par_pos++; return LAND; } if (c == '|' && par_string[par_pos] == '|'){ par_pos++; return LOR; } /* Char starts an identifier => read the name. */ if (isalpha (c) || c == '\'' || c == '\"'){ symrec *s; char startc = (char)c; int i; /* Initially make the buffer long enough for a 40-character symbol name. */ if (length == 0) length = 40, symbuf = (char *)malloc (length + 1); if(startc == '\'' || startc == '\"') c = par_string[par_pos++]; else startc = 0; /* false */ i = 0; do{ /* If buffer is full, make it larger. */ if (i == length){ length *= 2; symbuf2 = (char *)realloc (symbuf, length + 1); if (symbuf2 == NULL) { fprintf(stderr, "Parser error: failed to reallocate buffer to size %i.\n", length); exit(1); } else { symbuf = symbuf2; } } /* Add this character to the buffer. */ symbuf[i++] = (char)c; /* Get another character. */ c = par_string[par_pos++]; }while (c != '\0' && ((startc && c!=startc) || (!startc && (isalnum(c) || c == '.' || c == '_' || c == '[' || c == ']')))); if(!startc) par_pos--; symbuf[i] = '\0'; if(!startc){ s = getsym (symbuf); if (s == 0){ int jj; for (jj = 0; reserved_symbols[jj] != 0; jj++){ if(strcasecmp(symbuf, reserved_symbols[jj]) == 0){ fprintf(stderr, "Parser error: trying to redefine reserved symbol '%s'.\n", symbuf); exit(1); } } s = putsym (symbuf, S_CMPLX); } yylval.tptr = s; free(symbuf); if(s->type == S_CMPLX) return VAR; else return FNCT; }else{ yylval.str = strdup(symbuf); free(symbuf); return STR; } } /* Any other character is a token by itself. */ return c; }
0
ALLM/M3/octopus
ALLM/M3/octopus/liboct_parser/parser_f.c
/* Copyright (C) 2002 M. Marques, A. Castro, A. Rubio, G. Bertsch 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, 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <string.h> #include <math.h> #include <assert.h> #include <stdint.h> #include "liboct_parser.h" #include "symbols.h" #include "string_f.h" #ifndef FC_FUNC #error "Unknown Fortran name-mangling. Check configuration." #endif /* --------------------- Interface to the parsing routines ---------------------- */ /* --------------------------------------------------------- */ /* Initialization of the library */ /* --------------------------------------------------------- */ int FC_FUNC_(oct_parse_init, OCT_PARSE_INIT) (STR_F_TYPE s, int *dont_write STR_ARG1) { int r; char *s_c; TO_C_STR1(s, s_c); r = parse_init(s_c, dont_write); free(s_c); return r; } /* --------------------------------------------------------- */ void FC_FUNC_(oct_parse_putsym_int, OCT_PARSE_PUTSYM_INT) (STR_F_TYPE s, int *i STR_ARG1) { char *s_c; TO_C_STR1(s, s_c); parse_putsym_int(s_c, *i); free(s_c); } /* --------------------------------------------------------- */ void FC_FUNC_(oct_parse_putsym_double, OCT_PARSE_PUTSYM_DOUBLE) (STR_F_TYPE s, double *d STR_ARG1) { char *s_c; TO_C_STR1(s, s_c); parse_putsym_double(s_c, *d); free(s_c); } /* --------------------------------------------------------- */ void FC_FUNC_(oct_parse_putsym_complex, OCT_PARSE_PUTSYM_COMPLEX) (STR_F_TYPE s, gsl_complex *c STR_ARG1) { char *s_c; TO_C_STR1(s, s_c); parse_putsym_complex(s_c, *c); free(s_c); } /* --------------------------------------------------------- */ int FC_FUNC_(oct_parse_input, OCT_PARSE_INPUT) (STR_F_TYPE s, int *set_used STR_ARG1) { int r; char *s_c; TO_C_STR1(s, s_c); r = parse_input(s_c, *set_used); free(s_c); return r; } /* --------------------------------------------------------- */ int FC_FUNC_(oct_parse_input_string, OCT_PARSE_INPUT_STRING) (STR_F_TYPE s, int *set_used STR_ARG1) { int r; char *s_c; TO_C_STR1(s, s_c); r = parse_input_string(s_c, *set_used); free(s_c); return r; } /* --------------------------------------------------------- */ void FC_FUNC_(oct_parse_environment, OCT_PARSE_ENVIRONMENT) (STR_F_TYPE s STR_ARG1) { char *s_c; TO_C_STR1(s, s_c); parse_environment(s_c); free(s_c); } /* --------------------------------------------------------- */ void FC_FUNC_(oct_parse_end, OCT_PARSE_END) () { parse_end(); } /* --------------------------------------------------------- */ void FC_FUNC_(oct_sym_output_table, OCT_SYM_OUTPUT_TABLE) (int *only_unused, int *mpiv_node) { sym_output_table(*only_unused, *mpiv_node); } /* --------------------------------------------------------- */ /* Parser functions */ /* --------------------------------------------------------- */ int FC_FUNC_(oct_parse_isdef, OCT_PARSE_ISDEF) (STR_F_TYPE name STR_ARG1) { int r; char *name_c; TO_C_STR1(name, name_c); r = parse_isdef(name_c); free(name_c); return r; } /* --------------------------------------------------------- */ void FC_FUNC_(oct_parse_int, OCT_PARSE_INT) (STR_F_TYPE name, int64_t *def, int64_t *res STR_ARG1) { char *name_c; TO_C_STR1(name, name_c); *res = parse_int(name_c, *def); free(name_c); } /* --------------------------------------------------------- */ void FC_FUNC_(oct_parse_double, OCT_PARSE_DOUBLE) (STR_F_TYPE name, double *def, double *res STR_ARG1) { char *name_c; TO_C_STR1(name, name_c); *res = parse_double(name_c, *def); free(name_c); } /* --------------------------------------------------------- */ void FC_FUNC_(oct_parse_complex, OCT_PARSE_COMPLEX) (STR_F_TYPE name, gsl_complex *def, gsl_complex *res STR_ARG1) { char *name_c; TO_C_STR1(name, name_c); *res = parse_complex(name_c, *def); free(name_c); } /* --------------------------------------------------------- */ void FC_FUNC_(oct_parse_string, OCT_PARSE_STRING) (STR_F_TYPE name, STR_F_TYPE def, STR_F_TYPE res STR_ARG3) { char *c, *name_c, *def_c; TO_C_STR1(name, name_c); TO_C_STR2(def, def_c); c = parse_string(name_c, def_c); TO_F_STR3(c, res); /* convert string to Fortran */ free(name_c); free(def_c); /* this has to be *after* the to_f_str or we will have memory problems */ free(c); } /* --------------------------------------------------------- */ static void parse_block_error(const char *type, const char *name, int l, int c){ fprintf(stderr, "Parser error: block \"%s\" does not contain a %s in line %d and col %d.\n", name, type, l, c); exit(1); } /* --------------------------------------------------------- */ int FC_FUNC_(oct_parse_block, OCT_PARSE_BLOCK) (STR_F_TYPE name, sym_block **blk STR_ARG1) { int r; char *block_name; TO_C_STR1(name, block_name); r = parse_block(block_name, blk); free(block_name); return r; } /* --------------------------------------------------------- */ void FC_FUNC_(oct_parse_block_end, OCT_PARSE_BLOCK_END) (sym_block **blk) { parse_block_end(blk); } /* --------------------------------------------------------- */ int FC_FUNC_(oct_parse_block_n, OCT_PARSE_BLOCK_N) (sym_block **blk) { return parse_block_n(*blk); } /* --------------------------------------------------------- */ int FC_FUNC_(oct_parse_block_cols, OCT_PARSE_BLOCK_COLS) (sym_block **blk, int *l) { return parse_block_cols(*blk, *l); } /* --------------------------------------------------------- */ void FC_FUNC_(oct_parse_block_int, OCT_PARSE_BLOCK_INT) (sym_block **blk, int *l, int *c, int *res) { if(parse_block_int(*blk, *l, *c, res) != 0) parse_block_error("int", (*blk)->name, *l, *c); } /* --------------------------------------------------------- */ void FC_FUNC_(oct_parse_block_int8, OCT_PARSE_BLOCK_INT8) (sym_block **blk, int *l, int *c, int64_t *res) { if(parse_block_int8(*blk, *l, *c, res) != 0) parse_block_error("int", (*blk)->name, *l, *c); } /* --------------------------------------------------------- */ void FC_FUNC_(oct_parse_block_double, OCT_PARSE_BLOCK_DOUBLE) (sym_block **blk, int *l, int *c, double *res) { if(parse_block_double(*blk, *l, *c, res) != 0) parse_block_error("double", (*blk)->name, *l, *c); } /* --------------------------------------------------------- */ void FC_FUNC_(oct_parse_block_complex, OCT_PARSE_BLOCK_COMPLEX) (sym_block **blk, int *l, int *c, gsl_complex *res) { if(parse_block_complex(*blk, *l, *c, res) != 0) parse_block_error("complex", (*blk)->name, *l, *c); } /* --------------------------------------------------------- */ void FC_FUNC_(oct_parse_block_string, OCT_PARSE_BLOCK_STRING) (sym_block **blk, int *l, int *c, STR_F_TYPE res STR_ARG1) { char *s; if(parse_block_string(*blk, *l, *c, &s) != 0) parse_block_error("string", (*blk)->name, *l, *c); else{ TO_F_STR1(s, res); free(s); } } /* --------------------------------------------------------- */ void FC_FUNC_(oct_parse_expression, OCT_PARSE_EXPRESSION) (double *re, double *im, const int *ndim, const double *x, const double *r, const double *t, STR_F_TYPE pot STR_ARG1) { symrec *rec; parse_result c; char *s_c; TO_C_STR1(pot, s_c); rec = putsym("x", S_CMPLX); GSL_SET_COMPLEX(&rec->value.c, x[0], 0); rec->def = 1; if(*ndim > 1){ rec = putsym("y", S_CMPLX); GSL_SET_COMPLEX(&rec->value.c, x[1], 0); rec->def = 1; } if(*ndim > 2){ rec = putsym("z", S_CMPLX); GSL_SET_COMPLEX(&rec->value.c, x[2], 0); rec->def = 1; } if(*ndim > 3){ rec = putsym("w", S_CMPLX); GSL_SET_COMPLEX(&rec->value.c, x[3], 0); rec->def = 1; } rec = putsym("r", S_CMPLX); GSL_SET_COMPLEX(&rec->value.c, *r, 0); rec->def = 1; rec = putsym("t", S_CMPLX); GSL_SET_COMPLEX(&rec->value.c, *t, 0); rec->def = 1; parse_exp(s_c, &c); /* clean up */ rmsym("x"); if(*ndim > 1) rmsym("y"); if(*ndim > 2) rmsym("z"); if(*ndim > 3) rmsym("w"); rmsym("r"); rmsym("t"); *re = GSL_REAL(c.value.c); *im = GSL_IMAG(c.value.c); free(s_c); } /* --------------------------------------------------------- */ void FC_FUNC_(oct_parse_expression1, OCT_PARSE_EXPRESSION1) (double *re, double *im, STR_F_TYPE variable, double *val, STR_F_TYPE string STR_ARG2) { symrec *rec; parse_result c; char *s_c, *var_c; TO_C_STR1(variable, var_c); TO_C_STR2(string, s_c); rec = putsym(var_c, S_CMPLX); GSL_SET_COMPLEX(&rec->value.c, *val, 0); rec->def = 1; parse_exp(s_c, &c); rmsym(var_c); *re = GSL_REAL(c.value.c); *im = GSL_IMAG(c.value.c); free(s_c); free(var_c); }
0
ALLM/M3/octopus
ALLM/M3/octopus/liboct_parser/string_f.h
/* Copyright (C) 2003 M. Marques, A. Castro, A. Rubio, G. Bertsch 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, 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* --------------------- Fortran-to-C-string compatibility ---------------------- */ #include <stdlib.h> #if defined(_CRAY) #include <fortran.h> #define to_c_str(f, c) { \ char *fc; int slen; \ fc = _fcdtocp(f); \ for(slen=_fcdlen(f)-1; slen>=0 && fc[slen]==' '; slen--); \ slen++; \ c = (char *)malloc(slen+4); \ strncpy(c, _fcdtocp(f), slen); \ c[slen] = '\0'; \ } #define to_f_str(c, f) { \ char *fc; int flen, clen, i; \ flen = _fcdlen(f); \ fc = _fcdtocp(f); \ clen = strlen(c); \ for(i=0; i<clen && i<flen; i++) \ fc[i] = c[i]; \ for(; i<flen; i++) \ fc[i] = ' '; \ } #define STR_F_TYPE _fcd #define TO_C_STR1(s, c) to_c_str(s, c) #define TO_C_STR2(s, c) to_c_str(s, c) #define TO_C_STR3(s, c) to_c_str(s, c) #define TO_F_STR1(c, f) to_f_str(c, f) #define TO_F_STR2(c, f) to_f_str(c, f) #define TO_F_STR3(c, f) to_f_str(c, f) #define STR_ARG1 #define STR_ARG2 #define STR_ARG3 #else #define to_c_str(f, c, l) { \ int ii, ll; \ ll = (int)l; \ for(ll--; ll>=0; ll--) \ if(f[ll] != ' ') break; \ ll++; \ c = (char *)malloc((ll+4)*sizeof(char)); \ for(ii=0; ii<ll; ii++) c[ii] = f[ii]; \ c[ii] = '\0'; \ } #define to_f_str(c, f, l) { \ int ii, ll; \ ll = (int)l; \ for(ii=0; ii<ll && c[ii]!='\0'; ii++) \ f[ii] = c[ii]; \ for(; ii<ll; ii++) \ f[ii] = ' '; \ } #define STR_F_TYPE char * #define TO_C_STR1(s, c) to_c_str(s, c, l1) #define TO_C_STR2(s, c) to_c_str(s, c, l2) #define TO_C_STR3(s, c) to_c_str(s, c, l3) #define TO_F_STR1(c, f) to_f_str(c, f, l1) #define TO_F_STR2(c, f) to_f_str(c, f, l2) #define TO_F_STR3(c, f) to_f_str(c, f, l3) #define STR_ARG1 , unsigned long l1 #define STR_ARG2 , unsigned long l1, unsigned long l2 #define STR_ARG3 , unsigned long l1, unsigned long l2, unsigned long l3 #endif
0
ALLM/M3/octopus
ALLM/M3/octopus/liboct_parser/symbols.c
/* Copyright (C) 2002 M. Marques, A. Castro, A. Rubio, G. Bertsch, D. Strubbe 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, 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <strings.h> #include <ctype.h> #include <math.h> #include <gsl/gsl_complex_math.h> #include "symbols.h" #include "gsl_userdef.h" /* The symbol table: a chain of `struct symrec'. */ symrec *sym_table = (symrec *)0; void str_tolower(char *in) { for(; *in; in++) *in = (char)tolower(*in); } void sym_mark_table_used () { symrec *ptr; for (ptr = sym_table; ptr != (symrec *) 0; ptr = (symrec *)ptr->next) { ptr->used = 1; } } symrec *putsym (const char *sym_name, symrec_type sym_type) { symrec *ptr; ptr = (symrec *)malloc(sizeof(symrec)); /* names are always lowercase */ ptr->name = strdup(sym_name); str_tolower(ptr->name); ptr->def = 0; ptr->used = 0; ptr->type = sym_type; GSL_SET_COMPLEX(&ptr->value.c, 0, 0); /* set value to 0 even if fctn. */ ptr->next = (struct symrec *)sym_table; sym_table = ptr; return ptr; } symrec *getsym (const char *sym_name) { symrec *ptr; for (ptr = sym_table; ptr != (symrec *) 0; ptr = (symrec *)ptr->next) if (strcasecmp(ptr->name,sym_name) == 0){ ptr->used = 1; return ptr; } return (symrec *) 0; } int rmsym (const char *sym_name) { symrec *ptr, *prev; for (prev = (symrec *) 0, ptr = sym_table; ptr != (symrec *) 0; prev = ptr, ptr = ptr->next) if (strcasecmp(ptr->name,sym_name) == 0){ if(prev == (symrec *) 0) sym_table = ptr->next; else prev->next = ptr->next; free(ptr->name); free(ptr); return 1; } return 0; } struct init_fntc{ char *fname; int nargs; gsl_complex (*fnctptr)(); }; void sym_notdef (symrec *sym) { fprintf(stderr, "Parser error: symbol '%s' used before being defined.\n", sym->name); exit(1); } void sym_redef (symrec *sym) { fprintf(stderr, "Parser warning: redefining symbol, previous value "); sym_print(stderr, sym); fprintf(stderr, "\n"); } void sym_wrong_arg (symrec *sym) { if(sym->type == S_BLOCK) { fprintf(stderr, "Parser error: block name '%s' used in variable context.\n", sym->name); } else if(sym->type == S_STR) { fprintf(stderr, "Parser error: string variable '%s' used in expression context.\n", sym->name); } else { fprintf(stderr, "Parser error: function '%s' requires %d argument(s).\n", sym->name, sym->nargs); } exit(1); } static struct init_fntc arith_fncts[] = { {"sqrt", 1, (gsl_complex (*)()) &gsl_complex_sqrt}, {"exp", 1, (gsl_complex (*)()) &gsl_complex_exp}, {"ln", 1, (gsl_complex (*)()) &gsl_complex_log}, {"log", 1, (gsl_complex (*)()) &gsl_complex_log}, {"log10", 1, (gsl_complex (*)()) &gsl_complex_log10}, {"logb", 2, (gsl_complex (*)()) &gsl_complex_log_b}, /* takes two arguments logb(z, b) = log_b(z) */ {"arg", 1, (gsl_complex (*)()) &gsl_complex_carg}, {"abs", 1, (gsl_complex (*)()) &gsl_complex_cabs}, {"abs2", 1, (gsl_complex (*)()) &gsl_complex_cabs2}, {"logabs", 1, (gsl_complex (*)()) &gsl_complex_clogabs}, {"conjg", 1, (gsl_complex (*)()) &gsl_complex_conjugate}, {"inv", 1, (gsl_complex (*)()) &gsl_complex_inverse}, {"sin", 1, (gsl_complex (*)()) &gsl_complex_sin}, {"cos", 1, (gsl_complex (*)()) &gsl_complex_cos}, {"tan", 1, (gsl_complex (*)()) &gsl_complex_tan}, {"sec", 1, (gsl_complex (*)()) &gsl_complex_sec}, {"csc", 1, (gsl_complex (*)()) &gsl_complex_csc}, {"cot", 1, (gsl_complex (*)()) &gsl_complex_cot}, {"asin", 1, (gsl_complex (*)()) &gsl_complex_arcsin}, {"acos", 1, (gsl_complex (*)()) &gsl_complex_arccos}, {"atan", 1, (gsl_complex (*)()) &gsl_complex_arctan}, {"atan2", 2, (gsl_complex (*)()) &gsl_complex_arctan2}, /* takes two arguments atan2(y,x) = atan(y/x) */ {"asec", 1, (gsl_complex (*)()) &gsl_complex_arcsec}, {"acsc", 1, (gsl_complex (*)()) &gsl_complex_arccsc}, {"acot", 1, (gsl_complex (*)()) &gsl_complex_arccot}, {"sinh", 1, (gsl_complex (*)()) &gsl_complex_sinh}, {"cosh", 1, (gsl_complex (*)()) &gsl_complex_cosh}, {"tanh", 1, (gsl_complex (*)()) &gsl_complex_tanh}, {"sech", 1, (gsl_complex (*)()) &gsl_complex_sech}, {"csch", 1, (gsl_complex (*)()) &gsl_complex_csch}, {"coth", 1, (gsl_complex (*)()) &gsl_complex_coth}, {"asinh", 1, (gsl_complex (*)()) &gsl_complex_arcsinh}, {"acosh", 1, (gsl_complex (*)()) &gsl_complex_arccosh}, {"atanh", 1, (gsl_complex (*)()) &gsl_complex_arctanh}, {"asech", 1, (gsl_complex (*)()) &gsl_complex_arcsech}, {"acsch", 1, (gsl_complex (*)()) &gsl_complex_arccsch}, {"acoth", 1, (gsl_complex (*)()) &gsl_complex_arccoth}, /* user-defined step function. this is not available in GSL, but we use GSL namespacing and macros here. */ {"step", 1, (gsl_complex (*)()) &gsl_complex_step_real}, /* Minimum and maximum of two arguments (comparing real parts) */ {"min", 2, (gsl_complex (*)()) &gsl_complex_min_real}, {"max", 2, (gsl_complex (*)()) &gsl_complex_max_real}, {"erf", 1, (gsl_complex (*)()) &gsl_complex_erf}, {"realpart", 1, (gsl_complex (*)()) &gsl_complex_realpart}, {"imagpart", 1, (gsl_complex (*)()) &gsl_complex_imagpart}, {"round", 1, (gsl_complex (*)()) &gsl_complex_round}, {"floor", 1, (gsl_complex (*)()) &gsl_complex_floor}, {"ceiling", 1, (gsl_complex (*)()) &gsl_complex_ceiling}, {"rand", 0, (gsl_complex (*)()) &gsl_complex_rand}, {0, 0, 0} }; struct init_cnst{ char *fname; double re; double im; }; static struct init_cnst arith_cnts[] = { {"pi", M_PI, 0}, {"e", M_E, 0}, {"i", 0, 1}, {"true", 1, 0}, {"yes", 1, 0}, {"false", 0, 0}, {"no", 0, 0}, {0, 0, 0} }; char *reserved_symbols[] = { "x", "y", "z", "r", "w", "t", 0 }; void sym_init_table () /* puts arithmetic functions in table. */ { int i; symrec *ptr; for (i = 0; arith_fncts[i].fname != 0; i++){ ptr = putsym (arith_fncts[i].fname, S_FNCT); ptr->def = 1; ptr->used = 1; ptr->nargs = arith_fncts[i].nargs; ptr->value.fnctptr = arith_fncts[i].fnctptr; } /* now the constants */ for (i = 0; arith_cnts[i].fname != 0; i++){ ptr = putsym(arith_cnts[i].fname, S_CMPLX); ptr->def = 1; ptr->used = 1; GSL_SET_COMPLEX(&ptr->value.c, arith_cnts[i].re, arith_cnts[i].im); } } void sym_end_table() { symrec *ptr, *ptr2; for (ptr = sym_table; ptr != NULL;){ free(ptr->name); switch(ptr->type){ case S_STR: free(ptr->value.str); break; case S_BLOCK: if(ptr->value.block->n > 0){ free(ptr->value.block->lines); } free(ptr->value.block); break; case S_CMPLX: case S_FNCT: break; } ptr2 = ptr->next; free(ptr); ptr = ptr2; } sym_table = NULL; } /* this function is defined in src/basic/varinfo_low.c */ int varinfo_variable_exists(const char * var_name); void sym_output_table(int only_unused, int mpiv_node) { FILE *f; symrec *ptr; int any_unused = 0; if(mpiv_node != 0) { return; } if(only_unused) { f = stderr; } else { f = stdout; } for(ptr = sym_table; ptr != NULL; ptr = ptr->next){ if(only_unused && ptr->used == 1) continue; if(only_unused && varinfo_variable_exists(ptr->name)) continue; if(any_unused == 0) { fprintf(f, "\nParser warning: possible mistakes in input file.\n"); fprintf(f, "List of variable assignments not used by parser:\n"); any_unused = 1; } sym_print(f, ptr); } if(any_unused == 1) { fprintf(f, "\n"); } } void sym_print(FILE *f, const symrec *ptr) { fprintf(f, "%s", ptr->name); switch(ptr->type){ case S_CMPLX: if(fabs(GSL_IMAG(ptr->value.c)) < 1.0e-14){ fprintf(f, " = %f\n", GSL_REAL(ptr->value.c)); } else { fprintf(f, " = (%f,%f)\n", GSL_REAL(ptr->value.c), GSL_IMAG(ptr->value.c)); } break; case S_STR: fprintf(f, " = \"%s\"\n", ptr->value.str); break; case S_BLOCK: fprintf(f, "%s\n", " <= BLOCK"); break; case S_FNCT: fprintf(f, "%s\n", " <= FUNCTION"); break; } }
0
ALLM/M3/octopus
ALLM/M3/octopus/liboct_parser/symbols.h
/* Copyright (C) 2002 M. Marques, A. Castro, A. Rubio, G. Bertsch 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, 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef _SYMBOLS_H #define _SYMBOLS_H #include <gsl/gsl_complex.h> #include "liboct_parser.h" typedef enum{ S_CMPLX, S_STR, S_BLOCK, S_FNCT } symrec_type; /* Data type for links in the chain of symbols. */ typedef struct symrec{ char *name; /* name of symbol */ symrec_type type; /* type of symbol: complex, string, block, or function */ int def; /* has this symbol been defined */ int used; /* this symbol has been used before */ int nargs; /* if type==S_FNCT contains the number of arguments of the function */ union { gsl_complex c; /* value of a S_CMPLX */ char *str; /* value of a S_STR */ sym_block *block; /* to store blocks */ gsl_complex (*fnctptr)(); /* value of a S_FNCT */ } value; struct symrec *next; /* link field */ } symrec; /* The symbol table: a chain of struct symrec. */ extern symrec *sym_table; extern char *reserved_symbols[]; symrec *putsym (const char *sym_name, symrec_type sym_type); symrec *getsym (const char *sym_name); int rmsym (const char *sym_name); void sym_notdef(symrec *sym); void sym_redef(symrec *sym); void sym_wrong_arg(symrec *sym); void sym_init_table(void); void sym_end_table(void); void sym_output_table(int only_unused, int mpiv_node); void str_tolower(char *in); void sym_mark_table_used(); void sym_print(FILE *f, const symrec *ptr); #endif
0
ALLM/M3/octopus
ALLM/M3/octopus/scripts/autotools_check_config_h.py
#!/usr/bin/python3 import re import sys assert len(sys.argv) == 3, 'usage: ./autotools_check_config_h.py "path/to/config.h" "path/to/config.log"' SPECIAL_LIBRARIES = [ 'GSL', # does not appear in config.h ] missing_library = False _, config_h_path, config_log_path = sys.argv with open(config_h_path) as f: config_h = f.read() with open(config_log_path) as f: for line in f: if not re.match(r"^\s+\$(.*?)configure", line): continue configure_flags = line break for lib_match in re.finditer(r'with-(?P<lib>.*?)=', configure_flags): lib_name = lib_match.group('lib').replace('-prefix', '').upper().replace('-', '_') if lib_name not in SPECIAL_LIBRARIES and f"#define HAVE_{lib_name}" not in config_h: missing_library = True print(f"Could not find '{lib_name}' in config.h") for option_request in re.finditer(r'--enable-(?P<lib>[^ ]+)', configure_flags): option_name = option_request.group('lib').upper().replace('-', '_') if f"#define HAVE_{lib_name}" not in config_h: missing_library = True print(f"Could not find '{lib_name}' in config.h") sys.exit(missing_library)
0
ALLM/M3/octopus
ALLM/M3/octopus/scripts/buildbot_check.sh
#! /bin/bash # this script checks if buildbot master is marked as active in api # # requires: curl, jq color_red="\033[31;49;1m" color_green="\033[32;49;1m" color_reset="\033[0m" API_endpoint="https://octopus-code.org/buildbot/api/v2/masters" if ! [[ -x "$(command -v jq)" ]]; then printf "%bERROR: jq could not be found!%b\n" "${color_red}" "${color_reset}" exit 1 fi buildbot_master_info=$(curl -s -S "$API_endpoint") buildbot_master_active=$(echo "$buildbot_master_info" | jq '.masters[].active') if [[ "$buildbot_master_active" == "false" ]]; then printf "%bERROR: Buildbot master is not active!%b\nPlease restart this job after the octopus buildbot is activated.\n" "${color_red}" "${color_reset}" echo "Server response: $buildbot_master_info" exit 1 elif [[ "$buildbot_master_active" == "true" ]]; then printf "%bPASS: Buildbot master is active%b\n" "${color_green}" "${color_reset}" else printf "%bERROR: Buildbot master status could not be verified!%b\n" "${color_red}" "${color_reset}" echo "buildbot_master_active: $buildbot_master_active" echo "Server response: $buildbot_master_info" exit 1 fi
0
ALLM/M3/octopus
ALLM/M3/octopus/scripts/count-lines.py
#!/usr/bin/python3 import os import stat import time import shutil import subprocess start_year = 2002 start_month = 1 mytime = time.localtime() current_month = mytime[1] current_year = mytime[0] lines_filename='lines.dat' OUT = open(lines_filename, 'w') tics = "" i = 0 year = start_year month = start_month while True: ghash = subprocess.check_output('git rev-list -n 1 --before="{0}-{1}-01 00:00" main'.format(year, '{0:02d}'.format(month)), shell=True).decode('utf-8').strip() subprocess.call('git checkout {0}'.format(ghash), shell=True) lf90 = 0; lc = 0; lcl = 0; lcc = 0 for subdir, dirs, files in os.walk("."): if 'external_libs' in subdir: continue for file in files: if file.endswith('.F90'): lf90 += sum(1 for line in open(os.path.join(subdir, file), errors='ignore')) if file.endswith('.c') or file.endswith('.h') and file != 'config.h': lc += sum(1 for line in open(os.path.join(subdir, file), errors='ignore')) if file.endswith('.cl'): lcl += sum(1 for line in open(os.path.join(subdir, file), errors='ignore')) if file.endswith('.cc'): lcc += sum(1 for line in open(os.path.join(subdir, file), errors='ignore')) OUT.write('{0:6d} {1:2d} {2:4d} {3:7d} {4:7d} {5:7d} {6:7d}\n'.format(i, month, year, lf90, lc, lcl, lcc)) if i == 0 or i%12 == 0: if i != 0: tics = tics + "," tics = "{0}'{1}' {2}".format(tics, str(year)[2:5], i) if year == current_year and month == current_month: break i += 1 month += 1 if month == 13: month = 1 year += 1 OUT.close() gp_filename='lines.gp' GP = open(gp_filename, 'w') GP.write('set key left\n') GP.write("set xlabel 'Time'\n") GP.write("set ylabel 'kilo Lines of code'\n") GP.write("set xtics({0})\n".format(tics)) GP.write("set term post eps color solid 22\n") GP.write("set out 'oct_lines.eps'\n") GP.write("pl '"+lines_filename+"' u 1:($4/1000) t 'F90 lines' w l lw 3, '' u 1:($5/1000) t 'C lines' w l lt 3 lw 3, '' u 1:($6/1000) t 'OpenCL lines' w l lt 5 lw 3, '' u 1:($7/1000) t 'C++ lines' w l lt 2 lw 3,'' u 1:(($4+$5+$6+$7)/1000) t 'Total lines' w l lt 4 lw 4\n") GP.close() subprocess.call(['gnuplot', gp_filename])
0
ALLM/M3/octopus
ALLM/M3/octopus/scripts/git_check.sh
#! /bin/bash # This script runs "git add" on all of the files in current git repository. # If any of these files are filtered by .gitignore, it will return an error. # # requires: git color_red="\033[31;49;1m" color_green="\033[32;49;1m" color_reset="\033[0m" errfile=$(mktemp) git_repo_err=0 pushd "$(git rev-parse --show-toplevel)" > /dev/null || exit 1 git config --local advice.addIgnoredFile false files_list=$(find . -not -path './.git/*' -type f) IFS=$'\n' # shellcheck disable=SC2068 for file in $files_list; do git add "$file" 2> "$errfile" done=$? if [ "$done" -ne 0 ]; then printf "Checking: %s \n%bERROR: " "$file" "${color_red}" cat "$errfile" printf "%b\n\n" "${color_reset}" git_repo_err=1 fi done if [ "$git_repo_err" -eq 0 ]; then printf "%bPASS: no file in current git repository is ignored by your .gitignore files.%b\n" "${color_green}" "${color_reset}" fi popd > /dev/null || exit exit "$git_repo_err"
0
ALLM/M3/octopus
ALLM/M3/octopus/scripts/git_commit_hash.sh
#!/usr/bin/env bash # cd `dirname "$0"`/.. if [ -x "$(which git)" ] && git log > /dev/null 2>&1 ; then git log --pretty=format:'%H' -n 1 | grep -v gpg fi
0
ALLM/M3/octopus
ALLM/M3/octopus/scripts/mk_functionals_list.pl
#!/usr/bin/env perl # # Copyright (C) 2002-2006 M. Marques, A. Castro, A. Rubio, G. Bertsch # # 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, 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., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301, USA. # use Getopt::Std; use File::Find; getopts "hs:I:"; if($opt_h) { print <<"EndOfUsage"; Usage: mk_functionals_list.pl [-s DIR] [-I DIR] [-h] -s The top-level source tree directory, . if omitted -I The libxc include directory, in which to find xc_funcs.h -h This help message EndOfUsage exit 0; } $top_srcdir = ($opt_s ? $opt_s : "."); $src = "$top_srcdir/src/hamiltonian"; $funct = "$opt_I/xc_funcs.h"; $xc_ver = "$opt_I/xc_version.h"; if(!-d $src) { print STDERR "Cannot find directory '$src'. Run from top-level directory or set -s option appropriately.\n"; exit(1); } if(!-f $funct) { print STDERR "Cannot find file '$funct'. Set -I option appropriately.\n"; exit(1); } open(IN, "<$xc_ver"); while($_ = <IN>){ if(/\#define XC\_VERSION \"(.*)\"/){ $version_string = $1; } } close(IN); print STDERR "Version found: ", $version_string, "\n"; open(OUT, ">$src/functionals_list.F90"); print OUT <<"EndOfHeader"; ! Note: this file is generated automatically by scripts/mk_functionals_list.pl ! !%Variable XCFunctional !%Type integer !%Section Hamiltonian::XC !%Description !% Defines the exchange and correlation functionals to be used, !% specified as a sum of an exchange functional and a !% correlation functional, or a single exchange-correlation functional !% (<i>e.g.</i> <tt>hyb_gga_xc_pbeh</tt>). For more information on the functionals, see !% <a href=https://www.tddft.org/programs/libxc/functionals/libxc-$version_string> !% Libxc documentation</a>. The list provided here is from libxc $version_string; if you have !% linked against a different libxc version, you may have a somewhat different set !% of available functionals. Note that kinetic-energy functionals are not supported. !% !% The default functional will be selected by Octopus to be consistent !% with the pseudopotentials you are using. If you are not using !% pseudopotentials, Octopus cannot determine the functional used to !% generate the pseudopotential, or the pseudopotential functionals !% are inconsistent, Octopus will use the following defaults: !% !% <br>1D: <tt>lda_x_1d_soft + lda_c_1d_csc</tt> !% <br>2D: <tt>lda_x_2d + lda_c_2d_amgb</tt> !% <br>3D: <tt>lda_x + lda_c_pz_mod</tt> EndOfHeader open(IN, "<$funct"); while($_ = <IN>){ if(/\#define\s+(\S+)\s+(\d+)\s*\/\*\s*(.*?)\s*\*\//){ $option = $1; $number = $2; $comment = $3; # do not include kinetic-energy functionals next if($option =~ /^XC_\S+_K_/); if($option =~ /^XC_\S+_C_/ || $option =~ /^XC_\S+_XC_/){ $number *= 1000; } $option =~ s/XC_(.*)$/\L$1\E/g; $comment =~ s/\'/\`/g; print OUT "!%Option $option $number\n!% $comment\n"; } } print OUT <<EOF; !%Option oep_x 901 !% OEP: Exact exchange (not from libxc). !%Option slater_x 902 !% Slater approximation to the exact exchange (not from libxc). !%Option fbe_x 903 !% Exchange functional based on the force balance equation (not from libxc). !%Option ks_inversion 904 !% Inversion of KS potential (not from libxc). !%Option rdmft_xc_m 905 !% RDMFT Mueller functional (not from libxc). !%Option xc_half_hartree 917 !% Half-Hartree exchange for two electrons (supports complex scaling) (not from libxc). !% Defined by <math>v_{xc}(r) = v_H(r) / 2</math>. !%Option hyb_gga_xc_mvorb_hse06 921000 !% Density-based mixing parameter of HSE06 (not from libxc). !%Option hyb_gga_xc_mvorb_pbeh 922000 !% Density-based mixing parameter of PBEH (not from libxc). !% At the moment this is not supported for libxc >= 4.0. !%Option vdw_c_vdwdf 918000 !% van der Waals density functional vdW-DF correlation from libvdwxc (not from libxc). Use with gga_x_pbe_r. !%Option vdw_c_vdwdf2 919000 !% van der Waals density functional vdW-DF2 correlation from libvdwxc (not from libxc). Use with gga_x_rpw86. !%Option vdw_c_vdwdfcx 920000 !% van der Waals density functional vdW-DF-cx correlation from libvdwxc (not from libxc). Use with gga_x_lv_rpw86. !%Option none 0 !% Exchange and correlation set to zero (not from libxc). !%End EOF close(IN); close(OUT);
0
ALLM/M3/octopus
ALLM/M3/octopus/scripts/mk_varinfo.pl
#!/usr/bin/env perl # # Copyright (C) 2002-2006 M. Marques, A. Castro, A. Rubio, G. Bertsch # # 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, 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., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301, USA. # use Getopt::Std; use File::Find; use File::Path qw(make_path); getopts "hs:b:"; if($opt_h) { print <<"EndOfUsage"; Usage: mk_varinfo.pl [-b DIR] [-s DIR] [-h] -b The top level build tree directory, . if omitted -s The top level source tree directory, . if omited -h This help message EndOfUsage exit 0; } $top_srcdir = ($opt_s ? $opt_s : "."); $top_builddir = ($opt_b ? $opt_b : "."); $src = "$top_srcdir/src"; $share = "$top_builddir/share"; $include = "$top_builddir/src/include"; if(!-d $src || !-d $top_builddir) { print stderr <<"EndOfErrorMsg"; The src or build directory could not be found. Please run this script from the octopus toplevel directory or set -s and -b options appropriately. EndOfErrorMsg exit 1; } # Make missing build directories if missing if(!-d $share) { make_path($share) } if(!-d $include) { make_path($include) } # get all files named *.F90 recursively @F90 = (); finddepth (sub{ push @F90, $File::Find::name if /\.F90$/ }, "$src"); # Abort with warning if no *.F90 files were found. if($#F90 < 0) { print stderr <<"EndOfWarning"; Warning: No *.F90 files found. Probably, the source directory was not set correctly. EndOfWarning exit 2; } open(OUT_text, ">$share/varinfo"); open(OUT_orig, ">$share/varinfo_orig"); %opt_value = (); %varopt = (); %default_value = (); foreach $F90file (@F90){ open(IN, "<$F90file"); while($_=<IN>){ if(/!%Variable\s+(\S+)/i){ $var = $1; $desc = ""; do { s/^\s*!%//; s/\s*$//; if(/^Default\s+(\S+)/){ put_default($1, $var); } if(/^Option\s+(\S+)\s+bit\((\S+)\)/){ if($2 > 52) { printf STDERR "ERROR: bit($2) is too large and will overflow the maximum integer.\n"; printf STDERR "File $F90file, Variable $var, Option $1.\n"; exit(1); } put_opt($1, (1<<($2)), $var); } elsif(/^Option\s+(\S+)\s+(\S+)/){ put_opt($1, $2, $var); } if(/^ </){ # lines that start with a html command print_desc($desc) if($desc ne ""); $desc = $_."\n"; }elsif(/^ /){ # get whole description $desc .= $_."\n"; }else{ if($desc ne "") { print_desc($desc); $desc = ""; } printf OUT_text "%s\n", $_; printf OUT_orig "%s\n", $_; } $_ = <IN>; } until (eof(IN) || !/!%/ || /!%End/i); if($desc ne "") { print_desc($desc); } if(!/!%End/i){ print stderr "In info block of variable $var (file src/$F90file), block is incomplete\n"; exit 2; }else{ printf OUT_text "END\n\n"; printf OUT_orig "END\n\n"; } } } close(IN); } close(OUT_text); close(OUT_orig); print_opt(); print_options_header(); print_defaults_header(); ##################################################### # tries to put an option in global %opt_value sub put_opt{ my ($a, $b, $var) = @_; if($opt_value{$a} && ($opt_value{$a} ne $b)){ print stderr "Option '", $a, "' is defined multiple times\n", " '", $opt_value{$b}, "' ne '", $b, "'\n"; exit 3; } $opt_value{$a} = $b; $varopt{$var."__".$a} = $b; } ##################################################### # tries to put an option in global %opt_value sub put_default{ my ($a, $var) = @_; $default_value{$var} = $a; } ##################################################### # prints %opt_value to share/variables sub print_opt{ open(OUT, ">$share/variables"); my $key; foreach $key (sort(keys %opt_value)) { print OUT $key, " = ", $opt_value{"$key"}, "\n"; } close(OUT); } ##################################################### # prints %default_value to src/include/defaults.h sub print_defaults_header{ open(OUT, ">$include/defaults.h"); my $key; foreach $key (sort(keys %default_value)) { print OUT "#define DEFAULT__", uc $key, " (", $default_value{"$key"}, "_8)\n"; } close(OUT); } ##################################################### # prints %opt_value to src/include/options.h sub print_options_header{ open(OUT, ">$include/options.h"); my $key; foreach $key (sort(keys %varopt)) { print OUT "#define OPTION__", uc $key, " (", $varopt{"$key"}, "_int64)\n"; } close(OUT); } ##################################################### # justifies a string sub print_desc(){ my ($desc) = @_; my $ml = 75; my $i, $line; print OUT_orig $desc; $desc =~ s/\n/ /gm; $desc =~ s/^\s*//; $desc =~ s/\s\s+/ /g; # convert html to text $desc =~ s#<br/*>##g; $desc =~ s#<hr/*>#------------------------------------------\n#g; $desc =~ s#&nbsp;# #g; $desc =~ s#</*i>#_#g; $desc =~ s#</*b>#*#g; $desc =~ s#</*math>##g; $desc =~ s#</*tt>##g; $desc =~ s#</*ul>##g; $desc =~ s#<li># *) #g; $desc =~ s#</li>##g; while(){ if(length($desc) <= $ml){ print OUT_text " ", $desc, "\n"; last; } for($i=$ml; $i>0 && substr($desc, $i, 1) ne ' '; $i--){}; if($i == 0){ for($i=0; $i<length($desc) && substr($desc, $i, 1) ne ' '; $i++){}; } $line = substr($desc, 0, $i); $desc = substr($desc, $i+1); $spaces = $ml - length($line); if($spaces > 0){ for($i=0; $i<$spaces; $i++){ $line =~ s/([^ ]) ([^ ])/$1 $2/; } } print OUT_text " ", $line, "\n"; } }
0
ALLM/M3/octopus
ALLM/M3/octopus/scripts/preprocess.pl
#!/usr/bin/env perl my $fin = $ARGV[0]; my $ndebug = $ARGV[1] eq "no"; my $nline_num = $ARGV[2] eq "no"; open(IN, "<$fin"); while($_ = <IN>) { # First, eliminate the push_sub and pop_sub if the code is compiled in non-debug mode. # We replace it by an empty line as not to mess up the line numbers. if($ndebug){ if (/push_sub/) { print "\n"; next; } if (/pop_sub/) { print "\n"; next; } } # Substitute "\newline" by a real new line. s/\\newline/\n/g; # Substitute "\cardinal" by "#". s/\\cardinal/#/g; if($nline_num){ next if /^#/; } print; } close(IN);
0
ALLM/M3/octopus
ALLM/M3/octopus/scripts/true_compiler.sh
#!/usr/bin/env bash # # If the argument is mpicc or mpif90, prints the true compiler that is # being called. For the moment it only works if the -show argument is # accepted by the wrapper (mpich, openmpi and derivatives do). # It also works for the Cray compiler wrappers cc and ftn. # MPI if echo $1 | grep mpi > /dev/null; then if $1 -show &> /dev/null; then printf "("`basename $($1 -show | cut -f 1 -d" ")`")" else printf "(unknown)" fi # Cray compiler wrappers elif [ x$1 == xcc -o x$1 == xftn -o x$1 == xCC ]; then if $1 -show &> /dev/null; then printf "("`$1 -show | grep DRIVERNAME | cut -f 2 -d"="`")" else printf "(unknown)" fi fi
0
ALLM/M3/octopus
ALLM/M3/octopus/scripts/var2html.pl
#!/usr/bin/env perl # # Copyright (C) 2002-2006 M. Marques, A. Castro, A. Rubio, G. Bertsch # # 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, 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., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301, USA. # use Getopt::Std; getopts "hb:"; if($opt_h) { print <<"EndOfUsage"; Usage: var2html.pl [-b DIR] [-h] -b The top level build tree directory, . if omitted -h This help message EndOfUsage exit 0; } $top_builddir = ($opt_b ? $opt_b : "."); $doc = "$top_builddir/doc"; $share = "$top_builddir/share"; if(!-d $doc) { print STDERR "The output directory $doc does not exist.\n"; exit(1); } if(!-f "$share/varinfo_orig") { print STDERR "The input file $share/varinfo_orig does not exist.\n"; print STDERR "The script mk_varinfo.pl must be run before this script.\n"; exit(1); } # configuration $out_dir = "$doc/html/vars"; read_varinfo(); # generates %vars sort_variables(); # generates @sorted # make html pages print_index(); print_alpha(); print_vars(); print_texi(); sub read_varinfo(){ my $thisvar, $thisfield, $l; my $key, $arg; # let us parse the varinfo file open(IN, "<$share/varinfo_orig"); $thisvar = ""; $thisfield = ""; while($l = <IN>){ # for MathJax inline math: http://docs.mathjax.org/en/latest/start.html $l =~ s/<math>/\\(/g; $l =~ s/<\/math>/\\)/g; if($thisvar && $thisfield && $l !~ /^\w/){ if($l =~ /^\s*$/){ $vars{$thisvar}{$thisfield} .= "<br><br>\n"; }else{ $vars{$thisvar}{$thisfield} .= $l if($thisfield); } next; }else{ $thisfield = ""; } $l =~ /^(\S+)\s*(.*)$/; $key = lc($1); $arg = $2; if($key eq "variable"){ $thisvar = $arg; $vars{$thisvar}{"variable"} = $thisvar; } next if(!$thisvar); if($key eq "section"){ $vars{$thisvar}{"section"} = $arg; }elsif($key eq "type"){ $vars{$thisvar}{"type"} = $arg; if($arg ne "float" && $arg ne "integer" && $arg ne "flag" && $arg ne "string" && $arg ne "logical" && $arg ne "block" && $arg ne "virtual") { print STDERR "ERROR: Variable '$thisvar' has unknown type '$arg'.\n"; exit(1); } }elsif($key eq "default"){ $vars{$thisvar}{"default"} = $arg; }elsif($key eq "description"){ $thisfield = "description"; $vars{$thisvar}{$thisfield} = "<br>"; }elsif($key eq "option"){ $arg =~ /^(\S*)\s*(.*?)\s*$/; $thisfield = "option_$2_$1"; }elsif($key eq "end"){ if($vars{$thisvar}{"section"} eq "") { print STDERR "ERROR: Variable '$thisvar' lacks Section field.\n"; exit(1); } if($vars{$thisvar}{"type"} eq "") { print "ERROR: Variable '$thisvar' lacks Type field.\n"; exit(1); } if($vars{$thisvar}{"description"} eq "") { print "ERROR: Variable '$thisvar' lacks Description field.\n"; exit(1); } $thisvar = ""; $thisfield = ""; } } close(IN); } sub sort_variables(){ my %groups, @groups_sorted, $i; # we first make the groups foreach $key (keys %vars){ $groups{$vars{$key}{"section"}} = 1; } @groups_sorted = sort keys %groups; for($i=0; $i<=$#groups_sorted; $i++){ my @new = (); foreach $key (keys %vars){ push @new, $key if($vars{$key}{"section"} eq $groups_sorted[$i]); } push @sorted, sort @new; } } sub print_index(){ my $i, $j, $k, $key, $sect, $new_sect, $level; my @old, @new; open(OUT_index, ">$out_dir/vars_index.html"); open(OUT_tree, ">$out_dir/sections.js"); print OUT_index "<ul>\n"; print OUT_tree " USETEXTLINKS = 1 STARTALLOPEN = 0 ICONPATH = 'icons/' aux0 = gFld(\"Variables\", \"varsRightFrame.html\") foldersTree = aux0 "; $sect = ""; $level = 0; for($i=0; $i<=$#sorted; $i++){ $key = $sorted[$i]; $new_sect = $vars{$key}{"section"}; if($sect ne $new_sect){ @old = split("::", $sect); @new = split("::", $new_sect); for($j=0; $old[$j] && $new[$j] && $old[$j] eq $new[$j]; $j++){}; for($k=$j; $old[$k]; $k++){ print OUT_index "</ul>\n"; } for($k=$j; $new[$k]; $k++){ $new_sect =~ /^([^:]*)/; $link = "$1.html#".$vars{$key}{"section"}; $link =~ s/\s/_/g; print OUT_index "<li>", $new[$k], "</li>\n<ul>\n"; print OUT_tree "aux", $k+1, " = insFld(aux$k, gFld(\"", $new[$k], "\", \"vars/$link\"))\n"; } $sect = $new_sect; $level = $k; } $sect =~ /^([^:]*)/; $link = "$1.html#".$vars{$key}{"variable"}; $link =~ s/\s/_/g; print OUT_index "<li><a href='$link'>", $vars{$key}{"variable"}, " </a></li>\n"; print OUT_tree "insDoc(aux$level, gLnk(\"R\", \"", $vars{$key}{"variable"}, "\", \"vars/$link\"))\n"; } #print last <\ul> @old = split("::", $sect); for($j=0; $old[$j]; $j++){ print OUT_index "</ul>\n"; } print OUT_index "</ul>\n"; # close files close(OUT_index); close(OUT_tree); } sub print_alpha(){ my $key, $letter; open(OUT_tree, ">$out_dir/alpha.js"); print OUT_index "<ul>\n"; print OUT_tree " USETEXTLINKS = 1 STARTALLOPEN = 0 ICONPATH = 'icons/' aux0 = gFld(\"Variables\", \"varsRightFrame.html\") foldersTree = aux0 "; $letter = ''; foreach $key (sort { lc($a) cmp lc($b) } keys %vars){ $key =~ /^(.)/; $new_letter = lc($1); if($new_letter ne $letter){ $letter = $new_letter; print OUT_tree "aux1 = insFld(aux0, gFld(\"", uc($letter), "\", \"javascript:parent.op()\"))\n"; } $vars{$key}{"section"} =~ /^([^:]*)/; my $link = "vars/$1.html#".$vars{$key}{"variable"}; $link =~ s/\s/_/g; print OUT_tree "insDoc(aux1, gLnk(\"R\", \"", $vars{$key}{"variable"}, "\", \"$link\"))\n"; } close(OUT_tree); } sub print_vars(){ my $i, $k, $sect, $new_sect; $sect = ""; $sect_full = ""; for($i=0; $i<=$#sorted; $i++){ $key = $sorted[$i]; $new_sect = $vars{$key}{"section"}; $new_sect =~ s/:.*$//; $new_sect =~ s/\s/_/g; if($sect ne $new_sect){ my $link; if($sect){ print OUT " </body> </html>"; close(OUT) } $sect = $new_sect; open(OUT, ">$out_dir/$sect.html"); print OUT " <html> <head> <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /> <script type=\"text/javascript\" src=\"https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS_HTML-full\"></script> <style> BODY {background-color: white; font-size: 10pt; font-family: verdana,helvetica;} A {text-decoration: none;color: blue} </style> </head> <body> "; } if($sect_full ne $vars{$key}{"section"}){ $sect_full = $vars{$key}{"section"}; print OUT "\n<a name='", $vars{$key}{"section"}, "'</a>\n"; print OUT "<H2>", $vars{$key}{"section"}, "</H2>\n"; } # print the information about the variable print OUT "\n <p><b><a name='$vars{$key}{variable}'></a>$vars{$key}{variable}</b> <br/><i>Section</i>: $vars{$key}{section} <br/><i>Type</i>: $vars{$key}{type}\n"; if($vars{$key}{default} ne "") { print OUT "<br/><i>Default</i>: $vars{$key}{default}\n"; } print OUT "<br/>$vars{$key}{description}\n"; my $first = 1; foreach $k (sort keys %{ $vars{$key} }) { if($k =~ /^option_(.*?)_(.*)/) { if($first){ print OUT "<br/><i>Options</i>:\n<ul>\n"; $first = 0; } print OUT "<li><b>$2</b>"; print OUT ": ", $vars{$key}{$k}, "</li>\n"; } } print OUT "</ul>\n" if(!$first); print OUT "</p><hr width='30%' align='left'/>\n"; } close(OUT); } sub print_texi(){ my $i, $k, $sect, $new_sect; open(OUT, ">$doc/variables.texi"); print OUT "\@node Input Variables,,, \@chapter Input Variables \@code{octopus} has quite a few options, that we will subdivide in different groups. After the name of the option, its type and default value (when applicable) are given in parenthesis. "; $sect = ""; $sect_full = ""; for($i=0; $i<=$#sorted; $i++){ $key = $sorted[$i]; $new_sect = $vars{$key}{"section"}; $new_sect =~ s/:.*$//; $new_sect =~ s/\s/_/g; if($sect_full ne $vars{$key}{"section"}){ my $i, @p; if($sect_full){ print OUT "\@end itemize\n"; } $sect_full = $vars{$key}{"section"}; @p = split("::", $sect_full); print OUT '@node ', to_texi($p[$#p]), ",,,\n"; print OUT '@'; for($i=0; $i<$#p; $i++){ print OUT "sub"; } print OUT "section ", to_texi($p[$#p]), "\n"; print OUT "\@c ----------------------------------\n\n"; print OUT "\@itemize\n"; } # print the information about the variable print OUT "\@item \@strong{", to_texi($vars{$key}{variable}), "}@*\n", "\@vindex \@code{", to_texi($vars{$key}{variable}), "}@*\n", "\@emph{Section}: ", to_texi($vars{$key}{section}), "@*\n", "\@emph{Type}: ", to_texi($vars{$key}{type}), "@*\n"; print OUT "\@emph{Default}: ", to_texi($vars{$key}{default}), "@*\n" if($vars{$key}{default}); print OUT to_texi($vars{$key}{description}), "\n\n"; my $first = 1; foreach $k (sort keys %{ $vars{$key} }) { if($k =~ /^option_(.*?)_(.*)/) { if($first){ print OUT "\@emph{Options}:\n\@itemize \@minus\n"; $first = 0; } print OUT "\@item \@strong{", to_texi($2), "}"; print OUT ": ", to_texi($vars{$key}{$k}); } } print OUT "\@end itemize\n" if(!$first); print OUT "\n\@c ----------------------------------\n"; } # close the last itemize print OUT "\@end itemize\n"; # close file close(OUT); } sub to_texi(){ my ($t) = @_; #$t =~ s#\{#\@\{#g; #$t =~ s#\}#\@\}#g; $t =~ s#<br/*><br/*>##gi; $t =~ s#<br/*>#@*#gi; $t =~ s#<hr/*>#------------------------------------------@*#gi; $t =~ s#&nbsp;#@ #gi; $t =~ s#<i>#\@emph\{#gi; $t =~ s#<b>#\@strong\{#gi; $t =~ s#</[bi]>#\}#gi; while($t =~ m#<MATH>(.*?)</MATH>#s){ $tex = $1; $tex =~ s#\n# #gs; $verbatim = $1; $verbatim =~ s#\{#\@\{#g; $verbatim =~ s#\}#\@\}#g; $verbatim =~ s#\n# #gs; $t =~ s#<MATH>(.*?)</MATH>#\@ifnottex\n\@verbatim\n$verbatim\n\@end verbatim\n\@end ifnottex\n\@tex\n\$\$\n$tex\n\$\$\n\@end tex\n#s; } $t =~ s#<math>(.*?)</math>#\@math\{$1\}#gs; $t =~ s#<tt>#\@t\{#gi; $t =~ s#</tt>#\}#gi; $t =~ s#<ul>#\@itemize\n#gi; $t =~ s#</ul>#\@end itemize\n#gi; $t =~ s#<li>#\@item\n#gi; $t =~ s#</li>##gi; $t =~ s#&gt;#>#gi; $t =~ s#&lt;#<#gi; return $t; }
0
ALLM/M3/octopus/scripts
ALLM/M3/octopus/scripts/build/build_octopus_corvo.sh
#!/bin/bash ./configure --enable-fcs-solvers=fmm,direct --enable-fcs-fmm-comm=armci \ --enable-fcs-fmm-unrolled --enable-fcs-fmm-max-mpol=40 \ CFLAGS=-O3 CXXFLAGS=-O3 FCFLAGS=-O3 --disable-doc CXX=mpic++ CC=mpicc \ FC=mpif90 --prefix=$HOME/Software/scafacos \ LDFLAGS=-L/opt/scalapack/1.8.0/lib -L/opt/blacs/1.1/lib \ -L/opt/gotoblas2/1.08/lib -L/opt/netcdf/4.0.1/lib -L/opt/lapack/3.2/lib \ -L/opt/etsf_io/1.0.2/lib --enable-fcs-int=int --enable-fcs-float=double \ --enable-fcs-integer=integer --enable-fcs-real=real*8 make make install
0
ALLM/M3/octopus/scripts
ALLM/M3/octopus/scripts/build/build_octopus_corvo_pfft_fmm.sh
#!/bin/bash module add gcc module add ifort module add gsl module add etsf_io module add lapack module add netcdf module add gotoblas2 module add mpibull2 module add blacs module add scalapack export CC=mpicc export FC="mpif90" # It is important that "/opt/intel/Compiler//11.1/038/bin/intel64/" not to be in the PATH export PATH=/opt/mpi/mpibull2-1.3.9-14.s/bin:/opt/netcdf/4.0.1/bin:/opt/etsf_io/1.0.2/bin:/opt/gsl//1.13/bin:/opt/intel/composer_xe_2011_sp1.10.319//bin/intel64/:/opt/gcc//4.4/bin:/opt/slurm/bin:/usr/kerberos/bin:/opt/cuda//bin:/usr/local/bin:/bin:/usr/bin export LIBFM_HOME="$HOME/Software/scafacos" export PFFT_HOME="$HOME/local/pfft-1.0.5-alpha" export FFTW3_HOME="$HOME/local/fftw-3.3.2" export LIBS_PFFT="-L$PFFT_HOME/lib -L$FFTW3_HOME/lib -lpfft -lfftw3_mpi -lfftw3" export CFLAGS=" -I$PFFT_HOME/include -I$FFTW3_HOME/include -I$LIBFM_HOME/include" export LDFLAGS=$LDFLAGS" -L$LIBFM_HOME/lib -L$PFFT_HOME/lib -L$FFTW3_HOME/lib -lpfft -lfftw3_mpi -lfftw3 -lm " export FCFLAGS=$CFLAGS export CPPFLAGS=" -I$LIBFM_HOME/include " export LD_LIBRARY_PATH=$LIBFM_HOME/lib:$LD_LIBRARY_PATH ../configure --enable-mpi --with-libxc-prefix=$HOME/Software/libxc_9882 \ --prefix=$HOME/Software/octopus \ --with-blacs=/opt/blacs/1.1/lib/libblacs.a --with-scalapack \ --with-libfm="-L$LIBFM_HOME/lib -lfcs4fortran -lfcs -lfcs_direct -lfcs_fmm -lfcs_near -lfcs_gridsort -lfcs_common" \ --disable-openmp
0
ALLM/M3/octopus/scripts
ALLM/M3/octopus/scripts/build/build_octopus_edison.sh
#!/bin/bash module load cray-fftw gsl cray-netcdf-hdf5parallel parpack ./configure --prefix=`pwd` --with-libxc-prefix=/usr/common/usg/libxc/3.0.0/intel/ivybridge --enable-mpi \ CC=cc CXX=CC FC=ftn FCFLAGS="-fast -no-ipo" CFLAGS="-fast -no-ipo" \ FCCPP="/lib/cpp -ffreestanding" --with-fftw-prefix=$FFTW_DIR/.. --with-arpack="$ARPACK" --with-parpack=no \ --with-berkeleygw-prefix=/usr/common/software/berkeleygw/2.0 make -j 6 install
0
ALLM/M3/octopus/scripts
ALLM/M3/octopus/scripts/build/build_octopus_jugene.sh
#!/bin/bash module load gsl; module load lapack; autoreconf -i; export FC_INTEGER_SIZE=4; export CC_FORTRAN_INT=int; export CC=mpixlc_r; export CFLAGS='-g -O3 -qarch=450d'; export FC=mpixlf90_r; export FCFLAGS='-g -O3 -qarch=450d -qxlf90=autodealloc -qessl -qsmp=omp'; export LIBS_BLAS="-lesslsmpbg -L/opt/ibmmath/essl/4.4/lib -lesslbg"; export LIBS_LAPACK="-L$LAPACK_LIB -llapack"; export LIBS_FFT="-L/bgsys/local/fftw3/lib/ -lfftw3 -lm"; ./configure --prefix=$outdir \ --host=powerpc32-unknown-linux-gnu \ --build=powerpc64-unknown-linux-gnu \ --disable-gdlib \ --with-gsl-prefix=$GSL_DIR \ --enable-mpi --enable-openmp;
0
ALLM/M3/octopus/scripts
ALLM/M3/octopus/scripts/build/build_octopus_juqueen.sh
#/bin/bash module load gsl module load lapack module load blacs module load scalapack export PFFT_HOME="$HOME/local/pfft-threads-1.0.5-alpha" export FFTW3_HOME="$HOME/local/fftw-threads-3.3.2" export LD_LIBRARY_PATH=$PFFT_HOME/lib:$FFTW3_HOME/lib:$LD_LIBRARY_PATH export FC_INTEGER_SIZE=8 export CC_FORTRAN_INT=int export CC=mpicc export CFLAGS="-g -Wl,-relax -O3 -I$PFFT_HOME/include -I$FFTW3_HOME/include" export FC=mpif90 export FCFLAGS=$CFLAGS" -qxlf90=autodealloc -qessl -qsmp=omp " export LIBS_BLAS="-lesslsmpbg -L/opt/ibmmath/essl/4.4/lib -lesslbg" export LIBS_LAPACK="-L$LAPACK_LIB -llapack" export LIBS_FFT="-L$FFTW3_HOME/lib/ -lfftw3_mpi -lfftw3 -lm" echo "GSL DIR = $GSL_HOME " echo "PFFT DIR = $PFFT_HOME " export LDFLAGS=$LDFLAGS" -R/opt/ibmcmp/lib/bg/bglib \ -L/bgsys/drivers/V1R4M2_200_2010-100508P/ppc/gnu-linux/powerpc-bgp-linux/lib \ -L/bgsys/drivers/V1R4M2_200_2010-100508P/ppc/gnu-linux/lib/gcc/powerpc-bgp-linux/4.1.2 \ -L/opt/ibmcmp/xlf/bg/11.1/bglib \ -L/opt/ibmcmp/xlmass/bg/4.4/bglib \ -L/opt/ibmcmp/xlsmp/bg/1.7/bglib \ -L/bgsys/drivers/V1R4M2_200_2010-100508P/ppc/runtime/SPI \ -L/bgsys/drivers/V1R4M2_200_2010-100508P/ppc/comm/sys/lib \ -L/bgsys/drivers/V1R4M2_200_2010-100508P/ppc/comm/default/lib \ -L/usr/local/zlib/v1.2.3/lib \ -L/bgsys/drivers/ppcfloor/runtime/SPI \ -L$PFFT_HOME/lib -L$FFTW3_HOME/lib \ -lpfft -lfftw3_mpi -lfftw3 -lm \ -ldl -lxl -lxlopt -lrt -lpthread" SVN_VERS=$(svn info .. | grep Revision | awk '{print $2}') echo $SVN_VERS ../configure --prefix=$HOME/software/octopus_omp \ --with-libxc-prefix=$HOME/software/libxc_new \ --with-fft-lib="$FFTW3_HOME/lib/libfftw3.a $FFTW3_HOME/lib/libfftw3_omp.a" \ --host=powerpc32-unknown-linux-gnu \ --build=powerpc64-unknown-linux-gnu \ --disable-gdlib \ --disable-f90-forall \ --with-blas="-L/opt/ibmmath/lib64 -lesslbg" \ --with-lapack="-L$LAPACK_LIB -llapack" \ --with-gsl-prefix=$GSL_HOME \ --enable-mpi --enable-openmp
0
ALLM/M3/octopus/scripts
ALLM/M3/octopus/scripts/build/build_octopus_lapalma.sh
#!/bin/bash export PATH=/gpfs/apps/MPICH2/mx/default/64/bin:$PATH export LD_LIBRARY_PATH=/gpfs/apps/MPICH2/mx/default/64/lib:/gpfs/apps/MPICH2/slurm/64/lib export LD_LIBRARY_PATH=/gpfs/apps/GCC/4.6.1/lib64/:$HOME/local/openblas/4.6.1/lib:$LD_LIBRARY_PATH export CC="/gpfs/apps/MPICH2/mx/default/64/bin/mpicc -cc=/gpfs/apps/GCC/4.6.1/bin/gcc" export FC="/gpfs/apps/MPICH2/mx/default/64/bin/mpif90 -fc=/gpfs/apps/GCC/4.6.1/bin/gfortran" export CFLAGS="-m64 -O2 -I $PWD/external_libs/isf/wrappers " export FCFLAGS=$CFLAGS ../configure \ --with-blas=$HOME/local/openblas/4.6.1/lib/libopenblas.so.0 \ --with-lapack=/gpfs/apps/LAPACK/lib64/liblapack.a \ --disable-gdlib \ --with-gsl-prefix=$HOME/local/gsl/gnu \ --with-fft-lib=$HOME/local/fftw/3.3.4/lib/libfftw3.a \ --with-libxc-prefix=$HOME/local/libxc/gnu/4.6.1/2.2 \ --prefix=/gpfs/projects/ehu31/software/octopus/gnu/4.6.1 \ --enable-mpi --disable-f90-forall
0
ALLM/M3/octopus/scripts
ALLM/M3/octopus/scripts/build/build_octopus_lawrencium.sh
#!/bin/bash module load icc/10.1.018 module load ifort/10.1.018 module load mkl/2011.1.107 module load openmpi/1.4.3-intel module load netcdf/4.0-intel module load fftw/3.1.2-intel module load autoconf/2.65 module load gsl/1.13-intel module load gdlib/2.0.35 module load libtool/2.2.6b ./configure --prefix=`pwd` CC=mpicc FC=mpif90 CFLAGS="-O3" FCFLAGS="-O3 -check bounds" --enable-mpi \ --with-blas="-L$MKLROOT/lib/intel64 -Wl,--start-group -lmkl_intel_lp64 -lmkl_sequential -lmkl_core -Wl,--end-group -lpthread" \ --with-fft-lib="-L/global/software/centos-5.x86_64/modules/fftw/3.1.2-intel/lib -lfftw3" --with-netcdf-prefix="$NETCDF" --with-netcdf-include="$NETCDF/include" --enable-newuoa \ --with-libxc-prefix=`pwd` --with-blacs="$MKL_DIR/lib/intel64/libmkl_blacs_openmpi_lp64.a" --with-scalapack="$MKL_DIR/lib/intel64/libmkl_scalapack_lp64.a"
0
ALLM/M3/octopus/scripts
ALLM/M3/octopus/scripts/build/build_octopus_lonestar.sh
#!/bin/bash module load gsl module load mkl module load netcdf module load fftw3 cd libxc ./configure --prefix=`pwd`/.. --enable-mpi CC=mpicc FC=mpif90 F77=mpif90 FCFLAGS=-O3 CFLAGS=-O3 make install cd .. export SLKPATH=/opt/apps/intel11_1/mvapich2_1_6/scalapack/1.8.0/lib ./configure --prefix=`pwd` --enable-mpi CC=mpicc FC=mpif90 \ --with-blas="-Wl,--start-group $TACC_MKL_LIB/libmkl_intel_lp64.a $TACC_MKL_LIB/libmkl_sequential.a $TACC_MKL_LIB/libmkl_core.a -Wl,--end-group -lpthread" \ --with-fft-lib="-L$TACC_FFTW3_LIB -lfftw3" --with-netcdf-prefix="$TACC_NETCDF_DIR" --disable-gdlib \ --with-etsf-io-prefix="$HOME/etsf_io-1.0.3" --enable-newuoa --with-libxc-prefix=`pwd` \ --with-blacs="$SLKPATH/libscalapack.a $SLKPATH/blacs_MPI-LINUX-0.a $SLKPATH/blacsF77init_MPI-LINUX-0.a $SLKPATH/blacs_MPI-LINUX-0.a" make install
0
ALLM/M3/octopus/scripts
ALLM/M3/octopus/scripts/build/build_octopus_macos_brew.sh
#!/bin/bash ## NOTE: THIS SCRIPT IS NOT TESTED AND IS NOT USED IN THE CI. THE USER WILL BE ASKED WHETHER TO PROCEED # Set language (which is a bit tricky for MacOS) export LANG="en_US" export LC_CTYPE="en_US.UTF-8" export LC_ALL="en_US.UTF-8" # Determine the number of available processors. It is better to use only physical cpus n_proc=$(sysctl -n hw.physicalcpu) # Determine Homebrew prefix (differs between ARM and Intel architectures) homebrew=$(brew --prefix) # Define the current working directory PWD=$(pwd) # Define $PATH variable. this will override what is present so that this installtion uses either Homebrew toolchains (preferred) or Apple Toolchain # the final path will be: PATH=/opt/homebrew/bin:/opt/homebrew/sbin:/usr/bin:/usr/sbin:/bin:/sbin:<the_rest_of_the_original_path> # Note that duplicates are not and issue in PATH, so a single path can appears more than once. export PATH="$homebrew/bin:$homebrew/sbin:/usr/bin:/usr/sbin:/bin/sbin:$PATH" echo $PATH print_usage() { printf 'Welcome to Octopus compile script for MacOS!\n' printf '\t%s\n' "--prefix: installation path (default: './installed/')" printf '\t%s\n' "--root-path: path to the root of octopus repository (default: 'parent_of_pwd' (not ".."))" printf '\t%s\n' "-l, --install-libs: install required libraries (gcc, openmpi, autotools, libxc, gsl, fftw, lapack, scalapack). Homebrew is required. Default: no" printf '\t%s\n' "-s, --skip-config: skip the autoreconf and the configure command. Default: no" printf '\t%s\n' "-d, --debug: Compile with debug flags. Default: no" printf '\t%s\n' "-h, --help: print help (this list!)" } # Parse command shell line to detect arguments _arg_prefix="$PWD/installed" # Installation path _arg_root_path="${PWD%/*}" # Root path, where the Octopus repository is _arg_install_libs='no' _arg_skip_config='no' _arg_debug='no' while [[ $# -gt 0 ]]; do _key="$1" case "$_key" in # Define installation path --prefix) if [[ $# -lt 2 || $2 == -* ]]; then die "Missing value for the optional argument '$_key'." 1 fi _arg_prefix="$2" shift # past argument ;; --prefix=*) _arg_prefix="${_key##--prefix=}" ;; # Define root path for Octopus --root-path) if [[ $# -lt 2 || $2 == -* ]]; then die "Missing value for the optional argument '$_key'." 1 fi _arg_root_path="$2" shift # past argument ;; --root-path=*) _arg_root_path="${_key##--root-path=}" ;; -l|--install-libs) _arg_install_libs="yes" ;; -s|--skip-config) _arg_skip_config="yes" ;; -d|--debug) _arg_debug="yes" ;; -h|--help) print_usage return 0 ;; *) print_usage die "Unkown argument" 1 ;; esac shift # past argument or value done # THIS SCRIPT IS NOT TESTED AND IS NOT USED IN THE CI. ASK THE USER WHETHER TO PROCEED printf "Welcome to Octopus compile script for MacOS!\n" printf "This script is experimental and not automatically tested in the CIs, thus the installation might fail.\n" printf "Even if the installation is successful, it is still likely that many tests in 'make check' will fail due to numerical fluctuations and lack of certain libraries (e.g. CGAL).\n" printf "While this is acceptable for development, we recommend cautiousness when running Octopus for production calculations.\n" printf "Do you want to proceed with the installation? (y/n): " possible_confirmation_values=("y" "Y" "n" "N") confirmation_is_valid='no' while [[ $confirmation_is_valid == 'no' ]]; do read confirm_proceed # First, check that the user input is valid (y, Y, n, N) if [[ " ${possible_confirmation_values[@]} " =~ " $confirm_proceed " ]]; then confirmation_is_valid='yes' # Convert to lower case test_lower=$(tr '[:upper:]' '[:lower:]' <<< "$confirm_proceed") if [[ "$confirm_proceed" == "y" ]]; then echo "Proceeding..." elif [[ "$confirm_proceed" == "n" ]]; then echo "Aborting..." exit 0 fi else printf "Invalid answer. Please answer 'y' to proceed or 'n' to abort: " fi done # Test that root path was set correctly if [ ! -f "$_arg_root_path/configure.ac" ]; then echo "Error: Could not find configure.ac in octopus repository path ($_arg_root_path). Please pass the right path to the compilation script using the \"--root-path\" flag" exit 1 fi if [[ "$_arg_install_libs" == "yes" ]]; then brew install gcc # Specify the Homebrew's gcc for compiling open-mpi and gsl, otherwise it will take the default from Apple DevTools, causing linking issues brew install --cc=gcc-13 open-mpi gsl brew install autoconf automake libtool libxc fftw netcdf-fortran lapack scalapack fi # Compiler flags (Optimization and debugging info) if [[ "$_arg_debug" == "yes" ]]; then export CFLAGS="-O2 -g -Wall" export FCFLAGS="$CFLAGS -fbacktrace -ffree-line-length-none -fno-var-tracking-assignments -fbounds-check -finit-derived -frounding-math -fstack-protector-all -fcheck=all,no-array-temps -finit-real=snan -ffpe-trap=invalid,zero,overflow -fprofile-arcs" else export CFLAGS="-O3" export FCFLAGS="$CFLAGS -DNDEBUG -ffree-line-length-none -frounding-math -fbounds-check -ffpe-trap=invalid,zero,overflow -fstack-protector-all -fno-var-tracking-assignments" fi export CXXFLAGS="$CFLAGS -std=c++17" ### Linker flags ### export LDFLAGS="-L$homebrew/lib -L$homebrew/lib/gcc/current" export CPPFLAGS="-I$homebrew/include" # Lapack/Scalapack export LDFLAGS="$LDFLAGS -L$homebrew/opt/lapack/lib -L$homebrew/opt/scalapack/lib" export CPPFLAGS="$CPPFLAGS -I$homebrew/opt/lapack/include" # Libxc export LDFLAGS="$LDFLAGS -L$homebrew/opt/libxc/lib" export CPPFLAGS="$CPPFLAGS -I$homebrew/opt/libxc/include" # NETCDF export LDFLAGS="$LDFLAGS -L$homebrew/opt/hdf5/lib" export CPPFLAGS="$CPPFLAGS -I$homebrew/opt/hdf5/include" export CC="$homebrew/bin/mpicc" export FC="$homebrew/bin/mpif90" export CXX="$homebrew/bin/mpicxx" export CPP="$homebrew/bin/cpp-13" export FORTRAN_CPP="${FC:-gfortran} -E -P -cpp" # Configure if [[ "$_arg_skip_config" == "no" ]]; then pushd "$_arg_root_path" && autoreconf -i && popd "$_arg_root_path"/configure --prefix="$_arg_prefix" \ --enable-mpi \ --enable-openmp \ --with-libxc-prefix="$homebrew" \ --with-gsl-prefix="$homebrew" \ --with-fftw-prefix="$homebrew" \ --without-cgal \ --with-netcdf-prefix="$homebrew/opt/netcdf-fortran" \ --with-boost="$homebrew/opt/boost/lib" \ --with-blas="$homebrew/opt/lapack/lib/libblas.dylib" \ --with-lapack="$homebrew/opt/lapack/lib/liblapack.dylib" \ --with-blacs="$homebrew/opt/scalapack/lib/libscalapack.dylib" \ --with-scalapack="$homebrew/opt/scalapack/lib/libscalapack.dylib" fi make -j $n_proc && make -j $n_proc install
0
ALLM/M3/octopus/scripts
ALLM/M3/octopus/scripts/build/build_octopus_macos_macports.sh
#!/bin/bash ## NOTE: THIS SCRIPT IS NOT TESTED AND IS NOT USED IN THE CI. THE USER WILL BE ASKED WHETHER TO PROCEED # Set language (which is a bit tricky for MacOS) export LANG="en_US" export LC_CTYPE="en_US.UTF-8" export LC_ALL="en_US.UTF-8" # Determine the number of available processors. It is better to use only physical cpus n_proc=$(sysctl -n hw.physicalcpu) # Determine MacPorts prefix mac_ports="/opt/local" # Define the current working directory PWD=$(pwd) # Define $PATH variable. this will override what is present so that this installtion uses either MacPorts toolchains (preferred) or Apple Toolchain # the final path will be: PATH=/opt/local/bin:/opt/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin:<the_rest_of_the_original_path> export PATH="$mac_ports/bin:$mac_ports/sbin:/usr/bin:/usr/sbin:/bin/sbin:$PATH" print_usage() { printf 'Welcome to Octopus compile script for MacOS!\n' printf '\t%s\n' "--prefix: installation path (default: './installed/')" printf '\t%s\n' "--root-path: path to the root of octopus repository (default: 'parent_of_pwd' (not ".."))" printf '\t%s\n' "-l, --install-libs: install required libraries (gcc, openmpi, autotools, libxc, gsl, fftw, lapack, scalapack). MacPorts is required. Default: no" printf '\t%s\n' "-s, --skip-config: skip the autoreconf and the configure command. Default: no" printf '\t%s\n' "-d, --debug: Compile with debug flags. Default: no" printf '\t%s\n' "-h, --help: print help (this list!)" } # Parse command shell line to detect arguments _arg_prefix="$PWD/installed" # Installation path _arg_root_path="${PWD%/*}" # Root path, where the Octopus repository is _arg_install_libs='no' _arg_skip_config='no' _arg_debug='no' while [[ $# -gt 0 ]]; do _key="$1" case "$_key" in # Define installation path --prefix) if [[ $# -lt 2 || $2 == -* ]]; then die "Missing value for the optional argument '$_key'." 1 fi _arg_prefix="$2" shift # past argument ;; --prefix=*) _arg_prefix="${_key##--prefix=}" ;; # Define root path for Octopus --root-path) if [[ $# -lt 2 || $2 == -* ]]; then die "Missing value for the optional argument '$_key'." 1 fi _arg_root_path="$2" shift # past argument ;; --root-path=*) _arg_root_path="${_key##--root-path=}" ;; -l|--install-libs) _arg_install_libs="yes" ;; -s|--skip-config) _arg_skip_config="yes" ;; -d|--debug) _arg_debug="yes" ;; -h|--help) print_usage return 0 ;; *) print_usage die "Unkown argument" 1 ;; esac shift # past argument or value done # THIS SCRIPT IS NOT TESTED AND IS NOT USED IN THE CI. ASK THE USER WHETHER TO PROCEED printf "Welcome to Octopus compile script for MacOS!\n" printf "This script is experimental and not automatically tested in the CIs, thus the installation might fail.\n" printf "Even if the installation is successful, it is still likely that many tests in 'make check' will fail due to numerical fluctuations and lack of certain libraries (e.g. CGAL).\n" printf "While this is acceptable for development, we recommend cautiousness when running Octopus for production calculations.\n" printf "Do you want to proceed with the installation? (y/n): " possible_confirmation_values=("y" "Y" "n" "N") confirmation_is_valid='no' while [[ $confirmation_is_valid == 'no' ]]; do read confirm_proceed # First, check that the user input is valid (y, Y, n, N) if [[ " ${possible_confirmation_values[@]} " =~ " $confirm_proceed " ]]; then confirmation_is_valid='yes' # Convert to lower case test_lower=$(tr '[:upper:]' '[:lower:]' <<< "$confirm_proceed") if [[ "$confirm_proceed" == "y" ]]; then echo "Proceeding..." elif [[ "$confirm_proceed" == "n" ]]; then echo "Aborting..." exit 0 fi else printf "Invalid answer. Please answer 'y' to proceed or 'n' to abort: " fi done # Test that root path was set correctly if [ ! -f "$_arg_root_path/configure.ac" ]; then echo "Error: Could not find configure.ac in octopus repository path ($_arg_root_path). Please pass the right path to the compilation script using the \"--root-path\" flag" exit 1 fi if [[ "$_arg_install_libs" == "yes" ]]; then # -N stands for non-interactive, meaning that dependencies will be automatically installed sudo port -N install gcc12 autoconf automake libtool sudo port -N install openmpi-gcc12 +fortran sudo port -N install libxc5 +fortran sudo port -N install gsl +gcc12 sudo port -N install fftw-3 +openmpi sudo port -N install cgal5 sudo port -N install netcdf-fortran +gcc12 sudo port -N install lapack +gcc12 sudo port -N install scalapack +openmpi fi # Compiler flags (Optimization and debugging info) if [[ "$_arg_debug" == "yes" ]]; then export CFLAGS="-O2 -g -Wall" export FCFLAGS="$CFLAGS -fbacktrace -ffree-line-length-none -fno-var-tracking-assignments -fbounds-check -finit-derived -frounding-math -fstack-protector-all -fcheck=all,no-array-temps -finit-real=snan -ffpe-trap=invalid,zero,overflow -fprofile-arcs" else export CFLAGS="-O3" export FCFLAGS="$CFLAGS -DNDEBUG -ffree-line-length-none -frounding-math -fbounds-check -ffpe-trap=invalid,zero,overflow -fstack-protector-all -fno-var-tracking-assignments" fi export CXXFLAGS="$CFLAGS -std=c++17" # General flags export LDFLAGS="-L$mac_ports/lib" export CPPFLAGS="-I$mac_ports/include" # Configure if [[ "$_arg_skip_config" == "no" ]]; then pushd "$_arg_root_path" && autoreconf -i && popd "$_arg_root_path"/configure --prefix="$_arg_prefix" \ CC="$mac_ports/bin/mpicc-openmpi-gcc12" \ FC="$mac_ports/bin/mpif90-openmpi-gcc12" \ CXX="$mac_ports/bin/mpicxx-openmpi-gcc12" \ --enable-mpi \ --enable-openmp \ --with-libxc-prefix="$mac_ports/libexec/libxc5" \ --with-gsl-prefix="$mac_ports" \ --with-fftw-prefix="$mac_ports" \ --with-cgal="$mac_ports/lib/cmake/CGAL" \ --with-netcdf-prefix="$mac_ports/lib/cmake/netCDF" \ --with-netcdf-include="$mac_ports/include" \ --with-blas="$mac_ports/lib/lapack/libblas.dylib" \ --with-lapack="$mac_ports/lib/lapack/liblapack.dylib" \ --with-blacs="$mac_ports/lib/libscalapack.dylib" \ --with-scalapack="$mac_ports/lib/libscalapack.dylib" fi make -j $n_proc && make -j $n_proc install
0
ALLM/M3/octopus/scripts
ALLM/M3/octopus/scripts/build/build_octopus_magerit.sh
#!/bin/bash module purge module load gcc/4.4 module load openmpi/1.6.3 export LIBSDIR='/sw/openmpi/' export SOFTWARE_DIR="$HOME/SOFTWARE/exec" export FC=mpif90 export CC=mpicc export CXX=mpicxx export STDFLAGS="-O3 -mcpu=power7 -mtune=power7" export FCFLAGS=$STDFLAGS export CFLAGS=$STDFLAGS export CXXLAGS=$STDFLAGS export C_TYPE="gnu64-4.4-essl" export branch=`awk '{print $2}' ../.git/HEAD` export branch=`basename $branch` INSTALLDIR="$SOFTWARE_DIR/octopus/git-$C_TYPE/$branch" #GSL 1.16 --compiled with gcc 4.4.6 export GSL_HOME="$LIBSDIR/GSL/1.16/" #LAPACK gcc 4.4 export LAPACK_HOME="$LIBSDIR/LAPACK/3.4.2-gnu64-4.4" #PARMETIS gcc 4.7.2 export PARMETIS_HOME="$LIBSDIR/METIS/PARMETIS-4.0.3/" #METIS gcc 4.7.2 export METIS_HOME="$LIBSDIR/METIS/METIS-5.1.0/" #FFTW3.3.4 gcc 4.4 export FFTW_HOME="$LIBSDIR/FFTW/3.3.4-gnu64-4.4" export LD_LIBRARY_PATH=$FFTW_HOME/lib:$LD_LIBRARY_PATH #SCALAPACK gcc 4.4.6 export SCALAPACK_HOME="$LIBSDIR/SCALAPACK/2.0.2-gnu64-4.4/" export LD_LIBRARY_PATH=$SCALAPACK_HOME/lib:$LD_LIBRARY_PATH #LIBXC export LIBXC_HOME="$SOFTWARE_DIR/libxc/3.0.0-$C_TYPE/" #LIBVDWXC export LIBVDWXC_HOME="$SOFTWARE_DIR/libvdwxc/0.2.0-$C_TYPE/" export CPPFLAGS="-I$LIBVDWXC_HOME/include -DHAVE_LIBVDWXC" #export LIBS=-lvdwxcfort export LDFLAGS="-L$LIBVDWXC_HOME/lib -lvdwxcfort -Wl,-rpath=$LIBVDWXC_HOME/lib" export LD_LIBRARY_PATH=$LIBVDWXC_HOME/lib:$LD_LIBRARY_PATH export LD_LIBRARY_PATH=/opt/ibmcmp/lib64/:/opt/ibmcmp/xlsmp/2.1/lib64/:/opt/ibmcmp/xlf/13.1/lib64/:$LD_LIBRARY_PATH export LIBS_BLAS=" -L$SCALAPACK_HOME/lib -L$LAPACK_HOME/lib -lscalapack -llapack -lessl -lblacssmp -L$FFTW_HOME/lib -lfftw3 -lfftw3_threads -lfftw3_mpi / opt/gnu/gcc/4.4.6/lib64/libgfortran.a -L/opt/ibmcmp/xlf/13.1/lib64/ -lxlf90_r -lxlfmath -lxl -L/opt/ibmcmp/xlsmp/2.1/lib64/ -lxlomp_ser -Wl,--rpath /opt/ibmcmp/xlf/13.1/lib64/ /opt/ibmcmp/xlf/13.1/lib64/libxl.a -R/opt/ibmcmp/lib64/" make distclean make clean ../configure --prefix=$INSTALLDIR \ --disable-gdlib --disable-gsltest \ --with-libxc-prefix=$LIBXC_HOME \ --with-fftw-prefix=$FFTW_HOME \ --with-gsl-prefix=$GSL_HOME \ --with-metis-prefix=$METIS_HOME\ --with-parmetis-prefix=$PARMETIS_HOME \ --enable-mpi \ --enable-openmp
0
ALLM/M3/octopus/scripts
ALLM/M3/octopus/scripts/build/build_octopus_marenostrum2.sh
#!/bin/bash export LD_LIBRARY_PATH=/usr/lib export CC=mpicc export FC=mpif90 export CFLAGS="-q64 -O3 -qtune=ppc970 -qarch=ppc970 -qcache=auto -qnostrict -qignerrno -qinlglue" export FCFLAGS=$CFLAGS" -qessl -qxlf90=autodealloc" export LIBS_BLAS="-L/usr/lib64 -lessl" ./configure \ --with-lapack=/gpfs/apps/LAPACK/lib64/liblapack.a \ --disable-gsltest \ --disable-gdlib \ --with-gsl-prefix=$outdirGSL \ --with-fft-lib=$outdirFFT/lib/libfftw3.a \ --prefix=$outdir --enable-mpi --disable-f90-forall
0
ALLM/M3/octopus/scripts
ALLM/M3/octopus/scripts/build/build_octopus_marenostrum3.sh
#!/bin/bash module load MKL module load GSL export PREFIX=$HOME/Software export FFTW3_HOME=$HOME/local/fftw-3.3.2 export PFFT_HOME=$HOME/local/pfft-1.0.5-alpha export MKL_LIBS=$MKL_HOME/lib/intel64 export MKLROOT=$MKL_HOME export MKL_LIBS="-L$MKLROOT/lib/intel64 -lmkl_scalapack_lp64 -lmkl_intel_lp64 -lmkl_intel_thread -lmkl_core -lmkl_blacs_intelmpi_lp64 -lpthread -lm" export CC=mpicc export CFLAGS="-xHost -O3 -m64 -ip -prec-div -static-intel -sox -I$ISF_HOME/include -openmp -I$MKLROOT/include" export FC=mpif90 export FCFLAGS="-xHost -O3 -m64 -ip -prec-div -static-intel -sox -I$FFTW3_HOME/include -openmp -I$ISF_HOME/include -I$MKLROOT/include" export LIBS_BLAS="${MKL_LIBS}" export LIBS_FFT="-Wl,--start-group -L$PFFT_HOME/lib -L$FFTW3_HOME/lib -lpfft -lfftw3 -lfftw3_mpi -Wl,--end-group" ../configure --prefix=$PREFIX/octopus/ \ --enable-openmp --with-libxc-prefix=$PREFIX/libxc \ --disable-gdlib --with-gsl-prefix=/apps/GSL/1.15 \ --enable-mpi --enable-newuoa \ --with-pfft-prefix=$PFFT_HOME
0
ALLM/M3/octopus/scripts
ALLM/M3/octopus/scripts/build/build_octopus_mpcdf.sh
#!/bin/bash # # Compilation script for octopus. If this script is not executed in a subdirectory (e.g. _build) of the root octopus directory, # you have to pass the path to octopus directory to the compilation script using the --root-path flag # See ./build_octopus.sh --help for complete list of available options. # # Usage examples: # # build octopus for CPU, using gnu compilers and openmpi, with octopus at "$PWD/.." and install it to "$PWD/installed" # > ./build_octopus_mpcdf.sh # # build octopus for CPU, using intel compilers and intel-mpi, install it to "/u/user/octopus/" # > ./build_octopus_mpcdf.sh --compiler=intel --mpi=impi --prefix=/u/user/octopus/ # # build octopus with no compiler optimization, enable compiler warnings, and runtime checks # > ./build_octopus_mpcdf.sh --debug # # build octopus for CPU without MPI (with OpenMP support only) # > ./build_octopus_mpcdf.sh --no-mpi # # build octopus for CPU + GPU, using gnu compilers and cuda-aware openmpi (if possible) # > ./build_octopus_mpcdf.sh --cuda # # build octopus for CPU + GPU, using gnu compilers and cuda-unaware(!) openmpi # > ./build_octopus_mpcdf.sh --cuda --no-cuda-aware-mpi # # rebuild without running the configuration script # > ./build_octopus_mpcdf.sh --no-config # # rebuild without compiling the dependencies (WARNING: DO NOT USE THIS AFTER CHANGING THE FUNCTION/SUBROUTINE INTERFACES) # > ./build_octopus_mpcdf.sh --no-dep # # # NOTE: You must load the required runtime modules in your job submission script before # executing the octopus for your calculations. The list of these modules is printed # at the end of compilation and also is saved in your installation path at # .build.doc/required_runtime_modules file. You can also generate this list by passing # '--show-modules-only' flag to this script without compiling the code. set -e # version of this script VERSION="1.5" # default value of cli arguments _arg_config="on" _arg_dep="on" _arg_cuda="off" _arg_cuda_aware_mpi="on" _arg_debug="off" _arg_compiler="gnu" _arg_mpi="openmpi" _arg_prefix="$PWD/installed" _arg_root_path="${PWD%/*}" _arg_show_modules_only="off" # default modules # Latest tests: ## by MFT on COBRA, RAVEN & ADA clusters @06.2023 using octopus: dcef5ab038f9a49885da729daf6017c1d548d255 # other clusters may have different version of these modules # update the versions if necessary! # ## for OpenMP only modules_gcc="gcc/11" modules_intel="intel/21.5.0" modules_libs_openmp="mkl/2022.0 gsl hdf5-serial netcdf-serial etsf_io libxc/5.1.5 libvdwxc cgal boost/1.74" ## for MPI modules_intel_impi="intel/21.5.0 impi/2021.5" modules_gcc_impi="gcc/11 impi/2021.5" modules_gcc_openmpi="gcc/11 openmpi/4" modules_libs_mpi="mkl/2022.0 gsl hdf5-serial netcdf-serial etsf_io libxc/5.1.5 libvdwxc-mpi cgal boost/1.74 metis-64 parmetis-64 elpa/mpi/openmp/2022.11.001 dftbplus_openmp/22.2" ## For GPU modules_cuda="cuda/11.4" modules_cuda_aware_mpi="openmpi_gpu/4" # configuration features to verify ## common features we expect to detect in all cases common_features_list=('CGAL' 'NETCDF' 'ETSF_IO' 'FFTW3' 'LIBXC_FXC' 'LIBXC_KXC' 'LIBVDWXC' 'OPENMP') ## expected features of mpi version mpi_features_list=('MPI' 'ELPA' 'PARMETIS' 'LIBVDWXC_MPI' 'DFTBPLUS') ## expected features of cuda version cuda_features_list=('CUDA') expected_features_list=( "${common_features_list[@]}" ) die() { _die_ret="${2:-1}" test "${_PRINT_HELP:-no}" = yes && print_help >&2 echo "$1" >&2 exit "${_die_ret}" } print_help() { printf '%s\n' "Compilation script for octopus. This script needs to be executed in a subdirectory (e.g. _build) of the root directory or the path to octopus root directory must be set using --root-path flag." print_usage } print_usage() { printf '\nUsage: %s [--(no-)config] [--(no-)dep] [--(no-)cuda] [--(no-)cuda-aware-mpi] [--(no-)debug] [--compiler <arg>] [--no-mpi] [--mpi <arg>] [--prefix <arg>] [--show-modules-only] [-v|--version] [-h|--help]\n' "$0" printf '\t%s\n' "--config, --no-config: run configure script (on by default)" printf '\t%s\n' "--dep, --no-dep: compile dependencies (on by default)" printf '\t%s\n' "--cuda, --no-cuda: compile with CUDA support (off by default)" printf '\t%s\n' "--cuda-aware-mpi, --no-cuda-aware-mpi: compile with CUDA aware MPI support (on by default)" printf '\t%s\n' "--debug, --no-debug: compile with debug flags [disable optimization, activate compiler warnings and runtime checks, link to debug impi] (off by default)" printf '\t%s\n' "--compiler: compiler type. available options: 'intel' or 'gnu' (default: 'gnu')" printf '\t%s\n' "--no-mpi: compile without the MPI support (equivalent to '--mpi=off')" printf '\t%s\n' "--mpi: MPI implementation. available options: 'impi', 'openmpi', or 'off' (default: 'openmpi')" printf '\t%s\n' "--prefix: installation path (default: './installed/')" printf '\t%s\n' "--root-path: path to the root of octopus repository (default: '../')" printf '\t%s\n' "--show-modules-only: print the required runtime modules and exit" printf '\t%s\n' "-v, --version: print compilation script version" printf '\t%s\n' "-h, --help: print help (this list!)" } parse_commandline() { while test $# -gt 0 do _key="$1" case "$_key" in --no-config|--config) test "${1:0:5}" = "--no-" && _arg_config="off" ;; --no-dep|--dep) test "${1:0:5}" = "--no-" && _arg_dep="off" ;; --no-cuda|--cuda) test "${1:0:5}" = "--no-" || _arg_cuda="on" ;; --no-cuda-aware-mpi|--cuda-aware-mpi) test "${1:0:5}" = "--no-" && _arg_cuda_aware_mpi="off" ;; --no-debug|--debug) test "${1:0:5}" = "--no-" || _arg_debug="on" ;; --compiler) test $# -lt 2 && die "Missing value for the optional argument '$_key'." 1 _arg_compiler="$2" shift ;; --compiler=*) _arg_compiler="${_key##--compiler=}" ;; --no-mpi) _arg_mpi="off" ;; --mpi) test $# -lt 2 && die "Missing value for the optional argument '$_key'." 1 _arg_mpi="$2" shift ;; --mpi=*) _arg_mpi="${_key##--mpi=}" ;; --prefix) test $# -lt 2 && die "Missing value for the optional argument '$_key'." 1 _arg_prefix="$2" shift ;; --prefix=*) _arg_prefix="${_key##--prefix=}" ;; --root-path) test $# -lt 2 && die "Missing value for the optional argument '$_key'." 1 _arg_root_path="$2" shift ;; --root-path=*) _arg_root_path="${_key##--root-path=}" ;; --show-modules-only) _arg_show_modules_only="on" ;; -v|--version) echo Octopus compilation script v$VERSION exit 0 ;; -h|--help) print_help exit 0 ;; -h*) print_help exit 0 ;; *) _PRINT_HELP=yes die "FATAL ERROR: Unexpected argument '$1'" 1 ;; esac shift done } # verify expected features are detected in config.h as "#define HAVE_*** 1" verify_configuration() { read -ra _expected_features <<< "$@" for feature in "${_expected_features[@]}"; do printf "checking feature: %s ..." "$feature" _definition="#define HAVE_$feature 1" grep -q "$_definition" config.h || ( echo "NOT FOUND!" && echo "ERROR: Configuration script failed to detect $feature" && exit 1 ) echo "OK!" done } parse_commandline "$@" # expand ~ in path arguments _arg_prefix="${_arg_prefix/#\~/$HOME}" _arg_root_path="${_arg_root_path/#\~/$HOME}" echo "=====================================" [ "$_arg_show_modules_only" = "off" ] && echo "run configure: $_arg_config" [ "$_arg_show_modules_only" = "off" ] && echo "build dependencies: $_arg_dep" echo "compiler: $_arg_compiler" echo "mpi: $_arg_mpi" echo "cuda support: $_arg_cuda" [ "$_arg_mpi" = "openmpi" ] && [ "$_arg_cuda" = "on" ] && echo "cuda-aware-mpi: $_arg_cuda_aware_mpi" [ "$_arg_show_modules_only" = "off" ] && echo "debug mode: $_arg_debug" [ "$_arg_show_modules_only" = "off" ] && echo "installation path: $_arg_prefix" [ "$_arg_show_modules_only" = "off" ] && echo "octopus repository path: $_arg_root_path" echo "=====================================" if [ ! -f "$_arg_root_path/configure.ac" ]; then echo "Error: Could not find configure.ac in octopus repository path ($_arg_root_path). Please pass the right path to the compilation script using the \"--root-path\" flag" exit 1 fi # validating script arguments if [ "$_arg_compiler" != "intel" ] && [ "$_arg_compiler" != "gnu" ]; then echo "Error: Invalid --compiler option: $_arg_compiler" print_usage exit 1 fi if [ "$_arg_mpi" != "impi" ] && [ "$_arg_mpi" != "openmpi" ] && [ "$_arg_mpi" != "off" ]; then echo "Error: Invalid --mpi option: $_arg_mpi" print_usage exit 1 fi if [ "$_arg_compiler" = "intel" ] && [ "$_arg_mpi" = "openmpi" ]; then echo "WARNING: Compiling Octopus with intel compilers and linking to OpenMPI library is not supported!" echo "Will use IntelMPI (impi) instead!" _arg_mpi="impi" fi module purge if [ "$_arg_compiler" = "intel" ]; then if [ "$_arg_mpi" = "off" ]; then # shellcheck disable=2086 module load $modules_intel required_modules+=" ${modules_intel}" export CC=icc export FC=ifort export CXX=icpc MKL_FLAGS="-lmkl_intel_lp64 -lmkl_intel_thread -lmkl_core -liomp5 -lpthread -lm -ldl" elif [ "$_arg_mpi" = "impi" ]; then # shellcheck disable=2086 module load $modules_intel_impi required_modules+=" ${modules_intel_impi}" if [ "$_arg_debug" = "on" ]; then export I_MPI_LINK=dbg else export I_MPI_LINK=opt fi export CC=mpiicc export FC=mpiifort export CXX=mpiicpc MKL_FLAGS="-lmkl_scalapack_lp64 -lmkl_intel_lp64 -lmkl_intel_thread -lmkl_core -lmkl_blacs_intelmpi_lp64 -liomp5 -lpthread -lm -ldl" elif [ "$_arg_mpi" = "openmpi" ]; then # we should never reach this part of script! Adapt the script if we support Intel compilers + OpenMPI in future. echo "ERROR: Compiling Octopus with intel compilers and linking to OpenMPI library is not currently supported!" exit 1 fi if [ "$_arg_debug" = "on" ]; then export CFLAGS="-O0 -g -traceback" FCFLAGS_EXTRA="-warn all -warn noexternals -warn nounused -check all" else export CFLAGS="-O3 -xCORE-AVX512 -qopt-zmm-usage=high -fma -g -traceback" fi export CXXFLAGS="$CFLAGS" export FCFLAGS="$CFLAGS $FCFLAGS_EXTRA" elif [ "$_arg_compiler" = "gnu" ]; then if [ "$_arg_mpi" = "off" ]; then module load $modules_gcc required_modules+=" ${modules_gcc}" export CC=gcc export FC=gfortran export CXX=g++ MKL_FLAGS="-lmkl_gf_lp64 -lmkl_gnu_thread -lmkl_core -lgomp -lpthread -lm -ldl" elif [ "$_arg_mpi" = "impi" ]; then # shellcheck disable=2086 module load $modules_gcc_impi required_modules+=" ${modules_gcc_impi}" export CC=mpigcc export FC=mpigfortran export CXX=mpig++ MKL_FLAGS="-lmkl_scalapack_lp64 -lmkl_gf_lp64 -lmkl_gnu_thread -lmkl_core -lmkl_blacs_intelmpi_lp64 -lgomp -lpthread -lm -ldl" elif [ "$_arg_mpi" = "openmpi" ]; then # shellcheck disable=2086 module load $modules_gcc_openmpi required_modules+=" ${modules_gcc_openmpi}" export CC=mpicc export FC=mpif90 export CXX=mpicxx MKL_FLAGS="-lmkl_scalapack_lp64 -lmkl_gf_lp64 -lmkl_gnu_thread -lmkl_core -lmkl_blacs_openmpi_lp64 -lgomp -lpthread -lm -ldl" fi if [ $_arg_debug = on ]; then export CFLAGS="-O0 -g" FCFLAGS_EXTRA="-fallow-argument-mismatch -fallow-invalid-boz -fcheck=all -Wall -Wno-c-binding-type -Wno-maybe-uninitialized -Wno-unused-dummy-argument" else export CFLAGS="-O3 -march=native -g" FCFLAGS_EXTRA="-fallow-argument-mismatch -fallow-invalid-boz" fi export CXXFLAGS="$CFLAGS" export FCFLAGS="$CFLAGS $FCFLAGS_EXTRA" fi if [ "$_arg_mpi" = "off" ]; then # shellcheck disable=2086 module load $modules_libs_openmp export MKL="-L${MKLROOT}/lib/intel64 ${MKL_FLAGS}" ENABLE_MPI= SCALAPACK=no PARMETIS_HOME=no METIS_HOME=no ELPA_HOME=no DFTBPLUS_HOME=no else # shellcheck disable=2086 module load $modules_libs_mpi export MKL="-L${MKLROOT}/lib/intel64 ${MKL_FLAGS}" expected_features_list+=( "${mpi_features_list[@]}" ) ENABLE_MPI=--enable-mpi SCALAPACK=$MKL fi if [ "$_arg_compiler" = "intel" ]; then # gcc 10 or later is needed for newer C++ libraries. This needs to be loaded after $modules_libs_... module load gcc/11 fi if [ "$_arg_cuda" = "on" ]; then module load $modules_cuda required_modules+=" ${modules_cuda}" expected_features_list+=( "${cuda_features_list[@]}" ) if [ "$_arg_mpi" = "openmpi" ] && [ "$_arg_cuda_aware_mpi" = "on" ] ; then # on COBRA the underlying network drivers do not support CUDA-aware MPI module -s load $modules_cuda_aware_mpi && required_modules+=" ${modules_cuda_aware_mpi}"\ || echo "WARNING: CUDA-aware MPI module does not seem to be available in the current environment. Proceeding without the CUDA-aware MPI support!" fi CUDA_FLAGS="--enable-cuda --enable-nvtx --with-cuda-prefix=$CUDA_HOME" LDFLAGS="$LDFLAGS:$CUDA_HOME/lib64" else CUDA_FLAGS="" fi if [ "$_arg_show_modules_only" = "on" ]; then echo -e "\nRequired runtime modules for the selected configuration would be: ${required_modules}\n" exit 0 fi module list export CXXFLAGS="$CXXFLAGS -std=c++14" export LDFLAGS="-Xlinker -rpath=$MKL_HOME/lib/intel64:$GSL_HOME/lib:$NETCDF_HOME/lib:$ELPA_HOME/lib:$METIS_HOME/lib:$PARMETIS_HOME/lib:$LIBXC_HOME/lib:$DFTBPLUS_HOME/lib" if [ "$_arg_config" != "off" ]; then pushd "$_arg_root_path" autoreconf -i popd # shellcheck disable=2086 "$_arg_root_path"/configure $CUDA_FLAGS \ FCFLAGS_FFTW="-I$MKLROOT/include/fftw" \ --prefix="$_arg_prefix" \ $ENABLE_MPI \ --enable-openmp \ --disable-gdlib \ --enable-shared --disable-static \ --with-gsl-prefix="$GSL_HOME" \ --with-cgal="$CGAL_HOME" \ --with-libxc-prefix="$LIBXC_HOME" \ --with-libvdwxc-prefix="$LIBVDWXC_HOME" \ --with-blas="$MKL" \ --with-lapack="$MKL" \ --with-blacs="$SCALAPACK" \ --with-scalapack="$SCALAPACK" \ --with-netcdf-prefix="$NETCDF_HOME" \ --with-etsf-io-prefix="$ETSF_IO_HOME" \ --with-metis-prefix="$METIS_HOME" \ --with-parmetis-prefix="$PARMETIS_HOME" \ --with-boost="$BOOST_HOME" \ --with-elpa-prefix="$ELPA_HOME" \ --with-dftbplus-prefix="$DFTBPLUS_HOME" verify_configuration "${expected_features_list[@]}" fi if [ "$_arg_dep" = "off" ]; then NODEP=1 else NODEP=0 fi make NODEP=$NODEP -j20 make NODEP=$NODEP -j20 install # keep the compilation script, its cli arguments, config.log, and the list of required runtime modules # at .build.doc/ in installation path for future reference mkdir -p "$_arg_prefix"/.build.doc/ cp -f config.log "$_arg_prefix"/.build.doc/ cp -f "$0" "$_arg_prefix"/.build.doc/ echo "$0 $*" > "$_arg_prefix"/.build.doc/compilation_command echo "$required_modules" > "$_arg_prefix"/.build.doc/required_runtime_modules echo "=====================================" echo "Compilation done!" echo "A copy of this compilation script, its CLI arguments, config.log, and the list of required runtime modules are all stored in $_arg_prefix/.build.doc/ for future reference" echo -e "\nRequired runtime modules: ${required_modules}\n"
0
ALLM/M3/octopus/scripts
ALLM/M3/octopus/scripts/build/build_octopus_mpcdf_cmake.sh
#!/bin/bash set -e _arg_config="on" _arg_compiler="intel" _arg_mpi="impi" _arg_cuda="off" die() { _die_ret="${2:-1}" test "${_PRINT_HELP:-no}" = yes && print_help >&2 echo "$1" >&2 exit "${_die_ret}" } print_help() { printf '%s\n' "Compilation script for octopus using cmake." print_usage } print_usage() { printf '\nUsage: %s [--buildtype <arg>] [-h|--help]\n' "$0" printf '\t%s\n' "--config, --no-config: run configure step (on by default)" printf '\t%s\n' "--compiler: compiler type. available options: 'intel' or 'gcc' (default: 'intel')" printf '\t%s\n' "--mpi: MPI implementation. available options: 'impi', or 'openmpi' (default: 'impi')" printf '\t%s\n' "--cuda, --no-cuda: enable CUDA (default: 'off')" printf '\t%s\n' "-h, --help: print help (this list!)" } parse_commandline() { while test $# -gt 0 do _key="$1" case "$_key" in --no-config|--config) test "${1:0:5}" = "--no-" && _arg_config="off" ;; --compiler) test $# -lt 2 && die "Missing value for the optional argument '$_key'." 1 _arg_compiler="$2" shift ;; --mpi) test $# -lt 2 && die "Missing value for the optional argument '$_key'." 1 _arg_mpi="$2" shift ;; --no-cuda|--cuda) test "${1:0:6}" = "--cuda" && _arg_cuda="on" ;; -h|--help) print_help exit 0 ;; -h*) print_help exit 0 ;; *) _PRINT_HELP=yes die "FATAL ERROR: Unexpected argument '$1'" 1 ;; esac shift done } parse_commandline "$@" case $_arg_compiler in "intel") build_modules="intel/2024.0" ;; "gcc") build_modules="gcc/11" ;; *) echo "Error, compiler $_arg_compiler not supported" ;; esac if [[ "$_arg_cuda" == "on" ]]; then build_modules="$build_modules cuda/11.6" CUDA="-DOCTOPUS_CUDA:BOOL=ON" fi case $_arg_mpi in "impi") build_modules="$build_modules impi/2021.11" ;; "openmpi") if [[ "$_arg_cuda" == "on" ]]; then build_modules="$build_modules openmpi_gpu/4.1" else build_modules="$build_modules openmpi/4.1" fi ;; *) echo "Error, compiler $_arg_compiler not supported" ;; esac module purge module load cmake ninja module load $build_modules module load mkl/2024.0 gsl hdf5-serial netcdf-serial libxc/5.1.5 libvdwxc-mpi cgal boost/1.79 metis-64 parmetis-64 elpa/mpi/openmp/2023.11.001 if [[ "$_arg_compiler" == "intel" ]]; then # need a modern gcc for compiling C++ code with the intel compiler module load gcc/13 fi module list # include compiler and MPI name in build and install directories build=mpcdf-$_arg_compiler-$_arg_mpi if [[ "$_arg_cuda" == "on" ]]; then build=$build-cuda fi if [ "$_arg_config" != "off" ]; then cmake -B build-$build --preset mpcdf-$_arg_compiler -DCMAKE_INSTALL_PREFIX=install-$build $CUDA fi cmake --build build-$build cmake --install build-$build #ctest --test-dir build-$build -L short-run
0
ALLM/M3/octopus/scripts
ALLM/M3/octopus/scripts/build/build_octopus_stampede.sh
#!/bin/bash module swap mvapich2 impi module load fftw3 gsl hdf5 netcdf MKL_DIR=$MKLROOT ./configure --prefix=`pwd` CC=mpicc FC=mpif90 CFLAGS="-O3" FCFLAGS="-O3" --enable-mpi \ --with-blas="-L$MKL_DIR/lib/intel64 -Wl,--start-group -lmkl_intel_lp64 -lmkl_sequential -lmkl_core -Wl,--end-group -lpthread" --with-fftw-prefix="$TACC_FFTW3_DIR" \ --with-netcdf-prefix="$TACC_NETCDF_DIR" --enable-newuoa --with-libxc-prefix=`pwd`/../libxc-2.2.2 --with-blacs="$MKL_DIR/lib/intel64/libmkl_blacs_intelmpi_lp64.a" \ --with-scalapack="$MKL_DIR/lib/intel64/libmkl_scalapack_lp64.a" make -j 6 install
0
ALLM/M3/octopus/scripts
ALLM/M3/octopus/scripts/build/build_octopus_vulcan.sh
#!/bin/bash export LIBS_BLAS="-L/usr/local/tools/essl/5.1/lib/ -lesslsmpbg" export LIBS_LAPACK="/usr/local/tools/lapack/lib/liblapack.a" export LIBS_FFT="-L/usr/local/tools/fftw-3.3.3/lib/ -lfftw3_omp" export FC_INTEGER_SIZE=4 export CC_FORTRAN_INT=int export CC=mpixlc_r export FC=mpixlf95_r export LDFLAGS="-qsmp=omp" export CFLAGS="-g -O3" export FCFLAGS=$CFLAGS" -qxlf90=autodealloc -qessl" ./configure --with-libxc-prefix=$HOME --prefix=$HOME --host=powerpc32-unknown-linux-gnu --build=powerpc64-unknown-linux-gnu --with-gsl-prefix=$HOME --enable-openmp --enable-mpi
0
ALLM/M3/octopus/scripts
ALLM/M3/octopus/scripts/build/build_octopus_xbes.sh
#!/bin/bash ./configure \ PATH="$PATH:/home/common/lib/gsl-1.16-intel/bin" \ CC="mpiicc -m64" CFLAGS=" -O3 -march=native -I${MKLROOT}/include/intel64/lp64 -I${MKLROOT}/include" \ FC="mpiifort -m64" FCFLAGS="-O3 -I${MKLROOT}/include/intel64/lp64 -I${MKLROOT}/include" \ GSL_CONFIG=/home/common/lib/gsl-1.16-intel/bin/gsl-config --with-gsl-prefix="/home/common/lib/gsl-1.16-intel/" \ --with-libxc-prefix=$LIBXC_PREFIX \ --with-blas="${MKLROOT}/lib/intel64/libmkl_blas95_lp64.a ${MKLROOT}/lib/intel64/libmkl_lapack95_lp64.a -Wl,--start-group ${MKLROOT}/lib/intel64/libmkl_intel_lp64.a ${MKLROOT}/lib/intel64/libmkl_core.a ${MKLROOT}/lib/intel64/libmkl_sequential.a -Wl,--end-group -lpthread -lm -ldl" \ --with-lapack="${MKLROOT}/lib/intel64/libmkl_blas95_lp64.a ${MKLROOT}/lib/intel64/libmkl_lapack95_lp64.a -Wl,--start-group ${MKLROOT}/lib/intel64/libmkl_intel_lp64.a ${MKLROOT}/lib/intel64/libmkl_core.a ${MKLROOT}/lib/intel64/libmkl_sequential.a -Wl,--end-group -lpthread -lm -ldl" \ --with-fft-lib=/home/common/lib/fftw-3.3.4-intel/lib/libfftw3.a
0
ALLM/M3/octopus/scripts
ALLM/M3/octopus/scripts/test/test_octopus_cori.sh
-!/bin/bash -l -SBATCH -J pulpo -SBATCH -n 64 -SBATCH -C haswell -SBATCH -p regular -SBATCH -t 04:00:00 -SBATCH --export=ALL cd $HOME/cori/octopus export OMP_NUM_THREADS=1 export MPIEXEC=`which srun` export TEMPDIRPATH=$SCRATCH/tmp export OCT_TEST_NJOBS=15 make check &> $SLURM_SUBMIT_DIR/makecheck
0
ALLM/M3/octopus/scripts
ALLM/M3/octopus/scripts/test/test_octopus_edison.sh
#!/bin/bash -l #SBATCH -J pulpo #SBATCH -N 2 #SBATCH -p regular #SBATCH -t 04:00:00 #SBATCH --export=ALL cd $HOME/edison/octopus export OMP_NUM_THREADS=1 export MPIEXEC=`which srun` export TEMPDIRPATH=$SCRATCH/tmp export OCT_TEST_NJOBS=15 make check &> $SLURM_SUBMIT_DIR/makecheck
0
ALLM/M3/octopus/scripts
ALLM/M3/octopus/scripts/test/test_octopus_lonestar.sh
#!/bin/bash #$ -N test_pulpo #$ -cwd #$ -pe 6way 12 #$ -q development #$ -l h_rt=00:45:00 #$ -V cd $HOME/octopus export TEMPDIRPATH=$SCRATCH/tmp if [ ! -d $TEMPDIRPATH ]; then mkdir $TEMPDIRPATH fi export MPIEXEC=`which ibrun` export OCT_TEST_NPROCS=1 make check &> makecheck
0
ALLM/M3/octopus/scripts
ALLM/M3/octopus/scripts/test/test_octopus_stampede.sh
#!/usr/bin/env bash #SBATCH -n 16 #SBATCH -p development #SBATCH -t 01:00:00 #SBATCH --export=ALL module load perl WORKDIR=$PWD export TEMPDIRPATH=$SCRATCH/tmp cd $HOME/octopus export OCT_TEST_NJOBS=8 export MPIEXEC=`which ibrun` make check &> $WORKDIR/makecheck
0
ALLM/M3/octopus/share
ALLM/M3/octopus/share/opencl/cl_complex.h
/* Copyright (C) 2012 X. Andrade 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, 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __CL_COMPLEX_H__ #define __CL_COMPLEX_H__ #include <cl_global.h> DEVICE_FUNC inline double2 complex_number(const double x, const double y){ #ifdef CUDA return double2(x, y); #else return (double2) (x, y); #endif } DEVICE_FUNC inline double2 complex_conj(const double2 a){ #ifdef CUDA return double2(a.x, -a.y); #else return (double2) (a.x, -a.y); #endif } DEVICE_FUNC inline double2 complex_mul(const double2 a, const double2 b){ #ifdef CUDA return double2(a.x*b.x - a.y*b.y, a.y*b.x + a.x*b.y); #else return (double2)(a.x*b.x - a.y*b.y, a.y*b.x + a.x*b.y); #endif } DEVICE_FUNC inline double2 complex_dotp(const double2 a, const double2 b){ #ifdef CUDA return double2(a.x*b.x + a.y*b.y,-a.y*b.x + a.x*b.y); #else return (double2)(a.x*b.x + a.y*b.y,-a.y*b.x + a.x*b.y); #endif } DEVICE_FUNC inline double2 complex_div(const double2 a, const double2 b){ double2 c = b*b; return complex_mul(a, complex_conj(b))/(c.x + c.y); } DEVICE_FUNC inline double complex_real(const double2 a){ return a.x; } DEVICE_FUNC inline double complex_imag(const double2 a){ return a.y; } #endif /* Local Variables: mode: c coding: utf-8 End: */
0
ALLM/M3/octopus/share
ALLM/M3/octopus/share/opencl/cl_global.h
/* Copyright (C) 2012 X. Andrade 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, 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __CL_GLOBAL_H__ #define __CL_GLOBAL_H__ #ifdef EXT_KHR_FP64 #pragma OPENCL EXTENSION cl_khr_fp64 : enable #elif EXT_AMD_FP64 #pragma OPENCL EXTENSION cl_amd_fp64 : enable // We can use to printf from OpenCL, useful for debugging //#pragma OPENCL EXTENSION cl_amd_printf:enable #endif #ifdef CUDA #include <cuda_compat.h> #else #define DEVICE_FUNC #endif #endif /* Local Variables: mode: c coding: utf-8 End: */
0
ALLM/M3/octopus/share
ALLM/M3/octopus/share/opencl/cl_reduce.h
/* Copyright (C) 2012 X. Andrade 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, 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ // Define the CUDA warpReduce function #ifdef CUDA // shuffle instructions wrappers #if __CUDACC_VER_MAJOR__ >= 9 #define MASK_ALL_WARP 0xFFFFFFFF #define warpShflDown(var, delta) __shfl_down_sync (MASK_ALL_WARP, var, delta) #else #define warpShflDown(var, delta) __shfl_down (var, delta) #endif #ifdef __HIP_PLATFORM_AMD__ // ROCm has no intrinsic __syncwarp() // from hip/amd_detail/hip_cooperative_groups_helper.h #define __syncwarp() __builtin_amdgcn_fence(__ATOMIC_ACQ_REL, "agent") #endif // See for instance // https://developer.nvidia.com/blog/faster-parallel-reductions-kepler/ __device__ inline double dwarpReduce(double val) { #pragma unroll for (int offset = warpSize/2; offset > 0; offset /= 2){ val += warpShflDown(val, offset); } return val; } __device__ inline double2 zwarpReduce(double2 val) { #pragma unroll for (int offset = warpSize/2; offset > 0; offset /= 2){ val.x += warpShflDown(val.x, offset); val.y += warpShflDown(val.y, offset); } return val; } // Note that we need to be careful for Volta architectures // https://developer.nvidia.com/blog/using-cuda-warp-level-primitives/ __device__ inline void dwarpReduce_shared(volatile double * sdata, unsigned int tid) { double v = sdata[tid]; #pragma unroll for (int offset = warpSize; offset > 0; offset /= 2){ v += sdata[tid + offset]; __syncwarp(); sdata[tid] = v; __syncwarp(); } } #else // Defining the atomicAdd operation for double in OpenCL // We use the solution from GROMACS // https://streamhpc.com/blog/2016-02-09/atomic-operations-for-floats-in-opencl-improved/ // This got slightly modified to work properly with doubles inline void atomicAdd(volatile __global double *addr, double val) { union { unsigned long i; double f; } old, new1; do { old.f = *addr; new1.f = old.f + val; } while (atom_cmpxchg((volatile __global unsigned long *)addr, old.i, new1.i) != old.i); } #endif /* Local Variables: mode: c coding: utf-8 End: */
0
ALLM/M3/octopus/share
ALLM/M3/octopus/share/opencl/cl_rtype.h
/* Copyright (C) 2012 X. Andrade 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, 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __CL_RTYPE_H__ #define __CL_RTYPE_H__ #include <cl_global.h> #if defined(RTYPE_DOUBLE) typedef double rtype; #define X(x) d ## x #define MUL(x, y) ((x)*(y)) #define CONJ(x) (x) #define REAL(x) (x) #define IMAG(x) (0.0) #elif defined(RTYPE_COMPLEX) typedef double2 rtype; #define X(x) z ## x #define MUL(x, y) complex_mul(x, y) #define CONJ(x) complex_conj(x) #define REAL(x) complex_real(x) #define IMAG(x) complex_imag(x) #else #error Type not defined #endif #endif /* Local Variables: mode: c coding: utf-8 End: */
0
ALLM/M3/octopus/share
ALLM/M3/octopus/share/opencl/cuda_compat.h
/* Copyright (C) 2016 X. Andrade 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, 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __CUDA_COMPAT_H__ #define __CUDA_COMPAT_H__ #define __kernel extern "C" __global__ #define __global #define __constant // perhaps there is a type of memory for this #ifndef __local #define __local __shared__ #endif #define restrict __restrict__ #define barrier(x) __syncthreads() #define DEVICE_FUNC __host__ __device__ __device__ __forceinline__ static size_t get_global_id(const int ii){ switch(ii){ case 0 : return threadIdx.x + blockDim.x*blockIdx.x; case 1 : return threadIdx.y + blockDim.y*blockIdx.y; case 2 : return threadIdx.z + blockDim.z*blockIdx.z; } return 0; } __device__ __forceinline__ static size_t get_global_size(const int ii){ switch(ii){ case 0 : return blockDim.x*gridDim.x; case 1 : return blockDim.y*gridDim.y; case 2 : return blockDim.z*gridDim.z; } return 0; } __device__ __forceinline__ static size_t get_local_id(const int ii){ switch(ii){ case 0 : return threadIdx.x; case 1 : return threadIdx.y; case 2 : return threadIdx.z; } return 0; } __device__ __forceinline__ static size_t get_local_size(const int ii){ switch(ii){ case 0 : return blockDim.x; case 1 : return blockDim.y; case 2 : return blockDim.z; } return 0; } #define double2 Double2 class __align__(16) double2{ public: double x; double y; DEVICE_FUNC __forceinline__ double2(const double & a = 0, const double & b = 0):x(a), y(b){} }; DEVICE_FUNC __forceinline__ static Double2 operator*(const double & a, const Double2 & b){ Double2 c; c.x = a*b.x; c.y = a*b.y; return c; } DEVICE_FUNC __forceinline__ static Double2 operator*(const Double2 & a, const Double2 & b){ Double2 c; c.x = a.x*b.x; c.y = a.y*b.y; return c; } DEVICE_FUNC __forceinline__ static Double2 operator+(const Double2 & a, const Double2 & b){ Double2 c; c.x = a.x + b.x; c.y = a.y + b.y; return c; } DEVICE_FUNC __forceinline__ static Double2 operator-(const Double2 & a, const Double2 & b){ Double2 c; c.x = a.x - b.x; c.y = a.y - b.y; return c; } DEVICE_FUNC __forceinline__ static Double2 operator+=(Double2 & a, const Double2 & b){ a.x += b.x; a.y += b.y; return a; } DEVICE_FUNC __forceinline__ static Double2 operator-=(Double2 & a, const Double2 & b){ a.x -= b.x; a.y -= b.y; return a; } DEVICE_FUNC __forceinline__ static Double2 operator/(const Double2 & a, const double & b){ Double2 c; c.x = a.x/b; c.y = a.y/b; return c; } DEVICE_FUNC __forceinline__ static double sincos(const double & x, double * cosx){ double sinx; sincos(x, &sinx, cosx); return sinx; } #endif
0
ALLM/M3/octopus/src
ALLM/M3/octopus/src/basic/alloc_cache_low.cc
/* Copyright (C) 2019 X. Andrade 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, 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <cassert> #include <fortran_types.h> #include <iostream> #include <unordered_map> struct alloc_cache { typedef std::unordered_multimap<fint8, void *> map; map list; fint8 max_size; fint8 current_size; fint8 hits; fint8 misses; double vol_hits; double vol_misses; alloc_cache(fint8 arg_max_size) { max_size = arg_max_size; current_size = 0; hits = 0; misses = 0; vol_hits = 0.0; vol_misses = 0.0; } }; extern "C" void FC_FUNC(alloc_cache_init, ALLOC_CACHE_INIT)(alloc_cache **cache, fint8 max_size) { *cache = new alloc_cache(max_size); } extern "C" void FC_FUNC(alloc_cache_end, ALLOC_CACHE_END)(alloc_cache **cache, fint8 *hits, fint8 *misses, double *vol_hits, double *vol_misses) { assert((*cache)->list.empty()); *hits = (*cache)->hits; *misses = (*cache)->misses; *vol_hits = (*cache)->vol_hits++; *vol_misses = (*cache)->vol_misses++; delete *cache; } extern "C" void FC_FUNC(alloc_cache_put_low, ALLOC_CACHE_PUT_LOW)(alloc_cache **cache, const fint8 *size, void **loc, fint *put) { if ((*cache)->current_size + *size <= (*cache)->max_size) { (*cache)->current_size += *size; (*cache)->list.insert(alloc_cache::map::value_type(*size, *loc)); *put = 1; } else { *put = 0; } } #define CACHE_ALLOC_ANY_SIZE -1 extern "C" void FC_FUNC(alloc_cache_get_low, ALLOC_CACHE_GET_LOW)(alloc_cache **cache, const fint8 *size, fint *found, void **loc) { if (*size == CACHE_ALLOC_ANY_SIZE) { auto pos = (*cache)->list.begin(); *found = pos != (*cache)->list.end(); if (*found) { *loc = pos->second; (*cache)->list.erase(pos); } } else { auto pos = (*cache)->list.find(*size); *found = (pos != (*cache)->list.end()); if (*found) { (*cache)->current_size -= *size; assert(pos->first == *size); *loc = pos->second; (*cache)->list.erase(pos); (*cache)->hits++; (*cache)->vol_hits += *size; } else { *loc = NULL; (*cache)->misses++; (*cache)->vol_misses += *size; } } }
0
ALLM/M3/octopus/src
ALLM/M3/octopus/src/basic/cgal_polyhedra_low.cc
/* Copyright (C) 2014 Adapted from CGAL example (Author: Pierre Alliez) by Vladimir Fuka Copyright (C) 2020 Heiko Appel This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 3 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> // undef CC here because that is used in CGAL... #undef CC #ifdef HAVE_CGAL #include <fstream> #include <iostream> #include <list> #include <CGAL/AABB_face_graph_triangle_primitive.h> #include <CGAL/AABB_traits.h> #include <CGAL/AABB_tree.h> #include <CGAL/Polyhedron_3.h> #include <CGAL/Side_of_triangle_mesh.h> #include <CGAL/Simple_cartesian.h> #include <CGAL/algorithm.h> #include <CGAL/boost/graph/graph_traits_Polyhedron_3.h> typedef CGAL::Simple_cartesian<double> K; typedef K::Point_3 Point; typedef CGAL::Polyhedron_3<K> Polyhedron; typedef CGAL::AABB_face_graph_triangle_primitive<Polyhedron> Primitive; typedef CGAL::AABB_traits<K, Primitive> Traits; typedef CGAL::AABB_tree<Traits> Tree; typedef CGAL::Side_of_triangle_mesh<Polyhedron, K> Point_inside; typedef CGAL::Bbox_3 Bbox_3; typedef struct { double x, y, z; } d3; using std::cout; using std::endl; extern "C" int debuglevel; extern "C" { void polyhedron_from_file(Polyhedron **poly, const char *fname, int verbose, int *const ierr) { Polyhedron *polyhedron = new Polyhedron; std::ifstream in(fname); if (verbose) { cout << " Reading file " << fname << " " << endl; } try { in >> *polyhedron; } catch (...) { *ierr = 2; return; } if (verbose) { cout << " facets: " << polyhedron->size_of_facets() << endl; cout << " halfedges: " << polyhedron->size_of_halfedges() << endl; cout << " vertices: " << polyhedron->size_of_vertices() << endl; } if (polyhedron->size_of_facets() == 0 || polyhedron->size_of_halfedges() == 0 || polyhedron->size_of_vertices() == 0) { *ierr = 1; return; }; *poly = polyhedron; *ierr = 0; } void polyhedron_build_AABB_tree(Tree **tree_out, Polyhedron **polyhedron) { // Construct AABB tree with a KdTree Tree *tree = new Tree(faces(**polyhedron).first, faces(**polyhedron).second, **polyhedron); tree->accelerate_distance_queries(); *tree_out = tree; } bool polyhedron_point_inside(Tree **tree, Point *query) { // Initialize the point-in-polyhedron tester Point_inside inside_tester(**tree); // Determine the side and return true if inside or on the boundary. return inside_tester(*query) == CGAL::ON_BOUNDED_SIDE || inside_tester(*query) == CGAL::ON_BOUNDARY; } void polyhedron_finalize_AABB_tree(Tree **tree) { delete *tree; *tree = NULL; } void polyhedron_finalize_polyhedron(Polyhedron **polyhedron) { delete *polyhedron; *polyhedron = NULL; } } #endif
0
ALLM/M3/octopus/src
ALLM/M3/octopus/src/basic/clblas_low.c
#include <config.h> #ifdef HAVE_CLBLAS #include <clBLAS.h> void FC_FUNC_(clblasgetversion_low, CLBLASGETVERSION_LOW)(int * major, int * minor, int * patch, int * status){ cl_uint cl_major, cl_minor, cl_patch; *status = clblasGetVersion(&cl_major, &cl_minor, &cl_patch); *major = cl_major; *minor = cl_minor; *patch = cl_patch; } void FC_FUNC_(clblassetup_low, CLBLASSETUP_LOW)(int * status){ *status = clblasSetup(); } void FC_FUNC_(clblasteardown_low, CLBLASTEARDOWN_LOW)(){ clblasTeardown(); } void FC_FUNC_(clblasdtrsmex_low, CLBLASDTRSMEX_LOW)(int * order, int * side, int * uplo, int * transA, int * diag, cl_long * M, cl_long * N, double * alpha, const cl_mem * A, size_t * offA, size_t * lda, cl_mem * B, size_t * offB, size_t * ldb, cl_command_queue * CommandQueue, int * status){ *status = clblasDtrsm((clblasOrder) *order, (clblasSide) *side, (clblasUplo) *uplo, (clblasTranspose) *transA, (clblasDiag) *diag, (size_t) *M, (size_t) *N, *alpha, *A, (size_t) *offA, (size_t) *lda, *B, (size_t) *offB, (size_t) *ldb, 1, CommandQueue, 0, NULL, NULL); } void FC_FUNC_(clblasztrsmex_low, CLBLASZTRSMEX_LOW)(int * order, int * side, int * uplo, int * transA, int * diag, cl_long * M, cl_long * N, DoubleComplex * alpha, const cl_mem * A, size_t * offA, size_t * lda, cl_mem * B, size_t * offB, size_t * ldb, cl_command_queue * CommandQueue, int * status){ *status = clblasZtrsm((clblasOrder) *order, (clblasSide) *side, (clblasUplo) *uplo, (clblasTranspose) *transA, (clblasDiag) *diag, (size_t) *M, (size_t) *N, *alpha, *A, (size_t) *offA, (size_t) *lda, *B, (size_t) *offB, (size_t) *ldb, 1, CommandQueue, 0, NULL, NULL); } void FC_FUNC_(clblasdgemmex_low, CLBLASDGEMMEX_LOW)(int * order, int * transA, int * transB, cl_long * M, cl_long * N, cl_long * K, double * alpha, const cl_mem * A, cl_long * offA, cl_long * lda, const cl_mem * B, cl_long * offB, cl_long * ldb, double * beta, cl_mem * C, cl_long * offC, cl_long * ldc, cl_command_queue * CommandQueue, int * status){ *status = clblasDgemm((clblasOrder) *order, (clblasTranspose) *transA, (clblasTranspose) *transB, (size_t) *M, (size_t) *N, (size_t) *K, *alpha, *A, (size_t) *offA, (size_t) *lda, *B, (size_t) *offB, (size_t) *ldb, *beta, *C, (size_t) *offC, (size_t) *ldc, 1, CommandQueue, 0, NULL, NULL); } void FC_FUNC_(clblaszgemmex_low, CLBLASDGEMMEX_LOW)(int * order, int * transA, int * transB, cl_long * M, cl_long * N, cl_long * K, DoubleComplex * alpha, const cl_mem * A, cl_long * offA, cl_long * lda, const cl_mem * B, cl_long * offB, cl_long * ldb, DoubleComplex * beta, cl_mem * C, cl_long * offC, cl_long * ldc, cl_command_queue * CommandQueue, int * status){ *status = clblasZgemm((clblasOrder) *order, (clblasTranspose) *transA, (clblasTranspose) *transB, (size_t) *M, (size_t) *N, (size_t) *K, *alpha, *A, (size_t) *offA, (size_t) *lda, *B, (size_t) *offB, (size_t) *ldb, *beta, *C, (size_t) *offC, (size_t) *ldc, 1, CommandQueue, 0, NULL, NULL); } void FC_FUNC_(clblasdsyrkex_low, CLBLASDSYRKEX_LOW)(int * order, int * uplo, int * transA, cl_long * N, cl_long * K, double * alpha, const cl_mem * A, cl_long * offA, cl_long * lda, double * beta, cl_mem * C, cl_long * offC, cl_long * ldc, cl_command_queue * CommandQueue, int * status){ *status = clblasDsyrk((clblasOrder) *order, (clblasUplo) *uplo, (clblasTranspose) *transA, (size_t) *N, (size_t) *K, *alpha, *A, (size_t) *offA, (size_t) *lda, *beta, *C, (size_t) *offC, (size_t) *ldc, 1, CommandQueue, 0, NULL, NULL); } void FC_FUNC_(clblaszherkex_low, CLBLASZHERKEX_LOW)(int * order, int * uplo, int * transA, cl_long * N, cl_long * K, double * alpha, const cl_mem * A, cl_long * offA, cl_long * lda, double * beta, cl_mem * C, cl_long * offC, cl_long * ldc, cl_command_queue * CommandQueue, int * status){ *status = clblasZherk((clblasOrder) *order, (clblasUplo) *uplo, (clblasTranspose) *transA, (size_t) *N, (size_t) *K, *alpha, *A, (size_t) *offA, (size_t) *lda, *beta, *C, (size_t) *offC, (size_t) *ldc, 1, CommandQueue, 0, NULL, NULL); } clblasStatus FC_FUNC_(clblasddot_low, CLBLASDDOT_LOW)(cl_long * N, cl_mem * dotProduct, cl_long * offDP, const cl_mem *X, cl_long * offx, int *incx, const cl_mem * Y, cl_long * offy, int * incy, cl_mem * scratchBuff, cl_command_queue * CommandQueue, int * status){ *status = clblasDdot((size_t) *N, *dotProduct, (size_t) *offDP, *X, (size_t) *offx, *incx, *Y, (size_t) *offy, *incy, *scratchBuff, 1, CommandQueue, 0, NULL, NULL); } clblasStatus FC_FUNC_(clblaszdotc_low, CLBLASZDOTC_LOW)(cl_long * N, cl_mem * dotProduct, cl_long * offDP, const cl_mem *X, cl_long * offx, int *incx, const cl_mem * Y, cl_long * offy, int * incy, cl_mem * scratchBuff, cl_command_queue * CommandQueue, int * status){ *status = clblasZdotc((size_t) *N, *dotProduct, (size_t) *offDP, *X, (size_t) *offx, *incx, *Y, (size_t) *offy, *incy, *scratchBuff, 1, CommandQueue, 0, NULL, NULL); } clblasStatus FC_FUNC_(clblasdnrm2_low, CLBLASDNRM2_LOW)(cl_long * N, cl_mem * NRM2, cl_long * offNRM2, const cl_mem *X, cl_long * offx, int *incx, cl_mem * scratchBuff, cl_command_queue * CommandQueue, int * status){ *status = clblasDnrm2((size_t) *N, *NRM2, (size_t) *offNRM2, *X, (size_t) *offx, *incx, *scratchBuff, 1, CommandQueue, 0, NULL, NULL); } clblasStatus FC_FUNC_(clblasdznrm2_low, CLBLASDZNRM2_LOW)(cl_long * N, cl_mem * NRM2, cl_long * offNRM2, const cl_mem *X, cl_long * offx, int *incx, cl_mem * scratchBuff, cl_command_queue * CommandQueue, int * status){ *status = clblasDznrm2((size_t) *N, *NRM2, (size_t) *offNRM2, *X, (size_t) *offx, *incx, *scratchBuff, 1, CommandQueue, 0, NULL, NULL); } #endif
0
ALLM/M3/octopus/src
ALLM/M3/octopus/src/basic/clblast_low.c
/* Copyright (C) 2022 N. Tancogne-Dejean * * 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, 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., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. */ #include <config.h> #ifdef HAVE_CLBLAST #include <clblast_c.h> void FC_FUNC_(clblasdtrsmex_low, CLBLASDTRSMEX_LOW)(int * order, int * side, int * uplo, int * transA, int * diag, cl_long * M, cl_long * N, double * alpha, const cl_mem * A, size_t * offA, size_t * lda, cl_mem * B, size_t * offB, size_t * ldb, cl_command_queue * CommandQueue, int * status){ *status = CLBlastDtrsm((CLBlastLayout) *order, (CLBlastSide) *side, (CLBlastTriangle) *uplo, (CLBlastTranspose) *transA, (CLBlastDiagonal) *diag, (size_t) *M, (size_t) *N, *alpha, *A, (size_t) *offA, (size_t) *lda, *B, (size_t) *offB, (size_t) *ldb, CommandQueue, NULL); } void FC_FUNC_(clblasztrsmex_low, CLBLASZTRSMEX_LOW)(int * order, int * side, int * uplo, int * transA, int * diag, cl_long * M, cl_long * N, cl_double2 * alpha, const cl_mem * A, size_t * offA, size_t * lda, cl_mem * B, size_t * offB, size_t * ldb, cl_command_queue * CommandQueue, int * status){ *status = CLBlastZtrsm((CLBlastLayout) *order, (CLBlastSide) *side, (CLBlastTriangle) *uplo, (CLBlastTranspose) *transA, (CLBlastDiagonal) *diag, (size_t) *M, (size_t) *N, *alpha, *A, (size_t) *offA, (size_t) *lda, *B, (size_t) *offB, (size_t) *ldb, CommandQueue, NULL); } void FC_FUNC_(clblasdgemvex_low, CLBLASDGEMVEX_LOW)(int * order, int * transA, cl_long * M, cl_long * N, double * alpha, const cl_mem * A, cl_long * offA, cl_long * lda, const cl_mem * X, cl_long * offX, cl_long * incx, double * beta, cl_mem * Y, cl_long * offY, cl_long * incy, cl_command_queue * CommandQueue, int * status){ *status = CLBlastDgemv((CLBlastLayout) *order, (CLBlastTranspose) *transA, (size_t) *M, (size_t) *N, *alpha, *A, (size_t) *offA, (size_t) *lda, *X, (size_t) *offX, (size_t) *incx, *beta, *Y, (size_t) *offY, (size_t) *incy, CommandQueue, NULL); } void FC_FUNC_(clblaszgemvex_low, CLBLASZGEMVEX_LOW)(int * order, int * transA, cl_long * M, cl_long * N, cl_double2 * alpha, const cl_mem * A, cl_long * offA, cl_long * lda, const cl_mem * X, cl_long * offX, cl_long * incx, cl_double2 * beta, cl_mem * Y, cl_long * offY, cl_long * incy, cl_command_queue * CommandQueue, int * status){ *status = CLBlastZgemv((CLBlastLayout) *order, (CLBlastTranspose) *transA, (size_t) *M, (size_t) *N, *alpha, *A, (size_t) *offA, (size_t) *lda, *X, (size_t) *offX, (size_t) *incx, *beta, *Y, (size_t) *offY, (size_t) *incy, CommandQueue, NULL); } void FC_FUNC_(clblasdgemmex_low, CLBLASDGEMMEX_LOW)(int * order, int * transA, int * transB, cl_long * M, cl_long * N, cl_long * K, double * alpha, const cl_mem * A, cl_long * offA, cl_long * lda, const cl_mem * B, cl_long * offB, cl_long * ldb, double * beta, cl_mem * C, cl_long * offC, cl_long * ldc, cl_command_queue * CommandQueue, int * status){ *status = CLBlastDgemm((CLBlastLayout) *order, (CLBlastTranspose) *transA, (CLBlastTranspose) *transB, (size_t) *M, (size_t) *N, (size_t) *K, *alpha, *A, (size_t) *offA, (size_t) *lda, *B, (size_t) *offB, (size_t) *ldb, *beta, *C, (size_t) *offC, (size_t) *ldc, CommandQueue, NULL); } void FC_FUNC_(clblaszgemmex_low, CLBLASDGEMMEX_LOW)(int * order, int * transA, int * transB, cl_long * M, cl_long * N, cl_long * K, cl_double2 * alpha, const cl_mem * A, cl_long * offA, cl_long * lda, const cl_mem * B, cl_long * offB, cl_long * ldb, cl_double2 * beta, cl_mem * C, cl_long * offC, cl_long * ldc, cl_command_queue * CommandQueue, int * status){ *status = CLBlastZgemm((CLBlastLayout) *order, (CLBlastTranspose) *transA, (CLBlastTranspose) *transB, (size_t) *M, (size_t) *N, (size_t) *K, *alpha, *A, (size_t) *offA, (size_t) *lda, *B, (size_t) *offB, (size_t) *ldb, *beta, *C, (size_t) *offC, (size_t) *ldc, CommandQueue, NULL); } void FC_FUNC_(clblasdsyrkex_low, CLBLASDSYRKEX_LOW)(int * order, int * uplo, int * transA, cl_long * N, cl_long * K, double * alpha, const cl_mem * A, cl_long * offA, cl_long * lda, double * beta, cl_mem * C, cl_long * offC, cl_long * ldc, cl_command_queue * CommandQueue, int * status){ *status = CLBlastDsyrk((CLBlastLayout) *order, (CLBlastTriangle) *uplo, (CLBlastTranspose) *transA, (size_t) *N, (size_t) *K, *alpha, *A, (size_t) *offA, (size_t) *lda, *beta, *C, (size_t) *offC, (size_t) *ldc, CommandQueue, NULL); } void FC_FUNC_(clblaszherkex_low, CLBLASZHERKEX_LOW)(int * order, int * uplo, int * transA, cl_long * N, cl_long * K, double * alpha, const cl_mem * A, cl_long * offA, cl_long * lda, double * beta, cl_mem * C, cl_long * offC, cl_long * ldc, cl_command_queue * CommandQueue, int * status){ *status = CLBlastZherk((CLBlastLayout) *order, (CLBlastTriangle) *uplo, (CLBlastTranspose) *transA, (size_t) *N, (size_t) *K, *alpha, *A, (size_t) *offA, (size_t) *lda, *beta, *C, (size_t) *offC, (size_t) *ldc, CommandQueue, NULL); } CLBlastStatusCode FC_FUNC_(clblasddot_low, CLBLASDDOT_LOW)(cl_long * N, cl_mem * dotProduct, cl_long * offDP, const cl_mem *X, cl_long * offx, int *incx, const cl_mem * Y, cl_long * offy, int * incy, cl_mem * scratchBuff, cl_command_queue * CommandQueue, int * status){ *status = CLBlastDdot((size_t) *N, *dotProduct, (size_t) *offDP, *X, (size_t) *offx, *incx, *Y, (size_t) *offy, *incy, CommandQueue, NULL); } CLBlastStatusCode FC_FUNC_(clblaszdotc_low, CLBLASZDOTc_LOW)(cl_long * N, cl_mem * dotProduct, cl_long * offDP, const cl_mem *X, cl_long * offx, int *incx, const cl_mem * Y, cl_long * offy, int * incy, cl_mem * scratchBuff, cl_command_queue * CommandQueue, int * status){ *status = CLBlastZdotc((size_t) *N, *dotProduct, (size_t) *offDP, *X, (size_t) *offx, *incx, *Y, (size_t) *offy, *incy, CommandQueue, NULL); } CLBlastStatusCode FC_FUNC_(clblaszdotu_low, CLBLASZDOTU_LOW)(cl_long * N, cl_mem * dotProduct, cl_long * offDP, const cl_mem *X, cl_long * offx, int *incx, const cl_mem * Y, cl_long * offy, int * incy, cl_mem * scratchBuff, cl_command_queue * CommandQueue, int * status){ *status = CLBlastZdotu((size_t) *N, *dotProduct, (size_t) *offDP, *X, (size_t) *offx, *incx, *Y, (size_t) *offy, *incy, CommandQueue, NULL); } CLBlastStatusCode FC_FUNC_(clblasdnrm2_low, CLBLASDNRM2_LOW)(cl_long * N, cl_mem * NRM2, cl_long * offNRM2, const cl_mem *X, cl_long * offx, int *incx, cl_mem * scratchBuff, cl_command_queue * CommandQueue, int * status){ *status = CLBlastDnrm2((size_t) *N, *NRM2, (size_t) *offNRM2, *X, (size_t) *offx, *incx, CommandQueue, NULL); } CLBlastStatusCode FC_FUNC_(clblasdznrm2_low, CLBLASDZNRM2_LOW)(cl_long * N, cl_mem * NRM2, cl_long * offNRM2, const cl_mem *X, cl_long * offx, int *incx, cl_mem * scratchBuff, cl_command_queue * CommandQueue, int * status){ *status = CLBlastDznrm2((size_t) *N, *NRM2, (size_t) *offNRM2, *X, (size_t) *offx, *incx, CommandQueue, NULL); } #endif
0
ALLM/M3/octopus/src
ALLM/M3/octopus/src/basic/cublas.cc
/* Copyright (C) 2016 X. Andrade 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, 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <cstdio> #include <iostream> #include <fortran_types.h> #ifdef HAVE_CUDA #ifdef HAVE_HIP #include <hip/hip_runtime.h> #include <hipblas/hipblas.h> #define cudaStream_t hipStream_t #define CUdeviceptr hipDeviceptr_t // https://rocm.docs.amd.com/projects/HIPIFY/en/latest/tables/CUBLAS_API_supported_by_HIP.html #define cublasCreate hipblasCreate #define cublasDdot hipblasDdot #define cublasDestroy hipblasDestroy #define cublasDgemm hipblasDgemm #define cublasDgemv hipblasDgemv #define cublasDiagType_t hipblasDiagType_t #define cublasDnrm2 hipblasDnrm2 #define cublasDsyrk hipblasDsyrk #define cublasDtrsm hipblasDtrsm #define cublasDznrm2 hipblasDznrm2 /*_v2*/ #define cublasFillMode_t hipblasFillMode_t #define cublasHandle_t hipblasHandle_t #define cublasOperation_t hipblasOperation_t #define CUBLAS_POINTER_MODE_DEVICE HIPBLAS_POINTER_MODE_DEVICE #define cublasSetPointerMode hipblasSetPointerMode #define cublasSetStream hipblasSetStream #define cublasSideMode_t hipblasSideMode_t #define CUBLAS_STATUS_ALLOC_FAILED HIPBLAS_STATUS_ALLOC_FAILED #define CUBLAS_STATUS_ARCH_MISMATCH HIPBLAS_STATUS_ARCH_MISMATCH #define CUBLAS_STATUS_EXECUTION_FAILED HIPBLAS_STATUS_EXECUTION_FAILED #define CUBLAS_STATUS_INTERNAL_ERROR HIPBLAS_STATUS_INTERNAL_ERROR #define CUBLAS_STATUS_INVALID_VALUE HIPBLAS_STATUS_INVALID_VALUE #define CUBLAS_STATUS_LICENSE_ERROR HIPBLAS_STATUS_UNKNOWN #define CUBLAS_STATUS_MAPPING_ERROR HIPBLAS_STATUS_MAPPING_ERROR #define CUBLAS_STATUS_NOT_INITIALIZED HIPBLAS_STATUS_NOT_INITIALIZED #define CUBLAS_STATUS_NOT_SUPPORTED HIPBLAS_STATUS_NOT_SUPPORTED #define CUBLAS_STATUS_SUCCESS HIPBLAS_STATUS_SUCCESS #define cublasStatus_t hipblasStatus_t #define cublasZdotc hipblasZdotc /*_v2*/ #define cublasZdotu hipblasZdotu /*_v2*/ #define cublasZgemm hipblasZgemm /*_v2*/ #define cublasZgemv hipblasZgemv /*_v2*/ #define cublasZherk hipblasZherk /*_v2*/ #define cublasZtrsm hipblasZtrsm /*_v2*/ #define cuDoubleComplex hipblasDoubleComplex #else #include <cublas_v2.h> #include <cuda.h> #endif #else #include <complex> typedef int cublasHandle_t; typedef int CUdeviceptr; typedef std::complex<double> cuDoubleComplex; typedef int cudaStream_t; #endif #define CUBLAS_SAFE_CALL(x) cublas_safe_call(#x, x) #ifdef HAVE_CUDA static cublasStatus_t cublas_safe_call(const char *call, cublasStatus_t safe_call_result) { if (safe_call_result != CUBLAS_STATUS_SUCCESS) { #ifdef HAVE_HIP std::string error_str = hipblasStatusToString(safe_call_result); #else std::string error_str; switch (safe_call_result) { case CUBLAS_STATUS_SUCCESS: error_str = "CUBLAS_STATUS_SUCCESS"; break; case CUBLAS_STATUS_NOT_INITIALIZED: error_str = "CUBLAS_STATUS_NOT_INITIALIZED"; break; case CUBLAS_STATUS_ALLOC_FAILED: error_str = "CUBLAS_STATUS_ALLOC_FAILED"; break; case CUBLAS_STATUS_INVALID_VALUE: error_str = "CUBLAS_STATUS_INVALID_VALUE"; break; case CUBLAS_STATUS_ARCH_MISMATCH: error_str = "CUBLAS_STATUS_ARCH_MISMATCH"; break; case CUBLAS_STATUS_MAPPING_ERROR: error_str = "CUBLAS_STATUS_MAPPING_ERROR"; break; case CUBLAS_STATUS_EXECUTION_FAILED: error_str = "CUBLAS_STATUS_EXECUTION_FAILED"; break; case CUBLAS_STATUS_INTERNAL_ERROR: error_str = "CUBLAS_STATUS_INTERNAL_ERROR"; break; case CUBLAS_STATUS_NOT_SUPPORTED: error_str = "CUBLAS_STATUS_NOT_SUPPORTED"; break; case CUBLAS_STATUS_LICENSE_ERROR: error_str = "CUBLAS_STATUS_LICENSE_ERROR"; break; } #endif std::cerr << "\nerror: " << call << " failed with error '" << error_str << "'" << std::endl; exit(1); } return safe_call_result; } #endif extern "C" void FC_FUNC_(cublas_init, CUBLAS_INIT)(cublasHandle_t **handle, cudaStream_t **stream) { #ifdef HAVE_CUDA *handle = new cublasHandle_t; CUBLAS_SAFE_CALL(cublasCreate(*handle)); CUBLAS_SAFE_CALL(cublasSetPointerMode(**handle, CUBLAS_POINTER_MODE_DEVICE)); CUBLAS_SAFE_CALL(cublasSetStream(**handle, **stream)); #endif } extern "C" void FC_FUNC_(cublas_end, CUBLAS_END)(cublasHandle_t **handle) { #ifdef HAVE_CUDA CUBLAS_SAFE_CALL(cublasDestroy(**handle)); delete *handle; #endif } extern "C" void FC_FUNC_(cuda_blas_ddot, CUDA_BLAS_DDOT)(cublasHandle_t **handle, fint8 *n, CUdeviceptr **x, fint8 *offx, fint8 *incx, CUdeviceptr **y, fint8 *offy, fint8 *incy, CUdeviceptr **result, fint8 *off_result) { #ifdef HAVE_CUDA CUBLAS_SAFE_CALL(cublasDdot(**handle, *n, ((double *)**x) + *offx, *incx, ((double *)**y) + *offy, *incy, ((double *)**result) + *off_result)); #endif } extern "C" void FC_FUNC_(cuda_blas_zdotc, CUDA_BLAS_ZDOTC)( cublasHandle_t **handle, fint8 *n, CUdeviceptr **x, fint8 *offx, fint8 *incx, CUdeviceptr **y, fint8 *offy, fint8 *incy, CUdeviceptr **result, fint8 *off_result) { #ifdef HAVE_CUDA CUBLAS_SAFE_CALL(cublasZdotc(**handle, *n, ((cuDoubleComplex *)**x) + *offx, *incx, ((cuDoubleComplex *)**y) + *offy, *incy, ((cuDoubleComplex *)**result) + *off_result)); #endif } extern "C" void FC_FUNC_(cuda_blas_zdotu, CUDA_BLAS_ZDOTU)( cublasHandle_t **handle, fint8 *n, CUdeviceptr **x, fint8 *offx, fint8 *incx, CUdeviceptr **y, fint8 *offy, fint8 *incy, CUdeviceptr **result, fint8 *off_result) { #ifdef HAVE_CUDA CUBLAS_SAFE_CALL(cublasZdotu(**handle, *n, ((cuDoubleComplex *)**x) + *offx, *incx, ((cuDoubleComplex *)**y) + *offy, *incy, ((cuDoubleComplex *)**result) + *off_result)); #endif } extern "C" void FC_FUNC_(cuda_blas_dnrm2, CUDA_BLAS_DNRM2)(cublasHandle_t **handle, fint8 *n, CUdeviceptr **x, fint8 *offx, fint8 *incx, CUdeviceptr **result, fint8 *off_result) { #ifdef HAVE_CUDA CUBLAS_SAFE_CALL(cublasDnrm2(**handle, *n, ((double *)**x) + *offx, *incx, ((double *)**result) + *off_result)); #endif } extern "C" void FC_FUNC_(cuda_blas_znrm2, CUDA_BLAS_ZNRM2)(cublasHandle_t **handle, fint8 *n, CUdeviceptr **x, fint8 *offx, fint8 *incx, CUdeviceptr **result, fint8 *off_result) { #ifdef HAVE_CUDA CUBLAS_SAFE_CALL(cublasDznrm2(**handle, *n, ((cuDoubleComplex *)**x) + *offx, *incx, ((double *)**result) + *off_result)); #endif } extern "C" void FC_FUNC_(cuda_blas_dgemm, CUDA_BLAS_DGEMM)( cublasHandle_t **handle, fint *transa, fint *transb, fint8 *m, fint8 *n, fint8 *k, CUdeviceptr **alpha, CUdeviceptr **A, fint8 *lda, CUdeviceptr **B, fint8 *ldb, CUdeviceptr **beta, CUdeviceptr **C, fint8 *ldc) { #ifdef HAVE_CUDA CUBLAS_SAFE_CALL(cublasDgemm( **handle, (cublasOperation_t)*transa, (cublasOperation_t)*transb, *m, *n, *k, (double *)**alpha, (double *)**A, *lda, (double *)**B, *ldb, (double *)**beta, (double *)**C, *ldc)); #endif } extern "C" void FC_FUNC_(cuda_blas_zgemm, CUDA_BLAS_ZGEMM)( cublasHandle_t **handle, fint *transa, fint *transb, fint8 *m, fint8 *n, fint8 *k, CUdeviceptr **alpha, CUdeviceptr **A, fint8 *lda, CUdeviceptr **B, fint8 *ldb, CUdeviceptr **beta, CUdeviceptr **C, fint8 *ldc) { #ifdef HAVE_CUDA CUBLAS_SAFE_CALL(cublasZgemm( **handle, (cublasOperation_t)*transa, (cublasOperation_t)*transb, *m, *n, *k, (cuDoubleComplex *)**alpha, (cuDoubleComplex *)**A, *lda, (cuDoubleComplex *)**B, *ldb, (cuDoubleComplex *)**beta, (cuDoubleComplex *)**C, *ldc)); #endif } extern "C" void FC_FUNC_(cuda_blas_dgemv, CUDA_BLAS_DGEMV)( cublasHandle_t **handle, fint *transa, fint8 *m, fint8 *n, CUdeviceptr **alpha, CUdeviceptr **A, fint8 *lda, CUdeviceptr **x, fint8 *incx, CUdeviceptr **beta, CUdeviceptr **y, fint8 *incy) { #ifdef HAVE_CUDA CUBLAS_SAFE_CALL(cublasDgemv(**handle, (cublasOperation_t)*transa, *m, *n, (double *)**alpha, (double *)**A, *lda, (double *)**x, *incx, (double *)**beta, (double *)**y, *incy)); #endif } extern "C" void FC_FUNC_(cuda_blas_zgemv, CUDA_BLAS_ZGEMV)( cublasHandle_t **handle, fint *transa, fint8 *m, fint8 *n, CUdeviceptr **alpha, CUdeviceptr **A, fint8 *lda, CUdeviceptr **x, fint8 *incx, CUdeviceptr **beta, CUdeviceptr **y, fint8 *incy) { #ifdef HAVE_CUDA CUBLAS_SAFE_CALL(cublasZgemv( **handle, (cublasOperation_t)*transa, *m, *n, (cuDoubleComplex *)**alpha, (cuDoubleComplex *)**A, *lda, (cuDoubleComplex *)**x, *incx, (cuDoubleComplex *)**beta, (cuDoubleComplex *)**y, *incy)); #endif } extern "C" void FC_FUNC_(cuda_blas_dsyrk, CUDA_BLAS_DSYRK)(cublasHandle_t **handle, fint *uplo, fint *trans, fint8 *n, fint8 *k, CUdeviceptr **alpha, CUdeviceptr **A, fint8 *lda, CUdeviceptr **beta, CUdeviceptr **C, fint8 *ldc) { #ifdef HAVE_CUDA CUBLAS_SAFE_CALL(cublasDsyrk(**handle, (cublasFillMode_t)*uplo, (cublasOperation_t)*trans, *n, *k, (double *)**alpha, (double *)**A, *lda, (double *)**beta, (double *)**C, *ldc)); #endif } extern "C" void FC_FUNC_(cuda_blas_zherk, CUDA_BLAS_ZHERK)(cublasHandle_t **handle, fint *uplo, fint *trans, fint8 *n, fint8 *k, CUdeviceptr **alpha, CUdeviceptr **A, fint8 *lda, CUdeviceptr **beta, CUdeviceptr **C, fint8 *ldc) { #ifdef HAVE_CUDA CUBLAS_SAFE_CALL(cublasZherk(**handle, (cublasFillMode_t)*uplo, (cublasOperation_t)*trans, *n, *k, (double *)**alpha, (cuDoubleComplex *)**A, *lda, (double *)**beta, (cuDoubleComplex *)**C, *ldc)); #endif } extern "C" void FC_FUNC_(cuda_blas_dtrsm, CUDA_BLAS_DTRSM)( cublasHandle_t **handle, fint *side, fint *uplo, fint *trans, fint *diag, fint8 *m, fint8 *n, CUdeviceptr **alpha, CUdeviceptr **A, fint8 *lda, CUdeviceptr **B, fint8 *ldb) { #ifdef HAVE_CUDA CUBLAS_SAFE_CALL( cublasDtrsm(**handle, (cublasSideMode_t)*side, (cublasFillMode_t)*uplo, (cublasOperation_t)*trans, (cublasDiagType_t)*diag, *m, *n, (double *)**alpha, (double *)**A, *lda, (double *)**B, *ldb)); #endif } extern "C" void FC_FUNC_(cuda_blas_ztrsm, CUDA_BLAS_ZTRSM)( cublasHandle_t **handle, fint *side, fint *uplo, fint *trans, fint *diag, fint8 *m, fint8 *n, CUdeviceptr **alpha, CUdeviceptr **A, fint8 *lda, CUdeviceptr **B, fint8 *ldb) { #ifdef HAVE_CUDA CUBLAS_SAFE_CALL( cublasZtrsm(**handle, (cublasSideMode_t)*side, (cublasFillMode_t)*uplo, (cublasOperation_t)*trans, (cublasDiagType_t)*diag, *m, *n, (cuDoubleComplex *)**alpha, (cuDoubleComplex *)**A, *lda, (cuDoubleComplex *)**B, *ldb)); #endif } extern "C" void FC_FUNC_(cublas_set_stream, CUBLAS_SET_STREAM)(cublasHandle_t **handle, cudaStream_t **stream) { #ifdef HAVE_CUDA CUBLAS_SAFE_CALL(cublasSetStream(**handle, **stream)); #endif }
0
ALLM/M3/octopus/src
ALLM/M3/octopus/src/basic/cuda_low.cc
/* Copyright (C) 2016 X. Andrade 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, 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #ifdef HAVE_CUDA #if defined(HAVE_HIP) #include <hip/hip_runtime.h> #include <hip/hip_runtime_api.h> #include <hip/hiprtc.h> // https://rocm.docs.amd.com/projects/HIPIFY/en/latest/tables/CUDA_Driver_API_functions_supported_by_HIP.html #define CUcontext hipCtx_t #define cuCtxCreate hipCtxCreate #define cuCtxDestroy hipCtxDestroy #define cuCtxSetCacheConfig hipCtxSetCacheConfig #define CUDA_ERROR_OUT_OF_MEMORY hipErrorOutOfMemory #define CUDA_SUCCESS hipSuccess #define CUdevice hipDevice_t #define CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MAJOR hipDeviceAttributeComputeCapabilityMajor #define CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MINOR hipDeviceAttributeComputeCapabilityMinor #define CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_X hipDeviceAttributeMaxBlockDimX #define CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_Y hipDeviceAttributeMaxBlockDimY #define CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_Z hipDeviceAttributeMaxBlockDimZ #define CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_X hipDeviceAttributeMaxGridDimX #define CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_Y hipDeviceAttributeMaxGridDimY #define CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_Z hipDeviceAttributeMaxGridDimZ #define CU_DEVICE_ATTRIBUTE_MAX_SHARED_MEMORY_PER_BLOCK hipDeviceAttributeMaxSharedMemoryPerBlock #define CU_DEVICE_ATTRIBUTE_MAX_THREADS_PER_BLOCK hipDeviceAttributeMaxThreadsPerBlock #define CU_DEVICE_ATTRIBUTE_WARP_SIZE hipDeviceAttributeWarpSize #define cuDeviceGet hipDeviceGet #define cuDeviceGetAttribute hipDeviceGetAttribute #define cuDeviceGetCount hipGetDeviceCount #define cuDeviceGetName hipDeviceGetName #define CUdeviceptr hipDeviceptr_t #define cuDeviceTotalMem hipDeviceTotalMem #define cuDriverGetVersion hipDriverGetVersion #define CU_FUNC_ATTRIBUTE_BINARY_VERSION HIP_FUNC_ATTRIBUTE_BINARY_VERSION #define CU_FUNC_ATTRIBUTE_MAX_THREADS_PER_BLOCK HIP_FUNC_ATTRIBUTE_MAX_THREADS_PER_BLOCK #define CU_FUNC_ATTRIBUTE_PTX_VERSION HIP_FUNC_ATTRIBUTE_PTX_VERSION #define CU_FUNC_CACHE_PREFER_L1 hipFuncCachePreferL1 #define cuFuncGetAttribute hipFuncGetAttribute #define CUfunction hipFunction_t #define cuGetErrorName hipDrvGetErrorName #define cuInit hipInit #ifdef __HIP_PLATFORM_AMD__ // these are missing from hip/nvidia_detail/nvidia_hip_runtime_api.h #define CU_JIT_ERROR_LOG_BUFFER hipJitOptionErrorLogBuffer #define CU_JIT_ERROR_LOG_BUFFER_SIZE_BYTES hipJitOptionErrorLogBufferSizeBytes #endif #define CUjit_option hipJitOption #define cuLaunchKernel hipModuleLaunchKernel #define cuMemAlloc hipMalloc #define cuMemcpyDtoHAsync hipMemcpyDtoHAsync #define cuMemcpyHtoDAsync hipMemcpyHtoDAsync #define cuMemFree hipFree #define CUmodule hipModule_t #define cuModuleGetFunction hipModuleGetFunction #define cuModuleLoadDataEx hipModuleLoadDataEx #define cuModuleUnload hipModuleUnload #define CUresult hipError_t #define CUstream hipStream_t #define cuStreamCreate hipStreamCreateWithFlags #define cuStreamDestroy hipStreamDestroy #define CU_STREAM_NON_BLOCKING hipStreamNonBlocking #define cuStreamSynchronize hipStreamSynchronize // https://rocm.docs.amd.com/projects/HIPIFY/en/latest/tables/CUDA_RTC_API_supported_by_HIP.html #define nvrtcCompileProgram hiprtcCompileProgram #define nvrtcCreateProgram hiprtcCreateProgram #define nvrtcDestroyProgram hiprtcDestroyProgram #define nvrtcGetErrorString hiprtcGetErrorString #define nvrtcGetProgramLog hiprtcGetProgramLog #define nvrtcGetProgramLogSize hiprtcGetProgramLogSize #define nvrtcGetPTX hiprtcGetCode #define nvrtcGetPTXSize hiprtcGetCodeSize #define nvrtcProgram hiprtcProgram #define nvrtcResult hiprtcResult #define NVRTC_SUCCESS HIPRTC_SUCCESS #else #include <cuda.h> #include <nvrtc.h> #endif // all kernels and transfers are submitted to this non-blocking stream // -> allows operations from libraries to overlap with this stream CUstream *phStream; int current_stream; static int number_streams = 32; #else #include <stdint.h> typedef intptr_t CUcontext; typedef intptr_t CUdevice; typedef intptr_t CUmodule; typedef intptr_t CUfunction; typedef intptr_t CUdeviceptr; typedef intptr_t CUstream; #endif #include <cmath> #include <stdlib.h> //we have to include this before cmath to workaround a bug in the PGI "compiler". #include <iostream> #include <fstream> #include "string_f.h" /* fortran <-> c string compatibility issues */ #include <cassert> #include <cstring> #include <iterator> #include <map> #include <sstream> #include <stdbool.h> #include <vector> #include <cstdlib> #include <regex> #include <fortran_types.h> #define NVRTC_SAFE_CALL(x) \ do { \ nvrtcResult result = x; \ if (result != NVRTC_SUCCESS) { \ std::cerr << "\nerror: " #x " failed with error " \ << nvrtcGetErrorString(result) << '\n'; \ exit(1); \ } \ } while (0) #define CUDA_SAFE_CALL(x) \ do { \ CUresult result = x; \ if (result != CUDA_SUCCESS) { \ const char *msg; \ cuGetErrorName(result, &msg); \ std::cerr << "\nerror: " #x " failed with error " << msg << '\n'; \ if (result == CUDA_ERROR_OUT_OF_MEMORY) { \ std::cerr << "Octopus could not allocate enough memory on the GPU.\n"; \ std::cerr \ << "Please use either more GPUs to distribute the memory or try " \ "StatesPack = no to keep the states mostly on the CPU.\n"; \ } \ exit(1); \ } \ } while (0) using namespace std; extern "C" void FC_FUNC_(cuda_init, CUDA_INIT)(CUcontext **context, CUdevice **device, CUstream **stream, fint *device_number, fint *rank) { #ifdef HAVE_CUDA CUDA_SAFE_CALL(cuInit(0)); *context = new CUcontext; *device = new CUdevice; int ndevices; CUDA_SAFE_CALL(cuDeviceGetCount(&ndevices)); if (ndevices == 0) { cerr << "Error: no CUDA devices available." << std::endl; exit(1); } const auto* group_count = std::getenv("CTEST_RESOURCE_GROUP_COUNT"); auto resource_group = std::vector<int>(); if (group_count != nullptr) { for (int i = 0; i < std::stoi(group_count); ++i) { std::stringstream env_name; env_name << "CTEST_RESOURCE_GROUP_" << i << "_GPUS"; const auto* rg_gpus = std::getenv(env_name.str().c_str()); if (rg_gpus == nullptr){ std::cerr << "CTEST_RESOURCE_GROUP " << i << "does not have _GPUS group" << std::endl; exit(1); } const auto re = std::regex("id:(\\d+),slots:(\\d+)"); const auto rg_gpus_string = std::string(rg_gpus); std::smatch match; if (!std::regex_match(rg_gpus_string, match, re)){ std::cerr << "Unexpected envrionment variable\n" << env_name.str() << " = " << rg_gpus << std::endl; exit(1); } assert(match.size() == 3); resource_group.emplace_back(std::stoi(match[1])); } assert(resource_group.size() == std::stoi(group_count)); } if (!resource_group.empty()){ *device_number = resource_group[*rank % resource_group.size()]; if (*device_number >= ndevices){ std::cerr << "Requested unsupported GPU: " << *device_number << "/" << ndevices << std::endl; exit(1); } } else { *device_number = (*device_number + *rank) % ndevices; } CUDA_SAFE_CALL(cuDeviceGet(*device, *device_number)); CUDA_SAFE_CALL(cuCtxCreate(*context, 0, **device)); #ifdef __HIP_PLATFORM_NVIDIA__ // bug in hip/nvidia_detail/nvidia_hip_runtime_api.h CUDA_SAFE_CALL(cuCtxSetCacheConfig(static_cast<CUfunc_cache>(CU_FUNC_CACHE_PREFER_L1))); #elif defined(__HIP_PLATFORM_AMD__) // hipErrorNotSupported #else CUDA_SAFE_CALL(cuCtxSetCacheConfig(CU_FUNC_CACHE_PREFER_L1)); #endif phStream = new CUstream[number_streams]; for (current_stream = 0; current_stream < number_streams; ++current_stream) { CUDA_SAFE_CALL( cuStreamCreate(&phStream[current_stream], CU_STREAM_NON_BLOCKING)); } current_stream = 0; *stream = &phStream[current_stream]; #endif } extern "C" void FC_FUNC_(cuda_end, CUDA_END)(CUcontext **context, CUdevice **device) { #ifdef HAVE_CUDA CUDA_SAFE_CALL(cuStreamDestroy(phStream[current_stream])); CUDA_SAFE_CALL(cuCtxDestroy(**context)); delete *context; delete *device; #endif } extern "C" void FC_FUNC_(cuda_module_map_init, CUDA_MODULES_MAP_INIT)(map<string, CUmodule *> **module_map) { *module_map = new map<string, CUmodule *>; } extern "C" void FC_FUNC_(cuda_module_map_end, CUDA_MODULES_MAP_END)(map<string, CUmodule *> **module_map) { for (map<string, CUmodule *>::iterator map_it = (**module_map).begin(); map_it != (**module_map).end(); ++map_it) { CUmodule *module = map_it->second; #ifdef HAVE_CUDA CUDA_SAFE_CALL(cuModuleUnload(*module)); #endif delete module; } delete *module_map; } extern "C" void FC_FUNC_(cuda_build_program, CUDA_BUILD_PROGRAM)( map<string, CUmodule *> **module_map, CUmodule **module, CUdevice **device, STR_F_TYPE const fname, STR_F_TYPE const flags STR_ARG2) { #ifdef HAVE_CUDA char *fname_c; char *flags_c; TO_C_STR1(fname, fname_c); TO_C_STR2(flags, flags_c); string map_descriptor = string(fname_c) + string(flags_c); map<string, CUmodule *>::iterator map_it = (**module_map).find(map_descriptor); if (map_it != (**module_map).end()) { *module = map_it->second; free(fname_c); return; } // read the source string source; source = "#include \"" + string(fname_c) + "\"\n"; // cout << source << "|" << endl; nvrtcProgram prog; NVRTC_SAFE_CALL(nvrtcCreateProgram(&prog, source.c_str(), "kernel_include.c", 0, NULL, NULL)); int major = 0, minor = 0; CUDA_SAFE_CALL(cuDeviceGetAttribute( &major, CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MAJOR, **device)); CUDA_SAFE_CALL(cuDeviceGetAttribute( &minor, CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MINOR, **device)); char compute_version[3]; sprintf(compute_version, "%.1d%.1d", major, minor); string all_flags = #ifdef HAVE_HIP " -O3 -fcuda-flush-denormals-to-zero -ffp-contract=fast -DCUDA " + #else "--gpu-architecture=compute_" + string(compute_version) + " --ftz=true --fmad=true -DCUDA -default-device " + #endif string(flags_c); stringstream flags_stream(all_flags); istream_iterator<string> iter(flags_stream); istream_iterator<string> end; vector<string> tokens(iter, end); const char **opts = new const char *[tokens.size()]; for (unsigned ii = 0; ii < tokens.size(); ii++) opts[ii] = tokens[ii].c_str(); nvrtcResult err = nvrtcCompileProgram(prog, tokens.size(), opts); free(flags_c); size_t logSize; NVRTC_SAFE_CALL(nvrtcGetProgramLogSize(prog, &logSize)); char *log = new char[logSize]; NVRTC_SAFE_CALL(nvrtcGetProgramLog(prog, log)); if (logSize > 1) { cout << "Cuda compilation messages" << endl; cout << "File : " << fname_c << endl; cout << "Options : " << all_flags << endl; cout << log << endl; } if (NVRTC_SUCCESS != err) { cerr << "Error in compiling" << endl; exit(1); } delete[] log; delete[] opts; // Obtain PTX from the program. size_t ptxSize; NVRTC_SAFE_CALL(nvrtcGetPTXSize(prog, &ptxSize)); char *ptx = new char[ptxSize]; NVRTC_SAFE_CALL(nvrtcGetPTX(prog, ptx)); NVRTC_SAFE_CALL(nvrtcDestroyProgram(&prog)); *module = new CUmodule; const int num_options = 2; CUjit_option options[num_options]; void *option_values[num_options]; unsigned log_size = 4096; char log_buffer[log_size]; options[0] = CU_JIT_ERROR_LOG_BUFFER_SIZE_BYTES; option_values[0] = (void *)(long)log_size; options[1] = CU_JIT_ERROR_LOG_BUFFER; option_values[1] = (void *)log_buffer; CUresult result = cuModuleLoadDataEx(*module, ptx, num_options, options, option_values); if (result != CUDA_SUCCESS) { std::cerr << log_buffer << std::endl; const char *msg; cuGetErrorName(result, &msg); std::cerr << "\nerror: cuModuleLoadDataEx failed with error " << msg << '\n'; exit(1); } delete[] ptx; (**module_map)[map_descriptor] = *module; free(fname_c); #endif } extern "C" void FC_FUNC_(cuda_create_kernel, CUDA_CREATE_KERNEL)(CUfunction **kernel, CUmodule **module, STR_F_TYPE kernel_name STR_ARG1) { #ifdef HAVE_CUDA char *kernel_name_c; TO_C_STR1(kernel_name, kernel_name_c); *kernel = new CUfunction; CUDA_SAFE_CALL(cuModuleGetFunction(*kernel, **module, kernel_name_c)); free(kernel_name_c); #endif } extern "C" void FC_FUNC_(cuda_release_module, CUDA_RELEASE_MODULE)(CUmodule **module) { #ifdef HAVE_CUDA CUDA_SAFE_CALL(cuModuleUnload(**module)); delete *module; #endif } extern "C" void FC_FUNC_(cuda_release_kernel, CUDA_RELEASE_KERNEL)(CUfunction **kernel) { #ifdef HAVE_CUDA delete *kernel; #endif } extern "C" void FC_FUNC_(cuda_device_max_threads_per_block, CUDA_DEVICE_MAX_THREADS_PER_BLOCK)(CUdevice **device, fint *max_threads) { #ifdef HAVE_CUDA int value; CUDA_SAFE_CALL(cuDeviceGetAttribute( &value, CU_DEVICE_ATTRIBUTE_MAX_THREADS_PER_BLOCK, **device)); *max_threads = value; #endif } extern "C" void FC_FUNC_(cuda_kernel_max_threads_per_block, CUDA_KERNEL_MAX_THREADS_PER_BLOCK)(CUfunction **kernel, fint *max_threads) { #ifdef HAVE_CUDA int value; CUDA_SAFE_CALL(cuFuncGetAttribute(&value, CU_FUNC_ATTRIBUTE_MAX_THREADS_PER_BLOCK, **kernel)); *max_threads = value; #endif } extern "C" void FC_FUNC_(cuda_device_max_block_dim_x, CUDA_DEVICE_MAX_BLOCK_DIM_X)(CUdevice **device, fint *max_dim) { #ifdef HAVE_CUDA int value; CUDA_SAFE_CALL(cuDeviceGetAttribute( &value, CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_X, **device)); *max_dim = value; #endif } extern "C" void FC_FUNC_(cuda_device_max_block_dim_y, CUDA_DEVICE_MAX_BLOCK_DIM_Y)(CUdevice **device, fint *max_dim) { #ifdef HAVE_CUDA int value; CUDA_SAFE_CALL(cuDeviceGetAttribute( &value, CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_Y, **device)); *max_dim = value; #endif } extern "C" void FC_FUNC_(cuda_device_max_block_dim_z, CUDA_DEVICE_MAX_BLOCK_DIM_Z)(CUdevice **device, fint *max_dim) { #ifdef HAVE_CUDA int value; CUDA_SAFE_CALL(cuDeviceGetAttribute( &value, CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_Z, **device)); *max_dim = value; #endif } extern "C" void FC_FUNC_(cuda_device_max_grid_dim_x, CUDA_DEVICE_MAX_GRID_DIM_X)(CUdevice **device, fint *max_dim) { #ifdef HAVE_CUDA int value; CUDA_SAFE_CALL(cuDeviceGetAttribute( &value, CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_X, **device)); *max_dim = value; #endif } extern "C" void FC_FUNC_(cuda_device_max_grid_dim_y, CUDA_DEVICE_MAX_GRID_DIM_Y)(CUdevice **device, fint *max_dim) { #ifdef HAVE_CUDA int value; CUDA_SAFE_CALL(cuDeviceGetAttribute( &value, CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_Y, **device)); *max_dim = value; #endif } extern "C" void FC_FUNC_(cuda_device_max_grid_dim_z, CUDA_DEVICE_MAX_GRID_DIM_Z)(CUdevice **device, fint *max_dim) { #ifdef HAVE_CUDA int value; CUDA_SAFE_CALL(cuDeviceGetAttribute( &value, CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_Z, **device)); *max_dim = value; #endif } extern "C" void FC_FUNC_(cuda_device_total_memory, CUDA_DEVICE_TOTAL_MEMORY)(CUdevice **device, fint8 *total_memory) { #ifdef HAVE_CUDA size_t mem; CUDA_SAFE_CALL(cuDeviceTotalMem(&mem, **device)); *total_memory = mem; #endif } extern "C" void FC_FUNC_(cuda_device_shared_memory, CUDA_DEVICE_SHARED_MEMORY)(CUdevice **device, fint8 *shared_memory) { #ifdef HAVE_CUDA int mem; CUDA_SAFE_CALL(cuDeviceGetAttribute( &mem, CU_DEVICE_ATTRIBUTE_MAX_SHARED_MEMORY_PER_BLOCK, **device)); *shared_memory = mem; #endif } extern "C" void FC_FUNC_(cuda_mem_alloc, CUDA_MEM_ALLOC)(CUdeviceptr **cuda_ptr, const fint8 *size) { #ifdef HAVE_CUDA *cuda_ptr = new CUdeviceptr; #ifdef __HIP_PLATFORM_NVIDIA__ // bug in hip/nvidia_detail/nvidia_hip_runtime_api.h CUDA_SAFE_CALL(cuMemAlloc(reinterpret_cast<void**>(*cuda_ptr), *size)); #else CUDA_SAFE_CALL(cuMemAlloc(*cuda_ptr, *size)); #endif #endif } extern "C" void FC_FUNC_(cuda_mem_free, CUDA_MEM_FREE)(CUdeviceptr **cuda_ptr) { #ifdef HAVE_CUDA #ifdef __HIP_PLATFORM_NVIDIA__ // bug in hip/nvidia_detail/nvidia_hip_runtime_api.h CUDA_SAFE_CALL(cuMemFree(reinterpret_cast<void*>(**cuda_ptr))); #else CUDA_SAFE_CALL(cuMemFree(**cuda_ptr)); #endif delete *cuda_ptr; #endif } extern "C" void FC_FUNC_(cuda_memcpy_htod, CUDA_MEMCPY_HTOD)(CUdeviceptr **cuda_ptr, /* const */ void **data, fint8 *size, // https://github.com/ROCm/HIP/issues/3444 fint8 *offset) { #ifdef HAVE_CUDA CUDA_SAFE_CALL(cuMemcpyHtoDAsync(**cuda_ptr + *offset, *data, *size, phStream[current_stream])); #endif } extern "C" void FC_FUNC_(cuda_memcpy_dtoh, CUDA_MEMCPY_DTOH)(CUdeviceptr **cuda_ptr, void **data, fint8 *size, fint8 *offset) { #ifdef HAVE_CUDA CUDA_SAFE_CALL(cuMemcpyDtoHAsync(*data, **cuda_ptr + *offset, *size, phStream[current_stream])); #endif } extern "C" void FC_FUNC_(cuda_alloc_arg_array, CUDA_ALLOC_ARG_ARRAY)(vector<void *> **arg_array) { *arg_array = new vector<void *>; } extern "C" void FC_FUNC_(cuda_free_arg_array, CUDA_FREE_ARG_ARRAY)(vector<void *> **arg_array) { for (unsigned ii = 0; ii < (**arg_array).size(); ii++) free((**arg_array)[ii]); delete *arg_array; } extern "C" void FC_FUNC_(cuda_kernel_set_arg_buffer, CUDA_KERNEL_SET_ARG_BUFFER)(vector<void *> **arg_array, CUdeviceptr **cuda_ptr, fint *arg_index) { if (unsigned(*arg_index) >= (**arg_array).size()) (**arg_array).resize(*arg_index + 1, NULL); if ((**arg_array)[*arg_index] == NULL) (**arg_array)[*arg_index] = malloc(sizeof(CUdeviceptr)); memcpy((**arg_array)[*arg_index], *cuda_ptr, sizeof(CUdeviceptr)); } extern "C" void FC_FUNC_(cuda_kernel_set_arg_value, CUDA_KERNEL_SET_ARG_VALUE)(vector<void *> **arg_array, void **arg, fint *arg_index, fint *size) { if (unsigned(*arg_index) >= (**arg_array).size()) (**arg_array).resize(*arg_index + 1, NULL); if ((**arg_array)[*arg_index] == NULL) (**arg_array)[*arg_index] = malloc(*size); memcpy((**arg_array)[*arg_index], *arg, *size); } extern "C" void FC_FUNC_(cuda_context_synchronize, CUDA_CONTEXT_SYNCHRONIZE)() { #ifdef HAVE_CUDA CUDA_SAFE_CALL(cuStreamSynchronize(phStream[current_stream])); #endif } extern "C" void FC_FUNC_(cuda_synchronize_all_streams, CUDA_SYNCHRONIZE_ALL_STREAMS)() { #ifdef HAVE_CUDA for (int i = 0; i < number_streams; ++i) CUDA_SAFE_CALL(cuStreamSynchronize(phStream[i])); #endif } extern "C" void FC_FUNC_(cuda_launch_kernel, CUDA_LAUNCH_KERNEL)(CUfunction **kernel, fint8 *griddim, fint8 *blockdim, fint8 *shared_mem, vector<void *> **arg_array) { #ifdef HAVE_CUDA /* cout << "Kernel call" << endl; int nn; CUDA_SAFE_CALL(cuFuncGetAttribute(&nn, CU_FUNC_ATTRIBUTE_MAX_THREADS_PER_BLOCK, **kernel)); cout << "SIZE " << nn << endl; CUDA_SAFE_CALL(cuFuncGetAttribute(&nn, CU_FUNC_ATTRIBUTE_PTX_VERSION, **kernel)); cout << "PTX " << nn << endl; CUDA_SAFE_CALL(cuFuncGetAttribute(&nn, CU_FUNC_ATTRIBUTE_BINARY_VERSION, **kernel)); cout << "BINARY " << nn << endl; for(unsigned ii = 0; ii < (**arg_array).size(); ii++) cout << ii << " " << (**arg_array)[ii] << endl; cout << "GRID " << griddim[0] << " " << griddim[1] << " " << griddim[2] << endl; cout << "BLOCK " << blockdim[0] << " " << blockdim[1] << " " << blockdim[2] << endl; cout << "SHARED MEMORY " << *shared_mem << endl; */ assert((**arg_array).size() > 0); for (unsigned ii = 0; ii < (**arg_array).size(); ii++) assert((**arg_array)[ii] != NULL); CUDA_SAFE_CALL(cuLaunchKernel(**kernel, griddim[0], griddim[1], griddim[2], blockdim[0], blockdim[1], blockdim[2], *shared_mem, phStream[current_stream], &(**arg_array)[0], NULL)); // release the stored argument, this is not necessary in principle, // but it should help us to detect missing arguments. for (unsigned ii = 0; ii < (**arg_array).size(); ii++) free((**arg_array)[ii]); (**arg_array).resize(0); #endif } extern "C" void FC_FUNC_(cuda_device_name, CUDA_DEVICE_NAME)(CUdevice **device, STR_F_TYPE name STR_ARG1) { #ifdef HAVE_CUDA char devicename[200]; CUDA_SAFE_CALL(cuDeviceGetName(devicename, sizeof(devicename), **device)); TO_F_STR1(devicename, name); #endif } extern "C" void FC_FUNC_(cuda_device_capability, CUDA_DEVICE_CAPABILITY)(CUdevice **device, fint *major, fint *minor) { #ifdef HAVE_CUDA int cmajor = 0, cminor = 0; CUDA_SAFE_CALL(cuDeviceGetAttribute( &cmajor, CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MAJOR, **device)); CUDA_SAFE_CALL(cuDeviceGetAttribute( &cminor, CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MINOR, **device)); *major = cmajor; *minor = cminor; #endif } extern "C" void FC_FUNC_(cuda_driver_version, CUDA_DRIVER_VERSION)(fint *version) { #ifdef HAVE_CUDA int driverversion; CUDA_SAFE_CALL(cuDriverGetVersion(&driverversion)); *version = driverversion; #endif } extern "C" void FC_FUNC_(cuda_device_get_warpsize, CUDA_DEVICE_GET_WARPSIZE)(CUdevice **device, fint *warpSize) { #ifdef HAVE_CUDA int cwarpSize = 0; CUDA_SAFE_CALL(cuDeviceGetAttribute(&cwarpSize, CU_DEVICE_ATTRIBUTE_WARP_SIZE, **device)); *warpSize = cwarpSize; #endif } extern "C" void FC_FUNC_(cuda_deref, CUDA_DEREF)(CUdeviceptr **cuda_ptr, void **cuda_deref_ptr) { #ifdef HAVE_CUDA *cuda_deref_ptr = (void *)**cuda_ptr; #endif } extern "C" void FC_FUNC_(cuda_set_stream, CUDA_SET_STREAM)(CUstream **stream, fint *number) { #ifdef HAVE_CUDA current_stream = (*number - 1) % number_streams; *stream = &phStream[current_stream]; #endif } extern "C" void FC_FUNC_(cuda_get_stream, CUDA_GET_STREAM)(fint *number) { #ifdef HAVE_CUDA *number = current_stream + 1; #endif } extern "C" void FC_FUNC_(cuda_get_pointer_with_offset, CUDA_GET_POINTER_WITH_OFFSET)(CUdeviceptr **buffer, fint8 *offset, CUdeviceptr **buffer_offset) { *buffer_offset = new CUdeviceptr; **buffer_offset = (CUdeviceptr)((double *)**buffer + (ptrdiff_t)*offset); } extern "C" void FC_FUNC_(cuda_clean_pointer, CUDA_CLEAN_POINTER)(CUdeviceptr **buffer) { delete *buffer; }
0
ALLM/M3/octopus/src
ALLM/M3/octopus/src/basic/gdlib_f.c
/* Copyright (C) 2002-2006 the octopus team 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, 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #ifdef HAVE_GDLIB #include <assert.h> #include <ctype.h> #include <gd.h> #include <string.h> /* ---------------------- Interface to GD functions ------------------------ */ gdImagePtr gdlib_image_create_from(char *name) { char *ext; FILE *in; gdImagePtr im; if ((in = fopen(name, "rb")) == NULL) { return NULL; /* could not open file */ } /* get extension of filename */ for (ext = name + strlen(name); *ext != '.' && ext >= name; ext--) { *ext = tolower(*ext); } if (ext < name || ext == name + strlen(name)) { fclose(in); return NULL; /* could not find file type */ } /* get rid of . in extension */ ext++; /* load image file */ im = NULL; #ifdef HAVE_GD_JPEG if ((strcmp(ext, "jpg") == 0) || (strcmp(ext, "JPG") == 0) || (strcmp(ext, "jpeg") == 0) || (strcmp(ext, "JPEG") == 0)) im = gdImageCreateFromJpeg(in); #endif #ifdef HAVE_GD_PNG if ((strcmp(ext, "png") == 0) || (strcmp(ext, "PNG") == 0)) im = gdImageCreateFromPng(in); #endif #ifdef HAVE_GD_GIF if ((strcmp(ext, "gif") == 0) || (strcmp(ext, "GIF") == 0)) im = gdImageCreateFromGif(in); #endif fclose(in); return im; } int gdlib_image_sx(const gdImagePtr *im) { assert(*im != NULL); return gdImageSX(*im); } int gdlib_image_sy(const gdImagePtr *im) { assert(*im != NULL); return gdImageSY(*im); } void gdlib_image_get_pixel_rgb(const gdImagePtr *im, const int *x, const int *y, int *r, int *g, int *b) { int color; assert(*im != NULL); if (gdImageBoundsSafe(*im, *x, *y)) { color = gdImageGetPixel(*im, *x, *y); *r = gdImageRed(*im, color); *g = gdImageGreen(*im, color); *b = gdImageBlue(*im, color); } else { /* this will happen for boundary points */ // fprintf(stderr, "Illegal pixel coordinate %d %d\n", *x, *y); *r = 0; *g = 0; *b = 0; } } #else /* this is to avoid an empty source file (not allowed by ANSI C)*/ void useless() {} #endif /* defined HAVEGDLIB */
0
ALLM/M3/octopus/src
ALLM/M3/octopus/src/basic/getopt_f.c
/* Copyright (C) 2002 M. Marques, A. Castro, A. Rubio, G. Bertsch 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, 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <stdio.h> #include <stdlib.h> #include <getopt.h> #include "string_f.h" /* Fortran <-> c string compatibility issues */ #include <string.h> #if __has_include(<unistd.h>) #include <unistd.h> #endif // Below we check whether _POSIX_VERSION is defined to decide whether we can use // getopt_long. This is not entirely correct, becaues getopt_long is a GNU // extension which is not mandated by POSIX. However, most relevant major // UNIX-like operating systems that define _POSIX_VERSION also have getopt_long // in their standard C library. The list below is incomplete. // // Support is present in: Support is absent in: // // - Linux with both glibc and musl - HP-UX // - macOS - AIX // - FreeBSD, NetBSD, OpenBSD // - Solaris #if defined(_POSIX_VERSION) && !defined(__hpux) && !defined(_AIX) #define HAVE_GETOPT_LONG 1 #endif /* GENERAL FUNCTIONS AND VARIABLES */ char **argv; int argc; void FC_FUNC_(set_number_clarg, SET_NUMBER_CLP)(int *nargc) { argc = *nargc + 1; argv = (char **)malloc(argc * sizeof(char *)); } void FC_FUNC_(set_clarg, SET_CLARG)(int *i, STR_F_TYPE arg STR_ARG1) { char *c; TO_C_STR1(arg, c) argv[*i] = c; } void FC_FUNC_(clean_clarg, CLEAR_CLARG)() { int i; for (i = 0; i < argc; i++) free(argv[i]); free(argv); } /* FUNCTIONS TO BE USED BY THE PROGRAM oct-oscillator-strength */ void oscillator_strength_help() { printf("Usage: oct-oscillator-strength [OPTIONS] [w]\n"); printf("\n"); printf("Options:\n"); printf(" -h Prints this help and exits.\n"); printf(" -m <mode> Select the run mode:\n"); printf(" 1 (default) analyzes the signal present in an " "'ot' file.\n"); printf(" This should have been generated by this same " "utility\n"); printf(" (run mode 2).\n"); printf(" 2 Reads a number of 'multipoles' files, which " "should be\n"); printf(" present in the working directory, and be " "called\n"); printf(" 'multipoles.1', 'multipoles.2', ..., and " "generate an 'ot'\n"); printf(" file with the k-th order response of a given " "operator O.\n"); printf(" The order k is decided by the '-k' option. The " "operator\n"); printf(" is decided by the '-O' option.\n"); printf(" 3 Peforms an analysis of the second-order " "response of an\n"); printf(" operator O, present in the working directory, " "and\n"); printf(" previously generated with run mode 2. It also " "reads a\n"); printf(" file with a list of frequecies around which " "the search\n"); printf(" for resonances is performed.\n"); printf(" 4 Reads an 'ot' file, and generates an 'omega' " "file with\n"); printf(" either the sine or cosine Fourier transform of " "the\n"); printf(" signal present in 'ot'.\n"); printf(" -O <operator> Selects the operator to be analyzed:\n"); printf(" o If <operator> is a pair of integers in the " "form '(l,m)'\n"); printf( " then the operator will be the (l,m) multipole.\n"); printf(" o If <operator> is x, y, or z, then the response " "operator\n"); printf(" to be analyzed will be the dipole in the given " "direction.\n"); printf(" o If the -O option is not given in the command " "line, then\n"); printf(" the observation operator O will be the same as " "the\n"); printf(" perturbation operator that defines the initial " "kick.\n"); printf(" -f <file> This is the file where the frequencies needed in " "run mode\n"); printf(" 3 are stored.\n"); printf(" -d <gamma> gamma is the damping factor used in the SOS " "formulae that\n"); printf(" produce (hyper)-polarizabilities.\n"); printf(" -s <dw> Limits of the search interval: [w-dw,w+dw]\n"); printf(" -r <r> Number of resonances to search for.\n"); printf( " -n <N> Number of frequencies in which the search interval\n"); printf(" is discretized (default 1000)\n"); printf(" -k <k> Process, or generate, the k-th order response.\n"); printf(" -t <time> The signal analysis will be done by integrating in " "the \n"); printf(" time interval [0, <time>]. If this argument is " "absent,\n"); printf(" it makes use of all the time-window present in " "the\n"); printf(" multipoles files.\n"); exit(-1); } void FC_FUNC_(getopt_oscillator_strength, GETOPT_OSCILLATOR_STRENGTH)( int *mode, double *omega, double *searchinterval, int *order, int *nresonances, int *nfrequencies, double *time, int *l, int *m, double *damping, STR_F_TYPE ffile STR_ARG1) { int c; /* This line would be present if we wanted to make the omega a mandatory argument. But for the moment I think it should not be mandatory. if(argc==1) oscillator_strength_help(); */ while (1) { c = getopt(argc, argv, "hm:s:k:O:r:n:t:d:f:"); if (c == -1) break; switch (c) { case 'h': oscillator_strength_help(); break; case 'm': *mode = (int)atoi(optarg); break; case 's': *searchinterval = (double)atof(optarg); break; case 'O': c = sscanf(optarg, "(%d,%d)", l, m); if (c != 2) { switch (optarg[0]) { case 'x': *l = 0; *m = 1; break; case 'y': *l = 0; *m = 2; break; case 'z': *l = 0; *m = 3; break; default: printf("Problem reading the -O option value.\n\n"); oscillator_strength_help(); } } break; case 'k': *order = (int)atoi(optarg); break; case 'r': *nresonances = (int)atoi(optarg); break; case 'n': *nfrequencies = (int)atoi(optarg); break; case 't': *time = (double)atof(optarg); break; case 'f': TO_F_STR1(optarg, ffile); break; case 'd': *damping = (double)atof(optarg); break; case '?': oscillator_strength_help(); break; } } if (optind < argc) { while (optind < argc) *omega = (double)atof(argv[optind++]); } } /***************************************************************/ /* FUNCTIONS TO BE USED BY THE PROGRAM oct-harmonic-spectrum */ void harmonic_spectrum_help() { printf("Usage: oct-harmonic-spectrum [OPTIONS] \n"); printf("\n"); printf("Options:\n"); printf(" -h, --help Prints this help and exits.\n"); printf(" -v, --version Prints octopus version.\n"); printf(" -w, --freq=freq Specifies the fundamental frequency.\n"); printf( " -p, --pol=pol Specifies the direction of the light polarization.\n"); printf(" The oct-harmonic-spectrum utility program needs to " "know\n"); printf(" the direction along which the emission radiation " "is\n"); printf(" considered to be polarized. It may be linearly " "polarized\n"); printf(" or circularly polarized. The valid options are:\n"); printf(" 'x' : Linearly polarized field in the x " "direction.\n"); printf(" 'y' : Linearly polarized field in the x " "direction.\n"); printf(" 'z' : Linearly polarized field in the x " "direction.\n"); printf(" '+' : Circularly polarized field, " "counterclockwise.\n"); printf(" '-' : Circularly polarized field, clockwise.\n"); printf(" 'v' : Along a direction specified by -x X -y Y " "-z Z.\n"); printf(" The default is 'x'\n"); printf(" -a, --ar Calculates the angle-resolved harmonic-spectrum " "along a\n"); printf( " direction (X,Y,Z) specified by by -x X -y Y -z Z.\n"); printf(" -m, --mode=mode Whether the harmonic spectrum is computed by " "taking the\n"); printf(" second derivative of the dipole moment " "numerically, the \n"); printf(" the time derivative of the current, or by making " "use of \n:"); printf(" the dipole acceleration.\n"); printf(" ' The options are:\n"); printf(" '1' : use the dipole, take second derivative " "numerically.\n"); printf(" '2' : use the acceleration file.\n"); printf(" '3' : use the total current file.\n"); printf(" The default is '1'\n"); exit(-1); } void FC_FUNC_(getopt_harmonic_spectrum, GETOPT_HARMONIC_SPECTRUM)(double *w0, int *m, int *ar, double *x, double *y, double *z, STR_F_TYPE pol STR_ARG1) { int c; #if defined(HAVE_GETOPT_LONG) static struct option long_options[] = { {"help", no_argument, 0, 'h'}, {"version", no_argument, 0, 'v'}, {"freq", required_argument, 0, 'w'}, {"pol", required_argument, 0, 'p'}, {"mode", required_argument, 0, 'm'}, {"ar", required_argument, 0, 'a'}, {"x", required_argument, 0, 'x'}, {"y", required_argument, 0, 'y'}, {"z", required_argument, 0, 'z'}, {0, 0, 0, 0}}; #endif while (1) { int option_index = 0; #if defined(HAVE_GETOPT_LONG) c = getopt_long(argc, argv, "hvw:p:m:x:y:z:a", long_options, &option_index); #else c = getopt(argc, argv, "hvw:p:m:x:y:z:a"); #endif if (c == -1) break; switch (c) { case 'h': harmonic_spectrum_help(); break; case 'v': printf("octopus %s (git commit %s)\n", PACKAGE_VERSION, GIT_COMMIT); exit(0); case 'w': *w0 = (double)atof(optarg); break; case 'p': TO_F_STR1(optarg, pol); break; case 'm': *m = (int)atoi(optarg); break; case 'a': *ar = 1; break; case 'x': *x = (double)atof(optarg); break; case 'y': *y = (double)atof(optarg); break; case 'z': *z = (double)atof(optarg); break; } } } /***************************************************************/ /* FUNCTIONS TO BE USED BY THE PROGRAM oct-help */ void help_help() { printf("Usage: oct-help [options] \n"); printf("\n"); printf("Options:\n"); printf(" -h, --help Prints this help and exits.\n"); printf(" -v, --version Prints octopus version.\n"); printf(" -s, --search=STRING Search variables whose names contain string " "'STRING'.\n"); printf(" -p, --print=VARNAME Prints description of variable 'VARNAME'.\n"); exit(-1); } void FC_FUNC_(getopt_help, GETOPT_HELP)(STR_F_TYPE mode, STR_F_TYPE name STR_ARG2) { int c; #if defined(HAVE_GETOPT_LONG) static struct option long_options[] = {{"help", no_argument, 0, 'h'}, {"version", no_argument, 0, 'v'}, {"list", no_argument, 0, 'l'}, {"search", required_argument, 0, 's'}, {"print", required_argument, 0, 'p'}, {0, 0, 0, 0}}; #endif while (1) { int option_index = 0; #if defined(HAVE_GETOPT_LONG) c = getopt_long(argc, argv, "hvls:p:", long_options, &option_index); #else c = getopt(argc, argv, "hvls:p:"); #endif if (argc == 1) help_help(); if (c == -1) break; switch (c) { case 'h': help_help(); break; case 'v': printf("octopus %s (git commit %s)\n", PACKAGE_VERSION, GIT_COMMIT); exit(0); case 'l': TO_F_STR1("list", mode); return; case 's': TO_F_STR1("search", mode); TO_F_STR2(optarg, name); return; case 'p': TO_F_STR1("print", mode); TO_F_STR2(optarg, name); return; } } if (optind < argc) help_help(); } /***************************************************************/ /* FUNCTIONS TO BE USED BY THE PROGRAM octopus */ void octopus_help() { printf("Usage: octopus [options] \n"); printf("\n"); printf("Options:\n"); printf(" -h, --help Prints this help and exits.\n"); printf(" -v, --version Prints octopus version.\n"); printf(" -c, --config Prints compilation configuration options.\n"); exit(-1); } void FC_FUNC_(getopt_octopus, GETOPT_OCTOPUS)(STR_F_TYPE config_str STR_ARG1) { int c; char *config_str_c; #if defined(HAVE_GETOPT_LONG) static struct option long_options[] = {{"help", no_argument, 0, 'h'}, {"version", no_argument, 0, 'v'}, {"config", no_argument, 0, 'c'}, {0, 0, 0, 0}}; #endif while (1) { int option_index = 0; #if defined(HAVE_GETOPT_LONG) c = getopt_long(argc, argv, "hvc", long_options, &option_index); #else c = getopt(argc, argv, "hvc"); #endif if (c == -1) break; switch (c) { case 'h': octopus_help(); break; case 'v': printf("octopus %s (git commit %s)\n", PACKAGE_VERSION, GIT_COMMIT); exit(0); break; case 'c': TO_C_STR1(config_str, config_str_c); printf("%s\n", config_str_c); free(config_str_c); exit(0); break; } } if (optind < argc) octopus_help(); } /***************************************************************/ /* FUNCTIONS TO BE USED BY THE PROGRAM oct-casida_spectrum */ void casida_spectrum_help() { printf("Usage: oct-casida_spectrum [options] \n"); printf("\n"); printf("Options:\n"); printf(" -h, --help Prints this help and exits.\n"); printf(" -v, --version Prints octopus version.\n"); exit(-1); } void FC_FUNC_(getopt_casida_spectrum, GETOPT_CASIDA_SPECTRUM)() { int c; #if defined(HAVE_GETOPT_LONG) static struct option long_options[] = {{"help", no_argument, 0, 'h'}, {"version", no_argument, 0, 'v'}, {0, 0, 0, 0}}; #endif while (1) { int option_index = 0; #if defined(HAVE_GETOPT_LONG) c = getopt_long(argc, argv, "hv", long_options, &option_index); #else c = getopt(argc, argv, "hv"); #endif if (c == -1) break; switch (c) { case 'h': casida_spectrum_help(); break; case 'v': printf("octopus %s (git commit %s)\n", PACKAGE_VERSION, GIT_COMMIT); exit(0); } } if (optind < argc) casida_spectrum_help(); } /***************************************************************/ /* FUNCTIONS TO BE USED BY THE PROGRAM oct-center-geom */ void center_geom_help() { printf("Usage: oct-center-geom [options] \n"); printf("\n"); printf("Options:\n"); printf(" -h, --help Prints this help and exits.\n"); printf(" -v, --version Prints octopus version.\n"); exit(-1); } void FC_FUNC_(getopt_center_geom, GETOPT_CENTER_GEOM)() { int c; #if defined(HAVE_GETOPT_LONG) static struct option long_options[] = {{"help", no_argument, 0, 'h'}, {"version", no_argument, 0, 'v'}, {0, 0, 0, 0}}; #endif while (1) { int option_index = 0; #if defined(HAVE_GETOPT_LONG) c = getopt_long(argc, argv, "hv", long_options, &option_index); #else c = getopt(argc, argv, "hv"); #endif if (c == -1) break; switch (c) { case 'h': center_geom_help(); break; case 'v': printf("octopus %s (git commit %s)\n", PACKAGE_VERSION, GIT_COMMIT); exit(0); } } if (optind < argc) center_geom_help(); } /***************************************************************/ /* FUNCTIONS TO BE USED BY THE PROGRAM oct-center-geom */ void dielectric_function_help() { printf("Usage: oct-dielectric-function [options] \n"); printf("\n"); printf("Options:\n"); printf(" -h, --help Prints this help and exits.\n"); printf(" -v, --version Prints octopus version.\n"); exit(-1); } void FC_FUNC_(getopt_dielectric_function, GETOPT_DIELECTRIC_FUNCTION)() { int c; #if defined(HAVE_GETOPT_LONG) static struct option long_options[] = {{"help", no_argument, 0, 'h'}, {"version", no_argument, 0, 'v'}, {0, 0, 0, 0}}; #endif while (1) { int option_index = 0; #if defined(HAVE_GETOPT_LONG) c = getopt_long(argc, argv, "hv", long_options, &option_index); #else c = getopt(argc, argv, "hv"); #endif if (c == -1) break; switch (c) { case 'h': dielectric_function_help(); break; case 'v': printf("octopus %s (git commit %s)\n", PACKAGE_VERSION, GIT_COMMIT); exit(0); } } if (optind < argc) dielectric_function_help(); } /***************************************************************/ /* FUNCTIONS TO BE USED BY THE PROGRAM oct-propagation_spectrum */ void propagation_spectrum_help() { printf("Usage: oct-propagation_spectrum [options] \n"); printf("\n"); printf("Options:\n"); printf(" -h, --help Prints this help and exits.\n"); printf(" -v, --version Prints octopus version.\n"); printf(" -r, --reference REF REF should be the name of the 'reference' " "multipoles file,.\n"); printf(" whenever you want to do a time-dependent " "response function.\n"); printf(" calculation.\n"); exit(-1); } void FC_FUNC_(getopt_propagation_spectrum, GETOPT_PROPAGATION_SPECTRUM)(STR_F_TYPE fname STR_ARG1) { int c; #if defined(HAVE_GETOPT_LONG) static struct option long_options[] = { {"help", no_argument, 0, 'h'}, {"version", no_argument, 0, 'v'}, {"reference", required_argument, 0, 'r'}, {0, 0, 0, 0}}; #endif while (1) { int option_index = 0; #if defined(HAVE_GETOPT_LONG) c = getopt_long(argc, argv, "hvr:", long_options, &option_index); #else c = getopt(argc, argv, "hvr:"); #endif if (c == -1) break; switch (c) { case 'h': propagation_spectrum_help(); break; case 'v': printf("octopus %s (git commit %s)\n", PACKAGE_VERSION, GIT_COMMIT); exit(0); case 'r': TO_F_STR1(optarg, fname); break; } } if (optind < argc) propagation_spectrum_help(); } /***************************************************************/ /* FUNCTIONS TO BE USED BY THE PROGRAM oct-xyz-anim */ void xyz_anim_help() { printf("Usage: oct-xyz-anim [options] \n"); printf("\n"); printf("Options:\n"); printf(" -h, --help Prints this help and exits.\n"); printf(" -v, --version Prints octopus version.\n"); exit(-1); } void FC_FUNC_(getopt_xyz_anim, GETOPT_XYZ_ANIM)() { int c; #if defined(HAVE_GETOPT_LONG) static struct option long_options[] = {{"help", no_argument, 0, 'h'}, {"version", no_argument, 0, 'v'}, {0, 0, 0, 0}}; #endif while (1) { int option_index = 0; #if defined(HAVE_GETOPT_LONG) c = getopt_long(argc, argv, "hv", long_options, &option_index); #else c = getopt(argc, argv, "hv"); #endif if (c == -1) break; switch (c) { case 'h': xyz_anim_help(); break; case 'v': printf("octopus %s (git commit %s)\n", PACKAGE_VERSION, GIT_COMMIT); exit(0); } } if (optind < argc) xyz_anim_help(); } /***************************************************************/ /* FUNCTIONS TO BE USED BY THE PROGRAM oct-photoelectron_spectrum */ void photoelectron_spectrum_help() { printf("Usage: oct-photoelectron_spectrum [OPTIONS] \n"); printf("\n"); printf("Options:\n"); printf(" -h, --help Prints this help and exits.\n"); printf(" -v, --version Prints octopus version.\n"); printf(" -V, --vec=x,y,z The polar zenith direction in comma-separated " "format \n"); printf(" (without spaces). Default is the laser " "polarization. \n"); printf(" -u, --pvec=x,y,z The plane cut vector in comma-separated " "format.\n"); printf(" Default is 0,0,1 (px-py plane). \n"); printf(" -C, --center=x,y,z Center of the coordinates in p-space in " "comma-separated format \n"); printf(" Default: 0,0,0. \n"); printf(" -E, Maximum and minimum energy in colon-separated " "values. \n"); printf(" --espan=Emin:Emax " " \n"); printf(" -e, --de The resolution in energy.\n"); printf(" -T, Maximum and minimum theta in colon-separated " "format. \n"); printf(" --thspan=thetamin:thetamax " " \n"); printf(" -t, --dth The resolution in theta.\n"); printf(" -P, Maximum and minimum phi in colon separated " "format. \n"); printf(" --phspan=phimin:phimax " " \n"); printf(" -p, --dph The resolution in phi.\n"); printf(" -I, --integr=var The spectrum is integrated over the specified " "variable. For \n"); printf(" example \"-I phi\" integrates over phi. \n"); exit(-1); } void FC_FUNC_(getopt_photoelectron_spectrum, GETOPT_PHOTOELECTRON_SPECTRUM)(double *estep, double *espan, double *thstep, double *thspan, double *phstep, double *phspan, double *pol, double *center, double *pvec, int *integrate) { int c; char delims[] = ",:"; char *tok = NULL; #if defined(HAVE_GETOPT_LONG) static struct option long_options[] = {{"help", no_argument, 0, 'h'}, {"version", no_argument, 0, 'v'}, {"integr", required_argument, 0, 'I'}, {"de", required_argument, 0, 'e'}, {"espan", required_argument, 0, 'E'}, {"dth", required_argument, 0, 't'}, {"thspan", required_argument, 0, 'T'}, {"dph", required_argument, 0, 'p'}, {"phspan", required_argument, 0, 'P'}, {"vec", required_argument, 0, 'V'}, {"pvec", required_argument, 0, 'v'}, {"center", required_argument, 0, 'C'}, {0, 0, 0, 0}}; #endif while (1) { int option_index = 0; #if defined(HAVE_GETOPT_LONG) c = getopt_long(argc, argv, "hve:E:P:p:T:t:V:C:u:I:", long_options, &option_index); #else c = getopt(argc, argv, "hve:E:P:p:T:t:V:C:u:I:"); #endif if (c == -1) break; switch (c) { case 'h': photoelectron_spectrum_help(); break; case 'v': printf("octopus %s (git commit %s)\n", PACKAGE_VERSION, GIT_COMMIT); exit(0); break; case 'I': if ((strcmp(optarg, "phi") == 0)) { *integrate = 1; } else if ((strcmp(optarg, "theta") == 0)) { *integrate = 2; } else if ((strcmp(optarg, "r") == 0)) { *integrate = 3; } else if ((strcmp(optarg, "kx") == 0)) { *integrate = 4; } else if ((strcmp(optarg, "ky") == 0)) { *integrate = 5; } else if ((strcmp(optarg, "kz") == 0)) { *integrate = 6; } else { printf("Unrecognized integration variable %s.\n", optarg); *integrate = -1; } break; case 'e': *estep = atof(optarg); break; case 'E': tok = strtok(optarg, delims); espan[0] = atof(tok); tok = strtok(NULL, delims); espan[1] = atof(tok); break; case 't': *thstep = atof(optarg); break; case 'T': tok = strtok(optarg, delims); thspan[0] = atof(tok); tok = strtok(NULL, delims); thspan[1] = atof(tok); break; case 'p': *phstep = atof(optarg); break; case 'P': tok = strtok(optarg, delims); phspan[0] = atof(tok); tok = strtok(NULL, delims); phspan[1] = atof(tok); break; case 'V': tok = strtok(optarg, delims); pol[0] = atof(tok); tok = strtok(NULL, delims); pol[1] = atof(tok); tok = strtok(NULL, delims); pol[2] = atof(tok); break; case 'u': tok = strtok(optarg, delims); pvec[0] = atof(tok); tok = strtok(NULL, delims); pvec[1] = atof(tok); tok = strtok(NULL, delims); pvec[2] = atof(tok); break; case 'C': tok = strtok(optarg, delims); center[0] = atof(tok); tok = strtok(NULL, delims); center[1] = atof(tok); tok = strtok(NULL, delims); center[2] = atof(tok); break; } } }
0
ALLM/M3/octopus/src
ALLM/M3/octopus/src/basic/iihash_low.cc
/* Copyright (C) 2019 X. Andrade Copyright (C) 2021 S. Ohlmann 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, 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <unordered_map> #include <fortran_types.h> typedef std::unordered_map<fint, fint> map_type; typedef std::unordered_map<fint8, fint> map_type8; extern "C" void FC_FUNC_(iihash_map_init, IIHASH_MAP_INIT)(map_type **map) { *map = new map_type; } extern "C" void FC_FUNC_(iihash_map_end, IIHASH_MAP_END)(map_type **map) { delete *map; } extern "C" void FC_FUNC_(iihash_map_insert, IIHASH_MAP_INSERT)(map_type **map, const fint *key, const fint *val) { (**map)[*key] = *val; } extern "C" void FC_FUNC_(iihash_map_lookup, IIHASH_MAP_LOOKUP)(const map_type **map, const fint *key, fint *found, fint *val) { auto it = (*map)->find(*key); if (it == (*map)->end()) { *found = 0; } else { *found = 1; *val = it->second; } } /* functions for mapping of long long to int */ extern "C" void FC_FUNC_(lihash_map_init, LIHASH_MAP_INIT)(map_type8 **map) { *map = new map_type8; } extern "C" void FC_FUNC_(lihash_map_end, LIHASH_MAP_END)(map_type8 **map) { delete *map; } extern "C" void FC_FUNC_(lihash_map_insert, LIHASH_MAP_INSERT)(map_type8 **map, const fint8 *key, const fint *val) { (**map)[*key] = *val; } extern "C" void FC_FUNC_(lihash_map_lookup, LIHASH_MAP_LOOKUP)(const map_type8 **map, const fint8 *key, fint *found, fint *val) { auto it = (*map)->find(*key); if (it == (*map)->end()) { *found = 0; } else { *found = 1; *val = it->second; } }
0
ALLM/M3/octopus/src
ALLM/M3/octopus/src/basic/io_binary.c
/* Copyright (C) 2006 X. Andrade 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, 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* The functions in this file write and read an array to binary file. */ #define _FILE_OFFSET_BITS 64 #include <assert.h> #include <config.h> #include <errno.h> #include <fcntl.h> #include <math.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include "io_binary.h" typedef char byte; static const int64_t size_of[6] = {4, 8, 8, 16, 4, 8}; static const int64_t base_size_of[6] = {4, 8, 4, 8, 4, 8}; static const int64_t is_integer[6] = {0, 0, 0, 0, 1, 1}; static inline void inf_error(const char *msg) { perror(msg); } typedef union { float f[2]; double d[2]; } multi; /* A very basic endian conversion routine. This can be improved a lot, but it is not necessary, as restart files are converted at most once per run */ static inline void endian_convert(const int size, char *aa) { char tmp[8]; int ii; for (ii = 0; ii < size; ii++) tmp[ii] = aa[ii]; for (ii = 0; ii < size; ii++) aa[ii] = tmp[size - 1 - ii]; } static void convert(multi *in, multi *out, int t_in, int t_out); /* how to convert a complex to a real */ #define c2r hypot /* take the modulus */ /* THE HEADER OF THE FILE */ typedef struct { /* text to identify the file */ char text[7]; /*7 bytes*/ /* version of the format */ uint8_t version; /* 8 bytes*/ /* value of 1 in different formats, to recognize endianness */ uint32_t one_32; /*12 bytes */ float one_f; /* 16 bytes*/ uint64_t one_64; /* 24 bytes */ double one_d; /* 32 bytes */ /* the size of the array stored */ uint64_t np; /* 40 bytes */ /* the type of the wfs */ uint32_t type; /* 44 bytes */ /* extra values for future versions*/ uint32_t extra[5]; /* 64 bytes */ } header_t; static inline void init_header(header_t *hp) { int ii; strcpy(hp->text, "pulpo"); hp->text[6] = 0; hp->version = 0; hp->one_32 = 1; hp->one_f = 1.0; hp->one_64 = 1; hp->one_d = 1.0; for (ii = 0; ii < 5; ii++) hp->extra[ii] = 0; } static inline int check_header(header_t *hp, int *correct_endianness) { if (strcmp("pulpo", hp->text) != 0) return 5; if (hp->version != 0) return 5; /* Check the endianness of integer values and fix header components */ if (hp->one_32 != 1) { endian_convert(4, (char *)&(hp->one_32)); if (hp->one_32 != 1) return 5; endian_convert(4, (char *)&(hp->type)); } if (hp->one_64 != 1) { endian_convert(8, (char *)&(hp->one_64)); if (hp->one_64 != 1) return 5; endian_convert(8, (char *)&(hp->np)); } /* Check the endianness of floating point values */ *correct_endianness = 0; if (base_size_of[hp->type] == 4) { if (hp->one_f != 1.0) { endian_convert(4, (char *)&(hp->one_f)); if (hp->one_f != 1.0) return 5; *correct_endianness = 1; } } else { if (hp->one_d != 1.0) { endian_convert(8, (char *)&(hp->one_d)); if (hp->one_d != 1.0) return 5; *correct_endianness = 1; } } return 0; } void io_write_header(const int64_t *np, int *type, int *ierr, int *iio, char *fname) { header_t *hp; int fd; ssize_t moved; hp = (header_t *)malloc(sizeof(header_t)); assert(hp != NULL); assert(np > 0); *ierr = 0; fd = open(fname, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH); *iio += 100; if (fd < 0) { printf("Filename is %s\n", fname); inf_error("octopus.write_header in creating the header"); *ierr = 2; free(hp); return; } /* create header */ init_header(hp); hp->np = *np; hp->type = *type; /* write header */ moved = write(fd, hp, sizeof(header_t)); if (moved < sizeof(header_t)) { /* we couldn't write the complete header */ inf_error("octopus.write_header in writing the header"); *ierr = 3; } free(hp); close(fd); *iio += 1; } void write_binary(const int64_t *np, void *ff, int *type, int *ierr, int *iio, int *nhd, int *flpe, char *fname) { int fd; int64_t ii; ssize_t moved; ssize_t bytes_to_write; ssize_t offset; assert(np > 0); *ierr = 0; if (*nhd != 1) { io_write_header(np, type, ierr, iio, fname); } fd = open(fname, O_WRONLY, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH); iio += 100; if (fd < 0) { inf_error("octopus.write_binary in opening the file"); *ierr = 2; return; } /* skip the header and go until the end */ lseek(fd, 0, SEEK_END); /* flip endianness*/ if (*flpe == 1) { for (ii = 0; ii < (*np) * size_of[(*type)]; ii += base_size_of[(*type)]) endian_convert(base_size_of[(*type)], (char *)(ff + ii)); } /* now write the values */ bytes_to_write = (*np) * size_of[(*type)]; offset = 0; while (bytes_to_write > 0) { moved = write(fd, ff + offset, bytes_to_write); if (moved < 0) { /* an error occurred */ inf_error("octopus.write_binary in actual writing"); *ierr = 3; break; } bytes_to_write -= moved; offset += moved; } /* close the file */ close(fd); iio++; return; } /* this function neither allocates nor deallocates 'hp' */ void io_read_header(header_t *hp, int *correct_endianness, int *ierr, int *iio, char *fname) { int fd; ssize_t moved; *ierr = 0; fd = open(fname, O_RDONLY); *iio += 100; if (fd < 0) { *ierr = 2; return; } assert(hp != NULL); /* read header */ moved = read(fd, hp, sizeof(header_t)); if (moved != sizeof(header_t)) { /* we couldn't read the complete header */ *ierr = 3; return; } *ierr = check_header(hp, correct_endianness); if (*ierr != 0) { return; } close(fd); (*iio)++; } void read_binary(const int64_t *np, const int64_t *offset, byte *ff, int *output_type, int *ierr, int *iio, char *fname) { header_t *hp; int fd; int64_t ii; ssize_t moved; int correct_endianness; byte *read_f; assert(np > 0); /* read the header */ hp = (header_t *)malloc(sizeof(header_t)); assert(hp != NULL); io_read_header(hp, &correct_endianness, ierr, iio, fname); if (*ierr != 0) { free(hp); return; } /* check whether the sizes match */ if (hp->np < *np + *offset) { *ierr = 4; free(hp); return; } fd = open(fname, O_RDONLY); *iio += 100; if (fd < 0) { *ierr = 2; free(hp); return; } if (hp->type == *output_type) { /* format is the same, we just read */ read_f = ff; } else { /*format is not the same, we store into a temporary array */ read_f = (byte *)malloc((*np) * size_of[hp->type]); } /* set the start point */ if (*offset != 0) lseek(fd, (*offset) * size_of[hp->type] + sizeof(header_t), SEEK_SET); else lseek(fd, sizeof(header_t), SEEK_SET); /* now read the values and close the file */ moved = read(fd, read_f, (*np) * size_of[hp->type]); close(fd); (*iio)++; if (moved != (*np) * size_of[hp->type]) { /* we couldn't read the whole dataset */ *ierr = 3; if (hp->type != *output_type) { free(read_f); } free(hp); return; } /* convert endianness */ if (correct_endianness) { for (ii = 0; ii < (*np) * size_of[hp->type]; ii += base_size_of[hp->type]) endian_convert(base_size_of[hp->type], (char *)(read_f + ii)); } /* convert values if it is necessary */ if (hp->type != *output_type) { if (is_integer[hp->type] || is_integer[*output_type]) { *ierr = 5; } else { for (ii = 0; ii < *np; ii++) convert((multi *)(read_f + ii * size_of[hp->type]), (multi *)(ff + ii * size_of[*output_type]), hp->type, *output_type); /* set the error code according to the conversion done (see * src/basic/io_binary.h) */ if (hp->type == TYPE_FLOAT) *ierr = -1; if (hp->type == TYPE_FLOAT_COMPLEX) *ierr = -2; if (hp->type == TYPE_DOUBLE) *ierr = -3; if (hp->type == TYPE_DOUBLE_COMPLEX) *ierr = -4; } free(read_f); } free(hp); } /* This function converts between types. */ static void convert(multi *in, multi *out, int t_in, int t_out) { /* real types */ if (t_in == TYPE_FLOAT && t_out == TYPE_DOUBLE) { out->d[0] = in->f[0]; return; } if (t_in == TYPE_DOUBLE && t_out == TYPE_FLOAT) { out->f[0] = in->d[0]; return; } /* complex types */ if (t_in == TYPE_FLOAT_COMPLEX && t_out == TYPE_DOUBLE_COMPLEX) { out->d[0] = in->f[0]; out->d[1] = in->f[1]; return; } if (t_in == TYPE_DOUBLE_COMPLEX && t_out == TYPE_FLOAT_COMPLEX) { out->f[0] = in->d[0]; out->f[1] = in->d[1]; return; } /* real to complex */ if (t_in == TYPE_FLOAT && t_out == TYPE_FLOAT_COMPLEX) { out->f[0] = in->f[0]; out->f[1] = (float)0.0; return; } if (t_in == TYPE_DOUBLE && t_out == TYPE_FLOAT_COMPLEX) { out->f[0] = in->d[0]; out->f[1] = (float)0.0; return; } if (t_in == TYPE_FLOAT && t_out == TYPE_DOUBLE_COMPLEX) { out->d[0] = in->f[0]; out->d[1] = (double)0.0; return; } if (t_in == TYPE_DOUBLE && t_out == TYPE_DOUBLE_COMPLEX) { out->d[0] = in->d[0]; out->d[1] = (double)0.0; return; } /* complex to real */ if (t_in == TYPE_FLOAT_COMPLEX && t_out == TYPE_FLOAT) { out->f[0] = c2r(in->f[0], in->f[1]); return; } if (t_in == TYPE_DOUBLE_COMPLEX && t_out == TYPE_FLOAT) { out->f[0] = c2r(in->d[0], in->d[1]); return; } if (t_in == TYPE_FLOAT_COMPLEX && t_out == TYPE_DOUBLE) { out->d[0] = c2r(in->f[0], in->f[1]); return; } if (t_in == TYPE_DOUBLE_COMPLEX && t_out == TYPE_DOUBLE) { out->d[0] = c2r(in->d[0], in->d[1]); return; } } void get_info_binary(int64_t *np, int *type, int64_t *file_size, int *ierr, int *iio, char *fname) { header_t *hp; int correct_endianness; struct stat st; hp = (header_t *)malloc(sizeof(header_t)); assert(hp != NULL); /* read header */ io_read_header(hp, &correct_endianness, ierr, iio, fname); if (*ierr == 0) { *np = hp->np; *type = (int)hp->type; } else { *np = 0; *type = TYPE_NONE; } free(hp); stat(fname, &st); *file_size = (int64_t)st.st_size; }
0
ALLM/M3/octopus/src
ALLM/M3/octopus/src/basic/io_binary.h
#if 0 /* Copyright (C) 2009 X. Andrade 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, 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Note: This comment header is excluded by the preprocessor since this file is included in both C and Fortran source files, and thus neither comment style should be used. */ #endif #ifndef IO_BINARY_H #define IO_BINARY_H #if 0 /* These values must not be changed, as they are used in the restart files */ #endif #define TYPE_NONE -1 #define TYPE_FLOAT 0 #define TYPE_DOUBLE 1 #define TYPE_FLOAT_COMPLEX 2 #define TYPE_DOUBLE_COMPLEX 3 #define TYPE_INT_32 4 #define TYPE_INT_64 5 #endif
0
ALLM/M3/octopus/src
ALLM/M3/octopus/src/basic/io_csv.c
/* Copyright (C) 2006 octopus team 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, 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* The functions in this file read an array from an ascii matrix (csv) file. Format with values "valueXYZ" as follows File values.csv: -------- value111 value112 value113 value121 value122 value123 value131 value132 value133 value211 value212 value213 value221 value222 value223 value231 value232 value233 value311 value312 value313 value321 value322 value323 value331 value332 value333 -------- That is, every XY-plane as a table of values and all XY-planes separated by an empty row. The given matrix is interpolated/stretched to fit the calculation box defined in input file. Calculation box shape must be "parallelepiped". The delimiter can be a tab, a comma or a space. */ #include <assert.h> #include <config.h> #include <errno.h> #include <fcntl.h> #include <math.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include "string_f.h" #include "io_binary.h" static const int size_of[6] = {4, 8, 8, 16, 4, 8}; void FC_FUNC_(read_csv, READ_CSV)(unsigned long *np, void *f, int *output_type, int *ierr, STR_F_TYPE fname STR_ARG1) { char *filename; int i; FILE *fd; char *buf; char *c; const char sep[] = "\t\n ,"; int buf_size = 65536; TO_C_STR1(fname, filename); fd = fopen(filename, "r"); free(filename); *ierr = 0; if (fd == NULL) { *ierr = 2; return; } buf = (char *)malloc(buf_size * sizeof(char)); assert(buf != NULL); if ((*output_type) == TYPE_FLOAT) { i = 0; while (fgets(buf, buf_size * sizeof(char), fd) != NULL) { float d; c = strtok(buf, sep); while (c != NULL) { assert(i / 8 < *np); d = strtof(c, (char **)NULL); c = (char *)strtok((char *)NULL, sep); memcpy(f + i, &d, size_of[(*output_type)]); i += size_of[(*output_type)]; } } } else if ((*output_type) == TYPE_DOUBLE) { double d; i = 0; while (fgets(buf, buf_size * sizeof(char), fd) != NULL) { c = strtok(buf, sep); while (c != NULL) { assert(i / 8 < *np); d = strtod(c, (char **)NULL); memcpy(f + i, &d, size_of[(*output_type)]); c = (char *)strtok((char *)NULL, sep); i += size_of[(*output_type)]; } } } free(buf); fclose(fd); } void FC_FUNC_(get_info_csv, GET_INFO_CSV)(unsigned long *dims, int *ierr, STR_F_TYPE fname STR_ARG1) { char *filename; char *buf; char *c; FILE *fd; int buf_size = 65536; const char sep[] = "\n\t ,"; unsigned long curr_dims[3] = {0, 0, 0}; unsigned long prev_dims[2] = {0, 0}; TO_C_STR1(fname, filename); fd = fopen(filename, "r"); free(filename); *ierr = 0; if (fd == NULL) { *ierr = 2; return; } buf = (char *)malloc(buf_size * sizeof(char)); assert(buf != NULL); while (fgets(buf, buf_size * sizeof(char), fd) != NULL) { c = strtok(buf, sep); prev_dims[0] = curr_dims[0]; curr_dims[0] = 0; /** count the number of columns i.e. the size in x-direction**/ while (c != NULL) { curr_dims[0]++; c = (char *)strtok((char *)NULL, sep); } /** The number of columns must be the same on all non-empty rows **/ /** This only checks that the number of columns is correct within each z-block **/ if (prev_dims[0] > 0 && curr_dims[0] > 0) assert(curr_dims[0] == prev_dims[0]); /** If the previous line was empty and the current one is non-empty, then it signifies the start of a new z block i.e. a new xy-plane **/ if (prev_dims[0] == 0 && curr_dims[0] != 0) { prev_dims[1] = curr_dims[1]; curr_dims[1] = 0; curr_dims[2]++; /** The number of rows i.e. the size in y-direction must be the same * within all z-blocks **/ if (prev_dims[1] > 0 && curr_dims[1] > 0) assert(prev_dims[1] == curr_dims[1]); } /** If the current row is non-empty, increase the y-dimension **/ if (curr_dims[0] > 0) curr_dims[1]++; } dims[0] = curr_dims[0]; dims[1] = curr_dims[1]; dims[2] = curr_dims[2]; free(buf); fclose(fd); }
0
ALLM/M3/octopus/src
ALLM/M3/octopus/src/basic/nvtx_low.cc
/* Copyright (C) 2019, 2021 S. Ohlmann This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/. */ /* This is a wrapper around the NVTX (NVIDIA Tools Extension) profiling * functions */ #include <config.h> #ifdef HAVE_NVTX #include <nvToolsExt.h> /* These are colors from the "light" qualitative color scheme * from https://personal.sron.nl/~pault/ */ const uint32_t colors[] = {0xff77aadd, 0xff99ddff, 0xff44bb99, 0xffbbcc33, 0xffaaaa00, 0xffeedd88, 0xffee8866, 0xffffaabb, 0xffdddddd}; const int num_colors = sizeof(colors) / sizeof(uint32_t); #elif defined(HAVE_HIP) && defined(__HIP_PLATFORM_AMD__) #include <roctracer/roctx.h> #endif #include "string_f.h" /* fortran <-> c string compatibility issues */ #include <fortran_types.h> using namespace std; extern "C" void FC_FUNC_(nvtx_range_push, NVTX_RANGE_PUSH)(STR_F_TYPE range_name, const fint *idx STR_ARG1) { char *range_name_c; TO_C_STR1(range_name, range_name_c); #ifdef HAVE_NVTX /* The code for the colored ranges is taken from a blog post by Jiri Kraus: * https://developer.nvidia.com/blog/cuda-pro-tip-generate-custom-application-profile-timelines-nvtx/ */ int color_id = *idx; color_id = color_id % num_colors; nvtxEventAttributes_t eventAttrib = {0}; eventAttrib.version = NVTX_VERSION; eventAttrib.size = NVTX_EVENT_ATTRIB_STRUCT_SIZE; eventAttrib.colorType = NVTX_COLOR_ARGB; eventAttrib.color = colors[color_id]; eventAttrib.messageType = NVTX_MESSAGE_TYPE_ASCII; eventAttrib.message.ascii = range_name_c; nvtxRangePushEx(&eventAttrib); #elif defined(HAVE_HIP) && defined(__HIP_PLATFORM_AMD__) roctxRangePush(range_name_c); #endif free(range_name_c); } extern "C" void FC_FUNC_(nvtx_range_pop, NVTX_RANGE_POP)() { #ifdef HAVE_NVTX nvtxRangePop(); #elif defined(HAVE_HIP) && defined(__HIP_PLATFORM_AMD__) roctxRangePop(); #endif }
0
ALLM/M3/octopus/src
ALLM/M3/octopus/src/basic/oct_f.c
/* Copyright (C) 2002 M. Marques, A. Castro, A. Rubio, G. Bertsch 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, 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <ctype.h> #include <libgen.h> #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #if __has_include(<unistd.h>) #include <unistd.h> #endif #include <fortran_types.h> #ifdef _POSIX_VERSION #include <dirent.h> #include <sys/stat.h> #include <sys/time.h> #include <sys/types.h> #endif #include "string_f.h" /* Fortran <-> c string compatibility issues */ /* *********************** interface functions ********************** */ void FC_FUNC_(oct_mkdir, OCT_MKDIR)(STR_F_TYPE name STR_ARG1) { struct stat buf; char *name_c; TO_C_STR1(name, name_c); if (!*name_c) return; if (stat(name_c, &buf) == 0) { free(name_c); return; } #ifndef _WIN32 mkdir(name_c, 0775); #else mkdir(name_c); #endif free(name_c); } void FC_FUNC_(oct_stat, OCT_STAT)(fint *ierr, STR_F_TYPE name, STR_F_TYPE mod_time STR_ARG2) { char *name_c, *mod_time_c; struct stat statbuf; time_t mtime; struct tm *timeinfo; TO_C_STR1(name, name_c); *ierr = stat(name_c, &statbuf); if (*ierr == 0) { mtime = statbuf.st_mtime; /* last modification time */ timeinfo = localtime(&mtime); mod_time_c = asctime(timeinfo); } else { perror(name_c); /* what is the problem? */ mod_time_c = malloc(sizeof(char)); mod_time_c[0] = '\0'; } free(name_c); TO_F_STR2(mod_time_c, mod_time); if (*ierr != 0) { printf("ierr = %i\n", *ierr); free(mod_time_c); } /* otherwise, do not do this since 'mod_time_c' points at static data of * asctime */ } int FC_FUNC_(oct_dir_exists, OCT_DIR_EXISTS)(STR_F_TYPE name STR_ARG1) { int ierr; char *name_c; struct stat statbuf; TO_C_STR1(name, name_c); ierr = stat(name_c, &statbuf); free(name_c); if (ierr == 0) { return S_ISDIR(statbuf.st_mode); } else { return 0; } } void FC_FUNC_(oct_rm, OCT_RM)(STR_F_TYPE name STR_ARG1) { char *name_c; TO_C_STR1(name, name_c); unlink(name_c); free(name_c); } void FC_FUNC_(oct_getcwd, OCT_GETCWD)(STR_F_TYPE name STR_ARG1) { char s[256]; getcwd(s, 256); TO_F_STR1(s, name); } void FC_FUNC_(oct_realpath, OCT_REALPATH)(STR_F_TYPE fnam, STR_F_TYPE rnam STR_ARG2) { char *fn = NULL, *rn = NULL; TO_C_STR1(fnam, fn); rn = realpath(fn, NULL); free(fn); if (rn != NULL) { TO_F_STR2(rn, rnam); } else { TO_F_STR2("", rnam); } free(rn); return; } void FC_FUNC_(oct_dirname, OCT_DIRNAME)(STR_F_TYPE fnam, STR_F_TYPE dnam STR_ARG2) { char *fn = NULL, *dn = NULL; TO_C_STR1(fnam, fn); dn = dirname(fn); if (dn != NULL) { TO_F_STR2(dn, dnam); } else { TO_F_STR2("", dnam); } free(fn); return; } void FC_FUNC_(oct_basename, OCT_BASENAME)(STR_F_TYPE fnam, STR_F_TYPE bnam STR_ARG2) { char *fn = NULL, *bn = NULL; TO_C_STR1(fnam, fn); bn = basename(fn); free(fn); if (bn != NULL) { TO_F_STR2(bn, bnam); } else { TO_F_STR2("", bnam); } return; } void FC_FUNC_(oct_getenv, OCT_GETENV)(STR_F_TYPE var, STR_F_TYPE value STR_ARG2) { char *name_c, *var_c; TO_C_STR1(var, name_c); var_c = getenv(name_c); free(name_c); if (var_c != NULL) { TO_F_STR2(var_c, value); } else { TO_F_STR2("", value); } } /* this function gets a string of the form '1-12, 34' and fills array l with the 1 if the number is in the list, or 0 otherwise */ void FC_FUNC_(oct_wfs_list, OCT_WFS_LIST)(STR_F_TYPE str, fint l[16384] STR_ARG1) { int i, i1, i2; char c[20], *c1, *str_c, *s; TO_C_STR1(str, str_c); s = str_c; /* clear list */ for (i = 0; i < 16384; i++) l[i] = 0; while (*s) { /* get integer */ for (c1 = c; isdigit(*s) || isspace(*s); s++) if (isdigit(*s)) *c1++ = *s; *c1 = '\0'; i1 = atoi(c) - 1; if (*s == '-') { /* range */ s++; for (c1 = c; isdigit(*s) || isspace(*s); s++) if (isdigit(*s)) *c1++ = *s; *c1 = '\0'; i2 = atoi(c) - 1; } else /* single value */ i2 = i1; for (i = i1; i <= i2; i++) if (i >= 0 && i < 16384) l[i] = 1; if (*s) s++; } free(str_c); } /* ------------------------------ from varia.c ------------------------------- */ #include "varia.h" void FC_FUNC_(oct_progress_bar, OCT_PROGRESS_BAR)(fint *a, fint *max) { if (*max == 0) return; /* Skip the bar if the length is 0 */ progress_bar(*a, *max); } /* ------------------------------ some stuff -------------------------------- */ void FC_FUNC_(oct_gettimeofday, OCT_GETTIMEOFDAY)(fint *sec, fint *usec) { #ifdef _POSIX_VERSION struct timeval tv; gettimeofday(&tv, NULL); /* The typecast below should use long. However, this causes incompatibilities with Fortran integers. Using int will cause wrong results when tv.tv_sec exceeds INT_MAX=2147483647 */ *sec = (int)tv.tv_sec; *usec = (int)tv.tv_usec; /* char str[sizeof("HH:MM:SS")]; time_t local; local = tv.tv_sec; strftime(str, sizeof(str), "%T", localtime(&local)); printf("%s.%06ld \n", str, (long) tv.tv_usec); printf("%ld.%06ld \n", (long) tv.tv_sec, (long) tv.tv_usec); */ #else *sec = 0; *usec = 0; #endif } double FC_FUNC_(oct_clock, OCT_CLOCK)() { #ifdef _POSIX_VERSION int sec, usec; FC_FUNC_(oct_gettimeofday, OCT_GETTIMEOFDAY)(&sec, &usec); return sec + 1.0e-6 * usec; #else return (double)clock() / CLOCKS_PER_SEC; #endif } void FC_FUNC_(oct_nanosleep, OCT_NANOSLEEP)(fint *sec, fint *nsec) { #ifdef _POSIX_VERSION /* Datatypes should be long instead of int (see comment in gettimeofday) */ struct timespec req; req.tv_sec = (time_t)*sec; req.tv_nsec = (long)*nsec; nanosleep(&req, NULL); #endif } void FC_FUNC_(oct_sysname, OCT_SYSNAME)(STR_F_TYPE name STR_ARG1) { char *name_c; sysname(&name_c); TO_F_STR1(name_c, name); free(name_c); } int FC_FUNC_(oct_number_of_lines, OCT_NUMBER_OF_LINES)(STR_F_TYPE name STR_ARG1) { FILE *pf; int c, i; char *name_c; TO_C_STR1(name, name_c); pf = fopen(name_c, "r"); free(name_c); if (pf != NULL) { i = 0; while ((c = getc(pf)) != EOF) { if (c == '\n') i++; } fclose(pf); return i; } else { return -1; } } /* Given a string in C, it breaks it line by line and returns each as a Fortran string. Returns 0 if string does not have more lines. */ void FC_FUNC_(oct_break_c_string, OCT_BREAK_C_STRING)(char **str, char **s, STR_F_TYPE line_f STR_ARG1) { char *c, line[256]; /* hopefully no line is longer than 256 characters ;) */ if (*s == NULL) *s = *str; if (*s == NULL || **s == '\0') { *s = (char *)(0); return; } for (c = line; **s != '\0' && **s != '\n'; (*s)++, c++) *c = **s; *c = '\0'; if (**s == '\n') (*s)++; TO_F_STR1(line, line_f); } /* This function searches in directory given by dirname all files that have the following name: *_<real_number>_<integer>* It returns the value of <real_number> found that is closest to freq (or abs(freq)) and for which the value of <integer> matches with the tag argument. The value found is returned in the freq argument. ierr results: 0 : value found 1 : no matching file found 2 : cannot open the directory or function not available */ void FC_FUNC_(oct_search_file_lr, OCT_SEARCH_FILE_LR)(double *freq, const fint *tag, fint *ierr, STR_F_TYPE dirname STR_ARG1) { #ifdef _POSIX_VERSION DIR *dir; struct dirent *ent; char *name_c; char *num_start, *num_end; double read_value, min; int found_something, read_tag; TO_C_STR1(dirname, name_c); dir = opendir(name_c); if (dir == NULL) { *ierr = 2; return; } free(name_c); ent = NULL; found_something = 0; while (1) { ent = readdir(dir); if (ent == NULL) break; num_start = strchr(ent->d_name, '_'); if (num_start != NULL) { num_start++; /* now this points to the beginning of the number */ /* take the numerical value from the string */ read_value = strtod(num_start, &num_end); if (num_end == num_start) continue; /* no number found */ /* check that we have the correct tag */ if (num_end[0] == '_') { num_start = num_end + 1; read_tag = (int)strtol(num_start, &num_end, 10); if (num_end == num_start) continue; /* no tag found */ if (read_tag != *tag) continue; /* tag does not match */ } else continue; /* if this is the first number we found */ if (!found_something) { min = read_value; found_something = 1; } else if (fabs(fabs(min) - fabs(*freq)) > fabs(fabs(read_value) - fabs(*freq))) { /* if the value is closer than previous */ min = read_value; } } } closedir(dir); if (found_something) { *ierr = 0; *freq = min; } else { *ierr = 1; } #else #warning directory search not compiled fprintf(stderr, "Warning: Directory search not available since certain C " "functions are not available.\n"); *ierr = 2; #endif } void *FC_FUNC_(oct_get_memory_usage, OCT_GET_MEMORY_USAGE)() { #ifdef _POSIX_VERSION static size_t pagesize = 0; FILE *f; int pid; unsigned long mem; char s[256]; if (pagesize == 0) pagesize = sysconf(_SC_PAGESIZE); pid = getpid(); sprintf(s, "%s%d%s", "/proc/", pid, "/statm"); if ((f = fopen(s, "r")) == (FILE *)NULL) return (void *)(-1); fscanf(f, "%lu", &mem); fclose(f); return (void *)(mem * pagesize); #else return 0; #endif } void FC_FUNC_(oct_exit_failure, OCT_EXIT_FAILURE)() { exit(EXIT_FAILURE); }
0
ALLM/M3/octopus/src
ALLM/M3/octopus/src/basic/recipes.c
/* Copyright (C) 2002 M. Marques, A. Castro, A. Rubio, G. Bertsch 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, 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <gsl/gsl_rng.h> #include <locale.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #if __has_include(<unistd.h>) #include <unistd.h> #endif #ifdef _POSIX_VERSION #include <dirent.h> #include <sys/time.h> #endif #include "string_f.h" unsigned long int random_seed() { unsigned long int seed; FILE *devrandom; if ((devrandom = fopen("/dev/urandom", "r")) == NULL) { #ifdef _POSIX_VERSION struct timeval tv; gettimeofday(&tv, 0); seed = tv.tv_sec + tv.tv_usec; #else seed = 0; #endif } else { fread(&seed, sizeof(seed), 1, devrandom); fclose(devrandom); } return seed; } void FC_FUNC_(oct_printrecipe, OCT_PRINTRECIPE)(STR_F_TYPE _dir, STR_F_TYPE filename STR_ARG2) { #ifdef _POSIX_VERSION char *lang, *tmp, dir[512]; struct dirent **namelist; int ii, nn; gsl_rng *rng; /* get language */ lang = getenv("LANG"); if (lang == NULL) lang = "en"; /* convert directory from Fortran to C string */ TO_C_STR1(_dir, tmp); strcpy(dir, tmp); free(tmp); strcat(dir, "/recipes"); /* check out if lang dir exists */ nn = scandir(dir, &namelist, 0, alphasort); if (nn < 0) { printf("Directory does not exist: %s", dir); return; } for (ii = 0; ii < nn; ii++) if (strncmp(lang, namelist[ii]->d_name, 2) == 0) { strcat(dir, "/"); strcat(dir, namelist[ii]->d_name); break; } if (ii == nn) strcat(dir, "/en"); /* default */ /* clean up */ for (ii = 0; ii < nn; ii++) free(namelist[ii]); free(namelist); /* now we read the recipes */ nn = scandir(dir, &namelist, 0, alphasort); /* initialize random numbers */ gsl_rng_env_setup(); rng = gsl_rng_alloc(gsl_rng_default); gsl_rng_set(rng, random_seed()); ii = gsl_rng_uniform_int(rng, nn - 2); gsl_rng_free(rng); strcat(dir, "/"); strcat(dir, namelist[ii + 2]->d_name); /* skip ./ and ../ */ /* clean up again */ for (ii = 0; ii < nn; ii++) free(namelist[ii]); free(namelist); TO_F_STR2(dir, filename); #else printf("Sorry, recipes cannot be printed unless scandir and alphasort are " "available with your C compiler.\n"); #endif }
0
ALLM/M3/octopus/src
ALLM/M3/octopus/src/basic/signals.c
/* Copyright (C) 2016 X. Andrade 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, 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <signal.h> #include "string_f.h" /* fortran <-> c string compatibility issues */ #include <fortran_types.h> #include <stdlib.h> #include <string.h> #if __has_include(<unistd.h>) #include <unistd.h> #endif void FC_FUNC_(block_signals, BLOCK_SIGNALS)() { #ifdef _POSIX_VERSION struct sigaction act; act.sa_handler = SIG_IGN; sigemptyset(&act.sa_mask); act.sa_flags = 0; sigaction(SIGINT, &act, 0); sigaction(SIGTERM, &act, 0); #endif } void FC_FUNC_(unblock_signals, UNBLOCK_SIGNALS)() { #ifdef _POSIX_VERSION struct sigaction act; act.sa_handler = SIG_DFL; sigemptyset(&act.sa_mask); act.sa_flags = 0; sigaction(SIGINT, &act, 0); sigaction(SIGTERM, &act, 0); #endif } void handle_segv(int *); #ifdef _POSIX_VERSION void segv_handler(int signum, siginfo_t *si, void *vd) { handle_segv(&signum); signal(signum, SIG_DFL); kill(getpid(), signum); } #endif void FC_FUNC_(trap_segfault, TRAP_SEGFAULT)() { #ifdef _POSIX_VERSION struct sigaction act; sigemptyset(&act.sa_mask); act.sa_sigaction = segv_handler; act.sa_flags = SA_SIGINFO; sigaction(SIGTERM, &act, 0); sigaction(SIGKILL, &act, 0); sigaction(SIGSEGV, &act, 0); sigaction(SIGABRT, &act, 0); sigaction(SIGINT, &act, 0); sigaction(SIGBUS, &act, 0); sigaction(SIGILL, &act, 0); sigaction(SIGTSTP, &act, 0); sigaction(SIGQUIT, &act, 0); sigaction(SIGFPE, &act, 0); sigaction(SIGHUP, &act, 0); #endif } void FC_FUNC_(get_signal_description, GET_SIGNAL_DESCRIPTION)(fint *signum, STR_F_TYPE const signame STR_ARG1) { #ifdef _POSIX_VERSION TO_F_STR1(strsignal(*signum), signame); #else TO_F_STR1("(description not available)", signame); #endif }
0
ALLM/M3/octopus/src
ALLM/M3/octopus/src/basic/sihash_low.cc
/* Copyright (C) 2019 X. Andrade, 2021 M. Lueders 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, 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <string> #include <unordered_map> typedef std::unordered_map<std::string, int> map_type; extern "C" void sihash_map_init(map_type **map) { *map = new map_type; } extern "C" void sihash_map_end(map_type **map) { delete *map; } extern "C" void sihash_map_insert(map_type *map, const char *key, int val) { std::string my_key(key); (*map)[my_key] = val; } extern "C" void sihash_map_lookup(const map_type *map, const char *key, int *found, int *val) { std::string my_key(key); auto it = (map)->find(my_key); if (it == (map)->end()) { *found = 0; } else { *found = 1; *val = it->second; } } extern "C" void sihash_iterator_low_start(map_type::const_iterator *iterator, map_type::const_iterator *end, const map_type *map) { *iterator = map->begin(); *end = map->end(); } extern "C" void sihash_iterator_low_has_next(map_type::const_iterator iterator, map_type::const_iterator end, int *val) { *val = (iterator != end); } extern "C" void sihash_iterator_low_get(map_type::const_iterator *iterator, int *val) { *val = (*iterator)->second; (*iterator)++; }
0
ALLM/M3/octopus/src
ALLM/M3/octopus/src/basic/sort_low.cc
/* Copyright (C) 2016 X. Andrade Copyright (C) 2021 S. Ohlmann 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, 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <algorithm> #include <fortran_types.h> #include <new> // Functor object that compares indices based on an array template <typename TT> class compare { public: compare(const TT *array_val) { array = array_val; } TT operator()(const fint ii, const fint jj) { return array[ii] < array[jj]; } private: const TT *array; }; // Worker function that sorts an array and returns the order template <typename TT> void sort2(const fint size, TT *array, fint *indices) { // first sort the indices for (fint ii = 0; ii < size; ii++) { indices[ii] = ii; } std::sort(indices, indices + size, compare<TT>(array)); // now sort the array TT *array_copy = new TT[size]; std::copy(array, array + size, array_copy); for (fint ii = 0; ii < size; ii++) { array[ii] = array_copy[indices[ii]]; indices[ii]++; // convert indices to fortran convention } delete[] array_copy; } // Fortran interfaces extern "C" void FC_FUNC(isort1, ISORT1)(const fint *size, fint *array) { std::sort(array, array + *size); } extern "C" void FC_FUNC(isort2, ISORT2)(const fint *size, fint *array, fint *indices) { sort2<fint>(*size, array, indices); } extern "C" void FC_FUNC(lsort1, LSORT1)(const fint *size, fint8 *array) { std::sort(array, array + *size); } extern "C" void FC_FUNC(lsort2, LSORT2)(const fint *size, fint8 *array, fint *indices) { sort2<fint8>(*size, array, indices); } extern "C" void FC_FUNC(dsort1, DSORT1)(const fint *size, double *array) { std::sort(array, array + *size); } extern "C" void FC_FUNC(dsort2, DSORT2)(const fint *size, double *array, fint *indices) { sort2<double>(*size, array, indices); }
0
ALLM/M3/octopus/src
ALLM/M3/octopus/src/basic/sphash_low.cc
/* Copyright (C) 2019 X. Andrade, 2021 M. Lueders 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, 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <cassert> #include <string> #include <unordered_map> typedef std::unordered_map<std::string, void *> map_type; extern "C" void sphash_map_init(map_type **map) { *map = new map_type; } extern "C" void sphash_map_end(map_type **map) { delete *map; } extern "C" void sphash_map_insert(map_type *map, const char *key, void *ptr) { std::string my_key(key); assert(map->count(my_key) == 0); (*map)[my_key] = ptr; } extern "C" void sphash_map_lookup(const map_type *map, const char *key, int *found, void **ptr) { std::string my_key(key); auto it = (map)->find(my_key); if (it == (map)->end()) { *found = 0; } else { *found = 1; *ptr = it->second; } } extern "C" void sphash_iterator_low_start(map_type::const_iterator *iterator, map_type::const_iterator *end, const map_type *map) { *iterator = map->begin(); *end = map->end(); } extern "C" void sphash_iterator_low_has_next(map_type::const_iterator iterator, map_type::const_iterator end, int *result) { *result = (iterator != end); } extern "C" void sphash_iterator_low_get(map_type::const_iterator *iterator, void **ptr) { *ptr = (*iterator)->second; (*iterator)++; }
0
ALLM/M3/octopus/src
ALLM/M3/octopus/src/basic/varia.c
/* Copyright (C) 2002 M. Marques, A. Castro, A. Rubio, G. Bertsch 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, 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #if __has_include(<unistd.h>) #include <unistd.h> #endif #ifdef _POSIX_VERSION #include <sys/ioctl.h> #include <sys/time.h> #include <sys/types.h> #include <sys/utsname.h> #include <termios.h> #endif #include "varia.h" /** * Gets the name of the machine */ void sysname(char **c) { #ifdef _POSIX_VERSION struct utsname name; uname(&name); *c = (char *)malloc(sizeof(name.nodename) + sizeof(name.sysname) + 4); strcpy(*c, name.nodename); strcat(*c, " ("); strcat(*c, name.sysname); strcat(*c, ")"); #else *c = (char *)malloc(8); strcpy(*c, "unknown"); #endif } /** * returns true if process is in the foreground * copied from openssh scp source */ static int foreground_proc(void) { #ifdef _POSIX_VERSION static pid_t pgrp = -1; int ctty_pgrp; if (pgrp == -1) pgrp = getpgrp(); #ifdef _POSIX_VERSION return ((ctty_pgrp = tcgetpgrp(STDOUT_FILENO)) != -1 && ctty_pgrp == pgrp); #endif #else return 0; #endif } int getttywidth(void) { #ifdef _POSIX_VERSION struct winsize winsize; if (ioctl(fileno(stdout), TIOCGWINSZ, &winsize) != -1) return (winsize.ws_col ? winsize.ws_col : 80); else #endif return (80); } /** * displays progress bar with a percentage */ void progress_bar(int actual, int max) { static struct timeval start; static int old_pos, next_print; struct timeval now; char buf[512], fmt[64]; int i, j, ratio, barlength, remaining; double elapsed; if (actual < 0) { (void)gettimeofday(&start, (struct timezone *)0); actual = 0; old_pos = 0; next_print = 10; } if (max > 0) { ratio = 100 * actual / max; if (ratio < 0) ratio = 0; if (ratio > 100) { ratio = 100; fprintf(stderr, "Internal warning: progress_bar called with actual %i > max %i\n", actual, max); } } else ratio = 100; if (foreground_proc() == 0) { if (old_pos == 0) { printf("ETA: "); } barlength = getttywidth() - 6; j = actual * (barlength - 1) / max; if (j > barlength || actual == max) j = barlength; if (j < 1) j = 1; if (j > old_pos) { for (i = old_pos + 1; i <= j; i++) if (i * 100 / barlength >= next_print) { printf("%1d", next_print / 10 % 10); next_print += 10; } else printf("."); old_pos = j; if (j == barlength) printf("\n"); } } else { sprintf(buf, "%d", max); i = strlen(buf); if (i < 3) i = 3; sprintf(fmt, "\r[%%%dd/%%%dd]", i, i); sprintf(buf, fmt, actual, max); sprintf(buf + strlen(buf), " %3d%%", ratio); barlength = getttywidth() - strlen(buf) - 16; if (barlength > 0) { i = barlength * ratio / 100; sprintf(buf + strlen(buf), "|%.*s%*s|", i, "*******************************************************" "*******************************************************" "*******************************************************" "*******************************************************" "*******************************************************" "*******************************************************" "*******************************************************", barlength - i, ""); } /* time information now */ (void)gettimeofday(&now, (struct timezone *)0); elapsed = now.tv_sec - start.tv_sec; if (elapsed <= 0.0 || actual <= 0) { sprintf(buf + strlen(buf), " --:-- ETA"); } else { remaining = (int)(max / (actual / elapsed) - elapsed); if (remaining < 0) remaining = 0; i = remaining / 3600; if (i) sprintf(buf + strlen(buf), "%4d:", i); else sprintf(buf + strlen(buf), " "); i = remaining % 3600; sprintf(buf + strlen(buf), "%02d:%02d%s", i / 60, i % 60, " ETA"); } printf("%s", buf); } fflush(stdout); } #undef timersub
0
ALLM/M3/octopus/src
ALLM/M3/octopus/src/basic/varia.h
/* Copyright (C) 2002 M. Marques, A. Castro, A. Rubio, G. Bertsch 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, 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef _VARIA_H #define _VARIA_H void progress_bar(int actual, int max); void sysname(char **c); #endif
0
ALLM/M3/octopus/src
ALLM/M3/octopus/src/basic/varinfo_low.c
/* Copyright (C) 2002 M. Marques, A. Castro, A. Rubio, G. Bertsch 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, 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #define _GNU_SOURCE #include <ctype.h> #include <fortran_types.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "string_f.h" /* fortran <-> c string compatibility issues */ typedef struct opt_type { char *name; char *value; char *desc; struct opt_type *next; } opt_type; typedef struct var_type { char *name; char *type; char *default_str; /* default is a reserved keyword */ char *section; char *desc; opt_type *opt; struct var_type *next; } var_type; static var_type *vars = NULL; /* --------------------------------------------------------- */ char *get_token(char *s, char **dest) { char *s1; size_t len; /* get rid of initial whitespace */ for (; *s != '\0' && isspace(*s); s++) ; if (!isalnum(*s) && *s != '-') { *dest = NULL; return s; } for (s1 = s; isalnum(*s1) || *s1 == '_' || *s1 == '-' || *s1 == '('; s1++) ; len = s1 - s; *dest = (char *)strndup(s, len); return s1; } /* --------------------------------------------------------- */ void get_text(FILE *in, char **dest) { char c, line[256]; int b; for (;;) { /* check if the next line starts by a space */ if ((b = getc(in)) == EOF) return; c = (char)b; ungetc(c, in); if (!isspace(c)) return; fgets(line, 256, in); if (c == '\n') { line[0] = ' '; line[1] = '\n'; line[2] = '\0'; } if (!*dest) *dest = strdup(line + 1); else { *dest = realloc(*dest, strlen(*dest) + strlen(line + 1) + 1); strcat(*dest, line + 1); } } } /* --------------------------------------------------------- */ void FC_FUNC_(varinfo_init, VARINFO_INIT)(STR_F_TYPE const fname STR_ARG1) { char line[256], *fname_c; FILE *in; var_type *lvar = NULL; opt_type *lopt; TO_C_STR1(fname, fname_c); in = fopen(fname_c, "r"); free(fname_c); if (!in) { return; } while (fgets(line, 256, in)) { if (strncasecmp("Variable", line, 8) == 0) { char *s; get_token(line + 9, &s); if (s) { /* found a token */ if (!lvar) { lvar = (var_type *)malloc(sizeof(var_type)); vars = lvar; } else { lvar->next = (var_type *)malloc(sizeof(var_type)); lvar = lvar->next; } lvar->name = s; lvar->desc = NULL; lvar->type = NULL; lvar->default_str = NULL; lvar->section = NULL; lvar->opt = NULL; lvar->next = NULL; lopt = NULL; } continue; } /* if no variable was found continue */ if (!lvar) continue; if (strncasecmp("Type", line, 4) == 0) get_token(line + 5, &(lvar->type)); if (strncasecmp("Default", line, 7) == 0) get_token(line + 8, &(lvar->default_str)); if (strncasecmp("Section", line, 7) == 0) { char *s = line + 7; for (; *s != '\0' && isspace(*s); s++) ; lvar->section = strdup(s); } if (strncasecmp("Description", line, 11) == 0) { if (lvar->desc) { /* if repeated delete old description */ free(lvar->desc); lvar->desc = NULL; } get_text(in, &(lvar->desc)); } if (strncasecmp("Option", line, 6) == 0) { char *name, *value, *s; s = get_token(line + 6, &name); if (name) get_token(s, &value); if (name) { /* found an option */ if (!lopt) { lopt = (opt_type *)malloc(sizeof(opt_type)); lvar->opt = lopt; } else { lopt->next = (opt_type *)malloc(sizeof(var_type)); lopt = lopt->next; } lopt->name = name; lopt->value = value; lopt->desc = NULL; get_text(in, &(lopt->desc)); lopt->next = NULL; } } } fclose(in); } /* --------------------------------------------------------- */ void FC_FUNC_(varinfo_end, VARINFO_END)() { var_type *v = vars; for (; v;) { var_type *v1 = v->next; opt_type *o = v->opt; if (v->name) free(v->name); if (v->type) free(v->type); if (v->default_str) free(v->default_str); if (v->section) free(v->section); if (v->desc) free(v->desc); for (; o;) { opt_type *o1 = o->next; if (o->name) free(o->name); if (o->value) free(o->value); if (o->desc) free(o->desc); free(o); o = o1; } free(v); v = v1; } } /* --------------------------------------------------------- */ void FC_FUNC_(varinfo_getvar, VARINFO_GETVAR)(STR_F_TYPE const name, var_type **var STR_ARG1) { char *name_c; var_type *lvar; TO_C_STR1(name, name_c); for (lvar = vars; (lvar != NULL) && (strcasecmp(name_c, lvar->name) != 0); lvar = lvar->next) ; free(name_c); *var = lvar; } /* --------------------------------------------------------- */ void FC_FUNC_(varinfo_getinfo, VARINFO_GETINFO)(const var_type **var, char **name, char **type, char **default_str, char **section, char **desc) { if (var == NULL) { *name = NULL; *type = NULL; *default_str = NULL; *section = NULL; *desc = NULL; } else { *name = (*var)->name; *type = (*var)->type; *default_str = (*var)->default_str; *section = (*var)->section; *desc = (*var)->desc; } } /* --------------------------------------------------------- */ void FC_FUNC_(varinfo_getopt, VARINFO_GETOPT)(const var_type **var, opt_type **opt) { if (*var == NULL) *opt = NULL; else if (*opt == NULL) *opt = (*var)->opt; else *opt = (*opt)->next; } /* --------------------------------------------------------- */ void FC_FUNC_(varinfo_opt_getinfo, VARINFO_OPT_GETINFO)(const opt_type **opt, char **name, fint8 *value, char **desc) { if (opt == NULL) { *name = NULL; *desc = NULL; *value = 0; } else { *name = (*opt)->name; *desc = (*opt)->desc; if ((*opt)->value) { if (strncmp("bit", (*opt)->value, 3) == 0) { *value = ((int64_t)1) << strtoll((*opt)->value + 4, NULL, 10); } else { *value = strtoll((*opt)->value, NULL, 10); } } else { *value = 0; } } } /* --------------------------------------------------------- This function searches for a substring in the name of a variable. If var is set to NULL, it starts from the beginning of the list. If it is different from NULL, it assumes it is the result of a previous search and it starts searching from that point. It returns NULL if nothing is found. --------------------------------------------------------- */ /* used by liboct_parser/symbols.c */ int varinfo_variable_exists(const char *var_name) { var_type *lvar; for (lvar = vars; (lvar != NULL) && (strcasecmp(var_name, lvar->name) != 0); lvar = lvar->next) ; return (lvar != NULL); } void FC_FUNC_(varinfo_search_var, VARINFO_SEARCH_VAR)(const STR_F_TYPE name, var_type **var STR_ARG1) { char *name_c; var_type *lvar; if (*var == NULL) lvar = vars; else lvar = (*var)->next; TO_C_STR1(name, name_c); for (; (lvar != NULL) && (strcasestr(lvar->name, name_c) == 0); lvar = lvar->next) ; free(name_c); *var = lvar; } void FC_FUNC_(varinfo_search_option, VARINFO_SEARCH_OPTION)(const var_type **var, const STR_F_TYPE name, int *value, int *ierr STR_ARG1) { char *name_c; opt_type *opt; TO_C_STR1(name, name_c); opt = (*var)->opt; *ierr = -1; while (opt != NULL) { if (strcmp(opt->name, name_c) == 0) { *value = atoi(opt->value); printf("%s|%s|\n", opt->name, name_c); *ierr = 0; break; } opt = opt->next; } free(name_c); }
0
ALLM/M3/octopus/src
ALLM/M3/octopus/src/basic/write_iter_low.cc
/* Copyright (C) 2002 M. Marques, A. Castro, A. Rubio, G. Bertsch 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, 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <errno.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include "string_f.h" #include <config.h> #include <fortran_types.h> #include <iostream> #define CHUNK 1024 typedef struct { char *filename, *buf; size_t iter, pos, size; double dt; } write_iter; /* internal functions */ /** * @brief Reallocates the buffer of a write_iter struct if insufficient space is available. * * Check if the current position plus the given size plus one (for null-termination) * is greater than the allocated size of the buffer in the write_iter structure. If so, reallocate * memory to increase the size of the buffer. * * @param w Pointer to the write_iter struct. * @param s The additional size required for writing. */ static void write_iter_realloc(write_iter *w, int s) { if (w->pos + s + 1 <= w->size) return; while (w->pos + s + 1 > w->size) { w->size += CHUNK; } w->buf = (char *)realloc(w->buf, w->size); } static void write_iter_string_work(write_iter *w, const char *s) { int l; l = strlen(s); write_iter_realloc(w, l); strcpy(w->buf + w->pos, s); w->pos += l; } /** * @brief Centers a string within a specified length. * * This function takes a string `s1` and an integer `l2` as input. It centers the string `s1` within a string * of length `l2` by adding spaces before and after the string. The centered string is dynamically allocated * and returned as a new string. * * @param s1 Pointer to the input string to be centered. * @param l2 Length of the output string (including spaces). * * @return Pointer to the dynamically allocated centered string. * * @note The returned string must be freed using `free()` when no longer needed. */ static char *_str_center(const char *s1, int l2) { char *s2; int i, j, l1; l1 = strlen(s1); s2 = (char *)malloc(l2 + 8); /* we add 8 instead of 1 to avoid problems with sse/avx optimizations and valgrind*/ for (i = 0; i < (l2 - l1) / 2; i++) s2[i] = ' '; for (j = 0; j < l1 && i < l2; j++, i++) s2[i] = s1[j]; for (; i < l2; i++) s2[i] = ' '; s2[l2] = '\0'; return s2; } /** * @brief Writes a centered header to a write_iter struct * with a fixed width of 24 characters. * * @param w Pointer to the write_iter struct. * @param s Pointer to the string representing the header. */ void write_iter_header_work(write_iter *w, const char *s) { char *c; const size_t fixed_str_len = 24; c = _str_center(s, fixed_str_len); write_iter_string_work(w, c); free(c); } /* Functions called from FORTRAN */ extern "C" void FC_FUNC_(write_iter_init, WRITE_ITER_INIT)(void **v, const fint *i, const double *d, STR_F_TYPE fname STR_ARG1) { write_iter *w; w = (write_iter *)malloc(sizeof(write_iter)); TO_C_STR1(fname, w->filename); w->buf = NULL; w->pos = w->size = 0; w->iter = *i; w->dt = *d; *v = w; } extern "C" void FC_FUNC_(write_iter_clear, WRITE_ITER_CLEAR)(void **v) { write_iter *w = (write_iter *)*v; if (creat(w->filename, 0666) == -1) { std::cerr << "Could not create file '" << w->filename << "' (" << strerror(errno) << ")" << std::endl; exit(1); } } extern "C" void FC_FUNC_(write_iter_flush, WRITE_ITER_FLUSH)(void **v) { int fd; write_iter *w = (write_iter *)*v; if (!w->buf) return; fd = open(w->filename, O_WRONLY | O_CREAT | O_APPEND, 0666); if (fd == -1) { std::cerr << "Could not open file '" << w->filename << "' (" << strerror(errno) << ")" << std::endl; exit(1); } write(fd, w->buf, w->pos); close(fd); w->pos = 0; } extern "C" void FC_FUNC_(write_iter_end, WRITE_ITER_END)(void **v) { write_iter *w = (write_iter *)*v; FC_FUNC_(write_iter_flush, WRITE_ITER_FLUSH)(v); free(w->filename); if (w->buf) free(w->buf); free(w); } extern "C" void FC_FUNC_(write_iter_start, WRITE_ITER_START)(void **v) { write_iter *w = (write_iter *)*v; write_iter_realloc(w, 8 + 24); sprintf(w->buf + w->pos, "%8u%24.16e", (unsigned)(w->iter), w->iter * w->dt); w->pos += 8 + 24; w->iter++; } extern "C" void FC_FUNC_(write_iter_set, WRITE_ITER_SET)(void **v, const fint *i) { write_iter *w = (write_iter *)*v; w->iter = *i; } extern "C" void FC_FUNC_(write_iter_double_1, WRITE_ITER_DOUBLE_1)(void **v, const double *d, const fint *no) { write_iter *w = (write_iter *)*v; int i; write_iter_realloc(w, (*no) * 24); for (i = 0; i < *no; i++) { sprintf(w->buf + w->pos, "%24.16e", d[i]); w->pos += 24; } } extern "C" void FC_FUNC_(write_iter_float_1, WRITE_ITER_FLOAT_1)(void **v, const float *d, const fint *no) { write_iter *w = (write_iter *)*v; int i; write_iter_realloc(w, (*no) * 24); for (i = 0; i < *no; i++) { sprintf(w->buf + w->pos, "%24.16e", d[i]); w->pos += 24; } } extern "C" void FC_FUNC_(write_iter_double_n, WRITE_ITER_DOUBLE_N)(void **v, const double *d, const fint *no) { write_iter *w = (write_iter *)*v; int i; write_iter_realloc(w, (*no) * 24); for (i = 0; i < *no; i++) { sprintf(w->buf + w->pos, "%24.16e", d[i]); w->pos += 24; } } extern "C" void FC_FUNC_(write_iter_float_n, WRITE_ITER_FLOAT_N)(void **v, const float *d, const fint *no) { write_iter *w = (write_iter *)*v; int i; write_iter_realloc(w, (*no) * 24); for (i = 0; i < *no; i++) { sprintf(w->buf + w->pos, "%24.16e", d[i]); w->pos += 24; } } extern "C" void FC_FUNC_(write_iter_int_1, WRITE_ITER_INT_1)(void **v, const fint *d, const fint *no) { write_iter *w = (write_iter *)*v; int i; write_iter_realloc(w, (*no) * 8); for (i = 0; i < *no; i++) { sprintf(w->buf + w->pos, "%8d", d[i]); w->pos += 8; } } extern "C" void FC_FUNC_(write_iter_int_n, WRITE_ITER_INT_N)(void **v, const fint *d, const fint *no) { write_iter *w = (write_iter *)*v; int i; write_iter_realloc(w, (*no) * 8); for (i = 0; i < *no; i++) { sprintf(w->buf + w->pos, "%8d", d[i]); w->pos += 8; } } extern "C" void FC_FUNC_(write_iter_string, WRITE_ITER_STRING)(void **v, STR_F_TYPE s STR_ARG1) { char *c; TO_C_STR1(s, c); write_iter_string_work((write_iter *)*v, c); free(c); } extern "C" void FC_FUNC_(write_iter_header_start, WRITE_ITER_HEADER_START)(void **v) { write_iter *w = (write_iter *)*v; write_iter_string_work(w, "# Iter "); write_iter_header_work(w, "t"); } extern "C" void FC_FUNC_(write_iter_header, WRITE_ITER_HEADER)(void **v, STR_F_TYPE s STR_ARG1) { char *c; TO_C_STR1(s, c); write_iter_header_work((write_iter *)*v, c); free(c); } extern "C" void FC_FUNC_(write_iter_nl, WRITE_ITER_NL)(void **v) { write_iter_string_work((write_iter *)*v, "\n"); }
0
ALLM/M3/octopus/src
ALLM/M3/octopus/src/fdep/fortran_dependencies.pl
#!/usr/bin/env perl # # Copyright 2015 Lorenz Hüdepohl # # This file is part of fdep and licensed under the MIT license # see the file LICENSE for more information # use strict; use warnings; my %defs = (); my %uses = (); my %incs = (); my %files = (); # mode is the first argument: either mod or inc my $mode = shift; my $use_re = qr/^\s*use\s+(\S+)\s*$/; my $def_re = qr/^\s*(?:submodule|module)\s+(\S+)\s*$/; my $inc_re = qr/^\s*(\S+)\s*$/; sub add_use { my ($file, $module) = @_; if (defined($defs{$module}) && $defs{$module} eq $file) { # do not add self-dependencies return; } if (!defined($uses{$file})) { $uses{$file} = { $module => 1 }; } else { $uses{$file}{$module} = 1; } } sub add_def { my ($file, $module) = @_; if (!defined($defs{$module})) { $defs{$module} = $file; if (defined($uses{$file}) && defined($uses{$file}{$module})) { delete $uses{$file}{$module}; } } else { die "Module $module both defined in $file, $defs{$module}"; } } sub add_inc { my ($file, $module) = @_; if (!defined($incs{$file})) { $incs{$file} = { $module => 1 }; } else { $incs{$file}{$module} = 1; } } my $target = shift; foreach my $file (<>) { chomp($file); if (exists $files{$file}) { next; } else { $files{$file} = 1; } my $re; my $add; my $object; my $type; if (defined($ENV{V}) && $ENV{V} ge "2") { print STDERR "fdep: Considering file $file for target $target\n"; } if ($file =~ /^.*\.\/.fortran_dependencies\/(.*)\.def_mods[^.]*(\..*)$/) { $re = $def_re; $add = \&add_def; $object = $1 . $2; $type = 'DEF' } elsif ($file =~ /^.*\.\/.fortran_dependencies\/(.*)\.use_mods[^.]*(\..*)$/) { $re = $use_re; $add = \&add_use; $object = $1 . $2; $type = 'USE' } elsif ($file =~ /^.*\.\/.fortran_dependencies\/(.*)\.inc_mods[^.]*(\..*)$/) { $re = $inc_re; $add = \&add_inc; $object = $1 . $2; $type = 'INC' } else { die "Unrecognized file extension for '$file'"; } open(FILE,"<",$file) || die "\nCan't open $file: $!\n\n"; while(<FILE>) { chomp; if ($type eq "DEF" or $type eq "USE") { $_ = lc($_); } if ($_ =~ $re) { &$add($object, $1); } else { die "At $file:$.\nCannot parse module statement '$_', was expecting $re"; } } close(FILE) } # module dependencies if (lc($mode) eq 'mod') { foreach my $object (sort keys %uses) { for my $m (keys %{$uses{$object}}) { if (defined $defs{$m}) { print "$object: ", $defs{$m}, "\n"; } elsif (defined($ENV{V}) && $ENV{V} ge "1") { print STDERR "Warning: Cannot find definition of module $m in files for current target $target, might be external\n"; } } } # include file dependencies } elsif (lc($mode) eq 'inc') { foreach my $object (sort keys %incs) { for my $m (keys %{$incs{$object}}) { # This could be done in a more generic way to find the include files print "$object: ", glob($m), "\n"; } } }
0
ALLM/M3/octopus/src
ALLM/M3/octopus/src/grid/allocate_hardware_aware.cc
/* Copyright (C) 2019,2023 S. Ohlmann 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, 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "fortran_types.h" #include "vectors.h" #include <config.h> #include <iostream> #include <stdio.h> #include <stdlib.h> #ifdef HAVE_CUDA #ifdef HAVE_HIP #include <hip/hip_runtime.h> #define cuGetErrorName hipDrvGetErrorName #define cuMemAllocHost hipMemAllocHost #define cuMemFreeHost hipHostFree #define CUresult hipError_t #define CUDA_SUCCESS hipSuccess #else #include <cuda.h> #endif #define CUDA_SAFE_CALL(x) \ do { \ CUresult result = x; \ if (result != CUDA_SUCCESS) { \ const char *msg; \ cuGetErrorName(result, &msg); \ std::cerr << "\nerror: " #x " failed with error " << msg << '\n'; \ exit(1); \ } \ } while (0) #endif #ifdef __GLIBC__ #include <malloc.h> static int initialized = 0; static size_t threshold = 102400; // initial threshold at 100 kB #endif using namespace std; void *allocate_aligned(fint8 size_bytes) { #ifdef __GLIBC__ // do this only for glibc (which is default on Linux) if(!initialized || (size_t)size_bytes < threshold) { // set threshold to use mmap to less than the size to be allocated // to make sure that all batches are allocated using mmap // this circumvents heap fragmentation problems with aligned memory // also make sure we set this at least once in the beginning threshold = min(threshold, (size_t)(0.9*size_bytes)); int success = mallopt(M_MMAP_THRESHOLD, threshold); if(!success) { printf("Error setting mmap threshold option!\n"); printf("You might run into an out-of-memory condition because of heap fragmentation.\n"); printf("This can be caused by allocating aligned memory with posix_memalign in between other allocations.\n"); } initialized = 1; } #endif #ifdef DEBUG_ALLOC printf("Allocating %d bytes, unpinned.\n", (size_t)size_bytes); #endif void *aligned; int status; // align on vector size to improve vectorization status = posix_memalign(&aligned, (size_t)sizeof(double) * VEC_SIZE, (size_t)size_bytes); if (status != 0) { printf("Error allocating aligned memory!\n"); return NULL; } return aligned; } extern "C" void *dallocate_aligned(fint8 size) { return allocate_aligned(sizeof(double) * size); } extern "C" void *zallocate_aligned(fint8 size) { return allocate_aligned(sizeof(double) * 2 * size); } extern "C" void *sallocate_aligned(fint8 size) { return allocate_aligned(sizeof(float) * size); } extern "C" void *callocate_aligned(fint8 size) { return allocate_aligned(sizeof(float) * 2 * size); } extern "C" void deallocate_aligned(void *array) { #ifdef DEBUG_ALLOC printf("Deallocating unpinned.\n"); #endif free(array); } void *allocate_pinned(fint8 size_bytes) { #ifdef HAVE_CUDA #ifdef DEBUG_ALLOC printf("Allocating %d bytes, pinned.\n", (size_t)size_bytes); #endif void *pinned; CUDA_SAFE_CALL(cuMemAllocHost(&pinned, (size_t)size_bytes)); return pinned; #else printf("Error! Pinned memory requested, although CUDA not available. " "Returning aligned memory.\n"); return allocate_aligned(size_bytes); #endif } extern "C" void *dallocate_pinned(fint8 size) { return allocate_pinned(sizeof(double) * size); } extern "C" void *zallocate_pinned(fint8 size) { return allocate_pinned(sizeof(double) * 2 * size); } extern "C" void *sallocate_pinned(fint8 size) { return allocate_pinned(sizeof(float) * size); } extern "C" void *callocate_pinned(fint8 size) { return allocate_pinned(sizeof(float) * 2 * size); } extern "C" void deallocate_pinned(void *array) { #ifdef HAVE_CUDA #ifdef DEBUG_ALLOC printf("Deallocating pinned.\n"); #endif CUDA_SAFE_CALL(cuMemFreeHost(array)); #endif }
0
ALLM/M3/octopus/src
ALLM/M3/octopus/src/grid/hilbert.c
/* Copyright (C) 2013 X. Andrade Copyright (C) 2021 S. Ohlmann 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, 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <assert.h> /* This code is based on the implementation of the Hilbert curves presented in: J. Skilling, Programming the Hilbert curve, AIP Conf. Proc. 707, 381 (2004); http://dx.doi.org/10.1063/1.1751381 */ void Int4toTranspose(const int dim, const int h, int bits, int *x) { /* the code uses some funny way of storing the bits */ int idir, ibit, ifbit; for (idir = 0; idir < dim; idir++) x[idir] = 0; ifbit = 0; for (ibit = 0; ibit < bits; ibit++) { for (idir = dim - 1; idir >= 0; idir--) { x[idir] += (((h >> ifbit) & 1) << ibit); ifbit++; } } } void InttoTranspose(const int dim, const long long int h, int bits, int *x) { /* the code uses some funny way of storing the bits */ int idir, ibit, ifbit; for (idir = 0; idir < dim; idir++) x[idir] = 0; ifbit = 0; for (ibit = 0; ibit < bits; ibit++) { for (idir = dim - 1; idir >= 0; idir--) { x[idir] += (((h >> ifbit) & 1) << ibit); ifbit++; } } } void TransposetoAxes(int *X, int b, int n) { /* position, #bits, dimension */ int N = 2 << (b - 1), P, Q, t; int i; /* Gray decode by H ^ (H/2) */ t = X[n - 1] >> 1; for (i = n - 1; i > 0; i--) X[i] ^= X[i - 1]; X[0] ^= t; /* Undo excess work */ for (Q = 2; Q != N; Q <<= 1) { P = Q - 1; for (i = n - 1; i >= 0; i--) { if (X[i] & Q) { X[0] ^= P; /* invert */ } else { t = (X[0] ^ X[i]) & P; X[0] ^= t; X[i] ^= t; /* exchange */ } } } } void TransposetoInt(const int dim, long long int *h, int bits, int *x) { /* the code uses some funny way of storing the bits */ int idir, ibit, ifbit; *h = 0; ifbit = 0; for (ibit = 0; ibit < bits; ibit++) { for (idir = dim - 1; idir >= 0; idir--) { *h += (((x[idir] >> ibit) & 1) << ifbit); ifbit++; } } } void TransposetoInt4(const int dim, int *h, int bits, int *x) { /* the code uses some funny way of storing the bits */ int idir, ibit, ifbit; *h = 0; ifbit = 0; for (ibit = 0; ibit < bits; ibit++) { for (idir = dim - 1; idir >= 0; idir--) { *h += (((x[idir] >> ibit) & 1) << ifbit); ifbit++; } } } void AxestoTranspose(int *X, int b, int n) { /* position, #bits, dimension */ int M = 1 << (b - 1), P, Q, t; int i; /* Inverse undo */ for (Q = M; Q > 1; Q >>= 1) { P = Q - 1; for (i = 0; i < n; i++) { if (X[i] & Q) X[0] ^= P; /* invert */ else { /* exchange */ t = (X[0] ^ X[i]) & P; X[0] ^= t; X[i] ^= t; } } } /* Gray encode */ for (i = 1; i < n; i++) X[i] ^= X[i - 1]; t = 0; for (Q = M; Q > 1; Q >>= 1) if (X[n - 1] & Q) t ^= Q - 1; for (i = 0; i < n; i++) X[i] ^= t; } /* 64 bit integer versions */ void FC_FUNC_(hilbert_index_to_point, HILBERT_INDEX_TO_POINT)(const int *dim, const int *nbits, const long long int *index, int *point) { InttoTranspose(*dim, *index, *nbits, point); TransposetoAxes(point, *nbits, *dim); } void FC_FUNC_(hilbert_point_to_index, HILBERT_POINT_TO_INDEX)(const int *dim, const int *nbits, long long int *index, const int *point) { /* copy point to not overwrite original data */ int point_copy[*dim]; for (int i = 0; i < *dim; i++) point_copy[i] = point[i]; AxestoTranspose(point_copy, *nbits, *dim); TransposetoInt(*dim, index, *nbits, point_copy); } /* 32 bit integer versions */ void FC_FUNC_(hilbert_index_to_point_int, HILBERT_INDEX_TO_POINT_INT)(const int *dim, const int *nbits, const int *index, int *point) { Int4toTranspose(*dim, *index, *nbits, point); TransposetoAxes(point, *nbits, *dim); } void FC_FUNC_(hilbert_point_to_index_int, HILBERT_POINT_TO_INDEX_INT)(const int *dim, const int *nbits, int *index, const int *point) { /* copy point to not overwrite original data */ int point_copy[*dim]; for (int i = 0; i < *dim; i++) point_copy[i] = point[i]; AxestoTranspose(point_copy, *nbits, *dim); TransposetoInt4(*dim, index, *nbits, point_copy); }
0
ALLM/M3/octopus/src
ALLM/M3/octopus/src/grid/operate.c
/* Copyright (C) 2006 X. Andrade 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, 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <stddef.h> #include <assert.h> #include <vectors.h> /** * @brief Operates over * @param[in] opn * @param[in] w * @param[in] opnri * @param[in] opri * @param[in] rimap_inv * @param[in] fi * @param[in] ldfp * @param[out] fo * */ void FC_FUNC_(doperate_ri_vec, DOPERATE_RI_VEC)(const int *opn, const double *restrict w, const int *opnri, const int *opri, const int *rimap_inv, const int *rimap_inv_max, const double *restrict fi, const int *ldfp, double *restrict fo) { const size_t ldf = ldfp[0]; /* check whether we got aligned vectors or not */ int aligned = 1; aligned = aligned && (((long long)fi) % (8 * VEC_SIZE) == 0); aligned = aligned && (((long long)fo) % (8 * VEC_SIZE) == 0); aligned = aligned && ((1 << ldf) % VEC_SIZE == 0); if (aligned) { #define ALIGNED #include "operate_inc.c" #undef ALIGNED } else { /* not aligned */ #include "operate_inc.c" } } /* the same as doperate_ri_vec, but allows giving each an appropriate Fortan interface in which fi and fo are actually complex in Fortran Could be inline, but in that case pgcc will not put it in the symbol table. */ void FC_FUNC_(zoperate_ri_vec, ZOPERATE_RI_VEC)(const int *opn, const double *restrict w, const int *opnri, const int *opri, const int *rimap_inv, const int *rimap_inv_max, const double *restrict fi, const int *ldfp, double *restrict fo) { FC_FUNC_(doperate_ri_vec, DOPERATE_RI_VEC) (opn, w, opnri, opri, rimap_inv, rimap_inv_max, fi, ldfp, fo); } void FC_FUNC_(dgauss_seidel, DGAUSS_SEIDEL)(const int *opn, const double *restrict w, const int *opnri, const int *opri, const int *rimap_inv, const int *rimap_inv_max, const double *restrict factor, double *pot, const double *restrict rho) { const int n = opn[0]; const int nri = opnri[0]; int l, i, j; const int *index; register double a0; register const double fac = *factor; for (l = 0; l < nri; l++) { index = opri + n * l; i = rimap_inv[l]; for (; i < rimap_inv_max[l]; i++) { a0 = 0.0; for (j = 0; j < n; j++) a0 += w[j] * pot[i + index[j]]; pot[i] += fac * (a0 - rho[i]); } } }
0
ALLM/M3/octopus/src
ALLM/M3/octopus/src/grid/operate_inc.c
/* Copyright (C) 2006 X. Andrade 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, 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifdef ALIGNED #define LOAD VEC_LD #define STORE VEC_ST #else #define LOAD VEC_LDU #define STORE VEC_STU #endif { const ptrdiff_t n = opn[0]; const ptrdiff_t nri = opnri[0]; #if DEPTH >= 32 const ptrdiff_t unroll32 = max1(32 * VEC_SIZE >> ldf); #endif #if DEPTH >= 16 const ptrdiff_t unroll16 = max1(16 * VEC_SIZE >> ldf); #endif #if DEPTH >= 8 const ptrdiff_t unroll8 = max1(8 * VEC_SIZE >> ldf); #endif #if DEPTH >= 4 const ptrdiff_t unroll4 = max1(4 * VEC_SIZE >> ldf); #endif #if DEPTH >= 2 const ptrdiff_t unroll2 = max1(2 * VEC_SIZE >> ldf); #endif #if DEPTH >= 1 const ptrdiff_t unroll1 = max1(1 * VEC_SIZE >> ldf); #endif ptrdiff_t l, i, j; const int *restrict index; for (l = 0; l < nri; l++) { index = opri + n * l; i = rimap_inv[l]; #if DEPTH >= 32 for (; i < (rimap_inv_max[l] - unroll32 + 1); i += unroll32) { ptrdiff_t k; for (k = 0; k < (1 << ldf); k += 32 * VEC_SIZE) { register VEC_TYPE a0, a1, a2, a3; register VEC_TYPE a4, a5, a6, a7; register VEC_TYPE a8, a9, aa, ab; register VEC_TYPE ac, ad, ae, af; register VEC_TYPE b0, b1, b2, b3; register VEC_TYPE b4, b5, b6, b7; register VEC_TYPE b8, b9, ba, bb; register VEC_TYPE bc, bd, be, bf; a0 = a1 = a2 = a3 = VEC_ZERO; a4 = a5 = a6 = a7 = VEC_ZERO; a8 = a9 = aa = ab = VEC_ZERO; ac = ad = ae = af = VEC_ZERO; b0 = b1 = b2 = b3 = VEC_ZERO; b4 = b5 = b6 = b7 = VEC_ZERO; b8 = b9 = ba = bb = VEC_ZERO; bc = bd = be = bf = VEC_ZERO; for (j = 0; j < n; j++) { #ifdef VEC_SCAL_LD register VEC_TYPE wj = VEC_SCAL_LD(w + j); #else register VEC_TYPE wj = VEC_SCAL(w[j]); #endif ptrdiff_t indexj = (index[j] + i) << ldf; a0 = VEC_FMA(wj, LOAD(fi + indexj + k), a0); a1 = VEC_FMA(wj, LOAD(fi + indexj + 1 * VEC_SIZE + k), a1); a2 = VEC_FMA(wj, LOAD(fi + indexj + 2 * VEC_SIZE + k), a2); a3 = VEC_FMA(wj, LOAD(fi + indexj + 3 * VEC_SIZE + k), a3); a4 = VEC_FMA(wj, LOAD(fi + indexj + 4 * VEC_SIZE + k), a4); a5 = VEC_FMA(wj, LOAD(fi + indexj + 5 * VEC_SIZE + k), a5); a6 = VEC_FMA(wj, LOAD(fi + indexj + 6 * VEC_SIZE + k), a6); a7 = VEC_FMA(wj, LOAD(fi + indexj + 7 * VEC_SIZE + k), a7); a8 = VEC_FMA(wj, LOAD(fi + indexj + 8 * VEC_SIZE + k), a8); a9 = VEC_FMA(wj, LOAD(fi + indexj + 9 * VEC_SIZE + k), a9); aa = VEC_FMA(wj, LOAD(fi + indexj + 10 * VEC_SIZE + k), aa); ab = VEC_FMA(wj, LOAD(fi + indexj + 11 * VEC_SIZE + k), ab); ac = VEC_FMA(wj, LOAD(fi + indexj + 12 * VEC_SIZE + k), ac); ad = VEC_FMA(wj, LOAD(fi + indexj + 13 * VEC_SIZE + k), ad); ae = VEC_FMA(wj, LOAD(fi + indexj + 14 * VEC_SIZE + k), ae); af = VEC_FMA(wj, LOAD(fi + indexj + 15 * VEC_SIZE + k), af); b0 = VEC_FMA(wj, LOAD(fi + indexj + 16 * VEC_SIZE + k), b0); b1 = VEC_FMA(wj, LOAD(fi + indexj + 17 * VEC_SIZE + k), b1); b2 = VEC_FMA(wj, LOAD(fi + indexj + 18 * VEC_SIZE + k), b2); b3 = VEC_FMA(wj, LOAD(fi + indexj + 19 * VEC_SIZE + k), b3); b4 = VEC_FMA(wj, LOAD(fi + indexj + 20 * VEC_SIZE + k), b4); b5 = VEC_FMA(wj, LOAD(fi + indexj + 21 * VEC_SIZE + k), b5); b6 = VEC_FMA(wj, LOAD(fi + indexj + 22 * VEC_SIZE + k), b6); b7 = VEC_FMA(wj, LOAD(fi + indexj + 23 * VEC_SIZE + k), b7); b8 = VEC_FMA(wj, LOAD(fi + indexj + 24 * VEC_SIZE + k), b8); b9 = VEC_FMA(wj, LOAD(fi + indexj + 25 * VEC_SIZE + k), b9); ba = VEC_FMA(wj, LOAD(fi + indexj + 26 * VEC_SIZE + k), ba); bb = VEC_FMA(wj, LOAD(fi + indexj + 27 * VEC_SIZE + k), bb); bc = VEC_FMA(wj, LOAD(fi + indexj + 28 * VEC_SIZE + k), bc); bd = VEC_FMA(wj, LOAD(fi + indexj + 29 * VEC_SIZE + k), bd); be = VEC_FMA(wj, LOAD(fi + indexj + 30 * VEC_SIZE + k), be); bf = VEC_FMA(wj, LOAD(fi + indexj + 31 * VEC_SIZE + k), bf); } STORE(fo + (i << ldf) + k, a0); STORE(fo + (i << ldf) + 1 * VEC_SIZE + k, a1); STORE(fo + (i << ldf) + 2 * VEC_SIZE + k, a2); STORE(fo + (i << ldf) + 3 * VEC_SIZE + k, a3); STORE(fo + (i << ldf) + 4 * VEC_SIZE + k, a4); STORE(fo + (i << ldf) + 5 * VEC_SIZE + k, a5); STORE(fo + (i << ldf) + 6 * VEC_SIZE + k, a6); STORE(fo + (i << ldf) + 7 * VEC_SIZE + k, a7); STORE(fo + (i << ldf) + 8 * VEC_SIZE + k, a8); STORE(fo + (i << ldf) + 9 * VEC_SIZE + k, a9); STORE(fo + (i << ldf) + 10 * VEC_SIZE + k, aa); STORE(fo + (i << ldf) + 11 * VEC_SIZE + k, ab); STORE(fo + (i << ldf) + 12 * VEC_SIZE + k, ac); STORE(fo + (i << ldf) + 13 * VEC_SIZE + k, ad); STORE(fo + (i << ldf) + 14 * VEC_SIZE + k, ae); STORE(fo + (i << ldf) + 15 * VEC_SIZE + k, af); STORE(fo + (i << ldf) + 16 * VEC_SIZE + k, b0); STORE(fo + (i << ldf) + 17 * VEC_SIZE + k, b1); STORE(fo + (i << ldf) + 18 * VEC_SIZE + k, b2); STORE(fo + (i << ldf) + 19 * VEC_SIZE + k, b3); STORE(fo + (i << ldf) + 20 * VEC_SIZE + k, b4); STORE(fo + (i << ldf) + 21 * VEC_SIZE + k, b5); STORE(fo + (i << ldf) + 22 * VEC_SIZE + k, b6); STORE(fo + (i << ldf) + 23 * VEC_SIZE + k, b7); STORE(fo + (i << ldf) + 24 * VEC_SIZE + k, b8); STORE(fo + (i << ldf) + 25 * VEC_SIZE + k, b9); STORE(fo + (i << ldf) + 26 * VEC_SIZE + k, ba); STORE(fo + (i << ldf) + 27 * VEC_SIZE + k, bb); STORE(fo + (i << ldf) + 28 * VEC_SIZE + k, bc); STORE(fo + (i << ldf) + 29 * VEC_SIZE + k, bd); STORE(fo + (i << ldf) + 30 * VEC_SIZE + k, be); STORE(fo + (i << ldf) + 31 * VEC_SIZE + k, bf); } } #endif #if DEPTH >= 16 for (; i < (rimap_inv_max[l] - unroll16 + 1); i += unroll16) { ptrdiff_t k; for (k = 0; k < (1 << ldf); k += 16 * VEC_SIZE) { register VEC_TYPE a0, a1, a2, a3; register VEC_TYPE a4, a5, a6, a7; register VEC_TYPE a8, a9, aa, ab; register VEC_TYPE ac, ad, ae, af; a0 = a1 = a2 = a3 = VEC_ZERO; a4 = a5 = a6 = a7 = VEC_ZERO; a8 = a9 = aa = ab = VEC_ZERO; ac = ad = ae = af = VEC_ZERO; for (j = 0; j < n; j++) { #ifdef VEC_SCAL_LD register VEC_TYPE wj = VEC_SCAL_LD(w + j); #else register VEC_TYPE wj = VEC_SCAL(w[j]); #endif ptrdiff_t indexj = (index[j] + i) << ldf; a0 = VEC_FMA(wj, LOAD(fi + indexj + k), a0); a1 = VEC_FMA(wj, LOAD(fi + indexj + 1 * VEC_SIZE + k), a1); a2 = VEC_FMA(wj, LOAD(fi + indexj + 2 * VEC_SIZE + k), a2); a3 = VEC_FMA(wj, LOAD(fi + indexj + 3 * VEC_SIZE + k), a3); a4 = VEC_FMA(wj, LOAD(fi + indexj + 4 * VEC_SIZE + k), a4); a5 = VEC_FMA(wj, LOAD(fi + indexj + 5 * VEC_SIZE + k), a5); a6 = VEC_FMA(wj, LOAD(fi + indexj + 6 * VEC_SIZE + k), a6); a7 = VEC_FMA(wj, LOAD(fi + indexj + 7 * VEC_SIZE + k), a7); a8 = VEC_FMA(wj, LOAD(fi + indexj + 8 * VEC_SIZE + k), a8); a9 = VEC_FMA(wj, LOAD(fi + indexj + 9 * VEC_SIZE + k), a9); aa = VEC_FMA(wj, LOAD(fi + indexj + 10 * VEC_SIZE + k), aa); ab = VEC_FMA(wj, LOAD(fi + indexj + 11 * VEC_SIZE + k), ab); ac = VEC_FMA(wj, LOAD(fi + indexj + 12 * VEC_SIZE + k), ac); ad = VEC_FMA(wj, LOAD(fi + indexj + 13 * VEC_SIZE + k), ad); ae = VEC_FMA(wj, LOAD(fi + indexj + 14 * VEC_SIZE + k), ae); af = VEC_FMA(wj, LOAD(fi + indexj + 15 * VEC_SIZE + k), af); } STORE(fo + (i << ldf) + k, a0); STORE(fo + (i << ldf) + 1 * VEC_SIZE + k, a1); STORE(fo + (i << ldf) + 2 * VEC_SIZE + k, a2); STORE(fo + (i << ldf) + 3 * VEC_SIZE + k, a3); STORE(fo + (i << ldf) + 4 * VEC_SIZE + k, a4); STORE(fo + (i << ldf) + 5 * VEC_SIZE + k, a5); STORE(fo + (i << ldf) + 6 * VEC_SIZE + k, a6); STORE(fo + (i << ldf) + 7 * VEC_SIZE + k, a7); STORE(fo + (i << ldf) + 8 * VEC_SIZE + k, a8); STORE(fo + (i << ldf) + 9 * VEC_SIZE + k, a9); STORE(fo + (i << ldf) + 10 * VEC_SIZE + k, aa); STORE(fo + (i << ldf) + 11 * VEC_SIZE + k, ab); STORE(fo + (i << ldf) + 12 * VEC_SIZE + k, ac); STORE(fo + (i << ldf) + 13 * VEC_SIZE + k, ad); STORE(fo + (i << ldf) + 14 * VEC_SIZE + k, ae); STORE(fo + (i << ldf) + 15 * VEC_SIZE + k, af); } } #endif #if DEPTH >= 8 for (; i < (rimap_inv_max[l] - unroll8 + 1); i += unroll8) { ptrdiff_t k; for (k = 0; k < (1 << ldf); k += 8 * VEC_SIZE) { register VEC_TYPE a0, a1, a2, a3; register VEC_TYPE a4, a5, a6, a7; a0 = a1 = a2 = a3 = VEC_ZERO; a4 = a5 = a6 = a7 = VEC_ZERO; for (j = 0; j < n; j++) { #ifdef VEC_SCAL_LD register VEC_TYPE wj = VEC_SCAL_LD(w + j); #else register VEC_TYPE wj = VEC_SCAL(w[j]); #endif ptrdiff_t indexj = (index[j] + i) << ldf; a0 = VEC_FMA(wj, LOAD(fi + indexj + k), a0); a1 = VEC_FMA(wj, LOAD(fi + indexj + 1 * VEC_SIZE + k), a1); a2 = VEC_FMA(wj, LOAD(fi + indexj + 2 * VEC_SIZE + k), a2); a3 = VEC_FMA(wj, LOAD(fi + indexj + 3 * VEC_SIZE + k), a3); a4 = VEC_FMA(wj, LOAD(fi + indexj + 4 * VEC_SIZE + k), a4); a5 = VEC_FMA(wj, LOAD(fi + indexj + 5 * VEC_SIZE + k), a5); a6 = VEC_FMA(wj, LOAD(fi + indexj + 6 * VEC_SIZE + k), a6); a7 = VEC_FMA(wj, LOAD(fi + indexj + 7 * VEC_SIZE + k), a7); } STORE(fo + (i << ldf) + k, a0); STORE(fo + (i << ldf) + 1 * VEC_SIZE + k, a1); STORE(fo + (i << ldf) + 2 * VEC_SIZE + k, a2); STORE(fo + (i << ldf) + 3 * VEC_SIZE + k, a3); STORE(fo + (i << ldf) + 4 * VEC_SIZE + k, a4); STORE(fo + (i << ldf) + 5 * VEC_SIZE + k, a5); STORE(fo + (i << ldf) + 6 * VEC_SIZE + k, a6); STORE(fo + (i << ldf) + 7 * VEC_SIZE + k, a7); } } #endif #if DEPTH >= 4 for (; i < (rimap_inv_max[l] - unroll4 + 1); i += unroll4) { ptrdiff_t k; for (k = 0; k < (1 << ldf); k += 4 * VEC_SIZE) { register VEC_TYPE a0, a1, a2, a3; a0 = a1 = a2 = a3 = VEC_ZERO; for (j = 0; j < n; j++) { #ifdef VEC_SCAL_LD register VEC_TYPE wj = VEC_SCAL_LD(w + j); #else register VEC_TYPE wj = VEC_SCAL(w[j]); #endif ptrdiff_t indexj = (index[j] + i) << ldf; a0 = VEC_FMA(wj, LOAD(fi + indexj + k), a0); a1 = VEC_FMA(wj, LOAD(fi + indexj + 1 * VEC_SIZE + k), a1); a2 = VEC_FMA(wj, LOAD(fi + indexj + 2 * VEC_SIZE + k), a2); a3 = VEC_FMA(wj, LOAD(fi + indexj + 3 * VEC_SIZE + k), a3); } STORE(fo + (i << ldf) + k, a0); STORE(fo + (i << ldf) + 1 * VEC_SIZE + k, a1); STORE(fo + (i << ldf) + 2 * VEC_SIZE + k, a2); STORE(fo + (i << ldf) + 3 * VEC_SIZE + k, a3); } } #endif #if DEPTH >= 2 for (; i < (rimap_inv_max[l] - unroll2 + 1); i += unroll2) { ptrdiff_t k; for (k = 0; k < (1 << ldf); k += 2 * VEC_SIZE) { register VEC_TYPE a0, a1; a0 = a1 = VEC_ZERO; for (j = 0; j < n; j++) { #ifdef VEC_SCAL_LD register VEC_TYPE wj = VEC_SCAL_LD(w + j); #else register VEC_TYPE wj = VEC_SCAL(w[j]); #endif ptrdiff_t indexj = (index[j] + i) << ldf; a0 = VEC_FMA(wj, LOAD(fi + indexj + k), a0); a1 = VEC_FMA(wj, LOAD(fi + indexj + 1 * VEC_SIZE + k), a1); } STORE(fo + (i << ldf) + k, a0); STORE(fo + (i << ldf) + 1 * VEC_SIZE + k, a1); } } #endif #if DEPTH >= 1 for (; i < (rimap_inv_max[l] - unroll1 + 1); i += unroll1) { ptrdiff_t k; for (k = 0; k < (1 << ldf); k += VEC_SIZE) { register VEC_TYPE a0 = VEC_ZERO; for (j = 0; j < n; j++) { #ifdef VEC_SCAL_LD register VEC_TYPE wj = VEC_SCAL_LD(w + j); #else register VEC_TYPE wj = VEC_SCAL(w[j]); #endif ptrdiff_t indexj = (index[j] + i) << ldf; a0 = VEC_FMA(wj, LOAD(fi + indexj + k), a0); } STORE(fo + (i << ldf) + k, a0); } } #endif #if VEC_SIZE > 1 for (; i < rimap_inv_max[l]; i++) { ptrdiff_t k; for (k = 0; k < (1 << ldf); k++) { double a = 0.0; for (j = 0; j < n; j++) a += w[j] * fi[((index[j] + i) << ldf) + k]; fo[(i << ldf) + k] = a; } } #endif } /* l */ // this fence instruction is needed to ensure correctness when using // non-temporal stores #if defined(ALIGNED) && defined(FENCE) FENCE; #endif } #undef LOAD #undef STORE
0
ALLM/M3/octopus/src
ALLM/M3/octopus/src/hamiltonian/vdw_ts_low.c
/* ** Copyright (C) 2015 Xavier Andrade, Carlos Borca, Alfredo Correa ** ** This library is free software: you can redistribute it and/or modify ** it under the terms of the GNU Lesser General Public License as published by ** the Free Software Foundation, either version 3 of the License, or ** (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU Lesser General Public License for more details. ** ** You should have received a copy of the GNU Lesser General Public License ** along with this program. If not, see <http://www.gnu.org/licenses/>. ** */ #include <math.h> #include <stdio.h> #ifndef _TEST #include "config.h" #endif /* Function to retrieve Van der Waals parameters of the free atoms. */ void get_vdw_params(const int zatom, double *c6, double *alpha, double *r0) { switch (zatom) { // Hydrogen (H) case 1: *alpha = 4.500000; *c6 = 6.500000; *r0 = 3.100000; break; // Helium (He) case 2: *alpha = 1.380000; *c6 = 1.460000; *r0 = 2.650000; break; // Lithium (Li) case 3: *alpha = 164.200000; *c6 = 1387.000000; *r0 = 4.160000; break; // Berillium (Be) case 4: *alpha = 38.000000; *c6 = 214.000000; *r0 = 4.170000; break; // Boron (B) case 5: *alpha = 21.000000; *c6 = 99.500000; *r0 = 3.890000; break; // Carbon (C) case 6: *alpha = 12.000000; *c6 = 46.600000; *r0 = 3.590000; break; // Nitrogen (N) case 7: *alpha = 7.400000; *c6 = 24.200000; *r0 = 3.340000; break; // Oxygen (O) case 8: *alpha = 5.400000; *c6 = 15.600000; *r0 = 3.190000; break; // Fluorine (F) case 9: *alpha = 3.800000; *c6 = 9.520000; *r0 = 3.040000; break; // Neon (Ne) case 10: *alpha = 2.670000; *c6 = 6.380000; *r0 = 2.910000; break; // Sodium (Na) case 11: *alpha = 162.700000; *c6 = 1556.000000; *r0 = 3.730000; break; // Magnesium (Mg) case 12: *alpha = 71.000000; *c6 = 627.000000; *r0 = 4.270000; break; // Aluminium (Al) case 13: *alpha = 60.000000; *c6 = 528.000000; *r0 = 4.330000; break; // Silicon (Si) case 14: *alpha = 37.000000; *c6 = 305.000000; *r0 = 4.200000; break; // Phosphorus (P) case 15: *alpha = 25.000000; *c6 = 185.000000; *r0 = 4.010000; break; // Sulphur (S) case 16: *alpha = 19.600000; *c6 = 134.000000; *r0 = 3.860000; break; // Clorine (Cl) case 17: *alpha = 15.000000; *c6 = 94.600000; *r0 = 3.710000; break; // Argon (Ar) case 18: *alpha = 11.100000; *c6 = 64.300000; *r0 = 3.550000; break; // Potassium (K) case 19: *alpha = 292.900000; *c6 = 3897.000000; *r0 = 3.710000; break; // Calcium (Ca) case 20: *alpha = 160.000000; *c6 = 2221.000000; *r0 = 4.650000; break; // Scandium (Sc) case 21: *alpha = 120.000000; *c6 = 1383.000000; *r0 = 4.590000; break; // Titanium (Ti) case 22: *alpha = 98.000000; *c6 = 1044.000000; *r0 = 4.510000; break; // Vanadium (V) case 23: *alpha = 84.000000; *c6 = 832.000000; *r0 = 4.440000; break; // Chromium (Cr) case 24: *alpha = 78.000000; *c6 = 602.000000; *r0 = 3.990000; break; // Manganese (Mn) case 25: *alpha = 63.000000; *c6 = 552.000000; *r0 = 3.970000; break; // Iron (Fe) case 26: *alpha = 56.000000; *c6 = 482.000000; *r0 = 4.230000; break; // Cobalt (Co) case 27: *alpha = 50.000000; *c6 = 408.000000; *r0 = 4.180000; break; // Nickel (Ni) case 28: *alpha = 48.000000; *c6 = 373.000000; *r0 = 3.820000; break; // Copper (Cu) case 29: *alpha = 42.000000; *c6 = 253.000000; *r0 = 3.760000; break; // Zinc (Zn) case 30: *alpha = 40.000000; *c6 = 284.000000; *r0 = 4.020000; break; // Gallium (Ga) case 31: *alpha = 60.000000; *c6 = 498.000000; *r0 = 4.190000; break; // Germanium (Ge) case 32: *alpha = 41.000000; *c6 = 354.000000; *r0 = 4.200000; break; // Arsenic (As) case 33: *alpha = 29.000000; *c6 = 246.000000; *r0 = 4.110000; break; // Selenium (Se) case 34: *alpha = 25.000000; *c6 = 210.000000; *r0 = 4.040000; break; // Bromine (Br) case 35: *alpha = 20.000000; *c6 = 162.000000; *r0 = 3.930000; break; // Krypton (Kr) case 36: *alpha = 16.800000; *c6 = 129.600000; *r0 = 3.820000; break; // Rubidium (Rb) case 37: *alpha = 319.200000; *c6 = 4691.000000; *r0 = 3.720000; break; // Strontium (Sr) case 38: *alpha = 199.000000; *c6 = 3170.000000; *r0 = 4.540000; break; // Elements from 39 - Yttrium (Y) to 44 Ruthenium (Ru) are not included. // Rhodium (Rh) case 45: *alpha = 56.1; *c6 = 469.0; *r0 = 3.95; break; // Palladium (Pd) case 46: *alpha = 23.680000; *c6 = 157.500000; *r0 = 3.66000; break; // Silver (Ag) case 47: *alpha = 50.600000; *c6 = 339.000000; *r0 = 3.820000; break; // Cadmium (Cd) case 48: *alpha = 39.7; *c6 = 452.0; *r0 = 3.99; break; // Elements from 49 - Indium (In) to 51 - Antimony (Sb) are not included. // Tellurium (Te) case 52: *alpha = 37.65; *c6 = 396.0; *r0 = 4.22; break; // Iodine (I) case 53: *alpha = 35.000000; *c6 = 385.000000; *r0 = 4.170000; break; // Xenon (Xe) case 54: *alpha = 27.300000; *c6 = 285.900000; *r0 = 4.080000; break; // Element 55 - Caesium (Cs) is not included. // Barium (Ba) case 56: *alpha = 275.0; *c6 = 5727.0; *r0 = 4.77; break; // Elements from 57 - Lanthanum (La) to 76 - Osmium (Os) are not included. // Iridium (Ir) case 77: *alpha = 42.51; *c6 = 359.1; *r0 = 4.00; break; // Platinum (Pt) case 78: *alpha = 39.68; *c6 = 347.1; *r0 = 3.92; break; // Gold (Au) case 79: *alpha = 36.5; *c6 = 298.0; *r0 = 3.86; break; // Mercury (Hg) case 80: *alpha = 33.9; *c6 = 392.0; *r0 = 3.98; break; // Element 81 - Thallium (Tl) is not included. // Lead (Pb) case 82: *alpha = 61.8; *c6 = 697.0; *r0 = 4.31; break; // Bismuth (Bi) case 83: *alpha = 49.02; *c6 = 571.0; *r0 = 4.32; // Elements from 84 - Polonium (Po) to 118 - Ununoctium (Uuo) are not // included. } } /* Damping function. */ void fdamp(const double rr, const double r0ab, const double dd, const double sr, double *ff, double *dffdrab, double *dffdr0) { // Calculate the damping coefficient. double ee = exp(-dd * ((rr / (sr * r0ab)) - 1.0)); *ff = 1.0 / (1.0 + ee); double dee = ee * (*ff) * (*ff); // Calculate the derivative of the damping function with respect to the // distance between atoms A and B. *dffdrab = (dd / (sr * r0ab)) * dee; // Calculate the derivative of the damping function with respect to the // distance between the van der Waals radius. *dffdr0 = -dd * rr / (sr * r0ab * r0ab) * dee; } /* Calculation of the square of separations. */ void distance(const int iatom, const int jatom, const double coordinates[], double *rr, double *rr2, double *rr6, double *rr7) { double x_ij = coordinates[3 * iatom + 0] - coordinates[3 * jatom + 0]; double y_ij = coordinates[3 * iatom + 1] - coordinates[3 * jatom + 1]; double z_ij = coordinates[3 * iatom + 2] - coordinates[3 * jatom + 2]; *rr2 = x_ij * x_ij + y_ij * y_ij + z_ij * z_ij; *rr6 = rr2[0] * rr2[0] * rr2[0]; // This is the same as: *rr6 = (*rr2)*(*rr2)*(*rr2) *rr = sqrt(rr2[0]); // This is the same as: *rr = sqrt(*rr2) *rr7 = rr6[0] * rr[0]; // This is the same as: *rr6 = (*rr6)*(*rr) // Print information controls. // printf("R_(%i-%i)= %f\n", iatom+1, jatom+1, *rr); // printf("R_(%i-%i)^2 = %f\n", iatom+1, jatom+1, *rr2); // printf("R_(%i-%i)^6 = %f\n", iatom+1, jatom+1, *rr6); } /* Function to calculate the Van der Waals energy... and forces */ void vdw_calculate(const int natoms, const double dd, const double sr, const int zatom[], const double coordinates[], const double volume_ratio[], double *energy, double force[], double derivative_coeff[]) { int ia; *energy = 0.0; // Loop to calculate the pair-wise Van der Waals energy correction. for (ia = 0; ia < natoms; ia++) { double c6_a, alpha_a, r0_a; int ib; force[3 * ia + 0] = 0.0; force[3 * ia + 1] = 0.0; force[3 * ia + 2] = 0.0; derivative_coeff[ia] = 0.0; get_vdw_params(zatom[ia], &c6_a, &alpha_a, &r0_a); for (ib = 0; ib < natoms; ib++) { double c6_b, alpha_b, r0_b; if (ia == ib) continue; // Pair-wise calculation of separations. double rr, rr2, rr6, rr7; distance(ia, ib, coordinates, &rr, &rr2, &rr6, &rr7); get_vdw_params(zatom[ib], &c6_b, &alpha_b, &r0_b); // Determination of c6abfree, for isolated atoms a and b. double num = 2.0 * c6_a * c6_b; double den = (alpha_b / alpha_a) * c6_a + (alpha_a / alpha_b) * c6_b; double c6abfree = num / den; // Determination of the effective c6 coefficient. double c6abeff = volume_ratio[ia] * volume_ratio[ib] * c6abfree; // Determination of the effective radius of atom a. double r0ab = cbrt(volume_ratio[ia]) * r0_a + cbrt(volume_ratio[ib]) * r0_b; // Pair-wise calculation of the damping coefficient double ff; double dffdrab; double dffdr0; fdamp(rr, r0ab, dd, sr, &ff, &dffdrab, &dffdr0); // Pair-wise correction to energy. *energy += -0.5 * ff * c6abeff / rr6; // Calculation of the pair-wise partial energy derivative with respect to // the distance between atoms A and B. double deabdrab = dffdrab * c6abeff / rr6 - 6.0 * ff * c6abeff / rr7; // Derivative of the AB van der Waals separation with respect to the // volume ratio of atom A. double dr0dvra = r0_a / (3.0 * pow(volume_ratio[ia], 2.0 / 3.0)); // Derivative of the damping function with respecto to the volume ratio of // atom A. double dffdvra = dffdr0 * dr0dvra; // Calculation of the pair-wise partial energy derivative with respect to // the volume ratio of atom A. double deabdvra = dffdvra * c6abeff / rr6 + ff * volume_ratio[ib] * c6abfree / rr6; force[3 * ia + 0] += deabdrab * (coordinates[3 * ia + 0] - coordinates[3 * ib + 0]) / rr; force[3 * ia + 1] += deabdrab * (coordinates[3 * ia + 1] - coordinates[3 * ib + 1]) / rr; force[3 * ia + 2] += deabdrab * (coordinates[3 * ia + 2] - coordinates[3 * ib + 2]) / rr; derivative_coeff[ia] += deabdvra; // Print information controls. // printf("Distance between atoms %i and %i = %f.\n", ia+1, ib+1, rr); // printf("Atom %i, c6= %f, alpha= %f, r0= %f.\n", ia+1, c6_a, alpha_a, // r0_a); printf("Atom %i, c6= %f, alpha= %f, r0= %f.\n", ib+1, c6_b, // alpha_b, r0_b); printf("For atoms %i and %i, c6abeff= %f.\n", ia+1, // ib+1, c6abfree); } } // printf("THE FINAL VAN DER WAALS ENERGY CORRECTION IS = %f.\n", *energy); // printf("THE FINAL VAN DER WAALS FORCE CORRECTION IS = %f.\n", *force); } #ifndef _TEST /* This is a wrapper to be called from Fortran. */ void FC_FUNC_(f90_vdw_calculate, F90_VDW_CALCULATE)(const int *natoms, const double *dd, const double *sr, const int zatom[], const double coordinates[], const double volume_ratio[], double *energy, double force[], double derivative_coeff[]) { vdw_calculate(*natoms, *dd, *sr, zatom, coordinates, volume_ratio, energy, force, derivative_coeff); } #endif /* Main test function. */ #ifdef _TEST int main() { const int natoms = 3; const int zatom[] = {23, 29, 31}; const double volume_ratio[] = {1.0, 1.0, 1.0}; double energy; double force[natoms * 3]; double derivative_coeff[natoms]; double x; for (x = 0.1; x < 10; x += 0.1) { double coordinates[] = {0.2, -0.3, 0.5, -0.7, 1.1, -1.3, x, 0.0, 0.0}; vdw_calculate(natoms, zatom, coordinates, volume_ratio, &energy, force, derivative_coeff); coordinates[5] += 0.001; double energy_2; vdw_calculate(natoms, zatom, coordinates, volume_ratio, &energy_2, force, derivative_coeff); } } #endif
0
ALLM/M3/octopus/src
ALLM/M3/octopus/src/include/fortran_types.h
/* Copyright (C) 2013 X. Andrade 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, 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #ifndef __FORTRAN_TYPES_H__ #define __FORTRAN_TYPES_H__ typedef int fint; typedef int fint4; typedef long long int fint8; typedef char fchar; #endif
0
ALLM/M3/octopus/src
ALLM/M3/octopus/src/include/global.h
!! Copyright (C) 2003-2006 M. Marques, A. Castro, A. Rubio, G. Bertsch !! !! 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, 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., 51 Franklin Street, Fifth Floor, Boston, MA !! 02110-1301, USA. !! #include "config_F90.h" #include "options.h" #include "defaults.h" ! If the compiler accepts long Fortran lines, it is better to use that ! capacity, and build all the preprocessor definitions in one line. In ! this way, the debuggers will provide the right line numbers. #if defined(LONG_LINES) # define _newline_ # define _anl_ #else # define _newline_ \newline # define _anl_ & \newline #endif ! If the compiler accepts line number markers, then "CARDINAL" and "ACARDINAL" ! will put them. Otherwise, just a new line or a ampersand plus a new line. ! These macros should be used in macros that span several lines. They should by ! put immedialty before a line where a compilation error might occur and at the ! end of the macro. ! Note that the "cardinal" and "newline" words are substituted by the program ! preprocess.pl by the ampersand and by a real new line just before compilation. #if defined(LONG_LINES) # define CARDINAL # define ACARDINAL #else # if defined(F90_ACCEPTS_LINE_NUMBERS) # define CARDINAL _newline_\cardinal __LINE__ __FILE__ _newline_ # define ACARDINAL _anl_\cardinal __LINE__ __FILE__ _newline_ # else # define CARDINAL _newline_ # define ACARDINAL _anl_ # endif #endif ! The assertions are ignored if the code is compiled in not-debug mode (NDEBUG ! is defined). Otherwise it is merely a logical assertion that, when fails, ! prints out the assertion string, the file, and the line. The subroutine ! assert_die is in the global_m module. #if !defined(NDEBUG) # define ASSERT(expr) \ if(.not.(expr)) ACARDINAL \ call assert_die(TOSTRING(expr), ACARDINAL __FILE__, ACARDINAL __LINE__) \ CARDINAL #else # define ASSERT(expr) #endif ! Some compilers will not have the sizeof intrinsic. #ifdef HAVE_FC_SIZEOF # define FC_SIZEOF(x) sizeof(x) #else # define FC_SIZEOF(x) 1 #endif ! In octopus, one should normally use the SAFE_(DE)ALLOCATE macros below, which emit ! a helpful error if the allocation or deallocation fails. They also take care of ! calling the memory profiler. The "MY_DEALLOCATE" macro is only used in this file; ! in the code, one should use SAFE_DEALLOCATE_P for pointers and SAFE_DEALLOCATE_A ! for arrays. ! A special version of the SAFE_ALLOCATE macro named SAFE_ALLOCATE_TYPE is also ! provided to allocate a polymorphic variable. This is necessary because of the ! special Fortran syntax "type::var". #if defined(NDEBUG) # define SAFE_ALLOCATE(x) allocate(x) # define SAFE_ALLOCATE_TYPE(type, x) allocate(type::x) # define SAFE_ALLOCATE_TYPE_ARRAY(type, x, bounds) allocate(type::x bounds) # define SAFE_ALLOCATE_SOURCE(x, y) \ allocate(x, source=y); CARDINAL \ CARDINAL # define SAFE_ALLOCATE_SOURCE_A(x, y) \ if(allocated(y)) then; CARDINAL \ allocate(x, source=y); CARDINAL \ end if; \ CARDINAL # define SAFE_ALLOCATE_SOURCE_P(x, y) \ if(associated(y)) then; CARDINAL \ allocate(x, source=y); CARDINAL \ else; CARDINAL \ nullify(x); CARDINAL \ end if; \ CARDINAL # define SAFE_DEALLOCATE_P(x) \ if(associated(x)) then; CARDINAL \ deallocate(x); CARDINAL \ nullify(x); CARDINAL \ end if; \ CARDINAL # define SAFE_DEALLOCATE_A(x) \ if(allocated(x)) then; CARDINAL \ deallocate(x); CARDINAL \ end if; \ CARDINAL #else # define SAFE_ALLOCATE_PROFILE(x) \ if(not_in_openmp() .and. iand(prof_vars%mode, PROFILING_MEMORY).ne.0 .or. global_alloc_err.ne.0) ACARDINAL \ global_sizeof = FC_SIZEOF( ACARDINAL x ACARDINAL ); CARDINAL \ if(iand(prof_vars%mode, PROFILING_MEMORY).ne.0) ACARDINAL \ call profiling_memory_allocate(ACARDINAL TOSTRING(x), ACARDINAL __FILE__, ACARDINAL __LINE__, ACARDINAL global_sizeof); CARDINAL \ if(global_alloc_err.ne.0) ACARDINAL \ call alloc_error(global_sizeof, ACARDINAL __FILE__, ACARDINAL __LINE__); \ CARDINAL # define SAFE_ALLOCATE(x) \ allocate( ACARDINAL x, ACARDINAL stat=global_alloc_err); CARDINAL \ SAFE_ALLOCATE_PROFILE(x) # define SAFE_ALLOCATE_TYPE(type, x) \ allocate( ACARDINAL type::x, ACARDINAL stat=global_alloc_err); CARDINAL \ SAFE_ALLOCATE_PROFILE(x) ! Some versions of GCC have a bug in the sizeof() function such that the compiler crashes with a ICE ! when passing a polymorphic variable to the function and explicit array bounds are given. ! The workaround is not to pass the bounds to sizeof. Otherwise we could just use SAFE_ALLOCATE_TYPE. # define SAFE_ALLOCATE_TYPE_ARRAY(type, x, bounds) \ allocate( ACARDINAL type::x bounds, ACARDINAL stat=global_alloc_err); CARDINAL \ if(not_in_openmp() .and. iand(prof_vars%mode, PROFILING_MEMORY).ne.0 .or. global_alloc_err.ne.0) ACARDINAL \ global_sizeof = FC_SIZEOF( ACARDINAL x ACARDINAL ); CARDINAL \ if(iand(prof_vars%mode, PROFILING_MEMORY).ne.0) ACARDINAL \ call profiling_memory_allocate(ACARDINAL TOSTRING(x)+TOSTRING(bounds), ACARDINAL __FILE__, ACARDINAL __LINE__, ACARDINAL global_sizeof); CARDINAL \ if(global_alloc_err.ne.0) ACARDINAL \ call alloc_error(global_sizeof, ACARDINAL __FILE__, ACARDINAL __LINE__); \ CARDINAL # define SAFE_ALLOCATE_SOURCE_P(x, y) \ if(associated(y)) then; CARDINAL \ allocate( ACARDINAL x, ACARDINAL source=y, ACARDINAL stat=global_alloc_err); CARDINAL \ SAFE_ALLOCATE_PROFILE(x); CARDINAL \ else; CARDINAL \ nullify(x); CARDINAL \ end if; \ CARDINAL # define SAFE_ALLOCATE_SOURCE_A(x, y) \ if(allocated(y)) then; CARDINAL \ allocate( ACARDINAL x, ACARDINAL source=y, ACARDINAL stat=global_alloc_err); CARDINAL \ SAFE_ALLOCATE_PROFILE(x); CARDINAL \ end if; \ CARDINAL # define SAFE_ALLOCATE_SOURCE(x, y) \ allocate( ACARDINAL x, ACARDINAL source=y, ACARDINAL stat=global_alloc_err); CARDINAL \ SAFE_ALLOCATE_PROFILE(x); CARDINAL \ CARDINAL # define MY_DEALLOCATE(x) \ global_sizeof = FC_SIZEOF(x) ; \ CARDINAL \ deallocate(x, stat=global_alloc_err, errmsg=global_alloc_errmsg); CARDINAL \ if(not_in_openmp() .and. iand(prof_vars%mode, PROFILING_MEMORY).ne.0) ACARDINAL \ call profiling_memory_deallocate(TOSTRING(x), ACARDINAL __FILE__, ACARDINAL __LINE__, ACARDINAL global_sizeof); CARDINAL \ if(global_alloc_err.ne.0) then; CARDINAL \ write(stderr,'(a)') global_alloc_errmsg; CARDINAL \ call dealloc_error(global_sizeof, ACARDINAL __FILE__, ACARDINAL __LINE__); CARDINAL \ end if; \ CARDINAL # define SAFE_DEALLOCATE_P(x) \ if(associated(x)) then; CARDINAL \ MY_DEALLOCATE(x); CARDINAL \ nullify(x); CARDINAL \ end if; \ CARDINAL # define SAFE_DEALLOCATE_A(x) \ if(allocated(x)) then; CARDINAL \ MY_DEALLOCATE(x); CARDINAL \ end if; \ CARDINAL #endif #define SAFE_TOL(x, tol) sign(max(abs(x),tol),x) ! the TOSTRING macro converts a macro into a string ! do not use the STRINGIFY macro #define STRINGIFY(x) #x #define TOSTRING(x) STRINGIFY(x) ! Whenever a procedure is not called too many times, one should start it ! and finish it with the PUSH_SUB and POP_SUB macros, which are these ! pieces of code that call the push_sub and pop_sub routines defined ! in the messages_m module. #ifndef NDEBUG #define PUSH_SUB(routine) \ if(debug%trace) then; if(not_in_openmp()) then; CARDINAL \ call debug_push_sub(__FILE__+"." ACARDINAL +TOSTRING(routine)); CARDINAL \ endif; endif; \ CARDINAL #define POP_SUB(routine) \ if(debug%trace) then; if(not_in_openmp()) then; CARDINAL \ call debug_pop_sub(__FILE__+"." ACARDINAL +TOSTRING(routine)); CARDINAL \ endif; endif; \ CARDINAL #else #define PUSH_SUB(routine) #define POP_SUB(routine) #endif #define PUSH_SUB_WITH_PROFILE(routine) \ PUSH_SUB(routine) CARDINAL \ call profiling_in(TOSTRING(routine)); CARDINAL #define POP_SUB_WITH_PROFILE(routine) \ call profiling_out(TOSTRING(routine)); CARDINAL \ POP_SUB(routine) CARDINAL !! Local Variables: !! mode: f90 !! coding: utf-8 !! End:
0
ALLM/M3/octopus/src
ALLM/M3/octopus/src/include/vectors.h
/* Copyright (C) 2010 X. Andrade 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, 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #ifndef VECTORS_H #define VECTORS_H #ifdef __AVX__ // Check for intel avx #if defined(__AVX512F__) || defined(__AVX512PF__) || \ defined(__AVX512BW__) || defined(__AVX512ER__) || \ defined(__AVX512CD__) || defined(__AVX512DQ__) || \ defined(__AVX512VL__) // Use AVX512 #include <immintrin.h> #define VEC_SIZE 8 #define VEC_TYPE __m512d #define VEC_LD(addr) _mm512_load_pd(addr) #define VEC_LDU(addr) _mm512_loadu_pd(addr) #define VEC_ST(addr, vec) _mm512_stream_pd(addr, vec) #define VEC_STU(addr, vec) _mm512_storeu_pd(addr, vec) #define VEC_FMA(aa, bb, cc) _mm512_fmadd_pd(aa, bb, cc) #define VEC_SCAL(aa) _mm512_set1_pd(aa) #define VEC_ZERO _mm512_setzero_pd() #include <emmintrin.h> #define FENCE _mm_mfence() #define DEPTH 16 #elif defined(__AVX2__) // Use AVX2 #include <immintrin.h> #if defined(__FMA4__) || defined(__FMA__) #include <x86intrin.h> #endif #define VEC_SIZE 4 #define VEC_TYPE __m256d #define VEC_LD(addr) _mm256_load_pd(addr) #define VEC_LDU(addr) _mm256_loadu_pd(addr) #define VEC_ST(addr, vec) _mm256_stream_pd(addr, vec) #define VEC_STU(addr, vec) _mm256_storeu_pd(addr, vec) #ifdef __FMA4__ #define VEC_FMA(aa, bb, cc) _mm256_macc_pd(aa, bb, cc) #elif defined(__FMA__) #define VEC_FMA(aa, bb, cc) _mm256_fmadd_pd(aa, bb, cc) #else #define VEC_FMA(aa, bb, cc) _mm256_add_pd(cc, _mm256_mul_pd(aa, bb)) #endif #define VEC_SCAL(aa) _mm256_set1_pd(aa) #define VEC_ZERO _mm256_setzero_pd() #include <emmintrin.h> #define FENCE _mm_mfence() #define DEPTH 16 #else // Default to AVX #include <emmintrin.h> #if defined(__FMA4__) || defined(__FMA__) #include <x86intrin.h> #endif #define VEC_SIZE 2 #define VEC_TYPE __m128d #define VEC_LD(addr) _mm_load_pd(addr) #define VEC_LDU(addr) _mm_loadu_pd(addr) #define VEC_ST(addr, vec) _mm_stream_pd(addr, vec) #define VEC_STU(addr, vec) _mm_storeu_pd(addr, vec) #ifdef __FMA4__ #define VEC_FMA(aa, bb, cc) _mm_macc_pd(aa, bb, cc) #elif defined(__FMA__) #define VEC_FMA(aa, bb, cc) _mm_fmadd_pd(aa, bb, cc) #else #define VEC_FMA(aa, bb, cc) _mm_add_pd(cc, _mm_mul_pd(aa, bb)) #endif #define VEC_SCAL(aa) _mm_set1_pd(aa) #define VEC_ZERO _mm_setzero_pd() #define FENCE _mm_mfence() #define DEPTH 16 #endif #elif defined(__bg__) // Check for ibm blue_gene #ifdef __bgq__ // Check for blue_gene_q #define VEC_SIZE 4 #define VEC_TYPE vector4double #define VEC_LD(addr) vec_ld(0, (double *)(addr)) #define VEC_LDU(addr) \ ((vector4double){(addr)[0], (addr)[1], (addr)[2], (addr)[3]}) #define VEC_ST(addr, vec) vec_st(vec, 0, (double *)(addr)) #define VEC_STU(addr, vec) \ (addr)[0] = vec_extract(vec, 0); \ (addr)[1] = vec_extract(vec, 1); \ (addr)[2] = vec_extract(vec, 2); \ (addr)[3] = vec_extract(vec, 3) #define VEC_FMA(aa, bb, cc) vec_madd(aa, bb, cc) #define VEC_SCAL(aa) ((vector4double){aa, aa, aa, aa}) #define VEC_SCAL_LD(addr) vec_lds(0, (double *)(addr)) #define VEC_ZERO ((vector4double){0.0, 0.0, 0.0, 0.0}) #define DEPTH 16 #else // Otherwise use default blue_gene #define VEC_SIZE 2 #define VEC_TYPE double _Complex #define VEC_LD(addr) __lfpd(addr) #define VEC_LDU(addr) __cmplx((addr)[0], (addr)[1]) #define VEC_ST(addr, vec) __stfpd(addr, vec) #define VEC_STU(addr, vec) \ (addr)[0] = __creal(vec); \ (addr)[1] = __cimag(vec) #define VEC_FMA(aa, bb, cc) __fpmadd(cc, aa, bb) #define VEC_SCAL(aa) __cmplx(aa, aa) #define VEC_ZERO __cmplx(0.0, 0.0) #define DEPTH 16 #endif #else // Not explicitly optimized #define VEC_SIZE 1 #define VEC_TYPE double #define VEC_LD(addr) (addr)[0] #define VEC_LDU(addr) VEC_LD(addr) #define VEC_ST(addr, vec) (addr)[0] = vec #define VEC_STU(addr, vec) VEC_ST(addr, vec) #define VEC_FMA(aa, bb, cc) aa *bb + cc #define VEC_SCAL(aa) aa #define VEC_ZERO 0.0 #define DEPTH 8 #endif #define max1(x) (((x) > 0) ? (x) : 1) #endif
0
ALLM/M3/octopus/src
ALLM/M3/octopus/src/ions/symmetries_finite.c
/* * Brute force symmetry analyzer. * This is actually C++ program, masquerading as a C one! * * (C) 2011 X. Andrade Converted to a Fortran library. * (C) 1996, 2003 S. Patchkovskii, Serguei.Patchkovskii@sympatico.ca * * 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., 675 Mass Ave, Cambridge, MA 02139, USA. * * Revision 1.16 2003/04/04 13:05:03 patchkov * Revision 1.15 2000/01/25 16:47:17 patchkov * Revision 1.14 2000/01/25 16:39:08 patchkov * Revision 1.13 1996/05/24 12:32:08 ps * Revision 1.12 1996/05/23 16:10:47 ps * First reasonably stable version. * */ #include <config.h> #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <string_f.h> #define DIMENSION 3 #define MAXPARAM 7 typedef struct { int type; double x[DIMENSION]; } ATOM; /* * All specific structures should have corresponding elements in the * same position generic structure does. * * Planes are characterized by the surface normal direction * (taken in the direction *from* the coordinate origin) * and distance from the coordinate origin to the plane * in the direction of the surface normal. * * Inversion is characterized by location of the inversion center. * * Rotation is characterized by a vector (distance+direction) from the origin * to the rotation axis, axis direction and rotation order. Rotations * are in the clockwise direction looking opposite to the direction * of the axis. Note that this definition of the rotation axis * is *not* unique, since an arbitrary multiple of the axis direction * can be added to the position vector without changing actual operation. * * Mirror rotation is defined by the same parameters as normal rotation, * but the origin is now unambiguous since it defines the position of the * plane associated with the axis. * */ typedef struct _SYMMETRY_ELEMENT_ { void (*transform_atom)(struct _SYMMETRY_ELEMENT_ *el, ATOM *from, ATOM *to); int *transform; /* Correspondence table for the transformation */ int order; /* Applying transformation this many times is identity */ int nparam; /* 4 for inversion and planes, 7 for axes */ double maxdev; /* Larges error associated with the element */ double distance; double normal[DIMENSION]; double direction[DIMENSION]; } SYMMETRY_ELEMENT; typedef struct { char *group_name; /* Canonical group name */ char *symmetry_code; /* Group symmetry code */ int (*check)(void); /* Additional verification routine, not used */ } POINT_GROUP; static double ToleranceSame = 1e-3; static double TolerancePrimary = 5e-2; static double ToleranceFinal = 1e-4; static double MaxOptStep = 5e-1; static double MinOptStep = 1e-7; static double GradientStep = 1e-7; static double OptChangeThreshold = 1e-10; static double CenterOfSomething[DIMENSION]; static double *DistanceFromCenter = NULL; static int verbose = 0; static int MaxOptCycles = 200; static int OptChangeHits = 5; static int MaxAxisOrder = 20; static int AtomsCount = 0; static ATOM *Atoms = NULL; static int PlanesCount = 0; static SYMMETRY_ELEMENT **Planes = NULL; static SYMMETRY_ELEMENT *MolecularPlane = NULL; static int InversionCentersCount = 0; static SYMMETRY_ELEMENT **InversionCenters = NULL; static int NormalAxesCount = 0; static SYMMETRY_ELEMENT **NormalAxes = NULL; static int ImproperAxesCount = 0; static SYMMETRY_ELEMENT **ImproperAxes = NULL; static int *NormalAxesCounts = NULL; static int *ImproperAxesCounts = NULL; static int BadOptimization = 0; static char *SymmetryCode = NULL; /*"" ;*/ /* * Statistics */ static long StatTotal = 0; static long StatEarly = 0; static long StatPairs = 0; static long StatDups = 0; static long StatOrder = 0; static long StatOpt = 0; static long StatAccept = 0; /* * Point groups I know about */ int true(void) { return 1; } POINT_GROUP PointGroups[] = { {"C1", "", true}, {"Cs", "(sigma) ", true}, {"Ci", "(i) ", true}, {"C2", "(C2) ", true}, {"C3", "(C3) ", true}, {"C4", "(C4) (C2) ", true}, {"C5", "(C5) ", true}, {"C6", "(C6) (C3) (C2) ", true}, {"C7", "(C7) ", true}, {"C8", "(C8) (C4) (C2) ", true}, {"D2", "3*(C2) ", true}, {"D3", "(C3) 3*(C2) ", true}, {"D4", "(C4) 5*(C2) ", true}, {"D5", "(C5) 5*(C2) ", true}, {"D6", "(C6) (C3) 7*(C2) ", true}, {"D7", "(C7) 7*(C2) ", true}, {"D8", "(C8) (C4) 9*(C2) ", true}, {"C2v", "(C2) 2*(sigma) ", true}, {"C3v", "(C3) 3*(sigma) ", true}, {"C4v", "(C4) (C2) 4*(sigma) ", true}, {"C5v", "(C5) 5*(sigma) ", true}, {"C6v", "(C6) (C3) (C2) 6*(sigma) ", true}, {"C7v", "(C7) 7*(sigma) ", true}, {"C8v", "(C8) (C4) (C2) 8*(sigma) ", true}, {"C2h", "(i) (C2) (sigma) ", true}, {"C3h", "(C3) (S3) (sigma) ", true}, {"C4h", "(i) (C4) (C2) (S4) (sigma) ", true}, {"C5h", "(C5) (S5) (sigma) ", true}, {"C6h", "(i) (C6) (C3) (C2) (S6) (S3) (sigma) ", true}, {"C7h", "(C7) (S7) (sigma) ", true}, {"C8h", "(i) (C8) (C4) (C2) (S8) (S4) (sigma) ", true}, {"D2h", "(i) 3*(C2) 3*(sigma) ", true}, {"D3h", "(C3) 3*(C2) (S3) 4*(sigma) ", true}, {"D4h", "(i) (C4) 5*(C2) (S4) 5*(sigma) ", true}, {"D5h", "(C5) 5*(C2) (S5) 6*(sigma) ", true}, {"D6h", "(i) (C6) (C3) 7*(C2) (S6) (S3) 7*(sigma) ", true}, {"D7h", "(C7) 7*(C2) (S7) 8*(sigma) ", true}, {"D8h", "(i) (C8) (C4) 9*(C2) (S8) (S4) 9*(sigma) ", true}, {"D2d", "3*(C2) (S4) 2*(sigma) ", true}, {"D3d", "(i) (C3) 3*(C2) (S6) 3*(sigma) ", true}, {"D4d", "(C4) 5*(C2) (S8) 4*(sigma) ", true}, {"D5d", "(i) (C5) 5*(C2) (S10) 5*(sigma) ", true}, {"D6d", "(C6) (C3) 7*(C2) (S12) (S4) 6*(sigma) ", true}, {"D7d", "(i) (C7) 7*(C2) (S14) 7*(sigma) ", true}, {"D8d", "(C8) (C4) 9*(C2) (S16) 8*(sigma) ", true}, {"S4", "(C2) (S4) ", true}, {"S6", "(i) (C3) (S6) ", true}, {"S8", "(C4) (C2) (S8) ", true}, {"T", "4*(C3) 3*(C2) ", true}, {"Th", "(i) 4*(C3) 3*(C2) 4*(S6) 3*(sigma) ", true}, {"Td", "4*(C3) 3*(C2) 3*(S4) 6*(sigma) ", true}, {"O", "3*(C4) 4*(C3) 9*(C2) ", true}, {"Oh", "(i) 3*(C4) 4*(C3) 9*(C2) 4*(S6) 3*(S4) 9*(sigma) ", true}, {"Cinfv", "(Cinf) (sigma) ", true}, {"Dinfh", "(i) (Cinf) (C2) 2*(sigma) ", true}, {"I", "6*(C5) 10*(C3) 15*(C2) ", true}, {"Ih", "(i) 6*(C5) 10*(C3) 15*(C2) 6*(S10) 10*(S6) 15*(sigma) ", true}, {"Kh", "(i) (Cinf) (sigma) ", true}, }; #define PointGroupsCount (sizeof(PointGroups) / sizeof(POINT_GROUP)) char *PointGroupRejectionReason = NULL; /* * Generic functions */ double pow2(double x) { return x * x; } int establish_pairs(SYMMETRY_ELEMENT *elem) { int i, j, k, best_j; char *atom_used = calloc(AtomsCount, 1); double distance, best_distance; ATOM symmetric; if (atom_used == NULL) { fprintf(stderr, "Out of memory for tagging array in establish_pairs()\n"); exit(EXIT_FAILURE); } for (i = 0; i < AtomsCount; i++) { if (elem->transform[i] >= AtomsCount) { /* No symmetric atom yet */ if (verbose > 2) printf(" looking for a pair for %d\n", i); elem->transform_atom(elem, Atoms + i, &symmetric); if (verbose > 2) printf(" new coordinates are: (%g,%g,%g)\n", symmetric.x[0], symmetric.x[1], symmetric.x[2]); best_j = i; best_distance = 2 * TolerancePrimary; /* Performance value we'll reject */ for (j = 0; j < AtomsCount; j++) { if (Atoms[j].type != symmetric.type || atom_used[j]) continue; for (k = 0, distance = 0; k < DIMENSION; k++) { distance += pow2(symmetric.x[k] - Atoms[j].x[k]); } distance = sqrt(distance); if (verbose > 2) printf(" distance to %d is %g\n", j, distance); if (distance < best_distance) { best_j = j; best_distance = distance; } } if (best_distance > TolerancePrimary) { /* Too bad, there is no symmetric atom */ if (verbose > 0) printf(" no pair for atom %d - best was %d with err = %g\n", i, best_j, best_distance); free(atom_used); return -1; } elem->transform[i] = best_j; atom_used[best_j] = 1; if (verbose > 1) printf(" atom %d transforms to the atom %d, err = %g\n", i, best_j, best_distance); } } free(atom_used); return 0; } int check_transform_order(SYMMETRY_ELEMENT *elem) { int i, j, k; void rotate_reflect_atom(SYMMETRY_ELEMENT *, ATOM *, ATOM *); for (i = 0; i < AtomsCount; i++) { if (elem->transform[i] == i) /* Identity transform is Ok for any order */ continue; if (elem->transform_atom == rotate_reflect_atom) { j = elem->transform[i]; if (elem->transform[j] == i) continue; /* Second-order transform is Ok for improper axis */ } for (j = elem->order - 1, k = elem->transform[i]; j > 0; j--, k = elem->transform[k]) { if (k == i) { if (verbose > 0) printf(" transform looped %d steps too early from atom %d\n", j, i); return -1; } } if (k != i && elem->transform_atom == rotate_reflect_atom) { /* For improper axes, the complete loop may also take twice the order */ for (j = elem->order; j > 0; j--, k = elem->transform[k]) { if (k == i) { if (verbose > 0) printf(" (improper) transform looped %d steps too early " "from atom %d\n", j, i); return -1; } } } if (k != i) { if (verbose > 0) printf(" transform failed to loop after %d steps from atom %d\n", elem->order, i); return -1; } } return 0; } int same_transform(SYMMETRY_ELEMENT *a, SYMMETRY_ELEMENT *b) { int i, j; int code; if ((a->order != b->order) || (a->nparam != b->nparam) || (a->transform_atom != b->transform_atom)) return 0; for (i = 0, code = 1; i < AtomsCount; i++) { if (a->transform[i] != b->transform[i]) { code = 0; break; } } if (code == 0 && a->order > 2) { /* b can also be a reverse transformation for a */ for (i = 0; i < AtomsCount; i++) { j = a->transform[i]; if (b->transform[j] != i) return 0; } return 1; } return code; } SYMMETRY_ELEMENT *alloc_symmetry_element(void) { SYMMETRY_ELEMENT *elem = calloc(1, sizeof(SYMMETRY_ELEMENT)); int i; if (elem == NULL) { fprintf(stderr, "Out of memory allocating symmetry element\n"); exit(EXIT_FAILURE); } elem->transform = calloc(AtomsCount, sizeof(int)); if (elem->transform == NULL) { fprintf(stderr, "Out of memory allocating transform table for symmetry element\n"); exit(EXIT_FAILURE); } for (i = 0; i < AtomsCount; i++) { elem->transform[i] = AtomsCount + 1; /* An impossible value */ } return elem; } void destroy_symmetry_element(SYMMETRY_ELEMENT *elem) { if (elem != NULL) { if (elem->transform != NULL) free(elem->transform); free(elem); } } int check_transform_quality(SYMMETRY_ELEMENT *elem) { int i, j, k; ATOM symmetric; double r, max_r; for (i = 0, max_r = 0; i < AtomsCount; i++) { j = elem->transform[i]; elem->transform_atom(elem, Atoms + i, &symmetric); for (k = 0, r = 0; k < DIMENSION; k++) { r += pow2(symmetric.x[k] - Atoms[j].x[k]); } r = sqrt(r); if (r > ToleranceFinal) { if (verbose > 0) printf(" distance to symmetric atom (%g) is too big for %d\n", r, i); return -1; } if (r > max_r) max_r = r; } elem->maxdev = max_r; return 0; } double eval_optimization_target_function(SYMMETRY_ELEMENT *elem, int *finish) { int i, j, k; ATOM symmetric; double target, r, maxr; if (elem->nparam >= 4) { for (k = 0, r = 0; k < DIMENSION; k++) { r += elem->normal[k] * elem->normal[k]; } r = sqrt(r); if (r < ToleranceSame) { fprintf(stderr, "Normal collapsed!\n"); exit(EXIT_FAILURE); } for (k = 0; k < DIMENSION; k++) { elem->normal[k] /= r; } if (elem->distance < 0) { elem->distance = -elem->distance; for (k = 0; k < DIMENSION; k++) { elem->normal[k] = -elem->normal[k]; } } } if (elem->nparam >= 7) { for (k = 0, r = 0; k < DIMENSION; k++) { r += elem->direction[k] * elem->direction[k]; } r = sqrt(r); if (r < ToleranceSame) { fprintf(stderr, "Direction collapsed!\n"); exit(EXIT_FAILURE); } for (k = 0; k < DIMENSION; k++) { elem->direction[k] /= r; } } for (i = 0, target = maxr = 0; i < AtomsCount; i++) { elem->transform_atom(elem, Atoms + i, &symmetric); j = elem->transform[i]; for (k = 0, r = 0; k < DIMENSION; k++) { r += pow2(Atoms[j].x[k] - symmetric.x[k]); } if (r > maxr) maxr = r; target += r; } if (finish != NULL) { *finish = 0; if (sqrt(maxr) < ToleranceFinal) *finish = 1; } return target; } void get_params(SYMMETRY_ELEMENT *elem, double values[]) { memcpy(values, &elem->distance, elem->nparam * sizeof(double)); } void set_params(SYMMETRY_ELEMENT *elem, double values[]) { memcpy(&elem->distance, values, elem->nparam * sizeof(double)); } void optimize_transformation_params(SYMMETRY_ELEMENT *elem) { double values[MAXPARAM]; double grad[MAXPARAM]; double force[MAXPARAM]; double step[MAXPARAM]; double f, fold, fnew, fnew2, fdn, fup, snorm; double a, b, x; int vars = elem->nparam; int cycle = 0; int i, finish; int hits = 0; if (vars > MAXPARAM) { fprintf(stderr, "Catastrophe in optimize_transformation_params()!\n"); exit(EXIT_FAILURE); } f = 0; do { fold = f; f = eval_optimization_target_function(elem, &finish); /* Evaluate function, gradient and diagonal force constants */ if (verbose > 1) printf(" function value = %g\n", f); if (finish) { if (verbose > 1) printf(" function value is small enough\n"); break; } if (cycle > 0) { if (fabs(f - fold) > OptChangeThreshold) hits = 0; else hits++; if (hits >= OptChangeHits) { if (verbose > 1) printf(" no progress is made, stop optimization\n"); break; } } get_params(elem, values); for (i = 0; i < vars; i++) { values[i] -= GradientStep; set_params(elem, values); fdn = eval_optimization_target_function(elem, NULL); values[i] += 2 * GradientStep; set_params(elem, values); fup = eval_optimization_target_function(elem, NULL); values[i] -= GradientStep; grad[i] = (fup - fdn) / (2 * GradientStep); force[i] = (fup + fdn - 2 * f) / (GradientStep * GradientStep); if (verbose > 1) printf(" i = %d, grad = %12.6e, force = %12.6e\n", i, grad[i], force[i]); } /* Do a quasy-Newton step */ for (i = 0, snorm = 0; i < vars; i++) { if (force[i] < 0) force[i] = -force[i]; if (force[i] < 1e-3) force[i] = 1e-3; if (force[i] > 1e3) force[i] = 1e3; step[i] = -grad[i] / force[i]; snorm += step[i] * step[i]; } snorm = sqrt(snorm); if (snorm > MaxOptStep) { /* Renormalize step */ for (i = 0; i < vars; i++) step[i] *= MaxOptStep / snorm; snorm = MaxOptStep; } do { for (i = 0; i < vars; i++) { values[i] += step[i]; } set_params(elem, values); fnew = eval_optimization_target_function(elem, NULL); if (fnew < f) break; for (i = 0; i < vars; i++) { values[i] -= step[i]; step[i] /= 2; } set_params(elem, values); snorm /= 2; } while (snorm > MinOptStep); if ((snorm > MinOptStep) && (snorm < MaxOptStep / 2)) { /* try to do quadratic interpolation */ for (i = 0; i < vars; i++) values[i] += step[i]; set_params(elem, values); fnew2 = eval_optimization_target_function(elem, NULL); if (verbose > 1) printf(" interpolation base points: %g, %g, %g\n", f, fnew, fnew2); for (i = 0; i < vars; i++) values[i] -= 2 * step[i]; a = (4 * f - fnew2 - 3 * fnew) / 2; b = (f + fnew2 - 2 * fnew) / 2; if (verbose > 1) printf(" linear interpolation coefficients %g, %g\n", a, b); if (b > 0) { x = -a / (2 * b); if (x > 0.2 && x < 1.8) { if (verbose > 1) printf(" interpolated: %g\n", x); for (i = 0; i < vars; i++) values[i] += x * step[i]; } else b = 0; } if (b <= 0) { if (fnew2 < fnew) { for (i = 0; i < vars; i++) values[i] += 2 * step[i]; } else { for (i = 0; i < vars; i++) values[i] += step[i]; } } set_params(elem, values); } } while (snorm > MinOptStep && ++cycle < MaxOptCycles); f = eval_optimization_target_function(elem, NULL); if (cycle >= MaxOptCycles) BadOptimization = 1; if (verbose > 0) { if (cycle >= MaxOptCycles) printf(" maximum number of optimization cycles made\n"); printf(" optimization completed after %d cycles with f = %g\n", cycle, f); } } int refine_symmetry_element(SYMMETRY_ELEMENT *elem, int build_table) { int i; if (build_table && (establish_pairs(elem) < 0)) { StatPairs++; if (verbose > 0) printf(" no transformation correspondence table can be " "constructed\n"); return -1; } for (i = 0; i < PlanesCount; i++) { if (same_transform(Planes[i], elem)) { StatDups++; if (verbose > 0) printf(" transformation is identical to plane %d\n", i); return -1; } } for (i = 0; i < InversionCentersCount; i++) { if (same_transform(InversionCenters[i], elem)) { StatDups++; if (verbose > 0) printf(" transformation is identical to inversion center %d\n", i); return -1; } } for (i = 0; i < NormalAxesCount; i++) { if (same_transform(NormalAxes[i], elem)) { StatDups++; if (verbose > 0) printf(" transformation is identical to normal axis %d\n", i); return -1; } } for (i = 0; i < ImproperAxesCount; i++) { if (same_transform(ImproperAxes[i], elem)) { StatDups++; if (verbose > 0) printf(" transformation is identical to improper axis %d\n", i); return -1; } } if (check_transform_order(elem) < 0) { StatOrder++; if (verbose > 0) printf(" incorrect transformation order\n"); return -1; } optimize_transformation_params(elem); if (check_transform_quality(elem) < 0) { StatOpt++; if (verbose > 0) printf(" refined transformation does not pass the numeric " "threshold\n"); return -1; } StatAccept++; return 0; } /* * Plane-specific functions */ void mirror_atom(SYMMETRY_ELEMENT *plane, ATOM *from, ATOM *to) { int i; double r; for (i = 0, r = plane->distance; i < DIMENSION; i++) { r -= from->x[i] * plane->normal[i]; } to->type = from->type; for (i = 0; i < DIMENSION; i++) { to->x[i] = from->x[i] + 2 * r * plane->normal[i]; } } SYMMETRY_ELEMENT *init_mirror_plane(int i, int j) { SYMMETRY_ELEMENT *plane = alloc_symmetry_element(); double dx[DIMENSION], midpoint[DIMENSION], rab, r; int k; if (verbose > 0) printf("Trying mirror plane for atoms %d,%d\n", i, j); StatTotal++; plane->transform_atom = mirror_atom; plane->order = 2; plane->nparam = 4; for (k = 0, rab = 0; k < DIMENSION; k++) { dx[k] = Atoms[i].x[k] - Atoms[j].x[k]; midpoint[k] = (Atoms[i].x[k] + Atoms[j].x[k]) / 2.0; rab += dx[k] * dx[k]; } rab = sqrt(rab); if (rab < ToleranceSame) { fprintf(stderr, "Atoms %d and %d coincide (r = %g)\n", i, j, rab); exit(EXIT_FAILURE); } for (k = 0, r = 0; k < DIMENSION; k++) { plane->normal[k] = dx[k] / rab; r += midpoint[k] * plane->normal[k]; } if (r < 0) { /* Reverce normal direction, distance is always positive! */ r = -r; for (k = 0; k < DIMENSION; k++) { plane->normal[k] = -plane->normal[k]; } } plane->distance = r; if (verbose > 0) printf(" initial plane is at %g from the origin\n", r); if (refine_symmetry_element(plane, 1) < 0) { if (verbose > 0) printf(" refinement failed for the plane\n"); destroy_symmetry_element(plane); return NULL; } return plane; } SYMMETRY_ELEMENT *init_ultimate_plane(void) { SYMMETRY_ELEMENT *plane = alloc_symmetry_element(); double d0[DIMENSION], d1[DIMENSION], d2[DIMENSION]; double p[DIMENSION]; double r, s0, s1, s2; double *d; int i, j, k; if (verbose > 0) printf("Trying whole-molecule mirror plane\n"); StatTotal++; plane->transform_atom = mirror_atom; plane->order = 1; plane->nparam = 4; for (k = 0; k < DIMENSION; k++) d0[k] = d1[k] = d2[k] = 0; d0[0] = 1; d1[1] = 1; d2[2] = 1; for (i = 1; i < AtomsCount; i++) { for (j = 0; j < i; j++) { for (k = 0, r = 0; k < DIMENSION; k++) { p[k] = Atoms[i].x[k] - Atoms[j].x[k]; r += p[k] * p[k]; } r = sqrt(r); for (k = 0, s0 = s1 = s2 = 0; k < DIMENSION; k++) { p[k] /= r; s0 += p[k] * d0[k]; s1 += p[k] * d1[k]; s2 += p[k] * d2[k]; } for (k = 0; k < DIMENSION; k++) { d0[k] -= s0 * p[k]; d1[k] -= s1 * p[k]; d2[k] -= s2 * p[k]; } } } for (k = 0, s0 = s1 = s2 = 0; k < DIMENSION; k++) { s0 += d0[k]; s1 += d1[k]; s2 += d2[k]; } d = NULL; if (s0 >= s1 && s0 >= s2) d = d0; if (s1 >= s0 && s1 >= s2) d = d1; if (s2 >= s0 && s2 >= s1) d = d2; if (d == NULL) { fprintf(stderr, "Catastrophe in init_ultimate_plane(): %g, %g and %g have no " "ordering!\n", s0, s1, s2); exit(EXIT_FAILURE); } for (k = 0, r = 0; k < DIMENSION; k++) r += d[k] * d[k]; r = sqrt(r); if (r > 0) { for (k = 0; k < DIMENSION; k++) plane->normal[k] = d[k] / r; } else { for (k = 1; k < DIMENSION; k++) plane->normal[k] = 0; plane->normal[0] = 1; } for (k = 0, r = 0; k < DIMENSION; k++) r += CenterOfSomething[k] * plane->normal[k]; plane->distance = r; for (k = 0; k < AtomsCount; k++) plane->transform[k] = k; if (refine_symmetry_element(plane, 0) < 0) { if (verbose > 0) printf(" refinement failed for the plane\n"); destroy_symmetry_element(plane); return NULL; } return plane; } /* * Inversion-center specific functions */ void invert_atom(SYMMETRY_ELEMENT *center, ATOM *from, ATOM *to) { int i; to->type = from->type; for (i = 0; i < DIMENSION; i++) { to->x[i] = 2 * center->distance * center->normal[i] - from->x[i]; } } SYMMETRY_ELEMENT *init_inversion_center(void) { SYMMETRY_ELEMENT *center = alloc_symmetry_element(); int k; double r; if (verbose > 0) printf("Trying inversion center at the center of something\n"); StatTotal++; center->transform_atom = invert_atom; center->order = 2; center->nparam = 4; for (k = 0, r = 0; k < DIMENSION; k++) r += CenterOfSomething[k] * CenterOfSomething[k]; r = sqrt(r); if (r > 0) { for (k = 0; k < DIMENSION; k++) center->normal[k] = CenterOfSomething[k] / r; } else { center->normal[0] = 1; for (k = 1; k < DIMENSION; k++) center->normal[k] = 0; } center->distance = r; if (verbose > 0) printf(" initial inversion center is at %g from the origin\n", r); if (refine_symmetry_element(center, 1) < 0) { if (verbose > 0) printf(" refinement failed for the inversion center\n"); destroy_symmetry_element(center); return NULL; } return center; } /* * Normal rotation axis-specific routines. */ void rotate_atom(SYMMETRY_ELEMENT *axis, ATOM *from, ATOM *to) { double x[3], y[3], a[3], b[3], c[3]; double angle = axis->order ? 2 * M_PI / axis->order : 1.0; double a_sin = sin(angle); double a_cos = cos(angle); double dot; int i; if (DIMENSION != 3) { fprintf(stderr, "Catastrophe in rotate_atom!\n"); exit(EXIT_FAILURE); } for (i = 0; i < 3; i++) x[i] = from->x[i] - axis->distance * axis->normal[i]; for (i = 0, dot = 0; i < 3; i++) dot += x[i] * axis->direction[i]; for (i = 0; i < 3; i++) a[i] = axis->direction[i] * dot; for (i = 0; i < 3; i++) b[i] = x[i] - a[i]; c[0] = b[1] * axis->direction[2] - b[2] * axis->direction[1]; c[1] = b[2] * axis->direction[0] - b[0] * axis->direction[2]; c[2] = b[0] * axis->direction[1] - b[1] * axis->direction[0]; for (i = 0; i < 3; i++) y[i] = a[i] + b[i] * a_cos + c[i] * a_sin; for (i = 0; i < 3; i++) to->x[i] = y[i] + axis->distance * axis->normal[i]; to->type = from->type; } SYMMETRY_ELEMENT *init_ultimate_axis(void) { SYMMETRY_ELEMENT *axis = alloc_symmetry_element(); double dir[DIMENSION], rel[DIMENSION]; double s; int i, k; if (verbose > 0) printf("Trying infinity axis\n"); StatTotal++; axis->transform_atom = rotate_atom; axis->order = 0; axis->nparam = 7; for (k = 0; k < DIMENSION; k++) dir[k] = 0; for (i = 0; i < AtomsCount; i++) { for (k = 0, s = 0; k < DIMENSION; k++) { rel[k] = Atoms[i].x[k] - CenterOfSomething[k]; s += rel[k] * dir[k]; } if (s >= 0) for (k = 0; k < DIMENSION; k++) dir[k] += rel[k]; else for (k = 0; k < DIMENSION; k++) dir[k] -= rel[k]; } for (k = 0, s = 0; k < DIMENSION; k++) s += pow2(dir[k]); s = sqrt(s); if (s > 0) for (k = 0; k < DIMENSION; k++) dir[k] /= s; else dir[0] = 1; for (k = 0; k < DIMENSION; k++) axis->direction[k] = dir[k]; for (k = 0, s = 0; k < DIMENSION; k++) s += pow2(CenterOfSomething[k]); s = sqrt(s); if (s > 0) for (k = 0; k < DIMENSION; k++) axis->normal[k] = CenterOfSomething[k] / s; else { for (k = 1; k < DIMENSION; k++) axis->normal[k] = 0; axis->normal[0] = 1; } axis->distance = s; for (k = 0; k < AtomsCount; k++) axis->transform[k] = k; if (refine_symmetry_element(axis, 0) < 0) { if (verbose > 0) printf(" refinement failed for the infinity axis\n"); destroy_symmetry_element(axis); return NULL; } return axis; } SYMMETRY_ELEMENT *init_c2_axis(int i, int j, double support[DIMENSION]) { SYMMETRY_ELEMENT *axis; int k; double ris, rjs; double r, center[DIMENSION]; if (verbose > 0) printf("Trying c2 axis for the pair (%d,%d) with the support (%g,%g,%g)\n", i, j, support[0], support[1], support[2]); StatTotal++; /* First, do a quick sanity check */ for (k = 0, ris = rjs = 0; k < DIMENSION; k++) { ris += pow2(Atoms[i].x[k] - support[k]); rjs += pow2(Atoms[j].x[k] - support[k]); } ris = sqrt(ris); rjs = sqrt(rjs); if (fabs(ris - rjs) > TolerancePrimary) { StatEarly++; if (verbose > 0) printf(" Support can't actually define a rotation axis\n"); return NULL; } axis = alloc_symmetry_element(); axis->transform_atom = rotate_atom; axis->order = 2; axis->nparam = 7; for (k = 0, r = 0; k < DIMENSION; k++) r += CenterOfSomething[k] * CenterOfSomething[k]; r = sqrt(r); if (r > 0) { for (k = 0; k < DIMENSION; k++) axis->normal[k] = CenterOfSomething[k] / r; } else { axis->normal[0] = 1; for (k = 1; k < DIMENSION; k++) axis->normal[k] = 0; } axis->distance = r; for (k = 0, r = 0; k < DIMENSION; k++) { center[k] = (Atoms[i].x[k] + Atoms[j].x[k]) / 2 - support[k]; r += center[k] * center[k]; } r = sqrt(r); if (r <= TolerancePrimary) { /* c2 is underdefined, let's do something special */ if (MolecularPlane != NULL) { if (verbose > 0) printf(" c2 is underdefined, but there is a molecular plane\n"); for (k = 0; k < DIMENSION; k++) axis->direction[k] = MolecularPlane->normal[k]; } else { if (verbose > 0) printf(" c2 is underdefined, trying random direction\n"); for (k = 0; k < DIMENSION; k++) center[k] = Atoms[i].x[k] - Atoms[j].x[k]; if (fabs(center[2]) + fabs(center[1]) > ToleranceSame) { axis->direction[0] = 0; axis->direction[1] = center[2]; axis->direction[2] = -center[1]; } else { axis->direction[0] = -center[2]; axis->direction[1] = 0; axis->direction[2] = center[0]; } for (k = 0, r = 0; k < DIMENSION; k++) r += axis->direction[k] * axis->direction[k]; r = sqrt(r); for (k = 0; k < DIMENSION; k++) axis->direction[k] /= r; } } else { /* direction is Ok, renormalize it */ for (k = 0; k < DIMENSION; k++) axis->direction[k] = center[k] / r; } if (refine_symmetry_element(axis, 1) < 0) { if (verbose > 0) printf(" refinement failed for the c2 axis\n"); destroy_symmetry_element(axis); return NULL; } return axis; } SYMMETRY_ELEMENT *init_axis_parameters(double a[3], double b[3], double c[3]) { SYMMETRY_ELEMENT *axis; int i, order, sign; double ra, rb, rc, rab, rbc, rac, r; double angle; ra = rb = rc = rab = rbc = rac = 0; for (i = 0; i < DIMENSION; i++) { ra += a[i] * a[i]; rb += b[i] * b[i]; rc += c[i] * c[i]; } ra = sqrt(ra); rb = sqrt(rb); rc = sqrt(rc); if (fabs(ra - rb) > TolerancePrimary || fabs(ra - rc) > TolerancePrimary || fabs(rb - rc) > TolerancePrimary) { StatEarly++; if (verbose > 0) printf(" points are not on a sphere\n"); return NULL; } for (i = 0; i < DIMENSION; i++) { rab += (a[i] - b[i]) * (a[i] - b[i]); rac += (a[i] - c[i]) * (a[i] - c[i]); rbc += (c[i] - b[i]) * (c[i] - b[i]); } rab = sqrt(rab); rac = sqrt(rac); rbc = sqrt(rbc); if (fabs(rab - rbc) > TolerancePrimary) { StatEarly++; if (verbose > 0) printf(" points can't be rotation-equivalent\n"); return NULL; } if (rab <= ToleranceSame || rbc <= ToleranceSame || rac <= ToleranceSame) { StatEarly++; if (verbose > 0) printf(" rotation is underdefined by these points\n"); return NULL; } rab = (rab + rbc) / 2; angle = M_PI - 2 * asin(rac / (2 * rab)); if (verbose > 1) printf(" rotation angle is %f\n", angle); if (fabs(angle) <= M_PI / (MaxAxisOrder + 1)) { StatEarly++; if (verbose > 0) printf(" atoms are too close to a straight line\n"); return NULL; } order = floor((2 * M_PI) / angle + 0.5); if (order <= 2 || order > MaxAxisOrder) { StatEarly++; if (verbose > 0) printf(" rotation axis order (%d) is not from 3 to %d\n", order, MaxAxisOrder); return NULL; } axis = alloc_symmetry_element(); axis->order = order; axis->nparam = 7; for (i = 0, r = 0; i < DIMENSION; i++) r += CenterOfSomething[i] * CenterOfSomething[i]; r = sqrt(r); if (r > 0) { for (i = 0; i < DIMENSION; i++) axis->normal[i] = CenterOfSomething[i] / r; } else { axis->normal[0] = 1; for (i = 1; i < DIMENSION; i++) axis->normal[i] = 0; } axis->distance = r; axis->direction[0] = (b[1] - a[1]) * (c[2] - b[2]) - (b[2] - a[2]) * (c[1] - b[1]); axis->direction[1] = (b[2] - a[2]) * (c[0] - b[0]) - (b[0] - a[0]) * (c[2] - b[2]); axis->direction[2] = (b[0] - a[0]) * (c[1] - b[1]) - (b[1] - a[1]) * (c[0] - b[0]); /* * Arbitrarily select axis direction so that first non-zero component * of the direction is positive. */ sign = 0; if (axis->direction[0] <= 0) { if (axis->direction[0] < 0) { sign = 1; } else if (axis->direction[1] <= 0) { if (axis->direction[1] < 0) { sign = 1; } else if (axis->direction[2] < 0) { sign = 1; } } } if (sign) for (i = 0; i < DIMENSION; i++) axis->direction[i] = -axis->direction[i]; for (i = 0, r = 0; i < DIMENSION; i++) r += axis->direction[i] * axis->direction[i]; r = sqrt(r); for (i = 0; i < DIMENSION; i++) axis->direction[i] /= r; if (verbose > 1) { printf(" axis origin is at (%g,%g,%g)\n", axis->normal[0] * axis->distance, axis->normal[1] * axis->distance, axis->normal[2] * axis->distance); printf(" axis is in the direction (%g,%g,%g)\n", axis->direction[0], axis->direction[1], axis->direction[2]); } return axis; } SYMMETRY_ELEMENT *init_higher_axis(int ia, int ib, int ic) { SYMMETRY_ELEMENT *axis; double a[DIMENSION], b[DIMENSION], c[DIMENSION]; int i; if (verbose > 0) printf("Trying cn axis for the triplet (%d,%d,%d)\n", ia, ib, ic); StatTotal++; /* Do a quick check of geometry validity */ for (i = 0; i < DIMENSION; i++) { a[i] = Atoms[ia].x[i] - CenterOfSomething[i]; b[i] = Atoms[ib].x[i] - CenterOfSomething[i]; c[i] = Atoms[ic].x[i] - CenterOfSomething[i]; } if ((axis = init_axis_parameters(a, b, c)) == NULL) { if (verbose > 0) printf(" no coherent axis is defined by the points\n"); return NULL; } axis->transform_atom = rotate_atom; if (refine_symmetry_element(axis, 1) < 0) { if (verbose > 0) printf(" refinement failed for the c%d axis\n", axis->order); destroy_symmetry_element(axis); return NULL; } return axis; } /* * Improper axes-specific routines. * These are obtained by slight modifications of normal rotation * routines. */ void rotate_reflect_atom(SYMMETRY_ELEMENT *axis, ATOM *from, ATOM *to) { double x[3], y[3], a[3], b[3], c[3]; double angle = 2 * M_PI / axis->order; double a_sin = sin(angle); double a_cos = cos(angle); double dot; int i; if (DIMENSION != 3) { fprintf(stderr, "Catastrophe in rotate_reflect_atom!\n"); exit(EXIT_FAILURE); } for (i = 0; i < 3; i++) x[i] = from->x[i] - axis->distance * axis->normal[i]; for (i = 0, dot = 0; i < 3; i++) dot += x[i] * axis->direction[i]; for (i = 0; i < 3; i++) a[i] = axis->direction[i] * dot; for (i = 0; i < 3; i++) b[i] = x[i] - a[i]; c[0] = b[1] * axis->direction[2] - b[2] * axis->direction[1]; c[1] = b[2] * axis->direction[0] - b[0] * axis->direction[2]; c[2] = b[0] * axis->direction[1] - b[1] * axis->direction[0]; for (i = 0; i < 3; i++) y[i] = -a[i] + b[i] * a_cos + c[i] * a_sin; for (i = 0; i < 3; i++) to->x[i] = y[i] + axis->distance * axis->normal[i]; to->type = from->type; } SYMMETRY_ELEMENT *init_improper_axis(int ia, int ib, int ic) { SYMMETRY_ELEMENT *axis; double a[DIMENSION], b[DIMENSION], c[DIMENSION]; double centerpoint[DIMENSION]; double r; int i; if (verbose > 0) printf("Trying sn axis for the triplet (%d,%d,%d)\n", ia, ib, ic); StatTotal++; /* First, reduce the problem to Cn case */ for (i = 0; i < DIMENSION; i++) { a[i] = Atoms[ia].x[i] - CenterOfSomething[i]; b[i] = Atoms[ib].x[i] - CenterOfSomething[i]; c[i] = Atoms[ic].x[i] - CenterOfSomething[i]; } for (i = 0, r = 0; i < DIMENSION; i++) { centerpoint[i] = a[i] + c[i] + 2 * b[i]; r += centerpoint[i] * centerpoint[i]; } r = sqrt(r); if (r <= ToleranceSame) { StatEarly++; if (verbose > 0) printf( " atoms can not define improper axis of the order more than 2\n"); return NULL; } for (i = 0; i < DIMENSION; i++) centerpoint[i] /= r; for (i = 0, r = 0; i < DIMENSION; i++) r += centerpoint[i] * b[i]; for (i = 0; i < DIMENSION; i++) b[i] = 2 * r * centerpoint[i] - b[i]; /* Do a quick check of geometry validity */ if ((axis = init_axis_parameters(a, b, c)) == NULL) { if (verbose > 0) printf(" no coherent improper axis is defined by the points\n"); return NULL; } axis->transform_atom = rotate_reflect_atom; if (refine_symmetry_element(axis, 1) < 0) { if (verbose > 0) printf(" refinement failed for the s%d axis\n", axis->order); destroy_symmetry_element(axis); return NULL; } return axis; } /* * Control routines */ void find_center_of_something(void) { int i, j; double coord_sum[DIMENSION]; double r; for (j = 0; j < DIMENSION; j++) coord_sum[j] = 0; for (i = 0; i < AtomsCount; i++) { for (j = 0; j < DIMENSION; j++) coord_sum[j] += Atoms[i].x[j]; } for (j = 0; j < DIMENSION; j++) CenterOfSomething[j] = coord_sum[j] / AtomsCount; if (verbose > 0) printf("Center of something is at %15.10f, %15.10f, %15.10f\n", CenterOfSomething[0], CenterOfSomething[1], CenterOfSomething[2]); DistanceFromCenter = (double *)calloc(AtomsCount, sizeof(double)); if (DistanceFromCenter == NULL) { fprintf(stderr, "Unable to allocate array for the distances\n"); exit(EXIT_FAILURE); } for (i = 0; i < AtomsCount; i++) { for (j = 0, r = 0; j < DIMENSION; j++) r += pow2(Atoms[i].x[j] - CenterOfSomething[j]); DistanceFromCenter[i] = r; } } void find_planes(void) { int i, j; SYMMETRY_ELEMENT *plane = NULL; plane = init_ultimate_plane(); if (plane != NULL) { MolecularPlane = plane; PlanesCount++; Planes = (SYMMETRY_ELEMENT **)realloc(Planes, sizeof(SYMMETRY_ELEMENT *) * PlanesCount); if (Planes == NULL) { perror("Out of memory in find_planes"); exit(EXIT_FAILURE); } Planes[PlanesCount - 1] = plane; } for (i = 1; i < AtomsCount; i++) { for (j = 0; j < i; j++) { if (Atoms[i].type != Atoms[j].type) continue; if ((plane = init_mirror_plane(i, j)) != NULL) { PlanesCount++; Planes = (SYMMETRY_ELEMENT **)realloc( Planes, sizeof(SYMMETRY_ELEMENT *) * PlanesCount); if (Planes == NULL) { perror("Out of memory in find_planes"); exit(EXIT_FAILURE); } Planes[PlanesCount - 1] = plane; } } } } void destroy_planes(void) { int i; for (i = 0; i < PlanesCount; i++) destroy_symmetry_element(Planes[i]); PlanesCount = 0; free(Planes); MolecularPlane = NULL; Planes = NULL; } void find_inversion_centers(void) { SYMMETRY_ELEMENT *center; if ((center = init_inversion_center()) != NULL) { InversionCenters = (SYMMETRY_ELEMENT **)calloc(1, sizeof(SYMMETRY_ELEMENT *)); InversionCenters[0] = center; InversionCentersCount = 1; } } void destroy_inversion_centers(void) { int i; for (i = 0; i < InversionCentersCount; i++) destroy_symmetry_element(InversionCenters[i]); InversionCentersCount = 0; free(InversionCenters); InversionCenters = NULL; } void find_infinity_axis(void) { SYMMETRY_ELEMENT *axis; if ((axis = init_ultimate_axis()) != NULL) { NormalAxesCount++; NormalAxes = (SYMMETRY_ELEMENT **)realloc( NormalAxes, sizeof(SYMMETRY_ELEMENT *) * NormalAxesCount); if (NormalAxes == NULL) { perror("Out of memory in find_infinity_axes()"); exit(EXIT_FAILURE); } NormalAxes[NormalAxesCount - 1] = axis; } } void find_c2_axes(void) { int i, j, k, l, m; double center[DIMENSION]; double *distances = calloc(AtomsCount, sizeof(double)); double r; SYMMETRY_ELEMENT *axis; if (distances == NULL) { fprintf(stderr, "Out of memory in find_c2_axes()\n"); exit(EXIT_FAILURE); } for (i = 1; i < AtomsCount; i++) { for (j = 0; j < i; j++) { if (Atoms[i].type != Atoms[j].type) continue; if (fabs(DistanceFromCenter[i] - DistanceFromCenter[j]) > TolerancePrimary) continue; /* A very cheap, but quite effective check */ /* * First, let's try to get it cheap and use CenterOfSomething */ for (k = 0, r = 0; k < DIMENSION; k++) { center[k] = (Atoms[i].x[k] + Atoms[j].x[k]) / 2; r += pow2(center[k] - CenterOfSomething[k]); } r = sqrt(r); if (r > 5 * TolerancePrimary) { /* It's Ok to use CenterOfSomething */ if ((axis = init_c2_axis(i, j, CenterOfSomething)) != NULL) { NormalAxesCount++; NormalAxes = (SYMMETRY_ELEMENT **)realloc( NormalAxes, sizeof(SYMMETRY_ELEMENT *) * NormalAxesCount); if (NormalAxes == NULL) { perror("Out of memory in find_c2_axes"); exit(EXIT_FAILURE); } NormalAxes[NormalAxesCount - 1] = axis; } continue; } /* * Now, C2 axis can either pass through an atom, or through the * middle of the other pair. */ for (k = 0; k < AtomsCount; k++) { if ((axis = init_c2_axis(i, j, Atoms[k].x)) != NULL) { NormalAxesCount++; NormalAxes = (SYMMETRY_ELEMENT **)realloc( NormalAxes, sizeof(SYMMETRY_ELEMENT *) * NormalAxesCount); if (NormalAxes == NULL) { perror("Out of memory in find_c2_axes"); exit(EXIT_FAILURE); } NormalAxes[NormalAxesCount - 1] = axis; } } /* * Prepare data for an additional pre-screening check */ for (k = 0; k < AtomsCount; k++) { for (l = 0, r = 0; l < DIMENSION; l++) r += pow2(Atoms[k].x[l] - center[l]); distances[k] = sqrt(r); } for (k = 0; k < AtomsCount; k++) { for (l = 0; l < AtomsCount; l++) { if (Atoms[k].type != Atoms[l].type) continue; if (fabs(DistanceFromCenter[k] - DistanceFromCenter[l]) > TolerancePrimary || fabs(distances[k] - distances[l]) > TolerancePrimary) continue; /* We really need this one to run reasonably fast! */ for (m = 0; m < DIMENSION; m++) center[m] = (Atoms[k].x[m] + Atoms[l].x[m]) / 2; if ((axis = init_c2_axis(i, j, center)) != NULL) { NormalAxesCount++; NormalAxes = (SYMMETRY_ELEMENT **)realloc( NormalAxes, sizeof(SYMMETRY_ELEMENT *) * NormalAxesCount); if (NormalAxes == NULL) { perror("Out of memory in find_c2_axes"); exit(EXIT_FAILURE); } NormalAxes[NormalAxesCount - 1] = axis; } } } } } free(distances); } void destroy_normal_axes() { int i = 0; for (i = 0; i < NormalAxesCount; i++) destroy_symmetry_element(NormalAxes[i]); NormalAxesCount = 0; free(NormalAxes); NormalAxes = NULL; } void destroy_improper_axes() { int i = 0; for (i = 0; i < ImproperAxesCount; i++) destroy_symmetry_element(ImproperAxes[i]); ImproperAxesCount = 0; free(ImproperAxes); ImproperAxes = NULL; } void find_higher_axes(void) { int i, j, k; SYMMETRY_ELEMENT *axis; for (i = 0; i < AtomsCount; i++) { for (j = i + 1; j < AtomsCount; j++) { if (Atoms[i].type != Atoms[j].type) continue; if (fabs(DistanceFromCenter[i] - DistanceFromCenter[j]) > TolerancePrimary) continue; /* A very cheap, but quite effective check */ for (k = 0; k < AtomsCount; k++) { if (Atoms[i].type != Atoms[k].type) continue; if ((fabs(DistanceFromCenter[i] - DistanceFromCenter[k]) > TolerancePrimary) || (fabs(DistanceFromCenter[j] - DistanceFromCenter[k]) > TolerancePrimary)) continue; if ((axis = init_higher_axis(i, j, k)) != NULL) { NormalAxesCount++; NormalAxes = (SYMMETRY_ELEMENT **)realloc( NormalAxes, sizeof(SYMMETRY_ELEMENT *) * NormalAxesCount); if (NormalAxes == NULL) { perror("Out of memory in find_higher_axes"); exit(EXIT_FAILURE); } NormalAxes[NormalAxesCount - 1] = axis; } } } } } void find_improper_axes(void) { int i, j, k; SYMMETRY_ELEMENT *axis; for (i = 0; i < AtomsCount; i++) { for (j = i + 1; j < AtomsCount; j++) { for (k = 0; k < AtomsCount; k++) { if ((axis = init_improper_axis(i, j, k)) != NULL) { ImproperAxesCount++; ImproperAxes = (SYMMETRY_ELEMENT **)realloc( ImproperAxes, sizeof(SYMMETRY_ELEMENT *) * ImproperAxesCount); if (ImproperAxes == NULL) { perror("Out of memory in find_higher_axes"); exit(EXIT_FAILURE); } ImproperAxes[ImproperAxesCount - 1] = axis; } } } } } void report_planes(void) { int i; if (PlanesCount == 0) printf("There are no planes of symmetry in the molecule\n"); else { if (PlanesCount == 1) printf("There is a plane of symmetry in the molecule\n"); else printf("There are %d planes of symmetry in the molecule\n", PlanesCount); printf( " Residual Direction of the normal Distance\n"); for (i = 0; i < PlanesCount; i++) { printf("%3d %8.4e ", i, Planes[i]->maxdev); printf("(%11.8f,%11.8f,%11.8f) ", Planes[i]->normal[0], Planes[i]->normal[1], Planes[i]->normal[2]); printf("%14.8f\n", Planes[i]->distance); } } } void report_inversion_centers(void) { if (InversionCentersCount == 0) printf("There is no inversion center in the molecule\n"); else { printf("There in an inversion center in the molecule\n"); printf(" Residual Position\n"); printf(" %8.4e ", InversionCenters[0]->maxdev); printf("(%14.8f,%14.8f,%14.8f)\n", InversionCenters[0]->distance * InversionCenters[0]->normal[0], InversionCenters[0]->distance * InversionCenters[0]->normal[1], InversionCenters[0]->distance * InversionCenters[0]->normal[2]); } } void report_axes(void) { int i; if (NormalAxesCount == 0) printf("There are no normal axes in the molecule\n"); else { if (NormalAxesCount == 1) printf("There is a normal axis in the molecule\n"); else printf("There are %d normal axes in the molecule\n", NormalAxesCount); printf(" Residual Order Direction of the axis " " Supporting point\n"); for (i = 0; i < NormalAxesCount; i++) { printf("%3d %8.4e ", i, NormalAxes[i]->maxdev); if (NormalAxes[i]->order == 0) printf("Inf "); else printf("%3d ", NormalAxes[i]->order); printf("(%11.8f,%11.8f,%11.8f) ", NormalAxes[i]->direction[0], NormalAxes[i]->direction[1], NormalAxes[i]->direction[2]); printf("(%14.8f,%14.8f,%14.8f)\n", NormalAxes[0]->distance * NormalAxes[0]->normal[0], NormalAxes[0]->distance * NormalAxes[0]->normal[1], NormalAxes[0]->distance * NormalAxes[0]->normal[2]); } } } void report_improper_axes(void) { int i; if (ImproperAxesCount == 0) printf("There are no improper axes in the molecule\n"); else { if (ImproperAxesCount == 1) printf("There is an improper axis in the molecule\n"); else printf("There are %d improper axes in the molecule\n", ImproperAxesCount); printf(" Residual Order Direction of the axis " " Supporting point\n"); for (i = 0; i < ImproperAxesCount; i++) { printf("%3d %8.4e ", i, ImproperAxes[i]->maxdev); if (ImproperAxes[i]->order == 0) printf("Inf "); else printf("%3d ", ImproperAxes[i]->order); printf("(%11.8f,%11.8f,%11.8f) ", ImproperAxes[i]->direction[0], ImproperAxes[i]->direction[1], ImproperAxes[i]->direction[2]); printf("(%14.8f,%14.8f,%14.8f)\n", ImproperAxes[0]->distance * ImproperAxes[0]->normal[0], ImproperAxes[0]->distance * ImproperAxes[0]->normal[1], ImproperAxes[0]->distance * ImproperAxes[0]->normal[2]); } } } /* * General symmetry handling */ void report_and_reset_counters(void) { printf(" %10ld candidates examined\n" " %10ld removed early\n" " %10ld removed during initial mating stage\n" " %10ld removed as duplicates\n" " %10ld removed because of the wrong transformation order\n" " %10ld removed after unsuccessful optimization\n" " %10ld accepted\n", StatTotal, StatEarly, StatPairs, StatDups, StatOrder, StatOpt, StatAccept); StatTotal = StatEarly = StatPairs = StatDups = StatOrder = StatOpt = StatAccept = 0; } void find_symmetry_elements(void) { find_center_of_something(); if (verbose > -1) { printf("Looking for the inversion center\n"); } find_inversion_centers(); if (verbose > -1) { report_and_reset_counters(); printf("Looking for the planes of symmetry\n"); } find_planes(); if (verbose > -1) { report_and_reset_counters(); printf("Looking for infinity axis\n"); } find_infinity_axis(); if (verbose > -1) { report_and_reset_counters(); printf("Looking for C2 axes\n"); } find_c2_axes(); if (verbose > -1) { report_and_reset_counters(); printf("Looking for higher axes\n"); } find_higher_axes(); if (verbose > -1) { report_and_reset_counters(); printf("Looking for the improper axes\n"); } find_improper_axes(); if (verbose > -1) { report_and_reset_counters(); } } int compare_axes(const void *a, const void *b) { SYMMETRY_ELEMENT *axis_a = *(SYMMETRY_ELEMENT **)a; SYMMETRY_ELEMENT *axis_b = *(SYMMETRY_ELEMENT **)b; int i, order_a, order_b; order_a = axis_a->order; if (order_a == 0) order_a = 10000; order_b = axis_b->order; if (order_b == 0) order_b = 10000; if ((i = order_b - order_a) != 0) return i; if (axis_a->maxdev > axis_b->maxdev) return -1; if (axis_a->maxdev < axis_b->maxdev) return 1; return 0; } void sort_symmetry_elements(void) { if (PlanesCount > 1) { qsort(Planes, PlanesCount, sizeof(SYMMETRY_ELEMENT *), compare_axes); } if (NormalAxesCount > 1) { qsort(NormalAxes, NormalAxesCount, sizeof(SYMMETRY_ELEMENT *), compare_axes); } if (ImproperAxesCount > 1) { qsort(ImproperAxes, ImproperAxesCount, sizeof(SYMMETRY_ELEMENT *), compare_axes); } } void report_symmetry_elements_verbose(void) { report_inversion_centers(); report_axes(); report_improper_axes(); report_planes(); } void summarize_symmetry_elements(void) { int i; NormalAxesCounts = (int *)calloc(MaxAxisOrder + 1, sizeof(int)); ImproperAxesCounts = (int *)calloc(MaxAxisOrder + 1, sizeof(int)); for (i = 0; i < NormalAxesCount; i++) NormalAxesCounts[NormalAxes[i]->order]++; for (i = 0; i < ImproperAxesCount; i++) ImproperAxesCounts[ImproperAxes[i]->order]++; } void report_symmetry_elements_brief() { int i; char *symmetry_code = calloc(1, 10 * (PlanesCount + NormalAxesCount + ImproperAxesCount + InversionCentersCount + 2)); char buf[100]; if (symmetry_code == NULL) { fprintf(stderr, "Unable to allocate memory for symmetry ID code in " "report_symmetry_elements_brief()\n"); exit(EXIT_FAILURE); } if (PlanesCount + NormalAxesCount + ImproperAxesCount + InversionCentersCount == 0) { if (verbose > -1) printf("Molecule has no symmetry elements\n"); } else { if (verbose > -1) printf("Molecule has the following symmetry elements: "); if (InversionCentersCount > 0) strcat(symmetry_code, "(i) "); if (NormalAxesCounts[0] == 1) strcat(symmetry_code, "(Cinf) "); if (NormalAxesCounts[0] > 1) { sprintf(buf, "%d*(Cinf) ", NormalAxesCounts[0]); strcat(symmetry_code, buf); } for (i = MaxAxisOrder; i >= 2; i--) { if (NormalAxesCounts[i] == 1) { sprintf(buf, "(C%d) ", i); strcat(symmetry_code, buf); } if (NormalAxesCounts[i] > 1) { sprintf(buf, "%d*(C%d) ", NormalAxesCounts[i], i); strcat(symmetry_code, buf); } } for (i = MaxAxisOrder; i >= 2; i--) { if (ImproperAxesCounts[i] == 1) { sprintf(buf, "(S%d) ", i); strcat(symmetry_code, buf); } if (ImproperAxesCounts[i] > 1) { sprintf(buf, "%d*(S%d) ", ImproperAxesCounts[i], i); strcat(symmetry_code, buf); } } if (PlanesCount == 1) strcat(symmetry_code, "(sigma) "); if (PlanesCount > 1) { sprintf(buf, "%d*(sigma) ", PlanesCount); strcat(symmetry_code, buf); } if (verbose > -1) printf("%s\n", symmetry_code); } SymmetryCode = symmetry_code; } void identify_point_group(int *point_group) { int i; int last_matching = -1; int matching_count = 0; for (i = 0; i < PointGroupsCount; i++) { if (strcmp(SymmetryCode, PointGroups[i].symmetry_code) == 0) { if (PointGroups[i].check() == 1) { last_matching = i; matching_count++; } else { if (verbose > -2) { printf("It looks very much like %s, but it is not since %s\n", PointGroups[i].group_name, PointGroupRejectionReason); } } } } if (matching_count == 0) { printf("These symmetry elements match no point group I know of. Sorry.\n"); } if (matching_count > 1) { printf("These symmetry elements match more than one group I know of.\n" "SOMETHING IS VERY WRONG\n"); printf("Matching groups are:\n"); for (i = 0; i < PointGroupsCount; i++) { if ((strcmp(SymmetryCode, PointGroups[i].symmetry_code) == 0) && (PointGroups[i].check() == 1)) { printf(" %s\n", PointGroups[i].group_name); } } } if (verbose > 0 && matching_count == 1) { printf("It seems to be the %s point group\n", PointGroups[last_matching].group_name); } *point_group = last_matching; } /* * Input/Output */ void FC_FUNC_(symmetries_finite_init, SYMMETRIES_FINITE_INIT)(const int *natoms, const int *types, const double *positions, const int *verbosity, int *point_group) { int i; verbose = *verbosity; AtomsCount = *natoms; Atoms = calloc(AtomsCount, sizeof(ATOM)); for (i = 0; i < AtomsCount; i++) { Atoms[i].type = types[i]; Atoms[i].x[0] = positions[3 * i + 0]; Atoms[i].x[1] = positions[3 * i + 1]; Atoms[i].x[2] = positions[3 * i + 2]; if (verbose > 5) printf("%d %f %f %f\n", Atoms[i].type, Atoms[i].x[0], Atoms[i].x[1], Atoms[i].x[2]); } if (AtomsCount > 0) find_symmetry_elements(); sort_symmetry_elements(); summarize_symmetry_elements(); if (BadOptimization) printf("Refinement of some symmetry elements was terminated before " "convergence was reached.\n" "Some symmetry elements may remain unidentified.\n"); if (verbose >= 0) report_symmetry_elements_verbose(); report_symmetry_elements_brief(); identify_point_group(point_group); } void FC_FUNC_(symmetries_finite_get_group_name, SYMMETRIES_FINITE_GET_GROUP_NAME)(const int *point_group, STR_F_TYPE name STR_ARG1) { TO_F_STR1(PointGroups[*point_group].group_name, name); } void FC_FUNC_(symmetries_finite_get_group_elements, SYMMETRIES_FINITE_GET_GROUP_ELEMENTS)( const int *point_group, STR_F_TYPE elements STR_ARG1) { TO_F_STR1(PointGroups[*point_group].symmetry_code, elements); } void FC_FUNC_(symmetries_finite_end, SYMMETRIES_FINITE_END)() { destroy_inversion_centers(); destroy_planes(); destroy_normal_axes(); destroy_improper_axes(); free(SymmetryCode); SymmetryCode = NULL; free(DistanceFromCenter); DistanceFromCenter = NULL; free(NormalAxesCounts); NormalAxesCounts = NULL; free(ImproperAxesCounts); ImproperAxesCounts = NULL; free(Atoms); Atoms = NULL; }
0
ALLM/M3/octopus/src
ALLM/M3/octopus/src/math/checksum.c
/* Copyright (C) 2010 X. Andrade Copyright (C) 2021 S. Ohlmann 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, 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <fortran_types.h> /* This function implements a very stupid checksum function. The only important thing is that it produces different results for arrays with the same numbers but in different orders. For more serious applications a better function must be used. */ void FC_FUNC_(checksum_calculate, CHECKSUM_CALCULATE)(const fint *algorithm, const fint8 *narray, const fint8 *array, fint8 *sum) { fint8 i; fint8 mult; *sum = 0; mult = 1; for (i = 0; i < *narray; i++) { *sum += mult * array[i]; mult++; } }
0
ALLM/M3/octopus/src
ALLM/M3/octopus/src/math/cufft.cc
/* Copyright (C) 2016 X. Andrade 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, 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <cstdio> #include <cstdlib> #include <iostream> #include <fortran_types.h> #ifdef HAVE_CUDA #ifdef HAVE_HIP #include <hip/hip_runtime.h> #include <hipfft/hipfft.h> #define cudaStream_t hipStream_t #define CUdeviceptr hipDeviceptr_t // https://rocm.docs.amd.com/projects/HIPIFY/en/latest/tables/CUFFT_API_supported_by_HIP.html #define CUFFT_ALLOC_FAILED HIPFFT_ALLOC_FAILED #define cufftDestroy hipfftDestroy #define cufftDoubleComplex hipfftDoubleComplex #define cufftDoubleReal hipfftDoubleReal #define cufftExecD2Z hipfftExecD2Z #define cufftExecZ2D hipfftExecZ2D #define cufftExecZ2Z hipfftExecZ2Z #define CUFFT_FORWARD HIPFFT_FORWARD #define cufftHandle hipfftHandle #define CUFFT_INVERSE HIPFFT_BACKWARD #define cufftPlan3d hipfftPlan3d #define cufftResult hipfftResult #define cufftSetStream hipfftSetStream #define CUFFT_SUCCESS HIPFFT_SUCCESS #define CUFFT_INVALID_PLAN HIPFFT_INVALID_PLAN #define CUFFT_ALLOC_FAILED HIPFFT_ALLOC_FAILED #define CUFFT_INVALID_VALUE HIPFFT_INVALID_VALUE #define CUFFT_INTERNAL_ERROR HIPFFT_INTERNAL_ERROR #define CUFFT_EXEC_FAILED HIPFFT_EXEC_FAILED #define CUFFT_SETUP_FAILED HIPFFT_SETUP_FAILED #define CUFFT_INVALID_SIZE HIPFFT_INVALID_SIZE #define CUFFT_INCOMPLETE_PARAMETER_LIST HIPFFT_INCOMPLETE_PARAMETER_LIST #define CUFFT_INVALID_DEVICE HIPFFT_INVALID_DEVICE #define CUFFT_PARSE_ERROR HIPFFT_PARSE_ERROR #define CUFFT_NO_WORKSPACE HIPFFT_NO_WORKSPACE #define CUFFT_NOT_IMPLEMENTED HIPFFT_NOT_IMPLEMENTED #define CUFFT_NOT_SUPPORTED HIPFFT_NOT_SUPPORTED #define cufftType hipfftType #else #include <cuda.h> #include <cufft.h> #endif #else typedef int cufftHandle; typedef int CUdeviceptr; typedef int cudaStream_t; #endif #define CUFFT_SAFE_CALL(x) cufft_safe_call((x), #x, __FILE__, __LINE__) #ifdef HAVE_CUDA static cufftResult cufft_safe_call(cufftResult safe_call_result, const char *call, const char *file, const int line) { if (safe_call_result != CUFFT_SUCCESS) { std::string error_code; std::string error_desc; switch (safe_call_result) { case CUFFT_SUCCESS: error_code = "CUFFT_SUCCESS"; error_desc = "The cuFFT operation was successful"; break; case CUFFT_INVALID_PLAN: error_code = "CUFFT_INVALID_PLAN"; error_desc = "cuFFT was passed an invalid plan handle"; break; case CUFFT_ALLOC_FAILED: error_code = "CUFFT_ALLOC_FAILED"; error_desc = "cuFFT failed to allocate GPU or CPU memory"; break; case CUFFT_INVALID_VALUE: error_code = "CUFFT_INVALID_VALUE"; error_desc = "User specified an invalid pointer or parameter"; break; case CUFFT_INTERNAL_ERROR: error_code = "CUFFT_INTERNAL_ERROR"; error_desc = "Driver or internal cuFFT library error"; break; case CUFFT_EXEC_FAILED: error_code = "CUFFT_EXEC_FAILED"; error_desc = "Failed to execute an FFT on the GPU"; break; case CUFFT_SETUP_FAILED: error_code = "CUFFT_SETUP_FAILED"; error_desc = "The cuFFT library failed to initialize"; break; case CUFFT_INVALID_SIZE: error_code = "CUFFT_INVALID_SIZE"; error_desc = "User specified an invalid transform size"; break; case CUFFT_INCOMPLETE_PARAMETER_LIST: error_code = "CUFFT_INCOMPLETE_PARAMETER_LIST"; error_desc = "Missing parameters in call"; break; case CUFFT_INVALID_DEVICE: error_code = "CUFFT_INVALID_DEVICE"; error_desc = "Execution of a plan was on different GPU than plan creation"; break; case CUFFT_PARSE_ERROR: error_code = "CUFFT_PARSE_ERROR"; error_desc = "Internal plan database error"; break; case CUFFT_NO_WORKSPACE: error_code = "CUFFT_NO_WORKSPACE"; error_desc = "No workspace has been provided prior to plan execution"; break; case CUFFT_NOT_IMPLEMENTED: error_code = "CUFFT_NOT_IMPLEMENTED"; error_desc = "Function does not implement functionality for parameters given."; break; case CUFFT_NOT_SUPPORTED: error_code = "CUFFT_NOT_SUPPORTED"; error_desc = "Operation is not supported for parameters given."; break; default: error_code = "UNKOWN"; error_desc = "Unknown error code. Potentially deprecated value for cufftResult."; break; } std::cerr << file << ":" << line << ": error: " << error_code << " (" << safe_call_result << ") while calling\n" << " " << call << "\n" << error_desc << std::endl; exit(1); } return safe_call_result; } #endif extern "C" void FC_FUNC_(cuda_fft_plan3d, CUDA_FFT_PLAN3D)(cufftHandle **plan, fint *nx, fint *ny, fint *nz, fint *type, cudaStream_t **stream) { *plan = new cufftHandle; #ifdef HAVE_CUDA CUFFT_SAFE_CALL(cufftPlan3d(*plan, *nx, *ny, *nz, (cufftType)*type)); CUFFT_SAFE_CALL(cufftSetStream(**plan, **stream)); #endif } extern "C" void FC_FUNC_(cuda_fft_destroy, CUDA_FFT_DESTROY)(cufftHandle **plan) { #ifdef HAVE_CUDA CUFFT_SAFE_CALL(cufftDestroy(**plan)); #endif delete *plan; } extern "C" void FC_FUNC_(cuda_fft_execute_d2z, CUDA_FFT_EXECUTE_D2Z)(cufftHandle **plan, CUdeviceptr **idata, CUdeviceptr **odata, cudaStream_t **stream) { #ifdef HAVE_CUDA CUFFT_SAFE_CALL(cufftSetStream(**plan, **stream)); CUFFT_SAFE_CALL(cufftExecD2Z(**plan, (cufftDoubleReal *)**idata, (cufftDoubleComplex *)**odata)); #endif } extern "C" void FC_FUNC_(cuda_fft_execute_z2d, CUDA_FFT_EXECUTE_Z2D)(cufftHandle **plan, CUdeviceptr **idata, CUdeviceptr **odata, cudaStream_t **stream) { #ifdef HAVE_CUDA CUFFT_SAFE_CALL(cufftSetStream(**plan, **stream)); CUFFT_SAFE_CALL(cufftExecZ2D(**plan, (cufftDoubleComplex *)**idata, (cufftDoubleReal *)**odata)); #endif } extern "C" void FC_FUNC_(cuda_fft_execute_z2z_forward, CUDA_FFT_EXECUTE_Z2Z_FORWARD)(cufftHandle **plan, CUdeviceptr **idata, CUdeviceptr **odata, cudaStream_t **stream) { #ifdef HAVE_CUDA CUFFT_SAFE_CALL(cufftSetStream(**plan, **stream)); CUFFT_SAFE_CALL(cufftExecZ2Z(**plan, (cufftDoubleComplex *)**idata, (cufftDoubleComplex *)**odata, CUFFT_FORWARD)); #endif } extern "C" void FC_FUNC_(cuda_fft_execute_z2z_backward, CUDA_FFT_EXECUTE_Z2Z_BACKWARD)(cufftHandle **plan, CUdeviceptr **idata, CUdeviceptr **odata, cudaStream_t **stream) { #ifdef HAVE_CUDA CUFFT_SAFE_CALL(cufftSetStream(**plan, **stream)); CUFFT_SAFE_CALL(cufftExecZ2Z(**plan, (cufftDoubleComplex *)**idata, (cufftDoubleComplex *)**odata, CUFFT_INVERSE)); #endif }
0
ALLM/M3/octopus/src
ALLM/M3/octopus/src/math/dablas.c
/* Copyright (C) 2006 X. Andrade 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, 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <stdio.h> #include <fortran_types.h> /* declare blas functions */ void FC_FUNC(dscal, DSCAL)(const fint *n, const double *a, const double *x, const fint *incx); void FC_FUNC(daxpy, DAXPY)(const fint *n, const double *a, const double *x, const fint *incx, double *y, const fint *incy); /* interface to apply blas with a real constant over complex vectors */ void FC_FUNC(dazscal, DAZSCAL)(const fint *n, const double *restrict a, double *restrict x) { const fint twon = 2 * n[0]; const fint one = 1; FC_FUNC(dscal, DSCAL)(&twon, a, x, &one); } void FC_FUNC(dazaxpy, DAZAXPY)(const fint *n, const double *restrict a, const double *restrict x, double *restrict y) { const fint twon = 2 * n[0]; const fint one = 1; FC_FUNC(daxpy, DAXPY)(&twon, a, x, &one, y, &one); } void FC_FUNC(dgemm, DGEMM)(const char *transa, const char *transb, const fint *m, const fint *n, const fint *k, const double *alpha, const double *a, const fint *lda, const double *b, const fint *ldb, const double *beta, double *c, const fint *ldc); /* interface to apply dgemm passing complex vectors the same as dgemm, but allows giving each an appropriate Fortan interface in which alpha, beta, a, b, c are actually complex in Fortran Could be inline, but in that case pgcc will not put it in the symbol table. */ void FC_FUNC(zdgemm, ZDGEMM)(const char *transa, const char *transb, const fint *m, const fint *n, const fint *k, const double *alpha, const double *restrict a, const fint *lda, const double *restrict b, const fint *ldb, const double *beta, double *restrict c, const fint *ldc) { FC_FUNC(dgemm, DGEMM) (transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc); }
0
ALLM/M3/octopus/src
ALLM/M3/octopus/src/math/fftw_low.c
/* Copyright (C) 2002 M. Marques, A. Castro, A. Rubio, G. Bertsch 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, 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <fortran_types.h> /** * Optimizes the order of the FFT grid. * The best FFT grid dimensions are given by 2^a*3^b*5^c*7^d*11^e*13^f * where a,b,c,d are arbitrary and e,f are 0 or 1. * (http://www.fftw.org/doc/Complex-DFTs.html) * par is the parity: the result must satisfy n % 2 == par, provided par >= 0. * * NTD: To make cufft and FFTW to always give the same results, the multiples * of 11 and 13 are not allowed. */ void fft_optimize(int *n, int par) { if (*n <= 2) return; for (;; (*n)++) { int i, n2; if ((par >= 0) && (*n % 2 != par)) continue; /* For debugging: */ /* printf("%i has factors ", *n); */ n2 = *n; for (i = 2; i <= n2; i++) { if (n2 % i == 0) { /* For debugging: */ /* printf("%i ", i); */ if(i > 7) break; n2 = n2 / i; i--; } } /* For debugging: */ /* printf("\n"); */ if (n2 == 1) return; } } void FC_FUNC_(oct_fft_optimize, OCT_FFT_OPTIMIZE)(fint *n, fint *par) { fft_optimize(n, *par); }
0
ALLM/M3/octopus/src
ALLM/M3/octopus/src/math/metis_f.c
/* Copyright (C) 2013 M. Oliveira 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, 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <stdlib.h> #if defined(HAVE_METIS) #include <metis.h> #endif #if defined(HAVE_PARMETIS) #include <mpi.h> #include <parmetis.h> #endif #ifdef HAVE_METIS #if defined(METIS_USE_DOUBLEPRECISION) || REALTYPEWIDTH == 64 #error METIS must be compiled in single precision for Octopus. #endif void FC_FUNC_(oct_metis_setdefaultoptions, OCT_METIS_SETDEFAULTOPTIONS)(idx_t *options) { METIS_SetDefaultOptions(options); } int FC_FUNC_(oct_metis_partgraphrecursive, OCT_METIS_PARTGRAPHRECURSIVE)( idx_t *nvtxs, idx_t *ncon, idx_t *xadj, idx_t *adjncy, idx_t *nparts, real_t *tpwgts, real_t *ubvec, idx_t *options, idx_t *objval, idx_t *part) { return METIS_PartGraphRecursive(nvtxs, ncon, xadj, adjncy, NULL, NULL, NULL, nparts, tpwgts, ubvec, options, objval, part); } int FC_FUNC_(oct_metis_partgraphkway, OCT_METIS_PARTGRAPHKWAY)( idx_t *nvtxs, idx_t *ncon, idx_t *xadj, idx_t *adjncy, idx_t *nparts, real_t *tpwgts, real_t *ubvec, idx_t *options, idx_t *objval, idx_t *part) { return METIS_PartGraphKway(nvtxs, ncon, xadj, adjncy, NULL, NULL, NULL, nparts, tpwgts, ubvec, options, objval, part); } #endif #ifdef HAVE_PARMETIS void FC_FUNC_(oct_parmetis_v3_partkway, OCT_PARMETIS_PARTKWAY)(idx_t *vtxdist, idx_t *xadj, idx_t *adjncy, idx_t *ncon, idx_t *nparts, real_t *tpwgts, real_t *ubvec, idx_t *options, idx_t *edgecut, idx_t *part, MPI_Fint *fcomm) { idx_t wgtflag = 0, numflag = 1; MPI_Comm comm; comm = MPI_Comm_f2c(*fcomm); ParMETIS_V3_PartKway(vtxdist, xadj, adjncy, NULL, NULL, &wgtflag, &numflag, ncon, nparts, tpwgts, ubvec, options, edgecut, part, &comm); } #endif
0
ALLM/M3/octopus/src
ALLM/M3/octopus/src/math/minimizer_low.c
/* Copyright (C) 2002 M. Marques, A. Castro, A. Rubio, G. Bertsch, M. Oliveira 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, 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_math.h> #include <gsl/gsl_min.h> #include <gsl/gsl_multimin.h> #include <math.h> #include <stdio.h> #include <stdlib.h> #include "string_f.h" /* A. First, the interface to the gsl function that calculates the minimum of an N-dimensional function, with the knowledge of the function itself and its gradient. */ /* This is a type used to communicate with Fortran; func_d is the type of the interface to a Fortran subroutine that calculates the function and its gradient. */ typedef void (*func_d)(const int *, const double *, double *, const int *, double *); typedef struct { func_d func; } param_fdf_t; /* Compute both f and df together. */ static void my_fdf(const gsl_vector *v, void *params, double *f, gsl_vector *df) { double *x, *gradient, ff2; int i, dim, getgrad; param_fdf_t *p; p = (param_fdf_t *)params; dim = v->size; x = (double *)malloc(dim * sizeof(double)); gradient = (double *)malloc(dim * sizeof(double)); for (i = 0; i < dim; i++) x[i] = gsl_vector_get(v, i); getgrad = (df == NULL) ? 0 : 1; p->func(&dim, x, &ff2, &getgrad, gradient); if (f != NULL) *f = ff2; if (df != NULL) { for (i = 0; i < dim; i++) gsl_vector_set(df, i, gradient[i]); } free(x); free(gradient); } static double my_f(const gsl_vector *v, void *params) { double val; my_fdf(v, params, &val, NULL); return val; } /* The gradient of f, df = (df/dx, df/dy). */ static void my_df(const gsl_vector *v, void *params, gsl_vector *df) { my_fdf(v, params, NULL, df); } typedef void (*print_f_ptr)(const int *, const int *, const double *, const double *, const double *, const double *); int FC_FUNC_(oct_minimize, OCT_MINIMIZE)(const int *method, const int *dim, double *point, const double *step, const double *line_tol, const double *tolgrad, const double *toldr, const int *maxiter, func_d f, const print_f_ptr write_info, double *minimum) { int iter = 0; int status; double maxgrad, maxdr; int i; double *oldpoint; double *grad; const gsl_multimin_fdfminimizer_type *T = NULL; gsl_multimin_fdfminimizer *s; gsl_vector *x; gsl_vector *absgrad, *absdr; gsl_multimin_function_fdf my_func; param_fdf_t p; p.func = f; oldpoint = (double *)malloc(*dim * sizeof(double)); grad = (double *)malloc(*dim * sizeof(double)); my_func.f = &my_f; my_func.df = &my_df; my_func.fdf = &my_fdf; my_func.n = *dim; my_func.params = (void *)&p; /* Starting point */ x = gsl_vector_alloc(*dim); for (i = 0; i < *dim; i++) gsl_vector_set(x, i, point[i]); /* Allocate space for the gradient */ absgrad = gsl_vector_alloc(*dim); absdr = gsl_vector_alloc(*dim); // GSL recommends line_tol = 0.1; switch (*method) { case 1: T = gsl_multimin_fdfminimizer_steepest_descent; break; case 2: T = gsl_multimin_fdfminimizer_conjugate_fr; break; case 3: T = gsl_multimin_fdfminimizer_conjugate_pr; break; case 4: T = gsl_multimin_fdfminimizer_vector_bfgs; break; case 5: T = gsl_multimin_fdfminimizer_vector_bfgs2; break; } s = gsl_multimin_fdfminimizer_alloc(T, *dim); gsl_multimin_fdfminimizer_set(s, &my_func, x, *step, *line_tol); do { iter++; for (i = 0; i < *dim; i++) oldpoint[i] = point[i]; /* Iterate */ status = gsl_multimin_fdfminimizer_iterate(s); /* Get current minimum, point and gradient */ *minimum = gsl_multimin_fdfminimizer_minimum(s); for (i = 0; i < *dim; i++) point[i] = gsl_vector_get(gsl_multimin_fdfminimizer_x(s), i); for (i = 0; i < *dim; i++) grad[i] = gsl_vector_get(gsl_multimin_fdfminimizer_gradient(s), i); /* Compute convergence criteria */ for (i = 0; i < *dim; i++) gsl_vector_set(absdr, i, fabs(point[i] - oldpoint[i])); maxdr = gsl_vector_max(absdr); for (i = 0; i < *dim; i++) gsl_vector_set(absgrad, i, fabs(grad[i])); maxgrad = gsl_vector_max(absgrad); /* Print information */ write_info(&iter, dim, minimum, &maxdr, &maxgrad, point); /* Store infomation for next iteration */ for (i = 0; i < *dim; i++) oldpoint[i] = point[i]; if (status) break; if ((maxgrad <= *tolgrad) || (maxdr <= *toldr)) status = GSL_SUCCESS; else status = GSL_CONTINUE; } while (status == GSL_CONTINUE && iter <= *maxiter); if (status == GSL_CONTINUE) status = 1025; gsl_multimin_fdfminimizer_free(s); gsl_vector_free(x); gsl_vector_free(absgrad); gsl_vector_free(absdr); free(oldpoint); free(grad); return status; } /* B. Second, the interface to the gsl function that calculates the minimum of a one-dimensional function, with the knowledge of the function itself, but not its gradient. */ /* This is a type used to communicate with Fortran; func1 is the type of the interface to a Fortran subroutine that calculates the function and its gradient. */ typedef void (*func1)(const double *, double *); typedef struct { func1 func; } param_f1_t; double fn1(double x, void *params) { param_f1_t *p = (param_f1_t *)params; double fx; p->func(&x, &fx); return fx; } void FC_FUNC_(oct_1dminimize, OCT_1DMINIMIZE)(double *a, double *b, double *m, func1 f, int *status) { int iter = 0; int max_iter = 100; const gsl_min_fminimizer_type *T; gsl_min_fminimizer *s; gsl_function F; param_f1_t p; p.func = f; F.function = &fn1; F.params = (void *)&p; T = gsl_min_fminimizer_brent; s = gsl_min_fminimizer_alloc(T); *status = gsl_min_fminimizer_set(s, &F, *m, *a, *b); gsl_set_error_handler_off(); do { iter++; *status = gsl_min_fminimizer_iterate(s); *m = gsl_min_fminimizer_x_minimum(s); *a = gsl_min_fminimizer_x_lower(s); *b = gsl_min_fminimizer_x_upper(s); *status = gsl_min_test_interval(*a, *b, 0.00001, 0.0); /*if (*status == GSL_SUCCESS) printf ("Converged:\n");*/ /*printf ("%5d [%.7f, %.7f] %.7f \n", iter, *a, *b,*m);*/ } while (*status == GSL_CONTINUE && iter < max_iter); gsl_min_fminimizer_free(s); } /* C. Third, the interface to the gsl function that calculates the minimum of an N-dimensional function, with the knowledge of the function itself, but not its gradient. */ /* This is a type used to communicate with Fortran; funcn is the type of the interface to a Fortran subroutine that calculates the function and its gradient. */ typedef void (*funcn)(int *, double *, double *); typedef struct { funcn func; } param_fn_t; double fn(const gsl_vector *v, void *params) { double val; double *x; int i, dim; param_fn_t *p; p = (param_fn_t *)params; dim = v->size; x = (double *)malloc(dim * sizeof(double)); for (i = 0; i < dim; i++) x[i] = gsl_vector_get(v, i); p->func(&dim, x, &val); free(x); return val; } typedef void (*print_f_fn_ptr)(const int *, const int *, const double *, const double *, const double *); int FC_FUNC_(oct_minimize_direct, OCT_MINIMIZE_DIRECT)(const int *method, const int *dim, double *point, const double *step, const double *toldr, const int *maxiter, funcn f, const print_f_fn_ptr write_info, double *minimum) { int iter = 0, status, i; double size; const gsl_multimin_fminimizer_type *T = NULL; gsl_multimin_fminimizer *s = NULL; gsl_vector *x, *ss; gsl_multimin_function my_func; param_fn_t p; p.func = f; my_func.f = &fn; my_func.n = *dim; my_func.params = (void *)&p; /* Set the initial vertex size vector */ ss = gsl_vector_alloc(*dim); gsl_vector_set_all(ss, *step); /* Starting point */ x = gsl_vector_alloc(*dim); for (i = 0; i < *dim; i++) gsl_vector_set(x, i, point[i]); switch (*method) { case 6: T = gsl_multimin_fminimizer_nmsimplex; break; } s = gsl_multimin_fminimizer_alloc(T, *dim); gsl_multimin_fminimizer_set(s, &my_func, x, ss); do { iter++; status = gsl_multimin_fminimizer_iterate(s); if (status) break; *minimum = gsl_multimin_fminimizer_minimum(s); for (i = 0; i < *dim; i++) point[i] = gsl_vector_get(gsl_multimin_fminimizer_x(s), i); size = gsl_multimin_fminimizer_size(s); status = gsl_multimin_test_size(size, *toldr); write_info(&iter, dim, minimum, &size, point); } while (status == GSL_CONTINUE && iter < *maxiter); if (status == GSL_CONTINUE) status = 1025; gsl_vector_free(x); gsl_vector_free(ss); gsl_multimin_fminimizer_free(s); return status; }
0
ALLM/M3/octopus/src
ALLM/M3/octopus/src/math/nfft_f.c
/* Copyright (C) 2002 M. Marques, A. Castro, A. Rubio, G. Bertsch, M. Oliveira 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, 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <complex.h> #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #ifdef HAVE_NFFT #include "nfft3.h" // #include "nfft3util.h" // No longer used in NFFT3.3.2 and later https://github.com/NFFT/nfft/commit/9f91543bbc7271d1a8cc9c21cfc87287f921bdfe #else typedef int nfft_plan; #endif // NFFT FUNCTIONS void FC_FUNC(oct_nfft_init_1d, OCT_NFFT_INIT_1D)(nfft_plan *plan, int *N1, int *M) { #ifdef HAVE_NFFT nfft_init_1d(plan, *N1, *M); #endif } void FC_FUNC(oct_nfft_init_2d, OCT_NFFT_INIT_2D)(nfft_plan *plan, int *N1, int *N2, int *M) { #ifdef HAVE_NFFT nfft_init_2d(plan, *N1, *N2, *M); #endif } void FC_FUNC(oct_nfft_init_3d, OCT_NFFT_INIT_3D)(nfft_plan *plan, int *N1, int *N2, int *N3, int *M) { #ifdef HAVE_NFFT nfft_init_3d(plan, *N1, *N2, *N3, *M); #endif } void FC_FUNC(oct_nfft_init_guru, OCT_NFFT_INIT_GURU)(nfft_plan *ths, int *d, int *N, int *M, int *n, int *m, unsigned *nfft_flags, unsigned *fftw_flags) { #ifdef HAVE_NFFT nfft_init_guru(ths, *d, N, *M, n, *m, *nfft_flags, *fftw_flags); #endif } void FC_FUNC(oct_nfft_check, OCT_NFFT_CHECK)(nfft_plan *ths) { #ifdef HAVE_NFFT nfft_check(ths); #endif } void FC_FUNC(oct_nfft_finalize, OCT_NFFT_FINALIZE)(nfft_plan *ths) { #ifdef HAVE_NFFT nfft_finalize(ths); #endif } void FC_FUNC(oct_nfft_trafo, OCT_NFFT_TRAFO)(nfft_plan *ths) { #ifdef HAVE_NFFT nfft_trafo(ths); #endif } void FC_FUNC(oct_nfft_adjoint, OCT_NFFT_ADJOINT)(nfft_plan *ths) { #ifdef HAVE_NFFT nfft_adjoint(ths); #endif } void FC_FUNC(oct_nfft_precompute_one_psi_1d, OCT_NFFT_PRECOMPUTE_ONE_PSI_1D)(nfft_plan *plan, int *m, double *X1) { #ifdef HAVE_NFFT int ii; int M = *m; for (ii = 0; ii < M; ii++) plan->x[ii] = X1[ii]; #ifdef HAVE_NFFT_3_3 if (plan->flags & PRE_ONE_PSI) nfft_precompute_one_psi(plan); #else if (plan->nfft_flags & PRE_ONE_PSI) nfft_precompute_one_psi(plan); #endif #endif } void FC_FUNC(oct_nfft_precompute_one_psi_2d, OCT_NFFT_PRECOMPUTE_ONE_PSI_2D)(nfft_plan *plan, int *M, double *X1, double *X2) { #ifdef HAVE_NFFT int ii; int jj; for (ii = 0; ii < M[0]; ii++) { for (jj = 0; jj < M[1]; jj++) { plan->x[2 * (M[1] * ii + jj) + 0] = X1[ii]; plan->x[2 * (M[1] * ii + jj) + 1] = X2[jj]; } } #ifdef HAVE_NFFT_3_3 if (plan->flags & PRE_ONE_PSI) nfft_precompute_one_psi(plan); #else if (plan->nfft_flags & PRE_ONE_PSI) nfft_precompute_one_psi(plan); #endif #endif } void FC_FUNC(oct_nfft_precompute_one_psi_3d, OCT_NFFT_PRECOMPUTE_ONE_PSI_3D)(nfft_plan *plan, int *M, double *X1, double *X2, double *X3) { #ifdef HAVE_NFFT int ii, jj, kk; for (ii = 0; ii < M[0]; ii++) { for (jj = 0; jj < M[1]; jj++) { for (kk = 0; kk < M[2]; kk++) { plan->x[3 * (M[1] * M[2] * ii + M[2] * jj + kk) + 0] = X1[ii]; plan->x[3 * (M[1] * M[2] * ii + M[2] * jj + kk) + 1] = X2[jj]; plan->x[3 * (M[1] * M[2] * ii + M[2] * jj + kk) + 2] = X3[kk]; } } } #ifdef HAVE_NFFT_3_3 if (plan->flags & PRE_ONE_PSI) nfft_precompute_one_psi(plan); #else if (plan->nfft_flags & PRE_ONE_PSI) nfft_precompute_one_psi(plan); #endif #endif } // Type dependent functions // ********** COMPLEX ************ void FC_FUNC(zoct_set_f, ZOCT_SET_F)(nfft_plan *plan, int *M, int *DIM, double complex *VAL, int *IX, int *IY, int *IZ) { #ifdef HAVE_NFFT int dim = *DIM; int ix = *IX; int iy = *IY; int iz = *IZ; double complex val = *VAL; switch (dim) { case 1: plan->f[ix - 1] = val; break; case 2: plan->f[(ix - 1) * M[1] + (iy - 1)] = val; break; case 3: plan->f[(ix - 1) * M[1] * M[2] + (iy - 1) * M[2] + (iz - 1)] = val; break; } #endif } void FC_FUNC(zoct_get_f, ZOCT_GET_F)(nfft_plan *plan, int *M, int *DIM, double complex *val, int *IX, int *IY, int *IZ) { #ifdef HAVE_NFFT int dim = *DIM; int ix = *IX; int iy = *IY; int iz = *IZ; switch (dim) { case 1: *val = plan->f[ix - 1]; break; case 2: *val = plan->f[(ix - 1) * M[1] + (iy - 1)]; break; case 3: *val = plan->f[(ix - 1) * M[1] * M[2] + (iy - 1) * M[2] + (iz - 1)]; break; } #endif } void FC_FUNC(zoct_set_f_hat, ZOCT_SET_F_HAT)(nfft_plan *plan, int *DIM, double complex *VAL, int *IX, int *IY, int *IZ) { #ifdef HAVE_NFFT int dim = *DIM; int ix = *IX; int iy = *IY; int iz = *IZ; double complex val = *VAL; switch (dim) { case 1: plan->f_hat[ix - 1] = val; break; case 2: plan->f_hat[(ix - 1) * plan->N[1] + (iy - 1)] = val; break; case 3: plan->f_hat[(ix - 1) * plan->N[1] * plan->N[2] + (iy - 1) * plan->N[2] + (iz - 1)] = val; break; } #endif } void FC_FUNC(zoct_get_f_hat, ZOCT_GET_F_HAT)(nfft_plan *plan, int *DIM, double complex *val, int *IX, int *IY, int *IZ) { #ifdef HAVE_NFFT int dim = *DIM; int ix = *IX; int iy = *IY; int iz = *IZ; switch (dim) { case 1: *val = plan->f_hat[ix - 1]; break; case 2: *val = plan->f_hat[(ix - 1) * plan->N[1] + (iy - 1)]; break; case 3: *val = plan->f_hat[(ix - 1) * plan->N[1] * plan->N[2] + (iy - 1) * plan->N[2] + (iz - 1)]; break; } #endif } // ********** DOUBLE ************ void FC_FUNC(doct_set_f, DOCT_SET_F)(nfft_plan *plan, int *M, int *DIM, double *VAL, int *IX, int *IY, int *IZ) { #ifdef HAVE_NFFT int dim = *DIM; int ix = *IX; int iy = *IY; int iz = *IZ; double val = *VAL; switch (dim) { case 1: plan->f[ix - 1] = val; break; case 2: plan->f[(ix - 1) * M[1] + (iy - 1)] = val; break; case 3: plan->f[(ix - 1) * M[1] * M[2] + (iy - 1) * M[2] + (iz - 1)] = val; break; } #endif } void FC_FUNC(doct_get_f, DOCT_GET_F)(nfft_plan *plan, int *M, int *DIM, double *val, int *IX, int *IY, int *IZ) { #ifdef HAVE_NFFT int dim = *DIM; int ix = *IX; int iy = *IY; int iz = *IZ; switch (dim) { case 1: *val = plan->f[ix - 1]; break; case 2: *val = plan->f[(ix - 1) * M[1] + (iy - 1)]; break; case 3: *val = plan->f[(ix - 1) * M[1] * M[2] + (iy - 1) * M[2] + (iz - 1)]; break; } #endif } void FC_FUNC(doct_set_f_hat, DOCT_SET_F_HAT)(nfft_plan *plan, int *DIM, double *VAL, int *IX, int *IY, int *IZ) { #ifdef HAVE_NFFT int dim = *DIM; int ix = *IX; int iy = *IY; int iz = *IZ; double val = *VAL; switch (dim) { case 1: plan->f_hat[ix - 1] = val; break; case 2: plan->f_hat[(ix - 1) * plan->N[1] + (iy - 1)] = val; break; case 3: plan->f_hat[(ix - 1) * plan->N[1] * plan->N[2] + (iy - 1) * plan->N[2] + (iz - 1)] = val; break; } #endif } void FC_FUNC(doct_get_f_hat, DOCT_GET_F_HAT)(nfft_plan *plan, int *DIM, double *val, int *IX, int *IY, int *IZ) { #ifdef HAVE_NFFT int dim = *DIM; int ix = *IX; int iy = *IY; int iz = *IZ; switch (dim) { case 1: *val = plan->f_hat[ix - 1]; break; case 2: *val = plan->f_hat[(ix - 1) * plan->N[1] + (iy - 1)]; break; case 3: *val = plan->f_hat[(ix - 1) * plan->N[1] * plan->N[2] + (iy - 1) * plan->N[2] + (iz - 1)]; break; } #endif }
0
ALLM/M3/octopus/src
ALLM/M3/octopus/src/math/oct_gsl_f.c
/* Copyright (C) 2002 M. Marques, A. Castro, A. Rubio, G. Bertsch, M. Oliveira 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, 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <math.h> #include <stdio.h> #include <stdlib.h> #include <gsl/gsl_combination.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_sf.h> #include "string_f.h" #include <fortran_types.h> /* Numerical threshold for oct_bessel_k0 and oct_bessel_k1 */ #define BESSEL_K_THRES 1.0e2 /* ---------------------- Interface to GSL functions ------------------------ */ /* Special Functions */ double FC_FUNC_(oct_gamma, OCT_GAMMA)(const double *x) { return gsl_sf_gamma(*x); } double FC_FUNC_(oct_incomplete_gamma, OCT_INCOMPLETE_GAMMA)(const double *a, const double *x) { return gsl_sf_gamma_inc_Q(*a, *x); } double FC_FUNC_(oct_sph_bessel, OCT_SPH_BESSEL)(const fint *l, const double *x) { if (*l == 0) { return gsl_sf_bessel_j0(*x); } else if (*l == 1) { return gsl_sf_bessel_j1(*x); } else if (*l == 2) { return gsl_sf_bessel_j2(*x); } else { return gsl_sf_bessel_jl(*l, *x); } } double FC_FUNC_(oct_bessel, OCT_BESSEL)(const fint *n, const double *x) { return gsl_sf_bessel_Jn(*n, *x); } double FC_FUNC_(oct_bessel_in, OCT_BESSEL_IN)(const fint *n, const double *x) { return gsl_sf_bessel_In(*n, *x); } double FC_FUNC_(oct_bessel_j0, OCT_BESSEL_J0)(const double *x) { return gsl_sf_bessel_J0(*x); } double FC_FUNC_(oct_bessel_j1, OCT_BESSEL_J1)(const double *x) { return gsl_sf_bessel_J1(*x); } double FC_FUNC_(oct_bessel_k0, OCT_BESSEL_K0)(const double *x) { if (*x > BESSEL_K_THRES) { return 0.0e0; } else { return gsl_sf_bessel_K0(*x); } } double FC_FUNC_(oct_bessel_k1, OCT_BESSEL_K1)(const double *x) { if (*x > BESSEL_K_THRES) { return 0.0e0; } else { return gsl_sf_bessel_K1(*x); } } /* the GSL headers specify double x, not const double x */ double FC_FUNC_(oct_erfc, OCT_ERFC)(const double *x) { /* avoid floating invalids in the asymptotic limit */ if (*x > 20.0) return 0.0; if (*x < -20.0) return 2.0; /* otherwise call gsl */ return gsl_sf_erfc(*x); } /* the GSL headers specify double x, not const double x */ double FC_FUNC_(oct_erf, OCT_ERF)(const double *x) { /* avoid floating invalids in the asymptotic limit */ if (*x > 20.0) return 1.0; if (*x < -20.0) return -1.0; /* otherwise call gsl */ return gsl_sf_erf(*x); } double FC_FUNC_(oct_legendre_sphplm, OCT_LEGENDRE_SPHPLM)(const fint *l, const int *m, const double *x) { return gsl_sf_legendre_sphPlm(*l, *m, *x); } /* generalized Laguerre polynomials */ double FC_FUNC_(oct_sf_laguerre_n, OCT_SF_LAGUERRE_N)(const int *n, const double *a, const double *x) { return gsl_sf_laguerre_n(*n, *a, *x); } /* Combinations */ void FC_FUNC_(oct_combination_init, OCT_COMBINATION_INIT)(gsl_combination **c, const fint *n, const fint *k) { *c = gsl_combination_calloc(*n, *k); } void FC_FUNC_(oct_combination_next, OCT_COMBINATION_NEXT)(gsl_combination **c, fint *next) { *next = gsl_combination_next(((gsl_combination *)(*c))); } void FC_FUNC_(oct_get_combination, OCT_GET_COMBINATION)(gsl_combination **c, fint *comb) { int i; for (i = 0; i < ((gsl_combination *)(*c))->k; i++) { comb[i] = (fint)((gsl_combination *)(*c))->data[i]; } } void FC_FUNC_(oct_combination_end, OCT_COMBINATION_END)(gsl_combination **c) { gsl_combination_free(((gsl_combination *)(*c))); } /* Random Number Generation */ void FC_FUNC_(oct_ran_init, OCT_RAN_INIT)(gsl_rng **r) { gsl_rng_env_setup(); *r = gsl_rng_alloc(gsl_rng_default); } void FC_FUNC_(oct_ran_end, OCT_RAN_END)(gsl_rng **r) { gsl_rng_free(*r); } /* Random Number Distributions */ double FC_FUNC_(oct_ran_gaussian, OCT_RAN_GAUSSIAN)(const gsl_rng **r, const double *sigma) { return gsl_ran_gaussian(*r, *sigma); } double FC_FUNC_(oct_ran_flat, OCT_RAN_FLAT)(const gsl_rng **r, const double *a, const double *b) { return gsl_ran_flat(*r, *a, *b); } void FC_FUNC_(oct_strerror, OCT_STRERROR)(const fint *err, STR_F_TYPE res STR_ARG1) { const char *c; c = gsl_strerror(*err); TO_F_STR1(c, res); }
0
ALLM/M3/octopus/src
ALLM/M3/octopus/src/math/spline_low.cc
/* Copyright (C) 2016 M. Marques, A. Castro, A. Rubio, G. Bertsch, M. Oliveira, X. Andrade // Spline routines produced at the Lawrence Livermore National // Laboratory. Written by Xavier Andrade (xavier@llnl.gov), Erik // Draeger (draeger1@llnl.gov) and Francois Gygi (fgygi@ucdavis.edu). 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, 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <math.h> #include <stdio.h> #include <stdlib.h> #include <gsl/gsl_spline.h> #include "string_f.h" #include <fortran_types.h> #include <assert.h> #include <iostream> #include <vector> /* Interpolation */ extern "C" void FC_FUNC_(oct_spline_end, OCT_SPLINE_END)(void **spl, void **acc) { gsl_spline_free((gsl_spline *)(*spl)); gsl_interp_accel_free((gsl_interp_accel *)(*acc)); } extern "C" void FC_FUNC_(oct_spline_fit, OCT_SPLINE_FIT)(const fint *nrc, const double *x, const double *y, void **spl, void **acc) { /* the GSL headers actually specify size_t instead of const int for nrc */ *acc = (void *)gsl_interp_accel_alloc(); *spl = (void *)gsl_spline_alloc(gsl_interp_cspline, *nrc); gsl_spline_init((gsl_spline *)(*spl), x, y, *nrc); fflush(stdout); } extern "C" double FC_FUNC_(oct_spline_eval, OCT_SPLINE_EVAL)(const double *x, const void **spl, void **acc) { /* the GSL headers specify double x instead of const double x */ return gsl_spline_eval((gsl_spline *)(*spl), *x, (gsl_interp_accel *)(*acc)); } template <typename Type, int stride> void oct_spline_eval_array(fint nn, Type *xf, const void **spl, void **acc) { for (fint ii = 0; ii < nn; ii++) { xf[stride * ii] = Type(gsl_spline_eval( (gsl_spline *)(*spl), xf[stride * ii], (gsl_interp_accel *)(*acc))); } } extern "C" void FC_FUNC_(oct_spline_eval_array, OCT_SPLINE_EVAL_ARRAY)(const fint *nn, double *xf, const void **spl, void **acc) { oct_spline_eval_array<double, 1>(*nn, xf, spl, acc); } /* use a stride of 2 to store into just the real part of a Fortran complex array */ extern "C" void FC_FUNC_(oct_spline_eval_arrayz, OCT_SPLINE_EVAL_ARRAYZ)(const fint *nn, double *xf, const void **spl, void **acc) { oct_spline_eval_array<double, 2>(*nn, xf, spl, acc); } /* This function returns the number of points with which a spline was constructed (the size component of the gsl_spline struct). */ extern "C" fint FC_FUNC_(oct_spline_npoints, OCT_SPLINE_NPOINTS)(const void **spl, void **acc) { return (fint)((gsl_spline *)(*spl))->size; } /* This function places in the x array the x values of a given spline spl*/ extern "C" void FC_FUNC_(oct_spline_x, OCT_SPLINE_X)(const void **spl, double *x) { int size, i; size = (int)((gsl_spline *)(*spl))->size; for (i = 0; i < size; i++) x[i] = ((gsl_spline *)(*spl))->x[i]; } /* This function places in the y array the y values of a given spline spl*/ extern "C" void FC_FUNC_(oct_spline_y, OCT_SPLINE_Y)(const void **spl, double *y) { int size, i; size = (int)((gsl_spline *)(*spl))->size; for (i = 0; i < size; i++) y[i] = ((gsl_spline *)(*spl))->y[i]; } /* Returns the integral of the spline stored in spl, between a and b */ extern "C" double FC_FUNC_(oct_spline_eval_integ, OCT_SPLINE_EVAL_INTEG)(const void **spl, const double *a, const double *b, void **acc) { /* the GSL headers specify double a, double b */ return gsl_spline_eval_integ((gsl_spline *)(*spl), *a, *b, (gsl_interp_accel *)(*acc)); } extern "C" double FC_FUNC_(oct_spline_eval_integ_full, OCT_SPLINE_EVAL_INTEG_FULL)(const void **spl, void **acc) { /* the GSL headers specify double a, double b */ const int size = (int)((gsl_spline *)(*spl))->size; const double a = ((gsl_spline *)(*spl))->x[0]; const double b = ((gsl_spline *)(*spl))->x[size - 1]; return gsl_spline_eval_integ((gsl_spline *)(*spl), a, b, (gsl_interp_accel *)(*acc)); } /* Performs the derivative of a spline */ extern "C" double FC_FUNC_(oct_spline_eval_der, OCT_SPLINE_EVAL_DER)(const double *x, const void **spl, void **acc) { /* the GSL headers specify double x */ return gsl_spline_eval_deriv((gsl_spline *)(*spl), *x, (gsl_interp_accel *)(*acc)); } /* Performs the second derivative of a spline */ extern "C" double FC_FUNC_(oct_spline_eval_der2, OCT_SPLINE_EVAL_DER2)(const double *x, const void **spl, void **acc) { /* the GSL headers specify double x */ return gsl_spline_eval_deriv2((gsl_spline *)(*spl), *x, (gsl_interp_accel *)(*acc)); }
0
ALLM/M3/octopus/src
ALLM/M3/octopus/src/math/ylm.c
/* Copyright (C) 2002 M. Marques, A. Castro, A. Rubio, G. Bertsch 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, 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <float.h> #include <fortran_types.h> #include <math.h> #include <stdlib.h> #include <gsl/gsl_sf_legendre.h> /* normalization constants for the spherical harmonics */ static double sph_cnsts[16] = { /* l = 0 */ 0.28209479177387814347403972578, /* l = 1 */ 0.48860251190291992158638462283, 0.48860251190291992158638462283, 0.48860251190291992158638462283, /* l = 2 */ 1.09254843059207907054338570580, 1.09254843059207907054338570580, 0.31539156525252000603089369029, 1.09254843059207907054338570580, 0.54627421529603953527169285290, /* l = 3 */ 0.59004358992664351034561027754, 2.89061144264055405538938015439, 0.45704579946446573615802069691, 0.37317633259011539141439591319, 0.45704579946446573615802069691, 1.44530572132027702769469007719, 0.59004358992664351034561027754}; void oct_ylm_base(const double *r, const double *x, const double *y, const double *z, const fint *l, const fint *m, double *ylm); /* Computes real spherical harmonics ylm in the direction of vector r: ylm = c * plm( cos(theta) ) * sin(m*phi) for m < 0 ylm = c * plm( cos(theta) ) * cos(m*phi) for m >= 0 with (theta,phi) the polar angles of r, c a positive normalization constant and plm associated legendre polynomials. */ void FC_FUNC_(oct_ylm, OCT_YLM)(const fint *np, const double *x, const double *y, const double *z, const fint *l, const fint *m, double *restrict ylm) { if (l[0] == 0) { for (int ip = 0; ip < np[0]; ip++) ylm[ip] = sph_cnsts[0]; return; } for (int ip = 0; ip < np[0]; ip++) { double rr = sqrt(x[ip] * x[ip] + y[ip] * y[ip] + z[ip] * z[ip]); oct_ylm_base(&rr, &x[ip], &y[ip], &z[ip], l, m, &ylm[ip]); } } void FC_FUNC_(oct_ylm_vector, OCT_YLM_VECTOR)(const fint *np, const double *xx, const double *rr, const fint *l, const fint *m, double *restrict ylm) { if (l[0] == 0) { for (int ip = 0; ip < np[0]; ip++) ylm[ip] = sph_cnsts[0]; return; } for (int ip = 0; ip < np[0]; ip++) { oct_ylm_base(&rr[ip], &xx[ip * 3], &xx[ip * 3 + 1], &xx[ip * 3 + 2], l, m, &ylm[ip]); } } void oct_ylm_base(const double *r, const double *x, const double *y, const double *z, const fint *l, const fint *m, double *ylm) { double r2, r3, rr, rx, ry, rz, cosphi, sinphi, cosm, sinm, phase; int i; r2 = r[0] * r[0]; /* if r=0, direction is undefined => make ylm=0 except for l=0 */ if (r2 < 1.0e-30) { ylm[0] = 0.0; return; } switch (l[0]) { case 1: rr = 1.0 / r[0]; switch (m[0]) { case -1: ylm[0] = -sph_cnsts[1] * rr * y[0]; return; case 0: ylm[0] = sph_cnsts[2] * rr * z[0]; return; case 1: ylm[0] = -sph_cnsts[3] * rr * x[0]; return; } case 2: switch (m[0]) { case -2: ylm[0] = sph_cnsts[4] * x[0] * y[0] / r2; return; case -1: ylm[0] = -sph_cnsts[5] * y[0] * z[0] / r2; return; case 0: ylm[0] = sph_cnsts[6] * (3.0 * z[0] * z[0] / r2 - 1.0); return; case 1: ylm[0] = -sph_cnsts[7] * x[0] * z[0] / r2; return; case 2: ylm[0] = sph_cnsts[8] * (x[0] * x[0] - y[0] * y[0]) / r2; return; } case 3: r3 = r2 * r[0]; switch (m[0]) { case -3: ylm[0] = sph_cnsts[9] * ((3.0 * x[0] * x[0] - y[0] * y[0]) * y[0]) / r3; return; case -2: ylm[0] = sph_cnsts[10] * (x[0] * y[0] * z[0]) / r3; return; case -1: ylm[0] = sph_cnsts[11] * (y[0] * (5.0 * z[0] * z[0] - r2)) / r3; return; case 0: ylm[0] = sph_cnsts[12] * (z[0] * (5.0 * z[0] * z[0] - 3.0 * r2)) / r3; return; case 1: ylm[0] = sph_cnsts[13] * (x[0] * (5.0 * z[0] * z[0] - r2)) / r3; return; case 2: ylm[0] = sph_cnsts[14] * ((x[0] * x[0] - y[0] * y[0]) * z[0]) / r3; return; case 3: ylm[0] = sph_cnsts[15] * ((x[0] * x[0] - 3.0 * y[0] * y[0]) * x[0]) / r3; return; } } /* get phase */ rr = 1.0 / r[0]; rx = x[0] * rr; ry = y[0] * rr; rz = z[0] * rr; rr = hypot(rx, ry); if (rr < 1e-20) { cosphi = 0.0; sinphi = 0.0; } else { cosphi = rx / rr; sinphi = ry / rr; } /* compute sin(mphi) and cos(mphi) by adding cos/sin */ cosm = 1.; sinm = 0.; for (i = 0; i < abs(m[0]); i++) { double a = cosm, b = sinm; cosm = a * cosphi - b * sinphi; sinm = a * sinphi + b * cosphi; } phase = m[0] < 0 ? sinm : cosm; phase = m[0] == 0 ? phase : sqrt(2.0) * phase; /* lower bound with a small number (~= 10^-308) to avoid floating invalids */ rz = rz < DBL_MIN ? DBL_MIN : rz; rr = gsl_sf_legendre_sphPlm(l[0], abs(m[0]), rz); /* I am not sure whether we are including the Condon-Shortley factor (-1)^m */ ylm[0] = rr * phase; }
0
ALLM/M3/octopus/src
ALLM/M3/octopus/src/poisson/poisson_cutoffs.c
/* Copyright (C) 2006-2008 Luis Matos, A. Castro 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, 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <assert.h> #include <config.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_integration.h> #include <gsl/gsl_sf_bessel.h> #include <gsl/gsl_sf_expint.h> #include <math.h> #include <stdio.h> #define M_EULER_MASCHERONI 0.5772156649015328606065120 /* This file contains the definition of functions used by Fortran module poisson_cutoff_m. There are four functions to be defined: c_poisson_cutoff_3d_1d_finite: For the cutoff of 3D/0D cases, in which however we want the region of the cutoff to be a cylinder. c_poisson_cutoff_2d_0d: c_poisson_cutoff_2d_1d: */ /************************************************************************/ /************************************************************************/ /* C_POISSON_CUTOFF_3D_1D_FINITE */ /************************************************************************/ /************************************************************************/ struct parameters { double kx; double kr; double x0; double r0; int index; }; /* the index is the type of integral. This is necessary because depending of the value of k the the integral needs to be performed in different ways */ #define PFC_F_0 0 #define PFC_F_KX 1 #define PFC_F_KR 2 static const double tol = 1e-7; static double zero = 1e-100; static double f(double w, void *p) { struct parameters *params = (struct parameters *)p; const double kx = (params->kx); double kr = (params->kr); double x0 = (params->x0); double r0 = (params->r0); int index = (params->index); double result; if (w == 0) w = zero; if (fabs(kx - w) > tol) { result = sin((kx - w) * x0) / (kx - w) * sqrt(pow(w, 2.0 * index) * pow(r0, 2.0 * index)) / (kr * kr + w * w) * gsl_sf_bessel_Kn(index, r0 * fabs(w)); } else { result = x0 * sqrt(pow(w, 2.0 * index)) / (kr * kr + w * w) * gsl_sf_bessel_Kn(index, r0 * fabs(w)); } return result; } static double f_kx_zero(double w, void *p) { struct parameters *params = (struct parameters *)p; double kr = (params->kr); double x0 = (params->x0); double result; if (w == 0.0) w = zero; result = 2.0 * M_PI * w * gsl_sf_bessel_J0(kr * w) * (log(x0 + sqrt(w * w + x0 * x0)) - log(-x0 + sqrt(w * w + x0 * x0))); return result; } static double f_kr_zero(double w, void *p) { struct parameters *params = (struct parameters *)p; double kx = (params->kx); double r0 = (params->r0); double result; result = 4.0 * M_PI * cos(kx * w) * (sqrt(r0 * r0 + w * w) - fabs(w)); return result; } static double int_aux(int index, double kx, double kr, double x0, double r0, int which_int) { /*variables*/ double result, error; double xinf = 100.0 / r0; struct parameters params; /*pass the given parameters to program*/ const size_t wrk_size = 5000; /* I believe that 1e-6 is over-killing, a substantial gain in time is obtained by setting this threshold to 1e-3 */ /* const double epsilon_abs = 1e-6; */ /* const double epsilon_rel = 1e-6; */ const double epsilon_abs = 1e-3; const double epsilon_rel = 1e-3; /*creating the workspace*/ gsl_integration_workspace *ws = gsl_integration_workspace_alloc(wrk_size); /*create the function*/ gsl_function F; assert(which_int == PFC_F_0 || which_int == PFC_F_KR || which_int == PFC_F_KX); params.kx = kx; params.kr = kr; params.x0 = x0; params.r0 = r0; params.index = index; F.params = &params; /*select the integration method*/ switch (which_int) { case PFC_F_0: F.function = &f; gsl_integration_qag(&F, -xinf, xinf, epsilon_abs, epsilon_rel, wrk_size, 3, ws, &result, &error); break; case PFC_F_KX: F.function = &f_kx_zero; gsl_integration_qag(&F, 0.0, r0, epsilon_abs, epsilon_rel, wrk_size, 3, ws, &result, &error); break; case PFC_F_KR: F.function = &f_kr_zero; gsl_integration_qag(&F, 0.0, x0, epsilon_abs, epsilon_rel, wrk_size, 3, ws, &result, &error); break; } /*free the integration workspace*/ gsl_integration_workspace_free(ws); /*return*/ return result; } double poisson_finite_cylinder(double kx, double kr, double x0, double r0) { double result; if ((kx >= tol) & (kr >= tol)) { result = 4.0 * kr * r0 * gsl_sf_bessel_Jn(1, kr * r0) * int_aux(0, kx, kr, x0, r0, PFC_F_0) - 4.0 * gsl_sf_bessel_Jn(0, kr * r0) * int_aux(1, kx, kr, x0, r0, PFC_F_0) + 4.0 * M_PI / (kx * kx + kr * kr) * (1.0 + exp(-kr * x0) * (kx / kr * sin(kx * x0) - cos(kx * x0))); } else if ((kx < tol) & (kr >= tol)) { result = int_aux(0, kx, kr, x0, r0, PFC_F_KX); } else if ((kx >= tol) & (kr < tol)) { result = int_aux(0, kx, kr, x0, r0, PFC_F_KR); } else result = -2.0 * M_PI * (log(r0 / (x0 + sqrt(r0 * r0 + x0 * x0))) * r0 * r0 + x0 * (x0 - sqrt(r0 * r0 + x0 * x0))); /* the 1/(4pi) factor is due to the factor on the poissonsolver3d (end)*/ return result / (4.0 * M_PI); } /* --------------------- Interface to Fortran ---------------------- */ double FC_FUNC_(c_poisson_cutoff_3d_1d_finite, C_POISSON_CUTOFF_3D_1D_FINITE)(double *gx, double *gperp, double *xsize, double *rsize) { return poisson_finite_cylinder(*gx, *gperp, *xsize, *rsize); } /************************************************************************/ /************************************************************************/ /* C_POISSON_CUTOFF_2D_0D */ /************************************************************************/ /************************************************************************/ static double bessel_J0(double w, void *p) { return gsl_sf_bessel_J0(w); } /* --------------------- Interface to Fortran ---------------------- */ double FC_FUNC_(c_poisson_cutoff_2d_0d, C_POISSON_CUTOFF_2D_0D)(double *x, double *y) { double result, error; const size_t wrk_size = 500; const double epsilon_abs = 1e-3; const double epsilon_rel = 1e-3; gsl_integration_workspace *ws = gsl_integration_workspace_alloc(wrk_size); gsl_function F; F.function = &bessel_J0; gsl_integration_qag(&F, *x, *y, epsilon_abs, epsilon_rel, wrk_size, 3, ws, &result, &error); gsl_integration_workspace_free(ws); return result; } /************************************************************************/ /************************************************************************/ /* INTCOSLOG */ /************************************************************************/ /************************************************************************/ /* Int_0^mu dy cos(a*y) log(abs(b*y)) = (1/a) * (log(|b*mu|)*sin(a*mu) - Si(a*mu) ) */ double FC_FUNC(intcoslog, INTCOSLOG)(double *mu, double *a, double *b) { if (fabs(*a) > 0.0) { return (1.0 / (*a)) * (log((*b) * (*mu)) * sin((*a) * (*mu)) - gsl_sf_Si((*a) * (*mu))); } else { return (*mu) * (log((*mu) * (*b)) - 1.0); } } /************************************************************************/ /************************************************************************/ /* C_POISSON_CUTOFF_2D_1D */ /************************************************************************/ /************************************************************************/ struct parameters_2d_1d { double gx; double gy; double rc; }; static double cutoff_2d_1d(double w, void *p) { double k0arg, k0; struct parameters_2d_1d *params = (struct parameters_2d_1d *)p; double gx = (params->gx); double gy = (params->gy); k0arg = fabs(w * gx); if (k0arg < 0.05) { k0 = -(log(k0arg / 2) + M_EULER_MASCHERONI); } else if (k0arg < 50.0) { k0 = gsl_sf_bessel_K0(k0arg); } else { k0 = sqrt(2.0 * M_PI / k0arg) * exp(-k0arg); } return 4.0 * cos(w * gy) * k0; } /* --------------------- Interface to Fortran ---------------------- */ double FC_FUNC_(c_poisson_cutoff_2d_1d, C_POISSON_CUTOFF_2D_1D)(double *gy, double *gx, double *rc) { double result, error, res, b; struct parameters_2d_1d params; const size_t wrk_size = 5000; const double epsilon_abs = 1e-3; const double epsilon_rel = 1e-3; double mu; gsl_integration_workspace *ws = gsl_integration_workspace_alloc(wrk_size); gsl_function F; mu = 0.1 / (*gx); b = fabs((*gx)) / 2.0; params.gx = *gx; params.gy = *gy; params.rc = *rc; F.function = &cutoff_2d_1d; F.params = &params; res = -4.0 * FC_FUNC(intcoslog, INTCOSLOG)(&mu, gy, &b); if (fabs(*gy) > 0.0) { res = res - (4.0 * M_EULER_MASCHERONI / (*gy)) * sin((*gy) * mu); } else { res = res - 4.0 * M_EULER_MASCHERONI * mu; } gsl_integration_qag(&F, mu, (*rc), epsilon_abs, epsilon_rel, wrk_size, 3, ws, &result, &error); res = res + result; gsl_integration_workspace_free(ws); return res; } /************************************************************************/ /************************************************************************/ /* C_POISSON_CUTOFF_1D_0D */ /************************************************************************/ /************************************************************************/ struct parameters_1d_0d { double g; double a; }; static double cutoff_1d_0d(double w, void *p) { struct parameters_1d_0d *params = (struct parameters_1d_0d *)p; double g = (params->g); double a = (params->a); return 2.0 * (cos(w) / sqrt(w * w + a * a * g * g)); } /* --------------------- Interface to Fortran ---------------------- */ double FC_FUNC_(c_poisson_cutoff_1d_0d, C_POISSON_CUTOFF_1D_0D)(double *g, double *a, double *rc) { double result, error; struct parameters_1d_0d params; const size_t wrk_size = 5000; const double epsilon_abs = 1e-3; const double epsilon_rel = 1e-3; int status; gsl_integration_workspace *ws; gsl_function F; if ((*g) <= 0.0) { return 2.0 * asinh((*rc) / (*a)); }; if ((*g) * (*rc) > 100.0 * M_PI) { return 2.0 * gsl_sf_bessel_K0((*a) * (*g)); }; gsl_set_error_handler_off(); ws = gsl_integration_workspace_alloc(wrk_size); params.g = *g; params.a = *a; F.function = &cutoff_1d_0d; F.params = &params; status = gsl_integration_qag(&F, 0.0, (*rc) * (*g), epsilon_abs, epsilon_rel, wrk_size, 3, ws, &result, &error); gsl_integration_workspace_free(ws); if (status) { return 0.0; } else { return result; } }
0
ALLM/M3/octopus/src
ALLM/M3/octopus/src/species/anygrid.hpp
#ifndef PSEUDO_ANYGRID_HPP #define PSEUDO_ANYGRID_HPP /* Copyright (C) 2018 Xavier Andrade This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "base.hpp" #include "spline.h" #include <string> #include <vector> namespace pseudopotential { class anygrid : public pseudopotential::base { public: anygrid(bool uniform_grid) : uniform_grid_(uniform_grid) {} double mesh_spacing() const { return 0.01; } int mesh_size() const { if (uniform_grid_) { return mesh_size_; } else { return grid_.size(); } } virtual void grid(std::vector<double> &val) const { if (uniform_grid_) { pseudopotential::base::grid(val); } else { val = grid_; } } virtual void grid_weights(std::vector<double> &val) const { if (uniform_grid_) { pseudopotential::base::grid(val); } else { val = grid_weights_; } } protected: void interpolate(std::vector<double> &function) const { if (!uniform_grid_) return; std::vector<double> function_in_grid = function; assert(function.size() == grid_.size()); Spline function_spline; function_spline.fit(grid_.data(), function_in_grid.data(), function_in_grid.size(), SPLINE_FLAT_BC, SPLINE_NATURAL_BC); function.clear(); for (double rr = 0.0; rr <= grid_[grid_.size() - 1]; rr += mesh_spacing()) { function.push_back(function_spline.value(rr)); } } bool uniform_grid_; std::vector<double> grid_; std::vector<double> grid_weights_; int mesh_size_; }; } // namespace pseudopotential #endif
0
ALLM/M3/octopus/src
ALLM/M3/octopus/src/species/base.hpp
#ifndef PSEUDO_BASE_HPP #define PSEUDO_BASE_HPP /* Copyright (C) 2018 Xavier Andrade This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include <rapidxml.hpp> #include <sstream> #include <string> #include <vector> #define MAX_L 10 #define INVALID_L 333 namespace pseudopotential { enum class type { ULTRASOFT = 30, SEMILOCAL = 31, KLEINMAN_BYLANDER = 32, PAW = 33 }; enum class status { SUCCESS = 0, FILE_NOT_FOUND = 455, FORMAT_NOT_SUPPORTED = 456, UNKNOWN_FORMAT = 457, UNSUPPORTED_TYPE_ULTRASOFT = 458, UNSUPPORTED_TYPE_PAW = 459, UNSUPPORTED_TYPE = 460 }; enum class format { FILE_NOT_FOUND = 773, UNKNOWN = 774, UPF1 = 775, UPF2 = 776, QSO = 777, PSML = 778, PSF = 779, CPI = 780, FHI = 781, HGH = 782, PSP8 = 783 }; // these values match libxc convention enum class exchange { UNKNOWN = -2, ANY = -1, NONE = 0, LDA = 1, PBE = 101, PBE_SOL = 116, B88 = 106 }; enum class correlation { UNKNOWN = -2, ANY = -1, NONE = 0, LDA_PZ = 9, LDA_PW = 12, LDA_XC_TETER93 = 20, PBE = 130, PBE_SOL = 133, LYP = 131 }; class base { public: virtual ~base() {} virtual pseudopotential::type type() const { return type_; } virtual int lmax() const { return lmax_; } // Pure virtual functions virtual pseudopotential::format format() const = 0; virtual int size() const = 0; virtual std::string description() const = 0; virtual std::string symbol() const = 0; virtual int atomic_number() const = 0; virtual double mass() const = 0; virtual double valence_charge() const = 0; virtual int llocal() const = 0; virtual int nchannels() const = 0; virtual double mesh_spacing() const = 0; virtual int mesh_size() const = 0; virtual void local_potential(std::vector<double> &potential) const = 0; virtual int nprojectors() const = 0; virtual int nprojectors_per_l(int l) const = 0; virtual void projector(int l, int i, std::vector<double> &proj) const = 0; virtual double d_ij(int l, int i, int j) const = 0; virtual bool has_radial_function(int l) const = 0; virtual void radial_function(int l, std::vector<double> &function) const = 0; virtual void radial_potential(int l, std::vector<double> &function) const = 0; virtual void grid(std::vector<double> &val) const { val.resize(mesh_size()); for (unsigned ii = 0; ii < val.size(); ii++) val[ii] = ii * mesh_spacing(); } virtual void grid_weights(std::vector<double> &val) const { val.resize(mesh_size()); for (unsigned ii = 1; ii < val.size() - 1; ii++) val[ii] = mesh_spacing(); val[0] = 0.5 * mesh_spacing(); val[val.size() - 1] = 0.5 * mesh_spacing(); } // Functions for things that might not be provided virtual int nquad() const { return 0; } virtual double rquad() const { return 0.0; } virtual bool has_nlcc() const { return false; } virtual void nlcc_density(std::vector<double> &density) const { density.clear(); } virtual void beta(int index, int &l, std::vector<double> &proj) const { l = 0; proj.clear(); } virtual void dnm_zero(int nbeta, std::vector<std::vector<double>> &dnm) const { dnm.clear(); } virtual bool has_rinner() const { return false; } virtual void rinner(std::vector<double> &val) const { val.clear(); } virtual void qnm(int index, int &l1, int &l2, int &n, int &m, std::vector<double> &val) const { val.clear(); } virtual void qfcoeff(int index, int ltot, std::vector<double> &val) const { val.clear(); } virtual bool has_density() const { return false; } virtual void density(std::vector<double> &val) const { val.clear(); } virtual int nwavefunctions() const { return 0; } virtual void wavefunction(int index, int &n, int &l, double &occ, std::vector<double> &val) const { val.clear(); } virtual pseudopotential::exchange exchange() const { return pseudopotential::exchange::UNKNOWN; } virtual pseudopotential::correlation correlation() const { return pseudopotential::correlation::UNKNOWN; } virtual bool has_total_angular_momentum() const { return false; } virtual int projector_2j(int l, int ic) const { return 0; } // returns j multiplied by 2 virtual int wavefunction_2j(int ii) const { return 0; } // returns j multiplied by 2 protected: std::string filename_; template <typename Type> static Type value(const rapidxml::xml_base<> *node) { assert(node); std::istringstream stst(node->value()); Type value; stst >> value; return value; } pseudopotential::type type_; int lmax_; }; } // namespace pseudopotential #endif
0
ALLM/M3/octopus/src
ALLM/M3/octopus/src/species/detect_format.hpp
#ifndef PSEUDO_DETECT_FORMAT_HPP #define PSEUDO_DETECT_FORMAT_HPP /* Copyright (C) 2018 Xavier Andrade This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "base.hpp" #include <fstream> #include <iostream> #include <rapidxml.hpp> #include <string> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include <vector> namespace pseudopotential { static pseudopotential::format detect_format(const std::string &filename) { // check that the file is not a directory struct stat file_stat; if (stat(filename.c_str(), &file_stat) == -1) return pseudopotential::format::FILE_NOT_FOUND; if (S_ISDIR(file_stat.st_mode)) return pseudopotential::format::FILE_NOT_FOUND; // now open the file std::ifstream file(filename.c_str()); if (!file) return pseudopotential::format::FILE_NOT_FOUND; // First, try to read the file extension from the filename. This will detect non-xml files std::string extension = filename.substr(filename.find_last_of(".") + 1); std::transform(extension.begin(), extension.end(), extension.begin(), ::tolower); if (extension == "psp8" || extension == "drh") return pseudopotential::format::PSP8; if (extension == "psf") return pseudopotential::format::PSF; if (extension == "cpi") return pseudopotential::format::CPI; if (extension == "fhi") return pseudopotential::format::FHI; if (extension == "hgh") return pseudopotential::format::HGH; // If the file extension is not recognized, try to parse parse it as XML std::vector<char> buffer((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>()); buffer.push_back('\0'); rapidxml::xml_document<> doc; try { doc.parse<0>(&buffer[0]); // Return the specific format if the file is recognized if (doc.first_node("fpmd:species")) return pseudopotential::format::QSO; if (doc.first_node("qbox:species")) return pseudopotential::format::QSO; if (doc.first_node("PP_INFO")) return pseudopotential::format::UPF1; if (doc.first_node("UPF")) return pseudopotential::format::UPF2; if (doc.first_node("psml")) return pseudopotential::format::PSML; } catch (rapidxml::parse_error xml_error) { // Currently Octopus is passing a folder name to the ps_init() routine, which calls this function. // Here, we loop over all files in that folder, and try to detect their type. // As these folders also contain files, such as Makefile, etc. the catch condition will always be // met, and Octopus would print the confusing error messages. Therefore, the error messages are // disabled, until the whole mechanism is better understood. // std::cerr << "Error parsing pseudopotential file, " << filename.c_str() << ", as XML." << std::endl; // std::cerr << "rapidxml error:" << xml_error.what() << std::endl; } return pseudopotential::format::UNKNOWN; } } // namespace pseudopotential #endif
0
ALLM/M3/octopus/src
ALLM/M3/octopus/src/species/element.hpp
#ifndef PSEUDO_ELEMENT_HPP #define PSEUDO_ELEMENT_HPP /* Copyright (C) 2018 Xavier Andrade This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include <cassert> #include <cctype> #include <cstdlib> #include <fstream> #include <iostream> #include <map> #include <string> #include "share_directory.hpp" namespace pseudopotential { class element { private: struct properties; typedef std::map<std::string, properties> map_type; public: element(const std::string &symbol = "none") : symbol_(trim(symbol)) { symbol_[0] = std::toupper(symbol_[0]); for (unsigned ii = 1; ii < symbol_.size(); ii++) symbol_[ii] = std::tolower(symbol_[ii]); map(); // make sure the map is initialized } element(int atomic_number) { // special case: avoid ambiguity between isotopes if (atomic_number == 1) { symbol_ = 'H'; return; } for (map_type::iterator it = map().begin(); it != map().end(); ++it) { if (it->second.z_ == atomic_number) { symbol_ = trim(it->first); break; } } } bool valid() const { return map().find(symbol_) != map().end(); } double charge() const { return -1.0 * atomic_number(); } const std::string &symbol() const { return symbol_; } int atomic_number() const { return map().at(symbol_).z_; } double mass() const { return map().at(symbol_).mass_; } double vdw_radius() const { return map().at(symbol_).vdw_radius_; } private: struct properties { int z_; double mass_; double vdw_radius_; }; static map_type &map() { static map_type map; if (map.empty()) { std::string filename = pseudopotential::share_directory::get() + "/pseudopotentials/elements.dat"; std::ifstream file(filename.c_str()); if (!file) { std::cerr << "Internal error: cannot open file '" << filename << "'." << std::endl; exit(EXIT_FAILURE); } while (true) { std::string symbol; file >> symbol; if (file.eof()) break; if (symbol[0] == '#') { getline(file, symbol); continue; } properties prop; file >> prop.z_ >> prop.mass_ >> prop.vdw_radius_; if (file.eof()) break; map[symbol] = prop; } } return map; } static std::string &ltrim(std::string &str, const std::string &chars = "\t\n\v\f\r ") { str.erase(0, str.find_first_not_of(chars)); return str; } static std::string &rtrim(std::string &str, const std::string &chars = "\t\n\v\f\r ") { str.erase(str.find_last_not_of(chars) + 1); return str; } public: static std::string trim(std::string str, const std::string &chars = "\t\n\v\f\r ") { return ltrim(rtrim(str, chars), chars); } private: std::string symbol_; }; } // namespace pseudopotential #endif // Local Variables: // mode: c++ // coding: utf-8 // End:
0
ALLM/M3/octopus/src
ALLM/M3/octopus/src/species/element_low.cc
#include "element.hpp" #include "string_f.h" /* fortran <-> c string compatibility issues */ #include "fortran_types.h" extern "C" void FC_FUNC_(element_init, ELEMENT_INIT)(pseudopotential::element **el, STR_F_TYPE const symbol_f STR_ARG1) { char *symbol_c; TO_C_STR1(symbol_f, symbol_c); *el = new pseudopotential::element(symbol_c); free(symbol_c); } extern "C" void FC_FUNC_(element_end, ELEMENT_END)(pseudopotential::element **el) { delete *el; } extern "C" double FC_FUNC_(element_mass, ELEMENT_MASS)(pseudopotential::element **el) { return (*el)->mass(); } extern "C" double FC_FUNC_(element_vdw_radius, ELEMENT_VDW_RADIUS)(pseudopotential::element **el) { return (*el)->vdw_radius(); } extern "C" fint FC_FUNC_(element_atomic_number, ELEMENT_ATOMIC_NUMBER)(pseudopotential::element **el) { return (*el)->atomic_number(); } extern "C" fint FC_FUNC_(element_valid_low, ELEMENT_VALID_LOW)(pseudopotential::element **el) { return fint((*el)->valid()); }
0
ALLM/M3/octopus/src
ALLM/M3/octopus/src/species/pseudo_low.cc
/* Copyright (C) 2018 Xavier Andrade This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include <algorithm> #include <sys/stat.h> #include "string_f.h" /* fortran <-> c string compatibility issues */ #include "fortran_types.h" #include "base.hpp" #include "detect_format.hpp" #include "psml.hpp" #include "psp8.hpp" #include "qso.hpp" #include "upf1.hpp" #include "upf2.hpp" extern "C" fint FC_FUNC_(pseudo_detect_format, PSEUDO_DETECT_FORMAT)(STR_F_TYPE const filename_f STR_ARG1) { char *filename_c; TO_C_STR1(filename_f, filename_c); pseudopotential::format ft = pseudopotential::detect_format(filename_c); free(filename_c); return fint(ft); } extern "C" void FC_FUNC_(pseudo_init, PSEUDO_INIT)(pseudopotential::base **pseudo, STR_F_TYPE const filename_f, fint *format, fint *ierr STR_ARG1) { char *filename_c; TO_C_STR1(filename_f, filename_c); std::string filename(filename_c); free(filename_c); *ierr = 0; struct stat statbuf; bool found_file = !stat(filename.c_str(), &statbuf); if (!found_file) { *ierr = fint(pseudopotential::status::FILE_NOT_FOUND); return; } std::string extension = filename.substr(filename.find_last_of(".") + 1); std::transform(extension.begin(), extension.end(), extension.begin(), ::tolower); *pseudo = NULL; try { switch (pseudopotential::format(*format)) { case pseudopotential::format::QSO: *pseudo = new pseudopotential::qso(filename); break; case pseudopotential::format::UPF1: *pseudo = new pseudopotential::upf1(filename); break; case pseudopotential::format::UPF2: *pseudo = new pseudopotential::upf2(filename); break; case pseudopotential::format::PSML: *pseudo = new pseudopotential::psml(filename); break; case pseudopotential::format::PSP8: *pseudo = new pseudopotential::psp8(filename); break; default: *ierr = fint(pseudopotential::status::UNKNOWN_FORMAT); return; } } catch (pseudopotential::status stat) { *ierr = fint(stat); return; } assert(*pseudo); } extern "C" void FC_FUNC_(pseudo_end, PSEUDO_END)(pseudopotential::base **pseudo) { delete *pseudo; } extern "C" fint FC_FUNC_(pseudo_type, PSEUDO_TYPE)(const pseudopotential::base **pseudo) { return fint((*pseudo)->type()); } extern "C" fint FC_FUNC_(pseudo_format, PSEUDO_FORMAT)(pseudopotential::base **pseudo) { return fint((*pseudo)->format()); } extern "C" double FC_FUNC_(pseudo_valence_charge, PSEUDO_VALENCE_CHARGE)(const pseudopotential::base **pseudo) { return (*pseudo)->valence_charge(); } extern "C" double FC_FUNC_(pseudo_mesh_spacing, PSEUDO_MESH_SPACING)(const pseudopotential::base **pseudo) { return (*pseudo)->mesh_spacing(); } extern "C" fint FC_FUNC_(pseudo_mesh_size, PSEUDO_MESH_SIZE)(const pseudopotential::base **pseudo) { return (*pseudo)->mesh_size(); } extern "C" double FC_FUNC_(pseudo_mass, PSEUDO_MASS)(const pseudopotential::base **pseudo) { return (*pseudo)->mass(); } extern "C" fint FC_FUNC_(pseudo_lmax, PSEUDO_LMAX)(const pseudopotential::base **pseudo) { return (*pseudo)->lmax(); } extern "C" fint FC_FUNC_(pseudo_llocal, PSEUDO_LLOCAL)(const pseudopotential::base **pseudo) { return (*pseudo)->llocal(); } extern "C" fint FC_FUNC_(pseudo_nchannels, PSEUDO_NCHANNELS)(const pseudopotential::base **pseudo) { return (*pseudo)->nchannels(); } extern "C" fint FC_FUNC_(pseudo_nprojectors, PSEUDO_NPROJECTORS)(const pseudopotential::base **pseudo) { return (*pseudo)->nprojectors(); } extern "C" fint FC_FUNC_(pseudo_nprojectors_per_l, PSEUDO_NPROJECTORS_PER_L)(const pseudopotential::base **pseudo, fint *l) { return (*pseudo)->nprojectors_per_l(*l); } extern "C" void FC_FUNC_(pseudo_grid, PSEUDO_GRID)(const pseudopotential::base **pseudo, double *grid) { std::vector<double> val; (*pseudo)->grid(val); for (unsigned i = 0; i < val.size(); i++) grid[i] = val[i]; } extern "C" void FC_FUNC_(pseudo_grid_weights, PSEUDO_GRID_WEIGHT)( const pseudopotential::base **pseudo, double *weight) { std::vector<double> val; (*pseudo)->grid_weights(val); for (unsigned i = 0; i < val.size(); i++) weight[i] = val[i]; } extern "C" void FC_FUNC_(pseudo_local_potential, PSEUDO_LOCAL_POTENTIAL)( const pseudopotential::base **pseudo, double *local_potential) { std::vector<double> val; (*pseudo)->local_potential(val); for (unsigned i = 0; i < val.size(); i++) local_potential[i] = val[i]; } extern "C" void FC_FUNC_(pseudo_projector, PSEUDO_PROJECTOR)(const pseudopotential::base **pseudo, fint *l, fint *ic, double *projector) { std::vector<double> val; (*pseudo)->projector(*l, *ic - 1, val); for (unsigned i = 0; i < val.size(); i++) projector[i] = val[i]; } extern "C" double FC_FUNC_(pseudo_dij, PSEUDO_DIJ)(const pseudopotential::base **pseudo, fint *l, fint *ic, fint *jc) { return (*pseudo)->d_ij(*l, *ic - 1, *jc - 1); } extern "C" void FC_FUNC_(pseudo_radial_potential, PSEUDO_RADIAL_POTENTIAL)( const pseudopotential::base **pseudo, fint *l, double *radial_potential) { std::vector<double> val; (*pseudo)->radial_potential(*l, val); for (unsigned i = 0; i < val.size(); i++) radial_potential[i] = val[i]; } extern "C" fint FC_FUNC_(pseudo_has_radial_function_low, PSEUDO_HAS_RADIAL_FUNCTION_LOW)(const pseudopotential::base **pseudo, fint *l) { return fint((*pseudo)->has_radial_function(*l)); } extern "C" void FC_FUNC_(pseudo_radial_function, PSEUDO_RADIAL_FUNCTION)( const pseudopotential::base **pseudo, fint *l, double *radial_function) { std::vector<double> val; (*pseudo)->radial_function(*l, val); for (unsigned i = 0; i < val.size(); i++) radial_function[i] = val[i]; } extern "C" fint FC_FUNC_(pseudo_has_nlcc_low, PSEUDO_HAS_NLCC_LOW)(const pseudopotential::base **pseudo) { return fint((*pseudo)->has_nlcc()); } extern "C" void FC_FUNC_(pseudo_nlcc_density, PSEUDO_NLCC_DENSITY)( const pseudopotential::base **pseudo, double *nlcc_density) { std::vector<double> val; (*pseudo)->nlcc_density(val); for (unsigned i = 0; i < val.size(); i++) nlcc_density[i] = val[i]; } extern "C" fint FC_FUNC_(pseudo_has_density_low, PSEUDO_HAS_DENSITY_LOW)(const pseudopotential::base **pseudo) { return fint((*pseudo)->has_density()); } extern "C" void FC_FUNC_(pseudo_density, PSEUDO_DENSITY)(const pseudopotential::base **pseudo, double *density) { std::vector<double> val; (*pseudo)->density(val); for (unsigned i = 0; i < val.size(); i++) density[i] = val[i]; } extern "C" fint FC_FUNC_(pseudo_nwavefunctions, PSEUDO_NWAVEFUNCTIONS)(const pseudopotential::base **pseudo) { return (*pseudo)->nwavefunctions(); } extern "C" void FC_FUNC_(pseudo_wavefunction, PSEUDO_WAVEFUNCTION)( const pseudopotential::base **pseudo, const fint *index, fint *n, fint *l, double *occ, double *wavefunction) { std::vector<double> val; (*pseudo)->wavefunction(*index - 1, *n, *l, *occ, val); for (unsigned i = 0; i < val.size(); i++) wavefunction[i] = val[i]; } extern "C" fint FC_FUNC_(pseudo_exchange, PSEUDO_EXCHANGE)(const pseudopotential::base **pseudo) { return fint((*pseudo)->exchange()); } extern "C" fint FC_FUNC_(pseudo_correlation, PSEUDO_CORRELATION)(const pseudopotential::base **pseudo) { return fint((*pseudo)->correlation()); } extern "C" fint FC_FUNC_(pseudo_has_total_angular_momentum_low, PSEUDO_HAS_TOTAL_ANGULAR_MOMENTUM_LOW)( const pseudopotential::base **pseudo) { return fint((*pseudo)->has_total_angular_momentum()); } extern "C" fint FC_FUNC_(pseudo_projector_2j, PSEUDO_PROJECTOR_2J)( const pseudopotential::base **pseudo, fint *l, fint *ic) { return (*pseudo)->projector_2j(*l, *ic - 1); } extern "C" fint FC_FUNC_(pseudo_wavefunction_2j, PSEUDO_WAVEFUNCTION_2J)( const pseudopotential::base **pseudo, fint *ii) { return (*pseudo)->wavefunction_2j(*ii); }
0
ALLM/M3/octopus/src
ALLM/M3/octopus/src/species/pseudo_set_low.cc
/* Copyright (C) 2018 Xavier Andrade This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include <algorithm> #include <cassert> #include <sys/stat.h> #include "string_f.h" /* fortran <-> c string compatibility issues */ #include "fortran_types.h" #include "set.hpp" #include "element.hpp" extern "C" void FC_FUNC_(pseudo_set_init_low, PSEUDO_SET_INIT_LOW)(pseudopotential::set **pseudo_set, STR_F_TYPE const filename_f, fint *ierr STR_ARG1) { *ierr = 0; char *filename_c; TO_C_STR1(filename_f, filename_c); *pseudo_set = new pseudopotential::set(filename_c); assert(*pseudo_set); free(filename_c); } extern "C" void FC_FUNC_(pseudo_set_nullify, PSEUDO_SET_NULLIFY)(pseudopotential::set **pseudo_set) { *pseudo_set = NULL; } extern "C" void FC_FUNC_(pseudo_set_end, PSEUDO_SET_END)(pseudopotential::set **pseudo_set) { if (*pseudo_set) { delete *pseudo_set; *pseudo_set = NULL; } } extern "C" fint FC_FUNC_(pseudo_set_has_low, PSEUDO_SET_HAS_LOW)( const pseudopotential::set **pseudo_set, pseudopotential::element **el) { return (*pseudo_set)->has(**el); } extern "C" void FC_FUNC_(pseudo_set_file_path_low, PSEUDO_SET_FILE_PATH_LOW)( const pseudopotential::set **pseudo_set, pseudopotential::element **el, STR_F_TYPE const path_f STR_ARG1) { std::string path = (*pseudo_set)->file_path(**el); TO_F_STR1(path.c_str(), path_f); } extern "C" fint FC_FUNC_(pseudo_set_lmax, PSEUDO_SET_LMAX)( const pseudopotential::set **pseudo_set, pseudopotential::element **el) { return (*pseudo_set)->lmax(**el); } extern "C" fint FC_FUNC_(pseudo_set_llocal, PSEUDO_SET_LLOCAL)( const pseudopotential::set **pseudo_set, pseudopotential::element **el) { return (*pseudo_set)->llocal(**el); }
0
ALLM/M3/octopus/src
ALLM/M3/octopus/src/species/psml.hpp
#ifndef PSEUDO_PSML_HPP #define PSEUDO_PSML_HPP /* Copyright (C) 2018 Xavier Andrade This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include <cassert> #include <cmath> #include <fstream> #include <iostream> #include <sstream> #include <vector> #include "anygrid.hpp" #include "base.hpp" #include "element.hpp" #include <rapidxml.hpp> namespace pseudopotential { class psml : public pseudopotential::anygrid { public: psml(const std::string &filename, bool uniform_grid = false) : pseudopotential::anygrid(uniform_grid), file_(filename.c_str()), buffer_((std::istreambuf_iterator<char>(file_)), std::istreambuf_iterator<char>()) { filename_ = filename; buffer_.push_back('\0'); doc_.parse<0>(&buffer_[0]); root_node_ = doc_.first_node("psml"); spec_node_ = root_node_->first_node("pseudo-atom-spec"); // some files do not have "pseudo-atom-spec" but "header" if (!spec_node_) spec_node_ = root_node_->first_node("header"); assert(spec_node_); // now check the type bool has_local_potential = root_node_->first_node("local-potential"); bool has_nl_projectors = root_node_->first_node("nonlocal-projectors"); bool has_semilocal_potentials = root_node_->first_node("semilocal-potentials"); bool has_pseudo_wavefunctions = root_node_->first_node("pseudo-wave-functions"); if (has_nl_projectors && has_local_potential) { type_ = pseudopotential::type::KLEINMAN_BYLANDER; } else if (has_semilocal_potentials && has_pseudo_wavefunctions) { type_ = pseudopotential::type::SEMILOCAL; } else { throw status::UNSUPPORTED_TYPE; } { // read lmax std::string tag1, tag2; if (type_ == pseudopotential::type::KLEINMAN_BYLANDER) { tag1 = "nonlocal-projectors"; tag2 = "proj"; } else if (type_ == pseudopotential::type::SEMILOCAL) { tag1 = "semilocal-potentials"; tag2 = "slps"; } else { assert(false); } lmax_ = -1; rapidxml::xml_node<> *node = root_node_->first_node(tag1.c_str()); assert(node); node = node->first_node(tag2.c_str()); while (node) { int read_l = letter_to_l(node->first_attribute("l")->value()); lmax_ = std::max(lmax_, read_l); node = node->next_sibling(tag2.c_str()); } assert(lmax_ >= 0); assert(lmax_ < 9); } // read grid { rapidxml::xml_node<> *node = root_node_->first_node("grid"); assert(node); int size = value<int>(node->first_attribute("npts")); grid_.resize(size); std::istringstream stst(node->first_node("grid-data")->value()); for (int ii = 0; ii < size; ii++) { stst >> grid_[ii]; if (ii > 0) assert(grid_[ii] > grid_[ii - 1]); } assert(fabs(grid_[0]) <= 1e-10); mesh_size_ = 0; for (double rr = 0.0; rr <= grid_[grid_.size() - 1]; rr += mesh_spacing()) mesh_size_++; grid_weights_.resize(grid_.size()); // the integration weights are not available, we approximate them grid_weights_[0] = 0.5 * (grid_[1] - grid_[0]); for (unsigned ii = 1; ii < grid_.size() - 1; ii++) grid_weights_[ii] = grid_[ii + 1] - grid_[ii - 1]; grid_weights_[grid_.size() - 1] = 0.5 * (grid_[grid_.size() - 1] - grid_[grid_.size() - 2]); } } pseudopotential::format format() const { return pseudopotential::format::PSML; } int size() const { return buffer_.size(); }; std::string description() const { return ""; } std::string symbol() const { return element::trim(spec_node_->first_attribute("atomic-label")->value()); } int atomic_number() const { return value<int>(spec_node_->first_attribute("atomic-number")); } double mass() const { element el(symbol()); return el.mass(); } double valence_charge() const { return value<double>(spec_node_->first_node("valence-configuration") ->first_attribute("total-valence-charge")); } int llocal() const { return -1; } pseudopotential::exchange exchange() const { // PSML uses libxc ids, so we just need to read the value rapidxml::xml_node<> *node = spec_node_->first_node("exchange-correlation") ->first_node("libxc-info") ->first_node("functional"); while (node) { if (value<std::string>(node->first_attribute("type")) == "exchange") { return pseudopotential::exchange( value<int>(node->first_attribute("id"))); } node = node->next_sibling("functional"); } return pseudopotential::exchange::UNKNOWN; } pseudopotential::correlation correlation() const { // PSML uses libxc ids, so we just need to read the value rapidxml::xml_node<> *node = spec_node_->first_node("exchange-correlation") ->first_node("libxc-info") ->first_node("functional"); while (node) { if (value<std::string>(node->first_attribute("type")) == "correlation") { return pseudopotential::correlation( value<int>(node->first_attribute("id"))); } node = node->next_sibling("functional"); } return pseudopotential::correlation::UNKNOWN; } int nchannels() const { if (type_ == pseudopotential::type::SEMILOCAL) return 1; int nc = 0; rapidxml::xml_node<> *node = root_node_->first_node("nonlocal-projectors"); assert(node); node = node->first_node("proj"); while (node) { int read_ic = value<int>(node->first_attribute("seq")) - 1; nc = std::max(nc, read_ic + 1); node = node->next_sibling("proj"); } return nc; } void local_potential(std::vector<double> &val) const { read_function(root_node_->first_node("local-potential"), val, true); } int nprojectors() const { rapidxml::xml_node<> *node = root_node_->first_node("nonlocal-projectors")->first_node("proj"); int count = 0; while (node) { count++; node = node->next_sibling("proj"); } return count; } int nprojectors_per_l(int l) const { if (type_ == pseudopotential::type::SEMILOCAL) return 1; rapidxml::xml_node<> *node = root_node_->first_node("nonlocal-projectors")->first_node("proj"); int count = 0; while (node) { int read_l = letter_to_l(node->first_attribute("l")->value()); if (read_l == l) count++; node = node->next_sibling("proj"); } return count; } void projector(int l, int ic, std::vector<double> &val) const { rapidxml::xml_node<> *node = root_node_->first_node("nonlocal-projectors")->first_node("proj"); while (node) { int read_l = letter_to_l(node->first_attribute("l")->value()); int read_ic = value<int>(node->first_attribute("seq")) - 1; if (l == read_l && ic == read_ic) break; node = node->next_sibling("proj"); } read_function(node, val); } double d_ij(int l, int ic, int jc) const { if (ic != jc) return 0.0; rapidxml::xml_node<> *node = root_node_->first_node("nonlocal-projectors")->first_node("proj"); while (node) { int read_l = letter_to_l(node->first_attribute("l")->value()); int read_ic = value<int>(node->first_attribute("seq")) - 1; if (l == read_l && ic == read_ic) break; node = node->next_sibling("proj"); } assert(node); return value<double>(node->first_attribute("ekb")); } bool has_radial_function(int l) const { return false; } void radial_function(int l, std::vector<double> &val) const { rapidxml::xml_node<> *node = root_node_->first_node("pseudo-wave-functions")->first_node("pswf"); while (node) { int read_l = letter_to_l(node->first_attribute("l")->value()); if (l == read_l) break; node = node->next_sibling("pswf"); } read_function(node, val); } void radial_potential(int l, std::vector<double> &val) const { rapidxml::xml_node<> *node = root_node_->first_node("semilocal-potentials")->first_node("slps"); while (node) { int read_l = letter_to_l(node->first_attribute("l")->value()); if (l == read_l) break; node = node->next_sibling("slps"); } read_function(node, val); } bool has_nlcc() const { rapidxml::xml_node<> *node = root_node_->first_node("pseudocore-charge"); return node; } void nlcc_density(std::vector<double> &val) const { read_function(root_node_->first_node("pseudocore-charge"), val); for (unsigned ii = 0; ii < val.size(); ii++) val[ii] /= 4.0 * M_PI; } bool has_density() { return root_node_->first_node("valence-charge"); } void density(std::vector<double> &val) const { read_function(root_node_->first_node("valence-charge"), val); for (unsigned ii = 0; ii < val.size(); ii++) val[ii] /= 4.0 * M_PI; } bool has_total_angular_momentum() const { return spec_node_->first_attribute("relativity")->value() == std::string("dirac"); } int projector_2j(int l, int ic) const { rapidxml::xml_node<> *node = root_node_->first_node("nonlocal-projectors")->first_node("proj"); while (node) { int read_l = letter_to_l(node->first_attribute("l")->value()); int read_ic = value<int>(node->first_attribute("seq")) - 1; if (l == read_l && ic == read_ic) { double read_j = value<double>(node->first_attribute("j")); std::cout << l << " " << ic << " " << read_j << std::endl; return lrint(2.0 * read_j); } node = node->next_sibling("proj"); } assert(false); return 0; } private: void read_function(rapidxml::xml_node<> *base_node, std::vector<double> &val, bool potential_padding = false) const { assert(base_node); rapidxml::xml_node<> *node = base_node->first_node("radfunc")->first_node("data"); assert(node); int size = grid_.size(); if (node->first_attribute("npts")) size = value<int>(node->first_attribute("npts")); val.resize(grid_.size()); std::istringstream stst(node->value()); for (int ii = 0; ii < size; ii++) stst >> val[ii]; if (potential_padding) { for (unsigned ii = size; ii < grid_.size(); ii++) val[ii] = -valence_charge() / grid_[ii]; } else { for (unsigned ii = size; ii < grid_.size(); ii++) val[ii] = 0.0; } interpolate(val); } // for some stupid reason psml uses letters instead of numbers for angular // momentum static int letter_to_l(const std::string &letter) { if (letter == "s") return 0; if (letter == "p") return 1; if (letter == "d") return 2; if (letter == "f") return 3; if (letter == "g") return 4; if (letter == "h") return 5; return -1; } std::ifstream file_; std::vector<char> buffer_; rapidxml::xml_document<> doc_; rapidxml::xml_node<> *root_node_; rapidxml::xml_node<> *spec_node_; }; } // namespace pseudopotential #endif
0
ALLM/M3/octopus/src
ALLM/M3/octopus/src/species/psp8.hpp
#ifndef PSEUDO_PSP8_HPP #define PSEUDO_PSP8_HPP /* Copyright (C) 2018 Xavier Andrade This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include <cassert> #include <cmath> #include <fstream> #include <iostream> #include <sstream> #include <vector> #include "base.hpp" #include "element.hpp" namespace pseudopotential { class psp8 : public pseudopotential::base { public: psp8(const std::string &filename) { filename_ = filename; std::ifstream original_file(filename.c_str()); std::string buffer((std::istreambuf_iterator<char>(original_file)), std::istreambuf_iterator<char>()); std::replace(buffer.begin(), buffer.end(), 'D', 'E'); std::replace(buffer.begin(), buffer.end(), 'd', 'e'); std::istringstream file(buffer); type_ = pseudopotential::type::KLEINMAN_BYLANDER; // file size file.seekg(0, std::ios::beg); std::streampos file_size_ = file.tellg(); file.seekg(0, std::ios::end); file_size_ = file.tellg() - file_size_; // parse the header file.seekg(0, std::ios::beg); std::string line; // line 1 getline(file, description_); // line 2 double val; file >> val; atomic_number_ = round(val); file >> valence_charge_; getline(file, line); // line 3 int pspcod = -1; file >> pspcod >> ixc_ >> lmax_ >> llocal_ >> mesh_size_; if (pspcod != 8) throw status::UNKNOWN_FORMAT; getline(file, line); // line 4 file >> val; file >> val; nlcc_ = (val > 0.0); getline(file, line); // line 5 nprojectors_ = 0; nchannels_ = 0; for (int l = 0; l <= lmax_; l++) { int np; file >> np; nprojl_.push_back(np); nprojectors_ += np; nchannels_ = std::max(nchannels_, np); } getline(file, line); // line 6 int extension_switch; file >> extension_switch; getline(file, line); has_density_ = extension_switch == 1; has_soc_ = extension_switch == 2; // there is an extra line for spin orbit stuff if (has_soc_) getline(file, line); if (extension_switch > 2) throw status::FORMAT_NOT_SUPPORTED; // the projectors and local potential projectors_.resize(lmax_ + 1); ekb_.resize(lmax_ + 1); for (int l = 0; l <= lmax_; l++) { projectors_[l].resize(nprojl_[l]); ekb_[l].resize(nprojl_[l]); if (l == llocal_) { read_local_potential(file); continue; } if (nprojl_[l] == 0) continue; int read_l; file >> read_l; assert(read_l == l); for (int iproj = 0; iproj < nprojl_[l]; iproj++) { projectors_[l][iproj].resize(mesh_size_); file >> ekb_[l][iproj]; } getline(file, line); for (int ip = 0; ip < mesh_size_; ip++) { int read_ip; double grid_point; file >> read_ip >> grid_point; assert(read_ip == ip + 1); for (int iproj = 0; iproj < nprojl_[l]; iproj++) file >> projectors_[l][iproj][ip]; getline(file, line); } } // the local potential if it was not read before if (llocal_ > lmax_) read_local_potential(file); // NLCC if (nlcc_) { nlcc_density_.resize(mesh_size_); for (int ip = 0; ip < mesh_size_; ip++) { int read_ip; double grid_point; file >> read_ip >> grid_point >> nlcc_density_[ip]; assert(read_ip == ip + 1); getline(file, line); } } if (extension_switch == 1) { density_.resize(mesh_size_); for (int ip = 0; ip < mesh_size_; ip++) { int read_ip; double grid_point; file >> read_ip >> grid_point >> density_[ip]; assert(read_ip == ip + 1); getline(file, line); } } } pseudopotential::format format() const { return pseudopotential::format::PSP8; } int size() const { return file_size_; }; std::string description() const { return description_; } std::string symbol() const { pseudopotential::element el(atomic_number_); return el.symbol(); } int atomic_number() const { return atomic_number_; } double mass() const { pseudopotential::element el(atomic_number_); return el.mass(); } double valence_charge() const { return valence_charge_; } pseudopotential::exchange exchange() const { if (ixc_ > 0) { if (ixc_ == 1) return pseudopotential::exchange::NONE; if (ixc_ >= 2 && ixc_ <= 9) return pseudopotential::exchange::LDA; if (ixc_ == 11 || ixc_ == 12) return pseudopotential::exchange::PBE; } else { return pseudopotential::exchange((-ixc_ + ixc_ % 1000) / 1000); } return pseudopotential::exchange::UNKNOWN; } pseudopotential::correlation correlation() const { if (ixc_ > 0) { if (ixc_ == 1) return pseudopotential::correlation::LDA_XC_TETER93; if (ixc_ == 2) return pseudopotential::correlation::LDA_PZ; if (ixc_ == 7) return pseudopotential::correlation::LDA_PW; if (ixc_ == 7 || ixc_ == 8) return pseudopotential::correlation::NONE; if (ixc_ == 11) return pseudopotential::correlation::PBE; if (ixc_ == 12) return pseudopotential::correlation::NONE; } else { return pseudopotential::correlation(-ixc_ % 1000); } return pseudopotential::correlation::UNKNOWN; } int llocal() const { if (llocal_ > lmax_) return -1; return llocal_; } int nchannels() const { return nchannels_; } double mesh_spacing() const { return mesh_spacing_; } int mesh_size() const { return mesh_size_; } void local_potential(std::vector<double> &potential) const { potential.resize(mesh_size_); assert(mesh_size_ == local_potential_.size()); for (int ip = 0; ip < mesh_size_; ip++) potential[ip] = local_potential_[ip]; } int nprojectors() const { return nprojectors_; } int nprojectors_per_l(int l) const { return nprojl_[l]; } void projector(int l, int i, std::vector<double> &proj) const { proj.clear(); if (l > lmax_) return; if (i >= nprojl_[l]) return; proj.resize(mesh_size_); assert(mesh_size_ == projectors_[l][i].size()); for (int ip = 1; ip < mesh_size_; ip++) proj[ip] = projectors_[l][i][ip] / (mesh_spacing() * ip); extrapolate_first_point(proj); } double d_ij(int l, int i, int j) const { if (i != j) return 0.0; if (i >= nprojl_[l]) return 0.0; return ekb_[l][i]; } bool has_radial_function(int l) const { return false; } void radial_function(int l, std::vector<double> &function) const { function.clear(); } void radial_potential(int l, std::vector<double> &function) const { function.clear(); } bool has_nlcc() const { return nlcc_; } bool has_total_angular_momentum() const { return has_soc_; } void nlcc_density(std::vector<double> &density) const { density.resize(mesh_size_); assert(mesh_size_ == nlcc_density_.size()); for (int ip = 0; ip < mesh_size_; ip++) density[ip] = nlcc_density_[ip] / (4.0 * M_PI); } bool has_density() const { return has_density_; } void density(std::vector<double> &density) const { density.resize(mesh_size_); assert(mesh_size_ == density_.size()); for (int ip = 0; ip < mesh_size_; ip++) density[ip] = density_[ip] / (4.0 * M_PI); } private: void extrapolate_first_point(std::vector<double> &function_) const { assert(function_.size() >= 4); double x1 = mesh_spacing(); double x2 = 2 * mesh_spacing(); double x3 = 3 * mesh_spacing(); double f1 = function_[1]; double f2 = function_[2]; double f3 = function_[3]; // obtained from: // http://www.wolframalpha.com/input/?i=solve+%7Bb*x1%5E2+%2B+c*x1+%2B+d+%3D%3D+f1,++b*x2%5E2+%2B+c*x2+%2B+d+%3D%3D+f2,+b*x3%5E2+%2B+c*x3+%2B+d+%3D%3D+f3+%7D++for+b,+c,+d function_[0] = f1 * x2 * x3 * (x2 - x3) + f2 * x1 * x3 * (x3 - x1) + f3 * x1 * x2 * (x1 - x2); function_[0] /= (x1 - x2) * (x1 - x3) * (x2 - x3); } void read_local_potential(std::istream &file) { int read_llocal; std::string line; file >> read_llocal; assert(llocal_ == read_llocal); getline(file, line); local_potential_.resize(mesh_size_); for (int ip = 0; ip < mesh_size_; ip++) { int read_ip; double grid_point; file >> read_ip >> grid_point >> local_potential_[ip]; assert(read_ip == ip + 1); getline(file, line); if (ip == 1) { mesh_spacing_ = grid_point; } } } size_t file_size_; std::string description_; int atomic_number_; double valence_charge_; int ixc_; int llocal_; int mesh_size_; int nchannels_; double mesh_spacing_; std::vector<int> nprojl_; int nprojectors_; std::vector<std::vector<std::vector<double>>> projectors_; std::vector<std::vector<double>> ekb_; std::vector<double> local_potential_; bool nlcc_; std::vector<double> nlcc_density_; bool has_density_; std::vector<double> density_; bool has_soc_; }; } // namespace pseudopotential #endif
0
ALLM/M3/octopus/src
ALLM/M3/octopus/src/species/qso.hpp
#ifndef PSEUDO_QSO_HPP #define PSEUDO_QSO_HPP /* Copyright (C) 2018 Xavier Andrade This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include <cassert> #include <fstream> #include <iostream> #include <sstream> #include <vector> #include "base.hpp" #include "element.hpp" #include <rapidxml.hpp> namespace pseudopotential { class qso : public pseudopotential::base { public: qso(const std::string &filename) : file_(filename.c_str()), buffer_((std::istreambuf_iterator<char>(file_)), std::istreambuf_iterator<char>()) { filename_ = filename; buffer_.push_back('\0'); doc_.parse<0>(&buffer_[0]); root_node_ = doc_.first_node("fpmd:species"); // for the old version of the standard if (!root_node_) root_node_ = doc_.first_node("qbox:species"); if (!root_node_) throw status::FORMAT_NOT_SUPPORTED; pseudo_node_ = root_node_->first_node("ultrasoft_pseudopotential"); if (pseudo_node_) type_ = pseudopotential::type::ULTRASOFT; if (!pseudo_node_) { pseudo_node_ = root_node_->first_node("norm_conserving_semilocal_pseudopotential"); if (pseudo_node_) type_ = pseudopotential::type::KLEINMAN_BYLANDER; } if (!pseudo_node_) { pseudo_node_ = root_node_->first_node("norm_conserving_pseudopotential"); if (pseudo_node_) type_ = pseudopotential::type::SEMILOCAL; } assert(pseudo_node_); // read lmax lmax_ = -1; if (pseudo_node_->first_node("lmax")) { lmax_ = value<int>(pseudo_node_->first_node("lmax")); } else { for (int l = 0; l <= MAX_L; l++) { if (!has_projectors(l)) { lmax_ = l - 1; break; } } } assert(lmax_ >= 0); assert(lmax_ < MAX_L); } pseudopotential::format format() const { return pseudopotential::format::QSO; } int size() const { return buffer_.size(); }; std::string description() const { return root_node_->first_node("description")->value(); } std::string symbol() const { return element::trim(root_node_->first_node("symbol")->value()); } int atomic_number() const { return value<int>(root_node_->first_node("atomic_number")); } double mass() const { return value<double>(root_node_->first_node("mass")); } double valence_charge() const { return value<double>(pseudo_node_->first_node("valence_charge")); } int llocal() const { if (pseudo_node_->first_node("llocal")) { return value<int>(pseudo_node_->first_node("llocal")); } else { return -1; } } int nchannels() const { if (type_ == pseudopotential::type::ULTRASOFT) { int np = nbeta(); int nl = lmax() + 1; assert(np % nl == 0); return np / nl; } if (type_ == pseudopotential::type::KLEINMAN_BYLANDER) return 2; return 1; } int nquad() const { return value<int>(pseudo_node_->first_node("nquad")); } double rquad() const { return value<double>(pseudo_node_->first_node("rquad")); } double mesh_spacing() const { return value<double>(pseudo_node_->first_node("mesh_spacing")); } int mesh_size() const { rapidxml::xml_node<> *node = pseudo_node_->first_node("local_potential"); // kleinman bylander if (!node) node = pseudo_node_->first_node("vlocal"); // ultrasoft if (!node) node = pseudo_node_->first_node("projector"); // norm conserving assert(node); return value<int>(node->first_attribute("size")); } void local_potential(std::vector<double> &potential) const { rapidxml::xml_node<> *node = pseudo_node_->first_node("local_potential"); if (!node) { // for ultrasoft, this is called vlocal node = pseudo_node_->first_node("vlocal"); } assert(node); int size = value<int>(node->first_attribute("size")); potential.resize(size); std::istringstream stst(node->value()); for (int ii = 0; ii < size; ii++) { stst >> potential[ii]; } } int nprojectors() const { switch (type_) { case pseudopotential::type::ULTRASOFT: return nbeta(); case pseudopotential::type::KLEINMAN_BYLANDER: { int count = 0; rapidxml::xml_node<> *node = pseudo_node_->first_node("projector"); while (node) { count++; node = node->next_sibling("projector"); } return count; } case pseudopotential::type::SEMILOCAL: return 0; } return 0; } int nprojectors_per_l(int l) const { switch (type_) { case pseudopotential::type::ULTRASOFT: return nbeta() / ( lmax() + 1); case pseudopotential::type::KLEINMAN_BYLANDER: { int count = 0; rapidxml::xml_node<> *node = pseudo_node_->first_node("projector"); while (node) { int read_l = value<int>(node->first_attribute("l")); if (l == read_l) count++; node = node->next_sibling("projector"); } return count++; } case pseudopotential::type::SEMILOCAL: { int count = 0; rapidxml::xml_node<> *node = pseudo_node_->first_node("projector"); while (node) { int read_l = value<int>(node->first_attribute("l")); if (l == read_l) count++; node = node->next_sibling("projector"); } return count++; } } return 0; } void projector(int l, int i, std::vector<double> &proj) const { std::string tag = "projector"; rapidxml::xml_node<> *node = pseudo_node_->first_node(tag.c_str()); while (node) { int read_l = value<int>(node->first_attribute("l")); int read_i = value<int>(node->first_attribute("i")) - 1; if (l == read_l && i == read_i) break; node = node->next_sibling(tag.c_str()); } assert(node != NULL); int size = value<int>(node->first_attribute("size")); proj.resize(size); std::istringstream stst(node->value()); for (int ii = 0; ii < size; ii++) stst >> proj[ii]; } double d_ij(int l, int i, int j) const { rapidxml::xml_node<> *node = pseudo_node_->first_node("d_ij"); while (node) { int read_l = value<int>(node->first_attribute("l")); int read_i = value<int>(node->first_attribute("i")) - 1; int read_j = value<int>(node->first_attribute("j")) - 1; if (l == read_l && i == read_i && j == read_j) break; node = node->next_sibling("d_ij"); } assert(node != NULL); return value<double>(node); } bool has_radial_function(int l) const { rapidxml::xml_node<> *node = pseudo_node_->first_node("projector"); while (node) { int read_l = value<int>(node->first_attribute("l")); if (l == read_l) break; node = node->next_sibling("projector"); } return node->first_node("radial_function") != NULL; } void radial_function(int l, std::vector<double> &function) const { rapidxml::xml_node<> *node = pseudo_node_->first_node("projector"); while (node) { int read_l = value<int>(node->first_attribute("l")); if (l == read_l) break; node = node->next_sibling("projector"); } assert(node != NULL); assert(node->first_node("radial_function")); int size = value<int>(node->first_attribute("size")); function.resize(size); std::istringstream stst(node->first_node("radial_function")->value()); for (int ii = 0; ii < size; ii++) { stst >> function[ii]; } } void radial_potential(int l, std::vector<double> &function) const { rapidxml::xml_node<> *node = pseudo_node_->first_node("projector"); while (node) { int read_l = value<int>(node->first_attribute("l")); if (l == read_l) break; node = node->next_sibling("projector"); } assert(node != NULL); assert(node->first_node("radial_potential")); int size = value<int>(node->first_attribute("size")); function.resize(size); std::istringstream stst(node->first_node("radial_potential")->value()); for (int ii = 0; ii < size; ii++) { stst >> function[ii]; } } bool has_nlcc() const { return pseudo_node_->first_node("rho_nlcc"); } void nlcc_density(std::vector<double> &density) const { rapidxml::xml_node<> *node = pseudo_node_->first_node("rho_nlcc"); assert(node); int size = value<int>(node->first_attribute("size")); density.resize(size); std::istringstream stst(node->value()); for (int ii = 0; ii < size; ii++) { stst >> density[ii]; } } void beta(int index, int &l, std::vector<double> &proj) const { rapidxml::xml_node<> *node = pseudo_node_->first_node("beta"); for (int i = 0; i < index; i++) node = node->next_sibling("beta"); assert(node != NULL); l = value<int>(node->first_attribute("l")); int size = value<int>(node->first_attribute("size")); proj.resize(size); std::istringstream stst(node->value()); for (int ii = 0; ii < size; ii++) { stst >> proj[ii]; } } void dnm_zero(int nbeta, std::vector<std::vector<double>> &dnm) const { rapidxml::xml_node<> *node = pseudo_node_->first_node("dnm_zero"); std::istringstream stst(node->value()); dnm.resize(nbeta); for (int i = 0; i < nbeta; i++) { dnm[i].resize(nbeta); for (int j = 0; j < nbeta; j++) { stst >> dnm[i][j]; } } } bool has_rinner() const { rapidxml::xml_node<> *node = pseudo_node_->first_node("rinner"); return node; } void rinner(std::vector<double> &val) const { rapidxml::xml_node<> *node = pseudo_node_->first_node("rinner"); assert(node != NULL); int size = value<int>(node->first_attribute("size")); val.resize(size); std::istringstream stst(node->value()); for (int ii = 0; ii < size; ii++) { stst >> val[ii]; } } void qnm(int index, int &l1, int &l2, int &n, int &m, std::vector<double> &val) const { rapidxml::xml_node<> *node = pseudo_node_->first_node("qnm"); for (int i = 0; i < index; i++) node = node->next_sibling("qnm"); assert(node != NULL); n = value<int>(node->first_attribute("n")); m = value<int>(node->first_attribute("m")); l1 = value<int>(node->first_attribute("l1")); l2 = value<int>(node->first_attribute("l2")); int size = value<int>(node->first_attribute("size")); val.resize(size); std::istringstream stst(node->value()); for (int ii = 0; ii < size; ii++) { stst >> val[ii]; } } void qfcoeff(int index, int ltot, std::vector<double> &val) const { rapidxml::xml_node<> *node = pseudo_node_->first_node("qfcoeff"); while (node) { int read_index = value<int>(node->first_attribute("i")); int read_ltot = value<int>(node->first_attribute("ltot")); if (read_index == index && read_ltot == ltot) break; node = node->next_sibling("qfcoeff"); } assert(node != NULL); int size = value<int>(node->first_attribute("size")); val.resize(size); std::istringstream stst(node->value()); for (int ii = 0; ii < size; ii++) { stst >> val[ii]; } } private: bool has_projectors(int l) const { rapidxml::xml_node<> *node = pseudo_node_->first_node("projector"); while (node) { int read_l = value<int>(node->first_attribute("l")); if (l == read_l) break; node = node->next_sibling("projector"); } return node != NULL; } int nbeta() const { return value<int>(pseudo_node_->first_node("nbeta")); } std::ifstream file_; std::vector<char> buffer_; rapidxml::xml_document<> doc_; rapidxml::xml_node<> *root_node_; rapidxml::xml_node<> *pseudo_node_; }; } // namespace pseudopotential #endif