Skip to content

cdfwrite¤

cdfwrite ¤

Classes:

Name Description
CDF

Creates an empty CDF file.

CDF ¤

CDF(path: Union[str, Path], cdf_spec: Optional[Dict[str, Any]] = None, delete: bool = False)

Creates an empty CDF file.

Parameters:

Name Type Description Default

path ¤

Union[str, Path]

The path name of the CDF (with or without .cdf extension)

required

cdf_spec ¤

dict

The optional specification of the CDF file.

The keys for the dictionary are:

  • ['Majority']: 'row_major' or 'column_major', or its corresponding value. The default is 'column_major'.
  • ['Encoding']: Data encoding scheme. See the CDF documentation about the valid values. Can be in string or its numeric corresponding value. The default is 'host', which will be determined when the script runs.
  • ['Checksum']: Whether to set the data validation upon file creation. The default is False.
  • ['rDim_sizes']: The dimensional sizes, applicable only to rVariables.
  • ['Compressed']: Whether to compress the CDF at the file level. A value of 0-9 or True/False, the default is 0/False.
None

Methods:

Name Description
close

Closes the CDF Class.

write_globalattrs

Writes the global attributes.

write_var

Writes a variable, along with variable attributes and data.

write_variableattrs

Writes a variable's attributes, provided the variable already exists.

Source code in cdflib/cdfwrite.py
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
def __init__(self, path: Union[str, Path], cdf_spec: Optional[Dict[str, Any]] = None, delete: bool = False):
    path = pathlib.Path(path).expanduser()

    major = 1
    if cdf_spec is not None:
        major = cdf_spec.get("Majority", major)
        if isinstance(major, str):
            major = self._majority_token(major)

        encoding = cdf_spec.get("Encoding", 8)  # default is host
        if isinstance(encoding, str):
            encoding = self._encoding_token(encoding)

        checksum = cdf_spec.get("Checksum", False)

        cdf_compression = cdf_spec.get("Compressed", 0)
        if isinstance(cdf_compression, int):
            if not 0 <= cdf_compression <= 9:
                cdf_compression = 0
        else:
            cdf_compression = 6 if cdf_compression else 0

        rdim_sizes: Optional[List[int]] = cdf_spec.get("rDim_sizes", None)
        num_rdim: int = len(rdim_sizes) if rdim_sizes is not None else 0

    else:
        encoding = 8
        checksum = False
        cdf_compression = 0
        num_rdim = 0
        rdim_sizes = None

    if major not in [1, 2]:
        raise RuntimeError(f"Bad major: {major}")

    osSystem = pf.system()
    osMachine = pf.uname()[5]
    if encoding == 8:
        if osSystem != "SunOS" or osMachine != "sparc":
            self._encoding = self.IBMPC_ENCODING
        else:
            self._encoding = self.SUN_ENCODING
    else:
        self._encoding = encoding
        if self._encoding == -1:
            raise OSError("Bad encoding.")
    if not isinstance(checksum, bool):
        raise ValueError("Bad checksum.")

    if path.suffix != ".cdf":
        path = path.with_suffix(".cdf")
    if len(str(path)) > self.CDF_PATHNAME_LEN:
        raise OSError("CDF:", path, " longer than allowed length.")
    if path.is_file():
        if not delete:
            raise OSError("file: ", path, " already exists....\n", "Delete it or specify the 'delete=False' option.")
        else:
            path.unlink()

    self.path = path

    self.compressed_file = path.with_suffix(".tmp") if cdf_compression > 0 else None

    # Dictionary objects, these contains name, offset, and dimension information
    self.zvarsinfo: Dict[int, Tuple[str, int, int, List[int], List[bool]]] = {}
    self.rvarsinfo: Dict[int, Tuple[str, int, int, List[int], List[bool]]] = {}

    # Dictionary object, contains name, offset, and scope (global or variable)
    self.attrsinfo: Dict[int, Tuple[str, int, int]] = {}

    self.gattrs: List[str] = []  # List of global attributes
    self.vattrs: List[str] = []  # List of variable attributes
    self.attrs: List[str] = []  # List of ALL attributes
    self.zvars: List[str] = []  # List of z variable names
    self.rvars: List[str] = []  # List of r variable names
    self.checksum = checksum  # Boolean, whether or not to include the checksum at the end
    self.compression = cdf_compression  # Compression level (or True/False)
    self.num_rdim = num_rdim  # Number of r dimensions
    self.rdim_sizes = rdim_sizes  # Size of r dimensions
    self.majority = major

    with path.open("wb") as f:
        f.write(binascii.unhexlify(self.V3magicNUMBER_1))
        f.write(binascii.unhexlify(self.V3magicNUMBER_2))

        self.cdr_head = self._write_cdr(f, major, self._encoding, checksum)
        self.gdr_head = self._write_gdr(f)
        self.offset = f.tell()

    self.is_closed = False

close ¤

close() -> None

Closes the CDF Class.

1. If compression was set, this is where the compressed file is
   written.
2. If a checksum is needed, this will place the checksum at the end
   of the file.
Source code in cdflib/cdfwrite.py
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
def close(self) -> None:
    """
    Closes the CDF Class.

        1. If compression was set, this is where the compressed file is
           written.
        2. If a checksum is needed, this will place the checksum at the end
           of the file.

    """
    if self.is_closed:
        return

    if self.compressed_file is None:
        with self.path.open("rb+") as f:
            f.seek(0, 2)
            eof = f.tell()
            self._update_offset_value(f, self.gdr_head + 36, 8, eof)
            if self.checksum:
                f.write(self._md5_compute(f))
            self.is_closed = True
        return

    with self.path.open("rb+") as f:
        f.seek(0, 2)
        eof = f.tell()
        self._update_offset_value(f, self.gdr_head + 36, 8, eof)

        with self.compressed_file.open("wb+") as g:
            g.write(bytearray.fromhex(self.V3magicNUMBER_1))
            g.write(bytearray.fromhex(self.V3magicNUMBER_2c))
            self._write_ccr(f, g, self.compression)

            if self.checksum:
                g.seek(0, 2)
                g.write(self._md5_compute(g))

    self.path.unlink()  # NOTE: for Windows this is necessary
    self.compressed_file.rename(self.path)
    self.is_closed = True

write_globalattrs ¤

write_globalattrs(globalAttrs)

Writes the global attributes.

Parameters:

Name Type Description Default

globalAttrs ¤

Global attribute name(s) and their value(s) pair(s).

The value(s) is a dictionary of entry number and value pair(s). For example::

globalAttrs={}
globalAttrs['Global1']={0: 'Global Value 1'}
globalAttrs['Global2']={0: 'Global Value 2'}

For a non-string value, use a list with the value and its CDF data type. For example::

globalAttrs['Global3']={0: [12, 'cdf_int4']}
globalAttrs['Global4']={0: [12.34, 'cdf_double']}

If the data type is not provided, a corresponding CDF data type is assumed::

globalAttrs['Global3']={0: 12}     as 'cdf_int4'
globalAttrs['Global4']={0: 12.34}  as 'cdf_double'

CDF allows multi-values for non-string data for an attribute::

globalAttrs['Global5']={0: [[12.34,21.43], 'cdf_double']}

For multi-entries from a global variable, they should be presented in this form::

GA6={}
GA6[0]='abcd'
GA6[1]=[12, 'cdf_int2']
GA6[2]=[12.5, 'cdf_float']
GA6[3]=[[0,1,2], 'cdf_int8']
globalAttrs['Global6']=GA6
....
f.write_globalattrs(globalAttrs)
required
Source code in cdflib/cdfwrite.py
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
@is_open
def write_globalattrs(self, globalAttrs):
    """
    Writes the global attributes.

    Parameters
    ----------
    globalAttrs: dict
        Global attribute name(s) and their value(s) pair(s).

        The value(s) is a dictionary of entry number and value pair(s).
        For example::

            globalAttrs={}
            globalAttrs['Global1']={0: 'Global Value 1'}
            globalAttrs['Global2']={0: 'Global Value 2'}

        For a non-string value, use a list with the value and its
        CDF data type. For example::

            globalAttrs['Global3']={0: [12, 'cdf_int4']}
            globalAttrs['Global4']={0: [12.34, 'cdf_double']}

        If the data type is not provided, a corresponding
        CDF data type is assumed::

            globalAttrs['Global3']={0: 12}     as 'cdf_int4'
            globalAttrs['Global4']={0: 12.34}  as 'cdf_double'

        CDF allows multi-values for non-string data for an attribute::

            globalAttrs['Global5']={0: [[12.34,21.43], 'cdf_double']}

        For multi-entries from a global variable, they should be
        presented in this form::

            GA6={}
            GA6[0]='abcd'
            GA6[1]=[12, 'cdf_int2']
            GA6[2]=[12.5, 'cdf_float']
            GA6[3]=[[0,1,2], 'cdf_int8']
            globalAttrs['Global6']=GA6
            ....
            f.write_globalattrs(globalAttrs)
    """
    if not (isinstance(globalAttrs, dict)):
        raise ValueError("Global attribute(s) not in dictionary form")
    dataType = None
    numElems = None
    with self.path.open("rb+") as f:
        f.seek(0, 2)  # EOF (appending)
        for attr, entry in globalAttrs.items():
            if attr in self.gattrs:
                raise ValueError(f"Global attribute: {attr} already exists.")

            if attr in self.vattrs:
                logging.warning(f"Attribute: {attr} already defined as a variable attribute.")
                continue

            attrNum, offsetADR = self._write_adr(f, True, attr)
            entries = 0
            if entry is None:
                continue
            entryNumMaX = -1
            poffset = -1
            for entryNum, value in entry.items():
                if entryNumMaX < entryNum:
                    entryNumMaX = entryNum
                if hasattr(value, "__len__") and not isinstance(value, str):
                    if len(value) == 2:
                        # Check if the second value is a valid data type
                        value2 = value[1]
                        dataType = self._datatype_token(value2)
                        if dataType > 0:
                            # Data Type found
                            data = value[0]
                            if dataType == self.CDF_CHAR or dataType == self.CDF_UCHAR:
                                if isinstance(data, list) or isinstance(data, tuple):
                                    logger.warning("Invalid global attribute value")
                                    return
                                numElems = len(data)
                            elif dataType == self.CDF_EPOCH or dataType == self.CDF_EPOCH16 or dataType == self.CDF_TIME_TT2000:
                                cvalue = []
                                if isinstance(data, list) or isinstance(data, tuple):
                                    numElems = len(data)
                                    for x in range(0, numElems):
                                        if isinstance(data[x], str):
                                            cvalue.append(cdfepoch.CDFepoch.parse(data[x]))
                                        else:
                                            cvalue.append(data[x])
                                    data = cvalue
                                else:
                                    if isinstance(data, str):
                                        data = cdfepoch.CDFepoch.parse(data)
                                    numElems = 1
                            else:
                                if isinstance(data, list) or isinstance(data, tuple):
                                    numElems = len(data)
                                else:
                                    numElems = 1
                        else:
                            # Data type not found, both values are data.
                            data = value
                            numElems, dataType = self._datatype_define(value[0])
                            numElems = len(value)
                    else:
                        # Length greater than 2, so it is all data.
                        data = value
                        numElems, dataType = self._datatype_define(value[0])
                        numElems = len(value)
                else:
                    # Just one value
                    data = value
                    numElems, dataType = self._datatype_define(value)
                    if numElems is None:
                        logger.warning("Unknown data")
                        return

                offset = self._write_aedr(f, True, attrNum, entryNum, data, dataType, numElems, None)
                if entries == 0:
                    # ADR's AgrEDRhead
                    self._update_offset_value(f, offsetADR + 20, 8, offset)
                else:
                    # ADR's ADRnext
                    self._update_offset_value(f, poffset + 12, 8, offset)

                poffset = offset
                entries = entries + 1
            # ADR's NgrEntries
            self._update_offset_value(f, offsetADR + 36, 4, entries)
            # ADR's MAXgrEntry
            self._update_offset_value(f, offsetADR + 40, 4, entryNumMaX)

write_var ¤

write_var(var_spec, var_attrs=None, var_data=None)

Writes a variable, along with variable attributes and data.

Parameters:

Name Type Description Default

var_spec ¤

dict

The specifications of the variable.

The required/optional keys for creating a variable: Required keys:

  • ['Variable']: The name of the variable
  • ['Data_Type']: the CDF data type
  • ['Num_Elements']: The number of elements. Always 1 the for numeric type. The char length for string type.
  • ['Rec_Vary']: Record variance

For zVariables:

  • ['Dim_Sizes']: The dimensional sizes for zVariables only. Use [] for 0-dimension. Each and every dimension is varying for zVariables.

For rVariables:

  • ['Dim_Vary']: The dimensional variances for rVariables only.

Optional keys:

  • ['Var_Type']: Whether the variable is a zVariable or rVariable. Valid values: "zVariable" and "rVariable". The default is "zVariable".
  • ['Sparse']: Whether the variable has sparse records. Valid values are "no_sparse", "pad_sparse", and "prev_sparse". The default is 'no_sparse'.
  • ['Compress']: Set the gzip compression level (0 to 9), 0 for no compression. The default is to compress with level 6 (done only if the compressed data is less than the uncompressed data).
  • ['Block_Factor']: The blocking factor, the number of records in a chunk when the variable is compressed.
  • ['Pad']: The padded value (in bytes, numpy.ndarray or string)
required

var_attrs ¤

dict

{attribute:value} pairs.

The attribute is the name of a variable attribute. The value can have its data type specified for the numeric data. If not, based on Python's type, a corresponding CDF type is assumed: CDF_INT4 for int, CDF_DOUBLE for float, CDF_EPOCH16 for complex and and CDF_INT8 for long.

For example, the following defined attributes will have the same types in the CDF::

var_attrs= { 'attr1':  'value1',
          'attr2':  12.45,
          'attr3':  [3,4,5],
          .....
        }

With data type (in the list form)::

var_attrs= { 'attr1':  'value1',
          'attr2':  [12.45, 'CDF_DOUBLE'],
          'attr3':  [[3,4,5], 'CDF_INT4'],
          .....
        }
None

var_data ¤

The data for the variable. If the variable is a regular variable without sparse records, it must be in a single structure of bytes, or numpy.ndarray for numeric variable, or str or list of strs for string variable. If the variable has sparse records, var_data should be presented in a list/tuple with two elements, the first being a list/tuple that contains the physical record number(s), the second being the variable data in bytes, numpy.ndarray, or a list of strings. Variable data can have just physical records' data (with the same number of records as the first element) or have data from both physical records and virtual records (which with filled data). The var_data has the form::

[[rec_#1,rec_#2,rec_#3,...],
[data_#1,data_#2,data_#3,...]]

See the sample for its setup.

None
Source code in cdflib/cdfwrite.py
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
@is_open
def write_var(self, var_spec, var_attrs=None, var_data=None):
    """
    Writes a variable, along with variable attributes and data.

    Parameters
    ----------
    var_spec : dict
        The specifications of the variable.

        The required/optional keys for creating a variable:
        Required keys:

        - ['Variable']: The name of the variable
        - ['Data_Type']: the CDF data type
        - ['Num_Elements']: The number of elements. Always 1 the
          for numeric type. The char length for string type.
        - ['Rec_Vary']: Record variance

        For zVariables:

        - ['Dim_Sizes']: The dimensional sizes for zVariables only.
          Use [] for 0-dimension. Each and
          every dimension is varying for zVariables.

        For rVariables:

        - ['Dim_Vary']: The dimensional variances for rVariables only.

        Optional keys:

        - ['Var_Type']: Whether the variable is a zVariable or
          rVariable. Valid values: "zVariable" and
          "rVariable". The default is "zVariable".
        - ['Sparse']: Whether the variable has sparse records.
          Valid values are "no_sparse", "pad_sparse",
          and "prev_sparse". The default is 'no_sparse'.
        - ['Compress']: Set the gzip compression level (0 to 9), 0 for
          no compression. The default is to compress
          with level 6 (done only if the compressed
          data is less than the uncompressed data).
        - ['Block_Factor']: The blocking factor, the number of
          records in a chunk when the variable is compressed.
        - ['Pad']: The padded value (in bytes, numpy.ndarray or string)

    var_attrs : dict
        {attribute:value} pairs.

        The attribute is the name of a variable attribute.
        The value can have its data type specified for the
        numeric data. If not, based on Python's type, a
        corresponding CDF type is assumed: CDF_INT4 for int,
        CDF_DOUBLE for float, CDF_EPOCH16 for complex and
        and CDF_INT8 for long.

        For example, the following defined attributes will
        have the same types in the CDF::

            var_attrs= { 'attr1':  'value1',
                      'attr2':  12.45,
                      'attr3':  [3,4,5],
                      .....
                    }

        With data type (in the list form)::

            var_attrs= { 'attr1':  'value1',
                      'attr2':  [12.45, 'CDF_DOUBLE'],
                      'attr3':  [[3,4,5], 'CDF_INT4'],
                      .....
                    }

    var_data :
        The data for the variable. If the variable is
        a regular variable without sparse records, it must
        be in a single structure of bytes, or numpy.ndarray
        for numeric variable, or str or list of strs for
        string variable.
        If the variable has sparse records, var_data should
        be presented in a list/tuple with two elements,
        the first being a list/tuple that contains the
        physical record number(s), the second being the variable
        data in bytes, numpy.ndarray, or a list of strings. Variable
        data can have just physical records' data (with the same
        number of records as the first element) or have data from both
        physical records and virtual records (which with filled data).
        The var_data has the form::

            [[rec_#1,rec_#2,rec_#3,...],
            [data_#1,data_#2,data_#3,...]]

        See the sample for its setup.

    """
    if not isinstance(var_spec, dict):
        raise TypeError("Variable should be in dictionary form.")

    # Get variable info from var_spec
    try:
        dataType = int(var_spec["Data_Type"])
        numElems = int(var_spec["Num_Elements"])
        name = var_spec["Variable"]
        recVary = var_spec["Rec_Vary"]
    except Exception as e:
        raise ValueError("Missing/invalid required spec for creating variable.") from e
    # Get whether or not it is a z variable
    var_type = var_spec.setdefault("Var_Type", "zvariable")
    if var_type.lower() == "zvariable":
        zVar = True
    else:
        var_spec["Var_Type"] = "rVariable"
        zVar = False

    if dataType == self.CDF_CHAR or dataType == self.CDF_UCHAR:
        if numElems < 1:
            raise ValueError("Invalid Num_Elements for string data type variable")
    else:
        if numElems != 1:
            raise ValueError("Invalid Num_Elements for numeric data type variable")
    # If its a z variable, get the dimension info
    # Otherwise, use r variable info
    if zVar:
        try:
            dimSizes = var_spec["Dim_Sizes"]
            numDims = len(dimSizes)
            dimVary = []
            for _ in range(0, numDims):
                dimVary.append(True)
        except Exception:
            raise ValueError("Missing/invalid required spec for creating variable.")
    else:
        dimSizes = self.rdim_sizes
        numDims = self.num_rdim
        try:
            dimVary = var_spec["Dim_Vary"]
            if len(dimVary) != numDims:
                raise ValueError("Invalid Dim_Vary size for the rVariable.")
        except Exception:
            raise ValueError("Missing/invalid required spec for Dim_Vary for rVariable")
    # Get Sparseness info
    sparse = self._sparse_token(var_spec.get("Sparse", "no_sparse"))
    # Get compression info
    compression = var_spec.get("Compress", 6)
    if isinstance(compression, int):
        if not 0 <= compression <= 9:
            compression = 0
    else:
        compression = 6 if compression else 0

    # Get blocking factor
    blockingfactor = int(var_spec.get("Block_Factor", 1))

    # Get pad value
    pad = var_spec.get("Pad", None)
    if hasattr(pad, "__len__"):
        pad = pad[0]

    if name in self.zvars or name in self.rvars:
        raise ValueError(f"{name} already exists")

    with self.path.open("rb+") as f:
        f.seek(0, 2)  # EOF (appending)
        varNum, offset = self._write_vdr(
            f, dataType, numElems, numDims, dimSizes, name, dimVary, recVary, sparse, blockingfactor, compression, pad, zVar
        )
        # Update the GDR pointers if needed
        if zVar:
            if len(self.zvars) == 1:
                # GDR's zVDRhead
                self._update_offset_value(f, self.gdr_head + 20, 8, offset)
        else:
            if len(self.rvars) == 1:
                # GDR's rVDRhead
                self._update_offset_value(f, self.gdr_head + 12, 8, offset)

        # Write the variable attributes
        if var_attrs is not None:
            self._write_var_attrs(f, varNum, var_attrs, zVar)

        # Write the actual data to the file
        if not (var_data is None):
            if sparse == 0:
                varMaxRec = self._write_var_data_nonsparse(
                    f, zVar, varNum, dataType, numElems, recVary, compression, blockingfactor, var_data
                )
            else:
                notsupport = False
                if not isinstance(var_data, (list, tuple)):
                    notsupport = True

                if notsupport or len(var_data) != 2:
                    logger.warning(
                        "Sparse record #s and data are not of list/tuple form:\n"
                        " [ [rec_#1, rec_#2, rec_#3,    ],\n"
                        "   [data_#1, data_#2, data_#3, ....] ]"
                    )
                    return

                # Format data into: [[recstart1, recend1, data1],
                #                   [recstart2,recend2,data2], ...]
                var_data = self._make_sparse_blocks(var_spec, var_data[0], var_data[1])

                for block in var_data:
                    varMaxRec = self._write_var_data_sparse(f, zVar, varNum, dataType, numElems, recVary, block)
            # Update GDR MaxRec if writing an r variable
            if not zVar:
                # GDR's rMaxRec
                f.seek(self.gdr_head + 52)
                maxRec = int.from_bytes(f.read(4), "big", signed=True)
                if maxRec < varMaxRec:
                    self._update_offset_value(f, self.gdr_head + 52, 4, varMaxRec)

write_variableattrs ¤

write_variableattrs(variableAttrs)

Writes a variable's attributes, provided the variable already exists.

Parameters:

Name Type Description Default

variableAttrs ¤

dict

Variable attribute name and its entry value pair(s). The entry value is also a dictionary of variable id and value pair(s). Variable id can be the variable name or its id number in the file. Use write_var function if the variable does not exist. For example::

variableAttrs={}
entries_1={}
entries_1['var_name_1'] = 'abcd'
entries_1['var_name_2'] = [12, 'cdf_int4']
....
variableAttrs['attr_name_1']=entries_1
entries_2={}
entries_2['var_name_1'] = 'xyz'
entries_2['var_name_2'] = [[12, 34], 'cdf_int4']
....
variableAttrs['attr_name_2']=entries_2
....
....
f.write_variableattrs(variableAttrs)
required
Source code in cdflib/cdfwrite.py
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
@is_open
def write_variableattrs(self, variableAttrs):
    """
    Writes a variable's attributes, provided the variable already exists.

    Parameters
    ----------
    variableAttrs : dict
        Variable attribute name and its entry value pair(s).
        The entry value is also a dictionary of variable id and value
        pair(s).  Variable id can be the variable name or its id number
        in the file. Use write_var function if the variable does not exist.
        For example::

            variableAttrs={}
            entries_1={}
            entries_1['var_name_1'] = 'abcd'
            entries_1['var_name_2'] = [12, 'cdf_int4']
            ....
            variableAttrs['attr_name_1']=entries_1
            entries_2={}
            entries_2['var_name_1'] = 'xyz'
            entries_2['var_name_2'] = [[12, 34], 'cdf_int4']
            ....
            variableAttrs['attr_name_2']=entries_2
            ....
            ....
            f.write_variableattrs(variableAttrs)
    """
    if not (isinstance(variableAttrs, dict)):
        raise ValueError("Variable attribute(s) not in dictionary form")
    dataType = None
    numElems = None
    with self.path.open("rb+") as f:
        f.seek(0, 2)  # EOF (appending)
        for attr, attrs in variableAttrs.items():
            if not (isinstance(attr, str)):
                raise ValueError("Attribute name must be a string")
                return
            if attr in self.gattrs:
                raise ValueError(f"Variable attribute: {attr}" + " is already a global variable")
                return
            if attr in self.vattrs:
                attrNum = self.vattrs.index(attr)
                offsetA = self.attrsinfo[attrNum][2]
            else:
                attrNum, offsetA = self._write_adr(f, False, attr)
            entries = 0
            if attrs is None:
                continue
            if not (isinstance(attrs, dict)):
                raise ValueError("An attribute" "s attribute(s) not in dictionary form")
            entryNumX = -1
            poffset = -1
            for entryID, value in attrs.items():
                if isinstance(entryID, str) and (not (entryID in self.zvars) and not (entryID in self.rvars)):
                    raise KeyError(f"{entryID} not found in the CDF")

                if isinstance(entryID, numbers.Number) and (len(self.zvars) > 0 and len(self.rvars) > 0):
                    raise ValueError(f"{entryID} can not be used as the CDF has both zVariables and rVariables")

                if isinstance(entryID, str):
                    try:
                        entryNum = self.zvars.index(entryID)
                        zVar = True
                    except Exception:
                        try:
                            entryNum = self.rvars.index(entryID)
                            zVar = False
                        except Exception:
                            raise KeyError(f"{entryID} not found")
                else:
                    entryNum = int(entryID)
                    if len(self.zvars) > 0 and len(self.rvars) > 0:
                        raise ValueError(
                            "Can not use integer form for variable id as there ", "are both zVariables and rVaribales"
                        )
                    if len(self.zvars) > 0:
                        if entryNum >= len(self.zvars):
                            raise ValueError("Variable id: ", entryID, " not found")
                        else:
                            zVar = True
                    else:
                        if entryNum >= len(self.rvars):
                            raise ValueError("Variable id: ", entryID, " not found")
                        else:
                            zVar = False
                if entryNum > entryNumX:
                    entryNumX = entryNum
                if hasattr(value, "__len__") and not isinstance(value, str):
                    if len(value) == 2:
                        value2 = value[1]
                        dataType = self._datatype_token(value2)
                        if dataType > 0:
                            data = value[0]
                            if dataType == self.CDF_CHAR or dataType == self.CDF_UCHAR:
                                if isinstance(data, list) or isinstance(data, tuple):
                                    raise ValueError("Invalid variable attribute value")
                                numElems = len(data)
                            elif dataType == self.CDF_EPOCH or dataType == self.CDF_EPOCH16 or dataType == self.CDF_TIME_TT2000:
                                cvalue = []
                                if isinstance(data, list) or isinstance(data, tuple):
                                    numElems = len(data)
                                    for x in range(0, numElems):
                                        if isinstance(data[x], str):
                                            avalue = cdfepoch.CDFepoch.parse(data[x])
                                        else:
                                            avalue = data[x]
                                        if dataType == self.CDF_EPOCH16:
                                            cvalue.append(avalue.real)
                                            cvalue.append(avalue.imag)
                                        else:
                                            cvalue.append(avalue)
                                            data = cvalue
                                else:
                                    if isinstance(data, str):
                                        data = cdfepoch.CDFepoch.parse(data)
                                    numElems = 1
                            else:
                                if isinstance(data, list) or isinstance(data, tuple):
                                    numElems = len(data)
                                else:
                                    numElems = 1
                        else:
                            data = value
                            numElems, dataType = self._datatype_define(value[0])
                            numElems = len(value)
                    else:
                        data = value
                        numElems, dataType = self._datatype_define(value[0])
                        numElems = len(value)
                else:
                    data = value
                    numElems, dataType = self._datatype_define(value)
                    if numElems is None:
                        logger.warning("Unknown data")
                        return
                offset = self._write_aedr(f, False, attrNum, entryNum, data, dataType, numElems, zVar)
                if entries == 0:
                    if zVar:
                        # ADR's AzEDRhead
                        self._update_offset_value(f, offsetA + 48, 8, offset)
                    else:
                        # ADR's AgrEDRhead
                        self._update_offset_value(f, offsetA + 20, 8, offset)
                else:
                    # ADR's ADRnext
                    self._update_offset_value(f, poffset + 12, 8, offset)
                poffset = offset
                entries = entries + 1
            if zVar:
                # ADR's NzEntries
                self._update_offset_value(f, offsetA + 56, 4, entries)
                # ADR's MAXzEntry
                self._update_offset_value(f, offsetA + 60, 4, entryNumX)
            else:
                # ADR's NgrEntries
                self._update_offset_value(f, offsetA + 36, 4, entries)
                # ADR's MAXgrEntry
                self._update_offset_value(f, offsetA + 40, 4, entryNumX)

Sample Usage¤

>>> import cdfwrite
>>> import cdfread
>>> import numpy as np
>>>
>>> cdf_master = cdfread.CDF('/path/to/master_file.cdf')
>>> if (cdf_master.file != None):
>>> # Get the cdf's specification
>>> info=cdf_master.cdf_info()
>>> cdf_file=cdfwrite.CDF('/path/to/swea_file.cdf',cdf_spec=info,delete=True)
>>> if (cdf_file.file == None):
>>>     cdf_master.close()
>>>     raise OSError('Problem writing file.... Stop')
>>>
>>> # Get the global attributes
>>> globalaAttrs=cdf_master.globalattsget(expand=True)
>>> # Write the global attributes
>>> cdf_file.write_globalattrs(globalaAttrs)
>>> zvars=info['zVariables']
>>> print('no of zvars=',len(zvars))
>>> # Loop thru all the zVariables
>>> for x in range (0, len(zvars)):
>>>     # Get the variable's specification
>>>     varinfo=cdf_master.varinq(zvars[x])
>>>     #print('Z =============>',x,': ', varinfo['Variable'])
>>>     # Get the variable's attributes
>>>     varattrs=cdf_master.varattsget(zvars[x], expand=True)
>>>     if (varinfo['Sparse'].lower() == 'no_sparse'):
>>>         # A variable with no sparse records... get the variable data
>>>         vardata=.......
>>>         # Create the zVariable, write out the attributes and data
>>>         cdf_file.write_var(varinfo, var_attrs=varattrs, var_data=vardata)
>>>     else:
>>>         # A variable with sparse records...
>>>         # data is in this form [physical_record_numbers, data_values]
>>>         # physical_record_numbers (0-based) contains the real record
>>>         # numbers. For example, a variable has only 3 physical records
>>>         # at [0, 5, 10]:
>>>         varrecs=[0,5,10]
>>>         # data_values could contain only the physical records' data or
>>>         # both the physical and virtual records' data.
>>>         # For example, a float variable of 1-D with 3 elements with only
>>>         # 3 physical records at [0,5,10]:
>>>         # vardata = [[  5.55000000e+01, -1.00000002e+30,  6.65999985e+01],
>>>         #            [  6.66659973e+02,  7.77770020e+02,  8.88880005e+02],
>>>         #            [  2.00500000e+02,  2.10600006e+02,  2.20699997e+02]]
>>>         # Or, with virtual record data embedded in the data:
>>>         # vardata = [[  5.55000000e+01, -1.00000002e+30,  6.65999985e+01],
>>>         #            [ -1.00000002e+30, -1.00000002e+30, -1.00000002e+30],
>>>         #            [ -1.00000002e+30, -1.00000002e+30, -1.00000002e+30],
>>>         #            [ -1.00000002e+30, -1.00000002e+30, -1.00000002e+30],
>>>         #            [ -1.00000002e+30, -1.00000002e+30, -1.00000002e+30],
>>>         #            [  6.66659973e+02,  7.77770020e+02,  8.88880005e+02],
>>>         #            [ -1.00000002e+30, -1.00000002e+30, -1.00000002e+30],
>>>         #            [ -1.00000002e+30, -1.00000002e+30, -1.00000002e+30],
>>>         #            [ -1.00000002e+30, -1.00000002e+30, -1.00000002e+30],
>>>         #            [ -1.00000002e+30, -1.00000002e+30, -1.00000002e+30],
>>>         #            [  2.00500000e+02,  2.10600006e+02,  2.20699997e+02]]
>>>         # Records 1, 2, 3, 4, 6, 7, 8, 9 are all virtual records with pad
>>>         # data (variable defined with 'pad_sparse').
>>>         vardata=np.asarray([.,.,.,..])
>>>         # Create the zVariable, and optionally write out the attributes
>>>         # and data
>>>         cdf_file.write_var(varinfo, var_attrs=varattrs,
>>>                    var_data=[varrecs,vardata])
>>>    rvars=info['rVariables']
>>>    print('no of rvars=',len(rvars))
>>>    # Loop thru all the rVariables
>>>    for x in range (0, len(rvars)):
>>>        varinfo=cdf_master.varinq(rvars[x])
>>>        print('R =============>',x,': ', varinfo['Variable'])
>>>        varattrs=cdf_master.varattsget(rvars[x], expand=True)
>>>        if (varinfo['Sparse'].lower() == 'no_sparse'):
>>>            vardata=.......
>>>            # Create the rVariable, write out the attributes and data
>>>            cdf_file.write_var(varinfo, var_attrs=varattrs, var_data=vardata)
>>>        else:
>>>            varrecs=[.,.,.,..]
>>>            vardata=np.asarray([.,.,.,..])
>>>            cdf_file.write_var(varinfo, var_attrs=varattrs,
>>>                       var_data=[varrecs,vardata])
>>> cdf_master.close()
>>> cdf_file.close()