1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579
|
/*********************************************************************
Arithmetic - Do arithmetic operations on images.
Arithmetic is part of GNU Astronomy Utilities (Gnuastro) package.
Original author:
Mohammad Akhlaghi <mohammad@akhlaghi.org>
Contributing author(s):
Copyright (C) 2015-2025 Free Software Foundation, Inc.
Gnuastro is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation, either version 3 of the License, or (at your
option) any later version.
Gnuastro is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with Gnuastro. If not, see <http://www.gnu.org/licenses/>.
**********************************************************************/
#include <config.h>
#include <argp.h>
#include <errno.h>
#include <error.h>
#include <stdio.h>
#include <string.h>
#include <gnuastro/txt.h>
#include <gnuastro/wcs.h>
#include <gnuastro/list.h>
#include <gnuastro/fits.h>
#include <gnuastro/table.h>
#include <gnuastro/array.h>
#include <gnuastro/threads.h>
#include <gnuastro/arithmetic.h>
#include <gnuastro-internal/timing.h>
#include <gnuastro-internal/options.h>
#include <gnuastro-internal/checkset.h>
#include <gnuastro-internal/fixedstringmacros.h>
#include "main.h"
#include "ui.h"
#include "authors-cite.h"
/**************************************************************/
/********* Argp necessary global entities ************/
/**************************************************************/
/* Definition parameters for the argp: */
const char *
argp_program_version = PROGRAM_STRING "\n"
GAL_STRINGS_COPYRIGHT
"\n\nWritten/developed by "PROGRAM_AUTHORS;
const char *
argp_program_bug_address = PACKAGE_BUGREPORT;
static char
args_doc[] = "ASTRdata or number [ASTRdata] OPERATOR ...";
const char
doc[] = GAL_STRINGS_TOP_HELP_INFO PROGRAM_NAME" will do arithmetic "
"operations on one or multiple images and numbers. Simply put, the name "
"of the image along with the arithmetic operators and possible numbers "
"are given as arguments. The extensions of each input are specified with "
"(possibly multiple) calls to the '--hdu' option."
"\n\nCurrently "PROGRAM_NAME" only supports postfix or reverse polish "
"notation. For example to get the result of '5+6', you should write "
"'5 6 +', or to get the average of two images, you should write 'a.fits "
"b.fits + 2 /' (or more simply use the 'average' operator with "
"'a.fits b.fits average'). Please see the manual for more information. "
"\n\n"PROGRAM_NAME" recognizes a large collection of standard operators, "
"including basic arithmetic (e.g., +, -, x, /), mathematical (e.g., abs, "
"pow, sqrt, log), statistical (minvalue, min, max, average), comparison "
"(e.g., lt, le, gt), logical (e.g., and, or, not), the full set of "
"bitwise operators, and numeric type conversion operators to all known "
"types. Please run the command below for a complete list describing all "
"operators (press the 'SPACE' keyboard key, or arrow keys, to go down "
"and 'q' to return to the command-line):\n\n"
" $ info gnuastro \"Arithmetic operators\"\n"
GAL_STRINGS_MORE_HELP_INFO
/* After the list of options: */
"\v"
PACKAGE_NAME" home page: "PACKAGE_URL;
/**************************************************************/
/********* Initialize & Parse command-line **************/
/**************************************************************/
static void
ui_initialize_options(struct arithmeticparams *p,
struct argp_option *program_options,
struct argp_option *gal_commonopts_options)
{
size_t i;
struct gal_options_common_params *cp=&p->cp;
/* Set the necessary common parameters structure. */
cp->program_struct = p;
cp->poptions = program_options;
cp->program_name = PROGRAM_NAME;
cp->program_exec = PROGRAM_EXEC;
cp->program_bibtex = PROGRAM_BIBTEX;
cp->program_authors = PROGRAM_AUTHORS;
cp->numthreads = gal_threads_number();
cp->coptions = gal_commonopts_options;
/* Modify the common options. */
for(i=0; !gal_options_is_last(&cp->coptions[i]); ++i)
{
/* Select individually. */
switch(cp->coptions[i].key)
{
case GAL_OPTIONS_KEY_HDU:
cp->coptions[i].value=&p->hdus;
cp->coptions[i].type=GAL_TYPE_STRLL;
cp->coptions[i].doc="Nth call, used for HDU of Nth input FITS.";
break;
case GAL_OPTIONS_KEY_TYPE:
case GAL_OPTIONS_KEY_STDINTIMEOUT:
cp->coptions[i].flags=OPTION_HIDDEN;
break;
case GAL_OPTIONS_KEY_MINMAPSIZE:
cp->coptions[i].mandatory=GAL_OPTIONS_MANDATORY;
break;
}
/* Select by group. */
switch(cp->coptions[i].group)
{
case GAL_OPTIONS_GROUP_TESSELLATION:
if(cp->coptions[i].key!=GAL_OPTIONS_KEY_INTERPMETRIC)
cp->coptions[i].flags=OPTION_HIDDEN;
break;
}
}
}
/* Parse a single option: */
error_t
parse_opt(int key, char *arg, struct argp_state *state)
{
struct arithmeticparams *p = state->input;
/* Pass 'gal_options_common_params' into the child parser. */
state->child_inputs[0] = &p->cp;
/* In case the user incorrectly uses the equal sign (for example
with a short format or with space in the long format, then 'arg'
start with (if the short version was called) or be (if the long
version was called with a space) the equal sign. So, here we
check if the first character of arg is the equal sign, then the
user is warned and the program is stopped: */
if(arg && arg[0]=='=')
argp_error(state, "incorrect use of the equal sign ('='). For short "
"options, '=' should not be used and for long options, "
"there should be no space between the option, equal sign "
"and value");
/* Set the key to this option. */
switch(key)
{
/* Read the non-option tokens (arguments): */
case ARGP_KEY_ARG:
/* The user may give a shell variable that is empty! In that case
'arg' will be an empty string! We don't want to account for such
cases (and give a clear error that no input has been given). */
if(arg[0]!='\0') gal_list_str_add(&p->tokens, arg, 0);
break;
/* This is an option, set its value. */
default:
return gal_options_set_from_key(key, arg, p->cp.poptions, &p->cp);
}
return 0;
}
/**************************************************************/
/*************** Sanity Check *******************/
/**************************************************************/
static int
ui_check_dash_is_negative(char *string)
{
if( isdigit(string[1]) /* We already know 'string[0]' is '-' */
|| !strcmp(string, "-nan")
|| !strcmp(string, "-inf") )
return 1;
else return 0;
}
/* Check ONLY the options. When arguments are involved, do the check
in 'ui_check_options_and_arguments'. */
static void
ui_check_only_options(struct arithmeticparams *p)
{
if(p->wcsfile && strcmp(p->wcsfile,"none"))
{
if(gal_fits_file_recognized(p->wcsfile)==0)
error(EXIT_FAILURE, 0, "%s: file given to '--wcsfile' must be in "
"FITS format with a recognizable FITS format suffix.",
p->wcsfile);
if(p->wcshdu==NULL)
error(EXIT_FAILURE, 0, "%s: no HDU/extension specified (file given "
"to '--wcsfile')! Please use '--wcshdu' to specify a "
"HDU/extension to read from", p->wcsfile);
}
/* In case meta information are given, correct them into simple lists. */
gal_options_merge_list_of_csv(&p->metaname);
gal_options_merge_list_of_csv(&p->metaunit);
gal_options_merge_list_of_csv(&p->metacomment);
}
/* Sanity check on options AND arguments. If only option values are to be
checked, use 'ui_check_only_options'. */
static void
ui_check_options_and_arguments(struct arithmeticparams *p)
{
gal_list_str_t *token, *hdu;
size_t nummultiext=0, numhdus=0;
char *tofilename=NULL, *basename=NULL;
struct gal_options_common_params *cp=&p->cp;
/* First, make sure that tokens are actually given. */
if(p->tokens)
{
/* The input tokens are put in a lastin-firstout (simple) linked
list, so change them to the correct order so the order we pop a
token is the same order that the user input a value. Note that for
the options this was done in 'gal_options_read_config_set'. */
gal_list_str_reverse(&p->tokens);
}
else
{
if(p->arguments)
{
p->tokens=gal_txt_read_to_list(p->arguments);
free(p->arguments); p->arguments=NULL;
}
else
error(EXIT_FAILURE, 0, "no input tokens. Please specify a file "
"name or number (as operands) along with operator(s) as "
"input; or use the '--arguments' options. Please run any "
"of the following commands for more information.\n\n"
" $ astarithmetic --help # Short info.\n"
" $ info astarithmetic # Full invocation "
"documentation.\n");
}
/* To allow adding extensions to existing files, let the 'keep' flag be
the same as the 'dontdelete'. */
cp->keep=cp->dontdelete;
/* Set the output file name (if any is needed). Note that since the lists
are already reversed, the first FITS file encountered, is the first
FITS file given by the user. Also, note that these file name
operations are only necessary for the first FITS file in the token
list. In some scnearios, we need to know if an actual output name was
given or if the output name was set automatically. So we'll set
'outnamerequested' before automatically filling the output if not
given. */
p->outnamerequested = cp->output ? 1 : 0;
for(token=p->tokens; token!=NULL; token=token->next)
{
/* Strings given to the 'tofile' or 'tofilefree' operators are also
considered as outputs and we should delete them before starting
the parse. */
tofilename = ( strncmp(OPERATOR_PREFIX_TOFILE, token->v,
OPERATOR_PREFIX_LENGTH_TOFILE)==0
? &token->v[ OPERATOR_PREFIX_LENGTH_TOFILE ]
: ( strncmp(OPERATOR_PREFIX_TOFILEFREE, token->v,
OPERATOR_PREFIX_LENGTH_TOFILEFREE)==0
? &token->v[ OPERATOR_PREFIX_LENGTH_TOFILEFREE ]
: NULL ) );
if(tofilename)
gal_checkset_writable_remove(tofilename, basename, cp->keep,
cp->dontdelete);
/* This may be a simple filename. */
else
{
/* This token is a file, count how many mult-extension files we
have and use the first to set the output file's name (if it
has not been set). */
if( gal_array_name_recognized(token->v)
|| gal_fits_file_recognized(token->v) )
{
/* Increment the counter for FITS files (if they are
input). Recall that the 'load-col' operator can also have
'.fits' suffixes, but they aren't relevant here because
they are inputs, and their HDUs are given within the
operator string. */
if( strncmp(GAL_ARITHMETIC_OPSTR_LOADCOL_PREFIX, token->v,
GAL_ARITHMETIC_OPSTR_LOADCOL_PREFIX_LEN)
&& gal_array_name_recognized_multiext(token->v) )
++nummultiext;
/* If no output name is given, we need to extract the output
name from the inputs. */
if(basename==NULL) basename=token->v;
}
/* This token is a number. Check if a negative dash was present
that has been temporarily replaced with 'NEG_DASH_REPLACE'
before option parsing. */
else if( token->v[0]==NEG_DASH_REPLACE
&& ui_check_dash_is_negative(token->v) )
token->v[0]='-';
}
}
/* In case no output name has been given (can happen with operators like
'makenew' when the user doesn't set an input name explicity), use a
default name. */
if(p->append) cp->keep=1;
if(cp->output)
gal_checkset_writable_remove(cp->output, basename, cp->keep,
cp->dontdelete);
else
{
if(basename)
p->cp.output=gal_checkset_automatic_output(cp, basename,
"_arith.fits");
else
{
gal_checkset_allocate_copy("arithmetic.fits", &cp->output);
gal_checkset_writable_remove(cp->output, basename, cp->keep,
cp->dontdelete);
}
}
/* Count the number of HDU values (if globalhdu isn't given) and check if
its not less than the number of input FITS images. */
if(p->globalhdu)
{ if(p->hdus) { gal_list_str_free(p->hdus, 1); p->hdus=NULL; }; }
else
{
for(hdu=p->hdus; hdu!=NULL; hdu=hdu->next) ++numhdus;
if(numhdus<nummultiext)
error(EXIT_FAILURE, 0, "not enough HDUs. There are %zu input "
"files in formats that may contain multiple extensions (for "
"example FITS or TIFF). Therefore, the '--hdu' ('-h') option "
"must be called atleaset %zu times (once for each "
"multi-extension file). If the HDU value is the same for all "
"the files, you may use '--globalhdu' ('-g') to specify a "
"single HDU to be used for any number of input files",
nummultiext, nummultiext);
}
}
static void
ui_preparations(struct arithmeticparams *p)
{
size_t ndim, *dsize;
/* In case a file is specified to read the WCS from (and ignore input
datasets), read the WCS prior to starting parsing of the arguments. */
if(p->wcsfile && strcmp(p->wcsfile,"none"))
{
/* Read the number of dimensions and the size of each. */
dsize=gal_fits_img_info_dim(p->wcsfile, p->wcshdu, &ndim,
"--wcshdu");
/* Read the WCS. */
p->refdata.wcs=gal_wcs_read(p->wcsfile, p->wcshdu,
p->cp.wcslinearmatrix, 0, 0,
&p->refdata.nwcs, "--wcshdu");
if(p->refdata.wcs)
{
if(!p->cp.quiet)
printf(" - WCS: %s (hdu %s).\n", p->wcsfile, p->wcshdu);
}
else
fprintf(stderr, "WARNING: %s (hdu %s) didn't contain a "
"(readable by WCSLIB) WCS.\n", p->wcsfile, p->wcshdu);
/* Correct the WCS dimensions if necessary. Note that we don't need
the 'ndim' or 'dsize' any more. */
ndim=gal_dimension_remove_extra(ndim, dsize, p->refdata.wcs);
/* Clean up. */
free(dsize);
}
}
/**************************************************************/
/************ Set the parameters *************/
/**************************************************************/
void
ui_read_check_inputs_setup(int argc, char *argv[],
struct arithmeticparams *p)
{
size_t i;
struct gal_options_common_params *cp=&p->cp;
/* Include the parameters necessary for argp from this program ('args.h')
and for the common options to all Gnuastro ('commonopts.h'). We want
to directly put the pointers to the fields in 'p' and 'cp', so we are
simply including the header here to not have to use long macros in
those headers which make them hard to read and modify. This also helps
in having a clean environment: everything in those headers is only
available within the scope of this function. */
#include <gnuastro-internal/commonopts.h>
#include "args.h"
/* Initialize the options and necessary information. */
ui_initialize_options(p, program_options, gal_commonopts_options);
/* The dash of a negative number will cause problems with the option
readin. To work properly we will go over all the options/arguments and
if any one starts with a dash and is followed by a number, then the
dash is replaced by NEG_DASH_REPLACE. */
for(i=0;i<argc;++i)
if( argv[i][0]=='-' && ui_check_dash_is_negative(argv[i]) )
argv[i][0]=NEG_DASH_REPLACE;
/* Read the command-line options and arguments. */
errno=0;
if(argp_parse(&thisargp, argc, argv, 0, 0, p))
error(EXIT_FAILURE, errno, "parsing arguments");
/* Read the configuration files. */
gal_options_read_config_set(cp);
/* Print the option values if asked. Note that this needs to be done
after the sanity check so un-sane values are not printed in the output
state. */
gal_options_print_state(cp);
/* Prepare all the options as FITS keywords to write in output later. */
gal_options_as_fits_keywords(&p->cp);
/* Sanity check only on options. */
ui_check_only_options(p);
/* Check that the options and arguments fit well with each other. Note
that arguments don't go in a configuration file. So this test should
be done after (possibly) printing the option values. */
ui_check_options_and_arguments(p);
/* Initial preparations. */
ui_preparations(p);
}
/**************************************************************/
/************ Free allocated, report *************/
/**************************************************************/
void
ui_free_report(struct arithmeticparams *p, struct timeval *t1)
{
/* Free the simple strings. */
free(p->cp.output);
if(p->wcshdu) free(p->wcshdu);
if(p->globalhdu) free(p->globalhdu);
if(p->metaname) gal_list_str_free(p->metaname, 1);
if(p->metaunit) gal_list_str_free(p->metaunit, 1);
if(p->metacomment) gal_list_str_free(p->metacomment, 1);
/* If there are any remaining HDUs in the hdus linked list, then
free them. */
if(p->hdus)
gal_list_str_free(p->hdus, 1);
/* Report the duration of the job */
if(!p->cp.quiet)
gal_timing_report(t1, PROGRAM_NAME" finished in", 0);
}
|