Skip to content

Model

Logic Backend for View, connection to sources.

ModelLogic

Originally in Control

Logic backend for view. Initialized as object by View.

Source code in src/ibl_explorer/model.py
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
450
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
class ModelLogic:
    """Logic backend for view.
    Initialized as object by View.
    """

    def __init__(self):
        self._data_sources: dict = {}
        self._selected_source: str = ""
        self.data_display = reactive({})  # Reactive attribute refreshes view when content changes
        self.one_connector = OneConnector()  # Hardcoded init of OneConnector
        self.line_diagram = LineDiagram()  # Hardcoded init of LineDiagram

    async def init_model(self) -> bool:
        """Init sources as objects in _data_sources and create default list for display.
        Throws Error when trying to initialize child class of ABC (metaclass error).

        Returns:
            bool: If initialized successful, return true.
                Switches from LoadScreen to MainScreen.
        """
        for index, cls in enumerate(DataSource.__subclasses__()):
            instance = cls()
            self._data_sources.update({cls.__name__: instance})
            if index == 0:
                self._selected_source = cls.__name__
        return True

    def display_list(self, sel_list: str, eid: str = "", collection: str = "") -> dict:
        """Connector to getDataDisplay() of sources.

        Args:
            source (str): Source.
            sel_list (str | None): Selected list.
            eid (str | None): EID.
            collection (str | None): Collection.

        Returns:
            dict: Data for DataTree
        """
        if eid is None and collection is None:
            _search = None
        elif collection is None:
            _search = eid
        elif eid is None:
            _search = collection
        else:
            _search = [eid, collection]
        return self.one_connector.getDataDisplay(sel_list, _search)

    def get_dialog(self, menu: str) -> list:
        """Information on how to build dialog.
        Information is hardcoded right now, was planned to retrieve data from selected source.

        Args:
            menu (str): Selected dialog

        Example:
            [[Name of Field, Field, Data for the Field, Description]]

        Returns:
            list: Information on how to build dialog
        """
        if menu == "search":
            return [["dataset", "input", "Enter str or [list]",
                     "Enter a (partial) dataset name. Returns sessions containing matching datasets. A dataset matches if it contains the search string e.g. 'wheel.position' matches '_ibl_wheel.position.npy'. C.f. `datasets` argument."],
                ["date_range", "input", "Enter str or [list]",
                 "Enter a single date to search or a list of 2 dates that define the range (inclusive).  To define only the upper or lower date bound, set the other element to None. Useable types: str, list, datetime.datetime, datetime.date, pandas.timestamp"]]
        elif menu == "lists":
            return [["Select List", "select", ["Datasets", "Collections", "Revisions", "Subjects"], ""],
                    ["EID", "input", "EID", "Use only with Datasets and Collections"],
                    ["Collection", "input", "Enter Collections", "Use only with Datasets and Collections"], ]
        elif menu == "dataset_settings":
            return [["Select Position", "select", ["X", "Y", "Unmark"], ""]]

    def get_description(self, desc: str) -> str:
        """Retrieve description of dataset.
        Hardcoded to OneConnector.

        Args:
            desc (str): Path of file to describe.

        Returns:
            str: Description in dict format
        """
        return self.one_connector.getDescription(desc)

    def draw_diagram(self, data: list, settings: list) -> None:
        """Draw diagram, doesn't work."""
        x = self.one_connector.getDataset("5df90bef-df4f-4850-92b4-f0e43d619a0a", "trials")
        y = self.one_connector.getDataset("63ea5aaa-1b51-4378-b515-2b6ec0502e05", "trials")
        _data = [x, y]
        _settings = settings
        self.line_diagram.getDiagram(_data, _settings)

display_list(sel_list, eid='', collection='')

Connector to getDataDisplay() of sources.

Parameters:

Name Type Description Default
source str

Source.

required
sel_list str | None

Selected list.

required
eid str | None

EID.

''
collection str | None

Collection.

''

Returns:

Name Type Description
dict dict

Data for DataTree

Source code in src/ibl_explorer/model.py
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
def display_list(self, sel_list: str, eid: str = "", collection: str = "") -> dict:
    """Connector to getDataDisplay() of sources.

    Args:
        source (str): Source.
        sel_list (str | None): Selected list.
        eid (str | None): EID.
        collection (str | None): Collection.

    Returns:
        dict: Data for DataTree
    """
    if eid is None and collection is None:
        _search = None
    elif collection is None:
        _search = eid
    elif eid is None:
        _search = collection
    else:
        _search = [eid, collection]
    return self.one_connector.getDataDisplay(sel_list, _search)

draw_diagram(data, settings)

Draw diagram, doesn't work.

Source code in src/ibl_explorer/model.py
509
510
511
512
513
514
515
def draw_diagram(self, data: list, settings: list) -> None:
    """Draw diagram, doesn't work."""
    x = self.one_connector.getDataset("5df90bef-df4f-4850-92b4-f0e43d619a0a", "trials")
    y = self.one_connector.getDataset("63ea5aaa-1b51-4378-b515-2b6ec0502e05", "trials")
    _data = [x, y]
    _settings = settings
    self.line_diagram.getDiagram(_data, _settings)

get_description(desc)

Retrieve description of dataset. Hardcoded to OneConnector.

Parameters:

Name Type Description Default
desc str

Path of file to describe.

required

Returns:

Name Type Description
str str

Description in dict format

Source code in src/ibl_explorer/model.py
497
498
499
500
501
502
503
504
505
506
507
def get_description(self, desc: str) -> str:
    """Retrieve description of dataset.
    Hardcoded to OneConnector.

    Args:
        desc (str): Path of file to describe.

    Returns:
        str: Description in dict format
    """
    return self.one_connector.getDescription(desc)

get_dialog(menu)

Information on how to build dialog. Information is hardcoded right now, was planned to retrieve data from selected source.

Parameters:

Name Type Description Default
menu str

Selected dialog

required
Example

[[Name of Field, Field, Data for the Field, Description]]

Returns:

Name Type Description
list list

Information on how to build dialog

Source code in src/ibl_explorer/model.py
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
def get_dialog(self, menu: str) -> list:
    """Information on how to build dialog.
    Information is hardcoded right now, was planned to retrieve data from selected source.

    Args:
        menu (str): Selected dialog

    Example:
        [[Name of Field, Field, Data for the Field, Description]]

    Returns:
        list: Information on how to build dialog
    """
    if menu == "search":
        return [["dataset", "input", "Enter str or [list]",
                 "Enter a (partial) dataset name. Returns sessions containing matching datasets. A dataset matches if it contains the search string e.g. 'wheel.position' matches '_ibl_wheel.position.npy'. C.f. `datasets` argument."],
            ["date_range", "input", "Enter str or [list]",
             "Enter a single date to search or a list of 2 dates that define the range (inclusive).  To define only the upper or lower date bound, set the other element to None. Useable types: str, list, datetime.datetime, datetime.date, pandas.timestamp"]]
    elif menu == "lists":
        return [["Select List", "select", ["Datasets", "Collections", "Revisions", "Subjects"], ""],
                ["EID", "input", "EID", "Use only with Datasets and Collections"],
                ["Collection", "input", "Enter Collections", "Use only with Datasets and Collections"], ]
    elif menu == "dataset_settings":
        return [["Select Position", "select", ["X", "Y", "Unmark"], ""]]

init_model() async

Init sources as objects in _data_sources and create default list for display. Throws Error when trying to initialize child class of ABC (metaclass error).

Returns:

Name Type Description
bool bool

If initialized successful, return true. Switches from LoadScreen to MainScreen.

Source code in src/ibl_explorer/model.py
435
436
437
438
439
440
441
442
443
444
445
446
447
448
async def init_model(self) -> bool:
    """Init sources as objects in _data_sources and create default list for display.
    Throws Error when trying to initialize child class of ABC (metaclass error).

    Returns:
        bool: If initialized successful, return true.
            Switches from LoadScreen to MainScreen.
    """
    for index, cls in enumerate(DataSource.__subclasses__()):
        instance = cls()
        self._data_sources.update({cls.__name__: instance})
        if index == 0:
            self._selected_source = cls.__name__
    return True

DataSource

Copied from Notebook

Interface for data sources. Was planned to be a metaclass, which inherits from ABC and uses @abstractmethod decorator.

Why an "Interface" in Python?

Since the project was planned to be as modular as possible, the Control should've been able to fetch all data sources via the interface.

Source code in src/ibl_explorer/model.py
 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
 71
 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
class DataSource:
    """Interface for data sources.
    Was planned to be a metaclass, which inherits from ABC and uses @abstractmethod decorator.


    Note: Why an "Interface" in Python?
        Since the project was planned to be as modular as possible,
        the Control should've been able to fetch all data sources via the interface.
    """
    # 0: Not initialized, 1: initialized, no Errors, 2: initialized, messages available, 3: Error while initializing
    _status = [0, ["Not initialized, initialize with \"initSource()\" "],
               "Connector for the ONE API, using the Alyx fileformat"]
    _name = ""

    def initSource(self) -> bool:
        """Initially meant to be called, when the LoadScreen was already visible.
        Writes to _status and returns a bool when finished so the load screen could show the status of initialization.

        Example:
            0: Not initialized, 1: initialized, no Errors, 2: initialized, messages available, 3: Error while initializing Description.

            self._status = [0, ["Not initialized, initialize with \"initSource()\" "], "Connector for the ONE API, using the Alyx fileformat"]

            self._status = [1, [], "Connector for the ONE API, using the Alyx fileformat"]

            self._status = [2, ["Deprecation warning: ibllib is soon to be deprecated."], "Connector for the ONE API, using the Alyx fileformat"]

            self._status = [3, ["Exception: Library XY missing", "Source could not be initialized"], "Connector for the ONE API, using the Alyx fileformat"]

        returns:
            bool: True if initialization was successful, False otherwise.
        """
        pass

    def getStatus(self) -> dict:
        """Shows status of module, executed after initSource and on info page


        Example:
            status = {
            "Code": self._status[0],
            "Messages": self._status[1],
            "Description": self._status[2],
            }

        Returns:
            dict: Dictionary with Errorcode, Message list and Source description.
        """
        pass

    def getAvailableLists(self, default: bool = False) -> [ dict | str ]:
        """Returns available lists which can be displayed and searched
        First entry is default

        Args:
            default (bool, optional): Returns default list as str.

        Returns:
            dict | str: [listName, entryType, nameOfEntry, description] | listName
        """
        pass

    def getSearchParams(self) -> dict:
        """Returns a list of parameters which can be used to search the source.

        Returns:
            dict: {Name: [parameter name, [useable types], [description]]}"""
        pass

    def getDataDisplay(self, selectedList: str, searchTerm: [str | list] = "", param: list = []) -> dict:
        """Creates displayable data from list or search request.
        Either selectedList can be used for a list request or param for a search request.
        Use getAvailableLists() for available lists or getSearchParams() for search parameters.

        Args:
            selected List (str): Indicates list or search operation, can use searchTerm.
            searchTerm (str | list, optional): Used to list and search by Term.
            param (list, optional): Uses searchTerm.

        Returns:
            dict: Data that can be parsed as a tree by View.
        """

        pass

    def getDataset(self, uuid: str, term: str) -> list:
        """Get Dataset from API with UUID
        Args:
            uuid (str): UUID
            term (str): Further specify which Dataset should be returned.

        Returns:
            list: Dataset from API
        """
        pass

getAvailableLists(default=False)

Returns available lists which can be displayed and searched First entry is default

Parameters:

Name Type Description Default
default bool

Returns default list as str.

False

Returns:

Type Description
[dict | str]

dict | str: [listName, entryType, nameOfEntry, description] | listName

Source code in src/ibl_explorer/model.py
71
72
73
74
75
76
77
78
79
80
81
def getAvailableLists(self, default: bool = False) -> [ dict | str ]:
    """Returns available lists which can be displayed and searched
    First entry is default

    Args:
        default (bool, optional): Returns default list as str.

    Returns:
        dict | str: [listName, entryType, nameOfEntry, description] | listName
    """
    pass

getDataDisplay(selectedList, searchTerm='', param=[])

Creates displayable data from list or search request. Either selectedList can be used for a list request or param for a search request. Use getAvailableLists() for available lists or getSearchParams() for search parameters.

Parameters:

Name Type Description Default
selected List (str

Indicates list or search operation, can use searchTerm.

required
searchTerm str | list

Used to list and search by Term.

''
param list

Uses searchTerm.

[]

Returns:

Name Type Description
dict dict

Data that can be parsed as a tree by View.

Source code in src/ibl_explorer/model.py
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
def getDataDisplay(self, selectedList: str, searchTerm: [str | list] = "", param: list = []) -> dict:
    """Creates displayable data from list or search request.
    Either selectedList can be used for a list request or param for a search request.
    Use getAvailableLists() for available lists or getSearchParams() for search parameters.

    Args:
        selected List (str): Indicates list or search operation, can use searchTerm.
        searchTerm (str | list, optional): Used to list and search by Term.
        param (list, optional): Uses searchTerm.

    Returns:
        dict: Data that can be parsed as a tree by View.
    """

    pass

getDataset(uuid, term)

Get Dataset from API with UUID Args: uuid (str): UUID term (str): Further specify which Dataset should be returned.

Returns:

Name Type Description
list list

Dataset from API

Source code in src/ibl_explorer/model.py
106
107
108
109
110
111
112
113
114
115
def getDataset(self, uuid: str, term: str) -> list:
    """Get Dataset from API with UUID
    Args:
        uuid (str): UUID
        term (str): Further specify which Dataset should be returned.

    Returns:
        list: Dataset from API
    """
    pass

getSearchParams()

Returns a list of parameters which can be used to search the source.

Returns:

Name Type Description
dict dict

{Name: [parameter name, [useable types], [description]]}

Source code in src/ibl_explorer/model.py
83
84
85
86
87
88
def getSearchParams(self) -> dict:
    """Returns a list of parameters which can be used to search the source.

    Returns:
        dict: {Name: [parameter name, [useable types], [description]]}"""
    pass

getStatus()

Shows status of module, executed after initSource and on info page

Example

status = { "Code": self._status[0], "Messages": self._status[1], "Description": self._status[2], }

Returns:

Name Type Description
dict dict

Dictionary with Errorcode, Message list and Source description.

Source code in src/ibl_explorer/model.py
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
def getStatus(self) -> dict:
    """Shows status of module, executed after initSource and on info page


    Example:
        status = {
        "Code": self._status[0],
        "Messages": self._status[1],
        "Description": self._status[2],
        }

    Returns:
        dict: Dictionary with Errorcode, Message list and Source description.
    """
    pass

initSource()

Initially meant to be called, when the LoadScreen was already visible. Writes to _status and returns a bool when finished so the load screen could show the status of initialization.

Example

0: Not initialized, 1: initialized, no Errors, 2: initialized, messages available, 3: Error while initializing Description.

self._status = [0, ["Not initialized, initialize with "initSource()" "], "Connector for the ONE API, using the Alyx fileformat"]

self._status = [1, [], "Connector for the ONE API, using the Alyx fileformat"]

self._status = [2, ["Deprecation warning: ibllib is soon to be deprecated."], "Connector for the ONE API, using the Alyx fileformat"]

self._status = [3, ["Exception: Library XY missing", "Source could not be initialized"], "Connector for the ONE API, using the Alyx fileformat"]

Returns:

Name Type Description
bool bool

True if initialization was successful, False otherwise.

Source code in src/ibl_explorer/model.py
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
def initSource(self) -> bool:
    """Initially meant to be called, when the LoadScreen was already visible.
    Writes to _status and returns a bool when finished so the load screen could show the status of initialization.

    Example:
        0: Not initialized, 1: initialized, no Errors, 2: initialized, messages available, 3: Error while initializing Description.

        self._status = [0, ["Not initialized, initialize with \"initSource()\" "], "Connector for the ONE API, using the Alyx fileformat"]

        self._status = [1, [], "Connector for the ONE API, using the Alyx fileformat"]

        self._status = [2, ["Deprecation warning: ibllib is soon to be deprecated."], "Connector for the ONE API, using the Alyx fileformat"]

        self._status = [3, ["Exception: Library XY missing", "Source could not be initialized"], "Connector for the ONE API, using the Alyx fileformat"]

    returns:
        bool: True if initialization was successful, False otherwise.
    """
    pass

OneConnector(DataSource)

Copied from Notebook

Bases: DataSource

Connector for the IBL ONE API.

note

See DataSource for further method description.

Source code in src/ibl_explorer/model.py
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
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
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
269
270
271
272
273
274
275
276
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
317
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
class OneConnector(DataSource):
    """Connector for the IBL ONE API.

    note:
        See DataSource for further method description.
    """
    _status = [0, ["Not initialized, initialize with \"initSource()\" "],
               "Connector for the ONE API, using the Alyx fileformat"]
    _name = "ONE API - Alyx"

    def __init__(self):
        """Initializes the class.
        Copied from init_source(), since python threw a lot of errors regarding one and ba.
        Would probably (?) work in init_source().
        Doesn't use error handling.
        """
        try:
            self._setStatus(0, "")
            # Create an instance of the OneAlyx class, specifying the base URL of the server and a password for authentication
            self.one = ONE(base_url='https://openalyx.internationalbrainlab.org', username='intbrainlab',
                           password='international', silent=False)
            self.ba = AllenAtlas()
        except Exception as e:
            print(e)

    def getStatus(self) -> dict:
        status = {"Code": self._status[0], "Messages": self._status[1], "Description": self._status[2], }
        return (status)

    def getAvailableLists(self, default: bool = False) -> dict | str:
        available = {"Datasets": ["list_datasets", [str, str], ["EID", "Collection"], ""],
            "Collections": ["list_collections", [str], ["EID"], ""],
            "Revisions": ["list_revisions", [str], ["EID"], ""], "Subjects": ["list_subjects", [], [], ""], }
        if default is True:
            out = "list_datasets"
        else:
            out = available
        return out

    def getSearchParams(self) -> dict:
        params = {'dataset': ["dataset", [str], [""],
                              "Enter a (partial) dataset name. Returns sessions containing matching datasets. A dataset matches if it contains the search string e.g. 'wheel.position' matches '_ibl_wheel.position.npy'. C.f. `datasets` argument."],
            'date_range': ["date_range", [str, list], ["", ""],
                           "Enter a single date to search or a list of 2 dates that define the range (inclusive).  To define only the upper or lower date bound, set the other element to None. Useable types: str, list, datetime.datetime, datetime.date, pandas.timestamp"],
            'laboratory': ["laboratory", [str, list], ["", ""],
                           "A str or list of lab names, returns sessions from any of these labs (can be partial, i.e. any task protocol containing that str will be found)."],
            'number': ["number", [str, int], ["", ""],
                       "Number of session to be returned, i.e. number in sequence for a given date."],
            'project': ["project", [str, list], ["", ""],
                        "The project name (can be partial, i.e. any task protocol containing that str will be found)."],
            'subject': ["subject", [str, list], ["", ""],
                        "A list of subject nicknames, returns sessions for any of these subjects (can be partial, i.e. any task protocol containing that str will be found)."],
            'task_protocol': ["task_protocol", [str, list], ["", ""],
                              "The task protocol name (can be partial, i.e. any task protocol containing that str will be found)."],
            'details': ["details", [bool], [], "Show details"]}
        return (params)

    def getDataDisplay(self, selectedList: str, searchTerm: [str | list] = "", param: [list] = []) -> dict:
        """Retrieves list or search result from API and parses the data as dict/json.

        example:
            API Data: ["a/b/c", "a", "b", "c", "a/ab/bc"]

            Returns: {selectedList: {a: {b: {c: ""}, ab: {bc: ""}}}}
        """
        def parse_data(data: list, name: str) -> dict:
            """Method that parses results as dict

            Args:
                data (list): API data to parse
                name (str): Name of data to parse

            returns:
                dict: Parsed data
            """

            def recurse(data_r: dict, txt_r: list, txt_full: str) -> dict:
                """Recursive method that builds dict

                Args:
                    data_r (dict): Dict to be filled with data
                    txt_r (list): Split string
                    txt_full (str): Preparation for additional Data in dict, not used

                returns:
                    dict: dict with additional data from txt_r
                """
                _data_r: dict = deepcopy(data_r)

                if len(txt_r) == 0:  # End recursion when list is empty
                    return _data_r

                _txt_r = txt_r[0]  # Copy current position
                new_dict: dict = {}  # Dict for return

                if len(_data_r) > 0:  # Keys in dict
                    if _txt_r in _data_r.keys():  # Key in dict
                        if len(txt_r) == 1:
                            return _data_r
                        elif type(_data_r.get(_txt_r)) is dict:
                            _data_r.update({_txt_r: recurse(_data_r.get(_txt_r), txt_r[1:], txt_full)})
                            return _data_r
                        elif type(_data_r.get(_txt_r)) is str:
                            _data_r.update({_txt_r: new_dict})
                            _data_r.update({_txt_r: recurse(_data_r.get(_txt_r), txt_r[1:], txt_full)})
                            return _data_r
                    else:  # Key not in dict
                        if len(txt_r) == 1 and type(_data_r.get(_txt_r)) is dict:
                            return _data_r
                        elif len(txt_r) == 1:
                            _data_r.update({_txt_r: ""})
                            return _data_r
                        else:
                            _data_r.update({_txt_r: new_dict})
                            _data_r.update({_txt_r: recurse(_data_r.get(_txt_r), txt_r[1:], txt_full)})
                            return _data_r
                elif len(txt_r) == 1:  # No keys in dict and list == 1
                    _data_r.update({_txt_r: ""})
                    return _data_r
                else:  # No keys and further recursion
                    _data_r.setdefault(_txt_r, new_dict)
                    _data_r.update({_txt_r: recurse(_data_r.get(_txt_r), txt_r[1:], txt_full)})
                    return _data_r

            _txt: list = data  # String from api list
            _name: str = name  # Name for tree root
            _data: dict = {_name: {}}  # dict for return

            for txt in _txt:  # Iterate over api list, split strings into lists and build dict with recurse()
                if txt.rfind("/") > 0:
                    x = txt.split("/")
                else:
                    x = [txt]
                _data[_name] = recurse(_data[_name], x, txt)
            return _data

        output = []  # Variable for api results

        print("List Operation")
        match selectedList:
            case "list_datasets":
                if type(searchTerm) is list:
                    output = self.one.list_datasets(searchTerm[0], searchTerm[1])
                elif type(searchTerm) is str:
                    output = self.one.list_datasets(searchTerm)
                else:
                    output = self.one.list_datasets()
            case "list_collections":
                if searchTerm is str:
                    output = self.one.list_collections(searchTerm)
                else:
                    output = self.one.list_collections()
            case "list_revisions":
                if searchTerm is str:
                    output = self.one.list_revisions(searchTerm)
                else:
                    output = self.one.list_revisions()
            case "list_subjects":
                output = self.one.list_subjects()
            case "search":
                print("Search Operation")
                string = ""
                if type(param) is str:
                    param = [param]
                for search in param:
                    print(search)
                    if search[0] == "details":
                        string += str("details=" + search[1])
                    else:
                        string += str(search[0] + "=\'" + search[1] + "\'")
                print(string)
                output = self.one.search(string)

        return parse_data(output, selectedList)  # Parse api results as dict and return

    def getDescription(self, path: str) -> str:
        try:
            out = self.one.describe_dataset(path)
        except Exception as e:
            out = "Not found: " + str(e)
        return out

    def getDataset(self, uuid: str, term: str) -> list:
        """Get Dataset from API with UUID
        Args:
            uuid (str): UUID

        Returns:
            list: Dataset from API
        """
        rdata, info = self.one.load_object(uuid, term)
        data = rdata
        return (data)

    def _setStatus(self, state: int, message: str | None = None) -> None:
        """Internal status method.

        If state == 0, new initialization, clear messages.

        If state == 1, initialization without errors, messages cleared.

        If state == 2, status == 1, message appended.

        If state == 3, there is an error, message is appended to status messages.


        Args:
            state (int): Status code.
            message (str | None): Messages.
        """
        match int(state):
            # If state == 0, new initialization, clear messages
            case 0:
                self._status[0] = 0
                self._status[1].clear()
            # If state == 1, initialization without errors, messages cleared
            case 1:
                self._status[0] = 1
                self._status[1].clear()
            # If state == 2, status == 1, message appended
            case 2:
                self._status[0] = 1
                if message != "": self._status[1].append(message)
            # If state == 3, there is an error
            # Errorcode == 3, message is appended to status messages
            case 3:
                self._status[0] = 3
                if message != "": self._status[1].append(message)

__init__()

Initializes the class. Copied from init_source(), since python threw a lot of errors regarding one and ba. Would probably (?) work in init_source(). Doesn't use error handling.

Source code in src/ibl_explorer/model.py
128
129
130
131
132
133
134
135
136
137
138
139
140
141
def __init__(self):
    """Initializes the class.
    Copied from init_source(), since python threw a lot of errors regarding one and ba.
    Would probably (?) work in init_source().
    Doesn't use error handling.
    """
    try:
        self._setStatus(0, "")
        # Create an instance of the OneAlyx class, specifying the base URL of the server and a password for authentication
        self.one = ONE(base_url='https://openalyx.internationalbrainlab.org', username='intbrainlab',
                       password='international', silent=False)
        self.ba = AllenAtlas()
    except Exception as e:
        print(e)

getDataDisplay(selectedList, searchTerm='', param=[])

Retrieves list or search result from API and parses the data as dict/json.

example

API Data: ["a/b/c", "a", "b", "c", "a/ab/bc"]

Returns: {selectedList: {a: {b: {c: ""}, ab: {bc: ""}}}}

Source code in src/ibl_explorer/model.py
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
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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
def getDataDisplay(self, selectedList: str, searchTerm: [str | list] = "", param: [list] = []) -> dict:
    """Retrieves list or search result from API and parses the data as dict/json.

    example:
        API Data: ["a/b/c", "a", "b", "c", "a/ab/bc"]

        Returns: {selectedList: {a: {b: {c: ""}, ab: {bc: ""}}}}
    """
    def parse_data(data: list, name: str) -> dict:
        """Method that parses results as dict

        Args:
            data (list): API data to parse
            name (str): Name of data to parse

        returns:
            dict: Parsed data
        """

        def recurse(data_r: dict, txt_r: list, txt_full: str) -> dict:
            """Recursive method that builds dict

            Args:
                data_r (dict): Dict to be filled with data
                txt_r (list): Split string
                txt_full (str): Preparation for additional Data in dict, not used

            returns:
                dict: dict with additional data from txt_r
            """
            _data_r: dict = deepcopy(data_r)

            if len(txt_r) == 0:  # End recursion when list is empty
                return _data_r

            _txt_r = txt_r[0]  # Copy current position
            new_dict: dict = {}  # Dict for return

            if len(_data_r) > 0:  # Keys in dict
                if _txt_r in _data_r.keys():  # Key in dict
                    if len(txt_r) == 1:
                        return _data_r
                    elif type(_data_r.get(_txt_r)) is dict:
                        _data_r.update({_txt_r: recurse(_data_r.get(_txt_r), txt_r[1:], txt_full)})
                        return _data_r
                    elif type(_data_r.get(_txt_r)) is str:
                        _data_r.update({_txt_r: new_dict})
                        _data_r.update({_txt_r: recurse(_data_r.get(_txt_r), txt_r[1:], txt_full)})
                        return _data_r
                else:  # Key not in dict
                    if len(txt_r) == 1 and type(_data_r.get(_txt_r)) is dict:
                        return _data_r
                    elif len(txt_r) == 1:
                        _data_r.update({_txt_r: ""})
                        return _data_r
                    else:
                        _data_r.update({_txt_r: new_dict})
                        _data_r.update({_txt_r: recurse(_data_r.get(_txt_r), txt_r[1:], txt_full)})
                        return _data_r
            elif len(txt_r) == 1:  # No keys in dict and list == 1
                _data_r.update({_txt_r: ""})
                return _data_r
            else:  # No keys and further recursion
                _data_r.setdefault(_txt_r, new_dict)
                _data_r.update({_txt_r: recurse(_data_r.get(_txt_r), txt_r[1:], txt_full)})
                return _data_r

        _txt: list = data  # String from api list
        _name: str = name  # Name for tree root
        _data: dict = {_name: {}}  # dict for return

        for txt in _txt:  # Iterate over api list, split strings into lists and build dict with recurse()
            if txt.rfind("/") > 0:
                x = txt.split("/")
            else:
                x = [txt]
            _data[_name] = recurse(_data[_name], x, txt)
        return _data

    output = []  # Variable for api results

    print("List Operation")
    match selectedList:
        case "list_datasets":
            if type(searchTerm) is list:
                output = self.one.list_datasets(searchTerm[0], searchTerm[1])
            elif type(searchTerm) is str:
                output = self.one.list_datasets(searchTerm)
            else:
                output = self.one.list_datasets()
        case "list_collections":
            if searchTerm is str:
                output = self.one.list_collections(searchTerm)
            else:
                output = self.one.list_collections()
        case "list_revisions":
            if searchTerm is str:
                output = self.one.list_revisions(searchTerm)
            else:
                output = self.one.list_revisions()
        case "list_subjects":
            output = self.one.list_subjects()
        case "search":
            print("Search Operation")
            string = ""
            if type(param) is str:
                param = [param]
            for search in param:
                print(search)
                if search[0] == "details":
                    string += str("details=" + search[1])
                else:
                    string += str(search[0] + "=\'" + search[1] + "\'")
            print(string)
            output = self.one.search(string)

    return parse_data(output, selectedList)  # Parse api results as dict and return

getDataset(uuid, term)

Get Dataset from API with UUID Args: uuid (str): UUID

Returns:

Name Type Description
list list

Dataset from API

Source code in src/ibl_explorer/model.py
300
301
302
303
304
305
306
307
308
309
310
def getDataset(self, uuid: str, term: str) -> list:
    """Get Dataset from API with UUID
    Args:
        uuid (str): UUID

    Returns:
        list: Dataset from API
    """
    rdata, info = self.one.load_object(uuid, term)
    data = rdata
    return (data)

initSource()

Initially meant to be called, when the LoadScreen was already visible. Writes to _status and returns a bool when finished so the load screen could show the status of initialization.

Example

0: Not initialized, 1: initialized, no Errors, 2: initialized, messages available, 3: Error while initializing Description.

self._status = [0, ["Not initialized, initialize with "initSource()" "], "Connector for the ONE API, using the Alyx fileformat"]

self._status = [1, [], "Connector for the ONE API, using the Alyx fileformat"]

self._status = [2, ["Deprecation warning: ibllib is soon to be deprecated."], "Connector for the ONE API, using the Alyx fileformat"]

self._status = [3, ["Exception: Library XY missing", "Source could not be initialized"], "Connector for the ONE API, using the Alyx fileformat"]

Returns:

Name Type Description
bool bool

True if initialization was successful, False otherwise.

Source code in src/ibl_explorer/model.py
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
def initSource(self) -> bool:
    """Initially meant to be called, when the LoadScreen was already visible.
    Writes to _status and returns a bool when finished so the load screen could show the status of initialization.

    Example:
        0: Not initialized, 1: initialized, no Errors, 2: initialized, messages available, 3: Error while initializing Description.

        self._status = [0, ["Not initialized, initialize with \"initSource()\" "], "Connector for the ONE API, using the Alyx fileformat"]

        self._status = [1, [], "Connector for the ONE API, using the Alyx fileformat"]

        self._status = [2, ["Deprecation warning: ibllib is soon to be deprecated."], "Connector for the ONE API, using the Alyx fileformat"]

        self._status = [3, ["Exception: Library XY missing", "Source could not be initialized"], "Connector for the ONE API, using the Alyx fileformat"]

    returns:
        bool: True if initialization was successful, False otherwise.
    """
    pass

DiagramSource

Copied from Notebook

Source code in src/ibl_explorer/model.py
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
class DiagramSource:
    _name = ""
    _description = ""
    _requirements = []
    _settings = []

    def __init__(self):
        # Test if needed modules are available
        pass

    def getDescription(self) -> str:
        """Get description of diagram

        returns:
            str: Description
        """
        description = self._desc
        return (description)

    def getRequirements(self) -> list:
        # What data is needed for diagram
        requirements = self._requirements
        return (requirements)

    def getSettings(self) -> list:
        """Available settings for diagram

        returns:
            list: Available settings for diagram
        """
        settings = self._settings
        return (settings)

    def getDiagram(self, data: list, settings: list) -> None:
        """Create diagram with data and settings
        Should open a window with the diagram.

        args:
            data (list): Data
            settings (list): Settings
        """
        raise Exception("Method getDiagram not implemented.")
        pass

    def testDataset(self) -> list:
        """Dataset for test"""
        raise Exception("Method testDataset not implemented.")
        pass

getDescription()

Get description of diagram

Returns:

Name Type Description
str str

Description

Source code in src/ibl_explorer/model.py
359
360
361
362
363
364
365
366
def getDescription(self) -> str:
    """Get description of diagram

    returns:
        str: Description
    """
    description = self._desc
    return (description)

getDiagram(data, settings)

Create diagram with data and settings Should open a window with the diagram.

Parameters:

Name Type Description Default
data list

Data

required
settings list

Settings

required
Source code in src/ibl_explorer/model.py
382
383
384
385
386
387
388
389
390
391
def getDiagram(self, data: list, settings: list) -> None:
    """Create diagram with data and settings
    Should open a window with the diagram.

    args:
        data (list): Data
        settings (list): Settings
    """
    raise Exception("Method getDiagram not implemented.")
    pass

getSettings()

Available settings for diagram

Returns:

Name Type Description
list list

Available settings for diagram

Source code in src/ibl_explorer/model.py
373
374
375
376
377
378
379
380
def getSettings(self) -> list:
    """Available settings for diagram

    returns:
        list: Available settings for diagram
    """
    settings = self._settings
    return (settings)

testDataset()

Dataset for test

Source code in src/ibl_explorer/model.py
393
394
395
396
def testDataset(self) -> list:
    """Dataset for test"""
    raise Exception("Method testDataset not implemented.")
    pass

LineDiagram(DiagramSource)

Copied from Notebook

Bases: DiagramSource

Source code in src/ibl_explorer/model.py
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
class LineDiagram(DiagramSource):
    _name = "Line Diagram"
    _desc = "Simple two-axis line diagram."
    _requirements = [list, list]
    _settings = ["title", "xlabel", "ylabel", "color"]

    def getDiagram(self, data: list, settings: list):
        # Create diagram with data and settings
        plt.title(settings[0])
        plt.xlabel(settings[1])
        plt.ylabel(settings[2])
        plt.plot(data[0], data[1], color=settings[3])
        plt.show()

    def testDataset(self) -> list:
        # Dataset for test
        x = np.arange(1, 11)
        y = x * x
        out = [x, y]
        return (out)

getDescription()

Get description of diagram

Returns:

Name Type Description
str str

Description

Source code in src/ibl_explorer/model.py
359
360
361
362
363
364
365
366
def getDescription(self) -> str:
    """Get description of diagram

    returns:
        str: Description
    """
    description = self._desc
    return (description)

getSettings()

Available settings for diagram

Returns:

Name Type Description
list list

Available settings for diagram

Source code in src/ibl_explorer/model.py
373
374
375
376
377
378
379
380
def getSettings(self) -> list:
    """Available settings for diagram

    returns:
        list: Available settings for diagram
    """
    settings = self._settings
    return (settings)