Beispiel #1
0
CHEWING_API int chewing_Init(
		const char *dataPath,
		const char *hashPath )
{
	/* initialize Tree, Char, and Dict */
	/* FIXME: check the validation of dataPath */
	InitTree( dataPath );
	InitChar( dataPath );
	InitDict( dataPath );

	/* initialize Hash */
	/* FIXME: check the validation of hashPath */
	InitHash( hashPath );

	/* initialize SymbolTable */
	if ( ! InitSymbolTable( (char*) hashPath ) )
		InitSymbolTable( (char*) dataPath );
	if ( ! InitEasySymbolInput( (char *) hashPath ) )
		InitEasySymbolInput( (char *) dataPath );

	/* initialize HanyuPinYin table */
	if ( ! InitHanyuPinYin( hashPath ) )
		InitHanyuPinYin( dataPath );

#ifdef ENABLE_DEBUG
{
        char *dbg_path;
	int failsafe = 1;
	dbg_path = getenv( "CHEWING_DEBUG" );
	if ( dbg_path ) {
		fp_g = fopen( dbg_path, "w+" );
		if ( fp_g )
			failsafe = 0;
	}
	if ( failsafe == 1 ) {
		dbg_path = FAILSAFE_OUTPUT;
	        fp_g = fopen( dbg_path, "w+" );
		if ( ! fp_g ) {
			fprintf( stderr, 
				"Failed to record debug message in file.\n"
				"--> Output to stderr\n" );
		}
	}
	/* register debug service */
	if ( fp_g )
		addTerminateService( TerminateDebug );
}
#endif
	bTerminateCompleted = 0;
	return 0;
}
Beispiel #2
0
 void main()
 {
   int i;
   CSTree T,p,q;
   TElemType e,e1;
   InitTree(T);
   printf("构造空树后,树空否? %d(1:是 0:否) 树根为%c 树的深度为%d\n",TreeEmpty(T),Root(T),TreeDepth(T));
   CreateTree(T);
   printf("构造树T后,树空否? %d(1:是 0:否) 树根为%c 树的深度为%d\n",TreeEmpty(T),Root(T),TreeDepth(T));
   printf("先根遍历树T:\n");
   PreOrderTraverse(T,vi);
   printf("\n请输入待修改的结点的值 新值: ");
   scanf("%c%*c%c%*c",&e,&e1);
   Assign(T,e,e1);
   printf("后根遍历修改后的树T:\n");
   PostOrderTraverse(T,vi);
   printf("\n%c的双亲是%c,长子是%c,下一个兄弟是%c\n",e1,Parent(T,e1),LeftChild(T,e1),RightSibling(T,e1));
   printf("建立树p:\n");
   InitTree(p);
   CreateTree(p);
   printf("层序遍历树p:\n");
   LevelOrderTraverse(p,vi);
   printf("\n将树p插到树T中,请输入T中p的双亲结点 子树序号: ");
   scanf("%c%d%*c",&e,&i);
   q=Point(T,e);
   InsertChild(T,q,i,p);
   printf("层序遍历树T:\n");
   LevelOrderTraverse(T,vi);
   printf("\n删除树T中结点e的第i棵子树,请输入e i: ");
   scanf("%c%d",&e,&i);
   q=Point(T,e);
   DeleteChild(T,q,i);
   printf("层序遍历树T:\n",e,i);
   LevelOrderTraverse(T,vi);
   printf("\n");
   DestroyTree(T);
 }
Beispiel #3
0
void unitTest() {
    TreeType tree = InitTree();
    printf("After initlizing tree:\n");
    PrintTree(tree);
    PositionType question = 0;
    PositionType answer = 5;
    printf("IsLeaf test 1: %s\n", IsLeaf(tree, question) ? "error" : "pass");
    printf("IsLeaf test 2: %s\n", IsLeaf(tree, answer) ? "pass" : "error");
    printf("Top test: %s\n", Top(tree) == 0 ? "pass" : "error");
    printf("Question test 1: %s\n", strcmp(Question(tree, question), "Is it furry?") == 0 ? "pass" : "error");
    printf("Question test 2: %s\n", strcmp(Question(tree, answer), "Is it a lizard?") == 0 ? "pass" : "error");
    printf("%s\n", Question(tree, answer));
    ReplaceNode(tree, 7, "a kitten", "Is it an adult?");
    PrintTree(tree);
}
Beispiel #4
0
/*----------*/
TTree *NewTree()
{
	TTree *tree;
	
	if ( (tree=(TTree *)malloc(sizeof(TTree)))==NULL ) {
		strcpy(treeErrorMsg, "Out of memory creating tree.");
		return NULL;
	}
	memset(tree, 0, sizeof(TTree)); /* grj */
	tree->capacity=0;
	CheckCapacity(tree, 1000);
	
	InitTree(tree);
	
	return tree;
} /* NewTree */
BOOL CIfExpressEditorDlg::OnInitDialog()
{
	CCxBCGPDialog::OnInitDialog();
	ModifyStyle( WS_THICKFRAME, 0, SWP_FRAMECHANGED|SWP_DRAWFRAME );
	// TODO:  在此添加额外的初始化
	SetIcon(AfxGetApp()->LoadIcon(IDR_MAINFRAME), TRUE); // Set big icon
	if (!InitDlgCtrl())
	{
		MessageBox("解析输入条件表达式失败!",g_lpszAppTitle,MB_OK|MB_ICONERROR);
		EndDialog(0);
	}

	InitTree();
	return TRUE;  // return TRUE unless you set the focus to a control
	// 异常: OCX 属性页应返回 FALSE
}
Beispiel #6
0
void DlgCScenarioManager::OnCloneWithOutChild() 
{
	// TODO: Add your command handler code here
	HTREEITEM hItem = m_tree.GetSelectedItem();
	if(hItem == NULL)
		return;
	DWORD key = m_tree.GetItemData(hItem);
	Scenario *pScenario = m_manager.LookUp(key);
	Scenario *pClone = m_manager.CloneWithOutChild(pScenario,DefaultName(pScenario));
	if(pClone != NULL)
	{
		InitTree(pClone,m_tree.GetParentItem(hItem));
		InitPage();
		UpdateData(FALSE);
	}
}
Beispiel #7
0
BOOL DlgCScenarioManager::OnInitDialog() 
{
	CDialog::OnInitDialog();
	
	// TODO: Add extra initialization here
	m_tab.AddPage(IDS_STRSUMMARY, &m_page1, IDD_SUMMARY);
	m_tab.AddPage(IDS_STRDETAILS, &m_page2, IDD_DETAILS);
	m_tab.Show();

	m_strCurScenario = m_manager.GetCurAncestName();
	InitTree(m_manager.GetBaseScenario());
	m_tree.SelectItem(m_tree.GetRootItem());
    InitPage();
	UpdateData(FALSE);
	return TRUE;  // return TRUE unless you set the focus to a control
	              // EXCEPTION: OCX Property Pages should return FALSE
}
Beispiel #8
0
void DlgCScenarioManager::OnPromote() 
{
	// TODO: Add your command handler code here
	if(IDCANCEL ==AfxMessageBox(IDS_PROMOTESCENARIOMSG,MB_OKCANCEL))
		return;
	
	HTREEITEM hItem = m_tree.GetSelectedItem();
	if(hItem == NULL)
		return;
	DWORD key = m_tree.GetItemData(hItem);
	Scenario *pScenario = m_manager.LookUp(key);
    if(m_manager.Promote(pScenario))
	{
		InitTree(pScenario,m_tree.GetParentItem(m_tree.GetParentItem(hItem)));
		m_tree.DeleteItem(hItem);
	}
	InitPage();
}
void main()
{
	int i;
	CSTree T, p, q;
	TElemType e, e1;

	InitTree(T);
	printf("构造空树后,树空否?%d(1:是 0:否)。树根为%c,树的深度为%d。\n",
	       TreeEmpty(T), Root(T), TreeDepth(T));
	CreateTree(T);
	printf("构造树T后,树空否?%d(1:是 0:否)。树根为%c,树的深度为%d。\n",
	       TreeEmpty(T), Root(T), TreeDepth(T));
	printf("层序遍历树T:\n");
	LevelOrderTraverse(T, visit);
	printf("请输入待修改的结点的值 新值:");
	scanf("%c%*c%c%*c", &e, &e1);
	Assign(T, e, e1);
	printf("层序遍历修改后的树T:\n");
	LevelOrderTraverse(T, visit);
	printf("%c的双亲是%c,长子是%c,下一个兄弟是%c。\n", e1, Parent(T, e1),
	       LeftChild(T, e1), RightSibling(T, e1));
	printf("建立树p:\n");
	CreateTree(p);
	printf("层序遍历树p:\n");
	LevelOrderTraverse(p, visit);
	printf("将树p插到树T中,请输入T中p的双亲结点 子树序号:");
	scanf("%c%d%*c", &e, &i);
	q = Point(T, e);
	InsertChild(T, q, i, p);
	printf("层序遍历修改后的树T:\n");
	LevelOrderTraverse(T, visit);
	printf("先根遍历树T:\n");
	PreOrderTraverse(T, visit);
	printf("\n后根遍历树T:\n");
	PostOrderTraverse(T, visit);
	printf("\n删除树T中结点e的第i棵子树,请输入e i:");
	scanf("%c%d", &e, &i);
	q = Point(T, e);
	DeleteChild(T, q, i);
	printf("层序遍历修改后的树T:\n");
	LevelOrderTraverse(T, visit);
	DestroyTree(T);
}
Beispiel #10
0
DirectoryTree::DirectoryTree
	(
	wxWindow * wndParent,
	const wxWindowID id,
	const wxPoint& pntPosition,
	const wxSize& siz,
	long nStyle
	) :
  wxTreeCtrl(wndParent, id, pntPosition, siz, nStyle),
	m_wndParent(wndParent),
  m_imlButtons(9, 9, true), m_iml(16, 16, true),
	m_bShowHidden(false)
  {
  wxASSERT_MSG(wndParent != 0, wxT("DirectoryTree::DirectoryTree() 'wndParent' == 0."));
  wxASSERT_MSG(res, wxT("DirectoryTree::DirectoryTree() 'res' not loaded."));

	// TBI: work around wx's silly behaviour of showing a different icon when
  // the tree item is expanded
	// wx works as follows: one item for unselected (expanded or not) and selected open,
  // another for selected closed
	// It sounds logical, but it's actually silly:
  // showing 'openness' is what buttons, not icons, are for.
	// We want a different selected icon
	wxBitmap bmpFolderClosed = res->GetImage(resFolderNormal);
	m_iml.Add(bmpFolderClosed);
	m_iml.Add(bmpFolderClosed);
	
  // FIXME: why is this not in the msw version?
#ifdef _GENERIC_TREECTRL_H_
	wxBitmap bmpPlus = res->GetImage(resButtonPlus);
	wxBitmap bmpMinus = res->GetImage(resButtonMinus);
	m_imlButtons.Add(bmpPlus); // Unselected closed button
	m_imlButtons.Add(bmpPlus); // Selected closed button
	m_imlButtons.Add(bmpMinus); // Unselected open button
	m_imlButtons.Add(bmpMinus); // Selected open button
  SetButtonsImageList(&m_imlButtons);
#endif // def __UNIX__

	SetImageList(&m_iml);
	InitTree();
  }
KDPhotonsTree::KDPhotonsTree(Photons* toAdd)
{
	DWORD startTime = timeGetTime();

	size_t curNumberOfThreads = GLOBAL_PROPERTIES::numberOfThreads;
	m_logOfNumberOfThreads = 0;
	while(curNumberOfThreads>>=1)
		++m_logOfNumberOfThreads;

	size_t n = toAdd->size();
	if(!n) 
		throw Error("Empty photon vector");
	GLOBAL_PROPERTIES::numberOfProcessedPhotons += n;

	for(int i = 1 ; ; ++i) {
		n >>= i;
		if(!n) {
			n = 1 << i;
			break;
		}
		n <<= i;
	}


	m_numberOfPhotons = n;

	m_treeArray = new TreeElement[m_numberOfPhotons];

	InitTree(*toAdd, 1, toAdd->begin(), toAdd->end(), 0);

	m_photonsHeaps = new MaxHeap[GLOBAL_PROPERTIES::numberOfThreads];

	std::cout << "Photons KDtree build was over in " << (timeGetTime() - startTime) << " ms" << std::endl;

	delete toAdd;
}
Beispiel #12
0
void CPageDocuments::Initialize()
{
//  m_list.SetExtendedStyle(LVS_EX_FULLROWSELECT);
  CreateImageList();
  InitTree();
}
Beispiel #13
0
CHEWING_API ChewingContext *chewing_new()
{
	ChewingContext *ctx;
	int ret;
	char search_path[PATH_MAX];
	char path[PATH_MAX];

	ctx = ALC( ChewingContext, 1 );
	if ( !ctx )
		goto error;

	ctx->output = ALC ( ChewingOutput, 1 );
	if ( !ctx->output )
		goto error;

	ctx->data = allocate_ChewingData();
	if ( !ctx->data )
		goto error;

	chewing_Reset( ctx );

	ret = get_search_path( search_path, sizeof( search_path ) );
	if ( ret )
		goto error;

	ret = find_path_by_files(
		search_path, DICT_FILES, path, sizeof( path ) );
	if ( ret )
		goto error;
	ret = InitDict( ctx->data, path );
	if ( ret )
		goto error;
	ret = InitTree( ctx->data, path );
	if ( ret )
		goto error;

	ret = InitHash( ctx->data );
	if ( !ret )
		goto error;

	ctx->cand_no = 0;

	ret = find_path_by_files(
		search_path, SYMBOL_TABLE_FILES, path, sizeof( path ) );
	if ( ret )
		goto error;
	ret = InitSymbolTable( ctx->data, path );
	if ( ret )
		goto error;

	ret = find_path_by_files(
		search_path, EASY_SYMBOL_FILES, path, sizeof( path ) );
	if ( ret )
		goto error;
	ret = InitEasySymbolInput( ctx->data, path );
	if ( ret )
		goto error;

	ret = find_path_by_files(
		search_path, PINYIN_FILES, path, sizeof( path ) );
	if ( ret )
		goto error;
	ret = InitPinyin( ctx->data, path );
	if ( !ret )
		goto error;

	return ctx;
error:
	chewing_delete( ctx );
	return NULL;
}
Beispiel #14
0
void Encode()
{
     int i,c,len,r,s,lml,cbp;
     unsigned char codebuf[17],mask;
     InitTree();
     codebuf[0]=0;
     cbp=mask=1;
     s=0;
     r=N-F;
     memset(buffer,' ',r);
     for( len=0; len<F && (c = GetByte()) != EOF; len++ )
         buffer[r+len]=c;
     if(len==0)  return;
     for(i=1;i<=F;i++)
         InsertNode(r-i);
     InsertNode(r);
     do
     {
         if(mlen>len)
             mlen=len;
         if(mlen<=THRESHOLD)
         {
             mlen=1;
             codebuf[0]|=mask;
             codebuf[cbp++]=buffer[r];
         }
         else
         {
             codebuf[cbp++]=(unsigned char)mpos;
             codebuf[cbp++]=(unsigned char)(((mpos>>4)&0xF0)|(mlen-(THRESHOLD+1)));
         }
         if((mask<<=1)==0)
         {
             for(i=0;i<cbp;i++)
                 PutByte(codebuf[i]);
             codebuf[0]=0;
             cbp=mask=1;
         }
         lml=mlen;
         for(i=0;i<lml&&(c=GetByte())!=EOF;i++)
         {
             DeleteNode(s);
             buffer[s]=c;
             if(s<F-1)
                 buffer[s+N]=c;
             s=(s+1)&(N-1);
             r=(r+1)&(N-1);
             InsertNode(r);
         }
         while(i++<lml)
         {
             DeleteNode(s);
             s=(s+1)&(N-1);
             r=(r+1)&(N-1);
             if(--len)
                 InsertNode(r);
         }
     }while(len>0);

     if(cbp>1)
         for(i=0;i<cbp;i++)
             PutByte(codebuf[i]);
}
void KDPhotonsTree::InitTree(const Photons &photons, const size_t index, const Photons::iterator begin, const Photons::iterator end, const size_t depth) {
	const size_t dist_it = end - begin;
	if(dist_it < 0) {
		throw Error("initializing KD tree error");
	}
	if(dist_it < 1) {
		if(index < m_numberOfPhotons && begin != photons.end())m_treeArray[index] = TreeElement(*begin, ST_NON_EXIST);
		return;
	}

	if(dist_it == 1) {
		if(index < m_numberOfPhotons)m_treeArray[index] = TreeElement(*begin, ST_LEAF);
		return;
	}
	
	Point min( GLOBAL_PROPERTIES::INFINITY,  GLOBAL_PROPERTIES::INFINITY,  GLOBAL_PROPERTIES::INFINITY);
	Point max(-GLOBAL_PROPERTIES::INFINITY, -GLOBAL_PROPERTIES::INFINITY, -GLOBAL_PROPERTIES::INFINITY);
	for(Photons::iterator it = begin; it != end; it++) {
		if(it->position.x() < min.x()) min.x(it->position.x());
		if(it->position.y() < min.y()) min.y(it->position.y());
		if(it->position.z() < min.z()) min.z(it->position.z());
		if(it->position.x() > max.x()) max.x(it->position.x());
		if(it->position.y() > max.y()) max.y(it->position.y());
		if(it->position.z() > max.z()) max.z(it->position.z());
	}

	Point distPoint = max - min;
	Split_type split = 
			(distPoint.x() >= distPoint.y() && distPoint.x() >= distPoint.z()) ? ST_X_COORD 
			: ( (distPoint.y() >= distPoint.z()) ? ST_Y_COORD : ST_Z_COORD );

	std::sort(begin, end, split == ST_X_COORD ? x_comp_func : (split == ST_Y_COORD ? y_comp_func : z_comp_func) );

	const Photons::iterator middle = begin + ((end - begin)/2);
	if(((index << 1) | 1) < m_numberOfPhotons) {
		m_treeArray[index] = TreeElement(*middle, split);


		if(depth < m_logOfNumberOfThreads) {
			// Need to split to two threads (create extra one)

			/////////////////////////////////////////////////////////////
			// parallelization
			/////////////////////////////////////////////////////////////
			DWORD tID;
			HANDLE handle;

			PhotonsTreeBuildThreadArguments *arguments = 
				new PhotonsTreeBuildThreadArguments(*this, photons, (index << 1), begin, middle, depth+1);
			
			handle = CreateThread(
				NULL,
				0,
				ThreadBuildFunc,
				(LPVOID)arguments,
				0,
				&tID);
			/////////////////////////////////////////////////////////////

			// Complete second part of tree itself
			InitTree(photons, (index << 1) | 1, middle+1, end   , depth+1);

			// wait for sibling thread to finish his work
			WaitForSingleObject(handle, INFINITE);


		} else {
			InitTree(photons, (index << 1)    , begin   , middle, depth+1);
			InitTree(photons, (index << 1) | 1, middle+1, end   , depth+1);
		}
	} else {
		m_treeArray[index] = TreeElement(*middle, ST_LEAF);
	}
} 
Beispiel #16
0
void SWCompress_RW(SWCompressPtr state, SDL_RWops *in, SDL_RWops *out)
{
    int  i, c, len, r, s, last_match_length, code_buf_ptr;
    unsigned char mask;

    InitTree(state);  /* initialize trees */

    state->code_buf[0] = 0;

    code_buf_ptr = mask = 1;
    s = 0;
    r = N - F;

    for (i = s; i < r; i++)
    {
        state->text_buf[i] = OFTEN;  /* Clear the buffer with
        any character that will appear often. */
    }

    for (len = 0; len < F && (c = SDL_getc(in)) != EOF; len++ )
    {
        state->text_buf[r + len] = c;  /* Read F bytes into the last F bytes of the buffer */
    }

    state->textsize = len;
    if (state->textsize == 0)
        return;  /* text of size zero */

    for (i = 1; i <= F; i++)
        InsertNode(state, r - i);  /* Insert the F strings,
        each of which begins with one or more 'space' characters.  Note
        the order in which these strings are inserted.  This way,
        degenerate trees will be less likely to occur. */
    InsertNode(state, r);  /* Finally, insert the whole string just read.  The
        global variables match_length and match_position are set. */
    do {
        if (state->match_length > len)
            state->match_length = len;  /* match_length
            may be spuriously long near the end of text. */
        if (state->match_length <= THRESHOLD) {
            state->match_length = 1;  /* Not long enough match.  Send one byte. */
            state->code_buf[0] |= mask;  /* 'send one byte' flag */
            state->code_buf[code_buf_ptr++] = state->text_buf[r];  /* Send uncoded. */
        } else {
            state->code_buf[code_buf_ptr++] = (unsigned char) state->match_position;
            state->code_buf[code_buf_ptr++] = (unsigned char)
                                              (((state->match_position >> 4) & 0xf0)
                                               | (state->match_length - (THRESHOLD + 1)));  /* Send position and
                    length pair. Note match_length > THRESHOLD. */
        }
        if ((mask <<= 1) == 0) {  /* Shift mask left one bit. */
            for (i = 0; i < code_buf_ptr; i++)  /* Send at most 8 units of */
            {
                SDL_putc(state->code_buf[i],out); /* code together */
            }

            state->codesize += code_buf_ptr;
            state->code_buf[0] = 0;
            code_buf_ptr = mask = 1;
        }
        last_match_length = state->match_length;

        for (i = 0; i < last_match_length &&
                (c = SDL_getc(in)) != EOF; i++ )
        {
            DeleteNode(state, s);       /* Delete old strings and */
            state->text_buf[s] = c; /* read new bytes */
            if (s < F - 1) state->text_buf[s + N] = c;  /* If the position is
                near the end of buffer, extend the buffer to make
                string comparison easier. */
            s = (s + 1) & (N - 1);
            r = (r + 1) & (N - 1);
            /* Since this is a ring buffer, increment the position
                 modulo N. */
            InsertNode(state, r);   /* Register the string in text_buf[r..r+F-1] */
        }

        while (i++ < last_match_length) {   /* After the end of text, */
            DeleteNode(state, s);                   /* no need to read, but */
            s = (s + 1) & (N - 1);
            r = (r + 1) & (N - 1);
            if (--len) InsertNode(state, r);        /* buffer may not be empty. */
        }
    } while (len > 0);  /* until length of string to be processed is zero */

    if (code_buf_ptr > 1) {     /* Send remaining code. */
        for (i = 0; i < code_buf_ptr; i++)
        {
            SDL_putc(state->code_buf[i],out);
        }
        state->codesize += code_buf_ptr;
    }
}
Beispiel #17
0
//*******MAIN*******************************************************************
int main (int argc, char** argv)
{  
    std::cout<<"--------DUMPER TEMPLATE FIT: READ RAW DATA AND PRODUCE RECO TREE--------"<<std::endl;

    //-----this map tells how the MCPs will be order in the output tree. The names should match the cfg file----
    Fill_MCPList();  //look into the MCPMap.h class
    
    //--------Read Options--------------------------------
    ifstream inputCfg (argv[1], ios::in);

    std::string inputFolder = argv[2];
    int nChannels = atoi (argv[3]);
    std::string outputFile = argv[4];
    std::string ProMedioFile = argv[5];

    TProfile** wf_promed = new TProfile*[10];
    TH1F** templateHisto = new TH1F*[10];
    double pro_medio_CF[10] = {0., 0., 0., 0., 0., 0., 0., 0., 0., 0.};
    double pro_medio_Charge[10] = {0., 0., 0., 0., 0., 0., 0., 0., 0., 0.};
    TFile* inF = TFile::Open(ProMedioFile.c_str(),"read");                                                                
    for(int iCh=0; iCh<10; ++iCh) {
      wf_promed[iCh] = (TProfile*)inF->Get(Form("wf_promed_%d",iCh));                                                        
      wf_promed[iCh]->SetDirectory(0);                                                                                       
    }
    inF->Close();
    inF->Delete();                       
    for(int iCh=0; iCh<10; ++iCh) {                                                                                       
      templateHisto[iCh] = new TH1F(Form("templateHisto_%d",iCh), "", 1024, 0., 1024.);                                      
      for(int iBins=1; iBins<=1024; ++iBins) {
	if(iBins <= 100) templateHisto[iCh]->SetBinContent(iBins, wf_promed[iCh]->GetBinContent(iBins+150));  
	else if(iBins > 100 && iBins < 250) templateHisto[iCh]->SetBinContent(iBins, templateHisto[iCh]->GetBinContent(iBins-100));  
	else templateHisto[iCh]->SetBinContent(iBins, wf_promed[iCh]->GetBinContent(iBins));
      }
      double amp = 0.5;
      TimeConstFrac_ProMedio(templateHisto[iCh], amp, pro_medio_CF[iCh]);
      pro_medio_Charge[iCh] = templateHisto[iCh]->Integral(pro_medio_CF[iCh]-5, pro_medio_CF[iCh]+20);
      wf_promed[iCh]->Delete();                                                                                              
      //            std::cout << " iCh = " << iCh << " pro_medio_CF[iCh] = " << pro_medio_CF[iCh] << " pro_medio_Charge[iCh] = " << pro_medio_Charge[iCh] << std::endl;
    }                                                                                                                     


    // for(int iCh=0; iCh<10; ++iCh) std::cout << " templateHisto[iCh]->GetEntries() = " << templateHisto[iCh]->GetEntries() << std::endl;
    //    return 500;                                                                                            


    //---------output tree----------------
    TFile* outROOT = TFile::Open(("ntuples/reco_"+outputFile+".root").c_str(),"recreate");  
    outROOT->cd();
    
    TTree* outTree = new TTree("reco_tree", "reco_tree");
    outTree->SetDirectory(0);
    SetOutTree(outTree);
    
   
    int run=0, chNumber=0, HVtemp=0, PC=0;
    float X0temp=0.;
    std::string name, trig1, trig2;

    //---------definitions-----------
    std::map<int, int> PCOn;
    std::map<int, int> HVVal; 
    std::map<int, std::string> MCPName; 

    int start=0;
    //-------start to read the cfg file--------
    while(!inputCfg.eof())  
    {
      PCOn.clear();
      HVVal.clear();
      MCPName.clear();

      if (start==0) {   //read trigger chambers
	inputCfg >> trig1 >> trig2;
	start=1;
      }

      //-----fill maps--------
      for (int count=0; count<nChannels; count++)   //read exactly nChannels lines of the cfg file -> be careful to give the right number in input!!!!
	{
	  inputCfg >> run >> chNumber >> HVtemp >> X0temp >> PC >> name;

	  PCOn.insert(std::make_pair(chNumber,PC)); 
	  HVVal.insert(std::make_pair(chNumber,HVtemp)); 
	  MCPName.insert(std::make_pair(chNumber,name)); 
	}

      //-----Definitions
      vector<float> digiCh[10];
      float timeCF[10], timeCFcorr[10];
      float timeOT[10];
      float timeMax[10];
      float intBase[10], intSignal[10], intSignalcorr[10], ampMax[10];
      ///int fibreX[8], hodoYchannels[8];
      
      TH1F** wfHisto = new TH1F*[10];
      TF1** f_templateFit = new TF1*[10];      

      //--reading wire chamber from other tree --
      TChain* t1 = new TChain("outputTree");
      InitTree2(t1);

      //---Chain
      TChain* chain = new TChain("H4tree");
      InitTree(chain);

      char command1[300];
      sprintf(command1, "find  %s/%d/*/dqmPlotstotal.root > listTemp_%s_%d.txt", (inputFolder).c_str(), run, outputFile.c_str(), run);
      system(command1);
      char command2[300];
      sprintf(command2, "find  %s/%d/[0-9]*.root > listTemp2_%s_%d.txt", (inputFolder).c_str(), run, outputFile.c_str(), run);
      system(command2);

      char list1[200];
      char list2[200];
      sprintf (list1, "listTemp_%s_%d.txt", outputFile.c_str(), run);
      sprintf (list2, "listTemp2_%s_%d.txt", outputFile.c_str(), run);

      ifstream rootList (list1);
      ifstream rootList2 (list2);

      while (!rootList.eof() && !rootList2.eof())
	{
	  char iRun_tW[70];
	  rootList >> iRun_tW;
	  char iRun_str[70];
	  rootList2 >> iRun_str;
	  
	  TChain* tTemp = new TChain("outputTree");
	  tTemp->Add(iRun_tW);
	  TChain* tTempH4 = new TChain("H4tree");
	  tTempH4->Add(iRun_str);
	  
	  if (tTemp->GetEntries() == tTempH4->GetEntries())
	    {
	      t1->Add(iRun_tW);	
	      chain->Add(iRun_str);	
	    }
	  else
	    std::cout<<"Bad spill found.. Skipped"<<std::endl;
	  tTemp->Delete();
	  tTempH4->Delete();
	}

      char command3[300];
      sprintf(command3, "rm listTemp_%s_%d.txt", outputFile.c_str(), run);
      char command4[300];
      sprintf(command4, "rm listTemp2_%s_%d.txt", outputFile.c_str(), run);
      
      system(command3);
      system(command4);
      
      std::cout<<"start reading run: "<<run<<std::endl;
      
      //-----Data loop--------------------------------------------------------
      for(int iEntry=0; iEntry<chain->GetEntries(); iEntry++){
	//      for(int iEntry=7; iEntry<8; iEntry++){    //RA
	if(iEntry % 1000 == 0)	cout << "read entry: " << iEntry << endl;
            //-----Unpack data--------------------------------------------------
            for(int iCh=0; iCh<nChannels; iCh++)
            {
                digiCh[iCh].clear();
		wfHisto[iCh] = new TH1F(Form("wfHisto_%d", iCh), "", 1024, 0., 1024.);
            }

            //---Read the entry
            chain->GetEntry(iEntry);
 
	    unsigned int spill=spillNumber;
	    unsigned int event=evtNumber;

	    /*	    for(unsigned int iCh=0; iCh<nAdcChannels; iCh++)
		{
                    if(adcBoard[iCh] == 1 && adcChannel[iCh] == 0) 
                        sci_front_adc = adcData[iCh];
		    if(adcBoard[iCh] == 1 && adcChannel[iCh] >= HODOX_ADC_START_CHANNEL &&
		       adcChannel[iCh] <= HODOX_ADC_END_CHANNEL)
			fibreX[(adcChannel[iCh]-HODOX_ADC_START_CHANNEL)] = adcData[iCh];
		    if(adcBoard[iCh] == 1 && adcChannel[iCh] >= HODOY_ADC_START_CHANNEL &&
		       adcChannel[iCh] <= HODOY_ADC_END_CHANNEL)
			fibreY[(adcChannel[iCh]-HODOY_ADC_START_CHANNEL)] = adcData[iCh];
		}
	    */
	    int tStart[10] = {0,0,0,0,0,0,0,0,0,0};
	    int tStop[10] = {0,0,0,0,0,0,0,0,0,0};
	    int tMax[10] = {0,0,0,0,0,0,0,0,0,0};
	    float aMax[10] = {10000., 10000., 10000., 10000., 10000., 10000., 10000., 10000., 10000., 10000.};
	    float bLine[10] = {0.,0.,0.,0.,0., 0.,0.,0.,0.,0.};
	    //---Read digitizer samples
	    for(unsigned int iSample=0; iSample<nDigiSamples; iSample++){
	      if(iSample > 1024*10 - 1) break;
	      if (digiGroup[iSample] == 1 && digiChannel[iSample] == 0){
		digiCh[9].push_back(digiSampleValue[iSample]);
		wfHisto[9]->SetBinContent((iSample%1024) + 1, digiSampleValue[iSample]);

		int iBin = (iSample%1024) + 1;
		float value = digiSampleValue[iSample];
		if((iBin >= 10 && iBin < 30) || (iBin >= 500 && iBin < 1000)) bLine[9] += value/520;
		//		if(digiChannel[iSample] == 9) std::cout << " value = " << value << std::endl;
		if(value < aMax[9]) { aMax[9] = value; tMax[9] = iBin; }
		if(iBin > 50 && value < 500. && tStart[9] == 0) tStart[9] = iBin;
		if(iBin > 50 && value > 500. && tStart[9] != 0 && tStop[9] == 0) tStop[9] = iBin;		
	      }
	      else{
		digiCh[digiChannel[iSample]].push_back(digiSampleValue[iSample]);
		wfHisto[digiChannel[iSample]]->SetBinContent((iSample%1024) + 1, digiSampleValue[iSample]); 

		int iBin = (iSample%1024) + 1;
		float value = digiSampleValue[iSample];
		if((iBin >= 10 && iBin < 30) || (iBin >= 500 && iBin < 1000)) bLine[digiChannel[iSample]] += value/520;
		if(digiChannel[iSample] == 9) std::cout << " value = " << value << std::endl;
		if(value < aMax[digiChannel[iSample]]) { aMax[digiChannel[iSample]] = value; tMax[digiChannel[iSample]] = iBin;}
		if(iBin > 50 && value < 500. && tStart[digiChannel[iSample]] == 0) tStart[digiChannel[iSample]] = iBin;
		if(iBin > 50 && value > 500. && tStart[digiChannel[iSample]] != 0 && 
		   tStop[digiChannel[iSample]] == 0) tStop[digiChannel[iSample]] = iBin;
	      }
	    }

	    //---loop over MPC's channels  
            for(int iCh=0; iCh<nChannels; iCh++){
	      if(iCh < 4) continue;
	      if(iCh == 8) continue;

	      // std::cout << " loop over MCP iCh = " << iCh  << std::endl;
	      // std::cout << " bLine[iCh] = " << bLine[iCh] << std::endl;
	      // std::cout << " aMax[iCh] = " << aMax[iCh] << std::endl;
	      // std::cout << " tMax[iCh] = " << tMax[iCh] << std::endl;
	      // std::cout << " tStart[iCh] = " << tStart[iCh] << std::endl;
	      // std::cout << " tStop[iCh] = " << tStop[iCh] << std::endl;

	      tMax[iCh] -= 300;

	      double scale = 0.;
	      double scaleErr = 0.;
	      double baseL = 0.;
	      double baseLErr = 0.;
	      double xTime = 0.;
	      double xTimeErr = 0.;
	      
	      FindTemplateFit(scale, scaleErr, baseL, baseLErr, xTime, xTimeErr, tStart[iCh], tStop[iCh], tMax[iCh], aMax[iCh], bLine[iCh], templateHisto[iCh], wfHisto[iCh], &(f_templateFit[iCh]));

	      float par0 = f_templateFit[iCh]->GetParameter(0);
	      float par1 = f_templateFit[iCh]->GetParameter(1);
	      float par2 = f_templateFit[iCh]->GetParameter(2);
	      float par3 = f_templateFit[iCh]->GetParameter(3);

	      ampMax[iCh] = par0;
	      //tMax
	      timeMax[iCh] = (300. / par1) + par2;
	      timeCF[iCh] = (pro_medio_CF[iCh] / par1) + par2;
	      intSignal[iCh] = pro_medio_Charge[iCh] * par0/par1 + par3/par1 * 25;
	      intBase[iCh] = par3;

	      timeOT[iCh] = par2;
	      intSignalcorr[iCh] = par1;
	      timeCFcorr[iCh] = timeCF[iCh];

	      // std::cout << " >> timeMax[iCh] = " << timeMax[iCh] << std::endl;
	      // std::cout << " >> timeCF[iCh] = " << timeCF[iCh] << std::endl;
	      // std::cout << " >> f_templateFit[iCh]->GetParameter(0) = " << f_templateFit[iCh]->GetParameter(0) << std::endl;

	      /*
	      if(iCh == 4){
		TCanvas* c1 = new TCanvas();
		templateHisto[iCh]->Draw();
		f_templateFit[iCh]->Draw("same");
		c1->Print("pippo.png", "png");

		TCanvas* c2 = new TCanvas();
		wfHisto[iCh]->Draw();
		f_templateFit[iCh]->Draw("same");
		c2->Print("pippo2.png", "png");
		
		TFile outFile_template("outFile_template.root", "recreate");
		outFile_template.cd();
		iCh = 4;
		templateHisto[iCh]->Write(Form("promedio_%d", iCh));
		wfHisto[iCh]->Write(Form("wfHisto_%d", iCh));
		f_templateFit[iCh]->Write(Form("func_%d", iCh));
		outFile_template.Close();
	      }
	      */
	    }

	    /*	    
	    TFile outFile_template("outFile_template.root", "recreate");
	    outFile_template.cd();
	    for(int iCh=0; iCh<nChannels; iCh++){
	      if(iCh < 4) continue;
	      if(iCh == 8) continue;

	      templateHisto[iCh]->Write(Form("promedio_%d", iCh));
	      wfHisto[iCh]->Write(Form("wfHisto_%d", iCh));
	      f_templateFit[iCh]->Write(Form("func_%d", iCh));
	    }
	    outFile_template.Close();
	    return 100;
	    */

	    //--------dump ntuple - impulses are negative, invert the sign
	    for (int iCh=0; iCh<nChannels; iCh++)
	      {
		    time_CF[MCPList.at(MCPName.at(iCh))]   = timeCF[iCh];
		    time_CF_corr[MCPList.at(MCPName.at(iCh))]   = timeCFcorr[iCh];
		    time_OT[MCPList.at(MCPName.at(iCh))]   = timeOT[iCh];
		    time_Max[MCPList.at(MCPName.at(iCh))]   = timeMax[iCh];
		    amp_max[MCPList.at(MCPName.at(iCh))]   = ampMax[iCh];
		    amp_max_corr[MCPList.at(MCPName.at(iCh))]   = ampMax[iCh];
		    charge[MCPList.at(MCPName.at(iCh))]    = -intSignal[iCh];
		    charge_corr[MCPList.at(MCPName.at(iCh))]    = -intSignalcorr[iCh];
		    baseline[MCPList.at(MCPName.at(iCh))]  = intBase[iCh];

		    isPCOn[MCPList.at(MCPName.at(iCh))]      = PCOn.at(iCh);
		    HV[MCPList.at(MCPName.at(iCh))]          = HVVal.at(iCh);
		    if (strcmp((MCPName.at(iCh)).c_str(),trig1.c_str())==0)          isTrigger[MCPList.at(MCPName.at(iCh))] = 1;
		    //		    else if (strcmp((MCPName.at(iCh)).c_str(),trig2.c_str())==0)     isTrigger[MCPList.at(MCPName.at(iCh))] = 2;
		    else                                           isTrigger[MCPList.at(MCPName.at(iCh))] = 0;
		      
		    wfHisto[iCh]->Delete();
		  }
	    
      	     run_id = run;
	     X0     = X0temp;

	     t1->GetEntry(iEntry);
	     tdcX = (*TDCreco)[0];
	     tdcY = (*TDCreco)[1];

	     if (spill!=spillNumber || event!=evtNumber) {
	       std::cout<<"PROBLEM: non-coherent read"<<std::endl;
	       continue;
	     }

	     outTree->Fill();    
	     
      }
 
       //---Get ready for next run
        chain->Delete();
	t1->Delete();
    }
/*
 * Realiza la compresión del stream.
 */
void compress(int argc, char *argv[]) {
  int i;
  int c;
  int look_ahead_bytes;
  int current_position;
  int replace_count;
  int match_length;
  int match_position;

  /* Carga el buffer de anticipación. */
  current_position = 1;
  for ( i = 0 ; i < LOOK_AHEAD_SIZE ; i++ ) {
    if ( ( c = getchar() ) == EOF )
      break;
    window[ current_position + i ] = (unsigned char) c;
  }
  look_ahead_bytes = i; /* look_ahead_bytes = 17, excepto al final de
			   la compresión. */

  /* Inicializa el árbol de búsqueda binario. */
  InitTree( current_position );

  /* Longitud de la cadena encontrada. */
  match_length = 0;

  /* Posición de la cadena encontrada. */
  match_position = 0;

  /* Comienza la compresión. */
  while ( look_ahead_bytes > 0 ) {
    if ( match_length > look_ahead_bytes )
      match_length = look_ahead_bytes;
    /* Decidimos si enviar una "k" o un código "ij". */
    if ( match_length <= MIN_ENCODED_STRING_SIZE ) {
      /* "k": Un-encoded output. */
      bitio__put_bit(1);
      bitio__put_bits(window[ current_position ], 8);
      replace_count = 1;
    } else {
      /* "ij": Encoded output. */
      bitio__put_bit(0);
      bitio__put_bits(match_position, INDEX_SIZE);
      bitio__put_bits((match_length - (MIN_ENCODED_STRING_SIZE + 1)),
		      LENGTH_SIZE );
      replace_count = match_length;
    }

    /* Insertamos "replace_count" símbolos en el buffer de
       anticipación y los eleiminados del diccionario.*/
    for ( i = 0 ; i < replace_count ; i++ ) {
      /* Eliminamos del árbol binario de búsqueda los símbolos que
	 salen por la parte izquierda de la ventana deslizante. */
      DeleteString( MOD_WINDOW( current_position + LOOK_AHEAD_SIZE ) );
      /* Leemos los nuevos símbolos. */
      if ( ( c = getchar() ) == EOF )
	look_ahead_bytes--;
      else
	window[ MOD_WINDOW( current_position + LOOK_AHEAD_SIZE ) ]
	  = (unsigned char) c;
      /* Actualizamos el "puntero" por el que vamos comprimiendo el
	 stream de datos. No olvidemos que lo procesamos usando una
	 cola circular. */
      current_position = MOD_WINDOW( current_position + 1 );
      /* Insertamos en el árbol binario de búsqueda los nuevos
	 símbolos. */
      if ( look_ahead_bytes )
	match_length = AddString( current_position, &match_position );
    }
  };
  /* EOF alcanzado. */
  bitio__put_bit(0);
  bitio__put_bits(END_OF_STREAM, INDEX_SIZE);
  bitio__flush();
}
Beispiel #19
0
/*
______________________________________________________________________________________________

Main
______________________________________________________________________________________________

*/
int main(int argc, char *argv[])
{
	// --- Init Cluster variable ---------------------------------------------------------

	// carmen 0 => local execution i.e. show time on screen
	// carmen 1 => cluster execution i.e. refresh Performance.dat (default)

#if defined PARMPI
	// --- MPI Runtime system initialization
	// size - total number of processors
	// rnak - current CPU
	MPI_Init(&argc,&argv);
	MPI_Comm_size(MPI_COMM_WORLD, &size);
	MPI_Comm_rank(MPI_COMM_WORLD, &rank);
#else
  	size=1;
	rank=0;
#endif
  
	if (argc == 2)
		Cluster = atoi(argv[1]);

	// --- Print messages on screen- -----------------------------------------------------

	cout << "carmen: begin execution.\n\n";
	printf("Carmen %4.2f \n",CarmenVersion);
	cout << "Copyright (C) 2000-2005 by Olivier Roussel.\n";
	cout << "All rights reserved.\n\n";
	
#if defined PARMPI
	//Synchronize all parallel branches
  	MPI_Barrier(MPI_COMM_WORLD);
#endif

  	CPUTime.start();
  
  // --- Create first node of the tree structure ---------------------------------------

	Node 	*Mesh=0;
	FineMesh *FMesh=0;

	
	// --- Init global values (See Parameters.h and Parameters.cpp) ----------------------------

	cout << "carmen: init computation ...\n";
	InitParameters();

  // --- Debug output information for parallel execution -------------------------------------
  
#if defined PARMPI                                                                            
  	if (Multiresolution) 
  	{
		printf("\nParallel Multiresolution solver not implemented yet!\n");
		exit(0);
	}
	
  	printf("My Rank=%d\n",rank);
  
  	// --- Each CPU print his coordinates in the virtual processor cart ------------------------
	printf("Cart_i = %d;     Cart_j = %d;     Cart_k = %d;\n",coords[0],coords[1],coords[2]);
	
  	// --- Each CPU print his computation domain
  	printf("Xmin = %lf;     XMax = %lf;\n",XMin[1],XMax[1]);
	printf("Ymin = %lf;     YMax = %lf;\n",XMin[2],XMax[2]);
	printf("Zmin = %lf;     ZMax = %lf;\n",XMin[3],XMax[3]);
	
  	// --- And the local scale number ----------------------------------------------------------
  	printf("ScaleNb = %d\n",ScaleNb);
#endif
  
	// --- Allocate ----------------------------------------------------------------------------

	if (Multiresolution)
		Mesh = new Node;
	else
		FMesh = new FineMesh;

	// --- Init tree structure -----------------------------------------------------------------

	if (Multiresolution)
	{
		InitTree(Mesh);
		RefreshTree(Mesh);
	}

	// --- Compute initial integral values and init time step ----------------------------------

	if (Multiresolution)
		Mesh->computeIntegral();
	else
		FMesh->computeIntegral();
	
	// -- Write integral values --
	
	
			
	// -- Compute initial time step --
	InitTimeStep();

	if (rank==0) PrintIntegral("Integral.dat");

	// --- Save initial values into files ------------------------------------------------------

	if (PrintEvery == 0)
	{
		if (Multiresolution)
			View(Mesh, "Tree_0.dat", "Mesh_0.dat", "Average_0.dat");
		else
			View(FMesh,"Average_0.dat");
	}
	
	// --- When PrintEvery != 0, save initial values into specific name format ---

	if (PrintEvery != 0)
	{
		if (Multiresolution)
			ViewEvery(Mesh, 0);
		else
			ViewEvery(FMesh, 0);
	}

  	// --- Parallel execution only --------------------------------------------
  	// --- Save to disk DX header for ouput files -----------------------------
  	// --- This file is needed for the external postprocessing (merging files from the different processors)

#if defined PARMPI

	real 	tempXMin[4];
	real	tempXMax[4];
	
  	// --- Save original task parameters for the parallel execution
  	int tempScaleNb=ScaleNb;

  	// --- Simulate sequantial running
  	ScaleNb=AllTaskScaleNb;

  	for (int i=0;i<4;i++) 
  	{
  		tempXMin[i]=XMin[i];
		tempXMax[i]=XMax[i];
		// --- Simulate sequantial running
		XMin[i]=AllXMin[i];
		XMax[i]=AllXMax[i];
  	}

  	// --- Write header with parameters, as we have run sequantial code
  	if (rank==0) FMesh->writeHeader("header.txt");

  	// Restore variables
  	for (int i=0;i<4;i++) 
  	{
		XMin[i]=tempXMin[i];
   		XMax[i]=tempXMax[i];
	}
	
  	ScaleNb=tempScaleNb;

#endif  
  
  	// --- Done ---

	cout << "carmen: done.\n";

	// --- Write solver type ---

	if (Multiresolution)
		cout << "carmen: multiresolution (MR) solver.\n";
	else
		cout << "carmen: finite volume (FV) solver.\n";

	// --- Write number of iterations ---

	if (IterationNb == 1)
		cout << "carmen: compute 1 iteration ...\n";
  	else
		cout << "carmen: compute " << IterationNb << " iterations ...\n";
	
	printf("\n\n\n");

	// --- Begin time iteration ----------------------------------------------------------------

	for (IterationNo = 1; IterationNo <= IterationNb; IterationNo++)
	{

		// --- Time evolution procedure ---
		if (Multiresolution)
			TimeEvolution(Mesh);
		else
			TimeEvolution(FMesh);

		// --- Remesh ---
		 if (Multiresolution) Remesh(Mesh);

		// --- Check CPU Time ---
	  	CPUTime.check();

		// --- Write information every (Refresh) iteration ---
		if ((IterationNo-1)%Refresh == 0)
		{                                          
			// - Write integral values -
			if (rank==0) PrintIntegral("Integral.dat");

			if (Cluster == 0)
				ShowTime(CPUTime);  // Show time on screen
		  //else
			if (rank==0) Performance("carmen.prf"); // Refresh file "carmen.prf"
    		}

		// --- Backup data every (10*Refresh) iteration ---
		if ((IterationNo-1)%(10*Refresh) == 0 && UseBackup)
		{
			if (Multiresolution)
				Backup(Mesh);
			else
				Backup(FMesh);
    		}

		// --- Print solution if IterationNo = PrintIt1 to PrintIt6 ---
		if (Multiresolution)
			ViewIteration(Mesh);
		else
			ViewIteration(FMesh);

		// --- Print solution if IterationNo is a multiple of PrintEvery ---

		if (PrintEvery != 0)
		{
     			if (IterationNo%PrintEvery == 0)
			{
				if (Multiresolution)
					ViewEvery(Mesh, IterationNo);
				else
					ViewEvery(FMesh, IterationNo);
			}
		}

	// --- End time iteration ------------------------------------------------------------------
	}	

	// --- Backup final data  ------------------------------------------------------------------

	IterationNo--;

	if (UseBackup)
  {
		if (Multiresolution)
			Backup(Mesh);
		else
			Backup(FMesh);
	}

	// --- Write integral values ---------------------------------------------------------------
	
	if (rank==0) PrintIntegral("Integral.dat");
	
	IterationNo++;

	// --- Save values into file ---------------------------------------------------------------

	if (Multiresolution)
		View(Mesh, "Tree.dat", "Mesh.dat", "Average.dat");
	else
		View(FMesh, "Average.dat");

	cout << "\ncarmen: done.\n";
	
	// --- Analyse performance and save it into file -------------------------------------------
				
	if (rank==0) Performance("carmen.prf");	

	// --- End ---------------------------------------------------------------------------------

	if (Multiresolution)
		delete Mesh;
	else
		delete FMesh;


#if defined PARMPI

  	//free memory for the MPI runtime variables
	delete[] disp;
	delete[] blocklen;
	int sz;
	MPI_Buffer_detach(&MPIbuffer,&sz);
	// for (int i = 0; i < 4*Dimension; i++)	MPI_Request_free(&req[i]);
	MPI_Finalize();
	
#endif
    
  	cout <<"carmen: end execution.\n";
	return EXIT_SUCCESS;
}
HeronLocalFileStateMgr::HeronLocalFileStateMgr(const std::string& _topleveldir,
                                               EventLoop* eventLoop)
    : HeronStateMgr(_topleveldir), eventLoop_(eventLoop) {
  InitTree();
}
Beispiel #21
0
void PageDetail::Init(Scenario *pScenario)
{
	m_pCompManager = pScenario->GetCompManager();
    m_pScenario = pScenario;
	InitTree();
}
Beispiel #22
0
//---------------------------------------------------------------------------------------
// hlavni funkce se spoustou testu na overeni funkcnosti
//---------------------------------------------------------------------------------------
int main(void)
{
     Node *treeSet = InitTree();
     simplePrintAll(treeSet, 0);

     // test 1
     printf("Test 1.:");
     Node *r = findNodeByKey(treeSet, "IB002 Algorithms and data structures I");
     Node *algoritmy = findNodeByKey(treeSet, "algorithms");
     Node *found = findMinimalRootOfNodes(r, algoritmy);

     if (found == r)
     {
          printf("OK \n");
     }
     else
     {
          printf("Chyba: nalezeny uzel mel byt (%s), ale vas uzel byl (%s) \n",
                    r->key, found->key);
     }

     // test 2
    printf("Test 2.:");

    found = findMinimalRootOfNodes(algoritmy, algoritmy);
    if(found == algoritmy)
     {
        printf("OK \n");
     }
     else
     {
          printf("Chyba: nalezeny uzel mel byt (%s), ale vas uzel byl (%s) \n",
                    algoritmy->key, found->key);
     }

    // test 3
    printf("Test 3.:");

     Node *heapSort = findNodeByKey(r, "heap sort");
     Node *selectSort = findNodeByKey(r, "select sort");

     found = findMinimalRootOfNodes(heapSort, selectSort);
    if (found == findNodeByKey(r, "searching algorithms"))
     {
          printf("OK \n");
     }
     else
     {
          printf("Chyba, nalezeny uzel mel byt (%s), ale vas uzel byl (%s) \n",
                    findNodeByKey(r, "searching algorithms")->key, found->key);
     }

    // test 4
     printf("Test 4.:");

     Node *graphs = findNodeByKey(r, "graphs");
    Node *directedGraph = findNodeByKey(r, "directed graph");

    found = findMinimalRootOfNodes(graphs, directedGraph);

    if (found == graphs)
     {
          printf("OK \n");
     }
     else
     {
          printf("Chyba, nalezeny uzel mel byt (%s), ale vas uzel byl (%s) \n", graphs->key, found->key);
     }

    // test 5
     printf("Test 5.:");

    Node *BPlusTree = findNodeByKey(r, "B+ tree");
    Node *power = findNodeByKey(r, "power");

    found = findMinimalRootOfNodes(BPlusTree, power);

     if (found == r)
     {
          printf("OK \n");
     }
     else
     {
          printf("Chyba, nalezeny uzel mel byt (%s), ale vas uzel byl (%s) \n", r->key, found->key);
     }

    // test 6
     printf("Test 6.:");
     Node *dataStructures = findNodeByKey(r, "data structures");
     Node *mergeSort = findNodeByKey(r, "merge sort");

    found = findMinimalRootOfNodes(dataStructures, mergeSort);

    if (found == r)
     {
          printf("OK \n");
     }
     else
     {
          printf("Chyba, nalezeny uzel mel byt (%s), ale vas uzel byl (%s) \n", r->key, found->key);
     }

     DestroyTree(treeSet);

     return 0;
}
Beispiel #23
0
int main (int argc, char** argv)
{  
    // get run number
    std::string inputName = std::string(argv[1]);
    char split_char = '/';
    std::vector<std::string> tokens;
    std::istringstream split(inputName);
    for(std::string each; getline(split, each, split_char); 
        tokens.push_back(each));
    
    split_char = '_';
    std::vector<std::string> tokens_name;
    std::istringstream split_name(tokens.at(1));
    for(std::string each; getline(split_name, each, split_char); 
        tokens_name.push_back(each));

    const int Ch_ref1 = atoi((tokens_name.at(1)).c_str());
    const int Ch_ref2 = atoi((tokens_name.at(3)).c_str());
    const int Ch_1 = atoi((tokens_name.at(5)).c_str());
    const int Ch_2 = atoi((tokens_name.at(7)).c_str());
    const int Ch_3 = atoi((tokens_name.at(9)).c_str());

    std::vector<std::string> nameMCP;
    nameMCP.push_back("MiB1");
    nameMCP.push_back("MiB2");
    nameMCP.push_back("ScB");
    nameMCP.push_back("Planacon");
    nameMCP.push_back("MiB3");
    nameMCP.push_back("Roma2");
    if(tokens_name.at(0) == "Scan3") nameMCP.at(1) = "Roma1";

    std::vector<std::string> pcMCP;                                     
    for(unsigned int ii=0; ii<nameMCP.size(); ++ii) pcMCP.push_back("");
    pcMCP.at(Ch_ref1) = tokens_name.at(2);
    pcMCP.at(Ch_ref2) = tokens_name.at(4);
    pcMCP.at(Ch_1) = tokens_name.at(6);
    pcMCP.at(Ch_2) = tokens_name.at(8);
    pcMCP.at(Ch_3) = tokens_name.at(10);

    //---treshold setup Scan-dependent 
    init();
    const int iScanTh = atoi(argv[2])-1;
    float Ch_th[6]={0,0,0,0,0,0};
    Ch_th[Ch_ref1] = _th[iScanTh][Ch_ref1];
    Ch_th[Ch_ref2] = _th[iScanTh][Ch_ref2];
    Ch_th[Ch_1] = _th[iScanTh][Ch_1];
    Ch_th[Ch_2] = _th[iScanTh][Ch_2];
    Ch_th[Ch_3] = _th[iScanTh][Ch_3];


    TFile* out = TFile::Open((tokens_name.at(0)+"_outHistos.root").c_str(),"recreate");  
    out->cd();
    
    //Output dat
    std::ofstream data1(("analized_data/"+tokens_name.at(0)+"_"+nameMCP.at(Ch_1)+"_pc_"+pcMCP.at(Ch_1)+".dat").data());
    std::ofstream data2(("analized_data/"+tokens_name.at(0)+"_"+nameMCP.at(Ch_2)+"_pc_"+pcMCP.at(Ch_2)+".dat").data());
    std::ofstream data3(("analized_data/"+tokens_name.at(0)+"_"+nameMCP.at(Ch_3)+"_pc_"+pcMCP.at(Ch_3)+".dat").data());

    int nFiles = 1, iRun = 0, goodEvt = 0;
    int iScan = 0;
    
    //---usefull histos
    TH1F* chHistoBase_All[9];
    TH1F* chHistoSignal_All[9];
    TH1F* timeDiffHisto[9];
    TH1F* timeDiffHisto_Double = new TH1F("timeDiffHisto_Double", "timeDiffHisto_Double",5000,-10,10);
    //---histos initialization
    for(int iCh=0; iCh<6; ++iCh)
      {
	char h1[30], h2[30], h3[30];
	sprintf(h1, "histoBase_All_Ch%d", iCh);
	sprintf(h2, "histoSignal_All_Ch%d", iCh);
	sprintf(h3, "histoTime_Ch%d", iCh);
	chHistoBase_All[iCh] = new TH1F(h1,h1,30000,-30000,1000);
	chHistoSignal_All[iCh] = new TH1F(h2, h2,30000,-30000,1000);
	timeDiffHisto[iCh] = new TH1F(h3, h3,1024,0,1024);
      } 

    
    //---do runs loop
    ifstream log (argv[1], ios::in);
    while(log >> nFiles)
    {
      ++iScan;
      vector<float> digiCh[9];
      float timeCF[9];
      float baseline[9];
      float intSignal[9],  intBase[9];
      int count[5]={0,0,0,0,0}, spare[5]={0,0,0,0,0}, spare2[5]={0,0,0,0,0};
      int tot_tr1 = 0, tot_tr0 = 0, trig = 0;
      int HV1=0, HV2=0, HV3=0;
      
      TH1F* chHistoWF_Ch[9];
      TH1F* chHistoBase_Ch[9];
      TH1F* chHistoSignal_Ch[9];
      TH1F* timeDiffHisto_Triple_Ch1 = new TH1F(Form("timeDiffHisto_Triple_Ch1_Scan%d",iScan), "", 5000,-100,100);
      TH1F* timeDiffHisto_Triple_Ch2 = new TH1F(Form("timeDiffHisto_Triple_Ch2_Scan%d",iScan), "", 5000,-100,100);
      TH1F* timeDiffHisto_Triple_Ch3 = new TH1F(Form("timeDiffHisto_Triple_Ch3_Scan%d",iScan), "", 5000,-100,100);
      
      char ha[10];
      for (int iiw=0;iiw<9;++iiw){
	sprintf (ha,"histoWF_Ch%d_Scan_%d",iiw, iScan);
	chHistoWF_Ch[iiw] = new TH1F( ha, "", 1024,0.,1024);
	chHistoWF_Ch[iiw]->SetXTitle("Waveform");
	
	sprintf (ha,"histoBase_Ch%d_Scan_%d",iiw, iScan);
	chHistoBase_Ch[iiw] = new TH1F( ha, "", 30000,-30000,1000);
	chHistoBase_Ch[iiw] -> SetXTitle ("Integral BaseLine Ch(ADC)");
	
	sprintf (ha,"histoSignal_Ch%d_Scan_%d",iiw, iScan);
	chHistoSignal_Ch[iiw] = new TH1F( ha, "", 30000,-30000,1000);
	chHistoSignal_Ch[iiw] -> SetXTitle ("Integral Signal Ch(ADC)");
      }
      
      //---data chain
      TChain* chain = new TChain("eventRawData");
      InitTree(chain);
      for(int iFiles=0; iFiles<nFiles; iFiles++){
	log >> iRun;
	char iRun_str[30];
	sprintf(iRun_str, "../Analysis_TB/DATA/run_IMCP_%d_*.root", iRun);
	chain->Add(iRun_str);
	cout << "Reading:  ../Analysis_TB/DATA/run_IMCP_" << iRun << endl;
      }
      log >> HV1 >> HV2 >> HV3;
      
      for(int iEntry=0; iEntry<chain->GetEntries(); iEntry++) {
	
	//---always clear the std::vector !!!
	for(int iCh=0; iCh<9; iCh++) digiCh[iCh].clear();
	
	//---Read the entry
	chain->GetEntry(iEntry);
	
	//---DAQ bug workaround
	if(iRun < 145) goodEvt = 10;
	else goodEvt = 1;
	
	if(evtNumber % goodEvt == 0){
	  //---Read SciFront ADC value and set the e- multiplicity 
	  //---(default = 1)
	  trig = 1;
	  for(int iCh=0; iCh<nAdcChannels; iCh++)
	    {
	      if(adcData[iCh] > 1500 && adcBoard[iCh] == 1 && adcChannel[iCh] == 0) trig=2;
	      if(adcData[iCh] < 500 && adcBoard[iCh] == 1 && adcChannel[iCh] == 0) trig=0;
	    }
	  if(trig > 1) continue; 
	  
	  //---Read digitizer samples
	  for(int iSample=0; iSample<nDigiSamples; iSample++){
	    if(digiChannel[iSample] == 3){
	      digiCh[digiChannel[iSample]].push_back(-digiSampleValue[iSample]);
	      chHistoWF_Ch[digiChannel[iSample]]->SetBinContent(digiSampleIndex[iSample]+1, -digiSampleValue[iSample]);
	    }
	    else{
	      digiCh[digiChannel[iSample]].push_back(digiSampleValue[iSample]);
	      chHistoWF_Ch[digiChannel[iSample]]->SetBinContent(digiSampleIndex[iSample]+1, digiSampleValue[iSample]);
	    }
	    
	  }
	  for(int iCh=0; iCh<6; iCh++){
	    //	    baseline[iCh] = SubtractBaseline(5, 25, &digiCh[iCh]);
	    baseline[iCh] = SubtractBaseline(26, 46, &digiCh[iCh]);
	    intBase[iCh] = ComputeIntegral(26, 46, &digiCh[iCh]);
	    if(trig == 0) {
	      chHistoBase_All[iCh]->Fill(ComputeIntegral(26, 46, &digiCh[iCh]));
	      chHistoBase_Ch[iCh]->Fill(ComputeIntegral(26, 46, &digiCh[iCh]));
	      // 		    chHistoBase_All[iCh]->Fill(ComputeIntegral(0, 150, &digiCh[iCh]));
	      // 		    chHistoBase_Ch[iCh]->Fill(ComputeIntegral(0, 150, &digiCh[iCh]));
	    }
	    timeCF[iCh]=TimeConstFrac(30, 500, &digiCh[iCh], 0.5);
	    //		  timeDiffHisto[iCh]->Fill(timeCF[iCh]*0.2-timeCF[0]*0.2); 
	    timeDiffHisto[iCh]->Fill(timeCF[iCh]); 
	    
	    int t1 = (int)(timeCF[iCh]/0.2) - 3;
	    int t2 = (int)(timeCF[iCh]/0.2) + 17;
	    //---Fill the signal integral histo only if the e- multiplicity is 1
	    if(t1 > 30 && t1 < 1024 && t2 > 30 && t2 < 1024 && trig == 1)
	      {
		chHistoSignal_All[iCh]->Fill(ComputeIntegral(t1, t2, &digiCh[iCh]));
		chHistoSignal_Ch[iCh]->Fill(ComputeIntegral(t1, t2, &digiCh[iCh]));
		intSignal[iCh] = ComputeIntegral(t1, t2, &digiCh[iCh]);
	      }
	    else intSignal[iCh] = ComputeIntegral(50, 70, &digiCh[iCh]);
	  }// loop over Ch
	  //---Multiplicity == 1 --> compute efficency, fake rate and timing                                                                          
	  if(intSignal[Ch_ref1] < Ch_th[Ch_ref1] && intSignal[Ch_ref2] < Ch_th[Ch_ref2] && trig == 1){
	    ++tot_tr1;
	    float tDiff = (timeCF[Ch_ref1] - timeCF[Ch_ref2]);
	    float tMean = (timeCF[Ch_ref1] + timeCF[Ch_ref2])*0.5;
	    timeDiffHisto_Double->Fill(tDiff);
	    timeDiffHisto_Triple_Ch1->Fill(tMean - timeCF[Ch_1]);
	    timeDiffHisto_Triple_Ch2->Fill(tMean - timeCF[Ch_2]);
	    timeDiffHisto_Triple_Ch3->Fill(tMean - timeCF[Ch_3]);
	    
	    if(intSignal[Ch_1] < Ch_th[Ch_1]) ++count[1];
	    if(intSignal[Ch_2] < Ch_th[Ch_2]) ++count[2];
	    if(intSignal[Ch_3] < Ch_th[Ch_3]) ++count[3];
	    
	    if(intBase[Ch_1] < Ch_th[Ch_1])  ++spare[1];
	    if(intBase[Ch_2] < Ch_th[Ch_2])  ++spare[2];
	    if(intBase[Ch_3] < Ch_th[Ch_3])  ++spare[3];
	  }
	}// good Event
      }// loop over entries
    
      std::cout << "HV1 = " << HV1 << " HV2 = " << HV2 << " HV3 = " << HV3 << std::endl;
      double eff1 = ((double)count[1]-(double)spare[1])/(double)tot_tr1;
      double eff2 = ((double)count[2]-(double)spare[2])/(double)tot_tr1;
      double eff3 = ((double)count[3]-(double)spare[3])/(double)tot_tr1;
    
      double eff1Err = TMath::Sqrt((eff1*(1-eff1))/tot_tr1);
      double eff2Err = TMath::Sqrt((eff2*(1-eff2))/tot_tr1);
      double eff3Err = TMath::Sqrt((eff3*(1-eff3))/tot_tr1);

      std::cout << "Ch_1 eff = " << eff1 << " +/- " << eff1Err << std::endl;
      std::cout << "Ch_2 eff = " << eff2 << " +/- " << eff2Err << std::endl;
      std::cout << "Ch_3 eff = " << eff3 << " +/- " << eff3Err << std::endl;
     
      /*
	data1 << HV1 << " " <<  eff1 << " " << 0 << " " << eff1Err << std::endl;
	data1 << HV2 << " " <<  eff2 << " " << 0 << " " << eff2Err << std::endl;
	data1 << HV3 << " " <<  eff3 << " " << 0 << " " << eff3Err << std::endl;
      */
  
      for(int iw=0; iw<6; ++iw){
	if(iw == 2) continue;
	chHistoBase_Ch[iw]->Write();
	chHistoSignal_Ch[iw]->Write();
	chHistoWF_Ch[iw]->Write();
      }
      timeDiffHisto_Triple_Ch1->Write();
      timeDiffHisto_Triple_Ch2->Write();
      timeDiffHisto_Triple_Ch3->Write();
      chain->Delete();
    }

    for(int iw=0; iw<6; ++iw){
      if(iw == 2) continue;
      chHistoBase_All[iw]->Write();
      chHistoSignal_All[iw]->Write();
      timeDiffHisto[iw]->Write();
    }

    data1.close();
    data2.close();
    data3.close();

    timeDiffHisto_Double->Write();
    out->Close();
    return 0;
}
Beispiel #24
0
void main()
{
	CBTType *root=NULL;
	char  menusel;
	void (*TreeNodeData1)(CBTType *p);
	TreeNodeData1=TreeNodeData;

	root = InitTree();
	do{
		printf("请选择菜单添加二叉树的节点\n");
		printf("0.退出\t");
		printf("1.添加二叉树的节点\n");
		menusel = getch();
		switch(menusel)
		{
		case '1':
			AddTreeNode(root);
			break;
		case '0':
			break;
		default:
			;
		}
	}while(menusel != '0');

	do{
		printf("请选择菜单遍历二叉树,输入0表示退出:\n");
		printf("1.先序遍历DLR\t");
		printf("2.中序遍历LDR\n");
		printf("3.后序遍历LRD\t");
		printf("4.按层遍历\n");


		menusel = getch();
		switch(menusel)
		{
		case '0':
			break;
		case '1':
			printf("\n 先序遍历DLR的结果:");
			DLRTree(root,TreeNodeData1);
			printf("\n");
			break;
		case '2':
			printf("\n中序遍历LDR的结果:");
			LDRTree(root,TreeNodeData1);
			printf("\n");
			break;
		case '3':
			printf("\n 后序遍历LRD的结果:");
			LRDTree(root,TreeNodeData1);
			printf("\n");
			break;
		case '4':
			printf("\n 按层遍历的结果:");
			LevelTree(root,TreeNodeData1);
			printf("\n");
			break;
		default:
			;
		}
	
	}while(menusel != '0');

	printf("\n 二叉树深度为:%d \n",TreeDepth(root));

	ClearTree(root);
	root = NULL;


}