示例#1
0
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);
}
示例#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;
}
示例#3
0
void user (TString filename, int maxIter)
{
  float entries = 0; 
  //you have several parts ex: latino_TTTo2L2Nu_ext1_0001__part8.root 9,10, ......34
  for (int i = 0; i <= maxIter; i++)
   {
    TString file = filename;
    file += std::to_string(i);
    file += ".root";
    std::cout<<file<<std::endl;
    float n = reader1(file);
    entries += n;      
   }
  
  std::cout << entries << std::endl; 
}
示例#4
0
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;
}
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;
}
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();
}
示例#7
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;
    }
示例#8
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);
}
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;

}
示例#10
0
文件: main.cpp 项目: thortiede/unipax
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;
}
示例#11
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";
    }
}
    /* == 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.
         */

    }
int main(int argc, char* argv[]) {
    po::options_description desc("OPTIONS");
    desc.add_options()
        ("help,h", "Print usage information")
        ("verbose,v", "Enable verbose output")
        ("output,o", po::value<std::string>(), "Output file name")
        ("output-format,f", po::value<std::string>()->default_value("SQLite"), "Output OGR format (Default: 'SQLite')")
        ("add-untagged-nodes", "Add untagged nodes to point layer")
        ("add-metadata", "Add columns for version, changeset, timestamp, uid, and user")
        ("features-per-transaction", po::value<int>()->default_value(100000), "Number of features to add per transaction")
    ;

    po::options_description hidden;
    hidden.add_options()
    ("input-filename", po::value<std::string>(), "OSM input file")
    ;

    po::options_description parsed_options;
    parsed_options.add(desc).add(hidden);

    po::positional_options_description positional;
    positional.add("input-filename", 1);

    po::variables_map vm;
    po::store(po::command_line_parser(argc, argv).options(parsed_options).positional(positional).run(), vm);
    po::notify(vm);

    std::string input_filename;
    std::string output_filename;
    std::string output_format{"SQLite"};
    bool debug = false;

    config cfg;

    if (vm.count("help")) {
        print_help(desc);
        std::exit(0);
    }

    if (vm.count("verbose")) {
        cfg.verbose = true;
    }

    if (vm.count("output-format")) {
        output_format = vm["output-format"].as<std::string>();
    }

    if (vm.count("input-filename")) {
        input_filename = vm["input-filename"].as<std::string>();
    }

    if (vm.count("output")) {
        output_filename = vm["output"].as<std::string>();
    } else {
        auto slash = input_filename.rfind('/');
        if (slash == std::string::npos) {
            slash = 0;
        } else {
            ++slash;
        }
        output_filename = input_filename.substr(slash);
        auto dot = output_filename.find('.');
        if (dot != std::string::npos) {
            output_filename.erase(dot);
        }
        output_filename.append(".db");
    }

    int features_per_transaction = 0;
    if (vm.count("features-per-transaction")) {
        features_per_transaction = vm["features-per-transaction"].as<int>();
    }

    if (vm.count("add-untagged-nodes")) {
        cfg.add_untagged_nodes = true;
    }

    if (vm.count("add-metadata")) {
        cfg.add_metadata = true;
    }

    osmium::util::VerboseOutput vout{cfg.verbose};
    vout << "Writing to '" << output_filename << "'\n";

    osmium::area::Assembler::config_type assembler_config;
    if (debug) {
        assembler_config.debug_level = 1;
    }
    osmium::area::MultipolygonCollector<osmium::area::Assembler> collector{assembler_config};

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

    index_type index_pos;
    location_handler_type location_handler{index_pos};
    location_handler.ignore_errors();

    osmium::geom::OGRFactory<> factory {};

    CPLSetConfigOption("OGR_SQLITE_SYNCHRONOUS", "OFF");
    gdalcpp::Dataset dataset{output_format, output_filename, gdalcpp::SRS{factory.proj_string()}, { "SPATIALITE=TRUE", "INIT_WITH_EPSG=no" }};
    dataset.exec("PRAGMA journal_mode = OFF;");
    if (features_per_transaction) {
        dataset.enable_auto_transactions(features_per_transaction);
    }

    MyOGRHandler<decltype(factory)::projection_type> ogr_handler(dataset, factory, cfg);

    vout << "Pass 2...\n";
    osmium::io::Reader reader2{input_filename};

    osmium::apply(reader2, location_handler, ogr_handler, collector.handler([&ogr_handler](const osmium::memory::Buffer& area_buffer) {
        osmium::apply(area_buffer, ogr_handler);
    }));

    reader2.close();
    vout << "Pass 2 done\n";

    auto 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';
    }

    osmium::MemoryUsage memory;
    if (memory.peak()) {
        vout << "Memory used: " << memory.peak() << " MBytes\n";
    }
}
    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();
    }
示例#16
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;
}