Example #1
0
  void test_id() {
    Tuple* t1 = Tuple::create(state, 2);
    Tuple* t2 = Tuple::create(state, 2);

    Integer* id1 = t1->id(state);
    Integer* id2 = t2->id(state);

    TS_ASSERT(id1->to_native() > 0);
    TS_ASSERT(id2->to_native() > 0);

    TS_ASSERT_DIFFERS(id1, id2)

    TS_ASSERT_EQUALS(id1, t1->id(state));

    Integer* id3 = Fixnum::from(33)->id(state);
    TS_ASSERT_DIFFERS(id3, id1);

    Integer* id4 = Fixnum::from(33)->id(state);
    TS_ASSERT_EQUALS(id3, id4);
    TS_ASSERT(id4->to_native() % 2 == 1);

    Integer* id5 = Fixnum::from(34)->id(state);
    TS_ASSERT_DIFFERS(id4, id5);
    TS_ASSERT(id5->to_native() % 2 == 1);
  }
Example #2
0
  void test_hash() {
    TS_ASSERT_EQUALS(Qnil->hash(state), Qnil->hash(state));
    TS_ASSERT(Qnil->hash(state) > 0);

    TS_ASSERT_EQUALS(Qtrue->hash(state), Qtrue->hash(state));
    TS_ASSERT(Qtrue->hash(state) > 0);

    TS_ASSERT_EQUALS(Qfalse->hash(state), Qfalse->hash(state));
    TS_ASSERT(Qfalse->hash(state) > 0);

    TS_ASSERT_DIFFERS(Fixnum::from(1)->hash(state), Fixnum::from(2)->hash(state));
    TS_ASSERT_DIFFERS(Fixnum::from(-1)->hash(state), Fixnum::from(1)->hash(state));
    TS_ASSERT_DIFFERS(Fixnum::from(-2)->hash(state), Fixnum::from(-1)->hash(state));

    TS_ASSERT_EQUALS(Bignum::from(state, (native_int)13)->hash(state), Bignum::from(state, (native_int)13)->hash(state));
    TS_ASSERT(Bignum::from(state, (native_int)13)->hash(state) > 0);

    TS_ASSERT_EQUALS(Float::create(state, 15.0)->hash(state), Float::create(state, 15.0)->hash(state));
    TS_ASSERT(Float::create(state, 15.0)->hash(state) > 0);

    Object* obj = util_new_object();
    TS_ASSERT_EQUALS(obj->hash(state), obj->hash(state));
    TS_ASSERT(obj->hash(state) > 0);

    TS_ASSERT_EQUALS(String::create(state, "blah")->hash(state), String::create(state, "blah")->hash(state));
    TS_ASSERT(String::create(state, "blah")->hash(state) > 0);
  }
Example #3
0
void TestBootstrapAllocator::testSingleton(void)
{
    BootstrapAllocator *a1, *a2;

    a1 = BootstrapAllocator::getInstance();
    TS_ASSERT_DIFFERS(a1, (void*)NULL);
    a2 = BootstrapAllocator::getInstance();
    TS_ASSERT_DIFFERS(a2, (void*)NULL);

    TS_ASSERT_EQUALS(a1, a2);
}
    // test that checks RunDoNotUpdate does not do anything permanent on the class,
    // by checking by doing things repeatedly, and changing the order, makes no
    // difference
    void TestRunDoesNotUpdate()
    {
        NhsModelWithBackwardSolver system;

        double Ca_I = GetSampleCaIValue();
        system.SetIntracellularCalciumConcentration(Ca_I);

        // get initial active tension
        double init_Ta = system.GetActiveTension();

        system.SetStretchAndStretchRate(0.6, 0.1);
        system.RunDoNotUpdate(0, 1, 0.01);

        double Ta1 = system.GetNextActiveTension();

        system.SetStretchAndStretchRate(0.6, 0.2);
        system.RunDoNotUpdate(0, 1, 0.01);

        double Ta2 = system.GetNextActiveTension();

        // note that lam/end time etc must be large enough for there
        // to be non-zero Ta at the next time
        TS_ASSERT_DIFFERS(init_Ta, Ta1);
        TS_ASSERT_DIFFERS(init_Ta, Ta2);

        system.SetStretchAndStretchRate(0.6, 0.2);
        system.RunDoNotUpdate(0, 1, 0.01);

        double should_be_Ta2 = system.GetNextActiveTension();

        system.SetStretchAndStretchRate(0.6, 0.1);
        system.RunDoNotUpdate(0, 1, 0.01);

        double should_be_Ta1 = system.GetNextActiveTension();

        TS_ASSERT_DELTA(Ta1, should_be_Ta1, 1e-16); // on one system getting differences of 1e-22 for some reason

        TS_ASSERT_EQUALS(Ta2, should_be_Ta2);

        system.SetStretchAndStretchRate(0.6, 0.1);
        system.RunDoNotUpdate(0, 1, 0.01);

        double should_also_be_Ta1 = system.GetNextActiveTension();

        system.SetStretchAndStretchRate(0.6, 0.2);
        system.RunDoNotUpdate(0, 1, 0.01);

        double should_also_be_Ta2 = system.GetNextActiveTension();

        TS_ASSERT_EQUALS(Ta1, should_also_be_Ta1);
        TS_ASSERT_EQUALS(Ta2, should_also_be_Ta2);
    }
    void TestSolveCellSystemsInclUpdateVoltage() throw(Exception)
    {
        HeartConfig::Instance()->Reset();
        TetrahedralMesh<1,1> mesh;
        mesh.ConstructRegularSlabMesh(1.0, 1.0); // [0,1] with h=1.0, ie 2 node mesh

        MyCardiacCellFactory cell_factory;
        cell_factory.SetMesh(&mesh);

        MonodomainTissue<1> monodomain_tissue( &cell_factory );

        Vec voltage = PetscTools::CreateAndSetVec(2, -81.4354); // something that isn't resting potential
        monodomain_tissue.SolveCellSystems(voltage, 0, 1, false); // solve for 1ms without updating the voltage

        if (mesh.GetDistributedVectorFactory()->IsGlobalIndexLocal(0))
        {
            TS_ASSERT_DELTA(monodomain_tissue.GetCardiacCell(0)->GetVoltage(), -81.4354, 1e-3);
        }

        if (mesh.GetDistributedVectorFactory()->IsGlobalIndexLocal(1))
        {
            TS_ASSERT_DELTA(monodomain_tissue.GetCardiacCell(1)->GetVoltage(), -81.4354, 1e-3);
        }

        Vec voltage2 = PetscTools::CreateAndSetVec(2, -75);
        monodomain_tissue.SolveCellSystems(voltage2, 1, 2, true); // solve another ms, using this new voltage, but now updating the voltage too
        ReplicatableVector voltage2_repl(voltage2); // should have changed following solve

        // check the new voltage in the cell is NEAR -75 (otherwise the passed in voltage wasn't used, but
        // NOT EXACTLY -75, ie that the voltage was solved for.
        if (mesh.GetDistributedVectorFactory()->IsGlobalIndexLocal(0))
        {
            // check has been updated
            TS_ASSERT_DIFFERS(monodomain_tissue.GetCardiacCell(0)->GetVoltage(), -75);
            // check near -75
            TS_ASSERT_DELTA(monodomain_tissue.GetCardiacCell(0)->GetVoltage(), -75, 2.0); // within 2mV
            // check the passed in voltage was updated
            TS_ASSERT_DELTA(voltage2_repl[0], monodomain_tissue.GetCardiacCell(0)->GetVoltage(), 1e-10);
        }
        if (mesh.GetDistributedVectorFactory()->IsGlobalIndexLocal(1))
        {
            TS_ASSERT_DIFFERS(monodomain_tissue.GetCardiacCell(1)->GetVoltage(), -75);
            TS_ASSERT_DELTA(monodomain_tissue.GetCardiacCell(1)->GetVoltage(), -75, 2.0); // within 2mV
            TS_ASSERT_DELTA(voltage2_repl[1], monodomain_tissue.GetCardiacCell(1)->GetVoltage(), 1e-10);
        }

        PetscTools::Destroy(voltage);
        PetscTools::Destroy(voltage2);
    }
Example #6
0
  void testfindKeyinArgMap ( void )
  {
    TEST_HEADER;

    ArgParse argParse("intro", "outro");

    argParse.addArgument("-s, --unix-rocket",
                        "Unix rocket",
                        ArgParse::STRING );

    TS_ASSERT_DIFFERS ( argParse.findKeyinArgMap("-s"), argParse.m_params.end() );
    TS_ASSERT_DIFFERS ( argParse.findKeyinArgMap("--unix-rocket"), argParse.m_params.end() );

    TS_ASSERT_EQUALS( argParse.findKeyinArgMap("-u"), argParse.m_params.end() );
    TS_ASSERT_EQUALS( argParse.findKeyinArgMap("-r"), argParse.m_params.end() );
  }
Example #7
0
 void test_read_standard_workbook_from_fileobj()
 {
     auto path = PathHelper::GetDataDirectory("/genuine/empty.xlsx");
     std::ifstream fo(path, std::ios::binary);
     auto wb = xlnt::load_workbook(path);
     TS_ASSERT_DIFFERS(standard_workbook(), nullptr);
 }
    // Helper that verifies the two query handler trees have identical
    // structure. Note that we don't check that they are fully identical, just
    // that the replicated data matches the original structure.
    void verifyTreesMatch() {
        // The trees may not be replicated exactly, we really just
        // need to make sure they share the same structure and we want
        // to make sure we check it by traversing the actual data
        // structure (as opposed to, e.g., getting it from the
        // location service cache).
        typedef std::map<ObjectID, ObjectID> ParentMap;
        ParentMap orig_pm, replicated_pm;
        for(QueryHandler::NodeIterator orig_it = orig_handler->nodesBegin(), replicated_it = replicated_handler->nodesBegin();
            orig_it != orig_handler->nodesEnd() && replicated_it != replicated_handler->nodesEnd();
            orig_it++, replicated_it++)
        {
            orig_pm.insert(std::make_pair(orig_it.id(), orig_it.parentId()));
            replicated_pm.insert(std::make_pair(replicated_it.id(), replicated_it.parentId()));
        }

        // Then check that they really match
        TS_ASSERT_EQUALS(orig_pm.size(), replicated_pm.size());
        for(ParentMap::const_iterator replicated_it = replicated_pm.begin();
            replicated_it != replicated_pm.end();
            replicated_it++)
        {
            ParentMap::const_iterator orig_it = orig_pm.find(replicated_it->first);
            TS_ASSERT_DIFFERS(orig_it, orig_pm.end());
            if (orig_it == orig_pm.end()) continue;
            TS_ASSERT_EQUALS(orig_it->second, replicated_it->second);
        }
    }
Example #9
0
void TestBootstrapAllocator::testReset(void)
{
    uint32_t *chunk;
    BootstrapAllocator *ba;

    ba = BootstrapAllocator::getInstance();
    TS_ASSERT_DIFFERS(ba, (void*)NULL);

    chunk = (uint32_t*) ba->alloc(32);
    TS_ASSERT_DIFFERS(chunk, (void*)NULL);
    *chunk = 0xDEADBEEFu;

    BootstrapAllocator::reset();
    TS_ASSERT_DIFFERS(*chunk, 0xDEADBEEFu);

    chunk = (uint32_t*) ba->alloc((uint32_t) ba->heapSize());
    TS_ASSERT_DIFFERS(chunk, (void*)NULL);
}
Example #10
0
 void test_read_worksheet()
 {
     auto wb = standard_workbook();
     auto sheet2 = wb.get_sheet_by_name("Sheet2 - Numbers");
     TS_ASSERT_DIFFERS(sheet2, nullptr);
     TS_ASSERT_EQUALS("This is cell G5", sheet2.get_cell("G5").get_value<std::string>());
     TS_ASSERT_EQUALS(18, sheet2.get_cell("D18").get_value<int>());
     TS_ASSERT_EQUALS(true, sheet2.get_cell("G9").get_value<bool>());
     TS_ASSERT_EQUALS(false, sheet2.get_cell("G10").get_value<bool>());
 }
Example #11
0
 void testCopyConstructor1()
 {
   JxN1 source("ABC");
   JxN1 stdfStr(source);
   source = "CBA";
   TS_ASSERT_EQUALS(stdfStr.to_string(), "ABC");
   TS_ASSERT_EQUALS(stdfStr.storage(), 2u);
   TS_ASSERT_DIFFERS(stdfStr.to_string(), source.to_string());
   TS_ASSERT_EQUALS(source.to_string(), "CBA");
 }
Example #12
0
	// SYNOPSIS:
	// result should be 0 since the range specified is 1, and we are comparing two characters
	void test2Incorrect() {
		char const  data[6] = {'X','G','X','G','X','G'};
		
      	int  const test_len = 1;

		int  const   result = count_if_followed_by (data, test_len, 'X', 'G');

		TS_ASSERT_DIFFERS(result, 0);

	}
Example #13
0
 void testClone1()
 {
   JxN1 source("ABC");
   DataType::DataTypeSharedPtr stdfStr = source.clone();
   TS_ASSERT_EQUALS(stdfStr->to_string(), "ABC");
   TS_ASSERT_EQUALS(stdfStr->storage(), 2u);
   TS_ASSERT_EQUALS(stdfStr->to_string(), source.to_string());
   source = "CBA";
   TS_ASSERT_EQUALS(source.to_string(), "CBA");
   TS_ASSERT_DIFFERS(stdfStr->to_string(), source.to_string());
 }
Example #14
0
 void testClone1()
 {
   Sn stdfStr("ABC");
   TS_ASSERT_SAME_DATA(stdfStr.mData+2, "ABC", 3);
   TS_ASSERT_EQUALS(stdfStr.storage(), 5u);
   TS_ASSERT_EQUALS(stdfStr.max_size(), 65535u);
   DataType::DataTypeSharedPtr stdfStrP = stdfStr.clone();
   TS_ASSERT(stdfStrP->to_string() == "ABC");
   TS_ASSERT_EQUALS(stdfStrP->storage(), 5u);
   TS_ASSERT_DIFFERS(stdfStrP.get(), &stdfStr);
 }
Example #15
0
  void test_dup_ignores_singleton_class() {
    Tuple* tup = Tuple::create(state, 1);
    tup->put(state, 0, Qtrue);

    // Force it to exist.
    tup->singleton_class(state);

    Tuple* tup2 = as<Tuple>(tup->duplicate(state));

    TS_ASSERT(!try_as<SingletonClass>(tup2->klass_));

    TS_ASSERT_DIFFERS(tup->singleton_class(state), tup2->singleton_class(state));
  }
Example #16
0
    /**
     * Initializes a matrix with the specified id.
     *   Global matrices are set to the corresponding values,
     *   local matrices initialized with random values.
     *
     * @param i_id id of the matrix {0, .., 51} -> flux matrix, {52} -> jacobian (flux solver), {53, 54, 55} -> stiffness matrices, {56, 57, 58} -> transposed stiffness matrices, {59} -> jacobian (star matrix)
     * @param i_numberOfRows number of rows.
     * @param i_numberOfColumns number of columns.
     * @param o_matrix matrix, which is initialized.
     **/
    void initializeMatrix( unsigned int i_id,
                           unsigned int i_numberOfRows,
                           unsigned int i_numberOfColumns,
                           real*        o_matrix ) {
      // assert the matrices have been read
      assert( m_matrixIds.size() > 0 );

      // get the position of our matrix
      unsigned int l_position;
      for( l_position = 0; l_position < m_matrixIds.size(); l_position++ ) {
        if( i_id == m_matrixIds[l_position] ) {
          break;
        }
        else {
          // matrix with the given id couldn't be found
          TS_ASSERT_DIFFERS( l_position, m_matrixIds.size() -1 );
        }
      }

      // flux solver -> random values
      if( i_id == 52 ) {
        // assert correct matrix id
        TS_ASSERT_EQUALS( m_matrixIds[l_position], 52 );
        setRandomValues( i_numberOfRows * i_numberOfColumns,
                         o_matrix );
      } 
      // flux matrix, stiffness matrix or star matrix
      else {
        std::fill( o_matrix, o_matrix + i_numberOfRows * i_numberOfColumns, 0 );
        for( unsigned int l_element = 0; l_element < m_matrixRows[l_position].size(); l_element++ ) {
          // assert that we can save the non-zero element
          TS_ASSERT_LESS_THAN_EQUALS( m_matrixRows[l_position][l_element],    i_numberOfRows);
          TS_ASSERT_LESS_THAN_EQUALS( m_matrixColumns[l_position][l_element], i_numberOfColumns);

          unsigned int l_denseIndex = (m_matrixColumns[l_position][l_element]-1) * i_numberOfRows + (m_matrixRows[l_position][l_element]-1);

          // assert this a valid index
          TS_ASSERT_LESS_THAN( l_denseIndex, i_numberOfRows*i_numberOfColumns );

          if( i_id == 59 ) { // star matrix
            o_matrix[ l_denseIndex ] = ((real)rand()/(real)RAND_MAX)*10.0;
          }
          else if( i_id >= 56 && i_id <= 58 ) { // add minus-sign for time kernel
            o_matrix[ l_denseIndex ] = -m_matrixValues[l_position][l_element];
          }
          else{ // flux or stiffness matrix
            o_matrix[ l_denseIndex ] =  m_matrixValues[l_position][l_element];
          }
        }
      }
    }
Example #17
0
 void test_read_standalone_worksheet()
 {
     auto path = PathHelper::GetDataDirectory("/reader/sheet2.xml");
     xlnt::workbook wb;
     xlnt::worksheet ws(wb);
     {
         std::ifstream handle(path);
         ws = xlnt::read_worksheet(handle, wb, "Sheet 2", {"hello"}, {});
     }
     TS_ASSERT_DIFFERS(ws, nullptr);
     if(!(ws == nullptr))
     {
         TS_ASSERT_EQUALS(ws.get_cell("G5").get_value<std::string>(), "hello");
         TS_ASSERT_EQUALS(ws.get_cell("D30").get_value<int>(), 30);
         TS_ASSERT_EQUALS(ws.get_cell("K9").get_value<double>(), 0.09);
     }
 }
Example #18
0
  void test_duplicate() {
    Tuple* tup = Tuple::create(state, 1);
    tup->put(state, 0, Qtrue);

    tup->set_ivar(state, state->symbol("@name"), state->symbol("foo"));

    Tuple* tup2 = as<Tuple>(tup->duplicate(state));

    TS_ASSERT_EQUALS(tup2->at(state, 0), Qtrue);
    TS_ASSERT_DIFFERS(tup->id(state), tup2->id(state));

    TS_ASSERT(tup->ivars_ != tup2->ivars_);

    TS_ASSERT_EQUALS(tup2->get_ivar(state, state->symbol("@name")),
        state->symbol("foo"));

    tup->ivars_ = as<CompactLookupTable>(tup->ivars_)->to_lookuptable(state);
    Tuple* tup3 = as<Tuple>(tup->duplicate(state));

    TS_ASSERT(tup->ivars_ != tup2->ivars_);
    TS_ASSERT_EQUALS(tup3->get_ivar(state, state->symbol("@name")),
        state->symbol("foo"));
  }
    void TestArchivingSetOfSetOfPointers() throw (Exception)
    {
        /*
         * This test is an abstraction of archiving a set of sets of pointers and a list of objects.
         * Note that the list.push_back method uses the copy constructor. This is why we iterate
         * through the list to generate the pointers to populate the set.
         */

        std::vector<double> doubles;
        std::vector<bool> bools;

        OutputFileHandler handler("archive",false);
        std::string archive_filename;
        archive_filename = handler.GetOutputDirectoryFullPath() + "pointer_set.arch";

        // Save
        {
            // Create aClassOfSimpleVariablesn output archive
            std::ofstream ofs(archive_filename.c_str());
            boost::archive::text_oarchive output_arch(ofs);

            ClassOfSimpleVariables one(42, "hello", doubles,bools);
            ClassOfSimpleVariables two(256, "goodbye", doubles,bools);
            ClassOfSimpleVariables three(1, "not used in set", doubles,bools);

            std::list<ClassOfSimpleVariables> a_list;
            std::set<ClassOfSimpleVariables*> a_set;
            a_list.push_back(one);
            a_set.insert( &(a_list.back()) );
            a_list.push_back(two);
            a_set.insert( &(a_list.back()) );
            a_list.push_back(three);

            std::set<std::set<ClassOfSimpleVariables*> > wrapper_set;
            wrapper_set.insert(a_set);

            output_arch << static_cast<const std::list<ClassOfSimpleVariables>&>(a_list);
            output_arch << static_cast<const std::set<std::set<ClassOfSimpleVariables*> >&>(wrapper_set);
        }

        // Load
        {
            std::set<std::set<ClassOfSimpleVariables*> > wrapper_set;
            std::list<ClassOfSimpleVariables> a_list;

            // Create an input archive
            std::ifstream ifs(archive_filename.c_str(), std::ios::binary);
            boost::archive::text_iarchive input_arch(ifs);

            TS_ASSERT_EQUALS(wrapper_set.size(), 0u);
            input_arch >> a_list;
            input_arch >> wrapper_set;
            TS_ASSERT_EQUALS(wrapper_set.size(), 1u);
            const std::set<ClassOfSimpleVariables*>& a_set = *(wrapper_set.begin());
            TS_ASSERT_EQUALS(a_set.size(), 2u);

            ClassOfSimpleVariables* p_one_in_set = NULL;
            ClassOfSimpleVariables* p_two_in_set = NULL;
            for (std::set<ClassOfSimpleVariables*>::iterator it = a_set.begin();
                 it != a_set.end();
                 ++it)
            {
                   ClassOfSimpleVariables* p_class = *(it);
                   if (p_class->GetNumber() == 42)
                   {
                        TS_ASSERT_EQUALS(p_class->GetNumber(), 42);
                        TS_ASSERT_EQUALS(p_class->GetString(), "hello");
                        p_one_in_set = p_class;
                   }
                   else
                   {
                        TS_ASSERT_EQUALS(p_class->GetNumber(), 256);
                        TS_ASSERT_EQUALS(p_class->GetString(), "goodbye");
                        p_two_in_set = p_class;
                   }
            }

            ClassOfSimpleVariables* p_one_in_list = NULL;
            ClassOfSimpleVariables* p_two_in_list = NULL;
            for (std::list<ClassOfSimpleVariables>::iterator it = a_list.begin();
                 it != a_list.end();
                 ++it)
            {
                   ClassOfSimpleVariables* p_class = &(*it);
                   if (p_class->GetNumber() == 42)
                   {
                        TS_ASSERT_EQUALS(p_class->GetNumber(), 42);
                        TS_ASSERT_EQUALS(p_class->GetString(), "hello");
                        p_one_in_list = p_class;
                   }
                   else if (p_class->GetNumber() == 256)
                   {
                        TS_ASSERT_EQUALS(p_class->GetNumber(), 256);
                        TS_ASSERT_EQUALS(p_class->GetString(), "goodbye");
                        p_two_in_list = p_class;
                   }
                   else
                   {
                        TS_ASSERT_EQUALS(p_class->GetNumber(), 1);
                        TS_ASSERT_EQUALS(p_class->GetString(), "not used in set");
                   }
            }
            TS_ASSERT_DIFFERS(p_one_in_list, (void*)NULL);
            TS_ASSERT_DIFFERS(p_two_in_list, (void*)NULL);
            TS_ASSERT_EQUALS(p_one_in_list, p_one_in_set);
            TS_ASSERT_EQUALS(p_two_in_list, p_two_in_set);
        }
    }
Example #20
0
 void testGetExeBundleDir(void) {
     Sirikata::String res = Sirikata::Path::Get(Sirikata::Path::DIR_EXE_BUNDLE);
     TS_ASSERT_DIFFERS(res, "");
 }
    void TestArchiving() throw(Exception)
    {
        OutputFileHandler archive_dir_("mixed_mesh_archive"); // Clear folder
        FileFinder main_archive_dir("mixed_mesh_archive", RelativeTo::ChasteTestOutput);
        std::string archive_file = "mixed_dimension_mesh.arch";
        ArchiveLocationInfo::SetMeshFilename("mixed_dimension_mesh");

        MixedDimensionMesh<2,2>* p_mesh = new MixedDimensionMesh<2,2>(DistributedTetrahedralMeshPartitionType::DUMB);
        unsigned num_nodes;
        unsigned local_num_nodes;
        unsigned num_elements;
        unsigned num_cable_elements;
        unsigned num_local_cable_elements;
        // archive
        {
            TrianglesMeshReader<2,2> mesh_reader("mesh/test/data/mixed_dimension_meshes/2D_0_to_1mm_200_elements");

            p_mesh->ConstructFromMeshReader(mesh_reader);
            num_nodes = p_mesh->GetNumNodes();
            local_num_nodes = p_mesh->GetNumLocalNodes();
            num_elements = p_mesh->GetNumElements();
            num_cable_elements = p_mesh->GetNumCableElements();
            num_local_cable_elements = p_mesh->GetNumLocalCableElements();

            ArchiveOpener<boost::archive::text_oarchive, std::ofstream> arch_opener(main_archive_dir, archive_file);
            boost::archive::text_oarchive* p_arch = arch_opener.GetCommonArchive();

            AbstractTetrahedralMesh<2,2>* const p_mesh_abstract = static_cast<AbstractTetrahedralMesh<2,2>* >(p_mesh);
            (*p_arch) << p_mesh_abstract;
        }

        FileFinder ncl_file("mixed_dimension_mesh.ncl", main_archive_dir);
        TS_ASSERT(ncl_file.Exists());

        // restore
        {
            // Should archive the most abstract class you can to check boost knows what individual classes are.
            // (but here AbstractMesh doesn't have the methods below).
            AbstractTetrahedralMesh<2,2>* p_mesh_abstract2;

            // Create an input archive
            ArchiveOpener<boost::archive::text_iarchive, std::ifstream> arch_opener(main_archive_dir, archive_file);
            boost::archive::text_iarchive* p_arch = arch_opener.GetCommonArchive();

            // restore from the archive
            (*p_arch) >> p_mesh_abstract2;
            // Check we have the right number of nodes & elements
            MixedDimensionMesh<2,2>* p_mesh2 = static_cast<MixedDimensionMesh<2,2>*>(p_mesh_abstract2);

            TS_ASSERT_EQUALS(p_mesh2->GetNumNodes(), num_nodes);
            TS_ASSERT_EQUALS(p_mesh2->GetNumLocalNodes(), local_num_nodes);
            TS_ASSERT_EQUALS(p_mesh2->GetNumElements(), num_elements);
            TS_ASSERT_EQUALS(p_mesh2->GetNumCableElements(), num_cable_elements);
            TS_ASSERT_EQUALS(p_mesh2->GetNumLocalCableElements(), num_local_cable_elements);

            // Check elements have the right nodes
            for (unsigned i=0; i<num_cable_elements; i++)
            {
                try
                {
                    Element<1,2>* p_element = p_mesh->GetCableElement(i);
                    Element<1,2>* p_element2 = p_mesh2->GetCableElement(i);
                    TS_ASSERT_EQUALS(p_element->GetNodeGlobalIndex(0), p_element2->GetNodeGlobalIndex(0));
                }
                catch(Exception& e)
                {
                    TS_ASSERT_DIFFERS((int)e.GetShortMessage().find("does not belong to processor"),-1);
                }
            }
            delete p_mesh2;
        }

        // restore from a single processor archive
        {
            FileFinder archive_dir("mesh/test/data/mixed_mesh_archive", RelativeTo::ChasteSourceRoot);
            if ( PetscTools::IsSequential() )
            {
                ArchiveOpener<boost::archive::text_iarchive, std::ifstream> arch_opener(archive_dir, archive_file);
                boost::archive::text_iarchive* p_arch = arch_opener.GetCommonArchive();
                AbstractTetrahedralMesh<2,2>* p_mesh_abstract3 = NULL;
                (*p_arch) >> p_mesh_abstract3;

                //Double check that the cables are intact
                MixedDimensionMesh<2,2>* p_mesh3 = static_cast<MixedDimensionMesh<2,2>*>(p_mesh_abstract3);
                Element<1,2>* p_element = p_mesh3->GetCableElement(9);
                TS_ASSERT_EQUALS(p_element->GetNodeGlobalIndex(0), 64u);
                TS_ASSERT_EQUALS(p_element->GetNodeGlobalIndex(1), 65u);
                TS_ASSERT_DELTA(p_element->GetAttribute(), 10.5, 1e-8);

                delete p_mesh_abstract3;
            }
            else
            {
                typedef ArchiveOpener<boost::archive::text_iarchive, std::ifstream> InputArchiveOpener;
                if (PetscTools::GetMyRank() > 0)
                {
                    // Should not read this archive because none exists here.
                    TS_ASSERT_THROWS_CONTAINS(InputArchiveOpener arch_opener(archive_dir, archive_file),
                                              "Cannot load secondary archive file:");
                }
                else
                {
                    // Should not read this archive because there are two or more processes and
                    // this archive was written on one process.
                    InputArchiveOpener arch_opener(archive_dir, archive_file);
                    boost::archive::text_iarchive* p_arch = arch_opener.GetCommonArchive();
                    AbstractTetrahedralMesh<2,2>* p_mesh3 = NULL;
                    TS_ASSERT_THROWS_THIS((*p_arch) >> p_mesh3,
                                          "This archive was written for a different number of processors");

                }
            }
        }
Example #22
0
 void assertRotated()
 {
   TS_ASSERT_DIFFERS( m_headingAtStart, m_physicalModel.heading() );
 }
    /**
     * Tests archiving of the tissue object.
     * It creates one, changes the default values of some member variables and saves.
     * Then it tries to load from the archive and checks that the member variables are with the right values.
     */
    void TestSaveAndLoadExtendedBidomainTissue() throw (Exception)
    {
        HeartConfig::Instance()->Reset();
        // Archive settings
        FileFinder archive_dir("extended_tissue_archive", RelativeTo::ChasteTestOutput);
        std::string archive_file = "extended_bidomain_tissue.arch";

        bool cache_replication_saved = false;
        double saved_printing_timestep = 2.0;
        double default_printing_timestep = HeartConfig::Instance()->GetPrintingTimeStep();

        c_matrix<double, 3, 3> intra_tensor_before_archiving;
        c_matrix<double, 3, 3> intra_tensor_second_cell_before_archiving;
        c_matrix<double, 3, 3> extra_tensor_before_archiving;

        //creation and save
        {
            // This call is required to set the appropriate conductivity media and to make sure that HeartConfig
            // knows the mesh filename despite we use our own mesh reader.
            HeartConfig::Instance()->SetMeshFileName("mesh/test/data/cube_136_elements");

            TrianglesMeshReader<3,3> mesh_reader("mesh/test/data/cube_136_elements");
            DistributedTetrahedralMesh<3,3> mesh;
            mesh.ConstructFromMeshReader(mesh_reader);

            UnStimulatedCellFactory first_cell;
            StimulatedCellFactory second_cell;
            ExtracellularStimulusFactory extra_factory;
            first_cell.SetMesh(&mesh);
            second_cell.SetMesh(&mesh);
            extra_factory.SetMesh(&mesh);
            ExtendedBidomainTissue<3> extended_tissue( &first_cell, &second_cell , &extra_factory);

            //set a value different from default for the conductivities of the second cell
            extended_tissue.SetIntracellularConductivitiesSecondCell(Create_c_vector(25.0,26.0,27.0));
            //this is normally done by the problem class, but in this test we do it manually
            extended_tissue.CreateIntracellularConductivityTensorSecondCell();
            extended_tissue.SetCacheReplication(cache_replication_saved); // Not the default to check it is archived...

            //shuffle default values to check if they get archived properly
            extended_tissue.SetAmFirstCell(11.0);
            extended_tissue.SetAmSecondCell(22.0);
            extended_tissue.SetAmGap(33.0);
            extended_tissue.SetCmFirstCell(44.0);
            extended_tissue.SetCmSecondCell(55.0);
            extended_tissue.SetGGap(66.0);

            //again, away from default value to check for archiving
            extended_tissue.SetUserSuppliedExtracellularStimulus(true);

            //set some heterogeneities in Ggap
            std::vector<boost::shared_ptr<AbstractChasteRegion<3> > > heterogeneity_areas;
            std::vector<double> Ggap_values;
            ChastePoint<3> cornerA(-1, -1, 0);
            ChastePoint<3> cornerB(0.001, 0.001, 0.001);
            boost::shared_ptr<ChasteCuboid<3> > p_cuboid_1(new ChasteCuboid<3>(cornerA, cornerB));
            heterogeneity_areas.push_back(p_cuboid_1);
            //within the first area
            Ggap_values.push_back(143.0);
            extended_tissue.SetGgapHeterogeneities(heterogeneity_areas, Ggap_values);
            extended_tissue.CreateGGapConductivities();

            // Some checks to make sure HeartConfig is being saved and loaded by this too.
            HeartConfig::Instance()->SetPrintingTimeStep(saved_printing_timestep);
            TS_ASSERT_DELTA(HeartConfig::Instance()->GetPrintingTimeStep(), saved_printing_timestep, 1e-9);

            intra_tensor_before_archiving = extended_tissue.rGetIntracellularConductivityTensor(0);
            intra_tensor_second_cell_before_archiving = extended_tissue.rGetIntracellularConductivityTensorSecondCell(0);
            extra_tensor_before_archiving = extended_tissue.rGetExtracellularConductivityTensor(0);

            // Save
            ArchiveOpener<boost::archive::text_oarchive, std::ofstream> arch_opener(archive_dir, archive_file);
            boost::archive::text_oarchive* p_arch = arch_opener.GetCommonArchive();

            AbstractCardiacTissue<3>* const p_archive_bidomain_tissue = &extended_tissue;
            (*p_arch) << p_archive_bidomain_tissue;

            HeartConfig::Reset();
            TS_ASSERT_DELTA(HeartConfig::Instance()->GetPrintingTimeStep(), default_printing_timestep, 1e-9);
            TS_ASSERT_DIFFERS(saved_printing_timestep, default_printing_timestep);
        }
        //load
        {
            ArchiveOpener<boost::archive::text_iarchive, std::ifstream> arch_opener(archive_dir, archive_file);
            boost::archive::text_iarchive* p_arch = arch_opener.GetCommonArchive();

            AbstractCardiacTissue<3>* p_abstract_tissue;
            (*p_arch) >> p_abstract_tissue;
            assert(p_abstract_tissue!=NULL);

            //dynamic cast so we are able to test specific variables of ExtendedBidomainTissue
            ExtendedBidomainTissue<3>* p_extended_tissue = dynamic_cast<ExtendedBidomainTissue<3>*>(p_abstract_tissue);
            assert(p_extended_tissue != NULL);

            const c_matrix<double, 3, 3>& intra_tensor_after_archiving = p_extended_tissue->rGetIntracellularConductivityTensor(0);
            const c_matrix<double, 3, 3>& intra_tensor_second_cell_after_archiving = p_extended_tissue->rGetIntracellularConductivityTensorSecondCell(0);
            const c_matrix<double, 3, 3>& extra_tensor_after_archiving = p_extended_tissue->rGetExtracellularConductivityTensor(0);

            //check before archiving = after archiving
            for(unsigned i=0; i<3; i++)
            {
                for(unsigned j=0; j<3; j++)
                {
                    TS_ASSERT_DELTA(intra_tensor_before_archiving(i,j), intra_tensor_after_archiving(i,j), 1e-9);
                    TS_ASSERT_DELTA(intra_tensor_second_cell_before_archiving(i,j), intra_tensor_second_cell_after_archiving(i,j), 1e-9);
                    TS_ASSERT_DELTA(extra_tensor_before_archiving(i,j), extra_tensor_after_archiving(i,j), 1e-9);
                }
            }

            //check that the member variable mIntracellularConductivitiesSecondCell was archived properly
            TS_ASSERT_EQUALS(p_extended_tissue->GetIntracellularConductivitiesSecondCell()(0),25.0);
            TS_ASSERT_EQUALS(p_extended_tissue->GetIntracellularConductivitiesSecondCell()(1),26.0);
            TS_ASSERT_EQUALS(p_extended_tissue->GetIntracellularConductivitiesSecondCell()(2),27.0);

            //check that we get the same values from the archive which are different from the default
            TS_ASSERT_EQUALS(p_extended_tissue->GetAmFirstCell(), 11.0);
            TS_ASSERT_EQUALS(p_extended_tissue->GetAmSecondCell(), 22.0);
            TS_ASSERT_EQUALS(p_extended_tissue->GetAmGap(), 33.0);
            TS_ASSERT_EQUALS(p_extended_tissue->GetCmFirstCell(), 44.0);
            TS_ASSERT_EQUALS(p_extended_tissue->GetCmSecondCell(), 55.0);
            TS_ASSERT_EQUALS(p_extended_tissue->GetGGap(), 66.0);

            // We shouldn't need to re-build the mesh, but we use it to check that the new tissue has the same mesh
            // Also, when testing in parallel, we use it to get the vector factory to loop over the nodes we own.
            // this is because  p_extended_tissue->pGetMesh()->GetDistributedVectorFactory() doesn't compile (discards qualifier stuff caused by use of const).
            TrianglesMeshReader<3,3> mesh_reader("mesh/test/data/cube_136_elements");
            DistributedTetrahedralMesh<3,3> mesh;
            mesh.ConstructFromMeshReader(mesh_reader);

            TS_ASSERT_EQUALS(mesh.GetNumNodes(), p_extended_tissue->pGetMesh()->GetNumNodes());//note: this is allowed because GetNumNodes has const in the signature

            //check archiving of stimulus for first cell at some random times (it is unstimulated everywhere at all times)
            for (unsigned i = 0; i < mesh.GetNumNodes(); i++)
            {
                if (mesh.GetDistributedVectorFactory()->IsGlobalIndexLocal(i))
                {
                    TS_ASSERT_EQUALS(p_extended_tissue->GetCardiacCell(i)->GetIntracellularStimulus(0.0), 0.0);
                    TS_ASSERT_EQUALS(p_extended_tissue->GetCardiacCell(i)->GetIntracellularStimulus(0.1), 0.0);
                    TS_ASSERT_EQUALS(p_extended_tissue->GetCardiacCell(i)->GetIntracellularStimulus(2.5), 0.0);
                    TS_ASSERT_EQUALS(p_extended_tissue->GetCardiacCell(i)->GetIntracellularStimulus(28.9), 0.0);
                }
            }

            //for second cell and other stuff, we probe nodes 0 and 1.
            unsigned node_0 = 0u;
            unsigned node_1 = 1u;
            //If the test is run in parallel, we need to work out the new indices
            const std::vector<unsigned>& r_permutation = mesh.rGetNodePermutation();
            if (!r_permutation.empty())
            {
                node_0 = r_permutation[0u];
                node_1 = r_permutation[1u];
            }

            //second cell is stimulated in the corner (node 0) from time 0 to 1. check it gets all this after loading
            if (mesh.GetDistributedVectorFactory()->IsGlobalIndexLocal(node_0))
            {
                TS_ASSERT_EQUALS(p_extended_tissue->GetCardiacSecondCell(node_0)->GetIntracellularStimulus(0.5), -105.0*1400);
                TS_ASSERT_EQUALS(p_extended_tissue->GetCardiacSecondCell(node_0)->GetIntracellularStimulus(2.5), 0.0);

                //find local index of (the new) node_0, it should be in the heterogeneity region
                unsigned ownership_range_low = mesh.GetDistributedVectorFactory()->GetLow();
                unsigned  local_index = node_0 - ownership_range_low;
                //std::cout<<local_index<<std::endl;
                TS_ASSERT_EQUALS(p_extended_tissue->rGetGapsDistributed()[local_index],143.0);//g_gap value inside heterogeneity region
            }

            //node 0 has extracellular stimulus (1 ms from 0.1)
            if (mesh.GetDistributedVectorFactory()->IsGlobalIndexLocal(node_0))
            {
                TS_ASSERT_EQUALS(p_extended_tissue->GetExtracellularStimulus(node_0)->GetStimulus(0.0), 0);
                TS_ASSERT_EQUALS(p_extended_tissue->GetExtracellularStimulus(node_0)->GetStimulus(0.5), -428000);
                TS_ASSERT_EQUALS(p_extended_tissue->GetExtracellularStimulus(node_0)->GetStimulus(1.0), -428000);
                TS_ASSERT_EQUALS(p_extended_tissue->GetExtracellularStimulus(node_0)->GetStimulus(1.15), 0);
            }

            //node 1 doesn't
            if (mesh.GetDistributedVectorFactory()->IsGlobalIndexLocal(node_1))
            {
                TS_ASSERT_EQUALS(p_extended_tissue->GetExtracellularStimulus(node_1)->GetStimulus(0.0), 0);
                TS_ASSERT_EQUALS(p_extended_tissue->GetExtracellularStimulus(node_1)->GetStimulus(0.5), 0);
                TS_ASSERT_EQUALS(p_extended_tissue->GetExtracellularStimulus(node_1)->GetStimulus(1.0), 0);
                TS_ASSERT_EQUALS(p_extended_tissue->GetExtracellularStimulus(node_1)->GetStimulus(1.15), 0);

                //find local index of (the new) node_1, it should NOT be in the heterogeneity region
                unsigned ownership_range_low = mesh.GetDistributedVectorFactory()->GetLow();
                unsigned  local_index = node_1 - ownership_range_low;
                TS_ASSERT_EQUALS(p_extended_tissue->rGetGapsDistributed()[local_index],66.0);//standard g_gap value, outside heterogeneity region
            }

            //check the archiving of the flag (it would be false by default, but we set it to true before archiving)
            TS_ASSERT_EQUALS(p_extended_tissue->HasTheUserSuppliedExtracellularStimulus(),true);

            TS_ASSERT_EQUALS(cache_replication_saved, p_extended_tissue->GetDoCacheReplication());
            TS_ASSERT_DELTA(HeartConfig::Instance()->GetPrintingTimeStep(), saved_printing_timestep, 1e-9);
            TS_ASSERT_DIFFERS(saved_printing_timestep, default_printing_timestep); // Test we are testing something in case default changes

            delete p_extended_tissue;
        }
    }
Example #24
0
    void TestConductionVelocityConvergesFasterWithSvi1d()
    {
        double h[3] = {0.001,0.01,0.02};
        unsigned probe_node_index[3] = {300, 30, 15};
        unsigned number_of_nodes[3] = {1001, 101, 51};
        std::vector<double> conduction_vel_ici(3);
        std::vector<double> conduction_vel_svi(3);

        ReplicatableVector final_voltage_ici;
        ReplicatableVector final_voltage_svi;

        //HeartConfig::Instance()->SetUseRelativeTolerance(1e-8);
        HeartConfig::Instance()->SetSimulationDuration(4.0); //ms
        HeartConfig::Instance()->SetOdePdeAndPrintingTimeSteps(0.01, 0.01, 0.01);

        for (unsigned i=0; i<3; i++)
        {
            // ICI - ionic current interpolation - the default
            {
                DistributedTetrahedralMesh<1,1> mesh;
                mesh.ConstructRegularSlabMesh(h[i], 1.0);
                TS_ASSERT_EQUALS(mesh.GetNumNodes(), number_of_nodes[i]);

                //Double check (for later) that the indexing is as expected
                if (mesh.GetDistributedVectorFactory()->IsGlobalIndexLocal( probe_node_index[i] ))
                {
                    TS_ASSERT_DELTA(mesh.GetNode( probe_node_index[i] )->rGetLocation()[0], 0.3, 1e-8);
                }
                std::stringstream output_dir;
                output_dir << "MonodomainIci_" << h[i];
                HeartConfig::Instance()->SetOutputDirectory(output_dir.str());
                HeartConfig::Instance()->SetOutputFilenamePrefix("results");

                // need to have this for i=1,2 cases!!
                HeartConfig::Instance()->SetUseStateVariableInterpolation(false);

                BlockCellFactory<1> cell_factory;
                MonodomainProblem<1> monodomain_problem( &cell_factory );
                monodomain_problem.SetMesh(&mesh);
                monodomain_problem.Initialise();

                monodomain_problem.Solve();

                final_voltage_ici.ReplicatePetscVector(monodomain_problem.GetSolution());

//// see #1633
//// end time needs to be increased for these (say, to 7ms)
//                Hdf5DataReader simulation_data(OutputFileHandler::GetChasteTestOutputDirectory() + output_dir.str(),
//                                               "results", false);
//                PropagationPropertiesCalculator ppc(&simulation_data);
//                unsigned node_at_0_04 = (unsigned)round(0.04/h[i]);
//                unsigned node_at_0_40 = (unsigned)round(0.40/h[i]);
//                assert(fabs(mesh.GetNode(node_at_0_04)->rGetLocation()[0]-0.04)<1e-6);
//                assert(fabs(mesh.GetNode(node_at_0_40)->rGetLocation()[0]-0.40)<1e-6);
//                conduction_vel_ici[i] = ppc.CalculateConductionVelocity(node_at_0_04,node_at_0_40,0.36);
//                std::cout << "conduction_vel_ici = " << conduction_vel_ici[i] << "\n";
            }

            // SVI - state variable interpolation
            {
                DistributedTetrahedralMesh<1,1> mesh;
                mesh.ConstructRegularSlabMesh(h[i], 1.0);

                //Double check (for later) that the indexing is as expected
                if (mesh.GetDistributedVectorFactory()->IsGlobalIndexLocal( probe_node_index[i] ))
                {
                    TS_ASSERT_DELTA(mesh.GetNode( probe_node_index[i] )->rGetLocation()[0], 0.3, 1e-8);
                }
                std::stringstream output_dir;
                output_dir << "MonodomainSvi_" << h[i];
                HeartConfig::Instance()->SetOutputDirectory(output_dir.str());
                HeartConfig::Instance()->SetOutputFilenamePrefix("results");

                HeartConfig::Instance()->SetUseStateVariableInterpolation();

                BlockCellFactory<1> cell_factory;
                MonodomainProblem<1> monodomain_problem( &cell_factory );
                monodomain_problem.SetMesh(&mesh);
                monodomain_problem.Initialise();

                monodomain_problem.Solve();

                final_voltage_svi.ReplicatePetscVector(monodomain_problem.GetSolution());

//                Hdf5DataReader simulation_data(OutputFileHandler::GetChasteTestOutputDirectory() + output_dir.str(),
//                                               "results", false);
//                PropagationPropertiesCalculator ppc(&simulation_data);
//                unsigned node_at_0_04 = (unsigned)round(0.04/h[i]);
//                unsigned node_at_0_40 = (unsigned)round(0.40/h[i]);
//                assert(fabs(mesh.GetNode(node_at_0_04)->rGetLocation()[0]-0.04)<1e-6);
//                assert(fabs(mesh.GetNode(node_at_0_40)->rGetLocation()[0]-0.40)<1e-6);
//                conduction_vel_svi[i] = ppc.CalculateConductionVelocity(node_at_0_04,node_at_0_40,0.36);
//                std::cout << "conduction_vel_svi = " << conduction_vel_svi[i] << "\n";
            }

            if (i==0) // finest mesh
            {
                for (unsigned j=0; j<final_voltage_ici.GetSize(); j++)
                {
                    // visually checked they agree at this mesh resolution, and chosen tolerance from results
                    TS_ASSERT_DELTA(final_voltage_ici[j], final_voltage_svi[j], 0.3);

                    if (final_voltage_ici[j]>-80)
                    {
                        // shouldn't be exactly equal, as long as away from resting potential
                        TS_ASSERT_DIFFERS(final_voltage_ici[j], final_voltage_svi[j]);
                    }
                }

                double ici_voltage_at_0_03_finest_mesh = final_voltage_ici[ probe_node_index[i] ];
                double svi_voltage_at_0_03_finest_mesh = final_voltage_svi[ probe_node_index[i] ];
                TS_ASSERT_DELTA(svi_voltage_at_0_03_finest_mesh, 11.0067, 2e-4); //hardcoded value from fine svi
                TS_ASSERT_DELTA(ici_voltage_at_0_03_finest_mesh, 11.0067, 1.2e-1); //hardcoded value from fine svi
            }
            else if (i==1)
            {
                double ici_voltage_at_0_03_middle_mesh = final_voltage_ici[ probe_node_index[i] ];
                double svi_voltage_at_0_03_middle_mesh = final_voltage_svi[ probe_node_index[i] ];
                // ICI conduction velocity > SVI conduction velocity
                // and both should be greater than CV on finesh mesh
                TS_ASSERT_DELTA(ici_voltage_at_0_03_middle_mesh, 19.8924, 1e-3);
                TS_ASSERT_DELTA(svi_voltage_at_0_03_middle_mesh, 14.9579, 1e-3);
            }
            else
            {
                double ici_voltage_at_0_03_coarse_mesh = final_voltage_ici[ probe_node_index[i] ];
                double svi_voltage_at_0_03_coarse_mesh = final_voltage_svi[ probe_node_index[i] ];
                // ICI conduction velocity even greater than SVI conduction
                // velocity
                TS_ASSERT_DELTA(ici_voltage_at_0_03_coarse_mesh, 24.4938, 1e-3);
                TS_ASSERT_DELTA(svi_voltage_at_0_03_coarse_mesh, 17.3131, 1e-3);
            }
        }
    }
Example #25
0
 void assertMoved()
 {
   TS_ASSERT_DIFFERS( m_startingPosition, m_physicalModel.coordinate() );
 }
void
MediaPacketTest::testCopyPacket() {
  const int32_t size = 512;
  packet = MediaPacket::make(size);
  TSM_ASSERT("was able to allocate packet", packet);

  // everything else should be garbage.
  int64_t position = packet->getPosition();
  TSM_ASSERT("position was not set to -1", position == -1);

  position = 4;
  packet->setPosition(position);
  int64_t dts = 28349762;
  packet->setDts(dts);
  int64_t pts = 82729373;
  packet->setPts(pts);
  RefPointer<Rational> timeBase = Rational::make(3, 28972);
  packet->setTimeBase(timeBase.value());
  int32_t streamIndex = 8;
  packet->setStreamIndex(streamIndex);
  int64_t duration = 28387728;
  packet->setDuration(duration);
  int64_t convergenceDuration = 283;
  packet->setConvergenceDuration(convergenceDuration);

  // let's get access to the data

  RefPointer<Buffer> data = packet->getData();
  TS_ASSERT_EQUALS(size+16, data->getBufferSize());
  TS_ASSERT_EQUALS(size, packet->getSize());
  uint8_t* raw = (uint8_t*) data->getBytes(0, size);
  for (int i = 0; i < size; i++)
    raw[i] = i % 16;

  // Now, make a copy
  bool tests[] =
    { true, false };
  for (size_t i = 0; i < (sizeof(tests) / sizeof(tests[0])); i++) {
    RefPointer<MediaPacket> newPacket = MediaPacket::make(packet.value(), tests[i]);
    TSM_ASSERT("should not be empty", newPacket);

    // let's make sure that when not copying, the data is the same.

    TSM_ASSERT_EQUALS("should equal", position, newPacket->getPosition());
    TSM_ASSERT_EQUALS("should equal", pts, newPacket->getPts());
    TSM_ASSERT_EQUALS("should equal", dts, newPacket->getDts());
    TSM_ASSERT_EQUALS("should equal", streamIndex, newPacket->getStreamIndex());
    TSM_ASSERT_EQUALS("should equal", duration, newPacket->getDuration());
    TSM_ASSERT_EQUALS("should equal", convergenceDuration,
        newPacket->getConvergenceDuration());
    RefPointer<Rational> newBase = newPacket->getTimeBase();
    TSM_ASSERT("should be equal", newBase->compareTo(timeBase.value()) == 0);

    RefPointer<Buffer> buf = newPacket->getData();
    TS_ASSERT_EQUALS(size, newPacket->getSize());
    TS_ASSERT_EQUALS(size+16, buf->getBufferSize());
    uint8_t* d = (uint8_t*) buf->getBytes(0, size);
    if (!tests[i]) {
      TS_ASSERT_EQUALS(d, raw);
    } else {
      TS_ASSERT_DIFFERS(d, raw);
    }

    TS_ASSERT(d);
    for (int j = 0; j < size; j++) {
      TS_ASSERT_EQUALS(d[j], j % 16);
    }
  }
}
Example #27
0
 void testGetDirCurrent(void) {
     Sirikata::String res = Sirikata::Path::Get(Sirikata::Path::DIR_CURRENT);
     TS_ASSERT_DIFFERS(res, "");
     TS_ASSERT_DIFFERS(res, ".");
 }
Example #28
0
  void test_create() {
    Thread* thr = Thread::create(state, shared->new_vm());

    TS_ASSERT_DIFFERS(thr, Thread::current(state));
  }
Example #29
0
  void test_create() {
    Thread* thr = Thread::create(state, new_vm(), G(thread), 0);

    TS_ASSERT_DIFFERS(thr, Thread::current(state));
  }
    void TestArchivingOfParameters() throw (Exception)
    {
        OutputFileHandler handler("archive", false);
        std::string archive_filename;
        archive_filename = handler.GetOutputDirectoryFullPath() + "parameterised_ode.arch";
        double param_value;
        std::string param_name;
        { // Save
            AbstractOdeSystem * const p_ode = new ParameterisedOde;

            TS_ASSERT_EQUALS(p_ode->GetNumberOfParameters(), 1u);
            param_value = p_ode->GetParameter(0);
            param_name = p_ode->rGetParameterNames()[0];

            std::ofstream ofs(archive_filename.c_str());
            boost::archive::text_oarchive output_arch(ofs);
            output_arch << p_ode;
            delete p_ode;
        }
        { // Normal load
            std::ifstream ifs(archive_filename.c_str(), std::ios::binary);
            boost::archive::text_iarchive input_arch(ifs);
            AbstractOdeSystem* p_ode;
            input_arch >> p_ode;

            TS_ASSERT_EQUALS(p_ode->GetSystemName(), "ParameterisedOde");
            TS_ASSERT_EQUALS(p_ode->GetParameter(0), param_value);
            TS_ASSERT_EQUALS(p_ode->rGetParameterNames()[0], param_name);
            TS_ASSERT_EQUALS(p_ode->GetNumberOfParameters(), 1u);

            delete p_ode;
        }
        { // Load with param name changed
            ParameterisedOde ode;
            boost::shared_ptr<const AbstractOdeSystemInformation> p_info = ode.GetSystemInformation();
            AbstractOdeSystemInformation* p_mod_info = const_cast<AbstractOdeSystemInformation*>(p_info.get());
            std::string new_name("new_param_name");
            TS_ASSERT_DIFFERS(p_mod_info->mParameterNames[0], new_name);
            p_mod_info->mParameterNames[0] = new_name;

            std::ifstream ifs(archive_filename.c_str(), std::ios::binary);
            boost::archive::text_iarchive input_arch(ifs);
            AbstractOdeSystem* p_ode;
            TS_ASSERT_THROWS_CONTAINS(input_arch >> p_ode, "Archive specifies a parameter 'a' which does not appear in this class.");
            // Mend the ODE system info for the following tests.
            p_mod_info->mParameterNames[0] = param_name;
        }
        { // Load with a parameter added
            ParameterisedOde ode;
            boost::shared_ptr<const AbstractOdeSystemInformation> p_info = ode.GetSystemInformation();
            AbstractOdeSystemInformation* p_mod_info = const_cast<AbstractOdeSystemInformation*>(p_info.get());

            p_mod_info->mParameterNames.push_back("new_name");

            std::ifstream ifs(archive_filename.c_str(), std::ios::binary);
            boost::archive::text_iarchive input_arch(ifs);
            AbstractOdeSystem* p_ode;
            TS_ASSERT_THROWS_CONTAINS(input_arch >> p_ode, "Number of ODE parameters in archive does not match number in class.");
            // Mend the ODE system info for the following tests.
            p_mod_info->mParameterNames.resize(1u);
        }
        { // Load with a parameter added, and the constructor providing a default
            ParameterisedOde ode;
            boost::shared_ptr<const AbstractOdeSystemInformation> p_info = ode.GetSystemInformation();
            AbstractOdeSystemInformation* p_mod_info = const_cast<AbstractOdeSystemInformation*>(p_info.get());

            p_mod_info->mParameterNames.push_back("new_name");

            std::ifstream ifs(archive_filename.c_str(), std::ios::binary);
            boost::archive::text_iarchive input_arch(ifs);
            AbstractOdeSystem* p_ode;
            ParameterisedOde::fakeSecondParameter = true;
            input_arch >> p_ode;
            delete p_ode;
            // Mend the ODE system info for the following tests.
            ParameterisedOde::fakeSecondParameter = false;
            p_mod_info->mParameterNames.resize(1u);
        }
        { // Load with no defaults provided by the constructor
            ParameterisedOde::noParameterDefaults = true;
            std::ifstream ifs(archive_filename.c_str(), std::ios::binary);
            boost::archive::text_iarchive input_arch(ifs);
            AbstractOdeSystem* p_ode;
            input_arch >> p_ode;
            delete p_ode;
            // Mend the ODE system info for the following tests.
            ParameterisedOde::noParameterDefaults = false;
        }
    }