unsigned compare_images(std::string const& src_fn,
                        std::string const& dest_fn,
                        int threshold,
                        bool alpha)
{
    boost::optional<std::string> type = mapnik::type_from_filename(dest_fn);
    if (!type)
    {
        throw mapnik::image_reader_exception("Failed to detect type of: " + dest_fn);
    }
    std::unique_ptr<mapnik::image_reader> reader1(mapnik::get_image_reader(dest_fn,*type));
    if (!reader1.get())
    {
        throw mapnik::image_reader_exception("Failed to load: " + dest_fn);
    }
    mapnik::image_any const& image_1 = reader1->read(0,0,reader1->width(),reader1->height());

    boost::optional<std::string> type2 = mapnik::type_from_filename(src_fn);
    if (!type2)
    {
        throw mapnik::image_reader_exception("Failed to detect type of: " + src_fn);
    }
    std::unique_ptr<mapnik::image_reader> reader2(mapnik::get_image_reader(src_fn,*type2));
    if (!reader2.get())
    {
        throw mapnik::image_reader_exception("Failed to load: " + src_fn);
    }
    mapnik::image_any const& image_2 = reader2->read(0,0,reader2->width(),reader2->height());

    return mapnik::compare(image_1,image_2,threshold,alpha);
}
Example #2
0
int main()
{
	Reader reader1("./res/test.txt");
	Reader reader2("./res/test2.txt");

	std::string test1reader = reader1.readTextFromFile();
	reader2.readTextFromFile();
	
	std::vector<bool> test2reader = reader1.changeBinaryTextToBinary();
	std::vector<bool> test3reader = reader2.changeBinaryTextToBinary();
	
	std::vector<bool> text{ 1,1,0,1,0,0,1,1,1,0,1,1,1,0 };
	std::vector<bool> polynomial{ 1,0,1,1 };
	std::vector<bool> test4reader = crc(text,polynomial);

	for (auto x : test4reader)
		std::cout << x;
	std::cout << "\n";

	Writer wr("./res/testwriter.txt");

	wr.writeToFile(test1reader);
	wr.addToFile(test4reader);


	std::cin.get();
	return 0;
}
Example #3
0
TEST(PtsReader, Constructor)
{
    PtsReader reader1;

    StageFactory f;
    Stage* reader2(f.createStage("readers.pts"));
    EXPECT_TRUE(reader2);
}
Example #4
0
TEST(PlyReader, Constructor)
{
    PlyReader reader1;

    StageFactory f;
    std::unique_ptr<Stage> reader2(f.createStage("readers.ply"));
    EXPECT_TRUE(reader2.get());
}
Example #5
0
int main(int argc, char* argv[]) {

	if (argc < 2 || argc > 3) {
		std::cerr << "Usage: " << argv[0] << " INFILE [OUTFILE]" << std::endl;
		exit(1);
	}

	std::string input_filename(argv[1]);
	std::string output_filename;
	if (argc != 3) {
		output_filename = std::string("out.sqlite");
	} else {
		output_filename = std::string(argv[2]);
	}

	{
	// from http://stackoverflow.com/questions/1647557/ifstream-how-to-tell-if-specified-file-doesnt-exist/3071528#3071528
	struct stat file_info;
	if (stat(output_filename.c_str(), &file_info) == 0) {
		std::cerr << "ERROR: Output file '" << output_filename << "' exists. Aborting..." << std::endl;
		exit(1);
	}
	}

	std::set<osmium::unsigned_object_id_type> addr_interpolation_node_set;
	name2highways_type name2highway;

	index_pos_type index_pos;
	index_neg_type index_neg;
	location_handler_type location_handler(index_pos, index_neg);
	//location_handler.ignore_errors();

	MemHelper mem_helper;
	//mem_helper.start();
	{
	osmium::io::Reader reader(input_filename);

	FirstHandler first_handler(addr_interpolation_node_set, name2highway);

	osmium::apply(reader, location_handler, first_handler);
	reader.close();
	}
	//mem_helper.stop();

	osmium::io::Reader reader2(input_filename);
	SecondHandler second_handler(output_filename, addr_interpolation_node_set, name2highway);
	osmium::apply(reader2, location_handler, second_handler);
	reader2.close();

	google::protobuf::ShutdownProtobufLibrary();

	std::cout << std::endl;
	mem_helper.print_max();

	std::cout << "\nsoftware finished properly\n" << std::endl;
	return 0;
}
Example #6
0
        void reprocess(std::string preprocessedFile, std::string baseFilename) {
            
            binary_adjacency_list_reader<EdgeDataType> reader(preprocessedFile);
            max_vertex_id = (vid_t) reader.get_max_vertex_id();
            
            
            
            degarray = (vertex_degree *) calloc(max_vertex_id + 1, sizeof(vertex_degree));        
            vid_t nverts = max_vertex_id + 1;
            for(vid_t i=0; i < nverts; i++) {
                degarray[i].id = i;
            }
            
            phase = 0;
            /* Reader will invoke receive_edge() above */
            reader.read_edges(this);
            
            /* Now sort */
            quickSort(degarray, nverts, vertex_degree_less);
            
            /* Create translation table */
            translate_table = (vid_t*) calloc(sizeof(vid_t), nverts);
            for(vid_t i=0; i<nverts; i++) {
                translate_table[degarray[i].id] = i;
            }
            delete degarray;
            
            /* Write translate table */
            std::string translate_table_file = baseFilename + ".vertexmap";
            int df = open(translate_table_file.c_str(), O_RDWR | O_CREAT, S_IROTH | S_IWOTH | S_IWUSR | S_IRUSR);
            if (df < 0) logstream(LOG_ERROR) << "Could not write vertex map: " << translate_table_file <<
                " error: " << strerror(errno) << std::endl;
            assert(df >= 0);
            pwritea(df, translate_table, nverts, 0);
            close(df);
            
            /* Now recreate the processed file */
            std::string tmpfilename = preprocessedFile + ".old";
            rename(preprocessedFile.c_str(), tmpfilename.c_str());
            
            writer = new binary_adjacency_list_writer<EdgeDataType>(preprocessedFile);
            binary_adjacency_list_reader<EdgeDataType> reader2(tmpfilename);

            phase = 1;
            reader2.read_edges(this);
            
            writer->finish();
            delete writer;
            writer = NULL;
                           
            delete translate_table;
        }
TEST(TestBufferReader, TestSubBuffer)
{
  qi::Buffer buffer;
  char tmpStr1[] = "My ";
  char tmpStr2[] = "string!";
  char tmpSubStr[] = "beautiful ";

  buffer.write(tmpStr1, sizeof(tmpStr1));
  {
    qi::Buffer subBuffer;
    subBuffer.write(tmpSubStr, sizeof(tmpSubStr));
    buffer.addSubBuffer(subBuffer);
  }
  buffer.write(tmpStr2, sizeof(tmpStr2));

  qi::BufferReader reader1(buffer);
  ASSERT_EQ(reader1.position(), 0u);
  ASSERT_FALSE(reader1.hasSubBuffer());

  char *resultStr = new char[sizeof(tmpStr1) + sizeof(tmpSubStr) + sizeof(tmpStr2) - 2];

  size_t result = reader1.read(resultStr, sizeof(tmpStr1));
  ASSERT_EQ(result, sizeof(tmpStr1));
  ASSERT_EQ(sizeof(tmpStr1), reader1.position());

  ASSERT_TRUE(reader1.hasSubBuffer());

  {
    try {
      qi::BufferReader reader2(reader1.subBuffer());

      result = reader2.read(resultStr+sizeof(tmpStr1)-1, sizeof(tmpSubStr));
      ASSERT_EQ(result, sizeof(tmpSubStr));
    } catch (std::runtime_error& e) {
      ASSERT_STREQ("", e.what());
    }
  }

  result = reader1.read(resultStr+sizeof(tmpStr1)-1+sizeof(tmpSubStr)-1, sizeof(tmpStr2));

  ASSERT_EQ(result, sizeof(tmpStr2));

  ASSERT_STREQ("My beautiful string!", resultStr);

  delete[] resultStr;
}
Example #8
0
void testDeepAddition(std::string deepFilename1, std::string deepFilename2, std::string filenameComb) {
	deep::DeepImageReader reader(deepFilename1);
	deep::DeepImage * d1 = reader.read();
	//		printDeepImageStats(*d1);

	deep::DeepImageReader reader2(deepFilename2);
	deep::DeepImage * d2 = reader2.read();
	//	printDeepImageStats(*d2);

	d1->addDeepImage(*d2);
	//		printDeepImageStats(*d2);

	deep::Image * combImg = deep::renderDeepImage(*d1);
	writeImageFile(filenameComb, combImg->width(), combImg->height(), 4, combImg->data(0,0,0));
	delete d1;
	delete d2;
	delete combImg;
}
static size_t dual_read_test(const stdString &index_name, const stdString &channel_name,
                             const epicsTime *start = 0, const epicsTime *end = 0)
{
    stdString text;
    size_t num = 0;
    try
    {
        IndexFile index1, index2;
        index1.open(index_name);
        index2.open(index_name);
        RawDataReader reader1(index1);
        RawDataReader reader2(index2);
        const RawValue::Data *value1 = reader1.find(channel_name, start);
        const RawValue::Data *value2 = reader2.find(channel_name, start);
        while ((value1 &&
                (end==0  ||  RawValue::getTime(value1) < *end)) ||
               (value2 &&
                (end==0  ||  RawValue::getTime(value2) < *end)) )
        {
            if (value1 && (end==0  ||  RawValue::getTime(value1) < *end))
            {
                ++num;
                LOG_ASSERT(value1 == reader1.get());
                reader1.toString(text);
                printf("1) %s\n", text.c_str());
                value1 = reader1.next();
            }
            if (value2 && (end==0  ||  RawValue::getTime(value2) < *end))
            {
                ++num;
                LOG_ASSERT(value2 == reader2.get());
                reader2.toString(text);
                printf("2) %s\n", text.c_str());
                value2 = reader2.next();
            }
        }
    }
    catch (GenericException &e)
    {
        printf("Exception:\n%s\n", e.what());
        return 0;
    }
    return num;
}
Example #10
0
void testSubAdd(std::string filename1, std::string filename2) {
	deep::DeepImageReader reader(filename1);
	deep::DeepImage * d1 = reader.read();

	deep::DeepImageReader reader2(filename2);
	deep::DeepImage * d2 = reader2.read();

	d1->subtractDeepImage(*d2);
	deep::Image * subImg = deep::renderDeepImage(*d1);
	delete d1;
	d1 = reader.read();

	d2->subtractDeepImage(*d1);
	deep::Image * subImg2 = deep::renderDeepImage(*d2);

	for (int y = 0; y < subImg->height(); ++y) {
		for (int x = 0; x < subImg->width(); ++x) {
			float a1 = *subImg->data(y, x, 3);
			float a2 = *subImg2->data(y, x, 3);
			float a = std::max(std::min(a1 + a2, 1.f), 0.f);
			for (int c = 0; c < subImg->channels()-1; ++c) {
				float d1 = *subImg->data(y, x, c);
				float d2 = *subImg2->data(y, x, c);
				if (d2 < 0.0) {
					std::cerr << "Less than 0 value at (" << x << "," << y << ")[" << c << "]=" << d2 << std::endl;
					throw std::exception();
				} else {
					*subImg->data(y, x, c) = (a1*d1+a2*d2)/a;
				}
			}
			*subImg->data(y, x, 3) = a;
		}
	}

	std::cout << "Info about " << "deepsubcomb.png" << std::endl;
	printFlatImageStats(*subImg);
	writeImageFile("deepsubcomb.png", subImg->width(), subImg->height(), 4, subImg->data(0,0,0));
	delete d2;
	delete d1;
	delete subImg2;
	delete subImg;
}
Example #11
0
unsigned compare_images(mapnik::image_rgba8 const& src1,
                        std::string const& filepath,
                        int threshold,
                        bool alpha)
{
    boost::optional<std::string> type = mapnik::type_from_filename(filepath);
    if (!type)
    {
        throw mapnik::image_reader_exception("Failed to detect type of: " + filepath);
    }
    std::unique_ptr<mapnik::image_reader> reader2(mapnik::get_image_reader(filepath,*type));
    if (!reader2.get())
    {
        throw mapnik::image_reader_exception("Failed to load: " + filepath);
    }
    mapnik::image_any const& image_2 = reader2->read(0,0,reader2->width(),reader2->height());

    mapnik::image_rgba8 const& src2 = mapnik::util::get<mapnik::image_rgba8>(image_2);
    return mapnik::compare(src1,src2,threshold,alpha);
}
Example #12
0
void testDeepSubtraction(std::string deepFilename1, std::string deepFilename2, std::string filenameSub) {
	deep::DeepImageReader reader(deepFilename1);
	deep::DeepImage * d1 = reader.read();
//		printDeepImageStats(*d1);

	deep::DeepImageReader reader2(deepFilename2);
	deep::DeepImage * d2 = reader2.read();
//	printDeepImageStats(*d2);

	d1->subtractDeepImage(*d2);
//		printDeepImageStats(*d2);

	deep::Image * subImg = deep::renderDeepImage(*d1);
	std::cout << "Info about " << filenameSub << std::endl;
	deep::printFlatImageStats(*subImg);
	writeImageFile(filenameSub, subImg->width(), subImg->height(), 4, subImg->data(0,0,0));
	delete d1;
	delete d2;
	delete subImg;
}
int main(int argc, char* argv[]) {
    if (argc != 2) {
        std::cerr << "Usage: " << argv[0] << " INFILE\n";
        exit(1);
    }

    std::string output_format("SQLite");
    std::string input_filename(argv[1]);
    std::string output_filename("multipolygon.db");

    OGRDataSource* data_source = initialize_database(output_format, output_filename);

    osmium::area::ProblemReporterOGR problem_reporter(data_source);
    osmium::area::Assembler::config_type assembler_config(&problem_reporter);
    assembler_config.enable_debug_output();
    osmium::area::MultipolygonCollector<osmium::area::Assembler> collector(assembler_config);

    std::cerr << "Pass 1...\n";
    osmium::io::Reader reader1(input_filename);
    collector.read_relations(reader1);
    reader1.close();
    std::cerr << "Pass 1 done\n";

    index_type index_pos;
    index_type index_neg;
    location_handler_type location_handler(index_pos, index_neg);
    location_handler.ignore_errors();

    TestHandler test_handler(data_source);

    std::cerr << "Pass 2...\n";
    osmium::io::Reader reader2(input_filename);
    osmium::apply(reader2, location_handler, test_handler, collector.handler([&test_handler](const osmium::memory::Buffer& area_buffer) {
        osmium::apply(area_buffer, test_handler);
    }));
    reader2.close();
    std::cerr << "Pass 2 done\n";

    OGRDataSource::DestroyDataSource(data_source);
    OGRCleanupAll();
}
Example #14
0
    bool compare_images(std::string const& src_fn,std::string const& dest_fn)
    {
        std::unique_ptr<mapnik::image_reader> reader1(mapnik::get_image_reader(dest_fn,"png"));
        if (!reader1.get())
        {
            throw mapnik::image_reader_exception("Failed to load: " + dest_fn);
        }

        std::unique_ptr<mapnik::image_reader> reader2(mapnik::get_image_reader(src_fn,"png"));
        if (!reader2.get())
        {
            throw mapnik::image_reader_exception("Failed to load: " + src_fn);
        }

        const image_any desc_any = reader1->read(0,0,reader1->width(), reader1->height());
        const image_any src_any = reader2->read(0,0,reader2->width(), reader2->height());

        image_rgba8 const& dest = util::get<image_rgba8>(desc_any);
        image_rgba8 const& src = util::get<image_rgba8>(src_any);

        return compare(dest, src, 0, true) == 0;
    }
    void TestPurkinjeCellFactory() throw (Exception)
    {
        TrianglesMeshReader<2,2> reader("mesh/test/data/mixed_dimension_meshes/2D_0_to_1mm_200_elements");
        MixedDimensionMesh<2,2> mixed_mesh;
        mixed_mesh.ConstructFromMeshReader(reader);

        PurkinjeCellFactory cell_factory;
        TS_ASSERT_THROWS_THIS(cell_factory.GetMixedDimensionMesh(),
                              "The mixed dimension mesh object has not been set in the cell factory");
        cell_factory.SetMesh(&mixed_mesh);

        for (AbstractTetrahedralMesh<2,2>::NodeIterator current_node = mixed_mesh.GetNodeIteratorBegin();
             current_node != mixed_mesh.GetNodeIteratorEnd();
             ++current_node)
        {
            AbstractCardiacCellInterface* p_cell = cell_factory.CreatePurkinjeCellForNode( &(*current_node) , NULL);
            double y = current_node->rGetLocation()[1];

            // cable nodes are on y=0.05 (we don't test by index because indices may be permuted in parallel).
            if( fabs(y-0.05) < 1e-8 )
            {
                TS_ASSERT(dynamic_cast<CellDiFrancescoNoble1985FromCellML*>(p_cell) != NULL);
            }
            else
            {
                TS_ASSERT(dynamic_cast<FakeBathCell*>(p_cell) != NULL);
            }
            delete p_cell;
        }

        TS_ASSERT_EQUALS(cell_factory.GetMixedDimensionMesh(), &mixed_mesh);
        TrianglesMeshReader<2,2> reader2("mesh/test/data/2D_0_to_1mm_200_elements");
        TetrahedralMesh<2,2> mesh;
        mesh.ConstructFromMeshReader(reader2);
        TS_ASSERT_THROWS_THIS(cell_factory.SetMesh(&mesh),
                              "AbstractPurkinjeCellFactory must take a MixedDimensionMesh");

    }
int main(){

  std::cout << std::endl;

  std::thread reader1([]{ printNumber("Scott"); });
  std::thread reader2([]{ printNumber("Ritchie"); });
  std::thread w1([]{ addToTeleBook("Scott",1968); });
  std::thread reader3([]{ printNumber("Dijkstra"); });
  std::thread reader4([]{ printNumber("Scott"); });
  std::thread w2([]{ addToTeleBook("Bjarne",1965); });
  std::thread reader5([]{ printNumber("Scott"); });
  std::thread reader6([]{ printNumber("Ritchie"); });
  std::thread reader7([]{ printNumber("Scott"); });
  std::thread reader8([]{ printNumber("Bjarne"); });

  reader1.join();
  reader2.join();
  reader3.join();
  reader4.join();
  reader5.join();
  reader6.join();
  reader7.join();
  reader8.join();
  w1.join();
  w2.join();

  std::cout << std::endl;

  std::cout << "\nThe new telephone book" << std::endl;
  for (auto teleIt: teleBook){
    std::cout << teleIt.first << ": " << teleIt.second << std::endl;
  }

  std::cout << std::endl;

}
Example #17
0
TEST_F(PcapTest, MergeFiles) {
  PcapFilesReader reader(false, 0);
  reader.addFile(0, getFile1());
  reader.addFile(1, getFile2());
  reader.set_packet_handler(packet_handler, (void*)this);
  reader.start();
  int totalPackets = received;
  received = 0;
    
  PcapFilesReader reader1(false, 0);
  reader1.addFile(0, getFile1());
  reader1.set_packet_handler(packet_handler, (void*)this);
  reader1.start();
  int file1Packets = received;
  received = 0;

  PcapFilesReader reader2(false, 0);
  reader2.addFile(0, getFile2());
  reader2.set_packet_handler(packet_handler, (void*)this);
  reader2.start();
  int file2Packets = received;

  ASSERT_EQ(totalPackets, file1Packets + file2Packets);
}
    // Solve a Purkinje problem and check that the solution for the myocardium nodes is exactly the same as
    // the solution of an equivalent monodomain-only problem, that the purkinje voltage for
    // purkinje nodes doesn't change (no purkinje stimulus is given), and is 0 for non-purkinje nodes.
    void TestMonodomainPurkinjeSolver()
    {
        /* The assembly requires 1/time-step,
         * here we are providing enough information without starting a whole simulation */
        PdeSimulationTime::SetTime(0.0);
        PdeSimulationTime::SetPdeTimeStepAndNextTime(0.01, 0.01);

        HeartConfig::Instance()->SetUseAbsoluteTolerance(1e-12);
        HeartConfig::Instance()->SetPurkinjeSurfaceAreaToVolumeRatio(HeartConfig::Instance()->GetSurfaceAreaToVolumeRatio());

        std::string mesh_base("mesh/test/data/mixed_dimension_meshes/2D_0_to_1mm_200_elements");
        TrianglesMeshReader<2,2> reader(mesh_base);
        MixedDimensionMesh<2,2> mesh(DistributedTetrahedralMeshPartitionType::DUMB);
        mesh.ConstructFromMeshReader(reader);

        //The mixed dimension mesh specifies fibre radii, we override these for the purposes of the
        //test
        for (MixedDimensionMesh<2, 2>::CableElementIterator iter = mesh.GetCableElementIteratorBegin();
             iter != mesh.GetCableElementIteratorEnd();
             ++iter)
        {
            (*iter)->SetAttribute(0.56419); //1/sqrt(pi), so that the fibre cross section area is 1.0
        }


        std::string mesh_base2("mesh/test/data/2D_0_to_1mm_200_elements");
        TrianglesMeshReader<2,2> reader2(mesh_base2);
        TetrahedralMesh<2,2> mesh_just_monodomain;
        mesh_just_monodomain.ConstructFromMeshReader(reader2);

        PurkinjeCellFactory cell_factory;
        cell_factory.SetMesh(&mesh);

        NonPurkinjeCellFactory cell_factory_for_just_monodomain;
        cell_factory_for_just_monodomain.SetMesh(&mesh_just_monodomain);

        MonodomainTissue<2> tissue( &cell_factory );
        MonodomainTissue<2> tissue_for_just_monodomain( &cell_factory_for_just_monodomain );

        // Create an empty BCC - zero Neumann BCs will be applied everywhere
        BoundaryConditionsContainer<2,2,2> bcc;
        BoundaryConditionsContainer<2,2,1> bcc_for_just_monodomain;

        MonodomainPurkinjeSolver<2,2> solver(&mesh, &tissue, &bcc);

        MonodomainSolver<2,2> solver_just_monodomain(&mesh_just_monodomain, &tissue_for_just_monodomain, &bcc_for_just_monodomain);


        //Create an initial condition
        DistributedVectorFactory* p_vector_factory = mesh.GetDistributedVectorFactory();
        Vec init_cond = p_vector_factory->CreateVec(2);
        Vec init_cond_just_monodomain = p_vector_factory->CreateVec(1);

        // get the voltage stripes
        DistributedVector ic = mesh.GetDistributedVectorFactory()->CreateDistributedVector(init_cond);
        DistributedVector ic2 = mesh.GetDistributedVectorFactory()->CreateDistributedVector(init_cond_just_monodomain);
        DistributedVector::Stripe volume_stripe = DistributedVector::Stripe(ic, 0);
        DistributedVector::Stripe cable_stripe = DistributedVector::Stripe(ic, 1);

        for (DistributedVector::Iterator index = ic.Begin();
             index != ic.End();
             ++index)
        {
            volume_stripe[index] = tissue.GetCardiacCell(index.Global)->GetVoltage();
            cable_stripe[index] = tissue.GetPurkinjeCell(index.Global)->GetVoltage();//doesn't matter if this is fake
            // make it zero in the cable stripe for the nodes that are not in purkinje ..
        }
        ic.Restore();

        for (DistributedVector::Iterator index = ic2.Begin();
             index != ic2.End();
             ++index)
        {
            ic2[index] = tissue.GetCardiacCell(index.Global)->GetVoltage();
        }
        ic2.Restore();


        double t_end = 1;
        solver.SetTimes(0, t_end);
        solver.SetTimeStep(0.01);
        solver.SetInitialCondition(init_cond);

        solver.SetOutputDirectoryAndPrefix("MonodomainPurkinje","results");
        solver.SetOutputToTxt(true);
        solver.SetPrintingTimestepMultiple(10);

        Vec solution = solver.Solve();

        // the following assumes Luo-Rudy!!
        Vec init_cond_for_just_monodomain = PetscTools::CreateAndSetVec(mesh.GetNumNodes(), -83.853);

        solver_just_monodomain.SetTimes(0, t_end);
        solver_just_monodomain.SetTimeStep(0.01);
        solver_just_monodomain.SetInitialCondition(init_cond_for_just_monodomain);

        Vec solution_just_monodomain = solver_just_monodomain.Solve();


        // Test that certain blocks of the matrix and rhs vector in the monodomain-purkinje solve
        // match the matrix and vector for a normal monodomain solve
        Vec& r_purk_rhs = solver.GetLinearSystem()->rGetRhsVector();
        Vec& r_mono_rhs = solver_just_monodomain.GetLinearSystem()->rGetRhsVector();

        Mat& r_purk_mat = solver.GetLinearSystem()->rGetLhsMatrix();
        Mat& r_mono_mat = solver_just_monodomain.GetLinearSystem()->rGetLhsMatrix();

        TS_ASSERT_EQUALS(PetscVecTools::GetSize(r_purk_rhs), 2*PetscVecTools::GetSize(r_mono_rhs));
        assert(PetscVecTools::GetSize(r_mono_rhs)==mesh.GetNumNodes());

        int lo, hi;
        VecGetOwnershipRange(r_mono_rhs, &lo, &hi);

        // We don't explicitly test the values of the rhs, as this is also tested by comparing the solutions.
        // As the system matrices are different, the results won't be identical (but will be close) for the same linear solver tolerance.
        // for(int i=lo; i<hi; i++)
        // {
        //     TS_ASSERT_DELTA(PetscVecTools::GetElement(r_purk_rhs, 2*i), PetscVecTools::GetElement(r_mono_rhs, i), 1e-8);
        // }

        for(int i=lo; i<hi; i++)
        {
            for(unsigned j=0; j<mesh.GetNumNodes(); j++)
            {
                // 'top-left' block
                TS_ASSERT_DELTA(PetscMatTools::GetElement(r_purk_mat, 2*i,2*j), PetscMatTools::GetElement(r_mono_mat, i,j), 1e-8);
                // 'off-diagonal' blocks
                TS_ASSERT_DELTA(PetscMatTools::GetElement(r_purk_mat, 2*i,2*j+1), 0.0, 1e-8);
                TS_ASSERT_DELTA(PetscMatTools::GetElement(r_purk_mat, 2*i+1,2*j), 0.0, 1e-8);
            }
        }


        ReplicatableVector soln_repl(solution);
        ReplicatableVector soln_mono_repl(solution_just_monodomain);

        for(unsigned i=0; i<mesh.GetNumNodes(); i++)
        {
            if(55<=i && i<=65) // purkinje nodes for this mesh
            {
                //The Purkinje domain is a 1D line embedded within the tissue.
                //It is stimulated in the same way as the tissue domain, therefore
                //the propagation velocity should be the same (within numerical error).
                TS_ASSERT_DELTA(soln_repl[2*i+1], soln_repl[2*i], 1e-1);
            }
            else
            {
                TS_ASSERT_DELTA(soln_repl[2*i+1], 0.0, 1e-4)
            }

            TS_ASSERT_DELTA(soln_repl[2*i], soln_mono_repl[i], 1e-5);
        }

        HeartConfig::Instance()->SetUseStateVariableInterpolation(true);
        TS_ASSERT_THROWS_THIS(MonodomainPurkinjeSolver2d bad_solver(&mesh, &tissue, &bcc),"State-variable interpolation is not yet supported with Purkinje");
        HeartConfig::Instance()->SetUseStateVariableInterpolation(false);


        PetscTools::Destroy(solution);
        PetscTools::Destroy(init_cond);
        PetscTools::Destroy(init_cond_for_just_monodomain);
        PetscTools::Destroy(solution_just_monodomain);
        PetscTools::Destroy(init_cond_just_monodomain);
    }
    /* == Internal pressures ==
     *
     * Next, we run a simulation on a 2d annulus, with an internal pressure applied.
     */
    void TestAnnulusWithInternalPressure() throw (Exception)
    {
        /* The following should require little explanation now */
        TetrahedralMesh<2,2> electrics_mesh;
        QuadraticMesh<2> mechanics_mesh;

        // could (should?) use finer electrics mesh, but keeping electrics simulation time down
        TrianglesMeshReader<2,2> reader1("mesh/test/data/annuli/circular_annulus_960_elements");
        electrics_mesh.ConstructFromMeshReader(reader1);

        TrianglesMeshReader<2,2> reader2("mesh/test/data/annuli/circular_annulus_960_elements_quad",2 /*quadratic elements*/);
        mechanics_mesh.ConstructFromMeshReader(reader2);

        PointStimulus2dCellFactory cell_factory;

        std::vector<unsigned> fixed_nodes;
        std::vector<c_vector<double,2> > fixed_node_locations;
        for(unsigned i=0; i<mechanics_mesh.GetNumNodes(); i++)
        {
            double x = mechanics_mesh.GetNode(i)->rGetLocation()[0];
            double y = mechanics_mesh.GetNode(i)->rGetLocation()[1];

            if (fabs(x)<1e-6 && fabs(y+0.5)<1e-6)  // fixed point (0.0,-0.5) at bottom of mesh
            {
                fixed_nodes.push_back(i);
                c_vector<double,2> new_position;
                new_position(0) = x;
                new_position(1) = y;
                fixed_node_locations.push_back(new_position);
            }
            if (fabs(x)<1e-6 && fabs(y-0.5)<1e-6)  // constrained point (0.0,0.5) at top of mesh
            {
                fixed_nodes.push_back(i);
                c_vector<double,2> new_position;
                new_position(0) = x;
                new_position(1) = ElectroMechanicsProblemDefinition<2>::FREE;
                fixed_node_locations.push_back(new_position);
            }
        }

        /* Increase this end time to see more contraction */
        HeartConfig::Instance()->SetSimulationDuration(30.0);

        ElectroMechanicsProblemDefinition<2> problem_defn(mechanics_mesh);

        problem_defn.SetContractionModel(KERCHOFFS2003,0.1);
        problem_defn.SetUseDefaultCardiacMaterialLaw(COMPRESSIBLE);
        //problem_defn.SetZeroDisplacementNodes(fixed_nodes);
        problem_defn.SetFixedNodes(fixed_nodes, fixed_node_locations);
        problem_defn.SetMechanicsSolveTimestep(1.0);

        FileFinder finder("heart/test/data/fibre_tests/circular_annulus_960_elements.ortho",RelativeTo::ChasteSourceRoot);
        problem_defn.SetVariableFibreSheetDirectionsFile(finder, false);

        /* The elasticity solvers have two nonlinear solvers implemented, one hand-coded and one which uses PETSc's SNES
         * solver. The latter is not the default but can be more robust (and will probably be the default in later
         * versions). This is how it can be used. (This option can also be called if the compiled binary is run from
         * the command line (see ChasteGuides/RunningBinariesFromCommandLine) using the option "-mech_use_snes").
         */
        problem_defn.SetSolveUsingSnes();

        /* Now let us collect all the boundary elements on the inner (endocardial) surface. The following
         * uses knowledge about the geometry - the inner surface is r=0.3, the outer is r=0.5. */
        std::vector<BoundaryElement<1,2>*> boundary_elems;
        for (TetrahedralMesh<2,2>::BoundaryElementIterator iter
               = mechanics_mesh.GetBoundaryElementIteratorBegin();
             iter != mechanics_mesh.GetBoundaryElementIteratorEnd();
             ++iter)
        {
            ChastePoint<2> centroid = (*iter)->CalculateCentroid();
            double r = sqrt( centroid[0]*centroid[0] + centroid[1]*centroid[1] );

            if (r < 0.4)
            {
                BoundaryElement<1,2>* p_element = *iter;
                boundary_elems.push_back(p_element);
            }
        }

        /* This is how to set the pressure to be applied to these boundary elements. The negative sign implies
         * inward pressure.
         */
        problem_defn.SetApplyNormalPressureOnDeformedSurface(boundary_elems, -1.0 /*1 KPa is about 8mmHg*/);
        /* The solver computes the equilibrium solution (given the pressure loading) before the first timestep.
         * As there is a big deformation from the undeformed state to this loaded state, the nonlinear solver may
         * not converge. The following increments the loading (solves with p=-1/3, then p=-2/3, then p=-1), which
         * allows convergence to occur.
         */
        problem_defn.SetNumIncrementsForInitialDeformation(3);

        CardiacElectroMechanicsProblem<2,1> problem(COMPRESSIBLE,
                                                    MONODOMAIN,
                                                    &electrics_mesh,
                                                    &mechanics_mesh,
                                                    &cell_factory,
                                                    &problem_defn,
                                                    "TestAnnulusWithInternalPressure");

        /* If we want stresses and strains output, we can do the following. The deformation gradients and 2nd PK stresses
         * for each element will be written at the requested times.  */
        problem.SetOutputDeformationGradientsAndStress(10.0 /*how often (in ms) to write - should be a multiple of mechanics timestep*/);


        /* Since this test involves a large deformation at t=0, several Newton iterations are required. To see how the nonlinear
         * solve is progressing, you can run from the binary from the command line with the command line argument "-mech_verbose".
         */

        problem.Solve();
        /* Visualise using cmgui, and note the different shapes at t=-1 (undeformed) and t=0 (loaded)
         *
         * Note: if you want to have a time-dependent pressure, you can replace the second parameter (the pressure)
         * in `SetApplyNormalPressureOnDeformedSurface()` with a function pointer (the name of a function) which returns
         * the pressure as a function of time.
         */

    }
Example #20
0
	virtual void set_data (stream_reader * p_reader, t_size stream_size, t_uint32 type, cui::fcl::t_import_feedback & feedback, abort_callback & p_abort)
	{
		fcl::reader reader(p_reader, stream_size, p_abort);
		t_size i, count;
		reader.read_item(count);
		column_list_t newcolumns;
		for (i=0; i<count; i++)
		{
			t_uint32 column_id;
			t_uint32 column_size;

			reader.read_item(column_id);
			reader.read_item(column_size);

			column_t::ptr item = new column_t;

			fcl::reader reader2(reader, column_size, p_abort);

			t_uint32 element_id;
			t_uint32 element_size;

			auto dpiRead = false;

			while (reader2.get_remaining())
			{
				reader2.read_item(element_id);
				reader2.read_item(element_size);

				switch (element_id)
				{
				case identifier_name:
					reader2.read_item(item->name, element_size);
					break;
				case identifier_filter:
					reader2.read_item(item->filter, element_size);
					break;
				case identifier_sort:
					reader2.read_item(item->sort_spec, element_size);
					break;
				case identifier_display:
					reader2.read_item(item->spec, element_size);
					break;
				case identifier_edit_field:
					reader2.read_item(item->edit_field, element_size);
					break;
				case identifier_style:
					reader2.read_item(item->colour_spec, element_size);
					break;
				case identifier_resize:
					reader2.read_item(item->parts);
					break;
				case identifier_width:
					reader2.read_item(item->width.value);
					break;
				case identifier_width_dpi:
					{
						reader2.read_item(item->width.dpi);
						dpiRead = true;
						break;
					}
				case identifier_alignment:
					{
						t_uint32 temp;
						reader2.read_item(temp);
						item->align = ((alignment)temp);
					}
					break;
				case identifier_filter_type:
					{
						t_uint32 temp;
						reader2.read_item(temp);
						item->filter_type = ((playlist_filter_type)temp);
					}
					break;
				case identifier_use_sort:
					reader2.read_item(item->use_custom_sort);
					break;
				case identifier_use_style:
					reader2.read_item(item->use_custom_colour);
					break;
				case identifier_show:
					reader2.read_item(item->show);
					break;
				default:
					reader2.skip(element_size);
					break;
				};
			}
			if (!dpiRead)
				item->width.dpi = uih::GetSystemDpiCached().cx;
			newcolumns.add_item(item);
		}

		g_columns.set_entries_ref(newcolumns);
		refresh_all_playlist_views();	
		pvt::ng_playlist_view_t::g_on_columns_change();
	}
Example #21
0
	virtual void set_data(stream_reader * p_reader, t_size stream_size, t_uint32 type, cui::fcl::t_import_feedback & feedback, abort_callback & p_abort)
	{
		fcl::reader reader(p_reader, stream_size, p_abort);

		t_uint32 element_id;
		t_uint32 element_size;

		pfc::list_t<pvt::group_t> newgroups;
		bool b_groups_set = false;

		while (reader.get_remaining())
		{
			reader.read_item(element_id);
			reader.read_item(element_size);

			switch (element_id)
			{
			case identifier_show_groups:
				reader.read_item(pvt::cfg_grouping);
				break;
			//case identifier_artwork_reflection:
			//	reader.read_item(pvt::cfg_artwork_reflection);
			//	break;
			//case identifier_show_artwork:
			//	reader.read_item(pvt::cfg_show_artwork);
			//	break;
			//case identifier_artwork_width:
			//	reader.read_item(pvt::cfg_artwork_width);
			//	break;
			case identifier_groups:
			{
				t_size i, count;
				reader.read_item(count);
				for (i = 0; i<count; i++)
				{
					t_uint32 group_id;
					t_uint32 group_size;

					reader.read_item(group_id);
					reader.read_item(group_size);

					pvt::group_t item;

					fcl::reader reader2(reader, group_size, p_abort);

					t_uint32 group_element_id;
					t_uint32 group_element_size;

					while (reader2.get_remaining())
					{
						reader2.read_item(group_element_id);
						reader2.read_item(group_element_size);

						switch (group_element_id)
						{
						case identifier_script:
							reader2.read_item(item.string, group_element_size);
							break;
						case identifier_playlist_filter_mode:
						{
							t_uint32 temp;
							reader2.read_item(temp);
							item.filter_type = (playlist_filter_type&)temp;
						}
						break;
						case identifier_playlist_filter_string:
							reader2.read_item(item.filter_playlists, group_element_size);
							break;
						default:
							reader2.skip(group_element_size);
							break;
						};
					}
					newgroups.add_item(item);
				}
				b_groups_set = true;
				break;
			}
			default:
				reader.skip(element_size);
				break;
			};
		}

		if (b_groups_set)
			pvt::g_groups.set_groups(newgroups, false);
		pvt::ng_playlist_view_t::g_on_groups_change();
		//pvt::ng_playlist_view_t::g_on_show_artwork_change();
		//pvt::ng_playlist_view_t::g_on_artwork_width_change();

	}
    void TestDynamicExpansionNoElectroMechanics() throw (Exception)
    {
        TetrahedralMesh<2,2> electrics_mesh;
        QuadraticMesh<2> mechanics_mesh;

        // could (should?) use finer electrics mesh (if there was electrical activity occurring)
        // but keeping electrics simulation time down
        TrianglesMeshReader<2,2> reader1("mesh/test/data/annuli/circular_annulus_960_elements");
        electrics_mesh.ConstructFromMeshReader(reader1);

        TrianglesMeshReader<2,2> reader2("mesh/test/data/annuli/circular_annulus_960_elements_quad",2 /*quadratic elements*/);
        mechanics_mesh.ConstructFromMeshReader(reader2);

        ZeroStimulusCellFactory<CellLuoRudy1991FromCellML,2> cell_factory;

        std::vector<unsigned> fixed_nodes;
        std::vector<c_vector<double,2> > fixed_node_locations;
        for(unsigned i=0; i<mechanics_mesh.GetNumNodes(); i++)
        {
            double x = mechanics_mesh.GetNode(i)->rGetLocation()[0];
            double y = mechanics_mesh.GetNode(i)->rGetLocation()[1];

            if (fabs(x)<1e-6 && fabs(y+0.5)<1e-6)  // fixed point (0.0,-0.5) at bottom of mesh
            {
                fixed_nodes.push_back(i);
                c_vector<double,2> new_position;
                new_position(0) = x;
                new_position(1) = y;
                fixed_node_locations.push_back(new_position);
            }
            if (fabs(x)<1e-6 && fabs(y-0.5)<1e-6)  // constrained point (0.0,0.5) at top of mesh
            {
                fixed_nodes.push_back(i);
                c_vector<double,2> new_position;
                new_position(0) = x;
                new_position(1) = ElectroMechanicsProblemDefinition<2>::FREE;
                fixed_node_locations.push_back(new_position);
            }
        }

        HeartConfig::Instance()->SetSimulationDuration(110.0);

        ElectroMechanicsProblemDefinition<2> problem_defn(mechanics_mesh);

        problem_defn.SetContractionModel(KERCHOFFS2003,0.1);
        problem_defn.SetUseDefaultCardiacMaterialLaw(COMPRESSIBLE);
        //problem_defn.SetZeroDisplacementNodes(fixed_nodes);
        problem_defn.SetFixedNodes(fixed_nodes, fixed_node_locations);
        problem_defn.SetMechanicsSolveTimestep(1.0);

        FileFinder finder("heart/test/data/fibre_tests/circular_annulus_960_elements.ortho", RelativeTo::ChasteSourceRoot);
        problem_defn.SetVariableFibreSheetDirectionsFile(finder, false);

        // The snes solver seems more robust...
        problem_defn.SetSolveUsingSnes();
        problem_defn.SetVerboseDuringSolve(); // #2091

        // This is a 2d problem, so a direct solve (LU factorisation) is possible and will speed things up
        // markedly (might be able to remove this line after #2057 is done..)
        //PetscTools::SetOption("-pc_type", "lu"); // removed - see comments at the end of #1818.

        std::vector<BoundaryElement<1,2>*> boundary_elems;
        for (TetrahedralMesh<2,2>::BoundaryElementIterator iter
               = mechanics_mesh.GetBoundaryElementIteratorBegin();
              iter != mechanics_mesh.GetBoundaryElementIteratorEnd();
              ++iter)
        {
             ChastePoint<2> centroid = (*iter)->CalculateCentroid();
             double r = sqrt( centroid[0]*centroid[0] + centroid[1]*centroid[1] );

             if (r < 0.4)
             {
                 BoundaryElement<1,2>* p_element = *iter;
                 boundary_elems.push_back(p_element);
             }
        }
        problem_defn.SetApplyNormalPressureOnDeformedSurface(boundary_elems, LinearPressureFunction);

        CardiacElectroMechanicsProblem<2,1> problem(COMPRESSIBLE,
                                                    MONODOMAIN,
                                                    &electrics_mesh,
                                                    &mechanics_mesh,
                                                    &cell_factory,
                                                    &problem_defn,
                                                    "TestEmOnAnnulusDiastolicFilling");
        problem.Solve();

        // Hardcoded test of deformed position of (partially constrained) top node of the annulus, to check nothing has changed and that
        // different systems give the same result.
        TS_ASSERT_DELTA(problem.rGetDeformedPosition()[2](0), 0.0, 1e-15);
        TS_ASSERT_DELTA(problem.rGetDeformedPosition()[2](1), 0.5753, 1e-4);
        //Node 0 is on the righthand side, initially at x=0.5 y=0.0
        TS_ASSERT_DELTA(problem.rGetDeformedPosition()[0](0), 0.5376, 1e-4);
        TS_ASSERT_DELTA(problem.rGetDeformedPosition()[0](1), 0.0376, 1e-4);

        MechanicsEventHandler::Headings();
        MechanicsEventHandler::Report();
    }
    void TestStaticExpansionAndElectroMechanics() throw (Exception)
    {
        TetrahedralMesh<2,2> electrics_mesh;
        QuadraticMesh<2> mechanics_mesh;

        // could (should?) use finer electrics mesh, but keeping electrics simulation time down
        TrianglesMeshReader<2,2> reader1("mesh/test/data/annuli/circular_annulus_960_elements");
        electrics_mesh.ConstructFromMeshReader(reader1);

        TrianglesMeshReader<2,2> reader2("mesh/test/data/annuli/circular_annulus_960_elements_quad",2 /*quadratic elements*/);
        mechanics_mesh.ConstructFromMeshReader(reader2);

        PointStimulus2dCellFactory cell_factory;

         std::vector<unsigned> fixed_nodes;
        std::vector<c_vector<double,2> > fixed_node_locations;
        for(unsigned i=0; i<mechanics_mesh.GetNumNodes(); i++)
        {
            double x = mechanics_mesh.GetNode(i)->rGetLocation()[0];
            double y = mechanics_mesh.GetNode(i)->rGetLocation()[1];

            if (fabs(x)<1e-6 && fabs(y+0.5)<1e-6)  // fixed point (0.0,-0.5) at bottom of mesh
            {
                fixed_nodes.push_back(i);
                c_vector<double,2> new_position;
                new_position(0) = x;
                new_position(1) = y;
                fixed_node_locations.push_back(new_position);
            }
            if (fabs(x)<1e-6 && fabs(y-0.5)<1e-6)  // constrained point (0.0,0.5) at top of mesh
            {
                fixed_nodes.push_back(i);
                c_vector<double,2> new_position;
                new_position(0) = x;
                new_position(1) = ElectroMechanicsProblemDefinition<2>::FREE;
                fixed_node_locations.push_back(new_position);
            }
        }

        // NOTE: sometimes the solver fails to converge (nonlinear solver failing to find a solution) during repolarisation.
        // This occurs with this test (on some configurations?) when the end time is set to 400ms. This needs to be
        // investigated - often surprisingly large numbers of newton iterations are needed in part of the repolarisation stage, and
        // then nonlinear solve failure occurs. Sometimes the solver can get past this if the mechanics timestep is decreased.
        //
        // See ticket #2193

        HeartConfig::Instance()->SetSimulationDuration(400.0);

        ElectroMechanicsProblemDefinition<2> problem_defn(mechanics_mesh);

        problem_defn.SetContractionModel(KERCHOFFS2003,0.1);
        problem_defn.SetUseDefaultCardiacMaterialLaw(COMPRESSIBLE);
        //problem_defn.SetZeroDisplacementNodes(fixed_nodes);
        problem_defn.SetFixedNodes(fixed_nodes, fixed_node_locations);
        problem_defn.SetMechanicsSolveTimestep(1.0);

        FileFinder finder("heart/test/data/fibre_tests/circular_annulus_960_elements.ortho", RelativeTo::ChasteSourceRoot);
        problem_defn.SetVariableFibreSheetDirectionsFile(finder, false);

        // The snes solver seems more robust...
        problem_defn.SetSolveUsingSnes();
        problem_defn.SetVerboseDuringSolve(); // #2091

        // This is a 2d problem, so a direct solve (LU factorisation) is possible and will speed things up
        // markedly (might be able to remove this line after #2057 is done..)
        //PetscTools::SetOption("-pc_type", "lu"); // removed - see comments at the end of #1818.

        std::vector<BoundaryElement<1,2>*> boundary_elems;
        for (TetrahedralMesh<2,2>::BoundaryElementIterator iter
               = mechanics_mesh.GetBoundaryElementIteratorBegin();
             iter != mechanics_mesh.GetBoundaryElementIteratorEnd();
             ++iter)
        {
            ChastePoint<2> centroid = (*iter)->CalculateCentroid();
            double r = sqrt( centroid[0]*centroid[0] + centroid[1]*centroid[1] );

            if (r < 0.4)
            {
                BoundaryElement<1,2>* p_element = *iter;
                boundary_elems.push_back(p_element);
            }
        }
        problem_defn.SetApplyNormalPressureOnDeformedSurface(boundary_elems, -1.0 /*1 KPa is about 8mmHg*/);
        problem_defn.SetNumIncrementsForInitialDeformation(10);

        CardiacElectroMechanicsProblem<2,1> problem(COMPRESSIBLE,
                                                    MONODOMAIN,
                                                    &electrics_mesh,
                                                    &mechanics_mesh,
                                                    &cell_factory,
                                                    &problem_defn,
                                                    "TestEmOnAnnulus");

        problem.Solve();


        // We don't really test anything, we mainly just want to verify it solves OK past the initial jump and through
        // the cycle. Have visualised.
        // Hardcoded test of deformed position of (partially constrained) top node of the annulus, to check nothing has changed and that
        // different systems give the same result.
        TS_ASSERT_DELTA(problem.rGetDeformedPosition()[2](0), 0.0, 1e-16);
        TS_ASSERT_DELTA(problem.rGetDeformedPosition()[2](1), 0.5753, 1e-4);
        //Node 0 is on the righthand side, initially at x=0.5 y=0.0
        TS_ASSERT_DELTA(problem.rGetDeformedPosition()[0](0), 0.5376, 1e-4);
        TS_ASSERT_DELTA(problem.rGetDeformedPosition()[0](1), 0.0376, 1e-4);

        MechanicsEventHandler::Headings();
        MechanicsEventHandler::Report();
    }
Example #24
0
	virtual void set_data (stream_reader * p_reader, t_size stream_size, t_uint32 type, cui::fcl::t_import_feedback & feedback, abort_callback & p_abort)
	{
		fcl::reader reader(p_reader, stream_size, p_abort);
		t_uint32 element_id;
		t_uint32 element_size;

		while (reader.get_remaining())
		{
			reader.read_item(element_id);
			reader.read_item(element_size);

			pfc::array_t<t_uint8> data;
			data.set_size(element_size);
			reader.read(data.get_ptr(), data.get_size());
			

			switch (element_id)
			{
			case identifier_global_items:
				g_fonts_manager_data.m_common_items_entry->import(&stream_reader_memblock_ref(data), data.get_size(), type, p_abort);
				break;
			case identifier_global_labels:
				g_fonts_manager_data.m_common_labels_entry->import(&stream_reader_memblock_ref(data), data.get_size(), type, p_abort);
				break;
			case identifier_client_entries:
				{
					stream_reader_memblock_ref stream2(data);
					fcl::reader reader2(&stream2, data.get_size(), p_abort);

					t_size count, i;
					reader2.read_item(count);

					g_fonts_manager_data.m_entries.remove_all();
					g_fonts_manager_data.m_entries.set_count(count);

					for (i=0; i<count; i++)
					{
						t_uint32 element_id2;
						t_uint32 element_size2;
						reader2.read_item(element_id2);
						reader2.read_item(element_size2);
						if (element_id2 == identifier_client_entry)
						{
							pfc::array_t<t_uint8> data2;
							data2.set_size(element_size2);
							reader2.read(data2.get_ptr(), data2.get_size());
							g_fonts_manager_data.m_entries[i] = new fonts_manager_data::entry_t;
							g_fonts_manager_data.m_entries[i]->import(&stream_reader_memblock_ref(data2), data2.get_size(), type, p_abort);
						}
						else
							reader2.skip(element_size2);
					}
				}
				break;
			default:
				reader.skip(element_size);
				break;
			};
		}
		if (g_tab_appearance_fonts.is_active())
		{
			g_tab_appearance_fonts.update_mode_combobox();
			g_tab_appearance_fonts.update_font_desc();
			g_tab_appearance_fonts.update_change();
		}
		g_fonts_manager_data.g_on_common_font_changed(pfc_infinite);
		service_enum_t<cui::fonts::client> font_enum;
		cui::fonts::client::ptr ptr;
		while (font_enum.next(ptr))
			ptr->on_font_changed();
	}
Example #25
0
int main(int argc, char* argv[])
{
    if(argc < 3)
    {
        std::cout
            << "Error: no se especificaron suficientes archivos de entrada." 
            << std::endl;
        return 1;
    }
    
    std::string filename1 = argv[1];
    std::string filename2 = argv[2];
    
    FASTAReader reader1(filename1);
    FASTAReader reader2(filename2);
    
    reader1.setDefault(0);
    reader2.setDefault(1);
    
    //matriz de sustitucion
    int smatrix[]{ 5, -4, -4, -4,
                -4,  5, -4, -4,
                -4, -4,  5, -4,
                -4, -4, -4,  5};
    int gap_open   = 10;
    int gap_extend =  1;
    int match = 5;
    int mismatch = -4;
    
    #pragma omp parallel
    {
        int seq_len = DEFAULT_SEQ_LEN;
        
        //container vectors for sequences
        Buffer<int16_t> seqs1(seq_len * VSIZE, ALNSIZE);
        Buffer<int16_t> seqs2(seq_len * VSIZE, ALNSIZE);
        
        //containers for ids
        std::vector<std::string> seqs1_ids(VSIZE);
        std::vector<std::string> seqs2_ids(VSIZE);
        
        
        
        //legths of sequences
        int seqs1_len[VSIZE];
        int seqs2_len[VSIZE];
        
        //containter for flags
        Buffer<int8_t> flags(seq_len * seq_len * VSIZE, ALNSIZE);
        int16_t __attribute((aligned(ALNSIZE))) scores[VSIZE];
        int16_t __attribute((aligned(ALNSIZE))) ipos[VSIZE];
        int16_t __attribute((aligned(ALNSIZE))) jpos[VSIZE];
        
        //containers for arrays
        int16_t inf = gap_open + gap_extend + 1;
        //int16_t aF[256 * VSIZE] __attribute((aligned(ALNSIZE))) = {(int16_t)(-inf)};
        //int16_t aH[256 * VSIZE] __attribute((aligned(ALNSIZE))) = {0};

        int bsize = 128 * VSIZE;
	
        //Buffer<int16_t> E(bsize, ALNSIZE);
        Buffer<int16_t> F(bsize, ALNSIZE);
        Buffer<int16_t> H(bsize, ALNSIZE);
        //int16_t __attribute((aligned(ALNSIZE))) H[128 * VSIZE];
        
        //alignments
        char aln1[256];
        char aln2[256];
        
        //max sizes
        int max_x, max_y;
        
        //alignment start position
        int x0, y0;
        
        while(read_seqs(reader1, reader2, &seqs1, &seqs2, seqs1_len, seqs2_len, 
              &seqs1_ids, &seqs2_ids))
        {
            max_x = *std::max_element(seqs1_len, seqs1_len + VSIZE) + 1;
            max_y = *std::max_element(seqs2_len, seqs2_len + VSIZE) + 1;
            //E.clear(-inf);
            F.clear(-inf);
            H.clear(0);
            //flags.clear(0);
	    
            smith_waterman(seqs1.data(), seqs2.data(), match, mismatch, gap_open, gap_extend, 
			   flags.data(), scores, ipos, jpos, max_x, max_y, F.data(), H.data());
            
            for(int i = 0; i < VSIZE; i++)
            {
                //std::cout << scores[i] << std::endl;
                //std::cout << ipos[i] << std::endl;
                //std::cout << jpos[i] << std::endl;
                sw_backtrack(i, flags.data(), seqs1.data(), seqs2.data(), max_x, max_y,
                    aln1, aln2, ipos[i], jpos[i], x0, y0);
                //puts(aln1);
                //puts(aln2);
                print_alignment (stdout, seqs1_ids, seqs2_ids, scores, 
                    aln1, aln2, strlen(aln1), i);
            }
        }
    }
    return 0;
}
Example #26
0
File: main.cpp Project: z80/mapper
int main()
{
    vtkRenderer *ren1= vtkRenderer::New();
    ren1->SetBackground( 0.1, 0.2, 0.4 );

    /*
    ocl::STLSurf surf;
    ocl::STLReader reader( L"./test.stl", surf );

    int sz = static_cast<int>( surf.tris.size() );
    for ( std::list<ocl::Triangle>::iterator i=surf.tris.begin(); i!=surf.tris.end(); i++ )
    {
        ocl::Triangle & t = *i;
        vtkSmartPointer<vtkPoints>   pts      = vtkPoints::New();
        vtkSmartPointer<vtkPolyData> polyData = vtkPolyData::New();
        polyData->Allocate();
        vtkSmartPointer<vtkPolyDataMapper> mapper = vtkPolyDataMapper::New();
        mapper->SetInputData( polyData );
        vtkSmartPointer<vtkActor> actor = vtkActor::New();
        actor->SetMapper( mapper );
        actor->GetProperty()->SetColor( 0.75, 0.0, 0.0 );

        for ( int j=0; j<3; j++ )
            pts->InsertNextPoint( t.p[j].x, t.p[j].y, t.p[j].z );
        vtkIdType ids[2];
        ids[0] = 0;
        ids[1] = 1;
        polyData->InsertNextCell( VTK_LINE, 2, ids );
        ids[0] = 1;
        ids[1] = 2;
        polyData->InsertNextCell( VTK_LINE, 2, ids );
        ids[0] = 2;
        ids[1] = 0;
        polyData->InsertNextCell( VTK_LINE, 2, ids );

        polyData->SetPoints( pts );
        mapper->SetScalarRange( 0, sz-1 );

        ren1->AddActor( actor );
    }*/


    ocl::STLSurf surf2;
    ocl::STLReader reader2( L"./test.stl", surf2 );
    // Rotate using arbitrary face. For example, the very first one.
    ocl::Triangle t = *surf2.tris.begin();
    ocl::Point n = t.n;
    double nx, ny;
    // XY projection.
    if ( ( abs( n.x ) > std::numeric_limits<double>::epsilon() ) &&
         ( abs( n.y ) > std::numeric_limits<double>::epsilon() ) )
    {
        // Normalize projection and rotate to match it with Ox.
        double l = sqrt( n.x * n.x + n.y*n.y );
        nx = n.x / l;
        ny = n.y / l;
    }
    else
    {
        // Just unit matrix.
        nx = 1.0;
        ny = 0.0;
    }
    // And now rotate around Oy on minus cosine between n and (0, 0, -1).
    // Again inverted is equal to transposed.
    double c = -n.z;
    double s = sqrt( 1.0-c*c );

    // And resultant transformation is B*A*T.
    double x = t.p[0].x;
    double y = t.p[0].y;
    double z = t.p[0].z;
    double A[4][4];
    A[0][0] = c*nx;  A[0][1] = c*ny;  A[0][2] = s;   A[0][3] = c*(-ny*y-nx*x)-s*z;
    A[1][0] = -ny;   A[1][1] = nx;    A[1][2] = 0.0; A[1][3] = ny*x-nx*y;
    A[2][0] = -nx*s; A[2][1] = -ny*s; A[2][2] = c;   A[2][3] = -c*z-s*(-ny*y-nx*x);
    A[3][0] = 0.0;   A[3][1] = 0.0;   A[3][2] = 0.0; A[3][3] = 1.0;

    vtkSmartPointer<vtkPoints>   pts      = vtkPoints::New();
    vtkSmartPointer<vtkPolyData> polyData = vtkPolyData::New();
    polyData->Allocate();
    vtkSmartPointer<vtkPolyDataMapper> mapper = vtkPolyDataMapper::New();
    mapper->SetInputData( polyData );
    vtkSmartPointer<vtkActor> actor = vtkActor::New();
    actor->SetMapper( mapper );
    actor->GetProperty()->SetColor( 0.0, 0.75, 0.0 );
    actor->GetProperty()->SetOpacity( 0.5 );
    int sz = static_cast<int>( surf2.tris.size() );
    int ind = 0;
    for ( std::list<ocl::Triangle>::iterator i=surf2.tris.begin(); i!=surf2.tris.end(); i++ )
    {
        ocl::Triangle & t = *i;

        for ( int j=0; j<3; j++ )
        {
            double x1 = t.p[j].x;
            double x2 = t.p[j].y;
            double x3 = t.p[j].z;
            double y1 = A[0][0]*x1 + A[0][1]*x2 + A[0][2]*x3 + A[0][3];
            double y2 = A[1][0]*x1 + A[1][1]*x2 + A[1][2]*x3 + A[1][3];
            double y3 = A[2][0]*x1 + A[2][1]*x2 + A[2][2]*x3 + A[2][3];
            pts->InsertNextPoint( y1, y2, y3 );
        }
        vtkIdType ids[3];
        ids[0] = ind;
        ids[1] = ind+1;
        ids[2] = ind+2;
        ind += 3;
        polyData->InsertNextCell( VTK_TRIANGLE, 3, ids );
    }
    polyData->SetPoints( pts );
    mapper->SetScalarRange( 0, sz-1 );

    ren1->AddActor( actor );




    vtkRenderWindow *renWin = vtkRenderWindow::New();
    renWin->AddRenderer( ren1 );
    renWin->SetSize( 300, 300 );

    vtkSmartPointer<vtkCamera> cam = vtkCamera::New();
    cam->SetFocalPoint( 0.0, 0.0, 0.0 );
    cam->SetPosition( 150.0, 150.0, 0.0 );

    ren1->SetActiveCamera( cam );



    vtkRenderWindowInteractor *iren = vtkRenderWindowInteractor::New();
    iren->SetRenderWindow(renWin);
    //vtkInteractorStyleMultiTouchCamera *style = vtkInteractorStyleMultiTouchCamera::New();
    vtkSmartPointer<MouseInteractorStyle> style = vtkSmartPointer<MouseInteractorStyle>::New();
    iren->SetInteractorStyle(style);

    style->SetDefaultRenderer( ren1 );
    style->Data = polyData;

    //Start the event loop
    iren->Initialize();
    iren->Start();

    return 0;
}
Example #27
0
int main(int argc, char* argv[]) {
    static struct option long_options[] = {
        {"help",         no_argument, 0, 'h'},
        {"dump-wkt",     no_argument, 0, 'w'},
        {"dump-objects", no_argument, 0, 'o'},
        {0, 0, 0, 0}
    };

    osmium::handler::DynamicHandler handler;

    while (true) {
        int c = getopt_long(argc, argv, "hwo", long_options, 0);
        if (c == -1) {
            break;
        }

        switch (c) {
            case 'h':
                print_help();
                exit(0);
            case 'w':
                handler.set<WKTDump>(std::cout);
                break;
            case 'o':
                handler.set<osmium::handler::Dump>(std::cout);
                break;
            default:
                exit(1);
        }
    }

    int remaining_args = argc - optind;
    if (remaining_args != 1) {
        std::cerr << "Usage: " << argv[0] << " [OPTIONS] OSMFILE\n";
        exit(1);
    }

    osmium::io::File infile(argv[optind]);

    osmium::area::Assembler::config_type assembler_config;
    osmium::area::MultipolygonCollector<osmium::area::Assembler> collector(assembler_config);

    std::cout << "Pass 1...\n";
    osmium::io::Reader reader1(infile, osmium::osm_entity_bits::relation);
    collector.read_relations(reader1);
    reader1.close();
    std::cout << "Pass 1 done\n";

    std::cout << "Memory:\n";
    collector.used_memory();

    index_pos_type index_pos;
    index_neg_type index_neg;
    location_handler_type location_handler(index_pos, index_neg);
    location_handler.ignore_errors(); // XXX

    std::cout << "Pass 2...\n";
    osmium::io::Reader reader2(infile);
    osmium::apply(reader2, location_handler, collector.handler([&handler](osmium::memory::Buffer&& buffer) {
        osmium::apply(buffer, handler);
    }));
    reader2.close();
    std::cout << "Pass 2 done\n";

    std::cout << "Memory:\n";
    collector.used_memory();

    std::vector<const osmium::Relation*> incomplete_relations = collector.get_incomplete_relations();
    if (!incomplete_relations.empty()) {
        std::cerr << "Warning! Some member ways missing for these multipolygon relations:";
        for (const auto* relation : incomplete_relations) {
            std::cerr << " " << relation->id();
        }
        std::cerr << "\n";
    }
}
    void TestGeometryWithMetisPermuation() throw(Exception)
    {
        std::string mesh_base("mesh/test/data/mixed_dimension_meshes/2D_0_to_1mm_200_elements");
        TrianglesMeshReader<2,2> reader(mesh_base);
        MixedDimensionMesh<2,2> dumb_partition_mesh(DistributedTetrahedralMeshPartitionType::DUMB);
        dumb_partition_mesh.ConstructFromMeshReader(reader);


        for (MixedDimensionMesh<1,2>::CableElementIterator iter = dumb_partition_mesh.GetCableElementIteratorBegin();
             iter != dumb_partition_mesh.GetCableElementIteratorEnd();
             ++iter)
        {
            Element<1,2>& r_element = *(*iter);

            c_matrix<double, 2, 1> jacobian;
            c_matrix<double, 1, 2> inverse_jacobian;
            double jacobian_determinant;

            r_element.CalculateInverseJacobian(jacobian, jacobian_determinant, inverse_jacobian);

            TS_ASSERT_DELTA(jacobian(0,0), 0.01, 1e-6);
            TS_ASSERT_DELTA(jacobian(1,0), 0.0,  1e-6);
            TS_ASSERT_DELTA(inverse_jacobian(0,0), 100, 1e-6);
            TS_ASSERT_DELTA(inverse_jacobian(0,1), 0.0, 1e-6);
            TS_ASSERT_DELTA(jacobian_determinant, 0.01, 1e-6);

            // y value of all the cable nodes should be 0.05
            TS_ASSERT_DELTA(r_element.GetNodeLocation(0,1), 0.05, 1e-6);
            TS_ASSERT_DELTA(r_element.GetNodeLocation(1,1), 0.05, 1e-6);
            // x value at the ends of the cable element can also be anticipated
            TS_ASSERT_DELTA(r_element.GetNodeLocation(0,0), r_element.GetIndex()*0.01, 1e-6);
            TS_ASSERT_DELTA(r_element.GetNodeLocation(1,0), (r_element.GetIndex()+1)*0.01, 1e-6);

        }

        //Test that every cable element has a designated owner
        {
            unsigned local_owned=0u;
            for (unsigned i=0; i<dumb_partition_mesh.GetNumCableElements(); i++)
            {
                if (dumb_partition_mesh.CalculateDesignatedOwnershipOfCableElement(i))
                {
                    local_owned++;
                }
            }
            unsigned total_owned;
            MPI_Allreduce(&local_owned, &total_owned, 1, MPI_UNSIGNED, MPI_SUM, PETSC_COMM_WORLD);
            TS_ASSERT_EQUALS(total_owned, dumb_partition_mesh.GetNumCableElements());
        }

        TrianglesMeshReader<2,2> reader2(mesh_base);
        MixedDimensionMesh<2,2> partitioned_mesh;
        partitioned_mesh.ConstructFromMeshReader(reader2);


        for (MixedDimensionMesh<1,2>::CableElementIterator iter = partitioned_mesh.GetCableElementIteratorBegin();
             iter != partitioned_mesh.GetCableElementIteratorEnd();
             ++iter)
        {
            Element<1,2>& r_element = *(*iter);

            c_matrix<double, 2, 1> jacobian;
            c_matrix<double, 1, 2> inverse_jacobian;
            double jacobian_determinant;

            r_element.CalculateInverseJacobian(jacobian, jacobian_determinant, inverse_jacobian);

            TS_ASSERT_DELTA(jacobian(0,0), 0.01, 1e-6);
            TS_ASSERT_DELTA(jacobian(1,0), 0.0,  1e-6);
            TS_ASSERT_DELTA(inverse_jacobian(0,0), 100, 1e-6);
            TS_ASSERT_DELTA(inverse_jacobian(0,1), 0.0, 1e-6);
            TS_ASSERT_DELTA(jacobian_determinant, 0.01, 1e-6);

            // y value of all the cable nodes should be 0.05
            TS_ASSERT_DELTA(r_element.GetNodeLocation(0,1), 0.05, 1e-6);
            TS_ASSERT_DELTA(r_element.GetNodeLocation(1,1), 0.05, 1e-6);
            // x value at the ends of the cable element can also be anticipated
            TS_ASSERT_DELTA(r_element.GetNodeLocation(0,0), r_element.GetIndex()*0.01, 1e-6);
            TS_ASSERT_DELTA(r_element.GetNodeLocation(1,0), (r_element.GetIndex()+1)*0.01, 1e-6);

        }
        //Test that every cable element has a designated owner
        {
            unsigned local_owned=0u;
            for (unsigned i=0; i<partitioned_mesh.GetNumCableElements(); i++)
            {
                if (partitioned_mesh.CalculateDesignatedOwnershipOfCableElement(i))
                {
                    local_owned++;
                }
            }
            unsigned total_owned;
            MPI_Allreduce(&local_owned, &total_owned, 1, MPI_UNSIGNED, MPI_SUM, PETSC_COMM_WORLD);
            TS_ASSERT_EQUALS(total_owned, partitioned_mesh.GetNumCableElements());
        }
    }
Example #29
0
int main(int argC, char** argV)
{
	boost::program_options::options_description desc("Allowed options");
	bool debug = false;
	std::string input_file1, input_file2, output_file;
	std::string db_host, db_user, db_passw;
	std::string src1_db_name, src1_db_user, src1_db_passw;
	std::string src2_db_name, src2_db_user, src2_db_passw;
	std::string targetDb_name, targetDb_user, targetDb_passw;
	int db_port;
	desc.add_options()
								("help,h", "produce help message")
								("debug,d", "generate debug output")
								("db-host,H", boost::program_options::value< std::string >(&db_host)->default_value("localhost"), "host of the database server")
#ifdef ODB_MYSQL
								("src1-db-name,M", boost::program_options::value< std::string >(&src1_db_name), "name of the first UniPAX source database")
								("src2-db-name,N", boost::program_options::value< std::string >(&src2_db_name), "name of the second UniPAX source database")
								("target-db-name,T", boost::program_options::value< std::string >(&targetDb_name), "name of the UniPAX target database")
								("db-user,U", boost::program_options::value< std::string >(&db_user)->default_value("unipax"), "user name for the connection to the UniPAX database")
								("db-passw,p", boost::program_options::value< std::string >(&db_passw)->default_value("unipax"), "password of the UniPAX database")
								("db-port,P", boost::program_options::value< int >(&db_port)->default_value(3306), "port of the database server")
#elif defined ODB_ORACLE
								("src1-db-name,s1N", boost::program_options::value< std::string >(&src1_db_name), "SID of the first UniPAX source database")
								("src1-db-user,s1U", boost::program_options::value< std::string >(&src1_db_user)->default_value("unipax"), "user name of the first UniPAX source database")
								("src1-db-passw,s1P", boost::program_options::value< std::string >(&src1_db_passw)->default_value("unipax"), "password of the first UniPAX source database")
								("src2-db-name,s2N", boost::program_options::value< std::string >(&src2_db_name), "SID of the second UniPAX source database")
								("src2-db-user,s2U", boost::program_options::value< std::string >(&src2_db_user)->default_value("unipax"), "user name of the second UniPAX source database")
								("src2-db-passw,s2P", boost::program_options::value< std::string >(&src2_db_passw)->default_value("unipax"), "password of the second UniPAX source database")
								("target-db-name,tN", boost::program_options::value< std::string >(&targetDb_name), "name of the UniPAX target database")
								("target-db-user,tU", boost::program_options::value< std::string >(&targetDb_user)->default_value("unipax"), "user name of the UniPAX target database")
								("target-db-passw,tP", boost::program_options::value< std::string >(&targetDb_passw)->default_value("unipax"), "password of the UniPAX target database")
								("db-port,P", boost::program_options::value< int >(&db_port)->default_value(1521), "port of the database server")
#endif
								("input-file1,i", boost::program_options::value< std::string >(&input_file1), "first input file")
								("input-file2,j", boost::program_options::value< std::string >(&input_file2), "second input file")
								("file-output,o", boost::program_options::value< std::string >(&output_file), "use file-output instead of target database")
								;
	boost::program_options::positional_options_description pod;
	pod.add("output-file", -1); // for output
	boost::program_options::variables_map vm;
	boost::program_options::store(boost::program_options::command_line_parser(argC, argV).options(desc).positional(pod).run(), vm);
	boost::program_options::notify(vm);
	if (argC == 1 || vm.count("help"))
	{
		std::cout << desc << std::endl;
		return 0;
	}
	if (vm.count("debug"))
	{
		debug = true;
	}
	//		if (targetDb_name.empty() == output_file.empty())
	//		{
	//				std::cerr << "Please specify either at target database (-T name) or an outfile (-o name)." << std::endl;
	//				return 0;
	//		}
	//		if ((input_file1.empty() != input_file2.empty()) || (src1_db_name.empty() != src2_db_name.empty())
	//						|| (input_file1.empty() == src1_db_name.empty()))
	//		{
	//				std::cerr << "Please specify either input files (-i first -j second) or input databases (-M first -N second)." << std::endl;
	//				return 0;
	//		}
	//		if ((src1_db_name.empty() || !targetDb_name.empty()) && db_passw.empty())
	//		{
	//				std::cout << "Enter password for database access: ";
	//				std::cin >> db_passw;
	//		}
	UniPAX::MergerInputAdapter source1, source2;
	if (!src1_db_name.empty())
	{
		if (debug) std::cout << "input mode: db" << std::endl;
		// setup src DB connections
#ifdef ODB_MYSQL
		UniPAX::mysql::MySQLManager src1_db, src2_db;
		src1_db.setDBCredentials(db_user, db_passw, db_host, db_port, src1_db_name);
		source1 = UniPAX::MergerInputAdapter(src1_db);
		src2_db.setDBCredentials(db_user, db_passw, db_host, db_port, src2_db_name);
		source2 = UniPAX::MergerInputAdapter(src2_db);
#elif defined ODB_ORACLE
		UniPAX::oracle::OracleManager src1_db, src2_db;
		src1_db.setDBCredentials(src1_db_user, src1_db_passw, db_host, db_port, src1_db_name);
		source1 = UniPAX::MergerInputAdapter(src1_db);
		src2_db.setDBCredentials(src2_db_user, src2_db_passw, db_host, db_port, src2_db_name);
		source2 = UniPAX::MergerInputAdapter(src2_db);
#endif
	}
	else
	{
		if (debug) std::cout << "Input mode: file" << std::endl;
		// read infiles

		if (debug) std::cout << "Reading file " << input_file1 << std::endl;
		UniPAX::BIOPAXReader reader1(input_file1);
		reader1.setDebug(false);
		reader1.createObjectsOnly(true);
		if (!reader1.parse()) return 0;
		reader1.createObjectsOnly(false);
		if (!reader1.parse()) return 0;
		if (debug) std::cout << "done!" << std::endl;
		source1 = UniPAX::MergerInputAdapter(UnipaxPtr<UniPAX::PersistenceManager>::type(new UniPAX::PersistenceManager(reader1.getPersistenceManager())));

		if (debug) std::cout << "Reading file " << input_file2 << std::endl;
		UniPAX::BIOPAXReader reader2(input_file2);
		reader2.setDebug(false);
		reader2.createObjectsOnly(true);
		if (!reader2.parse()) return 0;
		reader2.createObjectsOnly(false);
		if (!reader2.parse()) return 0;
		if (debug) std::cout << "done!\n" << std::endl;
		source2 = UniPAX::MergerInputAdapter(UnipaxPtr<UniPAX::PersistenceManager>::type(new UniPAX::PersistenceManager(reader2.getPersistenceManager())));
	}
	source1.setIdGenFunction(&nextId);
	source2.setIdGenFunction(&nextId);
	UniPAX::KernelCollector result;
	std::vector<boost::shared_ptr<UniPAX::UPBase> > _first, _second;
	if (!(source1.getObjectsByType(_first, "Xref", true) && source2.getObjectsByType(_second, "Xref", true)))
	{
		return 0;
	}

	if (debug) std::cout << "Merging " << _first.size() << " with " << _second.size() << " Xref objects:" << std::endl;
	if (!mergeXrefs(result, _first, _second, debug))
	{
		return 0;
	}
	if (debug) std::cout << "Xref objects merged.\n" << std::endl;
	if (debug) std::cout << "Number of merged objects: " << result.getInstanceCount() << std::endl;
	//result.updateAll();
	_first.clear();
	_second.clear();


	if (!(source1.getObjectsByType(_first, "BioSource", false) && source2.getObjectsByType(_second, "BioSource", false)))
	{
		return 0;
	}
	if (debug) std::cout << "Merging " << _first.size() << " with " << _second.size() << " BioSource objects: "<< std::endl;
	if (!mergeBioSources(result, _first, _second, debug))
	{
		return 0;
	}
	if (debug) std::cout << "BioSource objects merged.\n" << std::endl;
	if (debug) std::cout << "Number of merged objects: " << result.getInstanceCount() << std::endl;
	_first.clear();
	_second.clear();

	if (!(source1.getObjectsByType(_first, "Provenance", false) && source2.getObjectsByType(_second, "Provenance", false)))
	{
		return 0;
	}
	if (debug) std::cout << "Merging " << _first.size() << " with " << _second.size() << " Provenance objects: "<< std::endl;
	if (!mergeInstancesOf<UniPAX::Provenance>(result, _first, _second, debug))
	{
		return 0;
	}
	if (debug) std::cout << "Provenance objects merged.\n" << std::endl;
	if (debug) std::cout << "Number of merged objects: " << result.getInstanceCount() << std::endl;
	_first.clear();
	_second.clear();

	if (!(source1.getObjectsByType(_first, "Evidence", false) && source2.getObjectsByType(_second, "Evidence", false)))
	{
		return 0;
	}
	if (debug) std::cout << "Merging " << _first.size() << " with " << _second.size() << " Evidence objects: "<< std::endl;
	if (!mergeInstancesOf<UniPAX::Evidence>(result, _first, _second, debug))
	{
		return 0;
	}
	if (debug) std::cout << "Evidence objects merged.\n" << std::endl;
	if (debug) std::cout << "Number of merged objects: " << result.getInstanceCount() << std::endl;
	_first.clear();
	_second.clear();

	if (!(source1.getObjectsByType(_first, "EntityReference", false) && source2.getObjectsByType(_second, "EntityReference", false)))
	{
		return 0;
	}
	if (debug) std::cout << "Merging " << _first.size() << " with " << _second.size() << " EntityReference objects: "<< std::endl;
	if (!mergeInstancesOf<UniPAX::EntityReference>(result, _first, _second, debug))
	{
		return 0;
	}
	if (debug) std::cout << "EntityReference objects merged.\n" << std::endl;
	if (debug) std::cout << "Number of merged objects: " << result.getInstanceCount() << std::endl;
	_first.clear();
	_second.clear();

	// Entity objects:
	if (!(source1.getObjectsByType(_first, "Gene", true) && source2.getObjectsByType(_second, "Gene", true)))
	{
		return 0;
	}
	if (debug) std::cout << "Merging " << _first.size() << " with " << _second.size() << " Gene objects: "<< std::endl;
	if (!mergeInstancesOf<UniPAX::Gene>(result, _first, _second, debug))
	{
		return 0;
	}
	if (debug) std::cout << "Gene objects merged.\n" << std::endl;
	if (debug) std::cout << "Number of merged objects: " << result.getInstanceCount() << std::endl;
	_first.clear();
	_second.clear();

	if (!(source1.getObjectsByType(_first, "Dna", true) && source2.getObjectsByType(_second, "Dna", true)))
	{
		return 0;
	}
	if (debug) std::cout << "Merging " << _first.size() << " with " << _second.size() << " Dna objects: "<< std::endl;
	if (!mergeEntitiesByRef<UniPAX::Dna>(result, _first, _second, debug))
	{
		return 0;
	}
	if (debug) std::cout << "Dna objects merged.\n" << std::endl;
	if (debug) std::cout << "Number of merged objects: " << result.getInstanceCount() << std::endl;
	_first.clear();
	_second.clear();

	if (!(source1.getObjectsByType(_first, "DnaRegion", true) && source2.getObjectsByType(_second, "DnaRegion", true)))
	{
		return 0;
	}
	if (debug) std::cout << "Merging " << _first.size() << " with " << _second.size() << " DnaRegion objects: "<< std::endl;
	if (!mergeEntitiesByRef<UniPAX::DnaRegion>(result, _first, _second, debug))
	{
		return 0;
	}
	if (debug) std::cout << "DnaRegion objects merged.\n" << std::endl;
	if (debug) std::cout << "Number of merged objects: " << result.getInstanceCount() << std::endl;
	_first.clear();
	_second.clear();

	if (!(source1.getObjectsByType(_first, "Protein", true) && source2.getObjectsByType(_second, "Protein", true)))
	{
		return 0;
	}
	if (debug) std::cout << "Merging " << _first.size() << " with " << _second.size() << " Protein objects: "<< std::endl;
	if (!mergeEntitiesByRef<UniPAX::Protein>(result, _first, _second, debug))
	{
		return 0;
	}
	if (debug) std::cout << "Protein objects merged.\n" << std::endl;
	if (debug) std::cout << "Number of merged objects: " << result.getInstanceCount() << std::endl;
	_first.clear();
	_second.clear();

	if (!(source1.getObjectsByType(_first, "Rna", true) && source2.getObjectsByType(_second, "Rna", true)))
	{
		return 0;
	}
	if (debug) std::cout << "Merging " << _first.size() << " with " << _second.size() << " Rna objects: "<< std::endl;
	if (!mergeEntitiesByRef<UniPAX::Rna>(result, _first, _second, debug))
	{
		return 0;
	}
	if (debug) std::cout << "Rna objects merged.\n" << std::endl;
	if (debug) std::cout << "Number of merged objects: " << result.getInstanceCount() << std::endl;
	_first.clear();
	_second.clear();

	if (!(source1.getObjectsByType(_first, "RnaRegion", true) && source2.getObjectsByType(_second, "RnaRegion", true)))
	{
		return 0;
	}
	if (debug) std::cout << "Merging " << _first.size() << " with " << _second.size() << " RnaRegion objects: "<< std::endl;
	if (!mergeEntitiesByRef<UniPAX::RnaRegion>(result, _first, _second, debug))
	{
		return 0;
	}
	if (debug) std::cout << "RnaRegion objects merged.\n" << std::endl;
	if (debug) std::cout << "Number of merged objects: " << result.getInstanceCount() << std::endl;
	_first.clear();
	_second.clear();

	if (!(source1.getObjectsByType(_first, "SmallMolecule", true) && source2.getObjectsByType(_second, "SmallMolecule", true)))
	{
		return 0;
	}
	if (debug) std::cout << "Merging " << _first.size() << " with " << _second.size() << " SmallMolecule objects: "<< std::endl;
	if (!mergeEntitiesByRef<UniPAX::SmallMolecule>(result, _first, _second, debug))
	{
		return 0;
	}
	if (debug) std::cout << "SmallMolecule objects merged.\n" << std::endl;
	if (debug) std::cout << "Number of merged objects: " << result.getInstanceCount() << std::endl;
	_first.clear();
	_second.clear();

	if (!(source1.getObjectsByType(_first, "Complex", true) && source2.getObjectsByType(_second, "Complex", true)))
	{
		return 0;
	}
	if (debug) std::cout << "Merging " << _first.size() << " with " << _second.size() << " Complex objects: "<< std::endl;
	if (!mergeInstancesOf<UniPAX::Complex>(result, _first, _second, debug))
	{
		return 0;
	}
	if (debug) std::cout << "Complex objects merged.\n" << std::endl;
	if (debug) std::cout << "Number of merged objects: " << result.getInstanceCount() << std::endl;
	_first.clear();
	_second.clear();

	// Add remaining UtilityClass objects...
	if (!(source1.getObjectsByType(_first, "UtilityClass", true) && source2.getObjectsByType(_second, "UtilityClass", true)))
	{
		return 0;
	}
	if (debug) std::cout << "Adding " << _first.size() << " with " << _second.size() << " UtilityClass objects: "<< std::endl;
	for (std::vector<UniPAX::UPBasePtr>::iterator it = _first.begin(); it != _first.end(); ++it)
	{
		if (debug) std::cout << (*it)->getType() << " object found..." << std::endl;
		if (!result.isMerged(*it))
		{

			if (debug) std::cout << "... and not yet merged." << std::endl;

			//if (!(*it)->update(result)) return 0;
			if ((*it)->getTypeID() == UniPAX::ClassType::idStoichiometry)
			{
				UniPAX::StoichiometryPtr stoi = boost::dynamic_pointer_cast<UniPAX::Stoichiometry>(*it);
				if (debug) std::cout << "before copy " << (stoi->getPhysicalEntity() != 0) << std::endl;
				if (!stoi->update(result)) return 0;
				if (debug) std::cout << "before copy after update " << (stoi->getPhysicalEntity() != 0) << std::endl;
			}
			UniPAX::UPBasePtr object = (*it)->dynamic_copy();
			object->setUnipaxId(nextId());
			if (!object->update(result)) return 0;
			if (object->getTypeID() == UniPAX::ClassType::idStoichiometry)
			{
				UniPAX::StoichiometryPtr stoi = boost::dynamic_pointer_cast<UniPAX::Stoichiometry>(object);
				if (debug) std::cout << "after copy " << (stoi->getPhysicalEntity() != 0) << std::endl;
				if (!stoi->update(result)) return 0;
				if (debug) std::cout << "before copy after update " << (stoi->getPhysicalEntity() != 0) << std::endl;
			}
			if (!result.collect(object)) return 0;
			result.addMerge(*it, object);
		}
	}
	for (std::vector<UniPAX::UPBasePtr>::iterator it = _second.begin(); it != _second.end(); ++it)
	{
		if (debug) std::cout << (*it)->getType() << " object found..." << std::endl;
		if (!result.isMerged(*it))
		{
			if (debug) std::cout << "... and not yet merged." << std::endl;

			//if (!(*it)->update(result)) return 0;
			UniPAX::UPBasePtr object = (*it)->dynamic_copy();
			object->setUnipaxId(nextId());
			if (!object->update(result)) return 0;
			if (!result.collect(object)) return 0;
			result.addMerge(*it, object);
		}
	}

	if (debug) std::cout << "UtilityClass objects added.\n" << std::endl;
	if (debug) std::cout << "Number of merged objects: " << result.getInstanceCount() << std::endl;
	_first.clear();
	_second.clear();



	if (!(source1.getObjectsByType(_first, "Interaction", true) && source2.getObjectsByType(_second, "Interaction", true)))
	{
		return 0;
	}
	if (debug) std::cout << "Merging " << _first.size() << " with " << _second.size() << " Interaction objects: "<< std::endl;
	if (!mergeInstancesOf<UniPAX::Interaction>(result, _first, _second, debug))
	{
		return 0;
	}
	if (debug) std::cout << "Interaction objects merged.\n" << std::endl;
	if (debug) std::cout << "Number of merged objects: " << result.getInstanceCount() << std::endl;
	_first.clear();
	_second.clear();

	if (!(source1.getObjectsByType(_first, "Pathway", true) && source2.getObjectsByType(_second, "Pathway", true)))
	{
		return 0;
	}
	if (debug) std::cout << "Merging " << _first.size() << " with " << _second.size() << " Pathway objects: "<< std::endl;
	if (!mergeInstancesOf<UniPAX::Pathway>(result, _first, _second, debug))
	{
		return 0;
	}
	if (debug) std::cout << "Pathway objects merged.\n" << std::endl;
	if (debug) std::cout << "Number of merged objects: " << result.getInstanceCount() << std::endl;
	_first.clear();
	_second.clear();

	if (debug) std::cout << result.isMerged(result.getInstance("175", "")) << std::endl;

	//result.updateAll();

	// \Entity objects


	/*if (debug) std::cout << "Merging BioSource objects:" << std::endl;
		  if (!mergeXrefs(result, _first, _second, debug))
		  {
		  return 0;
		  }
		  if (debug) std::cout << "Xref objects merged." << std::endl;*/

	//UniPAX::PersistenceManager target;
	/*UniPAX::mysql::MySQLManager targetDb;
		  if (!targetDb_name.empty())
		  {
		  targetDb.setDBCredentials(db_user, db_passw, db_host, db_port, targetDb_name);;
		  }*/

	// load all ids from dbs to merge
	/*std::vector<UnipaxId> ids1, ids2;
		  if (!src1_db.getIdsByType(ids1, "UPBase", true))
		  {
		  std::cerr << "Could not retrieve ids from database " << src1_db_name << ". Aborting merge." << std::endl;
		  return 0;
		  }
		  if (!src2_db.getIdsByType(ids2, "UPBase", true))
		  {
		  std::cerr << "Could not retrieve ids from database " << src2_db_name << ". Aborting merge." << std::endl;
		  return 0;
		  }
		  UniPAX::KernelCollector src1_manager, src2_manager;*/
	// merge UtilityClass subtypes

	/*{
		  std::vector<boost::shared_ptr<UniPAX::Xref> > all_xrefs1, all_xrefs2;
		  if (!src1_manager.getObjectsByType(all_xrefs1, "Xref", true))
		  {
		  std::cerr << "Could not retrieve Xref object pointers from database " << src1_db_name << ". Aborting merge." << std::endl;
		  return 0;
		  }
		  if (!src2_manager.getObjectsByType(all_xrefs2, "Xref", true))
		  {
		  std::cerr << "Could not retrieve Xref object pointers from database " << src2_db_name << ". Aborting merge." << std::endl;
		  return 0;
		  }
		  }
		// merge BioSource objects
		{
		std::vector<boost::shared_ptr<UniPAX::BioSource> > all_biosources1, all_biosources2;
		if (!src1_manager.getObjectsByType(all_biosources1, "BioSource", true))
		{
		std::cerr << "Could not retrieve BioSource object from database " << src1_db_name << ". Aborting merge." << std::endl;
		return 0;
		}
		if (!src1_manager.getObjectsByType(all_biosources2, "BioSource", true))
		{
		std::cerr << "Could not retrieve BioSource object from database " << src2_db_name << ". Aborting merge." << std::endl;
		return 0;
		}
		for (std::vector<boost::shared_ptr<UniPAX::BioSource> >::const_iterator it = all_biosources1.begin(); it != all_biosources1.end(); it++)
		{
		if ()
		}

		}*/
	/*for (std::vector<UnipaxId>::const_iterator it = ids1.begin(); it != ids1.end(); it++)
		  {

		  }*/
	UniPAX::BIOPAXWriter writer; // for output

	/*boost::shared_ptr<UniPAX::ProteinReference>  first = boost::dynamic_pointer_cast<UniPAX::ProteinReference>(db.getObjectByID(705070265));
		  boost::shared_ptr<UniPAX::ProteinReference>  second = boost::dynamic_pointer_cast<UniPAX::ProteinReference>(db.getObjectByID(705076958));
		  boost::shared_ptr<UniPAX::BioSource>  first_org = boost::dynamic_pointer_cast<UniPAX::BioSource>(db.getObjectByID(16777233));
		  boost::shared_ptr<UniPAX::BioSource>  second_org = boost::dynamic_pointer_cast<UniPAX::BioSource>(db.getObjectByID(16777218));

		  manager.collect(first);
		  manager.collect(second);
		  writer.setPersistenceManager(manager);
		  writer.write(output_file);

		  UniPAX::KernelCollector manager2;
		// make a copy of first object
		std::cout << first_org.get()->getUnipaxId() << std::endl;
		UniPAX::BioSource tmp_org(*first_org);
		boost::shared_ptr<UniPAX::BioSource> third_org = boost::shared_ptr<UniPAX::BioSource>(&tmp_org);
		// merge second object into new object
		if (third_org->merge(*second_org))
		{
		manager2.collect(third_org);
		manager2.addMerge(second_org, third_org);
		}
		std::cout << "davor" << std::endl;
		first->update(manager2);
		std::cout << "mitte" << std::endl;
		second->update(manager2);
		std::cout << "danach" << std::endl;

		// make a copy of first object
		UniPAX::ProteinReference* tmp = new UniPAX::ProteinReference(*first);
		boost::shared_ptr<UniPAX::ProteinReference> third(tmp);
		// merge second object into new object
		if (third->merge(*second))
		{
		manager2.collect(third);
		manager2.addMerge(second, third);
		}

		//	UniPAX::MySQLManager db2;
		//	db2.setDBCredentials(db_user, db_passw, db_host, db_port, "unipax2");
		//	db2.persist(manager2);
		//	// assign new unipaxId by force
		//	db2.assignIds(manager2, true);*/
	writer.setDebug(false);
	if (true) std::cout << "Writing " << result.getInstanceCount() << " objects to file." << std::endl;
	writer.setPersistenceManager(result);
	writer.write(output_file);

	return 0;
}
Example #30
0
int main(int argc, char *argv[]){
  
  if ( argc < 3 ){

    cout << "execute as ./rec_had_show <param file> <no. events>" <<endl;
    exit(1);

  }
  
  bool succ;
  double truP[3], recDir[3];
  
  string param_file = argv[1];

  int nEvent = atoi( argv[2] );
  
  bhep::gstore data_store;

  bhep::sreader reader(data_store);
  reader.file(param_file);
  reader.group("DATA"); reader.read();
  bhep::sreader reader2(data_store);
  reader2.file(param_file);
  reader2.group("ANA");reader2.read();
  
  //EventManager2 *eman = new EventManager2(data_store,bhep::MUTE);

  //eman->initialize();
  bhep::reader_root inDst;
  inDst.open( data_store.fetch_sstore("idst_file") );
  
  shower_rec* recon = new shower_rec();
  
  recon->initialize( data_store.fetch_dstore("tol"), data_store.fetch_dstore("res") );
  
  TFile *output = new TFile("test_out.root", "recreate");
  TTree *data = new TTree("t1","had. rec. info.");
  
  data->Branch("Success",&succ,"succ/B");
  data->Branch("TrueMom",&truP,"truP[3]/D");
  data->Branch("RecDirection",&recDir,"dir[3]/D");
  
  measurement_vector meas;
  EVector vert(3,0);
  
  for (int i = 0;i < nEvent;i++){
    
    //succ = eman->status();

    //if ( !succ ) return -1;
    //bhep::event& e = eman->read();
    bhep::event& e = inDst.read_event( i );
    std::cout << "...got event " << i <<std::endl;
    get_event_data( e, meas, vert, truP );
    
    if ( meas.size() != 0 ){

      shower *had_show = new shower( meas, vert );
      
      succ = recon->execute( *had_show );
      
      recDir[0] = had_show->get_direction()[0];
      recDir[1] = had_show->get_direction()[1];
      recDir[2] = had_show->get_direction()[2];
      
      data->Fill();
      
      delete had_show;
      stc_tools::destroy( meas );
    }
    
  }
  
  output->Write();
  output->Close();
  
  recon->finalize();
  
  //eman->finalize();
  inDst.close();
  
  return 0;
}