<commit_before>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

/* $Id$ */

///////////////////////////////////////////////////////////////////////////////
// Class AliPHOSCalibHistoProducer accumulating histograms
// with amplitudes per PHOS channel
// It is intended to run at DAQ computers (LDC, GDC, HLT or MOOD)
// and it fills the histograms with amplitudes per channel.
// Usage example see in PHOS/macros/Shuttle/AliPHOSCalibHistoProducer.C
//
// Author: Boris Polichtchouk, 4 October 2006
///////////////////////////////////////////////////////////////////////////////

#include "AliLog.h"
#include "AliPHOSCalibHistoProducer.h"
#include "TH1.h"
#include "TH2F.h"
#include "TFile.h"
#include "AliPHOSRawDecoder.h"

ClassImp(AliPHOSCalibHistoProducer)

//-----------------------------------------------------------------------------
AliPHOSCalibHistoProducer::AliPHOSCalibHistoProducer() :
  fRawDecoder(0),fHistoFile(0),fUpdatingRate(100),fIsOldRCUFormat(kFALSE),
  fEvents(0),fNbins(100),fXlow(0.),fXup(1000.)
{
  // Constructor: initializes data members
  // Checks existence of histograms which might have been left
  // from the previous runs to continues their filling

  fHistoFile =  new TFile("calibHisto.root","update");

  for(Int_t module=0; module<5; module++) {
    for(Int_t column=0; column<56; column++) {
      for(Int_t row=0; row<64; row++) {
	char hname[128];
	sprintf(hname,"mod%dcol%drow%d",module,column,row);
	TH1F* hist = (TH1F*)fHistoFile->Get(hname);
	if(hist)
	  fAmpHisto[module][column][row]=hist;
	else
	  fAmpHisto[module][column][row] = 0;
      }
    }
  }
}

//-----------------------------------------------------------------------------
AliPHOSCalibHistoProducer::AliPHOSCalibHistoProducer(Int_t nbinsx, Double_t xlow, Double_t xup) :
  fRawDecoder(0),fHistoFile(0),fUpdatingRate(100),fIsOldRCUFormat(kFALSE),
  fEvents(0),fNbins(nbinsx),fXlow(xlow),fXup(xup)
{
  // Constructor: initializes data members.
  // Checks existence of histograms which might have been left
  // from the previous runs to continues their filling.
  // In addition sets number of bins, low and upper limits common for all histograms.

  fHistoFile =  new TFile("calibHisto.root","update");

  for(Int_t module=0; module<5; module++) {
    for(Int_t column=0; column<56; column++) {
      for(Int_t row=0; row<64; row++) {
        char hname[128];
        sprintf(hname,"mod%dcol%drow%d",module,column,row);
        TH1F* hist = (TH1F*)fHistoFile->Get(hname);
        if(hist)
          fAmpHisto[module][column][row]=hist;
        else
          fAmpHisto[module][column][row] = 0;
      }
    }
  }
}

//-----------------------------------------------------------------------------
AliPHOSCalibHistoProducer::~AliPHOSCalibHistoProducer()
{
  // Destructor

  UpdateHistoFile();
  if(fHistoFile) delete fHistoFile;

}

//-----------------------------------------------------------------------------
AliPHOSCalibHistoProducer::AliPHOSCalibHistoProducer(const AliPHOSCalibHistoProducer &histoproducer) :
  TObject(histoproducer),fRawDecoder(histoproducer.fRawDecoder),fHistoFile(histoproducer.fHistoFile),
  fUpdatingRate(histoproducer.fUpdatingRate),fIsOldRCUFormat(histoproducer.fIsOldRCUFormat),
  fEvents(histoproducer.fEvents),fNbins(histoproducer.fNbins),fXlow(histoproducer.fXlow),fXup(histoproducer.fXup)
{
  //Copy constructor.

  for(Int_t module=0; module<5; module++) {
    for(Int_t column=0; column<56; column++) {
      for(Int_t row=0; row<64; row++) {
	char hname[128];
	sprintf(hname,"mod%dcol%drow%d",module,column,row);
	TH1F* hist = (TH1F*)histoproducer.fHistoFile->Get(hname);
	if(hist)
	  fAmpHisto[module][column][row]= new TH1F(*hist);
	else
	  fAmpHisto[module][column][row]=0;
      }
    }
  }
}

//-----------------------------------------------------------------------------
AliPHOSCalibHistoProducer& AliPHOSCalibHistoProducer::operator=
(const AliPHOSCalibHistoProducer &histoproducer)
{
  //Assignment operator.

  if(this != &histoproducer) {

    fRawDecoder = histoproducer.fRawDecoder;
    fHistoFile = histoproducer.fHistoFile;
    fUpdatingRate = histoproducer.fUpdatingRate;
    fIsOldRCUFormat = histoproducer.fIsOldRCUFormat;
    fEvents = histoproducer.fEvents;
    fEvents = histoproducer.fEvents;
    fNbins = histoproducer.fNbins;
    fXlow = histoproducer.fXlow;
    fXup = histoproducer.fXup;

    for(Int_t module=0; module<5; module++) {
      for(Int_t column=0; column<56; column++) {
	for(Int_t row=0; row<64; row++) {
	  if(fAmpHisto[module][column][row]){
	    delete fAmpHisto[module][column][row];
	    fAmpHisto[module][column][row] = histoproducer.fAmpHisto[module][column][row];
	  }
	  else
	  fAmpHisto[module][column][row] = histoproducer.fAmpHisto[module][column][row];
	}
      }
    }

  }

  return *this;
}
//-----------------------------------------------------------------------------
void AliPHOSCalibHistoProducer::Run()
{
  // Reads raw data of current event and fills amplitude histograms
  // The histograms are written to file every fUpdatingRate events

  if(!fRawDecoder) AliFatal("Raw decoder not set!");

  Double_t energy;
  Int_t mod,col,row;

  if(fIsOldRCUFormat)
    fRawDecoder->SetOldRCUFormat(kTRUE);

  while(fRawDecoder->NextDigit()) {

    if(fRawDecoder->IsLowGain()) continue;

    energy = fRawDecoder->GetEnergy();

    mod = fRawDecoder->GetModule()-1;
    col = fRawDecoder->GetColumn()-1;
    row = fRawDecoder->GetRow()-1;

    if(fAmpHisto[mod][col][row]) {
      fAmpHisto[mod][col][row]->Fill(energy);
    }
    else {
      char hname[128];
      sprintf(hname,"mod%dcol%drow%d",mod,col,row);
      fAmpHisto[mod][col][row] = new TH1F(hname,hname,fNbins,fXlow,fXup);
      fAmpHisto[mod][col][row]->Fill(energy);
    }
  }
    // update histograms in local file every 100th event
    if(fEvents != 0 && fEvents%fUpdatingRate == 0) {
      AliInfo(Form("Updating histo file, event %d, run %d\n",
		   fEvents,fRawDecoder->GetRawReader()->GetRunNumber()));
      UpdateHistoFile();
    }

    //   UpdateHistoFile();
    //   AliInfo(Form("%d events of run %d processed.",iEvent,runNum));

  fEvents++;

}

//-----------------------------------------------------------------------------
void AliPHOSCalibHistoProducer::UpdateHistoFile()
{
  // Write histograms to file

  if(!fHistoFile) return;
  if(!fHistoFile->IsOpen()) return;

  TH1F* hist=0;
  char hname[128];
  char htitle[128];

  for(Int_t module=0; module<5; module++) {
    sprintf(hname,"hMeanE%d",module);
    sprintf(htitle,"Mean energies in module %d",module);
    TH2F hMeanE(hname,htitle,56,0.,56.,64,0.,64);

    for(Int_t column=0; column<56; column++) {
      for(Int_t row=0; row<64; row++) {
	hist = fAmpHisto[module][column][row];
	if(hist) hist->Write(hist->GetName(),TObject::kWriteDelete);
	if(hist) hMeanE.SetBinContent(column,row,hist->GetMean());
      }
    }
    hMeanE.Write(hMeanE.GetName(),TObject::kWriteDelete);
  }

}
<commit_msg>#include added<commit_after>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

/* $Id$ */

///////////////////////////////////////////////////////////////////////////////
// Class AliPHOSCalibHistoProducer accumulating histograms
// with amplitudes per PHOS channel
// It is intended to run at DAQ computers (LDC, GDC, HLT or MOOD)
// and it fills the histograms with amplitudes per channel.
// Usage example see in PHOS/macros/Shuttle/AliPHOSCalibHistoProducer.C
//
// Author: Boris Polichtchouk, 4 October 2006
///////////////////////////////////////////////////////////////////////////////

#include "AliLog.h"
#include "AliPHOSCalibHistoProducer.h"
#include "TH1.h"
#include "TH2F.h"
#include "TFile.h"
#include "AliPHOSRawDecoder.h"
#include "AliRawReader.h"

ClassImp(AliPHOSCalibHistoProducer)

//-----------------------------------------------------------------------------
AliPHOSCalibHistoProducer::AliPHOSCalibHistoProducer() :
  fRawDecoder(0),fHistoFile(0),fUpdatingRate(100),fIsOldRCUFormat(kFALSE),
  fEvents(0),fNbins(100),fXlow(0.),fXup(1000.)
{
  // Constructor: initializes data members
  // Checks existence of histograms which might have been left
  // from the previous runs to continues their filling

  fHistoFile =  new TFile("calibHisto.root","update");

  for(Int_t module=0; module<5; module++) {
    for(Int_t column=0; column<56; column++) {
      for(Int_t row=0; row<64; row++) {
	char hname[128];
	sprintf(hname,"mod%dcol%drow%d",module,column,row);
	TH1F* hist = (TH1F*)fHistoFile->Get(hname);
	if(hist)
	  fAmpHisto[module][column][row]=hist;
	else
	  fAmpHisto[module][column][row] = 0;
      }
    }
  }
}

//-----------------------------------------------------------------------------
AliPHOSCalibHistoProducer::AliPHOSCalibHistoProducer(Int_t nbinsx, Double_t xlow, Double_t xup) :
  fRawDecoder(0),fHistoFile(0),fUpdatingRate(100),fIsOldRCUFormat(kFALSE),
  fEvents(0),fNbins(nbinsx),fXlow(xlow),fXup(xup)
{
  // Constructor: initializes data members.
  // Checks existence of histograms which might have been left
  // from the previous runs to continues their filling.
  // In addition sets number of bins, low and upper limits common for all histograms.

  fHistoFile =  new TFile("calibHisto.root","update");

  for(Int_t module=0; module<5; module++) {
    for(Int_t column=0; column<56; column++) {
      for(Int_t row=0; row<64; row++) {
        char hname[128];
        sprintf(hname,"mod%dcol%drow%d",module,column,row);
        TH1F* hist = (TH1F*)fHistoFile->Get(hname);
        if(hist)
          fAmpHisto[module][column][row]=hist;
        else
          fAmpHisto[module][column][row] = 0;
      }
    }
  }
}

//-----------------------------------------------------------------------------
AliPHOSCalibHistoProducer::~AliPHOSCalibHistoProducer()
{
  // Destructor

  UpdateHistoFile();
  if(fHistoFile) delete fHistoFile;

}

//-----------------------------------------------------------------------------
AliPHOSCalibHistoProducer::AliPHOSCalibHistoProducer(const AliPHOSCalibHistoProducer &histoproducer) :
  TObject(histoproducer),fRawDecoder(histoproducer.fRawDecoder),fHistoFile(histoproducer.fHistoFile),
  fUpdatingRate(histoproducer.fUpdatingRate),fIsOldRCUFormat(histoproducer.fIsOldRCUFormat),
  fEvents(histoproducer.fEvents),fNbins(histoproducer.fNbins),fXlow(histoproducer.fXlow),fXup(histoproducer.fXup)
{
  //Copy constructor.

  for(Int_t module=0; module<5; module++) {
    for(Int_t column=0; column<56; column++) {
      for(Int_t row=0; row<64; row++) {
	char hname[128];
	sprintf(hname,"mod%dcol%drow%d",module,column,row);
	TH1F* hist = (TH1F*)histoproducer.fHistoFile->Get(hname);
	if(hist)
	  fAmpHisto[module][column][row]= new TH1F(*hist);
	else
	  fAmpHisto[module][column][row]=0;
      }
    }
  }
}

//-----------------------------------------------------------------------------
AliPHOSCalibHistoProducer& AliPHOSCalibHistoProducer::operator=
(const AliPHOSCalibHistoProducer &histoproducer)
{
  //Assignment operator.

  if(this != &histoproducer) {

    fRawDecoder = histoproducer.fRawDecoder;
    fHistoFile = histoproducer.fHistoFile;
    fUpdatingRate = histoproducer.fUpdatingRate;
    fIsOldRCUFormat = histoproducer.fIsOldRCUFormat;
    fEvents = histoproducer.fEvents;
    fEvents = histoproducer.fEvents;
    fNbins = histoproducer.fNbins;
    fXlow = histoproducer.fXlow;
    fXup = histoproducer.fXup;

    for(Int_t module=0; module<5; module++) {
      for(Int_t column=0; column<56; column++) {
	for(Int_t row=0; row<64; row++) {
	  if(fAmpHisto[module][column][row]){
	    delete fAmpHisto[module][column][row];
	    fAmpHisto[module][column][row] = histoproducer.fAmpHisto[module][column][row];
	  }
	  else
	  fAmpHisto[module][column][row] = histoproducer.fAmpHisto[module][column][row];
	}
      }
    }

  }

  return *this;
}
//-----------------------------------------------------------------------------
void AliPHOSCalibHistoProducer::Run()
{
  // Reads raw data of current event and fills amplitude histograms
  // The histograms are written to file every fUpdatingRate events

  if(!fRawDecoder) AliFatal("Raw decoder not set!");

  Double_t energy;
  Int_t mod,col,row;

  if(fIsOldRCUFormat)
    fRawDecoder->SetOldRCUFormat(kTRUE);

  while(fRawDecoder->NextDigit()) {

    if(fRawDecoder->IsLowGain()) continue;

    energy = fRawDecoder->GetEnergy();

    mod = fRawDecoder->GetModule()-1;
    col = fRawDecoder->GetColumn()-1;
    row = fRawDecoder->GetRow()-1;

    if(fAmpHisto[mod][col][row]) {
      fAmpHisto[mod][col][row]->Fill(energy);
    }
    else {
      char hname[128];
      sprintf(hname,"mod%dcol%drow%d",mod,col,row);
      fAmpHisto[mod][col][row] = new TH1F(hname,hname,fNbins,fXlow,fXup);
      fAmpHisto[mod][col][row]->Fill(energy);
    }
  }
    // update histograms in local file every 100th event
    if(fEvents != 0 && fEvents%fUpdatingRate == 0) {
      AliInfo(Form("Updating histo file, event %d, run %d\n",
		   fEvents,fRawDecoder->GetRawReader()->GetRunNumber()));
      UpdateHistoFile();
    }

    //   UpdateHistoFile();
    //   AliInfo(Form("%d events of run %d processed.",iEvent,runNum));

  fEvents++;

}

//-----------------------------------------------------------------------------
void AliPHOSCalibHistoProducer::UpdateHistoFile()
{
  // Write histograms to file

  if(!fHistoFile) return;
  if(!fHistoFile->IsOpen()) return;

  TH1F* hist=0;
  char hname[128];
  char htitle[128];

  for(Int_t module=0; module<5; module++) {
    sprintf(hname,"hMeanE%d",module);
    sprintf(htitle,"Mean energies in module %d",module);
    TH2F hMeanE(hname,htitle,56,0.,56.,64,0.,64);

    for(Int_t column=0; column<56; column++) {
      for(Int_t row=0; row<64; row++) {
	hist = fAmpHisto[module][column][row];
	if(hist) hist->Write(hist->GetName(),TObject::kWriteDelete);
	if(hist) hMeanE.SetBinContent(column,row,hist->GetMean());
      }
    }
    hMeanE.Write(hMeanE.GetName(),TObject::kWriteDelete);
  }

}
<|endoftext|>


<commit_before>/* Copyright (c) 2010 Stanford University
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include "CoordinatorClient.h"
#include "ProtoBuf.h"

namespace RAMCloud {

/**
 * Create a new table.
 *
 * \param name
 *      Name for the new table (NULL-terminated string).
 *
 * \exception InternalError
 */
void
CoordinatorClient::createTable(const char* name)
{
    Buffer req;
    uint32_t length = strlen(name) + 1;
    CreateTableRpc::Request& reqHdr(allocHeader<CreateTableRpc>(req));
    reqHdr.nameLength = length;
    memcpy(new(&req, APPEND) char[length], name, length);
    while (true) {
        Buffer resp;
        sendRecv<CreateTableRpc>(session, req, resp);
        try {
            checkStatus(HERE);
            return;
        } catch (const RetryException& e) {
            LOG(DEBUG, "RETRY trying to create table");
            yield();
        }
    }
}

/**
 * Delete a table.
 *
 * All objects in the table are implicitly deleted, along with any
 * other information associated with the table (such as, someday,
 * indexes).  If the table does not currently exist than the operation
 * returns successfully without actually doing anything.
 *
 * \param name
 *      Name of the table to delete (NULL-terminated string).
 *
 * \exception InternalError
 */
void
CoordinatorClient::dropTable(const char* name)
{
    Buffer req, resp;
    uint32_t length = strlen(name) + 1;
    DropTableRpc::Request& reqHdr(allocHeader<DropTableRpc>(req));
    reqHdr.nameLength = length;
    memcpy(new(&req, APPEND) char[length], name, length);
    sendRecv<DropTableRpc>(session, req, resp);
    checkStatus(HERE);
}

/**
 * Look up a table by name and return a small integer handle that
 * can be used to access the table.
 *
 * \param name
 *      Name of the desired table (NULL-terminated string).
 *
 * \return
 *      The return value is an identifier for the table; this is used
 *      instead of the table's name for most RAMCloud operations
 *      involving the table.
 *
 * \exception TableDoesntExistException
 * \exception InternalError
 */
uint32_t
CoordinatorClient::openTable(const char* name)
{
    Buffer req, resp;
    uint32_t length = strlen(name) + 1;
    OpenTableRpc::Request& reqHdr(allocHeader<OpenTableRpc>(req));
    reqHdr.nameLength = length;
    memcpy(new(&req, APPEND) char[length], name, length);
    const OpenTableRpc::Response& respHdr(
        sendRecv<OpenTableRpc>(session, req, resp));
    checkStatus(HERE);
    return respHdr.tableId;
}

/**
 * Servers call this when they come online to beg for work.
 * \return
 *      A server ID guaranteed never to have been used before.
 */
uint64_t
CoordinatorClient::enlistServer(ServerType serverType,
                                string localServiceLocator)
{
    while (true) {
        try {
            Buffer req;
            Buffer resp;
            EnlistServerRpc::Request& reqHdr(
                allocHeader<EnlistServerRpc>(req));
            reqHdr.serverType = serverType;
            reqHdr.serviceLocatorLength = localServiceLocator.length() + 1;
            strncpy(new(&req, APPEND) char[reqHdr.serviceLocatorLength],
                    localServiceLocator.c_str(),
                    reqHdr.serviceLocatorLength);
            const EnlistServerRpc::Response& respHdr(
                sendRecv<EnlistServerRpc>(session, req, resp));
            checkStatus(HERE);
            return respHdr.serverId;
        } catch (TransportException& e) {
            LOG(NOTICE,
                "TransportException trying to talk to coordinator: %s",
                e.str().c_str());
            LOG(NOTICE, "retrying");
            yield();
        }
    }
}

/**
 * List all live backup servers.
 * Masters call and cache this periodically to find backups.
 */
void
CoordinatorClient::getBackupList(ProtoBuf::ServerList& serverList)
{
    Buffer req;
    Buffer resp;
    allocHeader<GetBackupListRpc>(req);
    const GetBackupListRpc::Response& respHdr(
        sendRecv<GetBackupListRpc>(session, req, resp));
    checkStatus(HERE);
    ProtoBuf::parseFromResponse(resp, sizeof(respHdr),
                                respHdr.serverListLength, serverList);
}

/**
 * Return the entire tablet map.
 * Clients use this to find objects.
 * If the returned data becomes too big, we should add parameters to
 * specify a subrange.
 * \param[out] tabletMap
 *      Each tablet has a service locator string describing where to find
 *      its master.
 */
void
CoordinatorClient::getTabletMap(ProtoBuf::Tablets& tabletMap)
{
    Buffer req;
    Buffer resp;
    allocHeader<GetTabletMapRpc>(req);
    const GetTabletMapRpc::Response& respHdr(
        sendRecv<GetTabletMapRpc>(session, req, resp));
    checkStatus(HERE);
    ProtoBuf::parseFromResponse(resp, sizeof(respHdr),
                                respHdr.tabletMapLength, tabletMap);
}

/**
 * Report a slow or dead server.
 */
void
CoordinatorClient::hintServerDown(string serviceLocator)
{
    Buffer req;
    Buffer resp;
    HintServerDownRpc::Request& reqHdr(
        allocHeader<HintServerDownRpc>(req));
    reqHdr.serviceLocatorLength = serviceLocator.length() + 1;
    strncpy(new(&req, APPEND) char[reqHdr.serviceLocatorLength],
            serviceLocator.c_str(),
            reqHdr.serviceLocatorLength);
    sendRecv<HintServerDownRpc>(session, req, resp);
    checkStatus(HERE);
}

/**
 * \copydoc MasterClient::ping
 */
void
CoordinatorClient::ping()
{
    Buffer req;
    Buffer resp;
    allocHeader<PingRpc>(req);
    sendRecv<PingRpc>(session, req, resp);
    checkStatus(HERE);
}

/**
 * Tell the coordinator that recovery of a particular tablets have
 * been recovered on the master who is calling.
 *
 * \param tablets
 *      The tablets which form a partition of a will which are
 *      now done recovering.
 */
void
CoordinatorClient::tabletsRecovered(const ProtoBuf::Tablets& tablets)
{
    Buffer req, resp;
    TabletsRecoveredRpc::Request& reqHdr(allocHeader<TabletsRecoveredRpc>(req));
    reqHdr.tabletsLength = serializeToResponse(req, tablets);
    sendRecv<TabletsRecoveredRpc>(session, req, resp);
    checkStatus(HERE);
}

} // namespace RAMCloud
<commit_msg>Expand CoordinatorClient docs<commit_after>/* Copyright (c) 2010 Stanford University
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include "CoordinatorClient.h"
#include "ProtoBuf.h"

namespace RAMCloud {

/**
 * Create a new table.
 *
 * \param name
 *      Name for the new table (NULL-terminated string).
 *
 * \exception InternalError
 */
void
CoordinatorClient::createTable(const char* name)
{
    Buffer req;
    uint32_t length = strlen(name) + 1;
    CreateTableRpc::Request& reqHdr(allocHeader<CreateTableRpc>(req));
    reqHdr.nameLength = length;
    memcpy(new(&req, APPEND) char[length], name, length);
    while (true) {
        Buffer resp;
        sendRecv<CreateTableRpc>(session, req, resp);
        try {
            checkStatus(HERE);
            return;
        } catch (const RetryException& e) {
            LOG(DEBUG, "RETRY trying to create table");
            yield();
        }
    }
}

/**
 * Delete a table.
 *
 * All objects in the table are implicitly deleted, along with any
 * other information associated with the table (such as, someday,
 * indexes).  If the table does not currently exist than the operation
 * returns successfully without actually doing anything.
 *
 * \param name
 *      Name of the table to delete (NULL-terminated string).
 *
 * \exception InternalError
 */
void
CoordinatorClient::dropTable(const char* name)
{
    Buffer req, resp;
    uint32_t length = strlen(name) + 1;
    DropTableRpc::Request& reqHdr(allocHeader<DropTableRpc>(req));
    reqHdr.nameLength = length;
    memcpy(new(&req, APPEND) char[length], name, length);
    sendRecv<DropTableRpc>(session, req, resp);
    checkStatus(HERE);
}

/**
 * Look up a table by name and return a small integer handle that
 * can be used to access the table.
 *
 * \param name
 *      Name of the desired table (NULL-terminated string).
 *
 * \return
 *      The return value is an identifier for the table; this is used
 *      instead of the table's name for most RAMCloud operations
 *      involving the table.
 *
 * \exception TableDoesntExistException
 * \exception InternalError
 */
uint32_t
CoordinatorClient::openTable(const char* name)
{
    Buffer req, resp;
    uint32_t length = strlen(name) + 1;
    OpenTableRpc::Request& reqHdr(allocHeader<OpenTableRpc>(req));
    reqHdr.nameLength = length;
    memcpy(new(&req, APPEND) char[length], name, length);
    const OpenTableRpc::Response& respHdr(
        sendRecv<OpenTableRpc>(session, req, resp));
    checkStatus(HERE);
    return respHdr.tableId;
}

/**
 * Servers call this when they come online to beg for work.
 * \param serverType
 *      Master, etc.
 * \param localServiceLocator
 *      The service locator describing how other hosts can contact the server.
 * \return
 *      A server ID guaranteed never to have been used before.
 */
uint64_t
CoordinatorClient::enlistServer(ServerType serverType,
                                string localServiceLocator)
{
    while (true) {
        try {
            Buffer req;
            Buffer resp;
            EnlistServerRpc::Request& reqHdr(
                allocHeader<EnlistServerRpc>(req));
            reqHdr.serverType = serverType;
            reqHdr.serviceLocatorLength = localServiceLocator.length() + 1;
            strncpy(new(&req, APPEND) char[reqHdr.serviceLocatorLength],
                    localServiceLocator.c_str(),
                    reqHdr.serviceLocatorLength);
            const EnlistServerRpc::Response& respHdr(
                sendRecv<EnlistServerRpc>(session, req, resp));
            checkStatus(HERE);
            return respHdr.serverId;
        } catch (TransportException& e) {
            LOG(NOTICE,
                "TransportException trying to talk to coordinator: %s",
                e.str().c_str());
            LOG(NOTICE, "retrying");
            yield();
        }
    }
}

/**
 * List all live backup servers.
 * Masters call and cache this periodically to find backups.
 * \param[out] serverList
 *      An empty ServerList that will be filled with current backup servers.
 */
void
CoordinatorClient::getBackupList(ProtoBuf::ServerList& serverList)
{
    Buffer req;
    Buffer resp;
    allocHeader<GetBackupListRpc>(req);
    const GetBackupListRpc::Response& respHdr(
        sendRecv<GetBackupListRpc>(session, req, resp));
    checkStatus(HERE);
    ProtoBuf::parseFromResponse(resp, sizeof(respHdr),
                                respHdr.serverListLength, serverList);
}

/**
 * Return the entire tablet map.
 * Clients use this to find objects.
 * If the returned data becomes too big, we should add parameters to
 * specify a subrange.
 * \param[out] tabletMap
 *      An empty Tablets that will be filled with current tablets.
 *      Each tablet has a service locator string describing where to find
 *      its master.
 */
void
CoordinatorClient::getTabletMap(ProtoBuf::Tablets& tabletMap)
{
    Buffer req;
    Buffer resp;
    allocHeader<GetTabletMapRpc>(req);
    const GetTabletMapRpc::Response& respHdr(
        sendRecv<GetTabletMapRpc>(session, req, resp));
    checkStatus(HERE);
    ProtoBuf::parseFromResponse(resp, sizeof(respHdr),
                                respHdr.tabletMapLength, tabletMap);
}

/**
 * Report a slow or dead server.
 */
void
CoordinatorClient::hintServerDown(string serviceLocator)
{
    Buffer req;
    Buffer resp;
    HintServerDownRpc::Request& reqHdr(
        allocHeader<HintServerDownRpc>(req));
    reqHdr.serviceLocatorLength = serviceLocator.length() + 1;
    strncpy(new(&req, APPEND) char[reqHdr.serviceLocatorLength],
            serviceLocator.c_str(),
            reqHdr.serviceLocatorLength);
    sendRecv<HintServerDownRpc>(session, req, resp);
    checkStatus(HERE);
}

/**
 * \copydoc MasterClient::ping
 */
void
CoordinatorClient::ping()
{
    Buffer req;
    Buffer resp;
    allocHeader<PingRpc>(req);
    sendRecv<PingRpc>(session, req, resp);
    checkStatus(HERE);
}

/**
 * Tell the coordinator that recovery of a particular tablets have
 * been recovered on the master who is calling.
 *
 * \param tablets
 *      The tablets which form a partition of a will which are
 *      now done recovering.
 */
void
CoordinatorClient::tabletsRecovered(const ProtoBuf::Tablets& tablets)
{
    Buffer req, resp;
    TabletsRecoveredRpc::Request& reqHdr(allocHeader<TabletsRecoveredRpc>(req));
    reqHdr.tabletsLength = serializeToResponse(req, tablets);
    sendRecv<TabletsRecoveredRpc>(session, req, resp);
    checkStatus(HERE);
}

} // namespace RAMCloud
<|endoftext|>


<commit_before><?hh // partial

namespace package\examples;

require_once __DIR__ . '/../vendor/autoload.php';

use package\Package;

$package = Package::fromOptions(shape(
    'namespace' => 'package\\examples\\classes\\',
    'packageDirectory' => realpath(__DIR__ . '/src')
));

foreach ($package->classes() as $class) {
    $instance = $class->instantiate();
    var_dump($instance);
}
<commit_msg>Update example<commit_after><?hh // partial

namespace package\examples;

require_once __DIR__ . '/../vendor/autoload.php';

use package\Package;

$classes = Package::fromOptions(shape(
    'namespace' => 'package\\examples\\classes\\',
    'packageDirectory' => realpath(__DIR__ . '/src')
))->classes()->toImmVector();

foreach ($classes as $class) {
    $instance = $class->instantiate();
    var_dump($instance);
}
<|endoftext|>


<commit_before>/*---------------------------------------------------------------------------*\
  =========                 |
  \\      /  F ield         | OpenFOAM: The Open Source CFD Toolbox
   \\    /   O peration     |
    \\  /    A nd           | Copyright (C) 2011 OpenFOAM Foundation
     \\/     M anipulation  |
-------------------------------------------------------------------------------
License
    This file is part of OpenFOAM.

    OpenFOAM is free software: you can redistribute it and/or modify it
    under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    OpenFOAM is distributed in the hope that it will be useful, but WITHOUT
    ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    for more details.

    You should have received a copy of the GNU General Public License
    along with OpenFOAM.  If not, see <http://www.gnu.org/licenses/>.

\*---------------------------------------------------------------------------*/

#include <fstream>
#include <iostream>
#include <vector>
#include <hdf5/hdffile.hpp>
#include <hdf5/hdfdataset.hpp>

using std::ofstream;
using std::ios;

#include "Time.H"
#include "zCFDFvMesh.H"
#include "primitiveMesh.H"
#include "wallFvPatch.H"
#include "symmetryFvPatch.H"
#include "cellModeller.H"

// * * * * * * * * * * * * * * * * Constructors  * * * * * * * * * * * * * * //

Foam::zCFDFvMesh::zCFDFvMesh(const IOobject& io)
:
    fvMesh(io)
{}

// * * * * * * * * * * * * * * * Member Functions  * * * * * * * * * * * * * //

void Foam::zCFDFvMesh::writezCFDMesh() const
{
    // make a directory called proInterface in the case
    mkDir(time().rootPath()/time().caseName()/"zCFDInterface");

    // open a file for the mesh
    std::string filename = (
        time().rootPath()/
        time().caseName()/
        "zCFDInterface"/
        time().caseName() + ".h5"
    ).c_str();
    hdf::HDFFile<> file(filename, hdf::HDFFile<>::truncate);

    Info<< "Writing Header" << endl;

    boost::shared_ptr<hdf::HDFGroup<> > meshg = file.openGroup("mesh", true);

    std::vector<hsize_t> dims(1, 1);
    meshg->createAttribute<int>("numFaces", dims)->writeData(nFaces());
    meshg->createAttribute<int>("numCells", dims)->writeData(nCells());

    int numFaces = nFaces();
    int numCells = nCells();

    std::vector<hsize_t> fileDims(2);

   Info<< "Writing Points" << endl;

    // Writing points
    {
      std::vector<double> coord;
      coord.reserve(nPoints()*3);

      const pointField& p = points();

       forAll(p, pointI)
       {
         coord.push_back(p[pointI].x());
         coord.push_back(p[pointI].y());
         coord.push_back(p[pointI].z());
       }

      fileDims[0] = coord.size()/3;
      fileDims[1] = 3;
      hdf::Slab<1> d1(fileDims);
      meshg->createDataset<double>("nodeVertex", d1)->writeData(coord);
    }

       Info<< "Writing Neighbours" << endl;

    const labelUList& own = owner();
    const labelUList& nei = neighbour();

    //const labelUList& cellZone = cellZones();
/*
    const wordList& cellZone = cellZones().names();
    forAll(cellZone, cz)
    {
      Info << cellZone[cz] << endl;

      Info << cellZones().whichZone(0) << endl;
      //Info<< cellZones()[cz] << std::endl;
    }
*/
    std::vector<int> cellZone(numCells,0);

    //std::map<int,int> foamCellZoneMap;
    for(int i = 0; i < numCells;++i){
       int cz = cellZones().whichZone(i);

        cellZone[i] = cz+1;
    }
{
    fileDims[0] = cellZone.size();
    fileDims[1] = 1;
    hdf::Slab<1> d1(fileDims);
    meshg->createDataset<int>("cellZone", d1)->writeData(cellZone);
}

    Info<< "Face Zones" << endl;
    const wordList& faceZone = faceZones().names();
    forAll(faceZone, cz)
    {
      Info << faceZone[cz] << endl;
      //Info<< cellZones()[cz] << std::endl;
      //    }
    }

    { // Face cell
      fileDims[0] = numFaces;
      fileDims[1] = 2;

      hdf::Slab<1> d2(fileDims);

      dims[0] = 2 * numFaces;
      hdf::Slab<1> memFaceCell(dims);

      boost::shared_ptr<hdf::HDFDataSet<> > dataset = meshg->createDataset<int>("faceCell", d2);

      std::vector<int> faceCell;
      //faceCell.reserve(2 * 50000);

      int faceOffset=0;
      int i=0;
      forAll(own, faceI)
      {
        int left = own[faceI];
        int right = nei[faceI];

        faceCell.push_back(left);
        faceCell.push_back(right);
/*
        if(i % 50000)
        {
          std::vector<hsize_t> dims(2,0);
          dims[0] = numFaces;
          dims[1] = 2;
          hdf::Slab<2> filespace(dims);
          dims[0] = 50000;
          dims[1] = 2;
          hdf::Slab<2> memspace(dims);
          std::vector<hsize_t> offset(2,0);
          offset[0] = faceOffset;
          std::vector<hsize_t> stride(2,1);
          hdf::Slab<2> fileselec(filespace,offset,stride,dims);
          dataset->writeData(&faceCell[0],memspace,fileselec);

          faceCell.resize(0);
          faceOffset += 50000;
        }*/
       i++;
      }

      forAll(boundary(), patchI)
      {
          const faceUList& patchFaces = boundaryMesh()[patchI];

          const labelList& patchFaceCells =
              boundaryMesh()[patchI].faceCells();
          forAll(patchFaces, faceI)
          {
            int left = patchFaceCells[faceI];
            int right = numCells;

            faceCell.push_back(left);
            faceCell.push_back(right);

            numCells++;
          }
      }
      if(faceCell.size())
      {
        std::vector<hsize_t> dims(2,0);
        dims[0] = numFaces;
        dims[1] = 2;
        hdf::Slab<2> filespace(dims);
        dims[0] = faceCell.size()/2;
        dims[1] = 2;
        hdf::Slab<2> memspace(dims);
        std::vector<hsize_t> offset(2,0);
        offset[0] = faceOffset;
        std::vector<hsize_t> stride(2,1);
        hdf::Slab<2> fileselec(filespace,offset,stride,dims);
        dataset->writeData(&faceCell[0],memspace,fileselec);
      }
      faceOffset += faceCell.size()/2;
      faceCell.resize(0);

    }

    Info<< "Writing Faces" << endl;

    const faceList& fcs = faces();

    size_t totalFaceNodes=0;
    { // FaceType
      std::vector<int> faceType;
      faceType.reserve(numFaces);
      forAll(own, faceI)
      {
        const labelList& l = fcs[faceI];
        int n = l.size();
        faceType.push_back(n);
        totalFaceNodes+=n;
      }
      forAll(boundary(), patchI)
      {
          const faceUList& patchFaces = boundaryMesh()[patchI];
          forAll(patchFaces, faceI)
          {
              const labelList& l = patchFaces[faceI];
              int n = l.size();
              faceType.push_back(n);
              totalFaceNodes+=n;
          }
      }
      fileDims[0] = numFaces;
      fileDims[1] = 1;
      hdf::Slab<1> d1(fileDims);
      meshg->createDataset<int>("faceType", d1)->writeData(faceType);
    }
    { // Face nodes
      fileDims[0] = totalFaceNodes;
      fileDims[1] = 1;
      hdf::Slab<1> d1(fileDims);
      boost::shared_ptr<hdf::HDFDataSet<> > dataset = meshg->createDataset<int>("faceNodes", d1);

      std::vector<int> faceNodes;
      faceNodes.reserve(totalFaceNodes);
      forAll(own, faceI)
      {
        const labelList& l = fcs[faceI];
        forAll(l, lI)
        {
          faceNodes.push_back(l[lI]);
        }
      }
      forAll(boundary(), patchI)
      {
          const faceUList& patchFaces = boundaryMesh()[patchI];
          forAll(patchFaces, faceI)
          {
              const labelList& l = patchFaces[faceI];
              forAll(l, lI)
              {
                faceNodes.push_back(l[lI]);
              }
          }
      }
      dataset->writeData(faceNodes);
    }

    Info<< "Writing Boundary Conditions" << endl;

    { // FaceBC
      std::vector<int> faceBC(numFaces, 0);
      int i=0;
      forAll(own, faceI)
      {
        faceBC[i] = 0; i++;
      }
      forAll(boundary(), patchI)
      {
          const faceUList& patchFaces = boundaryMesh()[patchI];
          forAll(patchFaces, faceI)
          {
            int bc = -1;
            // Write patch type
             if (isA<wallFvPatch>(boundary()[patchI]))
             {
                 bc=3;
             }
             else if (isA<symmetryFvPatch>(boundary()[patchI]))
             {
                 bc=7;
             }
             else
             {
                 bc=9;
             }

            faceBC[i] = bc; i++;
          }
      }
      assert(i == numFaces);
      fileDims[0] = numFaces;
      fileDims[1] = 1;
      hdf::Slab<1> d1(fileDims);
      meshg->createDataset<int>("faceBC", d1)->writeData(faceBC);
    }
    { // Face Info
      std::vector<int> faceInfo;
      faceInfo.reserve(2 * numFaces);
      forAll(own, faceI)
      {
        int z = 0;
        int dummy = 0;
        faceInfo.push_back(z);
        faceInfo.push_back(dummy);
      }
      forAll(boundary(), patchI)
      {
          const faceUList& patchFaces = boundaryMesh()[patchI];
          forAll(patchFaces, faceI)
          {

        int z = patchI+1;
        int dummy = 0;
        faceInfo.push_back(z);
        faceInfo.push_back(dummy);
         }
      }
      fileDims[0] = numFaces;
      fileDims[1] = 2;
      hdf::Slab<1> d1(fileDims);
      meshg->createDataset<int>("faceInfo", d1)->writeData(faceInfo);
    }

}

// ************************************************************************* //
<commit_msg>Added zone map writer<commit_after>/*---------------------------------------------------------------------------*\
  =========                 |
  \\      /  F ield         | OpenFOAM: The Open Source CFD Toolbox
   \\    /   O peration     |
    \\  /    A nd           | Copyright (C) 2011 OpenFOAM Foundation
     \\/     M anipulation  |
-------------------------------------------------------------------------------
License
    This file is part of OpenFOAM.

    OpenFOAM is free software: you can redistribute it and/or modify it
    under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    OpenFOAM is distributed in the hope that it will be useful, but WITHOUT
    ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    for more details.

    You should have received a copy of the GNU General Public License
    along with OpenFOAM.  If not, see <http://www.gnu.org/licenses/>.

\*---------------------------------------------------------------------------*/

#include <fstream>
#include <iostream>
#include <vector>
#include <map>
#include <hdf5/hdffile.hpp>
#include <hdf5/hdfdataset.hpp>

using std::ofstream;
using std::ios;

#include "Time.H"
#include "zCFDFvMesh.H"
#include "primitiveMesh.H"
#include "wallFvPatch.H"
#include "symmetryFvPatch.H"
#include "cellModeller.H"

// * * * * * * * * * * * * * * * * Constructors  * * * * * * * * * * * * * * //

Foam::zCFDFvMesh::zCFDFvMesh(const IOobject& io)
:
    fvMesh(io)
{}

// * * * * * * * * * * * * * * * Member Functions  * * * * * * * * * * * * * //

void Foam::zCFDFvMesh::writezCFDMesh() const
{
    // make a directory called proInterface in the case
    mkDir(time().rootPath()/time().caseName()/"zCFDInterface");

    // open a file for the mesh
    std::string filename = (
        time().rootPath()/
        time().caseName()/
        "zCFDInterface"/
        time().caseName() + ".h5"
    ).c_str();
    hdf::HDFFile<> file(filename, hdf::HDFFile<>::truncate);

    Info<< "Writing Header" << endl;

    boost::shared_ptr<hdf::HDFGroup<> > meshg = file.openGroup("mesh", true);

    std::vector<hsize_t> dims(1, 1);
    meshg->createAttribute<int>("numFaces", dims)->writeData(nFaces());
    meshg->createAttribute<int>("numCells", dims)->writeData(nCells());

    int numFaces = nFaces();
    int numCells = nCells();

    std::vector<hsize_t> fileDims(2);

   Info<< "Writing Points" << endl;

    // Writing points
    {
      std::vector<double> coord;
      coord.reserve(nPoints()*3);

      const pointField& p = points();

       forAll(p, pointI)
       {
         coord.push_back(p[pointI].x());
         coord.push_back(p[pointI].y());
         coord.push_back(p[pointI].z());
       }

      fileDims[0] = coord.size()/3;
      fileDims[1] = 3;
      hdf::Slab<1> d1(fileDims);
      meshg->createDataset<double>("nodeVertex", d1)->writeData(coord);
    }

       Info<< "Writing Neighbours" << endl;

    const labelUList& own = owner();
    const labelUList& nei = neighbour();

    //const labelUList& cellZone = cellZones();
/*
    const wordList& cellZone = cellZones().names();
    forAll(cellZone, cz)
    {
      Info << cellZone[cz] << endl;

      Info << cellZones().whichZone(0) << endl;
      //Info<< cellZones()[cz] << std::endl;
    }
*/
    std::vector<int> cellZone(numCells,0);

    //std::map<int,int> foamCellZoneMap;
    for(int i = 0; i < numCells;++i){
       int cz = cellZones().whichZone(i);

        cellZone[i] = cz+1;
    }
{
    fileDims[0] = cellZone.size();
    fileDims[1] = 1;
    hdf::Slab<1> d1(fileDims);
    meshg->createDataset<int>("cellZone", d1)->writeData(cellZone);
}

    Info<< "Face Zones" << endl;
    const wordList& faceZone = faceZones().names();
    forAll(faceZone, cz)
    {
      Info << faceZone[cz] << endl;
      //Info<< cellZones()[cz] << std::endl;
      //    }
    }

    { // Face cell
      fileDims[0] = numFaces;
      fileDims[1] = 2;

      hdf::Slab<1> d2(fileDims);

      dims[0] = 2 * numFaces;
      hdf::Slab<1> memFaceCell(dims);

      boost::shared_ptr<hdf::HDFDataSet<> > dataset = meshg->createDataset<int>("faceCell", d2);

      std::vector<int> faceCell;
      //faceCell.reserve(2 * 50000);

      int faceOffset=0;
      int i=0;
      forAll(own, faceI)
      {
        int left = own[faceI];
        int right = nei[faceI];

        faceCell.push_back(left);
        faceCell.push_back(right);
/*
        if(i % 50000)
        {
          std::vector<hsize_t> dims(2,0);
          dims[0] = numFaces;
          dims[1] = 2;
          hdf::Slab<2> filespace(dims);
          dims[0] = 50000;
          dims[1] = 2;
          hdf::Slab<2> memspace(dims);
          std::vector<hsize_t> offset(2,0);
          offset[0] = faceOffset;
          std::vector<hsize_t> stride(2,1);
          hdf::Slab<2> fileselec(filespace,offset,stride,dims);
          dataset->writeData(&faceCell[0],memspace,fileselec);

          faceCell.resize(0);
          faceOffset += 50000;
        }*/
       i++;
      }

      forAll(boundary(), patchI)
      {
          const faceUList& patchFaces = boundaryMesh()[patchI];

          const labelList& patchFaceCells =
              boundaryMesh()[patchI].faceCells();
          forAll(patchFaces, faceI)
          {
            int left = patchFaceCells[faceI];
            int right = numCells;

            faceCell.push_back(left);
            faceCell.push_back(right);

            numCells++;
          }
      }
      if(faceCell.size())
      {
        std::vector<hsize_t> dims(2,0);
        dims[0] = numFaces;
        dims[1] = 2;
        hdf::Slab<2> filespace(dims);
        dims[0] = faceCell.size()/2;
        dims[1] = 2;
        hdf::Slab<2> memspace(dims);
        std::vector<hsize_t> offset(2,0);
        offset[0] = faceOffset;
        std::vector<hsize_t> stride(2,1);
        hdf::Slab<2> fileselec(filespace,offset,stride,dims);
        dataset->writeData(&faceCell[0],memspace,fileselec);
      }
      faceOffset += faceCell.size()/2;
      faceCell.resize(0);

    }

    Info<< "Writing Faces" << endl;

    const faceList& fcs = faces();

    size_t totalFaceNodes=0;
    { // FaceType
      std::vector<int> faceType;
      faceType.reserve(numFaces);
      forAll(own, faceI)
      {
        const labelList& l = fcs[faceI];
        int n = l.size();
        faceType.push_back(n);
        totalFaceNodes+=n;
      }
      forAll(boundary(), patchI)
      {
          const faceUList& patchFaces = boundaryMesh()[patchI];
          forAll(patchFaces, faceI)
          {
              const labelList& l = patchFaces[faceI];
              int n = l.size();
              faceType.push_back(n);
              totalFaceNodes+=n;
          }
      }
      fileDims[0] = numFaces;
      fileDims[1] = 1;
      hdf::Slab<1> d1(fileDims);
      meshg->createDataset<int>("faceType", d1)->writeData(faceType);
    }
    { // Face nodes
      fileDims[0] = totalFaceNodes;
      fileDims[1] = 1;
      hdf::Slab<1> d1(fileDims);
      boost::shared_ptr<hdf::HDFDataSet<> > dataset = meshg->createDataset<int>("faceNodes", d1);

      std::vector<int> faceNodes;
      faceNodes.reserve(totalFaceNodes);
      forAll(own, faceI)
      {
        const labelList& l = fcs[faceI];
        forAll(l, lI)
        {
          faceNodes.push_back(l[lI]);
        }
      }
      forAll(boundary(), patchI)
      {
          const faceUList& patchFaces = boundaryMesh()[patchI];
          forAll(patchFaces, faceI)
          {
              const labelList& l = patchFaces[faceI];
              forAll(l, lI)
              {
                faceNodes.push_back(l[lI]);
              }
          }
      }
      dataset->writeData(faceNodes);
    }

    Info<< "Writing Boundary Conditions" << endl;
    std::vector<std::string> bcType;
    { // FaceBC
      std::vector<int> faceBC(numFaces, 0);
      int i=0;
      forAll(own, faceI)
      {
        faceBC[i] = 0; i++;
      }
      forAll(boundary(), patchI)
      {
            int bc = -1;
            // Write patch type
             if (isA<wallFvPatch>(boundary()[patchI]))
             {
                 bc=3;
                 bcType.push_back("wall");
             }
             else if (isA<symmetryFvPatch>(boundary()[patchI]))
             {
                 bc=7;
                 bcType.push_back("symmetry");
             }
             else
             {
                 bc=9;
                 bcType.push_back("freestream");
             }

          const faceUList& patchFaces = boundaryMesh()[patchI];
          forAll(patchFaces, faceI)
          {
            faceBC[i] = bc; i++;
          }
      }
      assert(i == numFaces);
      fileDims[0] = numFaces;
      fileDims[1] = 1;
      hdf::Slab<1> d1(fileDims);
      meshg->createDataset<int>("faceBC", d1)->writeData(faceBC);
    }
    std::map<int,std::string> bcNames;
    { // Face Info
      std::vector<int> faceInfo;
      faceInfo.reserve(2 * numFaces);
      forAll(own, faceI)
      {
        int z = 0;
        int dummy = 0;
        faceInfo.push_back(z);
        faceInfo.push_back(dummy);
      }
      forAll(boundary(), patchI)
      {
          const faceUList& patchFaces = boundaryMesh()[patchI];
          const wordList& names = boundaryMesh().names();

          int z = patchI+1;
          bcNames[patchI] = names[patchI];

          forAll(patchFaces, faceI)
          {

        int dummy = 0;
        faceInfo.push_back(z);
        faceInfo.push_back(dummy);
         }
      }
      fileDims[0] = numFaces;
      fileDims[1] = 2;
      hdf::Slab<1> d1(fileDims);
      meshg->createDataset<int>("faceInfo", d1)->writeData(faceInfo);
    }

    { // zone.py
          // Write zone helper
   std::string filename = (
        time().rootPath()/
        time().caseName()/
        "zCFDInterface"/
        time().caseName() + "_zone.py"
    ).c_str();

    std::ofstream out(filename.c_str());

    std::map<std::string, std::string> bcMap;
    bcMap["interior"] = "interior";
    bcMap["symmetry"] = "symmetry";
    bcMap["symmetry2"] = "symmetry plane";
    bcMap["freestream"] = "freestream";
    bcMap["wall"] = "wall";
    bcMap["inlet"] = "inlet";
    bcMap["pressure"] = "pressure";

    int zoneId = 1;

    out << "# Zone handling helper functions\n\n";
    out << "zone_name_to_id={";
    for (std::vector<std::string>::iterator itr = bcType.begin(); itr != bcType.end();
         ++itr) {
      out << "\"" << bcNames[zoneId - 1] << "\": " << zoneId << ",\n";
      zoneId++;
    }
    out << "}\n";

    out << "id_to_zone_name= {v: k for k, v in zone_name_to_id.items()}\n";

    out << "def to_id(names):\n";
    out << "    # Converts names list to id list\n";
    out << "    id=[]\n";
    out << "    for n in names:\n";
    out << "        id.append(zone_name_to_id[n])\n";
    out << "    return id\n";
    out << "def from_id(id):\n";
    out << "    # returns name of id\n";
    out << "    return id_to_zone_name[id]\n";

    out << "fluid_zone={";
    out << "\""
        << "fluid"
        << "\": " << 1 << ",\n";
    out << "}\n";

    for (std::map<std::string, std::string>::iterator bit = bcMap.begin();
         bit != bcMap.end(); ++bit) {
      out << bit->first << "=[";
      zoneId = 1;
      for (std::vector<std::string>::iterator itr = bcType.begin(); itr != bcType.end();
           ++itr) {
        std::string bcName = *itr;

        if (bcName == bit->second) {
          out << "\"" << bcNames[zoneId - 1] << "\",";
        }
        zoneId++;
      }
      out << "]\n";
    }
    out.close();

    }

}

// ************************************************************************* //
<|endoftext|>


<commit_before>/**
 * This file is part of the "libfnord" project
 *   Copyright (c) 2015 Paul Asmuth
 *
 * FnordMetric is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License v3.0. You should have received a
 * copy of the GNU General Public License along with this program. If not, see
 * <http://www.gnu.org/licenses/>.
 */
#include <unistd.h>
#include <fnord-base/io/file.h>
#include <fnord-base/io/fileutil.h>
#include <fnord-base/io/mmappedfile.h>
#include <fnord-base/logging.h>
#include <fnord-base/io/fileutil.h>
#include <fnord-base/util/binarymessagereader.h>
#include <fnord-base/util/binarymessagewriter.h>
#include <fnord-dproc/LocalScheduler.h>

namespace fnord {
namespace dproc {

LocalScheduler::LocalScheduler(
    const String& tempdir /* = "/tmp" */,
    size_t max_threads /* = 8 */,
    size_t max_requests /* = 32 */) :
    tempdir_(tempdir),
    tpool_(max_threads),
    req_tpool_(max_requests) {}

void LocalScheduler::start() {
  req_tpool_.start();
  tpool_.start();
}

void LocalScheduler::stop() {
  req_tpool_.stop();
  tpool_.stop();
}

RefPtr<TaskResultFuture> LocalScheduler::run(
    RefPtr<Application> app,
    const TaskSpec& task) {
  RefPtr<TaskResultFuture> result(new TaskResultFuture());

  try {
    auto instance = mkRef(
        new LocalTaskRef(
            app,
            task.task_name(),
            Buffer(task.params().data(), task.params().size())));

    req_tpool_.run([this, app, result, instance] () {
      try {
        LocalTaskPipeline pipeline;
        pipeline.tasks.push_back(instance);
        runPipeline(app.get(), &pipeline, result);

        if (instance->failed) {
          RAISE(kRuntimeError, "task failed");
        }

        result->returnResult(instance->task);
      } catch (const StandardException& e) {
        fnord::logError("dproc.scheduler", e, "task failed");
        result->returnError(e);
      }
    });
  } catch (const StandardException& e) {
    fnord::logError("dproc.scheduler", e, "task failed");
    result->returnError(e);
  }

  return result;
}

void LocalScheduler::runPipeline(
    Application* app,
    LocalTaskPipeline* pipeline,
    RefPtr<TaskResultFuture> result) {
  fnord::logInfo(
      "fnord.dproc",
      "Starting local pipeline id=$0 tasks=$1",
      (void*) pipeline,
      pipeline->tasks.size());

  std::unique_lock<std::mutex> lk(pipeline->mutex);
  result->updateStatus([&pipeline] (TaskStatus* status) {
    status->num_subtasks_total = pipeline->tasks.size();
  });

  while (pipeline->tasks.size() > 0) {
    bool waiting = true;
    size_t num_waiting = 0;
    size_t num_running = 0;
    size_t num_completed = 0;

    for (auto& taskref : pipeline->tasks) {

      if (taskref->finished) {
        ++num_completed;
        continue;
      }

      if (taskref->running) {
        ++num_running;
        continue;
      }

      if (!taskref->expanded) {
        taskref->expanded = true;

        auto cache_key = taskref->task->cacheKeySHA1();
        if (!cache_key.isEmpty()) {
          taskref->cache_filename = FileUtil::joinPaths(
              tempdir_,
              StringUtil::format("cache_$0", cache_key.get()));
        }

        auto cached =
            !cache_key.isEmpty() &&
            FileUtil::exists(taskref->cache_filename);

        if (cached) {
          auto cache_file = File::openFile(
              taskref->cache_filename,
              File::O_READ);

          Buffer cache_hdr(sizeof(uint64_t));
          cache_file.read(&cache_hdr);
          util::BinaryMessageReader reader(cache_hdr.data(), cache_hdr.size());
          auto cache_version = *reader.readUInt64();
          auto cache_size = cache_file.size() - cache_hdr.size();

          fnord::logDebug(
              "fnord.dproc",
              "Reading RDD from cache: $0, key=$1, version=$2",
              taskref->debug_name,
              cache_key.isEmpty() ? "<nil>" : cache_key.get(),
              cache_version);

          taskref->task->decode(
                new io::MmappedFile(
                    std::move(cache_file),
                    cache_hdr.size(),
                    cache_size));

          result->updateStatus([&pipeline] (TaskStatus* status) {
            ++status->num_subtasks_completed;
          });

          taskref->finished = true;
          waiting = false;
          break;
        }

        auto parent_task = taskref;
        size_t numdeps = 0;
        for (const auto& dep : taskref->task->dependencies()) {
          RefPtr<LocalTaskRef> depref(new LocalTaskRef(app, dep.task_name, dep.params));
          parent_task->dependencies.emplace_back(depref);
          pipeline->tasks.emplace_back(depref);
          ++numdeps;
        }

        if (numdeps > 0) {
          result->updateStatus([numdeps] (TaskStatus* status) {
            status->num_subtasks_total += numdeps;
          });
        }

        waiting = false;
        break;
      }

      bool deps_finished = true;
      for (const auto& dep : taskref->dependencies) {
        if (dep->failed) {
          taskref->failed = true;
          taskref->finished = true;
          waiting = false;
        }

        if (!dep->finished) {
          deps_finished = false;
        }
      }

      if (!taskref->finished) {
        if (!deps_finished) {
          ++num_waiting;
          continue;
        }

        auto ckey = taskref->task->cacheKeySHA1();
        fnord::logDebug(
            "fnord.dproc",
            "Computing RDD: $0, key=$1, version=$2",
            taskref->debug_name,
            ckey.isEmpty() ? "<nil>" : ckey.get(),
            taskref->task->cacheVersion());

        taskref->running = true;
        tpool_.run(std::bind(
            &LocalScheduler::runTask,
            this,
            pipeline,
            taskref,
            result));

        waiting = false;
      }
    }

    fnord::logDebug(
        "fnord.dproc",
        "Running local pipeline id=$0: $1",
        (void*) pipeline,
        result->status().toString());

    if (waiting) {
      pipeline->wakeup.wait(lk);
    }

    while (pipeline->tasks.size() > 0 && pipeline->tasks.back()->finished) {
      pipeline->tasks.pop_back();
    }
  }

  fnord::logDebug(
      "fnord.dproc",
      "Completed local pipeline id=$0",
      (void*) pipeline);
}

void LocalScheduler::runTask(
    LocalTaskPipeline* pipeline,
    RefPtr<LocalTaskRef> task,
    RefPtr<TaskResultFuture> result) {

  try {
    task->task->compute(task.get());

    if (!task->cache_filename.empty()) {
      auto cache_file = task->cache_filename;

      {
        auto f = File::openFile(
            cache_file + "~",
            File::O_CREATEOROPEN | File::O_WRITE | File::O_TRUNCATE);

        util::BinaryMessageWriter hdr;
        hdr.appendUInt64(task->task->cacheVersion());
        f.write(hdr.data(), hdr.size());

        auto res = task->task->encode();
        f.write(res->data(), res->size());
      }

      FileUtil::mv(cache_file + "~", cache_file);
    }
  } catch (const std::exception& e) {
    task->failed = true;
    fnord::logError("fnord.dproc", e, "error");
  }

  result->updateStatus([&pipeline] (TaskStatus* status) {
    ++status->num_subtasks_completed;
  });

  std::unique_lock<std::mutex> lk(pipeline->mutex);
  task->finished = true;
  lk.unlock();
  pipeline->wakeup.notify_all();
}

LocalScheduler::LocalTaskRef::LocalTaskRef(
    RefPtr<Application> app,
    const String& task_name,
    const Buffer& params) :
    task(app->getTaskInstance(task_name, params)),
    debug_name(StringUtil::format("$0#$1", app->name(), task_name)),
    running(false),
    expanded(false),
    finished(false),
    failed(false) {}

RefPtr<Task> LocalScheduler::LocalTaskRef::getDependency(size_t index) {
  if (index >= dependencies.size()) {
    RAISEF(kIndexError, "invalid dependecy index: $0", index);
  }

  const auto& dep = dependencies[index];
  return dep->task;
}

size_t LocalScheduler::LocalTaskRef::numDependencies() const {
  return dependencies.size();
}

} // namespace dproc
} // namespace fnord
<commit_msg>cache filenames<commit_after>/**
 * This file is part of the "libfnord" project
 *   Copyright (c) 2015 Paul Asmuth
 *
 * FnordMetric is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License v3.0. You should have received a
 * copy of the GNU General Public License along with this program. If not, see
 * <http://www.gnu.org/licenses/>.
 */
#include <unistd.h>
#include <fnord-base/io/file.h>
#include <fnord-base/io/fileutil.h>
#include <fnord-base/io/mmappedfile.h>
#include <fnord-base/logging.h>
#include <fnord-base/io/fileutil.h>
#include <fnord-base/util/binarymessagereader.h>
#include <fnord-base/util/binarymessagewriter.h>
#include <fnord-dproc/LocalScheduler.h>

namespace fnord {
namespace dproc {

LocalScheduler::LocalScheduler(
    const String& tempdir /* = "/tmp" */,
    size_t max_threads /* = 8 */,
    size_t max_requests /* = 32 */) :
    tempdir_(tempdir),
    tpool_(max_threads),
    req_tpool_(max_requests) {}

void LocalScheduler::start() {
  req_tpool_.start();
  tpool_.start();
}

void LocalScheduler::stop() {
  req_tpool_.stop();
  tpool_.stop();
}

RefPtr<TaskResultFuture> LocalScheduler::run(
    RefPtr<Application> app,
    const TaskSpec& task) {
  RefPtr<TaskResultFuture> result(new TaskResultFuture());

  try {
    auto instance = mkRef(
        new LocalTaskRef(
            app,
            task.task_name(),
            Buffer(task.params().data(), task.params().size())));

    req_tpool_.run([this, app, result, instance] () {
      try {
        LocalTaskPipeline pipeline;
        pipeline.tasks.push_back(instance);
        runPipeline(app.get(), &pipeline, result);

        if (instance->failed) {
          RAISE(kRuntimeError, "task failed");
        }

        result->returnResult(instance->task);
      } catch (const StandardException& e) {
        fnord::logError("dproc.scheduler", e, "task failed");
        result->returnError(e);
      }
    });
  } catch (const StandardException& e) {
    fnord::logError("dproc.scheduler", e, "task failed");
    result->returnError(e);
  }

  return result;
}

void LocalScheduler::runPipeline(
    Application* app,
    LocalTaskPipeline* pipeline,
    RefPtr<TaskResultFuture> result) {
  fnord::logInfo(
      "fnord.dproc",
      "Starting local pipeline id=$0 tasks=$1",
      (void*) pipeline,
      pipeline->tasks.size());

  std::unique_lock<std::mutex> lk(pipeline->mutex);
  result->updateStatus([&pipeline] (TaskStatus* status) {
    status->num_subtasks_total = pipeline->tasks.size();
  });

  while (pipeline->tasks.size() > 0) {
    bool waiting = true;
    size_t num_waiting = 0;
    size_t num_running = 0;
    size_t num_completed = 0;

    for (auto& taskref : pipeline->tasks) {

      if (taskref->finished) {
        ++num_completed;
        continue;
      }

      if (taskref->running) {
        ++num_running;
        continue;
      }

      if (!taskref->expanded) {
        taskref->expanded = true;

        auto cache_key = taskref->task->cacheKeySHA1();
        if (!cache_key.isEmpty()) {
          taskref->cache_filename = FileUtil::joinPaths(
              tempdir_,
              StringUtil::format("$0.rdd", cache_key.get()));
        }

        auto cached =
            !cache_key.isEmpty() &&
            FileUtil::exists(taskref->cache_filename);

        if (cached) {
          auto cache_file = File::openFile(
              taskref->cache_filename,
              File::O_READ);

          Buffer cache_hdr(sizeof(uint64_t));
          cache_file.read(&cache_hdr);
          util::BinaryMessageReader reader(cache_hdr.data(), cache_hdr.size());
          auto cache_version = *reader.readUInt64();
          auto cache_size = cache_file.size() - cache_hdr.size();

          fnord::logDebug(
              "fnord.dproc",
              "Reading RDD from cache: $0, key=$1, version=$2",
              taskref->debug_name,
              cache_key.isEmpty() ? "<nil>" : cache_key.get(),
              cache_version);

          taskref->task->decode(
                new io::MmappedFile(
                    std::move(cache_file),
                    cache_hdr.size(),
                    cache_size));

          result->updateStatus([&pipeline] (TaskStatus* status) {
            ++status->num_subtasks_completed;
          });

          taskref->finished = true;
          waiting = false;
          break;
        }

        auto parent_task = taskref;
        size_t numdeps = 0;
        for (const auto& dep : taskref->task->dependencies()) {
          RefPtr<LocalTaskRef> depref(new LocalTaskRef(app, dep.task_name, dep.params));
          parent_task->dependencies.emplace_back(depref);
          pipeline->tasks.emplace_back(depref);
          ++numdeps;
        }

        if (numdeps > 0) {
          result->updateStatus([numdeps] (TaskStatus* status) {
            status->num_subtasks_total += numdeps;
          });
        }

        waiting = false;
        break;
      }

      bool deps_finished = true;
      for (const auto& dep : taskref->dependencies) {
        if (dep->failed) {
          taskref->failed = true;
          taskref->finished = true;
          waiting = false;
        }

        if (!dep->finished) {
          deps_finished = false;
        }
      }

      if (!taskref->finished) {
        if (!deps_finished) {
          ++num_waiting;
          continue;
        }

        auto ckey = taskref->task->cacheKeySHA1();
        fnord::logDebug(
            "fnord.dproc",
            "Computing RDD: $0, key=$1, version=$2",
            taskref->debug_name,
            ckey.isEmpty() ? "<nil>" : ckey.get(),
            taskref->task->cacheVersion());

        taskref->running = true;
        tpool_.run(std::bind(
            &LocalScheduler::runTask,
            this,
            pipeline,
            taskref,
            result));

        waiting = false;
      }
    }

    fnord::logDebug(
        "fnord.dproc",
        "Running local pipeline id=$0: $1",
        (void*) pipeline,
        result->status().toString());

    if (waiting) {
      pipeline->wakeup.wait(lk);
    }

    while (pipeline->tasks.size() > 0 && pipeline->tasks.back()->finished) {
      pipeline->tasks.pop_back();
    }
  }

  fnord::logDebug(
      "fnord.dproc",
      "Completed local pipeline id=$0",
      (void*) pipeline);
}

void LocalScheduler::runTask(
    LocalTaskPipeline* pipeline,
    RefPtr<LocalTaskRef> task,
    RefPtr<TaskResultFuture> result) {

  try {
    task->task->compute(task.get());

    if (!task->cache_filename.empty()) {
      auto cache_file = task->cache_filename;

      {
        auto f = File::openFile(
            cache_file + "~",
            File::O_CREATEOROPEN | File::O_WRITE | File::O_TRUNCATE);

        util::BinaryMessageWriter hdr;
        hdr.appendUInt64(task->task->cacheVersion());
        f.write(hdr.data(), hdr.size());

        auto res = task->task->encode();
        f.write(res->data(), res->size());
      }

      FileUtil::mv(cache_file + "~", cache_file);
    }
  } catch (const std::exception& e) {
    task->failed = true;
    fnord::logError("fnord.dproc", e, "error");
  }

  result->updateStatus([&pipeline] (TaskStatus* status) {
    ++status->num_subtasks_completed;
  });

  std::unique_lock<std::mutex> lk(pipeline->mutex);
  task->finished = true;
  lk.unlock();
  pipeline->wakeup.notify_all();
}

LocalScheduler::LocalTaskRef::LocalTaskRef(
    RefPtr<Application> app,
    const String& task_name,
    const Buffer& params) :
    task(app->getTaskInstance(task_name, params)),
    debug_name(StringUtil::format("$0#$1", app->name(), task_name)),
    running(false),
    expanded(false),
    finished(false),
    failed(false) {}

RefPtr<Task> LocalScheduler::LocalTaskRef::getDependency(size_t index) {
  if (index >= dependencies.size()) {
    RAISEF(kIndexError, "invalid dependecy index: $0", index);
  }

  const auto& dep = dependencies[index];
  return dep->task;
}

size_t LocalScheduler::LocalTaskRef::numDependencies() const {
  return dependencies.size();
}

} // namespace dproc
} // namespace fnord
<|endoftext|>


<commit_before>#pragma once
//=====================================================================//
/*!	@file
	@brief	R8C/M110AN, R8C/M120AN グループ・システム・レジスター定義 @n
			Copyright 2014 Kunihito Hiramatsu
	@author	平松邦仁 (hira@rvf-rc45.net)
*/
//=====================================================================//
#include "io_utils.hpp"

namespace device {

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  プロセッサモードレジスタ０ PM0
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	typedef io8<0x0010> pm0_io;
	struct pm0_t : public pm0_io {
		using pm0_io::operator =;
		using pm0_io::operator ();
		using pm0_io::operator |=;
		using pm0_io::operator &=;

		bit_t<pm0_io, 3> SRST;
	};
	static pm0_t PM0;

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  モジュールスタンバイ制御レジスタ MSTCR
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	typedef io8<0x0012> mstcr_io;
	struct mstcr_t : public mstcr_io {
		using mstcr_io::operator =;
		using mstcr_io::operator ();
		using mstcr_io::operator |=;
		using mstcr_io::operator &=;

		bit_t<mstcr_io, 0> MSTTRJ;
		bit_t<mstcr_io, 1> MSTTRB;

		bit_t<mstcr_io, 4> MSTAD;
		bit_t<mstcr_io, 5> MSTTRC;
		bit_t<mstcr_io, 6> MSTUART;
	};
	static mstcr_t MSTCR;

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  プロテクトレジスタ PRCR
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	typedef io8<0x0013> prcr_io;
	struct prcr_t : public prcr_io {
		using prcr_io::operator =;
		using prcr_io::operator ();
		using prcr_io::operator |=;
		using prcr_io::operator &=;

		bit_t<prcr_io, 0> PRC0;
		bit_t<prcr_io, 1> PRC1;

		bit_t<prcr_io, 3> PRC3;
		bit_t<prcr_io, 4> PRC4;
	};
	static prcr_t PRCR;

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  ハードウェアリセットプロテクトレジスタ HRPR
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	typedef io8<0x0016> hrpr_io;
	struct hrpr_t : public hrpr_io {
		using hrpr_io::operator =;
		using hrpr_io::operator ();
		using hrpr_io::operator |=;
		using hrpr_io::operator &=;

		bit_t<hrpr_io, 0> RAMCRE;
	};
	static hrpr_t HRPR;

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  リセット要因判別レジスタ RSTFR
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	typedef io8<0x005f> rstfr_io;
	typedef io8_ro<0x005f> rstfr_io_ro;
	struct rstfr_t : public rstfr_io, rstfr_io_ro {
		using rstfr_io::operator =;
		using rstfr_io::operator ();
		using rstfr_io::operator |=;
		using rstfr_io::operator &=;

		using rstfr_io_ro::operator ();

		bit_t<rstfr_io, 0> CWR;

		bit_t<rstfr_io_ro, 1> HWR;
		bit_t<rstfr_io_ro, 2> SWR;
		bit_t<rstfr_io_ro, 3> WDR;
	};
	static rstfr_t RSTFR;

}
<commit_msg>update comment<commit_after>#pragma once
//=====================================================================//
/*!	@file
	@brief	R8C/M110AN, R8C/M120AN グループ・システム・レジスター定義 @n
			Copyright 2014 Kunihito Hiramatsu
	@author	平松邦仁 (hira@rvf-rc45.net)
*/
//=====================================================================//
#include "io_utils.hpp"

namespace device {

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  プロセッサモードレジスタ０ PM0
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	typedef io8<0x0010> pm0_io;
	struct pm0_t : public pm0_io {
		using pm0_io::operator =;
		using pm0_io::operator ();
		using pm0_io::operator |=;
		using pm0_io::operator &=;

		bit_t<pm0_io, 3> SRST;
	};
	static pm0_t PM0;

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  モジュールスタンバイ制御レジスタ MSTCR
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	typedef io8<0x0012> mstcr_io;
	struct mstcr_t : public mstcr_io {
		using mstcr_io::operator =;
		using mstcr_io::operator ();
		using mstcr_io::operator |=;
		using mstcr_io::operator &=;

		bit_t<mstcr_io, 0> MSTTRJ;
		bit_t<mstcr_io, 1> MSTTRB;

		bit_t<mstcr_io, 4> MSTAD;
		bit_t<mstcr_io, 5> MSTTRC;
		bit_t<mstcr_io, 6> MSTUART;
	};
	static mstcr_t MSTCR;

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  プロテクトレジスタ PRCR
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	typedef io8<0x0013> prcr_io;
	struct prcr_t : public prcr_io {
		using prcr_io::operator =;
		using prcr_io::operator ();
		using prcr_io::operator |=;
		using prcr_io::operator &=;

		bit_t<prcr_io, 0> PRC0;
		bit_t<prcr_io, 1> PRC1;

		bit_t<prcr_io, 3> PRC3;
		bit_t<prcr_io, 4> PRC4;
	};
	static prcr_t PRCR;

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  ハードウェアリセットプロテクトレジスタ HRPR
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	typedef io8<0x0016> hrpr_io;
	struct hrpr_t : public hrpr_io {
		using hrpr_io::operator =;
		using hrpr_io::operator ();
		using hrpr_io::operator |=;
		using hrpr_io::operator &=;

		bit_t<hrpr_io, 0> RAMCRE;
	};
	static hrpr_t HRPR;

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  リセット要因判別レジスタ RSTFR
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	typedef io8<0x005f> rstfr_io;
	typedef io8_ro<0x005f> rstfr_io_ro;
	struct rstfr_t : public rstfr_io, rstfr_io_ro {
		using rstfr_io::operator =;
		using rstfr_io::operator ();
		using rstfr_io::operator |=;
		using rstfr_io::operator &=;

		using rstfr_io_ro::operator ();

		bit_t<rstfr_io, 0> CWR;

		bit_t<rstfr_io_ro, 1> HWR;
		bit_t<rstfr_io_ro, 2> SWR;
		bit_t<rstfr_io_ro, 3> WDR;
	};
	static rstfr_t RSTFR;

}
<|endoftext|>


<commit_before>#include "species.hpp"
#include "vboindexer.hpp"
#include "universe.hpp"
#include "scene.hpp"
#include "shader.hpp"
#include "material.hpp"
#include "object.hpp"
#include "species_or_glyph.hpp"
#include "render_templates.hpp"
#include "family_templates.hpp"
#include "code/ylikuutio/hierarchy/hierarchy_templates.hpp"

// Include GLEW
#ifndef __GL_GLEW_H_INCLUDED
#define __GL_GLEW_H_INCLUDED
#include <GL/glew.h> // GLfloat, GLuint etc.
#endif

// Include standard headers
#include <cstddef>  // std::size_t
#include <iostream> // std::cout, std::cin, std::cerr

namespace yli
{
    namespace ontology
    {
        void Species::bind_object(yli::ontology::Object* const object)
        {
            // get `childID` from `Species` and set pointer to `object`.
            yli::hierarchy::bind_child_to_parent<yli::ontology::Object*>(
                    object,
                    this->object_pointer_vector,
                    this->free_objectID_queue,
                    this->number_of_objects);
        }

        void Species::unbind_object(const std::size_t childID)
        {
            yli::hierarchy::unbind_child_from_parent(
                    childID,
                    this->object_pointer_vector,
                    this->free_objectID_queue,
                    this->number_of_objects);
        }

        void Species::bind_to_parent()
        {
            // get `childID` from `Material` and set pointer to this `Species`.
            this->material_parent->bind_species(this);
        }

        void Species::bind_to_new_parent(yli::ontology::Material* const new_material_pointer)
        {
            // unbind from the old parent `Material`.
            this->material_parent->unbind_species(this->childID);

            // get `childID` from `Material` and set pointer to this `Species`.
            this->material_parent = new_material_pointer;
            this->material_parent->bind_species(this);
        }

        Species::~Species()
        {
            if (!this->is_symbiont_species)
            {
                // destructor.
                std::cout << "Species with childID " << std::dec << this->childID << " will be destroyed.\n";

                // destroy all objects of this species.
                std::cout << "All objects of this species will be destroyed.\n";
                yli::hierarchy::delete_children<yli::ontology::Object*>(this->object_pointer_vector, this->number_of_objects);

                // Cleanup VBO, shader and texture.
                glDeleteBuffers(1, &this->vertexbuffer);
                glDeleteBuffers(1, &this->uvbuffer);
                glDeleteBuffers(1, &this->normalbuffer);
                glDeleteBuffers(1, &this->elementbuffer);

                // set pointer to this species to nullptr.
                this->material_parent->set_species_pointer(this->childID, nullptr);
            }
        }

        void Species::render()
        {
            if (this->vram_buffer_in_use)
            {
                this->prerender();

                // render this `Species`.
                yli::ontology::render_species_or_glyph<yli::ontology::Species*>(this);

                this->postrender();
            }
        }

        yli::ontology::Entity* Species::get_parent() const
        {
            if (this->is_symbiont_species)
            {
                return nullptr;
            }
            return this->material_parent;
        }

        void Species::set_object_pointer(const std::size_t childID, yli::ontology::Object* const child_pointer)
        {
            yli::hierarchy::set_child_pointer(childID, child_pointer, this->object_pointer_vector, this->free_objectID_queue, this->number_of_objects);
        }

        std::size_t Species::get_image_width() const
        {
            return this->image_width;
        }

        const std::string& Species::get_model_file_format() const
        {
            return this->model_file_format;
        }

        std::size_t Species::get_image_height() const
        {
            return this->image_height;
        }
    }
}
<commit_msg>`Species::bind_to_parent`: check `this->material_parent` for `nullptr`.<commit_after>#include "species.hpp"
#include "vboindexer.hpp"
#include "universe.hpp"
#include "scene.hpp"
#include "shader.hpp"
#include "material.hpp"
#include "object.hpp"
#include "species_or_glyph.hpp"
#include "render_templates.hpp"
#include "family_templates.hpp"
#include "code/ylikuutio/hierarchy/hierarchy_templates.hpp"

// Include GLEW
#ifndef __GL_GLEW_H_INCLUDED
#define __GL_GLEW_H_INCLUDED
#include <GL/glew.h> // GLfloat, GLuint etc.
#endif

// Include standard headers
#include <cstddef>  // std::size_t
#include <iostream> // std::cout, std::cin, std::cerr

namespace yli
{
    namespace ontology
    {
        void Species::bind_object(yli::ontology::Object* const object)
        {
            // get `childID` from `Species` and set pointer to `object`.
            yli::hierarchy::bind_child_to_parent<yli::ontology::Object*>(
                    object,
                    this->object_pointer_vector,
                    this->free_objectID_queue,
                    this->number_of_objects);
        }

        void Species::unbind_object(const std::size_t childID)
        {
            yli::hierarchy::unbind_child_from_parent(
                    childID,
                    this->object_pointer_vector,
                    this->free_objectID_queue,
                    this->number_of_objects);
        }

        void Species::bind_to_parent()
        {
            // requirements:
            // `this->material_parent` must not be `nullptr`.
            yli::ontology::Material* const material = this->material_parent;

            if (material == nullptr)
            {
                std::cerr << "ERROR: `Species::bind_to_parent`: `material` is `nullptr`!\n";
                return;
            }

            // get `childID` from `Material` and set pointer to this `Species`.
            this->material_parent->bind_species(this);
        }

        void Species::bind_to_new_parent(yli::ontology::Material* const new_material_pointer)
        {
            // unbind from the old parent `Material`.
            this->material_parent->unbind_species(this->childID);

            // get `childID` from `Material` and set pointer to this `Species`.
            this->material_parent = new_material_pointer;
            this->material_parent->bind_species(this);
        }

        Species::~Species()
        {
            if (!this->is_symbiont_species)
            {
                // destructor.
                std::cout << "Species with childID " << std::dec << this->childID << " will be destroyed.\n";

                // destroy all objects of this species.
                std::cout << "All objects of this species will be destroyed.\n";
                yli::hierarchy::delete_children<yli::ontology::Object*>(this->object_pointer_vector, this->number_of_objects);

                // Cleanup VBO, shader and texture.
                glDeleteBuffers(1, &this->vertexbuffer);
                glDeleteBuffers(1, &this->uvbuffer);
                glDeleteBuffers(1, &this->normalbuffer);
                glDeleteBuffers(1, &this->elementbuffer);

                // set pointer to this species to nullptr.
                this->material_parent->set_species_pointer(this->childID, nullptr);
            }
        }

        void Species::render()
        {
            if (this->vram_buffer_in_use)
            {
                this->prerender();

                // render this `Species`.
                yli::ontology::render_species_or_glyph<yli::ontology::Species*>(this);

                this->postrender();
            }
        }

        yli::ontology::Entity* Species::get_parent() const
        {
            if (this->is_symbiont_species)
            {
                return nullptr;
            }
            return this->material_parent;
        }

        void Species::set_object_pointer(const std::size_t childID, yli::ontology::Object* const child_pointer)
        {
            yli::hierarchy::set_child_pointer(childID, child_pointer, this->object_pointer_vector, this->free_objectID_queue, this->number_of_objects);
        }

        std::size_t Species::get_image_width() const
        {
            return this->image_width;
        }

        const std::string& Species::get_model_file_format() const
        {
            return this->model_file_format;
        }

        std::size_t Species::get_image_height() const
        {
            return this->image_height;
        }
    }
}
<|endoftext|>


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

#include "taskschedulertbb.h"

namespace embree
{
  bool g_tbb_threads_initialized = false;
  tbb::task_scheduler_init g_tbb_threads(tbb::task_scheduler_init::deferred);

  class TBBAffinity: public tbb::task_scheduler_observer
  {
  public:
    tbb::atomic<int> threadCount;

    void on_scheduler_entry( bool ) {
      ++threadCount;
      setAffinity(TaskScheduler::threadIndex()); // FIXME: use threadCount?
    }

    void on_scheduler_exit( bool ) {
      --threadCount;
    }
  public:

    TBBAffinity() { threadCount = 0; }

    int  get_concurrency()      { return threadCount; }
    void set_concurrency(int i) { threadCount = i; }

  } tbb_affinity;

  size_t TaskScheduler::g_numThreads = 0;

  void TaskScheduler::create(size_t numThreads, bool set_affinity)
  {
    /* first terminate threads in case we configured them */
    if (g_tbb_threads_initialized) {
      g_tbb_threads.terminate();
      g_tbb_threads_initialized = false;
    }

    /* only set affinity if requested by the user */
    if (set_affinity) {
      tbb_affinity.set_concurrency(0);
      tbb_affinity.observe(true);
    }

    /* now either keep default settings or configure number of threads */
    if (numThreads == 0)
    {
      g_tbb_threads_initialized = false;
      g_numThreads = tbb::task_scheduler_init::default_num_threads();
    } else {
      g_tbb_threads_initialized = true;
      g_tbb_threads.initialize(int(numThreads));
      g_numThreads = numThreads;
    }

    /* also start worker threads in affinity mode */
    if (set_affinity) {
      tbb::parallel_for(size_t(0), size_t(g_numThreads), size_t(1), [] ( size_t i ) {
          while (tbb_affinity.threadCount != g_numThreads) {};
        });
    }
  }

  void TaskScheduler::destroy()
  {
    if (g_tbb_threads_initialized) {
      g_tbb_threads.terminate();
      g_tbb_threads_initialized = false;
    }
  }
}
<commit_msg>starting TBB threads if affinity got set<commit_after>// ======================================================================== //
// Copyright 2009-2016 Intel Corporation                                    //
//                                                                          //
// Licensed under the Apache License, Version 2.0 (the "License");          //
// you may not use this file except in compliance with the License.         //
// You may obtain a copy of the License at                                  //
//                                                                          //
//     http://www.apache.org/licenses/LICENSE-2.0                           //
//                                                                          //
// Unless required by applicable law or agreed to in writing, software      //
// distributed under the License is distributed on an "AS IS" BASIS,        //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and      //
// limitations under the License.                                           //
// ======================================================================== //

#include "taskschedulertbb.h"

namespace embree
{
  bool g_tbb_threads_initialized = false;
  tbb::task_scheduler_init g_tbb_threads(tbb::task_scheduler_init::deferred);

  class TBBAffinity: public tbb::task_scheduler_observer
  {
  public:
    tbb::atomic<int> threadCount;

    void on_scheduler_entry( bool ) {
      ++threadCount;
      setAffinity(TaskScheduler::threadIndex()); // FIXME: use threadCount?
    }

    void on_scheduler_exit( bool ) {
      --threadCount;
    }
  public:

    TBBAffinity() { threadCount = 0; }

    int  get_concurrency()      { return threadCount; }
    void set_concurrency(int i) { threadCount = i; }

  } tbb_affinity;

  size_t TaskScheduler::g_numThreads = 0;

  void TaskScheduler::create(size_t numThreads, bool set_affinity)
  {
    /* first terminate threads in case we configured them */
    if (g_tbb_threads_initialized) {
      g_tbb_threads.terminate();
      g_tbb_threads_initialized = false;
    }

    /* only set affinity if requested by the user */
    if (set_affinity) {
      tbb_affinity.set_concurrency(0);
      tbb_affinity.observe(true);
    }

    /* now either keep default settings or configure number of threads */
    if (numThreads == 0)
    {
      g_tbb_threads_initialized = false;
      g_numThreads = tbb::task_scheduler_init::default_num_threads();
    } else {
      g_tbb_threads_initialized = true;
      g_tbb_threads.initialize(int(numThreads));
      g_numThreads = numThreads;
    }

    /* also start worker threads in affinity mode */
    if (set_affinity) {
      tbb::parallel_for(size_t(0), size_t(g_numThreads), size_t(1), [] ( size_t i ) {
          while (tbb_affinity.threadCount != g_numThreads) {
            yield();
          };
        });
    }
  }

  void TaskScheduler::destroy()
  {
    if (g_tbb_threads_initialized) {
      g_tbb_threads.terminate();
      g_tbb_threads_initialized = false;
    }
  }
}
<|endoftext|>