snapshotgadget.cc 69.8 KB
Newer Older
jcl's avatar
jcl committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224
// ============================================================================
// Copyright Jean-Charles LAMBERT - 2008-2010                                       
// e-mail:   Jean-Charles.Lambert@oamp.fr                                      
// address:  Dynamique des galaxies                                            
//           Laboratoire d'Astrophysique de Marseille                          
//           Pole de l'Etoile, site de Chateau-Gombert                         
//           38, rue Frederic Joliot-Curie                                     
//           13388 Marseille cedex 13 France                                   
//           CNRS U.M.R 6110                                                   
// ============================================================================

/* 
	@author Jean-Charles Lambert <Jean-Charles.Lambert@oamp.fr>
 */


#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;
  bits   = 0;
  load_bits = 0;
  tframe = 0.;
  redshift=0.;
  frecord_offset = 4;
  czs = 0;
  czsmt= 0;
  bytes_counter = 0;
  multiplefiles = 0;
  lonely_file   = true;
  ntotmasses = 0.0;
  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";
  }
}
// ----------------------------------------------------------------------------
// 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;
  }
  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;
  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 {
        skipData(sizeof(T)*dim*header.npart[k]);
      }
    }
  }  
  int len2 = readFRecord();
225 226
  if (len2==len1) ; // remove warning....
  assert(len2==len1 && in.good() && len1==bytes_counter);
jcl's avatar
jcl committed
227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250
  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();
251 252
  if (len2==len1) ; // remove warning....
  assert(in.good() && len2==len1 && len1==bytes_counter);
jcl's avatar
jcl committed
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269
  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();
270
  if (len2==len1) ; // remove warning....
jcl's avatar
jcl committed
271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332
  assert(in.good() && len1==len2 && len1==bytes_counter);
  return 1;
}

// ============================================================================
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
333
          if (fail) assert(0);     // fail is true abort
jcl's avatar
jcl committed
334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398
        }
      }
      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;
          if (ntotmasses>0.) {    // different masses
            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
          if (ntotmasses > 0.) {  // different masses
            len2 = readFRecord(); // we must read from disk
399 400
            if (len2==len1) ; // remove warning....
            assert(in.good() && len2==len1 && len1==bytes_counter);
jcl's avatar
jcl committed
401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582
          }
          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);
        }
        // --> 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)
      if (ntotmasses == 0. && req_bits&MASS_BIT) { // no BLOCK_MASS present (mass inside the header)
        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);
  }
  return 1;
}
// ============================================================================
// unitConversion()                                                            
void CSnapshotGadgetIn::unitConversion()
{
583
  double BOLTZMANN, PROTONMASS;
jcl's avatar
jcl committed
584
  double UnitLength_in_cm, UnitMass_in_g, UnitVelocity_in_cm_per_s;
585 586
  double UnitTime_in_s, UnitDensity_in_cgs, UnitEnergy_in_cgs;
  double Xh;
jcl's avatar
jcl committed
587

588 589 590 591
#if 0
  double UnitPressure_in_cgs, HubbleParam=0.65m G;
  double GRAVITY;
#endif
jcl's avatar
jcl committed
592 593 594
  double MeanWeight, u, gamma;
  double RhoUniverse_omegabar;
  /* physical constants in cgs units */
595
  //GRAVITY   = 6.672e-8;
jcl's avatar
jcl committed
596 597 598 599 600 601 602 603 604 605 606 607 608 609
  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);
610
  //UnitPressure_in_cgs= UnitMass_in_g/ UnitLength_in_cm/ pow(UnitTime_in_s,2);
jcl's avatar
jcl committed
611 612
  UnitEnergy_in_cgs= UnitMass_in_g * pow(UnitLength_in_cm,2) / pow(UnitTime_in_s,2);

613
  //G=GRAVITY/ pow(UnitLength_in_cm,3) * UnitMass_in_g * pow(UnitTime_in_s,2);
jcl's avatar
jcl committed
614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 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 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 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 833 834 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 942 943 944 945 946 947 948 949 950 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 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 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 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 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 1174 1175 1176 1177 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 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 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

  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();
  }
  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;
  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::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;
  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;
  default: ok=false;
  }
  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;
  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;
  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;
  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];
    }
  }
}



  //
  // CSnapshotGadgetOut CLASS implementation
  //


// ----------------------------------------------------------------------------
// 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;
1278
    pot [i]   = NULL;
jclamber's avatar
jclamber committed
1279
    acc [i]   = NULL;
jcl's avatar
jcl committed
1280 1281 1282 1283 1284
    id  [i]   = NULL;
    ptrIsAlloc[i]["mass" ]=false; 
    ptrIsAlloc[i]["pos"  ]=false; 
    ptrIsAlloc[i]["vel"  ]=false; 
    ptrIsAlloc[i]["id"   ]=false; 
1285
    ptrIsAlloc[i]["pot"  ]=false;
jclamber's avatar
jclamber committed
1286
    ptrIsAlloc[i]["acc"  ]=false;
jcl's avatar
jcl committed
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
  }
  //id     = NULL;
  age    = NULL;
  metal  = NULL;
  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];    
1318 1319
    if (id  [i]&& ptrIsAlloc[i]["id"   ]) delete [] id[i];
    if (pot [i]&& ptrIsAlloc[i]["pot"  ]) delete [] pot[i];
jclamber's avatar
jclamber committed
1320
    if (acc [i]&& ptrIsAlloc[i]["acc"  ]) delete [] acc[i];
jcl's avatar
jcl committed
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 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461
  }
  // gas only
  if (rho      && ptrIsAlloc[0]["rho"  ]) delete [] rho;
  if (hsml     && ptrIsAlloc[0]["hsml" ]) delete [] hsml;
  if (metal    && ptrIsAlloc[0]["metal"]) {
    delete [] metal;
    metal=NULL;
  }
  if (temp     && ptrIsAlloc[0]["temp" ]) delete [] temp;
  if (intenerg && ptrIsAlloc[0]["u"    ]) delete [] intenerg;
  // stars only
  if (metal    && ptrIsAlloc[4]["metal"]) {
    delete [] metal;
    metal=NULL;
  }
  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;

  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;
1462 1463 1464
  case uns::Pot  :
    status = setPot(name, n, data, _addr);
    break;
jclamber's avatar
jclamber committed
1465 1466 1467
  case uns::Acc  :
    status = setAcc(name, n, data, _addr);
    break;
jcl's avatar
jcl committed
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 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 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 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 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709
  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;
  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("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 uns::Bulge  : index=3; break;
  case uns::Stars  : index=4; break;
  case uns::Bndry  : index=5; break;
  default:
    break;
  }
  if (addr) { // map address
    vel[index] = _vel;
  }
  else {
    ptrIsAlloc[index]["vel"]=true;
    if (vel[index]) delete [] vel[index];
    vel[index] = new float[_n*3];
    memcpy(vel[index],_vel,sizeof(float)*_n*3);
  }
  header.npart[index] = _n;
  bits |= VEL_BIT;
  return 1;
}
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
 // ============================================================================
 // setPot:
 int CSnapshotGadgetOut::setPot(std::string name, const int _n, float * _pot, 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
     pot[index]= _pot;
   }
   else{
     ptrIsAlloc[index]["pot"]=true;
     if (pot[index]) delete [] pot[index];
     pot[index] = new float[_n];
     memcpy(pot[index],_pot,sizeof(float)*_n);
   }
   header.npart[index] = _n;
   bits |= POT_BIT;
   return 1;
 }
jclamber's avatar
jclamber committed
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
 // ============================================================================
 // setAcc:
  int CSnapshotGadgetOut::setAcc(std::string name, const int _n, float * _acc, 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
     acc[index] = _acc;
   }
   else {
     ptrIsAlloc[index]["acc"]=true;
     if (acc[index]) delete [] acc[index];
     acc[index] = new float[_n*3];
     memcpy(acc[index],_acc,sizeof(float)*_n*3);
   }
   header.npart[index] = _n;
   bits |= ACC_BIT;
   return 1;
 }
jcl's avatar
jcl committed
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 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106
// ============================================================================
// setRho:                                                            
 int CSnapshotGadgetOut::setRho(const int _n, float * _rho, const bool addr)
{
  assert(_n==header.npart[0]);; // #rho particles = #gas particles
  if (addr) { // map address
    rho = _rho;
  }
  else {
    ptrIsAlloc[0]["rho"]=true;
    if (! rho) 
      rho = new float[_n];
    memcpy(rho,_rho,sizeof(float)*_n);
  }
  bits |= RHO_BIT;
  return 1;
}
// ============================================================================
// setHsml:                                                            
 int CSnapshotGadgetOut::setHsml(const int _n, float * _hsml, const bool addr)
{

  assert(_n==header.npart[0]);; // #hsml particles = #gas particles
  if (addr) { // map address
    hsml = _hsml;
  }
  else {
    ptrIsAlloc[0]["hsml"]=true;
    if (! hsml) 
      hsml = new float[_n];
    memcpy(hsml,_hsml,sizeof(float)*_n);
  }
  bits |= HSML_BIT;
  return 1;
}
 // ============================================================================
 // setU:                                                            
 int CSnapshotGadgetOut::setU(const int _n, float * _U, const bool addr)
 {
   
   assert(_n==header.npart[0]);; // #U particles = #gas particles
   if (addr) { // map address
     intenerg = _U;
   }
   else {
     ptrIsAlloc[0]["u"]=true;
     if (! intenerg) 
       intenerg = new float[_n];
     memcpy(intenerg,_U,sizeof(float)*_n);
   }
   bits |= U_BIT;
   return 1;
 }
 // ============================================================================
 // setTemp:                                                            
 int CSnapshotGadgetOut::setTemp(const int _n, float * _temp, const bool addr)
 {
   
   assert(_n==header.npart[0]);; // #U particles = #gas particles
   if (addr) { // map address
     temp = _temp;
   }
   else {
     ptrIsAlloc[0]["temp"]=true;
     if (! temp) 
       temp = new float[_n];
     memcpy(temp,_temp,sizeof(float)*_n);
   }
   bits |= TEMP_BIT;
   return 1;
 }
 // ============================================================================
 // setMetalGas:                                                            
 int CSnapshotGadgetOut::setMetalGas(const int _n, float * _mg, const bool addr)
 {
   
   assert(_n==header.npart[0]);; // #U particles = #gas particles
   if (addr) { // map address
     metal = _mg;
   }
   else {
     ptrIsAlloc[0]["metal"]=true;
     if (! metal) 
       metal = new float[header.npart[0]+header.npart[4]];
     memcpy(metal,_mg,sizeof(float)*_n);
   }
   bits |= METAL_BIT;
   return 1;
 }
 // ============================================================================
 // setMetalStars:                                                            
 int CSnapshotGadgetOut::setMetalStars(const int _n, float * _ms, const bool addr)
 {
   
   assert(_n==header.npart[4]);; // #metal stars particles
   if (addr) { // map address
     metal = _ms;
   }
   else {
     ptrIsAlloc[4]["metal"]=true;
     if (! metal) 
       metal = new float[header.npart[0]+header.npart[4]];        
     memcpy(metal+header.npart[0],_ms,sizeof(float)*_n);
   }
   bits |= METAL_BIT;
   return 1;
 }
 // ============================================================================
 // setAge:                                                            
 int CSnapshotGadgetOut::setAge(const int _n, float * _age, const bool addr)
 {
   
   assert(_n==header.npart[4]);; // #age stars particles
   if (addr) { // map address
     age = _age;
   }
   else {
     ptrIsAlloc[4]["age"]=true;
     if (! age) 
       age = new float[header.npart[4]];        
     memcpy(age,_age,sizeof(float)*_n);
   }
   bits |= AGE_BIT;
   return 1;
 }
 //// ============================================================================
//// saveDataMPV:                                                            
// int CSnapshotGadgetOut::saveDataMPV(const int _n, const float * _m, const float * _p, const float * _v)
//{
//  npartTotal = _n;
//  return 1;
//}
// ============================================================================
// save:                                                            
int CSnapshotGadgetOut::save()
{
  int fail=0;
#if 0
  if (!(bits & HEADER_BIT)) {
    std::cerr << "No Header Bit !!\n";
    fail = 1;
  }
#endif
  if (!(bits & MASS_BIT)) {
    std::cerr << "No Mass Bit !!\n";
    //fail = 1;
  }
  if (!(bits & POS_BIT)) {
    std::cerr << "No Pos Bit !!\n";
    //fail = 1;
  }
  if (!(bits & VEL_BIT)) {
    std::cerr << "No Vel Bit !!\n";
    //fail = 1;
  }

  if (!fail) {
    npartTotal = 0;
    for (int k=0; k<6;  k++) {
      header.npartTotal[k]= header.npart[k];
      npartTotal += header.npartTotal[k];
    }
    if (verbose) std::cerr << "CSnapshotGadgetOut::save npartTotal = " << npartTotal << "\n";
    setupHeader();
    saveFile();
  }
  return 1;
}
// ============================================================================
// writeData:                                                                     
// perform Write operation on Data                                   
int CSnapshotGadgetOut::writeData(char * ptr,const size_t size_bytes,const int items)
{
  bytes_counter += (size_bytes*items);

  // Save Data to file
  out.write(ptr,size_bytes*items);
  assert(out.good());
  
  return 1;
}
// ============================================================================
// setupHeader:                                                       
void CSnapshotGadgetOut::setupHeader(bool check)
{
  bool ok=true;
  if (check) {

  }
  if (ok) {
    // we assumed that there is only ONE file
    header.num_files=1;

    // here we figure out if masses are different
    // for all the particles of a component. Accordingly
    // we fill header.mass[] array
  
    ntot_withmasses=0;
    for(int k=0;k<6;k++) { // loop an component
      if (header.npart[k] ) {
        //assert(mass[k]!=NULL);
        float mass0=0.0;
        if (mass[k]!=NULL)
          mass0=mass[k][0]; // mass 0
        bool equal=true;
        // loop on all masses of the currentcomponent
        for(int n=0;(n<header.npart[k])&&equal;n++) {
          int pindex=n;
          assert(pindex<npartTotal);
//          if (pindex>npartTotal) {
//            std::cerr << "pindex :"<<pindex<<" "<< npartTotal <<"\n";
//          }

          if (mass[k]!=NULL && mass0 != mass[k][pindex]) { // mass differ !
            equal=false;
          }
        }
        if (equal) { // same masses for the component
          if (verbose) std::cerr <<"CSnapshotGadgetOut::setupHeader => same Mass["<<k<<"]="<<mass0<<"\n";
          header.mass[k] = mass0;
        } else {
          header.mass[k] = 0.0;
          ntot_withmasses+=header.npart[k];
        }
        //std::cerr << "index before ="<< index << "\n";
        //index += header.npart[k]; // next index in mass array
        //std::cerr << "index after  ="<< index << "\n";
      }
    }
  }
}
// ============================================================================
// saveFile():                                                       
void CSnapshotGadgetOut::saveFile()
{
  out.clear();
  out.open(simname.c_str(),std::ios::out | std::ios::binary);
  if (! out.is_open()) {
    std::cerr << "Unable to open file ["<<simname<<"]for writing\n"
	      << "aborting....\n";
    std::exit(1);
  }
  writeHeader();
  write();
  out.close();
}
// ============================================================================
// writeHeader():                                                               
// write gadget header structure                                                
// return values : 0 success, >0 not a Gadget header data                      
int CSnapshotGadgetOut::writeHeader()
{
  int status=0;
//  for (int i=0;i<6;i++) {
//    std::cerr << "header.npart["<<i<<"]="<<header.npart[i]<<"\n";
//    std::cerr << "header.mass ["<<i<<"]="<<header.mass [i]<<"\n";
//  }
    // Header block
  writeBlockName("HEAD",sizeof(t_io_header_1));
  bytes_counter=0;
  writeFRecord(sizeof(t_io_header_1));
  writeData((char *)  header.npart         , sizeof(int   ),  6);
  writeData((char *)  header.mass          , sizeof(double),  6);
  writeData((char *) &header.time          , sizeof(double),  1);
  writeData((char *) &header.redshift      , sizeof(double),  1);
  writeData((char *) &header.flag_sfr      , sizeof(int   ),  1);
  writeData((char *) &header.flag_feedback , sizeof(int   ),  1);
  writeData((char *)  header.npartTotal    , sizeof(int   ),  6);
  writeData((char *) &header.flag_cooling  , sizeof(int   ),  1);
  writeData((char *) &header.num_files     , sizeof(int   ),  1);
  writeData((char *) &header.BoxSize       , sizeof(double),  1);
  writeData((char *) &header.Omega0        , sizeof(double),  1);
  writeData((char *) &header.OmegaLambda   , sizeof(double),  1);
  writeData((char *) &header.HubbleParam   , sizeof(double),  1);
  writeData((char *)  header.fill          , sizeof(char  ), 96);
  writeFRecord(sizeof(t_io_header_1));

  //std::cerr << "len1="<<len1<< " len2="<<len2<< " bytes_counter="<<bytes_counter<<"\n";
  if (out.bad() )
    status = 2;
  return status;
}
// ============================================================================
// write():                                                               
// write gadget data
int CSnapshotGadgetOut::write()
{
  int blk;
  // POS
  if (bits & POS_BIT) {
    blk=sizeof(float)*3*npartTotal;
    writeBlockName("POS ",blk);
    writeFRecord(blk);
    for(int k=0;k<6;k++) {
      if (header.npart[k]) { // pos exist for the component
        assert(pos[k]!=NULL);
        writeData((char *) pos[k], sizeof(float)*3, header.npart[k]);
      }
    }
    writeFRecord(blk);
  }
  // VEL
  if (bits & VEL_BIT) {
    blk=sizeof(float)*3*npartTotal;
    writeBlockName("VEL ",blk);
    writeFRecord(blk);
    for(int k=0;k<6;k++)
      if (header.npart[k]) // vel exist for the component
        writeData((char *) vel[k], sizeof(float)*3, header.npart[k]);
    writeFRecord(blk);
  }
  // ID
  blk=sizeof(int)*npartTotal;
  writeBlockName("ID  ",blk);
  writeFRecord(blk);
  
  if (!(bits & ID_BIT)) {
    std::cerr << "No Ids Bit set, I am going to create them for you....\n";
    int * iid;
    iid = new int[npartTotal];

    for (int i=0; i<npartTotal; i++) iid[i]=i;
    writeData((char *) iid, sizeof(int), npartTotal);
    delete [] iid;
  } else { // There are IDs
    for(int k=0;k<6;k++)
      if (header.npart[k]) // id exist for the component
        writeData((char *) id[k], sizeof(int), header.npart[k]);
  }
  writeFRecord(blk);

  // MASS
  if (ntot_withmasses >0 ) {
    blk=sizeof(float)*ntot_withmasses;
    writeBlockName("MASS",blk);
    if (verbose) std::cerr << "CSnapshotGadgetOut::write => ntotwithmass="<<ntot_withmasses<<"\n";
    writeFRecord(blk);
    for(int k=0;k<6;k++)
      if (header.npart[k] && header.mass[k]==0) // mass exist for the component
        writeData((char *) mass[k], sizeof(float), header.npart[k]);
    writeFRecord(blk);
jclamber's avatar
jclamber committed
2107
  }  
jcl's avatar
jcl committed
2108 2109 2110 2111 2112 2113 2114 2115
  // U
  if (bits & U_BIT) {
    assert(header.npart[0]>0);
    blk=sizeof(float)*header.npart[0];
    writeBlockName("U   ",blk);
    writeFRecord(blk);
    writeData((char *) intenerg, sizeof(float), header.npart[0]);
    writeFRecord(blk);
jclamber's avatar
jclamber committed
2116