Ejemplo n.º 1
0
/*===========================================================================*/
void ExtractEdges::calculate_connections( const kvs::StructuredVolumeObject* volume )
{
    const size_t line_size = volume->numberOfNodesPerLine();
    const size_t slice_size = volume->numberOfNodesPerSlice();
    const Vector3ui resolution( volume->resolution() );
    const size_t nedges =
        3 * ( resolution.x() - 1 ) * ( resolution.y() - 1 ) * ( resolution.z() - 1 ) +
        2 * ( resolution.x() - 1 ) * ( resolution.y() - 1 ) +
        2 * ( resolution.y() - 1 ) * ( resolution.z() - 1 ) +
        2 * ( resolution.z() - 1 ) * ( resolution.x() - 1 ) +
        resolution.x() - 1 + resolution.y() - 1 + resolution.z() - 1;

    kvs::ValueArray<kvs::UInt32> connections( 2 * nedges );
    kvs::UInt32* connection = connections.data();

    kvs::UInt32 volume_vertex = 0;
    kvs::UInt32 connection_index = 0;
    for ( size_t z = 0; z < resolution.z(); ++z )
    {
        for ( size_t y = 0; y < resolution.y(); ++y )
        {
            for ( size_t x = 0; x < resolution.x(); ++x )
            {
                if ( x != resolution.x() - 1 )
                {
                    connection[ connection_index++ ] = volume_vertex;
                    connection[ connection_index++ ] = volume_vertex + 1;
                }

                if ( y != resolution.y() - 1 )
                {
                    connection[ connection_index++ ] = volume_vertex;
                    connection[ connection_index++ ] = volume_vertex + line_size;
                }

                if ( z != resolution.z() - 1 )
                {
                    connection[ connection_index++ ] = volume_vertex;
                    connection[ connection_index++ ] = volume_vertex + slice_size;
                }

                ++volume_vertex;
            }
        }
    }

    SuperClass::setConnections( connections );
}
Ejemplo n.º 2
0
    void
    Port::thaw ( void )
    {
//        DMESSAGE( "Thawing port %s", _name );

        activate();
        
        if ( _connections )
        {
            connections( _connections );
            
            free( _connections );

            _connections = NULL;
        }
    }
Ejemplo n.º 3
0
Archivo: daemon.cpp Proyecto: spito/dp
void Daemon::connecting( InputMessage &message, Channel channel ) {
    NOTE();

    OutputMessage response( MessageType::Control );
    response.tag( Code::Refuse );

    int peerId;
    std::string peerName;
    Address peerAddress;

    message >> peerId >> peerName >> peerAddress;
    channel->receive( message );

    if ( _state != State::FormingGroup ) {
        channel->send( response );
        return;
    }

    Channel masterLine = connectLine( peerAddress, LineType::Master );
    if ( masterLine ) {
        Line peer = std::make_shared< Peer >(
            peerId,
            std::move( peerName ),
            peerAddress.value(),
            std::move( masterLine ),
            channels()
        );

        bool ok = true;

        for ( int i = 0; i < channels(); ++i ) {
            Channel dataLine = connectLine( peerAddress, LineType::Data, i );
            if ( !dataLine ) {
                ok = false;
                break;
            }
            peer->openDataChannel( std::move( dataLine ), i );
        }

        if ( ok ) {
            connections().lockedInsert( peerId, std::move( peer ) );
            response.tag( Code::OK );
        }
    }

    channel->send( response );
}
Ejemplo n.º 4
0
int main(int argc, char **argv)
{
	int id1, id2, errs=0;

	if (argc < 3) {
		fprintf(stderr, "Usage: %s Place1 Place2\n", argv[0]);
		exit(1);
	}

	// convert args to place IDs
	id1 = (strlen(argv[1]) == 2) ? abbrevToID(argv[1]) : nameToID(argv[1]);
	id2 = (strlen(argv[1]) == 2) ? abbrevToID(argv[2]) : nameToID(argv[2]);

	// check place validity
	if (id1 == NOWHERE) {
		errs++;
		fprintf(stderr, "Invalid place name: %s\n", argv[1]);
	}
	if (id2 == NOWHERE) {
		errs++;
		fprintf(stderr, "Invalid place name: %s\n", argv[2]);
	}
	if (errs > 0) exit(1);

	Map europe;
	europe = newMap();

	// check for direct connection
    Transport t[NUM_TRANSPORT];  int i, n;

	printf("Between %s and %s ...\n", idToName(id1), idToName(id2));
	n = connections(europe, id1, id2, t);
	if (n == 0)
		printf("No direct connection\n");
	else {
		for (i = 0; i < n; i++) {
			switch (t[i]) {
			case ROAD: printf("Road connection\n"); break;
			case RAIL: printf("Rail connection\n"); break;
			case BOAT: printf("Boat connection\n"); break;
			default:   printf("Weird connection\n"); break;
			}
		}
	}
	return 0;
}
Ejemplo n.º 5
0
bool MetaDataBase::isSlotUsed( QObject *o, const QCString &slot )
{
    setupDataBase();
    MetaDataBaseRecord *r = db->find( (void*)o );
    if ( !r ) {
        qWarning( "No entry for %p (%s, %s) found in MetaDataBase",
                  o, o->name(), o->className() );
        return false;
    }

    QValueList<Connection> conns = connections( o );
    for ( QValueList<Connection>::Iterator it = conns.begin(); it != conns.end(); ++it ) {
        if ( (*it).slot == slot )
            return true;
    }
    return false;
}
Ejemplo n.º 6
0
/**
 *
 * Destroys this connection manager
 *
 * @return void
 */
DatabaseConnectionManager::~DatabaseConnectionManager()
{
    DatabaseConnection *connection;
    bool waiting = true;

    while (waiting) {

        // Our default state is not waiting
        waiting = false;

        Connections connections(this->connections);
        for (Connections::const_iterator it = connections.begin();
                it != connections.end(); ++it) {

            connection = it->first;

            if (connection->isStopping()) {

                // Wait for the connection to finish
                connection->join();

                // Remove from collection
                this->connections.erase(connection);

                // Free memory
                if (connection != mainConnection) {
                    delete connection;
                }
            } else {

                // Ask the connection to stop running
                connection->stop(false);

                // This connection may not be finished yet
                waiting = true;
            }
        }
    }

    delete this->mainConnection;

    #ifdef TRACK_POINTERS
    rDebug << "DatabaseConnectionManager::destroy" << this;
    #endif
}
Ejemplo n.º 7
0
void Event::remove_outgoing_connection (Event* outgoing)
{
	PROFILER(SCRIPTING);
	
    if (_connection_index == 0)
        return;
    
    std::vector<Event*> &outgoing_ref = connections()._outgoing;

    auto i = std::find(outgoing_ref.begin(), outgoing_ref.end(), outgoing);
	if (i != outgoing_ref.end()) {
		owner()->outgoing_event_was_disconnected(this, outgoing);

		outgoing_ref.erase(i);
		outgoing->remove_incoming_connection(this);
    }
	
}
Ejemplo n.º 8
0
Edit::Edit(QWidget *parent, bool usesClear, QString standard, int maximumLetters) : QLineEdit(parent)
{
    button = new Label(parent);
    button->hide();

    valueStandart = standard;
    this->setText(valueStandart);
    this->setToolTip(valueStandart);

#if defined(Q_WS_X11)
    {
        QFont f("Sans Serif", 6);
        this->setFont(f);
    }
#endif

#if defined(Q_WS_WIN)
    {
        QFont f("MS Shell Dlq 2", 9);
        this->setFont(f);
    }
#endif

    if(usesClear)
    {
        button->setToolTip(tr("Limpar Campo"));
        button->setCursor(Qt::PointingHandCursor);
        connect(button,SIGNAL(onClick()),this,SLOT(Clear()));
        button->setPixmap(QPixmap(url_clear));
        useClear = true;
    }

    this->setMaxLength(maximumLetters);

    connections();

    setUpperCase(false);

    this->installEventFilter(this);

    hasNext = false;

    setAutomaticallyNextComponent(false);
}
Ejemplo n.º 9
0
void TCPClient::handleConnectionBindResponse(const stun::Message& response)
{
	TraceL << "ConnectionBind success response" << endl;	

	auto transaction = reinterpret_cast<stun::Transaction*>(response.opaque);
	auto req = reinterpret_cast<RelayConnectionBinding*>(transaction->socket->opaque);
	
	auto conn = connections().get(req->peerAddress, nullptr);
	if (!conn) {
		assert(0);
		return;
	}
	
	// Data will now be transferred as-is to and from the peer.
	conn->Recv += sdelegate(this, &TCPClient::onRelayDataReceived);
	_observer.onRelayConnectionCreated(*this, conn, req->peerAddress);

	TraceL << "ConnectionBind success response: OK" << endl;
}
Ejemplo n.º 10
0
Archivo: IMGDock.C Proyecto: HeyJJ/ball
	bool IMGDock::findUnfrozenFragments(int fragment, set<int> frozen_fragments, set<int>& processed_fragments)
	{
		processed_fragments.insert(fragment);

		bool is_frozen = (frozen_fragments.find(fragment)!=frozen_fragments.end());
		bool is_connected_to_frozen_frag = 0;

		vector<StaticLigandFragment::Connection>& connections((*scoring_function_->getStaticLigandFragments())[fragment]->connections);

		for (Size j = 0; j < connections.size(); j++)
		{
			int neighbor_fragment = connections[j].fragment->ID;

			// add rotation-axis information only if the neighboring fragment has not been visited before and the neighboring fragment is not located within a frozen part of the ligand
			if (processed_fragments.find(neighbor_fragment) != processed_fragments.end())
			{
				continue;
			}
			if (findUnfrozenFragments(neighbor_fragment, frozen_fragments, processed_fragments))
			{
				is_connected_to_frozen_frag = 1;
				continue;
			}

			// allow the *neighboring* fragment to rotate around the bond connecting it this fragment
			vector<int> v(2);
			int nb_bond_id = 0;
			vector<StaticLigandFragment::Connection>& nb_connections((*scoring_function_->getStaticLigandFragments())[fragment]->connections);
			for (Size b = 0; b < nb_connections.size(); b++)
			{
				if (nb_connections[b].fragment->ID == fragment)
				{
					nb_bond_id = b;
					break;
				}
			}
			v[0] = neighbor_fragment; // id of the neighboring fragment
			v[1] = nb_bond_id; // id of bond of neighboring fragment
			bond_information_.push_back(v);
		}

		return (is_connected_to_frozen_frag || is_frozen) ;
	}
Ejemplo n.º 11
0
Archivo: Plug.cpp Proyecto: UIKit0/DT3
void PlugBase::remove_incoming_connection	(void)
{
	PROFILER(SCRIPTING);

    if (_connection_index == 0)
        return;
    
    PlugBase *&incoming_ref = connections()._incoming;

	// Disconnect old node
	if (incoming_ref) {

        //
        // Lock this owner and the incoming owner
        //
        
        std::unique_lock<std::recursive_mutex> lock_this(owner()->lock(),std::try_to_lock);
        std::unique_lock<std::recursive_mutex> lock_incoming(incoming_ref->owner()->lock(),std::try_to_lock);
        
        DTboolean lock_this_status = lock_this.owns_lock();
        DTboolean lock_incoming_status = lock_incoming.owns_lock();
        
        while (!lock_this_status || !lock_incoming_status) {
            if (lock_this_status)       lock_this.unlock();
            if (lock_incoming_status)   lock_incoming.unlock();
        
            lock_this_status = lock_this.owns_lock();
            lock_incoming_status = lock_incoming.owns_lock();
        }

        //
        // Do modifications
        //

        PlugBase *temp = incoming_ref;
        incoming_ref = NULL;
    
		owner()->incoming_plug_was_disconnected(temp, this);
		temp->remove_outgoing_connection(this);
	}
	
}
  void benchmark_connect_disconnect()
{
  static const unsigned num_connections = 1000000;
  std::vector<typename connection_type<Signal>::type> connections(num_connections);

  Signal signal;
  std::cout << "connecting " << num_connections << " connections then disconnecting: ";
  unsigned n;
  {
    boost::progress_timer timer;
    for(n = 0; n < num_connections; ++n)
    {
      connections.at(n) = signal.connect(myslot());
    }
    for(n = 0; n < num_connections; ++n)
    {
      connections.at(n).disconnect();
    }
  }
}
Ejemplo n.º 13
0
Archivo: daemon.cpp Proyecto: spito/dp
void Daemon::addDataLine( InputMessage &message, Channel channel ) {
    NOTE();

    OutputMessage response( MessageType::Control );
    response.tag( Code::Refuse );

    int peerId;
    int channelId;
    message >> peerId >> channelId;
    channel->receive( message );

    if ( _state == State::FormingGroup ) {
        Line peer = connections().lockedFind( peerId );
        if ( peer ) {
            peer->openDataChannel( channel, channelId );
            response.tag( Code::OK );
        }
    }
    channel->send( response );
}
Ejemplo n.º 14
0
Archivo: Plug.cpp Proyecto: UIKit0/DT3
void PlugBase::remove_outgoing_connection	(PlugBase* outgoing)
{
	PROFILER(SCRIPTING);

    if (_connection_index == 0)
        return;
    
    std::vector<PlugBase*> &outgoing_ref = connections()._outgoing;

    auto i = std::find(outgoing_ref.begin(), outgoing_ref.end(), outgoing);
	if (i != outgoing_ref.end()) {
    
        //
        // Lock this owner and the outgoing owner
        //
        
        std::unique_lock<std::recursive_mutex> lock_this(owner()->lock(),std::try_to_lock);
        std::unique_lock<std::recursive_mutex> lock_outgoing(outgoing->owner()->lock(),std::try_to_lock);

        DTboolean lock_this_status = lock_this.owns_lock();
        DTboolean lock_outgoing_status = lock_outgoing.owns_lock();
        
        while (!lock_this_status || !lock_outgoing_status) {
            if (lock_this_status)       lock_this.unlock();
            if (lock_outgoing_status)   lock_outgoing.unlock();
        
            lock_this_status = lock_this.owns_lock();
            lock_outgoing_status = lock_outgoing.owns_lock();
        }
        
        //
        // Do modifications
        //

		owner()->outgoing_plug_was_disconnected(this,outgoing);

		outgoing_ref.erase(i);
		outgoing->remove_incoming_connection();
    }
	
}
Ejemplo n.º 15
0
Archivo: daemon.cpp Proyecto: spito/dp
void Daemon::enslave( InputMessage &message, Channel channel ) {
    NOTE();

    OutputMessage response( MessageType::Control );
    if ( _state != State::Free ) {
        response.tag( Code::Refuse );
        std::string description = status();
        response << description;

        channel->send( response );
        channel->close();
        return;
    }

    int i;
    std::string selfName;
    int openChannels;
    message >> i >> selfName >> openChannels;
    channel->receive( message );


    response.tag( Code::OK );
    channel->send( response );

    rank( i );
    name( selfName );
    channels( openChannels );

    std::string address( net().peerAddress( *channel ) );
    Line master = std::make_shared< Peer >(
        0,
        "master",
        address.c_str(),
        std::move( channel )
    );

    connections().lockedInsert( 0, std::move( master ) ); // zero for master
    _state = State::Enslaved;
}
Ejemplo n.º 16
0
void ConnectionSet::_addConnectionToThread( ConnectionPtr connection )
{
    _needRebalance = true;
    lunchbox::ScopedWrite mutex( _impl->lock );
    if ( _impl->threads.size() > 0 ) 
    {
        Thread* minThread = *( std::min_element(_impl->threads.begin(), 
                               _impl->threads.end(), 
                               ThreadConnectionsSizeComparator()) );
        
        if ( minThread->set._impl->connections.size() < MAX_CONNECTIONS )
            minThread->set.addConnection( connection );    
        else 
        {
            Connections connections(1, connection);
            _createThread( connections );
        }
            
    }
    else 
    {
        _isThreadMode = true;
        size_t mid_connections = _impl->connections.size()/2;
        Connections connections1(_impl->connections.begin(), 
                                 _impl->connections.begin() + mid_connections );
        Connections connections2(_impl->connections.begin() + mid_connections, 
                                 _impl->connections.end() );
        connections1.push_back( connection );
        while( !_impl->connections.empty() ) 
        {
            ConnectionPtr lastConnection = _impl->connections.back();
            lastConnection->removeListener( _impl );
            _impl->connections.pop_back();
        }
        _createThread( connections1 );
        _createThread( connections2 );
    }
}
Ejemplo n.º 17
0
Archivo: daemon.cpp Proyecto: spito/dp
void Daemon::exit( int code ) {
    NOTE();
    Line master = connections().lockedFind( 0 );
    if ( !master ) {
        Logger::log( "inaccessible master" );
        ::exit( -code );
    }

    OutputMessage notification( MessageType::Control );
    notification.tag( Code::Done );
    master->master()->send( notification );

    while ( !_quit ) {
        Communicator::probe(
            _cache.at( ChannelID( ChannelType::All ).asIndex() ),
            [this]( Channel channel ) {
                this->consumeMessage( channel );
            },
            -1,
            false
        );
    }
    ::exit( code );
}
Ejemplo n.º 18
0
void PCB_BASE_FRAME::TestNetConnection( wxDC* aDC, int aNetCode )
{
    wxString msg;

    if( aNetCode <= 0 ) // -1 = not existing net, 0 = dummy net
        return;

    if( (m_Pcb->m_Status_Pcb & LISTE_RATSNEST_ITEM_OK) == 0 )
        Compile_Ratsnest( aDC, true );

    // Clear the cluster identifier (subnet) of pads for this net
    for( unsigned i = 0; i < m_Pcb->GetPadCount(); ++i )
    {
        D_PAD* pad = m_Pcb->GetPad(i);
        int    pad_net_code = pad->GetNetCode();

        if( pad_net_code < aNetCode )
            continue;

        if( pad_net_code > aNetCode )
            break;

        pad->SetSubNet( 0 );
    }

    m_Pcb->Test_Connections_To_Copper_Areas( aNetCode );

    // Search for the first and the last segment relative to the given net code
    if( m_Pcb->m_Track )
    {
        CONNECTIONS connections( m_Pcb );

        TRACK* firstTrack;
        TRACK* lastTrack = NULL;
        firstTrack = m_Pcb->m_Track.GetFirst()->GetStartNetCode( aNetCode );

        if( firstTrack )
            lastTrack = firstTrack->GetEndNetCode( aNetCode );

        if( firstTrack && lastTrack ) // i.e. if there are segments
        {
            connections.Build_CurrNet_SubNets_Connections( firstTrack, lastTrack, firstTrack->GetNetCode() );
        }
    }

    Merge_SubNets_Connected_By_CopperAreas( m_Pcb, aNetCode );

    // rebuild the active ratsnest for this net
    DrawGeneralRatsnest( aDC, aNetCode );
    TestForActiveLinksInRatsnest( aNetCode );
    DrawGeneralRatsnest( aDC, aNetCode );

    // Display results
    int net_notconnected_count = 0;
    NETINFO_ITEM* net = m_Pcb->FindNet( aNetCode );

    if( net )       // Should not occur, but ...
    {
        for( unsigned ii = net->m_RatsnestStartIdx; ii < net->m_RatsnestEndIdx; ii++ )
        {
            if( m_Pcb->m_FullRatsnest[ii].IsActive() )
                net_notconnected_count++;
        }

        msg.Printf( wxT( "links %d nc %d  net:nc %d" ),
                    m_Pcb->GetRatsnestsCount(), m_Pcb->GetUnconnectedNetCount(),
                    net_notconnected_count );
    }
    else
        msg.Printf( wxT( "net not found: netcode %d" ),aNetCode );

    SetStatusText( msg );
    return;
}
Ejemplo n.º 19
0
bool
fcppt::signal::unregister::base<T>::empty() const
{
	return connections().empty();
}
Ejemplo n.º 20
0
kvs::ObjectBase* BlockLoader::exec( const kvs::ObjectBase* object )
{
    
//    std::cout << volume->values().typeInfo()->typeName() <<std::endl;
    const size_t ndivisions = 24;
    const kvs::Vector3ui ncells = kvs::Vector3ui( nx - 1, ny - 1, nz - 1 );
    
    const int remainder_x = ncells.x() % block_size;
    const int remainder_y = ncells.y() % block_size;
    const int remainder_z = ncells.z() % block_size;
    
    const size_t block_x = ncells.x() / block_size + (bool)( remainder_x );  std::cout << "block_x: " << block_x <<std::endl;
    const size_t block_y = ncells.y() / block_size + (bool)( remainder_y );  std::cout << "block_y: " << block_y <<std::endl;
    const size_t block_z = ncells.z() / block_size + (bool)( remainder_z );  std::cout << "block_z: " << block_z <<std::endl;
    
    const size_t ncubes = block_x * block_y * block_z;
    const size_t nvertices = ( block_x + 1 ) * ( block_y + 1 ) * ( block_z + 1);
    std::cout << "nvertices: " << nvertices << std::endl;
    const size_t nnodes = nvertices + block_x * block_y * ( block_z + 1 ) + block_y * block_z * ( block_x + 1 ) + block_z * block_x * ( block_y + 1 ) + ncubes;
    std::cout << "nnodes: " << nnodes << std::endl;

    const size_t ntets = ncubes * ndivisions;
    std::cout << "ntets: " << ntets << std::endl;

    const kvs::UInt32 line_size = block_x + 1;
    std::cout<< "nnodesPerLine: " << line_size << std::endl;
    const kvs::UInt32 slice_size = ( block_x + 1 ) * ( block_y + 1 );
    std::cout<< "nnodesPerSlice: " << slice_size << std::endl;
        
    //Calculate the value and coord of every vertex
    kvs::AnyValueArray values;
    float* pvalues = static_cast<float*>( values.allocate<float>( nnodes ) );
    for( size_t i = 0; i < nnodes; i++ ) pvalues[i] = ori_values[i]; 
    
    kvs::ValueArray<kvs::Real32> coords( nnodes * 3 );
    kvs::Real32* pcoords = coords.pointer();
    float coord_x = 0.0;
    float coord_y = 0.0;
    float coord_z = 0.0;
    size_t count = 0;

    for ( size_t k = 0; k < ( block_z + 1 ); k++ )
    {
        if ( k == block_z )
        {
            coord_z = static_cast<float>( ncells.z() );
        }
        for ( size_t j = 0; j < ( block_y + 1 ); j++ )
        {
            if ( j == block_y )
            {
                coord_y = static_cast<float>( ncells.y() );
            }
            for ( size_t i = 0; i < ( block_x + 1 ); i++ )
            {
                if ( i == block_x )
                {
                    coord_x = static_cast<float>( ncells.x() );
                }
                
                count++;
                //coords
                *(pcoords++) = coord_x;   
                *(pcoords++) = coord_y;   
                *(pcoords++) = coord_z;
                coord_x += static_cast<float>( block_size );
            }            
            coord_x = 0.0;
            coord_y += static_cast<float>( block_size );
        }
        coord_y = 0.0;
        coord_z += static_cast<float>( block_size );
    }
    size_t index_x = count;

    float* p = new float[3];
    int initial_index = (int)block_size/2;
    float initial_coord = (float)block_size/2.0;
    
    int edge_index_x = remainder_x ? (int)( remainder_x )/2 : initial_index;
    int edge_index_y = remainder_y ? (int)( remainder_y )/2 : initial_index;
    int edge_index_z = remainder_z ? (int)( remainder_z )/2 : initial_index;
    float edge_coord_x = remainder_x ? (float)( remainder_x )/2.0 : initial_coord;
    float edge_coord_y = remainder_y ? (float)( remainder_y )/2.0 : initial_coord;
    float edge_coord_z = remainder_z ? (float)( remainder_z )/2.0 : initial_coord;
    
    int temp_index_x = 0;
    int temp_index_y = 0;
    int temp_index_z = 0;
    float temp_coord_x = 0.0;
    float temp_coord_y = 0.0;
    float temp_coord_z = 0.0;
    
    //Calculate the center of the face z = 0, 1, 2 ....    
    for ( size_t k = 0; k < ( block_z + 1 ); k++ )
    {
        temp_index_z = 0;
        temp_coord_z = 0.0;
        
        if ( k == block_z )
        {
            temp_index_z = remainder_z ? ( remainder_z - (int)block_size ) : 0; std::cout << "temp_index_z: " << temp_index_z << std::endl;
            temp_coord_z = remainder_z ? (float)( remainder_z - (int)block_size ) : 0.0;  std::cout << "temp_coord_z: " << temp_coord_z << std::endl;
        }
        for ( size_t j = 0; j < ( block_y ); j++ )
        {
            temp_index_y = initial_index;
            temp_coord_y = initial_coord;

            if ( j == block_y - 1 )
            {
                temp_index_y = edge_index_y;
                temp_coord_y = edge_coord_y;
            }
            for ( size_t i = 0; i < ( block_x ); i++ )
            { 
                temp_index_x = initial_index;
                temp_coord_x = initial_coord;

                if ( i == block_x - 1 )
                {
                    temp_index_x = edge_index_x;
                    temp_coord_x = edge_coord_x;
                }
                
                count++;
                p[0] = temp_coord_x + (float)(i * block_size);
                p[1] = temp_coord_y + (float)(j * block_size);
                p[2] = temp_coord_z + (float)(k * block_size);
                *(pcoords++) = p[0];
                *(pcoords++) = p[1];
                *(pcoords++) = p[2];
            }
        }
    }
    size_t index_y = count;
    std::cout<< "x_c: " << count <<std::endl;
    
    //Calculate the center of the face x = 0, 1, 2 ....    
    for ( size_t k = 0; k < ( block_z ); k++ )
    {
        temp_index_z = initial_index;
        temp_coord_z = initial_coord;
        
        if ( k == block_z - 1 )
        {
            temp_index_z = edge_index_z;
            temp_coord_z = edge_coord_z;
        }
        for ( size_t j = 0; j < ( block_y ); j++ )
        {
            temp_index_y = initial_index;
            temp_coord_y = initial_coord;

            if ( j == block_y - 1 )
            {
                temp_index_y = edge_index_y;
                temp_coord_y = edge_coord_y;
            }
            for ( size_t i = 0; i < ( block_x + 1 ); i++ )
            {
                temp_index_x = 0;
                temp_coord_x = 0.0;

                if ( i == block_x )
                {
                    temp_index_x = remainder_x ? ( remainder_x - (int)block_size ) : 0;
                    temp_coord_x = remainder_x ? (float)( remainder_x - (int)block_size ) : 0.0;
                }
                
                count++;
                
                p[0] = temp_coord_x + (float)(i * block_size);
                p[1] = temp_coord_y + (float)(j * block_size);
                p[2] = temp_coord_z + (float)(k * block_size);
                *(pcoords++) = p[0];
                *(pcoords++) = p[1];
                *(pcoords++) = p[2];
            }
        }
    }
    size_t index_z = count;
    std::cout<< "y_c: " << count <<std::endl;
    
    //Calculate the center of the face y = 0, 1, 2 ....    
    for ( size_t k = 0; k < ( block_z ); k++ )
    {
        temp_index_z = initial_index;
        temp_coord_z = initial_coord;
        
        if ( k == block_z - 1 )
        {
            temp_index_z = edge_index_z;
            temp_coord_z = edge_coord_z;
        }
        for ( size_t j = 0; j < ( block_y + 1 ); j++ )
        {
            temp_index_y = 0;
            temp_coord_y = 0.0;
            
            if ( j == block_y )
            {
                temp_index_y = remainder_y ? ( remainder_y - (int)block_size ) : 0;
                temp_coord_y = remainder_y ? (float)( remainder_y - (int)block_size ) : 0.0;
            }
            for ( size_t i = 0; i < ( block_x ); i++ )
            {
                temp_index_x = initial_index;
                temp_coord_x = initial_coord;
                
                if ( i == block_x - 1 )
                {
                    temp_index_x = edge_index_x;
                    temp_coord_x = edge_coord_x;
                }
                
                count++;
                
                p[0] = temp_coord_x + (float)(i * block_size);
                p[1] = temp_coord_y + (float)(j * block_size);
                p[2] = temp_coord_z + (float)(k * block_size);
                *(pcoords++) = p[0];
                *(pcoords++) = p[1];
                *(pcoords++) = p[2];
            }
        }
    }
    size_t index_gravity = count;
    std::cout<< "z_c: " << count <<std::endl;
    
    //Calculate the gravity center of every cell
    temp_index_x = initial_index;
    temp_index_y = initial_index;
    temp_index_z = initial_index;
    temp_coord_x = initial_coord;
    temp_coord_y = initial_coord;
    temp_coord_z = initial_coord;
    
    for ( size_t k = 0; k < ( block_z ); k++ )
    {
        if ( k == block_z - 1 )
        {
            temp_index_z = edge_index_z;
            temp_coord_z = edge_coord_z;
        }
        for ( size_t j = 0; j < ( block_y ); j++ )
        {
            if ( j == block_y - 1 )
            {
                temp_index_y = edge_index_y;
                temp_coord_y = edge_coord_y;
            }
            for ( size_t i = 0; i < ( block_x  ); i++ )
            {
                if ( i == block_x - 1 )
                {
                    temp_index_x = edge_index_x;
                    temp_coord_x = edge_coord_x;
                }
                p[0] = temp_coord_x + (float)(i * block_size);
                p[1] = temp_coord_y + (float)(j * block_size);
                p[2] = temp_coord_z + (float)(k * block_size);
                *(pcoords++) = p[0];
                *(pcoords++) = p[1];
                *(pcoords++) = p[2];
            }
            temp_index_x = initial_index;
            temp_coord_x = initial_coord;
        }
        temp_index_y = initial_coord;
        temp_coord_y = initial_coord;
    }

    //Calculate the new connection
    kvs::ValueArray<kvs::UInt32> connections( ntets * 4 );
    kvs::UInt32* pconnections = connections.pointer();
    
    for ( size_t k = 0; k < block_z; k++ )
    {
        for ( size_t j = 0; j < block_y; j++ )
        {
            for ( size_t i = 0; i < block_x; i++ )
            {
                const size_t index = i + j * line_size + k * slice_size;
                const kvs::UInt32 id0 = index;
                const kvs::UInt32 id1 = id0 + 1;
                const kvs::UInt32 id2 = id0 + line_size;
                const kvs::UInt32 id3 = id1 + line_size;
                const kvs::UInt32 id4 = id0 + slice_size;
                const kvs::UInt32 id5 = id1 + slice_size;
                const kvs::UInt32 id6 = id2 + slice_size;
                const kvs::UInt32 id7 = id3 + slice_size;
                
                const size_t index_center = i + j * block_x + k * block_x * block_y;
                const kvs::UInt32 id8 = index_x + index_center;
                const kvs::UInt32 id10 = id8 + (block_x * block_y);
                const kvs::UInt32 id11 = index_y + index_center;
                const kvs::UInt32 id9 = id11 + 1;
                const kvs::UInt32 id12 = index_z + index_center;
                const kvs::UInt32 id13 = id12 + block_x;
                const kvs::UInt32 id14 = index_gravity + index_center;

                //tet0
                *(pconnections++) = id14;
                *(pconnections++) = id8;
                *(pconnections++) = id0;
                *(pconnections++) = id1;
                
                //tet1
                *(pconnections++) = id14;
                *(pconnections++) = id8;
                *(pconnections++) = id1;
                *(pconnections++) = id3;
                
                //tet2
                *(pconnections++) = id14;
                *(pconnections++) = id8;
                *(pconnections++) = id3;
                *(pconnections++) = id2;
                
                //tet3
                *(pconnections++) = id14;
                *(pconnections++) = id8;
                *(pconnections++) = id2;
                *(pconnections++) = id0;
                
                //tet4
                *(pconnections++) = id14;
                *(pconnections++) = id9;
                *(pconnections++) = id1;
                *(pconnections++) = id5;
                
                //tet5
                *(pconnections++) = id14;
                *(pconnections++) = id9;
                *(pconnections++) = id5;
                *(pconnections++) = id7;
                
                //tet6
                *(pconnections++) = id14;
                *(pconnections++) = id9;
                *(pconnections++) = id7;
                *(pconnections++) = id3;
                
                //tet7
                *(pconnections++) = id14;
                *(pconnections++) = id9;
                *(pconnections++) = id3;
                *(pconnections++) = id1;
                
                //tet8
                *(pconnections++) = id14;
                *(pconnections++) = id10;
                *(pconnections++) = id5;
                *(pconnections++) = id4;
                
                //tet9
                *(pconnections++) = id14;
                *(pconnections++) = id10;
                *(pconnections++) = id4;
                *(pconnections++) = id6;
                
                //tet10
                *(pconnections++) = id14;
                *(pconnections++) = id10;
                *(pconnections++) = id6;
                *(pconnections++) = id7;
                
                //tet11
                *(pconnections++) = id14;
                *(pconnections++) = id10;
                *(pconnections++) = id7;
                *(pconnections++) = id5;
                
                //tet12
                *(pconnections++) = id14;
                *(pconnections++) = id11;
                *(pconnections++) = id4;
                *(pconnections++) = id0;
                
                //tet13
                *(pconnections++) = id14;
                *(pconnections++) = id11;
                *(pconnections++) = id0;
                *(pconnections++) = id2;
                
                //tet14
                *(pconnections++) = id14;
                *(pconnections++) = id11;
                *(pconnections++) = id2;
                *(pconnections++) = id6;
                
                //tet15
                *(pconnections++) = id14;
                *(pconnections++) = id11;
                *(pconnections++) = id6;
                *(pconnections++) = id4;
                
                //tet16
                *(pconnections++) = id14;
                *(pconnections++) = id12;
                *(pconnections++) = id1;
                *(pconnections++) = id0;
                
                //tet17
                *(pconnections++) = id14;
                *(pconnections++) = id12;
                *(pconnections++) = id0;
                *(pconnections++) = id4;
                
                //tet18
                *(pconnections++) = id14;
                *(pconnections++) = id12;
                *(pconnections++) = id4;
                *(pconnections++) = id5;
                
                //tet19
                *(pconnections++) = id14;
                *(pconnections++) = id12;
                *(pconnections++) = id5;
                *(pconnections++) = id1;
                
                //tet20
                *(pconnections++) = id14;
                *(pconnections++) = id13;
                *(pconnections++) = id2;
                *(pconnections++) = id3;
                
                //tet21
                *(pconnections++) = id14;
                *(pconnections++) = id13;
                *(pconnections++) = id3;
                *(pconnections++) = id7;
                
                //tet22
                *(pconnections++) = id14;
                *(pconnections++) = id13;
                *(pconnections++) = id7;
                *(pconnections++) = id6;
                
                //tet23
                *(pconnections++) = id14;
                *(pconnections++) = id13;
                *(pconnections++) = id6;
                *(pconnections++) = id2;

            }
            index_y ++;
        }
        index_z += block_x;
    }    

    SuperClass::setVeclen( 1 );
    SuperClass::setNNodes( nnodes );
    SuperClass::setNCells( ntets );
    SuperClass::setCellType( kvs::UnstructuredVolumeObject::Tetrahedra );
    SuperClass::setCoords( coords );
    SuperClass::setConnections( connections );
    SuperClass::setValues( values );
    SuperClass::updateMinMaxCoords();
    SuperClass::updateMinMaxValues();

    return this;
}
Ejemplo n.º 21
0
TreatmentInterface::TreatmentInterface(QWidget *parent) :
    QWidget(parent)
{
    createComponent();
    connections();
}
  void ConnectionsPerformanceTest::runSpatialPoolerTest(UInt numCells,
                                                        UInt numInputs,
                                                        UInt w,
                                                        UInt numWinners,
                                                        string label)
  {
    clock_t timer = clock();

    Connections connections(numCells, 1, numInputs);
    Cell cell;
    Segment segment;
    vector<Cell> sdr;
    Activity activity;

    // Initialize

    for (UInt c = 0; c < numCells; c++)
    {
      cell = Cell(c);
      segment = connections.createSegment(c);

      for (UInt i = 0; i < numInputs; i++)
      {
        connections.createSynapse(segment, i, (Permanence)rand()/RAND_MAX);
      }
    }

    checkpoint(timer, label + ": initialize");

    // Learn

    vector<Cell> winnerCells;
    SynapseData synapseData;
    Permanence permanence;

    for (int i = 0; i < 500; i++)
    {
      sdr = randomSDR(numInputs, w);
      activity = connections.computeActivity(sdr, 0.5, 0);
      winnerCells = computeSPWinnerCells(numWinners, activity);

      for (Cell winnerCell : winnerCells)
      {
        segment = Segment(0, winnerCell);

        for (Synapse synapse : connections.synapsesForSegment(segment))
        {
          synapseData = connections.dataForSynapse(synapse);
          permanence = synapseData.permanence;

          if (find(sdr.begin(), sdr.end(), synapseData.presynapticCell) !=
              sdr.end())
          {
            permanence += 0.2;
          }
          else
          {
            permanence -= 0.1;
          }

          permanence = max(permanence, (Permanence)0);
          permanence = min(permanence, (Permanence)1);

          // TODO (Question): Remove synapses with 0 permanence?

          connections.updateSynapsePermanence(synapse, permanence);
        }
      }
    }

    checkpoint(timer, label + ": initialize + learn");

    // Test

    for (int i = 0; i < 500; i++)
    {
      sdr = randomSDR(numInputs, w);
      activity = connections.computeActivity(sdr, 0.5, 0);
      winnerCells = computeSPWinnerCells(numWinners, activity);
    }

    checkpoint(timer, label + ": initialize + learn + test");
  }
Ejemplo n.º 23
0
void JSONSerializer::SerializeGeneralNode(
  rapidjson::Value& nodeValue, const shared_ptr<Node>& node)
{
  /// Save slots
  if (node->GetSerializableSlots().size() > 0) {
    rapidjson::Value slotsObject(rapidjson::kObjectType);
    for (const auto& slotPair : node->GetSerializableSlots()) {
      Slot* slot = slotPair.second;
      ASSERT(slot->GetName().get() != nullptr && !slot->GetName()->empty());
      rapidjson::Value slotObject(rapidjson::kObjectType);

      /// Save ghost flag
      if (slot->IsGhost()) {
        slotObject.AddMember("ghost", true, *mAllocator);
      }

      if (slot->mIsMultiSlot) {
        /// Save connections
        rapidjson::Value connections(rapidjson::kArrayType);
        for (const auto& connectedNode : slot->GetDirectMultiNodes()) {
          int connectedID = mNodes.at(connectedNode);
          connections.PushBack(connectedID, *mAllocator);
        }
        slotObject.AddMember("connect", connections, *mAllocator);
      }
      else {
        /// Save connection
        const auto& connectedNode = slot->GetDirectNode();
        if (connectedNode != nullptr && !slot->IsDefaulted()) {
          int connectedID = mNodes.at(connectedNode);
          slotObject.AddMember("connect", connectedID, *mAllocator);
        }

        /// Save default values
        FloatSlot* floatSlot;
        Vec2Slot* vec2Slot;
        Vec3Slot* vec3Slot;
        Vec4Slot* vec4Slot;
        StringSlot* stringSlot;

        if ((floatSlot = dynamic_cast<FloatSlot*>(slot)) != nullptr) {
          slotObject.AddMember("default", floatSlot->GetDefaultValue(), *mAllocator);
        }
        else if ((vec2Slot = dynamic_cast<Vec2Slot*>(slot)) != nullptr) {
          slotObject.AddMember("default", SerializeVec2(vec2Slot->GetDefaultValue()), 
            *mAllocator);
        }
        else if ((vec3Slot = dynamic_cast<Vec3Slot*>(slot)) != nullptr) {
          slotObject.AddMember("default", SerializeVec3(vec3Slot->GetDefaultValue()),
            *mAllocator);
        }
        else if ((vec4Slot = dynamic_cast<Vec4Slot*>(slot)) != nullptr) {
          slotObject.AddMember("default", SerializeVec4(vec4Slot->GetDefaultValue()),
            *mAllocator);
        }
        else if ((stringSlot = dynamic_cast<StringSlot*>(slot)) != nullptr) {
          slotObject.AddMember("default", stringSlot->GetDefaultValue(), *mAllocator);
        }
      }
      slotsObject.AddMember(rapidjson::Value(*slot->GetName(), *mAllocator),
        slotObject, *mAllocator);
    }
    nodeValue.AddMember("slots", slotsObject, *mAllocator);
  }
}
Ejemplo n.º 24
0
LoggedInDialog::LoggedInDialog()
{
    setupUi(this);
    this->setWindowTitle("Aeolus");
    connections();
}
Ejemplo n.º 25
0
kvs::ObjectBase* CubeToTetrahedraLinear::exec( const kvs::ObjectBase* object )
{
    const kvs::StructuredVolumeObject* volume = kvs::StructuredVolumeObject::DownCast( object );

//    std::cout << volume->values().typeInfo()->typeName() <<std::endl;
    const size_t ndivisions = 24;
    const kvs::Vector3ui ncells = volume->resolution() - kvs::Vector3ui( 1, 1, 1 );
    
    const int remainder_x = ncells.x() % block_size;
    const int remainder_y = ncells.y() % block_size;
    const int remainder_z = ncells.z() % block_size;
    
    const size_t block_x = ncells.x() / block_size + (bool)( remainder_x );  std::cout << "block_x: " << block_x <<std::endl;
    const size_t block_y = ncells.y() / block_size + (bool)( remainder_y );  std::cout << "block_y: " << block_y <<std::endl;
    const size_t block_z = ncells.z() / block_size + (bool)( remainder_z );  std::cout << "block_z: " << block_z <<std::endl;
    
    const size_t ncubes = block_x * block_y * block_z;
    const size_t nvertices = ( block_x + 1 ) * ( block_y + 1 ) * ( block_z + 1);
    std::cout << "nvertices: " << nvertices << std::endl;
    const size_t nnodes = nvertices + block_x * block_y * ( block_z + 1 ) + block_y * block_z * ( block_x + 1 ) + block_z * block_x * ( block_y + 1 ) + ncubes;
    std::cout << "nnodes: " << nnodes << std::endl;

    const size_t ntets = ncubes * ndivisions;
    std::cout << "ntets: " << ntets << std::endl;

    const kvs::UInt32 line_size = block_x + 1;
    std::cout<< "nnodesPerLine: " << line_size << std::endl;
    const kvs::UInt32 slice_size = ( block_x + 1 ) * ( block_y + 1 );
    std::cout<< "nnodesPerSlice: " << slice_size << std::endl;
    
    //Calculate the new value array
    float* ori_values = ( float* )volume->values().pointer();
    const size_t nx = volume->resolution().x();
    const size_t ny = volume->resolution().y();
//    const size_t nz = volume->resolution().z();
    
    //Calculate the value and coord of every vertex
    kvs::AnyValueArray values;
    float* pvalues = static_cast<float*>( values.allocate<float>( nnodes ) );
    kvs::ValueArray<kvs::Real32> coords( nnodes * 3 );
    kvs::Real32* pcoords = coords.pointer();
    size_t count_x = 0;
    size_t count_y = 0;
    size_t count_z = 0;
    float coord_x = 0.0;
    float coord_y = 0.0;
    float coord_z = 0.0;
    size_t count = 0;

    for ( size_t k = 0; k < ( block_z + 1 ); k++ )
    {
        if ( k == block_z )
        {
            count_z = nx * ny * ncells.z();
            coord_z = static_cast<float>( ncells.z() );
        }
        for ( size_t j = 0; j < ( block_y + 1 ); j++ )
        {
            if ( j == block_y )
            {
                count_y = nx * ncells.y();
                coord_y = static_cast<float>( ncells.y() );
            }
            for ( size_t i = 0; i < ( block_x + 1 ); i++ )
            {
                if ( i == block_x )
                {
                    count_x = ncells.x();
                    coord_x = static_cast<float>( ncells.x() );
                }
                //values
                *(pvalues + (count++)) = *(ori_values + count_x + count_y + count_z );
                count_x += block_size;
                
                //coords
                *(pcoords++) = coord_x;   
                *(pcoords++) = coord_y;   
                *(pcoords++) = coord_z;
                coord_x += static_cast<float>( block_size );
            }
            count_x = 0;
            count_y += ( volume->resolution().x() ) * block_size;
            
            coord_x = 0.0;
            coord_y += static_cast<float>( block_size );
        }
        count_y = 0;
        count_z += ( volume->nnodesPerSlice() ) * block_size;
        
        coord_y = 0.0;
        coord_z += static_cast<float>( block_size );
    }
    size_t index_x = count;
    
    //Evalute the value of the divided point with Linear
    bool parity = (bool)block_size % 2;
    float* p = new float[3];
        
    int initial_index = (int)block_size/2;
    float initial_coord = (float)block_size/2.0;
    
    int edge_index_x = remainder_x ? (int)( remainder_x )/2 : initial_index;
    int edge_index_y = remainder_y ? (int)( remainder_y )/2 : initial_index;
    int edge_index_z = remainder_z ? (int)( remainder_z )/2 : initial_index;
    float edge_coord_x = remainder_x ? (float)( remainder_x )/2.0 : initial_coord;
    float edge_coord_y = remainder_y ? (float)( remainder_y )/2.0 : initial_coord;
    float edge_coord_z = remainder_z ? (float)( remainder_z )/2.0 : initial_coord;
    
    int temp_index_x = 0;
    int temp_index_y = 0;
    int temp_index_z = 0;
    float temp_coord_x = 0.0;
    float temp_coord_y = 0.0;
    float temp_coord_z = 0.0;
    
    //Calculate the center of the face z = 0, 1, 2 ....    
    for ( size_t k = 0; k < ( block_z + 1 ); k++ )
    {
        temp_index_z = 0;
        temp_coord_z = 0.0;
        
        if ( k == block_z )
        {
            temp_index_z = remainder_z ? ( remainder_z - (int)block_size ) : 0; 
            temp_coord_z = remainder_z ? (float)( remainder_z - (int)block_size ) : 0.0;
        }
        for ( size_t j = 0; j < ( block_y ); j++ )
        {
            temp_index_y = initial_index;
            temp_coord_y = initial_coord;

            if ( j == block_y - 1 )
            {
                temp_index_y = edge_index_y;
                temp_coord_y = edge_coord_y;
            }
            for ( size_t i = 0; i < ( block_x ); i++ )
            { 
                temp_index_x = initial_index;
                temp_coord_x = initial_coord;

                if ( i == block_x - 1 )
                {
                    temp_index_x = edge_index_x;
                    temp_coord_x = edge_coord_x;
                }

                    int u = temp_index_x + (i * block_size);
                    int v = temp_index_y + (j * block_size);
                    int w = temp_index_z + (k * block_size);
                    p[0] = temp_coord_x + (float)(i * block_size);
                    p[1] = temp_coord_y + (float)(j * block_size);
                    p[2] = temp_coord_z + (float)(k * block_size);
                    *(pcoords++) = p[0];
                    *(pcoords++) = p[1];
                    *(pcoords++) = p[2];
                
                const size_t index = u + v * nx + w * nx * ny; 
                if( parity )
                    *(pvalues + (count++)) = (ori_values[index] + ori_values[index + 1] + ori_values[index + nx] + ori_values[index + 1 + nx])/4.0;
                else
                    *(pvalues + (count++)) = ori_values[index];
            }
        }
    }
    size_t index_y = count;
    std::cout<< "x_c: " << count <<std::endl;
    
    //Calculate the center of the face x = 0, 1, 2 ....
    for ( size_t k = 0; k < ( block_z ); k++ )
    {
        temp_index_z = initial_index;
        temp_coord_z = initial_coord;
        
        if ( k == block_z - 1 )
        {
            temp_index_z = edge_index_z;
            temp_coord_z = edge_coord_z;
        }
        for ( size_t j = 0; j < ( block_y ); j++ )
        {
            temp_index_y = initial_index;
            temp_coord_y = initial_coord;

            if ( j == block_y - 1 )
            {
                temp_index_y = edge_index_y;
                temp_coord_y = edge_coord_y;
            }
            for ( size_t i = 0; i < ( block_x + 1 ); i++ )
            {
                temp_index_x = 0;
                temp_coord_x = 0.0;

                if ( i == block_x )
                {
                    temp_index_x = remainder_x ? ( remainder_x - (int)block_size ) : 0;
                    temp_coord_x = remainder_x ? (float)( remainder_x - (int)block_size ) : 0.0;
                }
                
                int u = temp_index_x + (i * block_size);
                int v = temp_index_y + (j * block_size);
                int w = temp_index_z + (k * block_size);
                p[0] = temp_coord_x + (float)(i * block_size);
                p[1] = temp_coord_y + (float)(j * block_size);
                p[2] = temp_coord_z + (float)(k * block_size);
                *(pcoords++) = p[0];
                *(pcoords++) = p[1];
                *(pcoords++) = p[2];
                
                const size_t index = u + v * nx + w * nx * ny; 
                if( parity )
                    *(pvalues + (count++)) = (ori_values[index] + ori_values[index + nx] + ori_values[index + nx * ny] + ori_values[index + nx + nx * ny])/4.0;
                else
                    *(pvalues + (count++)) = ori_values[index]; 
            }
        }
    }
    size_t index_z = count;
    std::cout<< "y_c: " << count <<std::endl;
    
    //Calculate the center of the face y = 0, 1, 2 ....    
    for ( size_t k = 0; k < ( block_z ); k++ )
    {
        temp_index_z = initial_index;
        temp_coord_z = initial_coord;
        
        if ( k == block_z - 1 )
        {
            temp_index_z = edge_index_z;
            temp_coord_z = edge_coord_z;
        }
        for ( size_t j = 0; j < ( block_y + 1 ); j++ )
        {
            temp_index_y = 0;
            temp_coord_y = 0.0;
            
            if ( j == block_y )
            {
                temp_index_y = remainder_y ? ( remainder_y - (int)block_size ) : 0;
                temp_coord_y = remainder_y ? (float)( remainder_y - (int)block_size ) : 0.0;
            }
            for ( size_t i = 0; i < ( block_x ); i++ )
            {
                temp_index_x = initial_index;
                temp_coord_x = initial_coord;
                
                if ( i == block_x - 1 )
                {
                    temp_index_x = edge_index_x;
                    temp_coord_x = edge_coord_x;
                }
                
                int u = temp_index_x + (i * block_size);
                int v = temp_index_y + (j * block_size);
                int w = temp_index_z + (k * block_size);
                p[0] = temp_coord_x + (float)(i * block_size);
                p[1] = temp_coord_y + (float)(j * block_size);
                p[2] = temp_coord_z + (float)(k * block_size);
                *(pcoords++) = p[0];
                *(pcoords++) = p[1];
                *(pcoords++) = p[2];
                
                const size_t index = u + v * nx + w * nx * ny; 
                if( parity )
                    *(pvalues + (count++)) = (ori_values[index] + ori_values[index + 1] + ori_values[index + nx * ny] + ori_values[index + 1 + nx * ny])/4.0;
                else
                    *(pvalues + (count++)) = ori_values[index];
                
            }
        }
    }
    size_t index_gravity = count;
    std::cout<< "z_c: " << count <<std::endl;
    
    //Calculate the gravity center of every cell
    temp_index_x = initial_index;
    temp_index_y = initial_index;
    temp_index_z = initial_index;
    temp_coord_x = initial_coord;
    temp_coord_y = initial_coord;
    temp_coord_z = initial_coord;
    
    for ( size_t k = 0; k < ( block_z ); k++ )
    {
        if ( k == block_z - 1 )
        {
            temp_index_z = edge_index_z;
            temp_coord_z = edge_coord_z;
        }
        for ( size_t j = 0; j < ( block_y ); j++ )
        {
            if ( j == block_y - 1 )
            {
                temp_index_y = edge_index_y;
                temp_coord_y = edge_coord_y;
            }
            for ( size_t i = 0; i < ( block_x  ); i++ )
            {
                if ( i == block_x - 1 )
                {
                    temp_index_x = edge_index_x;
                    temp_coord_x = edge_coord_x;
                }
                
                int u = temp_index_x + (i * block_size);
                int v = temp_index_y + (j * block_size);
                int w = temp_index_z + (k * block_size);
                p[0] = temp_coord_x + (float)(i * block_size);
                p[1] = temp_coord_y + (float)(j * block_size);
                p[2] = temp_coord_z + (float)(k * block_size);
                *(pcoords++) = p[0];
                *(pcoords++) = p[1];
                *(pcoords++) = p[2];
                
                const size_t index = u + v * nx + w * nx * ny; 
                if( parity )
                    *(pvalues + (count++)) = (ori_values[index] + ori_values[index + 1] + ori_values[index + nx] + ori_values[index + nx + 1] + ori_values[index + nx * ny] + ori_values[index + 1 + nx * ny] + ori_values[index + nx + nx * ny] + ori_values[index + nx + 1 + nx * ny])/8.0;
                else
                    *(pvalues + (count++)) = ori_values[index];

                
            }
            temp_index_x = initial_index;
            temp_coord_x = initial_coord;
        }
        temp_index_y = initial_coord;
        temp_coord_y = initial_coord;
    }

    //Calculate the new connection
    kvs::ValueArray<kvs::UInt32> connections( ntets * 4 );
    kvs::UInt32* pconnections = connections.pointer();
    
    for ( size_t k = 0; k < block_z; k++ )
    {
        for ( size_t j = 0; j < block_y; j++ )
        {
            for ( size_t i = 0; i < block_x; i++ )
            {
                const size_t index = i + j * line_size + k * slice_size;
                const kvs::UInt32 id0 = index;
                const kvs::UInt32 id1 = id0 + 1;
                const kvs::UInt32 id2 = id0 + line_size;
                const kvs::UInt32 id3 = id1 + line_size;
                const kvs::UInt32 id4 = id0 + slice_size;
                const kvs::UInt32 id5 = id1 + slice_size;
                const kvs::UInt32 id6 = id2 + slice_size;
                const kvs::UInt32 id7 = id3 + slice_size;
                
                const size_t index_center = i + j * block_x + k * block_x * block_y;
                const kvs::UInt32 id8 = index_x + index_center;
                const kvs::UInt32 id10 = id8 + (block_x * block_y);
                const kvs::UInt32 id11 = index_y + index_center;
                const kvs::UInt32 id9 = id11 + 1;
                const kvs::UInt32 id12 = index_z + index_center;
                const kvs::UInt32 id13 = id12 + block_x;
                const kvs::UInt32 id14 = index_gravity + index_center;

                //tet0
                *(pconnections++) = id14;
                *(pconnections++) = id8;
                *(pconnections++) = id0;
                *(pconnections++) = id1;
                
                //tet1
                *(pconnections++) = id14;
                *(pconnections++) = id8;
                *(pconnections++) = id1;
                *(pconnections++) = id3;
                
                //tet2
                *(pconnections++) = id14;
                *(pconnections++) = id8;
                *(pconnections++) = id3;
                *(pconnections++) = id2;
                
                //tet3
                *(pconnections++) = id14;
                *(pconnections++) = id8;
                *(pconnections++) = id2;
                *(pconnections++) = id0;
                
                //tet4
                *(pconnections++) = id14;
                *(pconnections++) = id9;
                *(pconnections++) = id1;
                *(pconnections++) = id5;
                
                //tet5
                *(pconnections++) = id14;
                *(pconnections++) = id9;
                *(pconnections++) = id5;
                *(pconnections++) = id7;
                
                //tet6
                *(pconnections++) = id14;
                *(pconnections++) = id9;
                *(pconnections++) = id7;
                *(pconnections++) = id3;
                
                //tet7
                *(pconnections++) = id14;
                *(pconnections++) = id9;
                *(pconnections++) = id3;
                *(pconnections++) = id1;
                
                //tet8
                *(pconnections++) = id14;
                *(pconnections++) = id10;
                *(pconnections++) = id5;
                *(pconnections++) = id4;
                
                //tet9
                *(pconnections++) = id14;
                *(pconnections++) = id10;
                *(pconnections++) = id4;
                *(pconnections++) = id6;
                
                //tet10
                *(pconnections++) = id14;
                *(pconnections++) = id10;
                *(pconnections++) = id6;
                *(pconnections++) = id7;
                
                //tet11
                *(pconnections++) = id14;
                *(pconnections++) = id10;
                *(pconnections++) = id7;
                *(pconnections++) = id5;
                
                //tet12
                *(pconnections++) = id14;
                *(pconnections++) = id11;
                *(pconnections++) = id4;
                *(pconnections++) = id0;
                
                //tet13
                *(pconnections++) = id14;
                *(pconnections++) = id11;
                *(pconnections++) = id0;
                *(pconnections++) = id2;
                
                //tet14
                *(pconnections++) = id14;
                *(pconnections++) = id11;
                *(pconnections++) = id2;
                *(pconnections++) = id6;
                
                //tet15
                *(pconnections++) = id14;
                *(pconnections++) = id11;
                *(pconnections++) = id6;
                *(pconnections++) = id4;
                
                //tet16
                *(pconnections++) = id14;
                *(pconnections++) = id12;
                *(pconnections++) = id1;
                *(pconnections++) = id0;
                
                //tet17
                *(pconnections++) = id14;
                *(pconnections++) = id12;
                *(pconnections++) = id0;
                *(pconnections++) = id4;
                
                //tet18
                *(pconnections++) = id14;
                *(pconnections++) = id12;
                *(pconnections++) = id4;
                *(pconnections++) = id5;
                
                //tet19
                *(pconnections++) = id14;
                *(pconnections++) = id12;
                *(pconnections++) = id5;
                *(pconnections++) = id1;
                
                //tet20
                *(pconnections++) = id14;
                *(pconnections++) = id13;
                *(pconnections++) = id2;
                *(pconnections++) = id3;
                
                //tet21
                *(pconnections++) = id14;
                *(pconnections++) = id13;
                *(pconnections++) = id3;
                *(pconnections++) = id7;
                
                //tet22
                *(pconnections++) = id14;
                *(pconnections++) = id13;
                *(pconnections++) = id7;
                *(pconnections++) = id6;
                
                //tet23
                *(pconnections++) = id14;
                *(pconnections++) = id13;
                *(pconnections++) = id6;
                *(pconnections++) = id2;

            }
            index_y ++;
        }
        index_z += block_x;
    }    

    if ( volume->hasMinMaxExternalCoords() )
    {
        const kvs::Vector3f min_coord( volume->minExternalCoord() );
        const kvs::Vector3f max_coord( volume->maxExternalCoord() );
        SuperClass::setMinMaxExternalCoords( min_coord, max_coord );
    }

    if ( volume->hasMinMaxObjectCoords() )
    {
        const kvs::Vector3f min_coord( volume->minObjectCoord() );
        const kvs::Vector3f max_coord( volume->maxObjectCoord() );
        SuperClass::setMinMaxObjectCoords( min_coord, max_coord );
    }

    if ( volume->hasMinMaxValues() )
    {
        const kvs::Real64 min_value( volume->minValue() );
        const kvs::Real64 max_value( volume->maxValue() );
        SuperClass::setMinMaxValues( min_value, max_value );
    }

    SuperClass::setVeclen( volume->veclen() );
    SuperClass::setNNodes( nnodes );
    SuperClass::setNCells( ntets );
    SuperClass::setCellType( kvs::UnstructuredVolumeObject::Tetrahedra );
    SuperClass::setCoords( coords );
    SuperClass::setConnections( connections );
    SuperClass::setValues( values );
    SuperClass::updateMinMaxCoords();
    SuperClass::updateMinMaxValues();

    return this;
}
Ejemplo n.º 26
0
Dialog::Dialog(QString title, QWidget *parent)
    : QWidget(parent, Qt::WindowCloseButtonHint)
    , m_cbPort(new QComboBox(this))
    , m_cbBaud(new QComboBox(this))
    , m_bStart(new QPushButton("Start", this))
    , m_bStop(new QPushButton("Stop", this))
    , m_lTx(new QLabel("       Tx", this))
    , m_lRx(new QLabel("       Rx", this))
    , m_chbTimer(new QCheckBox("Timer", this))
    , m_leTimer(new QLineEdit(this))
    , m_lTickTime(new QLabel("00:00:00", this))
    , m_bRec(new QPushButton(QIcon(":/Resources/startRecToFile.png"), QString::null, this))
    , m_sbSamplRate(new QSpinBox(this))
    , m_bSetRate(new QPushButton("Set Rate", this))
    , m_bStopRec(new QPushButton(QIcon(":/Resources/stopRecToFile.png"), QString::null, this))
    , m_leSerialNum(new QLineEdit(this))
    , m_leModelName(new QLineEdit(this))
    , m_leTempLoad(new QLineEdit(this))
    , m_leTempEnv(new QLineEdit(this))
    , m_leTestName(new QLineEdit(this))
    , m_Port(new QSerialPort(this))
    , m_ComPort(new ComPort(m_Port, STARTBYTE, STOPBYTE, BYTESLENGTH, true, this))
    , m_Protocol(new ADCtoCSVProtocol(m_ComPort, this))
    , m_BlinkTimeTxNone(new QTimer(this))
    , m_BlinkTimeRxNone(new QTimer(this))
    , m_BlinkTimeTxColor(new QTimer(this))
    , m_BlinkTimeRxColor(new QTimer(this))
    , m_CurrentTime(new QTime())
    , m_LastRecieveTime(0.0)
    , m_isBright(true)
    , m_isRecording(false)
    , m_BlinkTimeRec(new QTimer(this))
    , m_TimeDisplay(new QTimer(this))
    , m_lVoltAvg(new QLabel("NONE", this))
    , m_lDeviation(new QLabel("NONE", this))
{
    setWindowTitle(title);
    view();
    connections();

    m_lTx->setStyleSheet("background: yellow; font: bold; font-size: 10pt");
    m_lRx->setStyleSheet("background: yellow; font: bold; font-size: 10pt");
    m_leTimer->setAlignment(Qt::AlignCenter);
    QFont font("Consolas", 15);
    m_leTimer->setFont(font);
    QRegExp regExpr("[0-5][0-9]:[0-5][0-9]:[0-5][0-9]");
    QRegExpValidator *validator = new QRegExpValidator(regExpr, this);
    m_leTimer->setValidator(validator);
    m_leTimer->setInputMask("00:00:00;O");

    m_lTickTime->setFont(font);
    m_lVoltAvg->setFont(font);
    m_lDeviation->setFont(font);

    QStringList portsNames;

    foreach(QSerialPortInfo portsAvailable, QSerialPortInfo::availablePorts())
    {
        portsNames << portsAvailable.portName();
    }

    m_cbPort->addItems(portsNames);

    QStringList bauds;
    bauds << "921600" << "115200";
    m_cbBaud->addItems(bauds);

    m_leTimer->setEnabled(false);
    m_bStop->setEnabled(false);
    m_bStopRec->setEnabled(false);
    m_bSetRate->setEnabled(false);
    m_bRec->setEnabled(false);

    m_BlinkTimeTxNone->setInterval(BLINKTIMETX);
    m_BlinkTimeRxNone->setInterval(BLINKTIMERX);
    m_BlinkTimeTxColor->setInterval(BLINKTIMETX);
    m_BlinkTimeRxColor->setInterval(BLINKTIMERX);

    m_BlinkTimeRec->setInterval(BLINKTIMEREC);

    m_TimeDisplay->setInterval(TIMEDISPLAY);

    QString exprT = "(\\-){,1}(\\d){,2}";
    QRegExp regExprT(exprT);
    QRegExpValidator *validatorT = new QRegExpValidator(regExprT, this);
    m_leTempLoad->setValidator(validatorT);
    m_leTempEnv->setValidator(validatorT);

    // [1-0]Temperary!!!
    m_leModelName->setEnabled(false);
    m_leModelName->setText("RR-5");
    QStringList completerList;
    completerList << "SensitivityTest" << "VoltageStabilityTest";
    QCompleter *completer = new QCompleter(completerList, this);
    completer->setCaseSensitivity(Qt::CaseInsensitive);
    m_leTestName->setCompleter(completer);
    // [1-0]Temperary!!!
}
Ejemplo n.º 27
0
	void pool::mutate_link(genome& g, bool force_bias){
		/* network encoding:
		 * | input nodes | bias | output nodes |
		 */		
		auto is_input = [&](unsigned int node) -> bool {
				return node < this->network_info.input_size; };
		auto is_output = [&](unsigned int node) -> bool {
				return node < this->network_info.functional_nodes && node >= 
					(this->network_info.input_size + this->network_info.bias_size); };
		auto is_bias = [&](unsigned int node) -> bool {
				return node < (this->network_info.input_size + this->network_info.bias_size) && node >= this->network_info.input_size; };

		std::uniform_int_distribution<unsigned int> distributor1(0, g.max_neuron-1);
		unsigned int neuron1 = distributor1(this->generator);

		std::uniform_int_distribution<unsigned int> distributor2
			(this->network_info.input_size + this->network_info.bias_size, g.max_neuron-1);
		unsigned int neuron2 = distributor2(this->generator);
			
		if (is_output(neuron1) && is_output(neuron2))
			return ;
		if (is_bias(neuron2)) 
			return ;	
		if (neuron1 == neuron2 && (!force_bias))
			return ;
		if (is_output(neuron1))
			std::swap(neuron1, neuron2);		

		if (force_bias){
			std::uniform_int_distribution<unsigned int> bias_choose
				(this->network_info.input_size, this->network_info.input_size + this->network_info.output_size-1);
			neuron1 = bias_choose(this->generator);			
		}

		if (!g.network_info.recurrent){
			// check for recurrency using BFS
			bool has_recurrence = false;
			if (is_bias(neuron1) || is_input(neuron1))
				has_recurrence = false;
			else {

				std::queue<unsigned int> que;
				std::vector<std::vector<unsigned int>> connections(g.max_neuron);	
				for (auto it = g.genes.begin(); it != g.genes.end(); it++)
					connections[(*it).second.from_node].push_back((*it).second.to_node);
				connections[neuron1].push_back(neuron2);
							
				for (size_t i=0; i<connections[neuron1].size(); i++)
					que.push(connections[neuron1][i]);
					while (!que.empty()){				
					unsigned int tmp = que.front();
					if (tmp == neuron1){
						has_recurrence = true;
						break;
					}
					que.pop();
					for (size_t i=0; i<connections[tmp].size(); i++)
						que.push(connections[tmp][i]);				
				}
			}
			if (has_recurrence)
				return ;

			// now we are sure that it doesn't has any recurrency	
		}
		
		// now we can create a link 
		gene new_gene;
		new_gene.from_node = neuron1;
		new_gene.to_node = neuron2;	

		// if genome already has this connection
		for (auto it = g.genes.begin(); it != g.genes.end(); it++)
			if ((*it).second.from_node == neuron1 && (*it).second.to_node == neuron2)
				return ;
		
		// add new innovation if needed
		new_gene.innovation_num = this->innovation.add_gene(new_gene);

		// mutate new link
		std::uniform_real_distribution<double> weight_generator(0.0, 1.0);
		new_gene.weight = weight_generator(this->generator) * 4.0 - 2.0;		
		
		g.genes[new_gene.innovation_num] = new_gene;
	}	
Ejemplo n.º 28
0
/**
 *
 * Reserves a database connection. Until this is freed, it will not be re-used.
 *
 * @param timeout The minimum amount of time to use this connection in seconds
 * @param receiver The object which we'll send any data to
 *
 * @return A UUID for this connection
 */
DatabaseConnection *DatabaseConnectionManager::reserveDatabaseConnectionObj(
        int timeout, SmartObject *receiver)
{
    ConnectionRecord record, currentRecord;
    DatabaseConnection *connection = nullptr, *currentConnection;
    int count;
    bool running, busy;

    if (timeout != 0) {

        // Expiry = unixtime + whatever timeout started as
        timeout += std::time(nullptr);
    }

    while (connection == nullptr) {

        // Reset counter
        count = 0;

        // Iterate connections
        Connections connections(this->connections);
        for (Connections::iterator it = connections.begin();
             it != connections.end(); ++it) {

            currentConnection = it->first;
            currentRecord = it->second;

            if (currentRecord.expiry != 0) {

                // This connection has an expiry. No expiry indicates that it is
                // a reserved connection that should not be re-assigned.
                if (connection == nullptr) {

                    // Lock this connection's mutex
                    currentConnection->mutex.lock();

                    // Check if this connection is in the process of shutting
                    // down or is busy with something (or has pending queries)
                    busy = currentConnection->busy
                            || !currentConnection->commands.empty();

                    // Unlock the mutex
                    currentConnection->mutex.unlock();

                    if (currentConnection->isStopping() && !busy) {

                        // Re-use this connection
                        connection = currentConnection;

                        // Disconnect the execution signal so if the old
                        // receiver is still around it won't keep getting
                        // signals
                        connection->disconnectQueue(
                            DatabaseConnection::EXECUTED);

                        // Rollback transaction if applicable
                        connection->call(Variant(),
                                         QueryEvent::CLEAN_STATE);
                    }

                } else if (currentRecord.expiry != 0
                           && currentRecord.expiry > std::time(nullptr)) {

                    // This connection has expired

                    // Lock this connection's mutex
                    currentConnection->mutex.lock();

                    // Check if this connection is in the process of shutting
                    // down or is busy with something
                    busy = currentConnection->busy
                            || !currentConnection->commands.empty();

                    // Unlock the mutex
                    currentConnection->mutex.unlock();

                    if (!busy) {
                        // Tell the connection to disconnect. We'll free memory
                        // after that is finished
                        if (!currentConnection->isStopping()) {

                            // Ensure this connection's signals are disconnected
                            currentConnection->disconnectQueue(
                                DatabaseConnection::EXECUTED);

                            // Connect to ourself. After the disconnect
                            // completes, we need to free the connection

                            currentConnection->connectQueue(
                                DatabaseConnection::EXECUTED, this);

                            currentConnection->call(Variant(currentRecord.uuid),
                                QueryEvent::DISCONNECT);
                        }

                        // Remove from the hash
                        this->connections.erase(currentConnection);

                        // Add to the disconnections hash
                        disconnectingConnections[currentRecord.uuid]
                                = currentConnection;
                    }
                }

                count++;
            }
        }

        if (connection == nullptr && count < maxConnections) {

            // Initialize new connection
            connection = mainConnection->clone(this);

            // Start new thread
            connection->start();
        }

        if (connection != nullptr) {
            record.expiry = timeout;
            record.uuid = UUID::makeUUID();
            record.receiver = receiver;
            this->connections[connection] = record;
        }

        if (connection == nullptr) {
            // Process any pending events
            Application::getInstance()->processEvents();

            // Also sleep for 30ms. There may not be events to process above
            // and we don't want to pin the cpu
            usleep(30 * 1000);
        }
    }

    if (receiver != nullptr) {

        // Lock mutex
        connection->mutex.lock();

        // Connect signal
        connection->connectQueue(DatabaseConnection::EXECUTED, receiver);

        // Unlock mutex
        connection->mutex.unlock();
    }

    return connection;
}
Ejemplo n.º 29
0
//
// compute similarities for the set of "true" pixels in region.
// affinity matrix is ordered in scanline order
//
void computeAffinities2(const SupportMap& icmap, const float sigma, const float dthresh, SMatrix** affinities)
{
    int width = icmap.size(0);
    int height = icmap.size(1);

    //build a scanline order index
    int numPixels = 0;
    Util::Array2D<int> index(width,height);
    index.init(-1);
    for (int y = 0; y < height; y++)
    {
        for (int x = 0; x < width; x++)
        {
            index(x,y) = numPixels;
            numPixels++;
        }
    }

    //sparse matrix data
    int* nz = new int[numPixels];           //number of non-zero entries in each row
    double** vals = new double*[numPixels];   //the values in each row
    int** col = new int*[numPixels];        //the column number for each value in the row

    int dthreshi = (int)ceil(dthresh);
    int wd = (2*dthreshi+1);                 //window diameter
    Util::Array1D<PointIC> connections(wd*wd);

    int row = 0;
    for (int x = 0; x < width; x++)
    {
        for (int y = 0; y < height; y++)
        {
            row = index(x,y);  //the row we are working on
            nz[row] = 0;       //connection count for row i
            int icIndex = 0;        //index into sparse supportMap
            for (int u = -dthreshi; u <= dthreshi; u++)
            {
                int yy = y + u;
                for (int v = -dthreshi; v <= dthreshi; v++)
                {
                    int xx = x + v;
                    if (xx < 0 || xx >= width) {
                        continue;
                    }
                    if (yy < 0 || yy >= height) {
                        continue;
                    }
                    if (u*u+v*v > dthresh*dthresh) {
                        continue;
                    }

                    //increment our index into the support map
                    while( icIndex < icmap(x,y).size() &&
                            icmap(x,y)(icIndex).y < yy)
                    {
                        icIndex++;
                    }
                    while( icIndex < icmap(x,y).size() &&
                            icmap(x,y)(icIndex).x < xx)
                    {
                        icIndex++;
                    }


                    float pss = 0.0;     //connection strength
                    if ((u == 0) && (v == 0))
                    {
                        pss = 1.0f;
                    }
                    else
                    {
                        float icsim = 0.0f;
                        if (icIndex < icmap(x,y).size() &&
                                icmap(x,y)(icIndex).x == xx &&
                                icmap(x,y)(icIndex).y == yy)
                        {
                            icsim = icmap(x,y)(icIndex).sim;
                            icIndex++;
                        }
                        pss = C_IC_SS(1-icsim);
                    }//if (u==0) & (v==0)

                    connections(nz[row]).x = xx;
                    connections(nz[row]).y = yy;
                    connections(nz[row]).sim = pss;
                    nz[row]++;
                }//for v
            }//for u

            //fill in entries of sparse matrix
            vals[row] = new double[nz[row]];
            col[row] = new int[nz[row]];
            for (int j = 0; j < nz[row]; j++)
            {
                float val = exp( -(1-connections(j).sim) / sigma);
                assert((val >= 0.0) && (val <= 1.0));
                vals[row][j] = val;
                col[row][j] = index(connections(j).x,connections(j).y);
            }
        }//for y
    }//for x

    *affinities = new SMatrix(numPixels,nz,col,vals);
    (*affinities)->symmetrize();
}
Ejemplo n.º 30
0
/* search connections between tracks and pads and propagate pad net codes to the track
 * segments.
 * Pads netcodes are assumed to be up to date.
 */
void PCB_BASE_FRAME::RecalculateAllTracksNetcode()
{
    // Build the net info list
    GetBoard()->BuildListOfNets();

    // Reset variables and flags used in computation
    for( TRACK* t = m_Pcb->m_Track;  t;  t = t->Next() )
    {
        t->m_TracksConnected.clear();
        t->m_PadsConnected.clear();
        t->start = NULL;
        t->end = NULL;
        t->SetState( BUSY | IN_EDIT | BEGIN_ONPAD | END_ONPAD, false );
        t->SetZoneSubNet( 0 );
        t->SetNetCode( NETINFO_LIST::UNCONNECTED );
    }

    // If no pad, reset pointers and netcode, and do nothing else
    if( m_Pcb->GetPadCount() == 0 )
        return;

    CONNECTIONS connections( m_Pcb );
    connections.BuildPadsList();
    connections.BuildTracksCandidatesList(m_Pcb->m_Track);

    // First pass: build connections between track segments and pads.
    connections.SearchTracksConnectedToPads();

    // For tracks connected to at least one pad,
    // set the track net code to the pad netcode
    for( TRACK* t = m_Pcb->m_Track;  t;  t = t->Next() )
    {
        if( t->m_PadsConnected.size() )
            t->SetNetCode( t->m_PadsConnected[0]->GetNetCode() );
    }

    // Pass 2: build connections between track ends
    for( TRACK* t = m_Pcb->m_Track;  t;  t = t->Next() )
    {
        connections.SearchConnectedTracks( t );
        connections.GetConnectedTracks( t );
    }

    // Propagate net codes from a segment to other connected segments
    bool new_pass_request = true;   // set to true if a track has its netcode changed from 0
                                    // to a known netcode to re-evaluate netcodes
                                    // of connected items
    while( new_pass_request )
    {
        new_pass_request = false;

        for( TRACK* t = m_Pcb->m_Track;  t;  t = t->Next() )
        {
            int netcode = t->GetNetCode();

            if( netcode == 0 )
            {
                // try to find a connected item having a netcode
                for( unsigned kk = 0; kk < t->m_TracksConnected.size(); kk++ )
                {
                    int altnetcode = t->m_TracksConnected[kk]->GetNetCode();
                    if( altnetcode )
                    {
                        new_pass_request = true;
                        netcode = altnetcode;
                        t->SetNetCode(netcode);
                        break;
                    }
                }
            }

            if( netcode )    // this track has a netcode
            {
                // propagate this netcode to connected tracks having no netcode
                for( unsigned kk = 0; kk < t->m_TracksConnected.size(); kk++ )
                {
                    int altnetcode = t->m_TracksConnected[kk]->GetNetCode();
                    if( altnetcode == 0 )
                    {
                        t->m_TracksConnected[kk]->SetNetCode(netcode);
                        new_pass_request = true;
                    }
                }
            }
        }
    }

    // Sort the track list by net codes:
    RebuildTrackChain( m_Pcb );
}