SDDSlib
Loading...
Searching...
No Matches
sdds.py
Go to the documentation of this file.
1"""
2@file sdds.py
3@brief Python script providing the SDDS Python module.
4@details
5This module provides the `SDDS` class and associated methods to load, manipulate, and save SDDS files.
6It supports both ASCII and binary SDDS formats and provides functionality to read, write, and manipulate SDDS data.
7
8Dependencies:
9 sddsdata module
10"""
11
12import sddsdata
13import sys
14import time
15
16
17class SDDS:
18 """
19 A class to represent and manipulate SDDS datasets.
20
21 This class provides methods to load, manipulate, and save SDDS data.
22 It supports ASCII and binary formats and facilitates operations on parameters, arrays, and columns.
23
24 Important:
25 - Each SDDS object must be initialized with a unique index ranging
26 from 0 to 19. This index is required to manage the internal SDDS
27 library resources and ensure no conflicts between multiple SDDS
28 objects in the same program.
29 - Ensure that the index is released (if necessary) before reusing it.
30
31 Attributes:
32 index (int): The index of the SDDS dataset (integer from 0 to 19).
33 description (list): List containing the description text and contents of the SDDS file.
34 parameterName (list): List of parameter names.
35 arrayName (list): List of array names.
36 columnName (list): List of column names.
37 parameterDefinition (list): List of parameter definitions.
38 arrayDefinition (list): List of array definitions.
39 arrayDimensions (list): List of array dimensions.
40 columnDefinition (list): List of column definitions.
41 parameterData (list): List of parameter data values.
42 arrayData (list): List of array data values.
43 columnData (list): List of column data values.
44 mode (int): The data storage mode (`SDDS_ASCII` or `SDDS_BINARY`).
45 """
46
47 # Class constants for error printing modes
48 SDDS_VERBOSE_PrintErrors = 1 # Verbose error printing mode
49 SDDS_EXIT_PrintErrors = 2 # Exit on error printing mode
50
51 # Class constants for SDDS check statuses
52 SDDS_CHECK_OKAY = 0 # SDDS check status: okay
53 SDDS_CHECK_NONEXISTENT = 1 # SDDS check status: non-existent
54 SDDS_CHECK_WRONGTYPE = 2 # SDDS check status: wrong type
55 SDDS_CHECK_WRONGUNITS = 3 # SDDS check status: wrong units
56
57 # Class constants for data types
58 SDDS_LONGDOUBLE = 1
59 SDDS_DOUBLE = 2
60 SDDS_REAL64 = 2
61 SDDS_FLOAT = 3
62 SDDS_REAL32 = 3
63 SDDS_LONG64 = 4
64 SDDS_INT64 = 4
65 SDDS_ULONG64 = 5
66 SDDS_UINT64 = 5
67 SDDS_LONG = 6
68 SDDS_INT32 = 6
69 SDDS_ULONG = 7
70 SDDS_UINT32 = 7
71 SDDS_SHORT = 8
72 SDDS_INT16 = 8
73 SDDS_USHORT = 9
74 SDDS_UINT16 = 9
75 SDDS_STRING = 10
76 SDDS_CHARACTER = 11
77 SDDS_NUM_TYPES = 11
78
79 # Class constants for modes
80 SDDS_BINARY = 1
81 SDDS_ASCII = 2
82 SDDS_FLUSH_TABLE = 1
83
84 def __init__(self, index):
85 """
86 Initializes a new SDDS object.
87
88 Args:
89 index (int): Integer index of the SDDS object. Must be between 0 and 19 inclusive.
90
91 The attributes are initialized to their default values.
92 """
93 if 0 <= index < 20:
94 self.index = index
95 else:
96 self.index = 0
97 # Initialize data storage variables
98 self.description = ["", ""]
100 self.arrayNamearrayName = []
101 self.columnNamecolumnName = []
102 self.parameterDefinition = []
103 self.arrayDefinition = []
104 self.arrayDimensions = []
105 self.columnDefinition = []
106 self.parameterData = []
107 self.arrayData = []
108 self.columnData = []
109 self.mode = self.SDDS_ASCII
110 self.loaded_pages = 0
111
112 def load(self, input):
113 """
114 Loads an SDDS file into the SDDS object.
115
116 Args:
117 input (str): The input SDDS filename to load.
118
119 Raises:
120 Exception: If unable to read the SDDS data.
121
122 This method reads the SDDS file specified by `input`, and populates the object's data structures
123 with the parameters, arrays, columns, and their respective data.
124 """
125 try:
126 # Open SDDS file
127 if sddsdata.InitializeInput(self.index, input) != 1:
128 time.sleep(1)
129 if sddsdata.InitializeInput(self.index, input) != 1:
130 raise ValueError("Failed to initialize SDDS input.")
131
132 # Get data storage mode (SDDS_ASCII or SDDS_BINARY)
133 self.mode = sddsdata.GetMode(self.index)
134
135 # Get description text and contents
136 self.description = sddsdata.GetDescription(self.index)
137
138 # Get parameter names
139 self.parameterNameparameterName = sddsdata.GetParameterNames(self.index)
140 numberOfParameters = len(self.parameterNameparameterName)
141
142 # Get array names
143 self.arrayNamearrayName = sddsdata.GetArrayNames(self.index)
144 numberOfArrays = len(self.arrayNamearrayName)
145
146 # Get column names
147 self.columnNamecolumnName = sddsdata.GetColumnNames(self.index)
148 numberOfColumns = len(self.columnNamecolumnName)
149
150 # Get parameter definitions
151 self.parameterDefinition = [sddsdata.GetParameterDefinition(self.index, name) for name in self.parameterNameparameterName]
152
153 # Get array definitions
154 self.arrayDefinition = [sddsdata.GetArrayDefinition(self.index, name) for name in self.arrayNamearrayName]
155
156 # Get column definitions
157 self.columnDefinition = [sddsdata.GetColumnDefinition(self.index, name) for name in self.columnNamecolumnName]
158
159 # Initialize parameter, array, and column data
160 self.parameterData = [[] for _ in range(numberOfParameters)]
161 self.arrayData = [[] for _ in range(numberOfArrays)]
162 self.columnData = [[] for _ in range(numberOfColumns)]
163 self.arrayDimensions = [[] for _ in range(numberOfArrays)]
164
165 # Read in SDDS data
166 page = sddsdata.ReadPage(self.index)
167 if page != 1:
168 raise Exception("Unable to read SDDS data for the first page")
169 while page > 0:
170 self.loaded_pages += 1
171 for i in range(numberOfParameters):
172 self.parameterData[i].append(sddsdata.GetParameter(self.index, i))
173 for i in range(numberOfArrays):
174 self.arrayData[i].append(sddsdata.GetArray(self.index, i))
175 self.arrayDimensions[i].append(sddsdata.GetArrayDimensions(self.index, i))
176 rows = sddsdata.RowCount(self.index)
177 if rows > 0:
178 for i in range(numberOfColumns):
179 self.columnData[i].append(sddsdata.GetColumn(self.index, i))
180 else:
181 for i in range(numberOfColumns):
182 self.columnData[i].append([])
183 page = sddsdata.ReadPage(self.index)
184
185 # Close SDDS file
186 if sddsdata.Terminate(self.index) != 1:
187 raise ValueError("Failed to terminate SDDS input.")
188
189 except:
190 sddsdata.PrintErrors(self.SDDS_VERBOSE_PrintErrors)
191 raise
192
193 def loadSparse(self, input, interval, offset):
194 """
195 Loads an SDDS file into the SDDS object with sparse data reading.
196
197 Args:
198 input (str): The input SDDS filename to load.
199 interval (int): Interval between pages to read.
200 offset (int): Offset to start reading from.
201
202 Raises:
203 Exception: If unable to read the SDDS data.
204
205 This method reads every `interval` pages from the SDDS file, starting from the page at `offset`.
206 """
207 try:
208 # Open SDDS file
209 if sddsdata.InitializeInput(self.index, input) != 1:
210 time.sleep(1)
211 if sddsdata.InitializeInput(self.index, input) != 1:
212 raise ValueError("Failed to initialize SDDS input.")
213
214 # Get data storage mode (SDDS_ASCII or SDDS_BINARY)
215 self.mode = sddsdata.GetMode(self.index)
216
217 # Get description text and contents
218 self.description = sddsdata.GetDescription(self.index)
219
220 # Get parameter names
221 self.parameterNameparameterName = sddsdata.GetParameterNames(self.index)
222 numberOfParameters = len(self.parameterNameparameterName)
223
224 # Get array names
225 self.arrayNamearrayName = sddsdata.GetArrayNames(self.index)
226 numberOfArrays = len(self.arrayNamearrayName)
227
228 # Get column names
229 self.columnNamecolumnName = sddsdata.GetColumnNames(self.index)
230 numberOfColumns = len(self.columnNamecolumnName)
231
232 # Get parameter definitions
233 self.parameterDefinition = [sddsdata.GetParameterDefinition(self.index, name) for name in self.parameterNameparameterName]
234
235 # Get array definitions
236 self.arrayDefinition = [sddsdata.GetArrayDefinition(self.index, name) for name in self.arrayNamearrayName]
237
238 # Get column definitions
239 self.columnDefinition = [sddsdata.GetColumnDefinition(self.index, name) for name in self.columnNamecolumnName]
240
241 # Initialize parameter, array, and column data
242 self.parameterData = [[] for _ in range(numberOfParameters)]
243 self.arrayData = [[] for _ in range(numberOfArrays)]
244 self.columnData = [[] for _ in range(numberOfColumns)]
245 self.arrayDimensions = [[] for _ in range(numberOfArrays)]
246
247 # Read in SDDS data sparsely
248 page = sddsdata.ReadPageSparse(self.index, interval, offset)
249 if page != 1:
250 raise Exception("Unable to read SDDS data for the first page")
251 while page > 0:
252 for i in range(numberOfParameters):
253 self.parameterData[i].append(sddsdata.GetParameter(self.index, i))
254 for i in range(numberOfArrays):
255 self.arrayData[i].append(sddsdata.GetArray(self.index, i))
256 self.arrayDimensions[i].append(sddsdata.GetArrayDimensions(self.index, i))
257 rows = sddsdata.RowCount(self.index)
258 if rows > 0:
259 for i in range(numberOfColumns):
260 self.columnData[i].append(sddsdata.GetColumn(self.index, i))
261 else:
262 for i in range(numberOfColumns):
263 self.columnData[i].append([])
264 page = sddsdata.ReadPageSparse(self.index, interval, offset)
265
266 # Close SDDS file
267 if sddsdata.Terminate(self.index) != 1:
268 raise ValueError("Failed to terminate SDDS input.")
269
270 except:
271 sddsdata.PrintErrors(self.SDDS_VERBOSE_PrintErrors)
272 raise
273
274 def loadLastRows(self, input, lastrows):
275 """
276 Loads an SDDS file into the SDDS object, reading only the last few rows.
277
278 Args:
279 input (str): The input SDDS filename to load.
280 lastrows (int): Number of last rows to read.
281
282 Raises:
283 Exception: If unable to read the SDDS data.
284
285 This method reads only the last `lastrows` rows from each page of the SDDS file.
286 """
287 try:
288 # Open SDDS file
289 if sddsdata.InitializeInput(self.index, input) != 1:
290 time.sleep(1)
291 if sddsdata.InitializeInput(self.index, input) != 1:
292 raise ValueError("Failed to initialize SDDS input.")
293
294 # Get data storage mode (SDDS_ASCII or SDDS_BINARY)
295 self.mode = sddsdata.GetMode(self.index)
296
297 # Get description text and contents
298 self.description = sddsdata.GetDescription(self.index)
299
300 # Get parameter names
301 self.parameterNameparameterName = sddsdata.GetParameterNames(self.index)
302 numberOfParameters = len(self.parameterNameparameterName)
303
304 # Get array names
305 self.arrayNamearrayName = sddsdata.GetArrayNames(self.index)
306 numberOfArrays = len(self.arrayNamearrayName)
307
308 # Get column names
309 self.columnNamecolumnName = sddsdata.GetColumnNames(self.index)
310 numberOfColumns = len(self.columnNamecolumnName)
311
312 # Get parameter definitions
313 self.parameterDefinition = [sddsdata.GetParameterDefinition(self.index, name) for name in self.parameterNameparameterName]
314
315 # Get array definitions
316 self.arrayDefinition = [sddsdata.GetArrayDefinition(self.index, name) for name in self.arrayNamearrayName]
317
318 # Get column definitions
319 self.columnDefinition = [sddsdata.GetColumnDefinition(self.index, name) for name in self.columnNamecolumnName]
320
321 # Initialize parameter, array, and column data
322 self.parameterData = [[] for _ in range(numberOfParameters)]
323 self.arrayData = [[] for _ in range(numberOfArrays)]
324 self.columnData = [[] for _ in range(numberOfColumns)]
325 self.arrayDimensions = [[] for _ in range(numberOfArrays)]
326
327 # Read in SDDS data (last rows)
328 page = sddsdata.ReadPageLastRows(self.index, lastrows)
329 if page != 1:
330 raise Exception("Unable to read SDDS data for the first page")
331 while page > 0:
332 for i in range(numberOfParameters):
333 self.parameterData[i].append(sddsdata.GetParameter(self.index, i))
334 for i in range(numberOfArrays):
335 self.arrayData[i].append(sddsdata.GetArray(self.index, i))
336 self.arrayDimensions[i].append(sddsdata.GetArrayDimensions(self.index, i))
337 rows = sddsdata.RowCount(self.index)
338 if rows > 0:
339 for i in range(numberOfColumns):
340 self.columnData[i].append(sddsdata.GetColumn(self.index, i))
341 else:
342 for i in range(numberOfColumns):
343 self.columnData[i].append([])
344 page = sddsdata.ReadPageLastRows(self.index, lastrows)
345
346 # Close SDDS file
347 if sddsdata.Terminate(self.index) != 1:
348 raise ValueError("Failed to terminate SDDS input.")
349
350 except:
351 sddsdata.PrintErrors(self.SDDS_VERBOSE_PrintErrors)
352 raise
353
354 def save(self, output):
355 """
356 Saves the SDDS object's data to an SDDS file.
357
358 Args:
359 output (str): The output SDDS filename to save the data.
360
361 Raises:
362 Exception: If unable to write the SDDS data.
363
364 This method writes the data stored in the SDDS object to the specified file, including the
365 parameters, arrays, columns, and their data.
366 """
367 try:
368 # Check for invalid SDDS data
369 numberOfParameters = len(self.parameterNameparameterName)
370 numberOfArrays = len(self.arrayNamearrayName)
371 numberOfColumns = len(self.columnNamecolumnName)
372 pages = 0
373
374 if numberOfParameters != len(self.parameterData):
375 raise Exception("Unmatched parameterName and parameterData")
376 if numberOfArrays != len(self.arrayData):
377 raise Exception("Unmatched arrayName and arrayData")
378 if numberOfColumns != len(self.columnData):
379 raise Exception("Unmatched columnName and columnData")
380 if numberOfParameters != len(self.parameterDefinition):
381 raise Exception("Unmatched parameterName and parameterDefinition")
382 if numberOfArrays != len(self.arrayDefinition):
383 raise Exception("Unmatched arrayName and arrayDefinition")
384 if numberOfColumns != len(self.columnDefinition):
385 raise Exception("Unmatched columnName and columnDefinition")
386
387 if numberOfParameters > 0:
388 pages = len(self.parameterData[0])
389 elif numberOfColumns > 0:
390 pages = len(self.columnData[0])
391 elif numberOfArrays > 0:
392 pages = len(self.arrayData[0])
393
394 for i in range(numberOfParameters):
395 if pages != len(self.parameterData[i]):
396 raise Exception("Unequal number of pages in parameter data")
397 for i in range(numberOfArrays):
398 if pages != len(self.arrayData[i]):
399 raise Exception("Unequal number of pages in array data")
400 if pages != len(self.arrayDimensions[i]):
401 raise Exception("Unequal number of pages in array dimension data")
402 for i in range(numberOfColumns):
403 if pages != len(self.columnData[i]):
404 raise Exception("Unequal number of pages in column data")
405 for page in range(pages):
406 rows = 0
407 if numberOfColumns > 0:
408 rows = len(self.columnData[0][page])
409 for i in range(numberOfColumns):
410 if rows != len(self.columnData[i][page]):
411 raise Exception("Unequal number of rows in column data")
412
413 # Open SDDS output file
414 if sddsdata.InitializeOutput(self.index, self.mode, 1, self.description[0], self.description[1], output) != 1:
415 raise ValueError("Failed to initialize SDDS output.")
416
417 # Define parameters, arrays, and columns
418 for i in range(numberOfParameters):
419 if sddsdata.DefineParameter(
420 self.index,
422 self.parameterDefinition[i][0],
423 self.parameterDefinition[i][1],
424 self.parameterDefinition[i][2],
425 self.parameterDefinition[i][3],
426 self.parameterDefinition[i][4],
427 self.parameterDefinition[i][5],
428 ) == -1:
429 raise ValueError("Failed to define parameter.")
430
431 for i in range(numberOfArrays):
432 if sddsdata.DefineArray(
433 self.index,
434 self.arrayNamearrayName[i],
435 self.arrayDefinition[i][0],
436 self.arrayDefinition[i][1],
437 self.arrayDefinition[i][2],
438 self.arrayDefinition[i][3],
439 self.arrayDefinition[i][4],
440 self.arrayDefinition[i][5],
441 self.arrayDefinition[i][6],
442 self.arrayDefinition[i][7],
443 ) == -1:
444 raise ValueError("Failed to define array.")
445
446 for i in range(numberOfColumns):
447 if sddsdata.DefineColumn(
448 self.index,
449 self.columnNamecolumnName[i],
450 self.columnDefinition[i][0],
451 self.columnDefinition[i][1],
452 self.columnDefinition[i][2],
453 self.columnDefinition[i][3],
454 self.columnDefinition[i][4],
455 self.columnDefinition[i][5],
456 ) == -1:
457 raise ValueError("Failed to define column.")
458
459 # Write SDDS header
460 if sddsdata.WriteLayout(self.index) != 1:
461 raise ValueError("Failed to write SDDS layout.")
462
463 # Write SDDS data
464 for page in range(pages):
465 rows = 0
466 if numberOfColumns > 0:
467 rows = len(self.columnData[0][page])
468 if sddsdata.StartPage(self.index, rows) != 1:
469 raise ValueError("Failed to start SDDS page.")
470 for i in range(numberOfParameters):
471 if sddsdata.SetParameter(self.index, i, self.parameterData[i][page]) != 1:
472 raise ValueError("Failed to set parameter value.")
473 for i in range(numberOfArrays):
474 if sddsdata.SetArray(
475 self.index, i, self.arrayData[i][page], self.arrayDimensions[i][page]
476 ) != 1:
477 raise ValueError("Failed to set array value.")
478 for i in range(numberOfColumns):
479 if sddsdata.SetColumn(self.index, i, self.columnData[i][page]) != 1:
480 raise ValueError("Failed to set column value.")
481 if sddsdata.WritePage(self.index) != 1:
482 raise ValueError("Failed to write SDDS page.")
483
484 # Close SDDS output file
485 if sddsdata.Terminate(self.index) != 1:
486 raise ValueError("Failed to terminate SDDS output.")
487 except:
488 sddsdata.PrintErrors(self.SDDS_VERBOSE_PrintErrors)
489 raise
490
491 def setDescription(self, text, contents):
492 """
493 Sets the description for the SDDS object.
494
495 Args:
496 text (str): Description text.
497 contents (str): Description contents.
498 """
499 self.description = [text, contents]
500
501 def defineParameter(self, name, symbol="", units="", description="", formatString="", type=SDDS_DOUBLE, fixedValue=""):
502 """
503 Defines a parameter for the SDDS object.
504
505 Args:
506 name (str): Parameter name.
507 symbol (str, optional): Parameter symbol.
508 units (str, optional): Parameter units.
509 description (str, optional): Parameter description.
510 formatString (str, optional): Format string for the parameter.
511 type (int, optional): Data type of the parameter. Defaults to SDDS_DOUBLE. Valid options include:
512 - SDDS_SHORT: 16-bit signed integer.
513 - SDDS_USHORT: 16-bit unsigned integer.
514 - SDDS_LONG: 32-bit signed integer.
515 - SDDS_ULONG: 32-bit unsigned integer.
516 - SDDS_LONG64: 64-bit signed integer.
517 - SDDS_ULONG64: 64-bit unsigned integer.
518 - SDDS_FLOAT: Single-precision floating-point number.
519 - SDDS_DOUBLE: Double-precision floating-point number.
520 - SDDS_LONGDOUBLE: Long double-precision floating-point number.
521 - SDDS_STRING: String (textual data).
522 - SDDS_CHARACTER: Single character.
523 fixedValue (str, optional): Fixed value of the parameter.
524
525 This method adds a parameter definition to the SDDS object.
526 """
527 self.parameterNameparameterName.append(name)
528 self.parameterDefinition.append(
529 [symbol, units, description, formatString, type, fixedValue]
530 )
531 self.parameterData.append([])
532
533 def defineSimpleParameter(self, name, type):
534 """
535 Defines a simple parameter with minimal information.
536
537 Args:
538 name (str): Parameter name.
539 type (int): Data type of the parameter. Valid options include:
540 - SDDS_SHORT: 16-bit signed integer.
541 - SDDS_USHORT: 16-bit unsigned integer.
542 - SDDS_LONG: 32-bit signed integer.
543 - SDDS_ULONG: 32-bit unsigned integer.
544 - SDDS_LONG64: 64-bit signed integer.
545 - SDDS_ULONG64: 64-bit unsigned integer.
546 - SDDS_FLOAT: Single-precision floating-point number.
547 - SDDS_DOUBLE: Double-precision floating-point number.
548 - SDDS_LONGDOUBLE: Long double-precision floating-point number.
549 - SDDS_STRING: String (textual data).
550 - SDDS_CHARACTER: Single character.
551
552 This method adds a parameter definition with default attributes.
553 """
554 self.parameterNameparameterName.append(name)
555 self.parameterDefinition.append(["", "", "", "", type, ""])
556 self.parameterData.append([])
557
558 def defineArray(self, name, symbol="", units="", description="", formatString="", group_name="", type=SDDS_DOUBLE, fieldLength=0, dimensions=1):
559 """
560 Defines an array for the SDDS object.
561
562 Args:
563 name (str): Array name.
564 symbol (str, optional): Array symbol.
565 units (str, optional): Array units.
566 description (str, optional): Array description.
567 formatString (str, optional): Format string for the array.
568 group_name (str, optional): Group name for the array.
569 type (int, optional): Data type of the array. Defaults to SDDS_DOUBLE, Valid options include:
570 - SDDS_SHORT: 16-bit signed integer.
571 - SDDS_USHORT: 16-bit unsigned integer.
572 - SDDS_LONG: 32-bit signed integer.
573 - SDDS_ULONG: 32-bit unsigned integer.
574 - SDDS_LONG64: 64-bit signed integer.
575 - SDDS_ULONG64: 64-bit unsigned integer.
576 - SDDS_FLOAT: Single-precision floating-point number.
577 - SDDS_DOUBLE: Double-precision floating-point number.
578 - SDDS_LONGDOUBLE: Long double-precision floating-point number.
579 - SDDS_STRING: String (textual data).
580 - SDDS_CHARACTER: Single character.
581 fieldLength (int, optional): Field length for the array.
582 dimensions (int, optional): Number of dimensions of the array. Defaults to 1
583
584 This method adds an array definition to the SDDS object.
585 """
586 self.arrayNamearrayName.append(name)
587 self.arrayDefinition.append(
588 [symbol, units, description, formatString, group_name, type, fieldLength, dimensions]
589 )
590 self.arrayData.append([])
591 self.arrayDimensions.append([])
592
593 def defineSimpleArray(self, name, type, dimensions):
594 """
595 Defines a simple array with minimal information.
596
597 Args:
598 name (str): Array name.
599 type (int): Data type of the array. Valid options include:
600 - SDDS_SHORT: 16-bit signed integer.
601 - SDDS_USHORT: 16-bit unsigned integer.
602 - SDDS_LONG: 32-bit signed integer.
603 - SDDS_ULONG: 32-bit unsigned integer.
604 - SDDS_LONG64: 64-bit signed integer.
605 - SDDS_ULONG64: 64-bit unsigned integer.
606 - SDDS_FLOAT: Single-precision floating-point number.
607 - SDDS_DOUBLE: Double-precision floating-point number.
608 - SDDS_LONGDOUBLE: Long double-precision floating-point number.
609 - SDDS_STRING: String (textual data).
610 - SDDS_CHARACTER: Single character.
611 dimensions (int): Number of dimensions of the array.
612
613 This method adds an array definition with default attributes.
614 """
615 self.arrayNamearrayName.append(name)
616 self.arrayDefinition.append(["", "", "", "", "", type, 0, dimensions])
617 self.arrayData.append([])
618 self.arrayDimensions.append([])
619
620 def defineColumn(self, name, symbol="", units="", description="", formatString="", type=SDDS_DOUBLE, fieldLength=0):
621 """
622 Defines a column for the SDDS object.
623
624 Args:
625 name (str): Column name.
626 symbol (str, optional): Column symbol.
627 units (str, optional): Column units.
628 description (str, optional): Column description.
629 formatString (str, optional): Format string for the column.
630 type (int, optional): Data type of the column. Defaults to SDDS_DOUBLE. Valid options include:
631 - SDDS_SHORT: 16-bit signed integer.
632 - SDDS_USHORT: 16-bit unsigned integer.
633 - SDDS_LONG: 32-bit signed integer.
634 - SDDS_ULONG: 32-bit unsigned integer.
635 - SDDS_LONG64: 64-bit signed integer.
636 - SDDS_ULONG64: 64-bit unsigned integer.
637 - SDDS_FLOAT: Single-precision floating-point number.
638 - SDDS_DOUBLE: Double-precision floating-point number.
639 - SDDS_LONGDOUBLE: Long double-precision floating-point number.
640 - SDDS_STRING: String (textual data).
641 - SDDS_CHARACTER: Single character.
642 fieldLength (int, optional): Field length for the column.
643
644 This method adds a column definition to the SDDS object.
645 """
646 self.columnNamecolumnName.append(name)
647 self.columnDefinition.append(
648 [symbol, units, description, formatString, type, fieldLength]
649 )
650 self.columnData.append([])
651
652 def defineSimpleColumn(self, name, type):
653 """
654 Defines a simple column with minimal information.
655
656 Args:
657 name (str): Column name.
658 type (int): Data type of the column. Valid options include:
659 - SDDS_SHORT: 16-bit signed integer.
660 - SDDS_USHORT: 16-bit unsigned integer.
661 - SDDS_LONG: 32-bit signed integer.
662 - SDDS_ULONG: 32-bit unsigned integer.
663 - SDDS_LONG64: 64-bit signed integer.
664 - SDDS_ULONG64: 64-bit unsigned integer.
665 - SDDS_FLOAT: Single-precision floating-point number.
666 - SDDS_DOUBLE: Double-precision floating-point number.
667 - SDDS_LONGDOUBLE: Long double-precision floating-point number.
668 - SDDS_STRING: String (textual data).
669 - SDDS_CHARACTER: Single character.
670
671 This method adds a column definition with default attributes.
672 """
673 self.columnNamecolumnName.append(name)
674 self.columnDefinition.append(["", "", "", "", type, 0])
675 self.columnData.append([])
676
677 def setParameterValueList(self, name, valueList):
678 """
679 Sets the list of parameter values for a parameter. This can be used to set values for multiple pages at once.
680
681 Args:
682 name (str): Parameter name.
683 valueList (list): List of values for the parameter.
684
685 Raises:
686 Exception: If the parameter name is invalid.
687
688 This method assigns a list of values to a parameter across pages.
689 """
690 numberOfParameters = len(self.parameterNameparameterName)
691 if name in self.parameterNameparameterName:
692 self.parameterData[self.parameterNameparameterName.index(name)] = valueList
693 else:
694 msg = "Invalid parameter name " + name
695 raise Exception(msg)
696
697 def getParameterValueList(self, name):
698 """
699 Gets the list of parameter values for a parameter. This can be used to get values for multiple pages at once.
700
701 Args:
702 name (str): Parameter name.
703
704 Returns:
705 list: List of values for the parameter.
706
707 Raises:
708 Exception: If the parameter name is invalid.
709
710 """
711 numberOfParameters = len(self.parameterNameparameterName)
712 if name in self.parameterNameparameterName:
713 return(self.parameterData[self.parameterNameparameterName.index(name)])
714 else:
715 msg = "Invalid parameter name " + name
716 raise Exception(msg)
717
718 def setParameterValue(self, name, value, page=1):
719 """
720 Sets a single parameter value at a specific page.
721
722 Args:
723 name (str): Parameter name.
724 value: Parameter value.
725 page (int, optional): Page number (1-based index, defaults to 1).
726
727 Raises:
728 Exception: If the parameter name or page is invalid.
729
730 This method sets the parameter value at the specified page.
731 """
732 page = page - 1
733 numberOfParameters = len(self.parameterNameparameterName)
734 if name in self.parameterNameparameterName:
735 i = self.parameterNameparameterName.index(name)
736 if len(self.parameterData[i]) == page:
737 self.parameterData[i][page:] = [value]
738 elif len(self.parameterData[i]) < page or page < 0:
739 msg = "Invalid page " + str(page + 1)
740 raise Exception(msg)
741 else:
742 self.parameterData[i][page] = value
743 else:
744 msg = "Invalid parameter name " + name
745 raise Exception(msg)
746
747 def getParameterValue(self, name, page=1):
748 """
749 Gets a single parameter value at a specific page.
750
751 Args:
752 name (str): Parameter name.
753 page (int, optional): Page number (1-based index, defaults to 1).
754
755 Returns:
756 value: Parameter value.
757
758 Raises:
759 Exception: If the parameter name or page is invalid.
760 """
761 page = page - 1
762 numberOfParameters = len(self.parameterNameparameterName)
763 if name in self.parameterNameparameterName:
764 i = self.parameterNameparameterName.index(name)
765 if len(self.parameterData[i]) == page:
766 return(self.parameterData[i][page:])
767 elif len(self.parameterData[i]) < page or page < 0:
768 msg = "Invalid page " + str(page + 1)
769 raise Exception(msg)
770 else:
771 return(self.parameterData[i][page])
772 else:
773 msg = "Invalid parameter name " + name
774 raise Exception(msg)
775
776 def setArrayValueLists(self, name, valueList, dimensionList):
777 """
778 Sets the nested list of array values and dimensions for a single array. This can be used to set values for multiple pages at once.
779
780 Args:
781 name (str): Array name.
782 valueList (list): Nested list of array values.
783 dimensionList (list): Nested list of array dimensions.
784
785 Raises:
786 Exception: If the array name is invalid.
787
788 This method assigns values and dimensions to an array across pages.
789 """
790 numberOfArrays = len(self.arrayNamearrayName)
791 if name in self.arrayNamearrayName:
792 i = self.arrayNamearrayName.index(name)
793 self.arrayDimensions[i] = dimensionList
794 self.arrayData[i] = valueList
795 else:
796 msg = "Invalid array name " + name
797 raise Exception(msg)
798
799 def getArrayValueLists(self, name):
800 """
801 Gets the nested list of array values for a single array. This can be used to get values for multiple pages at once.
802
803 Args:
804 name (str): Array name.
805
806 Returns:
807 list: Nested list of array values.
808
809 Raises:
810 Exception: If the array name is invalid.
811 """
812 numberOfArrays = len(self.arrayNamearrayName)
813 if name in self.arrayNamearrayName:
814 return(self.arrayData[self.arrayNamearrayName.index(name)])
815 else:
816 msg = "Invalid array name " + name
817 raise Exception(msg)
818
819 def getArrayDimensionLists(self, name):
820 """
821 Gets the nested list of array dimensions for a single array. This can be used to get dimensions for multiple pages at once.
822
823 Args:
824 name (str): Array name.
825
826 Returns:
827 list: Nested list of array dimensions.
828
829 Raises:
830 Exception: If the array name is invalid.
831 """
832 numberOfArrays = len(self.arrayNamearrayName)
833 if name in self.arrayNamearrayName:
834 return(self.arrayDimensions[self.arrayNamearrayName.index(name)])
835 else:
836 msg = "Invalid array name " + name
837 raise Exception(msg)
838
839 def setArrayValueList(self, name, valueList, dimensionList, page=1):
840 """
841 Sets a single array value and dimension at a specific page.
842
843 Args:
844 name (str): Array name.
845 valueList (list): Array values.
846 dimensionList (list): Array dimensions.
847 page (int, optional): Page number (1-based index, defaults to 1).
848
849 Raises:
850 Exception: If the array name or page is invalid.
851
852 This method sets the array values and dimensions at the specified page.
853 """
854 page = page - 1
855 numberOfArrays = len(self.arrayNamearrayName)
856 if name in self.arrayNamearrayName:
857 i = self.arrayNamearrayName.index(name)
858 if len(self.arrayData[i]) == page:
859 self.arrayData[i][page:] = [valueList]
860 self.arrayDimensions[i][page:] = [dimensionList]
861 elif len(self.arrayData[i]) < page or page < 0:
862 msg = "Invalid page " + str(page + 1)
863 raise Exception(msg)
864 else:
865 self.arrayData[i][page] = valueList
866 self.arrayDimensions[i][page] = dimensionList
867 else:
868 msg = "Invalid array name " + name
869 raise Exception(msg)
870
871 def getArrayValueList(self, name, page=1):
872 """
873 Gets a single array value at a specific page.
874
875 Args:
876 name (str): Array name.
877 page (int, optional): Page number (1-based index, defaults to 1).
878
879 Returns:
880 list: Array values.
881
882 Raises:
883 Exception: If the array name or page is invalid.
884 """
885 page = page - 1
886 numberOfArrays = len(self.arrayNamearrayName)
887 if name in self.arrayNamearrayName:
888 i = self.arrayNamearrayName.index(name)
889 if len(self.arrayData[i]) == page:
890 return(self.arrayData[i][page:])
891 elif len(self.arrayData[i]) < page or page < 0:
892 msg = "Invalid page " + str(page + 1)
893 raise Exception(msg)
894 else:
895 return(self.arrayData[i][page])
896 else:
897 msg = "Invalid array name " + name
898 raise Exception(msg)
899
900 def getArrayDimensionList(self, name, page=1):
901 """
902 Gets a single array dimension at a specific page.
903
904 Args:
905 name (str): Array name.
906 page (int, optional): Page number (1-based index, defaults to 1).
907
908 Returns:
909 list: Array dimension.
910
911 Raises:
912 Exception: If the array name or page is invalid.
913 """
914 page = page - 1
915 numberOfArrays = len(self.arrayNamearrayName)
916 if name in self.arrayNamearrayName:
917 i = self.arrayNamearrayName.index(name)
918 if len(self.arrayData[i]) == page:
919 return(self.arrayDimensions[i][page:])
920 elif len(self.arrayData[i]) < page or page < 0:
921 msg = "Invalid page " + str(page + 1)
922 raise Exception(msg)
923 else:
924 return(self.arrayDimensions[i][page])
925 else:
926 msg = "Invalid array name " + name
927 raise Exception(msg)
928
929 def setColumnValueLists(self, name, valueList):
930 """
931 Sets the nested list of column values for a single column. This can be used to set values for multiple pages at once.
932
933 Args:
934 name (str): Column name.
935 valueList (list): Nested list of column values.
936
937 Raises:
938 Exception: If the column name is invalid.
939
940 This method assigns a list of values to a column across pages.
941 """
942 numberOfColumns = len(self.columnNamecolumnName)
943 if name in self.columnNamecolumnName:
944 self.columnData[self.columnNamecolumnName.index(name)] = valueList
945 else:
946 msg = "Invalid column name " + name
947 raise Exception(msg)
948
949 def getColumnValueLists(self, name):
950 """
951 Gets the nested list of column values for a single column. This can be used to get values for multiple pages at once.
952
953 Args:
954 name (str): Column name.
955
956 Returns:
957 list: Nested list of column values.
958
959 Raises:
960 Exception: If the column name is invalid.
961 """
962 numberOfColumns = len(self.columnNamecolumnName)
963 if name in self.columnNamecolumnName:
964 return(self.columnData[self.columnNamecolumnName.index(name)])
965 else:
966 msg = "Invalid column name " + name
967 raise Exception(msg)
968
969 def setColumnValueList(self, name, valueList, page=1):
970 """
971 Sets a single column value list at a specific page.
972
973 Args:
974 name (str): Column name.
975 valueList (list): Column values.
976 page (int, optional): Page number (1-based index, defaults to 1).
977
978 Raises:
979 Exception: If the column name or page is invalid.
980
981 This method sets the column values at the specified page.
982 """
983 page = page - 1
984 if name in self.columnNamecolumnName:
985 i = self.columnNamecolumnName.index(name)
986 if len(self.columnData[i]) == page:
987 self.columnData[i][page:] = [valueList]
988 elif len(self.columnData[i]) < page or page < 0:
989 msg = "Invalid page " + str(page + 1)
990 raise Exception(msg)
991 else:
992 self.columnData[i][page] = valueList
993 else:
994 msg = "Invalid column name " + name
995 raise Exception(msg)
996
997 def getColumnValueList(self, name, page=1):
998 """
999 Gets a single column value list at a specific page.
1000
1001 Args:
1002 name (str): Column name.
1003 page (int, optional): Page number (1-based index, defaults to 1).
1004
1005 Returns:
1006 list: Column values.
1007
1008 Raises:
1009 Exception: If the column name or page is invalid.
1010 """
1011 page = page - 1
1012 numberOfColumns = len(self.columnNamecolumnName)
1013 if name in self.columnNamecolumnName:
1014 i = self.columnNamecolumnName.index(name)
1015 if len(self.columnData[i]) == page:
1016 return(self.columnData[i][page:])
1017 elif len(self.columnData[i]) < page or page < 0:
1018 msg = "Invalid page " + str(page + 1)
1019 raise Exception(msg)
1020 else:
1021 return(self.columnData[i][page])
1022 else:
1023 msg = "Invalid column name " + name
1024 raise Exception(msg)
1025
1026 def setColumnValue(self, name, value, page=1, row=1):
1027 """
1028 Sets a single column value at a specific page and row.
1029
1030 Args:
1031 name (str): Column name.
1032 value: Column value.
1033 page (int, optional): Page number (1-based index, defaults to 1).
1034 row (int, optional): Row number (1-based index, defaults to 1).
1035
1036 Raises:
1037 Exception: If the column name, page, or row is invalid.
1038
1039 This method sets the column value at the specified page and row.
1040 """
1041 page = page - 1
1042 row = row - 1
1043 numberOfColumns = len(self.columnNamecolumnName)
1044 if name in self.columnNamecolumnName:
1045 i = self.columnNamecolumnName.index(name)
1046 if len(self.columnData[i]) == page:
1047 if row == 0:
1048 self.columnData[i][page:] = [[value]]
1049 else:
1050 msg = "Invalid row " + str(row + 1)
1051 raise Exception(msg)
1052 elif len(self.columnData[i]) < page or page < 0:
1053 msg = "Invalid page " + str(page + 1)
1054 raise Exception(msg)
1055 else:
1056 if len(self.columnData[i][page]) == row:
1057 self.columnData[i][page][row:] = [value]
1058 elif len(self.columnData[i][page]) < row or row < 0:
1059 msg = "Invalid row " + str(row + 1)
1060 raise Exception(msg)
1061 else:
1062 self.columnData[i][page][row] = value
1063 else:
1064 msg = "Invalid column name " + name
1065 raise Exception(msg)
1066
1067 def getColumnValue(self, name, page=1, row=1):
1068 """
1069 Gets a single column value at a specific page and row.
1070
1071 Args:
1072 name (str): Column name.
1073 page (int, optional): Page number (1-based index, defaults to 1).
1074 row (int, optional): Row number (1-based index, defaults to 1).
1075
1076 Returns:
1077 value: Column value.
1078
1079 Raises:
1080 Exception: If the column name, page, or row is invalid.
1081 """
1082 page = page - 1
1083 row = row - 1
1084 numberOfColumns = len(self.columnNamecolumnName)
1085 if name in self.columnNamecolumnName:
1086 i = self.columnNamecolumnName.index(name)
1087 if len(self.columnData[i]) == page:
1088 if row == 0:
1089 return(self.columnData[i][page:])
1090 else:
1091 msg = "Invalid row " + str(row + 1)
1092 raise Exception(msg)
1093 elif len(self.columnData[i]) < page or page < 0:
1094 msg = "Invalid page " + str(page + 1)
1095 raise Exception(msg)
1096 else:
1097 if len(self.columnData[i][page]) == row:
1098 return(self.columnData[i][page][row:])
1099 elif len(self.columnData[i][page]) < row or row < 0:
1100 msg = "Invalid row " + str(row + 1)
1101 raise Exception(msg)
1102 else:
1103 return(self.columnData[i][page][row])
1104 else:
1105 msg = "Invalid column name " + name
1106 raise Exception(msg)
1107
1109 """
1110 Retrieves the number of parameters.
1111
1112 Returns:
1113 int: The number of parameters.
1114 """
1115 return(len(self.parameterNameparameterName))
1116
1117 def getArrayCount(self):
1118 """
1119 Retrieves the number of arrays.
1120
1121 Returns:
1122 int: The number of arrays.
1123 """
1124 return(len(self.arrayNamearrayName))
1125
1127 """
1128 Retrieves the number of columns.
1129
1130 Returns:
1131 int: The number of columns.
1132 """
1133 return(len(self.columnNamecolumnName))
1134
1136 """
1137 Retrieves a list of all parameter names.
1138
1139 Returns:
1140 list: A list of parameter names as strings, or an empty list.
1141 """
1142 return(self.parameterNameparameterName)
1143
1144 def getArrayNames(self):
1145 """
1146 Retrieves a list of all array names.
1147
1148 Returns:
1149 list: A list of array names as strings, or an empty list.
1150 """
1151 return(self.arrayNamearrayName)
1152
1154 """
1155 Retrieves a list of all column names.
1156
1157 Returns:
1158 list: A list of column names as strings, or an empty list.
1159 """
1160 return(self.columnNamecolumnName)
1161
1162 def getParameterDatatype(self, name):
1163 """
1164 Retrieves the data type of a parameter.
1165
1166 Args:
1167 name (str): Parameter name.
1168
1169 Returns:
1170 int: Number representing the data type of the parameter.
1171 """
1172 if name in self.parameterNameparameterName:
1173 return(self.parameterDefinition[self.parameterNameparameterName.index(name)][4])
1174 else:
1175 msg = "Invalid parameter name " + name
1176 raise Exception(msg)
1177
1178 def getArrayDatatype(self, name):
1179 """
1180 Retrieves the data type of a array.
1181
1182 Args:
1183 name (str): Array name.
1184
1185 Returns:
1186 int: Number representing the data type of the array.
1187 """
1188 if name in self.arrayNamearrayName:
1189 return(self.arrayDefinition[self.arrayNamearrayName.index(name)][5])
1190 else:
1191 msg = "Invalid array name " + name
1192 raise Exception(msg)
1193
1194 def getColumnDatatype(self, name):
1195 """
1196 Retrieves the data type of a column.
1197
1198 Args:
1199 name (str): Column name.
1200
1201 Returns:
1202 int: Number representing the data type of the column.
1203 """
1204 if name in self.columnNamecolumnName:
1205 return(self.columnDefinition[self.columnNamecolumnName.index(name)][4])
1206 else:
1207 msg = "Invalid column name " + name
1208 raise Exception(msg)
1209
1210 def getParameterUnits(self, name):
1211 """
1212 Retrieves the units of a parameter.
1213
1214 Args:
1215 name (str): Parameter name.
1216
1217 Returns:
1218 str: Units of the parameter.
1219 """
1220 if name in self.parameterNameparameterName:
1221 return(self.parameterDefinition[self.parameterNameparameterName.index(name)][1])
1222 else:
1223 msg = "Invalid parameter name " + name
1224 raise Exception(msg)
1225
1226 def getArrayDatatype(self, name):
1227 """
1228 Retrieves the units of a array.
1229
1230 Args:
1231 name (str): Array name.
1232
1233 Returns:
1234 str: Units of the array.
1235 """
1236 if name in self.arrayNamearrayName:
1237 return(self.arrayDefinition[self.arrayNamearrayName.index(name)][1])
1238 else:
1239 msg = "Invalid array name " + name
1240 raise Exception(msg)
1241
1242 def getColumnDatatype(self, name):
1243 """
1244 Retrieves the units of a column.
1245
1246 Args:
1247 name (str): Column name.
1248
1249 Returns:
1250 str: Units of the column.
1251 """
1252 if name in self.columnNamecolumnName:
1253 return(self.columnDefinition[self.columnNamecolumnName.index(name)][1])
1254 else:
1255 msg = "Invalid column name " + name
1256 raise Exception(msg)
1257
1258 def pageCount(self):
1259 """
1260 Retrieves the number or loaded pages
1261
1262 Returns:
1263 int: Number or loaded pages
1264 """
1265 return(self.loaded_pages)
1266
1267
1268
1269# Expose constants to the module-level namespace
1270SDDS_VERBOSE_PrintErrors = SDDS.SDDS_VERBOSE_PrintErrors
1271SDDS_EXIT_PrintErrors = SDDS.SDDS_EXIT_PrintErrors
1272SDDS_CHECK_OKAY = SDDS.SDDS_CHECK_OKAY
1273SDDS_CHECK_NONEXISTENT = SDDS.SDDS_CHECK_NONEXISTENT
1274SDDS_CHECK_WRONGTYPE = SDDS.SDDS_CHECK_WRONGTYPE
1275SDDS_CHECK_WRONGUNITS = SDDS.SDDS_CHECK_WRONGUNITS
1276SDDS_LONGDOUBLE = SDDS.SDDS_LONGDOUBLE
1277SDDS_DOUBLE = SDDS.SDDS_DOUBLE
1278SDDS_REAL64 = SDDS.SDDS_REAL64
1279SDDS_FLOAT = SDDS.SDDS_FLOAT
1280SDDS_REAL32 = SDDS.SDDS_REAL32
1281SDDS_LONG64 = SDDS.SDDS_LONG64
1282SDDS_INT64 = SDDS.SDDS_INT64
1283SDDS_ULONG64 = SDDS.SDDS_ULONG64
1284SDDS_UINT64 = SDDS.SDDS_UINT64
1285SDDS_LONG = SDDS.SDDS_LONG
1286SDDS_INT32 = SDDS.SDDS_INT32
1287SDDS_ULONG = SDDS.SDDS_ULONG
1288SDDS_UINT32 = SDDS.SDDS_UINT32
1289SDDS_SHORT = SDDS.SDDS_SHORT
1290SDDS_INT16 = SDDS.SDDS_INT16
1291SDDS_USHORT = SDDS.SDDS_USHORT
1292SDDS_UINT16 = SDDS.SDDS_UINT16
1293SDDS_STRING = SDDS.SDDS_STRING
1294SDDS_CHARACTER = SDDS.SDDS_CHARACTER
1295SDDS_NUM_TYPES = SDDS.SDDS_NUM_TYPES
1296SDDS_BINARY = SDDS.SDDS_BINARY
1297SDDS_ASCII = SDDS.SDDS_ASCII
1298SDDS_FLUSH_TABLE = SDDS.SDDS_FLUSH_TABLE
1299
1300def sdds_data_type_to_string(data_type_code):
1301 """
1302 Converts a numeric SDDS data type code to its string representation.
1303
1304 Args:
1305 data_type_code (int): Numeric code of the SDDS data type.
1306
1307 Returns:
1308 str: String representation of the SDDS data type.
1309 """
1310 # Mapping of SDDS numeric data type codes to string representations
1311 data_type_map = {
1312 1: "SDDS_LONGDOUBLE",
1313 2: "SDDS_DOUBLE",
1314 3: "SDDS_FLOAT",
1315 4: "SDDS_LONG64",
1316 5: "SDDS_ULONG64",
1317 6: "SDDS_LONG",
1318 7: "SDDS_ULONG",
1319 8: "SDDS_SHORT",
1320 9: "SDDS_USHORT",
1321 10: "SDDS_STRING",
1322 11: "SDDS_CHARACTER",
1323 }
1324 return data_type_map.get(data_type_code, "Unknown Data Type")
1325
1326def demo1(output):
1327 """
1328 Demonstrates how to save a demo SDDS file using the SDDS class.
1329
1330 Args:
1331 output (str): The output SDDS filename to save the demo data.
1332
1333 This function creates an SDDS object, populates it with sample data, and saves it to the specified output file.
1334 """
1335 x = SDDS(0)
1336 x.description[0] = "text"
1337 x.description[1] = "contents"
1338 x.parameterName = ["ShortP", "LongP", "FloatP", "DoubleP", "StringP", "CharacterP"]
1339 x.parameterData = [[1, 6], [2, 7], [3.3, 8.8], [4.4, 9.8], ["five", "ten"], ["a", "b"]]
1340 x.parameterDefinition = [
1341 ["", "", "", "", x.SDDS_SHORT, ""],
1342 ["", "", "", "", x.SDDS_LONG, ""],
1343 ["", "", "", "", x.SDDS_FLOAT, ""],
1344 ["", "", "", "", x.SDDS_DOUBLE, ""],
1345 ["", "", "", "", x.SDDS_STRING, ""],
1346 ["", "", "", "", x.SDDS_CHARACTER, ""],
1347 ]
1348
1349 x.arrayName = ["ShortA", "LongA", "FloatA", "DoubleA", "StringA", "CharacterA"]
1350 x.arrayDefinition = [
1351 ["", "", "", "", "", x.SDDS_SHORT, 0, 1],
1352 ["", "", "", "", "", x.SDDS_LONG, 0, 1],
1353 ["", "", "", "", "", x.SDDS_FLOAT, 0, 2],
1354 ["", "", "", "", "", x.SDDS_DOUBLE, 0, 1],
1355 ["", "", "", "", "", x.SDDS_STRING, 0, 1],
1356 ["", "", "", "", "", x.SDDS_CHARACTER, 0, 1],
1357 ]
1358 x.arrayDimensions = [
1359 [[6], [8]],
1360 [[5], [7]],
1361 [[2, 3], [2, 4]],
1362 [[4], [5]],
1363 [[4], [5]],
1364 [[4], [5]],
1365 ]
1366 x.arrayData = [
1367 [[1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6, 7, 8]],
1368 [[1, 2, 3, 4, 5], [1, 2, 3, 4, 5, 6, 7]],
1369 [[1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6, 7, 8]],
1370 [[1, 2, 3, 4], [1, 2, 3, 4, 5]],
1371 [["one", "two", "three", "four"], ["five", "six", "seven", "eight", "nine"]],
1372 [["a", "b", "c", "d"], ["e", "f", "g", "h", "i"]],
1373 ]
1374
1375 x.columnName = ["ShortC", "LongC", "FloatC", "DoubleC", "StringC", "CharacterC"]
1376 x.columnData = [
1377 [[1, 2, 3], [-1, -2, -3, -4]],
1378 [[1, 2, 3], [-1, -2, -3, -4]],
1379 [[1, 2, 3], [-1, -2, -3.6, -4.4]],
1380 [[1, 2, 3], [-1, -2, -3.6, -4.4]],
1381 [["row 1", "row 2", "row 3"], ["row 1", "row 2", "row 3", "row 4"]],
1382 [["x", "y", "z"], ["i", "j", "k", "l"]],
1383 ]
1384 x.columnDefinition = [
1385 ["", "", "", "", x.SDDS_SHORT, 0],
1386 ["", "", "", "", x.SDDS_LONG, 0],
1387 ["", "", "", "", x.SDDS_FLOAT, 0],
1388 ["", "", "", "", x.SDDS_DOUBLE, 0],
1389 ["", "", "", "", x.SDDS_STRING, 0],
1390 ["", "", "", "", x.SDDS_CHARACTER, 0],
1391 ]
1392
1393 x.save(output)
1394 del x
1395
1396
1397def demo2(output):
1398 """
1399 Demonstrates how to save a demo SDDS file using the SDDS class with simplified definitions.
1400
1401 Args:
1402 output (str): The output SDDS filename to save the demo data.
1403
1404 This function shows how to use simplified methods to define parameters, arrays, and columns.
1405 """
1406 x = SDDS(0)
1407 x.setDescription("text", "contents")
1408 names = ["Short", "Long", "Float", "Double", "String", "Character"]
1409 types = [x.SDDS_SHORT, x.SDDS_LONG, x.SDDS_FLOAT, x.SDDS_DOUBLE, x.SDDS_STRING, x.SDDS_CHARACTER]
1410 for i in range(6):
1411 x.defineSimpleParameter(names[i] + "P", types[i])
1412 if types[i] == x.SDDS_FLOAT:
1413 x.defineSimpleArray(names[i] + "A", types[i], 2)
1414 else:
1415 x.defineSimpleArray(names[i] + "A", types[i], 1)
1416 x.defineSimpleColumn(names[i] + "C", types[i])
1417 parameterData = [[1, 6], [2, 7], [3.3, 8.8], [4.4, 9.8], ["five", "ten"], ["a", "b"]]
1418 for i in range(6):
1419 x.setParameterValueList(names[i] + "P", parameterData[i])
1420
1421 arrayDimensions = [
1422 [[6], [8]],
1423 [[5], [7]],
1424 [[2, 3], [2, 4]],
1425 [[4], [5]],
1426 [[4], [5]],
1427 [[4], [5]],
1428 ]
1429 arrayData = [
1430 [[1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6, 7, 8]],
1431 [[1, 2, 3, 4, 5], [1, 2, 3, 4, 5, 6, 7]],
1432 [[1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6, 7, 8]],
1433 [[1, 2, 3, 4], [1, 2, 3, 4, 5]],
1434 [["one", "two", "three", "four"], ["five", "six", "seven", "eight", "nine"]],
1435 [["a", "b", "c", "d"], ["e", "f", "g", "h", "i"]],
1436 ]
1437 for i in range(6):
1438 x.setArrayValueLists(names[i] + "A", arrayData[i], arrayDimensions[i])
1439
1440 columnData = [
1441 [[1, 2, 3], [-1, -2, -3, -4]],
1442 [[1, 2, 3], [-1, -2, -3, -4]],
1443 [[1, 2, 3], [-1, -2, -3.6, -4.4]],
1444 [[1, 2, 3], [-1, -2, -3.6, -4.4]],
1445 [["row 1", "row 2", "row 3"], ["row 1", "row 2", "row 3", "row 4"]],
1446 [["x", "y", "z"], ["i", "j", "k", "l"]],
1447 ]
1448 for i in range(6):
1449 x.setColumnValueLists(names[i] + "C", columnData[i])
1450 x.save(output)
1451
1452
1453def demo3(output):
1454 """
1455 Demonstrates how to save a demo SDDS file using `sddsdata` commands directly.
1456
1457 Args:
1458 output (str): The output SDDS filename to save the demo data.
1459
1460 This function shows how to use `sddsdata` module functions directly to create and save an SDDS file.
1461 """
1462 x = SDDS(0)
1463
1464 try:
1465 # Open SDDS output file
1466 if sddsdata.InitializeOutput(x.index, x.SDDS_BINARY, 1, "", "", output) != 1:
1467 raise ValueError("Failed to initialize SDDS output.")
1468 # Setting column_major to true. Only use this if you are going to write whole columns and not one row at a time.
1469 sddsdata.SetColumnMajorOrder(x.index)
1470 # Define parameters
1471 if sddsdata.DefineSimpleParameter(x.index, "ParameterA", "mm", x.SDDS_DOUBLE) != 1:
1472 raise ValueError("Failed to define parameter.")
1473 # Define arrays
1474 if sddsdata.DefineSimpleArray(x.index, "ArrayA", "DegC", x.SDDS_DOUBLE, 1) != 1:
1475 raise ValueError("Failed to define array.")
1476 if sddsdata.DefineSimpleArray(x.index, "ArrayB", "DegC", x.SDDS_DOUBLE, 2) != 1:
1477 raise ValueError("Failed to define array.")
1478 # Define columns
1479 if sddsdata.DefineSimpleColumn(x.index, "ColumnA", "Volts", x.SDDS_DOUBLE) != 1:
1480 raise ValueError("Failed to define column.")
1481 if sddsdata.DefineSimpleColumn(x.index, "ColumnB", "Amps", x.SDDS_DOUBLE) != 1:
1482 raise ValueError("Failed to define column.")
1483 # Write SDDS header
1484 if sddsdata.WriteLayout(x.index) != 1:
1485 raise ValueError("Failed to write SDDS layout.")
1486 # Start SDDS page. Allocate 100 rows.
1487 if sddsdata.StartPage(x.index, 100) != 1:
1488 raise ValueError("Failed to start SDDS page.")
1489 # Set parameter values
1490 if sddsdata.SetParameter(x.index, "ParameterA", 1.1) != 1:
1491 raise ValueError("Failed to set parameter value.")
1492 # Set array values
1493 if sddsdata.SetArray(x.index, "ArrayA", [1, 2, 3], [3]) != 1:
1494 raise ValueError("Failed to set array value.")
1495 if sddsdata.SetArray(x.index, "ArrayB", [1, 2, 3, 4, 5, 6], [2, 3]) != 1:
1496 raise ValueError("Failed to set array value.")
1497 # Set column values
1498 if sddsdata.SetColumn(x.index, "ColumnA", [1, 2, 3]) != 1:
1499 raise ValueError("Failed to set column value.")
1500 if sddsdata.SetColumn(x.index, "ColumnB", [1, 2, 3]) != 1:
1501 raise ValueError("Failed to set column value.")
1502 # Write page to disk
1503 if sddsdata.WritePage(x.index) != 1:
1504 raise ValueError("Failed to write SDDS page.")
1505 # Close SDDS output file
1506 if sddsdata.Terminate(x.index) != 1:
1507 raise ValueError("Failed to terminate SDDS output.")
1508
1509 except:
1510 sddsdata.PrintErrors(x.SDDS_VERBOSE_PrintErrors)
1511 raise
1512
1513
1514def demo4(output):
1515 """
1516 Demonstrates how to save a demo SDDS file using `sddsdata` commands and writing one row at a time.
1517
1518 Args:
1519 output (str): The output SDDS filename to save the demo data.
1520
1521 This function shows how to write data to an SDDS file one row at a time, useful for logging applications.
1522 """
1523 x = SDDS(0)
1524
1525 try:
1526 # Open SDDS output file
1527 if sddsdata.InitializeOutput(x.index, x.SDDS_BINARY, 1, "", "", output) != 1:
1528 raise ValueError("Failed to initialize SDDS output.")
1529 # Turning on fsync mode and fixed rows count mode. These are useful for loggers.
1530 sddsdata.EnableFSync(x.index)
1531 sddsdata.SetFixedRowCountMode(x.index)
1532 # Define parameters
1533 if sddsdata.DefineSimpleParameter(x.index, "ParameterA", "mm", x.SDDS_DOUBLE) != 1:
1534 raise ValueError("Failed to define parameter.")
1535 # Define arrays
1536 if sddsdata.DefineSimpleArray(x.index, "ArrayA", "DegC", x.SDDS_DOUBLE, 1) != 1:
1537 raise ValueError("Failed to define array.")
1538 if sddsdata.DefineSimpleArray(x.index, "ArrayB", "DegC", x.SDDS_DOUBLE, 2) != 1:
1539 raise ValueError("Failed to define array.")
1540 # Define columns
1541 if sddsdata.DefineSimpleColumn(x.index, "ColumnA", "Volts", x.SDDS_DOUBLE) != 1:
1542 raise ValueError("Failed to define column.")
1543 if sddsdata.DefineSimpleColumn(x.index, "ColumnB", "Amps", x.SDDS_DOUBLE) != 1:
1544 raise ValueError("Failed to define column.")
1545 # Write SDDS header
1546 if sddsdata.WriteLayout(x.index) != 1:
1547 raise ValueError("Failed to write SDDS layout.")
1548 # Start SDDS page, allocate 2 rows.
1549 if sddsdata.StartPage(x.index, 2) != 1:
1550 raise ValueError("Failed to start SDDS page.")
1551 # Set parameter values
1552 if sddsdata.SetParameter(x.index, "ParameterA", 1.1) != 1:
1553 raise ValueError("Failed to set parameter value.")
1554 # Set array values
1555 if sddsdata.SetArray(x.index, "ArrayA", [1, 2, 3], [3]) != 1:
1556 raise ValueError("Failed to set array value.")
1557 if sddsdata.SetArray(x.index, "ArrayB", [1, 2, 3, 4, 5, 6], [2, 3]) != 1:
1558 raise ValueError("Failed to set array value.")
1559 # Set all columns, one row at a time
1560 if sddsdata.SetRowValues(x.index, 0, ["ColumnA", 1, "ColumnB", 1]) != 1:
1561 raise ValueError("Failed to set row values.")
1562 if sddsdata.SetRowValues(x.index, 1, ["ColumnA", 2, "ColumnB", 2]) != 1:
1563 raise ValueError("Failed to set row values.")
1564 # Update page because we reached the row allocation limit set in the StartPage command
1565 if sddsdata.UpdatePage(x.index, x.SDDS_FLUSH_TABLE) != 1:
1566 raise ValueError("Failed to update SDDS page.")
1567 # Set more rows
1568 if sddsdata.SetRowValues(x.index, 2, ["ColumnA", 3, "ColumnB", 3]) != 1:
1569 raise ValueError("Failed to set row values.")
1570 # Update page
1571 if sddsdata.UpdatePage(x.index, x.SDDS_FLUSH_TABLE) != 1:
1572 raise ValueError("Failed to update SDDS page.")
1573 # Close SDDS output file
1574 if sddsdata.Terminate(x.index) != 1:
1575 raise ValueError("Failed to terminate SDDS output.")
1576
1577 except:
1578 sddsdata.PrintErrors(x.SDDS_VERBOSE_PrintErrors)
1579 raise
1580
1581
1582def demo5(output):
1583 """
1584 Demonstrates how to open an existing SDDS file and add rows to the last page without loading the whole file into memory.
1585
1586 Args:
1587 output (str): The output SDDS filename to append data.
1588
1589 This function shows how to append data to an existing SDDS file efficiently.
1590 """
1591 x = SDDS(0)
1592
1593 try:
1594 # Open SDDS output file
1595 rows = sddsdata.InitializeAppendToPage(x.index, output, 100)
1596 if rows == 0:
1597 raise ValueError("Failed to initialize appending to SDDS page.")
1598 # Set all columns, one row at a time
1599 if sddsdata.SetRowValues(x.index, rows, ["ColumnA", 4, "ColumnB", 4]) != 1:
1600 raise ValueError("Failed to set row values.")
1601 if sddsdata.SetRowValues(x.index, rows + 1, ["ColumnA", 5, "ColumnB", 5]) != 1:
1602 raise ValueError("Failed to set row values.")
1603 if sddsdata.SetRowValues(x.index, rows + 2, ["ColumnA", 6, "ColumnB", 6]) != 1:
1604 raise ValueError("Failed to set row values.")
1605 # Update page
1606 if sddsdata.UpdatePage(x.index, x.SDDS_FLUSH_TABLE) != 1:
1607 raise ValueError("Failed to update SDDS page.")
1608 # Close SDDS output file
1609 if sddsdata.Terminate(x.index) != 1:
1610 raise ValueError("Failed to terminate SDDS output.")
1611
1612 except:
1613 sddsdata.PrintErrors(x.SDDS_VERBOSE_PrintErrors)
1614 raise
1615
1616
1617def demo6(output):
1618 """
1619 Demonstrates how to open an existing SDDS file and add a new page.
1620
1621 Args:
1622 output (str): The output SDDS filename to append data.
1623
1624 This function shows how to append a new page to an existing SDDS file.
1625 """
1626 x = SDDS(0)
1627
1628 try:
1629 # Open SDDS output file
1630 if sddsdata.InitializeAppend(x.index, output) != 1:
1631 raise ValueError("Failed to initialize appending to SDDS file.")
1632 # Allocate rows
1633 if sddsdata.StartPage(x.index, 100) != 1:
1634 raise ValueError("Failed to start SDDS page.")
1635 # Set parameter values
1636 if sddsdata.SetParameter(x.index, "ParameterA", 1.1) != 1:
1637 raise ValueError("Failed to set parameter value.")
1638 # Set array values
1639 if sddsdata.SetArray(x.index, "ArrayA", [1, 2, 3], [3]) != 1:
1640 raise ValueError("Failed to set array value.")
1641 if sddsdata.SetArray(x.index, "ArrayB", [1, 2, 3, 4, 5, 6], [2, 3]) != 1:
1642 raise ValueError("Failed to set array value.")
1643 # Set all columns, one row at a time
1644 if sddsdata.SetRowValues(x.index, 0, ["ColumnA", 7, "ColumnB", 7]) != 1:
1645 raise ValueError("Failed to set row values.")
1646 if sddsdata.SetRowValues(x.index, 1, ["ColumnA", 8, "ColumnB", 8]) != 1:
1647 raise ValueError("Failed to set row values.")
1648 if sddsdata.SetRowValues(x.index, 2, ["ColumnA", 9, "ColumnB", 9]) != 1:
1649 raise ValueError("Failed to set row values.")
1650 # Write page
1651 if sddsdata.WritePage(x.index) != 1:
1652 raise ValueError("Failed to write SDDS page.")
1653 # Close SDDS output file
1654 if sddsdata.Terminate(x.index) != 1:
1655 raise ValueError("Failed to terminate SDDS output.")
1656
1657 except:
1658 sddsdata.PrintErrors(x.SDDS_VERBOSE_PrintErrors)
1659 raise
A class to represent and manipulate SDDS datasets.
Definition sdds.py:17
getColumnValueLists(self, name)
Gets the nested list of column values for a single column.
Definition sdds.py:949
defineSimpleParameter(self, name, type)
Defines a simple parameter with minimal information.
Definition sdds.py:533
list parameterDefinition
Definition sdds.py:102
setArrayValueLists(self, name, valueList, dimensionList)
Sets the nested list of array values and dimensions for a single array.
Definition sdds.py:776
defineArray(self, name, symbol="", units="", description="", formatString="", group_name="", type=SDDS_DOUBLE, fieldLength=0, dimensions=1)
Defines an array for the SDDS object.
Definition sdds.py:558
defineSimpleColumn(self, name, type)
Defines a simple column with minimal information.
Definition sdds.py:652
getColumnValueList(self, name, page=1)
Gets a single column value list at a specific page.
Definition sdds.py:997
loadSparse(self, input, interval, offset)
Loads an SDDS file into the SDDS object with sparse data reading.
Definition sdds.py:193
list parameterData
Definition sdds.py:106
getArrayCount(self)
Retrieves the number of arrays.
Definition sdds.py:1117
getArrayDatatype(self, name)
Retrieves the data type of a array.
Definition sdds.py:1178
load(self, input)
Loads an SDDS file into the SDDS object.
Definition sdds.py:112
getArrayValueLists(self, name)
Gets the nested list of array values for a single array.
Definition sdds.py:799
setParameterValue(self, name, value, page=1)
Sets a single parameter value at a specific page.
Definition sdds.py:718
getColumnCount(self)
Retrieves the number of columns.
Definition sdds.py:1126
list arrayData
Definition sdds.py:107
getColumnValue(self, name, page=1, row=1)
Gets a single column value at a specific page and row.
Definition sdds.py:1067
setParameterValueList(self, name, valueList)
Sets the list of parameter values for a parameter.
Definition sdds.py:677
getParameterValue(self, name, page=1)
Gets a single parameter value at a specific page.
Definition sdds.py:747
list arrayName
Definition sdds.py:100
getParameterValueList(self, name)
Gets the list of parameter values for a parameter.
Definition sdds.py:697
int mode
Definition sdds.py:109
getArrayNames(self)
Retrieves a list of all array names.
Definition sdds.py:1144
defineParameter(self, name, symbol="", units="", description="", formatString="", type=SDDS_DOUBLE, fixedValue="")
Defines a parameter for the SDDS object.
Definition sdds.py:501
defineColumn(self, name, symbol="", units="", description="", formatString="", type=SDDS_DOUBLE, fieldLength=0)
Defines a column for the SDDS object.
Definition sdds.py:620
int SDDS_ASCII
Definition sdds.py:81
getParameterNames(self)
Retrieves a list of all parameter names.
Definition sdds.py:1135
list description
Definition sdds.py:98
getColumnDatatype(self, name)
Retrieves the data type of a column.
Definition sdds.py:1194
pageCount(self)
Retrieves the number or loaded pages.
Definition sdds.py:1258
setColumnValue(self, name, value, page=1, row=1)
Sets a single column value at a specific page and row.
Definition sdds.py:1026
list columnName
Definition sdds.py:101
getArrayDimensionLists(self, name)
Gets the nested list of array dimensions for a single array.
Definition sdds.py:819
defineSimpleArray(self, name, type, dimensions)
Defines a simple array with minimal information.
Definition sdds.py:593
getParameterCount(self)
Retrieves the number of parameters.
Definition sdds.py:1108
list columnDefinition
Definition sdds.py:105
setArrayValueList(self, name, valueList, dimensionList, page=1)
Sets a single array value and dimension at a specific page.
Definition sdds.py:839
int SDDS_VERBOSE_PrintErrors
Definition sdds.py:48
getParameterUnits(self, name)
Retrieves the units of a parameter.
Definition sdds.py:1210
list parameterName
Definition sdds.py:99
setDescription(self, text, contents)
Sets the description for the SDDS object.
Definition sdds.py:491
__init__(self, index)
Initializes a new SDDS object.
Definition sdds.py:84
int index
Definition sdds.py:94
list arrayDimensions
Definition sdds.py:104
list arrayDefinition
Definition sdds.py:103
loadLastRows(self, input, lastrows)
Loads an SDDS file into the SDDS object, reading only the last few rows.
Definition sdds.py:274
list columnData
Definition sdds.py:108
getArrayValueList(self, name, page=1)
Gets a single array value at a specific page.
Definition sdds.py:871
getParameterDatatype(self, name)
Retrieves the data type of a parameter.
Definition sdds.py:1162
int loaded_pages
Definition sdds.py:110
getArrayDimensionList(self, name, page=1)
Gets a single array dimension at a specific page.
Definition sdds.py:900
save(self, output)
Saves the SDDS object's data to an SDDS file.
Definition sdds.py:354
setColumnValueList(self, name, valueList, page=1)
Sets a single column value list at a specific page.
Definition sdds.py:969
getColumnNames(self)
Retrieves a list of all column names.
Definition sdds.py:1153
setColumnValueLists(self, name, valueList)
Sets the nested list of column values for a single column.
Definition sdds.py:929