bool SAXConfigurationHandler::startElement ( const QString & namespaceURI, 
        const QString & localName, const QString & qName, 
        const QXmlAttributes & atts ) {
    int idx = qName.find ( ':' );
    QString prefix = "";
    if ( idx > 0 ) {
        prefix = qName.left ( idx );
    }
    ConfigurationPtr c(new DefaultConfiguration( localName, 
            getLocationString(), namespaceURI, prefix ));

    // if processing the toplevel item simply push it, otherwise link it
    // with the parent
    if( d->configuration.isNull() ) {
        d->configuration = c;
    } else {
        ConfigurationPtr parent = d->elements.top();
        parent->addChild( c );
    }

    // process attributes
    for( int i = 0; i < atts.length(); i ++ ) {
        c->setAttribute( atts.localName( i ), atts.value( i ) );
    }

    // push currently built configuration to the stack
    d->elements.push( c );

    return true;
}
void	InstrumentTest::testInstrument() {
	debug(LOG_DEBUG, DEBUG_LOG, 0, "testInstrument() begin");
	ConfigurationPtr	config = Configuration::get(dbfilename);
	Database	database = config->database();

	// create an instrument
	Instrument	instrument(database, "BLUBB");

	// add a few components
	InstrumentComponentPtr	camera = InstrumentComponentPtr(
		new InstrumentComponentDirect(DeviceName::Camera,
			DeviceName("camera:simulator/camera"), 7, "localhost"));
	instrument.add(camera);
	InstrumentComponentPtr	ccd = InstrumentComponentPtr(
		new InstrumentComponentDerived(DeviceName::Ccd,
			instrument, DeviceName::Camera, 5));
	instrument.add(ccd);

	// check instrument
	CPPUNIT_ASSERT(instrument.name() == "BLUBB");

	// has method
	debug(LOG_DEBUG, DEBUG_LOG, 0, "test 'has' method");
	CPPUNIT_ASSERT(instrument.has(DeviceName::Camera));
	CPPUNIT_ASSERT(instrument.has(DeviceName::Ccd));

	// component_type method
	debug(LOG_DEBUG, DEBUG_LOG, 0, "test 'component_type' method");
	CPPUNIT_ASSERT(instrument.component_type(DeviceName::Camera)
		== InstrumentComponent::direct);
	CPPUNIT_ASSERT(instrument.component_type(DeviceName::Ccd)
		== InstrumentComponent::derived);

	// devicename method
	debug(LOG_DEBUG, DEBUG_LOG, 0, "test 'devicename' method");
	CPPUNIT_ASSERT(instrument.devicename(DeviceName::Camera)
		== DeviceName("camera:simulator/camera"));
	debug(LOG_DEBUG, DEBUG_LOG, 0, "ccd device: %s",
		instrument.devicename(DeviceName::Ccd).toString().c_str());
	CPPUNIT_ASSERT(instrument.devicename(DeviceName::Ccd)
		== DeviceName("camera:simulator/camera"));

	// name method
	debug(LOG_DEBUG, DEBUG_LOG, 0, "test 'name' method");
	debug(LOG_DEBUG, DEBUG_LOG, 0, "name(camera) = %s",
		instrument.name(DeviceName::Camera).c_str());
	CPPUNIT_ASSERT(instrument.name(DeviceName::Camera)
		== DeviceName("camera:simulator/camera").toString());

	debug(LOG_DEBUG, DEBUG_LOG, 0, "name(ccd) = %s",
		instrument.name(DeviceName::Ccd).c_str());
	CPPUNIT_ASSERT(instrument.name(DeviceName::Ccd) == "camera");

	// unit method
	debug(LOG_DEBUG, DEBUG_LOG, 0, "test 'unit' method");
	CPPUNIT_ASSERT(instrument.unit(DeviceName::Camera) == 7);
	CPPUNIT_ASSERT(instrument.unit(DeviceName::Ccd) == 5);
	
	debug(LOG_DEBUG, DEBUG_LOG, 0, "testInstrument() end");
}
	BulkPipe::BulkPipe(DevicePtr device, ConfigurationPtr conf, InterfacePtr interface, EndpointPtr in, EndpointPtr out, EndpointPtr interrupt, ITokenPtr claimToken):
		_device(device), _conf(conf), _interface(interface), _in(in), _out(out), _interrupt(interrupt), _claimToken(claimToken)
	{
		int currentConfigurationIndex = _device->GetConfiguration();
		if (conf->GetIndex() != currentConfigurationIndex)
			_device->SetConfiguration(conf->GetIndex());
	}
void	ConfigurationTest::testConfiguration() {
	debug(LOG_DEBUG, DEBUG_LOG, 0, "testConfiguration() begin");
	ConfigurationPtr	configuration
		= Configuration::get("configtest.db");
	configuration->set("global", ".", "name1", "value1");
	configuration->set("global", ".", "name2", "value2");
	debug(LOG_DEBUG, DEBUG_LOG, 0, "testConfiguration() end");
}
void	ConfigurationTest::testRemove() {
	debug(LOG_DEBUG, DEBUG_LOG, 0, "testRemove() begin");
	ConfigurationPtr	configuration
		= Configuration::get("configtest.db");
	configuration->remove("global", ".", "name1");
	CPPUNIT_ASSERT(configuration->get("global", ".", "name1", "value3")
		== "value3");
	debug(LOG_DEBUG, DEBUG_LOG, 0, "testRemove() end");
}
Beispiel #6
0
  VectorXd operator()(const VectorXd& x) const {
    m_config->SetDOFValues(toDblVec(x.topRows(m_nDof)));
    OR::Vector ptWorldA, ptWorldB, nWorldA, nWorldB;
    CalcWorldPoints(x, ptWorldA, ptWorldB);
     return toVector3d(ptWorldA - ptWorldB);

  }
    //_______________________________________________________
    bool ExceptionListWidget::checkException( ConfigurationPtr exception )
    {

        while( exception->exceptionPattern().isEmpty() || !QRegExp( exception->exceptionPattern() ).isValid() )
        {

            KMessageBox::error( this, i18n("Regular Expression syntax is incorrect") );
            QPointer<ExceptionDialog> dialog( new ExceptionDialog( this ) );
            dialog->setException( exception );
            if( dialog->exec() == QDialog::Rejected )
            {
                delete dialog;
                return false;
            }

            dialog->save();
            delete dialog;
        }

        return true;
    }
void	InstrumentTest::testSave() {
	debug(LOG_DEBUG, DEBUG_LOG, 0, "testSave() begin");
	ConfigurationPtr	config = Configuration::get(dbfilename);
	Database	database = config->database();
	DeviceMapperConfigurationPtr	devicemapperconfig
		= DeviceMapperConfiguration::get(config);

	// make sure we have an entry in the device mapper for TEST
	DeviceMapperPtr	devicemapper = devicemapperconfig->devicemapper();
	DeviceMap	mapentry(DeviceName("filterwheel:sx/0"));
	mapentry.name("TEST");
	mapentry.unitid(1291);
	mapentry.description("test filterwheel");
	devicemapper->add(mapentry);

	// create an instrument
	InstrumentPtr	instrument(new Instrument(database, "BLUBB"));

	// add a few components
	InstrumentComponentPtr	camera = InstrumentComponentPtr(
		new InstrumentComponentDirect(DeviceName::Camera,
			DeviceName("camera:simulator/camera"), 7, "localhost"));
	instrument->add(camera);
	InstrumentComponentPtr	ccd = InstrumentComponentPtr(
		new InstrumentComponentDerived(DeviceName::Ccd,
			*instrument, DeviceName::Camera, 5));
	instrument->add(ccd);
	InstrumentComponentPtr	filterwheel = InstrumentComponentPtr(
		new InstrumentComponentMapped(DeviceName::Filterwheel,
			database, "TEST"));
	instrument->add(filterwheel);

	// add the instrument to the database
	InstrumentConfigurationPtr	instrumentconfig
		= InstrumentConfiguration::get(config);
	instrumentconfig->addInstrument(instrument);

	debug(LOG_DEBUG, DEBUG_LOG, 0, "testSave() end");
}
Beispiel #9
0
void MainWindow::SaveConfiguration()
{
    try {
        int selected = ui->cbConfiguration->currentIndex();
        if(selected <= 0) throw std::runtime_error("You cannot save over the default configuration.");
        m_server.SaveConfiguration(m_configuration,m_configList[selected - 1]);

        // reload configurations for each device
        Server::DeviceList devices;
        m_server.GetDeviceList(&devices);
        for(Server::DeviceList::iterator device = devices.begin(); device != devices.end(); ++device)
        {
            ConfigurationPtr config = (*device)->GetConfiguration();
            if(config && config->GetName() == m_configList[selected - 1]) {
                (*device)->SetConfiguration(m_server.LoadConfiguration(m_configList[selected - 1]));
            }
        }

        QMessageBox::information(this,"","Configuration saved.");
    } catch(const std::runtime_error& e) {
        QMessageBox::critical(this,"Error creating configuration.",e.what());
    }
}
/**
 * \brief Get a list of interface association Descriptors from the device
 */
std::list<USBDescriptorPtr>	Device::interfaceAssociationDescriptors(
					bool videoonly) throw(USBError) {
	std::list<USBDescriptorPtr>	iadescriptors;

	// see whether there is any additional data that could contain
	// an interface association descriptor
	ConfigurationPtr	config = activeConfig();
	if (config->extra().size() == 0) {
		debug(LOG_DEBUG, DEBUG_LOG, 0, "no data for descriptors");
		return iadescriptors;
	}

	// try to parse additional descriptors
	DescriptorFactory	f(*this);
	std::vector<USBDescriptorPtr>	list = f.descriptors(config->extra());
	debug(LOG_DEBUG, DEBUG_LOG, 0, "found %d additional descriptors",
		list.size());

	// no check whether they are InterfaceAssociationDescriptors
	std::vector<USBDescriptorPtr>::const_iterator	i;
	for (i = list.begin(); i != list.end(); i++) {
		USBDescriptorPtr	dp = *i;
		if (isPtr<InterfaceAssociationDescriptor>(dp)) {
			InterfaceAssociationDescriptor	*iad
				= getPtr<InterfaceAssociationDescriptor>(dp);
			bool	isvideo = iad->isVideoInterfaceCollection();
			debug(LOG_DEBUG, DEBUG_LOG, 0, "isvideo = %s",
				(isvideo) ? "YES" : "NO");
			if ((!videoonly) || (isvideo)) {
				iadescriptors.push_back(dp);
			}
		}
	}

	// return all the interface association descriptors we have found
	return iadescriptors;
}
Beispiel #11
0
  void CalcWorldPointsAndNormal(const VectorXd& x, OR::Vector& ptWorldA, OR::Vector& ptWorldB, OR::Vector& nWorldA, OR::Vector& nWorldB)  const {
    DblVec dofs(x.data(), x.data() + m_nDof);
    OpenRAVE::Vector ptLocalA, ptLocalB;
    ptLocalA.x = x(m_nDof);
    ptLocalA.y = x(m_nDof + 1);
    ptLocalB.x = x(m_nDof + 2);
    ptLocalB.y = x(m_nDof + 3);

    m_config->SetDOFValues(dofs);
    ptWorldA = m_faceA.link->GetTransform() * (m_faceA.Tlf * ptLocalA);
    ptWorldB = m_faceB.link->GetTransform() * (m_faceB.Tlf * ptLocalB);
    
    nWorldA = geometry::quatRotate(geometry::quatMultiply(m_faceA.link->GetTransform().rot,m_faceA.Tlf.rot), OR::Vector(0,0,1));
    nWorldB = geometry::quatRotate(geometry::quatMultiply(m_faceB.link->GetTransform().rot,m_faceB.Tlf.rot), OR::Vector(0,0,1));
    
  }
    void testSerializeToFile () {
        DefaultConfigurationBuilder builder;
        DefaultConfigurationSerializer serializer;
        ConfigurationPtr cg;
        ConfigurationPtr cb;
        QString cge, cbe;
        int cgl, cgc, cbl, cbc;

        //construct good configuration
        cg = builder.buildFromFile( 
                srcdir + "/tests/test_config.xml", 
                cge, cgl, cgc, false );
        CPPUNIT_ASSERT_MESSAGE( 
                QString("%1 at line %2 column %3")
                .arg( cge ).arg( cgl ).arg( cgc ).latin1(), 
                cg );

        CPPUNIT_ASSERT ( 
                cg->setAttribute ( "escaped", "<>&\"'" ) != false );

        CPPUNIT_ASSERT ( serializer.serializeToFile (
                    builddir + "/serialized_config.xml", cg ) );

        //reconstruct good configuration from new file
        cb = builder.buildFromFile( 
                builddir + "/serialized_config.xml", cbe, cbl, cbc );
        CPPUNIT_ASSERT_MESSAGE( 
                QString("%1 at line %2 column %3")
                .arg( cbe ).arg( cbl ).arg( cbc ).latin1(), 
                cb );

        CPPUNIT_ASSERT ( cb->getAttribute ( "escaped" ) == "<>&\"'" );

        // compare both configs
        CPPUNIT_ASSERT ( cg->getName () == cb->getName () );
        // TODO: compare structure
    }
Beispiel #13
0
 FaceContactErrorCalculator(ConfigurationPtr config, const Face& faceA, const Face& faceB) :
   m_config(config), m_faceA(faceA), m_faceB(faceB), m_nDof(m_config->GetDOF()) {}
bool SAXConfigurationHandler::characters ( const QString & ch ) {
    //qDebug( "got characters: `%s'", ch.latin1() );
    ConfigurationPtr c = d->elements.top();
    c->setValue( c->getValue() + ch );
    return true;
}
/**
 * \brief Main function for the snowfocus program
 */
int	main(int argc, char *argv[]) {
	snowstar::CommunicatorSingleton	cs(argc, argv);

	std::string	instrumentname;
	int	steps = 10;
	double	exposuretime = 1.0;
	double	temperature = std::numeric_limits<double>::quiet_NaN();
	std::string	binning;
	std::string	frame;
	std::string	filtername;
	astro::focusing::Focusing::method_type	method
		= astro::focusing::Focusing::FWHM;

	int	c;
	int	longindex;
	while (EOF != (c = getopt_long(argc, argv, "b:c:de:f:hi:m:r:t:",
		longopts, &longindex)))
		switch (c) {
		case 'b':
			binning = optarg;
			break;
		case 'c':
			astro::config::Configuration::set_default(optarg);
			break;
		case 'd':
			debuglevel = LOG_DEBUG;
			break;
		case 'e':
			exposuretime = std::stod(optarg);
			break;
		case 'f':
			filtername = optarg;
			break;
		case 'h':
			usage(argv[0]);
			return EXIT_SUCCESS;
		case 'i':
			instrumentname = optarg;
			break;
		case 'm':
			method = astro::focusing::Focusing::string2method(optarg);
			break;
		case 'r':
			frame = optarg;
			break;
		case 's':
			steps = std::stoi(optarg);
			break;
		case 't':
			temperature = std::stod(optarg);
			break;
		}

	// the next argument is the command
	if (argc <= optind) {
		throw std::runtime_error("not enough arguments");
	}
	std::string	command = argv[optind++];
	debug(LOG_DEBUG, DEBUG_LOG, 0, "command: %s", command.c_str()); 
	if (command == "help") {
		usage(argv[0]);
		return EXIT_SUCCESS;
	}


	// get the configuration
	ConfigurationPtr	config = Configuration::get();

	// check whether we have an instrument
	if (0 == instrumentname.size()) {
		throw std::runtime_error("instrument name not set");
	}
	RemoteInstrument	instrument(config->database(),
						instrumentname);
	// get the device names
	CcdPrx	ccdprx = instrument.ccd_proxy();
	std::string	ccdname = ccdprx->getName();
	FocuserPrx	focuserprx = instrument.focuser_proxy();
	std::string	focusername = focuserprx->getName();
	debug(LOG_DEBUG, DEBUG_LOG, 0, "ccd: %s focuser: %s", ccdname.c_str(),
		focusername.c_str());

	// first get a connection to the server
	Ice::CommunicatorPtr	ic = CommunicatorSingleton::get();
	astro::ServerName	servername
		= instrument.servername(astro::DeviceName::Ccd);
	Ice::ObjectPrx	base = ic->stringToProxy(
				servername.connect("FocusingFactory"));
	FocusingFactoryPrx	focusingfactory
		= FocusingFactoryPrx::checkedCast(base);

	// get the focusing interface
	FocusingPrx	focusing = focusingfactory->get(ccdname, focusername);
	debug(LOG_DEBUG, DEBUG_LOG, 0, "got a focusing proxy");

	// creating a callback
	Ice::ObjectPtr	callback = new FocusCallbackI();
	CallbackAdapter	adapter(ic);
	Ice::Identity	ident = adapter.add(callback);
	focusing->ice_getConnection()->setAdapter(adapter.adapter());

	// handle the simple commands
	if (command == "status") {
		std::cout << "status: ";
		std::cout << focusingstate2string(focusing->status());
		std::cout << std::endl;
		return EXIT_SUCCESS;
	}
	if (command == "history") {
		show_history(focusing->history());
		return EXIT_SUCCESS;
	}
	if (command == "monitor") {
		std::cout << "current status: ";
		std::cout << focusingstate2string(focusing->status());
		std::cout << std::endl;
		focusing->registerCallback(ident);
		signal(SIGINT, handler);
		while (!signal_received) {
			sleep(1);
		}
		focusing->unregisterCallback(ident);
		return EXIT_SUCCESS;
	}

	if (command == "cancel") {
		focusing->cancel();
		std::cout << "cancel command sent" << std::endl;
		return EXIT_SUCCESS;
	}

	// throw exception for unknown commands
	if (command != "start") {
		throw std::runtime_error("unknown command");
	}

	// make sure temperature is set
	CoolerPrx	cooler;
	if (instrument.has(DeviceName::Cooler)) {
		cooler = instrument.cooler_proxy();
	}
	CoolerTask      coolertask(cooler, temperature);
	coolertask.wait();

	// next two arguments are the interval boundaries
	if ((argc - optind) < 2) {
		throw std::runtime_error("missing intervale arguments");
	}
	int	min = std::stoi(argv[optind++]);
	int	max = std::stoi(argv[optind++]);
	debug(LOG_DEBUG, DEBUG_LOG, 0, "interval [%d,%d]", min, max);
	if (min >= max) {
		throw std::runtime_error("not an interval");
	}


	// ensure that focuser is ready
	FocusState	state = focusing->status();
	debug(LOG_DEBUG, DEBUG_LOG, 0, "current state = %d", state);
	if ((state == FocusMOVING) && (state == FocusMEASURING)) {
		throw std::runtime_error("already focusing");
	}

	// set up the exposure
	CcdTask	ccdtask(ccdprx);
	ccdtask.frame(frame);
	ccdtask.binning(binning);
	ccdtask.exposuretime(exposuretime);

	// set up the focusing
	focusing->setSteps(steps);
	focusing->setMethod(convert(method));

	// start the focusing process
	debug(LOG_DEBUG, DEBUG_LOG, 0, "starting between %d and %d", min, max);
	focusing->start(min, max);
	debug(LOG_DEBUG, DEBUG_LOG, 0, "focusing started, status: %d",
		focusing->status());

	// wait for the process to complete
	bool	completed = false;
	signal(SIGINT, handler);
	do {
		sleep(1);
		switch (focusing->status()) {
        	case FocusIDLE:
        	case FocusMOVING:
        	case FocusMEASURING:
			break;
        	case FocusFOCUSED:
        	case FocusFAILED:
			completed = true;
			break;
		}
	} while ((!completed) && (!signal_received));
	if (completed) {
		std::cout << "final focus position: " << focuserprx->current();
		std::cout << std::endl;

		// display the history
		show_history(focusing->history());
	} else {
		std::cout << "focusing incomplete" << std::endl;
		return EXIT_FAILURE;
	}

	return EXIT_SUCCESS;
}
/**
 * \brief Construct a camera from a USB Device
 *
 * The constructor undertakes an extensive analysis of the descriptors
 * to find the video control and video streaming interfaces of the video
 * function of the device. It also makes sure no kernel driver is attached
 * to the device. It does not, however, claim any of the interfaces, this
 * is done when the device is really used.
 * \param _device	an USB device to open as a UVC camera
 * \param force		force opening as camera even if the
 *			interface associaten descriptor does not
 *			declare itself as a video interface association
 *                      descriptor (handles the TIS camera)
 * XXX apparently the force parameter is never used, so the question should be
 *     asked whether we can remove it.
 */
UVCCamera::UVCCamera(Device& _device, bool /* force */) throw(USBError)
	: device(_device) {
	debug(LOG_DEBUG, DEBUG_LOG, 0, "create a UVC camera object");

	// make sure the camera is open, this most probably will not have
	// any effect
	device.open();

	// scan the active configuration for one that has an Interface
	// association descriptor
	ConfigurationPtr config = device.activeConfig();
	if (config->extra().size() == 0) {
		debug(LOG_ERR, DEBUG_LOG, 0, "no extra descriptors");
		throw USBError("no InterfaceAssociationDescriptor");
	}

	// get the list of interface association descriptors
	std::list<USBDescriptorPtr>	iadlist
		= device.interfaceAssociationDescriptors(true);
	if (0 == iadlist.size()) {
		throw USBError("no Video Interface Association found");
	}
	iadptr = *iadlist.begin();
	debug(LOG_DEBUG, DEBUG_LOG, 0, "Video Interface Association found");

	// get the control interface, and the list of interface descriptors
	// for the control interface, and claim it
	uint8_t	ci = controlInterfaceNumber();
	videocontrol = (*config)[ci];
	debug(LOG_DEBUG, DEBUG_LOG, 0, "Control interface number: %d", ci);
	videocontrol->detachKernelDriver();

	// we also need to know all the video control descriptors appended
	// to this InterfaceDescriptor. The VideoControlDescriptorFactory
	// does that.
	debug(LOG_DEBUG, DEBUG_LOG, 0, "parse the video control descriptors");
	InterfaceDescriptorPtr	controlinterface = (*videocontrol)[0];
	VideoControlDescriptorFactory	vcdf(device);
	videocontroldescriptors = vcdf.descriptors(controlinterface->extra());
	std::cout << videocontroldescriptors[0];
	
	// now claim get the various interface descriptors, i.e. the
	// alternate settings for an interface
	int	interfacecount = iad().bInterfaceCount();
	debug(LOG_DEBUG, DEBUG_LOG, 0, "interfaces in association: %d",
		interfacecount);

	// now parse the video streaming interfaces
	debug(LOG_DEBUG, DEBUG_LOG, 0, "parse streaming interface descriptors");
	VideoStreamingDescriptorFactory	vsf(device);
	for (int vsif = controlInterfaceNumber() + 1;
		vsif < controlInterfaceNumber() + iad().bInterfaceCount();
		vsif++) {
		debug(LOG_DEBUG, DEBUG_LOG, 0,
			"analyzing video streaming interface %d", vsif);
		InterfacePtr	interface = (*config)[vsif];
		// only alternate setting 0 contains the formats
		InterfaceDescriptorPtr	id = (*interface)[0];
		std::string	extra = id->extra();
		debug(LOG_DEBUG, DEBUG_LOG, 0, "extra descriptors: %d bytes",
			extra.size());
		USBDescriptorPtr	vsd = vsf.descriptor(extra);
		debug(LOG_DEBUG, DEBUG_LOG, 0, "parse complete");
		videostreaming.push_back(vsd);
	}
	debug(LOG_DEBUG, DEBUG_LOG, 0, "UVCCamera constructed");
}
    void ConfigsParticleDecomp::gather() {
      System& system = getSystemRef();
      esutil::Error err(system.comm);
      
      int nprocs = system.comm->size();
      int myrank = system.comm->rank();
      
      int localN = system.storage->getNRealParticles();
      
      int curNumP = 0;
      boost::mpi::all_reduce(*system.comm, localN, curNumP, std::plus<int>());
      if(myrank==0){
        // check whether the number of particles is the same during the gathering
        if( curNumP != num_of_part ){
          stringstream msg;
          msg<<"   ConfigsParticleDecomp gathers the configurations of the same system\n"
                " with the same number of particles. If you need to store the systems\n"
                " with different number of particles you should use something else."
                " E.g `Configurations`";
          err.setException( msg.str() );
        }
      }

      ConfigurationPtr config = make_shared<Configuration> ();
      for (int rank_i=0; rank_i<nprocs; rank_i++) {
        map< size_t, Real3D > conf;
        if (rank_i == myrank) {
          CellList realCells = system.storage->getRealCells();
          for(CellListIterator cit(realCells); !cit.isDone(); ++cit) {
            int id = cit->id();
            Real3D property = Real3D(0,0,0);
            if(key=="position")
              property = cit->position();
            else if(key=="velocity")
              property = cit->velocity();
            else if(key=="unfolded"){
              Real3D& pos = cit->position();
              Int3D& img = cit->image();
              Real3D Li = system.bc->getBoxL();
              for (int i = 0; i < 3; ++i) property[i] = pos[i] + img[i] * Li[i];
            }
            else{
              stringstream msg;
              msg<<"Error. Key "<<key<<" is unknown. Use position, unfolded or"
                      " velocity.";
              err.setException( msg.str() );
            }
            
            conf[id] = property;
          }
    	}

        boost::mpi::broadcast(*system.comm, conf, rank_i);

        for (map<size_t,Real3D>::iterator itr=conf.begin(); itr != conf.end(); ++itr) {
          size_t id = itr->first;
          Real3D p = itr->second;
          if(idToCpu[id]==myrank) config->set(id, p[0], p[1], p[2]);
        }
      }

      pushConfig(config);
    }
    void Configurations::gather() {

      System& system = getSystemRef();
  
      // determine number of local particles and total particles

      int myN = system.storage->getNRealParticles();
      int maxN;   // maximal number of particles one processor has
      int totalN; // totlal number of particles all processors have

      boost::mpi::all_reduce(*system.comm, myN, maxN, boost::mpi::maximum<int>());
      boost::mpi::all_reduce(*system.comm, myN, totalN, std::plus<int>());

      LOG4ESPP_INFO(logger, "#Partices: me = " << myN << ", max = " << maxN
                            << ", totalN = " << totalN);

      int*  ids         = new int [maxN];  // buffer for gather
      Real3D* coordinates;
      Real3D* velocities;
      Real3D* forces;
      real* radii;

      if (gatherPos)    coordinates = new Real3D [maxN];  // buffer for gather
      if (gatherVel)    velocities  = new Real3D [maxN];  // buffer for gather
      if (gatherForce)  forces      = new Real3D [maxN];  // buffer for gather
      if (gatherRadius) radii       = new real [maxN];  // buffer for gather

      // fill the buffer with my values

      CellList realCells = system.storage->getRealCells();

      int i = 0; 
      for(CellListIterator cit(realCells); !cit.isDone(); ++cit) {
        ids[i] = cit->id();
        if (gatherPos) {
          Real3D pos = cit->position();
          Int3D img = cit->image();
          if (folded)
        	system.bc->foldPosition(pos, img);
          else
        	system.bc->unfoldPosition(pos, img);
          coordinates[i] = pos;
        }
        if (gatherVel)    velocities[i]  = cit->velocity();
        if (gatherForce)  forces[i]      = cit->force();
        if (gatherRadius) radii[i]       = cit->radius();
        i++;
      }

      if (i != myN) {
        LOG4ESPP_ERROR(logger, "mismatch for number of local particles");
      }

      // each proc sends its data to master process

      if (system.comm->rank() == 0) {

         ConfigurationPtr config = make_shared<Configuration> (); //totalN

         // root process collects data from all processors and sets it

         int nproc = system.comm->size();

         for (int iproc = 0; iproc < nproc; iproc++) {
           int nother;
           if (iproc) {
              int nIds, nVals;   // number of received values
              int tmp;
              boost::mpi::request req;
              boost::mpi::status  stat;
              LOG4ESPP_DEBUG(logger, "receive tags from " << iproc);
              req = system.comm->irecv<int>(iproc, DEFAULT_TAG, ids, maxN);
              system.comm->send(iproc, DEFAULT_TAG, 0);
              stat = req.wait();
              nIds = *stat.count<int>();
              if (gatherPos) {
                req = system.comm->irecv<Real3D>(iproc, DEFAULT_TAG, coordinates, maxN);
                system.comm->send(iproc, DEFAULT_TAG, 0);
                stat = req.wait();
                nVals = *stat.count<Real3D>();
                if (nVals != nIds) {
                  LOG4ESPP_ERROR(logger, "serious error collecting data, got " <<
                                nIds << " ids, but " << nVals << " coordinates");
                }
              }
              if (gatherVel) {
                req = system.comm->irecv<Real3D>(iproc, DEFAULT_TAG, velocities, maxN);
                system.comm->send(iproc, DEFAULT_TAG, 0);
                stat = req.wait();
                nVals = *stat.count<Real3D>();
                if (nVals != nIds) {
                  LOG4ESPP_ERROR(logger, "serious error collecting data, got " <<
                                nIds << " ids, but " << nVals << " velocities");
                }
              }
              if (gatherForce) {
                req = system.comm->irecv<Real3D>(iproc, DEFAULT_TAG, forces, maxN);
                system.comm->send(iproc, DEFAULT_TAG, 0);
                stat = req.wait();
                nVals = *stat.count<Real3D>();
                if (nVals != nIds) {
                  LOG4ESPP_ERROR(logger, "serious error collecting data, got " <<
                                nIds << " ids, but " << nVals << " forces");
                }
              }
              if (gatherRadius) {
                req = system.comm->irecv<real>(iproc, DEFAULT_TAG, radii, maxN);
                system.comm->send(iproc, DEFAULT_TAG, 0);
                stat = req.wait();
                nVals = *stat.count<real>();
                if (nVals != nIds) {
                  LOG4ESPP_ERROR(logger, "serious error collecting data, got " <<
                                nIds << " ids, but " << nVals << " radii");
                }
              }
              nother = nIds;
           } else {
             nother = myN;
           }
   
           LOG4ESPP_INFO(logger, "add " << nother << " coordinates of proc " << iproc);

           for (int i = 0; i < nother; i++) {
             //LOG4ESPP_DEBUG(logger, "set coordinates of particle with id = " << index <<
             //                       ": " << coordinates[3*i] << " " <<  coordinates[3*i+1] << " " << coordinates[3*i+2]);
             int index = ids[i];
             if (gatherPos)    config->setCoordinates(index, coordinates[i]);
             if (gatherVel)    config->setVelocities(index, velocities[i]);
             if (gatherForce)  config->setForces(index, forces[i]);
             if (gatherRadius) config->setRadius(index, radii[i]);
           }
        }

        LOG4ESPP_INFO(logger, "save the latest configuration");

        pushConfig(config);

      } else {

       LOG4ESPP_INFO(logger, "proc " << system.comm->rank() << " sends data " 
                      << " of " << myN << " particles");

       // not master process, send data to master process

       int tmp;

       boost::mpi::status stat;

       // wait for a signal (empty message) before sending

       system.comm->irecv<int>(0, DEFAULT_TAG, tmp);
       system.comm->send<int>(0, DEFAULT_TAG, ids, myN);
       if (gatherPos) {
         system.comm->irecv<int>(0, DEFAULT_TAG, tmp);
         system.comm->send<Real3D>(0, DEFAULT_TAG, coordinates, myN);
       }
       if (gatherVel) {
         system.comm->irecv<int>(0, DEFAULT_TAG, tmp);
         system.comm->send<Real3D>(0, DEFAULT_TAG, velocities, myN);
       }
       if (gatherForce) {
         system.comm->irecv<int>(0, DEFAULT_TAG, tmp);
         system.comm->send<Real3D>(0, DEFAULT_TAG, forces, myN);
       }
       if (gatherRadius) {
         system.comm->irecv<int>(0, DEFAULT_TAG, tmp);
         system.comm->send<real>(0, DEFAULT_TAG, radii, myN);
       }
      }

      // ToDo: remove first configuration if capacity is exhausted

      // master process saves the configuration

      if (gatherRadius) delete [] radii;
      if (gatherForce)  delete [] forces;
      if (gatherVel)    delete [] velocities;
      if (gatherPos)    delete [] coordinates;
      delete [] ids;
    }
        python::list StaticStructF::computeArraySingleChain(int nqx, int nqy, int nqz,
                real bin_factor, int chainlength) const {
            //fist the system coords are saved at each CPU
            System& system = getSystemRef();
            esutil::Error err(system.comm);
            Real3D Li = system.bc->getBoxL(); //Box size (Lx, Ly, Lz)

            int nprocs = system.comm->size(); // number of CPUs
            int myrank = system.comm->rank(); // current CPU's number

            int num_part = 0;
            ConfigurationPtr config = make_shared<Configuration > ();
            // loop over all CPU-numbers - to give all CPUs all particle coords
            for (int rank_i = 0; rank_i < nprocs; rank_i++) {
                map< size_t, Real3D > conf;
                if (rank_i == myrank) {
                    CellList realCells = system.storage->getRealCells();
                    for (CellListIterator cit(realCells); !cit.isDone(); ++cit) {
                        int id = cit->id();
                        conf[id] = cit->position();
                    }
                }
                boost::mpi::broadcast(*system.comm, conf, rank_i);

                // for simplicity we will number the particles from 0
                for (map<size_t, Real3D>::iterator itr = conf.begin(); itr != conf.end(); ++itr) {
                    size_t id = itr->first;
                    Real3D p = itr->second;
                    config->set(id, p[0], p[1], p[2]);
                    //config->set(num_part, p[0], p[1], p[2]);
                    num_part++;
                }
            }
            cout << "particles are given to each CPU!\n";
            // now all CPUs have all particle coords and num_part is the total number
            // of particles   

            // use all CPUs
            // TODO it could be a problem if   n_nodes > num_part

            // here starts calculation of the static structure factor

            //step size for qx, qy, qz
            real dqs[3];
            dqs[0] = 2. * M_PIl / Li[0];
            dqs[1] = 2. * M_PIl / Li[1];
            dqs[2] = 2. * M_PIl / Li[2];

            Real3D q;

            //calculations for binning
            real bin_size = bin_factor * min(dqs[0], (dqs[1], dqs[2]));
            real q_sqr_max = nqx * nqx * dqs[0] * dqs[0]
                    + nqy * nqy * dqs[1] * dqs[1]
                    + nqz * nqz * dqs[2] * dqs[2];
            real q_max = sqrt(q_sqr_max);
            int num_bins = (int) ceil(q_max / bin_size);
            vector<real> sq_bin;
            vector<real> q_bin;
            vector<int> count_bin;
            sq_bin.resize(num_bins);
            q_bin.resize(num_bins);
            count_bin.resize(num_bins);

            if (myrank == 0) {
                cout << nprocs << " CPUs\n\n"
                        << "bin size \t" << bin_size << "\n"
                        << "q_max    \t" << q_max << "\n";
            }

            real n_reci = 1. / num_part;
            real chainlength_reci = 1. / chainlength;
            real scos_local = 0; //will store cos-sum on each CPU
            real ssin_local = 0; //will store sin-sum on each CPU   
            //will store the summation of the the single chain structure factor
            real singleChain_localSum = 0;
            Real3D coordP;
            python::list pyli;

            //calculations for parallelizing (over chains)
            int num_chains;
            if (num_part % chainlength == 0)
                num_chains = num_part / chainlength;
            else {
                cout << "ERROR: chainlenght does not match total number of "
                        << "particles. num_part % chainlenght is unequal 0. \n"
                        << "Calculation of SingleChain_StaticStructF aborted\n";
                return pyli;
            }
            int cpp = (int) ceil((double) num_chains / nprocs); //chains per proc
            cout << "chains per proc\t" << cpp << "\n";


            //loop over different q values
            //starting from zero because combinations with negative components 
            //will give the same result in S(q). so S(q) is the same for
            //the 8 vectors q=(x,y,z),(-x,y,z), (x,-y,z),(x,y,-z),(-x,-y,z),...
            for (int hx = -nqx; hx <= nqx; hx++) {
                for (int hy = -nqy; hy <= nqy; hy++) {
                    for (int hz = 0; hz <= nqz; hz++) {

                        //values of q-vector
                        q[0] = hx * dqs[0];
                        q[1] = hy * dqs[1];
                        q[2] = hz * dqs[2];
                        real q_abs = q.abs();

                        //determining the bin number
                        int bin_i = (int) floor(q_abs / bin_size);
                        q_bin[bin_i] += q_abs;
                        count_bin[bin_i] += 1;

                        //resetting the variable that stores the sum for each q-vector
                        singleChain_localSum = 0;

                        //loop over chains (cid is chain_id)
                        for (int cid = myrank * cpp; cid < (1 + myrank) * cpp
                                && cid < num_chains; cid++) {
                            scos_local = 0; //resetting the cos sum for the each chain
                            ssin_local = 0; //resetting the sin sum for the each chain
                            //loop over particles
                            for (int k = cid * chainlength; k < (1 + cid) * chainlength && k < num_part;
                                    k++) {
                                coordP = config->getCoordinates(k);
                                scos_local += cos(q * coordP);
                                ssin_local += sin(q * coordP);
                            }
                            //the (summation part of the) single chain structure 
                            // factors are summed up for the averaging at the 
                            // end (over the chains)
                            singleChain_localSum += scos_local * scos_local
                                    + ssin_local * ssin_local;
                        }


                        if (myrank != 0) {
                            boost::mpi::reduce(*system.comm, singleChain_localSum, plus<real > (), 0);
                        }

                        if (myrank == 0) {
                            real singleChainSum = 0;
                            boost::mpi::reduce(*system.comm, singleChain_localSum, singleChainSum, plus<real > (), 0);
                            sq_bin[bin_i] += singleChainSum;
                        }
                    }
                }
            }
            //creates the python list with the results            
            if (myrank == 0) {
                //starting with bin_i = 1 will leave out the value for q=0, otherwise start with bin_i=0
                for (int bin_i = 1; bin_i < num_bins; bin_i++) {
                    real c = (count_bin[bin_i]) ? 1 / (real) count_bin[bin_i] : 0;
                    sq_bin[bin_i] = n_reci * chainlength_reci * sq_bin[bin_i] * c;
                    q_bin[bin_i] = q_bin[bin_i] * c;

                    python::tuple q_Sq_pair;
                    q_Sq_pair = python::make_tuple(q_bin[bin_i], sq_bin[bin_i]);
                    pyli.append(q_Sq_pair);
                }
            }
            return pyli;
        }
        python::list StaticStructF::computeArray(int nqx, int nqy, int nqz,
                real bin_factor) const {
            time_t start;
            time(&start);
            cout << "collective calc starts " << ctime(&start) << "\n";
            //fist the system coords are saved at each CPU
            System& system = getSystemRef();
            esutil::Error err(system.comm);
            Real3D Li = system.bc->getBoxL(); //Box size (Lx, Ly, Lz)

            int nprocs = system.comm->size(); // number of CPUs
            int myrank = system.comm->rank(); // current CPU's number

            if (myrank == 0) {
                cout << "collective calc starts " << ctime(&start) << "\n";
            }

            int num_part = 0;
            ConfigurationPtr config = make_shared<Configuration > ();
            // loop over all CPU-numbers - to give all CPUs all particle coords
            for (int rank_i = 0; rank_i < nprocs; rank_i++) {
                map< size_t, Real3D > conf;
                if (rank_i == myrank) {
                    CellList realCells = system.storage->getRealCells();
                    for (CellListIterator cit(realCells); !cit.isDone(); ++cit) {
                        int id = cit->id();
                        conf[id] = cit->position();
                    }
                }
                boost::mpi::broadcast(*system.comm, conf, rank_i);

                // for simplicity we will number the particles from 0
                for (map<size_t, Real3D>::iterator itr = conf.begin(); itr != conf.end(); ++itr) {
                    size_t id = itr->first;
                    Real3D p = itr->second;
                    config->set(id, p[0], p[1], p[2]);
                    //config->set(num_part, p[0], p[1], p[2]);
                    num_part++;
                }
            }
            if (myrank == 0) {
                time_t distributed;
                time(&distributed);
                cout << "particles on all CPUs " << ctime(&distributed) << "\n";
                cout << "distribution to CPUs took "
                        << difftime(distributed, start) << " seconds \n";
            }
            // now all CPUs have all particle coords and num_part is the total number
            // of particles

            // use all CPUs
            // TODO it could be a problem if   n_nodes > num_part

            // here starts calculation of the static structure factor

            //step size for qx, qy, qz
            real dqs[3];
            dqs[0] = 2. * M_PIl / Li[0];
            dqs[1] = 2. * M_PIl / Li[1];
            dqs[2] = 2. * M_PIl / Li[2];

            Real3D q;

            //calculations for binning
            real bin_size = bin_factor * min(dqs[0], (dqs[1], dqs[2]));
            real q_sqr_max = nqx * nqx * dqs[0] * dqs[0]
                    + nqy * nqy * dqs[1] * dqs[1]
                    + nqz * nqz * dqs[2] * dqs[2];
            real q_max = sqrt(q_sqr_max);
            int num_bins = (int) ceil(q_max / bin_size);
            vector<real> sq_bin;
            vector<real> q_bin;
            vector<int> count_bin;
            sq_bin.resize(num_bins);
            q_bin.resize(num_bins);
            count_bin.resize(num_bins);

            if (myrank == 0) {
                cout << nprocs << " CPUs\n\n"
                        << "bin size \t" << bin_size << "\n"
                        << "q_max    \t" << q_max << "\n";
            }

            real n_reci = 1. / num_part;
            real scos_local = 0; //will store cos-sum on each CPU
            real ssin_local = 0; //will store sin-sum on each CPU
            int ppp = (int) ceil((double) num_part / nprocs); //particles per proc

            Real3D coordP;

            python::list pyli;

            //loop over different q values
            //starting from zero because combinations with negative components 
            //will give the same result in S(q). so S(q) is the same for
            //the 8 vectors q=(x,y,z),(-x,y,z), (x,-y,z),(x,y,-z),(-x,-y,z),...
            for (int hx = -nqx; hx <= nqx; hx++) {
                for (int hy = -nqy; hy <= nqy; hy++) {
                    for (int hz = 0; hz <= nqz; hz++) {

                        //values of q-vector
                        q[0] = hx * dqs[0];
                        q[1] = hy * dqs[1];
                        q[2] = hz * dqs[2];
                        real q_abs = q.abs();

                        //determining the bin number
                        int bin_i = (int) floor(q_abs / bin_size);
                        q_bin[bin_i] += q_abs;
                        count_bin[bin_i] += 1;

                        //resetting the variables that store the local sum on each proc
                        scos_local = 0;
                        ssin_local = 0;

                        //loop over particles
                        for (int k = myrank * ppp; k < (1 + myrank) * ppp && k < num_part;
                                k++) {
                            coordP = config->getCoordinates(k);
                            scos_local += cos(q * coordP);
                            ssin_local += sin(q * coordP);
                        }
                        if (myrank != 0) {
                            boost::mpi::reduce(*system.comm, scos_local, plus<real > (), 0);
                            boost::mpi::reduce(*system.comm, ssin_local, plus<real > (), 0);
                        }

                        if (myrank == 0) {
                            real scos = 0;
                            real ssin = 0;
                            boost::mpi::reduce(*system.comm, scos_local, scos, plus<real > (), 0);
                            boost::mpi::reduce(*system.comm, ssin_local, ssin, plus<real > (), 0);
                            sq_bin[bin_i] += scos * scos + ssin * ssin;
                        }
                    }
                }
            }
            //creates the python list with the results            
            if (myrank == 0) {
                //starting with bin_i = 1 will leave out the value for q=0, otherwise start with bin_i=0
                for (int bin_i = 1; bin_i < num_bins; bin_i++) {
                    real c = (count_bin[bin_i]) ? 1 / (real) count_bin[bin_i] : 0;
                    sq_bin[bin_i] = n_reci * sq_bin[bin_i] * c;
                    q_bin[bin_i] = q_bin[bin_i] * c;

                    python::tuple q_Sq_pair;
                    q_Sq_pair = python::make_tuple(q_bin[bin_i], sq_bin[bin_i]);
                    pyli.append(q_Sq_pair);
                }
            }
            return pyli;
        }
int	main(int argc, char *argv[]) {
	debugthreads = 1;
	Exposure	exposure;
	unsigned int	nImages = 1;
	std::string	reponame;
	std::string	filtername;
	int	c;
	int	longindex;
	double	temperature = std::numeric_limits<double>::quiet_NaN();
	while (EOF != (c = getopt_long(argc, argv, "b:c:de:f:hn:p:r:t:?",
		longopts, &longindex)))
		switch (c) {
		case 'b':
			exposure.mode(Binning(optarg));
			break;
		case 'c':
			Configuration::set_default(optarg);
			break;
		case 'd':
			debuglevel = LOG_DEBUG;
			break;
		case 'e':
			exposure.exposuretime(atof(optarg));
			break;
		case 'f':
			filtername = std::string(optarg);
			break;
		case 'h':
		case '?':
			usage(argv[0]);
			return EXIT_SUCCESS;
		case 'n':
			nImages = atoi(optarg);
			break;
		case 'p':
			exposure.purpose(Exposure::string2purpose(optarg));
			break;
		case 'r':
			reponame = std::string(optarg);
			break;
		case 't':
			temperature = atof(optarg);
			break;
		case 1:
			exposure.frame(ImageRectangle(optarg));
			break;
		default:
			throw std::runtime_error("unknown option");
		}

	// next argument must be instrument name or help
	if (optind >= argc) {
		std::cerr << "missing instrument name" << std::endl;
		return EXIT_FAILURE;
	}
	std::string	instrumentname(argv[optind++]);

	// get the configuration
	ConfigurationPtr	config = Configuration::get();

	// backend for instruments
	InstrumentBackend	instrumentbackend(config->database());
        InstrumentPtr   instrument = instrumentbackend.get(instrumentname);

	// get the image repository
	ImageRepoPtr	repo(NULL);
	if (reponame.size() > 0) {
		ImageRepoConfigurationPtr	imagerepos
			= ImageRepoConfiguration::get(config);
		repo = imagerepos->repo(reponame);
	}

	// prepare a repository from which we can extract the devices
	Repository	repository;
	Devices		devices(repository);

	// get the devices
	CameraPtr	camera = devices.getCamera(instrument->getCamera(0).deviceurl());
	CcdPtr		ccd = devices.getCcd(instrument->getCcd(0).deviceurl());

	// If temperature is set, and a cooler is present, initialize the
	// cooler and wait until temperature is reached
	CoolerPtr	cooler(NULL);
	if ((temperature == temperature)
		&& (instrument->hasCooler())) {
		double	absolute = 273.15 + temperature;
		if (absolute < 0) {
			std::string	msg
				= stringprintf("illegal temperature: %f",
					temperature);
			debug(LOG_ERR, DEBUG_LOG, 0, "%s", msg.c_str());
			throw std::runtime_error(msg);
		}
		cooler = devices.getCooler(instrument->getCooler(0).deviceurl());
		cooler->setTemperature(absolute);
		cooler->setOn(true);

		double	delta;
		do {
			double	actual = cooler->getActualTemperature();
			delta = fabs(absolute - actual);
			debug(LOG_DEBUG, DEBUG_LOG, 0,
				"set: %.1f, actual: %.1f, delta: %.1f",
				absolute, actual, delta);
		} while (delta > 1);
	}

	// if the instrument has a filter wheel, we get a pointer to it
	// and try 
	FilterWheelPtr	filterwheel(NULL);
	if (instrument->hasFilterWheel()) {
		filterwheel = devices.getFilterWheel(
			instrument->getFilterWheel(0).deviceurl());
		filterwheel->wait(20);
		if (filtername.size() > 0) {
			filterwheel->select(filtername);
			filterwheel->wait(20);
		}
	}

	// start the stream
	unsigned int	imagesRetrieved = 0;
	ccd->startStream(exposure);
	while (imagesRetrieved < nImages) {
		ImagePtr	image = ccd->getEntry(true).image;
		debug(LOG_DEBUG, DEBUG_LOG, 0, "got image[%u] %s",
			++imagesRetrieved,
			image->size().toString().c_str());
		if (!image->hasMetadata(std::string("INSTRUME"))) {
			image->setMetadata(FITSKeywords::meta(
				std::string("INSTRUME"), instrument->name()));
		}
		// do something about the image
		if (repo) {
			repo->save(image);
		}
	}
	// stop the stream
	ccd->stopStream();

	// find out how many images were dropped
	if (ccd->dropped() > 0) {
		std::cerr << "images dropped: " << ccd->dropped() << std::endl;
	}

	// turn off the cooler
	if (cooler) {
		cooler->setOn(false);
	}
	
	return EXIT_SUCCESS;
}
/**
 * \brief Get the device mapper
 */
DeviceMapperPtr	DeviceMapperConfigurationBackend::devicemapper() {
    return DeviceMapper::get(_config->database());
}