Пример #1
0
void Allocation() {
/* This subroutine sets up most of the important adjustable arrays based on the number of atoms.  It also opens the dipole and vibtemp files for writing.*/
  int flag=0;
  char name[100];
  Atomdic=(int *)malloc(Natom*sizeof(int));
  Mol=(int *)malloc(Natom*sizeof(int));
  MolName=(int *)malloc(Natom*Natomtypes*sizeof(int));
//20Jun07 JLB: I have made the absurdly huge array much smaller
//  MolType=(int *)malloc(Natom*MaxMolTypes*sizeof(int));
  MolType=(int *)malloc((Natomtypes+20)*MaxMolTypes*sizeof(int));
  NMol=(int *)malloc(Natom*sizeof(int));
  rx=(double *)malloc(Natom*sizeof(double));
  ry=(double *)malloc(Natom*sizeof(double));
  rz=(double *)malloc(Natom*sizeof(double));
  vx=(double *)malloc(Natom*sizeof(double));
  vy=(double *)malloc(Natom*sizeof(double));
  vz=(double *)malloc(Natom*sizeof(double));
  Charge=(double *)malloc(Natom*sizeof(double));
  Netc=(double *)malloc(MaxMolTypes*sizeof(double));
  
  if(Atomdic==NULL || NMol==NULL || Mol==NULL || MolType==NULL) flag=1;
  if(rx==NULL || ry==NULL || rz==NULL || Charge==NULL) flag=1;
  if(vx==NULL || vy==NULL || vz==NULL) flag=1;
  if(Netc==NULL) flag=1;

  if(flag==1) {
    printf("malloc error.\n");
    exit(0);
  }
  //  trj=fopen(Atomlist,"r");
  //  FileOpenError(trj,Atomlist);
  dpol=fopen(Output4,"w");
  FileOpenError(dpol,Output4);
  vtemp=fopen(Output5,"w");
  FileOpenError(vtemp,Output5);
  conc=fopen(Output6,"w");
  FileOpenError(conc,Output6);
}
Пример #2
0
void printMatrixToFile( const char fn[], Matrix *m ) {
	FILE *fp = fopen( fn, "w" );
	if ( fp == NULL )
		FileOpenError( fn );

	for ( int i = 0; i < m->height; i++ ) {
		for ( int j = 0; j < m->width; j++ ) {
			fprintf( fp, "%.4f ", m->a[i][j] );
		}
		fprintf( fp, "\n");
	}

	fclose( fp );
}
Пример #3
0
void TextFileBinary(size_t count) {
    char *file_name;
    ClassStudent *mas;
    ClassStudent *mas2;
    ifstream istream;
    try {
        mas = new ClassStudent[count];
        mas2 = new ClassStudent[count];
        file_name = new char[MAX_NAME_SIZE];
        for (size_t i = 0; i < count; i++) {
            cout << TEXT << endl << endl;
            cout << "Enter info about student #" << i + 1 << " of " << count << endl;
            mas[i].SetInfo();
            system("pause");
            system("cls");
        }
        cout << TEXT_BIN << endl << endl;
        FileNameHandle(file_name);
        for (size_t i = 0; i < count; i++) {
            mas[i].BinaryPut(file_name);
        }
        system("pause");
        system("cls");
        cout << TEXT_BIN << endl << endl;
        FileNameHandle(file_name);
        istream.open(file_name, ios::in | ios::binary);
        if (istream.is_open() == false) {
            throw FileOpenError();
        }
        for (size_t i = 0; i < count; i++) {
            mas2[i].BinaryGet(istream, file_name);
        }
        for (size_t i = 0; i < count; i++) {
            mas2[i].DisplayInfo();
        }
    }
    catch (bad_alloc) {
        cerr << "Error with memory allocation" << endl;
        terminate();
    }
    catch (FileOpenError) {
        cerr << "Error with file openning" << endl;
        terminate();
    }
    istream.close();
    delete[] mas;
    delete[] mas2;
    delete file_name;
    return;
}
Пример #4
0
  void bz2ifstream::open(const string &bz2_filename_)
  {
    close();
    bz2_filename = bz2_filename_;
    f = fopen(bz2_filename.c_str(), "rb");
    if (!f)
      throw FileOpenError(bz2_filename);

    if (!bzOpen(f, false))
    {
      fclose(f);
      f = NULL;
      throw FileTypeError(bz2_filename);
    }
  }
Пример #5
0
  void gzifstream::open(const string &gz_filename_)
  {
    close();
    gz_filename = gz_filename_;
    f = fopen(gz_filename.c_str(), "rb");
    if (!f)
      throw FileOpenError(gz_filename);

    if (!gzOpen(f, false))
    {
      fclose(f);
      f = NULL;
      throw FileTypeError(gz_filename);
    }
  }
Пример #6
0
// read in patterns from file
bool ReadPatterns( void ) 
{
	ifstream infile;
	int 	 dummyInt;
	float	 dummyFloat;
	char	 filename[256];
	
// open the file
	strcpy( filename, gSequenceAPI->SequenceGetDirectory());
	strcat( filename, "/pat.txt" );	
	infile.open( filename );
	if ( infile.fail() )
	{		
		FileOpenError( filename );
		return false;
	}

// read the number of patterns
	SkipComments( &infile );
	infile >> kNumPats;

// read the sequence type, but ignored here as by default we use cyclic sequences
	SkipComments( &infile );
	infile >> dummyInt;
	
// create the storage matrix
	gOnlinePatterns = CreateMatrix( 0.0, kNumPats, gSequenceAPI->SequenceGetLayerSize() );

// read in the pattern values
	for ( int i = 0; i < kNumPats; i++ )
	{
		for ( int j = 0; j < gSequenceAPI->SequenceGetLayerSize(); j++ )
		{
			SkipComments( &infile );
			infile >> gOnlinePatterns[i][j];
		}
	}
	
// close and return
	infile.close();
	return true;
}
Пример #7
0
void GetCOdict(char *name) {
/* This subroutine populates the cut-off dictionary for each bond and throws an error if any possible combination of atoms do not have a specified bond*/
  FILE *fp;
  int i,j,iatom,jatom;
  double cut;
#define BUFLEN 1000
  char buffer[BUFLEN];
  fp=fopen(name,"r"); 
  FileOpenError(fp,name);

  for(i=0;i<Natomtypes;i++) {
    for(j=0;j<Natomtypes;j++)  COdic[i][j]=-1;
  }

  while(fscanf(fp,"%s",buffer)!=EOF) {
    if (strcmp(buffer,"#") == 0) {
      SkipLine(fp);
      continue;
    }
    iatom=AtomIndicator(buffer);
    fscanf(fp,"%s",buffer);
    jatom=AtomIndicator(buffer);
    fscanf(fp,"%lf",&cut);
    COdic[iatom][jatom]=cut;
    COdic[jatom][iatom]=cut;
  }
  for(i=0;i<Natomtypes;i++) {
    for(j=0;j<Natomtypes;j++) {
      if(COdic[i][j]==-1) {
        printf("Can't fine a certain pair for cut off dictionary!\n");
        exit(0);
      }
    }
  }


  close(fp);
}
Пример #8
0
int InContext::LoadContext( char *filename )
{
	ifstream	infile;
	char		tmpname[255];
	data_type	dummy1, dummy2, w;
	int			i, j;
	
	strcpy( tmpname, filename );
	strcat( tmpname, ".wts" );
	
	infile.open( tmpname );
	if ( infile.fail() )
	{
		FileOpenError( tmpname );
		return 0;
	}
	for ( i = 0; i < mContextSize; i++ )
	{
		for ( j = 0; j < mLayerSize; j++ )
		{
			infile >> dummy1 >> dummy2 >> w;
			mOutWts[i][j] = w;
		}
	}
	for ( i = 0; i < mContextSize; i++ )
	{
		for ( j = 0; j < mContextSize; j++ )
		{
			infile >> dummy1 >> dummy2 >> w;
			mCtxtWts[i][j] = w;
		}
	}
	infile.close();
	
	return 1;
}
Пример #9
0
int	CALMAPI::CALMReadSpecs( char* filename )
{
	ifstream	infile;
	char		dummy[32];
	char		mdlname[32];
	int			mdltype, mdlsize, mdlidx, mdlconn, link, delay;
	int			i, j;
	
	// open the file
	infile.open( filename );
	if ( infile.fail() ) 
	{
		FileOpenError( filename );
		return kCALMFileError;
	}
	
	// read in number of CALM modules
	SkipComments( &infile );		// ignore any strings starting with #
	infile >> mNumModules;
	// read in number of input modules
	SkipComments( &infile );
	infile >> mNumInputs;

	// set up the module array
	mNetwork->SetNumModules( mNumModules, mNumInputs );
	
	// read in each module. Pattern modules should be specified first, 
	// before all other module types.
	for ( i = 0; i < mNumModules+mNumInputs; i++ )
	{
		// read name of module
		SkipComments( &infile );
		infile >> mdlname;
		// read module type
		SkipComments( &infile );
		infile >> dummy;
		mdltype = ModuleType( dummy );
		// read number of nodes
		SkipComments( &infile );
		infile >> mdlsize;
		// initialize the module
		mNetwork->InitializeModule( i, mdltype, mdlsize, mdlname );
	}
	// read in connections
	for ( int i = 0; i < mNumModules; i++ )
	{
		// read name of to-module
		SkipComments( &infile );
		infile >> mdlname;
		// get idx for to-module
		mdlidx = mNetwork->GetModuleIndex( mdlname );
		// read number of connections
		SkipComments( &infile );
		infile >> mdlconn;
		// set connections array for module
		mNetwork->SetNumConnections( mdlidx, mdlconn );
		// set up each single connection
		for ( j = 0; j < mdlconn; j++ )
		{	
			// read from-module
			SkipComments( &infile );
			infile >> mdlname;
			// get connection type
			SkipComments( &infile );
			infile >> dummy;
			link = ConnectionType( dummy );
			// with time delay connections, the time constant should be provided
			if ( link == kDelayLink )
			{
				SkipComments( &infile );
				infile >> delay;
			}
			else delay = 0;
			// connect the modules
			mNetwork->ConnectModules( j, mdlidx, mNetwork->GetModuleIndex( mdlname ), link, delay );
		}			
std::vector<ParsedOption> getConfig(Config& conf, const std::string& flags, bool noFileIO = false)
{
	ProgramInterface api("Infomap",
			"Implementation of the Infomap clustering algorithm based on the Map Equation (see www.mapequation.org)",
			INFOMAP_VERSION);

	std::vector<std::string> optionalOutputDir; // Used if noFileIO
	// --------------------- Input options ---------------------
	if (!noFileIO)
	{
		api.addNonOptionArgument(conf.networkFile, "network_file",
				"The file containing the network data. Accepted formats: Pajek (implied by .net) and link list (.txt)");

		api.addOptionalNonOptionArguments(conf.additionalInput, "[additional input]",
				"More network layers for multiplex.", true);
	}
	else
		conf.networkFile = "no-name";

	api.addOptionArgument(conf.inputFormat, 'i', "input-format",
			"Specify input format ('pajek', 'link-list', 'states', '3gram', 'multiplex' or 'bipartite') to override format possibly implied by file extension.", "s");

	api.addOptionArgument(conf.withMemory, "with-memory",
			"Use second order Markov dynamics and let nodes be part of different modules. Simulate memory from first-order data if not '3gram' input.", true);

//	api.addOptionArgument(conf.bipartite, "bipartite",
//			"Let the source id of a link belong to a different kind of nodes and ignore that set in the output.");

	api.addOptionArgument(conf.skipAdjustBipartiteFlow, "skip-adjust-bipartite-flow",
			"Skip distributing all flow from the bipartite nodes (first column) to the ordinary nodes (second column).", true);

	api.addOptionArgument(conf.withMemory, "overlapping",
			"Let nodes be part of different and overlapping modules. Applies to ordinary networks by first representing the memoryless dynamics with memory nodes.");

	api.addOptionArgument(conf.hardPartitions, "hard-partitions",
			"Don't allow overlapping modules in memory networks by keeping the memory nodes constrained into their physical nodes.", true);

	api.addOptionArgument(conf.nonBacktracking, "non-backtracking",
			"Use non-backtracking dynamics and let nodes be part of different and overlapping modules. Applies to ordinary networks by first representing the non-backtracking dynamics with memory nodes.", true);

	api.addOptionArgument(conf.parseWithoutIOStreams, "without-iostream",
			"Parse the input network data without the iostream library. Can be a bit faster, but not as robust.", true);

	api.addOptionArgument(conf.zeroBasedNodeNumbers, 'z', "zero-based-numbering",
			"Assume node numbers start from zero in the input file instead of one.");

	api.addOptionArgument(conf.includeSelfLinks, 'k', "include-self-links",
			"Include links with the same source and target node. (Ignored by default.)");

	api.addOptionArgument(conf.skipCompleteDanglingMemoryNodes, "skip-complete-dangling-memory-nodes",
			"Skip add first order links to complete dangling memory nodes.");

	api.addOptionArgument(conf.nodeLimit, 'O', "node-limit",
			"Limit the number of nodes to read from the network. Ignore links connected to ignored nodes.", "n", true);

	api.addOptionArgument(conf.preClusterMultiplex, "pre-cluster-multiplex",
			"Pre-cluster multiplex networks layer by layer.", true);

	api.addOptionArgument(conf.clusterDataFile, 'c', "cluster-data",
			"Provide an initial two-level (.clu format) or multi-layer (.tree format) solution.", "p", true);

	api.addOptionArgument(conf.noInfomap, "no-infomap",
			"Don't run Infomap. Useful if initial cluster data should be preserved or non-modular data printed.", true);

	// --------------------- Output options ---------------------

	api.addOptionArgument(conf.outName, "out-name",
			"Use this name for the output files, like [output_directory]/[out-name].tree", "s", true);

	api.addOptionArgument(conf.noFileOutput, '0', "no-file-output",
			"Don't print any output to file.", true);

	api.addOptionArgument(conf.printMap, "map",
			"Print the top two-level modular network in the .map format.");

	api.addOptionArgument(conf.printClu, "clu",
			"Print the top cluster indices for each node.");

	api.addOptionArgument(conf.printTree, "tree",
			"Print the hierarchy in .tree format. (default true if no other output with cluster data)");

	api.addOptionArgument(conf.printFlowTree, "ftree",
			"Print the hierarchy in .tree format and append the hierarchically aggregated network links.", true);

	api.addOptionArgument(conf.printBinaryTree, "btree",
			"Print the tree in a streamable binary format.", true);

	api.addOptionArgument(conf.printBinaryFlowTree, "bftree",
			"Print the tree including horizontal flow links in a streamable binary format.");

	api.addOptionArgument(conf.printNodeRanks, "node-ranks",
			"Print the calculated flow for each node to a file.", true);

	api.addOptionArgument(conf.printFlowNetwork, "flow-network",
			"Print the network with calculated flow values.", true);

	api.addOptionArgument(conf.printPajekNetwork, "pajek",
			"Print the parsed network in Pajek format.", true);

	api.addOptionArgument(conf.printStateNetwork, "print-state-network",
			"Print the internal state network.", true);

	api.addOptionArgument(conf.printExpanded, "expanded",
			"Print the expanded network of memory nodes if possible.", true);

	// --------------------- Core algorithm options ---------------------
	api.addOptionArgument(conf.twoLevel, '2', "two-level",
			"Optimize a two-level partition of the network.");

	bool dummyUndirected;
	api.addOptionArgument(dummyUndirected, 'u', "undirected",
			"Assume undirected links. (default)");

	api.addOptionArgument(conf.directed, 'd', "directed",
			"Assume directed links.");

	api.addOptionArgument(conf.undirdir, 't', "undirdir",
			"Two-mode dynamics: Assume undirected links for calculating flow, but directed when minimizing codelength.");

	api.addOptionArgument(conf.outdirdir, "outdirdir",
			"Two-mode dynamics: Count only ingoing links when calculating the flow, but all when minimizing codelength.", true);

	api.addOptionArgument(conf.rawdir, 'w', "rawdir",
			"Two-mode dynamics: Assume directed links and let the raw link weights be the flow.", true);

	api.addOptionArgument(conf.recordedTeleportation, 'e', "recorded-teleportation",
			"If teleportation is used to calculate the flow, also record it when minimizing codelength.", true);

	api.addOptionArgument(conf.teleportToNodes, 'o', "to-nodes",
			"Teleport to nodes instead of to links, assuming uniform node weights if no such input data.", true);

	api.addOptionArgument(conf.teleportationProbability, 'p', "teleportation-probability",
			"The probability of teleporting to a random node or link.", "f", true);

	api.addOptionArgument(conf.selfTeleportationProbability, 'y', "self-link-teleportation-probability",
			"Additional probability of teleporting to itself. Effectively increasing the code rate, generating more and smaller modules.", "f", true);

	api.addOptionArgument(conf.markovTime, "markov-time",
			"Scale link flow with this value to change the cost of moving between modules. Higher for less modules.", "f", true);

	api.addOptionArgument(conf.preferredNumberOfModules, "preferred-number-of-modules",
			"Stop merge or split modules if preferred number of modules is reached.", "n", true);

	api.addOptionArgument(conf.multiplexRelaxRate, "multiplex-relax-rate",
			"The probability to relax the constraint to move only in the current layer. If negative, the inter-links have to be provided.", "f", true);

	api.addOptionArgument(conf.multiplexRelaxLimit, "multiplex-relax-limit",
			"The number of neighboring layers in each direction to relax to. If negative, relax to any layer.", "n", true);

	api.addOptionArgument(conf.seedToRandomNumberGenerator, 's', "seed",
			"A seed (integer) to the random number generator.", "n");

	// --------------------- Performance and accuracy options ---------------------
	api.addOptionArgument(conf.numTrials, 'N', "num-trials",
			"The number of outer-most loops to run before picking the best solution.", "n");

	api.addOptionArgument(conf.minimumCodelengthImprovement, 'm', "min-improvement",
			"Minimum codelength threshold for accepting a new solution.", "f", true);

	api.addOptionArgument(conf.randomizeCoreLoopLimit, 'a', "random-loop-limit",
			"Randomize the core loop limit from 1 to 'core-loop-limit'", true);

	api.addOptionArgument(conf.coreLoopLimit, 'M', "core-loop-limit",
			"Limit the number of loops that tries to move each node into the best possible module", "n", true);

	api.addOptionArgument(conf.levelAggregationLimit, 'L', "core-level-limit",
			"Limit the number of times the core loops are reapplied on existing modular network to search bigger structures.", "n", true);

	api.addOptionArgument(conf.tuneIterationLimit, 'T', "tune-iteration-limit",
			"Limit the number of main iterations in the two-level partition algorithm. 0 means no limit.", "n", true);

	api.addOptionArgument(conf.minimumRelativeTuneIterationImprovement, 'U', "tune-iteration-threshold",
			"Set a codelength improvement threshold of each new tune iteration to 'f' times the initial two-level codelength.", "f", true);

	api.addOptionArgument(conf.fastFirstIteration, "fast-first-iteration",
			"Move nodes to strongest connected module in the first iteration instead of minimizing the map equation.", true);

	api.addOptionArgument(conf.fastCoarseTunePartition, 'C', "fast-coarse-tune",
			"Try to find the quickest partition of each module when creating sub-modules for the coarse-tune part.", true);

	api.addOptionArgument(conf.alternateCoarseTuneLevel, 'A', "alternate-coarse-tune-level",
			"Try to find different levels of sub-modules to move in the coarse-tune part.", true);

	api.addOptionArgument(conf.coarseTuneLevel, 'S', "coarse-tune-level",
			"Set the recursion limit when searching for sub-modules. A level of 1 will find sub-sub-modules.", "n", true);

	api.addIncrementalOptionArgument(conf.fastHierarchicalSolution, 'F', "fast-hierarchical-solution",
			"Find top modules fast. Use -FF to keep all fast levels. Use -FFF to skip recursive part.");

	api.addIncrementalOptionArgument(conf.lowMemoryPriority, 'l', "low-memory",
			"Prioritize memory efficient algorithms before fast. Use -ll to optimize even more, but this may give approximate results.", true);

	api.addOptionArgument(conf.innerParallelization, "inner-parallelization",
			"Parallelize the innermost loop for greater speed. Note that this may give some accuracy tradeoff.");

	api.addOptionArgument(conf.resetConfigBeforeRecursion, "reset-options-before-recursion",
			"Reset options tuning the speed and accuracy before the recursive part.", true);

	api.addOptionArgument(conf.showBiNodes, "show-bipartite-nodes",
			"Include the bipartite nodes in the output.", true);

	// --------------------- Output options ---------------------
	if (!noFileIO)
	{
		api.addNonOptionArgument(conf.outDirectory, "out_directory",
				"The directory to write the results to");
	}
	else
	{
		api.addOptionalNonOptionArguments(optionalOutputDir, "[out_directory]",
				"The directory to write the results to.");
	}

	api.addIncrementalOptionArgument(conf.verbosity, 'v', "verbose",
			"Verbose output on the console. Add additional 'v' flags to increase verbosity up to -vvv.");

	api.addOptionArgument(conf.silent, "silent",
			"No output on the console.");

	api.parseArgs(flags);

	conf.parsedArgs = flags;

	if (noFileIO)
	{
		if (!optionalOutputDir.empty())
			conf.outDirectory = optionalOutputDir[0];
		else
			conf.noFileOutput = true;
	}

	// Some checks
	if (*--conf.outDirectory.end() != '/')
		conf.outDirectory.append("/");

	if (conf.haveOutput() && !isDirectoryWritable(conf.outDirectory))
		throw FileOpenError(io::Str() << "Can't write to directory '" <<
				conf.outDirectory << "'. Check that the directory exists and that you have write permissions.");

	if (conf.outName.empty())
		conf.outName = FileURI(conf.networkFile).getName();

	return api.getUsedOptionArguments();
}
Пример #11
0
void PostProcess(char *name,char *name2,char *name3) {

/*  This subroutine does the global lists after all the frames have been read.  out is the fra.out with the list of species and number of each per frame.  out2 is mol.out with the chemical identities of each species. out3 is num.out which is the scratch file with number of species per frame in a non-plottable format.*/

  int i,j;
  FILE *out,*out2,*out3;
  int step,molnum,id,num,itemp;
  int numcount[Nmoltype];

  out=fopen(name,"w");
  FileOpenError(out,name);
  out2=fopen(name2,"w");
  FileOpenError(out2,name2);
  out3=fopen(name3,"r");
  FileOpenError(out3,name3);

  fprintf(out,"Timestep\t");
  fprintf(out2,"%d\n\n",Nmoltype);

/*  To get the chemical identity of a species, this process loops over each atom type and writes the number of atoms of that type in the formula.    */
  for(i=0;i<Nmoltype;i++) {
    fprintf(out2,"%d\t",i);
    for(j=0;j<Natomtypes;j++) {
      itemp=MolType[Natomtypes*i+j];
      if(itemp!=0) {
        if(j==Carbon) {
          fprintf(out,"C");
          fprintf(out2,"C");
        }
        else if(j==Hydrogen) {
          fprintf(out,"H");
          fprintf(out2,"H");
        }
        else if(j==Oxygen) {
          fprintf(out,"O");
          fprintf(out2,"O");
        }
        else if(j==Nitrogen) {
          fprintf(out,"N");
          fprintf(out2,"N");
        }
        if(itemp!=1) {
          fprintf(out,"%d",itemp);
          fprintf(out2,"%d",itemp);
        }
      }
    }
    fprintf(out,"\t");
    fprintf(out2,"\n");
  }
  fprintf(out,"\n");

/*    for each molecule type, read the num.out scratch file and find the number of those molecules.  Then write it out in a nice column format suitable for plotting. */
  while(fscanf(out3,"%d",&step)!=EOF) {
    fscanf(out3,"%d",&num);
    for(i=0;i<Nmoltype;i++) numcount[i]=0;
    for(i=0;i<num;i++) {
      fscanf(out3,"%d",&id);
      fscanf(out3,"%d",&molnum);
      numcount[id]=molnum; 
    }
    fprintf(out,"%d\t",step);
    for(i=0;i<Nmoltype;i++) {
      fprintf(out,"%d\t",numcount[i]);
    }
    fprintf(out,"\n");
  }
}
Пример #12
0
void AnalyzeTrajectory(char *name,char *name2) {
/***************************************************************************/
/*  This subroutine loops through the data both with the bond lists and the position files.  
    Step 1: It checks the timestep for the bond list and then reads in the position data ensuring that the timesteps match.
    Step 2: It loops over the bonds to identify molecules 
    Step 3: It loops over the molecules to determine name and species.
    Step 4: It calculates and writes dipole.out and vibtemp.out.
    Step 5: It writes num.out */
/**************************************************************************/

  FILE *fp,*out3;//fp is the file with the bond lists.  out3 refers to a scratch file to keep track of how many of each type of molecules exist.
  int i,j,k,l,iatom,jatom,Nlink,count,iatomtype,jatomtype;
/* jatom is the neighbor, iatom is the self, Nlink is the number of neighbors, count is a running index to identify order of atoms (e.g. atom 5 is on line 38)*/
  int frame;
  int itemp,Molid;
/*itemp is a generic variable as needed, Molid is the line of the atom (e.g. atom 5 is on line 38 means Molid[4]=37 because of the zero).*/

  double BO,dtemp;//BO is bond order
  char buffer[1000];
  int Cnct[MaxNumBonds];//connectivity table for a given atom

  int Nspec,flag_mol,flag_spec,flag_identity,nd,timestep;
/*  Nspec is the number of species during this frame.  flag_mol is a binary flag with 1 indicating that this atom belongs to this molecule.  flag_spec is a binary flag with 1 indicating that a new species has been found.  I have no idea what purpose flag_identity serves, but a 1 indicates that flag_spec is 1.
nd is a return value from CheckExistence.*/

  int Name[Natomtypes],MolTemp[Natom];
/*Name is a counter for how many atoms of a given type are in this particular molecule. MolTemp is an array that keeps track of molecule id by atom id.  For example, if atom 5 belongs to molecule 3 MolTemp[4]=3*/

  int CheckExistence(); 
  void GetAtomdata();
  void GetCOMDipole();

  fp=fopen(name,"r"); 
  FileOpenError(fp,name);
  out3=fopen(name2,"w"); 
  FileOpenError(out3,name2);

  frame=0;

  while(fscanf(fp,"%s",buffer)!=EOF) {
/* Step 1 */
    if(strcmp(buffer,"Timestep")==0) {
      fscanf(fp,"%d",&timestep);
      //      GetAtomdata(timestep);
    }

/* Step 2 */
    if(strcmp(buffer,"q")==0) {
      frame++;
      count=0; 
/*             zeroing out the counters        */
      for(i=0;i<Natom;i++) {
        MolTemp[i]=-1;
        NMol[i]=1;
      }
/*          Step 2A reads the atomid as iatom, the first itemp is a discard of the atom type, Nlink is the number of neighbors, and then the loop over all the bonded neighbors is stored in Cnct, and the last itemp is the ignored 0 to mark the end.*/
      for(i=0;i<Natom;i++) {
        fscanf(fp,"%d",&iatom);
        iatom--;
        if(MolTemp[iatom]==-1) {
          MolTemp[iatom]=count;
          count++;
        }
        fscanf(fp,"%d",&itemp);
        fscanf(fp,"%d",&Nlink);
        for(j=0;j<Nlink;j++) {
          fscanf(fp,"%d",&itemp);
          itemp--;
          Cnct[j]=itemp;
        }
        fscanf(fp,"%d",&itemp);

/*         Step 2B reads the bond orders from the bond file and assigns atoms to molecules.  The first check is if a bond exists.  The second check is if i and j already belong to the same molecule.  If they don't and j has no molecule, assign it to i's molecule.  If they do, then j was assigned to a different number so loop through the molecule list and set all the atoms on that molecule to the new i molecule.  Then read and discard the remainder of the line.*/

        for(j=0;j<Nlink;j++) {
          fscanf(fp,"%lf",&BO);
          jatom=Cnct[j];
          Molid=MolTemp[jatom];
          iatomtype=Atomdic[iatom];
          jatomtype=Atomdic[jatom];
          if(BO>COdic[iatomtype][jatomtype]) {
            if(Molid!=MolTemp[iatom]) {
              if(MolTemp[jatom]==-1) MolTemp[jatom]=MolTemp[iatom];
              else {
                for(k=0;k<Natom;k++) {
                  if(MolTemp[k]==Molid) MolTemp[k]=MolTemp[iatom];
                }
              }
            }
          } 
        }
        fscanf(fp,"%lf",&dtemp);
        fscanf(fp,"%lf",&dtemp);
        fscanf(fp,"%lf",&dtemp);
      }

/*       Step 3 builds the chemical formula for each molecule.  For each molecule (the for loop over i with count as the maximum), loop over all the atoms.*/

      for(i=0;i<MaxMolTypes;i++) Netc[i]=0.0;
      for(i=0,Nspec=0,Nmolecule=0;i<count;i++) {

 /*     Step 3A: if the atom belongs to this molecule, increment the appropriate type counter (e.g. we have another carbon), flip flag_mol to 1, set the Mol value to this molecule, and add the atomic charge to the running charge total. */

        for(j=0;j<Natomtypes;j++) Name[j]=0;
        for(j=0,flag_mol=0;j<Natom;j++) {
          if(MolTemp[j]==i) {
            jatom=Atomdic[j]; 
            Name[jatom]++;
            flag_mol=1; 
            Mol[j]=Nmolecule; 
            Netc[Nmolecule]+=Charge[j];
          }
        }

/*     Step 3B: If this molecule contains any atoms (flag_mol==1), then determine if it is a new species.  MolName is populated as new species are found.  In one of the least efficient matching mechanisms ever, we walk through all the known species names.  If no match is found, the flag_spec is set to 1.  A zero flag_spec means that we have a match, increment the appropriate species counter.  Otherwise, if we have a zero number of species or a flipped flag_spec, we have a new species and need to populate its name.  Then we increment the number of species as appropriate and always add a new molecule.*/

        if(flag_mol==1) {
          flag_identity=1;
          for(k=0;k<Nspec;k++) {
            flag_spec=0;
            for(l=0;l<Natomtypes;l++) {
              if(MolName[Natomtypes*k+l]!=Name[l]) flag_spec=1;
            }
            if(flag_spec==0) NMol[k]++;  
            flag_identity*=flag_spec; 
          }
          if(Nspec==0 || flag_identity==1) {
            for(l=0;l<Natomtypes;l++) {
              MolName[Natomtypes*Nspec+l]=Name[l];
            } 
            Nspec++; 
          }
          Nmolecule++;
        }//ends the if(flag_mol==1) loop

      }//ends the for i up to count loop

/*  Step 4 does the end of frame cleanup including the writes for COM */
      fprintf(out3,"%d\t",timestep);
      printf("Timestep = %d\n",timestep);
      fprintf(dpol,"%d\n",Nmolecule);
      fprintf(dpol,"TSTEP %d\n",timestep);
      fprintf(vtemp,"%d\n",Nmolecule);
      fprintf(vtemp,"TSTEP %d\n",timestep);
      fprintf(conc,"TSTEP %d\n",timestep);
      fprintf(conc,"%d\n",Nmolecule);
      GetCOMDipole(Nmolecule,timestep,frame);

/*  Step 5 prints the list of species and their quantities   */
      fprintf(out3,"%d\t",Nspec);
      for(i=0;i<Nspec;i++) {
        nd=CheckExistence(i);
        fprintf(out3,"%d ",nd);
        fprintf(out3,"%d\t",NMol[i]);
      }
      fprintf(out3,"\n");
    }
  }
  fflush(out3);
  fclose(out3);
  fclose(fp);
}
Пример #13
0
void GetAtomlist(char *name) {
/*This subroutine reads the head of the configuration file to set the lattice parameters and the number of atoms.  It also checks that a full frame exists because it loops over the first frame to populate the Atomdic with the proper type for each atom id.*/
  
  FILE *fp;
  int i,iatom,count=0,itemp,id,flag;
  double dtemp;
  double a,b,c,d,e,f,g,h,ii,det;
  char buffer[1000];

  FILE *temp;
  fp=fopen(name,"r"); 
  FileOpenError(fp,name);

  while(fscanf(fp,"%s",buffer)!=EOF) {
    if(strcmp(buffer,"vectors:")==0) {
      fscanf(fp,"%s",buffer); 
      for(i=0;i<3;i++) fscanf(fp,"%lf",&latc_x[i]); 
      fscanf(fp,"%s",buffer); 
      for(i=0;i<3;i++) fscanf(fp,"%lf",&latc_y[i]); 
      fscanf(fp,"%s",buffer); 
      for(i=0;i<3;i++) fscanf(fp,"%lf",&latc_z[i]); 
    }
    else if(strcmp(buffer,"origin:")==0) {
      fscanf(fp,"%s",buffer); 
      for(i=0;i<3;i++) fscanf(fp,"%lf",&Origin[i]); 
    }
    else if(strcmp(buffer,"particles")==0) {
      fscanf(fp,"%d",&Natom);
      printf("# of atoms : %d\n",Natom);
      Allocation();
    }
    else if(strcmp(buffer,"positions")==0) {
      for(i=0,flag=0;i<Natom;i++) {
        fscanf(fp,"%d",&id);
        id--;
        fscanf(fp,"%s",buffer);
        iatom=AtomIndicator(buffer);
        Atomdic[id]=iatom;
        count++;
//        fscanf(fp,"%d",&itemp);
//        fprintf(temp,"\t%d",itemp);
//        fscanf(fp,"%lf",&dtemp);
//        fprintf(temp,"\t%lf",dtemp);
//        fscanf(fp,"%lf",&dtemp);
//        fprintf(temp,"\t%lf",dtemp);
//        fscanf(fp,"%lf",&dtemp);
//        fprintf(temp,"\t%lf",dtemp);
//        fscanf(fp,"%lf",&dtemp);
//        fprintf(temp,"\t%lf\n",dtemp);
	fgets(buffer,1000,fp);
        flag=1;
/*         fscanf(fp,"%lf",&dtemp); */
/*         fscanf(fp,"%lf",&dtemp); */
/*         fscanf(fp,"%lf",&dtemp); */
/*         fscanf(fp,"%lf",&dtemp); */
      }
      if(flag==1) break;
    }
  }
  if(Natom!=count) {
    printf("Can't read whole # of atoms.\n");
    exit(0);
  }


  a=latc_x[0]; b=latc_y[0]; c=latc_z[0];
  d=latc_x[1]; e=latc_y[1]; f=latc_z[1];
  g=latc_x[2]; h=latc_y[2]; ii=latc_z[2];
  det=a*e*ii-a*f*h-d*b*ii+d*c*h+g*b*f-g*c*e;
  if (det != 0) {
  Ilatc_x[0]=(e*ii-f*h)/det;
  Ilatc_x[1]=-(b*ii-c*h)/det;
  Ilatc_x[2]=(b*f-c*e)/det;

  Ilatc_y[0]=-(d*ii-f*g)/det;
  Ilatc_y[1]=(a*ii-c*g)/det;
  Ilatc_y[2]=-(a*f-c*d)/det;

  Ilatc_z[0]=(e*g-d*h)/det;
  Ilatc_z[1]=-(b*g-a*h)/det;
  Ilatc_z[2]=(a*e-b*d)/det;
  }

  close(fp);
}
Пример #14
0
void WinHttpStream::initRequest()
{
	TextParser<wchar_t> parser;
	if (!parser(L"%1://%[*-_.a-zA-Z0-9:@]2%%[/](*)*3",url))
		throw FileOpenError(THISLOCATION,ERROR_FILE_NOT_FOUND,url);

	String protocol = parser[1].str();
	String hostident = parser[2].str();
	String::SplitIterator hostidentsplit = hostident.split('@');
	String ident;
	String domain;
	domain = hostidentsplit.getNext();
	while (hostidentsplit.hasItems()) {
		ident = ident + domain + ConstStrW('@');
		domain = hostidentsplit.getNext();
	}
	String path = parser[3].str();
	natural port;
	String username;
	String password;
	bool secure;

	if (parser( L"%1:%u2",domain)) {
		domain = parser[1].str();
		port = parser[2];
		secure = false;
	} else if (protocol == ConstStrW(L"http")) {
		port = INTERNET_DEFAULT_HTTP_PORT;
		secure = false;
	} else if (protocol == ConstStrW(L"https")) {
		port = INTERNET_DEFAULT_HTTPS_PORT;
		secure = true;
	} else
		throw FileOpenError(THISLOCATION,ERROR_NOT_FOUND,url);

	if (!ident.empty()) {
		if (parser(L"%1:%2@",ident))  {
			username = parser[1].str();
			password = parser[2].str();
		} else {
			throw FileMsgException(THISLOCATION,0,url,"Invalid identification field in the url");
		}
	}
	DWORD accessType;
	switch (settings.proxyMode) {
	case pmManual:  accessType = INTERNET_OPEN_TYPE_PROXY;
	case pmDirect:  accessType = INTERNET_OPEN_TYPE_DIRECT;
	case pmAuto:  accessType = INTERNET_OPEN_TYPE_PRECONFIG;
	}

	TextFormatBuff<wchar_t> fmt;

	String proxyName;
	if (accessType == INTERNET_OPEN_TYPE_PROXY) {
		fmt(L"%1:%2") << settings.proxyAddr << settings.proxyPort;
		proxyName = fmt.write();
	}

	if (hInternet) InternetCloseHandle(hInternet);
	hInternet = InternetOpenW(settings.userAgent.cStr(),accessType,proxyName.cStr(),0,0);
	if (hInternet == 0) 
		throw FileMsgException(THISLOCATION,GetLastError(),url,"Cannot initialize WinInet");

	if (hConnect) InternetCloseHandle(hConnect);
	hConnect = InternetConnectW(hInternet,domain.cStr(),(INTERNET_PORT)port,
		username.empty()?0:username.cStr(),
		password.empty()?0:password.cStr(),
		INTERNET_SERVICE_HTTP ,0,0);
	if (hConnect == 0) 
		throw FileMsgException(THISLOCATION,GetLastError(),url,"Cannot connect remote site");
	
	DWORD reqFlags = INTERNET_FLAG_NO_UI |INTERNET_FLAG_HYPERLINK ;
	if (redirDisabled) reqFlags|=INTERNET_FLAG_NO_AUTO_REDIRECT ;
	if (!settings.cookiesEnabled) reqFlags|=INTERNET_FLAG_NO_COOKIES;
	if (secure) reqFlags|=INTERNET_FLAG_SECURE;
	

	hHTTPConn = HttpOpenRequestW(hConnect,String(method).cStr(),path.cStr(),
					0,0,0,reqFlags,0);
	if (hHTTPConn == 0) 
		throw FileMsgException(THISLOCATION,GetLastError(),url,"Cannot connect remote site");
	AutoArray<wchar_t> hdrall;
	for (HeaderMap::Iterator iter = hdrmap.getFwIter(); iter.hasItems();) {

		const HeaderMap::Entity &e = iter.getNext();
		fmt(L"%1: %2\n") << e.key << e.value;
		hdrall.append(fmt.write());
	}	
	if (!hdrall.empty() &&
		!HttpAddRequestHeadersW(hHTTPConn,hdrall.data(),(DWORD)hdrall.length(),HTTP_ADDREQ_FLAG_REPLACE|HTTP_ADDREQ_FLAG_ADD))
		throw FileMsgException(THISLOCATION,GetLastError(),url,"AddRequest failed");
	
	if (!HttpSendRequestW(hHTTPConn,0,0,postBuffer.data(),(DWORD)postBuffer.length())) {
		bool stillError = true;
		DWORD dwError = GetLastError();	
		if (dwError == ERROR_INTERNET_INVALID_CA && settings.allowUntrustedCert) {
			DWORD dwFlags;
			DWORD dwBuffLen = sizeof(dwFlags);

			InternetQueryOption (hHTTPConn, INTERNET_OPTION_SECURITY_FLAGS,
				(LPVOID)&dwFlags, &dwBuffLen);

			dwFlags |= SECURITY_FLAG_IGNORE_UNKNOWN_CA;
			InternetSetOption (hHTTPConn, INTERNET_OPTION_SECURITY_FLAGS,
				&dwFlags, sizeof (dwFlags) );
			if (HttpSendRequestW(hHTTPConn,0,0,postBuffer.data(),(DWORD)postBuffer.length()))
				stillError = false;			
		}
		if (stillError)
			throw FileMsgException(THISLOCATION,GetLastError(),url,"Failed to SendRequest");
	}
	postBuffer.clear();
}
Пример #15
0
  void AmberNetcdf::init(const char* name, const uint natoms) {
    int retval;

   
    retval = nc_open(name, NC_NOWRITE, &_ncid);
    if (retval)
      throw(FileOpenError(name, "", retval));    // May want to preserve code here in the future...

    // Read and validate global attributes...
    readGlobalAttributes();
    if (_conventions.empty() || _conventionVersion.empty())
      throw(FileOpenError(name, "Unable to find convention global attributes.  Is this really an Amber NetCDF trajectory?"));

    if (_conventions.find("AMBER") == std::string::npos)
      throw(FileOpenError(name, "Cannot find AMBER tag in global attribues.  Is this really an Amber NetCDF trajectory?"));
      
    if (_conventionVersion != std::string("1.0"))
      throw(FileOpenError(name, "Convention version is '" + _conventionVersion + "', but only 1.0 is supported for Amber NetCDF trajectories."));

    // Verify # of atoms match...
    int atom_id;
    retval = nc_inq_dimid(_ncid, "atom", &atom_id);
    if (retval)
      throw(FileOpenError(name, "Cannot read atom id"), retval);
    retval = nc_inq_dimlen(_ncid, atom_id, &_natoms);
    if (retval)
      throw(FileOpenError(name, "Cannot read atom length", retval));
    if (_natoms != natoms)
      throw(FileOpenError(name, "AmberNetcdf has different number of atoms than expected"));


    // Get nframes
    int frame_id;
    retval = nc_inq_dimid(_ncid, "frame", &frame_id);
    if (retval)
      throw(FileOpenError(name, "Cannot read frame information", retval));
    retval = nc_inq_dimlen(_ncid, frame_id, &_nframes);

    // Check for periodic cells...
    retval = nc_inq_varid(_ncid, "cell_lengths", &_cell_lengths_id);
    _periodic = !retval;

    // Any additional validation should go here...

    // Get coord-id for later use...
    retval = nc_inq_varid(_ncid, "coordinates", &_coord_id);
    if (retval)
      throw(FileOpenError(name, "Cannot get id for coordinates", retval));

    // Attempt to determine timestep by looking at dT between frames 1 & 2
    if (_nframes >= 2) {
      int time_id;
      retval = nc_inq_varid(_ncid, "time", &time_id);
      if (!retval) {
        float t0, t1;
        size_t idx[1];

        idx[0] = 0;
        retval = nc_get_var1_float(_ncid, time_id, idx, &t0);
        if (retval)
          throw(FileOpenError(name, "Cannot get first time point", retval));

        idx[0] = 1;
        retval = nc_get_var1_float(_ncid, time_id, idx, &t1);
        if (retval)
          throw(FileOpenError(name, "Cannot get second time point", retval));

        // Assume units are in picoseconds
        _timestep = (t1-t0)*1e-12;
      }
    }


    // Now cache the first frame...
    readRawFrame(0);
    cached_first = true;
    
  }