示例#1
0
文件: print.cpp 项目: AheadIO/Halide
int main(int argc, char **argv) {
    Var x;

    {
        Func f;

        f(x) = print(x * x, "the answer is", 42.0f, "unsigned", cast<uint32_t>(145));
        f.set_custom_print(halide_print);
        Image<int32_t> result = f.realize(10);

        for (int32_t i = 0; i < 10; i++) {
            if (result(i) != i * i) {
                return -1;
            }
        }

        assert(messages.size() == 10);
        for (size_t i = 0; i < messages.size(); i++) {
            long long square;
            float forty_two;
            unsigned long long one_forty_five;

            int scan_count = sscanf(messages[i].c_str(), "%lld the answer is %f unsigned %llu",
                                    &square, &forty_two, &one_forty_five);
            assert(scan_count == 3);
            assert(square == i * i);
            assert(forty_two == 42.0f);
            assert(one_forty_five == 145);
        }
    }

    messages.clear();

    {
        Func f;
        Param<int> param;
        param.set(127);

        // Test a string containing a printf format specifier (It should print it as-is).
        f(x) = print_when(x == 3, x * x, "g", 42.0f, "%s", param);
        f.set_custom_print(halide_print);
        Image<int32_t> result = f.realize(10);

        for (int32_t i = 0; i < 10; i++) {
            if (result(i) != i * i) {
                return -1;
            }
        }

        assert(messages.size() == 1);
        long long nine;
        float forty_two;
        long long p;

        int scan_count = sscanf(messages[0].c_str(), "%lld g %f %%s %lld",
                                &nine, &forty_two, &p);
        assert(scan_count == 3);
        assert(nine == 9);
        assert(forty_two == 42.0f);
        assert(p == 127);

    }

    messages.clear();

    {
        Func f;

        // Test a single message longer than 8K.
        std::vector<Expr> args;
        for (int i = 0; i < 500; i++) {
            uint64_t n = i;
            n *= n;
            n *= n;
            n *= n;
            n *= n;
            n += 100;
            int32_t hi = n >> 32;
            int32_t lo = n & 0xffffffff;
            args.push_back((cast<uint64_t>(hi) << 32) | lo);
            Expr dn = cast<double>((float)(n));
            args.push_back(dn);
        }
        f(x) = print(args);
        f.set_custom_print(halide_print);
        Image<uint64_t> result = f.realize(1);

        if (result(0) != 100) {
            return -1;
        }

        assert(messages.back().size() == 8191);
    }

    messages.clear();

    // Check that Halide's stringification of floats and doubles
    // matches %f and %e respectively.

    #ifndef _MSC_VER
    // msvc's library has different ideas about how %f and %e should come out.
    {
        Func f, g;

        const int N = 1000000;

        Expr e = reinterpret(Float(32), random_int());
        // Make sure we cover some special values.
        e = select(x == 0, 0.0f,
                   x == 1, -0.0f,
                   x == 2, std::numeric_limits<float>::infinity(),
                   x == 3, -std::numeric_limits<float>::infinity(),
                   x == 4, std::numeric_limits<float>::quiet_NaN(),
                   x == 5, -std::numeric_limits<float>::quiet_NaN(),
                   e);
        e = select(x == 5, std::numeric_limits<float>::denorm_min(),
                   x == 6, -std::numeric_limits<float>::denorm_min(),
                   x == 7, std::numeric_limits<float>::min(),
                   x == 8, -std::numeric_limits<float>::min(),
                   x == 9, std::numeric_limits<float>::max(),
                   x == 10, -std::numeric_limits<float>::max(),
                   e);

        f(x) = print(e);

        f.set_custom_print(halide_print);
        Image<float> imf = f.realize(N);

        assert(messages.size() == N);

        char correct[1024];
        for (int i = 0; i < N; i++) {
            snprintf(correct, sizeof(correct), "%f\n", imf(i));
            // OS X prints -nan as nan
            #ifdef __APPLE__
            if (messages[i] == "-nan\n") messages[i] = "nan\n";
            #endif
            if (messages[i] != correct) {
                printf("float %d: %s vs %s for %10.20e\n", i, messages[i].c_str(), correct, imf(i));
                return -1;
            }
        }

        messages.clear();

        g(x) = print(reinterpret(Float(64), (cast<uint64_t>(random_int()) << 32) | random_int()));
        g.set_custom_print(halide_print);
        Image<double> img = g.realize(N);

        assert(messages.size() == N);

        for (int i = 0; i < N; i++) {
            snprintf(correct, sizeof(correct), "%e\n", img(i));
            #ifdef __APPLE__
            if (messages[i] == "-nan\n") messages[i] = "nan\n";
            #endif
            if (messages[i] != correct) {
                printf("double %d: %s vs %s for %10.20e\n", i, messages[i].c_str(), correct, img(i));
                return -1;
            }
        }


    }
    #endif


    printf("Success!\n");
    return 0;
}
示例#2
0
BOOL CALLBACK DlgProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam){
    switch(msg){
		case WM_CLOSE:{
			DestroyWindow(hwnd);
			break;
		}
		case WM_DESTROY:{
			PostQuitMessage(0);
			break;
		}
		case WM_COMMAND:{
			if(HIWORD(wParam) == EN_CHANGE){
				const int ID = LOWORD(wParam);
				switch(ID){
					case IDC_CDLEFT:{
						Globals::PreviewCD.Left = GetDlgItemFloat(hwnd, ID);
						break;
					}
					case IDC_CDRIGHT:{
						Globals::PreviewCD.Right = GetDlgItemFloat(hwnd, ID);
						break;
					}
					case IDC_CDTOP:{
						Globals::PreviewCD.Top = GetDlgItemFloat(hwnd, ID);
						break;
					}
					case IDC_CDBOTTOM:{
						Globals::PreviewCD.Bottom = GetDlgItemFloat(hwnd, ID);
						break;
					}
					default:
						break;
				}
			}
			switch(LOWORD(wParam)){
				case IDM_EXIT1:{
					DestroyWindow(hwnd);
				}
				case IDM_OPEN1:{
					OPENFILENAME sfn;
					char sfPath[MAX_PATH];
					ZeroMemory( &sfn , sizeof( sfn));
					sfn.lStructSize = sizeof (OPENFILENAME);
					sfn.lpstrFile = sfPath;
					sfn.lpstrFile[0] = '\0';
					sfn.nMaxFile = MAX_PATH;
					sfn.lpstrFilter = "Foof Level Tile Set\0*.fts\0\0";
					sfn.nFilterIndex = 1;
					sfn.hwndOwner = hwnd;
					if(GetOpenFileName(&sfn) != 0){
						LevelTileSet.clear();
						AnimationSet.clear();
						DynamicSet.clear();
						DecoSet.clear();
						HazardousSet.clear();
						ifstream FileIn(sfPath);
						if(FileIn.is_open()){
							string Reader;
							FileIn >> Reader;
							if(Reader == "Foof72"){
								int Size = 0;
								FileIn >> Size;
								HWND hListBox = GetDlgItem(hwnd, IDC_COLLIST);
								SendMessage(hListBox, LB_RESETCONTENT, 0,0);
								for(int i = 0; i < Size; i++){
									LevelTile * pLevelTile = new LevelTile;
									FileIn >> pLevelTile->SpriteID;
									FileIn >> pLevelTile->IsCeiling;
									FileIn >> pLevelTile->IsNotWall;
									for(int i = 0; i < 64; i++){
										FileIn >> pLevelTile->HeightMask[i];
									}
									FileIn >> pLevelTile->Name;

									LevelTileSet.push_back(*pLevelTile);


									SendMessage(hListBox, LB_ADDSTRING, 0, (LPARAM)pLevelTile->Name.c_str());
								}
								FileIn >> Size;
								hListBox = GetDlgItem(hwnd, IDC_ANIMLIST);
								SendMessage(hListBox, LB_RESETCONTENT, 0,0);
								for(int i = 0; i < Size; i++){
									AnimationTrack * pAnim = new AnimationTrack;
									FileIn >> pAnim->Name;
									FileIn >> pAnim->iStartingFrame;
									FileIn >> pAnim->nFrames;
									FileIn >> pAnim->fDefaultSpeed;
									char TruncName[7];
									size_t TruncNameLength = pAnim->Name.copy(TruncName, 6,0);
									TruncName[TruncNameLength] = '\0';
									string Name = TruncName;
									char strFrames[50];
									sprintf(strFrames, "%i", pAnim->nFrames);
									char strFPS[50];
									sprintf(strFPS, "%f", pAnim->fDefaultSpeed);
									string ListEntry = Name + "..." + " - " + strFrames + " Frames" + ", " + strFPS + " FPS";
									SendMessage(hListBox, LB_ADDSTRING, 0, (LPARAM)ListEntry.c_str());
									AnimationSet.push_back(*pAnim);
								}
								FileIn >> Size;
								hListBox = GetDlgItem(hwnd, IDC_DYNLIST);
								SendMessage(hListBox, LB_RESETCONTENT, 0,0);
								for(int i = 0; i < Size; i++){
									DynamicObject * pDyn = NULL;
									int Type;
									FileIn >> Type;
									switch(Type){
										case 0:{  //Walker
											pDyn = new EnemyWalker;
											EnemyWalker * pWalker = (EnemyWalker*)pDyn;
											FileIn >> pWalker->AttackAnimationIndex
													>> pWalker->DeathAnimationIndex
													>> pWalker->JumpStrength
													>> pWalker->Speed
													>> pWalker->HP
													>> pWalker->Aggressiveness
													>> pWalker->bIsDormant
													>> pWalker->ShotType
													>> pWalker->ShotDirection
													>> pWalker->nBurstDelay
													>> pWalker->nShotsPerBurst;
											break;
										}
										case 1:{  //Flyer
											pDyn = new EnemyFlyer;
											EnemyFlyer * pWalker = (EnemyFlyer*)pDyn;
											FileIn >> pWalker->AttackAnimationIndex
													>> pWalker->DeathAnimationIndex
													>> pWalker->Speed
													>> pWalker->HP
													>> pWalker->FlightType
													>> pWalker->bIsDormant
													>> pWalker->ShotType
													>> pWalker->ShotDirection
													>> pWalker->nBurstDelay
													>> pWalker->nShotsPerBurst;
											break;
										}
										case 2: { //MOver
											pDyn = new Mover;
											Mover * pMover = (Mover*)pDyn;
											FileIn >> pMover->iMovingAnimationIndex
													>> pMover->HP
													>> pMover->bIsHazard;
											break;
										}
										case 5: { //Destructible
											pDyn = new DestructibleObject;
											DestructibleObject * pDest = (DestructibleObject*)pDyn;
											FileIn >> pDest->HP
												>> pDest->Type
												>> pDest->SpawnID;
											break;
										 }
										default:
											pDyn = new DynamicObject;
											break;
									}

									FileIn >> pDyn->Name
											>> pDyn->iDefaultAnimationIndex
											>> pDyn->iSpriteIndex
											>> pDyn->fDefaultScale
											>> pDyn->CD.Left
											>> pDyn->CD.Right
											>> pDyn->CD.Top
											>> pDyn->CD.Bottom;
									pDyn->Type = Type;
									DynamicSet.push_back(pDyn);
									SendMessage(hListBox, LB_ADDSTRING, 0, (LPARAM)pDyn->Name.c_str()); 
								}

								FileIn >> Size;
								hListBox = GetDlgItem(hwnd, IDC_HAZLIST);
								SendMessage(hListBox, LB_RESETCONTENT, 0,0);
								for(int i = 0; i < Size; i++){
									HazardousObject * pHaz = new HazardousObject();
									FileIn >> pHaz->Name;
									FileIn >> pHaz->SpriteID;
									FileIn >> pHaz->Damage;
									FileIn >> pHaz->fDefaultScale
										>> pHaz->CD.Left
										>> pHaz->CD.Right
										>> pHaz->CD.Top
										>> pHaz->CD.Bottom;

									SendMessage(hListBox, LB_ADDSTRING, 0, (LPARAM)pHaz->Name.c_str()); 

									HazardousSet.push_back(*pHaz);
								}
								FileIn >> Size;
								hListBox = GetDlgItem(hwnd, IDC_DECOLIST);
								SendMessage(hListBox, LB_RESETCONTENT, 0,0);
								for(int i = 0; i < Size; i++){
									StaticDeco * pDeco = new StaticDeco();
									FileIn >> pDeco->Name;
									FileIn >> pDeco->iSpriteID;
									FileIn >> pDeco->fDefaultScale
										>> pDeco->CD.Left
										>> pDeco->CD.Right
										>> pDeco->CD.Top
										>> pDeco->CD.Bottom;;

									SendMessage(hListBox, LB_ADDSTRING, 0, (LPARAM)pDeco->Name.c_str()); 

									DecoSet.push_back(*pDeco);
								}
								FileIn >> Size;
								hListBox = GetDlgItem(hwnd, IDC_PROJECTILELIST);
								SendMessage(hListBox, LB_RESETCONTENT, 0, 0);
								for(int i = 0; i < Size; i++){
									DynamicObject * pProj = new DynamicObject();
									FileIn >> pProj->Name 
										>> pProj->iDefaultAnimationIndex 
										>> pProj->fDefaultScale
										>> pProj->CD.Left
										>> pProj->CD.Right
										>> pProj->CD.Top
										>> pProj->CD.Bottom;

									SendMessage(hListBox, LB_ADDSTRING, 0, (LPARAM)pProj->Name.c_str()); 
									ProjectileSet.push_back(pProj);
								}
							}
							FileIn.close();
						}
					}
					break;
				}
				case IDM_SAVE1:{
					OPENFILENAME sfn;
					char sfPath[MAX_PATH];
					ZeroMemory( &sfn , sizeof( sfn));
					sfn.lStructSize = sizeof (OPENFILENAME);
					sfn.lpstrFile = sfPath;
					sfn.lpstrFile[0] = '\0';
					sfn.nMaxFile = MAX_PATH;
					sfn.lpstrFilter = "Foof Level Tile Set\0*.fts\0\0";
					sfn.nFilterIndex = 1;
					sfn.hwndOwner = hwnd;

					if(GetSaveFileName(&sfn) != 0){
								ofstream FileOut(sfPath);
						if(FileOut.is_open()){
							FileOut << "Foof72" << endl
								<< LevelTileSet.size() << endl;
							for(vector<LevelTile>::iterator it = LevelTileSet.begin(); it < LevelTileSet.end(); it++){
								const LevelTile * pLevelTile = &(*it);
								FileOut << pLevelTile->SpriteID << endl;
								FileOut << pLevelTile->IsCeiling << endl;
								FileOut << pLevelTile->IsNotWall << endl;
								for(int i = 0; i < 64; i++){
									FileOut << pLevelTile->HeightMask[i] << endl;
								}
								FileOut	<< pLevelTile->Name << endl;
							}
							FileOut << AnimationSet.size() << endl;
							for(vector<AnimationTrack>::iterator it = AnimationSet.begin(); it < AnimationSet.end(); it++){
								const AnimationTrack * pAnim = &(*it);
								FileOut << pAnim->Name << endl
									<< pAnim->iStartingFrame << endl
									<< pAnim->nFrames << endl
									<< pAnim->fDefaultSpeed << endl;
							}
							FileOut << DynamicSet.size() << endl;
							for(vector<DynamicObject*>::iterator it = DynamicSet.begin(); it < DynamicSet.end(); it++){
								DynamicObject * pDyn = (*it);
								FileOut << pDyn->Type << endl;
								switch(pDyn->Type){
									case 0:{  //Walker
										EnemyWalker * pWalker = (EnemyWalker*)pDyn;
										FileOut << pWalker->AttackAnimationIndex << endl
												<< pWalker->DeathAnimationIndex << endl
												<< pWalker->JumpStrength << endl
												<< pWalker->Speed << endl
												<< pWalker->HP << endl
												<< pWalker->Aggressiveness << endl
												<< pWalker->bIsDormant << endl
												<< pWalker->ShotType << endl
												<< pWalker->ShotDirection << endl
												<< pWalker->nBurstDelay << endl
												<< pWalker->nShotsPerBurst << endl;
										break;
									}
									case 1:{  //Flyer
										EnemyFlyer * pWalker = (EnemyFlyer*)pDyn;
										FileOut << pWalker->AttackAnimationIndex << endl
												<< pWalker->DeathAnimationIndex << endl
												<< pWalker->Speed << endl
												<< pWalker->HP << endl
												<< pWalker->FlightType << endl
												<< pWalker->bIsDormant << endl
												<< pWalker->ShotType << endl
												<< pWalker->ShotDirection << endl
												<< pWalker->nBurstDelay << endl
												<< pWalker->nShotsPerBurst << endl;
										break;
									}
									case 2:{
											Mover * pMover = (Mover*)pDyn;
											FileOut << pMover->iMovingAnimationIndex << endl
													<< pMover->HP << endl
													<< pMover->bIsHazard << endl;
										break;
									}
									case 5:{
										DestructibleObject * pDest = (DestructibleObject*)pDyn;
										FileOut << pDest->HP << endl
											<< pDest->Type << endl
											<< pDest->SpawnID << endl;
									}
									default:
										break;
								}
								FileOut << pDyn->Name << endl
									<< pDyn->iDefaultAnimationIndex << endl
									<< pDyn->iSpriteIndex << endl
									<< pDyn->fDefaultScale << endl
									<< pDyn->CD.Left << endl
									<< pDyn->CD.Right << endl
									<< pDyn->CD.Top << endl
									<< pDyn->CD.Bottom << endl;
							}

							FileOut << HazardousSet.size() << endl;
							for(vector<HazardousObject>::iterator it = HazardousSet.begin(); it < HazardousSet.end(); it++){
								const HazardousObject * pHaz = &(*it);
								FileOut << pHaz->Name << endl
									<< pHaz->SpriteID << endl
									<< pHaz->Damage << endl
									<< pHaz->fDefaultScale << endl
									<< pHaz->CD.Left << endl
									<< pHaz->CD.Right << endl
									<< pHaz->CD.Top << endl
									<< pHaz->CD.Bottom << endl;
							}
							FileOut << DecoSet.size() << endl;
							for(vector<StaticDeco>::iterator it = DecoSet.begin(); it < DecoSet.end(); it++){
								const StaticDeco * pDeco = &(*it);
								FileOut << pDeco->Name << endl
									<< pDeco->iSpriteID << endl
									<< pDeco->fDefaultScale << endl
									<< pDeco->CD.Left << endl
									<< pDeco->CD.Right << endl
									<< pDeco->CD.Top << endl
									<< pDeco->CD.Bottom << endl;
							}
							FileOut << ProjectileSet.size() << endl;
							for(vector<DynamicObject*>::iterator it = ProjectileSet.begin(); it < ProjectileSet.end(); it++){
								const DynamicObject* pProj = *it;
								FileOut << pProj->Name << endl
									<< pProj->iDefaultAnimationIndex << endl
									<< pProj->fDefaultScale << endl
									<< pProj->CD.Left << endl
									<< pProj->CD.Right << endl
									<< pProj->CD.Top << endl
									<< pProj->CD.Bottom << endl;
							}
							FileOut.close();
						}
					}
					break;
				}
				case IDC_REMHAZ:{
					HWND hHazList = GetDlgItem(hwnd, IDC_HAZLIST);
					const int Selection = SendMessage(hHazList, LB_GETCURSEL, (WPARAM)0, (LPARAM)0);
					if(Selection != LB_ERR){
						HazardousSet.erase(HazardousSet.begin() + Selection);
						SendMessage(hHazList, LB_DELETESTRING, (WPARAM)Selection, (LPARAM)0);
					}
					break;
				}
				case IDC_ADDHAZ:{
					HazardousObject * pHaz = new HazardousObject();
					pHaz->CD.Copy(Globals::PreviewCD);
					string LineEntry;
					pHaz->Damage = GetDlgItemInt(hwnd, IDC_HAZDMG, NULL, false);
					char strScale[8];
					GetDlgItemText(hwnd, IDC_HAZSCALE, strScale, 6);
					pHaz->fDefaultScale = (float)atof(strScale);

					pHaz->Name = "H:" + TextureAtlas.TextureList[SpriteID];
					pHaz->SpriteID = SpriteID;
					HazardousSet.push_back(*pHaz);

					LineEntry = pHaz->Name;
					HWND hHazList = GetDlgItem(hwnd, IDC_HAZLIST);
					SendMessage(hHazList, LB_ADDSTRING, 0, (LPARAM)LineEntry.c_str()); 
					break;
				}
				case IDC_ADDDYNAMIC:{
						HWND hDynamicList = GetDlgItem(hwnd, IDC_DYNLIST);
						const int Type = SendMessage(GetDlgItem(hwnd, IDC_DYNAMICCOMBO), CB_GETCURSEL, (WPARAM)0, (LPARAM)0);
						if(pEditObject){
							pEditObject = NULL;
						}
						int Result = IDCANCEL;
						switch(Type){
							case 0:
								Result = DialogBox(GetModuleHandle(NULL), MAKEINTRESOURCE(IDD_ADDWALKER), hwnd, AddDlgProc);
								break;
							case 1:
								Result = DialogBox(GetModuleHandle(NULL), MAKEINTRESOURCE(IDD_ADDFLYER), hwnd, AddFlyerDlgProc);
								break;
							case 2:
								Result = DialogBox(GetModuleHandle(NULL), MAKEINTRESOURCE(IDD_ADDMOVER), hwnd, AddMoverDlgProc);
								break;
							case 5:
								Result = DialogBox(GetModuleHandle(NULL), MAKEINTRESOURCE(IDD_ADDEST), hwnd, AddDestructibleDlgProc);
								break;
							default:
								Result = DialogBox(GetModuleHandle(NULL), MAKEINTRESOURCE(IDD_ADDDEFAULT), hwnd, AddDefault);
								break;
						}
						if(Result == IDOK){
							DynamicObject * pDyn = DynamicSet.back();
							pDyn->CD.Copy(Globals::PreviewCD);
							SendMessage(GetDlgItem(hwnd, IDC_DYNLIST), LB_ADDSTRING, 0, (LPARAM)pDyn->Name.c_str()); 
							pDyn->Type = Type;
						}
					break;
				}
				case IDC_EDITDYNAMIC:{
					break;
				}
				case IDC_DECOREMOVE:{
					HWND hDecoList = GetDlgItem(hwnd, IDC_DECOLIST);
					const int Selection = SendMessage(hDecoList, LB_GETCURSEL, (WPARAM)0, (LPARAM)0);
					if(Selection != LB_ERR){
						DecoSet.erase(DecoSet.begin() + Selection);
						SendMessage(hDecoList, LB_DELETESTRING, (WPARAM)Selection, (LPARAM)0);
					}
				}
				case IDC_REMOVEDYNAMIC:{
					HWND hDynList = GetDlgItem(hwnd, IDC_DYNLIST);
					const int Selection = SendMessage(hDynList, LB_GETCURSEL, (WPARAM)0, (LPARAM)0);
					if(Selection != LB_ERR){
						DynamicSet.erase(DynamicSet.begin() + Selection);
						SendMessage(hDynList, LB_DELETESTRING, (WPARAM)Selection, (LPARAM)0);
					}
				}
				case IDC_REMOVEANIM:{
					HWND hAnimList = GetDlgItem(hwnd, IDC_ANIMLIST);
					const int Selection = SendMessage(hAnimList, LB_GETCURSEL, (WPARAM)0, (LPARAM)0);
					if(Selection != LB_ERR){
						AnimationSet.erase(AnimationSet.begin() + Selection);
						SendMessage(hAnimList, LB_DELETESTRING, (WPARAM)Selection, (LPARAM)0);
					}
					break;
				}
				case IDC_ADDPROJ:{
					HWND hAnimList = GetDlgItem(hwnd, IDC_ANIMLIST);
					const int Selection = SendMessage(hAnimList, LB_GETCURSEL, (WPARAM)0, (LPARAM)0);
					if(Selection != LB_ERR){
						DynamicObject *pProj = new DynamicObject();
						pProj->fDefaultScale = GetDlgItemFloat(hwnd, IDC_PROJSCALE);
						pProj->Name = AnimationSet[Selection].Name;
						pProj->CD.Copy(Globals::PreviewCD);
						pProj->iDefaultAnimationIndex = Selection;
						ProjectileSet.push_back(pProj);

						HWND hProjectileList = GetDlgItem(hwnd, IDC_PROJECTILELIST);
						SendMessage(hProjectileList, LB_ADDSTRING, 0, (LPARAM)pProj->Name.c_str()); 
					}

					break;
				}
				case IDC_DECOADD:{
					StaticDeco *pDeco = new StaticDeco();
					char strScale[8];
					GetDlgItemText(hwnd, IDC_DECOSCALE, strScale, 6);
					pDeco->fDefaultScale = (float)atof(strScale);
					pDeco->iSpriteID = SpriteID;
					pDeco->Name = "S:" + TextureAtlas.TextureList[SpriteID];
					pDeco->CD.Copy(Globals::PreviewCD);
					HWND hListBox = GetDlgItem(hwnd, IDC_DECOLIST);
					string ListEntry = pDeco->Name;
					SendMessage(hListBox, LB_ADDSTRING, 0, (LPARAM)ListEntry.c_str()); 
					DecoSet.push_back(*pDeco);
					break;
				}	
				case IDC_ANIMADD:{
					AnimationTrack * pAnim = new AnimationTrack();
					char strFrames[8];
					GetDlgItemText(hwnd, IDC_NFRAMES, strFrames, 6);
					char strFPS[8];
					GetDlgItemText(hwnd, IDC_SPEED, strFPS, 6);
					pAnim->nFrames =  atoi(strFrames);//(;//GetDlgItemInt(hwnd, IDC_NFRAMES, false, false);
					pAnim->fDefaultSpeed = (float)atof(strFPS);
					pAnim->iStartingFrame = SpriteID;
					string Name = TextureAtlas.TextureList[SpriteID];
					pAnim->Name = Name;
					char TruncName[7];
					size_t TruncNameLength = Name.copy(TruncName, 6,0);
					TruncName[TruncNameLength] = '\0';
					Name = TruncName;
					HWND hListBox = GetDlgItem(hwnd, IDC_ANIMLIST);
					string ListEntry = Name + "..." + " - " + strFrames + " Frames" + ", " + strFPS + " FPS";
					SendMessage(hListBox, LB_ADDSTRING, 0, (LPARAM)ListEntry.c_str()); 

					AnimationSet.push_back(*pAnim);
					break;
				}
				case IDC_ADDTILE:{
					for(int i = SpriteID; i < SpriteID + 1; i++){
						const string Name = TextureAtlas.TextureList[i];

						string HeightMapName = Name;
						string::iterator it = HeightMapName.end() - 4;
						HeightMapName.replace(it, HeightMapName.end(), "_heightmask.png");
						HeightMapName.insert(0, "./");
													WCHAR wFileName[MAX_PATH];
								//Make sure we have .png at the end
								int sfLength = HeightMapName.length();
								// Convert to a wchar_t*
								size_t convertedChars = 0;
								mbstowcs_s(&convertedChars, wFileName, sfLength + 2, HeightMapName.c_str(), _TRUNCATE);

						LevelTile * pLevelTile = new LevelTile;
						bool bIsCeiling = IsDlgButtonChecked(hwnd, IDC_ISCEILING);

						GDIImageLoader::ConvertImageToHeightMask(wFileName, pLevelTile->HeightMask, bIsCeiling);
						pLevelTile->IsCeiling = (int)bIsCeiling;
						pLevelTile->IsNotWall = IsDlgButtonChecked(hwnd, IDC_ISWALL);
						pLevelTile->SpriteID = i;
						pLevelTile->Name = Name;

						LevelTileSet.push_back(*pLevelTile);
						SendMessage(GetDlgItem(hwnd, IDC_COLLIST), LB_ADDSTRING, 0, (LPARAM)pLevelTile->Name.c_str());
					}
					break;
			    }
				case IDC_IMAGECOMBO:{
					switch(HIWORD(wParam)){
						case CBN_SELCHANGE:{
							HWND hSpriteCombo = GetDlgItem(hwnd, IDC_IMAGECOMBO);
							SpriteID = SendMessage(hSpriteCombo, CB_GETCURSEL, (WPARAM)0, (LPARAM)0);
							break;
						}
						default:
							break;
					}
					break;
				}
				default:
					break;
			}
示例#3
0
 /**
  * Creates an instruction of the graph starting from an
  * instruction of another graph.
  * \param g The other graph.
  * \param id The id of the mdfi to be copied.
  * \return The id of the created instruction.
  */
 inline uint createMdfi(Mdfg* g, uint id){
     _instructions.emplace_back(g->_instructions.at(id));
     _instructions.back().setId(_nextId);
     ++_nextId;
     return _instructions.size() - 1;
 }
示例#4
0
bool  SteerLib::GJK_EPA::doContainsOrigin(std::vector<Util::Vector>& simplex, Util::Vector& direction)
{
	Util::Vector a = simplex.back();
	Util::Vector ao = a;
	ao.x = -ao.x;
	ao.y = -ao.y;
	ao.z = -ao.z;

	if (simplex.size() == 3)
	{
		Util::Vector c = simplex.at(1);
		Util::Vector b = simplex.at(0);
		Util::Vector ac = c - a;
		Util::Vector ab = b - a;
		Util::Vector abPerp = ab;
		abPerp.x = -ab.z;
		abPerp.y = 0;
		abPerp.z = ab.x;
		
		if (Util::dot(abPerp, c) >= 0.0f)
		{
			abPerp.x = -abPerp.x;
			abPerp.y = -abPerp.y;
			abPerp.z = -abPerp.z;
		}

		if (Util::dot(abPerp, ao) > 0.0f)
		{
			simplex.erase(std::find(simplex.begin(), simplex.end(), c)); 
			direction = abPerp; 
		}
		else
		{			
			Util::Vector acPerp = ac;
			acPerp.x = -ac.z;
			acPerp.y = 0;
			acPerp.z = ac.x;
			
			if (Util::dot(acPerp, b) >= 0.0f)
			{
				acPerp.x = -acPerp.x;
				acPerp.y = -acPerp.y;
				acPerp.z = -acPerp.z;
			}

			if (Util::dot(acPerp, ao) <= 0.0f) 
			{
				return true;
			}

			simplex.erase(std::find(simplex.begin(), simplex.end(), b));
			direction = acPerp;
		}
	}
	else if (simplex.size() == 2)
	{
	
		Util::Vector b = simplex.at(0);
		
		Util::Vector ab = b - a;
		
		Util::Vector abPerp = ab;
		abPerp.x = -ab.z;
		abPerp.y = 0.0f;
		abPerp.z = ab.x;

		if (Util::dot(abPerp, ao) < 0.0f) {
			abPerp.x = -abPerp.x;
			abPerp.y = -abPerp.y;
			abPerp.z = -abPerp.z;
		}
		direction = abPerp;
	}
	return false;
}
示例#5
0
	const T& last () const { return vector.back (); }
示例#6
0
 node add_file(std::string name) {
     if (!exists(name)) return {};
     files.emplace_back(new file(name));
     return *files.back();
 }
示例#7
0
	//Check threefold repetition (= current (!) position has occurred 3 or more times)
	//Return true if draw can be claimed
	bool threefoldRepetition(const std::vector<std::vector<int>>& boardHistory, const std::vector<std::pair<int,int>>& moveHistory, const std::vector<unsigned char>& stateHistory){

		//Return immediately if not enough moves
		if (boardHistory.size() < 3)
			return false;

		//Get current board status
		std::vector<int> currentBoard = boardHistory.back();
		std::pair<int,int> lastMove = moveHistory.back();
		unsigned char currentState = stateHistory.back();

		//Get pawn moves, they're needed for en passant check
		std::vector<int> pawnMoves;
		for (int a=0; a<64; a++){
			if (currentBoard[a] == W_PAWN){
				pawnMoves = join(pawnMoves, whitePawnMoveForwardLeft(currentBoard, a, lastMove));
				pawnMoves = join(pawnMoves, whitePawnMoveForwardRight(currentBoard, a, lastMove));
			}
			else if (currentBoard[a] == B_PAWN){
				pawnMoves = join(pawnMoves, blackPawnMoveForwardLeft(currentBoard, a, lastMove));
				pawnMoves = join(pawnMoves, blackPawnMoveForwardRight(currentBoard, a, lastMove));
			}
		}

		std::vector<int> pawnMovesTemp;

		size_t posCount = 1;
		size_t posNum = boardHistory.size()-1;
		bool ret = false;

		//Find equal positions
		for (size_t i=0; i<boardHistory.size(); i++){

			//Same turn (fast check, skip every 2nd position)
			if (posNum%2 == i%2) {

				//Same piece positions (slow check?)
				if (boardHistory[i] == currentBoard) {

					//Same rights to castle, check flags
					if ( (currentState & 60) && (stateHistory[i] & 60) ) {

						//Same rights to capture en passant
						//Collect all pawn moves
						pawnMovesTemp = std::vector<int>();
						for (int a=0; a<64; a++){
							if (boardHistory[i][a] == W_PAWN){
								pawnMovesTemp = join(pawnMovesTemp, whitePawnMoveForwardLeft(boardHistory[i], a, moveHistory[i]));
								pawnMovesTemp = join(pawnMovesTemp, whitePawnMoveForwardRight(boardHistory[i], a, moveHistory[i]));
							}
							else if (boardHistory[i][a] == B_PAWN){
								pawnMovesTemp = join(pawnMovesTemp, blackPawnMoveForwardLeft(boardHistory[i], a, moveHistory[i]));
								pawnMovesTemp = join(pawnMovesTemp, blackPawnMoveForwardRight(boardHistory[i], a, moveHistory[i]));
							}
						}
						//If the pawns have the same possible moves, then en passant rights are equal
						//Now also the positions are equal
						if (pawnMovesTemp == pawnMoves){
							posCount++;
							if (posCount >= 3){
								ret = true;
								break;
							}
						}
					}
				}
			}
		}

		return ret;
	}
示例#8
0
int vector_param_access(std::vector<int>& v) {
  return v.back(); // shouldn't report anything here
}
示例#9
0
  void Preprocess::Callback::ProcessWay(const OSMId& id,
                                        std::vector<OSMId>& nodes,
                                        const TagMap& tagMap)
  {
    TypeInfoRef areaType;
    TypeInfoRef wayType;
    int         isArea=0; // 0==unknown, 1==true, -1==false
    bool        isCoastlineArea=false;
    RawWay      way;
    bool        isCoastline=false;

    if (nodes.size()<2) {
      progress.Warning("Way "+
                       NumberToString(id)+
                       " has less than two nodes!");
      return;
    }

    if (id<lastWayId) {
      waySortingError=true;
    }

    way.SetId(id);

    auto areaTag=tagMap.find(typeConfig->tagArea);

    if (areaTag==tagMap.end()) {
      isArea=0;
    }
    else if (areaTag->second=="no" ||
             areaTag->second=="false" ||
             areaTag->second=="0") {
      isArea=-1;
    }
    else {
      isArea=1;
    }

    auto naturalTag=tagMap.find(typeConfig->tagNatural);

    if (naturalTag!=tagMap.end() &&
        naturalTag->second=="coastline") {
      isCoastline=true;
    }

    if (isCoastline) {
      isCoastlineArea=nodes.size()>3 &&
                      (nodes.front()==nodes.back() ||
                       isArea==1);
    }

    typeConfig->GetWayAreaType(tagMap,
                               wayType,
                               areaType);

    if (isArea==1 &&
        areaType==typeConfig->typeInfoIgnore) {
      isArea=0;
    }
    else if (isArea==-1 &&
             wayType==typeConfig->typeInfoIgnore) {
      isArea=0;
    }

    if (isArea==0) {
      if (wayType!=typeConfig->typeInfoIgnore &&
          areaType==typeConfig->typeInfoIgnore) {
        isArea=-1;
      }
      else if (wayType==typeConfig->typeInfoIgnore &&
               areaType!=typeConfig->typeInfoIgnore) {
        isArea=1;
      }
      else if (wayType!=typeConfig->typeInfoIgnore &&
               areaType!=typeConfig->typeInfoIgnore) {
        if (nodes.size()>3 &&
            nodes.front()==nodes.back()) {
          if (wayType->GetPinWay()) {
            isArea=-1;
          }
          else {
            isArea=1;
          }
        }
        else {
          isArea=-1;
        }
      }
    }

    switch (isArea) {
    case 1:
      areaStat[areaType->GetIndex()]++;

      if (areaType->GetIgnore()) {
        way.SetType(typeConfig->typeInfoIgnore,
                    true);
      }
      else {
        way.SetType(areaType,true);
      }

      if (nodes.size()>3 &&
          nodes.front()==nodes.back()) {
        nodes.pop_back();
      }

      areaCount++;
      break;
    case -1:
      wayStat[wayType->GetIndex()]++;

      if (wayType->GetIgnore()) {
        way.SetType(typeConfig->typeInfoIgnore,false);
      }
      else {
        way.SetType(wayType,false);
      }

      wayCount++;
      break;
    default:
      if (nodes.size()>3 &&
          nodes.front()==nodes.back()) {
        areaStat[typeIgnore]++;
        way.SetType(typeConfig->typeInfoIgnore,
                    true);

        nodes.pop_back();

        areaCount++;
      }
      else {
        wayStat[typeIgnore]++;
        way.SetType(typeConfig->typeInfoIgnore,
                    false);
        wayCount++;
      }
    }

    way.SetNodes(nodes);

    way.Parse(progress,
              *typeConfig,
              tagMap);

    way.Write(*typeConfig,
              wayWriter);

    lastWayId=id;

    if (isCoastline) {
      RawCoastline coastline;

      coastline.SetId(way.GetId());
      coastline.SetType(isCoastlineArea);
      coastline.SetNodes(way.GetNodes());

      coastline.Write(coastlineWriter);

      coastlineCount++;
    }
  }
示例#10
0
	unsigned int operator*() const {return _x.back();}
示例#11
0
	const Ham& operator++() {
	  for (int i=0; i<_H.size(); i++) for (;_hv[i]<=_x.back();_hv[i]=_x[++_hp[i]]*_H[i]);
	  _x.push_back(_hv[0]);
	  for (int i=1; i<_H.size(); i++) if (_hv[i]<_x.back()) _x.back()=_hv[i];
	  return *this;
	}
示例#12
0
  void Preprocess::ProcessWay(const TypeConfig& typeConfig,
                              const OSMId& id,
                              std::vector<OSMId>& nodes,
                              const std::map<TagId,std::string>& tagMap)
  {
    TypeId                                      areaType=typeIgnore;
    TypeId                                      wayType=typeIgnore;
    int                                         isArea=0; // 0==unknown, 1==true, -1==false
    std::map<TagId,std::string>::const_iterator areaTag;
    std::map<TagId,std::string>::const_iterator naturalTag;
    RawWay                                      way;
    bool                                        isCoastline=false;

    if (id<lastWayId) {
      waySortingError=true;
    }

    way.SetId(id);

    areaTag=tagMap.find(typeConfig.tagArea);

    if (areaTag==tagMap.end()) {
      isArea=0;
    }
    else if (areaTag->second=="no" ||
             areaTag->second=="false" ||
             areaTag->second=="0") {
      isArea=-1;
    }
    else {
      isArea=1;
    }

    naturalTag=tagMap.find(typeConfig.tagNatural);

    if (naturalTag!=tagMap.end() &&
        naturalTag->second=="coastline") {
      isCoastline=true;
    }

    typeConfig.GetWayAreaTypeId(tagMap,wayType,areaType);
    typeConfig.ResolveTags(tagMap,tags);

    if (isArea==1 &&
        areaType==typeIgnore) {
      isArea=0;
    }
    else if (isArea==-1 &&
             wayType==typeIgnore) {
      isArea=0;
    }

    if (isArea==0) {
      if (wayType!=typeIgnore &&
          areaType==typeIgnore) {
        isArea=-1;
      }
      else if (wayType==typeIgnore &&
               areaType!=typeIgnore) {
        isArea=1;
      }
      else if (wayType!=typeIgnore &&
               areaType!=typeIgnore) {
        if (nodes.size()>3 &&
            nodes.front()==nodes.back()) {
          if (typeConfig.GetTypeInfo(wayType).GetPinWay()) {
            isArea=-1;
          }
          else {
            isArea=1;
          }
        }
        else {
          isArea=-1;
        }
      }
    }

    switch (isArea) {
    case 1:
      way.SetType(areaType,true);

      if (nodes.size()>3 &&
          nodes.front()==nodes.back()) {
        nodes.pop_back();
      }

      areaCount++;
      break;
    case -1:
      way.SetType(wayType,false);
      wayCount++;
      break;
    default:
      if (nodes.size()>3 &&
          nodes.front()==nodes.back()) {
        way.SetType(typeIgnore,
                    true);

        nodes.pop_back();

        areaCount++;
      }
      else {
        way.SetType(typeIgnore,
                    false);
        wayCount++;
      }
    }

    way.SetNodes(nodes);
    way.SetTags(tags);

    way.Write(wayWriter);

    lastWayId=id;

    if (isCoastline) {
      RawCoastline coastline;

      coastline.SetId(way.GetId());
      coastline.SetType(way.IsArea());
      coastline.SetNodes(way.GetNodes());

      coastline.Write(coastlineWriter);

      coastlineCount++;
    }
  }
bool readTheXmlFile(std::string fileName, std::string headNode, std::string secondNode, std::vector<std::string> theNodes, std::vector<std::string> theAttributes, std::vector<ListaDeCaractere*> &theNodeValues, std::vector<std::string> &headAttributesValues)
{
    std::string moFoLongString;
    getTheFileAsString(fileName, moFoLongString);

    bool encoding = false;
    std::string sEncoding = "";
    int lastPosition = 0;

    for(int i = 0; i < moFoLongString.size(); i++)
    {
        lastPosition = i + 1;
        sEncoding += moFoLongString[i];
        if(moFoLongString[i] == '>')
        {
            encoding  = true;
            break;
        }
    }
    if(sEncoding != "<?xml version=\"1.0\" encoding=\"UTF-8\"?>")
    {
        std::cout<<"The encoding is not good buddy!!"<<'\n'<<"It should be: "<<"<?xml version=\"1.0\" encoding=\"UTF-8\"?>"<<'\n';
        return false;
    }
//    std::cout<<sEncoding<<'\n';

    std::vector<BSNodeXml> listOfActualNodes;

    std::string elementName1 =  "", elementName2 =  "", elementValue =  "", attributeName =  "", attributeValue =  "";
    bool readsAnElementName1 = false, readsAnElementName2 = false, readsAnElementValue = false, readsAnAttributeName = false, readsAnAttributeValue = false;

    for(int i = lastPosition; i < moFoLongString.size(); i++)
    {
        if(moFoLongString[i] == '<')
        {
            readsAnElementName1 = true; readsAnElementValue = false; readsAnAttributeName = false; readsAnAttributeValue = false;
            if(moFoLongString[i + 1] == '/')
            {
                readsAnElementName1 = false; readsAnElementName2 = true;
                i++;
            }
            else
            {
                BSNodeXml newNode;
                listOfActualNodes.push_back(newNode);
            }
            continue;
        }
        else
            if(moFoLongString[i] == ' ' && !readsAnAttributeValue)
            {
                if(attributeValue != "" && attributeName != "")
                {
                    BSAttribute atribut;
                    atribut.name = attributeName;
                    atribut.value = attributeValue;


                    headAttributesValues.push_back(attributeValue);
                    ///theNodeValues.back()->theCharArray2DAttributes.push_back(attributeValue);
                    ///listOfActualNodes.back().attributes.push_back(atribut);
                }
                attributeName = ""; attributeValue = "";

                readsAnElementName1 = false; readsAnElementName2 = false; readsAnElementValue = false; readsAnAttributeName = true; readsAnAttributeValue = false;
                continue;
            }
            else
                if(moFoLongString[i] == '=' && moFoLongString[i + 1] == '"' && !readsAnElementValue)
                {
                    readsAnElementName1 = false; readsAnElementName2 = false; readsAnElementValue = false; readsAnAttributeName = false; readsAnAttributeValue = true;
                    i++;
                    continue;
                }
                else
                    if(moFoLongString[i] == '"' && !readsAnElementValue)
                    {
                        if(attributeValue != "" && attributeName != "")
                        {
                            BSAttribute atribut;
                            atribut.name = attributeName;
                            atribut.value = attributeValue;

                            headAttributesValues.push_back(attributeValue);
                            ///theNodeValues.back()->theCharArray2DAttributes.push_back(attributeValue);
                            ///listOfActualNodes.back().attributes.push_back(atribut);
                        }
                        attributeName = ""; attributeValue = "";

                        readsAnElementName1 = false; readsAnElementName2 = false; readsAnElementValue = false; readsAnAttributeName = false; readsAnAttributeValue = false;
                        continue;
                    }
                    else
                        if(moFoLongString[i] == '>')
                        {
                            readsAnElementValue = true;
                            if(readsAnElementName2)
                            {
                                int index = 0;
                                for(int j = listOfActualNodes.size() - 1; j >= 0; j--)
                                {
                                    if(listOfActualNodes[j].checked != true)
                                    {
                                        index = j;
                                        break;
                                    }
                                }
                                readsAnElementValue = false;
                                if(!checkElementNames(listOfActualNodes[index].name, elementName2))
                                {
                                    std::cout<<"The element names do not match: "<<listOfActualNodes.back().name<<' '<<elementName2<<". Position: "<<i<<'\n';
                                    return false;
                                }
                                else
                                {
                                    if(elementName2 == secondNode)
                                    {
//                                        std::cout<<"    "<<elementName2<<'\n'<<'\n';
                                    }
                                    else
                                        if(elementName2 == headNode)
                                        {
//                                            std::cout<<elementName2<<'\n';
                                        }
                                        else
                                        {
                                            if(checkIfNodeIsWanted(elementName2, theNodes))
                                            {
                                                theNodeValues.back()->theCharArray2D.push_back(elementValue);
                                            }

//                                            std::cout<<"        "<<elementName2<<' '<<elementValue<<'\n';
                                        }
                                }
                                listOfActualNodes[index].checked = true;
                                elementName1 = ""; elementName2 = ""; elementValue = ""; attributeName = ""; attributeValue = "";
                            }
                            else
                            {
                                if(elementName1 == secondNode)
                                {
                                    ListaDeCaractere *newNode = new ListaDeCaractere;
                                    theNodeValues.push_back(newNode);

//                                    std::cout<<"    "<<elementName1<<'\n';
                                }
                                else
                                    if(elementName1 == headNode)
                                    {
//                                        std::cout<<elementName1<<'\n';
                                    }
                                listOfActualNodes.back().name = elementName1;
                                elementName1 = "";
                            }

                            readsAnElementName1 = false; readsAnElementName2 = false; readsAnAttributeName = false; readsAnAttributeValue = false;

                            //for(int k = 0; k < listOfActualNodes.back().attributes.size(); k++)
                            {
//                                std::cout<<listOfActualNodes.back().listOfMoFoAttributes[k].key<<' '<<listOfActualNodes.back().listOfMoFoAttributes[k].value<<'\n';
                            }
                            continue;
                        }

        ///write the name, attribute or the value of an element
        if(readsAnElementName1)
        {
            elementName1 += moFoLongString[i];
        }
        else
            if(readsAnElementName2)
            {
                elementName2 += moFoLongString[i];
            }
            else
                if(readsAnAttributeName)
                {
                    attributeName += moFoLongString[i];
                }
                else
                    if(readsAnAttributeValue)
                    {
                        attributeValue += moFoLongString[i];
                    }
                    else
                        if(readsAnElementValue)
                        {
                            elementValue += moFoLongString[i];
                        }
    }
    return true;
}
示例#14
0
 static SequencerBase& getInstance ()
 {
     return *_instances.back();
 }
示例#15
0
 /** Count the total number of columns for the data table
  *
  * @param columns vector of table column descriptions
  * @return total number of columns including sub columns
  */
 size_t count_table_columns(const std::vector<model::table::imaging_column>& columns)
 {
     if(columns.empty()) return 0;
     return columns.back().column_count();
 }
示例#16
0
文件: join.cpp 项目: mourisl/Rascaf
int main( int argc, char *argv[] )
{
    Alignments alignments ;
    Genome genome ;
    std::vector<int> rascafFileId ;

    char line[2048] ;
    char prefix[512] = "rascaf_scaffold" ;
    int rawAssemblyInd = 1 ;
    FILE *rascafFile ;
    bool contigLevel = false ;
    int i ;
    FILE *outputFile ;
    FILE *infoFile ;

    breakN = 1 ;

    if ( argc < 2 )
    {
        fprintf( stderr, "%s", usage ) ;
        exit( 1 ) ;
    }
    for ( i = 1 ; i < argc ; ++i )
    {
        if ( !strcmp( "-o", argv[i] ) )
        {
            strcpy( prefix, argv[i + 1 ] ) ;
            ++i ;
        }
        else if ( !strcmp( "-ms", argv[i] ) )
        {
            minSupport = atoi( argv[i + 1] ) ;
            ++i ;
        }
        else if ( !strcmp( "-ignoreGap", argv[i] ) )
        {
            ignoreGap = true ;
        }
        else if ( !strcmp( "-r", argv[i] ) )
        {
            rascafFileId.push_back( i + 1 ) ;
            ++i ;
        }
        else
        {
            fprintf( stderr, "Unknown option: %s\n", argv[i] ) ;
            exit( EXIT_FAILURE ) ;
        }

    }

    if ( rascafFileId.size() == 0 )
    {
        fprintf( stderr, "Must use -r to specify rascaf output file.\n" ) ;
        exit( EXIT_FAILURE ) ;
    }

    MAX_NEIGHBOR = 1 + rascafFileId.size() ;

    // Get the bam file.
    rascafFile = fopen( argv[ rascafFileId[0] ], "r" ) ;
    while ( fgets( line, sizeof( line ), rascafFile ) != NULL )
    {
        if ( strstr( line, "command line:" ) )
        {
            char *p ;
            char buffer[512] ;

            p = strstr( line, "-breakN" ) ;
            if ( p != NULL )
            {
                p += 7 ;
                while ( *p == ' ' )
                    ++p ;
                for ( i = 0 ; *p && *p != ' ' ; ++p, ++i )
                    buffer[i] = *p ;
                buffer[i] = '\0' ;
                breakN = atoi( buffer ) ;
            }

            p = strstr( line, "-b" ) ;
            if ( p == NULL )
            {
                fprintf( stderr, "Could not find the bam file specified by -b in Rascaf.\n" ) ;
                exit( 1 ) ;
            }
            p += 2 ;
            while ( *p == ' ' )
                ++p ;
            for ( i = 0 ; *p && *p != ' ' ; ++p, ++i )
                buffer[i] = *p ;
            buffer[i] = '\0' ;
            alignments.Open( buffer ) ;

            p = strstr( line, "-f") ;
            if ( p == NULL )
            {
                fprintf( stderr, "Could not find the raw assembly file specified by -f in Rascaf.\n" ) ;
                exit( 1 ) ;
            }
            p += 2 ;
            while ( *p == ' ' )
                ++p ;
            for ( i = 0 ; *p && *p != ' ' && *p != '\n' ; ++p, ++i )
                buffer[i] = *p ;
            buffer[i] = '\0' ;
            fprintf( stderr, "Found raw assembly file: %s\n", buffer ) ;
            genome.Open( alignments, buffer ) ;

            break ;
        }
    }
    fclose( rascafFile ) ;
    // Parse the input.
    for ( unsigned int fid = 0 ; fid < rascafFileId.size() ; ++fid )
    {
        rascafFile = fopen( argv[ rascafFileId[fid] ], "r" ) ;
        bool start = false ;
        int tag ;
        while ( fgets( line, sizeof( line ), rascafFile ) != NULL )
        {
            if ( strstr( line, "command line:" ) )
            {
                start = true ;
                if ( strstr( line, "-f" ) )
                {
                    contigLevel = true ;
                }

                continue ;
            }

            if ( !start )
                continue ;

            if ( !strcmp( line, "WARNINGS:\n" ) )
                break ;

            std::vector<struct _part> nparts  ;
            if ( line[0] >= '0' && line[0] <= '9' )
            {
                AddConnection( line, alignments, nparts ) ;
                connects.push_back( nparts ) ;
                tag = 0 ;
            }
            else if ( line[0] == '\t' || line[0] == ' ' )
            {
                // Break the nparts if the support is too low.
                int num = 0 ;
                for ( i = 0 ; line[i] < '0' || line[i] > '9' ; ++i )
                    ;
                for ( ; line[i] >= '0' && line[i] <= '9' ; ++i )
                    num = num * 10 + line[i] - '0' ;
                ++tag ;
                if ( num < minSupport )
                {
                    nparts = connects.back() ;
                    connects.pop_back() ;
                    int size = nparts.size() ;

                    std::vector<struct _part> newNParts ;
                    for ( i = 0 ; i < tag ; ++i )
                        newNParts.push_back( nparts[i] ) ;
                    if ( newNParts.size() > 1 )
                        connects.push_back( newNParts ) ;

                    newNParts.clear() ;
                    for ( ; i < size ; ++i  )
                        newNParts.push_back( nparts[i] ) ;
                    if ( newNParts.size() > 1 )
                        connects.push_back( newNParts ) ;

                    tag = 0 ;
                }
            }
        }
        fclose( rascafFile ) ;
    }
    if ( contigLevel == false )
    {
        genome.SetIsOpen( contigLevel ) ;
    }

    // Build the graph
    int contigCnt = genome.GetContigCount() ;
    int edgeCnt = 0 ;
    int csize = connects.size() ;

    for ( i = 0 ; i < csize ; ++i )
        edgeCnt += connects[i].size() ;

    ContigGraph contigGraph( contigCnt, contigCnt + edgeCnt ) ;
    for ( i = 0 ; i < contigCnt - 1 ; ++i )
    {
        if ( genome.GetChrIdFromContigId( i ) == genome.GetChrIdFromContigId( i + 1 ) )
        {
            contigGraph.AddEdge( i, 1, i + 1, 0 ) ;
        }
    }
    for ( i = 0 ; i < csize ; ++i )
    {
        std::vector<struct _part> &parts = connects[i] ;
        int size = parts.size() ;
        for ( int j = 0 ; j < size - 1 ; ++j )
        {
            struct _part &a = parts[j] ;
            struct _part &b = parts[j + 1] ;

            // Two dummy nodes for each contig. Left is 0, right is 1
            int dummyU = 0 ;
            int dummyV = 0 ;
            if ( a.strand == '+' )
                dummyU = 1 ;
            if ( b.strand == '-' )
                dummyV = 1 ;
            contigGraph.AddEdge( a.contigId, dummyU, b.contigId, dummyV, true ) ;
        }
    }

    // Check the cycles in the contig graph. This may introduces when combining different rascaf outputs.
    int *visitTime = new int[contigCnt] ;
    struct _pair *neighbors = new struct _pair[ MAX_NEIGHBOR ] ;

    bool *isInCycle = new bool[contigCnt] ;
    std::vector<int> cycleNodes ;
    memset( visitTime, -1, sizeof( int ) * contigCnt ) ;
    memset( isInCycle, false, sizeof( bool ) * contigCnt ) ;
    for ( i = 0 ; i < contigCnt ; ++i )
    {
        if ( isInCycle[i] )
            continue ;
        if ( contigGraph.IsInCycle( i, cycleNodes, visitTime ) )
        {
            int cnt = cycleNodes.size() ;
            //printf( "===\n") ;
            for ( int j = 0 ; j < cnt ; ++j )
            {
                //printf( "In cycle %d\n", cycleNodes[j] ) ;
                isInCycle[ cycleNodes[j] ] = true ;
            }
        }
    }
    //exit( 1 ) ;
    // Remove the connected edges involving the nodes in the cycle
    for ( i = 0 ; i < contigCnt ; ++i )
    {
        if ( isInCycle[i] )
        {
            for ( int dummy = 0 ; dummy <= 1 ; ++dummy )
            {
                int ncnt = contigGraph.GetNeighbors( i, dummy, neighbors, MAX_NEIGHBOR ) ;
                for ( int j = 0 ; j < ncnt ; ++j )
                {
                    if ( neighbors[j].a == i + 2 * dummy - 1 && neighbors[j].b != dummy
                            && genome.GetChrIdFromContigId( i ) == genome.GetChrIdFromContigId( neighbors[j].a ) )
                        continue ; // the connection created by the raw assembly
                    else
                        contigGraph.RemoveEdge( i, dummy, neighbors[j].a, neighbors[j].b ) ;
                }
            }
        }
    }
    //delete[] isInCycle ;
    //printf( "hi: %d %d\n", __LINE__, contigCnt ) ;
    //printf( "%d %d\n", contigGraph.GetNeighbors( 0, 0, neighbors, MAX_NEIGHBOR ), contigGraph.GetNeighbors( 0, 1, neighbors, MAX_NEIGHBOR ) ) ;
    // Sort the scaffolds from fasta file, so that longer scaffold come first
    int scafCnt = genome.GetChrCount() ;
    struct _pair *scafInfo = new struct _pair[scafCnt] ;
    memset( scafInfo, -1, sizeof( struct _pair) * scafCnt ) ;
    for ( i = 0 ; i < contigCnt ; ++i )
    {
        int chrId = genome.GetChrIdFromContigId( i ) ;
        if ( scafInfo[chrId].a == -1 )
        {
            scafInfo[ chrId ].a = i ;
            scafInfo[ chrId ].b = genome.GetChrLength( chrId ) ;
        }
    }
    qsort( scafInfo, scafCnt, sizeof( struct _pair ), CompScaffold ) ;

    // Merge the branches and build the scaffold
    ContigGraph scaffold( contigCnt, 2 * contigCnt ) ;

    // Use a method similar to topological sort
    bool *used = new bool[contigCnt] ;
    int *degree = new int[2 *contigCnt] ;
    int *danglingVisitTime = new int[contigCnt] ;
    int *counter = new int[contigCnt] ;
    int *visitDummy = new int[ contigCnt ] ;
    int *buffer = new int[contigCnt] ;
    int *buffer2 = new int[contigCnt] ;
    bool *isInQueue = new bool[ contigCnt ] ;
    int *chosen = new int[contigCnt] ;
    int chosenCnt ;

    memset( isInCycle, false, sizeof( bool ) * contigCnt ) ;
    memset( visitTime, -1, sizeof( int ) * contigCnt ) ;
    memset( visitDummy, -1, sizeof( int ) * contigCnt ) ;
    memset( counter, -1, sizeof( int ) * contigCnt ) ;

    // Use those memory to remove triangular cycles
    for ( i = 0 ; i < scafCnt ; ++i )
    {
        int from, to ;
        if ( scafInfo[i].a == -1 )
            continue ;
        genome.GetChrContigRange( genome.GetChrIdFromContigId( scafInfo[i].a ), from, to ) ;
        ForwardSearch( from, 0, i, visitTime, counter, visitDummy, contigGraph ) ;
        chosenCnt = 0 ;
        BackwardSearchForTriangularCycle( to, 1, i, visitTime, counter, visitDummy, contigGraph, chosen, chosenCnt ) ;

        for ( int j = 0 ; j < chosenCnt ; ++j )
        {
            //printf( "%d\n", chosen[j] ) ;
            isInCycle[ chosen[j] ] = true ;
        }
    }

    for ( i = 0 ; i < contigCnt ; ++i )
    {
        if ( isInCycle[i] )
        {
            for ( int dummy = 0 ; dummy <= 1 ; ++dummy )
            {
                int ncnt = contigGraph.GetNeighbors( i, dummy, neighbors, MAX_NEIGHBOR ) ;
                for ( int j = 0 ; j < ncnt ; ++j )
                {
                    if ( neighbors[j].a == i + 2 * dummy - 1 && neighbors[j].b != dummy
                            && genome.GetChrIdFromContigId( i ) == genome.GetChrIdFromContigId( neighbors[j].a ) )
                        continue ; // the connection created by the raw assembly
                    else
                        contigGraph.RemoveEdge( i, dummy, neighbors[j].a, neighbors[j].b ) ;
                }
            }
        }
    }


    memset( used, false, sizeof( bool ) * contigCnt ) ;
    memset( visitTime, -1, sizeof( int ) * contigCnt ) ;
    memset( visitDummy, -1, sizeof( int ) * contigCnt ) ;
    memset( danglingVisitTime, -1, sizeof( int ) * contigCnt ) ;
    memset( counter, -1, sizeof( int ) * contigCnt ) ;
    memset( isInQueue, false, sizeof( bool ) * contigCnt ) ;
    ContigGraph newGraph( contigCnt, edgeCnt ) ;

    // Compute the gap size
    int *gapSize = new int[contigCnt] ;
    for ( i = 0 ; i < contigCnt - 1 ; ++i )
    {
        if ( genome.GetChrIdFromContigId( i ) == genome.GetChrIdFromContigId( i + 1 ) )
        {
            struct _contig c1 = genome.GetContigInfo( i ) ;
            struct _contig c2 = genome.GetContigInfo( i + 1 ) ;
            gapSize[i] = c2.start - c1.end - 1 ;
        }
        else
            gapSize[i] = -1 ;
    }

    // Start search
    int ncnt ;
    struct _pair *queue = new struct _pair[ contigCnt ] ;
    int head = 0, tail ;
    int danglingTime = 0 ;

    // Pre-allocate the subgraph.
    ContigGraph subgraph( contigCnt, 3 * contigCnt ) ;
    for ( i = 0 ; i < scafCnt ; ++i )
    {
        //if ( used[144281] == true )
        //	printf( "changed %d %d\n", i, scafInfo[i - 1].a ) ;
        if ( scafInfo[i].a == -1 )
            continue ;
        int from, to ;
        genome.GetChrContigRange( genome.GetChrIdFromContigId( scafInfo[i].a ), from, to ) ;
        //printf( "%d: %d %d %d\n", i, scafInfo[i].b, from, to ) ;
        ForwardSearch( from, 0, i, visitTime, counter, visitDummy, contigGraph ) ;
        chosenCnt = 0 ;
        BackwardSearch( to, 1, i, visitTime, counter, contigGraph, chosen, chosenCnt ) ;

        /*printf( "%s %d (%d %d) %d\n", alignments.GetChromName( genome.GetChrIdFromContigId( scafInfo[i].a ) ), i, from, to, chosenCnt ) ;
        if ( chosenCnt > 1 )
        {
        	printf( "=== " ) ;
        	for ( int j = 0 ; j < chosenCnt ; ++j )
        		printf( "%d ", chosen[j] ) ;
        	printf( "\n" ) ;
        }*/

        for ( int j = 0 ; j < chosenCnt ; ++j )
        {
            ncnt = contigGraph.GetNeighbors( chosen[j], 0, neighbors, MAX_NEIGHBOR ) ;
            //printf( "%d %d %d: %d %d %d\n", j, chosen[j], ncnt, neighbors[0].a, visitTime[ neighbors[0].a ],
            //	counter[neighbors[0].a ] ) ;
            for ( int k = 0 ; k < ncnt ; ++k )
            {
                //if ( i == 639 )
                //	printf( "Neighbor from 0 %d: %d %d\n", k, neighbors[k].a, neighbors[k].b ) ;
                if ( visitTime[ neighbors[k].a ] == 2 * i + 1 && counter[neighbors[k].a ] == 2 )
                {
                    subgraph.AddEdge( chosen[j], 0, neighbors[k].a, neighbors[k].b, true ) ;
                    //printf( "subgraph: (%d %d)=>(%d %d)\n", chosen[j], 0, neighbors[k].a, neighbors[k].b ) ;
                }
            }

            ncnt = contigGraph.GetNeighbors( chosen[j], 1, neighbors, MAX_NEIGHBOR ) ;
            for ( int k = 0 ; k < ncnt ; ++k )
            {
                //if ( i == 639 )
                //	printf( "Neighbor from 1 %d: %d %d\n", k, neighbors[k].a, neighbors[k].b ) ;
                if ( visitTime[ neighbors[k].a ] == 2 * i + 1 && counter[neighbors[k].a ] == 2 )
                {
                    subgraph.AddEdge( chosen[j], 1, neighbors[k].a, neighbors[k].b, true ) ;
                    //printf( "subgraph: (%d %d)=>(%d %d)\n", chosen[j], 1, neighbors[k].a, neighbors[k].b ) ;
                }
            }
        }

        // Initialize the degree counter
        for ( int j = 0 ; j < chosenCnt ; ++j )
        {
            for ( int l = 0 ; l < 2 ; ++l )
            {
                /*if ( i == 6145 )
                {
                	std::vector<struct _pair> neighbors ;
                	ncnt = subgraph.GetNeighbors( chosen[j], l, neighbors ) ;
                	printf( "%d ncnt=%d\n", l, ncnt ) ;
                }*/

                ncnt = subgraph.GetNeighbors( chosen[j], l, neighbors, MAX_NEIGHBOR ) ;
                degree[ 2 * chosen[j] + l ] = ncnt ;
            }
        }

        // "topological" sort
        head = 0 ;
        isInQueue[from] = true ;
        queue[0].a = from ;
        queue[0].b = 0 ;
        tail = 1 ;
        int prevTag = -1 ;
        int *prevAdd = buffer ; // reuse counter to save some memory.
        int *nextAdd = buffer2 ;
        int firstAdd = -1 ;

        while ( head < tail )
        {
            int tailTag = tail ;
            for ( int j = head ; j < tailTag ; ++j )
            {
                nextAdd[j] = -1 ;
                if ( !used[ queue[j].a ] )
                {
                    used[ queue[j].a ] = true ;
                    if ( prevTag != -1 )
                    {
                        scaffold.AddEdge( queue[ prevTag].a, 1 - queue[prevTag].b, queue[j].a, queue[j].b ) ;
                        nextAdd[ prevTag ] = j ;

                        /*if ( i == 639 )
                        	printf( "(%lld %lld)=>(%lld %lld)\n", queue[ prevTag].a, 1 - queue[prevTag].b, queue[j].a, queue[j].b ) ;*/
                    }
                    else
                        firstAdd = j ;

                    prevTag = j ;
                }
                prevAdd[j] = prevTag ; // the most recent(<=) queue id when added to scaffold.

                ncnt = subgraph.GetNeighbors( queue[j].a, 1 - queue[j].b, neighbors, MAX_NEIGHBOR ) ;
                for ( int k = 0 ; k < ncnt ; ++k )
                {
                    --degree[ 2 * neighbors[k].a + neighbors[k].b ] ;
                    if ( degree[ 2 * neighbors[k].a + neighbors[k].b ] == 0 && !isInQueue[neighbors[k].a] )
                    {
                        isInQueue[ neighbors[k].a ] = true ;
                        queue[ tail ] = neighbors[k] ; // Interesting assignment, I think.
                        ++tail ;
                        /*if ( i == 639 )
                        	printf( "pushed in queue: %d\n", neighbors[k].a ) ;*/
                        // Put the consecutive contigs together.
                        struct _pair testNeighbors[ MAX_NEIGHBOR ] ;
                        struct _pair tag ;
                        tag = neighbors[k] ;
                        while ( 1 )
                        {
                            if ( contigGraph.GetNeighbors( tag.a, 1 - tag.b, testNeighbors, MAX_NEIGHBOR ) != 1 )
                                break ;
                            int n = subgraph.GetNeighbors( tag.a, 1 - tag.b, testNeighbors, MAX_NEIGHBOR ) ;
                            if ( n != 1 )
                                break ;
                            //printf( "%d %d\n", n, testNeighbors[0].a ) ;

                            struct _pair backNeighbors[ MAX_NEIGHBOR ] ;
                            if ( contigGraph.GetNeighbors( testNeighbors[0].a, testNeighbors[0].b, backNeighbors, MAX_NEIGHBOR ) != 1 )
                                break ;
                            n = subgraph.GetNeighbors( testNeighbors[0].a, testNeighbors[0].b, backNeighbors, MAX_NEIGHBOR ) ;
                            if ( n != 1 )
                                break ;
                            isInQueue[ testNeighbors[0].a ] = true ;
                            queue[tail] = testNeighbors[0] ;
                            ++tail ;
                            /*if ( i == 639 )
                            	printf( "pushed in queue: %d\n", testNeighbors[0].a ) ;*/
                            tag = testNeighbors[0] ;
                        }
                    }
                }
            }

            head = tailTag ;
        }
        // Remove the effect on the subgraph.
        /*if ( tail != chosenCnt )
        {
        	printf( "WARNING: not matched\n" ) ;
        	exit( 1 ) ;
        }*/
        for ( int j = 0 ; j < tail ; ++j )
        {
            visitDummy[ queue[j].a ] = -1 ;
            counter[ queue[j].a ] = -1 ;
            subgraph.RemoveAdjacentEdges( queue[j].a ) ;
            isInQueue[ queue[j].a ] = false ;
        }
        subgraph.ResetEdgeUsed() ;

        // no point is picked
        if ( prevTag == -1 )
        {
            continue ;
        }

        // Update the gap size
        prevTag = -1 ;
        for ( int j = 0 ; j < tail - 1 ; ++j )
        {
            if ( genome.GetChrIdFromContigId( queue[j].a ) == genome.GetChrIdFromContigId( from ) )
                prevTag = queue[j].a ;
            else if ( prevTag != -1 )
            {
                struct _contig c = genome.GetContigInfo( queue[j].a ) ;
                gapSize[prevTag] -= ( c.end - c.start + 1) ;
            }
        }
        // Add the dangling contigs. Use the fact that the queue holding the contigs in the same order as in the scaffold.
        // 5'->3' dangling
        int *chosenDummy = degree ;
        for ( int j = tail - 1 ; j >= 0 ; --j )
        {
            //if ( j < tail - 1 )
            //	continue ;
            chosenCnt = 0 ;
            //if ( queue[j].a == 0 )
            //	printf( "Dummy: %d %d %d\n", j, queue[j].b, 1 - queue[j].b ) ;
            SearchDangling( queue[j].a, queue[j].b, used, danglingTime, danglingVisitTime, contigGraph, false, chosen, chosenDummy, chosenCnt, genome ) ;
            ++danglingTime ;
            int prevTag = prevAdd[j] ;
            /*if ( queue[j].a == 0 )
            {
            	struct _pair neighbors[5] ;
            	int ncnt = contigGraph.GetNeighbors( queue[j].a, 1 - queue[j].b, neighbors, 5 ) ;
            	printf( "%d %d %d %d: %d %d\n", queue[j].b, chosenCnt, prevTag, ncnt, neighbors[0].a, used[ neighbors[0].a ] ) ;
            }*/
            if ( prevTag == -1 )
                break ;

            // Trim the dangling list
            int k = chosenCnt - 1 ;
            if ( j > 0 && j < tail - 1 )
            {
                for ( k = chosenCnt - 1 ; k >= 1 ; --k )
                    if ( genome.GetChrIdFromContigId( chosen[k] ) != genome.GetChrIdFromContigId( chosen[k - 1] ) )
                        break ;
            }

            // Test the gap size
            int len = 0 ;
            for ( int l = 0 ; l <= k ; ++l )
            {
                struct _contig c = genome.GetContigInfo( chosen[k] ) ;
                len += c.end - c.start + 1 ;
            }

            if ( j < tail - 1 )
            {
                int l ;
                for ( l = j ; l >= 0 ; --l )
                    if ( genome.GetChrIdFromContigId( queue[l].a ) == genome.GetChrIdFromContigId( from ) )
                        break ;

                if ( !ignoreGap && len >= gapSize[ queue[l].a ] + 100 )
                    continue ;
                else
                    gapSize[ queue[l].a ] -= len ;
            }


            for ( ; k >= 0 ; --k )
            {
                used[ chosen[k] ] = true ;
                //printf( "Dangling 1: %d=>%d\n", queue[prevTag].a, chosen[k] ) ;
                scaffold.InsertNode( queue[ prevTag ].a, 1 - queue[ prevTag ].b, chosen[k], chosenDummy[k] ) ;
            }
        }

        // 3'->5' dangling
        for ( int j = 0 ; j < tail ; ++j )
        {
            //if ( j > 0 )
            //	continue ;
            chosenCnt = 0 ;
            SearchDangling( queue[j].a, 1 - queue[j].b, used, danglingTime, danglingVisitTime, contigGraph, false, chosen, chosenDummy, chosenCnt, genome ) ;
            ++danglingTime ;

            int prevTag = prevAdd[j] ;
            int nextTag ;
            if ( prevTag == -1 || j <= firstAdd )
                nextTag = firstAdd ;
            else if ( j == prevTag )
                nextTag = j ;
            else
                nextTag = nextAdd[ prevTag ] ;
            if ( nextTag == -1 )
                break ;
            /*if ( queue[j].a == 37549 )
            {
            	struct _pair neighbors[5] ;
            	int ncnt = contigGraph.GetNeighbors( queue[j].a, queue[j].b, neighbors, 5 ) ;
            	fprintf( stderr, "%d %d %d: %d %d %d: %d %d %d\n", j, queue[j].a, queue[j].b, chosenCnt, nextTag, ncnt, chosen[0], chosenDummy[0], used[ chosen[0] ] ) ;
            }*/

            // trim the danling list
            int k = chosenCnt - 1 ;
            if ( j < tail - 1 && j > 0 )
            {
                for ( k = chosenCnt - 1 ; k >= 1 ; --k )
                    if ( genome.GetChrIdFromContigId( chosen[k] ) != genome.GetChrIdFromContigId( chosen[k - 1] ) )
                        break ;
            }

            // Test the gap size
            int len = 0 ;
            for ( int l = 0 ; l <= k ; ++l )
            {
                struct _contig c = genome.GetContigInfo( chosen[k] ) ;
                len += c.end - c.start + 1 ;
            }

            if ( j > 0 )
            {
                int l ;
                for ( l = j - 1 ; l >= 0 ; --l ) // Notice the j-1 here, because we want the gap strictly before current contig
                    if ( genome.GetChrIdFromContigId( queue[l].a ) == genome.GetChrIdFromContigId( from ) )
                        break ;

                if ( !ignoreGap && len >= gapSize[ queue[l].a ] + 100 )
                    continue ;
                else
                    gapSize[ queue[l].a ] -= len ;
            }

            for ( ; k >= 0 ; --k )
            {
                used[ chosen[k] ] = true ;
                scaffold.InsertNode( queue[nextTag].a, queue[nextTag].b, chosen[k], chosenDummy[k] ) ;
                //printf( "Dangling 2: %d<=%d\n", queue[nextTag].a, chosen[k] ) ;
                //if ( chosen[k] == 10246 )
                //	printf( "hi %d %d %d %d\n", j, queue[j].a, k, chosen[k] ) ;
            }
        }
    }
    //return 0 ;

    // Output the scaffold
    int id = 0 ;
    char infoFileName[512] ;
    char outputFileName[512] ;
    sprintf( infoFileName, "%s.info", prefix ) ;
    sprintf( outputFileName, "%s.fa", prefix ) ;

    outputFile = fopen( outputFileName, "w" ) ;
    infoFile = fopen( infoFileName, "w") ;

    memset( used, false, sizeof( bool ) * contigCnt ) ;
    for ( i = 0 ; i < contigCnt ; ++i )
    {
        //printf( "%d (%s)\n", i, alignments.GetChromName( genome.GetChrIdFromContigId( i ) )  ) ; fflush( stdout ) ;
        /*if ( i == 10246 )
        {
        	std::vector<struct _pair> neighbors ;
        	scaffold.GetNeighbors( i, 0, neighbors ) ;
        	printf( "%u\n", neighbors.size() ) ;
        }*/
        if ( used[i] )
            continue ;
        int ncnt1 = scaffold.GetNeighbors( i, 0, neighbors, MAX_NEIGHBOR ) ;
        int ncnt2 = scaffold.GetNeighbors( i, 1, neighbors, MAX_NEIGHBOR ) ;
        if ( ncnt1 == 0 || ncnt2 == 0 ) // The end of a scaffold
        {
            fprintf( outputFile, ">scaffold_%d\n", id) ;
            fprintf( infoFile, ">scaffold_%d", id ) ;
            ++id ;
            int p = i ;
            int dummyP = 1 ;
            if ( ncnt1 == 0 )
                dummyP = 0 ;

            used[i] = true ;
            genome.PrintContig( outputFile, i, dummyP ) ;
            fprintf( infoFile, " (%s %d %c)", alignments.GetChromName( genome.GetChrIdFromContigId( p ) ), p, dummyP == 0 ? '+' : '-' ) ;
            while ( 1 )
            {
                ncnt = scaffold.GetNeighbors( p, 1 - dummyP, neighbors, MAX_NEIGHBOR ) ;
                if ( ncnt == 0 )
                    break ;
                // ncnt must be 1
                int insertN = 17 ;

                if ( genome.GetChrIdFromContigId( p ) == genome.GetChrIdFromContigId( neighbors[0].a ) )
                {
                    struct _contig cp, cna ;
                    cp = genome.GetContigInfo( p ) ;
                    cna = genome.GetContigInfo( neighbors[0].a ) ;
                    if ( p < neighbors[0].a )
                        insertN = cna.start - cp.end - 1 ;
                    else if ( p > neighbors[0].a )
                        insertN = cp.start - cna.end - 1 ;

                }

                p = neighbors[0].a ;
                dummyP = neighbors[0].b ;
                for ( int j = 0 ; j < insertN ; ++j )
                    fprintf( outputFile, "N" ) ;
                used[p] = true ;
                genome.PrintContig( outputFile, p, dummyP ) ;

                fprintf( infoFile, " (%s %d %c)", alignments.GetChromName( genome.GetChrIdFromContigId( p ) ), p, dummyP == 0 ? '+' : '-' ) ;
            }
            fprintf( outputFile, "\n" ) ;
            fprintf( infoFile, "\n" ) ;
        }
    }

    for ( i = 0 ; i < contigCnt ; ++i )
        if ( !used[i] )
        {
            fprintf( stderr, "Unreported contig %d.\n", i ) ;
        }
    fclose( outputFile ) ;
    fclose( infoFile ) ;

    delete[] buffer ;
    delete[] buffer2 ;
    delete[] chosen ;
    delete[] queue ;
    delete[] counter ;
    delete[] visitTime ;
    delete[] used ;
    delete[] scafInfo ;
    delete[] isInQueue ;
    delete[] gapSize ;

    //fclose( rascafFile ) ;
    return 0 ;
}
示例#17
0
LogData * LogerManager::makeLogData(LoggerId id, int level)
{
    LogData * pLog = NULL;
    if (true)
    {
        if (!_freeLogDatas.empty())
        {
            AutoLock l(_logLock);
            if (!_freeLogDatas.empty())
            {
                pLog = _freeLogDatas.back();
                _freeLogDatas.pop_back();
            }
        }
        if (pLog == NULL)
        {
            pLog = new LogData();
        }
    }
    //append precise time to log
    if (true)
    {
        pLog->_id = id;
        pLog->_level = level;
        pLog->_type = LDT_GENERAL;
        pLog->_typeval = 0;
        pLog->_contentLen = 0;
#ifdef WIN32
        FILETIME ft;
        GetSystemTimeAsFileTime(&ft);
        unsigned long long now = ft.dwHighDateTime;
        now <<= 32;
        now |= ft.dwLowDateTime;
        now /= 10;
        now -= 11644473600000000ULL;
        now /= 1000;
        pLog->_time = now / 1000;
        pLog->_precise = (unsigned int)(now % 1000);
#else
        struct timeval tm;
        gettimeofday(&tm, NULL);
        pLog->_time = tm.tv_sec;
        pLog->_precise = tm.tv_usec / 1000;
#endif
    }

    //format log
    if (true)
    {
        tm tt = timeToTm(pLog->_time);

        pLog->_contentLen = sprintf(pLog->_content, "%d-%02d-%02d %02d:%02d:%02d.%03u %s ",
            tt.tm_year + 1900, tt.tm_mon + 1, tt.tm_mday, tt.tm_hour, tt.tm_min, tt.tm_sec, pLog->_precise,
            LOG_STRING[pLog->_level]);
        if (pLog->_contentLen < 0)
        {
            pLog->_contentLen = 0;
        }
    }
    return pLog;
}
int TriangleAdjacencyGraph::fillIndexFromStrip ( std::vector<Index> &indexVec,
    TriangleList &strip, bool rev )
{
  Triangle *triangle = rev ? strip.last : strip.first, *nextTriangle;
  HalfEdge *firstEdge, *halfEdge, *gate;
  WalkCase walkCase;
  Index vertex;
  int cost = 0;

  if (triangle) {
    cost = 3;
    indexVec.reserve(32); // find better value

    indexVec.resize(3);
    if ((nextTriangle = (rev ? triangle->prev : triangle->next))) {
      cost++;
      gate = findGateEdge(triangle,nextTriangle);
      firstEdge = gate->next->next;
      indexVec.push_back(vertex = gate->twin->next->vertexEnd());

      walkCase = LEFT;
      for ( triangle = nextTriangle; 
	  (nextTriangle = (rev ? triangle->prev : triangle->next));
	  triangle = nextTriangle ) {
	halfEdge = gate->twin;
	gate = findGateEdge(triangle,nextTriangle); 
	if (walkCase == RIGHT)
	  // RIGHT

	  if (halfEdge->next == gate) {
	    indexVec.push_back(vertex = gate->twin->next->vertexEnd());
	    walkCase = LEFT;
	    cost++;
	  }
	  else {
	    // swap; walkCase stays RIGHT;

	    indexVec.back() = gate->vertexEnd();
	    indexVec.push_back(gate->vertexStart());              
	    indexVec.push_back(vertex = gate->twin->next->vertexEnd());
	    cost += 2;
	  }
	else
	  // LEFT

	  if (halfEdge->next->next == gate) {
	    indexVec.push_back(vertex = gate->twin->next->vertexEnd());
	    walkCase = RIGHT;
	    cost++;
	  }
	  else {
	    // swap; walkCase stays LEFT;

	    indexVec.back() = gate->vertexStart();
	    indexVec.push_back(gate->vertexEnd());
	    indexVec.push_back(vertex = gate->twin->next->vertexEnd());
	    cost += 2;
	  }
      }
    }
    else 
      firstEdge = &triangle->halfEdgeVec[0];      
    indexVec[0] = vertex = firstEdge->vertexStart();
    indexVec[1] = vertex = firstEdge->next->vertexStart();      
    indexVec[2] = vertex = firstEdge->next->next->vertexStart();
  }

  return cost;
}
    void FdSimpleKlugeExtOUVPPEngine::calculate() const {

        ext::shared_ptr<SwingExercise> swingExercise(
            ext::dynamic_pointer_cast<SwingExercise>(arguments_.exercise));

        QL_REQUIRE(swingExercise, "Swing exercise supported only");

        const FdmVPPStepConditionFactory stepConditionFactory(arguments_);

        // 1. Exercise definition
        const std::vector<Time> exerciseTimes
            = swingExercise->exerciseTimes(rTS_->dayCounter(),
                                           rTS_->referenceDate());

        // 2. mesher set-up
        const Time maturity = exerciseTimes.back();
        const ext::shared_ptr<ExtOUWithJumpsProcess> klugeProcess
            = process_->getKlugeProcess();

        const ext::shared_ptr<StochasticProcess1D> klugeOUProcess
            = klugeProcess->getExtendedOrnsteinUhlenbeckProcess();

        const ext::shared_ptr<Fdm1dMesher> xMesher(
            new FdmSimpleProcess1dMesher(xGrid_, klugeOUProcess, maturity));

        const ext::shared_ptr<Fdm1dMesher> yMesher(
            new ExponentialJump1dMesher(yGrid_,
                                        klugeProcess->beta(),
                                        klugeProcess->jumpIntensity(),
                                        klugeProcess->eta(), 1e-3));

        const ext::shared_ptr<Fdm1dMesher> gMesher(
            new FdmSimpleProcess1dMesher(gGrid_,
                                         process_->getExtOUProcess(),maturity));

        const ext::shared_ptr<Fdm1dMesher> exerciseMesher(
            stepConditionFactory.stateMesher());

        const ext::shared_ptr<FdmMesher> mesher (
            new FdmMesherComposite(xMesher, yMesher, gMesher, exerciseMesher));

        // 3. Calculator
        const ext::shared_ptr<FdmInnerValueCalculator> zeroInnerValue(
            new FdmZeroInnerValue());

        const ext::shared_ptr<Payoff> zeroStrikeCall(
            new PlainVanillaPayoff(Option::Call, 0.0));

        const ext::shared_ptr<FdmInnerValueCalculator> fuelPrice(
            new FdmExpExtOUInnerValueCalculator(zeroStrikeCall,
                                                mesher, fuelShape_, 2));

        const ext::shared_ptr<FdmInnerValueCalculator> powerPrice(
            new FdmExtOUJumpModelInnerValue(zeroStrikeCall,mesher,powerShape_));

        const ext::shared_ptr<FdmInnerValueCalculator> sparkSpread(
            new FdmSparkSpreadInnerValue(
                ext::dynamic_pointer_cast<BasketPayoff>(arguments_.payoff),
                fuelPrice, powerPrice));

        // 4. Step conditions
        std::list<std::vector<Time> > stoppingTimes;
        std::list<ext::shared_ptr<StepCondition<Array> > > stepConditions;

        // 4.1 Bermudan step conditions
        stoppingTimes.push_back(exerciseTimes);
        const FdmVPPStepConditionMesher mesh = { 3u, mesher };
        
        const ext::shared_ptr<FdmVPPStepCondition> stepCondition(
            stepConditionFactory.build(mesh, fuelCostAddon_,
                                       fuelPrice, sparkSpread));

        stepConditions.push_back(stepCondition);

        const ext::shared_ptr<FdmStepConditionComposite> conditions(
            new FdmStepConditionComposite(stoppingTimes, stepConditions));

        // 5. Boundary conditions
        const FdmBoundaryConditionSet boundaries;

        // 6. set-up solver
        FdmSolverDesc solverDesc = { mesher, boundaries, conditions,
                                     zeroInnerValue, maturity, tGrid_, 0 };

        const ext::shared_ptr<FdmKlugeExtOUSolver<4> > solver(
            new FdmKlugeExtOUSolver<4>(Handle<KlugeExtOUProcess>(process_),
                                       rTS_, solverDesc, schemeDesc_));

        std::vector<Real> x(4);
        x[0] = process_->initialValues()[0];
        x[1] = process_->initialValues()[1];
        x[2] = process_->initialValues()[2];
        
        const Real tol = 1e-8;
        const Real maxExerciseValue = exerciseMesher->locations().back();
        const Real minExerciseValue = exerciseMesher->locations().front();

        Array results(exerciseMesher->size());
        for (Size i=0; i < results.size(); ++i) {

            x[3] = std::max(minExerciseValue + tol,
                            std::min(exerciseMesher->location(i),
                                     maxExerciseValue - tol));
            results[i] = solver->valueAt(x);
        }
        results_.value = stepCondition->maxValue(results);
    }
示例#20
0
void Tools::AssembleICDF(std::vector<double>& histogram, std::vector<double>& icdf, double& density)
{
	// std::vector<double> tmp = icdf; // Debug mode
	// try{
	int nbins = histogram.size();
	static std::vector<double> icdf_reverse;
	icdf.resize(nbins+1);
	icdf.front() = 0.;
	std::partial_sum(histogram.begin(), histogram.end(), icdf.begin()+1);
	density = icdf.back();

	if (density <= 0)
	{
		/* Give up reconstruction */
		std::fill(icdf.begin(), icdf.end(), 0.);
		density = 0;
		return;
	}

	/* First, we take care of negative values and overshots */
	int i0 = 0, i1 = nbins, imax = 0;
	for (int i=1; i<nbins; i++)
	{
		if (icdf.at(i) < 0) i0 = i;
		if (icdf.at(i) > density && i1 > i) i1 = i;
		if (icdf.at(i) > .5*density && icdf.at(i-1) < .5*density) imax = i;
	}

	if (i1 < i0) /* Accidents happen */
	{
		double df = (density - 0.)/(i0 - i1);
		for (int j=0; j<= i1; j++) icdf.at(j) = 0.;
		for (int j=i1+1; j<i0; j++) icdf.at(j) = (j-i1)*df;
		for (int j=i0; j<=nbins; j++) icdf.at(j) = density;
		i0 = 0; i1 = nbins;
	}

	if (i0 > 0)
	{
		int ind1 = i0 - 1;
		int ind2 = i0 + 1;
		double S = 0;
		for (int j = 1; j < ind2; j++) 
			S += icdf.at(j);
		double df = 2.*S/static_cast<double>((ind2-ind1)*(ind2-ind1-1));
		while (df<0 || (ind2-1-ind1)*df > icdf.at(ind2))
		{
			if (ind1 > 1  && icdf.at(ind2) <= density)
				ind1--;
			else if (ind2 < imax)
			{
				S += icdf.at(ind2);
				ind2++;
				ind1 = i0-1;
			}
			else // There is something wrong with the distribution. Give up momentum conservation
       		{
				ind1 = i0-1;
       			ind2 = i0+1;
	   			df = std::min(density, icdf.at(ind2))/(ind2-ind1);
       			break;
       		}

			df = 2.*S/static_cast<double>((ind2-ind1)*(ind2-ind1-1));
		}
		for (int j=0; j<ind1+1; j++)
			icdf.at(j) = 0;
		for (int j = ind1+1; j<ind2; j++)
			icdf.at(j) = (j-ind1)*df;
	}

	if (i1 < nbins)
	{
		int ind1 = i1 - 1;
		int ind2 = i1 + 1;
		double S = 0;
		for (int j = ind1+1; j < nbins; j++) 
			S += icdf.at(j);
		double df = 2.*((nbins-ind1-1)*density-S)/static_cast<double>((ind2-ind1)*(ind2-ind1-1));
		while (df<0 || (ind2-1-ind1)*df > density - icdf.at(ind1))
		{
			if (ind2 < nbins+1 && icdf.at(ind1) >= 0)
				ind2++;
			else if (ind1 > imax)
			{
				S += icdf.at(ind1);
				ind1--;
				ind2 = i1+1;
			}
			else
			{
				ind1 = i1-1;
				ind2 = i1+1;
				df =  (std::max(icdf.at(ind1), 0.) - density)/(ind1-ind2);
				break;
			}
			df = 2.*((nbins-ind1-1)*density-S)/static_cast<double>((ind2-ind1)*(ind2-ind1-1));
		}
		for (int j = ind1+1; j<ind2; j++)
			icdf.at(j) = density + (j-ind2)*df;
		for (int j=ind2; j<nbins; j++)
			icdf.at(j) = density;
	}

	double lowval=0.;
	int i = 1;
	/* Ensure that the ICDF is a monotonic function */
	while (i < imax)
	{
		if (lowval > icdf.at(i))
		{
			/* The vector icdf is monotonic up to index i-1 */
			int ind1 = i-1, ind2 = i+1;
			double minval = icdf.at(i);

            while (lowval > icdf.at(ind2))
            {
            	ind2++;
                if (minval > icdf.at(ind2)) 
               	{
               		minval = icdf.at(ind2);
               		i = ind2;
               	}
            }
            while (minval < icdf.at(ind1)) ind1--;
            double S = 0;
            for (int j = ind1+1; j<i; j++)
            	S += icdf.at(j);
            double df = 2.*(S - (i - ind1 - 1)*icdf.at(ind1))/static_cast<double>((i-ind1)*(i-ind1-1));
            while (df<0 || df*(i-1-ind1) > icdf.at(i) - icdf.at(ind1))
            {
           		if (i<imax)
           		{
	            	S += icdf.at(i);
            		i++;
           			df = 2.*(S - (i - ind1 - 1)*icdf.at(ind1))/static_cast<double>((i-ind1)*(i-ind1-1));
           		}
           		else // There is something wrong with the distribution. Give up momentum conservation
           		{
           			i = ind2;
           			df = (icdf.at(i) - icdf.at(ind1))/(i-ind1);
           			break;
           		}

            }
            for (int j=ind1+1; j<i; j++)
               icdf.at(j) = icdf.at(ind1) + df*(j-ind1);
		}
		lowval = icdf.at(i);
		i++;
	}
	double highval = density;
	i=nbins-1;
	while (i>imax)
	{
		if (highval < icdf.at(i))
		{        
			int ind1 = i+1, ind2 = i-1;
			double maxval = icdf.at(i); 
			while (highval < icdf.at(ind2))
			{
				ind2--;
				if (maxval < icdf.at(ind2))
				{
					maxval = icdf.at(ind2);
					i = ind2;
				}
			}
			while (maxval > icdf.at(ind1)) ind1++;  

			double S = 0;
			for (int j=i+1; j<ind1-1; j++)
				S += icdf.at(j);
			double df = 2/((ind1-i)*(ind1-i-1))*((ind1 - i -1) * icdf.at(ind1) - S);
			while (df < 0 || df*(ind1-i-1) > icdf.at(ind1) - icdf.at(i))
			{
				if (i>imax)
				{
					S += icdf.at(i);
					i--;
					df = 2/((ind1-i)*(ind1-i-1))*((ind1 - i -1) * icdf.at(ind1) - S);
				}
				else // There is something wrong with the distribution. Give up momentum conservation
				{
           			i = ind2;
           			df = (icdf.at(ind1) - icdf.at(i))/(ind1-i);
           			break;
				}
			}
            for (int j=ind1-1; j>i; j--)
               icdf.at(j) = icdf.at(ind1) + df*(j-ind1);
		}

		highval = icdf.at(i);
		i--;
	}
	for (int i=0; i<nbins; i++)
		histogram.at(i) = icdf.at(i+1) - icdf.at(i);
// }
// catch(...){ 
// std::cout << "Failure in the ICDF reconstruction\n"; 
// icdf= tmp;


// int nbins = histogram.size();
// static std::vector<double> icdf_reverse;
// icdf.resize(nbins+1);
// icdf.front() = 0.;
// std::partial_sum(histogram.begin(), histogram.end(), icdf.begin()+1);
// density = icdf.back();
// std::cout << "1:\n";
// for (double & s: icdf) std::cout << s << "\t"; std::cout << "\n\n"; 

// if (density <= 0)
// {
// 	/* Give up reconstruction */
// 	std::fill(icdf.begin(), icdf.end(), 0.);
// 	density = 0;
// 	return;
// }

// /* First, we take care of negative values and overshots */
// int i0 = 0, i1 = nbins, imax = 0;
// for (int i=1; i<nbins; i++)
// {
// 	if (icdf.at(i) < 0) i0 = i;
// 	if (icdf.at(i) > density && i1 > i) i1 = i;
// 	if (icdf.at(i) > .5*density && icdf.at(i-1) < .5*density) imax = i;
// }

// if (i1 < i0) /* Accidents happen */
// {
// 	double df = (density - 0.)/(i0 - i1);
// 	for (int j=0; j<= i1; j++) icdf.at(j) = 0.;
// 	for (int j=i1+1; j<i0; j++) icdf.at(j) = (j-i1)*df;
// 	for (int j=i0; j<=nbins; j++) icdf.at(j) = density;
// 	i0 = 0; i1 = nbins;
// }

// if (i0 > 0)
// {
// 	int ind1 = i0 - 1;
// 	int ind2 = i0 + 1;
// 	double S = 0;
// 	for (int j = 1; j < ind2; j++) 
// 		S += icdf.at(j);
// 	double df = 2.*S/static_cast<double>((ind2-ind1)*(ind2-ind1-1));
// 	while (df<0 || (ind2-1-ind1)*df > icdf.at(ind2))
// 	{
// 		if (ind1 > 1  && icdf.at(ind2) <= density)
// 			ind1--;
// 		else if (ind2 < imax)
// 		{
// 			S += icdf.at(ind2);
// 			ind2++;
// 			ind1 = i0-1;
// 		}
// 		else // There is something wrong with the distribution. Give up momentum conservation
//    		{
// 			ind1 = i0-1;
//    			ind2 = i0+1;
//    			df = std::min(density, icdf.at(ind2))/(ind2-ind1);
//    			break;
//    		}

// 		df = 2.*S/static_cast<double>((ind2-ind1)*(ind2-ind1-1));
// 	}
// 	for (int j=0; j<=ind1; j++)
// 		icdf.at(j) = 0;
// 	for (int j = ind1+1; j<ind2; j++)
// 		icdf.at(j) = (j-ind1)*df;
// 	std::cout << "2:\t ind1:\t" << ind1 << "\ti0:\t" << i0 << "\tind2:\t" << ind2 << "\n";
// }
// for (double & s: icdf) std::cout << s << "\t"; std::cout << "\n\n"; 

// if (i1 < nbins)
// {
// 	int ind1 = i1 - 1;
// 	int ind2 = i1 + 1;
// 	double S = 0;
// 	for (int j = ind1+1; j < nbins; j++) 
// 		S += icdf.at(j);
// 	double df = 2.*((nbins-ind1-1)*density-S)/static_cast<double>((ind2-ind1)*(ind2-ind1-1));
// 	while (df<0 || (ind2-1-ind1)*df > density - icdf.at(ind1))
// 	{
// 		if (ind2 < nbins+1 && icdf.at(ind1) >= 0)
// 			ind2++;
// 		else if (ind1 > imax)
// 		{
// 			S += icdf.at(ind1);
// 			ind1--;
// 			ind2 = i1+1;
// 		}
// 		else
// 		{
// 			ind1 = i1-1;
// 			ind2 = i1+1;
// 			df =  (std::max(icdf.at(ind1), 0.) - density)/(ind1-ind2);
// 			break;
// 		}
// 		df = 2.*((nbins-ind1-1)*density-S)/static_cast<double>((ind2-ind1)*(ind2-ind1-1));
// 	}
// 	for (int j = ind1+1; j<ind2; j++)
// 		icdf.at(j) = density + (j-ind2)*df;
// 	for (int j=ind2; j<nbins; j++)
// 		icdf.at(j) = density;
// std::cout << "3:\t ind1:\t" << ind1 << "\ti1:\t" << i1 << "\tind2:\t" << ind2 << "\n";
// }
// for (double & s: icdf) std::cout << s << "\t"; std::cout << "\n\n"; 

// double lowval=0.;
// int i = 1;
// /* Ensure that the ICDF is a monotonic function */
// while (i < imax)
// {
// 	if (lowval > icdf.at(i))
// 	{
// 		/* The vector icdf is monotonic up to index i-1 */
// 		int ind1 = i-1, ind2 = i+1;
// 		double minval = icdf.at(i);

//         while (lowval > icdf.at(ind2))
//         {
//         	ind2++;
//             if (minval > icdf.at(ind2)) 
//            	{
//            		minval = icdf.at(ind2);
//            		i = ind2;
//            	}
//         }
//         while (minval < icdf.at(ind1)) ind1--;
//         double S = 0;
//         for (int j = ind1+1; j<i; j++)
//         	S += icdf.at(j);
//         double df = 2.*(S - (i - ind1 - 1)*icdf.at(ind1))/static_cast<double>((i-ind1)*(i-ind1-1));
//         while (df<0 || df*(i-1-ind1) > icdf.at(i) - icdf.at(ind1))
//         {
//        		if (i<imax)
//        		{
//             	S += icdf.at(i);
//         		i++;
//        			df = 2.*(S - (i - ind1 - 1)*icdf.at(ind1))/static_cast<double>((i-ind1)*(i-ind1-1));
//        		}
//        		else // There is something wrong with the distribution. Give up momentum conservation
//        		{
//        			i = ind2;
//        			df = (icdf.at(i) - icdf.at(ind1))/(i-ind1);
//        			break;
//        		}

//         }
//         for (int j=ind1+1; j<i; j++)
//            icdf.at(j) = icdf.at(ind1) + df*(j-ind1);
// 	}
// 	lowval = icdf.at(i);
// 	i++;
// }
// std::cout << "4:\n";
// for (double & s: icdf) std::cout << s << "\t"; std::cout << "\n\n"; 
// double highval = density;
// i=nbins-1;
// while (i>imax)
// {
// 	if (highval < icdf.at(i))
// 	{        
// 		int ind1 = i+1, ind2 = i-1;
// 		double maxval = icdf.at(i); 
// 		while (highval < icdf.at(ind2))
// 		{
// 			ind2--;
// 			if (maxval < icdf.at(ind2))
// 			{
// 				maxval = icdf.at(ind2);
// 				i = ind2;
// 			}
// 		}
// 		while (maxval > icdf.at(ind1)) ind1++;  

// 		double S = 0;
// 		for (int j=i+1; j<ind1-1; j++)
// 			S += icdf.at(j);
// 		double df = 2/((ind1-i)*(ind1-i-1))*((ind1 - i -1) * icdf.at(ind1) - S);
// 		while (df < 0 || df*(ind1-i-1) > icdf.at(ind1) - icdf.at(i))
// 		{
// 			if (i>imax)
// 			{
// 				S += icdf.at(i);
// 				i--;
// 				df = 2/((ind1-i)*(ind1-i-1))*((ind1 - i -1) * icdf.at(ind1) - S);
// 			}
// 			else // There is something wrong with the distribution. Give up momentum conservation
// 			{
//        			i = ind2;
//        			df = (icdf.at(ind1) - icdf.at(i))/(ind1-i);
//        			break;
// 			}
// 		}
//         for (int j=ind1-1; j>i; j--)
//            icdf.at(j) = icdf.at(ind1) + df*(j-ind1);
// 	}

// 	highval = icdf.at(i);
// 	i--;
// }
// std::cout << "5:\n";
// for (double & s: icdf) std::cout << s << "\t"; std::cout << "\n\n"; 
// for (int i=0; i<nbins; i++)
// 	histogram.at(i) = icdf.at(i+1) - icdf.at(i);

// 	exit(1);
// }
}
示例#21
0
 char* arg(const char* value)
 {
     argp.push_back(new char [strlen(value) + 1]);
     strcpy(argp.back(), value);
     return argp.back();
 }
示例#22
0
void loadMiscSettings() {
	FileParser infile;
	// load miscellaneous settings from engine config
	// misc.txt
	if (infile.open(mods->locate("engine/misc.txt").c_str())) {
		while (infile.next()) {
			if (infile.key == "save_hpmp") {
				if (toInt(infile.val) == 1)
					SAVE_HPMP = true;
			} else if (infile.key == "default_name") {
				DEFAULT_NAME = infile.val.c_str();
			} else if (infile.key == "corpse_timeout") {
				CORPSE_TIMEOUT = toInt(infile.val);
			} else if (infile.key == "sell_without_vendor") {
				if (toInt(infile.val) == 1)
					SELL_WITHOUT_VENDOR = true;
				else
					SELL_WITHOUT_VENDOR = false;
			} else if (infile.key == "aim_assist") {
				AIM_ASSIST = toInt(infile.val);
			}
			
		}
		infile.close();
	} else fprintf(stderr, "Unable to open engine/misc.txt!\n");
	// resolutions.txt
	if (infile.open(mods->locate("engine/resolutions.txt").c_str())) {
		while (infile.next()) {
			if (infile.key == "menu_frame_width")
				FRAME_W = toInt(infile.val);
			else if (infile.key == "menu_frame_height")
				FRAME_H = toInt(infile.val);
			else if (infile.key == "icon_size")
				ICON_SIZE = toInt(infile.val);
			else if (infile.key == "required_width") {
				MIN_VIEW_W = toInt(infile.val);
				if (VIEW_W < MIN_VIEW_W) VIEW_W = MIN_VIEW_W;
				VIEW_W_HALF = VIEW_W/2;
			} else if (infile.key == "required_height") {
				MIN_VIEW_H = toInt(infile.val);
				if (VIEW_H < MIN_VIEW_H) VIEW_H = MIN_VIEW_H;
				VIEW_H_HALF = VIEW_H/2;
			}
		}
		infile.close();
	} else fprintf(stderr, "Unable to open engine/resolutions.txt!\n");
	// gameplay.txt
	if (infile.open(mods->locate("engine/gameplay.txt").c_str())) {
		while (infile.next()) {
			if (infile.key == "enable_playgame") {
				if (toInt(infile.val) == 1)
					ENABLE_PLAYGAME = true;
				else
					ENABLE_PLAYGAME = false;
			}
		}
		infile.close();
	} else fprintf(stderr, "Unable to open engine/gameplay.txt!\n");
	// combat.txt
	if (infile.open(mods->locate("engine/combat.txt").c_str())) {
		while (infile.next()) {
			if (infile.key == "max_absorb_percent") {
				MAX_ABSORB = toInt(infile.val);
			} else if (infile.key == "max_resist_percent") {
				MAX_RESIST = toInt(infile.val);
			} else if (infile.key == "max_block_percent") {
				MAX_BLOCK = toInt(infile.val);
			} else if (infile.key == "max_avoidance_percent") {
				MAX_AVOIDANCE = toInt(infile.val);
			}
		}
		infile.close();
	} else fprintf(stderr, "Unable to open engine/combat.txt!\n");
	// elements.txt
	if (infile.open(mods->locate("engine/elements.txt").c_str())) {
		Element e;
		ELEMENTS.clear();
		while (infile.next()) {
			if (infile.key == "name") e.name = infile.val;
			else if (infile.key == "resist") e.resist = infile.val;

			if (e.name != "" && e.resist != "") {
				ELEMENTS.push_back(e);
				e.name = e.resist = "";
			}
		}
		infile.close();
	} else fprintf(stderr, "Unable to open engine/elements.txt!\n");
	// classes.txt
	if (infile.open(mods->locate("engine/classes.txt").c_str())) {
		HeroClass c;
		HERO_CLASSES.clear();
		while (infile.next()) {
			if (infile.key == "name") c.name = infile.val;

			if (c.name != "") {
				HERO_CLASSES.push_back(c);
				c.name = "";
			}

			if (!HERO_CLASSES.empty()) {
				if (infile.key == "description") HERO_CLASSES.back().description = infile.val;
				else if (infile.key == "currency") HERO_CLASSES.back().currency = toInt(infile.val);
				else if (infile.key == "equipment") HERO_CLASSES.back().equipment = infile.val;
				else if (infile.key == "physical") HERO_CLASSES.back().physical = toInt(infile.val);
				else if (infile.key == "mental") HERO_CLASSES.back().mental = toInt(infile.val);
				else if (infile.key == "offense") HERO_CLASSES.back().offense = toInt(infile.val);
				else if (infile.key == "defense") HERO_CLASSES.back().defense = toInt(infile.val);
				else if (infile.key == "actionbar") {
					for (int i=0; i<12; i++) {
						HERO_CLASSES.back().hotkeys[i] = toInt(infile.nextValue());
					}
				}
				else if (infile.key == "powers") {
					string power;
					while ( (power = infile.nextValue()) != "") {
						HERO_CLASSES.back().powers.push_back(toInt(power));
					}
				}
			}
		}
		infile.close();
	} else fprintf(stderr, "Unable to open engine/classes.txt!\n");

	// Make a default hero class if none were found
	if (HERO_CLASSES.empty()) {
		HeroClass c;
		c.name = msg->get("Adventurer");
		HERO_CLASSES.push_back(c);
	}
}
示例#23
0
	T& last () { return vector.back (); }
示例#24
0
const IntPair& getKey( const uint64_t& i )
{
	intPairs.push_back( std::make_pair( static_cast<uint32_t>(i / 3), static_cast<uint32_t>(3 - (i % 3)) ) );
	return intPairs.back();
}
示例#25
0
bool TreeSocket::PreProcessOldProtocolMessage(User*& who, std::string& cmd, std::vector<std::string>& params)
{
	if ((cmd == "METADATA") && (params.size() >= 3) && (params[0][0] == '#'))
	{
		// :20D METADATA #channel extname :extdata
		return InsertCurrentChannelTS(params);
	}
	else if ((cmd == "FTOPIC") && (params.size() >= 4))
	{
		// :20D FTOPIC #channel 100 Attila :topic text
		return InsertCurrentChannelTS(params);
	}
	else if ((cmd == "PING") || (cmd == "PONG"))
	{
		if (params.size() == 1)
		{
			// If it's a PING with 1 parameter, reply with a PONG now, if it's a PONG with 1 parameter (weird), do nothing
			if (cmd[1] == 'I')
				this->WriteData(":" + ServerInstance->Config->GetSID() + " PONG " + params[0] + newline);

			// Don't process this message further
			return false;
		}

		// :20D PING 20D 22D
		// :20D PONG 20D 22D
		// Drop the first parameter
		params.erase(params.begin());

		// If the target is a server name, translate it to a SID
		if (!InspIRCd::IsSID(params[0]))
		{
			TreeServer* server = Utils->FindServer(params[0]);
			if (!server)
			{
				// We've no idea what this is, log and stop processing
				ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Received a " + cmd + " with an unknown target: \"" + params[0] + "\", command dropped");
				return false;
			}

			params[0] = server->GetID();
		}
	}
	else if ((cmd == "GLINE") || (cmd == "KLINE") || (cmd == "ELINE") || (cmd == "ZLINE") || (cmd == "QLINE"))
	{
		// Fix undocumented protocol usage: translate GLINE, ZLINE, etc. into ADDLINE or DELLINE
		if ((params.size() != 1) && (params.size() != 3))
			return false;

		parameterlist p;
		p.push_back(cmd.substr(0, 1));
		p.push_back(params[0]);

		if (params.size() == 3)
		{
			cmd = "ADDLINE";
			p.push_back(who->nick);
			p.push_back(ConvToStr(ServerInstance->Time()));
			p.push_back(ConvToStr(InspIRCd::Duration(params[1])));
			p.push_back(params[2]);
		}
		else
			cmd = "DELLINE";

		params.swap(p);
	}
	else if (cmd == "SVSMODE")
	{
		cmd = "MODE";
	}
	else if (cmd == "OPERQUIT")
	{
		// Translate OPERQUIT into METADATA
		if (params.empty())
			return false;

		cmd = "METADATA";
		params.insert(params.begin(), who->uuid);
		params.insert(params.begin()+1, "operquit");
		who = MyRoot->ServerUser;
	}
	else if ((cmd == "TOPIC") && (params.size() >= 2))
	{
		// :20DAAAAAC TOPIC #chan :new topic
		cmd = "FTOPIC";
		if (!InsertCurrentChannelTS(params))
			return false;

		params.insert(params.begin()+2, ConvToStr(ServerInstance->Time()));
	}
	else if (cmd == "MODENOTICE")
	{
		// MODENOTICE is always supported by 2.0 but it's optional in 2.2.
		params.insert(params.begin(), "*");
		params.insert(params.begin()+1, cmd);
		cmd = "ENCAP";
	}
	else if (cmd == "RULES")
	{
		return false;
	}
	else if (cmd == "INVITE")
	{
		// :20D INVITE 22DAAABBB #chan
		// :20D INVITE 22DAAABBB #chan 123456789
		// Insert channel timestamp after the channel name; the 3rd parameter, if there, is the invite expiration time
		return InsertCurrentChannelTS(params, 1, 2);
	}
	else if (cmd == "VERSION")
	{
		// :20D VERSION :InspIRCd-2.0
		// change to
		// :20D SINFO version :InspIRCd-2.0
		cmd = "SINFO";
		params.insert(params.begin(), "version");
	}
	else if (cmd == "JOIN")
	{
		// 2.0 allows and forwards legacy JOINs but we don't, so translate them to FJOINs before processing
		if ((params.size() != 1) || (IS_SERVER(who)))
			return false; // Huh?

		cmd = "FJOIN";
		Channel* chan = ServerInstance->FindChan(params[0]);
		params.push_back(ConvToStr(chan ? chan->age : ServerInstance->Time()));
		params.push_back("+");
		params.push_back(",");
		params.back().append(who->uuid);
		who = TreeServer::Get(who)->ServerUser;
	}
	else if ((cmd == "FMODE") && (params.size() >= 2))
	{
		// Translate user mode changes with timestamp to MODE
		if (params[0][0] != '#')
		{
			User* user = ServerInstance->FindUUID(params[0]);
			if (!user)
				return false;

			// Emulate the old nonsensical behavior
			if (user->age < ServerCommand::ExtractTS(params[1]))
				return false;

			cmd = "MODE";
			params.erase(params.begin()+1);
		}
	}
	else if ((cmd == "SERVER") && (params.size() > 4))
	{
		// This does not affect the initial SERVER line as it is sent before the link state is CONNECTED
		// :20D SERVER <name> * 0 <sid> <desc>
		// change to
		// :20D SERVER <name> <sid> <desc>

		params[1].swap(params[3]);
		params.erase(params.begin()+2, params.begin()+4);

		// If the source of this SERVER message is not bursting, then new servers it introduces are bursting
		TreeServer* server = TreeServer::Get(who);
		if (!server->IsBursting())
			params.insert(params.begin()+2, "burst=" + ConvToStr(ServerInstance->Time()*1000));
	}
	else if (cmd == "BURST")
	{
		// A server is introducing another one, drop unnecessary BURST
		return false;
	}

	return true; // Passthru
}
示例#26
0
	void ParsingFace(MPMesh* pMesh, MPMesh::FaceHandle faceHandle, const TestTree* pTree,
        Relation testRelation, MPMesh** meshList, std::vector<TMP_VInfo>& points, Octree<>* pOctree, GS::BaseMesh* pResult, GS::float4* color)
	{
        if (testRelation == REL_INSIDE) return;

		// 树不为空,存在一个on的节点
		ISectTriangle* triangle = pMesh->property(pMesh->SurfacePropHandle, faceHandle);
		assert(triangle);
        triangle->relationTestId.clear();
		for (auto &itr: *pTree)
            GetLeafList(itr.testTree, triangle->relationTestId);

		// 取得有效的相交网格列表
		std::sort(triangle->relationTestId.begin(), triangle->relationTestId.end());

		// 记录二次相交点
		std::map<ISCutSegItr, std::list<ISVertexItr>> crossRecord;
		unsigned n_test = triangle->relationTestId.size();
		Vec3d crossPoint;
		for (unsigned i = 0; i < n_test; i++)
		{
			auto &res1 = triangle->segs.find(triangle->relationTestId[i]);
            if (res1 == triangle->segs.end()) continue;
            auto &segs1 = res1->second;

			for (unsigned j = i+1; j < n_test; j++)
			{
				auto &res2 = triangle->segs.find(triangle->relationTestId[j]);
                if (res2 == triangle->segs.end()) continue;
                auto &segs2 = res2->second;

				for (auto segItr1 = segs1.segs.begin(); segItr1 != segs1.segs.end(); segItr1++)
				{
					for (auto segItr2 = segs2.segs.begin(); segItr2 != segs2.segs.end(); segItr2++)
					{
						if (SegIsectTest2D(*segItr1, *segItr2, points, crossPoint))
						{
							auto vItr = InsertPoint(triangle, INNER, crossPoint);
							vItr->Id = points.size();
							points.emplace_back();
							points.back().p3 = crossPoint;
							points.back().p2 = Point2(crossPoint[triangle->xi], crossPoint[triangle->yi]);
                            points.back().p2.setCustomIndex(vItr->Id);
							points.back().ptr = vItr;
							crossRecord[segItr2].push_back(vItr);
							crossRecord[segItr1].push_back(vItr);
						}
					}
				}
			}
		}

		// 根据相交测试的结果重新划分折痕
		std::list<ISCutSeg> tmpSegList;
		ISCutSeg tmpSeg;
		for (auto& pair: crossRecord)
		{
            if (pair.second.size() > 1) SortSegPoint(pair, points);
			tmpSeg.start = pair.first->start;
			tmpSeg.end = *pair.second.begin();
			tmpSegList.push_back(tmpSeg);

			std::list<ISVertexItr>::iterator vItr = pair.second.begin(), vItr2 = vItr;
			vItr2++;
			for (; vItr2 != pair.second.end(); vItr++, vItr2++)
			{
				tmpSeg.start = *vItr;
				tmpSeg.end = *vItr2;
				tmpSegList.push_back(tmpSeg);
			}

			tmpSeg.start = *(--pair.second.end());
			tmpSeg.end = pair.first->end;
			tmpSegList.push_back(tmpSeg);

			auto &tmpSegs = triangle->segs[pair.first->oppoTriangle->pMesh->ID];
			tmpSegs.segs.erase(pair.first);
			tmpSegs.segs.insert(tmpSegs.segs.end(), tmpSegList.begin(), tmpSegList.end());
			tmpSegList.clear();
		}

		// 建立约束条件
		std::vector<Segment2> segList;
		Point2 *p0, *p1;
		unsigned testId;
		for (unsigned i = 0; i < n_test; i++)
		{
			testId = triangle->relationTestId[i];
			auto& res1 = triangle->segs.find(testId);
            if (res1 == triangle->segs.end()) continue;
			auto& segs = res1->second;
			for (auto seg = segs.segs.begin(); seg != segs.segs.end(); seg++)
			{
				p0 = &points[seg->start->Id].p2;
				p1 = &points[seg->end->Id].p2;
				segList.emplace_back(*p0, *p1);
			}
		}
	
		Fade_2D*& dt = triangle->dtZone;
        dt = new Fade_2D;
		dt->insert(points[triangle->corner[0]->Id].p2);
		dt->insert(points[triangle->corner[1]->Id].p2);
		dt->insert(points[triangle->corner[2]->Id].p2);

		dt->createConstraint(segList, GEOM_FADE2D::CIS_IGNORE_DELAUNAY);
		dt->applyConstraintsAndZones();

		std::vector<Triangle2*> vAllTriangles;
		dt->getTrianglePointers(vAllTriangles);

		Point2 baryCenter2d;
		CSGTreeNode* curNode;
        Relation curRelation(REL_UNKNOWN), outRelation(REL_UNKNOWN);
        bool pass;

		for (auto triFrag: vAllTriangles)
		{
			baryCenter2d = triFrag->getBarycenter();
			GS::double3 v[3];
			v[0] = Vec3dToDouble3(points[triFrag->getCorner(0)->getCustomIndex()].p3);
			v[1] = Vec3dToDouble3(points[triFrag->getCorner(1)->getCustomIndex()].p3);
			v[2] = Vec3dToDouble3(points[triFrag->getCorner(2)->getCustomIndex()].p3);

			// 去除那些过小的三角形
			GS::double3x3 mat(GS::double3(1,1,1), v[2]-v[1], v[2]-v[0]);
			if (fabs(GS::determinant(mat)) < 1e-9) continue;

            pass = true;
			for (auto &test: *pTree)
			{
                curNode = GetFirstNode(test.testTree);
                while (curNode)
                {
                    curRelation = REL_UNKNOWN;
                    testId = curNode->pMesh->ID;
                    auto cop = triangle->coplanarTris.find(testId);
                    if (cop != triangle->coplanarTris.end())
                    {
						for (auto &coTri: cop->second)
						{
							if (IsInsideTriangle(triangle, meshList[testId], coTri, baryCenter2d, curRelation))
								break;
						}
                    }
                    if (curRelation == REL_UNKNOWN)
                    {
                        if (triangle->segs.find(testId) != triangle->segs.end())
                            curRelation = BSP2DInOutTest(triangle->segs[testId].bsp, &baryCenter2d);
                        else
                        {
                            Vec3d bc((Double3ToVec3d(v[0])+Double3ToVec3d(v[1])+Double3ToVec3d(v[2]))/3.0);
                            curRelation = PolyhedralInclusionTest(bc, pOctree, testId, pOctree->pMesh[testId]->bInverse);
                        }
                    }
                    curNode = GetNextNode(curNode, curRelation, outRelation);
                }
                if (!(test.targetRelation & outRelation))
                {
                    pass = false;
                    break;
                }
            }
            mark += 2;

            if (pass)
            {
#ifdef _DEBUG
				countd2 ++;
#endif
				pResult->AddTriangle(v);
				//pResult->AddTriangle(v, *color);
            }
        }
        SAFE_RELEASE(dt);
	}
示例#27
0
 /**
  * Creates an instruction of the graph.
  * \param in The instruction to be included into the graph.
  * \return The id of the created instruction.
  */
 inline uint createMdfi(Mdfi* in){
     _instructions.emplace_back(*in);
     _instructions.back().setId(_nextId);
     ++_nextId;
     return _instructions.size() - 1;
 }
示例#28
0
 void create_imaging_table_data(const model::metrics::run_metrics& metrics,
                                const std::vector<model::table::imaging_column>& columns,
                                const std::map<model::metric_base::base_metric::id_t, size_t>& row_offset,
                                I data_beg,
                                I data_end)
 {
     typedef typename model::metrics::run_metrics::id_t id_t;
     const size_t column_count = columns.back().column_count();
     const constants::tile_naming_method naming_method = metrics.run_info().flowcell().naming_method();
     const size_t q20_idx = metric::index_for_q_value(metrics.get_set<model::metrics::q_metric>(), 20);
     const size_t q30_idx = metric::index_for_q_value(metrics.get_set<model::metrics::q_metric>(), 30);
     std::vector<size_t> cmap(model::table::ImagingColumnCount, std::numeric_limits<size_t>::max());
     for(size_t i=0;i<columns.size();++i) cmap[columns[i].id()] = columns[i].offset();
     summary::read_cycle_vector_t cycle_to_read;
     summary::map_read_to_cycle_number(metrics.run_info().reads().begin(),
                                       metrics.run_info().reads().end(),
                                       cycle_to_read);
     if(data_beg+column_count*row_offset.size() > data_end)
         INTEROP_THROW(model::index_out_of_bounds_exception, "Table is larger than buffer");
     zero_first_column(data_beg, data_beg+column_count*row_offset.size(), column_count);
     populate_imaging_table_data_by_cycle(metrics.get_set<model::metrics::extraction_metric>(),
                                          q20_idx,
                                          q30_idx,
                                          naming_method,
                                          cycle_to_read,
                                          cmap,
                                          row_offset,
                                          column_count,
                                          data_beg, data_end);
     populate_imaging_table_data_by_cycle(metrics.get_set<model::metrics::error_metric>(),
                                          q20_idx,
                                          q30_idx,
                                          naming_method,
                                          cycle_to_read,
                                          cmap,
                                          row_offset,
                                          column_count,
                                          data_beg, data_end);
     populate_imaging_table_data_by_cycle(metrics.get_set<model::metrics::image_metric>(),
                                          q20_idx,
                                          q30_idx,
                                          naming_method,
                                          cycle_to_read,
                                          cmap,
                                          row_offset,
                                          column_count,
                                          data_beg, data_end);
     populate_imaging_table_data_by_cycle(metrics.get_set<model::metrics::corrected_intensity_metric>(),
                                          q20_idx,
                                          q30_idx,
                                          naming_method,
                                          cycle_to_read,
                                          cmap,
                                          row_offset,
                                          column_count,
                                          data_beg, data_end);
     populate_imaging_table_data_by_cycle(metrics.get_set<model::metrics::q_metric>(),
                                          q20_idx,
                                          q30_idx,
                                          naming_method,
                                          cycle_to_read,
                                          cmap,
                                          row_offset,
                                          column_count,
                                          data_beg, data_end);
     const typename model::metrics::run_metrics::tile_metric_set_t& tile_metrics =
             metrics.get_set<model::metrics::tile_metric>();
     for(typename std::map<id_t, size_t>::const_iterator it = row_offset.begin();it != row_offset.end();++it)
     {
         const id_t tid = model::metric_base::base_cycle_metric::tile_hash_from_id(it->first);
         if (!tile_metrics.has_metric(tid)) continue;
         const size_t cycle = static_cast<size_t>(model::metric_base::base_cycle_metric::cycle_from_id(it->first));
         const size_t row = it->second;
         const summary::read_cycle& read = cycle_to_read[cycle-1];
         table_populator::populate(tile_metrics.get_metric(tid),
                                   read.number,
                                   q20_idx,
                                   q30_idx,
                                   naming_method,
                                   cmap,
                                   data_beg+row*column_count, data_end);
     }
 }
示例#29
0
void ReadInput()
{
    if (!std::cin) return;

    std::string input;
    std::getline(std::cin, input);
    struct json_object *decode = parse_json(input);

    if (decode != NULL)
    {
        std::string cur_decode = std::string(JSON_GET_STR(decode, "i"));
        if (cur_decode != LAST_DECODE) {
            LAST_DECODE = cur_decode;

            const char *ll_str = JSON_GET_STR(decode, "ll");
            if (ll_str != NULL) {
                double x, y;
                sscanf(ll_str, "[ %lf, %lf ]", &y, &x);
                x += 15;

                Click newclick;
                newclick.x[0]   = x;
                newclick.x[1]   = y;
                newclick.alpha  = 1.0;
                newclick.dalpha = 1e-6;
                clicks.push_back(newclick);

                Explosion newexp;
                newexp.x[0]      = x;
                newexp.x[1]      = y;
                newexp.r      = 0.0;
                newexp.dr     = 0.05;
                newexp.alpha  = 0.7;
                newexp.dalpha = 0.01;
                explosions.push_back(newexp);

                std::string cur_kw = JSON_GET_STR(decode, "e");
                if (cur_kw.length() > MIN_KEYWORD_LENGTH || cur_kw.find_first_of(" ") != std::string::npos) {
                    if (keywords.find(cur_kw) != keywords.end()) {
                        double s, c;
                        s = sin(keywords[cur_kw].theta);
                        c = cos(keywords[cur_kw].theta);

                        keywords[cur_kw].count ++;
                        if (keywords[cur_kw].count > MAX_COUNT)
                            MAX_COUNT = keywords[cur_kw].count;
                        keywords[cur_kw].alpha = 1.0;
                        double R = KW_R(keywords[cur_kw].theta);
                        keywords[cur_kw].x[0]     = s * R;
                        keywords[cur_kw].x[1]     = c * R;
                    } else {
                        double s, c;
                        s = sin(KW_THETA);
                        c = cos(KW_THETA);

                        double R = KW_R(KW_THETA);
                        Keyword keywd;
                        keywd.kw     = cur_kw;
                        keywd.theta  = KW_THETA;
                        keywd.x[0]      = s * R;
                        keywd.x[1]      = c * R;
                        keywd.alpha  = 1.0;
                        keywd.dalpha = 1e-3;
                        keywd.count  = 1;
                        keywords[cur_kw] = keywd;

                        KW_THETA += KW_DTHETA;
                    }
                    //keywords[cur_kw].dr = 0.0;

                    Link li;
                    li.click  = &clicks.back();
                    li.kw     = &keywords[cur_kw];
                    li.alpha  = 0.25;
                    li.dalpha = 0.01;
                    links.push_back(li);
                }
            }
        }
        JSON_FREE(decode);
    }
}
示例#30
0
void FidoInterface::getFDR_MSE(const std::vector<double> &estFDR, 
         const std::vector<double> &empFDR,double &mse) {
  /* Estimate MSE mse1 as : 1/N multiply by the SUM from k=1 to N of (estFDR(k) - empFDR(k))^2 */
  
  /* Estimate MSE mse2 area as : sum trapezoid area of each segment  (integral of the absolute value)
   * A_segment(i) = abs(X1-Xo) * abs((y1 + y2 ) / 2)
   * Where yo = estimated FDR at segment i
   * Where y1 = estimated FDR at segment i + 1
   * Where Xo = empirical FDR at segment i
   * Where X1 = empirical FDR at segment i + 1
   * Total Area = Total Area / range of X
   */
  
  /* Estimate MSE mse3 area as : sum trapezoid area with antiderivatives of each segment (absolute value of the integral)
   * A_segment(i) = ((yo - m*Xo)*X1 + m/2 * X1^2) - ((yo - m*Xo)*Xo - m/2 * X2^2))
   * Where yo = estimated FDR at segment i
   * Where y1 = estimated FDR at segment i + 1
   * Where Xo = empirical FDR at segment i
   * Where X2 = empirical FDR at segment i + 1
   * Where m = (y1 - y0) / (X1 - X0)
   * Total Area = abs(Total Area / range of X)
   */
  
   /* Estimate MSE mse4 area as : sum trapezoid squared area with antiderivatives of each segment 
   * A_segment(i) = ((yo - m*Xo)*X1 + m/2 * X1^2) - ((yo - m*Xo)*Xo - m/2 * X2^2))
   * Where yo = estimated FDR at segment i
   * Where y1 = estimated FDR at segment i + 1
   * Where Xo = empirical FDR at segment i
   * Where X2 = empirical FDR at segment i + 1
   * Where m = (y1 - y0) / (X1 - X0)
   * Total Area = Total Area / range of X
   */
  
  if(   (*min_element(estFDR.begin(),estFDR.end()) >= mseThreshold_) 
     || (estFDR.size() != empFDR.size()) 
     || (estFDR.empty() || empFDR.empty())
     || (((*max_element(estFDR.begin(),estFDR.end()) <= 0.0) 
     && (*max_element(empFDR.begin(),empFDR.end()) <= 0.0))) ) {
    //no elements into the confidence interval or vectors empty 
    //or different size or all zeroes 
    //mse = mseThreshold_;
    mse = 1.0;
    //mse1 = mse2 = mse3 = mse4 = 1.0;
    return;
  }
  mse = 0.0;
  //mse1 = mse2 = mse3 = mse4 = 0.0;
  double x1,x2,y1,y2;

  for (unsigned k = 0; k < estFDR.size()-1; k++) {
    if (estFDR[k] <= mseThreshold_ && empFDR[k] <= mseThreshold_) {
      //empFDR and estFDR below threshold, y2,x2 are the diff of them
      x1 = estFDR[k];
      x2 = estFDR[k+1];
      y1 = x1 - empFDR[k];
      y2 = x2 - empFDR[k+1];
    } else if (estFDR[k] <= mseThreshold_) {
      //empFDR is above mseThreshold_, penalize the area positive
      x1 = estFDR[k];
      x2 = estFDR[k+1];
      y1 = x1;
      y2 = x2;
    } else {
      if (kUpdateRocN) {
        rocN_ = std::max(rocN_, (unsigned)std::max(50,std::min((int)k,500)));
      }
      break;
    }
    
    if ( x1 != x2 && x2 != 0 && y2 != 0 ) { //if there is an area
      x2 = min(x2,mseThreshold_); //in case x2 is above mseThreshold_
      //mse2 += trapezoid_area(x1,x2,y1,y2);
      //mse3 += abs(area(x1, y1, x2, y2));
      mse += areaSq(x1, y1, x2, y2);
    }
    
    //mse1 += pow(y1,2);
  }

  //mse1 += pow(y2,2); //last element of diff between vectors
  
  double normalizer1 = abs(std::min(estFDR.back(),mseThreshold_) - estFDR.front()); //normalize by x axis range (mseThreshold_ on top always)
  //double normalizer2 = (double)estFDR.size(); //normalize by the number of elements
  //std::cerr << estFDR[estFDR.size() - 2] << " " << estFDR.back() << std::endl;
  //std::cerr << empFDR[empFDR.size() - 2] << " " << empFDR.back() << std::endl;
  //mse1 /= normalizer2;
  //mse2 /= normalizer1;
  //mse3 /= normalizer1;
  mse /= (normalizer1*normalizer1*normalizer1)/3;
  return;
}