Example #1
0
File: HW5.c Project: shn1988110/HW5
void display_message(char input)
{
    char value;
    int i, m;
    for (m = 0; m< 5; ++m)
    {  
        int temp;
        char binary[8];     //initialize binary to be 0b00000000
        value = read_ascii(input,m); //retrieve the hex number from the ascii table
        //hex[m]= value; //assign the read value to a temp hex number holder 
        
        for (i=0;i<8;++i)
        {
            temp = value;
            temp = temp >> 7-i;
            temp = hextobinary(temp);
            binary[7-i]=temp;
        }
        
        for (i = 0; i < 8; ++i)
        {       
            display_pixel_set(start_position[0]+i,start_position[1]+m,binary[i]);
        }
        
    }

}
Example #2
0
SaneWinMain( argc, argv )
{
	FILE *input;
	if( argc > 2 )
	{
		input = sack_fopen( 0, argv[2], WIDE("rb+") );
		if( input )
		{
			if( StrCaseCmpEx( argv[1], WIDE( "u" ), 1 ) == 0 )
			{
				read_ascii( input );
				ascii_to_unicode();
				write_unicode( input );
			}
			else
			{
				read_unicode( input );
				unicode_to_ascii();
				write_ascii( input );
			}
			fclose( input );
		}
		else
			printf( WIDE( "Failed to open %s" ), argv[2] );
	}
	else
	{
		printf( WIDE("Usage: %s [u/a] [filename]\n"), argv[0] );
		printf( WIDE("  u or a is unicode or ascii mode; unicode translates from ascii to unicode\n") );
		printf( WIDE("  ascii translates from unicode to ascii\n") );
		printf( WIDE("  file will be written back in-place\n") );
	}
	return 0;
}
Example #3
0
int main(int argc, char* argv[])
{
	E2promMsg(PROJECT+std::string(" utility ascii2bin V")+VERSION);
	WRITE_FILE = true;

	try {

		parse_parm(argc, argv);

	} catch (e2prom::E2promException &err) {
	
		std::cerr << err.what() << '\n';
		return -1;
	}

	if (2 < argc) 
		read_ascii(argv[1], argv[2]);
	else
		read_ascii(argv[1]);

	return 0;
}
Example #4
0
STLFile::STLFile( const std::string &filename,
		  double vertex_matching_eps, 
		  double signed_volume_eps )
    : _filename(filename), _solid(vertex_matching_eps, signed_volume_eps)
{
    ibsimu.message( 1 ) << "Reading STL-file \'" << filename << "\'\n";
    ibsimu.inc_indent();

    std::ifstream ifstr( filename.c_str(), std::ios_base::binary );
    if( !ifstr.good() )
	throw( Error( ERROR_LOCATION, "Couldn't open file \'" + filename + "\'" ) );

    /* Check if ascii
     * Ascii files start with "solid XXX\n", on first line where XXX is free
     * form text. Second line starts with "facet normal" with possible leading whitespace
     * Binary files have free form 80 byte header
     */
    _ascii = false;
    char buf[1024];
    ifstr.read( buf, 1024 );
    std::streamsize c = ifstr.gcount();
    if( c > 6 && !strncasecmp( buf, "solid ", 6 ) ) {
	// Might be ascii, seek next line
	int a = 6;
	while( a < c && buf[a] != '\n' ) a++;
	while( a < c && isspace(buf[a]) ) a++;
	if( a+12 < c && !strncasecmp( &buf[a], "facet normal", 12 ) )
	    _ascii = true;
    }

    // Read triangle data
    ifstr.clear(); // Clear possible eofbit/failbit
    ifstr.seekg( 0 );
    if( _ascii )
	read_ascii( ifstr );
    else
	read_binary( ifstr );
    ifstr.close();

    // Convert to vertex triangle data
    build_vtriangle_data();
    _solid.check_data();
    _tri.clear();

    ibsimu.dec_indent();
}
Example #5
0
static int 
parse_ppm( FILE *fp, const char *filename, IMAGE *out )
{
	int bits;
	int ascii;
	int msb_first;

	if( read_header( fp, out, &bits, &ascii, &msb_first ) )
		return( -1 );

	/* What sort of read are we doing?
	 */
	if( !ascii && bits >= 8 )
		return( read_mmap( fp, filename, msb_first, out ) );
	else if( !ascii && bits == 1 )
		return( read_1bit_binary( fp, out ) );
	else if( ascii && bits == 1 )
		return( read_1bit_ascii( fp, out ) );
	else 
		return( read_ascii( fp, out ) );
}
Example #6
0
int read_ascii_set( LcSet &set,  const char *lcdir, const char *starid )
{
   char path[1024];
   if( !lcdir_star_dir( lcdir, starid, 'r', path ) )
       return SiteErr::errParams;

   DIR *dir;
   struct dirent *d;
   if ( !(dir = opendir(path)) ) {
      printf("Cannot open %s\n", path );
      return SiteErr::errMissing;
   }

   while ( d = readdir(dir) )
      if ( strncmp( d->d_name, "ascii.", 6 ) == 0 ) {
	 CommonLc *clc = read_ascii( lcdir, starid, d->d_name+6 );
	 if ( clc ) set.append( clc );
      }

   closedir( dir );
   return 0;
}
Example #7
0
void
read_array(xgobidata *xg)
{
  char fname[128];
  FILE *fp;
  static char *suffixes[] = {".dat", ""};

/*
 * Check file exists and open it - for stdin no open needs to be done
 * only assigning fp to be stdin.
*/
  if (strcmp((char *) xg->datafname, "stdin") == 0) {
    fp = stdin;

    /*
     * If reading from stdin, set an alarm.  If after 5 seconds,
     * no data has been read, print an error message and exit.
    */
    if (fp == stdin)
    {
      alarm((unsigned int) 5);
      signal(SIGALRM, stdin_empty);
    }
    read_ascii(fp, xg);
  }
  else {
    /* 
     * Are we reading the missing data into xg->raw_data ?
    */
    if (strcmp(
         ".missing",
         &xg->datafilename[strlen(xg->datafilename) - strlen(".missing")]
       ) == 0)
    {
      if ((fp = fopen(xg->datafilename, "r")) != NULL) {
        char *title, fulltitle[256];
        xg->is_missing_values_xgobi = True;
        xg->missing_values_present = True;
        read_ascii(fp, xg);

        /*
         * extend the title
        */
        title = (char *) XtMalloc(256 * sizeof(char));
        XtVaGetValues(xg->shell,
          XtNtitle, (String) &title,
          NULL);
        sprintf(fulltitle, "%s", title);

        /* -vtitle has been used */
        if (strcmp(xg->vtitle, "") != 0) {
           strcpy(fulltitle, xg->vtitle);
           sprintf(xg->vtitle, "");
        }

        XtVaSetValues(xg->shell,
          XtNtitle, (String) fulltitle,
          XtNiconName, (String) fulltitle,
          NULL);
      }
      else
      {
        (void) fprintf(stderr,
          "The file %s can't be opened for reading.\n", xg->datafilename);
        exit(0);
      }
    }
    else
    {
      /*
       * Try fname.bin before fname, to see whether there is a binary
       * data file available.  If there is, call read_binary().
      */
      strcpy(fname, (char *) xg->datafname);
      strcat(fname, ".bin");

      if ((fp = fopen(fname, "rb")) != NULL)
        read_binary(fp, xg);

      /*
       * If not, look for an ASCII file
      */
      else
      {
        fp = open_xgobi_file((char *) xg->datafname, 2, suffixes, "r", false);

        if (fp == NULL)
          exit(0);

        read_ascii(fp, xg);
      }
    }
  }

  if (xg->is_scatmat)
    make_scatmat(xg);
}
Example #8
0
/*-------------------------------------------------------------------*/
static void cardrdr_execute_ccw ( DEVBLK *dev, BYTE code, BYTE flags,
        BYTE chained, U16 count, BYTE prevcode, int ccwseq,
        BYTE *iobuf, BYTE *more, BYTE *unitstat, U16 *residual )
{
int     rc;                             /* Return code               */
int     num;                            /* Number of bytes to move   */

    UNREFERENCED(flags);
    UNREFERENCED(prevcode);
    UNREFERENCED(ccwseq);

    /* Open the device file if necessary */
    if ( !IS_CCW_SENSE(code) &&
        (dev->fd < 0 || (!dev->bs && !dev->fh)))
    {
        rc = open_cardrdr (dev, unitstat);
        if (rc) return;
    }

    /* Turn all read/feed commands into read, feed, select stacker 1 */
    if ((code & 0x17) == 0x02) code = 0x02;

    /* Turn all feed-only commands into NOP. This is ugly, and should
        really be thought out more. --JRM */
    if ((code & 0x37) == 0x23) code = 0x03;

    /* Process depending on CCW opcode */
    switch (code) {

    case 0x02:
    /*---------------------------------------------------------------*/
    /* READ                                                          */
    /*---------------------------------------------------------------*/
        /* Read next card if not data-chained from previous CCW */
        if ((chained & CCW_FLAGS_CD) == 0)
        {
            for (;;)
            {
                /* Read ASCII or EBCDIC card image */
                if (dev->ascii)
                        rc = read_ascii (dev, unitstat);
                else
                        rc = read_ebcdic (dev, unitstat);

                if (0
                        || rc != -2
                        || !dev->multifile
                        || open_cardrdr (dev, unitstat) != 0
                        )
                break;
            }

            /* Return error status if read was unsuccessful */
            if (rc) break;

            /* Initialize number of bytes in current card */
            dev->cardpos = 0;
            dev->cardrem = CARD_SIZE;

        } /* end if(!data-chained) */

        /* Calculate number of bytes to read and set residual count */
        num = (count < dev->cardrem) ? count : dev->cardrem;
        *residual = count - num;
        if (count < dev->cardrem) *more = 1;

        /* Copy data from card image buffer into channel buffer */
        memcpy (iobuf, dev->buf + dev->cardpos, num);

        /* Update number of bytes remaining in card image buffer */
        dev->cardpos += num;
        dev->cardrem -= num;

        /* Return normal status */
        *unitstat = CSW_CE | CSW_DE;
        break;

    case 0x03:
    /*---------------------------------------------------------------*/
    /* CONTROL NO-OPERATION                                          */
    /*---------------------------------------------------------------*/
        *residual = 0;
        *unitstat = CSW_CE | CSW_DE;
        break;

    case 0x04:
    /*---------------------------------------------------------------*/
    /* SENSE                                                         */
    /*---------------------------------------------------------------*/
        /* Calculate residual byte count */
        num = (count < dev->numsense) ? count : dev->numsense;
        *residual = count - num;
        if (count < dev->numsense) *more = 1;

        /* If sense is clear AND filename = "" OR sockdev and fd=-1 */
        /* Put an IR sense - so that an unsolicited sense can see the intreq */
        if(dev->sense[0]==0)
        {
            if(dev->filename[0]==0x00 ||
                    (dev->bs && dev->fd==-1))
            {
                dev->sense[0] = SENSE_IR;
                dev->sense[1] = SENSE1_RDR_RAIC; /* Retry when IntReq Cleared */
            }
        }

        /* Copy device sense bytes to channel I/O buffer */
        memcpy (iobuf, dev->sense, num);

        /* Clear the device sense bytes */
        memset (dev->sense, 0, sizeof(dev->sense));

        /* Return unit status */
        *unitstat = CSW_CE | CSW_DE;
        break;

    case 0xE4:
    /*---------------------------------------------------------------*/
    /* SENSE ID                                                      */
    /*---------------------------------------------------------------*/
        /* Calculate residual byte count */
        num = (count < dev->numdevid) ? count : dev->numdevid;
        *residual = count - num;
        if (count < dev->numdevid) *more = 1;

        /* Copy device identifier bytes to channel I/O buffer */
        memcpy (iobuf, dev->devid, num);

        /* Return unit status */
        *unitstat = CSW_CE | CSW_DE;
        break;

    default:
    /*---------------------------------------------------------------*/
    /* INVALID OPERATION                                             */
    /*---------------------------------------------------------------*/
        /* Set command reject sense byte, and unit check status */
        dev->sense[0] = SENSE_CR;
        *unitstat = CSW_CE | CSW_DE | CSW_UC;

    } /* end switch(code) */

} /* end function cardrdr_execute_ccw */
Example #9
0
void
main (int argc, char *argv[])
{
    int c;
    extern char *optarg;	/* getopt stuff */
    extern int optind;		/* getopt stuff */
    char *usage =
    "Usage: route_atob [-i ascii_data_file] [-(o|w) binary_out_file]\n";
    char *filename = "stdin";
    char *ofile = "stdout";
    char *wfile = NULL;
    int errors = 0;
    io_t *IO;
    trace_t *default_trace;
    FILE *fd;

    default_trace = New_Trace ();
    IO = New_IO (default_trace);

    while ((c = getopt (argc, argv, "i:f:o:w:v")) != -1)
	switch (c) {
	case 'o':
	    ofile = (char *) (optarg);
	    break;
	case 'w':
	    wfile = (char *) (optarg);
	    break;
	case 'i':
	case 'f':
	    filename = (char *) optarg;
	    break;
	case 'v':
	    set_trace (default_trace, TRACE_FLAGS, TR_ALL,
		       TRACE_LOGFILE, "stdout", NULL);
	    break;
	default:
	    errors++;
	}

    init_mrt (default_trace);

    if (ofile) {
	if (io_set (IO, IO_OUTFILE, ofile, NULL) < 0) {
	    printf ("Error setting outfile: %s (%s)\n", ofile, strerror (errno));
	    errors++;
	}
    }
    if (wfile) {
	if (io_set (IO, IO_OUTMSGQ, wfile, NULL) < 0) {
	    printf ("Error setting output: %s (%s)\n", wfile, strerror (errno));
	    errors++;
	}
    }
    if (errors) {
	fprintf (stderr, usage);
	printf ("\nMRT version (%s) compiled on %s\n\n",
		MRT_VERSION, __DATE__);
	exit (0);
    }

    if (!strcasecmp (filename, "stdin"))
	fd = stdin;
    else
	fd = fopen (filename, "r");

    if (fd == NULL) {
	perror (filename);
	exit (1);
    }
    read_ascii (fd, IO);
    exit (0);
}
Example #10
0
int
main(int argc, char**argv)
{
    int i, k;
    int n;
    Forceinfo force;
    Nbodyinfo nbody;

    init_nbodyinfo(&nbody);

    vtc_init_cputime();
    parse_argv(argc, argv);
    if (snapin_flag == 0 && !initcond_flag) {
	fprintf(stderr, "snapshot input file required (-i)\n");
	show_usage(argv[0]);
    }
    if (initcond_flag) {
	create_initcond(&nbody, initn);
	tstart = 0.0;
    }
    else {
	if (ionemo_flag) {
	    read_binary(snapinfile, &tstart, &nbody);
	}
	else if (usepob_flag) {
	    read_pob(snapinfile, &tstart, &nbody);
	}
	else {
	    read_ascii(snapinfile, &tstart, &nbody);
	}
    }
    n = nbody.n;
    nbody.a = (double (*)[3])malloc(sizeof(double)*3*n);
    nbody.p = (double *)malloc(sizeof(double)*n);
    if (NULL == nbody.a || NULL == nbody.p) {
	perror("main");
	exit(1);
    }
    if (tstart > tend) {
	fprintf(stderr, "start time %f larger than end time %f. abort.\n",
		tstart, tend);
	exit(1);
    }
#if DIRECT /* direct sum */
    vtc_get_default_direct_params(&force); /* get current values */
#else /* tree */
    vtc_get_default_tree_params(&force); /* get current values */
#endif /* direct/tree */

    /* modify some of them */
    force.theta = theta;
    force.eps = eps;
    force.ncrit = ncrit;
    force.node_div_crit = node_div_crit;
    force.p = me_order;
    force.negativemass = negativemass;
    force.pprad = pprad;
    force.full_dof = full_dof_flag;
    if (grape_flag) {
	force.calculator = GRAPE_FORCEONLY;
	force.calculator = GRAPE;
    }
    force.test_id = test_id;

    PR(snapinfile,s); PRL(snapoutfile,s);
    PRL(n,d); 
    PR(eps, f); PR(theta, f); PR(ncrit, d); PRL(node_div_crit, d); 


    {
	double mmin = 1e10;
	double mmax = 0.0;
	for (i = 0; i < nbody.n; i++) {
	    if (mmin > nbody.m[i]) mmin = nbody.m[i];
	    if (mmax < nbody.m[i]) mmax = nbody.m[i];
	}
	fprintf(stderr, "mmin: %e mmax: %e\n", mmin, mmax);
    }


#if COSMO
    time_integration_loop_hubble(&force, &nbody);
#else
    time_integration_loop(&force, &nbody);
#endif
#if USE_GM_API
    fprintf(stderr, "will m2_gm_finalize...\n");
    m2_gm_finalize();
    fprintf(stderr, "done m2_gm_finalize.\n");
#endif /* USE_GM_API */
    exit(0);
}
Example #11
0
int main(int argc, char* argv[])
{
    if(argc < 3)
    {
        printf("scf n_max l_max\n");
        exit(0);
    }

    MPI_Init(&argc, &argv);
    MPI_Comm_rank(MPI_COMM_WORLD, &ThisTask);
    MPI_Comm_size(MPI_COMM_WORLD, &NTask);

    /* global variables */
    decompose_nmax = atoi(argv[1]);
    decompose_lmax = atoi(argv[2]);
    
    /* This n_elements is NOT the number of terms in the triple sum. See documentation. */
    int n_elements = (decompose_nmax+1)*(decompose_lmax+1)*(decompose_lmax+1);
	
    /* Reads the N-body snapshot. Right now this read_snapshot() routine is written for
     * VL-2 snapshots. You will need to write your own routine for any other formats.
     * Returns how many particles this computing node is handling.
     */    
//     read_snapshot(NULL, NULL);
    read_ascii();

    printf("Task %d: NumPart = %lld\n", ThisTask, NumPart);

    MPI_Barrier(MPI_COMM_WORLD);

    double* mat_cos = (double*)malloc(n_elements*sizeof(double));
    double* mat_sin = (double*)malloc(n_elements*sizeof(double));

    /* This does the integral to compute the coefficients, given the positions and masses
     * of the particles. This routine is only summing the particles that the current node
     * responsible for. The results are stored in the place holder arrays mat_cos and mat_sin,
     * which will be combined with the results from all other nodes below.
     */
    scf_integral(mat_cos, mat_sin);

    MPI_Barrier(MPI_COMM_WORLD);

    double* mat_cos_reduced = (double*)malloc(n_elements*sizeof(double));
    double* mat_sin_reduced = (double*)malloc(n_elements*sizeof(double));

    /* Sum up the integrals from other nodes for the cosine terms */
    MPI_Reduce(mat_cos, mat_cos_reduced, n_elements, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
  
    MPI_Barrier(MPI_COMM_WORLD);
   
    /* Sum up the integrals from other nodes for the sine terms */
    MPI_Reduce(mat_sin, mat_sin_reduced, n_elements, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
  
  
    char out_filename[200];
    FILE* fout;
  
    /* Now write the coefficients to file */
    if(ThisTask == 0)
    {
//         printmat(mat_cos_reduced, mat_sin_reduced);

        sprintf(out_filename, "scfmatrix_%d_%d.scf", decompose_nmax, decompose_lmax);

        fout = fopen(out_filename, "w");
        
        if(fout == NULL)
        {
            perror("Can't write to matrix file!\n");
            MPI_Finalize();
            exit(1);
        }

        fwrite(&decompose_nmax, sizeof(decompose_nmax), 1, fout);
        fwrite(&decompose_lmax, sizeof(decompose_lmax), 1, fout);
        fwrite(mat_cos, sizeof(double), n_elements, fout);
        fwrite(mat_sin, sizeof(double), n_elements, fout);
        fwrite(mat_cos_reduced, sizeof(double), n_elements, fout);
        fwrite(mat_sin_reduced, sizeof(double), n_elements, fout);

        fclose(fout);

    }


    MPI_Barrier(MPI_COMM_WORLD);

	free(xx);
	free(yy);
	free(zz);
	free(mm);
	free(mat_cos);
	free(mat_sin);
	free(mat_cos_reduced);
	free(mat_sin_reduced);
	
	MPI_Finalize();
	
	return 0;
}
Example #12
0
qp_source_t qp_source_create(const char *filename, int value_type)
{
  struct qp_source *source;
  struct qp_reader rd;
  int r;

  source = make_source(filename, value_type);

  rd.fd = -1;
  rd.rd = 0;
  rd.len = 0;
  rd.past = 0;
  rd.file = NULL;
  rd.buf = NULL;
  rd.filename = (char *) filename;
  qp_rd = &rd;

  if(strcmp(filename,"-") == 0)
  {
    rd.file = stdin;
    rd.fd = STDIN_FILENO;
  }

  if(rd.fd == -1)
    rd.fd = open(filename, O_RDONLY);

  if(rd.fd == -1)
  {
    EWARN("open(\"%s\",O_RDONLY) failed\n", filename);
    QP_EWARN("%sFailed to open file%s %s%s%s\n",
        bred, trm, btur, filename, trm);
    goto fail;
  }

  if(!is_pipe(&rd))
  {
    /* don't buffer read() and lseek() */
    qp_rd = NULL;
  }
  else
  {
    /* this is a pipe */
    DEBUG("Virturalizing a pipe%s%s\n",
        (filename[0] == '-' && filename[1] == '\0')?
        "":" with name ",
        (filename[0] == '-' && filename[1] == '\0')?
        "":filename);
    rd.buf = qp_malloc(BUF_LEN);
  }

  if((r = read_sndfile(source, &rd)))
  {
    if(r == -1)
      goto fail;


    if(rd.past && qp_rd)
    {
      VASSERT(0, "libsndfile read to much data "
          "to see that the file was not a sndfile\n");
      QP_WARN("%sFailed to read file%s %s%s%s:"
          " read wrapper failed\n",
          bred, trm, btur, filename, trm);
      goto fail;
    }

    if(qp_rd)
    {
      /* Start reading the data from the qp_rd read() buffer */
      rd.rd = 0;
      /* no need to add more to the qp_rd read() buffer */
      rd.fd = -1;
    }
    /* The above lseek() should work fine. */
    else if(lseek(rd.fd, 0, SEEK_SET))
    {
      EWARN("lseek(fd=%d, 0, SEEK_SET) failed\n", rd.fd);
      QP_EWARN("%sFailed to read file%s %s%s%s: lseek() failed\n",
          bred, trm, btur, filename, trm);
    }

    if(!rd.file)
    {
      errno = 0;
      rd.file = fdopen(rd.fd, "r");
      ASSERT(fileno(rd.file) == rd.fd);
    }
    if(!rd.file)
    {
      EWARN("fopen(\"%s\",\"r\") failed\n", filename);
      QP_EWARN("%sFailed to open file%s %s%s%s\n",
          bred, trm, btur, filename, trm);
      goto fail;
    }

    errno = 0;

    if(read_ascii(source, &rd))
      goto fail;
  }

  if(rd.buf)
  {
    free(rd.buf);
    rd.buf = NULL;
  }

  {
    /* remove any channels that have very bad data */
    struct qp_channel **c;
    size_t i = 0, chan_num = 0;
    ASSERT(source->channels);
    c = source->channels;
    while(c[i])
    {
      ASSERT(c[i]->form == QP_CHANNEL_FORM_SERIES);
      if(!is_good_double(c[i]->series.min) ||
          !is_good_double(c[i]->series.max))
      {
        struct qp_channel **n;
        
        qp_channel_destroy(c[i]);

        /* move of all pointers from c[i+1] back one */
        for(n=&c[i]; *n;++n)
          *n = *(n+1);

        /* re-malloc copying and removing one */
        source->channels = 
          qp_realloc(source->channels, sizeof(struct qp_channel *)*
              ((source->num_channels)--));
        
        /* reset c to the next one which is now at the
         * same index */
        c = source->channels;

        QP_NOTICE("removed bad channel number %zu\n", chan_num);
      }
      else
        ++i;
      ++chan_num;
    }
    ASSERT(source->num_channels == i);
  }
  
  
  if(source->num_channels == 0)
    goto fail;


  if(source->num_channels > 1)
  {
    /****** Check that there is at least one point in all the channels */
    ssize_t i, num;
    double *x;
    num = source->num_values;
    x = qp_malloc(sizeof(double)*source->num_channels);
    for(i=0;i<source->num_channels;++i)
      x[i] = qp_channel_series_double_begin(source->channels[i]);

    while(num)
    {
      int found = 0;
      for(i=0;i<source->num_channels;++i)
        if(is_good_double(x[i]))
          ++found;

      if(found >= 2)
        /* that means there is at least one x/y point
         * in all the channels. */
        break;

      --num;
      if(!num)
        break;

      for(i=0;i<source->num_channels;++i)
        x[i] = qp_channel_series_double_next(source->channels[i]);
    }

    if(!num)
    {
      QP_WARN("Failed to find a good point in data from file \"%s\"\n",
          filename);
      goto fail;
    }
  }

  
  if(source->num_channels == 0)
    goto fail;


  if(app->op_linear_channel || source->num_channels == 1)
  {
    /* Prepend a linear channel */

    /* TODO: Make this use less memory */
    
    struct qp_channel *c, **new_channels;
    double start = 0, step = 1;
    size_t len, i;

    if(app->op_linear_channel)
    {
      c = app->op_linear_channel;
      ASSERT(c->data);
      start = ((double*)c->data)[0];
      step = ((double*)c->data)[1];
    }
    else
    {
      c = qp_channel_linear_create(start, step);
    }


    len = source->num_values;
    for(i=0;i<len;++i)
      qp_channel_series_double_append(c, start + i*step);
   
    /* Prepend the channel to source->channels */
    /* reuse dummy len */
    len = source->num_channels + 1;
    new_channels = qp_malloc(sizeof(c)*len+1);
    new_channels[0] = c;
    for(i=1;i<len;++i)
      new_channels[i] = source->channels[i-1];
    new_channels[i] = NULL;
    free(source->channels);
    source->channels = new_channels;
    ++(source->num_channels);

    if(source->labels && source->num_labels !=  source->num_channels)
    {
      // shift the labels and add the linear channel label
      source->labels = qp_realloc(source->labels,
          sizeof(char *)*(source->num_labels+2));
      source->labels[source->num_labels+1] = NULL;
      for(i=source->num_labels;i>=1;--i)
        source->labels[i] = source->labels[i-1];

      char s[128];
      snprintf(s,128, "%s[0]", source->name);
      // The first channel is the linear channel.
      source->labels[0] = qp_strdup(s);
      ++source->num_labels;
    }

    /* Another source may have more values so
     * we must make a new one in case it is used again. */
    if(app->op_linear_channel)
      app->op_linear_channel = qp_channel_linear_create(start, step);
  }
  
  add_source_buffer_remove_menus(source);
  
  {
    char skip[64];
    skip[0] = '\0';
    if(app->op_skip_lines)
      snprintf(skip, 64, "(after skipping %zu) ", app->op_skip_lines);


    INFO("created source with %zu sets of values %s"
      "in %zu channels from file %s\n",
      source->num_values, skip, source->num_channels,
      filename);

    QP_INFO("created source with %zu sets of "
      "values %sin %zu channels from file \"%s\"\n",
      source->num_values, skip, source->num_channels,
      filename);
#if QP_DEBUG
    if(source->labels)
    {
      char **labels;
      APPEND("Read labels:");
      for(labels = source->labels; *labels; ++labels)
        APPEND(" \"%s\"", *labels);
      APPEND("\n");
    }
#endif
  }

  qp_rd = NULL;

  if(strcmp(filename,"-") == 0)
    /* We do not close stdin */
    return source;

  if(rd.file)
    fclose(rd.file);
  else if(rd.fd != -1)
    close(rd.fd);

  qp_app_graph_detail_source_remake();
  qp_app_set_window_titles();

  return source;

fail:

  QP_WARN("No data loaded from file \"%s\"\n",
      filename);

  if(rd.buf)
    free(rd.buf);

  if(strcmp(filename,"-") != 0)
  {
    if(rd.file)
      fclose(rd.file);
    else if(rd.fd != -1)
      close(rd.fd);
  }

  if(source)
    qp_source_destroy(source);

  qp_rd = NULL;

  return NULL;
}
Example #13
0
int main(int argc, char *argv[])
{  
  int i, j, k, l, index, indexaux, Np, idPart;
  int ii, jj, kk;
  double xc, yc, zc; // Positions of the cells
  double xp, yp, zp, vxp, vyp, vzp; // Positions and velocities of the particles
  double Window_fn; //Window function
  double norm_factor; //Normalization factor for the momentum computation
  char *inFile=NULL;
  FILE *outfile=NULL, *outfile1=NULL, *outfile2=NULL;
  /*----- For verifications -----*/
  double totalMass=0.0;
  double totMassCIC=0.0;
  int sumaPart = 0;

  
  if(argc < 2)
    {
      printf("Error: Incomplete number of parameters. Execute as follows:\n");
      printf("%s Parameters_file\n", argv[0]);
      exit(0);
    }//if 

  inFile = argv[1];


  /*************************************************
             READING DATA FILE
  *************************************************/

  /*+++++  Reading parameters +++++*/
  printf("Reading parameters file\n");
  printf("--------------------------------------------------\n\n");
  read_parameters( inFile );

  printf("Parameters file read!\n");
  printf("--------------------------------------------------\n\n");

  printf("Reading data file\n");
  printf("--------------------------------------------------\n\n");

  
#ifdef BINARYDATA  
  /*+++++ Reading binary data file +++++*/
  read_binary();

  GV.NGRID3 = GV.NGRID * GV.NGRID * GV.NGRID;
  GV.dx = GV.L / (1.0*GV.NGRID);
  GV.volCell = GV.dx*GV.dx*GV.dx;
#endif

  
#ifdef ASCIIDATA 
  /*+++++ Allocating memory +++++*/
  part = (struct particle *) calloc((size_t) GV.NpTot,sizeof(struct particle));
  
  /*+++++ Reading data file +++++*/
  read_ascii( GV.FILENAME );

  /*+++++ Simulation parameters +++++*/  
  GV.NGRID3 = GV.NGRID * GV.NGRID * GV.NGRID;
  GV.dx = GV.L / ((double) GV.NGRID);
  GV.volCell = GV.dx*GV.dx*GV.dx;
#endif

  printf("Data file read!\n");
  printf("--------------------------------------------------\n\n");


  /*+++++ Computing mean density +++++*/
  printf("Computing mean density\n");
  printf("--------------------------------------------------\n\n");
  for(i=0; i<GV.NpTot; i++)
    {
      totalMass += part[i].mass;
    }//for i
  GV.rhoMean = totalMass / pow(GV.L, 3.0); // Mean density in 1e10M_sun/Mpc^3


  printf("-----------------------------------------------\n");
  printf("Cosmological parameters:\n");
  printf("OmegaM0=%lf OmegaL0=%lf redshift=%lf HubbleParam=%lf\n",
	 GV.OmegaM0,
	 GV.OmegaL0,
	 GV.zRS,
	 GV.HubbleParam);
  printf("-----------------------------------------------\n");
  printf("Simulation parameters:\n");
  printf("NGRID=%d NGRID3=%d Particle_Mass=%lf NpTotal=%ld \nrhoMean=%lf L=%lf volCell=%lf dx=%lf \nFilename=%s\n",
	 GV.NGRID,
	 GV.NGRID3,
	 GV.mass,
	 GV.NpTot,
	 GV.rhoMean,
	 GV.L,
	 GV.volCell,
	 GV.dx,
	 GV.FILENAME);
  printf("-----------------------------------------------\n");


  /*************************************************
                FROM PARTICLES TO GRID
  *************************************************/
  
  /*+++++ Array of structure Cell, size NGRID^3 +++++*/
  printf("Allocating memory\n");
  printf("-----------------------------------------------\n");
  cells = (struct Cell *) calloc( GV.NGRID3, sizeof( struct Cell) );
  printf("Memory allocated\n");
  printf("-----------------------------------------------\n");

  /*----- Setting values to zero at the beggining -----*/
  for(i=0; i<GV.NGRID3; i++){
    cells[i].Np_cell = 0;
    cells[i].denCon = 0.0;
    cells[i].rho = 0.0;
  }//for i
  
  printf("Locating cells\n");
  printf("-----------------------------------------------\n");

  /*++++ Locating cells +++++*/
  for(i=0; i<GV.NpTot; i++)    
    {
      locateCell(part[i].pos[X], part[i].pos[Y], part[i].pos[Z], i, cells);
    }//for i
  
  printf("Particles located in the grid\n");
  printf("-----------------------------------------------\n");


  printf("Performing the mass assignment\n");
  printf("-----------------------------------------------\n");
  
  
  /*+++++ Distribution scheme +++++*/
  for(i=0; i<GV.NGRID; i++)
    {
      for(j=0; j<GV.NGRID; j++)
	{
	  for(k=0; k<GV.NGRID; k++)
	    {
	      
	      /*----- Index of the cell  -----*/
	      index = INDEX(i,j,k); // C-order
	      
	      /*----- Coordinates in the center of the cell -----*/
	      xc = GV.dx*(0.5 + i);
	      yc = GV.dx*(0.5 + j);
	      zc = GV.dx*(0.5 + k);
	
	      /*----- Number of particles in the cell -----*/
	      Np = cells[index].Np_cell;
	      
	      for(l=0; l<Np; l++)
		{
		  /*::::: Particle ID :::::*/
		  idPart = cells[index].id_part[l];
		  
		  /*::::: Coordinates of the particle  :::::*/
		  xp = part[idPart].pos[X];
		  yp = part[idPart].pos[Y];
		  zp = part[idPart].pos[Z];
		  
	  
		  /*::::: Mass and momentum assignment to neighbour cells (CIC) :::::*/
		  for(ii=-1; ii<=1; ii++)
		    {
		      for(jj=-1; jj<=1; jj++)
			{
			  for(kk=-1; kk<=1; kk++)
			    {
		
			      indexaux = INDEX(mod(i+ii,GV.NGRID),mod(j+jj,GV.NGRID),mod(k+kk,GV.NGRID));
			      xc = GV.dx*(0.5 + i+ii);
			      yc = GV.dx*(0.5 + j+jj);
			      zc = GV.dx*(0.5 + k+kk);
			      
			      /*----- Mass with CIC assignment scheme ------*/
			      Window_fn = W(xc-xp, yc-yp, zc-zp, GV.dx);
			      cells[indexaux].rho += part[idPart].mass * Window_fn;
			    }//for kk
			}//for jj
		    }//for ii
	   	  
		}//for l	      	      
	      
	    }//for k
	}//for j
    }//for i
  
  free(part);
  
  /*+++++ Saving output file in ASCII format +++++*/
#ifdef ASCIIDATA
  outfile = fopen(strcat(GV.FILENAME,"_DenCon_CIC.dat"),"w");
  fprintf(outfile, "%s%9s %12s %12s %12s %12s %12s\n", 
	  "#", "Index", "NumberOfPars",
	  "x", "y", "z", "DenCon");
  
  for(i=0; i<GV.NGRID; i++)
    {
      for(j=0; j<GV.NGRID; j++)
	{
	  for(k=0; k<GV.NGRID; k++)
	    {
	
	      index = INDEX(i,j,k); // C-order
	      
	      /*----- coordinates of the centre of the cell -----*/
	      xc = GV.dx * (0.5 + i);
	      yc = GV.dx * (0.5 + j);
	      zc = GV.dx * (0.5 + k);
	
	      /*----- Calculating the final density in the cell -----*/
	      totMassCIC += cells[index].rho; /* We have not divided by the volume yet. 
						This is still the mass */
	      cells[index].rho = cells[index].rho / GV.volCell; //This is the actual density
	      
	      /*----- Verification of number of particles -----*/
	      sumaPart += cells[index].Np_cell;
	      
	      
	      /*----- Calculating the final density contrast in the cell -----*/
	      cells[index].denCon = (cells[index].rho/GV.rhoMean) - 1.0;
		
	      fprintf(outfile,
		      "%10d %10d %12.6lf %12.6lf %12.6lf %12.6lf\n", 
		      index, cells[index].Np_cell,
		      xc, yc, zc, cells[index].denCon);


	    }//for k
	}// for j
    }// for i

  fclose(outfile);
#endif


  /*+++++ Writing binary file +++++*/
#ifdef BINARYDATA
  for(i=0; i<GV.NGRID; i++)
    {
      for(j=0; j<GV.NGRID; j++)
	{
	  for(k=0; k<GV.NGRID; k++)
	    {
	      
	      index = INDEX(i,j,k); // C-order
	      
	      /*----- coordinates of the centre of the cell -----*/
	      cells[index].pos[X] = GV.dx * (0.5 + i);
	      cells[index].pos[Y] = GV.dx * (0.5 + j);
	      cells[index].pos[Z] = GV.dx * (0.5 + k);
	      
	      /*----- Calculating the final density in the cell -----*/
	      totMassCIC += cells[index].rho; /* We have not divided by the volume yet. 
						 This is still the mass */

	      cells[index].rho = cells[index].rho / GV.volCell; //This is the actual density
	      

	      /*----- Verification of number of particles -----*/
	      sumaPart += cells[index].Np_cell;
	      
	      
	      /*----- Calculating the final density contrast in the cell -----*/
	      cells[index].denCon = (cells[index].rho/GV.rhoMean) - 1.0;	      	      
	    }//for k
	}// for j
    }// for i

  write_binary();
#endif
  
    
  printf("Total number of particles:%10d\n", sumaPart);
  printf("Mass CIC = %lf\n",totMassCIC);
  printf("Mass Simulation = %lf\n", totalMass);
  
  /*+++++ Freeing up memory allocation +++++*/ 
  free(cells);
  
  printf("Code has finished successfully\n");

  return 0;
}//main