bz_main.c 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. // expects each point on its own line with real positions.
  2. // expects first line to be "dim npoints reals"--from thiemard
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. #include "bz_discr.h"
  6. void usage()
  7. {
  8. fprintf(stderr, "Usage: bz_discr [dim npoints] [file]\n\nIf file not present, read from stdin. If dim, npoints not present, \nassume header '%%dim %%npoints reals' (e.g. '2 100 reals') in file.\n");
  9. }
  10. int main(int argc, char **argv)
  11. {
  12. int dim, npoints,i,j;
  13. FILE *pointfile;
  14. double **pointset;
  15. FILE *random;
  16. unsigned int seed;
  17. random = fopen("/dev/random", "rb");
  18. fread(&seed, 4, 1, random);
  19. srand(seed);
  20. switch (argc) {
  21. case 0:
  22. case 1: // nothing, or program name only: all from stdin
  23. i=scanf("%d %d reals\n", &dim, &npoints);
  24. if (i != 2) {
  25. fprintf(stderr, "stdin mode and header line not present\n");
  26. usage();
  27. exit(EXIT_FAILURE);
  28. }
  29. pointfile=stdin;
  30. break;
  31. case 2: // one arg, interpret as file name
  32. pointfile = fopen(argv[1], "r");
  33. if (!pointfile) {
  34. fprintf(stderr, "File open failed: %s\n", argv[3]);
  35. exit(EXIT_FAILURE);
  36. }
  37. i=fscanf(pointfile, "%d %d reals\n", &dim, &npoints);
  38. if (i != 2) {
  39. fprintf(stderr, "stdin mode and header line not present\n");
  40. exit(EXIT_FAILURE);
  41. }
  42. break;
  43. case 3: // interpret as dim npoints
  44. dim=atoi(argv[1]);
  45. npoints=atoi(argv[2]);
  46. pointfile=stdin;
  47. break;
  48. case 4: // interpret as dim npoints file; file not allowed to have header
  49. dim=atoi(argv[1]);
  50. npoints=atoi(argv[2]);
  51. pointfile = fopen(argv[3], "r");
  52. if (!pointfile) {
  53. fprintf(stderr, "File open failed: %s\n", argv[3]);
  54. exit(EXIT_FAILURE);
  55. }
  56. break;
  57. default:
  58. usage();
  59. exit(EXIT_FAILURE);
  60. }
  61. fprintf(stderr, "Reading dim %d npoints %d\n", dim, npoints);
  62. pointset = malloc(npoints*sizeof(double*));
  63. for (i=0; i<npoints; i++) {
  64. pointset[i] = malloc(dim*sizeof(double));
  65. for (j=0; j<dim; j++) {
  66. // newline counts as whitespace
  67. if (!fscanf(pointfile, "%lg ", &(pointset[i][j]))) {
  68. fprintf(stderr, "File does not contain enough data points!\n");
  69. exit(EXIT_FAILURE);
  70. }
  71. }
  72. }
  73. fprintf(stderr, "Calling bz_discr calculation\n");
  74. printf("%g\n", poly_discr(pointset, dim, npoints));
  75. return EXIT_SUCCESS;
  76. }