Beispiel #1
0
int main(int argc, char *argv[])
{
    /* Important definitions */
    // Lengths
    size_t N = 0;  // Length of time series
    size_t M = 0;  // Length of sampling vector (number of frequencies)

    // Filenames
    char inname[100];
    char outname[100];

    // Sampling
    double low, high, rate;

    // Frequency of window function
    double winfreq = 0;

    // Options
    int quiet = 0;
    int unit = 1;
    int prep = 1;
    int autosamp = 0;
    int fast = 0;
    int useweight = 0;
    int windowmode = 0;
    int Nclean = 0;
    int filter = 0;

    
    /* Process command line arguments and return line count of the input file */
    N = cmdarg(argc, argv, inname, outname, &quiet, &unit, &prep, &low, &high,\
               &rate, &autosamp, &fast, &useweight, &windowmode, &winfreq,\
               &Nclean, &filter, NULL, NULL);
    
    // Pretty print
    if ( quiet == 0 || fast == 1 ){
        if ( windowmode == 0 && useweight != 0 )
            printf("\nCalculating the weighted power spectrum of \"%s\" ...\n",\
                   inname);
        else if ( windowmode == 0 )
            printf("\nCalculating the power spectrum of \"%s\" ...\n", inname);
        else
            printf("\nCalculating the window function of \"%s\" ...\n", inname);
    }
    

    /* Read data (and weights) from the input file */
    if ( quiet == 0 ) printf(" - Reading input\n");
    double* time = malloc(N * sizeof(double));
    double* flux = malloc(N * sizeof(double));
    double* weight = malloc(N * sizeof(double));
    readcols(inname, time, flux, weight, N, useweight, unit, quiet);
    
    // Do if fast-mode and window-mode is not activated
    if ( fast == 0 && windowmode == 0 ) {
        // Calculate Nyquist frequency
        double* dt = malloc(N-1 * sizeof(double));
        double nyquist;
        arr_diff(time, dt, N);
        nyquist = 1.0 / (2.0 * arr_median(dt, N-1)) * 1e6; // microHz !
        free(dt);

        // Calculate suggested sampling (4 times oversampling)
        double minsamp;
        minsamp = 1.0e6 / (4 * (time[N-1] - time[0])); // microHz !
    
        // Display info?
        if ( quiet == 0 ){
            printf(" -- INFO: Length of time series = %li\n", N);
            printf(" -- INFO: Nyquist frequency = %.2lf microHz\n", nyquist);
            printf(" -- INFO: Suggested minimum sampling = %.3lf microHz\n",\
                   minsamp);
        }

        // Apply automatic sampling?
        if ( autosamp != 0 ) {
            low = 5.0;
            high = nyquist;
            rate = minsamp;
        }
    }

    
    /* Prepare for power spectrum */
    // Calculate proper frequency range for window-function-mode
    double limit = 0;
    if ( windowmode != 0 ) {
        limit = low;
        low = winfreq - limit;
        high = winfreq + limit;
    }
    
    // Get length of sampling vector
    M = arr_util_getstep(low, high, rate);

    // Fill sampling vector with cyclic frequencies
    double* freq = malloc(M * sizeof(double));
    arr_init_linspace(freq, low, rate, M);

    // Initialise arrays for data storage
    double* power = malloc(M * sizeof(double));
    double* alpha = malloc(M * sizeof(double));
    double* beta = malloc(M * sizeof(double));


    /* Calculate power spectrum OR window function */
    if ( windowmode == 0 ) {
        // Subtract the mean to avoid "zero-frequency" problems
        if ( prep != 0 ) {
            if ( quiet == 0 ){
                printf(" - Subtracting the mean from time series\n");
            }
            arr_sca_add(flux, -arr_mean(flux, N), N);
        }
        else {
            if ( quiet == 0 )
                printf(" - Time series used *without* mean subtraction!\n");
        }
    
        // Display info
        if ( quiet == 0 ){
            printf(" - Calculating fourier transform\n");
            if ( autosamp != 0 ) {
                printf(" -- NB: Using automatic sampling!\n");
                printf(" -- INFO: Auto-sampling (in microHz): %.2lf to %.2lf"\
                       " in steps of %.4lf\n", low, high, rate);
            }
            else {
                printf(" -- INFO: Sampling (in microHz): %.2lf to %.2lf in"\
                       " steps of %.4lf\n", low, high, rate);
            }
            printf(" -- INFO: Number of sampling frequencies = %li\n", M);
        }

        // Calculate power spectrum with or without weights
        fourier(time, flux, weight, freq, N, M, power, alpha, beta, useweight);
    }
    else {
        if ( quiet == 0 ){
            printf(" - Calculating window function\n");
            printf(" -- INFO: Window frequency = %.2lf microHz\n", winfreq);
            printf(" -- INFO: Sampling in the range +/- %.2lf microHz in" \
                   " steps of %.4lf microHz\n", limit, rate);
            printf(" -- INFO: Number of sampling frequencies = %li\n", M);
        }

        // Calculate spectral window with or without weights
        windowfunction(time, freq, weight, N, M, winfreq, power, useweight);

        if ( quiet == 0 )
            printf(" - Sum of spectral window = %.4lf\n", arr_sum(power, M));

        // Move frequencies to the origin
        arr_sca_add(freq, -winfreq, M);
    }

        
    /* Write data to file */
    if ( quiet == 0 ) printf(" - Saving to file \"%s\"\n", outname);
    writecols(outname, freq, power, M);

    
    /* Free data */
    free(time);
    free(flux);
    free(weight);
    free(freq);
    free(power);
    free(alpha);
    free(beta);


    /* Done! */
    if ( quiet == 0 || fast ==1 ) printf("Done!\n\n");
    return 0; 
}
Beispiel #2
0
int
intip(char *ifname, int ifs, int argc, char **argv)
{
	int set, alias, flags, argcmax;
	ip_t ip;
	struct in_addr destbcast;
	struct ifaliasreq addreq, ridreq;
	struct sockaddr_in *sin;
	char  *msg, *cmdname;

	memset(&addreq, 0, sizeof(addreq));
	memset(&ridreq, 0, sizeof(ridreq));

	if (NO_ARG(argv[0])) {
		set = 0;
		argc--;
		argv++;
	} else
		set = 1;

	/*
	 * We use this function for ip and alias setup since they are
	 * the same thing.
	 */
	if (isprefix(argv[0], "alias")) {
		alias = 1;
		cmdname = "alias";
	} else if (isprefix(argv[0], "ip")) {
		alias = 0;
		cmdname = "ip";
	} else {
		printf("%% intip: Internal error\n");
		return 0;
	}

	argc--;
	argv++;

	flags = get_ifflags(ifname, ifs);
	if (flags & IFF_POINTOPOINT) {
		argcmax = 2;
		msg = "destination";
	} else if (flags & IFF_BROADCAST) {
		argcmax = 2;
		msg = "broadcast";
	} else {
		argcmax = 1;
		msg = NULL;
	}

	if (argc < 1 || argc > argcmax) {
		printf("%% %s <address>/<bits> %s%s%s\n", cmdname,
		    msg ? "[" : "", msg ? msg : "", msg ? "]" : "");
		printf("%% %s <address>/<netmask> %s%s%s\n", cmdname,
		    msg ? "[" : "", msg ? msg : "", msg ? "]" : "");
		printf("%% no %s <address>[/bits]\n", cmdname);
		printf("%% no %s <address>[/netmask]\n", cmdname);
		return(0);
	}

	/* ignore 'address' keyword, don't print error */
	if (isprefix(argv[0], "address")) {
		argc--;
		argv++;
	}

	if (isprefix(argv[0], "dhcp")) {
		char *args[] = { PKILL, "dhclient", ifname, '\0' };
		char leasefile[sizeof(LEASEPREFIX)+1+IFNAMSIZ];

		if (set)
			cmdarg(DHCLIENT, ifname);
		else {
			cmdargs(PKILL, args);
			snprintf(leasefile, sizeof(leasefile), "%s.%s",
			    LEASEPREFIX, ifname);
			rmtemp(leasefile);
		}
		return(0);
	}

	ip = parse_ip(argv[0], NO_NETMASK);

	if (ip.family == 0)
		/* bad IP specified */
		return(0);

	if (ip.bitlen == -1) {
		printf("%% Netmask not specified\n");
		return(0);
	}
	
	if (argc == 2)
		if (!inet_aton(argv[1], &destbcast)) {
			printf("%% Invalid %s address\n", msg);
			return(0);
		}
	
	strlcpy(addreq.ifra_name, ifname, sizeof(addreq.ifra_name));
	strlcpy(ridreq.ifra_name, ifname, sizeof(ridreq.ifra_name));

	if (!set) {
		sin = (struct sockaddr_in *)&ridreq.ifra_addr;
		sin->sin_len = sizeof(ridreq.ifra_addr);
		sin->sin_family = AF_INET;
		sin->sin_addr.s_addr = ip.addr.sin.s_addr;
	}

	if (!alias || !set) {
		/*
		 * Here we remove the top IP on the interface before we
		 * might add another one, or we delete the specified IP.
		 */
		if (ioctl(ifs, SIOCDIFADDR, &ridreq) < 0)
			if (!set)
				printf("%% intip: SIOCDIFADDR: %s\n",
				    strerror(errno));
	}

	if (set) {
		sin = (struct sockaddr_in *)&addreq.ifra_addr;
		sin->sin_family = AF_INET;
		sin->sin_len = sizeof(addreq.ifra_addr);
		sin->sin_addr.s_addr = ip.addr.sin.s_addr;
		sin = (struct sockaddr_in *)&addreq.ifra_mask;
		sin->sin_family = AF_INET;
		sin->sin_len = sizeof(addreq.ifra_mask);
		sin->sin_addr.s_addr = htonl(0xffffffff << (32 - ip.bitlen));
		if (argc == 2) {
			sin = (struct sockaddr_in *)&addreq.ifra_dstaddr;
			sin->sin_family = AF_INET;
			sin->sin_len = sizeof(addreq.ifra_dstaddr);
			sin->sin_addr.s_addr = destbcast.s_addr;
		}
		if (ioctl(ifs, SIOCAIFADDR, &addreq) < 0)
			printf("%% intip: SIOCAIFADDR: %s\n", strerror(errno));
	}

	return(0);
}
Beispiel #3
0
int main ( int argc, char *argv[] )
{
/***********************************************************************
 * Local variables
 ***********************************************************************/
    int ierr    = 0;    // Flag errors
    char *error = NULL; // Error message string

    double t1, t2, t3, t4, t5; // Variables to track runtime

    /* File in/out handling variables */
    char *inputFile = NULL, *outputFile = NULL;
    FILE *fp_in     = NULL, *fp_out     = NULL;

    input_data input_vars;               // Struct to store input variables
    input_data_init ( &input_vars );     // Set variables to initial values

    para_data para_vars;                 // Struct to store parallel variables
    para_data_init ( &para_vars );       // Set variables to initial values

    time_data time_vars;                 // Struct to store time variables
    time_data_init ( &time_vars );       // Set variables to initial values

    geom_data geom_vars;                 // Struct to store geometry variables
    geom_data_init ( &geom_vars );       // Set variables to initial values

    sn_data sn_vars;                     // Struct to store sn variables
    sn_data_init ( &sn_vars );           // Set variables to initial values

    data_data data_vars;                 // Struct to store data variables
    data_data_init ( &data_vars );       // Set variables to initial values

    control_data control_vars;           // Struct to store control variables
    control_data_init ( &control_vars ); // Set variables to initial values

    mms_data mms_vars;                   // Struct to store mms variables
    mms_data_init ( &mms_vars );         // Set variables to initial values

    solvar_data solvar_vars;             // Struct to store solvar variables
    solvar_data_init ( &solvar_vars );   // Set variables to initial values

    sweep_data sweep_vars;               // Struct to store sweep variables
    sweep_data_init ( &sweep_vars );     // Set variables to initial values

    dim_sweep_data dim_sweep_vars;

/***********************************************************************
 * Perform calls that set up the parallel environment in MPI and
 * OpenMP. Also starts the timer. Update parallel setup time.
 ***********************************************************************/
    /* Initialize the parallel environment */
    pinit ( argc, argv, &para_vars, &t1, &ierr );

    t2 = wtime(); // Get the MPI walltime

    /* Calc parallel setup time */
    time_vars.tparset = time_vars.tparset + t2 - t1;


/***********************************************************************
 * Read the command line arguments to get i/o file names.
 * Open the two files.
 ***********************************************************************/
    ierr = cmdarg ( argc, argv, &inputFile, &outputFile, &error,
             para_vars.iproc, para_vars.root );

    bcast_i_scalar ( &ierr, para_vars.comm_snap, para_vars.root, para_vars.nproc );

    /* Ensure arguments are valid */
    if ( ierr != 0 )
    {
        print_error ( NULL, error, para_vars.iproc, para_vars.root );

        FREE ( inputFile );
        FREE ( outputFile );
        FREE ( error );

        stop_run ( 0, 0, 0, &para_vars, &sn_vars, &data_vars, &mms_vars,
                   &geom_vars, &solvar_vars, &control_vars );
    }

    /* Open the input file to read in initial values */
    ierr = open_file ( &fp_in, inputFile, "r", &error, para_vars.iproc, para_vars.root );

    bcast_i_scalar ( &ierr, para_vars.comm_snap, para_vars.root, para_vars.nproc);

    /* Ensure input file is found */
    if ( ierr != 0 )
    {
        print_error ( NULL, error, para_vars.iproc, para_vars.root );

        FREE ( inputFile );
        FREE ( outputFile );
        FREE ( error );

        stop_run ( 0, 0, 0, &para_vars, &sn_vars, &data_vars, &mms_vars,
                   &geom_vars, &solvar_vars, &control_vars );
    }

    /* Open the output file to write results and error messages */
    ierr = open_file ( &fp_out, outputFile, "w", &error, para_vars.iproc, para_vars.root );

    bcast_i_scalar ( &ierr, para_vars.comm_snap, para_vars.root, para_vars.nproc );

    /* Ensure output file can be created */
    if ( ierr != 0 )
    {
        print_error ( NULL, error, para_vars.iproc, para_vars.root );

        FREE ( inputFile );
        FREE ( outputFile );
        FREE ( error );

        stop_run ( 0, 0, 0, &para_vars, &sn_vars, &data_vars, &mms_vars,
                   &geom_vars, &solvar_vars, &control_vars );
    }

/***********************************************************************
 * Write code version and execution time to output.
 ***********************************************************************/
    if ( para_vars.iproc == para_vars.root ) version_print ( fp_out );

/***********************************************************************
 * Read input
 ***********************************************************************/
    ierr = read_input ( fp_in, fp_out, &input_vars, &para_vars, &time_vars );

    ierr = close_file ( fp_in, inputFile, &error, para_vars.iproc,
                        para_vars.root );

    FREE ( inputFile );

    bcast_i_scalar ( &ierr, para_vars.comm_snap, para_vars.root, para_vars.nproc );

    if ( ierr != 0 )
    {
        print_error ( fp_out, error, para_vars.iproc, para_vars.root );

        FREE ( outputFile );
        FREE ( error );

        stop_run ( 0, 0, 0, &para_vars, &sn_vars, &data_vars, &mms_vars,
                   &geom_vars, &solvar_vars, &control_vars );
    }

/***********************************************************************
 * Get nthreads for each proc. Print the warning about resetting
 * nthreads if necessary. Don't stop run. Set up the SDD MPI topology.
 ***********************************************************************/
    t3 = wtime();

    pinit_omp ( para_vars.comm_snap, &input_vars.nthreads, input_vars.nnested,
                &para_vars.do_nested, &ierr, &error );

    if ( ierr != 0 ) print_error ( NULL, error, para_vars.iproc,
                                   para_vars.root );

    pcomm_set ( input_vars.npey, input_vars.npez, &para_vars, &ierr );

    t4 = wtime();

    time_vars.tparset = time_vars.tparset + t4 - t3;

/***********************************************************************
 * Setup problem
 ***********************************************************************/
    setup ( &input_vars, &para_vars, &time_vars, &geom_vars, &sn_vars,
            &data_vars, &solvar_vars, &control_vars, &mms_vars, fp_out,
            &ierr, &error );

/***********************************************************************
 * Call for the problem solution
 ***********************************************************************/
    translv ( &input_vars, &para_vars, &time_vars, &geom_vars, &sn_vars,
              &data_vars, &control_vars, &solvar_vars, &mms_vars,
              &sweep_vars, &dim_sweep_vars, fp_out, &ierr, &error );

/***********************************************************************
 * Output the results. Print the timing summary
 ***********************************************************************/
    output ( &input_vars, &para_vars, &time_vars, &geom_vars, &data_vars,
             &sn_vars, &control_vars, &mms_vars, &solvar_vars, &sweep_vars,
             fp_out, &ierr, &error );

    if ( para_vars.iproc == para_vars.root ) time_summ ( fp_out, &time_vars );

/***********************************************************************
 * Final cleanup: deallocate, close output file, end the program
 ***********************************************************************/
    dealloc_input ( 3, &sn_vars, &data_vars, &mms_vars );
    dealloc_solve ( 3, &geom_vars, &solvar_vars, &control_vars );

    t5 = wtime();
    time_vars.tsnap = t5 - t1;

    if ( para_vars.iproc == para_vars.root )
    {
        fprintf ( fp_out, "  Total Execution time"
                  "                   %.4E\n\n", time_vars.tsnap );
        fprintf ( fp_out, "  Grind Time (nanoseconds)"
                  "         %.4E\n\n", time_vars.tgrind );
        fprintf ( fp_out,
                  "****************************************"
                  "****************************************\n" );
    }

    ierr = close_file ( fp_out, outputFile, &error, para_vars.iproc, para_vars.root );

    FREE ( outputFile );

    bcast_i_scalar ( &ierr, para_vars.comm_snap, para_vars.root, para_vars.nproc );

    if ( ierr != 0 )
    {
        print_error ( 0, error, para_vars.iproc, para_vars.root );

        FREE ( error );

        stop_run ( 0, 0, 0, &para_vars, &sn_vars, &data_vars, &mms_vars,
                   &geom_vars, &solvar_vars, &control_vars );
    }


    if ( control_vars.otrdone )
    {
        FREE ( error );

        stop_run ( 0, 0, 1, &para_vars, &sn_vars, &data_vars, &mms_vars,
                   &geom_vars, &solvar_vars, &control_vars );
    }
    else
    {
        FREE ( error );

        stop_run ( 0, 0, 2, &para_vars, &sn_vars, &data_vars, &mms_vars,
                   &geom_vars, &solvar_vars, &control_vars );
    }

    return 0;
}
Beispiel #4
0
int
main(int argc, register char** argv)
{
	register int	n;
	register char*	s;
	char*		args;
	char*		codes;
	char**		av;
	char**		ap;
	int		i;
	int		count;
	int		len;
	int		traverse;
	int		size;
	Dir_t*		firstdir;
	Dir_t*		lastdir;
	Exnode_t*	x;
	Exnode_t*	y;
	Ftw_t		ftw;
	Finddisc_t	disc;

	setlocale(LC_ALL, "");
	error_info.id = "tw";
	av = argv + 1;
	args = 0;
	codes = 0;
	count = 0;
	size = 0;
	traverse = 1;
	firstdir = lastdir = newof(0, Dir_t, 1, 0);
	firstdir->name = ".";
	state.action = LIST;
	state.cmdflags = CMD_EXIT|CMD_IGNORE|CMD_IMPLICIT|CMD_NEWLINE;
	state.errexit = EXIT_QUIT;
	state.ftwflags = ftwflags()|FTW_DELAY;
	state.select = ALL;
	state.separator = '\n';
	memset(&disc, 0, sizeof(disc));
	for (;;)
	{
		switch (optget(argv, usage))
		{
		case 'a':
			args = opt_info.arg;
			state.cmdflags |= CMD_POST;
			continue;
		case 'c':
			if ((count = opt_info.num) < 0)
				error(3, "argument count must be >= 0");
			continue;
		case 'd':
			lastdir = lastdir->next = newof(0, Dir_t, 1, 0);
			lastdir->name = opt_info.arg;
			continue;
		case 'e':
			compile(opt_info.arg, 0);
			continue;
		case 'f':
			state.pattern = opt_info.arg;
			continue;
		case 'i':
			state.ignore = 1;
			continue;
		case 'l':
			state.localfs = 1;
			continue;
		case 'm':
			state.intermediate = 1;
			continue;
		case 'n':
			traverse = 0;
			continue;
		case 'p':
			state.ftwflags |= FTW_TWICE;
			continue;
		case 'q':
			state.cmdflags |= CMD_QUERY;
			continue;
		case 'r':
			state.ftwflags |= FTW_RECURSIVE;
			continue;
		case 's':
			if ((size = opt_info.num) < 0)
				error(3, "command size must be >= 0");
			continue;
		case 't':
			state.cmdflags |= CMD_TRACE;
			continue;
		case 'x':
			state.errexit = opt_info.arg ? opt_info.num : EXIT_QUIT;
			continue;
		case 'z':
			if (s = sfgetr(sfstdin, '\n', 1))
			{
				if (!(s = strdup(s)))
					error(ERROR_SYSTEM|3, "out of space");
				n = state.snapshot.format.delim = *s++;
				state.snapshot.format.path = s;
				if (!(s = strchr(s, n)))
				{
				osnap:
					error(3, "invalid snapshot on standard input");
				}
				*s++ = 0;
				if (!streq(state.snapshot.format.path, SNAPSHOT_ID))
					goto osnap;
				state.snapshot.format.path = s;
				if (!(s = strchr(s, n)))
					goto osnap;
				*s++ = 0;
				state.snapshot.format.easy = s;
				if (!(s = strchr(s, n)))
					goto osnap;
				*s++ = 0;
				if (*(state.snapshot.format.hard = s))
				{
					if (!(s = strchr(s, n)))
						goto osnap;
					*s = 0;
				}
				else
					state.snapshot.format.hard = 0;
				state.snapshot.sp = sfstdin;
				state.snapshot.prev = sfgetr(sfstdin, '\n', 0);
			}
			else
			{
				state.snapshot.format.path = SNAPSHOT_PATH;
				state.snapshot.format.easy = SNAPSHOT_EASY;
				state.snapshot.format.hard = SNAPSHOT_HARD;
				state.snapshot.format.delim = SNAPSHOT_DELIM[0];
			}
			if (!(state.snapshot.tmp = sfstropen()))
				error(ERROR_SYSTEM|3, "out of space");
			compile("sort:name;", 0);
			continue;
		case 'C':
			state.ftwflags |= FTW_NOSEEDOTDIR;
			continue;
		case 'D':
			error_info.trace = -opt_info.num;
			continue;
		case 'E':
			compile(opt_info.arg, 1);
			continue;
		case 'F':
			codes = opt_info.arg;
			continue;
		case 'G':
			disc.flags |= FIND_GENERATE;
			if (streq(opt_info.arg, "old"))
				disc.flags |= FIND_OLD;
			else if (streq(opt_info.arg, "gnu") || streq(opt_info.arg, "locate"))
				disc.flags |= FIND_GNU;
			else if (streq(opt_info.arg, "type"))
				disc.flags |= FIND_TYPE;
			else if (streq(opt_info.arg, "?"))
			{
				error(2, "formats are { default|dir type old gnu|locate }");
				return 0;
			}
			else if (!streq(opt_info.arg, "-") && !streq(opt_info.arg, "default") && !streq(opt_info.arg, "dir"))
				error(3, "%s: invalid find codes format -- { default|dir type old gnu|locate } expected", opt_info.arg);
			continue;
		case 'H':
			state.ftwflags |= FTW_META|FTW_PHYSICAL;
			continue;
		case 'I':
			state.icase = 1;
			continue;
		case 'L':
			state.ftwflags &= ~(FTW_META|FTW_PHYSICAL|FTW_SEEDOTDIR);
			continue;
		case 'P':
			state.ftwflags &= ~FTW_META;
			state.ftwflags |= FTW_PHYSICAL;
			continue;
		case 'S':
			state.separator = *opt_info.arg;
			continue;
		case 'X':
			state.ftwflags |= FTW_MOUNT;
			continue;
		case '?':
			error(ERROR_USAGE|4, "%s", opt_info.arg);
			continue;
		case ':':
			error(2, "%s", opt_info.arg);
			continue;
		}
		break;
	}
	argv += opt_info.index;
	argc -= opt_info.index;
	if (error_info.errors)
		error(ERROR_USAGE|4, "%s", optusage(NiL));

	/*
	 * do it
	 */

	if (state.snapshot.tmp)
		sfprintf(sfstdout, "%c%s%c%s%c%s%c%s%c\n",
			state.snapshot.format.delim, SNAPSHOT_ID,
			state.snapshot.format.delim, state.snapshot.format.path,
			state.snapshot.format.delim, state.snapshot.format.easy,
			state.snapshot.format.delim, state.snapshot.format.hard ? state.snapshot.format.hard : "",
			state.snapshot.format.delim);
	if (x = exexpr(state.program, "begin", NiL, 0))
		eval(x, NiL);
	if ((x = exexpr(state.program, "select", NiL, INTEGER)) || (x = exexpr(state.program, NiL, NiL, INTEGER)))
		state.select = x;
	if (!(state.ftwflags & FTW_PHYSICAL))
		state.ftwflags &= ~FTW_DELAY;
	memset(&ftw, 0, sizeof(ftw));
	ftw.path = ftw.name = "";
	if (traverse)
	{
		if (x = exexpr(state.program, "action", NiL, 0))
			state.action = x;
		if (x = exexpr(state.program, "sort", NiL, 0))
		{
			state.sortkey = x;
			y = 0;
			for (;;)
			{
				switch (x->op)
				{
				case ',':
					y = x->data.operand.right;
					/*FALLTHROUGH*/
				case '!':
				case '~':
				case S2B:
				case X2I:
					x = x->data.operand.left;
					continue;
				case ID:
					if (!(x = y))
						break;
					y = 0;
					continue;
				default:
					error(3, "invalid sort identifier (op 0x%02x)", x->op);
					break;
				}
				break;
			}
			state.sort = order;
		}
		if (*argv && (*argv)[0] == '-' && (*argv)[1] == 0)
		{
			state.ftwflags |= FTW_LIST;
			argv++;
			argc--;
		}
		if (*argv || args || count || !(state.cmdflags & CMD_IMPLICIT))
		{
			Cmddisc_t	disc;

			CMDDISC(&disc, state.cmdflags, errorf);
			state.cmd = cmdopen(argv, count, size, args, &disc);
			state.ftwflags |= FTW_DOT;
		}
		else
			state.cmdflags &= ~CMD_IMPLICIT;
		if (codes && (disc.flags & FIND_GENERATE))
		{
			char*	p;
			Dir_t*	dp;
			char	pwd[PATH_MAX];
			char	tmp[PATH_MAX];

			disc.version = FIND_VERSION;
			if (state.cmdflags & CMD_TRACE)
				disc.flags |= FIND_TYPE;
			if (state.cmdflags & CMD_QUERY)
				disc.flags |= FIND_OLD;
			disc.errorf = errorf;
			if (!(state.find = findopen(codes, NiL, NiL, &disc)))
				exit(2);
			if (disc.flags & FIND_TYPE)
			{
				state.act = ACT_CODETYPE;
				compile("_tw_init:mime;", 0);
				state.magicdisc.flags |= MAGIC_MIME;
			}
			else
				state.act = ACT_CODE;
			state.icase = 1;
			state.pattern = 0;
			state.sort = order;
			if (!state.program)
				compile("1", 0);
			if (!(state.sortkey = newof(0, Exnode_t, 1, 0)) || !(state.sortkey->data.variable.symbol = (Exid_t*)dtmatch(state.program->symbols, "name")))
				error(ERROR_SYSTEM|3, "out of space");
			state.sortkey->op = ID;
			s = p = 0;
			for (dp = (firstdir == lastdir) ? firstdir : firstdir->next; dp; dp = dp->next)
			{
				if (*(s = dp->name) == '/')
					sfsprintf(tmp, sizeof(tmp), "%s", s);
				else if (!p && !(p = getcwd(pwd, sizeof(pwd))))
					error(ERROR_SYSTEM|3, "cannot determine pwd path");
				else
					sfsprintf(tmp, sizeof(tmp), "%s/%s", p, s);
				pathcanon(tmp, sizeof(tmp), PATH_PHYSICAL);
				if (!(dp->name = strdup(tmp)))
					error(ERROR_SYSTEM|3, "out of space [PATH_PHYSICAL]");
			}
		}
		else if (state.snapshot.tmp)
			state.act = ACT_SNAPSHOT;
		else if (state.cmdflags & CMD_IMPLICIT)
			state.act = ACT_CMDARG;
		else if (state.action == LIST)
			state.act = ACT_LIST;
		else if (state.action)
			state.act = ACT_EVAL;
		if (state.intermediate)
		{
			state.actII = state.act;
			state.act = ACT_INTERMEDIATE;
		}
		if (state.pattern)
		{
			disc.version = FIND_VERSION;
			if (state.icase)
				disc.flags |= FIND_ICASE;
			disc.errorf = errorf;
			disc.dirs = ap = av;
			if (firstdir != lastdir)
				firstdir = firstdir->next;
			do {*ap++ = firstdir->name;} while (firstdir = firstdir->next);
			*ap = 0;
			if (!(state.find = findopen(codes, state.pattern, NiL, &disc)))
				exit(1);
			state.ftwflags |= FTW_TOP;
			n = state.select == ALL ? state.act : ACT_EVAL;
			while (s = findread(state.find))
			{
				switch (n)
				{
				case ACT_CMDARG:
					if ((i = cmdarg(state.cmd, s, strlen(s))) >= state.errexit)
						exit(i);
					break;
				case ACT_LIST:
					sfputr(sfstdout, s, '\n');
					break;
				default:
					ftwalk(s, tw, state.ftwflags, NiL);
					break;
				}
			}
		}
		else if (state.ftwflags & FTW_LIST)
		{
			sfopen(sfstdin, NiL, "rt");
			n = state.select == ALL && state.act == ACT_CMDARG;
			for (;;)
			{
				if (s = sfgetr(sfstdin, state.separator, 1))
					len = sfvalue(sfstdin) - 1;
				else if (state.separator != '\n')
				{
					state.separator = '\n';
					continue;
				}
				else if (s = sfgetr(sfstdin, state.separator, -1))
					len = sfvalue(sfstdin);
				else
					break;
				if (!n)
					ftwalk(s, tw, state.ftwflags, NiL);
				else if ((i = cmdarg(state.cmd, s, len)) >= state.errexit)
					exit(i);
			}
			if (sferror(sfstdin))
				error(ERROR_SYSTEM|2, "input read error");
		}
		else if (firstdir == lastdir)
			ftwalk(firstdir->name, tw, state.ftwflags, state.sort);
		else
		{
			ap = av;
			while (firstdir = firstdir->next)
				*ap++ = firstdir->name;
			*ap = 0;
			ftwalk((char*)av, tw, state.ftwflags|FTW_MULTIPLE, state.sort);
		}
		if (state.cmd && (i = cmdflush(state.cmd)) >= state.errexit)
			exit(i);
		if (state.find && (findclose(state.find) || state.finderror))
			exit(2);
	}
	else if (state.select)
		error_info.errors = eval(state.select, &ftw) == 0;
	if (x = exexpr(state.program, "end", NiL, 0))
		eval(x, &ftw);
	if (sfsync(sfstdout))
		error(ERROR_SYSTEM|2, "write error");
	exit(error_info.errors != 0);
}
Beispiel #5
0
static void
act(register Ftw_t* ftw, int op)
{
	char*	s;
	Sfio_t*	fp;
	int	i;
	int	j;
	int	k;
	int	n;
	int	r;

	switch (op)
	{
	case ACT_CMDARG:
		if ((i = cmdarg(state.cmd, ftw->path, ftw->pathlen)) >= state.errexit)
			exit(i);
		break;
	case ACT_CODE:
		if (findwrite(state.find, ftw->path, ftw->pathlen, (ftw->info & FTW_D) ? "system/dir" : (char*)0))
			state.finderror = 1;
		break;
	case ACT_CODETYPE:
		fp = sfopen(NiL, PATH(ftw), "r");
		if (findwrite(state.find, ftw->path, ftw->pathlen, magictype(state.magic, fp, PATH(ftw), &ftw->statb)))
			state.finderror = 1;
		if (fp)
			sfclose(fp);
		break;
	case ACT_EVAL:
		eval(state.action, ftw);
		break;
	case ACT_INTERMEDIATE:
		intermediate(ftw, ftw->path);
		break;
	case ACT_LIST:
		sfputr(sfstdout, ftw->path, '\n');
		break;
	case ACT_SNAPSHOT:
		print(state.snapshot.tmp, ftw, state.snapshot.format.path);
		sfputc(state.snapshot.tmp, state.snapshot.format.delim);
		i = sfstrtell(state.snapshot.tmp);
		print(state.snapshot.tmp, ftw, state.snapshot.format.easy);
		j = sfstrtell(state.snapshot.tmp);
		s = sfstrbase(state.snapshot.tmp);
		r = SNAPSHOT_new;
		if (!state.snapshot.prev)
			k = 1;
		else
		{
			do
			{
				if (!(k = urlcmp(state.snapshot.prev, s, state.snapshot.format.delim)))
				{
					r = SNAPSHOT_changed;
					if (!(k = memcmp(state.snapshot.prev + i, s + i, j - i) || state.snapshot.prev[j] != state.snapshot.format.delim))
					{
						if ((n = (int)sfvalue(sfstdin)) > 4 && state.snapshot.prev[n-2] == state.snapshot.format.delim)
						{
							sfwrite(sfstdout, state.snapshot.prev, n - 4);
							sfputc(sfstdout, '\n');
						}
						else
							sfwrite(sfstdout, state.snapshot.prev, n);
					}
				}
				else if (k > 0)
					break;
				else if (k < 0 && (n = (int)sfvalue(sfstdin)) > 4 && (state.snapshot.prev[n-2] != state.snapshot.format.delim || state.snapshot.prev[n-3] != SNAPSHOT_deleted))
				{
					sfwrite(sfstdout, state.snapshot.prev, n - (state.snapshot.prev[n-2] == state.snapshot.format.delim ? 4 : 1));
					sfputc(sfstdout, state.snapshot.format.delim);
					sfputc(sfstdout, SNAPSHOT_deleted);
					sfputc(sfstdout, state.snapshot.format.delim);
					sfputc(sfstdout, '\n');
					if (state.cmdflags & CMD_TRACE)
						error(1, "%s deleted", ftw->path);
				}
				if (!(state.snapshot.prev = sfgetr(sfstdin, '\n', 0)))
					break;
			} while (k < 0);
		}
		if (k)
		{
			if (state.snapshot.format.hard && (ftw->info & FTW_F))
			{
				sfputc(state.snapshot.tmp, state.snapshot.format.delim);
				print(state.snapshot.tmp, ftw, state.snapshot.format.hard);
			}
			sfputc(state.snapshot.tmp, state.snapshot.format.delim);
			sfputc(state.snapshot.tmp, r);
			sfputc(state.snapshot.tmp, state.snapshot.format.delim);
			sfputr(sfstdout, sfstruse(state.snapshot.tmp), '\n');
			if (state.cmdflags & CMD_TRACE)
				error(1, "%s %s", ftw->path, r == SNAPSHOT_new ? "new" : "changed");
		}
		else
			sfstrseek(state.snapshot.tmp, SEEK_SET, 0);
		break;
	}
}
Beispiel #6
0
int main(int argc, char *argv[])
{
    /* Important definitions */
    // Lengths
    size_t N = 0;  // Length of time series
    size_t M = 0;  // Length of sampling vector (number of frequencies)

    // Filenames
    char inname[100];
    char outname[100];
    char logname[100];

    // Sampling
    double low, high, rate;

    // Options
    int quiet = 0;
    int unit = 1;
    int prep = 1;
    int autosamp = 0;
    int fast = 0;
    int useweight = 0;
    int Nclean = 1;
    int filter = 0;

    
    /* Process command line arguments and return line count of the input file */
    N = cmdarg(argc, argv, inname, outname, &quiet, &unit, &prep, &low, &high,\
               &rate, &autosamp, &fast, &useweight, NULL, NULL, &Nclean,\
               &filter, NULL, NULL);

    // Pretty print
    if ( quiet == 0 || fast == 1){
        if ( useweight != 0 )
            printf("\nCLEANing the time series \"%s\" using weights...\n",\
                   inname);
        else
            printf("\nCLEANing the time series \"%s\" without weights...\n",\
                   inname);
    }

    
    /* Read data (and weights) from the input file */
    if ( quiet == 0 ) printf(" - Reading input\n");
    double* time = malloc(N * sizeof(double));
    double* flux = malloc(N * sizeof(double));
    double* weight = malloc(N * sizeof(double));
    readcols(inname, time, flux, weight, N, useweight, unit, quiet);

    // Do if fast-mode is not activated
    if ( fast == 0 ) {
        // Calculate Nyquist frequency
        double* dt = malloc(N-1 * sizeof(double));
        double nyquist;
        arr_diff(time, dt, N);
        nyquist = 1.0 / (2.0 * arr_median(dt, N-1)) * 1e6; // microHz !
        free(dt);

        // Automatic or manual sampling?
        int oversamp;
        if ( autosamp != 0 ) {
            low = 5.0;
            high = nyquist;
            oversamp = 4;
        }
        else {
            oversamp = (int) rate;
        }
            
       
        // Calculate N times oversampling (in microHz!)
        double minsamp = 1.0e6 / (oversamp * (time[N-1] - time[0]));
        rate = minsamp;
    
        // Display info?
        if ( quiet == 0 ){
            printf(" -- INFO: Length of time series = %li\n", N);
            printf(" -- INFO: Nyquist frequency = %.2lf microHz\n", nyquist);
            printf(" -- INFO: Using %i times oversampling = %.3lf microHz\n",\
                   oversamp, minsamp);
        }
    }
    else {
        // Only set the N times oversampling
        int oversamp = (int) rate;
        double minsamp = 1.0e6 / (oversamp * (time[N-1] - time[0]));
        rate = minsamp;
    }

    
    /* Prepare for power spectrum */
    // Get length of sampling vector
    M = arr_util_getstep(low, high, rate);

    // Fill sampling vector with cyclic frequencies
    double* freq = malloc(M * sizeof(double));
    arr_init_linspace(freq, low, rate, M);
    if ( quiet == 0 )
        printf(" -- INFO: Number of sampling frequencies = %li\n", M);

    // Subtract the mean to avoid "zero-frequency" problems
    double fmean = 0;
    if ( prep != 0 ) {
        if ( quiet == 0 ) printf(" - Subtracting the mean from time series\n");
        fmean = arr_mean(flux, N);
        arr_sca_add(flux, -fmean, N);
    }
    else {
        if ( quiet == 0 )
            printf(" - Time series used *without* mean subtraction!\n");
    }


    /* Prepare file for writing the CLEAN-output */
    // Create log-file
    strcpy(logname, outname);
    strcat(logname, ".cleanlog");
    FILE* logfile = fopen(logname, "w");

    // Write header
    fprintf(logfile, "# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"\
            "~~~~~~~~~~\n");
    fprintf(logfile, "# Log of CLEAN on \"%s\"\n", inname);
    fprintf(logfile, "# Interval: [%.2lf, %.2lf] microHz\n", low, high);
    fprintf(logfile, "# Finding %i frequencies\n", Nclean);
    fprintf(logfile, "# \n");
    fprintf(logfile, "# %8s %11s %11s %12s %12s\n", "Number", "Frequency",\
            "Power", "Alpha", "Beta");
    fprintf(logfile, "# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"\
            "~~~~~~~~~~\n");

    
    /* Find and clean peaks */
    // Init variables
    double fmax, alpmax, betmax, powmax;
    
    // Display info
    if ( quiet == 0 ) {
        printf(" - CLEANing %i frequencies in the range %.1lf to %.1lf"\
               " microHz\n", Nclean, low, high);
        printf("\n %9s %11s %11s\n", "Number", "Frequency", "Power");
    }

    // Enter CLEAN-loop
    for (int i = 0; i < Nclean; ++i) {
        // Display progress
        if ( quiet == 0 ) printf(" %6i", i+1);

        // Reset variables
        fmax = 0;
        alpmax = 0;
        betmax = 0;
        powmax = 0;

        // Call with or without weights
        fouriermax(time, flux, weight, freq, N, M, &fmax, &alpmax, &betmax,\
                   useweight);

        // Calculate the power and write to log
        powmax = alpmax*alpmax + betmax*betmax;
        fprintf(logfile, " %6i %15.6lf %12.6lg %12.6lf %12.6lf\n", i+1, fmax,\
                powmax, alpmax, betmax);
        if ( quiet == 0) printf(" %15.6lf %12.6lg \n", fmax, powmax);

        // Remove frequency from time series
        for (int j = 0; j < N; ++j) {
            flux[j] = flux[j] - alpmax * sin( PI2micro*fmax * time[j] ) - \
                                betmax * cos( PI2micro*fmax * time[j] );
        }
    }

    // Final touch
    fclose(logfile);
    if ( quiet == 0 ) printf("\n");

    
    /* Write CLEANed time series to file */
    if ( quiet == 0 ) printf(" - Saving to file \"%s\"\n", outname);

    // Add the mean to the time series data again
    if ( prep != 0 ) arr_sca_add(flux, fmean, N);

    // Save to file
    writecols3(outname, time, flux, weight, N, useweight, unit);

    
    /* Free data */
    free(time);
    free(flux);
    free(weight);
    free(freq);


    /* Done! */
    if ( quiet == 0 || fast ==1 ) printf("Done!\n\n");
    return 0; 
}