before changing it!
Copyright (C) 1987, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 2000
- Free Software Foundation, Inc.
+ Free Software Foundation, Inc.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public License as
/* This needs to come after some library #include
to get __GNU_LIBRARY__ defined. */
-#ifdef __GNU_LIBRARY__
+#ifdef __GNU_LIBRARY__
/* Don't include stdlib.h for non-GNU C libraries because some of them
contain conflicting prototypes for getopt. */
# include <stdlib.h>
# include <unistd.h>
-#endif /* GNU C library. */
+#endif /* GNU C library. */
#ifdef VMS
# include <unixlib.h>
When compiling libc, the _ macro is predefined. */
# ifdef HAVE_LIBINTL_H
# include <libintl.h>
-# define _(msgid) gettext (msgid)
+# define _(msgid) gettext (msgid)
# else
-# define _(msgid) (msgid)
+# define _(msgid) (msgid)
# endif
#endif
Also, when `ordering' is RETURN_IN_ORDER,
each non-option ARGV-element is returned here. */
-#if ! defined(HAVE_GETOPT) && ! defined(HAVE_GETOPT_LONG)
+#if ! defined(HAVE_GETOPT) && ! defined(HAVE_GETOPT_LONG)
char *optarg;
#endif
how much of ARGV has been scanned so far. */
/* 1003.2 says this must be 1 before any call. */
-#if ! defined(HAVE_GETOPT) && ! defined(HAVE_GETOPT_LONG)
+#if ! defined(HAVE_GETOPT) && ! defined(HAVE_GETOPT_LONG)
int optind = 1;
#endif
causes problems with re-calling getopt as programs generally don't
know that. */
-#if ! defined(HAVE_GETOPT) && ! defined(HAVE_GETOPT_LONG)
+#if ! defined(HAVE_GETOPT) && ! defined(HAVE_GETOPT_LONG)
int __getopt_initialized;
#else
extern int __getopt_initialized;
/* Callers store zero here to inhibit the error message
for unrecognized options. */
-#if ! defined(HAVE_GETOPT) && ! defined(HAVE_GETOPT_LONG)
+#if ! defined(HAVE_GETOPT) && ! defined(HAVE_GETOPT_LONG)
int opterr = 1;
#endif
This must be initialized on some systems to avoid linking in the
system's own getopt implementation. */
-#if ! defined(HAVE_GETOPT) && ! defined(HAVE_GETOPT_LONG)
+#if ! defined(HAVE_GETOPT) && ! defined(HAVE_GETOPT_LONG)
int optopt = '?';
#endif
/* Value of POSIXLY_CORRECT environment variable. */
static char *posixly_correct;
\f
-#ifdef __GNU_LIBRARY__
+#ifdef __GNU_LIBRARY__
/* We want to avoid inclusion of string.h with non-GNU libraries
because there are many ways it can cause trouble.
On some systems, it contains special magic macros that don't work
in GCC. */
# include <string.h>
-# define my_index strchr
+# define my_index strchr
#else
# if HAVE_STRING_H
while (*str)
{
if (*str == chr)
- return (char *) str;
+ return (char *) str;
str++;
}
return 0;
# endif /* text_set_element */
# define SWAP_FLAGS(ch1, ch2) \
- if (nonoption_flags_len > 0) \
- { \
- char __tmp = __getopt_nonoption_flags[ch1]; \
- __getopt_nonoption_flags[ch1] = __getopt_nonoption_flags[ch2]; \
- __getopt_nonoption_flags[ch2] = __tmp; \
+ if (nonoption_flags_len > 0) \
+ { \
+ char __tmp = __getopt_nonoption_flags[ch1]; \
+ __getopt_nonoption_flags[ch1] = __getopt_nonoption_flags[ch2]; \
+ __getopt_nonoption_flags[ch2] = __tmp; \
}
-#else /* !_LIBC */
+#else /* !_LIBC */
# define SWAP_FLAGS(ch1, ch2)
-#endif /* _LIBC */
+#endif /* _LIBC */
/* Exchange two adjacent subsequences of ARGV.
One subsequence is elements [first_nonopt,last_nonopt)
if (nonoption_flags_len > 0 && top >= nonoption_flags_max_len)
{
/* We must extend the array. The user plays games with us and
- presents new arguments. */
+ presents new arguments. */
char *new_str = malloc (top + 1);
if (new_str == NULL)
- nonoption_flags_len = nonoption_flags_max_len = 0;
+ nonoption_flags_len = nonoption_flags_max_len = 0;
else
- {
- memset (__mempcpy (new_str, __getopt_nonoption_flags,
- nonoption_flags_max_len),
- '\0', top + 1 - nonoption_flags_max_len);
- nonoption_flags_max_len = top + 1;
- __getopt_nonoption_flags = new_str;
- }
+ {
+ memset (__mempcpy (new_str, __getopt_nonoption_flags,
+ nonoption_flags_max_len),
+ '\0', top + 1 - nonoption_flags_max_len);
+ nonoption_flags_max_len = top + 1;
+ __getopt_nonoption_flags = new_str;
+ }
}
#endif
while (top > middle && middle > bottom)
{
if (top - middle > middle - bottom)
- {
- /* Bottom segment is the short one. */
- int len = middle - bottom;
- register int i;
-
- /* Swap it with the top part of the top segment. */
- for (i = 0; i < len; i++)
- {
- tem = argv[bottom + i];
- argv[bottom + i] = argv[top - (middle - bottom) + i];
- argv[top - (middle - bottom) + i] = tem;
- SWAP_FLAGS (bottom + i, top - (middle - bottom) + i);
- }
- /* Exclude the moved bottom segment from further swapping. */
- top -= len;
- }
+ {
+ /* Bottom segment is the short one. */
+ int len = middle - bottom;
+ register int i;
+
+ /* Swap it with the top part of the top segment. */
+ for (i = 0; i < len; i++)
+ {
+ tem = argv[bottom + i];
+ argv[bottom + i] = argv[top - (middle - bottom) + i];
+ argv[top - (middle - bottom) + i] = tem;
+ SWAP_FLAGS (bottom + i, top - (middle - bottom) + i);
+ }
+ /* Exclude the moved bottom segment from further swapping. */
+ top -= len;
+ }
else
- {
- /* Top segment is the short one. */
- int len = top - middle;
- register int i;
-
- /* Swap it with the bottom part of the bottom segment. */
- for (i = 0; i < len; i++)
- {
- tem = argv[bottom + i];
- argv[bottom + i] = argv[middle + i];
- argv[middle + i] = tem;
- SWAP_FLAGS (bottom + i, middle + i);
- }
- /* Exclude the moved top segment from further swapping. */
- bottom += len;
- }
+ {
+ /* Top segment is the short one. */
+ int len = top - middle;
+ register int i;
+
+ /* Swap it with the bottom part of the bottom segment. */
+ for (i = 0; i < len; i++)
+ {
+ tem = argv[bottom + i];
+ argv[bottom + i] = argv[middle + i];
+ argv[middle + i] = tem;
+ SWAP_FLAGS (bottom + i, middle + i);
+ }
+ /* Exclude the moved top segment from further swapping. */
+ bottom += len;
+ }
}
/* Update records for the slots the non-options now occupy. */
&& argc == original_argc && argv == original_argv)
{
if (nonoption_flags_max_len == 0)
- {
- if (__getopt_nonoption_flags == NULL
- || __getopt_nonoption_flags[0] == '\0')
- nonoption_flags_max_len = -1;
- else
- {
- const char *orig_str = __getopt_nonoption_flags;
- int len = nonoption_flags_max_len = strlen (orig_str);
- if (nonoption_flags_max_len < argc)
- nonoption_flags_max_len = argc;
- __getopt_nonoption_flags =
- (char *) malloc (nonoption_flags_max_len);
- if (__getopt_nonoption_flags == NULL)
- nonoption_flags_max_len = -1;
- else
- memset (__mempcpy (__getopt_nonoption_flags, orig_str, len),
- '\0', nonoption_flags_max_len - len);
- }
- }
+ {
+ if (__getopt_nonoption_flags == NULL
+ || __getopt_nonoption_flags[0] == '\0')
+ nonoption_flags_max_len = -1;
+ else
+ {
+ const char *orig_str = __getopt_nonoption_flags;
+ int len = nonoption_flags_max_len = strlen (orig_str);
+ if (nonoption_flags_max_len < argc)
+ nonoption_flags_max_len = argc;
+ __getopt_nonoption_flags =
+ (char *) malloc (nonoption_flags_max_len);
+ if (__getopt_nonoption_flags == NULL)
+ nonoption_flags_max_len = -1;
+ else
+ memset (__mempcpy (__getopt_nonoption_flags, orig_str, len),
+ '\0', nonoption_flags_max_len - len);
+ }
+ }
nonoption_flags_len = nonoption_flags_max_len;
}
else
if (optind == 0 || !__getopt_initialized)
{
if (optind == 0)
- optind = 1; /* Don't scan ARGV[0], the program name. */
+ optind = 1; /* Don't scan ARGV[0], the program name. */
optstring = _getopt_initialize (argc, argv, optstring);
__getopt_initialized = 1;
}
from the shell indicating it is not an option. The later information
is only used when the used in the GNU libc. */
#ifdef _LIBC
-# define NONOPTION_P (argv[optind][0] != '-' || argv[optind][1] == '\0' \
- || (optind < nonoption_flags_len \
- && __getopt_nonoption_flags[optind] == '1'))
+# define NONOPTION_P (argv[optind][0] != '-' || argv[optind][1] == '\0' \
+ || (optind < nonoption_flags_len \
+ && __getopt_nonoption_flags[optind] == '1'))
#else
# define NONOPTION_P (argv[optind][0] != '-' || argv[optind][1] == '\0')
#endif
/* Advance to the next ARGV-element. */
/* Give FIRST_NONOPT & LAST_NONOPT rational values if OPTIND has been
- moved back by the user (who may also have changed the arguments). */
+ moved back by the user (who may also have changed the arguments). */
if (last_nonopt > optind)
- last_nonopt = optind;
+ last_nonopt = optind;
if (first_nonopt > optind)
- first_nonopt = optind;
+ first_nonopt = optind;
if (ordering == PERMUTE)
- {
- /* If we have just processed some options following some non-options,
- exchange them so that the options come first. */
+ {
+ /* If we have just processed some options following some non-options,
+ exchange them so that the options come first. */
- if (first_nonopt != last_nonopt && last_nonopt != optind)
- exchange ((char **) argv);
- else if (last_nonopt != optind)
- first_nonopt = optind;
+ if (first_nonopt != last_nonopt && last_nonopt != optind)
+ exchange ((char **) argv);
+ else if (last_nonopt != optind)
+ first_nonopt = optind;
- /* Skip any additional non-options
- and extend the range of non-options previously skipped. */
+ /* Skip any additional non-options
+ and extend the range of non-options previously skipped. */
- while (optind < argc && NONOPTION_P)
- optind++;
- last_nonopt = optind;
- }
+ while (optind < argc && NONOPTION_P)
+ optind++;
+ last_nonopt = optind;
+ }
/* The special ARGV-element `--' means premature end of options.
- Skip it like a null option,
- then exchange with previous non-options as if it were an option,
- then skip everything else like a non-option. */
+ Skip it like a null option,
+ then exchange with previous non-options as if it were an option,
+ then skip everything else like a non-option. */
if (optind != argc && !strcmp (argv[optind], "--"))
- {
- optind++;
+ {
+ optind++;
- if (first_nonopt != last_nonopt && last_nonopt != optind)
- exchange ((char **) argv);
- else if (first_nonopt == last_nonopt)
- first_nonopt = optind;
- last_nonopt = argc;
+ if (first_nonopt != last_nonopt && last_nonopt != optind)
+ exchange ((char **) argv);
+ else if (first_nonopt == last_nonopt)
+ first_nonopt = optind;
+ last_nonopt = argc;
- optind = argc;
- }
+ optind = argc;
+ }
/* If we have done all the ARGV-elements, stop the scan
- and back over any non-options that we skipped and permuted. */
+ and back over any non-options that we skipped and permuted. */
if (optind == argc)
- {
- /* Set the next-arg-index to point at the non-options
- that we previously skipped, so the caller will digest them. */
- if (first_nonopt != last_nonopt)
- optind = first_nonopt;
- return -1;
- }
+ {
+ /* Set the next-arg-index to point at the non-options
+ that we previously skipped, so the caller will digest them. */
+ if (first_nonopt != last_nonopt)
+ optind = first_nonopt;
+ return -1;
+ }
/* If we have come to a non-option and did not permute it,
- either stop the scan or describe it to the caller and pass it by. */
+ either stop the scan or describe it to the caller and pass it by. */
if (NONOPTION_P)
- {
- if (ordering == REQUIRE_ORDER)
- return -1;
- optarg = argv[optind++];
- return 1;
- }
+ {
+ if (ordering == REQUIRE_ORDER)
+ return -1;
+ optarg = argv[optind++];
+ return 1;
+ }
/* We have found another option-ARGV-element.
- Skip the initial punctuation. */
+ Skip the initial punctuation. */
nextchar = (argv[optind] + 1
- + (longopts != NULL && argv[optind][1] == '-'));
+ + (longopts != NULL && argv[optind][1] == '-'));
}
/* Decode the current option-ARGV-element. */
if (longopts != NULL
&& (argv[optind][1] == '-'
- || (long_only && (argv[optind][2] || !my_index (optstring, argv[optind][1])))))
+ || (long_only && (argv[optind][2] || !my_index (optstring, argv[optind][1])))))
{
char *nameend;
const struct option *p;
int option_index;
for (nameend = nextchar; *nameend && *nameend != '='; nameend++)
- /* Do nothing. */ ;
+ /* Do nothing. */ ;
/* Test all long options for either exact match
- or abbreviated matches. */
+ or abbreviated matches. */
for (p = longopts, option_index = 0; p->name; p++, option_index++)
- if (!strncmp (p->name, nextchar, nameend - nextchar))
- {
- if ((unsigned int) (nameend - nextchar)
- == (unsigned int) strlen (p->name))
- {
- /* Exact match found. */
- pfound = p;
- indfound = option_index;
- exact = 1;
- break;
- }
- else if (pfound == NULL)
- {
- /* First nonexact match found. */
- pfound = p;
- indfound = option_index;
- }
- else
- /* Second or later nonexact match found. */
- ambig = 1;
- }
+ if (!strncmp (p->name, nextchar, nameend - nextchar))
+ {
+ if ((unsigned int) (nameend - nextchar)
+ == (unsigned int) strlen (p->name))
+ {
+ /* Exact match found. */
+ pfound = p;
+ indfound = option_index;
+ exact = 1;
+ break;
+ }
+ else if (pfound == NULL)
+ {
+ /* First nonexact match found. */
+ pfound = p;
+ indfound = option_index;
+ }
+ else
+ /* Second or later nonexact match found. */
+ ambig = 1;
+ }
if (ambig && !exact)
- {
- if (print_errors)
- fprintf (stderr, _("%s: option `%s' is ambiguous\n"),
- argv[0], argv[optind]);
- nextchar += strlen (nextchar);
- optind++;
- optopt = 0;
- return '?';
- }
+ {
+ if (print_errors)
+ fprintf (stderr, _("%s: option `%s' is ambiguous\n"),
+ argv[0], argv[optind]);
+ nextchar += strlen (nextchar);
+ optind++;
+ optopt = 0;
+ return '?';
+ }
if (pfound != NULL)
- {
- option_index = indfound;
- optind++;
- if (*nameend)
- {
- /* Don't test has_arg with >, because some C compilers don't
- allow it to be used on enums. */
- if (pfound->has_arg)
- optarg = nameend + 1;
- else
- {
- if (print_errors)
- {
- if (argv[optind - 1][1] == '-')
- /* --option */
- fprintf (stderr,
- _("%s: option `--%s' doesn't allow an argument\n"),
- argv[0], pfound->name);
- else
- /* +option or -option */
- fprintf (stderr,
- _("%s: option `%c%s' doesn't allow an argument\n"),
- argv[0], argv[optind - 1][0], pfound->name);
- }
-
- nextchar += strlen (nextchar);
-
- optopt = pfound->val;
- return '?';
- }
- }
- else if (pfound->has_arg == 1)
- {
- if (optind < argc)
- optarg = argv[optind++];
- else
- {
- if (print_errors)
- fprintf (stderr,
- _("%s: option `%s' requires an argument\n"),
- argv[0], argv[optind - 1]);
- nextchar += strlen (nextchar);
- optopt = pfound->val;
- return optstring[0] == ':' ? ':' : '?';
- }
- }
- nextchar += strlen (nextchar);
- if (longind != NULL)
- *longind = option_index;
- if (pfound->flag)
- {
- *(pfound->flag) = pfound->val;
- return 0;
- }
- return pfound->val;
- }
+ {
+ option_index = indfound;
+ optind++;
+ if (*nameend)
+ {
+ /* Don't test has_arg with >, because some C compilers don't
+ allow it to be used on enums. */
+ if (pfound->has_arg)
+ optarg = nameend + 1;
+ else
+ {
+ if (print_errors)
+ {
+ if (argv[optind - 1][1] == '-')
+ /* --option */
+ fprintf (stderr,
+ _("%s: option `--%s' doesn't allow an argument\n"),
+ argv[0], pfound->name);
+ else
+ /* +option or -option */
+ fprintf (stderr,
+ _("%s: option `%c%s' doesn't allow an argument\n"),
+ argv[0], argv[optind - 1][0], pfound->name);
+ }
+
+ nextchar += strlen (nextchar);
+
+ optopt = pfound->val;
+ return '?';
+ }
+ }
+ else if (pfound->has_arg == 1)
+ {
+ if (optind < argc)
+ optarg = argv[optind++];
+ else
+ {
+ if (print_errors)
+ fprintf (stderr,
+ _("%s: option `%s' requires an argument\n"),
+ argv[0], argv[optind - 1]);
+ nextchar += strlen (nextchar);
+ optopt = pfound->val;
+ return optstring[0] == ':' ? ':' : '?';
+ }
+ }
+ nextchar += strlen (nextchar);
+ if (longind != NULL)
+ *longind = option_index;
+ if (pfound->flag)
+ {
+ *(pfound->flag) = pfound->val;
+ return 0;
+ }
+ return pfound->val;
+ }
/* Can't find it as a long option. If this is not getopt_long_only,
- or the option starts with '--' or is not a valid short
- option, then it's an error.
- Otherwise interpret it as a short option. */
+ or the option starts with '--' or is not a valid short
+ option, then it's an error.
+ Otherwise interpret it as a short option. */
if (!long_only || argv[optind][1] == '-'
- || my_index (optstring, *nextchar) == NULL)
- {
- if (print_errors)
- {
- if (argv[optind][1] == '-')
- /* --option */
- fprintf (stderr, _("%s: unrecognized option `--%s'\n"),
- argv[0], nextchar);
- else
- /* +option or -option */
- fprintf (stderr, _("%s: unrecognized option `%c%s'\n"),
- argv[0], argv[optind][0], nextchar);
- }
- nextchar = (char *) "";
- optind++;
- optopt = 0;
- return '?';
- }
+ || my_index (optstring, *nextchar) == NULL)
+ {
+ if (print_errors)
+ {
+ if (argv[optind][1] == '-')
+ /* --option */
+ fprintf (stderr, _("%s: unrecognized option `--%s'\n"),
+ argv[0], nextchar);
+ else
+ /* +option or -option */
+ fprintf (stderr, _("%s: unrecognized option `%c%s'\n"),
+ argv[0], argv[optind][0], nextchar);
+ }
+ nextchar = (char *) "";
+ optind++;
+ optopt = 0;
+ return '?';
+ }
}
/* Look at and handle the next short option-character. */
if (temp == NULL || c == ':')
{
- if (print_errors)
- {
- if (posixly_correct)
- /* 1003.2 specifies the format of this message. */
- fprintf (stderr, _("%s: illegal option -- %c\n"),
- argv[0], c);
- else
- fprintf (stderr, _("%s: invalid option -- %c\n"),
- argv[0], c);
- }
- optopt = c;
- return '?';
+ if (print_errors)
+ {
+ if (posixly_correct)
+ /* 1003.2 specifies the format of this message. */
+ fprintf (stderr, _("%s: illegal option -- %c\n"),
+ argv[0], c);
+ else
+ fprintf (stderr, _("%s: invalid option -- %c\n"),
+ argv[0], c);
+ }
+ optopt = c;
+ return '?';
}
/* Convenience. Treat POSIX -W foo same as long option --foo */
if (temp[0] == 'W' && temp[1] == ';')
{
- char *nameend;
- const struct option *p;
- const struct option *pfound = NULL;
- int exact = 0;
- int ambig = 0;
- int indfound = 0;
- int option_index;
-
- /* This is an option that requires an argument. */
- if (*nextchar != '\0')
- {
- optarg = nextchar;
- /* If we end this ARGV-element by taking the rest as an arg,
- we must advance to the next element now. */
- optind++;
- }
- else if (optind == argc)
- {
- if (print_errors)
- {
- /* 1003.2 specifies the format of this message. */
- fprintf (stderr, _("%s: option requires an argument -- %c\n"),
- argv[0], c);
- }
- optopt = c;
- if (optstring[0] == ':')
- c = ':';
- else
- c = '?';
- return c;
- }
- else
- /* We already incremented `optind' once;
- increment it again when taking next ARGV-elt as argument. */
- optarg = argv[optind++];
-
- /* optarg is now the argument, see if it's in the
- table of longopts. */
-
- for (nextchar = nameend = optarg; *nameend && *nameend != '='; nameend++)
- /* Do nothing. */ ;
-
- /* Test all long options for either exact match
- or abbreviated matches. */
- for (p = longopts, option_index = 0; p->name; p++, option_index++)
- if (!strncmp (p->name, nextchar, nameend - nextchar))
- {
- if ((unsigned int) (nameend - nextchar) == strlen (p->name))
- {
- /* Exact match found. */
- pfound = p;
- indfound = option_index;
- exact = 1;
- break;
- }
- else if (pfound == NULL)
- {
- /* First nonexact match found. */
- pfound = p;
- indfound = option_index;
- }
- else
- /* Second or later nonexact match found. */
- ambig = 1;
- }
- if (ambig && !exact)
- {
- if (print_errors)
- fprintf (stderr, _("%s: option `-W %s' is ambiguous\n"),
- argv[0], argv[optind]);
- nextchar += strlen (nextchar);
- optind++;
- return '?';
- }
- if (pfound != NULL)
- {
- option_index = indfound;
- if (*nameend)
- {
- /* Don't test has_arg with >, because some C compilers don't
- allow it to be used on enums. */
- if (pfound->has_arg)
- optarg = nameend + 1;
- else
- {
- if (print_errors)
- fprintf (stderr, _("\
+ char *nameend;
+ const struct option *p;
+ const struct option *pfound = NULL;
+ int exact = 0;
+ int ambig = 0;
+ int indfound = 0;
+ int option_index;
+
+ /* This is an option that requires an argument. */
+ if (*nextchar != '\0')
+ {
+ optarg = nextchar;
+ /* If we end this ARGV-element by taking the rest as an arg,
+ we must advance to the next element now. */
+ optind++;
+ }
+ else if (optind == argc)
+ {
+ if (print_errors)
+ {
+ /* 1003.2 specifies the format of this message. */
+ fprintf (stderr, _("%s: option requires an argument -- %c\n"),
+ argv[0], c);
+ }
+ optopt = c;
+ if (optstring[0] == ':')
+ c = ':';
+ else
+ c = '?';
+ return c;
+ }
+ else
+ /* We already incremented `optind' once;
+ increment it again when taking next ARGV-elt as argument. */
+ optarg = argv[optind++];
+
+ /* optarg is now the argument, see if it's in the
+ table of longopts. */
+
+ for (nextchar = nameend = optarg; *nameend && *nameend != '='; nameend++)
+ /* Do nothing. */ ;
+
+ /* Test all long options for either exact match
+ or abbreviated matches. */
+ for (p = longopts, option_index = 0; p->name; p++, option_index++)
+ if (!strncmp (p->name, nextchar, nameend - nextchar))
+ {
+ if ((unsigned int) (nameend - nextchar) == strlen (p->name))
+ {
+ /* Exact match found. */
+ pfound = p;
+ indfound = option_index;
+ exact = 1;
+ break;
+ }
+ else if (pfound == NULL)
+ {
+ /* First nonexact match found. */
+ pfound = p;
+ indfound = option_index;
+ }
+ else
+ /* Second or later nonexact match found. */
+ ambig = 1;
+ }
+ if (ambig && !exact)
+ {
+ if (print_errors)
+ fprintf (stderr, _("%s: option `-W %s' is ambiguous\n"),
+ argv[0], argv[optind]);
+ nextchar += strlen (nextchar);
+ optind++;
+ return '?';
+ }
+ if (pfound != NULL)
+ {
+ option_index = indfound;
+ if (*nameend)
+ {
+ /* Don't test has_arg with >, because some C compilers don't
+ allow it to be used on enums. */
+ if (pfound->has_arg)
+ optarg = nameend + 1;
+ else
+ {
+ if (print_errors)
+ fprintf (stderr, _("\
%s: option `-W %s' doesn't allow an argument\n"),
- argv[0], pfound->name);
-
- nextchar += strlen (nextchar);
- return '?';
- }
- }
- else if (pfound->has_arg == 1)
- {
- if (optind < argc)
- optarg = argv[optind++];
- else
- {
- if (print_errors)
- fprintf (stderr,
- _("%s: option `%s' requires an argument\n"),
- argv[0], argv[optind - 1]);
- nextchar += strlen (nextchar);
- return optstring[0] == ':' ? ':' : '?';
- }
- }
- nextchar += strlen (nextchar);
- if (longind != NULL)
- *longind = option_index;
- if (pfound->flag)
- {
- *(pfound->flag) = pfound->val;
- return 0;
- }
- return pfound->val;
- }
- nextchar = NULL;
- return 'W'; /* Let the application handle it. */
+ argv[0], pfound->name);
+
+ nextchar += strlen (nextchar);
+ return '?';
+ }
+ }
+ else if (pfound->has_arg == 1)
+ {
+ if (optind < argc)
+ optarg = argv[optind++];
+ else
+ {
+ if (print_errors)
+ fprintf (stderr,
+ _("%s: option `%s' requires an argument\n"),
+ argv[0], argv[optind - 1]);
+ nextchar += strlen (nextchar);
+ return optstring[0] == ':' ? ':' : '?';
+ }
+ }
+ nextchar += strlen (nextchar);
+ if (longind != NULL)
+ *longind = option_index;
+ if (pfound->flag)
+ {
+ *(pfound->flag) = pfound->val;
+ return 0;
+ }
+ return pfound->val;
+ }
+ nextchar = NULL;
+ return 'W'; /* Let the application handle it. */
}
if (temp[1] == ':')
{
- if (temp[2] == ':')
- {
- /* This is an option that accepts an argument optionally. */
- if (*nextchar != '\0')
- {
- optarg = nextchar;
- optind++;
- }
- else
- optarg = NULL;
- nextchar = NULL;
- }
- else
- {
- /* This is an option that requires an argument. */
- if (*nextchar != '\0')
- {
- optarg = nextchar;
- /* If we end this ARGV-element by taking the rest as an arg,
- we must advance to the next element now. */
- optind++;
- }
- else if (optind == argc)
- {
- if (print_errors)
- {
- /* 1003.2 specifies the format of this message. */
- fprintf (stderr,
- _("%s: option requires an argument -- %c\n"),
- argv[0], c);
- }
- optopt = c;
- if (optstring[0] == ':')
- c = ':';
- else
- c = '?';
- }
- else
- /* We already incremented `optind' once;
- increment it again when taking next ARGV-elt as argument. */
- optarg = argv[optind++];
- nextchar = NULL;
- }
+ if (temp[2] == ':')
+ {
+ /* This is an option that accepts an argument optionally. */
+ if (*nextchar != '\0')
+ {
+ optarg = nextchar;
+ optind++;
+ }
+ else
+ optarg = NULL;
+ nextchar = NULL;
+ }
+ else
+ {
+ /* This is an option that requires an argument. */
+ if (*nextchar != '\0')
+ {
+ optarg = nextchar;
+ /* If we end this ARGV-element by taking the rest as an arg,
+ we must advance to the next element now. */
+ optind++;
+ }
+ else if (optind == argc)
+ {
+ if (print_errors)
+ {
+ /* 1003.2 specifies the format of this message. */
+ fprintf (stderr,
+ _("%s: option requires an argument -- %c\n"),
+ argv[0], c);
+ }
+ optopt = c;
+ if (optstring[0] == ':')
+ c = ':';
+ else
+ c = '?';
+ }
+ else
+ /* We already incremented `optind' once;
+ increment it again when taking next ARGV-elt as argument. */
+ optarg = argv[optind++];
+ nextchar = NULL;
+ }
}
return c;
}
const char *optstring;
{
return _getopt_internal (argc, argv, optstring,
- (const struct option *) 0,
- (int *) 0,
- 0);
+ (const struct option *) 0,
+ (int *) 0,
+ 0);
}
#endif
-#endif /* Not ELIDE_CODE. */
+#endif /* Not ELIDE_CODE. */
\f
#ifdef TEST
c = getopt (argc, argv, "abc:d:0123456789");
if (c == -1)
- break;
+ break;
switch (c)
- {
- case '0':
- case '1':
- case '2':
- case '3':
- case '4':
- case '5':
- case '6':
- case '7':
- case '8':
- case '9':
- if (digit_optind != 0 && digit_optind != this_option_optind)
- printf ("digits occur in two different argv-elements.\n");
- digit_optind = this_option_optind;
- printf ("option %c\n", c);
- break;
-
- case 'a':
- printf ("option a\n");
- break;
-
- case 'b':
- printf ("option b\n");
- break;
-
- case 'c':
- printf ("option c with value `%s'\n", optarg);
- break;
-
- case '?':
- break;
-
- default:
- printf ("?? getopt returned character code 0%o ??\n", c);
- }
+ {
+ case '0':
+ case '1':
+ case '2':
+ case '3':
+ case '4':
+ case '5':
+ case '6':
+ case '7':
+ case '8':
+ case '9':
+ if (digit_optind != 0 && digit_optind != this_option_optind)
+ printf ("digits occur in two different argv-elements.\n");
+ digit_optind = this_option_optind;
+ printf ("option %c\n", c);
+ break;
+
+ case 'a':
+ printf ("option a\n");
+ break;
+
+ case 'b':
+ printf ("option b\n");
+ break;
+
+ case 'c':
+ printf ("option c with value `%s'\n", optarg);
+ break;
+
+ case '?':
+ break;
+
+ default:
+ printf ("?? getopt returned character code 0%o ??\n", c);
+ }
}
if (optind < argc)
{
printf ("non-option ARGV-elements: ");
while (optind < argc)
- printf ("%s ", argv[optind++]);
+ printf ("%s ", argv[optind++]);
printf ("\n");
}
# define _GETOPT_H 1
#endif
-#ifdef __cplusplus
+#ifdef __cplusplus
extern "C" {
#endif
zero.
The field `has_arg' is:
- no_argument (or 0) if the option does not take an argument,
- required_argument (or 1) if the option requires an argument,
- optional_argument (or 2) if the option takes an optional argument.
+ no_argument (or 0) if the option does not take an argument,
+ required_argument (or 1) if the option requires an argument,
+ optional_argument (or 2) if the option takes an optional argument.
If the field `flag' is not NULL, it points to a variable that is set
to the value given in the field `val' when the option is found, but
/* Names for the values of the `has_arg' field of `struct option'. */
-# define no_argument 0
-# define required_argument 1
-# define optional_argument 2
-#endif /* need getopt */
+# define no_argument 0
+# define required_argument 1
+# define optional_argument 2
+#endif /* need getopt */
/* Get definitions and prototypes for functions to process the
arguments to the option '\0'. This behavior is specific to the GNU
`getopt'. */
-#if defined __STDC__
+#if defined __STDC__
# ifdef __GNU_LIBRARY__
/* Many other libraries have conflicting prototypes for getopt, with
differences in the consts, in stdlib.h. To avoid compilation
# ifndef __need_getopt
extern int getopt_long (int argc, char *const *argv, const char *shortopts,
- const struct option *longopts, int *longind);
+ const struct option *longopts, int *longind);
extern int getopt_long_only (int __argc, char *const *__argv,
- const char *__shortopts,
- const struct option *__longopts, int *__longind);
+ const char *__shortopts,
+ const struct option *__longopts, int *__longind);
/* Internal only. Users should not call this directly. */
extern int _getopt_internal (int __argc, char *const *__argv,
- const char *__shortopts,
- const struct option *__longopts, int *__longind,
- int __long_only);
+ const char *__shortopts,
+ const struct option *__longopts, int *__longind,
+ int __long_only);
# endif
#else /* not __STDC__ */
extern int getopt ();
# ifndef __need_getopt
extern int getopt_long (int argc, char *const *argv, const char *shortopts,
- const struct option *longopts, int *longind);
+ const struct option *longopts, int *longind);
extern int getopt_long_only (int __argc, char *const *__argv,
- const char *__shortopts,
- const struct option *__longopts, int *__longind);
+ const char *__shortopts,
+ const struct option *__longopts, int *__longind);
extern int _getopt_internal (int __argc, char *const *__argv,
- const char *__shortopts,
- const struct option *__longopts, int *__longind,
- int __long_only);
+ const char *__shortopts,
+ const struct option *__longopts, int *__longind,
+ int __long_only);
# endif
#endif /* __STDC__ */
-#ifdef __cplusplus
+#ifdef __cplusplus
}
#endif
#include <stdlib.h>
#endif
-#ifndef NULL
+#ifndef NULL
#define NULL 0
#endif
}
-#endif /* Not ELIDE_CODE. */
+#endif /* Not ELIDE_CODE. */
\f
#ifdef TEST
int option_index = 0;
static struct option long_options[] =
{
- {"add", 1, 0, 0},
- {"append", 0, 0, 0},
- {"delete", 1, 0, 0},
- {"verbose", 0, 0, 0},
- {"create", 0, 0, 0},
- {"file", 1, 0, 0},
- {0, 0, 0, 0}
+ {"add", 1, 0, 0},
+ {"append", 0, 0, 0},
+ {"delete", 1, 0, 0},
+ {"verbose", 0, 0, 0},
+ {"create", 0, 0, 0},
+ {"file", 1, 0, 0},
+ {0, 0, 0, 0}
};
c = getopt_long (argc, argv, "abc:d:0123456789",
- long_options, &option_index);
+ long_options, &option_index);
if (c == -1)
- break;
+ break;
switch (c)
- {
- case 0:
- printf ("option %s", long_options[option_index].name);
- if (optarg)
- printf (" with arg %s", optarg);
- printf ("\n");
- break;
-
- case '0':
- case '1':
- case '2':
- case '3':
- case '4':
- case '5':
- case '6':
- case '7':
- case '8':
- case '9':
- if (digit_optind != 0 && digit_optind != this_option_optind)
- printf ("digits occur in two different argv-elements.\n");
- digit_optind = this_option_optind;
- printf ("option %c\n", c);
- break;
-
- case 'a':
- printf ("option a\n");
- break;
-
- case 'b':
- printf ("option b\n");
- break;
-
- case 'c':
- printf ("option c with value `%s'\n", optarg);
- break;
-
- case 'd':
- printf ("option d with value `%s'\n", optarg);
- break;
-
- case '?':
- break;
-
- default:
- printf ("?? getopt returned character code 0%o ??\n", c);
- }
+ {
+ case 0:
+ printf ("option %s", long_options[option_index].name);
+ if (optarg)
+ printf (" with arg %s", optarg);
+ printf ("\n");
+ break;
+
+ case '0':
+ case '1':
+ case '2':
+ case '3':
+ case '4':
+ case '5':
+ case '6':
+ case '7':
+ case '8':
+ case '9':
+ if (digit_optind != 0 && digit_optind != this_option_optind)
+ printf ("digits occur in two different argv-elements.\n");
+ digit_optind = this_option_optind;
+ printf ("option %c\n", c);
+ break;
+
+ case 'a':
+ printf ("option a\n");
+ break;
+
+ case 'b':
+ printf ("option b\n");
+ break;
+
+ case 'c':
+ printf ("option c with value `%s'\n", optarg);
+ break;
+
+ case 'd':
+ printf ("option d with value `%s'\n", optarg);
+ break;
+
+ case '?':
+ break;
+
+ default:
+ printf ("?? getopt returned character code 0%o ??\n", c);
+ }
}
if (optind < argc)
{
printf ("non-option ARGV-elements: ");
while (optind < argc)
- printf ("%s ", argv[optind++]);
+ printf ("%s ", argv[optind++]);
printf ("\n");
}
int
main(int argc, char *argv[])
{
- int view, nview;
- char filename[128];
-
- float mu1=0. , mu2=6., density, afac, s;
+ int view, nview;
+ char filename[128];
- FILE *fp = (FILE *)NULL;
- if (argc !=4){
- fprintf(stderr, "Usage: %s iview nview phmfilename\n", argv[0]);
- exit (1);
- }
+ float mu1=0. , mu2=6., density, afac, s;
- view = atoi(argv[1]);
- nview = atoi(argv[2]);
- sprintf(filename, "%s", argv[3]);
+ FILE *fp = (FILE *)NULL;
+ if (argc !=4){
+ fprintf(stderr, "Usage: %s iview nview phmfilename\n", argv[0]);
+ exit (1);
+ }
- s = (float)view/((float)(nview-1));
-
- if ( s < 7./16. )
- density = mu1;
+ view = atoi(argv[1]);
+ nview = atoi(argv[2]);
+ sprintf(filename, "%s", argv[3]);
+
+ s = (float)view/((float)(nview-1));
+
+ if ( s < 7./16. )
+ density = mu1;
else if ( s > 9./16. )
- density = mu2;
+ density = mu2;
else {
- afac = ( (s - 7./16.) / 2./16.);
- density = log(1/((1-afac)*exp(-mu1) + afac * exp(-mu2)));
- }
-
-/*
- density = mu1 + (mu2-mu1)*s;
- if (s <=0.5)
- density = mu1;
- else
- density = mu2;
+ afac = ( (s - 7./16.) / 2./16.);
+ density = log(1/((1-afac)*exp(-mu1) + afac * exp(-mu2)));
+ }
+
+/*
+ density = mu1 + (mu2-mu1)*s;
+ if (s <=0.5)
+ density = mu1;
+ else
+ density = mu2;
*/
- if ( (fp = fopen(filename, "w")) == (FILE *)NULL){
- fprintf(stderr,"Error, can not open file \"tmpphmfile\"\n");
- exit(2);
- }
- fprintf(fp, "rectangle 0 0 11.5 11.5 0 0\n");
- fprintf(fp, "ellipse 0 0 11.4 11.4 0 1\n");
- fprintf(fp, "ellipse 0 0 1.25 1.25 0 %f\n", density);
+ if ( (fp = fopen(filename, "w")) == (FILE *)NULL){
+ fprintf(stderr,"Error, can not open file \"tmpphmfile\"\n");
+ exit(2);
+ }
+ fprintf(fp, "rectangle 0 0 11.5 11.5 0 0\n");
+ fprintf(fp, "ellipse 0 0 11.4 11.4 0 1\n");
+ fprintf(fp, "ellipse 0 0 1.25 1.25 0 %f\n", density);
- fclose(fp);
- exit(0);
+ fclose(fp);
+ exit(0);
}
/*****************************************************************************
** FILE IDENTIFICATION
**
-** Name: array2d.h
+** Name: array2d.h
** Purpose: 2-dimension array classes
-** Programmer: Kevin Rosenberg
-** Date Started: June 2000
+** Programmer: Kevin Rosenberg
+** Date Started: June 2000
**
** This is part of the CTSim program
** Copyright (c) 1983-2001 Kevin Rosenberg
#include "ctsupport.h"
-template<class T>
+template<class T>
class Array2d {
public:
Array2d (unsigned int x, unsigned int y)
- : m_nx(x), m_ny(y), array_data(0)
- {
- allocArray();
- }
+ : m_nx(x), m_ny(y), array_data(0)
+ {
+ allocArray();
+ }
Array2d ()
- : m_nx(0), m_ny(0), array_data(0)
- {}
+ : m_nx(0), m_ny(0), array_data(0)
+ {}
~Array2d ()
- {
- deleteArray();
- }
-
+ {
+ deleteArray();
+ }
+
void initSetSize (unsigned int x, unsigned int y)
- {
- m_nx = x;
- m_ny = y;
- deleteArray();
- allocArray();
- }
+ {
+ m_nx = x;
+ m_ny = y;
+ deleteArray();
+ allocArray();
+ }
T** getArray () const
- { return array_data; }
+ { return array_data; }
T* getColumn (unsigned int x) const
- { return (array_data ? array_data[x] : NULL); }
+ { return (array_data ? array_data[x] : NULL); }
T getPoint (unsigned int x, unsigned int y) const
- { return (array_data ? array_data[x][y] : NULL); }
+ { return (array_data ? array_data[x][y] : NULL); }
- unsigned int sizeofPixel () const
- { return sizeof(T); }
+ unsigned int sizeofPixel () const
+ { return sizeof(T); }
unsigned int sizeofColumn () const
- { return (sizeof(T) * m_ny); }
+ { return (sizeof(T) * m_ny); }
unsigned int sizeofArray () const
- { return (sizeof(T) * m_nx * m_ny); }
+ { return (sizeof(T) * m_nx * m_ny); }
private:
T** array_data;
void allocArray ()
- {
- if (array_data)
- deleteArray();
+ {
+ if (array_data)
+ deleteArray();
+
+ array_data = new T*[m_nx];
- array_data = new T*[m_nx];
-
- for (unsigned int i = 0; i < m_nx; i++)
- array_data[i] = new T[m_ny];
- }
+ for (unsigned int i = 0; i < m_nx; i++)
+ array_data[i] = new T[m_ny];
+ }
void deleteArray ()
- {
- if (array_data) {
- for (unsigned int i = 0; i < m_nx; i++)
- delete array_data [i];
- delete array_data;
- array_data = NULL;
- }
- }
+ {
+ if (array_data) {
+ for (unsigned int i = 0; i < m_nx; i++)
+ delete array_data [i];
+ delete array_data;
+ array_data = NULL;
+ }
+ }
Array2d& operator= (const Array2d& rhs); //assignment operator
/*****************************************************************************
** FILE IDENTIFICATION
**
-** Name: array2dfile.h
+** Name: array2dfile.h
** Purpose: 2-dimension array file class
-** Programmer: Kevin Rosenberg
-** Date Started: June 2000
+** Programmer: Kevin Rosenberg
+** Date Started: June 2000
**
** This is part of the CTSim program
** Copyright (c) 1983-2001 Kevin Rosenberg
L_HISTORY = 1,
L_USER = 2,
};
-
- Array2dFileLabel();
-
+
+ Array2dFileLabel();
+
Array2dFileLabel(const char* const str, double ctime = 0.);
-
+
Array2dFileLabel(const int type, const char* const str, double ctime = 0.);
-
+
~Array2dFileLabel();
-
+
const std::string& getLabelString (void) const
{ return m_strLabel; }
-
+
kfloat64 getCalcTime (void) const
{ return m_calcTime; }
-
+
void setCalcTime (kfloat64 calcTime)
{ m_calcTime = calcTime; }
-
+
void setLabelType (int labelType)
{ m_labelType = labelType; }
-
+
int getLabelType (void) const
{ return m_labelType; }
-
+
std::string& setLabelString (const char* const str)
{ m_strLabel = str; return (m_strLabel); }
-
+
std::string& setLabelString (const std::string& str)
{ m_strLabel = str; return (m_strLabel); }
-
+
void setDateTime (int year, int month, int day, int hour, int minute, int second);
-
+
void getDateTime (int& year, int& month, int& day, int& hour, int& minute, int& second) const;
-
+
const std::string& getDateString () const;
-
+
void print (std::ostream& os) const;
void printBrief (std::ostream& os) const;
void printBrief (std::ostringstream& os) const;
-
+
Array2dFileLabel (const Array2dFileLabel& rhs);
-
+
Array2dFileLabel& operator= (const Array2dFileLabel& rhs);
-
+
private:
void init (void);
-
+
kuint16 m_labelType;
kuint16 m_year;
kuint16 m_month;
kuint16 m_second;
std::string m_strLabel;
kfloat64 m_calcTime;
-
+
mutable std::string m_strDate;
};
-class Array2dFile
+class Array2dFile
{
public:
enum {
PIXEL_FLOAT32 = 7,
PIXEL_FLOAT64 = 8,
};
-
+
enum {
DATA_TYPE_INVALID = 0,
DATA_TYPE_REAL,
DATA_TYPE_COMPLEX,
};
-
+
Array2dFile (int nx, int ny, int pixelSize, int pixelFormat = PIXEL_INVALID, int dataType = DATA_TYPE_REAL);
Array2dFile (void);
~Array2dFile ();
-
+
void setArraySize (int nx, int ny, int pixelSize, int pixelFormat = PIXEL_INVALID, int dataType = DATA_TYPE_REAL);
-
+
void setArraySize (int nx, int ny);
-
+
unsigned int getNumLabels (void) const
{ return m_labels.size(); }
-
+
const Array2dFileLabel& labelGet (int label_num) const;
-
+
void labelAdd (const Array2dFileLabel& label);
-
+
void labelAdd (const char* const m_strLabel, double calc_time=0.);
-
+
void labelAdd (int type, const char* const m_strLabel, double calc_time=0.);
-
+
void labelsCopy (const Array2dFile& file, const char* const idStr = NULL);
-
+
void setPixelFormat (int type)
{ m_pixelFormat = type; }
-
+
void setPixelSize (int size)
{ m_pixelSize = size; }
-
+
kuint32 nx (void) const
{ return m_nx; }
-
+
kuint32 ny (void) const
{ return m_ny; }
-
+
bool isComplex() const
{ return m_dataType == DATA_TYPE_COMPLEX; }
-
+
bool isReal() const
{ return m_dataType == DATA_TYPE_REAL; }
-
+
int dataType () const
{ return static_cast<int>(m_dataType); }
-
+
void setDataType (int dataType)
{ m_dataType = dataType; }
-
+
void setAxisIncrement (double axisIncX, double axisIncY);
-
+
bool reallocRealToComplex ();
-
+
bool reallocComplexToReal ();
-
+
void getPixelValueRange (double& pvmin, double& pvmax) const;
void setAxisExtent (double minX, double maxX, double minY, double maxY);
bool getAxisExtent (double& minX, double& maxX, double& minY, double& maxY) const
kfloat64 axisIncrementY() const {return m_axisIncrementKnown ? m_axisIncrementY : 0.;}
void arrayDataClear (void);
-
+
bool fileRead (const char* const filename);
-
+
bool fileRead (const std::string& filename);
-
+
bool fileWrite (const char* const filename);
-
+
bool fileWrite (const std::string& filename);
-
- const std::string& getFilename (void) const
+
+ const std::string& getFilename (void) const
{ return m_filename; }
-
+
void printLabels (std::ostream& os) const;
void printLabelsBrief (std::ostream& os) const;
void printLabelsBrief (std::ostringstream& os) const;
-
+
unsigned int nLabels() const
{ return m_labels.size(); }
-
+
typedef std::vector<Array2dFileLabel*>::iterator labelIterator;
typedef std::vector<Array2dFileLabel*>::const_iterator constLabelIterator;
-
+
protected:
- typedef std::vector<Array2dFileLabel*> labelContainer;
-
+ typedef std::vector<Array2dFileLabel*> labelContainer;
+
static const kuint16 m_signature;
kuint16 m_headersize;
std::string m_filename;
-
+
kuint16 m_pixelSize;
kuint16 m_pixelFormat;
kuint16 m_axisIncrementKnown;
kuint16 m_dataType;
unsigned char** m_arrayData;
unsigned char** m_imaginaryArrayData;
-
+
private:
void init (void);
-
+
bool headerRead (frnetorderstream& fs);
-
+
bool headerWrite (frnetorderstream& fs);
-
+
bool arrayDataRead (frnetorderstream& fs);
-
+
bool arrayDataWrite (frnetorderstream& fs);
-
+
bool labelsRead (frnetorderstream& fs);
-
+
bool labelsWrite (frnetorderstream& fs);
-
+
bool labelSeek (int label_num);
-
+
void allocArrays ();
void freeArrays ();
-
+
void allocArray (unsigned char**& rppData);
void freeArray (unsigned char**& rppData);
-
+
Array2dFile (const Array2dFile& rhs); // copy constructor
Array2dFile& operator= (const Array2dFile&); // assignment operator
-
+
};
/*****************************************************************************
** FILE IDENTIFICATION
**
-** Name: backproject.h
+** Name: backproject.h
** Purpose: Backprojection classes
-** Programmer: Kevin Rosenberg
-** Date Started: June 2000
+** Programmer: Kevin Rosenberg
+** Date Started: June 2000
**
** This is part of the CTSim program
** Copyright (c) 1983-2001 Kevin Rosenberg
static const int INTERP_3BSPLINE;
#endif
- Backprojector (const Projections& proj, ImageFile& im, const char* const backprojName,
+ Backprojector (const Projections& proj, ImageFile& im, const char* const backprojName,
const char* const interpName, const int interpFactor, const ReconstructionROI* pROI);
~Backprojector ();
-
+
void BackprojectView (const double* const viewData, const double viewAngle);
void PostProcessing();
class Backproject
{
public:
- Backproject (const Projections& proj, ImageFile& im, int interpID, const int interpFactor,
+ Backproject (const Projections& proj, ImageFile& im, int interpID, const int interpFactor,
const ReconstructionROI* pROI);
virtual ~Backproject ();
kint32 ny;
double detInc;
double rotScale;
- int iDetCenter; // index refering to L=0 projection
+ int iDetCenter; // index refering to L=0 projection
int nDet;
double xMin, xMax, yMin, yMax; // Retangular coords of phantom
- double xInc, yInc; // size of cells
+ double xInc, yInc; // size of cells
int m_interpFactor;
double m_dFocalLength;
double m_dSourceDetectorLength;
BackprojectIntDiff (const Projections& proj, ImageFile& im, int interpID, const int interpFactor, const ReconstructionROI* pROI)
: BackprojectDiff (proj, im, interpID, interpFactor, pROI)
{}
-
+
void BackprojectView (const double* const t, const double view_angle);
};
#include "png.h"
#endif
#ifdef HAVE_G2_H
-extern "C" {
-#include "g2.h"
+extern "C" {
+#include "g2.h"
}
#ifdef HAVE_X11
extern "C" {
/*****************************************************************************
** FILE IDENTIFICATION
**
-** Name: ctglobals.h
+** Name: ctglobals.h
** Purpose: Global variables for CTSim
-** Programmer: Kevin Rosenberg
-** Date Started: Jan 20001
+** Programmer: Kevin Rosenberg
+** Date Started: Jan 20001
**
** This is part of the CTSim program
** Copyright (c) 1983-2001 Kevin Rosenberg
/*****************************************************************************
** FILE IDENTIFICATION
**
-** Name: ctndicomp.cpp
+** Name: ctndicomp.cpp
** Purpose: Interface to CTN Dicom header
-** Programmer: Kevin Rosenberg
-** Date Started: March 2001
+** Programmer: Kevin Rosenberg
+** Date Started: March 2001
**
** This is part of the CTSim program
** Copyright (c) 1983-2001 Kevin Rosenberg
Projections* m_pProjections;
DCM_OBJECT* m_pFile;
- void loadImage(unsigned short iNRows, unsigned short iNCols, unsigned short iBitsAllocated,
+ void loadImage(unsigned short iNRows, unsigned short iNCols, unsigned short iBitsAllocated,
unsigned short iBitsStored, unsigned short iHighBit, unsigned short iPixRep);
void loadProjections();
/*****************************************************************************
** FILE IDENTIFICATION
**
-** File Name: ctsupport.h
-** Author: Kevin Rosenberg
-** Purpose: Header file for CT support library
-** Date Started: Dec. 83
+** File Name: ctsupport.h
+** Author: Kevin Rosenberg
+** Purpose: Header file for CT support library
+** Date Started: Dec. 83
**
** This is part of the CTSim program
** Copyright (c) 1983-2001 Kevin Rosenberg
#endif
#ifndef TRUE
-#define TRUE 1
+#define TRUE 1
#endif
#ifndef FALSE
-#define FALSE 0
+#define FALSE 0
#endif
-#define OK TRUE
+#define OK TRUE
/*----------------------------------------------------------------------*/
/*----------------------------------------------------------------------*/
-#define NEWLINE '\n'
-#define TAB '\t'
-#define EOS '\0'
-#define BLANK ' '
+#define NEWLINE '\n'
+#define TAB '\t'
+#define EOS '\0'
+#define BLANK ' '
/*----------------------------------------------------------------------*/
#define ERR_TRACE -1
-#define ERR_WARNING 0
-#define ERR_SEVERE 1
-#define ERR_FATAL 2
+#define ERR_WARNING 0
+#define ERR_SEVERE 1
+#define ERR_FATAL 2
/*----------------------------------------------------------------------*/
/* codes for open command */
#ifdef MSVC
-#define OPEN_RDONLY O_RDONLY /* other system use standard codes */
-#define OPEN_WRONLY O_WRONLY /* for binary */
+#define OPEN_RDONLY O_RDONLY /* other system use standard codes */
+#define OPEN_WRONLY O_WRONLY /* for binary */
#define OPEN_RDWR O_RDWR
#else
-#define OPEN_RDONLY 0 /* other system use standard codes */
-#define OPEN_WRONLY 1 /* for binary */
+#define OPEN_RDONLY 0 /* other system use standard codes */
+#define OPEN_WRONLY 1 /* for binary */
#define OPEN_RDWR 2
#endif
#endif
-inline const char*
+inline const char*
fileBasename (const char* const filename)
{
const char* p = strrchr (filename, '/');
#include <cmath>
#define PI 3.14159265358979323846
-#define HALFPI 1.57079632679489661923 /* PI divided by 2 */
-#define QUARTPI 0.78539816339744830962 /* PI divided by 4 */
-#define I_PI 0.31830988618379067154 /* Inverse of PI */
-#define I_PID2 0.63661977236758134308 /* Inverse of PID2 */
-
-#define TWOPI 6.28318530717958647692
+#define HALFPI 1.57079632679489661923 /* PI divided by 2 */
+#define QUARTPI 0.78539816339744830962 /* PI divided by 4 */
+#define I_PI 0.31830988618379067154 /* Inverse of PI */
+#define I_PID2 0.63661977236758134308 /* Inverse of PID2 */
+
+#define TWOPI 6.28318530717958647692
#define SQRT2 1.414213562373095049
-#define F_EPSILON 1.0E-6
-#define D_EPSILON 1.0E-10
+#define F_EPSILON 1.0E-6
+#define D_EPSILON 1.0E-10
#define ASSUMEDZERO 1E-10
typedef double GRFMTX_2D[3][3];
typedef double GRFMTX_3D[4][4];
-inline double
+inline double
convertDegreesToRadians (double x)
{ return (x * (PI/180.)); }
// FUNTION DECLARATIONS
//////////////////////////////////////////////////////////////
-// clip.cpp
+// clip.cpp
bool clip_rect (double& x1, double& y1, double& x2, double& y2, const double rect[4]);
bool clip_segment (double& x1, double& y1, double& x2, double& y2, const double u, const double v);
bool clip_sector (double& x1, double& y1, double& x2, double& y2, const double u, const double v);
bool clip_triangle (double& x1, double& y1, double& x2, double& y2, const double u, const double v, const int clip_xaxis);
-// xform.cpp
+// xform.cpp
void indent_mtx2 (GRFMTX_2D m);
void xlat_mtx2 (GRFMTX_2D m, const double x, const double y);
void scale_mtx2 (GRFMTX_2D m, const double sx, const double sy);
/* screen character codes */
-#define SC_BKSP 8
-#define SC_TAB 9
-#define SC_BLANK ' '
+#define SC_BKSP 8
+#define SC_TAB 9
+#define SC_BLANK ' '
/* audio.cpp */
// Keyboard Section
-#define KEY_BKSP 8
-#define KEY_TAB 9
-#define KEY_RETURN 13
-#define KEY_ESCAPE 27
+#define KEY_BKSP 8
+#define KEY_TAB 9
+#define KEY_RETURN 13
+#define KEY_ESCAPE 27
// ASCII Section
#define BACKSPACE 8
-// #define LF 0x0A
-// #define CR 0x0D
-#define BELL 0x07
+// #define LF 0x0A
+// #define CR 0x0D
+#define BELL 0x07
#define SQUOTE '\''
#define DQUOTE '\"'
#define SHARP '#'
#define SLASH '/'
#define ASTERICK '*'
-#define COLON ':'
+#define COLON ':'
#define LBRACE '{'
#define RBRACE '}'
-#define LPAREN '('
+#define LPAREN '('
#define RPAREN ')'
-#define LBRACK '['
-#define RBRACK ']'
+#define LBRACK '['
+#define RBRACK ']'
#define LANBRACK '<'
#define RANBRACK '>'
#define SEMICOL ';'
#define UNDERLIN '_'
-#define COMMA ','
-#define CARET '^'
-#define TILDE '~'
-#define ATSIGN '@'
+#define COMMA ','
+#define CARET '^'
+#define TILDE '~'
+#define ATSIGN '@'
#define AMPERSAND '&'
-#define EXCLAM '!'
-#define DOLLAR '$'
+#define EXCLAM '!'
+#define DOLLAR '$'
#define PERCENT '%'
-#define PLUS '+'
-#define HYPHEN '-'
-#define EQUALS '='
+#define PLUS '+'
+#define HYPHEN '-'
+#define EQUALS '='
#define QUESTION '?'
-#define PERIOD '.'
+#define PERIOD '.'
#define VERTBAR '|'
-#endif /* #ifndef CTSUPPORT_H */
+#endif /* #ifndef CTSUPPORT_H */
double *x;
double *y;
int m_iPointCount;
-
+
EZPlotCurve (const double* x, const double* y, int n);
-
+
~EZPlotCurve();
};
//----------------------------------------------------------------------
-// GLOBAL VARIABLES
+// GLOBAL VARIABLES
//----------------------------------------------------------------------
-// axis definitions
+// axis definitions
enum {
- LINEAR = 1, // linear axis
- LOG, // logrithmic axis
- NOAXIS, // don't plot axis
+ LINEAR = 1, // linear axis
+ LOG, // logrithmic axis
+ NOAXIS, // don't plot axis
};
-// tick definitions
+// tick definitions
enum {
ABOVE = 1,
BELOW,
LEFT,
};
-// line types
+// line types
enum {
- NOLINE = 0,
+ NOLINE = 0,
SOLID,
DASH,
DASH1,
DASH4,
};
-// symbol definitions
+// symbol definitions
enum {
SB_CROSS = 1,
SB_PLUS,
};
enum {
- INSIDE = 1, // values of o_legendbox
+ INSIDE = 1, // values of o_legendbox
OUTSIDE,
NOLEGEND,
};
};
/*-----------------------------------------------------------------------------
-* GLOBAL VARIABLES
+* GLOBAL VARIABLES
*
* Naming Convention:
-* i_ Internal variable
-* Not user changable
-* o_ Option variable
-* Normal variable that is user modifiable
-* These variables must always have a valid value
-* d_ Device variable
-* Variables controlling devices
+* i_ Internal variable
+* Not user changable
+* o_ Option variable
+* Normal variable that is user modifiable
+* These variables must always have a valid value
+* d_ Device variable
+* Variables controlling devices
* clr_ Color variable
-* Holds a color value
-* c_ Character string variable
-* Contains a character string
-* v_ Value variable
-* User modifiable variable associated with the set variable (s_)
-* These variables do not always have a valid value
-* These variables change assumption EZPLOT makes about the plot
-* s_ Set variable.
-* TRUE if associated value variable (v_) has been set by the user
+* Holds a color value
+* c_ Character string variable
+* Contains a character string
+* v_ Value variable
+* User modifiable variable associated with the set variable (s_)
+* These variables do not always have a valid value
+* These variables change assumption EZPLOT makes about the plot
+* s_ Set variable.
+* TRUE if associated value variable (v_) has been set by the user
*---------------------------------------------------------------------------*/
#include <vector>
class EZPlot {
private:
//----------------------------------------------------------------------
- // POL Codes
+ // POL Codes
//----------------------------------------------------------------------
-
+
enum {
S_DATA = 2,
S_HELP,
S_EXIT,
S_CURVE,
S_SOLID,
- S_DASH,
+ S_DASH,
S_NOLINE,
S_BLACK,
S_RED,
S_TAG,
S_TEXTSIZE,
};
-
+
static const struct KeywordCodeTable m_sKeywords[];
static const int NKEYS;
-
+
std::vector<class EZPlotCurve*> m_vecCurves;
std::vector<int> m_veciColor;
std::vector<bool> m_vecbColorSet;
int m_iCurrentCurve;
// Colors
- int clr_axis; // color of all axis lines
- int clr_title; // color of main title
- int clr_label; // color of axis labels
- int clr_legend; // color of legend box
- int clr_grid; // color of grid lines
- int clr_number; // color of axis number labels
-
+ int clr_axis; // color of all axis lines
+ int clr_title; // color of main title
+ int clr_label; // color of axis labels
+ int clr_legend; // color of legend box
+ int clr_grid; // color of grid lines
+ int clr_number; // color of axis number labels
+
// Options
- double o_xporigin, o_yporigin; // origin of plot frame in NDC
- double o_xlength, o_ylength; // length of plot frame in NDC
-
- std::string c_xlabel; // label for x axis
- std::string c_ylabel; // label for y axis
- std::string c_title; // title to print above graph
-
- int o_linestyle, o_color; // style to use for curves all subsequent curves to EZPLOT
- int o_xaxis, o_yaxis; // Specifies where axis & labels are drawn
- bool o_grid; // Flag to draw a grid at major ticks
- bool o_box; // Flag to draw a box around the graph
-
- int o_xticks, o_yticks; // direction to draw tick marks
- bool o_xtlabel, o_ytlabel; // TRUE if label tick marks
-
- int o_xmajortick, o_ymajortick; // number of major ticks to draw
- int o_xminortick, o_yminortick; // number of minor ticks between major ticks
-
- int o_symbol; // Symbol type, (0 = no symbol)
- int o_symfreq; // frequency to draw symbols at curve points
-
- int o_legendbox; // controls whether legend is inside or outside of the axis extents
- int o_tag; // controls whether to draw tag at end of axes
-
- // VALUE & SET variables
- double v_xmin, v_xmax, v_ymin, v_ymax; // user supplied axis endpoints
- bool s_xmin, s_xmax, s_ymin, s_ymax; // TRUE is endpoint has been set
- double v_xtitle, v_ytitle; // NDC position to plot title
- bool s_xtitle, s_ytitle; // TRUE if set position for title
- double v_xcross, v_ycross; // position that axes cross
- bool s_xcross, s_ycross; // TRUE if set axes cross position
- double v_xlegend, v_ylegend; // upper-left position of legend box in NDC
- bool s_xlegend, s_ylegend; // TRUE if set position of legend box
- int v_lxfrac, v_lyfrac; // number of digits to right of decimal place
- bool s_lxfrac, s_lyfrac; // TRUE if set number of fractional digits
- double v_textsize; // size of text in NDC
- bool s_textsize; // TRUE if user set size of text
-
+ double o_xporigin, o_yporigin; // origin of plot frame in NDC
+ double o_xlength, o_ylength; // length of plot frame in NDC
+
+ std::string c_xlabel; // label for x axis
+ std::string c_ylabel; // label for y axis
+ std::string c_title; // title to print above graph
+
+ int o_linestyle, o_color; // style to use for curves all subsequent curves to EZPLOT
+ int o_xaxis, o_yaxis; // Specifies where axis & labels are drawn
+ bool o_grid; // Flag to draw a grid at major ticks
+ bool o_box; // Flag to draw a box around the graph
+
+ int o_xticks, o_yticks; // direction to draw tick marks
+ bool o_xtlabel, o_ytlabel; // TRUE if label tick marks
+
+ int o_xmajortick, o_ymajortick; // number of major ticks to draw
+ int o_xminortick, o_yminortick; // number of minor ticks between major ticks
+
+ int o_symbol; // Symbol type, (0 = no symbol)
+ int o_symfreq; // frequency to draw symbols at curve points
+
+ int o_legendbox; // controls whether legend is inside or outside of the axis extents
+ int o_tag; // controls whether to draw tag at end of axes
+
+ // VALUE & SET variables
+ double v_xmin, v_xmax, v_ymin, v_ymax; // user supplied axis endpoints
+ bool s_xmin, s_xmax, s_ymin, s_ymax; // TRUE is endpoint has been set
+ double v_xtitle, v_ytitle; // NDC position to plot title
+ bool s_xtitle, s_ytitle; // TRUE if set position for title
+ double v_xcross, v_ycross; // position that axes cross
+ bool s_xcross, s_ycross; // TRUE if set axes cross position
+ double v_xlegend, v_ylegend; // upper-left position of legend box in NDC
+ bool s_xlegend, s_ylegend; // TRUE if set position of legend box
+ int v_lxfrac, v_lyfrac; // number of digits to right of decimal place
+ bool s_lxfrac, s_lyfrac; // TRUE if set number of fractional digits
+ double v_textsize; // size of text in NDC
+ bool s_textsize; // TRUE if user set size of text
+
// Global variables
- double charheight; // Height of characters in NDC
- double charwidth; // Height of characters in NDC
- double xp_min, xp_max, yp_min, yp_max; // boundry of plot frame in NDC
- double xa_min, xa_max, ya_min, ya_max; // extent of axes in NDC
- double xgw_min, xgw_max, ygw_min, ygw_max; // boundary of graph in input coords
- double xgn_min, xgn_max, ygn_min, ygn_max; // boundy of graph in NDC
- double xt_min, xt_max, yt_min, yt_max; // boundary of axis ticks
- double xl_min, xl_max, yl_min, yl_max; // boundary of legend box
- double title_row; // y-coord of title row
- double xtl_ofs; // Offset y-coord of x tick labels from axis
- double ytl_ofs; // Offset x-coord of y tick labels from axis
- double xlbl_row; // row of x label in world coord
- double ylbl_col; // column of y label in world coord
- double xw_tickinc, yw_tickinc; // increment between major ticks in WC
- double xn_tickinc, yn_tickinc; // increment between major ticks in NDC
- int x_nint, y_nint; // number of intervals along x & y axes
- int x_fldwid, x_frac; // numeric field sizes & number of digits
- int y_fldwid, y_frac; // in fraction of number, used for printf()
- double xtl_wid, ytl_wid; // length of ticks labels in NDC
- double tl_height; // height of tick labels in NDC
- char x_numfmt[20]; // format to print x tick labels
- char y_numfmt[20]; // format to print y tick labels
-
+ double charheight; // Height of characters in NDC
+ double charwidth; // Height of characters in NDC
+ double xp_min, xp_max, yp_min, yp_max; // boundry of plot frame in NDC
+ double xa_min, xa_max, ya_min, ya_max; // extent of axes in NDC
+ double xgw_min, xgw_max, ygw_min, ygw_max; // boundary of graph in input coords
+ double xgn_min, xgn_max, ygn_min, ygn_max; // boundy of graph in NDC
+ double xt_min, xt_max, yt_min, yt_max; // boundary of axis ticks
+ double xl_min, xl_max, yl_min, yl_max; // boundary of legend box
+ double title_row; // y-coord of title row
+ double xtl_ofs; // Offset y-coord of x tick labels from axis
+ double ytl_ofs; // Offset x-coord of y tick labels from axis
+ double xlbl_row; // row of x label in world coord
+ double ylbl_col; // column of y label in world coord
+ double xw_tickinc, yw_tickinc; // increment between major ticks in WC
+ double xn_tickinc, yn_tickinc; // increment between major ticks in NDC
+ int x_nint, y_nint; // number of intervals along x & y axes
+ int x_fldwid, x_frac; // numeric field sizes & number of digits
+ int y_fldwid, y_frac; // in fraction of number, used for printf()
+ double xtl_wid, ytl_wid; // length of ticks labels in NDC
+ double tl_height; // height of tick labels in NDC
+ char x_numfmt[20]; // format to print x tick labels
+ char y_numfmt[20]; // format to print y tick labels
+
double m_dVP_xmin, m_dVP_ymin;
double m_dVP_xmax, m_dVP_ymax;
double m_dVP_xscale, m_dVP_yscale;
double m_xWorldScale, m_yWorldScale;
-
+
void drawAxes();
void symbol (int sym, double symwidth, double symheight);
void make_numfmt(char *fmtstr, int *fldwid, int *nfrac, double min, double max, int nint);
int axis_scale (double min, double max, int nint, double *minp, double *maxp, int *nintp);
-
+
SGP* m_pSGP;
POL m_pol;
-
+
void clearCurves ();
-
+
bool ezcmd (const char* const comm);
bool do_cmd(int lx);
void bad_option(char *opt);
void initPlotSettings();
-
+
void initKeywords ();
-
+
double convertWorldToNDC_X (double x)
{ return xgn_min + (x - xgw_min) * m_xWorldScale; }
-
+
double convertWorldToNDC_Y (double y)
{ return ygn_min + (y - ygw_min) * m_yWorldScale; }
-
+
public:
EZPlot ();
~EZPlot ();
-
+
bool ezset (const std::string& command);
bool ezset (const char* const command);
-
+
void addCurve (const float* x, const double* y, int num);
void addCurve (const double* x, const float* y, int num);
void addCurve (const double* x, const double* y, int num);
void addCurve (const double* y, int n);
void addCurve (const float* y, int n);
-
+
void plot (SGP* pSGP);
-};
+};
#endif
/*****************************************************************************
** FILE IDENTIFICATION
**
-** Name: filter.h
+** Name: filter.h
** Purpose: Signal filter header file
-** Programmer: Kevin Rosenberg
-** Date Started: June 2000
+** Programmer: Kevin Rosenberg
+** Date Started: June 2000
**
** This is part of the CTSim program
** Copyright (c) 1983-2001 Kevin Rosenberg
class SignalFilter {
public:
static const int FILTER_INVALID;
- static const int FILTER_ABS_BANDLIMIT; // filter times |x|
+ static const int FILTER_ABS_BANDLIMIT; // filter times |x|
static const int FILTER_ABS_SINC;
static const int FILTER_ABS_G_HAMMING;
static const int FILTER_ABS_HANNING;
static const int DOMAIN_INVALID;
static const int DOMAIN_FREQUENCY;
static const int DOMAIN_SPATIAL;
-
+
SignalFilter (const char* szFilterName, double dFilterMinimum, double dFilterMaximum, int nFilterPoints, double dBandwidth, double dFilterParam, const char* szDomainName);
SignalFilter (const int idFilter, double dFilterMinimum, double dFilterMaximum, int nFilterPoints, double dBandwidth, double dFilterParam, const int idDomain);
double* getFilter (void) const
{ return m_adFilter; }
- bool fail(void) const {return m_fail;}
+ bool fail(void) const {return m_fail;}
const std::string& failMessage(void) const {return m_failMessage;}
- const std::string& nameFilter(void) const { return m_nameFilter;}
- const std::string& nameDomain(void) const { return m_nameDomain;}
- const int idFilter(void) const { return m_idFilter;}
- const int idDomain(void) const { return m_idDomain;}
+ const std::string& nameFilter(void) const { return m_nameFilter;}
+ const std::string& nameDomain(void) const { return m_nameDomain;}
+ const int idFilter(void) const { return m_idFilter;}
+ const int idDomain(void) const { return m_idDomain;}
int getNFilterPoints (void) const { return m_nFilterPoints; }
const double getFilterMin(void) const {return m_dFilterMin;}
class fnetorderstream : public fstream {
public:
fnetorderstream (const char* filename, std::ios::openmode mode)
- : fstream (filename, mode) {}
+ : fstream (filename, mode) {}
~fnetorderstream (void)
{}
virtual void writeInt32 (kuint32 n);
virtual void writeFloat32 (kfloat32 n);
virtual void writeFloat64 (kfloat64 n);
-
+
virtual void readInt16 (kuint16& n);
virtual void readInt32 (kuint32& n);
virtual void readFloat32 (kfloat32& n);
virtual void writeInt32 (kuint32 n);
virtual void writeFloat32 (kfloat32 n);
virtual void writeFloat64 (kfloat64 n);
-
+
virtual void readInt16 (kuint16& n);
virtual void readInt32 (kuint32& n);
virtual void readFloat32 (kfloat32& n);
static void shuffleFourierToNaturalOrder (fftw_complex* pc, const int n);
static void shuffleNaturalToFourierOrder (fftw_complex* pc, const int n);
#endif
-
+
// Odd Number of Points
// Natural Frequency Order: -(n-1)/2...-1,0,1...(n-1)/2
// Fourier Frequency Order: 0, 1..(n-1)/2,-(n-1)/2...-1
// Natural Frequency Order: -n/2...-1,0,1...((n/2)-1)
// Fourier Frequency Order: 0,1...((n/2)-1),-n/2...-1
template<class T>
- static void shuffleNaturalToFourierOrder (T* pVector, const int n)
+ static void shuffleNaturalToFourierOrder (T* pVector, const int n)
{
T* pTemp = new T [n];
int i;
int i;
if (isOdd(n)) { // Odd
int iHalfN = (n - 1) / 2;
-
+
pTemp[iHalfN] = pVector[0];
for (i = 0; i < iHalfN; i++)
pTemp[i + 1 + iHalfN] = pVector[i + 1];
for (i = 0; i < iHalfN - 1; i++)
pTemp[i + iHalfN + 1] = pVector[i+1];
}
-
+
for (i = 0; i < n; i++)
pVector[i] = pTemp[i];
delete pTemp;
/* FILE IDENTIFICATION
**
-** File Name: hashtable.h
-** Author: Kevin Rosenberg
-** Purpose: Header file for hash table library
-** Date Started: Dec. 2000
+** File Name: hashtable.h
+** Author: Kevin Rosenberg
+** Purpose: Header file for hash table library
+** Date Started: Dec. 2000
**
** This is part of the CTSim program
** Copyright (c) 1983-2001 Kevin Rosenberg
std::string m_strKeyword;
int m_iCode;
class KeywordCodeEntry *m_pNext;
-
+
public:
-
+
KeywordCodeEntry (const char* const pszKeyword, int iCode);
-
+
const char* const getKeyword() const
{ return m_strKeyword.c_str(); }
int getCode () const
{ return m_iCode; }
-
- void setCode (int iCode)
+
+ void setCode (int iCode)
{ m_iCode = iCode; }
-
+
void setNext (KeywordCodeEntry* pNext)
{ m_pNext = pNext; }
-
+
KeywordCodeEntry* getNext ()
{ return m_pNext; }
};
enum {
HASHSIZE = 100,
};
-
+
KeywordCodeHashTable()
{ initTable(); }
-
+
~KeywordCodeHashTable()
{ freeTable(); }
-
+
void installKeywordCode (const char* const pszKeyword, int iCode);
KeywordCodeEntry* lookup (const char* const pszKeyword);
-
+
private:
KeywordCodeEntry* m_hashTable[HASHSIZE];
-
+
int hash (const char* s);
void initTable ();
void freeTable ();
/*****************************************************************************
** FILE IDENTIFICATION
**
-** Name: imagefile.h
+** Name: imagefile.h
** Purpose: imagefile class header
-** Programmer: Kevin Rosenberg
-** Date Started: June 2000
+** Programmer: Kevin Rosenberg
+** Date Started: June 2000
**
** This is part of the CTSim program
** Copyright (c) 1983-2001 Kevin Rosenberg
class F32Image : public Array2dFile
{
public:
- F32Image (int nx, int ny, int dataType = Array2dFile::DATA_TYPE_REAL);
+ F32Image (int nx, int ny, int dataType = Array2dFile::DATA_TYPE_REAL);
F32Image (void);
kfloat32** getArray (void)
static double redGrayscaleFactor() {return s_dRedGrayscaleFactor;}
static double greenGrayscaleFactor() {return s_dGreenGrayscaleFactor;}
static double blueGrayscaleFactor() {return s_dBlueGrayscaleFactor;}
- static double colorToGrayscale (double r, double g, double b)
+ static double colorToGrayscale (double r, double g, double b)
{ return r * s_dRedGrayscaleFactor + g * s_dGreenGrayscaleFactor + b * s_dBlueGrayscaleFactor; }
};
BilinearInterpolator (T** ppMatrix, unsigned int nx, unsigned int ny)
: m_ppMatrix(ppMatrix), m_nx(nx), m_ny(ny)
{}
-
+
T interpolate (double dXPos, double dYPos)
{
int iFloorX = static_cast<int>(floor(dXPos));
int iFloorY = static_cast<int>(floor (dYPos));
double dXFrac = dXPos - iFloorX;
double dYFrac = dYPos - iFloorY;
-
+
T result = 0;
-
+
if (iFloorX < 0 || iFloorY < 0 || iFloorX > m_nx-1 || iFloorY > m_ny-1)
result = 0;
else if (iFloorX == m_nx - 1 && iFloorY == m_ny - 1)
result = static_cast<T>(m_ppMatrix[iFloorX][iFloorY] + dXFrac * (m_ppMatrix[iFloorX+1][iFloorY] - m_ppMatrix[iFloorX][iFloorY]));
else
result = static_cast<T>
- ((1 - dXFrac) * (1 - dYFrac) * m_ppMatrix[iFloorX][iFloorY] +
- dXFrac * (1 - dYFrac) * m_ppMatrix[iFloorX+1][iFloorY] +
+ ((1 - dXFrac) * (1 - dYFrac) * m_ppMatrix[iFloorX][iFloorY] +
+ dXFrac * (1 - dYFrac) * m_ppMatrix[iFloorX+1][iFloorY] +
dYFrac * (1 - dXFrac) * m_ppMatrix[iFloorX][iFloorY+1] +
dXFrac * dYFrac * m_ppMatrix[iFloorX+1][iFloorY+1]);
-
+
return result;
}
};
const int m_nAngle;
const int m_nPos;
int m_nCenterPos;
-
+
public:
BilinearPolarInterpolator (T** ppMatrix, unsigned int nAngle,
- unsigned int nPos)
+ unsigned int nPos)
: m_ppMatrix(ppMatrix), m_nAngle(nAngle), m_nPos(nPos)
{
if (m_nPos %2)
int iFloorPos = static_cast<int>(floor (dPos));
double dAngleFrac = dAngle - iFloorAngle;
double dPosFrac = dPos - iFloorPos;
-
+
T result = 0;
-
+
if (iFloorAngle < -1 || iFloorPos < 0 || iFloorAngle > m_nAngle-1 || iFloorPos > m_nPos-1)
result = 0;
else if (iFloorAngle == -1 && iFloorPos == m_nPos-1)
int iLowerPos = (m_nPos-1) - iFloorPos;
int iUpperPos = (m_nPos-1) - (iFloorPos+1);
result = static_cast<T>
- ((1-dAngleFrac) * (1-dPosFrac) * m_ppMatrix[iFloorAngle][iFloorPos] +
- dAngleFrac * (1-dPosFrac) * m_ppMatrix[iUpperAngle][iLowerPos] +
- dPosFrac * (1-dAngleFrac) * m_ppMatrix[iFloorAngle][iFloorPos+1] +
- dAngleFrac * dPosFrac * m_ppMatrix[iUpperAngle][iUpperPos]);
+ ((1-dAngleFrac) * (1-dPosFrac) * m_ppMatrix[iFloorAngle][iFloorPos] +
+ dAngleFrac * (1-dPosFrac) * m_ppMatrix[iUpperAngle][iLowerPos] +
+ dPosFrac * (1-dAngleFrac) * m_ppMatrix[iFloorAngle][iFloorPos+1] +
+ dAngleFrac * dPosFrac * m_ppMatrix[iUpperAngle][iUpperPos]);
} else if (iFloorAngle == -1) {
int iLowerAngle = m_nAngle - 1;
int iLowerPos = (m_nPos-1) - iFloorPos;
int iUpperPos = (m_nPos-1) - (iFloorPos+1);
result = static_cast<T>
- ((1-dAngleFrac) * (1-dPosFrac) * m_ppMatrix[iLowerAngle][iLowerPos] +
- dAngleFrac * (1-dPosFrac) * m_ppMatrix[iFloorAngle+1][iFloorPos] +
- dPosFrac * (1-dAngleFrac) * m_ppMatrix[iLowerAngle][iUpperPos] +
- dAngleFrac * dPosFrac * m_ppMatrix[iFloorAngle+1][iFloorPos+1]);
+ ((1-dAngleFrac) * (1-dPosFrac) * m_ppMatrix[iLowerAngle][iLowerPos] +
+ dAngleFrac * (1-dPosFrac) * m_ppMatrix[iFloorAngle+1][iFloorPos] +
+ dPosFrac * (1-dAngleFrac) * m_ppMatrix[iLowerAngle][iUpperPos] +
+ dAngleFrac * dPosFrac * m_ppMatrix[iFloorAngle+1][iFloorPos+1]);
} else
result = static_cast<T>
- ((1-dAngleFrac) * (1-dPosFrac) * m_ppMatrix[iFloorAngle][iFloorPos] +
- dAngleFrac * (1-dPosFrac) * m_ppMatrix[iFloorAngle+1][iFloorPos] +
- dPosFrac * (1-dAngleFrac) * m_ppMatrix[iFloorAngle][iFloorPos+1] +
- dAngleFrac * dPosFrac * m_ppMatrix[iFloorAngle+1][iFloorPos+1]);
+ ((1-dAngleFrac) * (1-dPosFrac) * m_ppMatrix[iFloorAngle][iFloorPos] +
+ dAngleFrac * (1-dPosFrac) * m_ppMatrix[iFloorAngle+1][iFloorPos] +
+ dPosFrac * (1-dAngleFrac) * m_ppMatrix[iFloorAngle][iFloorPos+1] +
+ dAngleFrac * dPosFrac * m_ppMatrix[iFloorAngle+1][iFloorPos+1]);
}
return result;
}
BicubicPolyInterpolator (T** ppMatrix, unsigned int nx, unsigned int ny)
: m_ppMatrix(ppMatrix), m_nx(nx), m_ny(ny)
{}
-
+
T interpolate (double dXPos, double dYPos)
{
// int iFloorX = static_cast<int>(floor (dXPos));
LinearInterpolator (T* pY, unsigned int n, bool bZeroOutside = true)
: m_pX(0), m_pY(pY), m_n(n), m_bZeroOutsideRange(bZeroOutside)
{}
-
+
LinearInterpolator (T* pX, T* pY, unsigned int n, bool bZeroOutside = true)
: m_pX(pX), m_pY(pY), m_n(n), m_bZeroOutsideRange(bZeroOutside)
{}
-
+
double interpolate (double dX, int* piLastFloor = NULL)
{
double result = 0;
void setTotalWorkUnits (int totalUnits);
int getRank (void) const
- { return m_myRank; }
+ { return m_myRank; }
int getNumProcessors (void) const
- { return m_nProcessors; }
+ { return m_nProcessors; }
int getStartWorkUnit (int rank) const
- { return m_vStartWorkUnit [rank]; }
+ { return m_vStartWorkUnit [rank]; }
int getEndWorkUnit (int rank) const
{ return m_vEndWorkUnit [rank]; }
int getLocalWorkUnits (int rank) const
- { return m_vLocalWorkUnits [rank]; }
+ { return m_vLocalWorkUnits [rank]; }
int getMyStartWorkUnit (void) const
- { return m_vStartWorkUnit [m_myRank]; }
+ { return m_vStartWorkUnit [m_myRank]; }
int getMyEndWorkUnit (void) const
- { return m_vEndWorkUnit [m_myRank]; }
+ { return m_vEndWorkUnit [m_myRank]; }
int getMyLocalWorkUnits (void) const
- { return m_vLocalWorkUnits [m_myRank]; }
+ { return m_vLocalWorkUnits [m_myRank]; }
- MPI::Intracomm& getComm()
+ MPI::Intracomm& getComm()
{ return m_comm; }
void BcastString (string& str);
bool isPointInside (double x, double y, const CoordType coord_type) const;
bool clipLineNormalizedCoords (double& x1, double& y1, double& x2, double& y2) const;
-
+
bool clipLineWorldCoords (double& x1, double& y1, double& x2, double& y2) const;
const int nOutlinePoints() const {return m_nPoints;}
void printDefinition (std::ostringstream& os) const;
private:
- PhmElemType m_type; // pelem type (box, ellipse, etc)
- double m_cx, m_cy; // center of pelem
- double m_u, m_v; // size of pelem
- double m_atten; // X-ray attenuation coefficient
- double m_rot; // pelem rotation angle (in radians)
- double *m_x, *m_y; // ptr to array of points in obj world coord
- int m_nPoints; // number of points in outline arrays
- double m_xmin, m_xmax, m_ymin, m_ymax; // pelem limits
+ PhmElemType m_type; // pelem type (box, ellipse, etc)
+ double m_cx, m_cy; // center of pelem
+ double m_u, m_v; // size of pelem
+ double m_atten; // X-ray attenuation coefficient
+ double m_rot; // pelem rotation angle (in radians)
+ double *m_x, *m_y; // ptr to array of points in obj world coord
+ int m_nPoints; // number of points in outline arrays
+ double m_xmin, m_xmax, m_ymin, m_ymax; // pelem limits
GRFMTX_2D m_xformPhmToObj; // map from phantom to normalized pelem coords
- GRFMTX_2D m_xformObjToPhm; // map from normalized pelem coords to phantom coords
+ GRFMTX_2D m_xformObjToPhm; // map from normalized pelem coords to phantom coords
double* m_xOutline;
double* m_yOutline;
double m_rectLimits[4];
static const int POINTS_PER_CIRCLE;
- static const double SCALE_PELEM_EXTENT; // increase pelem limits by 0.5%
+ static const double SCALE_PELEM_EXTENT; // increase pelem limits by 0.5%
static const char* const convertTypeToName (PhmElemType iType);
typedef enum {
P_PELEMS, // Phantom made of PElems
- P_UNIT_PULSE, // Special phantom, not made of pelems
- P_FILTER // defined only by this type
+ P_UNIT_PULSE, // Special phantom, not made of pelems
+ P_FILTER // defined only by this type
} PhantomComposition;
~Phantom ();
void setComposition (PhantomComposition composition)
- { m_composition = composition; }
+ { m_composition = composition; }
const PhantomComposition getComposition () const
- { return m_composition; }
+ { return m_composition; }
bool createFromPhantom (const char* const phmName);
void addPElem (const char* const composition, const double cx, const double cy, const double u, const double v, const double rot, const double atten);
void convertToImagefile (ImageFile& im, double dViewRatio, const int in_nsample, const int trace) const;
- void convertToImagefile (ImageFile& im, double dViewRatio, const int in_nsample, const int trace,
+ void convertToImagefile (ImageFile& im, double dViewRatio, const int in_nsample, const int trace,
const int colStart, const int colCount, bool bStoreAtColumnPos) const;
- void convertToImagefile (ImageFile& im, int iNX, double dViewRatio, const int in_nsample, const int trace,
+ void convertToImagefile (ImageFile& im, int iNX, double dViewRatio, const int in_nsample, const int trace,
const int colStart, const int colCount, int iStorageOffset) const;
void printDefinitions (std::ostream& os) const;
void show (SGP& sgp) const;
void draw (SGP& sgp) const;
#endif
-
+
void addStdHerman ();
void addStdSheppLogan ();
void print (std::ostream& os) const;
void print (std::ostringstream& os) const;
- double maxAxisLength () const
+ double maxAxisLength () const
{ return maxValue<double> (m_xmax - m_xmin, m_ymax - m_ymin); }
- double getDiameterBoundaryCircle() const
+ double getDiameterBoundaryCircle() const
{ return SQRT2 * maxAxisLength(); }
const double xmin() const {return m_xmin;}
const double xmax() const {return m_xmax;}
const double ymin() const {return m_ymin;}
const double ymax() const {return m_ymax;}
- std::list<PhantomElement*>& listPElem() {return m_listPElem;}
+ std::list<PhantomElement*>& listPElem() {return m_listPElem;}
const std::list<PhantomElement*>& listPElem() const {return m_listPElem;}
const int nPElem() const {return m_nPElem;}
private:
PhantomComposition m_composition;
- int m_nPElem; // number of pelems in phantom
+ int m_nPElem; // number of pelems in phantom
double m_xmin, m_xmax, m_ymin, m_ymax; // extent of pelems in pelem coordinates
mutable std::list<PhantomElement*> m_listPElem; // pelem lists
std::string m_name;
/*****************************************************************************
** FILE IDENTIFICATION
**
-** Name: plotfile.h
+** Name: plotfile.h
** Purpose: PlotFile class header
-** Programmer: Kevin Rosenberg
-** Date Started: Dec 2000
+** Programmer: Kevin Rosenberg
+** Date Started: Dec 2000
**
** This is part of the CTSim program
** Copyright (c) 1983-2001 Kevin Rosenberg
-class PlotFile
+class PlotFile
{
private:
std::string m_strFilename;
int m_iNumColumns;
int m_iNumRecords;
bool m_bScatterPlot;
-
+
bool headerRead (std::iostream& os);
bool headerWrite (std::iostream& os);
bool columnsRead (std::iostream& os);
bool columnsWrite (std::iostream& os);
-
+
void initHeaders ();
-
+
PlotFile (const PlotFile& rhs); // copy constructor
PlotFile& operator= (const PlotFile&); // assignment operator
-
+
public:
PlotFile (int iNColumns, int iNRecords);
PlotFile (void);
~PlotFile ();
-
+
void setCurveSize (int iNCurves, int iNRecords, bool bScatterPlot = false);
-
+
void addDescription (const char* const pszDesc)
{ m_vecStrDescriptions.push_back (pszDesc); }
-
+
void addEzsetCommand (const char* const pszCmd)
{ m_vecStrEzsetCommands.push_back (pszCmd); }
-
+
bool addColumn (int iCol, const double* const pdColumn);
-
+
bool addColumn (int iCol, const float* const pdColumn);
-
+
void getColumn (int iCol, double *pdColumnData) const;
-
+
const std::string& getDate () const
{ return m_strDate; }
-
+
int getNumColumns () const
{ return m_iNumColumns; }
-
+
int getNumRecords () const
{ return m_iNumRecords; }
-
+
bool getIsScatterPlot() const
{ return m_bScatterPlot; }
-
+
bool getMinMax (int startingCol, double& min, double& max) const;
-
+
bool statistics (int startingCol, double& min, double& max, double& mean, double& mode, double& median, double &stddev) const;
-
+
unsigned int getNumDescriptions (void) const
{ return m_vecStrDescriptions.size(); }
-
+
const std::string& getDescription (int iDescIndex) const
{ return m_vecStrDescriptions[iDescIndex]; }
-
+
unsigned int getNumEzsetCommands (void) const
{ return m_vecStrEzsetCommands.size(); }
-
+
const std::string& getEzsetCommand (int iIndex) const
{ return m_vecStrEzsetCommands[iIndex]; }
-
+
bool fileRead (const char* const filename);
-
+
bool fileWrite (const char* const filename);
-
- const std::string& getFilename (void) const
+
+ const std::string& getFilename (void) const
{ return m_strFilename; }
-
+
void printHeaders (std::ostream& os) const;
void printHeaders (std::ostringstream& os) const;
void printHeadersBrief (std::ostream& os) const;
/*****************************************************************************
-** Name: pol.h
+** Name: pol.h
** Purpose: Header file for Problem Oriented Language Class
-** Programmer: Kevin Rosenberg
-** Date Started: 1984
+** Programmer: Kevin Rosenberg
+** Date Started: 1984
**
** This is part of the CTSim program
** Copyright (c) 1983-2001 Kevin Rosenberg
#include <stack>
class POL {
-
+
public:
-
- // codes for pol_usefile
+
+ // codes for pol_usefile
enum {
- P_USE_STR = 1, // use string as input source
- P_USE_FILE, // use file as input source
+ P_USE_STR = 1, // use string as input source
+ P_USE_FILE, // use file as input source
};
-
+
POL();
~POL();
-
+
void init ();
void addSkipWord (const char* const w);
void addSkipChar (int c);
void ungetch (int c);
int get_inputline (FILE *fp);
void set_inputline (const char* const line);
-
+
enum {
- MAXTOK = 200, // maximum length of a token
+ MAXTOK = 200, // maximum length of a token
MAXLINE = 1024, // maximum line length
MAXIDENT = 20,
MAXSKIPWORD = 20,
MIN_INT = -2000000000,
MAX_INT = 2000000000,
};
-
- // token types
+
+ // token types
enum {
- TT_STRING = 1, // string token
- TT_INT, // integer token
- TT_REAL, // floating point token
- TT_ALPHA, // alphabetic token
- TT_ALPNUM, // alphanumeric token
+ TT_STRING = 1, // string token
+ TT_INT, // integer token
+ TT_REAL, // floating point token
+ TT_ALPHA, // alphabetic token
+ TT_ALPNUM, // alphanumeric token
TT_NUMALPHA,
TT_SPECLCHAR,
- TT_EOF, // end of file reached
- TT_ERROR, // error in token, caused by call to wrong type of token reader
- TT_BLANK, // white space token. pol_tok() skips these
- TT_USERTOK, // user defined token
+ TT_EOF, // end of file reached
+ TT_ERROR, // error in token, caused by call to wrong type of token reader
+ TT_BLANK, // white space token. pol_tok() skips these
+ TT_USERTOK, // user defined token
};
-
+
private:
-
- // codes for pol_int and pol_float
- // if in reject catagory, get new number from terminal
+
+ // codes for pol_int and pol_float
+ // if in reject catagory, get new number from terminal
enum {
- P_FLTINT = 1, // get a real or integer number
- P_BFLTINT, // get a real or integer number, clip against bounds
- P_CBFLTINT, // get real or int, reject if outside bounds
- P_FLT, // get a real number
- P_BFLT, // get a real, clip against bounds
- P_CBFLT, // get a floating, reject if outside bounds
- P_INT, // get a integer number
- P_BINT, // get a integer, clip against bounds
- P_CBINT, // get a integer, reject if outside bounds
+ P_FLTINT = 1, // get a real or integer number
+ P_BFLTINT, // get a real or integer number, clip against bounds
+ P_CBFLTINT, // get real or int, reject if outside bounds
+ P_FLT, // get a real number
+ P_BFLT, // get a real, clip against bounds
+ P_CBFLT, // get a floating, reject if outside bounds
+ P_INT, // get a integer number
+ P_BINT, // get a integer, clip against bounds
+ P_CBINT, // get a integer, reject if outside bounds
};
-
+
#define LETTER 'a'
#define DIGIT '0'
-
-
+
+
// typedef std::map<std::string,int> KeywordCodeList;
-
+
struct token_st {
- int ready; // TRUE if token is ready
- // std::string tokstr; // token string
+ int ready; // TRUE if token is ready
+ // std::string tokstr; // token string
char tokstr[MAXTOK+1];
- int type; // type of token 'TT_'
- int code; // holds code for user defined tokens
- double fnum; // real value of token
- int inum; // integer value of token
+ int type; // type of token 'TT_'
+ int code; // holds code for user defined tokens
+ double fnum; // real value of token
+ int inum; // integer value of token
};
typedef struct token_st TOKEN;
- struct token_st token; // current token
-
- // Tables words stored with install() & found with lookup()
- KeywordCodeHashTable skiptable; // words to ignore and skip
- KeywordCodeHashTable cmdtable; // pol parameter commands
- KeywordCodeHashTable usertable; // user defined symbols
-
+ struct token_st token; // current token
+
+ // Tables words stored with install() & found with lookup()
+ KeywordCodeHashTable skiptable; // words to ignore and skip
+ KeywordCodeHashTable cmdtable; // pol parameter commands
+ KeywordCodeHashTable usertable; // user defined symbols
+
struct metachar {
- char eoc; /* end of command character */
- char str; /* string delimiter */
- char com; /* comment character */
- char cmd; /* pol parameter command character */
- char prg; /* program load character */
- char con; /* continuation across newline character */
- char out; /* character that delimits output to terminal */
- char ter; /* character indicates insertion of input from terminal */
- char inb; /* input from graphics device */
+ char eoc; /* end of command character */
+ char str; /* string delimiter */
+ char com; /* comment character */
+ char cmd; /* pol parameter command character */
+ char prg; /* program load character */
+ char con; /* continuation across newline character */
+ char out; /* character that delimits output to terminal */
+ char ter; /* character indicates insertion of input from terminal */
+ char inb; /* input from graphics device */
} meta;
-
-
+
+
char m_szSkipChars [MAXSKIPCHAR]; // characters to skip
bool m_bTrace;
bool m_bNewlineIsEOC;
-
+
struct KeywordCodeList {
char *keyword;
int code;
};
-
+
static const struct KeywordCodeList cmdlist[];
static const unsigned int NUMCMD;
-
- // Internal codes for pol commands
+
+ // Internal codes for pol commands
enum {
PC_EOC = 1,
PC_STR,
PC_COM,
PC_CMD,
PC_PRG,
- PC_CON,
+ PC_CON,
PC_OUT,
PC_TER,
- PC_INB,
+ PC_INB,
PC_NL_EOC,
PC_NL_NEOC,
PC_TRON,
PC_FILE,
PC_DUMP,
};
-
+
enum {
INPUT_STREAM = 1,
INPUT_FILE,
enum {
MAXFILE = 8,
};
-
- int currentf; /* pointer to current fp */
- FILE *filep[MAXFILE]; /* == NULL for string input */
- char *fname[MAXFILE]; /* pointer to filename */
-
- char inputline[MAXLINE]; /* current input line */
- int lineptr; /* current position in inputline */
-
+
+ int currentf; /* pointer to current fp */
+ FILE *filep[MAXFILE]; /* == NULL for string input */
+ char *fname[MAXFILE]; /* pointer to filename */
+
+ char inputline[MAXLINE]; /* current input line */
+ int lineptr; /* current position in inputline */
+
std::stack<int> m_stackPushBackInput;
bool skipSingleToken (char term[]);
int tok (struct token_st *token);
void dumptok (struct token_st *token);
-
-
+
+
int getpol_tok (struct token_st *token);
int getcmd ();
int gettok (TOKEN *tok);
void eatline ();
int type (int c);
int getch (FILE *fp);
-
+
};
#endif
/*****************************************************************************
** FILE IDENTIFICATION
**
-** Name: filter.h
+** Name: filter.h
** Purpose: Signal filter header file
-** Programmer: Kevin Rosenberg
-** Date Started: June 2000
+** Programmer: Kevin Rosenberg
+** Date Started: June 2000
**
** This is part of the CTSim program
** Copyright (c) 1983-2001 Kevin Rosenberg
BACKWARD = 1,
};
- ProcessSignal (const char* szFilterName, const char* szFilterMethodName,double bw, double signalIncrement,
- int n, double param, const char* szDomainName, const char* szFilterGenerationName,
- const int zeropad, const int preinterpolationFactor, const int iTraceLevel, int iGeometry,
+ ProcessSignal (const char* szFilterName, const char* szFilterMethodName,double bw, double signalIncrement,
+ int n, double param, const char* szDomainName, const char* szFilterGenerationName,
+ const int zeropad, const int preinterpolationFactor, const int iTraceLevel, int iGeometry,
double dFocalLength, double dSourceDetectorLength, SGP* pSGP = NULL);
~ProcessSignal();
void filterSignal (const float input[], double output[]) const;
- bool fail(void) const {return m_fail;}
+ bool fail(void) const {return m_fail;}
const std::string& failMessage(void) const {return m_failMessage;}
void setTraceLevel (int traceLevel) {m_traceLevel = traceLevel; }
static int convertFilterGenerationNameToID (const char* const fgName);
static const char* convertFilterGenerationIDToName (const int idFG);
static const char* convertFilterGenerationIDToTitle (const int idFG);
-
+
static const int getFilterMethodCount() {return s_iFilterMethodCount;}
static const char* const* getFilterMethodNameArray() {return s_aszFilterMethodName;}
static const char* const* getFilterMethodTitleArray() {return s_aszFilterMethodTitle;}
static int addZeropadFactor (int n, int iZeropad);
private:
- std::string m_nameFilterMethod;
- std::string m_nameFilterGeneration;
+ std::string m_nameFilterMethod;
+ std::string m_nameFilterGeneration;
int m_idFilterMethod;
int m_idFilterGeneration;
int m_nSignalPoints;
fftw_plan m_complexPlanForward, m_complexPlanBackward;
#endif
- void init (const int idFilter, int idFilterMethod, double dBandwidth, double dSignalIncrement,
- int nSignalPoints, double dFilterParam, const int idDomain, int idFilterGeneration, const int iZeropad,
- const int iPreinterpolationFactor, const int iTraceLevel, const int iGeometry, double dFocalLength,
+ void init (const int idFilter, int idFilterMethod, double dBandwidth, double dSignalIncrement,
+ int nSignalPoints, double dFilterParam, const int idDomain, int idFilterGeneration, const int iZeropad,
+ const int iPreinterpolationFactor, const int iTraceLevel, const int iGeometry, double dFocalLength,
double dSourceDetectorLength, SGP* pSGP);
- // transforms that use precalculated trig tables, therefore don't
+ // transforms that use precalculated trig tables, therefore don't
// require number of data points (n) as an argument
void finiteFourierTransform (const double input[], std::complex<double> output[], const int direction) const;
void finiteFourierTransform (const std::complex<double> input[], std::complex<double> output[], const int direction) const;
//used for rebinning divergent beam projections to parallel
-class ParallelRaysumCoordinate {
+class ParallelRaysumCoordinate {
public:
double m_dT; // Distance from center of origin
double m_dTheta; // perpendicular angle to origin
bool convertPolar (ImageFile& rIF, int iInterpolation);
bool convertFFTPolar (ImageFile& rIF, int iInterpolation, int iZeropad);
- void calcArrayPolarCoordinates (unsigned int nx, unsigned int ny, double** ppdView, double** ppdDet,
+ void calcArrayPolarCoordinates (unsigned int nx, unsigned int ny, double** ppdView, double** ppdDet,
int iNumDetWithZeros, double dZeropadRatio, double dDetInc);
void interpolatePolar (ImageFileArray& v, ImageFileArray& vImag, unsigned int nx, unsigned int ny, std::complex<double>** ppcDetValue,
- double** ppdDet, double** ppdView, unsigned int nView, unsigned int nDet, unsigned int nDetWithZeros,
+ double** ppdDet, double** ppdView, unsigned int nView, unsigned int nDet, unsigned int nDetWithZeros,
int iInterpolate);
bool reconstruct (ImageFile& im, const char* const filterName, double filt_param, const char* const filterMethodName, const int zeropad, const char* frequencyFilterName, const char* const interpName, int interp_param, const char* const backprojName, const int trace) const;
DetectorArray& getDetectorArray (const int iview)
{ return (*m_projData[iview]); }
-
+
const DetectorArray& getDetectorArray (const int iview) const
{ return (*m_projData[iview]); }
static bool copyViewData (const char* const filename, std::ostream& os, int startView, int endView);
static bool copyViewData (const std::string& filename, std::ostream& os, int startView, int endView);
-
+
private:
- int m_headerSize; // Size of disk file header
- int m_geometry; // Geometry of scanner
- class DetectorArray **m_projData; // Pointer to array of detarray_st pointers
- std::string m_remark; // description of raysum data
- int m_nDet; // number of detectors in array
- int m_nView; // number of rotated views
- double m_calcTime; // time required to calculate raysums
- double m_rotStart; // starting view rotation
- double m_rotInc; // angle between rotations
- double m_detStart; // distance of beginning detector to center phantom
- double m_detInc; // increment between detectors
+ int m_headerSize; // Size of disk file header
+ int m_geometry; // Geometry of scanner
+ class DetectorArray **m_projData; // Pointer to array of detarray_st pointers
+ std::string m_remark; // description of raysum data
+ int m_nDet; // number of detectors in array
+ int m_nView; // number of rotated views
+ double m_calcTime; // time required to calculate raysums
+ double m_rotStart; // starting view rotation
+ double m_rotInc; // angle between rotations
+ double m_detStart; // distance of beginning detector to center phantom
+ double m_detInc; // increment between detectors
double m_dFocalLength;
double m_dSourceDetectorLength;
double m_dViewDiameter;
/*****************************************************************************
** FILE IDENTIFICATION
**
-** Name: reconstruct.h Header file for Reconstruction class
+** Name: reconstruct.h Header file for Reconstruction class
** Programmer: Kevin Rosenberg
** Date Started: Aug 84
**
double m_dYMax;
};
-class Reconstructor
+class Reconstructor
{
private:
const Projections& m_rOriginalProj;
double* m_adPlotXAxis;
public:
- Reconstructor (const Projections& rProj, ImageFile& rIF, const char* const filterName, double filt_param,
- const char* const filterMethodName, const int zeropad, const char* filterGenerationName,
- const char* const interpName, int interpFactor, const char* const backprojectName, const int trace,
+ Reconstructor (const Projections& rProj, ImageFile& rIF, const char* const filterName, double filt_param,
+ const char* const filterMethodName, const int zeropad, const char* filterGenerationName,
+ const char* const interpName, int interpFactor, const char* const backprojectName, const int trace,
ReconstructionROI* pROI = NULL, bool bRebinToParallel = false, SGP* pSGP = NULL);
~Reconstructor ();
bool fail() const {return m_bFail;}
const std::string& failMessage() const {return m_strFailMessage;}
-
+
void plotFilter (SGP* pSGP = NULL);
void reconstructAllViews ();
{ m_viewAngle = viewAngle; }
private:
- DetectorValue* m_detValues; // Pointer to array of values recorded by detector
- int m_nDet; // Number of detectors in array */
- double m_viewAngle; // View angle in radians
+ DetectorValue* m_detValues; // Pointer to array of values recorded by detector
+ int m_nDet; // Number of detectors in array */
+ double m_viewAngle; // View angle in radians
DetectorArray& operator=(const DetectorArray& rhs); // assignment
DetectorArray (const DetectorArray& rhs); // copy constructor
static const int GEOMETRY_EQUIANGULAR;
static const int GEOMETRY_LINOGRAM;
-
- Scanner (const Phantom& phm, const char* const geometryName, int nDet,
- int nView, int iOffsetView, int nSample, const double rot_anglen,
+
+ Scanner (const Phantom& phm, const char* const geometryName, int nDet,
+ int nView, int iOffsetView, int nSample, const double rot_anglen,
double dFocalLengthRatio, double dCenterDetectorRatio, double dViewRatio, double dScanRatio);
~Scanner();
-
+
void collectProjections (Projections& proj, const Phantom& phm, const int trace = Trace::TRACE_NONE,
SGP* pSGP = NULL);
unsigned int nDet() const {return m_nDet;}
unsigned int nView() const {return m_nView;}
unsigned int offsetView() const {return m_iOffsetView;}
- unsigned int startView() const {return m_startView;}
+ unsigned int startView() const {return m_startView;}
double rotInc() const {return m_rotInc;}
double detInc() const {return m_detInc;}
double detLen() const {return m_detLen;}
static int convertGeometryNameToID (const char* const geometryName);
static const char* convertGeometryIDToName (const int idGeometry);
static const char* convertGeometryIDToTitle (const int idGeometry);
-
+
private:
bool m_fail;
std::string m_failMessage;
int m_idGeometry;
- unsigned int m_nDet; /* Number of detectors in array */
- unsigned int m_nView; /* Number of rotated views */
- unsigned int m_iOffsetView;
- unsigned int m_startView;
- unsigned int m_nSample; /* Number of rays per detector */
+ unsigned int m_nDet; /* Number of detectors in array */
+ unsigned int m_nView; /* Number of rotated views */
+ unsigned int m_iOffsetView;
+ unsigned int m_startView;
+ unsigned int m_nSample; /* Number of rays per detector */
double m_dFocalLength; // Focal Length, distance from source to center
double m_dSourceDetectorLength; // Distance from source to detectors
double m_dCenterDetectorLength; // Distance from center to detectors
double m_dViewDiameter; // Diameter of area being processed
double m_dScanDiameter; // Diamer of area being scanned
double m_dViewRatio; // View Ratio to diameter phantom
- double m_dFocalLengthRatio; // Source to Center Length as ratio to viewDiameter radius
+ double m_dFocalLengthRatio; // Source to Center Length as ratio to viewDiameter radius
double m_dCenterDetectorRatio; // Center to Detector Length as ratio of viewDiameter radius
double m_dScanRatio; // Scan length to view length ratio
double m_dFanBeamAngle;
- double m_detLen; // Total length of detector array
- double m_rotLen; // Rotation angle length in radians (norm 2PI)
- double m_detInc; // Increment between centers of detectors
- double m_rotInc; // Increment in rotation angle between views
+ double m_detLen; // Total length of detector array
+ double m_rotLen; // Rotation angle length in radians (norm 2PI)
+ double m_detInc; // Increment between centers of detectors
+ double m_rotInc; // Increment in rotation angle between views
double m_detStart;
double m_dXCenter; // Center of Phantom
- double m_dYCenter;
+ double m_dYCenter;
double m_dAngularDetIncrement;
double m_dAngularDetLen;
int m_trace;
struct {
- double xd1,yd1,xd2,yd2; /* Coordinates of detector endpoints */
- double xs1,ys1,xs2,ys2; /* Coordinates of source endpoints */
- double angle; /* Starting angle */
+ double xd1,yd1,xd2,yd2; /* Coordinates of detector endpoints */
+ double xs1,ys1,xs2,ys2; /* Coordinates of source endpoints */
+ double angle; /* Starting angle */
double dAngularDet;
} m_initPos;
#endif
SGPDriver (const char* szWinTitle = "", int xsize = 640, int ysize = 480);
-
+
~SGPDriver ();
int getPhysicalXSize () const
class SGP_RGBColor;
class SGP {
private:
- int m_iPhysicalXSize; // Physical Window size
+ int m_iPhysicalXSize; // Physical Window size
int m_iPhysicalYSize;
SGPDriver m_driver;
- double xw_min; // Window extents
+ double xw_min; // Window extents
double yw_min;
double xw_max;
double yw_max;
- double xv_min; // Viewport extents
+ double xv_min; // Viewport extents
double yv_min;
double xv_max;
double yv_max;
- double viewNDC[4]; // Viewport array for clip_rect()
+ double viewNDC[4]; // Viewport array for clip_rect()
int m_iCurrentPhysicalX;
int m_iCurrentPhysicalY;
// Master coordinates are coordinates before CTM transformation
// World coordinates are coordinates defined by setWindow()
// Normalized device coordinates range from 0. to 1. in both axes
- TransformationMatrix2D wc_to_ndc; // World coord to NDC matrix
- TransformationMatrix2D mc_to_ndc; // Master to NDC
+ TransformationMatrix2D wc_to_ndc; // World coord to NDC matrix
+ TransformationMatrix2D mc_to_ndc; // Master to NDC
TransformationMatrix2D ndc_to_mc; // NDC to Master
- TransformationMatrix2D m_ctm; // Current transfromation matrix
-
+ TransformationMatrix2D m_ctm; // Current transfromation matrix
+
void calc_transform ();
static SGP_RGBColor s_aRGBColor[];
#endif
public:
- enum { // linestyles
+ enum { // linestyles
LS_NOLINE = 0,
LS_SOLID = 0xffff,
LS_DASH1 = 0xff00,
};
enum { // Codes for marker symbols
- MARKER_POINT = 0, // small dot
- MARKER_SQUARE = 1, // empty square
- MARKER_FSQUARE = 2, // filled square
- MARKER_DIAMOND = 3, // empty diamond
- MARKER_FDIAMOND = 4, // filled diamond
- MARKER_CROSS = 5, // cross
- MARKER_XCROSS = 6, // x
- MARKER_CIRCLE = 7, // open circle
- MARKER_FCIRCLE = 8, // filled circle
- MARKER_BSQUARE = 9, // big open square
- MARKER_BDIAMOND = 10, // big open diamond
+ MARKER_POINT = 0, // small dot
+ MARKER_SQUARE = 1, // empty square
+ MARKER_FSQUARE = 2, // filled square
+ MARKER_DIAMOND = 3, // empty diamond
+ MARKER_FDIAMOND = 4, // filled diamond
+ MARKER_CROSS = 5, // cross
+ MARKER_XCROSS = 6, // x
+ MARKER_CIRCLE = 7, // open circle
+ MARKER_FCIRCLE = 8, // filled circle
+ MARKER_BSQUARE = 9, // big open square
+ MARKER_BDIAMOND = 10, // big open diamond
};
enum { MARK_COUNT = 11, };
static const unsigned char MARKER_BITMAP[MARK_COUNT][5];
enum {
- C_BLACK = 0, // color codes
+ C_BLACK = 0, // color codes
C_BLUE = 1,
C_GREEN = 2,
C_CYAN = 3,
** Name: timer.h
** Purpose: Header file for Timer class
** Author: Kevin Rosenberg
-** Date Started: Sep 2000
+** Date Started: Sep 2000
**
** This is part of the CTSim program
** Copyright (c) 1983-2001 Kevin Rosenberg
#ifndef _TIMER_H
#define _TIMER_H
-// pragma line required for Fedora 4 and wxWin 2.4.2
+// pragma line required for Fedora 4 and wxWin 2.4.2
#if defined(__GNUG__) && !defined(__APPLE__)
#pragma implementation "timer.h"
#endif
{
public:
Timer (void)
- { m_timeStart = ttime(); }
+ { m_timeStart = ttime(); }
virtual ~Timer (void)
- {}
+ {}
virtual double timerEnd (void)
{
- m_timeEnd = ttime();
- m_timeElapsed = m_timeEnd - m_timeStart;
-
- return (m_timeElapsed);
+ m_timeEnd = ttime();
+ m_timeElapsed = m_timeEnd - m_timeStart;
+
+ return (m_timeElapsed);
}
virtual void timerReport (const char* const msg) const
{
- std::cout << msg << ": " << m_timeElapsed << " seconds" << std::endl;
+ std::cout << msg << ": " << m_timeElapsed << " seconds" << std::endl;
}
virtual double timerEndAndReport (const char* const msg)
{
- double t = timerEnd ();
- timerReport (msg);
- return (t);
+ double t = timerEnd ();
+ timerReport (msg);
+ return (t);
}
double getTimeElapsed (void) const
- { return m_timeElapsed; }
+ { return m_timeElapsed; }
protected:
double m_timeStart;
double m_timeElapsed;
double ttime(void) const
- {
+ {
#ifdef HAVE_GETTIMEOFDAY
- struct timeval now;
- if (gettimeofday (&now, NULL))
- return 0;
-
- return (now.tv_sec + static_cast<double>(now.tv_usec) / 1000000.);
+ struct timeval now;
+ if (gettimeofday (&now, NULL))
+ return 0;
+
+ return (now.tv_sec + static_cast<double>(now.tv_usec) / 1000000.);
#elif defined(MSVC)
- struct _timeb now;
- _ftime (&now);
- return (now.time + static_cast<double>(now.millitm) / 1000.);
+ struct _timeb now;
+ _ftime (&now);
+ return (now.time + static_cast<double>(now.millitm) / 1000.);
#else
- return 0;
+ return 0;
#endif
- }
+ }
};
{
public:
TimerMPI (MPI::Intracomm& comm)
- : m_comm(comm)
+ : m_comm(comm)
{
- m_timeStart = MPI::Wtime();
+ m_timeStart = MPI::Wtime();
}
virtual ~TimerMPI (void)
virtual double timerEnd (void)
{
- m_timeEnd = MPI::Wtime();
- m_timeElapsed = m_timeEnd - m_timeStart;
-
- return (m_timeElapsed);
+ m_timeEnd = MPI::Wtime();
+ m_timeElapsed = m_timeEnd - m_timeStart;
+
+ return (m_timeElapsed);
}
virtual void timerReport (const char* const msg)
{
- if (m_comm.Get_rank() == 0)
- std::cout << msg << ": " << m_timeElapsed << " seconds" << std::endl;
+ if (m_comm.Get_rank() == 0)
+ std::cout << msg << ": " << m_timeElapsed << " seconds" << std::endl;
}
virtual double timerEndAndReport (const char* const msg)
{
- double t = timerEnd ();
- timerReport (msg);
- return (t);
+ double t = timerEnd ();
+ timerReport (msg);
+ return (t);
}
virtual void timerReportAllProcesses (const char* const msg)
{
- timerReport (msg);
+ timerReport (msg);
}
protected:
{
public:
TimerCollectiveMPI (MPI::Intracomm& comm)
- : TimerMPI::TimerMPI (comm)
+ : TimerMPI::TimerMPI (comm)
{
- m_comm.Barrier();
- m_timeStart = MPI::Wtime();
+ m_comm.Barrier();
+ m_timeStart = MPI::Wtime();
}
virtual ~TimerCollectiveMPI (void)
virtual double timerEnd (void)
{
- m_timeEnd = MPI::Wtime();
- m_timeElapsed = m_timeEnd - m_timeStart;
- m_comm.Reduce (&m_timeElapsed, &m_timeMin, 1, MPI::DOUBLE, MPI::MIN, 0);
- m_comm.Reduce (&m_timeElapsed, &m_timeMax, 1, MPI::DOUBLE, MPI::MAX, 0);
-
- return (m_timeElapsed);
+ m_timeEnd = MPI::Wtime();
+ m_timeElapsed = m_timeEnd - m_timeStart;
+ m_comm.Reduce (&m_timeElapsed, &m_timeMin, 1, MPI::DOUBLE, MPI::MIN, 0);
+ m_comm.Reduce (&m_timeElapsed, &m_timeMax, 1, MPI::DOUBLE, MPI::MAX, 0);
+
+ return (m_timeElapsed);
}
virtual double timerEndAndReport (const char* const msg)
{
- double t = timerEnd ();
- timerReport (msg);
- return (t);
+ double t = timerEnd ();
+ timerReport (msg);
+ return (t);
}
virtual void timerReport (const char* const msg)
{
- if (m_comm.Get_rank() == 0)
- std::cout << msg << " " << "Minimum=" << m_timeMin << ", Maximum=" << m_timeMax << " seconds" << std::endl;
+ if (m_comm.Get_rank() == 0)
+ std::cout << msg << " " << "Minimum=" << m_timeMin << ", Maximum=" << m_timeMax << " seconds" << std::endl;
}
virtual void timerReportAllProcesses (const char* const msg)
{
- std::cout << msg << ": " << "Minimum=" << m_timeMin << ", Maximum=" << m_timeMax << " seconds (Rank " << m_comm.Get_rank() << ")" << std::endl;
+ std::cout << msg << ": " << "Minimum=" << m_timeMin << ", Maximum=" << m_timeMax << " seconds (Rank " << m_comm.Get_rank() << ")" << std::endl;
}
private:
static const int TRACE_PROJECTIONS;
static const int TRACE_PLOT;
static const int TRACE_CLIPPING;
-
+
static const int BIT_CONSOLE;
static const int BIT_PHANTOM;
static const int BIT_PROJECTIONS;
static const int BIT_CLIPPING;
Trace (const char* const traceString);
-
+
void addTrace (const char* const traceString);
-
+
bool isTrace (const char* const traceQuery) const;
-
+
int getTraceLevel(void) const { return m_traceLevel; }
-
+
static int convertTraceNameToID (const char* traceName);
static const char* convertTraceIDToTitle (int idTrace);
static const char* convertTraceIDToName (int idTrace);
-
+
static const int getTraceCount() {return s_iTraceCount;}
static const char** getTraceNameArray() {return s_aszTraceName;}
static const char** getTraceTitleArray() {return s_aszTraceTitle;}
private:
-
+
int m_traceLevel;
-
+
bool addTraceElements (const char* const traceString);
static const char* s_aszTraceName[];
-void
+void
bresenham (int x1, int y1, int x2, int y2)
{
int delta_x = x2 - x1;
int dx_abs = (delta_x >= 0 ? delta_x : -delta_x);
-
+
int delta_y = y2 - y1;
int dy_abs = (delta_y >= 0 ? delta_y : -delta_y);
-
- // draws a line when abs(dx) >= abs(dy)
+
+ // draws a line when abs(dx) >= abs(dy)
if (dx_abs > dy_abs) {
int count = dx_abs + 1;
int major_inc = (x1 <= x2 ? 1 : -1);
- int min_inc = (delta_y >= 0 ? 1 : -1); // determine direction of minor axis
-
+ int min_inc = (delta_y >= 0 ? 1 : -1); // determine direction of minor axis
+
int d = dy_abs * 2 - dx_abs; // Put decision variable in d
int dinc1 = (dy_abs - dx_abs) * 2;
int dinc2 = 2 * dy_abs;
-
+
bresx (x1, y1, major_inc, d, d1, d2);
} else { //For plotting lines with abs(dy) > abs(sx)
int count = dy_abs + 1;
-
+
int major_inc = (y1 <= y2 ? 1 : -1);
int min_inc = (delta_x >= 0 ? 1 : -1); // check direction of minor axis
-
+
int d = dx_abs * 2 - dy_abs;
dinc1 = (dx_abs - dy_abs) * 2;
dinc2 = 2 * dx_abs;
-
+
bresy (x1, y1, major_inc, min_inc, count, d, d1, d2);
}
}
-static void
+static void
bresx (int x, int y, int majorinc, int minorinc, int count, int d, int d1, int d2)
{
do {
setpixel();
x += majorinc;
-
+
if (d < 0)
d += dinc2;
else {
}
} while (--count > 0);
}
-
-
-static void
+
+
+static void
bresy (int x, int y, int majorinc, int minorinc, int count, int d, int d1, int d2)
{
do {
setpixel();
y += majorinc;
-
+
if (d < 0)
d += dinc2;
else {
}
} while (--count > 0);
}
-
-
+
+
/*****************************************************************************
** FILE IDENTIFICATION
**
-** EZPLOT
+** EZPLOT
**
** This is part of the CTSim program
** Copyright (c) 1983-2001 Kevin Rosenberg
#endif
// Defaults
-static const double TICKRATIO = 0.4; // ratio of minor to major tick lengths
-static const int MAXNUMFMT = 15; // maximum length of a numeric format
+static const double TICKRATIO = 0.4; // ratio of minor to major tick lengths
+static const int MAXNUMFMT = 15; // maximum length of a numeric format
static const int DEF_CURVE_CLR = C_RED;
x[i] = xData[i];
y[i] = yData[i];
}
-
+
m_iPointCount = n;
}
}
-void
+void
EZPlot::addCurve (const double *y, int n)
{
double* x = new double [n];
-
+
for (int i = 0; i < n; i++)
x[i] = i;
-
+
addCurve (x, y, n);
delete x;
}
-void
+void
EZPlot::addCurve (const float *y, int n)
{
double* yDouble = new double [n];
-
+
for (int i = 0; i < n; i++)
yDouble[i] = y[i];
-
+
addCurve (yDouble, n);
delete yDouble;
}
EZPlot::addCurve (const float x[], const double y[], int num)
{
double* dx = new double [num];
-
+
for (int i = 0; i < num; i++)
dx[i] = x[i];
-
+
addCurve (dx, y, num);
delete dx;
}
EZPlot::addCurve (const double* const x, const float* const y, int num)
{
double* dy = new double [num];
-
+
for (int i = 0; i < num; i++)
dy[i] = y[i];
-
+
addCurve (x, dy, num);
-
+
delete dy;
}
{
if (num < 1)
return;
-
+
EZPlotCurve* pCurve = new EZPlotCurve (x, y, num);
m_vecCurves.push_back (pCurve);
}
void
EZPlot::clearCurves ()
{
- for (EZPlotCurveIterator i = m_vecCurves.begin(); i != m_vecCurves.end(); i++)
+ for (EZPlotCurveIterator i = m_vecCurves.begin(); i != m_vecCurves.end(); i++)
delete *i;
m_vecCurves.erase (m_vecCurves.begin(), m_vecCurves.end());
initPlotSettings();
m_pol.addSkipChar ('=');
-
+
m_pol.usefile (POL::P_USE_STR,"");
c_xlabel = "";
c_ylabel = "";
c_title = "";
-
+
o_xporigin = 0.0;
o_yporigin = 0.0;
o_xlength = 1.0;
o_ylength = 1.0;
-
+
o_xaxis = LINEAR;
o_yaxis = LINEAR;
-
+
o_grid = FALSE;
o_box = FALSE;
-
+
o_xmajortick = 10;
o_ymajortick = 8;
o_xminortick = 4;
o_yminortick = 4;
-
+
o_color = DEF_CURVE_CLR;
o_symfreq = 1;
o_symbol = -1;
o_linestyle = SGP::LS_SOLID;
-
+
o_xtlabel = TRUE;
o_ytlabel = TRUE;
o_xticks = BELOW;
o_yticks = LEFT;
-
+
o_legendbox = INSIDE;
o_tag = FALSE;
-
+
s_xtitle = FALSE;
s_ytitle = FALSE;
s_xcross = FALSE;
s_xlegend = FALSE;
s_ylegend = FALSE;
s_textsize = FALSE;
-
- clr_axis = C_LTGRAY; // set fixed colors
+
+ clr_axis = C_LTGRAY; // set fixed colors
clr_title = C_RED;
clr_label = C_BLUE;
clr_legend = C_CYAN;
}
-
+
int
}
-
+
int
}
-
+
int
}
-
+
const std::string*
}
-
+
/* NAME
-* plot Plots all curves collected by addCurves ()
+* plot Plots all curves collected by addCurves ()
*
* SYNOPSIS
* plot()
{
if (m_vecCurves.size() <= 0)
return;
-
+
m_pSGP = pSGP;
m_pSGP->setWindow (0., 0., 1., 1.);
-
+
if (s_textsize == TRUE)
m_pSGP->setTextPointSize (v_textsize);
charheight = m_pSGP->getCharHeight();
charwidth = m_pSGP->getCharWidth();
- double symheight = charheight * 0.3; // size of symbol in NDC
+ double symheight = charheight * 0.3; // size of symbol in NDC
double symwidth = symheight;
-
+
const EZPlotCurve& firstCurve = *m_vecCurves[0];
double xmin = firstCurve.x[0]; // extent of curves in world coord
- double xmax = xmin;
+ double xmax = xmin;
double ymin = firstCurve.y[0];
- double ymax = ymin;
+ double ymax = ymin;
unsigned int iCurve;
for (iCurve = 0; iCurve < m_vecCurves.size(); iCurve++) {
const EZPlotCurve* const pCurve = m_vecCurves [iCurve];
-
+
for (int ip = 0; ip < pCurve->m_iPointCount; ip++) {
if (pCurve->x[ip] > xmax)
xmax = pCurve->x[ip];
ymin = pCurve->y[ip];
}
}
-
- // extend graph limits for user defined axis cross positions
+
+ // extend graph limits for user defined axis cross positions
if (s_xcross == TRUE) {
if (v_xcross < xmin)
xmin = v_xcross;
else if (v_xcross > xmax)
xmax = v_xcross;
}
-
+
if (s_ycross == TRUE) {
if (v_ycross < ymin)
ymin = v_ycross;
else if (v_ycross > ymax)
ymax = v_ycross;
}
-
- // find nice endpoints for axes
+
+ // find nice endpoints for axes
if (! axis_scale (xmin, xmax, o_xmajortick - 1, &xgw_min, &xgw_max, &x_nint) || ! axis_scale (ymin, ymax, o_ymajortick - 1, &ygw_min, &ygw_max, &y_nint))
return;
-
- // check if user set x-axis extents
+
+ // check if user set x-axis extents
if (s_xmin == TRUE) {
xgw_min = v_xmin;
x_nint = o_xmajortick - 1;
xgw_max = v_xmax;
x_nint = o_xmajortick - 1;
}
-
- // check if user set y-axis extents
+
+ // check if user set y-axis extents
if (s_ymin == TRUE) {
ygw_min = v_ymin;
y_nint = o_ymajortick - 1;
ygw_max = v_ymax;
y_nint = o_ymajortick - 1;
}
-
- // calculate increment between major axis in world coordinates
+
+ // calculate increment between major axis in world coordinates
xw_tickinc = (xgw_max - xgw_min) / x_nint;
yw_tickinc = (ygw_max - ygw_min) / y_nint;
-
- // we have now calcuated xgw_min, xyw_max, ygw_min, & ygw_max
-
- // set the number of decimal point to users' setting or default
+
+ // we have now calcuated xgw_min, xyw_max, ygw_min, & ygw_max
+
+ // set the number of decimal point to users' setting or default
// Two formats for numbers: Fixed: -nnn.f and Exponent: -n.fffE+eee
if (s_lxfrac == TRUE)
x_frac = v_lxfrac;
else
x_frac = -1;
-
+
if (s_lyfrac == TRUE)
y_frac = v_lyfrac;
else
y_frac = -1;
-
+
make_numfmt (x_numfmt, &x_fldwid, &x_frac, xgw_min, xgw_max, x_nint);
make_numfmt (y_numfmt, &y_fldwid, &y_frac, ygw_min, ygw_max, y_nint);
-
- xtl_wid = x_fldwid * charwidth; // calc size of tick labels
+
+ xtl_wid = x_fldwid * charwidth; // calc size of tick labels
ytl_wid = y_fldwid * charwidth;
tl_height = charheight;
-
- // calculate the extent of the plot frame
+
+ // calculate the extent of the plot frame
xp_min = o_xporigin;
yp_min = o_yporigin;
xp_max = xp_min + o_xlength;
yp_max = yp_min + o_ylength;
-
+
xp_min = clamp (xp_min, 0., 1.);
xp_max = clamp (xp_max, 0., 1.);
yp_min = clamp (yp_min, 0., 1.);
yp_max = clamp (yp_max, 0., 1.);
-
- xa_min = xp_min; // extent of axes
+
+ xa_min = xp_min; // extent of axes
xa_max = xp_max;
ya_min = yp_min;
ya_max = yp_max;
-
- // adjust frame for title
+
+ // adjust frame for title
title_row = ya_max;;
if (c_title.length() > 0)
ya_max -= 0.7 * charheight; // allow room for yaxis ticklabel
- // calculate legend box boundaries
- int max_leg = 0; // longest legend in characters
- int num_leg = 0; // number of legend titles
+ // calculate legend box boundaries
+ int max_leg = 0; // longest legend in characters
+ int num_leg = 0; // number of legend titles
for (iCurve = 0; iCurve < m_vecCurves.size(); iCurve++) {
const std::string* pstrLegend = getLegend (iCurve);
}
}
}
-
+
if (num_leg > 0 && o_legendbox != NOLEGEND) {
- double leg_width = (max_leg + 2) * charwidth; // size of legend box
+ double leg_width = (max_leg + 2) * charwidth; // size of legend box
double leg_height = num_leg * 3 * charheight;
-
+
if (s_xlegend == TRUE)
xl_max = v_xlegend;
else {
xa_max -= (leg_width + 0.5 * charwidth);
}
xl_min = xl_max - leg_width;
-
+
if (s_ylegend == TRUE)
yl_max = v_ylegend;
else
yl_max = ya_max;
-
+
yl_min = yl_max - leg_height;
-
+
m_pSGP->setColor (clr_legend);
m_pSGP->drawRect (xl_min, yl_min, xl_max, yl_max);
-
- int iLegend = 0; // current legend position
+
+ int iLegend = 0; // current legend position
for (iCurve = 0; iCurve < m_vecCurves.size(); iCurve++) {
const std::string* pstrLegend = getLegend (iCurve);
if (! pstrLegend || pstrLegend->length() == 0)
continue;
-
+
double xmin = xl_min + 1.0 * charwidth;
double xmax = xl_max - 1.0 * charwidth;
double y = yl_max - (2.0 + iLegend * 3) * charheight;
-
+
m_pSGP->moveAbs (xmin, y + 0.5 * charheight);
m_pSGP->drawText (pstrLegend->c_str());
symbol (iSymbol, symwidth, symheight);
}
}
- ++iLegend; // move to next legend position
+ ++iLegend; // move to next legend position
}
- } // end legend printing
-
- // calculate the extent of the axes
-
+ } // end legend printing
+
+ // calculate the extent of the axes
+
/*-------------------------*/
/* adjust frame for labels */
/*-------------------------*/
-
- // X-Label
+
+ // X-Label
if (c_xlabel.length() > 0)
ya_min += 1.5 * charheight;
- xlbl_row = xp_min; // put x-label on bottom of plot frame
-
- // Y-Label
+ xlbl_row = xp_min; // put x-label on bottom of plot frame
+
+ // Y-Label
if (c_ylabel.length() > 0) {
m_pSGP->setTextAngle (HALFPI);
}
ylbl_col = xp_min;
-
+
/*------------------------------*/
/* adjust frame for tick labels */
/*------------------------------*/
-
- // Calc offset of tick labels from axes
+
+ // Calc offset of tick labels from axes
if (o_xaxis == NOAXIS || o_xtlabel == FALSE)
xtl_ofs = 0.0;
else if (o_xticks == BELOW)
xtl_ofs = -0.5 * charheight;
else if (o_xticks == ABOVE)
xtl_ofs = 0.5 * charheight;
-
+
if (o_yaxis == NOAXIS || o_ytlabel == FALSE)
ytl_ofs = 0.0;
else if (o_yticks == LEFT) {
ytl_ofs = -xExtentMax;
} else if (o_yticks == RIGHT)
ytl_ofs = 1.5 * charwidth;
-
+
xa_max -= 0.7 * x_fldwid * charwidth; // make room for last x tick label
xt_min = xa_min;
yt_min = ya_min;
xt_max = xa_max;
yt_max = ya_max;
-
- // see if need to shrink axis extents and/or tick extents
+
+ // see if need to shrink axis extents and/or tick extents
if (xtl_ofs != 0.0 && s_ycross == FALSE) {
if (o_xticks == BELOW) {
ya_min += 1.5 * charheight;
ya_min += 0.0;
yt_min = ya_min + 1.5 * charheight;
}
- } else // noaxis, no t-labels, or user set cross
+ } else // noaxis, no t-labels, or user set cross
yt_min = ya_min;
-
+
if (ytl_ofs != 0.0 && s_xcross == FALSE) {
if (o_yticks == LEFT) {
xa_min += 2*charwidth - ytl_ofs; // (2 + y_fldwid) * charwidth;
} else
xt_min = xa_min;
- // decrease size of graph, if necessary, to accommadate space
- // between axis boundary and boundary of ticks
- double x_added_ticks = 0; // number of tick spaces added to axis
+ // decrease size of graph, if necessary, to accommadate space
+ // between axis boundary and boundary of ticks
+ double x_added_ticks = 0; // number of tick spaces added to axis
double y_added_ticks = 0;
if (o_xaxis == NOAXIS || o_xtlabel == FALSE)
x_added_ticks = 0;
if (o_yaxis == NOAXIS || o_ytlabel == FALSE)
y_added_ticks = 0;
-
+
if (o_grid == TRUE) {
if (x_added_ticks < 0)
x_added_ticks = 2;
if (y_added_ticks < 0)
y_added_ticks = 2;
}
-
+
if (x_added_ticks < 0) {
if (o_yticks == LEFT || s_ycross)
x_added_ticks = 1;
else
x_added_ticks = 2;
}
-
+
if (y_added_ticks < 0) {
if (o_xticks == BELOW || s_xcross)
y_added_ticks = 1;
else
y_added_ticks = 2;
}
-
+
xn_tickinc = (xt_max - xt_min) / (x_nint + x_added_ticks);
yn_tickinc = (yt_max - yt_min) / (y_nint + y_added_ticks);
-
+
xt_min += 0.5 * x_added_ticks * xn_tickinc;
xt_max -= 0.5 * x_added_ticks * xn_tickinc;
yt_min += 0.5 * y_added_ticks * yn_tickinc;
yt_max -= 0.5 * y_added_ticks * yn_tickinc;
-
+
xgn_min = xt_min;
xgn_max = xt_max;
ygn_min = yt_min;
ygn_max = yt_max;
-
+
//------------------------------------------------------------------------
-
+
m_xWorldScale = (xgn_max - xgn_min) / (xgw_max - xgw_min);
m_yWorldScale = (ygn_max - ygn_min) / (ygw_max - ygw_min);
-
- // PLOT CURVES
-
+
+ // PLOT CURVES
+
m_pSGP->setLineStyle (SGP::LS_SOLID);
drawAxes();
-
+
double clipRect[4];
for (iCurve = 0; iCurve < m_vecCurves.size(); iCurve++) {
const EZPlotCurve* const pCurve = m_vecCurves [iCurve];
-
+
m_pSGP->setColor (getColor (iCurve));
}
x1 = x2;
y1 = y2;
- }
+ }
}
if (iSym > 0) {
int iSymFreq = getSymbolFreq (iCurve);
}
}
}
- }
+ }
}
/* NAME
-* drawAxes INTERNAL routine to draw axis & label them
+* drawAxes INTERNAL routine to draw axis & label them
*
* SYNOPSIS
* drawAxes()
*/
-void
+void
EZPlot::drawAxes()
{
- double xticklen = 0, yticklen = 0; // length of ticks in NDC
- double minorinc; // increment between minor axes
- double xaxispos, yaxispos; // crossing of axes
+ double xticklen = 0, yticklen = 0; // length of ticks in NDC
+ double minorinc; // increment between minor axes
+ double xaxispos, yaxispos; // crossing of axes
double x, y, x2, y2;
- bool axis_near; // TRUE if axis too close to print t-label
+ bool axis_near; // TRUE if axis too close to print t-label
int i, j;
char str[256];
char *numstr;
-
+
m_pSGP->setTextSize (charheight);
m_pSGP->setTextColor (1, -1);
-
+
if (o_xticks == ABOVE)
xticklen = 0.5 * charheight;
else if (o_xticks == BELOW)
xticklen = -0.5 * charheight;
-
+
if (o_yticks == RIGHT)
yticklen = charwidth;
else if (o_yticks == LEFT)
yticklen = -charwidth;
-
+
if (c_title.length() > 0) {
double wText, hText;
m_pSGP->setTextSize (charheight * 2.0);
m_pSGP->drawText (c_title);
m_pSGP->setTextSize (charheight);
}
-
+
if (o_grid == TRUE || o_box == TRUE) {
m_pSGP->setColor (clr_axis);
m_pSGP->moveAbs (xa_min, ya_min);
m_pSGP->lineAbs (xa_min, ya_max);
m_pSGP->lineAbs (xa_min, ya_min);
}
-
- // calculate position of axes
-
- // x-axis
- if (s_ycross == TRUE) { // convert users' world-coord
- xaxispos = convertWorldToNDC_Y (v_ycross);// axis to its position in NDC
+
+ // calculate position of axes
+
+ // x-axis
+ if (s_ycross == TRUE) { // convert users' world-coord
+ xaxispos = convertWorldToNDC_Y (v_ycross);// axis to its position in NDC
x = convertWorldToNDC_X (xgw_min);
} else
xaxispos = ya_min;
-
- // y-axis
- if (s_xcross == TRUE) { // convert users' world-coord
- yaxispos = convertWorldToNDC_X (v_xcross);// axis to its NDC position
+
+ // y-axis
+ if (s_xcross == TRUE) { // convert users' world-coord
+ yaxispos = convertWorldToNDC_X (v_xcross);// axis to its NDC position
y = convertWorldToNDC_Y (ygw_min);
} else
yaxispos = xa_min;
-
+
/*-------------*/
/* draw x-axis */
/*-------------*/
-
+
if (o_xaxis == LINEAR) {
- // draw axis line
-
+ // draw axis line
+
m_pSGP->setColor (clr_axis);
if (o_tag && !o_grid && !o_box && s_xcross) {
m_pSGP->moveAbs (xa_min, xaxispos - charheight);
m_pSGP->moveAbs (xa_max, xaxispos - charheight);
m_pSGP->lineAbs (xa_max, xaxispos + charheight);
}
-
+
if (o_grid == TRUE) {
m_pSGP->setColor (clr_grid);
for (i = 0; i <= x_nint; i++) {
m_pSGP->drawText (c_xlabel);
m_pSGP->setTextSize (charheight);
minorinc = xn_tickinc / (o_xminortick + 1);
-
+
for (i = 0; i <= x_nint; i++) {
x = xt_min + xn_tickinc * i;
m_pSGP->setColor (clr_axis);
if (o_yticks == LEFT && d <= 0 && d > -0.9 * xn_tickinc)
axis_near = TRUE;
}
-
+
if (o_xtlabel == TRUE && axis_near == FALSE) {
snprintf (str, sizeof(str), x_numfmt, xgw_min + xw_tickinc * i);
numstr = str_skip_head (str, " ");
m_pSGP->drawText (numstr);
}
}
- } // X - Axis
-
-
+ } // X - Axis
+
+
/*--------*/
/* y-axis */
/*--------*/
-
+
if (o_yaxis == LINEAR) {
-
+
m_pSGP->setColor (clr_axis);
if (o_tag && !o_grid && !o_box && s_ycross) {
m_pSGP->moveAbs (yaxispos - charwidth, ya_min);
m_pSGP->moveAbs (yaxispos - charwidth, ya_max);
m_pSGP->lineAbs (yaxispos + charwidth, ya_max);
}
-
+
if (o_grid == TRUE) {
m_pSGP->setColor (clr_grid);
for (i = 0; i <= y_nint; i++) {
m_pSGP->setTextAngle (0.0);
m_pSGP->setTextSize (charheight);
minorinc = yn_tickinc / (o_yminortick + 1);
-
+
for (i = 0; i <= y_nint; i++) {
y = yt_min + yn_tickinc * i;
m_pSGP->setColor (clr_axis);
m_pSGP->drawText (str);
}
}
- } // Y - Axis
+ } // Y - Axis
}
-void
+void
EZPlot::symbol (int sym, double symwidth, double symheight)
{
if (sym <= 0)
return;
-
+
if (sym == SB_CROSS) {
m_pSGP->markerRel (0, 0);
// m_pSGP->moveRel (-0.5 * symwidth, -0.5 * symheight);
/* NAME
-* axis_scale calculates graph axis scaling
+* axis_scale calculates graph axis scaling
*
* SYNOPSIS:
-* retval = axis_scale (min, max, nint, minp, maxp, nintp,
-* rec_total, rec_frac)
+* retval = axis_scale (min, max, nint, minp, maxp, nintp,
+* rec_total, rec_frac)
*
* INPUT:
-* double min Smallest value to plot
-* double max Largest value to plot
-* int nint Number of intervals desired
+* double min Smallest value to plot
+* double max Largest value to plot
+* int nint Number of intervals desired
*
* OUTPUT:
-* int retval FALSE if illegal parameters, else TRUE
-* double *minp Minimum graph value
-* double *maxp Maximum graph value
-* int *nintp Number of intervals for graph
+* int retval FALSE if illegal parameters, else TRUE
+* double *minp Minimum graph value
+* double *maxp Maximum graph value
+* int *nintp Number of intervals for graph
* int *rec_total Recommended field width for printing out the number
-* int *rec_frac Recommended number of digits for print fraction
+* int *rec_frac Recommended number of digits for print fraction
*/
-int
+int
EZPlot::axis_scale (double min, double max, int nint, double *minp, double *maxp, int *nintp)
{
if (min >= max || nint < 1) {
sys_error (ERR_WARNING, "Invalid params: min=%lf, max=%lf, num intervals=%d [axis_scale]", min, max, nint);
return (FALSE);
}
-
+
double eps = 0.025;
double a = fabs(min);
if (fabs(min) < fabs(max))
scale = scale * 10.0;
goto loop;
}
-
+
*minp *= scale;
*maxp *= scale;
-
+
return (TRUE);
}
/* NAME
-* make_numfmt Make a numeric format string
+* make_numfmt Make a numeric format string
*
* SYNOPSIS
* make_numfmt (fmtstr, fldwid, nfrac, min, max, nint)
-* char *fmtstr Returned format string for printf()
-* int *fldwid Returned field width
-* int *nfrac If < 0, then calculate best number of
-* fraction places & return that value
-* If >= 0, then use that number of places
-* double min Minimum value
-* double max Maximum value
-* int nint Number of intervals between min & max
+* char *fmtstr Returned format string for printf()
+* int *fldwid Returned field width
+* int *nfrac If < 0, then calculate best number of
+* fraction places & return that value
+* If >= 0, then use that number of places
+* double min Minimum value
+* double max Maximum value
+* int nint Number of intervals between min & max
*
* DESCRIPTION
* This routine is written as an INTERNAL routine for EZPLOT
*/
-static inline double
+static inline double
my_trunc (double x)
{
double integer;
-
+
modf (x, &integer);
-
+
return (integer);
}
-void
+void
EZPlot::make_numfmt (char *fmtstr, int *fldwid, int *nfrac, double minval, double maxval, int nint)
{
int wid, frac, expon;
-
+
double delta = (maxval - minval) / nint;
double absmin = fabs(minval);
double absmax = fabs(maxval);
absmax = absmin;
double logt = log10( absmax );
-
- if (fabs(logt) >= 6) { // use exponential format
+
+ if (fabs(logt) >= 6) { // use exponential format
if (fabs(logt) > 99)
- expon = 5; // E+102
+ expon = 5; // E+102
else
- expon = 4; // E+00
-
- if (*nfrac < 0) { // calculate frac
- delta /= pow (10., floor(logt)); // scale delta
+ expon = 4; // E+00
+
+ if (*nfrac < 0) { // calculate frac
+ delta /= pow (10., floor(logt)); // scale delta
frac = static_cast<int>(fabs(my_trunc(log10(delta)))) + 1;
if (frac < 1)
- frac = 1; // to be safe, add decimal pt
- } else // use users' frac
+ frac = 1; // to be safe, add decimal pt
+ } else // use users' frac
frac = *nfrac;
-
+
wid = 2 + frac + expon;
if (minval < 0. || maxval < 0.)
++wid;
sprintf (fmtstr, "%s%d%s%d%s", "%", wid, ".", frac, "g");
- } else { // use fixed format
+ } else { // use fixed format
wid = static_cast<int>(my_trunc(logt)) + 1;
if (wid < 1)
wid = 1;
if (minval < 0. || maxval < 0.)
++wid;
-
- if (*nfrac < 0) { // calculate frac
+
+ if (*nfrac < 0) { // calculate frac
if (delta >= 0.999999)
- frac = 1; // add a decimal pt to be safe
+ frac = 1; // add a decimal pt to be safe
else
frac = static_cast<int>(fabs(my_trunc(log10(delta)))) + 1;
- } else // use users' frac
+ } else // use users' frac
frac = *nfrac;
-
+
wid += 1 + frac;
sprintf (fmtstr, "%s%d%s%d%s", "%", wid, ".", frac, "f");
}
-
+
*fldwid = wid;
*nfrac = frac;
}
/*****************************************************************************
** FILE IDENTIFICATION
**
-** EZSET - Parameter control for EZPLOT
+** EZSET - Parameter control for EZPLOT
**
** This is part of the CTSim program
** Copyright (c) 1983-2001 Kevin Rosenberg
return ezset (command.c_str());
}
-bool
+bool
EZPlot::ezset (const char* const command)
{
return ezcmd (command);
}
-bool
+bool
EZPlot::ezcmd (const char* const comm)
{
m_pol.usefile (POL::P_USE_STR, "");
m_pol.set_inputline (comm);
-
+
char str [POL::MAXTOK+1];
int code;
bool retval = true;
}
else
retval = do_cmd (code);
-
- m_pol.closefile(); /* close input string file */
+
+ m_pol.closefile(); /* close input string file */
return (retval);
}
char strIn [1024];
int n;
double f;
-
+
switch (lx) {
case S_TEXTSIZE:
if (m_pol.readFloat (&f, POL::TT_REAL, FALSE, 0.0, 0.0) == TRUE) {
}
if (m_iCurrentCurve < 0)
o_linestyle = ls;
- else
+ else
setLinestyle (m_iCurrentCurve, ls);
break;
case S_NOLINE:
if (n >= 0) {
if (m_iCurrentCurve < 0)
o_color = n;
- else
+ else
setColor (m_iCurrentCurve, n);
} else
bad_option("The color you picked");
sym = n;
if (m_iCurrentCurve < 0)
o_symfreq = sym;
- else
+ else
setSymbolFreq (m_iCurrentCurve, sym);
}
} else if (m_pol.readWord ("none",4) == TRUE) {
if (n > 0)
m_iCurrentCurve = n - 1;
} else {
- if (m_pol.readWord ("all",3) == TRUE)
+ if (m_pol.readWord ("all",3) == TRUE)
m_iCurrentCurve = -1;
}
break;
fprintf (stderr, "Unimplemented EZPLOT command\n");
break;
}
-
+
m_pol.reader ();
return (true);
}
-void
+void
EZPlot::bad_option (char *opt)
{
sys_error (ERR_WARNING, "INVALID option: %s", opt);
//----------------------------------------------------------------------
-// KEYWORDS / CODES TABLE
+// KEYWORDS / CODES TABLE
//----------------------------------------------------------------------
const struct KeywordCodeTable EZPlot::m_sKeywords[] =
{
- {"solid", S_SOLID},
+ {"solid", S_SOLID},
{"dash", S_DASH},
{"curve", S_CURVE},
- {"noline", S_NOLINE},
- {"black", S_BLACK},
- {"red", S_RED},
- {"blue", S_BLUE},
- {"green", S_GREEN},
- {"pen", S_PEN},
- {"symbol", S_SYMBOL},
- {"every", S_EVERY},
- {"none", S_NONE},
- {"legend", S_LEGEND},
- {"xlegend", S_XLEGEND},
- {"ylegend", S_YLEGEND},
-
- {"xlin", S_XLIN},
- {"ylin", S_YLIN},
- {"xlog", S_XLOG},
- {"ylog", S_YLOG},
- {"xlabel", S_XLABEL},
- {"ylabel", S_YLABEL},
- {"xlength", S_XLENGTH},
- {"ylength", S_YLENGTH},
-
- {"xticks", S_XTICKS},
- {"yticks", S_YTICKS},
- {"above", S_ABOVE},
- {"label", S_LABEL},
- {"below", S_BELOW},
- {"nolabel", S_NOLABEL},
- {"right", S_RIGHT},
- {"left", S_LEFT},
-
- {"xautoscale", S_XAUTOSCALE},
- {"yautoscale", S_YAUTOSCALE},
- {"xmin", S_XMIN},
- {"ymin", S_YMIN},
- {"xmax", S_XMAX},
- {"ymax", S_YMAX},
- {"lxfrac", S_LXFRAC},
- {"lyfrac", S_LYFRAC},
- {"xcross", S_XCROSS},
- {"ycross", S_YCROSS},
- {"noxaxis", S_NOXAXIS},
- {"noyaxis", S_NOYAXIS},
- {"xporigin", S_XPORIGIN},
- {"yporigin", S_YPORIGIN},
- {"title", S_TITLE},
- {"xtitle", S_XTITLE},
- {"ytitle", S_YTITLE},
-
- {"replot", S_REPLOT},
- {"clear", S_CLEAR},
- {"store", S_STORE},
- {"restore", S_RESTORE},
- {"amark", S_AMARK},
- {"units", S_UNITS},
- {"inches", S_INCHES},
- {"user", S_USER},
-
- {"data", S_DATA},
- {"help", S_HELP},
- {"exit", S_EXIT},
-
- {"box", S_BOX},
- {"nobox", S_NOBOX},
- {"grid", S_GRID},
- {"nogrid", S_NOGRID},
- {"major", S_MAJOR},
- {"minor", S_MINOR},
- {"color", S_COLOR},
- {"legendbox", S_LEGENDBOX},
-
- {"no", S_NO},
-
- {"textsize", S_TEXTSIZE},
+ {"noline", S_NOLINE},
+ {"black", S_BLACK},
+ {"red", S_RED},
+ {"blue", S_BLUE},
+ {"green", S_GREEN},
+ {"pen", S_PEN},
+ {"symbol", S_SYMBOL},
+ {"every", S_EVERY},
+ {"none", S_NONE},
+ {"legend", S_LEGEND},
+ {"xlegend", S_XLEGEND},
+ {"ylegend", S_YLEGEND},
+
+ {"xlin", S_XLIN},
+ {"ylin", S_YLIN},
+ {"xlog", S_XLOG},
+ {"ylog", S_YLOG},
+ {"xlabel", S_XLABEL},
+ {"ylabel", S_YLABEL},
+ {"xlength", S_XLENGTH},
+ {"ylength", S_YLENGTH},
+
+ {"xticks", S_XTICKS},
+ {"yticks", S_YTICKS},
+ {"above", S_ABOVE},
+ {"label", S_LABEL},
+ {"below", S_BELOW},
+ {"nolabel", S_NOLABEL},
+ {"right", S_RIGHT},
+ {"left", S_LEFT},
+
+ {"xautoscale", S_XAUTOSCALE},
+ {"yautoscale", S_YAUTOSCALE},
+ {"xmin", S_XMIN},
+ {"ymin", S_YMIN},
+ {"xmax", S_XMAX},
+ {"ymax", S_YMAX},
+ {"lxfrac", S_LXFRAC},
+ {"lyfrac", S_LYFRAC},
+ {"xcross", S_XCROSS},
+ {"ycross", S_YCROSS},
+ {"noxaxis", S_NOXAXIS},
+ {"noyaxis", S_NOYAXIS},
+ {"xporigin", S_XPORIGIN},
+ {"yporigin", S_YPORIGIN},
+ {"title", S_TITLE},
+ {"xtitle", S_XTITLE},
+ {"ytitle", S_YTITLE},
+
+ {"replot", S_REPLOT},
+ {"clear", S_CLEAR},
+ {"store", S_STORE},
+ {"restore", S_RESTORE},
+ {"amark", S_AMARK},
+ {"units", S_UNITS},
+ {"inches", S_INCHES},
+ {"user", S_USER},
+
+ {"data", S_DATA},
+ {"help", S_HELP},
+ {"exit", S_EXIT},
+
+ {"box", S_BOX},
+ {"nobox", S_NOBOX},
+ {"grid", S_GRID},
+ {"nogrid", S_NOGRID},
+ {"major", S_MAJOR},
+ {"minor", S_MINOR},
+ {"color", S_COLOR},
+ {"legendbox", S_LEGENDBOX},
+
+ {"no", S_NO},
+
+ {"textsize", S_TEXTSIZE},
};
const int EZPlot::NKEYS = (sizeof(EZPlot::m_sKeywords) / sizeof (struct KeywordCodeTable));
-void
+void
EZPlot::initKeywords ()
{
for (int i = 0; i < NKEYS; i++)
/*****************************************************************************
-** Name: ezsupport.h
-** Function: Support routines for EZPlot library
-** Programmer: Kevin Rosenberg
-** Date Started: 1-22-85
+** Name: ezsupport.h
+** Function: Support routines for EZPlot library
+** Programmer: Kevin Rosenberg
+** Date Started: 1-22-85
**
** This is part of the CTSim program
** Copyright (c) 1983-2001 Kevin Rosenberg
/*****************************************************************************
** FILE IDENTIFICATION
**
-** POL - Problem Oriented Language
+** POL - Problem Oriented Language
**
** This is part of the CTSim program
** Copyright (c) 1983-2001 Kevin Rosenberg
const struct POL::KeywordCodeList POL::cmdlist[] = {
- { "eoc", PC_EOC,},
- { "str", PC_STR,},
- { "com", PC_COM,},
- { "cmd", PC_CMD,},
- { "prg", PC_PRG,},
- { "con", PC_CON,},
- { "out", PC_OUT,},
- { "ter", PC_TER,},
- { "inb", PC_INB,},
-
- { "nl_eoc",PC_NL_EOC,},
- { "nl_neoc", PC_NL_NEOC,},
- { "tron", PC_TRON,},
- { "troff", PC_TROFF,},
- { "file", PC_FILE,},
- { "dump", PC_DUMP,},
+ { "eoc", PC_EOC,},
+ { "str", PC_STR,},
+ { "com", PC_COM,},
+ { "cmd", PC_CMD,},
+ { "prg", PC_PRG,},
+ { "con", PC_CON,},
+ { "out", PC_OUT,},
+ { "ter", PC_TER,},
+ { "inb", PC_INB,},
+
+ { "nl_eoc",PC_NL_EOC,},
+ { "nl_neoc", PC_NL_NEOC,},
+ { "tron", PC_TRON,},
+ { "troff", PC_TROFF,},
+ { "file", PC_FILE,},
+ { "dump", PC_DUMP,},
};
const unsigned int POL::NUMCMD = (sizeof(POL::cmdlist) / sizeof (struct POL::KeywordCodeList));
{
}
-void
+void
POL::init ()
{
meta.eoc = SEMICOL;
meta.out = DOLLAR;
meta.ter = PERCENT;
meta.inb = LBRACK;
-
+
m_bNewlineIsEOC = true;
m_szSkipChars[0] = EOS;
-
-
+
+
for (unsigned int i = 0; i < NUMCMD; i++)
cmdtable.installKeywordCode (cmdlist[i].keyword, cmdlist[i].code);
-
- token.ready = false; // no token read yet
+
+ token.ready = false; // no token read yet
}
* char *w - word for pol to ignore and skip over in input
*
* tok() compares all tokens to words given to this routine. If it finds it,
-* it will immediately read another token.
+* it will immediately read another token.
*/
-void
+void
POL::addSkipWord (const char* const w)
{
skiptable.installKeywordCode (w, 0);
*
* skip all characters that appear in string s
*/
-void
+void
POL::addSkipChar (int c)
{
int n = strlen (m_szSkipChars);
/* get_word - matches tokens on a letter by letter basis
*
* char *search - string to search for
-* int nlet - maximum number of chars to search for match
+* int nlet - maximum number of chars to search for match
*/
-bool
+bool
POL::readWord (char *search, int nlet)
{
tok (&token);
if (m_bTrace)
sys_error (ERR_TRACE, "POL matching current token %s against word %s\n", token.tokstr, search);
-
+
if (strncasecmp (search, token.tokstr, nlet) == 0) {
dumptok (&token);
return (true);
}
/* usertok (str,code)
-* see if current token is a user defined token set with install()
+* see if current token is a user defined token set with install()
*
* char *str - token string as read from input
* int *code - returned code for user defined symbol
* return value - true if current token has been user defined
-* false if current token is not user defined
+* false if current token is not user defined
*/
bool
POL::readUserToken (char *str, int *code)
{
tok (&token);
-
+
if (m_bTrace)
sys_error (ERR_TRACE, "POL checking if current token '%s' is user defined\n", token.tokstr);
-
+
if (token.type == TT_USERTOK) {
*code = token.code;
strcpy (str, token.tokstr);
POL::readString (char *str)
{
tok (&token);
-
+
if (token.type == TT_STRING) {
strcpy (str, token.tokstr);
dumptok (&token);
/* integer - test for an integer
*
-* int *n: returned integer value
+* int *n: returned integer value
* int typecode = TT_INT if accept only integer values
-* = TT_REAL if accept both real and integer values
+* = TT_REAL if accept both real and integer values
* int boundcode= true if force to lie between boundries
-* = false can take any value it likes
-* int bb1: lower bound
-* int bb2: upper bound
+* = false can take any value it likes
+* int bb1: lower bound
+* int bb2: upper bound
*/
-bool
+bool
POL::readInteger (int *n, int typecode, bool boundcode, int bb1, int bb2)
{
tok (&token);
-
+
if (m_bTrace)
sys_error (ERR_TRACE, "POL checking if current token %s is an integer\n", token.tokstr);
-
+
if (token.type == TT_INT || token.type == TT_REAL) {
- if (boundcode) {
+ if (boundcode) {
if (token.inum < bb1)
*n = bb1;
else if (token.inum > bb2)
*n = bb2;
else
*n = token.inum;
- } else
+ } else
*n = token.inum;
dumptok (&token);
return (true);
POL::readFloat (double *n, double typecode, bool boundcode, double bb1, double bb2)
{
tok (&token);
-
+
if (m_bTrace)
sys_error (ERR_TRACE, "POL checking if current token %s is an floating point number\n", token.tokstr);
-
+
if (token.type == TT_INT || token.type == TT_REAL) {
- if (boundcode) {
+ if (boundcode) {
if (token.fnum < bb1)
*n = bb1;
else if (token.fnum > bb2)
*n = bb2;
else
*n = token.fnum;
- } else
+ } else
*n = token.fnum;
dumptok (&token);
return (true);
}
/*----------------------------------------------------------------------*/
-/* skip() - skip over any token except for end of command sequence */
-/* */
-/* returns true if succesful skip */
-/* returns false if already at end of command or EOF */
+/* skip() - skip over any token except for end of command sequence */
+/* */
+/* returns true if succesful skip */
+/* returns false if already at end of command or EOF */
/*----------------------------------------------------------------------*/
-bool
+bool
POL::skipTokens()
{
- char term[5]; /* string of characters not to skip */
-
+ char term[5]; /* string of characters not to skip */
+
term[0] = meta.eoc;
if (m_bNewlineIsEOC) {
term[1] = NEWLINE;
term[2] = EOS;
} else
term[1] = EOS;
-
+
return (skipSingleToken (term));
}
-void
+void
POL::reader()
{
while (skipTokens())
;
-
- dumptok (&token); /* skip end of command token */
+
+ dumptok (&token); /* skip end of command token */
}
/* skiptok (term) - skip a token unless the first character of a token is
-* in the string of terminators, term.
+* in the string of terminators, term.
* char *term - string of termination characters, don't skip these characters
-* skiptok() also does NOT skip TT_EOF
+* skiptok() also does NOT skip TT_EOF
* returns (true) if succesful skip of a token
* returns (false) if didn't skip, read termination character or TT_EOF
*/
-bool
+bool
POL::skipSingleToken (char term[])
{
tok (&token);
-
+
if (token.type == TT_EOF
|| (token.type == TT_SPECLCHAR && strchr(term, token.tokstr[0]) != NULL))
return (false);
}
}
-int
+int
POL::tok (struct token_st *token)
{
if (token->ready == false)
return (token->type);
}
-void
+void
POL::dumptok (struct token_st *token)
{
if (token->ready == false)
token->ready = false;
}
-int
+int
POL::getpol_tok (struct token_st *token)
{
KeywordCodeEntry* sym;
-
+
token->ready = false;
nexttok:
gettok (token);
-
+
if (token->type == TT_BLANK)
goto nexttok;
if (token->type == TT_SPECLCHAR) {
getcmd();
goto nexttok;
}
- if (token->tokstr[0] == meta.com) { /* skip comment */
+ if (token->tokstr[0] == meta.com) { /* skip comment */
eatline ();
goto nexttok;
}
fputs (token->tokstr, stderr);
goto nexttok;
}
- if (token->tokstr[0] == meta.con) { /* continuation across NEWLINE */
+ if (token->tokstr[0] == meta.con) { /* continuation across NEWLINE */
while (lookchar() == BLANK || lookchar() == TAB)
inchar();
if (lookchar() == NEWLINE)
inchar();
}
- if (token->tokstr[0] == meta.ter) { /* get input from terminal */
+ if (token->tokstr[0] == meta.ter) { /* get input from terminal */
usefile (P_USE_FILE, "");
tok (token);
closefile();
return (token->type);
}
}
-
+
/* look for filler words */
-
- if (skiptable.lookup (token->tokstr) != NULL) /* ignore words in skip table */
+
+ if (skiptable.lookup (token->tokstr) != NULL) /* ignore words in skip table */
goto nexttok;
-
+
/* look for user defined symbols */
-
+
if ((sym = usertable.lookup (token->tokstr)) != NULL) {
token->type = TT_USERTOK;
token->code = sym->getCode();
} else
token->code = 0;
-
+
if (m_bTrace)
sys_error (ERR_TRACE, "POL read token '%s', type = %d\n", token->tokstr, token->type);
-
+
return (token->type);
}
-int
+int
POL::getcmd()
{
int tt, found;
char str[MAXTOK+1];
KeywordCodeEntry *cmd;
TOKEN tok;
-
+
tt = getalpha (str, MAXTOK);
if (tt == TT_ERROR) {
sys_error (ERR_WARNING, "Error in POL parameter command");
found = false;
switch (cmd->getCode()) {
case PC_TRON:
- m_bTrace = true;
+ m_bTrace = true;
found = true;
break;
case PC_TROFF:
- m_bTrace = false;
+ m_bTrace = false;
found = true;
break;
case PC_FILE:
- found = true;
+ found = true;
tt = gettok (&tok);
usefile (P_USE_FILE, tok.tokstr);
break;
case PC_NL_EOC:
- found = true;
+ found = true;
m_bNewlineIsEOC = true;
break;
case PC_NL_NEOC:
- found = true;
+ found = true;
m_bNewlineIsEOC = false;
break;
case PC_DUMP:
- found = true;
+ found = true;
printf("eoc = %c str = %c com = %c cmd = %c prg = %c\n",
meta.eoc, meta.str, meta.com, meta.cmd, meta.prg);
printf("con = %c out = %c ter = %c inb = %c\n",
meta.con, meta.out, meta.ter, meta.inb);
- break;
+ break;
}
if (found == false) {
tt = gettok (&tok);
return (false);
}
switch(cmd->getCode()) {
- case PC_EOC:
+ case PC_EOC:
meta.eoc = tok.tokstr[0];
break;
case PC_STR:
default:
printf("command not implemented\n");
break;
- } /* switch (tok->type) */
- } /* if (found == false) */
- reader(); /* clean up command */
- } /* if legal command */
-
+ } /* switch (tok->type) */
+ } /* if (found == false) */
+ reader(); /* clean up command */
+ } /* if legal command */
+
return (true);
}
-int
+int
POL::gettok (TOKEN *tok)
{
int c, toktype;
int inum;
double fnum;
- int toksiz = MAXTOK; /* maximum length of token string */
-
+ int toksiz = MAXTOK; /* maximum length of token string */
+
while ((c = inchar()) == BLANK || c == TAB)
;
ungetch (c);
-
+
c = lookchar();
toktype = type(c);
-
+
fnum = 0.0;
inum = 0;
-
- if (c == BLANK || c == TAB) { /* skip white space */
+
+ if (c == BLANK || c == TAB) { /* skip white space */
getblank(tok->tokstr, toksiz);
toktype = TT_BLANK;
} else if (toktype == LETTER) {
toktype = getalpha (tok->tokstr, toksiz);
- } else if (c == meta.str) { /* quoted string */
+ } else if (c == meta.str) { /* quoted string */
getquote (tok->tokstr, toksiz);
toktype = TT_STRING;
} else if (type(c) == DIGIT || c == PLUS || c == HYPHEN || c == PERIOD) {
tok->tokstr[1] = EOS;
toktype = TT_SPECLCHAR;
}
-
+
tok->type = toktype;
tok->ready = true;
if (tok->type == TT_REAL || tok->type == TT_INT) {
tok->fnum = 0.0;
tok->inum = 0;
}
-
+
return (toktype);
}
-void
+void
POL::getblank (char *s, int toksiz)
{
int c;
-
+
while ((c = inchar()) == BLANK || c == TAB)
;
ungetch(c);
-
+
s[0] = BLANK;
s[1] = EOS;
}
-int
+int
POL::getalpha (char *s, int toksiz)
{
int i, chartype, alphatype;
-
+
if (type(lookchar()) != LETTER) {
s[0] = EOS;
return (TT_ERROR);
}
-
+
alphatype = TT_ALPHA;
- for (i = 0; i < toksiz; i++) { /* get alphanumeric token */
+ for (i = 0; i < toksiz; i++) { /* get alphanumeric token */
s[i] = inchar();
chartype = type (s[i]);
if (chartype != LETTER && chartype != DIGIT)
alphatype = TT_ALPNUM;
}
ungetch(s[i]);
-
+
if (i >= toksiz)
sys_error (ERR_SEVERE, "POL token too long.");
-
- s[i] = EOS; /* terminate token */
+
+ s[i] = EOS; /* terminate token */
return (alphatype);
}
/* getquote - get quoted string from file */
/* have already gotten delimiter in qs[0] */
-void
+void
POL::getquote (char *qs, int toksiz)
{
int delim;
-
- delim = inchar(); /* char = delimiter */
+
+ delim = inchar(); /* char = delimiter */
getescape(qs, delim, toksiz);
}
-void
-POL::getescape ( /* reads up to delim */
+void
+POL::getescape ( /* reads up to delim */
char *s,
int delim,
int toksiz
)
{
int i, c;
-
+
for (i = 0; (c = inchar()) != delim; i++) {
if (c == NEWLINE) {
sys_error (ERR_WARNING, "Missing closing delimiter.");
ungetch(c);
sys_error (ERR_SEVERE, "end of file inside quotation");
break;
- } else if (c == BSLASH) { /* escape character */
+ } else if (c == BSLASH) { /* escape character */
s[i++] = c;
- c = inchar(); /* get escaped character */
+ c = inchar(); /* get escaped character */
}
s[i] = c;
}
}
-bool
+bool
POL::readText (char *str, int lim)
{
int c;
str[0] = 0;
return false;
}
-
+
int i;
for (i = 0; i < lim && (c = inchar()) != EOF && c != NEWLINE; i++)
str[i] = c;
ungetch (c);
str[i] = 0;
-
+
return true;
}
//----------------------------------------------
-// Get a number for gettok()
+// Get a number for gettok()
//----------------------------------------------
-int
-POL::getnumber
+int
+POL::getnumber
(
- char str[], /* string to return token in */
- int strsize, /* maximum length of token string */
- double *fnum, /* floating point value of number read */
- int *inum /* integer value of number read */
+ char str[], /* string to return token in */
+ int strsize, /* maximum length of token string */
+ double *fnum, /* floating point value of number read */
+ int *inum /* integer value of number read */
)
{
int sp = 0;
double sign = 1.0;
- bool isSigned = false; /* true if number prefixed by '+' or '-' */
+ bool isSigned = false; /* true if number prefixed by '+' or '-' */
*fnum = 0.0;
*inum = 0;
str[0] = EOS;
-
+
int c = inchar();
if (c == HYPHEN) {
str[sp++] = c;
return (TT_ERROR);
} else
ungetch (c);
-
+
if (isSigned) {
c = lookchar();
if (c == PERIOD) {
- inchar(); /* get period */
- c = lookchar(); /* look at character past period */
- ungetch (PERIOD); /* put back period */
+ inchar(); /* get period */
+ c = lookchar(); /* look at character past period */
+ ungetch (PERIOD); /* put back period */
if (type(c) != DIGIT) {
str[sp] = EOS;
return (TT_SPECLCHAR);
return (TT_SPECLCHAR);
}
}
-
+
double whole = 0.0;
while (type(c = inchar()) == DIGIT) {
if (sp < strsize)
str[sp++] = c;
whole = 10.0 * whole + (c - '0');
}
- ungetch (c); /* put back non-numeric character */
-
+ ungetch (c); /* put back non-numeric character */
+
if (c != PERIOD && tolower(c) != 'e') {
str[sp] = EOS;
*fnum = whole * sign;
*inum = (int) *fnum;
return (TT_INT);
}
-
+
if (lookchar() == PERIOD) {
inchar();
if (sp < strsize)
str[sp++] = PERIOD;
}
-
+
double frac = 0.0;
double powerof10 = 10.0;
-
+
while (type(c = inchar()) == DIGIT) {
if (sp < strsize)
str[sp++] = c;
powerof10 *= 10.0;
}
ungetch (c);
-
+
double exp = 0.0;
double expsign = 1.0;
c = inchar();
str[sp++] = c;
expsign = -1.0;
} else if (type(c) != DIGIT) {
- --sp; /* erase 'e' */
+ --sp; /* erase 'e' */
ungetch (c);
ungetch ('e');
goto getnumexit;
} else
ungetch(c);
-
+
exp = 0;
while (type(c = inchar()) == DIGIT) {
if (sp < strsize)
}
ungetch (c);
}
-
+
getnumexit:
str[sp] = EOS;
*fnum = sign * (whole + frac) * pow (10.0, expsign * exp);
return (TT_REAL);
}
-void
+void
POL::eatline ()
{
char term [2];
-
+
term[0] = NEWLINE;
term[1] = EOS;
skipSingleToken (term);
}
-// return type of ASCII character
-int
+// return type of ASCII character
+int
POL::type (int c)
{
if (isalpha(c) || c == UNDERLIN)
//----------------------------------------------------------------------
-// POL INPUT
+// POL INPUT
//----------------------------------------------------------------------
/* usefile - set source of POL input
*
* int source - source of input
-* P_USE_STR - have POL use strings as input
-* P_USE_FILE - use file. filename is in str
+* P_USE_STR - have POL use strings as input
+* P_USE_FILE - use file. filename is in str
*
*/
-void
+void
POL::usefile (int source, char *fn)
{
FILE *fp;
-
+
++currentf;
if (currentf >= MAXFILE) {
--currentf;
sys_error (ERR_SEVERE, "files nested too deeply");
return;
}
-
+
while (! m_stackPushBackInput.empty())
m_stackPushBackInput.pop();
}
}
-void
+void
POL::closefile()
{
if (currentf >= 0) {
/*-----------------------------*/
-int
+int
POL::lookchar()
{
int c;
-
+
c = inchar();
ungetch (c);
return (c);
}
-int
+int
POL::inchar()
{
int c = 0;
-
+
if (currentf < 0)
return (EOF);
-
+
while (currentf >= 0 && (c = getch(filep[currentf])) == EOF && filep[currentf] != NULL) {
closefile ();
}
-
+
return (c);
}
/*--------------------------------------------------------------*/
-/* getch - get a (possibly pushed back) character */
-/* if fp == NULL, then get character from inputline */
+/* getch - get a (possibly pushed back) character */
+/* if fp == NULL, then get character from inputline */
/*--------------------------------------------------------------*/
-int
+int
POL::getch (FILE *fp)
{
int c;
}
} else
c = fgetc(fp);
-
+
return (c);
}
-// push character back on input
-void
+// push character back on input
+void
POL::ungetch (int c)
{
m_stackPushBackInput.push (c);
}
-int
+int
POL::get_inputline (FILE *fp)
{
while (! m_stackPushBackInput.empty())
return (OK);
}
-void
+void
POL::set_inputline (const char* const line)
{
while (! m_stackPushBackInput.empty())
/*****************************************************************************
** FILE IDENTIFICATION
**
-** Name: sgp.cpp Simple Graphics Package
-** Programmer: Kevin Rosenberg
+** Name: sgp.cpp Simple Graphics Package
+** Programmer: Kevin Rosenberg
**
** This is part of the CTSim program
** Copyright (c) 1983-2001 Kevin Rosenberg
SGPDriver::~SGPDriver ()
{
#if HAVE_G2_H
- if (isG2())
+ if (isG2())
g2_close (m_idG2);
#endif
}
setViewport (0., 0., 1., 1.);
moveAbs (0., 0.);
stylusNDC (0., 0., false);
-
+
setTextAngle (0.);
setTextPointSize (12);
setColor (C_BLACK);
m_driver.idWX()->SetFont (*m_pFont);
double dTestCharHeight = m_driver.idWX()->GetCharHeight();
m_dPointsPerPixel = iTestPointSize / dTestCharHeight;
- m_driver.idWX()->SetBackground (*wxWHITE_BRUSH);
+ m_driver.idWX()->SetBackground (*wxWHITE_BRUSH);
}
}
#endif
// NAME
// clear Clear Window
-void
+void
SGP::eraseWindow ()
{
#if HAVE_G2_H
#endif
#if HAVE_WXWINDOWS
if (m_driver.isWX()) {
- wxBrush brushWhite;
- brushWhite.SetColour(255,255,255);
- m_driver.idWX()->SetBackground(brushWhite);
- m_driver.idWX()->Clear();
- m_driver.idWX()->SetBackground(wxNullBrush);
+ wxBrush brushWhite;
+ brushWhite.SetColour(255,255,255);
+ m_driver.idWX()->SetBackground(brushWhite);
+ m_driver.idWX()->Clear();
+ m_driver.idWX()->SetBackground(wxNullBrush);
#if 1
- wxPen pen;
- pen.SetColour(255,255,255);
- m_driver.idWX()->SetBrush (brushWhite);
- m_driver.idWX()->DrawRectangle (0, 0, m_iPhysicalXSize, m_iPhysicalYSize);
- m_driver.idWX()->SetBrush (wxNullBrush);
+ wxPen pen;
+ pen.SetColour(255,255,255);
+ m_driver.idWX()->SetBrush (brushWhite);
+ m_driver.idWX()->DrawRectangle (0, 0, m_iPhysicalXSize, m_iPhysicalYSize);
+ m_driver.idWX()->SetBrush (wxNullBrush);
#endif
}
#endif
}
// NAME
-// sgp2_window Set window in world coordinates
-
+// sgp2_window Set window in world coordinates
+
void
SGP::setWindow (double xmin, double ymin, double xmax, double ymax)
sys_error (ERR_WARNING, "Minimum > Maximum [sgp2_window]");
return;
}
-
+
xw_min = xmin;
yw_min = ymin;
xw_max = xmax;
// NAME
-// sgp2_viewport Set viewport in NDC
+// sgp2_viewport Set viewport in NDC
void
SGP::setViewport (double xmin, double ymin, double xmax, double ymax)
sys_error (ERR_WARNING, "Minimum > Maximum [sgp2_viewport]");
return;
}
-
+
xv_min = xmin;
yv_min = ymin;
xv_max = xmax;
yv_max = ymax;
m_bRecalcTransform = true;
-
- viewNDC[0] = xmin; // Array for clip_rect()
+
+ viewNDC[0] = xmin; // Array for clip_rect()
viewNDC[1] = ymin;
viewNDC[2] = xmax;
viewNDC[3] = ymax;
// NAME
-// frameViewport draw box around viewport
+// frameViewport draw box around viewport
void
SGP::frameViewport (void)
#endif
}
-void
+void
SGP::setColor (int icol)
{
if (icol >= 0 && icol < s_iRGBColorCount) {
}
}
-void
+void
SGP::setPenWidth (int iWidth)
{
if (iWidth >= 0) {
}
//==============================================================
-// set line style. Pass 16 bit repeating pattern
+// set line style. Pass 16 bit repeating pattern
//==============================================================
-void
+void
SGP::setLineStyle (int style)
{
m_iLinestyle = style;
}
//==============================================================
-// absolute draw to
+// absolute draw to
//*==============================================================
-void
+void
SGP::lineAbs (double x, double y)
{
if (m_bRecalcTransform)
double x2 = x;
double y2 = y;
mc_to_ndc.transformPoint (&x2, &y2);
-
- if (clip_rect (x1, y1, x2, y2, viewNDC) == true) { // clip to viewport
+
+ if (clip_rect (x1, y1, x2, y2, viewNDC) == true) { // clip to viewport
stylusNDC (x1, y1, false); // move to first point
- stylusNDC (x2, y2, true); // draw to second point
+ stylusNDC (x2, y2, true); // draw to second point
}
m_dCurrentWorldX = x;
m_dCurrentWorldY = y;
}
-void
+void
SGP::moveAbs (double x, double y)
{
m_dCurrentWorldX = x;
- m_dCurrentWorldY = y; /* moves are not clipped */
+ m_dCurrentWorldY = y; /* moves are not clipped */
}
-void
+void
SGP::lineRel (double x, double y)
{
lineAbs (x + m_dCurrentWorldX, y + m_dCurrentWorldY);
}
-void
+void
SGP::moveRel (double x, double y)
{
moveAbs (x + m_dCurrentWorldX, y + m_dCurrentWorldY);
if (m_driver.isWX()) {
dHeight = m_driver.idWX()->GetCharHeight();
dHeight /= static_cast<double>(m_iPhysicalYSize);
- dHeight /= (yv_max - yv_min); // scale to viewport;
+ dHeight /= (yv_max - yv_min); // scale to viewport;
}
#endif
dHeight *= (yw_max - yw_min); // scale to world coordinates
if (m_driver.isWX()) {
dWidth = m_driver.idWX()->GetCharWidth();
dWidth /= static_cast<double>(m_iPhysicalXSize);
- dWidth /= (xv_max - xv_min); // scale to viewport
+ dWidth /= (xv_max - xv_min); // scale to viewport
}
#endif
dWidth *= (xw_max - xw_min); //scale to world coordinates
m_dTextAngle = convertRadiansToDegrees(angle);
}
-void
+void
SGP::polylineAbs (double x[], double y[], int n)
{
if (m_bRecalcTransform)
double x2 = x[1], y2 = y[1];
mc_to_ndc.transformPoint (&x2, &y2);
- double xt = x2; // don't pass (x2,y2) to clip, we need them
- double yt = y2; // as the beginning point of the next line
+ double xt = x2; // don't pass (x2,y2) to clip, we need them
+ double yt = y2; // as the beginning point of the next line
if (clip_rect (x1, y1, xt, yt, viewNDC)) {
stylusNDC (x1, y1, false);
stylusNDC (xt, yt, true);
}
-
+
for (int i = 2; i < n; i++) {
- x1 = x2; y1 = y2; // NDC endpoint of last line
+ x1 = x2; y1 = y2; // NDC endpoint of last line
x2 = x[i]; y2 = y[i];
mc_to_ndc.transformPoint (&x2, &y2);
xt = x2;
}
-void
+void
SGP::markerAbs (double x, double y)
{
if (m_bRecalcTransform)
double xndc = x;
double yndc = y;
mc_to_ndc.transformPoint (&xndc, &yndc);
- markerNDC (xndc, yndc);
+ markerNDC (xndc, yndc);
m_dCurrentWorldX = x;
m_dCurrentWorldY = y;
}
-void
+void
SGP::markerRel (double x, double y)
{
markerAbs (x + m_dCurrentWorldX, y + m_dCurrentWorldY);
}
-void
+void
SGP::pointAbs (double x, double y)
{
if (m_bRecalcTransform)
}
-void
+void
SGP::pointRel (double x, double y)
{
pointAbs (x + m_dCurrentWorldX, y + m_dCurrentWorldY);
drawText (rsMessage.c_str());
}
-void
+void
SGP::drawText (const char *pszMessage)
{
if (m_bRecalcTransform)
double yndc = m_dCurrentWorldY;
mc_to_ndc.transformPoint (&xndc, &yndc);
- stylusNDC (xndc, yndc, false); // move to location
+ stylusNDC (xndc, yndc, false); // move to location
#if HAVE_G2_H
if (m_driver.isG2()) {
// NAME
-// drawRect Draw box in graphics mode
+// drawRect Draw box in graphics mode
//
// SYNOPSIS
// drawbox (xmin, ymin, xmax, ymax)
-// double xmin, ymin Lower left corner of box
-// double xmax, ymax Upper left corner of box
+// double xmin, ymin Lower left corner of box
+// double xmax, ymax Upper left corner of box
//
// NOTES
// This routine leaves the current position of graphic cursor at lower
void
SGP::drawRect (double xmin, double ymin, double xmax, double ymax)
{
- moveAbs (xmin, ymin);
- lineAbs (xmax, ymin);
- lineAbs (xmax, ymax);
- lineAbs (xmin, ymax);
- lineAbs (xmin, ymin);
+ moveAbs (xmin, ymin);
+ lineAbs (xmax, ymin);
+ lineAbs (xmax, ymax);
+ lineAbs (xmin, ymax);
+ lineAbs (xmin, ymin);
}
// FUNCTION
-// sgp2_circle - draw circle of radius r at current center
-
-void
+// sgp2_circle - draw circle of radius r at current center
+
+void
SGP::drawCircle (const double r)
{
- drawArc (r, 0.0, TWOPI);
+ drawArc (r, 0.0, TWOPI);
}
//==============================================================
-// draw arc around current center. angles in radius
+// draw arc around current center. angles in radius
//==============================================================
-void
+void
SGP::drawArc (const double r, double start, double stop)
{
if (start > stop) {
double x = r * cos (start);
double y = r * sin (start);
- moveAbs (xCent + x, yCent + y); // move from center to start of arc
+ moveAbs (xCent + x, yCent + y); // move from center to start of arc
const double thetaIncrement = (5 * (TWOPI / 360)); // 5 degree increments
double cosTheta = cos (thetaIncrement);
double yp = s * x + c * y;
lineAbs (xCent + xp, yCent + yp);
- moveAbs (xCent, yCent); // move back to center of circle
+ moveAbs (xCent, yCent); // move back to center of circle
}
// NAME
-// calc_transform Calculate transform matrices
+// calc_transform Calculate transform matrices
void
SGP::calc_transform ()
{
double scaleX = (xv_max - xv_min) / (xw_max - xw_min);
double scaleY = (yv_max - yv_min) / (yw_max - yw_min);
-
+
wc_to_ndc.setIdentity();
wc_to_ndc.mtx[0][0] = scaleX;
wc_to_ndc.mtx[2][0] = xv_min - scaleX * xw_min;
calc_transform();
}
-void
+void
SGP::ctmSet (const TransformationMatrix2D& m)
{
m_ctm = m;
}
-void
+void
SGP::postTranslate (double x, double y)
{
TransformationMatrix2D m;
}
-void
+void
SGP::preScale (double sx, double sy)
{
TransformationMatrix2D m;
}
-void
+void
SGP::postScale (double sx, double sy)
{
TransformationMatrix2D m;
}
-void
+void
SGP::preRotate (double theta)
{
TransformationMatrix2D m;
}
-void
+void
SGP::postRotate (double theta)
{
TransformationMatrix2D m;
}
-void
+void
SGP::preShear (double shrx, double shry)
{
TransformationMatrix2D m;
}
-void
+void
SGP::postShear (double shrx, double shry)
{
TransformationMatrix2D m;
////////////////////////////////////////////////////////////////////////
// Pixel patterns of marker symbols (1x1 to 5x5 matrix)
-const unsigned char SGP::MARKER_BITMAP[MARK_COUNT][5] =
-{
- {'\000', '\000', '\010', '\000', '\000'}, // small dot
- {'\000', '\034', '\024', '\034', '\000'}, // empty square
- {'\000', '\034', '\034', '\034', '\000'}, // filled square
- {'\000', '\010', '\024', '\010', '\000'}, // empty diamond
- {'\000', '\010', '\034', '\010', '\000'}, // filled diamond
- {'\010', '\010', '\076', '\010', '\010'}, // cross
- {'\000', '\024', '\010', '\024', '\000'}, // X
- {'\034', '\042', '\042', '\042', '\034'}, // open circle
- {'\034', '\076', '\076', '\076', '\034'}, // filled circle
- {'\076', '\042', '\042', '\042', '\076'}, // big open square
- {'\010', '\024', '\042', '\024', '\010'}, // big open diamond
+const unsigned char SGP::MARKER_BITMAP[MARK_COUNT][5] =
+{
+ {'\000', '\000', '\010', '\000', '\000'}, // small dot
+ {'\000', '\034', '\024', '\034', '\000'}, // empty square
+ {'\000', '\034', '\034', '\034', '\000'}, // filled square
+ {'\000', '\010', '\024', '\010', '\000'}, // empty diamond
+ {'\000', '\010', '\034', '\010', '\000'}, // filled diamond
+ {'\010', '\010', '\076', '\010', '\010'}, // cross
+ {'\000', '\024', '\010', '\024', '\000'}, // X
+ {'\034', '\042', '\042', '\042', '\034'}, // open circle
+ {'\034', '\076', '\076', '\076', '\034'}, // filled circle
+ {'\076', '\042', '\042', '\042', '\076'}, // big open square
+ {'\010', '\024', '\042', '\024', '\010'}, // big open diamond
};
/*****************************************************************************
** FILE IDENTIFICATION
**
-** Name: transformmatrix.cpp
-** Function: Transform Matrix routine for graphic library
-** Programmer: Kevin Rosenberg
-** Date Started: 1-22-85
+** Name: transformmatrix.cpp
+** Function: Transform Matrix routine for graphic library
+** Programmer: Kevin Rosenberg
+** Date Started: 1-22-85
**
** This is part of the CTSim program
** Copyright (c) 1983-2001 Kevin Rosenberg
mtx[2][0] = m[2][0]; mtx[2][1] = m[2][1]; mtx[2][2] = m[2][2];
}
-void
+void
TransformationMatrix2D::setTranslate (double x, double y)
{
setIdentity();
}
-void
+void
TransformationMatrix2D::setScale (double sx, double sy)
{
setIdentity();
}
-void
+void
TransformationMatrix2D::setShear (double shrx, double shry)
{
setIdentity();
mtx[0][1] = shry;
}
-void
+void
TransformationMatrix2D::setRotate (double theta)
{
double s = sin (theta);
}
-void
+void
TransformationMatrix2D::setIdentity ()
{
mtx[0][0] = 1.; mtx[0][1] = 0.; mtx[0][2] = 0.;
double determ = determinant ();
if (fabs(determ) < 1E-6) {
sys_error (ERR_WARNING, "Determinant = %g [TransformationMatrix2D::invert]", determ);
- print (std::cout);
- std::cout << std::endl;
+ print (std::cout);
+ std::cout << std::endl;
}
b[0][0] = (mtx[1][1] * mtx[2][2] - mtx[2][1] * mtx[1][2]) / determ;
b[1][0] = -(mtx[1][0] * mtx[2][2] - mtx[2][0] * mtx[1][2]) / determ;
b[2][0] = (mtx[1][0] * mtx[2][1] - mtx[2][0] * mtx[1][1]) / determ;
-
+
b[0][1] = -(mtx[0][1] * mtx[2][2] - mtx[2][1] * mtx[0][2]) / determ;
b[1][1] = (mtx[0][0] * mtx[2][2] - mtx[2][0] * mtx[0][2]) / determ;
b[2][1] = -(mtx[0][0] * mtx[2][1] - mtx[2][0] * mtx[0][1]) / determ;
-
+
b[0][2] = (mtx[0][1] * mtx[1][2] - mtx[1][1] * mtx[0][2]) / determ;
b[1][2] = -(mtx[0][0] * mtx[1][2] - mtx[1][0] * mtx[0][2]) / determ;
b[2][2] = (mtx[0][0] * mtx[1][1] - mtx[1][0] * mtx[0][1]) / determ;
}
-double
+double
TransformationMatrix2D::determinant () const
{
return
}
-void
+void
TransformationMatrix2D::transformPoint (double* pX, double *pY) const
{
double x = *pX * mtx[0][0] + *pY * mtx[1][0] + mtx[2][0];
void
TransformationMatrix2D::print (std::ostream& ostr) const
{
- std::cout << mtx[0][0] << " " << mtx[0][1] << " " << mtx[0][2] << std::endl;
- std::cout << mtx[1][0] << " " << mtx[1][1] << " " << mtx[1][2] << std::endl;
- std::cout << mtx[2][0] << " " << mtx[2][1] << " " << mtx[2][2] << std::endl;
+ std::cout << mtx[0][0] << " " << mtx[0][1] << " " << mtx[0][2] << std::endl;
+ std::cout << mtx[1][0] << " " << mtx[1][1] << " " << mtx[1][2] << std::endl;
+ std::cout << mtx[2][0] << " " << mtx[2][1] << " " << mtx[2][2] << std::endl;
}
for (int row = 0; row < 3; row++)
for (int col = 0; col < 3; col++) {
- c[row][col] = 0.;
- for (int calc = 0; calc < 3; calc++)
- c[row][col] += a.mtx[row][calc] * b.mtx[calc][col];
+ c[row][col] = 0.;
+ for (int calc = 0; calc < 3; calc++)
+ c[row][col] += a.mtx[row][calc] * b.mtx[calc][col];
}
return TransformationMatrix2D (c);
/*****************************************************************************
** FILE IDENTIFICATION
**
-** Name: array2dfile.cpp
+** Name: array2dfile.cpp
** Purpose: 2-dimension array file class
-** Programmer: Kevin Rosenberg
-** Date Started: June 2000
+** Programmer: Kevin Rosenberg
+** Date Started: June 2000
**
** This is part of the CTSim program
** Copyright (c) 1983-2001 Kevin Rosenberg
m_second = lt->tm_sec;
}
-Array2dFileLabel::Array2dFileLabel()
+Array2dFileLabel::Array2dFileLabel()
{
init();
}
: m_strLabel (str)
{
init();
-
+
m_labelType = L_USER;
m_calcTime = ctime;
}
: m_strLabel (str)
{
init();
-
+
m_labelType = type;
m_calcTime = ctime;
}
{
}
-void
+void
Array2dFileLabel::setDateTime (int year, int month, int day, int hour, int minute, int second)
{
m_year = year;
m_second = second;
}
-void
+void
Array2dFileLabel::getDateTime (int& year, int& month, int& day, int& hour, int& minute, int& second) const
{
year = m_year;
second = m_second;
}
-const std::string&
+const std::string&
Array2dFileLabel::getDateString (void) const
{
char szDate [128];
m_strLabel = rhs.m_strLabel;
m_year = rhs.m_year; m_month = rhs.m_month; m_day = rhs.m_day;
m_hour = rhs.m_hour; m_minute = rhs.m_minute; m_second = rhs.m_second;
-
+
return (*this);
}
-void
+void
Array2dFile::allocArrays ()
{
- if (m_arrayData)
+ if (m_arrayData)
freeArray (m_arrayData);
if (m_imaginaryArrayData)
freeArray (m_imaginaryArrayData);
rppData[i] = new unsigned char [columnBytes];
}
-void
+void
Array2dFile::freeArrays ()
{
- if (m_arrayData)
+ if (m_arrayData)
freeArray (m_arrayData);
-
- if (m_imaginaryArrayData)
+
+ if (m_imaginaryArrayData)
freeArray (m_imaginaryArrayData);
-
+
}
void
Array2dFile::fileWrite (const char* const filename)
{
m_filename = filename;
-
+
frnetorderstream fs (m_filename.c_str(), std::ios::out | std::ios::in | std::ios::trunc | std::ios::binary);
if (fs.fail()) {
sys_error (ERR_WARNING, "Error opening file %s for writing [fileCreate]", m_filename.c_str());
}
if (! headerWrite(fs))
return false;
-
+
if (! arrayDataWrite (fs))
return false;
-
+
if (! labelsWrite (fs))
return false;
-
+
return true;
}
Array2dFile::fileRead (const char* const filename)
{
m_filename = filename;
-
+
frnetorderstream fs (m_filename.c_str(), std::ios::out | std::ios::in | std::ios::binary);
if (fs.fail()) {
sys_error (ERR_WARNING, "Unable to open file %s [fileRead]", m_filename.c_str());
return false;
}
-
+
if (! headerRead(fs))
return false;
-
+
allocArrays ();
-
+
if (! arrayDataRead(fs))
return false;;
-
+
if (! labelsRead (fs))
return false;
-
+
return true;
}
m_axisIncrementY = incY;
}
-void
+void
Array2dFile::setAxisExtent (double minX, double maxX, double minY, double maxY)
{
m_axisExtentKnown = true;
sys_error (ERR_WARNING, "Tried to read header with file closed [headerRead]");
return false;
}
-
+
fs.seekg (0);
kuint16 file_signature;
-
+
fs.readInt16 (m_headersize);
fs.readInt16 (file_signature);
fs.readInt16 (m_pixelFormat);
fs.readFloat64 (m_maxY);
fs.readFloat64 (m_offsetPV);
fs.readFloat64 (m_scalePV);
-
+
int read_m_headersize = fs.tellg();
if (read_m_headersize != m_headersize) {
sys_error (ERR_WARNING, "Read m_headersize %d != file m_headersize %d", read_m_headersize, m_headersize);
sys_error (ERR_WARNING, "File signature %d != true signature %d", file_signature, m_signature);
return false;
}
-
+
return ! fs.fail();
}
sys_error (ERR_WARNING, "Tried to write header with ! fs");
return false;
}
-
+
m_numFileLabels = m_labels.size();
-
+
fs.seekp (0);
fs.writeInt16 (m_headersize);
fs.writeInt16 (m_signature);
fs.writeFloat64 (m_maxY);
fs.writeFloat64 (m_offsetPV);
fs.writeFloat64 (m_scalePV);
-
+
m_headersize = static_cast<kuint16>(fs.tellp());
fs.seekp (0);
fs.writeInt16 (m_headersize);
-
+
return ! fs.fail();
}
sys_error (ERR_WARNING, "Tried to arrayDataWrite with !fs");
return false;
}
-
- if (! m_arrayData)
+
+ if (! m_arrayData)
return false;
-
+
fs.seekp (m_headersize);
int columnSize = m_ny * m_pixelSize;
for (unsigned int ix = 0; ix < m_nx; ix++) {
fs.write (reinterpret_cast<const char*>(ptrColumn), m_pixelSize);
ptrColumn += m_pixelSize;
}
- } else
+ } else
fs.write (reinterpret_cast<const char*>(ptrColumn), columnSize);
}
if (m_dataType == DATA_TYPE_COMPLEX) {
fs.write (reinterpret_cast<const char*>(ptrColumn), m_pixelSize);
ptrColumn += m_pixelSize;
}
- } else
+ } else
fs.write (reinterpret_cast<const char*>(ptrColumn), columnSize);
}
}
-
+
return true;
}
sys_error (ERR_WARNING, "Tried to arrayDataRead with ! fs");
return false;
}
-
+
if (! m_arrayData)
return false;
-
+
fs.seekg (m_headersize);
int columnSize = m_ny * m_pixelSize;
for (unsigned int ix = 0; ix < m_nx; ix++) {
fs.read (reinterpret_cast<char*>(ptrColumn), m_pixelSize);
ConvertReverseNetworkOrder (ptrColumn, m_pixelSize);
ptrColumn += m_pixelSize;
- }
+ }
} else
fs.read (reinterpret_cast<char*>(ptrColumn), columnSize);
}
fs.read (reinterpret_cast<char*>(ptrColumn), m_pixelSize);
ConvertReverseNetworkOrder (ptrColumn, m_pixelSize);
ptrColumn += m_pixelSize;
- }
+ }
} else
fs.read (reinterpret_cast<char*>(ptrColumn), columnSize);
}
}
-
+
return true;
}
fs.seekg (pos);
if (fs.fail())
return false;
-
+
for (int i = 0; i < m_numFileLabels; i++) {
kuint16 labelType, year, month, day, hour, minute, second;
kfloat64 calcTime;
-
+
fs.readInt16 (labelType);
fs.readInt16 (year);
fs.readInt16 (month);
fs.readInt16 (minute);
fs.readInt16 (second);
fs.readFloat64 (calcTime);
-
+
kuint16 strLength;
fs.readInt16 (strLength);
char* pszLabelStr = new char [strLength+1];
fs.read (pszLabelStr, strLength);
pszLabelStr[strLength] = 0;
-
+
Array2dFileLabel* pLabel = new Array2dFileLabel (labelType, pszLabelStr, calcTime);
delete pszLabelStr;
-
+
pLabel->setDateTime (year, month, day, hour, minute, second);
m_labels.push_back (pLabel);
}
-
+
return true;
}
{
off_t pos = m_headersize + m_arraySize;
fs.seekp (pos);
-
+
for (constLabelIterator l = m_labels.begin(); l != m_labels.end(); l++) {
const Array2dFileLabel& label = **l;
kuint16 labelType = label.getLabelType();
const char* const labelString = label.getLabelString().c_str();
int year, month, day, hour, minute, second;
kuint16 yearBuf, monthBuf, dayBuf, hourBuf, minuteBuf, secondBuf;
-
+
label.getDateTime (year, month, day, hour, minute, second);
yearBuf = year; monthBuf = month; dayBuf = day;
hourBuf = hour; minuteBuf = minute; secondBuf = second;
-
+
fs.writeInt16 (labelType);
fs.writeInt16 (yearBuf);
fs.writeInt16 (monthBuf);
fs.writeInt16 (strlength);
fs.write (labelString, strlength);
}
-
+
return true;
}
Array2dFile::labelAdd (int type, const char* const lstr, double calc_time)
{
Array2dFileLabel label (type, lstr, calc_time);
-
+
labelAdd (label);
}
Array2dFile::labelAdd (const Array2dFileLabel& label)
{
Array2dFileLabel* pLabel = new Array2dFileLabel(label);
-
+
m_labels.push_back (pLabel);
}
}
}
-void
+void
Array2dFile::arrayDataClear (void)
{
if (m_arrayData) {
{
for (constLabelIterator l = m_labels.begin(); l != m_labels.end(); l++) {
const Array2dFileLabel& label = **l;
-
+
label.print (os);
os << std::endl;
}
{
for (constLabelIterator l = m_labels.begin(); l != m_labels.end(); l++) {
const Array2dFileLabel& label = **l;
-
+
label.printBrief (os);
}
}
{
for (constLabelIterator l = m_labels.begin(); l != m_labels.end(); l++) {
const Array2dFileLabel& label = **l;
-
+
label.printBrief (os);
}
}
/*****************************************************************************
** FILE IDENTIFICATION
**
-** Name: backprojectors.cpp Classes for backprojection
+** Name: backprojectors.cpp Classes for backprojection
** Programmer: Kevin Rosenberg
** Date Started: June 2000
**
const int Backprojector::BPROJ_DIFF = 2;
const int Backprojector::BPROJ_IDIFF = 3;
-const char* const Backprojector::s_aszBackprojectName[] =
+const char* const Backprojector::s_aszBackprojectName[] =
{
"trig",
"table",
"idiff",
};
-const char* const Backprojector::s_aszBackprojectTitle[] =
+const char* const Backprojector::s_aszBackprojectTitle[] =
{
"Direct Trigometric",
"Trigometric Table",
const int Backprojector::INTERP_3BSPLINE = 7;
#endif
-const char* const Backprojector::s_aszInterpName[] =
+const char* const Backprojector::s_aszInterpName[] =
{
"nearest",
"linear",
#endif
};
-const char* const Backprojector::s_aszInterpTitle[] =
+const char* const Backprojector::s_aszInterpTitle[] =
{
"Nearest",
"Linear",
-Backprojector::Backprojector (const Projections& proj, ImageFile& im, const char* const backprojName,
+Backprojector::Backprojector (const Projections& proj, ImageFile& im, const char* const backprojName,
const char* const interpName, const int interpFactor, const ReconstructionROI* pROI)
{
m_fail = false;
m_pBackprojectImplem = NULL;
-
+
initBackprojector (proj, im, backprojName, interpName, interpFactor, pROI);
}
-void
+void
Backprojector::BackprojectView (const double* const viewData, const double viewAngle)
{
if (m_pBackprojectImplem != NULL)
m_pBackprojectImplem->BackprojectView (viewData, viewAngle);
}
-void
+void
Backprojector::PostProcessing()
{
if (m_pBackprojectImplem != NULL)
// Backproject* projector = selectBackprojector (...)
//
// PURPOSE
-// Selects a backprojector based on BackprojType
+// Selects a backprojector based on BackprojType
// and initializes the backprojector
bool
-Backprojector::initBackprojector (const Projections& proj, ImageFile& im, const char* const backprojName,
+Backprojector::initBackprojector (const Projections& proj, ImageFile& im, const char* const backprojName,
const char* const interpName, const int interpFactor, const ReconstructionROI* pROI)
{
m_nameBackproject = backprojName;
m_failMessage = "Invalid interpolation name ";
m_failMessage += interpName;
}
-
+
if (m_fail || m_idBackproject == BPROJ_INVALID || m_idInterpolation == INTERP_INVALID) {
m_fail = true;
return false;
}
-
+
if (proj.geometry() == Scanner::GEOMETRY_EQUILINEAR)
m_pBackprojectImplem = static_cast<Backproject*>(new BackprojectEquilinear(proj, im, m_idInterpolation, interpFactor, pROI));
- else if (proj.geometry() == Scanner::GEOMETRY_EQUIANGULAR)
+ else if (proj.geometry() == Scanner::GEOMETRY_EQUIANGULAR)
m_pBackprojectImplem = static_cast<Backproject*>(new BackprojectEquiangular(proj, im, m_idInterpolation, interpFactor, pROI));
else if (proj.geometry() == Scanner::GEOMETRY_PARALLEL) {
if (m_idBackproject == BPROJ_TRIG)
m_failMessage = "Unable to select a backprojection method [Backprojector::initBackprojector]";
return false;
}
-
+
return true;
}
Backprojector::convertBackprojectNameToID (const char* const backprojName)
{
int backprojID = BPROJ_INVALID;
-
+
for (int i = 0; i < s_iBackprojectCount; i++)
if (strcasecmp (backprojName, s_aszBackprojectName[i]) == 0) {
backprojID = i;
break;
}
-
+
return (backprojID);
}
Backprojector::convertBackprojectIDToName (int bprojID)
{
static const char *bprojName = "";
-
+
if (bprojID >= 0 && bprojID < s_iBackprojectCount)
return (s_aszBackprojectName[bprojID]);
-
+
return (bprojName);
}
Backprojector::convertBackprojectIDToTitle (const int bprojID)
{
static const char *bprojTitle = "";
-
+
if (bprojID >= 0 && bprojID < s_iBackprojectCount)
return (s_aszBackprojectTitle[bprojID]);
-
+
return (bprojTitle);
}
Backprojector::convertInterpNameToID (const char* const interpName)
{
int interpID = INTERP_INVALID;
-
+
for (int i = 0; i < s_iInterpCount; i++)
if (strcasecmp (interpName, s_aszInterpName[i]) == 0) {
interpID = i;
break;
}
-
+
return (interpID);
}
Backprojector::convertInterpIDToName (const int interpID)
{
static const char *interpName = "";
-
+
if (interpID >= 0 && interpID < s_iInterpCount)
return (s_aszInterpName[interpID]);
-
+
return (interpName);
}
Backprojector::convertInterpIDToTitle (const int interpID)
{
static const char *interpTitle = "";
-
+
if (interpID >= 0 && interpID < s_iInterpCount)
return (s_aszInterpTitle[interpID]);
-
+
return (interpTitle);
}
// PURPOSE
// Pure virtual base class for all backprojectors.
-Backproject::Backproject (const Projections& proj, ImageFile& im, int interpType, const int interpFactor,
+Backproject::Backproject (const Projections& proj, ImageFile& im, int interpType, const int interpFactor,
const ReconstructionROI* pROI)
: proj(proj), im(im), interpType(interpType), m_interpFactor(interpFactor), m_bPostProcessingDone(false)
{
detInc = proj.detInc();
nDet = proj.nDet();
- iDetCenter = (nDet - 1) / 2; // index refering to L=0 projection
-
+ iDetCenter = (nDet - 1) / 2; // index refering to L=0 projection
+
if (proj.geometry() == Scanner::GEOMETRY_PARALLEL)
rotScale = PI / proj.nView(); // scale by number of PI rotations
else if (proj.geometry() == Scanner::GEOMETRY_EQUIANGULAR || proj.geometry() == Scanner::GEOMETRY_EQUILINEAR)
rotScale = (2 * PI) / proj.nView(); // scale by number of 2PI rotations
else
sys_error (ERR_SEVERE, "Invalid geometry type %d [Backproject::Backproject]", proj.geometry());
-
+
v = im.getArray();
nx = im.nx();
ny = im.ny();
im.arrayDataClear();
-
+
xMin = -proj.phmLen() / 2; // Retangular coords of phantom
xMax = xMin + proj.phmLen();
yMin = -proj.phmLen() / 2;
yMax = yMin + proj.phmLen();
-
+
if (pROI) {
if (pROI->m_dXMin > xMin)
xMin = pROI->m_dXMin;
}
}
- xInc = (xMax - xMin) / nx; // size of cells
+ xInc = (xMax - xMin) / nx; // size of cells
yInc = (yMax - yMin) / ny;
-
+
im.setAxisIncrement (xInc, yInc);
im.setAxisExtent (xMin, xMax, yMin, yMax);
os << "xMin=" << xMin << ", xMax=" << xMax << ", xInc=" << xInc << "\n";
os << "yMin=" << yMin << ", yMax=" << yMax << ", yInc=" << yInc << "\n";
os << "iDetPos index outside bounds: " << iDetPos << " [backprojector]";;
-
+
sys_error (ERR_WARNING, os.str().c_str());
#endif
}
BackprojectTrig::BackprojectView (const double* const filteredProj, const double view_angle)
{
double theta = view_angle;
-
+
CubicPolyInterpolator* pCubicInterp = NULL;
if (interpType == Backprojector::INTERP_CUBIC)
pCubicInterp = new CubicPolyInterpolator (filteredProj, nDet);
-
- double x = xMin + xInc / 2; // Rectang coords of center of pixel
+
+ double x = xMin + xInc / 2; // Rectang coords of center of pixel
for (int ix = 0; ix < nx; x += xInc, ix++) {
double y = yMin + yInc / 2;
for (int iy = 0; iy < ny; y += yInc, iy++) {
double r = sqrt (x * x + y * y); // distance of cell from center
double phi = atan2 (y, x); // angle of cell from center
double L = r * cos (theta - phi); // position on detector
-
+
if (interpType == Backprojector::INTERP_NEAREST) {
int iDetPos = iDetCenter + nearest<int> (L / detInc); // calc'd index in the filter raysum array
-
+
if (iDetPos >= 0 && iDetPos < nDet)
v[ix][iy] += rotScale * filteredProj[iDetPos];
} else if (interpType == Backprojector::INTERP_LINEAR) {
- double p = L / detInc; // position along detector
+ double p = L / detInc; // position along detector
double pFloor = floor (p);
int iDetPos = iDetCenter + static_cast<int>(pFloor);
- double frac = p - pFloor; // fraction distance from det
+ double frac = p - pFloor; // fraction distance from det
if (iDetPos >= 0 && iDetPos < nDet - 1)
v[ix][iy] += rotScale * ((1-frac) * filteredProj[iDetPos] + frac * filteredProj[iDetPos+1]);
} else if (interpType == Backprojector::INTERP_CUBIC) {
- double p = iDetCenter + (L / detInc); // position along detector
+ double p = iDetCenter + (L / detInc); // position along detector
if (p >= 0 && p < nDet)
v[ix][iy] += rotScale * pCubicInterp->interpolate (p);
}
if (interpType == Backprojector::INTERP_CUBIC)
delete pCubicInterp;
-}
+}
// CLASS IDENTICATION
// PURPOSE
// Precalculates trigometric function value for each point in image for backprojection.
-BackprojectTable::BackprojectTable (const Projections& proj, ImageFile& im, int interpType,
+BackprojectTable::BackprojectTable (const Projections& proj, ImageFile& im, int interpType,
const int interpFactor, const ReconstructionROI* pROI)
: Backproject (proj, im, interpType, interpFactor, pROI)
{
arrayPhi.initSetSize (im.nx(), im.ny());
r = arrayR.getArray();
phi = arrayPhi.getArray();
-
- double x, y; // Rectang coords of center of pixel
+
+ double x, y; // Rectang coords of center of pixel
int ix, iy;
for (x = xMin + xInc / 2, ix = 0; ix < nx; x += xInc, ix++)
for (y = yMin + yInc / 2, iy = 0; iy < ny; y += yInc, iy++) {
BackprojectTable::BackprojectView (const double* const filteredProj, const double view_angle)
{
double theta = view_angle;
-
+
CubicPolyInterpolator* pCubicInterp = NULL;
if (interpType == Backprojector::INTERP_CUBIC)
pCubicInterp = new CubicPolyInterpolator (filteredProj, nDet);
-
+
for (int ix = 0; ix < nx; ix++) {
ImageFileColumn pImCol = v[ix];
-
+
for (int iy = 0; iy < ny; iy++) {
double L = r[ix][iy] * cos (theta - phi[ix][iy]);
-
+
if (interpType == Backprojector::INTERP_NEAREST) {
- int iDetPos = iDetCenter + nearest<int>(L / detInc); // calc index in the filtered raysum vector
-
+ int iDetPos = iDetCenter + nearest<int>(L / detInc); // calc index in the filtered raysum vector
+
if (iDetPos >= 0 && iDetPos < nDet)
pImCol[iy] += filteredProj[iDetPos];
} else if (interpType == Backprojector::INTERP_LINEAR) {
- double dPos = L / detInc; // position along detector
+ double dPos = L / detInc; // position along detector
double dPosFloor = floor (dPos);
int iDetPos = iDetCenter + static_cast<int>(dPosFloor);
- double frac = dPos - dPosFloor; // fraction distance from det
+ double frac = dPos - dPosFloor; // fraction distance from det
if (iDetPos >= 0 && iDetPos < nDet - 1)
pImCol[iy] += ((1-frac) * filteredProj[iDetPos] + frac * filteredProj[iDetPos+1]);
} else if (interpType == Backprojector::INTERP_CUBIC) {
- double p = iDetCenter + (L / detInc); // position along detector
+ double p = iDetCenter + (L / detInc); // position along detector
if (p >= 0 && p < nDet)
pImCol[iy] += pCubicInterp->interpolate (p);
}
- } // end for y
- } // end for x
+ } // end for y
+ } // end for x
if (interpType == Backprojector::INTERP_CUBIC)
delete pCubicInterp;
// Backprojects by precalculating the change in L position for each x & y step in the image.
// Iterates in x & y direction by adding difference in L position
-BackprojectDiff::BackprojectDiff (const Projections& proj, ImageFile& im, int interpType,
+BackprojectDiff::BackprojectDiff (const Projections& proj, ImageFile& im, int interpType,
const int interpFactor, const ReconstructionROI* pROI)
: Backproject (proj, im, interpType, interpFactor, pROI)
{
- // calculate center of first pixel v[0][0]
+ // calculate center of first pixel v[0][0]
double x = xMin + xInc / 2;
double y = yMin + yInc / 2;
start_r = sqrt (x * x + y * y);
start_phi = atan2 (y, x);
-
+
im.arrayDataClear();
}
BackprojectDiff::BackprojectView (const double* const filteredProj, const double view_angle)
{
double theta = view_angle;
-
- // Distance between detectors for an angle given in units of detectors
+
+ // Distance between detectors for an angle given in units of detectors
double det_dx = xInc * cos (theta) / detInc;
double det_dy = yInc * sin (theta) / detInc;
-
- // calculate detPosition for first point in image (ix=0, iy=0)
+
+ // calculate detPosition for first point in image (ix=0, iy=0)
double detPosColStart = iDetCenter + start_r * cos (theta - start_phi) / detInc;
-
+
CubicPolyInterpolator* pCubicInterp = NULL;
- double* deltaFilteredProj = NULL;
+ double* deltaFilteredProj = NULL;
if (interpType == Backprojector::INTERP_LINEAR) {
// precalculate scaled difference for linear interpolation
deltaFilteredProj = new double [nDet];
} else if (interpType == Backprojector::INTERP_CUBIC) {
pCubicInterp = new CubicPolyInterpolator (filteredProj, nDet);
}
-
+
int iLastDet = nDet - 1;
for (int ix = 0; ix < nx; ix++, detPosColStart += det_dx) {
double curDetPos = detPosColStart;
ImageFileColumn pImCol = v[ix];
-
+
for (int iy = 0; iy < ny; iy++, curDetPos += det_dy) {
if (interpType == Backprojector::INTERP_NEAREST) {
- int iDetPos = nearest<int> (curDetPos); // calc index in the filtered raysum vector
-
+ int iDetPos = nearest<int> (curDetPos); // calc index in the filtered raysum vector
+
if (iDetPos >= 0 && iDetPos < nDet)
*pImCol++ += filteredProj[iDetPos];
} else if (interpType == Backprojector::INTERP_LINEAR) {
double detPosFloor = floor (curDetPos);
int iDetPos = static_cast<int>(detPosFloor);
- double frac = curDetPos - detPosFloor; // fraction distance from det
+ double frac = curDetPos - detPosFloor; // fraction distance from det
if (iDetPos >= 0 && iDetPos <= iLastDet)
- *pImCol++ += filteredProj[iDetPos] + (frac * deltaFilteredProj[iDetPos]);
+ *pImCol++ += filteredProj[iDetPos] + (frac * deltaFilteredProj[iDetPos]);
} else if (interpType == Backprojector::INTERP_CUBIC) {
- double p = curDetPos; // position along detector
+ double p = curDetPos; // position along detector
if (p >= 0 && p < nDet)
*pImCol++ += pCubicInterp->interpolate (p);
}
- } // end for y
- } // end for x
+ } // end for y
+ } // end for x
if (interpType == Backprojector::INTERP_LINEAR)
delete deltaFilteredProj;
static const long scaleBitmask = scale - 1;
static const long halfScale = scale / 2;
static const double dInvScale = 1. / scale;
-
+
const long det_dx = nearest<long> (xInc * cos (theta) / detInc * scale);
const long det_dy = nearest<long> (yInc * sin (theta) / detInc * scale);
-
- // calculate L for first point in image (0, 0)
+
+ // calculate L for first point in image (0, 0)
long detPosColStart = nearest<long> ((start_r * cos (theta - start_phi) / detInc + iDetCenter) * scale);
-
- double* deltaFilteredProj = NULL;
+
+ double* deltaFilteredProj = NULL;
CubicPolyInterpolator* pCubicInterp = NULL;
if (interpType == Backprojector::INTERP_LINEAR) {
// precalculate scaled difference for linear interpolation
} else if (interpType == Backprojector::INTERP_CUBIC) {
pCubicInterp = new CubicPolyInterpolator (filteredProj, nDet);
}
-
+
int iLastDet = nDet - 1;
for (int ix = 0; ix < nx; ix++, detPosColStart += det_dx) {
long curDetPos = detPosColStart;
ImageFileColumn pImCol = v[ix];
-
+
if (interpType == Backprojector::INTERP_NEAREST) {
for (int iy = 0; iy < ny; iy++, curDetPos += det_dy) {
const int iDetPos = (curDetPos + halfScale) >> scaleShift;
else
pImCol++;
- } // end for iy
+ } // end for iy
} else if (interpType == Backprojector::INTERP_FREQ_PREINTERPOLATION) {
for (int iy = 0; iy < ny; iy++, curDetPos += det_dy) {
const int iDetPos = ((curDetPos + halfScale) >> scaleShift) * m_interpFactor;
*pImCol++ += filteredProj[iDetPos];
else
pImCol++;
- } // end for iy
+ } // end for iy
} else if (interpType == Backprojector::INTERP_LINEAR) {
for (int iy = 0; iy < ny; iy++, curDetPos += det_dy) {
const long iDetPos = curDetPos >> scaleShift;
if (iDetPos >= 0 && iDetPos <= iLastDet) {
- const long detRemainder = curDetPos & scaleBitmask;
- *pImCol++ += filteredProj[iDetPos] + (detRemainder * deltaFilteredProj[iDetPos]);
- } else
+ const long detRemainder = curDetPos & scaleBitmask;
+ *pImCol++ += filteredProj[iDetPos] + (detRemainder * deltaFilteredProj[iDetPos]);
+ } else
pImCol++;
- } // end for iy
+ } // end for iy
} else if (interpType == Backprojector::INTERP_CUBIC) {
for (int iy = 0; iy < ny; iy++, curDetPos += det_dy) {
*pImCol++ += pCubicInterp->interpolate (static_cast<double>(curDetPos) / scale);
}
} // end Cubic
} // end for ix
-
+
if (interpType == Backprojector::INTERP_LINEAR)
delete deltaFilteredProj;
else if (interpType == Backprojector::INTERP_CUBIC)
BackprojectEquiangular::BackprojectView (const double* const filteredProj, const double view_angle)
{
double beta = view_angle;
-
+
CubicPolyInterpolator* pCubicInterp = NULL;
if (interpType == Backprojector::INTERP_CUBIC)
pCubicInterp = new CubicPolyInterpolator (filteredProj, nDet);
-
+
for (int ix = 0; ix < nx; ix++) {
ImageFileColumn pImCol = v[ix];
-
- for (int iy = 0; iy < ny; iy++) {
+
+ for (int iy = 0; iy < ny; iy++) {
double dAngleDiff = beta - phi[ix][iy];
double rcos_t = r[ix][iy] * cos (dAngleDiff);
double rsin_t = r[ix][iy] * sin (dAngleDiff);
double gamma = atan (rcos_t / dFLPlusSin);
double dPos = gamma / detInc; // position along detector
double dL2 = dFLPlusSin * dFLPlusSin + (rcos_t * rcos_t);
-
+
if (interpType == Backprojector::INTERP_NEAREST) {
- int iDetPos = iDetCenter + nearest<int>(dPos); // calc index in the filtered raysum vector
+ int iDetPos = iDetCenter + nearest<int>(dPos); // calc index in the filtered raysum vector
if (iDetPos >= 0 && iDetPos < nDet)
pImCol[iy] += filteredProj[iDetPos] / dL2;
} else if (interpType == Backprojector::INTERP_LINEAR) {
double dPosFloor = floor (dPos);
int iDetPos = iDetCenter + static_cast<int>(dPosFloor);
- double frac = dPos - dPosFloor; // fraction distance from det
+ double frac = dPos - dPosFloor; // fraction distance from det
if (iDetPos >= 0 && iDetPos < nDet - 1)
pImCol[iy] += (filteredProj[iDetPos] + frac * (filteredProj[iDetPos+1] - filteredProj[iDetPos])) / dL2;
} else if (interpType == Backprojector::INTERP_CUBIC) {
- double d = iDetCenter + dPos; // position along detector
+ double d = iDetCenter + dPos; // position along detector
if (d >= 0 && d < nDet)
pImCol[iy] += pCubicInterp->interpolate (d) / dL2;
}
- } // end for y
- } // end for x
+ } // end for y
+ } // end for x
if (interpType == Backprojector::INTERP_CUBIC)
delete pCubicInterp;
BackprojectEquilinear::BackprojectView (const double* const filteredProj, const double view_angle)
{
double beta = view_angle;
-
+
CubicPolyInterpolator* pCubicInterp = NULL;
if (interpType == Backprojector::INTERP_CUBIC)
pCubicInterp = new CubicPolyInterpolator (filteredProj, nDet);
-
+
for (int ix = 0; ix < nx; ix++) {
ImageFileColumn pImCol = v[ix];
-
+
for (int iy = 0; iy < ny; iy++) {
double dAngleDiff = beta - phi[ix][iy];
double rcos_t = r[ix][iy] * cos (dAngleDiff);
double rsin_t = r[ix][iy] * sin (dAngleDiff);
-
+
double dU = (m_dFocalLength + rsin_t) / m_dFocalLength;
double dDetPos = rcos_t / dU;
- // Scale for imaginary detector that passes through origin of phantom, see Kak-Slaney Figure 3.22.
- dDetPos *= m_dSourceDetectorLength / m_dFocalLength;
- double dPos = dDetPos / detInc; // position along detector array
+ // Scale for imaginary detector that passes through origin of phantom, see Kak-Slaney Figure 3.22.
+ dDetPos *= m_dSourceDetectorLength / m_dFocalLength;
+ double dPos = dDetPos / detInc; // position along detector array
if (interpType == Backprojector::INTERP_NEAREST) {
- int iDetPos = iDetCenter + nearest<int>(dPos); // calc index in the filtered raysum vector
- if (iDetPos >= 0 && iDetPos < nDet)
+ int iDetPos = iDetCenter + nearest<int>(dPos); // calc index in the filtered raysum vector
+ if (iDetPos >= 0 && iDetPos < nDet)
pImCol[iy] += (filteredProj[iDetPos] / (dU * dU));
} else if (interpType == Backprojector::INTERP_LINEAR) {
double dPosFloor = floor (dPos);
int iDetPos = iDetCenter + static_cast<int>(dPosFloor);
- double frac = dPos - dPosFloor; // fraction distance from det
+ double frac = dPos - dPosFloor; // fraction distance from det
if (iDetPos >= 0 && iDetPos < nDet - 1)
pImCol[iy] += (filteredProj[iDetPos] + frac * (filteredProj[iDetPos+1] - filteredProj[iDetPos]))
/ (dU * dU);
} else if (interpType == Backprojector::INTERP_CUBIC) {
- double d = iDetCenter + dPos; // position along detector
+ double d = iDetCenter + dPos; // position along detector
if (d >= 0 && d < nDet)
pImCol[iy] += pCubicInterp->interpolate (d) / (dU * dU);
}
- } // end for y
- } // end for x
+ } // end for y
+ } // end for x
if (interpType == Backprojector::INTERP_CUBIC)
delete pCubicInterp;
/*****************************************************************************
** FILE IDENTIFICATION
**
-** Name: ctndicomp.cpp
+** Name: ctndicomp.cpp
** Purpose: Interface to CTN Dicom classes
-** Programmer: Kevin Rosenberg
-** Date Started: March 2001
+** Programmer: Kevin Rosenberg
+** Date Started: March 2001
**
** This is part of the CTSim program
** Copyright (c) 1983-2001 Kevin Rosenberg
#ifdef HAVE_CTN_DICOM
-#include "ctndicom.h"
+#include "ctndicom.h"
#include "imagefile.h"
#include "projections.h"
DicomImporter::DicomImporter (const char* const pszFile)
- : m_strFilename(pszFile), m_bFail(false), m_iContents(DICOM_CONTENTS_INVALID),
+ : m_strFilename(pszFile), m_bFail(false), m_iContents(DICOM_CONTENTS_INVALID),
m_pImageFile(NULL), m_pProjections(NULL), m_pFile(NULL)
{
unsigned long lOptions = DCM_ORDERLITTLEENDIAN | DCM_FORMATCONVERSION;
CONDITION cond = DCM_OpenFile (pszFile, lOptions, &m_pFile);
if (cond != DCM_NORMAL) {
m_bFail = true;
- char textbuf [2048];
+ char textbuf [2048];
CONDITION cond2 = COND_TopCondition (&cond, textbuf, sizeof(textbuf));
cond2 = DCM_NORMAL; // testing
if (cond2 != DCM_NORMAL) {
unsigned short iNRows, iNCols, iBitsAllocated, iBitsStored, iHighBit, iPixRep;
DCM_ELEMENT aElemRequired[] = {
- {DCM_IMGROWS, DCM_US, "", 1, sizeof(iNRows),
+ {DCM_IMGROWS, DCM_US, "", 1, sizeof(iNRows),
{reinterpret_cast<char*>(&iNRows)}},
- {DCM_IMGCOLUMNS, DCM_US, "", 1, sizeof(iNCols),
+ {DCM_IMGCOLUMNS, DCM_US, "", 1, sizeof(iNCols),
{reinterpret_cast<char*>(&iNCols)}},
- {DCM_IMGBITSALLOCATED, DCM_US, "", 1, sizeof(iBitsAllocated),
+ {DCM_IMGBITSALLOCATED, DCM_US, "", 1, sizeof(iBitsAllocated),
{reinterpret_cast<char*>(&iBitsAllocated)}},
- {DCM_IMGBITSSTORED, DCM_US, "", 1, sizeof(iBitsStored),
+ {DCM_IMGBITSSTORED, DCM_US, "", 1, sizeof(iBitsStored),
{reinterpret_cast<char*>(&iBitsStored)}},
- {DCM_IMGHIGHBIT, DCM_US, "", 1, sizeof(iHighBit),
+ {DCM_IMGHIGHBIT, DCM_US, "", 1, sizeof(iHighBit),
{reinterpret_cast<char*>(&iHighBit)}},
- {DCM_IMGPIXELREPRESENTATION, DCM_US, "", 1, sizeof(iPixRep),
+ {DCM_IMGPIXELREPRESENTATION, DCM_US, "", 1, sizeof(iPixRep),
{reinterpret_cast<char*>(&iPixRep)}},
};
int nElemRequired = sizeof (aElemRequired) / sizeof(DCM_ELEMENT);
}
void
-DicomImporter::loadImage(unsigned short iNRows, unsigned short iNCols, unsigned short iBitsAllocated,
+DicomImporter::loadImage(unsigned short iNRows, unsigned short iNCols, unsigned short iBitsAllocated,
unsigned short iBitsStored, unsigned short iHighBit, unsigned short iPixRep)
{
U32 lRtnLength;
unsigned short iSamplesPerPixel, iPlanarConfig;
-
- DCM_ELEMENT elemPlanarConfig =
- {DCM_IMGPLANARCONFIGURATION, DCM_US, "", 1, sizeof(iPlanarConfig),
+
+ DCM_ELEMENT elemPlanarConfig =
+ {DCM_IMGPLANARCONFIGURATION, DCM_US, "", 1, sizeof(iPlanarConfig),
{reinterpret_cast<char*>(&iPlanarConfig)}};
- DCM_ELEMENT elemSamplesPerPixel =
- {DCM_IMGSAMPLESPERPIXEL, DCM_US, "", 1,
+ DCM_ELEMENT elemSamplesPerPixel =
+ {DCM_IMGSAMPLESPERPIXEL, DCM_US, "", 1,
sizeof(iSamplesPerPixel), {reinterpret_cast<char*>(&iSamplesPerPixel)}};
if (DCM_ParseObject (&m_pFile, &elemSamplesPerPixel, 1, NULL, 0, NULL) != DCM_NORMAL)
char szRescaleIntercept[17];
double dRescaleSlope = 1;
double dRescaleIntercept = 0;
- DCM_ELEMENT elemRescaleSlope =
- {DCM_IMGRESCALESLOPE, DCM_DS, "", 1, strlen(szRescaleSlope),
+ DCM_ELEMENT elemRescaleSlope =
+ {DCM_IMGRESCALESLOPE, DCM_DS, "", 1, strlen(szRescaleSlope),
{szRescaleSlope}};
- DCM_ELEMENT elemRescaleIntercept =
- {DCM_IMGRESCALEINTERCEPT, DCM_DS, "", 1, strlen(szRescaleIntercept),
+ DCM_ELEMENT elemRescaleIntercept =
+ {DCM_IMGRESCALEINTERCEPT, DCM_DS, "", 1, strlen(szRescaleIntercept),
{szRescaleIntercept}};
if (DCM_ParseObject (&m_pFile, &elemRescaleSlope, 1, NULL, 0, NULL) == DCM_NORMAL) {
if (sscanf (szRescaleSlope, "%lf", &dRescaleSlope) != 1)
unsigned char* pRawPixels = new unsigned char [lCheckLengthInBytes];
elemPixelData.length = lCheckLengthInBytes;
elemPixelData.d.ot = pRawPixels;
-
+
void* ctx = NULL;
CONDITION cond = DCM_GetElementValue (&m_pFile, &elemPixelData, &lRtnLength, &ctx);
if ((cond != DCM_NORMAL) && (cond != DCM_GETINCOMPLETE)) {
unsigned short iNViews, iNDets;
DCM_ELEMENT aElemRequired[] = {
- {DCM_IMGROWS, DCM_US, "", 1, sizeof(iNViews),
+ {DCM_IMGROWS, DCM_US, "", 1, sizeof(iNViews),
{reinterpret_cast<char*>(&iNViews)}},
- {DCM_IMGCOLUMNS, DCM_US, "", 1, sizeof(iNDets),
+ {DCM_IMGCOLUMNS, DCM_US, "", 1, sizeof(iNDets),
{reinterpret_cast<char*>(&iNDets)}},
};
int nElemRequired = sizeof (aElemRequired) / sizeof(DCM_ELEMENT);
unsigned char* pRawProjections = new unsigned char [lRtnLength];
elemProjections.length = lRtnLength;
elemProjections.d.ot = pRawProjections;
-
+
ctx = NULL;
CONDITION cond = DCM_GetElementValue (&m_pFile, &elemProjections, &lRtnLength, &ctx);
if ((cond != DCM_NORMAL) && (cond != DCM_GETINCOMPLETE)) {
unsigned short iPixRep = 0;
unsigned short iSamplesPerPixel = 1;
DCM_ELEMENT aElemRequired[] = {
- {DCM_IMGROWS, DCM_US, "", 1, sizeof(iNRows),
+ {DCM_IMGROWS, DCM_US, "", 1, sizeof(iNRows),
{reinterpret_cast<char*>(&iNRows)}},
- {DCM_IMGCOLUMNS, DCM_US, "", 1, sizeof(iNCols),
+ {DCM_IMGCOLUMNS, DCM_US, "", 1, sizeof(iNCols),
{reinterpret_cast<char*>(&iNCols)}},
- {DCM_IMGBITSALLOCATED, DCM_US, "", 1, sizeof(iBitsAllocated),
+ {DCM_IMGBITSALLOCATED, DCM_US, "", 1, sizeof(iBitsAllocated),
{reinterpret_cast<char*>(&iBitsAllocated)}},
- {DCM_IMGBITSSTORED, DCM_US, "", 1, sizeof(iBitsStored),
+ {DCM_IMGBITSSTORED, DCM_US, "", 1, sizeof(iBitsStored),
{reinterpret_cast<char*>(&iBitsStored)}},
- {DCM_IMGHIGHBIT, DCM_US, "", 1, sizeof(iHighBit),
+ {DCM_IMGHIGHBIT, DCM_US, "", 1, sizeof(iHighBit),
{reinterpret_cast<char*>(&iHighBit)}},
- {DCM_IMGPIXELREPRESENTATION, DCM_US, "", 1, sizeof(iPixRep),
+ {DCM_IMGPIXELREPRESENTATION, DCM_US, "", 1, sizeof(iPixRep),
{reinterpret_cast<char*>(&iPixRep)}},
- {DCM_IMGSAMPLESPERPIXEL, DCM_US, "", 1, sizeof(iSamplesPerPixel),
+ {DCM_IMGSAMPLESPERPIXEL, DCM_US, "", 1, sizeof(iSamplesPerPixel),
{reinterpret_cast<char*>(&iSamplesPerPixel)}},
- {DCM_IMGRESCALESLOPE, DCM_DS, "", 1, strlen(szRescaleSlope),
+ {DCM_IMGRESCALESLOPE, DCM_DS, "", 1, strlen(szRescaleSlope),
{szRescaleSlope}},
- {DCM_IMGRESCALEINTERCEPT, DCM_DS, "", 1, strlen(szRescaleIntercept),
+ {DCM_IMGRESCALEINTERCEPT, DCM_DS, "", 1, strlen(szRescaleIntercept),
{szRescaleIntercept}},
- {DCM_IMGPHOTOMETRICINTERP, DCM_CS, "", 1, strlen(szImgPhotometricInterp),
+ {DCM_IMGPHOTOMETRICINTERP, DCM_CS, "", 1, strlen(szImgPhotometricInterp),
{szImgPhotometricInterp}},
- {DCM_IMGPIXELSPACING, DCM_DS, "", 1, strlen(szPixelSpacing),
+ {DCM_IMGPIXELSPACING, DCM_DS, "", 1, strlen(szPixelSpacing),
{szPixelSpacing}},
- {DCM_RELIMAGEORIENTATIONPATIENT, DCM_DS, "", 1,
+ {DCM_RELIMAGEORIENTATIONPATIENT, DCM_DS, "", 1,
strlen(szRelImageOrientationPatient), {szRelImageOrientationPatient}},
- {DCM_RELIMAGEPOSITIONPATIENT, DCM_DS, "", 1,
+ {DCM_RELIMAGEPOSITIONPATIENT, DCM_DS, "", 1,
strlen(szRelImagePositionPatient), {szRelImagePositionPatient}},
{DCM_ACQKVP, DCM_DS, "", 1, strlen(szAcqKvp), {szAcqKvp}},
- {DCM_RELACQUISITIONNUMBER, DCM_IS, "", 1, strlen(szRelAcquisitionNumber),
+ {DCM_RELACQUISITIONNUMBER, DCM_IS, "", 1, strlen(szRelAcquisitionNumber),
{szRelAcquisitionNumber}},
- {DCM_ACQSLICETHICKNESS, DCM_DS, "", 1, strlen(szRelAcquisitionNumber),
+ {DCM_ACQSLICETHICKNESS, DCM_DS, "", 1, strlen(szRelAcquisitionNumber),
{szRelAcquisitionNumber}},
- {DCM_RELIMAGENUMBER, DCM_IS, "", 1, strlen(szRelImageNumber),
+ {DCM_RELIMAGENUMBER, DCM_IS, "", 1, strlen(szRelImageNumber),
{szRelImageNumber}},
- {DCM_IDSOPINSTANCEUID, DCM_UI, "", 1, strlen(szIDSOPInstanceUID),
+ {DCM_IDSOPINSTANCEUID, DCM_UI, "", 1, strlen(szIDSOPInstanceUID),
{szIDSOPInstanceUID}},
- {DCM_IDMANUFACTURER, DCM_LO, "", 1, strlen(szIDManufacturer),
+ {DCM_IDMANUFACTURER, DCM_LO, "", 1, strlen(szIDManufacturer),
{szIDManufacturer}},
- {DCM_RELPOSITIONREFINDICATOR, DCM_LO, "", 1,
+ {DCM_RELPOSITIONREFINDICATOR, DCM_LO, "", 1,
strlen(szRelPositionRefIndicator), {szRelPositionRefIndicator}},
- {DCM_RELFRAMEOFREFERENCEUID, DCM_UI, "", 1,
+ {DCM_RELFRAMEOFREFERENCEUID, DCM_UI, "", 1,
strlen(szRelFrameOfReferenceUID), {szRelFrameOfReferenceUID}},
- {DCM_RELSERIESNUMBER, DCM_IS, "", 1, strlen(szRelSeriesNumber),
+ {DCM_RELSERIESNUMBER, DCM_IS, "", 1, strlen(szRelSeriesNumber),
{szRelSeriesNumber}},
- {DCM_RELSERIESINSTANCEUID, DCM_UI, "", 1, strlen(szIDAccessionNumber),
+ {DCM_RELSERIESINSTANCEUID, DCM_UI, "", 1, strlen(szIDAccessionNumber),
{szIDAccessionNumber}},
- {DCM_IDACCESSIONNUMBER, DCM_SH, "", 1, strlen(szIDAccessionNumber),
+ {DCM_IDACCESSIONNUMBER, DCM_SH, "", 1, strlen(szIDAccessionNumber),
{szIDAccessionNumber}},
{DCM_RELSTUDYID, DCM_SH, "", 1, strlen(szRelStudyID), {szRelStudyID}},
- {DCM_IDREFERRINGPHYSICIAN, DCM_PN, "", 1, strlen(szIDReferringPhysician),
+ {DCM_IDREFERRINGPHYSICIAN, DCM_PN, "", 1, strlen(szIDReferringPhysician),
{szIDReferringPhysician}},
{DCM_IDSTUDYTIME, DCM_TM, "", 1, strlen(szIDStudyTime), {szIDStudyTime}},
{DCM_IDSTUDYDATE, DCM_DA, "", 1, strlen(szIDStudyDate), {szIDStudyDate}},
- {DCM_RELSTUDYINSTANCEUID, DCM_UI, "", 1, strlen(szRelStudyInstanceUID),
+ {DCM_RELSTUDYINSTANCEUID, DCM_UI, "", 1, strlen(szRelStudyInstanceUID),
{szRelStudyInstanceUID}},
{DCM_PATSEX, DCM_CS, "", 1, strlen(szPatSex), {szPatSex}},
{DCM_PATBIRTHDATE, DCM_DA, "", 1, strlen(szPatBirthdate), {szPatBirthdate}},
{DCM_IDIMAGETYPE, DCM_CS, "", 1, strlen(szIDImageType), {szIDImageType}},
{DCM_IDMODALITY, DCM_CS, "", 1, strlen(szModality), {szModality}},
{DCM_IDSOPCLASSUID, DCM_UI, "", 1, strlen(szSOPClassUID), {szSOPClassUID}},
- {DCM_IDMANUFACTURERMODEL, DCM_LO, "", 1, strlen(szIDManufacturerModel),
+ {DCM_IDMANUFACTURERMODEL, DCM_LO, "", 1, strlen(szIDManufacturerModel),
{szIDManufacturerModel}},
{DCM_PATCOMMENTS, DCM_LT, "", 1, strlen(pszPatComments), {pszPatComments}},
};
unsigned char* pRawPixels = new unsigned char [lRealLength];
elemPixelData.length = lRealLength;
elemPixelData.d.ot = pRawPixels;
-
+
ImageFileArray v = m_pImageFile->getArray();
for (int iy = 0; iy < iNRows; iy++) {
for (int ix = 0; ix < iNCols; ix++) {
/*****************************************************************************
** File IDENTIFICATION
-**
+**
** Name: filter.cpp
** Purpose: Routines for signal-procesing filters
-** Progammer: Kevin Rosenberg
+** Progammer: Kevin Rosenberg
** Date Started: Aug 1984
**
** This is part of the CTSim program
int SignalFilter::N_INTEGRAL=500; //static member
const int SignalFilter::FILTER_INVALID = -1 ;
-const int SignalFilter::FILTER_ABS_BANDLIMIT = 0; // filter times |x|
+const int SignalFilter::FILTER_ABS_BANDLIMIT = 0; // filter times |x|
const int SignalFilter::FILTER_ABS_G_HAMMING = 1;
const int SignalFilter::FILTER_ABS_HANNING = 2;
const int SignalFilter::FILTER_ABS_COSINE = 3;
*
* SYNOPSIS
* f = SignalFilter (filt_type, bw, filterMin, filterMax, n, param, domain, analytic)
-* double f Generated filter vector
-* int filt_type Type of filter wanted
-* double bw Bandwidth of filter
-* double filterMin, filterMax Filter limits
-* int nFilterPoints Number of points in signal
-* double param General input parameter to filters
-* int domain FREQUENCY or SPATIAL domain wanted
+* double f Generated filter vector
+* int filt_type Type of filter wanted
+* double bw Bandwidth of filter
+* double filterMin, filterMax Filter limits
+* int nFilterPoints Number of points in signal
+* double param General input parameter to filters
+* int domain FREQUENCY or SPATIAL domain wanted
*/
SignalFilter::SignalFilter (const char* szFilterName, double dFilterMinimum, double dFilterMaximum, int nFilterPoints, double dBandwidth, double dFilterParam, const char* szDomainName)
{
m_nFilterPoints = 0;
m_dBandwidth = dBandwidth;
- m_dFilterParam = dFilterParam;
+ m_dFilterParam = dFilterParam;
m_idFilter = convertFilterNameToID (szFilterName);
if (m_idFilter == FILTER_INVALID) {
m_fail = true;
m_failMessage = " less than 2";
return;
}
-
+
m_nameFilter = convertFilterIDToName (m_idFilter);
m_nameDomain = convertDomainIDToName (m_idDomain);
m_nFilterPoints = nFilterPoints;
- m_dFilterParam = dFilterParam;
+ m_dFilterParam = dFilterParam;
m_dBandwidth = dBandwidth;
m_dFilterMin = dFilterMinimum;
m_dFilterMax = dFilterMaximum;
-
+
m_dFilterInc = (m_dFilterMax - m_dFilterMin) / (m_nFilterPoints - 1);
m_adFilter = new double [m_nFilterPoints];
-
+
if (m_idDomain == DOMAIN_FREQUENCY)
createFrequencyFilter (m_adFilter);
else if (m_idDomain == DOMAIN_SPATIAL)
int center = (m_nFilterPoints - 1) / 2;
int sidelen = center;
m_adFilter[center] = 4. / (a * a);
-
+
for (int i = 1; i <= sidelen; i++ )
m_adFilter [center + i] = m_adFilter [center - i] = c / (4 * (i * i) - 1);
} else {
SignalFilter::convertFilterNameToID (const char *filterName)
{
int filterID = FILTER_INVALID;
-
+
for (int i = 0; i < s_iFilterCount; i++)
if (strcasecmp (filterName, s_aszFilterName[i]) == 0) {
filterID = i;
break;
}
-
+
return (filterID);
}
SignalFilter::convertFilterIDToName (const int filterID)
{
static const char *name = "";
-
+
if (filterID >= 0 && filterID < s_iFilterCount)
return (s_aszFilterName [filterID]);
-
+
return (name);
}
SignalFilter::convertFilterIDToTitle (const int filterID)
{
static const char *title = "";
-
+
if (filterID >= 0 && filterID < s_iFilterCount)
return (s_aszFilterTitle [filterID]);
-
+
return (title);
}
SignalFilter::convertDomainNameToID (const char* const domainName)
{
int dID = DOMAIN_INVALID;
-
+
for (int i = 0; i < s_iDomainCount; i++)
if (strcasecmp (domainName, s_aszDomainName[i]) == 0) {
dID = i;
break;
}
-
+
return (dID);
}
SignalFilter::convertDomainIDToName (const int domainID)
{
static const char *name = "";
-
+
if (domainID >= 0 && domainID < s_iDomainCount)
return (s_aszDomainName [domainID]);
-
+
return (name);
}
SignalFilter::convertDomainIDToTitle (const int domainID)
{
static const char *title = "";
-
+
if (domainID >= 0 && domainID < s_iDomainCount)
return (s_aszDomainTitle [domainID]);
-
+
return (title);
}
SignalFilter::response (double x)
{
double response = 0;
-
+
if (m_idDomain == DOMAIN_SPATIAL)
response = spatialResponse (m_idFilter, m_dBandwidth, x, m_dFilterParam);
else if (m_idDomain == DOMAIN_FREQUENCY)
response = frequencyResponse (m_idFilter, m_dBandwidth, x, m_dFilterParam);
-
+
return (response);
}
-double
+double
SignalFilter::spatialResponse (int filterID, double bw, double x, double param)
{
if (haveAnalyticSpatial(filterID))
{
int iFirst = clamp (iStart, 0, m_nFilterPoints - 1);
int iLast = clamp (iFirst + nPoints - 1, 0, m_nFilterPoints - 1);
-
+
for (int i = iFirst; i <= iLast; i++)
pdFilter[i - iFirst] = m_adFilter[i];
}
/* NAME
-* filter_spatial_response_calc Calculate filter by discrete inverse fourier
-* transform of filters's frequency
-* response
+* filter_spatial_response_calc Calculate filter by discrete inverse fourier
+* transform of filters's frequency
+* response
*
* SYNOPSIS
* y = filter_spatial_response_calc (filt_type, x, m_bw, param, n)
-* double y Filter's response in spatial domain
-* int filt_type Type of filter (definitions in ct.h)
-* double x Spatial position to evaluate filter
-* double m_bw Bandwidth of window
-* double param General parameter for various filters
-* int n Number of points to calculate integrations
+* double y Filter's response in spatial domain
+* int filt_type Type of filter (definitions in ct.h)
+* double x Spatial position to evaluate filter
+* double m_bw Bandwidth of window
+* double param General parameter for various filters
+* int n Number of points to calculate integrations
*/
-double
+double
SignalFilter::spatialResponseCalc (double x) const
{
return (spatialResponseCalc (m_idFilter, m_dBandwidth, x, m_dFilterParam, N_INTEGRAL));
}
-double
+double
SignalFilter::spatialResponseCalc (int filterID, double bw, double x, double param, int n)
{
double zmin, zmax;
-
+
if (filterID == FILTER_TRIANGLE) {
zmin = 0;
zmax = bw;
zmax = bw / 2;
}
double zinc = (zmax - zmin) / (n - 1);
-
+
double z = zmin;
double* q = new double [n];
for (int i = 0; i < n; i++, z += zinc)
q[i] = frequencyResponse (filterID, bw, z, param) * cos (TWOPI * z * x);
-
+
double y = 2 * integrateSimpson (zmin, zmax, q, n);
delete q;
-
+
return (y);
}
/* NAME
-* filter_frequency_response Return filter frequency response
+* filter_frequency_response Return filter frequency response
*
* SYNOPSIS
* h = filter_frequency_response (filt_type, u, m_bw, param)
-* double h Filters frequency response at u
-* int filt_type Type of filter
-* double u Frequency to evaluate filter at
-* double m_bw Bandwidth of filter
-* double param General input parameter for various filters
+* double h Filters frequency response at u
+* int filt_type Type of filter
+* double u Frequency to evaluate filter at
+* double m_bw Bandwidth of filter
+* double param General input parameter for various filters
*/
-double
+double
SignalFilter::frequencyResponse (double u) const
{
return frequencyResponse (m_idFilter, m_dBandwidth, u, m_dFilterParam);
}
-double
+double
SignalFilter::frequencyResponse (int filterID, double bw, double u, double param)
{
double q;
double au = fabs (u);
double abw = fabs (bw);
-
+
switch (filterID) {
case FILTER_BANDLIMIT:
if (au >= (abw / 2) + F_EPSILON)
q = au * abw * sinc (PI * abw * au, 1.);
break;
case FILTER_HANNING:
- param = 0.5;
+ param = 0.5;
// follow through to G_HAMMING
case FILTER_G_HAMMING:
if (au >= (abw / 2) + F_EPSILON)
sys_error (ERR_WARNING, "Frequency response for filter %d not implemented [filter_frequency_response]", filterID);
break;
}
-
+
return (q);
}
/* NAME
-* filter_spatial_response_analytic Calculate filter by analytic inverse fourier
-* transform of filters's frequency
-* response
+* filter_spatial_response_analytic Calculate filter by analytic inverse fourier
+* transform of filters's frequency
+* response
*
* SYNOPSIS
* y = filter_spatial_response_analytic (filt_type, x, m_bw, param)
-* double y Filter's response in spatial domain
-* int filt_type Type of filter (definitions in ct.h)
-* double x Spatial position to evaluate filter
-* double m_bw Bandwidth of window
-* double param General parameter for various filters
+* double y Filter's response in spatial domain
+* int filt_type Type of filter (definitions in ct.h)
+* double x Spatial position to evaluate filter
+* double m_bw Bandwidth of window
+* double param General parameter for various filters
*/
-double
+double
SignalFilter::spatialResponseAnalytic (double x) const
{
return spatialResponseAnalytic (m_idFilter, m_dBandwidth, x, m_dFilterParam);
SignalFilter::haveAnalyticSpatial (int filterID)
{
bool haveAnalytic = false;
-
+
switch (filterID) {
case FILTER_BANDLIMIT:
case FILTER_TRIANGLE:
default:
break;
}
-
+
return (haveAnalytic);
}
-double
+double
SignalFilter::spatialResponseAnalytic (int filterID, double bw, double x, double param)
{
double q, temp;
double w = bw / 2;
double b = PI / bw;
double b2 = TWOPI / bw;
-
+
switch (filterID) {
case FILTER_BANDLIMIT:
q = bw * sinc(u * w, 1.0);
q = 0;
break;
}
-
+
return (q);
}
// Functions that are inline in filter.h
-// sinc Return sin(x)/x function
+// sinc Return sin(x)/x function
// v = sinc (x, mult)
// Calculates sin(x * mult) / x;
-// integral_abscos Returns integral of u*cos(u)
+// integral_abscos Returns integral of u*cos(u)
//
// q = integral_abscos (u, w)
-// double q Integral value
-// double u Integration variable
-// double w Upper integration boundary
+// double q Integral value
+// double u Integration variable
+// double w Upper integration boundary
// Returns the value of integral of u*cos(u)*dV for V = 0 to w
}
#ifdef HAVE_FFTW
-void Fourier::shuffleNaturalToFourierOrder (fftw_complex* pVector, const int n)
+void Fourier::shuffleNaturalToFourierOrder (fftw_complex* pVector, const int n)
{
fftw_complex* pTemp = static_cast<fftw_complex*>(fftw_malloc(sizeof(fftw_complex) * n));
int i;
-
+
if (isOdd(n)) { // Odd
int iHalfN = (n - 1) / 2;
-
+
pTemp[0][0] = pVector[iHalfN][0];
pTemp[0][1] = pVector[iHalfN][1];
for (i = 0; i < iHalfN; i++) {
pTemp[i + iHalfN][1] = pVector[i][1];
}
}
-
+
for (i = 0; i < n; i++) {
pVector[i][0] = pTemp[i][0];
pVector[i][1] = pTemp[i][1];
int i;
if (isOdd(n)) { // Odd
int iHalfN = (n - 1) / 2;
-
+
pTemp[iHalfN][0] = pVector[0][0];
pTemp[iHalfN][1] = pVector[0][1];
for (i = 0; i < iHalfN; i++) {
pTemp[i + iHalfN + 1][1] = pVector[i+1][1];
}
}
-
+
for (i = 0; i < n; i++) {
pVector[i][0] = pTemp[i][0];
pVector[i][1] = pTemp[i][1];
}
-
+
fftw_free(pTemp);
}
#endif
/*****************************************************************************
** FILE IDENTIFICATION
**
-** Name: imagefile.cpp
+** Name: imagefile.cpp
** Purpose: Imagefile classes
-** Programmer: Kevin Rosenberg
-** Date Started: June 2000
+** Programmer: Kevin Rosenberg
+** Date Started: June 2000
**
** This is part of the CTSim program
** Copyright (c) 1983-2001 Kevin Rosenberg
#endif
const int ImageFile::EXPORT_FORMAT_RAW = 6;
-const char* ImageFile::s_aszExportFormatName[] =
+const char* ImageFile::s_aszExportFormatName[] =
{
"text",
"pgm",
#endif
};
-const char* ImageFile::s_aszExportFormatTitle[] =
+const char* ImageFile::s_aszExportFormatTitle[] =
{
"Text",
"PGM",
#endif
-const char* ImageFile::s_aszImportFormatName[] =
+const char* ImageFile::s_aszImportFormatName[] =
{
"ppm",
#ifdef HAVE_PNG
#endif
};
-const char* ImageFile::s_aszImportFormatTitle[] =
+const char* ImageFile::s_aszImportFormatTitle[] =
{
"PPM",
#ifdef HAVE_PNG
setDataType (Array2dFile::DATA_TYPE_REAL);
}
-void
+void
ImageFile::getCenterCoordinates (unsigned int& iXCenter, unsigned int& iYCenter)
{
if (isEven (m_nx))
iXCenter = m_nx / 2;
else
iXCenter = (m_nx - 1) / 2;
-
+
if (isEven (m_ny))
iYCenter = m_ny / 2;
else
}
-void
-ImageFile::filterResponse (const char* const domainName, double bw, const char* const filterName,
+void
+ImageFile::filterResponse (const char* const domainName, double bw, const char* const filterName,
double filt_param, double dInputScale, double dOutputScale)
{
ImageFileArray v = getArray();
SignalFilter filter (filterName, domainName, bw, filt_param);
-
+
unsigned int iXCenter, iYCenter;
getCenterCoordinates (iXCenter, iYCenter);
-
+
for (unsigned int ix = 0; ix < m_nx; ix++)
for (unsigned int iy = 0; iy < m_ny; iy++) {
long lD2 = ((ix - iXCenter) * (ix - iXCenter)) + ((iy - iYCenter) * (iy - iYCenter));
ImageFileArrayConst v = getArray();
if (v == NULL || m_nx == 0 || m_ny == 0)
return false;
-
+
ImageFileArrayConst vComp = imComp.getArray();
-
+
double myMean = 0.;
for (unsigned int ix = 0; ix < m_nx; ix++) {
for (unsigned int iy = 0; iy < m_ny; iy++) {
}
}
myMean /= (m_nx * m_ny);
-
+
double sqErrorSum = 0.;
double absErrorSum = 0.;
double sqDiffFromMeanSum = 0.;
absValueSum += fabs(v[ix2][iy]);
}
}
-
+
d = ::sqrt (sqErrorSum / sqDiffFromMeanSum);
r = absErrorSum / absValueSum;
-
+
int hx = m_nx / 2;
int hy = m_ny / 2;
double eMax = -1;
eMax = error;
}
}
-
+
e = eMax;
-
+
return true;
}
ImageFile::printComparativeStatistics (const ImageFile& imComp, std::ostream& os) const
{
double d, r, e;
-
+
if (comparativeStatistics (imComp, d, r, e)) {
os << " Normalized root mean squared distance (d): " << d << std::endl;
os << " Normalized mean absolute distance (r): " << r << std::endl;
ImageFile::printStatistics (std::ostream& os) const
{
double min, max, mean, mode, median, stddev;
-
+
statistics (min, max, mean, mode, median, stddev);
if (isComplex())
os << "Real Component Statistics" << std::endl;
-
+
os << " min: " << min << std::endl;
os << " max: " << max << std::endl;
os << " mean: " << mean << std::endl;
os << " mode: " << mode << std::endl;
os << "median: " << median << std::endl;
os << "stddev: " << stddev << std::endl;
-
+
if (isComplex()) {
statistics (getImaginaryArray(), min, max, mean, mode, median, stddev);
os << std::endl << "Imaginary Component Statistics" << std::endl;
{
int nx = m_nx;
int ny = m_ny;
-
+
if (v == NULL || nx == 0 || ny == 0)
return;
-
+
std::vector<double> vecImage;
int iVec = 0;
vecImage.resize (nx * ny);
for (int iy = 0; iy < ny; iy++)
vecImage[iVec++] = v[ix][iy];
}
-
+
vectorNumericStatistics (vecImage, nx * ny, min, max, mean, mode, median, stddev);
}
int nx = m_nx;
int ny = m_ny;
ImageFileArrayConst v = getArray();
-
+
if (v == NULL || nx == 0 || ny == 0)
return;
-
+
min = v[0][0];
max = v[0][0];
for (int ix = 0; ix < nx; ix++) {
{
if (dataType() != Array2dFile::DATA_TYPE_REAL)
return false;
-
+
if (! reallocRealToComplex())
return false;
-
+
ImageFileArray vImag = getImaginaryArray();
for (unsigned int ix = 0; ix < m_nx; ix++) {
ImageFileColumn vCol = vImag[ix];
for (unsigned int iy = 0; iy < m_ny; iy++)
*vCol++ = 0;
}
-
+
return true;
}
{
if (dataType() != Array2dFile::DATA_TYPE_COMPLEX)
return false;
-
+
ImageFileArray vReal = getArray();
ImageFileArray vImag = getImaginaryArray();
for (unsigned int ix = 0; ix < m_nx; ix++) {
vImagCol++;
}
}
-
+
return reallocComplexToReal();
}
sys_error (ERR_WARNING, "Difference sizes of images [ImageFile::subtractImage]");
return false;
}
-
+
if (isComplex() || rRHS.isComplex() && ! result.isComplex())
result.convertRealToComplex();
-
+
ImageFileArrayConst vLHS = getArray();
ImageFileArrayConst vLHSImag = getImaginaryArray();
ImageFileArrayConst vRHS = rRHS.getArray();
ImageFileArrayConst vRHSImag = rRHS.getImaginaryArray();
ImageFileArray vResult = result.getArray();
ImageFileArray vResultImag = result.getImaginaryArray();
-
+
for (unsigned int ix = 0; ix < m_nx; ix++) {
for (unsigned int iy = 0; iy < m_ny; iy++) {
vResult[ix][iy] = vLHS[ix][iy] - vRHS[ix][iy];
}
}
}
-
+
return true;
}
sys_error (ERR_WARNING, "Difference sizes of images [ImageFile::subtractImage]");
return false;
}
-
+
if (isComplex() || rRHS.isComplex() && ! result.isComplex())
result.convertRealToComplex();
-
+
ImageFileArrayConst vLHS = getArray();
ImageFileArrayConst vLHSImag = getImaginaryArray();
ImageFileArrayConst vRHS = rRHS.getArray();
ImageFileArrayConst vRHSImag = rRHS.getImaginaryArray();
ImageFileArray vResult = result.getArray();
ImageFileArray vResultImag = result.getImaginaryArray();
-
+
for (unsigned int ix = 0; ix < m_nx; ix++) {
for (unsigned int iy = 0; iy < m_ny; iy++) {
vResult[ix][iy] = vLHS[ix][iy] + vRHS[ix][iy];
}
}
}
-
+
return true;
}
sys_error (ERR_WARNING, "Difference sizes of images [ImageFile::subtractImage]");
return false;
}
-
+
if (isComplex() || rRHS.isComplex() && ! result.isComplex())
result.convertRealToComplex();
-
+
ImageFileArrayConst vLHS = getArray();
ImageFileArrayConst vLHSImag = getImaginaryArray();
ImageFileArrayConst vRHS = rRHS.getArray();
ImageFileArrayConst vRHSImag = rRHS.getImaginaryArray();
ImageFileArray vResult = result.getArray();
ImageFileArray vResultImag = result.getImaginaryArray();
-
+
for (unsigned int ix = 0; ix < m_nx; ix++) {
for (unsigned int iy = 0; iy < m_ny; iy++) {
if (result.isComplex()) {
vResult[ix][iy] = vLHS[ix][iy] * vRHS[ix][iy];
}
}
-
-
+
+
return true;
}
sys_error (ERR_WARNING, "Difference sizes of images [ImageFile::subtractImage]");
return false;
}
-
+
if (isComplex() || rRHS.isComplex() && ! result.isComplex())
result.convertRealToComplex();
-
+
ImageFileArrayConst vLHS = getArray();
ImageFileArrayConst vLHSImag = getImaginaryArray();
ImageFileArrayConst vRHS = rRHS.getArray();
ImageFileArrayConst vRHSImag = rRHS.getImaginaryArray();
ImageFileArray vResult = result.getArray();
ImageFileArray vResultImag = result.getImaginaryArray();
-
+
for (unsigned int ix = 0; ix < m_nx; ix++) {
for (unsigned int iy = 0; iy < m_ny; iy++) {
if (result.isComplex()) {
}
}
}
-
+
return true;
}
sys_error (ERR_WARNING, "Difference sizes of images [ImageFile::invertPixelValues]");
return false;
}
-
+
if (isComplex() && ! result.isComplex())
result.convertRealToComplex();
-
+
ImageFileArrayConst vLHS = getArray();
ImageFileArray vResult = result.getArray();
-
+
for (unsigned int ix = 0; ix < m_nx; ix++) {
ImageFileColumnConst in = vLHS[ix];
ImageFileColumn out = vResult[ix];
for (unsigned int iy = 0; iy < m_ny; iy++)
*out++ = - *in++;
}
-
+
return true;
}
sys_error (ERR_WARNING, "Difference sizes of images [ImageFile::invertPixelValues]");
return false;
}
-
+
if (isComplex() && ! result.isComplex())
result.convertRealToComplex();
-
+
bool bComplexOutput = result.isComplex();
ImageFileArrayConst vLHS = getArray();
if (! bComplexOutput) // check if should convert to complex output
bComplexOutput = true;
break;
}
-
+
ImageFileArrayConst vLHSImag = getImaginaryArray();
ImageFileArray vResult = result.getArray();
ImageFileArray vResultImag = result.getImaginaryArray();
-
+
for (unsigned int ix = 0; ix < m_nx; ix++) {
for (unsigned int iy = 0; iy < m_ny; iy++) {
if (result.isComplex()) {
vResult[ix][iy] = ::sqrt (vLHS[ix][iy]);
}
}
-
-
+
+
return true;
}
sys_error (ERR_WARNING, "Difference sizes of images [ImageFile::log]");
return false;
}
-
+
if (isComplex() && ! result.isComplex())
result.convertRealToComplex();
-
+
ImageFileArrayConst vLHS = getArray();
ImageFileArrayConst vLHSImag = getImaginaryArray();
ImageFileArray vResult = result.getArray();
ImageFileArray vResultImag = result.getImaginaryArray();
-
+
for (unsigned int ix = 0; ix < m_nx; ix++) {
for (unsigned int iy = 0; iy < m_ny; iy++) {
if (result.isComplex()) {
}
}
}
-
-
+
+
return true;
}
sys_error (ERR_WARNING, "Difference sizes of images [ImageFile::invertPixelValues]");
return false;
}
-
+
if (isComplex() && ! result.isComplex())
result.convertRealToComplex();
-
+
ImageFileArrayConst vLHS = getArray();
ImageFileArrayConst vLHSImag = getImaginaryArray();
ImageFileArray vResult = result.getArray();
ImageFileArray vResultImag = result.getImaginaryArray();
-
+
for (unsigned int ix = 0; ix < m_nx; ix++) {
for (unsigned int iy = 0; iy < m_ny; iy++) {
if (result.isComplex()) {
vResult[ix][iy] = ::exp (vLHS[ix][iy]);
}
}
-
-
+
+
return true;
}
unsigned int ny = m_ny;
unsigned int newNX = result.nx();
unsigned int newNY = result.ny();
-
+
double dXScale = static_cast<double>(newNX) / static_cast<double>(nx);
double dYScale = static_cast<double>(newNY) / static_cast<double>(ny);
-
+
if (isComplex() && ! result.isComplex())
result.convertRealToComplex();
-
+
ImageFileArrayConst vReal = getArray();
ImageFileArrayConst vImag = getImaginaryArray();
ImageFileArray vResult = result.getArray();
ImageFileArray vResultImag = result.getImaginaryArray();
-
+
BilinearInterpolator<ImageFileValue> realInterp (vReal, nx, ny);
BilinearInterpolator<ImageFileValue> imagInterp (vImag, nx, ny);
sys_error (ERR_WARNING, "Difference sizes of images [ImageFile::invertPixelValues]");
return false;
}
-
+
if (result.dataType() == Array2dFile::DATA_TYPE_REAL) {
if (! result.convertRealToComplex ())
return false;
}
-
+
fftw_complex* in = static_cast<fftw_complex*> (fftw_malloc (sizeof(fftw_complex) * m_nx * m_ny));
-
+
ImageFileArrayConst vReal = getArray();
ImageFileArrayConst vImag = getImaginaryArray();
-
+
unsigned int ix, iy;
unsigned int iArray = 0;
for (ix = 0; ix < m_nx; ix++) {
iArray++;
}
}
-
- fftw_plan plan = fftw_plan_dft_2d (m_nx, m_ny, in, in, FFTW_FORWARD, FFTW_ESTIMATE);
+
+ fftw_plan plan = fftw_plan_dft_2d (m_nx, m_ny, in, in, FFTW_FORWARD, FFTW_ESTIMATE);
fftw_execute (plan);
-
+
ImageFileArray vRealResult = result.getArray();
ImageFileArray vImagResult = result.getImaginaryArray();
iArray = 0;
}
fftw_free(in);
fftw_destroy_plan (plan);
-
+
Fourier::shuffleFourierToNaturalOrder (result);
-
+
return true;
}
sys_error (ERR_WARNING, "Difference sizes of images [ImageFile::invertPixelValues]");
return false;
}
-
+
if (result.dataType() == Array2dFile::DATA_TYPE_REAL) {
if (! result.convertRealToComplex ())
return false;
}
-
+
ImageFileArrayConst vReal = getArray();
ImageFileArrayConst vImag = getImaginaryArray();
ImageFileArray vRealResult = result.getArray();
for (ix = 0; ix < m_nx; ix++) {
for (iy = 0; iy < m_ny; iy++) {
vRealResult[ix][iy] = vReal[ix][iy];
- if (isComplex())
+ if (isComplex())
vImagResult[ix][iy] = vImag[ix][iy];
else
vImagResult[ix][iy] = 0;
}
}
-
+
Fourier::shuffleNaturalToFourierOrder (result);
-
+
fftw_complex* in = static_cast<fftw_complex*>(fftw_malloc(sizeof(fftw_complex) * m_nx * m_ny));
-
+
unsigned int iArray = 0;
for (ix = 0; ix < m_nx; ix++) {
for (iy = 0; iy < m_ny; iy++) {
iArray++;
}
}
-
+
fftw_plan plan = fftw_plan_dft_2d (m_nx, m_ny, in, in, FFTW_BACKWARD, FFTW_ESTIMATE);
-
+
fftw_execute (plan);
-
+
iArray = 0;
for (ix = 0; ix < m_nx; ix++) {
for (iy = 0; iy < m_ny; iy++) {
}
fftw_destroy_plan (plan);
fftw_free(in);
-
+
return true;
}
sys_error (ERR_WARNING, "Difference sizes of images [ImageFile::fftRows]");
return false;
}
-
+
if (result.dataType() == Array2dFile::DATA_TYPE_REAL) {
if (! result.convertRealToComplex ())
return false;
}
-
+
ImageFileArrayConst vReal = getArray();
ImageFileArrayConst vImag = getImaginaryArray();
-
+
fftw_complex* in = static_cast<fftw_complex*>(fftw_malloc(sizeof(fftw_complex) * m_nx));
fftw_plan plan = fftw_plan_dft_1d (m_nx, in, in, FFTW_FORWARD, FFTW_ESTIMATE);
- std::complex<double>* pcRow = new std::complex<double> [m_nx];
+ std::complex<double>* pcRow = new std::complex<double> [m_nx];
for (unsigned int iy = 0; iy < m_ny; iy++) {
unsigned int ix;
for (ix = 0; ix < m_nx; ix++) {
else
in[ix][1] = 0;
}
-
+
fftw_execute (plan);
-
+
for (ix = 0; ix < m_nx; ix++)
pcRow[ix] = std::complex<double>(in[ix][0], in[ix][1]);
-
+
Fourier::shuffleFourierToNaturalOrder (pcRow, m_nx);
for (ix = 0; ix < m_nx; ix++) {
vReal[ix][iy] = pcRow[ix].real() / m_nx;
}
}
delete [] pcRow;
-
+
fftw_destroy_plan (plan);
fftw_free(in);
-
+
return true;
-}
+}
bool
ImageFile::ifftRows (ImageFile& result) const
sys_error (ERR_WARNING, "Difference sizes of images [ImageFile::fftRows]");
return false;
}
-
+
if (result.dataType() == Array2dFile::DATA_TYPE_REAL) {
if (! result.convertRealToComplex ())
return false;
}
-
+
ImageFileArrayConst vReal = getArray();
ImageFileArrayConst vImag = getImaginaryArray();
-
+
fftw_complex* in = static_cast<fftw_complex*>(fftw_malloc(sizeof(fftw_complex) * m_nx));
fftw_plan plan = fftw_plan_dft_1d (m_nx, in, in, FFTW_BACKWARD, FFTW_ESTIMATE);
std::complex<double>* pcRow = new std::complex<double> [m_nx];
-
+
unsigned int ix, iy;
// unsigned int iArray = 0;
for (iy = 0; iy < m_ny; iy++) {
dImag = vImag[ix][iy];
pcRow[ix] = std::complex<double> (vReal[ix][iy], dImag);
}
-
+
Fourier::shuffleNaturalToFourierOrder (pcRow, m_nx);
-
+
for (ix = 0; ix < m_nx; ix++) {
in[ix][0] = pcRow[ix].real();
in[ix][1] = pcRow[ix].imag();
}
-
+
fftw_execute (plan);
-
+
for (ix = 0; ix < m_nx; ix++) {
vReal[ix][iy] = in[ix][0];
vImag[ix][iy] = in[ix][1];
}
}
delete [] pcRow;
-
+
fftw_destroy_plan (plan);
fftw_free(in);
-
+
return true;
}
sys_error (ERR_WARNING, "Difference sizes of images [ImageFile::fftRows]");
return false;
}
-
+
if (result.dataType() == Array2dFile::DATA_TYPE_REAL) {
if (! result.convertRealToComplex ())
return false;
}
-
+
ImageFileArrayConst vReal = getArray();
ImageFileArrayConst vImag = getImaginaryArray();
-
+
fftw_complex* in = static_cast<fftw_complex*>(fftw_malloc(sizeof(fftw_complex) * m_ny));
fftw_plan plan = fftw_plan_dft_1d (m_ny, in, in, FFTW_FORWARD, FFTW_ESTIMATE);
- std::complex<double>* pcCol = new std::complex<double> [m_ny];
+ std::complex<double>* pcCol = new std::complex<double> [m_ny];
for (unsigned int ix = 0; ix < m_nx; ix++) {
unsigned int iy;
for (iy = 0; iy < m_ny; iy++) {
else
in[iy][1] = 0;
}
-
+
fftw_execute (plan);
-
+
for (iy = 0; iy < m_ny; iy++)
pcCol[iy] = std::complex<double>(in[iy][0], in[iy][1]);
-
+
Fourier::shuffleFourierToNaturalOrder (pcCol, m_ny);
for (iy = 0; iy < m_ny; iy++) {
vReal[ix][iy] = pcCol[iy].real() / m_ny;
}
}
delete [] pcCol;
-
+
fftw_destroy_plan (plan);
fftw_free(in);
-
+
return true;
}
sys_error (ERR_WARNING, "Difference sizes of images [ImageFile::fftRows]");
return false;
}
-
+
if (result.dataType() == Array2dFile::DATA_TYPE_REAL) {
if (! result.convertRealToComplex ())
return false;
}
-
+
ImageFileArrayConst vReal = getArray();
ImageFileArrayConst vImag = getImaginaryArray();
-
+
fftw_complex* in = static_cast<fftw_complex*>(fftw_malloc(sizeof(fftw_complex) * m_ny));
fftw_plan plan = fftw_plan_dft_1d (m_ny, in, in, FFTW_BACKWARD, FFTW_ESTIMATE);
std::complex<double>* pcCol = new std::complex<double> [m_ny];
-
+
unsigned int ix, iy;
// unsigned int iArray = 0;
for (ix = 0; ix < m_nx; ix++) {
dImag = vImag[ix][iy];
pcCol[iy] = std::complex<double> (vReal[ix][iy], dImag);
}
-
+
Fourier::shuffleNaturalToFourierOrder (pcCol, m_ny);
-
+
for (iy = 0; iy < m_ny; iy++) {
in[iy][0] = pcCol[iy].real();
in[iy][1] = pcCol[iy].imag();
}
-
+
fftw_execute (plan);
-
+
for (iy = 0; iy < m_ny; iy++) {
vReal[ix][iy] = in[iy][0];
vImag[ix][iy] = in[iy][1];
}
}
delete [] pcCol;
-
+
fftw_destroy_plan (plan);
fftw_free(in);
-
+
return true;
}
sys_error (ERR_WARNING, "Difference sizes of images [ImageFile::invertPixelValues]");
return false;
}
-
+
if (! result.isComplex())
if (! result.convertRealToComplex ())
return false;
-
+
ImageFileArrayConst vLHS = getArray();
ImageFileArrayConst vLHSImag = getImaginaryArray();
ImageFileArray vRealResult = result.getArray();
ImageFileArray vImagResult = result.getImaginaryArray();
-
+
unsigned int ix, iy;
-
+
// alloc output matrix
CTSimComplex** complexOut = new CTSimComplex* [m_nx];
for (ix = 0; ix < m_nx; ix++)
complexOut[ix] = new CTSimComplex [m_ny];
-
+
// fourier each x column
CTSimComplex* pY = new CTSimComplex [m_ny];
for (ix = 0; ix < m_nx; ix++) {
if (isComplex())
dImag = vLHSImag[ix][iy];
pY[iy] = std::complex<double>(vLHS[ix][iy], dImag);
- }
+ }
ProcessSignal::finiteFourierTransform (pY, complexOut[ix], m_ny, ProcessSignal::FORWARD);
}
delete [] pY;
-
+
// fourier each y row
CTSimComplex* pX = new CTSimComplex [m_nx];
CTSimComplex* complexOutRow = new CTSimComplex [m_nx];
}
delete [] pX;
delete [] complexOutRow;
-
+
for (ix = 0; ix < m_nx; ix++)
for (iy = 0; iy < m_ny; iy++) {
vRealResult[ix][iy] = complexOut[ix][iy].real();
vImagResult[ix][iy] = complexOut[ix][iy].imag();
}
-
+
Fourier::shuffleFourierToNaturalOrder (result);
-
+
// delete complexOut matrix
for (ix = 0; ix < m_nx; ix++)
delete [] complexOut[ix];
delete [] complexOut;
-
+
return true;
}
sys_error (ERR_WARNING, "Difference sizes of images [ImageFile::invertPixelValues]");
return false;
}
-
+
if (result.dataType() == Array2dFile::DATA_TYPE_REAL) {
if (! result.convertRealToComplex ())
return false;
}
-
+
ImageFileArrayConst vLHSReal = getArray();
ImageFileArrayConst vLHSImag = getImaginaryArray();
ImageFileArray vRealResult = result.getArray();
ImageFileArray vImagResult = result.getImaginaryArray();
-
+
unsigned int ix, iy;
// alloc 2d complex output matrix
CTSimComplex** complexOut = new CTSimComplex* [m_nx];
for (ix = 0; ix < m_nx; ix++)
complexOut[ix] = new CTSimComplex [m_ny];
-
+
// put input image into result
for (ix = 0; ix < m_nx; ix++)
for (iy = 0; iy < m_ny; iy++) {
else
vImagResult[ix][iy] = 0;
}
-
+
Fourier::shuffleNaturalToFourierOrder (result);
-
+
// ifourier each x column
CTSimComplex* pCol = new CTSimComplex [m_ny];
for (ix = 0; ix < m_nx; ix++) {
ProcessSignal::finiteFourierTransform (pCol, complexOut[ix], m_ny, ProcessSignal::BACKWARD);
}
delete [] pCol;
-
+
// ifourier each y row
CTSimComplex* complexInRow = new CTSimComplex [m_nx];
CTSimComplex* complexOutRow = new CTSimComplex [m_nx];
}
delete [] complexInRow;
delete [] complexOutRow;
-
+
for (ix = 0; ix < m_nx; ix++)
for (iy = 0; iy < m_ny; iy++) {
vRealResult[ix][iy] = complexOut[ix][iy].real();
vImagResult[ix][iy] = complexOut[ix][iy].imag();
}
-
+
// delete complexOut matrix
for (ix = 0; ix < m_nx; ix++)
delete [] complexOut[ix];
delete [] complexOut;
-
+
return true;
}
sys_error (ERR_WARNING, "Difference sizes of images [ImageFile::invertPixelValues]");
return false;
}
-
+
ImageFileArray vReal = getArray();
ImageFileArray vImag = getImaginaryArray();
ImageFileArray vRealResult = result.getArray();
-
+
for (unsigned int ix = 0; ix < m_nx; ix++)
for (unsigned int iy = 0; iy < m_ny; iy++) {
- if (isComplex())
+ if (isComplex())
vRealResult[ix][iy] = ::sqrt (vReal[ix][iy] * vReal[ix][iy] + vImag[ix][iy] * vImag[ix][iy]);
else
vRealResult[ix][iy] = ::fabs(vReal[ix][iy]);
}
-
+
if (result.isComplex())
result.reallocComplexToReal();
-
+
return true;
}
sys_error (ERR_WARNING, "Difference sizes of images [ImageFile::invertPixelValues]");
return false;
}
-
+
ImageFileArray vReal = getArray();
ImageFileArray vImag = getImaginaryArray();
ImageFileArray vRealResult = result.getArray();
-
+
for (unsigned int ix = 0; ix < m_nx; ix++) {
for (unsigned int iy = 0; iy < m_ny; iy++) {
if (isComplex())
}
if (result.isComplex())
result.reallocComplexToReal();
-
+
return true;
}
sys_error (ERR_WARNING, "Difference sizes of images [ImageFile::invertPixelValues]");
return false;
}
-
+
ImageFileArray vReal = getArray();
ImageFileArray vRealResult = result.getArray();
-
+
for (unsigned int ix = 0; ix < m_nx; ix++) {
for (unsigned int iy = 0; iy < m_ny; iy++) {
vRealResult[ix][iy] = vReal[ix][iy];
if (result.isComplex())
result.reallocComplexToReal();
-
+
return true;
}
sys_error (ERR_WARNING, "Difference sizes of images [ImageFile::invertPixelValues]");
return false;
}
-
+
ImageFileArray vImag = getArray();
ImageFileArray vRealResult = result.getArray();
-
+
for (unsigned int ix = 0; ix < m_nx; ix++) {
for (unsigned int iy = 0; iy < m_ny; iy++) {
if (isComplex())
if (result.isComplex())
result.reallocComplexToReal();
-
+
return true;
}
sys_error (ERR_WARNING, "Difference sizes of images [ImageFile::invertPixelValues]");
return false;
}
-
+
if (isComplex() && ! result.isComplex())
result.convertRealToComplex();
-
+
ImageFileArrayConst vLHS = getArray();
ImageFileArrayConst vLHSImag = getImaginaryArray();
ImageFileArray vResult = result.getArray();
ImageFileArray vResultImag = result.getImaginaryArray();
-
+
for (unsigned int ix = 0; ix < m_nx; ix++) {
for (unsigned int iy = 0; iy < m_ny; iy++) {
if (result.isComplex()) {
vResult[ix][iy] = vLHS[ix][iy] * vLHS[ix][iy];
}
}
-
+
return true;
}
ImageFile::convertExportFormatNameToID (const char* const formatName)
{
int formatID = EXPORT_FORMAT_INVALID;
-
+
for (int i = 0; i < s_iExportFormatCount; i++)
if (strcasecmp (formatName, s_aszExportFormatName[i]) == 0) {
formatID = i;
break;
}
-
+
return (formatID);
}
ImageFile::convertExportFormatIDToName (int formatID)
{
static const char *formatName = "";
-
+
if (formatID >= 0 && formatID < s_iExportFormatCount)
return (s_aszExportFormatName[formatID]);
-
+
return (formatName);
}
ImageFile::convertExportFormatIDToTitle (const int formatID)
{
static const char *formatTitle = "";
-
+
if (formatID >= 0 && formatID < s_iExportFormatCount)
return (s_aszExportFormatTitle[formatID]);
-
+
return (formatTitle);
}
ImageFile::convertImportFormatNameToID (const char* const formatName)
{
int formatID = IMPORT_FORMAT_INVALID;
-
+
for (int i = 0; i < s_iImportFormatCount; i++)
if (strcasecmp (formatName, s_aszImportFormatName[i]) == 0) {
formatID = i;
break;
}
-
+
return (formatID);
}
ImageFile::convertImportFormatIDToName (int formatID)
{
static const char *formatName = "";
-
+
if (formatID >= 0 && formatID < s_iImportFormatCount)
return (s_aszImportFormatName[formatID]);
-
+
return (formatName);
}
ImageFile::convertImportFormatIDToTitle (const int formatID)
{
static const char *formatTitle = "";
-
+
if (formatID >= 0 && formatID < s_iImportFormatCount)
return (s_aszImportFormatTitle[formatID]);
-
+
return (formatTitle);
}
ImageFile::importImage (const char* const pszFormat, const char* const pszFilename)
{
int iFormatID = convertImportFormatNameToID (pszFormat);
-
+
if (iFormatID == IMPORT_FORMAT_PPM)
return readImagePPM (pszFilename);
#ifdef HAVE_PNG
else if (iFormatID == IMPORT_FORMAT_PNG)
return readImagePNG (pszFilename);
#endif
-
+
sys_error (ERR_SEVERE, "Invalid format %s [ImageFile::importImage]", pszFormat);
return false;
}
else
c = fgetc(fp);
}
-
+
ungetc (c, fp);
}
fclose(fp);
return false;
}
-
+
int nRows, nCols, iMaxValue;
- skipSpacePPM (fp);
+ skipSpacePPM (fp);
if (fscanf (fp, "%d", &nCols) != 1) {
fclose(fp);
return false;
return false;
}
setArraySize (nRows, nCols);
-
+
if (cSignature == '5' || cSignature == '6') { // binary modes
int c = fgetc(fp);
if (c == 13) {
}
} else
skipSpacePPM (fp); // ascii may have comments
-
+
bool bMonochromeImage = false;
double dMaxValue = iMaxValue;
double dMaxValue3 = iMaxValue * 3;
}
}
}
-
+
fclose(fp);
return true;
}
ImageFile::readImagePNG (const char* const pszFile)
{
FILE* fp = fopen(pszFile, "rb");
- if (!fp)
+ if (!fp)
return false;
unsigned char header[8];
fread (header, 1, 8, fp);
fclose (fp);
return false;
}
-
+
png_structp png_ptr = png_create_read_struct (PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
if (!png_ptr) {
fclose(fp);
return false;
}
-
+
png_infop info_ptr = png_create_info_struct(png_ptr);
if (!info_ptr) {
png_destroy_read_struct(&png_ptr, (png_infopp)NULL, (png_infopp)NULL);
fclose(fp);
return false;
}
-
+
png_infop end_info = png_create_info_struct(png_ptr);
if (!end_info) {
png_destroy_read_struct(&png_ptr, &info_ptr, (png_infopp)NULL);
fclose(fp);
return false;
}
-
+
if (setjmp(png_ptr->jmpbuf)) {
png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
fclose(fp);
return false;
}
-
+
png_init_io(png_ptr, fp);
png_set_sig_bytes(png_ptr, 8);
png_read_info(png_ptr, info_ptr);
-
+
int width = png_get_image_width (png_ptr, info_ptr);
int height = png_get_image_height (png_ptr, info_ptr);
int bit_depth = png_get_bit_depth (png_ptr, info_ptr);
int color_type = png_get_color_type (png_ptr, info_ptr);
-
- if (color_type == PNG_COLOR_TYPE_PALETTE && bit_depth <= 8)
+
+ if (color_type == PNG_COLOR_TYPE_PALETTE && bit_depth <= 8)
png_set_expand(png_ptr);
-
- if (color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8)
+
+ if (color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8)
png_set_expand(png_ptr);
-
+
if (bit_depth < 8)
png_set_packing(png_ptr);
-
+
if (color_type & PNG_COLOR_MASK_ALPHA)
png_set_strip_alpha(png_ptr);
-
+
if (bit_depth == 16)
png_set_swap(png_ptr); // convert to little-endian format
-
+
png_read_update_info(png_ptr, info_ptr); // update with transformations
int rowbytes = png_get_rowbytes (png_ptr, info_ptr);
bit_depth = png_get_bit_depth (png_ptr, info_ptr);
color_type = png_get_color_type (png_ptr, info_ptr);
-
+
png_bytep* row_pointers = new png_bytep [height];
int i;
for (i = 0; i < height; i++)
row_pointers[i] = new unsigned char [rowbytes];
-
+
png_read_image(png_ptr, row_pointers);
-
+
setArraySize (width, height);
ImageFileArray v = getArray();
for (int iy = 0; iy < height; iy++) {
int iBase = ix * 2;
dV = (row_pointers[iy][iBase] + (row_pointers[iy][iBase+1] << 8)) / 65536.;
} else
- dV = 0;
+ dV = 0;
} else if (color_type == PNG_COLOR_TYPE_RGB) {
if (bit_depth == 8) {
int iBase = ix * 3;
double dB = row_pointers[iy][iBase+2] / 255.;
dV = colorToGrayscale (dR, dG, dB);
} else
- dV = 0;
+ dV = 0;
}
v[ix][height-iy-1] = dV;
}
}
-
+
png_read_end(png_ptr, end_info);
png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
-
+
for (i = 0; i < height; i++)
delete row_pointers[i];
delete row_pointers;
-
+
fclose (fp);
return true;
}
ImageFile::exportImage (const char* const pszFormat, const char* const pszFilename, int nxcell, int nycell, double densmin, double densmax)
{
int iFormatID = convertExportFormatNameToID (pszFormat);
-
+
if (iFormatID == EXPORT_FORMAT_PGM)
return writeImagePGM (pszFilename, nxcell, nycell, densmin, densmax);
else if (iFormatID == EXPORT_FORMAT_PGMASCII)
else if (iFormatID == EXPORT_FORMAT_DICOM) {
DicomExporter dicomExport (this);
bool bSuccess = dicomExport.writeFile (pszFilename);
- if (! bSuccess)
+ if (! bSuccess)
sys_error (ERR_SEVERE, dicomExport.failMessage().c_str());
return bSuccess;
}
#endif
- else if (iFormatID == EXPORT_FORMAT_RAW)
- return writeImageRaw(pszFilename, nxcell, nycell);
-
-
+ else if (iFormatID == EXPORT_FORMAT_RAW)
+ return writeImageRaw(pszFilename, nxcell, nycell);
+
+
sys_error (ERR_SEVERE, "Invalid format %s [ImageFile::exportImage]", pszFormat);
return false;
}
int nx = m_nx;
int ny = m_ny;
ImageFileArray v = getArray();
-
+
unsigned char* rowp = new unsigned char [nx * nxcell];
-
+
if ((fp = fopen (outfile, "wb")) == NULL)
return false;
-
+
fprintf(fp, "P5\n");
fprintf(fp, "%d %d\n", nx, ny);
fprintf(fp, "255\n");
-
+
for (int irow = ny - 1; irow >= 0; irow--) {
for (int icol = 0; icol < nx; icol++) {
int pos = icol * nxcell;
}
}
for (int ir = 0; ir < nycell; ir++) {
- for (int ic = 0; ic < nx * nxcell; ic++)
+ for (int ic = 0; ic < nx * nxcell; ic++)
fputc( rowp[ic], fp );
}
}
-
+
delete rowp;
fclose(fp);
-
+
return true;
}
int nx = m_nx;
int ny = m_ny;
ImageFileArray v = getArray();
-
+
unsigned char* rowp = new unsigned char [nx * nxcell];
-
+
if ((fp = fopen (outfile, "wb")) == NULL)
return false;
-
+
fprintf(fp, "P2\n");
fprintf(fp, "%d %d\n", nx, ny);
fprintf(fp, "255\n");
-
+
for (int irow = ny - 1; irow >= 0; irow--) {
for (int icol = 0; icol < nx; icol++) {
int pos = icol * nxcell;
}
}
for (int ir = 0; ir < nycell; ir++) {
- for (int ic = 0; ic < nx * nxcell; ic++)
+ for (int ic = 0; ic < nx * nxcell; ic++)
fprintf(fp, "%d ", rowp[ic]);
fprintf(fp, "\n");
}
}
-
+
delete rowp;
fclose(fp);
-
+
return true;
}
int ny = m_ny;
ImageFileArray v = getArray();
ImageFileArray vImag = getImaginaryArray();
-
+
if ((fp = fopen (outfile, "w")) == NULL)
return false;
-
+
for (int irow = ny - 1; irow >= 0; irow--) {
for (int icol = 0; icol < nx; icol++) {
if (isComplex()) {
}
fprintf(fp, "\n");
}
-
+
fclose(fp);
-
+
return true;
}
int nx = m_nx;
int ny = m_ny;
ImageFileArray v = getArray();
-
+
unsigned char* rowp = new unsigned char [nx * nxcell * (bitdepth / 8)];
-
+
FILE *fp = fopen (outfile, "wb");
if (! fp)
return false;
-
+
png_structp png_ptr = png_create_write_struct (PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
if (! png_ptr)
return false;
-
+
png_infop info_ptr = png_create_info_struct (png_ptr);
if (! info_ptr) {
png_destroy_write_struct (&png_ptr, (png_infopp) NULL);
fclose (fp);
return false;
}
-
+
if (setjmp (png_ptr->jmpbuf)) {
png_destroy_write_struct (&png_ptr, &info_ptr);
fclose (fp);
return false;
}
-
+
png_init_io(png_ptr, fp);
-
+
png_set_IHDR (png_ptr, info_ptr, nx * nxcell, ny * nycell, bitdepth, PNG_COLOR_TYPE_GRAY, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
-
+
png_write_info(png_ptr, info_ptr);
for (int irow = ny - 1; irow >= 0; irow--) {
png_bytep row_pointer = rowp;
-
+
for (int icol = 0; icol < nx; icol++) {
int pos = icol * nxcell;
double dens = (v[icol][irow] - densmin) / (densmax - densmin);
dens = clamp (dens, 0., 1.);
unsigned int outval = static_cast<unsigned int> (dens * max_out_level);
-
+
for (int p = pos; p < pos + nxcell; p++) {
if (bitdepth == 8)
rowp[p] = outval;
for (int ir = 0; ir < nycell; ir++)
png_write_rows (png_ptr, &row_pointer, 1);
}
-
+
png_write_end (png_ptr, info_ptr);
png_destroy_write_struct (&png_ptr, &info_ptr);
delete rowp;
-
+
fclose(fp);
-
+
return true;
}
#endif
int nx = m_nx;
int ny = m_ny;
ImageFileArray v = getArray();
-
+
unsigned char* rowp = new unsigned char [nx * nxcell];
-
+
gdImagePtr gif = gdImageCreate(nx * nxcell, ny * nycell);
for (int i = 0; i < N_GRAYSCALE; i++)
gs_indices[i] = gdImageColorAllocate(gif, i, i, i);
-
+
int lastrow = ny * nycell - 1;
for (int irow = 0; irow < ny; irow++) {
int rpos = irow * nycell;
}
}
}
-
+
FILE *out;
if ((out = fopen (outfile,"w")) == NULL) {
sys_error(ERR_SEVERE, "Error opening output file %s for writing", outfile);
gdImageGif(gif,out);
fclose(out);
gdImageDestroy(gif);
-
+
delete rowp;
-
+
return true;
}
#endif
int nx = m_nx;
int ny = m_ny;
ImageFileArray v = getArray();
-
+
if ((fp = fopen (outfile, "wb")) == NULL)
return false;
-
+
for (int irow = ny - 1; irow >= 0; irow--) {
for (int icol = 0; icol < nx; icol++) {
float dens = v[icol][irow];
fwrite(&dens, sizeof(float), 1, fp);
}
}
-
+
fclose(fp);
return true;
}
/*****************************************************************************
** FILE IDENTIFICATION
-**
+**
** Name: phm.cpp
** Purpose: Routines for phantom objects
-** Progammer: Kevin Rosenberg
+** Progammer: Kevin Rosenberg
** Date Started: Aug 1984
**
** This is part of the CTSim program
#include "ct.h"
const int PhantomElement::POINTS_PER_CIRCLE = 360;
-const double PhantomElement::SCALE_PELEM_EXTENT=0.000; // increase pelem limits by 0.5%
-//const double PhantomElement::SCALE_PELEM_EXTENT=0.005; // increase pelem limits by 0.5%
+const double PhantomElement::SCALE_PELEM_EXTENT=0.000; // increase pelem limits by 0.5%
+//const double PhantomElement::SCALE_PELEM_EXTENT=0.005; // increase pelem limits by 0.5%
const int Phantom::PHM_INVALID = -1;
const int Phantom::PHM_HERMAN = 0;
const int Phantom::PHM_SHEPP_LOGAN = 1;
const int Phantom::PHM_UNITPULSE = 2;
-const char* Phantom::s_aszPhantomName[] =
+const char* Phantom::s_aszPhantomName[] =
{
"herman",
"shepp-logan",
"unit-pulse",
};
-const char* Phantom::s_aszPhantomTitle[] =
+const char* Phantom::s_aszPhantomTitle[] =
{
"Herman Head",
"Shepp-Logan",
createFromPhantom (phmName);
}
-void
+void
Phantom::init ()
{
m_nPElem = 0;
Phantom::convertPhantomIDToName (int phmID)
{
static const char *name = "";
-
+
if (phmID >= 0 && phmID < s_iPhantomCount)
return (s_aszPhantomName[phmID]);
-
+
return (name);
}
Phantom::convertPhantomIDToTitle (int phmID)
{
static const char *title = "";
-
+
if (phmID >= 0 && phmID < s_iPhantomCount)
return (s_aszPhantomName[phmID]);
-
+
return (title);
}
int
-Phantom::convertNameToPhantomID (const char* const phmName)
+Phantom::convertNameToPhantomID (const char* const phmName)
{
int id = PHM_INVALID;
-
+
for (int i = 0; i < s_iPhantomCount; i++)
if (strcasecmp (phmName, s_aszPhantomName[i]) == 0) {
id = i;
break;
}
-
+
return (id);
}
m_failMessage += phmName;
return false;
}
-
+
m_name = phmName;
createFromPhantom (phmid);
return true;
bool
Phantom::createFromPhantom (const int phmid)
{
- switch (phmid)
+ switch (phmid)
{
case PHM_HERMAN:
addStdHerman();
break;
case PHM_UNITPULSE:
m_composition = P_UNIT_PULSE;
- addPElem ("rectangle", 0., 0., 100., 100., 0., 0.); // outline
- addPElem ("ellipse", 0., 0., 1., 1., 0., 1.); // pulse
+ addPElem ("rectangle", 0., 0., 100., 100., 0., 0.); // outline
+ addPElem ("ellipse", 0., 0., 1., 1., 0., 1.); // pulse
break;
default:
m_fail = true;
m_failMessage += phmid;
return false;
}
-
+
m_id = phmid;
-
+
return true;
}
{
bool bGoodFile = true;
FILE *fp;
-
+
if ((fp = fopen (fname, "r")) == NULL)
return (false);
-
+
m_name = fname;
-
+
while (1) {
double cx, cy, u, v, rot, dens;
char pelemtype[80];
-
+
int status = fscanf (fp, "%79s %lf %lf %lf %lf %lf %lf", pelemtype, &cx, &cy, &u, &v, &rot, &dens);
-
- if (status == static_cast<int>(EOF))
+
+ if (status == static_cast<int>(EOF))
break;
else if (status != 7) {
sys_error (ERR_WARNING, "Insufficient fields reading phantom file %s [Phantom::createFromFile]", fname);
}
addPElem (pelemtype, cx, cy, u, v, rot, dens);
}
-
+
fclose (fp);
-
+
return (bGoodFile);
}
Phantom::fileWrite (const char* const fname)
{
fstream file (fname, std::ios::out);
-
+
if (! file.fail())
printDefinitions (file);
return ! file.fail();
}
/* NAME
-* addPElem Add pelem
+* addPElem Add pelem
*
* SYNOPSIS
* addPElem (type, cx, cy, u, v, rot, atten)
-* char *type type of pelem (box, ellipse, etc)
-* double cx, cy pelem center
-* double u,v pelem size
-* double rot rotation angle of pelem (in degrees)
-* double atten x-ray attenuation cooefficient
+* char *type type of pelem (box, ellipse, etc)
+* double cx, cy pelem center
+* double u,v pelem size
+* double rot rotation angle of pelem (in degrees)
+* double atten x-ray attenuation cooefficient
*/
-void
+void
Phantom::addPElem (const char *type, const double cx, const double cy, const double u, const double v, const double rot, const double atten)
{
PhmElemType pe_type = PhantomElement::convertNameToType (type);
sys_error (ERR_WARNING, "Unknown PhantomElement type %s [PhantomElement::PhantomElement]", type);
return;
}
-
+
PhantomElement *pelem = new PhantomElement (type, cx, cy, u, v, rot, atten);
m_listPElem.push_front (pelem);
-
+
// update phantom limits
if (m_xmin > pelem->xmin()) m_xmin = pelem->xmin();
if (m_xmax < pelem->xmax()) m_xmax = pelem->xmax();
if (m_ymin > pelem->ymin()) m_ymin = pelem->ymin();
if (m_ymax < pelem->ymax()) m_ymax = pelem->ymax();
-
+
m_nPElem++;
}
/*----------------------------------------------------------------------*/
-/* Input-Output Routines */
+/* Input-Output Routines */
/*----------------------------------------------------------------------*/
/* NAME
-* print Print vertices of Phantom pelems
+* print Print vertices of Phantom pelems
*
* SYNOPSIS
* print (phm)
*/
-void
+void
Phantom::print (std::ostream& os) const
{
os << "Number of PElements: " << m_nPElem << "\n";
os << "Limits: xmin=" << m_xmin << ", ymin=" << m_ymin << ", xmax=" << m_xmax << ", ymax=" << m_ymax << "\n";
-
+
for (PElemConstIterator i = m_listPElem.begin(); i != m_listPElem.end(); i++) {
const PhantomElement& rPE = **i;
os << "PhantomElement: nPoints=" << rPE.nOutlinePoints();
os << ", atten=" << rPE.atten() << " rot=" << convertRadiansToDegrees (rPE.rot()) << "\n";
os << "xmin=" << rPE.xmin() << ", ymin=" << rPE.ymin() << ", xmax=" << rPE.xmax() << ", ymax=" << rPE.ymax() << "\n";
-
+
if (false)
for (int i = 0; i < rPE.nOutlinePoints(); i++)
os << rPE.xOutline()[i] << "," << rPE.yOutline()[i] << "\n";
}
}
-void
+void
Phantom::print (std::ostringstream& os) const
{
os << "Number of PElements: " << m_nPElem << "\n";
os << "Limits: xmin=" << m_xmin << ", ymin=" << m_ymin << ", xmax=" << m_xmax << ", ymax=" << m_ymax << "\n";
-
+
for (PElemConstIterator i = m_listPElem.begin(); i != m_listPElem.end(); i++) {
const PhantomElement& rPE = **i;
os << "PhantomElement: nPoints=" << rPE.nOutlinePoints();
os << ", atten=" << rPE.atten() << " rot=" << convertRadiansToDegrees (rPE.rot()) << "\n";
os << "xmin=" << rPE.xmin() << ", ymin=" << rPE.ymin() << ", xmax=" << rPE.xmax() << ", ymax=" << rPE.ymax() << "\n";
-
+
if (false)
for (int i = 0; i < rPE.nOutlinePoints(); i++)
os << rPE.xOutline()[i] << "," << rPE.yOutline()[i] << "\n";
/* NAME
-* show Show vector outline of Phantom to user
+* show Show vector outline of Phantom to user
*
* SYNOPSIS
* show (pic)
*/
#ifdef HAVE_SGP
-void
+void
Phantom::show () const
{
SGPDriver driverSGP ("Phantom Show");
SGP sgp (driverSGP);
-
+
show (sgp);
-
+
std::cout << "Press return to continue";
cio_kb_getc();
}
-void
+void
Phantom::show (SGP& sgp) const
{
double wsize = m_xmax - m_xmin;
- if ((m_ymax - m_ymin) > wsize)
+ if ((m_ymax - m_ymin) > wsize)
wsize = m_ymax - m_ymin;
wsize *= 1.01;
double halfWindow = wsize / 2;
-
+
double xcent = m_xmin + (m_xmax - m_xmin) / 2;
double ycent = m_ymin + (m_ymax - m_ymin) / 2;
-
+
sgp.setWindow (xcent - halfWindow, ycent - halfWindow, xcent + halfWindow, ycent + halfWindow);
-
+
draw (sgp);
}
#endif
/* NAME
-* draw Draw vector outline of Phantom
+* draw Draw vector outline of Phantom
*
* SYNOPSIS
* draw ()
*/
#ifdef HAVE_SGP
-void
+void
Phantom::draw (SGP& sgp) const
{
for (PElemIterator i = m_listPElem.begin(); i != m_listPElem.end(); i++)
/* NAME
-* addStdSheppLogan Make head phantom of Shepp-Logan
+* addStdSheppLogan Make head phantom of Shepp-Logan
*
* REFERENCES
* S. W. Rowland, "Computer Implementation of Image Reconstruction
-* Formulas", in "Image Reconstruction from Projections: Implementation
-* and Applications", edited by G. T. Herman, 1978.
+* Formulas", in "Image Reconstruction from Projections: Implementation
+* and Applications", edited by G. T. Herman, 1978.
*/
-void
+void
Phantom::addStdSheppLogan ()
{
addPElem ("ellipse", 0.0000, 0.0000, 0.6900, 0.9200, 0.0, 1.00);
/* NAME
-* addStdHerman Standard head phantom of G. T. Herman
+* addStdHerman Standard head phantom of G. T. Herman
*
* REFERENCES
* G. T. Herman, "Image Reconstructions from Projections: The Fundementals
-* of Computed Tomography", 1979.
+* of Computed Tomography", 1979.
*/
-void
+void
Phantom::addStdHerman ()
{
addPElem ("ellipse", 0.000, 1.50, 0.375, 0.3000, 90.00, -0.003);
/* NAME
-* convertToImagefile Make image array from Phantom
+* convertToImagefile Make image array from Phantom
*
* SYNOPSIS
* pic_to_imagefile (pic, im, nsample)
-* Phantom& pic Phantom definitions
-* ImageFile *im Computed pixel array
-* int nsample Number of samples along each axis for each pixel
-* (total samples per pixel = nsample * nsample)
+* Phantom& pic Phantom definitions
+* ImageFile *im Computed pixel array
+* int nsample Number of samples along each axis for each pixel
+* (total samples per pixel = nsample * nsample)
*/
void
convertToImagefile (im, dViewRatio, in_nsample, trace, 0, im.nx(), true);
}
-void
-Phantom::convertToImagefile (ImageFile& im, const double dViewRatio, const int in_nsample, const int trace,
+void
+Phantom::convertToImagefile (ImageFile& im, const double dViewRatio, const int in_nsample, const int trace,
const int colStart, const int colCount, bool bStoreAtColumnPos) const
{
int iStorageOffset = (bStoreAtColumnPos ? colStart : 0);
convertToImagefile (im, im.nx(), dViewRatio, in_nsample, trace, colStart, colCount, iStorageOffset);
}
-void
-Phantom::convertToImagefile (ImageFile& im, const int iTotalRasterCols, const double dViewRatio,
+void
+Phantom::convertToImagefile (ImageFile& im, const int iTotalRasterCols, const double dViewRatio,
const int in_nsample, const int trace, const int colStart, const int colCount, int iStorageOffset) const
{
const int nx = im.nx();
const int ny = im.ny();
if (nx < 2 || ny < 2)
return;
-
+
int nsample = in_nsample;
- if (nsample < 1)
+ if (nsample < 1)
nsample = 1;
-
+
double dx = m_xmax - m_xmin;
double dy = m_ymax - m_ymin;
double xcent = m_xmin + dx / 2;
double ycent = m_ymin + dy / 2;
double dHalflen = dViewRatio * (getDiameterBoundaryCircle() / SQRT2 / 2);
-
+
double xmin = xcent - dHalflen;
double xmax = xcent + dHalflen;
double ymin = ycent - dHalflen;
double ymax = ycent + dHalflen;
-
+
// Each pixel holds the average of the intensity of the cell with (ix,iy) at the center of the pixel
// Set major increments so that the last cell v[nx-1][ny-1] will start at xmax - xinc, ymax - yinc).
// Set minor increments so that sample points are centered in cell
-
+
double xinc = (xmax - xmin) / (iTotalRasterCols);
double yinc = (ymax - ymin) / ny;
-
- double kxinc = xinc / nsample; /* interval between samples */
+
+ double kxinc = xinc / nsample; /* interval between samples */
double kyinc = yinc / nsample;
- double kxofs = kxinc / 2; /* offset of 1st point */
+ double kxofs = kxinc / 2; /* offset of 1st point */
double kyofs = kyinc / 2;
-
+
im.setAxisExtent (xmin, xmax, ymin, ymax);
im.setAxisIncrement (xinc, yinc);
-
+
ImageFileArray v = im.getArray();
-
+
for (int ix = 0; ix < colCount; ix++) {
int iColStore = ix + iStorageOffset;
ImageFileColumn vCol = v[iColStore];
for (int iy = 0; iy < ny; iy++)
*vCol++ = 0;
}
-
+
double x_start = xmin + (colStart * xinc);
for (PElemConstIterator pelem = m_listPElem.begin(); pelem != m_listPElem.end(); pelem++) {
const PhantomElement& rPElem = **pelem;
} /* for iy */
} /* for ix */
} /* for pelem */
-
-
+
+
if (nsample > 1) {
double factor = 1.0 / static_cast<double>(nsample * nsample);
-
-
+
+
for (int ix = 0; ix < colCount; ix++) {
int iColStore = ix + iStorageOffset;
ImageFileColumn vCol = v[iColStore];
: m_cx(cx), m_cy(cy), m_u(u), m_v(v), m_atten(atten), m_nPoints(0), m_xOutline(0), m_yOutline(0)
{
m_rot = convertDegreesToRadians (rot); // convert angle to radians
-
+
m_type = convertNameToType (type);
-
+
makeTransformMatrices (); // calc transform matrices between phantom and normalized phantomelement
- makeVectorOutline (); // calculate vector outline of pelem
-
+ makeVectorOutline (); // calculate vector outline of pelem
+
m_rectLimits[0] = m_xmin; m_rectLimits[1] = m_ymin;
m_rectLimits[2] = m_xmax; m_rectLimits[3] = m_ymax;
}
PhantomElement::convertNameToType (const char* const typeName)
{
PhmElemType type = PELEM_INVALID;
-
+
if (strcasecmp (typeName, "rectangle") == 0)
type = PELEM_RECTANGLE;
else if (strcasecmp (typeName, "triangle") == 0)
type = PELEM_SECTOR;
else if (strcasecmp (typeName, "segment") == 0)
type = PELEM_SEGMENT;
-
+
return (type);
}
PhantomElement::convertTypeToName (PhmElemType iType)
{
static char* pszType = "Unknown";
-
+
if (iType == PELEM_RECTANGLE)
pszType = "rectangle";
else if (iType == PELEM_TRIANGLE)
pszType = "sector";
else if (iType == PELEM_SEGMENT)
pszType = "segment";
-
+
return pszType;
}
-void
+void
PhantomElement::makeTransformMatrices ()
{
GRFMTX_2D temp;
-
- // To map normalized Pelem coords to world Phantom
- // scale by (u, v)
- // rotate by rot
- // translate by (cx, cy)
-
+
+ // To map normalized Pelem coords to world Phantom
+ // scale by (u, v)
+ // rotate by rot
+ // translate by (cx, cy)
+
scale_mtx2 (m_xformObjToPhm, m_u, m_v);
rot_mtx2 (temp, m_rot);
mult_mtx2 (m_xformObjToPhm, temp, m_xformObjToPhm);
xlat_mtx2 (temp, m_cx, m_cy);
mult_mtx2 (m_xformObjToPhm, temp, m_xformObjToPhm);
-
+
// to map world Phantom coodinates to normalized PElem coords
// translate by (-cx, -cy)
// rotate by -rot
// scale by (1/u, 1/v)
-
+
xlat_mtx2 (m_xformPhmToObj, -m_cx, -m_cy);
rot_mtx2 (temp, -m_rot);
mult_mtx2 (m_xformPhmToObj, temp, m_xformPhmToObj);
/* NAME
-* pelem_make_points INTERNAL routine to calculate point array for an pelem
+* pelem_make_points INTERNAL routine to calculate point array for an pelem
*
* SYNOPSIS
* makepelempts (pelem)
-* PELEM *pelem pelem whose points we are calculating
+* PELEM *pelem pelem whose points we are calculating
*
* NOTES
* Called by phm_add_pelem()
double radius, theta, start, stop;
double xfact, yfact;
int cpts;
-
+
m_nPoints = 0;
switch (m_type) {
case PELEM_RECTANGLE:
m_nPoints = 5;
m_xOutline = new double [m_nPoints];
m_yOutline = new double [m_nPoints];
- m_xOutline[0] =-m_u; m_yOutline[0] =-m_v;
- m_xOutline[1] = m_u; m_yOutline[1] =-m_v;
- m_xOutline[2] = m_u; m_yOutline[2] = m_v;
- m_xOutline[3] =-m_u; m_yOutline[3] = m_v;
- m_xOutline[4] =-m_u; m_yOutline[4] =-m_v;
+ m_xOutline[0] =-m_u; m_yOutline[0] =-m_v;
+ m_xOutline[1] = m_u; m_yOutline[1] =-m_v;
+ m_xOutline[2] = m_u; m_yOutline[2] = m_v;
+ m_xOutline[3] =-m_u; m_yOutline[3] = m_v;
+ m_xOutline[4] =-m_u; m_yOutline[4] =-m_v;
break;
case PELEM_TRIANGLE:
m_nPoints = 4;
m_xOutline = new double [m_nPoints];
m_yOutline = new double [m_nPoints];
- m_xOutline[0] =-m_u; m_yOutline[0] = 0.0;
- m_xOutline[1] = m_u; m_yOutline[1] = 0.0;
- m_xOutline[2] = 0.0; m_yOutline[2] = m_v;
- m_xOutline[3] =-m_u; m_yOutline[3] = 0.0;
+ m_xOutline[0] =-m_u; m_yOutline[0] = 0.0;
+ m_xOutline[1] = m_u; m_yOutline[1] = 0.0;
+ m_xOutline[2] = 0.0; m_yOutline[2] = m_v;
+ m_xOutline[3] =-m_u; m_yOutline[3] = 0.0;
break;
case PELEM_ELLIPSE:
cpts = numCirclePoints (TWOPI);
break;
case PELEM_SECTOR:
radius = sqrt(m_u * m_u + m_v * m_v);
- theta = atan(m_u / m_v); // angle with y-axis
+ theta = atan(m_u / m_v); // angle with y-axis
start = 3.0 * HALFPI - theta;
stop = 3.0 * HALFPI + theta;
cpts = numCirclePoints (stop - start);
m_nPoints = 3 + cpts;
m_xOutline = new double [m_nPoints];
m_yOutline = new double [m_nPoints];
-
- m_xOutline[0] = 0.0; m_yOutline[0] = m_v;
- m_xOutline[1] =-m_u; m_yOutline[1] = 0.0;
+
+ m_xOutline[0] = 0.0; m_yOutline[0] = m_v;
+ m_xOutline[1] =-m_u; m_yOutline[1] = 0.0;
calcArcPoints (&m_xOutline[2], &m_yOutline[2], cpts, 0.0, m_v, radius, start, stop);
m_xOutline[cpts + 2] = 0.0;
m_yOutline[cpts + 2] = m_v;
break;
case PELEM_SEGMENT:
radius = sqrt(m_u * m_u + m_v * m_v);
- theta = atan (m_u / m_v); // angle with y-axis
+ theta = atan (m_u / m_v); // angle with y-axis
start = 3.0 * HALFPI - theta;
stop = 3.0 * HALFPI + theta;
-
+
cpts = numCirclePoints (stop - start);
m_nPoints = cpts + 1;
m_xOutline = new double [m_nPoints];
m_yOutline = new double [m_nPoints];
-
+
calcArcPoints (m_xOutline, m_yOutline, cpts, 0.0, m_v, radius, start, stop);
m_xOutline[cpts] = -m_u;
m_yOutline[cpts] = 0.0;
sys_error(ERR_WARNING, "Illegal phantom element type %d [makeVectorOutline]", m_type);
return;
}
-
+
rotate2d (m_xOutline, m_yOutline, m_nPoints, m_rot);
xlat2d (m_xOutline, m_yOutline, m_nPoints, m_cx, m_cy);
-
+
minmax_array (m_xOutline, m_nPoints, m_xmin, m_xmax);
minmax_array (m_yOutline, m_nPoints, m_ymin, m_ymax);
-
+
// increase pelem extent by SCALE_PELEM_EXTENT to eliminate chance of
- // missing actual pelem maximum due to polygonal sampling
-
+ // missing actual pelem maximum due to polygonal sampling
+
xfact = (m_xmax - m_xmin) * SCALE_PELEM_EXTENT;
yfact = (m_ymax - m_ymin) * SCALE_PELEM_EXTENT;
-
+
m_xmin -= xfact;
m_ymin -= yfact;
m_xmax += xfact;
/* NAME
-* calc_arc Calculate outline of a arc of a circle
+* calc_arc Calculate outline of a arc of a circle
*
* SYNOPSIS
* calc_arc (x, y, xcent, ycent, pts, r, start, stop)
-* double x[], y[]; Array of points
-* int pts Number of points in array
-* double xcent, ycent Center of cirlce
-* double r Radius of circle
-* double start, stop Beginning & ending angles
+* double x[], y[]; Array of points
+* int pts Number of points in array
+* double xcent, ycent Center of cirlce
+* double r Radius of circle
+* double start, stop Beginning & ending angles
*/
-void
+void
PhantomElement::calcArcPoints (double x[], double y[], const int pts, const double xcent, const double ycent, const double r, const double start, const double stop)
{
if (r <= 0.0)
sys_error (ERR_WARNING, "negative or zero radius in calc_arc()");
-
- double theta = (stop - start) / (pts - 1); // angle incr. between points
+
+ double theta = (stop - start) / (pts - 1); // angle incr. between points
double c = cos(theta);
double s = sin(theta);
-
+
x[0] = r * cos (start) + xcent;
y[0] = r * sin (start) + ycent;
-
+
double xp = x[0] - xcent;
double yp = y[0] - ycent;
for (int i = 1; i < pts; i++) {
//
-void
+void
PhantomElement::calcEllipsePoints (double x[], double y[], const int pts, const double u, const double v)
{
- calcArcPoints (x, y, m_nPoints, 0.0, 0.0, 1.0, 0.0, TWOPI); // make a unit circle
- scale2d (x, y, m_nPoints, m_u, m_v); // scale to ellipse
+ calcArcPoints (x, y, m_nPoints, 0.0, 0.0, 1.0, 0.0, TWOPI); // make a unit circle
+ scale2d (x, y, m_nPoints, m_u, m_v); // scale to ellipse
}
/* NAME
-* circle_pts Calculate number of points to use for circle segment
+* circle_pts Calculate number of points to use for circle segment
*
* SYNOPSIS
* n = circle_pts (theta)
-* int n Number of points to use for arc
-* double theta Length of arc in radians
+* int n Number of points to use for arc
+* double theta Length of arc in radians
*/
-int
+int
PhantomElement::numCirclePoints (double theta)
{
theta = clamp (theta, 0., TWOPI);
-
+
return static_cast<int> (POINTS_PER_CIRCLE * theta / TWOPI + 1.5);
}
double cx1 = x1, cy1 = y1, cx2 = x2, cy2 = y2;
if (! clip_rect (cx1, cy1, cx2, cy2, m_rectLimits))
return false;
-
- // convert phantom coordinates to pelem coordinates
+
+ // convert phantom coordinates to pelem coordinates
xform_mtx2 (m_xformPhmToObj, x1, y1);
xform_mtx2 (m_xformPhmToObj, x2, y2);
-
+
if (! clipLineNormalizedCoords (x1, y1, x2, y2))
return false;
-
- // convert standard pelem coordinates back to phantom coordinates
+
+ // convert standard pelem coordinates back to phantom coordinates
xform_mtx2 (m_xformObjToPhm, x1, y1);
xform_mtx2 (m_xformObjToPhm, x2, y2);
-
+
return true;
}
/* NAME
-* pelem_clip_line Clip pelem against an arbitrary line
+* pelem_clip_line Clip pelem against an arbitrary line
*
* SYNOPSIS
* pelem_clip_line (pelem, x1, y1, x2, y2)
-* PhantomElement& pelem; Pelem to be clipped
-* double *x1, *y1, *x2, *y2 Endpoints of line to be clipped
+* PhantomElement& pelem; Pelem to be clipped
+* double *x1, *y1, *x2, *y2 Endpoints of line to be clipped
*
* RETURNS
* true if line passes through pelem
-* (x1, y1, x2, y2 hold coordinates of new line)
+* (x1, y1, x2, y2 hold coordinates of new line)
* false if line do not pass through pelem
-* (x1, y1, x2, y2 are undefined)
+* (x1, y1, x2, y2 are undefined)
*/
bool
PhantomElement::clipLineNormalizedCoords (double& x1, double& y1, double& x2, double& y2) const
{
bool accept = false;
-
+
switch (m_type) {
case PELEM_RECTANGLE:
double rect[4];
sys_error (ERR_WARNING, "Illegal pelem type %d [pelem_clip_line]", m_type);
break;
}
-
+
return(accept);
}
-// METHOD IDENTIFICATION
-// PhantomElement::isPointInside Check if point is inside pelem
+// METHOD IDENTIFICATION
+// PhantomElement::isPointInside Check if point is inside pelem
//
// SYNOPSIS
// is_point_inside (pelem, x, y, coord_type)
-// double x, y Point to see if lies in pelem
-// int coord_type Coordinate type (PELEM_COORD or PHM_COORD)
+// double x, y Point to see if lies in pelem
+// int coord_type Coordinate type (PELEM_COORD or PHM_COORD)
//
// RETURNS
// true if point lies within pelem
sys_error(ERR_WARNING, "Illegal coordinate type in pelem_is_point_inside");
return (false);
}
-
+
switch (m_type) {
case PELEM_RECTANGLE:
if (x > 1. || x < -1. || y > 1. || y < -1.)
case PELEM_ELLIPSE:
if (x > 1. || x < -1. || y > 1. || y < -1.)
return (false);
- if (x * x + y * y > 1.) // check if inside unit circle
+ if (x * x + y * y > 1.) // check if inside unit circle
return (false);
else
return (true);
break;
-
+
// for clipping segments & sectors, must NOT scale by (1/u, 1/v)
- // because this destroys information about size of arc component
-
+ // because this destroys information about size of arc component
+
case PELEM_SEGMENT:
if (x > 1. || x < -1. || y > 0.)
- return (false); // clip against y > 0
- x *= m_u; // put back u & v scale
+ return (false); // clip against y > 0
+ x *= m_u; // put back u & v scale
y *= m_v;
if (x * x + (y-m_v) * (y-m_v) > m_u * m_u + m_v * m_v)
- return (false); // clip against circle, r = sqrt(@)
+ return (false); // clip against circle, r = sqrt(@)
else
return (true);
break;
case PELEM_SECTOR:
- if (x > 1. || x < -1. || y > 1.) // extent
+ if (x > 1. || x < -1. || y > 1.) // extent
return (false);
- if (y > 1. - x || y > 1. + x) // triangle
- return (false); // clip against triangle
- x *= m_u; // circle: put back u & v scale
+ if (y > 1. - x || y > 1. + x) // triangle
+ return (false); // clip against triangle
+ x *= m_u; // circle: put back u & v scale
y *= m_v;
if (x * x + (y-m_v) * (y-m_v) > m_u * m_u + m_v * m_v)
- return (false); // clip against circle
+ return (false); // clip against circle
else
return (true);
break;
sys_error (ERR_WARNING, "Illegal pelem type in pelem_is_point_inside()");
break;
}
-
+
return (false);
}
/*****************************************************************************
** File IDENTIFICATION
-**
+**
** Name: procsignal.cpp
** Purpose: Routines for processing signals and projections
-** Progammer: Kevin Rosenberg
+** Progammer: Kevin Rosenberg
** Date Started: Aug 1984
**
** This is part of the CTSim program
// CLASS IDENTIFICATION
// ProcessSignal
//
-ProcessSignal::ProcessSignal (const char* szFilterName, const char* szFilterMethodName, double dBandwidth,
- double dSignalIncrement, int nSignalPoints, double dFilterParam, const char* szDomainName,
- const char* szFilterGenerationName, int iZeropad, int iPreinterpolationFactor, int iTraceLevel,
+ProcessSignal::ProcessSignal (const char* szFilterName, const char* szFilterMethodName, double dBandwidth,
+ double dSignalIncrement, int nSignalPoints, double dFilterParam, const char* szDomainName,
+ const char* szFilterGenerationName, int iZeropad, int iPreinterpolationFactor, int iTraceLevel,
int iGeometry, double dFocalLength, double dSourceDetectorLength, SGP* pSGP)
: m_adFourierCosTable(NULL), m_adFourierSinTable(NULL), m_adFilter(NULL), m_fail(false)
{
m_failMessage += szDomainName;
return;
}
-
- init (m_idFilter, m_idFilterMethod, dBandwidth, dSignalIncrement, nSignalPoints, dFilterParam, m_idDomain,
- m_idFilterGeneration, iZeropad, iPreinterpolationFactor, iTraceLevel, iGeometry, dFocalLength,
+
+ init (m_idFilter, m_idFilterMethod, dBandwidth, dSignalIncrement, nSignalPoints, dFilterParam, m_idDomain,
+ m_idFilterGeneration, iZeropad, iPreinterpolationFactor, iTraceLevel, iGeometry, dFocalLength,
dSourceDetectorLength, pSGP);
}
void
-ProcessSignal::init (const int idFilter, const int idFilterMethod, double dBandwidth, double dSignalIncrement,
- int nSignalPoints, double dFilterParam, const int idDomain, const int idFilterGeneration,
- const int iZeropad, const int iPreinterpolationFactor, int iTraceLevel, int iGeometry,
+ProcessSignal::init (const int idFilter, const int idFilterMethod, double dBandwidth, double dSignalIncrement,
+ int nSignalPoints, double dFilterParam, const int idDomain, const int idFilterGeneration,
+ const int iZeropad, const int iPreinterpolationFactor, int iTraceLevel, int iGeometry,
double dFocalLength, double dSourceDetectorLength, SGP* pSGP)
{
int i;
m_idGeometry = iGeometry;
m_dFocalLength = dFocalLength;
m_dSourceDetectorLength = dSourceDetectorLength;
-
+
if (m_idFilter == SignalFilter::FILTER_INVALID || m_idDomain == SignalFilter::DOMAIN_INVALID || m_idFilterMethod == FILTER_METHOD_INVALID || m_idFilterGeneration == FILTER_GENERATION_INVALID) {
m_fail = true;
return;
m_dBandwidth = dBandwidth;
m_nSignalPoints = nSignalPoints;
m_dSignalInc = dSignalIncrement;
- m_dFilterParam = dFilterParam;
+ m_dFilterParam = dFilterParam;
m_iZeropad = iZeropad;
m_iPreinterpolationFactor = iPreinterpolationFactor;
-
- // scale signalInc/BW to adjust for imaginary detector through origin of phantom
+
+ // scale signalInc/BW to adjust for imaginary detector through origin of phantom
// see Kak-Slaney Fig 3.22, for Collinear diagram
if (m_idGeometry == Scanner::GEOMETRY_EQUILINEAR) {
double dEquilinearScale = m_dSourceDetectorLength / m_dFocalLength;
m_dSignalInc /= dEquilinearScale;
m_dBandwidth *= dEquilinearScale;
}
-
+
if (m_idFilterMethod == FILTER_METHOD_FFT) {
#if HAVE_FFTW
m_idFilterMethod = FILTER_METHOD_RFFTW;
return;
#endif
}
-
+
bool m_bFrequencyFiltering = true;
if (m_idFilterMethod == FILTER_METHOD_CONVOLUTION)
m_bFrequencyFiltering = false;
-
+
// Spatial-based filtering
if (! m_bFrequencyFiltering) {
-
+
if (m_idFilterGeneration == FILTER_GENERATION_DIRECT) {
m_nFilterPoints = 2 * (m_nSignalPoints - 1) + 1;
m_dFilterMin = -m_dSignalInc * (m_nSignalPoints - 1);
dlgEZPlot.getEZPlot()->addCurve (adFrequencyFilter, m_nFilterPoints);
dlgEZPlot.ShowModal();
}
-#endif
+#endif
Fourier::shuffleNaturalToFourierOrder (adFrequencyFilter, m_nFilterPoints);
#ifdef HAVE_SGP
if (g_bRunningWXWindows && m_traceLevel > 0) {
#endif
} // if (geometry)
} // if (spatial filtering)
-
+
else if (m_bFrequencyFiltering) { // Frequency-based filtering
-
+
if (m_idFilterGeneration == FILTER_GENERATION_DIRECT) {
// calculate number of filter points with zeropadding
m_nFilterPoints = addZeropadFactor (m_nSignalPoints, m_iZeropad);
m_nOutputPoints = m_nFilterPoints * m_iPreinterpolationFactor;
-
+
if (isOdd (m_nFilterPoints)) { // Odd
m_dFilterMin = -1. / (2 * m_dSignalInc);
m_dFilterMax = 1. / (2 * m_dSignalInc);
m_dFilterInc = (m_dFilterMax - m_dFilterMin) / m_nFilterPoints;
m_dFilterMax -= m_dFilterInc;
}
-
- SignalFilter filter (m_idFilter, m_dFilterMin, m_dFilterMax, m_nFilterPoints, m_dBandwidth,
+
+ SignalFilter filter (m_idFilter, m_dFilterMin, m_dFilterMax, m_nFilterPoints, m_dBandwidth,
m_dFilterParam, SignalFilter::DOMAIN_FREQUENCY);
m_adFilter = new double [m_nFilterPoints];
filter.copyFilterData (m_adFilter, 0, m_nFilterPoints);
-
+
#if defined(HAVE_WXWINDOWS) && (defined(DEBUG) || defined(_DEBUG))
if (g_bRunningWXWindows && m_traceLevel > 0) {
EZPlotDialog dlgEZPlot;
dlgEZPlot.ShowModal();
}
#endif
-
+
// This works fairly well. I'm not sure why since scaling for geometries is done on
// frequency filter rather than spatial filter as it should be.
// It gives values slightly off than freq/inverse filtering
dlgEZPlot.ShowModal();
}
#endif
-
+
// FILTERING: FREQUENCY - INVERSE FOURIER
-
+
} else if (m_idFilterGeneration == FILTER_GENERATION_INVERSE_FOURIER) {
// calculate number of filter points with zeropadding
int nSpatialPoints = 2 * (m_nSignalPoints - 1) + 1;
sys_error (ERR_TRACE, "nFilterPoints = %d", m_nFilterPoints);
#endif
double* adSpatialFilter = new double [m_nFilterPoints];
- SignalFilter filter (m_idFilter, m_dFilterMin, m_dFilterMax, nSpatialPoints, m_dBandwidth,
+ SignalFilter filter (m_idFilter, m_dFilterMin, m_dFilterMax, nSpatialPoints, m_dBandwidth,
m_dFilterParam, SignalFilter::DOMAIN_SPATIAL);
filter.copyFilterData (adSpatialFilter, 0, nSpatialPoints);
#if defined(HAVE_WXWINDOWS) && (defined(DEBUG) || defined(_DEBUG))
dlgEZPlot.ShowModal();
}
#endif
-
+
if (m_idGeometry == Scanner::GEOMETRY_EQUILINEAR) {
for (i = 0; i < nSpatialPoints; i++)
adSpatialFilter[i] *= 0.5;
#endif
for (i = nSpatialPoints; i < m_nFilterPoints; i++)
adSpatialFilter[i] = 0;
-
+
m_adFilter = new double [m_nFilterPoints];
std::complex<double>* acInverseFilter = new std::complex<double> [m_nFilterPoints];
finiteFourierTransform (adSpatialFilter, acInverseFilter, m_nFilterPoints, BACKWARD);
#endif
}
}
-
+
// precalculate sin and cosine tables for fourier transform
if (m_idFilterMethod == FILTER_METHOD_FOURIER_TABLE) {
int nFourier = imax (m_nFilterPoints,m_nOutputPoints) * imax (m_nFilterPoints, m_nOutputPoints) + 1;
angle += angleIncrement;
}
}
-
+
#if HAVE_FFTW
if (m_idFilterMethod == FILTER_METHOD_FFTW || m_idFilterMethod == FILTER_METHOD_RFFTW) {
for (i = 0; i < m_nFilterPoints; i++) //fftw uses unnormalized fft
m_adFilter[i] /= m_nFilterPoints;
}
-
+
if (m_idFilterMethod == FILTER_METHOD_RFFTW) {
m_adRealFftInput = static_cast<double*>(fftw_malloc (sizeof(double) * m_nFilterPoints));
m_adRealFftOutput = static_cast<double*>(fftw_malloc (sizeof(double) * m_nFilterPoints));
m_adRealFftSignal = static_cast<double*>(fftw_malloc (sizeof(double) * m_nOutputPoints));
m_adRealFftBackwardOutput = static_cast<double*>(fftw_malloc (sizeof(double) * m_nOutputPoints));
m_realPlanBackward = fftw_plan_r2r_1d (m_nOutputPoints, m_adRealFftSignal, m_adRealFftBackwardOutput, FFTW_HC2R, FFTW_ESTIMATE);
- for (i = 0; i < m_nFilterPoints; i++)
+ for (i = 0; i < m_nFilterPoints; i++)
m_adRealFftInput[i] = 0;
} else if (m_idFilterMethod == FILTER_METHOD_FFTW) {
m_adComplexFftInput = static_cast<fftw_complex*>(fftw_malloc (sizeof(fftw_complex) * m_nFilterPoints));
m_adComplexFftBackwardOutput = static_cast<fftw_complex*>(fftw_malloc (sizeof(fftw_complex) * m_nOutputPoints));
m_complexPlanBackward = fftw_plan_dft_1d (m_nOutputPoints, m_adComplexFftSignal, m_adComplexFftBackwardOutput, FFTW_BACKWARD, FFTW_ESTIMATE);
- for (i = 0; i < m_nFilterPoints; i++)
+ for (i = 0; i < m_nFilterPoints; i++)
m_adComplexFftInput[i][0] = m_adComplexFftInput[i][1] = 0;
- for (i = 0; i < m_nOutputPoints; i++)
+ for (i = 0; i < m_nOutputPoints; i++)
m_adComplexFftSignal[i][0] = m_adComplexFftSignal[i][1] = 0;
}
#endif
-
+
}
ProcessSignal::~ProcessSignal (void)
delete [] m_adFourierSinTable;
delete [] m_adFourierCosTable;
delete [] m_adFilter;
-
+
#if HAVE_FFTW
if (m_idFilterMethod == FILTER_METHOD_FFTW) {
fftw_destroy_plan(m_complexPlanForward);
ProcessSignal::convertFilterMethodNameToID (const char* const filterMethodName)
{
int fmID = FILTER_METHOD_INVALID;
-
+
for (int i = 0; i < s_iFilterMethodCount; i++)
if (strcasecmp (filterMethodName, s_aszFilterMethodName[i]) == 0) {
fmID = i;
break;
}
-
+
return (fmID);
}
ProcessSignal::convertFilterMethodIDToName (const int fmID)
{
static const char *name = "";
-
+
if (fmID >= 0 && fmID < s_iFilterMethodCount)
return (s_aszFilterMethodName [fmID]);
-
+
return (name);
}
ProcessSignal::convertFilterMethodIDToTitle (const int fmID)
{
static const char *title = "";
-
+
if (fmID >= 0 && fmID < s_iFilterMethodCount)
return (s_aszFilterMethodTitle [fmID]);
-
+
return (title);
}
ProcessSignal::convertFilterGenerationNameToID (const char* const fgName)
{
int fgID = FILTER_GENERATION_INVALID;
-
+
for (int i = 0; i < s_iFilterGenerationCount; i++)
if (strcasecmp (fgName, s_aszFilterGenerationName[i]) == 0) {
fgID = i;
break;
}
-
+
return (fgID);
}
ProcessSignal::convertFilterGenerationIDToName (const int fgID)
{
static const char *name = "";
-
+
if (fgID >= 0 && fgID < s_iFilterGenerationCount)
return (s_aszFilterGenerationName [fgID]);
-
+
return (name);
}
ProcessSignal::convertFilterGenerationIDToTitle (const int fgID)
{
static const char *name = "";
-
+
if (fgID >= 0 && fgID < s_iFilterGenerationCount)
return (s_aszFilterGenerationTitle [fgID]);
-
+
return (name);
}
int i;
for (i = 0; i < m_nSignalPoints; i++)
input[i] = constInput[i];
-
+
if (m_idGeometry == Scanner::GEOMETRY_EQUILINEAR) {
for (int i = 0; i < m_nSignalPoints; i++) {
int iDetFromCenter = i - (m_nSignalPoints / 2);
double* inverseFourier = new double [m_nFilterPoints];
finiteFourierTransform (fftSignal, inverseFourier, m_nFilterPoints, BACKWARD);
delete fftSignal;
- for (i = 0; i < m_nSignalPoints; i++)
+ for (i = 0; i < m_nSignalPoints; i++)
output[i] = inverseFourier[i];
delete inverseFourier;
} else if (m_idFilterMethod == FILTER_METHOD_FOURIER_TABLE) {
double* inverseFourier = new double [m_nFilterPoints];
finiteFourierTransform (fftSignal, inverseFourier, BACKWARD);
delete fftSignal;
- for (i = 0; i < m_nSignalPoints; i++)
+ for (i = 0; i < m_nSignalPoints; i++)
output[i] = inverseFourier[i];
delete inverseFourier;
}
else if (m_idFilterMethod == FILTER_METHOD_RFFTW) {
for (i = 0; i < m_nSignalPoints; i++)
m_adRealFftInput[i] = input[i];
-
+
fftw_execute (m_realPlanForward);
for (i = 0; i < m_nFilterPoints; i++)
m_adRealFftSignal[i] = m_adFilter[i] * m_adRealFftOutput[i];
for (i = m_nFilterPoints; i < m_nOutputPoints; i++)
- m_adRealFftSignal[i] = 0;
-
+ m_adRealFftSignal[i] = 0;
+
fftw_execute (m_realPlanBackward);
for (i = 0; i < m_nSignalPoints * m_iPreinterpolationFactor; i++)
output[i] = m_adRealFftBackwardOutput[i];
} else if (m_idFilterMethod == FILTER_METHOD_FFTW) {
for (i = 0; i < m_nSignalPoints; i++)
m_adComplexFftInput[i][0] = input[i];
-
+
fftw_execute (m_complexPlanForward);
for (i = 0; i < m_nFilterPoints; i++) {
m_adComplexFftSignal[i][0] = m_adFilter[i] * m_adComplexFftOutput[i][0];
m_adComplexFftSignal[i][1] = m_adFilter[i] * m_adComplexFftOutput[i][1];
}
fftw_execute (m_complexPlanBackward);
- for (i = 0; i < m_nSignalPoints * m_iPreinterpolationFactor; i++)
+ for (i = 0; i < m_nSignalPoints * m_iPreinterpolationFactor; i++)
output[i] = m_adComplexFftBackwardOutput[i][0];
}
#endif
/* NAME
-* convolve Discrete convolution of two functions
+* convolve Discrete convolution of two functions
*
* SYNOPSIS
* r = convolve (f1, f2, dx, n, np, func_type)
-* double r Convolved result
-* double f1[], f2[] Functions to be convolved
-* double dx Difference between successive x values
-* int n Array index to center convolution about
-* int np Number of points in f1 array
-* int func_type EVEN or ODD or EVEN_AND_ODD function f2
+* double r Convolved result
+* double f1[], f2[] Functions to be convolved
+* double dx Difference between successive x values
+* int n Array index to center convolution about
+* int np Number of points in f1 array
+* int func_type EVEN or ODD or EVEN_AND_ODD function f2
*
* NOTES
* f1 is the projection data, its indices range from 0 to np - 1.
* The index for f2, the filter, ranges from -(np-1) to (np-1).
* There are 3 ways to handle the negative vertices of f2:
-* 1. If we know f2 is an EVEN function, then f2[-n] = f2[n].
-* All filters used in reconstruction are even.
-* 2. If we know f2 is an ODD function, then f2[-n] = -f2[n]
+* 1. If we know f2 is an EVEN function, then f2[-n] = f2[n].
+* All filters used in reconstruction are even.
+* 2. If we know f2 is an ODD function, then f2[-n] = -f2[n]
* 3. If f2 is both ODD AND EVEN, then we must store the value of f2
-* for negative indices. Since f2 must range from -(np-1) to (np-1),
-* if we add (np - 1) to f2's array index, then f2's index will
-* range from 0 to 2 * (np - 1), and the origin, x = 0, will be
-* stored at f2[np-1].
+* for negative indices. Since f2 must range from -(np-1) to (np-1),
+* if we add (np - 1) to f2's array index, then f2's index will
+* range from 0 to 2 * (np - 1), and the origin, x = 0, will be
+* stored at f2[np-1].
*/
-double
+double
ProcessSignal::convolve (const double func[], const double dx, const int n, const int np) const
{
double sum = 0.0;
-
+
#if UNOPTIMIZED_CONVOLUTION
for (int i = 0; i < np; i++)
sum += func[i] * m_adFilter[n - i + (np - 1)];
for (int i = 0; i < np; i++)
sum += *func++ * *f2--;
#endif
-
+
return (sum * dx);
}
-double
+double
ProcessSignal::convolve (const float func[], const double dx, const int n, const int np) const
{
double sum = 0.0;
-
+
#if UNOPTIMIZED_CONVOLUTION
for (int i = 0; i < np; i++)
sum += func[i] * m_adFilter[n - i + (np - 1)];
for (int i = 0; i < np; i++)
sum += *func++ * *f2--;
#endif
-
+
return (sum * dx);
}
ProcessSignal::finiteFourierTransform (const double input[], double output[], const int n, int direction)
{
std::complex<double>* complexOutput = new std::complex<double> [n];
-
+
finiteFourierTransform (input, complexOutput, n, direction);
for (int i = 0; i < n; i++)
output[i] = complexOutput[i].real();
{
if (direction < 0)
direction = -1;
- else
+ else
direction = 1;
-
+
double angleIncrement = direction * 2 * PI / n;
for (int i = 0; i < n; i++) {
double sumReal = 0;
{
if (direction < 0)
direction = -1;
- else
+ else
direction = 1;
-
+
double angleIncrement = direction * 2 * PI / n;
for (int i = 0; i < n; i++) {
std::complex<double> sum (0,0);
{
if (direction < 0)
direction = -1;
- else
+ else
direction = 1;
-
+
double angleIncrement = direction * 2 * PI / n;
for (int i = 0; i < n; i++) {
double sumReal = 0;
{
if (direction < 0)
direction = -1;
- else
+ else
direction = 1;
-
+
for (int i = 0; i < m_nFilterPoints; i++) {
double sumReal = 0, sumImag = 0;
for (int j = 0; j < m_nFilterPoints; j++) {
{
if (direction < 0)
direction = -1;
- else
+ else
direction = 1;
-
+
for (int i = 0; i < m_nFilterPoints; i++) {
double sumReal = 0, sumImag = 0;
for (int j = 0; j < m_nFilterPoints; j++) {
int tableIndex = i * j;
if (direction > 0) {
- sumReal += input[j].real() * m_adFourierCosTable[tableIndex]
+ sumReal += input[j].real() * m_adFourierCosTable[tableIndex]
- input[j].imag() * m_adFourierSinTable[tableIndex];
sumImag += input[j].real() * m_adFourierSinTable[tableIndex]
+ input[j].imag() * m_adFourierCosTable[tableIndex];
} else {
- sumReal += input[j].real() * m_adFourierCosTable[tableIndex]
+ sumReal += input[j].real() * m_adFourierCosTable[tableIndex]
- input[j].imag() * -m_adFourierSinTable[tableIndex];
sumImag += input[j].real() * -m_adFourierSinTable[tableIndex]
+ input[j].imag() * m_adFourierCosTable[tableIndex];
{
if (direction < 0)
direction = -1;
- else
+ else
direction = 1;
-
+
for (int i = 0; i < m_nFilterPoints; i++) {
double sumReal = 0;
for (int j = 0; j < m_nFilterPoints; j++) {
int tableIndex = i * j;
if (direction > 0) {
- sumReal += input[j].real() * m_adFourierCosTable[tableIndex]
+ sumReal += input[j].real() * m_adFourierCosTable[tableIndex]
- input[j].imag() * m_adFourierSinTable[tableIndex];
} else {
- sumReal += input[j].real() * m_adFourierCosTable[tableIndex]
+ sumReal += input[j].real() * m_adFourierCosTable[tableIndex]
- input[j].imag() * -m_adFourierSinTable[tableIndex];
}
}
/*****************************************************************************
** FILE IDENTIFICATION
**
-** Name: projections.cpp Projection data classes
+** Name: projections.cpp Projection data classes
** Programmer: Kevin Rosenberg
** Date Started: Aug 84
**
const int Projections::POLAR_INTERP_BILINEAR = 1;
const int Projections::POLAR_INTERP_BICUBIC = 2;
-const char* const Projections::s_aszInterpName[] =
+const char* const Projections::s_aszInterpName[] =
{
"nearest",
"bilinear",
// {"bicubic"},
};
-const char* const Projections::s_aszInterpTitle[] =
+const char* const Projections::s_aszInterpTitle[] =
{
"Nearest",
"Bilinear",
/* NAME
-* Projections Constructor for projections matrix storage
+* Projections Constructor for projections matrix storage
*
* SYNOPSIS
* proj = projections_create (filename, nView, nDet)
-* Projections& proj Allocated projections structure & matrix
-* int nView Number of rotated view
-* int nDet Number of detectors
+* Projections& proj Allocated projections structure & matrix
+* int nView Number of rotated view
+* int nDet Number of detectors
*
*/
Projections::convertInterpNameToID (const char* const interpName)
{
int interpID = POLAR_INTERP_INVALID;
-
+
for (int i = 0; i < s_iInterpCount; i++)
if (strcasecmp (interpName, s_aszInterpName[i]) == 0) {
interpID = i;
break;
}
-
+
return (interpID);
}
Projections::convertInterpIDToName (const int interpID)
{
static const char *interpName = "";
-
+
if (interpID >= 0 && interpID < s_iInterpCount)
return (s_aszInterpName[interpID]);
-
+
return (interpName);
}
Projections::convertInterpIDToTitle (const int interpID)
{
static const char *interpTitle = "";
-
+
if (interpID >= 0 && interpID < s_iInterpCount)
return (s_aszInterpTitle[interpID]);
-
+
return (interpTitle);
}
m_nView = nView;
m_nDet = nDet;
newProjData ();
-
+
time_t t = time (NULL);
tm* lt = localtime (&t);
m_year = lt->tm_year;
m_label.setLabelType (Array2dFileLabel::L_HISTORY);
deleteProjData();
init (scanner.nView(), scanner.nDet());
-
+
m_rotInc = scanner.rotInc();
m_detInc = scanner.detInc();
m_detStart = scanner.detStart();
}
// Helical 180 Linear Interpolation.
-// This member function takes a set of helical scan projections and
-// performs a linear interpolation between pairs of complementary rays
+// This member function takes a set of helical scan projections and
+// performs a linear interpolation between pairs of complementary rays
// to produce a single projection data set approximating what would be
// measured at a single axial plane.
-// Complementary rays are rays which traverse the same path through the
+// Complementary rays are rays which traverse the same path through the
// phantom in opposite directions.
//
// For parallel beam geometry, a ray with a given gantry angle beta and a
// detector iDet will have a complementary ray at beta + pi and nDet-iDet
//
// For equiangular or equilinear beam geometry the complementary ray to
-// gantry angle beta and fan-beam angle gamma is at
+// gantry angle beta and fan-beam angle gamma is at
// beta-hat = beta +2*gamma + pi, and gamma-hat = -gamma.
// Note that beta-hat - beta depends on gamma and is not constant.
//
// The algorithm used here is from Crawford and King, Med. Phys. 17(6)
// 1990 p967; what they called method "C", CSH-HH. It uses interpolation only
// between pairs of complementary rays on either side of an image plane.
-// Input data must sample gantry angles from zero to
+// Input data must sample gantry angles from zero to
// (2*pi + 2* fan-beam-angle). The data set produced contains gantry
// angles from 0 to Pi+fan-beam-angle. This is a "halfscan" data set,
-// which still contains redundant data, and can be used with a half scan
+// which still contains redundant data, and can be used with a half scan
// reconstruction to produce an image.
// In this particular implementation a lower triangle from (beta,gamma) =
// (0,-fanAngle/2)->(2*fanAngle,-fanAngle/2)->(0,fanAngle/2) contains
// zeros, but is actually redundant with data contained in the region
// (pi+fanAngle,-fanAngle/2)->(pi+fanAngle, fanAngle/2) ->(pi-fanAngle,
-// fanAngle/2).
+// fanAngle/2).
//
-int
+int
Projections::Helical180LI(int interpolation_view)
{
- if (m_geometry == Scanner::GEOMETRY_INVALID)
+ if (m_geometry == Scanner::GEOMETRY_INVALID)
{
std::cerr << "Invalid geometry " << m_geometry << std::endl;
return (2);
- }
- else if (m_geometry == Scanner::GEOMETRY_PARALLEL)
+ }
+ else if (m_geometry == Scanner::GEOMETRY_PARALLEL)
{
std::cerr << "Helical 180LI not yet implemented for PARALLEL geometry"
<< std::endl;
return (2);
}
- else if (m_geometry == Scanner::GEOMETRY_EQUILINEAR)
+ else if (m_geometry == Scanner::GEOMETRY_EQUILINEAR)
{
std::cerr << "Helical 180LI not yet implemented for EQUILINEAR geometry"
<< std::endl;
return (2);
}
- else if (m_geometry == Scanner::GEOMETRY_EQUIANGULAR)
+ else if (m_geometry == Scanner::GEOMETRY_EQUIANGULAR)
{
return Helical180LI_Equiangular(interpolation_view);
}
int
Projections::Helical180LI_Equiangular(int interpView)
{
- double dbeta = m_rotInc;
- double dgamma = m_detInc;
+ double dbeta = m_rotInc;
+ double dgamma = m_detInc;
double fanAngle = m_dFanBeamAngle;
int offsetView=0;
-
+
// is there enough data in the data set? Should have 2(Pi+fanAngle)
// coverage minimum
if ( m_nView < static_cast<int>((2*( PI + fanAngle ) ) / dbeta) -1 ){
}
else
{
- // check if there is PI+fanAngle data on either side of the
+ // check if there is PI+fanAngle data on either side of the
// of the specified image plane
- if ( interpView*dbeta < PI+fanAngle ||
- interpView*dbeta + PI + fanAngle > m_nView*dbeta)
+ if ( interpView*dbeta < PI+fanAngle ||
+ interpView*dbeta + PI + fanAngle > m_nView*dbeta)
{
std::cerr << "There isn't PI+fanAngle of data on either side of the requested interpolation view" << std::endl;
return(1);
}
int last_interp_view = static_cast<int> ((PI+fanAngle)/dbeta);
-
+
// make a new array for data...
class DetectorArray ** newdetarray = new DetectorArray * [last_interp_view+1];
for ( int i=0 ; i <= last_interp_view ; i++ ){
newdetarray[i]->setViewAngle((i+offsetView)*dbeta);
DetectorValue* newdetval = (newdetarray[i])->detValues();
// and initialize the data to zero
- for (int j=0; j < m_nDet; j++)
+ for (int j=0; j < m_nDet; j++)
newdetval[j] = 0.;
}
int last_acq_view = 2*last_interp_view;
for ( int iView = 0 ; iView <= last_acq_view; iView++) {
- double beta = iView * dbeta;
-
+ double beta = iView * dbeta;
+
for ( int iDet = 0; iDet < m_nDet; iDet++) {
double gamma = (iDet -(m_nDet-1)/2)* dgamma ;
int newiView, newiDet;
- if (beta < PI+fanAngle) { //if (PI +fanAngle - beta > dbeta )
- //newbeta = beta;
- //newgamma = gamma;
- newiDet = iDet;
- newiView = iView;
+ if (beta < PI+fanAngle) { //if (PI +fanAngle - beta > dbeta )
+ //newbeta = beta;
+ //newgamma = gamma;
+ newiDet = iDet;
+ newiView = iView;
}
else // (beta > PI+fanAngle)
{
// newiView = nearest<int>((beta + 2*gamma - PI)/dbeta);
//newiView = static_cast<int>(( (iView*dbeta) + 2*(iDet-(m_nDet-1)/2)*dgamma - PI)/dbeta);
newiView = nearest<int>(( (iView*dbeta) + 2*(iDet-(m_nDet-1)/2)*dgamma - PI)/dbeta);
- }
+ }
#ifdef DEBUG
//std::cout << beta << " "<< gamma << " " << newbeta << " " << newgamma <<" " << iView-offsetView << " " << iDet << " " << newiView << " " << newiDet << std::endl;
//std::cout << iView-offsetView << " " << iDet << " " << newiView << " " << newiDet << std::endl;
#endif
- if ( ( beta > fanAngle - 2*gamma)
+ if ( ( beta > fanAngle - 2*gamma)
&& ( beta < 2*PI + fanAngle -2*gamma) )
{ // not in region 1 or 8
DetectorValue* detval = (m_projData[iView+offsetView])->detValues();
DetectorValue* newdetval = (newdetarray[newiView])->detValues();
- if ( beta > fanAngle - 2*gamma
+ if ( beta > fanAngle - 2*gamma
&& beta <= 2*fanAngle ) { // in region 2
- newdetval[newiDet] +=
+ newdetval[newiDet] +=
(beta +2*gamma - fanAngle)/(PI+2*gamma)
* detval[iDet];
- } else if ( beta > 2*fanAngle
+ } else if ( beta > 2*fanAngle
&& beta <= PI - 2*gamma) { // in region 3
- newdetval[newiDet] +=
+ newdetval[newiDet] +=
(beta +2*gamma - fanAngle)/(PI+2*gamma)
* detval[iDet];
- }
- else if ( beta > PI -2*gamma
+ }
+ else if ( beta > PI -2*gamma
&& beta <= PI + fanAngle ) { // in region 4
- newdetval[newiDet] +=
+ newdetval[newiDet] +=
(beta +2*gamma - fanAngle)/(PI+2*gamma)
* detval[iDet];
- }
- else if ( beta > PI + fanAngle
+ }
+ else if ( beta > PI + fanAngle
&& beta <= PI +2*fanAngle -2*gamma) { // in region 5
- newdetval[newiDet] +=
+ newdetval[newiDet] +=
(2*PI - beta - 2*gamma + fanAngle)/(PI-2*gamma)
*detval[iDet];
- }
- else if ( beta > PI +2*fanAngle -2*gamma
+ }
+ else if ( beta > PI +2*fanAngle -2*gamma
&& beta <= 2*PI) { // in region 6
- newdetval[newiDet] +=
+ newdetval[newiDet] +=
(2*PI - beta - 2*gamma + fanAngle)/(PI-2*gamma)
*detval[iDet];
- }
- else if ( beta > 2*PI
+ }
+ else if ( beta > 2*PI
&& beta <= 2*PI + fanAngle -2*gamma){ // in region 7
- newdetval[newiDet] +=
+ newdetval[newiDet] +=
(2*PI - beta -2*gamma + fanAngle)/(PI-2*gamma)
*detval[iDet];
- }
- else
- {
+ }
+ else
+ {
; // outside region of interest
}
}
m_projData = newdetarray;
m_nView = last_interp_view+1;
- return (0);
+ return (0);
}
// HalfScanFeather:
-// A HalfScan Projection Data Set for equiangular geometry,
-// covering gantry angles from 0 to pi+fanBeamAngle
+// A HalfScan Projection Data Set for equiangular geometry,
+// covering gantry angles from 0 to pi+fanBeamAngle
// and fan angle gamma from -fanBeamAngle/2 to fanBeamAngle/2
// contains redundant information. If one copy of this data is left as
-// zero, (as in the Helical180LI routine above) overweighting is avoided,
-// but the discontinuity in the data introduces ringing in the image.
+// zero, (as in the Helical180LI routine above) overweighting is avoided,
+// but the discontinuity in the data introduces ringing in the image.
// This routine makes a copy of the data and applies a weighting to avoid
// over-representation, as given in Appendix C of Crawford and King, Med
// Phys 17 1990, p967.
int
Projections::HalfScanFeather(void)
{
- double dbeta = m_rotInc;
- double dgamma = m_detInc;
+ double dbeta = m_rotInc;
+ double dgamma = m_detInc;
double fanAngle = m_dFanBeamAngle;
-// is there enough data?
+// is there enough data?
if ( m_nView != static_cast<int>(( PI+fanAngle ) / dbeta) +1 ){
std::cerr << "Data set does seem have enough data to be a halfscan data set" << std::endl;
return (1);
}
for ( int iView2 = 0 ; iView2 < m_nView; iView2++) {
- double beta2 = iView2 * dbeta;
+ double beta2 = iView2 * dbeta;
for ( int iDet2 = 0; iDet2 < m_nDet; iDet2++) {
double gamma2 = (iDet2 -(m_nDet-1)/2)* dgamma ;
- if ( ( beta2 >= PI - 2*gamma2) ) { // in redundant data region
+ if ( ( beta2 >= PI - 2*gamma2) ) { // in redundant data region
int iView1, iDet1;
iDet1 = (m_nDet -1) - iDet2;
//iView1 = nearest<int>((beta2 + 2*gamma2 - PI)/dbeta);
- iView1 = nearest<int>(( (iView2*dbeta)
+ iView1 = nearest<int>(( (iView2*dbeta)
+ 2*(iDet2-(m_nDet-1)/2)*dgamma - PI)/dbeta);
detval1[iDet1] = detval2[iDet2] ;
double x, w1,w2,beta1, gamma1;
- beta1= iView1*dbeta;
+ beta1= iView1*dbeta;
gamma1 = -gamma2;
if ( beta1 <= (fanAngle - 2*gamma1) )
x = beta1 / ( fanAngle - 2*gamma1);
- else if ( (fanAngle - 2*gamma1 <= beta1 ) && beta1 <= PI - 2*gamma1)
- x = 1;
- else if ( (PI - 2*gamma1 <= beta1 ) && ( beta1 <=PI + fanAngle) )
+ else if ( (fanAngle - 2*gamma1 <= beta1 ) && beta1 <= PI - 2*gamma1)
+ x = 1;
+ else if ( (PI - 2*gamma1 <= beta1 ) && ( beta1 <=PI + fanAngle) )
x = (PI +fanAngle - beta1)/(fanAngle + 2*gamma1);
else {
std::cerr << "Shouldn't be here!"<< std::endl;
}
w1 = (3*x - 2*x*x)*x;
w2 = 1-w1;
- detval1[iDet1] *= w1;
+ detval1[iDet1] *= w1;
detval2[iDet2] *= w2;
- }
+ }
}
}
- // heuristic scaling, why this factor?
+ // heuristic scaling, why this factor?
double scalefactor = m_nView * m_rotInc / PI;
for ( int iView = 0 ; iView < m_nView; iView++) {
DetectorValue* detval = (m_projData[iView])->detValues();
}
}
- return (0);
+ return (0);
}
// NAME
// newProjData
-void
+void
Projections::newProjData (void)
{
if (m_projData)
sys_error(ERR_WARNING, "m_projData != NULL [newProjData]");
-
+
if (m_nView > 0 && m_nDet) {
m_projData = new DetectorArray* [m_nView];
-
+
for (int i = 0; i < m_nView; i++)
m_projData[i] = new DetectorArray (m_nDet);
}
/* NAME
-* projections_free Free memory allocated to projections
+* projections_free Free memory allocated to projections
*
* SYNOPSIS
* projections_free(proj)
-* Projections& proj Projectionss to be deallocated
+* Projections& proj Projectionss to be deallocated
*/
-void
+void
Projections::deleteProjData (void)
{
if (m_projData != NULL) {
for (int i = 0; i < m_nView; i++)
delete m_projData[i];
-
+
delete m_projData;
m_projData = NULL;
}
*
*/
-bool
+bool
Projections::headerWrite (fnetorderstream& fs)
{
kuint16 _hsize = m_headerSize;
kuint16 _hour = m_hour;
kuint16 _minute = m_minute;
kuint16 _second = m_second;
-
+
kfloat64 _calcTime = m_calcTime;
kfloat64 _rotStart = m_rotStart;
kfloat64 _rotInc = m_rotInc;
fs.seekp(0);
if (! fs)
return false;
-
+
fs.writeInt16 (_hsize);
fs.writeInt16 (_signature);
fs.writeInt32 (_nView);
fs.writeInt16 (_second);
fs.writeInt16 (_remarksize);
fs.write (m_remark.c_str(), _remarksize);
-
+
m_headerSize = fs.tellp();
_hsize = m_headerSize;
fs.seekp(0);
fs.writeInt16 (_hsize);
if (! fs)
return false;
-
+
return true;
}
kuint16 _hsize, _signature, _year, _month, _day, _hour, _minute, _second, _remarksize = 0;
kuint32 _nView, _nDet, _geom;
kfloat64 _calcTime, _rotStart, _rotInc, _detStart, _detInc, _focalLength, _sourceDetectorLength, _viewDiameter, _fanBeamAngle;
-
+
fs.seekg(0);
if (! fs)
return false;
-
+
fs.readInt16 (_hsize);
fs.readInt16 (_signature);
fs.readInt32 (_nView);
fs.readInt16 (_minute);
fs.readInt16 (_second);
fs.readInt16 (_remarksize);
-
+
if (! fs) {
sys_error (ERR_SEVERE, "Error reading header information , _remarksize=%d [projections_read_header]", _remarksize);
return false;
}
-
+
if (_signature != m_signature) {
sys_error (ERR_SEVERE, "File %s does not have a valid projection file signature", m_filename.c_str());
return false;
}
-
+
char* pszRemarkStorage = new char [_remarksize+1];
fs.read (pszRemarkStorage, _remarksize);
if (! fs) {
pszRemarkStorage[_remarksize] = 0;
m_remark = pszRemarkStorage;
delete pszRemarkStorage;
-
+
off_t _hsizeread = fs.tellg();
if (!fs || _hsizeread != _hsize) {
sys_error (ERR_WARNING, "File header size read %ld != file header size stored %ld [read_projections_header]\n_remarksize=%ld", (long int) _hsizeread, _hsize, _remarksize);
return false;
}
-
+
m_headerSize = _hsize;
m_nView = _nView;
m_nDet = _nDet;
m_hour = _hour;
m_minute = _minute;
m_second = _second;
-
+
m_label.setLabelType (Array2dFileLabel::L_HISTORY);
m_label.setLabelString (m_remark);
m_label.setCalcTime (m_calcTime);
m_label.setDateTime (m_year, m_month, m_day, m_hour, m_minute, m_second);
-
+
return true;
}
#else
frnetorderstream fileRead (m_filename.c_str(), std::ios::in | std::ios::binary); // | std::ios::nocreate);
#endif
-
+
if (fileRead.fail())
return false;
-
+
if (! headerRead (fileRead))
return false;
-
+
deleteProjData ();
newProjData();
-
+
for (int i = 0; i < m_nView; i++) {
if (! detarrayRead (fileRead, *m_projData[i], i))
break;
}
-
+
fileRead.close();
return true;
}
-bool
+bool
Projections::copyViewData (const std::string& filename, std::ostream& os, int startView, int endView)
{
return copyViewData (filename.c_str(), os, startView, endView);
}
-bool
+bool
Projections::copyViewData (const char* const filename, std::ostream& os, int startView, int endView)
{
frnetorderstream is (filename, std::ios::in | std::ios::binary);
kuint16 sizeHeader, signature;
kuint32 _nView, _nDet;
-
+
is.seekg (0);
if (is.fail()) {
sys_error (ERR_SEVERE, "Unable to read projection file %s", filename);
is.readInt32 (_nDet);
int nView = _nView;
int nDet = _nDet;
-
+
if (signature != m_signature) {
sys_error (ERR_SEVERE, "Illegal signature in projection file %s", filename);
return false;
}
-
+
if (startView < 0)
startView = 0;
if (startView > nView - 1)
startView = nView;
if (endView < 0 || endView > nView - 1)
endView = nView - 1;
-
+
if (startView > endView) { // swap if start > end
int tempView = endView;
endView = startView;
startView = tempView;
}
-
+
int sizeView = 8 /* view_angle */ + 4 /* nDet */ + (4 * nDet);
unsigned char* pViewData = new unsigned char [sizeView];
-
+
for (int i = startView; i <= endView; i++) {
is.seekg (sizeHeader + i * sizeView);
is.read (reinterpret_cast<char*>(pViewData), sizeView);
if (is.fail() || os.fail())
break;
}
-
+
delete pViewData;
- if (is.fail())
+ if (is.fail())
sys_error (ERR_SEVERE, "Error reading projection file");
- if (os.fail())
+ if (os.fail())
sys_error (ERR_SEVERE, "Error writing projection file");
-
+
return (! (is.fail() | os.fail()));
}
-bool
+bool
Projections::copyHeader (const std::string& filename, std::ostream& os)
{
return copyHeader (filename.c_str(), os);
sys_error (ERR_SEVERE, "Illegal signature in projection file %s", filename);
return false;
}
-
+
unsigned char* pHdrData = new unsigned char [sizeHeader];
is.read (reinterpret_cast<char*>(pHdrData), sizeHeader);
if (is.fail()) {
sys_error (ERR_SEVERE, "Error reading header");
return false;
}
-
+
os.write (reinterpret_cast<char*>(pHdrData), sizeHeader);
if (os.fail()) {
sys_error (ERR_SEVERE, "Error writing header");
return false;
}
-
+
return true;
}
sys_error (ERR_SEVERE, "Error opening file %s for output [projections_create]", filename);
return false;
}
-
+
if (! headerWrite (fs))
return false;
-
+
if (m_projData != NULL) {
for (int i = 0; i < m_nView; i++) {
if (! detarrayWrite (fs, *m_projData[i], i))
}
if (! fs)
return false;
-
+
fs.close();
-
+
return true;
}
/* NAME
-* detarrayRead Read a Detector Array structure from the disk
+* detarrayRead Read a Detector Array structure from the disk
*
* SYNOPSIS
* detarrayRead (proj, darray, view_num)
-* DETARRAY *darray Detector array storage location to be filled
-* int view_num View number to read
+* DETARRAY *darray Detector array storage location to be filled
+* int view_num View number to read
*/
bool
const int detheader_bytes = sizeof(kfloat64) /* view_angle */ + sizeof(kint32) /* nDet */;
const int view_bytes = detheader_bytes + detval_bytes;
const off_t start_data = m_headerSize + (iview * view_bytes);
- DetectorValue* detval_ptr = darray.detValues();
+ DetectorValue* detval_ptr = darray.detValues();
kfloat64 view_angle;
kuint32 nDet;
-
+
fs.seekg (start_data);
-
+
fs.readFloat64 (view_angle);
fs.readInt32 (nDet);
darray.setViewAngle (view_angle);
// darray.setNDet ( nDet);
-
+
for (unsigned int i = 0; i < nDet; i++) {
kfloat32 detval;
fs.readFloat32 (detval);
}
if (! fs)
return false;
-
+
return true;
}
/* NAME
-* detarrayWrite Write detector array data to the disk
+* detarrayWrite Write detector array data to the disk
*
* SYNOPSIS
* detarrayWrite (darray, view_num)
-* DETARRAY *darray Detector array data to be written
-* int view_num View number to write
+* DETARRAY *darray Detector array data to be written
+* int view_num View number to write
*
* DESCRIPTION
* This routine writes the detarray data from the disk sequentially to
const int detheader_bytes = sizeof(kfloat64) /* view_angle */ + sizeof(kint32) /* nDet */;
const int view_bytes = detheader_bytes + detval_bytes;
const off_t start_data = m_headerSize + (iview * view_bytes);
- const DetectorValue* const detval_ptr = darray.detValues();
+ const DetectorValue* const detval_ptr = darray.detValues();
kfloat64 view_angle = darray.viewAngle();
kuint32 nDet = darray.nDet();
-
+
fs.seekp (start_data);
if (! fs) {
sys_error (ERR_SEVERE, "Error seeking detectory array [detarrayWrite]");
return false;
}
-
+
fs.writeFloat64 (view_angle);
fs.writeInt32 (nDet);
-
+
for (unsigned int i = 0; i < nDet; i++) {
kfloat32 detval = detval_ptr[i];
fs.writeFloat32 (detval);
}
-
+
if (! fs)
return (false);
-
+
return true;
}
/* NAME
-* printProjectionData Print projections data
+* printProjectionData Print projections data
*
* SYNOPSIS
* printProjectionData ()
}
}
-void
+void
Projections::printScanInfo (std::ostringstream& os) const
{
os << "Number of detectors: " << m_nDet << "\n";
}
-bool
+bool
Projections::convertPolar (ImageFile& rIF, int iInterpolationID)
{
unsigned int nx = rIF.nx();
Projections* pProj = this;
if (m_geometry == Scanner::GEOMETRY_EQUIANGULAR || m_geometry == Scanner::GEOMETRY_EQUILINEAR)
pProj = interpolateToParallel();
-
+
Array2d<double> adView (nx, ny);
Array2d<double> adDet (nx, ny);
double** ppdView = adView.getArray();
pProj->calcArrayPolarCoordinates (nx, ny, ppdView, ppdDet, pProj->m_nDet, 1., pProj->m_detInc);
- pProj->interpolatePolar (v, vImag, nx, ny, ppcDetValue, ppdView, ppdDet, pProj->m_nView, pProj->m_nDet,
+ pProj->interpolatePolar (v, vImag, nx, ny, ppcDetValue, ppdView, ppdDet, pProj->m_nView, pProj->m_nDet,
pProj->m_nDet, iInterpolationID);
for (iView = 0; iView < pProj->m_nView; iView++)
}
-bool
+bool
Projections::convertFFTPolar (ImageFile& rIF, int iInterpolationID, int iZeropad)
{
#ifndef HAVE_FFTW
if (! v || nx == 0 || ny == 0)
return false;
-
+
Projections* pProj = this;
if (m_geometry == Scanner::GEOMETRY_EQUIANGULAR || m_geometry == Scanner::GEOMETRY_EQUILINEAR)
pProj = interpolateToParallel();
std::complex<double>** ppcDetValue = new std::complex<double>* [pProj->m_nView];
//double dInterpScale = (pProj->m_nDet-1) / static_cast<double>(iInterpDet-1);
double dInterpScale = pProj->m_nDet / static_cast<double>(iInterpDet);
-
+
double dFFTScale = 1. / static_cast<double>(iInterpDet * iInterpDet);
int iMidPoint = iInterpDet / 2;
double dMidPoint = static_cast<double>(iInterpDet) / 2.;
pcIn[iDet1+iZerosAdded][0] = pcIn[iDet1][0];
pcIn[iDet1+iZerosAdded][1] = pcIn[iDet1][1];
}
- for (int iDet2 = iMidPoint; iDet2 < iMidPoint + iZerosAdded; iDet2++)
+ for (int iDet2 = iMidPoint; iDet2 < iMidPoint + iZerosAdded; iDet2++)
pcIn[iDet2][0] = pcIn[iDet2][1] = 0;
}
ppcDetValue[iView] = new std::complex<double> [iNumInterpDetWithZeros];
for (int iD = 0; iD < iNumInterpDetWithZeros; iD++) {
- ppcDetValue[iView][iD] = std::complex<double> (pcIn[iD][0] * dFFTScale, pcIn[iD][1] * dFFTScale);
+ ppcDetValue[iView][iD] = std::complex<double> (pcIn[iD][0] * dFFTScale, pcIn[iD][1] * dFFTScale);
}
Fourier::shuffleFourierToNaturalOrder (ppcDetValue[iView], iNumInterpDetWithZeros);
}
fftw_free(pcIn) ;
- fftw_destroy_plan (plan);
-
+ fftw_destroy_plan (plan);
+
Array2d<double> adView (nx, ny);
Array2d<double> adDet (nx, ny);
double** ppdView = adView.getArray();
double** ppdDet = adDet.getArray();
- pProj->calcArrayPolarCoordinates (nx, ny, ppdView, ppdDet, iNumInterpDetWithZeros, dZeropadRatio,
+ pProj->calcArrayPolarCoordinates (nx, ny, ppdView, ppdDet, iNumInterpDetWithZeros, dZeropadRatio,
pProj->m_detInc * dInterpScale);
- pProj->interpolatePolar (v, vImag, nx, ny, ppcDetValue, ppdView, ppdDet, pProj->m_nView, pProj->m_nDet,
+ pProj->interpolatePolar (v, vImag, nx, ny, ppcDetValue, ppdView, ppdDet, pProj->m_nView, pProj->m_nDet,
iNumInterpDetWithZeros, iInterpolationID);
if (m_geometry == Scanner::GEOMETRY_EQUIANGULAR || m_geometry == Scanner::GEOMETRY_EQUILINEAR)
yMin = (yMin - yCent) * dZeropadRatio + yCent;
yMax = (yMax - yCent) * dZeropadRatio + yCent;
- double xInc = (xMax - xMin) / nx; // size of cells
+ double xInc = (xMax - xMin) / nx; // size of cells
double yInc = (yMax - yMin) / ny;
- double dDetCenter = (iNumDetWithZeros - 1) / 2.; // index refering to L=0 projection
+ double dDetCenter = (iNumDetWithZeros - 1) / 2.; // index refering to L=0 projection
// +1 is correct for frequency data, ndet-1 is correct for projections
// if (isEven (iNumDetWithZeros))
- // dDetCenter = (iNumDetWithZeros + 0) / 2;
+ // dDetCenter = (iNumDetWithZeros + 0) / 2;
// Calculates polar coordinates (view#, det#) for each point on phantom grid
- double x = xMin + xInc / 2; // Rectang coords of center of pixel
+ double x = xMin + xInc / 2; // Rectang coords of center of pixel
for (unsigned int ix = 0; ix < nx; x += xInc, ix++) {
double y = yMin + yInc / 2;
for (unsigned int iy = 0; iy < ny; y += yInc, iy++) {
phi -= PI;
r = -r;
}
-
+
ppdView[ix][iy] = (phi - m_rotStart) / m_rotInc;
ppdDet[ix][iy] = (r / dDetInc) + dDetCenter;
}
void
Projections::interpolatePolar (ImageFileArray& v, ImageFileArray& vImag,
- unsigned int nx, unsigned int ny, std::complex<double>** ppcDetValue, double** ppdView,
+ unsigned int nx, unsigned int ny, std::complex<double>** ppcDetValue, double** ppdView,
double** ppdDet, unsigned int nView, unsigned int nDet, unsigned int nDetWithZeros, int iInterpolationID)
{
typedef std::complex<double> complexValue;
- BilinearPolarInterpolator<complexValue>* pBilinear = NULL;
- BicubicPolyInterpolator<complexValue>* pBicubic = NULL;
+ BilinearPolarInterpolator<complexValue>* pBilinear = NULL;
+ BicubicPolyInterpolator<complexValue>* pBicubic = NULL;
if (iInterpolationID == POLAR_INTERP_BILINEAR)
pBilinear = new BilinearPolarInterpolator<complexValue> (ppcDetValue, nView, nDetWithZeros);
else if (iInterpolationID == POLAR_INTERP_BICUBIC)
pBicubic = new BicubicPolyInterpolator<complexValue> (ppcDetValue, nView, nDetWithZeros);
-
+
for (unsigned int ix = 0; ix < ny; ix++) {
for (unsigned int iy = 0; iy < ny; iy++) {
if (iInterpolationID == POLAR_INTERP_NEAREST) {
unsigned int iView = nearest<int> (ppdView[ix][iy]);
unsigned int iDet = nearest<int> (ppdDet[ix][iy]);
if (iView == nView)
- iView = 0;
+ iView = 0;
if (iDet >= 0 && iDet < nDetWithZeros && iView >= 0 && iView < nView) {
v[ix][iy] = ppcDetValue[iView][iDet].real();
if (vImag)
v[ix][iy] = 0;
if (vImag)
vImag[ix][iy] = 0;
- }
+ }
} else if (iInterpolationID == POLAR_INTERP_BILINEAR) {
std::complex<double> vInterp = pBilinear->interpolate (ppdView[ix][iy], ppdDet[ix][iy]);
m_rotStart = 0;
m_dViewDiameter = sin (m_dFanBeamAngle / 2) * m_dFocalLength * 2;
- if (! ((iNViews == 750 && lDataLength == 1560000L) || (iNViews == 950 && lDataLength == 1976000L)
+ if (! ((iNViews == 750 && lDataLength == 1560000L) || (iNViews == 950 && lDataLength == 1976000L)
|| (iNViews == 1500 && lDataLength == 3120000)))
return false;
} else if (iGeometry == Scanner::GEOMETRY_EQUILINEAR) {
double dFanAngle = atan (dDetPos / pProjections->sourceDetectorLength());
pC->m_dTheta = dViewAngle + dFanAngle;
- pC->m_dT = dFocalLength * sin(dFanAngle);
+ pC->m_dT = dFocalLength * sin(dFanAngle);
} else if (iGeometry == Scanner::GEOMETRY_EQUIANGULAR) {
// fan angle is same as dDetPos
pC->m_dTheta = dViewAngle + dDetPos;
- pC->m_dT = dFocalLength * sin (dDetPos);
+ pC->m_dT = dFocalLength * sin (dDetPos);
}
if (m_iThetaRange != THETA_RANGE_UNCONSTRAINED) {
pC->m_dTheta = normalizeAngle (pC->m_dTheta);
/*****************************************************************************
** FILE IDENTIFICATION
**
-** Name: reconstruct.cpp Reconstruction class
+** Name: reconstruct.cpp Reconstruction class
** Programmer: Kevin Rosenberg
** Date Started: Aug 84
**
*
* SYNOPSIS
* im = proj.reconstruct (im, filt_type, filt_param, interp_type)
- * IMAGE *im Output image
- * int filt_type Type of convolution filter to use
- * double filt_param Filter specific parameter
- * Currently, used only with Hamming filters
- * int interp_type Type of interpolation method to use
+ * IMAGE *im Output image
+ * int filt_type Type of convolution filter to use
+ * double filt_param Filter specific parameter
+ * Currently, used only with Hamming filters
+ * int interp_type Type of interpolation method to use
*
* ALGORITHM
*
- * Calculate one-dimensional filter in spatial domain
- * Allocate & clear (zero) the 2d output image array
+ * Calculate one-dimensional filter in spatial domain
+ * Allocate & clear (zero) the 2d output image array
* For each projection view
- * Convolve raysum array with filter
- * Backproject raysums and add (summate) to image array
+ * Convolve raysum array with filter
+ * Backproject raysums and add (summate) to image array
* end
*/
-Reconstructor::Reconstructor (const Projections& rProj, ImageFile& rIF, const char* const filterName,
- double filt_param, const char* const filterMethodName, const int zeropad,
- const char* filterGenerationName, const char* const interpName,
- int interpFactor, const char* const backprojectName, const int iTrace,
+Reconstructor::Reconstructor (const Projections& rProj, ImageFile& rIF, const char* const filterName,
+ double filt_param, const char* const filterMethodName, const int zeropad,
+ const char* filterGenerationName, const char* const interpName,
+ int interpFactor, const char* const backprojectName, const int iTrace,
ReconstructionROI* pROI, bool bRebinToParallel, SGP* pSGP)
- : m_rOriginalProj(rProj),
+ : m_rOriginalProj(rProj),
m_pProj(bRebinToParallel ? m_rOriginalProj.interpolateToParallel() : &m_rOriginalProj),
- m_rImagefile(rIF), m_pProcessSignal(0), m_pBackprojector(0),
+ m_rImagefile(rIF), m_pProcessSignal(0), m_pBackprojector(0),
m_iTrace(iTrace), m_bRebinToParallel(bRebinToParallel), m_bFail(false), m_adPlotXAxis(0)
{
m_nFilteredProjections = m_pProj->nDet() * interpFactor;
#endif
double filterBW = 1. / m_pProj->detInc();
- m_pProcessSignal = new ProcessSignal (filterName, filterMethodName, filterBW, m_pProj->detInc(),
- m_pProj->nDet(), filt_param, "spatial", filterGenerationName, zeropad, interpFactor, iTrace,
+ m_pProcessSignal = new ProcessSignal (filterName, filterMethodName, filterBW, m_pProj->detInc(),
+ m_pProj->nDet(), filt_param, "spatial", filterGenerationName, zeropad, interpFactor, iTrace,
m_pProj->geometry(), m_pProj->focalLength(), m_pProj->sourceDetectorLength(), pSGP);
if (m_pProcessSignal->fail()) {
if (iViewCount <= 0)
iViewCount = m_pProj->nView() - iStartView;
-
+
for (int iView = iStartView; iView < (iStartView + iViewCount); iView++) {
- if (m_iTrace == Trace::TRACE_CONSOLE)
- std::cout <<"Reconstructing view " << iView << " (last = " << m_pProj->nView() - 1 << ")\n";
-
+ if (m_iTrace == Trace::TRACE_CONSOLE)
+ std::cout <<"Reconstructing view " << iView << " (last = " << m_pProj->nView() - 1 << ")\n";
+
const DetectorArray& rDetArray = m_pProj->getDetectorArray (iView);
const DetectorValue* detval = rDetArray.detValues();
m_pProcessSignal->filterSignal (detval, adFilteredProj);
#ifdef HAVE_BSPLINE_INTERP
- if (interp_type == I_BSPLINE)
- bspline (m_pProj->nDet(), zoom_factor, spline_order, adFilteredProj, adFilteredProj);
-
+ if (interp_type == I_BSPLINE)
+ bspline (m_pProj->nDet(), zoom_factor, spline_order, adFilteredProj, adFilteredProj);
+
#ifdef HAVE_SGP
if (trace >= Trace::TRACE_PLOT && interp_type == I_BSPLINE && pSGP) {
- bspline (m_pProj->nDet(), zoom_factor, spline_order, adFilteredProj, adFilteredProj);
+ bspline (m_pProj->nDet(), zoom_factor, spline_order, adFilteredProj, adFilteredProj);
ezplot_1d (adFilteredProj, m_nFilteredProjections);
}
#endif
#endif
- if (bBackprojectView)
+ if (bBackprojectView)
m_pBackprojector->BackprojectView (adFilteredProj, rDetArray.viewAngle());
#ifdef HAVE_SGP
pSGP->setTextPointSize (12);
ezplotProj.plot (pSGP);
-}
+}
#endif //HAVE_SGP
}
/*****************************************************************************
** FILE IDENTIFICATION
**
-** Name: scanner.cpp
+** Name: scanner.cpp
** Purpose: Classes for CT scanner
** Programmer: Kevin Rosenberg
** Date Started: 1984
const int Scanner::GEOMETRY_EQUILINEAR = 2;
const int Scanner::GEOMETRY_LINOGRAM = 3;
-const char* const Scanner::s_aszGeometryName[] =
+const char* const Scanner::s_aszGeometryName[] =
{
"parallel",
"equiangular",
"linogram",
};
-const char* const Scanner::s_aszGeometryTitle[] =
+const char* const Scanner::s_aszGeometryTitle[] =
{
"Parallel",
"Equiangular",
// NAME
-// DetectorArray Construct a DetectorArray
+// DetectorArray Construct a DetectorArray
DetectorArray::DetectorArray (const int nDet)
{
// NAME
-// ~DetectorArray Free memory allocated to a detector array
+// ~DetectorArray Free memory allocated to a detector array
DetectorArray::~DetectorArray (void)
{
/* NAME
-* Scanner::Scanner Construct a user specified detector structure
+* Scanner::Scanner Construct a user specified detector structure
*
* SYNOPSIS
* Scanner (phm, nDet, nView, nSample)
-* Phantom& phm PHANTOM that we are making detector for
+* Phantom& phm PHANTOM that we are making detector for
* int geomety Geometry of detector
-* int nDet Number of detector along detector array
-* int nView Number of rotated views
-* int nSample Number of rays per detector
+* int nDet Number of detector along detector array
+* int nView Number of rotated views
+* int nSample Number of rays per detector
*/
-Scanner::Scanner (const Phantom& phm, const char* const geometryName,
- int nDet, int nView, int offsetView,
- int nSample, const double rot_anglen,
- const double dFocalLengthRatio,
- const double dCenterDetectorRatio,
+Scanner::Scanner (const Phantom& phm, const char* const geometryName,
+ int nDet, int nView, int offsetView,
+ int nSample, const double rot_anglen,
+ const double dFocalLengthRatio,
+ const double dCenterDetectorRatio,
const double dViewRatio, const double dScanRatio)
{
m_fail = false;
m_failMessage += geometryName;
return;
}
-
+
if (nView < 1 || nDet < 1) {
m_fail = true;
m_failMessage = "nView & nDet must be greater than 0";
}
if (nSample < 1)
m_nSample = 1;
-
+
m_nDet = nDet;
m_nView = nView;
m_iOffsetView = offsetView;
m_dCenterDetectorLength = (m_dViewDiameter / 2) * m_dCenterDetectorRatio;
m_dSourceDetectorLength = m_dFocalLength + m_dCenterDetectorLength;
m_dScanDiameter = m_dViewDiameter * m_dScanRatio;
-
+
m_dXCenter = phm.xmin() + (phm.xmax() - phm.xmin()) / 2;
m_dYCenter = phm.ymin() + (phm.ymax() - phm.ymin()) / 2;
m_rotLen = rot_anglen;
const double dAngle = asin ((m_dScanDiameter / 2) / m_dFocalLength);
const double dHalfDetLen = m_dSourceDetectorLength * tan (dAngle);
-
+
m_detLen = dHalfDetLen * 2;
m_detStart = -dHalfDetLen;
m_detInc = m_detLen / m_nDet;
dDetectorArrayEndOffset = m_detInc;
m_detLen += dDetectorArrayEndOffset;
}
-
+
m_dFanBeamAngle = dAngle * 2;
m_initPos.xs1 = m_dXCenter;
m_initPos.ys1 = m_dYCenter + m_dFocalLength;
m_dAngularDetLen = dAngularScale * (m_detLen + dDetectorArrayEndOffset);
m_dAngularDetIncrement = dAngularScale * m_detInc;
m_initPos.dAngularDet = -m_dAngularDetLen / 2;
-
+
m_dFanBeamAngle = dAngle * 2;
m_initPos.angle = m_iOffsetView * m_rotInc;
m_initPos.xs1 = m_dXCenter;
m_initPos.ys2 = m_dYCenter + m_dFocalLength;
m_detLen += dDetectorArrayEndOffset;
}
-
- // Calculate incrementatal rotation matrix
+
+ // Calculate incrementatal rotation matrix
GRFMTX_2D temp;
xlat_mtx2 (m_rotmtxIncrement, -m_dXCenter, -m_dYCenter);
rot_mtx2 (temp, m_rotInc);
mult_mtx2 (m_rotmtxIncrement, temp, m_rotmtxIncrement);
xlat_mtx2 (temp, m_dXCenter, m_dYCenter);
mult_mtx2 (m_rotmtxIncrement, temp, m_rotmtxIncrement);
-
+
}
Scanner::~Scanner (void)
Scanner::convertGeometryIDToName (const int geomID)
{
const char *name = "";
-
+
if (geomID >= 0 && geomID < s_iGeometryCount)
return (s_aszGeometryName[geomID]);
-
+
return (name);
}
Scanner::convertGeometryIDToTitle (const int geomID)
{
const char *title = "";
-
+
if (geomID >= 0 && geomID < s_iGeometryCount)
return (s_aszGeometryName[geomID]);
-
+
return (title);
}
int
-Scanner::convertGeometryNameToID (const char* const geomName)
+Scanner::convertGeometryNameToID (const char* const geomName)
{
int id = GEOMETRY_INVALID;
-
+
for (int i = 0; i < s_iGeometryCount; i++)
if (strcasecmp (geomName, s_aszGeometryName[i]) == 0) {
id = i;
break;
}
-
+
return (id);
}
/* NAME
-* collectProjections Calculate projections for a Phantom
+* collectProjections Calculate projections for a Phantom
*
* SYNOPSIS
* collectProjections (proj, phm, start_view, nView, bStoreViewPos, trace)
* Projectrions& proj Projection storage
-* Phantom& phm Phantom for which we collect projections
+* Phantom& phm Phantom for which we collect projections
* bool bStoreViewPos TRUE then storage proj at normal view position
-* int trace Trace level
+* int trace Trace level
*/
}
void
-Scanner::collectProjections (Projections& proj, const Phantom& phm, const int iStartView,
- const int iNumViews, const int iOffsetView, bool bStoreAtViewPosition,
+Scanner::collectProjections (Projections& proj, const Phantom& phm, const int iStartView,
+ const int iNumViews, const int iOffsetView, bool bStoreAtViewPosition,
const int trace, SGP* pSGP)
{
int iStorageOffset = (bStoreAtViewPosition ? iStartView : 0);
}
void
-Scanner::collectProjections (Projections& proj, const Phantom& phm, const int iStartView,
- const int iNumViews, const int iOffsetView, int iStorageOffset,
+Scanner::collectProjections (Projections& proj, const Phantom& phm, const int iStartView,
+ const int iNumViews, const int iOffsetView, int iStorageOffset,
const int trace, SGP* pSGP)
{
m_trace = trace;
double start_angle = (iStartView + iOffsetView) * proj.rotInc();
-
- // Calculate initial rotation matrix
+
+ // Calculate initial rotation matrix
GRFMTX_2D rotmtx_initial, temp;
xlat_mtx2 (rotmtx_initial, -m_dXCenter, -m_dYCenter);
rot_mtx2 (temp, start_angle);
mult_mtx2 (rotmtx_initial, temp, rotmtx_initial);
xlat_mtx2 (temp, m_dXCenter, m_dYCenter);
mult_mtx2 (rotmtx_initial, temp, rotmtx_initial);
-
+
double xd1=0, yd1=0, xd2=0, yd2=0;
if (m_idGeometry != GEOMETRY_EQUIANGULAR) {
xd1 = m_initPos.xd1;
yd1 = m_initPos.yd1;
xd2 = m_initPos.xd2;
yd2 = m_initPos.yd2;
- xform_mtx2 (rotmtx_initial, xd1, yd1); // rotate detector endpoints
- xform_mtx2 (rotmtx_initial, xd2, yd2); // to initial view_angle
+ xform_mtx2 (rotmtx_initial, xd1, yd1); // rotate detector endpoints
+ xform_mtx2 (rotmtx_initial, xd2, yd2); // to initial view_angle
}
-
+
double xs1 = m_initPos.xs1;
double ys1 = m_initPos.ys1;
double xs2 = m_initPos.xs2;
double ys2 = m_initPos.ys2;
xform_mtx2 (rotmtx_initial, xs1, ys1); // rotate source endpoints to
xform_mtx2 (rotmtx_initial, xs2, ys2); // initial view angle
-
+
int iView;
double viewAngle;
for (iView = 0, viewAngle = start_angle; iView < iNumViews; iView++, viewAngle += proj.rotInc()) {
int iStoragePosition = iView + iStorageOffset;
DetectorArray& detArray = proj.getDetectorArray( iStoragePosition );
-
-#ifdef HAVE_SGP
+
+#ifdef HAVE_SGP
if (pSGP && m_trace >= Trace::TRACE_PHANTOM) {
m_pSGP = pSGP;
double dWindowSize = dmax (m_detLen, m_dSourceDetectorLength) * 2;
m_dXMaxWin = m_dXCenter + dHalfWindowSize;
m_dYMinWin = m_dYCenter - dHalfWindowSize;
m_dYMaxWin = m_dYCenter + dHalfWindowSize;
-
+
m_pSGP->setWindow (m_dXMinWin, m_dYMinWin, m_dXMaxWin, m_dYMaxWin);
m_pSGP->setRasterOp (RO_COPY);
#endif
phm.draw (*m_pSGP);
m_dTextHeight = m_pSGP->getCharHeight ();
-
+
traceShowParam ("Phantom:", "%s", PROJECTION_TRACE_ROW_PHANT_ID, C_BLACK, phm.name().c_str());
traceShowParam ("Geometry:", "%s", PROJECTION_TRACE_ROW_GEOMETRY, C_BLUE, convertGeometryIDToName(m_idGeometry));
traceShowParam ("Focal Length Ratio:", "%.2f", PROJECTION_TRACE_ROW_FOCAL_LENGTH, C_BLUE, m_dFocalLengthRatio);
traceShowParam ("Num Detectors:", "%d", PROJECTION_TRACE_ROW_NDET, C_BLUE, proj.nDet());
traceShowParam ("Num Views:", "%d", PROJECTION_TRACE_ROW_NVIEW, C_BLUE, proj.nView());
traceShowParam ("Samples / Ray:", "%d", PROJECTION_TRACE_ROW_SAMPLES, C_BLUE, m_nSample);
-
+
m_pSGP->setMarker (SGP::MARKER_BDIAMOND);
}
#endif
-
+
#ifdef HAVE_SGP
if (m_pSGP && m_trace >= Trace::TRACE_PHANTOM) {
m_pSGP->setColor (C_BLACK);
m_pSGP->lineAbs (xs2, ys2);
m_pSGP->moveAbs (xd1, yd1);
m_pSGP->lineAbs (xd2, yd2);
- } else if (m_idGeometry == GEOMETRY_EQUILINEAR) {
+ } else if (m_idGeometry == GEOMETRY_EQUILINEAR) {
m_pSGP->setPenWidth (4);
m_pSGP->moveAbs (xs1, ys1);
m_pSGP->lineAbs (xs2, ys2);
#endif
if (m_trace == Trace::TRACE_CONSOLE)
std::cout << "Current View: " << iView+iStartView << std::endl;
-
+
projectSingleView (phm, detArray, xd1, yd1, xd2, yd2, xs1, ys1, xs2, ys2, viewAngle + 3 * HALFPI);
detArray.setViewAngle (viewAngle);
-
+
#ifdef HAVE_SGP
if (m_pSGP && m_trace >= Trace::TRACE_PHANTOM) {
- // rs_plot (detArray, xd1, yd1, dXCenter, dYCenter, theta);
+ // rs_plot (detArray, xd1, yd1, dXCenter, dYCenter, theta);
}
#endif
xform_mtx2 (m_rotmtxIncrement, xs1, ys1);
xform_mtx2 (m_rotmtxIncrement, xs2, ys2);
if (m_idGeometry != GEOMETRY_EQUIANGULAR) {
- xform_mtx2 (m_rotmtxIncrement, xd1, yd1); // rotate detector endpoints
+ xform_mtx2 (m_rotmtxIncrement, xd1, yd1); // rotate detector endpoints
xform_mtx2 (m_rotmtxIncrement, xd2, yd2);
}
} /* for each iView */
/* NAME
-* rayview Calculate raysums for a view at any angle
+* rayview Calculate raysums for a view at any angle
*
* SYNOPSIS
* rayview (phm, detArray, xd1, nSample, yd1, xd2, yd2, xs1, ys1, xs2, ys2)
-* Phantom& phm Phantom to scan
-* DETARRAY *detArray Storage of values for detector array
-* Scanner& det Scanner parameters
-* double xd1, yd1, xd2, yd2 Beginning & ending detector positions
-* double xs1, ys1, xs2, ys2 Beginning & ending source positions
+* Phantom& phm Phantom to scan
+* DETARRAY *detArray Storage of values for detector array
+* Scanner& det Scanner parameters
+* double xd1, yd1, xd2, yd2 Beginning & ending detector positions
+* double xs1, ys1, xs2, ys2 Beginning & ending source positions
*
* RAY POSITIONING
* For each detector, have there are a variable number of rays traced.
* In that case, the detector position is the center of the detector cell.
*/
-void
+void
Scanner::projectSingleView (const Phantom& phm, DetectorArray& detArray, const double xd1, const double yd1, const double xd2, const double yd2, const double xs1, const double ys1, const double xs2, const double ys2, const double dDetAngle)
{
-
- double sdx = (xs2 - xs1) / detArray.nDet(); // change in coords
+
+ double sdx = (xs2 - xs1) / detArray.nDet(); // change in coords
double sdy = (ys2 - ys1) / detArray.nDet(); // between source
- double xs_maj = xs1 + (sdx / 2); // put ray source in center of cell
+ double xs_maj = xs1 + (sdx / 2); // put ray source in center of cell
double ys_maj = ys1 + (sdy / 2);
-
+
double ddx=0, ddy=0, ddx2=0, ddy2=0, ddx2_ofs=0, ddy2_ofs=0, xd_maj=0, yd_maj=0;
double dAngleInc=0, dAngleSampleInc=0, dAngleSampleOffset=0, dAngleMajor=0;
if (m_idGeometry == GEOMETRY_EQUIANGULAR) {
dAngleSampleOffset = dAngleSampleInc / 2;
dAngleMajor = dDetAngle - (m_dAngularDetLen/2) + dAngleSampleOffset;
} else {
- ddx = (xd2 - xd1) / detArray.nDet(); // change in coords
+ ddx = (xd2 - xd1) / detArray.nDet(); // change in coords
ddy = (yd2 - yd1) / detArray.nDet(); // between detectors
- ddx2 = ddx / m_nSample; // Incr. between rays with detector cell
- ddy2 = ddy / m_nSample; // Doesn't include detector endpoints
+ ddx2 = ddx / m_nSample; // Incr. between rays with detector cell
+ ddy2 = ddy / m_nSample; // Doesn't include detector endpoints
ddx2_ofs = ddx2 / 2; // offset of 1st ray from start of detector cell
ddy2_ofs = ddy2 / 2;
-
+
xd_maj = xd1 + ddx2_ofs; // Incr. between detector cells
yd_maj = yd1 + ddy2_ofs;
}
-
+
DetectorValue* detval = detArray.detValues();
-
+
if (phm.getComposition() == P_UNIT_PULSE) { // put unit pulse in center of view
for (int d = 0; d < detArray.nDet(); d++)
detval[d] = 0;
xd = m_dCenterDetectorLength * cos (dAngle);
yd = m_dCenterDetectorLength * sin (dAngle);
}
-
+
#ifdef HAVE_SGP
if (m_pSGP && m_trace >= Trace::TRACE_PROJECTIONS) {
m_pSGP->setColor (C_YELLOW);
m_pSGP->lineAbs (xd, yd);
}
#endif
-
+
sum += projectSingleLine (phm, xd, yd, xs, ys);
-
+
#ifdef HAVE_SGP
- // if (m_trace >= Trace::TRACE_CLIPPING) {
- // traceShowParam ("Attenuation:", "%s", PROJECTION_TRACE_ROW_ATTEN, C_LTMAGENTA, " ");
- // traceShowParam ("Attenuation:", "%.3f", PROJECTION_TRACE_ROW_ATTEN, C_LTMAGENTA, sum);
- // }
+ // if (m_trace >= Trace::TRACE_CLIPPING) {
+ // traceShowParam ("Attenuation:", "%s", PROJECTION_TRACE_ROW_ATTEN, C_LTMAGENTA, " ");
+ // traceShowParam ("Attenuation:", "%.3f", PROJECTION_TRACE_ROW_ATTEN, C_LTMAGENTA, sum);
+ // }
#endif
if (m_idGeometry == GEOMETRY_EQUIANGULAR)
dAngle += dAngleSampleInc;
yd += ddy2;
}
} // for each sample in detector
-
+
detval[d] = sum / m_nSample;
xs_maj += sdx;
ys_maj += sdy;
}
-void
+void
Scanner::traceShowParam (const char *szLabel, const char *fmt, int row, int color, ...)
-{
+{
va_list arg;
va_start(arg, color);
#ifdef HAVE_SGP
traceShowParamRasterOp (RO_COPY, szLabel, fmt, row, color, arg);
#else
traceShowParamRasterOp (0, szLabel, fmt, row, color, arg);
-#endif
+#endif
va_end(arg);
}
-void
+void
Scanner::traceShowParamXOR (const char *szLabel, const char *fmt, int row, int color, ...)
-{
+{
va_list arg;
va_start(arg, color);
#ifdef HAVE_SGP
va_end(arg);
}
-void
+void
Scanner::traceShowParamRasterOp (int iRasterOp, const char *szLabel, const char *fmt, int row, int color, va_list args)
-{
+{
char szValue[256];
-
+
vsnprintf (szValue, sizeof(szValue), fmt, args);
-
+
#ifdef HAVE_SGP
if (m_pSGP) {
m_pSGP->setRasterOp (iRasterOp);
m_pSGP->moveAbs (dXPos + dValueOffset, dYPos);
m_pSGP->drawText (szValue);
}
- } else
+ } else
#endif
{
cio_put_str (szLabel);
/* NAME
-* projectSingleLine INTERNAL: Calculates raysum along a line for a Phantom
+* projectSingleLine INTERNAL: Calculates raysum along a line for a Phantom
*
* SYNOPSIS
* rsum = phm_ray_attenuation (phm, x1, y1, x2, y2)
-* double rsum Ray sum of Phantom along given line
-* Phantom& phm; Phantom from which to calculate raysum
-* double *x1, *y1, *x2, y2 Endpoints of ray path (in Phantom coords)
+* double rsum Ray sum of Phantom along given line
+* Phantom& phm; Phantom from which to calculate raysum
+* double *x1, *y1, *x2, y2 Endpoints of ray path (in Phantom coords)
*/
-double
+double
Scanner::projectSingleLine (const Phantom& phm, const double x1, const double y1, const double x2, const double y2)
{
- // check ray against each pelem in Phantom
+ // check ray against each pelem in Phantom
double rsum = 0.0;
for (PElemConstIterator i = phm.listPElem().begin(); i != phm.listPElem().end(); i++)
rsum += projectLineAgainstPElem (**i, x1, y1, x2, y2);
-
+
return (rsum);
}
/* NAME
-* pelem_ray_attenuation Calculate raysum of an pelem along one line
+* pelem_ray_attenuation Calculate raysum of an pelem along one line
*
* SYNOPSIS
* rsum = pelem_ray_attenuation (pelem, x1, y1, x2, y2)
-* double rsum Computed raysum
-* PhantomElement& pelem Pelem to scan
-* double x1, y1, x2, y2 Endpoints of raysum line
+* double rsum Computed raysum
+* PhantomElement& pelem Pelem to scan
+* double x1, y1, x2, y2 Endpoints of raysum line
*/
-double
+double
Scanner::projectLineAgainstPElem (const PhantomElement& pelem, double x1, double y1, double x2, double y2)
{
if (! pelem.clipLineWorldCoords (x1, y1, x2, y2)) {
cio_tone (1000., 0.05);
return (0.0);
}
-
+
#ifdef HAVE_SGP
if (m_pSGP && m_trace == Trace::TRACE_CLIPPING) {
m_pSGP->setRasterOp (RO_XOR);
m_pSGP->setRasterOp (RO_SET);
}
#endif
-
+
double len = lineLength (x1, y1, x2, y2);
return (len * pelem.atten());
}
/*****************************************************************************
** FILE IDENTIFICATION
**
-** Name: trace.cpp Class for trace
+** Name: trace.cpp Class for trace
** Programmer: Kevin Rosenberg
** Date Started: June 2000
**
const int Trace::BIT_PLOT = 0x0008;
const int Trace::BIT_CLIPPING = 0x0010;
-const char* Trace::s_aszTraceName[] =
+const char* Trace::s_aszTraceName[] =
{
"none",
"console",
"clipping",
};
-const char* Trace::s_aszTraceTitle[] =
+const char* Trace::s_aszTraceTitle[] =
{
"None",
"Console",
return (title);
}
-
+
int
-Trace::convertTraceNameToID (const char* const traceName)
+Trace::convertTraceNameToID (const char* const traceName)
{
int id = Trace::TRACE_INVALID;
for (int i = 0; i < s_iTraceCount; i++)
if (strcasecmp (traceName, s_aszTraceName[i]) == 0) {
- id = i;
- break;
+ id = i;
+ break;
}
return (id);
** Date Started: 1984
**
** OVERVIEW
-** Routines to clip lines against objects
-** All routines get the endpoints of the line, and
-** the SNARK size of the object (u,v)
+** Routines to clip lines against objects
+** All routines get the endpoints of the line, and
+** the SNARK size of the object (u,v)
**
** This is part of the CTSim program
** Copyright (c) 1983-2001 Kevin Rosenberg
/* NAME
- * clip_segment Clip against a segment of a circle
+ * clip_segment Clip against a segment of a circle
*
* SYNOPSIS
* clip_segment (x1, y1, x2, y2, u, v)
- * double& x1,*y1,*x2,*y2 Endpoints of line
- * double u,v Dimensions of segment
+ * double& x1,*y1,*x2,*y2 Endpoints of line
+ * double u,v Dimensions of segment
*/
bool
double xc2 = x2 * u;
double yc2 = y2 * v;
- if (yc1 > 0. && yc2 > 0.) // reject lines above y-axis
+ if (yc1 > 0. && yc2 > 0.) // reject lines above y-axis
return false;
double radius = sqrt (u * u + v * v);
if (clip_circle (xc1, yc1, xc2, yc2, 0.0, v, radius, 0.0, 0.0) == false)
return false;
- if (yc1 > 0. && yc2 > 0.) // trivial reject above y-axis
+ if (yc1 > 0. && yc2 > 0.) // trivial reject above y-axis
return false;
- // clip above x-axis
+ // clip above x-axis
if (yc1 > 0.) {
xc1 = xc1 + (xc2-xc1)*(0.0-yc1)/(yc2-yc1);
yc1 = 0.0;
/* NAME
- * clip_sector Clip a line against a sector of a circle
+ * clip_sector Clip a line against a sector of a circle
*
* SYNOPSIS
* clip_sector (x1, y1, x2, y2, u, v)
- * double& x1,*y1,*x2,*y2 Endpoints of line
- * double u,v Size of sector
+ * double& x1,*y1,*x2,*y2 Endpoints of line
+ * double u,v Size of sector
*/
-bool
+bool
clip_sector (double& x1, double& y1, double& x2, double& y2, const double u, const double v)
{
double xc1 = x1 * u;
double yc1 = y1 * v;
double xc2 = x2 * u;
double yc2 = y2 * v;
-
+
double radius = sqrt (u * u + v * v);
if (clip_circle (xc1, yc1, xc2, yc2, 0.0, v, radius, 0.0, 0.0) == false)
if (clip_triangle (xc1, yc1, xc2, yc2, u, v, false) == false)
return false;
-
+
x1 = xc1 / u;
y1 = yc1 / v;
x2 = xc2 / u;
y2 = yc2 / v;
-
+
return true;
}
/* NAME
- * clip_circle Clip a line against a circle
+ * clip_circle Clip a line against a circle
*
* SYNOPSIS
* clip_circle (x1,y1,x2,y2,cx,cy,radius,t1,t2)
- * double& x1,*y1,*x2,*y2 Endpoints of line to be clipped
- * double cx,cy Center of circle
- * double radius Radius of circle
- * double t1,t2 Starting & stopping angles of clipping
+ * double& x1,*y1,*x2,*y2 Endpoints of line to be clipped
+ * double cx,cy Center of circle
+ * double radius Radius of circle
+ * double t1,t2 Starting & stopping angles of clipping
*/
-bool
+bool
clip_circle (double& x1, double& y1, double& x2, double& y2, const double cx, const double cy, const double radius, double t1, double t2)
{
double xc1 = x1;
double ccx = cx;
double ccy = cy;
- double xtrans = -xc1; // move (x1,y1) to origin
+ double xtrans = -xc1; // move (x1,y1) to origin
double ytrans = -yc1;
xc1 += xtrans;
ccx += xtrans;
ccy += ytrans;
- double theta = -atan2 (yc2, xc2); // rotate line to lie on x-axis
+ double theta = -atan2 (yc2, xc2); // rotate line to lie on x-axis
GRFMTX_2D rotmtx;
- rot_mtx2 (rotmtx, theta); // xc1,yc1 is at origin, no need to rot
+ rot_mtx2 (rotmtx, theta); // xc1,yc1 is at origin, no need to rot
xform_mtx2 (rotmtx, xc2, yc2);
xform_mtx2 (rotmtx, ccx, ccy);
- t1 += theta; // rotate start and stop angles
+ t1 += theta; // rotate start and stop angles
t2 += theta;
t1 = normalizeAngle (t1);
t2 = normalizeAngle (t2);
return false;
}
- if (fabs(ccy) > radius) /* check if can reject */
+ if (fabs(ccy) > radius) /* check if can reject */
return false;
-
+
double temp = sqrt (radius * radius - ccy * ccy);
double xcmin = ccx - temp;
double xcmax = ccx + temp;
-
+
if (fabs(t2 - t1) < D_EPSILON) {
if (xc1 < xcmin)
xc1 = xcmin;
} else if (t1 < t2) {
if (t1 < PI && t2 > PI)
if (xc1 < xcmin)
- xc1 = xcmin;
+ xc1 = xcmin;
} else if (t1 > t2) {
if (t1 < PI)
if (xc1 < xcmin)
- xc1 = xcmin;
+ xc1 = xcmin;
if (xc2 > xcmax)
xc2 = xcmax;
}
/* NAME
- * clip_triangle Clip a line against a triangle
+ * clip_triangle Clip a line against a triangle
*
* SYNOPSIS
* clip_triangle (x1, y1, x2, y2, u, v, clip_xaxis)
- * double& x1, *y1, *x2, *y2 Endpoints of line
- * double u, v Size of 1/2 base len & height
- * int clip_xaxis Boolean flag whether to clip against x axis
- * (Use true for all triangles)
- * (false if used internally by sector clipping routine)
+ * double& x1, *y1, *x2, *y2 Endpoints of line
+ * double u, v Size of 1/2 base len & height
+ * int clip_xaxis Boolean flag whether to clip against x axis
+ * (Use true for all triangles)
+ * (false if used internally by sector clipping routine)
*
* DESCRIPTION
- * x
- * /|\ Note that vertices of triangle are
- * / | \ (-u, 0)
- * / | \ (u, 0)
- * / | \ (0, v)
+ * x
+ * /|\ Note that vertices of triangle are
+ * / | \ (-u, 0)
+ * / | \ (u, 0)
+ * / | \ (0, v)
* / | v \
* / | \
* +------+------+
* 1) Inside of this routine, values of (u,v) are assumed to be (1,1)
*
* 2) Derivation of clipping equations:
- * Using parametric equations for the line
- * xv = x1 + t * (x2 - x1)
+ * Using parametric equations for the line
+ * xv = x1 + t * (x2 - x1)
* yv = y1 + t * (y2 - y1)
- * so,
+ * so,
* t = (xv - x1) / (x2 - x1)
* yv = y1 + (xv - x1) * (y2 - y1) / (x2 - x1)
* yv = y1 + (xv - x1) * dy / dx
*
- * Now, find the intersections with the following clipping boundries:
- * yv = v - (v/u) * xv (yv = mx + b)
- * yv = v + (v/u) * xv (m = v/u, b = v);
+ * Now, find the intersections with the following clipping boundries:
+ * yv = v - (v/u) * xv (yv = mx + b)
+ * yv = v + (v/u) * xv (m = v/u, b = v);
*/
static int tcode (const double x, const double y, const double m, const double b, const int clip_xaxis);
-bool
+bool
clip_triangle (double& x1, double& y1, double& x2, double& y2, const double u, const double v, const int clip_xaxis)
{
- double m = v / u; // slope of triangle lines
- double b = v; // y-intercept of triangle lines
+ double m = v / u; // slope of triangle lines
+ double b = v; // y-intercept of triangle lines
int c1 = tcode (x1, y1, m, b, clip_xaxis);
int c2 = tcode (x2, y2, m, b, clip_xaxis);
#endif
while ( c1 || c2 ) {
if ( c1 & c2 ) {
- return false; // trivial reject
+ return false; // trivial reject
}
int c = c1;
if (c1 == 0)
c = c2;
double x = 0, y = 0;
- if (c & 1) { // below
+ if (c & 1) { // below
x = x1 + (x2-x1)*(0.0-y1)/(y2-y1);
y = 0.0;
- } else if (c & 2) { // right
+ } else if (c & 2) { // right
double dx, dy;
dx = x2 - x1;
dy = y2 - y1;
if (fabs(dx) > D_EPSILON)
- x = (-y1 + b + x1 * dy/dx) / (m + dy/dx);
+ x = (-y1 + b + x1 * dy/dx) / (m + dy/dx);
else
- x = x1;
+ x = x1;
y = -m * x + b;
- } else if (c & 4) { /* left */
+ } else if (c & 4) { /* left */
double dx, dy;
dx = x2 - x1;
dy = y2 - y1;
if (fabs(dx) > D_EPSILON) {
- x = (y1 - b - x1 * dy/dx);
- x /= (m - dy/dx);
+ x = (y1 - b - x1 * dy/dx);
+ x /= (m - dy/dx);
} else
- x = x1;
+ x = x1;
y = m * x + b;
}
-
+
if (c == c1) {
x1=x; y1=y; c1=tcode (x1,y1,m,b,clip_xaxis);
} else {
#endif
}
- return true; /* we have clipped the line, and it is good */
+ return true; /* we have clipped the line, and it is good */
}
/* compute region code */
-static int
+static int
tcode (const double x, const double y, const double m, const double b, const int clip_xaxis)
{
int c = 0;
- if (clip_xaxis && y < 0.) // below triange
+ if (clip_xaxis && y < 0.) // below triange
c = 1;
- if (y > -m * x + b + D_EPSILON) // right of triangle
+ if (y > -m * x + b + D_EPSILON) // right of triangle
c += 2;
- if (y > m * x + b + D_EPSILON) // left of triangle
+ if (y > m * x + b + D_EPSILON) // left of triangle
c += 4;
-
+
return (c);
-}
+}
/* NAME
- * clip_rect Clip a line against a rectangle
+ * clip_rect Clip a line against a rectangle
*
* SYNOPSIS
* clip_rect (x1, y1, x2, y2, rect)
- * double& x1, *y1, *x2, *y2 Endpoints of line
- * double rect[4] Rectangle to clip against
- * ordered xmin, ymin, xmax, ymax
+ * double& x1, *y1, *x2, *y2 Endpoints of line
+ * double rect[4] Rectangle to clip against
+ * ordered xmin, ymin, xmax, ymax
*/
static int rectcode (double x, double y, const double rect[4]);
while (c1 || c2) {
if (c1 & c2)
- return false; // trivial reject
+ return false; // trivial reject
int c = c1;
if (c1 == 0)
c = c2;
- if (c & 1) { // left
+ if (c & 1) { // left
y = y1 + (y2-y1)*(rect[0]-x1)/(x2-x1);
x = rect[0];
- } else if (c & 2) { // right
+ } else if (c & 2) { // right
y = y1 + (y2-y1)*(rect[2]-x1)/(x2-x1);
x = rect[2];
- } else if (c & 4) { // bottom
+ } else if (c & 4) { // bottom
x = x1 + (x2-x1)*(rect[1]-y1)/(y2-y1);
y = rect[1];
- } else if (c & 8) { // top
+ } else if (c & 8) { // top
x = x1 + (x2-x1)*(rect[3]-y1)/(y2-y1);
y = rect[3];
}
-
+
if (c == c1) {
x1=x; y1=y; c1=rectcode(x1,y1,rect);
} else {
x2=x; y2=y; c2=rectcode(x2,y2,rect);
}
}
- return true; // we have clipped the line, and it is good
+ return true; // we have clipped the line, and it is good
}
/* NAME
- * rectcode INTERNAL routine to return position of
- * point relative to a rectangle
+ * rectcode INTERNAL routine to return position of
+ * point relative to a rectangle
*
* SYNOPSIS
* c = rectcode (x, y, rect)
- * int c Position of point relative to the window
- * double x, y Point to test against window
- * double rect[4] Coordinates of rectangle extent
- * Ordered [xmin, ymin, xmax, ymax]
+ * int c Position of point relative to the window
+ * double x, y Point to test against window
+ * double rect[4] Coordinates of rectangle extent
+ * Ordered [xmin, ymin, xmax, ymax]
*/
-static int
-rectcode (double x, double y, const double rect[4])
+static int
+rectcode (double x, double y, const double rect[4])
{
int c = 0;
else if (y > rect[3])
c += 8;
return (c);
-}
+}
/* NAME
- * cio_put_c Put a character on screen
+ * cio_put_c Put a character on screen
*
* SYNOPSIS
* cio_put_c (c)
- * char c Character to write
+ * char c Character to write
*
* NOTES
* Color of character is determined by the global variable, crtv.text_attr.
* and maybe the screen will scroll
*/
-void
+void
cio_put_c (int c)
{
fputc(c, stdout);
/* NAME
- * cio_put_cc Put a char on screen count times
+ * cio_put_cc Put a char on screen count times
*
* SYNOPSIS
* cio_put_cc (c, count)
- * char c Character to write
- * int count Number of characters to write
+ * char c Character to write
+ * int count Number of characters to write
*/
-void
+void
cio_put_cc (int c, int count)
{
for (int i = 0; i < count; i++)
- cio_put_c (c);
+ cio_put_c (c);
}
-void
+void
cio_put_str (const char *str)
{
fputs (str, stdout);
/* NAME
- * kb_getc Get a character from the keyboard
+ * kb_getc Get a character from the keyboard
*
* SYNOPSIS
* key = kb_getc()
*
* DESCRIPTION
- * 1. This routine returns an EXTENTED ASCII code,
- * the extended codes have a low byte of 0 and a distinctive
- * high byte, such as 0x2D00 and 0x3200
- * 2. This routine waits until a key has been typed
- * 2. The keystroke will not be echoed.
+ * 1. This routine returns an EXTENTED ASCII code,
+ * the extended codes have a low byte of 0 and a distinctive
+ * high byte, such as 0x2D00 and 0x3200
+ * 2. This routine waits until a key has been typed
+ * 2. The keystroke will not be echoed.
*/
unsigned int cio_kb_getc(void)
return fgetc(stdin);
}
-void
+void
cio_kb_ungetc (unsigned int c)
{
ungetc(c, stdin);
}
/* NAME
- * kb_gets Get a string from the keyboard
+ * kb_gets Get a string from the keyboard
*
* SYNOPSIS
* str = kb_gets (str, maxlen)
- * char *str Space to store input string
- * int maxlen Maximum number of characters to read
- * (Not including EOS)
+ * char *str Space to store input string
+ * int maxlen Maximum number of characters to read
+ * (Not including EOS)
* NOTES
- * Backspace - erases character to the right
- * Escape - erases to beginning of line
- * Return - ends string (no not cause a linefeed)
+ * Backspace - erases character to the right
+ * Escape - erases to beginning of line
+ * Return - ends string (no not cause a linefeed)
*/
char *
}
/* NAME
- * kb_waitc Wait for a character from the keyboard
+ * kb_waitc Wait for a character from the keyboard
*
* SYNOPSIS
* key = kb_waitc (astr, estr, beep)
- * int key Keystroke entered
- * char *astr String of valid ascii characters
- * bool beep If TRUE, beep when user hits invalid key
+ * int key Keystroke entered
+ * char *astr String of valid ascii characters
+ * bool beep If TRUE, beep when user hits invalid key
*
*/
do {
c = cio_kb_getc ();
if (strchr (astr, c) != NULL)
- break;
+ break;
if (beep_on_error)
cio_beep();
} while (1);
-
+
return (c);
}
/* NAME
- * beep sound a beep to user
+ * beep sound a beep to user
*
* SYNOPSIS
* beep()
void cio_beep (void)
{
- cio_tone (2000.0, 0.3);
+ cio_tone (2000.0, 0.3);
}
/* NAME
- * tone play a frequency sound for some duration
+ * tone play a frequency sound for some duration
*
* SYNOPSIS
* tone (freq, length)
- * double freq frequency to play in Hertz
- * double length duration to play note in seconds
+ * double freq frequency to play in Hertz
+ * double length duration to play note in seconds
*/
-void
+void
cio_tone (double freq, double length)
{
#if 1
fprintf(stdout, "\007");
#else
- cio_spkr_freq (freq); /* Set frequency of tone */
- cio_spkr_on (); /* Turn on speaker */
- pause (length); /* Pause for length seconds */
- cio_spkr_off (); /* Turn off speaker */
+ cio_spkr_freq (freq); /* Set frequency of tone */
+ cio_spkr_on (); /* Turn on speaker */
+ pause (length); /* Pause for length seconds */
+ cio_spkr_off (); /* Turn off speaker */
#endif
}
#include "fnetorderstream.h"
-void
+void
ConvertNetworkOrder (void* buffer, size_t bytes)
{
#ifndef WORDS_BIGENDIAN
if (bytes < 2)
- return;
+ return;
char* start = static_cast<char*>(buffer);
char* end = start + bytes - 1; // last byte
size_t nSwap = bytes / 2;
-
+
while (nSwap-- > 0) {
- unsigned char c = *start;
- *start++ = *end;
- *end-- = c;
+ unsigned char c = *start;
+ *start++ = *end;
+ *end-- = c;
}
-#endif
+#endif
}
-void
+void
ConvertReverseNetworkOrder (void* buffer, size_t bytes)
{
#ifdef WORDS_BIGENDIAN
if (bytes < 2)
- return;
+ return;
char* start = static_cast<char*>(buffer);
- char* end = start + bytes - 1; // last byte
+ char* end = start + bytes - 1; // last byte
size_t nSwap = bytes / 2;
-
+
while (nSwap-- > 0) {
- unsigned char c = *start;
- *start++ = *end;
- *end-- = c;
+ unsigned char c = *start;
+ *start++ = *end;
+ *end-- = c;
}
-#endif
+#endif
}
void
write (reinterpret_cast<char*>(&n), 4);
}
-void
+void
frnetorderstream::writeFloat32 (kfloat32 n) {
#ifdef WORDS_BIGENDIAN
SwapBytes4 (&n);
write (reinterpret_cast<char*>(&n), 4);
}
-void
+void
frnetorderstream::writeFloat64 (kfloat64 n) {
#ifdef WORDS_BIGENDIAN
SwapBytes8 (&n);
write (reinterpret_cast<char*>(&n), 8);
}
-void
+void
frnetorderstream::readInt16 (kuint16& n) {
read (reinterpret_cast<char*>(&n), 2);
#ifdef WORDS_BIGENDIAN
#endif
}
-void
+void
frnetorderstream::readInt32 (kuint32& n) {
read (reinterpret_cast<char*>(&n), 4);
#ifdef WORDS_BIGENDIAN
/*****************************************************************************
** FILE IDENTIFICATION
**
-** Name: globalvars.cpp
+** Name: globalvars.cpp
** Purpose: Global variables
-** Programmer: Kevin Rosenberg
-** Date Started: Jan 2001
+** Programmer: Kevin Rosenberg
+** Date Started: Jan 2001
**
** This is part of the CTSim program
** Copyright (c) 1983-2001 Kevin Rosenberg
{
int nLength = strlen (pszKeyword);
char* pszCopy = new char [ nLength + 1];
- for (int i = 0; i < nLength; i++)
+ for (int i = 0; i < nLength; i++)
pszCopy[i] = tolower (pszKeyword[i]);
pszCopy[nLength] = 0;
{
int nLength = strlen (pszCompare);
char* pszCopy = new char [ nLength + 1];
- for (int i = 0; i < nLength; i++)
+ for (int i = 0; i < nLength; i++)
pszCopy[i] = tolower (pszCompare[i]);
pszCopy[nLength] = 0;
// inittable (table)
// clear symbol table
-void
+void
KeywordCodeHashTable::initTable ()
{
- int i;
+ int i;
- for (i = 0; i < HASHSIZE; i++)
- m_hashTable[i] = NULL;
+ for (i = 0; i < HASHSIZE; i++)
+ m_hashTable[i] = NULL;
}
// freetable (table)
-// free all memory allocated to table, then clear table
+// free all memory allocated to table, then clear table
-void
+void
KeywordCodeHashTable::freeTable ()
{
- int i;
- KeywordCodeEntry *p, *np;
-
- for (i = 0; i < HASHSIZE; i++) {
- np = m_hashTable [i];
- while (np != NULL) {
- p = np->getNext();
- delete np;
- np = p;
+ int i;
+ KeywordCodeEntry *p, *np;
+
+ for (i = 0; i < HASHSIZE; i++) {
+ np = m_hashTable [i];
+ while (np != NULL) {
+ p = np->getNext();
+ delete np;
+ np = p;
}
- }
- initTable ();
+ }
+ initTable ();
}
-// form hash value of string s
-int
+// form hash value of string s
+int
KeywordCodeHashTable::hash (const char* s)
{
- int hashval = 0;
+ int hashval = 0;
while (*s != EOS) {
- hashval += tolower(*s);
+ hashval += tolower(*s);
s++;
}
- return (hashval % HASHSIZE);
+ return (hashval % HASHSIZE);
}
{
KeywordCodeEntry *found = NULL;
for (KeywordCodeEntry* np = m_hashTable[ hash( pszLookup ) ]; np != NULL; np = np->getNext())
- if (np->matchesKeyword (pszLookup)) {
- found = np; // found it
- break;
- }
+ if (np->matchesKeyword (pszLookup)) {
+ found = np; // found it
+ break;
+ }
return (found);
}
{
KeywordCodeEntry *np = lookup (pszKeyword);
- if (np == NULL) { // not found
- np = new KeywordCodeEntry (pszKeyword, iCode);
- int hashval = hash (np->getKeyword());
- np->setNext (m_hashTable[ hashval ]);
- m_hashTable[hashval] = np;
- } else // already defined
- np->setCode (iCode);
+ if (np == NULL) { // not found
+ np = new KeywordCodeEntry (pszKeyword, iCode);
+ int hashval = hash (np->getKeyword());
+ np->setNext (m_hashTable[ hashval ]);
+ m_hashTable[hashval] = np;
+ } else // already defined
+ np->setCode (iCode);
}
}
// Lagrange formula for N=4 (cubic)
-
+
double xd_0 = x - lo;
double xd_1 = x - (lo + 1);
double xd_2 = x - (lo + 2);
// Precalculate 2nd derivative of y and put in m_pdY2
// Calculated by solving set of simultaneous CubicSpline spline equations
// Only n-2 CubicSpline spline equations, but able to make two more
- // equations by setting second derivative to 0 at ends
+ // equations by setting second derivative to 0 at ends
m_pdY2 = new double [n];
m_pdY2[0] = 0; // second deriviative = 0 at beginning and end
double* temp = new double [n - 1];
temp[0] = 0;
int i;
- for (i = 1; i < n - 1; i++) {
+ for (i = 1; i < n - 1; i++) {
double t = 2 + (0.5 * m_pdY2[i-1]);
temp[i] = y[i+1] + y[i-1] - y[i] - y[i];
temp[i] = (3 * temp[i] - 0.5 * temp[i-1]) / t;
m_pdY2[i] = -0.5 / t;
}
- for (i = n - 2; i >= 0; i--)
+ for (i = n - 2; i >= 0; i--)
m_pdY2[i] = temp[i] + m_pdY2[i] * m_pdY2[i + 1];
delete temp;
double hiFr = 1 - loFr;
double y = loFr * m_pdY[lo] + hiFr * m_pdY[hi];
y += oneSixth * ((loFr*loFr*loFr - loFr) * m_pdY2[lo] + (hiFr*hiFr*hiFr - hiFr) * m_pdY2[hi]);
-
+
return y;
}
-
+
*
* SYNOPSIS
* double integrateSimpson (xmin, xmax, y, np)
-* double xmin, xmax Extent of integration
-* double y[] Function values to be integrated
-* int np number of data points
-* (must be an odd number and at least 3)
+* double xmin, xmax Extent of integration
+* double y[] Function values to be integrated
+* int np number of data points
+* (must be an odd number and at least 3)
*
* RETURNS
* integrand of function
*/
-double
-integrateSimpson (const double xmin, const double xmax, const double *y, const int np)
+double
+integrateSimpson (const double xmin, const double xmax, const double *y, const int np)
{
if (np < 2)
return (0.);
else if (np == 2)
return ((xmax - xmin) * (y[0] + y[1]) / 2);
-
+
double area = 0;
int nDiv = (np - 1) / 2; // number of divisions
- double width = (xmax - xmin) / (double) (np - 1); // width of cells
-
+ double width = (xmax - xmin) / (double) (np - 1); // width of cells
+
for (int i = 1; i <= nDiv; i++) {
int xr = 2 * i;
int xl = xr - 2; // 2 * (i - 1) == 2 * i - 2 == xr - 2
int xm = xr - 1; // (xl+xr)/2 == (xr+xr-2)/2 == (2*xr-2)/2 = xr-1
-
+
area += (width / 3.0) * (y[xl] + 4.0 * y[xm] + y[xr]);
}
-
- if ((np & 1) == 0) /* do last trapazoid */
+
+ if ((np & 1) == 0) /* do last trapazoid */
area += width * (y[np-2] + y[np-1]) / 2;
-
+
return (area);
}
*
* SYNOPSIS
* t = normalizeAngle (theta)
-* double t Normalized angle
+* double t Normalized angle
* double theta Input angle
*/
-double
+double
normalizeAngle (double theta)
{
while (theta < 0.)
theta += TWOPI;
while (theta >= TWOPI)
theta -= TWOPI;
-
+
return (theta);
}
-void
+void
vectorNumericStatistics (std::vector<double> vec, const int nPoints, double& min, double& max, double& mean, double& mode, double& median, double& stddev)
{
if (nPoints <= 0)
return;
-
+
mean = 0;
min = vec[0];
max = vec[0];
mean += v;
}
mean /= nPoints;
-
+
static const int nbin = 1024;
int hist[ nbin ] = {0};
double spread = max - min;
stddev += diff * diff;
}
stddev = sqrt (stddev / nPoints);
-
+
int max_binindex = 0;
int max_bin = -1;
for (int ibin = 0; ibin < nbin; ibin++) {
max_binindex = ibin;
}
}
-
+
mode = (max_binindex * spread / (nbin - 1)) + min;
-
+
std::sort(vec.begin(), vec.end());
-
+
if (nPoints % 2) // Odd
median = vec[((nPoints - 1) / 2)];
else // Even
/*****************************************************************************
** FILE IDENTIFICATION
**
-** Name: plotfile.cpp
+** Name: plotfile.cpp
** Purpose: plotfile class
-** Programmer: Kevin Rosenberg
-** Date Started: Dec 2000
+** Programmer: Kevin Rosenberg
+** Date Started: Dec 2000
**
** This is part of the CTSim program
** Copyright (c) 1983-2001 Kevin Rosenberg
sys_error (ERR_SEVERE, "Illegal column number %d [PlotFile::addColumn]", iCol);
return (false);
}
-
+
for (int iRec = 0; iRec < m_iNumRecords; iRec++)
m_vecCurves[ iRec + (iCol * m_iNumRecords) ] = pdColData [iRec];
-
+
return true;
}
sys_error (ERR_SEVERE, "Illegal column number %d [PlotFile::addColumn]", iCol);
return (false);
}
-
+
for (int iRec = 0; iRec < m_iNumRecords; iRec++)
m_vecCurves[ iRec + (iCol * m_iNumRecords) ] = pdColData [iRec];
-
+
return true;
}
sys_error (ERR_SEVERE, "Illegal column number %d [PlotFile::addColumn]", iCol);
return;
}
-
+
for (int iRec = 0; iRec < m_iNumRecords; iRec++)
pdColData[iRec] = m_vecCurves[ iRec + (iCol * m_iNumRecords) ];
-
+
}
bool
sys_error (ERR_WARNING, "iStartingCol >= iNumColumns");
return false;
}
-
+
int iOffset = iStartingCol * m_iNumRecords;
dMin = m_vecCurves[ 0 + iOffset ];
dMax = dMin;
-
+
for (int iCol = iStartingCol; iCol < m_iNumColumns; iCol++) {
int iOffset = iCol * m_iNumRecords;
for (int iRec = 0; iRec < m_iNumRecords; iRec++) {
dMax = dVal;
}
}
-
+
return true;
}
-bool
+bool
PlotFile::statistics (int iStartingCol, double& min, double& max, double& mean, double& mode, double& median, double &stddev) const
{
if (iStartingCol >= m_iNumColumns) {
sys_error (ERR_WARNING, "iStartingCol >= iNumColumns");
return false;
}
-
+
int iNPoints = (m_iNumColumns - iStartingCol) * m_iNumRecords;
std::vector<double> vec;
vec.resize (iNPoints);
-
+
int iVec = 0;
for (int iCol = iStartingCol; iCol < m_iNumColumns; iCol++) {
int iOffset = iCol * m_iNumRecords;
for (int iRec = 0; iRec < m_iNumRecords; iRec++)
vec[iVec++] = m_vecCurves[ iRec + iOffset ];
}
-
+
vectorNumericStatistics (vec, iNPoints, min, max, mean, mode, median, stddev);
-
+
return true;
}
PlotFile::fileWrite (const char* const filename)
{
m_strFilename = filename;
-
+
fstream fs (m_strFilename.c_str(), std::ios::out | std::ios::trunc);
if (fs.fail()) {
sys_error (ERR_WARNING, "Error opening file %s for writing [fileCreate]", m_strFilename.c_str());
return false;
}
-
+
if (! headerWrite(fs) || ! columnsWrite (fs))
return false;
-
+
return true;
}
PlotFile::fileRead (const char* const filename)
{
m_strFilename = filename;
-
+
#ifdef MSVC
fstream fs (m_strFilename.c_str(), std::ios::in);
#else
fstream fs (m_strFilename.c_str(), std::ios::in); // | std::ios::nocreate);
#endif
-
+
if (fs.fail()) {
sys_error (ERR_WARNING, "Unable to open file %s [fileRead]", m_strFilename.c_str());
return false;
}
-
+
if (! headerRead(fs))
return false;
-
+
setCurveSize (m_iNumColumns, m_iNumRecords);
-
+
if (! columnsRead(fs))
return false;;
-
+
return true;
}
sys_error (ERR_WARNING, "Tried to read header with file closed [headerRead]");
return false;
}
-
+
initHeaders();
fs.seekg (0);
bool bFinishedHeaders = false;
sys_error (ERR_WARNING, "Tried to write header with ! fs");
return false;
}
-
+
fs.seekp (0);
fs << m_iNumColumns << " " << m_iNumRecords << "\n";
unsigned int i;
for (i = 0; i < m_vecStrEzsetCommands.size(); i++)
fs << m_vecStrEzsetCommands[i] << "\n";
-
+
for (i = 0; i < m_vecStrDescriptions.size(); i++)
fs << "# " << m_vecStrDescriptions[i] << "\n";
-
+
if (! m_strDate.empty())
fs << "# Date: " << m_strDate << "\n";
-
+
return ! fs.fail();
}
sys_error (ERR_WARNING, "Tried to columnWrite with !fs");
return false;
}
-
+
fs << "<datapoints>\n";
-
+
int iStride = m_iNumRecords;
for (int iRec = 0; iRec < m_iNumRecords; iRec++) {
for (int iCol = 0; iCol < m_iNumColumns; iCol++)
fs << m_vecCurves [iRec + (iCol * iStride)] << " ";
fs << "\n";
}
-
+
fs << "</datapoints>\n";
-
+
fs << "</plotfile>\n";
-
+
return ! fs.fail();
}
sys_error (ERR_WARNING, "Tried to arrayDataRead with ! fs");
return false;
}
-
+
if (m_iNumColumns == 0 || m_iNumRecords == 0) {
sys_error (ERR_WARNING, "Called PlotFile::columnsRead with 0 columns or records");
return false;
/* NAME
- * str_skip_head Skip leading characters of string
+ * str_skip_head Skip leading characters of string
*
* SYNOPSIS
- * shortened = str_skip_head (str, charlist)
- * OUT shortened Start of shortened string
- * IN char *str String to have beginning skipped
- * IN char *charlist List of characters to skip over
+ * shortened = str_skip_head (str, charlist)
+ * OUT shortened Start of shortened string
+ * IN char *str String to have beginning skipped
+ * IN char *charlist List of characters to skip over
*
* NOTES
- * This routine returns the position in a string (str) of the
- * first character that is not in an specified string of characters
- * (charlist).
+ * This routine returns the position in a string (str) of the
+ * first character that is not in an specified string of characters
+ * (charlist).
*/
char*
-str_skip_head (const char* str, const char* const charlist)
+str_skip_head (const char* str, const char* const charlist)
{
const char* p = str;
}
char*
-str_skip_head (const char* str, char* charlist)
+str_skip_head (const char* str, char* charlist)
{
const char* p = str;
/* NAME
- * str_lower Convert a string to lower case
+ * str_lower Convert a string to lower case
*
* SYNOPSIS
- * str = str_lower (str)
- * char *str String to be converted
+ * str = str_lower (str)
+ * char *str String to be converted
*/
char *
str_lower (char *s)
{
char *p = s;
-
- while (*p) { /* while (*p != EOS) */
- *p = tolower(*p);
- ++p;
+
+ while (*p) { /* while (*p != EOS) */
+ *p = tolower(*p);
+ ++p;
}
return (s);
}
/* NAME
- * str_rm_tail Remove characters from end of string
+ * str_rm_tail Remove characters from end of string
*
* SYNOPSIS
- * str = str_rm_tail (str, charlist)
- * char *str String to have end removed
-k * char *charlist List of characters to remove from string
+ * str = str_rm_tail (str, charlist)
+ * char *str String to have end removed
+k * char *charlist List of characters to remove from string
*
*/
str_rm_tail (char *str, const char* const charlist)
{
int i;
-
+
for (i = strlen(str) - 1; i >= 0; i--)
if (strchr (charlist, str[i]) != NULL)
str[i] = EOS;
else
- break; /* found non-specified char, all done */
+ break; /* found non-specified char, all done */
return (str);
}
/* NAME
- * str_wrm_tail Remove white space from end of string
+ * str_wrm_tail Remove white space from end of string
*
* SYNOPSIS
- * str = str_wrm_tail (str)
- * char *str String to have white space removed
+ * str = str_wrm_tail (str)
+ * char *str String to have white space removed
*
*/
}
/* NAME
- * str_upper Convert a string to upper case
+ * str_upper Convert a string to upper case
*
* SYNOPSIS
- * str = str_upper (str)
- * char *str String to be converted
+ * str = str_upper (str)
+ * char *str String to be converted
*/
char *
{
char *p = s;
- while (*p) { /* while (*s != EOS) */
+ while (*p) { /* while (*s != EOS) */
*p = toupper(*p);
p++;
}
#ifdef TEST
-int
+int
main (void)
{
string str, clist;
printf ("Enter list of characters to be skipped -- ");
gets (clist);
printf ("\n");
-
+
skip = str_skip_head (str, clist);
-
+
printf ("Shortened string = '%s'\n", skip);
}
#endif
#endif
/* NAME
-* sys_error System error handler
+* sys_error System error handler
*
* SYNOPSIS
* sys_error (severity, msg, args . . .)
-* int severity Severity of error
-* char *msg Error message
-* args Argument list, direct transfer to printf stack
+* int severity Severity of error
+* char *msg Error message
+* args Argument list, direct transfer to printf stack
*/
-static int s_reportErrorLevel = ERR_TRACE; // Set error reporting level
+static int s_reportErrorLevel = ERR_TRACE; // Set error reporting level
void sys_error (int severity, const char *msg, ...)
{
va_list arg;
-
+
va_start(arg, msg);
-
+
std::string strOutput;
sys_verror (strOutput, severity, msg, arg);
-
+
#ifdef HAVE_WXWINDOWS
if (g_bRunningWXWindows) {
if (theApp) {
wxCommandEvent eventLog (wxEVT_COMMAND_MENU_SELECTED, MAINMENU_LOG_EVENT );
wxString msg (strOutput.c_str());
if (msg.length() > 0) {
- msg += "\n";
- eventLog.SetString( msg );
- wxPostEvent( theApp->getMainFrame(), eventLog ); // send log event, thread safe
+ msg += "\n";
+ eventLog.SetString( msg );
+ wxPostEvent( theApp->getMainFrame(), eventLog ); // send log event, thread safe
}
} else {
wxMutexGuiEnter();
void sys_verror (std::string& strOutput, int severity, const char *msg, va_list arg)
{
if (severity < s_reportErrorLevel)
- return; // ignore error if less than reporting level
-
+ return; // ignore error if less than reporting level
+
std::ostringstream os;
if (severity > ERR_TRACE)
return;
}
}
-
+
switch (severity) {
case ERR_FATAL:
os << "FATAL ERROR: ";
default:
os << "Illegal error severity #" << severity << ": ";
}
-
+
char errStr[2000];
-
+
#if HAVE_VSNPRINTF
vsnprintf (errStr, sizeof(errStr), msg, arg);
#elif HAVE_VSPRINTF
#else
strncpy (errStr, sizeof(errStr), "Error message not available on this platform.");
#endif
-
+
os << errStr;
strOutput = os.str();
-
+
if (severity == ERR_FATAL) {
std::cerr << strOutput << "\n";
- throw std::runtime_error (strOutput);
+ throw std::runtime_error (strOutput);
}
-
+
#if INTERACTIVE_ERROR_DISPLAY
std::cout << "A - Abort C - Continue W - Turn off warnings? ";
// fflush(stderr);
- do
+ do
{
- int c = cio_kb_waitc("AaBbCcWw", TRUE); /* get code from keyboard */
+ int c = cio_kb_waitc("AaBbCcWw", TRUE); /* get code from keyboard */
c = tolower (c);
fputc (c, stderr);
fputc (NEWLINE, stderr);
-
+
if (c == 'a')
exit (1);
else if (c == 'c')
return;
- else if (c == 'w')
+ else if (c == 'w')
{
- sys_error_level (ERR_SEVERE); /* report severe & fatal errors */
+ sys_error_level (ERR_SEVERE); /* report severe & fatal errors */
break;
}
} while (TRUE);
/* NAME
-* sys_error_level Set error reporting level
+* sys_error_level Set error reporting level
*
* SYNOPSIS
* sys_error_level (severity)
-* int severity Report all error as serious as severity and beyond
+* int severity Report all error as serious as severity and beyond
*
* DESCRIPTION
* Causes the system to ignore all error below the level of severity
* error and ignore warnings
*/
-void
+void
sys_error_level (int severity)
{
if (severity == ERR_FATAL ||
/* NAME
- * rotate2d Rotates an array of 2 dimensional vectors
+ * rotate2d Rotates an array of 2 dimensional vectors
*
* SYNOPSIS
* rotate2d (x, y, n, angle)
- * double x[], y[] Array of points
- * int n Number of points in array
- * double angle Rotation angle (counter-clockwise)
+ * double x[], y[] Array of points
+ * int n Number of points in array
+ * double angle Rotation angle (counter-clockwise)
*/
-void
+void
rotate2d (double x[], double y[], int n, double angle)
{
double cos_theta = cos (angle);
/* NAME
- * xlat2d Translates an array of 2 dimensional vectors
+ * xlat2d Translates an array of 2 dimensional vectors
*
* SYNOPSIS
* xlat2d (x, y, n, xoffset, yoffset)
- * double x[], y[] Array of points
- * int n Number of points in array
- * double xoffset, yoffset Offset to translate points by
+ * double x[], y[] Array of points
+ * int n Number of points in array
+ * double xoffset, yoffset Offset to translate points by
*/
-void
+void
xlat2d (double x[], double y[], int n, double xoffset, double yoffset)
{
for (int i = 0; i < n; i++) {
/* NAME
- * scale2d Scale an array of 2 dimensional vectors
+ * scale2d Scale an array of 2 dimensional vectors
*
* SYNOPSIS
* scale2d (x, y, n, xoffset, yoffset)
- * double x[], y[] Array of points
- * int n Number of points in array
- * double xfact, yfact x & y scaling factors
+ * double x[], y[] Array of points
+ * int n Number of points in array
+ * double xfact, yfact x & y scaling factors
*/
-void
+void
scale2d (double x[], double y[], int n, double xfact, double yfact)
{
for (int i = 0; i < n; i++) {
}
-void
+void
indent_mtx2 (GRFMTX_2D m)
{
m[0][0] = 1.0; m[0][1] = 0.0; m[0][2] = 0.0;
m[2][0] = 0.0; m[2][1] = 0.0; m[2][2] = 1.0;
}
-void
+void
xlat_mtx2 (GRFMTX_2D m, const double x, const double y)
{
indent_mtx2 (m);
m[2][1] = y;
}
-void
+void
scale_mtx2 (GRFMTX_2D m, const double sx, const double sy)
{
indent_mtx2 (m);
m[1][1] = sy;
}
-void
+void
rot_mtx2 (GRFMTX_2D m, const double theta)
{
double c = cos(theta);
m[1][0] = -s; m[1][1] = c;
}
-void
+void
mult_mtx2 (const GRFMTX_2D m1, const GRFMTX_2D m2, GRFMTX_2D result)
{
GRFMTX_2D temp;
for (int col = 0; col < 3; col++) {
temp[row][col] = 0;
for (int calc = 0; calc < 3; calc++)
- temp[row][col] += m1[row][calc] * m2[calc][col];
+ temp[row][col] += m1[row][calc] * m2[calc][col];
}
}
result[r][col] = temp[r][col];
}
-void
+void
xform_mtx2 (const GRFMTX_2D m, double& x, double& y)
{
double xt = x * m[0][0] + y * m[1][0] + m[2][0];
BackgroundManager::OnUnitTick (wxCommandEvent& event)
{
int iUnits = event.GetInt();
-
+
BackgroundSupervisor* pSupervisor = reinterpret_cast<BackgroundSupervisor*>(event.GetClientData());
if (pSupervisor == NULL) {
sys_error (ERR_SEVERE, "Received NULL task [BackgroundManager::OnUnitTick]");
BackgroundManagerTask* pTask = lookupTask (pSupervisor);
if (pTask == NULL) {
- sys_error (ERR_SEVERE, "Error looking up task [BackgroundManager::OnUnitTick]");
- return;
+ sys_error (ERR_SEVERE, "Error looking up task [BackgroundManager::OnUnitTick]");
+ return;
}
pTask->gauge()->SetValue (iUnits);
}
wxCriticalSectionLocker locker (m_criticalSection);
int iNumTasks = m_vecpTasks.size();
- std::vector<bool> vecPositionUsed (iNumTasks); //vector of used table positions
+ std::vector<bool> vecPositionUsed (iNumTasks); //vector of used table positions
for (int iP = 0; iP < iNumTasks; iP++)
vecPositionUsed[iP] = false;
iFirstUnusedPos = i;
break;
}
-
+
wxPoint posGauge (m_sizeBorder.x, m_sizeBorder.y + iFirstUnusedPos * m_sizeCell.y);
wxPoint posLabel (m_sizeBorder.x + m_sizeGauge.x, m_sizeBorder.y + iFirstUnusedPos * m_sizeCell.y);
wxPoint posButton (m_sizeBorder.x + m_sizeGauge.x + m_sizeLabel.x, m_sizeBorder.y + iFirstUnusedPos * m_sizeCell.y);
wxStaticText* pLabel = new wxStaticText (m_pCanvas, -1, pszTaskName, posLabel, m_sizeLabel);
wxButton* pButton = new wxButton (m_pCanvas, s_iNextButtonID, _T("Cancel"), posButton, m_sizeButton, wxBU_LEFT);
- BackgroundManagerTask* pTask = new BackgroundManagerTask (pSupervisor, pszTaskName,
+ BackgroundManagerTask* pTask = new BackgroundManagerTask (pSupervisor, pszTaskName,
iFirstUnusedPos, pGauge, pLabel, pButton, s_iNextButtonID);
m_vecpTasks.push_back (pTask);
resizeWindow();
if (m_iNumTasks == 1) {
m_pCanvas->SetFocus();
- Show(true);
+ Show(true);
}
}
bool bFound = false;
for (TaskContainer::iterator iTask = m_vecpTasks.begin(); iTask != m_vecpTasks.end(); iTask++) {
if ((*iTask)->supervisor() == pSupervisor) {
- delete (*iTask)->gauge();
- delete (*iTask)->label();
- delete (*iTask)->button();
+ delete (*iTask)->gauge();
+ delete (*iTask)->label();
+ delete (*iTask)->button();
delete *iTask;
m_vecpTasks.erase (iTask);
m_iNumTasks--;
- bFound = true;
+ bFound = true;
break;
}
}
if (! bFound) {
- sys_error (ERR_SEVERE, "Unable to find supervisor [BackgroundManager::OnRemoveTask]");
+ sys_error (ERR_SEVERE, "Unable to find supervisor [BackgroundManager::OnRemoveTask]");
return;
}
pSupervisor->ackRemoveBackgroundManager();
wxSize m_sizeBorder;
wxSize m_sizeCellSpacing;
wxSize m_sizeButton;
-
+
public:
BackgroundManager ();
~BackgroundManager();
public:
BackgroundManagerTask (BackgroundSupervisor* pSupervisor, const char* const pszName, int iPos,
- wxGauge* pGauge, wxStaticText* pLabel, wxButton* pButton, int iButtonID)
- : m_pSupervisor(pSupervisor), m_strName(pszName), m_iPosition(iPos), m_pGauge(pGauge),
+ wxGauge* pGauge, wxStaticText* pLabel, wxButton* pButton, int iButtonID)
+ : m_pSupervisor(pSupervisor), m_strName(pszName), m_iPosition(iPos), m_pGauge(pGauge),
m_pLabel(pLabel), m_pButton(pButton), m_iButtonID(iButtonID)
{}
#include "wx/wx.h"
#endif
-// pragma line required for Fedora 4 and wxWin 2.4.2
+// pragma line required for Fedora 4 and wxWin 2.4.2
#pragma implementation "timer.h"
#include "ct.h"
BackgroundSupervisor::BackgroundSupervisor (SupervisorThread* pMyThread, wxWindow* pParentFrame, BackgroundProcessingDocument* pDocument, const char* const pszProcessTitle, int iTotalUnits)
- : wxEvtHandler(), m_pMyThread(pMyThread), m_pParentFrame(pParentFrame), m_pDocument(pDocument), m_strProcessTitle(pszProcessTitle),
+ : wxEvtHandler(), m_pMyThread(pMyThread), m_pParentFrame(pParentFrame), m_pDocument(pDocument), m_strProcessTitle(pszProcessTitle),
m_iTotalUnits(iTotalUnits), m_iNumThreads(0), m_bDone(false), m_bFail(false), m_bCancelled(false), m_iRunning(0),
m_pTimer(NULL), m_bWorkersDeleted(false), m_bBackgroundManagerAdded(false)
{
if (m_bWorkersDeleted)
return;
- for (int i = 0; i < m_iNumThreads; i++)
- if (m_vecpThreads[i])
+ for (int i = 0; i < m_iNumThreads; i++)
+ if (m_vecpThreads[i])
m_vecpThreads[i]->Delete(); // send Destroy message to workers
#ifdef USE_BKGMGR
wxPostEvent (theApp->getBackgroundManager(), doneEvent);
#endif
- while (m_iRunning > 0 || m_bBackgroundManagerAdded)
+ while (m_iRunning > 0 || m_bBackgroundManagerAdded)
m_pMyThread->Sleep(50);
-
+
m_bWorkersDeleted = true;
}
return false;
m_pTimer = new Timer;
-
+
std::string strLabel (m_strProcessTitle);
strLabel += " ";
strLabel += m_pParentFrame->GetTitle();
for (int i = 0; i < m_iNumThreads; i++)
m_vecpThreads[i]->Run();
-
+
return true;
}
BackgroundSupervisor::onWorkerUnitTick ()
{
++m_iUnitsDone;
-
+
#ifdef USE_BKGMGR
wxCommandEvent addTaskEvent (wxEVT_COMMAND_MENU_SELECTED, MSG_BACKGROUND_SUPERVISOR_UNIT_TICK);
addTaskEvent.SetInt (m_iUnitsDone - 1);
void
BackgroundSupervisor::onWorkerDone (int iThread)
{
- wxCriticalSection critsectDone;
- critsectDone.Enter();
+ wxCriticalSection critsectDone;
+ critsectDone.Enter();
m_iRunning--;
#ifdef DEBUG
if (theApp->getVerboseLogging()) {
wxString msg;
- msg.Printf("Background Supervisor: Thread finished. Remaining threads: %d\n", m_iRunning);
+ msg.Printf("Background Supervisor: Thread finished. Remaining threads: %d\n", m_iRunning);
wxCommandEvent eventLog (wxEVT_COMMAND_MENU_SELECTED, MAINMENU_LOG_EVENT );
eventLog.SetString( msg );
wxPostEvent( theApp->getMainFrame(), eventLog ); // send log event
wxWindow* m_pParentFrame;
BackgroundProcessingDocument* m_pDocument;
const std::string m_strProcessTitle;
-
+
const unsigned int m_iTotalUnits;
int m_iNumThreads;
volatile bool m_bDone;
MSG_WORKER_THREAD_FAIL = 7507, // sent by workers when they fail
};
- BackgroundSupervisor (SupervisorThread* pMyThread, wxWindow* pParentFrame, BackgroundProcessingDocument* pDocument, const char* const pszProcessTitle,
+ BackgroundSupervisor (SupervisorThread* pMyThread, wxWindow* pParentFrame, BackgroundProcessingDocument* pDocument, const char* const pszProcessTitle,
int iTotalUnits);
BackgroundSupervisor ()
bool start();
virtual void onDone() {};
-
+
virtual void onCancel();
virtual void onWorkerFail(int iThread, std::string strFailMessage);
static const char* rcsindent = "$Id$";
-struct option CTSimApp::ctsimOptions[] =
+struct option CTSimApp::ctsimOptions[] =
{
{"help", 0, 0, O_HELP},
{"version", 0, 0, O_VERSION},
#ifdef HAVE_SETPRIORITY
setpriority (PRIO_PROCESS, 0, 15); // set to low scheduling priority
#endif
-
+
openConfig();
-
+
g_bRunningWXWindows = true;
bool bPrintFiles = false;
// process options
#endif
if (c == -1)
break;
-
+
switch (c) {
case O_VERSION:
std::cout << rcsindent << std::endl;
exit (1);
}
}
-
+
m_docManager = new wxDocManager (wxDEFAULT_DOCMAN_FLAGS, true);
-
+
m_pDocTemplImage = new wxDocTemplate (m_docManager, "ImageFile", "*.if", "", "if", "ImageFile", "ImageView", CLASSINFO(ImageFileDocument), CLASSINFO(ImageFileView));
m_pDocTemplProjection = new wxDocTemplate (m_docManager, "ProjectionFile", "*.pj", "", "pj", "ProjectionFile", "ProjectionView", CLASSINFO(ProjectionFileDocument), CLASSINFO(ProjectionFileView));
m_pDocTemplPhantom = new wxDocTemplate (m_docManager, "PhantomFile", "*.phm", "", "phm", "PhantomFile", "PhantomView", CLASSINFO(PhantomFileDocument), CLASSINFO(PhantomFileView));
#if wxUSE_GLCANVAS
m_pDocTemplGraph3d = new wxDocTemplate (m_docManager, "Graph3dFile", "*.g3d", "", "g3d", "Graph3dFile", "Graph3dView", CLASSINFO(Graph3dFileDocument), CLASSINFO(Graph3dFileView), wxTEMPLATE_INVISIBLE);
#endif
-
+
#if wxUSE_GIF
wxImage::AddHandler(new wxGIFHandler); // Required for images in the online documentation
#endif
-
+
#if wxUSE_STREAMS && wxUSE_ZIPSTREAM && wxUSE_ZLIB
wxFileSystem::AddHandler(new wxZipFSHandler); // Required for advanced HTML help
#endif
-
+
// Create the main frame window
int xDisplay, yDisplay;
::wxDisplaySize (&xDisplay, &yDisplay);
- m_pFrame = new MainFrame(m_docManager, (wxFrame *) NULL, -1, "CTSim", wxPoint(0, 0),
+ m_pFrame = new MainFrame(m_docManager, (wxFrame *) NULL, -1, "CTSim", wxPoint(0, 0),
#ifdef CTSIM_MDI
- wxSize(nearest<int>(xDisplay * .75), nearest<int>(yDisplay * .75)),
+ wxSize(nearest<int>(xDisplay * .75), nearest<int>(yDisplay * .75)),
#else
- wxSize(nearest<int>(xDisplay * .6), nearest<int>(yDisplay * .4)),
+ wxSize(nearest<int>(xDisplay * .6), nearest<int>(yDisplay * .4)),
#endif
wxDEFAULT_FRAME_STYLE);
-
+
setIconForFrame (m_pFrame);
m_pFrame->Centre(wxBOTH);
- m_pFrame->Show(true);
+ m_pFrame->Show(true);
SetTopWindow (m_pFrame);
-
+
if (m_pConfig)
m_docManager->FileHistoryLoad(*m_pConfig);
-
+
#ifdef CTSIM_MDI
m_pLogDoc = newTextDoc();
if (m_pLogDoc) {
m_pLog = new wxTextCtrl (m_pFrame, -1, "Log Window\n", wxPoint(0, 0), wxSize(0,0), wxTE_MULTILINE | wxTE_READONLY);
#endif
wxLog::SetActiveTarget (new wxLogTextCtrl(m_pLog));
-
+
wxString helpDir;
if (! m_pConfig->Read("HelpDir", &helpDir))
helpDir = ::wxGetCwd();
wxString docFile = docDir + "ctsim.htb";
if (! m_pFrame->getHtmlHelpController().AddBook(docFile) &&
! m_pFrame->getHtmlHelpController().AddBook("/usr/share/ctsim/ctsim.htb") &&
- ! m_pFrame->getHtmlHelpController().AddBook("/tmp/ctsim.htb"))
+ ! m_pFrame->getHtmlHelpController().AddBook("/tmp/ctsim.htb"))
*m_pLog << "Cannot initialize the HTML Help system" << "\n";
else {
if (::wxDirExists ("/tmp"))
m_pFrame->getHtmlHelpController().UseConfig (m_pConfig);
}
#endif
-
+
for (int i = optind + 1; i <= argc; i++) {
wxString filename = argv [i - 1];
wxDocument* pNewDoc = m_docManager->CreateDocument (filename, wxDOC_SILENT);
closeEvent.SetInt (MAINMENU_FILE_EXIT);
m_pFrame->AddPendingEvent(closeEvent);
}
-
+
if (getStartupTips())
ShowTips();
-
+
#ifdef HAVE_WXTHREADS
m_pBackgroundMgr = new BackgroundManager;
#endif
CTSimApp::setIconForFrame(wxFrame* pFrame)
{
wxIcon iconApp (ctsim16_xpm);
-
+
if (iconApp.Ok())
pFrame->SetIcon (iconApp);
}
CTSimApp::OnExit()
{
closeConfig();
-
+
#ifdef HAVE_DMALLOC
dmalloc_shutdown();
#endif
#else
m_pConfig = new wxConfig("ctsim", "Kevin Rosenberg", ".ctsim", "", wxCONFIG_USE_LOCAL_FILE);
#endif
-
+
wxConfigBase::Set(m_pConfig);
m_pConfig->Read ("AdvancedOptions", &m_bAdvancedOptions);
m_pConfig->Read ("SetModifyNewDocs", &m_bSetModifyNewDocs);
CTSimApp::getUntitledFilename()
{
static int untitledNumber = 1;
-
+
wxString filename ("Untitled");
filename << untitledNumber++;
-
+
return (filename);
}
#endif
{
m_bShuttingDown = false;
-
+
//// Make a menubar
wxMenu *file_menu = new wxMenu;
-
+
file_menu->Append(MAINMENU_FILE_CREATE_PHANTOM, "Cr&eate Phantom...\tCtrl-P");
file_menu->Append(MAINMENU_FILE_CREATE_FILTER, "Create &Filter...\tCtrl-F");
file_menu->Append(wxID_OPEN, "&Open...\tCtrl-O");
-
+
file_menu->AppendSeparator();
file_menu->Append (MAINMENU_IMPORT, "&Import...\tCtrl-M");
file_menu->Append (MAINMENU_FILE_PREFERENCES, "Prefere&nces...");
file_menu->Append(MAINMENU_FILE_EXIT, "E&xit");
-
+
// history of files visited
theApp->getDocManager()->FileHistoryAddFilesToMenu(file_menu);
theApp->getDocManager()->FileHistoryUseMenu(file_menu);
-
+
#ifndef CTSIM_MDI
m_pWindowMenu = new wxMenu;
m_pWindowMenu->UpdateUI (this);
#endif
-
+
wxMenu* help_menu = new wxMenu;
help_menu->Append (MAINMENU_HELP_CONTENTS, "&Contents\tF1");
help_menu->Append (MAINMENU_HELP_TIPS, "&Tips");
help_menu->Append (MAINMENU_HELP_SECONDARY, "&Secondary Help");
#endif
help_menu->Append (MAINMENU_HELP_ABOUT, "&About");
-
+
wxMenuBar* menu_bar = new wxMenuBar;
-
+
menu_bar->Append(file_menu, "&File");
#ifndef CTSIM_MDI
menu_bar->Append(m_pWindowMenu, "&Window");
#endif
menu_bar->Append(help_menu, "&Help");
-
+
SetMenuBar(menu_bar);
-
-
+
+
#ifndef CTSIM_MDI
int i;
for (i = 0; i < MAX_WINDOW_MENUITEMS; i++) {
m_pWindowMenu->Enable (MAINMENU_WINDOW_BASE+i, false);
}
#endif
-
+
m_iDefaultPhantomID = Phantom::PHM_HERMAN;
m_iDefaultFilterID = SignalFilter::FILTER_BANDLIMIT;
m_iDefaultFilterDomainID = SignalFilter::DOMAIN_FREQUENCY;
m_dDefaultFilterInputScale = 1.;
m_dDefaultFilterOutputScale = 1.;
m_iDefaultImportFormat = ImageFile::IMPORT_FORMAT_PNG;
-
+
wxAcceleratorEntry accelEntries[15];
accelEntries[0].Set (wxACCEL_CTRL, static_cast<int>('O'), wxID_OPEN);
accelEntries[1].Set (wxACCEL_CTRL, static_cast<int>('P'), MAINMENU_FILE_CREATE_PHANTOM);
#else
wxAcceleratorTable accelTable (5, accelEntries);
#endif
-
+
SetAcceleratorTable (accelTable);
}
if (theApp->getConfig())
theApp->getDocManager()->FileHistorySave (*theApp->getConfig());
::wxYield();
- delete theApp->getDocManager();
-
+ delete theApp->getDocManager();
+
}
void
{
#ifdef CTSIM_MDI
if (theApp->getLogDoc()) {
- int xSize, ySize;
+ int xSize, ySize;
GetClientSize(&xSize, &ySize);
int yLogSize = ySize / 4;
theApp->getLogDoc()->getView()->getFrame()->SetSize (0, ySize - yLogSize, xSize, yLogSize);
theApp->getLogDoc()->getView()->getFrame()->Show (true);
}
#endif
-
+
#if CTSIM_MDI
wxDocMDIParentFrame::OnSize (event);
#else
#endif
}
-void
+void
MainFrame::OnCreatePhantom(wxCommandEvent& event)
{
DialogGetPhantom dialogPhantom (this, m_iDefaultPhantomID);
m_iDefaultPhantomID = Phantom::convertNameToPhantomID (selection.c_str());
theApp->getDocManager()->CreateDocument (filename, wxDOC_SILENT);
}
-
+
}
-void
+void
MainFrame::OnCreateFilter (wxCommandEvent& WXUNUSED(event))
{
DialogGetFilterParameters dialogFilter (this, m_iDefaultFilterXSize, m_iDefaultFilterYSize, m_iDefaultFilterID, m_dDefaultFilterParam, m_dDefaultFilterBandwidth, m_iDefaultFilterDomainID, m_dDefaultFilterInputScale, m_dDefaultFilterOutputScale);
m_dDefaultFilterInputScale = dialogFilter.getInputScale();
m_dDefaultFilterOutputScale = dialogFilter.getOutputScale();
std::ostringstream os;
- os << "Generate Filter=" << strFilter.c_str()
- << ", size=(" << static_cast<int>(m_iDefaultFilterXSize) << "," << static_cast<int>(m_iDefaultFilterYSize)
- << "), domain=" << strDomain.c_str() << ", filterParam=" << m_dDefaultFilterParam << ", bandwidth=" << m_dDefaultFilterBandwidth
+ os << "Generate Filter=" << strFilter.c_str()
+ << ", size=(" << static_cast<int>(m_iDefaultFilterXSize) << "," << static_cast<int>(m_iDefaultFilterYSize)
+ << "), domain=" << strDomain.c_str() << ", filterParam=" << m_dDefaultFilterParam << ", bandwidth=" << m_dDefaultFilterBandwidth
<< ", inputScale=" << m_dDefaultFilterInputScale << ", outputScale=" << m_dDefaultFilterOutputScale;
*theApp->getLog() << os.str().c_str() << "\n";
wxString filename = "untitled.if";
if (! pImageDoc) {
sys_error (ERR_SEVERE, "Unable to create image file");
return;
- }
+ }
pImageDoc->setImageFile (pImageFile);
if (theApp->getAskDeleteNewDocs())
pImageDoc->Modify (true);
if (! pProjDoc) {
sys_error (ERR_SEVERE, "Unable to create projection file");
return;
- }
+ }
pProjDoc->setProjections (pProjections);
if (theApp->getAskDeleteNewDocs())
pProjDoc->Modify (true);
theApp->ShowTips();
}
-void
+void
MainFrame::OnHelpContents (wxCommandEvent& event)
{
showHelp (event.GetId());
}
-void
+void
MainFrame::OnHelpButton (wxCommandEvent& event)
{
showHelp (event.GetId());
MainFrame::showHelp (int commandID)
{
switch (commandID) {
-
+
case MAINMENU_HELP_CONTENTS:
#ifdef CTSIM_WINHELP
m_winHelp.DisplayContents ();
m_htmlHelp.Display ("Contents");
#endif
break;
-
+
default:
#ifdef CTSIM_WINHELP
m_winHelp.DisplaySection (commandID);
}
}
-void
+void
MainFrame::OnExit (wxCommandEvent& WXUNUSED(event) )
{
Close(true);
static_cast<wxMenuItemBase*>(m_apWindowMenuItems[i])->SetName (wxString("[EMPTY]"));
m_apWindowMenuData[i] = NULL;
}
-#endif
+#endif
}
-void
+void
MainFrame::DoWindowMenu (int iMenuPosition, wxCommandEvent& event)
{
if (wxDocument* pDoc = m_apWindowMenuData [iMenuPosition]) {
class BitmapControl : public wxPanel
{
-private:
+private:
DECLARE_DYNAMIC_CLASS (BitmapControl)
DECLARE_EVENT_TABLE ()
wxBitmap* m_pBitmap;
-
+
public:
BitmapControl (wxBitmap* pBitmap, wxWindow *parent, wxWindowID id = -1,
const wxPoint& pos = wxDefaultPosition,
long style = wxSTATIC_BORDER,
const wxValidator& validator = wxDefaultValidator,
const wxString& name = "BitmapCtrl");
-
-
+
+
virtual ~BitmapControl();
-
+
virtual wxSize GetBestSize() const;
-
- wxBitmap* getBitmap()
+
+ wxBitmap* getBitmap()
{ return m_pBitmap; }
-
+
void OnPaint(wxPaintEvent& event);
};
IMPLEMENT_CLASS(BitmapControl, wxPanel)
-BitmapControl::BitmapControl (wxBitmap* pBitmap, wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size,
+BitmapControl::BitmapControl (wxBitmap* pBitmap, wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size,
long style, const wxValidator& validator, const wxString& name)
: m_pBitmap(pBitmap)
{
Create(parent, id, pos, size, style, name);
-
+
SetSize (GetBestSize());
}
class BitmapDialog : public wxDialog {
private:
BitmapControl* m_pBitmapCtrl;
-
+
public:
BitmapDialog (wxBitmap* pBitmap, char const* pszTitle);
virtual ~BitmapDialog();
: wxDialog(theApp->getMainFrame(), -1, wxString(pszTitle), wxDefaultPosition, wxDefaultSize, wxDIALOG_MODAL | wxDEFAULT_DIALOG_STYLE)
{
wxBoxSizer* pTopSizer = new wxBoxSizer (wxVERTICAL);
-
+
pTopSizer->Add (new BitmapControl (pBitmap, this), 0, wxALIGN_CENTER | wxALL, 5);
-
+
wxBoxSizer* pButtonSizer = new wxBoxSizer (wxHORIZONTAL);
wxButton* pButtonOk = new wxButton (this, wxID_OK, "Ok");
pButtonSizer->Add (pButtonOk, 0, wxEXPAND | wxALL, 10);
-
+
pTopSizer->Add (pButtonSizer, 0, wxALIGN_CENTER);
-
+
SetAutoLayout (true);
SetSizer (pTopSizer);
pTopSizer->Fit (this);
{}
-void
+void
MainFrame::OnPreferences (wxCommandEvent& WXUNUSED(event) )
{
- DialogPreferences dlg (this, "CTSim Preferences", theApp->getAdvancedOptions(),
- theApp->getAskDeleteNewDocs(), theApp->getVerboseLogging(), theApp->getStartupTips(),
+ DialogPreferences dlg (this, "CTSim Preferences", theApp->getAdvancedOptions(),
+ theApp->getAskDeleteNewDocs(), theApp->getVerboseLogging(), theApp->getStartupTips(),
theApp->getUseBackgroundTasks());
if (dlg.ShowModal() == wxID_OK) {
theApp->setAdvancedOptions (dlg.getAdvancedOptions());
}
}
-void
+void
MainFrame::OnImport (wxCommandEvent& WXUNUSED(event) )
{
DialogImportParameters dialogImport (this, m_iDefaultImportFormat);
if (dialogImport.ShowModal() != wxID_OK)
return;
-
+
wxString strFormatName (dialogImport.getFormatName ());
m_iDefaultImportFormat = ImageFile::convertImportFormatNameToID (strFormatName.c_str());
-
+
wxString strExt;
wxString strWildcard;
if (m_iDefaultImportFormat == ImageFile::IMPORT_FORMAT_PPM) {
else {
return;
}
-
- wxString strFilename = wxFileSelector (wxString("Import Filename"), wxString(""),
+
+ wxString strFilename = wxFileSelector (wxString("Import Filename"), wxString(""),
wxString(""), strExt, strWildcard, wxHIDE_READONLY | wxOPEN);
if (! strFilename.IsEmpty()) {
if (m_iDefaultImportFormat == ImageFile::IMPORT_FORMAT_PPM || m_iDefaultImportFormat == ImageFile::IMPORT_FORMAT_PNG) {
pIFDoc->getView()->getFrame()->Show(true);
} else
delete pIF;
- }
+ }
#ifdef HAVE_CTN_DICOM
else if (m_iDefaultImportFormat == ImageFile::IMPORT_FORMAT_DICOM) {
DicomImporter dicomImport (strFilename.c_str());
pIFDoc->Modify (true);
pIFDoc->UpdateAllViews();
pIFDoc->getView()->setInitialClientSize();
- pIFDoc->Activate();
+ pIFDoc->Activate();
} else if (dicomImport.testProjections()) {
ProjectionFileDocument* pProjDoc = theApp->newProjectionDoc();
Projections* pProj = dicomImport.getProjections();
pProjDoc->Modify (true);
pProjDoc->UpdateAllViews();
pProjDoc->getView()->setInitialClientSize();
- pProjDoc->Activate();
+ pProjDoc->Activate();
} else
::wxMessageBox ("Unrecognized DICOM file contents", "Import Error");
- }
+ }
#endif
else
sys_error (ERR_WARNING, "Unknown import format type");
}
#include "./splash.xpm"
-void
+void
MainFrame::OnAbout(wxCommandEvent& WXUNUSED(event) )
{
wxString strOSDesc = ::wxGetOsDescription();
*theApp->getLog() << " " << CTSIMVERSION;
#endif
*theApp->getLog() << "\n";
-
+
wxBitmap bmp (splash);
if (bmp.Ok()) {
BitmapDialog dlg (&bmp, "About CTSim");
msg << "Version: " << CTSIMVERSION << "\n\n";
#endif
msg += "Author: Kevin Rosenberg <kevin@rosenberg.net>\nUsage: ctsim [files-to-open..] [--help]";
-
+
wxMessageBox(msg, "About CTSim", wxOK | wxICON_INFORMATION, this);
*theApp->getLog() << msg << "\n";
}
newDoc->SetDocumentTemplate (m_pDocTemplPlot);
newDoc->OnNewDocument();
}
-
+
return newDoc;
}
{
wxString strFilename (getUntitledFilename());
strFilename += ".txt";
-
+
TextFileDocument* newDoc = dynamic_cast<TextFileDocument*>(m_pDocTemplText->CreateDocument (""));
if (newDoc) {
newDoc->SetDocumentName (m_pDocTemplText->GetDocumentName());
newDoc->SetDocumentTemplate (m_pDocTemplText);
newDoc->OnNewDocument();
}
-
+
return newDoc;
}
newDoc->SetDocumentTemplate (m_pDocTemplPhantom);
newDoc->OnNewDocument();
}
-
+
return newDoc;
}
newDoc->SetDocumentTemplate (m_pDocTemplGraph3d);
newDoc->OnNewDocument();
}
-
+
return newDoc;
}
#endif
enum { MAX_WINDOW_MENUITEMS = 20 };
wxMenuItem* m_apWindowMenuItems[MAX_WINDOW_MENUITEMS];
wxDocument* m_apWindowMenuData[MAX_WINDOW_MENUITEMS];
-
+
int m_iDefaultImportFormat;
int m_iDefaultPhantomID;
int m_iDefaultFilterID;
int m_iDefaultFilterDomainID;
- unsigned int m_iDefaultFilterXSize;
+ unsigned int m_iDefaultFilterXSize;
unsigned int m_iDefaultFilterYSize;
double m_dDefaultFilterParam;
double m_dDefaultFilterBandwidth;
void OnCreateFilter (wxCommandEvent& event);
void OnExit (wxCommandEvent& event);
-
+
void OnUpdateUI (wxUpdateUIEvent& event);
-
+
void OnWindowMenu0 (wxCommandEvent& event);
void OnWindowMenu1 (wxCommandEvent& event);
void OnWindowMenu2 (wxCommandEvent& event);
void OnWindowMenu17 (wxCommandEvent& event);
void OnWindowMenu18 (wxCommandEvent& event);
void OnWindowMenu19 (wxCommandEvent& event);
-
+
void DoWindowMenu (int iMenuPosition, wxCommandEvent& event);
bool getShuttingDown() const { return m_bShuttingDown; }
wxTextCtrl* getLog()
{ return m_pLog; }
- wxDocManager* getDocManager()
+ wxDocManager* getDocManager()
{ return m_docManager; }
-
+
wxString getUntitledFilename();
int getNumberCPU() const { return wxThread::GetCPUCount(); }
EZPlotDialog* makeEZPlotDialog()
{ return new EZPlotDialog (m_pFrame); }
-
+
void getCompatibleImages (const ImageFileDocument* pIFDoc, std::vector<ImageFileDocument*>& vecIF);
bool getAdvancedOptions() const { return m_bAdvancedOptions; }
void setAdvancedOptions (bool bAdv) { m_bAdvancedOptions = bAdv; }
MAINMENU_FILE_PREFERENCES,
MAINMENU_LOG_EVENT,
MAINMENU_IMPORT,
-
+
PJMENU_FILE_PROPERTIES,
PJMENU_RECONSTRUCT_FBP,
PJMENU_RECONSTRUCT_FBP_REBIN,
PJMENU_PLOT_TTHETA_SAMPLING,
PJMENU_PLOT_HISTOGRAM,
PJMENU_ARTIFACT_REDUCTION,
-
+
IFMENU_FILE_EXPORT,
IFMENU_FILE_PROPERTIES,
IFMENU_PLOT_FFT_ROW,
IFMENU_PLOT_FFT_COL,
IFMENU_PLOT_HISTOGRAM,
-
+
IFMENU_VIEW_SCALE_AUTO,
IFMENU_VIEW_SCALE_MINMAX,
IFMENU_VIEW_SCALE_FULL,
-
+
IFMENU_COMPARE_IMAGES,
IFMENU_COMPARE_ROW,
IFMENU_COMPARE_COL,
IFMENU_FILTER_IMAGINARY,
IFMENU_FILTER_SHUFFLENATURALTOFOURIERORDER,
IFMENU_FILTER_SHUFFLEFOURIERTONATURALORDER,
-
+
PHMMENU_FILE_PROPERTIES,
PHMMENU_PROCESS_RASTERIZE,
PHMMENU_PROCESS_PROJECTIONS,
PLOTMENU_FILE_PROPERTIES,
PLOTMENU_VIEW_SCALE_MINMAX,
PLOTMENU_VIEW_SCALE_AUTO,
- PLOTMENU_VIEW_SCALE_FULL,
+ PLOTMENU_VIEW_SCALE_FULL,
GRAPH3D_VIEW_WIREFRAME,
GRAPH3D_VIEW_COLOR,
wxString* psTitle = new wxString [nChoices];
for (int i = 0; i < nChoices; i++)
psTitle[i] = aszTitle[i];
-
+
Create (pParent, -1, wxDefaultPosition, wxSize(-1,-1), nChoices, psTitle, wxLB_SINGLE | wxLB_NEEDED_SB);
-
+
m_ppszValues = aszValue;
delete [] psTitle;
};
wxString* psTitle = new wxString [nChoices];
for (int i = 0; i < nChoices; i++)
psTitle[i] = aszTitle[i];
-
+
Create (pParent, -1, strTitle, wxDefaultPosition, wxDefaultSize, nChoices, psTitle, 1, wxRA_SPECIFY_COLS);
-
+
m_ppszValues = aszValue;
delete [] psTitle;
};
: wxDialog (pParent, -1, _T("Select Phantom"), wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE | wxCAPTION)
{
wxBoxSizer* pTopSizer = new wxBoxSizer (wxVERTICAL);
-
+
pTopSizer->Add (new wxStaticText (this, -1, "Select Phantom"), 0, wxCENTER | wxALL, 5);
-
+
pTopSizer->Add (new wxStaticLine (this, -1, wxDefaultPosition, wxSize(3,3), wxHORIZONTAL), 0, wxEXPAND | wxALL, 5);
-
+
m_pRadioBoxPhantom = new StringValueAndTitleRadioBox (this, _T("Phantom"), Phantom::getPhantomCount(), Phantom::getPhantomTitleArray(), Phantom::getPhantomNameArray());
m_pRadioBoxPhantom->SetSelection (iDefaultPhantom);
pTopSizer->Add (m_pRadioBoxPhantom, 0, wxALL | wxALIGN_CENTER);
-
+
pTopSizer->Add (new wxStaticLine (this, -1, wxDefaultPosition, wxSize(3,3), wxHORIZONTAL), 0, wxEXPAND | wxALL, 5);
-
+
wxBoxSizer* pButtonSizer = new wxBoxSizer (wxHORIZONTAL);
wxButton* pButtonOk = new wxButton (this, wxID_OK, "Okay");
pButtonSizer->Add (pButtonOk, 0, wxEXPAND | wxALL, 10);
pTopSizer->Add (pButtonSizer, 0, wxALIGN_CENTER);
pButtonOk->SetDefault();
-
+
SetAutoLayout (true);
SetSizer (pTopSizer);
pTopSizer->Fit (this);
: wxDialog (pParent, -1, _T("Select Phantom"), wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE | wxCAPTION)
{
wxBoxSizer* pTopSizer = new wxBoxSizer (wxVERTICAL);
-
+
pTopSizer->Add (new wxStaticText (this, -1, "Select Theta Range"), 0, wxCENTER | wxALL, 5);
-
+
pTopSizer->Add (new wxStaticLine (this, -1, wxDefaultPosition, wxSize(3,3), wxHORIZONTAL), 0, wxEXPAND | wxALL, 5);
-
+
wxString asTitle[] = {"Unconstrained", "Normalized to 2pi", "Fold to pi"};
-
+
m_pRadioBoxThetaRange = new wxRadioBox (this, -1, _T("Theta Range"), wxDefaultPosition, wxDefaultSize, 3, asTitle, 1, wxRA_SPECIFY_COLS);
if (iDefaultThetaRange == ParallelRaysums::THETA_RANGE_UNCONSTRAINED)
m_pRadioBoxThetaRange->SetSelection (0);
m_pRadioBoxThetaRange->SetSelection (2);
pTopSizer->Add (m_pRadioBoxThetaRange, 0, wxALL | wxALIGN_CENTER);
-
+
pTopSizer->Add (new wxStaticLine (this, -1, wxDefaultPosition, wxSize(3,3), wxHORIZONTAL), 0, wxEXPAND | wxALL, 5);
-
+
wxBoxSizer* pButtonSizer = new wxBoxSizer (wxHORIZONTAL);
wxButton* pButtonOk = new wxButton (this, wxID_OK, "Okay");
pButtonSizer->Add (pButtonOk, 0, wxEXPAND | wxALL, 10);
pTopSizer->Add (pButtonSizer, 0, wxALIGN_CENTER);
pButtonOk->SetDefault();
-
+
SetAutoLayout (true);
SetSizer (pTopSizer);
pTopSizer->Fit (this);
: wxDialog (pParent, -1, pszTitle, wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE | wxCAPTION), m_rVecIF(rVecIF)
{
wxBoxSizer* pTopSizer = new wxBoxSizer (wxVERTICAL);
-
+
pTopSizer->Add (new wxStaticText (this, -1, pszTitle), 0, wxALIGN_CENTER | wxALL, 5);
-
+
pTopSizer->Add (new wxStaticLine (this, -1, wxDefaultPosition, wxSize(3,3), wxHORIZONTAL), 0, wxALL, 5);
-
+
int iNImages = m_rVecIF.size();
wxString* pstrImages = new wxString [iNImages];
for (int i = 0; i < iNImages; i++) {
m_pListBoxImageChoices->SetSelection (0);
pTopSizer->Add (m_pListBoxImageChoices, 0, wxALL | wxALIGN_CENTER | wxEXPAND);
-
+
if (bShowMakeDifference) {
m_pMakeDifferenceImage = new wxCheckBox (this, -1, "Make Difference Image");
m_pMakeDifferenceImage->SetValue (FALSE);
m_pMakeDifferenceImage = NULL;
pTopSizer->Add (new wxStaticLine (this, -1, wxDefaultPosition, wxSize(3,3), wxHORIZONTAL), 0, wxEXPAND | wxALL, 5);
-
+
wxBoxSizer* pButtonSizer = new wxBoxSizer (wxHORIZONTAL);
wxButton* pButtonOk = new wxButton (this, wxID_OK, "Okay");
pButtonSizer->Add (pButtonOk, 0, wxEXPAND | wxALL, 10);
pButtonSizer->Add (pButtonCancel, 0, wxEXPAND | wxALL, 10);
CTSimHelpButton* pButtonHelp = new CTSimHelpButton (this, IDH_DLG_COMPARISON);
pButtonSizer->Add (pButtonHelp, 0, wxEXPAND | wxALL, 10);
-
+
pTopSizer->Add (pButtonSizer, 0, wxALIGN_CENTER);
pButtonOk->SetDefault();
-
+
SetAutoLayout (true);
SetSizer (pTopSizer);
pTopSizer->Fit (this);
// CLASS DiaglogPreferences Implementation
/////////////////////////////////////////////////////////////////////
-DialogPreferences::DialogPreferences (wxWindow* pParent, const char* const pszTitle,
+DialogPreferences::DialogPreferences (wxWindow* pParent, const char* const pszTitle,
bool bAdvancedOptions, bool bAskDeleteNewDocs, bool bVerboseLogging, bool bStartupTips, bool bUseBackgroundTasks)
: wxDialog (pParent, -1, _T(pszTitle), wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE | wxCAPTION)
{
wxBoxSizer* pTopSizer = new wxBoxSizer (wxVERTICAL);
-
+
pTopSizer->Add (new wxStaticText (this, -1, pszTitle), 0, wxALIGN_CENTER | wxTOP | wxLEFT | wxRIGHT, 5);
-
+
pTopSizer->Add (new wxStaticLine (this, -1, wxDefaultPosition, wxSize(3,3), wxHORIZONTAL), 0, wxEXPAND | wxALL, 5);
m_pCBAdvancedOptions = new wxCheckBox (this, -1, "Advanced Options", wxDefaultPosition, wxSize(250, 25), 0);
#endif
pTopSizer->Add (new wxStaticLine (this, -1, wxDefaultPosition, wxSize(3,3), wxHORIZONTAL), 0, wxEXPAND | wxALL, 5);
-
+
wxBoxSizer* pButtonSizer = new wxBoxSizer (wxHORIZONTAL);
wxButton* pButtonOk = new wxButton (this, wxID_OK, "Okay");
pButtonSizer->Add (pButtonOk, 0, wxEXPAND | wxALL, 10);
pButtonSizer->Add (pButtonCancel, 0, wxEXPAND | wxALL, 10);
CTSimHelpButton* pButtonHelp = new CTSimHelpButton (this, IDH_DLG_PREFERENCES);
pButtonSizer->Add (pButtonHelp, 0, wxEXPAND | wxALL, 10);
-
+
pTopSizer->Add (pButtonSizer, 0, wxALIGN_CENTER);
pButtonOk->SetDefault();
-
+
SetAutoLayout (true);
SetSizer (pTopSizer);
pTopSizer->Fit (this);
: wxDialog (pParent, -1, _T(pszTitle), wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE | wxCAPTION)
{
wxBoxSizer* pTopSizer = new wxBoxSizer (wxVERTICAL);
-
+
pTopSizer->Add (new wxStaticText (this, -1, pszTitle), 0, wxALIGN_CENTER | wxTOP | wxLEFT | wxRIGHT, 5);
-
+
pTopSizer->Add (new wxStaticLine (this, -1, wxDefaultPosition, wxSize(3,3), wxHORIZONTAL), 0, wxEXPAND | wxALL, 5);
-
+
std::ostringstream os;
os << dDefaultMin;
m_pTextCtrlMin = new wxTextCtrl (this, -1, os.str().c_str(), wxDefaultPosition, wxSize(100, 25), 0);
std::ostringstream osMax;
osMax << dDefaultMax;
m_pTextCtrlMax = new wxTextCtrl (this, -1, osMax.str().c_str(), wxDefaultPosition, wxSize(100, 25), 0);
-
+
wxFlexGridSizer *pGridSizer = new wxFlexGridSizer (2);
pGridSizer->Add (new wxStaticText (this, -1, "Minimum"), 0, wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL);
pGridSizer->Add (m_pTextCtrlMin, 0, wxALIGN_CENTER_VERTICAL);
pGridSizer->Add (new wxStaticText (this, -1, "Maximum"), 0, wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL);
pGridSizer->Add (m_pTextCtrlMax, 0, wxALIGN_CENTER_VERTICAL);
pTopSizer->Add (pGridSizer, 1, wxALL, 10);
-
+
pTopSizer->Add (new wxStaticLine (this, -1, wxDefaultPosition, wxSize(3,3), wxHORIZONTAL), 0, wxEXPAND | wxALL, 5);
-
+
wxBoxSizer* pButtonSizer = new wxBoxSizer (wxHORIZONTAL);
wxButton* pButtonOk = new wxButton (this, wxID_OK, "Okay");
pButtonSizer->Add (pButtonOk, 0, wxEXPAND | wxALL, 10);
pButtonSizer->Add (pButtonCancel, 0, wxEXPAND | wxALL, 10);
CTSimHelpButton* pButtonHelp = new CTSimHelpButton (this, IDH_DLG_MINMAX);
pButtonSizer->Add (pButtonHelp, 0, wxEXPAND | wxALL, 10);
-
+
pTopSizer->Add (pButtonSizer, 0, wxALIGN_CENTER);
pButtonOk->SetDefault();
-
+
SetAutoLayout (true);
SetSizer (pTopSizer);
pTopSizer->Fit (this);
: wxDialog (pParent, -1, _T("Auto Scale Parameters"), wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE | wxCAPTION), m_dMean(mean), m_dMode(mode), m_dMedian(median), m_dStdDev(stddev)
{
wxBoxSizer* pTopSizer = new wxBoxSizer (wxVERTICAL);
-
+
pTopSizer->Add (new wxStaticText (this, -1, "Auto Scale Parameters"), 0, wxALIGN_CENTER | wxTOP | wxLEFT | wxRIGHT, 5);
-
+
pTopSizer->Add (new wxStaticLine (this, -1, wxDefaultPosition, wxSize(3,3), wxHORIZONTAL), 0, wxEXPAND | wxALL, 5);
-
+
wxString asTitle[] = {"Mode", "Median", "Mean"};
-
+
m_pRadioBoxCenter = new wxRadioBox (this, -1, _T("Center"), wxDefaultPosition, wxDefaultSize, 3, asTitle, 1, wxRA_SPECIFY_COLS);
m_pRadioBoxCenter->SetSelection (0);
pTopSizer->Add (m_pRadioBoxCenter, 0, wxALL | wxALIGN_CENTER);
-
+
wxGridSizer *pGridSizer = new wxGridSizer (2);
pGridSizer->Add (new wxStaticText (this, -1, "Standard Deviation Factor"), 0, wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL);
std::ostringstream osDefaultFactor;
m_pTextCtrlStdDevFactor = new wxTextCtrl (this, -1, osDefaultFactor.str().c_str(), wxDefaultPosition, wxSize(100, 25), 0);
pGridSizer->Add (m_pTextCtrlStdDevFactor, 0, wxALIGN_CENTER_VERTICAL);
pTopSizer->Add (pGridSizer, 1, wxALL, 10);
-
+
pTopSizer->Add (new wxStaticLine (this, -1, wxDefaultPosition, wxSize(3,3), wxHORIZONTAL), 0, wxEXPAND | wxALL, 5);
-
+
wxBoxSizer* pButtonSizer = new wxBoxSizer (wxHORIZONTAL);
wxButton* pButtonOk = new wxButton (this, wxID_OK, "Okay");
pButtonSizer->Add (pButtonOk, 0, wxEXPAND | wxALL, 10);
pButtonSizer->Add (pButtonCancel, 0, wxEXPAND | wxALL, 10);
CTSimHelpButton* pButtonHelp = new CTSimHelpButton (this, IDH_DLG_AUTOSCALE);
pButtonSizer->Add (pButtonHelp, 0, wxEXPAND | wxALL, 10);
-
+
pTopSizer->Add (pButtonSizer, 0, wxALIGN_CENTER);
pButtonOk->SetDefault();
-
+
SetAutoLayout (true);
SetSizer (pTopSizer);
pTopSizer->Fit (this);
dCenter = m_dMedian;
else if (iCenter == 2)
dCenter = m_dMean;
-
+
wxString sStddevFactor = m_pTextCtrlStdDevFactor->GetValue();
double dValue;
if (! sStddevFactor.ToDouble (&dValue)) {
*pMin = dCenter - dHalfWidth;
*pMax = dCenter + dHalfWidth;
*theApp->getLog() << "Setting minimum to " << *pMin << " and maximum to " << *pMax << "\n";
-
+
return true;
}
if (! sStddevFactor.ToDouble (&dValue)) {
*theApp->getLog() << "Error: Non-numeric Standard Deviation Factor of " << sStddevFactor << "\n";
}
-
+
return dValue;
}
// DialogGetRasterParameters
/////////////////////////////////////////////////////////////////////
-DialogGetRasterParameters::DialogGetRasterParameters
+DialogGetRasterParameters::DialogGetRasterParameters
(wxWindow* pParent, int iDefaultXSize, int iDefaultYSize, int iDefaultNSamples, double dDefaultViewRatio)
: wxDialog (pParent, -1, _T("Rasterization Parameters"), wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE | wxCAPTION)
{
wxBoxSizer* pTopSizer = new wxBoxSizer (wxVERTICAL);
-
+
pTopSizer->Add (new wxStaticText (this, -1, "Rasterization Parameters"), 0, wxALIGN_CENTER | wxTOP | wxLEFT | wxRIGHT, 5);
-
+
pTopSizer->Add (new wxStaticLine (this, -1, wxDefaultPosition, wxSize(3,3), wxHORIZONTAL), 0, wxEXPAND | wxALL, 5);
-
+
wxFlexGridSizer *pGridSizer = new wxFlexGridSizer (2);
std::ostringstream os;
os << iDefaultXSize;
pGridSizer->Add (m_pTextCtrlNSamples, 0, wxALIGN_CENTER_VERTICAL);
pTopSizer->Add (pGridSizer, 1, wxALL, 10);
-
+
pTopSizer->Add (new wxStaticLine (this, -1, wxDefaultPosition, wxSize(3,3), wxHORIZONTAL), 0, wxEXPAND | wxALL, 5);
-
+
wxBoxSizer* pButtonSizer = new wxBoxSizer (wxHORIZONTAL);
wxButton* pButtonOk = new wxButton (this, wxID_OK, "Okay");
pButtonSizer->Add (pButtonOk, 0, wxEXPAND | wxALL, 10);
pTopSizer->Add (pButtonSizer, 0, wxALIGN_CENTER);
pButtonOk->SetDefault();
-
+
SetAutoLayout (true);
SetSizer (pTopSizer);
pTopSizer->Fit (this);
/////////////////////////////////////////////////////////////////////
-DialogGetProjectionParameters::DialogGetProjectionParameters
- (wxWindow* pParent, int iDefaultNDet, int iDefaultNView, int iDefaultOffsetView, int iDefaultNSamples,
+DialogGetProjectionParameters::DialogGetProjectionParameters
+ (wxWindow* pParent, int iDefaultNDet, int iDefaultNView, int iDefaultOffsetView, int iDefaultNSamples,
double dDefaultRotAngle, double dDefaultFocalLength, double dDefaultCenterDetectorLength,
double dDefaultViewRatio, double dDefaultScanRatio, int iDefaultGeometry, int iDefaultTrace)
: wxDialog (pParent, -1, _T("Projection Parameters"), wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE | wxCAPTION)
{
wxBoxSizer* pTopSizer = new wxBoxSizer (wxVERTICAL);
-
+
m_dDefaultRotAngle = dDefaultRotAngle;
m_dDefaultFocalLength = dDefaultFocalLength;
m_dDefaultCenterDetectorLength = dDefaultCenterDetectorLength;
m_iDefaultNDet = iDefaultNDet;
m_iDefaultTrace = iDefaultTrace;
m_iDefaultGeometry = iDefaultGeometry;
-
+
pTopSizer->Add (new wxStaticText (this, -1, "Projection Parameters"), 0, wxALIGN_CENTER | wxTOP | wxLEFT | wxRIGHT, 5);
-
+
pTopSizer->Add (new wxStaticLine (this, -1, wxDefaultPosition, wxSize(3,3), wxHORIZONTAL), 0, wxEXPAND | wxALL, 5);
-
+
wxFlexGridSizer* pGridSizer = new wxFlexGridSizer (2);
m_pRadioBoxGeometry = new StringValueAndTitleRadioBox (this, _T("Geometry"), Scanner::getGeometryCount(), Scanner::getGeometryTitleArray(), Scanner::getGeometryNameArray());
m_pRadioBoxGeometry->SetSelection (iDefaultGeometry);
-
+
pGridSizer->Add (m_pRadioBoxGeometry, 0, wxALL | wxALIGN_CENTER | wxEXPAND);
-
+
m_pRadioBoxTrace = new StringValueAndTitleRadioBox (this, _T("Trace Level"), Trace::getTraceCount(), Trace::getTraceTitleArray(), Trace::getTraceNameArray());
m_pRadioBoxTrace->SetSelection (iDefaultTrace);
pGridSizer->Add (m_pRadioBoxTrace, 0, wxALL | wxALIGN_CENTER | wxEXPAND);
- wxFlexGridSizer* pText1Sizer = new wxFlexGridSizer(2);
+ wxFlexGridSizer* pText1Sizer = new wxFlexGridSizer(2);
std::ostringstream os;
os << iDefaultNDet;
m_pTextCtrlNDet = new wxTextCtrl (this, -1, os.str().c_str(), wxDefaultPosition, wxSize(100, 25), 0);
m_pTextCtrlRotAngle = new wxTextCtrl (this, -1, osRotAngle.str().c_str(), wxDefaultPosition, wxSize(100, 25), 0);
pText2Sizer->Add (new wxStaticText (this, -1, "Rotation Angle (Fraction of circle)"), 0, wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL);
pText2Sizer->Add (m_pTextCtrlRotAngle, 0, wxALIGN_CENTER_VERTICAL);
-
+
std::ostringstream osOffsetView;
osOffsetView << iDefaultOffsetView;
m_pTextCtrlOffsetView = new wxTextCtrl (this, -1, osOffsetView.str().c_str(), wxDefaultPosition, wxSize(100, 25), 0);
pGridSizer->Add (pText2Sizer);
pTopSizer->Add (pGridSizer, 1, wxALL, 10);
-
+
pTopSizer->Add (new wxStaticLine (this, -1, wxDefaultPosition, wxSize(3,3), wxHORIZONTAL), 0, wxEXPAND | wxALL, 5);
-
+
wxBoxSizer* pButtonSizer = new wxBoxSizer (wxHORIZONTAL);
wxButton* pButtonOk = new wxButton (this, wxID_OK, "Okay");
pButtonSizer->Add (pButtonOk, 0, wxEXPAND | wxALL, 10);
pButtonSizer->Add (pButtonCancel, 0, wxEXPAND | wxALL, 10);
CTSimHelpButton* pButtonHelp = new CTSimHelpButton (this, IDH_DLG_PROJECTIONS);
pButtonSizer->Add (pButtonHelp, 0, wxEXPAND | wxALL, 10);
-
+
pTopSizer->Add (pButtonSizer, 0, wxALIGN_CENTER);
pButtonOk->SetDefault();
-
+
SetAutoLayout (true);
SetSizer (pTopSizer);
pTopSizer->Fit (this);
DialogGetProjectionParameters::getOffsetView ()
{
if (theApp->getAdvancedOptions()) {
- wxString strCtrl = m_pTextCtrlOffsetView->GetValue();
- unsigned long lValue;
- if (strCtrl.ToULong (&lValue))
- return lValue;
- else
- return (m_iDefaultOffsetView);
+ wxString strCtrl = m_pTextCtrlOffsetView->GetValue();
+ unsigned long lValue;
+ if (strCtrl.ToULong (&lValue))
+ return lValue;
+ else
+ return (m_iDefaultOffsetView);
}
else
return 0;
else
return (m_dDefaultRotAngle);
} else {
- if (Scanner::convertGeometryNameToID (m_pRadioBoxGeometry->getSelectionStringValue()) ==
+ if (Scanner::convertGeometryNameToID (m_pRadioBoxGeometry->getSelectionStringValue()) ==
Scanner::GEOMETRY_PARALLEL)
return (PI);
else
/////////////////////////////////////////////////////////////////////
-DialogGetReconstructionParameters::DialogGetReconstructionParameters (wxWindow* pParent, int iDefaultXSize,
- int iDefaultYSize, int iDefaultFilterID, double dDefaultHammingParam,
- int iDefaultFilterMethodID, int iDefaultFilterGenerationID, int iDefaultZeropad,
+DialogGetReconstructionParameters::DialogGetReconstructionParameters (wxWindow* pParent, int iDefaultXSize,
+ int iDefaultYSize, int iDefaultFilterID, double dDefaultHammingParam,
+ int iDefaultFilterMethodID, int iDefaultFilterGenerationID, int iDefaultZeropad,
int iDefaultInterpID, int iDefaultInterpParam, int iDefaultBackprojectID, int iTrace,
ReconstructionROI* pDefaultROI)
: wxDialog (pParent, -1, _T("Reconstruction Parameters"), wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE | wxCAPTION)
{
wxBoxSizer* pTopSizer = new wxBoxSizer (wxVERTICAL);
-
+
m_iDefaultXSize = iDefaultXSize;
m_iDefaultYSize = iDefaultYSize;
m_dDefaultFilterParam = dDefaultHammingParam;
pTopSizer->Add (new wxStaticText (this, -1, "Filtered Backprojection Parameters"), 0, wxALIGN_CENTER | wxTOP | wxLEFT | wxRIGHT, 5);
pTopSizer->Add (new wxStaticLine (this, -1, wxDefaultPosition, wxSize(3,3), wxHORIZONTAL), 0, wxEXPAND | wxALL, 5);
-
+
wxFlexGridSizer* pGridSizer = NULL;
if (theApp->getAdvancedOptions())
pGridSizer = new wxFlexGridSizer (4);
m_pRadioBoxFilter = new StringValueAndTitleRadioBox (this, _T("Filter"), SignalFilter::getReconstructFilterCount(), SignalFilter::getFilterTitleArray(), SignalFilter::getFilterNameArray());
m_pRadioBoxFilter->SetSelection (iDefaultFilterID);
pGridSizer->Add (m_pRadioBoxFilter, 0, wxALL | wxALIGN_LEFT | wxEXPAND);
-
+
if (theApp->getAdvancedOptions()) {
m_pRadioBoxFilterMethod = new StringValueAndTitleRadioBox (this, _T("Filter Method"), ProcessSignal::getFilterMethodCount(), ProcessSignal::getFilterMethodTitleArray(), ProcessSignal::getFilterMethodNameArray());
m_pRadioBoxFilterMethod->SetSelection (iDefaultFilterMethodID);
m_pRadioBoxFilterGeneration = new StringValueAndTitleRadioBox (this, _T("Filter Generation"), ProcessSignal::getFilterGenerationCount(), ProcessSignal::getFilterGenerationTitleArray(), ProcessSignal::getFilterGenerationNameArray());
m_pRadioBoxFilterGeneration->SetSelection (iDefaultFilterGenerationID);
pGridSizer->Add (m_pRadioBoxFilterGeneration, 0, wxALL | wxALIGN_LEFT | wxEXPAND);
-
+
m_pRadioBoxBackproject = new StringValueAndTitleRadioBox (this, _T("Backprojection"), Backprojector::getBackprojectCount(), Backprojector::getBackprojectTitleArray(), Backprojector::getBackprojectNameArray());
m_pRadioBoxBackproject->SetSelection (iDefaultBackprojectID);
pGridSizer->Add (m_pRadioBoxBackproject, 0, wxALL | wxALIGN_RIGHT | wxEXPAND);
m_pRadioBoxInterp = new StringValueAndTitleRadioBox (this, _T("Interpolation"), Backprojector::getInterpCount(), Backprojector::getInterpTitleArray(), Backprojector::getInterpNameArray());
m_pRadioBoxInterp->SetSelection (iDefaultInterpID);
pGridSizer->Add (m_pRadioBoxInterp, 0, wxALL | wxALIGN_RIGHT | wxEXPAND);
-
+
static const char* aszTraceTitle[] = {"None", "Full"};
static const char* aszTraceName[] = {"none", "full"};
m_pRadioBoxTrace = new StringValueAndTitleRadioBox (this, _T("Trace Level"), 2, aszTraceTitle, aszTraceName);
m_pTextCtrlInterpParam = new wxTextCtrl (this, -1, osInterpParam.str().c_str(), wxDefaultPosition, wxSize(100, 25), 0);
pGridSizer->Add (new wxStaticText (this, -1, "Interpolation Parameter"), 0, wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL);
pGridSizer->Add (m_pTextCtrlInterpParam, 0, wxALIGN_LEFT | wxALIGN_CENTER_VERTICAL);
-#endif
+#endif
if (theApp->getAdvancedOptions()) {
wxFlexGridSizer* pROIGridSizer = new wxFlexGridSizer (2);
}
pTopSizer->Add (pGridSizer, 1, wxALL, 3);
-
+
pTopSizer->Add (new wxStaticLine (this, -1, wxDefaultPosition, wxSize(3,3), wxHORIZONTAL), 0, wxEXPAND | wxALL, 5);
-
+
wxBoxSizer* pButtonSizer = new wxBoxSizer (wxHORIZONTAL);
wxButton* pButtonOk = new wxButton (this, wxID_OK, "Okay");
pButtonSizer->Add (pButtonOk, 0, wxEXPAND | wxALL, 10);
pButtonSizer->Add (pButtonCancel, 0, wxEXPAND | wxALL, 10);
CTSimHelpButton* pButtonHelp = new CTSimHelpButton (this, IDH_DLG_RECONSTRUCTION);
pButtonSizer->Add (pButtonHelp, 0, wxEXPAND | wxALL, 10);
-
+
pTopSizer->Add (pButtonSizer, 0, wxALIGN_CENTER);
pButtonOk->SetDefault();
-
+
SetAutoLayout (true);
SetSizer (pTopSizer);
pTopSizer->Layout();
: wxDialog (pParent, -1, _T("Filter Parameters"), wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE | wxCAPTION)
{
wxBoxSizer* pTopSizer = new wxBoxSizer (wxVERTICAL);
-
- pTopSizer->Add (new wxStaticText (this, -1, "Filter Parameters"), 0, wxALIGN_CENTER | wxTOP | wxLEFT | wxRIGHT, 5);
+
+ pTopSizer->Add (new wxStaticText (this, -1, "Filter Parameters"), 0, wxALIGN_CENTER | wxTOP | wxLEFT | wxRIGHT, 5);
pTopSizer->Add (new wxStaticLine (this, -1, wxDefaultPosition, wxSize(3,3), wxHORIZONTAL), 0, wxEXPAND | wxALL, 5);
-
+
wxFlexGridSizer* pGridSizer = new wxFlexGridSizer (2);
m_pRadioBoxFilter = new StringValueAndTitleRadioBox (this, _T("Filter"), SignalFilter::getFilterCount(), SignalFilter::getFilterTitleArray(), SignalFilter::getFilterNameArray());
m_pRadioBoxFilter->SetSelection (iDefaultFilterID);
pGridSizer->Add (m_pRadioBoxFilter, 0, wxALL | wxALIGN_LEFT | wxEXPAND);
-
+
m_pRadioBoxDomain = new StringValueAndTitleRadioBox (this, _T("Domain"), SignalFilter::getDomainCount(), SignalFilter::getDomainTitleArray(), SignalFilter::getDomainNameArray());
m_pRadioBoxDomain->SetSelection (iDefaultDomainID);
pGridSizer->Add (m_pRadioBoxDomain, 0, wxALL | wxALIGN_LEFT | wxEXPAND);
-
+
std::ostringstream os;
os << iDefaultXSize;
m_pTextCtrlXSize = new wxTextCtrl (this, -1, os.str().c_str(), wxDefaultPosition, wxSize(100, 25), 0);
m_pTextCtrlOutputScale = new wxTextCtrl (this, -1, osOutputScale.str().c_str(), wxDefaultPosition, wxSize(100, 25), 0);
pGridSizer->Add (new wxStaticText (this, -1, "Filter Output Scale"), 0, wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL);
pGridSizer->Add (m_pTextCtrlOutputScale, 0, wxALIGN_LEFT | wxALIGN_CENTER_VERTICAL);
-
+
pTopSizer->Add (pGridSizer, 1, wxALL, 3);
-
+
pTopSizer->Add (new wxStaticLine (this, -1, wxDefaultPosition, wxSize(3,3), wxHORIZONTAL), 0, wxEXPAND | wxALL, 5);
-
+
wxBoxSizer* pButtonSizer = new wxBoxSizer (wxHORIZONTAL);
wxButton* pButtonOk = new wxButton (this, wxID_OK, "Okay");
pButtonSizer->Add (pButtonOk, 0, wxEXPAND | wxALL, 10);
pButtonSizer->Add (pButtonCancel, 0, wxEXPAND | wxALL, 10);
CTSimHelpButton* pButtonHelp = new CTSimHelpButton (this, IDH_DLG_FILTER);
pButtonSizer->Add (pButtonHelp, 0, wxEXPAND | wxALL, 10);
-
+
pTopSizer->Add (pButtonSizer, 0, wxALIGN_CENTER);
pButtonOk->SetDefault();
: wxDialog (pParent, -1, _T("Select ExportParameters"), wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE | wxCAPTION)
{
wxBoxSizer* pTopSizer = new wxBoxSizer (wxVERTICAL);
-
+
pTopSizer->Add (new wxStaticText (this, -1, "Select Export Format"), 0, wxALIGN_CENTER | wxALL, 5);
-
+
pTopSizer->Add (new wxStaticLine (this, -1, wxDefaultPosition, wxSize(3,3), wxHORIZONTAL), 0, wxALL, 5);
-
- m_pRadioBoxFormat = new StringValueAndTitleRadioBox (this, _T("File Type"),
+
+ m_pRadioBoxFormat = new StringValueAndTitleRadioBox (this, _T("File Type"),
ImageFile::getExportFormatCount(), ImageFile::getExportFormatTitleArray(), ImageFile::getExportFormatNameArray());
m_pRadioBoxFormat->SetSelection (iDefaultFormatID);
pTopSizer->Add (m_pRadioBoxFormat, 0, wxALL | wxALIGN_CENTER);
-
+
pTopSizer->Add (new wxStaticLine (this, -1, wxDefaultPosition, wxSize(3,3), wxHORIZONTAL), 0, wxEXPAND | wxALL, 5);
-
+
wxBoxSizer* pButtonSizer = new wxBoxSizer (wxHORIZONTAL);
wxButton* pButtonOk = new wxButton (this, wxID_OK, "Okay");
pButtonSizer->Add (pButtonOk, 0, wxEXPAND | wxALL, 10);
pButtonSizer->Add (pButtonCancel, 0, wxEXPAND | wxALL, 10);
CTSimHelpButton* pButtonHelp = new CTSimHelpButton (this, IDH_DLG_EXPORT);
pButtonSizer->Add (pButtonHelp, 0, wxEXPAND | wxALL, 10);
-
+
pTopSizer->Add (pButtonSizer, 0, wxALIGN_CENTER);
pButtonOk->SetDefault();
: wxDialog (pParent, -1, _T("Select Import Parameters"), wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE | wxCAPTION)
{
wxBoxSizer* pTopSizer = new wxBoxSizer (wxVERTICAL);
-
+
pTopSizer->Add (new wxStaticText (this, -1, "Select Import Format"), 0, wxALIGN_CENTER | wxALL, 5);
-
+
pTopSizer->Add (new wxStaticLine (this, -1, wxDefaultPosition, wxSize(3,3), wxHORIZONTAL), 0, wxALL, 5);
-
- m_pRadioBoxFormat = new StringValueAndTitleRadioBox (this, _T("File Type"),
+
+ m_pRadioBoxFormat = new StringValueAndTitleRadioBox (this, _T("File Type"),
ImageFile::getImportFormatCount(), ImageFile::getImportFormatTitleArray(), ImageFile::getImportFormatNameArray());
m_pRadioBoxFormat->SetSelection (iDefaultFormatID);
pTopSizer->Add (m_pRadioBoxFormat, 0, wxALL | wxALIGN_CENTER);
-
+
pTopSizer->Add (new wxStaticLine (this, -1, wxDefaultPosition, wxSize(3,3), wxHORIZONTAL), 0, wxEXPAND | wxALL, 5);
-
+
wxBoxSizer* pButtonSizer = new wxBoxSizer (wxHORIZONTAL);
wxButton* pButtonOk = new wxButton (this, wxID_OK, "Okay");
pButtonSizer->Add (pButtonOk, 0, wxEXPAND | wxALL, 10);
pButtonSizer->Add (pButtonCancel, 0, wxEXPAND | wxALL, 10);
CTSimHelpButton* pButtonHelp = new CTSimHelpButton (this, IDH_DLG_IMPORT);
pButtonSizer->Add (pButtonHelp, 0, wxEXPAND | wxALL, 10);
-
+
pTopSizer->Add (pButtonSizer, 0, wxALIGN_CENTER);
pButtonOk->SetDefault();
m_iDefaultYSize = iDefaultYSize;
wxBoxSizer* pTopSizer = new wxBoxSizer (wxVERTICAL);
-
+
pTopSizer->Add (new wxStaticText (this, -1, pszTitle), 0, wxALIGN_CENTER | wxTOP | wxLEFT | wxRIGHT, 5);
-
+
pTopSizer->Add (new wxStaticLine (this, -1, wxDefaultPosition, wxSize(3,3), wxHORIZONTAL), 0, wxEXPAND | wxALL, 5);
-
+
std::ostringstream os;
os << iDefaultXSize;
m_pTextCtrlXSize = new wxTextCtrl (this, -1, os.str().c_str(), wxDefaultPosition, wxSize(100, 25), 0);
std::ostringstream osYSize;
osYSize << iDefaultYSize;
m_pTextCtrlYSize = new wxTextCtrl (this, -1, osYSize.str().c_str(), wxDefaultPosition, wxSize(100, 25), 0);
-
+
wxFlexGridSizer *pGridSizer = new wxFlexGridSizer (2);
pGridSizer->Add (new wxStaticText (this, -1, "X Size"), 0, wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL);
pGridSizer->Add (m_pTextCtrlXSize, 0, wxALIGN_CENTER_VERTICAL);
pGridSizer->Add (new wxStaticText (this, -1, "Y Size"), 0, wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL);
pGridSizer->Add (m_pTextCtrlYSize, 0, wxALIGN_CENTER_VERTICAL);
pTopSizer->Add (pGridSizer, 1, wxALL, 10);
-
+
pTopSizer->Add (new wxStaticLine (this, -1, wxDefaultPosition, wxSize(3,3), wxHORIZONTAL), 0, wxEXPAND | wxALL, 5);
-
+
wxBoxSizer* pButtonSizer = new wxBoxSizer (wxHORIZONTAL);
wxButton* pButtonOk = new wxButton (this, wxID_OK, "Okay");
pButtonSizer->Add (pButtonOk, 0, wxEXPAND | wxALL, 10);
wxButton* pButtonCancel = new wxButton (this, wxID_CANCEL, "Cancel");
pButtonSizer->Add (pButtonCancel, 0, wxEXPAND | wxALL, 10);
-
+
pTopSizer->Add (pButtonSizer, 0, wxALIGN_CENTER);
pButtonOk->SetDefault();
// DialogGetConvertPolarParameters
/////////////////////////////////////////////////////////////////////
-DialogGetConvertPolarParameters::DialogGetConvertPolarParameters (wxWindow* pParent, const char* const pszTitle,
+DialogGetConvertPolarParameters::DialogGetConvertPolarParameters (wxWindow* pParent, const char* const pszTitle,
int iDefaultXSize, int iDefaultYSize, int iDefaultInterpolationID, int iDefaultZeropad, int iHelpID)
: wxDialog (pParent, -1, _T(pszTitle), wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE | wxCAPTION)
{
m_iDefaultZeropad = iDefaultZeropad;
wxBoxSizer* pTopSizer = new wxBoxSizer (wxVERTICAL);
-
- pTopSizer->Add (new wxStaticText (this, -1, pszTitle), 0, wxALIGN_CENTER | wxTOP | wxLEFT | wxRIGHT, 5);
+
+ pTopSizer->Add (new wxStaticText (this, -1, pszTitle), 0, wxALIGN_CENTER | wxTOP | wxLEFT | wxRIGHT, 5);
pTopSizer->Add (new wxStaticLine (this, -1, wxDefaultPosition, wxSize(3,3), wxHORIZONTAL), 0, wxEXPAND | wxALL, 5);
-
+
wxFlexGridSizer* pGridSizer = new wxFlexGridSizer (1);
-
+
m_pRadioBoxInterpolation = new StringValueAndTitleRadioBox (this, _T("Interpolation"), Projections::getInterpCount(), Projections::getInterpTitleArray(), Projections::getInterpNameArray());
m_pRadioBoxInterpolation->SetSelection (iDefaultInterpolationID);
pGridSizer->Add (m_pRadioBoxInterpolation, 0, wxALL | wxALIGN_CENTER);
-
+
wxFlexGridSizer* pTextGridSizer = new wxFlexGridSizer (2);
std::ostringstream os;
os << iDefaultXSize;
- m_pTextCtrlXSize = new wxTextCtrl (this, -1, os.str().c_str(), wxDefaultPosition, wxSize(100, 25), 0);
+ m_pTextCtrlXSize = new wxTextCtrl (this, -1, os.str().c_str(), wxDefaultPosition, wxSize(100, 25), 0);
pTextGridSizer->Add (new wxStaticText (this, -1, "X Size"), 0, wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL);
pTextGridSizer->Add (m_pTextCtrlXSize, 0, wxALIGN_LEFT | wxALIGN_CENTER_VERTICAL);
std::ostringstream osYSize;
pGridSizer->Add (pTextGridSizer, 0, wxALIGN_CENTER | wxALL);
pTopSizer->Add (pGridSizer, 1, wxALL | wxALIGN_CENTER, 3);
-
+
pTopSizer->Add (new wxStaticLine (this, -1, wxDefaultPosition, wxSize(3,3), wxHORIZONTAL), 0, wxEXPAND | wxALL, 5);
-
+
wxBoxSizer* pButtonSizer = new wxBoxSizer (wxHORIZONTAL);
wxButton* pButtonOk = new wxButton (this, wxID_OK, "Okay");
pButtonSizer->Add (pButtonOk, 0, wxEXPAND | wxALL, 10);
pButtonSizer->Add (pButtonCancel, 0, wxEXPAND | wxALL, 10);
CTSimHelpButton* pButtonHelp = new CTSimHelpButton (this, iHelpID);
pButtonSizer->Add (pButtonHelp, 0, wxEXPAND | wxALL, 10);
-
+
pTopSizer->Add (pButtonSizer, 0, wxALIGN_CENTER);
pButtonOk->SetDefault();
SetAutoLayout (true);
class DialogGetRasterParameters : public wxDialog
{
public:
- DialogGetRasterParameters (wxWindow* pParent, int iDefaultXSize = 0, int iDefaultYSize = 0,
+ DialogGetRasterParameters (wxWindow* pParent, int iDefaultXSize = 0, int iDefaultYSize = 0,
int iDefaultNSamples = 1, double dDefaultViewRatio = 1);
virtual ~DialogGetRasterParameters ();
class DialogGetProjectionParameters : public wxDialog
{
public:
- DialogGetProjectionParameters (wxWindow* pParent, int iDefaultNDet = 0,
- int iDefaultNView = 0, int iDefaultOffsetView = 0, int iDefaultNSamples = 1, double dDefaultRotAngle = 1.,
- double dDefaultFocalLength = 1, double dDefaultCenterDetectorLength = 1, double dDefaultViewRatio = 1.,
+ DialogGetProjectionParameters (wxWindow* pParent, int iDefaultNDet = 0,
+ int iDefaultNView = 0, int iDefaultOffsetView = 0, int iDefaultNSamples = 1, double dDefaultRotAngle = 1.,
+ double dDefaultFocalLength = 1, double dDefaultCenterDetectorLength = 1, double dDefaultViewRatio = 1.,
double dDefaultScanRatio = 1., int iDefaultGeometry = Scanner::GEOMETRY_PARALLEL, int iDefaultTrace = Trace::TRACE_NONE);
~DialogGetProjectionParameters ();
unsigned int getNDet ();
unsigned int getNView ();
- unsigned int getOffsetView ();
+ unsigned int getOffsetView ();
unsigned int getNSamples ();
int getTrace ();
int m_iDefaultNDet;
int m_iDefaultNView;
- int m_iDefaultOffsetView;
+ int m_iDefaultOffsetView;
int m_iDefaultNSamples;
int m_iDefaultTrace;
int m_iDefaultGeometry;
class DialogGetReconstructionParameters : public wxDialog
{
public:
- DialogGetReconstructionParameters (wxWindow* pParent, int iDefaultXSize = 0, int iDefaultYSize = 0,
- int iDefaultFilterID = SignalFilter::FILTER_ABS_BANDLIMIT, double dDefaultFilterParam = 1.,
- int iDefaultFilterMethodID = ProcessSignal::FILTER_METHOD_CONVOLUTION,
- int iDefaultFilterGeneration = ProcessSignal::FILTER_GENERATION_DIRECT,
- int iDefaultZeropad = 3, int iDefaultInterpID = Backprojector::INTERP_LINEAR,
- int iDefaultInterpParam = 1, int iDefaultBackprojectID = Backprojector::BPROJ_IDIFF,
+ DialogGetReconstructionParameters (wxWindow* pParent, int iDefaultXSize = 0, int iDefaultYSize = 0,
+ int iDefaultFilterID = SignalFilter::FILTER_ABS_BANDLIMIT, double dDefaultFilterParam = 1.,
+ int iDefaultFilterMethodID = ProcessSignal::FILTER_METHOD_CONVOLUTION,
+ int iDefaultFilterGeneration = ProcessSignal::FILTER_GENERATION_DIRECT,
+ int iDefaultZeropad = 3, int iDefaultInterpID = Backprojector::INTERP_LINEAR,
+ int iDefaultInterpParam = 1, int iDefaultBackprojectID = Backprojector::BPROJ_IDIFF,
int iDefaultTrace = Trace::TRACE_NONE, ReconstructionROI* pROI = NULL);
virtual ~DialogGetReconstructionParameters ();
private:
const double m_dMean;
- const double m_dMode;
- const double m_dMedian;
- const double m_dStdDev;
+ const double m_dMode;
+ const double m_dMedian;
+ const double m_dStdDev;
wxTextCtrl* m_pTextCtrlStdDevFactor;
wxRadioBox* m_pRadioBoxCenter;
class DialogGetConvertPolarParameters : public wxDialog
{
public:
- DialogGetConvertPolarParameters (wxWindow* pParent, const char* const pszTitle, int iDefaultXSize = 0,
- int iDefaultYSize = 0, int iDefaultInterpolationID = Projections::POLAR_INTERP_BILINEAR,
+ DialogGetConvertPolarParameters (wxWindow* pParent, const char* const pszTitle, int iDefaultXSize = 0,
+ int iDefaultYSize = 0, int iDefaultInterpolationID = Projections::POLAR_INTERP_BILINEAR,
int iDefaultZeropad = 3, int iHelpID = IDH_DLG_POLAR);
virtual ~DialogGetConvertPolarParameters ();
IMPLEMENT_CLASS(EZPlotControl, wxPanel)
-EZPlotControl::EZPlotControl (wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size,
+EZPlotControl::EZPlotControl (wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size,
long style, const wxValidator& validator, const wxString& name)
: m_pEZPlot(0), m_pSGPDriver(0), m_pSGP(0), m_pDC(0)
{
}
EZPlotControl::~EZPlotControl()
-{
+{
delete m_pEZPlot;
delete m_pSGP;
delete m_pSGPDriver;
m_parentTop = parent;
while ( m_parentTop && m_parentTop->GetParent() )
m_parentTop = m_parentTop->GetParent();
-
+
wxBoxSizer* pTopSizer = new wxBoxSizer (wxVERTICAL);
pTopSizer->Add (m_pEZPlotCtrl = new EZPlotControl (this), 0, wxALIGN_CENTER | wxALL, 5);
-
+
wxBoxSizer* pButtonSizer = new wxBoxSizer (wxHORIZONTAL);
wxButton* pButtonOk = new wxButton (this, wxID_OK, "Ok");
pButtonSizer->Add (pButtonOk, 0, wxEXPAND | wxALL, 10);
if (bCancelButton) {
wxButton* pButtonCancel = new wxButton (this, wxID_CANCEL, "Cancel");
pButtonSizer->Add (pButtonCancel, 0, wxEXPAND | wxALL, 10);
- }
+ }
pTopSizer->Add (pButtonSizer, 0, wxALIGN_CENTER);
-
+
SetAutoLayout (true);
SetSizer (pTopSizer);
pTopSizer->Fit (this);
class EZPlotControl : public wxPanel
{
-private:
+private:
DECLARE_DYNAMIC_CLASS (EZPlotControl)
DECLARE_EVENT_TABLE ()
EZPlot* m_pEZPlot;
virtual wxSize GetBestSize() const;
- EZPlot* getEZPlot()
+ EZPlot* getEZPlot()
{ return m_pEZPlot; }
void OnPaint(wxPaintEvent& event);
ProjectionsDialog::ProjectionsDialog (Scanner& rScanner, Projections& rProj, const Phantom& rPhantom, const int iTrace, wxWindow *parent)
- : wxDialog(parent, -1, "Collect Projections", wxDefaultPosition), m_rScanner(rScanner), m_rProjections(rProj), m_rPhantom(rPhantom),
+ : wxDialog(parent, -1, "Collect Projections", wxDefaultPosition), m_rScanner(rScanner), m_rProjections(rProj), m_rPhantom(rPhantom),
m_pSGPDriver(NULL), m_pSGP(NULL), m_iTrace(iTrace), m_pDC(NULL), m_btnAbort(0), m_btnPause(0), m_btnStep(0)
{
m_state = Continue;
m_parentTop = parent;
while ( m_parentTop && m_parentTop->GetParent() )
m_parentTop = m_parentTop->GetParent();
-
+
m_btnAbort = new wxButton(this, wxID_CANCEL, _("Cancel"));
wxLayoutConstraints* c = new wxLayoutConstraints;
c->right.SameAs(this, wxRight, 2*LAYOUT_X_MARGIN);
c->bottom.SameAs(this, wxBottom, 2*LAYOUT_Y_MARGIN);
-
+
wxSize sizeBtn = wxButton::GetDefaultSize();
c->width.Absolute(sizeBtn.x);
c->height.Absolute(sizeBtn.y);
-
+
m_btnAbort->SetConstraints(c);
-
+
m_btnPause = new wxButton (this, ID_BTN_PAUSE, wxString("Pause"));
wxLayoutConstraints* cPause = new wxLayoutConstraints;
cPause->right.SameAs(this, wxRight, 3*LAYOUT_X_MARGIN + sizeBtn.x);
cPause->width.Absolute(sizeBtn.x);
cPause->height.Absolute(sizeBtn.y);
m_btnPause->SetConstraints(cPause);
-
+
m_btnStep = new wxButton (this, ID_BTN_STEP, wxString("Step"));
wxLayoutConstraints* cStep = new wxLayoutConstraints;
cStep->right.SameAs(this, wxRight, 5*LAYOUT_X_MARGIN + sizeBtn.x * 2);
cStep->width.Absolute(sizeBtn.x);
cStep->height.Absolute(sizeBtn.y);
m_btnStep->SetConstraints(cStep);
-
+
SetAutoLayout(TRUE);
Layout();
-
+
wxSize sizeDlg (500,500);
if (sizeDlg.x != sizeDlg.y) {
sizeDlg.x = imax(sizeDlg.x,sizeDlg.y);
}
if (m_iTrace >= Trace::TRACE_PLOT)
sizeDlg.x += 250;
-
+
m_iClientX = sizeDlg.x;
m_iClientY = sizeDlg.y;
SetClientSize(sizeDlg);
-
+
Centre(wxCENTER_FRAME | wxBOTH);
-
+
if ( m_parentTop )
m_parentTop->Enable(FALSE);
-
+
Show(TRUE);
Enable(TRUE); // enable this window
-
+
m_bitmap.Create (m_iClientX, m_iClientY); // save a copy of screen
m_pDC = dynamic_cast<wxDC*> (new wxClientDC (this));
int x, y;
this->GetClientSize(&x, &y);
m_pSGPDriver = new SGPDriver (m_pDC, x, y);
m_pSGP = new SGP (*m_pSGPDriver);
-
+
wxYield(); // Update the display
-
+
m_pSGP->setTextPointSize(10);
#ifdef __WXMAC__
MacUpdateImmediately();
const DetectorValue* detValues = detArray.detValues();
double* detPos = new double [detArray.nDet()];
for (int i = 0; i < detArray.nDet(); i++)
- detPos[i] = i;
+ detPos[i] = i;
EZPlot ezplot;
ezplot.ezset ("grid");
ezplot.ezset ("box");
{
if (iViewNumber <= m_iLastView) // already done this view
return true;
-
+
if (iViewNumber < m_rProjections.nView()) {
showView (iViewNumber);
wxYield(); // update the display
::wxUsleep(500);
}
} else {
- m_state = Finished; // so that we return TRUE below and
+ m_state = Finished; // so that we return TRUE below and
// that [Cancel] handler knew what to do
}
-
+
#ifdef __WXMAC__
MacUpdateImmediately();
#endif
-
+
return m_state != Cancelled;
}
// request to cancel was received, the next time Update() is called we
// will handle it
m_state = Cancelled;
-
+
// update the button state immediately so that the user knows that the
// request has been noticed
m_btnAbort->Disable();
}
-void
+void
ProjectionsDialog::OnPause (wxCommandEvent& event)
{
if ( m_state == Finished ) {
}
}
-void
+void
ProjectionsDialog::OnStep (wxCommandEvent& event)
{
if ( m_state == Finished ) {
{
if ( m_parentTop )
m_parentTop->Enable(TRUE);
-
+
delete m_pSGP;
delete m_pSGPDriver;
delete m_pDC;
wxDC* m_pDC;
wxButton *m_btnAbort; // the abort button (or NULL if none)
- wxButton *m_btnPause;
+ wxButton *m_btnPause;
wxButton *m_btnStep;
wxMemoryDC m_memoryDC; // for restoring image on OnPaint
IMPLEMENT_CLASS(ReconstructDialog, wxDialog)
-ReconstructDialog::ReconstructDialog (Reconstructor& rReconstruct, const Projections& rProj,
+ReconstructDialog::ReconstructDialog (Reconstructor& rReconstruct, const Projections& rProj,
ImageFile& rIF, const int iTrace, wxWindow *parent)
-: wxDialog(parent, -1, "Reconstruction", wxDefaultPosition), m_rReconstructor(rReconstruct),
- m_rProjections(rProj), m_rImageFile(rIF), m_pSGPDriver(NULL), m_pSGP(NULL),
+: wxDialog(parent, -1, "Reconstruction", wxDefaultPosition), m_rReconstructor(rReconstruct),
+ m_rProjections(rProj), m_rImageFile(rIF), m_pSGPDriver(NULL), m_pSGP(NULL),
m_iTrace(iTrace), m_pDC(NULL), m_btnAbort(0), m_btnPause(0), m_btnStep(0)
{
m_state = Continue;
m_parentTop = parent;
while ( m_parentTop && m_parentTop->GetParent() )
m_parentTop = m_parentTop->GetParent();
-
+
m_btnAbort = new wxButton(this, wxID_CANCEL, _("Cancel"));
wxLayoutConstraints* c = new wxLayoutConstraints;
c->right.SameAs(this, wxRight, 2*LAYOUT_X_MARGIN);
c->bottom.SameAs(this, wxBottom, 2*LAYOUT_Y_MARGIN);
-
+
wxSize sizeBtn = wxButton::GetDefaultSize();
c->width.Absolute(sizeBtn.x);
c->height.Absolute(sizeBtn.y);
-
+
m_btnAbort->SetConstraints(c);
-
+
m_btnPause = new wxButton (this, ID_BTN_PAUSE, wxString("Pause"));
wxLayoutConstraints* cPause = new wxLayoutConstraints;
cPause->right.SameAs(this, wxRight, 3*LAYOUT_X_MARGIN + sizeBtn.x);
cPause->width.Absolute(sizeBtn.x);
cPause->height.Absolute(sizeBtn.y);
m_btnPause->SetConstraints(cPause);
-
+
m_btnStep = new wxButton (this, ID_BTN_STEP, wxString("Step"));
wxLayoutConstraints* cStep = new wxLayoutConstraints;
cStep->right.SameAs(this, wxRight, 5*LAYOUT_X_MARGIN + sizeBtn.x * 2);
cStep->width.Absolute(sizeBtn.x);
cStep->height.Absolute(sizeBtn.y);
m_btnStep->SetConstraints(cStep);
-
+
SetAutoLayout(TRUE);
Layout();
-
+
m_nxGraph = 500;
m_nyGraph = 500;
wxSize sizeDlg (m_nxGraph, m_nyGraph);
m_nxImage = m_rImageFile.nx();
if (m_nxImage > MAX_IMAGE_X)
- m_nxImage = MAX_IMAGE_X;
+ m_nxImage = MAX_IMAGE_X;
m_nyImage = m_rImageFile.ny();
if (m_nyImage > MAX_IMAGE_Y)
- m_nyImage = MAX_IMAGE_Y;
-
+ m_nyImage = MAX_IMAGE_Y;
+
sizeDlg.x += m_nxImage;
sizeDlg.y = imax (sizeDlg.y, m_nyImage);
-
+
m_iClientX = sizeDlg.x;
m_iClientY = sizeDlg.y;
SetClientSize (sizeDlg);
-
+
Centre(wxCENTER_FRAME | wxBOTH);
-
+
if ( m_parentTop )
- m_parentTop->Enable(FALSE);
-
+ m_parentTop->Enable(FALSE);
+
Show(TRUE);
Enable(TRUE); // enable this window
-
+
m_bitmap.Create (m_iClientX, m_iClientY); // save a copy of screen
m_pDC = dynamic_cast<wxDC*> (new wxClientDC (this));
int x, y;
this->GetClientSize(&x, &y);
m_pSGPDriver = new SGPDriver (m_pDC, x, y);
m_pSGP = new SGP (*m_pSGPDriver);
-
+
wxYield(); // Update the display
-
+
m_pSGPDriver->idWX()->SetFont(*wxSWISS_FONT);
}
void
ReconstructDialog::showView (int iViewNumber, bool bBackprojectView)
{
- if ( iViewNumber < m_rProjections.nView() ) {
- m_iLastView = iViewNumber;
- ::wxYield(); // update the display
- m_pSGP->eraseWindow();
- m_btnPause->Refresh();
- m_btnStep->Refresh();
- m_btnAbort->Refresh();
-
- char szProgress [256];
- snprintf (szProgress, sizeof(szProgress), "Reconstructing View %d (%.1f%%)", iViewNumber, 100 * iViewNumber / static_cast<double>(m_rProjections.nView()));
- m_pSGP->setViewport (0, 0, 1, 1);
- m_pSGP->setWindow (0, 0, 1, 1);
- m_pSGP->setTextColor (C_LTRED, -1);
- m_pSGP->setTextPointSize (20.);
- m_pSGP->moveAbs(0., m_pSGP->getCharHeight());
- m_pSGP->drawText (szProgress);
- m_pSGP->setTextPointSize (10.);
-
+ if ( iViewNumber < m_rProjections.nView() ) {
+ m_iLastView = iViewNumber;
+ ::wxYield(); // update the display
+ m_pSGP->eraseWindow();
+ m_btnPause->Refresh();
+ m_btnStep->Refresh();
+ m_btnAbort->Refresh();
+
+ char szProgress [256];
+ snprintf (szProgress, sizeof(szProgress), "Reconstructing View %d (%.1f%%)", iViewNumber, 100 * iViewNumber / static_cast<double>(m_rProjections.nView()));
+ m_pSGP->setViewport (0, 0, 1, 1);
+ m_pSGP->setWindow (0, 0, 1, 1);
+ m_pSGP->setTextColor (C_LTRED, -1);
+ m_pSGP->setTextPointSize (20.);
+ m_pSGP->moveAbs(0., m_pSGP->getCharHeight());
+ m_pSGP->drawText (szProgress);
+ m_pSGP->setTextPointSize (10.);
+
int iXDialog, iYDialog;
GetClientSize (&iXDialog, &iYDialog);
double dGraphWidth = (iXDialog - m_nxImage) / static_cast<double>(iXDialog);
- m_rReconstructor.reconstructView (iViewNumber, 1, m_pSGP, bBackprojectView, dGraphWidth);
+ m_rReconstructor.reconstructView (iViewNumber, 1, m_pSGP, bBackprojectView, dGraphWidth);
::wxYield();
::wxYield();
::wxYield();
::wxYield();
- ImageFileArrayConst v = m_rImageFile.getArray();
- int xBase = m_nxGraph;
- int yBase = 0;
- if (m_nyGraph > m_nyImage)
- yBase = (m_nyGraph - m_nyImage) / 2;
- double minValue = v[0][0];
- double maxValue = v[0][0];
- for (int ix = 0; ix < m_nxImage; ix++) {
- for (int iy = 0; iy < m_nyImage; iy++) {
- double dPixel = v[ix][iy];
- if (dPixel < minValue)
- minValue = dPixel;
- else if (dPixel > maxValue)
- maxValue = dPixel;
- }
- }
- unsigned char* imageData = new unsigned char [m_nxImage * m_nyImage * 3];
- double dScale = 255 / (maxValue - minValue);
- for (int ix2 = 0; ix2 < m_nxImage; ix2++) {
- for (int iy = 0; iy < m_nyImage; iy++) {
- double dPixel = v[ix2][iy];
- dPixel = (dPixel - minValue) * dScale;
- int intensity = nearest<int>(dPixel);
- intensity = clamp (intensity, 0, 255);
- int baseAddr = ((m_nyImage - 1 - iy) * m_nxImage + ix2) * 3;
- imageData[baseAddr] = imageData[baseAddr+1] = imageData[baseAddr+2] = intensity;
- }
- }
- wxImage image (m_nxImage, m_nyImage, imageData, true);
- wxBitmap bitmap (image);
- m_pSGP->getDriver().idWX()->DrawBitmap(bitmap, xBase, yBase, false);
- delete imageData;
- }
+ ImageFileArrayConst v = m_rImageFile.getArray();
+ int xBase = m_nxGraph;
+ int yBase = 0;
+ if (m_nyGraph > m_nyImage)
+ yBase = (m_nyGraph - m_nyImage) / 2;
+ double minValue = v[0][0];
+ double maxValue = v[0][0];
+ for (int ix = 0; ix < m_nxImage; ix++) {
+ for (int iy = 0; iy < m_nyImage; iy++) {
+ double dPixel = v[ix][iy];
+ if (dPixel < minValue)
+ minValue = dPixel;
+ else if (dPixel > maxValue)
+ maxValue = dPixel;
+ }
+ }
+ unsigned char* imageData = new unsigned char [m_nxImage * m_nyImage * 3];
+ double dScale = 255 / (maxValue - minValue);
+ for (int ix2 = 0; ix2 < m_nxImage; ix2++) {
+ for (int iy = 0; iy < m_nyImage; iy++) {
+ double dPixel = v[ix2][iy];
+ dPixel = (dPixel - minValue) * dScale;
+ int intensity = nearest<int>(dPixel);
+ intensity = clamp (intensity, 0, 255);
+ int baseAddr = ((m_nyImage - 1 - iy) * m_nxImage + ix2) * 3;
+ imageData[baseAddr] = imageData[baseAddr+1] = imageData[baseAddr+2] = intensity;
+ }
+ }
+ wxImage image (m_nxImage, m_nyImage, imageData, true);
+ wxBitmap bitmap (image);
+ m_pSGP->getDriver().idWX()->DrawBitmap(bitmap, xBase, yBase, false);
+ delete imageData;
+ }
::wxYield();
}
bool
ReconstructDialog::reconstructView (int iViewNumber, bool bBackproject)
{
- if (iViewNumber <= m_iLastView) // have already done this view
- return true;
-
- if (iViewNumber < m_rProjections.nView()) {
- ::wxYield(); // update the display
- showView (iViewNumber, bBackproject);
- ::wxYield(); // update the display
- if (m_iTrace >= Trace::TRACE_PLOT) {
- ::wxUsleep(250);
- }
- } else {
- m_state = Finished; // so that we return TRUE below and
- } // that [Cancel] handler knew what to do
-
- ::wxYield(); // update the display
- return m_state != Cancelled;
+ if (iViewNumber <= m_iLastView) // have already done this view
+ return true;
+
+ if (iViewNumber < m_rProjections.nView()) {
+ ::wxYield(); // update the display
+ showView (iViewNumber, bBackproject);
+ ::wxYield(); // update the display
+ if (m_iTrace >= Trace::TRACE_PLOT) {
+ ::wxUsleep(250);
+ }
+ } else {
+ m_state = Finished; // so that we return TRUE below and
+ } // that [Cancel] handler knew what to do
+
+ ::wxYield(); // update the display
+ return m_state != Cancelled;
}
void ReconstructDialog::OnCancel (wxCommandEvent& event)
{
- if ( m_state == Finished ) {
- // this means that the count down is already finished and we're being
- // shown as a modal dialog - so just let the default handler do the job
- event.Skip();
- } else {
- // request to cancel was received, the next time Update() is called we
- // will handle it
- m_state = Cancelled;
-
- // update the button state immediately so that the user knows that the
- // request has been noticed
- m_btnAbort->Disable();
- }
+ if ( m_state == Finished ) {
+ // this means that the count down is already finished and we're being
+ // shown as a modal dialog - so just let the default handler do the job
+ event.Skip();
+ } else {
+ // request to cancel was received, the next time Update() is called we
+ // will handle it
+ m_state = Cancelled;
+
+ // update the button state immediately so that the user knows that the
+ // request has been noticed
+ m_btnAbort->Disable();
+ }
}
-void
+void
ReconstructDialog::OnPause (wxCommandEvent& event)
{
- if ( m_state == Finished ) {
- // this means that the count down is already finished and we're being
- // shown as a modal dialog - so just let the default handler do the job
- event.Skip();
- } else if (m_state == Continue) {
- m_memoryDC.SelectObject (m_bitmap); // in memoryDC
- m_pSGP->setDC (&m_memoryDC);
- m_memoryDC.SetFont (*wxSWISS_FONT);
- showView (m_iLastView, false);
- m_state = Paused;
- m_btnPause->SetLabel (wxString("Resume"));
- m_pSGP->setDC (m_pDC);
- m_memoryDC.SelectObject(wxNullBitmap);
- } else if (m_state == Paused) {
- m_state = Continue;
- m_btnPause->SetLabel (wxString("Pause"));
- }
+ if ( m_state == Finished ) {
+ // this means that the count down is already finished and we're being
+ // shown as a modal dialog - so just let the default handler do the job
+ event.Skip();
+ } else if (m_state == Continue) {
+ m_memoryDC.SelectObject (m_bitmap); // in memoryDC
+ m_pSGP->setDC (&m_memoryDC);
+ m_memoryDC.SetFont (*wxSWISS_FONT);
+ showView (m_iLastView, false);
+ m_state = Paused;
+ m_btnPause->SetLabel (wxString("Resume"));
+ m_pSGP->setDC (m_pDC);
+ m_memoryDC.SelectObject(wxNullBitmap);
+ } else if (m_state == Paused) {
+ m_state = Continue;
+ m_btnPause->SetLabel (wxString("Pause"));
+ }
}
-void
+void
ReconstructDialog::OnStep (wxCommandEvent& event)
{
- if ( m_state == Finished ) {
- event.Skip();
- } else if (m_state == Continue) {
- m_memoryDC.SelectObject (m_bitmap); // in memoryDC
- m_pSGP->setDC (&m_memoryDC);
- m_memoryDC.SetFont (*wxSWISS_FONT);
- showView (m_iLastView, false);
- m_state = Paused;
- m_btnPause->SetLabel (wxString("Resume"));
- m_pSGP->setDC (m_pDC);
- m_memoryDC.SelectObject(wxNullBitmap);
- Refresh();
- } else if (m_state == Paused) {
- m_memoryDC.SelectObject (m_bitmap); // in memoryDC
- m_pSGP->setDC (&m_memoryDC);
- m_memoryDC.SetFont (*wxSWISS_FONT);
- reconstructView (m_iLastView + 1);
- m_pSGP->setDC (m_pDC);
- m_memoryDC.SelectObject(wxNullBitmap);
- Refresh();
- }
+ if ( m_state == Finished ) {
+ event.Skip();
+ } else if (m_state == Continue) {
+ m_memoryDC.SelectObject (m_bitmap); // in memoryDC
+ m_pSGP->setDC (&m_memoryDC);
+ m_memoryDC.SetFont (*wxSWISS_FONT);
+ showView (m_iLastView, false);
+ m_state = Paused;
+ m_btnPause->SetLabel (wxString("Resume"));
+ m_pSGP->setDC (m_pDC);
+ m_memoryDC.SelectObject(wxNullBitmap);
+ Refresh();
+ } else if (m_state == Paused) {
+ m_memoryDC.SelectObject (m_bitmap); // in memoryDC
+ m_pSGP->setDC (&m_memoryDC);
+ m_memoryDC.SetFont (*wxSWISS_FONT);
+ reconstructView (m_iLastView + 1);
+ m_pSGP->setDC (m_pDC);
+ m_memoryDC.SelectObject(wxNullBitmap);
+ Refresh();
+ }
}
void ReconstructDialog::OnClose(wxCloseEvent& event)
{
if ( m_state == Uncancellable )
- event.Veto(TRUE); // can't close this dialog
+ event.Veto(TRUE); // can't close this dialog
else if ( m_state == Finished )
- event.Skip(); // let the default handler close the window as we already terminated
+ event.Skip(); // let the default handler close the window as we already terminated
else
- m_state = Cancelled; // next Update() will notice it
+ m_state = Cancelled; // next Update() will notice it
}
void
ReconstructDialog::OnPaint (wxPaintEvent& event)
{
- wxPaintDC paintDC (this);
- if (m_state == Paused) {
- paintDC.DrawBitmap (m_bitmap, 0, 0, false);
- }
+ wxPaintDC paintDC (this);
+ if (m_state == Paused) {
+ paintDC.DrawBitmap (m_bitmap, 0, 0, false);
+ }
}
ReconstructDialog::~ReconstructDialog()
{
- if ( m_parentTop )
- m_parentTop->Enable(TRUE);
-
- delete m_pSGP;
- delete m_pSGPDriver;
- delete m_pDC;
+ if ( m_parentTop )
+ m_parentTop->Enable(TRUE);
+
+ delete m_pSGP;
+ delete m_pSGPDriver;
+ delete m_pDC;
}
wxDC* m_pDC;
wxButton *m_btnAbort; // the abort button (or NULL if none)
- wxButton *m_btnPause;
+ wxButton *m_btnPause;
wxButton *m_btnStep;
wxMemoryDC m_memoryDC; // for restoring image on OnPaint
m_bBadFileOpen = true;
return false;
}
-
+
if (theApp->getVerboseLogging() && filename != "")
*theApp->getLog() << "Read image file " << filename << "\n";
-
- SetFilename(filename, true);
+
+ SetFilename(filename, true);
Modify(false);
getView()->setInitialClientSize();
UpdateAllViews();
return true;
}
-bool
+bool
ImageFileDocument::IsModified(void) const
{
return wxDocument::IsModified();
}
-void
+void
ImageFileDocument::Modify(bool mod)
{
wxDocument::Modify(mod);
}
-ImageFileView*
+ImageFileView*
ImageFileDocument::getView() const
-{
- return dynamic_cast<ImageFileView*>(GetFirstView());
+{
+ return dynamic_cast<ImageFileView*>(GetFirstView());
}
bool
{
m_criticalSection.Enter();
bool bFound = false;
- for (BackgroundContainer::iterator i = m_vecpBackgroundSupervisors.begin();
- i != m_vecpBackgroundSupervisors.end();
- i++)
+ for (BackgroundContainer::iterator i = m_vecpBackgroundSupervisors.begin();
+ i != m_vecpBackgroundSupervisors.end();
+ i++)
if (*i == pSupervisor) {
m_vecpBackgroundSupervisors.erase(i);
bFound = true;
}
m_criticalSection.Leave();
- if (! bFound)
+ if (! bFound)
sys_error (ERR_SEVERE, "Could not find background task [OnRemoveBackground]");
}
#endif
{
#ifdef HAVE_WXTHREADS
m_criticalSection.Enter();
- for (BackgroundContainer::iterator i = m_vecpBackgroundSupervisors.begin();
+ for (BackgroundContainer::iterator i = m_vecpBackgroundSupervisors.begin();
i != m_vecpBackgroundSupervisors.end(); i++)
(*i)->onCancel();
m_criticalSection.Leave();
IMPLEMENT_DYNAMIC_CLASS(ProjectionFileDocument, BackgroundProcessingDocument)
-bool
+bool
ProjectionFileDocument::OnSaveDocument(const wxString& filename)
{
if (! m_pProjectionFile->write (filename.c_str())) {
delete m_pProjectionFile;
}
-bool
+bool
ProjectionFileDocument::OnOpenDocument(const wxString& filename)
{
if (! OnSaveModified())
Modify(false);
getView()->setInitialClientSize();
UpdateAllViews();
-
+
return true;
}
-bool
+bool
ProjectionFileDocument::IsModified(void) const
{
return wxDocument::IsModified();
}
-void
+void
ProjectionFileDocument::Modify(bool mod)
{
wxDocument::Modify(mod);
}
-ProjectionFileView*
+ProjectionFileView*
ProjectionFileDocument::getView() const
-{
- return dynamic_cast<ProjectionFileView*>(GetFirstView());
+{
+ return dynamic_cast<ProjectionFileView*>(GetFirstView());
}
void
cancelRunningTasks();
}
-bool
+bool
PhantomFileDocument::OnOpenDocument(const wxString& constFilename)
{
if (! OnSaveModified())
Modify(false);
UpdateAllViews();
m_bBadFileOpen = false;
-
+
return true;
}
-bool
+bool
PhantomFileDocument::OnSaveDocument(const wxString& filename)
{
if (! m_phantom.fileWrite (filename.c_str())) {
return true;
}
-bool
+bool
PhantomFileDocument::IsModified(void) const
{
return false;
}
-void
+void
PhantomFileDocument::Modify(bool mod)
{
wxDocument::Modify(mod);
}
-PhantomFileView*
+PhantomFileView*
PhantomFileDocument::getView() const
-{
- return dynamic_cast<PhantomFileView*>(GetFirstView());
+{
+ return dynamic_cast<PhantomFileView*>(GetFirstView());
}
void
IMPLEMENT_DYNAMIC_CLASS(PlotFileDocument, wxDocument)
-bool
+bool
PlotFileDocument::OnSaveDocument(const wxString& filename)
{
m_namePlot = filename.c_str();
return true;
}
-bool
+bool
PlotFileDocument::OnOpenDocument(const wxString& filename)
{
if (! OnSaveModified())
Modify (false);
getView()->setInitialClientSize();
UpdateAllViews();
-
+
return true;
}
-bool
+bool
PlotFileDocument::IsModified(void) const
{
return wxDocument::IsModified();
}
-void
+void
PlotFileDocument::Modify (bool mod)
{
wxDocument::Modify(mod);
}
-PlotFileView*
+PlotFileView*
PlotFileDocument::getView() const
-{
- return dynamic_cast<PlotFileView*>(GetFirstView());
+{
+ return dynamic_cast<PlotFileView*>(GetFirstView());
}
void
IMPLEMENT_DYNAMIC_CLASS(TextFileDocument, wxDocument)
-bool
+bool
TextFileDocument::OnSaveDocument(const wxString& filename)
{
TextFileView *view = getView();
return true;
}
-bool
+bool
TextFileDocument::OnOpenDocument(const wxString& filename)
{
TextFileView *view = getView();
-
+
if (! view->getTextCtrl()->LoadFile(filename)) {
m_bBadFileOpen = true;
return false;
}
-
+
SetFilename (filename, true);
Modify (false);
UpdateAllViews();
return true;
}
-bool
+bool
TextFileDocument::IsModified(void) const
{
return false;
-
+
TextFileView *view = getView();
-
+
if (view)
return (wxDocument::IsModified() || view->getTextCtrl()->IsModified());
else
}
-TextFileView*
+TextFileView*
TextFileDocument::getView() const
-{
- return dynamic_cast<TextFileView*>(GetFirstView());
+{
+ return dynamic_cast<TextFileView*>(GetFirstView());
}
-wxTextCtrl*
+wxTextCtrl*
TextFileDocument::getTextCtrl()
-{
- return dynamic_cast<TextFileView*>(GetFirstView())->getTextCtrl();
+{
+ return dynamic_cast<TextFileView*>(GetFirstView())->getTextCtrl();
}
//////////////////////////////////////////////////////////////////////////
IMPLEMENT_DYNAMIC_CLASS(Graph3dFileDocument, wxDocument)
-Graph3dFileDocument::Graph3dFileDocument(void)
+Graph3dFileDocument::Graph3dFileDocument(void)
: m_bBadFileOpen(false), m_nVertices(0), m_pVertices(0), m_pNormals(0),m_nx(0),m_ny(0),m_array(0)
{
}
-Graph3dFileDocument::~Graph3dFileDocument()
+Graph3dFileDocument::~Graph3dFileDocument()
{
}
-bool
+bool
Graph3dFileDocument::OnSaveDocument(const wxString& filename)
{
Modify(false);
return true;
}
-bool
+bool
Graph3dFileDocument::OnOpenDocument(const wxString& filename)
{
SetFilename (filename, true);
return true;
}
-bool
+bool
Graph3dFileDocument::IsModified(void) const
{
return wxDocument::IsModified();
}
-Graph3dFileView*
+Graph3dFileView*
Graph3dFileDocument::getView() const
-{
- return dynamic_cast<Graph3dFileView*>(GetFirstView());
+{
+ return dynamic_cast<Graph3dFileView*>(GetFirstView());
}
bool
virtual bool IsModified () const;
virtual bool Revert ();
virtual void Modify (bool mod);
-
- ImageFileDocument ()
+
+ ImageFileDocument ()
: m_bBadFileOpen(false)
{
m_pImageFile = new ImageFile;
}
- virtual ~ImageFileDocument ()
+ virtual ~ImageFileDocument ()
{
delete m_pImageFile;
}
const ImageFile& getImageFile() const { return *m_pImageFile; }
ImageFile& getImageFile() { return *m_pImageFile; }
void setImageFile (ImageFile* pImageFile)
- {
+ {
delete m_pImageFile;
m_pImageFile = pImageFile;
}
DECLARE_DYNAMIC_CLASS(ProjectionFileDocument)
Projections* m_pProjectionFile;
bool m_bBadFileOpen;
-
+
public:
virtual bool OnSaveDocument (const wxString& filename);
virtual bool OnOpenDocument (const wxString& filename);
virtual bool IsModified () const;
virtual void Modify (bool mod);
-
- ProjectionFileDocument ()
+
+ ProjectionFileDocument ()
: m_bBadFileOpen(false)
{
m_pProjectionFile = new Projections;
virtual ~ProjectionFileDocument ();
- const Projections& getProjections () const { return *m_pProjectionFile; }
- Projections& getProjections () { return *m_pProjectionFile; }
+ const Projections& getProjections () const { return *m_pProjectionFile; }
+ Projections& getProjections () { return *m_pProjectionFile; }
void setProjections (Projections* pProjections)
{ delete m_pProjectionFile;
bool m_bBadFileOpen;
public:
- PhantomFileDocument ()
- : m_idPhantom(Phantom::PHM_INVALID), m_bBadFileOpen(false)
+ PhantomFileDocument ()
+ : m_idPhantom(Phantom::PHM_INVALID), m_bBadFileOpen(false)
{}
virtual ~PhantomFileDocument ();
const wxString& getPhantomName () const { return m_namePhantom; }
- const Phantom& getPhantom () const { return m_phantom; }
+ const Phantom& getPhantom () const { return m_phantom; }
- Phantom& getPhantom () { return m_phantom; }
+ Phantom& getPhantom () { return m_phantom; }
virtual bool OnOpenDocument (const wxString& filename);
virtual bool OnSaveDocument (const wxString& filename);
bool m_bBadFileOpen;
public:
- PlotFileDocument ()
+ PlotFileDocument ()
: m_bBadFileOpen(false)
{}
- virtual ~PlotFileDocument ()
- {}
+ virtual ~PlotFileDocument ()
+ {}
const wxString& getPlotName () const
- { return m_namePlot; }
+ { return m_namePlot; }
const PlotFile& getPlotFile () const
- { return m_plot; }
+ { return m_plot; }
PlotFile& getPlotFile ()
- { return m_plot; }
+ { return m_plot; }
virtual bool OnOpenDocument (const wxString& filename);
virtual bool OnSaveDocument (const wxString& filename);
bool m_bBadFileOpen;
public:
- TextFileDocument(void)
+ TextFileDocument(void)
: m_bBadFileOpen(false)
{}
public:
Graph3dFileDocument(void);
- virtual ~Graph3dFileDocument(void);
-
+ virtual ~Graph3dFileDocument(void);
+
virtual bool OnSaveDocument (const wxString& filename);
virtual bool OnOpenDocument (const wxString& filename);
virtual bool IsModified () const;
#include <sstream_subst>
#endif
-inline void
+inline void
Graph3dFileView::intensityToColor (double dIntensity, GLfloat* vecColor)
{
if (dIntensity < 0 || dIntensity > 1) {
vecColor[0] = vecColor[1] = vecColor[2] = 1;
return;
}
-
+
float fRange = dIntensity * 5;
int iRange = static_cast<int>(floor (fRange));
float fFrac = fRange - iRange;
-
+
// Rainbow: Purple->Blue->Cyan->Green->Yellow->Red = (1,0,1)-(0,0,1)-(0,1,1)-(0,1,0)-(1,1,0)-(1,0,0)
switch (iRange) {
case 0:
//*************************************************************************
template<class T>
-static void
+static void
CalculateVectorNormal (T fVert1[], T fVert2[], T fVert3[], T *fNormalX, T *fNormalY, T *fNormalZ)
{
T Qx = fVert2[0] - fVert1[0];
T Px = fVert3[0] - fVert1[0];
T Py = fVert3[1] - fVert1[1];
T Pz = fVert3[2] - fVert1[2];
-
+
*fNormalX = Py*Qz - Pz*Qy;
*fNormalY = Pz*Qx - Px*Qz;
*fNormalZ = Px*Qy - Py*Qx;
-}
+}
IMPLEMENT_DYNAMIC_CLASS(Graph3dFileView, wxView)
END_EVENT_TABLE()
Graph3dFileView::Graph3dFileView ()
- : m_pFileMenu(NULL), m_pViewMenu(NULL), m_pStatusBar(NULL), m_pCanvas(NULL),
- m_dXRotate(-180), m_dYRotate(-210), m_dZRotate(195),
- m_bDoubleBuffer(true), m_bSmooth(true), m_bWireframe(false),
+ : m_pFileMenu(NULL), m_pViewMenu(NULL), m_pStatusBar(NULL), m_pCanvas(NULL),
+ m_dXRotate(-180), m_dYRotate(-210), m_dZRotate(195),
+ m_bDoubleBuffer(true), m_bSmooth(true), m_bWireframe(false),
m_bLighting(false), m_bColor(true), m_bUseVertexArrays(false),
m_bColorScaleMinSet(false), m_bColorScaleMaxSet(false),
m_pFrame(NULL)
GetDocumentManager()->ActivateView(this, false, true);
}
-bool
+bool
Graph3dFileView::OnCreate (wxDocument *doc, long WXUNUSED(flags) )
{
m_pFrame = CreateChildFrame(doc, this);
m_pCanvas->SetClientSize (m_pCanvas->GetBestSize());
m_pFrame->SetTitle("Graph3dFileView");
- m_pCanvas->SetCurrent();
- InitGL();
+ m_pCanvas->SetCurrent();
+ InitGL();
m_pCanvas->SwapBuffers();
m_pViewMenu->Check (GRAPH3D_VIEW_COLOR, m_bColor);
m_pFrame->SetFocus();
m_pFrame->Show(true);
Activate(true);
-
+
return true;
-}
+}
-Graph3dFileCanvas*
+Graph3dFileCanvas*
Graph3dFileView::CreateCanvas (wxFrame* parent)
{
Graph3dFileCanvas* pCanvas = new Graph3dFileCanvas (this, parent, wxPoint(-1,-1), wxSize(-1,-1), 0);
-
+
pCanvas->SetBackgroundColour(*wxWHITE);
pCanvas->Clear();
-
+
return pCanvas;
}
{
if (! GetDocument())
return;
-
+
if (m_bSmooth) {
glShadeModel (GL_SMOOTH);
} else {
glShadeModel (GL_FLAT);
}
-
+
if (m_bLighting) {
glEnable (GL_LIGHTING);
} else {
glDisable (GL_LIGHTING);
}
-
+
unsigned int nx = GetDocument()->nx();
unsigned int ny = GetDocument()->ny();
glRotated (m_dYRotate, 1.0, 0.0, 0.0);
glTranslated (-static_cast<double>(nx - 1) / 2, 0.0, -static_cast<double>(ny - 1) / 2);
- InitMaterials();
+ InitMaterials();
if (m_bWireframe) {
if (! m_bColor)
glColor3f (1.0f, 1.0f, 1.0f);
glCallList (DISPLAYLIST_COLOR);
}
}
-
+
}
void
{
if (! GetDocument())
return;
-
+
unsigned int nx = GetDocument()->nx();
unsigned int ny = GetDocument()->ny();
const ImageFileArrayConst v = GetDocument()->getArray();
if (nx == 0 || ny == 0 || ! v)
return;
-
+
glNewList (DISPLAYLIST_COLOR, GL_COMPILE);
-
+
double dMin = m_dColorScaleMin;
double dIntensityScale = m_dColorScaleMax - m_dColorScaleMin;
double actOffset = m_dGraphMin;
for (ix = 0; ix < nx - 1; ix++, dXPos++) {
double dYPos = -dYOffset;
glBegin(GL_QUAD_STRIP);
- double p1[3], p2[3], p3[3], n1[3];
+ double p1[3], p2[3], p3[3], n1[3];
p1[0] = dXPos; p1[1] = actScale * (v[ix][0] + actOffset); p1[2] = dYPos;
- p2[0] = dXPos+1; p2[1] = actScale * (v[ix+1][0] + actOffset); p2[2] = dYPos;
+ p2[0] = dXPos+1; p2[1] = actScale * (v[ix+1][0] + actOffset); p2[2] = dYPos;
p3[0] = dXPos; p3[1] = actScale * (v[ix][1] + actOffset); p3[2] = dYPos + 1;
CalculateVectorNormal<double> (p1, p2, p3, &n1[0], &n1[1], &n1[2]);
intensityToColor (dIntensity1, vecColor);
glColor3fv (vecColor);
}
- glVertex3dv (p1); glNormal3dv (n1);
+ glVertex3dv (p1); glNormal3dv (n1);
if (m_bColor) {
intensityToColor (dIntensity2, vecColor);
glColor3fv (vecColor);
}
- glVertex3dv (p2); glNormal3dv (n1);
+ glVertex3dv (p2); glNormal3dv (n1);
double lastP[3];
- lastP[0] = ix; lastP[1] = actScale * (v[ix][0] + actOffset); lastP[2] = 0;
- for (unsigned int iy = 1; iy < ny - 1; iy++, dYPos++) {
+ lastP[0] = ix; lastP[1] = actScale * (v[ix][0] + actOffset); lastP[2] = 0;
+ for (unsigned int iy = 1; iy < ny - 1; iy++, dYPos++) {
p1[0] = dXPos; p1[1] = actScale * (v[ix][iy] + actOffset); p1[2] = dYPos;
p2[0] = dXPos+1; p2[1] = actScale * (v[ix+1][iy] + actOffset); p2[2] = dYPos;
CalculateVectorNormal (p1, p2, lastP, &n1[0], &n1[1], &n1[2]);
lastP[0] = p1[0]; lastP[1] = p1[1]; lastP[2] = p1[2];
if (m_bColor) {
- dIntensity1 = (v[ix][iy] - dMin) / dIntensityScale;
- dIntensity2 = (v[ix+1][iy] - dMin) / dIntensityScale;
- intensityToColor (dIntensity1, vecColor);
- glColor3fv (vecColor);
+ dIntensity1 = (v[ix][iy] - dMin) / dIntensityScale;
+ dIntensity2 = (v[ix+1][iy] - dMin) / dIntensityScale;
+ intensityToColor (dIntensity1, vecColor);
+ glColor3fv (vecColor);
}
- glVertex3dv (p1); glNormal3dv (n1);
+ glVertex3dv (p1); glNormal3dv (n1);
if (m_bColor) {
- intensityToColor (dIntensity2, vecColor);
- glColor3fv (vecColor);
+ intensityToColor (dIntensity2, vecColor);
+ glColor3fv (vecColor);
}
glVertex3dv (p2); glNormal3dv (n1);
- }
+ }
glEnd(); // QUAD_STRIP
}
glEndList();
for (ix = 0; ix < nx - 1; ix++, dXPos++) {
double dYPos = -dYOffset;
glBegin(GL_QUAD_STRIP);
- double p1[3], p2[3], p3[3], n1[3];
+ double p1[3], p2[3], p3[3], n1[3];
p1[0] = dXPos; p1[1] = actScale * (v[ix][0] + actOffset); p1[2] = dYPos;
- p2[0] = dXPos+1; p2[1] = actScale * (v[ix+1][0] + actOffset); p2[2] = dYPos;
+ p2[0] = dXPos+1; p2[1] = actScale * (v[ix+1][0] + actOffset); p2[2] = dYPos;
p3[0] = dXPos; p3[1] = actScale * (v[ix][1] + actOffset); p3[2] = dYPos + 1;
CalculateVectorNormal<double> (p1, p2, p3, &n1[0], &n1[1], &n1[2]);
- glVertex3dv (p1);
- glNormal3dv (n1);
- glVertex3dv (p2);
- glNormal3dv (n1);
+ glVertex3dv (p1);
+ glNormal3dv (n1);
+ glVertex3dv (p2);
+ glNormal3dv (n1);
double lastP[3];
- lastP[0] = ix; lastP[1] = actScale * (v[ix][0] + actOffset); lastP[2] = 0;
- for (unsigned int iy = 1; iy < ny - 1; iy++, dYPos++) {
+ lastP[0] = ix; lastP[1] = actScale * (v[ix][0] + actOffset); lastP[2] = 0;
+ for (unsigned int iy = 1; iy < ny - 1; iy++, dYPos++) {
p1[0] = dXPos; p1[1] = actScale * (v[ix][iy] + actOffset); p1[2] = dYPos;
p2[0] = dXPos+1; p2[1] = actScale * (v[ix+1][iy] + actOffset); p2[2] = dYPos;
CalculateVectorNormal (p1, p2, lastP, &n1[0], &n1[1], &n1[2]);
lastP[0] = p1[0]; lastP[1] = p1[1]; lastP[2] = p1[2];
- glVertex3dv (p1); glNormal3dv (n1);
- glVertex3dv (p2); glNormal3dv (n1);
- }
+ glVertex3dv (p1); glNormal3dv (n1);
+ glVertex3dv (p2); glNormal3dv (n1);
+ }
glEnd(); // QUAD_STRIP
}
glEndList();
{
std::ostringstream os;
*theApp->getLog() << ">>>>\n" << os.str().c_str() << "<<<<\n";
- wxMessageDialog dialogMsg (getFrameForChild(), os.str().c_str(),
- "Imagefile Properties", wxOK | wxICON_INFORMATION);
+ wxMessageDialog dialogMsg (getFrameForChild(), os.str().c_str(),
+ "Imagefile Properties", wxOK | wxICON_INFORMATION);
dialogMsg.ShowModal();
}
-void
+void
Graph3dFileView::OnDraw (wxDC* dc)
{
if (m_pCanvas) {
m_pCanvas->SetCurrent();
#ifdef DEBUG
- *theApp->getLog() << "Drawing 3d surface\n";
+ *theApp->getLog() << "Drawing 3d surface\n";
#endif
Draw();
m_pCanvas->SwapBuffers();
if (m_pStatusBar) {
std::ostringstream os;
- os << "Xangle=" << m_dXRotate << ", Yangle=" << m_dYRotate
+ os << "Xangle=" << m_dXRotate << ", Yangle=" << m_dYRotate
<< ", Zangle=" << m_dZRotate;
m_pStatusBar->SetStatusText (os.str().c_str());
}
}
-void
+void
Graph3dFileView::Draw ()
{
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
glPushMatrix();
- DrawSurface();
+ DrawSurface();
glPopMatrix();
glFlush();
}
return;
int nx = GetDocument()->nx();
int ny = GetDocument()->ny();
-
+
#if 1
static float position0[] = {nx/2, ny*2, -ny*2, 0.0f,};
static float ambient0[] = {.1f, .1f, .1f, 1.0f};
static float back_mat_diffuse[] = {1.0f, 1.0f, 1.0f, 1.0f};
static float lmodel_ambient[] = {1.0f, 1.0f, 1.0f, 1.0f};
static float lmodel_twoside[] = {GL_TRUE};
-
+
//glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
glHint(GL_LINE_SMOOTH, GL_DONT_CARE);
glEnable(GL_NORMALIZE);
-
+
glLightfv (GL_LIGHT0, GL_AMBIENT, ambient0);
glLightfv (GL_LIGHT0, GL_DIFFUSE, diffuse0);
glLightfv (GL_LIGHT0, GL_POSITION, position0);
glEnable (GL_LIGHT0);
-
+
glLightfv (GL_LIGHT1, GL_AMBIENT, ambient1);
glLightfv (GL_LIGHT1, GL_DIFFUSE, diffuse1);
glLightfv (GL_LIGHT1, GL_POSITION, position1);
glEnable (GL_LIGHT1);
-
+
glLightModelfv (GL_LIGHT_MODEL_AMBIENT, lmodel_ambient);
glLightModelfv (GL_LIGHT_MODEL_TWO_SIDE, lmodel_twoside);
-
+
glMaterialfv (GL_FRONT_AND_BACK, GL_SHININESS, front_mat_shininess);
glMaterialfv (GL_FRONT_AND_BACK, GL_SPECULAR, front_mat_specular);
glMaterialfv (GL_FRONT_AND_BACK, GL_DIFFUSE, front_mat_diffuse);
glMaterialfv (GL_BACK, GL_SHININESS, back_mat_shininess);
glMaterialfv (GL_BACK, GL_SPECULAR, back_mat_specular);
glMaterialfv (GL_BACK, GL_DIFFUSE, back_mat_diffuse);
-
+
glColorMaterial (GL_FRONT_AND_BACK, GL_DIFFUSE);
glColorMaterial (GL_FRONT_AND_BACK, GL_SPECULAR);
glEnable(GL_COLOR_MATERIAL);
#else
GLfloat impLPos[] = {1.0f, 1.0f, 1.0f, 0.0f};
-
+
GLfloat defaultLightAmb [] = {.2f, .2f, .2f, 1.0f};
GLfloat defaultLightDiff [] = {.2f, .2f, .2f, 1.0f};
GLfloat defaultLightSpec [] = { .3f, .3f, .3f, 1.0f};
-
+
GLfloat defaultGlobalAmb [] = {.3f, .3f, .3f, 1.0f};
GLfloat defaultGlobalDiff[] = {.3f, .3f, .3f, 1.0f};
-
+
GLfloat defaultMatShine[] = { 30.0f };
GLfloat defaultMatSpec[] = { .4f, .4f, .4f, 1.0f};
GLfloat defaultMatAmb[] = { .3f, .3f, .3f, 1.0f};
GLfloat defaultMatDiff[] = { .5f, .5f, .5f, 1.0f};
-
+
GLfloat brassMatAmb[] = { .33f, .22f, .03f, 1.0f};
GLfloat brassMatDiff[] = { .78f, .57f, .11f, 1.0f};
GLfloat brassMatSpec[] = { .99f, .91f, .81f, 1.0f};
GLfloat brassMatShine[] = { 27.8f };
-
+
GLfloat emeraldMatAmb[] = { .02f1, .1745f , .021f, 1.0f };
GLfloat emeraldMatDiff[] = { .075f, .6142f , .075f, 1.0f };
GLfloat emeraldMatSpec[] = { .633f, .7278f , .633f, 1.0f };
GLfloat emeraldMatShine[] = { 76.8f };
-
+
GLfloat slateMatAmb[] = { .02f, .02f , .02f, 1.0f };
GLfloat slateMatDiff[] = { .02f, .01f , .01f, 1.0f };
GLfloat slateMatSpec[] = { .4f, .4f , .4f , 1.0f };
GLfloat slateMatShine[] = { .768f };
-
+
// double opnX = nx, opnY = ny, opnZ = z;
// eyeX = 1; eyeY = 1, eyeZ = 1;
-
+
impLPos[0] = nx/2.; impLPos[1]= ny/2.; impLPos[2] = 0.;
//opnListNum = 1;
//impGraphicsFlag = IMP__3D;
-
+
// glutInitDisplayMode (GLUT_DOUBLE| GLUT_RGB | GLUT_DEPTH | GLUT_ACCUM);
// glutInitWindowSize (IMP_WIN_X, IMP_WIN_Y);
// glutInitWindowPosition (100, 100);
// glutCreateWindow ("- imp3D graphics -" );
-
+
glClearColor (0.0f, 0.0f, 0.0f, 0.0f);
-
+
glShadeModel (GL_SMOOTH);
glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
glHint(GL_LINE_SMOOTH, GL_DONT_CARE);
glEnable(GL_NORMALIZE);
-
-
+
+
glEnable(GL_DEPTH_TEST);
-
+
glLightfv(GL_LIGHT0, GL_AMBIENT, defaultLightAmb);
glLightfv(GL_LIGHT0, GL_DIFFUSE, defaultLightDiff);
glLightfv(GL_LIGHT0, GL_SPECULAR,defaultLightSpec);
-
+
glLightfv(GL_LIGHT1, GL_AMBIENT, defaultLightAmb);
glLightfv(GL_LIGHT1, GL_DIFFUSE, defaultLightDiff);
glLightfv(GL_LIGHT1, GL_SPECULAR,defaultLightSpec);
-
+
glLightfv(GL_LIGHT2, GL_AMBIENT , defaultLightAmb);
glLightfv(GL_LIGHT2, GL_DIFFUSE , defaultLightDiff);
glLightfv(GL_LIGHT2, GL_SPECULAR, defaultLightSpec);
-
+
glLightfv(GL_LIGHT0, GL_POSITION,impLPos);
glLightfv(GL_LIGHT1, GL_POSITION,impLPos);
glLightfv(GL_LIGHT2, GL_POSITION,impLPos);
-
+
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT , defaultMatAmb);
glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE , defaultMatDiff);
glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR , defaultMatSpec);
glMaterialfv(GL_FRONT_AND_BACK, GL_SHININESS, defaultMatShine);
-
+
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, defaultGlobalAmb);
-
+
glColorMaterial(GL_FRONT_AND_BACK, GL_DIFFUSE);
-
+
glEnable(GL_COLOR_MATERIAL);
-
+
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT1);
glEnable(GL_LIGHT2);
glEnable(GL_LIGHT0);
#endif
-
+
}
-void
+void
Graph3dFileView::InitGL ()
{
glClearColor (0.0f, 0.0f, 0.0f, 0.0f);
-
+
glDisable (GL_CULL_FACE);
glEnable (GL_DEPTH_TEST);
-
+
}
-void
+void
Graph3dFileView::OnUpdate (wxView *WXUNUSED(sender), wxObject *WXUNUSED(hint) )
{
if (! GetDocument())
return;
-
+
unsigned int nx = GetDocument()->nx();
unsigned int ny = GetDocument()->ny();
const ImageFileArrayConst v = GetDocument()->getArray();
if (! m_bColorScaleMinSet)
m_dColorScaleMin = min;
if (! m_bColorScaleMaxSet)
- m_dColorScaleMax = max;
+ m_dColorScaleMax = max;
}
double dRadius = maxValue<int> (nx, ny) * SQRT2 / 2;
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho (-dRadius, dRadius, -dRadius, dRadius, dRadius*5, -dRadius*5);
-
+
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
#if 0
up[0] = 0; up[1] = 1; up[2] = 0;
gluLookAt (eyep[0], eyep[1], eyep[2], lookp[0], lookp[1], lookp[2], up[0], up[1], up[2]);
#endif
-
+
CreateDisplayList();
if (m_pCanvas) {
- m_pCanvas->SwapBuffers();
+ m_pCanvas->SwapBuffers();
m_pCanvas->Refresh();
}
}
-bool
+bool
Graph3dFileView::OnClose (bool deleteWindow)
{
if (! GetDocument() || ! GetDocument()->Close())
return false;
-
+
Activate (false);
if (m_pCanvas) {
m_pCanvas->setView(NULL);
wxString s(theApp->GetAppName());
if (m_pFrame)
m_pFrame->SetTitle(s);
-
+
SetFrame(NULL);
-
+
if (deleteWindow) {
delete m_pFrame;
m_pFrame = NULL;
if (GetDocument() && GetDocument()->getBadFileOpen())
::wxYield(); // wxWindows bug workaround
}
-
+
return true;
}
-void
+void
Graph3dFileView::setInitialClientSize ()
{
if (m_pFrame && m_pCanvas) {
m_pFrame->Show (true);
m_pFrame->SetFocus();
}
-}
+}
-void
+void
Graph3dFileView::OnScaleAuto (wxCommandEvent& event)
{
#if 0
#endif
}
-void
+void
Graph3dFileView::OnScaleSet (wxCommandEvent& event)
{
if (! GetDocument())
return;
-
+
unsigned int nx = GetDocument()->nx();
unsigned int ny = GetDocument()->ny();
const ImageFileArrayConst v = GetDocument()->getArray();
dMin = m_dColorScaleMin;
if (m_bColorScaleMaxSet)
dMax = m_dColorScaleMax;
-
+
DialogGetMinMax dialogMinMax (getFrameForChild(), "Set Color Scale Minimum & Maximum", dMin, dMax);
int retVal = dialogMinMax.ShowModal();
if (retVal == wxID_OK) {
}
}
-void
+void
Graph3dFileView::OnScaleFull (wxCommandEvent& event)
{
if (m_bColorScaleMinSet || m_bColorScaleMaxSet) {
wxDocChildFrame* subframe = new wxDocChildFrame (doc, view, theApp->getMainFrame(), -1, "Graph3dFile Frame", wxPoint(-1,-1), wxSize(-1,-1), wxDEFAULT_FRAME_STYLE);
#endif
theApp->setIconForFrame (subframe);
-
+
// status bar text not showing tested with enlightenment. disabling for now...
-#if 0
+#if 0
m_pStatusBar = new wxStatusBar (subframe, -1);
subframe->SetStatusBar (m_pStatusBar);
m_pStatusBar->Show(true);
#endif
m_pFileMenu = new wxMenu;
-
+
m_pFileMenu->Append(MAINMENU_FILE_CREATE_PHANTOM, "Cr&eate Phantom...\tCtrl-P");
m_pFileMenu->Append(MAINMENU_FILE_CREATE_FILTER, "Create &Filter...\tCtrl-F");
m_pFileMenu->Append(wxID_OPEN, "&Open...\tCtrl-O");
m_pFileMenu->Append(wxID_CLOSE, "&Close\tCtrl-W");
-
+
m_pFileMenu->AppendSeparator();
m_pFileMenu->Append(IFMENU_FILE_PROPERTIES, "P&roperties");
-
+
m_pFileMenu->AppendSeparator();
m_pFileMenu->Append(wxID_PRINT, "&Print...");
m_pFileMenu->Append(wxID_PRINT_SETUP, "Print &Setup...");
GetDocumentManager()->FileHistoryAddFilesToMenu(m_pFileMenu);
GetDocumentManager()->FileHistoryUseMenu(m_pFileMenu);
-
+
m_pViewMenu = new wxMenu;
m_pViewMenu->Append(GRAPH3D_VIEW_WIREFRAME, "Wi&reframe\tCtrl-R", "", true);
m_pViewMenu->Append(GRAPH3D_VIEW_SMOOTH, "S&mooth\tCtrl-M", "", true);
m_pViewMenu->Append(GRAPH3D_VIEW_SCALE_MINMAX, "Color Scale S&et Min/Max...\tCtrl-E");
m_pViewMenu->Append(GRAPH3D_VIEW_SCALE_AUTO, "Color Scale &Auto...\tCtrl-A");
m_pViewMenu->Append(GRAPH3D_VIEW_SCALE_FULL, "Color F&ull Scale\tCtrl-U");
-
-
+
+
wxMenu *help_menu = new wxMenu;
help_menu->Append(MAINMENU_HELP_CONTENTS, "&Contents\tF1");
help_menu->Append(MAINMENU_HELP_ABOUT, "&About");
-
+
wxMenuBar *menu_bar = new wxMenuBar;
-
+
menu_bar->Append(m_pFileMenu, "&File");
menu_bar->Append(m_pViewMenu, "&View");
menu_bar->Append(help_menu, "&Help");
-
+
subframe->SetMenuBar(menu_bar);
-
+
subframe->Centre(wxBOTH);
wxAcceleratorEntry accelEntries[7];
-Graph3dFileCanvas::Graph3dFileCanvas (Graph3dFileView* view, wxWindow *parent, const wxPoint& pos,
+Graph3dFileCanvas::Graph3dFileCanvas (Graph3dFileView* view, wxWindow *parent, const wxPoint& pos,
const wxSize& size, long style)
: wxGLCanvas (parent, -1, pos, size, style), m_pView(view)
{
// parent->Show (true);
#if 0
- // Make sure server supports the vertex array extension
+ // Make sure server supports the vertex array extension
char* extensions = (char *) glGetString( GL_EXTENSIONS );
if (!extensions || !strstr( extensions, "GL_EXT_vertex_array" )) {
m_pView->m_bUseVertexArrays = GL_FALSE;
{
}
-void
+void
Graph3dFileCanvas::OnPaint (wxPaintEvent& event)
{
wxPaintDC dc(this);
return wxSize (400,400);
}
-void
+void
Graph3dFileCanvas::OnSize (wxSizeEvent& event)
{
#ifndef __WXMOTIF__
// if (!GetContext()) return;
#endif
-
+
int width, height;
GetClientSize (&width, &height);
Reshape (width, height);
}
-void
+void
Graph3dFileCanvas::OnChar(wxKeyEvent& event)
{
if (! m_pView)
return;
-
+
wxCommandEvent dummyEvent;
switch (event.KeyCode()) {
case WXK_LEFT:
- m_pView->m_dZRotate += 15.0;
+ m_pView->m_dZRotate += 15.0;
Refresh (false);
break;
case WXK_RIGHT:
}
-void
+void
Graph3dFileCanvas::OnMouseEvent(wxMouseEvent& event)
{
static int dragging = 0;
static float last_x, last_y;
-
+
if (! m_pView)
return;
-
+
if(event.LeftIsDown()) {
if(! dragging) {
dragging = 1;
dragging = 0;
}
-void
+void
Graph3dFileCanvas::OnEraseBackground(wxEraseEvent& event)
{
// Do nothing: avoid flashing.
class Graph3dFileCanvas;
-class Graph3dFileView : public wxView
+class Graph3dFileView : public wxView
{
friend class Graph3dFileCanvas;
private:
- DECLARE_DYNAMIC_CLASS(Graph3dFileView)
+ DECLARE_DYNAMIC_CLASS(Graph3dFileView)
DECLARE_EVENT_TABLE()
-
+
wxMenu* m_pFileMenu;
wxMenu *m_pViewMenu;
wxStatusBar* m_pStatusBar;
wxDocChildFrame* CreateChildFrame(wxDocument *doc, wxView *view);
#endif
- wxWindow* getFrameForChild()
+ wxWindow* getFrameForChild()
#if CTSIM_MDI
{ return theApp->getMainFrame(); }
#else
void OnScaleSet (wxCommandEvent& event);
void OnScaleAuto (wxCommandEvent& event);
void OnScaleFull (wxCommandEvent& event);
-
+
void setInitialClientSize();
#if CTSIM_MDI
wxDocChildFrame* getFrame() { return m_pFrame; }
#endif
Graph3dFileCanvas* getCanvas() { return m_pCanvas; }
- Graph3dFileDocument* GetDocument()
+ Graph3dFileDocument* GetDocument()
{ return dynamic_cast<Graph3dFileDocument*>(wxView::GetDocument()); }
};
ProjectorSupervisorThread::ProjectorSupervisorThread (PhantomFileView* pProjView, int iNDet, int iNView, int iOffsetView,
const char* pszGeometry, int iNSample, double dRotation, double dFocalLength, double dCenterDetectorLength,
double dViewRatio, double dScanRatio, const char* const pszLabel)
-: SupervisorThread(), m_pPhantomView(pProjView), m_iNDet(iNDet), m_iNView(iNView), m_iOffsetView(iOffsetView), m_strGeometry(pszGeometry),
+: SupervisorThread(), m_pPhantomView(pProjView), m_iNDet(iNDet), m_iNView(iNView), m_iOffsetView(iOffsetView), m_strGeometry(pszGeometry),
m_iNSample(iNSample), m_dRotation(dRotation), m_dFocalLength(dFocalLength), m_dCenterDetectorLength(dCenterDetectorLength),
m_dViewRatio(dViewRatio), m_dScanRatio(dScanRatio), m_strLabel(pszLabel)
{
wxThread::ExitCode
ProjectorSupervisorThread::Entry()
{
- ProjectorSupervisor projSupervisor (this, m_pPhantomView, m_iNDet, m_iNView, m_iOffsetView,
+ ProjectorSupervisor projSupervisor (this, m_pPhantomView, m_iNDet, m_iNView, m_iOffsetView,
m_strGeometry.c_str(), m_iNSample, m_dRotation, m_dFocalLength, m_dCenterDetectorLength, m_dViewRatio, m_dScanRatio, m_strLabel.c_str());
projSupervisor.start();
}
if (! projSupervisor.cancelled())
- projSupervisor.onDone();
+ projSupervisor.onDone();
projSupervisor.deleteWorkers();
return static_cast<wxThread::ExitCode>(0);
//
/////////////////////////////////////////////////////////////////////
-ProjectorSupervisor::ProjectorSupervisor (SupervisorThread* pThread, PhantomFileView* pPhantomView, int iNDet, int iNView, int iOffsetView,
+ProjectorSupervisor::ProjectorSupervisor (SupervisorThread* pThread, PhantomFileView* pPhantomView, int iNDet, int iNView, int iOffsetView,
const char* pszGeometry, int iNSample, double dRotation, double dFocalLength, double dCenterDetectorLength,
double dViewRatio, double dScanRatio, const char* const pszLabel)
: BackgroundSupervisor (pThread, pPhantomView->GetFrame(), pPhantomView->GetDocument(), "Projecting", iNView),
- m_pPhantomView(pPhantomView), m_pPhantomDoc(pPhantomView->GetDocument()),
- m_iNDet(iNDet), m_iNView(iNView), m_iOffsetView(iOffsetView), m_pszGeometry(pszGeometry), m_iNSample(iNSample),
- m_dRotation(dRotation), m_dFocalLength(dFocalLength), m_dCenterDetectorLength(dCenterDetectorLength),
+ m_pPhantomView(pPhantomView), m_pPhantomDoc(pPhantomView->GetDocument()),
+ m_iNDet(iNDet), m_iNView(iNView), m_iOffsetView(iOffsetView), m_pszGeometry(pszGeometry), m_iNSample(iNSample),
+ m_dRotation(dRotation), m_dFocalLength(dFocalLength), m_dCenterDetectorLength(dCenterDetectorLength),
m_dViewRatio(dViewRatio), m_dScanRatio(dScanRatio), m_pszLabel(pszLabel)
{
m_pScanner = new Scanner (m_pPhantomDoc->getPhantom(), m_pszGeometry, m_iNDet,
m_vecpChildProjections.reserve (getNumWorkers());
for (int iThread = 0; iThread < getNumWorkers(); iThread++) {
- m_vecpChildProjections[iThread] = new Projections (*m_pScanner);
+ m_vecpChildProjections[iThread] = new Projections (*m_pScanner);
}
{
ProjectorWorker* pThread = new ProjectorWorker (this, iThread, iStartUnit, iNumUnits);
m_vecpChildProjections[iThread]->setNView (iNumUnits);
- pThread->SetParameters (m_pPhantomView, m_vecpChildProjections[iThread], m_pScanner, m_iNDet, m_iNView, m_iOffsetView,
+ pThread->SetParameters (m_pPhantomView, m_vecpChildProjections[iThread], m_pScanner, m_iNDet, m_iNView, m_iOffsetView,
m_pszGeometry, m_iNSample, m_dRotation, m_dFocalLength, m_dCenterDetectorLength, m_dViewRatio, m_dScanRatio);
return pThread;
wxCommandEvent newProjEvent (wxEVT_COMMAND_MENU_SELECTED, NEW_PROJECTIONFILE_EVENT);
newProjEvent.SetClientData (pProjections);
wxPostEvent (theApp->getMainFrame(), newProjEvent);
-
+
setDone();
}
void
ProjectorWorker::SetParameters (PhantomFileView* pPhantomView, Projections* pProjections, Scanner* pScanner,
- int iNDet, int iView, int iOffsetView,
+ int iNDet, int iView, int iOffsetView,
const char* pszGeometry, int iNSample, double dRotation, double dFocalLength, double dCenterDetectorLength,
double dViewRatio, double dScanRatio)
{
std::string failMsg;
if (bFail) {
failMsg = "Unable to make Projector: ";
- failMsg += m_pScanner->failMessage().c_str();
+ failMsg += m_pScanner->failMessage().c_str();
wxCommandEvent event( wxEVT_COMMAND_MENU_SELECTED, MAINMENU_LOG_EVENT );
event.SetString( failMsg.c_str() );
wxPostEvent( theApp->getMainFrame(), event );
#ifdef DEBUG
if (theApp->getVerboseLogging()) {
wxString msg;
- msg.Printf("Worker thread: Received destroy message at work unit #%d\n", iUnit);
+ msg.Printf("Worker thread: Received destroy message at work unit #%d\n", iUnit);
wxCommandEvent event( wxEVT_COMMAND_MENU_SELECTED, MAINMENU_LOG_EVENT );
event.SetString( msg );
- wxPostEvent( theApp->getMainFrame(), event );
+ wxPostEvent( theApp->getMainFrame(), event );
}
#endif
break;
}
- m_pScanner->collectProjections (*m_pProjections, rPhantom, iUnit + m_iStartUnit, 1,
+ m_pScanner->collectProjections (*m_pProjections, rPhantom, iUnit + m_iStartUnit, 1,
m_iOffsetView, iUnit, Trace::TRACE_NONE);
m_pSupervisor->onWorkerUnitTick();
}
const std::string m_strLabel;
public:
- ProjectorSupervisorThread(PhantomFileView* pProjView, int iNDet, int iNView, int iOffsetView,
+ ProjectorSupervisorThread(PhantomFileView* pProjView, int iNDet, int iNView, int iOffsetView,
const char* pszGeometry, int iNSample, double dRotation, double dFocalLength, double dCenterDetectorLength,
double dViewRatio, double dScanRatio, const char* const pszLabel);
PhantomFileView* m_pPhantomView;
PhantomFileDocument* m_pPhantomDoc;
Scanner* m_pScanner;
-
+
const int m_iNDet;
const int m_iNView;
const int m_iOffsetView;
public:
- ProjectorWorker (ProjectorSupervisor* pSupervisor, int iThread, int iStartView, int iNumViews)
+ ProjectorWorker (ProjectorSupervisor* pSupervisor, int iThread, int iStartView, int iNumViews)
: BackgroundWorkerThread (pSupervisor, iThread, iStartView, iNumViews)
{}
-
- void SetParameters (PhantomFileView* pPhantomFile, Projections* pProjections, Scanner* pScanner,
+
+ void SetParameters (PhantomFileView* pPhantomFile, Projections* pProjections, Scanner* pScanner,
int iNDet, int iView, int iOffsetView,
const char* const pszGeometry, int iNSample, double dRotation, double dFocalLength, double dCenterDetectorLength,
double dViewRatio, double dScanRatio);
#endif // HAVE_WXTHREADS
#endif // _THREADPROJ_H_
-
+
//
/////////////////////////////////////////////////////////////////////
-RasterizerSupervisorThread::RasterizerSupervisorThread (PhantomFileView* pProjView, int iNX, int iNY,
+RasterizerSupervisorThread::RasterizerSupervisorThread (PhantomFileView* pProjView, int iNX, int iNY,
int iNSample, double dViewRatio, const char* const pszLabel)
: SupervisorThread(), m_pPhantomView(pProjView), m_iNX(iNX), m_iNY(iNY), m_iNSample(iNSample), m_dViewRatio(dViewRatio), m_strLabel(pszLabel)
{
RasterizerSupervisorThread::Entry()
{
RasterizerSupervisor rasterSupervisor (this, m_pPhantomView, m_iNX, m_iNY, m_iNSample, m_dViewRatio, m_strLabel.c_str());
-
+
rasterSupervisor.start();
-
+
while (! rasterSupervisor.workersDone() && ! rasterSupervisor.fail() && ! rasterSupervisor.cancelled()) {
Sleep(100);
}
-
+
if (rasterSupervisor.fail())
{
wxString msg ("Error starting Rasterizer supervisor: ");
eventLog.SetString( msg );
wxPostEvent( theApp->getMainFrame(), eventLog ); // send log event
}
-
+
if (! rasterSupervisor.cancelled())
rasterSupervisor.onDone();
rasterSupervisor.deleteWorkers();
-
+
return static_cast<wxThread::ExitCode>(0);
}
//
/////////////////////////////////////////////////////////////////////
-RasterizerSupervisor::RasterizerSupervisor (SupervisorThread* pThread, PhantomFileView* pPhantomView, int iNX, int iNY,
+RasterizerSupervisor::RasterizerSupervisor (SupervisorThread* pThread, PhantomFileView* pPhantomView, int iNX, int iNY,
int iNSample, double dViewRatio, const char* const pszLabel)
: BackgroundSupervisor (pThread, pPhantomView->GetFrame(), pPhantomView->GetDocument(), "Rasterizing", iNX),
- m_pPhantomView(pPhantomView), m_pPhantomDoc(pPhantomView->GetDocument()),
+ m_pPhantomView(pPhantomView), m_pPhantomDoc(pPhantomView->GetDocument()),
m_iNX(iNX), m_iNY(iNY), m_iNSample(iNSample), m_dViewRatio(dViewRatio), m_pszLabel(pszLabel)
{
m_vecpChildImageFiles.reserve (getNumWorkers());
RasterizerWorker* pThread = new RasterizerWorker (this, iThread, iStartUnit, iNumUnits);
m_vecpChildImageFiles[iThread]->setArraySize (iNumUnits, m_iNY);
pThread->SetParameters (m_pPhantomView, m_vecpChildImageFiles[iThread], m_iNX, m_iNY, m_iNSample, m_dViewRatio);
-
+
return pThread;
}
{
wxCriticalSection doneSection;
wxCriticalSectionLocker critsect (doneSection);
-
+
ImageFile* pImageFile = getImageFile();
pImageFile->labelAdd (m_pszLabel, getTimerEnd());
-
+
wxCommandEvent eventLog (wxEVT_COMMAND_MENU_SELECTED, MAINMENU_LOG_EVENT );
wxString msg (m_pszLabel);
msg += "\n";
eventLog.SetString( msg );
wxPostEvent( theApp->getMainFrame(), eventLog ); // send log event
-
+
wxCommandEvent newImageEvent (wxEVT_COMMAND_MENU_SELECTED, NEW_IMAGEFILE_EVENT);
newImageEvent.SetClientData (pImageFile);
wxPostEvent (theApp->getMainFrame(), newImageEvent);
-
+
setDone();
}
RasterizerSupervisor::getImageFile()
{
ImageFile* pImageFile = new ImageFile (m_iNX, m_iNY);
-
+
size_t iColSize = sizeof(ImageFileValue) * m_iNY;
-
+
ImageFileArray globalArray = pImageFile->getArray();
int iGlobalCol = 0;
for (int iw = 0; iw < getNumWorkers(); iw++) {
#ifdef DEBUG
if (theApp->getVerboseLogging()) {
wxString msg;
- msg.Printf("Worker thread: Received destroy message at work unit #%d\n", iUnit);
+ msg.Printf("Worker thread: Received destroy message at work unit #%d\n", iUnit);
wxCommandEvent event( wxEVT_COMMAND_MENU_SELECTED, MAINMENU_LOG_EVENT );
event.SetString( msg );
- wxPostEvent( theApp->getMainFrame(), event );
+ wxPostEvent( theApp->getMainFrame(), event );
}
#endif
break;
rPhantom.convertToImagefile (*m_pImageFile, m_iNX, m_dViewRatio, m_iNSample, Trace::TRACE_NONE, iUnit + m_iStartUnit, 1, iUnit);
m_pSupervisor->onWorkerUnitTick();
}
-
+
m_pSupervisor->onWorkerDone (m_iThread);
-
+
while (! TestDestroy())
Sleep(100);
-
+
return static_cast<wxThread::ExitCode>(0);
}
PhantomFileView* m_pPhantomView;
std::vector<ImageFile*> m_vecpChildImageFiles;
PhantomFileDocument* m_pPhantomDoc;
-
+
const int m_iNX;
const int m_iNY;
const int m_iNSample;
public:
- RasterizerSupervisor (SupervisorThread* pThread, PhantomFileView* pProjView, int iNX, int iNY,
+ RasterizerSupervisor (SupervisorThread* pThread, PhantomFileView* pProjView, int iNX, int iNY,
int iNSample, double dViewRatio, const char* const pszLabel);
virtual BackgroundWorkerThread* createWorker (int iThread, int iStartUnit, int iNumUnits);
public:
- RasterizerWorker (RasterizerSupervisor* pSupervisor, int iThread, int iStartView, int iNumViews)
+ RasterizerWorker (RasterizerSupervisor* pSupervisor, int iThread, int iStartView, int iNumViews)
: BackgroundWorkerThread (pSupervisor, iThread, iStartView, iNumViews)
{}
-
- void SetParameters (PhantomFileView* pPhantomFile, ImageFile* pImageFile, int iNX, int iY,
+
+ void SetParameters (PhantomFileView* pPhantomFile, ImageFile* pImageFile, int iNX, int iY,
int iNSample, double dViewRatio);
virtual wxThread::ExitCode Entry(); // thread execution starts here
#endif // HAVE_WXTHREADS
#endif // _THREADRASTER_H_
-
+
//
/////////////////////////////////////////////////////////////////////
-ReconstructorSupervisorThread::ReconstructorSupervisorThread (ProjectionFileView* pProjView, int iNX, int iNY,
- const char* pszFilterName, double dFilterParam, const char* pszFilterMethod, int iZeropad,
- const char* pszFilterGenerationName, const char* pszInterpName, int iInterpParam,
+ReconstructorSupervisorThread::ReconstructorSupervisorThread (ProjectionFileView* pProjView, int iNX, int iNY,
+ const char* pszFilterName, double dFilterParam, const char* pszFilterMethod, int iZeropad,
+ const char* pszFilterGenerationName, const char* pszInterpName, int iInterpParam,
const char* pszBackprojectName, const char* const pszLabel, ReconstructionROI* pROI, bool bRebinToParallel)
-: SupervisorThread(), m_pProjView(pProjView), m_iNX(iNX), m_iNY(iNY), m_strFilterName(pszFilterName), m_dFilterParam(dFilterParam),
- m_strFilterMethod(pszFilterMethod), m_iZeropad(iZeropad), m_strFilterGenerationName(pszFilterGenerationName),
- m_strInterpName(pszInterpName), m_iInterpParam(iInterpParam), m_strBackprojectName(pszBackprojectName),
+: SupervisorThread(), m_pProjView(pProjView), m_iNX(iNX), m_iNY(iNY), m_strFilterName(pszFilterName), m_dFilterParam(dFilterParam),
+ m_strFilterMethod(pszFilterMethod), m_iZeropad(iZeropad), m_strFilterGenerationName(pszFilterGenerationName),
+ m_strInterpName(pszInterpName), m_iInterpParam(iInterpParam), m_strBackprojectName(pszBackprojectName),
m_strLabel(pszLabel), m_reconROI(*pROI), m_bRebinToParallel(bRebinToParallel)
{
}
if (m_bRebinToParallel)
pProj = pProj->interpolateToParallel();
- ReconstructorSupervisor reconSupervisor (this, pProj, m_pProjView, m_iNX, m_iNY,
- m_strFilterName.c_str(), m_dFilterParam, m_strFilterMethod.c_str(), m_iZeropad, m_strFilterGenerationName.c_str(),
+ ReconstructorSupervisor reconSupervisor (this, pProj, m_pProjView, m_iNX, m_iNY,
+ m_strFilterName.c_str(), m_dFilterParam, m_strFilterMethod.c_str(), m_iZeropad, m_strFilterGenerationName.c_str(),
m_strInterpName.c_str(), m_iInterpParam, m_strBackprojectName.c_str(), m_strLabel.c_str(), &m_reconROI);
reconSupervisor.start();
wxPostEvent( theApp->getMainFrame(), eventLog ); // send log event
}
if (! reconSupervisor.cancelled())
- reconSupervisor.onDone();
+ reconSupervisor.onDone();
reconSupervisor.deleteWorkers();
if (m_bRebinToParallel)
/////////////////////////////////////////////////////////////////////
ReconstructorSupervisor::ReconstructorSupervisor (SupervisorThread* pThread, Projections* pProj,
- ProjectionFileView* pProjView, int iImageNX, int iImageNY, const char* pszFilterName, double dFilterParam,
- const char* pszFilterMethod, int iZeropad, const char* pszFilterGenerationName,
- const char* pszInterpName, int iInterpParam, const char* pszBackprojectName, const char* const pszLabel,
+ ProjectionFileView* pProjView, int iImageNX, int iImageNY, const char* pszFilterName, double dFilterParam,
+ const char* pszFilterMethod, int iZeropad, const char* pszFilterGenerationName,
+ const char* pszInterpName, int iInterpParam, const char* pszBackprojectName, const char* const pszLabel,
ReconstructionROI* pROI)
: BackgroundSupervisor (pThread, pProjView->GetFrame(), pProjView->GetDocument(), "Reconstructing", pProjView->GetDocument()->getProjections().nView()),
- m_pProj(pProj), m_pProjView(pProjView), m_pProjDoc(pProjView->GetDocument()),
- m_iImageNX(iImageNX), m_iImageNY(iImageNY),
+ m_pProj(pProj), m_pProjView(pProjView), m_pProjDoc(pProjView->GetDocument()),
+ m_iImageNX(iImageNX), m_iImageNY(iImageNY),
m_pszFilterName(pszFilterName), m_dFilterParam(dFilterParam), m_pszFilterMethod(pszFilterMethod),
m_iZeropad(iZeropad), m_pszFilterGenerationName(pszFilterGenerationName), m_pszInterpName(pszInterpName),
m_iInterpParam(iInterpParam), m_pszBackprojectName(pszBackprojectName), m_pszLabel(pszLabel),
{
m_vecpChildImageFile.reserve (getNumWorkers());
for (int iThread = 0; iThread < getNumWorkers(); iThread++) {
- m_vecpChildImageFile[iThread] = new ImageFile (m_iImageNX, m_iImageNY);
+ m_vecpChildImageFile[iThread] = new ImageFile (m_iImageNX, m_iImageNY);
}
}
ReconstructorSupervisor::createWorker (int iThread, int iStartUnit, int iNumUnits)
{
ReconstructorWorker* pThread = new ReconstructorWorker (this, iThread, iStartUnit, iNumUnits);
- pThread->SetParameters (m_pProj, m_pProjView, m_vecpChildImageFile[iThread], m_pszFilterName,
+ pThread->SetParameters (m_pProj, m_pProjView, m_vecpChildImageFile[iThread], m_pszFilterName,
m_dFilterParam, m_pszFilterMethod, m_iZeropad, m_pszFilterGenerationName, m_pszInterpName,
m_iInterpParam, m_pszBackprojectName, m_pReconROI);
ImageFile* pImageFile = new ImageFile (m_iImageNX, m_iImageNY);
pImageFile->arrayDataClear();
ImageFileArray pArray = pImageFile->getArray();
-
+
int i;
for (i = 0; i < getNumWorkers(); i++) {
ImageFileArrayConst pChildArray = m_vecpChildImageFile[i]->getArray();
for (int iy = 0; iy < m_iImageNY; iy++)
pArray[ix][iy] += pChildArray[ix][iy];
}
-
+
return (pImageFile);
}
/////////////////////////////////////////////////////////////////////
void
-ReconstructorWorker::SetParameters (const Projections* pProj, ProjectionFileView* pProjView, ImageFile* pImageFile,
+ReconstructorWorker::SetParameters (const Projections* pProj, ProjectionFileView* pProjView, ImageFile* pImageFile,
const char* pszFilterName, double dFilterParam, const char* pszFilterMethod, int iZeropad,
- const char* pszFilterGenerationName, const char* pszInterpName, int iInterpParam,
+ const char* pszFilterGenerationName, const char* pszInterpName, int iInterpParam,
const char* pszBackprojectName, ReconstructionROI* pROI)
{
m_pProj = pProj;
m_pProjView = pProjView;
m_pImageFile = pImageFile;
m_pszFilterName = pszFilterName;
- m_dFilterParam = dFilterParam;
+ m_dFilterParam = dFilterParam;
m_pszFilterMethod = pszFilterMethod;
m_iZeropad = iZeropad;
m_pszFilterGenerationName = pszFilterGenerationName;
wxThread::ExitCode
ReconstructorWorker::Entry ()
{
- Reconstructor* pReconstructor = new Reconstructor (*m_pProj, *m_pImageFile, m_pszFilterName,
- m_dFilterParam, m_pszFilterMethod, m_iZeropad, m_pszFilterGenerationName, m_pszInterpName,
+ Reconstructor* pReconstructor = new Reconstructor (*m_pProj, *m_pImageFile, m_pszFilterName,
+ m_dFilterParam, m_pszFilterMethod, m_iZeropad, m_pszFilterGenerationName, m_pszInterpName,
m_iInterpParam, m_pszBackprojectName, Trace::TRACE_NONE, m_pReconROI, false);
bool bFail = pReconstructor->fail();
std::string failMsg;
if (bFail) {
failMsg = "Unable to make reconstructor: ";
- failMsg += pReconstructor->failMessage().c_str();
+ failMsg += pReconstructor->failMessage().c_str();
wxCommandEvent event( wxEVT_COMMAND_MENU_SELECTED, MAINMENU_LOG_EVENT );
event.SetString( failMsg.c_str() );
wxPostEvent( theApp->getMainFrame(), event );
#ifdef DEBUG
if (theApp->getVerboseLogging()) {
wxString msg;
- msg.Printf("Worker thread: Received destroy message at work unit #%d\n", iUnit);
+ msg.Printf("Worker thread: Received destroy message at work unit #%d\n", iUnit);
wxCommandEvent event( wxEVT_COMMAND_MENU_SELECTED, MAINMENU_LOG_EVENT );
event.SetString( msg );
- wxPostEvent( theApp->getMainFrame(), event );
+ wxPostEvent( theApp->getMainFrame(), event );
}
#endif
break;
delete pReconstructor;
if (bFail) {
- m_pSupervisor->onWorkerFail (m_iThread, failMsg);
+ m_pSupervisor->onWorkerFail (m_iThread, failMsg);
} else {
- m_pSupervisor->onWorkerDone (m_iThread);
+ m_pSupervisor->onWorkerDone (m_iThread);
}
while (! TestDestroy())
const bool m_bRebinToParallel;
public:
- ReconstructorSupervisorThread(ProjectionFileView* pProjView, int iNX, int iNY, const char* pszFilterName,
- double dFilterParam, const char* pszFilterMethod, int iZeropad, const char* pszFilterGenerationName,
+ ReconstructorSupervisorThread(ProjectionFileView* pProjView, int iNX, int iNY, const char* pszFilterName,
+ double dFilterParam, const char* pszFilterMethod, int iZeropad, const char* pszFilterGenerationName,
const char* pszInterpName, int iInterpParam, const char* pszBackprojectName, const char* const pszLabel,
ReconstructionROI* pROI, bool bRebinToParallel);
const Projections* m_pProj;
ProjectionFileView* m_pProjView;
ProjectionFileDocument* m_pProjDoc;
-
+
const int m_iImageNX;
const int m_iImageNY;
ReconstructionROI* m_pReconROI;
public:
- ReconstructorSupervisor (SupervisorThread* pMyThread, Projections* pProj, ProjectionFileView* pProjView,
- int iNX, int iNY, const char* pszFilterName, double dFilterParam, const char* pszFilterMethod, int iZeropad,
- const char* pszFilterGenerationName, const char* pszInterpName, int iInterpParam,
+ ReconstructorSupervisor (SupervisorThread* pMyThread, Projections* pProj, ProjectionFileView* pProjView,
+ int iNX, int iNY, const char* pszFilterName, double dFilterParam, const char* pszFilterMethod, int iZeropad,
+ const char* pszFilterGenerationName, const char* pszInterpName, int iInterpParam,
const char* pszBackprojectName, const char* const pszLabel, ReconstructionROI* pReconROI);
virtual BackgroundWorkerThread* createWorker (int iThread, int iStartUnit, int iNumUnits);
ReconstructionROI* m_pReconROI;
public:
- ReconstructorWorker (ReconstructorSupervisor* pSupervisor, int iThread, int iStartView, int iNumViews)
+ ReconstructorWorker (ReconstructorSupervisor* pSupervisor, int iThread, int iStartView, int iNumViews)
: BackgroundWorkerThread (pSupervisor, iThread, iStartView, iNumViews)
{}
-
- void SetParameters (const Projections* pProj, ProjectionFileView* pProjFile, ImageFile* pImageFile,
- const char* const pszFilterName, double dFilterParam, const char* const pszFilterMethod,
+
+ void SetParameters (const Projections* pProj, ProjectionFileView* pProjFile, ImageFile* pImageFile,
+ const char* const pszFilterName, double dFilterParam, const char* const pszFilterMethod,
int iZeropad, const char* const pszFilterGenerationName, const char* const pszInterpName, int iInterpParam,
const char* pszBackprojectName, ReconstructionROI* pROI);
#endif // HAVE_WXTHREADS
#endif // _THREADRECON_H_
-
+
ImageFileCanvas::~ImageFileCanvas()
{}
-void
+void
ImageFileCanvas::OnDraw(wxDC& dc)
{
if (m_pView)
m_pView->OnDraw(& dc);
}
-void
+void
ImageFileCanvas::DrawRubberBandCursor (wxDC& dc, int x, int y)
{
const ImageFile& rIF = m_pView->GetDocument()->getImageFile();
int nx = rIF.nx();
int ny = rIF.ny();
-
+
int yPt = ny - y - 1;
dc.SetLogicalFunction (wxINVERT);
dc.SetPen (*wxGREEN_PEN);
{
x = m_xCursor;
y = m_yCursor;
-
+
if (m_xCursor >= 0 && m_yCursor >= 0)
return true;
else
return false;
}
-void
+void
ImageFileCanvas::OnMouseEvent(wxMouseEvent& event)
{
if (! m_pView)
return;
-
-
+
+
wxClientDC dc(this);
PrepareDC(dc);
-
+
wxPoint pt(event.GetLogicalPosition(dc));
-
+
const ImageFileDocument* pIFDoc = m_pView->GetDocument();
if (! pIFDoc)
return;
bestSize.x = 800;
if (bestSize.y > 800)
bestSize.y = 800;
-
+
if (bestSize.y < iMinY)
bestSize.y = iMinY;
if (bestSize.x < iMinX)
bestSize.x = iMinX;
-
+
return bestSize;
}
EVT_MENU(IFMENU_PLOT_HISTOGRAM, ImageFileView::OnPlotHistogram)
END_EVENT_TABLE()
-ImageFileView::ImageFileView()
+ImageFileView::ImageFileView()
: wxView(), m_pBitmap(0), m_pFrame(0), m_pCanvas(0), m_pFileMenu(0),
m_pFilterMenu(0), m_bMinSpecified(false), m_bMaxSpecified(false),
m_iDefaultExportFormatID(ImageFile::EXPORT_FORMAT_PNG)
GetDocument()->Activate();
}
-void
+void
ImageFileView::OnScaleAuto (wxCommandEvent& event)
{
const ImageFile& rIF = GetDocument()->getImageFile();
GetDocument()->Activate();
}
-void
+void
ImageFileView::OnScaleMinMax (wxCommandEvent& event)
{
const ImageFile& rIF = GetDocument()->getImageFile();
double min, max;
if (! m_bMinSpecified && ! m_bMaxSpecified)
rIF.getMinMax (min, max);
-
+
if (m_bMinSpecified)
min = m_dMinPixel;
if (m_bMaxSpecified)
max = m_dMaxPixel;
-
+
DialogGetMinMax dialogMinMax (getFrameForChild(), "Set Image Minimum & Maximum", min, max);
int retVal = dialogMinMax.ShowModal();
if (retVal == wxID_OK) {
GetDocument()->Activate();
}
-void
+void
ImageFileView::OnScaleFull (wxCommandEvent& event)
{
if (m_bMinSpecified || m_bMaxSpecified) {
{
std::vector<ImageFileDocument*> vecIF;
theApp->getCompatibleImages (GetDocument(), vecIF);
-
+
if (vecIF.size() == 0) {
wxMessageBox("There are no compatible image files open for comparision", "No comparison images");
} else {
DialogGetComparisonImage dialogGetCompare(getFrameForChild(), "Get Comparison Image", vecIF, true);
-
+
if (dialogGetCompare.ShowModal() == wxID_OK) {
const ImageFile& rIF = GetDocument()->getImageFile();
ImageFileDocument* pCompareDoc = dialogGetCompare.getImageFileDocument();
*theApp->getLog() << ">>>>\n" << os.str().c_str() << "<<<<\n";
if (dialogGetCompare.getMakeDifferenceImage()) {
ImageFile* pDifferenceImage = new ImageFile;
-
+
pDifferenceImage->setArraySize (rIF.nx(), rIF.ny());
if (! rIF.subtractImages (rCompareIF, *pDifferenceImage)) {
*theApp->getLog() << "Unable to subtract images\n";
return;
}
pDifferenceDoc->setImageFile (pDifferenceImage);
-
+
wxString s = GetFrame()->GetTitle() + ": ";
pDifferenceImage->labelsCopy (rIF, s.c_str());
s = pCompareDoc->GetFirstView()->GetFrame()->GetTitle() + ": ";
pDifferenceImage->labelsCopy (rCompareIF, s.c_str());
std::ostringstream osLabel;
- osLabel << "Compare image " << GetDocument()->GetFirstView()->GetFrame()->GetTitle().c_str()
+ osLabel << "Compare image " << GetDocument()->GetFirstView()->GetFrame()->GetTitle().c_str()
<< " and " << pCompareDoc->GetFirstView()->GetFrame()->GetTitle().c_str() << ": "
<< os.str().c_str();
pDifferenceImage->labelAdd (os.str().c_str());
if (theApp->getAskDeleteNewDocs())
pDifferenceDoc->Modify (true);
- OnUpdate(this, NULL);
+ OnUpdate(this, NULL);
pDifferenceDoc->UpdateAllViews(this);
- pDifferenceDoc->getView()->setInitialClientSize();
+ pDifferenceDoc->getView()->setInitialClientSize();
pDifferenceDoc->Activate();
}
wxMessageBox(os.str().c_str(), "Image Comparison");
{
std::vector<ImageFileDocument*> vecIF;
theApp->getCompatibleImages (GetDocument(), vecIF);
-
+
if (vecIF.size() == 0) {
wxMessageBox ("There are no compatible image files open for comparision", "No comparison images");
} else {
DialogGetComparisonImage dialogGetCompare (getFrameForChild(), "Get Image to Add", vecIF, false);
-
+
if (dialogGetCompare.ShowModal() == wxID_OK) {
ImageFile& rIF = GetDocument()->getImageFile();
ImageFileDocument* pRHSDoc = dialogGetCompare.getImageFileDocument();
sys_error (ERR_SEVERE, "Unable to create image file");
return;
}
- ImageFile& newImage = pNewDoc->getImageFile();
+ ImageFile& newImage = pNewDoc->getImageFile();
newImage.setArraySize (rIF.nx(), rIF.ny());
rIF.addImages (rRHSIF, newImage);
std::ostringstream os;
- os << "Add image " << GetDocument()->GetFirstView()->GetFrame()->GetTitle().c_str() << " and "
+ os << "Add image " << GetDocument()->GetFirstView()->GetFrame()->GetTitle().c_str() << " and "
<< pRHSDoc->GetFirstView()->GetFrame()->GetTitle().c_str();
wxString s = GetDocument()->GetFirstView()->GetFrame()->GetTitle() + ": ";
newImage.labelsCopy (rIF, s.c_str());
{
std::vector<ImageFileDocument*> vecIF;
theApp->getCompatibleImages (GetDocument(), vecIF);
-
+
if (vecIF.size() == 0) {
wxMessageBox ("There are no compatible image files open for comparision", "No comparison images");
} else {
DialogGetComparisonImage dialogGetCompare (getFrameForChild(), "Get Image to Subtract", vecIF, false);
-
+
if (dialogGetCompare.ShowModal() == wxID_OK) {
ImageFile& rIF = GetDocument()->getImageFile();
ImageFileDocument* pRHSDoc = dialogGetCompare.getImageFileDocument();
sys_error (ERR_SEVERE, "Unable to create image file");
return;
}
- ImageFile& newImage = pNewDoc->getImageFile();
+ ImageFile& newImage = pNewDoc->getImageFile();
newImage.setArraySize (rIF.nx(), rIF.ny());
rIF.subtractImages (rRHSIF, newImage);
std::ostringstream os;
- os << "Subtract image " << GetDocument()->GetFirstView()->GetFrame()->GetTitle().c_str() << " and "
+ os << "Subtract image " << GetDocument()->GetFirstView()->GetFrame()->GetTitle().c_str() << " and "
<< pRHSDoc->GetFirstView()->GetFrame()->GetTitle().c_str();
wxString s = GetDocument()->GetFirstView()->GetFrame()->GetTitle() + ": ";
newImage.labelsCopy (rIF, s.c_str());
{
std::vector<ImageFileDocument*> vecIF;
theApp->getCompatibleImages (GetDocument(), vecIF);
-
+
if (vecIF.size() == 0) {
wxMessageBox ("There are no compatible image files open for comparision", "No comparison images");
} else {
DialogGetComparisonImage dialogGetCompare (getFrameForChild(), "Get Image to Multiply", vecIF, false);
-
+
if (dialogGetCompare.ShowModal() == wxID_OK) {
ImageFile& rIF = GetDocument()->getImageFile();
ImageFileDocument* pRHSDoc = dialogGetCompare.getImageFileDocument();
sys_error (ERR_SEVERE, "Unable to create image file");
return;
}
- ImageFile& newImage = pNewDoc->getImageFile();
+ ImageFile& newImage = pNewDoc->getImageFile();
newImage.setArraySize (rIF.nx(), rIF.ny());
rIF.multiplyImages (rRHSIF, newImage);
std::ostringstream os;
- os << "Multiply image " << GetDocument()->GetFirstView()->GetFrame()->GetTitle().c_str() << " and "
+ os << "Multiply image " << GetDocument()->GetFirstView()->GetFrame()->GetTitle().c_str() << " and "
<< pRHSDoc->GetFirstView()->GetFrame()->GetTitle().c_str();
wxString s = GetDocument()->GetFirstView()->GetFrame()->GetTitle() + ": ";
newImage.labelsCopy (rIF, s.c_str());
{
std::vector<ImageFileDocument*> vecIF;
theApp->getCompatibleImages (GetDocument(), vecIF);
-
+
if (vecIF.size() == 0) {
wxMessageBox ("There are no compatible image files open for comparision", "No comparison images");
} else {
DialogGetComparisonImage dialogGetCompare (getFrameForChild(), "Get Image to Divide", vecIF, false);
-
+
if (dialogGetCompare.ShowModal() == wxID_OK) {
ImageFile& rIF = GetDocument()->getImageFile();
ImageFileDocument* pRHSDoc = dialogGetCompare.getImageFileDocument();
sys_error (ERR_SEVERE, "Unable to create image file");
return;
}
- ImageFile& newImage = pNewDoc->getImageFile();
+ ImageFile& newImage = pNewDoc->getImageFile();
newImage.setArraySize (rIF.nx(), rIF.ny());
rIF.divideImages (rRHSIF, newImage);
std::ostringstream os;
- os << "Divide image " << GetDocument()->GetFirstView()->GetFrame()->GetTitle().c_str() << " by "
+ os << "Divide image " << GetDocument()->GetFirstView()->GetFrame()->GetTitle().c_str() << " by "
<< pRHSDoc->GetFirstView()->GetFrame()->GetTitle().c_str();
wxString s = GetDocument()->GetFirstView()->GetFrame()->GetTitle() + ": ";
newImage.labelsCopy (rIF, s.c_str());
}
-ImageFileCanvas*
+ImageFileCanvas*
ImageFileView::CreateCanvas (wxFrame* parent)
{
ImageFileCanvas* pCanvas = new ImageFileCanvas (this, parent, wxPoint(-1,-1),
- wxSize(-1,-1), 0);
+ wxSize(-1,-1), 0);
pCanvas->SetBackgroundColour(*wxWHITE);
pCanvas->Clear();
-
+
return pCanvas;
}
m_pFileMenu->Append(wxID_SAVEAS, "Save &As...");
m_pFileMenu->Append(wxID_CLOSE, "&Close\tCtrl-W");
m_pFileMenu->Append(wxID_REVERT, "Re&vert");
-
+
m_pFileMenu->AppendSeparator();
m_pFileMenu->Append(IFMENU_FILE_PROPERTIES, "P&roperties\tCtrl-I");
m_pFileMenu->Append(IFMENU_FILE_EXPORT, "Expor&t...");
-
+
m_pFileMenu->AppendSeparator();
m_pFileMenu->Append(wxID_PRINT, "&Print...");
m_pFileMenu->Append(wxID_PRINT_SETUP, "Print &Setup...");
m_pFileMenu->Append(MAINMENU_FILE_EXIT, "E&xit");
GetDocumentManager()->FileHistoryAddFilesToMenu(m_pFileMenu);
GetDocumentManager()->FileHistoryUseMenu(m_pFileMenu);
-
+
wxMenu* edit_menu = new wxMenu;
edit_menu->Append(IFMENU_EDIT_COPY, "Copy\tCtrl-C");
edit_menu->Append(IFMENU_EDIT_CUT, "Cut\tCtrl-X");
edit_menu->Append(IFMENU_EDIT_PASTE, "Paste\tCtrl-V");
-
+
wxMenu *view_menu = new wxMenu;
view_menu->Append(IFMENU_VIEW_SCALE_MINMAX, "Display Scale S&et...\tCtrl-E");
view_menu->Append(IFMENU_VIEW_SCALE_AUTO, "Display Scale &Auto...\tCtrl-A");
view_menu->Append(IFMENU_VIEW_SCALE_FULL, "Display F&ull Scale\tCtrl-U");
-
+
m_pFilterMenu = new wxMenu;
m_pFilterMenu->Append (IFMENU_FILTER_INVERTVALUES, "In&vert Values");
m_pFilterMenu->Append (IFMENU_FILTER_SQUARE, "&Square");
m_pFilterMenu->Append (IFMENU_FILTER_PHASE, "&Phase");
m_pFilterMenu->Append (IFMENU_FILTER_REAL, "Re&al");
m_pFilterMenu->Append (IFMENU_FILTER_IMAGINARY, "Ima&ginary");
-
+
wxMenu* image_menu = new wxMenu;
image_menu->Append (IFMENU_IMAGE_ADD, "&Add...");
image_menu->Append (IFMENU_IMAGE_SUBTRACT, "&Subtract...");
#if wxUSE_GLCANVAS
image_menu->Append (IFMENU_IMAGE_CONVERT3D, "Convert &3-D\tCtrl-3");
#endif
-
+
m_pMenuAnalyze = new wxMenu;
m_pMenuAnalyze->Append (IFMENU_PLOT_ROW, "Plot &Row");
m_pMenuAnalyze->Append (IFMENU_PLOT_COL, "Plot &Column");
m_pMenuAnalyze->Enable (IFMENU_COMPARE_COL, false);
m_pMenuAnalyze->Enable (IFMENU_PLOT_FFT_ROW, false);
m_pMenuAnalyze->Enable (IFMENU_PLOT_FFT_COL, false);
-
+
wxMenu *help_menu = new wxMenu;
help_menu->Append(MAINMENU_HELP_CONTENTS, "&Contents\tF1");
help_menu->Append (MAINMENU_HELP_TIPS, "&Tips");
help_menu->Append (IDH_QUICKSTART, "&Quick Start");
help_menu->Append(MAINMENU_HELP_ABOUT, "&About");
-
+
wxMenuBar *menu_bar = new wxMenuBar;
-
+
menu_bar->Append(m_pFileMenu, "&File");
menu_bar->Append(edit_menu, "&Edit");
menu_bar->Append(view_menu, "&View");
menu_bar->Append(m_pFilterMenu, "Fi<er");
menu_bar->Append(m_pMenuAnalyze, "&Analyze");
menu_bar->Append(help_menu, "&Help");
-
+
subframe->SetMenuBar(menu_bar);
-
+
subframe->Centre(wxBOTH);
-
+
wxAcceleratorEntry accelEntries[10];
accelEntries[0].Set (wxACCEL_CTRL, static_cast<int>('A'), IFMENU_VIEW_SCALE_AUTO);
accelEntries[1].Set (wxACCEL_CTRL, static_cast<int>('U'), IFMENU_VIEW_SCALE_FULL);
wxAcceleratorTable accelTable (iEntry, accelEntries);
subframe->SetAcceleratorTable (accelTable);
-
+
return subframe;
}
-bool
+bool
ImageFileView::OnCreate (wxDocument *doc, long WXUNUSED(flags) )
{
m_bMinSpecified = false;
m_bMaxSpecified = false;
m_dAutoScaleFactor = 1.;
-
+
m_pFrame = CreateChildFrame(doc, this);
SetFrame (m_pFrame);
m_pCanvas = CreateCanvas (m_pFrame);
m_pFrame->Show(true);
Activate(true);
-
+
return true;
}
-void
+void
ImageFileView::setInitialClientSize ()
{
if (m_pFrame && m_pCanvas) {
wxSize bestSize = m_pCanvas->GetBestSize();
-
+
m_pFrame->SetClientSize (bestSize);
m_pFrame->Show (true);
m_pFrame->SetFocus();
}
-}
+}
-void
+void
ImageFileView::OnDraw (wxDC* dc)
{
if (m_pBitmap && m_pBitmap->Ok()) {
-#ifdef DEBUG
+#ifdef DEBUG
*theApp->getLog() << "Drawing bitmap\n";
#endif
dc->DrawBitmap(*m_pBitmap, 0, 0, false);
}
-
+
int xCursor, yCursor;
if (m_pCanvas->GetCurrentCursor (xCursor, yCursor))
m_pCanvas->DrawRubberBandCursor (*dc, xCursor, yCursor);
}
-void
+void
ImageFileView::OnUpdate (wxView *WXUNUSED(sender), wxObject *WXUNUSED(hint) )
{
const ImageFile& rIF = GetDocument()->getImageFile();
m_dMaxPixel = max;
}
double scaleWidth = m_dMaxPixel - m_dMinPixel;
-
+
unsigned char* imageData = new unsigned char [nx * ny * 3];
if (! imageData) {
sys_error (ERR_SEVERE, "Unable to allocate memory for Image display");
delete imageData;
m_pCanvas->SetScrollbars(20, 20, nx/20, ny/20);
m_pCanvas->SetBackgroundColour(*wxWHITE);
- }
-
+ }
+
if (m_pCanvas)
m_pCanvas->Refresh();
}
-bool
+bool
ImageFileView::OnClose (bool deleteWindow)
{
if (! GetDocument() || ! GetDocument()->Close())
return false;
-
+
Activate (false);
if (m_pCanvas) {
m_pCanvas->setView(NULL);
wxString s(theApp->GetAppName());
if (m_pFrame)
m_pFrame->SetTitle(s);
-
+
SetFrame(NULL);
-
+
if (deleteWindow) {
delete m_pFrame;
m_pFrame = NULL;
if (GetDocument() && GetDocument()->getBadFileOpen())
::wxYield(); // wxWindows bug workaround
}
-
+
return true;
}
if (m_pBitmap)
pBitmapObject->SetBitmap (*m_pBitmap);
-
+
if (wxTheClipboard->Open()) {
wxTheClipboard->SetData (pBitmapObject);
wxTheClipboard->Close();
ImageFileView::OnEditPaste (wxCommandEvent& event)
{
ImageFile& rIF = GetDocument()->getImageFile();
-
+
if (wxTheClipboard->Open()) {
wxBitmap bitmap;
if (wxTheClipboard->IsSupported (wxDF_BITMAP)) {
bitmap = bitmapObject.GetBitmap ();
}
wxTheClipboard->Close();
-
+
int nx = rIF.nx();
int ny = rIF.ny();
bool bMonochrome = false;
if (! m_bMaxSpecified)
m_dMaxPixel = max;
}
-
+
DialogExportParameters dialogExport (getFrameForChild(), m_iDefaultExportFormatID);
if (dialogExport.ShowModal() == wxID_OK) {
wxString strFormatName (dialogExport.getFormatName ());
m_iDefaultExportFormatID = ImageFile::convertExportFormatNameToID (strFormatName.c_str());
-
+
wxString strExt;
wxString strWildcard;
if (m_iDefaultExportFormatID == ImageFile::EXPORT_FORMAT_PGM || m_iDefaultExportFormatID == ImageFile::EXPORT_FORMAT_PGMASCII) {
strExt = "";
strWildcard = "Miscellaneous (*.*)|*.*";
}
-
- const wxString& strFilename = wxFileSelector (wxString("Export Filename"), wxString(""),
+
+ const wxString& strFilename = wxFileSelector (wxString("Export Filename"), wxString(""),
wxString(""), strExt, strWildcard, wxOVERWRITE_PROMPT | wxHIDE_READONLY | wxSAVE);
if (strFilename) {
rIF.exportImage (strFormatName.c_str(), strFilename.c_str(), 1, 1, m_dMinPixel, m_dMaxPixel);
ImageFile& rIF = GetDocument()->getImageFile();
unsigned int iOldNX = rIF.nx();
unsigned int iOldNY = rIF.ny();
-
+
DialogGetXYSize dialogGetXYSize (getFrameForChild(), "Set New X & Y Dimensions", iOldNX, iOldNY);
if (dialogGetXYSize.ShowModal() == wxID_OK) {
unsigned int iNewNX = dialogGetXYSize.getXSize();
wxMessageBox ("No row selected. Please use left mouse button on image to select column","Error");
return;
}
-
+
const ImageFile& rIF = GetDocument()->getImageFile();
ImageFileArrayConst v = rIF.getArray();
ImageFileArrayConst vImag = rIF.getImaginaryArray();
int nx = rIF.nx();
int ny = rIF.ny();
-
+
if (v != NULL && yCursor < ny) {
double* pX = new double [nx];
double* pYReal = new double [nx];
} else
rPlotFile.setCurveSize (2, nx);
rPlotFile.addColumn (0, pX);
- rPlotFile.addColumn (1, pYReal);
+ rPlotFile.addColumn (1, pYReal);
if (rIF.isComplex()) {
rPlotFile.addColumn (2, pYImag);
rPlotFile.addColumn (3, pYMag);
wxMessageBox ("No column selected. Please use left mouse button on image to select column","Error");
return;
}
-
+
const ImageFile& rIF = GetDocument()->getImageFile();
ImageFileArrayConst v = rIF.getArray();
ImageFileArrayConst vImag = rIF.getImaginaryArray();
int nx = rIF.nx();
int ny = rIF.ny();
-
+
if (v != NULL && xCursor < nx) {
double* pX = new double [ny];
double* pYReal = new double [ny];
} else
rPlotFile.setCurveSize (2, ny);
rPlotFile.addColumn (0, pX);
- rPlotFile.addColumn (1, pYReal);
+ rPlotFile.addColumn (1, pYReal);
if (rIF.isComplex()) {
rPlotFile.addColumn (2, pYImag);
rPlotFile.addColumn (3, pYMag);
wxMessageBox ("No row selected. Please use left mouse button on image to select column","Error");
return;
}
-
+
const ImageFile& rIF = GetDocument()->getImageFile();
ImageFileArrayConst v = rIF.getArray();
ImageFileArrayConst vImag = rIF.getImaginaryArray();
int nx = rIF.nx();
int ny = rIF.ny();
-
+
if (v != NULL && yCursor < ny) {
fftw_complex* pcIn = static_cast<fftw_complex*>(fftw_malloc (sizeof(fftw_complex) * nx));
-
+
int i;
for (i = 0; i < nx; i++) {
pcIn[i][0] = v[i][yCursor];
else
pcIn[i][1] = 0;
}
-
+
fftw_plan plan = fftw_plan_dft_1d (nx, pcIn, pcIn, FFTW_FORWARD, FFTW_ESTIMATE);
fftw_execute (plan);
fftw_destroy_plan (plan);
-
+
double* pX = new double [nx];
double* pYReal = new double [nx];
double* pYImag = new double [nx];
Fourier::shuffleFourierToNaturalOrder (pYReal, nx);
Fourier::shuffleFourierToNaturalOrder (pYImag, nx);
Fourier::shuffleFourierToNaturalOrder (pYMag, nx);
-
+
PlotFileDocument* pPlotDoc = theApp->newPlotDoc();
if (! pPlotDoc) {
sys_error (ERR_SEVERE, "Internal error: unable to create Plot file");
delete pYImag;
delete pYMag;
fftw_free(pcIn);
-
+
if (theApp->getAskDeleteNewDocs())
pPlotDoc->Modify (true);
pPlotDoc->getView()->getFrame()->Show(true);
wxMessageBox ("No column selected. Please use left mouse button on image to select column","Error");
return;
}
-
+
const ImageFile& rIF = GetDocument()->getImageFile();
ImageFileArrayConst v = rIF.getArray();
ImageFileArrayConst vImag = rIF.getImaginaryArray();
int nx = rIF.nx();
int ny = rIF.ny();
-
+
if (v != NULL && xCursor < nx) {
fftw_complex* pcIn = new fftw_complex [ny];
double *pdTemp = new double [ny];
-
+
int i;
for (i = 0; i < ny; i++)
pdTemp[i] = v[xCursor][i];
Fourier::shuffleNaturalToFourierOrder (pdTemp, ny);
- for (i = 0; i < ny; i++)
+ for (i = 0; i < ny; i++)
pcIn[i][0] = pdTemp[i];
-
+
for (i = 0; i < ny; i++) {
if (rIF.isComplex())
pdTemp[i] = vImag[xCursor][i];
Fourier::shuffleNaturalToFourierOrder (pdTemp, ny);
for (i = 0; i < ny; i++)
pcIn[i][1] = pdTemp[i];
-
+
fftw_plan plan = fftw_plan_dft_1d (ny, pcIn, pcIn, FFTW_BACKWARD, FFTW_ESTIMATE);
fftw_execute (plan);
fftw_destroy_plan (plan);
-
+
double* pX = new double [ny];
double* pYReal = new double [ny];
double* pYImag = new double [ny];
pYImag[i] = pcIn[i][1] / ny;
pYMag[i] = ::sqrt (pcIn[i][0] * pcIn[i][0] + pcIn[i][1] * pcIn[i][1]);
}
-
+
PlotFileDocument* pPlotDoc = theApp->newPlotDoc();
if (! pPlotDoc) {
sys_error (ERR_SEVERE, "Internal error: unable to create Plot file");
delete pYMag;
delete pdTemp;
delete [] pcIn;
-
+
if (theApp->getAskDeleteNewDocs())
pPlotDoc->Modify (true);
pPlotDoc->getView()->getFrame()->Show(true);
wxMessageBox ("No column selected. Please use left mouse button on image to select column","Error");
return;
}
-
+
std::vector<ImageFileDocument*> vecIFDoc;
theApp->getCompatibleImages (GetDocument(), vecIFDoc);
if (vecIFDoc.size() == 0) {
return;
}
DialogGetComparisonImage dialogGetCompare (getFrameForChild(), "Get Comparison Image", vecIFDoc, false);
-
+
if (dialogGetCompare.ShowModal() == wxID_OK) {
ImageFileDocument* pCompareDoc = dialogGetCompare.getImageFileDocument();
const ImageFile& rIF = GetDocument()->getImageFile();
const ImageFile& rCompareIF = pCompareDoc->getImageFile();
-
+
ImageFileArrayConst v1 = rIF.getArray();
ImageFileArrayConst v2 = rCompareIF.getArray();
int nx = rIF.nx();
int ny = rIF.ny();
-
+
if (v1 != NULL && xCursor < nx) {
double* pX = new double [ny];
double* pY1 = new double [ny];
rPlotFile.addColumn (0, pX);
rPlotFile.addColumn (1, pY1);
rPlotFile.addColumn (2, pY2);
-
+
unsigned int iL;
for (iL = 0; iL < rIF.nLabels(); iL++) {
std::string s = GetDocument()->GetFirstView()->GetFrame()->GetTitle().c_str();
wxMessageBox ("No column selected. Please use left mouse button on image to select column","Error");
return;
}
-
+
std::vector<ImageFileDocument*> vecIFDoc;
theApp->getCompatibleImages (GetDocument(), vecIFDoc);
-
+
if (vecIFDoc.size() == 0) {
wxMessageBox ("No compatible images for Row Comparison", "Error");
return;
}
-
+
DialogGetComparisonImage dialogGetCompare (getFrameForChild(), "Get Comparison Image", vecIFDoc, false);
-
+
if (dialogGetCompare.ShowModal() == wxID_OK) {
ImageFileDocument* pCompareDoc = dialogGetCompare.getImageFileDocument();
const ImageFile& rIF = GetDocument()->getImageFile();
const ImageFile& rCompareIF = pCompareDoc->getImageFile();
-
+
ImageFileArrayConst v1 = rIF.getArray();
ImageFileArrayConst v2 = rCompareIF.getArray();
int nx = rIF.nx();
int ny = rIF.ny();
-
+
if (v1 != NULL && yCursor < ny) {
double* pX = new double [nx];
double* pY1 = new double [nx];
void
ImageFileView::OnPlotHistogram (wxCommandEvent& event)
-{
+{
const ImageFile& rIF = GetDocument()->getImageFile();
ImageFileArrayConst v = rIF.getArray();
int nx = rIF.nx();
int ny = rIF.ny();
-
+
if (v != NULL && nx > 0 && ny > 0) {
PlotFileDocument* pPlotDoc = theApp->newPlotDoc();
if (! pPlotDoc) {
sys_error (ERR_SEVERE, "Internal error: unable to create Plot file");
return;
}
-
+
double* pX = new double [NUMBER_HISTOGRAM_BINS];
double* pY = new double [NUMBER_HISTOGRAM_BINS];
double dMin, dMax;
rIF.getMinMax (dMin, dMax);
double dBinWidth = (dMax - dMin) / NUMBER_HISTOGRAM_BINS;
-
+
for (int i = 0; i < NUMBER_HISTOGRAM_BINS; i++) {
pX[i] = dMin + (i + 0.5) * dBinWidth;
pY[i] = 0;
if (iBin >= 0 && iBin < NUMBER_HISTOGRAM_BINS)
pY[iBin] += 1;
}
-
+
PlotFile& rPlotFile = pPlotDoc->getPlotFile();
std::ostringstream os;
os << "Histogram";
m_pView = NULL;
}
-void
+void
PhantomCanvas::OnDraw (wxDC& dc)
{
if (m_pView)
{
if (! m_pView)
return wxSize(0,0);
-
+
int xSize, ySize;
theApp->getMainFrame()->GetClientSize (&xSize, &ySize);
xSize = maxValue<int> (xSize, ySize);
EVT_MENU(PHMMENU_PROCESS_PROJECTIONS, PhantomFileView::OnProjections)
END_EVENT_TABLE()
-PhantomFileView::PhantomFileView()
+PhantomFileView::PhantomFileView()
: wxView(), m_pFrame(NULL), m_pCanvas(NULL), m_pFileMenu(0)
{
#if defined(DEBUG) || defined(_DEBUG)
m_dDefaultScanRatio = 1;
m_iDefaultGeometry = Scanner::GEOMETRY_PARALLEL;
m_iDefaultTrace = Trace::TRACE_NONE;
-
-#ifdef DEBUG
+
+#ifdef DEBUG
m_iDefaultRasterNX = 115;
m_iDefaultRasterNY = 115;
m_iDefaultRasterNSamples = 1;
void
PhantomFileView::OnProjections (wxCommandEvent& event)
{
- DialogGetProjectionParameters dialogProjection (getFrameForChild(),
- m_iDefaultNDet, m_iDefaultNView, m_iDefaultOffsetView, m_iDefaultNSample, m_dDefaultRotation,
- m_dDefaultFocalLength, m_dDefaultCenterDetectorLength, m_dDefaultViewRatio, m_dDefaultScanRatio,
+ DialogGetProjectionParameters dialogProjection (getFrameForChild(),
+ m_iDefaultNDet, m_iDefaultNView, m_iDefaultOffsetView, m_iDefaultNSample, m_dDefaultRotation,
+ m_dDefaultFocalLength, m_dDefaultCenterDetectorLength, m_dDefaultViewRatio, m_dDefaultScanRatio,
m_iDefaultGeometry, m_iDefaultTrace);
int retVal = dialogProjection.ShowModal();
- if (retVal != wxID_OK)
+ if (retVal != wxID_OK)
return;
-
+
m_iDefaultNDet = dialogProjection.getNDet();
m_iDefaultNView = dialogProjection.getNView();
m_iDefaultOffsetView = dialogProjection.getOffsetView();
m_iDefaultGeometry = Scanner::convertGeometryNameToID (sGeometry.c_str());
double dRotationRadians = m_dDefaultRotation;
m_dDefaultRotation /= TWOPI; // convert back to fraction of a circle
-
+
if (m_iDefaultNDet <= 0 || m_iDefaultNView <= 0 || sGeometry == "")
return;
-
+
const Phantom& rPhantom = GetDocument()->getPhantom();
- Scanner theScanner (rPhantom, sGeometry.c_str(), m_iDefaultNDet, m_iDefaultNView, m_iDefaultOffsetView, m_iDefaultNSample,
+ Scanner theScanner (rPhantom, sGeometry.c_str(), m_iDefaultNDet, m_iDefaultNView, m_iDefaultOffsetView, m_iDefaultNSample,
dRotationRadians, m_dDefaultFocalLength, m_dDefaultCenterDetectorLength, m_dDefaultViewRatio, m_dDefaultScanRatio);
if (theScanner.fail()) {
wxString msg = "Failed making scanner\n";
wxMessageBox (msg, "Error");
return;
}
-
+
std::ostringstream os;
- os << "Projections for " << rPhantom.name()
- << ": nDet=" << m_iDefaultNDet
- << ", nView=" << m_iDefaultNView
- << ", gantry offset=" << m_iDefaultOffsetView
- << ", nSamples=" << m_iDefaultNSample
- << ", RotAngle=" << m_dDefaultRotation
- << ", FocalLengthRatio=" << m_dDefaultFocalLength
+ os << "Projections for " << rPhantom.name()
+ << ": nDet=" << m_iDefaultNDet
+ << ", nView=" << m_iDefaultNView
+ << ", gantry offset=" << m_iDefaultOffsetView
+ << ", nSamples=" << m_iDefaultNSample
+ << ", RotAngle=" << m_dDefaultRotation
+ << ", FocalLengthRatio=" << m_dDefaultFocalLength
<< ", CenterDetectorLengthRatio=" << m_dDefaultCenterDetectorLength
- << ", ViewRatio=" << m_dDefaultViewRatio
- << ", ScanRatio=" << m_dDefaultScanRatio
- << ", Geometry=" << sGeometry.c_str()
- << ", FanBeamAngle=" << convertRadiansToDegrees (theScanner.fanBeamAngle());
-
+ << ", ViewRatio=" << m_dDefaultViewRatio
+ << ", ScanRatio=" << m_dDefaultScanRatio
+ << ", Geometry=" << sGeometry.c_str()
+ << ", FanBeamAngle=" << convertRadiansToDegrees (theScanner.fanBeamAngle());
+
Timer timer;
Projections* pProj = NULL;
if (m_iDefaultTrace > Trace::TRACE_CONSOLE) {
pProj = new Projections;
pProj->initFromScanner (theScanner);
-
+
ProjectionsDialog dialogProjections (theScanner, *pProj, rPhantom, m_iDefaultTrace, dynamic_cast<wxWindow*>(getFrameForChild()));
for (int iView = 0; iView < pProj->nView(); iView++) {
::wxYield();
pProjector->SetPriority(60);
pProjector->Run();
return;
- } else
+ } else
#endif // HAVE_WXTHREADS
{
pProj = new Projections;
for (int i = 0; i < pProj->nView(); i++) {
//theScanner.collectProjections (*pProj, rPhantom, i, 1, true, m_iDefaultTrace);
theScanner.collectProjections (*pProj, rPhantom, i, 1, theScanner.offsetView(), true, m_iDefaultTrace);
- if ((i + 1) % ITER_PER_UPDATE == 0)
- if (! dlgProgress.Update (i+1)) {
- delete pProj;
- return;
- }
+ if ((i + 1) % ITER_PER_UPDATE == 0)
+ if (! dlgProgress.Update (i+1)) {
+ delete pProj;
+ return;
+ }
}
}
}
-
+
*theApp->getLog() << os.str().c_str() << "\n";
pProj->setRemark (os.str());
pProj->setCalcTime (timer.timerEnd());
-
+
ProjectionFileDocument* pProjectionDoc = theApp->newProjectionDoc();
if (! pProjectionDoc) {
sys_error (ERR_SEVERE, "Unable to create projection document");
void
PhantomFileView::OnRasterize (wxCommandEvent& event)
{
- DialogGetRasterParameters dialogRaster (getFrameForChild(), m_iDefaultRasterNX, m_iDefaultRasterNY,
+ DialogGetRasterParameters dialogRaster (getFrameForChild(), m_iDefaultRasterNX, m_iDefaultRasterNY,
m_iDefaultRasterNSamples, m_dDefaultRasterViewRatio);
int retVal = dialogRaster.ShowModal();
if (retVal != wxID_OK)
return;
-
+
m_iDefaultRasterNX = dialogRaster.getXSize();
m_iDefaultRasterNY = dialogRaster.getYSize();
m_iDefaultRasterNSamples = dialogRaster.getNSamples();
m_iDefaultRasterNSamples = 1;
if (m_dDefaultRasterViewRatio < 0)
m_dDefaultRasterViewRatio = 0;
- if (m_iDefaultRasterNX <= 0 || m_iDefaultRasterNY <= 0)
+ if (m_iDefaultRasterNX <= 0 || m_iDefaultRasterNY <= 0)
return;
-
+
const Phantom& rPhantom = GetDocument()->getPhantom();
std::ostringstream os;
- os << "Rasterize Phantom " << rPhantom.name() << ": XSize=" << m_iDefaultRasterNX << ", YSize="
- << m_iDefaultRasterNY << ", ViewRatio=" << m_dDefaultRasterViewRatio << ", nSamples="
+ os << "Rasterize Phantom " << rPhantom.name() << ": XSize=" << m_iDefaultRasterNX << ", YSize="
+ << m_iDefaultRasterNY << ", ViewRatio=" << m_dDefaultRasterViewRatio << ", nSamples="
<< m_iDefaultRasterNSamples;;
-
+
#if HAVE_WXTHREADS
if (theApp->getUseBackgroundTasks()) {
RasterizerSupervisorThread* pThread = new RasterizerSupervisorThread (this, m_iDefaultRasterNX, m_iDefaultRasterNY,
}
pThread->SetPriority (60);
pThread->Run();
- } else
+ } else
#endif
{
ImageFile* pImageFile = new ImageFile (m_iDefaultRasterNX, m_iDefaultRasterNY);
- wxProgressDialog dlgProgress (wxString("Rasterize"),
- wxString("Rasterization Progress"),
- pImageFile->nx() + 1,
- getFrameForChild(),
- wxPD_CAN_ABORT );
+ wxProgressDialog dlgProgress (wxString("Rasterize"),
+ wxString("Rasterization Progress"),
+ pImageFile->nx() + 1,
+ getFrameForChild(),
+ wxPD_CAN_ABORT );
Timer timer;
for (unsigned int i = 0; i < pImageFile->nx(); i++) {
- rPhantom.convertToImagefile (*pImageFile, m_dDefaultRasterViewRatio,
- m_iDefaultRasterNSamples, Trace::TRACE_NONE,
- i, 1, true);
- if ((i + 1) % ITER_PER_UPDATE == 0)
- if (! dlgProgress.Update (i+1)) {
- delete pImageFile;
- return;
- }
+ rPhantom.convertToImagefile (*pImageFile, m_dDefaultRasterViewRatio,
+ m_iDefaultRasterNSamples, Trace::TRACE_NONE,
+ i, 1, true);
+ if ((i + 1) % ITER_PER_UPDATE == 0)
+ if (! dlgProgress.Update (i+1)) {
+ delete pImageFile;
+ return;
+ }
}
-
+
ImageFileDocument* pRasterDoc = theApp->newImageDoc();
if (! pRasterDoc) {
sys_error (ERR_SEVERE, "Unable to create image file");
}
-PhantomCanvas*
+PhantomCanvas*
PhantomFileView::CreateCanvas (wxFrame *parent)
{
- PhantomCanvas* pCanvas = new PhantomCanvas (this, parent, wxPoint(-1,-1),
- wxSize(-1,-1), 0);
+ PhantomCanvas* pCanvas = new PhantomCanvas (this, parent, wxPoint(-1,-1),
+ wxSize(-1,-1), 0);
pCanvas->SetBackgroundColour(*wxWHITE);
pCanvas->Clear();
-
+
return pCanvas;
}
wxDocChildFrame *subframe = new wxDocChildFrame (doc, view, theApp->getMainFrame(), -1, "Phantom Frame", wxPoint(-1,-1), wxSize(-1,-1), wxDEFAULT_FRAME_STYLE);
#endif
theApp->setIconForFrame (subframe);
-
+
m_pFileMenu = new wxMenu;
-
+
m_pFileMenu->Append(MAINMENU_FILE_CREATE_PHANTOM, "Cr&eate Phantom...\tCtrl-P");
m_pFileMenu->Append(MAINMENU_FILE_CREATE_FILTER, "Create &Filter...\tCtrl-F");
m_pFileMenu->Append(wxID_OPEN, "&Open...\tCtrl-O");
m_pFileMenu->Append(wxID_SAVEAS, "Save &As...");
m_pFileMenu->Append(wxID_CLOSE, "&Close");
-
+
m_pFileMenu->AppendSeparator();
m_pFileMenu->Append(PHMMENU_FILE_PROPERTIES, "P&roperties\tCtrl-I");
-
+
m_pFileMenu->AppendSeparator();
m_pFileMenu->Append(wxID_PRINT, "&Print...");
m_pFileMenu->Append(wxID_PRINT_SETUP, "Print &Setup...");
m_pFileMenu->Append(MAINMENU_FILE_EXIT, "E&xit");
GetDocumentManager()->FileHistoryAddFilesToMenu(m_pFileMenu);
GetDocumentManager()->FileHistoryUseMenu(m_pFileMenu);
-
+
wxMenu *process_menu = new wxMenu;
process_menu->Append(PHMMENU_PROCESS_RASTERIZE, "&Rasterize...\tCtrl-R");
process_menu->Append(PHMMENU_PROCESS_PROJECTIONS, "&Projections...\tCtrl-J");
-
+
wxMenu *help_menu = new wxMenu;
help_menu->Append(MAINMENU_HELP_CONTENTS, "&Contents\tF1");
help_menu->Append (MAINMENU_HELP_TIPS, "&Tips");
help_menu->Append (IDH_QUICKSTART, "&Quick Start");
help_menu->Append(MAINMENU_HELP_ABOUT, "&About");
-
+
wxMenuBar *menu_bar = new wxMenuBar;
-
+
menu_bar->Append(m_pFileMenu, "&File");
menu_bar->Append(process_menu, "&Process");
menu_bar->Append(help_menu, "&Help");
-
+
subframe->SetMenuBar(menu_bar);
subframe->Centre(wxBOTH);
-
+
wxAcceleratorEntry accelEntries[3];
accelEntries[0].Set (wxACCEL_CTRL, static_cast<int>('J'), PHMMENU_PROCESS_PROJECTIONS);
accelEntries[1].Set (wxACCEL_CTRL, static_cast<int>('R'), PHMMENU_PROCESS_RASTERIZE);
accelEntries[2].Set (wxACCEL_CTRL, static_cast<int>('I'), PHMMENU_FILE_PROPERTIES);
wxAcceleratorTable accelTable (3, accelEntries);
subframe->SetAcceleratorTable (accelTable);
-
+
return subframe;
}
-bool
+bool
PhantomFileView::OnCreate(wxDocument *doc, long WXUNUSED(flags) )
{
m_pFrame = CreateChildFrame(doc, this);
m_pFrame->Show(true);
Activate(true);
-
+
return true;
}
-void
+void
PhantomFileView::OnUpdate (wxView *WXUNUSED(sender), wxObject *WXUNUSED(hint) )
{
if (m_pCanvas)
m_pCanvas->Refresh();
}
-bool
+bool
PhantomFileView::OnClose (bool deleteWindow)
{
if (! GetDocument() || ! GetDocument()->Close())
return false;
-
+
Activate(false);
if (m_pCanvas) {
m_pCanvas->setView(NULL);
wxString s(wxTheApp->GetAppName());
if (m_pFrame)
m_pFrame->SetTitle(s);
-
+
SetFrame(NULL);
-
+
if (deleteWindow) {
delete m_pFrame;
m_pFrame = NULL;
if (GetDocument() && GetDocument()->getBadFileOpen())
::wxYield(); // wxWindows bug workaround
}
-
+
return true;
}
m_pView = NULL;
}
-void
+void
ProjectionFileCanvas::OnDraw(wxDC& dc)
{
if (m_pView)
Projections& rProj = m_pView->GetDocument()->getProjections();
bestSize.Set (rProj.nDet(), rProj.nView());
}
-
+
if (bestSize.x > 800)
bestSize.x = 800;
if (bestSize.y > 800)
END_EVENT_TABLE()
-ProjectionFileView::ProjectionFileView()
+ProjectionFileView::ProjectionFileView()
: wxView(), m_pBitmap(0), m_pFrame(0), m_pCanvas(0), m_pFileMenu(0)
{
#ifdef DEBUG
m_iDefaultNX = 256;
m_iDefaultNY = 256;
#endif
-
+
m_iDefaultFilter = SignalFilter::FILTER_ABS_BANDLIMIT;
m_dDefaultFilterParam = 1.;
#if HAVE_FFTW
m_iDefaultInterpolation = Backprojector::INTERP_LINEAR;
m_iDefaultInterpParam = 1;
m_iDefaultTrace = Trace::TRACE_NONE;
-
+
m_iDefaultPolarNX = 256;
m_iDefaultPolarNY = 256;
m_iDefaultPolarInterpolation = Projections::POLAR_INTERP_BILINEAR;
ProjectionFileView::OnConvertRectangular (wxCommandEvent& event)
{
Projections& rProj = GetDocument()->getProjections();
-
+
int nDet = rProj.nDet();
int nView = rProj.nView();
ImageFile* pIF = new ImageFile (nDet, nView);
ImageFileArray v = pIF->getArray();
for (int iv = 0; iv < nView; iv++) {
DetectorValue* detval = rProj.getDetectorArray(iv).detValues();
-
+
for (int id = 0; id < nDet; id++)
v[id][iv] = detval[id];
}
-
+
ImageFileDocument* pRectDoc = theApp->newImageDoc ();
if (! pRectDoc) {
sys_error (ERR_SEVERE, "Unable to create image file");
m_iDefaultPolarNY = dialogPolar.getYSize();
ImageFile* pIF = new ImageFile (m_iDefaultPolarNX, m_iDefaultPolarNY);
m_iDefaultPolarInterpolation = Projections::convertInterpNameToID (strInterpolation.c_str());
-
+
if (! rProj.convertPolar (*pIF, m_iDefaultPolarInterpolation)) {
delete pIF;
*theApp->getLog() << "Error converting to Polar\n";
return;
}
-
+
ImageFileDocument* pPolarDoc = theApp->newImageDoc();
if (! pPolarDoc) {
sys_error (ERR_SEVERE, "Unable to create image file");
pPolarDoc->setImageFile (pIF);
pIF->labelAdd (rProj.getLabel().getLabelString().c_str(), rProj.calcTime());
std::ostringstream os;
- os << "Convert projection file " << GetFrame()->GetTitle().c_str() << " to polar image: xSize="
- << m_iDefaultPolarNX << ", ySize=" << m_iDefaultPolarNY << ", interpolation="
+ os << "Convert projection file " << GetFrame()->GetTitle().c_str() << " to polar image: xSize="
+ << m_iDefaultPolarNX << ", ySize=" << m_iDefaultPolarNY << ", interpolation="
<< strInterpolation.c_str();
*theApp->getLog() << os.str().c_str() << "\n";
pIF->labelAdd (os.str().c_str());
m_iDefaultPolarNY = dialogPolar.getYSize();
m_iDefaultPolarZeropad = dialogPolar.getZeropad();
ImageFile* pIF = new ImageFile (m_iDefaultPolarNX, m_iDefaultPolarNY);
-
+
m_iDefaultPolarInterpolation = Projections::convertInterpNameToID (strInterpolation.c_str());
if (! rProj.convertFFTPolar (*pIF, m_iDefaultPolarInterpolation, m_iDefaultPolarZeropad)) {
delete pIF;
pPolarDoc->setImageFile (pIF);
pIF->labelAdd (rProj.getLabel().getLabelString().c_str(), rProj.calcTime());
std::ostringstream os;
- os << "Convert projection file " << GetFrame()->GetTitle().c_str() << " to FFT polar image: xSize="
- << m_iDefaultPolarNX << ", ySize=" << m_iDefaultPolarNY << ", interpolation="
+ os << "Convert projection file " << GetFrame()->GetTitle().c_str() << " to FFT polar image: xSize="
+ << m_iDefaultPolarNX << ", ySize=" << m_iDefaultPolarNY << ", interpolation="
<< strInterpolation.c_str() << ", zeropad=" << m_iDefaultPolarZeropad;
*theApp->getLog() << os.str().c_str() << "\n";
pIF->labelAdd (os.str().c_str());
DialogGetThetaRange dlgTheta (this->getFrame(), ParallelRaysums::THETA_RANGE_UNCONSTRAINED);
if (dlgTheta.ShowModal() != wxID_OK)
return;
-
+
int iThetaRange = dlgTheta.getThetaRange();
-
+
Projections& rProj = GetDocument()->getProjections();
ParallelRaysums parallel (&rProj, iThetaRange);
PlotFileDocument* pPlotDoc = theApp->newPlotDoc();
ParallelRaysums::CoordinateContainer& coordContainer = parallel.getCoordinates();
double* pdT = new double [parallel.getNumCoordinates()];
double* pdTheta = new double [parallel.getNumCoordinates()];
-
+
for (int i = 0; i < parallel.getNumCoordinates(); i++) {
pdT[i] = coordContainer[i]->m_dT;
pdTheta[i] = coordContainer[i]->m_dTheta;
void
ProjectionFileView::OnPlotHistogram (wxCommandEvent& event)
-{
+{
Projections& rProj = GetDocument()->getProjections();
int nDet = rProj.nDet();
int nView = rProj.nView();
-
+
if (nDet < 1 || nView < 1)
return;
sys_error (ERR_SEVERE, "Internal error: unable to create Plot file");
return;
}
-
+
DetectorValue* pdDetval = rProj.getDetectorArray(0).detValues();
double dMin = pdDetval[0], dMax = pdDetval[0];
double* pX = new double [NUMBER_HISTOGRAM_BINS];
double* pY = new double [NUMBER_HISTOGRAM_BINS];
double dBinWidth = (dMax - dMin) / NUMBER_HISTOGRAM_BINS;
-
+
for (int i = 0; i < NUMBER_HISTOGRAM_BINS; i++) {
pX[i] = dMin + (i + 0.5) * dBinWidth;
pY[i] = 0;
if (iBin >= 0 && iBin < NUMBER_HISTOGRAM_BINS)
pY[iBin] += 1;
}
- }
+ }
PlotFile& rPlotFile = pPlotDoc->getPlotFile();
std::ostringstream os;
os << "Histogram";
wxProgressDialog dlgProgress (wxString("Convert to Parallel"), wxString("Conversion Progress"), 1, getFrameForChild(), wxPD_APP_MODAL);
Projections* pProjNew = rProj.interpolateToParallel();
ProjectionFileDocument* pProjDocNew = theApp->newProjectionDoc();
- pProjDocNew->setProjections (pProjNew);
-
+ pProjDocNew->setProjections (pProjNew);
+
if (ProjectionFileView* projView = pProjDocNew->getView()) {
projView->OnUpdate (projView, NULL);
if (projView->getCanvas())
m_iDefaultPolarNY = dialogPolar.getYSize();
m_iDefaultPolarZeropad = dialogPolar.getZeropad();
ImageFile* pIF = new ImageFile (m_iDefaultPolarNX, m_iDefaultPolarNY);
-
+
m_iDefaultPolarInterpolation = Projections::convertInterpNameToID (strInterpolation.c_str());
if (! rProj.convertFFTPolar (*pIF, m_iDefaultPolarInterpolation, m_iDefaultPolarZeropad)) {
delete pIF;
pPolarDoc->setImageFile (pIF);
pIF->labelAdd (rProj.getLabel().getLabelString().c_str(), rProj.calcTime());
std::ostringstream os;
- os << "Reconstruct Fourier " << GetFrame()->GetTitle().c_str() << ": xSize="
- << m_iDefaultPolarNX << ", ySize=" << m_iDefaultPolarNY << ", interpolation="
+ os << "Reconstruct Fourier " << GetFrame()->GetTitle().c_str() << ": xSize="
+ << m_iDefaultPolarNX << ", ySize=" << m_iDefaultPolarNY << ", interpolation="
<< strInterpolation.c_str() << ", zeropad=" << m_iDefaultPolarZeropad;
*theApp->getLog() << os.str().c_str() << "\n";
pIF->labelAdd (os.str().c_str());
defaultROI.m_dXMax = defaultROI.m_dXMin + rProj.phmLen();
defaultROI.m_dYMin = -rProj.phmLen() / 2;
defaultROI.m_dYMax = defaultROI.m_dYMin + rProj.phmLen();
-
- DialogGetReconstructionParameters dialogReconstruction (getFrameForChild(), m_iDefaultNX, m_iDefaultNY,
- m_iDefaultFilter, m_dDefaultFilterParam, m_iDefaultFilterMethod, m_iDefaultFilterGeneration,
- m_iDefaultZeropad, m_iDefaultInterpolation, m_iDefaultInterpParam, m_iDefaultBackprojector,
+
+ DialogGetReconstructionParameters dialogReconstruction (getFrameForChild(), m_iDefaultNX, m_iDefaultNY,
+ m_iDefaultFilter, m_dDefaultFilterParam, m_iDefaultFilterMethod, m_iDefaultFilterGeneration,
+ m_iDefaultZeropad, m_iDefaultInterpolation, m_iDefaultInterpParam, m_iDefaultBackprojector,
m_iDefaultTrace, &defaultROI);
-
+
int retVal = dialogReconstruction.ShowModal();
if (retVal != wxID_OK)
return;
-
+
m_iDefaultNX = dialogReconstruction.getXSize();
m_iDefaultNY = dialogReconstruction.getYSize();
wxString optFilterName = dialogReconstruction.getFilterName();
m_iDefaultBackprojector = Backprojector::convertBackprojectNameToID (optBackprojectName.c_str());
m_iDefaultTrace = dialogReconstruction.getTrace();
dialogReconstruction.getROI (&defaultROI);
-
- if (m_iDefaultNX <= 0 && m_iDefaultNY <= 0)
+
+ if (m_iDefaultNX <= 0 && m_iDefaultNY <= 0)
return;
-
+
std::ostringstream os;
os << "Reconstruct " << rProj.getFilename() << ": xSize=" << m_iDefaultNX << ", ySize=" << m_iDefaultNY << ", Filter=" << optFilterName.c_str() << ", FilterParam=" << m_dDefaultFilterParam << ", FilterMethod=" << optFilterMethodName.c_str() << ", FilterGeneration=" << optFilterGenerationName.c_str() << ", Zeropad=" << m_iDefaultZeropad << ", Interpolation=" << optInterpName.c_str() << ", InterpolationParam=" << m_iDefaultInterpParam << ", Backprojection=" << optBackprojectName.c_str();
if (bRebinToParallel)
os << "; Interpolate to Parallel";
-
+
Timer timerRecon;
ImageFile* pImageFile = NULL;
if (m_iDefaultTrace > Trace::TRACE_CONSOLE) {
pImageFile = new ImageFile (m_iDefaultNX, m_iDefaultNY);
- Reconstructor* pReconstructor = new Reconstructor (rProj, *pImageFile, optFilterName.c_str(),
- m_dDefaultFilterParam, optFilterMethodName.c_str(), m_iDefaultZeropad, optFilterGenerationName.c_str(),
- optInterpName.c_str(), m_iDefaultInterpParam, optBackprojectName.c_str(), m_iDefaultTrace,
+ Reconstructor* pReconstructor = new Reconstructor (rProj, *pImageFile, optFilterName.c_str(),
+ m_dDefaultFilterParam, optFilterMethodName.c_str(), m_iDefaultZeropad, optFilterGenerationName.c_str(),
+ optInterpName.c_str(), m_iDefaultInterpParam, optBackprojectName.c_str(), m_iDefaultTrace,
&defaultROI, bRebinToParallel);
-
+
ReconstructDialog* pDlgReconstruct = new ReconstructDialog (*pReconstructor, rProj, *pImageFile, m_iDefaultTrace, getFrameForChild());
for (int iView = 0; iView < rProj.nView(); iView++) {
::wxYield();
} else {
#if HAVE_WXTHREADS
if (theApp->getUseBackgroundTasks()) {
- ReconstructorSupervisorThread* pReconstructor = new ReconstructorSupervisorThread (this, m_iDefaultNX,
- m_iDefaultNY, optFilterName.c_str(), m_dDefaultFilterParam, optFilterMethodName.c_str(),
- m_iDefaultZeropad, optFilterGenerationName.c_str(), optInterpName.c_str(), m_iDefaultInterpParam,
+ ReconstructorSupervisorThread* pReconstructor = new ReconstructorSupervisorThread (this, m_iDefaultNX,
+ m_iDefaultNY, optFilterName.c_str(), m_dDefaultFilterParam, optFilterMethodName.c_str(),
+ m_iDefaultZeropad, optFilterGenerationName.c_str(), optInterpName.c_str(), m_iDefaultInterpParam,
optBackprojectName.c_str(), os.str().c_str(), &defaultROI, bRebinToParallel);
if (pReconstructor->Create() != wxTHREAD_NO_ERROR) {
sys_error (ERR_SEVERE, "Error creating reconstructor thread");
pReconstructor->SetPriority (60);
pReconstructor->Run();
return;
- } else
+ } else
#endif
{
pImageFile = new ImageFile (m_iDefaultNX, m_iDefaultNY);
wxProgressDialog dlgProgress (wxString("Reconstruction"), wxString("Reconstruction Progress"), rProj.nView() + 1, getFrameForChild(), wxPD_CAN_ABORT );
- Reconstructor* pReconstructor = new Reconstructor (rProj, *pImageFile, optFilterName.c_str(),
- m_dDefaultFilterParam, optFilterMethodName.c_str(), m_iDefaultZeropad, optFilterGenerationName.c_str(),
- optInterpName.c_str(), m_iDefaultInterpParam, optBackprojectName.c_str(), m_iDefaultTrace,
+ Reconstructor* pReconstructor = new Reconstructor (rProj, *pImageFile, optFilterName.c_str(),
+ m_dDefaultFilterParam, optFilterMethodName.c_str(), m_iDefaultZeropad, optFilterGenerationName.c_str(),
+ optInterpName.c_str(), m_iDefaultInterpParam, optBackprojectName.c_str(), m_iDefaultTrace,
&defaultROI, bRebinToParallel);
-
+
for (int iView = 0; iView < rProj.nView(); iView++) {
pReconstructor->reconstructView (iView, 1);
- if ((iView + 1) % ITER_PER_UPDATE == 0)
- if (! dlgProgress.Update (iView + 1)) {
- delete pReconstructor;
- return; // don't make new window, thread will do this
- }
+ if ((iView + 1) % ITER_PER_UPDATE == 0)
+ if (! dlgProgress.Update (iView + 1)) {
+ delete pReconstructor;
+ return; // don't make new window, thread will do this
+ }
}
pReconstructor->postProcessing();
delete pReconstructor;
}
*theApp->getLog() << os.str().c_str() << "\n";
pImageFile->labelAdd (rProj.getLabel());
- pImageFile->labelAdd (os.str().c_str(), timerRecon.timerEnd());
+ pImageFile->labelAdd (os.str().c_str(), timerRecon.timerEnd());
pReconDoc->setImageFile (pImageFile);
if (theApp->getAskDeleteNewDocs())
}
-ProjectionFileCanvas*
+ProjectionFileCanvas*
ProjectionFileView::CreateCanvas (wxFrame *parent)
{
ProjectionFileCanvas* pCanvas;
int width, height;
parent->GetClientSize(&width, &height);
-
+
pCanvas = new ProjectionFileCanvas (this, parent, wxPoint(-1,-1), wxSize(width, height), 0);
-
+
pCanvas->SetScrollbars(20, 20, 50, 50);
pCanvas->SetBackgroundColour(*wxWHITE);
pCanvas->Clear();
-
+
return pCanvas;
}
wxDocChildFrame *subframe = new wxDocChildFrame (doc, view, theApp->getMainFrame(), -1, "Projection Frame", wxPoint(-1,-1), wxSize(-1,-1), wxDEFAULT_FRAME_STYLE);
#endif
theApp->setIconForFrame (subframe);
-
+
m_pFileMenu = new wxMenu;
-
+
m_pFileMenu->Append(MAINMENU_FILE_CREATE_PHANTOM, "Cr&eate Phantom...\tCtrl-P");
m_pFileMenu->Append(MAINMENU_FILE_CREATE_FILTER, "Create &Filter...\tCtrl-F");
m_pFileMenu->Append(wxID_OPEN, "&Open...\tCtrl-O");
m_pFileMenu->Append(wxID_SAVE, "&Save\tCtrl-S");
m_pFileMenu->Append(wxID_SAVEAS, "Save &As...");
m_pFileMenu->Append(wxID_CLOSE, "&Close\tCtrl-W");
-
+
m_pFileMenu->AppendSeparator();
m_pFileMenu->Append(PJMENU_FILE_PROPERTIES, "P&roperties\tCtrl-I");
-
+
m_pFileMenu->AppendSeparator();
m_pFileMenu->Append(wxID_PRINT, "&Print...");
m_pFileMenu->Append(wxID_PRINT_SETUP, "Print &Setup...");
m_pFileMenu->Append(MAINMENU_FILE_EXIT, "E&xit");
GetDocumentManager()->FileHistoryAddFilesToMenu(m_pFileMenu);
GetDocumentManager()->FileHistoryUseMenu(m_pFileMenu);
-
+
m_pConvertMenu = new wxMenu;
m_pConvertMenu->Append (PJMENU_CONVERT_RECTANGULAR, "&Rectangular Image");
m_pConvertMenu->Append (PJMENU_CONVERT_POLAR, "&Polar Image...\tCtrl-L");
m_pConvertMenu->Append (PJMENU_CONVERT_FFT_POLAR, "FF&T->Polar Image...\tCtrl-T");
m_pConvertMenu->AppendSeparator();
m_pConvertMenu->Append (PJMENU_CONVERT_PARALLEL, "&Interpolate to Parallel");
-
+
// wxMenu* filter_menu = new wxMenu;
// filter_menu->Append (PJMENU_ARTIFACT_REDUCTION, "&Artifact Reduction");
-
+
wxMenu* analyze_menu = new wxMenu;
analyze_menu->Append (PJMENU_PLOT_HISTOGRAM, "&Plot Histogram");
analyze_menu->Append (PJMENU_PLOT_TTHETA_SAMPLING, "Plot T-T&heta Sampling...\tCtrl-H");
m_pReconstructMenu->Append (PJMENU_RECONSTRUCT_FBP, "&Filtered Backprojection...\tCtrl-R", "Reconstruct image using filtered backprojection");
m_pReconstructMenu->Append (PJMENU_RECONSTRUCT_FBP_REBIN, "Filtered &Backprojection (Rebin to Parallel)...\tCtrl-B", "Reconstruct image using filtered backprojection");
m_pReconstructMenu->Append (PJMENU_RECONSTRUCT_FOURIER, "&Inverse Fourier...\tCtrl-E", "Direct inverse Fourier");
-
+
wxMenu *help_menu = new wxMenu;
help_menu->Append(MAINMENU_HELP_CONTENTS, "&Contents\tF1");
help_menu->Append (MAINMENU_HELP_TIPS, "&Tips");
help_menu->Append (IDH_QUICKSTART, "&Quick Start");
help_menu->Append(MAINMENU_HELP_ABOUT, "&About");
-
+
wxMenuBar *menu_bar = new wxMenuBar;
-
+
menu_bar->Append (m_pFileMenu, "&File");
menu_bar->Append (m_pConvertMenu, "&Convert");
// menu_bar->Append (filter_menu, "Fi<er");
menu_bar->Append (analyze_menu, "&Analyze");
menu_bar->Append (m_pReconstructMenu, "&Reconstruct");
menu_bar->Append (help_menu, "&Help");
-
- subframe->SetMenuBar(menu_bar);
+
+ subframe->SetMenuBar(menu_bar);
subframe->Centre(wxBOTH);
-
+
wxAcceleratorEntry accelEntries[7];
accelEntries[0].Set (wxACCEL_CTRL, static_cast<int>('L'), PJMENU_CONVERT_POLAR);
accelEntries[1].Set (wxACCEL_CTRL, static_cast<int>('T'), PJMENU_CONVERT_FFT_POLAR);
accelEntries[6].Set (wxACCEL_CTRL, static_cast<int>('H'), PJMENU_PLOT_TTHETA_SAMPLING);
wxAcceleratorTable accelTable (7, accelEntries);
subframe->SetAcceleratorTable (accelTable);
-
+
return subframe;
}
-bool
+bool
ProjectionFileView::OnCreate(wxDocument *doc, long WXUNUSED(flags) )
{
m_pFrame = CreateChildFrame(doc, this);
m_pFrame->Show(true);
Activate(true);
-
+
return true;
}
-void
+void
ProjectionFileView::OnDraw (wxDC* dc)
{
if (m_pBitmap && m_pBitmap->Ok())
}
-void
+void
ProjectionFileView::setInitialClientSize ()
{
if (m_pFrame && m_pCanvas) {
m_pFrame->Show (true);
m_pFrame->SetFocus();
}
-}
+}
-void
+void
ProjectionFileView::OnUpdate (wxView *WXUNUSED(sender), wxObject *WXUNUSED(hint) )
{
const Projections& rProj = GetDocument()->getProjections();
const int nDet = rProj.nDet();
const int nView = rProj.nView();
- if (rProj.geometry() == Scanner::GEOMETRY_PARALLEL) {
+ if (rProj.geometry() == Scanner::GEOMETRY_PARALLEL) {
m_pReconstructMenu->Enable (PJMENU_RECONSTRUCT_FBP_REBIN, false);
m_pConvertMenu->Enable (PJMENU_CONVERT_PARALLEL, false);
} else {
max = detval[ix];
}
}
-
+
unsigned char* imageData = new unsigned char [nDet * nView * 3];
if (! imageData) {
sys_error (ERR_SEVERE, "Unable to allocate memory for image display");
m_pBitmap = new wxBitmap (image);
delete imageData;
}
-
+
m_pCanvas->SetScrollbars(20, 20, nDet/20, nView/20);
m_pCanvas->SetBackgroundColour(*wxWHITE);
m_pCanvas->Refresh();
}
-bool
+bool
ProjectionFileView::OnClose (bool deleteWindow)
{
//GetDocumentManager()->ActivateView (this, false, true);
if (! GetDocument() || ! GetDocument()->Close())
return false;
-
+
Activate(false);
if (m_pCanvas) {
- m_pCanvas->setView(NULL);
+ m_pCanvas->setView(NULL);
m_pCanvas = NULL;
}
wxString s(wxTheApp->GetAppName());
if (m_pFrame)
m_pFrame->SetTitle(s);
-
+
SetFrame(NULL);
-
+
if (deleteWindow) {
delete m_pFrame;
m_pFrame = NULL;
if (GetDocument() && GetDocument()->getBadFileOpen())
::wxYield(); // wxWindows bug workaround
}
-
+
return true;
}
}
-void
+void
PlotFileCanvas::OnDraw(wxDC& dc)
{
if (m_pView)
EVT_MENU(PLOTMENU_VIEW_SCALE_FULL, PlotFileView::OnScaleFull)
END_EVENT_TABLE()
-PlotFileView::PlotFileView()
-: wxView(), m_pFrame(0), m_pCanvas(0), m_pEZPlot(0), m_pFileMenu(0),
+PlotFileView::PlotFileView()
+: wxView(), m_pFrame(0), m_pCanvas(0), m_pEZPlot(0), m_pFileMenu(0),
m_bMinSpecified(false), m_bMaxSpecified(false)
{
}
{
if (m_pEZPlot)
delete m_pEZPlot;
-
- GetDocumentManager()->FileHistoryRemoveMenu (m_pFileMenu);
+
+ GetDocumentManager()->FileHistoryRemoveMenu (m_pFileMenu);
GetDocumentManager()->ActivateView(this, FALSE, TRUE);
}
}
-void
+void
PlotFileView::OnScaleAuto (wxCommandEvent& event)
{
const PlotFile& rPlotFile = GetDocument()->getPlotFile();
GetDocument()->Activate();
}
-void
+void
PlotFileView::OnScaleMinMax (wxCommandEvent& event)
{
const PlotFile& rPlotFile = GetDocument()->getPlotFile();
double min;
double max;
-
+
if (! m_bMinSpecified || ! m_bMaxSpecified) {
if (! rPlotFile.getMinMax (1, min, max)) {
*theApp->getLog() << "Error: unable to find Min/Max\n";
return;
}
}
-
+
if (m_bMinSpecified)
min = m_dMinPixel;
if (m_bMaxSpecified)
max = m_dMaxPixel;
-
+
DialogGetMinMax dialogMinMax (getFrameForChild(), "Set Y-axis Minimum & Maximum", min, max);
int retVal = dialogMinMax.ShowModal();
if (retVal == wxID_OK) {
GetDocument()->Activate();
}
-void
+void
PlotFileView::OnScaleFull (wxCommandEvent& event)
{
if (m_bMinSpecified || m_bMaxSpecified) {
}
-PlotFileCanvas*
+PlotFileCanvas*
PlotFileView::CreateCanvas (wxFrame* parent)
{
PlotFileCanvas* pCanvas;
-
- pCanvas = new PlotFileCanvas (this, parent, wxPoint(-1,-1), wxSize(-1,-1), 0);
+
+ pCanvas = new PlotFileCanvas (this, parent, wxPoint(-1,-1), wxSize(-1,-1), 0);
pCanvas->SetBackgroundColour(*wxWHITE);
pCanvas->Clear();
-
+
return pCanvas;
}
wxDocChildFrame *subframe = new wxDocChildFrame(doc, view, theApp->getMainFrame(), -1, "Plot Frame", wxPoint(-1,-1), wxSize(-1,-1), wxDEFAULT_FRAME_STYLE);
#endif
theApp->setIconForFrame (subframe);
-
+
m_pFileMenu = new wxMenu;
-
+
m_pFileMenu->Append(MAINMENU_FILE_CREATE_PHANTOM, "Cr&eate Phantom...\tCtrl-P");
m_pFileMenu->Append(MAINMENU_FILE_CREATE_FILTER, "Create &Filter...\tCtrl-F");
m_pFileMenu->Append(wxID_OPEN, "&Open...\tCtrl-O");
m_pFileMenu->Append(wxID_SAVE, "&Save\tCtrl-S");
m_pFileMenu->Append(wxID_SAVEAS, "Save &As...");
m_pFileMenu->Append(wxID_CLOSE, "&Close\tCtrl-W");
-
+
m_pFileMenu->AppendSeparator();
m_pFileMenu->Append(PLOTMENU_FILE_PROPERTIES, "P&roperties\tCtrl-I");
-
+
m_pFileMenu->AppendSeparator();
m_pFileMenu->Append(wxID_PRINT, "&Print...");
m_pFileMenu->Append(wxID_PRINT_SETUP, "Print &Setup...");
m_pFileMenu->Append(MAINMENU_FILE_EXIT, "E&xit");
GetDocumentManager()->FileHistoryAddFilesToMenu(m_pFileMenu);
GetDocumentManager()->FileHistoryUseMenu(m_pFileMenu);
-
+
wxMenu *view_menu = new wxMenu;
view_menu->Append(PLOTMENU_VIEW_SCALE_MINMAX, "Display Scale &Set...\tCtrl-E");
view_menu->Append(PLOTMENU_VIEW_SCALE_AUTO, "Display Scale &Auto...\tCtrl-A");
view_menu->Append(PLOTMENU_VIEW_SCALE_FULL, "Display &Full Scale\tCtrl-U");
-
+
wxMenu *help_menu = new wxMenu;
help_menu->Append(MAINMENU_HELP_CONTENTS, "&Contents\tF1");
help_menu->Append (MAINMENU_HELP_TIPS, "&Tips");
help_menu->Append (IDH_QUICKSTART, "&Quick Start");
help_menu->Append(MAINMENU_HELP_ABOUT, "&About");
-
+
wxMenuBar *menu_bar = new wxMenuBar;
-
+
menu_bar->Append(m_pFileMenu, "&File");
menu_bar->Append(view_menu, "&View");
menu_bar->Append(help_menu, "&Help");
-
+
subframe->SetMenuBar(menu_bar);
subframe->Centre(wxBOTH);
-
+
wxAcceleratorEntry accelEntries[4];
accelEntries[0].Set (wxACCEL_CTRL, static_cast<int>('E'), PLOTMENU_VIEW_SCALE_MINMAX);
accelEntries[1].Set (wxACCEL_CTRL, static_cast<int>('A'), PLOTMENU_VIEW_SCALE_AUTO);
accelEntries[3].Set (wxACCEL_CTRL, static_cast<int>('I'), PLOTMENU_FILE_PROPERTIES);
wxAcceleratorTable accelTable (4, accelEntries);
subframe->SetAcceleratorTable (accelTable);
-
+
return subframe;
}
-bool
+bool
PlotFileView::OnCreate (wxDocument *doc, long WXUNUSED(flags) )
{
m_bMinSpecified = false;
m_bMaxSpecified = false;
m_dAutoScaleFactor = 1.;
-
+
m_pFrame = CreateChildFrame(doc, this);
SetFrame(m_pFrame);
m_pCanvas = CreateCanvas (m_pFrame);
m_pFrame->SetClientSize (m_pCanvas->GetBestSize());
m_pCanvas->SetClientSize (m_pCanvas->GetBestSize());
m_pFrame->SetTitle ("Plot File");
-
+
m_pFrame->Show(true);
Activate(true);
-
+
return true;
}
-void
+void
PlotFileView::setInitialClientSize ()
{
if (m_pFrame && m_pCanvas) {
wxSize bestSize = m_pCanvas->GetBestSize();
-
+
m_pFrame->SetClientSize (bestSize);
m_pFrame->Show (true);
m_pFrame->SetFocus();
}
-}
+}
-void
+void
PlotFileView::OnDraw (wxDC* dc)
{
const PlotFile& rPlotFile = GetDocument()->getPlotFile();
const int iNColumns = rPlotFile.getNumColumns();
const int iNRecords = rPlotFile.getNumRecords();
-
+
if (iNColumns > 0 && iNRecords > 0) {
int xsize, ysize;
m_pCanvas->GetClientSize (&xsize, &ysize);
}
-void
+void
PlotFileView::OnUpdate (wxView *WXUNUSED(sender), wxObject *WXUNUSED(hint) )
{
const PlotFile& rPlotFile = GetDocument()->getPlotFile();
const int iNColumns = rPlotFile.getNumColumns();
const int iNRecords = rPlotFile.getNumRecords();
const bool bScatterPlot = rPlotFile.getIsScatterPlot();
-
+
if (iNColumns > 0 && iNRecords > 0) {
if (m_pEZPlot)
delete m_pEZPlot;
m_pEZPlot = new EZPlot;
-
+
for (unsigned int iEzset = 0; iEzset < rPlotFile.getNumEzsetCommands(); iEzset++)
m_pEZPlot->ezset (rPlotFile.getEzsetCommand (iEzset));
-
+
if (m_bMinSpecified) {
std::ostringstream os;
os << "ymin " << m_dMinPixel;
m_pEZPlot->ezset (os.str());
}
-
+
if (m_bMaxSpecified) {
std::ostringstream os;
os << "ymax " << m_dMaxPixel;
m_pEZPlot->ezset (os.str());
}
-
+
m_pEZPlot->ezset("box");
m_pEZPlot->ezset("grid");
-
+
double* pdX = new double [iNRecords];
double* pdY = new double [iNRecords];
if (! bScatterPlot) {
rPlotFile.getColumn (0, pdX);
-
+
for (int iCol = 1; iCol < iNColumns; iCol++) {
rPlotFile.getColumn (iCol, pdY);
m_pEZPlot->addCurve (pdX, pdY, iNRecords);
delete pdX;
delete pdY;
}
-
+
if (m_pCanvas)
m_pCanvas->Refresh();
}
-bool
+bool
PlotFileView::OnClose (bool deleteWindow)
{
if (! GetDocument() || ! GetDocument()->Close())
return false;
-
+
Activate(false);
if (m_pCanvas) {
m_pCanvas->setView (NULL);
wxString s(wxTheApp->GetAppName());
if (m_pFrame)
m_pFrame->SetTitle(s);
-
+
SetFrame(NULL);
if (deleteWindow) {
delete m_pFrame;
if (GetDocument() && GetDocument()->getBadFileOpen())
::wxYield(); // wxWindows bug workaround
}
-
+
return true;
}
IMPLEMENT_DYNAMIC_CLASS(TextFileView, wxView)
-TextFileView::~TextFileView()
+TextFileView::~TextFileView()
{
GetDocumentManager()->FileHistoryRemoveMenu (m_pFileMenu);
GetDocumentManager()->ActivateView(this, FALSE, TRUE);;
{
m_pFrame = CreateChildFrame(doc, this);
SetFrame (m_pFrame);
-
+
int width, height;
m_pFrame->GetClientSize(&width, &height);
m_pFrame->SetTitle("TextFile");
m_pCanvas = new TextFileCanvas (this, m_pFrame, wxPoint(-1,-1), wxSize(width, height), wxTE_MULTILINE | wxTE_READONLY);
m_pFrame->SetTitle("Log");
-
+
m_pFrame->Show (true);
Activate (true);
-
+
return true;
}
{
}
-bool
+bool
TextFileView::OnClose (bool deleteWindow)
{
if (! theApp->getMainFrame()->getShuttingDown())
return false;
-
+
Activate(false);
//GetDocumentManager()->ActivateView (this, false, true);
if (! GetDocument() || ! GetDocument()->Close())
return false;
-
+
SetFrame(NULL);
if (deleteWindow) {
delete m_pFrame;
if (GetDocument() && GetDocument()->getBadFileOpen())
::wxYield(); // wxWindows bug workaround
}
-
+
return TRUE;
}
wxDocChildFrame* subframe = new wxDocChildFrame (doc, view, theApp->getMainFrame(), -1, "TextFile Frame", wxPoint(-1, -1), wxSize(300, 150), wxDEFAULT_FRAME_STYLE, "Log");
#endif
theApp->setIconForFrame (subframe);
-
+
m_pFileMenu = new wxMenu;
-
+
m_pFileMenu->Append(MAINMENU_FILE_CREATE_PHANTOM, "Cr&eate Phantom...\tCtrl-P");
m_pFileMenu->Append(MAINMENU_FILE_CREATE_FILTER, "Create &Filter...\tCtrl-F");
m_pFileMenu->Append(wxID_OPEN, "&Open...\tCtrl-O");
m_pFileMenu->Append(wxID_SAVE, "&Save\tCtrl-S");
m_pFileMenu->Append(wxID_SAVEAS, "Save &As...");
// m_pFileMenu->Append(wxID_CLOSE, "&Close\tCtrl-W");
-
+
m_pFileMenu->AppendSeparator();
m_pFileMenu->Append(wxID_PRINT, "&Print...");
m_pFileMenu->Append(wxID_PRINT_SETUP, "Print &Setup...");
m_pFileMenu->Append(MAINMENU_FILE_EXIT, "E&xit");
GetDocumentManager()->FileHistoryAddFilesToMenu(m_pFileMenu);
GetDocumentManager()->FileHistoryUseMenu(m_pFileMenu);
-
+
wxMenu *help_menu = new wxMenu;
help_menu->Append(MAINMENU_HELP_CONTENTS, "&Contents\tF1");
help_menu->Append (MAINMENU_HELP_TIPS, "&Tips");
help_menu->Append (IDH_QUICKSTART, "&Quick Start");
help_menu->Append(MAINMENU_HELP_ABOUT, "&About");
-
+
wxMenuBar *menu_bar = new wxMenuBar;
-
+
menu_bar->Append(m_pFileMenu, "&File");
menu_bar->Append(help_menu, "&Help");
-
+
subframe->SetMenuBar(menu_bar);
subframe->Centre(wxBOTH);
-
+
return subframe;
}
{
private:
DECLARE_DYNAMIC_CLASS(ImageFileView)
-
+
wxMemoryDC m_memoryDC;
wxBitmap* m_pBitmap;
wxMenu* m_pMenuAnalyze;
-
+
ImageFileCanvas *CreateCanvas (wxFrame* parent);
#if CTSIM_MDI
wxDocMDIChildFrame* m_pFrame;
wxDocChildFrame* m_pFrame;
wxDocChildFrame* CreateChildFrame(wxDocument *doc, wxView *view);
#endif
-
+
ImageFileCanvas *m_pCanvas;
wxMenu* m_pFileMenu;
wxMenu* m_pFilterMenu;
double m_dMinPixel;
double m_dMaxPixel;
double m_dAutoScaleFactor;
-
+
int m_iDefaultExportFormatID;
- wxWindow* getFrameForChild()
+ wxWindow* getFrameForChild()
#if CTSIM_MDI
{ return theApp->getMainFrame(); }
#else
void OnDraw(wxDC* dc);
void OnUpdate(wxView *sender, wxObject *hint = NULL);
bool OnClose (bool deleteWindow = true);
-
+
void OnEditCopy (wxCommandEvent& event);
void OnEditCut (wxCommandEvent& event);
void OnEditPaste (wxCommandEvent& event);
void OnRevert (wxCommandEvent& event);
- void OnExport (wxCommandEvent& event);
+ void OnExport (wxCommandEvent& event);
void OnProperties (wxCommandEvent& event);
- void OnCompare (wxCommandEvent& event);
+ void OnCompare (wxCommandEvent& event);
void OnScaleSize (wxCommandEvent& event);
void OnInvertValues (wxCommandEvent& event);
void OnSquare (wxCommandEvent& event);
void OnFFTCols (wxCommandEvent& event);
void OnIFFTCols (wxCommandEvent& event);
#endif
-
+
void OnMagnitude (wxCommandEvent& event);
void OnPhase (wxCommandEvent& event);
void OnReal (wxCommandEvent& event);
void OnImaginary (wxCommandEvent& event);
-
+
void OnScaleAuto (wxCommandEvent& event);
void OnScaleMinMax (wxCommandEvent& event);
void OnScaleFull (wxCommandEvent& event);
void OnPlotHistogram (wxCommandEvent& event);
void OnCompareRow (wxCommandEvent& event);
void OnCompareCol (wxCommandEvent& event);
-
+
#if CTSIM_MDI
wxDocMDIChildFrame* getFrame() { return m_pFrame; }
#else
wxMenu* getMenuAnalyze() { return m_pMenuAnalyze; }
- ImageFileDocument* GetDocument()
+ ImageFileDocument* GetDocument()
{ return dynamic_cast<ImageFileDocument*>(wxView::GetDocument()); }
-
+
DECLARE_EVENT_TABLE()
};
int m_xCursor;
int m_yCursor;
-
+
public:
ImageFileCanvas (ImageFileView* v, wxFrame *frame, const wxPoint& pos, const wxSize& size, const long style);
virtual ~ImageFileCanvas();
{
private:
DECLARE_DYNAMIC_CLASS(ProjectionFileView)
-
+
wxMemoryDC m_memoryDC;
wxBitmap* m_pBitmap;
-
+
ProjectionFileCanvas *CreateCanvas (wxFrame* parent);
#if CTSIM_MDI
wxDocMDIChildFrame* m_pFrame;
wxDocChildFrame* m_pFrame;
wxDocChildFrame* CreateChildFrame(wxDocument *doc, wxView *view);
#endif
-
+
ProjectionFileCanvas *m_pCanvas;
wxMenu* m_pFileMenu;
wxMenu* m_pReconstructMenu;
int m_iDefaultInterpParam;
int m_iDefaultBackprojector;
int m_iDefaultTrace;
-
+
int m_iDefaultPolarNX;
int m_iDefaultPolarNY;
int m_iDefaultPolarInterpolation;
int m_iDefaultPolarZeropad;
- wxWindow* getFrameForChild()
+ wxWindow* getFrameForChild()
#if CTSIM_MDI
{ return theApp->getMainFrame(); }
#else
virtual ~ProjectionFileView();
void canvasClosed()
{ m_pCanvas = NULL; m_pFrame = NULL; }
-
+
bool OnCreate(wxDocument *doc, long flags);
void OnDraw(wxDC* dc);
void OnUpdate(wxView *sender, wxObject *hint = NULL);
wxMenu* getFileMenu() { return m_pFileMenu; }
wxMenu* getReconstructMenu() { return m_pReconstructMenu; }
- ProjectionFileDocument* GetDocument()
+ ProjectionFileDocument* GetDocument()
{ return dynamic_cast<ProjectionFileDocument*>(wxView::GetDocument()); }
DECLARE_EVENT_TABLE()
};
private:
ProjectionFileView* m_pView;
-public:
+public:
ProjectionFileCanvas (ProjectionFileView* v, wxFrame *frame, const wxPoint& pos, const wxSize& size, const long style);
virtual ~ProjectionFileCanvas() ;
private:
DECLARE_DYNAMIC_CLASS(PhantomFileView)
DECLARE_EVENT_TABLE()
-
+
PhantomCanvas *CreateCanvas (wxFrame* parent);
#if CTSIM_MDI
wxDocMDIChildFrame* m_pFrame;
wxDocChildFrame* m_pFrame;
wxDocChildFrame* CreateChildFrame(wxDocument *doc, wxView *view);
#endif
-
+
PhantomCanvas *m_pCanvas;
wxMenu* m_pFileMenu;
-
+
int m_iDefaultNDet;
int m_iDefaultNView;
int m_iDefaultOffsetView;
double m_dDefaultCenterDetectorLength;
double m_dDefaultViewRatio;
double m_dDefaultScanRatio;
-
+
int m_iDefaultRasterNX;
int m_iDefaultRasterNY;
int m_iDefaultRasterNSamples;
double m_dDefaultRasterViewRatio;
- wxWindow* getFrameForChild()
+ wxWindow* getFrameForChild()
#if CTSIM_MDI
{ return theApp->getMainFrame(); }
#else
virtual ~PhantomFileView();
void canvasClosed()
{ m_pCanvas = NULL; m_pFrame = NULL; }
-
+
bool OnCreate(wxDocument *doc, long flags);
void OnUpdate(wxView *sender, wxObject *hint = NULL);
bool OnClose (bool deleteWindow = true);
void OnProperties (wxCommandEvent& event);
void OnRasterize (wxCommandEvent& event);
void OnProjections (wxCommandEvent& event);
-
- PhantomFileDocument* GetDocument()
+
+ PhantomFileDocument* GetDocument()
{ return dynamic_cast<PhantomFileDocument*>(wxView::GetDocument()); }
-
+
wxMenu* getFileMenu() { return m_pFileMenu; }
#if CTSIM_MDI
wxDocMDIChildFrame* getFrame() { return m_pFrame; }
private:
PhantomFileView* m_pView;
-public:
+public:
PhantomCanvas (PhantomFileView* v, wxFrame *frame, const wxPoint& pos, const wxSize& size, const long style);
virtual ~PhantomCanvas();
class PlotFileView : public wxView
{
DECLARE_DYNAMIC_CLASS(PlotFileView)
-
+
private:
#if CTSIM_MDI
wxDocMDIChildFrame* m_pFrame;
wxDocChildFrame* m_pFrame;
wxDocChildFrame* CreateChildFrame(wxDocument *doc, wxView *view);
#endif
-
+
PlotFileCanvas *m_pCanvas;
EZPlot* m_pEZPlot;
wxMenu* m_pFileMenu;
-
+
bool m_bMinSpecified;
bool m_bMaxSpecified;
double m_dMinPixel;
double m_dMaxPixel;
double m_dAutoScaleFactor;
-
+
PlotFileCanvas *CreateCanvas (wxFrame* parent);
- wxWindow* getFrameForChild()
+ wxWindow* getFrameForChild()
#if CTSIM_MDI
{ return theApp->getMainFrame(); }
#else
virtual ~PlotFileView();
void canvasClosed()
{ m_pCanvas = NULL; m_pFrame = NULL; }
-
+
bool OnCreate(wxDocument *doc, long flags);
void OnDraw(wxDC* dc);
void OnUpdate(wxView *sender, wxObject *hint = NULL);
void OnScaleMinMax (wxCommandEvent& event);
void OnScaleAuto (wxCommandEvent& event);
void OnScaleFull (wxCommandEvent& event);
-
+
#if CTSIM_MDI
wxDocMDIChildFrame* getFrame() { return m_pFrame; }
#else
wxDocChildFrame* getFrame() { return m_pFrame; }
#endif
-
+
void setInitialClientSize();
wxMenu* getFileMenu() { return m_pFileMenu; }
- PlotFileDocument* GetDocument()
+ PlotFileDocument* GetDocument()
{ return dynamic_cast<PlotFileDocument*>(wxView::GetDocument()); }
-
+
DECLARE_EVENT_TABLE()
};
{
private:
PlotFileView* m_pView;
-
+
public:
PlotFileCanvas (PlotFileView* v, wxFrame *frame, const wxPoint& pos, const wxSize& size, const long style);
virtual ~PlotFileCanvas();
-
+
virtual void OnDraw(wxDC& dc);
virtual wxSize GetBestSize() const;
#endif
wxMenu* m_pFileMenu;
TextFileCanvas *m_pCanvas;
-
+
public:
- TextFileView()
+ TextFileView()
: wxView() , m_pFrame(0), m_pCanvas(0)
{}
~TextFileView();
void OnUpdate (wxView *sender, wxObject *hint = (wxObject *) NULL);
bool OnClose (bool deleteWindow = TRUE);
- TextFileDocument* GetDocument()
+ TextFileDocument* GetDocument()
{ return dynamic_cast<TextFileDocument*>(wxView::GetDocument()); }
-
+
TextFileCanvas* getTextCtrl() { return m_pCanvas; }
wxMenu* getFileMenu() { return m_pFileMenu; }
#if CTSIM_MDI
{
TextFileView *m_pView;
-public:
+public:
TextFileCanvas (TextFileView *v, wxFrame *frame, const wxPoint& pos, const wxSize& size, long style);
~TextFileCanvas ();
virtual wxSize GetBestSize() const;
static void convertStringToArgcv (char* szLine, int* piArgc, char*** pppArgv);
-void
+void
ctsimtext_usage (const char *program)
{
std::cout << "usage: " << fileBasename(program) << " ctsim-function-name ctstim-function-parameters...\n";
std::cout << " phm2if Convert a geometric phantom into an imagefile\n";
std::cout << " phm2pj Take projections of a phantom object\n";
std::cout << " phm2helix Take projections of a phantom object\n";
- std::cout << " pjHinterp Interpolate helical projections of a phantom object\n";
+ std::cout << " pjHinterp Interpolate helical projections of a phantom object\n";
std::cout << " linogram Print linogram sampling\n";
}
-void
+void
interactive_usage ()
{
std::cout << "usage: function-name parameters...\n";
static bool s_bInteractive = false;
-int
+int
ctsimtext_main (int argc, char * argv[])
{
- int iReturn = 0;
+ int iReturn = 0;
if (argc > 1 && (strcmp(s_szProgramName, fileBasename (argv[0])) == 0 || strcmp(s_szProgramName2, fileBasename (argv[0])) == 0 || strcmp(s_szProgramName3, fileBasename (argv[0])) == 0)) {
argv++;
std::cout << ", Version " << VERSION;
#endif
std::cout << " (Type \"quit\" to end)\n\n";
-
+
while (1) {
#ifdef HAVE_READLINE
char* pszInputLine = readline (szPrompt);
break;
if (*pszInputLine != EOS)
add_history (pszInputLine);
-
+
#else // DONT_HAVE_READLINE
-
+
static const int s_MaxLineLength = 1024;
char* pszInputLine = new char [s_MaxLineLength+1];
std::cout << szPrompt;
std::cin.getline (pszInputLine, s_MaxLineLength);
-
+
#ifdef DEBUG
std::cout << "#" << pszInputLine << "#\n";
#endif
-
+
std::cout << std::flush;
std::cout << "\n";
#endif // DONT_HAVE_READLINE
-
- if (strncasecmp (pszInputLine, "quit", 4) == 0)
+
+ if (strncasecmp (pszInputLine, "quit", 4) == 0)
break;
-
+
convertStringToArgcv (pszInputLine, &argc, &argv);
#ifdef DEBUG
for (int i = 0; i < argc; i++)
std::cout << "Token " << i << ": " << argv[i] << "\n";
#endif
iReturn = processCommand (argc, argv);
-
+
delete pszInputLine;
}
}
-
+
return iReturn;
}
char* pCurrentPos = pszLine;
int nTokens = 0;
std::vector<char*> vecpszToken;
-
+
// Process line
bool bInDoubleQuote = false;
bool bInSingleQuote = false;
bool bInToken = false;
-
+
while (*pCurrentPos) {
if (isspace (*pCurrentPos)) {
if (! bInToken)
nTokens++;
vecpszToken.push_back (pCurrentPos);
}
-
+
pCurrentPos++;
}
-
+
*piArgc = nTokens;
if (nTokens > 0) {
*pppArgv = new char* [nTokens];
*pppArgv = NULL;
}
-static int
+static int
processCommand (int argc, char* const argv[])
{
if (argc < 1)
return 1;
-
+
const char* const pszFunction = fileBasename (argv[0]);
- try {
+ try {
if (strcasecmp (pszFunction, "if1") == 0)
return if1_main (argc, argv);
else if (strcasecmp (pszFunction, "if2") == 0)
std::cerr << "Exception: " << e.what() << std::endl;
} catch (...) {
std::cerr << "Unknown exception caught\n";
- }
+ }
return 1;
}
-int
+int
main (int argc, char* argv[])
{
-#if defined(HAVE_FFTW) && defined(HAVE_GETENV)
+#if defined(HAVE_FFTW) && defined(HAVE_GETENV)
const char* const pszHome = getenv("HOME");
char* pszWisdom = NULL;
pszWisdom[nHome] = '/';
strcpy(pszWisdom+nHome+1,szFileBase);
pszWisdom[nHome+nBase+2] = 0;
-
+
FILE *wisdom = fopen(pszWisdom,"r");
- if (wisdom) {
+ if (wisdom) {
fftw_import_wisdom_from_file(wisdom);
fclose(wisdom);
}
#endif
int retval = ctsimtext_main(argc, argv);
-
-#if defined(HAVE_FFTW) && defined(HAVE_GETENV)
+
+#if defined(HAVE_FFTW) && defined(HAVE_GETENV)
if (pszWisdom) {
FILE* wisdom = fopen(pszWisdom,"w+");
if (wisdom) {
}
}
#endif
-
+
return retval;
}
static const char* g_szIdStr = "$Id$";
-void
+void
if1_usage (const char *program)
{
std::cout << "usage: " << fileBasename(program) << " infile outfile [OPTIONS]" << std::endl;
std::cout << " --help Print this help message" << std::endl;
}
-int
+int
if1_main (int argc, char *const argv[])
{
char *in_file;
while (1)
{
int c = getopt_long (argc, argv, "", my_options, NULL);
-
+
if (c == -1)
- break;
-
+ break;
+
switch (c)
- {
- case O_INVERT:
- opt_invert = 1;
- break;
- case O_LOG:
- opt_log = 1;
- break;
- case O_SQR:
- opt_sqr = 1;
- break;
- case O_SQRT:
- opt_sqrt = 1;
- break;
- case O_EXP:
- opt_exp = 1;
- break;
- case O_VERBOSE:
- opt_verbose = 1;
- break;
+ {
+ case O_INVERT:
+ opt_invert = 1;
+ break;
+ case O_LOG:
+ opt_log = 1;
+ break;
+ case O_SQR:
+ opt_sqr = 1;
+ break;
+ case O_SQRT:
+ opt_sqrt = 1;
+ break;
+ case O_EXP:
+ opt_exp = 1;
+ break;
+ case O_VERBOSE:
+ opt_verbose = 1;
+ break;
case O_VERSION:
#ifdef VERSION
- std::cout << "Version " << VERSION << std::endl << g_szIdStr << std::endl;
+ std::cout << "Version " << VERSION << std::endl << g_szIdStr << std::endl;
#else
std::cout << "Unknown version number" << std::endl;
#endif
- return (0);
- case O_HELP:
- case '?':
- if1_usage(argv[0]);
- return (0);
- default:
- if1_usage(argv[0]);
- return (1);
- }
+ return (0);
+ case O_HELP:
+ case '?':
+ if1_usage(argv[0]);
+ return (0);
+ default:
+ if1_usage(argv[0]);
+ return (1);
+ }
}
if (optind + 2 != argc)
if1_usage(argv[0]);
return (1);
}
-
+
in_file = argv[optind];
out_file = argv[optind + 1];
}
#ifndef NO_MAIN
-int
+int
main (int argc, char *const argv[])
{
int retval = 1;
static const char* g_szIdStr = "$Id$";
-void
+void
if2_usage (const char *program)
{
std::cout << "usage: " << fileBasename(program) << " infile1 infile2 outfile [OPTIONS]\n";
std::cout << " --help Print this help message\n";
}
-int
+int
if2_main (int argc, char *const argv[])
{
ImageFile* pim_in1;
int opt_rowPlot = -1;
int opt_columnPlot = -1;
Timer timerProgram;
-
+
while (1) {
char* endptr;
int c = getopt_long (argc, argv, "", my_options, NULL);
-
+
if (c == -1)
break;
-
+
switch (c) {
case O_ADD:
opt_add = 1;
return (1);
}
}
-
+
if ((opt_bImageOutputFile || opt_bPlotOutputFile) && (optind + 3 != argc)) {
if2_usage(argv[0]);
return (1);
if2_usage(argv[0]);
return (1);
}
-
+
in_file1 = argv[optind];
in_file2 = argv[optind + 1];
if (opt_bImageOutputFile || opt_bPlotOutputFile)
strOutFile = argv[optind + 2];
-
+
pim_in1 = new ImageFile ();
pim_in2 = new ImageFile ();
ImageFile& im_in1 = *pim_in1;
ImageFile& im_in2 = *pim_in2;
-
+
if (! im_in1.fileRead(in_file1) || ! im_in2.fileRead(in_file2)) {
sys_error (ERR_WARNING, "Error reading an image");
return (1);
}
-
+
if (im_in1.nx() != im_in2.nx() || im_in1.ny() != im_in2.ny()) {
sys_error (ERR_SEVERE, "Error: Size of image 1 (%d,%d) and image 2 (%d,%d) do not match",
im_in1.nx(), im_in1.ny(), im_in2.nx(), im_in2.ny());
sys_error (ERR_SEVERE, "Error: Size of image < 0");
return(1);
}
-
+
ImageFileArray v1 = im_in1.getArray();
ImageFileArray v2 = im_in2.getArray();
ImageFileArray vout = NULL;
-
+
if (opt_bImageOutputFile && opt_bPlotOutputFile) {
sys_error (ERR_SEVERE, "Both Image and Plot output files can not be selected simultaneously");
return (1);
pim_out = new ImageFile (im_in1.nx(), im_in1.ny());
vout = pim_out->getArray();
}
-
+
std::string strOperation;
int nx = im_in1.nx();
int ny = im_in1.ny();
int nx2 = im_in2.nx();
int ny2 = im_in2.ny();
-
+
if (opt_add) {
strOperation = "Add Images";
im_in1.addImages (im_in2, *pim_out);
im_in1.comparativeStatistics (im_in2, d, r, e);
std::cout << "d=" << d << ", r=" << r << ", e=" << e << std::endl;
}
-
+
int i;
if (opt_columnPlot > 0) {
if (opt_columnPlot >= nx || opt_columnPlot >= nx2) {
double* plot_xaxis = new double [nx];
for (i = 0; i < nx; i++)
plot_xaxis[i] = i;
-
+
PlotFile plotFile (3, nx);
-
+
plotFile.addColumn (0, plot_xaxis);
plotFile.addColumn (1, v1[opt_columnPlot]);
plotFile.addColumn (2, v2[opt_columnPlot]);
plotFile.addEzsetCommand ("xticks major 5");
plotFile.fileWrite (strOutFile.c_str());
-
+
delete plot_xaxis;
}
-
+
if (opt_rowPlot > 0) {
if (opt_rowPlot >= ny || opt_rowPlot >= ny2) {
sys_error (ERR_SEVERE, "row_plot > ny");
double* plot_xaxis = new double [ny];
double* v1Row = new double [ny];
double* v2Row = new double [ny2];
-
+
for (i = 0; i < ny; i++)
plot_xaxis[i] = i;
for (i = 0; i < ny; i++)
v1Row[i] = v1[i][opt_rowPlot];
for (i = 0; i < ny2; i++)
v2Row[i] = v2[i][opt_rowPlot];
-
+
PlotFile plotFile (3, ny);
-
+
plotFile.addColumn (0, plot_xaxis);
plotFile.addColumn (1, v1Row);
plotFile.addColumn (2, v2Row);
plotFile.addEzsetCommand ("box");
plotFile.addEzsetCommand ("grid");
plotFile.addEzsetCommand ("xticks major 5");
-
+
plotFile.fileWrite (strOutFile.c_str());
-
+
delete plot_xaxis;
delete v1Row;
delete v2Row;
}
-
+
if (opt_bImageOutputFile) {
pim_out->labelsCopy (im_in1, "if2 file 1: ");
pim_out->labelsCopy (im_in2, "if2 file 2: ");
pim_out->labelAdd (Array2dFileLabel::L_HISTORY, strOperation.c_str(), timerProgram.timerEnd());
pim_out->fileWrite (strOutFile);
}
-
+
return (0);
}
#ifndef NO_MAIN
-int
+int
main (int argc, char *const argv[])
{
int retval = 1;
-
+
try {
retval = if2_main(argc, argv);
} catch (exception e) {
} catch (...) {
std::cerr << "Unknown exception\n";
}
-
+
return (retval);
}
#endif
#include "ct.h"
-enum { O_SCALE, O_MIN, O_MAX, O_AUTO, O_CENTER, O_STATS, O_FORMAT, O_LABELS,
+enum { O_SCALE, O_MIN, O_MAX, O_AUTO, O_CENTER, O_STATS, O_FORMAT, O_LABELS,
O_HELP, O_VERBOSE, O_VERSION, O_DEBUG };
static struct option my_options[] =
static const char O_FORMAT_PGMASC_STR[]="pgmasc";
static const char O_FORMAT_RAW_STR[]="raw";
-void
+void
ifexport_usage (const char *program)
{
std::cout << "usage: " << fileBasename(program) << " ifname outfile [OPTIONS]\n";
}
-int
+int
ifexport_main (int argc, char *const argv[])
{
ImageFile* pim = NULL;
int c = getopt_long (argc, argv, "", my_options, NULL);
char *endptr = NULL;
char *endstr;
-
+
if (c == -1)
- break;
-
+ break;
+
switch (c)
- {
- case O_MIN:
- opt_set_min = 1;
- densmin = strtod(optarg, &endptr);
- endstr = optarg + strlen(optarg);
- if (endptr != endstr)
- {
- sys_error (ERR_SEVERE, "Error setting --min to %s", optarg);
- ifexport_usage(argv[0]);
- return (1);
- }
- break;
- case O_MAX:
- opt_set_max = 1;
- densmax = strtod(optarg, &endptr);
- endstr = optarg + strlen(optarg);
- if (endptr != endstr)
- {
- sys_error (ERR_SEVERE, "Error setting --max to %s", optarg);
- ifexport_usage(argv[0]);
- return (1);
- }
- break;
- case O_SCALE:
- opt_scale = strtol(optarg, &endptr, 10);
- endstr = optarg + strlen(optarg);
- if (endptr != endstr)
- {
- sys_error (ERR_SEVERE, "Error setting --scale to %s", optarg);
- ifexport_usage(argv[0]);
- return (1);
- }
- break;
- case O_AUTO:
- if (strcmp(optarg, O_AUTO_FULL_STR) == 0)
- opt_auto = O_AUTO_FULL;
- else if (strcmp(optarg, O_AUTO_STD1_STR) == 0)
- opt_auto = O_AUTO_STD1;
- else if (strcmp(optarg, O_AUTO_STD0_5_STR) == 0)
- opt_auto = O_AUTO_STD0_5;
- else if (strcmp(optarg, O_AUTO_STD0_1_STR) == 0)
- opt_auto = O_AUTO_STD0_1;
- else if (strcmp(optarg, O_AUTO_STD2_STR) == 0)
- opt_auto = O_AUTO_STD2;
- else if (strcmp(optarg, O_AUTO_STD3_STR) == 0)
- opt_auto = O_AUTO_STD3;
- else
- {
- sys_error (ERR_SEVERE, "Invalid auto mode %s", optarg);
- ifexport_usage(argv[0]);
- return (1);
- }
- break;
- case O_CENTER:
- if (strcmp(optarg, O_CENTER_MEDIAN_STR) == 0)
- opt_center = O_CENTER_MEDIAN;
- else if (strcmp(optarg, O_CENTER_MEAN_STR) == 0)
- opt_center = O_CENTER_MEAN;
- else if (strcmp(optarg, O_CENTER_MODE_STR) == 0)
- opt_center = O_CENTER_MODE;
- else
- {
- sys_error (ERR_SEVERE, "Invalid center mode %s", optarg);
- ifexport_usage(argv[0]);
- return (1);
- }
- break;
- case O_FORMAT:
- if (strcmp(optarg, O_FORMAT_PGM_STR) == 0)
- opt_format = O_FORMAT_PGM;
- else if (strcmp(optarg, O_FORMAT_PGMASC_STR) == 0)
- opt_format = O_FORMAT_PGMASC;
+ {
+ case O_MIN:
+ opt_set_min = 1;
+ densmin = strtod(optarg, &endptr);
+ endstr = optarg + strlen(optarg);
+ if (endptr != endstr)
+ {
+ sys_error (ERR_SEVERE, "Error setting --min to %s", optarg);
+ ifexport_usage(argv[0]);
+ return (1);
+ }
+ break;
+ case O_MAX:
+ opt_set_max = 1;
+ densmax = strtod(optarg, &endptr);
+ endstr = optarg + strlen(optarg);
+ if (endptr != endstr)
+ {
+ sys_error (ERR_SEVERE, "Error setting --max to %s", optarg);
+ ifexport_usage(argv[0]);
+ return (1);
+ }
+ break;
+ case O_SCALE:
+ opt_scale = strtol(optarg, &endptr, 10);
+ endstr = optarg + strlen(optarg);
+ if (endptr != endstr)
+ {
+ sys_error (ERR_SEVERE, "Error setting --scale to %s", optarg);
+ ifexport_usage(argv[0]);
+ return (1);
+ }
+ break;
+ case O_AUTO:
+ if (strcmp(optarg, O_AUTO_FULL_STR) == 0)
+ opt_auto = O_AUTO_FULL;
+ else if (strcmp(optarg, O_AUTO_STD1_STR) == 0)
+ opt_auto = O_AUTO_STD1;
+ else if (strcmp(optarg, O_AUTO_STD0_5_STR) == 0)
+ opt_auto = O_AUTO_STD0_5;
+ else if (strcmp(optarg, O_AUTO_STD0_1_STR) == 0)
+ opt_auto = O_AUTO_STD0_1;
+ else if (strcmp(optarg, O_AUTO_STD2_STR) == 0)
+ opt_auto = O_AUTO_STD2;
+ else if (strcmp(optarg, O_AUTO_STD3_STR) == 0)
+ opt_auto = O_AUTO_STD3;
+ else
+ {
+ sys_error (ERR_SEVERE, "Invalid auto mode %s", optarg);
+ ifexport_usage(argv[0]);
+ return (1);
+ }
+ break;
+ case O_CENTER:
+ if (strcmp(optarg, O_CENTER_MEDIAN_STR) == 0)
+ opt_center = O_CENTER_MEDIAN;
+ else if (strcmp(optarg, O_CENTER_MEAN_STR) == 0)
+ opt_center = O_CENTER_MEAN;
+ else if (strcmp(optarg, O_CENTER_MODE_STR) == 0)
+ opt_center = O_CENTER_MODE;
+ else
+ {
+ sys_error (ERR_SEVERE, "Invalid center mode %s", optarg);
+ ifexport_usage(argv[0]);
+ return (1);
+ }
+ break;
+ case O_FORMAT:
+ if (strcmp(optarg, O_FORMAT_PGM_STR) == 0)
+ opt_format = O_FORMAT_PGM;
+ else if (strcmp(optarg, O_FORMAT_PGMASC_STR) == 0)
+ opt_format = O_FORMAT_PGMASC;
#if HAVE_PNG
- else if (strcmp(optarg, O_FORMAT_PNG_STR) == 0)
- opt_format = O_FORMAT_PNG;
- else if (strcmp(optarg, O_FORMAT_PNG16_STR) == 0)
- opt_format = O_FORMAT_PNG16;
+ else if (strcmp(optarg, O_FORMAT_PNG_STR) == 0)
+ opt_format = O_FORMAT_PNG;
+ else if (strcmp(optarg, O_FORMAT_PNG16_STR) == 0)
+ opt_format = O_FORMAT_PNG16;
#endif
- else if (strcmp(optarg, O_FORMAT_RAW_STR) == 0)
- opt_format = O_FORMAT_RAW;
+ else if (strcmp(optarg, O_FORMAT_RAW_STR) == 0)
+ opt_format = O_FORMAT_RAW;
#if HAVE_GIF
- else if (strcmp(optarg, O_FORMAT_GIF_STR) == 0)
- opt_format = O_FORMAT_GIF;
+ else if (strcmp(optarg, O_FORMAT_GIF_STR) == 0)
+ opt_format = O_FORMAT_GIF;
#endif
else {
- sys_error (ERR_SEVERE, "Invalid format mode %s", optarg);
- ifexport_usage(argv[0]);
- return (1);
- }
- break;
- case O_LABELS:
- opt_labels = 1;
- break;
- case O_VERBOSE:
- opt_verbose = 1;
- break;
- case O_DEBUG:
- opt_debug = 1;
- break;
- case O_STATS:
- opt_stats = 1;
- break;
+ sys_error (ERR_SEVERE, "Invalid format mode %s", optarg);
+ ifexport_usage(argv[0]);
+ return (1);
+ }
+ break;
+ case O_LABELS:
+ opt_labels = 1;
+ break;
+ case O_VERBOSE:
+ opt_verbose = 1;
+ break;
+ case O_DEBUG:
+ opt_debug = 1;
+ break;
+ case O_STATS:
+ opt_stats = 1;
+ break;
case O_VERSION:
#ifdef VERSION
- std::cout << "Version " << VERSION << std::endl << g_szIdStr << std::endl;
+ std::cout << "Version " << VERSION << std::endl << g_szIdStr << std::endl;
#else
std::cout << "Unknown version number\n";
#endif
- return (0);
- case O_HELP:
- case '?':
- ifexport_usage(argv[0]);
- return (0);
- default:
- ifexport_usage(argv[0]);
- return (1);
- }
+ return (0);
+ case O_HELP:
+ case '?':
+ ifexport_usage(argv[0]);
+ return (0);
+ default:
+ ifexport_usage(argv[0]);
+ return (1);
+ }
}
if (optind + 2 != argc) {
ifexport_usage(argv[0]);
return (1);
}
-
+
in_file = argv[optind];
out_file = argv[optind+1];
double min, max, mean, mode, median, stddev;
double window = 0;
im.statistics(min, max, mean, mode, median, stddev);
-
+
if (opt_auto == O_AUTO_FULL) {
- if (! opt_set_max)
- densmax = max;
- if (! opt_set_min)
- densmin = min;
+ if (! opt_set_max)
+ densmax = max;
+ if (! opt_set_min)
+ densmin = min;
}
if (opt_stats || opt_auto != O_AUTO_FULL) {
- if (opt_auto == O_AUTO_FULL)
- ;
- else if (opt_auto == O_AUTO_STD1)
- window = stddev;
- else if (opt_auto == O_AUTO_STD0_1)
- window = stddev * 0.1;
- else if (opt_auto == O_AUTO_STD0_5)
- window = stddev * 0.5;
- else if (opt_auto == O_AUTO_STD2)
- window = stddev * 2;
- else if (opt_auto == O_AUTO_STD3)
- window = stddev * 3;
- else {
- sys_error (ERR_SEVERE, "Internal Error: Invalid auto mode %d", opt_auto);
- return (1);
- }
+ if (opt_auto == O_AUTO_FULL)
+ ;
+ else if (opt_auto == O_AUTO_STD1)
+ window = stddev;
+ else if (opt_auto == O_AUTO_STD0_1)
+ window = stddev * 0.1;
+ else if (opt_auto == O_AUTO_STD0_5)
+ window = stddev * 0.5;
+ else if (opt_auto == O_AUTO_STD2)
+ window = stddev * 2;
+ else if (opt_auto == O_AUTO_STD3)
+ window = stddev * 3;
+ else {
+ sys_error (ERR_SEVERE, "Internal Error: Invalid auto mode %d", opt_auto);
+ return (1);
+ }
}
if (opt_stats) {
- std::cout <<"nx: " << im.nx() << std::endl;
- std::cout <<"ny: " << im.ny() << std::endl;
- std::cout <<"min: " << min << std::endl;
- std::cout <<"max: " << max << std::endl;
- std::cout <<"mean: " << mean << std::endl;
- std::cout <<"mode: " << mode << std::endl;
- std::cout <<"stddev: " << stddev << std::endl;
+ std::cout <<"nx: " << im.nx() << std::endl;
+ std::cout <<"ny: " << im.ny() << std::endl;
+ std::cout <<"min: " << min << std::endl;
+ std::cout <<"max: " << max << std::endl;
+ std::cout <<"mean: " << mean << std::endl;
+ std::cout <<"mode: " << mode << std::endl;
+ std::cout <<"stddev: " << stddev << std::endl;
}
if (opt_auto != O_AUTO_FULL) {
- double center;
-
- if (opt_center == O_CENTER_MEDIAN)
- center = median;
- else if (opt_center == O_CENTER_MODE)
- center = mode;
- else if (opt_center == O_CENTER_MEAN)
- center = mean;
- else {
- sys_error (ERR_SEVERE, "Internal Error: Invalid center mode %d", opt_center);
- return (1);
- }
- if (! opt_set_max)
- densmax = center + window;
- if (! opt_set_min)
- densmin = center - window;
+ double center;
+
+ if (opt_center == O_CENTER_MEDIAN)
+ center = median;
+ else if (opt_center == O_CENTER_MODE)
+ center = mode;
+ else if (opt_center == O_CENTER_MEAN)
+ center = mean;
+ else {
+ sys_error (ERR_SEVERE, "Internal Error: Invalid center mode %d", opt_center);
+ return (1);
+ }
+ if (! opt_set_max)
+ densmax = center + window;
+ if (! opt_set_min)
+ densmin = center - window;
}
}
-
+
if (opt_stats) {
std::cout << "min display: " << densmin << std::endl;
std::cout << "max display: " << densmax << std::endl;
}
-
+
if (opt_format == O_FORMAT_PGM)
im.writeImagePGM (out_file, opt_scale, opt_scale, densmin, densmax);
else if (opt_format == O_FORMAT_PGMASC)
im.writeImagePNG (out_file, 16, opt_scale, opt_scale, densmin, densmax);
#endif
#if HAVE_GIF
- else if (opt_format == O_FORMAT_GIF)
+ else if (opt_format == O_FORMAT_GIF)
im.writeImageGIF (out_file, opt_scale, opt_scale, densmin, densmax);
#endif
else if (opt_format == O_FORMAT_RAW)
- im.writeImageRaw (out_file, opt_scale, opt_scale);
+ im.writeImageRaw (out_file, opt_scale, opt_scale);
else
{
sys_error (ERR_SEVERE, "Internal Error: Invalid format mode %d", opt_format);
#ifndef NO_MAIN
-int
+int
main (int argc, char *const argv[])
{
int retval = 1;
try {
retval = ifexport_main(argc, argv);
} catch (exception e) {
- std::cerr << "Exception: " << e.what() << std::endl;
+ std::cerr << "Exception: " << e.what() << std::endl;
} catch (...) {
- std::cerr << "Unknown exception\n";
+ std::cerr << "Unknown exception\n";
}
return (retval);
static const char* g_szIdStr = "$Id$";
-void
+void
ifinfo_usage (const char *program)
{
std::cout << "usage: " << fileBasename(program) << " image-filename [OPTIONS]\n";
std::cout << " --help Print this help message\n";
}
-int
+int
ifinfo_main (int argc, char *const argv[])
{
ImageFile *im = NULL;
while (1)
{
int c = getopt_long (argc, argv, "", my_options, NULL);
-
+
if (c == -1)
- break;
-
+ break;
+
switch (c)
- {
- case O_LABELS:
- opt_labels = 1;
- break;
- case O_STATS:
- opt_stats = 1;
- break;
- case O_NO_LABELS:
- opt_labels = 0;
- break;
- case O_NO_STATS:
- opt_stats = 0;
- break;
- case O_VERBOSE:
- opt_verbose = 1;
- break;
- case O_DEBUG:
- opt_debug = 0;
- break;
+ {
+ case O_LABELS:
+ opt_labels = 1;
+ break;
+ case O_STATS:
+ opt_stats = 1;
+ break;
+ case O_NO_LABELS:
+ opt_labels = 0;
+ break;
+ case O_NO_STATS:
+ opt_stats = 0;
+ break;
+ case O_VERBOSE:
+ opt_verbose = 1;
+ break;
+ case O_DEBUG:
+ opt_debug = 0;
+ break;
case O_VERSION:
#ifdef VERSION
- std::cout << "Version " << VERSION << std::endl << g_szIdStr << std::endl;
+ std::cout << "Version " << VERSION << std::endl << g_szIdStr << std::endl;
#else
std::cout << "Unknown version number\n";
#endif
- return (0);
- case O_HELP:
- case '?':
- ifinfo_usage(argv[0]);
- return (0);
- default:
- ifinfo_usage(argv[0]);
- return (1);
- }
+ return (0);
+ case O_HELP:
+ case '?':
+ ifinfo_usage(argv[0]);
+ return (0);
+ default:
+ ifinfo_usage(argv[0]);
+ return (1);
+ }
}
if (optind + 1 != argc) {
ifinfo_usage (argv[0]);
return (1);
}
-
+
in_file = argv[optind];
im = new ImageFile ();
return (1);
}
- if (opt_labels)
+ if (opt_labels)
im->printLabels (std::cout);
if (opt_stats) {
std::cout << "Data type: ";
if (im->dataType() == Array2dFile::DATA_TYPE_COMPLEX)
std::cout << "Complex\n";
- else
+ else
std::cout << "Real\n";
im->printStatistics (std::cout);
}
#ifndef NO_MAIN
-int
+int
main (int argc, char *const argv[])
{
int retval = 1;
try {
retval = ifinfo_main(argc, argv);
} catch (exception e) {
- std::cerr << "Exception: " << e.what() << std::endl;
+ std::cerr << "Exception: " << e.what() << std::endl;
} catch (...) {
- std::cerr << "Unknown exception\n";
+ std::cerr << "Unknown exception\n";
}
return (retval);
static const char* g_szIdStr = "$Id$";
-void
+void
linogram_usage (const char *program)
{
std::cout << "usage: " << fileBasename(program) << " n d [OPTIONS]\n";
std::cout << " --help Print this help message\n";
}
-int
+int
linogram_main (int argc, char *const argv[])
{
int opt_polar_rt = 0;
while (1)
{
int c = getopt_long (argc, argv, "", my_options, NULL);
-
+
if (c == -1)
- break;
-
+ break;
+
switch (c)
- {
- case O_XY:
- opt_xy = 1;
- break;
- case O_POLAR_RT:
- opt_polar_rt = 1;
- break;
- case O_VERBOSE:
- opt_verbose = 1;
- break;
- case O_DEBUG:
- opt_debug = 0;
- break;
+ {
+ case O_XY:
+ opt_xy = 1;
+ break;
+ case O_POLAR_RT:
+ opt_polar_rt = 1;
+ break;
+ case O_VERBOSE:
+ opt_verbose = 1;
+ break;
+ case O_DEBUG:
+ opt_debug = 0;
+ break;
case O_VERSION:
#ifdef VERSION
- std::cout << "Version " << VERSION << std::endl << g_szIdStr << std::endl;
+ std::cout << "Version " << VERSION << std::endl << g_szIdStr << std::endl;
#else
std::cout << "Unknown version number\n";
#endif
- return (0);
- case O_HELP:
- case '?':
- linogram_usage(argv[0]);
- return (0);
- default:
- linogram_usage(argv[0]);
- return (1);
- }
+ return (0);
+ case O_HELP:
+ case '?':
+ linogram_usage(argv[0]);
+ return (0);
+ default:
+ linogram_usage(argv[0]);
+ return (1);
+ }
}
if (optind + 2 != argc) {
linogram_usage (argv[0]);
return (1);
}
-
+
const char* in_n = argv[optind];
const char* in_d = argv[optind+1];
int min = -max;
double theta_base = PI/4;
// theta_base = 0;
-
+
double theta_vec [size];
for (int i = 0; i < size; i++) {
int m = i - (2 * n + 1);
for (m = 0; m < size; m++) {
double step = d * cos(theta_vec[m]);
for (int id = min; id <= max; id++) {
- double r = id * step;
- double x = r * cos(theta_vec[m] + theta_base);
- double y = r * sin(theta_vec[m] + theta_base);
- printf ("%lf,%lf ", x, y);
+ double r = id * step;
+ double x = r * cos(theta_vec[m] + theta_base);
+ double y = r * sin(theta_vec[m] + theta_base);
+ printf ("%lf,%lf ", x, y);
}
printf ("\n");
}
-
+
for (m = 0; m < size; m++) {
double step = d * cos(theta_vec[m]);
for (int id = min; id <= max; id++) {
- double r = id * step;
- double x = r * cos(theta_vec[m] + PI/2 + theta_base);
- double y = r * sin(theta_vec[m] + PI/2 + theta_base);
- printf ("%lf,%lf ", x, y);
+ double r = id * step;
+ double x = r * cos(theta_vec[m] + PI/2 + theta_base);
+ double y = r * sin(theta_vec[m] + PI/2 + theta_base);
+ printf ("%lf,%lf ", x, y);
}
printf ("\n");
}
int m;
for (m = 0; m < size; m++) {
if (! opt_polar_rt)
- printf ("%lf: ", theta_vec[m] + theta_base);
+ printf ("%lf: ", theta_vec[m] + theta_base);
double step = d * cos(theta_vec[m]);
for (int id = min; id <= max; id++) {
- if (opt_polar_rt)
- printf ("%lf,", theta_vec[m] + theta_base);
- printf ("%lf ", id * step);
+ if (opt_polar_rt)
+ printf ("%lf,", theta_vec[m] + theta_base);
+ printf ("%lf ", id * step);
}
printf ("\n");
}
-
+
for (m = 0; m < size; m++) {
if (! opt_polar_rt)
- printf ("%lf: ", theta_vec[m] + PI/2 + theta_base);
+ printf ("%lf: ", theta_vec[m] + PI/2 + theta_base);
double step = d * cos(theta_vec[m]);
for (int id = min; id <= max; id++) {
- if (opt_polar_rt)
- printf ("%lf,", theta_vec[m] + PI/2 + theta_base);
- printf ("%lf ", id * step);
+ if (opt_polar_rt)
+ printf ("%lf,", theta_vec[m] + PI/2 + theta_base);
+ printf ("%lf ", id * step);
}
printf ("\n");
}
}
-
+
return (0);
}
#ifndef NO_MAIN
-int
+int
main (int argc, char *const argv[])
{
int retval = 1;
try {
retval = linogram_main(argc, argv);
} catch (exception e) {
- std::cerr << "Exception: " << e.what() << std::endl;
+ std::cerr << "Exception: " << e.what() << std::endl;
} catch (...) {
- std::cerr << "Unknown exception\n";
+ std::cerr << "Unknown exception\n";
}
return (retval);
}
-void
+void
MPIWorld::setTotalWorkUnits(int totalWorkUnits)
{
if (m_nProcessors < 1)
currWorkUnits += m_vLocalWorkUnits[iProc];
}
-
+
}
void
if (m_myRank == 0)
strcpy (buf, str.c_str());
-
+
m_comm.Bcast (buf, len + 1, MPI::CHAR, 0);
if (m_myRank > 0)
enum { O_PHANTOMPROG, O_PHMFILE, O_DESC, O_NRAY, O_ROTANGLE, O_GEOMETRY, O_FOCAL_LENGTH, O_CENTER_DETECTOR_LENGTH,
O_VIEW_RATIO, O_SCAN_RATIO, O_OFFSETVIEW, O_TRACE, O_VERBOSE, O_HELP, O_DEBUG, O_VERSION };
-static struct option phm2helix_options[] =
+static struct option phm2helix_options[] =
{
{"phantom", 1, 0, O_PHANTOMPROG},
{"desc", 1, 0, O_DESC},
static const char* g_szIdStr = "$Id$";
-void
+void
phm2helix_usage (const char *program)
{
- std::cout << "usage: " << fileBasename(program) << " outfile ndet nview phmprog [OPTIONS]\n";
- std::cout << "Calculate (projections) through time varying phantom object \n\n";
- std::cout << " outfile Name of output file for projectsions\n";
- std::cout << " ndet Number of detectors\n";
- std::cout << " nview Number of rotated views\n";
- std::cout << " phmprog Name of phm generation executable\n";
- std::cout << " --phmfile Temp phantom file name \n";
- std::cout << " --desc Description of raysum\n";
- std::cout << " --nray Number of rays per detector (default = 1)\n";
- std::cout << " --rotangle Angle to rotate view through (fraction of a circle)\n";
- std::cout << " (default = select appropriate for geometry)\n";
- std::cout << " --geometry Geometry of scanning\n";
- std::cout << " parallel Parallel scan beams (default)\n";
- std::cout << " equilinear Equilinear divergent scan beams\n";
- std::cout << " equiangular Equiangular divergent scan beams\n";
- std::cout << " --focal-length Focal length ratio (ratio to radius of phantom)\n";
- std::cout << " (default = 1)\n";
- std::cout << " --view-ratio Length to view (view diameter to phantom diameter)\n";
- std::cout << " (default = 1)\n";
- std::cout << " --scan-ratio Length to scan (scan diameter to view diameter)\n";
- std::cout << " (default = 1)\n";
- std::cout << " --offsetview Intial gantry offset in 'views' (default = 0)\n";
- std::cout << " --trace Trace level to use\n";
- std::cout << " none No tracing (default)\n";
- std::cout << " console Trace text level\n";
- std::cout << " --verbose Verbose mode\n";
- std::cout << " --debug Debug mode\n";
- std::cout << " --version Print version\n";
- std::cout << " --help Print this help message\n";
+ std::cout << "usage: " << fileBasename(program) << " outfile ndet nview phmprog [OPTIONS]\n";
+ std::cout << "Calculate (projections) through time varying phantom object \n\n";
+ std::cout << " outfile Name of output file for projectsions\n";
+ std::cout << " ndet Number of detectors\n";
+ std::cout << " nview Number of rotated views\n";
+ std::cout << " phmprog Name of phm generation executable\n";
+ std::cout << " --phmfile Temp phantom file name \n";
+ std::cout << " --desc Description of raysum\n";
+ std::cout << " --nray Number of rays per detector (default = 1)\n";
+ std::cout << " --rotangle Angle to rotate view through (fraction of a circle)\n";
+ std::cout << " (default = select appropriate for geometry)\n";
+ std::cout << " --geometry Geometry of scanning\n";
+ std::cout << " parallel Parallel scan beams (default)\n";
+ std::cout << " equilinear Equilinear divergent scan beams\n";
+ std::cout << " equiangular Equiangular divergent scan beams\n";
+ std::cout << " --focal-length Focal length ratio (ratio to radius of phantom)\n";
+ std::cout << " (default = 1)\n";
+ std::cout << " --view-ratio Length to view (view diameter to phantom diameter)\n";
+ std::cout << " (default = 1)\n";
+ std::cout << " --scan-ratio Length to scan (scan diameter to view diameter)\n";
+ std::cout << " (default = 1)\n";
+ std::cout << " --offsetview Intial gantry offset in 'views' (default = 0)\n";
+ std::cout << " --trace Trace level to use\n";
+ std::cout << " none No tracing (default)\n";
+ std::cout << " console Trace text level\n";
+ std::cout << " --verbose Verbose mode\n";
+ std::cout << " --debug Debug mode\n";
+ std::cout << " --version Print version\n";
+ std::cout << " --help Print this help message\n";
}
-int
+int
phm2helix_main (int argc, char* const argv[])
{
- Phantom phm;
- std::string optGeometryName = Scanner::convertGeometryIDToName(Scanner::GEOMETRY_PARALLEL);
- char *opt_outfile = NULL;
- std::string opt_desc;
- std::string opt_PhmProg;
- std::string opt_PhmFileName = "tmpphmfile";
- int opt_ndet;
- int opt_nview;
- int opt_offsetview = 0;
- int opt_nray = 1;
- double dOptFocalLength = 2.;
- double dOptCenterDetectorLength = 2;
- double dOptViewRatio = 1.;
- double dOptScanRatio = 1.;
- int opt_trace = Trace::TRACE_NONE;
- int opt_verbose = 0;
- int opt_debug = 0;
- double opt_rotangle = -1;
- char* endptr = NULL;
- char* endstr;
-
- Timer timerProgram;
-
- while (1) {
- int c = getopt_long(argc, argv, "", phm2helix_options, NULL);
-
- if (c == -1)
- break;
-
- switch (c) {
- case O_VERBOSE:
- opt_verbose = 1;
- break;
- case O_DEBUG:
- opt_debug = 1;
- break;
- case O_TRACE:
- if ((opt_trace = Trace::convertTraceNameToID(optarg))
- == Trace::TRACE_INVALID) {
- phm2helix_usage(argv[0]);
- return (1);
- }
- break;
- case O_PHMFILE:
- opt_PhmFileName = optarg;
- break;
- case O_DESC:
- opt_desc = optarg;
- break;
- case O_ROTANGLE:
- opt_rotangle = strtod(optarg, &endptr);
- endstr = optarg + strlen(optarg);
- if (endptr != endstr) {
- std::cerr << "Error setting --rotangle to " << optarg << std::endl;
- phm2helix_usage(argv[0]);
- return (1);
- }
- break;
- case O_GEOMETRY:
- optGeometryName = optarg;
- break;
- case O_FOCAL_LENGTH:
- dOptFocalLength = strtod(optarg, &endptr);
- endstr = optarg + strlen(optarg);
- if (endptr != endstr) {
- std::cerr << "Error setting --focal-length to " << optarg << std::endl;
- phm2helix_usage(argv[0]);
- return (1);
- }
- break;
- case O_CENTER_DETECTOR_LENGTH:
- dOptCenterDetectorLength = strtod(optarg, &endptr);
- endstr = optarg + strlen(optarg);
- if (endptr != endstr) {
- std::cerr << "Error setting --center-detector-length to " << optarg << std::endl;
- phm2helix_usage(argv[0]);
- return (1);
- }
- break;
- case O_VIEW_RATIO:
- dOptViewRatio = strtod(optarg, &endptr);
- endstr = optarg + strlen(optarg);
- if (endptr != endstr) {
- std::cerr << "Error setting --view-ratio to " << optarg << std::endl;
- phm2helix_usage(argv[0]);
- return (1);
- }
- break;
- case O_SCAN_RATIO:
- dOptScanRatio = strtod(optarg, &endptr);
- endstr = optarg + strlen(optarg);
- if (endptr != endstr) {
- std::cerr << "Error setting --scan-ratio to " << optarg << std::endl;
- phm2helix_usage(argv[0]);
- return (1);
- }
- break;
- case O_NRAY:
- opt_nray = strtol(optarg, &endptr, 10);
- endstr = optarg + strlen(optarg);
- if (endptr != endstr) {
- std::cerr << "Error setting --nray to %s" << optarg << std::endl;
- phm2helix_usage(argv[0]);
- return (1);
- }
- break;
- case O_OFFSETVIEW:
- opt_offsetview = strtol(optarg, &endptr, 10);
- endstr = optarg + strlen(optarg);
- if (endptr != endstr) {
- std::cerr << "Error setting --offsetview to %s" << optarg << std::endl;
- phm2helix_usage(argv[0]);
- return (1);
- }
- break;
- case O_VERSION:
+ Phantom phm;
+ std::string optGeometryName = Scanner::convertGeometryIDToName(Scanner::GEOMETRY_PARALLEL);
+ char *opt_outfile = NULL;
+ std::string opt_desc;
+ std::string opt_PhmProg;
+ std::string opt_PhmFileName = "tmpphmfile";
+ int opt_ndet;
+ int opt_nview;
+ int opt_offsetview = 0;
+ int opt_nray = 1;
+ double dOptFocalLength = 2.;
+ double dOptCenterDetectorLength = 2;
+ double dOptViewRatio = 1.;
+ double dOptScanRatio = 1.;
+ int opt_trace = Trace::TRACE_NONE;
+ int opt_verbose = 0;
+ int opt_debug = 0;
+ double opt_rotangle = -1;
+ char* endptr = NULL;
+ char* endstr;
+
+ Timer timerProgram;
+
+ while (1) {
+ int c = getopt_long(argc, argv, "", phm2helix_options, NULL);
+
+ if (c == -1)
+ break;
+
+ switch (c) {
+ case O_VERBOSE:
+ opt_verbose = 1;
+ break;
+ case O_DEBUG:
+ opt_debug = 1;
+ break;
+ case O_TRACE:
+ if ((opt_trace = Trace::convertTraceNameToID(optarg))
+ == Trace::TRACE_INVALID) {
+ phm2helix_usage(argv[0]);
+ return (1);
+ }
+ break;
+ case O_PHMFILE:
+ opt_PhmFileName = optarg;
+ break;
+ case O_DESC:
+ opt_desc = optarg;
+ break;
+ case O_ROTANGLE:
+ opt_rotangle = strtod(optarg, &endptr);
+ endstr = optarg + strlen(optarg);
+ if (endptr != endstr) {
+ std::cerr << "Error setting --rotangle to " << optarg << std::endl;
+ phm2helix_usage(argv[0]);
+ return (1);
+ }
+ break;
+ case O_GEOMETRY:
+ optGeometryName = optarg;
+ break;
+ case O_FOCAL_LENGTH:
+ dOptFocalLength = strtod(optarg, &endptr);
+ endstr = optarg + strlen(optarg);
+ if (endptr != endstr) {
+ std::cerr << "Error setting --focal-length to " << optarg << std::endl;
+ phm2helix_usage(argv[0]);
+ return (1);
+ }
+ break;
+ case O_CENTER_DETECTOR_LENGTH:
+ dOptCenterDetectorLength = strtod(optarg, &endptr);
+ endstr = optarg + strlen(optarg);
+ if (endptr != endstr) {
+ std::cerr << "Error setting --center-detector-length to " << optarg << std::endl;
+ phm2helix_usage(argv[0]);
+ return (1);
+ }
+ break;
+ case O_VIEW_RATIO:
+ dOptViewRatio = strtod(optarg, &endptr);
+ endstr = optarg + strlen(optarg);
+ if (endptr != endstr) {
+ std::cerr << "Error setting --view-ratio to " << optarg << std::endl;
+ phm2helix_usage(argv[0]);
+ return (1);
+ }
+ break;
+ case O_SCAN_RATIO:
+ dOptScanRatio = strtod(optarg, &endptr);
+ endstr = optarg + strlen(optarg);
+ if (endptr != endstr) {
+ std::cerr << "Error setting --scan-ratio to " << optarg << std::endl;
+ phm2helix_usage(argv[0]);
+ return (1);
+ }
+ break;
+ case O_NRAY:
+ opt_nray = strtol(optarg, &endptr, 10);
+ endstr = optarg + strlen(optarg);
+ if (endptr != endstr) {
+ std::cerr << "Error setting --nray to %s" << optarg << std::endl;
+ phm2helix_usage(argv[0]);
+ return (1);
+ }
+ break;
+ case O_OFFSETVIEW:
+ opt_offsetview = strtol(optarg, &endptr, 10);
+ endstr = optarg + strlen(optarg);
+ if (endptr != endstr) {
+ std::cerr << "Error setting --offsetview to %s" << optarg << std::endl;
+ phm2helix_usage(argv[0]);
+ return (1);
+ }
+ break;
+ case O_VERSION:
#ifdef VERSION
- std::cout << "Version: " << VERSION << std::endl << g_szIdStr << std::endl;
+ std::cout << "Version: " << VERSION << std::endl << g_szIdStr << std::endl;
#else
- std::cout << "Unknown version number\n";
+ std::cout << "Unknown version number\n";
#endif
- return (0);
- case O_HELP:
- case '?':
- phm2helix_usage(argv[0]);
- return (0);
- default:
- phm2helix_usage(argv[0]);
- return (1);
- } // end of switch
- } // end of while loop
-
- if (optind + 4 != argc) {
- phm2helix_usage(argv[0]);
- return (1);
- }
-
- opt_outfile = argv[optind];
- opt_ndet = strtol(argv[optind+1], &endptr, 10);
- endstr = argv[optind+1] + strlen(argv[optind+1]);
- if (endptr != endstr) {
- std::cerr << "Error setting --ndet to " << argv[optind+1] << std::endl;
- phm2helix_usage(argv[0]);
- return (1);
- }
- opt_nview = strtol(argv[optind+2], &endptr, 10);
- endstr = argv[optind+2] + strlen(argv[optind+2]);
- if (endptr != endstr) {
- std::cerr << "Error setting --nview to " << argv[optind+2] << std::endl;
- phm2helix_usage(argv[0]);
- return (1);
- }
- opt_PhmProg = argv[optind+3];
-
- if (opt_rotangle < 0) {
- if (optGeometryName.compare ("parallel") == 0)
- opt_rotangle = 0.5;
- else
- opt_rotangle = 1.0;
- }
-
- std::ostringstream desc;
- desc << "phm2helix: NDet=" << opt_ndet
- << ", Nview=" << opt_nview
- << ", NRay=" << opt_nray
- << ", RotAngle=" << opt_rotangle
- << ", OffsetView =" << opt_offsetview
- << ", Geometry=" << optGeometryName
- << ", PhantomProg=" << opt_PhmProg
- << ", PhmFileName=" << opt_PhmFileName;
- if (opt_desc.length()) {
- desc << ": " << opt_desc;
- }
- opt_desc = desc.str();
-
- opt_rotangle *= TWOPI;
-
- int stat;
- char extcommand[100];
- if(opt_debug != 0)
- std::cout << opt_PhmProg << " " << 0 << " " << opt_nview << " " << opt_PhmFileName << std::endl;
- //extcommand << opt_PhmProg << " " << 0 << " " << opt_nview << " " << opt_PhmFileName ;
-
- sprintf(extcommand, "%s %d %d %s", opt_PhmProg.c_str(), 0, opt_nview, opt_PhmFileName.c_str() );
-
- stat = system( extcommand );
- if (stat != 0 )
- std::cerr << "Error executing external phantom program " << opt_PhmProg << " with command " << extcommand << std::endl;
-
- phm.createFromFile (opt_PhmFileName.c_str());
- remove(opt_PhmFileName.c_str());
-
- Scanner scanner (phm, optGeometryName.c_str(), opt_ndet, opt_nview,
- opt_offsetview, opt_nray, opt_rotangle, dOptFocalLength,
- dOptCenterDetectorLength, dOptViewRatio, dOptScanRatio);
- if (scanner.fail()) {
- std::cout << "Scanner Creation Error: " << scanner.failMessage()
- << std::endl;
- return (1);
- }
-
- Projections pjGlobal(scanner);
-
-
- for( int iView = 0; iView < opt_nview; iView++ ){
- if(opt_debug != 0)
- std::cout << opt_PhmProg << " " << iView << " " << opt_nview << " " << opt_PhmFileName << std::endl;
- //extcommand << opt_PhmProg << " " << iView << " " << opt_nview << " " << opt_PhmFileName ;
-
- sprintf(extcommand, "%s %d %d %s", opt_PhmProg.c_str(), iView, opt_nview, opt_PhmFileName.c_str() );
- stat = system( extcommand );
-
- if (stat != 0 )
- std::cerr << "Error executing external phantom program " << opt_PhmProg << " with command " << extcommand << std::endl;
- Phantom phmtmp;
- phmtmp.createFromFile (opt_PhmFileName.c_str());
-
- scanner.collectProjections (pjGlobal, phmtmp, iView,
- 1, scanner.offsetView(), true, opt_trace);
- remove(opt_PhmFileName.c_str());
- }
-
-
- pjGlobal.setCalcTime (timerProgram.timerEnd());
- pjGlobal.setRemark (opt_desc);
- pjGlobal.write (opt_outfile);
- if (opt_verbose) {
- phm.print (std::cout);
- std::cout << std::endl;
- std::ostringstream os;
- pjGlobal.printScanInfo (os);
- std::cout << os.str() << std::endl;
- std::cout << " Remark: " << pjGlobal.remark() << std::endl;
- std::cout << "Run time: " << pjGlobal.calcTime() << " seconds\n";
- }
-
- return (0);
+ return (0);
+ case O_HELP:
+ case '?':
+ phm2helix_usage(argv[0]);
+ return (0);
+ default:
+ phm2helix_usage(argv[0]);
+ return (1);
+ } // end of switch
+ } // end of while loop
+
+ if (optind + 4 != argc) {
+ phm2helix_usage(argv[0]);
+ return (1);
+ }
+
+ opt_outfile = argv[optind];
+ opt_ndet = strtol(argv[optind+1], &endptr, 10);
+ endstr = argv[optind+1] + strlen(argv[optind+1]);
+ if (endptr != endstr) {
+ std::cerr << "Error setting --ndet to " << argv[optind+1] << std::endl;
+ phm2helix_usage(argv[0]);
+ return (1);
+ }
+ opt_nview = strtol(argv[optind+2], &endptr, 10);
+ endstr = argv[optind+2] + strlen(argv[optind+2]);
+ if (endptr != endstr) {
+ std::cerr << "Error setting --nview to " << argv[optind+2] << std::endl;
+ phm2helix_usage(argv[0]);
+ return (1);
+ }
+ opt_PhmProg = argv[optind+3];
+
+ if (opt_rotangle < 0) {
+ if (optGeometryName.compare ("parallel") == 0)
+ opt_rotangle = 0.5;
+ else
+ opt_rotangle = 1.0;
+ }
+
+ std::ostringstream desc;
+ desc << "phm2helix: NDet=" << opt_ndet
+ << ", Nview=" << opt_nview
+ << ", NRay=" << opt_nray
+ << ", RotAngle=" << opt_rotangle
+ << ", OffsetView =" << opt_offsetview
+ << ", Geometry=" << optGeometryName
+ << ", PhantomProg=" << opt_PhmProg
+ << ", PhmFileName=" << opt_PhmFileName;
+ if (opt_desc.length()) {
+ desc << ": " << opt_desc;
+ }
+ opt_desc = desc.str();
+
+ opt_rotangle *= TWOPI;
+
+ int stat;
+ char extcommand[100];
+ if(opt_debug != 0)
+ std::cout << opt_PhmProg << " " << 0 << " " << opt_nview << " " << opt_PhmFileName << std::endl;
+ //extcommand << opt_PhmProg << " " << 0 << " " << opt_nview << " " << opt_PhmFileName ;
+
+ sprintf(extcommand, "%s %d %d %s", opt_PhmProg.c_str(), 0, opt_nview, opt_PhmFileName.c_str() );
+
+ stat = system( extcommand );
+ if (stat != 0 )
+ std::cerr << "Error executing external phantom program " << opt_PhmProg << " with command " << extcommand << std::endl;
+
+ phm.createFromFile (opt_PhmFileName.c_str());
+ remove(opt_PhmFileName.c_str());
+
+ Scanner scanner (phm, optGeometryName.c_str(), opt_ndet, opt_nview,
+ opt_offsetview, opt_nray, opt_rotangle, dOptFocalLength,
+ dOptCenterDetectorLength, dOptViewRatio, dOptScanRatio);
+ if (scanner.fail()) {
+ std::cout << "Scanner Creation Error: " << scanner.failMessage()
+ << std::endl;
+ return (1);
+ }
+
+ Projections pjGlobal(scanner);
+
+
+ for( int iView = 0; iView < opt_nview; iView++ ){
+ if(opt_debug != 0)
+ std::cout << opt_PhmProg << " " << iView << " " << opt_nview << " " << opt_PhmFileName << std::endl;
+ //extcommand << opt_PhmProg << " " << iView << " " << opt_nview << " " << opt_PhmFileName ;
+
+ sprintf(extcommand, "%s %d %d %s", opt_PhmProg.c_str(), iView, opt_nview, opt_PhmFileName.c_str() );
+ stat = system( extcommand );
+
+ if (stat != 0 )
+ std::cerr << "Error executing external phantom program " << opt_PhmProg << " with command " << extcommand << std::endl;
+ Phantom phmtmp;
+ phmtmp.createFromFile (opt_PhmFileName.c_str());
+
+ scanner.collectProjections (pjGlobal, phmtmp, iView,
+ 1, scanner.offsetView(), true, opt_trace);
+ remove(opt_PhmFileName.c_str());
+ }
+
+
+ pjGlobal.setCalcTime (timerProgram.timerEnd());
+ pjGlobal.setRemark (opt_desc);
+ pjGlobal.write (opt_outfile);
+ if (opt_verbose) {
+ phm.print (std::cout);
+ std::cout << std::endl;
+ std::ostringstream os;
+ pjGlobal.printScanInfo (os);
+ std::cout << os.str() << std::endl;
+ std::cout << " Remark: " << pjGlobal.remark() << std::endl;
+ std::cout << "Run time: " << pjGlobal.calcTime() << " seconds\n";
+ }
+
+ return (0);
}
#ifndef NO_MAIN
-int
+int
main (int argc, char* argv[])
{
int retval = 1;
#include "timer.h"
-enum { O_PHANTOM, O_DESC, O_NSAMPLE, O_FILTER, O_VIEW_RATIO, O_TRACE, O_VERBOSE, O_HELP,
+enum { O_PHANTOM, O_DESC, O_NSAMPLE, O_FILTER, O_VIEW_RATIO, O_TRACE, O_VERBOSE, O_HELP,
O_PHMFILE, O_FILTER_DOMAIN, O_FILTER_BW, O_FILTER_PARAM, O_DEBUG, O_VERSION };
-static struct option my_options[] =
+static struct option my_options[] =
{
{"phantom", 1, 0, O_PHANTOM},
{"phmfile", 1, 0, O_PHMFILE},
static const char* g_szIdStr = "$Id$";
-void
+void
phm2if_usage (const char *program)
{
std::cout << "phm2if_usage: " << fileBasename(program) << " outfile nx ny [--phantom phantom-name] [--phmfile filename] [--filter filter-name] [OPTIONS]\n";
void mpi_gather_image (MPIWorld& mpiWorld, ImageFile* pImGlobal, ImageFile* pImLocal, const int optDebug);
#endif
-int
+int
phm2if_main (int argc, char* const argv[])
{
ImageFile* pImGlobal = NULL;
char *endptr = NULL;
char *endstr;
Timer timerProgram;
-
+
#ifdef HAVE_MPI
ImageFile* pImLocal = NULL;
MPIWorld mpiWorld (argc, argv);
int c = getopt_long(argc, argv, "", my_options, NULL);
if (c == -1)
break;
-
+
switch (c) {
case O_PHANTOM:
optPhmName = optarg;
return (1);
}
}
-
+
if (optPhmName == "" && optFilterName == "" && optPhmFilename == "") {
std::cerr << "No phantom defined\n" << std::endl;
phm2if_usage(argv[0]);
return (1);
}
-
+
if (optind + 3 != argc) {
phm2if_usage(argv[0]);
return (1);
phm2if_usage(argv[0]);
return (1);
}
-
+
std::ostringstream oss;
oss << "phm2if: nx=" << opt_nx << ", ny=" << opt_ny << ", viewRatio=" << optViewRatio << ", nsample=" << opt_nsample << ", ";
if (optPhmFilename != "")
if (optDesc != "")
oss << ": " << optDesc;
optDesc = oss.str();
-
+
if (optPhmName != "") {
phm.createFromPhantom (optPhmName.c_str());
if (phm.fail()) {
return (1);
}
}
-
+
if (optPhmFilename != "") {
phm.createFromFile(optPhmFilename.c_str());
#ifdef HAVE_MPI
- if (mpiWorld.getRank() == 0)
+ if (mpiWorld.getRank() == 0)
std::cerr << "Can't use phantom from file in MPI mode\n";
return (1);
#endif
}
-
+
if (optVerbose)
std::cout << "Rasterize Phantom to Image\n" << std::endl;
#ifdef HAVE_MPI
}
#endif
-
+
#ifdef HAVE_MPI
TimerCollectiveMPI timerBcast (mpiWorld.getComm());
mpiWorld.BcastString (optPhmName);
mpiWorld.getComm().Bcast (&optViewRatio, 1, MPI::DOUBLE, 0);
mpiWorld.getComm().Bcast (&optFilterParam, 1, MPI::DOUBLE, 0);
mpiWorld.getComm().Bcast (&optFilterBW, 1, MPI::DOUBLE, 0);
-
+
mpiWorld.BcastString (optFilterName);
mpiWorld.BcastString (optDomainName);
-
+
if (optVerbose)
timerBcast.timerEndAndReport ("Time to broadcast variables");
-
+
mpiWorld.setTotalWorkUnits (opt_nx);
-
+
if (mpiWorld.getRank() > 0 && optPhmName != "")
phm.createFromPhantom (optPhmName.c_str());
-
+
if (mpiWorld.getRank() == 0) {
pImGlobal = new ImageFile (opt_nx, opt_ny);
}
#else
pImGlobal = new ImageFile (opt_nx, opt_ny);
#endif
-
+
ImageFileArray v = NULL;
#ifdef HAVE_MPI
if (mpiWorld.getRank() == 0)
v = pImGlobal->getArray ();
-
+
if (phm.getComposition() == P_UNIT_PULSE) {
if (mpiWorld.getRank() == 0) {
v[opt_nx/2][opt_ny/2] = 1.;
phm.convertToImagefile (*pImLocal, optViewRatio, opt_nsample, optTrace, mpiWorld.getMyStartWorkUnit(), mpiWorld.getMyLocalWorkUnits(), false);
if (optVerbose)
timerRasterize.timerEndAndReport ("Time to rasterize phantom");
-
+
TimerCollectiveMPI timerGather (mpiWorld.getComm());
mpi_gather_image (mpiWorld, pImGlobal, pImLocal, optDebug);
if (optVerbose)
phm.convertToImagefile (*pImGlobal, optViewRatio, opt_nsample, optTrace);
}
#endif
-
+
#ifdef HAVE_MPI
- if (mpiWorld.getRank() == 0)
+ if (mpiWorld.getRank() == 0)
#endif
{
double calctime = timerProgram.timerEnd ();
if (optVerbose)
std::cout << "Time to rasterize phantom: " << calctime << " seconds\n";
}
-
+
delete pImGlobal;
#ifdef HAVE_MPI
delete pImLocal;
#endif
-
+
return (0);
}
ImageFileArray vLocal = pImLocal->getArray();
ImageFileArray vGlobal = NULL;
int nyLocal = pImLocal->ny();
-
+
if (mpiWorld.getRank() == 0)
vGlobal = pImGlobal->getArray();
-
+
for (int iw = 0; iw < mpiWorld.getMyLocalWorkUnits(); iw++)
mpiWorld.getComm().Send(vLocal[iw], nyLocal, pImLocal->getMPIDataType(), 0, 0);
-
+
if (mpiWorld.getRank() == 0) {
for (int iProc = 0; iProc < mpiWorld.getNumProcessors(); iProc++) {
for (int iw = mpiWorld.getStartWorkUnit(iProc); iw <= mpiWorld.getEndWorkUnit(iProc); iw++) {
}
}
}
-
+
}
#endif
#ifndef NO_MAIN
-int
+int
main (int argc, char* argv[])
{
int retval = 1;
-
+
try {
retval = phm2if_main(argc, argv);
} catch (exception e) {
} catch (...) {
std::cerr << "Unknown exception\n";
}
-
+
return (retval);
}
#endif
enum { O_PHANTOM, O_DESC, O_NRAY, O_ROTANGLE, O_PHMFILE, O_GEOMETRY, O_FOCAL_LENGTH, O_CENTER_DETECTOR_LENGTH,
O_VIEW_RATIO, O_SCAN_RATIO, O_OFFSETVIEW, O_TRACE, O_VERBOSE, O_HELP, O_DEBUG, O_VERSION };
-static struct option phm2pj_options[] =
+static struct option phm2pj_options[] =
{
{"phantom", 1, 0, O_PHANTOM},
{"phmfile", 1, 0, O_PHMFILE},
static const char* g_szIdStr = "$Id$";
-void
+void
phm2pj_usage (const char *program)
{
std::cout << "usage: " << fileBasename(program) << " outfile ndet nview [--phantom phantom-name] [--phmfile filename] [OPTIONS]\n";
void GatherProjectionsMPI (MPIWorld& mpiWorld, Projections& pjGlobal, Projections& pjLocal, const int opt_debug);
#endif
-int
+int
phm2pj_main (int argc, char* const argv[])
{
Phantom phm;
double opt_rotangle = -1;
char* endptr = NULL;
char* endstr;
-
+
#ifdef HAVE_MPI
MPIWorld mpiWorld (argc, argv);
#endif
-
+
Timer timerProgram;
-
+
#ifdef HAVE_MPI
if (mpiWorld.getRank() == 0) {
#endif
while (1) {
int c = getopt_long(argc, argv, "", phm2pj_options, NULL);
-
+
if (c == -1)
break;
-
+
switch (c) {
case O_PHANTOM:
optPhmName = optarg;
return (1);
}
break;
- case O_OFFSETVIEW:
- opt_offsetview = strtol(optarg, &endptr, 10);
- endstr = optarg + strlen(optarg);
- if (endptr != endstr) {
- std::cerr << "Error setting --offsetview to %s" << optarg << std::endl;
- phm2pj_usage(argv[0]);
- return (1);
- }
- break;
+ case O_OFFSETVIEW:
+ opt_offsetview = strtol(optarg, &endptr, 10);
+ endstr = optarg + strlen(optarg);
+ if (endptr != endstr) {
+ std::cerr << "Error setting --offsetview to %s" << optarg << std::endl;
+ phm2pj_usage(argv[0]);
+ return (1);
+ }
+ break;
case O_VERSION:
#ifdef VERSION
return (1);
}
}
-
+
if (optPhmName == "" && optPhmFileName == "") {
std::cerr << "No phantom defined\n" << std::endl;
phm2pj_usage(argv[0]);
phm2pj_usage(argv[0]);
return (1);
}
-
+
opt_outfile = argv[optind];
opt_ndet = strtol(argv[optind+1], &endptr, 10);
endstr = argv[optind+1] + strlen(argv[optind+1]);
phm2pj_usage(argv[0]);
return (1);
}
-
+
if (opt_rotangle < 0) {
if (optGeometryName.compare ("parallel") == 0)
opt_rotangle = 0.5;
else
opt_rotangle = 1.0;
}
-
+
std::ostringstream desc;
desc << "phm2pj: NDet=" << opt_ndet << ", Nview=" << opt_nview << ", NRay=" << opt_nray << ", RotAngle=" << opt_rotangle << "OffsetView =" << opt_offsetview << ", Geometry=" << optGeometryName << ", ";
if (optPhmFileName.length()) {
desc << ": " << opt_desc;
}
opt_desc = desc.str();
-
+
if (optPhmName != "") {
phm.createFromPhantom (optPhmName.c_str());
if (phm.fail()) {
return (1);
}
}
-
+
if (optPhmFileName != "") {
#ifdef HAVE_MPI
std::cerr << "Can not read phantom from file in MPI mode\n";
#endif
phm.createFromFile (optPhmFileName.c_str());
}
-
+
#ifdef HAVE_MPI
}
#endif
-
+
#ifdef HAVE_MPI
TimerCollectiveMPI timerBcast(mpiWorld.getComm());
mpiWorld.BcastString (optPhmName);
mpiWorld.getComm().Bcast (&opt_trace, 1, MPI::INT, 0);
if (opt_verbose)
timerBcast.timerEndAndReport ("Time to broadcast variables");
-
+
if (mpiWorld.getRank() > 0 && optPhmName != "")
phm.createFromPhantom (optPhmName.c_str());
#endif
-
+
opt_rotangle *= TWOPI;
- Scanner scanner (phm, optGeometryName.c_str(), opt_ndet, opt_nview, opt_offsetview, opt_nray,
- opt_rotangle, dOptFocalLength, dOptCenterDetectorLength, dOptViewRatio, dOptScanRatio);
+ Scanner scanner (phm, optGeometryName.c_str(), opt_ndet, opt_nview, opt_offsetview, opt_nray,
+ opt_rotangle, dOptFocalLength, dOptCenterDetectorLength, dOptViewRatio, dOptScanRatio);
if (scanner.fail()) {
std::cout << "Scanner Creation Error: " << scanner.failMessage() << std::endl;
return (1);
}
#ifdef HAVE_MPI
mpiWorld.setTotalWorkUnits (opt_nview);
-
+
Projections pjGlobal;
if (mpiWorld.getRank() == 0)
pjGlobal.initFromScanner (scanner);
-
+
if (opt_verbose) {
std::ostringstream os;
pjGlobal.printScanInfo(os);
std::cout << os.str();
}
-
+
Projections pjLocal (scanner);
pjLocal.setNView (mpiWorld.getMyLocalWorkUnits());
-
+
if (opt_debug)
std::cout << "pjLocal->nview = " << pjLocal.nView() << " (process " << mpiWorld.getRank() << ")\n";;
-
+
TimerCollectiveMPI timerProject (mpiWorld.getComm());
scanner.collectProjections (pjLocal, phm, mpiWorld.getMyStartWorkUnit(), mpiWorld.getMyLocalWorkUnits(), false, opt_trace);
if (opt_verbose)
timerProject.timerEndAndReport ("Time to collect projections");
-
+
TimerCollectiveMPI timerGather (mpiWorld.getComm());
GatherProjectionsMPI (mpiWorld, pjGlobal, pjLocal, opt_debug);
- if (opt_verbose)
+ if (opt_verbose)
timerGather.timerEndAndReport ("Time to gather projections");
-
+
#else
Projections pjGlobal (scanner);
scanner.collectProjections (pjGlobal, phm, 0, opt_nview, opt_offsetview, true, opt_trace);
#endif
-
+
#ifdef HAVE_MPI
- if (mpiWorld.getRank() == 0)
+ if (mpiWorld.getRank() == 0)
#endif
{
pjGlobal.setCalcTime (timerProgram.timerEnd());
std::cout << "Run time: " << pjGlobal.calcTime() << " seconds\n";
}
}
-
+
return (0);
}
double viewAngle = detArray.viewAngle();
int nDet = detArray.nDet();
DetectorValue* detval = detArray.detValues();
-
+
mpiWorld.getComm().Send(&viewAngle, 1, MPI::DOUBLE, 0, 0);
mpiWorld.getComm().Send(&nDet, 1, MPI::INT, 0, 0);
mpiWorld.getComm().Send(detval, nDet, MPI::FLOAT, 0, 0);
}
-
+
if (mpiWorld.getRank() == 0) {
for (int iProc = 0; iProc < mpiWorld.getNumProcessors(); iProc++) {
for (int iw = mpiWorld.getStartWorkUnit(iProc); iw <= mpiWorld.getEndWorkUnit(iProc); iw++) {
int nDet;
DetectorArray& detArray = pjGlobal.getDetectorArray(iw);
DetectorValue* detval = detArray.detValues();
-
+
mpiWorld.getComm().Recv(&viewAngle, 1, MPI::DOUBLE, iProc, 0, status);
mpiWorld.getComm().Recv(&nDet, 1, MPI::INT, iProc, 0, status);
mpiWorld.getComm().Recv(detval, nDet, MPI::FLOAT, iProc, 0, status);
#ifndef NO_MAIN
-int
+int
main (int argc, char* argv[])
{
int retval = 1;
-
+
try {
retval = phm2pj_main(argc, argv);
#if HAVE_DMALLOC
} catch (...) {
std::cerr << "Unknown exception\n";
}
-
+
return (retval);
}
#endif
******************************************************************************/
/* FILE
- * pj2if.c Convert Raysum to image
+ * pj2if.c Convert Raysum to image
*
* DATE
* Apr 1999
static const char* g_szIdStr = "$Id$";
-void
+void
pj2if_usage (const char *program)
{
std::cout << "usage: " << fileBasename(program) << " in-proj-file out-if-file [OPTIONS]\n";
std::cout << " --help Print this help message\n";
}
-int
+int
pj2if_main (const int argc, char *const argv[])
{
char *pj_name, *im_name;
{
int c = getopt_long (argc, argv, "", my_options, NULL);
if (c == -1)
- break;
-
+ break;
+
switch (c)
- {
- case O_VERBOSE:
- optVerbose = true;
- break;
+ {
+ case O_VERBOSE:
+ optVerbose = true;
+ break;
case O_VERSION:
#ifdef VERSION
- std::cout << "Version " << VERSION << std::endl << g_szIdStr << std::endl;
+ std::cout << "Version " << VERSION << std::endl << g_szIdStr << std::endl;
#else
std::cout << "Unknown version number\n";
#endif
- return (0);
- case O_HELP:
- case '?':
- pj2if_usage(argv[0]);
- return (0);
- default:
- pj2if_usage(argv[0]);
- return (1);
- }
+ return (0);
+ case O_HELP:
+ case '?':
+ pj2if_usage(argv[0]);
+ return (0);
+ default:
+ pj2if_usage(argv[0]);
+ return (1);
+ }
}
-
+
if (argc - optind != 2) {
pj2if_usage(argv[0]);
return (1);
pj.printScanInfo (os);
std::cout << os.str();
}
-
+
ImageFile im (pj.nDet(), pj.nView());
-
+
ImageFileArray v = im.getArray();
for (int iy = 0; iy < pj.nView(); iy++) {
im.labelAdd (pj.getLabel());
im.labelAdd (Array2dFileLabel::L_HISTORY, "Conversion from .pj to .if", timerProgram.timerEnd());
im.fileWrite (im_name);
-
+
return(0);
}
#ifndef NO_MAIN
-int
+int
main (const int argc, char *const argv[])
{
int retval = 1;
static struct option my_options[] =
{
- {"interpview", 1, 0, O_INTERPVIEW},
- {"trace", 1, 0, O_TRACE},
- {"debug", 0, 0, O_DEBUG},
- {"verbose", 0, 0, O_VERBOSE},
- {"help", 0, 0, O_HELP},
- {"version", 0, 0, O_VERSION},
- {0, 0, 0, 0}
+ {"interpview", 1, 0, O_INTERPVIEW},
+ {"trace", 1, 0, O_TRACE},
+ {"debug", 0, 0, O_DEBUG},
+ {"verbose", 0, 0, O_VERBOSE},
+ {"help", 0, 0, O_HELP},
+ {"version", 0, 0, O_VERSION},
+ {0, 0, 0, 0}
};
static const char* g_szIdStr = "$Id$";
bool bOptDebug = 1;
int optTrace = Trace::TRACE_NONE;
char *endptr = NULL;
- char *endstr;
+ char *endstr;
int opt_interpview=-1;
-
+
while (1) {
int c = getopt_long(argc, argv, "", my_options, NULL);
-
+
if (c == -1)
break;
-
+
switch (c) {
case O_INTERPVIEW:
opt_interpview = strtol(optarg, &endptr, 10);
endstr = optarg + strlen(optarg);
- if (endptr != endstr) {
- std::cerr << "Error setting --interpview to %s" << optarg << std::endl;
- pjHinterp_usage(argv[0]);
- return(1);
+ if (endptr != endstr) {
+ std::cerr << "Error setting --interpview to %s" << optarg << std::endl;
+ pjHinterp_usage(argv[0]);
+ return(1);
}
break;
case O_VERBOSE:
bOptDebug = true;
break;
case O_TRACE:
- if ((optTrace = Trace::convertTraceNameToID(optarg))
- == Trace::TRACE_INVALID) {
- pjHinterp_usage(argv[0]);
- return (1);
+ if ((optTrace = Trace::convertTraceNameToID(optarg))
+ == Trace::TRACE_INVALID) {
+ pjHinterp_usage(argv[0]);
+ return (1);
}
break;
case O_VERSION:
#ifdef VERSION
- std::cout << "Version " << VERSION << std::endl <<
- g_szIdStr << std::endl;
+ std::cout << "Version " << VERSION << std::endl <<
+ g_szIdStr << std::endl;
#else
std::cout << "Unknown version number" << std::endl;
#endif
return (0);
-
+
case O_HELP:
- case '?':
+ case '?':
pjHinterp_usage(argv[0]);
return (0);
default:
return (1);
} // end switch
} // end while
-
+
if (optind + 2 != argc) {
pjHinterp_usage(argv[0]);
return (1);
}
-
+
pszProjFilename = argv[optind];
-
+
pszInterpFilename = argv[optind + 1];
-
+
Projections projections;
- if ( projections.read(pszProjFilename) != true ){
- std::cerr << "Error reading input file " << pszProjFilename << std::endl;
+ if ( projections.read(pszProjFilename) != true ){
+ std::cerr << "Error reading input file " << pszProjFilename << std::endl;
return (1);
}
- if (bOptVerbose) {
- std::ostringstream os;
+ if (bOptVerbose) {
+ std::ostringstream os;
projections.printScanInfo(os);
std::cout << os.str();
}
-
+
int status = projections.Helical180LI(opt_interpview);
if ( status != 0 ) return (1);
status = projections.HalfScanFeather();
if ( status != 0 ) return (1);
projections.write( pszInterpFilename );
-
+
return (0);
}
******************************************************************************/
/* FILE
-* pjinfo.c Convert Raysum to image
+* pjinfo.c Convert Raysum to image
*
* DATE
* August 2000
static const char* g_szIdStr = "$Id$";
-void
+void
pjinfo_usage (const char *program)
{
std::cout << "usage: " << fileBasename(program) << " proj-file [OPTIONS]\n";
-int
+int
pjinfo_main (const int argc, char *const argv[])
{
std::string pj_name;
int optStartView = 0;
int optEndView = -1; // tells copyViewData to use default last view
extern int optind;
-
+
while (1)
{
char *endptr, *endstr;
int c = getopt_long (argc, argv, "", my_options, NULL);
if (c == -1)
break;
-
+
switch (c)
{
case O_DUMP:
return (1);
}
}
-
+
if (argc - optind != 1) {
pjinfo_usage(argv[0]);
return (1);
}
-
+
pj_name = argv[optind];
-
+
if (optBinaryHeader)
Projections::copyHeader (pj_name, std::cout);
else if (optBinaryViews)
sys_error (ERR_SEVERE, "Can not open projection file %s", pj_name.c_str());
return (1);
}
-
+
if (optDump) {
pj.printProjectionData (optStartView, optEndView);
} else {
std::cout << os.str();
}
}
-
+
return(0);
}
#ifndef NO_MAIN
-int
+int
main (const int argc, char *const argv[])
{
int retval = 1;
-
+
try {
retval = pjinfo_main(argc, argv);
} catch (exception e) {
} catch (...) {
std::cerr << "Unknown exception\n";
}
-
+
return (retval);
}
#endif
static const char* g_szIdStr = "$Id$";
-void
+void
pjrec_usage (const char *program)
{
std::cout << "usage: " << fileBasename(program) << " raysum-file image-file nx-image ny-image [OPTIONS]" << std::endl;
#endif
-int
+int
pjrec_main (int argc, char * const argv[])
{
Projections projGlobal;
while (1) {
int c = getopt_long(argc, argv, "", my_options, NULL);
char *endptr = NULL;
-
+
if (c == -1)
- break;
-
+ break;
+
switch (c)
- {
- case O_INTERP:
- sOptInterpName = optarg;
- break;
- case O_PREINTERPOLATION_FACTOR:
- iOptPreinterpolationFactor = strtol(optarg, &endptr, 10);
- if (endptr != optarg + strlen(optarg)) {
- pjrec_usage(argv[0]);
- return(1);
- }
- break;
- case O_FILTER:
- sOptFilterName = optarg;
- break;
+ {
+ case O_INTERP:
+ sOptInterpName = optarg;
+ break;
+ case O_PREINTERPOLATION_FACTOR:
+ iOptPreinterpolationFactor = strtol(optarg, &endptr, 10);
+ if (endptr != optarg + strlen(optarg)) {
+ pjrec_usage(argv[0]);
+ return(1);
+ }
+ break;
+ case O_FILTER:
+ sOptFilterName = optarg;
+ break;
case O_FILTER_METHOD:
- sOptFilterMethodName = optarg;
+ sOptFilterMethodName = optarg;
+ break;
+ case O_FILTER_GENERATION:
+ sOptFilterGenerationName = optarg;
+ break;
+ case O_FILTER_PARAM:
+ dOptFilterParam = strtod(optarg, &endptr);
+ if (endptr != optarg + strlen(optarg)) {
+ pjrec_usage(argv[0]);
+ return(1);
+ }
+ break;
+ case O_ZEROPAD:
+ iOptZeropad = strtol(optarg, &endptr, 10);
+ if (endptr != optarg + strlen(optarg)) {
+ pjrec_usage(argv[0]);
+ return(1);
+ }
+ break;
+ case O_BACKPROJ:
+ sOptBackprojectName = optarg;
+ break;
+ case O_VERBOSE:
+ bOptVerbose = true;
+ break;
+ case O_DEBUG:
+ bOptDebug = true;
+ break;
+ case O_TRACE:
+ if ((optTrace = Trace::convertTraceNameToID(optarg)) == Trace::TRACE_INVALID) {
+ pjrec_usage(argv[0]);
+ return (1);
+ }
break;
- case O_FILTER_GENERATION:
- sOptFilterGenerationName = optarg;
- break;
- case O_FILTER_PARAM:
- dOptFilterParam = strtod(optarg, &endptr);
- if (endptr != optarg + strlen(optarg)) {
- pjrec_usage(argv[0]);
- return(1);
- }
- break;
- case O_ZEROPAD:
- iOptZeropad = strtol(optarg, &endptr, 10);
- if (endptr != optarg + strlen(optarg)) {
- pjrec_usage(argv[0]);
- return(1);
- }
- break;
- case O_BACKPROJ:
- sOptBackprojectName = optarg;
- break;
- case O_VERBOSE:
- bOptVerbose = true;
- break;
- case O_DEBUG:
- bOptDebug = true;
- break;
- case O_TRACE:
- if ((optTrace = Trace::convertTraceNameToID(optarg)) == Trace::TRACE_INVALID) {
- pjrec_usage(argv[0]);
- return (1);
- }
- break;
case O_VERSION:
#ifdef VERSION
- std::cout << "Version " << VERSION << std::endl << g_szIdStr << std::endl;
+ std::cout << "Version " << VERSION << std::endl << g_szIdStr << std::endl;
#else
std::cout << "Unknown version number" << std::endl;
#endif
- return (0);
- case O_HELP:
- case '?':
- pjrec_usage(argv[0]);
- return (0);
- default:
- pjrec_usage(argv[0]);
- return (1);
- }
+ return (0);
+ case O_HELP:
+ case '?':
+ pjrec_usage(argv[0]);
+ return (0);
+ default:
+ pjrec_usage(argv[0]);
+ return (1);
+ }
}
-
+
if (optind + 4 != argc) {
pjrec_usage(argv[0]);
return (1);
}
pszFilenameProj = argv[optind];
-
+
pszFilenameImage = argv[optind + 1];
-
+
nx = strtol(argv[optind + 2], &endptr, 10);
ny = strtol(argv[optind + 3], &endptr, 10);
-
+
std::ostringstream filterDesc;
if (dOptFilterParam >= 0)
- filterDesc << sOptFilterName << ": alpha=" << dOptFilterParam;
+ filterDesc << sOptFilterName << ": alpha=" << dOptFilterParam;
else
filterDesc << sOptFilterName;
std::ostringstream label;
label << "pjrec: " << nx << "x" << ny << ", " << filterDesc.str() << ", " << sOptInterpName << ", preinterpolationFactor=" << iOptPreinterpolationFactor << ", " << sOptBackprojectName;
sRemark = label.str();
-
+
if (bOptVerbose)
std::cout << "SRemark: " << sRemark << std::endl;
#ifdef HAVE_MPI
return (1);
}
reconstruct.reconstructAllViews();
-
+
if (bOptVerbose)
timerReconstruct.timerEndAndReport ("Time to reconstruct");
imGlobal->labelAdd (Array2dFileLabel::L_HISTORY, sRemark.c_str(), dCalcTime);
imGlobal->fileWrite (pszFilenameImage);
if (bOptVerbose)
- std::cout << "Run time: " << dCalcTime << " seconds" << std::endl;
+ std::cout << "Run time: " << dCalcTime << " seconds" << std::endl;
}
#ifdef HAVE_MPI
MPI::Finalize();
if (mpiWorld.getRank() == 0) {
for (int iProc = 0; iProc < mpiWorld.getNumProcessors(); iProc++) {
for (int iw = mpiWorld.getStartWorkUnit(iProc); iw <= mpiWorld.getEndWorkUnit(iProc); iw++) {
- DetectorArray& detarray = projGlobal.getDetectorArray( iw );
- int nDet = detarray.nDet();
- DetectorValue* detval = detarray.detValues();
-
- double viewAngle = detarray.viewAngle();
- mpiWorld.getComm().Send(&nDet, 1, MPI::INT, iProc, 0);
- mpiWorld.getComm().Send(&viewAngle, 1, MPI::DOUBLE, iProc, 0);
- mpiWorld.getComm().Send(detval, nDet, MPI::FLOAT, iProc, 0);
+ DetectorArray& detarray = projGlobal.getDetectorArray( iw );
+ int nDet = detarray.nDet();
+ DetectorValue* detval = detarray.detValues();
+
+ double viewAngle = detarray.viewAngle();
+ mpiWorld.getComm().Send(&nDet, 1, MPI::INT, iProc, 0);
+ mpiWorld.getComm().Send(&viewAngle, 1, MPI::DOUBLE, iProc, 0);
+ mpiWorld.getComm().Send(detval, nDet, MPI::FLOAT, iProc, 0);
}
}
}
#ifndef NO_MAIN
-int
+int
main (int argc, char* argv[])
{
int retval = 1;
try {
retval = pjrec_main(argc, argv);
} catch (exception e) {
- std::cerr << "Exception: " << e.what() << std::endl;
+ std::cerr << "Exception: " << e.what() << std::endl;
} catch (...) {
- std::cerr << "Unknown exception" << std::endl;
+ std::cerr << "Unknown exception" << std::endl;
}
return (retval);