コード例 #1
0
ファイル: outbox.cpp プロジェクト: BackupTheBerlios/toped-svn
void console::TELLFuncList::addFunc(wxString name, void* arguments)
{
   ArgList* arglist = static_cast<ArgList*>(arguments);
   wxListItem row;
   row.SetMask(wxLIST_MASK_DATA | wxLIST_MASK_TEXT);
   row.SetId(GetItemCount());
   row.SetData(GetItemCount());
   row.SetText((arglist->front()).c_str());arglist->pop_front();
   long inum = InsertItem(row);
   SetColumnWidth(0, wxLIST_AUTOSIZE);
   //
   row.SetColumn(1);
   row.SetMask(wxLIST_MASK_TEXT);
   row.SetText(name.c_str());
   SetItem(row);
   SetColumnWidth(1, wxLIST_AUTOSIZE);
   //
   std::string strlist("( ");
   while (!arglist->empty())
   {
      strlist += arglist->front();arglist->pop_front();
      if (arglist->size()) strlist += " , ";
   }
   strlist += " )";
   //
   row.SetColumn(2);
   row.SetMask(wxLIST_MASK_TEXT);
   row.SetText(strlist.c_str());
   SetItem(row);
   SetColumnWidth(2, wxLIST_AUTOSIZE);
}
コード例 #2
0
ファイル: outbox.cpp プロジェクト: BackupTheBerlios/toped-svn
void console::TELLFuncList::addFunc(wxString name, void* arguments)
{
   ArgList* arglist = static_cast<ArgList*>(arguments);
   wxListItem row;
   row.SetMask(wxLIST_MASK_DATA | wxLIST_MASK_TEXT);
   row.SetId(GetItemCount());
   row.SetData(GetItemCount());
   row.SetText( wxString((arglist->front()).c_str(), wxConvUTF8));arglist->pop_front();
   InsertItem(row);
   SetColumnWidth(0, wxLIST_AUTOSIZE);
   //
   row.SetColumn(1);
   row.SetMask(wxLIST_MASK_TEXT);
   row.SetText(name.c_str());
   SetItem(row);
   SetColumnWidth(1, wxLIST_AUTOSIZE);
   //
   wxString strlist(wxT("( "));
   while (!arglist->empty())
   {
      strlist << wxString(arglist->front().c_str(), wxConvUTF8);arglist->pop_front();
      if (arglist->size()) strlist << wxT(" , ");
   }
   delete arglist;
   strlist << wxT(" )");
   //
   row.SetColumn(2);
   row.SetMask(wxLIST_MASK_TEXT);
   row.SetText(strlist);
   SetItem(row);
   SetColumnWidth(2, wxLIST_AUTOSIZE);
}
コード例 #3
0
ファイル: command_line.cpp プロジェクト: ballmillsapest/KBase
void CommandLine::ParseFromArgv(const ArgList& argv)
{
    if (argv.empty()) {
        return;
    }

    // Anyway, we start from scratch.
    argv_ = Argv(1);
    last_not_param_ = argv_.begin();
    switches_.clear();

    SetProgram(FilePath(argv[0]));
    AddArguments(this, argv);
}
コード例 #4
0
ファイル: Exec_Analyze.cpp プロジェクト: Amber-MD/cpptraj
// Exec_Analyze::Execute()
Exec::RetType Exec_Analyze::Execute(CpptrajState& State, ArgList& argIn) {
  // Remove 'analyze'
  ArgList arg = argIn;
  arg.RemoveFirstArg();
  if (arg.empty()) {
    mprinterr("Error: No analysis command specified.\n");
    return CpptrajState::ERR;
  }
  mprintf("Warning: The 'analyze' prefix is no longer necessary and may be soon deprecated.\n");
  if (arg.CommandIs("matrix"))
    mprintf("Warning: NOTE: 'analyze matrix' is now 'diagmatrix'.\n");
  else
    mprintf("Warning: To add an analysis command the the queue, only the command name needs\n"
            "Warning: to be specified, e.g. '%s <args>'.\n", arg.Command());
  Cmd const& cmd = Command::SearchTokenType(DispatchObject::ANALYSIS, arg.Command());
  if (cmd.Empty()) {
    mprinterr("Error: Analysis command '%s' not found.\n", arg.Command());
    return CpptrajState::ERR;
  }
  return State.AddToAnalysisQueue( (Analysis*)cmd.Alloc(), arg );
}
コード例 #5
0
// Exec_RotateDihedral::Execute()
Exec::RetType Exec_RotateDihedral::Execute(CpptrajState& State, ArgList& argIn) {
  // Get input COORDS set
  std::string setname = argIn.GetStringKey("crdset");
  if (setname.empty()) {
    mprinterr("Error: Specify COORDS dataset name with 'crdset'.\n");
    return CpptrajState::ERR;
  }
  DataSet_Coords* CRD = (DataSet_Coords*)State.DSL().FindCoordsSet( setname );
  if (CRD == 0) {
    mprinterr("Error: Could not find COORDS set '%s'\n", setname.c_str());
    return CpptrajState::ERR;
  }
  if (CRD->Size() < 1) {
    mprinterr("Error: COORDS set is empty.\n");
    return CpptrajState::ERR;
  }
  int frame = argIn.getKeyInt("frame", 0);
  if (frame < 0 || frame >= (int)CRD->Size()) {
    mprinterr("Error: Specified frame %i is out of range.\n", frame+1);
    return CpptrajState::ERR;
  }
  mprintf("    ROTATEDIHEDRAL: Using COORDS '%s', frame %i\n", CRD->legend(), frame+1);
  // Get target frame
  Frame FRM = CRD->AllocateFrame();
  CRD->GetFrame(frame, FRM);
  // Save as reference
  Frame refFrame = FRM;

  // Create output COORDS set if necessary
  DataSet_Coords* OUT = 0;
  int outframe = 0;
  std::string outname = argIn.GetStringKey("name");
  if (outname.empty()) {
    // This will not work for TRAJ data sets
    if (CRD->Type() == DataSet::TRAJ) {
      mprinterr("Error: Using TRAJ as input set requires use of 'name' keyword for output.\n");
      return CpptrajState::ERR;
    }
    OUT = CRD;
    outframe = frame;
  } else {
    // Create new output set with 1 empty frame.
    OUT = (DataSet_Coords*)State.DSL().AddSet( DataSet::COORDS, outname );
    if (OUT == 0) return CpptrajState::ERR;
    OUT->Allocate( DataSet::SizeArray(1, 1) );
    OUT->CoordsSetup( CRD->Top(), CRD->CoordsInfo() );
    OUT->AddFrame( CRD->AllocateFrame() );
    mprintf("\tOutput to set '%s'\n", OUT->legend());
  }

  // Determine whether we are setting or incrementing.
  enum ModeType { SET = 0, INCREMENT };
  ModeType mode = SET;
  if (argIn.Contains("value"))
    mode = SET;
  else if (argIn.Contains("increment"))
    mode = INCREMENT;
  else {
    mprinterr("Error: Specify 'value <value>' or 'increment <increment>'\n");
    return CpptrajState::ERR;
  }
  double value = argIn.getKeyDouble(ModeStr[mode], 0.0);
  switch (mode) {
    case SET: mprintf("\tDihedral will be set to %g degrees.\n", value); break;
    case INCREMENT: mprintf("\tDihedral will be incremented by %g degrees.\n", value); break;
  }
  // Convert to radians
  value *= Constants::DEGRAD;

  // Select dihedral atoms
  int A1, A2, A3, A4;
  if (argIn.Contains("type")) {
    // By type
    ArgList typeArg = argIn.GetStringKey("type");
    if (typeArg.empty()) {
      mprinterr("Error: No dihedral type specified after 'type'\n");
      return CpptrajState::ERR;
    }
    DihedralSearch dihSearch;
    dihSearch.SearchForArgs( typeArg );
    if (dihSearch.NoDihedralTokens()) {
      mprinterr("Error: Specified dihedral type not recognized.\n");
      return CpptrajState::ERR;
    }
    // Get residue
    int res = argIn.getKeyInt("res", -1);
    if (res <= 0) {
      mprinterr("Error: If 'type' specified 'res' must be specified and > 0.\n");
      return CpptrajState::ERR;
    }
    // Search for dihedrals. User residue #s start from 1.
    if (dihSearch.FindDihedrals(CRD->Top(), Range(res-1)))
      return CpptrajState::ERR;
    DihedralSearch::mask_it dih = dihSearch.begin();
    A1 = dih->A0();
    A2 = dih->A1();
    A3 = dih->A2();
    A4 = dih->A3();
  } else {
    // By masks
    AtomMask m1( argIn.GetMaskNext() );
    AtomMask m2( argIn.GetMaskNext() );
    AtomMask m3( argIn.GetMaskNext() );
    AtomMask m4( argIn.GetMaskNext() );
    if (CRD->Top().SetupIntegerMask( m1 )) return CpptrajState::ERR;
    if (CRD->Top().SetupIntegerMask( m2 )) return CpptrajState::ERR;
    if (CRD->Top().SetupIntegerMask( m3 )) return CpptrajState::ERR;
    if (CRD->Top().SetupIntegerMask( m4 )) return CpptrajState::ERR;
    if (m1.Nselected() != 1) return MaskError( m1 );
    if (m2.Nselected() != 1) return MaskError( m2 );
    if (m3.Nselected() != 1) return MaskError( m3 );
    if (m4.Nselected() != 1) return MaskError( m4 );
    A1 = m1[0];
    A2 = m2[0];
    A3 = m3[0];
    A4 = m4[0];
  }
  mprintf("\tRotating dihedral defined by atoms '%s'-'%s'-'%s'-'%s'\n",
          CRD->Top().AtomMaskName(A1).c_str(),
          CRD->Top().AtomMaskName(A2).c_str(),
          CRD->Top().AtomMaskName(A3).c_str(),
          CRD->Top().AtomMaskName(A4).c_str());
  // Set mask of atoms that will move during dihedral rotation
  AtomMask Rmask = DihedralSearch::MovingAtoms(CRD->Top(), A2, A3);
  // Calculate current value of dihedral
  double torsion = Torsion( FRM.XYZ(A1), FRM.XYZ(A2), FRM.XYZ(A3), FRM.XYZ(A4) );
  // Calculate delta needed to get to target value.
  double delta;
  switch (mode) {
    case SET:       delta = value - torsion; break;
    case INCREMENT: delta = value; break;
  }
  mprintf("\tOriginal torsion is %g, rotating by %g degrees.\n",
          torsion*Constants::RADDEG, delta*Constants::RADDEG);
  // Set axis of rotation
  Vec3 axisOfRotation = FRM.SetAxisOfRotation( A2, A3 );
  // Calculate rotation matrix for delta.
  Matrix_3x3 rotationMatrix;
  rotationMatrix.CalcRotationMatrix(axisOfRotation, delta);
  // Rotate around axis
  FRM.Rotate(rotationMatrix, Rmask);
  // RMS-fit the non-moving part of the coords back on original
  AtomMask refMask = Rmask;
  refMask.InvertMask();
  FRM.Align( refFrame, refMask );
  // Update coords
  OUT->SetCRD( outframe, FRM );

  return CpptrajState::OK;
}
コード例 #6
0
ファイル: console.cpp プロジェクト: wjvaandrager/ros
bool DxlROSCommand::execute(ArgList args)
{
  // Sanity check
  if (args.size() != nargs_)
	return false;
  
  if (name_ == "exit")
  {
    ros::shutdown();
    return true;
  }
  else if (name_ == "id")
  {
    if (args.size() == 1)
    {
      int id = atoi(args[0].c_str());
      if (id >= 0 && id <= 255)
        console_->setMotor(id);
      else
        return false;
    }
    else
    {
      CDxlGeneric *motor = console_->getMotor();
      DxlROSConsole::MotorList &motors = console_->getMotors();
    
      cout << "Available motors:" << endl;
      for (size_t ii=0; ii < motors.size(); ++ii)
      {
        if (motors[ii] == motor)
          cout << "* ";
        else
          cout << "  ";
        cout << "id " << motors[ii]->getID() << endl;
      }
    }
  
    return true;
  }
  else if (name_ == "hb")
  {
    double freq = atof(args[0].c_str());
    if (freq < 0)
      return false;
      
    if (freq > 0)
      console_->setHeartbeatInterval(1/freq);
    else
      console_->setHeartbeatInterval(0);
      
    return true;
  }
  else if (name_ == "scan")
  {
    CDxlGeneric *motor = console_->createMotor();
    CDxlConfig config;
    std::vector<int> motors;

    for (int id=1; id < BROADCAST_ID && ros::ok(); ++id)
    {
      motor->setConfig(config.setID(id));
      if (motor->ping() == DXL_SUCCESS)
        motors.push_back(id);
        
      std::cout << "Scanning [";
      for (int ii=1; ii < BROADCAST_ID; ++ii)
        if (!(ii%15))
        {
          if (ii < id)
            cout << "=";
          else
            cout << ".";
        }
      cout << "]\r" << flush;
    }
    
    delete motor;
    
    if (motors.empty())
    {
      cout << "No motors found. Check the connection and power." << endl;
    }
    else
    {
      cout << "Motor controllers found on bus:" << endl;
      for (size_t ii=0; ii < motors.size(); ++ii)
        cout << "  id " << motors[ii] << endl;
    }
    
    return true;
  }
  
  CDxlGeneric *motor = console_->getMotor();
  if (!motor)
  {
    cout << "Error:" << endl << "  No motor specified" << endl;
    return true;
  }
  
  if (name_ == "init")
    DXLC_SAFE_CALL(motor->init(false));
  else if (name_ == "mode")
  {
    if (args[0] == "speed")
      DXLC_SAFE_CALL(motor->set3MxlMode(SPEED_MODE));
    else if (args[0] == "pos")
      DXLC_SAFE_CALL(motor->set3MxlMode(POSITION_MODE));
    else if (args[0] == "current")
      DXLC_SAFE_CALL(motor->set3MxlMode(CURRENT_MODE));
    else if (args[0] == "torque")
      DXLC_SAFE_CALL(motor->set3MxlMode(TORQUE_MODE));
    else if (args[0] == "sine")
      DXLC_SAFE_CALL(motor->set3MxlMode(SINUSOIDAL_POSITION_MODE));
    else if (args[0] == "ext_init")
      DXLC_SAFE_CALL(motor->set3MxlMode(EXTERNAL_INIT));
    else if (args[0] == "hsi_init")
      DXLC_SAFE_CALL(motor->set3MxlMode(HOME_SWITCH_AND_INDEX_INIT));
    else if (args[0] == "pwm")
      DXLC_SAFE_CALL(motor->set3MxlMode(PWM_MODE));
    else if (args[0] == "stop")
      DXLC_SAFE_CALL(motor->set3MxlMode(STOP_MODE));
    else
    {
      cout << "Unknown mode" << endl;
      return false;
    }
  }
  else if (name_ == "config")
  {
    CXMLConfiguration config_xml;
    
    if (!config_xml.loadFile(args[0]))
    {
      cout << "Couldn't read config from " << args[0] << endl;
      return false;
    }
    
    CDxlConfig config;
    if (args.size() == 2)
      config.readConfig(config_xml.root().section(args[1]));
    else
      config.readConfig(config_xml.root());
      
    if (config.mID.isSet() && config.mID != motor->getID())
      cout << "Config has different ID. Ignoring" << std::endl;
      
    config.setID(motor->getID());
    DXLC_SAFE_CALL(config.configureDynamixel(motor));
  }
  else if (name_ == "pos")
  {
    switch (args.size())
    {
      case 0:
        DXLC_SAFE_CALL(motor->getPos());
        cout << "Position:" << endl << "  " << motor->presentPos() << " rad" << endl;
        break;
      case 1:
        DXLC_SAFE_CALL(motor->setPos(atof(args[0].c_str())));
        break;
      case 2:
        DXLC_SAFE_CALL(motor->setPos(atof(args[0].c_str()), atof(args[1].c_str())));
        break;
      case 3:
        DXLC_SAFE_CALL(motor->setPos(atof(args[0].c_str()), atof(args[1].c_str()), atof(args[2].c_str())));
        break;
    }
  }
  else if (name_ == "speed")
    DXLC_SAFE_CALL(motor->setSpeed(atof(args[0].c_str())));
  else if (name_ == "accel")
    DXLC_SAFE_CALL(motor->setAcceleration(atof(args[0].c_str())));
  else if (name_ == "moffset")
    DXLC_SAFE_CALL(motor->setMotorOffset(atof(args[0].c_str())));
  else if (name_ == "joffset")
    DXLC_SAFE_CALL(motor->setJointOffset(atof(args[0].c_str())));
  else if (name_ == "jlimits")
    DXLC_SAFE_CALL(motor->setAngleLimits(atof(args[0].c_str()), atof(args[1].c_str())));
  else if (name_ == "lpos")
  {
    switch (args.size())
    {
      case 0:
        DXLC_SAFE_CALL(motor->getLinearPos());
        cout << "Position:" << endl << "  " << motor->presentLinearPos() << " m" << endl;
        break;
      case 1:
        DXLC_SAFE_CALL(motor->setLinearPos(atof(args[0].c_str())));
        break;
      case 2:
        DXLC_SAFE_CALL(motor->setLinearPos(atof(args[0].c_str()), atof(args[1].c_str())));
        break;
      case 3:
        DXLC_SAFE_CALL(motor->setLinearPos(atof(args[0].c_str()), atof(args[1].c_str()), atof(args[2].c_str())));
        break;
    }
  }
  else if (name_ == "lspeed")
    DXLC_SAFE_CALL(motor->setLinearSpeed(atof(args[0].c_str())));
  else if (name_ == "laccel")
    DXLC_SAFE_CALL(motor->setLinearAcceleration(atof(args[0].c_str())));
  else if (name_ == "current")
    DXLC_SAFE_CALL(motor->setCurrent(atof(args[0].c_str())));
  else if (name_ == "torque")
    DXLC_SAFE_CALL(motor->setTorque(atof(args[0].c_str())));
  else if (name_ == "pwm")
    DXLC_SAFE_CALL(motor->setPWM(atof(args[0].c_str())));
  else if (name_ == "freq")
    DXLC_SAFE_CALL(motor->setSineFrequency(atof(args[0].c_str())));
  else if (name_ == "ampl")
    DXLC_SAFE_CALL(motor->setSineAmplitude(atof(args[0].c_str())));
  else if (name_ == "phase")
    DXLC_SAFE_CALL(motor->setSinePhase(atof(args[0].c_str())));
  else if (name_ == "accel")
    DXLC_SAFE_CALL(motor->setAcceleration(atof(args[0].c_str())));
  else if (name_ == "ppid")
  {
    if (args.empty())
    {
      double p, d, i, i_limit;
      DXLC_SAFE_CALL(motor->getPIDPosition(p, d, i, i_limit));
      cout << "Position gains:" << endl << "  " << std::fixed
           << "P  " << std::setw(8) << std::setprecision(3) << p << ", "
           << "D  " << std::setw(8) << std::setprecision(3) << d << ", "
           << "I  " << std::setw(8) << std::setprecision(3) << i << ", "
           << "IL " << std::setw(8) << std::setprecision(3) << i_limit << endl;
    }
    else
      DXLC_SAFE_CALL(motor->setPIDPosition(atof(args[0].c_str()), atof(args[1].c_str()), atof(args[2].c_str()), atof(args[3].c_str())));
  }
  else if (name_ == "spid")
  {
    if (args.empty())
    {
      double p, d, i, i_limit;
      DXLC_SAFE_CALL(motor->getPIDSpeed(p, d, i, i_limit));
      cout << "Speed gains:" << endl << "  " << std::fixed
           << "P  " << std::setw(8) << std::setprecision(3) << p << ", "
           << "D  " << std::setw(8) << std::setprecision(3) << d << ", "
           << "I  " << std::setw(8) << std::setprecision(3) << i << ", "
           << "IL " << std::setw(8) << std::setprecision(3) << i_limit << endl;
    }
    else
      DXLC_SAFE_CALL(motor->setPIDSpeed(atof(args[0].c_str()), atof(args[1].c_str()), atof(args[2].c_str()), atof(args[3].c_str())));
  }
  else if (name_ == "cpid")
  {
    if (args.empty())
    {
      double p, d, i, i_limit;
      DXLC_SAFE_CALL(motor->getPIDCurrent(p, d, i, i_limit));
      cout << "Current gains:" << endl << "  " << std::fixed
           << "P  " << std::setw(8) << std::setprecision(3) << p << ", "
           << "D  " << std::setw(8) << std::setprecision(3) << d << ", "
           << "I  " << std::setw(8) << std::setprecision(3) << i << ", "
           << "IL " << std::setw(8) << std::setprecision(3) << i_limit << endl;
    }
    else
      DXLC_SAFE_CALL(motor->setPIDCurrent(atof(args[0].c_str()), atof(args[1].c_str()), atof(args[2].c_str()), atof(args[3].c_str())));
  }
  else if (name_ == "tpid")
  {
    if (args.empty())
    {
      double p, d, i, i_limit;
      DXLC_SAFE_CALL(motor->getPIDTorque(p, d, i, i_limit));
      cout << "Torque gains:" << endl << "  " << std::fixed
           << "P  " << std::setw(8) << std::setprecision(3) << p << ", "
           << "D  " << std::setw(8) << std::setprecision(3) << d << ", "
           << "I  " << std::setw(8) << std::setprecision(3) << i << ", "
           << "IL " << std::setw(8) << std::setprecision(3) << i_limit << endl;
    }
    else
      DXLC_SAFE_CALL(motor->setPIDTorque(atof(args[0].c_str()), atof(args[1].c_str()), atof(args[2].c_str()), atof(args[3].c_str())));
  }
  else if (name_ == "state")
  {
    DxlROSConsole::MotorList &motors = console_->getMotors();

    cout << "State:" << endl << std::fixed;

    for (size_t ii=0; ii < motors.size(); ++ii)
    {
      if (motors[ii]->isInitialized() && motors[ii]->getID() != BROADCAST_ID)
      {
        if (motors[ii] == motor)
          cout << "* ";
        else
          cout << "  ";
        
        DXLC_SAFE_CALL(motors[ii]->getState());
        DXLC_SAFE_CALL(motors[ii]->getStatus());

        cout << "id " << motors[ii]->getID() << " "
           << std::setw(8) << std::setprecision(3) << motors[ii]->presentVoltage() << " V, "
           << std::setw(8) << std::setprecision(3) << motors[ii]->presentCurrent() << " A, "
           << std::setw(8) << std::setprecision(3) << motors[ii]->presentTorque()  << " Nm, "
           << std::setw(8) << std::setprecision(3) << motors[ii]->presentPos()     << " rad, "
           << std::setw(8) << std::setprecision(3) << motors[ii]->presentSpeed()   << " rad/s, "
           << C3mxl::translateErrorCode(motors[ii]->presentStatus()) << " (0x" << hex << motors[ii]->presentStatus() << dec << ")" << endl;
      }
    }
    
    cout << std::resetiosflags(std::ios_base::floatfield);
  }
  else if (name_ == "bus")
  {
    DXLC_SAFE_CALL(motor->getBusVoltage());
    cout << "Bus voltage:" << endl << "  " << motor->presentBusVoltage() << " V" << endl;
  }
  else if (name_ == "sensors")
  {
    DXLC_SAFE_CALL(motor->getSensorVoltages());
    cout << "Analog sensor voltages:" << endl << "  " << std::fixed
         << "Bus         " << std::setw(8) << std::setprecision(3) << motor->presentBusVoltage() << ", "
         << "Current ADC " << std::setw(8) << std::setprecision(3) << motor->presentCurrentADCVoltage() << ", "
         << "Analog 1    " << std::setw(8) << std::setprecision(3) << motor->presentAnalog1Voltage() << ", "
         << "Analog 2    " << std::setw(8) << std::setprecision(3) << motor->presentAnalog2Voltage() << endl;
  }
  else if (name_ == "log")
    DXLC_SAFE_CALL(motor->setLogInterval(atoi(args[0].c_str())));
  else if (name_ == "getlog")
  {
    DXLC_SAFE_CALL(motor->getLog());
    TMxlLog log = motor->presentLog();
    cout << "    Time      PWM  Current  Voltage  Desired   Actual" << endl;
    for (TMxlLog::iterator ii = log.begin(); ii != log.end(); ++ii)
      cout << (*ii) << endl;
  }
  else if (name_ == "savelog")
  {
    DXLC_SAFE_CALL(motor->getLog());
    TMxlLog log = motor->presentLog();

    std::ofstream logstream(args[0].c_str());
    logstream << "    Time      PWM  Current  Voltage  Desired   Actual" << endl;
    for (TMxlLog::iterator ii = log.begin(); ii != log.end(); ++ii)
      logstream << (*ii) << endl;
    logstream.close();
  }
  else if (name_ == "table")
  {
    BYTE data[256];
    
    // Read control table in chunks to stay within maximum message size
    for (int ii=0; ii < 256; ii += 64)
      DXLC_SAFE_CALL(motor->readData(ii, 64, &data[ii]));

    cout << "Control table:" << endl;
    for (int rr=0; rr != 16; rr++)
    {
      cout << "  " << hex << std::setfill('0');
      for (int cc=0; cc != 16; ++cc)
      {
        cout << std::setw(2) << cc*16+rr << ": " << std::setw(2) << (int)data[cc*16+rr];
        if (cc < 16-1) cout << ", ";
      }
      cout << dec << std::setfill(' ') << endl;
    }
  }
  else
  {
    cout << "Error:" << endl << "  Unknown command" << endl;
    return false;
  }

  return true;
}
コード例 #7
0
ファイル: DataIO_Std.cpp プロジェクト: Amber-MD/cpptraj
// DataIO_Std::Read_1D()
int DataIO_Std::Read_1D(std::string const& fname, 
                        DataSetList& datasetlist, std::string const& dsname)
{
  ArgList labels;
  bool hasLabels = false;
  // Buffer file
  BufferedLine buffer;
  if (buffer.OpenFileRead( fname )) return 1;

  // Read the first line. Attempt to determine the number of columns
  const char* linebuffer = buffer.Line();
  if (linebuffer == 0) return 1;
  int ntoken = buffer.TokenizeLine( SEPARATORS );
  if ( ntoken == 0 ) {
    mprinterr("Error: No columns detected in %s\n", buffer.Filename().full());
    return 1;
  }

  // Try to skip past any comments. If line begins with a '#', assume it
  // contains labels. 
  bool isCommentLine = true;
  const char* ptr = linebuffer;
  while (isCommentLine) {
    // Skip past any whitespace
    while ( *ptr != '\0' && isspace(*ptr) ) ++ptr;
    // Assume these are column labels until proven otherwise.
    if (*ptr == '#') {
      labels.SetList(ptr+1, SEPARATORS );
      if (!labels.empty()) {
        hasLabels = true;
        // If first label is Frame assume it is the index column
        if (labels[0] == "Frame" && indexcol_ == -1)
          indexcol_ = 0;
      }
      linebuffer = buffer.Line();
      ptr = linebuffer;
      if (ptr == 0) {
        mprinterr("Error: No data found in file.\n");
        return 1;
      }
    } else 
      // Not a recognized comment character, assume data.
      isCommentLine = false;
  }
  // Special case: check if labels are '#F1   F2 <name> [nframes <#>]'. If so, assume
  // this is a cluster matrix file.
  if ((labels.Nargs() == 3 || labels.Nargs() == 5) && labels[0] == "F1" && labels[1] == "F2")
  {
    mprintf("Warning: Header format '#F1 F2 <name>' detected, assuming cluster pairwise matrix.\n");
    return IS_ASCII_CMATRIX;
  }
  // Column user args start from 1
  if (indexcol_ > -1)
    mprintf("\tUsing column %i as index column.\n", indexcol_ + 1);

  // Should be at first data line. Tokenize the line.
  ntoken = buffer.TokenizeLine( SEPARATORS );
  // If # of data columns does not match # labels, clear labels.
  if ( !labels.empty() && ntoken != labels.Nargs() ) {
    labels.ClearList();
    hasLabels = false;
  }
  // Index column checks
  if (indexcol_ != -1 ) {
    if (indexcol_ >= ntoken) {
      mprinterr("Error: Specified index column %i is out of range (%i columns).\n",
                indexcol_+1, ntoken);
      return 1;
    }
    if (!onlycols_.Empty() && !onlycols_.InRange(indexcol_)) {
      mprinterr("Error: Index column %i specified, but not in given column range '%s'\n",
                indexcol_+1, onlycols_.RangeArg());
      return 1;
    }
  }

  // Determine the type of data stored in each column. Assume numbers should
  // be read with double precision.
  MetaData md( dsname );
  DataSetList::DataListType inputSets;
  unsigned int nsets = 0;
  for (int col = 0; col != ntoken; ++col) {
    std::string token( buffer.NextToken() );
    if (!onlycols_.Empty() && !onlycols_.InRange( col )) {
      mprintf("\tSkipping column %i\n", col+1);
      inputSets.push_back( 0 );
    } else {
      md.SetIdx( col+1 );
      if (hasLabels) md.SetLegend( labels[col] );
      if ( col == indexcol_ ) {
        // Always save the index column as floating point
        inputSets.push_back( new DataSet_double() );
      } else if (validInteger(token)) {
        // Integer number
        inputSets.push_back( datasetlist.Allocate(DataSet::INTEGER) );
      } else if (validDouble(token)) {
        // Floating point number
        inputSets.push_back( new DataSet_double() );
      } else {
        // Assume string. Not allowed for index column.
        if (col == indexcol_) {
          mprintf("Warning: '%s' index column %i has string values. No indices will be read.\n", 
                    buffer.Filename().full(), indexcol_+1);
          indexcol_ = -1;
        }
        inputSets.push_back( new DataSet_string() );
      }
      inputSets.back()->SetMeta( md );
      nsets++;
    }
  }
  if (inputSets.empty() || nsets == 0) {
    mprinterr("Error: No data detected.\n");
    return 1;
  }

  // Read in data
  while (linebuffer != 0) {
    if ( buffer.TokenizeLine( SEPARATORS ) != ntoken ) {
      PrintColumnError(buffer.LineNumber());
      break;
    }
    // Convert data in columns
    for (int i = 0; i < ntoken; ++i) {
      const char* token = buffer.NextToken();
      if (inputSets[i] != 0) {
        if (inputSets[i]->Type() == DataSet::DOUBLE)
          ((DataSet_double*)inputSets[i])->AddElement( atof(token) );
        else if (inputSets[i]->Type() == DataSet::INTEGER)
          ((DataSet_integer*)inputSets[i])->AddElement( atoi(token) );
        else
          ((DataSet_string*)inputSets[i])->AddElement( std::string(token) );
      }
    }
    //Ndata++;
    linebuffer = buffer.Line();
  }
  buffer.CloseFile();
   mprintf("\tDataFile %s has %i columns, %i lines.\n", buffer.Filename().full(),
           ntoken, buffer.LineNumber());

  // Create list containing only data sets.
  DataSetList::DataListType mySets;
  DataSet_double* Xptr = 0;
  for (int idx = 0; idx != (int)inputSets.size(); idx++) {
    if (inputSets[idx] != 0) {
      if ( idx != indexcol_ )
        mySets.push_back( inputSets[idx] );
      else
        Xptr = (DataSet_double*)inputSets[idx];
    }
  }
  mprintf("\tRead %zu data sets.\n", mySets.size());
  std::string Xlabel;
  if (indexcol_ != -1 && indexcol_ < labels.Nargs())
    Xlabel = labels[indexcol_];
  if (Xptr == 0)
    datasetlist.AddOrAppendSets(Xlabel, DataSetList::Darray(), mySets);
  else {
    datasetlist.AddOrAppendSets(Xlabel, Xptr->Data(), mySets);
    delete Xptr;
  }

  return 0;
}