<commit_before>// Test how we produce the scariness score.

// RUN: %clangxx_asan -O0 %s -o %t
// On OSX and Windows, alloc_dealloc_mismatch=1 isn't 100% reliable, so it's
// off by default. It's safe for these tests, though, so we turn it on.
// RUN: export %env_asan_opts=detect_stack_use_after_return=1:handle_abort=1:print_scariness=1:alloc_dealloc_mismatch=1
// Make sure the stack is limited (may not be the default under GNU make)
// RUN: ulimit -s 4096
// RUN: not %run %t  1 2>&1 | FileCheck %s --check-prefix=CHECK1
// RUN: not %run %t  2 2>&1 | FileCheck %s --check-prefix=CHECK2
// RUN: not %run %t  3 2>&1 | FileCheck %s --check-prefix=CHECK3
// RUN: not %run %t  4 2>&1 | FileCheck %s --check-prefix=CHECK4
// RUN: not %run %t  5 2>&1 | FileCheck %s --check-prefix=CHECK5
// RUN: not %run %t  6 2>&1 | FileCheck %s --check-prefix=CHECK6
// RUN: not %run %t  7 2>&1 | FileCheck %s --check-prefix=CHECK7
// RUN: not %run %t  8 2>&1 | FileCheck %s --check-prefix=CHECK8
// RUN: not %run %t  9 2>&1 | FileCheck %s --check-prefix=CHECK9
// RUN: not %run %t 10 2>&1 | FileCheck %s --check-prefix=CHECK10
// RUN: not %run %t 11 2>&1 | FileCheck %s --check-prefix=CHECK11
// RUN: not %run %t 12 2>&1 | FileCheck %s --check-prefix=CHECK12
// RUN: not %run %t 13 2>&1 | FileCheck %s --check-prefix=CHECK13
// RUN: not %run %t 14 2>&1 | FileCheck %s --check-prefix=CHECK14
// RUN: not %run %t 15 2>&1 | FileCheck %s --check-prefix=CHECK15
// RUN: not %run %t 16 2>&1 | FileCheck %s --check-prefix=CHECK16
// RUN: not %run %t 17 2>&1 | FileCheck %s --check-prefix=CHECK17
// RUN: not %run %t 18 2>&1 | FileCheck %s --check-prefix=CHECK18
// RUN: not %run %t 19 2>&1 | FileCheck %s --check-prefix=CHECK19
// RUN: not %run %t 20 2>&1 | FileCheck %s --check-prefix=CHECK20
// RUN: not %run %t 21 2>&1 | FileCheck %s --check-prefix=CHECK21
// RUN: not %run %t 22 2>&1 | FileCheck %s --check-prefix=CHECK22
// RUN: not %run %t 23 2>&1 | FileCheck %s --check-prefix=CHECK23
// RUN: not %run %t 24 2>&1 | FileCheck %s --check-prefix=CHECK24
// RUN: not %run %t 25 2>&1 | FileCheck %s --check-prefix=CHECK25
// RUN: not %run %t 26 2>&1 | FileCheck %s --check-prefix=CHECK26
// Parts of the test are too platform-specific:
// REQUIRES: x86_64-target-arch
// REQUIRES: shell
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#include <sanitizer/asan_interface.h>

enum ReadOrWrite { Read = 0, Write = 1 };

struct S32 {
  char x[32];
};

template<class T>
void HeapBuferOverflow(int Idx, ReadOrWrite w) {
  T *t = new T[100];
  static T sink;
  if (w)
    t[100 + Idx] = T();
  else
    sink = t[100 + Idx];
  delete [] t;
}

template<class T>
void HeapUseAfterFree(int Idx, ReadOrWrite w) {
  T *t = new T[100];
  static T sink;
  sink = t[0];
  delete [] t;
  if (w)
    t[Idx] = T();
  else
    sink = t[Idx];
}

template<class T>
void StackBufferOverflow(int Idx, ReadOrWrite w) {
  T t[100];
  static T sink;
  sink = t[Idx];
  if (w)
    t[100 + Idx] = T();
  else
    sink = t[100 + Idx];
}

template<class T>
T *LeakStack() {
  T t[100];
  static volatile T *x;
  x = &t[0];
  return (T*)x;
}

template<class T>
void StackUseAfterReturn(int Idx, ReadOrWrite w) {
  static T sink;
  T *t = LeakStack<T>();
  if (w)
    t[100 + Idx] = T();
  else
    sink = t[100 + Idx];
}

char    g1[100];
short   g2[100];
int     g4[100];
int64_t g8[100];
S32     gm[100];

void DoubleFree() {
  int *x = new int;
  static volatile int two = 2;
  for (int i = 0; i < two; i++)
    delete x;
}

void StackOverflow(int Idx) {
  int some_stack[10000];
  static volatile int *x;
  x = &some_stack[0];
  if (Idx > 0)
    StackOverflow(Idx - 1);
}

void UseAfterPoison() {
  int buf[100];
  __asan_poison_memory_region(buf, sizeof(buf));
  static volatile int sink;
  sink = buf[42];
}

int main(int argc, char **argv) {
  char arr[100];
  static volatile int zero = 0;
  static volatile int *zero_ptr = 0;
  static volatile int *wild_addr = (int*)0x10000000; // System-dependent.
  if (argc != 2) return 1;
  int kind = atoi(argv[1]);
  switch (kind) {
    case 1: HeapBuferOverflow<char>(0, Read); break;
    case 2: HeapBuferOverflow<int>(0, Read); break;
    case 3: HeapBuferOverflow<short>(0, Write); break;
    case 4: HeapBuferOverflow<int64_t>(2, Write); break;
    case 5: HeapBuferOverflow<S32>(4, Write); break;
    case 6: HeapUseAfterFree<char>(0, Read); break;
    case 7: HeapUseAfterFree<int>(0, Write); break;
    case 8: HeapUseAfterFree<int64_t>(0, Read); break;
    case 9: HeapUseAfterFree<S32>(0, Write); break;
    case 10: StackBufferOverflow<char>(0, Write); break;
    case 11: StackBufferOverflow<int64_t>(0, Read); break;
    case 12: StackBufferOverflow<int>(4, Write); break;
    case 13: StackUseAfterReturn<char>(0, Read); break;
    case 14: StackUseAfterReturn<S32>(0, Write); break;
    case 15: g1[zero + 100] = 0; break;
    case 16: gm[0] = gm[zero + 100 + 1]; break;
    case 17: DoubleFree(); break;
    case 18: StackOverflow(1000000); break;
    case 19: *zero_ptr = 0; break;
    case 20: *wild_addr = 0; break;
    case 21: zero = *wild_addr; break;
    case 22: ((void (*)(void))wild_addr)(); break;
    case 23: delete (new int[10]); break;
    case 24: free((char*)malloc(100) + 10); break;
    case 25: memcpy(arr, arr+10, 20);  break;
    case 26: UseAfterPoison(); break;
    // CHECK1: SCARINESS: 12 (1-byte-read-heap-buffer-overflow)
    // CHECK2: SCARINESS: 17 (4-byte-read-heap-buffer-overflow)
    // CHECK3: SCARINESS: 33 (2-byte-write-heap-buffer-overflow)
    // CHECK4: SCARINESS: 52 (8-byte-write-heap-buffer-overflow-far-from-bounds)
    // CHECK5: SCARINESS: 55 (multi-byte-write-heap-buffer-overflow-far-from-bounds)
    // CHECK6: SCARINESS: 40 (1-byte-read-heap-use-after-free)
    // CHECK7: SCARINESS: 46 (4-byte-write-heap-use-after-free)
    // CHECK8: SCARINESS: 51 (8-byte-read-heap-use-after-free)
    // CHECK9: SCARINESS: 55 (multi-byte-write-heap-use-after-free)
    // CHECK10: SCARINESS: 46 (1-byte-write-stack-buffer-overflow)
    // CHECK11: SCARINESS: 38 (8-byte-read-stack-buffer-overflow)
    // CHECK12: SCARINESS: 61 (4-byte-write-stack-buffer-overflow-far-from-bounds)
    // CHECK13: SCARINESS: 50 (1-byte-read-stack-use-after-return)
    // CHECK14: SCARINESS: 65 (multi-byte-write-stack-use-after-return)
    // CHECK15: SCARINESS: 31 (1-byte-write-global-buffer-overflow)
    // CHECK16: SCARINESS: 36 (multi-byte-read-global-buffer-overflow-far-from-bounds)
    // CHECK17: SCARINESS: 42 (double-free)
    // CHECK18: SCARINESS: 10 (stack-overflow)
    // CHECK19: SCARINESS: 10 (null-deref)
    // CHECK20: SCARINESS: 30 (wild-addr-write)
    // CHECK21: SCARINESS: 20 (wild-addr-read)
    // CHECK22: SCARINESS: 60 (wild-jump)
    // CHECK23: SCARINESS: 10 (alloc-dealloc-mismatch)
    // CHECK24: SCARINESS: 40 (bad-free)
    // CHECK25: SCARINESS: 10 (memcpy-param-overlap)
    // CHECK26: SCARINESS: 27 (4-byte-read-use-after-poison)
  }
}
<commit_msg>Revert "Copy over most of the scariness_score test to the general tests"<commit_after><|endoftext|>


<commit_before>/*============================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center (DKFZ)
All rights reserved.

Use of this source code is governed by a 3-clause BSD license that can be
found in the LICENSE file.

============================================================================*/

// Testing
#include "mitkTestingMacros.h"
#include "mitkTestFixture.h"

//MITK includes
#include "mitkVector.h"
#include "mitkStandardToftsModel.h"
#include "mitkAIFBasedModelBase.h"

class mitkStandardToftsModelTestSuite : public mitk::TestFixture
{
  CPPUNIT_TEST_SUITE(mitkStandardToftsModelTestSuite);
  MITK_TEST(GetModelDisplayNameTest);
  MITK_TEST(GetModelTypeTest);
  MITK_TEST(GetParameterNamesTest);
  MITK_TEST(GetNumberOfParametersTest);
  MITK_TEST(GetParameterUnitsTest);
  MITK_TEST(GetDerivedParameterNamesTest);
  MITK_TEST(GetNumberOfDerivedParametersTest);
  MITK_TEST(GetDerivedParameterUnitsTest);
  MITK_TEST(ComputeModelfunctionTest);
  MITK_TEST(ComputeDerivedParametersTest);
  CPPUNIT_TEST_SUITE_END();

private:
  mitk::StandardToftsModel::Pointer m_testmodel;
  mitk::ModelBase::ModelResultType m_output;
  mitk::ModelBase::DerivedParameterMapType m_derivedParameters;

public:
  void setUp() override
  {
    mitk::ModelBase::TimeGridType m_grid(60);
    mitk::ModelBase::ParametersType m_testparameters(2);
    mitk::AIFBasedModelBase::AterialInputFunctionType m_arterialInputFunction (60);

    m_testparameters[mitk::StandardToftsModel::POSITION_PARAMETER_Ktrans] = 35.0;
    m_testparameters(mitk::StandardToftsModel::POSITION_PARAMETER_ve) = 0.5;

    for (int i = 0; i < 22; ++i)
    {
      // time grid in seconds, 14s between frames
      m_grid[i] = (double)14 * i;
    }

    // AIF from Weinmann, H. J., Laniado, M., and W.Mtzel (1984). Pharmacokinetics of GD - DTPA / dimeglumine after intravenous injection into healthy volunteers. Phys Chem Phys Med NMR, 16(2) : 16772.
    int D = 1;
    double a1 = 3.99;
    double m1 = 0.144;
    double a2 = 4.78;
    double m2 = 0.0111;
    for (int i = 0; i < 22; ++i)
    {
      if (i < 5)
        m_arterialInputFunction[i] = 0;
      else
        m_arterialInputFunction[i] = D * (a1 * exp(-m1 * m_grid[i]) + a2 * exp(-m2 * m_grid[i]));
    }

    m_testmodel = mitk::StandardToftsModel::New();
    m_testmodel->SetTimeGrid(m_grid);
    m_testmodel->SetAterialInputFunctionValues(m_arterialInputFunction);
    m_testmodel->SetAterialInputFunctionTimeGrid(m_grid);

    //ComputeModelfunction is called within GetSignal(), therefore no explicit testing of ComputeModelFunction()
    m_output = m_testmodel->GetSignal(m_testparameters);
    m_derivedParameters = m_testmodel->GetDerivedParameters(m_testparameters);
  }

  void tearDown() override
  {
    m_testmodel = nullptr;
    m_output.clear();
    m_derivedParameters.clear();
  }

  void GetModelDisplayNameTest()
  {
    m_testmodel->GetModelDisplayName();
    CPPUNIT_ASSERT_MESSAGE("Checking model display name.", m_testmodel->GetModelDisplayName() == "Standard Tofts Model");
  }

  void GetModelTypeTest()
  {
    CPPUNIT_ASSERT_MESSAGE("Checking model type.", m_testmodel->GetModelType() == "Perfusion.MR");
  }

  void GetParameterNamesTest()
  {
    mitk::StandardToftsModel::ParameterNamesType parameterNames;
    parameterNames.push_back("KTrans");
    parameterNames.push_back("ve");
    CPPUNIT_ASSERT_MESSAGE("Checking parameter names.", m_testmodel->GetParameterNames() == parameterNames);
  }

  void GetNumberOfParametersTest()
  {
    CPPUNIT_ASSERT_MESSAGE("Checking number of parameters in model.", m_testmodel->GetNumberOfParameters() == 2);
  }

  void GetParameterUnitsTest()
  {
    mitk::StandardToftsModel::ParamterUnitMapType parameterUnits;
    parameterUnits.insert(std::make_pair("KTrans", "ml/min/100ml"));
    parameterUnits.insert(std::make_pair("ve", "ml/ml"));

    CPPUNIT_ASSERT_MESSAGE("Checking parameter units.", m_testmodel->GetParameterUnits() == parameterUnits);
  }

  void GetDerivedParameterNamesTest()
  {
    mitk::StandardToftsModel::ParameterNamesType derivedParameterNames;

    derivedParameterNames.push_back("kep");

    CPPUNIT_ASSERT_MESSAGE("Checking derived parameter names.", m_testmodel->GetDerivedParameterNames() == derivedParameterNames);
  }

  void GetNumberOfDerivedParametersTest()
  {
    CPPUNIT_ASSERT_MESSAGE("Checking number of parameters in model.", m_testmodel->GetNumberOfDerivedParameters() == 1);
  }

  void GetDerivedParameterUnitsTest()
  {
    mitk::StandardToftsModel::ParamterUnitMapType derivedParameterUnits;
    derivedParameterUnits.insert(std::make_pair("kep", "1/min"));

    CPPUNIT_ASSERT_MESSAGE("Checking parameter units.", m_testmodel->GetDerivedParameterUnits() == derivedParameterUnits);
  }

  void ComputeModelfunctionTest()
  {
    CPPUNIT_ASSERT_MESSAGE("Checking signal at time frame 0.", mitk::Equal(0.0, m_output[0], 1e-6, true) == true);
    CPPUNIT_ASSERT_MESSAGE("Checking signal at time frame 5.", mitk::Equal(0.085056, m_output[5], 1e-6, true) == true);
    CPPUNIT_ASSERT_MESSAGE("Checking signal at time frame 10.", mitk::Equal(0.442948, m_output[10], 1e-6, true) == true);
    CPPUNIT_ASSERT_MESSAGE("Checking signal at time frame 20.", mitk::Equal(0.254551, m_output[20], 1e-6, true) == true);
  }

  void ComputeDerivedParametersTest()
  {
    CPPUNIT_ASSERT_MESSAGE("Checking kep.", mitk::Equal(70.0, m_derivedParameters["kep"], 1e-6, true) == true);
  }

};

MITK_TEST_SUITE_REGISTRATION(mitkStandardToftsModel)
<commit_msg>Minor bug fix.<commit_after>/*============================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center (DKFZ)
All rights reserved.

Use of this source code is governed by a 3-clause BSD license that can be
found in the LICENSE file.

============================================================================*/

// Testing
#include "mitkTestingMacros.h"
#include "mitkTestFixture.h"

//MITK includes
#include "mitkVector.h"
#include "mitkStandardToftsModel.h"
#include "mitkAIFBasedModelBase.h"

class mitkStandardToftsModelTestSuite : public mitk::TestFixture
{
  CPPUNIT_TEST_SUITE(mitkStandardToftsModelTestSuite);
  MITK_TEST(GetModelDisplayNameTest);
  MITK_TEST(GetModelTypeTest);
  MITK_TEST(GetParameterNamesTest);
  MITK_TEST(GetNumberOfParametersTest);
  MITK_TEST(GetParameterUnitsTest);
  MITK_TEST(GetDerivedParameterNamesTest);
  MITK_TEST(GetNumberOfDerivedParametersTest);
  MITK_TEST(GetDerivedParameterUnitsTest);
  MITK_TEST(ComputeModelfunctionTest);
  MITK_TEST(ComputeDerivedParametersTest);
  CPPUNIT_TEST_SUITE_END();

private:
  mitk::StandardToftsModel::Pointer m_testmodel;
  mitk::ModelBase::ModelResultType m_output;
  mitk::ModelBase::DerivedParameterMapType m_derivedParameters;

public:
  void setUp() override
  {
    mitk::ModelBase::TimeGridType m_grid(22);
    mitk::ModelBase::ParametersType m_testparameters(2);
    mitk::AIFBasedModelBase::AterialInputFunctionType m_arterialInputFunction (22);

    m_testparameters[mitk::StandardToftsModel::POSITION_PARAMETER_Ktrans] = 35.0;
    m_testparameters(mitk::StandardToftsModel::POSITION_PARAMETER_ve) = 0.5;

    for (int i = 0; i < 22; ++i)
    {
      // time grid in seconds, 14s between frames
      m_grid[i] = (double)14 * i;
    }

    // AIF from Weinmann, H. J., Laniado, M., and W.Mtzel (1984). Pharmacokinetics of GD - DTPA / dimeglumine after intravenous injection into healthy volunteers. Phys Chem Phys Med NMR, 16(2) : 16772.
    int D = 1;
    double a1 = 3.99;
    double m1 = 0.144;
    double a2 = 4.78;
    double m2 = 0.0111;
    for (int i = 0; i < 22; ++i)
    {
      if (i < 5)
        m_arterialInputFunction[i] = 0;
      else
        m_arterialInputFunction[i] = D * (a1 * exp(-m1 * m_grid[i]) + a2 * exp(-m2 * m_grid[i]));
    }

    m_testmodel = mitk::StandardToftsModel::New();
    m_testmodel->SetTimeGrid(m_grid);
    m_testmodel->SetAterialInputFunctionValues(m_arterialInputFunction);
    m_testmodel->SetAterialInputFunctionTimeGrid(m_grid);

    //ComputeModelfunction is called within GetSignal(), therefore no explicit testing of ComputeModelFunction()
    m_output = m_testmodel->GetSignal(m_testparameters);
    m_derivedParameters = m_testmodel->GetDerivedParameters(m_testparameters);
  }

  void tearDown() override
  {
    m_testmodel = nullptr;
    m_output.clear();
    m_derivedParameters.clear();
  }

  void GetModelDisplayNameTest()
  {
    m_testmodel->GetModelDisplayName();
    CPPUNIT_ASSERT_MESSAGE("Checking model display name.", m_testmodel->GetModelDisplayName() == "Standard Tofts Model");
  }

  void GetModelTypeTest()
  {
    CPPUNIT_ASSERT_MESSAGE("Checking model type.", m_testmodel->GetModelType() == "Perfusion.MR");
  }

  void GetParameterNamesTest()
  {
    mitk::StandardToftsModel::ParameterNamesType parameterNames;
    parameterNames.push_back("KTrans");
    parameterNames.push_back("ve");
    CPPUNIT_ASSERT_MESSAGE("Checking parameter names.", m_testmodel->GetParameterNames() == parameterNames);
  }

  void GetNumberOfParametersTest()
  {
    CPPUNIT_ASSERT_MESSAGE("Checking number of parameters in model.", m_testmodel->GetNumberOfParameters() == 2);
  }

  void GetParameterUnitsTest()
  {
    mitk::StandardToftsModel::ParamterUnitMapType parameterUnits;
    parameterUnits.insert(std::make_pair("KTrans", "ml/min/100ml"));
    parameterUnits.insert(std::make_pair("ve", "ml/ml"));

    CPPUNIT_ASSERT_MESSAGE("Checking parameter units.", m_testmodel->GetParameterUnits() == parameterUnits);
  }

  void GetDerivedParameterNamesTest()
  {
    mitk::StandardToftsModel::ParameterNamesType derivedParameterNames;

    derivedParameterNames.push_back("kep");

    CPPUNIT_ASSERT_MESSAGE("Checking derived parameter names.", m_testmodel->GetDerivedParameterNames() == derivedParameterNames);
  }

  void GetNumberOfDerivedParametersTest()
  {
    CPPUNIT_ASSERT_MESSAGE("Checking number of parameters in model.", m_testmodel->GetNumberOfDerivedParameters() == 1);
  }

  void GetDerivedParameterUnitsTest()
  {
    mitk::StandardToftsModel::ParamterUnitMapType derivedParameterUnits;
    derivedParameterUnits.insert(std::make_pair("kep", "1/min"));

    CPPUNIT_ASSERT_MESSAGE("Checking parameter units.", m_testmodel->GetDerivedParameterUnits() == derivedParameterUnits);
  }

  void ComputeModelfunctionTest()
  {
    CPPUNIT_ASSERT_MESSAGE("Checking signal at time frame 0.", mitk::Equal(0.0, m_output[0], 1e-6, true) == true);
    CPPUNIT_ASSERT_MESSAGE("Checking signal at time frame 5.", mitk::Equal(0.085056, m_output[5], 1e-6, true) == true);
    CPPUNIT_ASSERT_MESSAGE("Checking signal at time frame 10.", mitk::Equal(0.442948, m_output[10], 1e-6, true) == true);
    CPPUNIT_ASSERT_MESSAGE("Checking signal at time frame 20.", mitk::Equal(0.254551, m_output[20], 1e-6, true) == true);
  }

  void ComputeDerivedParametersTest()
  {
    CPPUNIT_ASSERT_MESSAGE("Checking kep.", mitk::Equal(70.0, m_derivedParameters["kep"], 1e-6, true) == true);
  }

};

MITK_TEST_SUITE_REGISTRATION(mitkStandardToftsModel)
<|endoftext|>


<commit_before>/*****************************************************************************************[Aiger.C]
Copyright (c) 2007, Niklas Sorensson

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute,
sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or
substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT
OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
**************************************************************************************************/

#include "utils/ParseUtils.h"
#include "circ/Aiger.h"

using namespace Minisat;

static unsigned int readPacked(StreamBuffer& in){
    unsigned int x = 0, i = 0;
    int ch;

    while ((ch = *in) & 0x80){
        if (ch == EOF) fprintf(stderr, "ERROR! Unexpected end of file!\n"), exit(1);
        x |= (ch & 0x7f) << (7 * i++);
        ++in;
    }
    if (ch == EOF) fprintf(stderr, "ERROR! Unexpected end of file!\n"), exit(1);
    ++in;

    return x | (ch << (7 * i));
}

static Sig aigToSig(vec<Sig>& id2sig, int aiger_lit) {
    if (aiger_lit == 0)      return sig_False;
    else if (aiger_lit == 1) return sig_True;
    else {
      assert((aiger_lit >> 1) < id2sig.size());
      assert((aiger_lit >> 1) >= 0);
      return id2sig[aiger_lit >> 1] ^ bool(aiger_lit & 1);
    }
}

void Minisat::readAiger(const char* filename, Circ& c, Box& b, Flops& flp)
{
    gzFile f = gzopen(filename, "rb");

    if (f == NULL)
        fprintf(stderr, "ERROR! Could not open file <%s> for reading\n", filename), exit(1);

    StreamBuffer in(f);

    if (!eagerMatch(in, "aig "))
        fprintf(stderr, "PARSE ERROR! Unexpected char: %c\n", *in), exit(1);

    int max_var   = parseInt(in);
    int n_inputs  = parseInt(in);
    int n_flops = parseInt(in);
    int n_outputs = parseInt(in);
    int n_gates   = parseInt(in);

    // fprintf(stderr, "max_var   = %d\n", max_var);
    // fprintf(stderr, "n_inputs  = %d\n", n_inputs);
    // fprintf(stderr, "n_outputs = %d\n", n_outputs);
    // fprintf(stderr, "n_flops = %d\n", n_flops);
    // fprintf(stderr, "n_gates   = %d\n", n_gates);
    // fprintf(stderr, "sum       = %d\n", n_gates + n_flops + n_inputs);

    if (max_var != n_inputs + n_flops + n_gates)
        fprintf(stderr, "ERROR! Header mismatching sizes (M != I + L + A)\n"), exit(1);

    c.clear();
    b.clear();
    flp.clear();

    vec<Sig> id2sig(max_var+1, sig_Undef);

    // Create input gates:
    for (int i = 0; i < n_inputs; i++){
        Sig x = c.mkInp();
        b.inps.push(gate(x));
        id2sig[i+1] = x;
    }

    vec<unsigned int> aiger_outputs;
    vec<unsigned int> aiger_latch_defs;
    vec<Gate>         latch_gates;

    // Create latch gates:
    for (int i = 0; i < n_flops; i++){
        Sig x = c.mkInp();
        id2sig[i+n_inputs+1] = x;
        latch_gates.push(gate(x));
    }

    // Read latch definitions:
    for (int i = 0; i < n_flops; i++){
        aiger_latch_defs.push(parseInt(in));
        skipLine(in); }

    // Read outputs:
    for (int i = 0; i < n_outputs; i++){
        aiger_outputs.push(parseInt(in));
        skipLine(in); }

    // Read gates:
    for (int i = n_inputs + n_flops + 1; i < max_var + 1; i++){
        unsigned delta0 = readPacked(in);
        unsigned delta1 = readPacked(in);
        unsigned x      = 2*i - delta0;
        unsigned y      = x   - delta1;
        id2sig[i]       = c.mkAnd(aigToSig(id2sig, x), aigToSig(id2sig, y));

        assert(i < id2sig.size());
        assert((int)delta0 < 2*i);
        assert(delta1 <= 2*i - delta0);
        // fprintf(stderr, "read gate %d = %d & %d\n", 2*i, x, y);
    }

    // Map outputs:
    for (int i = 0; i < aiger_outputs.size(); i++)
        b.outs.push(aigToSig(id2sig, aiger_outputs[i]));

    // Map flops:
    flp.adjust(c);
    for (int i = 0; i < aiger_latch_defs.size(); i++){
        Sig x = aigToSig(id2sig, aiger_latch_defs[i]);
        flp.defineFlop(latch_gates[i], x);
    }

    gzclose(f);
    // printf("Read %d number of gates\n", c.nGates());
}

static void writePacked(FILE* file, unsigned int x)
{
    unsigned char ch;

    while (x & ~0x7f){
        ch = (x & 0x7f) | 0x80;
        putc(ch, file);
        x >>= 7;
    }

    ch = x;
    putc(ch, file);
}

static unsigned int sigToAig(GMap<unsigned int>& gate2id, Sig x) {
    if (x == sig_False)      return 0;
    else if (x == sig_True)  return 1;
    else return (gate2id[gate(x)]<<1) + (unsigned int)sign(x);
}

void Minisat::writeAiger(const char* filename, const Circ& c, const Box& b, const Flops& flp)
{
    // fprintf(stderr, "aig %u %u %u %d %d\n", c.size(), inputs.size(), latch_defs.size(), outputs.size(), c.nGates());

    unsigned int n_inputs = b.inps.size(), n_flops = flp.size();

    // Generate the same set, but in an order compatible with the AIGER format:
    GSet uporder;
    for (int i = 0; i < b.inps.size(); i++) uporder.insert(b.inps[i]);
    for (int i = 0; i < flp.size(); i++)    uporder.insert(flp[i]);

    // Build set of all sink-nodes:
    vec<Gate> sinks;
    for (int i = 0; i < b.outs.size(); i++) sinks.push(gate(b.outs[i]));
    for (int i = 0; i < flp   .size(); i++) sinks.push(gate(flp.def(flp[i])));
    bottomUpOrder(c, sinks, uporder);

    unsigned int       n_gates = uporder.size() - n_inputs - n_flops;
    GMap<unsigned int> gate2id; gate2id.growTo(c.lastGate());
    for (int i = 0; i < uporder.size(); i++)
        gate2id[uporder[i]] = i + 1;

    FILE* f = fopen(filename, "wb");

    if (f == NULL)
        fprintf(stderr, "ERROR! Could not open file <%s> for writing\n", filename), exit(1);

    // fprintf(stderr, "aig %u %u %u %d %d\n", uporder.size(), n_inputs, n_flops, c.outputs.size(), n_gates);
    fprintf(f, "aig %u %u %u %d %d\n", uporder.size(), n_inputs, n_flops, b.outs.size() - n_flops, n_gates);

    // Write latch-defs:
    for (int i = 0; i < flp.size(); i++)
        fprintf(f, "%u\n", sigToAig(gate2id, flp.def(flp[i])));

    // Write outputs:
    for (int i = 0; i < b.outs.size(); i++)
        fprintf(f, "%u\n", sigToAig(gate2id, b.outs[i]));

    // Write gates:
    for (int i = 0; i < (int)n_gates; i++){
        Gate         g    = uporder[n_inputs + n_flops + i];     assert(type(g) == gtype_And);
        unsigned int glit = (n_inputs + n_flops + i + 1) << 1;
        unsigned int llit = sigToAig(gate2id, c.lchild(g));
        unsigned int rlit = sigToAig(gate2id, c.rchild(g));

        if (llit < rlit){
            unsigned int tmp = llit; llit = rlit; rlit = tmp; }

        assert(glit > llit);
        assert(llit >= rlit);

        // fprintf(stderr, "%d = %d & %d\n", glit, llit, rlit);
        writePacked(f, glit - llit);
        writePacked(f, llit - rlit);
    }
    fclose(f);
}
<commit_msg>Small bugfix in writeAiger().<commit_after>/*****************************************************************************************[Aiger.C]
Copyright (c) 2007, Niklas Sorensson

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute,
sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or
substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT
OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
**************************************************************************************************/

#include "utils/ParseUtils.h"
#include "circ/Aiger.h"

using namespace Minisat;

static unsigned int readPacked(StreamBuffer& in){
    unsigned int x = 0, i = 0;
    int ch;

    while ((ch = *in) & 0x80){
        if (ch == EOF) fprintf(stderr, "ERROR! Unexpected end of file!\n"), exit(1);
        x |= (ch & 0x7f) << (7 * i++);
        ++in;
    }
    if (ch == EOF) fprintf(stderr, "ERROR! Unexpected end of file!\n"), exit(1);
    ++in;

    return x | (ch << (7 * i));
}

static Sig aigToSig(vec<Sig>& id2sig, int aiger_lit) {
    if (aiger_lit == 0)      return sig_False;
    else if (aiger_lit == 1) return sig_True;
    else {
      assert((aiger_lit >> 1) < id2sig.size());
      assert((aiger_lit >> 1) >= 0);
      return id2sig[aiger_lit >> 1] ^ bool(aiger_lit & 1);
    }
}

void Minisat::readAiger(const char* filename, Circ& c, Box& b, Flops& flp)
{
    gzFile f = gzopen(filename, "rb");

    if (f == NULL)
        fprintf(stderr, "ERROR! Could not open file <%s> for reading\n", filename), exit(1);

    StreamBuffer in(f);

    if (!eagerMatch(in, "aig "))
        fprintf(stderr, "PARSE ERROR! Unexpected char: %c\n", *in), exit(1);

    int max_var   = parseInt(in);
    int n_inputs  = parseInt(in);
    int n_flops = parseInt(in);
    int n_outputs = parseInt(in);
    int n_gates   = parseInt(in);

    // fprintf(stderr, "max_var   = %d\n", max_var);
    // fprintf(stderr, "n_inputs  = %d\n", n_inputs);
    // fprintf(stderr, "n_outputs = %d\n", n_outputs);
    // fprintf(stderr, "n_flops = %d\n", n_flops);
    // fprintf(stderr, "n_gates   = %d\n", n_gates);
    // fprintf(stderr, "sum       = %d\n", n_gates + n_flops + n_inputs);

    if (max_var != n_inputs + n_flops + n_gates)
        fprintf(stderr, "ERROR! Header mismatching sizes (M != I + L + A)\n"), exit(1);

    c.clear();
    b.clear();
    flp.clear();

    vec<Sig> id2sig(max_var+1, sig_Undef);

    // Create input gates:
    for (int i = 0; i < n_inputs; i++){
        Sig x = c.mkInp();
        b.inps.push(gate(x));
        id2sig[i+1] = x;
    }

    vec<unsigned int> aiger_outputs;
    vec<unsigned int> aiger_latch_defs;
    vec<Gate>         latch_gates;

    // Create latch gates:
    for (int i = 0; i < n_flops; i++){
        Sig x = c.mkInp();
        id2sig[i+n_inputs+1] = x;
        latch_gates.push(gate(x));
    }

    // Read latch definitions:
    for (int i = 0; i < n_flops; i++){
        aiger_latch_defs.push(parseInt(in));
        skipLine(in); }

    // Read outputs:
    for (int i = 0; i < n_outputs; i++){
        aiger_outputs.push(parseInt(in));
        skipLine(in); }

    // Read gates:
    for (int i = n_inputs + n_flops + 1; i < max_var + 1; i++){
        unsigned delta0 = readPacked(in);
        unsigned delta1 = readPacked(in);
        unsigned x      = 2*i - delta0;
        unsigned y      = x   - delta1;
        id2sig[i]       = c.mkAnd(aigToSig(id2sig, x), aigToSig(id2sig, y));

        assert(i < id2sig.size());
        assert((int)delta0 < 2*i);
        assert(delta1 <= 2*i - delta0);
        // fprintf(stderr, "read gate %d = %d & %d\n", 2*i, x, y);
    }

    // Map outputs:
    for (int i = 0; i < aiger_outputs.size(); i++)
        b.outs.push(aigToSig(id2sig, aiger_outputs[i]));

    // Map flops:
    flp.adjust(c);
    for (int i = 0; i < aiger_latch_defs.size(); i++){
        Sig x = aigToSig(id2sig, aiger_latch_defs[i]);
        flp.defineFlop(latch_gates[i], x);
    }

    gzclose(f);
    // printf("Read %d number of gates\n", c.nGates());
}

static void writePacked(FILE* file, unsigned int x)
{
    unsigned char ch;

    while (x & ~0x7f){
        ch = (x & 0x7f) | 0x80;
        putc(ch, file);
        x >>= 7;
    }

    ch = x;
    putc(ch, file);
}

static unsigned int sigToAig(GMap<unsigned int>& gate2id, Sig x) {
    if (x == sig_False)      return 0;
    else if (x == sig_True)  return 1;
    else return (gate2id[gate(x)]<<1) + (unsigned int)sign(x);
}

void Minisat::writeAiger(const char* filename, const Circ& c, const Box& b, const Flops& flp)
{
    // fprintf(stderr, "aig %u %u %u %d %d\n", c.size(), inputs.size(), latch_defs.size(), outputs.size(), c.nGates());

    unsigned int n_inputs = b.inps.size(), n_flops = flp.size();

    // Generate the same set, but in an order compatible with the AIGER format:
    GSet uporder;
    for (int i = 0; i < b.inps.size(); i++) uporder.insert(b.inps[i]);
    for (int i = 0; i < flp.size(); i++)    uporder.insert(flp[i]);

    // Build set of all sink-nodes:
    vec<Gate> sinks;
    for (int i = 0; i < b.outs.size(); i++) sinks.push(gate(b.outs[i]));
    for (int i = 0; i < flp   .size(); i++) sinks.push(gate(flp.def(flp[i])));
    bottomUpOrder(c, sinks, uporder);

    unsigned int       n_gates = uporder.size() - n_inputs - n_flops;
    GMap<unsigned int> gate2id; gate2id.growTo(c.lastGate());
    for (int i = 0; i < uporder.size(); i++)
        gate2id[uporder[i]] = i + 1;

    FILE* f = fopen(filename, "wb");

    if (f == NULL)
        fprintf(stderr, "ERROR! Could not open file <%s> for writing\n", filename), exit(1);

    // fprintf(stderr, "aig %u %u %u %d %d\n", uporder.size(), n_inputs, n_flops, c.outputs.size(), n_gates);
    fprintf(f, "aig %u %u %u %d %d\n", uporder.size(), n_inputs, n_flops, b.outs.size(), n_gates);

    // Write latch-defs:
    for (int i = 0; i < flp.size(); i++)
        fprintf(f, "%u\n", sigToAig(gate2id, flp.def(flp[i])));

    // Write outputs:
    for (int i = 0; i < b.outs.size(); i++)
        fprintf(f, "%u\n", sigToAig(gate2id, b.outs[i]));

    // Write gates:
    for (int i = 0; i < (int)n_gates; i++){
        Gate         g    = uporder[n_inputs + n_flops + i];     assert(type(g) == gtype_And);
        unsigned int glit = (n_inputs + n_flops + i + 1) << 1;
        unsigned int llit = sigToAig(gate2id, c.lchild(g));
        unsigned int rlit = sigToAig(gate2id, c.rchild(g));

        if (llit < rlit){
            unsigned int tmp = llit; llit = rlit; rlit = tmp; }

        assert(glit > llit);
        assert(llit >= rlit);

        // fprintf(stderr, "%d = %d & %d\n", glit, llit, rlit);
        writePacked(f, glit - llit);
        writePacked(f, llit - rlit);
    }
    fclose(f);
}
<|endoftext|>


<commit_before>
<commit_msg>Update outputter.cpp<commit_after>#include <iostream>
#include <iterator>
#include <string>
#include <vector>

int main();
{
   std::copy(parseCommand.begin(), parseCommand.end(), std::ostream_iterator<std::string>(std::cout, "\n")); //test line to op "parseCommand"
}
<|endoftext|>


<commit_before>#include <accumulate.hpp>

#include <vector>
#include <iterator>
#include <string>

#include "catch.hpp"

using iter::accumulate;

TEST_CASE("Simple sum", "[accumulate]") {
    std::vector<int> ns{1,2,3,4,5};
    auto a = accumulate(ns);

    const std::vector<int> v(std::begin(a), std::end(a));
    const std::vector<int> vc{1,3,6,10,15};
    REQUIRE( v == vc );
}

<commit_msg>tests accumulate with BasicIterable<commit_after>#include <accumulate.hpp>
#include "helpers.hpp"

#include <vector>
#include <iterator>
#include <string>

#include "catch.hpp"

using iter::accumulate;
using itertest::BasicIterable;

using Vec = const std::vector<int>;
TEST_CASE("Simple sum", "[accumulate]") {
    Vec ns{1,2,3,4,5};
    auto a = accumulate(ns);

    Vec v(std::begin(a), std::end(a));
    Vec vc{1,3,6,10,15};
    REQUIRE( v == vc );
}

TEST_CASE("With subtraction lambda", "[accumulate]") {
    Vec ns{5,4,3,2,1};
    auto a = accumulate(ns, [](int a, int b){return a - b; });

    Vec v(std::begin(a), std::end(a));
    Vec vc{5, 1, -2, -4, -5};
    REQUIRE( v == vc );
}

TEST_CASE("initializer_list works", "[accumulate]") {
    auto a = accumulate({1, 2, 3});
    Vec v(std::begin(a), std::end(a));
    Vec vc{1, 3, 6};

    REQUIRE( v == vc );
}

TEST_CASE("binds reference when it should", "[enumerate]") {
    BasicIterable<int> bi{1, 2};
    accumulate(bi);
    REQUIRE_FALSE( bi.was_moved_from() );
}

TEST_CASE("moves rvalues into enumerable object", "[enumerate]") {
    BasicIterable<int> bi{1, 2};
    accumulate(std::move(bi));
    REQUIRE( bi.was_moved_from() );
}
<|endoftext|>


<commit_before>// Makes distance matrix based on procrustes RMS between maps

#include "acmacs-base/argv.hh"
#include "acmacs-base/range-v3.hh"
#include "acmacs-base/quicklook.hh"
#include "acmacs-chart-2/factory-import.hh"
#include "acmacs-chart-2/chart-modify.hh"
#include "acmacs-chart-2/procrustes.hh"
#include "acmacs-chart-2/common.hh"
#include "acmacs-chart-2/stress.hh"
#include "acmacs-chart-2/randomizer.hh"
#include "acmacs-chart-2/bounding-ball.hh"
#include "acmacs-draw/surface-cairo.hh"
#include "acmacs-draw/drawi-generator.hh"

// ----------------------------------------------------------------------

using namespace acmacs::argv;
struct Options : public argv
{
    Options(int a_argc, const char* const a_argv[], on_error on_err = on_error::exit) : argv() { parse(a_argc, a_argv, on_err); }

    std::string_view help_pre() const override { return "compare titers of mutiple tables"; }
    argument<str_array> charts{*this, arg_name{"chart"}, mandatory};

    option<str> output{*this, 'o', desc{"output .drawi file"}};
    option<size_t> number_of_optimizations{*this, 'n', dflt{100ul}};
    option<str> minimum_column_basis{*this, 'm', dflt{"none"}};
    option<size_t> number_of_dimensions{*this, 'd', dflt{2ul}};
    option<bool>   rough{*this, "rough"};
};

int main(int argc, char* const argv[])
{
    int exit_code = 0;
    try {
        Options opt(argc, argv);
        const auto precision = (opt.rough) ? acmacs::chart::optimization_precision::rough : acmacs::chart::optimization_precision::fine;

        std::vector<acmacs::chart::ChartModify> charts;
        for (const auto& filename : opt.charts)
            charts.emplace_back(acmacs::chart::import_from_file(filename));

        const auto chart_name = [](const auto& chart) { return chart.info()->date(); };

        for (auto& chart : charts) {
            chart.projections_modify()->remove_all();
            chart.relax(acmacs::chart::number_of_optimizations_t{*opt.number_of_optimizations}, acmacs::chart::MinimumColumnBasis{opt.minimum_column_basis},
                        acmacs::number_of_dimensions_t{*opt.number_of_dimensions}, acmacs::chart::use_dimension_annealing::no, acmacs::chart::optimization_options{precision});
            chart.projections_modify()->sort();
            AD_DEBUG("{}  {:9.4f}", chart_name(chart), chart.projections()->best()->stress());
        }

        acmacs::chart::TableDistances table_distances;
        for (size_t t1 = 0; t1 < (charts.size() - 1); ++t1) {
            for (size_t t2 = t1 + 1; t2 < charts.size(); ++t2) {
                acmacs::chart::CommonAntigensSera common(charts[t1], charts[t2], acmacs::chart::CommonAntigensSera::match_level_t::strict);
                const auto procrustes_data = acmacs::chart::procrustes(*charts[t1].projection(0), *charts[t2].projection(0), common.points(), acmacs::chart::procrustes_scaling_t::no);
                table_distances.add_value(acmacs::chart::Titer::Regular, t1, t2, procrustes_data.rms);
                AD_DEBUG("{} {}  {:6.4f}", chart_name(charts[t1]), chart_name(charts[t2]), procrustes_data.rms);
            }
        }

        // ----------------------------------------------------------------------
        // make-module, also for chart-table-compare

        acmacs::chart::Stress stress(acmacs::number_of_dimensions_t{2}, charts.size());
        stress.table_distances() = table_distances;

        double best_stress{9e99};
        acmacs::Layout best_layout(charts.size(), stress.number_of_dimensions());
        for ([[maybe_unused]] auto attempt : acmacs::range(*opt.number_of_optimizations)) {
            acmacs::Layout layout(charts.size(), stress.number_of_dimensions());
            acmacs::chart::LayoutRandomizerPlain rnd(10.0, std::nullopt);
            for (auto point_no : acmacs::range(layout.number_of_points()))
                layout.update(point_no, rnd.get(stress.number_of_dimensions()));

            const auto status1 =
                acmacs::chart::optimize(acmacs::chart::optimization_method::alglib_cg_pca, stress, layout.data(), layout.data() + layout.size(), acmacs::chart::optimization_precision::rough);
            // fmt::print("{:3d} stress: {} <- {} iterations: {}\n", attempt, status1.final_stress, status1.initial_stress, status1.number_of_iterations);
            if (status1.final_stress < best_stress) {
                best_stress = status1.final_stress;
                best_layout = layout;
            }
        }
        AD_DEBUG("best_stress: {}", best_stress);

        if (opt.output) {
            acmacs::drawi::Generator gen;
            const acmacs::BoundingBall bb{minimum_bounding_ball(best_layout)};
            gen.viewport().set_from_center_size(bb.center(), bb.diameter());
            for (size_t t1 = 0; t1 < charts.size(); ++t1) {
                gen.add_point().coord(best_layout[t1]).label(chart_name(charts[t1]));
            }
            gen.generate(opt.output);
        }
    }
    catch (std::exception& err) {
        AD_ERROR("{}", err);
        exit_code = 2;
    }
    return exit_code;
}

// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<commit_msg>chart-table-map-compare<commit_after>// Makes distance matrix based on procrustes RMS between maps

#include "acmacs-base/argv.hh"
#include "acmacs-base/range-v3.hh"
#include "acmacs-base/quicklook.hh"
#include "acmacs-chart-2/factory-import.hh"
#include "acmacs-chart-2/chart-modify.hh"
#include "acmacs-chart-2/procrustes.hh"
#include "acmacs-chart-2/common.hh"
#include "acmacs-chart-2/stress.hh"
#include "acmacs-chart-2/randomizer.hh"
#include "acmacs-chart-2/bounding-ball.hh"
#include "acmacs-draw/surface-cairo.hh"
#include "acmacs-draw/drawi-generator.hh"

// ----------------------------------------------------------------------

using namespace acmacs::argv;
struct Options : public argv
{
    Options(int a_argc, const char* const a_argv[], on_error on_err = on_error::exit) : argv() { parse(a_argc, a_argv, on_err); }

    std::string_view help_pre() const override { return "compare titers of mutiple tables"; }
    argument<str_array> charts{*this, arg_name{"chart"}, mandatory};

    option<str> output{*this, 'o', desc{"output .drawi file"}};
    option<size_t> number_of_optimizations{*this, 'n', dflt{100ul}};
    option<str> minimum_column_basis{*this, 'm', dflt{"none"}};
    option<size_t> number_of_dimensions{*this, 'd', dflt{2ul}};
    option<bool>   rough{*this, "rough"};
};

int main(int argc, char* const argv[])
{
    int exit_code = 0;
    try {
        Options opt(argc, argv);
        const auto precision = (opt.rough) ? acmacs::chart::optimization_precision::rough : acmacs::chart::optimization_precision::fine;

        std::vector<acmacs::chart::ChartModify> charts;
        for (const auto& filename : opt.charts)
            charts.emplace_back(acmacs::chart::import_from_file(filename));

        const auto chart_name = [](const auto& chart) { return chart.info()->date(); };

        for (auto& chart : charts) {
            chart.projections_modify()->remove_all();
            chart.relax(acmacs::chart::number_of_optimizations_t{*opt.number_of_optimizations}, acmacs::chart::MinimumColumnBasis{opt.minimum_column_basis},
                        acmacs::number_of_dimensions_t{*opt.number_of_dimensions}, acmacs::chart::use_dimension_annealing::no, acmacs::chart::optimization_options{precision});
            chart.projections_modify()->sort();
            AD_DEBUG("{}  {:9.4f}", chart_name(chart), chart.projections()->best()->stress());
        }

        acmacs::chart::TableDistances table_distances;
        for (size_t t1 = 0; t1 < (charts.size() - 1); ++t1) {
            for (size_t t2 = t1 + 1; t2 < charts.size(); ++t2) {
                acmacs::chart::CommonAntigensSera common(charts[t1], charts[t2], acmacs::chart::CommonAntigensSera::match_level_t::strict);
                if (!common.points().empty()) {
                    const auto procrustes_data = acmacs::chart::procrustes(*charts[t1].projection(0), *charts[t2].projection(0), common.points(), acmacs::chart::procrustes_scaling_t::no);
                    table_distances.add_value(acmacs::chart::Titer::Regular, t1, t2, procrustes_data.rms);
                    AD_DEBUG("{} {}  {:6.4f}", chart_name(charts[t1]), chart_name(charts[t2]), procrustes_data.rms);
                }
            }
        }

        // ----------------------------------------------------------------------
        // make-module, also for chart-table-compare

        acmacs::chart::Stress stress(acmacs::number_of_dimensions_t{2}, charts.size());
        stress.table_distances() = table_distances;

        double best_stress{9e99};
        acmacs::Layout best_layout(charts.size(), stress.number_of_dimensions());
        for ([[maybe_unused]] auto attempt : acmacs::range(*opt.number_of_optimizations)) {
            acmacs::Layout layout(charts.size(), stress.number_of_dimensions());
            acmacs::chart::LayoutRandomizerPlain rnd(10.0, std::nullopt);
            for (auto point_no : acmacs::range(layout.number_of_points()))
                layout.update(point_no, rnd.get(stress.number_of_dimensions()));

            const auto status1 =
                acmacs::chart::optimize(acmacs::chart::optimization_method::alglib_cg_pca, stress, layout.data(), layout.data() + layout.size(), acmacs::chart::optimization_precision::rough);
            // fmt::print("{:3d} stress: {} <- {} iterations: {}\n", attempt, status1.final_stress, status1.initial_stress, status1.number_of_iterations);
            if (status1.final_stress < best_stress) {
                best_stress = status1.final_stress;
                best_layout = layout;
            }
        }
        AD_DEBUG("best_stress: {}", best_stress);

        if (opt.output) {
            acmacs::drawi::Generator gen;
            const acmacs::BoundingBall bb{minimum_bounding_ball(best_layout)};
            gen.viewport().set_from_center_size(bb.center(), bb.diameter());
            for (size_t t1 = 0; t1 < charts.size(); ++t1) {
                gen.add_point().coord(best_layout[t1]).label(chart_name(charts[t1]));
            }
            gen.generate(opt.output);
        }
    }
    catch (std::exception& err) {
        AD_ERROR("{}", err);
        exit_code = 2;
    }
    return exit_code;
}

// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<|endoftext|>


<commit_before>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: matchlocale.hxx,v $
 * $Revision: 1.9 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

/* PLEASE DON'T DELETE ANY COMMENT LINES, ALSO IT'S UNNECESSARY. */

#ifndef CONFIGMGR_MATCHLOCALE_HXX
#define CONFIGMGR_MATCHLOCALE_HXX

#include <com/sun/star/uno/Sequence.hxx>
#include <com/sun/star/lang/Locale.hpp>

#include <rtl/ustring.hxx>
#include <vector>

namespace configmgr
{
// -----------------------------------------------------------------------------

    namespace localehelper
    {
    // -------------------------------------------------------------------------
        using ::rtl::OUString;
        using ::com::sun::star::lang::Locale;
        namespace uno       = ::com::sun::star::uno;
        namespace lang      = ::com::sun::star::lang;

    // -------------------------------------------------------------------------
        extern char const * const c_sAnyLanguage;
        extern char const * const c_sDefLanguage;

        extern bool isAnyLanguage(OUString const & _sLanguage);
        extern bool isDefaultLanguage(OUString const & _sLanguage);

        extern OUString getAnyLanguage();
        extern OUString getDefaultLanguage();

        extern Locale getAnyLocale();
        extern Locale getDefaultLocale();

    // -------------------------------------------------------------------------
    /// Type for storing a list of Locales
        typedef std::vector< Locale > LocaleSequence;
        typedef LocaleSequence::size_type SequencePos;

        // the max value of SequencePos - marks out-of-range (Value == -1 == ~0)
        SequencePos const c_noPosition = SequencePos(0)-SequencePos(1);

        // conversion helpers
        Locale makeLocale(OUString const& sLocaleName_);
        OUString makeIsoLocale(Locale const& aUnoLocale_);

        LocaleSequence makeLocaleSequence(uno::Sequence<OUString> const& sLocaleNames_);
        LocaleSequence makeLocaleSequence(uno::Sequence<Locale> const& aUnoLocales_);
        uno::Sequence<OUString> makeIsoSequence(LocaleSequence const& aLocales_);
        uno::Sequence<Locale>   makeUnoSequence(LocaleSequence const& aLocales_);

        inline
        bool equalLocale(Locale const & lhs, Locale const & rhs)
        { return lhs.Language == rhs.Language && lhs.Country == rhs.Country; }

        inline
        bool equalLanguage(Locale const & lhs, Locale const & rhs)
        { return lhs.Language == rhs.Language; }
    // -------------------------------------------------------------------------
        bool designatesAllLocales(Locale const& aLocale_);
        bool designatesAllLocales(LocaleSequence const& aLocales_);
    // -------------------------------------------------------------------------

        /// result of matching a locale against a target locale
        enum  MatchQuality
        {
            MISMATCH = 0,           /// match: locales do not match (must be zero!)
            MATCH_LANGUAGE,         /// match: languages match - country mismatch
            MATCH_LANGUAGE_PLAIN,   /// match: languages match - no country to match
            MATCH_LOCALE,           /// match: full match
            BEST_MATCH = MATCH_LOCALE
        };

        /// compare two locales for 'nearness'
        MatchQuality match(Locale const& aLocale_, Locale const& aTarget_);

    // -------------------------------------------------------------------------
        /// result of matching a Locale against a target sequence of locales
        class MatchResult
        {
            SequencePos     m_nPos;
            MatchQuality    m_eQuality;

        public:
            /// construct a default (no match) result
            MatchResult()
            { reset(); }

            /// construct a result from given parameters - use with care
            MatchResult(SequencePos nPos_, MatchQuality eQuality_)
            : m_nPos( nPos_ )
            , m_eQuality(eQuality_)
            {}

            /// construct an optimum result
            static MatchResult best() { return MatchResult(0,MATCH_LOCALE); }

            /// has there been a match
            bool isMatch() const { return m_eQuality != MISMATCH; }
            /// is this the best match possible ?
            bool isBest() const { return m_nPos == 0 && m_eQuality == MATCH_LOCALE; }

            /// retrieve the position that was matched
            SequencePos position() const { return m_nPos; }
            /// retrieve the quality of match
            MatchQuality quality() const { return m_eQuality; }

            /// assign the given position and quality, if they are an improvement
            bool improve(SequencePos nPos, MatchQuality eQuality_);

            /// reset to no match or best match state
            void reset()
            {
                m_nPos =  c_noPosition;
                m_eQuality = MISMATCH;
            }

            // ---------------------------------------------------------------------
            // comparing MatchResults
            friend bool operator ==(MatchResult const& lhs, MatchResult const& rhs)
            {
                return  lhs.m_nPos == rhs.m_nPos &&
                        lhs.m_eQuality == rhs.m_eQuality;
            }

            // ordering of MatchResults - greater is better
            friend bool operator < (MatchResult const& lhs, MatchResult const& rhs)
            {
                if (lhs.m_nPos > rhs.m_nPos) return true; // greater position is worse
                if (lhs.m_nPos < rhs.m_nPos) return false;

                return (lhs.m_eQuality < rhs.m_eQuality);  // least Quality is worse
            }

        };

        // ---------------------------------------------------------------------
        // derived relational operators
        inline bool operator !=(MatchResult const& lhs, MatchResult const& rhs)
        { return !(lhs == rhs); }
        inline bool operator > (MatchResult const& lhs, MatchResult const& rhs)
        { return rhs < lhs; }
        inline bool operator <= (MatchResult const& lhs, MatchResult const& rhs)
        { return !(rhs < lhs); }
        inline bool operator >=(MatchResult const& lhs, MatchResult const& rhs)
        { return !(lhs < rhs); }

        // ---------------------------------------------------------------------
        /// match a locale against a sequence of locales
        MatchResult match(Locale const& aLocale_, LocaleSequence const& aTarget_);

        /// improve an existing match of a locale against a sequence of locales
        bool improveMatch(MatchResult& rMatch_, Locale const& aLocale_, LocaleSequence const& aTarget_);

        /// match a locale against a sequence of locales for a given quality level
        bool isMatch(Locale const& aLocales, LocaleSequence const& aTarget_, MatchQuality eRequiredQuality_);

    // -------------------------------------------------------------------------
        /// add defaults to a sequence of locales
        void addFallbackLocales(LocaleSequence& aTargetList_);

    // -------------------------------------------------------------------------
        class FindBestLocale
        {
        public:
            /// construct a MatchLocale with no target locale
            FindBestLocale();
            /// construct a MatchLocale with a single target locale
            FindBestLocale(Locale const& aTarget_);
            /// construct a MatchLocale with a sequence of locales
            FindBestLocale(LocaleSequence const& aTarget_);

            /// is there any match ?
            bool isMatch() const { return m_aResult.isMatch(); }

            /// is there an optimum match (so we are done) ?
            bool isBestMatch() const { return m_aResult.isBest(); }

            /// get the best match found
            Locale getBestMatch() const;

            /// get the quality of the best match found
            MatchQuality getMatchQuality() const { return m_aResult.quality(); }

            /// check, if the given locale improves the quality. if it does, accept it
            bool accept(Locale const& aLocale_);

            /// change the target locale (and reset matching)
            void reset(Locale const& aTarget_);

            /// change the target locales (and reset matching)
            void reset(LocaleSequence const& aTarget_);

            /// reset the match result, indicating whether a match is needed at all
            void reset(bool bNeedLocale_ = true);

        private:
            void implSetTarget(LocaleSequence const& aTarget_);

            LocaleSequence  m_aTarget;
            MatchResult     m_aResult;
        };

    } // namespace
// -----------------------------------------------------------------------------

} // namespace

#endif

<commit_msg>INTEGRATION: CWS sb88 (1.9.10); FILE MERGED 2008/06/03 15:29:48 sb 1.9.10.1: #i89553 applied patch by cmc<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: matchlocale.hxx,v $
 * $Revision: 1.10 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

/* PLEASE DON'T DELETE ANY COMMENT LINES, ALSO IT'S UNNECESSARY. */

#ifndef CONFIGMGR_MATCHLOCALE_HXX
#define CONFIGMGR_MATCHLOCALE_HXX

#include <com/sun/star/uno/Sequence.hxx>
#include <com/sun/star/lang/Locale.hpp>

#include <rtl/ustring.hxx>
#include <vector>

namespace configmgr
{
// -----------------------------------------------------------------------------

    namespace localehelper
    {
    // -------------------------------------------------------------------------
        using ::rtl::OUString;
        using ::com::sun::star::lang::Locale;
        namespace uno       = ::com::sun::star::uno;
        namespace lang      = ::com::sun::star::lang;

    // -------------------------------------------------------------------------
        extern char const * const c_sAnyLanguage;
        extern char const * const c_sDefLanguage;

        extern bool isAnyLanguage(OUString const & _sLanguage);
        extern bool isDefaultLanguage(OUString const & _sLanguage);

        extern OUString getAnyLanguage();
        extern OUString getDefaultLanguage();

        extern Locale getAnyLocale();
        extern Locale getDefaultLocale();

    // -------------------------------------------------------------------------
    /// Type for storing a list of Locales
        typedef std::vector< Locale > LocaleSequence;
        typedef LocaleSequence::size_type SequencePos;

        // the max value of SequencePos - marks out-of-range (Value == -1 == ~0)
        SequencePos const c_noPosition = SequencePos(0)-SequencePos(1);

        // conversion helpers
        Locale makeLocale(OUString const& sLocaleName_);
        OUString makeIsoLocale(Locale const& aUnoLocale_);

        LocaleSequence makeLocaleSequence(uno::Sequence<OUString> const& sLocaleNames_);
        uno::Sequence<OUString> makeIsoSequence(LocaleSequence const& aLocales_);

        inline
        bool equalLocale(Locale const & lhs, Locale const & rhs)
        { return lhs.Language == rhs.Language && lhs.Country == rhs.Country; }

        inline
        bool equalLanguage(Locale const & lhs, Locale const & rhs)
        { return lhs.Language == rhs.Language; }
    // -------------------------------------------------------------------------
        bool designatesAllLocales(Locale const& aLocale_);
        bool designatesAllLocales(LocaleSequence const& aLocales_);
    // -------------------------------------------------------------------------

        /// result of matching a locale against a target locale
        enum  MatchQuality
        {
            MISMATCH = 0,           /// match: locales do not match (must be zero!)
            MATCH_LANGUAGE,         /// match: languages match - country mismatch
            MATCH_LANGUAGE_PLAIN,   /// match: languages match - no country to match
            MATCH_LOCALE,           /// match: full match
            BEST_MATCH = MATCH_LOCALE
        };

        /// compare two locales for 'nearness'
        MatchQuality match(Locale const& aLocale_, Locale const& aTarget_);

    // -------------------------------------------------------------------------
        /// result of matching a Locale against a target sequence of locales
        class MatchResult
        {
            SequencePos     m_nPos;
            MatchQuality    m_eQuality;

        public:
            /// construct a default (no match) result
            MatchResult()
            { reset(); }

            /// construct a result from given parameters - use with care
            MatchResult(SequencePos nPos_, MatchQuality eQuality_)
            : m_nPos( nPos_ )
            , m_eQuality(eQuality_)
            {}

            /// construct an optimum result
            static MatchResult best() { return MatchResult(0,MATCH_LOCALE); }

            /// has there been a match
            bool isMatch() const { return m_eQuality != MISMATCH; }
            /// is this the best match possible ?
            bool isBest() const { return m_nPos == 0 && m_eQuality == MATCH_LOCALE; }

            /// retrieve the position that was matched
            SequencePos position() const { return m_nPos; }
            /// retrieve the quality of match
            MatchQuality quality() const { return m_eQuality; }

            /// assign the given position and quality, if they are an improvement
            bool improve(SequencePos nPos, MatchQuality eQuality_);

            /// reset to no match or best match state
            void reset()
            {
                m_nPos =  c_noPosition;
                m_eQuality = MISMATCH;
            }

            // ---------------------------------------------------------------------
            // comparing MatchResults
            friend bool operator ==(MatchResult const& lhs, MatchResult const& rhs)
            {
                return  lhs.m_nPos == rhs.m_nPos &&
                        lhs.m_eQuality == rhs.m_eQuality;
            }

            // ordering of MatchResults - greater is better
            friend bool operator < (MatchResult const& lhs, MatchResult const& rhs)
            {
                if (lhs.m_nPos > rhs.m_nPos) return true; // greater position is worse
                if (lhs.m_nPos < rhs.m_nPos) return false;

                return (lhs.m_eQuality < rhs.m_eQuality);  // least Quality is worse
            }

        };

        // ---------------------------------------------------------------------
        // derived relational operators
        inline bool operator !=(MatchResult const& lhs, MatchResult const& rhs)
        { return !(lhs == rhs); }
        inline bool operator > (MatchResult const& lhs, MatchResult const& rhs)
        { return rhs < lhs; }
        inline bool operator <= (MatchResult const& lhs, MatchResult const& rhs)
        { return !(rhs < lhs); }
        inline bool operator >=(MatchResult const& lhs, MatchResult const& rhs)
        { return !(lhs < rhs); }

        /// improve an existing match of a locale against a sequence of locales
        bool improveMatch(MatchResult& rMatch_, Locale const& aLocale_, LocaleSequence const& aTarget_);

        /// match a locale against a sequence of locales for a given quality level
        bool isMatch(Locale const& aLocales, LocaleSequence const& aTarget_, MatchQuality eRequiredQuality_);

    // -------------------------------------------------------------------------
        /// add defaults to a sequence of locales
        void addFallbackLocales(LocaleSequence& aTargetList_);

    // -------------------------------------------------------------------------
        class FindBestLocale
        {
        public:
            /// construct a MatchLocale with a single target locale
            FindBestLocale(Locale const& aTarget_);

            /// is there any match ?
            bool isMatch() const { return m_aResult.isMatch(); }

            /// is there an optimum match (so we are done) ?
            bool isBestMatch() const { return m_aResult.isBest(); }

            /// get the quality of the best match found
            MatchQuality getMatchQuality() const { return m_aResult.quality(); }

            /// check, if the given locale improves the quality. if it does, accept it
            bool accept(Locale const& aLocale_);

            /// reset the match result, indicating whether a match is needed at all
            void reset(bool bNeedLocale_ = true);

        private:
            void implSetTarget(LocaleSequence const& aTarget_);

            LocaleSequence  m_aTarget;
            MatchResult     m_aResult;
        };

    } // namespace
// -----------------------------------------------------------------------------

} // namespace

#endif

<|endoftext|>


<commit_before>/*
 * Copyright (C) 2014 Open Source Robotics Foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
*/

#include <robot_msgs/stringmsg.pb.h>
#include <sys/types.h>
#include <chrono>
#include <string>
#include "ignition/transport/Node.hh"
#include "gtest/gtest.h"

using namespace ignition;

std::string topic = "/foo";
std::string data = "bar";

//////////////////////////////////////////////////
/// \brief Provide a service.
void srvEcho(const std::string &_topic, const robot_msgs::StringMsg &_req,
  robot_msgs::StringMsg &_rep, bool &_result)
{
  assert(_topic != "");

  EXPECT_EQ(_req.data(), data);
  _rep.set_data(_req.data());
  _result = true;
}

//////////////////////////////////////////////////
void runReplier()
{
  // srvExecuted = false;
  transport::Node node;
  std::this_thread::sleep_for(std::chrono::milliseconds(100));
  EXPECT_TRUE(node.Advertise(topic, srvEcho));

  int i = 0;
  while (i < 100)
  {
    std::this_thread::sleep_for(std::chrono::milliseconds(10));
    ++i;
  }
}

//////////////////////////////////////////////////
/// \brief Three different nodes running in two different processes. In the
/// subscriber processs there are two nodes. Both should receive the message.
/// After some time one of them unsubscribe. After that check that only one
/// node receives the message.
TEST(twoProcSrvCallSync, SrvTwoProcs)
{
  unsigned int timeout = 500;
  pid_t pid = fork();

  if (pid == 0)
    runReplier();
  else
  {
    robot_msgs::StringMsg req;
    robot_msgs::StringMsg rep;
    bool result;

    req.set_data(data);

    transport::Node node1;
    EXPECT_TRUE(node1.Request(topic, req, timeout, rep, result));
    EXPECT_EQ(req.data(), rep.data());
    EXPECT_TRUE(result);

    auto t1 = std::chrono::system_clock::now();
    EXPECT_FALSE(node1.Request("unknown_service", req, timeout, rep, result));
    auto t2 = std::chrono::system_clock::now();

    double elapsed =
      std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1).count();

    // Check if the elapsed time was close to the timeout.
    EXPECT_NEAR(elapsed, timeout, 1.0);

    // Wait for the child process to return.
    int status;
    waitpid(pid, &status, 0);
  }
}

//////////////////////////////////////////////////
int main(int argc, char **argv)
{
  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}
<commit_msg>Removing sleep in service call test (not needed).<commit_after>/*
 * Copyright (C) 2014 Open Source Robotics Foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
*/

#include <robot_msgs/stringmsg.pb.h>
#include <sys/types.h>
#include <chrono>
#include <string>
#include "ignition/transport/Node.hh"
#include "gtest/gtest.h"

using namespace ignition;

std::string topic = "/foo";
std::string data = "bar";

//////////////////////////////////////////////////
/// \brief Provide a service.
void srvEcho(const std::string &_topic, const robot_msgs::StringMsg &_req,
  robot_msgs::StringMsg &_rep, bool &_result)
{
  assert(_topic != "");

  EXPECT_EQ(_req.data(), data);
  _rep.set_data(_req.data());
  _result = true;
}

//////////////////////////////////////////////////
void runReplier()
{
  // srvExecuted = false;
  transport::Node node;
  EXPECT_TRUE(node.Advertise(topic, srvEcho));

  int i = 0;
  while (i < 100)
  {
    std::this_thread::sleep_for(std::chrono::milliseconds(10));
    ++i;
  }
}

//////////////////////////////////////////////////
/// \brief Three different nodes running in two different processes. In the
/// subscriber processs there are two nodes. Both should receive the message.
/// After some time one of them unsubscribe. After that check that only one
/// node receives the message.
TEST(twoProcSrvCallSync, SrvTwoProcs)
{
  unsigned int timeout = 500;
  pid_t pid = fork();

  if (pid == 0)
    runReplier();
  else
  {
    robot_msgs::StringMsg req;
    robot_msgs::StringMsg rep;
    bool result;

    req.set_data(data);

    transport::Node node1;
    EXPECT_TRUE(node1.Request(topic, req, timeout, rep, result));
    EXPECT_EQ(req.data(), rep.data());
    EXPECT_TRUE(result);

    auto t1 = std::chrono::system_clock::now();
    EXPECT_FALSE(node1.Request("unknown_service", req, timeout, rep, result));
    auto t2 = std::chrono::system_clock::now();

    double elapsed =
      std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1).count();

    // Check if the elapsed time was close to the timeout.
    EXPECT_NEAR(elapsed, timeout, 1.0);

    // Wait for the child process to return.
    int status;
    waitpid(pid, &status, 0);
  }
}

//////////////////////////////////////////////////
int main(int argc, char **argv)
{
  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}
<|endoftext|>


<commit_before>#ifndef test_elementretrieveallattributes
#define test_elementretrieveallattributes

/*
This C++ source file was generated by for Arabica
and is a derived work from the source document.
The source document contained the following notice:

Copyright (c) 2001 World Wide Web Consortium,
(Massachusetts Institute of Technology, Institut National de
Recherche en Informatique et en Automatique, Keio University). All
Rights Reserved. This program is distributed under the W3C's Software
Intellectual Property License. This program is distributed in the
hope that it will be useful, but WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.
See W3C License http://www.w3.org/Consortium/Legal/ for more details.

*/
/**
 *     The "getAttributes()" method(Node Interface) may
 *    be used to retrieve the set of all attributes of an
 *    element.
 *
 *    Create a list of all the attributes of the last child
 *    of the first employee by using the "getAttributes()"
 *    method.  Examine the length of the attribute list.
 *    This test uses the "getLength()" method from the
 *    NameNodeMap interface.
* @author NIST
* @author Mary Brady
* @see http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-core#ID-84CF096
* @see http://lists.w3.org/Archives/Public/www-dom-ts/2002Mar/0002.html
*/

template<class string_type, class string_adaptor>
class elementretrieveallattributes : public DOMTestCase<string_type, string_adaptor>
{
    typedef DOMTestCase<string_type, string_adaptor> baseT;
   public:
     elementretrieveallattributes(std::string name) : baseT(name)
     {

       //   check if loaded documents are supported for content type
       const std::string contentType = baseT::getContentType();
    baseT::preload(contentType, "staff", false);
    }

  typedef typename Arabica::DOM::DOMImplementation<string_type, string_adaptor>  DOMImplementation;
  typedef typename Arabica::DOM::Document<string_type, string_adaptor> Document;
  typedef typename Arabica::DOM::DocumentType<string_type, string_adaptor> DocumentType;
  typedef typename Arabica::DOM::DocumentFragment<string_type, string_adaptor> DocumentFragment;
  typedef typename Arabica::DOM::Node<string_type, string_adaptor> Node;
  typedef typename Arabica::DOM::Element<string_type, string_adaptor> Element;
  typedef typename Arabica::DOM::Attr<string_type, string_adaptor> Attr;
  typedef typename Arabica::DOM::NodeList<string_type, string_adaptor> NodeList;
  typedef typename Arabica::DOM::NamedNodeMap<string_type, string_adaptor> NamedNodeMap;
  typedef typename Arabica::DOM::Entity<string_type, string_adaptor> Entity;
  typedef typename Arabica::DOM::EntityReference<string_type, string_adaptor> EntityReference;
  typedef typename Arabica::DOM::CharacterData<string_type, string_adaptor> CharacterData;
  typedef typename Arabica::DOM::CDATASection<string_type, string_adaptor> CDATASection;
  typedef typename Arabica::DOM::Text<string_type, string_adaptor> Text;
  typedef typename Arabica::DOM::Comment<string_type, string_adaptor> Comment;
  typedef typename Arabica::DOM::ProcessingInstruction<string_type, string_adaptor> ProcessingInstruction;
  typedef typename Arabica::DOM::Notation<string_type, string_adaptor> Notation;

  typedef typename Arabica::DOM::DOMException DOMException;
  typedef string_type String;
  typedef string_adaptor SA;
  typedef bool boolean;

   /*
    * Runs the test case.
    */
   void runTest()
   {
      Document doc;
      NodeList addressList;
      Node testAddress;
      NamedNodeMap attributes;
      doc = (Document) baseT::load("staff", false);
      addressList = doc.getElementsByTagName(SA::construct_from_utf8("address"));
      testAddress = addressList.item(0);
      attributes = testAddress.getAttributes();
      baseT::assertSize(2, attributes, __LINE__, __FILE__);

   }

   /*
    *  Gets URI that identifies the test.
    */
   std::string getTargetURI() const
   {
      return "http://www.w3.org/2001/DOM-Test-Suite/level1/core/elementretrieveallattributes";
   }
};

#endif
<commit_msg>skip if no external DTD<commit_after>#ifndef test_elementretrieveallattributes
#define test_elementretrieveallattributes

/*
This C++ source file was generated by for Arabica
and is a derived work from the source document.
The source document contained the following notice:

Copyright (c) 2001 World Wide Web Consortium,
(Massachusetts Institute of Technology, Institut National de
Recherche en Informatique et en Automatique, Keio University). All
Rights Reserved. This program is distributed under the W3C's Software
Intellectual Property License. This program is distributed in the
hope that it will be useful, but WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.
See W3C License http://www.w3.org/Consortium/Legal/ for more details.

*/
/**
 *     The "getAttributes()" method(Node Interface) may
 *    be used to retrieve the set of all attributes of an
 *    element.
 *
 *    Create a list of all the attributes of the last child
 *    of the first employee by using the "getAttributes()"
 *    method.  Examine the length of the attribute list.
 *    This test uses the "getLength()" method from the
 *    NameNodeMap interface.
* @author NIST
* @author Mary Brady
* @see http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-core#ID-84CF096
* @see http://lists.w3.org/Archives/Public/www-dom-ts/2002Mar/0002.html
*/

template<class string_type, class string_adaptor>
class elementretrieveallattributes : public DOMTestCase<string_type, string_adaptor>
{
    typedef DOMTestCase<string_type, string_adaptor> baseT;
   public:
     elementretrieveallattributes(std::string name) : baseT(name)
     {

       //   check if loaded documents are supported for content type
       const std::string contentType = baseT::getContentType();
    baseT::preload(contentType, "staff", false);
    }

  typedef typename Arabica::DOM::DOMImplementation<string_type, string_adaptor>  DOMImplementation;
  typedef typename Arabica::DOM::Document<string_type, string_adaptor> Document;
  typedef typename Arabica::DOM::DocumentType<string_type, string_adaptor> DocumentType;
  typedef typename Arabica::DOM::DocumentFragment<string_type, string_adaptor> DocumentFragment;
  typedef typename Arabica::DOM::Node<string_type, string_adaptor> Node;
  typedef typename Arabica::DOM::Element<string_type, string_adaptor> Element;
  typedef typename Arabica::DOM::Attr<string_type, string_adaptor> Attr;
  typedef typename Arabica::DOM::NodeList<string_type, string_adaptor> NodeList;
  typedef typename Arabica::DOM::NamedNodeMap<string_type, string_adaptor> NamedNodeMap;
  typedef typename Arabica::DOM::Entity<string_type, string_adaptor> Entity;
  typedef typename Arabica::DOM::EntityReference<string_type, string_adaptor> EntityReference;
  typedef typename Arabica::DOM::CharacterData<string_type, string_adaptor> CharacterData;
  typedef typename Arabica::DOM::CDATASection<string_type, string_adaptor> CDATASection;
  typedef typename Arabica::DOM::Text<string_type, string_adaptor> Text;
  typedef typename Arabica::DOM::Comment<string_type, string_adaptor> Comment;
  typedef typename Arabica::DOM::ProcessingInstruction<string_type, string_adaptor> ProcessingInstruction;
  typedef typename Arabica::DOM::Notation<string_type, string_adaptor> Notation;

  typedef typename Arabica::DOM::DOMException DOMException;
  typedef string_type String;
  typedef string_adaptor SA;
  typedef bool boolean;

   /*
    * Runs the test case.
    */
   void runTest()
   {
      Document doc;
      NodeList addressList;
      Node testAddress;
      NamedNodeMap attributes;
      DocumentType docType;
      NamedNodeMap notations;
      Notation notationNode;
      String notationName;
      doc = (Document) baseT::load("staff", false);
      docType = doc.getDoctype();
      baseT::assertNotNull(docType, __LINE__, __FILE__);
      notations = docType.getNotations();
      baseT::assertNotNull(notations, __LINE__, __FILE__);
      notationNode = (Notation) notations.getNamedItem(SA::construct_from_utf8("notation1"));
      baseT::skipIfNull(notationNode);
      addressList = doc.getElementsByTagName(SA::construct_from_utf8("address"));
      testAddress = addressList.item(0);
      attributes = testAddress.getAttributes();
      baseT::assertSize(2, attributes, __LINE__, __FILE__);

   }

   /*
    *  Gets URI that identifies the test.
    */
   std::string getTargetURI() const
   {
      return "http://www.w3.org/2001/DOM-Test-Suite/level1/core/elementretrieveallattributes";
   }
};

#endif
<|endoftext|>


<commit_before>#include "photoeffects.hpp"

using namespace cv;

Point findFarthestPoint(Point vector, Mat& image)
{
    int a,b;
    if(vector.x<=0)
    {
        a=0;
    }
    else
    {
        a=1;
    }

    if(vector.y<=0)
    {
        b=0;
    }
    else
    {
        b=1;
    }

    return Point(a*image.cols, b*image.rows);
}

int fadeColor(InputArray src, OutputArray dst,
              Point startPoint, Point endPoint)
{

    CV_Assert(!src.empty());
    Mat image=src.getMat();
    CV_Assert(image.type() == CV_8UC1 || image.type() == CV_8UC3);
    CV_Assert(startPoint.x>=0 && startPoint.x<image.cols);
    CV_Assert(endPoint.x>=0 && endPoint.x<image.cols);
    CV_Assert(startPoint.y>=0 && startPoint.y<image.rows);
    CV_Assert(endPoint.y>=0 && endPoint.y<image.rows);
    CV_Assert(startPoint!=endPoint);
    // perpendicular to the line
    Point perpendicular;
    perpendicular.x=endPoint.x-startPoint.x;
    perpendicular.y=endPoint.y-startPoint.y;
    //line equation: A*x+By+C=0

    int A=perpendicular.y;
    int B=perpendicular.x;
    int C=-startPoint.y*A-B*startPoint.x;
    //find the most distant point from the line
    Point farthestPoint=findFarthestPoint(perpendicular, image);

    int maxDistance=abs(A*farthestPoint.y+B*farthestPoint.x+C);
    //one channel
    if(src.type() == CV_8UC1)
    {
        for(int i=0;i<image.rows;i++)
            for(int j=0;j<image.cols;j++)
            {
                int distance=A*i+B*j+C;
                //change pixels only in the direction of the perpendicular
                if(distance>0)
                {
                    int channelValue=image.at<uchar>(i,j);
                    channelValue*=(maxDistance-distance);
                    channelValue+=255*distance;
                    channelValue/=maxDistance;
                    image.at<uchar>(i,j)=channelValue;
                }
            }
        image.copyTo(dst);
        return 0;
    }

    //three channel
    for(int i=0;i<image.rows;i++)
        for(int j=0;j<image.cols;j++)
        {
            int distance=A*i+B*j+C;
            //change pixels only in the direction of the perpendicular
            if(distance>0)
            {
                for(int n=0;n<3;n++)
                {
                    int channelValue=image.at<Vec3b>(i,j)[n];
                    channelValue*=(maxDistance-distance);
                    channelValue+=255*distance;
                    channelValue/=maxDistance;
                    image.at<Vec3b>(i,j)[n]=channelValue;
                }
            }
        }
    image.copyTo(dst);
    return 0;
}
<commit_msg>attempt to improve<commit_after>#include "photoeffects.hpp"

using namespace cv;

Point findFarthestPoint(Point vector, Mat& image)
{
    int a,b;
    if(vector.x<=0)
    {
        a=0;
    }
    else
    {
        a=1;
    }

    if(vector.y<=0)
    {
        b=0;
    }
    else
    {
        b=1;
    }

    return Point(a*image.cols, b*image.rows);
}

int fadeColor(InputArray src, OutputArray dst,
              Point startPoint, Point endPoint)
{

    CV_Assert(!src.empty());
    Mat image=src.getMat();
    CV_Assert(image.type() == CV_8UC1 || image.type() == CV_8UC3);
    CV_Assert(startPoint.x>=0 && startPoint.x<image.cols);
    CV_Assert(endPoint.x>=0 && endPoint.x<image.cols);
    CV_Assert(startPoint.y>=0 && startPoint.y<image.rows);
    CV_Assert(endPoint.y>=0 && endPoint.y<image.rows);
    CV_Assert(startPoint!=endPoint);
    // perpendicular to the line
    Point perpendicular;
    perpendicular.x=endPoint.x-startPoint.x;
    perpendicular.y=endPoint.y-startPoint.y;
    //line equation: A*x+By+C=0

    int A=perpendicular.y;
    int B=perpendicular.x;
    int C=-startPoint.y*A-B*startPoint.x;
    //find the most distant point from the line
    Point farthestPoint=findFarthestPoint(perpendicular, image);

    int maxDistance=abs(A*farthestPoint.y+B*farthestPoint.x+C);

    int numChannel=image.channels();
    dst.create(image.size(),image.type());
    Mat dstMat=dst.getMat();
    for(int i=0;i<image.rows;i++)
    {
        uchar* line( image.ptr<uchar>(i) );
        uchar* dstLine(dstMat.ptr<uchar>(i) );
        for(int j=0;j<image.cols;j++)
        {
            int distance=A*i+B*j+C;
            //change pixels only in the direction of the perpendicular
            if(distance>0)
            {

                for(int n=0;n<numChannel;n++)
                {
                    int channelValue=line[numChannel*j+n];
                    channelValue*=(maxDistance-distance);
                    channelValue+=255*distance;
                    channelValue/=maxDistance;
                    dstLine[numChannel*j+n]=channelValue;
                }
            }
        }
    }
    return 0;
}
<|endoftext|>