snapshotgadget.cc 78.7 KB
Newer Older
jcl's avatar
jcl committed
1
// ============================================================================
jclamber's avatar
jclamber committed
2
// Copyright Jean-Charles LAMBERT - 2008-2015
jclamber's avatar
jclamber committed
3 4 5
//           Centre de donneeS Astrophysiques de Marseille (CeSAM)              
// e-mail:   Jean-Charles.Lambert@lam.fr                                      
// address:  Aix Marseille Universite, CNRS, LAM 
jcl's avatar
jcl committed
6 7 8 9
//           Laboratoire d'Astrophysique de Marseille                          
//           Pole de l'Etoile, site de Chateau-Gombert                         
//           38, rue Frederic Joliot-Curie                                     
//           13388 Marseille cedex 13 France                                   
jclamber's avatar
jclamber committed
10
//           CNRS UMR 7326                                       
jcl's avatar
jcl committed
11 12 13
// ============================================================================

/* 
jclamber's avatar
jclamber committed
14
	@author Jean-Charles Lambert <Jean-Charles.Lambert@lam.fr>
jcl's avatar
jcl committed
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
 */


#include <sstream>
#include <cstdlib>
#include "snapshotgadget.h"
#include "uns.h"
#include "ctools.h"
#define DEBUG 0
#include "unsdebug.h"

extern "C" {
  int io_nemo(const char * , const char *, ...);
#include <stdinc.h>
#include <filestruct.h>
#include <nemo.h>
#include <snapshot/snapshot.h>
};
namespace uns {

  
// ----------------------------------------------------------------------------
// READING constructor                                                                 
 CSnapshotGadgetIn::CSnapshotGadgetIn(const std::string _name,
                                  const std::string _comp, 
                                  const std::string _time,
				  const bool verb)
   :CSnapshotInterfaceIn(_name, _comp, _time, verb)
{
  filename = _name;
  //valid=false;
  first_loc = true;
  status=false;
  is_open=false;
  is_read=false;
  swap   = false;
  mass   = NULL;
  pos    = NULL;
  vel    = NULL;
  acc    = NULL;
  pot    = NULL;
  id     = NULL;
  age    = NULL;
  metal  = NULL;
  intenerg=NULL;
  temp   = NULL;
  rho    = NULL;
  hsml   = NULL;
  zs     = NULL;
  zsmt   = NULL;
  im     = NULL;
jclamber's avatar
jclamber committed
66
  ssl    = NULL;
67
  cm     = NULL;
jcl's avatar
jcl committed
68 69 70 71 72 73 74 75 76 77
  bits   = 0;
  load_bits = 0;
  tframe = 0.;
  redshift=0.;
  frecord_offset = 4;
  czs = 0;
  czsmt= 0;
  bytes_counter = 0;
  multiplefiles = 0;
  lonely_file   = true;
78
  ntotmasses = 0;
jcl's avatar
jcl committed
79 80 81 82 83 84 85 86 87 88 89
  verbose = verb;
  
  int fail = open(filename);
  if (!fail) {
    valid=true;
    std::ostringstream stm;
    stm << getVersion();
    interface_type = "Gadget" + stm.str();
    interface_index=1;
    file_structure = "component";
  }
90

jcl's avatar
jcl committed
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
}
// ----------------------------------------------------------------------------
// destructor                                                                 
CSnapshotGadgetIn::~CSnapshotGadgetIn()
{
  if (valid) {
    if (mass)     delete [] mass;
    if (pos)      delete [] pos;
    if (vel)      delete [] vel;
    if (acc)      delete [] acc;
    if (pot)      delete [] pot;
    if (id)       delete [] id;
    if (age)      delete [] age;
    if (metal)    delete [] metal;
    if (intenerg) delete [] intenerg;
    if (temp)     delete [] temp;
    if (rho)      delete [] rho;  
    if (hsml)     delete [] hsml;  
    if (zs)       delete [] zs;
    if (zsmt)     delete [] zsmt;
    if (im)       delete [] im;
jclamber's avatar
jclamber committed
112
    if (ssl)      delete [] ssl;
113
    if (cm)       delete [] cm;
114 115 116 117 118 119 120
    std::map<std::string,std::vector <float>  >::const_iterator it;
    for (it =  data_vector.begin(); it != data_vector.end(); it++) {
          std::cerr << "~CSnapshotGadgetIn(): Delete key = " <<  it->first
                    << "  size=" << it->second.size() << "\n";
          data_vector[it->first].clear();

      }
jcl's avatar
jcl committed
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
  }
  crv.clear();
}
// ============================================================================
// getSnapshotRange                                                            
ComponentRangeVector * CSnapshotGadgetIn::getSnapshotRange()
{
  //crv.clear();
  if (valid && crv.size()) {
    //crv = getCRV();
    //ComponentRange::list(&crv);
    if (first) {
      first       = false;
      crv_first   = crv;
      nbody_first = getNtotal();
      //std::cerr << "CSnapshotGadgetIn::getSnapshotRange() = " << nbody_first << "\n";
      time_first  = getTime();
    }
  }
  return &crv;
}
//// ============================================================================
//// nextFrame 
//int CSnapshotGadgetIn::nextFrame()
//{
//  user_select.setSelection(getSelectPart(),getSnapshotRange());
//  return nextFrame(user_select.getIndexesTab(),user_select.getNSel());
//}

// ============================================================================
// nextFrame 
int CSnapshotGadgetIn::nextFrame(uns::UserSelection &user_select)
{
  int status=0;
  assert(valid==true);
  if (first_loc) {
    first_loc = false;
    if (checkRangeTime(getTime())) {
      read(user_select); // read Gadget
      status = 1;
    }
  }
  return status;
}

// ============================================================================
// open() :                                                                    
// open file and return :                                                      
// 0 : success                                                                 
// 1 : unable to open                                                          
// 2 : not a GADGET file                                                       
int CSnapshotGadgetIn::open(const std::string myfile)
{
  int fail=0;
  in.clear();
  in.open(myfile.c_str(),std::ios::in | std::ios::binary);
  if ( ! in.is_open()) {
   in.close();
   in.clear(); // mandatory under win32 !
   // try to open a multiple gadget file
   file0 = myfile+".0";
   PRINT("GadgetIn::open In gadget open file0 : " << file0 << "\n";)
   in.open(file0.c_str(),std::ios::in | std::ios::binary);
   if (in.is_open()) {
//     assert(in.good());
     lonely_file=false;
     PRINT("It's a multiple gadget file.\n";)
   }
  }
  if ( ! in.is_open()) {
    fail = 1;               // unable to open
    PRINT("In gadget, failed to open...\n";)
  }
  else {
    is_open=true;
    if (guessVersion()) {
      fail = readHeader(0);    // try to read header
      if (!fail) status=true; // valid header
      else close();           // not valid header
    }
    else {
      fail=1;
      close();             // not a valid gadgetfile
    }
  }
  return fail;
}
// ============================================================================
int CSnapshotGadgetIn::close()
{
  if (is_open) in.close();
  is_open = false;
  return 1;
}
// ============================================================================
template <class T> int CSnapshotGadgetIn::readCompData(T ** data, const int * index2,
                                                       const int * npartOffset,const int dim, const int nsel)
{
  bytes_counter=0;
  int len1 = readFRecord();
  checkFileVsArray(len1,sizeof(T),npart_total_local*dim);
  // allocate memory for the array
  if (*data==NULL) { // the first time
    *data = new T[dim*nsel];
  }
  T * ptr = *data;
227 228 229 230 231 232
  float fskip; // file skip factor
  if (array_vs_file_size<=1) {
    fskip=float(array_vs_file_size+1);
  } else {
    fskip=0.5;
  }
jcl's avatar
jcl committed
233 234 235 236 237 238
  for(int k=0;k<6;k++) {   
    if (header.npart[k]>0) { // there are particles for the component
      int idx=index2[npartOffset[k]];                
      if (idx != -1) {
        readData((char *) &ptr[dim*idx], sizeof(T), dim*header.npart[k]);
      } else {
239
        skipData(fskip*sizeof(T)*dim*header.npart[k]);
jcl's avatar
jcl committed
240 241 242 243
      }
    }
  }  
  int len2 = readFRecord();
244 245
  if (len2==len1) ; // remove warning....
  assert(len2==len1 && in.good() && len1==bytes_counter);
jcl's avatar
jcl committed
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269
  return 1;
}
// ============================================================================
template <class T> int CSnapshotGadgetIn::readGasStarsUnknownArray(T ** data, int * nguess,const int * compOffset)
{
  bytes_counter=0;
  int len1 = readFRecord();
  *nguess = len1/sizeof(float)/(header.npart[0]+header.npart[4]); // geuss #records
  //std::cerr << "NGuess constant = " << *nguess << "\n";
  checkFileVsArray(len1,sizeof(T),(*nguess)*(header.npart[0]+header.npart[4]));
  // allocate memory for the array
  if (*data==NULL) { // the first time
    *data = new T[(*nguess)*(header.npartTotal[0]+header.npartTotal[4])];
  }
  T * ptr = *data;
  // read gas DATA
  int idx=compOffset[0]*(*nguess); // set index to the correct offset
  assert((idx+(*nguess)*header.npart[0])<=(*nguess)*(header.npartTotal[0]+header.npartTotal[4]));
  readData((char *) &ptr[idx], sizeof(float),(*nguess)*header.npart[0]);
  // read stars DATA
  idx=header.npartTotal[0]*(*nguess)+compOffset[4]*(*nguess);
  assert((idx+(*nguess)*header.npart[4])<=(*nguess)*(header.npartTotal[0]+header.npartTotal[4]));
  readData((char *) &ptr[idx], sizeof(float),(*nguess)*header.npart[4]);
  int len2 = readFRecord();
270 271
  if (len2==len1) ; // remove warning....
  assert(in.good() && len2==len1 && len1==bytes_counter);
jcl's avatar
jcl committed
272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
  return 1;
}
// ============================================================================
template <class T> int CSnapshotGadgetIn::readOneArray(T ** data, const int compid,const int * compOffset)
{
  bytes_counter=0;
  int len1 = readFRecord();
  checkFileVsArray(len1,sizeof(T),header.npart[compid]);
  // allocate memory for the array
  if (*data==NULL) { // the first time
    *data = new T[header.npartTotal[compid]];
  }
  T * ptr = *data;
  int idx=compOffset[0]; // set index to the correct offset
  assert((idx+header.npart[compid])<=header.npartTotal[compid]);
  readData((char *) &ptr[idx], sizeof(float),header.npart[compid] );
  int len2 = readFRecord();
289
  if (len2==len1) ; // remove warning....
jcl's avatar
jcl committed
290 291 292
  assert(in.good() && len1==len2 && len1==bytes_counter);
  return 1;
}
jclamber's avatar
jclamber committed
293
// ============================================================================
294
template <class T> int CSnapshotGadgetIn::readStreamBlock(const std::string req_blockname, std::vector<T> & data)
jclamber's avatar
jclamber committed
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
{
  if (is_read) { // file has already been read
    close();
  }
  int fail = open(filename);
  if (fail) assert(0);     // fail is true abort

  assert(sizeof(T)==sizeof(float)); // works only for float NOW

  int last_len=0;
  // loop on all the files
  for (int i=0; i<header.num_files || (i==0 && header.num_files==0);i++) {
    std::string infile;
    if (header.num_files > 0 ) { // more than one file
      std::ostringstream stm;
      stm << "." << i;               // add ".XX" extension
      infile = filename + stm.str(); // new filename
      if (i>0) {
        close();                 // close previous file
        int fail=open(infile);   // open new file,read header
        if (fail) assert(0);     // fail is true abort
      }
    }
    else infile=filename;        // lonely file

    bool stop=false;
    bool ok=false;

    while(readBlockName() && !stop) {
      if (req_blockname == block_name) { // found requested block name
        bytes_counter=0;
        int len1 = readFRecord();

328 329
        if (data.size()==0) { //  first time
          data.resize(len1/sizeof(T)); // !! TO CHECK
jclamber's avatar
jclamber committed
330 331 332
        }
        else {
          if (i>0) { // more than one file
333
            data.resize((last_len+len1)/sizeof(T));
jclamber's avatar
jclamber committed
334 335 336 337 338
          } else {
            std::cerr << "WARNING, pointer not allocated...\n";
          }
        }

339
        T * ptr = &data[0];
jclamber's avatar
jclamber committed
340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
        readData((char *) &ptr[last_len], sizeof(T), len1/sizeof(T) );
        int len2 = readFRecord();
        if (len2==len1) ; // remove warning....
        assert(in.good() && len1==len2 && len1==bytes_counter);
        last_len += len1;
        stop=true; // we must stop
        ok=true;
      } else {
        if (!ok) {
          if (in.eof()) { // it's end of file, must stop loop
            stop=true;
          }
          else {
            skipBlock();
          }
        }

      }
    }
  }

361 362 363
//  if (last_len>0) { // found something
//    *nbody=last_len/sizeof(T);
//  }
jclamber's avatar
jclamber committed
364 365
  return 1;
}
jcl's avatar
jcl committed
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

// ============================================================================
int CSnapshotGadgetIn::read(uns::UserSelection &user_select)
{
  const uns::t_indexes_tab * index=user_select.getIndexesTab();
  const int nsel=user_select.getNSel();
  
  int npartOffset[6], // store absolute component offset (between components)
      compOffset[6];  // store relative component offset
  if (! is_read ) {
    //checkCompBits(index,nsel);
    
    // check component bits`
    comp_bits=user_select.compBits();

    //ComponentRange::list(&crv);
    //ComponentRange::list(user_select.getCrvFromSelection());
    
    is_read=true;
    assert(nsel<=npartTotal);
    // compute offset in case of multiple gadget file
    npartOffset[0] = 0;
    compOffset[0]  = 0;
    for (int i=1;i<=5;i++) {
      npartOffset[i] = npartOffset[i-1]+header.npartTotal[i-1];
      compOffset[i] = 0;
      if (verbose) std::cerr
          << "npartOffset["<<i<<"]="<<npartOffset[i]<<" npartOffset["<<i-1<<"]="
          <<npartOffset[i-1]<<" header.npartTotal["<<i-1<<"]="<<header.npartTotal[i-1]<<"\n";
    }
    //for (int i=0;i<6;i++)   std::cerr << "npartOffset["<<i<<"]="<<npartOffset[i] <<"\n";
    
    // allocate array to store indexes
    int * index2  = new int[npartTotal];
    for (int i=0; i<npartTotal; i++)
      index2[i] = -1; // index2 init

    for (int i=0, cpt=0; i<npartTotal; i++) {
      int idx=index[i].i;
      assert(idx<npartTotal);
      //std::cerr << i<< " " << index[i].i << " "<< index[i].idx << " " << nsel << " " <<npartTotal << "\n";
      if (idx != -1 ) {
        index2[idx] = cpt++;
      }
    }

    int z_offset  =0; // metalicity offset
    int age_offset=0; // age offset
    int im_offset=0; // age offset
    // loop on all the files
    for (int i=0; i<header.num_files || (i==0 && header.num_files==0);i++) {
      std::string infile;
      if (header.num_files > 0 ) { // more than one file
        std::ostringstream stm;
        stm << "." << i;               // add ".XX" extension
        infile = filename + stm.str(); // new filename
        if (i>0) {
          close();                 // close previous file
          int fail=open(infile);   // open new file,read header
425
          if (fail) assert(0);     // fail is true abort
jcl's avatar
jcl committed
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
        }
      }
      else infile=filename;        // lonely file
      int len1=0,len2=0;
      bool stop=false;
      std::string next_block_name;
      if (version==1) next_block_name="POS";

      // Read the whole file till a valid block exist
      // or stop = true in case of Gadget1 file
      while (req_bits!=0 && readBlockName() && !stop) {
        if (version==1) block_name=next_block_name;
        bool ok=false;
        // --> Postions block
        if (block_name=="POS" && req_bits&POS_BIT) {
          load_bits |= POS_BIT;
          ok=true;
          readCompData(&pos,index2,npartOffset,3, nsel);
          if (version==1) next_block_name="VEL";
        }
        // --> Velocities block
        if (block_name=="VEL" && req_bits&VEL_BIT) {
          load_bits |= VEL_BIT;
          ok=true;
          readCompData(&vel,index2,npartOffset,3,nsel);
          if (version==1) next_block_name="ID";
        }
        // --> IDs block
        if (block_name=="ID" && req_bits&ID_BIT) {
          load_bits |= ID_BIT;
          ok=true;
          readCompData(&id,index2,npartOffset,1,nsel);
          if (version==1) next_block_name="MASS";
        }
        // --> MASS block
        if (block_name=="MASS" && req_bits&MASS_BIT ) {
          load_bits |= MASS_BIT;
          ok=true;
          bytes_counter=0;
465
          if (ntotmasses>0) {    // different masses
jcl's avatar
jcl committed
466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488
            len1 = readFRecord(); // we must read from disk
            checkFileVsArray(len1,sizeof(float),ntotmasses);
          }
          // allocate memory if NULL pointer
          if (! mass )  mass = new float[nsel  ];
          for(int k=0;k<6;k++) {
            for(int n=0;n<header.npart[k];n++){
              int idx=index2[npartOffset[k]+n];
              assert(idx<nsel);
              if (idx != -1 && (header.mass[k] == 0)) {          // variable mass selected
                readData((char *) &mass[idx], sizeof(float), 1); // read from disk
              } else {
                if (idx == -1 && (header.mass[k] == 0)) {        // variable mass **not** selected
                  float tmp;
                  readData((char *) &tmp, sizeof(float), 1);     // read from disk (skip it)
                } else {
                  if (idx != -1 && (header.mass[k] != 0)) {      // constant mass selected
                    mass[idx] = header.mass[k];                  // read from header
                  }
                }
              }
            } // for n
          } // for k
489
          if (ntotmasses > 0) {  // different masses
jcl's avatar
jcl committed
490
            len2 = readFRecord(); // we must read from disk
491 492
            if (len2==len1) ; // remove warning....
            assert(in.good() && len2==len1 && len1==bytes_counter);
jcl's avatar
jcl committed
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 580 581 582 583 584 585 586 587 588
          }
          if (version==1) stop=true; // we stop reading for gadget1
        }
        // --> POT block
        if (block_name=="POT" && req_bits&POT_BIT) {
          load_bits |= POT_BIT;
          ok=true;
          readCompData(&pot,index2,npartOffset,1,nsel);
        }
        // --> Acceleration block
        if (block_name=="ACCE" && req_bits&ACC_BIT) {
          load_bits |= ACC_BIT;
          ok=true;
          readCompData(&acc,index2,npartOffset,3,nsel);
        }
        // --> U block (Internal energy)
        if (block_name=="U" && req_bits&U_BIT && comp_bits&GAS_BIT) {
          load_bits |= U_BIT;
          assert(header.npart[0]>0); // (gas only)
          ok=true;
          readOneArray(&intenerg,0,compOffset);
        }
        // --> Temperature block
        if (block_name=="NE" && req_bits&TEMP_BIT && comp_bits&GAS_BIT) {
          load_bits |= TEMP_BIT;
          assert(header.npart[0]>0); // (gas only)
          ok=true;
          readOneArray(&temp,0,compOffset);
        }
        // --> RHO block (density)
        if (block_name=="RHO" && req_bits&RHO_BIT && comp_bits&GAS_BIT) {
          load_bits |= RHO_BIT;
          assert(header.npart[0]>0); // (gas only)
          ok=true;
          readOneArray(&rho,0,compOffset);
        }
        // --> HSML block (neighbours size)
        if (block_name=="HSML" && req_bits&HSML_BIT && comp_bits&GAS_BIT) {
          load_bits |= HSML_BIT;
          assert(header.npart[0]>0); // (gas only)
          ok=true;
          readOneArray(&hsml,0,compOffset);
        }
        // --> Z block (Metalicity)
        if (block_name=="Z" && req_bits&METAL_BIT && (comp_bits&GAS_BIT || comp_bits&STARS_BIT)) {
          load_bits |= METAL_BIT;
          assert((header.npart[0]+header.npart[4])>0); // gas+stars
          ok=true;
          bytes_counter=0;
          len1 = readFRecord();
          checkFileVsArray(len1,sizeof(float),header.npart[0]+header.npart[4]);
          // allocate memory for array only if NULL pointer
          if (!metal) {
            metal = new float[header.npartTotal[0]+header.npartTotal[4]];
          }
          // read gas metal
          int idx=compOffset[0];
          assert((idx+header.npart[0])<=(header.npartTotal[0]+header.npartTotal[4]));
          readData((char *) &metal[idx], sizeof(float),header.npart[0]);
          // read stars metal
          idx=header.npartTotal[0]+compOffset[4];
          assert((idx+header.npart[4])<=(header.npartTotal[0]+header.npartTotal[4]));
          readData((char *) &metal[idx], sizeof(float),header.npart[4]);
          len2 = readFRecord();
          assert(in.good() && len1==len2 && len1==bytes_counter);
        }
        // --> AGE block
        if (block_name=="AGE" && req_bits&AGE_BIT && comp_bits&STARS_BIT) {
          load_bits |= AGE_BIT;
          ok=true;
          bytes_counter=0;
          len1 = readFRecord();
          checkFileVsArray(len1,sizeof(float),header.npart[4]);
          // allocate memory for array only if NULL pointer
          if (!age) {
            age = new float[header.npartTotal[4]];
          }
          if (len1/4 != header.npart[4]) {
            std::cerr << "\nWARNING: Wang's AGE bug detected.......skipping age\n";
            in.seekg(len1,std::ios::cur);
          } else {
            assert(header.npart[4]>0); // stars only
            int idx=age_offset;
            assert((idx+header.npart[4])<=(header.npartTotal[4]));
            readData((char *) &age[idx], sizeof(float),header.npart[4]);
          }
          len2 = readFRecord();
          assert(in.good() && len1==len2);// && len1==bytes_counter);
        }
        // --> IM block
        if (block_name=="iM" && req_bits&IM_BIT && comp_bits&STARS_BIT) {
          load_bits |= IM_BIT;
          assert((header.npart[4])>0); // stars
          ok=true;
          readOneArray(&im,4,compOffset);
        }
jclamber's avatar
jclamber committed
589 590 591 592 593 594 595
        // --> SSL block
        if (block_name=="SSL" && req_bits&SSL_BIT && comp_bits&STARS_BIT) {
          load_bits |= SSL_BIT;
          assert((header.npart[4])>0); // stars
          ok=true;
          readOneArray(&ssl,4,compOffset);
        }
596 597 598 599 600 601 602 603 604 605
        // --> CM block
        if (block_name=="cM" && req_bits&CM_BIT && (comp_bits&GAS_BIT || comp_bits&STARS_BIT)) {
          assert((load_bits&CM_BIT)==0); // if failed means that multiple file not supported for this block
          load_bits |= CM_BIT;
          assert((header.npart[0]+header.npart[4])>0); // gas+stars
          ok=true;
          int ccm;
          readGasStarsUnknownArray(&cm,&ccm,compOffset);
          assert(ccm==1); // there is only one value per particle
        }
jcl's avatar
jcl committed
606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637
        // --> Zs block
        if (block_name=="Zs" && req_bits&ZS_BIT && (comp_bits&GAS_BIT || comp_bits&STARS_BIT)) {
          assert((load_bits&ZS_BIT)==0); // if failed means that multiple file not supported for this block
          load_bits |= ZS_BIT;
          assert((header.npart[0]+header.npart[4])>0); // gas+stars
          ok=true;
          readGasStarsUnknownArray(&zs,&czs,compOffset);
        }
        // --> ZSMT block
        if (block_name=="ZSMT" && req_bits&ZSMT_BIT && (comp_bits&GAS_BIT || comp_bits&STARS_BIT)) {
          assert((load_bits&ZSMT_BIT)==0); // if failed means that multiple file not supported for this block
          load_bits |= ZSMT_BIT;
          assert((header.npart[0]+header.npart[4])>0); // gas+stars
          ok=true;
          readGasStarsUnknownArray(&zsmt,&czsmt,compOffset);
        }
        if (!ok) {
          if (in.eof()) {
            stop=true;
          }
          else {
            skipBlock();
            if (version==1) { // we set the nextblockname
              if (block_name=="POS") next_block_name="VEL";
              if (block_name=="VEL") next_block_name="ID";
              if (block_name=="ID" ) next_block_name="MASS";
            }
          }
        }
      } // end of while readBlock
      
      // add masses if no BLOCK_MASS present (mass inside the header)
638
      if (ntotmasses == 0 && req_bits&MASS_BIT) { // no BLOCK_MASS present (mass inside the header)
jcl's avatar
jcl committed
639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684
        load_bits |= MASS_BIT;
        // allocate memory if NULL pointer
        if (! mass )  mass = new float[nsel  ];
        for(int k=0;k<6;k++) {
          for(int n=0;n<header.npart[k];n++){
            int idx=index2[npartOffset[k]+n];
            assert(idx<nsel);
            if (idx != -1 && (header.mass[k] != 0)) {      // constant mass selected
              mass[idx] = header.mass[k];                  // read from header
            }
          } // for n
        } // for k
      } // if

      // correct the offset of the particles which have been read
      for (int i=0;i<6;i++) {
        npartOffset[i] = npartOffset[i]+header.npart[i];
        compOffset[i] = compOffset[i]+header.npart[i];
      }
      // correction for metalicity and age
      z_offset   += (header.npart[0]+header.npart[4]);
      age_offset += header.npart[4];
      im_offset  += header.npart[4];
    } // end of loop on numfiles

    // garbage collecting
    delete [] index2;

    // convert to temperature units
    if (header.npartTotal[0] > 0) {
      //unitConversion();
    }
    // check bits
    freeNotLoadedData(&mass     ,MASS_BIT);
    freeNotLoadedData(&pos      ,POS_BIT);
    freeNotLoadedData(&vel      ,VEL_BIT);
    freeNotLoadedData(&acc      ,ACC_BIT);
    freeNotLoadedData(&pot      ,POT_BIT);
    freeNotLoadedData(&age      ,AGE_BIT);
    freeNotLoadedData(&metal    ,METAL_BIT);
    freeNotLoadedData(&temp     ,TEMP_BIT);
    freeNotLoadedData(&intenerg ,U_BIT);
    freeNotLoadedData(&rho      ,RHO_BIT);
    freeNotLoadedData(&hsml     ,HSML_BIT);
    freeNotLoadedData(&zs       ,ZS_BIT);
    freeNotLoadedData(&zsmt     ,ZSMT_BIT);
685
    freeNotLoadedData(&im       ,IM_BIT);
jclamber's avatar
jclamber committed
686
    freeNotLoadedData(&ssl      ,SSL_BIT);
687
    freeNotLoadedData(&cm       ,CM_BIT);
jcl's avatar
jcl committed
688 689 690 691 692 693 694
  }
  return 1;
}
// ============================================================================
// unitConversion()                                                            
void CSnapshotGadgetIn::unitConversion()
{
695
  double BOLTZMANN, PROTONMASS;
jcl's avatar
jcl committed
696
  double UnitLength_in_cm, UnitMass_in_g, UnitVelocity_in_cm_per_s;
697 698
  double UnitTime_in_s, UnitDensity_in_cgs, UnitEnergy_in_cgs;
  double Xh;
jcl's avatar
jcl committed
699

700 701 702 703
#if 0
  double UnitPressure_in_cgs, HubbleParam=0.65m G;
  double GRAVITY;
#endif
jcl's avatar
jcl committed
704 705 706
  double MeanWeight, u, gamma;
  double RhoUniverse_omegabar;
  /* physical constants in cgs units */
707
  //GRAVITY   = 6.672e-8;
jcl's avatar
jcl committed
708 709 710 711 712 713 714 715 716 717 718 719 720 721
  BOLTZMANN = 1.3806e-16;
  PROTONMASS = 1.6726e-24;

  /* internal unit system of the code */
  UnitLength_in_cm= 3.085678e21;   /*  code length unit in cm/h */
  UnitMass_in_g= 1.989e43;         /*  code mass unit in g/h */
#ifdef GRAPE_UNIT 
  UnitVelocity_in_cm_per_s= 207.9*1.0e5;
#else
  UnitVelocity_in_cm_per_s= 1.0e5;
#endif

  UnitTime_in_s= UnitLength_in_cm / UnitVelocity_in_cm_per_s;
  UnitDensity_in_cgs= UnitMass_in_g/ pow(UnitLength_in_cm,3);
722
  //UnitPressure_in_cgs= UnitMass_in_g/ UnitLength_in_cm/ pow(UnitTime_in_s,2);
jcl's avatar
jcl committed
723 724
  UnitEnergy_in_cgs= UnitMass_in_g * pow(UnitLength_in_cm,2) / pow(UnitTime_in_s,2);

725
  //G=GRAVITY/ pow(UnitLength_in_cm,3) * UnitMass_in_g * pow(UnitTime_in_s,2);
jcl's avatar
jcl committed
726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832

  Xh= 0.76;  /* mass fraction of hydrogen */
  
  RhoUniverse_omegabar=1.9e-29*0.04;

  assert(intenerg != NULL);

  for(int i=0;i<header.npart[0];i++) {

    MeanWeight= 4.0/(3*Xh+1+4*Xh*temp[i]) * PROTONMASS;

    /* convert internal energy to cgs units */

    u  = intenerg[i] * UnitEnergy_in_cgs/ UnitMass_in_g;

    gamma= 5.0/3;

    /* get temperature in Kelvin */

    temp[i] = MeanWeight/BOLTZMANN * (gamma-1) * u;
    if (rho) {
      rho[i] *= UnitDensity_in_cgs/RhoUniverse_omegabar;
    }
	  
#if 0
#ifndef NOAGE
    if(P[i].Type==4)
      {
	if(P[i].Age!=0)
	  P[i].Age=1.0/P[i].Age-1;
	else
	  {
	    //cout<<"Error Age"<<endl;
	    //cout<<"N="<<i<<P[i].Age<< endl;
	    //exit(0);
	  }

      }
#endif
#endif
  }

}
// ============================================================================
// compare 2 elements                                                          
int compare( const void * a, const void * b )
{
  t_particle_data_lite 
    * pa = ( t_particle_data_lite * ) a, 
    * pb = ( t_particle_data_lite * ) b;
  return (pa->Id - pb->Id);
}

// ============================================================================
// readHeader():                                                               
// read gadget header structure                                                
// return values : 0 success, >0 not a Gadget header data                      
int CSnapshotGadgetIn::readHeader(const int id)
{
  int len1,len2;

  // Header block
  readBlockName();
  bytes_counter=0;
  len1 = readFRecord();
  readData((char *)  header.npart         , sizeof(int   ),  6);
  readData((char *)  header.mass          , sizeof(double),  6);
  readData((char *) &header.time          , sizeof(double),  1);
  readData((char *) &header.redshift      , sizeof(double),  1);
  readData((char *) &header.flag_sfr      , sizeof(int   ),  1);
  readData((char *) &header.flag_feedback , sizeof(int   ),  1);
  readData((char *)  header.npartTotal    , sizeof(int   ),  6);
  readData((char *) &header.flag_cooling  , sizeof(int   ),  1);
  readData((char *) &header.num_files     , sizeof(int   ),  1);
  readData((char *) &header.BoxSize       , sizeof(double),  1);
  readData((char *) &header.Omega0        , sizeof(double),  1);
  readData((char *) &header.OmegaLambda   , sizeof(double),  1);
  readData((char *) &header.HubbleParam   , sizeof(double),  1);
  readData((char *)  header.fill          , sizeof(char  ), 96);
  len2 = readFRecord();
  if (verbose) {
    std::cerr << "header.flag_cooling = " << header.flag_cooling << "\n";
  }
  //std::cerr << "len1="<<len1<< " len2="<<len2<< " bytes_counter="<<bytes_counter<<"\n";
  if (in.bad() || len1!=len2 || len1!=bytes_counter)
    return 2;
  if (id==0) {                         // first time
    tframe = header.time;
    redshift = header.redshift;
    npartTotal = 0;
    npart_total_local = 0;
    ntotmasses  = 0 ; // !!!!!!!!!!! NEW
    for(int k=0; k<6; k++)  {
      npartTotal += header.npartTotal[k];    // count global total  particles
      npart_total_local += header.npart[k];  // count local total particles
    }
    for(int k=0; k<6; k++) {
      if (header.mass[k] == 0 ) {
        //ntotmasses += header.npartTotal[k];
        ntotmasses += header.npart[k];
      }
      if (verbose) {
        std::cerr << "mass["<<k<<"]="<<header.mass[k]<<"\n";
      }      
    }
    storeComponents();
  }
jclamber's avatar
jclamber committed
833 834
  in_start_block = in.tellg(); // save poistion of input file

jcl's avatar
jcl committed
835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941
  return 0;
}
// ============================================================================
// readBlockName : read Gadget2 file format block                              
bool CSnapshotGadgetIn::readBlockName()
{
  bool status=true;
  if (version == 2 ) { // gadget2 file format
    int dummy,nextblock;
    char name[5];
    array_vs_file_size = 0;
    readData((char *) &dummy    , sizeof(int) , 1); // read
    readData((char *) name      , sizeof(char), 4); // read label
    readData((char *) &nextblock, sizeof(int) , 1); // read nextblock
    readData((char *) &dummy    , sizeof(int) , 1); // read
#if 0
    int i=0; while (isupper(name[i])&& i<4) i++;
    name[i]='\0';
#else
    int i=0; while (name[i]!=' ' && i<4) i++;
    name[i]='\0';
#endif

    block_name=name;
    status = in.good();
    if (status && block_name!= "HEAD" && verbose) 
      std::cerr << "Reading Block Name : <" << block_name << ">\n";
  }
  return status;
}
// ============================================================================
// guessVersion()                                                              
// detect Gadget  file format version ( 1 or 2 )                               
// return true if successfully detected otherwise false                        
bool CSnapshotGadgetIn::guessVersion()
{
  bool status=true;
  // try to read 32bits length fortran record
  int dummy;
  swap = false; // no swapping
  array_vs_file_size = 0;
  readData((char *) &dummy, sizeof(int), 1); // read
  //std::cerr << "GadgetIn::guessVersion dummy = "<<dummy<<"\n";
  if( dummy != 256  && dummy != 8  ) {           // unknow number
    swap = true;                                 // need bytes swapping
    swapBytes((int *) &dummy, sizeof(int));      // swap
    //std::cerr << "GadgetIn::guessVersion dummy swapped= "<<dummy<<"\n";
    if( dummy != 256  && dummy != 8  )           // unknow swapped number
     status = false;                             // not a gadget file    
  }
  if (status) {
    if (dummy==256) version=1; // gadget1
    else            version=2; // gadget2
    in.seekg(0,std::ios::beg); // rewind
    //std::cerr << "gadget Version : " <<version << "\n"; 
  }

  return status;
}
// ============================================================================
// readData:                                                                     
// perform IO (Read,Write) operation on Data                                   
int CSnapshotGadgetIn::readData(char * ptr,const size_t size_bytes,const int items)
{
  if (array_vs_file_size==0) { // no conversion
    bytes_counter += (size_bytes*items);

    // get data from file
    in.read(ptr,size_bytes*items);
    //assert(in.good());
    if (! in.good()) return 0;
    
    // We SWAP data
    if (swap && (size_bytes != CHAR)) { // swapping requested
      for (int i=0; i<items; i++) {
        swapBytes(ptr,size_bytes);
        ptr += size_bytes;
      }
    }
  } else if (array_vs_file_size==1) {
    bytes_counter += (size_bytes*2*items);
    // data bigger on file
    // we must use a temporary variable
    double tmp;
    for (int i=0; i<items; i++) {
      in.read((char *) &tmp,sizeof(double)); // read one double from file
      if (swap && (size_bytes != CHAR)) { // swapping requested
        swapBytes((char *) &tmp,sizeof(double));
      }
      float tofloat=(float) tmp; // cast to float
      memcpy(ptr+sizeof(float)*i,(char*)&tofloat,sizeof(float)); // copy back to array

    }

  }
  return 1;
}
// ============================================================================
// getData                                                               
// return requested array according 'name' selection                                               
bool CSnapshotGadgetIn::getData(const std::string comp, std::string name, int *n,float **data)
{
  bool ok=true;
  *data=NULL;
  *n = 0;
  
  int nbody,first,last;
942 943 944 945 946 947 948 949 950
  bool status=false;

  if (comp!="STREAM") {
    status=getRangeSelect(comp.c_str(),&nbody,&first,&last,false); // find components ranges
    if (!status && comp=="all") { // retreive all particles selected by the user
      status=1;
      first=0;
      nbody=getNSel();
    }
jcl's avatar
jcl committed
951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051
  }
  switch(CunsOut::s_mapStringValues[name]) {
  case uns::Nbody :
    if (status) {
      *data = NULL;
      *n = nbody;
    } else {
      ok = false;
    }
    break;  
  case uns::Nsel   :
    if (status) {
      *n    = nbody;
    } else {
      ok=false;
    }  
  case uns::Pos   :
    if (status && getPos()) {
      *data = &getPos()[first*3];
      *n    = nbody;//getNSel();
    } else {
      ok=false;
    }
    break;
  case uns::Vel  :
    if (status && getVel()) {
      *data = &getVel()[first*3];
      *n    = nbody;//getNSel();
    } else {
      ok=false;
    }
    break;
  case uns::Acc  :
    if (status && getAcc()) {
      *data = &getAcc()[first*3];
      *n    = nbody;//getNSel();
    } else {
      ok=false;
    }
    break;
  case uns::Pot  :
    if (status && getPot()) {
      *data = &getPot()[first];
      *n    = nbody;//getNSel();
    } else {
      ok=false;
    }
    break;
  case uns::Mass  :
    if (status && getMass()) {
      *data = &getMass()[first];
      *n    = nbody;//getNSel();
    } else {
      ok=false;
    }
    break;
  case uns::Rho :
    if (status && comp=="gas" && getRho(*n)) {
      *data = getRho(*n);
    } else {
      ok=false;
    }
    break;
  case uns::U :
    if (status && comp=="gas" && getU(*n)) {
      *data = getU(*n);
    } else {
      ok=false;
    } 
    break;
  case uns::Hsml :
    if (status && comp=="gas" && getHsml(*n)) {
      *data = getHsml(*n);
    } else {
      ok=false;
    }  
    break;
  case uns::Temp :
    if (status && comp=="gas" && getTemp(*n)) {
      *data = getTemp(*n);
    } else {
      ok=false;
    } 
    break;
  case uns::Age :
    if (status && comp=="stars" && getAge(*n)) {
      *data = getAge(*n);
    } else {
      ok=false;
    } 
    break;
  case uns::Metal :
    if (status && comp=="gas" && ckloadBit(METAL_BIT)) {
      *data = getMetalGas(*n);
    } else
      if (status && comp=="stars" && ckloadBit(METAL_BIT)) {
      *data = getMetalStars(*n);
    } else {
      ok=false;
    }    
    break;
1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064
  case uns::Cm :
    if (status && comp=="gas") {
      *data = getCmGas(*n);
    } else
      if (status && comp=="stars") {
        *data = getCmStars(*n);
      } else
        if (status && comp=="all") {
          *data = getCm(*n);
        } else {
          ok=false;
        }
    break;
jcl's avatar
jcl committed
1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097
  case uns::Zs :
    if (status && comp=="gas") {
      *data = getZsGas(*n);
    } else
      if (status && comp=="stars") {
        *data = getZsStars(*n);
      } else
        if (status && comp=="all") {
          *data = getZs(*n);
        } else {
          ok=false;
        }
    break;
  case uns::ZSMT :
    if (status && comp=="gas") {
      *data = getZsmtGas(*n);
    } else
      if (status && comp=="stars") {
        *data = getZsmtStars(*n);
      } else
        if (status && comp=="all") {
          *data = getZsmt(*n);
        } else {
          ok=false;
        }
    break;
  case uns::Im :
    if (status && comp=="stars" && getIm(*n)) {
      *data = getIm(*n);
    } else {
      ok=false;
    }
    break;
jclamber's avatar
jclamber committed
1098 1099 1100 1101 1102 1103 1104
  case uns::Ssl :
    if (status && comp=="stars" && getSsl(*n)) {
      *data = getSsl(*n);
    } else {
      ok=false;
    }
    break;
jclamber's avatar
jclamber committed
1105 1106
  default: // unkown name
      if (comp=="STREAM") { // data stream reading
1107 1108 1109 1110 1111 1112 1113 1114
        if (data_vector[name].size()==0) { // map key does not exist
          std::vector<float> * p = &(data_vector[name]);
          int status=readStreamBlock(name,*p);
          if (status>0) {
            ok=true;
          }
        } else {
          ok = true;
jclamber's avatar
jclamber committed
1115
        }
1116 1117 1118 1119 1120
        if (ok) {
          *n = data_vector[name].size();
          *data = &data_vector[name][0];
        }

jclamber's avatar
jclamber committed
1121 1122 1123
      } else {
        ok=false;
      }
jcl's avatar
jcl committed
1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173
  }
  if (ok && !*data &&
      (CunsOut::s_mapStringValues[name]!=uns::Nbody &&
       CunsOut::s_mapStringValues[name]!=uns::Nsel)) ok = false; // not ok because array is NULL
  if (verbose) {
    if (ok) {
      std::cerr << "CSnapshotGadgetIn::getData name["<<name<<"]=" << CunsOut::s_mapStringValues[name] << "\n";
    } else {
      std::cerr << "**WARNING** CSnapshotGadgetIn::getData Value ["<<name<<"] for component <"<<comp<<"> does not exist...\n";
    }
  }
  return ok;
}
// ============================================================================
// getData                                                               
// return requested array according 'name' selection                                               
bool CSnapshotGadgetIn::getData(const std::string name,int *n,float **data)
{
  bool ok=true;
  *data=NULL;
  *n = 0;
  
  switch(CunsOut::s_mapStringValues[name]) {
  case uns::Pos   :
    *data = getPos();
    *n    = getNSel();
    break;
  case uns::Vel  :
    *data = getVel();
    *n    = getNSel();
    break;
  case uns::Mass  :
    *data = getMass();
    *n    = getNSel();
    break;
  case uns::Rho :
    *data = getRho(*n);
    break;
  case uns::U :
    *data = getU(*n);
    break;
  case uns::Hsml :
    *data = getHsml(*n);
    break;
  case uns::Temp :
    *data = getTemp(*n);
    break;
  case uns::Age :
    *data = getAge(*n);
    break;
jclamber's avatar
jclamber committed
1174 1175 1176 1177
  case uns::Acc :
    *data = getAcc();
    *n    = getNSel();
    break;
jcl's avatar
jcl committed
1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205
  case uns::Metal :
    if (comp_bits&STARS_BIT && comp_bits&GAS_BIT)      // gas and stars requested
      *data = getMetal(*n);
    else
      if (comp_bits&STARS_BIT)                         // only stars requested
        *data = getMetalStars(*n);
      else
        if (comp_bits&GAS_BIT)                         // only gas requested
          *data = getMetalGas(*n);
    break;
  case uns::GasMetal :
    if (ckloadBit(METAL_BIT))
      *data = getMetalGas(*n);
    break;
  case uns::StarsMetal :
    if (ckloadBit(METAL_BIT))
      *data = getMetalStars(*n);
    break;
  case uns::Zs :
    if (comp_bits&STARS_BIT && comp_bits&GAS_BIT)      // gas and stars requested
      *data = getZs(*n);
    else
      if (comp_bits&STARS_BIT)                         // only stars requested
        *data = getZsStars(*n);
      else
        if (comp_bits&GAS_BIT)                         // only gas requested
          *data = getZsGas(*n);
    break;
1206 1207 1208 1209 1210 1211 1212 1213 1214 1215
  case uns::Cm :
    if (comp_bits&STARS_BIT && comp_bits&GAS_BIT)      // gas and stars requested
      *data = getCm(*n);
    else
      if (comp_bits&STARS_BIT)                         // only stars requested
        *data = getCmStars(*n);
      else
        if (comp_bits&GAS_BIT)                         // only gas requested
          *data = getCmGas(*n);
    break;
jcl's avatar
jcl committed
1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228
  case uns::ZSMT :
    if (comp_bits&STARS_BIT && comp_bits&GAS_BIT)      // gas and stars requested
      *data = getZsmt(*n);
    else
      if (comp_bits&STARS_BIT)                         // only stars requested
        *data = getZsmtStars(*n);
      else
        if (comp_bits&GAS_BIT)                         // only gas requested
          *data = getZsmtGas(*n);
    break;
  case uns::Im :
    *data = getIm(*n);
    break;
jclamber's avatar
jclamber committed
1229 1230 1231
  case uns::Ssl :
    *data = getSsl(*n);
    break;
jcl's avatar
jcl committed
1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423
  default: ok=false;
  }
  
  if (ok && !*data) ok = false; // not ok because array is NULL
  if (verbose) {
    if (ok) {
      std::cerr << "CSnapshotGadgetIn::getData name["<<name<<"]=" << CunsOut::s_mapStringValues[name] << "\n";
    } else {
      std::cerr << "**WARNING** CSnapshotGadgetIn::getData Value ["<<name<<"] does not exist...\n";
    }
  }
  return ok;
}
// ============================================================================
// getData                                                               
// return requested float according 'name' selection                                               
bool CSnapshotGadgetIn::getData(const std::string name,float *data)
{
  bool ok=true;
  *data=0.0;  
  switch(CunsOut::s_mapStringValues[name]) {
  case uns::Time   :
    *data = getTime();   
    break;
  case uns::Redshift   :
    *data = getRedshift();   
    break; 
  default: ok=false;
  }
  if (verbose) {
    if (ok) {
      std::cerr << "CSnapshotGadgetIn::getData name["<<name<<"]=" << CunsOut::s_mapStringValues[name] << "\n";
    }  else {
      std::cerr << "**WARNING** CSnapshotGadgetIn::getData Value ["<<name<<"] does not exist...\n";
    }
  }
  return ok;
}
// ============================================================================
// getData                                                               
// return requested array according 'name' selection                                               
bool CSnapshotGadgetIn::getData(const std::string comp,const std::string name,int *n, int **data)
{
  bool ok=true;
  *data=NULL;
  *n = 0;
  
  int nbody,first,last;
  bool status=getRangeSelect(comp.c_str(),&nbody,&first,&last,false); // find components ranges
  if (!status && comp=="all") { // retreive all particles selected by the user
    status=1;
    first=0;
    nbody=getNSel();
  }
  switch(CunsOut::s_mapStringValues[name]) {
  case uns::Id :
    if (status && ckloadBit(ID_BIT)) {
      *data = id+first;
      *n = nbody;
    } else {
      ok = false;
    }
    break;
  case uns::Nbody :
    if (status) {
      *data = NULL;
      *n = nbody;
    } else {
      ok = false;
    }
    break;  
  default: ok=false;
  }
  if (verbose) {
    if (ok) {
      std::cerr << "CSnapshotGadgetIn::getData name["<<name<<"]=" << CunsOut::s_mapStringValues[name] << "\n";
    } else {
      std::cerr << "**WARNING** CSnapshotGadgetIn::getData Value ["<<name<<"] for component <"<<comp<<"> does not exist...\n";
    }
  }
  return ok;
}

// ============================================================================
// getData                                                               
// return requested array according 'name' selection                                               
bool CSnapshotGadgetIn::getData(const std::string name,int *n, int **data)
{
  bool ok=true;
  *data=NULL;
  *n = 0;
  
  switch(CunsOut::s_mapStringValues[name]) {
  case uns::Id :
    if (ckloadBit(ID_BIT)) {
      *data = id;
      *n    = getNSel();
    } else {
      ok = false;
    }
    break;
  default: ok=false;
  }
  if (verbose) {
    if (ok) {
      std::cerr << "CSnapshotGadgetIn::getData name["<<name<<"]=" << CunsOut::s_mapStringValues[name] << "\n";
    } else {
      std::cerr << "**WARNING** CSnapshotGadgetIn::getData Value ["<<name<<"] does not exist...\n";
    }
  }
  return ok;
}
// ============================================================================
// getData                                                               
// return requested int according 'name' selection                                               
bool CSnapshotGadgetIn::getData(const std::string name,int *data)
{
  bool ok=true;
  *data=0;
  switch(CunsOut::s_mapStringValues[name]) {
  case uns::Nsel   :
    *data = getNSel();
    break;
  case uns::Ngas   :
    *data = header.npartTotal[0];
    break;
  case uns::Nhalo   :
    *data = header.npartTotal[1];
    break;
  case uns::Ndisk   :
    *data = header.npartTotal[2];
    break;
  case uns::Nbulge   :
    *data = header.npartTotal[3];
    break;
  case uns::Nstars   :
    *data = header.npartTotal[4];
    break;
  case uns::Nbndry   :
    *data = header.npartTotal[5];
    break;
  case uns::Czs   :
    *data = czs;
    break;
  case uns::Czsmt   :
    *data = czsmt;
    break;
  default: ok=false;
  }
  if (ok && !*data) ok = false; // not ok because array is NULL
  if (verbose) {
    if (ok) {
      std::cerr << "CSnapshotGadgetIn::getData name["<<name<<"]=" << CunsOut::s_mapStringValues[name] << "\n";
    } else {
      std::cerr << "**WARNING** CSnapshotGadgetIn::getData Value ["<<name<<"] does not exist or empty\n";
    }
  }
  return ok;
}
// ============================================================================
// isLittleEndian()                                                            
// Test endianess: return true if little endian architecture, false if big endian
bool CSnapshotGadgetIn::isLittleEndian()
{
  bool status=false;
  int one=1;
  char * p = (char *)&one;
  if (p[0]==1 ) status=true;
  return status;
}
// ============================================================================
// storeComponents:                                                            
void CSnapshotGadgetIn::storeComponents()
{
  uns::ComponentRange cr;
  // all
  cr.setData(0,npartTotal-1);
  cr.setType("all");
  crv.clear();
  crv.push_back(cr);
  // components
  const char * comp [] = { "gas", "halo", "disk", "bulge", "stars", "bndry"};
  for(int k=0,start=0; k<6; k++)  {
    if (header.npartTotal[k]) {
      cr.setData(start,start+header.npartTotal[k]-1,comp[k]);
      crv.push_back(cr);
      start+=header.npartTotal[k];
    }
  }
}


jclamber's avatar
jclamber committed
1424 1425 1426 1427 1428
// ----------------------------------------------------------------------------
//
//                     CSnapshotGadgetOut CLASS implementation
//
// ----------------------------------------------------------------------------
jcl's avatar
jcl committed
1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450

// ----------------------------------------------------------------------------
// WRITING constructor
CSnapshotGadgetOut::CSnapshotGadgetOut(const std::string _n, const std::string _t, const bool _v):CSnapshotInterfaceOut(_n, _t, _v)
{
  if (simtype=="gadget1") version=1;
  else
    if (simtype=="gadget2") version=2;
  else {
    std::cerr << "Unkwown Gadget file type : ["<<simtype<<"]\n"
        << "aborting .....\n";
    std::exit(1);
  }
  std::ostringstream stm;
  stm << version;
  interface_type = "Gadget" + stm.str();
  file_structure = "component"; // "component" like file
  if (verbose) std::cerr << "CSnapshotGadgetOut::CSnapshotGadgetOut simname = " << simname <<"\n";
  for (int i=0;i<6; i++) {
    mass[i]   = NULL;
    pos [i]   = NULL;
    vel [i]   = NULL;
1451
    pot [i]   = NULL;
jclamber's avatar
jclamber committed
1452
    acc [i]   = NULL;
jcl's avatar
jcl committed
1453
    id  [i]   = NULL;
jclamber's avatar
jclamber committed
1454
    metal[i]  = NULL;
jcl's avatar
jcl committed
1455 1456 1457 1458
    ptrIsAlloc[i]["mass" ]=false; 
    ptrIsAlloc[i]["pos"  ]=false; 
    ptrIsAlloc[i]["vel"  ]=false; 
    ptrIsAlloc[i]["id"   ]=false; 
1459
    ptrIsAlloc[i]["pot"  ]=false;
jclamber's avatar
jclamber committed
1460
    ptrIsAlloc[i]["acc"  ]=false;
jclamber's avatar
jclamber committed
1461
    ptrIsAlloc[i]["metal"]=false;
jcl's avatar
jcl committed
1462 1463 1464
  }
  //id     = NULL;
  age    = NULL;
jclamber's avatar
jclamber committed
1465
  //metal  = NULL;
jcl's avatar
jcl committed
1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492
  intenerg=NULL;
  temp   = NULL;
  rho    = NULL;
  hsml   = NULL;
  ntot_withmasses=0;

  // gas only
  ptrIsAlloc[0]["temp" ]=false;
  ptrIsAlloc[0]["rho"  ]=false; 
  ptrIsAlloc[0]["hsml" ]=false; 
  ptrIsAlloc[0]["metal"]=false; 
  ptrIsAlloc[0]["u"    ]=false; 
  // stars only
  ptrIsAlloc[4]["age"  ]=false; 
  ptrIsAlloc[4]["metal"]=false; 
  
  bits   = 0;
  bzero(&header,sizeof(header));
}
// ----------------------------------------------------------------------------
// destructor                                                                 
CSnapshotGadgetOut::~CSnapshotGadgetOut()
{
  for (int i=0; i<6; i++) {
    if (mass[i]&& ptrIsAlloc[i]["mass" ]) delete [] mass[i];
    if (pos [i]&& ptrIsAlloc[i]["pos"  ]) delete [] pos[i];
    if (vel [i]&& ptrIsAlloc[i]["vel"  ]) delete [] vel[i];    
1493 1494
    if (id  [i]&& ptrIsAlloc[i]["id"   ]) delete [] id[i];
    if (pot [i]&& ptrIsAlloc[i]["pot"  ]) delete [] pot[i];
jclamber's avatar
jclamber committed
1495
    if (acc [i]&& ptrIsAlloc[i]["acc"  ]) delete [] acc[i];
jclamber's avatar
jclamber committed
1496
    if (metal[i]&& ptrIsAlloc[i]["metal"]) delete [] metal[i];
jcl's avatar
jcl committed
1497 1498 1499 1500
  }
  // gas only
  if (rho      && ptrIsAlloc[0]["rho"  ]) delete [] rho;
  if (hsml     && ptrIsAlloc[0]["hsml" ]) delete [] hsml;
jclamber's avatar
jclamber committed
1501 1502 1503 1504
//  if (metal    && ptrIsAlloc[0]["metal"]) {
//    delete [] metal;
//    metal=NULL;
//  }
jcl's avatar
jcl committed
1505 1506 1507
  if (temp     && ptrIsAlloc[0]["temp" ]) delete [] temp;
  if (intenerg && ptrIsAlloc[0]["u"    ]) delete [] intenerg;
  // stars only
jclamber's avatar
jclamber committed
1508 1509 1510 1511
//  if (metal    && ptrIsAlloc[4]["metal"]) {
//    delete [] metal;
//    metal=NULL;
//  }
jcl's avatar
jcl committed
1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627
  if (age      && ptrIsAlloc[4]["age"  ]) delete [] age;
}
// ----------------------------------------------------------------------------
// putHeader
  int CSnapshotGadgetOut::setHeader(void * _header)
{
  setHeader((t_io_header_1 *) (_header));
  return 1;
}
  // ----------------------------------------------------------------------------
  // setData
  int CSnapshotGadgetOut::setData(std::string name,float  data)
  {
    bool ok=true;
    int status=0;
  
    switch(CunsOut::s_mapStringValues[name]) {
    case uns::Time : 
      status = 1;
      header.time = data;
      break;
    default: ok=false;
    }
  
    if (verbose) {
      if (ok) {
        std::cerr << "CSnapshotGadgetOut::setData name["<<name<<"]=" << CunsOut::s_mapStringValues[name] << "\n";
      } else {
        std::cerr << "** WARNING ** SnapshotGadgetOut::setData Value ["<<name<<"] does not exist.....\n";
      }
    }
    return status;
  }

// ----------------------------------------------------------------------------
// setData
int CSnapshotGadgetOut::setData(std::string name, const int n ,int * data,const bool _addr)
{
  bool ok=true;
  int status=0;

  switch(CunsOut::s_mapStringValues[name]) {
#if 0    
  case uns::Id :
    assert(n==npartTotal);
    if (_addr) { // map address
      id = data;
    }
    else {
      //ptrIsAlloc["mass"]=true;
      if (! id) 
	id = new int[npartTotal];
      memcpy(id,data,sizeof(int)*n);
    }
    bits |= ID_BIT;
    break;
#endif
  default: ok=false;
  }
  
  if (verbose) {
    if (ok) { std::cerr << "CSnapshotGadgetOut::setData name["<<name<<"]=" << CunsOut::s_mapStringValues[name] << "\n";
    } else {
      std::cerr << "** WARNING ** CSnapshotGadgetOut::setData Value ["<<name<<"] does not exist.....\n";    
    }
  }
  return status;
}
// ----------------------------------------------------------------------------
// setData
int CSnapshotGadgetOut::setData(std::string name, const int n ,float * data,const bool _addr)
{
  bool ok=true;
  int status=0;

  switch(CunsOut::s_mapStringValues[name]) {
  case uns::Rho : 
    status = setRho(n, data, _addr);
    break;
  case uns::Hsml: 
    status = setHsml(n, data, _addr);
    break;
  case uns::U: 
    status = setU(n, data, _addr);
    break;
  case uns::Temp  :
    status = setTemp(n, data, _addr);
    break;
  case uns::Age  :
    status = setAge(n, data, _addr);
    break;
  case uns::GasMetal  :
    status = setMetalGas(n, data, _addr);
    break;
  case uns::StarsMetal  :
    status = setMetalStars(n, data, _addr);
    break;
  default: ok=false;
  }

  if (verbose) {
    if (ok) { std::cerr << "CSnapshotGadgetOut::setData name["<<name<<"]=" << CunsOut::s_mapStringValues[name] << "\n";
    } else {
      std::cerr << "** WARNING ** CSnapshotGadgetOut::setData Value ["<<name<<"] does not exist.....\n";
    }
  }
  return status;
}
// ----------------------------------------------------------------------------
// setData
// setData("gas","pos",n,gas_array,true)
int CSnapshotGadgetOut::setData(std::string name,std::string array,  const int n ,float * data,const bool _addr)
{
  bool ok=true;
  int status=0;

jclamber's avatar
jclamber committed
1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667
  if ( name == "EXTRA" ) { // it's an extra data
    status = setExtra(array,n, data, _addr);
  } else {
    switch(CunsOut::s_mapStringValues[array]) {
    case uns::Pos  :
      status = setPos(name, n, data, _addr);
      break;
    case uns::Vel  :
      status = setVel(name, n, data, _addr);
      break;
    case uns::Mass :
      status = setMass(name, n, data, _addr);
      break;
    case uns::Pot  :
      status = setPot(name, n, data, _addr);
      break;
    case uns::Acc  :
      status = setAcc(name, n, data, _addr);
      break;
    case uns::Hsml :
      status = setHsml(n, data, _addr);
      break;
    case uns::Rho  :
      status = setRho(n, data, _addr);
      break;
    case uns::U  :
      status = setU(n, data, _addr);
      break;
    case uns::Temp  :
      status = setTemp(n, data, _addr);
      break;
    case uns::Age  :
      status = setAge(n, data, _addr);
      break;
    case uns::GasMetal  :
      status = setMetalGas(n, data, _addr);
      break;
    case uns::StarsMetal  :
      status = setMetalStars(n, data, _addr);
      break;
jclamber's avatar
jclamber committed
1668 1669 1670 1671 1672 1673 1674 1675 1676
    case uns::Metal  :
      if (name=="gas") {
        status = setMetalGas(n, data, _addr);
      } else {
        if (name=="stars") {
          status = setMetalStars(n, data, _addr);
        }
      }
      break;
jclamber's avatar
jclamber committed
1677 1678
    default: ok=false;
    }
jcl's avatar
jcl committed
1679

jclamber's avatar
jclamber committed
1680
  }
jcl's avatar
jcl committed
1681 1682 1683 1684
  if (verbose) {
    if (ok) { 
      std::cerr << "CSnapshotGadgetOut::setData name["<<name<<"]=" << CunsOut::s_mapStringValues[name] << "\n";
    } else {
jclamber's avatar
jclamber committed
1685 1686 1687 1688 1689
      if (name != "EXTRA") {
        std::cerr << "** WARNING ** CSnapshotGadgetOut::setData Value ["<<name<<"] does not exist.....\n";
      } else {
        std::cerr << "CSnapshotGadgetOut::setData EXTRA tags["<<array<<"]\n";
      }
jcl's avatar
jcl committed
1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902
    }
  }
  return status;
}
// ----------------------------------------------------------------------------
// setData
// setData("all","id",n,gas_array,true)
int CSnapshotGadgetOut::setData(std::string name,std::string array,  const int n ,int * data,const bool _addr)
{
  bool ok=true;
  int status=0;
  
  switch(CunsOut::s_mapStringValues[name]) {
  case uns::Gas   :
  case uns::Halo  :
  case uns::Disk  :
  case uns::Bulge :
  case uns::Stars :
  case uns::Bndry :
    status = setId(name, n, data, _addr);
    break;
  default: ok=false;
  }

  if (verbose) {
    if (ok) { 
      std::cerr << "CSnapshotGadgetOut::setData name["<<name<<"]=" << CunsOut::s_mapStringValues[name] << "\n";
    } else {
      std::cerr << "** WARNING ** CSnapshotGadgetOut::setData Value ["<<name<<"] does not exist.....\n";
    }
  }
  return status;
#if 0
  switch(CunsOut::s_mapStringValues[array]) {
  case uns::Id  :
    status = setData(array, n, data, _addr);
    break;
  default: ok=false;
  }

  if (verbose) {
    if (ok) {
      std::cerr << "CSnapshotGadgetOut::setData name["<<name<<"]=" << CunsOut::s_mapStringValues[name] << "\n";
    } else {
      std::cerr << "** WARNING ** CSnapshotGadgetOut::setData Value ["<<name<<"] does not exist.....\n";
    }
  }
  return status;
#endif
  
}

// ----------------------------------------------------------------------------
// setData
// setData("gas",n,pos,vel,mass,true)
int CSnapshotGadgetOut::setData(std::string name, const int n ,float * data, float * data1, float * data2, const bool _addr)
{
  bool ok=true;
  int status=0;

  switch(CunsOut::s_mapStringValues[name]) {
  case uns::Gas   :
  case uns::Halo  :
  case uns::Disk  :
  case uns::Bulge :
  case uns::Stars :
  case uns::Bndry :
    status = setMass(name, n, data , _addr);
    status = setPos (name, n, data1, _addr);
    status = setVel (name, n, data2, _addr);
    break;
  default: ok=false;
  }
  
  if (verbose) {
    if (ok) { 
      std::cerr << "CSnapshotGadgetOut::setData name["<<name<<"]=" << CunsOut::s_mapStringValues[name] << "\n";
    } else {
      std::cerr << "** WARNING ** CSnapshotGadgetOut::setData Value ["<<name<<"] does not exist.....\n";
    }
  }
  return status;
}

// ============================================================================
// setHeader:                                                            
int CSnapshotGadgetOut::setHeader(t_io_header_1 * _header)
{
  memcpy(&header,_header,sizeof(t_io_header_1));
  bits &= HEADER_BIT;
  return 1;
}
// ============================================================================
// setNbody:                                                            
int CSnapshotGadgetOut::setNbody(const int _nbody)
{
  npartTotal = _nbody;
  return 1;
}
// ============================================================================
// setId:                                                            
int CSnapshotGadgetOut::setId(std::string name, const int _n, int * _id, const bool addr)
{
  int index=-1;
  switch(CunsOut::s_mapStringValues[name]) {
  case uns::Gas    : index=0; break;
  case uns::Halo   : index=1; break;
  case uns::Disk   : index=2; break;
  case uns::Bulge  : index=3; break;
  case uns::Stars  : index=4; break;
  case uns::Bndry  : index=5; break;
  default:
    break;
  }
  assert(index!=-1);
  if (addr) { // map address
    id[index] = _id;
  }
  else {
    ptrIsAlloc[index]["id"]=true;
    if (id[index])  delete [] id[index];
    id[index] = new int[_n];
    memcpy(id[index],_id,sizeof(int)*_n);
  }
  header.npart[index] = _n;
  bits |= ID_BIT;
  return 1;
}
// ============================================================================
// setMass:                                                            
  int CSnapshotGadgetOut::setMass(std::string name, const int _n, float * _mass, const bool addr)
  {
    int index=-1;
    switch(CunsOut::s_mapStringValues[name]) {
    case uns::Gas    : index=0; break;
    case uns::Halo   : index=1; break;
    case uns::Disk   : index=2; break;
    case uns::Bulge  : index=3; break;
    case uns::Stars  : index=4; break;
    case uns::Bndry  : index=5; break;
    default:
      break;
    }
    assert(index!=-1);
  if (addr) { // map address
    mass[index] = _mass;
  }
  else {
    ptrIsAlloc[index]["mass"]=true;
    if (mass[index])  delete [] mass[index];
    mass[index] = new float[_n];
    memcpy(mass[index],_mass,sizeof(float)*_n);
  }
  header.npart[index] = _n;
  bits |= MASS_BIT;
  return 1;
}
// ============================================================================
// setPos:                                                            
int CSnapshotGadgetOut::setPos(std::string name, const int _n, float * _pos, const bool addr)
{
  int index=-1;
  switch(CunsOut::s_mapStringValues[name]) {
  case uns::Gas    : index=0; break;
  case uns::Halo   : index=1; break;
  case uns::Disk   : index=2; break;
  case uns::Bulge  : index=3; break;
  case uns::Stars  : index=4; break;
  case uns::Bndry  : index=5; break;
  default:
    break;
  }
  if (addr) { // map address
    pos[index]= _pos;
  }
  else{
    ptrIsAlloc[index]["pos"]=true;
    if (pos[index]) delete [] pos[index]; 
    pos[index] = new float[_n*3];
    memcpy(pos[index],_pos,sizeof(float)*_n*3);
  }
  header.npart[index] = _n;
  bits |= POS_BIT;
  return 1;
}
// ============================================================================
// setVel:                                                            
 int CSnapshotGadgetOut::setVel(std::string name, const int _n, float * _vel, const bool addr)
{
  int index=-1;
  switch(CunsOut::s_mapStringValues[name]) {
  case uns::Gas    : index=0; break;
  case uns::Halo   : index=1; break;
  case uns::Disk   : index=2; break;
  case <