Changeset 12660


Ignore:
Timestamp:
07/19/12 11:46:26 (13 years ago)
Author:
jschierm
Message:

Python versions of WriteData and pairoptions.

Location:
issm/trunk-jpl/src/m
Files:
1 added
2 edited

Legend:

Unmodified
Added
Removed
  • issm/trunk-jpl/src/m/classes/pairoptions.py

    r12038 r12660  
    1 class pairoptions:
    2         #properties
    3         def __init__(self,*args):
    4                 # {{{ Properties
    5                 if len(args)%2==1:
    6                         raise RuntimeError('pairoption error message: an even number of options is required')
    7 
    8                 #create a pairoption object
    9                 if len(args)==0:
    10                         self.list=[]
    11                 else:
    12                         self.list=[]
    13                         for i in range(int(round(len(args)/2))):
    14                                 if isinstance(args[2*i],str):
    15                                         self.list.append([args[2*i],args[2*i+1]])
     1"""
     2PAIROPTIONS class definition
     3 
     4    Usage:
     5       pairoptions=pairoptions();
     6       pairoptions=pairoptions('module',true,'solver',false);
     7"""
     8
     9from WriteData import *
     10
     11class pairoptions(object):
     12        def __init__(self,*arg):
     13                self.functionname = ''
     14                self.list         = {}
     15
     16#               %get calling function name
     17#               a=dbstack;
     18#               if length(a)>1,
     19#                       self.functionname=a(2).file(1:end-2);
     20#               else
     21#                       self.functionname='';
     22#               end
     23
     24                #initialize list
     25                if not len(arg):
     26                        pass    #Do nothing,
     27                else:
     28                        self.buildlist(*arg)
     29        # }}}
     30
     31        def buildlist(self,*arg):    # {{{
     32                """BUILDLIST - build list of objects from input"""
     33
     34                #check length of input
     35                if len(arg) % 2:
     36                        raise TypeError('error: an even number of options is required')
     37                numoptions = len(arg)/2
     38
     39                #go through arg and build list of objects
     40                for i in xrange(numoptions):
     41                        if isinstance(arg[2*i],str):
     42                                self.list[arg[2*i]] = arg[2*i+1];
     43                        else:
     44                                #option is not a string, ignore it
     45                                print "WARNING: option number %d '%s' is not a string and will be ignored." % (i+1,type(arg[2*i]))
     46        # }}}
     47
     48        def addfield(self,field,value):    # {{{
     49                """ADDFIELD - add a field to an options list"""
     50                if isinstance(field,str):
     51                        if field in self.list:
     52                                print "WARNING: field '%s' with value=%s exists and will be overwritten with value=%s." % (field,str(self.list[field]),str(value))
     53                        self.list[field] = value
     54        # }}}
     55
     56        def addfielddefault(self,field,value):    # {{{
     57                """ADDFIELDDEFAULT - add a field to an options list if it does not exist"""
     58                if isinstance(field,str):
     59                        if not field in self.list:
     60                                self.list[field] = value
     61        # }}}
     62
     63        def AssignObjectFields(self,obj2):    # {{{
     64                """ASSIGNOBJECTFIELDS - assign object fields from options"""
     65                for item in self.list.iteritems():
     66                        if item[0] in dir(obj2):
     67                                setattr(obj2,item[0],item[1])
     68                        else:
     69                                print "WARNING: field '%s' is not a property of '%s'." % (item[0],type(obj2))
     70                return obj2
     71        # }}}
     72
     73        def changefieldvalue(self,field,newvalue):    # {{{
     74                """CHANGEOPTIONVALUE - change the value of an option in an option list"""
     75
     76                self.list[field]=newvalue;
     77        # }}}
     78
     79#       function obj = deleteduplicates(obj,warn) % {{{
     80#       %DELETEDUPLICATES - delete duplicates in an option list
     81#
     82#               %track the first occurance of each option
     83#               [dummy lines]=unique(obj.list(:,1),'first');
     84#               clear dummy
     85#
     86#               %warn user if requested
     87#               if warn,
     88#                       numoptions=size(obj.list,1);
     89#                       for i=1:numoptions,
     90#                               if ~ismember(i,lines),
     91#                                       disp(['WARNING: option ' obj.list{i,1} ' appeared more than once. Only its first occurence will be kept'])
     92#                               end
     93#                       end
     94#               end
     95#
     96#               %remove duplicates from the options list
     97#               obj.list=obj.list(lines,:);
     98#       end % }}}
     99
     100        def __repr__(self):    # {{{
     101                s="   functionname: %s\n" % self.functionname
     102                if self.list:
     103                        s+="   list: (%ix%i)\n\n" % (len(self.list),2)
     104                        for item in self.list.iteritems():
     105                                if   isinstance(item[1],str):
     106                                        s+="     field: %-10s value: '%s'\n" % (item[0],item[1])
     107                                elif isinstance(item[1],(bool,int,long,float)):
     108                                        s+="     field: %-10s value: %g\n" % (item[0],item[1])
    16109                                else:
    17                                         #option is not a string, ignore it
    18                                         print("%s%i%s"%('buildlist info: option number ',i,' is not a string, it will be ignored'))
    19                                         continue
    20 
    21                 #}}}
    22         def __repr__(obj):
    23                 # {{{ Display
    24                 if not obj.list:
    25                         string='   list: empty'
    26                 else:
    27                         string="   list: (%i)"%(len(obj.list))
    28                         for i in range(len(obj.list)):
    29                                 if isinstance(obj.list[i][1],str):
    30                                         string2="     field: %-10s value: '%s'"%(obj.list[i][0],obj.list[i][1])
    31                                 elif isinstance(obj.list[i][1],float):
    32                                         string2="     field: %-10s value: %g"%(obj.list[i][0],obj.list[i][1])
    33                                 elif isinstance(obj.list[i][1],int):
    34                                         string2="     field: %-10s value: %i"%(obj.list[i][0],obj.list[i][1])
    35                                 else:
    36                                         string2="     field: %-10s value: (%i)"%(len(obj.list[i][1]))
    37                                 string="%s\n%s"%(string,string2)
    38                 return string
     110                                        s+="     field: %-10s value: %s\n" % (item[0],type(item[1]))
     111                else:
     112                        s+="   list: empty\n"
     113                return s
     114        # }}}
     115
     116        def exist(self,field):    # {{{
     117                """EXIST - check if the option exist"""
     118
     119                #some argument checking:
     120                if field == None or field == '':
     121                        raise ValueError('exist error message: bad usage');
     122                if not isinstance(field,str):
     123                        raise TypeError("exist error message: field '%s' should be a string." % str(field));
     124
     125                #Recover option
     126                if field in self.list:
     127                        return True
     128                else:
     129                        return False
     130        # }}}
     131
     132#       function num = fieldoccurences(obj,field), % {{{
     133#       %FIELDOCCURENCES - get number of occurence of a field
     134#
     135#               %check input
     136#               if ~ischar(field),
     137#                       error('fieldoccurences error message: field should be a string');
     138#               end
     139#
     140#               %get number of occurence
     141#               num=sum(strcmpi(field,obj.list(:,1)));
     142#       end % }}}
     143
     144        def getfieldvalue(self,field,default=None):    # {{{
     145                """
     146                GETOPTION - get the value of an option
     147       
     148                Usage:
     149                   value=options.getfieldvalue(field,default)
     150         
     151                Find an option value from a field. A default option
     152                can be given in input if the field does not exist
     153         
     154                Examples:
     155                   value=options.getfieldvalue(options,'caxis')
     156                   value=options.getfieldvalue(options,'caxis',[0 2])
     157                """
     158
     159                #some argument checking:
     160                if field == None or field == '':
     161                        raise ValueError('getfieldvalue error message: bad usage');
     162                if not isinstance(field,str):
     163                        raise TypeError("getfieldvalue error message: field '%s' should be a string." % str(field));
     164
     165                #Recover option
     166                if field in self.list:
     167                        value=self.list[field]
     168                else:
     169                        if not default == None:
     170                                value=default
     171                        else:
     172                                raise KeyError("error message: field '%s' has not been provided by user (and no default value has been specified)." % field)
     173
     174                return value
     175        # }}}
     176
     177        def removefield(self,field,warn):    # {{{
     178                """
     179                REMOVEFIELD - delete a field in an option list
     180         
     181                Usage:
     182                   obj=removefield(self,field,warn)
     183         
     184                if warn==1 display an info message to warn user that
     185                some of his options have been removed.
     186                """
     187
     188                #check if field exist
     189                if field in self.list:
     190
     191                        #remove duplicates from the options list
     192                        del self.list[field]
     193
     194                        #warn user if requested
     195                        if warn:
     196                                print "removefield info: option '%s' has been removed from the list of options." % field
     197        # }}}
     198
     199        def marshall(self,fid,firstindex):    # {{{
     200
     201                for i,item in enumerate(self.list.iteritems()):
     202                        name  = item[0]
     203                        value = item[1]
     204
     205                        #Write option name
     206                        WriteData(fid,'enum',(firstindex-1)+2*i+1,'data',name,'format','String')
     207
     208                        #Write option value
     209                        if   isinstance(value,str):
     210                                WriteData(fid,'enum',(firstindex-1)+2*i+2,'data',value,'format','String')
     211                        elif isinstance(value,(bool,int,long,float)):
     212                                WriteData(fid,'enum',(firstindex-1)+2*i+2,'data',value,'format','Double')
     213                        else:
     214                                raise TypeError("Cannot marshall option '%s': format not supported yet." % name)
     215        # }}}
     216
  • issm/trunk-jpl/src/m/model/WriteData.m

    r12365 r12660  
    3535%Step 2: write the data itself.
    3636if     strcmpi(format,'Boolean'),% {{{
    37         if(numel(data)~=1), error(['field ' field ' cannot be marshalled as it has more than one element!']); end
     37        if(numel(data)~=1), error(['field ' EnumToString(enum) ' cannot be marshalled as it has more than one element!']); end
    3838
    3939        %first write length of record
     
    5959        % }}}
    6060elseif strcmpi(format,'Double'), % {{{
    61         if(numel(data)~=1), error(['field ' field ' cannot be marshalled as it has more than one element!']); end
     61        if(numel(data)~=1), error(['field ' EnumToString(enum) ' cannot be marshalled as it has more than one element!']); end
    6262
    6363        %first write length of record
Note: See TracChangeset for help on using the changeset viewer.