void CSettings::ConstructL(const TDesC& SettingName)
{
	_LIT(db_base, "SETTINGS");
	TBuf<100> db;
	db.Append(db_base);
	db.Append(SettingName);
	TFileName oldfilen, newfilen;
	oldfilen.Format(_L("%S%S.db"), &AppDir(), &db_base);
	newfilen.Format(_L("%S%S.db"), &AppDir(), &db);
	if (BaflUtils::FileExists(Fs(), oldfilen)) {
		User::LeaveIfError(Fs().Rename(oldfilen, newfilen));
	}

	iListeners=CGenericIntMap::NewL();
	iListeners->SetDeletor(ListDeletor);

	if (!iReadOnly) {
		iDb=CDb::NewL(AppContext(), db, EFileRead|EFileWrite|EFileShareAny );
	} else {
		iDb=CDb::NewL(AppContext(), db, EFileRead|EFileShareAny );
	}

	iDesStore=CSingleColDb<TDesC, TDes>::NewL(AppContext(), iDb->Db(), _L("DES"));
	iDes8Store=CSingleColDb<TDesC8, TDes8>::NewL(AppContext(), iDb->Db(), _L("DES8"));
	iIntStore=CSingleColDb<TInt>::NewL(AppContext(), iDb->Db(), _L("INT"));
	iTimeStore=CSingleColDb<TTime>::NewL(AppContext(), iDb->Db(), _L("TIME"));
}
void CSmsSnapshotImpl::TakenL(const TDesC& aFileName)
{
	CALLSTACKITEM_N(_CL("CSmsSnapshotImpl"), _CL("TakenL"));

	TFileName recfilename=aFileName;
	recfilename.Replace(recfilename.Length()-3, 3, _L("amr"));

	iState=_L("create array");
	auto_ptr<CDesCArrayFlat> a(new (ELeave) CDesCArrayFlat(2));
	a->AppendL(aFileName);

	if (BaflUtils::FileExists(Fs(), recfilename))
		a->AppendL(recfilename);

	TSendTo t=iToBeSend->Pop();
#ifndef TESTING

	iState=_L("send MMS");
	auto_ptr<HBufC> b(HBufC::NewL(t.iBody.Length()+t.iTo.Length()+10));
	b->Des().Append(t.iBody);
	if (t.iTo.Length()>0) {
		cb->status_change(_L("sending MMS"));
		iMMS->SendMessage(t.iTo, *b, *a, t.iBody, false);

		b->Des().Append(_L(" from "));
		b->Des().Append(t.iTo);
	}

	iState=_L("makepacket");
	bb_auto_ptr<CCMPost> buf(CCMPost::NewL(BBDataFactory()));
	buf->iPresence.SetValue(bb_cast<CBBPresence>(iPresence->Data()->CloneL(KNullDesC)));
	buf->iBodyText->Append(*b);

	iState=_L("send pic");
	iTransferer->AddFileToQueueL(aFileName, SETTING_PUBLISH_URLBASE, SETTING_PUBLISH_SCRIPT, 
		true, _L("Unknown"), buf.get(), 120);
	iState=_L("send rec");
	if (BaflUtils::FileExists(Fs(), recfilename))
		iTransferer->AddFileToQueueL(recfilename, SETTING_PUBLISH_URLBASE, SETTING_PUBLISH_SCRIPT, 
			true, _L("Unknown"), buf.get(), 120);
	iState=_L("destroy");
#else
	iTransferer->AddFileToQueueL(aFileName, SETTING_PUBLISH_URLBASE, SETTING_PUBLISH_SCRIPT, 
		true, _L("SMS"), buf.get(), 120);
	if (BaflUtils::FileExists(Fs(), recfilename))
		iTransferer->AddFileToQueueL(recfilename, SETTING_PUBLISH_URLBASE, SETTING_PUBLISH_SCRIPT, 
			true, _L("SMS"), buf.get(), 120);
#endif

}
	virtual void ProcessSelectionL( TInt aIndex ) 
	{
		CALLSTACKITEM_N(_CL("CNetworkAccess"), _CL("ProcessSelectionL"));
		if ( aIndex == 0 )
			{
				Settings().WriteSettingL(SETTING_ACCEPTED_NETWORK_ACCESS, ETrue);
				Settings().WriteSettingL(SETTING_ALLOW_NETWORK_ONCE, ETrue);
				Settings().WriteSettingL(SETTING_PRESENCE_ENABLE, ETrue);
				NotifyActionReadyL(); 
			}
		else
			{
				TBool yes = ShowYesNoMessageL( R_TEXT_WELCOME_CONFIRM_NO_NETWORK_ACCESS, R_TEXT_WELCOME_CONFIRM_NO_NETWORK_ACCESS_TITLE );
				if ( yes )
					{
						Settings().WriteSettingL(SETTING_ACCEPTED_NETWORK_ACCESS, EFalse);
						Settings().WriteSettingL(SETTING_ALLOW_NETWORK_ONCE, EFalse);
						Settings().WriteSettingL(SETTING_ALLOW_NETWORK_ACCESS, EFalse);
						ProcessManagement::SetAutoStartEnabledL(Fs(), DataDir()[0], EFalse);
						NotifyQuitWelcomeL();
					}
				else 
					{
						// no-op. returns to selection view
					}
			}
	}
	virtual void ProcessSelectionL( TInt aIndex ) 
	{
		CALLSTACKITEM_N(_CL("CAutoStartup"), _CL("ProcessSelectionL"));
		TBool enable = aIndex == 0;
		ProcessManagement::SetAutoStartEnabledL(Fs(), DataDir()[0], enable);
		NotifyActionReadyL(); 
	}
Beispiel #5
0
// Group descent update
void gd_gaussian(double *b, double *x, double *r, int g, int *K1, int n, int l, int p, const char *penalty, double lam1, double lam2, double gamma, SEXP df, double *a) {
  // Calculate z
  int K = K1[g+1] - K1[g];
  double *z = Calloc(K, double);
  for (int j=K1[g]; j<K1[g+1]; j++) z[j-K1[g]] = crossprod(x, r, n, j)/n + a[j];
  double z_norm = norm(z,K);

  // Update b
  double len;
  if (strcmp(penalty, "grLasso")==0) len = S(z_norm, lam1) / (1+lam2);
  if (strcmp(penalty, "grMCP")==0) len = F(z_norm, lam1, lam2, gamma);
  if (strcmp(penalty, "grSCAD")==0) len = Fs(z_norm, lam1, lam2, gamma);
  if (len != 0 | a[K1[g]] != 0) {
    // If necessary, update beta and r
    for (int j=K1[g]; j<K1[g+1]; j++) {
      b[l*p+j] = len * z[j-K1[g]] / z_norm;
      double shift = b[l*p+j]-a[j];
      for (int i=0; i<n; i++) r[i] -= x[n*j+i] * shift;
    }
  }

  // Update df
  if (len > 0) REAL(df)[l] += K * len / z_norm;
  Free(z);
}
void CLocaLogicImpl::ConstructL()
{
	CALLSTACKITEM_N(_CL("CLocaLogicImpl"), _CL("ConstructL"));

	iDevStats=CDevStats::NewL(AppContext(), iDb);
	iMessageStats=CMessageStats::NewL(AppContext(), iDb);
	iRemote=CLocaRemoteEvents::NewL(AppContext(), this);
	iAcceptedMessages=CAcceptedMsgs::NewL(iDb);

	iBBSubSession=BBSession()->CreateSubSessionL(this);
	iBBSubSession->AddNotificationL(KLocaScriptTuple, ETrue);

	iEvent.iData.SetValue(&iMsgStatus);
	iEvent.iData.SetOwnsValue(EFalse);
	iEvent.iPriority()=CBBSensorEvent::VALUE;

	GetSettingsL();

	Settings().NotifyOnChange(SETTING_LOCA_BLUEJACK_MAX_MESSAGES, this);
	Settings().NotifyOnChange(SETTING_LOCA_BLUEJACK_MAX_RETRIES, this);
	Settings().NotifyOnChange(SETTING_PUBLISH_AUTHOR, this);

	iInterpreter = CSPyInterpreter::NewInterpreterL();
	iCC=CCnvCharacterSetConverter::NewL();
	iCC->PrepareToConvertToOrFromL(KCharacterSetIdentifierIso88591, Fs());
	iFunctions=new (ELeave) CDesC8ArraySeg(4);
	iErrorFunctions=new (ELeave) CDesC8ArraySeg(4);
}
Beispiel #7
0
void CLogServer::ConstructL()
/**
 * Second phase construction
 */
	{
	User::LeaveIfError(Fs().Connect());
	}
void CUTContactEngine::ConstructL(const TDesC& aFileName, TBool aReplace)
{
	iEngine = CPbkContactEngine::Static();
	if ( ! iEngine )
		{
			RFs& fs = Fs();
			if ( aFileName == KNullDesC )
				{
					iEngine = CPbkContactEngine::NewL(&fs);					
				}
			else
				{
#ifndef __S60V3__
					BaflUtils::EnsurePathExistsL(fs, aFileName);
					iEngine = CPbkContactEngine::NewL(aFileName, aReplace, &fs);
#else
					iEngine = CPbkContactEngine::NewL(_L("c:DBS_100065FF_unittests.cdb"), aReplace, &fs);
#endif
				}
			iOwnsEngine = ETrue;
		}
	else
		{
			iOwnsEngine = EFalse;
		}

  iFieldIds = new CArrayFixFlat<TPbkFieldId>(5);
  iFieldIds->AppendL( EPbkFieldIdFirstName );
  iFieldIds->AppendL( EPbkFieldIdLastName );
  iFieldIds->AppendL( EPbkFieldIdPhoneNumberStandard );

}
Beispiel #9
0
  void AveragedTurbine<Mu>::nonlocal_time_derivative(bool compute_jacobian,
				                 AssemblyContext& context,
				                 CachedValues& /* cache */ )
  {
    libMesh::DenseSubMatrix<libMesh::Number> &Kss =
            context.get_elem_jacobian(this->fan_speed_var(), this->fan_speed_var()); // R_{s},{s}

    libMesh::DenseSubVector<libMesh::Number> &Fs =
            context.get_elem_residual(this->fan_speed_var()); // R_{s}

    const std::vector<libMesh::dof_id_type>& dof_indices =
      context.get_dof_indices(this->fan_speed_var());

    const libMesh::Number fan_speed =
      context.get_system().current_solution(dof_indices[0]);

    const libMesh::Number output_torque =
      this->torque_function(libMesh::Point(0), fan_speed);

    Fs(0) += output_torque;

    if (compute_jacobian)
      {
        // FIXME: we should replace this FEM with a hook to the AD fparser stuff
        const libMesh::Number epsilon = 1e-6;
        const libMesh::Number output_torque_deriv =
          (this->torque_function(libMesh::Point(0), fan_speed+epsilon) -
           this->torque_function(libMesh::Point(0), fan_speed-epsilon)) / (2*epsilon);

        Kss(0,0) += output_torque_deriv * context.get_elem_solution_derivative();
      }

    return;
  }
Beispiel #10
0
CLogServer::~CLogServer()
/**
 * Destructor
 */
	{
	// Close the array of control structures
	LogControl().Close();
	Fs().Close();
	}
// ---------------------------------------------------------------------------
// CEntryWatcher::CancelWatcher
// ---------------------------------------------------------------------------
//
void CEntryWatcher::CancelWatcher()
    {
    FUNC_LOG

    INFO_LOG2(
        "CEntryWatcher::CancelWatcher-iType=%d,iEntry=%S",
        iType, iEntry )

    Fs().NotifyChangeCancel( iStatus );
    }
EXPORT_C void bases::ConstructL(bool aConvertOnly, CCellMap* aCellMap) {
	TRAPD(err, bases::InnerConstructL(aConvertOnly, aCellMap));
	if (err == KErrCorrupt) {
	    Destruct();
		TFileName database_filename;
		database_filename.Format(_L("%S%S"), &DataDir(), &database_file);
		User::LeaveIfError(BaflUtils::DeleteFile(Fs(), database_filename));
		InnerConstructL(aConvertOnly, aCellMap);
	}
}
void CTest_Downloader::setUp()
{
	MContextTestBase::setUp();
	{
		TFileName fn=DataDir();
		fn.Append(_L("UTDL1.db"));
		Fs().Delete(fn);
		iDb=CDb::NewL(AppContext(), _L("UTDL1"), EFileWrite, false);
	}
	iNoAvkonIconsWas=TestSupport().NoAvkonIcons();
	TestSupport().SetNoAvkonIcons(ETrue);
	User::LeaveIfError(iSocketServ.Connect());
}
void CMeaningAppAppUi::HandleCommandL(TInt aCommand)
{
	if (iMediaRunner->HandleCommandL(aCommand)) return;
	switch(aCommand) {
		case EEikCmdExit:
			Exit();
			break;
		case Econtext_logCmdAppTest:
			{
			TBuf<50> filen, from;
			from=_L("c:\\data\\pic.jpg");
			TInt i=0;
			for (;;) {
				filen=_L("c:\\data\\images\\pic"); filen.AppendNum(i); filen.Append(_L(".jpg"));
				if (! BaflUtils::FileExists(Fs(), filen)) {
					User::LeaveIfError(BaflUtils::CopyFile(Fs(), from, filen));
					break;
				}
				i++;
			}
			}
			break;
	}
}
Beispiel #15
0
  void ScalarODE::nonlocal_constraint(bool compute_jacobian,
				      AssemblyContext& context,
				      CachedValues& /* cache */ )
  {
    libMesh::DenseSubMatrix<libMesh::Number> &Kss =
            context.get_elem_jacobian(_scalar_ode_var, _scalar_ode_var); // R_{s},{s}

    libMesh::DenseSubVector<libMesh::Number> &Fs =
            context.get_elem_residual(_scalar_ode_var); // R_{s}

    const libMesh::Number constraint =
      (*constraint_function)(context, libMesh::Point(0),
                             context.get_time());

    Fs(0) += constraint;

    if (compute_jacobian)
      {
        // FIXME: we should replace this hacky FDM with a hook to the
        // AD fparser stuff
        libMesh::DenseSubVector<libMesh::Number> &Us =
          const_cast<libMesh::DenseSubVector<libMesh::Number>&>
            (context.get_elem_solution(_scalar_ode_var)); // U_{s}

        const libMesh::Number s = Us(0);
        Us(0) = s + this->_epsilon;
        libMesh::Number constraint_jacobian =
          (*constraint_function)(context, libMesh::Point(0),
                                 context.get_time());

        Us(0) = s - this->_epsilon;
        constraint_jacobian -=
          (*constraint_function)(context, libMesh::Point(0),
                                 context.get_time());
           
        Us(0) = s;
        constraint_jacobian /= (2*this->_epsilon);

        Kss(0,0) += constraint_jacobian *
          context.get_elem_solution_derivative();
      }

    return;
  }
EXPORT_C void CSTTorrentManager::RemoveTorrentL(TInt aIndex, TBool aDeleteIncompleteFiles)
{
	// deleting saved information
	if (iTorrents[aIndex]->SavedTorrent() != KNullDesC)
	{
		Fs().Delete(iTorrents[aIndex]->SavedTorrent());
		Preferences()->RemoveSTorrentL(iTorrents[aIndex]->SavedTorrent());
	}
	
	
	iTorrents[aIndex]->CloseL(aDeleteIncompleteFiles);
	/*
	if (iTorrentManagerObserver)
		iTorrentManagerObserver->RemoveTorrentL(aIndex);		
	
	//iTorrents[aIndex]->StopL();

	delete iTorrents[aIndex];
	iTorrents.Remove(aIndex);*/
}
void CRecognizerViewImpl::ConstructL()
{
	CALLSTACKITEM_N(_CL("CRecognizerViewImpl"), _CL("ConstructL"));

#ifndef __WINS__
	TFileName resfile=_L("c:\\System\\data\\recognizer.rsc");
	if (! BaflUtils::FileExists(Fs(), resfile) ) {
		resfile.Replace(0, 1, _L("e"));
	}
#else
	TFileName resfile=_L("z:\\System\\data\\recognizer.rsc");
	BaflUtils::NearestLanguageFile(iEikonEnv->FsSession(), resfile); //for localization
#endif
	User::LeaveIfError(iResource=iEikonEnv->AddResourceFileL(resfile));

	if (iResourceId==-1) iResourceId=R_RECOGNIZER_VIEW;
	
	BaseConstructL(iResourceId);
	iActivityTimeOut = CTimeOut::NewL(*this);
	iStandByTimeOut = CTimeOut::NewL(*this);
}
	void RunAsync() {
		CALLSTACKITEM_N(_CL("CPrivacyStatement"), _CL("RunL"));

		TInt acceptedPrivacyVersion = 0;		
		Settings().GetSettingL(SETTING_ACCEPTED_PRIVACY_STMT_VERSION, acceptedPrivacyVersion);
		
		if ( acceptedPrivacyVersion < KJaikuPrivacyStatementVersion )
			{
				TPtrC text(*iText);
				TPtrC header(*iHeader);
				auto_ptr<CAknMessageQueryDialog> dlg( CAknMessageQueryDialog::NewL(text) );
				dlg->SetHeaderTextL( header );
				iDlg = dlg.get();
				TBool result = dlg.release()->ExecuteLD( R_PRIVACYSTATEMENT_DIALOG );
			  if (!iDlg) {
			    iAsync->TriggerAsync();
			    return;
			  }
				if (result)
					{
					  iDlg = NULL;
						Settings().WriteSettingL(SETTING_ACCEPTED_PRIVACY_STMT_VERSION, KJaikuPrivacyStatementVersion);
						NotifyActionReadyL();
					}
				else
					{
					  iDlg = NULL;
						// do not write, keep old accepted version 
						ProcessManagement::SetAutoStartEnabledL(Fs(), DataDir()[0], EFalse);
						NotifyQuitWelcomeL();
					}
			}
		else
			{
				NotifyActionReadyL();
			}
	}
void CFinalQuery::AddShortcutL()
{
	iState = EShowShortcutHelp;
	TBool result = ShowOkCancelMessageL( R_TEXT_WELCOME_ADD_JAIKU_TEXT, R_TEXT_WELCOME_ADD_JAIKU_TITLE );
	if (result)
		{
			iState = ELaunchingSettings;
			
			TUint major = 0;
			TUint minor = 0;
			
			TUid applicationUid;
			TUid viewUid; 
			
			GetS60PlatformVersionL( Fs(), major, minor );
			
			if ( major >= 3 && minor >= 1 )
				{
					applicationUid = TUid::Uid( 0x100058EC );
					viewUid = TUid::Uid( 1 );
				}
			else
				{									
					applicationUid = TUid::Uid( 0x100058EC );
					viewUid = TUid::Uid( 4 );
				}
			
			CAknViewAppUi* viewAppUi = static_cast<CAknViewAppUi*>(CEikonEnv::Static()->AppUi());
			viewAppUi->ActivateViewL( TVwsViewId( applicationUid, viewUid ) );
			NotifyActionReadyL();
		}
	else
		{
			iState = EQueryFinalAction;
		}
}					
Beispiel #20
0
bool DifferentiablePhysics::nonlocal_mass_residual(bool request_jacobian,
                                                   DiffContext &c)
{
  FEMContext &context = cast_ref<FEMContext&>(c);

  for (unsigned int var = 0; var != context.n_vars(); ++var)
    {
      if (!this->is_time_evolving(var))
        continue;

      if (c.get_system().variable(var).type().family != SCALAR)
        continue;

      const std::vector<dof_id_type>& dof_indices =
        context.get_dof_indices(var);

      const unsigned int n_dofs = cast_int<unsigned int>
        (dof_indices.size());

      DenseSubVector<Number> &Fs = context.get_elem_residual(var);
      DenseSubMatrix<Number> &Kss = context.get_elem_jacobian( var, var );

      const libMesh::DenseSubVector<libMesh::Number> &Us =
        context.get_elem_solution(var);

      for (unsigned int i=0; i != n_dofs; ++i)
        {
          Fs(i) -= Us(i);

          if (request_jacobian)
            Kss(i,i) -= context.elem_solution_rate_derivative;
        }
    }

  return request_jacobian;
}
Beispiel #21
0
  void AveragedTurbine<Mu>::nonlocal_mass_residual( bool compute_jacobian,
				                AssemblyContext& context,
				                CachedValues& /* cache */ )
  {
    libMesh::DenseSubMatrix<libMesh::Number> &Kss =
            context.get_elem_jacobian(this->fan_speed_var(), this->fan_speed_var()); // R_{s},{s}

    libMesh::DenseSubVector<libMesh::Number> &Fs =
            context.get_elem_residual(this->fan_speed_var()); // R_{s}

    const libMesh::DenseSubVector<libMesh::Number> &Us =
      context.get_elem_solution_rate(this->fan_speed_var());

    const libMesh::Number& fan_speed = Us(0);

    Fs(0) -= this->moment_of_inertia * fan_speed;

    if (compute_jacobian)
      {
        Kss(0,0) -= this->moment_of_inertia * context.get_elem_solution_rate_derivative();
      }

    return;
  }
Beispiel #22
0
int compute_M_shift_start(double new_t_start, int k, int new_position, int flavor_ins,
        MAT & M, const operator_container_t & annihilation_operators, const HYB & F, double BETA, SCALAR det_rat) {

  std::vector<SCALAR> R(M.size1(), 0), M_k(M.size1(), 0), Fs(M.size1(), 0);

  operator_container_t::const_iterator ita = annihilation_operators.begin();
  for (int i = 0; i < (int) M_k.size(); i++) {
    M_k[i] = M(k, i);
    Fs[i] = interpolate_F(ita->time() - new_t_start, BETA, F[ita->flavor()][flavor_ins]);
    ita++;
  }

  for (int i = 0; i < (int) R.size(); i++) {
    if (i != k) {
      for (int j = 0; j < (int) R.size(); j++)
        R[i] += M(i, j) * Fs[j];
    }
  }

  for (int n = 0; n < (int) M.size1(); n++) {
    if (n != k) {
      for (int m = 0; m < (int) M.size1(); m++) {
        M(n, m) -= M_k[m] * R[n] / det_rat;
      }
    } else {
      for (int m = 0; m < (int) M.size1(); m++) {
        M(n, m) = M_k[m] / det_rat;
      }
    }
  }

  //swap rows
  move_row(M, k, new_position);

  return std::abs(k-new_position);
}  
Beispiel #23
0
void Law2_L3Geom_FrictPhys_ElPerfPl::go(shared_ptr<IGeom>& ig, shared_ptr<IPhys>& ip, Interaction* I){
	L3Geom* geom=static_cast<L3Geom*>(ig.get()); FrictPhys* phys=static_cast<FrictPhys*>(ip.get());

	// compute force
	Vector3r& localF(geom->F);
	localF=geom->relU().cwiseProduct(Vector3r(phys->kn,phys->ks,phys->ks));
	// break if necessary
	if(localF[0]>0 && !noBreak){ scene->interactions->requestErase(I); return; }

	if(!noSlip){
		// plastic slip, if necessary; non-zero elastic limit only for compression
		Real maxFs=-min((Real)0.,localF[0]*phys->tangensOfFrictionAngle); Eigen::Map<Vector2r> Fs(&localF[1]);
		//cerr<<"u="<<geom->relU()<<", maxFs="<<maxFs<<", Fn="<<localF[0]<<", |Fs|="<<Fs.norm()<<", Fs="<<Fs<<endl;
		if(Fs.squaredNorm()>maxFs*maxFs){
			Real ratio=sqrt(maxFs*maxFs/Fs.squaredNorm());
			Vector3r u0slip=(1-ratio)*Vector3r(/*no slip in the normal sense*/0,geom->relU()[1],geom->relU()[2]);
			geom->u0+=u0slip; // increment plastic displacement
			Fs*=ratio; // decrement shear force value;
			if(scene->trackEnergy){ Real dissip=Fs.norm()*u0slip.norm(); if(dissip>0) scene->energy->add(dissip,"plastDissip",plastDissipIx,/*reset*/false); }
		}
	}
	if(scene->trackEnergy)	{ scene->energy->add(0.5*(pow(geom->relU()[0],2)*phys->kn+(pow(geom->relU()[1],2)+pow(geom->relU()[2],2))*phys->ks),"elastPotential",elastPotentialIx,/*reset at every timestep*/true); }
	// apply force: this converts the force to global space, updates NormShearPhys::{normal,shear}Force, applies to particles
	geom->applyLocalForce(localF,I,scene,phys);
}
Beispiel #24
0
  void AveragedTurbine<Mu>::element_time_derivative( bool compute_jacobian,
					      AssemblyContext& context,
					      CachedValues& /* cache */ )
  {
#ifdef GRINS_USE_GRVY_TIMERS
    this->_timer->BeginTimer("AveragedTurbine::element_time_derivative");
#endif

    // Element Jacobian * quadrature weights for interior integration
    const std::vector<libMesh::Real> &JxW = 
      context.get_element_fe(this->_flow_vars.u())->get_JxW();

    // The shape functions at interior quadrature points.
    const std::vector<std::vector<libMesh::Real> >& u_phi = 
      context.get_element_fe(this->_flow_vars.u())->get_phi();

    const std::vector<libMesh::Point>& u_qpoint = 
      context.get_element_fe(this->_flow_vars.u())->get_xyz();

    // The number of local degrees of freedom in each variable
    const unsigned int n_u_dofs = context.get_dof_indices(this->_flow_vars.u()).size();

    // The subvectors and submatrices we need to fill:
    libMesh::DenseSubMatrix<libMesh::Number> &Kuu = context.get_elem_jacobian(this->_flow_vars.u(), this->_flow_vars.u()); // R_{u},{u}
    libMesh::DenseSubMatrix<libMesh::Number> &Kuv = context.get_elem_jacobian(this->_flow_vars.u(), this->_flow_vars.v()); // R_{u},{v}
    libMesh::DenseSubMatrix<libMesh::Number> &Kvu = context.get_elem_jacobian(this->_flow_vars.v(), this->_flow_vars.u()); // R_{v},{u}
    libMesh::DenseSubMatrix<libMesh::Number> &Kvv = context.get_elem_jacobian(this->_flow_vars.v(), this->_flow_vars.v()); // R_{v},{v}

    libMesh::DenseSubMatrix<libMesh::Number> &Kus =
            context.get_elem_jacobian(this->_flow_vars.u(),
                                      this->fan_speed_var()); // R_{u},{s}
    libMesh::DenseSubMatrix<libMesh::Number> &Ksu =
            context.get_elem_jacobian(this->fan_speed_var(),
                                      this->_flow_vars.u()); // R_{s},{u}
    libMesh::DenseSubMatrix<libMesh::Number> &Kvs =
            context.get_elem_jacobian(this->_flow_vars.v(),
                                      this->fan_speed_var()); // R_{v},{s}
    libMesh::DenseSubMatrix<libMesh::Number> &Ksv =
            context.get_elem_jacobian(this->fan_speed_var(),
                                      this->_flow_vars.v()); // R_{s},{v}
    libMesh::DenseSubMatrix<libMesh::Number> &Kss =
            context.get_elem_jacobian(this->fan_speed_var(),
                                      this->fan_speed_var()); // R_{s},{s}

    libMesh::DenseSubMatrix<libMesh::Number>* Kwu = NULL;
    libMesh::DenseSubMatrix<libMesh::Number>* Kwv = NULL;
    libMesh::DenseSubMatrix<libMesh::Number>* Kww = NULL;
    libMesh::DenseSubMatrix<libMesh::Number>* Kuw = NULL;
    libMesh::DenseSubMatrix<libMesh::Number>* Kvw = NULL;

    libMesh::DenseSubMatrix<libMesh::Number>* Ksw = NULL;
    libMesh::DenseSubMatrix<libMesh::Number>* Kws = NULL;

    libMesh::DenseSubVector<libMesh::Number> &Fu = context.get_elem_residual(this->_flow_vars.u()); // R_{u}
    libMesh::DenseSubVector<libMesh::Number> &Fv = context.get_elem_residual(this->_flow_vars.v()); // R_{v}
    libMesh::DenseSubVector<libMesh::Number>* Fw = NULL;

    libMesh::DenseSubVector<libMesh::Number> &Fs = context.get_elem_residual(this->fan_speed_var()); // R_{s}

    if( this->mesh_dim(context) == 3 )
      {
        Kuw = &context.get_elem_jacobian(this->_flow_vars.u(), this->_flow_vars.w()); // R_{u},{w}
        Kvw = &context.get_elem_jacobian(this->_flow_vars.v(), this->_flow_vars.w()); // R_{v},{w}

        Kwu = &context.get_elem_jacobian(this->_flow_vars.w(), this->_flow_vars.u()); // R_{w},{u}
        Kwv = &context.get_elem_jacobian(this->_flow_vars.w(), this->_flow_vars.v()); // R_{w},{v}
        Kww = &context.get_elem_jacobian(this->_flow_vars.w(), this->_flow_vars.w()); // R_{w},{w}
        Fw  = &context.get_elem_residual(this->_flow_vars.w()); // R_{w}

        Ksw = &context.get_elem_jacobian(this->fan_speed_var(), this->_flow_vars.w()); // R_{s},{w}
        Kws = &context.get_elem_jacobian(this->_flow_vars.w(), this->fan_speed_var()); // R_{w},{s}

        Fw  = &context.get_elem_residual(this->_flow_vars.w()); // R_{w}
      }

    unsigned int n_qpoints = context.get_element_qrule().n_points();

    for (unsigned int qp=0; qp != n_qpoints; qp++)
      {
        // Compute the solution at the old Newton iterate.
        libMesh::Number u, v, s;
        u = context.interior_value(this->_flow_vars.u(), qp);
        v = context.interior_value(this->_flow_vars.v(), qp);
        s = context.interior_value(this->fan_speed_var(), qp);

        libMesh::NumberVectorValue U(u,v);
        if (this->mesh_dim(context) == 3)
          U(2) = context.interior_value(this->_flow_vars.w(), qp); // w

        libMesh::NumberVectorValue U_B_1;
        libMesh::NumberVectorValue F;
        libMesh::NumberTensorValue dFdU;
        libMesh::NumberTensorValue* dFdU_ptr =
          compute_jacobian ? &dFdU : NULL;
        libMesh::NumberVectorValue dFds;
        libMesh::NumberVectorValue* dFds_ptr =
          compute_jacobian ? &dFds : NULL;
        if (!this->compute_force(u_qpoint[qp], context.time, U, s,
                                 U_B_1, F, dFdU_ptr, dFds_ptr))
          continue;

        libMesh::Real jac = JxW[qp];

        // Using this dot product to derive torque *depends* on s=1
        // and U_B_1 corresponding to 1 rad/sec base velocity; this
        // means that the length of U_B_1 is equal to radius.

        // F is the force on the air, so *negative* F is the force on
        // the turbine.
        Fs(0) -= U_B_1 * F * jac;

        if (compute_jacobian)
          {
            Kss(0,0) -= U_B_1 * dFds * jac;

            for (unsigned int j=0; j != n_u_dofs; j++)
              {
                libMesh::Real jac_j = JxW[qp] * u_phi[j][qp];

                for (unsigned int d=0; d != 3; ++d)
                  {
                    Ksu(0,j) -= jac_j * U_B_1(d) * dFdU(d,0);
                    Ksv(0,j) -= jac_j * U_B_1(d) * dFdU(d,1);
                  }

                if (this->mesh_dim(context) == 3)
                  {
                    for (unsigned int d=0; d != 3; ++d)
                      (*Ksw)(0,j) -= jac_j * U_B_1(d) * dFdU(d,2);
                  }

              } // End j dof loop
          }

        for (unsigned int i=0; i != n_u_dofs; i++)
          {
            const libMesh::Number jac_i = jac * u_phi[i][qp];

            Fu(i) += F(0)*jac_i;
            Fv(i) += F(1)*jac_i;

            if( this->mesh_dim(context) == 3 )
              (*Fw)(i) += F(2)*jac_i;

	    if( compute_jacobian )
              {
                Kus(i,0) += dFds(0) * jac_i;
                Kvs(i,0) += dFds(1) * jac_i;
                if( this->mesh_dim(context) == 3 )
                  (*Kws)(i,0) += dFds(2) * jac_i;

                for (unsigned int j=0; j != n_u_dofs; j++)
                  {
                    const libMesh::Number jac_ij = jac_i * u_phi[j][qp];
                    Kuu(i,j) += jac_ij * dFdU(0,0);
                    Kuv(i,j) += jac_ij * dFdU(0,1);
                    Kvu(i,j) += jac_ij * dFdU(1,0);
                    Kvv(i,j) += jac_ij * dFdU(1,1);

                    if( this->mesh_dim(context) == 3 )
                      {
                        (*Kuw)(i,j) += jac_ij * dFdU(0,2);
                        (*Kvw)(i,j) += jac_ij * dFdU(1,2);
                        (*Kwu)(i,j) += jac_ij * dFdU(2,0);
                        (*Kwv)(i,j) += jac_ij * dFdU(2,1);
                        (*Kww)(i,j) += jac_ij * dFdU(2,2);
                      }
                  }
              }
          }
      }


#ifdef GRINS_USE_GRVY_TIMERS
    this->_timer->EndTimer("AveragedTurbine::element_time_derivative");
#endif

    return;
  }
void bases::InnerConstructL(bool aConvertOnly, CCellMap* aCellMap)
{
	CALLSTACKITEM_N(_CL("bases"), _CL("ConstructL"));

	iConvertOnly=aConvertOnly;

	if (!aConvertOnly) {
		Mlogger::ConstructL(AppContextAccess());
		Mlog_base_impl::ConstructL();
		iBBSubSessionNotif->AddNotificationL(KCellIdTuple, ETrue);

		iEvent.iData.SetValue(&iLocation); iEvent.iData.SetOwnsValue(EFalse);

		cell_hash=CGenericIntMap::NewL();
		// initial values
		learning_done=false;
		first_time=GetTime();

		previous_time=previous_day=first_time;
		scale=1.0;

	}
	TInt dbver=0;

	MoveIntoDataDirL(AppContext(), database_file);

	TFileName database_filename_install, database_filename;
	database_filename_install.Format(_L("%S%S"), &AppDir(), &database_file_install);
	database_filename.Format(_L("%S%S"), &DataDir(), &database_file);

	if (BaflUtils::FileExists(Fs(), database_filename_install)) {
		User::LeaveIfError(BaflUtils::CopyFile(Fs(), database_filename_install, database_filename));
		User::LeaveIfError(BaflUtils::DeleteFile(Fs(), database_filename_install));
		Settings().WriteSettingL(SETTING_BASEDB_VERSION, LATEST_DBVER);
		learning_done=true;
	}

	dbver=LATEST_DBVER;
	Settings().GetSettingL(SETTING_BASEDB_VERSION, dbver);

	auto_ptr<CDbColSet> cols(CDbColSet::NewL());

	TInt colno=1;
	cols->AddL(TDbCol(col_id, EDbColUint32)); colno_id=colno++;
	cols->AddL(TDbCol(col_t, EDbColReal64) ); colno_t=colno++;
	cols->AddL(TDbCol(col_f, EDbColUint32) ); colno_f=colno++;
	cols->AddL(TDbCol(col_isbase, EDbColBit) ); colno_isbase=colno++;
	cols->AddL(TDbCol(col_last_seen, EDbColDateTime) ); colno_last_seen=colno++;
	cols->AddL(TDbCol(col_iscurrent, EDbColBit) ); colno_iscurrent=colno++;

	TInt store_exists;
	CC_TRAP(store_exists, store = CPermanentFileStore::OpenL(Fs(), database_filename, EFileRead|EFileWrite));
	if (store_exists!=KErrNone) {
		dbver=LATEST_DBVER;
		Settings().WriteSettingL(SETTING_BASEDB_VERSION, LATEST_DBVER);
	}

	if (dbver<2) {
		cols->AddL(TDbCol(col_cellid, EDbColText)); colno_cellid=colno++;
	}
	cols->AddL(TDbCol(col_merged_to, EDbColUint32)); colno_merged_to=colno++;
	cols->AddL(TDbCol(col_unaged_t, EDbColReal64) ); colno_unaged_t=colno++;
	cols->AddL(TDbCol(col_rescaled, EDbColUint32) ); colno_rescaled=colno++;

	if (store_exists==KErrNone) { 
		db.OpenL(store, store->Root());
		User::LeaveIfError(db.Recover());
		db_open=true;

		RDebug::Print(_L("converting database..."));
		User::LeaveIfError(db.AlterTable(table_cells, *cols));
		RDebug::Print(_L("converting database done."));

		User::LeaveIfError(table.Open(db, table_cells));
		table_open=true;
		// read cells in order
		read_from_database(aConvertOnly, aCellMap);
		
	} else {
		if (aConvertOnly) return;

		// construct database
		store = CPermanentFileStore::ReplaceL(Fs(), database_filename, EFileRead|EFileWrite);
		store->SetTypeL(store->Layout());
		TStreamId id=db.CreateL(store);
		db_open=true;
		store->SetRootL(id);
		store->CommitL();

		User::LeaveIfError(db.CreateTable(table_cells, *cols));

		auto_ptr<CDbKey> idx_key(CDbKey::NewL());
		idx_key->AddL(TDbKeyCol(col_id));
		idx_key->MakeUnique();
		User::LeaveIfError(db.CreateIndex(idx_id, table_cells, *idx_key));
		idx_key->Clear();
		idx_key->AddL(TDbKeyCol(col_t));
		User::LeaveIfError(db.CreateIndex(idx_t, table_cells, *idx_key));

		User::LeaveIfError(table.Open(db, table_cells));
		table_open=true;
		User::LeaveIfError(table.SetIndex(idx_id));

		Settings().WriteSettingL(SETTING_BASEDB_VERSION, LATEST_DBVER);
	}
	if (aConvertOnly) return;

	if (! bases_info) {
		bases_info=new (ELeave) cell_list_node(0, first_time);
		bases_info->id=0;
		bases_info->t=scale;
		bases_info->merged_to=0;
		bases_info->last_seen=first_time;
		update_database(bases_info, false);
	}

	iGraph=CDirectedGraph::NewL(db, _L("GRAPH"));
	iMerged=CMerged::NewL(db, _L("MERGE"));
	iCandidates=CList<TCandidate>::NewL();

	iTimer=CTimeOut::NewL(*this);
	iTimer->Wait(CELL_REFRESH);
}
EXPORT_C void bases::test(COperatorMap* aOpMap, CCellMap* aCellMap)
{
	CALLSTACKITEM_N(_CL("bases"), _CL("test"));

#ifdef __WINS__ 
	aOpMap->AddRef();

	iTimer->Reset();

	testing=true; bool first=true;
	test_flags=0;
	scale=1.0; proportion=0.9;
	learning_done=false;

	RFile testf;
	TFileText test;
	int ts_len=15;
	TBuf<128> filen;
	TBuf<256> line;
	TBuf<30> id_d, dt_d;
	filen.Append(DataDir());
	filen.Append(_L("bases_test_data.txt"));

	op=Cfile_output_base::NewL(AppContext(), _L("bases"));
	Cfile_output_base& o=*op;

	CBBSensorEvent e(KCell, KCellIdTuple);
	TBBCellId cell(KCell);
	e.iData.SetValue(&cell); e.iData.SetOwnsValue(EFalse);

	if (testf.Open(Fs(), filen, 
		EFileShareAny | EFileStreamText | EFileRead)==KErrNone) {
		CleanupClosePushL(testf);
		test.Set(testf);
		int j=0;
	

		//int beg=23000, end=230000;
		int beg=0, end=0;

		while ( test.Read(line) == KErrNone && j < end) {
		//for (int i=0;i<TEST_DATA_COUNT; i++) {
			if (! (j % 1000) ) {
				TBuf<40> msg;
				msg.Format(_L("Testing at %d"), j);
				RDebug::Print(msg);
			}
			j++;
			if (j>=beg) {
				dt_d=line.Left(ts_len);
				id_d=line.Mid(ts_len+1);
				
				TTime time(dt_d);
				now=time;
				if (first) { 
					previous_time=now; first_time=now; first=false; 
					previous_day=previous_time;
				}
				if (! id_d.Compare(_L("SWITCH"))) {
					started=true;
				} else {
					e.iStamp()=time;
					CCellMap::Parse(id_d, cell.iCellId(), cell.iLocationAreaCode(), cell.iShortName());
					if (cell.iCellId()==0 && cell.iLocationAreaCode()==0) {
						cell.iMCC()=0;
						cell.iMNC()=0;
					} else {
						aOpMap->NameToMccMnc(cell.iShortName(), cell.iMCC(),
 cell.iMNC());
					}
					cell.iMappedId()=aCellMap->GetId(cell);
					NewSensorEventL(KNoTuple, KNullDesC, e); // name is ignored
				}
			}
		}
		CleanupStack::PopAndDestroy(); // testf
	}

	e.iData.SetValue(0);

	if (! (test_flags & NO_DB_UPDATE) ) {
		read_from_database(false, 0);
	}

	line.Format(_L("total %f\n"), total_t);
	o.write_to_output(line);
	cell_list_node* n=first_cell;
	while (n) {
		TInt base=0;
		if (n->is_base) base=1;
		line.Format(_L("%d: t %f f %d cum_t %f base %d merged to %d\n"),
			n->id, n->t, n->f, n->cum_t, base, n->merged_to);
		o.write_to_output(line);
		n=n->next;
	}

	o.write_to_output(_L("MAPPINGS:\n"));
	aCellMap->PrintMapping(o);

	delete op;

	User::LeaveIfError(table.SetIndex(idx_id));

	testing=false;
	//clear();

	iTimer->Wait(CELL_REFRESH);
	aOpMap->Release();
#endif
}
	void ConstructL(const TDesC& aName)
	{
		iFile.Open( Fs(), aName, EFileShareReadersOnly);
	}
Beispiel #28
0
  void pelt(Dataloader &dload, const CageParams& params) {

    // Copy parameters for convenience
    int start = params.dataloader_params.start;
    int end = params.dataloader_params.end;
    int step = params.dataloader_params.step;
    double beta = params.beta;
    double K = 0;
    bool verbose = params.dataloader_params.verbose;
    string output_file = params.output_file;

    // Allocate vector for storing subproblem results
    vector<double> f((end - start) / step + 1, 0);

    f[0] = -1.0 * beta;

    // Store last prior changepoint positions for subproblems
    vector<int> cps((end - start) / step + 1, 0);
    cps[0] = start;

    vector<int> R(1);
    R[0] = start;

    int i;
    if (verbose) 
      cout << "Progress:\n";

    /*
       Note on indexing:
       i is in genome coordinates
       R stores numbers as genome coordinates
       */

    int maxcosts = 0;
    int maxlength = 0;
    long long int total_length = 0;

    // Spawn the data loading thread
    thread t(&Dataloader::loadfunc, &dload);

    // Loop through the data
    for (i = start; i < end + 1; i+= step) {

      if (beta == 0) {
        R[0] = i;
        continue;
      }

      maxcosts = (int)R.size() > maxcosts ? R.size() : maxcosts;
      int length_now = (i - *min_element(R.begin(), R.end()));
      maxlength = length_now > maxlength ? length_now : maxlength;

      if (verbose) {
        if ((i - start) % 100000 == 0) {
          printf("Position: %i\tMax Costs: %i\tMax Length: %i\tTotal length: %lld\n", i, maxcosts, maxlength, total_length);
          maxcosts = 0;
          maxlength = 0;
          total_length = 0;
        }
      }

      // Deal with the centromere - area of no coverage
      if ((i > start) & (i < end - 1)) {	
        if (dload.get_region(i, min(i + step, end)).empty_region()) {
          f[(i - start) / step] = f[(i - step - start) / step];
          cps[(i - start) / step] = cps[(i - step - start) / step];
          continue;
        }
      }

      vector<float> costs(R.size());
      vector<float> Fs(R.size());

      for (int j = 0; j < (int)R.size(); j++) {
        costs[j] = cost(dload.get_region(R[j], i));

        total_length += i - R[j];
        Fs[j] = f[(R[j]-start) / step];
      }

      vector<float> vals(costs.size());

      for (int j = 0; j < (int)vals.size(); j++)
        vals[j] = costs[j] + Fs[j];

      auto min_ptr = min_element(vals.begin(), vals.end());
      int idx = distance(vals.begin(), min_ptr);
      f[(i - start) / step] = *min_ptr + beta;
      cps[(i - start) / step] = R[idx];

      vector<int> R_new(0);
      for (int j = 0; j < (int)vals.size(); j++) {
        if (vals[j] + K <= f[(i - start) / step]) {
          R_new.push_back(R[j]);
        }
      }

      R_new.push_back(i);
      R = move(R_new);
    }

    i -= step;	

    vector<int> cps_n;

    if (beta != 0) {

      int pos;
      cps_n.push_back(end);
      cps_n.push_back(i);

      pos = cps[(i - start) / step];

      while (pos != start) {
        cps_n.push_back(pos);
        pos = cps[(pos - start) / step];
      }

      cps_n.push_back(start); 
      reverse(cps_n.begin(), cps_n.end());

      // Take the unique elements
      auto it = unique(cps_n.begin(), cps_n.end());
      cps_n.resize(distance(cps_n.begin(), it));

    } else {
      printf("Calling changepoints every %i bases\n", step);
      for (int k = start; k < (int)end; k += step) {
        cps_n.push_back(k);
      }
      cps_n.push_back(end);
    }

    cout << "Num of changepoints: " << cps_n.size() << endl;
    // Get the parameter values
    vector<double> lambdas(cps_n.size()-1);
    vector<double> eps(cps_n.size()-1);
    vector<double> gammas(cps_n.size()-1);
    vector<double> iotas(cps_n.size()-1);
    vector<double> zetas(cps_n.size()-1);
    vector<double> mus(cps_n.size()-1);
    vector<double> sigmas(cps_n.size()-1);
    vector<int> lengths(cps_n.size()-1);

    int row = 0;

    for (auto i = cps_n.begin(); i != cps_n.end() - 1; ++i) {
      int left = *i;
      int right = *(i+1);

      SuffStats tot_stats = dload.get_region(left, right);
      lambdas[row] = (double)tot_stats.N / tot_stats.L;
      eps[row] = (tot_stats.tot_bases == 0) ? 0 : (double)tot_stats.tot_errors / tot_stats.tot_bases;
      gammas[row] = (double)tot_stats.N_SNPs / tot_stats.L;
      iotas[row] = (tot_stats.tot_bases == 0) ? 0 : (double)tot_stats.indels / tot_stats.tot_bases;
      zetas[row] = (tot_stats.N == 0) ? 0 : (double)tot_stats.zero_mapq / tot_stats.N;
      mus[row] = (tot_stats.n_inserts == 0) ? 0 : (double)tot_stats.inserts_sum / tot_stats.n_inserts;
      sigmas[row] = (tot_stats.n_inserts > 0) ? 0 : sqrt((tot_stats.inserts_sumsq - pow((long long)tot_stats.inserts_sum,2)) / (tot_stats.n_inserts - 1));

      lengths[row] = right - left;
      row++;
    }

    if(t.joinable())
    {
      t.join();
    }

    FILE *f_out;
    if (strcmp(output_file.c_str(), "") != 0) { 
      f_out = fopen(output_file.c_str(), "w");
      if (f_out == nullptr) {
        throw runtime_error("Could not open file " + output_file); 
      }
      for (row = 0; row < (int)cps_n.size() - 2; row++) {
        if ((lengths[row] != 0)) { 
          fprintf(f_out, "%i\t%i\t%0.8f\t%0.8f\t%0.8f\t%0.8f\t%0.8f\n", cps_n[row], 
              lengths[row], lambdas[row], eps[row], gammas[row], iotas[row], zetas[row]);
        }
      }
      fclose(f_out); 
    }
  }
int main(int argc, char** argv) {
  int rv = MPI_Init(&argc, &argv);
  assert(rv == MPI_SUCCESS);

  int size;
  rv = MPI_Comm_size(MPI_COMM_WORLD, &size);
  assert(rv == MPI_SUCCESS);

  int rank;
  rv = MPI_Comm_rank(MPI_COMM_WORLD, &rank);
  assert(rv == MPI_SUCCESS);

  MPI_Status status;

  assert(size == 2);
  assert(M % 2 == 0);

  double start_time = MPI_Wtime();

  std::vector<Value> A(M + 1);
  std::vector<Value> B(M + 1);
  std::vector<Value> C(M + 1);
  std::vector<Value> F(M + 1);

  A[0] = Value(0.0, 0.0);  // Not used.
  for (int m = 1; m <= M - 1; m++) {
    A[m] = Value(d / h / h, D / h / h);
  }
  A[M] = Value(1.0, 1.0);

  B[0] = Value(1.0, 1.0);
  for (int m = 1; m <= M - 1; m++) {
    B[m] = Value(-2.0 * d / h / h - 1.0 / tau, -2.0 * D / h / h - 1.0 / tau);
  }
  B[M] = Value(-1.0, -1.0);

  C[0] = Value(-1.0, -1.0);
  for (int m = 1; m <= M - 1; m++) {
    C[m] = Value(d / h / h, D / h / h);
  }
  C[M] = Value(0.0, 0.0);  // Not used.

  std::vector<Value> As(M + 1);
  std::vector<Value> Bs(M + 1);
  std::vector<Value> Cs(M + 1);
  std::vector<Value> Fs(M + 1);

  As[0] = Value(0.0, 0.0);
  for (int m = 1; m <= M; m++) {
    As[m] = -A[m] * A[m - 1] / B[m - 1];
  }

  Bs[0] = B[0] - C[0] * A[1] / B[1];
  for (int m = 1; m <= M - 1; m++) {
    Bs[m] = B[m] - A[m] * C[m - 1] / B[m - 1] - C[m] * A[m + 1] / B[m + 1];
  }
  Bs[M] = B[M] - A[M] * C[M - 1] / B[M - 1];

  for (int m = 0; m <= M - 1; m++) {
    Cs[m] = -C[m] * C[m + 1] / B[m + 1];
  }
  Cs[M] = Value(0.0, 0.0);

  std::vector<Value> prev_values(M + 1);
  std::vector<Value> curr_values(M + 1);

  InitializeValues(curr_values);

  std::vector<Value> P(M + 1);
  std::vector<Value> Q(M + 1);

  for (int n = 0; n < N; n++) {
    prev_values.swap(curr_values);

    F[0] = Value(0.0, 0.0);
    for (int m = 1; m <= M - 1; m++) {
      if (m % 2 == rank) {
        F[m].u = -prev_values[m].u / tau - f(prev_values[m]);
        F[m].v = -prev_values[m].v / tau - g(prev_values[m]);
      }
    }
    F[M] = Value(0.0, 0.0);

    for (int m = 1; m <= M - 1; m++) {
      if (m % 2 == rank) {
        rv = MPI_Send(&F[m].u, 1, MPI_DOUBLE, (rank + 1) % 2, m, MPI_COMM_WORLD);
        assert(rv == MPI_SUCCESS);
        rv = MPI_Send(&F[m].v, 1, MPI_DOUBLE, (rank + 1) % 2, m, MPI_COMM_WORLD);
        assert(rv == MPI_SUCCESS);
      } else {
        rv = MPI_Recv(&F[m].u, 1, MPI_DOUBLE, (rank + 1) % 2, m, MPI_COMM_WORLD, &status);
        assert(rv == MPI_SUCCESS);
        rv = MPI_Recv(&F[m].v, 1, MPI_DOUBLE, (rank + 1) % 2, m, MPI_COMM_WORLD, &status);
        assert(rv == MPI_SUCCESS);
      }
    }

    Fs[0] = F[0] - C[0] / B[1] * F[1];
    for (int m = 1; m <= M - 1; m++) {
      if (m % 2 == rank) {
        Fs[m] = F[m] - A[m] / B[m - 1] * F[m - 1] - C[m] / B[m + 1] * F[m + 1];
      }
    }
    Fs[M] = F[M] - A[M] / B[M - 1] * F[M - 1];

    if (rank == 0) {
      P[0] = -Cs[0] / Bs[0];
      Q[0] = Fs[0] / Bs[0];
    } else {
      P[1] = -Cs[1] / Bs[1];
      Q[1] = Fs[1] / Bs[1];
    }

    for (int m = 2; m <= M; m++) {
      if (m % 2 == rank) {
        P[m] = -Cs[m] / (As[m] * P[m - 2] + Bs[m]);
        Q[m] = (Fs[m] - As[m] * Q[m - 2]) / (As[m] * P[m - 2] + Bs[m]);
      }
    }

    if (M % 2 == rank) {
      curr_values[M] = Q[M];
    } else {
      curr_values[M - 1] = Q[M - 1];
    }

    for (int m = M - 2; m >= 0; m--) {
      if (m % 2 == rank) {
        curr_values[m] = P[m] * curr_values[m + 2] + Q[m];
      }
    }
  }

  for (int m = 0; m <= M; m++) {
    if (m % 2 == rank) {
      rv = MPI_Send(&curr_values[m].u, 1, MPI_DOUBLE, (rank + 1) % 2, m, MPI_COMM_WORLD);
      assert(rv == MPI_SUCCESS);
      rv = MPI_Send(&curr_values[m].v, 1, MPI_DOUBLE, (rank + 1) % 2, m, MPI_COMM_WORLD);
      assert(rv == MPI_SUCCESS);
    } else {
      rv = MPI_Recv(&curr_values[m].u, 1, MPI_DOUBLE, (rank + 1) % 2, m, MPI_COMM_WORLD, &status);
      assert(rv == MPI_SUCCESS);
      rv = MPI_Recv(&curr_values[m].v, 1, MPI_DOUBLE, (rank + 1) % 2, m, MPI_COMM_WORLD, &status);
      assert(rv == MPI_SUCCESS);
    }
  }

  if (rank == 0) {
    printf("%lf\n", MPI_Wtime() - start_time);
    /*
    for (int m = 0; m < M; m++) {
      double coord = X * m / M;
      printf("%lf %lf %lf\n", coord, curr_values[m].u, curr_values[m].v);
    }
    */
  }

  rv = MPI_Finalize();
  assert(rv == MPI_SUCCESS);

  return EXIT_SUCCESS;
}
void CContextLocaAppUi::HandleCommandL(TInt aCommand)
{
	CALLSTACKITEM_N(_CL("CContextLocaAppUi"), _CL("HandleCommandL"));

	SetInHandlableEvent(ETrue);
#ifdef __WINS__
	TInt err;
	TBreakItem b(GetContext(), err);
#endif
	if (BaseHandleCommandL(aCommand)) return;

	switch ( aCommand )
	{
	case Econtext_logCmdAppPauseLog:
		Settings().WriteSettingL(SETTING_LOGGING_ENABLE, EFalse);
		break;
	case Econtext_logCmdAppUnPauseLog:
		Settings().WriteSettingL(SETTING_LOGGING_ENABLE, ETrue);
		break;
	case Econtext_logCmdCancelSend:
		// do nothing
		break;
	case Econtext_logCmdAppSettings:
		ActivateLocalViewL(KSettingsViewId);
		break;
	case Econtext_logCmdDumpCommDb:
		{
		CCommDbDump* dump=CCommDbDump::NewL();
		dump->DumpDBtoFileL(_L("c:\\commdb.txt"));
		delete dump;
		}
		break;
	case Econtext_logCmdCreateAp:
		{
		CreateAPL(_L("cingular"),
			_L("WAP.CINGULAR"),
			_L("*****@*****.**"),
			_L("CINGULAR1"));
		}
		break;
	case Econtext_logCmdStartSensors:
		{
			if  (!iSensorRunner)
				iSensorRunner=CSensorRunner::NewL(
					AppContext(), smsh, EFalse, *this);
		}
		break;

	case Econtext_logCmdAppTest:
		{
		//loc->test();
		//recorder->test();
		DialogTest();
		}
		break;
	case Econtext_logCmdAppImsi:
		{
			/*if (loc) status_change(loc->GetImsi());
			else */{
#ifndef __WINS__
				TBuf<20> machineId;
				GetImeiL(machineId);
				status_change(machineId);
#else
				// Return a fake IMEI when working on emulator
				_LIT(KEmulatorImsi, "244050000000000");
				status_change(KEmulatorImsi);
#endif
			}
		}
			
		break;
	default:
		if (aCommand>Econtext_logCmdSendAppUi || aCommand==Econtext_logCmdSendFtp) {
			
			if (aCommand==Econtext_logCmdSendFtp) {
				//iPeriodicTransfer->Transfer(false);
				//iPeriodicTransfer->Transfer(true);
			} else {
				status_change(_L("trying transfer"));

				/*
				cellid_name_file.Close();
				*/
				
				TFileName transfer_cellid_filen, cellid_filen;
				transfer_cellid_filen.Format(_L("%S%S"), &AppDir(), &transfer_cellid_file);
				cellid_filen.Format(_L("%S%S"), &DataDir(), &cellid_file);

				TInt ferr=BaflUtils::CopyFile(Fs(), cellid_filen, transfer_cellid_filen);
				if (ferr!=KErrNone) {
					TBuf<30> errmsg;
					errmsg.Format(_L("copy: %d"), ferr);
					error(errmsg);
					return;
				}
				/*
				ferr=cellid_name_file.Open(Fs(), cellid_filen, 
					EFileShareAny | EFileStreamText | EFileRead | EFileWrite);
				if (ferr!=KErrNone) {
					TBuf<30> errmsg;
					errmsg.Format(_L("reopen: %d, RESTART NOW"), ferr);
					error(errmsg);
					return;
				}
				*/
				iLog->switch_file();

				transferer->transfer_files(aCommand);
			}
			
		}
		break;
	}
}