<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef _SD_SIMPLEREFERENCECOMPONENT_HXX_
#define _SD_SIMPLEREFERENCECOMPONENT_HXX_

#include "osl/interlck.h"
#include "sal/types.h"

#include <cstddef>
#include <new>

#include <sddllapi.h>

namespace sd {

/** A simple base implementation for reference-counted components.
    acts like sal::SimpleReferenceObject but calls the virtual disposing()
    methods before the ref count switches from 1 to zero.
 */
class SimpleReferenceComponent
{
public:
    SimpleReferenceComponent();

    /** @ATTENTION
        The results are undefined if, for any individual instance of
        SimpleReferenceComponent, the total number of calls to acquire() exceeds
        the total number of calls to release() by a plattform dependent amount
        (which, hopefully, is quite large).
     */
    SD_DLLPUBLIC void acquire();
    SD_DLLPUBLIC void release();

    void Dispose();

    bool isDisposed() const { return mbDisposed; }

    /** see general class documentation
     */
    static void * operator new(std::size_t nSize) SAL_THROW((std::bad_alloc));

    /** see general class documentation
     */
    static void * operator new(std::size_t nSize,
                               std::nothrow_t const & rNothrow)
       ;

    /** see general class documentation
     */
    static void operator delete(void * pPtr);

    /** see general class documentation
     */
    static void operator delete(void * pPtr, std::nothrow_t const & rNothrow)
       ;

protected:
    virtual void disposing();

    virtual ~SimpleReferenceComponent();

private:
    oslInterlockedCount m_nCount;

    /** not implemented
        @internal
     */
    SimpleReferenceComponent(SimpleReferenceComponent &);

    /** not implemented
        @internal
     */
    void operator =(SimpleReferenceComponent);

#ifndef WNT
    /** not implemented (see general class documentation)
        @internal
     */
    static void * operator new[](std::size_t);

    /** not implemented (see general class documentation)
        @internal
     */
    static void operator delete[](void * pPtr);
#endif
    bool mbDisposed;
};

}

#endif // _SALHELPER_SimpleReferenceComponent_HXX_

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Revert "windows compiler insist to have access to delete[], no matter what"<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef _SD_SIMPLEREFERENCECOMPONENT_HXX_
#define _SD_SIMPLEREFERENCECOMPONENT_HXX_

#include "osl/interlck.h"
#include "sal/types.h"

#include <cstddef>
#include <new>

#include <sddllapi.h>

namespace sd {

/** A simple base implementation for reference-counted components.
    acts like sal::SimpleReferenceObject but calls the virtual disposing()
    methods before the ref count switches from 1 to zero.
 */
class SimpleReferenceComponent
{
public:
    SimpleReferenceComponent();

    /** @ATTENTION
        The results are undefined if, for any individual instance of
        SimpleReferenceComponent, the total number of calls to acquire() exceeds
        the total number of calls to release() by a plattform dependent amount
        (which, hopefully, is quite large).
     */
    SD_DLLPUBLIC void acquire();
    SD_DLLPUBLIC void release();

    void Dispose();

    bool isDisposed() const { return mbDisposed; }

    /** see general class documentation
     */
    static void * operator new(std::size_t nSize) SAL_THROW((std::bad_alloc));

    /** see general class documentation
     */
    static void * operator new(std::size_t nSize,
                               std::nothrow_t const & rNothrow)
       ;

    /** see general class documentation
     */
    static void operator delete(void * pPtr);

    /** see general class documentation
     */
    static void operator delete(void * pPtr, std::nothrow_t const & rNothrow)
       ;

protected:
    virtual void disposing();

    virtual ~SimpleReferenceComponent();

private:
    oslInterlockedCount m_nCount;

    /** not implemented
        @internal
     */
    SimpleReferenceComponent(SimpleReferenceComponent &);

    /** not implemented
        @internal
     */
    void operator =(SimpleReferenceComponent);

    /** not implemented (see general class documentation)
        @internal
     */
    static void * operator new[](std::size_t);

    /** not implemented (see general class documentation)
        @internal
     */
    static void operator delete[](void * pPtr);

    bool mbDisposed;
};

}

#endif // _SALHELPER_SimpleReferenceComponent_HXX_

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>///////////////////////////////////////////////////////////////////////
//
// Test IO
//
// Purpose:
//  This extends testcbsdk with explicit testing of data io.
//  This is incomplete and only includes tests that were relevant to debugging specific problems.
//
//  Call with -c to enable continuous data (not tested), -e to enable events (works ok),
//  and -r <int> to specify a fixed runtime (?not working).
//  while running, press Esc key to stop.
//
//  Note:
//   Make sure only the SDK is used here, and not cbhwlib directly
//    this will ensure SDK is capable of whatever test suite can do
//   Do not throw exceptions, catch possible exceptions and handle them the earliest possible in this library
//

#include <map>
#include <string>
#include <vector>
#include <stdio.h>
#include <conio.h>
#include <inttypes.h>
#include "debugmacs.h"

#include "cbsdk.h"

#define INST 0

typedef struct _cbsdk_config {
    uint32_t nInstance;
    uint32_t bActive;
    uint16_t begchan;
    uint32_t begmask;
    uint32_t begval;
    uint16_t endchan;
    uint32_t endmask;
    uint32_t endval;
    bool bDouble;
    uint32_t uWaveforms;
    uint32_t uConts;
    uint32_t uEvents;
    uint32_t uComments;
    uint32_t uTrackings;
    bool bAbsolute;
} cbsdk_config;

void handleResult(cbSdkResult res)
{
    switch (res)
    {
    case CBSDKRESULT_SUCCESS:
        break;
    case CBSDKRESULT_NOTIMPLEMENTED:
        printf("Not implemented\n");
        break;
    case CBSDKRESULT_INVALIDPARAM:
        printf("Invalid parameter\n");
        break;
    case CBSDKRESULT_WARNOPEN:
        printf("Real-time interface already initialized\n");
    case CBSDKRESULT_WARNCLOSED:
        printf("Real-time interface already closed\n");
        break;
    case CBSDKRESULT_ERROPENCENTRAL:
        printf("Unable to open library for Central interface\n");
        break;
    case CBSDKRESULT_ERROPENUDP:
        printf("Unable to open library for UDP interface\n");
        break;
    case CBSDKRESULT_ERROPENUDPPORT:
        printf("Unable to open UDP interface\n");
        break;
    case CBSDKRESULT_OPTERRUDP:
        printf("Unable to set UDP interface option\n");
        break;
    case CBSDKRESULT_MEMERRUDP:
        printf("Unable to assign UDP interface memory\n"
            " Consider using sysctl -w net.core.rmem_max=8388608\n"
            " or sysctl -w kern.ipc.maxsockbuf=8388608\n");
        break;
    case CBSDKRESULT_INVALIDINST:
        printf("Invalid UDP interface\n");
        break;
    case CBSDKRESULT_ERRMEMORYTRIAL:
        printf("Unable to allocate RAM for trial cache data\n");
        break;
    case CBSDKRESULT_ERROPENUDPTHREAD:
        printf("Unable to Create UDP thread\n");
        break;
    case CBSDKRESULT_ERROPENCENTRALTHREAD:
        printf("Unable to start Cerebus real-time data thread\n");
        break;
    case CBSDKRESULT_ERRINIT:
        printf("Library initialization error\n");
        break;
    case CBSDKRESULT_ERRMEMORY:
        printf("Library memory allocation error\n");
        break;
    case CBSDKRESULT_TIMEOUT:
        printf("Connection timeout error\n");
        break;
    case CBSDKRESULT_ERROFFLINE:
        printf("Instrument is offline\n");
        break;
    default:
        printf("Unexpected error\n");
        break;
    }
}

cbSdkVersion testGetVersion(void)
{
    // Library version can be read even before library open (return value is a warning)
    //  actual NSP version however needs library to be open
    cbSdkVersion ver;
    cbSdkResult res = cbSdkGetVersion(INST, &ver);
    if (res != CBSDKRESULT_SUCCESS)
    {
        printf("Unable to determine instrument version\n");
    }
    else {
        printf("Initializing Cerebus real-time interface %d.%02d.%02d.%02d (protocol cb%d.%02d)...\n", ver.major, ver.minor, ver.release, ver.beta, ver.majorp, ver.minorp);
    }
    handleResult(res);
    return ver;
}

// Author & Date:   Ehsan Azar    24 Oct 2012
// Purpose: Test openning the library
cbSdkResult testOpen(void)
{
    // Try to get the version. Should be a warning because we are not yet open.
    cbSdkVersion ver = testGetVersion();

    // Open the device using default connection type.
    cbSdkConnectionType conType = CBSDKCONNECTION_DEFAULT;
    cbSdkResult res = cbSdkOpen(INST, conType);
    if (res != CBSDKRESULT_SUCCESS)
        printf("Unable to open instrument connection.\n");
    handleResult(res);

    cbSdkInstrumentType instType;
    if (res >= 0)
    {
        // Return the actual opened connection
        res = cbSdkGetType(INST, &conType, &instType);
        if (res != CBSDKRESULT_SUCCESS)
            printf("Unable to determine connection type\n");
        handleResult(res);
        // if (instType == CBSDKINSTRUMENT_NPLAY || instType == CBSDKINSTRUMENT_REMOTENPLAY)
        //  	printf("Unable to open UDP interface to nPlay\n");

        if (conType < 0 || conType > CBSDKCONNECTION_CLOSED)
            conType = CBSDKCONNECTION_COUNT;
        if (instType < 0 || instType > CBSDKINSTRUMENT_COUNT)
            instType = CBSDKINSTRUMENT_COUNT;

        char strConnection[CBSDKCONNECTION_COUNT + 1][8] = {"Default", "Central", "Udp", "Closed", "Unknown"};
        char strInstrument[CBSDKINSTRUMENT_COUNT + 1][13] = {"NSP", "nPlay", "Local NSP", "Remote nPlay", "Unknown"};

        // Now that we are open, get the version again.
        ver = testGetVersion();

        // Summary results.
        printf("%s real-time interface to %s (%d.%02d.%02d.%02d) successfully initialized\n", strConnection[conType], strInstrument[instType], ver.nspmajor, ver.nspminor, ver.nsprelease, ver.nspbeta);
    }

    return res;
}

void testGetConfig(void)
{
    uint32_t proc = 1;
    uint32_t nChansInGroup;
    uint16_t pGroupList[cbNUM_ANALOG_CHANS];
    for (uint32_t group_ix = 1; group_ix < 7; group_ix++)
    {
        cbSdkResult res = cbSdkGetSampleGroupList(INST, proc, group_ix, &nChansInGroup, pGroupList);
        if (res == CBSDKRESULT_SUCCESS)
        {
            printf("In sampling group %d, found %d channels.\n", group_ix, nChansInGroup);
        }
        handleResult(res);
    }
}

void testGetTrialConfig(cbsdk_config& cfg)
{
    cbSdkResult res = cbSdkGetTrialConfig(INST, &cfg.bActive, &cfg.begchan, &cfg.begmask, &cfg.begval,
        &cfg.endchan, &cfg.endmask, &cfg.endval, &cfg.bDouble,
        &cfg.uWaveforms, &cfg.uConts, &cfg.uEvents, &cfg.uComments, &cfg.uTrackings, &cfg.bAbsolute);
}

// Author & Date:   Ehsan Azar    25 Oct 2012
// Purpose: Test closing the library
cbSdkResult testClose(void)
{
    cbSdkResult res = cbSdkClose(INST);
    if (res == CBSDKRESULT_SUCCESS)
    {
        printf("Interface closed successfully\n");
    }
    else
    {
        printf("Unable to close interface.\n");
        handleResult(res);
    }
    return res;
}

/////////////////////////////////////////////////////////////////////////////
// The test suit main entry
int main(int argc, char *argv[])
{
    // Parse command line arguments.
    bool bCont = false;
    bool bEv = false;
    bool bComm = false;
    uint32_t runtime = 30000;
    size_t optind;
    for (optind = 1; optind < argc && argv[optind][0] == '-'; optind++)
    {
        switch (argv[optind][1]) {
        case 'c': bCont = true; break;
        case 'e': bEv = true; break;
        case 'r': runtime = 30000 * (argv[optind][2] - '0');
        }
    }

    cbSdkResult res = testOpen();
    if (res < 0)
        printf("testOpen failed (%d)!\n", res);
    else
        printf("testOpen succeeded\n");

    testGetConfig();

    cbsdk_config cfg;
    testGetTrialConfig(cfg);
    cfg.bActive = 1;

    cfg.uConts = bCont ? cbSdk_CONTINUOUS_DATA_SAMPLES : 0;
    cfg.uEvents = bEv ? cbSdk_EVENT_DATA_SAMPLES : 0;
    res = cbSdkSetTrialConfig(INST, cfg.bActive, cfg.begchan, cfg.begmask, cfg.begval, cfg.endchan, cfg.endmask, cfg.endval,
        cfg.bDouble, cfg.uWaveforms, cfg.uConts, cfg.uEvents, cfg.uComments, cfg.uTrackings, cfg.bAbsolute);

    uint32_t start_time;
    uint32_t elapsed_time = 0;
    res = cbSdkGetTime(INST, &start_time);
    char kb_ch = '1';
    while ((kb_ch != 27) && ((runtime == 0) || (elapsed_time < runtime)))
    {
        res = cbSdkGetTime(INST, &elapsed_time);
        elapsed_time -= start_time;

        // cbSdkInitTrialData to determine how many samples are available
        cbSdkTrialEvent* ptrialevent = new cbSdkTrialEvent;
        if (!bEv) {
            delete ptrialevent;
            ptrialevent = nullptr;
        }
        cbSdkTrialCont* ptrialcont = new cbSdkTrialCont;
        if (!bCont) {
            delete ptrialcont;
            ptrialcont = nullptr;
        }
        cbSdkTrialComment* ptrialcomment = new cbSdkTrialComment;
        if (!bComm) {
            delete ptrialcomment;
            ptrialcomment = nullptr;
        }
        res = cbSdkInitTrialData(INST, 0, ptrialevent, ptrialcont, ptrialcomment, 0);

        // allocate memory
        if (ptrialevent && (ptrialevent->count > 0))
        {
            for (size_t ev_ix = 0; ev_ix < ptrialevent->count; ev_ix++)
            {
                uint16_t chan_id = ptrialevent->chan[ev_ix];  // 1-based

                // Every event channel, regardless of type (spike, digital, serial), gets an array of timestamps.
                for (size_t un_ix = 0; un_ix < cbMAXUNITS + 1; un_ix++)
                {
                    uint32_t n_samples = ptrialevent->num_samples[ev_ix][un_ix];
                    if (n_samples)
                    {
                        // alloc num_samples uint32_t
                        ptrialevent->timestamps[ev_ix][un_ix] = malloc(n_samples * sizeof(uint32_t));
                    }
                    else {
                        ptrialevent->timestamps[ev_ix][un_ix] = NULL;
                    }
                }

                uint8_t chanType;
                cbSdkGetChannelType(INST, chan_id, &chanType);
                if ((chanType == cbCHANTYPE_DIGIN) || (chanType == cbCHANTYPE_SERIAL))
                {
                    // alloc waveform data
                    uint32_t n_samples = ptrialevent->num_samples[ev_ix][0];
                    ptrialevent->waveforms[ev_ix] = malloc(n_samples * sizeof(uint16_t));
                    // TODO: If double then allocate sizeof(double)
                }
            }
        }

        if (ptrialcont && (ptrialcont->count > 0))
        {
            // TODO: Allocate continuous data
        }

        // cbSdkGetTrialData to fetch the data
        res = cbSdkGetTrialData(INST, cfg.bActive, ptrialevent, ptrialcont, ptrialcomment, 0);

        // Print something to do with the data.
        if (ptrialevent && (ptrialevent->count > 0))
        {
            for (size_t ev_ix = 0; ev_ix < ptrialevent->count; ev_ix++)
            {
                for (size_t un_ix = 0; un_ix < cbMAXUNITS + 1; un_ix++)
                {
                    if (ptrialevent->num_samples[ev_ix][un_ix])
                    {
                        uint32_t* ts = (uint32_t *)ptrialevent->timestamps[ev_ix][un_ix];
                        // printf(" %" PRIu32, *ts);
                    }
                }
                // printf("\n");

                uint16_t chan_id = ptrialevent->chan[ev_ix];
                uint8_t chanType;
                cbSdkGetChannelType(INST, chan_id, &chanType);
                if ((chanType == cbCHANTYPE_DIGIN) || (chanType == cbCHANTYPE_SERIAL))
                {
                    uint32_t n_samples = ptrialevent->num_samples[ev_ix][0];
                    if (n_samples > 0)
                    {
                        uint32_t* ts = (uint32_t *)ptrialevent->timestamps[ev_ix][0];
                        printf("%" PRIu32 ":", *ts);
                    }
                    uint16_t* wf = (uint16_t*)ptrialevent->waveforms[ev_ix];
                    for (uint32_t sample_ix = 0; sample_ix < n_samples; sample_ix++)
                    {
                        printf(" %" PRIu16, wf[sample_ix]);
                    }
                    if (n_samples > 0) printf("\n");
                }
            }
        }

        if (ptrialcont && (ptrialcont->count > 0))
        {
            // TODO: Print continous data
        }

        // Free allocated memory.
        if (ptrialevent)
        {
            if (ptrialevent->count > 0)
            {
                for (size_t ev_ix = 0; ev_ix < ptrialevent->count; ev_ix++)
                {
                    for (size_t un_ix = 0; un_ix < cbMAXUNITS + 1; un_ix++)
                    {
                        if (ptrialevent->num_samples[ev_ix][un_ix])
                        {
                            free(ptrialevent->timestamps[ev_ix][un_ix]);
                            ptrialevent->timestamps[ev_ix][un_ix] = NULL;
                        }
                    }

                    uint16_t chan_id = ptrialevent->chan[ev_ix];
                    uint8_t chanType;
                    cbSdkGetChannelType(INST, chan_id + 1, &chanType);
                    if ((chanType == cbCHANTYPE_DIGIN) || (chanType == cbCHANTYPE_SERIAL))
                    {
                        free(ptrialevent->waveforms[ev_ix]);
                        ptrialevent->waveforms[ev_ix] = NULL;
                    }
                }
            }
            delete ptrialevent;
            ptrialevent = nullptr;
        }

        if (ptrialcont)
        {
            if (ptrialcont->count > 0)
            {
                // TODO: Free continous data
            }
            delete ptrialcont;
            ptrialcont = nullptr;
        }

        if (_kbhit())
        {
            kb_ch = _getch();
        }
    }

    res = testClose();
    if (res < 0)
        printf("testClose failed (%d)!\n", res);
    else
        printf("testClose succeeded\n");

    return 0;
}
<commit_msg>guard out win-specific conio to allow project to build on linux.<commit_after>///////////////////////////////////////////////////////////////////////
//
// Test IO
//
// Purpose:
//  This extends testcbsdk with explicit testing of data io.
//  This is incomplete and only includes tests that were relevant to debugging specific problems.
//
//  Call with -c to enable continuous data (not tested), -e to enable events (works ok),
//  and -r <int> to specify a fixed runtime (?not working).
//  while running, press Esc key to stop.
//
//  Note:
//   Make sure only the SDK is used here, and not cbhwlib directly
//    this will ensure SDK is capable of whatever test suite can do
//   Do not throw exceptions, catch possible exceptions and handle them the earliest possible in this library
//

#include <map>
#include <string>
#include <vector>
#include <stdio.h>
#ifdef WIN32
#include <conio.h>
#endif //win32
#include <inttypes.h>
#include "debugmacs.h"

#include "cbsdk.h"

#define INST 0

typedef struct _cbsdk_config {
    uint32_t nInstance;
    uint32_t bActive;
    uint16_t begchan;
    uint32_t begmask;
    uint32_t begval;
    uint16_t endchan;
    uint32_t endmask;
    uint32_t endval;
    bool bDouble;
    uint32_t uWaveforms;
    uint32_t uConts;
    uint32_t uEvents;
    uint32_t uComments;
    uint32_t uTrackings;
    bool bAbsolute;
} cbsdk_config;

void handleResult(cbSdkResult res)
{
    switch (res)
    {
    case CBSDKRESULT_SUCCESS:
        break;
    case CBSDKRESULT_NOTIMPLEMENTED:
        printf("Not implemented\n");
        break;
    case CBSDKRESULT_INVALIDPARAM:
        printf("Invalid parameter\n");
        break;
    case CBSDKRESULT_WARNOPEN:
        printf("Real-time interface already initialized\n");
    case CBSDKRESULT_WARNCLOSED:
        printf("Real-time interface already closed\n");
        break;
    case CBSDKRESULT_ERROPENCENTRAL:
        printf("Unable to open library for Central interface\n");
        break;
    case CBSDKRESULT_ERROPENUDP:
        printf("Unable to open library for UDP interface\n");
        break;
    case CBSDKRESULT_ERROPENUDPPORT:
        printf("Unable to open UDP interface\n");
        break;
    case CBSDKRESULT_OPTERRUDP:
        printf("Unable to set UDP interface option\n");
        break;
    case CBSDKRESULT_MEMERRUDP:
        printf("Unable to assign UDP interface memory\n"
            " Consider using sysctl -w net.core.rmem_max=8388608\n"
            " or sysctl -w kern.ipc.maxsockbuf=8388608\n");
        break;
    case CBSDKRESULT_INVALIDINST:
        printf("Invalid UDP interface\n");
        break;
    case CBSDKRESULT_ERRMEMORYTRIAL:
        printf("Unable to allocate RAM for trial cache data\n");
        break;
    case CBSDKRESULT_ERROPENUDPTHREAD:
        printf("Unable to Create UDP thread\n");
        break;
    case CBSDKRESULT_ERROPENCENTRALTHREAD:
        printf("Unable to start Cerebus real-time data thread\n");
        break;
    case CBSDKRESULT_ERRINIT:
        printf("Library initialization error\n");
        break;
    case CBSDKRESULT_ERRMEMORY:
        printf("Library memory allocation error\n");
        break;
    case CBSDKRESULT_TIMEOUT:
        printf("Connection timeout error\n");
        break;
    case CBSDKRESULT_ERROFFLINE:
        printf("Instrument is offline\n");
        break;
    default:
        printf("Unexpected error\n");
        break;
    }
}

cbSdkVersion testGetVersion(void)
{
    // Library version can be read even before library open (return value is a warning)
    //  actual NSP version however needs library to be open
    cbSdkVersion ver;
    cbSdkResult res = cbSdkGetVersion(INST, &ver);
    if (res != CBSDKRESULT_SUCCESS)
    {
        printf("Unable to determine instrument version\n");
    }
    else {
        printf("Initializing Cerebus real-time interface %d.%02d.%02d.%02d (protocol cb%d.%02d)...\n", ver.major, ver.minor, ver.release, ver.beta, ver.majorp, ver.minorp);
    }
    handleResult(res);
    return ver;
}

// Author & Date:   Ehsan Azar    24 Oct 2012
// Purpose: Test openning the library
cbSdkResult testOpen(void)
{
    // Try to get the version. Should be a warning because we are not yet open.
    cbSdkVersion ver = testGetVersion();

    // Open the device using default connection type.
    cbSdkConnectionType conType = CBSDKCONNECTION_DEFAULT;
    cbSdkResult res = cbSdkOpen(INST, conType);
    if (res != CBSDKRESULT_SUCCESS)
        printf("Unable to open instrument connection.\n");
    handleResult(res);

    cbSdkInstrumentType instType;
    if (res >= 0)
    {
        // Return the actual opened connection
        res = cbSdkGetType(INST, &conType, &instType);
        if (res != CBSDKRESULT_SUCCESS)
            printf("Unable to determine connection type\n");
        handleResult(res);
        // if (instType == CBSDKINSTRUMENT_NPLAY || instType == CBSDKINSTRUMENT_REMOTENPLAY)
        //  	printf("Unable to open UDP interface to nPlay\n");

        if (conType < 0 || conType > CBSDKCONNECTION_CLOSED)
            conType = CBSDKCONNECTION_COUNT;
        if (instType < 0 || instType > CBSDKINSTRUMENT_COUNT)
            instType = CBSDKINSTRUMENT_COUNT;

        char strConnection[CBSDKCONNECTION_COUNT + 1][8] = {"Default", "Central", "Udp", "Closed", "Unknown"};
        char strInstrument[CBSDKINSTRUMENT_COUNT + 1][13] = {"NSP", "nPlay", "Local NSP", "Remote nPlay", "Unknown"};

        // Now that we are open, get the version again.
        ver = testGetVersion();

        // Summary results.
        printf("%s real-time interface to %s (%d.%02d.%02d.%02d) successfully initialized\n", strConnection[conType], strInstrument[instType], ver.nspmajor, ver.nspminor, ver.nsprelease, ver.nspbeta);
    }

    return res;
}

void testGetConfig(void)
{
    uint32_t proc = 1;
    uint32_t nChansInGroup;
    uint16_t pGroupList[cbNUM_ANALOG_CHANS];
    for (uint32_t group_ix = 1; group_ix < 7; group_ix++)
    {
        cbSdkResult res = cbSdkGetSampleGroupList(INST, proc, group_ix, &nChansInGroup, pGroupList);
        if (res == CBSDKRESULT_SUCCESS)
        {
            printf("In sampling group %d, found %d channels.\n", group_ix, nChansInGroup);
        }
        handleResult(res);
    }
}

void testGetTrialConfig(cbsdk_config& cfg)
{
    cbSdkResult res = cbSdkGetTrialConfig(INST, &cfg.bActive, &cfg.begchan, &cfg.begmask, &cfg.begval,
        &cfg.endchan, &cfg.endmask, &cfg.endval, &cfg.bDouble,
        &cfg.uWaveforms, &cfg.uConts, &cfg.uEvents, &cfg.uComments, &cfg.uTrackings, &cfg.bAbsolute);
}

// Author & Date:   Ehsan Azar    25 Oct 2012
// Purpose: Test closing the library
cbSdkResult testClose(void)
{
    cbSdkResult res = cbSdkClose(INST);
    if (res == CBSDKRESULT_SUCCESS)
    {
        printf("Interface closed successfully\n");
    }
    else
    {
        printf("Unable to close interface.\n");
        handleResult(res);
    }
    return res;
}

/////////////////////////////////////////////////////////////////////////////
// The test suit main entry
int main(int argc, char *argv[])
{
    // Parse command line arguments.
    bool bCont = false;
    bool bEv = false;
    bool bComm = false;
    uint32_t runtime = 30000;
    size_t optind;
    for (optind = 1; optind < argc && argv[optind][0] == '-'; optind++)
    {
        switch (argv[optind][1]) {
        case 'c': bCont = true; break;
        case 'e': bEv = true; break;
        case 'r': runtime = 30000 * (argv[optind][2] - '0');
        }
    }

    cbSdkResult res = testOpen();
    if (res < 0)
        printf("testOpen failed (%d)!\n", res);
    else
        printf("testOpen succeeded\n");

    testGetConfig();

    cbsdk_config cfg;
    testGetTrialConfig(cfg);
    cfg.bActive = 1;

    cfg.uConts = bCont ? cbSdk_CONTINUOUS_DATA_SAMPLES : 0;
    cfg.uEvents = bEv ? cbSdk_EVENT_DATA_SAMPLES : 0;
    res = cbSdkSetTrialConfig(INST, cfg.bActive, cfg.begchan, cfg.begmask, cfg.begval, cfg.endchan, cfg.endmask, cfg.endval,
        cfg.bDouble, cfg.uWaveforms, cfg.uConts, cfg.uEvents, cfg.uComments, cfg.uTrackings, cfg.bAbsolute);

    uint32_t start_time;
    uint32_t elapsed_time = 0;
    res = cbSdkGetTime(INST, &start_time);
    char kb_ch = '1';
    while ((kb_ch != 27) && ((runtime == 0) || (elapsed_time < runtime)))
    {
        res = cbSdkGetTime(INST, &elapsed_time);
        elapsed_time -= start_time;

        // cbSdkInitTrialData to determine how many samples are available
        cbSdkTrialEvent* ptrialevent = new cbSdkTrialEvent;
        if (!bEv) {
            delete ptrialevent;
            ptrialevent = nullptr;
        }
        cbSdkTrialCont* ptrialcont = new cbSdkTrialCont;
        if (!bCont) {
            delete ptrialcont;
            ptrialcont = nullptr;
        }
        cbSdkTrialComment* ptrialcomment = new cbSdkTrialComment;
        if (!bComm) {
            delete ptrialcomment;
            ptrialcomment = nullptr;
        }
        res = cbSdkInitTrialData(INST, 0, ptrialevent, ptrialcont, ptrialcomment, 0);

        // allocate memory
        if (ptrialevent && (ptrialevent->count > 0))
        {
            for (size_t ev_ix = 0; ev_ix < ptrialevent->count; ev_ix++)
            {
                uint16_t chan_id = ptrialevent->chan[ev_ix];  // 1-based

                // Every event channel, regardless of type (spike, digital, serial), gets an array of timestamps.
                for (size_t un_ix = 0; un_ix < cbMAXUNITS + 1; un_ix++)
                {
                    uint32_t n_samples = ptrialevent->num_samples[ev_ix][un_ix];
                    if (n_samples)
                    {
                        // alloc num_samples uint32_t
                        ptrialevent->timestamps[ev_ix][un_ix] = malloc(n_samples * sizeof(uint32_t));
                    }
                    else {
                        ptrialevent->timestamps[ev_ix][un_ix] = NULL;
                    }
                }

                uint8_t chanType;
                cbSdkGetChannelType(INST, chan_id, &chanType);
                if ((chanType == cbCHANTYPE_DIGIN) || (chanType == cbCHANTYPE_SERIAL))
                {
                    // alloc waveform data
                    uint32_t n_samples = ptrialevent->num_samples[ev_ix][0];
                    ptrialevent->waveforms[ev_ix] = malloc(n_samples * sizeof(uint16_t));
                    // TODO: If double then allocate sizeof(double)
                }
            }
        }

        if (ptrialcont && (ptrialcont->count > 0))
        {
            // TODO: Allocate continuous data
        }

        // cbSdkGetTrialData to fetch the data
        res = cbSdkGetTrialData(INST, cfg.bActive, ptrialevent, ptrialcont, ptrialcomment, 0);

        // Print something to do with the data.
        if (ptrialevent && (ptrialevent->count > 0))
        {
            for (size_t ev_ix = 0; ev_ix < ptrialevent->count; ev_ix++)
            {
                for (size_t un_ix = 0; un_ix < cbMAXUNITS + 1; un_ix++)
                {
                    if (ptrialevent->num_samples[ev_ix][un_ix])
                    {
                        uint32_t* ts = (uint32_t *)ptrialevent->timestamps[ev_ix][un_ix];
                        // printf(" %" PRIu32, *ts);
                    }
                }
                // printf("\n");

                uint16_t chan_id = ptrialevent->chan[ev_ix];
                uint8_t chanType;
                cbSdkGetChannelType(INST, chan_id, &chanType);
                if ((chanType == cbCHANTYPE_DIGIN) || (chanType == cbCHANTYPE_SERIAL))
                {
                    uint32_t n_samples = ptrialevent->num_samples[ev_ix][0];
                    if (n_samples > 0)
                    {
                        uint32_t* ts = (uint32_t *)ptrialevent->timestamps[ev_ix][0];
                        printf("%" PRIu32 ":", *ts);
                    }
                    uint16_t* wf = (uint16_t*)ptrialevent->waveforms[ev_ix];
                    for (uint32_t sample_ix = 0; sample_ix < n_samples; sample_ix++)
                    {
                        printf(" %" PRIu16, wf[sample_ix]);
                    }
                    if (n_samples > 0) printf("\n");
                }
            }
        }

        if (ptrialcont && (ptrialcont->count > 0))
        {
            // TODO: Print continous data
        }

        // Free allocated memory.
        if (ptrialevent)
        {
            if (ptrialevent->count > 0)
            {
                for (size_t ev_ix = 0; ev_ix < ptrialevent->count; ev_ix++)
                {
                    for (size_t un_ix = 0; un_ix < cbMAXUNITS + 1; un_ix++)
                    {
                        if (ptrialevent->num_samples[ev_ix][un_ix])
                        {
                            free(ptrialevent->timestamps[ev_ix][un_ix]);
                            ptrialevent->timestamps[ev_ix][un_ix] = NULL;
                        }
                    }

                    uint16_t chan_id = ptrialevent->chan[ev_ix];
                    uint8_t chanType;
                    cbSdkGetChannelType(INST, chan_id + 1, &chanType);
                    if ((chanType == cbCHANTYPE_DIGIN) || (chanType == cbCHANTYPE_SERIAL))
                    {
                        free(ptrialevent->waveforms[ev_ix]);
                        ptrialevent->waveforms[ev_ix] = NULL;
                    }
                }
            }
            delete ptrialevent;
            ptrialevent = nullptr;
        }

        if (ptrialcont)
        {
            if (ptrialcont->count > 0)
            {
                // TODO: Free continous data
            }
            delete ptrialcont;
            ptrialcont = nullptr;
        }

#ifdef WIN32
        if (_kbhit())
        {
            kb_ch = _getch();
        }
#endif
    }

    res = testClose();
    if (res < 0)
        printf("testClose failed (%d)!\n", res);
    else
        printf("testClose succeeded\n");

    return 0;
}
<|endoftext|>


<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ppapi/cpp/mouse_lock.h"

#include "ppapi/c/ppb_mouse_lock.h"
#include "ppapi/c/ppp_mouse_lock.h"
#include "ppapi/cpp/completion_callback.h"
#include "ppapi/cpp/instance.h"
#include "ppapi/cpp/instance_handle.h"
#include "ppapi/cpp/module.h"
#include "ppapi/cpp/module_impl.h"

namespace pp {

namespace {

static const char kPPPMouseLockInterface[] = PPP_MOUSELOCK_INTERFACE;

void MouseLockLost(PP_Instance instance) {
  void* object =
      Instance::GetPerInstanceObject(instance, kPPPMouseLockInterface);
  if (!object)
    return;
  static_cast<MouseLock*>(object)->MouseLockLost();
}

const PPP_MouseLock ppp_mouse_lock = {
  &MouseLockLost
};

template <> const char* interface_name<PPB_MouseLock>() {
  return PPB_MOUSELOCK_INTERFACE;
}

}  // namespace

MouseLock::MouseLock(Instance* instance)
    : associated_instance_(instance) {
  Module::Get()->AddPluginInterface(kPPPMouseLockInterface, &ppp_mouse_lock);
  instance->AddPerInstanceObject(kPPPMouseLockInterface, this);
}

MouseLock::~MouseLock() {
  Instance::RemovePerInstanceObject(associated_instance_,
                                    kPPPMouseLockInterface, this);
}

int32_t MouseLock::LockMouse(const CompletionCallback& cc) {
  if (!has_interface<PPB_MouseLock>())
    return cc.MayForce(PP_ERROR_NOINTERFACE);
  return get_interface<PPB_MouseLock>()->LockMouse(
      associated_instance_.pp_instance(), cc.pp_completion_callback());
}

void MouseLock::UnlockMouse() {
  if (has_interface<PPB_MouseLock>()) {
    get_interface<PPB_MouseLock>()->UnlockMouse(
        associated_instance_.pp_instance());
  }
}

}  // namespace pp
<commit_msg>Check explicitly for PPB_MouseLock v1.0 in pp::MouseLock.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ppapi/cpp/mouse_lock.h"

#include "ppapi/c/ppb_mouse_lock.h"
#include "ppapi/c/ppp_mouse_lock.h"
#include "ppapi/cpp/completion_callback.h"
#include "ppapi/cpp/instance.h"
#include "ppapi/cpp/instance_handle.h"
#include "ppapi/cpp/module.h"
#include "ppapi/cpp/module_impl.h"

namespace pp {

namespace {

static const char kPPPMouseLockInterface[] = PPP_MOUSELOCK_INTERFACE;

void MouseLockLost(PP_Instance instance) {
  void* object =
      Instance::GetPerInstanceObject(instance, kPPPMouseLockInterface);
  if (!object)
    return;
  static_cast<MouseLock*>(object)->MouseLockLost();
}

const PPP_MouseLock ppp_mouse_lock = {
  &MouseLockLost
};

template <> const char* interface_name<PPB_MouseLock_1_0>() {
  return PPB_MOUSELOCK_INTERFACE_1_0;
}

}  // namespace

MouseLock::MouseLock(Instance* instance)
    : associated_instance_(instance) {
  Module::Get()->AddPluginInterface(kPPPMouseLockInterface, &ppp_mouse_lock);
  instance->AddPerInstanceObject(kPPPMouseLockInterface, this);
}

MouseLock::~MouseLock() {
  Instance::RemovePerInstanceObject(associated_instance_,
                                    kPPPMouseLockInterface, this);
}

int32_t MouseLock::LockMouse(const CompletionCallback& cc) {
  if (!has_interface<PPB_MouseLock_1_0>())
    return cc.MayForce(PP_ERROR_NOINTERFACE);
  return get_interface<PPB_MouseLock_1_0>()->LockMouse(
      associated_instance_.pp_instance(), cc.pp_completion_callback());
}

void MouseLock::UnlockMouse() {
  if (has_interface<PPB_MouseLock_1_0>()) {
    get_interface<PPB_MouseLock_1_0>()->UnlockMouse(
        associated_instance_.pp_instance());
  }
}

}  // namespace pp
<|endoftext|>


<commit_before>/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */

#include <ns3/core-module.h>
#include <ns3/node.h>
#include <ns3/point-to-point-net-device.h>
#include <ns3/point-to-point-channel.h>
#include <ns3/drop-tail-queue.h>
#include <ns3/gnuplot.h>
#include "BitAlternante.h"

#define TAM_PAQUETE 994

using namespace ns3;

NS_LOG_COMPONENT_DEFINE ("Practica03");

int
main (int argc, char *argv[])
{
  Time::SetResolution (Time::MS);

  //Variables para parametros de linea de comandos
  DataRate velocidadTxDesde(1);
  DataRate velocidadTxHasta(100);
  Time     retardoPropDesde(1);
  Time     retardoPropHasta(100);
  Time     tRetransmisionDesde(1);
  Time     tRetransmisionHasta(100);

  //Obtencion de parametros por linea de comandos
  CommandLine cmd;
  cmd.AddValue("velocidadTxDesde", "valor de la velocidad de transmision inicial", velocidadTxDesde);
  cmd.AddValue("velocidadTxHasta", "valor de la velocidad de transmision final", velocidadTxHasta);
  cmd.AddValue("retardoPropDesde", "retardo de propagacion inicial", retardoPropDesde);
  cmd.AddValue("retardoPropHasta", "retardo de propagacion final", retardoPropHasta);
  cmd.AddValue("tRetransmisionDesde", "temporizador de retransmisiones inicial", tRetransmisionDesde);
  cmd.AddValue("tRetransmisionHasta", "temporizador de retransmisiones final", tRetransmisionHasta);
  cmd.Parse(argc, argv);

  // Componentes del escenario:
  // Dos nodos
  Ptr<Node> nodoTx = CreateObject<Node> ();
  Ptr<Node> nodoRx = CreateObject<Node> ();
  // Dos dispositivos de red
  Ptr<PointToPointNetDevice> dispTx = CreateObject<PointToPointNetDevice> ();
  Ptr<PointToPointNetDevice> dispRx = CreateObject<PointToPointNetDevice> ();
  // Un canal punto a punto
  Ptr<PointToPointChannel> canal = CreateObject<PointToPointChannel> ();;
  // Una aplicación transmisora
  BitAlternanteTx transmisor(dispRx, Time("10ms"), 994);
  // Y una receptora
  BitAlternanteRx receptor(dispTx);

  // Montamos el escenario:
  // Añadimos una cola a cada dispositivo
  dispTx->SetQueue (CreateObject<DropTailQueue> ());
  dispRx->SetQueue (CreateObject<DropTailQueue> ());
  // Añadimos cada dispositivo a su nodo
  nodoTx->AddDevice (dispTx);
  nodoRx->AddDevice (dispRx);
  // Añadimos cada aplicación a su nodo
  nodoTx->AddApplication(&transmisor);
  nodoRx->AddApplication(&receptor);
  // Asociamos los dos dispositivos al canal
  dispTx->Attach (canal);
  dispRx->Attach (canal);

  /*// Modificamos los parámetos configurables
  canal->SetAttribute ("Delay", StringValue ("2ms"));
  dispTx->SetAttribute ("DataRate", StringValue ("5Mbps"));
  */

  /*// Activamos el transmisor
  transmisor.SetStartTime (Seconds (1.0));
  transmisor.SetStopTime (Seconds (10.0));
  */

  //NS_LOG_UNCOND ("Voy a simular");

  /*
   * PRIMERA GRAFICA
   */
  NS_LOG_INFO ("############################");
  NS_LOG_INFO ("# PRIMERA GRAFICA ##########");
  NS_LOG_INFO ("############################");
  Gnuplot plot1;
  //TODO: plot1.SetTitle("");

  //Calculo de la velocidad de transmision media
  DataRate velocidadTxMedia((velocidadTxDesde.GetBitRate() + velocidadTxHasta.GetBitRate()) / 2);
  NS_LOG_INFO ("velocidadTxMedia: " << velocidadTxMedia.GetBitRate());
  NS_LOG_INFO ("############################");
  //Configuracion de la constante (velocidad transmision)
  dispTx->SetAttribute ("DataRate", DataRateValue(velocidadTxMedia));
  //Bucle para la creación de cada curva
  for (int i = 0; i < 5 ; i++) {
    //Calculo del parametro (retardo de propagacion)
    Time retardoPropActual(retardoPropDesde.GetDouble() + i * (retardoPropHasta.GetDouble() - retardoPropDesde.GetDouble()) / 4);
    NS_LOG_INFO ("retardoPropActual: " << retardoPropActual.GetDouble());
    NS_LOG_INFO ("***************************");
    //Configuración del parametro (retardo de propagacion)
    canal->SetAttribute ("Delay", TimeValue(retardoPropActual));
    //Creacion de una nueva curva
    Gnuplot2dDataset dataset;
    for (int j = 0; j < 10; j++) {
      //Calculo del temporizador de retransmision
      Time tRetransmisionActual(tRetransmisionDesde.GetDouble() + j * (tRetransmisionHasta.GetDouble() - tRetransmisionDesde.GetDouble() / 9));
      //Configuracion de aplicacion (temporizador de retransmision)
      BitAlternanteTx transmisor(dispRx, tRetransmisionActual, TAM_PAQUETE);
      Simulator::Run ();
      Simulator::Destroy ();
      dataset.Add(tRetransmisionActual.GetDouble(), transmisor.TotalDatos());

      NS_LOG_INFO ("   tRetransmisionActual: " << tRetransmisionActual.GetDouble());
      NS_LOG_INFO ("   Total paquetes: " << transmisor.TotalDatos());
      NS_LOG_INFO ("-----------------------");
    }
    //Añadimos el dataset a la grafica
    plot1.AddDataset(dataset);
  }

  /*
   * SEGUNDA GRAFICA
   */
  NS_LOG_INFO ("############################");
  NS_LOG_INFO ("# SEGUNDA GRAFICA ##########");
  NS_LOG_INFO ("############################");

  Gnuplot plot2;
  //TODO: plot2.SetTitle("");

  //Calculo del retardo de propagacion
  Time retardoPropMedio((retardoPropDesde.GetDouble() + retardoPropHasta.GetDouble()) / 2);
  NS_LOG_INFO ("retardoPropMedio: " << retardoPropMedio.GetDouble());
  NS_LOG_INFO ("############################");

  //Configuracion de la constante (retardo de propagacion)
  canal->SetAttribute ("Delay", TimeValue(retardoPropMedio));
  //Bucle para la creación de cada curva
  for (int i = 0; i < 5; i++) {
    //Calculo del parametro (velocidad de transmision)
    DataRate velocidadTxActual(velocidadTxDesde.GetBitRate() + i * (velocidadTxHasta.GetBitRate() - velocidadTxDesde.GetBitRate()) / 4);
    NS_LOG_INFO ("velocidadTxActual: " << velocidadTxActual.GetBitRate());
    NS_LOG_INFO ("***************************");
    //Configuracion del parametro (velocidad transmision)
    dispTx->SetAttribute ("DataRate", DataRateValue(velocidadTxActual));
    //Creacion de la curva
    Gnuplot2dDataset dataset;
    for (int j = 0; j < 10; j++) {
      //Calculo del temporizador de retransmision
      Time tRetransmisionActual(tRetransmisionDesde.GetDouble() + j * (tRetransmisionHasta.GetDouble() - tRetransmisionDesde.GetDouble() / 9));
      //Configuracion de aplicacion (temporizador de retransmision)
      BitAlternanteTx transmisor(dispRx, tRetransmisionActual, TAM_PAQUETE);
      Simulator::Run ();
      Simulator::Destroy ();
      dataset.Add(tRetransmisionActual.GetDouble(), transmisor.TotalDatos());

      NS_LOG_INFO ("   tRetransmisionActual: " << tRetransmisionActual.GetDouble());
      NS_LOG_INFO ("   Total paquetes: " << transmisor.TotalDatos());
      NS_LOG_INFO ("-----------------------");
    }
    //Añadimos el dataset a la grafica
    plot2.AddDataset(dataset);
  }

  NS_LOG_UNCOND ("Total paquetes: " << transmisor.TotalDatos());

  return 0;
}
<commit_msg>simulador.cc en desarrollo... (4)<commit_after>/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */

#include <ns3/core-module.h>
#include <ns3/node.h>
#include <ns3/point-to-point-net-device.h>
#include <ns3/point-to-point-channel.h>
#include <ns3/drop-tail-queue.h>
#include <ns3/gnuplot.h>
#include "BitAlternante.h"

#define TAM_PAQUETE 994

using namespace ns3;

NS_LOG_COMPONENT_DEFINE ("Practica03");

int
main (int argc, char *argv[])
{
  Time::SetResolution (Time::MS);

  //Variables para parametros de linea de comandos
  DataRate velocidadTxDesde(1);
  DataRate velocidadTxHasta(100);
  Time     retardoPropDesde(1);
  Time     retardoPropHasta(100);
  Time     tRetransmisionDesde(1);
  Time     tRetransmisionHasta(100);

  //Obtencion de parametros por linea de comandos
  CommandLine cmd;
  cmd.AddValue("velocidadTxDesde", "valor de la velocidad de transmision inicial", velocidadTxDesde);
  cmd.AddValue("velocidadTxHasta", "valor de la velocidad de transmision final", velocidadTxHasta);
  cmd.AddValue("retardoPropDesde", "retardo de propagacion inicial", retardoPropDesde);
  cmd.AddValue("retardoPropHasta", "retardo de propagacion final", retardoPropHasta);
  cmd.AddValue("tRetransmisionDesde", "temporizador de retransmisiones inicial", tRetransmisionDesde);
  cmd.AddValue("tRetransmisionHasta", "temporizador de retransmisiones final", tRetransmisionHasta);
  cmd.Parse(argc, argv);

  // Componentes del escenario:
  // Dos nodos
  Ptr<Node> nodoTx = CreateObject<Node> ();
  Ptr<Node> nodoRx = CreateObject<Node> ();
  // Dos dispositivos de red
  Ptr<PointToPointNetDevice> dispTx = CreateObject<PointToPointNetDevice> ();
  Ptr<PointToPointNetDevice> dispRx = CreateObject<PointToPointNetDevice> ();
  // Un canal punto a punto
  Ptr<PointToPointChannel> canal = CreateObject<PointToPointChannel> ();;
  // Una aplicación transmisora
  BitAlternanteTx transmisor(dispRx, Time("10ms"), 994);
  // Y una receptora
  BitAlternanteRx receptor(dispTx);

  // Montamos el escenario:
  // Añadimos una cola a cada dispositivo
  dispTx->SetQueue (CreateObject<DropTailQueue> ());
  dispRx->SetQueue (CreateObject<DropTailQueue> ());
  // Añadimos cada dispositivo a su nodo
  nodoTx->AddDevice (dispTx);
  nodoRx->AddDevice (dispRx);
  // Añadimos cada aplicación a su nodo
  nodoTx->AddApplication(&transmisor);
  nodoRx->AddApplication(&receptor);
  // Asociamos los dos dispositivos al canal
  dispTx->Attach (canal);
  dispRx->Attach (canal);

  /*// Modificamos los parámetos configurables
  canal->SetAttribute ("Delay", StringValue ("2ms"));
  dispTx->SetAttribute ("DataRate", StringValue ("5Mbps"));
  */
  /*
  transmisor.SetStartTime (Seconds (1.0));
  transmisor.SetStopTime (Seconds (10.0));
  */

  //NS_LOG_UNCOND ("Voy a simular");

  /*
   * PRIMERA GRAFICA
   */
  NS_LOG_INFO ("############################");
  NS_LOG_INFO ("# PRIMERA GRAFICA ##########");
  NS_LOG_INFO ("############################");
  Gnuplot plot1;
  //TODO: plot1.SetTitle("");

  //Calculo de la velocidad de transmision media
  DataRate velocidadTxMedia((velocidadTxDesde.GetBitRate() + velocidadTxHasta.GetBitRate()) / 2);
  NS_LOG_INFO ("velocidadTxMedia: " << velocidadTxMedia.GetBitRate());
  NS_LOG_INFO ("############################");
  //Configuracion de la constante (velocidad transmision)
  dispTx->SetAttribute ("DataRate", DataRateValue(velocidadTxMedia));
  //Bucle para la creación de cada curva
  for (int i = 0; i < 5 ; i++) {
    //Calculo del parametro (retardo de propagacion)
    Time retardoPropActual(retardoPropDesde.GetDouble() + i * (retardoPropHasta.GetDouble() - retardoPropDesde.GetDouble()) / 4);
    NS_LOG_INFO ("retardoPropActual: " << retardoPropActual.GetDouble());
    NS_LOG_INFO ("***************************");
    //Configuración del parametro (retardo de propagacion)
    canal->SetAttribute ("Delay", TimeValue(retardoPropActual));
    //Creacion de una nueva curva
    Gnuplot2dDataset dataset;
    for (int j = 0; j < 10; j++) {
      //Calculo del temporizador de retransmision
      Time tRetransmisionActual(tRetransmisionDesde.GetDouble() + j * (tRetransmisionHasta.GetDouble() - tRetransmisionDesde.GetDouble() / 9));
      //Configuracion de aplicacion (temporizador de retransmision)
      BitAlternanteTx transmisor(dispRx, tRetransmisionActual, TAM_PAQUETE);
      transmisor.SetStartTime (Seconds (1.0));
      transmisor.SetStopTime (Seconds (10.0));
      Simulator::Run ();
      Simulator::Destroy ();
      dataset.Add(tRetransmisionActual.GetDouble(), transmisor.TotalDatos());

      NS_LOG_INFO ("   tRetransmisionActual: " << tRetransmisionActual.GetDouble());
      NS_LOG_INFO ("   Total paquetes: " << transmisor.TotalDatos());
      NS_LOG_INFO ("-----------------------");
    }
    //Añadimos el dataset a la grafica
    plot1.AddDataset(dataset);
  }

  /*
   * SEGUNDA GRAFICA
   */
  NS_LOG_INFO ("############################");
  NS_LOG_INFO ("# SEGUNDA GRAFICA ##########");
  NS_LOG_INFO ("############################");

  Gnuplot plot2;
  //TODO: plot2.SetTitle("");

  //Calculo del retardo de propagacion
  Time retardoPropMedio((retardoPropDesde.GetDouble() + retardoPropHasta.GetDouble()) / 2);
  NS_LOG_INFO ("retardoPropMedio: " << retardoPropMedio.GetDouble());
  NS_LOG_INFO ("############################");

  //Configuracion de la constante (retardo de propagacion)
  canal->SetAttribute ("Delay", TimeValue(retardoPropMedio));
  //Bucle para la creación de cada curva
  for (int i = 0; i < 5; i++) {
    //Calculo del parametro (velocidad de transmision)
    DataRate velocidadTxActual(velocidadTxDesde.GetBitRate() + i * (velocidadTxHasta.GetBitRate() - velocidadTxDesde.GetBitRate()) / 4);
    NS_LOG_INFO ("velocidadTxActual: " << velocidadTxActual.GetBitRate());
    NS_LOG_INFO ("***************************");
    //Configuracion del parametro (velocidad transmision)
    dispTx->SetAttribute ("DataRate", DataRateValue(velocidadTxActual));
    //Creacion de la curva
    Gnuplot2dDataset dataset;
    for (int j = 0; j < 10; j++) {
      //Calculo del temporizador de retransmision
      Time tRetransmisionActual(tRetransmisionDesde.GetDouble() + j * (tRetransmisionHasta.GetDouble() - tRetransmisionDesde.GetDouble() / 9));
      //Configuracion de aplicacion (temporizador de retransmision)
      BitAlternanteTx transmisor(dispRx, tRetransmisionActual, TAM_PAQUETE);
      transmisor.SetStartTime (Seconds (1.0));
      transmisor.SetStopTime (Seconds (10.0));
      Simulator::Run ();
      Simulator::Destroy ();
      dataset.Add(tRetransmisionActual.GetDouble(), transmisor.TotalDatos());

      NS_LOG_INFO ("   tRetransmisionActual: " << tRetransmisionActual.GetDouble());
      NS_LOG_INFO ("   Total paquetes: " << transmisor.TotalDatos());
      NS_LOG_INFO ("-----------------------");
    }
    //Añadimos el dataset a la grafica
    plot2.AddDataset(dataset);
  }

  NS_LOG_UNCOND ("Total paquetes: " << transmisor.TotalDatos());

  return 0;
}
<|endoftext|>


<commit_before>/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */

#include <ns3/core-module.h>
#include <ns3/node.h>
#include <ns3/point-to-point-net-device.h>
#include <ns3/point-to-point-channel.h>
#include <ns3/drop-tail-queue.h>
#include <ns3/gnuplot.h>
#include "BitAlternante.h"

#define TAM_PAQUETE 994

using namespace ns3;

NS_LOG_COMPONENT_DEFINE ("Practica03");

int
main (int argc, char *argv[])
{
  Time::SetResolution (Time::MS);

  //Variables para parametros de linea de comandos
  DataRate velocidadTxDesde(1);
  DataRate velocidadTxHasta(100);
  Time     retardoPropDesde(1);
  Time     retardoPropHasta(100);
  Time     tRetransmisionDesde(1);
  Time     tRetransmisionHasta(100);

  //Obtencion de parametros por linea de comandos
  CommandLine cmd;
  cmd.AddValue("velocidadTxDesde", "valor de la velocidad de transmision inicial", velocidadTxDesde);
  cmd.AddValue("velocidadTxHasta", "valor de la velocidad de transmision final", velocidadTxHasta);
  cmd.AddValue("retardoPropDesde", "retardo de propagacion inicial", retardoPropDesde);
  cmd.AddValue("retardoPropHasta", "retardo de propagacion final", retardoPropHasta);
  cmd.AddValue("tRetransmisionDesde", "temporizador de retransmisiones inicial", tRetransmisionDesde);
  cmd.AddValue("tRetransmisionHasta", "temporizador de retransmisiones final", tRetransmisionHasta);
  cmd.Parse(argc, argv);

  // Componentes del escenario:
  // Dos nodos
  Ptr<Node> nodoTx = CreateObject<Node> ();
  Ptr<Node> nodoRx = CreateObject<Node> ();
  // Dos dispositivos de red
  Ptr<PointToPointNetDevice> dispTx = CreateObject<PointToPointNetDevice> ();
  Ptr<PointToPointNetDevice> dispRx = CreateObject<PointToPointNetDevice> ();
  // Un canal punto a punto
  Ptr<PointToPointChannel> canal = CreateObject<PointToPointChannel> ();;
  // Una aplicación transmisora
  BitAlternanteTx transmisor(dispRx, Time("10ms"), 994);
  // Y una receptora
  BitAlternanteRx receptor(dispTx);

  // Montamos el escenario:
  // Añadimos una cola a cada dispositivo
  dispTx->SetQueue (CreateObject<DropTailQueue> ());
  dispRx->SetQueue (CreateObject<DropTailQueue> ());
  // Añadimos cada dispositivo a su nodo
  nodoTx->AddDevice (dispTx);
  nodoRx->AddDevice (dispRx);
  // Añadimos cada aplicación a su nodo
  nodoTx->AddApplication(&transmisor);
  nodoRx->AddApplication(&receptor);
  // Asociamos los dos dispositivos al canal
  dispTx->Attach (canal);
  dispRx->Attach (canal);

  /*// Modificamos los parámetos configurables
  canal->SetAttribute ("Delay", StringValue ("2ms"));
  dispTx->SetAttribute ("DataRate", StringValue ("5Mbps"));
  */
  /*
  transmisor.SetStartTime (Seconds (1.0));
  transmisor.SetStopTime (Seconds (10.0));
  */

  //NS_LOG_UNCOND ("Voy a simular");

  /*
   * PRIMERA GRAFICA
   */
  NS_LOG_INFO ("############################");
  NS_LOG_INFO ("# PRIMERA GRAFICA ##########");
  NS_LOG_INFO ("############################");
  Gnuplot plot1;
  //TODO: plot1.SetTitle("");

  //Calculo de la velocidad de transmision media
  DataRate velocidadTxMedia((velocidadTxDesde.GetBitRate() + velocidadTxHasta.GetBitRate()) / 2);
  NS_LOG_INFO ("velocidadTxMedia: " << velocidadTxMedia.GetBitRate());
  NS_LOG_INFO ("############################");
  //Configuracion de la constante (velocidad transmision)
  dispTx->SetAttribute ("DataRate", DataRateValue(velocidadTxMedia));
  //Bucle para la creación de cada curva
  for (int i = 0; i < 5 ; i++) {
    //Calculo del parametro (retardo de propagacion)
    Time retardoPropActual(retardoPropDesde.GetDouble() + i * (retardoPropHasta.GetDouble() - retardoPropDesde.GetDouble()) / 4);
    NS_LOG_INFO ("retardoPropActual: " << retardoPropActual.GetDouble());
    NS_LOG_INFO ("***************************");
    //Configuración del parametro (retardo de propagacion)
    canal->SetAttribute ("Delay", TimeValue(retardoPropActual));
    //Creacion de una nueva curva
    Gnuplot2dDataset dataset;
    for (int j = 0; j < 10; j++) {
      //Calculo del temporizador de retransmision
      Time tRetransmisionActual(tRetransmisionDesde.GetDouble() + j * (tRetransmisionHasta.GetDouble() - tRetransmisionDesde.GetDouble() / 9));
      //Configuracion de aplicacion (temporizador de retransmision)
      BitAlternanteTx transmisor(dispRx, tRetransmisionActual, TAM_PAQUETE);
      transmisor.SetStartTime (Seconds (1.0));
      transmisor.SetStopTime (Seconds (10.0));
      Simulator::Run ();
      Simulator::Destroy ();
      dataset.Add(tRetransmisionActual.GetDouble(), transmisor.TotalDatos());

      NS_LOG_INFO ("   tRetransmisionActual: " << tRetransmisionActual.GetDouble());
      NS_LOG_INFO ("   Total paquetes: " << transmisor.TotalDatos());
      NS_LOG_INFO ("-----------------------");
    }
    //Añadimos el dataset a la grafica
    plot1.AddDataset(dataset);
  }

  /*
   * SEGUNDA GRAFICA
   */
  NS_LOG_INFO ("############################");
  NS_LOG_INFO ("# SEGUNDA GRAFICA ##########");
  NS_LOG_INFO ("############################");

  Gnuplot plot2;
  //TODO: plot2.SetTitle("");

  //Calculo del retardo de propagacion
  Time retardoPropMedio((retardoPropDesde.GetDouble() + retardoPropHasta.GetDouble()) / 2);
  NS_LOG_INFO ("retardoPropMedio: " << retardoPropMedio.GetDouble());
  NS_LOG_INFO ("############################");

  //Configuracion de la constante (retardo de propagacion)
  canal->SetAttribute ("Delay", TimeValue(retardoPropMedio));
  //Bucle para la creación de cada curva
  for (int i = 0; i < 5; i++) {
    //Calculo del parametro (velocidad de transmision)
    DataRate velocidadTxActual(velocidadTxDesde.GetBitRate() + i * (velocidadTxHasta.GetBitRate() - velocidadTxDesde.GetBitRate()) / 4);
    NS_LOG_INFO ("velocidadTxActual: " << velocidadTxActual.GetBitRate());
    NS_LOG_INFO ("***************************");
    //Configuracion del parametro (velocidad transmision)
    dispTx->SetAttribute ("DataRate", DataRateValue(velocidadTxActual));
    //Creacion de la curva
    Gnuplot2dDataset dataset;
    for (int j = 0; j < 10; j++) {
      //Calculo del temporizador de retransmision
      Time tRetransmisionActual(tRetransmisionDesde.GetDouble() + j * (tRetransmisionHasta.GetDouble() - tRetransmisionDesde.GetDouble() / 9));
      //Configuracion de aplicacion (temporizador de retransmision)
      BitAlternanteTx transmisor(dispRx, tRetransmisionActual, TAM_PAQUETE);
      transmisor.SetStartTime (Seconds (1.0));
      transmisor.SetStopTime (Seconds (10.0));
      Simulator::Run ();
      Simulator::Destroy ();
      dataset.Add(tRetransmisionActual.GetDouble(), transmisor.TotalDatos());

      NS_LOG_INFO ("   tRetransmisionActual: " << tRetransmisionActual.GetDouble());
      NS_LOG_INFO ("   Total paquetes: " << transmisor.TotalDatos());
      NS_LOG_INFO ("-----------------------");
    }
    //Añadimos el dataset a la grafica
    plot2.AddDataset(dataset);
  }

  NS_LOG_UNCOND ("Total paquetes: " << transmisor.TotalDatos());

  return 0;
}
<commit_msg>simulador.cc en desarrollo... (5)<commit_after>/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */

#include <ns3/core-module.h>
#include <ns3/node.h>
#include <ns3/point-to-point-net-device.h>
#include <ns3/point-to-point-channel.h>
#include <ns3/drop-tail-queue.h>
#include <ns3/gnuplot.h>
#include "BitAlternante.h"

#define TAM_PAQUETE 994

using namespace ns3;

NS_LOG_COMPONENT_DEFINE ("Practica03");

int
main (int argc, char *argv[])
{
  Time::SetResolution (Time::MS);

  //Variables para parametros de linea de comandos
  DataRate velocidadTxDesde(1);
  DataRate velocidadTxHasta(100);
  Time     retardoPropDesde(1);
  Time     retardoPropHasta(100);
  Time     tRetransmisionDesde(1);
  Time     tRetransmisionHasta(100);

  //Obtencion de parametros por linea de comandos
  CommandLine cmd;
  cmd.AddValue("velocidadTxDesde", "valor de la velocidad de transmision inicial", velocidadTxDesde);
  cmd.AddValue("velocidadTxHasta", "valor de la velocidad de transmision final", velocidadTxHasta);
  cmd.AddValue("retardoPropDesde", "retardo de propagacion inicial", retardoPropDesde);
  cmd.AddValue("retardoPropHasta", "retardo de propagacion final", retardoPropHasta);
  cmd.AddValue("tRetransmisionDesde", "temporizador de retransmisiones inicial", tRetransmisionDesde);
  cmd.AddValue("tRetransmisionHasta", "temporizador de retransmisiones final", tRetransmisionHasta);
  cmd.Parse(argc, argv);

  // Componentes del escenario:
  // Dos nodos
  Ptr<Node> nodoTx = CreateObject<Node> ();
  Ptr<Node> nodoRx = CreateObject<Node> ();
  // Dos dispositivos de red
  Ptr<PointToPointNetDevice> dispTx = CreateObject<PointToPointNetDevice> ();
  Ptr<PointToPointNetDevice> dispRx = CreateObject<PointToPointNetDevice> ();
  // Un canal punto a punto
  Ptr<PointToPointChannel> canal = CreateObject<PointToPointChannel> ();;
  // Una aplicación transmisora
  //BitAlternanteTx transmisor(dispRx, Time("10ms"), 994);
  // Y una receptora
  BitAlternanteRx receptor(dispTx);

  // Montamos el escenario:
  // Añadimos una cola a cada dispositivo
  dispTx->SetQueue (CreateObject<DropTailQueue> ());
  dispRx->SetQueue (CreateObject<DropTailQueue> ());
  // Añadimos cada dispositivo a su nodo
  nodoTx->AddDevice (dispTx);
  nodoRx->AddDevice (dispRx);
  // Añadimos cada aplicación a su nodo
  nodoTx->AddApplication(&transmisor);
  nodoRx->AddApplication(&receptor);
  // Asociamos los dos dispositivos al canal
  dispTx->Attach (canal);
  dispRx->Attach (canal);

  /*// Modificamos los parámetos configurables
  canal->SetAttribute ("Delay", StringValue ("2ms"));
  dispTx->SetAttribute ("DataRate", StringValue ("5Mbps"));
  */
  /*
  transmisor.SetStartTime (Seconds (1.0));
  transmisor.SetStopTime (Seconds (10.0));
  */

  //NS_LOG_UNCOND ("Voy a simular");

  /*
   * PRIMERA GRAFICA
   */
  NS_LOG_INFO ("############################");
  NS_LOG_INFO ("# PRIMERA GRAFICA ##########");
  NS_LOG_INFO ("############################");
  Gnuplot plot1;
  //TODO: plot1.SetTitle("");

  //Calculo de la velocidad de transmision media
  DataRate velocidadTxMedia((velocidadTxDesde.GetBitRate() + velocidadTxHasta.GetBitRate()) / 2);
  NS_LOG_INFO ("velocidadTxMedia: " << velocidadTxMedia.GetBitRate());
  NS_LOG_INFO ("############################");
  //Configuracion de la constante (velocidad transmision)
  dispTx->SetAttribute ("DataRate", DataRateValue(velocidadTxMedia));
  //Bucle para la creación de cada curva
  for (int i = 0; i < 5 ; i++) {
    //Calculo del parametro (retardo de propagacion)
    Time retardoPropActual(retardoPropDesde.GetDouble() + i * (retardoPropHasta.GetDouble() - retardoPropDesde.GetDouble()) / 4);
    NS_LOG_INFO ("retardoPropActual: " << retardoPropActual.GetDouble());
    NS_LOG_INFO ("***************************");
    //Configuración del parametro (retardo de propagacion)
    canal->SetAttribute ("Delay", TimeValue(retardoPropActual));
    //Creacion de una nueva curva
    Gnuplot2dDataset dataset;
    for (int j = 0; j < 10; j++) {
      //Calculo del temporizador de retransmision
      Time tRetransmisionActual(tRetransmisionDesde.GetDouble() + j * (tRetransmisionHasta.GetDouble() - tRetransmisionDesde.GetDouble() / 9));
      //Configuracion de aplicacion (temporizador de retransmision)
      BitAlternanteTx transmisor(dispRx, tRetransmisionActual, TAM_PAQUETE);
      transmisor.SetStartTime (Seconds (1.0));
      transmisor.SetStopTime (Seconds (10.0));
      Simulator::Run ();
      Simulator::Destroy ();
      dataset.Add(tRetransmisionActual.GetDouble(), transmisor.TotalDatos());

      NS_LOG_INFO ("   tRetransmisionActual: " << tRetransmisionActual.GetDouble());
      NS_LOG_INFO ("   Total paquetes: " << transmisor.TotalDatos());
      NS_LOG_INFO ("-----------------------");
    }
    //Añadimos el dataset a la grafica
    plot1.AddDataset(dataset);
  }

  /*
   * SEGUNDA GRAFICA
   */
  NS_LOG_INFO ("############################");
  NS_LOG_INFO ("# SEGUNDA GRAFICA ##########");
  NS_LOG_INFO ("############################");

  Gnuplot plot2;
  //TODO: plot2.SetTitle("");

  //Calculo del retardo de propagacion
  Time retardoPropMedio((retardoPropDesde.GetDouble() + retardoPropHasta.GetDouble()) / 2);
  NS_LOG_INFO ("retardoPropMedio: " << retardoPropMedio.GetDouble());
  NS_LOG_INFO ("############################");

  //Configuracion de la constante (retardo de propagacion)
  canal->SetAttribute ("Delay", TimeValue(retardoPropMedio));
  //Bucle para la creación de cada curva
  for (int i = 0; i < 5; i++) {
    //Calculo del parametro (velocidad de transmision)
    DataRate velocidadTxActual(velocidadTxDesde.GetBitRate() + i * (velocidadTxHasta.GetBitRate() - velocidadTxDesde.GetBitRate()) / 4);
    NS_LOG_INFO ("velocidadTxActual: " << velocidadTxActual.GetBitRate());
    NS_LOG_INFO ("***************************");
    //Configuracion del parametro (velocidad transmision)
    dispTx->SetAttribute ("DataRate", DataRateValue(velocidadTxActual));
    //Creacion de la curva
    Gnuplot2dDataset dataset;
    for (int j = 0; j < 10; j++) {
      //Calculo del temporizador de retransmision
      Time tRetransmisionActual(tRetransmisionDesde.GetDouble() + j * (tRetransmisionHasta.GetDouble() - tRetransmisionDesde.GetDouble() / 9));
      //Configuracion de aplicacion (temporizador de retransmision)
      BitAlternanteTx transmisor(dispRx, tRetransmisionActual, TAM_PAQUETE);
      transmisor.SetStartTime (Seconds (1.0));
      transmisor.SetStopTime (Seconds (10.0));
      Simulator::Run ();
      Simulator::Destroy ();
      dataset.Add(tRetransmisionActual.GetDouble(), transmisor.TotalDatos());

      NS_LOG_INFO ("   tRetransmisionActual: " << tRetransmisionActual.GetDouble());
      NS_LOG_INFO ("   Total paquetes: " << transmisor.TotalDatos());
      NS_LOG_INFO ("-----------------------");
    }
    //Añadimos el dataset a la grafica
    plot2.AddDataset(dataset);
  }

  NS_LOG_UNCOND ("Total paquetes: " << transmisor.TotalDatos());

  return 0;
}
<|endoftext|>


<commit_before>/*
 * Copyright 2009 The VOTCA Development Team (http://www.votca.org)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

#include "topology.h"
#include "interaction.h"
#include <votca/tools/rangeparser.h>
#include <stdexcept>

namespace votca { namespace csg {

Topology::~Topology()
{
    Cleanup();
    if(_bc)
        delete (_bc);
    _bc = NULL;
}

void Topology::Cleanup()
{
    // cleanup beads
    {
        BeadContainer::iterator i;
        for(i=_beads.begin();i<_beads.end();++i)
            delete *i;
        _beads.clear();
    }
    // cleanup molecules
    {
        MoleculeContainer::iterator i;
        for(i=_molecules.begin();i<_molecules.end();++i)
            delete *i;
        _molecules.clear();
    }
    // cleanup residues
    {
        ResidueContainer::iterator i;
        for(i=_residues.begin();i<_residues.end();++i)
            delete (*i);
        _residues.clear();
    }
    // cleanup interactions
    {
        InteractionContainer::iterator i;
        for(i=_interactions.begin();i<_interactions.end();++i)
            delete (*i);
        _interactions.clear();
    }
    // cleanup _bc object
    if(_bc)
        delete (_bc);
    _bc = new OpenBox();
}

/// \todo implement checking!!
void Topology::CreateMoleculesByRange(string name, int first, int nbeads, int nmolecules)
{
    Molecule *mol = CreateMolecule(name);
    int beadcount=0;

    BeadContainer::iterator bead;
    for(bead=_beads.begin(); bead!=_beads.end(); ++bead) {
        while(--first > 0) continue;
        string bname = //lexical_cast<string>(mol->getId()) + ":"
                      //lexical_cast<string>(bead->Residue()) + ":"
                      //+
                      (*bead)->getName();
        mol->AddBead((*bead), bname);
        if(++beadcount == nbeads) {
            if(--nmolecules <= 0) break;
            mol = CreateMolecule(name);
            beadcount = 0;
        }
    }
}

/// \todo clean up CreateMoleculesByResidue!
void Topology::CreateMoleculesByResidue()
{
    // first create a molecule for each residue
    ResidueContainer::iterator res;
    for(res=_residues.begin(); res!=_residues.end(); ++res) {
        CreateMolecule((*res)->getName());
    }

    // add the beads to the corresponding molecules based on their resid
    BeadContainer::iterator bead;
    for(bead=_beads.begin(); bead!=_beads.end(); ++bead) {
        //MoleculeByIndex((*bead)->getResnr())->AddBead((*bead)->getId(), (*bead)->getName());

        MoleculeByIndex((*bead)->getResnr())->AddBead((*bead), string("1:TRI:") + (*bead)->getName());
    }

    /// \todo sort beads in molecules that all beads are stored in the same order. This is needed for the mapping!
}

void Topology::CreateOneBigMolecule(string name)
{
    Molecule *mi = CreateMolecule(name);

    BeadContainer::iterator bead;

    for(bead=_beads.begin(); bead!=_beads.end(); ++bead) {
        stringstream n("");
        n << (*bead)->getResnr() +1 << ":" <<  _residues[(*bead)->getResnr()]->getName() << ":" << (*bead)->getName();
        //cout << n.str() << endl;
        mi->AddBead((*bead), n.str());
    }
}

void Topology::Add(Topology *top)
{
    BeadContainer::iterator bead;
    ResidueContainer::iterator res;
    MoleculeContainer::iterator mol;

    int res0=ResidueCount();

    for(bead=top->_beads.begin(); bead!=top->_beads.end(); ++bead) {
        Bead *bi = *bead;
        BeadType *type =  GetOrCreateBeadType(bi->getType()->getName());
        CreateBead(bi->getSymmetry(), bi->getName(), type, bi->getResnr()+res0, bi->getM(), bi->getQ());
    }

    for(res=top->_residues.begin();res!=top->_residues.end(); ++res) {
        CreateResidue((*res)->getName());
    }

    // \todo beadnames in molecules!!
    for(mol=top->_molecules.begin();mol!=top->_molecules.end(); ++mol) {
        Molecule *mi = CreateMolecule((*mol)->getName());
        for(int i=0; i<mi->BeadCount(); i++) {
            mi->AddBead(mi->getBead(i), "invalid");
        }
    }
}

void Topology::CopyTopologyData(Topology *top)
{
    BeadContainer::iterator it_bead;
    ResidueContainer::iterator it_res;
    MoleculeContainer::iterator it_mol;
    InteractionContainer::iterator it_ia;

    _bc->setBox(top->getBox());
    _time = top->_time;
    _step = top->_step;

    // cleanup old data
    Cleanup();

    // copy all residues
    for(it_res=top->_residues.begin();it_res!=top->_residues.end(); ++it_res) {
        CreateResidue((*it_res)->getName());
    }

    // create all beads
    for(it_bead=top->_beads.begin(); it_bead!=top->_beads.end(); ++it_bead) {
        Bead *bi = *it_bead;
        BeadType *type =  GetOrCreateBeadType(bi->getType()->getName());
        Bead *bn = CreateBead(bi->getSymmetry(), bi->getName(), type, bi->getResnr(), bi->getM(), bi->getQ());
        bn->setOptions(bi->Options());
    }

    // copy all molecules
    for(it_mol=top->_molecules.begin();it_mol!=top->_molecules.end(); ++it_mol) {
        Molecule *mi = CreateMolecule((*it_mol)->getName());
        for(int i=0; i<(*it_mol)->BeadCount(); i++) {
            int beadid = (*it_mol)->getBead(i)->getId();
            mi->AddBead(_beads[beadid], (*it_mol)->getBeadName(i));
        }
    }
    // TODO: copy interactions
    //for(it_ia=top->_interaction.begin();it_ia=top->_interactions.end();++it_ia) {

    //}
}

void Topology::RenameMolecules(string range, string name)
{
    RangeParser rp;
    RangeParser::iterator i;

    rp.Parse(range);
    for(i=rp.begin();i!=rp.end();++i) {
        if((unsigned int)*i > _molecules.size())
            throw runtime_error(string("RenameMolecules: num molecules smaller than"));
        getMolecule(*i-1)->setName(name);
    }
}

void Topology::CheckMoleculeNaming(void)
{
    map<string,int> nbeads;

    for(MoleculeContainer::iterator iter = _molecules.begin(); iter!=_molecules.end(); ++iter) {
        map<string,int>::iterator entry = nbeads.find((*iter)->getName());
        if(entry != nbeads.end()) {
            if(entry->second != (*iter)->BeadCount())
                throw runtime_error("There are molecules which have the same name but different number of bead "
                        "please check the section manual topology handling in the votca manual");
            continue;
        }
        nbeads[(*iter)->getName()] = (*iter)->BeadCount();
    }
}

void Topology::AddBondedInteraction(Interaction *ic)
{
    map<string,int>::iterator iter;
    iter = _interaction_groups.find(ic->getGroup());
    if(iter!=_interaction_groups.end())
        ic->setGroupId((*iter).second);
    else {
        int i= _interaction_groups.size();
        _interaction_groups[ic->getGroup()] = i;
        ic->setGroupId(i);
    }
    _interactions.push_back(ic);
    _interactions_by_group[ic->getGroup()].push_back(ic);
}

std::list<Interaction *> Topology::InteractionsInGroup(const string &group)
{
    map<string, list<Interaction*> >::iterator iter;
    iter = _interactions_by_group.find(group);
    if(iter == _interactions_by_group.end())
        return list<Interaction *>();
    return iter->second;
}

BeadType *Topology::GetOrCreateBeadType(string name)
{
    map<string, int>::iterator iter;

    iter = _beadtype_map.find(name);
    if(iter == _beadtype_map.end()) {
        BeadType *bt = new BeadType(this, _beadtypes.size(), name);
        _beadtypes.push_back(bt);
        _beadtype_map[name] = bt->getId();
        return bt;
    }
    else {
        return _beadtypes[(*iter).second];
    }
    return NULL;
}

vec Topology::BCShortestConnection(const vec &r_i, const vec &r_j) const
{
    return _bc->BCShortestConnection(r_i, r_j);
}

vec Topology::getDist(int bead1, int bead2) const
{
    return BCShortestConnection(
            getBead(bead1)->getPos(),
            getBead(bead2)->getPos());
}

double Topology::BoxVolume()
{
    return _bc->BoxVolume();
}

void Topology::RebuildExclusions()
{
    _exclusions.CreateExclusions(this);
}

BoundaryCondition::eBoxtype Topology::autoDetectBoxType(const matrix &box) {
    // set the box type to OpenBox in case "box" is the zero matrix,
    // to OrthorhombicBox in case "box" is a diagonal matrix,
    // or to TriclinicBox otherwise
    if(box.get(0,0)==0 && box.get(0,1)==0 && box.get(0,2)==0 &&
       box.get(1,0)==0 && box.get(1,1)==0 && box.get(1,2)==0 &&
       box.get(2,0)==0 && box.get(2,1)==0 && box.get(2,2)==0) {
        cout << "box open\n";
        return BoundaryCondition::typeOpen;
    }
    else
    if(box.get(0,1)==0 && box.get(0,2)==0 &&
       box.get(1,0)==0 && box.get(1,2)==0 &&
       box.get(2,0)==0 && box.get(2,1)==0) {
        cout << "box orth\n";
        return BoundaryCondition::typeOrthorhombic;
    }
    else {
        cout << "box tric\n";
        return BoundaryCondition::typeTriclinic;
    }
    return BoundaryCondition::typeOpen;
}

double Topology::ShortestBoxSize()
{
    vec _box_a = getBox().getCol(0);
    vec _box_b = getBox().getCol(1);
    vec _box_c = getBox().getCol(2);

    // create plane normals
    vec _norm_a = _box_b ^ _box_c;
    vec _norm_b = _box_c ^ _box_a;
    vec _norm_c = _box_a ^ _box_b;

    _norm_a.normalize();
    _norm_b.normalize();
    _norm_c.normalize();

    double la = _box_a * _norm_a;
    double lb = _box_b * _norm_b;
    double lc = _box_c * _norm_c;

    return min(la, min(lb, lc));
}

}}
<commit_msg>minor change concerning cout<commit_after>/*
 * Copyright 2009 The VOTCA Development Team (http://www.votca.org)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

#include "topology.h"
#include "interaction.h"
#include <votca/tools/rangeparser.h>
#include <stdexcept>

namespace votca { namespace csg {

Topology::~Topology()
{
    Cleanup();
    if(_bc)
        delete (_bc);
    _bc = NULL;
}

void Topology::Cleanup()
{
    // cleanup beads
    {
        BeadContainer::iterator i;
        for(i=_beads.begin();i<_beads.end();++i)
            delete *i;
        _beads.clear();
    }
    // cleanup molecules
    {
        MoleculeContainer::iterator i;
        for(i=_molecules.begin();i<_molecules.end();++i)
            delete *i;
        _molecules.clear();
    }
    // cleanup residues
    {
        ResidueContainer::iterator i;
        for(i=_residues.begin();i<_residues.end();++i)
            delete (*i);
        _residues.clear();
    }
    // cleanup interactions
    {
        InteractionContainer::iterator i;
        for(i=_interactions.begin();i<_interactions.end();++i)
            delete (*i);
        _interactions.clear();
    }
    // cleanup _bc object
    if(_bc)
        delete (_bc);
    _bc = new OpenBox();
}

/// \todo implement checking!!
void Topology::CreateMoleculesByRange(string name, int first, int nbeads, int nmolecules)
{
    Molecule *mol = CreateMolecule(name);
    int beadcount=0;

    BeadContainer::iterator bead;
    for(bead=_beads.begin(); bead!=_beads.end(); ++bead) {
        while(--first > 0) continue;
        string bname = //lexical_cast<string>(mol->getId()) + ":"
                      //lexical_cast<string>(bead->Residue()) + ":"
                      //+
                      (*bead)->getName();
        mol->AddBead((*bead), bname);
        if(++beadcount == nbeads) {
            if(--nmolecules <= 0) break;
            mol = CreateMolecule(name);
            beadcount = 0;
        }
    }
}

/// \todo clean up CreateMoleculesByResidue!
void Topology::CreateMoleculesByResidue()
{
    // first create a molecule for each residue
    ResidueContainer::iterator res;
    for(res=_residues.begin(); res!=_residues.end(); ++res) {
        CreateMolecule((*res)->getName());
    }

    // add the beads to the corresponding molecules based on their resid
    BeadContainer::iterator bead;
    for(bead=_beads.begin(); bead!=_beads.end(); ++bead) {
        //MoleculeByIndex((*bead)->getResnr())->AddBead((*bead)->getId(), (*bead)->getName());

        MoleculeByIndex((*bead)->getResnr())->AddBead((*bead), string("1:TRI:") + (*bead)->getName());
    }

    /// \todo sort beads in molecules that all beads are stored in the same order. This is needed for the mapping!
}

void Topology::CreateOneBigMolecule(string name)
{
    Molecule *mi = CreateMolecule(name);

    BeadContainer::iterator bead;

    for(bead=_beads.begin(); bead!=_beads.end(); ++bead) {
        stringstream n("");
        n << (*bead)->getResnr() +1 << ":" <<  _residues[(*bead)->getResnr()]->getName() << ":" << (*bead)->getName();
        //cout << n.str() << endl;
        mi->AddBead((*bead), n.str());
    }
}

void Topology::Add(Topology *top)
{
    BeadContainer::iterator bead;
    ResidueContainer::iterator res;
    MoleculeContainer::iterator mol;

    int res0=ResidueCount();

    for(bead=top->_beads.begin(); bead!=top->_beads.end(); ++bead) {
        Bead *bi = *bead;
        BeadType *type =  GetOrCreateBeadType(bi->getType()->getName());
        CreateBead(bi->getSymmetry(), bi->getName(), type, bi->getResnr()+res0, bi->getM(), bi->getQ());
    }

    for(res=top->_residues.begin();res!=top->_residues.end(); ++res) {
        CreateResidue((*res)->getName());
    }

    // \todo beadnames in molecules!!
    for(mol=top->_molecules.begin();mol!=top->_molecules.end(); ++mol) {
        Molecule *mi = CreateMolecule((*mol)->getName());
        for(int i=0; i<mi->BeadCount(); i++) {
            mi->AddBead(mi->getBead(i), "invalid");
        }
    }
}

void Topology::CopyTopologyData(Topology *top)
{
    BeadContainer::iterator it_bead;
    ResidueContainer::iterator it_res;
    MoleculeContainer::iterator it_mol;
    InteractionContainer::iterator it_ia;

    _bc->setBox(top->getBox());
    _time = top->_time;
    _step = top->_step;

    // cleanup old data
    Cleanup();

    // copy all residues
    for(it_res=top->_residues.begin();it_res!=top->_residues.end(); ++it_res) {
        CreateResidue((*it_res)->getName());
    }

    // create all beads
    for(it_bead=top->_beads.begin(); it_bead!=top->_beads.end(); ++it_bead) {
        Bead *bi = *it_bead;
        BeadType *type =  GetOrCreateBeadType(bi->getType()->getName());
        Bead *bn = CreateBead(bi->getSymmetry(), bi->getName(), type, bi->getResnr(), bi->getM(), bi->getQ());
        bn->setOptions(bi->Options());
    }

    // copy all molecules
    for(it_mol=top->_molecules.begin();it_mol!=top->_molecules.end(); ++it_mol) {
        Molecule *mi = CreateMolecule((*it_mol)->getName());
        for(int i=0; i<(*it_mol)->BeadCount(); i++) {
            int beadid = (*it_mol)->getBead(i)->getId();
            mi->AddBead(_beads[beadid], (*it_mol)->getBeadName(i));
        }
    }
    // TODO: copy interactions
    //for(it_ia=top->_interaction.begin();it_ia=top->_interactions.end();++it_ia) {

    //}
}

void Topology::RenameMolecules(string range, string name)
{
    RangeParser rp;
    RangeParser::iterator i;

    rp.Parse(range);
    for(i=rp.begin();i!=rp.end();++i) {
        if((unsigned int)*i > _molecules.size())
            throw runtime_error(string("RenameMolecules: num molecules smaller than"));
        getMolecule(*i-1)->setName(name);
    }
}

void Topology::CheckMoleculeNaming(void)
{
    map<string,int> nbeads;

    for(MoleculeContainer::iterator iter = _molecules.begin(); iter!=_molecules.end(); ++iter) {
        map<string,int>::iterator entry = nbeads.find((*iter)->getName());
        if(entry != nbeads.end()) {
            if(entry->second != (*iter)->BeadCount())
                throw runtime_error("There are molecules which have the same name but different number of bead "
                        "please check the section manual topology handling in the votca manual");
            continue;
        }
        nbeads[(*iter)->getName()] = (*iter)->BeadCount();
    }
}

void Topology::AddBondedInteraction(Interaction *ic)
{
    map<string,int>::iterator iter;
    iter = _interaction_groups.find(ic->getGroup());
    if(iter!=_interaction_groups.end())
        ic->setGroupId((*iter).second);
    else {
        int i= _interaction_groups.size();
        _interaction_groups[ic->getGroup()] = i;
        ic->setGroupId(i);
    }
    _interactions.push_back(ic);
    _interactions_by_group[ic->getGroup()].push_back(ic);
}

std::list<Interaction *> Topology::InteractionsInGroup(const string &group)
{
    map<string, list<Interaction*> >::iterator iter;
    iter = _interactions_by_group.find(group);
    if(iter == _interactions_by_group.end())
        return list<Interaction *>();
    return iter->second;
}

BeadType *Topology::GetOrCreateBeadType(string name)
{
    map<string, int>::iterator iter;

    iter = _beadtype_map.find(name);
    if(iter == _beadtype_map.end()) {
        BeadType *bt = new BeadType(this, _beadtypes.size(), name);
        _beadtypes.push_back(bt);
        _beadtype_map[name] = bt->getId();
        return bt;
    }
    else {
        return _beadtypes[(*iter).second];
    }
    return NULL;
}

vec Topology::BCShortestConnection(const vec &r_i, const vec &r_j) const
{
    return _bc->BCShortestConnection(r_i, r_j);
}

vec Topology::getDist(int bead1, int bead2) const
{
    return BCShortestConnection(
            getBead(bead1)->getPos(),
            getBead(bead2)->getPos());
}

double Topology::BoxVolume()
{
    return _bc->BoxVolume();
}

void Topology::RebuildExclusions()
{
    _exclusions.CreateExclusions(this);
}

BoundaryCondition::eBoxtype Topology::autoDetectBoxType(const matrix &box) {
    // set the box type to OpenBox in case "box" is the zero matrix,
    // to OrthorhombicBox in case "box" is a diagonal matrix,
    // or to TriclinicBox otherwise
    if(box.get(0,0)==0 && box.get(0,1)==0 && box.get(0,2)==0 &&
       box.get(1,0)==0 && box.get(1,1)==0 && box.get(1,2)==0 &&
       box.get(2,0)==0 && box.get(2,1)==0 && box.get(2,2)==0) {
        //cout << "box open\n";
        return BoundaryCondition::typeOpen;
    }
    else
    if(box.get(0,1)==0 && box.get(0,2)==0 &&
       box.get(1,0)==0 && box.get(1,2)==0 &&
       box.get(2,0)==0 && box.get(2,1)==0) {
        //cout << "box orth\n";
        return BoundaryCondition::typeOrthorhombic;
    }
    else {
        //cout << "box tric\n";
        return BoundaryCondition::typeTriclinic;
    }
    return BoundaryCondition::typeOpen;
}

double Topology::ShortestBoxSize()
{
    vec _box_a = getBox().getCol(0);
    vec _box_b = getBox().getCol(1);
    vec _box_c = getBox().getCol(2);

    // create plane normals
    vec _norm_a = _box_b ^ _box_c;
    vec _norm_b = _box_c ^ _box_a;
    vec _norm_c = _box_a ^ _box_b;

    _norm_a.normalize();
    _norm_b.normalize();
    _norm_c.normalize();

    double la = _box_a * _norm_a;
    double lb = _box_b * _norm_b;
    double lc = _box_c * _norm_c;

    return min(la, min(lb, lc));
}

}}
<|endoftext|>