Commit 4dab0828 authored by Martin Bauer's avatar Martin Bauer
Browse files

Code Cleanup

- assignment collection
- sympyextensions
parent 54b343b9
import sympy as sp
from pystencils import Field, Assignment
from pystencils.astnodes import SympyAssignment
from pystencils.sympyextensions import getSymmetricPart
from pystencils.sympyextensions import get_symmetric_part
from pystencils.data_types import createType
from lbmpy.simplificationfactory import createSimplificationStrategy
from lbmpy.boundaries.boundaryhandling import BoundaryOffsetInfo, LbmWeightInfo
......@@ -126,7 +126,7 @@ class UBB(Boundary):
if self._adaptVelocityToForce:
cqc = lbMethod.conservedQuantityComputation
shiftedVelEqs = cqc.equilibriumInputEquationsFromInitValues(velocity=velocity)
velocity = [eq.rhs for eq in shiftedVelEqs.extract(cqc.firstOrderMomentSymbols).mainAssignments]
velocity = [eq.rhs for eq in shiftedVelEqs.new_filtered(cqc.firstOrderMomentSymbols).main_assignments]
c_s_sq = sp.Rational(1, 3)
weightOfDirection = LbmWeightInfo.weightOfDirection
......@@ -140,8 +140,8 @@ class UBB(Boundary):
densitySymbol = sp.Symbol("rho")
pdfFieldAccesses = [pdfField(i) for i in range(len(lbMethod.stencil))]
densityEquations = cqc.outputEquationsFromPdfs(pdfFieldAccesses, {'density': densitySymbol})
densitySymbol = lbMethod.conservedQuantityComputation.definedSymbols()['density']
result = densityEquations.allEquations
densitySymbol = lbMethod.conservedQuantityComputation.defined_symbols()['density']
result = densityEquations.all_assignments
result += [Assignment(pdfField[neighbor](inverseDir),
pdfField(direction) - velTerm * densitySymbol)]
return result
......@@ -159,31 +159,31 @@ class FixedDensity(Boundary):
def __call__(self, pdfField, directionSymbol, lbMethod, **kwargs):
"""Boundary condition that fixes the density/pressure at the obstacle"""
def removeAsymmetricPartOfmainAssignments(eqColl, dofs):
newmainAssignments = [Assignment(e.lhs, getSymmetricPart(e.rhs, dofs)) for e in eqColl.mainAssignments]
return eqColl.copy(newmainAssignments)
def removeAsymmetricPartOfmain_assignments(eqColl, dofs):
newmain_assignments = [Assignment(e.lhs, get_symmetric_part(e.rhs, dofs)) for e in eqColl.main_assignments]
return eqColl.copy(newmain_assignments)
neighbor = BoundaryOffsetInfo.offsetFromDir(directionSymbol, lbMethod.dim)
inverseDir = BoundaryOffsetInfo.invDir(directionSymbol)
cqc = lbMethod.conservedQuantityComputation
velocity = cqc.definedSymbols()['velocity']
symmetricEq = removeAsymmetricPartOfmainAssignments(lbMethod.getEquilibrium(), dofs=velocity)
velocity = cqc.defined_symbols()['velocity']
symmetricEq = removeAsymmetricPartOfmain_assignments(lbMethod.getEquilibrium(), dofs=velocity)
substitutions = {sym: pdfField(i) for i, sym in enumerate(lbMethod.preCollisionPdfSymbols)}
symmetricEq = symmetricEq.copyWithSubstitutionsApplied(substitutions)
symmetricEq = symmetricEq.new_with_substitutions(substitutions)
simplification = createSimplificationStrategy(lbMethod)
symmetricEq = simplification(symmetricEq)
densitySymbol = cqc.definedSymbols()['density']
densitySymbol = cqc.defined_symbols()['density']
density = self._density
densityEq = cqc.equilibriumInputEquationsFromInitValues(density=density).insertSubexpressions().mainAssignments[0]
densityEq = cqc.equilibriumInputEquationsFromInitValues(density=density).new_without_subexpressions().main_assignments[0]
assert densityEq.lhs == densitySymbol
transformedDensity = densityEq.rhs
conditions = [(eq_i.rhs, sp.Equality(directionSymbol, i))
for i, eq_i in enumerate(symmetricEq.mainAssignments)] + [(0, True)]
for i, eq_i in enumerate(symmetricEq.main_assignments)] + [(0, True)]
eq_component = sp.Piecewise(*conditions)
subExprs = [Assignment(eq.lhs, transformedDensity if eq.lhs == densitySymbol else eq.rhs)
......
......@@ -11,8 +11,8 @@ from lbmpy.chapman_enskog.derivative import collectDerivatives, createNestedDiff
from lbmpy.moments import discreteMoment, momentMatrix, polynomialToExponentRepresentation, getMomentIndices, \
nonAliasedMoment
from pystencils.cache import diskcache
from pystencils.sympyextensions import normalizeProduct, multidimensionalSummation, kroneckerDelta
from pystencils.sympyextensions import productSymmetric
from pystencils.sympyextensions import normalize_product, multidimensional_sum, kronecker_delta
from pystencils.sympyextensions import symmetric_product
# --------------------------------------------- Helper Functions -------------------------------------------------------
......@@ -77,7 +77,7 @@ class CeMoment(sp.Symbol):
class LbMethodEqMoments:
def __init__(self, lbMethod):
self._eq = tuple(e.rhs for e in lbMethod.getEquilibrium().mainAssignments)
self._eq = tuple(e.rhs for e in lbMethod.getEquilibrium().main_assignments)
self._momentCache = dict()
self._postCollisionMomentCache = dict()
self._stencil = lbMethod.stencil
......@@ -189,7 +189,7 @@ def takeMoments(eqn, pdfToMomentName=(('f', '\Pi'), ('\Omega f', '\\Upsilon')),
derivativeTerm = None
cIndices = []
rest = 1
for factor in normalizeProduct(productTerm):
for factor in normalize_product(productTerm):
if isinstance(factor, Diff):
assert fIndex is None
fIndex = determineFIndex(factor.getArgRecursive())
......@@ -269,13 +269,13 @@ def chainSolveAndSubstitute(eqSequence, unknownSelector, normalizingFunc=diffExp
def countVars(expr, variables):
factorList = normalizeProduct(expr)
factorList = normalize_product(expr)
diffsToUnpack = [e for e in factorList if isinstance(e, Diff)]
factorList = [e for e in factorList if not isinstance(e, Diff)]
while diffsToUnpack:
d = diffsToUnpack.pop()
args = normalizeProduct(d.arg)
args = normalize_product(d.arg)
for a in args:
if isinstance(a, Diff):
diffsToUnpack.append(a)
......@@ -402,7 +402,7 @@ def matchEquationsToNavierStokes(conservationEquations, rho=sp.Symbol("rho"), u=
ref = diffSimplify(Diff(factor * u[i], t) + sum(Diff(factor * u[i] * u[j], j) for j in range(dim)))
shearAndPressureEqs.append(diffSimplify(momentEqs[i]) - ref)
# extract pressure term
# new_filtered pressure term
coefficentArgSets = []
for i, eq in enumerate(shearAndPressureEqs):
coefficentArgSets.append(set())
......@@ -460,8 +460,8 @@ class ChapmanEnskogAnalysis(object):
cqc = method.conservedQuantityComputation
self._method = method
self._momentCache = LbMethodEqMoments(method)
self.rho = cqc.definedSymbols(order=0)[1]
self.u = cqc.definedSymbols(order=1)[1]
self.rho = cqc.defined_symbols(order=0)[1]
self.u = cqc.defined_symbols(order=1)[1]
self.t = sp.Symbol("t")
self.epsilon = sp.Symbol("epsilon")
......@@ -471,7 +471,7 @@ class ChapmanEnskogAnalysis(object):
# Taking moments
c = sp.Matrix([expandedSymbol("c", subscript=i) for i in range(self._method.dim)])
momentsUntilOrder1 = [1] + list(c)
momentsOrder2 = [c_i * c_j for c_i, c_j in productSymmetric(c, c)]
momentsOrder2 = [c_i * c_j for c_i, c_j in symmetric_product(c, c)]
symbolicRelaxationRates = [rr for rr in method.relaxationRates if isinstance(rr, sp.Symbol)]
if constants is None:
......@@ -541,7 +541,7 @@ class ChapmanEnskogAnalysis(object):
def getShearViscosityCandidates(self):
result = set()
dim = self._method.dim
for i, j in productSymmetric(range(dim), range(dim), withDiagonal=False):
for i, j in symmetric_product(range(dim), range(dim), with_diagonal=False):
result.add(-sp.cancel(self._sigmaWithoutErrorTerms[i, j] / (Diff(self.u[i], j) + Diff(self.u[j], i))))
return result
......@@ -554,7 +554,7 @@ class ChapmanEnskogAnalysis(object):
# Check that shear viscosity does not depend on any u derivatives - create conditions (equations) that
# have to be fulfilled for this to be the case
viscosityReference = self._sigmaWithoutErrorTerms[0, 1].expand().coeff(Diff(self.u[0], 1))
for i, j in productSymmetric(range(dim), range(dim), withDiagonal=False):
for i, j in symmetric_product(range(dim), range(dim), with_diagonal=False):
term = self._sigmaWithoutErrorTerms[i, j]
equalCrossTermCondition = sp.expand(term.coeff(Diff(self.u[i], j)) - viscosityReference)
term = term.subs({Diff(self.u[i], j): 0,
......@@ -656,7 +656,7 @@ class SteadyStateChapmanEnskogAnalysis(object):
moment = summand.atoms(CeMoment)
moment = moment.pop()
collisionOperatorExponent = normalizeProduct(summand).count(B)
collisionOperatorExponent = normalize_product(summand).count(B)
if collisionOperatorExponent == 0:
result += summand
else:
......@@ -716,8 +716,8 @@ class SteadyStateChapmanEnskogAnalysis(object):
dim = self.method.dim
D = createNestedDiff
s = functools.partial(multidimensionalSummation, dim=dim)
kd = kroneckerDelta
s = functools.partial(multidimensional_sum, dim=dim)
kd = kronecker_delta
eta, eta_b = sp.symbols("nu nu_B")
u = sp.symbols("u_:3")[:dim]
......
import sympy as sp
from pystencils.sympyextensions import normalizeProduct
from pystencils.sympyextensions import normalize_product
from lbmpy.chapman_enskog.derivative import Diff, DiffOperator, expandUsingLinearity, normalizeDiffOrder
from lbmpy.chapman_enskog.chapman_enskog import expandedSymbol, useChapmanEnskogAnsatz
......@@ -133,7 +133,7 @@ class SteadyStateChapmanEnskogAnalysis(object):
derivative = None
newProd = 1
for arg in reversed(normalizeProduct(product)):
for arg in reversed(normalize_product(product)):
if isinstance(arg, Diff):
assert derivative is None, "More than one derivative term in the product"
derivative = arg
......
......@@ -6,18 +6,18 @@ import sympy as sp
from lbmpy.moments import polynomialToExponentRepresentation
from pystencils.cache import diskcache, memorycache
from pystencils.sympyextensions import makeExponentialFuncArgumentSquares
from pystencils.sympyextensions import complete_the_squares_in_exp
@memorycache()
def momentGeneratingFunction(function, symbols, symbolsInResult):
def momentGeneratingFunction(generating_function, symbols, symbolsInResult):
"""
Computes the moment generating function of a probability distribution. It is defined as:
.. math ::
F[f(\mathbf{x})](\mathbf{t}) = \int e^{<\mathbf{x}, \mathbf{t}>} f(x)\; dx
:param function: sympy expression
:param generating_function: sympy expression
:param symbols: a sequence of symbols forming the vector x
:param symbolsInResult: a sequence forming the vector t
:return: transformation result F: an expression that depends now on symbolsInResult
......@@ -33,7 +33,7 @@ def momentGeneratingFunction(function, symbols, symbolsInResult):
"""
assert len(symbols) == len(symbolsInResult)
for t_i, v_i in zip(symbolsInResult, symbols):
function *= sp.exp(t_i * v_i)
generating_function *= sp.exp(t_i * v_i)
# This is a custom transformation that speeds up the integrating process
# of a MaxwellBoltzmann distribution
......@@ -43,11 +43,11 @@ def momentGeneratingFunction(function, symbols, symbolsInResult):
# Without this transformation the following assumptions are required for the u and v variables of Maxwell Boltzmann
# 2D: real=True ( without assumption it will not work)
# 3D: no assumption ( with assumptions it will not work )
function = makeExponentialFuncArgumentSquares(function, symbols)
function = function.collect(symbols)
generating_function = complete_the_squares_in_exp(generating_function.simplify(), symbols)
generating_function = generating_function.collect(symbols)
bounds = [(s_i, -sp.oo, sp.oo) for s_i in symbols]
result = sp.integrate(function, *bounds)
result = sp.integrate(generating_function, *bounds)
return sp.simplify(result)
......
......@@ -192,7 +192,7 @@ def createLatticeBoltzmannAst(updateRule=None, optimizationParams={}, **kwargs):
params['optimizationParams'] = optimizationParams
updateRule = createLatticeBoltzmannUpdateRule(**params)
fieldTypes = set(fa.field.dtype for fa in updateRule.definedSymbols if isinstance(fa, Field.Access))
fieldTypes = set(fa.field.dtype for fa in updateRule.defined_symbols if isinstance(fa, Field.Access))
res = createKernel(updateRule, target=optParams['target'], dataType=collateTypes(fieldTypes),
cpuOpenMP=optParams['openMP'], cpuVectorizeInfo=optParams['vectorization'],
gpuIndexing=optParams['gpuIndexing'], gpuIndexingParams=optParams['gpuIndexingParams'],
......@@ -205,17 +205,17 @@ def createLatticeBoltzmannAst(updateRule=None, optimizationParams={}, **kwargs):
@diskcacheNoFallback
def createLatticeBoltzmannUpdateRule(collisionRule=None, optimizationParams={}, **kwargs):
params, optParams = updateWithDefaultParameters(kwargs, optimizationParams)
params, opt_params = updateWithDefaultParameters(kwargs, optimizationParams)
if collisionRule is None:
collisionRule = createLatticeBoltzmannCollisionRule(**params, optimizationParams=optParams)
collisionRule = createLatticeBoltzmannCollisionRule(**params, optimizationParams=opt_params)
lbMethod = collisionRule.method
lb_method = collisionRule.method
if params['output'] and params['kernelType'] == 'streamPullCollide':
cqc = lbMethod.conservedQuantityComputation
outputEqs = cqc.outputEquationsFromPdfs(lbMethod.preCollisionPdfSymbols, params['output'])
collisionRule = collisionRule.merge(outputEqs)
cqc = lb_method.conservedQuantityComputation
output_eqs = cqc.outputEquationsFromPdfs(lb_method.preCollisionPdfSymbols, params['output'])
collisionRule = collisionRule.new_merged(output_eqs)
if params['entropic']:
if params['entropicNewtonIterations']:
......@@ -228,33 +228,33 @@ def createLatticeBoltzmannUpdateRule(collisionRule=None, optimizationParams={},
else:
collisionRule = addEntropyCondition(collisionRule, omegaOutputField=params['omegaOutputField'])
elif params['smagorinsky']:
smagorinskyConstant = 0.12 if params['smagorinsky'] is True else params['smagorinsky']
collisionRule = addSmagorinskyModel(collisionRule, smagorinskyConstant,
smagorinsky_constant = 0.12 if params['smagorinsky'] is True else params['smagorinsky']
collisionRule = addSmagorinskyModel(collisionRule, smagorinsky_constant,
omegaOutputField=params['omegaOutputField'])
fieldDtype = 'float64' if optParams['doublePrecision'] else 'float32'
field_data_type = 'float64' if opt_params['doublePrecision'] else 'float32'
if optParams['symbolicField'] is not None:
srcField = optParams['symbolicField']
elif optParams['fieldSize']:
fieldSize = [s + 2 for s in optParams['fieldSize']] + [len(collisionRule.stencil)]
srcField = Field.createFixedSize(params['fieldName'], fieldSize, indexDimensions=1,
layout=optParams['fieldLayout'], dtype=fieldDtype)
if opt_params['symbolicField'] is not None:
src_field = opt_params['symbolicField']
elif opt_params['fieldSize']:
field_size = [s + 2 for s in opt_params['fieldSize']] + [len(collisionRule.stencil)]
src_field = Field.createFixedSize(params['fieldName'], field_size, indexDimensions=1,
layout=opt_params['fieldLayout'], dtype=field_data_type)
else:
srcField = Field.createGeneric(params['fieldName'], spatialDimensions=collisionRule.method.dim,
indexDimensions=1, layout=optParams['fieldLayout'], dtype=fieldDtype)
src_field = Field.createGeneric(params['fieldName'], spatialDimensions=collisionRule.method.dim,
indexDimensions=1, layout=opt_params['fieldLayout'], dtype=field_data_type)
dstField = srcField.newFieldWithDifferentName(params['secondFieldName'])
dst_field = src_field.newFieldWithDifferentName(params['secondFieldName'])
if params['kernelType'] == 'streamPullCollide':
accessor = StreamPullTwoFieldsAccessor
if any(optParams['builtinPeriodicity']):
accessor = PeriodicTwoFieldsAccessor(optParams['builtinPeriodicity'], ghostLayers=1)
return createLBMKernel(collisionRule, srcField, dstField, accessor)
if any(opt_params['builtinPeriodicity']):
accessor = PeriodicTwoFieldsAccessor(opt_params['builtinPeriodicity'], ghostLayers=1)
return createLBMKernel(collisionRule, src_field, dst_field, accessor)
elif params['kernelType'] == 'collideOnly':
return createLBMKernel(collisionRule, srcField, srcField, CollideOnlyInplaceAccessor)
return createLBMKernel(collisionRule, src_field, src_field, CollideOnlyInplaceAccessor)
elif params['kernelType'] == 'streamPullOnly':
return createStreamPullWithOutputKernel(lbMethod, srcField, dstField, params['output'])
return createStreamPullWithOutputKernel(lb_method, src_field, dst_field, params['output'])
else:
raise ValueError("Invalid value of parameter 'kernelType'", params['kernelType'])
......
......@@ -9,8 +9,8 @@ from lbmpy.continuous_distribution_measures import multiDifferentiation
from lbmpy.moments import momentsUpToComponentOrder
from pystencils.cache import memorycache
# ------------------------------------------- Internal Functions -------------------------------------------------------
from pystencils.sympyextensions import fastSubs
from pystencils.sympyextensions import scalarProduct
from pystencils.sympyextensions import fast_subs
from pystencils.sympyextensions import scalar_product
def __getIndexedSymbols(passedSymbols, prefix, indices):
......@@ -79,7 +79,7 @@ def __cumulantRawMomentTransform(index, dependentVarDict, outerFunction, default
partitionList.append(i)
if len(partitionList) == 0: # special case for zero index
return fastSubs(outerFunction(zerothMoment), subsDict)
return fast_subs(outerFunction(zerothMoment), subsDict)
# implementation of Faa di Bruno's formula:
result = 0
......@@ -98,14 +98,14 @@ def __cumulantRawMomentTransform(index, dependentVarDict, outerFunction, default
index[i] = 1
result = result.subs(createMomentSymbol(index), 0)
return fastSubs(result, subsDict)
return fast_subs(result, subsDict)
@memorycache(maxsize=16)
def __getDiscreteCumulantGeneratingFunction(function, stencil, waveNumbers):
assert len(stencil) == len(function)
laplaceTrafo = sum([factor * sp.exp(scalarProduct(waveNumbers, e)) for factor, e in zip(function, stencil)])
laplaceTrafo = sum([factor * sp.exp(scalar_product(waveNumbers, e)) for factor, e in zip(function, stencil)])
return sp.ln(laplaceTrafo)
......
......@@ -16,7 +16,7 @@ def createLbmSplitGroups(lbmCollisionEqs):
Required simplification hints:
- velocity: sequence of velocity symbols
"""
sh = lbmCollisionEqs.simplificationHints
sh = lbmCollisionEqs.simplification_hints
assert 'velocity' in sh, "Needs simplification hint 'velocity': Sequence of velocity symbols"
preCollisionSymbols = set(lbmCollisionEqs.method.preCollisionPdfSymbols)
......@@ -26,10 +26,10 @@ def createLbmSplitGroups(lbmCollisionEqs):
stencil = lbmCollisionEqs.method.stencil
importantSubExpressions = {e.lhs for e in lbmCollisionEqs.subexpressions
if preCollisionSymbols.intersection(lbmCollisionEqs.getDependentSymbols([e.lhs]))}
if preCollisionSymbols.intersection(lbmCollisionEqs.dependent_symbols([e.lhs]))}
otherWrittenFields = []
for eq in lbmCollisionEqs.mainAssignments:
for eq in lbmCollisionEqs.main_assignments:
if eq.lhs not in postCollisionSymbols and isinstance(eq.lhs, Field.Access):
otherWrittenFields.append(eq.lhs)
if eq.lhs not in nonCenterPostCollisionSymbols:
......@@ -44,7 +44,7 @@ def createLbmSplitGroups(lbmCollisionEqs):
directionGroups = defaultdict(list)
dim = len(stencil[0])
for direction, eq in zip(stencil, lbmCollisionEqs.mainAssignments):
for direction, eq in zip(stencil, lbmCollisionEqs.main_assignments):
if direction == tuple([0]*dim):
splitGroups[0].append(eq.lhs)
continue
......@@ -57,5 +57,5 @@ def createLbmSplitGroups(lbmCollisionEqs):
directionGroups[direction].append(eq.lhs)
splitGroups += directionGroups.values()
lbmCollisionEqs.simplificationHints['splitGroups'] = splitGroups
lbmCollisionEqs.simplification_hints['splitGroups'] = splitGroups
return lbmCollisionEqs
......@@ -251,8 +251,8 @@ class LatticeBoltzmannStep:
inpEqs = cqc.equilibriumInputEquationsFromInitValues(rhoField, [velField(i) for i in range(D)])
setterEqs = lbMethod.getEquilibrium(conservedQuantityEquations=inpEqs)
setterEqs = setterEqs.copyWithSubstitutionsApplied({sym: pdfField(i)
for i, sym in enumerate(lbMethod.postCollisionPdfSymbols)})
setterEqs = setterEqs.new_with_substitutions({sym: pdfField(i)
for i, sym in enumerate(lbMethod.postCollisionPdfSymbols)})
setterEqs = createSimplificationStrategy(lbMethod)(setterEqs)
setterKernel = createKernel(setterEqs, target='cpu').compile()
......
......@@ -53,7 +53,7 @@ def compileMacroscopicValuesGetter(lbMethod, outputQuantities, pdfArr=None, fiel
stencil = lbMethod.stencil
pdfSymbols = [pdfField(i) for i in range(len(stencil))]
eqs = cqc.outputEquationsFromPdfs(pdfSymbols, outputMapping).allEquations
eqs = cqc.outputEquationsFromPdfs(pdfSymbols, outputMapping).all_assignments
if target == 'cpu':
import pystencils.cpu as cpu
......@@ -118,10 +118,10 @@ def compileMacroscopicValuesSetter(lbMethod, quantitiesToSet, pdfArr=None, field
simplification = createSimplificationStrategy(lbMethod)
eq = simplification(eq)
else:
eq = eq.insertSubexpressions()
eq = eq.new_without_subexpressions()
substitutions = {sym: pdfField(i) for i, sym in enumerate(lbMethod.postCollisionPdfSymbols)}
eq = eq.copyWithSubstitutionsApplied(substitutions).allEquations
eq = eq.new_with_substitutions(substitutions).all_assignments
if target == 'cpu':
import pystencils.cpu as cpu
......@@ -146,18 +146,18 @@ def createAdvancedVelocitySetterCollisionRule(lbMethod, velocityArray, velocityR
velocityField = Field.createFromNumpyArray('velInput', velocityArray, indexDimensions=1)
cqc = lbMethod.conservedQuantityComputation
densitySymbol = cqc.definedSymbols(order=0)[1]
velocitySymbols = cqc.definedSymbols(order=1)[1]
densitySymbol = cqc.defined_symbols(order=0)[1]
velocitySymbols = cqc.defined_symbols(order=1)[1]
# density is computed from pdfs
eqInputFromPdfs = cqc.equilibriumInputEquationsFromPdfs(lbMethod.preCollisionPdfSymbols)
eqInputFromPdfs = eqInputFromPdfs.extract([densitySymbol])
eqInputFromPdfs = eqInputFromPdfs.new_filtered([densitySymbol])
# velocity is read from input field
velSymbols = [velocityField(i) for i in range(lbMethod.dim)]
eqInputFromField = cqc.equilibriumInputEquationsFromInitValues(velocity=velSymbols)
eqInputFromField = eqInputFromField.extract(velocitySymbols)
eqInputFromField = eqInputFromField.new_filtered(velocitySymbols)
# then both are merged together
eqInput = eqInputFromPdfs.merge(eqInputFromField)
eqInput = eqInputFromPdfs.new_merged(eqInputFromField)
# set first order relaxation rate
lbMethod = deepcopy(lbMethod)
......
......@@ -157,7 +157,7 @@ def getMomentsOfContinuousMaxwellianEquilibrium(moments, dim, rho=sp.Symbol("rho
>>> getMomentsOfContinuousMaxwellianEquilibrium( ( (0,0,0), (1,0,0), (0,1,0), (0,0,1), (2,0,0) ), dim=3 )
[rho, rho*u_0, rho*u_1, rho*u_2, rho*(c_s**2 + u_0**2)]
"""
from pystencils.sympyextensions import removeHigherOrderTerms
from pystencils.sympyextensions import remove_higher_order_terms
from lbmpy.moments import MOMENT_SYMBOLS
from lbmpy.continuous_distribution_measures import continuousMoment
......@@ -167,7 +167,7 @@ def getMomentsOfContinuousMaxwellianEquilibrium(moments, dim, rho=sp.Symbol("rho
mb = continuousMaxwellianEquilibrium(dim, rho, u, MOMENT_SYMBOLS[:dim], c_s_sq_helper)
result = [continuousMoment(mb, moment, MOMENT_SYMBOLS[:dim]).subs(c_s_sq_helper, c_s_sq) for moment in moments]
if order is not None:
result = [removeHigherOrderTerms(r, order, u) for r in result]
result = [remove_higher_order_terms(r, order=order, symbols=u) for r in result]
return result
......@@ -219,7 +219,7 @@ def getCumulantsOfContinuousMaxwellianEquilibrium(cumulants, dim, rho=sp.Symbol(
c_s_sq=sp.Symbol("c_s") ** 2, order=None):
from lbmpy.moments import MOMENT_SYMBOLS
from lbmpy.continuous_distribution_measures import continuousCumulant
from pystencils.sympyextensions import removeHigherOrderTerms
from pystencils.sympyextensions import remove_higher_order_terms
# trick to speed up sympy integration (otherwise it takes multiple minutes, or aborts):
# use a positive, real symbol to represent c_s_sq -> then replace this symbol afterwards with the real c_s_sq
......@@ -227,7 +227,7 @@ def getCumulantsOfContinuousMaxwellianEquilibrium(cumulants, dim, rho=sp.Symbol(
mb = continuousMaxwellianEquilibrium(dim, rho, u, MOMENT_SYMBOLS[:dim], c_s_sq_helper)
result = [continuousCumulant(mb, cumulant, MOMENT_SYMBOLS[:dim]).subs(c_s_sq_helper, c_s_sq) for cumulant in cumulants]
if order is not None:
result = [removeHigherOrderTerms(r, order, u) for r in result]
result = [remove_higher_order_terms(r, order=order, symbols=u) for r in result]
return result
......
......@@ -8,9 +8,9 @@ RelaxationInfo = namedtuple('RelaxationInfo', ['equilibriumValue', 'relaxationRa
class LbmCollisionRule(AssignmentCollection):
def __init__(self, lbmMethod, *args, **kwargs):
def __init__(self, lb_method, *args, **kwargs):
super(LbmCollisionRule, self).__init__(*args, **kwargs)
self.method = lbmMethod
self.method = lb_method
class AbstractLbMethod(abc.ABCMeta('ABC', (object,), {})):
......
......@@ -32,7 +32,7 @@ class AbstractConservedQuantityComputation(abc.ABCMeta('ABC', (object,), {})):
and :func:`equilibriumInputEquationsFromInitValues`
"""
def definedSymbols(self, order='all'):
def defined_symbols(self, order='all'):
"""
Returns a dict, mapping names of conserved quantities to their symbols
"""
......@@ -98,7 +98,7 @@ class DensityVelocityComputation(AbstractConservedQuantityComputation):
def compressible(self):
return self._compressible
def definedSymbols(self, order='all'):
def defined_symbols(self, order='all'):
if order == 'all':
return {'density': self._symbolOrder0,
'velocity': self._symbolsOrder1}
......@@ -171,7 +171,7 @@ class DensityVelocityComputation(AbstractConservedQuantityComputation):
ac = applyForceModelShift('macroscopicVelocityShift', dim, ac, self._forceModel, self._compressible)
main_assignments = []
eqs = OrderedDict([(eq.lhs, eq.rhs) for eq in ac.allEquations])
eqs = OrderedDict([(eq.lhs, eq.rhs) for eq in ac.all_assignments])
if 'density' in outputQuantityNamesToSymbols:
density_output_symbol = outputQuantityNamesToSymbols['density']
......@@ -203,11 +203,11 @@ class DensityVelocityComputation(AbstractConservedQuantityComputation):
self._symbolOrder0, self._symbolsOrder1)
mom_density_eq_coll = applyForceModelShift('macroscopicVelocityShift', dim, mom_density_eq_coll,
self._forceModel, self._compressible)
for sym, val in zip(momentum_density_output_symbols, mom_density_eq_coll.mainAssignments[1:]):
for sym, val in zip(momentum_density_output_symbols, mom_density_eq_coll.main_assignments[1:]):
main_assignments.append(Assignment(sym, val.rhs))
ac = ac.copy(main_assignments, [Assignment(a, b) for a, b in eqs.items()])
return ac.newWithoutUnusedSubexpressions()
return ac.new_without_unused_subexpressions()
def __repr__(self):
return "ConservedValueComputation for %s" % (", " .join(self.conservedQuantities.keys()),)
......@@ -278,10 +278,10 @@ def divideFirstOrderMomentsByRho(assignment_collection, dim):
Returns a new equation collection where the u terms (first order moments) are divided by rho.
The dim parameter specifies the number of first order moments. All subsequent equations are just copied over.
"""
oldEqs = assignment_collection.mainAssignments
rho = oldEqs[0].lhs
new_first_order_moment_eq = [Assignment(eq.lhs, eq.rhs / rho) for eq in oldEqs[1:dim+1]]
new_eqs = [oldEqs[0]] + new_first_order_moment_eq + oldEqs[dim+1:]
old_eqs = assignment_collection.main_assignments
rho = old_eqs[0].lhs
new_first_order_moment_eq = [Assignment(eq.lhs, eq.rhs / rho) for eq in old_eqs[1:dim+1]]
new_eqs = [old_eqs[0]] + new_first_order_moment_eq + old_eqs[dim+1:]
return assignment_collection.copy(new_eqs)
......@@ -289,9 +289,9 @@ def addDensityOffset(assignment_collection, offset=sp.Rational(1, 1)):
"""
Assumes that first equation is the density (zeroth moment). Changes the density equations by adding offset to it.
"""
oldEqs = assignment_collection.mainAssignments
newDensity = Assignment(oldEqs[0].lhs, oldEqs[0].rhs + offset)
return assignment_collection.copy([newDensity] + oldEqs[1:])
old_eqs = assignment_collection.main_assignments
new_density = Assignment(old_eqs[0].lhs, old_eqs[0].rhs + offset)
return assignment_collection.copy([new_density] + old_eqs[1:])
def applyForceModelShift(shiftMemberName, dim, assignment_collection, forceModel, compressible, reverse=False):
......@@ -301,7 +301,7 @@ def applyForceModelShift(shiftMemberName, dim, assignment_collection, forceModel
equation collection are assumed to be the velocity equations.
"""
if forceModel is not None and hasattr(forceModel, shiftMemberName):
old_eqs = assignment_collection.mainAssignments
old_eqs = assignment_collection.main_assignments
density = old_eqs[0].lhs if compressible else sp.Rational(1, 1)
old_vel_eqs = old_eqs[1:dim + 1]
shift_func = getattr(forceModel, shiftMemberName)
......
......@@ -11,7 +11,7 @@ from lbmpy.stencils import stencilsHaveSameEntries, getStencil
from lbmpy.moments import isEven, gramSchmidt, getDefaultMomentSetForStencil, MOMENT_SYMBOLS, \
exponentsToPolynomialRepresentations, momentsOfOrder, momentsUpToComponentOrder, sortMomentsIntoGroupsOfSameOrder, \
getOrder, discreteMoment