Beispiel #1
0
/** Remove peaks from a input workspace
  */
Workspace2D_sptr
RemovePeaks::removePeaks(API::MatrixWorkspace_const_sptr dataws, int wsindex,
                         double numfwhm) {
  // Check
  if (m_vecPeakCentre.empty())
    throw runtime_error("RemovePeaks has not been setup yet. ");

  // Initialize vectors
  const MantidVec &vecX = dataws->readX(wsindex);
  const MantidVec &vecY = dataws->readY(wsindex);
  const MantidVec &vecE = dataws->readE(wsindex);

  size_t sizex = vecX.size();
  vector<bool> vec_useX(sizex, true);

  // Exclude regions
  size_t numbkgdpoints =
      excludePeaks(vecX, vec_useX, m_vecPeakCentre, m_vecPeakFWHM, numfwhm);
  size_t numbkgdpointsy = numbkgdpoints;
  size_t sizey = vecY.size();
  if (sizex > sizey)
    --numbkgdpointsy;

  // Construct output workspace
  Workspace2D_sptr outws = boost::dynamic_pointer_cast<Workspace2D>(
      WorkspaceFactory::Instance().create("Workspace2D", 1, numbkgdpoints,
                                          numbkgdpointsy));
  outws->getAxis(0)->setUnit(dataws->getAxis(0)->unit()->unitID());
  MantidVec &outX = outws->dataX(0);
  MantidVec &outY = outws->dataY(0);
  MantidVec &outE = outws->dataE(0);
  size_t index = 0;
  for (size_t i = 0; i < sizex; ++i) {
    if (vec_useX[i]) {
      if (index >= numbkgdpoints)
        throw runtime_error("Programming logic error (1)");
      outX[index] = vecX[i];
      ++index;
    }
  }
  index = 0;
  for (size_t i = 0; i < sizey; ++i) {
    if (vec_useX[i]) {
      if (index >= numbkgdpointsy)
        throw runtime_error("Programming logic error (2)");
      outY[index] = vecY[i];
      outE[index] = vecE[i];
      ++index;
    }
  }

  return outws;
}
  /** Construct output
   */
  Workspace2D_sptr RefinePowderInstrumentParameters2::genOutputWorkspace(FunctionDomain1DVector domain,
                                                               FunctionValues rawvalues)
  {
    // 1. Create and set up output workspace
    size_t lenx = m_dataWS->readX(m_wsIndex).size();
    size_t leny = m_dataWS->readY(m_wsIndex).size();

    Workspace2D_sptr outws = boost::dynamic_pointer_cast<Workspace2D>
        (WorkspaceFactory::Instance().create("Workspace2D", 6, lenx, leny));

    outws->getAxis(0)->setUnit("dSpacing");

    TextAxis* taxis = new TextAxis(outws->getNumberHistograms());
    taxis->setLabel(0, "Data");
    taxis->setLabel(1, "Model");
    taxis->setLabel(2, "DiffDM");
    taxis->setLabel(3, "Start");
    taxis->setLabel(4, "DiffDS");
    taxis->setLabel(5, "Zdiff");
    outws->replaceAxis(1, taxis);

    // 3. Re-calculate values
    FunctionValues funcvalues(domain);
    m_positionFunc->function(domain, funcvalues);

    // 4. Add values
    // a) X axis
    for (size_t iws = 0; iws < outws->getNumberHistograms(); ++iws)
    {
      MantidVec& vecX = outws->dataX(iws);
      for (size_t n = 0; n < lenx; ++n)
        vecX[n] = domain[n];
    }

    // b) Y axis
    const MantidVec& dataY = m_dataWS->readY(m_wsIndex);

    for (size_t i = 0; i < domain.size(); ++i)
    {
      outws->dataY(0)[i] = dataY[i];
      outws->dataY(1)[i] = funcvalues[i];
      outws->dataY(2)[i] = dataY[i] - funcvalues[i];
      outws->dataY(3)[i] = rawvalues[i];
      outws->dataY(4)[i] = dataY[i] - rawvalues[i];
    }

    // 5. Zscore
    vector<double> zscore = Kernel::getZscore(outws->readY(2));
    for (size_t i = 0; i < domain.size(); ++i)
      outws->dataY(5)[i] = zscore[i];

    return outws;
  }
Beispiel #3
0
/**
 * Reads the data (FITS matrix) from a single FITS file into a
 * workspace (directly into the spectra, using one spectrum per image
 * row).
 *
 * @param fileInfo information on the FITS file to load, including its path
 * @param cmpp centimeters per pixel, to scale/normalize values
 * @param ws workspace with the required dimensions
 * @param buffer pre-allocated buffer to read from file
 *
 * @throws std::runtime_error if there are file input issues
 */
void LoadFITS::readDataToWorkspace(const FITSInfo &fileInfo, double cmpp,
                                   Workspace2D_sptr ws,
                                   std::vector<char> &buffer) {
  const size_t bytespp = (fileInfo.bitsPerPixel / 8);
  const size_t len = m_pixelCount * bytespp;
  readInBuffer(fileInfo, buffer, len);

  const size_t nrows(fileInfo.axisPixelLengths[1]),
      ncols(fileInfo.axisPixelLengths[0]);
  // Treat buffer as a series of bytes
  uint8_t *buffer8 = reinterpret_cast<uint8_t *>(buffer.data());

  PARALLEL_FOR_NO_WSP_CHECK()
  for (int i = 0; i < static_cast<int>(nrows); ++i) {
    auto &dataX = ws->dataX(i);
    auto &dataY = ws->dataY(i);
    auto &dataE = ws->dataE(i);
    std::fill(dataX.begin(), dataX.end(), static_cast<double>(i) * cmpp);

    for (size_t j = 0; j < ncols; ++j) {
      // Map from 2D->1D index
      const size_t start = ((i * (bytespp)) * nrows) + (j * (bytespp));
      uint8_t const *const buffer8Start = buffer8 + start;
      // Reverse byte order of current value. Make sure we allocate enough
      // enough space to hold the size
      uint8_t byteValue[g_maxBytesPP];
      std::reverse_copy(buffer8Start, buffer8Start + bytespp, byteValue);

      double val = 0;
      if (fileInfo.bitsPerPixel == 8) {
        val = toDouble<uint8_t>(byteValue);
      } else if (fileInfo.bitsPerPixel == 16) {
        val = toDouble<uint16_t>(byteValue);
      } else if (fileInfo.bitsPerPixel == 32 && !fileInfo.isFloat) {
        val = toDouble<uint32_t>(byteValue);
      } else if (fileInfo.bitsPerPixel == 64 && !fileInfo.isFloat) {
        val = toDouble<uint32_t>(byteValue);
      } else if (fileInfo.bitsPerPixel == 32 && fileInfo.isFloat) {
        val = toDouble<float>(byteValue);
      } else if (fileInfo.bitsPerPixel == 64 && fileInfo.isFloat) {
        val = toDouble<double>(byteValue);
      }

      val = fileInfo.scale * val - fileInfo.offset;
      dataY[j] = val;
      dataE[j] = sqrt(val);
    }
  }
}
Beispiel #4
0
/** Filter non-background data points out and create a background workspace
  */
Workspace2D_sptr
ProcessBackground::filterForBackground(BackgroundFunction_sptr bkgdfunction) {
  double posnoisetolerance = getProperty("NoiseTolerance");
  double negnoisetolerance = getProperty("NegativeNoiseTolerance");
  if (isEmpty(negnoisetolerance))
    negnoisetolerance = posnoisetolerance;

  // Calcualte theoretical values
  const std::vector<double> x = m_dataWS->readX(m_wsIndex);
  API::FunctionDomain1DVector domain(x);
  API::FunctionValues values(domain);
  bkgdfunction->function(domain, values);

  g_log.information() << "Function used to select background points : "
                      << bkgdfunction->asString() << "\n";

  // Optional output
  string userbkgdwsname = getPropertyValue("UserBackgroundWorkspace");
  if (userbkgdwsname.size() == 0)
    throw runtime_error("In mode SelectBackgroundPoints, "
                        "UserBackgroundWorkspace must be given!");

  size_t sizex = domain.size();
  size_t sizey = values.size();
  MatrixWorkspace_sptr visualws = boost::dynamic_pointer_cast<MatrixWorkspace>(
      WorkspaceFactory::Instance().create("Workspace2D", 4, sizex, sizey));
  for (size_t i = 0; i < sizex; ++i) {
    for (size_t j = 0; j < 4; ++j) {
      visualws->dataX(j)[i] = domain[i];
    }
  }
  for (size_t i = 0; i < sizey; ++i) {
    visualws->dataY(0)[i] = values[i];
    visualws->dataY(1)[i] = m_dataWS->readY(m_wsIndex)[i] - values[i];
    visualws->dataY(2)[i] = posnoisetolerance;
    visualws->dataY(3)[i] = -negnoisetolerance;
  }
  setProperty("UserBackgroundWorkspace", visualws);

  // Filter for background
  std::vector<double> vecx, vecy, vece;
  for (size_t i = 0; i < domain.size(); ++i) {
    // double y = m_dataWS->readY(m_wsIndex)[i];
    // double theoryy = values[i]; y-theoryy
    double purey = visualws->readY(1)[i];
    if (purey < posnoisetolerance && purey > -negnoisetolerance) {
      // Selected
      double x = domain[i];
      double y = m_dataWS->readY(m_wsIndex)[i];
      double e = m_dataWS->readE(m_wsIndex)[i];
      vecx.push_back(x);
      vecy.push_back(y);
      vece.push_back(e);
    }
  }
  g_log.information() << "Found " << vecx.size() << " background points out of "
                      << m_dataWS->readX(m_wsIndex).size()
                      << " total data points. "
                      << "\n";

  // Build new workspace for OutputWorkspace
  size_t nspec = 3;
  Workspace2D_sptr outws =
      boost::dynamic_pointer_cast<DataObjects::Workspace2D>(
          API::WorkspaceFactory::Instance().create("Workspace2D", nspec,
                                                   vecx.size(), vecy.size()));
  for (size_t i = 0; i < vecx.size(); ++i) {
    for (size_t j = 0; j < nspec; ++j)
      outws->dataX(j)[i] = vecx[i];
    outws->dataY(0)[i] = vecy[i];
    outws->dataE(0)[i] = vece[i];
  }

  return outws;
}
Beispiel #5
0
    /**
    * Executes the algorithm.
    * Saves the workspace specified by the user to the VTK XML format
    */
    void SaveVTK::exec()
    {
      std::string filename = getProperty("Filename");
      g_log.debug() << "Parameters: Filename='" << filename << "'" << std::endl;
      //add extension
      filename += ".vtu";

      MatrixWorkspace_sptr inputWorkspace = getProperty("InputWorkspace");
      if( !inputWorkspace )
      {
        g_log.error("Failed to retrieve inputWorkspace.");
        throw Exception::NullPointerException("SaveVTK::exec()", "inputWorkspace");
      }

      checkOptionalProperties();

      //Open file for writing
      std::ofstream outVTP(filename.c_str());
      if( !outVTP )
      {
        g_log.error("Failed to open file: " + filename);
        throw Exception::FileError("Failed to open file ", filename);
      }

      // First write document level XML header
      outVTP << "<?xml version=\"1.0\"?>\n"
        "<VTKFile type=\"UnstructuredGrid\" version=\"0.1\" byte_order=\"LittleEndian\">\n"
        "<UnstructuredGrid>\n";

      const std::string workspaceID = inputWorkspace->id();    
      if( workspaceID.find("Workspace2D") != std::string::npos )
      {
        const Workspace2D_sptr localWorkspace = 
          boost::dynamic_pointer_cast<Workspace2D>(inputWorkspace);
        //      const size_t numberOfHist = localWorkspace->getNumberHistograms();

        //Write out whole range
        bool xMin(m_Xmin > 0.0), xMax(m_Xmax > 0.0);
        Progress prog(this,0.0,1.0,97);
        if( !xMin && !xMax )
        {
          for( int hNum = 2; hNum < 100; ++hNum )
          {
            writeVTKPiece(outVTP, localWorkspace->dataX(hNum), localWorkspace->dataY(hNum), 
              localWorkspace->dataE(hNum), hNum);
            prog.report();
          }
        }
        else
        {
          for( int hNum = 2; hNum < 100; ++hNum )
          {
            std::vector<double> xValue, yValue, errors;
            std::vector<double>::size_type nVals(localWorkspace->dataY(hNum).size());
            for( int i = 0; i < (int)nVals; ++i )
            {
              if( xMin && localWorkspace->dataX(hNum)[i] < m_Xmin ) continue;
              if( xMax && localWorkspace->dataX(hNum)[i+1] > m_Xmax)
              {
                xValue.push_back(localWorkspace->dataX(hNum)[i]);
                break;
              }
              xValue.push_back(localWorkspace->dataX(hNum)[i]);
              if( i == (int)nVals - 1 )
              {
                xValue.push_back(localWorkspace->dataX(hNum)[i+1]);
              } 	    
              yValue.push_back(localWorkspace->dataY(hNum)[i]);
              errors.push_back(localWorkspace->dataE(hNum)[i]);
            }
            //sanity check
            assert( (int)xValue.size() == (int)yValue.size() + 1 );

            writeVTKPiece(outVTP, xValue, yValue, errors, hNum);
            prog.report();
          }
        }
      }
      else
      {
        outVTP.close();
        Poco::File(filename).remove();
        throw Exception::NotImplementedError("SaveVTK only implemented for Workspace2D\n");
      }

      // Final XML end block tags
      outVTP << "</UnstructuredGrid>\n</VTKFile>\n";
      outVTP.close();
    }
/** Output distributions in order for a better understanding of the log
  * Result is written to a Workspace2D
  *
  * @param timevec  :: a vector of time stamps
  * @param stepsize :: resolution of the delta time count bin
  */
Workspace2D_sptr GetTimeSeriesLogInformation::calDistributions(
    std::vector<Kernel::DateAndTime> timevec, double stepsize) {
  // 1. Get a vector of delta T (in unit of seconds)
  double dtmin = static_cast<double>(timevec.back().totalNanoseconds() -
                                     timevec[0].totalNanoseconds()) *
                 1.0E-9;
  double dtmax = 0.0;

  vector<double> vecdt(timevec.size() - 1, 0.0);
  for (size_t i = 1; i < timevec.size(); ++i) {
    vecdt[i - 1] = static_cast<double>(timevec[i].totalNanoseconds() -
                                       timevec[i - 1].totalNanoseconds()) *
                   1.0E-9;
    if (vecdt[i - 1] < dtmin)
      dtmin = vecdt[i - 1];
    else if (vecdt[i - 1] > dtmax)
      dtmax = vecdt[i - 1];
  }

  // 2. Create a vector of counts
  size_t numbins;
  if (m_ignoreNegativeTime && dtmin < 0) {
    numbins = static_cast<size_t>(ceil((dtmax) / stepsize)) + 2;
  } else {
    numbins = static_cast<size_t>(ceil((dtmax - dtmin) / stepsize)) + 2;
  }

  g_log.notice() << "Distribution has " << numbins << " bins.  Delta T = ("
                 << dtmin << ", " << dtmax << ")\n";

  Workspace2D_sptr distws = boost::dynamic_pointer_cast<Workspace2D>(
      API::WorkspaceFactory::Instance().create("Workspace2D", 1, numbins,
                                               numbins));
  MantidVec &vecDeltaT = distws->dataX(0);
  MantidVec &vecCount = distws->dataY(0);

  double countmin = dtmin;
  if (m_ignoreNegativeTime && dtmin < 0)
    countmin = 0;

  for (size_t i = 0; i < numbins; ++i)
    vecDeltaT[i] = countmin + (static_cast<double>(i) - 1) * stepsize;
  for (size_t i = 0; i < numbins; ++i)
    vecCount[i] = 0;

  // 3. Count
  for (double dt : vecdt) {
    int index;
    if (dt < 0 && m_ignoreNegativeTime) {
      index = 0;
    } else {
      auto viter = lower_bound(vecDeltaT.begin(), vecDeltaT.end(), dt);
      index = static_cast<int>(viter - vecDeltaT.begin());
      if (index >= static_cast<int>(vecDeltaT.size())) {
        // Out of upper boundary
        g_log.error() << "Find index = " << index
                      << " > vecX.size = " << vecDeltaT.size() << ".\n";
      } else if (dt < vecDeltaT[index]) {
        --index;
      }

      if (index < 0)
        throw runtime_error("How can this happen.");
    }
    vecCount[index] += 1;
  }

  return distws;
}