コード例 #1
0
 /**
  * @return The processing instructions.
  */
 const std::string ReflectometryWorkflowBase::getWorkspaceIndexList() const
 {
   const std::string instructions = getProperty("ProcessingInstructions");
   return instructions;
 }
コード例 #2
0
ファイル: CreateWorkspace.cpp プロジェクト: trnielsen/mantid
/// Exec function
void CreateWorkspace::exec()
{
    // Contortions to get at the vector in the property without copying it
    const Property * const dataXprop = getProperty("DataX");
    const Property * const dataYprop = getProperty("DataY");
    const Property * const dataEprop = getProperty("DataE");
    const std::vector<double>& dataX = *dynamic_cast<const ArrayProperty<double>*>(dataXprop);
    const std::vector<double>& dataY = *dynamic_cast<const ArrayProperty<double>*>(dataYprop);
    const std::vector<double>& dataE = *dynamic_cast<const ArrayProperty<double>*>(dataEprop);

    const int nSpec = getProperty("NSpec");
    const std::string xUnit = getProperty("UnitX");
    const std::string vUnit = getProperty("VerticalAxisUnit");
    const std::vector<std::string> vAxis = getProperty("VerticalAxisValues");
    std::string parentWorkspace = getPropertyValue("ParentWorkspace");

    if ( ( vUnit != "SpectraNumber" ) && ( static_cast<int>(vAxis.size()) != nSpec ) )
    {
        throw std::invalid_argument("Number of y-axis labels must match number of histograms.");
    }

    // Verify length of vectors makes sense with NSpec
    if ( ( dataY.size() % nSpec ) != 0 )
    {
        throw std::invalid_argument("Length of DataY must be divisible by NSpec");
    }
    const std::size_t ySize = dataY.size() / nSpec;

    // Check whether the X values provided are to be re-used for (are common to) every spectrum
    const bool commonX( dataX.size() == ySize || dataX.size() == ySize+1 );

    std::size_t xSize;
    MantidVecPtr XValues;
    if ( commonX )
    {
        xSize = dataX.size();
        XValues.access() = dataX;
    }
    else
    {
        if ( dataX.size() % nSpec != 0 )
        {
            throw std::invalid_argument("Length of DataX must be divisible by NSpec");
        }

        xSize = static_cast<int>(dataX.size()) / nSpec;
        if ( xSize < ySize || xSize > ySize + 1 )
        {
            throw std::runtime_error("DataX width must be as DataY or +1");
        }

    }

    const bool dataE_provided = !dataE.empty();
    if ( dataE_provided && dataY.size() != dataE.size() )
    {
        throw std::runtime_error("DataE (if provided) must be the same size as DataY");
    }

    MatrixWorkspace_sptr parentWS;
    if (!parentWorkspace.empty())
    {
        try
        {
            parentWS = boost::dynamic_pointer_cast<MatrixWorkspace>( AnalysisDataService::Instance().retrieve(parentWorkspace) );
        }
        catch(...)
        {
            g_log.warning("Parent workspace not found");
            // ignore parent workspace
        }
    }

    // Create the OutputWorkspace
    MatrixWorkspace_sptr outputWS;
    if (parentWS)
    {
        // if parent is defined use it to initialise the workspace
        outputWS = WorkspaceFactory::Instance().create(parentWS, nSpec, xSize, ySize);
    }
    else
    {
        // otherwise create a blank workspace
        outputWS = WorkspaceFactory::Instance().create("Workspace2D", nSpec, xSize, ySize);
    }

    Progress progress(this,0,1,nSpec);

    PARALLEL_FOR1(outputWS)
    for ( int i = 0; i < nSpec; i++ )
    {
        PARALLEL_START_INTERUPT_REGION

        const std::vector<double>::difference_type xStart = i*xSize;
        const std::vector<double>::difference_type xEnd = xStart + xSize;
        const std::vector<double>::difference_type yStart = i*ySize;
        const std::vector<double>::difference_type yEnd = yStart + ySize;

        // Just set the pointer if common X bins. Otherwise, copy in the right chunk (as we do for Y).
        if ( commonX )
        {
            outputWS->setX(i,XValues);
        }
        else
        {
            outputWS->dataX(i).assign(dataX.begin()+xStart,dataX.begin()+xEnd);
        }

        outputWS->dataY(i).assign(dataY.begin()+yStart,dataY.begin()+yEnd);

        if ( dataE_provided) outputWS->dataE(i).assign(dataE.begin()+yStart,dataE.begin()+yEnd);

        progress.report();
        PARALLEL_END_INTERUPT_REGION
    }
    PARALLEL_CHECK_INTERUPT_REGION

    // Set the Unit of the X Axis
    try
    {
        outputWS->getAxis(0)->unit() = UnitFactory::Instance().create(xUnit);
    }
    catch ( Exception::NotFoundError & )
    {
        outputWS->getAxis(0)->unit() = UnitFactory::Instance().create("Label");
        Unit_sptr unit = outputWS->getAxis(0)->unit();
        boost::shared_ptr<Units::Label> label = boost::dynamic_pointer_cast<Units::Label>(unit);
        label->setLabel(xUnit, xUnit);
    }

    // Populate the VerticalAxis. A spectra one is there by default with a 1->N mapping
    if ( vUnit != "SpectraNumber" )
    {
        if ( vUnit == "Text" )
        {
            TextAxis* const newAxis = new TextAxis(vAxis.size());
            outputWS->replaceAxis(1, newAxis);
            for ( size_t i = 0; i < vAxis.size(); i++ )
            {
                newAxis->setLabel(i, vAxis[i]);
            }
        }
        else
        {
            NumericAxis* const newAxis = new NumericAxis(vAxis.size());
            newAxis->unit() = UnitFactory::Instance().create(vUnit);
            outputWS->replaceAxis(1, newAxis);
            for ( size_t i = 0; i < vAxis.size(); i++ )
            {
                try
                {
                    newAxis->setValue(i, boost::lexical_cast<double, std::string>(vAxis[i]) );
                }
                catch ( boost::bad_lexical_cast & )
                {
                    throw std::invalid_argument("CreateWorkspace - YAxisValues property could not be converted to a double.");
                }
            }
        }
    }

    // Set distribution flag
    outputWS->isDistribution(getProperty("Distribution"));

    // Set Y Unit label
    if (!parentWS || !getPropertyValue("YUnitLabel").empty())
    {
        outputWS->setYUnitLabel(getProperty("YUnitLabel"));
    }

    // Set Workspace Title
    if (!parentWS || !getPropertyValue("WorkspaceTitle").empty())
    {
        outputWS->setTitle(getProperty("WorkspaceTitle"));
    }

    // Set OutputWorkspace property
    setProperty("OutputWorkspace", outputWS);
}
コード例 #3
0
ファイル: camera_activity.cpp プロジェクト: 112000/opencv
int CameraActivity::getFrameHeight()
{
    if (frameHeight <= 0)
        frameHeight = getProperty(ANDROID_CAMERA_PROPERTY_FRAMEHEIGHT);
    return frameHeight;
}
コード例 #4
0
/** Executes the algorithm. 
 * 
 *  @throw std::runtime_error Thrown with Workspace problems
 */
void RotateInstrumentComponent::exec()
{
  // Get the workspace
  MatrixWorkspace_sptr WS = getProperty("Workspace");
  const std::string ComponentName = getProperty("ComponentName");
  const int DetID = getProperty("DetectorID");
  const double X = getProperty("X");
  const double Y = getProperty("Y");
  const double Z = getProperty("Z");
  const double angle = getProperty("Angle");
  const bool RelativeRotation = getProperty("RelativeRotation");

  if (X + Y + Z == 0.0) throw std::invalid_argument("The rotation axis must not be a zero vector");

  Instrument_const_sptr inst = WS->getInstrument();
  IComponent_const_sptr comp;

  // Find the component to move
  if (DetID != -1)
  {
      comp = inst->getDetector(DetID);
      if (comp == 0)
      {
          std::ostringstream mess;
          mess<<"Detector with ID "<<DetID<<" was not found.";
          g_log.error(mess.str());
          throw std::runtime_error(mess.str());
      }
  }
  else if (!ComponentName.empty())
  {
      comp = inst->getComponentByName(ComponentName);
      if (comp == 0)
      {
          std::ostringstream mess;
          mess<<"Component with name "<<ComponentName<<" was not found.";
          g_log.error(mess.str());
          throw std::runtime_error(mess.str());
      }
  }
  else
  {
      g_log.error("DetectorID or ComponentName must be given.");
      throw std::invalid_argument("DetectorID or ComponentName must be given.");
  }

  // First set new relative or absolute rotation
  Quat Rot;
  if (RelativeRotation)
  {
      Quat Rot0 = comp->getRelativeRot();
      Rot = Rot0 * Quat(angle,V3D(X,Y,Z));
  }
  else
  {
      Rot = Quat(angle,V3D(X,Y,Z));
      // Then find the corresponding relative position
      boost::shared_ptr<const IComponent> parent = comp->getParent();
      if (parent)
      {
          Quat rot0 = parent->getRelativeRot();
          rot0.inverse();
          Rot = Rot * rot0;
      }
  }

  //Need to get the address to the base instrument component
  Geometry::ParameterMap& pmap = WS->instrumentParameters();
  // Add a parameter for the new rotation
  pmap.addQuat(comp.get(), "rot", Rot);

  return;
}
コード例 #5
0
    /// Run the algorithm
    void PredictFractionalPeaks::exec()
    {
       PeaksWorkspace_sptr Peaks=getProperty("Peaks");

       vector<double> hOffsets = getProperty("HOffset");
       vector<double> kOffsets = getProperty("KOffset");
       vector<double> lOffsets = getProperty("LOffset");
       if ( hOffsets.empty())hOffsets.push_back(0.0);
       if ( kOffsets.empty())kOffsets.push_back(0.0);
       if ( lOffsets.empty())lOffsets.push_back(0.0);

;
       bool includePeaksInRange= getProperty("IncludeAllPeaksInRange");

       if(  Peaks->getNumberPeaks()<=0)
       {
         g_log.error()<<"There are No peaks in the input PeaksWorkspace\n";
         return;
       }

       API::Sample samp= Peaks->sample();

       Geometry::OrientedLattice &ol = samp.getOrientedLattice();

       Geometry::Instrument_const_sptr Instr = Peaks->getInstrument();

       boost::shared_ptr<IPeaksWorkspace> OutPeaks=WorkspaceFactory::Instance().createPeaks();
       OutPeaks->setInstrument(Instr);
      // AnalysisDataService::Instance().addOrReplace(getPropertyValue("FracPeaks"),OutPeaks);

       V3D hkl;
       int peakNum =0;
       int NPeaks = Peaks->getNumberPeaks();
       Kernel::Matrix<double> Gon;
       Gon.identityMatrix();

       double Hmin= getProperty("Hmin");
       double Hmax= getProperty("Hmax");
       double Kmin= getProperty("Kmin");
       double Kmax= getProperty("Kmax");
       double Lmin= getProperty("Lmin");
       double Lmax= getProperty("Lmax");

       int N=NPeaks;
       if( includePeaksInRange)
       {
         N=(int)((Hmax-Hmin+1)*(Kmax-Kmin+1)*(Lmax-Lmin+1)+.5);
         N=max<int>(100,N);
       }
       IPeak& peak0 =Peaks->getPeak(0);
       int RunNumber = peak0.getRunNumber();
       Gon=peak0.getGoniometerMatrix();
       Progress prog(this, 0,  1,N);
       if( includePeaksInRange)
       {


         hkl[0]=Hmin;
         hkl[1]=Kmin;
         hkl[2]=Lmin;
       }else
       {
         hkl[0]=peak0.getH();
         hkl[1]=peak0.getK();
         hkl[2] =peak0.getL();


       }

       Kernel::DblMatrix UB= ol.getUB();
       vector< vector<int> > AlreadyDonePeaks;
       bool done = false;
       int ErrPos = 1;//Used to determine position in code of a throw
       while( !done)
       {
         for( size_t hoffset=0;hoffset<hOffsets.size();hoffset++)
           for(size_t  koffset=0;koffset<kOffsets.size();koffset++)
             for( size_t loffset=0;loffset<lOffsets.size();loffset++)
                try
                {
                  V3D hkl1( hkl );
                  ErrPos = 0;

                  hkl1[0] += hOffsets[hoffset] ;
                  hkl1[1] += kOffsets[koffset] ;
                  hkl1[2] += lOffsets[loffset] ;

                  Kernel::V3D Qs = UB * hkl1 ;
                  Qs*= 2.0;
                  Qs*=M_PI;
                  Qs=Gon*Qs;
                  if( Qs[2] <= 0 )
                    continue;

                  ErrPos=1;
                  boost::shared_ptr<IPeak> peak( Peaks->createPeak( Qs, 1 ));

                  peak->setGoniometerMatrix(Gon);

                  if (Qs[2]>0 && peak->findDetector())
                  {
                    ErrPos=2;
                    vector<int> SavPk;
                    SavPk.push_back(RunNumber);
                    SavPk.push_back((int)floor(1000*hkl1[0]+.5));
                    SavPk.push_back((int)floor(1000*hkl1[1]+.5));
                    SavPk.push_back((int)floor(1000*hkl1[2]+.5));

                  //TODO keep list sorted so searching is faster?
                    vector<vector<int> >::iterator it = find(AlreadyDonePeaks.begin(),AlreadyDonePeaks.end(),SavPk);

                    ErrPos=3;
                    if( it == AlreadyDonePeaks.end())
                      AlreadyDonePeaks.push_back(SavPk);
                    else
                      continue;


                    ErrPos=4;
                    peak->setHKL(hkl1);
                    peak->setRunNumber(RunNumber);
                    OutPeaks->addPeak(*peak);
                  }
                }catch(...)
                {

                  if( ErrPos != 1)// setQLabFrame in createPeak throws exception
                    throw new std::invalid_argument( "Invalid data at this point");
                }
         if( includePeaksInRange)
         {
           hkl[0]++;
           if( hkl[0]>Hmax)
           {
             hkl[0]=Hmin;
             hkl[1]++;
             if( hkl[1]> Kmax)
             {

               hkl[1]=Kmin;
               hkl[2]++;
               if( hkl[2]> Lmax)
                 done = true;
             }
           }
         }else
         {
           peakNum++;
           if( peakNum >= NPeaks)
             done = true;
           else
           {// peak0= Peaks->getPeak(peakNum);
             IPeak& peak1= Peaks->getPeak(peakNum);
           //??? could not assign to peak0 above. Did not work
            // the peak that peak0 was associated with did NOT change
             hkl[0]=peak1.getH();
             hkl[1]=peak1.getK();
             hkl[2] =peak1.getL();
             Gon=peak1.getGoniometerMatrix();
             RunNumber = peak1.getRunNumber();

           }
         }
         prog.report();
       }


     setProperty("FracPeaks",OutPeaks);



    }
コード例 #6
0
ファイル: test_dll.cpp プロジェクト: elohim-meth/rtti
int main(int argc, char* argv[])
{
    (void) argc; (void) argv;
    try {
        register_rtti();
        auto lambda = [](std::string const &name, const rtti::variant &value)
        {
            std::cout << name << " = " << value.to<std::string>() << std::endl;
            return true;
        };

        auto nsGlobal = rtti::MetaNamespace::global(); assert(nsGlobal);
        //gNS->forceDeferredDefine(rtti::MetaContainer::ForceDeferred::Recursive);
        std::cout << "namespace " << nsGlobal->name() << std::endl;
        std::cout << "Attribute count: " << nsGlobal->attributeCount() << std::endl;
        nsGlobal->for_each_attribute(lambda);
        std::cout << std::endl;

        auto nsStd = nsGlobal->getNamespace("std"); assert(nsStd);
        std::cout << "namespace " << nsStd->qualifiedName() << std::endl;
        std::cout << "Attribute count: " << nsStd->attributeCount() << std::endl;
        nsStd->for_each_attribute(lambda);
        std::cout << std::endl;

        auto nsTest = nsGlobal->getNamespace("test"); assert(nsTest);
        std::cout << "namespace " << nsTest->qualifiedName() << std::endl;
        std::cout << "Attribute count: " << nsTest->attributeCount() << std::endl;
        nsTest->for_each_attribute(lambda);
        std::cout << std::endl;

        {
            auto prop = nsGlobal->getProperty("global_string"); assert(prop);
            std::cout << prop->qualifiedName() << std::endl;
            prop->set(std::string{"Qwerty"});
            assert(prop->get().cvalue<std::string>() == "Qwerty");
            assert(prop->get().value<const std::string>() == "Qwerty");

            const auto v = prop->get();
            assert(v.value<std::string>() == "Qwerty");
            prop->set(std::string{"YouTube"});
            assert(v.value<std::string>() == "YouTube");
        }

        {
            auto prop = nsGlobal->getProperty("global_readonly_string"); assert(prop);
            std::cout << prop->qualifiedName() << std::endl;
            const auto v = prop->get();
            assert(v.value<std::string>() == "Hello, World");
            try { prop->set(std::string{"Qwerty"}); assert(false);
            } catch (const rtti::runtime_error &e) { LOG_RED(e.what()); };
        }

        {
            auto itosM = nsGlobal->getMethod("intToStr"); assert(itosM);
            {
                bool ok = false;
                auto r = itosM->invoke(123, ok);
                assert(r.value<std::string>() == "123" && ok);
            }

            {
                const bool ok = false;
                try { auto r = itosM->invoke(123, ok); assert(false);
                } catch (const rtti::runtime_error &e) { LOG_RED(e.what()); };
            }

            {
                try { auto r = itosM->invoke(123, false); assert(false);
                } catch (const rtti::runtime_error &e) { LOG_RED(e.what()); };
            }

            {
                rtti::variant ok = false;
                auto r = itosM->invoke(123, ok);
                assert(r.value<std::string>() == "123" && ok.value<bool>());
            }

            {
                rtti::variant const ok = false;
                try { auto r = itosM->invoke(123, ok); assert(false);
                } catch (const rtti::runtime_error &e) { LOG_RED(e.what()); };
            }

            {
                bool ok = false;
                rtti::variant vok = std::ref(ok);
                auto r = itosM->invoke(123, vok);
                assert(r.value<std::string>() == "123" && ok && vok.value<bool>());
            }

            {
                const bool ok = false;
                rtti::variant vok = std::ref(ok);
                try { auto r = itosM->invoke(123, vok); assert(false);
                } catch (const rtti::runtime_error &e) { LOG_RED(e.what()); };
            }

            {
                rtti::variant ok = false;
                try { auto r = itosM->invoke(123, std::move(ok)); assert(false);
                } catch (const rtti::runtime_error &e) { LOG_RED(e.what()); };
            }

        }

        test_cast_1();
        test_variant_1();

        std::printf("\n");
    } catch(const std::exception& e) {
        LOG_RED(e.what());
    } catch (...) {
        LOG_RED("Unknown exception!");
    }

    return 0;
}
コード例 #7
0
void PointByPointVCorrection::exec()
{
  // Get the input workspace and output workspace
  MatrixWorkspace_const_sptr inputWS1 = getProperty("InputW1");
  MatrixWorkspace_const_sptr inputWS2 = getProperty("InputW2");
  MatrixWorkspace_sptr outputWS= getProperty("OutputWorkspace");

  // Check that everything is OK.
  check_validity(inputWS1,inputWS2,outputWS);

  // Now do the normalisation
  const int size=static_cast<int>(inputWS1->readX(0).size());
  const int nHist=static_cast<int>(inputWS1->getNumberHistograms());
  Progress prog(this,0.0,1.0,nHist);

  PARALLEL_FOR3(inputWS1,inputWS2,outputWS)
  for (int i=0;i<nHist;i++) //Looping on all histograms
  {
		PARALLEL_START_INTERUPT_REGION

    const MantidVec& X=inputWS1->readX(i);
    outputWS->setX( i, inputWS1->refX(i) );

    const MantidVec& Y1=inputWS1->readY(i);
    const MantidVec& Y2=inputWS2->readY(i);
    const MantidVec& E1=inputWS1->readE(i);
    const MantidVec& E2=inputWS2->readE(i);
    MantidVec& resultY=outputWS->dataY(i);
    MantidVec& resultE=outputWS->dataE(i);


    // Work on the Y data
    MantidVec binwidths(size); //MantidVec for bin widths
    MantidVec errors(size-1); //MantidVec for temporary errors
    std::adjacent_difference(X.begin(),X.end(),binwidths.begin()); //Calculate the binwidths
    std::transform(binwidths.begin()+1,binwidths.end(),Y2.begin(),resultY.begin(),VectorHelper::DividesNonNull<double>());
    std::transform(Y1.begin(),Y1.end(),resultY.begin(),resultY.begin(),std::multiplies<double>()); // Now resultY contains the A_i=s_i/v_i*Dlam_i

    // Calculate the errors squared related to A_i at this point
    for (int j=0;j<size-1;j++)
    {
      double r=0.0;
      if (std::abs(Y1[j])>1e-7)
        r+=std::pow(E1[j]/Y1[j],2);
      if (std::abs(Y2[j])>1e-7)
        r+=std::pow(E2[j]/Y2[j],2);
      errors[j]=r; // This are the errors^2 of S_i/v_i*Dlam_i
      if (errors[j]>DBL_MAX || errors[j]<-DBL_MAX)
        errors[j]=0;
    }

    // Calculate the normaliser
    double factor1=std::accumulate(Y1.begin(),Y1.end(),0.0);
    double factor2=std::accumulate(resultY.begin(),resultY.end(),0.0);
    double factor=factor1/factor2;

    // Now propagate the error bars due to the normaliser
    double error2_factor1=std::inner_product(E1.begin(),E1.end(),E1.begin(),0.0);
    double error2_factor2=0;

    for (int j=0;j<size-1;j++)
    {
      double test=std::abs(std::pow(resultY[j],2));
      if (test>DBL_MAX)
        test=0;
      error2_factor2+=errors[j]*test/factor2/factor2;
    }
    double error2_factor=(error2_factor1/factor1/factor1+error2_factor2);
    
    // Calculate the normalized Y values
    // NOTE: Previously, we had been using std::transform with std::bind2nd(std::multiplies<double>(),factor)
    //       here, but that seemed to have strange effects in Windows Debug builds which caused the unit tests
    //       to sometimes fail.  Maybe this is some compiler bug to do with using bind2nd within the parrallel macros.
    for( auto rY = resultY.begin(); rY != resultY.end(); ++rY )
    {
      *rY *= factor; // Now result is s_i/v_i*Dlam_i*(sum_i s_i)/(sum_i S_i/v_i*Dlam_i)
    }
    
    //Finally get the normalized errors
    for (int j=0;j<size-1;j++)
      resultE[j]=resultY[j]*sqrt(errors[j]+error2_factor);

    // Check that any masking matches, print a warning if not
    check_masks(inputWS1,inputWS2,i);

    prog.report();
		PARALLEL_END_INTERUPT_REGION
  }
	PARALLEL_CHECK_INTERUPT_REGION

  outputWS->setYUnitLabel("Counts normalised to a vanadium");
  outputWS->isDistribution(false);
}
コード例 #8
0
/** Execute the algorithm.
 */
void CreateMDWorkspace::exec() {
  // Get the properties and validate them
  std::string eventType = getPropertyValue("EventType");
  int ndims_prop = getProperty("Dimensions");
  if (ndims_prop <= 0)
    throw std::invalid_argument(
        "You must specify a number of dimensions >= 1.");
  int mind = this->getProperty("MinRecursionDepth");
  int maxd = this->getProperty("MaxRecursionDepth");
  if (mind > maxd)
    throw std::invalid_argument(
        "MinRecursionDepth must be <= MaxRecursionDepth.");
  if (mind < 0 || maxd < 0)
    throw std::invalid_argument(
        "MinRecursionDepth and MaxRecursionDepth must be positive.");

  size_t ndims = static_cast<size_t>(ndims_prop);

  std::vector<double> extents = getProperty("Extents");
  std::vector<std::string> names = getProperty("Names");
  std::vector<std::string> units = getProperty("Units");
  std::vector<std::string> frames = getProperty("Frames");

  if (extents.size() != ndims * 2)
    throw std::invalid_argument("You must specify twice as many extents "
                                "(min,max) as there are dimensions.");
  if (names.size() != ndims)
    throw std::invalid_argument(
        "You must specify as many names as there are dimensions.");
  if (units.size() != ndims)
    throw std::invalid_argument(
        "You must specify as many units as there are dimensions.");
  // If no frames are specified we want to default to the General Frame,
  // to ensure backward compatibility. But if they are only partly specified,
  // then we want to throw an error. It should be either used correctly or not
  // at all
  if (!frames.empty() && frames.size() != ndims) {
    throw std::invalid_argument(
        "You must specify as many frames as there are dimensions.");
  }

  if (frames.empty()) {
    frames.resize(ndims);
    std::fill(frames.begin(), frames.end(), GeneralFrame::GeneralFrameName);
  }

  // Have the factory create it
  IMDEventWorkspace_sptr out =
      MDEventFactory::CreateMDWorkspace(ndims, eventType);

  // Give all the dimensions
  for (size_t d = 0; d < ndims; d++) {
    auto frame = createMDFrame(frames[d], units[d]);
    MDHistoDimension *dim = new MDHistoDimension(
        names[d], names[d], *frame, static_cast<coord_t>(extents[d * 2]),
        static_cast<coord_t>(extents[d * 2 + 1]), 1);
    out->addDimension(MDHistoDimension_sptr(dim));
  }

  // Initialize it using the dimension
  out->initialize();

  // Call the templated function to finish ints
  CALL_MDEVENT_FUNCTION(this->finish, out);

  // --- File back end ? ----------------
  std::string filename = getProperty("Filename");
  if (!filename.empty()) {
    // First save to the NXS file
    g_log.notice() << "Running SaveMD" << std::endl;
    IAlgorithm_sptr alg = createChildAlgorithm("SaveMD");
    alg->setPropertyValue("Filename", filename);
    alg->setProperty("InputWorkspace",
                     boost::dynamic_pointer_cast<IMDWorkspace>(out));
    alg->executeAsChildAlg();
    // And now re-load it with this file as the backing.
    g_log.notice() << "Running LoadMD" << std::endl;
    alg = createChildAlgorithm("LoadMD");
    alg->setPropertyValue("Filename", filename);
    alg->setProperty("FileBackEnd", true);
    alg->setPropertyValue("Memory", getPropertyValue("Memory"));
    alg->executeAsChildAlg();
    // Replace the workspace with the loaded, file-backed one
    IMDWorkspace_sptr temp;
    temp = alg->getProperty("OutputWorkspace");
    out = boost::dynamic_pointer_cast<IMDEventWorkspace>(temp);
  }

  // Save it on the output.
  setProperty("OutputWorkspace", boost::dynamic_pointer_cast<Workspace>(out));
}
コード例 #9
0
ファイル: StyleLoader.cpp プロジェクト: JurajKubelka/Envision
void StyleLoader::load(const QString& propertyName, bool& value)
{
	value = getProperty(propertyName).compare("true", Qt::CaseInsensitive) == 0;
}
コード例 #10
0
const String CtrlrMidiDevice::getName()
{
	return (getProperty(Ids::name));
}
コード例 #11
0
ファイル: AccountHandler.cpp プロジェクト: Distrotech/abiword
bool AccountHandler::autoConnect()
{
	const std::string autoconnect = getProperty("autoconnect");
	return strcmp(autoconnect.c_str(), "true") == 0;
}
コード例 #12
0
const bool CtrlrMidiDevice::getState()
{
	return (getProperty(Ids::midiDevState));
}
コード例 #13
0
const bool CtrlrMidiDevice::getType()
{
	return ((bool)getProperty(Ids::midiDevType));
}
コード例 #14
0
ファイル: map.cpp プロジェクト: stevecotton/Aethyra
const std::string &Map::getMusicFile() const
{
    return getProperty("music");
}
コード例 #15
0
ファイル: Rebin.cpp プロジェクト: trnielsen/mantid
    /** Executes the rebin algorithm
    *
    *  @throw runtime_error Thrown if the bin range does not intersect the range of the input workspace
    */
    void Rebin::exec()
    {
      // Get the input workspace
      MatrixWorkspace_sptr inputWS = getProperty("InputWorkspace");
      MatrixWorkspace_sptr outputWS = getProperty("OutputWorkspace");

      // Are we preserving event workspace-iness?
      bool PreserveEvents = getProperty("PreserveEvents");

      // Rebinning in-place
      bool inPlace = (inputWS == outputWS);

      // retrieve the properties
      const std::vector<double> in_params=getProperty("Params");
      std::vector<double> rb_params;

      // The validator only passes parameters with size 1, or 3xn.  No need to check again here
      if (in_params.size() >= 3){
        // Input are min, delta, max
        rb_params = in_params;

      } else if (in_params.size() == 1){
        double xmin = 0.;
        double xmax = 0.;
        inputWS->getXMinMax(xmin, xmax);

        g_log.information() << "Using the current min and max as default " << xmin << ", " << xmax << std::endl;

        rb_params.push_back(xmin);
        rb_params.push_back(in_params[0]);
        rb_params.push_back(xmax);

      }

      const bool dist = inputWS->isDistribution();

      const bool isHist = inputWS->isHistogramData();

      // workspace independent determination of length
      const int histnumber = static_cast<int>(inputWS->getNumberHistograms());
      MantidVecPtr XValues_new;
      // create new output X axis
      const int ntcnew = VectorHelper::createAxisFromRebinParams(rb_params, XValues_new.access());

      //---------------------------------------------------------------------------------
      //Now, determine if the input workspace is actually an EventWorkspace
      EventWorkspace_const_sptr eventInputWS = boost::dynamic_pointer_cast<const EventWorkspace>(inputWS);

      if (eventInputWS != NULL)
      {
        //------- EventWorkspace as input -------------------------------------
        EventWorkspace_sptr eventOutputWS = boost::dynamic_pointer_cast<EventWorkspace>(outputWS);

        if (inPlace && PreserveEvents)
        {
          // -------------Rebin in-place, preserving events ----------------------------------------------
          // This only sets the X axis. Actual rebinning will be done upon data access.
          eventOutputWS->setAllX(XValues_new);
          this->setProperty("OutputWorkspace", boost::dynamic_pointer_cast<MatrixWorkspace>(eventOutputWS));
        }
        else if (!inPlace && PreserveEvents)
        {
          // -------- NOT in-place, but you want to keep events for some reason. ----------------------
          // Must copy the event workspace to a new EventWorkspace (and bin that).

          //Make a brand new EventWorkspace
          eventOutputWS = boost::dynamic_pointer_cast<EventWorkspace>(
              API::WorkspaceFactory::Instance().create("EventWorkspace", inputWS->getNumberHistograms(), 2, 1));
          //Copy geometry over.
          API::WorkspaceFactory::Instance().initializeFromParent(inputWS, eventOutputWS, false);
          //You need to copy over the data as well.
          eventOutputWS->copyDataFrom( (*eventInputWS) );

          // This only sets the X axis. Actual rebinning will be done upon data access.
          eventOutputWS->setAllX(XValues_new);

          //Cast to the matrixOutputWS and save it
          this->setProperty("OutputWorkspace", boost::dynamic_pointer_cast<MatrixWorkspace>(eventOutputWS));
        }
        else
        {
          //--------- Different output, OR you're inplace but not preserving Events --- create a Workspace2D -------
          g_log.information() << "Creating a Workspace2D from the EventWorkspace " << eventInputWS->getName() << ".\n";

          //Create a Workspace2D
          // This creates a new Workspace2D through a torturous route using the WorkspaceFactory.
          // The Workspace2D is created with an EMPTY CONSTRUCTOR
          outputWS = WorkspaceFactory::Instance().create("Workspace2D",histnumber,ntcnew,ntcnew-1);
          WorkspaceFactory::Instance().initializeFromParent(inputWS, outputWS, true);

          //Initialize progress reporting.
          Progress prog(this,0.0,1.0, histnumber);

          //Go through all the histograms and set the data
          PARALLEL_FOR3(inputWS, eventInputWS, outputWS)
          for (int i=0; i < histnumber; ++i)
          {
            PARALLEL_START_INTERUPT_REGION

            //Set the X axis for each output histogram
            outputWS->setX(i, XValues_new);

            //Get a const event list reference. eventInputWS->dataY() doesn't work.
            const EventList& el = eventInputWS->getEventList(i);
            MantidVec y_data, e_data;
            // The EventList takes care of histogramming.
            el.generateHistogram(*XValues_new, y_data, e_data);

            //Copy the data over.
            outputWS->dataY(i).assign(y_data.begin(), y_data.end());
            outputWS->dataE(i).assign(e_data.begin(), e_data.end());

            //Report progress
            prog.report(name());
            PARALLEL_END_INTERUPT_REGION
          }
          PARALLEL_CHECK_INTERUPT_REGION

          //Copy all the axes
          for (int i=1; i<inputWS->axes(); i++)
          {
            outputWS->replaceAxis( i, inputWS->getAxis(i)->clone(outputWS.get()) );
            outputWS->getAxis(i)->unit() = inputWS->getAxis(i)->unit();
          }

          //Copy the units over too.
          for (int i=0; i < outputWS->axes(); ++i)
            outputWS->getAxis(i)->unit() = inputWS->getAxis(i)->unit();
          outputWS->setYUnit(eventInputWS->YUnit());
          outputWS->setYUnitLabel(eventInputWS->YUnitLabel());

          // Assign it to the output workspace property
          setProperty("OutputWorkspace", outputWS);
        }

      } // END ---- EventWorkspace
コード例 #16
0
ファイル: StyleLoader.cpp プロジェクト: JurajKubelka/Envision
void StyleLoader::load(const QString& propertyName, QString& value)
{
	value = getProperty(propertyName);
}
コード例 #17
0
/** Executes the algorithm. Reading in Log entries from the Nexus file
 *
 *  @throw Mantid::Kernel::Exception::FileError  Thrown if file is not recognised to be a Nexus datafile
 *  @throw std::runtime_error Thrown with Workspace problems
 */
void LoadMuonLog::exec()
{
  // Retrieve the filename from the properties and perform some initial checks on the filename

  m_filename = getPropertyValue("Filename");

  MuonNexusReader nxload;
  if ( nxload.readLogData(m_filename) != 0 )
  {
    g_log.error("In LoadMuonLog: " + m_filename + " can not be opened.");
    throw Exception::FileError("File does not exist:" , m_filename);
  }

  // Get the input workspace and retrieve sample from workspace.
  // the log data will be loaded into the Sample container of the workspace
  // Also set the sample name at this point, as part of the sample related log data.

  const MatrixWorkspace_sptr localWorkspace = getProperty("Workspace");
  localWorkspace->mutableSample().setName(nxload.getSampleName());

  // Attempt to load the content of each NXlog section into the Sample object
  // Assumes that MuonNexusReader has read all log data
  // Two cases of double or string data allowed
 Progress prog(this,0.0,1.0,nxload.numberOfLogs());
  for (int i = 0; i < nxload.numberOfLogs(); i++)
  {
    std::string logName=nxload.getLogName(i);
    TimeSeriesProperty<double> *l_PropertyDouble = new TimeSeriesProperty<double>(logName);
    TimeSeriesProperty<std::string> *l_PropertyString = new TimeSeriesProperty<std::string>(logName);
    std::vector<double> logTimes;

    // Read log file into Property which is then stored in Sample object
    if(!nxload.logTypeNumeric(i))
    {
       std::string logValue;
       std::time_t logTime;
       for( int j=0;j<nxload.getLogLength(i);j++)
       {
          nxload.getLogStringValues(i,j,logTime,logValue);
          l_PropertyString->addValue(logTime, logValue);
       }
    }
    else
    {
       double logValue;
       std::time_t logTime;
       for( int j=0;j<nxload.getLogLength(i);j++)
       {
          nxload.getLogValues(i,j,logTime,logValue);
          l_PropertyDouble->addValue(logTime, logValue);
       }
    }

    // store Property in Sample object and delete unused object
    if ( nxload.logTypeNumeric(i) )
    {
      localWorkspace->mutableRun().addLogData(l_PropertyDouble);
      delete l_PropertyString;
    }
    else
    {
      localWorkspace->mutableRun().addLogData(l_PropertyString);
      delete l_PropertyDouble;
    }
    prog.report();
  } // end for


  // operation was a success and ended normally
  return;
}
コード例 #18
0
ファイル: ResampleX.cpp プロジェクト: trnielsen/mantid
  /** Execute the algorithm.
   */
  void ResampleX::exec()
  {
    // generically having access to the input workspace is a good idea
    MatrixWorkspace_sptr inputWS = getProperty("InputWorkspace");
    MatrixWorkspace_sptr outputWS = getProperty("OutputWorkspace");
    bool inPlace = (inputWS == outputWS); // Rebinning in-place
    m_isDistribution = inputWS->isDistribution();
    m_isHistogram = inputWS->isHistogramData();
    int numSpectra = static_cast<int>(inputWS->getNumberHistograms());

    // the easy parameters
    m_useLogBinning  = getProperty("LogBinning");
    m_numBins        = getProperty("NumberBins");
    m_preserveEvents = getProperty("PreserveEvents");

    // determine the xmin/xmax for the workspace
    vector<double> xmins = getProperty("XMin");
    vector<double> xmaxs = getProperty("XMax");
    string error = determineXMinMax(inputWS, xmins, xmaxs);
    if (!error.empty())
      throw std::runtime_error(error);

    // start doing actual work
    EventWorkspace_const_sptr inputEventWS = boost::dynamic_pointer_cast<const EventWorkspace>(inputWS);
    if (inputEventWS != NULL)
    {
      if (m_preserveEvents)
      {
        EventWorkspace_sptr outputEventWS = boost::dynamic_pointer_cast<EventWorkspace>(outputWS);
        if (inPlace)
        {
          g_log.debug() << "Rebinning event workspace in place\n";
        }
        else
        {
          g_log.debug() << "Rebinning event workspace in place\n";

          // copy the event workspace to a new EventWorkspace
          outputEventWS = boost::dynamic_pointer_cast<EventWorkspace>(
              API::WorkspaceFactory::Instance().create("EventWorkspace", inputWS->getNumberHistograms(), 2, 1));
          // copy geometry over.
          API::WorkspaceFactory::Instance().initializeFromParent(inputEventWS, outputEventWS, false);
          // copy over the data as well.
          outputEventWS->copyDataFrom( (*inputEventWS) );
        }

        // initialize progress reporting.
        Progress prog(this,0.0,1.0, numSpectra);

        // do the rebinning
        PARALLEL_FOR2(inputEventWS, outputWS)
        for (int wkspIndex = 0; wkspIndex < numSpectra; ++wkspIndex)
        {
          PARALLEL_START_INTERUPT_REGION
          MantidVec xValues;
          double delta = this->determineBinning(xValues, xmins[wkspIndex], xmaxs[wkspIndex]);
          g_log.debug() << "delta[wkspindex=" << wkspIndex << "] = " << delta << "\n";
          outputEventWS->getSpectrum(wkspIndex)->setX(xValues);
          prog.report(name()); //Report progress
          PARALLEL_END_INTERUPT_REGION
        }
        PARALLEL_CHECK_INTERUPT_REGION

        this->setProperty("OutputWorkspace", boost::dynamic_pointer_cast<MatrixWorkspace>(outputEventWS));
      } // end if (m_preserveEvents)
      else // event workspace -> matrix workspace
      {
        //--------- Different output, OR you're inplace but not preserving Events --- create a Workspace2D -------
        g_log.information() << "Creating a Workspace2D from the EventWorkspace " << inputEventWS->getName() << ".\n";

        //Create a Workspace2D
        // This creates a new Workspace2D through a torturous route using the WorkspaceFactory.
        // The Workspace2D is created with an EMPTY CONSTRUCTOR
        outputWS = WorkspaceFactory::Instance().create("Workspace2D",numSpectra,m_numBins,m_numBins-1);
        WorkspaceFactory::Instance().initializeFromParent(inputWS, outputWS, true);

        //Initialize progress reporting.
        Progress prog(this,0.0,1.0, numSpectra);

        //Go through all the histograms and set the data
        PARALLEL_FOR2(inputEventWS, outputWS)
        for (int wkspIndex=0; wkspIndex < numSpectra; ++wkspIndex)
        {
          PARALLEL_START_INTERUPT_REGION

          //Set the X axis for each output histogram
          MantidVec xValues;
          double delta = this->determineBinning(xValues, xmins[wkspIndex], xmaxs[wkspIndex]);
          g_log.debug() << "delta[wkspindex=" << wkspIndex << "] = " << delta << "\n";
          outputWS->setX(wkspIndex, xValues);

          //Get a const event list reference. inputEventWS->dataY() doesn't work.
          const EventList& el = inputEventWS->getEventList(wkspIndex);
          MantidVec y_data, e_data;
          // The EventList takes care of histogramming.
          el.generateHistogram(xValues, y_data, e_data);

          //Copy the data over.
          outputWS->dataY(wkspIndex).assign(y_data.begin(), y_data.end());
          outputWS->dataE(wkspIndex).assign(e_data.begin(), e_data.end());

          //Report progress
          prog.report(name());
          PARALLEL_END_INTERUPT_REGION
        }
        PARALLEL_CHECK_INTERUPT_REGION

        //Copy all the axes
        for (int i=1; i<inputWS->axes(); i++)
        {
          outputWS->replaceAxis( i, inputWS->getAxis(i)->clone(outputWS.get()) );
          outputWS->getAxis(i)->unit() = inputWS->getAxis(i)->unit();
        }

        //Copy the units over too.
        for (int i=0; i < outputWS->axes(); ++i)
          outputWS->getAxis(i)->unit() = inputWS->getAxis(i)->unit();
        outputWS->setYUnit(inputEventWS->YUnit());
        outputWS->setYUnitLabel(inputEventWS->YUnitLabel());

        // Assign it to the output workspace property
        setProperty("OutputWorkspace", outputWS);
      }
      return;
    }
コード例 #19
0
 void PropertyInt2ListControl::updateCaption()
 {
   PropertyPtr proper = getProperty();
   if (proper != nullptr)
     mName->setCaption(proper->getType()->getName());
 }
コード例 #20
0
/** Execute the algorithm.
 */
void VesuvioL1ThetaResolution::exec() {
  // Set up random number generator
  m_generator.seed(static_cast<boost::mt19937::result_type>(
      static_cast<int>(getProperty("Seed"))));

  // Load the instrument workspace
  loadInstrument();

  const std::string l1DistributionWsName = getPropertyValue("L1Distribution");
  const std::string thetaDistributionWsName =
      getPropertyValue("ThetaDistribution");
  const size_t numHist = m_instWorkspace->getNumberHistograms();
  const int numEvents = getProperty("NumEvents");

  // Create output workspace of resolution
  m_outputWorkspace =
      WorkspaceFactory::Instance().create("Workspace2D", 4, numHist, numHist);

  // Set vertical axis to statistic labels
  auto specAxis = new TextAxis(4);
  specAxis->setLabel(0, "l1_Mean");
  specAxis->setLabel(1, "l1_StdDev");
  specAxis->setLabel(2, "theta_Mean");
  specAxis->setLabel(3, "theta_StdDev");
  m_outputWorkspace->replaceAxis(1, specAxis);

  // Set X axis to spectrum numbers
  m_outputWorkspace->getAxis(0)->setUnit("Label");
  auto xAxis = boost::dynamic_pointer_cast<Units::Label>(
      m_outputWorkspace->getAxis(0)->unit());
  if (xAxis)
    xAxis->setLabel("Spectrum Number");

  // Create output workspaces for distributions if required
  if (!l1DistributionWsName.empty()) {
    m_l1DistributionWs = WorkspaceFactory::Instance().create(
        m_instWorkspace, numHist, numEvents, numEvents);

    // Set Y axis
    m_l1DistributionWs->setYUnitLabel("Events");

    // Set X axis
    auto xAxis = m_l1DistributionWs->getAxis(0);
    xAxis->setUnit("Label");
    auto labelUnit = boost::dynamic_pointer_cast<Units::Label>(xAxis->unit());
    if (labelUnit)
      labelUnit->setLabel("l1");
  }

  if (!thetaDistributionWsName.empty()) {
    m_thetaDistributionWs = WorkspaceFactory::Instance().create(
        m_instWorkspace, numHist, numEvents, numEvents);

    // Set Y axis
    m_thetaDistributionWs->setYUnitLabel("Events");

    // Set X axis
    auto xAxis = m_thetaDistributionWs->getAxis(0);
    xAxis->setUnit("Label");
    auto labelUnit = boost::dynamic_pointer_cast<Units::Label>(xAxis->unit());
    if (labelUnit)
      labelUnit->setLabel("theta");
  }

  // Set up progress reporting
  Progress prog(this, 0.0, 1.0, numHist);

  // Loop for all detectors
  for (size_t i = 0; i < numHist; i++) {
    std::vector<double> l1;
    std::vector<double> theta;
    IDetector_const_sptr det = m_instWorkspace->getDetector(i);

    // Report progress
    std::stringstream report;
    report << "Detector " << det->getID();
    prog.report(report.str());
    g_log.information() << "Detector ID " << det->getID() << '\n';

    // Do simulation
    calculateDetector(det, l1, theta);

    // Calculate statistics for L1 and theta
    Statistics l1Stats = getStatistics(l1);
    Statistics thetaStats = getStatistics(theta);

    g_log.information() << "l0: mean=" << l1Stats.mean
                        << ", std.dev.=" << l1Stats.standard_deviation
                        << "\ntheta: mean=" << thetaStats.mean
                        << ", std.dev.=" << thetaStats.standard_deviation
                        << '\n';

    // Set values in output workspace
    const int specNo = m_instWorkspace->getSpectrum(i).getSpectrumNo();
    m_outputWorkspace->dataX(0)[i] = specNo;
    m_outputWorkspace->dataX(1)[i] = specNo;
    m_outputWorkspace->dataX(2)[i] = specNo;
    m_outputWorkspace->dataX(3)[i] = specNo;
    m_outputWorkspace->dataY(0)[i] = l1Stats.mean;
    m_outputWorkspace->dataY(1)[i] = l1Stats.standard_deviation;
    m_outputWorkspace->dataY(2)[i] = thetaStats.mean;
    m_outputWorkspace->dataY(3)[i] = thetaStats.standard_deviation;

    // Process data for L1 distribution
    if (m_l1DistributionWs) {
      std::vector<double> &x = m_l1DistributionWs->dataX(i);
      std::vector<double> y(numEvents, 1.0);

      std::sort(l1.begin(), l1.end());
      std::copy(l1.begin(), l1.end(), x.begin());

      m_l1DistributionWs->dataY(i) = y;

      auto &spec = m_l1DistributionWs->getSpectrum(i);
      spec.setSpectrumNo(specNo);
      spec.addDetectorID(det->getID());
    }

    // Process data for theta distribution
    if (m_thetaDistributionWs) {
      std::vector<double> &x = m_thetaDistributionWs->dataX(i);
      std::vector<double> y(numEvents, 1.0);

      std::sort(theta.begin(), theta.end());
      std::copy(theta.begin(), theta.end(), x.begin());

      m_thetaDistributionWs->dataY(i) = y;

      auto &spec = m_thetaDistributionWs->getSpectrum(i);
      spec.setSpectrumNo(specNo);
      spec.addDetectorID(det->getID());
    }
  }

  // Process the L1 distribution workspace
  if (m_l1DistributionWs) {
    const double binWidth = getProperty("L1BinWidth");
    setProperty("L1Distribution",
                processDistribution(m_l1DistributionWs, binWidth));
  }

  // Process the theta distribution workspace
  if (m_thetaDistributionWs) {
    const double binWidth = getProperty("ThetaBinWidth");
    setProperty("ThetaDistribution",
                processDistribution(m_thetaDistributionWs, binWidth));
  }

  setProperty("OutputWorkspace", m_outputWorkspace);
}
コード例 #21
0
ファイル: LoadNexusLogs.cpp プロジェクト: dezed/mantid
/** Executes the algorithm. Reading in the file and creating and populating
*  the output workspace
*
*  @throw Exception::FileError If the Nexus file cannot be found/opened
*  @throw std::invalid_argument If the optional properties are set to invalid
*values
*/
void LoadNexusLogs::exec() {
  std::string filename = getPropertyValue("Filename");
  MatrixWorkspace_sptr workspace = getProperty("Workspace");

  // Find the entry name to use (normally "entry" for SNS, "raw_data_1" for
  // ISIS)
  std::string entry_name = LoadTOFRawNexus::getEntryName(filename);

  ::NeXus::File file(filename);
  // Find the root entry
  try {
    file.openGroup(entry_name, "NXentry");
  } catch (::NeXus::Exception &) {
    throw std::invalid_argument("Unknown NeXus file format found in file '" +
                                filename + "'");
  }

  /// Use frequency start for Monitor19 and Special1_19 logs with "No Time" for
  /// SNAP
  try {
    file.openPath("DASlogs");
    try {
      file.openGroup("frequency", "NXlog");
      try {
        file.openData("time");

        //----- Start time is an ISO8601 string date and time. ------
        try {
          file.getAttr("start", freqStart);

        } catch (::NeXus::Exception &) {
          // Some logs have "offset" instead of start
          try {
            file.getAttr("offset", freqStart);
          } catch (::NeXus::Exception &) {
            g_log.warning() << "Log entry has no start time indicated.\n";
            file.closeData();
            throw;
          }
        }
        file.closeData();
      } catch (::NeXus::Exception &) {
        // No time. This is not an SNS SNAP file
      }
      file.closeGroup();
    } catch (::NeXus::Exception &) {
      // No time. This is not an SNS frequency group
    }
    file.closeGroup();
  } catch (::NeXus::Exception &) {
    // No time. This is not an SNS group
  }
  // print out the entry level fields
  std::map<std::string, std::string> entries = file.getEntries();
  std::map<std::string, std::string>::const_iterator iend = entries.end();
  for (std::map<std::string, std::string>::const_iterator it = entries.begin();
       it != iend; ++it) {
    std::string group_name(it->first);
    std::string group_class(it->second);
    if (group_name == "DASlogs" || group_class == "IXrunlog" ||
        group_class == "IXselog" || group_name == "framelog") {
      loadLogs(file, group_name, group_class, workspace);
    }
    if (group_class == "IXperiods") {
      loadNPeriods(file, workspace);
    }
  }

  // If there's measurement information, load that info as logs.
  loadAndApplyMeasurementInfo(&file, *workspace);

  // Freddie Akeroyd 12/10/2011
  // current ISIS implementation contains an additional indirection between
  // collected frames via an
  // "event_frame_number" array in NXevent_data (which eliminates frames with no
  // events).
  // the proton_log is for all frames and so is longer than the event_index
  // array, so we need to
  // filter the proton_charge log based on event_frame_number
  // This difference will be removed in future for compatibility with SNS, but
  // the code below will allow current SANS2D files to load
  if (workspace->mutableRun().hasProperty("proton_log")) {
    std::vector<int> event_frame_number;
    this->getLogger().notice()
        << "Using old ISIS proton_log and event_frame_number indirection..."
        << std::endl;
    try {
      // Find the bank/name corresponding to the first event data entry, i.e.
      // one with type NXevent_data.
      file.openPath("/" + entry_name);
      std::map<std::string, std::string> entries = file.getEntries();
      std::map<std::string, std::string>::const_iterator it = entries.begin();
      std::string eventEntry;
      for (; it != entries.end(); ++it) {
        if (it->second == "NXevent_data") {
          eventEntry = it->first;
          break;
        }
      }
      this->getLogger().debug()
          << "Opening"
          << " /" + entry_name + "/" + eventEntry + "/event_frame_number"
          << " to find the event_frame_number\n";
      file.openPath("/" + entry_name + "/" + eventEntry +
                    "/event_frame_number");
      file.getData(event_frame_number);
    } catch (const ::NeXus::Exception &) {
      this->getLogger().warning() << "Unable to load event_frame_number - "
                                     "filtering events by time will not work "
                                  << std::endl;
    }
    file.openPath("/" + entry_name);
    if (!event_frame_number.empty()) // ISIS indirection - see above comments
    {
      Kernel::TimeSeriesProperty<double> *plog =
          dynamic_cast<Kernel::TimeSeriesProperty<double> *>(
              workspace->mutableRun().getProperty("proton_log"));
      if (!plog)
        throw std::runtime_error(
            "Could not cast (interpret) proton_log as a time "
            "series property. Cannot continue.");
      Kernel::TimeSeriesProperty<double> *pcharge =
          new Kernel::TimeSeriesProperty<double>("proton_charge");
      std::vector<double> pval;
      std::vector<Mantid::Kernel::DateAndTime> ptime;
      pval.reserve(event_frame_number.size());
      ptime.reserve(event_frame_number.size());
      std::vector<Mantid::Kernel::DateAndTime> plogt = plog->timesAsVector();
      std::vector<double> plogv = plog->valuesAsVector();
      for (auto number : event_frame_number) {
        ptime.push_back(plogt[number]);
        pval.push_back(plogv[number]);
      }
      pcharge->create(ptime, pval);
      pcharge->setUnits("uAh");
      workspace->mutableRun().addProperty(pcharge, true);
    }
  }
  try {
    // Read the start and end time strings
    file.openData("start_time");
    Kernel::DateAndTime start(file.getStrData());
    file.closeData();
    file.openData("end_time");
    Kernel::DateAndTime end(file.getStrData());
    file.closeData();
    workspace->mutableRun().setStartAndEndTime(start, end);
  } catch (::NeXus::Exception &) {
  }

  if (!workspace->run().hasProperty("gd_prtn_chrg")) {
    // Try pulling it from the main proton_charge entry first
    try {
      file.openData("proton_charge");
      std::vector<double> values;
      file.getDataCoerce(values);
      std::string units;
      file.getAttr("units", units);
      double charge = values.front();
      if (units.find("picoCoulomb") != std::string::npos) {
        charge *= 1.e-06 / 3600.;
      }
      workspace->mutableRun().setProtonCharge(charge);
    } catch (::NeXus::Exception &) {
      // Try and integrate the proton logs
      try {
        // Use the DAS logs to integrate the proton charge (if any).
        workspace->mutableRun().getProtonCharge();
      } catch (Exception::NotFoundError &) {
        // Ignore not found property error.
      }
    }
  }

  // Close the file
  file.close();
}
コード例 #22
0
/** Loads the instrument into a workspace.
 */
void VesuvioL1ThetaResolution::loadInstrument() {
  // Get the filename for the VESUVIO IDF
  MatrixWorkspace_sptr tempWS =
      WorkspaceFactory::Instance().create("Workspace2D", 1, 1, 1);
  const std::string vesuvioIPF = tempWS->getInstrumentFilename("VESUVIO");

  // Load an empty VESUVIO instrument workspace
  IAlgorithm_sptr loadInst =
      AlgorithmManager::Instance().create("LoadEmptyInstrument");
  loadInst->initialize();
  loadInst->setChild(true);
  loadInst->setLogging(false);
  loadInst->setProperty("OutputWorkspace", "__evs");
  loadInst->setProperty("Filename", vesuvioIPF);
  loadInst->execute();
  m_instWorkspace = loadInst->getProperty("OutputWorkspace");

  // Load the PAR file if provided
  const std::string parFilename = getPropertyValue("PARFile");
  if (!parFilename.empty()) {
    g_log.information() << "Loading PAR file: " << parFilename << '\n';

    // Get header format
    std::map<size_t, std::string> headerFormats;
    headerFormats[5] = "spectrum,theta,t0,-,R";
    headerFormats[6] = "spectrum,-,theta,t0,-,R";

    std::ifstream parFile(parFilename);
    if (!parFile) {
      throw std::runtime_error("Cannot open PAR file");
    }
    std::string header;
    getline(parFile, header);
    g_log.debug() << "PAR file header: " << header << '\n';
    boost::trim(header);
    std::vector<std::string> headers;
    boost::split(headers, header, boost::is_any_of("\t "),
                 boost::token_compress_on);
    size_t numCols = headers.size();
    g_log.debug() << "PAR file columns: " << numCols << '\n';

    std::string headerFormat = headerFormats[numCols];
    if (headerFormat.empty()) {
      std::stringstream error;
      error << "Unrecognised PAR file header. Number of colums: " << numCols
            << " (expected either 5 or 6.";
      throw std::runtime_error(error.str());
    }
    g_log.debug() << "PAR file header format: " << headerFormat << '\n';

    // Update instrument
    IAlgorithm_sptr updateInst =
        AlgorithmManager::Instance().create("UpdateInstrumentFromFile");
    updateInst->initialize();
    updateInst->setChild(true);
    updateInst->setLogging(false);
    updateInst->setProperty("Workspace", m_instWorkspace);
    updateInst->setProperty("Filename", parFilename);
    updateInst->setProperty("MoveMonitors", false);
    updateInst->setProperty("IgnorePhi", true);
    updateInst->setProperty("AsciiHeader", headerFormat);
    updateInst->execute();
    m_instWorkspace = updateInst->getProperty("Workspace");
  }

  const int specIdxMin = static_cast<int>(
      m_instWorkspace->getIndexFromSpectrumNumber(getProperty("SpectrumMin")));
  const int specIdxMax = static_cast<int>(
      m_instWorkspace->getIndexFromSpectrumNumber(getProperty("SpectrumMax")));

  // Crop the workspace to just the detectors we are interested in
  IAlgorithm_sptr crop = AlgorithmManager::Instance().create("CropWorkspace");
  crop->initialize();
  crop->setChild(true);
  crop->setLogging(false);
  crop->setProperty("InputWorkspace", m_instWorkspace);
  crop->setProperty("OutputWorkspace", "__evs");
  crop->setProperty("StartWorkspaceIndex", specIdxMin);
  crop->setProperty("EndWorkspaceIndex", specIdxMax);
  crop->execute();
  m_instWorkspace = crop->getProperty("OutputWorkspace");

  m_sample = m_instWorkspace->getInstrument()->getSample();
}
コード例 #23
0
ファイル: Load.cpp プロジェクト: peterfpeterson/mantid
void Load::loadMultipleFiles() {
  // allFilenames contains "rows" of filenames. If the row has more than 1 file
  // in it
  // then that row is to be summed across each file in the row
  const std::vector<std::vector<std::string>> allFilenames =
      getProperty("Filename");
  std::string outputWsName = getProperty("OutputWorkspace");

  std::vector<std::string> wsNames(allFilenames.size());
  std::transform(allFilenames.begin(), allFilenames.end(), wsNames.begin(),
                 generateWsNameFromFileNames);

  auto wsName = wsNames.cbegin();
  assert(allFilenames.size() == wsNames.size());

  std::vector<API::Workspace_sptr> loadedWsList;
  loadedWsList.reserve(allFilenames.size());

  Workspace_sptr tempWs;

  // Cycle through the filenames and wsNames.
  for (auto filenames = allFilenames.cbegin(); filenames != allFilenames.cend();
       ++filenames, ++wsName) {
    auto filename = filenames->cbegin();
    Workspace_sptr sumWS = loadFileToWs(*filename, *wsName);

    ++filename;
    for (; filename != filenames->cend(); ++filename) {
      tempWs = loadFileToWs(*filename, "__@loadsum_temp@");
      sumWS = plusWs(sumWS, tempWs);
    }

    API::WorkspaceGroup_sptr group =
        boost::dynamic_pointer_cast<WorkspaceGroup>(sumWS);
    if (group) {
      std::vector<std::string> childWsNames = group->getNames();
      auto childWsName = childWsNames.begin();
      size_t count = 1;
      for (; childWsName != childWsNames.end(); ++childWsName, ++count) {
        Workspace_sptr childWs = group->getItem(*childWsName);
        const std::string childName =
            group->getName() + "_" + std::to_string(count);
        API::AnalysisDataService::Instance().addOrReplace(childName, childWs);
        // childWs->setName(group->getName() + "_" +
        // boost::lexical_cast<std::string>(count));
      }
    }
    // Add the sum to the list of loaded workspace names.
    loadedWsList.push_back(sumWS);
  }

  // If we only have one loaded ws, set it as the output.
  if (loadedWsList.size() == 1) {
    setProperty("OutputWorkspace", loadedWsList[0]);
    AnalysisDataService::Instance().rename(loadedWsList[0]->getName(),
                                           outputWsName);
  }
  // Else we have multiple loaded workspaces - group them and set the group as
  // output.
  else {
    API::WorkspaceGroup_sptr group = groupWsList(loadedWsList);
    setProperty("OutputWorkspace", group);

    std::vector<std::string> childWsNames = group->getNames();
    size_t count = 1;
    for (auto &childWsName : childWsNames) {
      if (childWsName == outputWsName) {
        Mantid::API::Workspace_sptr child = group->getItem(childWsName);
        // child->setName(child->getName() + "_" +
        // boost::lexical_cast<std::string>(count));
        const std::string childName =
            child->getName() + "_" + std::to_string(count);
        API::AnalysisDataService::Instance().addOrReplace(childName, child);
        count++;
      }
    }

    childWsNames = group->getNames();
    count = 1;
    for (auto &childWsName : childWsNames) {
      Workspace_sptr childWs = group->getItem(childWsName);
      std::string outWsPropName = "OutputWorkspace_" + std::to_string(count);
      ++count;
      declareProperty(Kernel::make_unique<WorkspaceProperty<Workspace>>(
          outWsPropName, childWsName, Direction::Output));
      setProperty(outWsPropName, childWs);
    }
  }

  // Clean up.
  if (tempWs) {
    Algorithm_sptr alg =
        AlgorithmManager::Instance().createUnmanaged("DeleteWorkspace");
    alg->initialize();
    alg->setChild(true);
    alg->setProperty("Workspace", tempWs);
    alg->execute();
  }
}
コード例 #24
0
/** Loads the instrument into a workspace.
 */
void VesuvioL1ThetaResolution::calculateDetector(
    IDetector_const_sptr detector, std::vector<double> &l1Values,
    std::vector<double> &thetaValues) {
  const int numEvents = getProperty("NumEvents");
  l1Values.reserve(numEvents);
  thetaValues.reserve(numEvents);

  double sampleWidth = getProperty("SampleWidth");
  // If the sample is large fix the width to the approximate beam width
  if (sampleWidth > 4.0)
    sampleWidth = 4.0;

  // Get detector dimensions
  Geometry::Object_const_sptr pixelShape = detector->shape();
  if (!pixelShape || !pixelShape->hasValidShape()) {
    throw std::invalid_argument("Detector pixel has no defined shape!");
  }
  Geometry::BoundingBox detBounds = pixelShape->getBoundingBox();
  V3D detBoxWidth = detBounds.width();
  const double detWidth = detBoxWidth.X() * 100;
  const double detHeight = detBoxWidth.Y() * 100;

  g_log.debug() << "detWidth=" << detWidth << "\ndetHeight=" << detHeight
                << '\n';

  // Scattering angle in rad
  const double theta = m_instWorkspace->detectorTwoTheta(*detector);
  if (theta == 0.0)
    return;

  // Final flight path in cm
  const double l1av = detector->getDistance(*m_sample) * 100.0;

  const double x0 = l1av * sin(theta);
  const double y0 = l1av * cos(theta);

  // Get as many events as defined by NumEvents
  // This loop is not iteration limited but highly unlikely to ever become
  // infinate
  while (l1Values.size() < static_cast<size_t>(numEvents)) {
    const double xs = -sampleWidth / 2 + sampleWidth * random();
    const double ys = 0.0;
    const double zs = -sampleWidth / 2 + sampleWidth * random();
    const double rs = sqrt(pow(xs, 2) + pow(zs, 2));

    if (rs <= sampleWidth / 2) {
      const double a = -detWidth / 2 + detWidth * random();
      const double xd = x0 - a * cos(theta);
      const double yd = y0 + a * sin(theta);
      const double zd = -detHeight / 2 + detHeight * random();

      const double l1 =
          sqrt(pow(xd - xs, 2) + pow(yd - ys, 2) + pow(zd - zs, 2));
      double angle = acos(yd / l1);

      if (xd < 0.0)
        angle *= -1;

      // Convert angle to degrees
      angle *= 180.0 / M_PI;

      l1Values.push_back(l1);
      thetaValues.push_back(angle);
    }

    interruption_point();
  }
}
コード例 #25
0
/** Execute the algorithm.
 */
void CreateGroupingWorkspace::exec() {
  MatrixWorkspace_sptr inWS = getProperty("InputWorkspace");
  std::string InstrumentName = getPropertyValue("InstrumentName");
  std::string InstrumentFilename = getPropertyValue("InstrumentFilename");
  std::string OldCalFilename = getPropertyValue("OldCalFilename");
  std::string GroupNames = getPropertyValue("GroupNames");
  std::string grouping = getPropertyValue("GroupDetectorsBy");
  int numGroups = getProperty("FixedGroupCount");
  std::string componentName = getPropertyValue("ComponentName");

  // Some validation
  int numParams = 0;
  if (inWS)
    numParams++;
  if (!InstrumentName.empty())
    numParams++;
  if (!InstrumentFilename.empty())
    numParams++;

  if (numParams > 1)
    throw std::invalid_argument("You must specify exactly ONE way to get an "
                                "instrument (workspace, instrument name, or "
                                "IDF file). You specified more than one.");
  if (numParams == 0)
    throw std::invalid_argument("You must specify exactly ONE way to get an "
                                "instrument (workspace, instrument name, or "
                                "IDF file). You specified none.");

  if (!OldCalFilename.empty() && !GroupNames.empty())
    throw std::invalid_argument("You must specify either to use the "
                                "OldCalFilename parameter OR GroupNames but "
                                "not both!");

  bool sortnames = false;

  // ---------- Get the instrument one of 3 ways ---------------------------
  Instrument_const_sptr inst;
  if (inWS) {
    inst = inWS->getInstrument();
  } else {
    Algorithm_sptr childAlg = createChildAlgorithm("LoadInstrument", 0.0, 0.2);
    MatrixWorkspace_sptr tempWS = boost::make_shared<Workspace2D>();
    childAlg->setProperty<MatrixWorkspace_sptr>("Workspace", tempWS);
    childAlg->setPropertyValue("Filename", InstrumentFilename);
    childAlg->setProperty("RewriteSpectraMap",
                          Mantid::Kernel::OptionalBool(true));
    childAlg->setPropertyValue("InstrumentName", InstrumentName);
    childAlg->executeAsChildAlg();
    inst = tempWS->getInstrument();
  }

  if (GroupNames.empty() && OldCalFilename.empty()) {
    if (grouping.compare("All") == 0) {
      GroupNames = inst->getName();
    } else if (inst->getName().compare("SNAP") == 0 &&
               grouping.compare("Group") == 0) {
      GroupNames = "East,West";
    } else {
      sortnames = true;
      GroupNames = "";
      int maxRecurseDepth = this->getProperty("MaxRecursionDepth");

      // cppcheck-suppress syntaxError
          PRAGMA_OMP(parallel for schedule(dynamic, 1) )
          for (int num = 0; num < 300; ++num) {
            PARALLEL_START_INTERUPT_REGION
            std::ostringstream mess;
            mess << grouping << num;
            IComponent_const_sptr comp =
                inst->getComponentByName(mess.str(), maxRecurseDepth);
            PARALLEL_CRITICAL(GroupNames)
            if (comp)
              GroupNames += mess.str() + ",";
            PARALLEL_END_INTERUPT_REGION
          }
          PARALLEL_CHECK_INTERUPT_REGION
    }
  }

  // --------------------------- Create the output --------------------------
  auto outWS = boost::make_shared<GroupingWorkspace>(inst);
  this->setProperty("OutputWorkspace", outWS);

  // This will get the grouping
  std::map<detid_t, int> detIDtoGroup;

  Progress prog(this, 0.2, 1.0, outWS->getNumberHistograms());
  // Make the grouping one of three ways:
  if (!GroupNames.empty())
    detIDtoGroup = makeGroupingByNames(GroupNames, inst, prog, sortnames);
  else if (!OldCalFilename.empty())
    detIDtoGroup = readGroupingFile(OldCalFilename, prog);
  else if ((numGroups > 0) && !componentName.empty())
    detIDtoGroup =
        makeGroupingByNumGroups(componentName, numGroups, inst, prog);

  g_log.information() << detIDtoGroup.size()
                      << " entries in the detectorID-to-group map.\n";
  setProperty("NumberGroupedSpectraResult",
              static_cast<int>(detIDtoGroup.size()));

  if (detIDtoGroup.empty()) {
    g_log.warning() << "Creating empty group workspace\n";
    setProperty("NumberGroupsResult", static_cast<int>(0));
  } else {
    size_t numNotFound = 0;

    // Make the groups, if any
    std::map<detid_t, int>::const_iterator it_end = detIDtoGroup.end();
    std::map<detid_t, int>::const_iterator it;
    std::unordered_set<int> groupCount;
    for (it = detIDtoGroup.begin(); it != it_end; ++it) {
      int detID = it->first;
      int group = it->second;
      groupCount.insert(group);
      try {
        outWS->setValue(detID, double(group));
      } catch (std::invalid_argument &) {
        numNotFound++;
      }
    }
    setProperty("NumberGroupsResult", static_cast<int>(groupCount.size()));

    if (numNotFound > 0)
      g_log.warning() << numNotFound << " detector IDs (out of "
                      << detIDtoGroup.size()
                      << ") were not found in the instrument\n.";
  }
}
コード例 #26
0
/** Execute the algorithm.
 */
void ImportMDEventWorkspace::exec() {
  std::string filename = getProperty("Filename");

  std::ifstream file;
  try {
    file.open(filename.c_str(), std::ios::in);
  } catch (std::ifstream::failure &e) {
    g_log.error() << "Cannot open file: " << filename;
    throw(e);
  }

  // Extract data from the file, excluding comment lines.
  std::string line;
  std::string lastLine;
  size_t nActualColumns = 0;
  while (std::getline(file, line)) {
    boost::algorithm::trim(line);
    if (std::string::npos == line.find_first_of(CommentLineStartFlag())) {
      std::stringstream buffer(line);
      std::copy(std::istream_iterator<std::string>(buffer),
                std::istream_iterator<std::string>(),
                std::back_inserter(m_file_data));

      if (lastLine == MDEventBlockFlag()) {
        std::vector<std::string> strVec;
        boost::algorithm::split(strVec, line, boost::is_any_of("\t "),
                                boost::token_compress_on);
        nActualColumns = strVec.size();
      }
    }
    lastLine = line;
  }

  file.close();

  // Check the file format.
  quickFileCheck();

  // Extract some well used posisions
  m_posDimStart =
      std::find(m_file_data.begin(), m_file_data.end(), DimensionBlockFlag());
  m_posMDEventStart =
      std::find(m_file_data.begin(), m_file_data.end(), MDEventBlockFlag());

  // Calculate the dimensionality
  int posDiffDims =
      static_cast<int>(std::distance(m_posDimStart, m_posMDEventStart));
  m_nDimensions = (posDiffDims - 1) / 4;

  // Calculate the actual number of columns in the MDEvent data.
  int posDiffMDEvent =
      static_cast<int>(std::distance(m_posMDEventStart, m_file_data.end()));
  const size_t columnsForFullEvents =
      m_nDimensions + 4; // signal, error, run_no, detector_no
  m_IsFullDataObjects = (nActualColumns == columnsForFullEvents);

  if (0 == nActualColumns) {
    m_nDataObjects = 0;
    g_log.warning() << "The number of actual columns found in the file "
                       "(exlcuding comments) is zero" << std::endl;
  } else {
    m_nDataObjects = posDiffMDEvent / nActualColumns;
  }

  // Get the min and max extents in each dimension.
  std::vector<double> extentMins(m_nDimensions);
  std::vector<double> extentMaxs(m_nDimensions);
  DataCollectionType::iterator mdEventEntriesIterator = m_posMDEventStart;
  for (size_t i = 0; i < m_nDataObjects; ++i) {
    mdEventEntriesIterator += 2;
    if (m_IsFullDataObjects) {
      mdEventEntriesIterator += 2;
    }
    for (size_t j = 0; j < m_nDimensions; ++j) {
      double coord = convert<double>(*(++mdEventEntriesIterator));
      extentMins[j] = coord < extentMins[j] ? coord : extentMins[j];
      extentMaxs[j] = coord > extentMaxs[j] ? coord : extentMaxs[j];
    }
  }

  // Create a target output workspace.
  IMDEventWorkspace_sptr outWs = MDEventFactory::CreateMDWorkspace(
      m_nDimensions, m_IsFullDataObjects ? "MDEvent" : "MDLeanEvent");

  // Extract Dimensions and add to the output workspace.
  DataCollectionType::iterator dimEntriesIterator = m_posDimStart;
  auto unitFactory = makeMDUnitFactoryChain();
  for (size_t i = 0; i < m_nDimensions; ++i) {
    std::string id = convert<std::string>(*(++dimEntriesIterator));
    std::string name = convert<std::string>(*(++dimEntriesIterator));
    std::string units = convert<std::string>(*(++dimEntriesIterator));
    int nbins = convert<int>(*(++dimEntriesIterator));

    auto mdUnit = unitFactory->create(units);
    Mantid::Geometry::GeneralFrame frame(
        Mantid::Geometry::GeneralFrame::GeneralFrameName, std::move(mdUnit));
    outWs->addDimension(MDHistoDimension_sptr(new MDHistoDimension(
        id, name, frame, static_cast<coord_t>(extentMins[i]),
        static_cast<coord_t>(extentMaxs[i]), nbins)));
  }

  CALL_MDEVENT_FUNCTION(this->addEventsData, outWs)

  // set output
  this->setProperty("OutputWorkspace", outWs);
}
コード例 #27
0
ファイル: camera_activity.cpp プロジェクト: 112000/opencv
int CameraActivity::getFrameWidth()
{
    if (frameWidth <= 0)
        frameWidth = getProperty(ANDROID_CAMERA_PROPERTY_FRAMEWIDTH);
    return frameWidth;
}
コード例 #28
0
ファイル: ResampleX.cpp プロジェクト: mantidproject/mantid
/** Execute the algorithm.
 */
void ResampleX::exec() {
  // generically having access to the input workspace is a good idea
  MatrixWorkspace_sptr inputWS = getProperty("InputWorkspace");
  MatrixWorkspace_sptr outputWS = getProperty("OutputWorkspace");
  bool inPlace = (inputWS == outputWS); // Rebinning in-place
  m_isDistribution = inputWS->isDistribution();
  m_isHistogram = inputWS->isHistogramData();
  const int numSpectra = static_cast<int>(inputWS->getNumberHistograms());

  // the easy parameters
  m_useLogBinning = getProperty("LogBinning");
  m_numBins = getProperty("NumberBins");
  m_preserveEvents = getProperty("PreserveEvents");

  // determine the xmin/xmax for the workspace
  vector<double> xmins = getProperty("XMin");
  vector<double> xmaxs = getProperty("XMax");
  string error = determineXMinMax(inputWS, xmins, xmaxs);
  if (!error.empty())
    throw std::runtime_error(error);

  bool common_limits = true;
  {
    double xmin_common = xmins[0];
    double xmax_common = xmaxs[0];
    for (size_t i = 1; i < xmins.size(); ++i) {
      if (xmins[i] != xmin_common) {
        common_limits = false;
        break;
      }
      if (xmaxs[i] != xmax_common) {
        common_limits = false;
        break;
      }
    }
  }
  if (common_limits) {
    g_log.debug() << "Common limits between all spectra\n";
  } else {
    g_log.debug() << "Does not have common limits between all spectra\n";
  }

  // start doing actual work
  EventWorkspace_const_sptr inputEventWS =
      boost::dynamic_pointer_cast<const EventWorkspace>(inputWS);
  if (inputEventWS != nullptr) {
    if (m_preserveEvents) {
      if (inPlace) {
        g_log.debug() << "Rebinning event workspace in place\n";
      } else {
        g_log.debug() << "Rebinning event workspace out of place\n";
        outputWS = inputWS->clone();
      }
      auto outputEventWS =
          boost::dynamic_pointer_cast<EventWorkspace>(outputWS);

      if (common_limits) {
        // get the delta from the first since they are all the same
        BinEdges xValues(0);
        const double delta = this->determineBinning(xValues.mutableRawData(),
                                                    xmins[0], xmaxs[0]);
        g_log.debug() << "delta = " << delta << "\n";
        outputEventWS->setAllX(xValues);
      } else {
        // initialize progress reporting.
        Progress prog(this, 0.0, 1.0, numSpectra);

        // do the rebinning
        PARALLEL_FOR_IF(Kernel::threadSafe(*inputEventWS, *outputWS))
        for (int wkspIndex = 0; wkspIndex < numSpectra; ++wkspIndex) {
          PARALLEL_START_INTERUPT_REGION
          BinEdges xValues(0);
          const double delta = this->determineBinning(
              xValues.mutableRawData(), xmins[wkspIndex], xmaxs[wkspIndex]);
          g_log.debug() << "delta[wkspindex=" << wkspIndex << "] = " << delta
                        << " xmin=" << xmins[wkspIndex]
                        << " xmax=" << xmaxs[wkspIndex] << "\n";
          outputEventWS->setHistogram(wkspIndex, xValues);
          prog.report(name()); // Report progress
          PARALLEL_END_INTERUPT_REGION
        }
        PARALLEL_CHECK_INTERUPT_REGION
      }
    }    // end if (m_preserveEvents)
    else // event workspace -> matrix workspace
    {
      //--------- Different output, OR you're inplace but not preserving Events
      g_log.information() << "Creating a Workspace2D from the EventWorkspace "
                          << inputEventWS->getName() << ".\n";
      outputWS = create<DataObjects::Workspace2D>(
          *inputWS, numSpectra, HistogramData::BinEdges(m_numBins + 1));

      // Initialize progress reporting.
      Progress prog(this, 0.0, 1.0, numSpectra);

      // Go through all the histograms and set the data
      PARALLEL_FOR_IF(Kernel::threadSafe(*inputEventWS, *outputWS))
      for (int wkspIndex = 0; wkspIndex < numSpectra; ++wkspIndex) {
        PARALLEL_START_INTERUPT_REGION

        // Set the X axis for each output histogram
        MantidVec xValues;
        const double delta =
            this->determineBinning(xValues, xmins[wkspIndex], xmaxs[wkspIndex]);
        g_log.debug() << "delta[wkspindex=" << wkspIndex << "] = " << delta
                      << "\n";
        outputWS->setBinEdges(wkspIndex, xValues);

        // Get a const event list reference. inputEventWS->dataY() doesn't work.
        const EventList &el = inputEventWS->getSpectrum(wkspIndex);
        MantidVec y_data, e_data;
        // The EventList takes care of histogramming.
        el.generateHistogram(xValues, y_data, e_data);

        // Copy the data over.
        outputWS->mutableY(wkspIndex) = std::move(y_data);
        outputWS->mutableE(wkspIndex) = std::move(e_data);

        // Report progress
        prog.report(name());
        PARALLEL_END_INTERUPT_REGION
      }
      PARALLEL_CHECK_INTERUPT_REGION

      // Copy all the axes
      for (int i = 1; i < inputWS->axes(); i++) {
        outputWS->replaceAxis(i, inputWS->getAxis(i)->clone(outputWS.get()));
        outputWS->getAxis(i)->unit() = inputWS->getAxis(i)->unit();
      }

      // Copy the units over too.
      for (int i = 0; i < outputWS->axes(); ++i) {
        outputWS->getAxis(i)->unit() = inputWS->getAxis(i)->unit();
      }
      outputWS->setYUnit(inputEventWS->YUnit());
      outputWS->setYUnitLabel(inputEventWS->YUnitLabel());
    }
    // Assign it to the output workspace property
    setProperty("OutputWorkspace", outputWS);
    return;
  } else // (inputeventWS != NULL)
コード例 #29
0
UT_Error OXML_Element_Run::serializeProperties(IE_Exp_OpenXML* exporter)
{
	//TODO: Add all the property serializations here
	UT_Error err = UT_OK;
	const gchar* szValue = NULL;

	err = exporter->startRunProperties(TARGET);
	if(err != UT_OK)
		return err;

	if(getProperty("lang", szValue) == UT_OK)
	{
		if(!strcmp(szValue, "-none-"))
			err = exporter->setNoProof(TARGET);
		else
			err = exporter->setLanguage(TARGET, szValue);
		if(err != UT_OK)
			return err;
	}

	if(getProperty("font-family", szValue) == UT_OK)
	{
		err = exporter->setFontFamily(TARGET, szValue);
		if(err != UT_OK)
			return err;
	}

	if(getProperty("font-weight", szValue) == UT_OK)
	{
		if(!strcmp(szValue, "bold"))
		{
			err = exporter->setBold(TARGET);
			if(err != UT_OK)
				return err;
		}
	}

	if(getProperty("font-style", szValue) == UT_OK)
	{
		if(!strcmp(szValue, "italic"))
		{
			err = exporter->setItalic(TARGET);
			if(err != UT_OK)
				return err;
		}
	}

	if(getProperty("font-size", szValue) == UT_OK)
	{
		err = exporter->setFontSize(TARGET, szValue);
		if(err != UT_OK)
			return err;
	}
	
	if(getProperty("text-decoration", szValue) == UT_OK)
	{
		if(strstr(szValue, "underline"))
		{
			err = exporter->setUnderline(TARGET);
			if(err != UT_OK)
				return err;
		}

		if(strstr(szValue, "overline"))
		{
			err = exporter->setOverline(TARGET);
			if(err != UT_OK)
				return err;
		}

		if(strstr(szValue, "line-through"))
		{
			err = exporter->setLineThrough(TARGET);
			if(err != UT_OK)
				return err;
		}
	}

	if(getProperty("text-position", szValue) == UT_OK)
	{
		if(!strcmp(szValue, "superscript"))
		{
			err = exporter->setSuperscript(TARGET);
			if(err != UT_OK)
				return err;
		}

		else if(!strcmp(szValue, "subscript"))
		{
			err = exporter->setSubscript(TARGET);
			if(err != UT_OK)
				return err;
		}
	}

	if(getProperty("color", szValue) == UT_OK)
	{
		err = exporter->setTextColor(TARGET, szValue);
		if(err != UT_OK)
			return err;
	}

	if(getProperty("bgcolor", szValue) == UT_OK)
	{
		err = exporter->setBackgroundColor(TARGET, szValue);
		if(err != UT_OK)
			return err;
	}

	if(getProperty("dir-override", szValue) == UT_OK)
	{
		err = exporter->setTextDirection(TARGET, szValue);
		if(err != UT_OK)
			return err;
	}

	return exporter->finishRunProperties(TARGET);
}
コード例 #30
0
ファイル: ModeratorTzero.cpp プロジェクト: DanNixon/mantid
void ModeratorTzero::execEvent(const std::string &emode) {
  g_log.information("Processing event workspace");

  const MatrixWorkspace_const_sptr matrixInputWS =
      getProperty("InputWorkspace");

  // generate the output workspace pointer
  API::MatrixWorkspace_sptr matrixOutputWS = getProperty("OutputWorkspace");
  if (matrixOutputWS != matrixInputWS) {
    matrixOutputWS = matrixInputWS->clone();
    setProperty("OutputWorkspace", matrixOutputWS);
  }
  auto outputWS = boost::dynamic_pointer_cast<EventWorkspace>(matrixOutputWS);

  // calculate tof shift once for all neutrons if emode==Direct
  double t0_direct(-1);
  if (emode == "Direct") {
    Kernel::Property *eiprop = outputWS->run().getProperty("Ei");
    double Ei = boost::lexical_cast<double>(eiprop->value());
    mu::Parser parser;
    parser.DefineVar("incidentEnergy", &Ei); // associate E1 to this parser
    parser.SetExpr(m_formula);
    t0_direct = parser.Eval();
  }

  const auto &spectrumInfo = outputWS->spectrumInfo();
  const double Lss = spectrumInfo.l1();

  // Loop over the spectra
  const size_t numHists = static_cast<size_t>(outputWS->getNumberHistograms());
  Progress prog(this, 0.0, 1.0, numHists); // report progress of algorithm
  PARALLEL_FOR_IF(Kernel::threadSafe(*outputWS))
  for (int i = 0; i < static_cast<int>(numHists); ++i) {
    PARALLEL_START_INTERUPT_REGION
    size_t wsIndex = static_cast<size_t>(i);
    EventList &evlist = outputWS->getSpectrum(wsIndex);
    if (evlist.getNumberEvents() > 0) // don't bother with empty lists
    {
      double L1(Lss); // distance from source to sample
      double L2(-1);  // distance from sample to detector

      if (spectrumInfo.hasDetectors(i)) {
        if (spectrumInfo.isMonitor(i)) {
          // redefine the sample as the monitor
          L1 = Lss + spectrumInfo.l2(i); // L2 in SpectrumInfo defined negative
          L2 = 0;
        } else {
          L2 = spectrumInfo.l2(i);
        }
      } else {
        g_log.error() << "Unable to calculate distances to/from detector" << i
                      << '\n';
      }

      if (L2 >= 0) {
        // One parser for each parallel processor needed (except Edirect mode)
        double E1;
        mu::Parser parser;
        parser.DefineVar("incidentEnergy", &E1); // associate E1 to this parser
        parser.SetExpr(m_formula);

        // fast neutrons are shifted by min_t0_next, irrespective of tof
        double v1_max = L1 / m_t1min;
        E1 = m_convfactor * v1_max * v1_max;
        double min_t0_next = parser.Eval();

        if (emode == "Indirect") {
          double t2(-1.0); // time from sample to detector. (-1) signals error
          if (spectrumInfo.isMonitor(i)) {
            t2 = 0.0;
          } else {
            static const double convFact =
                1.0e-6 * sqrt(2 * PhysicalConstants::meV /
                              PhysicalConstants::NeutronMass);
            std::vector<double> wsProp =
                spectrumInfo.detector(i).getNumberParameter("Efixed");
            if (!wsProp.empty()) {
              double E2 = wsProp.at(0);        //[E2]=meV
              double v2 = convFact * sqrt(E2); //[v2]=meter/microsec
              t2 = L2 / v2;
            } else {
              // t2 is kept to -1 if no Efixed is found
              g_log.debug() << "Efixed not found for detector " << i << '\n';
            }
          }
          if (t2 >= 0) // t2 < 0 when no detector info is available
          {
            // fix the histogram bins
            auto &x = evlist.mutableX();
            for (double &tof : x) {
              if (tof < m_t1min + t2)
                tof -= min_t0_next;
              else
                tof -= CalculateT0indirect(tof, L1, t2, E1, parser);
            }

            MantidVec tofs = evlist.getTofs();
            for (double &tof : tofs) {
              if (tof < m_t1min + t2)
                tof -= min_t0_next;
              else
                tof -= CalculateT0indirect(tof, L1, t2, E1, parser);
            }
            evlist.setTofs(tofs);
            evlist.setSortOrder(Mantid::DataObjects::EventSortType::UNSORTED);
          } // end of if( t2>= 0)
        }   // end of if(emode=="Indirect")
        else if (emode == "Elastic") {
          // Apply t0 correction to histogram bins
          auto &x = evlist.mutableX();
          for (double &tof : x) {
            if (tof < m_t1min * (L1 + L2) / L1)
              tof -= min_t0_next;
            else
              tof -= CalculateT0elastic(tof, L1 + L2, E1, parser);
          }

          MantidVec tofs = evlist.getTofs();
          for (double &tof : tofs) {
            // add a [-0.1,0.1] microsecond noise to avoid artifacts
            // resulting from original tof data
            if (tof < m_t1min * (L1 + L2) / L1)
              tof -= min_t0_next;
            else
              tof -= CalculateT0elastic(tof, L1 + L2, E1, parser);
          }
          evlist.setTofs(tofs);
          evlist.setSortOrder(Mantid::DataObjects::EventSortType::UNSORTED);
        } // end of else if(emode=="Elastic")
        else if (emode == "Direct") {
          // fix the histogram bins
          evlist.mutableX() -= t0_direct;

          MantidVec tofs = evlist.getTofs();
          for (double &tof : tofs) {
            tof -= t0_direct;
          }
          evlist.setTofs(tofs);
          evlist.setSortOrder(Mantid::DataObjects::EventSortType::UNSORTED);
        } // end of else if(emode=="Direct")
      }   // end of if(L2 >= 0)
    }     // end of if (evlist.getNumberEvents() > 0)
    prog.report();
    PARALLEL_END_INTERUPT_REGION
  } // end of for (int i = 0; i < static_cast<int>(numHists); ++i)
  PARALLEL_CHECK_INTERUPT_REGION
  outputWS->clearMRU(); // Clears the Most Recent Used lists */
} // end of void ModeratorTzero::execEvent()