void AlgorytmGenetyczny::krzyzuj(AlgorytmGenetyczny::OsobnikDNA ojciec, AlgorytmGenetyczny::OsobnikDNA matka) {
    std::vector<int> a = ojciec.getRozwiazanie(), b = matka.getRozwiazanie();
    a = inwersja(a);
    b = inwersja(b);
    int i = rand() % liczbaWierzcholkow;
    std::swap_ranges(a.begin() + i, a.end(), b.begin() + i);
    a = odwrotnaInversja(a);
    b = odwrotnaInversja(b);
    if (a[0] != wierzcholekPoczatkowy)
        for (int i = 0; i < a.size(); i++)
            if (a[i] == wierzcholekPoczatkowy) {
                std::swap(a[0], a[i]);
                break;
            }
    if (b[0] != wierzcholekPoczatkowy)
        for (int i = 0; i < b.size(); i++)
            if (b[i] == wierzcholekPoczatkowy) {
                std::swap(b[0], b[i]);
                break;
            };
    OsobnikDNA syn(this), corka(this);
    syn.setRozwiazanie(a);
    corka.setRozwiazanie(b);
    populacja.push_back(syn);
    populacja.push_back(corka);
}
Exemplo n.º 2
0
bool DLDPCEnDec::decodeOne(const vector<int>& accSyn, int codeID, const vector<double>& initLLR, vector<int>& decSeq)
{
	if (codeID == ldpcCodes.nCodes + 1)
		return true;

	int codeIndex = ldpcCodes.codeIDMapInd[codeID];

	int synLen = (ldpcCodes.codeLen / ldpcCodes.period) * codeID;

	// get the syndrome from the accumulated syndrome

	vector<int> syn(synLen);

	int currIndex = 0, prevIndex = 0;

	syn[0] = accSyn[0];

	for (int i = 1; i<synLen; i++)
	{
		syn[i] =  ((accSyn[i] + accSyn[i-1]) % 2);
	}

	return beliefPropagation(&ldpcCodes.ir[codeIndex][0], &ldpcCodes.jc[0],
		synLen, ldpcCodes.codeLen, ldpcCodes.nzmax, &initLLR[0], &syn[0], &decSeq[0]);
}
Exemplo n.º 3
0
	void ThreadPool::AddRequest(WorkRequest* preq)
	{
		if(preq != NULL)
		{
			Synchronized syn(m_Mutex);
			m_WorkRequestList.push_back(preq);
		}

		Notify();
	}
Exemplo n.º 4
0
int main( int argc, char *argv[] ) {
    SynfireParameters params(argc, argv);
    Timer timer;

    timer.Start();
    Synfire syn(params);
    timer.Stop();
    std::cout << "Initialization time: " << US_TO_MS(timer.Duration()) << " ms." << std::endl;

    syn.Run();
}
Exemplo n.º 5
0
	void TimerThread::Run()
	{
		while(IsContinue())
		{
			TIMER_REQUEST_T tTimerReq = {0};
			bool bHasReq = false;
			bool bReqExpired = false;
			int nDiffTime = 0;

			// 取一个Timer请求
			{
				Synchronized syn(m_Mutex);
				m_TimerRequestList.sort();

				TimerRequestList::iterator it = m_TimerRequestList.begin();
				if(it != m_TimerRequestList.end())
				{
					tTimerReq = *it;
					bHasReq = true;

					struct timeval tv = {0};
					gettimeofday(&tv, NULL);

					if(tv.tv_sec >= tTimerReq.nTimestamp)
					{
						m_TimerRequestList.pop_front();
						bReqExpired = true;
					}
					else
					{
						nDiffTime = tTimerReq.nTimestamp - tv.tv_sec;
					}
				}
			}

			// 对请求执行定时
			if(bHasReq)
			{
				if(bReqExpired)
				{
					DoTimerRequest(tTimerReq.pRequest);
				}
				else
				{
					Wait(nDiffTime);
				}
			}
			else
			{
				Wait();
			}
		}
	}
Exemplo n.º 6
0
	void EventNetDispatch::Halt()
	{
		SOCKET_SELF_MSG_T msg;
		msg.nMsgType = SOCKET_SELF_MSG_EXIT_THREAD;
		msg.nSocketFd = 0;

		{
			Synchronized syn(m_MutexClient);
			Socket::WriteSocket(m_fdConnSelfClient, (const char*)&msg, sizeof(msg));
		}

		Socket::CloseSocket(m_fdListen);
		this->StopRunning();
	}
Exemplo n.º 7
0
	void EventMsqThreadImpl::Run()
	{
		while(m_EventMsqDispatch.m_bContinue)
		{
			try
			{
				Buffer bufMsg;
				memset(bufMsg.Inout(), 0, bufMsg.Capacity());
				IPCMSQ_RET_TYPE_E nRetMsq = IPCMSQ_RET_OK;

				{
					// 加锁,读取消息队列(进入临界区)
					// 经验证:linux平台不需要加锁,但是其他平台由于线程实现机制的特殊性,不能保证消息接收时原子操作
					Synchronized syn(m_EventMsqDispatch.m_Mutex);

					if(!m_EventMsqDispatch.m_bContinue)
					{
						return;
					}
					else
					{
						nRetMsq = IPCMSQ::ReceiveMsg(m_EventMsqDispatch.m_EventMsqOption.nMsqId, bufMsg);
					}
				}

				if(nRetMsq == IPCMSQ_RET_OK)
				{
					// 检测收到的消息是否是关闭消息
					EVENT_MSQ_MAGIC_MSG_T msg;
					if(bufMsg.Size() == sizeof(msg)
					   && !memcmp(bufMsg.Inout(), &msg, sizeof(msg)))
					{
						return;
					}

					try
					{
						m_EventMsqDispatch.m_EventMsqOption.pHandler->DoReceiveMsqData(bufMsg);
					}
					catch(...)
					{
					}
				}
			}
			catch(const LWPR::Exception& e)
			{
				fprintf(stderr, "%s\n", e.what());
			}
		}
	}
Exemplo n.º 8
0
int main(int argc, char** argv) {
    read_all_syn_files();
    FILE *input_file;
    Token* tk;
    uint32_t state;
    Automaton* a;
    a = automata_list + automaton_program_id;
    if (argc <= 1) {
        fprintf(stderr, "Usage:\n");
        fprintf(stderr, "  %s <input file>\n", argv[0]);
        return 1;
    }
    printf("Parsing file <%s>\n\n\n", argv[1]);
    initialize_lex();
    
    input_file = fopen(argv[1], "r");
    tk = NULL;
    state = a->initial_state;
    while (next_useful_token(input_file, &tk) && tk != NULL) {
        while(syn(tk, &a, &state) == 0) {
            //printf("-> %s, %d \n", a->name, state);
            // following without reading
        }
        //printf("-> %s, %d \n", a->name, state);
        //printf("read %s\n", tk->str);
    }      
    while(syn(tk, &a, &state));

    //print_identifiers();
    free_automata();
    freeLex();
    fclose(input_file);
    if (tk == NULL) 
        return 0;
    return 1;
}
Exemplo n.º 9
0
	void EventNetDispatch::MakeSocketDispatching(SOCKET_FD_T fd)
	{
		assert(fd >= 0);

		SOCKET_SELF_MSG_T msg;
		msg.nMsgType = SOCKET_SELF_MSG_ADD_FD;
		msg.nSocketFd = fd;

		Synchronized syn(m_MutexClient);
		LWPR::SOCKET_RET_TYPE_E nRet = Socket::WriteSocket(m_fdConnSelfClient, (const char*)&msg, sizeof(msg));
		if(nRet != LWPR::SOCKET_RET_OK)
		{
			// 信号发生时,会执行到这里
			LWPR::Socket::CloseSocket(fd);
		}
	}
Exemplo n.º 10
0
size_t I1::write( std::FILE* out )
{
    for( ConstSynIter itr = synRoots.begin(); itr != synRoots.end(); ++itr ) {
        //convert roots into offsets
        try {
            Synonym* syn( document->synonym( *itr ) );
            primary->addSynonym( syn->location() );
        }
        catch( Class1Error& e ) {
            printError( e.code );
        }
    }
    size_t written( primary->write( out ) );
    std::sort( secondary.begin(), secondary.end(), ptrLess< IndexItem* >() );
    for( IndexIter itr = secondary.begin(); itr != secondary.end(); ++itr )
        written += ( *itr )->write( out );
    return written;
}
Exemplo n.º 11
0
	void TimerThread::AddTimerRequest(WorkRequest* preq, int seconds)
	{
		if(preq != NULL)
		{
			struct timeval tv = {0};
			gettimeofday(&tv, NULL);

			TIMER_REQUEST_T timer = {0};
			timer.pRequest = preq;
			timer.nTimestamp = tv.tv_sec + seconds;

			{
				Synchronized syn(m_Mutex);
				m_TimerRequestList.push_back(timer);
			}

			Notify();
		}
	}
Exemplo n.º 12
0
    void
    connectionmanager::connect(thread t, index s_gid, targetindex target)
    {
        if (vm["model"].as<std::string>() == "tsodyks2") {
            const double delay = vm["delay"].as<double>();
            const double weight = vm["weight"].as<double>();
            const double U = vm["U"].as<double>();
            const double u = vm["u"].as<double>();
            const double x = vm["x"].as<double>();
            const double tau_rec = vm["tau_rec"].as<double>();
            const double tau_fac = vm["tau_fac"].as<double>();
            //TODO permute parameters
            tsodyks2 syn(delay, weight, U, u, x, tau_rec, tau_fac, target);

            ConnectorBase* conn = validate_source_entry( t, s_gid);
            ConnectorBase* c = add_connection<tsodyks2>( conn, syn );
            connections_[ t ].set( s_gid, c );
        }
        else {
            throw std::invalid_argument("synapse model unknown");
        }
    }
Exemplo n.º 13
0
int main(int argc, char *argv[])
{
    if(argc<3){
        cout<<"Modo de uso:"<<endl;
        cout<<"./AST fileIN fileOUT"<<endl;
    }
    else{
        File fp(argv[1], argv[2]);

        Lex *lex = new Lex();
        lex->startLex(fp);

        Syntactic syn(lex);
        syn.parser();
        fp.close();
        syn.show();

        Semantic sem;
        sem.parsing();
    }

    return 0;
}
Exemplo n.º 14
0
	void ThreadPool::ThreadWorker::Run()
	{
		// 所有线程数量
		AutomaticCount autoTotalThread(m_ThreadPool.m_nTotalThread);

		while(IsContinue())
		{
			WorkRequest* pReq = NULL;

			{
				// 空闲线程计数
				AutomaticCount autoIdleThread(m_ThreadPool.m_nIdleThread);
				m_ThreadPool.Wait();

				// 取请求
				Synchronized syn(m_ThreadPool.m_Mutex);
				ThreadPool::WorkRequestList::iterator it = m_ThreadPool.m_WorkRequestList.begin();
				if(it != m_ThreadPool.m_WorkRequestList.end())
				{
					pReq = *it;
					m_ThreadPool.m_WorkRequestList.pop_front();
				}
			}

			// 执行请求
			if(pReq != NULL)
			{
				pReq->DoWork();
			}

			// 调整线程池
			if(m_ThreadPool.IsNeededToCreateThread() || m_ThreadPool.IsNeededToDestroyThread())
			{
				m_ThreadPool.m_pThreadManage->Notify();
			}
		}
	}
Exemplo n.º 15
0
	void EventNetWorkThread::Run()
	{
		AutomaticCount autoTotalThread(m_EventNetDispatch.m_nTotalThread);

		while(IsContinue())
		{
			try
			{
				// 可读socket
				SOCKET_FD_T nReadySocket = -1;

				{
					// 空闲线程计数
					AutomaticCount autoIdleThread(m_EventNetDispatch.m_nIdleThread);

					// 加锁,获取可读的Socket(进入临界区)
					Synchronized syn(m_EventNetDispatch.m_MutexEvent);

					// 找一个可读socket,开始工作
					if(m_EventNetDispatch.m_listReadableSocket.size() > 0)
					{
						nReadySocket = m_EventNetDispatch.m_listReadableSocket.back();
						m_EventNetDispatch.m_listReadableSocket.pop_back();
					}

					// 如果没有可读socket,则select
					while(-1 == nReadySocket)
					{
						// 判断当前线程是否可以继续执行
						if(!m_EventNetDispatch.IsContinue())
						{
							return;
						}

						fd_set setReadableFd;
						memcpy(&setReadableFd, &m_EventNetDispatch.m_setActiveFd, sizeof(m_EventNetDispatch.m_setActiveFd));
						struct timeval tv = {0};
						tv.tv_sec = m_EventNetDispatch.m_EventNetOption.nHousekeepInterval;
						tv.tv_usec = 0;
						struct timeval *ptv = &tv;

						if(!m_EventNetDispatch.m_EventNetOption.bAllowDoHousekeep)
						{
							ptv = NULL;
						}

						int nCode = select(m_EventNetDispatch.m_fdMax + 1, &setReadableFd, NULL, NULL, ptv);
						// 有socket可读
						if(nCode > 0)
						{
							for(int i = 0; i <= m_EventNetDispatch.m_fdMax; i++)
							{
								if(FD_ISSET(i, &setReadableFd))
								{
									// 更新socket最后活跃时间
									m_EventNetDispatch.m_mapActiveFd[i] = time(NULL);

									// 处理新来连接
									if(i == m_EventNetDispatch.m_fdListen)
									{
										SOCKET_FD_T fd = LWPR::Socket::AcceptSocket(i);
										if(fd != -1)
										{
											// 如果新来的连接超过select支持的最大数,则CloseSocket
											if(fd >= FD_SETSIZE)
											{
												Socket::CloseSocket(fd);
											}
											else
											{
												FD_SET(fd, &m_EventNetDispatch.m_setActiveFd);
												m_EventNetDispatch.m_mapActiveFd[fd] = time(NULL);
												m_EventNetDispatch.m_fdMax = (fd > m_EventNetDispatch.m_fdMax) ? fd : m_EventNetDispatch.m_fdMax;
												if(m_EventNetDispatch.m_EventNetOption.bAllowDoRcvConnHandler)
												{
													try
													{
														m_EventNetDispatch.m_EventNetOption.pHandler->DoReceiveConnection(fd);
													}
													catch(...)
													{
													}
												}
											}
										}
									}
									// 处理自身连接,用来内部控制信息的传递
									else if(i == m_EventNetDispatch.m_fdConnSelfServer)
									{
										LWPR::Buffer buf;
										SOCKET_RET_TYPE_E res = Socket::ReadSocket(i, buf, sizeof(SOCKET_SELF_MSG_T));
										if(res == SOCKET_RET_OK)
										{
											SOCKET_SELF_MSG_T* pMsg = (SOCKET_SELF_MSG_T*)buf.Inout();

											switch(pMsg->nMsgType)
											{
											case SOCKET_SELF_MSG_ADD_FD:
												FD_SET(pMsg->nSocketFd, &m_EventNetDispatch.m_setActiveFd);
												m_EventNetDispatch.m_mapActiveFd[pMsg->nSocketFd] = time(NULL);
												break;
											case SOCKET_SELF_MSG_EXIT_THREAD:
												break;
											default:
												assert(0);
											}
										}
									}
									// 处理第一个可读socket
									else if(-1 == nReadySocket)
									{
										nReadySocket = i;
										FD_CLR(i, &m_EventNetDispatch.m_setActiveFd);
									}
									// 处理其余可读socket
									else
									{
										m_EventNetDispatch.m_listReadableSocket.push_back(i);
										FD_CLR(i, &m_EventNetDispatch.m_setActiveFd);
									}
								}
							}
						}
						// select 超时
						else if(nCode == 0)
						{
							// 检查不活跃的socket
							if(m_EventNetDispatch.m_EventNetOption.bAllowDoHousekeep)
							{
								for(int i = 0; i <= m_EventNetDispatch.m_fdMax; i++)
								{
									if(FD_ISSET(i, &m_EventNetDispatch.m_setActiveFd))
									{
										if(i == m_EventNetDispatch.m_fdListen)
										{
										}
										else if(i == m_EventNetDispatch.m_fdConnSelfServer)
										{
										}
										else
										{
											if((time(NULL) - m_EventNetDispatch.m_mapActiveFd[i]) >= m_EventNetDispatch.m_EventNetOption.nSocketExpiredTime)
											{
												if(m_EventNetDispatch.m_EventNetOption.bAllowDoCloseHandler)
												{
													try
													{
														m_EventNetDispatch.m_EventNetOption.pHandler->DoCloseExpiredSocket(i);
													}
													catch(...)
													{
													}
												}

												Socket::CloseSocket(i);
												FD_CLR(i, &m_EventNetDispatch.m_setActiveFd);
											}
										}
									}
								}
							}
						}
					} // end of while(-1 == nReadableSocket)
				} // end of Lock

				// 准备处理找到的连接
				SOCKET_RET_TYPE_E nRet = SOCKET_RET_OK;
				try
				{
					nRet = m_EventNetDispatch.m_EventNetOption.pHandler->DoReceiveNormalData(nReadySocket);
				}
				catch(...)
				{
					nRet = SOCKET_RET_FAILED;
				}

				switch(nRet)
				{
				case SOCKET_RET_FAILED:
				case SOCKET_RET_TIMEOUT:
					Socket::CloseSocket(nReadySocket);
					break;
				case SOCKET_RET_OK:
					m_EventNetDispatch.MakeSocketDispatching(nReadySocket);
					break;
				case SOCKET_RET_FREE:
					break;
				default:
					assert(0);
				}
			}
			catch(const LWPR::Exception& e)
			{
				fprintf(stderr, "%s\n", e.what());
			}
		}
	}
Exemplo n.º 16
0
    /** \fn help(int argc, char *const argv[], po::variables_map& vm)
        \brief Helper using boost program option to facilitate the command line manipulation
        \param argc number of argument from the command line
        \param argv the command line from the driver or external call
        \param vm encapsulate the command line
        \return error message from mapp::mapp_error
     */
    int model_help(int argc, char* const argv[], po::variables_map& vm)
    {
        po::options_description desc("Allowed options");
        desc.add_options()
        ("help", "produce help message")
        ("models", "list available connection models")
        ("connector", "encapsulate connections in connector")
        ("nConnections", po::value<int>()->default_value(1), "number of incoming(manager)/outgoing(connector) connections")
        ("nDetectors", po::value<int>()->default_value(1), "number of spike detectors")


        ("manager", "encapsulate connectors in connection manager")
        ("nNeurons", po::value<int>()->default_value(1), "number of neurons")
        ("min_delay", po::value<int>()->default_value(2), "min delay of simulation")
        ("nSpikes", po::value<int>()->default_value(2), "total number of spikes")
        ("nGroups", po::value<int>()->default_value(1), "theoretical number of threads")
        ("size", po::value<int>()->default_value(1), "theoretical number of ranks")
        ("rank", po::value<int>()->default_value(0), "theoretical rank id")
        ("thread", po::value<int>()->default_value(0), "theoretical thread id")

        ("model", po::value<std::string>()->default_value("tsodyks2"), "connection model")

        // tsodyks2 parameters
        // synapse parameters are not checked
        ("delay", po::value<double>()->default_value(1.0), "delay")
        ("weight", po::value<double>()->default_value(1.0), "weight")
        ("U", po::value<double>()->default_value(0.5), "U")
        ("u", po::value<double>()->default_value(0.5), "u")
        ("x", po::value<double>()->default_value(1), "x")
        ("tau_rec", po::value<double>()->default_value(800.0), "tau_rec")
        ("tau_fac", po::value<double>()->default_value(0.0), "tau_fac")
        //memory pool for hte connector
        ("pool", po::value<bool>()->default_value(false), "pool memory manager")

        // simulation parameters
        ("dt", po::value<double>()->default_value(0.1), "time between spikes")
        ("iterations", po::value<int>()->default_value(1), "number of iterations (spikes)");


        po::store(po::parse_command_line(argc, argv, desc), vm);
        po::notify(vm);

        if (vm.count("manager")) {
            if (vm["nGroups"].as<int>() <= vm["thread"].as<int>()) {
                std::cout << "Error: thread has to be smaller than number of threads" << std::endl;
                return mapp::MAPP_BAD_DATA;
            }
            if (vm["size"].as<int>() <= vm["rank"].as<int>()) {
                std::cout << "Error: rank has to be smaller than number of ranks" << std::endl;
                return mapp::MAPP_BAD_DATA;
            }
            if (vm["min_delay"].as<int>() <= 0) {
                std::cout << "Error: min_delay has to be greater than 0" << std::endl;
                return mapp::MAPP_BAD_DATA;
            }
            if (vm["nSpikes"].as<int>() <= 0) {
                std::cout << "Error: nSpikes has to be greater than 0" << std::endl;
                return mapp::MAPP_BAD_DATA;
            }
            if (vm["nNeurons"].as<int>() <= 0) {
                std::cout << "Error: nNeurons has to be greater than 0" << std::endl;
                return mapp::MAPP_BAD_DATA;
            }
        }
        else if (vm.count("connector")) {
            if (vm["nConnections"].as<int>() <= 0) {
                std::cout << "Error: Number of connections per connector has to be greater than 0" << std::endl;
                return mapp::MAPP_BAD_DATA;
            }
        }
        else {
            if (vm["nConnections"].as<int>() != 1) {
                std::cout << "Error: Encapsulate connections in connector to enable multiple connections" << std::endl;
                return mapp::MAPP_BAD_DATA;
            }
        }

        //check for valid synapse model & parameters
        if (vm["model"].as<std::string>() == "tsodyks2") {
            const double delay = vm["delay"].as<double>();
            const double weight = vm["weight"].as<double>();
            const double U = vm["U"].as<double>();
            const double u = vm["u"].as<double>();
            const double x = vm["x"].as<double>();
            const double tau_rec = vm["tau_rec"].as<double>();
            const double tau_fac = vm["tau_fac"].as<double>();

            try {
                short lid = 0; // only one node
                spikedetector sd;
                tsodyks2 syn(delay, weight, U, u, x, tau_rec, tau_fac, lid);
            }
            catch (std::invalid_argument& e) {
                std::cout << "Error in model parameters: " << e.what() << std::endl;
                return mapp::MAPP_BAD_DATA;
            }
        }
        /* else if ( more models ) */
        else {
            std::cout << "Error: Selected connection model is  unknown" << std::endl;
            return mapp::MAPP_BAD_DATA;
        }
        //check for valid dt
        if (vm["dt"].as<double>() < 0.1) {
            std::cout << "Error: Time between spikes has to be bigger than 0.1" << std::endl;
            return mapp::MAPP_BAD_DATA;
        }
        //check for valid iterations
        if (vm["iterations"].as<int>() < 1) {
            std::cout << "Error: Number of iterations has to be a greater than 0" << std::endl;
            return mapp::MAPP_BAD_DATA;
        }
        //list available synapse models
        if (vm.count("models")){
            std::cout << "   Following connection models are available: \n";
            std::cout << "       name           list of accepted parameters\n";
            std::cout << "       tsodyks2       delay, weight, U, u, x, tau_rec, tau_fac\n";
                std::cout << "";
                return mapp::MAPP_USAGE;
            }

        if (vm.count("help")){
            std::cout << desc;
            return mapp::MAPP_USAGE;
        }
        return mapp::MAPP_OK;
    }
Exemplo n.º 17
0
net::ClientSocket::ClientSocket(int af, int protocol, bool trace, int local_port, const struct sockaddr_in * name, int namelen) :
    Socket(af, protocol, trace) {

    local_addr.sin_family = AF_INET;
    local_addr.sin_port = htons(local_port);
    local_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    // This is dumb, but the router requires that the client socket binds to a static port.
    if (SOCKET_ERROR == ::bind(winsocket, (const sockaddr*)&local_addr, sizeof(local_addr))) {
        traceError(WSAGetLastError(), "SOCKET_ERROR while binding");
        throw new SocketException("Could not bind client socket!");
    }

    dest = *name;
    dest_len = namelen;

    // Three-way handshake.
    // Step 1: Send the sequence number to the server
    dgram _syn;
    syn(_syn);
    if (trace) tracefile << "CLIENT: Sending SYN message with Seq No " << _syn.seqno << "\n";
    int sentbytes = send_dgram(_syn);
    if (sentbytes == SOCKET_ERROR) {
        traceError(WSAGetLastError(), "SOCKET_ERROR while sendto");
        throw new SocketException("Could not send SYN");
    }

    sndr_seqno = nextSeqNo(_syn.seqno);

    // Step 2: Wait for SYNACK
    if (trace) tracefile << "CLIENT: Waiting for SYNACK message\n";
    while (true) {

        dgram _synack;
        int recvbytes = recv_dgram(_synack);
        if (recvbytes == SOCKET_ERROR) {
            if (WSAGetLastError() == WSAETIMEDOUT) {
                // Timed out, re-send syn
                send_dgram(_syn);
                continue; // Timed out, try again
            }
            // Some other error occured
            traceError(WSAGetLastError(), "SOCKET_ERROR while recv");
            throw new SocketException("Could not receive SYNACK message from server!");
        }
        if (recvbytes < sizeof(dgram)) continue; // Throw away unexpected packet
        if (_synack.type != SYNACK) continue; //Throw away unexpected packet

        if (trace) tracefile << "CLIENT: Received SYNACK with Seq No " << _synack.seqno << "\n";

        recv_seqno = nextSeqNo(_synack.seqno);

        // Step 3: Send ACK
        if (trace) tracefile << "CLIENT: Sending ACK in response to SYNACK\n";
        // Simulate loss of packet!
        send_ack(_synack);

        break;
    }
    if (trace) {
        tracefile << "CLIENT: Connection established!\n";
        tracefile << "Next sequence numbers will be:\n";
        tracefile << "  Client: " << sndr_seqno << "\n";
        tracefile << "  Server: " << recv_seqno << "\n";
    }
}
Exemplo n.º 18
0
    /** \fn help(int argc, char *const argv[], po::variables_map& vm)
        \brief Helper using boost program option to facilitate the command line manipulation
        \param argc number of argument from the command line
        \param argv the command line from the driver or external call
        \param vm encapsulate the command line
        \return error message from mapp::mapp_error
     */
    int model_help(int argc, char* const argv[], po::variables_map& vm, subpragram& subprog)
    {
        std::string subprog_str;
        if (argc>1)
            subprog_str = argv[1];

        bool use_mpi = false;
        bool use_manager = false;
        bool use_connector = false;
        bool use_connection = false;

        if (argc >= 2 && subprog_str == "connection") {
            subprog = connection;
            use_connection = true;
        }
        else if (argc >= 2 && subprog_str == "connector") {
            subprog = connector;
            use_connector = true;
        }
        else if (argc >= 2 && subprog_str == "manager") {
            subprog = manager;
            use_manager = true;
        }
        else if (argc >= 2 && subprog_str == "distributed") {
            subprog = distributed;
            use_mpi = true;
        }
        else {
            std::cout << "subprogram could not be detected. Use --help for information" << std::endl;
        }
        po::options_description desc("Allowed options");

        desc.add_options()
        ("help", "produce help message");

        if (use_manager || use_mpi || use_connector || use_connection)
        desc.add_options()
        ("models", "list available connection models")
        ("model", po::value<std::string>()->default_value("tsodyks2"), "connection model")
        // tsodyks2 parameters
        ("delay", po::value<double>()->default_value(1.0), "delay")
        ("weight", po::value<double>()->default_value(1.0), "weight")
        ("U", po::value<double>()->default_value(0.5), "U")
        ("u", po::value<double>()->default_value(0.5), "u")
        ("x", po::value<double>()->default_value(1), "x")
        ("tau_rec", po::value<double>()->default_value(800.0), "tau_rec")
        ("tau_fac", po::value<double>()->default_value(0.0), "tau_fac")
        ("nSpikes", po::value<int>()->default_value(2), "total number of spikes");

        if (use_manager || use_mpi || use_connector)
            desc.add_options()
            ("pool", po::value<bool>()->default_value(false), "pool memory manager") //memory pool for hte connector
            ("fanout", po::value<int>()->default_value(1), "number of incoming(manager)/outgoing(connector) connections");

        if (use_manager || use_mpi)
            desc.add_options()
            ("min_delay", po::value<int>()->default_value(2), "min delay of simulation")
            ("nThreads", po::value<int>()->default_value(1), "number of threads")
            ("nProcesses", po::value<int>()->default_value(1), "number of ranks")
            ("simtime", po::value<int>()->default_value(4), "simulation time")
            ("nNeurons", po::value<int>()->default_value(10), "number of neurons");

        if (use_mpi)
            desc.add_options()
            ("run", po::value<std::string>()->default_value("/usr/bin/mpiexec"), "mpi run command")
            ("rate", po::value<double>()->default_value(-1), "firing rate per neuron");

        if (use_manager)
            desc.add_options()
            ("manager", "encapsulate connectors in connection manager")
            ("rank", po::value<int>()->default_value(0), "fake rank id")
            ("thread", po::value<int>()->default_value(0), "fake thread id");

        if (use_connector)
            desc.add_options()
            ("connector", "encapsulate connections in connector");

        po::store(po::parse_command_line(argc, argv, desc), vm);
        po::notify(vm);


        //check for all
        if (use_mpi || use_manager || use_connector || use_connection)
        if (vm["nSpikes"].as<int>() <= 0 ) {
            std::cout << "Error: nSpikes has to be greater than 0" << std::endl;
            return mapp::MAPP_BAD_DATA;
        }
        //check for multiple
        if (use_mpi || use_manager || use_connector) {
            if (vm["fanout"].as<int>() <= 0) {
                std::cout << "Error: Number of connections has to be greater than 0" << std::endl;
                return mapp::MAPP_BAD_DATA;
            }
        }

        //check for multiple
        if (use_mpi || use_manager) {
            if (vm["nThreads"].as<int>() <= 0) {
                std::cout << "Error: nThreads has to be greater than 0" << std::endl;
                return mapp::MAPP_BAD_DATA;
            }
            if (vm["nProcesses"].as<int>() <= 0) {
                std::cout << "Error: nProcesses has to be greater than 0" << std::endl;
                return mapp::MAPP_BAD_DATA;
            }
            if (vm["min_delay"].as<int>() <= 0) {
                std::cout << "Error: min_delay has to be greater than 0" << std::endl;
                return mapp::MAPP_BAD_DATA;
            }
            if (vm["simtime"].as<int>() <= 0 || (vm["simtime"].as<int>() % vm["min_delay"].as<int>()) != 0) {
                std::cout << "Error: simtime has to be a multiple of min_delay" << std::endl;
                return mapp::MAPP_BAD_DATA;
            }
            if (vm["nNeurons"].as<int>() <= 0) {
                std::cout << "Error: nNeurons has to be greater than 0" << std::endl;
                return mapp::MAPP_BAD_DATA;
            }
        }

        if (use_manager) {
            if (vm["nProcesses"].as<int>() <= vm["rank"].as<int>()) {
                std::cout << "Error: rank has to be smaller than nProcesses" << std::endl;
                return mapp::MAPP_BAD_DATA;
            }
            if (vm["nThreads"].as<int>() <= vm["thread"].as<int>()) {
                std::cout << "Error: thread has to be smaller than nThreads" << std::endl;
                return mapp::MAPP_BAD_DATA;
            }
        }

        //check for valid synapse model & parameters
        if (use_mpi || use_manager || use_connector || use_connection)
        if (vm["model"].as<std::string>() == "tsodyks2") {
            const double delay = vm["delay"].as<double>();
            const double weight = vm["weight"].as<double>();
            const double U = vm["U"].as<double>();
            const double u = vm["u"].as<double>();
            const double x = vm["x"].as<double>();
            const double tau_rec = vm["tau_rec"].as<double>();
            const double tau_fac = vm["tau_fac"].as<double>();

            try {
                short lid = 0; // only one node
                spikedetector sd;
                tsodyks2 syn(delay, weight, U, u, x, tau_rec, tau_fac, lid);
            }
            catch (std::invalid_argument& e) {
                std::cout << "Error in model parameters: " << e.what() << std::endl;
                return mapp::MAPP_BAD_DATA;
            }
        }
        /* else if ( more models ) */
        else {
            std::cout << "Error: Selected connection model is  unknown" << std::endl;
            return mapp::MAPP_BAD_DATA;
        }


        //list available synapse models
        if (use_mpi || use_manager || use_connector || use_connection)
        if (vm.count("models")){
            std::cout << "   Following connection models are available: \n";
            std::cout << "       name           list of accepted parameters\n";
            std::cout << "       tsodyks2       delay, weight, U, u, x, tau_rec, tau_fac\n";
                std::cout << "";
                return mapp::MAPP_USAGE;
            }

        if (vm.count("help")){
            if (use_manager || use_mpi || use_connector || use_connection)
                std::cout << desc;
            else
                std::cout << "chose subprogram: connection, connector, manager or distributed" << std::endl;
            return mapp::MAPP_USAGE;
        }

        if (use_manager || use_mpi || use_connector || use_connection){
            return mapp::MAPP_OK;
        }
        else{
            return mapp::MAPP_USAGE;
        }
    }
Exemplo n.º 19
0
    /** \fn content(po::variables_map const& vm)
        \brief Execute the NEST synapse Miniapp.
        \param vm encapsulate the command line and all needed informations
     */
    void model_content(po::variables_map const& vm, subpragram& subprog)
    {
        int nSpikes = vm["nSpikes"].as<int>();

        bool use_connection = subprog == connection;
        bool use_connector = subprog == connector;
        bool use_manager = subprog == manager;
        bool use_mpi = subprog == distributed;

        if (use_mpi) {
            std::stringstream command;

            std::string path = helper_build_path::mpi_bin_path();

            size_t nthread = vm["nThreads"].as<int>();
            std::string mpi_run = vm["run"].as<std::string>();
            size_t nproc = vm["nProcesses"].as<int>();

            //command line args

            size_t ncells = vm["nNeurons"].as<int>();
            size_t fan = vm["fanout"].as<int>();
            size_t mindelay = vm["min_delay"].as<int>();
            size_t simtime = vm["simtime"].as<int>();
            
            double rate = vm["rate"].as<double>();
            if (rate>=0) {
                nSpikes = rate * ncells * simtime;
                std::cout << "WARNING: nSpikes is overwritten by rate. new value of nSpikes=" << nSpikes << std::endl; 
            }
            std::string syn_model = vm["model"].as<std::string>();
            double syn_delay = vm["delay"].as<double>();
            double syn_weight = vm["weight"].as<double>();
            double syn_U = vm["U"].as<double>();
            double syn_u = vm["u"].as<double>();
            double syn_x = vm["x"].as<double>();
            double syn_tau_rec = vm["tau_rec"].as<double>();
            double syn_tau_fac = vm["tau_fac"].as<double>();
            bool pool = vm["pool"].as<bool>();

            std::string exec ="nest_dist_exec";

            command << "OMP_NUM_THREADS=" << nthread << " " <<
                mpi_run <<" -n "<< nproc << " " << path << exec <<
                " " << nthread << " " << simtime << " " <<
                ncells << " " << fan << " " <<
                nSpikes << " " << mindelay << " " <<
                syn_model << " " << syn_delay << " " <<
                syn_weight << " " << syn_U << " " <<
                syn_u << " " << syn_x << " " <<
                syn_tau_rec << " " << syn_tau_fac << " " << pool;

            std::cout<< "Running command " << command.str() <<std::endl;
            system(command.str().c_str());

            return;
        }

        boost::chrono::system_clock::duration delay;


        if ( use_manager ) {
            const bool pool = vm["pool"].as<bool>();
            const int thrd = vm["thread"].as<int>(); // thead_num
            const int min_delay=vm["min_delay"].as<int>();
            const int simtime = vm["simtime"].as<int>();
            const int nthreads = vm["nThreads"].as<int>();
            const int rank = vm["rank"].as<int>();
            const int size = vm["nProcesses"].as<int>();
            const int ncells = vm["nNeurons"].as<int>();
            const int fanout = vm["fanout"].as<int>();

            //setup allocator
            nest::pool_env penv(nthreads, pool);

            //build connection manager
            connectionmanager cm(vm);
            environment::continousdistribution neuro_dist(size, rank, ncells);
            environment::presyn_maker presyns(fanout, environment::fixedoutdegree);
            presyns(thrd, &neuro_dist);

            //preallocate vector for results
            std::vector<spikedetector> detectors(ncells);
            std::vector<targetindex> detectors_targetindex(ncells);

            // register spike detectors
            for(unsigned int i=0; i < ncells; ++i) {
                detectors[i].set_lid(i);    //give nodes a local id
                //scheduler stores pointers to the spike detectors
                detectors_targetindex[i] = scheduler::add_node(&detectors[i]);  //add them to the scheduler
            }

            environment::continousdistribution neuro_vp_dist(nthreads, thrd, &neuro_dist);
            build_connections_from_neuron(thrd, neuro_vp_dist, presyns, detectors_targetindex, cm);

            // generate all events for one thread
            environment::event_generator generator(1);
            double mean = static_cast<double>(simtime) / static_cast<double>(nSpikes);
            double lambda = 1.0 / static_cast<double>(mean * size);

            //all events available
            environment::continousdistribution event_dist(1, 0, ncells);

            environment::generate_poisson_events(generator.begin(),
                             simtime, nthreads, rank, size, lambda, &event_dist);

            const unsigned int stats_generated_spikes = generator.get_size(0);
            int t = 0;
            spikeevent se;
            boost::chrono::system_clock::time_point start = boost::chrono::system_clock::now();
            while (t<simtime) {
                t+=min_delay;
                // get events from all threads
                while(generator.compare_top_lte(0, t)) {
                    environment::gen_event g = generator.pop(0);
                    index nid = g.first;
                    se.set_stamp( Time(g.second) ); // in Network::send< SpikeEvent >
                    se.set_sender_gid( nid ); // in Network::send< SpikeEvent >
                    cm.send(thrd, nid, se); //send spike
                }
            }
            delay = boost::chrono::system_clock::now() - start;
            std::cout << "Connection manager simulated" << std::endl;
            std::cout << "Statistics:" << std::endl;
            std::cout << "\tgenerated spikes: " << stats_generated_spikes << std::endl;
            int recvSpikes=0;
            for (unsigned int i=0; i<detectors.size(); i++)
                recvSpikes+=detectors[i].spikes.size();
            std::cout << "\trecv spikes: " << recvSpikes << std::endl;

            std::cout << "\tEvents left:" << std::endl;

            while (!generator.empty(0)) {  // thread 0
                environment::gen_event g = generator.pop(0); // thread 0
                std::cout << "Event " << g.first << " " << g.second << std::endl;
            }
        }
        else if ( use_connector ) {
            const bool pool = vm["pool"].as<bool>();
            const double syn_delay = vm["delay"].as<double>();
            const double syn_weight = vm["weight"].as<double>();
            const double syn_U = vm["U"].as<double>();
            const double syn_u = vm["u"].as<double>();
            const double syn_x = vm["x"].as<double>();
            const double syn_tau_rec = vm["tau_rec"].as<double>();
            const double syn_tau_fac = vm["tau_fac"].as<double>();

            const int fanout = vm["fanout"].as<int>();

            //setup allocator
            nest::pool_env penv(1, pool); // use one thread

            //preallocate vector for results
            std::vector<spikedetector> detectors(fanout);
            std::vector<targetindex> detectors_targetindex(fanout);
            for(unsigned int i=0; i < fanout; ++i) {
                detectors[i].set_lid(i);    //give nodes a local id
                //scheduler stores pointers to the spike detectors
                detectors_targetindex[i] = scheduler::add_node(&detectors[i]);  //add them to the scheduler
            }

            //create connector ptr
            //has to be set to NULL (check add_connection(..))
            ConnectorBase* conn = NULL;

            //build connector
            for(unsigned int i=0; i < fanout; ++i) {
                //TODO permute parameters
                tsodyks2 synapse(syn_delay, syn_weight, syn_U, syn_u, syn_x, syn_tau_rec, syn_tau_fac, detectors_targetindex[i%fanout]);
                conn = add_connection(conn, synapse); //use static function from connectionmanager
            }

            //create a few events
            std::vector< spikeevent > events(nSpikes);
            for (unsigned int i=0; i<nSpikes; i++) {
                Time t(i*10.0);
                events[i].set_stamp( t ); // in Network::send< SpikeEvent >
                events[i].set_sender( NULL ); // in Network::send< SpikeEvent >
            }

            boost::chrono::system_clock::time_point start = boost::chrono::system_clock::now();
            for (unsigned int i=0; i<nSpikes; i++) {
                conn->send(events[i]); //send spike
            }

            delay = boost::chrono::system_clock::now() - start;
            std::cout << "Connector simulated with " << fanout << " connections" << std::endl;
        }
        else {
            const double syn_delay = vm["delay"].as<double>();
            const double syn_weight = vm["weight"].as<double>();
            const double syn_U = vm["U"].as<double>();
            const double syn_u = vm["u"].as<double>();
            const double syn_x = vm["x"].as<double>();
            const double syn_tau_rec = vm["tau_rec"].as<double>();
            const double syn_tau_fac = vm["tau_fac"].as<double>();

            //preallocate vector for results
            spikedetector detector;
            // register spike detectors
            targetindex detector_targetindex = scheduler::add_node(&detector);  //add them to the scheduler

            tsodyks2 syn(syn_delay, syn_weight, syn_U, syn_u, syn_x, syn_tau_rec, syn_tau_fac, detector_targetindex);

            //create a few events
            std::vector< spikeevent > events(nSpikes);
            for (unsigned int i=0; i<nSpikes; i++) {
                Time t(i*10.0);
                events[i].set_stamp( t ); // in Network::send< SpikeEvent >
                events[i].set_sender( NULL ); // in Network::send< SpikeEvent >
            }

            double t_lastspike = 0.0;
            boost::chrono::system_clock::time_point start = boost::chrono::system_clock::now();
            for (unsigned int i=0; i<nSpikes; i++) {
                syn.send(events[i], t_lastspike); //send spike
                t_lastspike += 0.2; // dt - time between spiks
            }
            delay = boost::chrono::system_clock::now() - start;
            std::cout << "Single connection simulated" << std::endl;
            std::cout << "Last weight " << detector.spikes.back().get_weight() << std::endl;
        }

        std::cout << "Duration: " << delay << std::endl;

    }