void NsAdapterCatalog::addReplica(const Replica& replica) throw (DmException) { struct dpns_fileid uniqueId; // If server is empty, parse the surl std::string host; if (replica.server.empty()) { Url u(replica.rfn); host = u.domain; if (host.empty()) throw DmException(DM_INVALID_VALUE, "Empty server specified, and SFN does not include it: %s", replica.rfn.c_str()); } else { host = replica.server; } uniqueId.fileid = replica.fileid; strncpy(uniqueId.server, getenv("DPNS_HOST"), sizeof(uniqueId.server)); std::string pool; if (replica.hasField("pool")) pool = replica.getString("pool"); std::string filesystem; if (replica.hasField("filesystem")) filesystem = replica.getString("filesystem"); wrapCall(dpns_addreplica(NULL, &uniqueId, host.c_str(), replica.rfn.c_str(), replica.status, replica.type, pool.c_str(), filesystem.c_str())); }
bool swap(Replica box1, Replica box2, RanMars *random) { double beta1 = 1/box1.temp, beta2 = 1/box2.temp; double u1 = box1.u, u2 = box2.u; double delta = -1*(beta2-beta1)*(u2-u1); // cout << delta << "\t" << exp(-delta) << endl; //check if swap move is accepted bool accept = false; if (delta<=0) { accept = true; // cout << "accepted" << endl; } else { double prob = exp(-delta); double rand = random->uniform(); if (rand<prob) { accept=true; // cout << "accepted here!" << endl; } } //if accepted, then swap if (accept) { double **x1 = box1.get_pos(); box1.set_pos(box2.get_pos()); box2.set_pos(x1); } // else // cout << "rejected" << endl; return accept; }
google::protobuf::Message* TestRPCServerMRC::OpenOperation( const pbrpc::Auth& auth, const pbrpc::UserCredentials& user_credentials, const google::protobuf::Message& request, const char* data, uint32_t data_len, boost::scoped_array<char>* response_data, uint32_t* response_data_len) { const openRequest* rq = reinterpret_cast<const openRequest*>(&request); openResponse* response = new openResponse(); XCap* xcap = response->mutable_creds()->mutable_xcap(); xcap->set_access_mode(rq->flags()); xcap->set_client_identity("client_identity"); xcap->set_expire_time_s(3600); xcap->set_expire_timeout_s(static_cast<uint32_t>(time(0)) + 3600); xcap->set_file_id(rq->volume_name() + ":0"); xcap->set_replicate_on_close(false); xcap->set_server_signature("signature"); xcap->set_snap_config(SNAP_CONFIG_SNAPS_DISABLED); xcap->set_snap_timestamp(0); xcap->set_truncate_epoch(0); xcap->set_voucher_size(0); struct timeval tp; gettimeofday(&tp, NULL); xcap->set_expire_time_ms(tp.tv_sec * 1000 + tp.tv_usec / 1000); XLocSet* xlocset = response->mutable_creds()->mutable_xlocs(); xlocset->set_read_only_file_size(file_size_); xlocset->set_replica_update_policy(""); // "" = REPL_UPDATE_PC_NONE; xlocset->set_version(0); xlocset->add_replicas(); Replica* replica = xlocset->mutable_replicas(0); replica->set_replication_flags(0); for (std::vector<std::string>::iterator it = osd_uuids_.begin(); it != osd_uuids_.end(); ++it) { replica->add_osd_uuids(*it); } replica->mutable_striping_policy()->set_type(STRIPING_POLICY_RAID0); replica->mutable_striping_policy()->set_stripe_size(128); replica->mutable_striping_policy()->set_width(1); response->set_timestamp_s(static_cast<uint32_t>(time(0))); return response; }
ReplicaReturnResult ReplicaManager::ProcessReceivedCommand(ParticipantStruct *participantStruct, ReceivedCommand *receivedCommand) { Replica *replica = (Replica*) NetworkIDGenerator::GET_BASE_OBJECT_FROM_ID(receivedCommand->networkID); bool objectExists; unsigned index; ReplicaReturnResult b; if (replica) { index = replicatedObjects.GetIndexFromKey(replica, &objectExists); if (objectExists==false) { // Two ways to handle this. One is to autoregister the object - but this is dangerous in that if you have a network object that is not // using the replica system it would be of the wrong type, read read invalid memory, and crash. // Construct(replica, playerId, broadcast, true); // The other way is to assert and do nothing. The disadvantage is now the user has to register the object in order to receive calls on it. #ifdef _DEBUG // If this assert hits, call ReferencePointer on your replica pointer after it is created. assert(0); #endif return REPLICA_CANCEL_PROCESS; } } if (receivedCommand->command==ID_REPLICA_MANAGER_SERIALIZE) { if (replica && (replicatedObjects[index].allowedInterfaces & REPLICA_RECEIVE_SERIALIZE)) { b=replica->Deserialize(receivedCommand->userData, receivedCommand->u1, replicatedObjects[index].lastDeserializeTrue, receivedCommand->playerId); if (b==REPLICA_PROCESSING_DONE) replicatedObjects[index].lastDeserializeTrue=RakNet::GetTime(); return b; } } else if (receivedCommand->command==ID_REPLICA_MANAGER_CONSTRUCTION) { // If networkID already exists on this system, ignore the packet if (replica==0) { #ifdef _DEBUG assert(_constructionCB); #endif // Call the registered callback. If it crashes, you forgot to register the callback in SetReceiveConstructionCB return _constructionCB(receivedCommand->userData, receivedCommand->u1, receivedCommand->networkID, receivedCommand->playerId, this); } } else if (receivedCommand->command==ID_REPLICA_MANAGER_SCOPE_CHANGE) { if (replica && (replicatedObjects[index].allowedInterfaces & REPLICA_RECEIVE_SCOPE_CHANGE)) { return replica->ReceiveScopeChange(receivedCommand->userData, receivedCommand->playerId); } } else if (receivedCommand->command==ID_REPLICA_MANAGER_DESTRUCTION) { if (replica && (replicatedObjects[index].allowedInterfaces & REPLICA_RECEIVE_DESTRUCTION)) { return replica->ReceiveDestruction(receivedCommand->userData, receivedCommand->playerId); } } else if (receivedCommand->command==ID_REPLICA_MANAGER_DOWNLOAD_COMPLETE) { if (_receiveDownloadCompleteCB) { return _receiveDownloadCompleteCB(receivedCommand->userData, receivedCommand->playerId, this); } } return REPLICA_CANCEL_PROCESS; }
void ReplicaManager::Update(RakPeerInterface *peer) { if (participantList.Size()==0) return; unsigned participantIndex, remoteObjectListIndex, replicatedObjectsIndex; ReplicaReturnResult res; bool sendTimestamp; ParticipantStruct *participantStruct; unsigned commandListIndex; RakNet::BitStream outBitstream, userDataBitstream; RakNetTime currentTime; bool objectExists; PacketPriority priority; PacketReliability reliability; ReceivedCommand *receivedCommand; Replica *replica; unsigned char command; currentTime=0; // For each participant for (participantIndex=0; participantIndex < participantList.Size(); participantIndex++) { participantStruct = participantList[participantIndex]; // For each CommandStruct to send for (commandListIndex=0; commandListIndex < participantStruct->commandList.Size(); commandListIndex++) { // Only call RakNet::GetTime() once because it's slow if (currentTime==0) currentTime=RakNet::GetTime(); replica=participantStruct->commandList[commandListIndex].replica; command=participantStruct->commandList[commandListIndex].command; replicatedObjectsIndex=replicatedObjects.GetIndexFromKey(replica, &objectExists); #ifdef _DEBUG assert(objectExists); #endif // If construction is set, call SendConstruction. The only precondition is that the object was not already created, // which was checked in ReplicaManager::Replicate if (command & REPLICA_EXPLICIT_CONSTRUCTION) { if (replicatedObjects[replicatedObjectsIndex].allowedInterfaces & REPLICA_SEND_CONSTRUCTION) { userDataBitstream.Reset(); sendTimestamp=false; res=replica->SendConstruction(currentTime, participantStruct->playerId, &userDataBitstream, &sendTimestamp); if (res==REPLICA_PROCESSING_DONE) { outBitstream.Reset(); // If SendConstruction returns true and writes to outBitStream, do this send. Clear the construction command. Then process the next command for this CommandStruct, if any. if (sendTimestamp) { outBitstream.Write((unsigned char)ID_TIMESTAMP); outBitstream.Write(currentTime); } outBitstream.Write((unsigned char)ID_REPLICA_MANAGER_CONSTRUCTION); // It's required to send an NetworkID if available. // Problem: // A->B->C // | | // D->E // // A creates. // B->C->E->D->B will cycle forever. // Fix is to always include an networkID. Objects are not created if that object id already is present. if (replica->GetNetworkID()!=UNASSIGNED_NETWORK_ID) { outBitstream.Write(true); outBitstream.Write(replica->GetNetworkID()); } else outBitstream.Write(false); outBitstream.Write(&userDataBitstream, userDataBitstream.GetNumberOfBitsUsed()); peer->Send(&outBitstream, HIGH_PRIORITY, RELIABLE_ORDERED, sendChannel, participantStruct->playerId, false); // Turn off this bit participantStruct->commandList[commandListIndex].command &= 0xFF ^ REPLICA_EXPLICIT_CONSTRUCTION; // Add the object to the participant's object list, indicating this object has been remotely created RemoteObject remoteObject; remoteObject.replica=replica; remoteObject.inScope=defaultScope; remoteObject.lastSendTime=0; // Create an entry for this object. We do this now, even if the user might refuse the SendConstruction override, // because that call may be delayed and other commands sent while that is pending. We always do the REPLICA_EXPLICIT_CONSTRUCTION call first. participantStruct->remoteObjectList.Insert(remoteObject.replica,remoteObject); } else if (res==REPLICA_PROCESS_LATER) { continue; } else // REPLICA_CANCEL_PROCESS { assert(res==REPLICA_CANCEL_PROCESS); participantStruct->commandList[commandListIndex].command=0; } } else { // Don't allow construction, or anything else for this object, as the construction send call is disallowed participantStruct->commandList[commandListIndex].command=0; } } else if (command & REPLICA_IMPLICIT_CONSTRUCTION) { // Turn off this bit participantStruct->commandList[commandListIndex].command &= 0xFF ^ REPLICA_IMPLICIT_CONSTRUCTION; // Add the object to the participant's object list, indicating this object is assumed to be remotely created RemoteObject remoteObject; remoteObject.replica=replica; remoteObject.inScope=defaultScope; remoteObject.lastSendTime=0; // Create an entry for this object. We do this now, even if the user might refuse the SendConstruction override, // because that call may be delayed and other commands sent while that is pending. We always do the REPLICA_EXPLICIT_CONSTRUCTION call first. participantStruct->remoteObjectList.Insert(remoteObject.replica,remoteObject); } // Sends the download complete packet // If callDownloadCompleteCB is true then check all the remaining objects starting at commandListIndex // I scan every frame in case the callback returns false to delay, and after that time a new object is Replicated if (participantStruct->callDownloadCompleteCB) { bool anyHasConstruction; unsigned j; anyHasConstruction=false; for (j=0; j < participantStruct->commandList.Size(); j++) { if (participantStruct->commandList[j].command & REPLICA_EXPLICIT_CONSTRUCTION) { anyHasConstruction=true; break; } } // If none have REPLICA_EXPLICIT_CONSTRUCTION, send ID_REPLICA_MANAGER_DOWNLOAD_COMPLETE and set callDownloadCompleteCB false if (anyHasConstruction==false) { ReplicaReturnResult sendDLComplete; userDataBitstream.Reset(); if (_sendDownloadCompleteCB) sendDLComplete=_sendDownloadCompleteCB(&userDataBitstream, currentTime, participantStruct->playerId, this); // If you return false, this will be called again next update else sendDLComplete=REPLICA_CANCEL_PROCESS; if (sendDLComplete==REPLICA_PROCESSING_DONE) { outBitstream.Reset(); outBitstream.Write((unsigned char)ID_REPLICA_MANAGER_DOWNLOAD_COMPLETE); outBitstream.Write(&userDataBitstream, userDataBitstream.GetNumberOfBitsUsed()); peer->Send(&outBitstream, HIGH_PRIORITY, RELIABLE_ORDERED, sendChannel, participantStruct->playerId, false); participantStruct->callDownloadCompleteCB=false; } else if (sendDLComplete==REPLICA_CANCEL_PROCESS) { participantStruct->callDownloadCompleteCB=false; } else { assert(sendDLComplete==REPLICA_PROCESS_LATER); // else REPLICA_PROCESS_LATER } } } // The remaining commands, SendScopeChange and Serialize, require the object the command references exists on the remote system, so check that remoteObjectListIndex = participantStruct->remoteObjectList.GetIndexFromKey(replica, &objectExists); if (objectExists) { command = participantStruct->commandList[commandListIndex].command; // Process SendScopeChange. if ((command & (REPLICA_SCOPE_TRUE | REPLICA_SCOPE_FALSE))) { if (replica->GetNetworkID()==UNASSIGNED_NETWORK_ID) continue; // Not set yet so call this later. if (replicatedObjects[replicatedObjectsIndex].allowedInterfaces & REPLICA_SEND_SCOPE_CHANGE) { bool scopeTrue = (command & REPLICA_SCOPE_TRUE)!=0; // Only send scope changes if the requested change is different from what they already have if (participantStruct->remoteObjectList[remoteObjectListIndex].inScope!=scopeTrue) { userDataBitstream.Reset(); res=replica->SendScopeChange(scopeTrue, &userDataBitstream, currentTime, participantStruct->playerId); if (res==REPLICA_PROCESSING_DONE) { // If the user returns true and does write to outBitstream, do this send. Clear the scope change command. Then process the next command for this CommandStruct, if any. outBitstream.Reset(); outBitstream.Write((unsigned char)ID_REPLICA_MANAGER_SCOPE_CHANGE); outBitstream.Write(replica->GetNetworkID()); outBitstream.Write(&userDataBitstream, userDataBitstream.GetNumberOfBitsUsed()); peer->Send(&outBitstream, HIGH_PRIORITY, RELIABLE_ORDERED, sendChannel, participantStruct->playerId, false); // Set the scope for this object and system participantStruct->remoteObjectList[remoteObjectListIndex].inScope=scopeTrue; // If scope is true, turn on serialize, since you virtually always want to serialize when an object goes in scope participantStruct->commandList[commandListIndex].command |= REPLICA_SERIALIZE; // Turn off these bits - Call is processed participantStruct->commandList[commandListIndex].command &= 0xFF ^ (REPLICA_SCOPE_TRUE | REPLICA_SCOPE_FALSE); } else if (res==REPLICA_CANCEL_PROCESS) { // Turn off these bits - Call is canceled participantStruct->commandList[commandListIndex].command &= 0xFF ^ (REPLICA_SCOPE_TRUE | REPLICA_SCOPE_FALSE); } else { // If the user returns false and the scope is currently set to false, just continue with another CommandStruct. Don't process serialization until scoping is resolved first. if (scopeTrue==false) continue; // If the user returns false and the scope is currently set to false, process the next command for this CommandStruct, if any. } } } else { // Turn off these bits - Call is disallowed participantStruct->commandList[commandListIndex].command &= 0xFF ^ (REPLICA_SCOPE_TRUE | REPLICA_SCOPE_FALSE); // Set the scope - even if the actual send is disabled we might still be able to serialize. participantStruct->remoteObjectList[remoteObjectListIndex].inScope=(command & REPLICA_SCOPE_TRUE)!=0; } } command = participantStruct->commandList[commandListIndex].command; // Process Serialize if ((participantStruct->commandList[commandListIndex].command & REPLICA_SERIALIZE)) { if (replica->GetNetworkID()==UNASSIGNED_NETWORK_ID) continue; // Not set yet so call this later. // If scope is currently false for this object in the RemoteObject list, cancel this serialize as the scope changed before the serialization went out if (participantStruct->remoteObjectList[remoteObjectListIndex].inScope && (replicatedObjects[replicatedObjectsIndex].allowedInterfaces & REPLICA_SEND_SERIALIZE)) { do { userDataBitstream.Reset(); priority=HIGH_PRIORITY; reliability=RELIABLE_ORDERED; sendTimestamp=false; res=replica->Serialize(&sendTimestamp, &userDataBitstream, participantStruct->remoteObjectList[remoteObjectListIndex].lastSendTime, &priority, &reliability, currentTime, participantStruct->playerId); if (res==REPLICA_PROCESSING_DONE || res==REPLICA_PROCESS_AGAIN) { participantStruct->remoteObjectList[remoteObjectListIndex].lastSendTime=currentTime; outBitstream.Reset(); if (sendTimestamp) { outBitstream.Write((unsigned char)ID_TIMESTAMP); outBitstream.Write(currentTime); } outBitstream.Write((unsigned char)ID_REPLICA_MANAGER_SERIALIZE); outBitstream.Write(replica->GetNetworkID()); outBitstream.Write(&userDataBitstream, userDataBitstream.GetNumberOfBitsUsed()); peer->Send(&outBitstream, priority, reliability, sendChannel, participantStruct->playerId, false); // Clear the serialize bit when done if (res==REPLICA_PROCESSING_DONE) participantStruct->commandList[commandListIndex].command &= 0xFF ^ REPLICA_SERIALIZE; // else res==REPLICA_PROCESS_AGAIN so it will repeat the enclosing do {} while(); loop } else if (res==REPLICA_CANCEL_PROCESS) { // Clear the serialize bit participantStruct->commandList[commandListIndex].command &= 0xFF ^ REPLICA_SERIALIZE; } else { // if the user returns REPLICA_PROCESS_LATER, just continue with another CommandStruct. assert(res==REPLICA_PROCESS_LATER); } } while(res==REPLICA_PROCESS_AGAIN); } else { // Cancel this serialize participantStruct->commandList[commandListIndex].command &= 0xFF ^ REPLICA_SERIALIZE; } } } } // Go through the command list and delete all cleared commands, from back to front. It is more efficient to do this than to delete them as we process commandListIndex=participantStruct->commandList.Size(); if (commandListIndex>0) { #ifdef _MSC_VER #pragma warning( disable : 4127 ) // warning C4127: conditional expression is constant #endif while (1) { if (participantStruct->commandList[commandListIndex-1].command==0) { // If this is the last item in the list, and it probably is, then it just changes a number rather than shifts the entire array participantStruct->commandList.RemoveAtIndex(commandListIndex-1); } if (--commandListIndex==0) break; } } // Now process queued receives while (participantStruct->pendingCommands.Size()) { receivedCommand=participantStruct->pendingCommands.Pop(); participantStruct=GetParticipantByPlayerID(receivedCommand->playerId); if (participantStruct) { res=ProcessReceivedCommand(participantStruct, receivedCommand); // Returning false means process this command again later if (res==REPLICA_PROCESS_LATER) { // Push the command back in the queue participantStruct->pendingCommands.PushAtHead(receivedCommand); // Stop processing, because all processing is in order break; } else { assert(res==REPLICA_CANCEL_PROCESS); } } // Done with this command, so delete it delete receivedCommand->userData; delete receivedCommand; } } }
sim_results simrun_master( const sim_parameters& par,const mpi::communicator& mpicomm) { // ----- PREPARE SIMULATION ----- // assume something went wrong until we are sure it didn't sim_results res; res.success = false; // ----- RUN SIMULATION ----- Replica* rep = new Replica(par); if ( rep->prepare( par.init ) == false ) { delete rep; return res; } unsigned int finished_workers = 0; unsigned int scheduled_bins = 0; unsigned int completed_bins = 0; unsigned int enqueued_bins = par.bins; // define procedure to query the slaves for new work requests function<void()> mpiquery_work_requests( [&]() { while ( boost::optional<mpi::status> status = mpicomm.iprobe( mpi::any_source, MSGTAG_S_M_REQUEST_BINS ) ) { // receive the request and hand out new bins to the source mpicomm.recv( status->source(), MSGTAG_S_M_REQUEST_BINS ); if ( enqueued_bins > 0 ) { mpicomm.send( status->source(), MSGTAG_M_S_DISPATCHED_BINS, 1 ); scheduled_bins += 1; enqueued_bins -= 1; } else { mpicomm.send( status->source(), MSGTAG_M_S_DISPATCHED_BINS, 0 ); ++finished_workers; } } } ); // define procedure to query the slaves for finished work function<void()> mpiquery_finished_work( [&]() { while ( boost::optional<mpi::status> status = mpicomm.iprobe( mpi::any_source, 2 ) ) { mpicomm.recv( status->source(), 2 ); --scheduled_bins; ++completed_bins; } } ); cout << ":: Performing Monte Carlo cycle" << endl; cout << endl; cout << " Progress:" << endl; // perform dry runs to reach thermal equilibrium for(unsigned int mcs = 0; mcs < par.drysweeps; mcs++) { // take care of the slaves mpiquery_finished_work(); mpiquery_work_requests(); rep->mcs(); } unsigned int completed_bins_master = 0; std::vector<double> q2_binmeans; std::vector<double> q4_binmeans; while ( enqueued_bins > 0 ) { cout << '\r' << " Bin " << completed_bins << "/" << par.bins; cout.flush(); --enqueued_bins; ++scheduled_bins; // initialize binning array vector<double> q2_currentbin; vector<double> q4_currentbin; try { // try to allocate enough memory ... q2_currentbin.reserve( par.binwidth ); q4_currentbin.reserve( par.binwidth ); } catch ( bad_alloc ) { delete rep; return res; } for (unsigned int mcs = 0;mcs < par.binwidth;++mcs ) { // take care of the slaves mpiquery_finished_work(); mpiquery_work_requests(); // perform a Monte Carlo step rep->mcs(); // measure observables double q2 = 0, q4 = 0; double thissample_q = rep->Q(); // remember the sample's properties to calculate their mean value q2 = thissample_q * thissample_q; q4 = thissample_q * thissample_q * thissample_q * thissample_q; q2_currentbin.push_back(q2); q4_currentbin.push_back(q4); } q2_binmeans.push_back( accumulate( q2_currentbin.begin(), q2_currentbin.end(), 0.0 ) / static_cast<double>( q2_currentbin.size() ) ); q2_currentbin.clear(); --scheduled_bins; ++completed_bins_master; ++completed_bins; } ++finished_workers; while ( completed_bins != par.bins || static_cast<int>( finished_workers ) < mpicomm.size() ) { if ( boost::optional<mpi::status> status = mpicomm.iprobe( mpi::any_source, MSGTAG_S_M_FINISHED_BINS ) ) { mpicomm.recv( status->source(), MSGTAG_S_M_FINISHED_BINS ); --scheduled_bins; ++completed_bins; cout << "\n"; cout << '\r' << " Bin " << completed_bins << "/" << par.bins; cout.flush(); } if ( boost::optional<mpi::status> status = mpicomm.iprobe( mpi::any_source, MSGTAG_S_M_REQUEST_BINS ) ) { // receive the request for more work mpicomm.recv( status->source(), MSGTAG_S_M_REQUEST_BINS ); // tell him there is no more work mpicomm.send( status->source(), MSGTAG_M_S_DISPATCHED_BINS, 0 ); ++finished_workers; } } assert( enqueued_bins == 0 ); assert( scheduled_bins == 0 ); cout << '\r' << " Bin " << completed_bins << "/" << par.bins << endl; cout.flush(); // all measurements done ... let's tidy things up delete rep; assert( mpicomm.rank() == 0 ); vector< vector<double> > q2_binmeans_collector; mpi::gather( mpicomm, q2_binmeans, q2_binmeans_collector, 0 ); vector<double> q2_binmeans_all; for ( auto it = q2_binmeans_collector.begin(); it != q2_binmeans_collector.end(); ++it ) { q2_binmeans_all.insert( q2_binmeans_all.end(), it->begin(), it->end() ); } double q2 = 0, q4 = 0; q2 = static_cast<double>( accumulate( q2_binmeans_all.begin(), q2_binmeans_all.end(), 0.0 ) ) / static_cast<double>( q2_binmeans_all.size() ); double B = 0; B = (3 - q4 / (q2 * q2)) / 2; res.B = B; res.success = true; return res; }
void simrun_slave( const sim_parameters& par,const mpi::communicator& mpicomm) { Replica* rep = new Replica(par); if ( rep->prepare( par.init ) == false ) { delete rep; } // perform dry runs to reach thermal equilibrium rep->mcstep_dry( par.drysweeps ); unsigned int completed_bins_thisslave = 0; bool master_out_of_work = false; unsigned int scheduled_bins_thisslave; mpicomm.send( 0, MSGTAG_S_M_REQUEST_BINS ); mpicomm.recv( 0, MSGTAG_M_S_DISPATCHED_BINS, scheduled_bins_thisslave ); master_out_of_work = ( scheduled_bins_thisslave == 0 ); std::vector<double> q2_binmeans; std::vector<double> q4_binmeans; while ( scheduled_bins_thisslave > 0 ) { unsigned int new_scheduled_bins_thisslave; mpi::request master_answer; if ( !master_out_of_work ) { // ask the master for more work mpicomm.send( 0, MSGTAG_S_M_REQUEST_BINS ); master_answer = mpicomm.irecv( 0, MSGTAG_M_S_DISPATCHED_BINS, new_scheduled_bins_thisslave ); } // initialize binning array vector<double> q2_currentbin; vector<double> q4_currentbin; try { // try to allocate enough memory ... q2_currentbin.reserve( par.binwidth ); q4_currentbin.reserve( par.binwidth ); } catch ( bad_alloc ) { delete rep; } for (unsigned int mcs = 0;mcs < par.binwidth;++mcs ) { // perform a Monte Carlo step rep->mcs(); // measure observables double q2 = 0, q4 = 0; double thissample_q = rep->Q(); // remember the sample's properties to calculate their mean value q2 = thissample_q * thissample_q; q4 = thissample_q * thissample_q * thissample_q * thissample_q; q2_currentbin.push_back(q2); q4_currentbin.push_back(q4); } q2_binmeans.push_back( accumulate( q2_currentbin.begin(), q2_currentbin.end(), 0.0 ) / static_cast<double>( q2_currentbin.size() ) ); q2_currentbin.clear(); // report completion of the work mpicomm.send( 0, 2 ); ++completed_bins_thisslave; --scheduled_bins_thisslave; if ( !master_out_of_work ) { // wait for answer from master concerning the next bin master_answer.wait(); if ( new_scheduled_bins_thisslave == 1 ) { ++scheduled_bins_thisslave; } else { master_out_of_work = true; } } } assert( mpicomm.rank() != 0 ); mpi::gather( mpicomm, q2_binmeans, 0 ); return; }
virtual void SetUp() { oneSM_2.create(sm2_name, sm2_initstate); }
ReplicaReturnResult ReplicaManager::ProcessReceivedCommand(ParticipantStruct *participantStruct, ReceivedCommand *receivedCommand) { (void) participantStruct; // If this assert hits you didn't first call RakPeer::SetNetworkIDManager as required. RakAssert(rakPeerInterface->GetNetworkIDManager()); if (rakPeerInterface->GetNetworkIDManager()==0) return REPLICA_CANCEL_PROCESS; Replica *replica = (Replica*) rakPeerInterface->GetNetworkIDManager()->GET_BASE_OBJECT_FROM_ID(receivedCommand->networkID); bool objectExists; unsigned index=0; ReplicaReturnResult b; if (replica) { index = replicatedObjects.GetIndexFromKey(replica, &objectExists); if (objectExists==false) { if (receivedCommand->command==ID_REPLICA_MANAGER_CONSTRUCTION) { // Object already exists with this ID, but call construction anyway #ifdef _DEBUG RakAssert(_constructionCB); #endif // Call the registered callback. If it crashes, you forgot to register the callback in SetReceiveConstructionCB return _constructionCB->ReceiveConstruction(receivedCommand->userData, receivedCommand->u1, receivedCommand->networkID, replica, receivedCommand->systemAddress, this); } else { // This networkID is already in use but ReferencePointer was never called on it. // RakAssert(0); return REPLICA_CANCEL_PROCESS; } } } if (receivedCommand->command==ID_REPLICA_MANAGER_SERIALIZE) { if (replica && (replicatedObjects[index].allowedInterfaces & REPLICA_RECEIVE_SERIALIZE)) { b=replica->Deserialize(receivedCommand->userData, receivedCommand->u1, replicatedObjects[index].lastDeserializeTrue, receivedCommand->systemAddress); if (b==REPLICA_PROCESSING_DONE) replicatedObjects[index].lastDeserializeTrue=RakNet::GetTime(); return b; } } else if (receivedCommand->command==ID_REPLICA_MANAGER_CONSTRUCTION) { // If networkID already exists on this system, ignore the packet #ifdef _DEBUG RakAssert(_constructionCB); #endif // Call the registered callback. If it crashes, you forgot to register the callback in SetReceiveConstructionCB return _constructionCB->ReceiveConstruction(receivedCommand->userData, receivedCommand->u1, receivedCommand->networkID, replica, receivedCommand->systemAddress, this); } else if (receivedCommand->command==ID_REPLICA_MANAGER_SCOPE_CHANGE) { if (replica && (replicatedObjects[index].allowedInterfaces & REPLICA_RECEIVE_SCOPE_CHANGE)) { return replica->ReceiveScopeChange(receivedCommand->userData, receivedCommand->systemAddress, receivedCommand->u1); } } else if (receivedCommand->command==ID_REPLICA_MANAGER_DESTRUCTION) { if (replica && (replicatedObjects[index].allowedInterfaces & REPLICA_RECEIVE_DESTRUCTION)) { return replica->ReceiveDestruction(receivedCommand->userData, receivedCommand->systemAddress, receivedCommand->u1); } } else if (receivedCommand->command==ID_REPLICA_MANAGER_DOWNLOAD_COMPLETE) { if (_receiveDownloadCompleteCB) { return _receiveDownloadCompleteCB->ReceiveDownloadComplete(receivedCommand->userData, receivedCommand->systemAddress, this); } } return REPLICA_CANCEL_PROCESS; }
int main(int argc, char **argv) { cout << "usage: pdbgen <indexfile> <boxdim> [0/1: reverse drms cal] [1: outputcrowders crowders]" << endl; AminoAcids aminoAcidData; cout << "Loading amino acid data. "; aminoAcidData.loadAminoAcidData(AMINOACIDDATASOURCE); cout << "Done." << endl; cout << "Loading pair lookup table. " << endl; aminoAcidData.loadLJPotentialData(LJPDSOURCE); cout << "Done." << endl; vector<Replica> Conformations; Replica initalReplica; initalReplica.setAminoAcidData(aminoAcidData); initalReplica.reserveConiguousMoleculeArray(30); Replica reference; reference.setAminoAcidData(aminoAcidData); char *indexfilename = new char[256]; char *savefilename = new char[256]; char *datafilename = new char[256]; char *drmsEfilename = new char[256]; float boundary(atof(argv[2])); cout << "File: " << argv[1] << endl; cout << "Bounding box size: " << boundary << "A**3" << endl; bool printCrowders(false); bool reversedrms=false; if (argc > 3) { if (argv[3][0]=='1') reversedrms = true; } if (argc > 4) { if (argv[4][0]=='1') printCrowders = true; } strcpy(indexfilename,argv[1]); char * strstrresult = strstr(indexfilename,"fileindex"); if (strstrresult==NULL) { cout << "You must provide and index file as the input" << endl; exit(0); } ifstream indexfile(indexfilename); if (!indexfile.good()) { cout << "Failed to open file: " << indexfilename << endl; exit(0); } char line[512] = {0}; int loadcount = 0; float max_d = 0; while (!indexfile.eof()) { indexfile.getline(line,512); int index; char crowder; int result = sscanf(line,"%d %s %c",&index,datafilename,&crowder); if (result==3) { if (crowder=='N' || (crowder=='Y' && printCrowders)) { cout << "load : " << datafilename << endl; initalReplica.loadMolecule(datafilename); reference.loadMolecule(datafilename); if (loadcount > 0) { Vector3f c = initalReplica.molecules[initalReplica.moleculeCount-1].position; for(int i=0;i<initalReplica.molecules[initalReplica.moleculeCount-1].residueCount;i++) { Vector3f r = initalReplica.molecules[initalReplica.moleculeCount-1].Residues[i].position; max_d = max((c-r).magnitude(),max_d); } } loadcount++; } } } cout << "finished loading" << endl; indexfile.close(); memset(datafilename,0,256); strncpy(datafilename,indexfilename,strlen(indexfilename)-strlen("fileindex")); strcat(datafilename,"boundconformations"); memset(drmsEfilename,0,256); strncpy(drmsEfilename,indexfilename,strlen(indexfilename)-strlen("fileindex")); strcat(drmsEfilename,"drms.dat"); int iteration; float energy; // system energy float temperature; float energyC; // complex energy int samples = 0; ifstream datafile(datafilename); if (!datafile.good()) { cout << "Failed to open file: " << datafilename << endl; exit(0); } else { cout << "loading data: "<< datafilename << endl; } //ofstream drmslog(drmsEfilename); //drmslog.precision(7); //first 2 lines contain nothing datafile.getline(line,512); datafile.getline(line,512); // next lines are in sets of the number of non crowders // 501000; -9.18593; 5.3; 297.6 // 0 0: -0.258606 -0.929792 -0.256388 -0.053619 7.369041 103.941734 91.936638 // 0 1: -0.055370 -0.464538 -0.429429 0.772482 7.673889 89.995583 96.419502 char savename[256]; int instanceNo = 0; while (!datafile.eof()) { datafile.getline(line,512); //cout << "line: "<< line << endl; //int result = sscanf(line,"%d; %f; %f; %f;",&iteration,&energy,&distance,&temperature); int result = sscanf(line,"%d; %f (%f); %f;",&iteration,&energy,&energyC,&temperature); //int result = sscanf(line,"%d; %f; %f;",&iteration,&energy,&temperature); initalReplica.temperature = temperature; initalReplica.potential = energy; if (abs(temperature-300.0f)<1.0f && iteration>10000000) // if the instance is at 300K and more than 1m iterations are done { Quaternion rotation0; Vector3f vrotation0; Vector3f position0; Replica instance; instance.copy(initalReplica); for (int i=0;i<instance.moleculeCount;i++) { datafile.getline(line,512); Quaternion rotationi; Vector3f positioni; Vector3f vrotationi; int mno; int crowderyn; //cout << line << endl; char * token = strtok(line, ":"); sscanf(token,"%d %d",&crowderyn,&mno); // new format if (crowderyn==1 && !printCrowders) continue; // ignore crowders rotationi.w = atof(strtok(NULL, " ")); rotationi.x = atof(strtok(NULL, " ")); rotationi.y = atof(strtok(NULL, " ")); rotationi.z = atof(strtok(NULL, " ")); positioni.x = atof(strtok(NULL, " ")); positioni.y = atof(strtok(NULL, " ")); positioni.z = atof(strtok(NULL, " ")); rotationi.normalize(); instance.molecules[i].setRotation(rotationi); if (crowderyn==0) // only two in the simulation { Vector3f v = positioni - instance.molecules[0].position; positioni.x -= boundary * round(v.x/boundary); positioni.y -= boundary * round(v.y/boundary); positioni.z -= boundary * round(v.z/boundary); } instance.molecules[i].setPosition(positioni); } memset(savename,0,256); instanceNo++; sprintf(savename, "pdbgen_results/sample_%d_%0.1fK_%5.2f.pdb",instanceNo,temperature,energy); //if (energy < -70.0) instance.saveAsSinglePDB(savename); //double drms(DRMS(&instance,&reference,reversedrms)); //drmslog << energy << " " << drms << endl; cout << "Saved frame " << instanceNo << ": " << savename << endl; } } datafile.close(); //drmslog.close(); cout << "Exiting..." << endl; return 0; }