"""Useful bits and bobs... autoclass:: StatisticsAccumulator.. autofunction:: asdict_shallow.. autofunction:: force_evaluation.. autofunction:: force_compile.. autofunction:: normalize_boundaries.. autofunction:: project_from_base.. autofunction:: mask_from_elements"""__copyright__="""Copyright (C) 2020 University of Illinois Board of Trustees"""__license__="""Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:The above copyright notice and this permission notice shall be included inall copies or substantial portions of the Software.THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS INTHE SOFTWARE."""fromtypingimportOptionalfromarraycontextimporttag_axesfrommeshmode.dof_arrayimportDOFArrayfrommeshmode.transform_metadataimport(DiscretizationElementAxisTag,DiscretizationDOFAxisTag)
[docs]defasdict_shallow(dc_instance)->dict:"""Convert a dataclass into a dict. What :func:`dataclasses.asdict` should have been: no recursion, no deep copy. Simply turn one layer of a dataclass into a :class:`dict`. """fromdataclassesimportfieldsreturn{attr.name:getattr(dc_instance,attr.name)forattrinfields(dc_instance)}
[docs]classStatisticsAccumulator:"""Class that provides statistical functions for multiple values. .. automethod:: __init__ .. automethod:: add_value .. automethod:: sum .. automethod:: mean .. automethod:: max .. automethod:: min .. autoattribute:: num_values """
[docs]def__init__(self,scale_factor:float=1)->None:"""Initialize an empty StatisticsAccumulator object. Parameters ---------- scale_factor Scale returned statistics by this factor. """# Number of values stored in the StatisticsAccumulatorself.num_values:int=0self._sum:float=0self._min:Optional[float]=Noneself._max:Optional[float]=Noneself.scale_factor=scale_factor
[docs]defadd_value(self,v:float)->None:"""Add a new value to the statistics."""ifvisNone:returnself.num_values+=1self._sum+=vifself._minisNoneorv<self._min:self._min=vifself._maxisNoneorv>self._max:self._max=v
[docs]defsum(self)->Optional[float]:"""Return the sum of added values."""ifself.num_values==0:returnNonereturnself._sum*self.scale_factor
[docs]defmean(self)->Optional[float]:"""Return the mean of added values."""ifself.num_values==0:returnNonereturnself._sum/self.num_values*self.scale_factor
[docs]defmax(self)->Optional[float]:"""Return the max of added values."""ifself.num_values==0orself._maxisNone:returnNonereturnself._max*self.scale_factor
[docs]defmin(self)->Optional[float]:"""Return the min of added values."""ifself.num_values==0orself._minisNone:returnNonereturnself._min*self.scale_factor
[docs]defforce_evaluation(actx,x):"""Force evaluation of a (possibly lazy) array."""ifactxisNone:returnxreturnactx.freeze_thaw(x)
[docs]defforce_compile(actx,f,*args):"""Force compilation of *f* with *args*."""new_args=[force_evaluation(actx,arg)forarginargs]f_compiled=actx.compile(f)f_compiled(*new_args)returnf_compiled
[docs]defnormalize_boundaries(boundaries):""" Normalize the keys of *boundaries*. Promotes boundary tags to :class:`grudge.dof_desc.BoundaryDomainTag`. """fromgrudge.dof_descimportas_dofdescreturn{as_dofdesc(key).domain_tag:bdryforkey,bdryinboundaries.items()}
[docs]defproject_from_base(dcoll,tgt_dd,field):"""Project *field* from *DISCR_TAG_BASE* to the same discr. as *tgt_dd*."""fromgrudge.dof_descimportDISCR_TAG_BASE,as_dofdescfromgrudge.opimportprojecttgt_dd=as_dofdesc(tgt_dd)iftgt_dd.discretization_tagisnotDISCR_TAG_BASE:tgt_dd_base=tgt_dd.with_discr_tag(DISCR_TAG_BASE)returnproject(dcoll,tgt_dd_base,tgt_dd,field)else:returnfield
[docs]defmask_from_elements(dcoll,dd,actx,elements):"""Get a :class:`~meshmode.dof_array.DOFArray` mask corresponding to *elements*. Returns ------- mask: :class:`meshmode.dof_array.DOFArray` A DOF array containing $1$ for elements that are in *elements* and $0$ for elements that aren't. """discr=dcoll.discr_from_dd(dd)mesh=discr.meshzeros=discr.zeros(actx)group_arrays=[]forigrpinrange(len(mesh.groups)):start_elem_nr=mesh.base_element_nrs[igrp]end_elem_nr=start_elem_nr+mesh.groups[igrp].nelementsgrp_elems=elements[(elements>=start_elem_nr)&(elements<end_elem_nr)]-start_elem_nrgrp_ary_np=actx.to_numpy(zeros[igrp])grp_ary_np[grp_elems]=1group_arrays.append(actx.from_numpy(grp_ary_np))returntag_axes(actx,{0:DiscretizationElementAxisTag(),1:DiscretizationDOFAxisTag()},DOFArray(actx,tuple(group_arrays)))