动态定义函数的编程概念

2024-09-27 21:30:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个问题,我计算了一个模型和一个参考数据集的不同评估指标-数据集被用来是三维(x,y,t)和netcdf数据。评估指标必须针对四种不同类型的时间聚集进行处理:无聚集、整个期间的聚集、带重采样的聚集(每月)和分组聚集(每小时、每月、每年)。你知道吗

我选择的工作马是pythonxarray,因为它们在netcdf处理方面非常灵活。你知道吗

从简单的分数偏差开始,我有以下代码:

def BIAS_temporal(self,varns_result=None,aggregtime=None,dim_time=None):
    """ Compute the BIAS/ME for a timeseries -> e.g. R^3 --> R^2:
        BIAS(x,y) = SUM_{dim_t} ( MOD(x,y,dim_t) - OBS(x,y,dim_t) ) """
    def bias(x):
        return ( x[namex] - x[namey] )
    def biasmean(x):
        return ( x[namex] - x[namey] ).mean(dim=coordtime)
    #
    endresult = xarray.Dataset()
    for varnsproof,varnsref,varnsres in zip(self.varns_proof,self.varns_ref,varns_result):
        # rename the data variables and combine both datasets for evaluation
        namex=varnsres+"_x"; namey=varnsres+"_y"
        self.DSref.rename({varnsref : namey },inplace=True)
        self.DSproof.rename({varnsproof : namex },inplace=True)
        DScomb = xarray.merge([self.DSref,self.DSproof])
        coordtime     = self.MetricCalcProg.ListDimsToXarray(dim_time[varnsref])     #extract the name of time coordinate
        #
        if aggregtime == 'fullperiod':
            DSnew = biasmean(DScomb).to_dataset(name = varnsres)
            ...
        elif aggregtime == '-':
            DSnew = bias(DScomb).to_dataset(name = varnsres)
        elif "overperiod" in aggregtime:
            grpby_method=self.MetricCalcProg.ConvertAggregKey2Groupby(aggregtime)
            DSnew = DScomb.groupby(coordtime+'.'+grpby_method).apply(biasmean)
            DSnew = DSnew.to_dataset(name = varnsres)
            ... 
        elif "overperiod" not in aggregtime:
            resamplefreq=self.MetricCalcProg.ConvertAggregKey2Resample(aggregtime)
            DSnew = DScomb.resample(time=resamplefreq,keep_attrs=True).apply(biasmean)
            DSnew = DSnew.to_dataset(name = varnsres)
            ...
        #
        self.DSref.rename({namey : varnsref },inplace=True)
        self.DSproof.rename({namex : varnsproof },inplace=True)
        unitsnew=GeneralUtils.safe_access_bib('',KeyError,dicttest=self.DSref[varnsref].attrs,dictkey='units',errhandle=False)
        if unitsnew is None: unitsnew='-'
        longnew="temporal BIAS of "+str(GeneralUtils.safe_access_bib('', KeyError, dicttest=self.DSref[varnsref].attrs, \
            dictkey='long_name',errhandle=False))
        self.Update_Attributes(Datasetobj=DSnew,variable=varnsres,stdname=varnsres,units=unitsnew,longname=longnew)
        endresult = xarray.merge([endresult,DSnew])
    return endresult

如您所见,我需要定义函数'bias'和'biasmean',以始终获得正确的结果,而不管聚合方法'aggregtime'。定义另一个度量,如“LinearCorrelation”,代码几乎相同:

def LinCorr_temporal(self,varns_result=None,aggregtime=None,dim_time=None):
    """ Compute the linear correlation for a timeseries -> e.g. R^3 --> R^2:
        LinCorr(x,y) = ???"""
    def correl2dtm(x):
        a = ( x[namex] - x[namex].mean(dim=coordtime) ) * ( x[namey] - x[namey].mean(dim=coordtime) ) \
            / x[namex].std(dim=coordtime) / x[namey].std(dim=coordtime)
        return a.mean(dim=coordtime)
    #
    endresult = xarray.Dataset()
    for varnsproof,varnsref,varnsres in zip(self.varns_proof,self.varns_ref,varns_result):
        # ensure that only time stamps are considerd being present in both datasets (otherwise LC>1)
        self.DSproof = self.DSproof[varnsproof].where(self.DSref[varnsref].notnull()).to_dataset(name=varnsproof) #harmonize the nan's between both datasets (independent calculations would destroy lincor), part A
        self.DSref   = self.DSref[varnsref].where(self.DSproof[varnsproof].notnull()).to_dataset(name=varnsref)   #harmonize the nan's between both datasets, part B
        # rename the data variables and combine both datasets for evaluation
        namex=varnsres+"_x"; namey=varnsres+"_y"
        self.DSref.rename({varnsref : namey },inplace=True)
        self.DSproof.rename({varnsproof : namex },inplace=True)
        DScomb = xarray.merge([self.DSref,self.DSproof])
        coordtime     = self.MetricCalcProg.ListDimsToXarray(dim_time[varnsref])     #extract the name of time coordinate
        #
        if aggregtime == 'fullperiod':
            DSnew = correl2dtm(DScomb).to_dataset(name = varnsres)
            ...
        elif aggregtime == '-':
            print(' The Linear Corr. computation makes no sense for each single time step ')
            exit()
        elif "overperiod" in aggregtime:
            grpby_method=self.MetricCalcProg.ConvertAggregKey2Groupby(aggregtime)
            DSnew = DScomb.groupby(coordtime+'.'+grpby_method).apply(correl2dtm)
            DSnew = DSnew.to_dataset(name = varnsres)
            ...
        elif "overperiod" not in aggregtime:
                            resamplefreq=self.MetricCalcProg.ConvertAggregKey2Resample(aggregtime)
            DSnew = DScomb.resample(time=resamplefreq,keep_attrs=True).apply(correl2dtm)
            DSnew = DSnew.to_dataset(name = varnsres)
            ...
        #
        self.DSref.rename({namey : varnsref },inplace=True)
        self.DSproof.rename({namex : varnsproof },inplace=True)
        unitsnew='1'
        longnew="temporal lin. correl. of "+str(GeneralUtils.safe_access_bib('', KeyError, dicttest=self.DSref[varnsref].attrs, \
            dictkey='long_name',errhandle=False))
        self.Update_Attributes(Datasetobj=DSnew,variable=varnsres,stdname=varnsres,units=unitsnew,longname=longnew)
        endresult = xarray.merge([endresult,DSnew])
    return endresult

如您所见,与“偏差”计算相比,只有细微差别。函数定义不同。聚合时间“-”的异常只出现在“lincorru temporal”和where语句中,where语句只选择存在“notnull”数据的网格点。你知道吗

关于函数“def bias”和“def correl2dtm”的定义,您是否建议将此处定义的两种方法结合起来?我想有一种编程技术我到现在还没有掌握,那就是动态定义函数。你知道吗


Tags: nameselftruetimerenamedimnamexnamey
1条回答
网友
1楼 · 发布于 2024-09-27 21:30:41

函数是python中的对象,因此可以将它们指定给变量。可以将它们作为函数参数传递:

def bias(x, namex, namey, coordtime=False):
    return (x[namex] - x[namey])

def correl2dtm(x, namex, namey, coordtime):
    a = (x[namex] - x[namex].mean(dim=coordtime)) * (x[namey] - x[namey].mean(dim=coordtime)) \
        / x[namex].std(dim=coordtime) / x[namey].std(dim=coordtime)
    return a.mean(dim=coordtime)

def temporal(self, func, varns_result=None,aggregtime=None,dim_time=None):
    ...
    DSnew = func(DScomb, namex, namey, coordtime).to_dataset(name = varnsres)
    ...

# call temporal() with bias function (= old BIAS_temporal)
temporal(bias, ...)

# call temporal() with correl2dtm (= old LinCorr_temporal)
temporal(correl2dtm, ...)

相关问题 更多 >

    热门问题