Bsoft  2.1.0
Bernard's software package
utilities.cpp
Go to the documentation of this file.
1 
9 #include <errno.h>
10 #include <sys/sysctl.h>
11 #include <stdio.h>
12 #include "utilities.h"
13 
14 #include <iostream>
15 
16 #define MAX_GET_LEN 32
17 
18 // Definition of global variables
19 int verbose(0); // Default: No output to shell
20 string command; // Command line
21 
22 ostream &tab(ostream &out)
23 {
24  return out << '\t';
25 }
26 
36 int cmd_line(int argc, char **argv)
37 {
38  int i;
39 
40  command.clear();
41 
42  for ( i=0; i<argc; i++ )
43  command = command + argv[i] + " ";
44 
45  if ( verbose & VERB_DEBUG )
46  cout << "DEBUG: cmd_line: " << command << endl;
47 
48  return 0;
49 }
50 
59 {
60  return Bstring(command);
61 }
62 
72 {
73  time_t ti = time(NULL);
74 
75  Bstring clstring = "# " + command;
76 
77  clstring = clstring + "\n# " + asctime(localtime(&ti)) + "\n";
78 
79  if ( verbose & VERB_DEBUG )
80  cout << "DEBUG command_line_time: " << clstring << endl;
81 
82  return clstring;
83 }
84 
92 string get_user_name()
93 {
94  int bufsize;
95 
96  if ( (bufsize = sysconf(_SC_GETPW_R_SIZE_MAX)) == -1 )
97  bufsize = 16384;
98 
99  char buffer[bufsize];
100  passwd pw, *result = NULL;
101 
102  string user_name("unknown");
103 
104  if ( getpwuid_r(getuid(), &pw, buffer, bufsize, &result) == 0 && result)
105  user_name = pw.pw_name;
106 
107  return user_name;
108 }
109 
126 void usage(const char** use, int all)
127 {
128  int i;
129 
130  if ( all )
131  for ( i = 0; use[i] != NULL; i++ )
132  cout << use[i] << endl;
133  else
134  for ( i = 0; use[i] && strstr(use[i], "Example") == 0; i++ )
135  cout << use[i] << endl;
136 
137  cout << endl << "Bsoft version " << BVERSION << " (" << 8*sizeof(long) << " bit)" << endl << endl;
138 
139  bexit(0);
140 }
141 
152 {
153  SysType type = Unknown_System;
154  char* test = new char[8];
155  int* itest = (int *) test;
156  float* ftest = (float *) test;
157 
158  memcpy(test, "jbh ", 8);
159 
160  if ( itest[0] == 1784834080 && fabs(ftest[0] - 6.84272e+25) < 1e+21 )
161  type = BigIEEE;
162 
163  if ( itest[0] == 543711850 && fabs(ftest[0] - 1.96837e-19) < 1e-23 )
164  type = LittleIEEE;
165 
166  if ( ( ( verbose > VERB_PROCESS ) && show ) || ( verbose & VERB_DEBUG ) ) {
167  switch ( type ) {
168  case BigIEEE:
169  cout << "System type: Big-endian IEEE";
170  break;
171  case LittleIEEE:
172  cout << "System type: Little-endian IEEE";
173  break;
174  default:
175  cout << "System type: Unknown";
176  break;
177  }
178  cout << " (" << 8*sizeof(long) << ")" << endl << endl;
179  }
180 
181  if ( verbose & VERB_DEBUG )
182  cout << "DEBUG systype: " << test << " " << itest[0] << " " << ftest[0] << " " << type << endl;
183 
184  delete[] test;
185 
186  return type;
187 }
188 
194 {
195  size_t np(1);
196 
197 #ifdef OMP_H
198  np = omp_get_num_procs();
199 #endif
200 #ifdef HAVE_GCD
201  np = sysconf( _SC_NPROCESSORS_ONLN );
202 #endif
203 
204  return np;
205 }
206 
212 {
213 #if defined(CTL_HW) && (defined(HW_MEMSIZE) || defined(HW_PHYSMEM64))
214 
215  int mib[2];
216  mib[0] = CTL_HW;
217 #if defined(HW_MEMSIZE)
218  mib[1] = HW_MEMSIZE; // OSX
219 #elif defined(HW_PHYSMEM64)
220  mib[1] = HW_PHYSMEM64; // NetBSD, OpenBSD
221 #endif
222  u_int namelen = sizeof(mib) / sizeof(mib[0]);
223  long size(0);
224  size_t len = sizeof(size);
225 
226  if (sysctl(mib, namelen, &size, &len, NULL, 0) == 0)
227  return size;
228 
229 #elif defined(_SC_PHYS_PAGES)
230 
231 #if defined(_SC_PAGESIZE) // FreeBSD, Linux, OpenBSD, and Solaris
232  return (long)sysconf( _SC_PHYS_PAGES ) *
233  (long)sysconf( _SC_PAGESIZE );
234 
235 #elif defined(_SC_PAGE_SIZE)
236  return (long)sysconf( _SC_PHYS_PAGES ) *
237  (long)sysconf( _SC_PAGE_SIZE );
238 #endif
239 
240 #elif defined(_SC_AIX_REALMEM) // AIX
241  return (long)sysconf( _SC_AIX_REALMEM ) * (long)1024L;
242 
243 #endif
244 
245  perror("system_memory: sysctl error");
246 
247  return 0;
248 }
249 
255 int memory_check(long mem_required)
256 {
257  long mem_avail = system_memory();
258 
259  if ( verbose ) {
260  cout << "Memory available: " << mem_avail << endl;
261  cout << "Memory required: " << mem_required << " ("
262  << setprecision(2) << mem_required*100.0/mem_avail << " %)" << endl << endl;
263  }
264 
265  if ( mem_avail < mem_required ) {
266  cerr << "Error: Not enough memory!" << endl;
267  cerr << "Memory available: " << mem_avail << endl;
268  cerr << "Memory required: " << mem_required << endl << endl;
269  bexit(-1);
270  }
271 
272  return 1;
273 }
274 
280 int bexit(int value)
281 {
282  exit(value);
283  return value;
284 }
285 
295 DataType getdatatype(char letter)
296 {
297  DataType type;
298 
299  switch ( letter ) {
300  case '1': type = Bit; break;
301  case 'b': type = UCharacter; break;
302  case 'c': type = SCharacter; break;
303  case 'u': type = UShort; break;
304  case 's': type = Short; break;
305  case 'j': type = UInteger; break;
306  case 'i': type = Integer; break;
307  case 'k': type = ULong; break;
308  case 'l': type = Long; break;
309  case 'f': type = Float; break;
310  case 'd': type = Double; break;
311  case 'S': type = Short; break;
312  case 'I': type = Integer; break;
313  case 'F': type = Float; break;
314  case 'D': type = Double; break;
315  default: type = Unknown_Type; break;
316  }
317 
318  return type;
319 }
320 
321 
335 int select_numbers(Bstring& string, int n, int* numsel)
336 {
337  vector<int> ns = select_numbers(string, n);
338  for ( long i=0; i<n; ++i ) numsel[i] = ns[i];
339  return 0;
340 }
341 
342 vector<int> select_numbers(Bstring& string, int n)
343 {
344  vector<int> numsel(n, 0);
345 
346  int i, j, k;
347 
348  if ( string.length() < 1 || string == "all" ) {
349  for ( i=0; i<n; i++ ) numsel[i] = 1;
350  return numsel;
351  }
352 
353  if ( verbose & VERB_DEBUG )
354  cout << "DEBUG select_numbers: string=" << string << " n=" << n << endl;
355 
356  Bstring* s, *s2, *sc;
357  Bstring* strcol = string.split(":");
358  Bstring* strarr = NULL;
359 
360  for ( k=1, sc = strcol; sc; sc = sc->next, k++ ) {
361  strarr = sc->split(",");
362 
363  for ( s = strarr; s; s = s->next ) {
364  s2 = s->split("-");
365  i = j = s2->integer();
366  if ( s2->next ) j = s2->next->integer();
367  for ( ; i <= j && i < n; i++ ) numsel[i] = k;
368  string_kill(s2);
369  }
370 
371  string_kill(strarr);
372  }
373 
374  string_kill(strcol);
375 
376  if ( verbose & VERB_DEBUG ) {
377  cout << "DEBUG select_numbers: ";
378  for ( i=0; i<n; i++ ) cout << numsel[i];
379  cout << endl;
380  }
381 
382  return numsel;
383 }
384 
397 int findNextPowerOf(int startNumber, int powerOf)
398 {
399  int rVal = powerOf;
400 
401  if (powerOf <= 0 ) {
402  rVal = 0;
403  } else if (powerOf == 1) {
404  rVal = startNumber;
405  } else {
406  while (rVal < startNumber) {
407  rVal *= powerOf;
408  }
409  }
410 
411  return rVal;
412 }
413 
423 int get_integer(char* ptr, int len)
424 {
425  if ( len > MAX_GET_LEN ) {
426  cerr << "Error in get_integer: scanning length too large!" << endl;
427  return 0;
428  }
429  char temp[MAX_GET_LEN];
430  int d(0);
431  strncpy(temp, ptr, len);
432  temp[len] = 0;
433  sscanf(temp, "%d", &d);
434  return d;
435 }
436 
446 float get_float(char* ptr, int len)
447 {
448  if ( len > MAX_GET_LEN ) {
449  cerr << "Error in get_integer: scanning length too large!" << endl;
450  return 0;
451  }
452  char temp[MAX_GET_LEN];
453  float f(0);
454  strncpy(temp, ptr, len);
455  temp[len] = 0;
456  sscanf(temp, "%f", &f);
457  return f;
458 }
459 
468 void swapbytes(unsigned char* v, size_t n)
469 {
470  unsigned char t;
471  size_t i;
472 
473  for ( i=0, n--; i<n; i++, n-- ) {
474  t = v[i];
475  v[i] = v[n];
476  v[n] = t;
477  }
478 }
479 
489 void swapbytes(size_t size, unsigned char* v, size_t n)
490 {
491  if ( n < 2 ) return;
492 
493  if ( verbose & VERB_DEBUG )
494  cout << "DEBUG swapbytes: size=" << size << " n=" << n << endl;
495 
496  size_t i;
497 
498  for ( i=0; i<size; i+=n, v+=n ) swapbytes(v, n);
499 }
500 
512 void vax2ieee(unsigned char* v, int sb)
513 {
514  unsigned char t[4];
515  int i, shift, expnt;
516 
517  if ( sb ) {
518  t[0] = v[2]; // Swap byte order
519  t[1] = v[3];
520  t[2] = v[0];
521  t[3] = v[1];
522  } else {
523  t[0] = v[1]; // Swap for VAX format
524  t[1] = v[0];
525  t[2] = v[3];
526  t[3] = v[2];
527  }
528  for ( i=0; i<4; i++ ) v[i] = t[i];
529 
530  expnt = (v[0] << 1) | (v[1] >> 7); // Get exponent
531  if ( expnt == 0 )
532  if ( v[0] == 0 ) // Special case zero
533  memset(t, '\0', 4);
534  else { // Special case infinity or NaN
535  t[0] = 0xff;
536  t[1] = v[1] | 0x80;
537  }
538  else if ( expnt > 2 ) // Normalized value
539  t[0] = v[0] - 0x01; // Subtract 2 from the exponent
540  else { // Denormalized value
541  shift = 3 - expnt;
542  t[0] = v[0] & 0x80; // Keep sign, expnt = 0
543  t[1] = ( (v[1] & 0x7f) >> shift ) | ( 0x10 << expnt );
544  t[2] = ( v[1] << ( 8-shift ) ) | ( v[2] >> shift );
545  t[3] = ( v[2] << ( 8-shift ) ) | ( v[3] >> shift );
546  }
547  for ( i=0; i<4; i++ ) v[i] = t[i];
548 }
549 
558 double angle_set_negPI_to_PI(double angle)
559 {
560  if ( !isfinite(angle) ) return 0;
561 
562 // angle = fmod(angle, TWOPI);
563  angle -= TWOPI*(long(angle/TWOPI));
564  while ( angle <= -M_PI ) angle += TWOPI;
565  while ( angle > M_PI ) angle -= TWOPI;
566 
567  return angle;
568 }
569 
586 float remove_negative_zeros(float value0, float threshold)
587 {
588  float value;
589 
590  if ( (value0 > threshold) && (value0 < 0) )
591  value = 0;
592  else
593  value = value0;
594 
595  return value;
596 }
597 
609 size_t get_chunk_size(size_t datasize)
610 {
611  size_t np = system_processors();
612  size_t chunk_size = datasize/np;
613 
614  if ( chunk_size < datasize && chunk_size < MIN_SIZE_FOR_THREADING ) {
615  chunk_size = MIN_SIZE_FOR_THREADING;
616  np = (datasize - 1)/chunk_size + 1;
617  }
618 
619  if ( verbose & VERB_PROCESS )
620  cout << "Number of processors: " << np << endl << endl;
621 
622  if ( verbose & VERB_FULL )
623  cout << "Chunk size: " << chunk_size << endl << endl;
624 
625  if ( verbose & VERB_DEBUG )
626  cout << "DEBUG get_chunk_size: chunk_size = " << chunk_size << endl;
627 
628  return chunk_size;
629 }
630 
643 size_t get_chunk_size(size_t datasize, size_t c)
644 {
645  size_t np = system_processors();
646  size_t chunk_size(datasize/np);
647 
648  while ( chunk_size%c ) chunk_size++;
649 
650  if ( chunk_size < datasize && chunk_size < MIN_SIZE_FOR_THREADING ) {
651  chunk_size = MIN_SIZE_FOR_THREADING;
652  np = (datasize - 1)/chunk_size + 1;
653  }
654 
655  if ( verbose & VERB_PROCESS )
656  cout << "Number of processors: " << np << endl << endl;
657 
658  if ( verbose & VERB_FULL )
659  cout << "Chunk size: " << chunk_size << endl << endl;
660 
661  if ( verbose & VERB_DEBUG )
662  cout << "DEBUG get_chunk_size: chunk_size = " << chunk_size << endl;
663 
664  return chunk_size;
665 }
666 
667 
680 int error_show(const char* message, const char* file, int line)
681 {
682  char string[1024];
683 
684  snprintf(string, 1024, "[%s:%d] %s", file, line, message);
685 
686  perror(string);
687 
688  if ( errno ) cerr << "errno " << errno << ": ";
689 
690  switch ( errno ) {
691  case ENOENT:
692  cerr << "Make sure the file exists and the path to the file is correct" << endl;
693  break;
694  case EACCES:
695  cerr << "Make sure you have permission to write to this directory" << endl;
696  break;
697  case ENOMEM:
698  cerr << "The memory available on this computer may be insufficient" << endl;
699  break;
700  default:
701  cerr << endl;
702  }
703 
704  return errno;
705 }
706 
719 int error_show(string message, string file, int line)
720 {
721 // char string[1024];
722 
723 // snprintf(string, 1024, "[%s:%d] %s", file, line, message);
724 
725  string s = "[" + file + ":" + to_string(line) + "] " + message;
726 
727  perror(s.c_str());
728 // cout << s << endl;
729 
730  if ( errno ) cerr << "errno " << errno << ": ";
731 
732  switch ( errno ) {
733  case ENOENT:
734  cerr << "Make sure the file exists and the path to the file is correct" << endl;
735  break;
736  case EACCES:
737  cerr << "Make sure you have permission to write to this directory" << endl;
738  break;
739  case ENOMEM:
740  cerr << "The memory available on this computer may be insufficient" << endl;
741  break;
742  default:
743  cerr << endl;
744  }
745 
746  return errno;
747 }
748 
command_line_time
Bstring command_line_time()
Returns the command line and time in a string.
Definition: utilities.cpp:71
system_processors
size_t system_processors()
Returns the number of processors.
Definition: utilities.cpp:193
SysType
SysType
Definition: utilities.h:131
Bit
@ Bit
Definition: utilities.h:152
VERB_DEBUG
#define VERB_DEBUG
Definition: utilities.h:116
ULong
@ ULong
Definition: utilities.h:159
string_kill
int string_kill(Bstring *list)
Kills a string linked list.
Definition: Bstring.cpp:768
UCharacter
@ UCharacter
Definition: utilities.h:153
verbose
int verbose(0)
Bstring
Definition: Bstring.h:29
usage
void usage(const char **use, int all)
Prints usage information.
Definition: utilities.cpp:126
MAX_GET_LEN
#define MAX_GET_LEN
Definition: utilities.cpp:16
vax2ieee
void vax2ieee(unsigned char *v, int sb)
Converts VAX floating point format to IEEE floating point format.
Definition: utilities.cpp:512
Bstring::integer
long integer()
Definition: Bstring.cpp:547
swapbytes
void swapbytes(unsigned char *v, size_t n)
Swaps bytes.
Definition: utilities.cpp:468
use
const char * use[]
Definition: b3v.cpp:19
tab
ostream & tab(ostream &out)
Definition: utilities.cpp:22
command_line
Bstring command_line()
Returns the command line.
Definition: utilities.cpp:58
sb
int sb(0)
memory_check
int memory_check(long mem_required)
Checking if there is enough memory, abort if not.
Definition: utilities.cpp:255
length
double length(vector< T > v)
Definition: Vector3.h:530
VERB_PROCESS
#define VERB_PROCESS
Definition: utilities.h:111
angle_set_negPI_to_PI
double angle_set_negPI_to_PI(double angle)
Returns an angle between -PI and PI.
Definition: utilities.cpp:558
command
string command
Definition: utilities.cpp:20
Short
@ Short
Definition: utilities.h:156
BVERSION
#define BVERSION
Definition: utilities.h:9
cmd_line
int cmd_line(int argc, char **argv)
Reconstructs the command line as a global string.
Definition: utilities.cpp:36
remove_negative_zeros
float remove_negative_zeros(float value0, float threshold)
Prevent a negative sign from being placed in front of zero value in a text file.
Definition: utilities.cpp:586
getdatatype
DataType getdatatype(char letter)
Get the data type indicated by a single letter code.
Definition: utilities.cpp:295
system_memory
long system_memory()
Returns system memory size.
Definition: utilities.cpp:211
get_chunk_size
size_t get_chunk_size(size_t datasize)
Returns the chunk size per thread.
Definition: utilities.cpp:609
systype
SysType systype(int show)
Finds the system type - mostly just for byte order.
Definition: utilities.cpp:151
UShort
@ UShort
Definition: utilities.h:155
Unknown_Type
@ Unknown_Type
Definition: utilities.h:151
show
int show(0)
LittleIEEE
@ LittleIEEE
Definition: utilities.h:135
BigIEEE
@ BigIEEE
Definition: utilities.h:133
bexit
int bexit(int value)
Exit function for cleanup and debugging.
Definition: utilities.cpp:280
error_show
int error_show(const char *message, const char *file, int line)
Displays the error with file and line reference.
Definition: utilities.cpp:680
M_PI
#define M_PI
Definition: utilities.h:63
utilities.h
Header file for general utilities.
Integer
@ Integer
Definition: utilities.h:158
Unknown_System
@ Unknown_System
Definition: utilities.h:132
Long
@ Long
Definition: utilities.h:160
isfinite
bool isfinite(complex< T > &value)
findNextPowerOf
int findNextPowerOf(int startNumber, int powerOf)
Finds the next greatest number that is a power of a given number.
Definition: utilities.cpp:397
get_float
float get_float(char *ptr, int len)
Converts a defined length string into a floating point number.
Definition: utilities.cpp:446
Bstring::next
Bstring * next
Definition: Bstring.h:31
get_integer
int get_integer(char *ptr, int len)
Converts a defined length string into an integer.
Definition: utilities.cpp:423
Bstring::split
Bstring * split()
Definition: Bstring.cpp:605
VERB_FULL
#define VERB_FULL
Definition: utilities.h:113
SCharacter
@ SCharacter
Definition: utilities.h:154
DataType
DataType
Base data type specifier.
Definition: utilities.h:150
Double
@ Double
Definition: utilities.h:162
Float
@ Float
Definition: utilities.h:161
UInteger
@ UInteger
Definition: utilities.h:157
MIN_SIZE_FOR_THREADING
#define MIN_SIZE_FOR_THREADING
Definition: utilities.h:47
get_user_name
string get_user_name()
Returns the user name.
Definition: utilities.cpp:92
select_numbers
int select_numbers(Bstring &string, int n, int *numsel)
Converts a string with a selection specification into an integer array.
Definition: utilities.cpp:335
TWOPI
#define TWOPI
Definition: utilities.h:72