Exemple #1
0
    def post(self,fetched,slab,axes,specifications,confined_by,aux,axismap):
        ''' Post processing retouches the bounds and later will deal with the mask'''
        import cdms2 as cdms
        fetched=cdms.createVariable(fetched,copy=1)
        faxes=fetched.getAxisList()
        a=None
        for i in range(len(faxes)):
            if confined_by[i] is self:
                newaxvals=[]
                bounds=[]
                a=None
                sh=list(fetched.shape)
                sh[i]=1
                for l in self.aux[i]:
                    try:
                        tmp=fetched(**{faxes[i].id:(l,l)})
                        ax=tmp.getAxis(i)
                        #print ax
                        newaxvals.append(ax[0])
			if ax.getBounds()!=None:
                   	     bounds.append(ax.getBounds()[0])
			else:
			     bounds=None
                    except Exception,err:
                        #print 'err:',err,'match:',self.match
                        if self.match==1:
                            raise Exception,'Error axis value :'+str(l)+' was requested but is not present in slab\n(more missing might exists)'
                        elif self.match==0:
                            tmp=MV2.ones(sh,typecode=MV2.float)
                            tmp=MV2.masked_equal(tmp,1)
                            if type(l)==type(cdtime.comptime(1999)) or type(l)==type(cdtime.reltime(0,'days since 1999')) or type(l)==type(''):
                                if type(l)!=type(''):
                                    newaxvals.append(l.torel(faxes[i].units).value)
                                else:
                                    newaxvals.append(cdtime.s2r(l,faxes[i].units).value)
                            else:
                                newaxvals.append(l)
                            if bounds is not None:
                                bounds.append([ax[-1]-1.,ax[-1]+1])
                        else:
                            tmp=None
                    if not tmp is None:
                        if a is None:
                            a=tmp
                        elif not tmp is None:
                            a=MV2.concatenate((a,tmp),i)
                if bounds is not None:
			newax=cdms.createAxis(numpy.array(newaxvals),bounds=numpy.array(bounds),id=ax.id)
		else:
			newax=cdms.createAxis(numpy.array(newaxvals),id=ax.id)
                for att in faxes[i].attributes.keys():
                    setattr(newax,att,faxes[i].attributes.get(att))
                for j in range(len(fetched.shape)):
                    if j==i:
                        a.setAxis(i,newax)
                    else:
                        a.setAxis(j,faxes[j])
                fetched=a.astype(fetched.dtype.char)
                faxes=fetched.getAxisList()
Exemple #2
0
    def post(self,fetched,slab,axes,specifications,confined_by,aux,axismap):
        ''' Post processing retouches the bounds and later will deal with the mask'''
        import cdms2 as cdms
        fetched=cdms.createVariable(fetched,copy=1)
        faxes=fetched.getAxisList()
        a=None
        for i in range(len(faxes)):
            if confined_by[i] is self:
                newaxvals=[]
                bounds=[]
                a=None
                sh=list(fetched.shape)
                sh[i]=1
                for l in self.aux[i]:
                    try:
                        tmp=fetched(**{faxes[i].id:(l,l)})
                        ax=tmp.getAxis(i)
                        #print ax
                        newaxvals.append(ax[0])
			if ax.getBounds()!=None:
                   	     bounds.append(ax.getBounds()[0])
			else:
			     bounds=None
                    except Exception,err:
                        #print 'err:',err,'match:',self.match
                        if self.match==1:
                            raise Exception,'Error axis value :'+str(l)+' was requested but is not present in slab\n(more missing might exists)'
                        elif self.match==0:
                            tmp=MV2.ones(sh,typecode=MV2.float)
                            tmp=MV2.masked_equal(tmp,1)
                            if type(l)==type(cdtime.comptime(1999)) or type(l)==type(cdtime.reltime(0,'days since 1999')) or type(l)==type(''):
                                if type(l)!=type(''):
                                    newaxvals.append(l.torel(faxes[i].units).value)
                                else:
                                    newaxvals.append(cdtime.s2r(l,faxes[i].units).value)
                            else:
                                newaxvals.append(l)
                            if bounds is not None:
                                bounds.append([ax[-1]-1.,ax[-1]+1])
                        else:
                            tmp=None
                    if not tmp is None:
                        if a is None:
                            a=tmp
                        elif not tmp is None:
                            a=MV2.concatenate((a,tmp),i)
                if bounds is not None:
			newax=cdms.createAxis(numpy.array(newaxvals),bounds=numpy.array(bounds),id=ax.id)
		else:
			newax=cdms.createAxis(numpy.array(newaxvals),id=ax.id)
                for att in faxes[i].attributes.keys():
                    setattr(newax,att,faxes[i].attributes.get(att))
                for j in range(len(fetched.shape)):
                    if j==i:
                        a.setAxis(i,newax)
                    else:
                        a.setAxis(j,faxes[j])
                fetched=a.astype(fetched.dtype.char)
                faxes=fetched.getAxisList()
Exemple #3
0
def createMapping(filename):
    vars, files, csv = ingestCSV(filename)
    print("FILE ):<{}>".format(files[0]))

    out = {}

    f = cdms2.open(files[0])
    times = []
    time_values = []
    time_partition = []
    nontimes = []
    for v in f.listvariables():
        tim = f[v].getTime()
        if tim is None:  # not a time one
            nontimes.append(v)
        else:
            times.append(v)

    map_files = []
    index = 0
    for l in csv:
        if l.strip() == "":
            break
        sp = l.strip().split(",")
        time_values.append(
            cdtime.s2r(sp[0], tim.units, tim.getCalendar()).value)
        indx = vars.index(times[0])
        location = int(sp[indx].split(":")[0])
        if len(map_files) == 0:
            map_files.append([location, [index, index]])
            time_partition.append(index)
        elif map_files[-1][0] != location:
            map_files.append([location, [index, index]])
            time_partition.append(index)
        else:  # same file
            map_files[-1][1][-1] = index + 1
            time_partition[-1] = index + 1
        index += 1
    print(map_files)
    mapping = "[[" + str(times).replace("'", "") + ",["
    mapping += ",".join([
        "[{},{},-,-,-,{}]".format(v[0], v[1], os.path.basename(files[nm]))
        for nm, v in map_files
    ])
    mapping += "]],[" + str(nontimes).replace(
        "'", "") + ",[[-,-,-,-,-,{}]]]]".format(
            os.path.basename(files[map_files[0][0]]))
    out["mapping"] = mapping
    out["time"] = {
        "id": tim.id,
        "values": time_values,
        "partition": time_partition
    }
    out["files"] = files
    out["vars"] = vars
    out["directory"] = os.path.dirname(files[map_files[0][0]])
    return out
Exemple #4
0
def getTimeSubsetStartEndIndices(time_axis, start, end, required_hour=None):
    """
    Analyses time_axis and returns a (start_index, end_index) tuple that
    represent the correct indices in the array for start and end. If
    required_hour is given then it also checks start is set on the time
    of day (e.g. 0 for midnight and 12 for midday) expected. If not it adjusts
    the start_index so it is on the required_hour. It does NOT adjust the
    end_index.
    """

    units = time_axis.units
    start_time = cdtime.s2r(start, units, cdtime.Calendar360)
    end_time = cdtime.s2r(end, units, cdtime.Calendar360)

    # Check hour of start_time if required
    if required_hour != None:
        required_hour = int(required_hour)
        comp_time = start_time.tocomp()
        hour = comp_time.hour
        print start_time
        print start_time.tocomp()
        print hour
        if hour != required_hour:
            print "Adjusting to next day to get required hour right."
            new_start = comp_time.add(1, cdtime.Day)
            new_start.hour = required_hour
            print "New start time:", new_start
            start_time = new_start.torel(units, cdtime.Calendar360)

    start_value = start_time.value
    end_value = end_time.value

    # Check both indices are in the axis values
    if start_value not in time_axis[:]:
        raise Exception("Start index not in axis values: " + str(start_value))
    if end_value not in time_axis[:]:
        raise Exception("End index not in axis values: " + str(end_value))

    t_values = list(time_axis[:])

    start_index = t_values.index(start_value)
    end_index = t_values.index(end_value)

    return (start_index, end_index)
Exemple #5
0
    def specify(self,slab,axes,specification,confined_by,aux):
        ''' First part: confine the slab within a Domain wide enough to do the exact in post'''
        import string,copy
        from numpy.ma import minimum,maximum
        # myconfined is for later, we can't confine a dimension twice with an argument plus a keyword or 2 keywords
        myconfined=[None]*len(axes)
        self.aux=copy.copy(specification)
        # First look at the arguments (i.e not keywords) and confine the dimensions
        # in the order of the arguments
        for i in range(len(self.args)):
            if confined_by[i] is None :  # Check it hasn't been confined by somebody else
                myconfined[i]=1  # dim confined by argument list
                confined_by[i]=self # for cdms I want to confine this dimension
                self.aux[i]=specs=list(self.args[i]) # How do we want to confine this dim ?
                if type(specs)==type(slice(0)):
                    specification[i]=specs  # If it's a slicing nothing to do
                else: # But if it's not...
                    if specs[0] is None:
                        tmp=axes[i].getBounds()
                        if tmp is None:
                            raise ValueError, 'Region error, axis:'+axes[i].id+' has no bounds'
                        specs[0]=minimum(minimum(tmp[0],tmp[-1]))
                    if specs[1] is None:
                        tmp=axes[i].getBounds()
                        if tmp is None:
                            raise ValueError, 'Region error, axis:'+axes[i].id+' has no bounds'
                        specs[1]=maximum(maximum(tmp[0],tmp[-1]))
                    if axes[i].isTime(): # Time is as always "Special"
                        import cdtime
                        tc=type(cdtime.comptime(0))  # component time type
                        tr=type(cdtime.reltime(0,'months since 0'))  # relative time type
                        t=type(specs[0]) # my first spec type
                        if t==type(''): #if my first spec is passed as a string
                            specs[0]=cdtime.s2r(specs[0],axes[i].units)
                        elif t==tc or t==tr: #if my first spec is passed as a cdtime object
                            specs[0]=cdtime.torel(specs[0],axes[i].units)
                        else: # If not it has to be that the users knows the time values in the axis
                            pass
                        t=type(specs[1]) # my second spec type
                        if t==type(''): #if my second spec is passed as a string
                            specs[1]=cdtime.s2r(specs[1],axes[i].units)
                        elif t==tc or t==tr: #if my second spec is passed as a cdtime object
                            specs[1]=cdtime.torel(specs[1],axes[i].units)
                    sp=[specs[0],specs[1],'oob']  # Now retrieve the values wide enough for the exact                    specification[i]=sp  # sets the specifications
            else:
                return 1
        for kw in self.kargs.keys():
            axis=None
            for i in range(len(axes)):
                if axes[i].id==kw : axis=i
            if axis is None:
                if kw=='time' :
                    for i in range(len(axes)):
                        if axes[i].isTime() : axis=i
                elif kw=='level' :
                    for i in range(len(axes)):
                        if axes[i].isLevel() : axis=i
                elif kw=='longitude' :
                    for i in range(len(axes)):
                        if axes[i].isLongitude() : axis=i
                elif kw=='latitude' :
                    for i in range(len(axes)):
                        if axes[i].isLatitude() : axis=i
                elif not kw in ['exact','atol','rtol']: # keyword not a recognised keyword or dimension name
                    raise 'Error, keyword: '+kw+' not recognized'
            # At this point, if axis is None:
            # we are dealing with a keyword for the selector
            # so we'll skip it
            if not axis is None : 
                if confined_by[axis] is None:
                    confined_by[axis]=self
                    myconfined[axis]=1
                    self.aux[axis]=specs=list(self.kargs[kw])
                    if type(specs)!=type(slice(0)):
                        if specs[0] is None:
                            tmp=axes[axis].getBounds()
                            if tmp is None:
                                raise ValueError, 'Region error, axis:'+axes[axis].id+' has no bounds'
                            specs[0]=minimum(minimum(tmp[0],tmp[-1]))
                        if specs[1] is None:
                            tmp=axes[axis].getBounds()
                            if tmp is None:
                                raise ValueError, 'Region error, axis:'+axes[axis].id+' has no bounds'
                            specs[1]=maximum(maximum(tmp[0],tmp[-1]))
                        if axes[axis].isTime():
                            import cdtime
                            tc=type(cdtime.comptime(0))
                            tr=type(cdtime.reltime(0,'months since 0'))
                            t=type(specs[0])
                            if t==type(''):
                                specs[0]=cdtime.s2r(specs[0],axes[i].units)
                            elif t==tc or t==tr:
                                specs[0]=cdtime.torel(specs[0],axes[i].units)
                            t=type(specs[1])
                            if t==type(''):
                                specs[1]=cdtime.s2r(specs[1],axes[i].units)
                            elif t==tc or t==tr:
                                specs[1]=cdtime.torel(specs[1],axes[i].units)
                        sp=[specs[0],specs[1],'oob']
                        specification[axis]=sp
                    else:
                        specification[axis]=specs

                else:
                    if myconfined[axis]==1:
                        raise 'Error you are attempting to set the axis: '+str(axes[axis].id)+' more than once'
                    else:
                        return 1
        return 0
Exemple #6
0
    def specify(self, slab, axes, specification, confined_by, aux):
        ''' First part: confine the slab within a Domain wide enough to do the exact in post'''
        import string, copy
        from numpy.ma import minimum, maximum
        # myconfined is for later, we can't confine a dimension twice with an argument plus a keyword or 2 keywords
        myconfined = [None] * len(axes)
        self.aux = copy.copy(specification)
        # First look at the arguments (i.e not keywords) and confine the dimensions
        # in the order of the arguments
        for i in range(len(self.args)):
            if confined_by[
                    i] is None:  # Check it hasn't been confined by somebody else
                myconfined[i] = 1  # dim confined by argument list
                confined_by[
                    i] = self  # for cdms I want to confine this dimension
                self.aux[i] = specs = list(
                    self.args[i])  # How do we want to confine this dim ?
                if not (isinstance(specs, list) or isinstance(specs, tuple)):
                    raise Exception, "Error in Selector, you must specify a list or a tuple, you passed:" + str(
                        specs)
                elif type(specs[0]) == type(
                        cdtime.comptime(1999)) or type(specs[0]) == type(
                            cdtime.reltime(0, 'days since 1999')) or type(
                                specs[0]) == type(''):
                    list2 = []
                    for l in specs:
                        if type(l) != type(''):
                            list2.append(l.torel('days since 1900').value)
                        else:
                            list2.append(
                                cdtime.s2r(l, 'days since 1900').value)
                    min = minimum(list2)
                    max = maximum(list2)
                    specification[i] = cdtime.reltime(
                        min, 'days since 1900'), cdtime.reltime(
                            max, 'days since 1900')
                else:  # But if it's not...
                    specification[i] = minimum(specs), maximum(
                        specs)  # sets the specifications
            else:
                return 1
        for kw in self.kargs.keys():
            axis = None
            for i in range(len(axes)):
                if axes[i].id == kw: axis = i
            if axis is None:
                if kw == 'time':
                    for i in range(len(axes)):
                        if axes[i].isTime(): axis = i
                elif kw == 'level':
                    for i in range(len(axes)):
                        if axes[i].isLevel(): axis = i
                elif kw == 'longitude':
                    for i in range(len(axes)):
                        if axes[i].isLongitude(): axis = i
                elif kw == 'latitude':
                    for i in range(len(axes)):
                        if axes[i].isLatitude(): axis = i
                elif not kw in [
                        'match'
                ]:  # keyword not a recognised keyword or dimension name
                    raise Exception, 'Error, keyword: ' + kw + ' not recognized'
            # At this point, if axis is None:
            # we are dealing with a keyword for the selector
            # so we'll skip it
            if not axis is None:
                if confined_by[axis] is None:
                    confined_by[axis] = self
                    myconfined[axis] = 1
                    self.aux[axis] = specs = list(self.kargs[kw])
                    if type(specs[0]) == type(cdtime.comptime(1999)) or type(
                            specs[0]) == type(
                                cdtime.reltime(0, 'days since 1999')) or type(
                                    specs[0]) == type(''):
                        list2 = []
                        for l in specs:
                            if type(l) != type(''):
                                list2.append(l.torel('days since 1900').value)
                            else:
                                list2.append(
                                    cdtime.s2r(l, 'days since 1900').value)
                        min = minimum(list2)
                        max = maximum(list2)
                        specification[axis] = cdtime.reltime(
                            min, 'days since 1900'), cdtime.reltime(
                                max, 'days since 1900')
                    else:  # But if it's not...
                        specification[axis] = minimum(specs), maximum(specs)

                else:
                    if myconfined[axis] == 1:
                        raise 'Error you are attempting to set the axis: ' + str(
                            axes[axis].id) + ' more than once'
                    else:
                        return 1
        return 0
Exemple #7
0
    def specify(self, slab, axes, specification, confined_by, aux):
        ''' First part: confine the slab within a Domain wide enough to do the exact in post'''
        import string, copy
        from numpy.ma import minimum, maximum
        # myconfined is for later, we can't confine a dimension twice with an argument plus a keyword or 2 keywords
        myconfined = [None] * len(axes)
        self.aux = copy.copy(specification)
        # First look at the arguments (i.e not keywords) and confine the dimensions
        # in the order of the arguments
        for i in range(len(self.args)):
            if confined_by[
                    i] is None:  # Check it hasn't been confined by somebody else
                myconfined[i] = 1  # dim confined by argument list
                confined_by[
                    i] = self  # for cdms I want to confine this dimension
                self.aux[i] = specs = list(
                    self.args[i])  # How do we want to confine this dim ?
                if type(specs) == type(slice(0)):
                    specification[i] = specs  # If it's a slicing nothing to do
                else:  # But if it's not...
                    if specs[0] is None:
                        tmp = axes[i].getBounds()
                        if tmp is None:
                            raise ValueError, 'Region error, axis:' + axes[
                                i].id + ' has no bounds'
                        specs[0] = minimum(minimum(tmp[0], tmp[-1]))
                    if specs[1] is None:
                        tmp = axes[i].getBounds()
                        if tmp is None:
                            raise ValueError, 'Region error, axis:' + axes[
                                i].id + ' has no bounds'
                        specs[1] = maximum(maximum(tmp[0], tmp[-1]))
                    if axes[i].isTime():  # Time is as always "Special"
                        import cdtime
                        tc = type(cdtime.comptime(0))  # component time type
                        tr = type(cdtime.reltime(
                            0, 'months since 0'))  # relative time type
                        t = type(specs[0])  # my first spec type
                        if t == type(
                                ''):  #if my first spec is passed as a string
                            specs[0] = cdtime.s2r(specs[0], axes[i].units)
                        elif t == tc or t == tr:  #if my first spec is passed as a cdtime object
                            specs[0] = cdtime.torel(specs[0], axes[i].units)
                        else:  # If not it has to be that the users knows the time values in the axis
                            pass
                        t = type(specs[1])  # my second spec type
                        if t == type(
                                ''):  #if my second spec is passed as a string
                            specs[1] = cdtime.s2r(specs[1], axes[i].units)
                        elif t == tc or t == tr:  #if my second spec is passed as a cdtime object
                            specs[1] = cdtime.torel(specs[1], axes[i].units)
                    sp = [
                        specs[0], specs[1], 'oob'
                    ]  # Now retrieve the values wide enough for the exact                    specification[i]=sp  # sets the specifications
            else:
                return 1
        for kw in self.kargs.keys():
            axis = None
            for i in range(len(axes)):
                if axes[i].id == kw: axis = i
            if axis is None:
                if kw == 'time':
                    for i in range(len(axes)):
                        if axes[i].isTime(): axis = i
                elif kw == 'level':
                    for i in range(len(axes)):
                        if axes[i].isLevel(): axis = i
                elif kw == 'longitude':
                    for i in range(len(axes)):
                        if axes[i].isLongitude(): axis = i
                elif kw == 'latitude':
                    for i in range(len(axes)):
                        if axes[i].isLatitude(): axis = i
                elif not kw in [
                        'exact', 'atol', 'rtol'
                ]:  # keyword not a recognised keyword or dimension name
                    raise 'Error, keyword: ' + kw + ' not recognized'
            # At this point, if axis is None:
            # we are dealing with a keyword for the selector
            # so we'll skip it
            if not axis is None:
                if confined_by[axis] is None:
                    confined_by[axis] = self
                    myconfined[axis] = 1
                    self.aux[axis] = specs = list(self.kargs[kw])
                    if type(specs) != type(slice(0)):
                        if specs[0] is None:
                            tmp = axes[axis].getBounds()
                            if tmp is None:
                                raise ValueError, 'Region error, axis:' + axes[
                                    axis].id + ' has no bounds'
                            specs[0] = minimum(minimum(tmp[0], tmp[-1]))
                        if specs[1] is None:
                            tmp = axes[axis].getBounds()
                            if tmp is None:
                                raise ValueError, 'Region error, axis:' + axes[
                                    axis].id + ' has no bounds'
                            specs[1] = maximum(maximum(tmp[0], tmp[-1]))
                        if axes[axis].isTime():
                            import cdtime
                            tc = type(cdtime.comptime(0))
                            tr = type(cdtime.reltime(0, 'months since 0'))
                            t = type(specs[0])
                            if t == type(''):
                                specs[0] = cdtime.s2r(specs[0], axes[i].units)
                            elif t == tc or t == tr:
                                specs[0] = cdtime.torel(
                                    specs[0], axes[i].units)
                            t = type(specs[1])
                            if t == type(''):
                                specs[1] = cdtime.s2r(specs[1], axes[i].units)
                            elif t == tc or t == tr:
                                specs[1] = cdtime.torel(
                                    specs[1], axes[i].units)
                        sp = [specs[0], specs[1], 'oob']
                        specification[axis] = sp
                    else:
                        specification[axis] = specs

                else:
                    if myconfined[axis] == 1:
                        raise 'Error you are attempting to set the axis: ' + str(
                            axes[axis].id) + ' more than once'
                    else:
                        return 1
        return 0
Exemple #8
0
 def renderTemplate(self,tmpl,data,gm,taxis,zaxis):
   ## ok first basic template stuff, let's store the displays
   ## because we need to return actors for min/max/mean
   displays = tmpl.plot(self.canvas,data,gm,bg=self.bg)
   returned = {}
   for d in displays:
       if d is None:
         continue
       texts=d.backend.get("vtk_backend_text_actors",[])
       for t in texts:
         ## ok we had a text actor, let's see if it's min/max/mean
         txt = t.GetInput()
         s0=txt.split()[0]
         if s0 in ["Min","Max","Mean"]:
             returned["vtk_backend_%s_text_actor" % s0] = t
         else:
             returned["vtk_backend_%s_text_actor" % d.backend["vtk_backend_template_attribute"]] = t
       self.canvas.display_names.remove(d.name)
       del(vcs.elements["display"][d.name])
   ## Sometimes user passes "date" as an attribute to replace date
   if hasattr(data,"user_date"):
       taxis = cdms2.createAxis([cdtime.s2r(data.user_date,"days since 1900").value])
       taxis.designateTime()
       taxis.units="days since 1900"
       if zaxis is not None and zaxis.isTime():
           zaxis=taxis
   if taxis is not None:
     try:
       tstr = str(cdtime.reltime(taxis[0],taxis.units).tocomp(taxis.getCalendar()))
       #ok we have a time axis let's display the time
       crdate = vcs2vtk.applyAttributesFromVCStmpl(tmpl,"crdate")
       crdate.string = tstr.split()[0].replace("-","/")
       crtime = vcs2vtk.applyAttributesFromVCStmpl(tmpl,"crtime")
       crtime.string = tstr.split()[1]
       if not (None,None,None) in self._renderers.keys():
           ren = self.createRenderer()
           self.renWin.AddRenderer(ren)
           self.setLayer(ren,1)
           self._renderers[(None,None,None)]=ren
       else:
           ren = self._renderers[(None,None,None)]
       tt,to = crdate.name.split(":::")
       tt = vcs.elements["texttable"][tt]
       to = vcs.elements["textorientation"][to]
       if crdate.priority>0:
           actors = vcs2vtk.genTextActor(ren,to=to,tt=tt)
           returned["vtk_backend_crdate_text_actor"]=actors[0]
       del(vcs.elements["texttable"][tt.name])
       del(vcs.elements["textorientation"][to.name])
       del(vcs.elements["textcombined"][crdate.name])
       tt,to = crtime.name.split(":::")
       tt = vcs.elements["texttable"][tt]
       to = vcs.elements["textorientation"][to]
       if crtime.priority>0:
           actors = vcs2vtk.genTextActor(ren,to=to,tt=tt)
           returned["vtk_backend_crtime_text_actor"]=actors[0]
       del(vcs.elements["texttable"][tt.name])
       del(vcs.elements["textorientation"][to.name])
       del(vcs.elements["textcombined"][crtime.name])
     except:
         pass
   if zaxis is not None:
     try:
       # ok we have a zaxis to draw
       zname = vcs2vtk.applyAttributesFromVCStmpl(tmpl,"zname")
       zname.string=zaxis.id
       zvalue = vcs2vtk.applyAttributesFromVCStmpl(tmpl,"zvalue")
       if zaxis.isTime():
           zvalue.string = str(zaxis.asComponentTime()[0])
       else:
           zvalue.string= "%g" % zaxis[0]
       if not (None,None,None) in self._renderers.keys():
           ren = self.createRenderer()
           self.renWin.AddRenderer(ren)
           self.setLayer(ren,1)
           self._renderers[(None,None,None)]=ren
       else:
           ren = self._renderers[(None,None,None)]
       tt,to = zname.name.split(":::")
       tt = vcs.elements["texttable"][tt]
       to = vcs.elements["textorientation"][to]
       if zname.priority>0:
           vcs2vtk.genTextActor(ren,to=to,tt=tt)
       del(vcs.elements["texttable"][tt.name])
       del(vcs.elements["textorientation"][to.name])
       del(vcs.elements["textcombined"][zname.name])
       if hasattr(zaxis,"units"):
           zunits = vcs2vtk.applyAttributesFromVCStmpl(tmpl,"zunits")
           zunits.string=zaxis.units
           if zunits.priority>0:
               tt,to = zunits.name.split(":::")
               tt = vcs.elements["texttable"][tt]
               to = vcs.elements["textorientation"][to]
               vcs2vtk.genTextActor(ren,to=to,tt=tt)
               del(vcs.elements["texttable"][tt.name])
               del(vcs.elements["textorientation"][to.name])
               del(vcs.elements["textcombined"][zunits.name])
       tt,to = zvalue.name.split(":::")
       tt = vcs.elements["texttable"][tt]
       to = vcs.elements["textorientation"][to]
       if zvalue.priority>0:
           actors = vcs2vtk.genTextActor(ren,to=to,tt=tt)
           returned["vtk_backend_zvalue_text_actor"]=actors[0]
       del(vcs.elements["texttable"][tt.name])
       del(vcs.elements["textorientation"][to.name])
       del(vcs.elements["textcombined"][zvalue.name])
     except:
         pass
   return returned
Exemple #9
0
    def specify(self, slab, axes, specification, confined_by, aux):
        """ First part: confine the slab within a Domain wide enough to do the exact in post"""
        import string, copy
        from numpy.ma import minimum, maximum

        # myconfined is for later, we can't confine a dimension twice with an argument plus a keyword or 2 keywords
        myconfined = [None] * len(axes)
        self.aux = copy.copy(specification)
        # First look at the arguments (i.e not keywords) and confine the dimensions
        # in the order of the arguments
        for i in range(len(self.args)):
            if confined_by[i] is None:  # Check it hasn't been confined by somebody else
                myconfined[i] = 1  # dim confined by argument list
                confined_by[i] = self  # for cdms I want to confine this dimension
                self.aux[i] = specs = list(self.args[i])  # How do we want to confine this dim ?
                if not (isinstance(specs, list) or isinstance(specs, tuple)):
                    raise Exception, "Error in Selector, you must specify a list or a tuple, you passed:" + str(specs)
                elif (
                    type(specs[0]) == type(cdtime.comptime(1999))
                    or type(specs[0]) == type(cdtime.reltime(0, "days since 1999"))
                    or type(specs[0]) == type("")
                ):
                    list2 = []
                    for l in specs:
                        if type(l) != type(""):
                            list2.append(l.torel("days since 1900").value)
                        else:
                            list2.append(cdtime.s2r(l, "days since 1900").value)
                    min = minimum(list2)
                    max = maximum(list2)
                    specification[i] = cdtime.reltime(min, "days since 1900"), cdtime.reltime(max, "days since 1900")
                else:  # But if it's not...
                    specification[i] = minimum(specs), maximum(specs)  # sets the specifications
            else:
                return 1
        for kw in self.kargs.keys():
            axis = None
            for i in range(len(axes)):
                if axes[i].id == kw:
                    axis = i
            if axis is None:
                if kw == "time":
                    for i in range(len(axes)):
                        if axes[i].isTime():
                            axis = i
                elif kw == "level":
                    for i in range(len(axes)):
                        if axes[i].isLevel():
                            axis = i
                elif kw == "longitude":
                    for i in range(len(axes)):
                        if axes[i].isLongitude():
                            axis = i
                elif kw == "latitude":
                    for i in range(len(axes)):
                        if axes[i].isLatitude():
                            axis = i
                elif not kw in ["match"]:  # keyword not a recognised keyword or dimension name
                    raise Exception, "Error, keyword: " + kw + " not recognized"
            # At this point, if axis is None:
            # we are dealing with a keyword for the selector
            # so we'll skip it
            if not axis is None:
                if confined_by[axis] is None:
                    confined_by[axis] = self
                    myconfined[axis] = 1
                    self.aux[axis] = specs = list(self.kargs[kw])
                    if (
                        type(specs[0]) == type(cdtime.comptime(1999))
                        or type(specs[0]) == type(cdtime.reltime(0, "days since 1999"))
                        or type(specs[0]) == type("")
                    ):
                        list2 = []
                        for l in specs:
                            if type(l) != type(""):
                                list2.append(l.torel("days since 1900").value)
                            else:
                                list2.append(cdtime.s2r(l, "days since 1900").value)
                        min = minimum(list2)
                        max = maximum(list2)
                        specification[axis] = (
                            cdtime.reltime(min, "days since 1900"),
                            cdtime.reltime(max, "days since 1900"),
                        )
                    else:  # But if it's not...
                        specification[axis] = minimum(specs), maximum(specs)

                else:
                    if myconfined[axis] == 1:
                        raise "Error you are attempting to set the axis: " + str(axes[axis].id) + " more than once"
                    else:
                        return 1
        return 0
Exemple #10
0
    def __init__(self, axis, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.isTime = axis.isTime()
        self.indexMode = False
        self.startIndex = 0
        self.isModuloed = False
        self.isLat = False
        self.isLon = False

        # Init Layout
        hbox = QtGui.QHBoxLayout()
        vbox = QtGui.QVBoxLayout()
        vbox.setSpacing(0)
        vbox.setMargin(0)        
        self.setLayout(hbox)

        # Init combo box
        self.axisCombo = QAxisComboWidget()
        hbox.addWidget(self.axisCombo)

        # Init sliders
        hbox.addLayout(vbox)
        self.topLabel = QtGui.QLabel('From', self)
        hbox = QtGui.QHBoxLayout()        
        hbox.addWidget(self.topLabel)
        vbox.addLayout(hbox)
        self.topSlider = QtGui.QSlider(QtCore.Qt.Horizontal)
        self.topSlider.setTickPosition(QtGui.QSlider.TicksAbove)
        tip = "Use left/right arrows to move slider by 1 unit"
        self.topSlider.setToolTip(tip)
        self.bottomSlider = QtGui.QSlider(QtCore.Qt.Horizontal)        
        self.bottomSlider.setTickPosition(QtGui.QSlider.TicksBelow)
        self.bottomSlider.setToolTip(tip)
        vbox.addWidget(self.topSlider)
        vbox.addWidget(self.bottomSlider)

        # Init axis slider value labels
        self.bottomLabel = QtGui.QLabel('To', self)
        self.bottomLabel.setAlignment(QtCore.Qt.AlignRight)
        aLabel = QtGui.QLabel('', self)
        hbox = QtGui.QHBoxLayout()        
        #hbox.addWidget(aLabel)
        hbox.addWidget(self.bottomLabel)
        vbox.addLayout(hbox)

        # Initialize the sliders' and comboBox's values
#        self.initialAxis = copy_axis( axis )
        self.initAxisValues(axis)
        self.setSlidersMinMax()
        if self.isModuloed:
            self.updateTopSlider(self.findAxisIndex(axis[0]))
        else:
            self.topSlider.setValue(self.minIndex)
            
        if self.isModuloed:
            self.updateBottomSlider(self.findAxisIndex(axis[-1]))
        else:
            self.bottomSlider.setValue(self.maxIndex)
        self.axisCombo.initValues(self.axisValues)

        # Connect Signals
        self.connect(self.topSlider, QtCore.SIGNAL('valueChanged (int)'),
                     self.updateMin)
        self.connect(self.bottomSlider, QtCore.SIGNAL('valueChanged (int)'),
                     self.updateMax)
        self.connect(self.axisCombo,
                     QtCore.SIGNAL('axisComboMinValueChanged (int)'),
                     self.updateTopSlider)
        self.connect(self.axisCombo,
                     QtCore.SIGNAL('axisComboMaxValueChanged (int)'),
                     self.updateBottomSlider)
        if self.isModuloed:
            self.updateMin(self.findAxisIndex(axis[0]))
            self.updateMax(self.findAxisIndex(axis[-1]))

        #Ok at tht point let see if it is a "pinned" axis
        if axis.isTime():
            k="UVTIMEAXIS"
        elif axis.isLatitude():
            k="UVLATAXIS"
            self.isLat = True
        elif axis.isLongitude():
            k="UVLONAXIS"
            self.isLon = True
        elif axis.isLevel():
            k="UVLEVELAXIS"
        else:
            k=axis.id
        if k in pins and pins[k]["pinned"]:
            v1,v2=pins[k]["vals"]
            if axis.isTime():
                v1=cdtime.s2r(v1,axis.units,axis.getCalendar()).value
                v2=cdtime.s2r(v2,axis.units,axis.getCalendar()).value
            try: # If this falis then we don't need to worry about restting or pinning this guy he's outside the range
                # But if it faisl other should still be able to be pinned
                i1,i2=axis.mapInterval((v1,v2))
                self.updateTopSlider(i1)
                self.updateBottomSlider(i2)
                self.parent().pin.click()
            except:
                pass
# - a partir d'une chaines de caracteres
ctime = cdtime.s2c('2000-1-1 0')
# - on verifie
print ctime
#  -> 2000-1-1 0:0:0.0
# - on verifie des valeurs numeriques
print ctime.year,ctime.day
#  -> 2000 1

# Creer un objet 'reltime' : temps relatif
# - en specifiant explicitement (valeur, unites CF)
rtime = cdtime.reltime(50, 'years since 1950')
print '%s | %s | %s' %(rtime,rtime.value,rtime.units)
#  -> 50.000000 years since 1950 | 50.0 | years since 1950
# - a partir d'une chaines de caracteres et d'unites
rtime = cdtime.s2r('2000-1-1 0','years since 1950')
print rtime.value
#  -> 50.0

# Operations
# - soustraction/addition
print ctime.add(1,cdtime.Year),'|',rtime.add(-1,cdtime.Year)
#  -> 2001-1-1 0:0:0.0 | 49.00 years since 1950
# - conversions
rtime2 = ctime.torel('days since 2000')
ctime2 = rtime.tocomp().add(1,cdtime.Year)
# - comparaison
print rtime2 == rtime
#  -> True
print ctime2 <= ctime
#  -> False