Skip to content

read_file

phyllotaxis_analysis.read_file Link

This module contains a class and some functions to read and extract data from a csv file. We suppose that the data for each plant is stored in a column.

read_csv_file Link

read_csv_file(filename, delimiter=',')

Read a CSV file and extract integer values from its cells.

The function reads a tab-delimited CSV file, parses each cell as an integer, and returns a list of lists containing only the successfully parsed integers. Empty cells and non-integer values are skipped.

Parameters:

Name Type Description Default
filename str

Path to the CSV file to be read.

required

Returns:

Type Description
list[list[int]]

A list of lists, where each inner list contains the integers parsed from a row of the CSV file. Returns an empty list if the file is not found or cannot be read.

Raises:

Type Description
FileNotFoundError

If the specified file does not exist (handled internally; prints an error message and returns an empty list).

Exception

For other file reading errors (handled internally; prints an error message and returns an empty list).

Examples:

>>> from phyllotaxis_analysis.read_file import read_csv_file
>>> read_csv_file("data/angles.csv")
[[45, 90, 135], [30, 60, 90]]
>>> read_csv_file("nonexistent.csv")
Error: File 'nonexistent.csv' not found.
[]
Source code in src/phyllotaxis_analysis/read_file.py
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
def read_csv_file(filename: str, delimiter=',') -> list[list[int]]:
    """
    Read a CSV file and extract integer values from its cells.

    The function reads a tab-delimited CSV file, parses each cell as an integer,
    and returns a list of lists containing only the successfully parsed integers.
    Empty cells and non-integer values are skipped.

    Parameters
    ----------
    filename : str
        Path to the CSV file to be read.

    Returns
    -------
    list[list[int]]
        A list of lists, where each inner list contains the integers parsed from
        a row of the CSV file. Returns an empty list if the file is not found or
        cannot be read.

    Raises
    ------
    FileNotFoundError
        If the specified file does not exist (handled internally; prints an error
        message and returns an empty list).
    Exception
        For other file reading errors (handled internally; prints an error message
        and returns an empty list).

    Examples
    --------
    >>> from phyllotaxis_analysis.read_file import read_csv_file
    >>> read_csv_file("data/angles.csv")
    [[45, 90, 135], [30, 60, 90]]
    >>> read_csv_file("nonexistent.csv")
    Error: File 'nonexistent.csv' not found.
    []
    """
    try:
        with open(filename, 'r') as fobj:
            readerObj = csv.reader(fobj, delimiter=delimiter)
            mainList = [list(row) for row in readerObj]
            angles = []
            for row in mainList:
                current_row = []
                for angle in row:
                    if angle != "":
                        try:
                            current_row.append(int(angle))
                        except ValueError:
                            # Skip non-integer values or handle as needed
                            pass
                angles.append(current_row)
        return angles
    except FileNotFoundError:
        print(f"Error: File '{filename}' not found.")
        return []
    except Exception as e:
        print(f"Error reading file: {e}")
        return []

read_seq_file Link

read_seq_file(filename)
Read and extract data from a .seq file.

Reads a .seq file and extracts sequences of divergence angles, skipping the first 12 lines.
The file is expected to contain numerical data with specific line endings (either '' or ')')
that indicate the end of a sequence.
Parameters
filename : str
    Path to the .seq file to be read.
Returns
list[list[int]]
    A list of sequences, where each sequence is a list of integers representing divergence angles.
Raises
FileNotFoundError
    If the specified file does not exist.
IOError
    If there is an error reading the file.
Examples
>>> from phyllotaxis_analysis.read_file import read_seq_file
>>> import tempfile
>>> import os
>>>
>>> # Create a temporary example.seq file
>>> with tempfile.NamedTemporaryFile(mode='w', suffix='.seq', delete=False) as f:
>>>     f.write("10 20 30 40 50

60 70 80 90 100 ") >>> temp_filename = f.name >>> >>> try: >>> angles = read_seq_file(temp_filename) >>> if angles: >>> len(angles) >>> angles[0][:5] >>> finally: >>> os.unlink(temp_filename)

Source code in src/phyllotaxis_analysis/read_file.py
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
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
def read_seq_file(filename):
    """
    Read and extract data from a .seq file.

    Reads a .seq file and extracts sequences of divergence angles, skipping the first 12 lines.
    The file is expected to contain numerical data with specific line endings (either '' or ')')
    that indicate the end of a sequence.

    Parameters
    ----------
    filename : str
        Path to the .seq file to be read.

    Returns
    -------
    list[list[int]]
        A list of sequences, where each sequence is a list of integers representing divergence angles.

    Raises
    ------
    FileNotFoundError
        If the specified file does not exist.
    IOError
        If there is an error reading the file.

    Examples
    --------
    >>> from phyllotaxis_analysis.read_file import read_seq_file
    >>> import tempfile
    >>> import os
    >>>
    >>> # Create a temporary example.seq file
    >>> with tempfile.NamedTemporaryFile(mode='w', suffix='.seq', delete=False) as f:
    >>>     f.write("10 20 30 40 50\n60 70 80 90 100\n")
    >>>     temp_filename = f.name
    >>>
    >>> try:
    >>>     angles = read_seq_file(temp_filename)
    >>>     if angles:
    >>>         len(angles)
    >>>         angles[0][:5]
    >>> finally:
    >>>     os.unlink(temp_filename)
    """
    anglesList = []
    seq = []

    try:
        with open(filename, 'r') as fobj:
            # Skip header (first 12 lines)
            for _ in range(12):
                next(fobj, None)

            # Process data lines
            for line in fobj:
                if len(line) > 3:
                    if '\\' in line[-4:]:
                        # Line continues in next line
                        splittedLine = line[:-3].split()
                        seq.extend([int(i) for i in splittedLine])
                    elif ')' in line[-4:]:
                        # End of sequence
                        splittedLine = line[:-8].split()
                        seq.extend([int(i) for i in splittedLine])
                        anglesList.append(seq)
                        seq = []

        return anglesList

    except (FileNotFoundError, IOError) as e:
        # Re-raise with more context
        raise type(e)(f"Error reading file {filename}: {str(e)}")

read_txt_data_file Link

read_txt_data_file(filename)

Reads a text data file containing angles represented by integer values and returns a list of lists with those values.

Parameters:

Name Type Description Default
filename str

The path to the text file that will be read, including its name and file extension (e.g., 'path/to/file.txt').

required

Returns:

Type Description
list

The list of lists where each inner list contains three integer values representing angles in a line of the input text file. If there are any issues reading or parsing the file, an empty list will be returned.

Raises:

Type Description
FileNotFoundError

If the specified file does not exist.

ValueError

If the file contains non-integer values that cannot be converted.

Notes
  • Lines with non-integer values are skipped with a warning message.
  • The function returns an empty list if any error occurs during file reading or parsing.

Examples:

>>> from phyllotaxis_analysis.read_file import read_txt_data_file
>>> read_txt_data_file('data/angles.txt')
[[120, 135, 150], [110, 125, 140], [105, 120, 135]]
>>> read_txt_data_file('nonexistent.txt')
[]
>>> read_txt_data_file('invalid.txt')
Warning: Skipping line with non-integer values: 120 abc 150
[[120, 150]]
Source code in src/phyllotaxis_analysis/read_file.py
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
def read_txt_data_file(filename):
    """
    Reads a text data file containing angles represented by integer values and returns a list of lists with those values.

    Parameters
    ----------
    filename : str
        The path to the text file that will be read, including its name and file extension (e.g., 'path/to/file.txt').

    Returns
    -------
    list
        The list of lists where each inner list contains three integer values representing angles in a line of the input text file. If there are any issues reading or parsing the file, an empty list will be returned.

    Raises
    ------
    FileNotFoundError
        If the specified file does not exist.
    ValueError
        If the file contains non-integer values that cannot be converted.

    Notes
    -----
    - Lines with non-integer values are skipped with a warning message.
    - The function returns an empty list if any error occurs during file reading or parsing.

    Examples
    --------
    >>> from phyllotaxis_analysis.read_file import read_txt_data_file
    >>> read_txt_data_file('data/angles.txt')
    [[120, 135, 150], [110, 125, 140], [105, 120, 135]]
    >>> read_txt_data_file('nonexistent.txt')
    []
    >>> read_txt_data_file('invalid.txt')
    Warning: Skipping line with non-integer values: 120 abc 150
    [[120, 150]]
    """
    anglesList = []
    try:
        with open(filename, 'r') as fobj:
            for line in fobj:
                # Strip whitespace from both ends instead of just removing last char
                line = line.strip()
                if not line:  # Skip empty lines
                    continue

                lineList = line.split(' ')
                try:
                    l = [int(i) for i in lineList if i]  # Skip empty strings
                    anglesList.append(l)
                except ValueError:
                    print(f"Warning: Skipping line with non-integer values: {line}")

        return anglesList
    except FileNotFoundError:
        print(f"Error: File '{filename}' not found")
        return []
    except Exception as e:
        print(f"Error reading file '{filename}': {e}")
        return []