Пример #1
0
void ArgList::getSlice(int startIndex, ArgList& result) const
{
    if (startIndex <= 0 || static_cast<unsigned>(startIndex) >= m_argCount) {
        result = ArgList(m_args, 0);
        return;
    }
    result = ArgList(m_args + startIndex, m_argCount - startIndex);
}
Пример #2
0
const SpObject *SpVM::eval(const SpExpr *expr, SpEnv *env) {
   // check whether this expression is an atom or a function call
   if (expr->head()->type() == TOKEN_FUNCTION_CALL) {
      // this is a function call expression
      std::string func_name(expr->head()->value());

      // we find the function associated with this name in the given environment
      const SpObject *obj = resolve(func_name, env);
      if (obj == NULL || obj->type() != T_FUNCTION) RUNTIME_ERROR_F("'%s' is not a function", func_name.c_str());

      // now call the function
      return call_function(func_name, 
         static_cast<const SpFunction *>(obj->self()), expr, env);
   } else {
      // evaluate this atom
      std::string val = expr->head()->value();
      switch (expr->head()->type()) {
         case TOKEN_NAME: {
            const SpObject *obj = resolve(val, env); 
            if (obj == NULL)
               RUNTIME_ERROR_F("Undeclared variable '%s'", val.c_str());
            return obj->shallow_copy();
         }
         case TOKEN_NUMERIC:
            return new SpIntValue(atoi(val.c_str()));
         case TOKEN_CLOSURE:
            // the closure expression is stored in the first argument of the
            // object expression
            return new SpRefObject(new SpClosure(ArgList(), NULL, *expr->cbegin()));
         default:
            RUNTIME_ERROR("Unsupported operation");
      }
   }
}
Пример #3
0
// ParmFile::WritePrefixTopology()
int ParmFile::WritePrefixTopology(Topology const& Top, std::string const& prefix,
                                  ParmFormatType fmtIn, int debugIn)
{
  if (prefix.empty()) return 1;
  std::string newfilename = prefix + "." + Top.OriginalFilename().Base();
  return WriteTopology(Top, newfilename, ArgList(), fmtIn, debugIn);
}
Пример #4
0
ff::ArgList ff::SignatureParser::parseArgument(const std::string &str, std::string::size_type l, std::string::size_type r)
{
    if (l + 1 >= r) return ArgList(ff::T_Void);

    string astr = str.substr(l + 1, r - l - 1);

    {// (void)
        if (cc::trim(astr) == string("void")) {
            return ArgList(ff::T_Void);
        }
    }
    { // (/count)
        string::size_type slash_pos = 0;

        if ((slash_pos = astr.rfind('/', r)) != string::npos) {
            string count_str = str.substr(slash_pos + 1);

            size_t count = std::atoi(count_str.c_str());

            return ArgList(count);
        }
    }
    {// (type name, ...)
        vector<string> al = cc::splitString(astr, ',', cc::trim);

        string::size_type space_pos = 0;

        ArgList arglist(ff::T_List);

        for (vector<string>::iterator it = al.begin();  \
             it != al.end();it ++) {
            if (it->empty()) {
                arglist.arglist.push_back(ArgumentType(T_Any));
                continue;
            }
            if ((space_pos = it->find(' ')) == string::npos) {
                arglist.arglist.push_back(ArgumentType(it->substr(0, space_pos),  \
                                                cc::trim(it->substr(space_pos))));
            } else {
                arglist.arglist.push_back(ArgumentType(*it));
            }
        }
    }

    return ArgList(T_Error);
}
Пример #5
0
void ArgList::getSlice(int startIndex, ArgList& result) const
{
    if (startIndex <= 0 || startIndex >= m_argCount) {
        result = ArgList();
        return;
    }

    result.m_args = m_args + startIndex;
    result.m_argCount =  m_argCount - startIndex;
}
Пример #6
0
JSValue callGetter(ExecState* exec, JSValue base, JSValue getterSetter)
{
    // FIXME: Some callers may invoke get() without checking for an exception first.
    // We work around that by checking here.
    if (exec->hadException())
        return exec->exception()->value();

    JSObject* getter = jsCast<GetterSetter*>(getterSetter)->getter();

    CallData callData;
    CallType callType = getter->methodTable(exec->vm())->getCallData(getter, callData);
    return call(exec, getter, callType, callData, base, ArgList());
}
Пример #7
0
EncodedJSValue DFG_OPERATION operationCallGetter(ExecState* exec, JSCell* base, JSCell* value)
{
    JSGlobalData* globalData = &exec->globalData();
    NativeCallFrameTracer tracer(globalData, exec);
    
    GetterSetter* getterSetter = asGetterSetter(value);
    JSObject* getter = getterSetter->getter();
    if (!getter)
        return JSValue::encode(jsUndefined());
    CallData callData;
    CallType callType = getter->methodTable()->getCallData(getter, callData);
    return JSValue::encode(call(exec, getter, callType, callData, asObject(base), ArgList()));
}
Пример #8
0
int main(int argc, char** argv)
{
  
  CommandlineUtils ArgList(argc, argv);

  // Get input image names
  int InputImPairSize = 0;
  char** InputImName = ArgList.GetArgsByOption("-i", InputImPairSize);
  
  // Get output image names
  int OutputImPairSize = 0;
  char** OutputImName = ArgList.GetArgsByOption("-o", OutputImPairSize);

  // Get calibration file name
  int CalibSize = 0;
  char** CalibFile = ArgList.GetArgsByOption("-c", CalibSize);

  // Get input image size
  // int SizeDim = 0;
  // char** ImSize = ArgList.GetArgsByOption("-s", SizeDim);
  
  // int ImWidth  = atoi(ImSize[0]);
  // int ImHeight = atoi(ImSize[1]);
  
  char* lInput  = InputImName[0];
  char* rInput  = InputImName[1];
  char* lOutput = OutputImName[0];
  char* rOutput = OutputImName[1];

 
  if( lInput==NULL || rInput==NULL )
    {
      std::cerr << "Empty input images!" << std::endl;
      return 0;
    }
  
  if( lOutput==NULL || rOutput==NULL )
    {   
      std::cerr << "Empty output images!" << std::endl;
      return 0;
    }

  StereoVision sv;

  sv.calibrationLoad(CalibFile[0]);

  sv.undistortImage(lInput, rInput, lOutput, rOutput);
  
  return 0;
}
Пример #9
0
bool add_running_arguments(string& cmd, Widget origin)
{
    if (cmd == "run")
	cmd = gdb->rerun_command();

    if (gdb->type() != JDB)
	return true;		// Ok, perform the command

    if (!is_run_cmd(cmd))
	return true;		// Ok, perform the command

    strip_leading_space(cmd);
    string args = cmd.after(rxwhite);

    ProgramInfo info;

    if (args.empty() && gdb->has_debug_command())
    {
	// JDB 1.1 requires at least a class name after the `run' command.
	cmd += " " + info.file;
    }

    if (info.running && !gdb->has_debug_command())
    {
	// JDB 1.2 cannot rerun a program after it has been started.
	// Offer to restart JDB instead.
	static Widget restart_jdb = 0;
	static string saved_run_command;

	if (restart_jdb == 0)
	{
	    restart_jdb = 
		verify(XmCreateQuestionDialog(find_shell(origin),
				 XMST("confirm_restart_gdb_dialog"), 
				 ArgList(0), 0));
	    Delay::register_shell(restart_jdb);
	    XtAddCallback(restart_jdb, XmNhelpCallback,   
			  ImmediateHelpCB, XtPointer(0));
	    XtAddCallback(restart_jdb, XmNokCallback,     
			  RestartAndRunCB, (XtPointer)&saved_run_command);
	}

	saved_run_command = cmd;
	XtManageChild(restart_jdb);

	return false;		// Don't perform the command yet
    }

    return true;
}
Пример #10
0
// Analysis_Hist::Setup()
Analysis::RetType Analysis_Hist::ExternalSetup(DataSet_1D* dsIn, std::string const& histname,
                                       int setidx, std::string const& outfilenameIn,
                                       bool minArgSetIn, double minIn,
                                       bool maxArgSetIn, double maxIn,
                                       double stepIn, int binsIn, double tempIn,
                                       NormMode normIn,
                                       DataSetList& datasetlist, DataFileList& DFLin)
{
  debug_ = 0;
  if (dsIn == 0) return Analysis::ERR;
  outfilename_ = outfilenameIn;
  outfile_ = DFLin.AddDataFile(outfilename_);
  Temp_ = tempIn; 
  if (Temp_ != -1.0)
    calcFreeE_ = true;
  else
    calcFreeE_ = false;
  gnuplot_ = false;
  normalize_ = normIn;
  circular_ = false;
  nativeOut_ = false;
  minArgSet_ = minArgSetIn;
  if (minArgSet_)
    default_min_ = minIn;
  maxArgSet_ = maxArgSetIn;
  if (maxArgSet_)
    default_max_ = maxIn;
  default_step_ = stepIn;
  default_bins_ = binsIn;
  calcAMD_ = false;
  amddata_ = 0;

  dimensionArgs_.push_back( ArgList(dsIn->Meta().Legend()) ); // Needed for dim label
  histdata_.push_back( dsIn );
  N_dimensions_ = 1;
  std::string setname = histname;
  std::string htype;
  if (calcFreeE_)
    htype = "FreeE_";
  else
    htype = "Hist_";
  if (setname.empty())
    setname = datasetlist.GenerateDefaultName(htype + dsIn->Meta().Name());
  hist_ = datasetlist.AddSet( DataSet::DOUBLE, MetaData(setname, dsIn->Meta().Aspect(), setidx) );
  if (hist_ == 0) return Analysis::ERR;
  hist_->SetLegend(htype + dsIn->Meta().Legend());
  if (outfile_ != 0) outfile_->AddDataSet( hist_ );
  return Analysis::OK;
}
Пример #11
0
int main(int argc, char *argv[])
{
    auto index = clang_createIndex(0, 0);
    std::vector<std::string> default_args = { {"-x"}, {"c++"}, {"-std=c++11"} };
    std::string filename;
    ArgList arglist( default_args );

    if ( argc > 1 ) {
	arglist = ArgList( argc - 2, argv + 1 );
	filename = argv[argc - 1];
    } else {
	filename = argv[1];
    }
      
    TUnit tu( index, filename );
  
    if ( !tu.parse( arglist.count(), arglist ) ) {
	std::cout << "Translation Unit Initial Parse Failed!\n";
    }

    std::string input;
    std::vector<char> filebuffer;
    while( std::getline( std::cin, input ) ) {
	if ( input == "REPARSE" ) {
	    filebuffer = ReparseSource();

	    CXUnsavedFile unsaved_file = { filename.c_str(),
					   filebuffer.data(),
					   filebuffer.size() };

	    // std::cout << "Size = " << filebuffer.size()
	    // 		<< "Contents:\n" << filebuffer.data()
	    // 		<< "\n";

	    if ( tu.parse( std::vector<CXUnsavedFile>( 1, unsaved_file ) ) ) {
		TokenizeSource( tu.handle() );
	    } else {
		std::cout << "Reparse FAILED!\n" << end_pattern << "\n";
	    }
	}
    }

    clang_disposeIndex( index );
    return 0;
}
Пример #12
0
static MString get_tip_of_the_day(Widget w, int n)
{
    struct tip_of_the_day_resource_values {
	XmString tip;
    };

    const string tip_name = "tip" + itostring(n);

    XtResource r;
    r.resource_name   = XTRESSTR(tip_name.chars());
    r.resource_class  = XTRESSTR("Tip");
    r.resource_type   = XmRXmString;
    r.resource_size   = sizeof(XmString);
    r.resource_offset = XtOffsetOf(tip_of_the_day_resource_values, tip);
    r.default_type    = XtRImmediate;
    r.default_addr    = XtPointer(0);

    tip_of_the_day_resource_values values;
    XtGetApplicationResources(w, &values, &r, 1, ArgList(0), 0);

    return MString(values.tip, true);
}
Пример #13
0
unsigned UserDefinedCodeViewTypesBuilder::GetMemberFunctionTypeIndex(const MemberFunctionTypeDescriptor& MemberDescriptor,
    uint32_t const *const ArgumentTypes)
{
    std::vector<TypeIndex> argumentTypes;
    argumentTypes.reserve(MemberDescriptor.NumberOfArguments);
    for (uint16_t iArgument = 0; iArgument < MemberDescriptor.NumberOfArguments; iArgument++)
    {
        argumentTypes.emplace_back(ArgumentTypes[iArgument]);
    }

    ArgListRecord ArgList(TypeRecordKind::ArgList, argumentTypes);
    TypeIndex ArgumentList = TypeTable.writeKnownType(ArgList);

    MemberFunctionRecord MemberFunction(TypeIndex(MemberDescriptor.ReturnType), 
                                        TypeIndex(MemberDescriptor.ContainingClass), 
                                        TypeIndex(MemberDescriptor.TypeIndexOfThisPointer), 
                                        CallingConvention(MemberDescriptor.CallingConvention), 
                                        FunctionOptions::None, MemberDescriptor.NumberOfArguments, 
                                        ArgumentList, 
                                        MemberDescriptor.ThisAdjust);

    TypeIndex MemberFunctionIndex = TypeTable.writeKnownType(MemberFunction);
    return MemberFunctionIndex.getIndex();
}
Пример #14
0
int main(int argc, char** argv)
{
  enum LEFT_RIGHT { LEFT=0, RIGHT=1 };
  
  CommandlineUtils ArgList(argc, argv);

  // Get left image set
  int ImSetSizeL = 0;
  char** ImNameL = ArgList.GetArgsByOption("-l", ImSetSizeL);
  
  // Get right image set
  int ImSetSizeR = 0;
  char** ImNameR = ArgList.GetArgsByOption("-r", ImSetSizeR);

  // Get square size
  int size_len;
  char** squareSizeStr = ArgList.GetArgsByOption("-d", size_len);
  float squareSize = atof(squareSizeStr[0]);
  

  // Get output name
  int NameSize;
  char** OutputName = ArgList.GetArgsByOption("-o", NameSize);

  if(ImNameL == NULL)
    {
      std::cerr << "Empty left image set!" << std::endl;
      return 0;
    }
  
  if(ImNameR == NULL)
    {   
      std::cerr << "Empty right image set!" << std::endl;
      return 0;
    }
  
  if(ImSetSizeL != ImSetSizeR)
    {
      std::cerr << "Unmatched number of images in left and right set" << std::endl; 
      return 0;
    }

  // int NumOfIm = ImSetSizeL;

  // Get board size
  int BoardDimension = 0;
  char** BoardSize = ArgList.GetArgsByOption("-s", BoardDimension);
  
  if(BoardDimension != 2)
    {
      std::cerr << "Only two dimensional checkerboard is supported!" << std::endl;
      return 0;
    }

  int CornersX = atoi(BoardSize[0]);
  int CornersY = atoi(BoardSize[1]);
  
  // Load images 
  IplImage** ImSetL = LoadImages(ImNameL, ImSetSizeL);
  IplImage** ImSetR = LoadImages(ImNameR, ImSetSizeR);
  
  int ImWidth  = ImSetL[0]->width;
  int ImHeight = ImSetL[1]->height;

  StereoVision sv;

  // Initialize calibration
  sv.calibrationInit(ImWidth, ImHeight, CornersX, CornersY);
  
  // Calibrate left image set
  sv.monoCalibrate(ImSetSizeL, ImSetL, LEFT);
  sv.monoCalibrate(ImSetSizeR, ImSetR, RIGHT);

  // Calibrate stereo pair
  sv.stereoCalibrate(squareSize, ImSetSizeL, ImSetL, ImSetR);

  // Output calibration result
  sv.calibrationSave(OutputName[0]);
 
  // Release images
  ReleaseImages(ImSetL, ImSetSizeL);
  ReleaseImages(ImSetR, ImSetSizeR);

  
  return 0;
}
Пример #15
0
/** Replace all variables in given ArgList with their values. */
ArgList VariableArray::ReplaceVariables(ArgList const& argIn, DataSetList const& DSL, int debug)
{
  if (debug > 0) mprintf("DEBUG: Before variable replacement:  [%s]\n", argIn.ArgLine());
  ArgList modCmd = argIn;
  for (int n = 0; n < modCmd.Nargs(); n++) {
    size_t pos = modCmd[n].find("$");
    while (pos != std::string::npos) {
      // Argument is/contains a variable. Find first non-alphanumeric char
      size_t len = 1;
      for (size_t pos1 = pos+1; pos1 < modCmd[n].size(); pos1++, len++)
        if (!isalnum(modCmd[n][pos1])) break;
      std::string var_in_arg = modCmd[n].substr(pos, len);
      // See if variable occurs in CurrentVars_
      Varray::const_iterator vp = CurrentVars_.begin();
      for (; vp != CurrentVars_.end(); ++vp)
        if (vp->first == var_in_arg) break;
      // If found replace with value from CurrentVars_
      if (vp != CurrentVars_.end()) {
        if (debug > 0)
          mprintf("DEBUG: Replaced variable '%s' with value '%s'\n",
                  var_in_arg.c_str(), vp->second.c_str());
        std::string arg = modCmd[n];
        arg.replace(pos, vp->first.size(), vp->second);
        modCmd.ChangeArg(n, arg);
      } else {
        // Not found in CurrentVars_; see if this is a DataSet.
        for (size_t pos1 = pos+len; pos1 < modCmd[n].size(); pos1++, len++)
          if (!isalnum(modCmd[n][pos1]) &&
              modCmd[n][pos1] != '[' &&
              modCmd[n][pos1] != ':' &&
              modCmd[n][pos1] != ']' &&
              modCmd[n][pos1] != '_' &&
              modCmd[n][pos1] != '-' &&
              modCmd[n][pos1] != '%')
            break;
        var_in_arg = modCmd[n].substr(pos+1, len-1);
        DataSet* ds = DSL.GetDataSet( var_in_arg );
        if (ds == 0) {
          mprinterr("Error: Unrecognized variable in command: %s\n", var_in_arg.c_str());
          return ArgList();
        } else {
          if (ds->Type() != DataSet::STRING && ds->Group() != DataSet::SCALAR_1D) {
            mprinterr("Error: Only 1D data sets supported.\n");
            return ArgList();
          }
          if (ds->Size() < 1) {
            mprinterr("Error: Set is empty.\n");
            return ArgList();
          }
          if (ds->Size() > 1)
            mprintf("Warning: Only using first value.\n");
          std::string value;
          if (ds->Type() == DataSet::STRING)
            value = (*((DataSet_string*)ds))[0];
          else
            value = doubleToString(((DataSet_1D*)ds)->Dval(0));
          if (debug > 0)
            mprintf("DEBUG: Replaced variable '$%s' with value '%s' from DataSet '%s'\n",
                    var_in_arg.c_str(), value.c_str(), ds->legend());
          std::string arg = modCmd[n];
          arg.replace(pos, var_in_arg.size()+1, value);
          modCmd.ChangeArg(n, arg);
        }
      }
      pos = modCmd[n].find("$");
    } // END loop over this argument
  }
  return modCmd;
}
Пример #16
0
// Action_DihedralScan::Init()
Action::RetType Action_DihedralScan::Init(ArgList& actionArgs, ActionInit& init, int debugIn)
{
  if (init.DSL().EnsembleNum() > -1) {
    mprinterr("Error: DIHEDRALSCAN currently cannot be used in ensemble mode.\n");
    return Action::ERR;
  }
  TrajectoryFile::TrajFormatType outfmt = TrajectoryFile::UNKNOWN_TRAJ;
  Topology* outtop = 0;
  int iseed = -1;

  debug_ = debugIn;
  // Get Keywords - first determine mode
  if (actionArgs.hasKey("random"))
    mode_ = RANDOM;
  else if (actionArgs.hasKey("interval"))
    mode_ = INTERVAL;
  else
    mode_ = INTERVAL;
  // Get residue range
  resRange_.SetRange(actionArgs.GetStringKey("resrange"));
  if (!resRange_.Empty())
    resRange_.ShiftBy(-1); // User res args start from 1
  // Determine which angles to search for
  dihSearch_.SearchForArgs(actionArgs);
  // If nothing is enabled, enable all 
  dihSearch_.SearchForAll();
  // For interval, get value to shift by, set max rotations and set up 
  // output trajectory.
  if ( mode_ == INTERVAL ) { 
    interval_ = actionArgs.getNextDouble(60.0);
    maxVal_ = (int) (360.0 / interval_);
    if (maxVal_ < 0) maxVal_ = -maxVal_;
    outfilename_ = actionArgs.GetStringKey("outtraj");
    if (!outfilename_.empty()) {
      outfmt = TrajectoryFile::GetFormatFromArg( actionArgs );
      outtop = init.DSL().GetTopology( actionArgs );
      if (outtop == 0) {
        mprinterr("Error: dihedralscan: No topology for output traj.\n");
        return Action::ERR;
      }
    }
  }
  // Get 'random' args
  if (mode_ == RANDOM) {
    check_for_clashes_ = actionArgs.hasKey("check");
    checkAllResidues_ = actionArgs.hasKey("checkallresidues");
    cutoff_ = actionArgs.getKeyDouble("cutoff",0.8);
    rescutoff_ = actionArgs.getKeyDouble("rescutoff",10.0);
    backtrack_ = actionArgs.getKeyInt("backtrack",4);
    increment_ = actionArgs.getKeyInt("increment",1);
    max_factor_ = actionArgs.getKeyInt("maxfactor",2);
    // Check validity of args
    if (cutoff_ < Constants::SMALL) {
      mprinterr("Error: cutoff too small.\n");
      return Action::ERR;
    }
    if (rescutoff_ < Constants::SMALL) {
      mprinterr("Error: rescutoff too small.\n");
      return Action::ERR;
    }
    if (backtrack_ < 0) {
      mprinterr("Error: backtrack value must be >= 0\n");
      return Action::ERR;
    }
    if ( increment_<1 || (360 % increment_)!=0 ) {
      mprinterr("Error: increment must be a factor of 360.\n");
      return Action::ERR;
    }
    // Calculate max increment
    max_increment_ = 360 / increment_;
    // Seed random number gen
    iseed = actionArgs.getKeyInt("rseed",-1);
    RN_.rn_set( iseed );
  }
  // Output file for # of problems
  DataFile* problemFile = init.DFL().AddDataFile(actionArgs.GetStringKey("out"), actionArgs);
  // Dataset to store number of problems
  number_of_problems_ = init.DSL().AddSet(DataSet::INTEGER, actionArgs.GetStringNext(),"Nprob");
  if (number_of_problems_==0) return Action::ERR;
  // Add dataset to data file list
  if (problemFile != 0) problemFile->AddDataSet(number_of_problems_);

  mprintf("    DIHEDRALSCAN: Dihedrals in");
  if (resRange_.Empty())
    mprintf(" all solute residues.\n");
  else
    mprintf(" residue range [%s]\n", resRange_.RangeArg());
  switch (mode_) {
    case RANDOM:
      mprintf("\tDihedrals will be rotated to random values.\n");
      if (iseed==-1)
        mprintf("\tRandom number generator will be seeded using time.\n");
      else
        mprintf("\tRandom number generator will be seeded using %i\n",iseed);
      if (check_for_clashes_) {
        mprintf("\tWill attempt to recover from bad steric clashes.\n");
        if (checkAllResidues_)
          mprintf("\tAll residues will be checked.\n");
        else
          mprintf("\tResidues up to the currenly rotating dihedral will be checked.\n");
        mprintf("\tAtom cutoff %.2f, residue cutoff %.2f, backtrack = %i\n",
                cutoff_, rescutoff_, backtrack_);
        mprintf("\tWhen clashes occur dihedral will be incremented by %i\n",increment_);
        mprintf("\tMax # attempted rotations = %i times number dihedrals.\n",
                max_factor_);
      }
      break;
    case INTERVAL:
      mprintf("\tDihedrals will be rotated at intervals of %.2f degrees.\n",
              interval_);
      if (!outfilename_.empty())
        mprintf("\tCoordinates output to %s, format %s\n",outfilename_.c_str(), 
                TrajectoryFile::FormatString(outfmt));
      break;
  }
  // Setup output trajectory
  if (!outfilename_.empty()) {
    if (outtraj_.InitTrajWrite(outfilename_, ArgList(), outfmt)) return Action::ERR;
    outframe_ = 0;
  } 
  // Square cutoffs to compare to dist^2 instead of dist
  cutoff_ *= cutoff_;
  rescutoff_ *= rescutoff_;
  // Increment backtrack by 1 since we need to skip over current res
  ++backtrack_;
  // Initialize CheckStructure
  if (checkStructure_.SeparateInit( false, "*", "", "", 0.8, 1.15, false, init.DFL() )) {
    mprinterr("Error: Could not set up structure check for DIHEDRALSCAN.\n");
    return Action::ERR;
  }
  return Action::OK;
}
Пример #17
0
Файл: vsl.C Проект: sampost/ddd
// Main VSL program
int main(int argc, char *argv[])
{
    // Set flags
    {
        // SGI CC wants this:
        const char** tmp_argv = (const char**)argv;
        VSEFlags::parse(argc, tmp_argv, "vsllib");
        argv = (char **)tmp_argv;
    }

    // Init toolkit
    Widget toplevel = XtAppInitialize(&app_con, "Vsl",
                                      (XrmOptionDescRec *)0, ZERO,
                                      &argc, argv, (char**)fallback_resources,
                                      ArgList(0), ZERO);

    // Create Viewport
    Arg arglist[10];        // Arguments
    int a = 0;              // Argument counter
    XtSetArg(arglist[a], ARGSTR(XtNallowHoriz), true);
    a++;
    XtSetArg(arglist[a], ARGSTR(XtNallowVert),  true);
    a++;
    Widget viewport = XtCreateManagedWidget("viewport", viewportWidgetClass,
                                            toplevel, arglist, a);

    // Create DocSpace
    a = 0;
    Widget docSpace = XtCreateManagedWidget("docSpace", docSpaceWidgetClass,
                                            viewport, arglist, a);
    XtAddCallback(docSpace, XtNcallback, SelectCB, 0);
    XtAddCallback(docSpace, XtNexposeCallback, ExposeCB, 0);
    XtAddCallback(docSpace, XtNquitCallback, QuitCB, 0);

    // Set font table
    StringBox::fontTable = new FontTable(XtDisplay(toplevel));

    // Fetch name
    string library_file = VSEFlags::library_file;
    if (argc > 1)
    {
        library_file = argv[1];
        if (library_file[0] == '-')
        {
            std::cout << argv[0] << ": usage: " << argv[0] << " [options] "
                      << "VSLLIB [THEMES...]\n\n" << VSEFlags::explain();

            exit(EXIT_FAILURE);
        }
    }

    // Create pic in THEBOX
    {
        // Read library
        long starttime = clock();
        ThemedVSLLib lib(library_file, VSEFlags::optimize_mode());
        long endtime = clock();

        assert(lib.OK());

        if (VSEFlags::show_optimizing_time)
            std::cout << "\nRead & optimizing time: "
                      << (endtime - starttime) / 1000 << " ms\n";

        // Build themes
        StringArray themes;
        for (int i = 2; i < argc; i++)
            themes += argv[i];
        lib.set_theme_list(themes);
        assert(lib.OK());

        if (VSEFlags::assert_library_ok)
            assert(lib.OK());

        if (VSEFlags::dump_library)
            std::cout << lib;

        if (VSEFlags::dump_tree)
            lib.dumpTree(std::cout);

        if (VSEFlags::suppress_eval)
            return EXIT_SUCCESS;

        // Fetch last function def (typically "main")
        VSLDef *def = lib.lastdef();

        if (def == 0)
        {
            std::cerr << argv[0] << ": cannot find last definition (sorry)\n";
            return EXIT_FAILURE;
        }

        // Eval function
        ListBox *arg = vsl_args(argc, argv);

        starttime = clock();
        for (int loop = 1; loop < VSEFlags::loops; loop++)
        {
            Box *result = (Box *)def->eval(arg);
            lib.output(result);
            result->unlink();
        }
        Box *result = (Box *)def->eval(arg);
        lib.output(result);
        endtime = clock();
        arg->unlink();

        // Show eval time
        if (VSEFlags::show_eval_time)
            std::cout << "\nEvaluation time: "
                      << (endtime - starttime) / 1000 << " ms\n";

        if (result && VSEFlags::dump_picture)
            std::cout << "#!" << argv[0] << "\n#include <std.vsl>\n\nmain() -> "
                      << *result << ";\n";

        thebox = result;

        // Stack and library are destroyed upon leaving this block
    }

    if (thebox && !thebox->size().isValid())
    {
        std::cerr << argv[0] << ": result has no size (maybe list?)\n";
        thebox->unlink();
        thebox = 0;
    }

    if (thebox == 0)
    {
        std::cerr << argv[0] << ": evaluation failed (sorry)\n";
        return EXIT_FAILURE;
    }

    // Realize Widget
    XtRealizeWidget(toplevel);

    // Process events
    XtAppMainLoop(app_con);

    // Never reached...
    return EXIT_SUCCESS;
}
Пример #18
0
// Exec_PermuteDihedrals::RandomizeAngles()
void Exec_PermuteDihedrals::RandomizeAngles(Frame& currentFrame, Topology const& topIn) {
  Matrix_3x3 rotationMatrix;
# ifdef DEBUG_PERMUTEDIHEDRALS
  // DEBUG
  int debugframenum=0;
  Trajout_Single DebugTraj;
  DebugTraj.PrepareTrajWrite("debugtraj.nc",ArgList(),(Topology*)&topIn,
                             CoordinateInfo(), BB_dihedrals_.size()*max_factor_,
                             TrajectoryFile::AMBERNETCDF);
  DebugTraj.WriteSingle(debugframenum++,currentFrame);
# endif
  int next_resnum;
  int bestLoop = 0;
  int number_of_rotations = 0;
  // Set max number of rotations to try.
  int max_rotations = (int)BB_dihedrals_.size();
  max_rotations *= max_factor_;

  // Loop over all dihedrals
  std::vector<PermuteDihedralsType>::const_iterator next_dih = BB_dihedrals_.begin();
  next_dih++;
  for (std::vector<PermuteDihedralsType>::const_iterator dih = BB_dihedrals_.begin();
                                                     dih != BB_dihedrals_.end(); 
                                                     ++dih, ++next_dih)
  {
    ++number_of_rotations;
    // Get the residue atom of the next dihedral. Residues up to and
    // including this residue will be checked for bad clashes 
    if (next_dih != BB_dihedrals_.end()) 
      next_resnum = next_dih->resnum;
    else
      next_resnum = dih->resnum - 1;
    // Set axis of rotation
    Vec3 axisOfRotation = currentFrame.SetAxisOfRotation(dih->atom1, dih->atom2);
    // Generate random value to rotate by in radians
    // Guaranteed to rotate by at least 1 degree.
    // NOTE: could potentially rotate 360 - prevent?
    // FIXME: Just use 2PI and rn_gen, get everything in radians
    double theta_in_degrees = ((int)(RN_.rn_gen()*100000) % 360) + 1;
    double theta_in_radians = theta_in_degrees * Constants::DEGRAD;
    // Calculate rotation matrix for random theta
    rotationMatrix.CalcRotationMatrix(axisOfRotation, theta_in_radians);
    int loop_count = 0;
    double clash = 0;
    double bestClash = 0;
    if (debug_>0) mprintf("DEBUG: Rotating dihedral %zu res %8i:\n", dih - BB_dihedrals_.begin(),
                          dih->resnum+1);
    bool rotate_dihedral = true;
    while (rotate_dihedral) {
      if (debug_>0) {
        mprintf("\t%8i %12s %12s, +%.2lf degrees (%i).\n",dih->resnum+1,
                topIn.AtomMaskName(dih->atom1).c_str(),
                topIn.AtomMaskName(dih->atom2).c_str(),
                theta_in_degrees,loop_count);
      }
      // Rotate around axis
      currentFrame.Rotate(rotationMatrix, dih->Rmask);
#     ifdef DEBUG_PERMUTEDIHEDRALS
      // DEBUG
      DebugTraj.WriteSingle(debugframenum++,currentFrame);
#     endif
      // If we dont care about sterics exit here
      if (!check_for_clashes_) break;
      // Check resulting structure for issues
      int checkresidue;
      if (!checkAllResidues_)
        checkresidue = CheckResidue(currentFrame, topIn, *dih, next_resnum, clash);
      else
        checkresidue = CheckResidue(currentFrame, topIn, *dih, topIn.Nres(), clash);
      if (checkresidue==0)
        rotate_dihedral = false;
      else if (checkresidue==-1) {
        if (dih - BB_dihedrals_.begin() < 2) {
          mprinterr("Error: Cannot backtrack; initial structure already has clashes.\n");
          number_of_rotations = max_rotations + 1;
        } else {
          dih--; //  0
          dih--; // -1
          next_dih = dih;
          next_dih++;
          if (debug_>0)
            mprintf("\tCannot resolve clash with further rotations, trying previous again.\n");
        }
        break;
      }
      if (clash > bestClash) {bestClash = clash; bestLoop = loop_count;}
      //n_problems = CheckResidues( currentFrame, second_atom );
      //if (n_problems > -1) {
      //  mprintf("%i\tCheckResidues: %i problems.\n",frameNum,n_problems);
      //  rotate_dihedral = false;
      //} else if (loop_count==0) {
      if (loop_count==0 && rotate_dihedral) {
        if (debug_>0)
          mprintf("\tTrying dihedral increments of +%i\n",increment_);
        // Instead of a new random dihedral, try increments
        theta_in_degrees = (double)increment_;
        theta_in_radians = theta_in_degrees * Constants::DEGRAD;
        // Calculate rotation matrix for new theta
        rotationMatrix.CalcRotationMatrix(axisOfRotation, theta_in_radians);
      }
      ++loop_count;
      if (loop_count == max_increment_) {
        if (debug_>0)
          mprintf("%i iterations! Best clash= %.3lf at %i\n",max_increment_,
                  sqrt(bestClash),bestLoop);
        if (dih - BB_dihedrals_.begin() < backtrack_) {
          mprinterr("Error: Cannot backtrack; initial structure already has clashes.\n");
          number_of_rotations = max_rotations + 1;
        } else { 
          for (int bt = 0; bt < backtrack_; bt++)
            dih--;
          next_dih = dih;
          next_dih++;
          if (debug_>0)
            mprintf("\tCannot resolve clash with further rotations, trying previous %i again.\n",
                    backtrack_ - 1);
        }
        break;
        // Calculate how much to rotate back in order to get to best clash
        /*int num_back = bestLoop - 359;
        theta_in_degrees = (double) num_back;
        theta_in_radians = theta_in_degrees * Constants::DEGRAD;
        // Calculate rotation matrix for theta
        calcRotationMatrix(rotationMatrix, axisOfRotation, theta_in_radians);
        // Rotate back to best clash
        frm.Frm().RotateAroundAxis(rotationMatrix, theta_in_radians, dih->Rmask);
        // DEBUG
        DebugTraj.WriteFrame(debugframenum++,currentParm,*currentFrame);
        // Sanity check
        CheckResidue(currentFrame, *dih, second_atom, &clash);
        rotate_dihedral=false;*/
        //DebugTraj.EndTraj();
        //return 1;
      }
    } // End dihedral rotation loop
    // Safety valve - number of defined dihedrals times * maxfactor
    if (number_of_rotations > max_rotations) {
      mprinterr("Error: # of rotations (%i) exceeds max rotations (%i), exiting.\n",
                number_of_rotations, max_rotations);
//#     ifdef DEBUG_PERMUTEDIHEDRALS
//      DebugTraj.EndTraj();
//#     endif
      // Return gracefully for now
      break;
      //return 1;
    }
  } // End loop over dihedrals
# ifdef DEBUG_PERMUTEDIHEDRALS
  DebugTraj.EndTraj();
  mprintf("\tNumber of rotations %i, expected %u\n",number_of_rotations,BB_dihedrals_.size());
# endif
}
Пример #19
0
void parser::SimpleSt()
{
	if (curlex->type==KeyWord&&curlex->lexnum==LexInt)
	{
		do
		{
			newlex();
			if (curlex->type==Variable)
			{
				PolizItem *tmpcur=curpolizelem;
				table.declvar(curlex->lexstr);
				PolizElem *temp=new PolizVarAddr(curlex->lexstr,0);
				addpolizelem(temp);
				newlex();
				if (!Array(true))
					if (!VarArg())
					{
						delete temp;
						curpolizelem=tmpcur;
						if (tmpcur)
							tmpcur->next=0;
						else
							poliz=0;
					}
			}
			else
				throw parserr("declaration of variable or array expected",curlex);
		} while (curlex->type==Divider&&curlex->lexnum==',');
	}
	else if (curlex->type==Variable)
	{
		PolizElem *temp=new PolizVarAddr(curlex->lexstr,0);
		addpolizelem(temp);
		newlex();
		Array(false);
		if (curlex->type==Operation&&curlex->lexnum=='=')
		{
			newlex();
			Exp1();
			temp=new PolizFunAssig;
			addpolizelem(temp);
		}
		else parserr("expected `='",curlex);
	}
	else if (curlex->type==KeyWord&&curlex->lexnum==LexGoto)
	{
		newlex();
		if (curlex->type==Label)
		{
			PolizElem *temp=new PolizLabel(curlex->lexstr);
			addpolizelem(temp);
			temp=new PolizOpGo;
			addpolizelem(temp);
			newlex();
		}
		else parserr("name of label expected",curlex);
	}
	else if (curlex->type==KeyWord&&curlex->lexnum==LexPrint)
	{
		PolizElem *temp=new PolizPrintEnd;
		addpolizelem(temp);
		newlex();
		ArgList();
		temp=new PolizPrint;
		addpolizelem(temp);
	}
	else if (curlex->type==KeyWord&&curlex->lexnum==LexSell)
	{
		newlex();
		Arg2();
		PolizElem *temp=new PolizSell;
		addpolizelem(temp);
	}
	else if (curlex->type==KeyWord&&curlex->lexnum==LexBuy)
	{
		newlex();
		Arg2();
		PolizElem *temp=new PolizBuy;
		addpolizelem(temp);
	}
	else if (curlex->type==KeyWord&&curlex->lexnum==LexProd)
	{
		newlex();
		Arg1();
		PolizElem *temp=new PolizProd;
		addpolizelem(temp);
	}
	else if (curlex->type==KeyWord&&curlex->lexnum==LexJoin)
	{
		newlex();
		Arg1();
		PolizElem *temp=new PolizJoin;
		addpolizelem(temp);
	}
	else if (curlex->type==KeyWord&&curlex->lexnum==LexBuild)
	{
		newlex();
		Arg0();
		PolizElem *temp=new PolizBuild;
		addpolizelem(temp);
	}
	else if (curlex->type==KeyWord&&curlex->lexnum==LexTurn)
	{
		newlex();
		Arg0();
		PolizElem *temp=new PolizTurn;
		addpolizelem(temp);
	}
	else throw parserr("expected operator",curlex);
}
Пример #20
0
/** Read command line args. */
Cpptraj::Mode Cpptraj::ProcessCmdLineArgs(int argc, char** argv) {
  bool hasInput = false;
  bool interactive = false;
  Sarray inputFiles;
  Sarray topFiles;
  Sarray trajinFiles;
  Sarray trajoutFiles;
  Sarray refFiles;
  for (int i = 1; i < argc; i++) {
    std::string arg(argv[i]);
    if ( arg == "--help" || arg == "-h" ) {
      // --help, -help: Print usage and exit
      SetWorldSilent(true);
      Usage();
      return QUIT;
    }
    if ( arg == "-V" || arg == "--version" ) {
      // -V, --version: Print version number and exit
      SetWorldSilent( true );
      loudPrintf("CPPTRAJ: Version %s\n", CPPTRAJ_VERSION_STRING);
      return QUIT;
    }
    if ( arg == "--internal-version" ) {
      // --internal-version: Print internal version number and quit.
      SetWorldSilent( true );
      loudPrintf("CPPTRAJ: Internal version # %s\n", CPPTRAJ_INTERNAL_VERSION);
      return QUIT;
    }
    if ( arg == "--defines" ) {
      // --defines: Print information on compiler defines used and exit
      SetWorldSilent( true );
      loudPrintf("Compiled with:");
      loudPrintf("%s\n", Cpptraj::Defines().c_str());
      return QUIT;
    }
    if (arg == "-tl") {
      // -tl: Trajectory length
      if (topFiles.empty()) {
        mprinterr("Error: No topology file specified.\n");
        return ERROR;
      }
      SetWorldSilent( true );
      if (State_.TrajLength( topFiles[0], trajinFiles )) return ERROR;
      return QUIT;
    }
    if ( arg == "--interactive" )
      interactive = true;
    else if ( arg == "-debug" && i+1 != argc) {
      // -debug: Set overall debug level
      ArgList dbgarg( argv[++i] );
      State_.SetListDebug( dbgarg );
    } else if ( arg == "--log" && i+1 != argc)
      // --log: Set up log file for interactive mode
      logfilename_ = argv[++i];
    else if ( arg == "-p" && i+1 != argc) {
      // -p: Topology file
      topFiles.push_back( argv[++i] );
    } else if ( arg == "-y" && i+1 != argc) {
      // -y: Trajectory file in
      trajinFiles.push_back( argv[++i] );
    } else if ( arg == "-x" && i+1 != argc) {
      // -x: Trajectory file out
      trajoutFiles.push_back( argv[++i] );
    } else if ( arg == "-c" && i+1 != argc) {
      // -c: Reference file
      refFiles.push_back( argv[++i] );
    } else if (arg == "-i" && i+1 != argc) {
      // -i: Input file(s)
      inputFiles.push_back( argv[++i] );
    } else if (arg == "-ms" && i+1 != argc) {
      // -ms: Parse mask string, print selected atom #s
      if (ProcessMask( topFiles, refFiles, std::string(argv[++i]), false, false )) return ERROR;
      return QUIT;
    } else if (arg == "-mr" && i+1 != argc) {
      // -mr: Parse mask string, print selected res #s
      if (ProcessMask( topFiles, refFiles, std::string(argv[++i]), false, true )) return ERROR;
      return QUIT;
    } else if (arg == "--mask" && i+1 != argc) {
      // --mask: Parse mask string, print selected atom details
      if (ProcessMask( topFiles, refFiles, std::string(argv[++i]), true, false )) return ERROR;
      return QUIT;
    } else if (arg == "--resmask" && i+1 != argc) {
      // --resmask: Parse mask string, print selected residue details
      if (ProcessMask( topFiles, refFiles, std::string(argv[++i]), true, true )) return ERROR;
      return QUIT;
    } else if ( i == 1 ) {
      // For backwards compatibility with PTRAJ; Position 1 = TOP file
      topFiles.push_back( argv[i] );
    } else if ( i == 2 ) {
      // For backwards compatibility with PTRAJ; Position 2 = INPUT file
      inputFiles.push_back( argv[i] );
    } else {
      // Unrecognized
      mprintf("  Unrecognized input on command line: %i: %s\n", i,argv[i]);
      Usage();
      return ERROR;
    }
  }
  Cpptraj::Intro();
  // Add all topology files specified on command line.
  for (Sarray::const_iterator topFilename = topFiles.begin();
                              topFilename != topFiles.end();
                              ++topFilename)
    if (State_.AddTopology( *topFilename, ArgList() )) return ERROR;
  // Add all reference trajectories specified on command line.
  for (Sarray::const_iterator refName = refFiles.begin();
                              refName != refFiles.end();
                              ++refName)
    if (State_.AddReference( *refName )) return ERROR;
  // Add all input trajectories specified on command line.
  for (Sarray::const_iterator trajinName = trajinFiles.begin();
                              trajinName != trajinFiles.end();
                              ++trajinName)
    if (State_.AddTrajin( *trajinName )) return ERROR;
  // Add all output trajectories specified on command line.
  if (!trajoutFiles.empty()) {
    hasInput = true; // This allows direct traj conversion with no other input 
    for (Sarray::const_iterator trajoutName = trajoutFiles.begin();
                                trajoutName != trajoutFiles.end();
                                ++trajoutName)
      if (State_.AddOutputTrajectory( *trajoutName )) return ERROR;
  }
  // Process all input files specified on command line.
  if ( !inputFiles.empty() ) {
    hasInput = true;
    for (Sarray::const_iterator inputFilename = inputFiles.begin();
                                inputFilename != inputFiles.end();
                                ++inputFilename)
    {
      Command::RetType c_err = Command::ProcessInput( State_, *inputFilename );
      if (c_err == Command::C_ERR && State_.ExitOnError()) return ERROR;
      if (c_err == Command::C_QUIT) return QUIT;
    }
  }
  // Determine whether to enter interactive mode
  if (!hasInput || interactive) {
    // Test if input is really from a console
    if ( isatty(fileno(stdin)) )
      return INTERACTIVE;
    else {
      // "" means read from STDIN
      Command::RetType c_err = Command::ProcessInput( State_, "" ); 
      if (c_err == Command::C_ERR && State_.ExitOnError()) return ERROR;
      if (c_err == Command::C_QUIT) return QUIT;
    }
  }
  return BATCH;
}
Пример #21
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;
}
Пример #22
0
// Initialize
PlotArea::PlotArea(Widget w, const string& fontname)
    : area(w), dpy(XtDisplay(w)), win(XtWindow(w)),
      cx(0), cy(0), px(1), py(1), xscale(0.0), yscale(0.0),
      gc(0), font(0), vchar(0), jmode(0), line_type(0), width(0),
      type(LineSolid), pointsize(1), pending_plots(0), last_commands()
{
    plot_resource_values values;
    XtGetApplicationResources(area, &values,
			      plot_subresources, XtNumber(plot_subresources),
			      ArgList(0), 0);

    // Init font
    font = XLoadQueryFont(dpy, fontname.chars());
    if (font == 0)
	font = XLoadQueryFont(dpy, values.font);
    if (font == 0)
	font = XLoadQueryFont(dpy, "fixed");
    if (font == 0)
    {
	std::cerr << "Cannot load font\n";
	exit(1);
    }
    
    vchar = font->ascent + font->descent;

    // Init point size
    pointsize = values.pointsize;
    if (pointsize <= 0 || pointsize > 10) 
    {
	std::cerr << "Invalid point size " << pointsize << "\n";
	pointsize = 1;
    }

    // Init colors
    Pixel black = BlackPixelOfScreen(XtScreen(area));
    Pixel white = WhitePixelOfScreen(XtScreen(area));
    int depth;
    XtVaGetValues(area, XmNdepth, &depth, XtPointer(0));
    if (depth <= 1)
    {
	// Monochrome
	colors[0] = white;
	for (int i = 1; i < Ncolors; i++)
	    colors[i] = black;
    }
    else
    {
	// Multi-color or gray
	Visual *vis = DefaultVisualOfScreen(XtScreen(area));
	bool gray = (vis->c_class == StaticGray || vis->c_class == GrayScale);
	Colormap cmap;
	XtVaGetValues(area, XmNcolormap, &cmap, XtPointer(0));

	for (int i = 0; i < Ncolors; i++)
	{
	    string color = gray ? gray_values[i] : color_values[i];
	    XColor xcolor;
	    if (!XParseColor(dpy, cmap, color.chars(), &xcolor))
	    {
		std::cerr << "Unable to parse " << quote(color) 
		     << ".  Using black.\n";
		colors[i] = black;
	    }
	    else
	    {
		if (XAllocColor(dpy, cmap, &xcolor)) {
		    colors[i] = xcolor.pixel;
		}
		else
		{
		    std::cerr << "Cannot allocate " << quote(color)
			 << ".  Using black.\n";
		    colors[i] = black;
		}
	    }
	}
    }

    // Init dashes
    int i;
    for (i = 0; i < Ndashes; i++)
    { 
	string v;
	if (depth <= 1)
	    v = dash_mono[i];
	else
	    v = dash_color[i];

	if (v.length() == 0 || v[0] == '0')
	{
	    dashes[i][0] = (unsigned char)0;
	}
	else
	{
	    for (int j = 0; j < int(v.length()); j++)
		dashes[i][j] = (unsigned char) (v[j] - '0');
	}
	dashes[i][v.length()] = (unsigned char)0;
    }

    // Init widths
    widths[0] = 2;
    for (i = 1; i < Nwidths; i++)
	widths[i] = 0;
}
Пример #23
0
// Analysis_Hist::Analyze()
Analysis::RetType Analysis_Hist::Analyze() {
  // Set up dimensions
  // Size of histdata and dimensionArgs should be the same
  size_t total_bins = 0UL;
  for (unsigned int hd = 0; hd < N_dimensions_; hd++) {
    if ( setupDimension(dimensionArgs_[hd], *(histdata_[hd]), total_bins) ) 
      return Analysis::ERR;
  }
  // dimensionArgs no longer needed
  dimensionArgs_.clear();

  // Check that the number of data points in each dimension are equal
  std::vector<DataSet_1D*>::iterator ds = histdata_.begin();
  size_t Ndata = (*ds)->Size();
  ++ds;
  for (; ds != histdata_.end(); ++ds)
  {
    //mprintf("DEBUG: DS %s size %i\n",histdata[hd]->Name(),histdata[hd]->Xmax()+1);
    if (Ndata != (*ds)->Size()) {
      mprinterr("Error: Hist: Dataset %s has inconsistent # data points (%zu), expected %zu.\n",
                (*ds)->legend(), (*ds)->Size(), Ndata);
      return Analysis::ERR;
    }
  }
  mprintf("\tHist: %zu data points in each dimension.\n", Ndata);
  if (calcAMD_ && Ndata != amddata_->Size()) {
    mprinterr("Error: Hist: AMD data set size (%zu) does not match # expected data points (%zu).\n",
              amddata_->Size(), Ndata);
    return Analysis::ERR;
  }

  // Allocate bins
  mprintf("\tHist: Allocating histogram, total bins = %zu\n", total_bins);
  Bins_.resize( total_bins, 0.0 );

  // Bin data
  for (size_t n = 0; n < Ndata; n++) {
    long int index = 0;
    HdimType::const_iterator dim = dimensions_.begin();
    OffType::const_iterator bOff = binOffsets_.begin();
    for (std::vector<DataSet_1D*>::iterator ds = histdata_.begin();
                                            ds != histdata_.end(); ++ds, ++dim, ++bOff)
    {
      double dval = (*ds)->Dval( n );
      // Check if data is out of bounds for this dimension.
      if (dval > dim->Max() || dval < dim->Min()) {
        index = -1L;
        break;
      }
      // Calculate index for this particular dimension (idx)
      long int idx = (long int)((dval - dim->Min()) / dim->Step());
      if (debug_>1) mprintf(" [%s:%f (%li)],", dim->label(), dval, idx);
      // Calculate overall index in Bins, offset has already been calcd.
      index += (idx * (*bOff));
    }
    // If index was successfully calculated, populate bin
    if (index > -1L && index < (long int)Bins_.size()) {
      if (debug_ > 1) mprintf(" |index=%li",index);
      if (calcAMD_)
        Bins_[index] += exp( amddata_->Dval(n) );
      else
        Bins_[index]++;
    } else {
      mprintf("\tWarning: Frame %zu Coordinates out of bounds (%li)\n", n+1, index);
    }
    if (debug_>1) mprintf("}\n");
  }
  // Calc free energy if requested
  if (calcFreeE_) CalcFreeE();

  // Normalize if requested
  if (normalize_ != NO_NORM) Normalize();

  if (nativeOut_) {
    // Use Histogram built-in output
    PrintBins();
  } else {
    // Using DataFileList framework, set-up labels etc.
    if (N_dimensions_ == 1) {
      DataSet_double& dds = static_cast<DataSet_double&>( *hist_ );
      // Since Allocate1D only reserves data, use assignment op.
      dds = Bins_;
      hist_->SetDim(Dimension::X, dimensions_[0]);
    } else if (N_dimensions_ == 2) {
      DataSet_MatrixDbl& mds = static_cast<DataSet_MatrixDbl&>( *hist_ );
      mds.Allocate2D( dimensions_[0].Bins(), dimensions_[1].Bins() );
      std::copy( Bins_.begin(), Bins_.end(), mds.begin() );
      hist_->SetDim(Dimension::X, dimensions_[0]);
      hist_->SetDim(Dimension::Y, dimensions_[1]);
      outfile_->ProcessArgs("noxcol usemap nolabels");
    } else if (N_dimensions_ == 3) {
      DataSet_GridFlt& gds = static_cast<DataSet_GridFlt&>( *hist_ );
      //gds.Allocate3D( dimensions_[0].Bins(), dimensions_[1].Bins(), dimensions_[2].Bins() );
      gds.Allocate_N_O_D( dimensions_[0].Bins(), dimensions_[1].Bins(), dimensions_[2].Bins(),
                          Vec3(dimensions_[0].Min(), dimensions_[1].Min(), dimensions_[2].Min()),
                          Vec3(dimensions_[0].Step(), dimensions_[1].Step(), dimensions_[2].Step())
                        );
      //std::copy( Bins_.begin(), Bins_.end(), gds.begin() );
      // FIXME: Copy will not work since in grids data is ordered with Z
      // changing fastest. Should the ordering in grid be changed?
      size_t idx = 0;
      for (size_t z = 0; z < gds.NZ(); z++)
        for (size_t y = 0; y < gds.NY(); y++)
          for (size_t x = 0; x < gds.NX(); x++)
            gds.SetElement( x, y, z, (float)Bins_[idx++] );
      hist_->SetDim(Dimension::X, dimensions_[0]);
      hist_->SetDim(Dimension::Y, dimensions_[1]);
      hist_->SetDim(Dimension::Z, dimensions_[2]);
      outfile_->ProcessArgs("noxcol usemap nolabels");
      // Create pseudo-topology/trajectory
      if (!traj3dName_.empty()) {
        Topology pseudo;
        pseudo.AddTopAtom(Atom("H3D", 0), Residue("H3D", 1, ' ', ' '));
        pseudo.CommonSetup();
        if (!parmoutName_.empty()) {
          ParmFile pfile;
          if (pfile.WriteTopology( pseudo, parmoutName_, ParmFile::UNKNOWN_PARM, 0 ))
            mprinterr("Error: Could not write pseudo topology to '%s'\n", parmoutName_.c_str());
        }
        Trajout_Single out;
        if (out.PrepareTrajWrite(traj3dName_, ArgList(), &pseudo, CoordinateInfo(),
                                 Ndata, traj3dFmt_) == 0)
        {
          Frame outFrame(1);
          for (size_t i = 0; i < Ndata; ++i) {
            outFrame.ClearAtoms();
            outFrame.AddVec3( Vec3(histdata_[0]->Dval(i), 
                                   histdata_[1]->Dval(i), 
                                   histdata_[2]->Dval(i)) );
            out.WriteSingle(i, outFrame);
          }
          out.EndTraj();
        } else
          mprinterr("Error: Could not set up '%s' for write.\n", traj3dName_.c_str());
      }
    }
  }

  return Analysis::OK;
}
Пример #24
0
EncodedJSValue JSC_HOST_CALL dateUTC(ExecState* exec) 
{
    double ms = millisecondsFromComponents(exec, ArgList(exec), WTF::UTCTime);
    return JSValue::encode(jsNumber(timeClip(ms)));
}