Example #1
0
    void TestReadOnlyDistributedVector()
    {
        DistributedVectorFactory factory(10);
        Vec petsc_vec = factory.CreateVec();

        {
            DistributedVector distributed_vector = factory.CreateDistributedVector(petsc_vec);
            for (DistributedVector::Iterator index = distributed_vector.Begin();
                    index!= distributed_vector.End();
                    ++index)
            {
                distributed_vector[index] = (double) PetscTools::GetMyRank();
            }
       }

#if (PETSC_VERSION_MAJOR == 3 && PETSC_VERSION_MINOR >= 6) //PETSc 3.6 or later
        // Lock the vector so that modern PETSc (3.6) won't want to change it
        EXCEPT_IF_NOT(VecLockPush(petsc_vec) == 0);
#endif
        {
            DistributedVector distributed_vector_read = factory.CreateDistributedVector(petsc_vec, true);

            for (DistributedVector::Iterator index = distributed_vector_read.Begin();
                    index!= distributed_vector_read.End();
                    ++index)
            {
                TS_ASSERT_EQUALS(distributed_vector_read[index], (double) PetscTools::GetMyRank());
                distributed_vector_read[index] = 2.0;
            }
        }
#if (PETSC_VERSION_MAJOR == 3 && PETSC_VERSION_MINOR >= 6) //PETSc 3.6 or later
        // Take the lock back
        EXCEPT_IF_NOT(VecLockPop(petsc_vec) == 0);
#endif

        PetscTools::Destroy(petsc_vec);
    }
Example #2
0
char* CommandLineArguments::GetValueCorrespondingToOption(const std::string& rOption, int valueNumber)
{
    EXCEPT_IF_NOT(valueNumber>0);
    TestOptionFormat(rOption);

    int index = GetIndexForArgument(rOption);
    int num_args = GetNumberOfArgumentsForOption(rOption, true);
    if (num_args < valueNumber)
    {
        std::stringstream ss;
        ss<<"Index="<<valueNumber<<" requested for '"<<rOption<<"', but only "<<num_args<<" given.";
        EXCEPTION(ss.str());
    }

    return (*p_argv)[index+valueNumber];
}
NodeBasedCellPopulationWithParticles<DIM>::NodeBasedCellPopulationWithParticles(NodesOnlyMesh<DIM>& rMesh,
                                      std::vector<CellPtr>& rCells,
                                      const std::vector<unsigned> locationIndices,
                                      bool deleteMesh)
    : NodeBasedCellPopulation<DIM>(rMesh, rCells, locationIndices, deleteMesh, false)
{
    EXCEPT_IF_NOT(PetscTools::IsSequential());
    if (!locationIndices.empty())
    {
        // Create a set of node indices corresponding to particles
        std::set<unsigned> node_indices;
        std::set<unsigned> location_indices;
        std::set<unsigned> particle_indices;

        for (typename AbstractMesh<DIM,DIM>::NodeIterator node_iter = rMesh.GetNodeIteratorBegin();
             node_iter != rMesh.GetNodeIteratorEnd();
             ++node_iter)
        {
            node_indices.insert(node_iter->GetIndex());
        }
        for (unsigned i=0; i<locationIndices.size(); i++)
        {
            location_indices.insert(locationIndices[i]);
        }

        std::set_difference(node_indices.begin(), node_indices.end(),
                            location_indices.begin(), location_indices.end(),
                            std::inserter(particle_indices, particle_indices.begin()));

        // This method finishes and then calls Validate()
        SetParticles(particle_indices);
    }
    else
    {
        for (typename NodesOnlyMesh<DIM>::NodeIterator node_iter = rMesh.GetNodeIteratorBegin();
             node_iter != rMesh.GetNodeIteratorEnd();
             ++node_iter)
        {
            (*node_iter).SetIsParticle(false);
        }
        NodeBasedCellPopulationWithParticles::Validate();
    }
}
void CellMLToSharedLibraryConverter::ConvertCellmlToSo(const std::string& rCellmlFullPath,
                                                       const std::string& rCellmlFolder)
{
    FileFinder tmp_folder;
    FileFinder build_folder;

    std::string old_cwd = GetCurrentWorkingDirectory();
    // Check that the Chaste build tree exists
    FileFinder chaste_root("", RelativeTo::ChasteBuildRoot);

    if (!chaste_root.IsDir())
    {
        EXCEPTION("No Chaste build tree found at '" << chaste_root.GetAbsolutePath()
                  << "' - you need the source to use CellML models directly in Chaste.");
    }
    FileFinder component_dir(mComponentName, RelativeTo::ChasteBuildRoot);
    if (!component_dir.IsDir())
    {
        EXCEPTION("Unable to convert CellML model: required Chaste component '" << mComponentName
                  << "' does not exist in '" << chaste_root.GetAbsolutePath() << "'.");
    }
    // Try the conversion
    try
    {
        // Need to create a .so file from the CellML...
        if (PetscTools::AmMaster())
        {
            // Create a temporary folder within heart/dynamic
            std::stringstream folder_name;
            folder_name << "dynamic/tmp_" << getpid() << "_" << time(NULL);

#ifdef CHASTE_CMAKE ///todo: #2656 - ignoring all cmake-specific code, revise after cmake transition
#define COVERAGE_IGNORE
            tmp_folder.SetPath(component_dir.GetAbsolutePath() + "/" + folder_name.str(), RelativeTo::Absolute);
            build_folder.SetPath(component_dir.GetAbsolutePath() + "/" + folder_name.str(), RelativeTo::Absolute);
#undef COVERAGE_IGNORE
#else
            tmp_folder.SetPath(component_dir.GetAbsolutePath() + "/" + folder_name.str(), RelativeTo::Absolute);
            build_folder.SetPath(component_dir.GetAbsolutePath() + "/build/" + ChasteBuildDirName() + "/" + folder_name.str(), RelativeTo::Absolute);
#endif

            int ret = mkdir((tmp_folder.GetAbsolutePath()).c_str(), 0700);
            if (ret != 0)
            {
                EXCEPTION("Failed to create temporary folder '" << tmp_folder.GetAbsolutePath() << "' for CellML conversion: "
                          << strerror(errno));
            }

            // Copy the .cellml file (and any relevant others) into the temporary folder
            FileFinder cellml_file(rCellmlFullPath, RelativeTo::Absolute);
            FileFinder cellml_folder = cellml_file.GetParent();
            std::string cellml_leaf_name = cellml_file.GetLeafNameNoExtension();
            std::vector<FileFinder> cellml_files = cellml_folder.FindMatches(cellml_leaf_name + "*");

            BOOST_FOREACH(const FileFinder& r_cellml_file, cellml_files)
            {
                r_cellml_file.CopyTo(tmp_folder);
            }

#ifdef CHASTE_CMAKE ///todo: #2656 - ignoring all cmake-specific code, revise after cmake transition
#define COVERAGE_IGNORE
            std::string cmake_lists_filename = tmp_folder.GetAbsolutePath() + "/CMakeLists.txt";
            std::ofstream cmake_lists_filestream(cmake_lists_filename.c_str());
            cmake_lists_filestream << "cmake_minimum_required(VERSION 2.8.10)\n" <<
                                      "find_package(Chaste COMPONENTS " << mComponentName << ")\n" <<
                                      "chaste_do_cellml(sources " << cellml_file.GetAbsolutePath() << " " << "ON)\n" <<
                                      "set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR})\n" <<
                                      "include_directories(${Chaste_THIRD_PARTY_INCLUDE_DIRS} ${Chaste_INCLUDE_DIRS})\n" <<
                                      "add_library(" << cellml_leaf_name << " SHARED " << "${sources})\n"
                                      //"target_link_libraries(" << cellml_leaf_name << " ${Chaste_LIBRARIES})\n"
                                      ;
            cmake_lists_filestream.close();
            std::string cmake_args = " -DCMAKE_PREFIX_PATH=" + chaste_root.GetAbsolutePath() +
                                     " -DCMAKE_BUILD_TYPE=" + ChasteBuildType() +
                                     " -DBUILD_SHARED_LIBS=ON" +
                                     " -DENABLE_CHASTE_TESTING=OFF" +
                                     " -DChaste_USE_SHARED_LIBS=ON";
            EXPECT0(chdir, tmp_folder.GetAbsolutePath());
            EXPECT0(system, "cmake" + cmake_args + " .");
            EXPECT0(system, "cmake --build . --config " + ChasteBuildType());
#undef COVERAGE_IGNORE
#else
            // Change to Chaste source folder
            EXPECT0(chdir, chaste_root.GetAbsolutePath());
            // Run scons to generate C++ code and compile it to a .so
            EXPECT0(system, "scons --warn=no-all dyn_libs_only=1 build=" + ChasteBuildType() + " " + tmp_folder.GetAbsolutePath());
#endif

            FileFinder so_file(tmp_folder.GetAbsolutePath() + "/lib" + cellml_leaf_name + "." + msSoSuffix, RelativeTo::Absolute);
            EXCEPT_IF_NOT(so_file.Exists());
            // CD back
            EXPECT0(chdir, old_cwd);

            // Copy the .so to the same folder as the original .cellml file
            FileFinder destination_folder(rCellmlFolder, RelativeTo::Absolute);
            so_file.CopyTo(destination_folder);

            if (mPreserveGeneratedSources)
            {
                // Copy generated source code as well
                std::vector<FileFinder> generated_files = build_folder.FindMatches("*.?pp");
                BOOST_FOREACH(const FileFinder& r_generated_file, generated_files)
                {
                    r_generated_file.CopyTo(destination_folder);
                }
            }
            // Delete the temporary folders
            build_folder.DangerousRemove();
            tmp_folder.DangerousRemove();
        }
void NodeBasedCellPopulationWithParticles<DIM>::WriteVtkResultsToFile(const std::string& rDirectory)
{
#ifdef CHASTE_VTK
    // Store the present time as a string
    std::stringstream time;
    time << SimulationTime::Instance()->GetTimeStepsElapsed();

    // Make sure the nodes are ordered contiguously in memory
    NodeMap map(1 + this->mpNodesOnlyMesh->GetMaximumNodeIndex());
    this->mpNodesOnlyMesh->ReMesh(map);

    // Store the number of cells for which to output data to VTK
    unsigned num_nodes = this->GetNumNodes();
    std::vector<double> rank(num_nodes);
    std::vector<double> particles(num_nodes);

    unsigned num_cell_data_items = 0;
    std::vector<std::string> cell_data_names;

    // We assume that the first cell is representative of all cells
    if (num_nodes > 0)
    {
        num_cell_data_items = this->Begin()->GetCellData()->GetNumItems();
        cell_data_names = this->Begin()->GetCellData()->GetKeys();
    }

    std::vector<std::vector<double> > cell_data;
    for (unsigned var=0; var<num_cell_data_items; var++)
    {
        std::vector<double> cell_data_var(num_nodes);
        cell_data.push_back(cell_data_var);
    }

    // Create mesh writer for VTK output
    VtkMeshWriter<DIM, DIM> mesh_writer(rDirectory, "results_"+time.str(), false);
    mesh_writer.SetParallelFiles(*(this->mpNodesOnlyMesh));

    // Iterate over any cell writers that are present
    for (typename std::vector<boost::shared_ptr<AbstractCellWriter<DIM, DIM> > >::iterator cell_writer_iter = this->mCellWriters.begin();
         cell_writer_iter != this->mCellWriters.end();
         ++cell_writer_iter)
    {
        // Create vector to store VTK cell data
        std::vector<double> vtk_cell_data(num_nodes);

        // Loop over nodes
        for (typename AbstractMesh<DIM,DIM>::NodeIterator node_iter = this->mrMesh.GetNodeIteratorBegin();
             node_iter != this->mrMesh.GetNodeIteratorEnd();
             ++node_iter)
        {
            unsigned node_index = node_iter->GetIndex();

            // If this node is a particle (not a cell), then we set the 'dummy' VTK cell data for this to be -2.0...
            if (this->IsParticle(node_index))
            {
                vtk_cell_data[node_index] = -2.0;
            }
            else
            {
                // ...otherwise we populate the vector of VTK cell data as usual
                CellPtr p_cell = this->GetCellUsingLocationIndex(node_index);
                vtk_cell_data[node_index] = (*cell_writer_iter)->GetCellDataForVtkOutput(p_cell, this);
            }
        }

        mesh_writer.AddPointData((*cell_writer_iter)->GetVtkCellDataName(), vtk_cell_data);
    }

    // Loop over cells
    for (typename AbstractCellPopulation<DIM>::Iterator cell_iter = this->Begin();
         cell_iter != this->End();
         ++cell_iter)
    {
        // Get the node index corresponding to this cell
        unsigned global_index = this->GetLocationIndexUsingCell(*cell_iter);
        unsigned node_index = this->rGetMesh().SolveNodeMapping(global_index);

        for (unsigned var=0; var<num_cell_data_items; var++)
        {
            cell_data[var][node_index] = cell_iter->GetCellData()->GetItem(cell_data_names[var]);
        }

        rank[node_index] = (PetscTools::GetMyRank());
    }

    mesh_writer.AddPointData("Process rank", rank);

    // Loop over nodes
    for (typename AbstractMesh<DIM,DIM>::NodeIterator node_iter = this->mrMesh.GetNodeIteratorBegin();
         node_iter != this->mrMesh.GetNodeIteratorEnd();
         ++node_iter)
    {
        unsigned node_index = node_iter->GetIndex();
        particles[node_index] = (double) (this->IsParticle(node_index));
    }

    mesh_writer.AddPointData("Non-particles", particles);

    if (num_cell_data_items > 0)
    {
        for (unsigned var=0; var<cell_data.size(); var++)
        {
            mesh_writer.AddPointData(cell_data_names[var], cell_data[var]);
        }
    }

    mesh_writer.WriteFilesUsingMesh(*(this->mpNodesOnlyMesh));

    *(this->mpVtkMetaFile) << "        <DataSet timestep=\"";
    *(this->mpVtkMetaFile) << SimulationTime::Instance()->GetTimeStepsElapsed();
    *(this->mpVtkMetaFile) << "\" group=\"\" part=\"0\" file=\"results_";
    *(this->mpVtkMetaFile) << SimulationTime::Instance()->GetTimeStepsElapsed();
    EXCEPT_IF_NOT(PetscTools::IsSequential());
    {
        *(this->mpVtkMetaFile) << ".vtu\"/>\n";
    }
/*    {
        // Parallel vtu files  .vtu -> .pvtu
        *(this->mpVtkMetaFile) << ".pvtu\"/>\n";
    }*/
#endif //CHASTE_VTK
}