Exemple #1
0
bool CNSVariable::SetPrimVar_Compressible(double eddy_visc, double turb_ke, CFluidModel *FluidModel) {
	unsigned short iVar;
  bool check_dens = false, check_press = false, check_sos = false, check_temp = false, RightVol = true;
  
  
  SetVelocity();   // Computes velocity and velocity^2
  double density = GetDensity();
  double staticEnergy = GetEnergy()-0.5*Velocity2 - turb_ke;

  /* check will be moved inside fluid model plus error description strings*/
  FluidModel->SetTDState_rhoe(density, staticEnergy);

  check_dens = SetDensity();
  check_press = SetPressure(FluidModel->GetPressure());
  check_sos = SetSoundSpeed(FluidModel->GetSoundSpeed2());
  check_temp = SetTemperature(FluidModel->GetTemperature());
  
  /*--- Check that the solution has a physical meaning ---*/
  
  if (check_dens || check_press || check_sos || check_temp) {
    
    /*--- Copy the old solution ---*/
    
    for (iVar = 0; iVar < nVar; iVar++)
      Solution[iVar] = Solution_Old[iVar];
    
    /*--- Recompute the primitive variables ---*/
    
    SetVelocity();   // Computes velocity and velocity^2
	double density = GetDensity();
	double staticEnergy = GetEnergy()-0.5*Velocity2 - turb_ke;
	/* check will be moved inside fluid model plus error description strings*/
	FluidModel->SetTDState_rhoe(density, staticEnergy);

	check_dens = SetDensity();
	check_press = SetPressure(FluidModel->GetPressure());
	check_sos = SetSoundSpeed(FluidModel->GetSoundSpeed2());
	check_temp = SetTemperature(FluidModel->GetTemperature());
    
    RightVol = false;
    
  }
  
  /*--- Set enthalpy ---*/
  
	SetEnthalpy();                                  // Requires pressure computation.
  
  /*--- Set laminar viscosity ---*/
  
	SetLaminarViscosity(FluidModel->GetLaminarViscosity(FluidModel->GetTemperature(), GetDensity()));
  
  /*--- Set eddy viscosity ---*/
  
  SetEddyViscosity(eddy_visc);
  
  return RightVol;
  
}
Exemple #2
0
bool CNSVariable::SetPrimVar_Compressible(double eddy_visc, double turb_ke, CConfig *config) {
	unsigned short iVar;
  bool check_dens = false, check_press = false, check_sos = false, check_temp = false, RightVol = true;
  
  double Gas_Constant = config->GetGas_ConstantND();
	double Gamma = config->GetGamma();
  
  SetVelocity();                                  // Computes velocity and velocity^2
  check_dens = SetDensity();                      // Check the density
	check_press = SetPressure(Gamma, turb_ke);      // Requires velocity2 computation.
	check_sos = SetSoundSpeed(Gamma);               // Requires pressure computation.
	check_temp = SetTemperature(Gas_Constant);      // Requires pressure computation.
  
  /*--- Check that the solution has a physical meaning ---*/
  
  if (check_dens || check_press || check_sos || check_temp) {
    
    /*--- Copy the old solution ---*/
    
    for (iVar = 0; iVar < nVar; iVar++)
      Solution[iVar] = Solution_Old[iVar];
    
    /*--- Recompute the primitive variables ---*/
    
    SetVelocity();
    check_dens = SetDensity();
    check_press = SetPressure(Gamma, turb_ke);
    check_sos = SetSoundSpeed(Gamma);
    check_temp = SetTemperature(Gas_Constant);
    
    RightVol = false;
    
  }
  
  /*--- Set enthalpy ---*/
  
	SetEnthalpy();                                  // Requires pressure computation.
  
  /*--- Set laminar viscosity ---*/
  
	SetLaminarViscosity(config);                    // Requires temperature computation.
  
  /*--- Set eddy viscosity ---*/
  
  SetEddyViscosity(eddy_visc);
  
  return RightVol;
  
}
/* * Open the netcdf file, read all dimension and variable IDs, close.
  * Return the number of frames in the file. 
  */
int Traj_AmberNetcdf::setupTrajin(std::string const& fname, Topology* trajParm)
{
  filename_.SetFileNameWithExpansion( fname );
  if (openTrajin()) return TRAJIN_ERR;

  // Sanity check - Make sure this is a Netcdf trajectory
  if ( GetNetcdfConventions() != NC_AMBERTRAJ ) {
    mprinterr("Error: Netcdf file %s conventions do not include \"AMBER\"\n",filename_.base());
    return TRAJIN_ERR;
  }
  // Get global attributes
  std::string attrText = GetAttrText("ConventionVersion");
  if ( attrText != "1.0") 
    mprintf("Warning: Netcdf file %s has ConventionVersion that is not 1.0 (%s)\n",
            filename_.base(), attrText.c_str());
  // Get title
  SetTitle( GetAttrText("title") );
  // Get Frame info
  if ( SetupFrame()!=0 ) return TRAJIN_ERR;
  // Setup Coordinates/Velocities
  if ( SetupCoordsVelo()!=0 ) return TRAJIN_ERR;
  SetVelocity( HasVelocities() );
  // Check that specified number of atoms matches expected number.
  if (Ncatom() != trajParm->Natom()) {
    mprinterr("Error: Number of atoms in NetCDF file %s (%i) does not\n",
              filename_.base(),Ncatom());
    mprinterr("       match number in associated parmtop (%i)!\n",trajParm->Natom());
    return TRAJIN_ERR;
  }
  // Setup Time
  if ( SetupTime()!=0 ) return TRAJIN_ERR;
  // Box info
  double boxcrd[6];
  if (SetupBox(boxcrd, NC_AMBERTRAJ) == 1) // 1 indicates an error
    return TRAJIN_ERR;
  SetBox( boxcrd );
  // Replica Temperatures - Allowed to fail silently
  if (SetupTemperature() == 0)
    SetTemperature( true );
  // Replica Dimensions
  if ( SetupMultiD() == -1 ) return TRAJIN_ERR;
  // NOTE: TO BE ADDED
  // labelDID;
  //int cell_spatialDID, cell_angularDID;
  //int spatialVID, cell_spatialVID, cell_angularVID;
  // Amber Netcdf coords are float. Allocate a float array for converting
  // float to/from double.
  if (Coord_ != 0) delete[] Coord_;
  Coord_ = new float[ Ncatom3() ];
  if (Veloc_ != 0) delete[] Veloc_;
  if (velocityVID_ != -1) 
    Veloc_ = new float[ Ncatom3() ];
  else
    Veloc_ = 0;
  if (debug_>1) NetcdfDebug();
  closeTraj();
  // NetCDF files are always seekable
  SetSeekable( true );
  return Ncframe();
}
Exemple #4
0
MPMBase::MPMBase(int elem,int theMatl,double angin)
{
    int i;

    inElem=elem;
    mp=-1.;						// calculated in PreliminaryCalcs, unless set in input file
    matnum=theMatl;
    SetAnglez0InDegrees(angin);
    SetAngley0InDegrees(0.0);
    SetAnglex0InDegrees(0.0);

    // space to hold velocity fields
    // these only change if there are cracks
    vfld = (char *)malloc(maxShapeNodes*sizeof(char));
    for(i=1; i<maxShapeNodes; i++)
        vfld[i]=NO_CRACK;

    // zero stresses and strains
    ZeroTensor(&sp);
    pressure = 0.;
    ZeroTensor(&ep);
    ZeroTensor(&eplast);
    ZeroTensorAntisym(&wrot);
    ZeroVector(&acc);

    // zero energies
    plastEnergy=0.;
    dispEnergy=0.;
    workEnergy=0.;
    resEnergy=0.;
    heatEnergy=0.;
    entropy=0;

    // for J integral if needed (on non-rigid only)
    velGrad=NULL;

    // material data is needed
    matData=NULL;

    // concentration (c units) and gradient (c units/mm)
    pConcentration=0.;
    pDiffusion=NULL;

    // temperature (degrees) and gradient (degrees/mm)
    SetTemperature(0.,0.);
    pTemp=NULL;

    // CPDI data
    cpdi = NULL;
    faceArea = NULL;

    // PS - when point created, velocity and position and ext force should be set too
    ZeroVector(&vel);

    // counts crossing and sign is whether or not left the grid
    elementCrossings=0;

    // rotation matrix (when tracked)
    Rtot = NULL;
}
Exemple #5
0
void
init_clara()
{
  at_32 n,handle;
  C(GetAvailableCameras(&n));
  C(GetCameraHandle(n-1,&handle));
  C(SetCurrentCamera(handle));
  C(Initialize("/usr/local/etc/andor"));
  // C(SetTriggerMode(1 /*external*/));
  C(SetTriggerMode(0 /*internal*/));
  C(SetExposureTime(.001));
  C(SetReadMode(4 /*image*/));
  C(SetAcquisitionMode(1 /*single scan*/));
  C(CoolerON());
  C(SetADChannel(1 /*fast*/));
  C(SetFastExtTrigger(1));
  C(SetFrameTransferMode(1));
  int h=512, w=512;
  clara_h=h;
  clara_w=w;
  //C(SetIsolatedCropMode(1,h,w,1,1));
  C(SetImage(1,1,1,w,1,h));
  C(GetSizeOfCircularBuffer(&clara_circ_buf_size));
  clara_buf=malloc(sizeof(*clara_buf)*
		   h*w*clara_circ_buf_size);
  if(!clara_buf)
    printf("can't allocate memory for pictures\n");
  //C(SetAcquisitionMode(5 /*run till abort*/));
  C(SetTemperature(-15));
}
void ANDOR885_Camera::setCoolerStat(int stat) throw(std::exception)
{
	int errorValue;

	if (stat == ANDOR_ON) {
		if (coolerStat != ANDOR_ON) {
			errorValue = SetTemperature(coolerSetpt);
			throwError(errorValue, "Error setting cooler temperature");
			
			errorValue = CoolerON();
			throwError(errorValue, "Error turning on cooler");
			
			coolerStat = ANDOR_ON;
		}
	} 
	else if (stat == ANDOR_OFF) {
		if (coolerStat != ANDOR_OFF) {
			errorValue = CoolerOFF();
			throwError(errorValue, "Error turning off cooler");
			
			coolerStat = ANDOR_OFF;
		}
	}
	else {
		throw ANDOR885_Exception("Unrecognized Cooler Status requested");
	}
}
// Traj_AmberCoord::processWriteArgs()
int Traj_AmberCoord::processWriteArgs(ArgList& argIn) {
  SetTemperature( argIn.hasKey("remdtraj") );
  if (argIn.hasKey("highprecision")) { 
    outfmt_ = "%8.6lf";
    highPrecision_ = true;
  }
  return 0;
}
// Traj_AmberRestartNC::processWriteArgs()
int Traj_AmberRestartNC::processWriteArgs(ArgList& argIn) {
  // For write, assume we want velocities unless specified
  SetVelocity(!argIn.hasKey("novelocity"));
  SetTemperature(argIn.hasKey("remdtraj"));
  time0_ = argIn.getKeyDouble("time0", 1.0);
  dt_ = argIn.getKeyDouble("dt",1.0);
  return 0;
}
Exemple #9
0
void FGTank::ResetToIC(void)
{
  SetTemperature( InitialTemperature );
  SetStandpipe ( InitialStandpipe );
  SetContents ( InitialContents );
  PctFull = 100.0*Contents/Capacity;
  SetPriority( InitialPriority );
  CalculateInertias();
}
Exemple #10
0
void FGTank::ResetToIC(void)
{
  SetTemperature( InitialTemperature );
  SetStandpipe ( InitialStandpipe );
  SetContents ( InitialContents );
  PctFull = 100.0*Contents/Capacity;
  SetPriority( InitialPriority );
  PreviousUsed = 0.0;
}
bool ANDOR885_Camera::deviceExit()
{
	int errorValue;
	bool error = false;
	int temp;

	//Stop Acquisition; ignore errors
	AbortIfAcquiring();

    //CloseShutter
	shutterMode = SHUTTERMODE_CLOSE;
	errorValue = SetShutter(ttl,shutterMode,closeTime,openTime);
	printError(errorValue, "Shutter error", &error, ANDOR_ERROR);

	int i = -1;
	errorValue = IsCoolerOn(&i);
	printError(errorValue, "Error determing cooler status", &error, ANDOR_ERROR);
	if (!error) {
		if (i == 1) {
			GetTemperature(&temp);
			if(temp < 5) {
				coolerSetpt = 10;
			}
			errorValue = SetTemperature(coolerSetpt);
			printError(errorValue, "Error setting cooler temperature", &error, ANDOR_ERROR);
		}

		if (!error) {
			GetTemperature(&temp);
			while(temp < 5) {
				std::cerr << "Camera temperature rising...: " << temp << " deg C" << std::endl;
				Sleep(2000);
				GetTemperature(&temp);
			}
		}

		if (i == 1){
			errorValue=CoolerOFF();        // Switch off cooler (if used)
			printError(errorValue, "Error switching cooler off", &error, ANDOR_ERROR);
			if (!error) {
				coolerStat = ANDOR_OFF;
			}
		}

	}

	errorValue = ShutDown();
	printError(errorValue, "Error shutting down", &error, ANDOR_ERROR);

	std::cerr << "Shutting down..." << std::endl;

	initialized = false;
	return error;
}
void ANDOR885_Camera::setCoolerSetpt(int setpt) throw(std::exception)
{
	int errorValue;

	if (setpt > maxTemp || setpt < minTemp) {
		throw ANDOR885_Exception("Chosen temperature out of range.\n Temperature must be between " 
			+ STI::Utils::valueToString(minTemp) + " and " + STI::Utils::valueToString(maxTemp));
	}

	errorValue = SetTemperature(coolerSetpt);
	throwError(errorValue, "Error setting cooler temperature");
		
	coolerSetpt = setpt;
}
Exemple #13
0
void
uninit_clara()
{
  C(SetTemperature(temp_shutoff));
  float t;
  GetTemperatureF(&t);
  while(fabsf(temp_shutoff-t)>5){
    printf("temperature is %f should be %d\n",
	   t,temp_shutoff);
    GetTemperatureF(&t);
    sleep(5);
  }
  C(ShutDown()); 
}
Exemple #14
0
vector<double> const& tWeightUpdateGradient::UpdateWeights(double newtemp,vector<double> const& gradient)
{
  //  cerr << "Updating weight for gradient\n";
  // make sure we got all the gradients
  assert(gradient.size()==OrigWeights().size());

  cerr << "new temp = "<<newtemp<<endl;
  SetTemperature(newtemp);
  if ( newtemp == 0.0 )
    return CurrentWeights();

  vector<double>& prevWeights = PrevWeights();
  vector<double> const& origWeights = OrigWeights();
  double beta = _origDamping/newtemp;
  double gamma = _prevDamping/newtemp;
  double sfact = 1.0/(beta+gamma);
  double bfact = beta*sfact;
  double gfact = gamma*sfact;
  double origsum = 0.0;
  double maxw = -HUGE_VAL;
  // go over the instances and update new weights
  int i;
  for ( i=0 ; i<prevWeights.size() ; i++ ) {
    origsum += origWeights[i];
    double weight = bfact*log(origWeights[i]) + gfact*log(prevWeights[i]) - sfact*_lRate*gradient[i];
    prevWeights[i] = weight;
    if ( weight > maxw )
	  maxw = weight;
  }
  // normalize
  double wsum = 0.0;
  for ( i=0 ; i<prevWeights.size() ; i++ ) {
    prevWeights[i] -= maxw;
    prevWeights[i] = exp(prevWeights[i]);
    if ( prevWeights[i] < TINY )
      prevWeights[i] = TINY;
    wsum += prevWeights[i];
  }
  double f = origsum / wsum;
  for ( i=0 ; i<prevWeights.size() ; i++ ) {
    prevWeights[i] *= f;
    cerr << "Weight " << i << "=" << prevWeights[i] << "("<<gradient[i]<<")"<<endl;
  }

  return CurrentWeights();
}
/** Set up netcdf restart file for reading, get all variable and dimension IDs. 
  * Also check number of atoms against associated parmtop.
  */
int Traj_AmberRestartNC::setupTrajin(std::string const& fname, Topology* trajParm)
{
  filename_.SetFileNameWithExpansion( fname );
  if (openTrajin()) return TRAJIN_ERR;
  // Sanity check - Make sure this is a Netcdf restart
  if ( GetNetcdfConventions() != NC_AMBERRESTART ) {
    mprinterr("Error: Netcdf restart file %s conventions do not include \"AMBERRESTART\"\n",
              filename_.base());
    return TRAJIN_ERR;
  }
  // Get global attributes
  std::string attrText = GetAttrText("ConventionVersion");
  if (attrText!="1.0")
    mprintf("Warning: Netcdf restart file %s has ConventionVersion that is not 1.0 (%s)\n",
            filename_.base(), attrText.c_str());
  // Get title
  SetTitle( GetAttrText("title") );
  // Setup Coordinates/Velocities
  if ( SetupCoordsVelo()!=0 ) return TRAJIN_ERR;
  SetVelocity( HasVelocities() );
  // Check that specified number of atoms matches expected number.
  if (Ncatom() != trajParm->Natom()) {
    mprinterr("Error: Number of atoms in NetCDF restart file %s (%i) does not\n",
              filename_.base(), Ncatom());
    mprinterr("       match number in associated parmtop (%i)!\n",trajParm->Natom());
    return TRAJIN_ERR;
  }
  // Setup Time
  if ( SetupTime()!=0 ) return TRAJIN_ERR;
  // Box info
  double boxcrd[6];
  if (SetupBox(boxcrd, NC_AMBERRESTART) == 1) // 1 indicates an error
    return TRAJIN_ERR;
  SetBox( boxcrd );
  // Replica Temperatures - allowed to fail silently 
  if (SetupTemperature() == 0)
    SetTemperature( true );
  if ( SetupMultiD() == -1 ) return TRAJIN_ERR;
  // NOTE: TO BE ADDED
  // labelDID;
  //int cell_spatialDID, cell_angularDID;
  //int spatialVID, cell_spatialVID, cell_angularVID;
  closeTraj();
  // Only 1 frame for NC restarts
  return 1;
}
Exemple #16
0
vector<double> const& tWeightUpdateRandom::UpdateWeights(double newtemp,vector<double> const& gradient)
{
  //  cerr << "Updating weight for random\n";
  SetTemperature(newtemp);
  if ( newtemp == 0.0 )
    return CurrentWeights();

  vector<double>& prevWeights = PrevWeights();
  vector<double> const& origWeights = OrigWeights();
  //mn130103  double scale = sqrt(newtemp);
  double var = 1.0/newtemp;
  double wsum = 0.0;
  double origsum = 0.0;
  int i;
  // go over the instances and update new weights
  for ( i=0 ; i<prevWeights.size() ; i++ ) {
    //mn130103    double noise = 0.0;
    double weight = 0.0;
    // sampling is according to original weight
    // This assumes original weights are whole numbers!!!
    for ( int w=1 ; w <= origWeights[i] ; w++ )
	weight += _RandomProbGenerator.SampleGamma(var) * newtemp;
    if ( weight < TINY )
      weight = TINY;
    prevWeights[i] = weight;
    origsum += origWeights[i];
    wsum += weight;
  }
  // normalize
  double fact = origsum / wsum;
  for ( i=0 ; i<prevWeights.size() ; i++ ) {
    prevWeights[i] *= fact;
    //    cerr << "Weight " << i << "=" << prevWeights[i] << endl;
  }

  return CurrentWeights();
}
Exemple #17
0
bool ATIKCCD::ISNewSwitch(const char *dev, const char *name, ISState *states, char *names[], int n)
{
    if (dev != nullptr && !strcmp(dev, getDeviceName()))
    {
        // Gain/Offset Presets
        if (!strcmp(name, ControlPresetsSP.name))
        {
            int prevIndex = IUFindOnSwitchIndex(&ControlPresetsSP);
            IUUpdateSwitch(&ControlPresetsSP, states, names, n);
            int targetIndex = IUFindOnSwitchIndex(&ControlPresetsSP);
            uint16_t value = static_cast<uint16_t>(targetIndex + 2);
            uint8_t *data = reinterpret_cast<uint8_t*>(&value);
            int rc = ArtemisCameraSpecificOptionSetData(hCam, ID_AtikHorizonGOPresetMode, data, 2);
            if (rc != ARTEMIS_OK)
            {
                ControlPresetsSP.s = IPS_ALERT;
                IUResetSwitch(&ControlPresetsSP);
                ControlPresetsS[prevIndex].s = ISS_ON;
            }
            else
                ControlPresetsSP.s = IPS_OK;

            IDSetSwitch(&ControlPresetsSP, nullptr);
            return true;
        }

        // Cooler controler
        if (!strcmp(name, CoolerSP.name))
        {
            if (IUUpdateSwitch(&CoolerSP, states, names, n) < 0)
            {
                CoolerSP.s = IPS_ALERT;
                IDSetSwitch(&CoolerSP, nullptr);
                return true;
            }

            bool enabled = (CoolerS[COOLER_ON].s == ISS_ON);

            // If user turns on cooler, but the requested temperature is higher than current temperature
            // then we set temperature to zero degrees. If that was still higher than current temperature
            // we return an error
            if (enabled && TemperatureRequest > TemperatureN[0].value)
            {
                TemperatureRequest = 0;
                // If current temperature is still lower than zero, then we shouldn't risk
                // setting temperature to any arbitrary value. Instead, we report an error and ask
                // user to explicitly set the requested temperature.
                if (TemperatureRequest > TemperatureN[0].value)
                {
                    CoolerS[COOLER_ON].s = ISS_OFF;
                    CoolerS[COOLER_OFF].s = ISS_OFF;
                    CoolerSP.s = IPS_ALERT;
                    LOGF_WARN("Cannot manually activate cooler since current temperature is %.2f. To activate cooler, request a lower temperature.", TemperatureN[0].value);
                    IDSetSwitch(&CoolerSP, nullptr);
                    return true;
                }

                SetTemperature(0);
                return true;
            }

            return activateCooler(enabled);
        }
    }

    return INDI::CCD::ISNewSwitch(dev, name, states, names, n);
}
// Traj_AmberNetcdf::processWriteArgs()
int Traj_AmberNetcdf::processWriteArgs(ArgList& argIn) {
  SetTemperature(argIn.hasKey("remdtraj"));
  SetVelocity(argIn.hasKey("velo"));
  return 0;
}
Exemple #19
0
KVHarpeeIC::KVHarpeeIC(UInt_t number, Float_t pressure, Float_t temp, Float_t thick) : KVVAMOSDetector(number, "C4H10")
{
   // Make the ionisation chamber of Harpee composed by:
   // - one 1.5 mylar window;
   // - 3 volumes of C4H10 with thicknesses (2*dz): 2.068 cm, thick, 1.278 cm.
   //   By default thick=10.457 cm;
   //   Only the 2nd gaz volume is "active".
   //
   // The width (2*dx) of this detector is ??? and the height (2*dy) is ???.
   // The ionisation chamber is closed with the silicon wall in Harpee.
   //
   // Input: pressure - pressure of the gaz in mbar
   //        temp     - temperature of the gaz in degrees celsius.
   //                   Default temperature = 19°C
   //        thick    - the thickness in cm of the 2nd volume of gaz.
   Warning("KVHarpeeIC", "Check if the width, the height and the thickness are correct in this constructor");

   init();
   SetType("CHI");
   SetLabel("CHI");
   SetName(GetArrayName());

   // number of absorber
   Int_t Nabs = 4;

   // material of each absorber
   const Char_t* mat[] = {"Myl", "C4H10", "C4H10", "C4H10"};

   // thickness of each absorber
   Float_t th[] = {
      static_cast<Float_t>(1.5 * KVUnits::um),
      static_cast<Float_t>(2.068 * KVUnits::cm),
      static_cast<Float_t>(thick * KVUnits::cm),
      static_cast<Float_t>(1.278 * KVUnits::cm)
   };

   // active absorber flag
   Bool_t  active[] = { kFALSE, kFALSE, kTRUE, kFALSE};

   // width and height of the detector. TO BE VERIFIED
   Float_t w = 40 * KVUnits::cm;
   Float_t h = 12 * KVUnits::cm;

   // total thickness of the detector
   Float_t wtot = 0;
   for (Int_t i = 0; i < Nabs; i++) wtot += th[i];

   // pressure and temperature of the detector
   SetPressure(pressure * KVUnits::mbar);
   SetTemperature(temp);

   // Adding the absorbers
   TGeoShape* shape = NULL;
   for (Int_t i = 0; i < Nabs; i++) {

      Double_t dx = w / 2;
      Double_t dy = h / 2;
      Double_t dz = th[i] / 2;

      fTotThick += th[i];

      // box shape of the absorber
      shape  = new TGeoBBox(dx, dy, dz);

      // build and position absorber in mother volume.
      // Reference is the center of absorber
      Double_t ztrans = dz - wtot / 2;
      for (Int_t j = 0; j < Nabs - 1; j++) ztrans += (j < i) * th[j];
      TGeoTranslation* tr = new TGeoTranslation(0., 0., ztrans);
      AddAbsorber(mat[i], shape, tr, active[i]);
   }
}
void FGStandardAtmosphere::SetTemperatureSL(double t, eTemperature unit)
{
  SetTemperature(t, 0.0, unit);
}
// Traj_AmberCoord::setupTrajin()
int Traj_AmberCoord::setupTrajin(std::string const& fname, Topology* trajParm)
{
  // Set up file for reading 
  if (file_.SetupRead( fname, debug_ )) return TRAJIN_ERR;
  // Attempt to open the file. Read and set the title and titleSize
  if ( file_.OpenFile() ) return TRAJIN_ERR;
  std::string title = file_.GetLine();
  // Allocate mem to read in frame (plus REMD header if present). REMD
  // header is checked for when file is IDd. Title size is used in seeking. 
  natom3_ = trajParm->Natom() * 3;
  file_.SetupFrameBuffer( natom3_, 8, 10, hasREMD_, title.size() );
  if (debug_ > 0) {
    mprintf("Each frame is %u bytes", file_.FrameSize());
    if (hasREMD_ != 0) mprintf(" (including REMD header)");
    mprintf(".\n");
  }
  // Read the first frame of coordinates
  if ( file_.ReadFrame() == -1 ) {
    mprinterr("Error in read of Coords frame 1 of trajectory %s.\n", file_.Filename().base());
    return TRAJIN_ERR;
  }
  // Check for box coordinates. If present, update the frame size and
  // reallocate the frame buffer.
  Box boxInfo;
  std::string nextLine = file_.GetLine();
  if ( !nextLine.empty() ) {
    if (debug_>0) rprintf("DEBUG: Line after first frame: (%s)\n", nextLine.c_str());
    if ( IsRemdHeader(nextLine.c_str()) ) {
      // REMD header - no box coords
      numBoxCoords_ = 0;
    } else {
      double box[8];
      numBoxCoords_ = sscanf(nextLine.c_str(), "%8lf%8lf%8lf%8lf%8lf%8lf%8lf%8lf",
                             box, box+1, box+2, box+3, box+4, box+5, box+6, box+7);
      if (numBoxCoords_ == -1) {
        mprinterr("Error: Could not read Box coord line of trajectory %s.",file_.Filename().base());
        return TRAJIN_ERR;
      } else if (numBoxCoords_ == 8) {
        // Full line of coords was read, no box coords.
        numBoxCoords_ = 0;
      } else if (numBoxCoords_ == 3) {
        // Box lengths only, ortho. or truncated oct. Use default parm angles.
        box[3] = boxAngle_[0] = trajParm->ParmBox().Alpha();
        box[4] = boxAngle_[1] = trajParm->ParmBox().Beta();
        box[5] = boxAngle_[2] = trajParm->ParmBox().Gamma();
        boxInfo.SetBox( box );
      } else if (numBoxCoords_ == 6) {
        // General triclinic. Set lengths and angles.
        boxInfo.SetBox( box );
      } else {
        mprinterr("Error: Expect only 3 or 6 box coords, got %i\n", numBoxCoords_);
        mprinterr("Error: Box line=[%s]\n", nextLine.c_str());
        return TRAJIN_ERR;
      }
    }
    // Reallocate frame buffer accordingly
    file_.ResizeBuffer( numBoxCoords_ );
  }
  // Calculate Frames and determine seekable. If not possible and this is not a
  // compressed file the trajectory is probably corrupted. Frames will
  // be read until EOF.
  int Frames = 0;
  if (debug_>0)
    rprintf("Title offset=%lu FrameSize=%lu UncompressedFileSize=%lu\n",
            title.size(), file_.FrameSize(), file_.UncompressedSize());
  off_t title_size = (off_t) title.size();
  off_t frame_size = (off_t) file_.FrameSize();
  off_t uncompressed_size = file_.UncompressedSize();
  off_t file_size = uncompressed_size - title_size;
  bool seekable = false;
  if (file_.Compression() != CpptrajFile::NO_COMPRESSION) {
    // -----==== AMBER TRAJ COMPRESSED ====------
    // If the uncompressed size of compressed file is reported as <= 0,
    // uncompressed size cannot be determined. Read coordinates until
    // EOF.
    if (uncompressed_size <= 0) {
      mprintf("Warning: %s: Uncompressed size of trajectory could not be determined.\n",
              file_.Filename().base());
      if (file_.Compression() == CpptrajFile::BZIP2)
        mprintf("         (This is normal for bzipped files)\n");
      mprintf("         Number of frames could not be calculated.\n");
      mprintf("         Frames will be read until EOF.\n");
      Frames = TRAJIN_UNK;
      seekable = false;
    } else {
      // Frame calculation for large gzip files
      if (file_.Compression() == CpptrajFile::GZIP) {
        // Since this is gzip compressed, if the file_size % frame size != 0, 
        // it could be that the uncompressed filesize > 4GB. Since 
        //   ISIZE = uncompressed % 2^32, 
        // try ((file_size + (2^32 * i)) % frame_size) and see if any are 0.
        if ( (file_size % frame_size) != 0) {
          // Determine the maximum number of iterations to try based on the
          // fact that Amber trajectories typically compress about 3x with
          // gzip.
          off_t tmpfsize = ((file_size * 4) - uncompressed_size) / 4294967296LL;
          int maxi = (int) tmpfsize;
          ++maxi;
          if (debug_>1)
            mprintf("\tLooking for uncompressed gzip size > 4GB, %i iterations.\n",maxi);
          tmpfsize = 0;
          bool sizeFound = false;
          for (int i = 0; i < maxi; i++ ) {
            tmpfsize = (4294967296LL * i) + file_size;
            if ( (tmpfsize % frame_size) == 0) {sizeFound=true; break;}
          }
          if (sizeFound) file_size = tmpfsize;
        }
      }
      if ((file_size % frame_size) == 0) {
        Frames = (int) (file_size / frame_size);
        seekable = true;
      } else {
        mprintf("Warning: %s: Number of frames in compressed traj could not be determined.\n",
                file_.Filename().base());
        mprintf("         Frames will be read until EOF.\n");
        Frames = TRAJIN_UNK;
        seekable=false;
      }
    }
  } else {     
    // ----==== AMBER TRAJ NOT COMPRESSED ====----
    Frames = (int) (file_size / frame_size);
    if ( (file_size % frame_size) == 0 ) {
      seekable = true;
    } else {
      mprintf("Warning: %s: Could not accurately predict # frames. This usually \n",
              file_.Filename().base());
      mprintf("         indicates a corrupted trajectory. Will attempt to read %i frames.\n",
              Frames);
      seekable=false;
    }
  }

  if (debug_>0)
    rprintf("Atoms: %i FrameSize: %lu TitleSize: %lu NumBox: %i Seekable: %i Frames: %i\n\n", 
            trajParm->Natom(), frame_size, title_size, numBoxCoords_, (int)seekable, Frames);
  // Close the file
  file_.CloseFile();
  // Set trajectory info
  SetBox( boxInfo );
  SetTemperature( hasREMD_ != 0 );
  SetTitle( title );
  SetSeekable( seekable );
  return Frames;
}
//------------------------------------------------------------------------------
//	FUNCTION NAME:	InitializeCamera()
//
//  RETURNS:				If the function terminates before entering the message loop,
//      						return FALSE.
//    							Otherwise, return the WPARAM value sent by the WM_QUIT
//									message.
//
//  LAST MODIFIED:	PMcK	11/11/98
//
//  DESCRIPTION:		calls initialization function, processes message loop
//
//                  Windows recognizes this function by name as the initial
//									entry point for the program.  This function calls the
//									application initialization routine, if no other instance of
//									the program is running, and always calls the instance
//									initialization routine.  It then executes a	message
//									retrieval and dispatch loop that is the top-level control
//    							structure for the remainder of execution.  The loop is
//									terminated when a WM_QUIT  message is received, at which
//									time this function exits the application instance by
//									returning the value passed by PostQuitMessage().
//
//    							If the function must abort before entering the message loop,
//									it returns the conventional value NULL.
//
//
//	ARGUMENTS: 			hInstance - The handle to the instance of this application
//									that is currently being executed.
//
//    							hPrevInstance - The handle to the instance of this
//									application that was last executed.  If this is the only
//									instance of this application executing, hPrevInstance is
//									NULL. In Win32 applications, this parameter is always NULL.
//
//    							lpCmdLine - A pointer to a null terminated string specifying
//									the command line of the application.
//
//    							nCmdShow - Specifies how the main window is to be diplayed.
//------------------------------------------------------------------------------
bool ANDOR885_Camera::InitializeCamera()
{
	AndorCapabilities	caps;
	char 				aBuffer[256];
	int					errorValue;
	bool				errorFlag = false;
//	int 				test,test2; //need to pause while camera initializes

	float				speed, STemp, gain;
	int					iSpeed, nAD, nAmp, nPreAmp, index, IsPreAmpAvailable;

	int i;


	caps.ulSize = sizeof(AndorCapabilities);

	long numCameras;
	GetAvailableCameras(&numCameras);

    GetCurrentDirectoryA(256,aBuffer);// Look in current working directory
                                    // for driver files. Note: had to override usual mapping of GetCurrentDirectory to
									// GetCurrentDirectoryW because of mismatch of argument types.

    errorValue=Initialize(aBuffer);  // Initialize driver in current directory
	printError(errorValue, "Initialize error", &errorFlag, ANDOR_ERROR);
	if (errorFlag)
		return true;

    // Get camera capabilities
    errorValue=GetCapabilities(&caps);
	printError(errorValue, "Get Andor Capabilities information Error", &errorFlag, ANDOR_ERROR);

    // Get Head Model
    errorValue=GetHeadModel(model);
	printError(errorValue, "Get Head Model information Error", &errorFlag, ANDOR_ERROR);

    // Get detector information
    errorValue=GetDetector(&imageWidth,&imageHeight);
	printError(errorValue, "Get Detector information Error", &errorFlag, ANDOR_ERROR);

	// Set frame transfer mode
	errorValue=SetFrameTransferMode((frameTransfer == ANDOR_ON) ? 1 : 0);
	printError(errorValue, "Set Frame Transfer Mode Error", &errorFlag, ANDOR_ERROR);

    // Set acquisition mode to required setting specified in xxxxWndw.c
    errorValue=SetAcquisitionMode(acquisitionMode);
	printError(errorValue, "Set Acquisition Mode Error", &errorFlag, ANDOR_ERROR);

	
	if(caps.ulGetFunctions > 32)
	{
		GetEMCCDGain(&EMCCDGain);
	}

	if(readMode == READMODE_IMAGE) {
    	// This function only needs to be called when acquiring an image. It sets
		// the horizontal and vertical binning and the area of the image to be
		// captured. In this example it is set to 1x1 binning and is acquiring the
		// whole image
  		SetImage(1,1,1,imageWidth,1,imageHeight);
	}

    // Set read mode to required setting specified in xxxxWndw.c
    errorValue=SetReadMode(readMode);
	printError(errorValue, "Set Read Mode Error", &errorFlag, ANDOR_ERROR);

    // Set Vertical speed to max
/*    STemp = 0;
    VSnumber = 0;
    GetNumberVSSpeeds(&index);
    for(iSpeed=0; iSpeed<index; iSpeed++){
      GetVSSpeed(iSpeed, &speed);
      if(speed > STemp){
        STemp = speed;
        VSnumber = iSpeed;
      }
    }
    errorValue=SetVSSpeed(VSnumber);
	printError(errorValue, "Set Vertical Speed Error", &errorFlag, ANDOR_ERROR);
*/
	
	if (!notDestructed){
		STemp = 0;
		GetNumberVSSpeeds(&index);
		for(iSpeed=0; iSpeed < index; iSpeed++){
			GetVSSpeed(iSpeed, &speed);
			verticalShiftSpeed_t.choices[iSpeed] = STI::Utils::valueToString(speed);
			if(speed > STemp){
				STemp = speed;
				verticalShiftSpeed = iSpeed;
			}
		}
		verticalShiftSpeed_t.initial = (--verticalShiftSpeed_t.choices.end())->second;
	}
    errorValue = SetVSSpeed(verticalShiftSpeed);
	printError(errorValue, "Set Vertical Speed Error", &errorFlag, ANDOR_ERROR);

	/* Set Vertical Clock Voltage; 
		note: only the fastest vertical shift speeds will benefit from the higher clock voltage;
			  increasing clock voltage adds noise.
	*/
	if (!notDestructed) {
		index = 0;
		errorValue = GetNumberVSAmplitudes(&index);
		if (errorValue == DRV_SUCCESS) {
			for (i = 0; i < index; i++){
				if (i == 0){
					verticalClockVoltage_t.choices[i] = "Normal";
				} else {
					verticalClockVoltage_t.choices[i] = STI::Utils::valueToString(i);
				}
			}
			verticalClockVoltage_t.initial = (verticalClockVoltage_t.choices.begin())->second;
		}
	}
	errorValue = SetVSAmplitude(0);
	printError(errorValue, "Set Vertical Clock Voltage Error", &errorFlag, ANDOR_ERROR);

    // Set Horizontal Speed to max and check bit depth
	//(scan over all possible AD channels; although, the 885 has only one 14-bit channel)
		STemp = 0;
	//    HSnumber = 0;
		ADnumber = 0;
	if (!notDestructed) {
		errorValue = GetNumberADChannels(&nAD);
		if (errorValue != DRV_SUCCESS){
		  std::cerr << "Get number AD Channel Error\n";
		  errorFlag = true;
		}
		else if (nAD != 1) {
			std::cerr << "Expect 1 AD channel for this camera. The following code will miss channels\n";
			errorFlag = true;
		}
		else {
			errorValue = GetNumberHSSpeeds(0, 0, &index);
			if(errorValue == DRV_SUCCESS){
				for (iSpeed = 0; iSpeed < index; iSpeed++) {
				  GetHSSpeed(0, 0, iSpeed, &speed);
				  horizontalShiftSpeed_t.choices[iSpeed] = STI::Utils::valueToString(speed);
				  if(speed < STemp){
					STemp = speed;
					horizontalShiftSpeed = iSpeed;
				  }
				}
				horizontalShiftSpeed_t.initial = horizontalShiftSpeed_t.choices.find(horizontalShiftSpeed)->second;
			}
			//getBitDepth
			if (DRV_SUCCESS != GetBitDepth(0, &bitDepth))
				return true;
		}

		errorValue = GetNumberAmp(&nAmp);
		printError(errorValue, "Get Number Amplifiers Error", &errorFlag, ANDOR_ERROR);

		errorValue = GetNumberPreAmpGains(&nPreAmp);
		printError(errorValue, "Get Number Preamplifiers Error", &errorFlag, ANDOR_ERROR);

		if (nAmp == 1 && nAD == 1) {
			for (i = 0; i < nPreAmp; i++) {
				errorValue = GetPreAmpGain(i, &gain);
				errorValue = IsPreAmpGainAvailable(0,0,horizontalShiftSpeed,i,&IsPreAmpAvailable);
				if (IsPreAmpAvailable == 1) {
					preAmpGain_t.choices[i] = STI::Utils::valueToString(gain);
				}
			}
			if (!preAmpGain_t.choices.empty()) {
				preAmpGain = preAmpGain_t.choices.begin()->first;
				//preAmpGainPos = 0;
				preAmpGain_t.initial = (preAmpGain_t.choices.begin())->second; // set the initial condition for the preamplifier gain
				errorValue = SetPreAmpGain(preAmpGain);
				printError(errorValue, "Set AD Channel Error", &errorFlag, ANDOR_ERROR);
			} else {
				std::cerr << "No gains available at this speed. Weird.";
				errorFlag = true;
			}
		} else {
			std::cerr << "Unexpected number of A/D's or output amps" << std::endl;
			std::cerr << "Expected A/D's:       1 \t Measured: " << nAD << std::endl;
			std::cerr << "Expected output Amps: 1 \t Measured: " << nAmp << std::endl;
			errorFlag = true;
		}
	}
	else {
		errorValue = SetPreAmpGain(preAmpGain);
		printError(errorValue, "Set AD Channel Error", &errorFlag, ANDOR_ERROR);
	}
	

    errorValue=SetADChannel(ADnumber);
	printError(errorValue, "Set AD Channel Error", &errorFlag, ANDOR_ERROR);


    errorValue=SetHSSpeed(0,horizontalShiftSpeed);
	printError(errorValue, "Set Horizontal Speed Error", &errorFlag, ANDOR_ERROR);

    if(errorFlag)
    	//MessageBox(GetActiveWindow(),aBuffer,"Error!",MB_OK); SMD
	    std::cerr<<aBuffer<<std::endl;


  // Wait for 2 seconds to allow MCD to calibrate fully before allowing an
  // acquisition to begin
//  test=GetTickCount();
//  do{
//  	test2=GetTickCount()-test;
//  }while(test2<2000);

	Sleep(2000);

	errorValue = SetExposureTime(exposureTime);
	printError(errorValue, "Exposure time error", &errorFlag, ANDOR_ERROR);

	// It is necessary to get the actual times as the system will calculate the
	// nearest possible time. eg if you set exposure time to be 0, the system
	// will use the closest value (around 0.01s)
	  GetAcquisitionTimings(&exposureTime,&accumulateTime,&kineticTime);
	  std::cerr << "Actual Exposure Time is " << exposureTime << " s.\n";

  // Set Shutter is made up of ttl level, shutter and open close time

  //Check Get open close time
	if(openTime==0)
		openTime=1;
	if(closeTime==0)
		closeTime=1;

	// Set shutter
	errorValue=SetShutter(ttl,shutterMode,closeTime,openTime);
	if(errorValue!=DRV_SUCCESS){
		std::cerr << "Shutter error\n";
		errorFlag = true;  
	}
	else
		std::cerr << "Shutter set to specifications\n";

	/*// Determine availability of trigger option and set trigger selection
	std::map<int,std::string>::iterator it;
	std::vector<int> triggerKeys;
	for (it = triggerMode_t.choices.begin(); it != triggerMode_t.choices.end(); it++)
	{
		errorValue = SetTriggerMode(it->first);
		if (errorValue != DRV_SUCCESS)
			triggerKeys.push_back(it->first);
	}
	for (int i = 0; i < triggerKeys.size(); i++)
		triggerMode_t.choices.erase(triggerKeys.at(i));

	if (triggerMode_t.choices.empty()) {
		std::cerr << "No triggerModes found" << std::endl;
		return true;
	}
	else if (triggerMode_t.choices.find(TRIGGERMODE_EXTERNAL_EXPOSURE) != 
		triggerMode_t.choices.end()) 
		triggerMode = TRIGGERMODE_EXTERNAL_EXPOSURE;
	else if (triggerMode_t.choices.find(TRIGGERMODE_EXTERNAL) != 
		triggerMode_t.choices.end())
		triggerMode = TRIGGERMODE_EXTERNAL;
	else
		triggerMode = triggerMode_t.choices.begin()->first;

	errorValue=SetTriggerMode(triggerMode);
	printError(errorValue, "Set Trigger Mode Error", &errorFlag, ANDOR_ERROR);
	triggerMode_t.initial = triggerMode_t.choices.find(triggerMode)->second;
*/

	// Determine availability of trigger option and set trigger selection
	std::map<int,std::string>::iterator it;
	std::vector<int> triggerKeys;
	for (it = triggerMode_t.choices.begin(); it != triggerMode_t.choices.end(); it++)
	{
		errorValue = SetTriggerMode(it->first);
		if (errorValue != DRV_SUCCESS)
			triggerKeys.push_back(it->first);
	}
	for (int i = 0; i < triggerKeys.size(); i++)
		triggerMode_t.choices.erase(triggerKeys.at(i));

	if (triggerMode_t.choices.empty()) {
		std::cerr << "No triggerModes found" << std::endl;
		return true;
	}
	else if (triggerMode_t.choices.find(TRIGGERMODE_EXTERNAL_EXPOSURE) != 
		triggerMode_t.choices.end()) 
		triggerMode = TRIGGERMODE_EXTERNAL_EXPOSURE;
	else if (triggerMode_t.choices.find(TRIGGERMODE_EXTERNAL) != 
		triggerMode_t.choices.end())
		triggerMode = TRIGGERMODE_EXTERNAL;
	else
		triggerMode = triggerMode_t.choices.begin()->first;

	errorValue=SetTriggerMode(triggerMode);
	printError(errorValue, "Set Trigger Mode Error", &errorFlag, ANDOR_ERROR);
	triggerMode_t.initial = triggerMode_t.choices.find(triggerMode)->second;


	errorValue = GetTemperatureRange(&minTemp, &maxTemp);
	if (errorValue != DRV_SUCCESS){
		std::cerr << "Error finding temperature range or camera is not on" << std::endl;
		errorFlag = true;
	}
	else {
		std::cerr << "Temperature must be between " << minTemp << " and " << maxTemp << std::endl;
		std::cerr << "Warning: Water cooling is required for temperatures < -58 deg C" << std::endl;

		//Set temperature
		if (coolerSetpt > maxTemp || coolerSetpt < minTemp) {
			std::cerr << "Chosen temperature out of range." << std::endl;
			if (coolerSetpt > maxTemp)
				coolerSetpt = maxTemp;
			else
				coolerSetpt = minTemp;
			std::cerr << "Resetting temp to nearest acceptable value " << std::endl;
		} 

		errorValue = SetTemperature(coolerSetpt);
		printError(errorValue, "Error setting cooler temperature", &errorFlag, ANDOR_ERROR);

		int i;
		errorValue = IsCoolerOn(&i);
		if (i == 0) {
			// if it's off and it's supposed to be on, turn it on
			if (coolerStat == ANDOR_ON) {
				std::cerr << "Turning on cooler." << std::endl;
				errorValue = CoolerON();
				printError(errorValue, "Error turning on cooler", &errorFlag, ANDOR_ERROR);
			}
			
		} else if (i == 1) {
			std::cerr << "Cooler is on." << std::endl;
			//if it's on and it's supposed to be off, turn it off
			if (coolerStat == ANDOR_OFF)
			{
				errorValue = CoolerOFF();
				printError(errorValue, "Error turning off cooler", &errorFlag, ANDOR_ERROR);
			} else {
				errorValue = GetTemperature(&i);
				switch(errorValue){
					case DRV_TEMP_STABILIZED:
						std::cerr << "Cooler temp has stabilized at " << i << " deg C" << std::endl;
						break;
					case DRV_TEMP_NOT_REACHED:
						std::cerr << "Cooler temp is " << i << " deg C" << std::endl;
						std::cerr << "Cooler setpoint has not been reached." << std::endl;
						std::cerr << "This may be because water cooling is required for setpoints < -58 deg C" << std::endl;
						std::cerr << "Either wait or try resetting cooler setpoint" << std::endl;
						break;
					case DRV_TEMP_DRIFT:
						std::cerr << "Cooler temp is " << i << " deg C" << std::endl;
						std::cerr << "Cooler temperature has drifted. Try resetting setpoint" << std::endl;
						break;
					case DRV_TEMP_NOT_STABILIZED:
						std::cerr << "Cooler temp is " << i << " deg C" << std::endl;
						std::cerr << "Temperature has been reached, but cooler has not stabilized" << std::endl;
						std::cerr << "Either wait or try resetting cooler setpoint" << std::endl;
						break;
					default:
						std::cerr << "Unrecognized error sequence. Camera may be off or acquiring" << std::endl;
						break;
				}
			}
		}
		
		
		if(!errorFlag){
			std::cerr << "Cooler temperature set to: " << coolerSetpt << std::endl;
		}
	
	}




	errorValue = SetSpool(0,0,NULL,10);  //Disable spooling
	printError(errorValue, "Spool mode error", &errorFlag, ANDOR_ERROR);

	// Returns the value from PostQuitMessage
	return errorFlag;
}