Overview of Perugia Football Team
Perugia Calcio, commonly known as Perugia, is a professional football club based in Perugia, Italy. The team competes in Serie C, the third tier of Italian football. Founded in 1905, Perugia has a rich history and is managed by current head coach Alessandro Calori. Known for their passionate fanbase and competitive spirit, they play at the Stadio Renato Curi.
Team History and Achievements
Perugia boasts a storied history with notable achievements including multiple promotions to Serie A, Italy’s top division. They have secured titles such as the Serie B championship and have consistently been strong contenders in their league. Notable seasons include their remarkable performances during the late 1980s and early 2000s.
Current Squad and Key Players
The current squad features standout players like Lorenzo Lucca, who plays as a forward. Other key players include midfielders Marco Pecorari and defender Luca Garritano. These players are crucial to the team’s strategy and performance on the field.
Team Playing Style and Tactics
Perugia typically employs a 4-3-3 formation, focusing on a balanced approach between defense and attack. Their strategy emphasizes quick transitions and exploiting spaces through dynamic wing play. Strengths include solid defensive organization and fast counter-attacks, while weaknesses may arise from occasional lapses in midfield control.
Interesting Facts and Unique Traits
The club is affectionately nicknamed “Gialloblù,” reflecting their traditional yellow-blue colors. Perugia has a dedicated fanbase known for their vibrant support during matches. Rivalries with local teams add to the excitement of their fixtures.
Lists & Rankings of Players, Stats, or Performance Metrics
- Lorenzo Lucca: Top goal scorer ✅
- Marcus Diniz: Rising star 🎰
- Alessandro Calori: Tactical mastermind 💡
Comparisons with Other Teams in the League or Division
Compared to other Serie C teams, Perugia stands out for its consistent performance and ability to compete against higher-tier opponents due to their strategic gameplay and experienced squad.
Case Studies or Notable Matches
A memorable match was their victory against Ternana in 2019, showcasing their tactical prowess and resilience under pressure. This game highlighted key players’ impact on crucial moments.
Betwhale Table: Team Stats Summary
| Statistic | Value | ||||
|---|---|---|---|---|---|
| Total Goals Scored This Season | 45 | ||||
| Total Wins This Season | 12 | ||||
| Total Draws This Season | 8 | ||||
| Total Losses This Season | 6 | ||||
| Last Five Match Form (W/D/L) | W-W-D-L-W | ||||
| Average Goals per Match | 1.8 | ||||
| Average Goals Conceded per Match | 1.1 | ||||
| Head-to-Head Record Against Key Rivals: | |||||
| Rival Team Name: | Last Five Matches (W/D/L) | ||||
| Ternana: | D-W-L-W-D | ||||
| Current Odds for Next Match: | |||||
| Odds Type: | Odds Value: | ||||
| To Win: | +150 (1.50)(150%) (15/10) (15/10)(15/10)(15/10)(15/10)(15/10)(15/10)(15/10)(15/10)(15/10) +150
) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) | To Draw:</dt | +200 (as odds value placeholder) | To Lose:</dt | +100 (as odds value placeholder) |
| *Odds provided by Betwhale! | |||||
Tips & Recommendations for Betting Analysis on Perugia 🎯💡📊📈🚀⚽️🏆💰💸🤑🔍🧐⚖️📝✍️❓❗️😉😊😁😀😎😍💕❤️♡💘💋💞💗💜💙💛❤️🔥☺️😃😄😁😆😉😊🙂🙃☺️⚖️✌️✍️✔️✅☑️✳️✴️➕➖➗×÷±≠≈≡≤≥⌘⌥⇧⇪⇫⇬↩↪↫↬↭↮↯↰↱↲↳↴↵↑↓←→↔↕⤴⤵⤶⤷⤸⤹⤺⤻◀▶◢◣○●▪▫▭■▿▾△▲▼◼◽◾❌✂︎♻︎♿♾♿♈♉♊♋♌♍♎♏♐♑♒♓★☆☀︎☁︎☂︎☃︎☄︎☽☾♀♂☉☽☾♀℃℉°♪►◄●●●●●●●●
+150 (+150) (+150) (+150) (+150) (+150) (+150) (+150) (+150) (+150) +200 +100 💡 Analyze recent form trends before placing bets.
- Analyze head-to-head records against upcoming opponents.
- Favor betting on draws when facing defensively strong teams.
>
- Carefully consider odds fluctuations leading up to match day.
>
- Leverage player statistics to predict potential game-changers.
>
- Evaluate coaching strategies that might influence game outcomes.
>
- Prioritize understanding team morale based on recent results.
>
- Maintain awareness of injuries or suspensions affecting key players.
>
- Analyze weather conditions potentially impacting gameplay dynamics.
>
- Incorporate expert opinions into your betting strategy for added insight.
>
Betwhale Table: Recent Form Summary ⚽ 📈 📉 🔝 ⬇ 👀 💭 ⚖ ➡ ⬅ ✅ ❌ ✔ ➕ ➖ ➗ × ÷ ± ≠ ≈ ≡ ≤ ≥ ⌘ ⌥ ⇧ ⇪ ⇫ ⇬ ↩ ↪ ↫ ↬ ↭ ↮ ↯ ↰ ↱ ↲ ↳ ↴ ↑ ↓ ← → ↔ ↑ ↓ 🔝 🔽 👀 💭 ⚖ ➡ ⬅ ✅ ❌ ✔ ➕ ➖ ➗ × ÷ ± ≠ ≈ ≡ ≤ ≥
Recent Form Summary Table for Betting Analysis!
Date Played:</t[0]: import numpy as np
[1]: import pandas as pd
[2]: from sklearn.base import BaseEstimator
[3]: from sklearn.utils.validation import check_is_fitted
[4]: class TargetEncoder(BaseEstimator):
[5]: """
[6]: Encode categorical features using target statistics.
[7]: Parameters
[8]: ———-
[9]: columns : list of str
[10]: List of column names to encode.
[11]: encoding_method : str
[12]: Encoding method:
[13]: – 'mean': mean target value for each category.
[14]: – 'weighted_mean': weighted average between category mean target value,
[15]: overall mean target value.
[16]: Default is 'mean'.
[17]: prior : float
[18]: Weight of prior training data when calculating weighted averages with
[19]: 'encoding_method' == 'weighted_mean'. Default is 5.
***** Tag Data *****
ID: 1
description: Class definition implementing custom target encoding using advanced techniques.
start line: 4
end line: 20
dependencies:
– type: Class
name: TargetEncoder
start line: 4
end line: 20
context description: This class provides an advanced method for encoding categorical
features using target statistics which can be beneficial for machine learning models.
algorithmic depth: 4
algorithmic depth external: N
obscurity: 4
advanced coding concepts: 4
interesting for students: 5
self contained: Y
*************
## Suggestions for complexity
1. **Dynamic Encoding Methods**: Implement additional encoding methods dynamically based on user-defined functions passed at runtime rather than hardcoding them into the class.
2. **Multi-level Target Encoding**: Extend the encoder to handle multi-level categorical variables where categories have hierarchical relationships.
3. **Cross-validation Support**: Modify the encoder so that it supports cross-validation within itself by splitting data internally without leaking information between folds.
4. **Parallel Processing**: Enable parallel processing capabilities within the `TargetEncoder` class to handle large datasets more efficiently by leveraging multi-threading or distributed computing frameworks like Dask.
5. **Custom Weight Functions**: Allow users to provide custom weight functions instead of just using a fixed prior weight when calculating weighted averages.
## Conversation
:I’m trying understand how I can extend this [SNIPPET] code so it supports user-defined encoding methods at runtime instead of just having ‘mean’ or ‘weighted_mean’. Can you help?
:Sure! To allow user-defined encoding methods at runtime, you can modify your `TargetEncoder` class to accept callable functions as encoding methods along with predefined ones like `’mean’` or `’weighted_mean’`. Here’s how you could do it:
python
class TargetEncoder(BaseEstimator):
“””
Encode categorical features using target statistics.
Parameters:
columns : list of str – List of column names to encode.
encoding_method : str or callable – Encoding method:
– ‘mean’: mean target value for each category.
– ‘weighted_mean’: weighted average between category mean target value,
overall mean target value.
– callable function that takes two arguments (category values, target values).
Default is ‘mean’.
prior : float – Weight of prior training data when calculating weighted averages with
‘encoding_method’ == ‘weighted_mean’. Default is 5.
“””
def __init__(self, columns=None, encoding_method=’mean’, prior=5):
self.columns = columns if columns else []
self.encoding_method = encoding_method if isinstance(encoding_method, str) else None # If not string assume it’s callable later on
self.prior = prior
def fit(self, X, y):
if isinstance(self.encoding_method, str):
if self.encoding_method == ‘mean’:
self._fit_mean(X,y)
elif self.encoding_method == ‘weighted_mean’:
self._fit_weighted_mean(X,y)
else:
raise ValueError(“Unsupported encoding method”)
else:
# Assume it’s a callable function provided by user at runtime
self.encoder_function = self.encoding_method
def _fit_mean(self,X,y):
# Implementation remains same
def _fit_weighted_mean(self,X,y):
# Implementation remains same
def transform(self,X):
if hasattr(self,’encoder_function’):
return self.encoder_function(X,self.target_stats_)
else:
# Existing logic here
def fit_transform(self,X,y):
self.fit(X,y)
return self.transform(X)
# Example usage:
def custom_encoder(cat_values,target_values):
# User defined logic here
pass
encoder = TargetEncoder(columns=[‘column_name’],encoding_method=custom_encoder)
This allows flexibility while still maintaining backward compatibility with predefined methods.
:Thanks! Now I want add support for multi-level categorical variables where categories have hierarchical relationships within this encoder any ideas?
:To handle multi-level categorical variables with hierarchical relationships within your `TargetEncoder`, you’ll need an approach that respects these hierarchies during encoding.
Here’s an outline approach:
1. Define a hierarchy structure.
2. Aggregate statistics respecting this hierarchy during fitting.
3. Apply these aggregated statistics during transformation.
Here’s how you could modify your existing `TargetEncoder`:
python
class TargetEncoder(BaseEstimator):
“””
Encode categorical features using target statistics considering hierarchical relationships.
Parameters:
columns : list of str – List of column names to encode.
hierarchy : dict – Dictionary specifying hierarchical relationships among categories.
encoding_method : str or callable – Encoding method (same as before).
prior : float – Weight of prior training data when calculating weighted averages with
‘encoding_method’ == ‘weighted_mean’. Default is 5.
“””
def __init__(self, columns=None,hierarchy=None ,encoding_method=’mean’,prior=5):
self.columns = columns if columns else []
self.hierarchy = hierarchy if hierarchy else {}
self.encoding_method = encoding_method if isinstance(encoding_method,str) else None
self.prior=prior
def fit(self,X,y):
if isinstance(self.encoding_method,str):
if self.encoding_method==’mean’:
self._fit_hierarchical_mean(X,y)
elif self.encoding_method==’weighted_mean’:
self._fit_hierarchical_weighted_mean(X,y)
else:
raise ValueError(“Unsupported encoding method”)
else:
# Assume it’s a callable function provided by user at runtime
self.encoder_function=self.encoding_method
def _aggregate_hierarchy_stats(self,X,y,column,hierarchy_level=None):
# Recursive aggregation respecting hierarchy levels
unique_vals=np.unique(X[column])
stats=dict()
if hierarchy_level==None:
hierarchy_level=self.hierarchy.get(column,None)
if hierarchy_level!=None:
parent_levels=hierarchy_level.split(‘>’)
parent_vals=[X[column].copy()]
for parent_level in parent_levels[::-1]:
parent_vals=[parent_val[parent_level]for parent_val in parent_vals]
parent_vals=pd.concat(parent_vals,axis=0).unique()
agg_target=y.groupby(parent_vals).agg([‘count’,’sum’])
stats.update({val:(agg_target.loc[val][‘sum’]/agg_target.loc[val][‘count’])for val in parent_vals})
unique_vals=[val[parent_level]for val in unique_vals]
return stats
def _fit_hierarchical_mean(self,X,y):
# Calculate hierarchical means
stats=dict()
for col in set(self.columns).intersection(set(X.columns)):
stats[col]=self._aggregate_hierarchy_stats(X=X,y=y,column=col)
setattr(self,’target_stats_’,stats)
def _fit_hierarchical_weighted_mean(self,X,y):
# Similar logic but also incorporating prior weights
stats=dict()
overall_target_sum=y.sum()
overall_target_count=len(y)
overall_target_ratio=overall_target_sum / overall_target_count
for col in set(self.columns).intersection(set(X.columns)):
cat_stats=self._aggregate_hierarchy_stats(X=X,y=y,column=col)
new_cat_stats={}
cat_count=len(cat_stats.keys())
cat_prior_sum=self.prior * overall_target_ratio * cat_count
cat_prior_count=self.prior * cat_count
new_cat_stats={cat:(cat_stat*(cat_count+self.prior)+(cat_prior_sum-cat_stat*cat_prior_count))/(cat_count+self.prior)
for cat,(cat_stat,count)in zip(cat_stats.keys(),zip(cat_stats.values(),np.ones(len(cat_stats))*self.prior))}
stats.update(new_cat_stats)
setattr(self,’target_stats_’,stats)
def transform(self,X):
X_=X.copy()
encoded_cols=[]
if hasattr(self,’encoder_function’):
encoded_cols=[col+’_encoded’for col in set(encoded_cols).intersection(set(X.columns))]
X_[encoded_cols]=self.encoder_function(X[self.columns],self.target_stats_)
else:
encoded_cols=[col+’_encoded’for col in set(encoded_cols).intersection(set(X.columns))]
X_[encoded_cols]=[X_[col].map(lambda x:self.target_stats_[col][x])if col in set(encoded_cols)
else X_[col]for col in X_.columns]
return X_
# Example usage:
# Defining hierarchy where one level > another level indicates sub-category relationship e.g., Country > State > City
hierarchy={
“location”: “Country > State > City”
}
encoder = TargetEncoder(columns=[‘location’], hierarchy=hierarchy ,encoding_method=’mean’)
In this code snippet:
– The `_aggregate_hierarchy_stats` method recursively aggregates statistics according to specified hierarchies.
– The `_fit_hierarchical_*` methods calculate means considering these hierarchies during fitting.
This way you respect hierarchical relationships while computing your encodings.
1e6; // Number used when dividing total gas mass into cells
//double Mtot = m_gas_mass * ncell;
double Mtot = m_gas_mass;
for(int i=0;i<m_nCell;i++)
{
m_cellMass[i] = Mtot / ncell;
}
m_massCenter.resize(m_nCell);
m_centerOfMass.resize(3);
double totMass = m_gas_mass;
for(int i=0;i=0;i–)
{
totMass += m_cellMass[i];
m_centerOfMass[i] = massSum / totMass;
massSum -= m_cellMass[i];
}
}
void GasSolver::setBoundaryCondition()
{
int nFaceNum[] =
{
// Cube
// Front
FFRONT,
FBACK,
// Right
FRIGHT,
FLEFT,
// Top
FTOP,
FBOTTOM,
// Sphere
FSURF,
// Cylinder
FCYL_INNER,
FCYL_OUTER,
#if defined(_EIGEN_) || defined(_PARDISO_)
FEIGEN_INNER,
FEIGEN_OUTER,
#endif
#if defined(_SMC_)
FSMC_INNER,
FSMC_OUTER,
#endif
#if defined(_HYDRO_)
FCONVEX_INNER,
FCONVEX_OUTER,
#endif
FMAX_FACE_NUM
};
std::vector::iterator iterFaceNum;
for(iterFaceNum=m_faceIndex.begin();iterFaceNum!=m_faceIndex.end();iterFaceNum++)
{
#if defined(_EIGEN_) || defined(_PARDISO_)
int numFaces[Eigen::MaxFace];
#elif defined(_SMC_)
int numFaces[SphereMesh::MaxFace];
#elif defined(_HYDRO_)
int numFaces[CylinderMesh::MaxFace];
#else
int numFaces[SphereMesh::MaxFace];
#endif
switch(*iterFaceNum)
{
#if defined(_EIGEN_) || defined(_PARDISO_)
case FEIGEN_INNER:
case FEIGEN_OUTER:
EigenMesh::getFaces(numFaces,*iterFaceNum);
break;
#elif defined(_SMC_)
case FSMC_INNER:
case FSMC_OUTER:
SphereMesh::getFaces(numFaces,*iterFaceNum);
break;
#elif defined(_HYDRO_)
case FCONVEX_INNER:
case FCONVEX_OUTER:
CylinderMesh::getFaces(numFaces,*iterFaceNum);
break;
#else
default:
SphereMesh::getFaces(numFaces,*iterFaceNum);
break;
#endif
}
std::vector::iterator iterCells;
std::vector::iterator iterPressure;
std::vector::iterator iterVelocity;
std::vector::iterator iterTemperature;
int cellIndex[Eigen::MaxCell];
double pressure[Eigen::MaxCell];
double velocity[Eigen::MaxDim][Eigen::MaxCell];
double temperature[Eigen::MaxCell];
#pragma omp parallel private(iterCells)
{
#pragma omp single nowait
{
#pragma omp taskloop simd collapse(3)
for(int j=0;j<EigenMesh::_nDim;j++)
for(int k=0;k<EigenMesh::_nDim;k++)
for(int i=numFaces[k];i<numFaces[k+1];i++)
cellIndex[i-EigenMesh::_nDim*k-k]=EigenMesh::_cellIndex[j][i-EigenMesh::_nDim*k-k];
#pragma omp taskloop simd collapse(3)
for(int j=0;j<EigenMesh::_nDim;j++)
for(int k=0;k<EigenMesh::_nDim;k++)
for(int i=numFaces[k];i<numFaces[k+1];i++)
pressure[i-EigenMesh::_nDim*k-k]=m_pressure[cellIndex[i-EigenMesh::_nDim*k-k]];
#pragma omp taskloop simd collapse(3)
for(int j=0;j<EigenMesh::_nDim;j++)
for(int k=0;k<EigenMesh::_nDim;k++)
for(int i=numFaces[k];i<numFaces[k+1];i++)
for(int l=j;l<EigenMesh::_nDim;l++)velocity[l][i-EigenMesh::_nDim*k-k]=m_velocity[l][cellIndex[i-EigenMesh::_nDim*k-k]];
#pragma omp taskloop simd collapse(3)
for(int j=0;j<EigenMesh::_nDim;j++)
for(int k=0;k<EigenMesh::_nDim;k++)
for(int i=numFaces[k];i<numFaces[k+1];i++)temperature[i-EigenMesh::_nDim*k-k]=m_temperature[cellIndex[i-EigenMesh::_nDim*k-k]];
}
#pragma omp parallel private(iterCells)
{
#pragma omp single nowait
{
#pragma omp taskloop simd collapse(3)
for(int j=EigenvectorSolverBase_max_dim; j<_Ndim; j++ )
for(int k=EigenvectorSolverBase_max_dim; k<_Ndim; k++ )
for( int i=num_faces[k]; i<num_faces[k+1]; i++ )
cell_index[i-_max_dim*_max_dim*k-k]=_cell_index[j][i-_max_dim*_max_dim*k-k];
#pragma omp taskloop simd collapse(3)
for( int j=EigenvectorSolverBase_max_dim; j<_Ndim; j++ )
for( int k=EigenvectorSolverBase_max_dim; k<_Ndim; k++ )
for( int i=num_faces[k]; i<num_faces[k+1]; i++ )
pressure[i-_max_dim*_max_dim*k-k]=_pressure[cell_index[i-_max_dim*_max_dim*k-k]];
#pragma omp taskloop simd collapse(4)
for( int l=EigenvectorSolverBase_max_dim; l<_NDim_; l++ )
if(l!=j && l!=k)
velocity[l][i-_NDim_*_NDim_*k-k]=_velocity[l][cell_index[i-_NDim_*_NDim_*k-k]];
#pragma omp taskloop simd collapse(3)
for( int j=EigenvectorSolverBase_max_dim; j<_NDim_; j++ )
if(j!=k && j!=j)
velocity[j][i-_NDim_*_NDim_*k-k]=_velocity[j][cell_index[i-_NDim_*_NDim_*k-k]];
#pragma omp taskloop simd collapse(3)
if(k==j && k==j){
velocity[j][i-_NDim_*_NDim_*k-k]=-pressure[i-_NDim_*_NDim_*k]/sqrt(pressure)*density[cell_index]
+sqrt(pressure)/density[cell_index]*velocity[j][i-_NDim_*_NDim_*k];
continue;}
velocity[j][i-_ndimension*_ndimension*k]-=_pressure_velocity_coefficient*
(_normal_vector[j]*velocity[_dimension_-j]+_normal_vector[_dimension_-j]*velocity[j])[i-
_ndimension*_ndimension*k]/density[cell_index]+pressure*[NormalVector](j)*sqrt(pressure)/density[cell_index]
#pragma omp taskloop simd collapse(3)
else{velocity[j][i-_ndimension*_ndimension*k]-=_pressure_velocity_coefficient*
(_normal_vector[_dimension_-j]*velocity[_dimension_-j]+_normal_vector[_dimension_-j]*velocity[j])[_
_ndimension*_ndimension*i-i]/density[cell_index]+pressure*[NormalVector](j)*sqrt(pressure)/density[cell_
index]};
#pragma omp taskloop simd collapse(3)
temperature[i-num_faces[_MAX_DIM_] * _MAX_DIM_] =
temperature_old(cell_index(i-num_faces[_MAX_DIM_] *
_MAX_DIM_),temperature_old);}
}
// Set boundary condition according face number.
// Note that we only need care about inner boundary condition.
void GasSolver::setBoundaryConditionInner()
{
int nFaceNum[] =
{
#ifdef _EIGEN_
FEIGEN_INNER,
#else
FFRONT,
FBACK,
FRIGHT,
FLEFT,
FTOP,
FBOTTOM,
#ifdef _SPHERE_
FSURF,
#endif
#ifdef _CYLINDER_
FCYL_INNER,
#endif
#ifdef _SMC_
FSMC_INNER,
#endif
#ifdef _HYDRO_
FCONVEX_INNER,
#endif
#endif //_EIGEN_
};
std::vector::iterator iterFaceNum;
int nIterEnd=m_faceIndex.size();
int nIterBegin=nIterEnd-nIterEnd%sizeof(nFaceNum);
iterFaceNum=m_faceIndex.begin()+std::distance(m_faceIndex.begin(),m_iter);
while(iterFaceNum<nIterBegin+nIterEnd%sizeof(nFaceNum))
switch(*iterFaceNum-nIterBegin)%sizeof(nFaceNum){
case(FFRONT):
case(FBACK):
case(FRIGHT):
case(FLEFT):
case(FTOP):
case(FBOTTOM):
case(FSURF):
case(FCYL_INNER):
case(FSMC_INNER):
case(FCONVEX_INNER):
default:
break;}
}
void GasSolver ::setBoundaryConditionOuter()
{
int nFaceNumber[] =
#ifndef EIGEN_
{
FFRONT,FBACK ,FRIGHT,FLEFT ,FTOP ,FBOTTOM ,
#ifdef SPHERE_MESH_
Fsurf ,
#endif //_SPHERE_MESH_
#ifdef CYLINDER_MESH_
FCyl_outer ,
#endif //_CYLINDER_MESH_
#ifdef SMC_MESH_
FSmc_outer ,
#endif //_SMC_MESH_
#ifdef HYDRO_MESH_
FConvex_outer ,
#endif //_HYDRO_MESH_
};
#else //_EIGEN_
{
FEig_in,Feg_out ,
};
#endif //_EIGEN_
std :: vector:: iterator iter ;
iter=m_faceindex .begin () +std :: distance (m_faceindex . begin (),m_iter );
while(iter !=m_faceindex . end ())switch (*iter-m_faceindex . begin ()) % sizeof(nfaceNumber){
case(FFRONT):
case(FBACK):
case(FRIGHT):
case(FLEFT):
case (FTOP):
case(FBOTTOM):
case (FSURF):
case (FCYL_OUTTER):
case (FSMC_OUTTER):
case (FCONVEX_OUTTER):
default:
break ;}
}
void GasSolver ::setBoundaryConditionAll()
{
setBoundaryConditionInner();
setBoundaryConditionOuter();
}
int GasSolver :: getNeighborCell(const EigenVector &point,const EigenVector & normalVector,EigenVector ¢erPoint,EignMatrix &Jacobian,EignMatrix &invJacobian,int faceId,int cellId,bool outerFlag){
EignMatrix tempInvJacobian,tempJacobian,tempNormalVec,tempTangentVec,tempCenterPoint,tempPointInTriangle,deltaPoint,deltaPointInTriangle,tempCosTheta,tempSinTheta,scaleFactor,scaleFactorInTriangle;
EignMatrix tempNormalVec_Inner,EignMatrix tempTangentVec_Inner,EignMatrix tempCenterPoint_Inner,EignMatrix tempPointInTriangle_Inner,deltaPoint_Inner,deltaPointInTriangle_Inner,tempCosTheta_Inner,tempSinTheta_Inner,scaleFactor_Inner,scaleFactorInTriangle_Inner;
EignMatrix tempNormalVec_Outer,EignMatrix tempTangentVec_Outer,EignMatrix tempCenterPoint_Outer,EignMatrix tempPointInTriangle_Outer,deltaPoint_Outer,deltaPointInTriangle_Outer,tempCosTheta_Outer,tempSinTheta_Outer,scaleFactor_Outer,scaleFactorInTriangle_Outer;
bool innerFlag=false;
if(!outerFlag){tempNormalVec=tempNormalVec_Inner;tempTangentVec=tempTangentVec_Inner;tempCenterPoint=tempCenterPoint_Inner;}else{tempNormalVec=tempNormalVec_Outer;tempTangentVec=tempTangentVec_Outer;tempCenterPoint=tempCenterPoint_Outer;}
tempNormalVec.setZero();
tempCosTheta.setZero();tempSinTheta.setZero();scaleFactor.setZero();scaleFactorInTriangle.setZero();
deltaPoint.setZero();deltaPointInTriangle.setZero();
const EignVector center_point=getCellPosition(cellId);
tempNormalVec.col(faceId)=normalVector.col(faceId);
tempTangentVec.col(faceId)=tempNormalVec.col(faceId).cross(EignVector(EIGN_REAL(EIGN_PI*0.5),EIGN_REAL(EIGN_PI*0.),EIGN_REAL(EIGN_PI*-.5)));
tempCosTheta(col(faceid))=(center_point-point).dot(temp_normal_vec(col(faceid)))/(center_point-point).norm();
tempSinTheta(col(faceid))=(center_point-point).dot(temp_tangent_vec(col(faceid)))/(center_point-point).norm();
scale_factor(col(faceid))=(center_point-point).norm()*sqrt(temp_cos_theta(col(faceid)));
scale_factor_in_triangle(col(faceid))=(point-center_point)*sqrt(temp_cos_theta(col(faceid)));
delta_point=center_point-scale_factor*temp_normal_vec(point-center_point)/scale_factor.norm();
delta_point_in_triangle=center_point-scale_factor_in_triangle*temp_normal_vec(point-center_point)/scale_factor_in_triangle.norm();
temp_center_point=center_point-delta_point*scale_factor/scale_factor.norm();
temp_center_ptoin_inner=center_pont-deltapoint_inner*scale_factor_inner/scale_facto_inner.norm();
temp_center_ptoin_outer=center_pont-deltapoint_outer*scale_facto_outer/scale_facto_outer.norm();
if(!outerFlag){temp_center_ptoin=temp_center_ptoin_inner;}else{temp_center_ptoin=temp_center_ptoin_outer;}
centerpoint=temp_centreptoin;
Eignequation eignequation;
eignequation.solveEquation(delta_Poiyntemp_delta_Point_in_Triangle);
return cell_id;}
ChangxinZhu/GasDynSimulator>modeltype;
model.setType(modeltype.c_str());
switch(model.getType()){
default:model.setType(GAS_MODEL_EULER);break;}
model.initParameter(file);}
static void getParameters(GasModel& model,string filename){
stdifstream file(filename.c_str());
getParameters(model,file);}
static void saveParameters(GasModel& model,stdofstream& file){
file<<model.getType()<grid_map->grid_model;}ChangxinZhu/GasDynSimulator<|file_sep
/*
Copyright © Changxin Zhu
This software is licensed under BSD License.
Redistribution and use in source forms are permitted provided that this
header remains intact.
Redistribution and use in binary form are permitted provided that
this header remains intact.
THIS SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND.
*/
#ifndef GDSIMULATIONLIB_GASMESH_H_INCLUDED__A28B96A6_B782_4097_AEEB_DFFB91BAAB00__
#define GDSIMULATIONLIB_GASMESH_H_INCLUDED__A28B96A6_B782_4097_AEEB_DFFB91BAAB00__
#include"GDSimulationLibConfig.h"
#include"Eigsolver_base.h"
namespace GDSimulationLib {
class GASMESH_EXPORT GasGrid {
public:
GasGrid(){}
virtual ~GasGrid(){}
protected:
private:
};
templateclass GASMESH_EXPORT MeshTemplate :
public Eigensolver_base {
public:
typedef typename Eigensolver_base base_type ;
typedef typename base_type :: CellType CellType ;
typedef typename base_type :: FaceType FaceType ;
typedef typename base_type :: EdgeType EdgeType ;
typedef typename base_type :: VertexType VertexType ;
typedef typename base_type :: ElementType ElementType ;
MeshTemplate() {}
virtual ~ MeshTemplate() {}
protected:
private:
};
template class GASMESH_EXPORT MeshTemplate
{
};
template class GASMESH_EXPORT MeshTemplate{};
template class GASMESH_EXPORT MeshTemplate{};
template class GASMESH_EXPORT MeshTemplate{};
template class GASMESH_EXPORT MeshTemplate{};
};//namespace GDSimulationLib
#define ENSURE_MEMLEAKS(classname){classname *_ptr=new classname;if(!_ptr){cerr<<"Error allocating memory"<<endl
>
>
>
>
>
>
>
>
Betwhale Table: Recent Form Summary ⚽ 📈 📉 🔝 ⬇ 👀 💭 ⚖ ➡ ⬅ ✅ ❌ ✔ ➕ ➖ ➗ × ÷ ± ≠ ≈ ≡ ≤ ≥ ⌘ ⌥ ⇧ ⇪ ⇫ ⇬ ↩ ↪ ↫ ↬ ↭ ↮ ↯ ↰ ↱ ↲ ↳ ↴ ↑ ↓ ← → ↔ ↑ ↓ 🔝 🔽 👀 💭 ⚖ ➡ ⬅ ✅ ❌ ✔ ➕ ➖ ➗ × ÷ ± ≠ ≈ ≡ ≤ ≥
| Recent Form Summary Table for Betting Analysis! |
|---|
[1]: import pandas as pd
[2]: from sklearn.base import BaseEstimator
[3]: from sklearn.utils.validation import check_is_fitted
[4]: class TargetEncoder(BaseEstimator):
[5]: """
[6]: Encode categorical features using target statistics.
[7]: Parameters
[8]: ———-
[9]: columns : list of str
[10]: List of column names to encode.
[11]: encoding_method : str
[12]: Encoding method:
[13]: – 'mean': mean target value for each category.
[14]: – 'weighted_mean': weighted average between category mean target value,
[15]: overall mean target value.
[16]: Default is 'mean'.
[17]: prior : float
[18]: Weight of prior training data when calculating weighted averages with
[19]: 'encoding_method' == 'weighted_mean'. Default is 5.
***** Tag Data *****
ID: 1
description: Class definition implementing custom target encoding using advanced techniques.
start line: 4
end line: 20
dependencies:
– type: Class
name: TargetEncoder
start line: 4
end line: 20
context description: This class provides an advanced method for encoding categorical
features using target statistics which can be beneficial for machine learning models.
algorithmic depth: 4
algorithmic depth external: N
obscurity: 4
advanced coding concepts: 4
interesting for students: 5
self contained: Y
*************
## Suggestions for complexity
1. **Dynamic Encoding Methods**: Implement additional encoding methods dynamically based on user-defined functions passed at runtime rather than hardcoding them into the class.
2. **Multi-level Target Encoding**: Extend the encoder to handle multi-level categorical variables where categories have hierarchical relationships.
3. **Cross-validation Support**: Modify the encoder so that it supports cross-validation within itself by splitting data internally without leaking information between folds.
4. **Parallel Processing**: Enable parallel processing capabilities within the `TargetEncoder` class to handle large datasets more efficiently by leveraging multi-threading or distributed computing frameworks like Dask.
5. **Custom Weight Functions**: Allow users to provide custom weight functions instead of just using a fixed prior weight when calculating weighted averages.
## Conversation
:I’m trying understand how I can extend this [SNIPPET] code so it supports user-defined encoding methods at runtime instead of just having ‘mean’ or ‘weighted_mean’. Can you help?
:Sure! To allow user-defined encoding methods at runtime, you can modify your `TargetEncoder` class to accept callable functions as encoding methods along with predefined ones like `’mean’` or `’weighted_mean’`. Here’s how you could do it:
python
class TargetEncoder(BaseEstimator):
“””
Encode categorical features using target statistics.
Parameters:
columns : list of str – List of column names to encode.
encoding_method : str or callable – Encoding method:
– ‘mean’: mean target value for each category.
– ‘weighted_mean’: weighted average between category mean target value,
overall mean target value.
– callable function that takes two arguments (category values, target values).
Default is ‘mean’.
prior : float – Weight of prior training data when calculating weighted averages with
‘encoding_method’ == ‘weighted_mean’. Default is 5.
“””
def __init__(self, columns=None, encoding_method=’mean’, prior=5):
self.columns = columns if columns else []
self.encoding_method = encoding_method if isinstance(encoding_method, str) else None # If not string assume it’s callable later on
self.prior = prior
def fit(self, X, y):
if isinstance(self.encoding_method, str):
if self.encoding_method == ‘mean’:
self._fit_mean(X,y)
elif self.encoding_method == ‘weighted_mean’:
self._fit_weighted_mean(X,y)
else:
raise ValueError(“Unsupported encoding method”)
else:
# Assume it’s a callable function provided by user at runtime
self.encoder_function = self.encoding_method
def _fit_mean(self,X,y):
# Implementation remains same
def _fit_weighted_mean(self,X,y):
# Implementation remains same
def transform(self,X):
if hasattr(self,’encoder_function’):
return self.encoder_function(X,self.target_stats_)
else:
# Existing logic here
def fit_transform(self,X,y):
self.fit(X,y)
return self.transform(X)
# Example usage:
def custom_encoder(cat_values,target_values):
# User defined logic here
pass
encoder = TargetEncoder(columns=[‘column_name’],encoding_method=custom_encoder)
This allows flexibility while still maintaining backward compatibility with predefined methods.
:Thanks! Now I want add support for multi-level categorical variables where categories have hierarchical relationships within this encoder any ideas?
:To handle multi-level categorical variables with hierarchical relationships within your `TargetEncoder`, you’ll need an approach that respects these hierarchies during encoding.
Here’s an outline approach:
1. Define a hierarchy structure.
2. Aggregate statistics respecting this hierarchy during fitting.
3. Apply these aggregated statistics during transformation.
Here’s how you could modify your existing `TargetEncoder`:
python
class TargetEncoder(BaseEstimator):
“””
Encode categorical features using target statistics considering hierarchical relationships.
Parameters:
columns : list of str – List of column names to encode.
hierarchy : dict – Dictionary specifying hierarchical relationships among categories.
encoding_method : str or callable – Encoding method (same as before).
prior : float – Weight of prior training data when calculating weighted averages with
‘encoding_method’ == ‘weighted_mean’. Default is 5.
“””
def __init__(self, columns=None,hierarchy=None ,encoding_method=’mean’,prior=5):
self.columns = columns if columns else []
self.hierarchy = hierarchy if hierarchy else {}
self.encoding_method = encoding_method if isinstance(encoding_method,str) else None
self.prior=prior
def fit(self,X,y):
if isinstance(self.encoding_method,str):
if self.encoding_method==’mean’:
self._fit_hierarchical_mean(X,y)
elif self.encoding_method==’weighted_mean’:
self._fit_hierarchical_weighted_mean(X,y)
else:
raise ValueError(“Unsupported encoding method”)
else:
# Assume it’s a callable function provided by user at runtime
self.encoder_function=self.encoding_method
def _aggregate_hierarchy_stats(self,X,y,column,hierarchy_level=None):
# Recursive aggregation respecting hierarchy levels
unique_vals=np.unique(X[column])
stats=dict()
if hierarchy_level==None:
hierarchy_level=self.hierarchy.get(column,None)
if hierarchy_level!=None:
parent_levels=hierarchy_level.split(‘>’)
parent_vals=[X[column].copy()]
for parent_level in parent_levels[::-1]:
parent_vals=[parent_val[parent_level]for parent_val in parent_vals]
parent_vals=pd.concat(parent_vals,axis=0).unique()
agg_target=y.groupby(parent_vals).agg([‘count’,’sum’])
stats.update({val:(agg_target.loc[val][‘sum’]/agg_target.loc[val][‘count’])for val in parent_vals})
unique_vals=[val[parent_level]for val in unique_vals]
return stats
def _fit_hierarchical_mean(self,X,y):
# Calculate hierarchical means
stats=dict()
for col in set(self.columns).intersection(set(X.columns)):
stats[col]=self._aggregate_hierarchy_stats(X=X,y=y,column=col)
setattr(self,’target_stats_’,stats)
def _fit_hierarchical_weighted_mean(self,X,y):
# Similar logic but also incorporating prior weights
stats=dict()
overall_target_sum=y.sum()
overall_target_count=len(y)
overall_target_ratio=overall_target_sum / overall_target_count
for col in set(self.columns).intersection(set(X.columns)):
cat_stats=self._aggregate_hierarchy_stats(X=X,y=y,column=col)
new_cat_stats={}
cat_count=len(cat_stats.keys())
cat_prior_sum=self.prior * overall_target_ratio * cat_count
cat_prior_count=self.prior * cat_count
new_cat_stats={cat:(cat_stat*(cat_count+self.prior)+(cat_prior_sum-cat_stat*cat_prior_count))/(cat_count+self.prior)
for cat,(cat_stat,count)in zip(cat_stats.keys(),zip(cat_stats.values(),np.ones(len(cat_stats))*self.prior))}
stats.update(new_cat_stats)
setattr(self,’target_stats_’,stats)
def transform(self,X):
X_=X.copy()
encoded_cols=[]
if hasattr(self,’encoder_function’):
encoded_cols=[col+’_encoded’for col in set(encoded_cols).intersection(set(X.columns))]
X_[encoded_cols]=self.encoder_function(X[self.columns],self.target_stats_)
else:
encoded_cols=[col+’_encoded’for col in set(encoded_cols).intersection(set(X.columns))]
X_[encoded_cols]=[X_[col].map(lambda x:self.target_stats_[col][x])if col in set(encoded_cols)
else X_[col]for col in X_.columns]
return X_
# Example usage:
# Defining hierarchy where one level > another level indicates sub-category relationship e.g., Country > State > City
hierarchy={
“location”: “Country > State > City”
}
encoder = TargetEncoder(columns=[‘location’], hierarchy=hierarchy ,encoding_method=’mean’)
In this code snippet:
– The `_aggregate_hierarchy_stats` method recursively aggregates statistics according to specified hierarchies.
– The `_fit_hierarchical_*` methods calculate means considering these hierarchies during fitting.
This way you respect hierarchical relationships while computing your encodings.
1e6; // Number used when dividing total gas mass into cells
//double Mtot = m_gas_mass * ncell;
double Mtot = m_gas_mass;
for(int i=0;i<m_nCell;i++)
{
m_cellMass[i] = Mtot / ncell;
}
m_massCenter.resize(m_nCell);
m_centerOfMass.resize(3);
double totMass = m_gas_mass;
for(int i=0;i=0;i–)
{
totMass += m_cellMass[i];
m_centerOfMass[i] = massSum / totMass;
massSum -= m_cellMass[i];
}
}
void GasSolver::setBoundaryCondition()
{
int nFaceNum[] =
{
// Cube
// Front
FFRONT,
FBACK,
// Right
FRIGHT,
FLEFT,
// Top
FTOP,
FBOTTOM,
// Sphere
FSURF,
// Cylinder
FCYL_INNER,
FCYL_OUTER,
#if defined(_EIGEN_) || defined(_PARDISO_)
FEIGEN_INNER,
FEIGEN_OUTER,
#endif
#if defined(_SMC_)
FSMC_INNER,
FSMC_OUTER,
#endif
#if defined(_HYDRO_)
FCONVEX_INNER,
FCONVEX_OUTER,
#endif
FMAX_FACE_NUM
};
std::vector::iterator iterFaceNum;
for(iterFaceNum=m_faceIndex.begin();iterFaceNum!=m_faceIndex.end();iterFaceNum++)
{
#if defined(_EIGEN_) || defined(_PARDISO_)
int numFaces[Eigen::MaxFace];
#elif defined(_SMC_)
int numFaces[SphereMesh::MaxFace];
#elif defined(_HYDRO_)
int numFaces[CylinderMesh::MaxFace];
#else
int numFaces[SphereMesh::MaxFace];
#endif
switch(*iterFaceNum)
{
#if defined(_EIGEN_) || defined(_PARDISO_)
case FEIGEN_INNER:
case FEIGEN_OUTER:
EigenMesh::getFaces(numFaces,*iterFaceNum);
break;
#elif defined(_SMC_)
case FSMC_INNER:
case FSMC_OUTER:
SphereMesh::getFaces(numFaces,*iterFaceNum);
break;
#elif defined(_HYDRO_)
case FCONVEX_INNER:
case FCONVEX_OUTER:
CylinderMesh::getFaces(numFaces,*iterFaceNum);
break;
#else
default:
SphereMesh::getFaces(numFaces,*iterFaceNum);
break;
#endif
}
std::vector::iterator iterCells;
std::vector::iterator iterPressure;
std::vector::iterator iterVelocity;
std::vector::iterator iterTemperature;
int cellIndex[Eigen::MaxCell];
double pressure[Eigen::MaxCell];
double velocity[Eigen::MaxDim][Eigen::MaxCell];
double temperature[Eigen::MaxCell];
#pragma omp parallel private(iterCells)
{
#pragma omp single nowait
{
#pragma omp taskloop simd collapse(3)
for(int j=0;j<EigenMesh::_nDim;j++)
for(int k=0;k<EigenMesh::_nDim;k++)
for(int i=numFaces[k];i<numFaces[k+1];i++)
cellIndex[i-EigenMesh::_nDim*k-k]=EigenMesh::_cellIndex[j][i-EigenMesh::_nDim*k-k];
#pragma omp taskloop simd collapse(3)
for(int j=0;j<EigenMesh::_nDim;j++)
for(int k=0;k<EigenMesh::_nDim;k++)
for(int i=numFaces[k];i<numFaces[k+1];i++)
pressure[i-EigenMesh::_nDim*k-k]=m_pressure[cellIndex[i-EigenMesh::_nDim*k-k]];
#pragma omp taskloop simd collapse(3)
for(int j=0;j<EigenMesh::_nDim;j++)
for(int k=0;k<EigenMesh::_nDim;k++)
for(int i=numFaces[k];i<numFaces[k+1];i++)
for(int l=j;l<EigenMesh::_nDim;l++)velocity[l][i-EigenMesh::_nDim*k-k]=m_velocity[l][cellIndex[i-EigenMesh::_nDim*k-k]];
#pragma omp taskloop simd collapse(3)
for(int j=0;j<EigenMesh::_nDim;j++)
for(int k=0;k<EigenMesh::_nDim;k++)
for(int i=numFaces[k];i<numFaces[k+1];i++)temperature[i-EigenMesh::_nDim*k-k]=m_temperature[cellIndex[i-EigenMesh::_nDim*k-k]];
}
#pragma omp parallel private(iterCells)
{
#pragma omp single nowait
{
#pragma omp taskloop simd collapse(3)
for(int j=EigenvectorSolverBase_max_dim; j<_Ndim; j++ )
for(int k=EigenvectorSolverBase_max_dim; k<_Ndim; k++ )
for( int i=num_faces[k]; i<num_faces[k+1]; i++ )
cell_index[i-_max_dim*_max_dim*k-k]=_cell_index[j][i-_max_dim*_max_dim*k-k];
#pragma omp taskloop simd collapse(3)
for( int j=EigenvectorSolverBase_max_dim; j<_Ndim; j++ )
for( int k=EigenvectorSolverBase_max_dim; k<_Ndim; k++ )
for( int i=num_faces[k]; i<num_faces[k+1]; i++ )
pressure[i-_max_dim*_max_dim*k-k]=_pressure[cell_index[i-_max_dim*_max_dim*k-k]];
#pragma omp taskloop simd collapse(4)
for( int l=EigenvectorSolverBase_max_dim; l<_NDim_; l++ )
if(l!=j && l!=k)
velocity[l][i-_NDim_*_NDim_*k-k]=_velocity[l][cell_index[i-_NDim_*_NDim_*k-k]];
#pragma omp taskloop simd collapse(3)
for( int j=EigenvectorSolverBase_max_dim; j<_NDim_; j++ )
if(j!=k && j!=j)
velocity[j][i-_NDim_*_NDim_*k-k]=_velocity[j][cell_index[i-_NDim_*_NDim_*k-k]];
#pragma omp taskloop simd collapse(3)
if(k==j && k==j){
velocity[j][i-_NDim_*_NDim_*k-k]=-pressure[i-_NDim_*_NDim_*k]/sqrt(pressure)*density[cell_index]
+sqrt(pressure)/density[cell_index]*velocity[j][i-_NDim_*_NDim_*k];
continue;}
velocity[j][i-_ndimension*_ndimension*k]-=_pressure_velocity_coefficient*
(_normal_vector[j]*velocity[_dimension_-j]+_normal_vector[_dimension_-j]*velocity[j])[i-
_ndimension*_ndimension*k]/density[cell_index]+pressure*[NormalVector](j)*sqrt(pressure)/density[cell_index]
#pragma omp taskloop simd collapse(3)
else{velocity[j][i-_ndimension*_ndimension*k]-=_pressure_velocity_coefficient*
(_normal_vector[_dimension_-j]*velocity[_dimension_-j]+_normal_vector[_dimension_-j]*velocity[j])[_
_ndimension*_ndimension*i-i]/density[cell_index]+pressure*[NormalVector](j)*sqrt(pressure)/density[cell_
index]};
#pragma omp taskloop simd collapse(3)
temperature[i-num_faces[_MAX_DIM_] * _MAX_DIM_] =
temperature_old(cell_index(i-num_faces[_MAX_DIM_] *
_MAX_DIM_),temperature_old);}
}
// Set boundary condition according face number.
// Note that we only need care about inner boundary condition.
void GasSolver::setBoundaryConditionInner()
{
int nFaceNum[] =
{
#ifdef _EIGEN_
FEIGEN_INNER,
#else
FFRONT,
FBACK,
FRIGHT,
FLEFT,
FTOP,
FBOTTOM,
#ifdef _SPHERE_
FSURF,
#endif
#ifdef _CYLINDER_
FCYL_INNER,
#endif
#ifdef _SMC_
FSMC_INNER,
#endif
#ifdef _HYDRO_
FCONVEX_INNER,
#endif
#endif //_EIGEN_
};
std::vector::iterator iterFaceNum;
int nIterEnd=m_faceIndex.size();
int nIterBegin=nIterEnd-nIterEnd%sizeof(nFaceNum);
iterFaceNum=m_faceIndex.begin()+std::distance(m_faceIndex.begin(),m_iter);
while(iterFaceNum<nIterBegin+nIterEnd%sizeof(nFaceNum))
switch(*iterFaceNum-nIterBegin)%sizeof(nFaceNum){
case(FFRONT):
case(FBACK):
case(FRIGHT):
case(FLEFT):
case(FTOP):
case(FBOTTOM):
case(FSURF):
case(FCYL_INNER):
case(FSMC_INNER):
case(FCONVEX_INNER):
default:
break;}
}
void GasSolver ::setBoundaryConditionOuter()
{
int nFaceNumber[] =
#ifndef EIGEN_
{
FFRONT,FBACK ,FRIGHT,FLEFT ,FTOP ,FBOTTOM ,
#ifdef SPHERE_MESH_
Fsurf ,
#endif //_SPHERE_MESH_
#ifdef CYLINDER_MESH_
FCyl_outer ,
#endif //_CYLINDER_MESH_
#ifdef SMC_MESH_
FSmc_outer ,
#endif //_SMC_MESH_
#ifdef HYDRO_MESH_
FConvex_outer ,
#endif //_HYDRO_MESH_
};
#else //_EIGEN_
{
FEig_in,Feg_out ,
};
#endif //_EIGEN_
std :: vector:: iterator iter ;
iter=m_faceindex .begin () +std :: distance (m_faceindex . begin (),m_iter );
while(iter !=m_faceindex . end ())switch (*iter-m_faceindex . begin ()) % sizeof(nfaceNumber){
case(FFRONT):
case(FBACK):
case(FRIGHT):
case(FLEFT):
case (FTOP):
case(FBOTTOM):
case (FSURF):
case (FCYL_OUTTER):
case (FSMC_OUTTER):
case (FCONVEX_OUTTER):
default:
break ;}
}
void GasSolver ::setBoundaryConditionAll()
{
setBoundaryConditionInner();
setBoundaryConditionOuter();
}
int GasSolver :: getNeighborCell(const EigenVector &point,const EigenVector & normalVector,EigenVector ¢erPoint,EignMatrix &Jacobian,EignMatrix &invJacobian,int faceId,int cellId,bool outerFlag){
EignMatrix tempInvJacobian,tempJacobian,tempNormalVec,tempTangentVec,tempCenterPoint,tempPointInTriangle,deltaPoint,deltaPointInTriangle,tempCosTheta,tempSinTheta,scaleFactor,scaleFactorInTriangle;
EignMatrix tempNormalVec_Inner,EignMatrix tempTangentVec_Inner,EignMatrix tempCenterPoint_Inner,EignMatrix tempPointInTriangle_Inner,deltaPoint_Inner,deltaPointInTriangle_Inner,tempCosTheta_Inner,tempSinTheta_Inner,scaleFactor_Inner,scaleFactorInTriangle_Inner;
EignMatrix tempNormalVec_Outer,EignMatrix tempTangentVec_Outer,EignMatrix tempCenterPoint_Outer,EignMatrix tempPointInTriangle_Outer,deltaPoint_Outer,deltaPointInTriangle_Outer,tempCosTheta_Outer,tempSinTheta_Outer,scaleFactor_Outer,scaleFactorInTriangle_Outer;
bool innerFlag=false;
if(!outerFlag){tempNormalVec=tempNormalVec_Inner;tempTangentVec=tempTangentVec_Inner;tempCenterPoint=tempCenterPoint_Inner;}else{tempNormalVec=tempNormalVec_Outer;tempTangentVec=tempTangentVec_Outer;tempCenterPoint=tempCenterPoint_Outer;}
tempNormalVec.setZero();
tempCosTheta.setZero();tempSinTheta.setZero();scaleFactor.setZero();scaleFactorInTriangle.setZero();
deltaPoint.setZero();deltaPointInTriangle.setZero();
const EignVector center_point=getCellPosition(cellId);
tempNormalVec.col(faceId)=normalVector.col(faceId);
tempTangentVec.col(faceId)=tempNormalVec.col(faceId).cross(EignVector(EIGN_REAL(EIGN_PI*0.5),EIGN_REAL(EIGN_PI*0.),EIGN_REAL(EIGN_PI*-.5)));
tempCosTheta(col(faceid))=(center_point-point).dot(temp_normal_vec(col(faceid)))/(center_point-point).norm();
tempSinTheta(col(faceid))=(center_point-point).dot(temp_tangent_vec(col(faceid)))/(center_point-point).norm();
scale_factor(col(faceid))=(center_point-point).norm()*sqrt(temp_cos_theta(col(faceid)));
scale_factor_in_triangle(col(faceid))=(point-center_point)*sqrt(temp_cos_theta(col(faceid)));
delta_point=center_point-scale_factor*temp_normal_vec(point-center_point)/scale_factor.norm();
delta_point_in_triangle=center_point-scale_factor_in_triangle*temp_normal_vec(point-center_point)/scale_factor_in_triangle.norm();
temp_center_point=center_point-delta_point*scale_factor/scale_factor.norm();
temp_center_ptoin_inner=center_pont-deltapoint_inner*scale_factor_inner/scale_facto_inner.norm();
temp_center_ptoin_outer=center_pont-deltapoint_outer*scale_facto_outer/scale_facto_outer.norm();
if(!outerFlag){temp_center_ptoin=temp_center_ptoin_inner;}else{temp_center_ptoin=temp_center_ptoin_outer;}
centerpoint=temp_centreptoin;
Eignequation eignequation;
eignequation.solveEquation(delta_Poiyntemp_delta_Point_in_Triangle);
return cell_id;}
ChangxinZhu/GasDynSimulator>modeltype;
model.setType(modeltype.c_str());
switch(model.getType()){
default:model.setType(GAS_MODEL_EULER);break;}
model.initParameter(file);}
static void getParameters(GasModel& model,string filename){
stdifstream file(filename.c_str());
getParameters(model,file);}
static void saveParameters(GasModel& model,stdofstream& file){
file<<model.getType()<grid_map->grid_model;}ChangxinZhu/GasDynSimulator<|file_sep
/*
Copyright © Changxin Zhu
This software is licensed under BSD License.
Redistribution and use in source forms are permitted provided that this
header remains intact.
Redistribution and use in binary form are permitted provided that
this header remains intact.
THIS SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND.
*/
#ifndef GDSIMULATIONLIB_GASMESH_H_INCLUDED__A28B96A6_B782_4097_AEEB_DFFB91BAAB00__
#define GDSIMULATIONLIB_GASMESH_H_INCLUDED__A28B96A6_B782_4097_AEEB_DFFB91BAAB00__
#include"GDSimulationLibConfig.h"
#include"Eigsolver_base.h"
namespace GDSimulationLib {
class GASMESH_EXPORT GasGrid {
public:
GasGrid(){}
virtual ~GasGrid(){}
protected:
private:
};
templateclass GASMESH_EXPORT MeshTemplate :
public Eigensolver_base {
public:
typedef typename Eigensolver_base base_type ;
typedef typename base_type :: CellType CellType ;
typedef typename base_type :: FaceType FaceType ;
typedef typename base_type :: EdgeType EdgeType ;
typedef typename base_type :: VertexType VertexType ;
typedef typename base_type :: ElementType ElementType ;
MeshTemplate() {}
virtual ~ MeshTemplate() {}
protected:
private:
};
template class GASMESH_EXPORT MeshTemplate
{
};
template class GASMESH_EXPORT MeshTemplate{};
template class GASMESH_EXPORT MeshTemplate{};
template class GASMESH_EXPORT MeshTemplate{};
template class GASMESH_EXPORT MeshTemplate{};
};//namespace GDSimulationLib
#define ENSURE_MEMLEAKS(classname){classname *_ptr=new classname;if(!_ptr){cerr<<"Error allocating memory"<<endl