Пример #1
0
void CMainGame::Init(HWND hMainWnd)
{
	srand( GetTickCount() );

#ifndef _HACK_SHIELD_
	DIRECTORYMGR->Init();
#endif

	DIRECTORYMGR->SetLoadMode(eLM_EffectScript);
	LoadEffectFileTable("list_h_m.befl");
	LoadEffectFileTable("list_h_w.befl");
	LoadEffectFileTable("list_e_m.befl");
	LoadEffectFileTable("list_e_w.befl");
	// 090624 ONS 신규종족 이펙트 처리 추가
	LoadEffectFileTable("list_d_m.befl");
	LoadEffectFileTable("list_d_w.befl");
	DIRECTORYMGR->SetLoadMode(eLM_Root);

	m_pEngine = new CEngine;
	m_pEngine->Init(hMainWnd,&GAMERESRCMNGR->m_GameDesc.dispInfo,
		GAMERESRCMNGR->m_GameDesc.MaxShadowNum,GAMERESRCMNGR->m_GameDesc.MaxShadowTexDetail,0,
		GAMERESRCMNGR->m_GameDesc.FramePerSec);

	// 080507 LUJ, 설정 파일에서 리소스 파일 이름을 읽어들인다
	{
		char fileName[ MAX_PATH ] = { 0 };
		{
			const char* defaultFile = "data\\interface\\windows\\image_path.bin";

			strcpy( fileName, defaultFile );
		}

		FILE* file = fopen( "system\\launcher.sav", "r" );

		if( file )
		{
			char		buffer[ MAX_PATH ]	= { 0 };
			const char* separator			= " =\n";

			while( fgets( buffer, sizeof( buffer ), file ) )
			{
				const char* token = strtok( buffer, separator );

				if( 0 == token ||	// empty line
					';' == token[ 0 ] )	// comment
				{
					continue;
				}
				else if( ! strcmpi( "imagePath",  token ) )
				{
					token = strtok( 0, separator );

					if( token &&
						fopen( token, "r" ) )
					{
						strcpy( fileName, token );
					}
				}
			}
		}

		fclose( file );

		RESRCMGR->Init( fileName, FILE_IMAGE_MSG );
	}

	NETWORK->Init(hMainWnd);
	WINDOWMGR->Init();

	gHwnd = hMainWnd;
	OPTIONMGR->Init();
	OPTIONMGR->ApplySettings();
	MACROMGR->Init();
	AUDIOMGR->Initialize(
		hMainWnd);
	AUDIOMGR->PlayBGM(
		1);
	// 튜토리얼 매니져는, 사운드, npc 관련 리소스들이 모두 로딩 된 후 로딩하도록 한다. 꼭!
	TUTORIALMGR->Init();	
	MOVEPOINT->Init();
	g_UserInput.Init();
	GUILDMGR->Init();
	CHATTIPMGR->Init();
	SIEGEWARFAREMGR->Init();
	NPCRECALLMGR->Initialize();

	g_pEngineObjectCache = new CEngineObjectCache;
	g_pEngineObjectCache->Init(g_pExecutive, CEngineObjectCache::MAX_ENGINE_OBJECT_CACHE_SIZE);

	// 클라이언트도 미니덤프를 생성하도록 _DEBUG 제거. by hseos 2007.06.24 일단 서비스 용에서는 미니덤프 사용X
#ifdef _DEBUG
	MiniDumper md(MiniDumper::DUMP_LEVEL_2);
#else if _GMTOOL_
	MiniDumper md(MiniDumper::DUMP_LEVEL_0);
#endif

	BALLOONOUTLINE->InitChatBalloon();
}
Пример #2
0
// Analysis_TI::Calc_Increment()
int Analysis_TI::Calc_Increment() {
  // Determine max points if not given.
  int maxpts = avg_max_;
  if (maxpts == -1) {
    for (unsigned int idx = 0; idx != input_dsets_.size(); idx++) {
      DataSet_1D const& ds = static_cast<DataSet_1D const&>( *(input_dsets_[idx]) );
      if (maxpts == -1)
        maxpts = (int)ds.Size();
      else if (maxpts != (int)ds.Size()) {
        mprintf("Warning: # points in '%s' (%zu) is different than %i.\n",
                ds.legend(), ds.Size(), maxpts);
        maxpts = std::min( maxpts, (int)ds.Size() );
        mprintf("Warning:   Will only use %i points.\n", maxpts);
      }
    }
  }
  if (maxpts < 1) {
    mprinterr("Error: Max points to use is < 1.\n");
    return 1;
  }
  if (avg_skip_ >= maxpts) {
    mprinterr("Error: 'avgskip' (%i) > max (%i).\n", avg_skip_, maxpts);
    return 1;
  }
  // sum: Hold the results of integration for each curve (increment)
  Darray sum;
  // points: Hold point values at which each avg is being calculated
  Iarray points;
  // Loop over input data sets. 
  for (unsigned int idx = 0; idx != input_dsets_.size(); idx++) {
    DataSet_1D const& ds = static_cast<DataSet_1D const&>( *(input_dsets_[idx]) );
    if (CheckSet(ds)) return 1; 
    // Calculate averages for each increment
    Darray avg;
    Iarray increments;
    int count = 0;
    int endpt = maxpts -1;
    double currentSum = 0.0;
    if (debug_ > 0) mprintf("DEBUG: Lambda %g\n", xval_[idx]);
    for (int pt = avg_skip_; pt != maxpts; pt++)
    {
      currentSum += ds.Dval(pt);
      count++;
      if (count == avg_increment_ || pt == endpt) {
        avg.push_back( currentSum / ((double)(pt - avg_skip_ + 1)) );
        increments.push_back(pt+1);
        if (debug_ > 0)
          mprintf("DEBUG:\t\tAvg from %i to %i: %g\n", avg_skip_+1, pt+1, avg.back());
        count = 0;
      }
    }
    if (sum.empty()) {
      sum.resize(avg.size());
      points = increments;
    } else if (sum.size() != avg.size()) {
      mprinterr("Error: Different # of increments for set '%s'; got %zu, expected %zu.\n",
                ds.legend(), avg.size(), sum.size());
      return 1;
    }
    // Create increment curve data sets
    if (curve_.empty()) {
      MetaData md(dAout_->Meta().Name(), "TIcurve");
      for (unsigned int j = 0; j != avg.size(); j++) {
        md.SetIdx( increments[j] );
        DataSet* ds = masterDSL_->AddSet(DataSet::XYMESH, md);
        if (ds == 0) return Analysis::ERR;
        ds->ModifyDim(Dimension::X).SetLabel("Lambda");
        ds->SetLegend( md.Name() + "_Skip" + integerToString(increments[j]) );
        if (curveout_ != 0) curveout_->AddDataSet( ds );
        curve_.push_back( ds );
      }
    }
    for (unsigned int j = 0; j != avg.size(); j++) {
      DataSet_Mesh& CR = static_cast<DataSet_Mesh&>( *(curve_[j]) );
      CR.AddXY(xval_[idx], avg[j]);
      if (mode_ == GAUSSIAN_QUAD)
        sum[j] += (wgt_[idx] * avg[j]);
    }
  } // END loop over data sets
  if (mode_ == TRAPEZOID) Integrate_Trapezoid(sum);
  // Store final integration values
  DataSet_Mesh& DA = static_cast<DataSet_Mesh&>( *dAout_ );
  DA.ModifyDim(Dimension::X).SetLabel("Point");
  for (unsigned int j = 0; j != points.size(); j++)
    DA.AddXY(points[j], sum[j]);

  return 0;
}
Пример #3
0
// DataIO_Mdout::ReadData()
int DataIO_Mdout::ReadData(FileName const& fname,
                            DataSetList& datasetlist, std::string const& dsname)
{
  mprintf("\tReading from mdout file: %s\n", fname.full());
  BufferedLine buffer;
  if (buffer.OpenFileRead( fname )) return 1;
  const char* ptr = buffer.Line();
  if (ptr == 0) {
    mprinterr("Error: Nothing in MDOUT file: %s\n", fname.full());
    return 1;
  }
  // ----- PARSE THE INPUT SECTION ----- 
  int imin = -1;           // imin for this file
  const char* Trigger = 0; // Trigger for storing energies, must be 8 chars long.
  int frame = 0;           // Frame counter for this file
  double dt = 1.0;         // Timestep for this file (MD)
  double t0 = 0.0;         // Initial time for this file (MD)
  int ntpr = 1;            // Value of ntpr
  int irest = 0;           // Value of irest
  while ( ptr != 0 && strncmp(ptr, "   2.  CONTROL  DATA", 20) != 0 )
    ptr = buffer.Line();
  if (ptr == 0) return EOF_ERROR();
  // Determine whether this is dynamics or minimization, get dt
  ptr = buffer.Line(); // Dashes 
  ptr = buffer.Line(); // Blank 
  ptr = buffer.Line(); // title line
  while ( strncmp(ptr, "   3.  ATOMIC", 13) != 0 ) 
  {
    ArgList mdin_args( ptr, " ,=" ); // Remove commas, equal signs
    // Scan for stuff we want
    //mprintf("DEBUG:\tInput[%i] %s", mdin_args.Nargs(), mdin_args.ArgLine());
    for (int col=0; col < mdin_args.Nargs(); col += 2) {
      int col1 = col + 1;
      if (mdin_args[col] == "imin") {
        imin = convertToInteger( mdin_args[ col1 ] );
        if (debug_ > 0) mprintf("\t\tMDIN: imin is %i\n", imin);
        // Set a trigger for printing. For imin5 this is the word minimization.
        // For imin0 or imin1 this is NSTEP.
        if      (imin==0) Trigger = " NSTEP =";
        else if (imin==1) Trigger = "   NSTEP";
        else if (imin==5) Trigger = "minimiza";
        // Since imin0 and imin1 first trigger has no data, set frame 1 lower.
        if (imin==1 || imin==0) frame = -1;
      } else if (mdin_args[col] == "dt") {
        dt = convertToDouble( mdin_args[ col1 ] );
        if (debug_ > 0) mprintf("\t\tMDIN: dt is %f\n", dt);
      } else if (mdin_args[col] == "t") {
        t0 = convertToDouble( mdin_args[ col1 ] );
        if (debug_ > 0) mprintf("\t\tMDIN: t is %f\n", t0);
      } else if (mdin_args[col] == "ntpr") {
        ntpr = convertToInteger( mdin_args[ col1 ] );
        if (debug_ > 0) mprintf("\t\tMDIN: ntpr is %i\n", ntpr);
      } else if (mdin_args[col] == "irest") {
        irest = convertToInteger( mdin_args[ col1 ] );
        if (debug_ > 0) mprintf("\t\tMDIN: irest is %i\n", irest);
      }
    }
    ptr = buffer.Line();
    if (ptr == 0) return EOF_ERROR();
  }
  if (Trigger == 0) {
    mprinterr("Error: Could not determine whether MDOUT is md, min, or post-process.\n");
    return 1;
  }
  // ----- PARSE THE ATOMIC ... SECTION -----
  while ( ptr != 0 && strncmp(ptr, "   4.  RESULTS", 14) != 0 )
  {
    ptr = buffer.Line();
    // If run is a restart, set the initial time value.
    if (irest == 1) {
      if (strncmp(ptr, " begin time", 11) == 0) {
        sscanf(ptr, " begin time read from input coords = %lf", &t0);
        if (debug_ > 0) mprintf("\t\tMD restart initial time= %f\n", t0);
      }
    }
  }
  if (ptr == 0) return EOF_ERROR();
  // ----- PARSE THE RESULTS SECTION -----
  bool finalE = false;
  int nstep;
  int minStep = 0; // For imin=1 only
  if (irest == 0)
    nstep = 0;
  else
    nstep = ntpr;
  double Energy[N_FIELDTYPES];
  std::fill( Energy, Energy+N_FIELDTYPES, 0.0 );
  std::vector<bool> EnergyExists(N_FIELDTYPES, false);
  DataSetList::Darray TimeVals;
  DataSetList::DataListType inputSets(N_FIELDTYPES, 0);
  Sarray Name(2);
  double time = 0.0;
  while (ptr != 0) {
    // Check for end of imin 0 or 1 run; do not record Average and Stdevs
    if ( (imin == 1 && (strncmp(ptr, "                    FINAL", 25) == 0 ||
                        strncmp(ptr, "   5.  TIMINGS",            14) == 0   )) ||
         (imin == 0 && strncmp(ptr, "      A V", 9) == 0))
      finalE = true;
    // Check for '| TI region  2' to prevent reading duplicate energies
    if ( strncmp(ptr, "| TI region  2", 14) == 0 ) {
      while (ptr != 0 && !(ptr[0] == ' ' && ptr[1] == '-'))
        ptr = buffer.Line();
      if (ptr == 0) return EOF_ERROR();
    }
    // Record set for energy post-processing
    if (imin == 5 && strncmp(ptr, "minimizing", 10) == 0)
      nstep = atoi( ptr + 22 );
    // MAIN OUTPUT ROUTINE
    // If the trigger has been reached print output.
    // For imin0 and imin1 the first trigger will have no data.
    // If the end of the file has been reached print then exit.
    if ( strncmp(ptr, Trigger, 8) == 0 || finalE ) {
      if (frame > -1) {
        // Store all energies present.
        for (int i = 0; i < (int)N_FIELDTYPES; i++) {
          if (EnergyExists[i]) {
            if (inputSets[i] == 0) {
              MetaData md( dsname, Enames[i] );
              md.SetLegend( dsname + "_" + Enames[i] );
              inputSets[i] = new DataSet_double();
              inputSets[i]->SetMeta( md );
            }
            // Since energy terms can appear and vanish over the course of the
            // mdout file, resize if necessary.
            if (frame > (int)inputSets[i]->Size())
              ((DataSet_double*)inputSets[i])->Resize( frame );
            ((DataSet_double*)inputSets[i])->AddElement( Energy[i] );
          }
        }
        TimeVals.push_back( time );
        nstep += ntpr;
      }
      frame++;
      if (finalE) break;
    }
    // Check for NSTEP in minimization or post-processing. Values will be
    // on the next line. NOTE: NSTEP means something different for imin=5.
    if ((imin == 1 || imin == 5) && strncmp(ptr, "   NSTEP", 8) == 0) {
      ptr = buffer.Line(); // Get next line
      //sscanf(ptr, " %6lf    %13lE  %13lE  %13lE", Energy+NSTEP, Energy+EPtot, Energy+RMS, Energy+GMAX);
      sscanf(ptr, " %i %lE %lE %lE", &minStep, Energy+EPtot, Energy+RMS, Energy+GMAX);
      EnergyExists[EPtot] = true;
      EnergyExists[RMS] = true;
      EnergyExists[GMAX] = true;
      ptr = buffer.Line();
    }
    // Tokenize line, scan through until '=' is reached; value after is target.
    int ntokens = buffer.TokenizeLine(" ");
    if (ntokens > 0) {
      int nidx = 0;
      Name[0].clear();
      Name[1].clear();
      for (int tidx = 0; tidx < ntokens; tidx++) {
        const char* tkn = buffer.NextToken();
        if (tkn[0] == '=') {
          FieldType Eindex = getEindex(Name);
          tkn = buffer.NextToken();
          ++tidx;
          if (tkn == 0)
            mprintf("Warning: No numerical value, line %i column %i. Skipping.\n",
                    buffer.LineNumber(), tidx+1);
          else if (tkn[0] == '*' || tkn[0] == 'N') // Assume if number begins with N it is NaN
            mprintf("Warning: Numerical overflow detected, line %i column %i. Skipping.\n",
                     buffer.LineNumber(), tidx+1);
          else {
            if (Eindex != N_FIELDTYPES) {
              Energy[Eindex] = atof( tkn );
              EnergyExists[Eindex] = true;
            }
          }
          nidx = 0;
          Name[0].clear();
          Name[1].clear();
        } else {
          if (nidx > 1) break; // Two tokens, no '=' found. Not an E line.
          Name[nidx++].assign( tkn );
        }
      }
    }
    // Set time
    switch (imin) {
      case 5: time = (double)nstep + t0; break;
      case 1: time = (double)minStep + t0; break;
      case 0: time = ((double)nstep * dt) + t0; break;
    }
    // Read in next line
    ptr = buffer.Line();
  }
  mprintf("\t%i frames\n", frame);
  buffer.CloseFile();
  std::string Xlabel;
  if      (imin == 5) Xlabel.assign("Set");
  else if (imin == 1) Xlabel.assign("Nstep");
  else                Xlabel.assign("Time"); // imin == 0
  if (datasetlist.AddOrAppendSets( Xlabel, TimeVals, inputSets )) return 1;
  return 0;
}
Пример #4
0
/** save current graph. */
void
SkillGuiGraphDrawingArea::save()
{
  Gtk::Window *w = dynamic_cast<Gtk::Window *>(get_toplevel());
  __fcd_save->set_transient_for(*w);

  int result = __fcd_save->run();
  if (result == Gtk::RESPONSE_OK) {

    Gtk::FileFilter *f = __fcd_save->get_filter();
    std::string filename = __fcd_save->get_filename();
    if (filename != "") {
      if (f == __filter_dot) {
	save_dotfile(filename.c_str());
      } else {
	Cairo::RefPtr<Cairo::Surface> surface;

	bool write_to_png = false;
	if (f == __filter_pdf) {
	  surface = Cairo::PdfSurface::create(filename, __bbw, __bbh);
	} else if (f == __filter_svg) {
	  surface = Cairo::SvgSurface::create(filename, __bbw, __bbh);
	} else if (f == __filter_png) {
	  surface = Cairo::ImageSurface::create(Cairo::FORMAT_ARGB32,
						(int)ceilf(__bbw),
						(int)ceilf(__bbh));
	  write_to_png = true;
	}

	if (surface) {
	  __cairo = Cairo::Context::create(surface);
	  
	  bool old_scale_override = __scale_override;
	  double old_tx = __translation_x;
	  double old_ty = __translation_y;
	  double old_scale = __scale;
	  __translation_x = __pad_x;
	  __translation_y = __bbh - __pad_y;
	  __scale = 1.0;
	  __scale_override = true;

	  if (__graph) {
	    gvRender(__gvc, __graph, (char *)"skillguicairo", NULL);
	  }

	  if (write_to_png) {
	    surface->write_to_png(filename);
	  }

	  __cairo.clear();

	  __translation_x = old_tx;
	  __translation_y = old_ty;
	  __scale = old_scale;
	  __scale_override = old_scale_override;
	}
      }

    } else {
      Gtk::MessageDialog md(*w, "Invalid filename",
			    /* markup */ false, Gtk::MESSAGE_ERROR,
			    Gtk::BUTTONS_OK, /* modal */ true);
      md.set_title("Invalid File Name");
      md.run();
    }
  }

  __fcd_save->hide();
}
Пример #5
0
///////////////////////////////////////////////////////////////////////////////
// Returns true upon success
bool PngOptionsDlg::StoreValues()
{
	m_settings.backupOldPngFiles = m_chkBackupOldPngFiles.IsChecked();
	m_settings.keepInterlacing = m_chkKeepInterlacing.IsChecked();
	m_settings.avoidGreyWithSimpleTransparency = m_chkAvoidGreyWith.IsChecked();
	m_settings.ignoreAnimatedGifs = m_chkIgnoreAnimatedGifs.IsChecked();
	m_settings.keepFileDate = m_chkKeepFileDate.IsChecked();

	if( m_radBkColorRemove.IsChecked() )
	{
		m_settings.bkgdOption = POChunk_Remove;
	}
	if( m_radBkColorKeep.IsChecked() )
	{
		m_settings.bkgdOption = POChunk_Keep;
	}
	if( m_radBkColorForce.IsChecked() )
	{
		m_settings.bkgdOption = POChunk_Force;
	}
	m_settings.bkgdColor = m_cbtBkColor.GetColor();

	if( m_radTextRemove.IsChecked() )
	{
		m_settings.textOption = POChunk_Remove;
	}
	if( m_radTextKeep.IsChecked() )
	{
		m_settings.textOption = POChunk_Keep;
	}
	if( m_radTextForce.IsChecked() )
	{
		m_settings.textOption = POChunk_Force;
	}
	m_settings.textKeyword = m_comboTextKeyword.GetText();
	m_settings.textData = m_editTextData.GetText();

	if( m_radPhysRemove.IsChecked() )
	{
		m_settings.physOption = POChunk_Remove;
	}
	if( m_radPhysKeep.IsChecked() )
	{
		m_settings.physOption = POChunk_Keep;
	}
	if( m_radPhysForce.IsChecked() )
	{
		m_settings.physOption = POChunk_Force;
	}
	m_settings.physPpmX = m_editPpmX.GetTextInt();
	m_settings.physPpmY = m_editPpmY.GetTextInt();

	// Validity check
	if( m_settings.textOption == POChunk_Force && m_settings.textKeyword.IsEmpty() )
	{
		MsgDialog md("Please set the forced text keyword.", GetText(), CMT_Warning, CBT_Ok);
		md.DoModal(this);
		m_comboTextKeyword.SetFocus();
		return false;
	}
	return true;
}
Пример #6
0
void Scouter::UnitFinished(int unit){
	NLOG("Scouter::UnitFinished");
	const UnitDef* ud = G->cb->GetUnitDef(unit);
	if( ud == 0) return;
	bool naset = false;
	if(G->abstract == false){
		// load scouters.txt so that we can get the list of units the modder has defined as scouters
		string filename;
		filename += "NTAI/";
		filename += G->cb->GetModName();
		filename += "/mod.tdf";
		ifstream fp;
		fp.open(filename.c_str(), ios::in);
		char buffer[4000];
		if(fp.is_open() == false){
			G->L.print(" error loading mod.tdf");
		}else{
			char in_char;
			int bsize = 0;
			while(fp.get(in_char)){
				buffer[bsize] += in_char;
				bsize++;
			}
			if(bsize > 0){
				CSunParser md(G);
				md.LoadBuffer(buffer,bsize);
				vector<string> v;
				v = bds::set_cont(v,md.SGetValueMSG("AI\\Scouters"));
				if(v.empty() == false){
					for(vector<string>::iterator vi = v.begin(); vi != v.end(); ++vi){
						if(*vi == ud->name){
							naset = true;
							break;
						}
					}
				}
			}
		}
	}else{
		// determine if this si a scouter or not dynamically
		if((ud->speed > 60)&&(ud->movedata != 0)&&(ud->canfly == false)&&(ud->transportCapacity == 0)&&(ud->isCommander == false)&&(ud->builder == false)) naset = true;
		if((ud->weapons.empty() == true)&&(ud->canfly == true)&&(ud->transportCapacity == 0)&&(ud->isCommander == false)&&(ud->builder == false)) naset = true;
	}
	float3 dpos = G->cb->GetUnitPos(unit);
	if((ud->extractsMetal >0)&&(cp.empty() == false)){
		for(map<int, list<float3> >::iterator i = cp.begin(); i != cp.end(); ++i){
			if(i->second.empty() == false){
				for(list<float3>::iterator j = i->second.begin(); j != i->second.end(); ++j){
					if(*j == dpos){
						i->second.erase(j);
						break;
					}
				}
			}
		}
		if(mexes.empty() == false){
			for(list<float3>::iterator i = mexes.begin(); i != mexes.end(); ++i){
				if( *i == dpos){
					mexes.erase(i);
					break;
				}
			}
		}
	}
	if(naset){
		if((G->cb->GetCurrentFrame()%3 == 2)||(cp.empty() == true)){
            cp[unit] = start_pos;
		}else if(G->cb->GetCurrentFrame()%3 == 1){
			list<float3> cf;
			for(int xa = 0; xa < G->Ch->xSectors; xa++){
				for(int ya = 0; ya < G->Ch->ySectors; ya++){
					if(xa > ya){
                        cf.push_back(G->Ch->sector[xa][ya].centre);
					}else{
						cf.insert(cf.begin(),G->Ch->sector[xa][ya].centre);
					}
				}
			}
			cp[unit] = cf;
		}else if(G->cb->GetCurrentFrame()%3 == 0){
            cp[unit] = mexes;
		}
		G->L.print("scouter found");
	 }
}
Пример #7
0
//  Exec_SortEnsembleData::Sort_pH_Data()
int Exec_SortEnsembleData::Sort_pH_Data(DataSetList const& setsToSort, DataSetList& OutputSets,
                                        unsigned int maxFrames)
const
{
  // Cast sets back to DataSet_PHREMD
  typedef std::vector<DataSet_PHREMD*> Parray;
  Parray PHsets;
  for (DataSetList::const_iterator ds = setsToSort.begin(); ds != setsToSort.end(); ++ds)
    PHsets.push_back( (DataSet_PHREMD*)*ds );

  // Gather initial pH data values, ensure no duplicates
  typedef std::vector<double> Darray;
  Darray pHvalues;
# ifdef MPI
  pHvalues.resize( Parallel::Ensemble_Size() );
  Darray phtmp;
  for (Parray::const_iterator ds = PHsets.begin(); ds != PHsets.end(); ++ds)
    phtmp.push_back( (*ds)->Initial_pH() );
  if (comm_.AllGather(&phtmp[0], phtmp.size(), MPI_DOUBLE, &pHvalues[0])) {
    rprinterr("Error: Gathering pH values.\n");
    return 1;
  }
# else
  for (Parray::const_iterator ds = PHsets.begin(); ds != PHsets.end(); ++ds)
    pHvalues.push_back( (*ds)->Initial_pH() );
# endif
  ReplicaInfo::Map<double> pH_map;
  if (pH_map.CreateMap( pHvalues )) {
    rprinterr("Error: Duplicate pH value detected (%.2f) in ensemble.\n", pH_map.Duplicate());
    return 1;
  }
  Darray sortedPH;
  mprintf("\tInitial pH values:");
  for (ReplicaInfo::Map<double>::const_iterator ph = pH_map.begin(); ph != pH_map.end(); ++ph)
  {
    mprintf(" %6.2f", ph->first);
    sortedPH.push_back( ph->first );
  }
  mprintf("\n");

  // Create sets to hold sorted pH values. Create a set for each pH value
  // and each residue. Final output sets will be PH0R0, PH0R1, PH1R0, ...
  // TODO check that residue info all the same
  DataSet_PHREMD::Rarray const& Residues = PHsets[0]->Residues();
  int defaultState = 0;
# ifdef MPI
  if ( PHsets[0]->Type() == DataSet::PH_IMPL)
    defaultState = -1;
# endif
  if (debug_ > 0)
    rprintf("DEBUG: Sorting %u frames for %zu sets, %zu pH values.\n",
            maxFrames, PHsets.size(), sortedPH.size());
  for (unsigned int idx = 0; idx != sortedPH.size(); idx++) {
    OutputSets.SetEnsembleNum( idx );
    for (unsigned int res = 0; res != Residues.size(); ++res) {
      MetaData md(PHsets[0]->Meta().Name(), Residues[res].Name().Truncated(), Residues[res].Num());
      DataSet_pH* out = (DataSet_pH*)OutputSets.AddSet( DataSet::PH, md );
      if (out==0) return 1;
      //out->SetLegend( "pH " + doubleToString( sortedPH[idx] ) );
      out->Set_Solvent_pH( sortedPH[idx] );
      out->SetResidueInfo( Residues[res] );
      out->SetTimeValues(PHsets[0]->Time());
      out->Resize( maxFrames, defaultState );
    }
  }

  // ---------------------------------------------
  if ( PHsets[0]->Type() == DataSet::PH_EXPL) {
    // Loop over unsorted sets
    for (Parray::const_iterator ds = PHsets.begin(); ds != PHsets.end(); ++ds)
    {
      DataSet_PHREMD_Explicit* in = (DataSet_PHREMD_Explicit*)*ds;
      unsigned int phidx = 0;
      for (unsigned int n = 0; n < maxFrames; n++)
      {
        float phval = in->pH_Values()[n];
        int setidx = pH_map.FindIndex( phval ) * Residues.size();
        //rprintf("DEBUG: %6u Set %10s pH= %6.2f going to %2i\n", n+1, in->legend(), phval, idx);
        //mflush();
        for (unsigned int res = 0; res < in->Residues().size(); res++, setidx++, phidx++)
        {
          DataSet_pH* out = (DataSet_pH*)OutputSets[setidx];
          //if (res == 0 && idx == 0) {
          //  rprintf("DEBUG: Frame %3u res %2u State %2i pH %6.2f\n", 
          //          n, res, in->Res(res).State(n), phval);
          //  mflush();
          //}
          out->SetState(n, in->ResStates()[phidx], in->RecordType(n));
        }
      }
    } // END loop over unsorted sets
#   ifdef MPI
    // Now we need to reduce down each set onto the thread where it belongs.
    if (Parallel::World().Size() > 1) {
      for (int idx = 0; idx != (int)OutputSets.size(); idx++) {
        DataSet_pH* out = (DataSet_pH*)OutputSets[idx];
        int ensembleRank = Parallel::MemberEnsCommRank( out->Meta().EnsembleNum() );
        //rprintf("DEBUG: Reduce set %s to rank %i\n", out->legend(), ensembleRank);
        out->Reduce( comm_, ensembleRank );
      }
      // Remove sets that do not belong on this rank
      for (int idx = (int)OutputSets.size() - 1; idx > -1; idx--) {
        DataSet* out = OutputSets[idx];
        int ensembleRank = Parallel::MemberEnsCommRank( out->Meta().EnsembleNum() );
        if (ensembleRank != comm_.Rank()) {
          //rprintf("DEBUG: Remove set %s (%i) from rank %i\n", out->legend(),
          //        idx, comm_.Rank());
          OutputSets.RemoveSet( out );
        }
      }
    }
#   endif
  // ---------------------------------------------
  } else if ( PHsets[0]->Type() == DataSet::PH_IMPL) {
#   ifdef MPI
    typedef std::vector<int> Iarray;
    typedef std::vector<Iarray> Iarray2;
    typedef std::vector<bool> Barray;
    // True if I have this pH value
    Barray isMyPh( sortedPH.size(), false );
    // Which rank in ensemble has which pH
    Iarray pHrank( sortedPH.size(), 0 );
    for (int phidx = 0; phidx != (int)sortedPH.size(); phidx++)
    {
      int ensembleRank = Parallel::MemberEnsCommRank( phidx );
      pHrank[phidx] = ensembleRank;
      isMyPh[phidx] = (ensembleRank == comm_.Rank());
    }
    // DEBUG
    for (unsigned int idx = 0; idx != pHrank.size(); idx++)
      mprintf("\tpH %6.2f on rank %i\n", sortedPH[idx], pHrank[idx]);
    // Hold frame-residue-state for each pH not on this rank.
    Iarray2 FrmResState( sortedPH.size() );
    // Loop over unsorted sets
    for (Parray::const_iterator ds = PHsets.begin(); ds != PHsets.end(); ++ds)
    {
      DataSet_PHREMD_Implicit* in = (DataSet_PHREMD_Implicit*)*ds;
      // Loop over frames
      for (unsigned int n = 0; n < maxFrames; n++)
      {
        DataSet_PHREMD_Implicit::Record const& Rec = in->Records()[n];
        float phval = Rec.pH();
        int phidx = pH_map.FindIndex( phval );
        if (isMyPh[phidx]) {
          // This pH belongs to me. Set value.
          int setidx = phidx * Residues.size();
          if (Rec.RecType() == Cph::FULL_RECORD) {
            // Info for all residues
            for (unsigned int res = 0; res < in->Residues().size(); res++, setidx++)
              ((DataSet_pH*)OutputSets[setidx])->SetState(n, Rec.ResStates()[res], Rec.RecType());
          } else if (Rec.RecType() > -1) {
            // Info for single residue, record type for all residues
            //rprintf("\tSetting my pH %6.2f frame %8i state %2i idx %6i res %6i '%s'\n", sortedPH[phidx], n, Rec.ResStates()[0], setidx, Rec.RecType(), OutputSets[setidx+Rec.RecType()]->legend());
            for (int res = 0; res < (int)in->Residues().size(); res++, setidx++)
              if (res == Rec.RecType())
                ((DataSet_pH*)OutputSets[setidx])->SetState(n, Rec.ResStates()[0], Rec.RecType());
              else
                ((DataSet_pH*)OutputSets[setidx])->SetRecType(n, Rec.RecType());
          }
        } else {
          // This pH belongs to another rank. Save it.
          if (Rec.RecType() > -1) {
            // Info for a single residue present
            FrmResState[phidx].push_back( n );
            FrmResState[phidx].push_back( Rec.RecType() );
            FrmResState[phidx].push_back( Rec.ResStates()[0] );
          } else {
            // Info for all residues present
            FrmResState[phidx].push_back( n );
            FrmResState[phidx].push_back( Rec.RecType() );
            for (unsigned int res = 0; res < in->Residues().size(); res++)
              FrmResState[phidx].push_back( Rec.ResStates()[res] );
          }
        }
      } // END loop over frames
    } // END loop over sets
    // DEBUG
/*
    comm_.Barrier();
    for (int rank = 0; rank < comm_.Size(); rank++)
    {
      if (rank == comm_.Rank())
      {
        for (unsigned int phidx = 0; phidx != sortedPH.size(); phidx++) {
          rprintf("DEBUG: pH %6.2f: %8s %6s %2s\n", sortedPH[phidx], "Frm", "Res", "St");
          Iarray const& FRS = FrmResState[phidx];
          unsigned int idx = 0;
          while (idx < FRS.size()) {
            int rec = FRS[idx+1];
            if (rec > -1) {
              rprintf("                  %8i %6i %2i\n", FRS[idx], rec, FRS[idx+2]);
              idx += 3;
            } else {
              rprintf("                  %8i %6i All Residues\n", FRS[idx], rec);
              idx += (2 + Residues.size());
            }
          }
        }
      }
      comm_.Barrier();
    }
*/
    // Communicate states to other ranks
    typedef std::vector<unsigned int> Uarray;
    Uarray sizeOnRank( comm_.Size() );
    for (unsigned int phidx = 0; phidx != sortedPH.size(); phidx++)
    {
      // Each rank says how many frames of this pH they have collected and
      // send to rank the pH belongs to.
      unsigned int nph = FrmResState[phidx].size();
      comm_.Gather(&nph, 1, MPI_UNSIGNED, &sizeOnRank[0], pHrank[phidx]);
      if (pHrank[phidx] == comm_.Rank())
      {
        // This pH belongs to me. I should have no frames at this pH.
        if (sizeOnRank[comm_.Rank()] > 0) {
          rprinterr("Internal Error: Rank has frames to communicate at its pH\n");
          Parallel::Abort(1);
        }
        unsigned int totalSize = 0;
        for (unsigned int idx = 0; idx != sizeOnRank.size(); idx++) {
          totalSize += sizeOnRank[idx];
          //rprintf("DEBUG: Rank %4u has %8u frames of pH %6.2f\n",
          //        idx, sizeOnRank[idx], sortedPH[phidx]);
        }
        //rprintf("DEBUG: Total incoming size: %u\n", totalSize);
        FrmResState[phidx].resize( totalSize );
        // Receive state info for this pH from other ranks
        int* frsArray = &(FrmResState[phidx][0]);
        for (int rank = 0; rank != comm_.Size(); rank++) {
          if (rank != comm_.Rank()) {
            comm_.Recv(frsArray, sizeOnRank[rank], MPI_INT, rank, 1600+rank);
            frsArray += sizeOnRank[rank];
          }
        }
      } else {
        // This pH belongs to another rank. Send my info there.
        int* frsArray = &(FrmResState[phidx][0]);
        comm_.Send(frsArray, nph, MPI_INT, pHrank[phidx], 1600+comm_.Rank());
      }
      comm_.Barrier();
    }
    // Fill in state info
    std::vector<DataSet*> ToRemove;
    for (unsigned int phidx = 0; phidx != sortedPH.size(); phidx++)
    {
      int setidx = phidx * Residues.size();
      if (pHrank[phidx] == comm_.Rank())
      {
        Iarray const& FRS = FrmResState[phidx];
        // This pH belongs to me. Fill in the information received from
        // other ranks.
        unsigned int idx = 0;
        while (idx < FRS.size()) {
          int rec = FRS[idx+1];
          if (rec > -1) {
            // Info for single residue, record type for all residues
            //rprintf("\tSetting pH %6.2f frame %8i state %2i idx %6i res %6i '%s'\n", sortedPH[phidx], FRS[idx], FRS[idx+2], setidx, rec, OutputSets[setidx+rec]->legend());
            for (int res = 0; res != (int)Residues.size(); res++) {
              DataSet_pH* out = (DataSet_pH*)OutputSets[setidx + res];
              if (rec == res)
                out->SetState( FRS[idx], FRS[idx+2], rec );
              else
                out->SetRecType( FRS[idx], rec );
            }
            idx += 3;
          } else {
            //rprintf("                  %8i %6i All Residues\n", FRS[idx], rec);
            int frm = FRS[idx];
            idx += 2;
            for (unsigned int res = 0; res != Residues.size(); res++, idx++) {
              DataSet_pH* out = (DataSet_pH*)OutputSets[setidx + res];
              out->SetState( frm, FRS[idx], rec );
            }
          }
        }
        // Fill in any remaining data. FIXME safe to assume first frame is set?
        for (unsigned int res = 0; res != Residues.size(); res++) {
          DataSet_pH* out = (DataSet_pH*)OutputSets[setidx + res];
          for (unsigned int n = 1; n < maxFrames; n++)
            if (out->State(n) == -1)
              out->SetState(n, out->State(n-1), out->RecordType(n));
        }
      } else {
        // This pH does not belong to me. Mark associated data sets to be removed.
        for (unsigned int res = 0; res != Residues.size(); res++)
          ToRemove.push_back( OutputSets[setidx + res] );
      }
    }
    // Remove data sets that do not belong to me.
    for (std::vector<DataSet*>::reverse_iterator it = ToRemove.rbegin();
                                                 it != ToRemove.rend(); ++it)
    {
      //rprintf("DEBUG: '%s' does not belong to me.\n", (*it)->legend());
      OutputSets.RemoveSet( *it );
    }
#   else /* if not MPI */
    // Loop over frames
    for (unsigned int n = 0; n < maxFrames; n++)
    {
      // Loop over unsorted sets
      for (Parray::const_iterator ds = PHsets.begin(); ds != PHsets.end(); ++ds)
      {
        DataSet_PHREMD_Implicit* in = (DataSet_PHREMD_Implicit*)*ds;
        DataSet_PHREMD_Implicit::Record const& Rec = in->Records()[n];
        float phval = Rec.pH();
        int setidx = pH_map.FindIndex( phval ) * Residues.size();
        if (Rec.RecType() == Cph::FULL_RECORD) {
          for (unsigned int res = 0; res < in->Residues().size(); res++, setidx++)
          {
            DataSet_pH* out = (DataSet_pH*)OutputSets[setidx];
            //if (res == 0 && idx == 0) {
            //  rprintf("DEBUG: Frame %3u res %2u State %2i pH %6.2f\n", 
            //          n, res, in->Res(res).State(n), phval);
            //  mflush();
            //}
            out->SetState(n, Rec.ResStates()[res], Rec.RecType());
          }
        } else {
          for (int res = 0; res < (int)in->Residues().size(); res++, setidx++)
          {
            DataSet_pH* out = (DataSet_pH*)OutputSets[setidx];
            if (res == Rec.RecType())
              out->SetState(n, Rec.ResStates()[0], Rec.RecType());
            else
              // State for this residue not recorded - use previous state.
              // Should be fine since first state always has all residues.
              out->SetState(n, out->State(n-1), Rec.RecType());
          }
        }
      } // END loop over unsorted sets
    } // END loop over frames
#   endif /* MPI */
  // ---------------------------------------------
  } else {
    return 1; // Sanity check
  }
  return 0;
}
Пример #8
0
void make_data_dirs(scfg_t* cfg)
{
	char	str[MAX_PATH+1];

	md(cfg->data_dir);
	sprintf(str,"%ssubs",cfg->data_dir);
	md(str);
	sprintf(str,"%sdirs",cfg->data_dir);
	md(str);
	sprintf(str,"%stext",cfg->data_dir);
	md(str);
	sprintf(str,"%smsgs",cfg->data_dir);
	md(str);
	sprintf(str,"%suser",cfg->data_dir);
	md(str);
	sprintf(str,"%suser/ptrs",cfg->data_dir);
	md(str);
	sprintf(str,"%sqnet",cfg->data_dir);
	md(str);
	sprintf(str,"%sfile",cfg->data_dir);
	md(str);

	md(cfg->logs_dir);
	sprintf(str,"%slogs",cfg->logs_dir);
	md(str);

	if(cfg->mods_dir[0])
		md(cfg->mods_dir);

#if 0
	int		i;

	for(i=0;i<cfg->total_subs;i++) {
		if(cfg->sub[i]->data_dir[0]
			&& (!i || stricmp(cfg->sub[i]->data_dir,cfg->sub[i-1]->data_dir))) {
			backslash(cfg->sub[i]->data_dir);
			md(cfg->sub[i]->data_dir);
		}
	}

	for(i=0;i<cfg->total_dirs;i++) {
		if(cfg->dir[i]->data_dir[0]
			&& (!i || stricmp(cfg->dir[i]->data_dir,cfg->dir[i-1]->data_dir))) {
			backslash(cfg->dir[i]->data_dir);
			md(cfg->dir[i]->data_dir);
		}
		if(cfg->dir[i]->misc&DIR_FCHK) 
			md(cfg->dir[i]->path); 
	}

	for(i=0;i<cfg->total_txtsecs;i++) {
		sprintf(str,"%stext/%s",cfg->data_dir,cfg->txtsec[i]->code);
		md(str);
	}
#endif
}
Пример #9
0
	void Inverse(const Matrix4 &m, Matrix4 &result)
	{
		// This entire function desparately needs to be optimised as im repeating many a operation several times.
		// However, I've left these as is for clarities sake(whatever hope that has with an operation like inverse).

		// If the Matrix4 is Orthogonal then we can just transpose it to make things easier.
		if (IsOrthogonal(m))
		{
			return Transpose(m, result); 
		}

		// If it is not orthogonal then we have lots and lots and lots of calculations to do.
		// So we need to calculate the co-factors for each element in the new Matrix4....
		// The co-factor for a given point in a new Matrix4 is given by.
		//
		// Determinat of sub-Matrix4
		//     /--            --\       /--            --\       /--            --\   
		//     | RES XXX XXX XXX|       | RES XXX XXX XXX|       | RES XXX XXX XXX|
		//     | XX (m22) XX XXX| MINUS | X (m22) XXX XXX|  ADD  | XXX XX (m23) XX| 
		//     | XXX XX (m33) XX| MINUS | X XXX XXX (m34)|  ADD  | XXX XX (m33) XX|
		//     | XXX XXX X (m44)|       | X XXX (m43) XXX|       | XXX XX XX (m44)|
		//     \--            --/       \--            --/       \--            --/ ... ETC
		//
		// 
		// To break it down more, for m11 in the inverse the equation is similar to the determinant.
		// We cancel out the rows and columns of the subject.
		//
		// EXAMPLE OF ROW & COLUMN CANCELLING
		//     /--            --\       /--            --\       /--            --\   
		//     | m11 XXX XXX XXX|       | m11 XXX XXX XXX|       | m11 XXX XXX XXX|
		//     | XXX m22 m23 m24| >   > | XXX m22 XXX XXX| >   > | XXX m22 XXX XXX| 
		//     | XXX m32 m33 m34| >   > | XXX XXX m33 m34| >   > | XXX XXX m33 XXX|
		//     | XXX m42 m43 m44|       | XXX XXX m43 m44|       | XXX XXX XXX m44|
		//     \--            --/       \--            --/       \--            --/
		//
		// m11(-1) = m22*(m33*m44 - m34*m43) + m23*(m34*m42 - m32*m44) + m24*(m32*m43 - m33*m42);
		//
		// Finally after getting the co-factor we need divide the entire Matrix4 by the determinant of the
		// old Matrix4.


		// Co-factors of the X Axis vector.
		float cof11, cof12, cof13, cof14;

		// Co-factors of the Y Axis vector.
		float cof21, cof22, cof23, cof24;

		// Co-factors of the Z Axis vector.
		float cof31, cof32, cof33, cof34;

		// Co-factors of the W Axis vector.
		float cof41, cof42, cof43, cof44;

		// The determinant of the inputed Matrix4.
		Matrix4 md(m);
		float detInv = 1.0f / md.Determinant();

		// And so it starts...
		
		//*********************************************************************************************************
		//                                             X AXIS VECTOR
		//*********************************************************************************************************

		// Cofactor of element m11 aka X component of the x axis vector.
		cof11 = m.yY*(m.zZ*m.wW - m.zW*m.wZ) + m.yZ*(m.zW*m.wY - m.zY*m.wW) + m.yW*(m.zY*m.wZ - m.zZ*m.wY);

		// Cofactor of element m12 aka Y component of the x axis vector.
		cof12 = -(m.yX*(m.zZ*m.wW - m.zW*m.wZ) + m.yZ*(m.zW*m.wX - m.zX*m.wW) + m.yW*(m.zX*m.wZ - m.zZ*m.wX));

		// Cofactor of element m13 aka Z component of the x axis vector.
		cof13 = m.yX*(m.zY*m.wW - m.zW*m.wY) + m.yY*(m.zW*m.wX - m.zX*m.wW) + m.yW*(m.zX*m.wY - m.zY*m.wX);

		// Cofactor of element m14 aka W component of the x axis vector.
		cof14 = -(m.yX*(m.zY*m.wZ - m.zZ*m.wY) + m.yY*(m.zZ*m.wX - m.zX*m.wZ) + m.yZ*(m.zX*m.wY - m.zY*m.wX));
	
		//*********************************************************************************************************
		//                                             Y AXIS VECTOR
		//*********************************************************************************************************

		// Cofactor of element m21 aka X component of the y axis vector.
		cof21 = -(m.xY*(m.zZ*m.wW - m.zW*m.wZ) + m.xY*(m.zY*m.wW - m.zW*m.wY) + m.xW*(m.zY*m.wZ - m.zZ*m.wY));
		
		// Cofactor of element m22 aka Y component of the y axis vector.
		cof22 = m.xX*(m.zZ*m.wW - m.zW*m.wZ) + m.xZ*(m.wX*m.zW - m.wW*m.zX) + m.xW*(m.zX*m.wZ - m.zZ*m.wX);

		// Cofactor of element m23 aka Z component of the y axis vector.
		cof23 = -(m.xX*(m.zY*m.wW - m.zW*m.wY) + m.xY*(m.wX*m.zW - m.wW*m.zX) + m.xW*(m.zX*m.wY - m.zY*m.wX));

		// Cofactor of element m24 aka W component of the y axis vector.
		cof24 = m.xX*(m.zY*m.wZ - m.zZ*m.wY) + m.xY*(m.wX*m.zZ - m.wZ*m.zX) + m.xZ*(m.zX*m.wY - m.zY*m.wX);
	
		//*********************************************************************************************************
		//                                             Z AXIS VECTOR
		//*********************************************************************************************************

		// Cofactor of element m31 aka X component of the z axis vector.
		cof31 = m.xY*(m.yZ*m.wW - m.yW*m.wZ) + m.xZ*(m.wY*m.yW - m.wW*m.yY) + m.xW*(m.yY*m.wZ - m.yZ*m.wY);

		// Cofactor of element m32 aka Y component of the z axis vector.
		cof32 = -(m.xX*(m.yZ*m.wW - m.yW*m.wZ) + m.xZ*(m.wX*m.yW - m.wW*m.yX) + m.xW*(m.yX*m.wZ - m.yZ*m.wX));
		
		// Cofactor of element m33 aka Z component of the z axis vector.
		cof33 = m.xX*(m.yY*m.wW - m.yW*m.wY) + m.xY*(m.wX*m.yW - m.wW*m.yX) + m.xW*(m.yX*m.wY - m.yY*m.wX);
		
		// Cofactor of element m34 aka W component of the z axis vector.
		cof34 = -(m.xX*(m.yY*m.wZ - m.yZ*m.wY) + m.xY*(m.wX*m.yZ - m.wZ*m.yX) + m.xZ*(m.yX*m.wY - m.yY*m.wX));
	
		//*********************************************************************************************************
		//                                             W AXIS VECTOR
		//*********************************************************************************************************

		// Cofactor of element m41 aka X component of the w axis vector.
		cof41 = m.xY*(m.yZ*m.zW - m.yW*m.zZ) + m.xZ*(m.zY*m.yW - m.zW*m.yY) + m.xW*(m.yY*m.zZ - m.yZ*m.zY);

		// Cofactor of element m42 aka Y component of the w axis vector.
		cof42 = -(m.xX*(m.yZ*m.zW - m.yW*m.zZ) + m.xZ*(m.yW*m.zX - m.yX*m.zW) + m.xW*(m.yX*m.zZ - m.yZ*m.zX));
		
		// Cofactor of element m43 aka Z component of the w axis vector.
		cof43 = m.xX*(m.yY*m.zW - m.yW*m.zY) + m.xY*(m.zX*m.yW - m.zW*m.yX) + m.xW*(m.yX*m.zY - m.yY*m.zX);
		
		// Cofactor of element m44 aka Z component of the w axis vector.
		cof44 = -(m.xX*(m.yY*m.zZ - m.yZ*m.zY) + m.xY*(m.zX*m.yZ - m.zZ*m.yX) + m.xZ*(m.yX*m.zY - m.yY*m.zX));

		// Now we have all the co-factors we punch them into our resultant Matrix4 and divide by the determinant.

		// Inverse X axis of m.
		result.xX = (cof11 * detInv);
		result.xY = (cof12 * detInv);
		result.xZ = (cof13 * detInv);
		result.xW = (cof14 * detInv);

		// Inverse Y axis of m.
		result.yX = (cof21 * detInv);
		result.yY = (cof22 * detInv);
		result.yZ = (cof23 * detInv);
		result.yW = (cof24 * detInv);

		// Inverse Z axis of m.
		result.zX = (cof31 * detInv);
		result.zY = (cof32 * detInv);
		result.zZ = (cof33 * detInv);
		result.zW = (cof34 * detInv);

		// Inverse W axis of m.
		result.wX = (cof41 * detInv);
		result.wY = (cof42 * detInv);
		result.wZ = (cof43 * detInv);
		result.wW = (cof44 * detInv);
	}
Пример #10
0
/* MapEditorWindow::openMap
 * Opens [map] in the editor
 *******************************************************************/
bool MapEditorWindow::openMap(Archive::mapdesc_t map)
{
	// If a map is currently open and modified, prompt to save changes
	if (editor.getMap().isModified())
	{
		wxMessageDialog md(this, S_FMT("Save changes to map %s?", currentMapDesc().name), "Unsaved Changes", wxYES_NO | wxCANCEL);
		int answer = md.ShowModal();
		if (answer == wxID_YES)
			saveMap();
		else if (answer == wxID_CANCEL)
			return true;
	}

	// Show blank map
	this->Show(true);
	map_canvas->Refresh();
	Layout();
	Update();
	Refresh();

	// Clear current map data
	for (unsigned a = 0; a < map_data.size(); a++)
		delete map_data[a];
	map_data.clear();

	// Get map parent archive
	Archive* archive = NULL;
	if (map.head)
	{
		archive = map.head->getParent();

		// Load map data
		if (map.archive)
		{
			WadArchive temp;
			temp.open(map.head->getMCData());
			for (unsigned a = 0; a < temp.numEntries(); a++)
				map_data.push_back(new ArchiveEntry(*(temp.getEntry(a))));
		}
		else
		{
			ArchiveEntry* entry = map.head;
			while (entry)
			{
				bool end = (entry == map.end);
				map_data.push_back(new ArchiveEntry(*entry));
				entry = entry->nextEntry();
				if (end)
					break;
			}
		}
	}

	// Set texture manager archive
	tex_man.setArchive(archive);

	// Clear current map
	closeMap();

	// Attempt to open map
	theSplashWindow->show("Loading Map", true, this);
	bool ok = editor.openMap(map);
	theSplashWindow->hide();

	// Show window if opened ok
	if (ok)
	{
		mdesc_current = map;

		// Read DECORATE definitions if any
		theGameConfiguration->parseDecorateDefs(theArchiveManager->baseResourceArchive());
		for (int i = 0; i < theArchiveManager->numArchives(); ++i)
			theGameConfiguration->parseDecorateDefs(theArchiveManager->getArchive(i));

		// Load scripts if any
		loadMapScripts(map);

		// Lock map entries
		lockMapEntries();

		// Reset map checks panel
		panel_checks->reset();

		map_canvas->viewFitToMap(true);
		map_canvas->Refresh();

		// Set window title
		if (archive)
			SetTitle(S_FMT("SLADE - %s of %s", map.name, archive->getFilename(false)));
		else
			SetTitle(S_FMT("SLADE - %s (UNSAVED)", map.name));

		// Create backup
		if (map.head && !backup_manager->writeBackup(map_data, map.head->getTopParent()->getFilename(false), map.head->getName(true)))
			LOG_MESSAGE(1, "Warning: Failed to backup map data");
	}

	return ok;
}
Пример #11
0
// Analysis_Modes::Setup()
Analysis::RetType Analysis_Modes::Setup(ArgList& analyzeArgs, AnalysisSetup& setup, int debugIn)
{
  debug_ = debugIn;
  // Analysis type
  if (analyzeArgs.hasKey("fluct"))
    type_ = FLUCT;
  else if (analyzeArgs.hasKey("displ"))
    type_ = DISPLACE;
  else if (analyzeArgs.hasKey("corr"))
    type_ = CORR;
  else if (analyzeArgs.Contains("trajout"))
    type_ = TRAJ;
  else if (analyzeArgs.hasKey("eigenval"))
    type_ = EIGENVAL;
  else if (analyzeArgs.hasKey("rmsip"))
    type_ = RMSIP;
  else {
    mprinterr("Error: No analysis type specified.\n");
    return Analysis::ERR;
  }

  // Get modes name
  std::string modesfile = analyzeArgs.GetStringKey("name");
  if (modesfile.empty()) {
    // Check for deprecated args
    CheckDeprecated(analyzeArgs, modesfile, "file");
    CheckDeprecated(analyzeArgs, modesfile, "stack");
    if (modesfile.empty()) {
      mprinterr("Error: No 'name <modes data set name>' argument given.\n");
      return Analysis::ERR;
    }
  }
  // Get second modes name for RMSIP
  std::string modesfile2 = analyzeArgs.GetStringKey("name2");
  if (type_ == RMSIP) {
    if (modesfile2.empty()) {
      mprinterr("Error: 'rmsip' requires second modes data 'name2 <modes>'\n");
      return Analysis::ERR;
    }
  } else
    modesfile2.clear();
  // Get topology for TRAJ/CORR
  Topology* analyzeParm = setup.DSL().GetTopology( analyzeArgs ); 

  if (type_ == TRAJ ) {
    // Get trajectory format args for projected traj
    beg_ = analyzeArgs.getKeyInt("beg",1) - 1; // Args start at 1
    std::string tOutName = analyzeArgs.GetStringKey("trajout");
    if (tOutName.empty()) {
      mprinterr("Error: Require output trajectory filename, 'trajout <name>'\n");
      return Analysis::ERR;
    }
    TrajectoryFile::TrajFormatType tOutFmt = TrajectoryFile::UNKNOWN_TRAJ;
    if ( analyzeArgs.Contains("trajoutfmt") )
      tOutFmt = TrajectoryFile::GetFormatFromString( analyzeArgs.GetStringKey("trajoutfmt") );
    if (analyzeParm == 0) {
      mprinterr("Error: Could not get topology for output trajectory.\n");
      return Analysis::ERR;
    }
    AtomMask tOutMask( analyzeArgs.GetStringKey("trajoutmask") );
    if ( analyzeParm->SetupIntegerMask( tOutMask ) || tOutMask.None() ) {
      mprinterr("Error: Could not setup output trajectory mask.\n");
      return Analysis::ERR;
    }
    tOutMask.MaskInfo();
    // Strip topology to match mask.
    if (tOutParm_ != 0) delete tOutParm_;
    tOutParm_ = analyzeParm->modifyStateByMask( tOutMask );
    if (tOutParm_ == 0) {
      mprinterr("Error: Could not create topology to match mask.\n");
      return Analysis::ERR;
    }
    // Setup output traj
    if (trajout_.InitTrajWrite( tOutName, ArgList(), tOutFmt ) != 0) {
      mprinterr("Error: Could not init output trajectory.\n");
      return Analysis::ERR;
    }
    // Get min and max for PC
    pcmin_ = analyzeArgs.getKeyDouble("pcmin", -10.0);
    pcmax_ = analyzeArgs.getKeyDouble("pcmax",  10.0);
    if (pcmax_ < pcmin_ || pcmax_ - pcmin_ < Constants::SMALL) {
      mprinterr("Error: pcmin must be less than pcmax\n");
      return Analysis::ERR;
    }
    tMode_ = analyzeArgs.getKeyInt("tmode", 1);
  } else {
    // Args for everything else
    beg_ = analyzeArgs.getKeyInt("beg",7) - 1; // Args start at 1
    bose_ = analyzeArgs.hasKey("bose");
    calcAll_ = analyzeArgs.hasKey("calcall");
  }
  end_ = analyzeArgs.getKeyInt("end", 50);
  factor_ = analyzeArgs.getKeyDouble("factor",1.0);
  std::string setname = analyzeArgs.GetStringKey("setname");

  // Check if modes name exists on the stack
  modinfo_ = (DataSet_Modes*)setup.DSL().FindSetOfType( modesfile, DataSet::MODES );
  if (modinfo_ == 0) {
    mprinterr("Error: '%s' not found: %s\n", modesfile.c_str(), DataSet_Modes::DeprecateFileMsg);
    return Analysis::ERR;
  }
  if (!modesfile2.empty()) {
    modinfo2_ = (DataSet_Modes*)setup.DSL().FindSetOfType( modesfile2, DataSet::MODES );
    if (modinfo2_ == 0) {
      mprinterr("Error: Set %s not found.\n", modesfile2.c_str());
      return Analysis::ERR;
    }
  }

  // Check modes type for specified analysis
  if (type_ == FLUCT || type_ == DISPLACE || type_ == CORR || type_ == TRAJ) {
    if (modinfo_->Meta().ScalarType() != MetaData::COVAR && 
        modinfo_->Meta().ScalarType() != MetaData::MWCOVAR)
    {
      mprinterr("Error: Modes must be of type COVAR or MWCOVAR for %s.\n",
                analysisTypeString[type_]);
      return Analysis::ERR;
    }
  }

  // Get output filename for types that use DataSets
  std::string outfilename = analyzeArgs.GetStringKey("out"); // TODO all datafile?
  DataFile* dataout = 0;
  if (type_ == FLUCT || type_ == DISPLACE || type_ == EIGENVAL || type_ == RMSIP)
    dataout = setup.DFL().AddDataFile( outfilename, analyzeArgs );
  else if (type_ == CORR) {
    // CORR-specific setup
    outfile_ = setup.DFL().AddCpptrajFile( outfilename, "Modes analysis",
                                           DataFileList::TEXT, true );
    if (outfile_ == 0) return Analysis::ERR;
    // Get list of atom pairs
    if (analyzeParm == 0) {
      mprinterr("Error: 'corr' requires topology.\n");
      return Analysis::ERR;
    }
    std::string maskexp = analyzeArgs.GetStringKey("mask1");
    if (maskexp.empty()) {
      while (analyzeArgs.hasKey("maskp")) {
        // Next two arguments should be one-atom masks
        std::string a1mask = analyzeArgs.GetMaskNext();
        std::string a2mask = analyzeArgs.GetMaskNext();
        if (a1mask.empty() || a2mask.empty()) {
          mprinterr("Error: For 'corr' two 1-atom masks are expected.\n");
          return Analysis::ERR;
        }
        // Check that each mask is just 1 atom
        AtomMask m1( a1mask );
        AtomMask m2( a2mask );
        analyzeParm->SetupIntegerMask( m1 ); 
        analyzeParm->SetupIntegerMask( m2 );
        if ( m1.Nselected()==1 && m2.Nselected()==1 )
          // Store atom pair
          atompairStack_.push_back( std::pair<int,int>( m1[0], m2[0] ) );
        else {
          mprinterr("Error: For 'corr', masks should specify only one atom.\n"
                    "\tM1[%s]=%i atoms, M2[%s]=%i atoms.\n", m1.MaskString(), m1.Nselected(),
                    m2.MaskString(), m2.Nselected());
          return Analysis::ERR;
        }
      }
    } else {
      AtomMask mask1( maskexp );
      maskexp = analyzeArgs.GetStringKey("mask2");
      if (maskexp.empty()) {
        mprinterr("Error: 'mask2' must be specified if 'mask1' is.\n");
        return Analysis::ERR;
      }
      AtomMask mask2( maskexp );
      if ( analyzeParm->SetupIntegerMask( mask1 ) ) return Analysis::ERR;
      if ( analyzeParm->SetupIntegerMask( mask2 ) ) return Analysis::ERR;
      mask1.MaskInfo();
      mask2.MaskInfo();
      if (mask1.None() || mask2.None()) {
        mprinterr("Error: One or both masks are empty.\n");
        return Analysis::ERR;
      }
      if (mask1.Nselected() != mask2.Nselected()) {
        mprinterr("Error: # atoms in mask 1 not equal to # atoms in mask 2.\n");
        return Analysis::ERR;
      }
      for (int idx = 0; idx != mask1.Nselected(); idx++)
        atompairStack_.push_back( std::pair<int,int>( mask1[idx], mask2[idx] ) );
    }
    if ( atompairStack_.empty() ) {
      mprinterr("Error: No atom pairs found (use 'maskp' or 'mask1'/'mask2' keywords.)\n");
      return Analysis::ERR;
    }
  }

  // Set up data sets
  Dimension Xdim;
  if (type_ == FLUCT) {
    if (setname.empty()) setname = setup.DSL().GenerateDefaultName("FLUCT");
    MetaData md(setname, "rmsX");
    OutSets_.resize( 4, 0 );
    OutSets_[RMSX] = setup.DSL().AddSet( DataSet::DOUBLE, md );
    md.SetAspect("rmsY");
    OutSets_[RMSY] = setup.DSL().AddSet( DataSet::DOUBLE, md );
    md.SetAspect("rmsZ");
    OutSets_[RMSZ] = setup.DSL().AddSet( DataSet::DOUBLE, md );
    md.SetAspect("rms");
    OutSets_[RMS]  = setup.DSL().AddSet( DataSet::DOUBLE, md );
    Xdim = Dimension(1, 1, "Atom_no.");
  } else if (type_ == DISPLACE) {
    if (setname.empty()) setname = setup.DSL().GenerateDefaultName("DISPL");
    MetaData md(setname, "displX");
    OutSets_.resize( 3, 0 );
    OutSets_[RMSX] = setup.DSL().AddSet( DataSet::DOUBLE, md );
    md.SetAspect("displY");
    OutSets_[RMSY] = setup.DSL().AddSet( DataSet::DOUBLE, md );
    md.SetAspect("displZ");
    OutSets_[RMSZ] = setup.DSL().AddSet( DataSet::DOUBLE, md );
    Xdim = Dimension(1, 1, "Atom_no.");
  } else if (type_ == EIGENVAL) {
    if (setname.empty()) setname = setup.DSL().GenerateDefaultName("XEVAL");
    MetaData md(setname, "Frac");
    OutSets_.resize( 3, 0 );
    OutSets_[0] = setup.DSL().AddSet( DataSet::DOUBLE, md );
    md.SetAspect("Cumulative");
    OutSets_[1] = setup.DSL().AddSet( DataSet::DOUBLE, md );
    md.SetAspect("Eigenval");
    OutSets_[2] = setup.DSL().AddSet( DataSet::DOUBLE, md );
    Xdim = Dimension( 1, 1, "Mode" );
  } else if (type_ == RMSIP) {
    if (setname.empty()) setname = setup.DSL().GenerateDefaultName("RMSIP");
    OutSets_.push_back( setup.DSL().AddSet( DataSet::DOUBLE, setname ) );
    if (dataout != 0) dataout->ProcessArgs("noxcol");
    OutSets_[0]->SetupFormat() = TextFormat(TextFormat::GDOUBLE);
    OutSets_[0]->SetLegend( modinfo_->Meta().Legend() + "_X_" + modinfo2_->Meta().Legend() );
  }
  for (std::vector<DataSet*>::const_iterator set = OutSets_.begin(); set != OutSets_.end(); ++set)
  {
    if (*set == 0) return Analysis::ERR;
    if (dataout != 0) dataout->AddDataSet( *set );
    (*set)->SetDim(Dimension::X, Xdim);
  }

  // Status
  mprintf("    ANALYZE MODES: Calculating %s using modes from %s", 
          analysisTypeString[type_], modinfo_->legend());
  if ( type_ != TRAJ ) {
    if (type_ != EIGENVAL)
      mprintf(", modes %i to %i", beg_+1, end_);
    if (outfile_ != 0)
      mprintf("\n\tResults are written to %s\n", outfile_->Filename().full());
    else if (dataout != 0)
      mprintf("\n\tResults are written to '%s'\n", dataout->DataFilename().full());
    if (type_ != EIGENVAL && type_ != RMSIP) {
      if (bose_)
        mprintf("\tBose statistics used.\n");
      else
        mprintf("\tBoltzmann statistics used.\n");
      if (calcAll_)
        mprintf("\tEigenvectors associated with zero or negative eigenvalues will be used.\n");
      else
        mprintf("\tEigenvectors associated with zero or negative eigenvalues will be skipped.\n");
    }
    if (type_ == DISPLACE)
      mprintf("\tFactor for displacement: %f\n", factor_);
    if (type_ == CORR) {
      mprintf("\tUsing the following atom pairs:");
      for (modestack_it apair = atompairStack_.begin();
                        apair != atompairStack_.end(); ++apair)
        mprintf(" (%i,%i)", apair->first+1, apair->second+1 );
      mprintf("\n");
    }
    if (type_ == RMSIP)
      mprintf("\tRMSIP calculated to modes in %s\n", modinfo2_->legend());
  } else {
    mprintf("\n\tCreating trajectory for mode %i\n"
              "\tWriting to trajectory %s\n"
              "\tPC range: %f to %f\n"
              "\tScaling factor: %f\n", tMode_, 
            trajout_.Traj().Filename().full(), pcmin_, pcmax_, factor_);
  }

  return Analysis::OK;
}
Пример #12
0
int x509write_csr_der( x509write_csr *ctx, unsigned char *buf, size_t size,
                       int (*f_rng)(void *, unsigned char *, size_t),
                       void *p_rng )
{
    int ret;
    const char *sig_oid;
    size_t sig_oid_len = 0;
    unsigned char *c, *c2;
    unsigned char hash[64];
    unsigned char sig[POLARSSL_MPI_MAX_SIZE];
    unsigned char tmp_buf[2048];
    size_t pub_len = 0, sig_and_oid_len = 0, sig_len;
    size_t len = 0;
    pk_type_t pk_alg;

    /*
     * Prepare data to be signed in tmp_buf
     */
    c = tmp_buf + sizeof( tmp_buf );

    ASN1_CHK_ADD( len, x509_write_extensions( &c, tmp_buf, ctx->extensions ) );

    if( len )
    {
        ASN1_CHK_ADD( len, asn1_write_len( &c, tmp_buf, len ) );
        ASN1_CHK_ADD( len, asn1_write_tag( &c, tmp_buf, ASN1_CONSTRUCTED |
                                                        ASN1_SEQUENCE ) );

        ASN1_CHK_ADD( len, asn1_write_len( &c, tmp_buf, len ) );
        ASN1_CHK_ADD( len, asn1_write_tag( &c, tmp_buf, ASN1_CONSTRUCTED |
                                                        ASN1_SET ) );

        ASN1_CHK_ADD( len, asn1_write_oid( &c, tmp_buf, OID_PKCS9_CSR_EXT_REQ,
                                          OID_SIZE( OID_PKCS9_CSR_EXT_REQ ) ) );

        ASN1_CHK_ADD( len, asn1_write_len( &c, tmp_buf, len ) );
        ASN1_CHK_ADD( len, asn1_write_tag( &c, tmp_buf, ASN1_CONSTRUCTED |
                                                        ASN1_SEQUENCE ) );
    }

    ASN1_CHK_ADD( len, asn1_write_len( &c, tmp_buf, len ) );
    ASN1_CHK_ADD( len, asn1_write_tag( &c, tmp_buf, ASN1_CONSTRUCTED |
                                                    ASN1_CONTEXT_SPECIFIC ) );

    ASN1_CHK_ADD( pub_len, pk_write_pubkey_der( ctx->key,
                                                tmp_buf, c - tmp_buf ) );
    c -= pub_len;
    len += pub_len;

    /*
     *  Subject  ::=  Name
     */
    ASN1_CHK_ADD( len, x509_write_names( &c, tmp_buf, ctx->subject ) );

    /*
     *  Version  ::=  INTEGER  {  v1(0), v2(1), v3(2)  }
     */
    ASN1_CHK_ADD( len, asn1_write_int( &c, tmp_buf, 0 ) );

    ASN1_CHK_ADD( len, asn1_write_len( &c, tmp_buf, len ) );
    ASN1_CHK_ADD( len, asn1_write_tag( &c, tmp_buf, ASN1_CONSTRUCTED |
                                                    ASN1_SEQUENCE ) );

    /*
     * Prepare signature
     */
    md( md_info_from_type( ctx->md_alg ), c, len, hash );

    pk_alg = pk_get_type( ctx->key );
    if( pk_alg == POLARSSL_PK_ECKEY )
        pk_alg = POLARSSL_PK_ECDSA;

    if( ( ret = pk_sign( ctx->key, ctx->md_alg, hash, 0, sig, &sig_len,
                         f_rng, p_rng ) ) != 0 ||
        ( ret = oid_get_oid_by_sig_alg( pk_alg, ctx->md_alg,
                                        &sig_oid, &sig_oid_len ) ) != 0 )
    {
        return( ret );
    }

    /*
     * Write data to output buffer
     */
    c2 = buf + size;
    ASN1_CHK_ADD( sig_and_oid_len, x509_write_sig( &c2, buf,
                                        sig_oid, sig_oid_len, sig, sig_len ) );

    c2 -= len;
    memcpy( c2, c, len );

    len += sig_and_oid_len;
    ASN1_CHK_ADD( len, asn1_write_len( &c2, buf, len ) );
    ASN1_CHK_ADD( len, asn1_write_tag( &c2, buf, ASN1_CONSTRUCTED |
                                                 ASN1_SEQUENCE ) );

    return( (int) len );
}
Пример #13
0
int DataIO_XVG::ReadData(FileName const& fname, 
                         DataSetList& datasetlist, std::string const& dsname)
{
  std::vector<std::string> Legends;
  BufferedLine infile;

  if (infile.OpenFileRead( fname )) return 1;
  const char* ptr = infile.Line();
  if (ptr == 0) return 1;
  // Skip any comments
  while (ptr != 0 && ptr[0] == '#')
    ptr = infile.Line();
  // Try to get set legends
  while (ptr != 0 && ptr[0] == '@') {
    ArgList line(ptr, " \t");
    if (line.Nargs() > 3 && line[1][0] == 's') {
      std::string legend = line.GetStringKey("legend");
      if (!legend.empty()) {
        // Spaces will cause issues with data set selection.
        for (std::string::iterator s = legend.begin(); s != legend.end(); ++s)
          if (*s == ' ') *s = '_';
        Legends.push_back( legend );
      }
    }
    ptr = infile.Line();
  }
  if (Legends.empty()) {
    mprinterr("Error: No set legends found in XVG file.\n");
    return 1;
  }
  if (ptr == 0) {
    mprinterr("Error: No data in XVG file.\n");
    return 1;
  }
  // Create 1 data set for each legend
  DataSetList::DataListType inputSets;
  for (unsigned int i = 0; i != Legends.size(); i++) {
    MetaData md( dsname, i );
    md.SetLegend( Legends[i] );
    DataSet_double* ds = new DataSet_double();
    if (ds == 0) return 1;
    ds->SetMeta( md );
    inputSets.push_back( ds );
  }
  mprintf("\t%s has %zu columns of data.\n", fname.base(), inputSets.size());
  // Should now be positioned at first line of data. Assume first column is time values.
  DataSetList::Darray Xvals;
  int expectedCols = (int)inputSets.size() + 1;
  while (ptr != 0) {
    int ncols = infile.TokenizeLine(" \t");
    if (ncols != expectedCols)
      mprinterr("Error: Line %i: %i columns != expected # cols %i\n", infile.LineNumber(),
                ncols, expectedCols);
    else {
      Xvals.push_back( atof( infile.NextToken() ) );
      for (unsigned int i = 0; i != inputSets.size(); i++)
        ((DataSet_double*)inputSets[i])->AddElement( atof( infile.NextToken() ) );
    }
    ptr = infile.Line();
  }
  infile.CloseFile();
  return (datasetlist.AddOrAppendSets( "", Xvals, inputSets ));
}
Пример #14
0
// Action_Vector::Init()
Action::RetType Action_Vector::Init(ArgList& actionArgs, ActionInit& init, int debugIn)
{
  DataFile* df = 0;
  std::string filename = actionArgs.GetStringKey("out");
  if (actionArgs.hasKey("trajout")) return DeprecatedErr( "trajout" );
  if (actionArgs.hasKey("trajfmt")) return DeprecatedErr( "trajfmt" );
  if (actionArgs.hasKey("parmout")) return DeprecatedErr( "parmout" );
  ptrajoutput_ = actionArgs.hasKey("ptrajoutput");
  if (ptrajoutput_) {
    if (filename.empty()) {
      mprinterr("Error: 'ptrajoutput' specified but no 'out <filename>' arg given.\n");
      return Action::ERR;
    }
    outfile_ = init.DFL().AddCpptrajFile(filename, "Vector (PTRAJ)");
    if (outfile_ == 0) return Action::ERR;
  } else
    df = init.DFL().AddDataFile( filename, actionArgs );
  bool calc_magnitude = actionArgs.hasKey("magnitude");
  if (calc_magnitude && ptrajoutput_) {
    mprinterr("Error: 'ptrajoutput' and 'magnitude' are incompatible.\n");
    return Action::ERR;
  }
  needBoxInfo_ = false;
  // Deprecated: corrired, corr, ired
  if ( actionArgs.hasKey("principal") ) {
    mode_ = PRINCIPAL_X;
    if ( actionArgs.hasKey("x") ) mode_ = PRINCIPAL_X;
    if ( actionArgs.hasKey("y") ) mode_ = PRINCIPAL_Y;
    if ( actionArgs.hasKey("z") ) mode_ = PRINCIPAL_Z;
  } else if (actionArgs.hasKey("center"))
    mode_ = CENTER;
  else if (actionArgs.hasKey("dipole"))
    mode_ = DIPOLE;
  else if (actionArgs.hasKey("box"))
    mode_ = BOX;
  else if (actionArgs.hasKey("corrplane"))
    mode_ = CORRPLANE;
  else if (actionArgs.hasKey("corrired"))
    return WarnDeprecated();
  else if (actionArgs.hasKey("corr"))
    return WarnDeprecated();
  else if (actionArgs.hasKey("mask"))
    mode_ = MASK;
  else if (actionArgs.hasKey("ucellx"))
    mode_ = BOX_X;
  else if (actionArgs.hasKey("ucelly"))
    mode_ = BOX_Y;
  else if (actionArgs.hasKey("ucellz"))
    mode_ = BOX_Z;
  else if (actionArgs.hasKey("boxcenter"))
    mode_ = BOX_CTR;
  else if (actionArgs.hasKey("minimage"))
    mode_ = MINIMAGE; 
  else
    mode_ = MASK;
  if (mode_ == BOX || mode_ == BOX_X || mode_ == BOX_Y || mode_ == BOX_Z ||
      mode_ == BOX_CTR || mode_ == MINIMAGE)
    needBoxInfo_ = true;
  // Check if IRED vector
  bool isIred = actionArgs.hasKey("ired"); 
  // Vector Mask
  if (mode_ != BOX && mode_ != BOX_X && mode_ != BOX_Y && mode_ != BOX_Z)
    mask_.SetMaskString( actionArgs.GetMaskNext() );
  // Get second mask if necessary
  if (mode_ == MASK || mode_ == MINIMAGE) {
    std::string maskexpr = actionArgs.GetMaskNext();
    if (maskexpr.empty()) {
      mprinterr("Error: Specified vector mode (%s) requires a second mask.\n",
                ModeString[ mode_ ]);
      return Action::ERR;
    }
    mask2_.SetMaskString( maskexpr );
  }
  // Set up vector dataset and IRED status
  MetaData md(actionArgs.GetStringNext(), MetaData::M_VECTOR);
  if (isIred) md.SetScalarType( MetaData::IREDVEC );
  Vec_ = (DataSet_Vector*)init.DSL().AddSet(DataSet::VECTOR, md, "Vec");
  if (Vec_ == 0) return Action::ERR;
  // Add set to output file if not doing ptraj-compatible output
  if (!ptrajoutput_ && df != 0)
    df->AddDataSet( Vec_ );
  // Set up magnitude data set.
  if (calc_magnitude) {
    Magnitude_ = init.DSL().AddSet(DataSet::FLOAT, MetaData(Vec_->Meta().Name(), "Mag"));
    if (Magnitude_ == 0) return Action::ERR;
    if (df != 0) df->AddDataSet( Magnitude_ );
  }
  
  mprintf("    VECTOR: Type %s", ModeString[ mode_ ]);
  if (calc_magnitude)
    mprintf(" (with magnitude)");
  if (isIred)
    mprintf(", IRED");
  if (mask_.MaskStringSet())
     mprintf(", mask [%s]", mask_.MaskString());
  if (mask2_.MaskStringSet())
    mprintf(", second mask [%s]", mask2_.MaskString());
  if (!filename.empty()) {
    if (ptrajoutput_)
      mprintf(", ptraj-compatible output to");
    else
      mprintf(", output to");
    mprintf(" %s", filename.c_str());
  }
  mprintf("\n");

  return Action::OK;
}
Пример #15
0
/*
 * Do an RSA operation, then remove the message padding
 */
int rsa_pkcs1_decrypt( rsa_context *ctx,
                       int mode, size_t *olen,
                       const unsigned char *input,
                       unsigned char *output,
                       size_t output_max_len)
{
    int ret;
    size_t ilen;
    unsigned char *p;
    unsigned char bt;
    unsigned char buf[POLARSSL_MPI_MAX_SIZE];
#if defined(POLARSSL_PKCS1_V21)
    unsigned char lhash[POLARSSL_MD_MAX_SIZE];
    unsigned int hlen;
    const md_info_t *md_info;
    md_context_t md_ctx;
#endif

    ilen = ctx->len;

    if( ilen < 16 || ilen > sizeof( buf ) )
        return( POLARSSL_ERR_RSA_BAD_INPUT_DATA );

    ret = ( mode == RSA_PUBLIC )
          ? rsa_public(  ctx, input, buf )
          : rsa_private( ctx, input, buf );

    if( ret != 0 )
        return( ret );

    p = buf;

    switch( ctx->padding )
    {
        case RSA_PKCS_V15:

            if( *p++ != 0 )
                return( POLARSSL_ERR_RSA_INVALID_PADDING );
            
            bt = *p++;
            if( ( bt != RSA_CRYPT && mode == RSA_PRIVATE ) ||
                ( bt != RSA_SIGN && mode == RSA_PUBLIC ) )
            {
                return( POLARSSL_ERR_RSA_INVALID_PADDING );
            }

            if( bt == RSA_CRYPT )
            {
                while( *p != 0 && p < buf + ilen - 1 )
                    p++;

                if( *p != 0 || p >= buf + ilen - 1 )
                    return( POLARSSL_ERR_RSA_INVALID_PADDING );

                p++;
            }
            else
            {
                while( *p == 0xFF && p < buf + ilen - 1 )
                    p++;

                if( *p != 0 || p >= buf + ilen - 1 )
                    return( POLARSSL_ERR_RSA_INVALID_PADDING );

                p++;
            }

            break;

#if defined(POLARSSL_PKCS1_V21)
        case RSA_PKCS_V21:
            
            if( *p++ != 0 )
                return( POLARSSL_ERR_RSA_INVALID_PADDING );

            md_info = md_info_from_type( ctx->hash_id );
            if( md_info == NULL )
                return( POLARSSL_ERR_RSA_BAD_INPUT_DATA );
                
            hlen = md_get_size( md_info );

            md_init_ctx( &md_ctx, md_info );
            
            // Generate lHash
            //
            md( md_info, lhash, 0, lhash );

            // seed: Apply seedMask to maskedSeed
            //
            mgf_mask( buf + 1, hlen, buf + hlen + 1, ilen - hlen - 1,
                       &md_ctx );

            // DB: Apply dbMask to maskedDB
            //
            mgf_mask( buf + hlen + 1, ilen - hlen - 1, buf + 1, hlen,  
                       &md_ctx );

            p += hlen;
            md_free_ctx( &md_ctx );

            // Check validity
            //
            if( memcmp( lhash, p, hlen ) != 0 )
                return( POLARSSL_ERR_RSA_INVALID_PADDING );

            p += hlen;

            while( *p == 0 && p < buf + ilen )
                p++;

            if( p == buf + ilen )
                return( POLARSSL_ERR_RSA_INVALID_PADDING );

            if( *p++ != 0x01 )
                return( POLARSSL_ERR_RSA_INVALID_PADDING );

            break;
#endif

        default:

            return( POLARSSL_ERR_RSA_INVALID_PADDING );
    }

    if (ilen - (p - buf) > output_max_len)
        return( POLARSSL_ERR_RSA_OUTPUT_TOO_LARGE );

    *olen = ilen - (p - buf);
    memcpy( output, p, *olen );

    return( 0 );
}
Пример #16
0
// NOTE: Currently relatively memory-intensive. Eventually set up so that SecStruct and
// CO_HN_Hbond members exist only for selected residues? Use Map?
Action::RetType Action_DSSP::Setup(ActionSetup& setup) {
  // Set up mask for this parm
  if ( setup.Top().SetupIntegerMask( Mask_ ) ) return Action::ERR;
  if ( Mask_.None() ) {
    mprintf("Warning: DSSP: Mask has no atoms.\n");
    return Action::SKIP;
  }

  // Initially mark all residues already set up as not selected and 
  // reset all atom coordinate indices.
  for (unsigned int res = 0; res != SecStruct_.size(); res++) {
    SecStruct_[res].isSelected = false;
    SecStruct_[res].C  = -1;
    SecStruct_[res].H  = -1;
    SecStruct_[res].N  = -1;
    SecStruct_[res].O  = -1;
    SecStruct_[res].CA = -1;
  }

  // Set up SecStruct for each solute residue
  Range soluteRes = setup.Top().SoluteResidues();
  Nres_ = soluteRes.Back() + 1;
  if (debug_>0) mprintf("\tDSSP: Setting up for %i residues.\n", Nres_);

  // Set up for each residue of the current Parm if not already set-up.
  SSres RES;
  RES.sstype = NONE;
  RES.isSelected = false;
  RES.C  = -1;
  RES.O  = -1;
  RES.N  = -1;
  RES.H  = -1;
  RES.CA = -1;
  RES.CO_HN_Hbond.assign( Nres_, 0 );
  std::fill( RES.SSprob, RES.SSprob + NSSTYPE, 0 );
  RES.resDataSet = 0;
  // Only resize SecStruct if current # residues > previous # residues
  if (Nres_ > (int)SecStruct_.size())
    SecStruct_.resize(Nres_, RES);

  // Go through all atoms in mask. Determine which residues have their C,
  // O, N, or H atoms selected. Store the actual coordinate index 
  // (i.e. atom# * 3) instead of atom # for slight speed gain. 
  for (AtomMask::const_iterator atom = Mask_.begin(); atom!=Mask_.end(); ++atom) {
    int res = setup.Top()[*atom].ResNum();
    // If residue is out of bounds skip it
    if ( res < Nres_ ) {
      //fprintf(stdout,"DEBUG: Atom %i Res %i [%s]\n",*atom,res,P->names[*atom]);
      SecStruct_[res].isSelected = true;
      if (      setup.Top()[*atom].Name() == BB_C_)
        SecStruct_[res].C = (*atom) * 3;
      else if ( setup.Top()[*atom].Name() == BB_O_)
        SecStruct_[res].O = (*atom) * 3;
      else if ( setup.Top()[*atom].Name() == BB_N_)
        SecStruct_[res].N = (*atom) * 3;
      else if ( setup.Top()[*atom].Name() == BB_H_)
        SecStruct_[res].H = (*atom) * 3;
      else if ( setup.Top()[*atom].Name() == BB_CA_)
        SecStruct_[res].CA = (*atom) * 3;
    }
  }

  // For each residue selected in the mask, check if residue is missing atoms. 
  // Set up DataSet if necessary. 
  Nselected_ = 0;
  std::vector<std::string> missingResidues;
  MetaData md(dsetname_, "res");
  DataSet::DataType dt = DataSet::INTEGER;
  if (printString_) dt = DataSet::STRING;
  for (int res = 0; res < Nres_; ++res) {
    if (SecStruct_[res].isSelected) {
      // Check if C-O/N-H selected.
      SecStruct_[res].hasCO = (SecStruct_[res].C != -1 &&
                               SecStruct_[res].O != -1);
      SecStruct_[res].hasNH = (SecStruct_[res].N != -1 &&
                               SecStruct_[res].H != -1);
      if (!SecStruct_[res].hasCO || !SecStruct_[res].hasNH || SecStruct_[res].CA == -1)
      {
        missingResidues.push_back( setup.Top().TruncResNameNum( res ) );
        if (debug_ > 0) {
          mprintf("Warning: Not all BB atoms found for res %s:", missingResidues.back().c_str());
          if (SecStruct_[res].N==-1) mprintf(" N");
          if (SecStruct_[res].H==-1) mprintf(" H");
          if (SecStruct_[res].C==-1) mprintf(" C");
          if (SecStruct_[res].O==-1) mprintf(" O");
          if (SecStruct_[res].CA==-1) mprintf(" CA");
          mprintf("\n");
        }
      }
      // Set up dataset if necessary 
      if (SecStruct_[res].resDataSet == 0) {
        md.SetIdx( res+1 );
        md.SetLegend( setup.Top().TruncResNameNum(res) );
        // Setup dataset for this residue
        SecStruct_[res].resDataSet = Init_.DSL().AddSet( dt, md );
        if (SecStruct_[res].resDataSet == 0) {
          mprinterr("Error: Could not allocate DSSP data set for residue %i\n", res+1);
          return Action::ERR;
        }
        if (outfile_ != 0) outfile_->AddDataSet(SecStruct_[res].resDataSet);
      }
      ++Nselected_;
    }
  }
  if (!missingResidues.empty()) {
    mprintf("Warning: Not all BB atoms found for %u residues:", missingResidues.size());
    for (std::vector<std::string>::const_iterator mr = missingResidues.begin();
                                                  mr != missingResidues.end(); ++mr)
      mprintf(" %s", mr->c_str());
    mprintf("\nInfo: This is expected for Proline and terminal/non-standard residues.\n"
              "Info: Expected BB atom names: N=[%s]  H=[%s]  C=[%s]  O=[%s]  CA=[%s]\n",
            *BB_N_, *BB_H_, *BB_C_, *BB_O_, *BB_CA_ );
    mprintf("Info: Re-run with action debug level >= 1 to see which residues are missing atoms.\n");
  }

  // Count number of selected residues
  mprintf("\tMask [%s] corresponds to %u residues.\n", Mask_.MaskString(), Nselected_);
# ifdef DSSPDEBUG
  // DEBUG - Print atom nums for each residue set up
  for (int res=0; res < Nres_; res++) {
    if (SecStruct_[res].isSelected) {
      mprintf("DEBUG: Res %i", res + 1);
      if (SecStruct_[res].hasCO)
        mprintf(" C=%s O=%s",setup.Top().AtomMaskName(SecStruct_[res].C/3).c_str(),
                             setup.Top().AtomMaskName(SecStruct_[res].O/3).c_str());
      if (SecStruct_[res].hasNH)
        mprintf(" N=%s H=%s",setup.Top().AtomMaskName(SecStruct_[res].N/3).c_str(),
                             setup.Top().AtomMaskName(SecStruct_[res].H/3).c_str());
      if (SecStruct_[res].CA != -1)
        mprintf(" CA=%s",setup.Top().AtomMaskName(SecStruct_[res].CA/3).c_str());
      mprintf("\n");
    }
  }
# endif
  return Action::OK;
}
Пример #17
0
void Scouter::UnitIdle(int unit){
	NLOG("Scouter::UnitIdle");
	if(G->cb->GetUnitDef(unit) == 0) return;
	bool naset = false;
	const UnitDef* ud = G->cb->GetUnitDef(unit);
	if(G->abstract == false){
		// load scouters.txt so that we can get the list of units the modder has defined as scouters
		string filename;
		filename += "NTAI/";
		filename += G->cb->GetModName();
		filename += "/mod.tdf";
		ifstream fp;
		fp.open(filename.c_str(), ios::in);
		char buffer[4000];
		if(fp.is_open() == false){
			G->L.print(" error loading mod.tdf");
		}else{
			char in_char;
			int bsize = 0;
			while(fp.get(in_char)){
				buffer[bsize] = in_char;
				bsize++;
			}
			if(bsize > 0){
				CSunParser md(G);
				md.LoadBuffer(buffer,bsize);
				vector<string> v;
				v = bds::set_cont(v,md.SGetValueMSG("AI\\Scouters"));
				if(v.empty() == false){
					for(vector<string>::iterator vi = v.begin(); vi != v.end(); ++vi){
						if(*vi == ud->name){
							naset = true;
							break;
						}
					}
				}
			}
		}
	}else{
		// determine if this si a scouter or not dynamically
		if((ud->speed > 70)&&(ud->movedata != 0)&&(ud->canfly == false)&&(ud->transportCapacity == 0)&&(ud->isCommander == false)&&(ud->builder == false)) naset = true;
		if((ud->weapons.empty() == true)&&(ud->canfly == true)&&(ud->transportCapacity == 0)&&(ud->isCommander == false)&&(ud->builder == false)) naset = true;
	}
	
	if(naset){
		TCommand tc;
		tc.unit = unit;
		tc.clear = false;
		tc.created = G->cb->GetCurrentFrame();
		tc.Priority = tc_assignment;
		for(int i = G->cb->GetCurrentFrame(); i%46 != 0; i++){
			cp[unit].push_back(cp[unit].front());
			cp[unit].pop_front();
		}
		float3 pos_temp = cp[unit].front();
		tc.c.params.push_back(pos_temp.x);
		tc.c.params.push_back(G->cb->GetElevation(pos_temp.x,pos_temp.z));
		tc.c.params.push_back(pos_temp.z);
		tc.c.params.push_back(40);
		tc.c.timeOut = 10 MINUTES + G->cb->GetCurrentFrame();
		tc.created = G->cb->GetCurrentFrame();
		tc.c.id=CMD_MOVE;
		cp[unit].push_back(cp[unit].front());
		cp[unit].erase(cp[unit].begin());
		G->GiveOrder(tc);
	 }
}
Пример #18
0
// Action_DSSP::Print()
void Action_DSSP::Print() {
  if (dsetname_.empty()) return;
  // Try not to print empty residues. Find the minimum and maximum residue
  // for which there is data. Output res nums start from 1.
  int min_res = -1;
  int max_res = -1;
  for (int resi = 0; resi != (int)SecStruct_.size(); resi++) {
    if (SecStruct_[resi].resDataSet != 0) {
      if (min_res < 0) min_res = resi;
      if (resi > max_res) max_res = resi;
    }
  }
  if (min_res < 0 || max_res < min_res) {
    mprinterr("Error: No residues have SS data.\n");
    return;
  }
  // Calculate average of each SS type across all residues.
  if (dsspFile_ != 0) {
    std::vector<DataSet*> dsspData_(NSSTYPE);
    Dimension Xdim( min_res + 1, 1, "Residue" );
    MetaData md(dsetname_, "avgss", MetaData::NOT_TS);
    // Set up a dataset for each SS type. TODO: NONE type?
    for (int ss = 1; ss < NSSTYPE; ss++) {
      md.SetIdx(ss);
      md.SetLegend( SSname[ss] );
      dsspData_[ss] = Init_.DSL().AddSet(DataSet::DOUBLE, md);
      dsspData_[ss]->SetDim(Dimension::X, Xdim);
      dsspFile_->AddDataSet( dsspData_[ss] ); 
    }
    
    // Calc the avg SS type for each residue that has data.
    int idx = 0; 
    for (int resi = min_res; resi < max_res+1; resi++) {
      if (SecStruct_[resi].resDataSet != 0) {
        for (int ss = 1; ss < NSSTYPE; ss++) {
          double avg = (double)SecStruct_[resi].SSprob[ss];
          avg /= (double)Nframe_;
          dsspData_[ss]->Add(idx, &avg);
        }
        ++idx;
      }
    }
  }
  // Print out SS assignment like PDB
  if (assignout_ != 0) {
      int total = 0;
      int startRes = -1;
      std::string resLine, ssLine;
      for (int resi = min_res; resi < max_res+1; resi++) {
        if (startRes == -1) startRes = resi;
        // Convert residue name.
        resLine += Residue::ConvertResName( SecStruct_[resi].resDataSet->Meta().Legend() );
        // Figure out which SS element is dominant for res if selected
        if (SecStruct_[resi].resDataSet != 0) {
          int dominantType = 0;
          int ssmax = 0;
          for (int ss = 0; ss < NSSTYPE; ss++) {
            if ( SecStruct_[resi].SSprob[ss] > ssmax ) {
              ssmax = SecStruct_[resi].SSprob[ss];
              dominantType = ss;
            }
          }
          ssLine += dssp_char[dominantType];
        } else
          ssLine += '-';
        total++;
        if ((total % 50) == 0 || resi == max_res) {
          assignout_->Printf("%-8i %s\n", startRes+1, resLine.c_str());
          assignout_->Printf("%8s %s\n\n", " ", ssLine.c_str());
          startRes = -1;
          resLine.clear();
          ssLine.clear();
        } else if ((total % 10) == 0) {
          resLine += ' '; 
          ssLine += ' ';
        }
      }
  }
}
Пример #19
0
// A constructor
WIFIWindow::WIFIWindow(wxFrame *frame, const wxString& WiFiServerName):
    wxWindow(frame, wxID_ANY,     wxPoint(20,20), wxSize(5,5), wxSIMPLE_BORDER)

{
    parent_frame = (MyFrame *)frame;
    m_sock = NULL;

    m_pdata_server_string = new wxString(WiFiServerName);

    m_watchtick = 0;
    m_timer_active = false;

//    Decide upon Server source
    wxString msg(_T("WiFi Server is...."));
    msg.Append(*m_pdata_server_string);
    wxLogMessage(msg);

    if(m_pdata_server_string->Contains(_T("TCP/IP")))
    {
        wxString WIFI_data_ip;
        WIFI_data_ip = m_pdata_server_string->Mid(7);         // extract the IP

        if(!WIFI_data_ip.IsEmpty())
        {
// Create the socket
            m_sock = new wxSocketClient();

// Setup the event handler and subscribe to most events
            m_sock->SetEventHandler(*this, WIFI_SOCKET_ID);

            m_sock->SetNotify(wxSOCKET_CONNECTION_FLAG |
                              wxSOCKET_INPUT_FLAG |
                              wxSOCKET_LOST_FLAG);
            m_sock->Notify(TRUE);

            m_busy = FALSE;

//    Build the target address

//    n.b. Win98
//    wxIPV4address::Hostname() uses sockets function gethostbyname() for address resolution
//    Implications...Either name target must exist in c:\windows\hosts, or
//                            a DNS server must be active on the network.
//    If neither true, then wxIPV4address::Hostname() will block (forever?)....
//
//    Workaround....
//    Use a thread to try the name lookup, in case it hangs

            WIFIDNSTestThread *ptest_thread = NULL;
            ptest_thread = new WIFIDNSTestThread(WIFI_data_ip);

            ptest_thread->Run();                      // Run the thread from ::Entry()


//    Sleep and loop for N seconds
#define SLEEP_TEST_SEC  2

            for(int is=0 ; is<SLEEP_TEST_SEC * 10 ; is++)
            {
                wxMilliSleep(100);
                if(wifi_s_dns_test_flag)
                    break;
            }

            if(!wifi_s_dns_test_flag)
            {

                wxString msg(WIFI_data_ip);
                msg.Prepend(_T("Could not resolve TCP/IP host '"));
                msg.Append(_T("'\n Suggestion: Try 'xxx.xxx.xxx.xxx' notation"));
                OCPNMessageDialog md(this, msg, _T("OpenCPN Message"), wxICON_ERROR );
                md.ShowModal();

                m_sock->Notify(FALSE);
                m_sock->Destroy();

                return;
            }

            addr.Hostname(WIFI_data_ip);
            addr.Service(SERVER_PORT);

            // It is considered safe to block GUI during socket IO, since WIFI data activity is infrequent
            m_sock->SetFlags(wxSOCKET_WAITALL | wxSOCKET_BLOCK );
            m_sock->Connect(addr, FALSE);       // Non-blocking connect

            //  Initialize local data stores
            for(int ilocal = 0 ; ilocal < NLOCALSTORE ; ilocal++)
            {
                station_data[ilocal].bisvalid = false;
            }

            Timer1.SetOwner(this, TIMER_WIFI1);
            m_scan_interval_msec = 10000;
            Timer1.Start(m_scan_interval_msec,wxTIMER_CONTINUOUS);
            m_timer_active = true;
        }         // !Isempty()
    }

    Hide();
}
Пример #20
0
// Analysis_Lifetime::Setup()
Analysis::RetType Analysis_Lifetime::Setup(ArgList& analyzeArgs, DataSetList* datasetlist,
                            TopologyList* PFLin, DataFileList* DFLin, int debugIn)
{
  // Get Keywords
  FileName outfileName( analyzeArgs.GetStringKey("out") );
  std::string setname = analyzeArgs.GetStringKey("name");
  bool sortSets = (!analyzeArgs.hasKey("nosort"));
  windowSize_ = analyzeArgs.getKeyInt("window", -1);
  averageonly_ = analyzeArgs.hasKey("averageonly");
  cumulative_ = analyzeArgs.hasKey("cumulative");
  deltaAvg_ = analyzeArgs.hasKey("delta");
  cut_ = analyzeArgs.getKeyDouble("cut", 0.5);
  fuzzCut_ = analyzeArgs.getKeyInt("fuzz", -1);
  if (fuzzCut_ < 1) fuzzCut_ = -1;
  normalizeCurves_ = !analyzeArgs.hasKey("rawcurve");
  if (analyzeArgs.hasKey("greater"))
    Compare_ = Compare_GreaterThan;
  else if (analyzeArgs.hasKey("less"))
    Compare_ = Compare_LessThan;
  else
    Compare_ = Compare_GreaterThan;
  // Select datasets from remaining args
  if (inputDsets_.AddSetsFromArgs( analyzeArgs.RemainingArgs(), *datasetlist )) {
    mprinterr("Error: lifetime: Could not add data sets.\n");
    return Analysis::ERR;
  }
  // Sort data sets
  if (sortSets) inputDsets_.SortArray1D(); 

  // Create output datasets
  DataFile* outfile = 0;
  DataFile* maxfile = 0;
  DataFile* avgfile = 0;
  if (setname.empty())
    setname = datasetlist->GenerateDefaultName( "lifetime" );
  if ( windowSize_ != -1) {
    outfile = DFLin->AddDataFile(outfileName, analyzeArgs);
    if (!averageonly_ && outfile != 0) {
      maxfile = DFLin->AddDataFile(outfileName.DirPrefix() + "max." + 
                                   outfileName.Base(), analyzeArgs);
      avgfile = DFLin->AddDataFile(outfileName.DirPrefix() + "avg." + 
                                   outfileName.Base(), analyzeArgs);
    }
    int didx = 0;
    for (Array1D::const_iterator set = inputDsets_.begin(); set != inputDsets_.end(); ++set)
    {
      MetaData md(setname, didx);
      md.SetLegend( (*set)->Meta().Legend() );
      DataSet_1D* outSet = (DataSet_1D*)datasetlist->AddSet( DataSet::FLOAT, md );
      if (CheckDsetError(outSet, "output", (*set)->legend())) 
        return Analysis::ERR;
      outputDsets_.push_back( outSet );
      if (outfile != 0) outfile->AddDataSet( outSet );
      if (!averageonly_) {
        // MAX
        md.SetAspect("max");
        outSet = (DataSet_1D*)datasetlist->AddSet(DataSet::INTEGER, md);
        if (CheckDsetError(outSet, "lifetime max", (*set)->legend()))
          return Analysis::ERR;
        maxDsets_.push_back( outSet );
        if (maxfile != 0) maxfile->AddDataSet( outSet );
        // AVG
        md.SetAspect("avg");
        outSet = (DataSet_1D*)datasetlist->AddSet(DataSet::FLOAT, md);
        if (CheckDsetError(outSet, "lifetime avg", (*set)->legend()))
          return Analysis::ERR;
        avgDsets_.push_back( outSet );
        if (avgfile != 0) avgfile->AddDataSet( outSet );
      }
      ++didx;
    }
    // Set step to window size.
    std::string fileArgs = "xstep " + integerToString( windowSize_ ); 
    if (outfile != 0) outfile->ProcessArgs( fileArgs );
    if (maxfile != 0) maxfile->ProcessArgs( fileArgs );
    if (avgfile != 0) avgfile->ProcessArgs( fileArgs );
  }
  // Lifetime curves
  DataFile* crvfile = 0;
  if (!averageonly_) {
    if (!outfileName.empty()) {
      crvfile = DFLin->AddDataFile(outfileName.DirPrefix() + "crv." + 
                                   outfileName.Base(), analyzeArgs);
    }
    MetaData md(setname, "curve");
    for (int didx = 0; didx != (int)inputDsets_.size(); didx++)
    {
      md.SetIdx(didx);
      DataSet_1D* outSet = (DataSet_1D*)datasetlist->AddSet(DataSet::DOUBLE, md);
      if (CheckDsetError(outSet, "lifetime curve", inputDsets_[didx]->legend()))
        return Analysis::ERR;
      curveSets_.push_back( outSet );
      if (crvfile != 0) crvfile->AddDataSet( outSet );
    }
  }
  // Non-window output file
  if (!averageonly_ && windowSize_ == -1) {
    standalone_ = DFLin->AddCpptrajFile( outfileName, "Lifetimes", DataFileList::TEXT, true );
    if (standalone_ == 0) return Analysis::ERR;
  } else
    standalone_ = 0; 

  if (!averageonly_)
    mprintf("    LIFETIME: Calculating average lifetime using a cutoff of %f", cut_);
  else
    mprintf("    LIFETIME: Calculating only averages");
  mprintf(" of data in %i sets\n", inputDsets_.size());
  if (!sortSets) mprintf("\tInput data sets will not be sorted.\n");
  if (debugIn > 0)
    for (Array1D::const_iterator set = inputDsets_.begin(); set != inputDsets_.end(); ++set)
      mprintf("\t%s\n", (*set)->legend());
  if (Compare_ == Compare_GreaterThan) 
    mprintf("\tValues greater than %f are considered present.\n", cut_);
  else
    mprintf("\tValues less than %f are considered present.\n", cut_);
  if (windowSize_ != -1) {
    mprintf("\tAverage of data over windows will be saved to sets named %s\n",
            setname.c_str());
    mprintf("\tWindow size for averaging: %i\n", windowSize_);
    if (cumulative_)
      mprintf("\tCumulative averages will be saved.\n");
    if (deltaAvg_)
      mprintf("\tChange of average from previous average will be saved.\n");
  }
  if (outfile != 0) {
    mprintf("\tOutfile: %s", outfile->DataFilename().full());
    if (!averageonly_ && outfile != 0)
      mprintf(", %s, %s", maxfile->DataFilename().base(), avgfile->DataFilename().base());
    mprintf("\n");
  }
  if (!averageonly_) {
    if (crvfile != 0)
      mprintf("\tLifetime curves output: %s\n", crvfile->DataFilename().base());
    if (normalizeCurves_)
      mprintf("\tLifetime curves will be normalized.\n");
    else
      mprintf("\tLifetime curves will not be normalized.\n");
  }
  if (fuzzCut_ != -1)
    mprintf("\tFuzz value of %i frames will be used.\n", fuzzCut_);
  return Analysis::OK;
}
Пример #21
0
static void
rename_dir(const atf_tc_t *tc, const char *mp)
{
	char pb1[MAXPATHLEN], pb2[MAXPATHLEN], pb3[MAXPATHLEN];
	struct stat ref, sb;

	if (FSTYPE_RUMPFS(tc))
		atf_tc_skip("rename not supported by file system");

	USES_DIRS;

	md(pb1, mp, "dir1");
	if (rump_sys_mkdir(pb1, 0777) == -1)
		atf_tc_fail_errno("mkdir 1");

	md(pb2, mp, "dir2");
	if (rump_sys_mkdir(pb2, 0777) == -1)
		atf_tc_fail_errno("mkdir 2");
	md(pb2, mp, "dir2/subdir");
	if (rump_sys_mkdir(pb2, 0777) == -1)
		atf_tc_fail_errno("mkdir 3");

	md(pb3, mp, "dir1/file");
	if (rump_sys_mknod(pb3, S_IFREG | 0777, -1) == -1)
		atf_tc_fail_errno("create file");
	if (rump_sys_stat(pb3, &ref) == -1)
		atf_tc_fail_errno("stat of file");

	/*
	 * First try ops which should succeed.
	 */

	/* rename within directory */
	md(pb3, mp, "dir3");
	if (rump_sys_rename(pb1, pb3) == -1)
		atf_tc_fail_errno("rename 1");
	checkfile(pb3, &ref);

	/* rename directory onto itself (two ways, should fail) */
	md(pb1, mp, "dir3/.");
	if (rump_sys_rename(pb1, pb3) != -1 || errno != EINVAL)
		atf_tc_fail_errno("rename 2");
	if (FSTYPE_ZFS(tc))
		atf_tc_expect_fail("PR kern/47656: Test known to be broken");
	if (rump_sys_rename(pb3, pb1) != -1 || errno != EISDIR)
		atf_tc_fail_errno("rename 3");

	checkfile(pb3, &ref);

	/* rename father of directory into directory */
	md(pb1, mp, "dir2/dir");
	md(pb2, mp, "dir2");
	if (rump_sys_rename(pb2, pb1) != -1 || errno != EINVAL)
		atf_tc_fail_errno("rename 4");

	/* same for grandfather */
	md(pb1, mp, "dir2/subdir/dir2");
	if (rump_sys_rename(pb2, pb1) != -1 || errno != EINVAL)
		atf_tc_fail("rename 5");

	checkfile(pb3, &ref);

	/* rename directory over a non-empty directory */
	if (rump_sys_rename(pb2, pb3) != -1 || errno != ENOTEMPTY)
		atf_tc_fail("rename 6");

	/* cross-directory rename */
	md(pb1, mp, "dir3");
	md(pb2, mp, "dir2/somedir");
	if (rump_sys_rename(pb1, pb2) == -1)
		atf_tc_fail_errno("rename 7");
	checkfile(pb2, &ref);

	/* move to parent directory */
	md(pb1, mp, "dir2/somedir/../../dir3");
	if (rump_sys_rename(pb2, pb1) == -1)
		atf_tc_fail_errno("rename 8");
	md(pb1, mp, "dir2/../dir3");
	checkfile(pb1, &ref);

	/* atomic cross-directory rename */
	md(pb3, mp, "dir2/subdir");
	if (rump_sys_rename(pb1, pb3) == -1)
		atf_tc_fail_errno("rename 9");
	checkfile(pb3, &ref);

	/* rename directory over an empty directory */
	md(pb1, mp, "parent");
	md(pb2, mp, "parent/dir1");
	md(pb3, mp, "parent/dir2");
	RL(rump_sys_mkdir(pb1, 0777));
	RL(rump_sys_mkdir(pb2, 0777));
	RL(rump_sys_mkdir(pb3, 0777));
	RL(rump_sys_rename(pb2, pb3));

	RL(rump_sys_stat(pb1, &sb));
	if (! FSTYPE_MSDOS(tc))
		ATF_CHECK_EQ(sb.st_nlink, 3);
	RL(rump_sys_rmdir(pb3));
	RL(rump_sys_rmdir(pb1));
}
Пример #22
0
/*
 * Implementation of the PKCS#1 v2.1 RSAES-OAEP-ENCRYPT function
 */
int rsa_rsaes_oaep_encrypt( rsa_context *ctx,
                            int (*f_rng)(void *, unsigned char *, size_t),
                            void *p_rng,
                            int mode,
                            const unsigned char *label, size_t label_len,
                            size_t ilen,
                            const unsigned char *input,
                            unsigned char *output )
{
    size_t olen;
    int ret;
    unsigned char *p = output;
    unsigned int hlen;
    const md_info_t *md_info;
    md_context_t md_ctx;

    if( ctx->padding != RSA_PKCS_V21 || f_rng == NULL )
        return( POLARSSL_ERR_RSA_BAD_INPUT_DATA );

    md_info = md_info_from_type( ctx->hash_id );

    if( md_info == NULL )
        return( POLARSSL_ERR_RSA_BAD_INPUT_DATA );

    olen = ctx->len;
    hlen = md_get_size( md_info );

    if( olen < ilen + 2 * hlen + 2 || f_rng == NULL )
        return( POLARSSL_ERR_RSA_BAD_INPUT_DATA );

    memset( output, 0, olen );

    *p++ = 0;

    // Generate a random octet string seed
    //
    if( ( ret = f_rng( p_rng, p, hlen ) ) != 0 )
        return( POLARSSL_ERR_RSA_RNG_FAILED + ret );

    p += hlen;

    // Construct DB
    //
    md( md_info, label, label_len, p );
    p += hlen;
    p += olen - 2 * hlen - 2 - ilen;
    *p++ = 1;
    memcpy( p, input, ilen );

    md_init_ctx( &md_ctx, md_info );

    // maskedDB: Apply dbMask to DB
    //
    mgf_mask( output + hlen + 1, olen - hlen - 1, output + 1, hlen,
               &md_ctx );

    // maskedSeed: Apply seedMask to seed
    //
    mgf_mask( output + 1, hlen, output + hlen + 1, olen - hlen - 1,
               &md_ctx );

    md_free_ctx( &md_ctx );

    return( ( mode == RSA_PUBLIC )
            ? rsa_public(  ctx, output, output )
            : rsa_private( ctx, f_rng, p_rng, output, output ) );
}
void MainWindow::onMetaData()
{
    MetaDataDialog md(mediaPlayer_);
    md.exec();
}
Пример #24
0
/*
 * Implementation of the PKCS#1 v2.1 RSAES-OAEP-DECRYPT function
 */
int rsa_rsaes_oaep_decrypt( rsa_context *ctx,
                            int (*f_rng)(void *, unsigned char *, size_t),
                            void *p_rng,
                            int mode,
                            const unsigned char *label, size_t label_len,
                            size_t *olen,
                            const unsigned char *input,
                            unsigned char *output,
                            size_t output_max_len )
{
    int ret;
    size_t ilen;
    unsigned char *p;
    unsigned char buf[POLARSSL_MPI_MAX_SIZE];
    unsigned char lhash[POLARSSL_MD_MAX_SIZE];
    unsigned int hlen;
    const md_info_t *md_info;
    md_context_t md_ctx;

    if( ctx->padding != RSA_PKCS_V21 )
        return( POLARSSL_ERR_RSA_BAD_INPUT_DATA );

    ilen = ctx->len;

    if( ilen < 16 || ilen > sizeof( buf ) )
        return( POLARSSL_ERR_RSA_BAD_INPUT_DATA );

    ret = ( mode == RSA_PUBLIC )
          ? rsa_public(  ctx, input, buf )
          : rsa_private( ctx, f_rng, p_rng, input, buf );

    if( ret != 0 )
        return( ret );

    p = buf;

    if( *p++ != 0 )
        return( POLARSSL_ERR_RSA_INVALID_PADDING );

    md_info = md_info_from_type( ctx->hash_id );
    if( md_info == NULL )
        return( POLARSSL_ERR_RSA_BAD_INPUT_DATA );

    hlen = md_get_size( md_info );

    md_init_ctx( &md_ctx, md_info );

    // Generate lHash
    //
    md( md_info, label, label_len, lhash );

    // seed: Apply seedMask to maskedSeed
    //
    mgf_mask( buf + 1, hlen, buf + hlen + 1, ilen - hlen - 1,
               &md_ctx );

    // DB: Apply dbMask to maskedDB
    //
    mgf_mask( buf + hlen + 1, ilen - hlen - 1, buf + 1, hlen,
               &md_ctx );

    p += hlen;
    md_free_ctx( &md_ctx );

    // Check validity
    //
    if( memcmp( lhash, p, hlen ) != 0 )
        return( POLARSSL_ERR_RSA_INVALID_PADDING );

    p += hlen;

    while( *p == 0 && p < buf + ilen )
        p++;

    if( p == buf + ilen )
        return( POLARSSL_ERR_RSA_INVALID_PADDING );

    if( *p++ != 0x01 )
        return( POLARSSL_ERR_RSA_INVALID_PADDING );

    if (ilen - (p - buf) > output_max_len)
        return( POLARSSL_ERR_RSA_OUTPUT_TOO_LARGE );

    *olen = ilen - (p - buf);
    memcpy( output, p, *olen );

    return( 0 );
}
Пример #25
0
/*
 * This first function contains the code common to both
 * Export() and ExportLossy()
 *
 * For safety, if the file already exists it stores the filename
 * the user wants in actualName, and returns a temporary file name.
 * The calling function should rename the file when it's successfully
 * exported.
 */
wxString ExportCommon( AudacityProject *project, wxString format,
                       wxString defaultExtension, bool selectionOnly, double *t0, double *t1,
                       int *numChannels, wxString &actualName, int maxNumChannels,
                       MixerSpec **mixerSpec )
{
    TrackList *tracks = project->GetTracks();

    /* First analyze the selected audio, perform sanity checks, and provide
     * information as appropriate. */

    /* Tally how many are right, left, mono, and make sure at
       least one track is selected (if selectionOnly==true) */

    int numSelected = 0, numLeft = 0, numRight = 0, numMono = 0;
    float earliestBegin = *t1;
    float latestEnd = *t0;

    TrackListIterator iter1(tracks);
    Track *tr = iter1.First();

    while (tr) {
        if (tr->GetKind() == Track::Wave) {
            if (tr->GetSelected() || !selectionOnly) {

                numSelected++;

                if (tr->GetChannel() == Track::LeftChannel)
                    numLeft++;
                else if (tr->GetChannel() == Track::RightChannel)
                    numRight++;
                else if (tr->GetChannel() == Track::MonoChannel) {
                    // It's a mono channel, but it may be panned
                    float pan = ((WaveTrack*)tr)->GetPan();

                    if (pan == -1.0)
                        numLeft++;
                    else if (pan == 1.0)
                        numRight++;
                    else if (pan == 0)
                        numMono++;
                    else {
                        // Panned partially off-center. Mix as stereo.
                        numLeft++;
                        numRight++;
                    }
                }
                if(tr->GetOffset() < earliestBegin)
                    earliestBegin = tr->GetOffset();

                if(tr->GetEndTime() > latestEnd)
                    latestEnd = tr->GetEndTime();

            }
        }

        tr = iter1.Next();
    }

    if(*t0 < earliestBegin)
        *t0 = earliestBegin;

    if(*t1 > latestEnd)
        *t1 = latestEnd;

    if (numSelected == 0 && selectionOnly) {
        wxMessageBox(_("No tracks are selected! Use Ctrl-A (Select All)\nChoose Export... to export all tracks."),
                     _("Unable to export"),
                     wxOK | wxICON_INFORMATION);

        return wxT("");
    }

    /* Detemine if exported file will be stereo or mono or multichannel,
       and if mixing will occur */

    bool downMix = (gPrefs->Read( wxT("/FileFormats/ExportDownMix" ), true ) !=0) ? true:false ;

    int channels;
    if( downMix || !mixerSpec )
    {
        if (numRight > 0 || numLeft > 0)
            channels = 2;
        else
            channels = 1;

        numRight += numMono;
        numLeft += numMono;

        if (numLeft > 1 || numRight > 1)
            if (channels == 2) {
                ShowWarningDialog(project, wxT("MixStereo"),
                                  _("Your tracks will be mixed down to two stereo channels in the exported file."));
            }
            else {
                ShowWarningDialog(project, wxT("MixMono"),
                                  _("Your tracks will be mixed down to a single mono channel in the exported file."));
            }
    }
    else
    {
        ExportMixerDialog md( tracks, selectionOnly, maxNumChannels, NULL,
                              1, _( "Advanced Mixing Options" ) );

        if( md.ShowModal() != wxID_OK )
            return wxT( "" );

        *mixerSpec = new MixerSpec( *( md.GetMixerSpec() ) );
        channels = ( *mixerSpec )->GetNumChannels();
    }

    /* Prepare and display the filename selection dialog */

    wxString path = gPrefs->Read(wxT("/DefaultExportPath"),
                                 ::wxGetCwd());
    wxString nameOnly;
    wxString extension;
    wxString defaultName = project->GetName();
    wxString fName;
    wxString maskString;
    wxString endOfPathSep;

#if 0 // this code shouldn't be here --dmazzoni
    //MERGE exercise exception
    if (defaultName == wxT("ThrowExceptionOnExport")) {  //lda
        throw("Exercise exception");
    }
#endif

    if (defaultExtension.Left(1) == wxT("."))
        defaultExtension =
            defaultExtension.Right(defaultExtension.Length()-1);

    maskString.Printf(wxT("%s files (*.%s)|*.%s|All files (*.*)|*.*"), format.c_str(),
                      defaultExtension.c_str(), defaultExtension.c_str());

    bool fileOkay;

    do {
        fileOkay = true;

        fName = defaultName + wxT(".") + defaultExtension;
        fName = wxFileSelector(wxString::Format(_("Save %s File As:"),
                                                format.c_str()),
                               path,
                               fName,       // default file name
                               defaultExtension,
                               maskString,
                               wxSAVE | wxOVERWRITE_PROMPT);

        if (fName.Length() >= 256) {
            wxMessageBox
            (_("Sorry, pathnames longer than 256 characters not supported."));
            return wxT("");
        }

        if (fName == wxT(""))
            return wxT("");

        ::wxSplitPath(fName, &path, &nameOnly, &extension);

        //
        // Make sure the user doesn't accidentally save the file
        // as an extension with no name, like just plain ".wav".
        //

        if ((nameOnly.Left(1)==wxT(".") && extension==wxT("")) ||
                (nameOnly==wxT("") && extension!=wxT(""))) {
            wxString prompt =
                _("Are you sure you want to save the file as \"")+
                ::wxFileNameFromPath(fName)+wxT("\"?\n");

            int action = wxMessageBox(prompt,
                                      wxT("Warning"),
                                      wxYES_NO | wxICON_EXCLAMATION,
                                      project);

            fileOkay = (action == wxYES);
            continue;
        }

        //
        // Check the extension - add the default if it's not there,
        // and warn user if it's abnormal.
        //

        wxString defaultExtension3 = defaultExtension;
        if (defaultExtension.Length() > 3)
            defaultExtension = defaultExtension.Left(3);

        if (extension == wxT("")) {
#ifdef __WXMSW__
            // Windows prefers 3-char uppercase extensions
            extension = defaultExtension;
#else
            // Linux and Mac prefer lowercase extensions
            extension = defaultExtension.Lower();
#endif
        }
        else if (extension.Upper() != defaultExtension.Upper() &&
                 extension.Upper() != defaultExtension3.Upper()) {
#ifdef __WXMSW__
            // Windows prefers 3-char extensions
            defaultExtension3 = defaultExtension3;
#endif

            wxString prompt;
            prompt.Printf(_("You are about to save a %s file with the name %s.\nNormally these files end in %s, and some programs will not open files with nonstandard extensions.\nAre you sure you want to save the file under this name?"),
                          format.c_str(),
                          (wxT("\"")+nameOnly+wxT(".")+extension+wxT("\"")).c_str(),
                          (wxT("\".")+defaultExtension+wxT("\"")).c_str());

            int action = wxMessageBox(prompt,
                                      wxT("Warning"),
                                      wxYES_NO | wxICON_EXCLAMATION,
                                      project);

            if (action == wxYES)
                fileOkay = true;
            else {
                fileOkay = false;
                defaultName = nameOnly + wxT(".") + extension;
            }
        }

        if (path.Length() > 0 && path.Last() == wxFILE_SEP_PATH)
            endOfPathSep = wxT("");
        else
            endOfPathSep = wxFILE_SEP_PATH;

        fName = path + endOfPathSep +
                nameOnly + wxT(".") + extension;
    } while(!fileOkay);

    /*
     * Ensure that exporting a file by this name doesn't overwrite
     * one of the existing files in the project.  (If it would
     * overwrite an existing file, DirManager tries to rename the
     * existing file.)
     */

    if (!project->GetDirManager()->EnsureSafeFilename(wxFileName(fName)))
        return wxT("");

    gPrefs->Write(wxT("/DefaultExportPath"), path);

    *numChannels = channels;

    /*
     * To be even MORE safe, return a temporary file name based
     * on this one...
     */

    actualName = fName;

    int suffix = 0;
    while(::wxFileExists(fName)) {
        fName = path + endOfPathSep +
                nameOnly + wxString::Format(wxT("%d"), suffix) + wxT(".") + extension;
        suffix++;
    }

    return fName;
}
Пример #26
0
 void error(const QString &text, QWidget *parent)
 {
     MessageDialog md(QMessageBox::Critical, QObject::tr("Error"), text, QMessageBox::Ok, parent);
     md.connect(md.button(QMessageBox::Ok), &QPushButton::clicked, &md, &QMessageBox::accept);
     md.exec();
 }
Пример #27
0
// Analysis_TI::Setup()
Analysis::RetType Analysis_TI::Setup(ArgList& analyzeArgs, AnalysisSetup& setup, int debugIn)
{
  debug_ = debugIn;
  int nq = analyzeArgs.getKeyInt("nq", 0);
  ArgList nskipArg(analyzeArgs.GetStringKey("nskip"), ","); // Comma-separated
  avg_increment_ = analyzeArgs.getKeyInt("avgincrement", -1);
  avg_max_ = analyzeArgs.getKeyInt("avgmax", -1);
  avg_skip_ = analyzeArgs.getKeyInt("avgskip", 0);
  n_bootstrap_pts_ = analyzeArgs.getKeyInt("bs_pts", -1);
  n_bootstrap_samples_ = analyzeArgs.getKeyInt("bs_samples", 0);
  bootstrap_seed_ = analyzeArgs.getKeyInt("bs_seed", -1);
  bootstrap_fac_ = analyzeArgs.getKeyDouble("bs_fac", 0.75);
  if (!nskipArg.empty()) {
    avgType_ = SKIP;
    // Specified numbers of points to skip
    nskip_.clear();
    for (int i = 0; i != nskipArg.Nargs(); i++) {
      nskip_.push_back( nskipArg.getNextInteger(0) );
      if (nskip_.back() < 0) nskip_.back() = 0;
    }
  } else if (avg_increment_ > 0)
    avgType_ = INCREMENT;
  else if (n_bootstrap_samples_ > 0)
    avgType_ = BOOTSTRAP;
  else
    avgType_ = AVG;
  masterDSL_ = setup.DslPtr();
  // Get lambda values
  ArgList xArgs(analyzeArgs.GetStringKey("xvals"), ","); // Also comma-separated
  if (!xArgs.empty()) {
    xval_.clear();
    for (int i = 0; i != xArgs.Nargs(); i++)
      xval_.push_back( xArgs.getNextDouble(0.0) );
  }
  std::string setname = analyzeArgs.GetStringKey("name");
  DataFile* outfile = setup.DFL().AddDataFile(analyzeArgs.GetStringKey("out"), analyzeArgs);
  curveout_ = setup.DFL().AddDataFile(analyzeArgs.GetStringKey("curveout"), analyzeArgs);
  // Select datasets from remaining args
  if (input_dsets_.AddSetsFromArgs( analyzeArgs.RemainingArgs(), setup.DSL() )) {
    mprinterr("Error: Could not add data sets.\n");
    return Analysis::ERR;
  }
  if (input_dsets_.empty()) {
    mprinterr("Error: No input data sets.\n");
    return Analysis::ERR;
  }
  if (SetQuadAndWeights(nq)) return Analysis::ERR;
  // Determine integration mode
  if (nq > 0)
    mode_ = GAUSSIAN_QUAD;
  else
    mode_ = TRAPEZOID;
  // Check that # abscissas matches # data sets
  if (xval_.size() != input_dsets_.size()) {
     mprinterr("Error: Expected %zu data sets for integration, got %zu\n",
               input_dsets_.size(), xval_.size());
    return Analysis::ERR;
  }
  // Set up output data sets
  DataSet::DataType dtype = DataSet::DOUBLE;
  if (avgType_ == SKIP || avgType_ == INCREMENT)
    dtype = DataSet::XYMESH;
  dAout_ = setup.DSL().AddSet(dtype, setname, "TI");
  if (dAout_ == 0) return Analysis::ERR;
  if (outfile != 0) outfile->AddDataSet( dAout_ );
  MetaData md(dAout_->Meta().Name(), "TIcurve");
  if (avgType_ == AVG) {
    // Single curve
    curve_.push_back( setup.DSL().AddSet(DataSet::XYMESH, md) );
    if (curve_.back() == 0) return Analysis::ERR;
    curve_.back()->ModifyDim(Dimension::X).SetLabel("Lambda");
    if (curveout_ != 0) curveout_->AddDataSet( curve_.back() );
    if (outfile != 0) outfile->ProcessArgs("noxcol");
  } else if (avgType_ == SKIP) {
    // As many curves as skip values
    for (Iarray::const_iterator it = nskip_.begin(); it != nskip_.end(); ++it) {
      md.SetIdx( *it );
      DataSet* ds = setup.DSL().AddSet(DataSet::XYMESH, md);
      if (ds == 0) return Analysis::ERR;
      ds->ModifyDim(Dimension::X).SetLabel("Lambda");
      ds->SetLegend( md.Name() + "_Skip" + integerToString(*it) );
      if (curveout_ != 0) curveout_->AddDataSet( ds );
      curve_.push_back( ds );
    }
  } else if (avgType_ == BOOTSTRAP) {
    // As many curves as resamples
    for (int nsample = 0; nsample != n_bootstrap_samples_; nsample++) {
      md.SetIdx(nsample);
      DataSet* ds = setup.DSL().AddSet(DataSet::XYMESH, md);
      if (ds == 0) return Analysis::ERR;
      ds->ModifyDim(Dimension::X).SetLabel("Lambda");
      ds->SetLegend( md.Name() + "_Sample" + integerToString(nsample) );
      if (curveout_ != 0) curveout_->AddDataSet( ds );
      curve_.push_back( ds );
    }
    // Standard devation of avg free energy over samples
    dA_SD_ = setup.DSL().AddSet(DataSet::DOUBLE, MetaData(md.Name(), "SD"));
    if (dA_SD_ == 0) return Analysis::ERR;
    if (outfile != 0) {
      outfile->AddDataSet( dA_SD_ );
      outfile->ProcessArgs("noxcol");
    }
  }
  // NOTE: INCREMENT is set up once data set size is known 

  mprintf("    TI: Calculating TI");
  if (mode_ == GAUSSIAN_QUAD) {
    mprintf(" using Gaussian quadrature with %zu points.\n", xval_.size());
    mprintf("\t%6s %8s %8s %s\n", "Point", "Abscissa", "Weight", "SetName");
    for (unsigned int i = 0; i != xval_.size(); i++)
      mprintf("\t%6i %8.5f %8.5f %s\n", i, xval_[i], wgt_[i], input_dsets_[i]->legend());
  } else {
    mprintf(" using the trapezoid rule.\n");
    mprintf("\t%6s %8s %s\n", "Point", "Abscissa", "SetName");
    for (unsigned int i = 0; i != xval_.size(); i++)
      mprintf("\t%6i %8.5f %s\n", i, xval_[i], input_dsets_[i]->legend());
  }
  mprintf("\tResult(s) of integration(s) saved in set '%s'\n", dAout_->legend());
  if (avgType_ == AVG)
    mprintf("\tUsing all data points in <DV/DL> calc.\n");
  else if (avgType_ == SKIP) {
    mprintf("\tSkipping first");
    for (Iarray::const_iterator it = nskip_.begin(); it != nskip_.end(); ++it)
      mprintf(" %i", *it);
    mprintf(" data points for <DV/DL> calc.\n");
  } else if (avgType_ == INCREMENT) {
    mprintf("\tCalculating <DV/DL> starting from point %i, increment by %i.",
            avg_skip_, avg_increment_);
    if (avg_max_ != -1)
      mprintf(" Max %i points.", avg_max_);
    mprintf("\n");
  } else if (avgType_ == BOOTSTRAP) {
    mprintf("\tStandard devation of result stored in set '%s'\n", dA_SD_->legend());
    mprintf("\tCalculating <DV/DL> from %i bootstrap resamples.\n", n_bootstrap_samples_);
    if (n_bootstrap_pts_ > 0)
      mprintf("\tBootstrap resample size is %i data points.\n", n_bootstrap_pts_);
    else
      mprintf("\tWill use bootstrap resample size of %g%% of total points.\n",
              bootstrap_fac_*100.0);
    if (bootstrap_seed_ != -1)
      mprintf("\tBoostrap base seed is %i\n", bootstrap_seed_);
  }
  mprintf("\tTI curve(s) saved in set(s)");
  if (avgType_ != INCREMENT)
    for (DSarray::const_iterator ds = curve_.begin(); ds != curve_.end(); ++ds)
      mprintf(" '%s'", (*ds)->legend());
  else
    mprintf(" named '%s'", md.PrintName().c_str());
  mprintf("\n");
  if (outfile != 0) mprintf("\tResults written to '%s'\n", outfile->DataFilename().full());
  if (curveout_!= 0) mprintf("\tTI curve(s) written to '%s'\n", curveout_->DataFilename().full());

  return Analysis::OK;
}
Пример #28
0
/*
 * Add the message padding, then do an RSA operation
 */
int rsa_pkcs1_encrypt( rsa_context *ctx,
                       int (*f_rng)(void *, unsigned char *, size_t),
                       void *p_rng,
                       int mode, size_t ilen,
                       const unsigned char *input,
                       unsigned char *output )
{
    size_t nb_pad, olen;
    int ret;
    unsigned char *p = output;
#if defined(POLARSSL_PKCS1_V21)
    unsigned int hlen;
    const md_info_t *md_info;
    md_context_t md_ctx;
#endif

    olen = ctx->len;

    if( f_rng == NULL )
        return( POLARSSL_ERR_RSA_BAD_INPUT_DATA );

    switch( ctx->padding )
    {
        case RSA_PKCS_V15:

            if( olen < ilen + 11 )
                return( POLARSSL_ERR_RSA_BAD_INPUT_DATA );

            nb_pad = olen - 3 - ilen;

            *p++ = 0;
            if( mode == RSA_PUBLIC )
            {
                *p++ = RSA_CRYPT;

                while( nb_pad-- > 0 )
                {
                    int rng_dl = 100;

                    do {
                        ret = f_rng( p_rng, p, 1 );
                    } while( *p == 0 && --rng_dl && ret == 0 );

                    // Check if RNG failed to generate data
                    //
                    if( rng_dl == 0 || ret != 0)
                        return POLARSSL_ERR_RSA_RNG_FAILED + ret;

                    p++;
                }
            }
            else
            {
                *p++ = RSA_SIGN;

                while( nb_pad-- > 0 )
                    *p++ = 0xFF;
            }

            *p++ = 0;
            memcpy( p, input, ilen );
            break;
        
#if defined(POLARSSL_PKCS1_V21)
        case RSA_PKCS_V21:

            md_info = md_info_from_type( ctx->hash_id );
            if( md_info == NULL )
                return( POLARSSL_ERR_RSA_BAD_INPUT_DATA );

            hlen = md_get_size( md_info );

            if( olen < ilen + 2 * hlen + 2 || f_rng == NULL )
                return( POLARSSL_ERR_RSA_BAD_INPUT_DATA );

            memset( output, 0, olen );

            *p++ = 0;

            // Generate a random octet string seed
            //
            if( ( ret = f_rng( p_rng, p, hlen ) ) != 0 )
                return( POLARSSL_ERR_RSA_RNG_FAILED + ret );

            p += hlen;

            // Construct DB
            //
            md( md_info, p, 0, p );
            p += hlen;
            p += olen - 2 * hlen - 2 - ilen;
            *p++ = 1;
            memcpy( p, input, ilen ); 

            md_init_ctx( &md_ctx, md_info );

            // maskedDB: Apply dbMask to DB
            //
            mgf_mask( output + hlen + 1, olen - hlen - 1, output + 1, hlen,  
                       &md_ctx );

            // maskedSeed: Apply seedMask to seed
            //
            mgf_mask( output + 1, hlen, output + hlen + 1, olen - hlen - 1,  
                       &md_ctx );

            md_free_ctx( &md_ctx );
            break;
#endif

        default:

            return( POLARSSL_ERR_RSA_INVALID_PADDING );
    }

    return( ( mode == RSA_PUBLIC )
            ? rsa_public(  ctx, output, output )
            : rsa_private( ctx, output, output ) );
}
Пример #29
0
int state_scrub(struct snapraid_state* state, int plan, int olderthan)
{
	block_off_t blockmax;
	block_off_t countlimit;
	block_off_t i;
	block_off_t count;
	time_t recentlimit;
	int ret;
	struct snapraid_parity_handle parity_handle[LEV_MAX];
	struct snapraid_plan ps;
	time_t* timemap;
	unsigned error;
	time_t now;
	unsigned l;

	/* get the present time */
	now = time(0);

	msg_progress("Initializing...\n");

	if ((plan == SCRUB_BAD || plan == SCRUB_NEW || plan == SCRUB_FULL)
		&& olderthan >= 0) {
		/* LCOV_EXCL_START */
		log_fatal("You can specify -o, --older-than only with a numeric percentage.\n");
		exit(EXIT_FAILURE);
		/* LCOV_EXCL_STOP */
	}

	blockmax = parity_allocated_size(state);

	/* preinitialize to avoid warnings */
	countlimit = 0;
	recentlimit = 0;

	ps.state = state;
	if (state->opt.force_scrub_even) {
		ps.plan = SCRUB_EVEN;
	} else if (plan == SCRUB_FULL) {
		ps.plan = SCRUB_FULL;
	} else if (plan == SCRUB_NEW) {
		ps.plan = SCRUB_NEW;
	} else if (plan == SCRUB_BAD) {
		ps.plan = SCRUB_BAD;
	} else if (state->opt.force_scrub_at) {
		/* scrub the specified amount of blocks */
		ps.plan = SCRUB_AUTO;
		countlimit = state->opt.force_scrub_at;
		recentlimit = now;
	} else {
		ps.plan = SCRUB_AUTO;
		if (plan >= 0) {
			countlimit = md(blockmax, plan, 100);
		} else {
			/* by default scrub 8.33% of the array (100/12=8.(3)) */
			countlimit = md(blockmax, 1, 12);
		}

		if (olderthan >= 0) {
			recentlimit = now - olderthan * 24 * 3600;
		} else {
			/* by default use a 10 day time limit */
			recentlimit = now - 10 * 24 * 3600;
		}
	}

	/* identify the time limit */
	/* we sort all the block times, and we identify the time limit for which we reach the quota */
	/* this allow to process first the oldest blocks */
	timemap = malloc_nofail(blockmax * sizeof(time_t));

	/* copy the info in the temp vector */
	count = 0;
	log_tag("block_count:%u\n", blockmax);
	for (i = 0; i < blockmax; ++i) {
		snapraid_info info = info_get(&state->infoarr, i);

		/* skip unused blocks */
		if (info == 0)
			continue;

		timemap[count++] = info_get_time(info);
	}

	if (!count) {
		/* LCOV_EXCL_START */
		log_fatal("The array appears to be empty.\n");
		exit(EXIT_FAILURE);
		/* LCOV_EXCL_STOP */
	}

	/* sort it */
	qsort(timemap, count, sizeof(time_t), time_compare);

	/* output the info map */
	i = 0;
	log_tag("info_count:%u\n", count);
	while (i < count) {
		unsigned j = i + 1;
		while (j < count && timemap[i] == timemap[j])
			++j;
		log_tag("info_time:%" PRIu64 ":%u\n", (uint64_t)timemap[i], j - i);
		i = j;
	}

	/* compute the limits from count/recentlimit */
	if (ps.plan == SCRUB_AUTO) {
		/* no more than the full count */
		if (countlimit > count)
			countlimit = count;

		/* decrease until we reach the specific recentlimit */
		while (countlimit > 0 && timemap[countlimit - 1] > recentlimit)
			--countlimit;

		/* if there is something to scrub */
		if (countlimit > 0) {
			/* get the most recent time we want to scrub */
			ps.timelimit = timemap[countlimit - 1];

			/* count how many entries for this exact time we have to scrub */
			/* if the blocks have all the same time, we end with countlimit == lastlimit */
			ps.lastlimit = 1;
			while (countlimit > ps.lastlimit && timemap[countlimit - ps.lastlimit - 1] == ps.timelimit)
				++ps.lastlimit;
		} else {
			/* if nothing to scrub, disable also other limits */
			ps.timelimit = 0;
			ps.lastlimit = 0;
		}

		log_tag("count_limit:%u\n", countlimit);
		log_tag("time_limit:%" PRIu64 "\n", (uint64_t)ps.timelimit);
		log_tag("last_limit:%u\n", ps.lastlimit);
	}

	/* free the temp vector */
	free(timemap);

	/* open the file for reading */
	for (l = 0; l < state->level; ++l) {
		ret = parity_open(&parity_handle[l], l, state->parity[l].path, state->file_mode);
		if (ret == -1) {
			/* LCOV_EXCL_START */
			log_fatal("WARNING! Without an accessible %s file, it isn't possible to scrub.\n", lev_name(l));
			exit(EXIT_FAILURE);
			/* LCOV_EXCL_STOP */
		}
	}

	msg_progress("Scrubbing...\n");

	error = 0;

	ret = state_scrub_process(state, parity_handle, 0, blockmax, &ps, now);
	if (ret == -1) {
		++error;
		/* continue, as we are already exiting */
	}

	for (l = 0; l < state->level; ++l) {
		ret = parity_close(&parity_handle[l]);
		if (ret == -1) {
			/* LCOV_EXCL_START */
			log_fatal("DANGER! Unexpected close error in %s disk.\n", lev_name(l));
			++error;
			/* continue, as we are already exiting */
			/* LCOV_EXCL_STOP */
		}
	}

	/* abort if required */
	if (error != 0)
		return -1;
	return 0;
}
Пример #30
0
void BoatDialog::OnAddPolar( wxCommandEvent& event )
{
    wxFileConfig *pConf = GetOCPNConfigObject();
    pConf->SetPath ( _T( "/PlugIns/WeatherRouting/BoatDialog" ) );

    wxString path;
    pConf->Read ( _T ( "FilePath" ), &path, *GetpSharedDataLocation()
                  + _T("plugins/weather_routing_pi/data/polars"));
    path = wxFileName(path).GetPath();

    wxFileDialog openDialog
        ( this, _( "Select Polar File" ), path, wxT ( "" ),
          wxT ( "CSV, POL, TXT (*.csv, *.pol, *.txt)|*.CSV;*.csv;*.csv.gz;*.csv.bz2;*.POL;*.pol;*.pol.gz;*.pol.bz2;*.TXT;*.txt;*.txt.gz;*.txt.bz2|All files (*.*)|*.*" ),
          wxFD_OPEN | wxFD_MULTIPLE );

    if( openDialog.ShowModal() != wxID_OK )
        return;

    pConf->Write( _T ( "FilePath" ), openDialog.GetPath());

    wxArrayString paths;
    openDialog.GetPaths(paths);

    bool generate = false, existed = true;
    for(unsigned int i=0; i<paths.GetCount(); i++) {
        wxString filename = paths[i], message;
        Polar polar;

        for(unsigned int j=0; j<m_Boat.Polars.size(); j++)
            if(m_Boat.Polars[j].FileName == filename)
                goto skip;

        existed = wxFileName::Exists(filename);

        // write dummy file
        if(!existed) {
            wxFile file;
            if(file.Open(filename, wxFile::write))
                file.Write(dummy_polar);
        }
        
        if(polar.Open(filename, message)) {
            m_Boat.Polars.push_back(polar);
            RepopulatePolars();
            m_lPolars->SetItemState(m_Boat.Polars.size()-1, wxLIST_STATE_SELECTED, wxLIST_STATE_SELECTED);
            generate = true;
        } else {
            wxMessageDialog md(this, message,
                               _("OpenCPN Weather Routing Plugin"),
                               wxICON_ERROR | wxOK );
            md.ShowModal();
        }
    skip:;
    }

    if(generate)
        GenerateCrossOverChart();
            
    if(!existed)
        OnEditPolar(event);
}