//----------------------------------------------------------------------------- // Name: // Desc: //----------------------------------------------------------------------------- void C3DBody::GetMatrix( D3DXMATRIX &mOut ) { mOut = FinalState().m_mOrientation; InitialState().m_mOrientation.m[3][0] = InitialState().m_mOrientation.m[3][1] = InitialState().m_mOrientation.m[3][2] = 0.0f; mOut.m[3][0] = FinalState().m_vPosition.x; mOut.m[3][1] = FinalState().m_vPosition.y; mOut.m[3][2] = FinalState().m_vPosition.z; mOut.m[3][3] = 1.0f; }
//----------------------------------------------------------------------------- // Name: // Desc: //----------------------------------------------------------------------------- void C3DBody::SetMatrix( const D3DXMATRIX &mInitial ) { Reset( InitialState() ); InitialState().m_mOrientation = mInitial; InitialState().m_mOrientation.m[3][0] = InitialState().m_mOrientation.m[3][1] = InitialState().m_mOrientation.m[3][2] = 0.0f; InitialState().m_vPosition.x = mInitial.m[3][0]; InitialState().m_vPosition.y = mInitial.m[3][1]; InitialState().m_vPosition.z = mInitial.m[3][2]; }
//----------------------------------------------------------------------------- // Name: // Desc: //----------------------------------------------------------------------------- void C3DBody::Integrate( float fDeltaT ) { // // integrate primary variables // // translation FinalState().m_vPosition = InitialState().m_vPosition + fDeltaT * InitialState().m_vVelocity; // rotation D3DXMATRIX mAngularVelocity; // convert angular velocity vector to a skew-symmetric matrix // then matrix-multiply this to perform the cross-product // to get the change in the orientation matrix D3DXMatrixSkewSymmetric( &mAngularVelocity, &InitialState().m_vAngularVelocity ); FinalState().m_mOrientation = InitialState().m_mOrientation + ( fDeltaT * mAngularVelocity ) * InitialState().m_mOrientation; // linear velocity FinalState().m_vVelocity = InitialState().m_vVelocity + ( fDeltaT * m_fMassInverse ) * InitialState().m_vForce; // angular momentum FinalState().m_vAngularMomentum = InitialState().m_vAngularMomentum + fDeltaT * InitialState().m_vTorque; D3DXMatrixOrthonormalize( &FinalState().m_mOrientation, &FinalState().m_mOrientation ); // // calculate auxiliary values // D3DXMATRIX mOrientationTranspose; D3DXMatrixTranspose( &mOrientationTranspose, &FinalState().m_mOrientation ); FinalState().m_mInertiaTensorInverseWorld = FinalState().m_mOrientation * m_mInertiaTensorInverse * mOrientationTranspose; D3DXVec3TransformNormal( &FinalState().m_vAngularVelocity, &FinalState().m_vAngularMomentum, &FinalState().m_mInertiaTensorInverseWorld ); }
//----------------------------------------------------------------------------- // Name: // Desc: //----------------------------------------------------------------------------- C3DBody::C3DBody() : m_bGravity( true ), m_bDamping( true ), m_bHanging( true ), m_fKDampingLinear( 0.04f ), m_fKDampingAngular( 0.008f ), m_fMinKDampingLinear( 0.002f ), m_fMinKDampingAngular( 0.002f ), m_fMassInverse( 1.0f ), m_fMass( 1.0f ), m_fDensity( 0.4f ), m_eShapeType( BOX ), m_pInitialState( &m_States[0] ), m_pFinalState( &m_States[1] ) { Reset( InitialState() ); Reset( FinalState() ); m_vGravity = D3DXVECTOR3( 0.0f, 0.0f, -9.8f ); // D3DXVECTOR3( 0.0f, -9.8f, 0.0f ); // assume it's a box m_eShapeType = BOX; float dx = 0.4f; float dy = 0.4f; float dz = 0.8f; m_fMass = m_fDensity * dx * dy * dz; _ASSERT( m_fMass > 0.0f ); m_fMassInverse = 1.0f / m_fMass; float dx2 = 0.5f * dx; float dy2 = 0.5f * dy; float dz2 = 0.5f * dz; D3DXMatrixIdentity( &m_mInertiaTensorInverse ); m_mInertiaTensorInverse.m[0][0] = 3.0f / ( m_fMass * (dy2*dy2 + dz2*dz2) ); m_mInertiaTensorInverse.m[1][1] = 3.0f / ( m_fMass * (dx2*dx2 + dz2*dz2) ); m_mInertiaTensorInverse.m[2][2] = 3.0f / ( m_fMass * (dx2*dx2 + dy2*dy2) ); // CM -> hanger m_vHangerPos = D3DXVECTOR3( 0.0f, 0.0f, 0.4f ); }
//----------------------------------------------------------------------------- // Name: // Desc: //----------------------------------------------------------------------------- void C3DBody::SumForces() { // clear forces InitialState().m_vTorque = D3DXVECTOR3(0.0f, 0.0f, 0.0f); InitialState().m_vForce = D3DXVECTOR3(0.0f, 0.0f, 0.0f); // test code #define INITIAL_ROTATION 0 #if INITIAL_ROTATION static bool bInitial = true; if( bInitial ) { srand( (unsigned)time( NULL ) ); D3DXVECTOR3 vDir = D3DXVECTOR3( 2.0f * rand() / RAND_MAX - 1.0f, 2.0f * rand() / RAND_MAX - 1.0f, -1.0f * rand() / RAND_MAX ); D3DXVec3Normalize( &vDir, &vDir ); InitialState().m_vAngularMomentum = vDir * 0.02f; bInitial = false; } #endif #define INITIAL_ORIENTATION 1 #if INITIAL_ORIENTATION static bool bInitialO = true; if( bInitialO ) { srand( (unsigned)time( NULL ) ); D3DXVECTOR3 vAxis = D3DXVECTOR3( 2.0f * rand() / RAND_MAX - 1.0f, 2.0f * rand() / RAND_MAX - 1.0f, -1.0f * rand() / RAND_MAX ); D3DXVec3Normalize( &vAxis, &vAxis ); float fAngle = 3.14159f/4.0f; D3DXMATRIX mRot; D3DXMatrixRotationAxis( &mRot, &vAxis, fAngle ); InitialState().m_mOrientation *= mRot; bInitialO = false; } #endif if( m_bGravity ) { if( m_bHanging ) { // rotate hanger vector into world space D3DXVECTOR3 vHangerWorldVector; D3DXVec3TransformNormal( &vHangerWorldVector, &m_vHangerPos, &InitialState().m_mOrientation ); // torque = MgR D3DXVECTOR3 vTorqueGravity; D3DXVec3Cross( &vTorqueGravity, &m_vGravity, &vHangerWorldVector ); InitialState().m_vTorque += m_fMass * vTorqueGravity; } else //not hanging { InitialState().m_vForce += m_vGravity / m_fMassInverse; } } if( m_bDamping ) { InitialState().m_vForce += -m_fKDampingLinear * InitialState().m_vVelocity; InitialState().m_vTorque += -m_fKDampingAngular * InitialState().m_vAngularVelocity; } else // use minimum damping values { InitialState().m_vForce += -m_fMinKDampingLinear * InitialState().m_vVelocity; InitialState().m_vTorque += -m_fMinKDampingAngular * InitialState().m_vAngularVelocity; } }
int main(int argc,char **argv) { PetscErrorCode ierr; PatternCtx user; TS ts; Vec x; DMDALocalInfo info; double noiselevel = -1.0; // negative value means no initial noise PetscInitialize(&argc,&argv,(char*)0,help); // parameter values from pages 21-22 in Hundsdorfer & Verwer (2003) user.L = 2.5; user.Du = 8.0e-5; user.Dv = 4.0e-5; user.phi = 0.024; user.kappa = 0.06; ierr = PetscOptionsBegin(PETSC_COMM_WORLD, "ptn_", "options for patterns", ""); CHKERRQ(ierr); ierr = PetscOptionsReal("-noisy_init", "initialize u,v with this much random noise (e.g. 0.2) on top of usual initial values", "pattern.c",noiselevel,&noiselevel,NULL);CHKERRQ(ierr); ierr = PetscOptionsReal("-L","square domain side length; recommend L >= 0.5", "pattern.c",user.L,&user.L,NULL);CHKERRQ(ierr); ierr = PetscOptionsReal("-Du","diffusion coefficient of first equation", "pattern.c",user.Du,&user.Du,NULL);CHKERRQ(ierr); ierr = PetscOptionsReal("-Dv","diffusion coefficient of second equation", "pattern.c",user.Dv,&user.Dv,NULL);CHKERRQ(ierr); ierr = PetscOptionsReal("-phi","dimensionless feed rate (=F in (Pearson, 1993))", "pattern.c",user.phi,&user.phi,NULL);CHKERRQ(ierr); ierr = PetscOptionsReal("-kappa","dimensionless rate constant (=k in (Pearson, 1993))", "pattern.c",user.kappa,&user.kappa,NULL);CHKERRQ(ierr); ierr = PetscOptionsEnd(); CHKERRQ(ierr); //DMDACREATE ierr = DMDACreate2d(PETSC_COMM_WORLD, DM_BOUNDARY_PERIODIC, DM_BOUNDARY_PERIODIC, DMDA_STENCIL_BOX, // for 9-point stencil 4,4,PETSC_DECIDE,PETSC_DECIDE, 2, 1, // degrees of freedom, stencil width NULL,NULL,&user.da); CHKERRQ(ierr); //ENDDMDACREATE ierr = DMSetFromOptions(user.da); CHKERRQ(ierr); ierr = DMSetUp(user.da); CHKERRQ(ierr); ierr = DMDASetFieldName(user.da,0,"u"); CHKERRQ(ierr); ierr = DMDASetFieldName(user.da,1,"v"); CHKERRQ(ierr); ierr = DMDAGetLocalInfo(user.da,&info); CHKERRQ(ierr); if (info.mx != info.my) { SETERRQ(PETSC_COMM_WORLD,1,"pattern.c requires mx == my"); } ierr = DMDASetUniformCoordinates(user.da, 0.0, user.L, 0.0, user.L, -1.0, -1.0); CHKERRQ(ierr); ierr = DMSetApplicationContext(user.da,&user); CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD, "running on %d x %d grid with square cells of side h = %.6f ...\n", info.mx,info.my,user.L/(double)(info.mx)); CHKERRQ(ierr); //TSSETUP ierr = TSCreate(PETSC_COMM_WORLD,&ts); CHKERRQ(ierr); ierr = TSSetProblemType(ts,TS_NONLINEAR); CHKERRQ(ierr); ierr = TSSetDM(ts,user.da); CHKERRQ(ierr); ierr = DMDATSSetRHSFunctionLocal(user.da,INSERT_VALUES, (DMDATSRHSFunctionLocal)FormRHSFunctionLocal,&user); CHKERRQ(ierr); ierr = DMDATSSetIFunctionLocal(user.da,INSERT_VALUES, (DMDATSIFunctionLocal)FormIFunctionLocal,&user); CHKERRQ(ierr); ierr = DMDATSSetIJacobianLocal(user.da, (DMDATSIJacobianLocal)FormIJacobianLocal,&user); CHKERRQ(ierr); ierr = TSSetType(ts,TSARKIMEX); CHKERRQ(ierr); ierr = TSSetExactFinalTime(ts,TS_EXACTFINALTIME_MATCHSTEP); CHKERRQ(ierr); ierr = TSSetInitialTimeStep(ts,0.0,5.0); CHKERRQ(ierr); // t_0 = 0.0, dt = 5.0 ierr = TSSetDuration(ts,1000000,200.0); CHKERRQ(ierr); // t_f = 200 ierr = TSSetFromOptions(ts);CHKERRQ(ierr); //ENDTSSETUP ierr = DMCreateGlobalVector(user.da,&x); CHKERRQ(ierr); ierr = InitialState(x,noiselevel,&user); CHKERRQ(ierr); ierr = TSSolve(ts,x); CHKERRQ(ierr); VecDestroy(&x); TSDestroy(&ts); DMDestroy(&user.da); PetscFinalize(); return 0; }
int main(int argc,char **argv) { PetscErrorCode ierr; DM da; /* structured grid topology object */ TS ts; /* time-stepping object (contains snes) */ SNES snes; /* Newton solver object */ Vec X,residual; /* solution, residual */ Mat J; /* Jacobian matrix */ PetscInt Mx,My,fsteps,steps; ISColoring iscoloring; PetscReal tstart,tend,ftime,secperday=3600.0*24.0,Y0; PetscBool fdflg = PETSC_FALSE, mfileflg = PETSC_FALSE, optflg = PETSC_FALSE; char mfile[PETSC_MAX_PATH_LEN] = "out.m"; MatFDColoring matfdcoloring; PorousCtx user; /* user-defined work context */ PetscInitialize(&argc,&argv,(char *)0,help); ierr = DMDACreate2d(PETSC_COMM_WORLD, DMDA_BOUNDARY_NONE, DMDA_BOUNDARY_NONE, // correct for zero Dirichlet DMDA_STENCIL_STAR, // nonlinear diffusion but diffusivity // depends on soln W not grad W -21,-21, // default to 20x20 grid but override with // -da_grid_x, -da_grid_y (or -da_refine) PETSC_DECIDE,PETSC_DECIDE, // num of procs in each dim 2, // dof = 2: node = (W,Y) // or node = (P,dPsqr) // or node = (ddxE,ddyN) 1, // s = 1 (stencil extends out one cell) PETSC_NULL,PETSC_NULL, // no specify proc decomposition &da);CHKERRQ(ierr); ierr = DMSetApplicationContext(da,&user);CHKERRQ(ierr); /* get Vecs and Mats for this grid */ ierr = DMCreateGlobalVector(da,&X);CHKERRQ(ierr); ierr = VecDuplicate(X,&residual);CHKERRQ(ierr); ierr = VecDuplicate(X,&user.geom);CHKERRQ(ierr); ierr = DMGetMatrix(da,MATAIJ,&J);CHKERRQ(ierr); /* set up contexts */ tstart = 10.0 * secperday; /* 10 days in seconds */ tend = 30.0 * secperday; steps = 20; Y0 = 1.0; /* initial value of Y, for computing initial value of P; note Ymin = 0.1 is different */ user.da = da; ierr = DefaultContext(&user);CHKERRQ(ierr); ierr = PetscOptionsBegin(PETSC_COMM_WORLD, "","options to (W,P)-space better hydrology model alt","");CHKERRQ(ierr); { ierr = PetscOptionsReal("-alt_sigma","nonlinear power","", user.sigma,&user.sigma,PETSC_NULL);CHKERRQ(ierr); ierr = PetscOptionsReal("-alt_Ymin", "min capacity thickness (esp. in pressure computation)","", user.Ymin,&user.Ymin,PETSC_NULL);CHKERRQ(ierr); ierr = PetscOptionsReal("-alt_Wmin", "min water amount (esp. in pressure computation)","", user.Wmin,&user.Wmin,PETSC_NULL);CHKERRQ(ierr); ierr = PetscOptionsReal("-alt_Y0", "constant initial capacity thickness","", Y0,&Y0,PETSC_NULL);CHKERRQ(ierr); ierr = PetscOptionsReal("-alt_Cmelt", "additional coefficient for amount of melt","", user.Cmelt,&user.Cmelt,PETSC_NULL);CHKERRQ(ierr); ierr = PetscOptionsReal("-alt_Creep", "creep closure coefficient","", user.Creep,&user.Creep,PETSC_NULL);CHKERRQ(ierr); ierr = PetscOptionsReal("-alt_L","half-width of square region in meters","", user.L,&user.L,PETSC_NULL);CHKERRQ(ierr); ierr = PetscOptionsReal("-alt_tstart_days","start time in days","", tstart/secperday,&tstart,&optflg);CHKERRQ(ierr); if (optflg) { tstart *= secperday; } ierr = PetscOptionsReal("-alt_tend_days","end time in days","", tend/secperday,&tend,&optflg);CHKERRQ(ierr); if (optflg) { tend *= secperday; } ierr = PetscOptionsInt("-alt_steps","number of timesteps to take","", steps,&steps,PETSC_NULL);CHKERRQ(ierr); ierr = PetscOptionsBool("-alt_converge_check", "run silent and check for convergence", "",user.run_silent,&user.run_silent,PETSC_NULL); CHKERRQ(ierr); ierr = PetscOptionsString("-mfile", "name of Matlab file to write results","", mfile,mfile,PETSC_MAX_PATH_LEN,&mfileflg); CHKERRQ(ierr); } ierr = PetscOptionsEnd();CHKERRQ(ierr); /* fix remaining parameters */ ierr = DerivedConstants(&user);CHKERRQ(ierr); ierr = VecStrideSet(user.geom,0,user.H0);CHKERRQ(ierr); /* H(x,y) = H0 */ ierr = VecStrideSet(user.geom,1,0.0);CHKERRQ(ierr); /* b(x,y) = 0 */ ierr = DMDASetUniformCoordinates(da, // square domain -user.L, user.L, -user.L, user.L, 0.0, 1.0);CHKERRQ(ierr); ierr = DMDAGetInfo(da,PETSC_IGNORE,&Mx,&My, PETSC_IGNORE,PETSC_IGNORE,PETSC_IGNORE, PETSC_IGNORE,PETSC_IGNORE,PETSC_IGNORE,PETSC_IGNORE, PETSC_IGNORE,PETSC_IGNORE,PETSC_IGNORE);CHKERRQ(ierr); user.dx = 2.0 * user.L / (Mx-1); user.dy = 2.0 * user.L / (My-1); /* setup TS = timestepping object */ ierr = TSCreate(PETSC_COMM_WORLD,&ts);CHKERRQ(ierr); ierr = TSSetType(ts,TSCN);CHKERRQ(ierr); ierr = TSSetRHSFunction(ts,residual,RHSFunction,&user);CHKERRQ(ierr); /* use coloring to compute rhs Jacobian efficiently */ ierr = PetscOptionsGetBool(PETSC_NULL,"-fd",&fdflg,PETSC_NULL);CHKERRQ(ierr); if (fdflg){ ierr = DMGetColoring(da,IS_COLORING_GLOBAL,MATAIJ,&iscoloring);CHKERRQ(ierr); ierr = MatFDColoringCreate(J,iscoloring,&matfdcoloring);CHKERRQ(ierr); ierr = MatFDColoringSetFromOptions(matfdcoloring);CHKERRQ(ierr); ierr = ISColoringDestroy(&iscoloring);CHKERRQ(ierr); ierr = MatFDColoringSetFunction(matfdcoloring, (PetscErrorCode (*)(void))RHSFunction,&user);CHKERRQ(ierr); ierr = TSSetRHSJacobian(ts,J,J,TSDefaultComputeJacobianColor, matfdcoloring);CHKERRQ(ierr); } else { /* default case */ ierr = TSSetRHSJacobian(ts,J,J,RHSJacobian,&user);CHKERRQ(ierr); } /* set initial state: W = barenblatt, P = pi (W/Y0)^sigma */ ierr = InitialState(da,&user,tstart,Y0,X);CHKERRQ(ierr); /* set up times for time-stepping */ ierr = TSSetInitialTimeStep(ts,tstart, (tend - tstart) / (PetscReal)steps);CHKERRQ(ierr); ierr = TSSetDuration(ts,steps,tend);CHKERRQ(ierr); ierr = TSSetExactFinalTime(ts,PETSC_TRUE);CHKERRQ(ierr); ierr = TSMonitorSet(ts,MyTSMonitor,&user,PETSC_NULL);CHKERRQ(ierr); /* Set SNESVI type and supply upper and lower bounds. */ ierr = TSGetSNES(ts,&snes);CHKERRQ(ierr); ierr = SNESVISetComputeVariableBounds(snes,FormPositivityBounds); CHKERRQ(ierr); /* ask user to finalize settings */ ierr = TSSetFromOptions(ts);CHKERRQ(ierr); /* report on setup */ if (!user.run_silent) { ierr = PetscPrintf(PETSC_COMM_WORLD, "setup done: square side length = %.3f km\n" " grid Mx,My = %d,%d\n" " spacing dx,dy = %.3f,%.3f m\n" " times tstart:dt:tend = %.3f:%.3f:%.3f days\n", 2.0 * user.L / 1000.0, Mx, My, user.dx, user.dy, tstart / secperday, (tend-tstart)/(steps*secperday), tend / secperday); CHKERRQ(ierr); } if (mfileflg) { if (!user.run_silent) { ierr = PetscPrintf(PETSC_COMM_WORLD, "writing initial W,P and geometry H,b to Matlab file %s ...\n", mfile);CHKERRQ(ierr); } ierr = print2vecmatlab(da,X,"W_init","P_init",mfile,PETSC_FALSE);CHKERRQ(ierr); ierr = print2vecmatlab(da,user.geom,"H","b",mfile,PETSC_TRUE);CHKERRQ(ierr); } /* run time-stepping with implicit steps */ ierr = TSSolve(ts,X,&ftime);CHKERRQ(ierr); /* make a report on run and final state */ ierr = TSGetTimeStepNumber(ts,&fsteps);CHKERRQ(ierr); if ((!user.run_silent) && (ftime != tend)) { ierr = PetscPrintf(PETSC_COMM_WORLD, "***WARNING3***: reported final time wrong: ftime(=%.12e) != tend(=%.12e) (days)\n", ftime / secperday, tend / secperday);CHKERRQ(ierr); } if ((!user.run_silent) && (fsteps != steps)) { ierr = PetscPrintf(PETSC_COMM_WORLD, "***WARNING4***: reported number of steps wrong: fsteps(=%D) != steps(=%D)\n", fsteps, steps);CHKERRQ(ierr); } if (mfileflg) { if (!user.run_silent) { ierr = PetscPrintf(PETSC_COMM_WORLD, "writing final fields to %s ...\n",mfile);CHKERRQ(ierr); } ierr = print2vecmatlab(da,X,"W_final","P_final",mfile,PETSC_TRUE);CHKERRQ(ierr); ierr = printfigurematlab(da,2,"W_init","W_final",mfile,PETSC_TRUE);CHKERRQ(ierr); ierr = printfigurematlab(da,3,"P_init","P_final",mfile,PETSC_TRUE);CHKERRQ(ierr); } if (user.run_silent) { ierr = PetscPrintf(PETSC_COMM_WORLD, "%6d %6d %9.3f %.12e\n", Mx, My, (tend-tstart)/secperday, user.maxrnorm);CHKERRQ(ierr); } /* Free work space. */ ierr = MatDestroy(&J);CHKERRQ(ierr); if (fdflg) { ierr = MatFDColoringDestroy(&matfdcoloring);CHKERRQ(ierr); } ierr = VecDestroy(&X);CHKERRQ(ierr); ierr = VecDestroy(&user.geom);CHKERRQ(ierr); ierr = VecDestroy(&residual);CHKERRQ(ierr); ierr = TSDestroy(&ts);CHKERRQ(ierr); ierr = DMDestroy(&da);CHKERRQ(ierr); ierr = PetscFinalize();CHKERRQ(ierr); PetscFunctionReturn((PetscInt)(user.not_converged_warning)); }
AudacityProject::AudacityProject(wxWindow * parent, wxWindowID id, const wxPoint & pos, const wxSize & size): wxFrame(parent, id, "Audacity", pos, size), mRate((double) gPrefs->Read("/SamplingRate/DefaultProjectSampleRate", 44100)), mDirty(false), mAPalette(NULL), mDrag(NULL), mTrackPanel(NULL), mHistoryWindow(NULL), mAutoScrolling(false) { // // Create track list // mTracks = new TrackList(); mLastSavedTracks = NULL; // // Initialize view info (shared with TrackPanel) // // Selection mViewInfo.sel0 = 0.0; mViewInfo.sel1 = 0.0; // Horizontal scrollbar mViewInfo.total = 1.0; mViewInfo.screen = 1.0; mViewInfo.h = 0.0; mViewInfo.zoom = 44100.0 / 512.0; mViewInfo.lastZoom = mViewInfo.zoom; // Vertical scrollbar mViewInfo.vpos = 0; mViewInfo.scrollStep = 16; mViewInfo.sbarH = 0; mViewInfo.sbarScreen = 1; mViewInfo.sbarTotal = 1; mMenuBar = NULL; CreateMenuBar(); int left = 0, top = 0, width, height; GetClientSize(&width, &height); // // Create the Palette (if we're not using a windowed palette) // if (!gWindowedPalette) { int h = GetAPaletteHeight(); int ptop = 0; #ifdef __WXMSW__ ptop++; #endif mAPalette = new APalette(this, 0, wxPoint(10, ptop), wxSize(width - 10, h)); top += h + 1 + ptop; height -= h + 1 + ptop; } // // Create the status bar // int sh = GetStatusHeight(); mStatus = new AStatus(this, 0, wxPoint(0, height - sh), wxSize(width, sh), mRate, this); height -= sh; mStatus->SetField(wxString::Format("Welcome to Audacity version %s", AUDACITY_VERSION_STRING), 0); // // Create the TrackPanel and the scrollbars // mTrackPanel = new TrackPanel(this, TrackPanelID, wxPoint(left, top), wxSize(width - sbarSpaceWidth, height - sbarSpaceWidth), mTracks, &mViewInfo, this); int hoffset = mTrackPanel->GetLeftOffset() - 1; int voffset = mTrackPanel->GetRulerHeight(); #ifdef __WXMAC__ width++; height++; #endif mHsbar = new wxScrollBar(this, HSBarID, wxPoint(hoffset, top + height - sbarSpaceWidth), wxSize(width - hoffset - sbarSpaceWidth + sbarExtraLen, sbarControlWidth), wxSB_HORIZONTAL); mVsbar = new wxScrollBar(this, VSBarID, wxPoint(width - sbarSpaceWidth, top + voffset), wxSize(sbarControlWidth, height - sbarSpaceWidth - voffset + sbarExtraLen), wxSB_VERTICAL); InitialState(); FixScrollbars(); // // Set the Icon // // loads either the XPM or the windows resource, depending on the platform #ifndef __WXMAC__ wxIcon ic(wxICON(AudacityLogo)); SetIcon(ic); #endif // Min size, max size SetSizeHints(250, 200, 20000, 20000); // Create tags object mTags = new Tags(); #ifdef __WXMSW__ // Accept drag 'n' drop files DragAcceptFiles(true); #endif gAudacityProjects.Add(this); }
void AudacityProject::OpenFile(wxString fileName) { if (mDirty || !mTracks->IsEmpty()) { AudacityProject *project = CreateNewAudacityProject(gParentWindow); project->OpenFile(fileName); } // We want to open projects using wxTextFile, but if it's NOT a project // file (but actually a WAV file, for example), then wxTextFile will spin // for a long time searching for line breaks. So, we look for our // signature at the beginning of the file first: bool isProjectFile; wxString firstLine = "AudacityProject"; char temp[16]; if (!::wxFileExists(fileName)) { wxMessageBox(_("Could not open file: ") + mFileName); return; } // Make sure it isn't already open int numProjects = gAudacityProjects.Count(); for (int i = 0; i < numProjects; i++) if (gAudacityProjects[i]->mFileName == fileName) { wxMessageBox("That project is already open in another window."); return; } wxFile ff(fileName); if (!ff.IsOpened()) { wxMessageBox(_("Could not open file: ") + mFileName); return; } ff.Read(temp, 15); temp[15] = 0; isProjectFile = (firstLine == temp); ff.Close(); if (!isProjectFile) { // Try opening it as any other form of audio Import(fileName); return; } wxTextFile f; f.Open(fileName); if (!f.IsOpened()) { wxMessageBox(_("Could not open file: ") + mFileName); return; } mFileName = fileName; mName = wxFileNameFromPath(mFileName); SetTitle(mName); /// /// Parse project file /// wxString projName; wxString projPath; wxString version; long longVpos; f.GetFirstLine(); // This should say "AudacityProject" if (f.GetNextLine() != "Version") goto openFileError; version = f.GetNextLine(); if (version != AUDACITY_FILE_FORMAT_VERSION) { wxMessageBox(_("This project was saved by a different version of " "Audacity and is no longer supported.")); return; } if (f.GetNextLine() != "projName") goto openFileError; projName = f.GetNextLine(); projPath = wxPathOnly(mFileName); if (!mDirManager.SetProject(projPath, projName, false)) return; if (f.GetNextLine() != "sel0") goto openFileError; if (!(f.GetNextLine().ToDouble(&mViewInfo.sel0))) goto openFileError; if (f.GetNextLine() != "sel1") goto openFileError; if (!(f.GetNextLine().ToDouble(&mViewInfo.sel1))) goto openFileError; if (f.GetNextLine() != "vpos") goto openFileError; if (!(f.GetNextLine().ToLong(&longVpos))) goto openFileError; mViewInfo.vpos = longVpos; if (f.GetNextLine() != "h") goto openFileError; if (!(f.GetNextLine().ToDouble(&mViewInfo.h))) goto openFileError; if (f.GetNextLine() != "zoom") goto openFileError; if (!(f.GetNextLine().ToDouble(&mViewInfo.zoom))) goto openFileError; if (version != "0.9") { if (f.GetNextLine() != "rate") goto openFileError; if (!(f.GetNextLine().ToDouble(&mRate))) goto openFileError; mStatus->SetRate(mRate); } mTracks->Clear(); mTracks->Load(&f, &mDirManager); // By making a duplicate set of pointers to the existing blocks // on disk, we add one to their reference count, guaranteeing // that their reference counts will never reach zero and thus // the version saved on disk will be preserved until the // user selects Save(). if (1) { VTrack *t; TrackListIterator iter(mTracks); mLastSavedTracks = new TrackList(); t = iter.First(); while (t) { mLastSavedTracks->Add(t->Duplicate()); t = iter.Next(); } } f.Close(); InitialState(); FixScrollbars(); mTrackPanel->Refresh(false); return; openFileError: wxMessageBox(wxString:: Format(_("Error reading Audacity Project %s in line %d"), (const char *) mFileName, f.GetCurrentLine())); f.Close(); return; }
// Defined as a leaf class DiameterEapServerStateTable_S() { AddStateTableEntry(StInitialize, DiameterEapServerStateMachine::EvRxDER, StCheckDER, acCheckDER); AddStateTableEntry(StInitialize, DiameterEapServerStateMachine::EvSgDisconnect, StTerminated); AddWildcardStateTableEntry(StInitialize, StTerminated); AddStateTableEntry(StCheckDER, DiameterEapServerStateMachine::EvSgValidDER, StWaitEapMsg, acForwardEapResponse); AddStateTableEntry(StCheckDER, DiameterEapServerStateMachine::EvSgInvalidDER, StRejected, acSendDEA_DueToInvalidDER); AddStateTableEntry(StWaitDER, DiameterEapServerStateMachine::EvRxDER, StCheckDER, acCheckDER); AddStateTableEntry(StWaitDER, DiameterEapServerStateMachine::EvSgDisconnect, StTerminated); AddWildcardStateTableEntry(StWaitDER, StTerminated); AddStateTableEntry(StWaitEapMsg, DiameterEapServerStateMachine::EvRxEapRequest, StWaitDER, acSendDEAwithContinue); AddStateTableEntry(StWaitEapMsg, DiameterEapServerStateMachine::EvRxEapSuccess, StWaitAuthorization, acAuthorize); AddStateTableEntry(StWaitEapMsg, DiameterEapServerStateMachine::EvRxEapFailure, StRejected, acSendDEA_DueToAuthenticationFailure); AddStateTableEntry(StWaitEapMsg, DiameterEapServerStateMachine::EvSgDisconnect, StTerminated); AddWildcardStateTableEntry(StWaitEapMsg, StTerminated); AddStateTableEntry(StWaitAuthorization, DiameterEapServerStateMachine::EvSgAuthorizationSuccess, StAccepted, acSendDEAwithSuccess); AddStateTableEntry(StWaitAuthorization, DiameterEapServerStateMachine::EvSgAuthorizationFailure, StRejected, acSendDEA_DueToAuthorizationFailure); AddStateTableEntry(StWaitAuthorization, DiameterEapServerStateMachine::EvSgDisconnect, StTerminated); AddWildcardStateTableEntry(StWaitAuthorization, StTerminated); // Re-authentication AddStateTableEntry(StAccepted, DiameterEapServerStateMachine::EvRxDER, StCheckDER, acCheckDER); AddStateTableEntry(StAccepted, DiameterEapServerStateMachine::EvSgDisconnect, StTerminated); AddWildcardStateTableEntry(StAccepted, StTerminated); AddWildcardStateTableEntry(StRejected, StRejected); AddWildcardStateTableEntry(StTerminated, StTerminated); InitialState(StInitialize); }
bool FMultiBoxCustomizationData::RemoveUnnecessaryTransactions(const TArray< TSharedRef< const FMultiBlock > >& AllBlocks) { // A local struct describing the state of the menu struct FCustomizationState { FCustomizationState(const TArray< TSharedRef< const FMultiBlock > >& InAllBlocks) { for ( int32 BlockIdx = 0; BlockIdx < InAllBlocks.Num(); ++BlockIdx ) { StateData.Add(InAllBlocks[BlockIdx]->GetAction()); } } // Applies the inverse operation of the given transaction to mutate the state void ApplyInverseOfTransaction(const FCustomBlockTransaction& Trans) { if ( Trans.TransactionType == FCustomBlockTransaction::Add ) { // Remove on an add operation if ( ensure(StateData.IsValidIndex(Trans.BlockIndex)) ) { ensure(StateData[Trans.BlockIndex] == Trans.Command); StateData.RemoveAt(Trans.BlockIndex); } } else if ( Trans.TransactionType == FCustomBlockTransaction::Remove ) { // Add on a remove transaction StateData.Insert(Trans.Command, Trans.BlockIndex); } } // Compares two states. If all elements of the states are the same then they are "equal" bool operator==(const FCustomizationState& Other) const { if ( StateData.Num() != Other.StateData.Num() ) { return false; } const int32 Length = StateData.Num(); for ( int32 StateIdx = 0; StateIdx < Length; ++StateIdx ) { if ( StateData[StateIdx] != Other.StateData[StateIdx] ) { return false; } } return true; } private: TArray<TWeakPtr<const FUICommandInfo>> StateData; }; if( Transactions.Num() > 0 ) { // Take the current state and start applying the inverse of each transaction to it to determine the states before the current. // If we found any state that is identical to the current state, all transactions between that state and the current state are unnecessary, so remove them // Record the initial (current) state and initialize the Test state. FCustomizationState InitialState(AllBlocks); FCustomizationState TestState = InitialState; // Walk backwards through all transactions, applying the inverse of each transaction to the test state for ( int32 TransIdx = Transactions.Num() - 1; TransIdx >= 0; --TransIdx ) { TestState.ApplyInverseOfTransaction(Transactions[TransIdx]); // If the test state is equal to the current state, all transactions between are unnecessary. Remove them. if ( TestState == InitialState ) { for ( int32 RemoveIdx = Transactions.Num() - 1; RemoveIdx >= TransIdx; --RemoveIdx ) { RemoveTransactionAt(RemoveIdx); } // Return true to indicate we actually removed something. return true; } } } // All transactions were necessary to form the final state. Return false. return false; }
AudacityProject::AudacityProject(wxWindow * parent, wxWindowID id, const wxPoint & pos, const wxSize & size):wxFrame(parent, id, "Audacity", pos, size), mRate((double) gPrefs-> Read("/SamplingRate/DefaultProjectSampleRate", 44100)), mDirty(false), mDrag(NULL), mTrackPanel(NULL), mHistoryWindow(NULL), mAutoScrolling(false), mTotalToolBarHeight(0), mDraggingToolBar(NoneID) { // // Create track list // mTracks = new TrackList(); mLastSavedTracks = NULL; // // Initialize view info (shared with TrackPanel) // // Selection mViewInfo.sel0 = 0.0; mViewInfo.sel1 = 0.0; // Horizontal scrollbar mViewInfo.total = 1.0; mViewInfo.screen = 1.0; mViewInfo.h = 0.0; mViewInfo.zoom = 44100.0 / 512.0; mViewInfo.lastZoom = mViewInfo.zoom; // Vertical scrollbar mViewInfo.vpos = 0; mViewInfo.scrollStep = 16; mViewInfo.sbarH = 0; mViewInfo.sbarScreen = 1; mViewInfo.sbarTotal = 1; // Some GUI prefs gPrefs->Read("/GUI/UpdateSpectrogram", &mViewInfo.bUpdateSpectrogram, true); gPrefs->Read("/GUI/AutoScroll", &mViewInfo.bUpdateTrackIndicator, true); // Some extra information mViewInfo.bIsPlaying = false; mViewInfo.bRedrawWaveform = false; mMenuBar = NULL; CreateMenuBar(); int left = 0, top = 0, width, height; GetClientSize(&width, &height); // // Create the Control Toolbar (if we're not using a windowed toolbar) // The control toolbar should be automatically loaded--other toolbars are optional. if (!gControlToolBarStub->GetWindowedStatus()) { int h = gControlToolBarStub->GetHeight(); ToolBar *tb = new ControlToolBar(this, 0, wxPoint(10, top), wxSize(width - 10, h)); mToolBarArray.Add((ToolBar *) tb); top += h + 1; height -= h + 1; mTotalToolBarHeight += h; } if (gEditToolBarStub) { if(gEditToolBarStub->GetLoadedStatus() && !gEditToolBarStub->GetWindowedStatus()) { int h = gEditToolBarStub->GetHeight(); ToolBar *etb = new EditToolBar(this,0 ,wxPoint(10,top), wxSize(width-10,h)); mToolBarArray.Add((ToolBar *) etb); top +=h + 1; height -= h + 1; mTotalToolBarHeight +=h; } } // // Create the status bar // int sh = GetStatusHeight(); mStatus = new AStatus(this, 0, wxPoint(0, height - sh), wxSize(width, sh), mRate, this); height -= sh; mStatus->SetField(wxString::Format("Welcome to Audacity version %s", AUDACITY_VERSION_STRING), 0); // // Create the TrackPanel and the scrollbars // mTrackPanel = new TrackPanel(this, TrackPanelID, wxPoint(left, top), wxSize(width - sbarSpaceWidth, height - sbarSpaceWidth), mTracks, &mViewInfo, this); int hoffset = mTrackPanel->GetLeftOffset() - 1; int voffset = mTrackPanel->GetRulerHeight(); #ifdef __WXMAC__ width++; height++; #endif mHsbar = new wxScrollBar(this, HSBarID, wxPoint(hoffset, top + height - sbarSpaceWidth), wxSize(width - hoffset - sbarSpaceWidth + sbarExtraLen, sbarControlWidth), wxSB_HORIZONTAL); mVsbar = new wxScrollBar(this, VSBarID, wxPoint(width - sbarSpaceWidth, top + voffset), wxSize(sbarControlWidth, height - sbarSpaceWidth - voffset + sbarExtraLen), wxSB_VERTICAL); InitialState(); FixScrollbars(); // // Set the Icon // // loads either the XPM or the windows resource, depending on the platform #ifndef __WXMAC__ wxIcon ic(wxICON(AudacityLogo)); SetIcon(ic); #endif // Min size, max size SetSizeHints(250, 200, 20000, 20000); // Create tags object mTags = new Tags(); #ifdef __WXMSW__ // Accept drag 'n' drop files DragAcceptFiles(true); #endif gAudacityProjects.Add(this); }
// What to do when a view is created. Creates actual // windows for displaying the view. bool AudioView::OnCreate(wxDocument *doc, long WXUNUSED(flags) ) { gNumViewsOpen++; frame = wxGetApp().CreateChildFrame(doc, this, TRUE); // // Create Menu Bar // menuBar = new wxMenuBar(); fileMenu = new wxMenu(); fileMenu->Append(wxID_NEW, "&New...\tCtrl+N"); fileMenu->Append(wxID_OPEN, "&Open...\tCtrl+O"); fileMenu->Append(wxID_CLOSE, "&Close\tCtrl+W"); fileMenu->Append(wxID_SAVE, "&Save\tCtrl+S"); fileMenu->Append(wxID_SAVEAS, "Save As..."); fileMenu->Append(ExportID, "&Export..."); fileMenu->AppendSeparator(); fileMenu->Append(wxID_PRINT, "&Print...\tCtrl+P"); fileMenu->Append(wxID_PRINT_SETUP, "Print Setup..."); fileMenu->Append(wxID_PREVIEW, "Print Preview"); fileMenu->AppendSeparator(); fileMenu->Append(wxID_EXIT, "E&xit"); editMenu = new wxMenu(); editMenu->Append(UndoID, "&Undo\tCtrl+Z"); editMenu->Append(RedoID, "&Redo\tCtrl+R"); editMenu->AppendSeparator(); editMenu->Append(CutID, "Cut\tCtrl+X"); editMenu->Append(CopyID, "Copy\tCtrl+C"); editMenu->Append(PasteID, "Paste\tCtrl+V"); editMenu->Append(ClearID, "Clear\tCtrl+B"); editMenu->AppendSeparator(); editMenu->Append(SelectAllID, "Select All\tCtrl+A"); doc->GetCommandProcessor()->SetEditMenu(editMenu); projectMenu = new wxMenu(); projectMenu->Append(ImportID, "&Import Audio...\tCtrl+I"); projectMenu->Append(ImportRawID, "Import Raw Data..."); projectMenu->Append(ImportMIDIID, "Import &MIDI..."); projectMenu->Append(ImportMP3ID, "Import MP3..."); projectMenu->AppendSeparator(); projectMenu->Append(WaveTrackID, "New Audio Track"); // projectMenu->Append(LabelTrackID, "New Label Track"); projectMenu->AppendSeparator(); projectMenu->Append(RemoveTrackID, "&Remove Track(s)"); trackMenu = new wxMenu(); trackMenu->Append(QuickMixID, "Quick Mix"); trackMenu->AppendSeparator(); trackMenu->Append(WaveDisplayID, "Waveform Display"); trackMenu->Append(SpectrumDisplayID, "Spectrum Display"); trackMenu->AppendSeparator(); // trackMenu->Append(AutoCorrelateID, "AutoCorrelate"); trackMenu->Append(PitchID, "Pitch Extract"); effectMenu = new wxMenu(); numEffects = Effect::GetNumEffects(); for(int fi = 0; fi < numEffects; fi++) effectMenu->Append(FirstEffectID+fi, (Effect::GetEffect(fi))->GetEffectName()); helpMenu = new wxMenu; helpMenu->Append(wxID_ABOUT, "&About Audacity..."); menuBar->Append(fileMenu, "&File"); menuBar->Append(editMenu, "&Edit"); menuBar->Append(projectMenu, "&Project"); menuBar->Append(trackMenu, "&Track"); menuBar->Append(effectMenu, "E&ffect"); menuBar->Append(helpMenu, "&Help"); frame->SetMenuBar(menuBar); // // Make all child windows // int sbarWidth = 15; rulerPanel = new RulerPanel(this, frame, wxDefaultPosition, wxSize(600 - labelWidth, 30), 0); trackPanel = new TrackPanel(this, frame, wxDefaultPosition, wxSize(600, 300), 0); hsbar = new wxScrollBar(frame, HSBarID, wxDefaultPosition, wxSize(600, sbarWidth), wxSB_HORIZONTAL); vsbar = new wxScrollBar(frame, VSBarID, wxDefaultPosition, wxSize(sbarWidth, 300), wxSB_VERTICAL); status = new wxStaticText(frame, 0, "", wxDefaultPosition, wxDefaultSize); status->SetLabel(""); wxButton *b1; wxButton *b2; wxButton *b3; wxButton *b4; wxBitmap *zoomIn = new wxBitmap(); wxBitmap *zoomOut = new wxBitmap(); wxBitmap *play = new wxBitmap(); wxBitmap *stop = new wxBitmap(); if (zoomIn->LoadFile(BITMAP_PRE "ZoomIn" BITMAP_SUF,AUDACITY_BITMAP_TYPE) && zoomOut->LoadFile(BITMAP_PRE "ZoomOut" BITMAP_SUF,AUDACITY_BITMAP_TYPE) && play->LoadFile(BITMAP_PRE "Play" BITMAP_SUF,AUDACITY_BITMAP_TYPE) && stop->LoadFile(BITMAP_PRE "Stop" BITMAP_SUF,AUDACITY_BITMAP_TYPE)) { b1 = (wxButton *)new wxBitmapButton (frame, ZoomInButtonID, *zoomIn, wxPoint(0, 0), wxSize(36, 36)); b2 = (wxButton *)new wxBitmapButton (frame, ZoomOutButtonID, *zoomOut, wxPoint(30, 0), wxSize(36, 36)); b3 = (wxButton *)new wxBitmapButton (frame, PlayButtonID, *play, wxPoint(30, 0), wxSize(36, 36)); b4 = (wxButton *)new wxBitmapButton (frame, StopButtonID, *stop, wxPoint(30, 0), wxSize(36, 36)); b1->SetBackgroundColour(backgroundColor); b2->SetBackgroundColour(backgroundColor); b3->SetBackgroundColour(backgroundColor); b4->SetBackgroundColour(backgroundColor); } else { delete zoomIn; delete zoomOut; delete play; delete stop; b1 = new wxButton(frame, ZoomInButtonID, "<", wxPoint(0, 0), wxSize(36,36)); b2 = new wxButton(frame, ZoomOutButtonID, ">", wxPoint(0, 0), wxSize(36,36)); b3 = new wxButton(frame, PlayButtonID, "Play", wxPoint(0, 0), wxSize(128,36)); b4 = new wxButton(frame, StopButtonID, "Stop", wxPoint(0, 0), wxSize(128,36)); } wxBitmap *smallLogoBitmap = new wxBitmap(); wxStaticBitmap *smallLogo = 0; if (smallLogoBitmap->LoadFile(BITMAP_PRE "AudacitySmall" BITMAP_SUF, AUDACITY_BITMAP_TYPE)) { smallLogo = new wxStaticBitmap(frame, 0, *smallLogoBitmap, wxDefaultPosition, wxDefaultSize); } // // Lay them out using box sizers // mainSizer = new wxBoxSizer(wxVERTICAL); topSizer = new wxBoxSizer(wxHORIZONTAL); bottomSizer = new wxBoxSizer(wxHORIZONTAL); trackSizer = new wxBoxSizer(wxVERTICAL); mainSizer->Add(topSizer, 1, wxEXPAND, 0); mainSizer->Add(bottomSizer, 0, wxEXPAND | wxALL, 2); topSizer->Add(trackSizer, 1, wxEXPAND, 0); topSizer->Add(vsbar, 0, wxEXPAND | wxBOTTOM, sbarWidth); trackSizer->Add(rulerPanel, 0, wxEXPAND | wxLEFT, labelWidth); trackSizer->Add(trackPanel, 1, wxEXPAND, 0); trackSizer->Add(hsbar, 0, wxEXPAND, 0); bottomSizer->Add(b1, 0, wxEXPAND, 0); bottomSizer->Add(b2, 0, wxEXPAND, 0); bottomSizer->Add(b3, 0, wxEXPAND | wxLEFT, 24); bottomSizer->Add(b4, 0, wxEXPAND, 0); bottomSizer->Add(status, 1, wxEXPAND | wxLEFT, 24); if (smallLogo) bottomSizer->Add(smallLogo, 0, wxLEFT | wxRIGHT, 24); frame->SetAutoLayout(true); frame->SetSizer(mainSizer); mainSizer->Fit(frame); mainSizer->SetSizeHints(frame); // // // InitialState(); FixScrollbars(); frame->SetBackgroundColour(backgroundColor); #ifdef __X__ // X seems to require a forced resize int x, y; frame->GetSize(&x, &y); frame->SetSize(-1, -1, x, y); #endif // Min size, max size frame->SetSizeHints(250,200,20000,20000); frame->Show(TRUE); #ifdef __WXMAC__ // This (hack) tells various windows not to erase the background on update events. //frame->m_MacEraseBack = false; trackPanel->m_MacEraseBack = false; rulerPanel->m_MacEraseBack = false; hsbar->m_MacEraseBack = false; vsbar->m_MacEraseBack = false; #endif #ifdef DEBUG_PASTE_BUG // probably can remove this - fixed WaveTrack *left = 0; WaveTrack *right = 0; ImportWAV("Mussorgsky1.WAV", &left, &right, &((AudioDoc *)GetDocument())->dirManager); selected->Clear(); GetTracks()->Add(left); selected->Add(left); PushState(); sel0 = 2.0; sel1 = 4.0; Cut(); left->Debug(); sel0 = 4.0; sel1 = 4.0; Paste(); left->Debug(); FixScrollbars(); REDRAW(trackPanel); REDRAW(rulerPanel); #endif return TRUE; }
int main(int argc, char **argv) { #ifdef _OPENMP /* Compilation with OMP */ int numthreads; numthreads = omp_get_max_threads(); omp_set_num_threads(numthreads); #endif time_t t; struct tm *tm; t = time(NULL); tm = localtime(&t); if((argc >1) && (argv[1][1] == 'd')) {debug = 1; d_level = 1;} /* Initial debugging */ srand(time(NULL)); gsl_rng_env_setup(); /* Random generator initialization */ gsl_rng_default_seed = rand()*RAND_MAX; sprintf(mesg,"Seed: %ld ",gsl_rng_default_seed); DEBUG(mesg); /* Declaration of variables */ /* Contadores */ int i, time, tr_TT = 0; int Nscan = 0; /* Others */ int def = 1; /* Default = 1 */ int temporal_correction = 1; int total_spikes1 = 0, total_spikes2 = 0; double var_value; double *final_conf, *final_conf2; /* Date variables */ char day[100], hour[100]; strftime(day, 100, "%m-%d-%Y",tm); sprintf(hour,"%d.%02d",tm->tm_hour,tm->tm_min); /* Data store */ Create_Dir("results"); FILE *file[8]; /* System variables (magnitudes) */ t_th *th; /* neuron vector */ double R = 0; /* Kuramoto order parameter */ double fr_volt[2]; /* Stores width and center of the Lorentzian distr. (R) */ double fr_x; /* Center of the Lorentzian distr. */ double fr_y; /* Width " " " " */ double perturbation = 0; double fr, fr2; /* Mean field (firing rate) */ double avg_fr1,avg2_fr1; int medida; double inst_fr_avg; int intervalo; int total_spikes_inst; double avg_v1 = 0, avg_v2 = 0; long double v1_center = 0, v2_center = 0; double dt, *p, phi = 0; double rh_final = 1, vh_final = 1; /* FR *** initial conds. for r and v ( FR equations) */ t_data *d, *data; d = malloc(sizeof(*d)); data = malloc(sizeof(*data)); d->scan = 0; /* Exploring is unabled by default */ d->MaxDim = 5000000; /* Raster plot will be disabled for higher dim */ sprintf(d->file,"%s_%s",day,hour); sprintf(mesg2,"results/%s",d->file); Create_Dir(mesg2); Create_Dir("temp"); sprintf(mesg2,"cp volt_avg.R ./temp"); system(mesg2); /*********************************/ /* Program arguments assignation */ /*********************************/ *data = Scan_Data(DATA_FILE,*d); d = data; while((argc--) != 1) { /* Terminal arguments can be handled */ *data = Arg(argv[argc], *d); d = data; if(argv[1][0] != '-') def = 0; } #ifdef _OPENMP /* Work is divided between the cores */ int chunksize = d->N/numthreads; if(chunksize > 10) chunksize = 10; #endif /* Initial tunning: step size, and scanning issues */ Intro(d,&Nscan,&tr_TT); if(d_level == 4){ temporal_correction = 0; DEBUG("Temporal correction is OFF");} d->var_value = d->eta; d->scan_max = Nscan; d->pert = 0; if(d->scan_mode == 3) { d->pert = 1; d->scan_mode = 2; } double dTT = d->TT; double dTT2 = d->TT*2.0; /* Configuration at the end of simulation */ final_conf = (double*) malloc (d->N*sizeof(double)); final_conf2 = (double*) malloc (d->N*sizeof(double)); /**********************************/ /* New simulations can start here */ /**********************************/ do { if(d->scan_mode >= 1) d = Var_update(d); Data_Files(&file,*d,0); Data_Files(&file,*d,4); total_spikes1 = 0; total_spikes2 = 0; /********************/ /* Oscillator setup */ /********************/ th = (t_th*) calloc (d->N,sizeof(t_th)); for(i=0 ;i<d->N ;i++ ) { /* The total number (N) is stored in each package */ th[i].N = d->N; } th[0].pert = 0; th[0].rh = 1; th[0].vh = 1; /* FR **** Initial condition for the FR equations */ p = (double*) malloc ((d->N+1)*sizeof(double)); /* QIF: vr and vp and g */ for(i=0 ;i<d->N ;i++ ) { th[i].vr = d->vr; th[i].vp = d->vp; th[i].g = d->g; } if(d->scan_mode == 2 && d->scan > 0) { for(i=0 ;i<d->N ;i++ ) { th[i].v = final_conf[i]; /* We mantain the last configuration of voltages */ th[i].th = final_conf2[i]; } } else { InitialState(th,d->init_dist); /* Initial state configuration */ /* InitialState(th,d->init_dist+1); */ } for(i=0 ;i<d->N ;i++ ) { th[i].spike = 0; /* Spike */ th[i].tr = 0; th[i].tr2 = 0; th[i].ph = VarChange(th[i]); } dt = d->dt; if(def == 0) /* Debug message: data display */ DEBUG2(DataDebug(*d,&file)); if(d->scan_mode == 2 && d->scan > 0) { th[0].rh = rh_final; /* FR **** final configuration of the pevious ... */ th[0].vh = vh_final; /* ... simulation is taken as the initial configuration */ } /** Distributions *******************/ /* QIF: J */ sprintf(mesg,"Building distribution for J_i. J0 = %lf ",d->J ); if(d->J_dist == 1) DEBUG(mesg); p = InitCond(p,d->N,2,d->J,d->J_sigma); if(d->J_dist == 0) { for(i=0 ;i<d->N ;i++ ) th[i].J = d->J; } else for(i=0 ;i<d->N ;i++ ) th[i].J = p[i]; /* QIF: eta */ sprintf(mesg,"Building distribution for eta_i. eta0 = %lf ",d->eta ); if(d->eta_dist == 1) DEBUG(mesg); p = InitCond(p,d->N,2,d->eta,d->eta_sigma); if(d->eta_dist == 0) { for(i=0 ;i<d->N ;i++ ) th[i].eta = d->eta; } else { for(i=0 ;i<d->N ;i++ ) th[i].eta = p[i]; } /* QIF: V0 */ sprintf(mesg,"Building distribution for V0_i. V0 = %lf ",d->v0 ); if(d->v0_dist == 1) DEBUG(mesg); p = InitCond(p,d->N,2,d->v0,d->v0_sigma); if(d->v0_dist == 0) { for(i=0 ;i<d->N ;i++ ) th[i].V0 = d->v0; } else for(i=0 ;i<d->N ;i++ ) th[i].V0 = p[i]; /* Simulation */ sprintf(mesg,"Simulating dynamics of: v' = v² + I "); DEBUG(mesg); sprintf(mesg,"I = J*r + n - g*r(v - v0)"); DEBUG(mesg); sprintf(mesg,"I = %.3lf*r + %.3lf - %.3lf*r(v - %.3lf) ",d->J,d->eta,d->g,d->v0); DEBUG(mesg); time = 0; fr = 0; fr2 = 0; avg_fr1 = 0; avg2_fr1 = 0; medida = 0; v1_center = 0; v2_center = 0; d->voltdist = 0; intervalo = 0; inst_fr_avg = 0; total_spikes_inst = 0; do { /* In each step we must compute the mean field potential (r) */ if(time%((int)((float)d->TT/(10.0*dt))) == 0) { /* Control point */ sprintf(mesg,"%d%% ",(int)(((time*dt)/(float)d->TT)*100) ); DEBUG(mesg); } /* Parallelizable, watch out with pointers and shared variables */ #pragma omp parallel for schedule(dynamic,chunksize) for(i=0 ;i<d->N ;i++ ) { /* i represents each oscillator */ th[i].r = fr; if(th[0].pert == 1) th[i].r = th[0].FR; th[i].r2 = fr2; th[i].spike = 0; th[i].spike2 = 0; if(temporal_correction == 1) { if(th[i].tr == 1) { th[i].tr = 2; th[i].spike = 1; } else if(th[i].tr == 2) { th[i].tr = 0; } else th[i] = QIF(*d,th[i]); } else { th[i] = QIF(*d, th[i]); if(th[i].tr == 1) th[i].spike = 1; th[i].tr = 0; } th[i] = THETA(*d,th[i]); if(time*dt >= (d->TT/4.0)*3.0) th[i].total_spikes += th[i].spike; } /* Simulation of rate equations */ th[0] = Theory(*d,th[0]); /* Ends here */ fr = MeanField(th,d->dt,1); fr2 = MeanField(th,d->dt,2); if((time*d->dt)/d->TT > 0.9) { total_spikes1 += th[0].global_s1; total_spikes2 += th[0].global_s2; for(i=0 ;i<d->N ;i++ ) { v1_center += th[i].v; v2_center += th[i].th; } v1_center /= d->N; v2_center /= d->N; medida++; avg_v1 += v1_center; avg_v2 += v2_center; } /* Inst FR */ total_spikes_inst += th[0].global_s1; intervalo++; if(abs(time - (int)(d->TT/d->dt)) <= 50) { d->voltdist++; Data_Files(&file,*d,2); for(i=0 ;i<d->N ;i++ ) fprintf(file[6],"%lf\n",th[i].v); Data_Files(&file,*d,3); } if(d->disable_raster == 0) for(i=0 ;i<d->N ;i++ ) { if(th[i].spike == 1) fprintf(file[2] ,"%lf\t%d\t-1\n",time*d->dt,i); if(th[i].spike2 == 1) fprintf(file[2] ,"%lf\t-1\t%d\n",time*d->dt,i); } R = OrderParameter(th,&phi); th[0].FR = 0; th[0].pert = 0; /* Perturbation introduced here */ if((time > (d->TT/d->dt)-100) && d->pert == 1 && d->dx >= 0) { if(time == (d->TT/d->dt)-100 +1) { avg_fr1 = (double)total_spikes1/((double)medida*d->dt); avg_fr1 /= d->N; printf("\n Average FR 0: %.8lf",avg_fr1); fflush(stdout); } if(abs(time-(int)((d->TT/d->dt)-100))%5 == 0) { Perturbation(&th,*d,1); th[0].pert = 1; printf("\nPerturbation: %lf!!",d->pert_amplitude); perturbation = d->pert_amplitude; } if(time == (d->TT/d->dt)-1) { d->TT = dTT2; d->pert = 2; } } else if((time == (d->TT/d->dt)-1) && d->pert == 1) { Perturbation(&th,*d,0); th[0].vh += d->perturbation_FR; /* FR *** Perturbation for FR equations */ th[0].pert = 1; printf("\nPerturbation: %lf!!",d->pert_amplitude); perturbation = d->pert_amplitude; d->TT = dTT2; avg_fr1 = (double)total_spikes1/((double)medida*d->dt); avg_fr1 /= d->N; printf("\n Average FR 0: %.8lf",avg_fr1); fflush(stdout); d->pert = 2; } fprintf(file[3] ,"%lf\t%lf\t%lf\t%lf\t%lf\t%lf\t%lf\t%lf\t%lf\n",time*dt,fr,R,phi,fr2,R,phi,th[0].rh,th[0].vh); fprintf(file[0] ,"%lf\t%lf\t%lf\t%lf\n",time*d->dt,th[d->N/4].v,th[d->N/4].th,perturbation); if(time%50 == 0) { inst_fr_avg = (double)total_spikes_inst/(double)intervalo; inst_fr_avg = inst_fr_avg/(d->N*d->dt); intervalo = 0; fprintf(file[7],"%lf\t%lf\n",time*d->dt,inst_fr_avg); inst_fr_avg = 0; total_spikes_inst = 0; } perturbation = 0; time++; } while(time*d->dt< d->TT); if(d->pert == 2) { d->TT = dTT; d->pert = 1; } avg_fr1 = (double)total_spikes1/((double)medida*d->dt); avg_fr1 /= d->N; printf("\n Average FR 1: %.8lf",avg_fr1); avg2_fr1 = (double)total_spikes2/((double)medida*d->dt); avg2_fr1 /= d->N; printf("\n Average FR Theta: %.8lf\n",avg2_fr1); avg_v1 /= medida; avg_v2 /= medida; avg_v2 = tan(avg_v2*0.5); R_script(*d,avg2_fr1,avg_v2); R_calc(*d,&fr_x,&fr_y); /* fr: 0 voltage: 1 */ fr_volt[0] = fr_x; fr_volt[1] = fr_y; fr_x = 2*fr_x/(PI); fr_y = 2*fr_y; printf("\n Average Voltage (v) : %lf\n Average Voltage (Theta) : %lf",avg_v1, avg_v2); printf("\n Average Voltage (v) using v distribution: %lf\n Average FR using v dist : %lf\n",fr_volt[1]*2,fr_volt[0]*(2.0/(PI))); if(d->scan_mode >= 1) { switch(d->variable) { case 1: var_value = d->J; break; case 2: var_value = d->eta; break; case 3: var_value = d->g; break; case 4: var_value = d->v0; break; } fprintf(file[4] ,"%lf\t%lf\t%lf\t%lf\t%lf\t%lf\t%lf\n",var_value,avg_fr1,avg2_fr1,avg_v1, avg_v2,fr_x,fr_y); } printf("\n"); free(p); for(i=0 ;i<d->N ;i++ ) { fprintf(file[1] ,"%d\t%lf\t%lf\n",i,th[i].v,th[i].th); final_conf[i] = th[i].v; final_conf2[i] = th[i].th; } free(th); d->scan++; Data_Files(&file,*d,1); Data_Files(&file,*d,5); if(d->scan_mode == 0) break; } while (d->scan < Nscan); /* Simulation ends here */ free(final_conf); free(final_conf2); /* system("R -f histogram.R --quiet --slave"); */ /* Gnuplot_Init(*d,day,hour); */ system("rm -r ./temp"); printf("\n"); return 0; }