Example #1
0
//******************************************************************************
// Main
//******************************************************************************
int main(int argc, char **argv) {
    args::ArgumentParser parser("Checks if images are different within a tolerance.\n"
                                "Intended for use with library tests.\n"
                                "http://github.com/spinicist/QUIT");
    args::HelpFlag       help(parser, "HELP", "Show this help message", {'h', "help"});
    args::Flag           verbose(parser, "VERBOSE", "Print more information", {'v', "verbose"});
    args::ValueFlag<std::string> input_path(parser, "INPUT", "Input file for difference",
                                            {"input"});
    args::ValueFlag<std::string> baseline_path(parser, "BASELINE", "Baseline file for difference",
                                               {"baseline"});
    args::ValueFlag<double> tolerance(parser, "TOLERANCE", "Tolerance (mean percent difference)",
                                      {"tolerance"}, 0);
    args::ValueFlag<double> noise(parser, "NOISE",
                                  "Added noise level, tolerance is relative to this", {"noise"}, 0);
    args::Flag              absolute(parser, "ABSOLUTE",
                        "Use absolute difference, not relative (avoids 0/0 problems)",
                        {'a', "abs"});
    QI::ParseArgs(parser, argc, argv, verbose);
    auto input    = QI::ReadImage(QI::CheckValue(input_path), verbose);
    auto baseline = QI::ReadImage(QI::CheckValue(baseline_path), verbose);

    auto diff = itk::SubtractImageFilter<QI::VolumeF>::New();
    diff->SetInput1(input);
    diff->SetInput2(baseline);

    auto sqr_norm = itk::SquareImageFilter<QI::VolumeF, QI::VolumeF>::New();
    if (absolute) {
        sqr_norm->SetInput(diff->GetOutput());
    } else {
        auto diff_norm = itk::DivideImageFilter<QI::VolumeF, QI::VolumeF, QI::VolumeF>::New();
        diff_norm->SetInput1(diff->GetOutput());
        diff_norm->SetInput2(baseline);
        diff_norm->Update();
        sqr_norm->SetInput(diff_norm->GetOutput());
    }
    auto stats = itk::StatisticsImageFilter<QI::VolumeF>::New();
    stats->SetInput(sqr_norm->GetOutput());
    stats->Update();

    const double mean_sqr_diff      = stats->GetMean();
    const double root_mean_sqr_diff = sqrt(mean_sqr_diff);
    const double rel_diff =
        (noise.Get() > 0) ? root_mean_sqr_diff / noise.Get() : root_mean_sqr_diff;
    const bool passed = rel_diff <= tolerance.Get();
    QI::Log(verbose, "Mean Square Diff: {}\nRelative noise: {}\nSquare-root mean square diff: {}\nRelative Diff: {}\nTolerance: {}\nResult: ", mean_sqr_diff
    ,noise.Get()
                                         , root_mean_sqr_diff
                                         , rel_diff
                                         , tolerance.Get()
                                         , (passed ? "Passed" : "Failed"));
    if (passed) {
        return EXIT_SUCCESS;
    } else {
        return EXIT_FAILURE;
    }
}
bool RDCartSlot::breakAway(unsigned msecs)
{
  bool ret=false;
  unsigned cartnum=0;

  if(slot_options->mode()==RDSlotOptions::BreakawayMode) {
    if(msecs==0) {
      stop();
      SetInput(true);
      unload();
      slot_box->setService(slot_svcname);
      slot_box->setStatusLine(tr("Waiting for break..."));
    }
    else {
      cartnum=SelectCart(slot_svcname,msecs);
      if(cartnum!=0) {
	switch(slot_deck->state()) {
	case RDPlayDeck::Playing:
	case RDPlayDeck::Paused:
	case RDPlayDeck::Stopping:
	  slot_breakaway_cart=cartnum;
	  slot_breakaway_length=msecs;
	  stop();
	  break;

	case RDPlayDeck::Stopped:
	case RDPlayDeck::Finished:
	SetInput(false);
	if(slot_timescaling_active) {
	  load(cartnum,msecs);
	}
	else {
	  load(cartnum);
	}
	play();
	syslog(LOG_INFO,"started breakaway, len: %u  cart: %u  cut: %d",
	       msecs,cartnum,slot_logline->cutNumber());
	break;
	}
      }
      else {
	slot_box->setStatusLine(tr("No cart found for length")+" "+
				RDGetTimeLength(msecs,false,false));
      }
    }
  }
  return ret;
}
Example #3
0
HRESULT XMLReader::LoadFromBuffer(const BYTE* pBuffer, UINT nLen)
{
	CComPtr<IStream> pFileStream;
	m_nError = S_OK;

	//on ia64 there is no definiton of SHCreateMemStream therfore 
	//we load it dynamicly from dll file
	typedef struct IStream *(STDAPICALLTYPE *CreateMemStream)(__in_bcount_opt(cbInit) const BYTE *pInit, UINT cbInit);

	HINSTANCE hInst = ::GetModuleHandleA("SHLWAPI.DLL");

	if (NULL == hInst) {
		m_nError = S_FALSE;		
		return m_nError;
	}
	
	//12 it's an ordinal for SHCreateMemStream function
	CreateMemStream pfMemStream = reinterpret_cast<CreateMemStream>(GetProcAddress(hInst, reinterpret_cast<LPCSTR>(LOWORD(12))));

	if (NULL == pfMemStream) {
		m_nError = S_FALSE;
		return m_nError;
	}

	pFileStream = (*pfMemStream)(pBuffer, nLen);

	if (NULL == pFileStream) {
		m_nError = S_FALSE;
	}
	else {
		SetInput(pFileStream);
	}

	return m_nError;	
}
Example #4
0
signal_renderer::signal_renderer(const double& sample_frequency,
                                 const double& window_duration)
  : m_sample_frequency(sample_frequency),
    m_window_duration(window_duration),
    m_size(m_sample_frequency*window_duration),
    m_data(m_size,m_size,0.0), // capacity, size, value
    m_time(gammatone::detail::linspace(0.0,m_window_duration,m_size)),
    
    m_table(decltype(m_table)::New()),
    m_xaxis(decltype(m_xaxis)::New()),
    m_signal(decltype(m_signal)::New()),
    m_view(decltype(m_view)::New()),
    m_chart(decltype(m_chart)::New())
{
  m_xaxis->SetName("time (s)");
  m_signal->SetName("signal");

  m_xaxis->SetArray(m_time.data(),m_time.size(),1);
  m_signal->SetArray(m_data.linearize(),m_data.size(),1);
  
  m_table->AddColumn(m_xaxis);
  m_table->AddColumn(m_signal);
  
  m_view->GetRenderer()->SetBackground(1.0, 1.0, 1.0);
  m_view->GetScene()->AddItem(m_chart);

  auto line = m_chart->AddPlot(vtkChart::LINE);
  line->SetInput(m_table,0,1);
  line->SetColor(255, 0, 0, 255);
  line->SetWidth(1.0);
}
Example #5
0
void WinFrame::ShowDemo()
{
    static int n;

    static const char* demos[] =
    {
        "5 + (6! - 8^3)*2.5",
        "x = 6",
        "y = z = x*2",
        "x+y+z",
        "log 10 + 26",
        "100!",
        "10^10^10",
        "3---8",
        "|3---8|",
        "sin pi/2 + sqrt(1 + (2^-12)*2)",
        "sum[i=1, 10](i*2 - 2^i)",
        "cross([1, 2, 3], [4, 5, 6])",
        "| [0, -1, 2] - [4, 0.5, 3] |",
        nullptr
    };

    /* Set next demo */
    if (!demos[n])
        n = 0;

    SetInput(demos[n]);
    ExecExpr(demos[n]);

    ++n;
}
Example #6
0
int LoadAsn (AsnInfo *asn) {

    /* Arguments:
     **  input		 i: Name of input file or image
     **  asn			io: Association info structure
     */

    extern int status;
    void printInfo (AsnInfo *);
    int SetInput (AsnInfo *);
    int SetAsnSingle (AsnInfo *);
    int GetAsnTable (AsnInfo *);
    int GetGlobalInfo (AsnInfo *);

    /* Determine whether input is a single file, an association table,
     ** or an entry from an association table. */
    if (SetInput (asn))
        return (status);

    if (asn->process == FULL) {
        sprintf (MsgText,"LoadAsn:  Processing FULL Association");
    } else if (asn->process == PARTIAL) {
        sprintf (MsgText,"LoadAsn:  Processing PART of Association");
    } else {
        sprintf (MsgText,"LoadAsn:  Processing SINGLE exposure");
    }
    trlmessage (MsgText);

    /* Read in global info from ASN table's primary header */	
    if (GetGlobalInfo (asn)) {
        trlerror (" Problem getting primary header information.");
        return (status);
    }


    /* Read in ASN table, and load appropriate members info into memory */
    if (asn->process == SINGLE) {
        /* Set ASN structure values to process a single exposure */
        if (SetAsnSingle (asn))
            return (status);
    } else {
        if (GetAsnTable (asn))
            return (status);
    }

    if (asn->debug) { 
        sprintf (MsgText,"LoadAsn:  Read in ASN table %s ", asn->asn_table);
        trlmessage (MsgText);
    }


    /* Print a summary of information about the association */
    if (asn->verbose)
        printInfo (asn);

    return (status);
}
Example #7
0
File: SOM.C Project: dunghand/msrds
void TrainNet(NET* Net)
{
  INT  n,t;
  POLE Pole;
  REAL wOld, wNew, ScoreOld, ScoreNew, dScore, dScoreMean, StepSize;
  REAL Input[N];
  REAL Output[M];
  REAL Target[M];

  n = 0;
  while (n<TRAIN_STEPS) {
    t = 0;
    InitializePole(&Pole);
    fprintf(f, " Time     Angle     Force\n");
    fprintf(f, "%4.1fs    %5.1f°    %5.1fN\n", t * T, Pole.w, Pole.F);
    wOld = Pole.w;
    ScoreOld = ScoreOfPole(&Pole);
    SimulatePole(&Pole);
    wNew = Pole.w;
    ScoreNew = ScoreOfPole(&Pole);
    while (PoleStillBalanced(&Pole) AND (t<BALANCED)) {
      n++;
      t++;
      Net->Alpha   = 0.5 * pow(0.01, (REAL) n / TRAIN_STEPS);
      Net->Alpha_  = 0.5 * pow(0.01, (REAL) n / TRAIN_STEPS);
      Net->Alpha__ = 0.005;
      Net->Gamma   = 0.05;
      Net->Sigma   = 6.0 * pow(0.2, (REAL) n / TRAIN_STEPS);
      Input[0] = wOld;
      Input[1] = wNew;
      SetInput(Net, Input);
      PropagateNet(Net);
      GetOutput(Net, Output);
      Pole.F = Output[0];
      StepSize = Net->KohonenLayer->StepSize[Net->Winner];
      Pole.F += StepSize * RandomNormalREAL(0, 10);
      fprintf(f, "%4.1fs    %5.1f°    %5.1fN\n", t * T, Pole.w, Pole.F);
      wOld = Pole.w;
      ScoreOld = ScoreOfPole(&Pole);
      SimulatePole(&Pole);
      wNew = Pole.w;
      ScoreNew = ScoreOfPole(&Pole);
      dScore = ScoreNew - ScoreOld;
      dScoreMean = Net->KohonenLayer->dScoreMean[Net->Winner];
      if (dScore > dScoreMean) {
        Target[0] = Pole.F;
        TrainUnits(Net, Input, Target);
      }
      Net->KohonenLayer->dScoreMean[Net->Winner] += Net->Gamma * (dScore - dScoreMean);
    }
    if (PoleStillBalanced(&Pole))
      fprintf(f, "Pole still balanced after %0.1fs ...\n\n", t * T);
    else
      fprintf(f, "Pole fallen after %0.1fs ...\n\n", (t+1) * T);
  }
}
Example #8
0
void CHveditDlg::OnSelchangeListChannels()
{
   int n;

   n = m_ctlChannels.GetSelItems(m_nChannels, m_Selection);

   if (n > 0) {
      m_Voltage = m_Demand[ChannelIndex(m_Selection[0])];
      SetInput();
   }
}
Example #9
0
bool WinFrame::ExecExpr(const std::string& expr)
{
    /* If expression is empty -> show information */
    if (expr.empty())
        ShowIntro();
    else if (expr == "exit")
    {
        /* Clear input to avoid storing "exit" in the config-file */
        SetInput("");
        Close();
    }
    else if (expr == "demo")
        ShowDemo();
    else if (expr == "const")
        ShowConstants();
    else if (expr == "clear")
    {
        constantsSet_.constants.clear();
        constantsSet_.ResetStd();
        ShowConstants();
    }
    else
    {
        /* Setup compute mode */
        Ac::ComputeMode mode;
        mode.degree = GetOptionDegree();

        /* Show status message */
        SetOutput("computing ...");

#ifdef AC_MULTI_THREADED

        /* Wait until previous thread has successfully terminated */
        if (computing_)
            return false;
        JoinThread();

#endif

        /* Compute expression */
#ifdef AC_MULTI_THREADED

        computing_ = true;
        thread_ = std::unique_ptr<std::thread>(new std::thread(&WinFrame::ComputeThreadProc, this, expr, mode));

#else

        ComputeThreadProc(expr.ToStdString(), mode);

#endif
    }

    return true;
}
Example #10
0
HRESULT XMLReader::LoadFromFile(const std::wstring& sFileName)
{
	CComPtr<IStream> pFileStream;
	m_nError = S_OK;

	if (!FAILED(m_nError = SHCreateStreamOnFile(sFileName.c_str(), STGM_READ, &pFileStream)))
    {   		
		SetInput(pFileStream);
    }	

	return m_nError;	
}
Example #11
0
void SimulateNet(NET* Net, INT* Input, INT* Target, BOOL Training, BOOL Protocoling)
{
  INT Output[M];
   
  SetInput(Net, Input, Protocoling);
  PropagateNet(Net);
  GetOutput(Net, Output, Protocoling);
   
  ComputeOutputError(Net, Target);
  if (Training)
    AdjustWeights(Net);
}
Example #12
0
void SimulateNet(NET* Net, REAL* Input, REAL* Output, REAL* Target, BOOL Training)
{
  SetInput(Net, Input);
  PropagateNet(Net);
  GetOutput(Net, Output);
   
  ComputeOutputError(Net, Target);
  if (Training) {
    BackpropagateNet(Net);
    AdjustWeights(Net);
  }
}
Example #13
0
void VolumeRayCastMapper::SetInput(int port, vtkDataSet *genericInput)
{
	vtkImageData *input =
		vtkImageData::SafeDownCast(genericInput);

	if (input)
	{
		SetInput(port, input);
	}
	else
	{
		vtkErrorMacro("The SetInput method of this mapper requires vtkImageData as input");
	}
}
Example #14
0
string FlowAnalysis::vtkWriteGrid(const string& out, vtkSmartPointer<vtkUniformGrid>& grid){
	auto compressor=vtkSmartPointer<vtkZLibDataCompressor>::New();
	auto writer=vtkSmartPointer<vtkXMLImageDataWriter>::New();
	string fn=scene->expandTags(out)+".vti";
	writer->SetFileName(fn.c_str());
	#if VTK_MAJOR_VERSION==5
		writer->SetInput(grid);
	#else
		writer->SetInputData(grid);
	#endif
	// writer->SetDataModeToAscii();
 	writer->SetCompressor(compressor);
	writer->Write();
	return fn;
}
void RDCartSlot::updateOptions()
{
  slot_deck->setCard(slot_options->card());
  slot_deck->setPort(slot_options->outputPort());
  switch(slot_options->mode()) {
  case RDSlotOptions::CartDeckMode:
    SetInput(false);
    slot_logline->setHookMode(slot_options->hookMode());
    if(slot_options->hookMode()) {
      slot_options_button->setText(tr("Options")+"\n"+tr("[Hook]"));
    }
    else {
      slot_options_button->setText(tr("Options")+"\n"+tr("[Full]"));
    }

    break;

  case RDSlotOptions::BreakawayMode:
    SetInput(true);
    slot_start_button->setDisabled(true);
    slot_box->setService(slot_svcname);
    slot_box->setStatusLine(tr("Waiting for break..."));
    slot_load_button->setText(tr("Load"));
    slot_logline->setHookMode(false);
    slot_options_button->setText(tr("Options")+"\n"+tr("[Breakaway]"));
    break;

  case RDSlotOptions::LastMode:
    break;
  }
  slot_box->setMode(slot_options->mode());
  slot_options->save();
  if(slot_logline->cartNumber()!=0) {
    load(slot_logline->cartNumber());
  }
}
Example #16
0
void write_vtk_file(const Domain<lattice_model>& domain, const std::string& output_dir,
        const std::string& output_filename, uint64_t t)
{
    const auto xl = domain.xlength();
    const auto yl = domain.ylength();
    const auto zl = domain.zlength();
    // Compute point coordinates
    auto points = vtkSmartPointer<vtkPoints>::New();
    compute_coordinates(domain, points);

    // Compute velocity and density vectors
    auto velocities = vtkSmartPointer<vtkDoubleArray>::New();
    auto densities = vtkSmartPointer<vtkDoubleArray>::New();

    velocities->SetNumberOfComponents(lattice_model::D);
    densities->SetNumberOfComponents(1);

    velocities->SetName("Velocity");
    densities->SetName("Density");

    for (auto z = 1u; z < zl + 1; ++z) {
        for (auto y = 1u; y < yl + 1; ++y) {
            for (auto x = 1u; x < xl + 1; ++x) {
                auto current_cell = domain.cell(x, y, z);
                auto density = current_cell.density();
                auto vel = current_cell.velocity(density);

                densities->InsertNextTuple1(density);
                velocities->InsertNextTuple3(vel[0], vel[1], vel[2]);
            }
        }
    }

    // Create a grid and write coordinates and velocity/density
    auto structuredGrid = vtkSmartPointer<vtkStructuredGrid>::New();
    structuredGrid->SetDimensions(xl, yl, zl);
    structuredGrid->SetPoints(points);
    structuredGrid->GetPointData()->SetVectors(velocities);
    structuredGrid->GetPointData()->SetScalars(densities);
    // Save filename as a combination of passed filename and timestep
    std::stringstream sstr;
    sstr << output_dir << "/" << output_filename << "." << t << ".vts";
    // Write file
    auto writer = vtkSmartPointer<vtkXMLStructuredGridWriter>::New();
    writer->SetFileName(sstr.str().c_str());
    writer->SetInput(structuredGrid);
    writer->Write();
}
Example #17
0
void TechBot::eventManager(std::string str)
{
    SavePrevevent();
    setEvent(str);

    Saveinput();

    SetInput(str);

    if(!same_event()) 
    {
        selectMatch();
    }

    restore_input();
}
static void AddOffset(const itk::Image<TPixel, VImageDimension>* inputImage, int offset, mitk::Image::Pointer outputImage)
{
  typedef itk::Image<TPixel, VImageDimension> ImageType;
  typedef itk::ShiftScaleImageFilter<ImageType, ImageType> FilterType;

  auto filter = FilterType::New();
  filter->SetInput(inputImage);
  filter->SetShift(offset);

  filter->Update();

  // This is the tricky part that is done wrong very often. As the image data
  // of ITK images and MITK images are binary compatible, we don't need to
  // cast or copy the ITK output image. Instead, we just want to reference
  // the image data and tell ITK that we took the ownership.
  mitk::GrabItkImageMemory(filter->GetOutput(), outputImage);
}
Example #19
0
uint TYL40Adc::Read(const int& InputN) {
	TLock Lock(CriticalSection);

	EAssert(FileDesc >= 0);

	Notify->OnNotifyFmt(TNotifyType::ntInfo, "Reading YL-40 input %d ...", InputN);
	SetInput(InputN);

	uchar Val;
	int Read;
	for (int ReadN = 0; ReadN < 2; ReadN++) {
		Read = read(FileDesc, &Val, 1);
		EAssertR(Read == 1, "Failed to read YL-40!");
		usleep(PROCESSING_DELAY);
	}

	return (uint) Val;
}
Example #20
0
void SmoothedClassProbabilites< TImage>
::GenerateData()
{

  typename TImage::Pointer out = this->GetOutput(0);
  out->SetRegions(this->GetInput(0)->GetLargestPossibleRegion());
  out->Allocate();

  for(unsigned int i = 0 ; i < this->GetNumberOfInputs(); i++)
  {

    auto gf = itk::DiscreteGaussianImageFilter<TImage,TImage>::New();
    gf->SetInput(this->GetInput(i));
    gf->SetVariance(this->m_Sigma);
    gf->Update();

    ImageRegionConstIterator<TImage> git(gf->GetOutput(),gf->GetOutput()->GetLargestPossibleRegion());
    ImageRegionIterator<TImage> maskiter(m_MaskImage, m_MaskImage->GetLargestPossibleRegion());
    ImageRegionIterator<TImage> outputIter(out, out->GetLargestPossibleRegion());

    while (!outputIter.IsAtEnd())
    {
      if(maskiter.Value() > 0 ){

        if(git.Value() > outputIter.Value())
          outputIter.Set(i);
      }else
      {
        outputIter.Set(0);
      }

      ++git;
      ++outputIter;
      ++maskiter;
    }
  }






}
Example #21
0
void CHveditDlg::Increment(const float incr)
{
   int n, i;

   // Get current selection
   n = m_ctlChannels.GetSelItems(m_nChannels, m_Selection);

   // Set voltage to selected channels
   for (i = 0; i < n; i++)
      m_Demand[ChannelIndex(m_Selection[i])] = max(0, m_Demand[ChannelIndex(m_Selection[i])] + incr);

   if (n > 0)
      m_Voltage = m_Demand[ChannelIndex(m_Selection[0])];

   SetInput();

   UpdateODB(n == 1 ? ChannelIndex(m_Selection[0]) : -1);
   UpdateListBox(n == 1 ? m_Selection[0] : -1);
}
Example #22
0
VOID
ChangeInput(
    PGLOBAL_DEVICE_INFO     pGDI,
    UCHAR                   Input,
    UCHAR                   Output,
    USHORT                  Channel,
    USHORT                  Old,
    USHORT                  New
)
/*++

Routine Description

    Change an input gradually from its current value to its target value

    NOTE - this routine ASSUMES that each input has 32 steps

--*/
{
    USHORT Current, Final;

    Current = Old >> 11;
    Final   = New >> 11;

    /*
    **  At least once to get the output amp right
    */

    while (TRUE) {
        SetInput(pGDI,
                 Input,
                 (USHORT)(Current << 11),
                 Channel,
                 MIXCROSSCAPS_NORMAL_STEREO,
                 Output);

        if (Current == Final) {
            break;
        }
        Current = Current > Final ? Current - 1 : Current + 1;
    }
}
Example #23
0
    vtkSmartPointer<vtkPolyData> VoxelCarving::createVisualHull(
        const double isolevel) const {

        // create vtk visualization pipeline from voxel grid
        auto spoints = vtkSmartPointer<vtkStructuredPoints>::New();
        auto vdim    = static_cast<int>(voxel_dim_);
        spoints->SetDimensions(vdim, vdim, vdim);
        spoints->SetSpacing(params_.voxel_width, params_.voxel_height,
                            params_.voxel_depth);
        spoints->SetOrigin(params_.start_x, params_.start_y, params_.start_z);

        auto farray = vtkSmartPointer<vtkFloatArray>::New();
        auto vsize  = static_cast<vtkIdType>(voxel_size_);
        farray->SetNumberOfValues(vsize);
        farray->SetArray(vox_array_.get(), vsize, 1);
        spoints->GetPointData()->SetScalars(farray);

        // create iso surface with marching cubes
        auto mc_source = vtkSmartPointer<vtkMarchingCubes>::New();
#if VTK_MAJOR_VERSION < 6
        mc_source->SetInput(spoints);
#else
        mc_source->SetInputData(spoints);
#endif
        mc_source->SetNumberOfContours(1);
        mc_source->SetValue(0, isolevel);

        // calculate surface normals
        auto surface_normals = vtkSmartPointer<vtkPolyDataNormals>::New();
        surface_normals->SetInputConnection(mc_source->GetOutputPort());
        surface_normals->SetFeatureAngle(60.0);
        surface_normals->ComputePointNormalsOn();
        surface_normals->Update();

        return surface_normals->GetOutput();
    }
nsAutoCompleteController::~nsAutoCompleteController()
{
  SetInput(nsnull);
}
Example #25
0
C3DFileAdapter::OutputTables
C3DFileAdapter::extendRead(const std::string& fileName) const {
    auto reader = btk::AcquisitionFileReader::New();
    reader->SetFilename(fileName);
    reader->Update();
    auto acquisition = reader->GetOutput();

    OutputTables tables{};
    auto& marker_table = *(new TimeSeriesTableVec3{});
    auto&  force_table = *(new TimeSeriesTableVec3{});
    tables.emplace(_markers, 
                   std::shared_ptr<TimeSeriesTableVec3>(&marker_table));
    tables.emplace(_forces, 
                   std::shared_ptr<TimeSeriesTableVec3>(&force_table));

    auto marker_pts = btk::PointCollection::New();

    for(auto it = acquisition->BeginPoint();
        it != acquisition->EndPoint();
        ++it) {
        auto pt = *it;
        if(pt->GetType() == btk::Point::Marker)
               marker_pts->InsertItem(pt);
    }

    if(marker_pts->GetItemNumber() != 0) {
        marker_table.
            updTableMetaData().
            setValueForKey("DataRate", 
                           std::to_string(acquisition->GetPointFrequency()));

        marker_table.
            updTableMetaData().
            setValueForKey("Units", 
                           acquisition->GetPointUnit());

        ValueArray<std::string> marker_labels{};
        for(auto it = marker_pts->Begin();
            it != marker_pts->End();
            ++it) {
            marker_labels.
            upd().
            push_back(SimTK::Value<std::string>((*it)->GetLabel()));
        }

        TimeSeriesTableVec3::DependentsMetaData marker_dep_metadata{};
        marker_dep_metadata.setValueArrayForKey("labels", marker_labels);
        marker_table.setDependentsMetaData(marker_dep_metadata);

        double time_step{1.0 / acquisition->GetPointFrequency()};
        for(int f = 0; 
            f < marker_pts->GetFrontItem()->GetFrameNumber();
            ++f) {
            SimTK::RowVector_<SimTK::Vec3> row{marker_pts->GetItemNumber()};
            int m{0};
            for(auto it = marker_pts->Begin();
                it != marker_pts->End();
                ++it) {
                auto pt = *it;
                row[m++] = SimTK::Vec3{pt->GetValues().coeff(f, 0),
                                       pt->GetValues().coeff(f, 1),
                                       pt->GetValues().coeff(f, 2)};
            }
            marker_table.appendRow(0 + f * time_step, row);
        }
    }

    // This is probably the right way to get the raw forces data from force 
    // platforms. Extract the collection of force platforms.
    auto force_platforms_extractor = btk::ForcePlatformsExtractor::New();
    force_platforms_extractor->SetInput(acquisition);
    auto force_platform_collection = force_platforms_extractor->GetOutput();
    force_platforms_extractor->Update();

    std::vector<SimTK::Matrix_<double>> fpCalMatrices{};
    std::vector<SimTK::Matrix_<double>> fpCorners{};
    std::vector<SimTK::Matrix_<double>> fpOrigins{};
    std::vector<unsigned>               fpTypes{};
    auto    fp_force_pts = btk::PointCollection::New();
    auto   fp_moment_pts = btk::PointCollection::New();
    auto fp_position_pts = btk::PointCollection::New();
    for(auto platform = force_platform_collection->Begin(); 
        platform != force_platform_collection->End(); 
        ++platform) {
        const auto& calMatrix = (*platform)->GetCalMatrix();
        const auto& corners   = (*platform)->GetCorners();
        const auto& origins   = (*platform)->GetOrigin();
        fpCalMatrices.push_back(convertToSimtkMatrix(calMatrix));
        fpCorners.push_back(convertToSimtkMatrix(corners));
        fpOrigins.push_back(convertToSimtkMatrix(origins));
        fpTypes.push_back(static_cast<unsigned>((*platform)->GetType()));

        // Get ground reaction wrenches for the force platform.
        auto ground_reaction_wrench_filter = 
            btk::GroundReactionWrenchFilter::New();
        ground_reaction_wrench_filter->SetInput(*platform);
        auto wrench_collection = ground_reaction_wrench_filter->GetOutput();
        ground_reaction_wrench_filter->Update();
        
        for(auto wrench = wrench_collection->Begin();
            wrench != wrench_collection->End(); 
            ++wrench) {
            // Forces time series.
            fp_force_pts->InsertItem((*wrench)->GetForce());
            // Moment time series.
            fp_moment_pts->InsertItem((*wrench)->GetMoment());
            // Position time series.
            fp_position_pts->InsertItem((*wrench)->GetPosition());
        }
    }

    //shrik<btk::ForcePlatform::Origin> foo;

    if(fp_force_pts->GetItemNumber() != 0) {
        force_table.
            updTableMetaData().
            setValueForKey("CalibrationMatrices", std::move(fpCalMatrices));

        force_table.
            updTableMetaData().
            setValueForKey("Corners",             std::move(fpCorners));

        force_table.
            updTableMetaData().
            setValueForKey("Origins",             std::move(fpOrigins));

        force_table.
            updTableMetaData().
            setValueForKey("Types",               std::move(fpTypes));

        force_table.
            updTableMetaData().
            setValueForKey("DataRate", 
                           std::to_string(acquisition->GetAnalogFrequency()));

        ValueArray<std::string> labels{};
        ValueArray<std::string> units{};
        for(int fp = 1; fp <= fp_force_pts->GetItemNumber(); ++fp) {
            auto fp_str = std::to_string(fp);

            labels.upd().push_back(SimTK::Value<std::string>("f" + fp_str));
            auto force_unit = acquisition->GetPointUnits().
                at(_unit_index.at("force"));
            units.upd().push_back(SimTK::Value<std::string>(force_unit));

            labels.upd().push_back(SimTK::Value<std::string>("m" + fp_str));
            auto moment_unit = acquisition->GetPointUnits().
                at(_unit_index.at("moment"));
            units.upd().push_back(SimTK::Value<std::string>(moment_unit));

            labels.upd().push_back(SimTK::Value<std::string>("p" + fp_str));
            auto position_unit = acquisition->GetPointUnits().
                at(_unit_index.at("marker"));
            units.upd().push_back(SimTK::Value<std::string>(position_unit));
        }
        TimeSeriesTableVec3::DependentsMetaData force_dep_metadata{};
        force_dep_metadata.setValueArrayForKey("labels", labels);
        force_dep_metadata.setValueArrayForKey("units", units);
        force_table.setDependentsMetaData(force_dep_metadata);

        double time_step{1.0 / acquisition->GetAnalogFrequency()};
        for(int f = 0;
            f < fp_force_pts->GetFrontItem()->GetFrameNumber();
            ++f) {
            SimTK::RowVector_<SimTK::Vec3>
                row{fp_force_pts->GetItemNumber() * 3};
            int col{0};
            for(auto fit = fp_force_pts->Begin(),
                mit =     fp_moment_pts->Begin(),
                pit =   fp_position_pts->Begin();
                fit != fp_force_pts->End();
                ++fit, 
                ++mit,
                ++pit) {
                row[col] = SimTK::Vec3{(*fit)->GetValues().coeff(f, 0),
                                       (*fit)->GetValues().coeff(f, 1),
                                       (*fit)->GetValues().coeff(f, 2)};
                ++col;
                row[col] = SimTK::Vec3{(*mit)->GetValues().coeff(f, 0),
                                       (*mit)->GetValues().coeff(f, 1),
                                       (*mit)->GetValues().coeff(f, 2)};
                ++col;
                row[col] = SimTK::Vec3{(*pit)->GetValues().coeff(f, 0),
                                       (*pit)->GetValues().coeff(f, 1),
                                       (*pit)->GetValues().coeff(f, 2)};
                ++col;
            }
            force_table.appendRow(0 + f * time_step, row);
        }
    }

    EventTable event_table{};
    auto events = acquisition->GetEvents();
    for(auto it = events->Begin();
        it != events->End();
        ++it) {
        auto et = *it;
        event_table.push_back({et->GetLabel(),
                               et->GetTime(),
                               et->GetFrame(),
                               et->GetDescription()});
    }
       marker_table.updTableMetaData().setValueForKey("events", event_table);
        force_table.updTableMetaData().setValueForKey("events", event_table);

    return tables;
}
Example #26
0
int main(int argc, char **argv) {
    args::ArgumentParser parser(
        "Calculates T1/B1 maps from MP2/3-RAGE data\nhttp://github.com/spinicist/QUIT");
    args::Positional<std::string> input_path(parser, "INPUT FILE", "Path to complex MP-RAGE data");
    args::HelpFlag                help(parser, "HELP", "Show this help message", {'h', "help"});
    args::Flag           verbose(parser, "VERBOSE", "Print more information", {'v', "verbose"});
    args::ValueFlag<int> threads(parser,
                                 "THREADS",
                                 "Use N threads (default=4, 0=hardware limit)",
                                 {'T', "threads"},
                                 QI::GetDefaultThreads());
    args::ValueFlag<std::string> outarg(
        parser, "OUTPREFIX", "Add a prefix to output filenames", {'o', "out"});
    args::ValueFlag<std::string> json_file(
        parser, "FILE", "Read JSON input from file instead of stdin", {"file"});
    args::ValueFlag<float> beta_arg(
        parser,
        "BETA",
        "Regularisation factor for robust contrast calculation "
        "(https://journals.plos.org/plosone/article?id=10.1371/journal.pone.0099676)",
        {'b', "beta"},
        0.0);
    args::Flag t1(parser, "T1", "Calculate T1 map via spline look-up", {'t', "t1"});
    QI::ParseArgs(parser, argc, argv, verbose, threads);

    auto inFile = QI::ReadImage<QI::SeriesXF>(QI::CheckPos(input_path), verbose);

    auto ti_1                     = itk::ExtractImageFilter<QI::SeriesXF, QI::VolumeXF>::New();
    auto ti_2                     = itk::ExtractImageFilter<QI::SeriesXF, QI::VolumeXF>::New();
    auto region                   = inFile->GetLargestPossibleRegion();
    region.GetModifiableSize()[3] = 0;
    ti_1->SetExtractionRegion(region);
    ti_1->SetDirectionCollapseToSubmatrix();
    ti_1->SetInput(inFile);
    region.GetModifiableIndex()[3] = 1;
    ti_2->SetExtractionRegion(region);
    ti_2->SetDirectionCollapseToSubmatrix();
    ti_2->SetInput(inFile);

    QI::Log(verbose, "Generating MP2 contrasts");
    using BinaryFilter = itk::BinaryGeneratorImageFilter<QI::VolumeXF, QI::VolumeXF, QI::VolumeF>;
    auto MP2Filter     = BinaryFilter::New();
    MP2Filter->SetInput1(ti_1->GetOutput());
    MP2Filter->SetInput2(ti_2->GetOutput());
    const float &beta = beta_arg.Get();
    MP2Filter->SetFunctor([&](const std::complex<float> &p1, const std::complex<float> &p2) {
        return MP2Contrast(p1, p2, beta);
    });
    MP2Filter->Update();
    const std::string out_prefix = outarg ? outarg.Get() : QI::StripExt(input_path.Get());
    QI::WriteImage(MP2Filter->GetOutput(), out_prefix + "_MP2" + QI::OutExt(), verbose);

    if (t1) {
        QI::Log(verbose, "Reading sequence information");
        rapidjson::Document input =
            json_file ? QI::ReadJSON(json_file.Get()) : QI::ReadJSON(std::cin);
        QI::MP2RAGESequence mp2rage_sequence(input["MP2RAGE"]);
        QI::Log(verbose, "Building look-up spline");
        int            num_entries = 100;
        Eigen::ArrayXd T1_values   = Eigen::ArrayXd::LinSpaced(num_entries, 0.25, 4.0);
        Eigen::ArrayXd MP2_values(num_entries);
        for (int i = 0; i < num_entries; i++) {
            const auto  sig = One_MP2RAGE(1., T1_values[i], 1., mp2rage_sequence);
            const float mp2 = MP2Contrast(sig[0], sig[1]);
            if ((i > 0) && (mp2 > MP2_values[i - 1])) {
                num_entries = i;
                break;
            } else {
                MP2_values[i] = mp2;
            }
        }
        QI::Log(verbose, "Lookup table length = {}", num_entries);
        QI::SplineInterpolator mp2_to_t1(MP2_values.head(num_entries), T1_values.head(num_entries));
        if (beta) {
            QI::Log(verbose, "Recalculating unregularised MP2 image");
            MP2Filter->SetFunctor(
                [&](const std::complex<float> &p1, const std::complex<float> &p2) {
                    return MP2Contrast(p1, p2, 0.0);
                });
            MP2Filter->Update();
        }
        using UnaryFilter   = itk::UnaryGeneratorImageFilter<QI::VolumeF, QI::VolumeF>;
        auto T1LookupFilter = UnaryFilter::New();
        T1LookupFilter->SetInput(MP2Filter->GetOutput());
        auto lookup = [&](const float &p) { return mp2_to_t1(p); };
        T1LookupFilter->SetFunctor(lookup);
        QI::Log(verbose, "Calculating T1");
        T1LookupFilter->Update();
        QI::WriteImage(T1LookupFilter->GetOutput(), out_prefix + "_MP2_T1" + QI::OutExt(), verbose);
    }
    QI::Log(verbose, "Finished.");
    return EXIT_SUCCESS;
}
Example #27
0
File: main.c Project: vidarh/SAM
int main(int argc, char **argv)
{
	int i;
	int phonetic = 0;

	char* wavfilename = NULL;
	unsigned char input[256];
	
	memset(input, 0, 256);

	if (argc <= 1)
	{
		PrintUsage();
		return 1;
	}

	i = 1;
	while(i < argc)
	{
		if (argv[i][0] != '-')
		{
			strcat_s((char*)input, 256, argv[i]);
			strcat_s((char*)input, 256, " ");
		} else
		{
			if (strcmp(&argv[i][1], "wav")==0)
			{
				wavfilename = argv[i+1];
				i++;
			} else
			if (strcmp(&argv[i][1], "sing")==0)
			{
				EnableSingmode();
			} else
			if (strcmp(&argv[i][1], "phonetic")==0)
			{
				phonetic = 1;
			} else
			if (strcmp(&argv[i][1], "debug")==0)
			{
				debug = 1;
			} else
			if (strcmp(&argv[i][1], "pitch")==0)
			{
				SetPitch((unsigned char)min(atoi(argv[i+1]),255));
				i++;
			} else
			if (strcmp(&argv[i][1], "speed")==0)
			{
				SetSpeed((unsigned char)min(atoi(argv[i+1]),255));
				i++;
			} else
			if (strcmp(&argv[i][1], "mouth")==0)
			{
				SetMouth((unsigned char)min(atoi(argv[i+1]),255));
				i++;
			} else
			if (strcmp(&argv[i][1], "throat")==0)
			{
				SetThroat((unsigned char)min(atoi(argv[i+1]),255));
				i++;
			} else
			{
				PrintUsage();
				return 1;
			}
		}
		
		i++;
	} //while

	for(i=0; input[i] != 0; i++)
		input[i] = (unsigned char)toupper((int)input[i]);

	if (debug)
	{
		if (phonetic) printf("phonetic input: %s\n", input);
		else printf("text input: %s\n", input); 
	}
	
	if (!phonetic)
	{
		strcat_s((char*)input, 256, "[");
		if (!TextToPhonemes(input)) return 1;
		if (debug)
			printf("phonetic input: %s\n", input);
	} else strcat_s((char*)input, 256, "\x9b");

#ifdef USESDL
	if ( SDL_Init(SDL_INIT_AUDIO) < 0 ) 
	{
		printf("Unable to init SDL: %s\n", SDL_GetError());
		exit(1);
	}
	atexit(SDL_Quit);
#endif

	SetInput(input);
	if (!SAMMain())
	{
		PrintUsage();
		return 1;
	}

	if (wavfilename != NULL) 
		WriteWav(wavfilename, GetBuffer(), GetBufferLength()/50);
	else
		OutputSound();

	return 0;
}
void RDCartSlot::stateChangedData(int id,RDPlayDeck::State state)
{
  //printf("stateChangedData(%d,%d)\n",id,state);
  short lvls[2]={-10000,-10000};

  switch(state) {
  case RDPlayDeck::Playing:
    LogPlayout(state);
    slot_start_button->
      setEnabled(slot_options->mode()==RDSlotOptions::CartDeckMode);
    slot_start_button->setPalette(slot_playing_color);
    slot_load_button->setDisabled(true);
    slot_options_button->setDisabled(true);
    break;

  case RDPlayDeck::Stopped:
  case RDPlayDeck::Finished:
    LogPlayout(state);
    slot_start_button->
      setEnabled(slot_options->mode()==RDSlotOptions::CartDeckMode);
    slot_start_button->setPalette(slot_ready_color);
    slot_load_button->setEnabled(true);
    slot_options_button->setEnabled(true);
    slot_box->setTimer(0);
    slot_box->updateMeters(lvls);
    slot_box->setCart(slot_logline);
    switch(slot_options->mode()) {
    case RDSlotOptions::CartDeckMode:
      if(!slot_stop_requested) {
	switch(slot_options->stopAction()) {
	case RDSlotOptions::RecueOnStop:
	  break;
	  
	case RDSlotOptions::UnloadOnStop:
	  unload();
	  break;
	  
	case RDSlotOptions::LoopOnStop:
	  play();
	  break;
	  
	case RDSlotOptions::LastStop:
	  break;
	}
      }
      break;

    case RDSlotOptions::BreakawayMode:
      if(slot_breakaway_cart>0) {
	SetInput(false);
	load(slot_breakaway_cart);
	play();
	syslog(LOG_INFO,"started breakaway, len: %u  cart: %u  cut: %d",
	       slot_breakaway_length,slot_breakaway_cart,
	       slot_logline->cutNumber());
	slot_breakaway_cart=0;
	slot_breakaway_length=0;
      }
      else {
	SetInput(true);
	unload();
	slot_box->setService(slot_svcname);
	slot_box->setStatusLine(tr("Waiting for break..."));
	//	LogPlayout(RDAirPlayConf::TrafficFinish);
      }
      break;

    case RDSlotOptions::LastMode:
      break;
    }
    slot_stop_requested=false;
    break;

  case RDPlayDeck::Stopping:
  case RDPlayDeck::Paused:
    break;
  }
  
}
Example #29
0
 void DiPostEffectPass::RefreshInput()
 {
     SetInput(mInput.first,mInput.second);
 }
C3DFileAdapter::OutputTables
C3DFileAdapter::extendRead(const std::string& fileName) const {
    auto reader = btk::AcquisitionFileReader::New();
    reader->SetFilename(fileName);
    reader->Update();
    auto acquisition = reader->GetOutput();

    EventTable event_table{};
    auto events = acquisition->GetEvents();
    for (auto it = events->Begin();
        it != events->End();
        ++it) {
        auto et = *it;
        event_table.push_back({ et->GetLabel(),
            et->GetTime(),
            et->GetFrame(),
            et->GetDescription() });
    }

    OutputTables tables{};

    auto marker_pts = btk::PointCollection::New();

    for(auto it = acquisition->BeginPoint();
        it != acquisition->EndPoint();
        ++it) {
        auto pt = *it;
        if(pt->GetType() == btk::Point::Marker)
               marker_pts->InsertItem(pt);
    }

    if(marker_pts->GetItemNumber() != 0) {

        int marker_nrow = marker_pts->GetFrontItem()->GetFrameNumber();
        int marker_ncol = marker_pts->GetItemNumber();

        std::vector<double> marker_times(marker_nrow);
        SimTK::Matrix_<SimTK::Vec3> marker_matrix(marker_nrow, marker_ncol);

        std::vector<std::string> marker_labels{};
        for (auto it = marker_pts->Begin(); it != marker_pts->End(); ++it) {
            marker_labels.push_back(SimTK::Value<std::string>((*it)->GetLabel()));
        }

        double time_step{1.0 / acquisition->GetPointFrequency()};
        for(int f = 0; f < marker_nrow; ++f) {
            SimTK::RowVector_<SimTK::Vec3> row{ marker_pts->GetItemNumber(), 
                                                SimTK::Vec3(SimTK::NaN) };
            int m{0};
            for(auto it = marker_pts->Begin();  it != marker_pts->End(); ++it) {
                auto pt = *it;
                // BTK reads empty values as zero, but sets a "residual" value
                // to -1 and it is how it knows to export these values as 
                // blank, instead of 0,  when exporting to .trc
                // See: BTKCore/Code/IO/btkTRCFileIO.cpp#L359-L360
                // Read in value if it is not zero or residual is not -1
                if (!pt->GetValues().row(f).isZero() ||    //not precisely zero
                    (pt->GetResiduals().coeff(f) != -1) ) {//residual is not -1
                    row[m] = SimTK::Vec3{ pt->GetValues().coeff(f, 0),
                                          pt->GetValues().coeff(f, 1),
                                          pt->GetValues().coeff(f, 2) };
                }
                ++m;
            }

            marker_matrix.updRow(f) = row;
            marker_times[f] = 0 + f * time_step; //TODO: 0 should be start_time
        }

        // Create the data
        auto marker_table = 
            std::make_shared<TimeSeriesTableVec3>(marker_times, 
                                                  marker_matrix, 
                                                  marker_labels);

        marker_table->
            updTableMetaData().
            setValueForKey("DataRate",
                std::to_string(acquisition->GetPointFrequency()));

        marker_table->
            updTableMetaData().
            setValueForKey("Units",
                acquisition->GetPointUnit());

        marker_table->updTableMetaData().setValueForKey("events", event_table);

        tables.emplace(_markers, marker_table);
    }

    // This is probably the right way to get the raw forces data from force 
    // platforms. Extract the collection of force platforms.
    auto force_platforms_extractor = btk::ForcePlatformsExtractor::New();
    force_platforms_extractor->SetInput(acquisition);
    auto force_platform_collection = force_platforms_extractor->GetOutput();
    force_platforms_extractor->Update();

    std::vector<SimTK::Matrix_<double>> fpCalMatrices{};
    std::vector<SimTK::Matrix_<double>> fpCorners{};
    std::vector<SimTK::Matrix_<double>> fpOrigins{};
    std::vector<unsigned>               fpTypes{};
    auto    fp_force_pts = btk::PointCollection::New();
    auto   fp_moment_pts = btk::PointCollection::New();
    auto fp_position_pts = btk::PointCollection::New();
    for(auto platform = force_platform_collection->Begin(); 
        platform != force_platform_collection->End(); 
        ++platform) {
        const auto& calMatrix = (*platform)->GetCalMatrix();
        const auto& corners   = (*platform)->GetCorners();
        const auto& origins   = (*platform)->GetOrigin();
        fpCalMatrices.push_back(convertToSimtkMatrix(calMatrix));
        fpCorners.push_back(convertToSimtkMatrix(corners));
        fpOrigins.push_back(convertToSimtkMatrix(origins));
        fpTypes.push_back(static_cast<unsigned>((*platform)->GetType()));

        // Get ground reaction wrenches for the force platform.
        auto ground_reaction_wrench_filter = 
            btk::GroundReactionWrenchFilter::New();
        ground_reaction_wrench_filter->setLocation(
            btk::GroundReactionWrenchFilter::Location(getLocationForForceExpression()));
        ground_reaction_wrench_filter->SetInput(*platform);
        auto wrench_collection = ground_reaction_wrench_filter->GetOutput();
        ground_reaction_wrench_filter->Update();
        
        for(auto wrench = wrench_collection->Begin();
            wrench != wrench_collection->End(); 
            ++wrench) {
            // Forces time series.
            fp_force_pts->InsertItem((*wrench)->GetForce());
            // Moment time series.
            fp_moment_pts->InsertItem((*wrench)->GetMoment());
            // Position time series.
            fp_position_pts->InsertItem((*wrench)->GetPosition());
        }
    }

    if(fp_force_pts->GetItemNumber() != 0) {

        std::vector<std::string> labels{};
        ValueArray<std::string> units{};
        for(int fp = 1; fp <= fp_force_pts->GetItemNumber(); ++fp) {
            auto fp_str = std::to_string(fp);

            labels.push_back(SimTK::Value<std::string>("f" + fp_str));
            auto force_unit = acquisition->GetPointUnits().
                at(_unit_index.at("force"));
            units.upd().push_back(SimTK::Value<std::string>(force_unit));

            labels.push_back(SimTK::Value<std::string>("p" + fp_str));
            auto position_unit = acquisition->GetPointUnits().
                at(_unit_index.at("marker"));
            units.upd().push_back(SimTK::Value<std::string>(position_unit));

            labels.push_back(SimTK::Value<std::string>("m" + fp_str));
            auto moment_unit = acquisition->GetPointUnits().
                at(_unit_index.at("moment"));
            units.upd().push_back(SimTK::Value<std::string>(moment_unit));
        }

        const int nf = fp_force_pts->GetFrontItem()->GetFrameNumber();
        
        std::vector<double> force_times(nf);
        SimTK::Matrix_<SimTK::Vec3> force_matrix(nf, (int)labels.size());

        double time_step{1.0 / acquisition->GetAnalogFrequency()};

        for(int f = 0; f < nf;  ++f) {
            SimTK::RowVector_<SimTK::Vec3> 
                row{fp_force_pts->GetItemNumber() * 3};
            int col{0};
            for(auto fit = fp_force_pts->Begin(),
                mit =     fp_moment_pts->Begin(),
                pit =   fp_position_pts->Begin();
                fit != fp_force_pts->End();
                ++fit, 
                ++mit,
                ++pit) {
                row[col] = SimTK::Vec3{(*fit)->GetValues().coeff(f, 0),
                                       (*fit)->GetValues().coeff(f, 1),
                                       (*fit)->GetValues().coeff(f, 2)};
                ++col;
                row[col] = SimTK::Vec3{(*pit)->GetValues().coeff(f, 0),
                                       (*pit)->GetValues().coeff(f, 1),
                                       (*pit)->GetValues().coeff(f, 2)};
                ++col;
                row[col] = SimTK::Vec3{(*mit)->GetValues().coeff(f, 0),
                                       (*mit)->GetValues().coeff(f, 1),
                                       (*mit)->GetValues().coeff(f, 2)};
                ++col;
            }
            force_matrix.updRow(f) = row;
            force_times[f] = 0 + f * time_step; //TODO: 0 should be start_time
        }

        auto&  force_table = 
            *(new TimeSeriesTableVec3(force_times, force_matrix, labels));

        TimeSeriesTableVec3::DependentsMetaData force_dep_metadata
            = force_table.getDependentsMetaData();

        // add units to the dependent meta data
        force_dep_metadata.setValueArrayForKey("units", units);
        force_table.setDependentsMetaData(force_dep_metadata);

        force_table.
            updTableMetaData().
            setValueForKey("CalibrationMatrices", std::move(fpCalMatrices));

        force_table.
            updTableMetaData().
            setValueForKey("Corners", std::move(fpCorners));

        force_table.
            updTableMetaData().
            setValueForKey("Origins", std::move(fpOrigins));

        force_table.
            updTableMetaData().
            setValueForKey("Types", std::move(fpTypes));

        force_table.
            updTableMetaData().
            setValueForKey("DataRate",
                std::to_string(acquisition->GetAnalogFrequency()));

        tables.emplace(_forces,
            std::shared_ptr<TimeSeriesTableVec3>(&force_table));

        force_table.updTableMetaData().setValueForKey("events", event_table);
    }

    return tables;
}