Example #1
0
void PreClass::prettyPrint(std::ostream &out) const {
  out << "Class ";
  if (m_attrs & AttrAbstract) { out << "abstract "; }
  if (m_attrs & AttrFinal) { out << "final "; }
  if (m_attrs & AttrInterface) { out << "interface "; }
  out << m_name->data() << " at " << m_offset;
  if (m_hoistable == MaybeHoistable) {
    out << " (maybe-hoistable)";
  } else if (m_hoistable == AlwaysHoistable) {
    out << " (always-hoistable)";
  }
  if (m_attrs & AttrUnique)     out << " (unique)";
  if (m_attrs & AttrPersistent) out << " (persistent)";
  if (m_id != -1) {
    out << " (ID " << m_id << ")";
  }
  out << std::endl;

  for (Func* const* it = methods(); it != methods() + numMethods(); ++it) {
    out << " ";
    (*it)->prettyPrint(out);
  }
  for (const Prop* it = properties();
      it != properties() + numProperties();
      ++it) {
    out << " ";
    it->prettyPrint(out);
  }
  for (const Const* it = constants();
      it != constants() + numConstants();
      ++it) {
    out << " ";
    it->prettyPrint(out);
  }
}
Example #2
0
void ASTInfo::code_gen(llvm::Module *M, llvm::IRBuilder<> &B)
{
    llvm::LLVMContext &context = M->getContext();

    if (!__brain_index_ptr) {
        // Create global variable |brain.index|
        llvm::Type *Ty = llvm::Type::getInt32Ty(context);
        const llvm::APInt Zero = llvm::APInt(32, 0); // int32 0
        llvm::Constant *InitV = llvm::Constant::getIntegerValue(Ty, Zero);
        ASTInfo::__brain_index_ptr = new llvm::GlobalVariable(*M, Ty, false,
                                          // Keep one copy when linking (weak)
                                          llvm::GlobalValue::WeakAnyLinkage,
                                          InitV,
                                          "brain.index");
    }

    if (!__brain_cells_ptr) {
        // Create |brain.cells|
        auto *ArrTy = llvm::ArrayType::get(llvm::Type::getInt32Ty(context),
                                           ArgsOptions::instance()->get_cells_size());
        // Create a vector of _k_cells_size items equal to 0
        std::vector<llvm::Constant *> constants(ArgsOptions::instance()->get_cells_size(),
                                                B.getInt32(0));
        llvm::ArrayRef<llvm::Constant *> Constants = llvm::ArrayRef<llvm::Constant *>(constants);
        llvm::Constant *InitPtr = llvm::ConstantArray::get(ArrTy, Constants);
        ASTInfo::__brain_cells_ptr = new llvm::GlobalVariable(*M, ArrTy, false,
                                          // Keep one copy when linking (weak)
                                          llvm::GlobalValue::WeakAnyLinkage,
                                          InitPtr,
                                          "brain.cells");
    }
}
Array HHVM_FUNCTION(get_class_constants, const String& className) {
  auto const cls = Unit::loadClass(className.get());
  if (cls == NULL) {
    return Array::attach(MixedArray::MakeReserve(0));
  }

  auto const numConstants = cls->numConstants();
  ArrayInit arrayInit(numConstants, ArrayInit::Map{});

  auto const consts = cls->constants();
  for (size_t i = 0; i < numConstants; i++) {
    // Note: hphpc doesn't include inherited constants in
    // get_class_constants(), so mimic that behavior
    if (consts[i].cls == cls && !consts[i].isAbstract() &&
        !consts[i].isType()) {
      auto const name  = const_cast<StringData*>(consts[i].name.get());
      Cell value = consts[i].val;
      // Handle dynamically set constants
      if (value.m_type == KindOfUninit) {
        value = cls->clsCnsGet(consts[i].name);
      }
      assert(value.m_type != KindOfUninit);
      arrayInit.set(name, cellAsCVarRef(value));
    }
  }

  return arrayInit.toArray();
}
Example #4
0
int main( int ac, char **av )
{
	int *nlen;
	static char **name, **seq;
	double score;
	extern double score_calc_for_score( int, char ** );

	arguments( ac, av );

	getnumlen( stdin );
	rewind( stdin );

	nlen = AllocateIntVec( njob );
	name = AllocateCharMtx( njob, B+1 );
	seq = AllocateCharMtx( njob, nlenmax+2 );

	readData_pointer( stdin, name, nlen, seq );

	if( !isaligned( njob, seq ) ) ErrorExit( "Not aligned." );

	constants( njob, seq );

	score = score_calc_for_score( njob, seq );
	if( scoremtx == 0 ) score += offset;

	fprintf( stdout, "score = %f\n", score );
	if     ( scoremtx ==  0 ) fprintf( stdout, "JTT %dPAM\n", pamN );
	else if( scoremtx ==  1 ) fprintf( stdout, "Dayhoff( machigai ga aru )\n" );
	else if( scoremtx ==  2 ) fprintf( stdout, "M-Y\n" );
	else if( scoremtx == -1 ) fprintf( stdout, "DNA 1:%d\n", kimuraR );

	fprintf( stdout, "gap penalty = %+6.2f, %+6.2f, %+6.2f\n", (double)ppenalty/1000, (double)ppenalty_ex/1000, (double)poffset/1000 );
	exit( 0 );
}
Example #5
0
void
compile(Node *n)	/* called from parser only */
{
	extern long autooffset;
	Errjmp x;
	n=constants(n);
	if(cflag){
		fprint(2, "%z:constants:\n");
		dump(n, 0);
	}
	errsave(x);
	if(errmark()){
		autooffset=0;
		resultloc=0;
		breakloc=-1;
		continueloc=-1;
		didbecome=0;
		freenode(n);
		errrest(x);
		errjmp();
	}
	istart();
	gen(n, 0);
	freenode(n);
	errrest(x);
}
constants constants::init()
{
  lMask[0] = 0; // probably unused, but not written in the following loop

  for (unsigned long j = 0; j < longBits; ++j)
  {
    bitMask[j] = 1ul << j;                    // bit j set
    leqMask[j] = (bitMask[j]-1) | bitMask[j]; // bits 0..j set
    lMask[j+1] = leqMask[j];                  // lMask[j+1] has bits 0..j set
  }

  firstbit[0] = charBits; // out-of-bounds indication
  firstbit[1] = 0;

  // find least significant set bit by a simple recurrence
  for (unsigned int j = 1; j < (1 << (charBits-1)); ++j)
  {
    firstbit[2*j]   = firstbit[j]+1; // for even numbers use recursion
    firstbit[2*j+1] = 0;             // for odd numbers, it is 0
  }

  lastbit[0] = 0; // out-of-bounds indication
  lastbit[1] = 1; // this points to bit 0, because of position+1 convention

  // find most significant set bit by a simple recurrence
  for (unsigned int j = 1; j < (1 << (charBits-1)); ++j)
  {
    lastbit[2*j]   = lastbit[j]+1; // for even numbers use recursion
    lastbit[2*j+1] = lastbit[j]+1; // for odd numbers use recursion as well
  }

  return constants(); // return an (empty) instance of our own class
}
Example #7
0
  void Module::set_name(STATE, Symbol* name, Module* under) {
    if(!module_name()->nil_p()) return;

    if(under == G(object)) {
      module_name(state, name);
    } else {
      Symbol* under_name = under->module_name();

      if(!under_name->nil_p()) {
        std::ostringstream path_name;
        path_name << under_name->cpp_str(state) << "::" << name->cpp_str(state);
        module_name(state, state->symbol(path_name.str()));

        LookupTable::iterator i(constants());

        while(i.advance()) {
          if(Module* m = try_as<Module>(i.value())) {
            if(m->module_name()->nil_p()) {
              m->set_name(state, as<Symbol>(i.key()), this);
            }
          }
        }
      }
    }
  }
Example #8
0
/**************************************************************************//**
 *  Return a random position close to the supplied one. Same Shell.
******************************************************************************/
dVec Cylinder::randUpdateSmall (MTRand &random, const dVec &pos) const {
    dVec randPos;
    randPos = pos;
    for (int i = 0; i < NDIM; i++)
        randPos[i] += constants()->displaceDelta()*(-0.5 + random.rand());
    putInside(randPos);
    return randPos;
}
Example #9
0
 void
 Model::fail(void) {
   if (!_failed) {
     _failed = true;
     ConstraintI* failedConstraint = new ConstraintI(Location().introduce(),constants().lit_false);
     _items.push_back(failedConstraint);
   }
 }
Example #10
0
std::vector<constant_exprt> collect_literal_constants(
    const invariant_programt &program)
{
  const compare_constantt compare(program);
  constant_sett constants(compare);
  const constant_expr_visitort visitor(program, constants);
  const invariant_programt::program_ranget &range=program.invariant_range;
  std::for_each(range.begin, range.end, visitor);
  return std::vector<constant_exprt>(constants.begin(), constants.end());
}
Example #11
0
//---------------------------------------------------------------------
void Node::QueryUser()
{
	/*
	REGISTER sip:[email protected]
	To: <sip:[email protected]>
	From: <sip:[email protected]>

*/
	//char *aor="sip:[email protected]";

	char buf[50];
	printf("input the user aor you want to call\n");
	gets(buf);
	char *aor=buf;
	
	unsigned int uid=uhash(aor);
	Constants constants(NULL);
	ChordId UserID(uid,&constants);
	ChordId pred=mynode->getFingerTable()->getPredecessor();
	ChordId localnode=getChordId();
	
	//for test
	if(UserID.BelongsRightInclusive(pred,localnode))
	{
		printf("\nThe user infomation is on this node\n");
		uinfo_t *user_info=uinfo_t::find_user_info_by_aor(aor,user_info_list);
		char *dest;
		osip_uri_to_str(user_info->bindings->contact->url,&dest);
		printf("user contact is %s\n",dest);
		osip_free(dest);
		return;

	}
	else
	{
		ChordId next_hop=closestPrecedingFinger(UserID);
		//ChordId next_hop=getChordId();
		ChordId empty(-1,&constants);
		if(!next_hop.equals(empty))
		{
			char *tmp=next_hop.GetAddress();
			char *requri = (char *)osip_malloc (4 + strlen(tmp) + 1) ;
			sprintf (requri, "sip:%s", tmp);
			SndUserRegisterRequest(aor,requri);
			if(requri)	osip_free(requri) ;
		}
		else  //do not know where to send
		{
			return ;
		}
		
	}

}
Example #12
0
methodHandle Bytecode_invoke::static_target(TRAPS) {  
  methodHandle m;  
  KlassHandle resolved_klass;
  constantPoolHandle constants(THREAD, _method->constants());
  
  if (adjusted_invoke_code() != Bytecodes::_invokeinterface) {        
    LinkResolver::resolve_method(m, resolved_klass, constants, index(), CHECK_(methodHandle()));    
  } else {    
    LinkResolver::resolve_interface_method(m, resolved_klass, constants, index(), CHECK_(methodHandle()));
  }   
  return m;
}
Example #13
0
//---------------------------------------------------------------------
void
Node::TransferUserInfoToPred(ChordId node)
{
	uinfo_t *red_cur=red_user_info_list;
	uinfo_t *cur=user_info_list;
	while(red_cur != NULL)
	{
		char *red_aor;
		uinfo_t *red_tmp=red_cur;
		red_cur=red_cur->next;
		osip_uri_to_str(red_tmp->aor->uri,&red_aor);
		if(red_aor)	osip_free(red_aor) ;
			
		char * red_registrar= (char *)osip_malloc(4 + strlen(node.GetAddress()) +1) ;
		sprintf (red_registrar, "sip:%s", node.GetAddress());
		SndUserRegisterRequest(RED_REGISTER,red_tmp,red_registrar ,3600);
		if(red_registrar)	osip_free(red_registrar) ;
		
		REMOVE_ELEMENT(red_user_info_list,red_tmp);
		delete red_tmp;
		

	}
	
	ChordId localnode=getChordId();
	unsigned int uid=0;
	while(cur != NULL)
	{
		
		char *aor;
		uinfo_t *tmp=cur;
		cur=cur->next;
		osip_uri_to_str(tmp->aor->uri,&aor);
		uid=uhash(aor);
		if(aor)	osip_free(aor) ;

		Constants constants(NULL);
		ChordId UserID(uid,&constants);
		if(!UserID.BelongsRightInclusive(node,localnode))
		{
			char * registrar= (char *)osip_malloc(4 + strlen(node.GetAddress()) +1) ;
			sprintf (registrar, "sip:%s", node.GetAddress());
			SndUserRegisterRequest(USER_REGISTRATION,tmp,registrar,3600);
			if(registrar)	osip_free(registrar) ;
		
			REMOVE_ELEMENT(user_info_list,tmp);
			//ADD_ELEMENT(red_user_info_list,tmp);//move this user info to redundant user info list
			delete tmp;
		}
	}

}
void MatrixFunctionDialog::showConstants() {
	QMenu menu;
	ConstantsWidget constants(&menu);
	connect(&constants, SIGNAL(constantSelected(QString)), this, SLOT(insertConstant(QString)));
	connect(&constants, SIGNAL(constantSelected(QString)), &menu, SLOT(close()));
	connect(&constants, SIGNAL(canceled()), &menu, SLOT(close()));

	QWidgetAction* widgetAction = new QWidgetAction(this);
	widgetAction->setDefaultWidget(&constants);
	menu.addAction(widgetAction);

	QPoint pos(-menu.sizeHint().width()+ui.tbConstants->width(),-menu.sizeHint().height());
	menu.exec(ui.tbConstants->mapToGlobal(pos));
}
Example #15
0
  FunctionI*
  Model::matchFn(const ASTString& id,
                 const std::vector<Type>& t) {
    if (id==constants().var_redef->id())
      return constants().var_redef;
    Model* m = this;
    while (m->_parent)
      m = m->_parent;
    FnMap::iterator i_id = m->fnmap.find(id);
    if (i_id == m->fnmap.end()) {
      return NULL;
    }
    std::vector<FunctionI*>& v = i_id->second;
    for (unsigned int i=0; i<v.size(); i++) {
      FunctionI* fi = v[i];
#ifdef MZN_DEBUG_FUNCTION_REGISTRY
      std::cerr << "try " << *fi;
#endif
      if (fi->params().size() == t.size()) {
        bool match=true;
        for (unsigned int j=0; j<t.size(); j++) {
          if (!t[j].isSubtypeOf(fi->params()[j]->type())) {
#ifdef MZN_DEBUG_FUNCTION_REGISTRY
            std::cerr << t[j].toString() << " does not match "
            << fi->params()[j]->type().toString() << "\n";
#endif
            match=false;
            break;
          }
        }
        if (match) {
          return fi;
        }
      }
    }
    return NULL;
  }
Example #16
0
  FunctionI*
  Model::matchFn(Call* c) const {
    if (c->id()==constants().var_redef->id())
      return constants().var_redef;
    const Model* m = this;
    while (m->_parent)
      m = m->_parent;
    FnMap::const_iterator it = m->fnmap.find(c->id());
    if (it == m->fnmap.end()) {
      return NULL;
    }
    const std::vector<FunctionI*>& v = it->second;
    for (unsigned int i=0; i<v.size(); i++) {
      FunctionI* fi = v[i];
#ifdef MZN_DEBUG_FUNCTION_REGISTRY
      std::cerr << "try " << *fi;
#endif
      if (fi->params().size() == c->args().size()) {
        bool match=true;
        for (unsigned int j=0; j<c->args().size(); j++) {
          if (!c->args()[j]->type().isSubtypeOf(fi->params()[j]->type())) {
#ifdef MZN_DEBUG_FUNCTION_REGISTRY
            std::cerr << c->args()[j]->type().toString() << " does not match "
            << fi->params()[j]->type().toString() << "\n";
            std::cerr << "Wrong argument is " << *c->args()[j];
#endif
            match=false;
            break;
          }
        }
        if (match) {
          return fi;
        }
      }
    }
    return NULL;
  }
Example #17
0
void CCodeGenerator::operator()(Function* feature) {
    // Emit a function, or extern declaration if the function is native.
    String::Ptr id = feature->name();
	op_ = Operand();
    if (feature->is_virtual()) { return; }
	function_ = feature;
    loc(feature);
    line();
    func_sig(feature);
    if (feature->is_native()) {
        out_ << ";\n";
		function_ = 0;
        return;
    }
    out_ << " {\n"; 

    indent_ += 4;
    enter_scope();

    // Set up the 'self' variable with the constructor, if necessary; this 
    // allocates memory for the object using calloc.
    if (feature->is_constructor()) {
        ctor_preamble(class_);
    } 

    // If this is main(), then emit the code to load constants.
    String::Ptr name = feature->name();
    Feature::Ptr parent = feature->parent();
    if (name->string() == "main" && parent->name()->string() == "Boot") {
        assert(!"check for entry point instead of this hack");
        constants();
    }
    
    // Load constants
    //assert("Load constants" && 0); 

    Block::Ptr block = feature->block();
    block(this);

    if (feature->type()->is_void() || feature->is_constructor()) {
        func_return();
    }

    exit_scope();
    indent_ -= 4;
	function_ = 0;

	out_ << "}\n\n";
}
Example #18
0
/**************************************************************************//**
 *  Constructor.
 * 
 *  Initialize the worm object. 
 *  @param numParticles The number of particles
******************************************************************************/
Worm::Worm(int numParticles) {

	int numTimeSlices = constants()->numTimeSlices();

	/* Setup the bead array */
	beads.resize(numTimeSlices,numParticles);
	beads = 1;

	/* Count the initial number of beads */
	resetNumBeadsOn();

	/* The initial configuration is always diagonal */
	isConfigDiagonal = true;

	/* Max worm cost [PRE 74, 036701 (2006)] */
	maxWormCost = 4.0;

	/* Initialize the properties of the worm */
	reset();
}
TEST(SubstitutionMethod, forward)
{
    CompressedMatrix<double> coeficients(3, 3);
    coeficients[0][0] = 1;
    coeficients[1][0] = 1;
    coeficients[1][1] = 1;
    coeficients[2][0] = 1;
    coeficients[2][1] = 1;
    coeficients[2][2] = 1;

    CompressedMatrix<double> constants(3, 1);
    constants[0][0] = 1;
    constants[1][0] = 3;
    constants[2][0] = 6;

    CompressedMatrix<double> variables = SubstitutionMethod::forward(coeficients, constants);

    EXPECT_EQ(variables[0][0], 1.);
    EXPECT_EQ(variables[1][0], 2.);
    EXPECT_EQ(variables[2][0], 3.);
}
Example #20
0
/**************************************************************************//**
 *  Return a random position close to the supplied one. Shell Jump
******************************************************************************/
dVec Cylinder::randUpdateJumpShell (MTRand &random, const dVec &pos) const {
    dVec randPos;
    randPos = pos;
    double theta = atan2(pos[1],pos[0]);
    double oldr = sqrt(pos[0]*pos[0] + pos[1]*pos[1]);
    double newr;

    if (random.rand() > 0.5)
        newr = oldr + (1.00 + 2.50*random.rand());
    else
        newr = oldr - (1.00 + 2.50*random.rand());

    if (newr < 0.0)
        newr *= -1.0;

    double ranTheta = M_PI*(-0.05 + 0.1*random.rand());
    randPos[0] = newr*cos(theta + ranTheta);
    randPos[1] = newr*sin(theta + ranTheta);
    randPos[2] += constants()->displaceDelta()*(-0.5 + random.rand());

    putInside(randPos);
    return randPos;
}
      void
      UniqueLinSolveAtom::retrieve(const Query& query, 
			       Answer& answer) throw (PluginError)
      {
	Tuple parms = query.getInputTuple();
	
	std::string matrixPred = "";
	std::string constantPred = "";
	int argc = 2;
	char* argv[] = {"-linkname", "math -mathlink"};

	//check number and type of arguments
	if (parms.size()!= 2)
	  {
	    throw PluginError("Wrong number of arguments");
	  }
	else
	  {
	    if(parms[0].isSymbol() && parms[1].isSymbol()) 
	      {
		matrixPred = parms[0].getString();
		//std::cout << "Matrixpraedikat: " << matrixPred << std::endl;
		constantPred = parms[1].getString();
		//std::cout << "Vektorpraedikat: " << vectorPred << std::endl;
	      }
	    else
	      {
		throw PluginError("Wrong type of arguments");
	      }
	  }
	//get complete Interpretation of given predicates in query
	AtomSet totalInt = query.getInterpretation();
	AtomSet matrixInt;
	AtomSet constantInt;
      
	if (totalInt.empty()) 
	  {
	    throw PluginError("Could not find any interpretion");
	  }
	else 
	  {
	    // separate interpretation into facts of first predicate (matrix)
	    totalInt.matchPredicate(matrixPred, matrixInt);
	    // and into facts of second predicate (vector)
	    totalInt.matchPredicate(constantPred, constantInt);
	  }
	
	int mRows = 0;
	int mColumns = 0;
	int cRows = 0;
	int cColumns = 0;
	evaluateMatrix(matrixInt, mRows, mColumns);
	evaluateVector(constantInt, cRows, cColumns);
	
	if(mRows != cRows) throw PluginError("Coefficient matrix and target vector(s) or matrix do not have the same dimensions.");

	std::vector <std::vector <std::string> > matrix(mRows);
	for(int i = 0; i < mRows; i++)
	  matrix[i].resize(mColumns);
	
	std::vector <std::vector <std::string> > constants(cRows);
	for (int i = 0; i < cRows; i++)
	  constants[i].resize(cColumns);

	//write the values of the Atoms in the Interpretation into std::vectors for further processing
	convertMatrixToVector(matrixInt, mRows, mColumns, matrix);
	convertMatrixToVector(constantInt, cRows, cColumns, constants); 

	//check if matrix and target vector or matrix are fully defined
	checkVector(matrix, mRows, mColumns, matrixPred);
	checkVector(constants, cRows, cColumns, constantPred);
	 
	//convert matrix to MatrixRank-expression and calculate rank of coefficient matrix A 
	std::string coeffMRankExpr = toMatrixRankExpr(matrix, mRows, mColumns);
	//std::cout << "MatrixRank expression: " << coeffMRankExpr << std::endl;
	int coeffMRank = calculateRank(argc, argv, coeffMRankExpr);

	//convert matrix A and target b to MatrixRank-expression and calculate rank
	//of extended coefficient matrix [A,b]
	std::string extendedMRankExpr = toMatrixRankExpr(matrix, mRows, mColumns, constants, cRows, cColumns);
	//std::cout << "Extended MatrixRank expression: " << extendedMRankExpr << std::endl;
	int extCoeffMRank = calculateRank(argc, argv, extendedMRankExpr);

	//compare calculated ranks and number of matrix colums, iff they are equal, 
	//a unique solution for the matrix equation exists
	if ((coeffMRank == extCoeffMRank) && (coeffMRank == mColumns))
	  {
	    std::string linSolExpr = toLinearSolveExpr(matrix, mRows, mColumns, constants, cRows, cColumns);
	    std::vector <std::string> result;
	    result = calculateSolution(argc, argv, linSolExpr);
	    if(result.size() != mColumns*cColumns)
	      throw PluginError("Wrong number of arguments in result vector");
	    Tuple out;
	    int index = 0;

	    //fill the result values with correct indices into Tuple out
	    //and add all Tuples to Answer
	    for (int r = 1; r <= mColumns; r++)
	      {
		for(int c = 1; c<= cColumns; c++)
		  {
		    out.push_back(Term(r));
		    out.push_back(Term(c));
		    out.push_back(Term(result[index],true));
		    answer.addTuple(out);
		    out.clear();
		    index++;
		  }
	      }
	  }
      }      
Example #22
0
int main( int argc, char *argv[] )
{
	static char com[10000];
	static int  *nlen;	
	int left, right;
	int res;
	static char **name, **seq, **nogap;
	static int **gapmap;
	static int *order;
	int i, j;
	FILE *infp;
	RNApair ***pairprob;
	RNApair **alnpairprob;
	RNApair *pairprobpt;
	RNApair *pt;
	int *alnpairnum;
	float prob;
	int adpos;

	arguments( argc, argv );
#ifndef enablemultithread
	nthread = 0;
#endif

	if( inputfile )
	{
		infp = fopen( inputfile, "r" );
		if( !infp )
		{
			fprintf( stderr, "Cannot open %s\n", inputfile );
			exit( 1 );
		}
	}
	else
		infp = stdin;

	if( !whereismccaskillmea )
		whereismccaskillmea = "";

	getnumlen( infp );
	rewind( infp );

	if( dorp != 'd' )
	{
		fprintf( stderr, "nuc only\n" );
		exit( 1 );
	}

	seq = AllocateCharMtx( njob, nlenmax*2+1 );
	nogap = AllocateCharMtx( njob, nlenmax*2+1 );
	gapmap = AllocateIntMtx( njob, nlenmax*2+1 );
	order = AllocateIntVec( njob );
	name = AllocateCharMtx( njob, B+1 );
	nlen = AllocateIntVec( njob );
	pairprob = (RNApair ***)calloc( njob, sizeof( RNApair ** ) );
	alnpairprob = (RNApair **)calloc( nlenmax, sizeof( RNApair * ) );
	alnpairnum = AllocateIntVec( nlenmax );

	for( i=0; i<nlenmax; i++ ) alnpairnum[i] = 0;

	readData_pointer( infp, name, nlen, seq );
	fclose( infp );

	for( i=0; i<njob; i++ )
	{
		pairprob[i] = (RNApair **)calloc( nlenmax, sizeof( RNApair * ) );
		for( j=0; j<nlenmax; j++ )
		{
			pairprob[i][j] = (RNApair *)calloc( 1, sizeof( RNApair ) );
			pairprob[i][j][0].bestpos = -1;
			pairprob[i][j][0].bestscore = -1.0;
		}
		strcpy( nogap[i], seq[i] );
		order[i] = i;
	}
	for( j=0; j<nlenmax; j++ )
	{
		alnpairprob[j] = (RNApair *)calloc( 1, sizeof( RNApair ) );
		alnpairprob[j][0].bestpos = -1;
		alnpairprob[j][0].bestscore = -1.0;
	}


	constants( njob, seq );

	if( alg == 'G' )
		fprintf( stderr, "Running DAFS (Sato et al. 2012; http://www.ncrna.org/).\n" );
	else
		fprintf( stderr, "Running mxscarna with the mccaskill_mea mode.\n" );
#ifdef enablemultithread
	if( nthread > 0 )
	{
		int jobpos;
		pthread_t *handle;
		pthread_mutex_t mutex;
		thread_arg_t *targ;
		jobpos = 0;

		targ = calloc( nthread, sizeof( thread_arg_t ) );
		handle = calloc( nthread, sizeof( pthread_t ) );
		pthread_mutex_init( &mutex, NULL );

		for( i=0; i<nthread; i++ )
		{
			targ[i].thread_no = i;
			targ[i].njob = njob;
			targ[i].jobpospt = &jobpos;
			targ[i].gapmap = gapmap;
			targ[i].nogap = nogap;
			targ[i].nlenmax = nlenmax;
			targ[i].pairprob = pairprob;
			targ[i].mutex = &mutex;

//			athread( targ );
			pthread_create( handle+i, NULL, athread, (void *)(targ+i) );
			
		}

		for( i=0; i<nthread; i++ )
		{
			pthread_join( handle[i], NULL );
		}
		pthread_mutex_destroy( &mutex );


		for( i=0; i<njob; i++ )
		{
			fprintf( stdout, ">%d\n", i );
			outmccaskill( stdout, pairprob[i], nlenmax );
		}
	}
	else
#endif
	{
		for( i=0; i<njob; i++ )
		{
			fprintf( stderr, "%d / %d\n", i+1, njob );
			commongappick_record( 1, nogap+i, gapmap[i] );
			infp = fopen( "_mccaskillinorg", "w" );
//			fprintf( infp, ">in\n%s\n", nogap[i] );
			fprintf( infp, ">in\n" );
			write1seq( infp, nogap[i] );
			fclose( infp );
	
			system( "tr -d '\\r' < _mccaskillinorg > _mccaskillin" ); // for cygwin, wakaran
			if( alg == 'G' )
				sprintf( com, "env PATH=%s dafs --mafft-out _mccaskillout _mccaskillin > _dum1 2>_dum", whereismccaskillmea );
			else
				sprintf( com, "env PATH=%s mxscarnamod -m -writebpp  _mccaskillin > _mccaskillout 2>_dum", whereismccaskillmea );
			res = system( com );
	
			if( res )
			{
				fprintf( stderr, "ERROR IN mccaskill_mea\n" );
				exit( 1 );
			}
	
			infp = fopen( "_mccaskillout", "r" );
			readrawmccaskill( infp, pairprob[i], nlenmax );
			fclose( infp );
			fprintf( stdout, ">%d\n", i );
			outmccaskill( stdout, pairprob[i], nlenmax );
		}
	}

	for( i=0; i<njob; i++ )
	{
		for( j=0; j<nlen[i]; j++ ) for( pairprobpt=pairprob[i][j]; pairprobpt->bestpos!=-1; pairprobpt++ )
		{
			left = gapmap[i][j];
			right = gapmap[i][pairprobpt->bestpos];
			prob = pairprobpt->bestscore;

			for( pt=alnpairprob[left]; pt->bestpos!=-1; pt++ )
				if( pt->bestpos == right ) break;

			if( pt->bestpos == -1 )
			{
				alnpairprob[left] = (RNApair *)realloc( alnpairprob[left], (alnpairnum[left]+2) * sizeof( RNApair ) );
				adpos = alnpairnum[left];
				alnpairnum[left]++;
				alnpairprob[left][adpos].bestscore = 0.0;
				alnpairprob[left][adpos].bestpos = right;
				alnpairprob[left][adpos+1].bestscore = -1.0;
				alnpairprob[left][adpos+1].bestpos = -1;
				pt = alnpairprob[left]+adpos;
			}
			else
				adpos = pt-alnpairprob[left];

			pt->bestscore += prob;
			if( pt->bestpos != right )
			{
				fprintf( stderr, "okashii!\n" );
				exit( 1 );
			}
//			fprintf( stderr, "adding %d-%d, %f\n", left, right, prob );
		}
	}

	for( i=0; i<njob; i++ )
	{
		for( j=0; j<nlenmax; j++ ) free( pairprob[i][j] );
		free( pairprob[i] );
	}
	free( pairprob );
	for( j=0; j<nlenmax; j++ ) free( alnpairprob[j] );
	free( alnpairprob );
	free( alnpairnum );
	fprintf( stderr, "%d thread(s)\n", nthread );
	return( 0 );

#if 0
	fprintf( stdout, "result=\n" );

	for( i=0; i<nlenmax; i++ ) for( pairprobpt=alnpairprob[i]; pairprobpt->bestpos!=-1; pairprobpt++ )
	{
		pairprobpt->bestscore /= (float)njob;
		left = i;
		right = pairprobpt->bestpos;
		prob = pairprobpt->bestscore;
		fprintf( stdout, "%d-%d, %f\n", left, right, prob );
	}

	return( 0 );
#endif
}
Example #23
0
int main( int argc, char **argv )
{
	int i, j;
	FILE *fp, *infp;
	char **seq;
	int *grpseq;
	char *tmpseq;
	int  **pointt;
	static char name[M][B];
	static int nlen[M];
	double **mtx;
	double **mtx2;
	double score, score0;
	static short *table1;
	char b[B];

	arguments( argc, argv );

	if( inputfile )
	{
		infp = fopen( inputfile, "r" );
		if( !infp )
		{
			fprintf( stderr, "Cannot open %s\n", inputfile );
			exit( 1 );
		}
	}
	else
		infp = stdin;

#if 0
	PreRead( stdin, &njob, &nlenmax );
#else
	getnumlen( infp );
#endif
	rewind( infp );
	if( njob < 2 )
	{
		fprintf( stderr, "At least 2 sequences should be input!\n"
						 "Only %d sequence found.\n", njob );
		exit( 1 );
	}

	tmpseq = AllocateCharVec( nlenmax+1 );
	seq = AllocateCharMtx( njob, nlenmax+1 );
	grpseq = AllocateIntVec( nlenmax+1 );
	pointt = AllocateIntMtx( njob, nlenmax+1 );
	mtx = AllocateDoubleMtx( njob, njob );
	mtx2 = AllocateDoubleMtx( njob, njob );
	pamN = NOTSPECIFIED;

#if 0
	FRead( infp, name, nlen, seq );
#else
	readData( infp, name, nlen, seq );
#endif

	fclose( infp );

	constants( njob, seq );

	if( dorp == 'd' ) tsize = (int)pow( 4, 6 );
	else              tsize = (int)pow( 6, 6 );

	maxl = 0;
	for( i=0; i<njob; i++ ) 
	{
		gappick0( tmpseq, seq[i] );
		nlen[i] = strlen( tmpseq );
		if( nlen[i] < 6 )
		{
			fprintf( stderr, "Seq %d, too short, %d characters\n", i+1, nlen[i] );
			exit( 1 );
		}
		if( nlen[i] > maxl ) maxl = nlen[i];
		if( dorp == 'd' ) /* nuc */
		{
			seq_grp_nuc( grpseq, tmpseq );
			makepointtable_nuc( pointt[i], grpseq );
		}
		else                 /* amino */
		{
			seq_grp( grpseq, tmpseq );
			makepointtable( pointt[i], grpseq );
		}
	}
	for( i=0; i<njob; i++ )
	{
		table1 = (short *)calloc( tsize, sizeof( short ) );
		if( !table1 ) ErrorExit( "Cannot allocate table1\n" );
		if( i % 10 == 0 )
		{
			fprintf( stderr, "%4d / %4d\r", i+1, njob );
		}
		makecompositiontable_p( table1, pointt[i] );

		for( j=i; j<njob; j++ ) 
		{
			score = (double)commonsextet_p( table1, pointt[j] );
			mtx[i][j] = score;
		} 
		free( table1 );
	}
	for( i=0; i<njob; i++ )
	{
		score0 = mtx[i][i];
		for( j=0; j<njob; j++ ) 
			mtx2[i][j] = ( score0 - mtx[MIN(i,j)][MAX(i,j)] ) / score0 * 3.0;
	}
	for( i=0; i<njob-1; i++ ) for( j=i+1; j<njob; j++ ) 
	{
#if TEST
                double jscore;
                jscore = mtx[i][j] / ( MIN( strlen( seq[i] ), strlen( seq[j] ) ) - 2 );
                fprintf( stdout, "jscore = %f\n", jscore );

		fprintf( stdout, "mtx2[%d][%d] = %f, mtx2[%d][%d] = %f\n", i, j, mtx2[i][j], j, i, mtx2[j][i] );
#endif
		mtx2[i][j] = MIN( mtx2[i][j], mtx2[j][i] );
#if TEST
		fprintf( stdout, "sonokekka mtx2[%d][%d] %f\n", i, j, mtx2[i][j] );
#endif
	}

	if( disopt )
	{
		for( i=0; i<njob; i++ ) 
		{
			sprintf( b, "=lgth = %04d", nlen[i] );
			strins( b, name[i] );
		}
	}
		
	fp = fopen( "hat2", "w" );
	if( !fp ) ErrorExit( "Cannot open hat2." );
	WriteHat2( fp, njob, name, mtx2 );
	fclose( fp );

	fprintf( stderr, "\n" );
	SHOWVERSION;
	exit( 0 );
}
Example #24
0
int main( int argc, char *argv[] )
{
	static int  nlen[M];	
	static char **name, **seq;
	int i, j, alloclen, c;
	double **mtx;
	double *self;
	double tmpdouble;
	FILE *fp;

	arguments( argc, argv );

	getnumlen( stdin );
	rewind( stdin );

	if( njob < 2 )
	{
		fprintf( stderr, "At least 2 sequences should be input!\n"
						 "Only %d sequence found.\n", njob ); 
		exit( 1 );
	}

	name = AllocateCharMtx( njob, B+1 );
	seq = AllocateCharMtx( njob, nlenmax*9+1 );
	mtx = AllocateDoubleMtx( njob, njob );
	self = AllocateDoubleVec( njob );
	alloclen = nlenmax*9;

	readData_pointer( stdin, name, nlen, seq );
	constants( njob, seq );




	c = seqcheck( seq );
	if( c )
	{
		fprintf( stderr, "Illeagal character %c\n", c );
		exit( 1 );
	}

	for( i=0; i<njob; i++ ) 
	{
		self[i] = (double)substitution_nid( seq[i], seq[i] );
//		fprintf( stdout, "self[%d] = %f\n", i, self[i] );
	}

	for( i=0; i<njob-1; i++ ) 
		for( j=i+1; j<njob; j++ ) 
		{
			tmpdouble = (double)substitution_score( seq[i], seq[j] );
//			fprintf( stdout, "tmpdouble = %f\n", tmpdouble );
			mtx[i][j] = ( 1.0 - tmpdouble / MIN( self[i], self[j] ) );
			if( mtx[i][j] < 0.95 )
				mtx[i][j] = - log( 1.0 - mtx[i][j] );
			else
				mtx[i][j] = 3.0;
		}
	
#if TEST
	for( i=0; i<njob-1; i++ ) for( j=i+1; j<njob; j++ ) 
		fprintf( stdout, "i=%d, j=%d, mtx[][] = %f\n", i, j, mtx[i][j] );
#endif

	fp = fopen( "hat2", "w" );
	WriteHat2_pointer( fp, njob, name, mtx );
	fclose( fp );
	exit( 0 );

	return( 0 );
}
Example #25
0
 void Module::setup(STATE) {
   constants(state, LookupTable::create(state));
   method_table(state, MethodTable::create(state));
 }
Example #26
0
int main( int argc, char **argv )
{
	int i, j;
	char **seq;
	static char **name;
	static int nlen[M];
	float *selfscore;
	double **mtx;
	FILE *fp;
	FILE *infp;
	float ssi, ssj, bunbo;


	arguments( argc, argv );
#ifndef enablemultithread
	nthread = 0;
#endif

	if( inputfile )
	{
		infp = fopen( inputfile, "r" );
		if( !infp )
		{
			fprintf( stderr, "Cannot open %s\n", inputfile );
			exit( 1 );
		}
	}
	else
		infp = stdin;

#if 0
	PreRead( stdin, &njob, &nlenmax );
#else
	getnumlen( infp );
#endif
	rewind( infp );

	seq = AllocateCharMtx( njob, nlenmax+1 );
	name = AllocateCharMtx( njob, B+1 );
	mtx = AllocateDoubleMtx( njob, njob );
	selfscore = AllocateFloatVec( njob );

#if 0
	FRead( stdin, name, nlen, seq );
#else
	readData_pointer( infp, name, nlen, seq );
#endif
	fclose( infp );

	constants( njob, seq );

#if 0
	for( i=0; i<njob-1; i++ ) 
	{
		fprintf( stderr, "%4d/%4d\r", i+1, njob );
		for( j=i+1; j<njob; j++ ) 
			mtx[i][j] = (double)substitution_hosei( seq[i], seq[j] );
//			fprintf( stderr, "i=%d,j=%d, l=%d &&&  %f\n", i, j, nlen[0], mtx[i][j] );
	}
#else // 061003
	for( i=0; i<njob; i++ )
	{
		selfscore[i] = (float)naivepairscore11( seq[i], seq[i], penalty );

	}
#ifdef enablemultithread
	if( nthread > 0 )
	{
		thread_arg_t *targ;
		Jobtable jobpos;
		pthread_t *handle;
		pthread_mutex_t mutex;

		jobpos.i = 0;
		jobpos.j = 0;

		targ = calloc( nthread, sizeof( thread_arg_t ) );
		handle = calloc( nthread, sizeof( pthread_t ) );
		pthread_mutex_init( &mutex, NULL );

		for( i=0; i<nthread; i++ )
		{
			targ[i].thread_no = i;
			targ[i].njob = njob;
			targ[i].selfscore = selfscore;
			targ[i].mtx = mtx;
			targ[i].seq = seq;
			targ[i].jobpospt = &jobpos;
			targ[i].mutex = &mutex;

			pthread_create( handle+i, NULL, athread, (void *)(targ+i) );
		}

		for( i=0; i<nthread; i++ )
		{
			pthread_join( handle[i], NULL );
		}
		pthread_mutex_destroy( &mutex );
	}
	else
#endif
	{
		for( i=0; i<njob-1; i++ )
		{
			ssi = selfscore[i];
			fprintf( stderr, "%4d/%4d\r", i+1, njob );
			for( j=i+1; j<njob; j++ )
			{
				ssj = selfscore[j];
				bunbo = MIN( ssi, ssj );
				if( bunbo == 0.0 )
					mtx[i][j] = 1.0;
				else
					mtx[i][j] = 1.0 - (double)naivepairscore11( seq[i], seq[j], penalty ) / bunbo;
//					mtx[i][j] = 1.0 - (double)naivepairscore11( seq[i], seq[j], penalty ) / MIN( selfscore[i], selfscore[j] );
//				fprintf( stderr, "i=%d,j=%d, l=%d### %f, score = %d\n", i, j, nlen[0], mtx[i][j], naivepairscore11( seq[i], seq[j], penalty )  );
			}
		}
	}
#endif
	
#if TEST
	for( i=0; i<njob-1; i++ ) for( j=i+1; j<njob; j++ ) 
		fprintf( stdout, "i=%d, j=%d, mtx[][] = %f\n", i, j, mtx[i][j] );
#endif

	fp = fopen( "hat2", "w" );
	WriteHat2_pointer( fp, njob, name, mtx );
	fclose( fp );
#if 0
	if( treeout )
	{
		int ***topol;
		double **len;

		topol = AllocateIntCub( njob, 2, njob );
		len = AllocateDoubleMtx( njob, njob );
		veryfastsupg_double_outtree( njob, mtx, topol, len );
	}
#endif
	SHOWVERSION;
	exit( 0 );
/*
	res = system( ALNDIR "/spgsdl < hat2"  );
	if( res ) exit( 1 );
	else exit( 0 );
*/
}
Example #27
0
 void Module::set_const(STATE, Object* sym, Object* val) {
   constants()->store(state, sym, val);
   state->shared().inc_global_serial(state);
 }
Example #28
0
void Node::RegisterUser(REG_TYPE type,char * aor,char *contact,char *username,char * passwd)
{
	/*
      REGISTER sip:[email protected] SIP/2.0
	  Via:SIP/2.0/UDP 192.168.1.61:15060;branch=z9hG4bkxxxxx
      To:liqq <sip:[email protected]>
	  From:liqq <sip:[email protected]>
	  Call-ID:
	  CSeq:
	  Contact:<sip:[email protected]>
	  Content-Length:0
	  */
	/*判断本节点是否对该用户信息负责,
	如果负责,添加到user_info_list,
	如果不负责,计算next-hop,并发送REGISTER请求*/
	unsigned int uid;
	uid=uhash(aor);
	ChordId localnode=getChordId();
	ChordId pred=getFingerTable()->getPredecessor();
	Constants constants(NULL);
	ChordId UserID(uid,&constants);

	aor_t aaor(aor);
	binding_t abind(contact);
	uinfo_t *user_info=new uinfo_t(username,passwd);
	user_info->uinfo_set_aor(&aaor);
	user_info->uinfo_set_binding(&abind);
	ADD_ELEMENT(local_user_info_list,user_info);

//	int lid=localnode.GetId();
//	int pid=predecessor.GetId();
	
	//if((lid<pid && uid<=lid && uid>pid)||(lid>pid && (uid < lid || uid >=pid)))
	if(UserID.BelongsRightInclusive(pred,localnode))
	{
		printf("Add a new local user\n");
		uinfo_t *uinfo=new uinfo_t(username,passwd);
		uinfo->uinfo_set_aor(&aaor);
		uinfo->uinfo_set_binding(&abind);
		ADD_ELEMENT(user_info_list,uinfo);
		
		if(pred.equals(localnode))
		{
			uinfo_t *ruinfo=new uinfo_t(username,passwd);
			ruinfo->uinfo_set_aor(&aaor);
			ruinfo->uinfo_set_binding(&abind);
			ADD_ELEMENT(red_user_info_list,ruinfo);
		}
		ChordId succ=getFingerTable()->getSuccessor(0);
		if(!succ.equals(getChordId()))
		{
		string next_hop="sip:";
		next_hop+=succ.GetAddress();
		SndUserRegisterRequest(RED_REGISTER,uinfo,next_hop.c_str() ,3600);
		}
	}
	else
	{
		ChordId	node=closestPrecedingFinger(UserID);
		//ChordId node=getFingerTable()->getPredecessor();
		//ChordId node=getChordId();
		string registrar="sip:";
		registrar+=node.GetAddress();
		SndUserRegisterRequest(USER_REGISTRATION,user_info,registrar.c_str() ,3600);

	}

}
Example #29
0
/**
 * Main driver.
 * Read in all program options from the user using boost::program_options and setup the simulation
 * cell, initial conditions and both the interaction and external potential. Either equilibrate or
 * restart a simulation, then start measuring. We output all the simulation parameters to disk as a
 * log file so that it can be restart again assigning it a unique PIMCID.
 * @see boost::program_options -- http://www.boost.org/doc/libs/1_43_0/doc/html/program_options.html
 */
int main (int argc, char *argv[]) {

    /* Get initial time */
    time_t start_time = time(NULL);
    time_t current_time; //current time
    bool wallClockReached = false;

	uint32 seed = 139853;	// The seed for the random number generator

	Setup setup;

	/* Attempt to parse the command line options */
    try {
		setup.getOptions(argc,argv);
    }
    catch(exception& ex) {
        cerr << "error: " << ex.what() << "\n";
        return 1;
    }
    catch(...) {
        cerr << "Exception of unknown type!\n";
    }

	/* Parse the setup options and possibly exit */
	if (setup.parseOptions())
		return 1;

	/* The global random number generator, we add the process number to the seed (for
	 * use in parallel simulations.*/
	seed = setup.seed(seed);
	MTRand random(seed);

	/* Get the simulation box */
	Container *boxPtr = NULL;
	boxPtr = setup.cell();

	/* Create the worldlines */
	if (setup.worldlines())
		return 1;

	/* Setup the simulation constants */
	setup.setConstants();

	/* Setup the simulation communicator */
	setup.communicator();

    /* Get number of paths to use */
    int Npaths = constants()->Npaths();

    /* Create and initialize the Nearest Neighbor Lookup Table */
    boost::ptr_vector<LookupTable> lookupPtrVec;
    for(int i=0; i<Npaths; i++){
        lookupPtrVec.push_back(
                new LookupTable(boxPtr,constants()->numTimeSlices(),
                                constants()->initialNumParticles()));
    }

	/* Create and initialize the potential pointers */
	PotentialBase *interactionPotentialPtr = NULL;
	interactionPotentialPtr = setup.interactionPotential();

	PotentialBase *externalPotentialPtr = NULL;
	externalPotentialPtr = setup.externalPotential(boxPtr);

	/* Get the initial conditions associated with the external potential */
	/* Must use the copy constructor as we return a copy */
	Array<dVec,1> initialPos =
		externalPotentialPtr->initialConfig(boxPtr,random,constants()->initialNumParticles());

    externalPotentialPtr->output(9.0);
    exit(-1);

    // dVec pos;
    // pos = 0.0;
    // cout << "Testing Potential = " << externalPotentialPtr->V(pos) << endl;
    // exit(-1);

    /* Perform a classical canonical pre-equilibration to obtain a suitable
     * initial state */
	if (!constants()->restart()) {
       ClassicalMonteCarlo CMC(externalPotentialPtr,interactionPotentialPtr,random,boxPtr,
               initialPos);
       CMC.run(constants()->numEqSteps(),0);
   }

	/* Setup the path data variable */
    vector<Path *> pathPtrVec;
    for(int i=0; i<Npaths; i++){
        pathPtrVec.push_back(
                new Path(boxPtr,lookupPtrVec[i],constants()->numTimeSlices(),
                         initialPos,constants()->numBroken()));
    }

    /* The Trial Wave Function (constant for pimc) */
    WaveFunctionBase *waveFunctionPtr = NULL;
	waveFunctionPtr = setup.waveFunction(*pathPtrVec.front());

	/* Setup the action */
    vector<ActionBase *> actionPtrVec;
    for(int i=0; i<Npaths; i++){
        actionPtrVec.push_back(
                setup.action(*pathPtrVec[i],lookupPtrVec[i],externalPotentialPtr,
                             interactionPotentialPtr,waveFunctionPtr) );
    }

    /* The list of Monte Carlo updates (moves) that will be performed */
    vector< boost::ptr_vector<MoveBase> * > movesPtrVec;
    for(int i=0; i<Npaths;i++){
        movesPtrVec.push_back(
                setup.moves(*pathPtrVec[i],actionPtrVec[i],random).release());
    }

    /* The list of estimators that will be performed */
    /*vector< boost::ptr_vector<EstimatorBase> * > estimatorsPtrVec;
    for(int i=0; i<Npaths;i++){
        estimatorsPtrVec.push_back(
                setup.estimators(*pathPtrVec[i],actionPtrVec[i],random).release());
        if(i > 0) {
            for(uint32 j=0; j<estimatorsPtrVec.back()->size(); j++)
                estimatorsPtrVec.back()->at(j).appendLabel(str(format("%d") % (i+1)));
        }
    }
    */

   /* The list of estimators that will be performed */
    vector< boost::ptr_vector<EstimatorBase> * > estimatorsPtrVec;
    for(int i=0; i<Npaths;i++){
        estimatorsPtrVec.push_back(setup.estimators(*pathPtrVec[i],actionPtrVec[i],random).release());
        if(i>0){
            stringstream tmpSS;
            for(unsigned j=0; j<estimatorsPtrVec.back()->size(); j++){
                tmpSS.str("");
                tmpSS << i+1 ;
                estimatorsPtrVec.back()->at(j).appendLabel(tmpSS.str());
            }
        }
    }

    /* Setup the multi-path estimators */
    if(Npaths>1){
        estimatorsPtrVec.push_back(setup.multiPathEstimators(pathPtrVec,actionPtrVec).release());
    }




	/* Setup the pimc object */
    PathIntegralMonteCarlo pimc(pathPtrVec,random,movesPtrVec,estimatorsPtrVec,
                                !setup.params["start_with_state"].as<string>().empty(),
                                setup.params["bin_size"].as<int>());

	/* If this is a fresh run, we equilibrate and output simulation parameters to disk */
	if (!constants()->restart()) {

		/* Equilibrate */
		cout << format("[PIMCID: %09d] - Equilibration Stage.") % constants()->id() << endl;
		for (uint32 n = 0; n < constants()->numEqSteps(); n++)
			pimc.equilStep(n,setup.params.count("relax"),setup.params.count("relaxmu"));

		/* Output simulation details/parameters */
		setup.outputOptions(argc,argv,seed,boxPtr,lookupPtrVec.front().getNumNNGrid());
	}

	cout << format("[PIMCID: %09d] - Measurement Stage.") % constants()->id() << endl;

	/* Sample */
	int oldNumStored = 0;
	int outNum = 0;
	int numOutput = setup.params["output_config"].as<int>();
	uint32 n = 0;
	do {
		pimc.step();
		if (pimc.numStoredBins > oldNumStored) {
			oldNumStored = pimc.numStoredBins;
			cout << format("[PIMCID: %09d] - Bin #%4d stored to disk.") % constants()->id()
				% oldNumStored << endl;
		}
		n++;

		/* Output configurations to disk */
		if ((numOutput > 0) && ((n % numOutput) == 0)) {
			pathPtrVec.front()->outputConfig(outNum);
			outNum++;
		}

        /* Check if we've reached the wall clock limit*/
        if(constants()->wallClockOn()){
            current_time = time(NULL);
            if ( uint32(current_time)  > (uint32(start_time) + constants()->wallClock()) ){
                wallClockReached = true;
                break;
            }
        }
	} while (pimc.numStoredBins < setup.params["number_bins_stored"].as<int>());
    if (wallClockReached)
        cout << format("[PIMCID: %09d] - Wall clock limit reached.") % constants()->id() << endl;
    else
        cout << format("[PIMCID: %09d] - Measurement complete.") % constants()->id() << endl;

	/* Output Results */
    if (!constants()->saveStateFiles())
        pimc.saveStateFromStr();
	pimc.finalOutput();

	/* Free up memory */
	delete interactionPotentialPtr;
	delete externalPotentialPtr;
	delete boxPtr;
    delete waveFunctionPtr;

	initialPos.free();

	return 1;
}
Example #30
0
 void Module::del_const(STATE, Symbol* sym) {
   constants()->remove(state, sym);
   state->shared().inc_global_serial(state);
 }