Changeset 26871


Ignore:
Timestamp:
02/10/22 00:48:20 (3 years ago)
Author:
bdef
Message:

CHG: improving netcdf io

Location:
issm/trunk-jpl/src/m
Files:
4 edited

Legend:

Unmodified
Added
Removed
  • issm/trunk-jpl/src/m/contrib/defleurian/netCDF/export_netCDF.m

    r26858 r26871  
    137137                                                                end
    138138                                                                Var = md.(groups{i}).(fields{j}){k}.(subfields{l});
     139                                                                if sum(numel(Var) == size(Var)) == 0,  %this is a 2D array or more (and not a vector with dimension 2 = 1)
     140                                                                        Var = Var';
     141                                                                end
    139142                                                                [DimSize,DimValue,varid]=CreateVar(ncid,Var,subgroupID,subfields{l},DimSize,DimValue);
    140143                                                                if ~isempty(varid),
     
    165168
    166169                        elseif isa(Var,'struct')  % structures need special treatment
    167 
    168170                                if strcmp(groups{i}, 'results'),
    169171                                        klasstring='results.results';
     
    182184                                                if ~ismember(subfields{k}, {'errlog', 'outlog'})
    183185                                                        StackedVar=restable();
    184                                                         for l=1:Listsize
     186                                                        for l=1:Listsize,
    185187                                                                Var = md.(groups{i}).(fields{j})(l).(subfields{k});
    186188                                                                if length(Var) == 0,
     
    192194                                                        end
    193195                                                        if verbose > 4,
    194                                                                 disp(sprintf("=@@=creating var for %s.%s.%s",groups{i}, fields{j}, subfields{k}));
     196                                                                disp(sprintf("=$$=creating var for %s.%s.%s",groups{i}, fields{j}, subfields{k}));
     197                                                                disp(sprintf("last index on the list is %i",lastindex));
    195198                                                        end
    196199                                                        StackedVar=StackedVar.finalize(lastindex);
     
    218221                                        disp(sprintf("WARNING, md.%s.%s is not treated as it does not fall in one of the existing cases with class '%s'.",groups{i}, fields{j}, class(md.(groups{i}).(fields{j}))))
    219222                                end
    220                         % elseif strcmp(fields{j},'bamg')
    221                         %       klass=class(md.(groups{i}));
    222                         %       % if strcmp(klass,'struct')
    223                         %       %       klass=groups{i};
    224                         %       % end
    225                         %       netcdf.putAtt(groupID,netcdf.getConstant('NC_GLOBAL'),'classtype',klass);
    226                         %       if length(Var)>1
    227                         %               listsize=length(Var);
    228                         %               subgroupID=netcdf.defGrp(groupID,fields{j});
    229                         %               klass=class(md.(groups{i}).(fields{j}));
    230                         %               netcdf.putAtt(subgroupID,netcdf.getConstant('NC_GLOBAL'),'classtype',klass);
    231                         %               for k=1:listsize
    232                         %                       if isfield(Var(k),'step')
    233                         %                               lname=[int2str(Var(k).step)];
    234                         %                       else
    235                         %                               lname=[class(Var(k)) int2str(k)];
    236                         %                       end
    237 
    238                         %                       listgroupID=netcdf.defGrp(subgroupID,lname);
    239                         %                       klass=class(md.(groups{i}).(fields{j}){k});
    240                         %                       netcdf.putAtt(listgroupID,netcdf.getConstant('NC_GLOBAL'),'classtype',klass);
    241                         %                       subfields=fieldnames(Var(k));
    242                         %                       for l=1:length(subfields)
    243                         %                               if ~strcmp(subfields{l},'outlog')
    244                         %                                       if verbose > 4,
    245                         %                                               disp(sprintf("=[]=creating var for %s.%s[%i].%s", groups{i}, fields{j}, k, subfields{l}))
    246                         %                                       end
    247                         %                                       Var=md.(groups{i}).(fields{j}){k}.(subfields{l});
    248                         %                                       [DimSize,DimValue,varid]=CreateVar(ncid,Var,listgroupID,subfields{l},DimSize,DimValue);
    249                         %                                       if ~isempty(varid),
    250                         %                                               FillVar(Var,listgroupID,varid);
    251                         %                                       end
    252                         %                               end
    253                         %                       end
    254                         %               end
    255                                 % else
    256                                 %       subgroupID=netcdf.defGrp(groupID,fields{j});
    257                                 %       klass=class(md.(groups{i}));
    258                                 %       netcdf.putAtt(subgroupID,netcdf.getConstant('NC_GLOBAL'),'classtype',klass);
    259                                 %       subfields=fieldnames(Var);
    260                                 %       for k=1:length(subfields)
    261                                 %               if ~strcmp(subfields{k},'outlog')
    262                                 %                       if verbose > 4,
    263                                 %                               disp(sprintf("====creating var for %s.%s.%s", groups{i}, fields{j}, subfields{k}))
    264                                 %                       end
    265                                 %                       Var=md.(groups{i}).(fields{j}).(subfields{k});
    266                                 %                       [DimSize,DimValue,varid]=CreateVar(ncid,Var,subgroupID,subfields{k},DimSize,DimValue);
    267                                 %                       if ~isempty(varid),
    268                                 %                               FillVar(Var,subgroupID,varid);
    269                                 %                       end
    270                                 %               end
    271                                 %       end
    272                                 % end
    273223                        elseif sum(strcmp(class(Var), issmclasses)) == 1,  % that is an issm class
    274224                                if strcmp(class(Var), 'solution'),
  • issm/trunk-jpl/src/m/contrib/defleurian/netCDF/export_netCDF.py

    r26858 r26871  
    5858        #as much scalars as stpes (or less) so just one value per step
    5959        else:
    60             return np.asarray(self.data)
     60            return np.squeeze(np.asarray(self.data))
    6161
    6262
     
    158158                            subfields = dict.keys(md.__dict__[group].__dict__[field].__getitem__(0))
    159159                        for subfield in subfields:
    160                             if subfield not in['errlog', 'outlog']:
     160                            if subfield not in ['errlog', 'outlog']:
    161161                                StackedVar = ResTable()
    162162                                #first loop over the field (result type) to find the index of the last subfield (variable)
     
    241241                        subfields = dict.keys(md.__dict__[group].__dict__[field].__getitem__(0))
    242242                    for subfield in subfields:
    243                         if subfield not in['errlog', 'outlog']:
     243                        if subfield not in ['errlog', 'outlog']:
    244244                            StackedVar = ResTable()
    245245                            for listindex in range(0, Listsize):
     
    248248                                    lastindex = listindex + 1
    249249                                except AttributeError:
    250                                     Var = md.__dict__[group].__dict__[field].__getitem__(listindex)[subfield]
     250                                    Var = md.__dict__[group].__dict__[field].__dict__[subfield]
     251                                    lastindex = listindex
    251252                                except KeyError:
    252253                                    #Some fields only exist for the first step
    253254                                    lastindex = listindex
    254                                     continue
     255                                    break
    255256                                Var = SqueezeVar(Var)
    256257                                StackedVar.update(Var)
     
    308309        if val_type.startswith('<U'):
    309310            val_type = 'stringarray'
     311            print(var)
    310312    except AttributeError:
    311313        val_type = type(var)
     
    332334        if field == 'name':  # it looks like netCDF does not like attributes that are called "name"
    333335            field = 'varname'
    334         #Group.__setattr__(str(field).swapcase(), str(var))
    335336        Group.__setattr__(str(field), str(var))
    336337        ncvar = None
     
    338339    elif val_type == "stringarray":
    339340        #if all strings are the same set it as an attribute
    340         if all(var == var[0]):
     341        try:
     342            samestring = all(var == var[0])
     343        except IndexError:
     344            #Only one string
     345            samestring = True
     346        if samestring:
    341347            if field == 'name':
    342348                field = 'varname'
    343             #Group.__setattr__(str(field).swapcase(), str(var[0]))
    344             Group.__setattr__(str(field), str(var[0]))
     349            try:
     350                Group.__setattr__(str(field), str(var[0]))
     351            except IndexError:
     352                Group.__setattr__(str(field), str(var))
    345353            ncvar = None
    346354        else:
     
    360368            dimensions, DimDict = GetDim(NCData, val_shape, val_type, DimDict, val_dim)
    361369            ncvar = Group.createVariable(str(field), nctype, dimensions=dimensions, zlib=True)
    362     # treating bool tables and dict as string tables
    363     elif val_type in [collections.OrderedDict, dict, 'bool']:
     370    # treating dict as string tables
     371    elif val_type in [collections.OrderedDict, dict]:
    364372        if val_shape in [(), (0,), 0]:
    365373            ncvar = Group.createVariable(str(field), str, zlib=True)
     
    367375            dimensions, DimDict = GetDim(NCData, val_shape, val_type, DimDict, val_dim)
    368376            ncvar = Group.createVariable(str(field), str, dimensions=dimensions, zlib=True)
    369     # Now dealing with numeric variables
    370     elif val_type in [float, 'float64', np.float64, int, 'int64']:
     377    # treating bool as integers
     378    elif val_type == 'bool':
     379        if val_shape in [(), (0,), 0]:
     380            ncvar = Group.createVariable(str(field), int, zlib=True)
     381        else:
     382            dimensions, DimDict = GetDim(NCData, val_shape, val_type, DimDict, val_dim)
     383            ncvar = Group.createVariable(str(field), int, dimensions=dimensions, zlib=True)
     384    # Now dealing with doubles, we convert them to int if possible
     385    elif val_type in [float, 'float64', np.float64]:
     386        try:
     387            #check if we are integer and under C long overflow also skip empty arrays
     388            IsInt = np.sum(np.mod(var, 1)) == 0 and np.all(abs(var) < 2147483647) and len(var) > 0
     389        except TypeError:
     390            #check if we are integer and under C long overflow
     391            IsInt = np.mod(var, 1) == 0 and abs(var) < 2147483647
     392        if IsInt:
     393            val_type = 'int64'
     394        if val_shape in [(), (0,), 0] and not SupDim:
     395            ncvar = Group.createVariable(str(field), TypeDict[val_type], zlib=True)
     396        else:
     397            dimensions, DimDict = GetDim(NCData, val_shape, val_type, DimDict, val_dim)
     398            if SupDim:
     399                dimensions = SupDim + dimensions
     400            ncvar = Group.createVariable(str(field), TypeDict[val_type], dimensions=dimensions, zlib=True)
     401    elif val_type in [int, 'int64']:
    371402        if val_shape in [(), (0,), 0] and not SupDim:
    372403            ncvar = Group.createVariable(str(field), TypeDict[val_type], zlib=True)
     
    415446    elif val_type == 'bool':
    416447        for elt in range(0, val_shape[0]):
    417             ncvar[elt] = str(invar[elt])
     448            ncvar[elt] = int(invar[elt])  #str(invar[elt])
    418449    # treating dictionaries as tables of strings
    419450    elif val_type in [collections.OrderedDict, dict]:
  • issm/trunk-jpl/src/m/contrib/defleurian/netCDF/restable.m

    r26858 r26871  
    2121                function outdat = finalize(self, rows)
    2222                        if length(self.data)>rows,
    23                                 %we have more scalars than steps, so we have an array
    24                                 maxsize=[];
    25                                 for d=1:size(self.sizes,2)
    26                                         maxsize=[maxsize,max(self.sizes(:,d))];
    27                                 end
    28                                 findim=[maxsize, rows];
    29                                 %first check if all steps are the same size
    30                                 SameSize = sum(self.sizes - self.sizes(1))==0;
    31                                 if SameSize,
    32                                         %same size for all steps, just reshape
    33                                         outdat=reshape(self.data, findim);
     23                                if size(self.sizes, 1)==1,
     24                                        %just one step, data don't need treatment
     25                                        outdat=self.data;
    3426                                else,
    35                                         %different sizes at each steps, first create a table big enough for the biggest step
    36                                         startpoint=1;
    37                                         datadim=ndims(self.data);
    38                                         outdat=NaN*ones(findim);
    39                                         for r=1:rows
    40                                                 curlen = prod(self.sizes(r, :));
    41                                                 outdat(1:self.sizes(r,1), 1:self.sizes(r,2), r) = reshape(self.data(startpoint:startpoint+curlen-1),self.sizes(r,:));
    42                                                 startpoint = startpoint+curlen;
     27                                        %we have more scalars than steps, so we have an array
     28                                        maxsize=[];
     29                                        for d=1:size(self.sizes,2)
     30                                                maxsize=[maxsize,max(self.sizes(:,d))];
    4331                                        end
     32                                        findim=[maxsize, rows];
     33                                        %first check if all steps are the same size
     34                                        SameSize = sum(self.sizes - self.sizes(1))==0;
     35                                        if SameSize,
     36                                                %same size for all steps, just reshape
     37                                                outdat=reshape(self.data, findim);
     38                                        else,
     39                                                %different sizes at each steps, first create a table big enough for the biggest step
     40                                                startpoint=1;
     41                                                datadim=ndims(self.data);
     42                                                outdat=NaN*ones(findim);
     43                                                for r=1:rows
     44                                                        curlen = prod(self.sizes(r, :));
     45                                                        outdat(1:self.sizes(r,1), 1:self.sizes(r,2), r) = reshape(self.data(startpoint:startpoint+curlen-1),self.sizes(r,:));
     46                                                        startpoint = startpoint+curlen;
     47                                                end
    4448
    45                                 end
     49                                        end
     50                                end,
    4651                        else,
    4752                                %as much scalars as steps (or less) so just one value per step
  • issm/trunk-jpl/src/m/io/loadvars.py

    r26857 r26871  
    132132                            Tree = nvdict['md'].__dict__[classtree[mod][0]].__dict__[classtree[mod][1]]
    133133                        else:
    134                             #nvdict['md'].__dict__[classtree[mod][0]].__dict__[classtree[mod][1]] = [getattr(classtype[mod][1], listtype)() for i in range(max(1, len(NCFile.dimensions['Time'])))]
    135                             #Tree = nvdict['md'].__dict__[classtree[mod][0]].__dict__[classtree[mod][1]][:]
    136134                            setattr(nvdict['md'].__dict__[classtree[mod][0]], classtree[mod][1], getattr(classtype[mod][1], 'solution')([]))
    137135                            for i in range(max(1, stepnum)):
     
    139137                            Tree = nvdict['md'].__dict__[classtree[mod][0]].__dict__[classtree[mod][1]][:]
    140138                    #}}}
    141                 elif classtype[mod][0] == 'massfluxatgate.massfluxatgate':  #this is for output definitions {{{
     139                #elif classtype[mod][0] == 'massfluxatgate.massfluxatgate':  #this is for output definitions {{{
     140                elif mod.startswith('outputdefinition'):  #this is for output definitions {{{
    142141                    defname = split('Output|[0-9]+', classtree[mod][1])[1] + 's'
    143142                    defindex = int(findall('[0-9]+', classtree[mod][1])[0])
    144                     nvdict['md'].__dict__[classtree[mod][0]].__dict__[defname].append(getattr(classtype[mod][1], 'massfluxatgate')())
     143                    outdeftype = split(r'\.', classtype[mod][0])[0]
     144                    nvdict['md'].__dict__[classtree[mod][0]].__dict__[defname].append(getattr(classtype[mod][1], outdeftype)())
    145145                    Tree = nvdict['md'].__dict__[classtree[mod][0]].__dict__[defname][defindex - 1]
    146146                #}}}
     
    212212                            else:
    213213                                if NewFormat:
    214                                     print(varval.dimensions)
    215214                                    incomplete = 'Time' not in varval.dimensions
    216215                                    if incomplete:
    217                                         chosendim = varval.dimensions[0]
    218                                         timelist = np.arange(0, len(NCFile.dimensions[chosendim]))
    219                                         print('WARNING, {} is not present on every times, we chose {}({}) as the dimension to write it with'.format(var, chosendim, len(NCFile.dimensions[chosendim])))
     216                                        try:
     217                                            chosendim = varval.dimensions[0]
     218                                            timelist = np.arange(0, len(NCFile.dimensions[chosendim]))
     219                                            print('WARNING, {} is not present on every times, we chose {}({}) as the dimension to write it with'.format(var, chosendim, len(NCFile.dimensions[chosendim])))
     220                                        except IndexError:
     221                                            #just one step, so no dimension, we just put it on the first solutionstep
     222                                            timelist = [0]
    220223                                    else:
    221224                                        timelist = np.arange(0, len(NCFile.dimensions['Time']))
     
    239242                        else:
    240243                            if vardim == 0:  #that is a scalar
    241                                 if str(varval[0]) in['', '--', 'emptycell']:  #no value
     244                                if str(varval[0]) in ['', '--', 'emptycell']:  #no value
    242245                                    Tree.__dict__[str(var)] = []
    243246                                elif varval[0] == 'True':  #treatin bool
Note: See TracChangeset for help on using the changeset viewer.