source: TI04-geosplat/trunk/pygss/common.py @ 798

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/TI04-geosplat/trunk/pygss/common.py@798
Revision 798, 5.9 KB checked in by astephen, 14 years ago (diff)

Latest working version with install method.
Can accept more than one file but doesn't combine variables yet.

Line 
1#   Copyright (C) 2004 CCLRC & NERC( Natural Environment Research Council ).
2#   This software may be distributed under the terms of the
3#   Q Public License, version 1.0 or later. http://ndg.nerc.ac.uk/public_docs/QPublic_license.txt
4
5"""
6common.py
7=========
8
9Holds common functions and classes used in the package.
10
11"""
12
13# Import python modules
14import os
15
16# Import package modules
17from serverConfig import *
18
19# Set up commmon variables. These are CAPITALISED to
20# improve visibility in other modules.
21
22STAGES=["DatasetPage", "VariablesPage", "RenderingOptionsPage", "PlotConfigPage", "ResultsPage"]
23
24DOMAIN_PARAMS=("start_time", "end_time", "time_interval", "horiz_domain", 
25                      "resolution", "vertical_units", "vertical_domain", 
26                       "outputFormat")
27
28# Set up common functions
29
30def isUndefined(dict, item): 
31    """
32    Function that returns 1 if item is not a key in dict or
33    is defined as None in dict.
34    """
35    if dict.has_key(item):
36        if dict[item]!=None:
37            return 0
38    return 1
39   
40   
41def keyPatternMatch(dct, pattern):
42    """
43    Returns 1 if one or more keys in the dictionary 'dct' match the
44    pattern provided using string.find(). Returns 0 otherwise.
45    """
46    for key in dct.keys():
47        if key.find(pattern)>-1:
48            return 1
49    return 0
50   
51
52def getValuesInRange(start, end, array):
53    """
54    getValuesInRange function - takes a start and end value and returns the
55    values in the array that are between them.
56    """
57    # check all are floats
58    array=map(lambda x: float(x), list(array))
59    if array[0]>array[-1]: array.reverse()
60    if start>end:  (start, end)=(end, start)
61    (start, end)=(float(start), float(end))
62    rtarray=[]
63    for i in array:
64        if i>=start and i<=end:
65            rtarray.append(i)
66    return rtarray
67
68
69def translateURI(uri):
70    """
71    Takes a URL and returns the location of the file on the local network
72    or takes a local path and returns the URL of the file/directory.
73    """
74    if uri.find("http")>-1:
75        newpath=uri.replace(OUTPUT_DIR_URL, OUTPUT_DIR)
76    else:
77        newpath=uri.replace(OUTPUT_DIR, OUTPUT_DIR_URL)
78    return newpath
79
80
81def getBestName(v):
82        """
83        Returns the most appropriate variable or axis name for a long name listing.
84        """       
85        if not hasattr(v, "standard_name"):
86            if not hasattr(v, "long_name"):
87                   if not hasattr(v, "title"):
88                       if not hasattr(v, "name"):
89                           if hasattr(v, "id"):
90                               name=v.id
91                           else:
92                               name="unnamed_variable"
93                       else:
94                           name=v.name
95                   else:
96                       name=v.title
97            else:
98                   name=v.long_name
99        else:
100               name=v.standard_name
101        # Fix name to remove leading asterisks and lower case surface start.
102        name=name.replace("_", " ")
103        if name[:2]=="**": name=(name[2:]).strip()
104        if name[:7]=="surface": name=(name[7:]).strip()
105        return name
106
107
108def minmax(array):
109    """
110    Returns the min and max of any 1-D array.
111    """
112    mn=min(array)
113    mx=max(array)
114    return (mn,mx)
115
116
117def deUnicodeObject(obj):
118    """
119    Returns the object identical except unicode strings are all
120    converted to normal strings.
121    """
122    tupleFound=None
123    if type(obj)==type((1,2)): 
124        tupleFound=1
125        obj=list(obj)
126
127    if type(obj)==type([]):
128        rtobj=[]
129        for i in obj:
130            if type(i) in (type([]), type((1,2))):
131                rtobj.append(deUnicodeObject(i)) 
132            elif type(i)==type(u""):
133                rtobj.append(str(i))
134            else:
135                rtobj.append(i)
136        if tupleFound==1: rtobj=tuple(rtobj)
137
138    elif type(obj)==type(u""):
139        rtobj=str(obj)
140    else: 
141        rtobj=obj
142    return rtobj
143
144def overlap(list1, list2):
145    """
146    overlap function - returns a list of overlapping items in list1 and list2.
147    Otherwise returns None.
148    """ 
149    rtlist=[]
150    for i in list1:
151       if i in list2: rtlist.append(i)
152
153    if len(rtlist)>0:
154        return rtlist
155    else:
156        return None
157
158def makeDirsAndPerms(basedir, dirs, permissions, owner, verbose="no"):
159    """
160    A function for making directories recursively and setting permissions/ownership.
161    """
162    if type(dirs)==str: dirs=[dirs]
163    dirs=[basedir]+list(dirs)
164    dir=None
165
166    while len(dirs)>0:
167
168        if dir:
169            dir=os.path.join(dir, dirs[0])
170        else:
171            dir=dirs[0]
172        dirs=dirs[1:]
173
174        if not os.path.exists(dir):
175            if verbose=="yes":   print "Making directory:", dir
176            os.mkdir(dir)
177            os.chmod(dir, permissions)
178            os.system('/bin/chown %s %s' % (owner, dir))
179
180    return
181   
182def checkSubDirectory(user=None):
183    """
184    checkSubDirectory method - checks if the required sub-directory exists
185    to write the output and if not it creates it.
186    """ 
187    if user==None or user=="None":   user="anonymous"
188    outputDir=os.path.join(OUTPUT_DIR, user, "dx_output")
189    if not os.path.isdir(outputDir):
190        makeDirsAndPerms(OUTPUT_DIR, (user, "dx_output"), OUTPUT_DIR_PERMISSION, "%s.%s" %
191                                           (OUTPUT_FILE_USER, OUTPUT_FILE_GROUP))
192    # Local rule follows
193    if LOCAL_RULES==1:  makeAccessControlFile(user)     
194    return outputDir
195   
196# Set up common classes
197class RedirectStdout:
198    """
199    RedirectStdout class - used to direct standard output away from
200    the screen in CGI scripts.
201    """
202
203    def write(self, item):
204        """
205        write method - allows dummy standard out to work.
206        """
207        pass
208
209    def flush(self):
210        """
211        Method to do nothing, again!
212        """
213        pass
Note: See TracBrowser for help on using the repository browser.