Skip to content

base

Abstract reader to parse various inputs into neurons.

Any subclass should implement at least one of read_buffer or read_dataframe.

PARAMETER DESCRIPTION
fmt
        A string describing how to parse filenames into neuron
        properties. For example '{id}.swc'.

TYPE: str

file_ext
        The file extension to look for when searching folders.
        For example '.swc'. Alternatively, you can re-implement
        the `is_valid_file` method for more complex filters. That
        method needs to be able to deal with: Path objects, ZipInfo
        objects and strings.

TYPE: str

name_fallback
        Fallback for name when reading from e.g. string.

TYPE: str DEFAULT: 'NA'

attrs
        Additional attributes to use when creating the neuron.
        Will be overwritten by later additions (e.g. from `fmt`).

TYPE: dict DEFAULT: None

ignore_hidden
        Whether to ignore files that start with "._".

TYPE: bool DEFAULT: True

Source code in navis/io/base.py
 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
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 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
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
class BaseReader(ABC):
    """Abstract reader to parse various inputs into neurons.

    Any subclass should implement at least one of `read_buffer` or
    `read_dataframe`.

    Parameters
    ----------
    fmt :           str
                    A string describing how to parse filenames into neuron
                    properties. For example '{id}.swc'.
    file_ext :      str
                    The file extension to look for when searching folders.
                    For example '.swc'. Alternatively, you can re-implement
                    the `is_valid_file` method for more complex filters. That
                    method needs to be able to deal with: Path objects, ZipInfo
                    objects and strings.
    name_fallback : str
                    Fallback for name when reading from e.g. string.
    attrs :         dict
                    Additional attributes to use when creating the neuron.
                    Will be overwritten by later additions (e.g. from `fmt`).
    ignore_hidden : bool
                    Whether to ignore files that start with "._".
    """

    def __init__(
        self,
        fmt: str,
        file_ext: str,
        name_fallback: str = "NA",
        read_binary: bool = False,
        attrs: Optional[Dict[str, Any]] = None,
        ignore_hidden=True,
    ):
        self.attrs = attrs
        self.fmt = fmt
        self.file_ext = file_ext
        self.name_fallback = name_fallback
        self.read_binary = read_binary
        self.ignore_hidden = ignore_hidden

        if self.file_ext.startswith("*"):
            raise ValueError('File extension must be ".ext", not "*.ext"')

    def files_in_dir(
        self, dpath: Path, include_subdirs: bool = DEFAULT_INCLUDE_SUBDIRS
    ) -> Iterable[Path]:
        """List files to read in directory."""
        if not isinstance(dpath, Path):
            dpath = Path(dpath)
        dpath = dpath.expanduser()
        pattern = "*"
        if include_subdirs:
            pattern = os.path.join("**", pattern)

        yield from (f for f in dpath.glob(pattern) if self.is_valid_file(f))

    def is_valid_file(self, file):
        """Return true if file should be considered for reading."""
        if isinstance(file, ZipInfo):
            file = file.filename
        elif isinstance(file, tarfile.TarInfo):
            file = file.name
        elif isinstance(file, Path):
            file = file.name

        if self.ignore_hidden and str(file).startswith("._"):
            return False

        if str(file).endswith(self.file_ext):
            return True
        return False

    def _make_attributes(
        self, *dicts: Optional[Dict[str, Any]], **kwargs
    ) -> Dict[str, Any]:
        """Combine attributes with a timestamp and those defined on the object.

        Later additions take precedence:

        - created_at (now)
        - object-defined attributes
        - additional dicts given as *args
        - additional attributes given as **kwargs

        Returns
        -------
        Dict[str, Any]
            Arbitrary string-keyed attributes.
        """
        return merge_dicts(
            dict(created_at=str(datetime.datetime.now())),
            self.attrs,
            *dicts,
            **kwargs,
        )

    def read_buffer(
        self, f: IO, attrs: Optional[Dict[str, Any]] = None
    ) -> "core.BaseNeuron":
        """Read buffer into a single neuron.

        Parameters
        ----------
        f :         IO
                    Readable buffer.
        attrs :     dict | None
                    Arbitrary attributes to include in the neuron.

        Returns
        -------
        core.NeuronObject
        """
        raise NotImplementedError(
            "Reading from buffer not implemented for " f"{type(self)}"
        )

    def read_file_path(
        self, fpath: os.PathLike, attrs: Optional[Dict[str, Any]] = None
    ) -> "core.BaseNeuron":
        """Read single file from path into a neuron.

        Parameters
        ----------
        fpath :     str | os.PathLike
                    Path to files.
        attrs :     dict or None
                    Arbitrary attributes to include in the neuron.

        Returns
        -------
        core.BaseNeuron
        """
        p = Path(fpath)
        with open(p, "rb" if self.read_binary else "r") as f:
            try:
                props = self.parse_filename(f.name)
                props["origin"] = str(p)
                return self.read_buffer(f, merge_dicts(props, attrs))
            except BaseException as e:
                raise ValueError(f"Error reading file {p}") from e

    def read_from_zip(
        self,
        files: Union[str, List[str]],
        zippath: os.PathLike,
        attrs: Optional[Dict[str, Any]] = None,
        on_error: Union[Literal["ignore", Literal["raise"]]] = "ignore",
    ) -> "core.NeuronList":
        """Read given files from a zip into a NeuronList.

        Typically not used directly but via `read_zip()` dispatcher.

        Parameters
        ----------
        files :     zipfile.ZipInfo | list thereof
                    Files inside the ZIP file to read.
        zippath :   str | os.PathLike
                    Path to zip file.
        attrs :     dict or None
                    Arbitrary attributes to include in the TreeNeuron.
        on_error :  'ignore' | 'raise'
                    What do do when error is encountered.

        Returns
        -------
        core.NeuronList

        """
        p = Path(zippath)
        files = utils.make_iterable(files)

        neurons = []
        with ZipFile(p, "r") as zip:
            for file in files:
                # Note the `file` is of type zipfile.ZipInfo here
                props = self.parse_filename(file.orig_filename)
                props["origin"] = str(p)
                try:
                    n = self.read_bytes(zip.read(file), merge_dicts(props, attrs))
                    neurons.append(n)
                except BaseException:
                    if on_error == "ignore":
                        logger.warning(f'Failed to read "{file.filename}" from zip.')
                    else:
                        raise

        return core.NeuronList(neurons)

    def read_zip(
        self,
        fpath: os.PathLike,
        parallel="auto",
        limit: Optional[int] = None,
        attrs: Optional[Dict[str, Any]] = None,
        on_error: Union[Literal["ignore", Literal["raise"]]] = "ignore",
    ) -> "core.NeuronList":
        """Read files from a zip into a NeuronList.

        This is a dispatcher for `.read_from_zip`.

        Parameters
        ----------
        fpath :     str | os.PathLike
                    Path to zip file.
        limit :     int, optional
                    Limit the number of files read from this directory.
        attrs :     dict or None
                    Arbitrary attributes to include in the TreeNeuron.
        on_error :  'ignore' | 'raise'
                    What do do when error is encountered.

        Returns
        -------
        core.NeuronList

        """
        fpath = Path(fpath).expanduser()
        read_fn = partial(
            self.read_from_zip, zippath=fpath, attrs=attrs, on_error=on_error
        )
        neurons = parallel_read_archive(
            read_fn=read_fn,
            fpath=fpath,
            file_ext=self.is_valid_file,
            limit=limit,
            parallel=parallel,
        )
        return core.NeuronList(neurons)

    def read_from_tar(
        self,
        files: Union[str, List[str]],
        tarpath: os.PathLike,
        attrs: Optional[Dict[str, Any]] = None,
        on_error: Union[Literal["ignore", Literal["raise"]]] = "ignore",
    ) -> "core.NeuronList":
        """Read given files from a tar into a NeuronList.

        Typically not used directly but via `read_tar()` dispatcher.

        Parameters
        ----------
        files :     tarfile.TarInfo | list thereof
                    Files inside the tar file to read.
        tarpath :   str | os.PathLike
                    Path to tar file.
        attrs :     dict or None
                    Arbitrary attributes to include in the TreeNeuron.
        on_error :  'ignore' | 'raise'
                    What do do when error is encountered.

        Returns
        -------
        core.NeuronList

        """
        p = Path(tarpath)
        files = utils.make_iterable(files)

        neurons = []
        with tarfile.open(p, "r") as tf:
            for file in files:
                # Note the `file` is of type tarfile.TarInfo here
                props = self.parse_filename(file.name.split("/")[-1])
                props["origin"] = str(p)
                try:
                    n = self.read_bytes(
                        tf.extractfile(file).read(), merge_dicts(props, attrs)
                    )
                    neurons.append(n)
                except BaseException:
                    if on_error == "ignore":
                        logger.warning(f'Failed to read "{file.filename}" from tar.')
                    else:
                        raise

        return core.NeuronList(neurons)

    def read_tar(
        self,
        fpath: os.PathLike,
        parallel="auto",
        limit: Optional[int] = None,
        attrs: Optional[Dict[str, Any]] = None,
        on_error: Union[Literal["ignore", Literal["raise"]]] = "ignore",
    ) -> "core.NeuronList":
        """Read files from a tar archive into a NeuronList.

        This is a dispatcher for `.read_from_tar`.

        Parameters
        ----------
        fpath :     str | os.PathLike
                    Path to tar file.
        limit :     int, optional
                    Limit the number of files read from this directory.
        attrs :     dict or None
                    Arbitrary attributes to include in the TreeNeuron.
        on_error :  'ignore' | 'raise'
                    What do do when error is encountered.

        Returns
        -------
        core.NeuronList

        """
        fpath = Path(fpath).expanduser()
        read_fn = partial(
            self.read_from_tar, tarpath=fpath, attrs=attrs, on_error=on_error
        )
        neurons = parallel_read_archive(
            read_fn=read_fn,
            fpath=fpath,
            file_ext=self.is_valid_file,
            limit=limit,
            parallel=parallel,
        )
        return core.NeuronList(neurons)

    def read_ftp(
        self,
        url,
        parallel="auto",
        limit: Optional[int] = None,
        attrs: Optional[Dict[str, Any]] = None,
        on_error: Union[Literal["ignore", Literal["raise"]]] = "ignore",
    ) -> "core.NeuronList":
        """Read files from an FTP server.

        This is a dispatcher for `.read_from_ftp`.

        Parameters
        ----------
        url :       str
                    Can be the path to a single file or a directory.
        limit :     int, optional
                    Limit the number of files read from this directory.
        attrs :     dict or None
                    Arbitrary attributes to include in the TreeNeuron.
        on_error :  'ignore' | 'raise'
                    What do do when error is encountered.

        Returns
        -------
        core.NeuronList

        """
        # Remove the ftp:// prefix
        url = url.replace("ftp://", "")

        # Split into server and path
        server, path = url.split("/", 1)

        # Check if server contains a port
        if ":" in server:
            server, port = server.split(":")
            port = int(port)
        else:
            port = 21  # default port

        read_fn = partial(self.read_from_ftp, attrs=attrs, on_error=on_error)
        neurons = parallel_read_ftp(
            read_fn=read_fn,
            server=server,
            port=port,
            path=path,
            file_ext=self.is_valid_file,
            limit=limit,
            parallel=parallel,
        )
        return core.NeuronList(neurons)

    def read_from_ftp(
        self,
        files: Union[str, List[str]],
        ftp: FTP,
        attrs: Optional[Dict[str, Any]] = None,
        on_error: Union[Literal["ignore", Literal["raise"]]] = "ignore",
    ) -> "core.NeuronList":
        """Read given files from an FTP server into a NeuronList.

        Typically not used directly but via `read_ftp()` dispatcher.

        Parameters
        ----------
        files :     tarfile.TarInfo | list thereof
                    Files inside the tar file to read.
        ftp :       ftplib.FTP | "GLOBAL"
                    The FTP client. This should already be connected, logged in
                    and in the correct directory. If "GLOBAL", we will look for a
                    `_FTP` global variable.
        attrs :     dict or None
                    Arbitrary attributes to include in the TreeNeuron.
        on_error :  'ignore' | 'raise'
                    What do do when error is encountered.

        Returns
        -------
        core.NeuronList

        """
        # When reading in parallel, we expect there to be a global FTP connection
        # that was initialized once for each worker process.
        if ftp == "GLOBAL":
            if "_FTP" not in globals():
                raise ValueError("No global FTP connection found.")
            ftp = _FTP

        files = utils.make_iterable(files)

        neurons = []
        for file in files:
            # Read the file into a bytes
            with io.BytesIO() as f:
                ftp.retrbinary("RETR " + file, f.write)
                f.seek(0)
                props = self.parse_filename(file)
                props["origin"] = f"{ftp.host}:{ftp.port}{ftp.pwd()}/{file}"
                try:
                    n = self.read_buffer(f, merge_dicts(props, attrs))
                    neurons.append(n)
                except BaseException:
                    if on_error == "ignore":
                        logger.warning(f'Failed to read "{file}" from FTP.')
                    else:
                        raise

        return core.NeuronList(neurons)

    def read_directory(
        self,
        path: os.PathLike,
        include_subdirs=DEFAULT_INCLUDE_SUBDIRS,
        parallel="auto",
        limit: Optional[int] = None,
        attrs: Optional[Dict[str, Any]] = None,
    ) -> "core.NeuronList":
        """Read directory of files into a NeuronList.

        Parameters
        ----------
        fpath :             str | os.PathLike
                            Path to directory containing files.
        include_subdirs :   bool, optional
                            Whether to descend into subdirectories, default False.
        parallel :          str | bool | "auto"
        limit :             int, optional
                            Limit the number of files read from this directory.
        attrs :             dict or None
                            Arbitrary attributes to include in the TreeNeurons
                            of the NeuronList

        Returns
        -------
        core.NeuronList
        """
        files = list(self.files_in_dir(Path(path), include_subdirs))

        if isinstance(limit, int):
            files = files[:limit]
        elif isinstance(limit, list):
            files = [f for f in files if f in limit]
        elif isinstance(limit, slice):
            files = files[limit]
        elif isinstance(limit, str):
            # Check if limit is a regex
            if rgx.search(limit):
                files = [f for f in files if re.search(limit, str(f.name))]
            else:
                files = [f for f in files if limit in str(f)]

        read_fn = partial(self.read_file_path, attrs=attrs)
        neurons = parallel_read(read_fn, files, parallel)
        return core.NeuronList(neurons)

    def read_url(
        self, url: str, attrs: Optional[Dict[str, Any]] = None
    ) -> "core.BaseNeuron":
        """Read file from URL into a neuron.

        Parameters
        ----------
        url :       str
                    URL to file.
        attrs :     dict or None
                    Arbitrary attributes to include in the neuron.

        Returns
        -------
        core.BaseNeuron
        """
        # Note: originally, we used stream=True and passed `r.raw` to the
        # read_buffer function but that caused issue when there was more
        # than one chunk which would require us to concatenate the chunks
        # `via r.raw.iter_content()`.
        # Instead, we will simply read the whole content, wrap it in a BytesIO
        # and pass that to the read_buffer function. This is not ideal as it
        # will load the whole file into memory while the streaming solution
        # may have raised an exception earlier if the file was corrupted or
        # the wrong format.
        with requests.get(url, stream=False) as r:
            r.raise_for_status()
            props = self.parse_filename(url.split("/")[-1])
            props["origin"] = url
            return self.read_buffer(io.BytesIO(r.content), merge_dicts(props, attrs))

    def read_string(
        self, s: str, attrs: Optional[Dict[str, Any]] = None
    ) -> "core.BaseNeuron":
        """Read single string into a Neuron.

        Parameters
        ----------
        s :         str
                    String.
        attrs :     dict or None
                    Arbitrary attributes to include in the neuron.

        Returns
        -------
        core.BaseNeuron
        """
        sio = io.StringIO(s)
        return self.read_buffer(
            sio, merge_dicts({"name": self.name_fallback, "origin": "string"}, attrs)
        )

    def read_bytes(
        self, s: str, attrs: Optional[Dict[str, Any]] = None
    ) -> "core.BaseNeuron":
        """Read bytes into a Neuron.

        Parameters
        ----------
        s :         bytes
                    Bytes.
        attrs :     dict or None
                    Arbitrary attributes to include in the neuron.

        Returns
        -------
        core.BaseNeuron
        """
        sio = io.BytesIO(s)
        return self.read_buffer(
            sio, merge_dicts({"name": self.name_fallback, "origin": "string"}, attrs)
        )

    def read_dataframe(
        self, nodes: pd.DataFrame, attrs: Optional[Dict[str, Any]] = None
    ) -> "core.BaseNeuron":
        """Convert a DataFrame into a neuron.

        Parameters
        ----------
        nodes :     pandas.DataFrame
        attrs :     dict or None
                    Arbitrary attributes to include in the neuron.

        Returns
        -------
        core.BaseNeuron
        """
        raise NotImplementedError(
            "Reading DataFrames not implemented for " f"{type(self)}"
        )

    def read_any_single(
        self, obj, attrs: Optional[Dict[str, Any]] = None
    ) -> "core.BaseNeuron":
        """Attempt to convert an arbitrary object into a neuron.

        Parameters
        ----------
        obj :       typing.IO | pandas.DataFrame | str | os.PathLike
                    Readable buffer, dataframe, path or URL to single file,
                    or parsable string.
        attrs :     dict or None
                    Arbitrary attributes to include in the neuron.

        Returns
        -------
        core.BaseNeuron
        """
        if hasattr(obj, "read"):
            return self.read_buffer(obj, attrs)
        if isinstance(obj, pd.DataFrame):
            return self.read_dataframe(obj, attrs)
        if isinstance(obj, os.PathLike):
            if str(obj).endswith(".zip"):
                return self.read_zip(obj, attrs=attrs)
            elif ".tar" in str(obj):
                return self.read_tar(obj, attrs=attrs)
            return self.read_file_path(obj, attrs)
        if isinstance(obj, str):
            # See if this might be a file (make sure to expand user)
            if os.path.isfile(os.path.expanduser(obj)):
                p = Path(obj).expanduser()
                if p.suffix == ".zip":
                    return self.read_zip(p, attrs=attrs)
                return self.read_file_path(p, attrs)
            if obj.startswith("http://") or obj.startswith("https://"):
                return self.read_url(obj, attrs)
            if obj.startswith("ftp://"):
                return self.read_ftp(obj, attrs=attrs)
            return self.read_string(obj, attrs)
        if isinstance(obj, bytes):
            return self.read_bytes(obj, attrs)
        raise ValueError(f"Could not read neuron from object of type '{type(obj)}'")

    def read_any_multi(
        self,
        objs,
        include_subdirs=DEFAULT_INCLUDE_SUBDIRS,
        parallel="auto",
        attrs: Optional[Dict[str, Any]] = None,
    ) -> "core.NeuronList":
        """Attempt to convert an arbitrary object into a NeuronList,
        potentially in parallel.

        Parameters
        ----------
        obj :               sequence
                            Sequence of anything readable by read_any_single or
                            directory path(s).
        include_subdirs :   bool
                            Whether to include subdirectories of a given
                            directory.
        parallel :          str | bool | int | None
                            "auto" or True for n_cores // 2, otherwise int for
                            number of jobs, or False for serial.
        attrs :             dict or None
                            Arbitrary attributes to include in each TreeNeuron
                            of the NeuronList.

        Returns
        -------
        core.NeuronList

        """
        if not utils.is_iterable(objs):
            objs = [objs]

        if not objs:
            logger.warning("No files found, returning empty NeuronList")
            return core.NeuronList([])

        new_objs = []
        for obj in objs:
            try:
                if os.path.isdir(os.path.expanduser(obj)):
                    new_objs.extend(self.files_in_dir(obj, include_subdirs))
                    continue
            except TypeError:
                pass
            new_objs.append(obj)

        if (
            isinstance(parallel, str)
            and parallel.lower() == "auto"
            and len(new_objs) < 200
        ):
            parallel = False

        read_fn = partial(self.read_any_single, attrs=attrs)
        neurons = parallel_read(read_fn, new_objs, parallel)
        return core.NeuronList(neurons)

    def read_any(
        self,
        obj,
        include_subdirs=DEFAULT_INCLUDE_SUBDIRS,
        parallel="auto",
        limit=None,
        attrs: Optional[Dict[str, Any]] = None,
    ) -> "core.NeuronObject":
        """Attempt to read an arbitrary object into a neuron.

        Parameters
        ----------
        obj :       typing.IO | str | os.PathLike | pandas.DataFrame
                    Buffer, path to file or directory, URL, string, or
                    dataframe.

        Returns
        -------
        core.NeuronObject
        """
        if utils.is_iterable(obj) and not hasattr(obj, "read"):
            return self.read_any_multi(obj, parallel, include_subdirs, attrs)
        else:
            try:
                if os.path.isdir(os.path.expanduser(obj)):
                    return self.read_directory(
                        obj, include_subdirs, parallel, limit, attrs
                    )
            except TypeError:
                pass
            try:
                if os.path.isfile(os.path.expanduser(obj)) and str(obj).endswith(
                    ".zip"
                ):
                    return self.read_zip(obj, parallel, limit, attrs)
                if os.path.isfile(os.path.expanduser(obj)) and ".tar" in str(obj):
                    return self.read_tar(obj, parallel, limit, attrs)
                if isinstance(obj, str) and obj.startswith("ftp://"):
                    return self.read_ftp(obj, parallel, limit, attrs)
            except TypeError:
                pass
            return self.read_any_single(obj, attrs)

    def parse_filename(self, filename: str) -> dict:
        """Extract properties from filename according to specified formatter.

        Parameters
        ----------
        filename : str

        Returns
        -------
        props :     dict
                    Properties extracted from filename.

        """
        # Make sure we are working with the filename not the whole path
        filename = Path(filename).name

        # Escape all special characters
        fmt = re.escape(self.fmt)

        # Unescape { and }
        fmt = fmt.replace("\\{", "{").replace("\\}", "}")

        # Replace all e.g. {name} with {.*}
        prop_names = []
        for prop in re.findall("{.*?}", fmt):
            prop_names.append(prop[1:-1].replace(" ", ""))
            fmt = fmt.replace(prop, "(.*)")

        # Match
        match = re.search(fmt, filename)

        if not match:
            raise ValueError(f'Unable to match "{self.fmt}" to filename "{filename}"')

        props = {"file": filename}
        for i, prop in enumerate(prop_names):
            for p in prop.split(","):
                # Ignore empty ("{}")
                if not p:
                    continue

                # If datatype was specified
                if ":" in p:
                    p, dt = p.split(":")

                    props[p] = match.group(i + 1)

                    if dt == "int":
                        props[p] = int(props[p])
                    elif dt == "float":
                        props[p] = float(props[p])
                    elif dt == "bool":
                        props[p] = bool(props[p])
                    elif dt == "str":
                        props[p] = str(props[p])
                    else:
                        raise ValueError(
                            f'Unable to interpret datatype "{dt}" ' f"for property {p}"
                        )
                else:
                    props[p] = match.group(i + 1)
        return props

    def _extract_connectors(self, nodes: pd.DataFrame) -> Optional[pd.DataFrame]:
        """Infer outgoing/incoming connectors from data.

        Parameters
        ----------
        nodes :     pd.DataFrame

        Returns
        -------
        Optional[pd.DataFrame]
                    With columns `["node_id", "x", "y", "z", "connector_id", "type"]`
        """
        return

List files to read in directory.

Source code in navis/io/base.py
261
262
263
264
265
266
267
268
269
270
271
272
def files_in_dir(
    self, dpath: Path, include_subdirs: bool = DEFAULT_INCLUDE_SUBDIRS
) -> Iterable[Path]:
    """List files to read in directory."""
    if not isinstance(dpath, Path):
        dpath = Path(dpath)
    dpath = dpath.expanduser()
    pattern = "*"
    if include_subdirs:
        pattern = os.path.join("**", pattern)

    yield from (f for f in dpath.glob(pattern) if self.is_valid_file(f))

Return true if file should be considered for reading.

Source code in navis/io/base.py
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
def is_valid_file(self, file):
    """Return true if file should be considered for reading."""
    if isinstance(file, ZipInfo):
        file = file.filename
    elif isinstance(file, tarfile.TarInfo):
        file = file.name
    elif isinstance(file, Path):
        file = file.name

    if self.ignore_hidden and str(file).startswith("._"):
        return False

    if str(file).endswith(self.file_ext):
        return True
    return False

Extract properties from filename according to specified formatter.

PARAMETER DESCRIPTION
filename

TYPE: str

RETURNS DESCRIPTION
props

Properties extracted from filename.

TYPE: dict

Source code in navis/io/base.py
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
def parse_filename(self, filename: str) -> dict:
    """Extract properties from filename according to specified formatter.

    Parameters
    ----------
    filename : str

    Returns
    -------
    props :     dict
                Properties extracted from filename.

    """
    # Make sure we are working with the filename not the whole path
    filename = Path(filename).name

    # Escape all special characters
    fmt = re.escape(self.fmt)

    # Unescape { and }
    fmt = fmt.replace("\\{", "{").replace("\\}", "}")

    # Replace all e.g. {name} with {.*}
    prop_names = []
    for prop in re.findall("{.*?}", fmt):
        prop_names.append(prop[1:-1].replace(" ", ""))
        fmt = fmt.replace(prop, "(.*)")

    # Match
    match = re.search(fmt, filename)

    if not match:
        raise ValueError(f'Unable to match "{self.fmt}" to filename "{filename}"')

    props = {"file": filename}
    for i, prop in enumerate(prop_names):
        for p in prop.split(","):
            # Ignore empty ("{}")
            if not p:
                continue

            # If datatype was specified
            if ":" in p:
                p, dt = p.split(":")

                props[p] = match.group(i + 1)

                if dt == "int":
                    props[p] = int(props[p])
                elif dt == "float":
                    props[p] = float(props[p])
                elif dt == "bool":
                    props[p] = bool(props[p])
                elif dt == "str":
                    props[p] = str(props[p])
                else:
                    raise ValueError(
                        f'Unable to interpret datatype "{dt}" ' f"for property {p}"
                    )
            else:
                props[p] = match.group(i + 1)
    return props

Attempt to read an arbitrary object into a neuron.

PARAMETER DESCRIPTION
obj
    Buffer, path to file or directory, URL, string, or
    dataframe.

TYPE: typing.IO | str | os.PathLike | pandas.DataFrame

RETURNS DESCRIPTION
core.NeuronObject
Source code in navis/io/base.py
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
def read_any(
    self,
    obj,
    include_subdirs=DEFAULT_INCLUDE_SUBDIRS,
    parallel="auto",
    limit=None,
    attrs: Optional[Dict[str, Any]] = None,
) -> "core.NeuronObject":
    """Attempt to read an arbitrary object into a neuron.

    Parameters
    ----------
    obj :       typing.IO | str | os.PathLike | pandas.DataFrame
                Buffer, path to file or directory, URL, string, or
                dataframe.

    Returns
    -------
    core.NeuronObject
    """
    if utils.is_iterable(obj) and not hasattr(obj, "read"):
        return self.read_any_multi(obj, parallel, include_subdirs, attrs)
    else:
        try:
            if os.path.isdir(os.path.expanduser(obj)):
                return self.read_directory(
                    obj, include_subdirs, parallel, limit, attrs
                )
        except TypeError:
            pass
        try:
            if os.path.isfile(os.path.expanduser(obj)) and str(obj).endswith(
                ".zip"
            ):
                return self.read_zip(obj, parallel, limit, attrs)
            if os.path.isfile(os.path.expanduser(obj)) and ".tar" in str(obj):
                return self.read_tar(obj, parallel, limit, attrs)
            if isinstance(obj, str) and obj.startswith("ftp://"):
                return self.read_ftp(obj, parallel, limit, attrs)
        except TypeError:
            pass
        return self.read_any_single(obj, attrs)

Attempt to convert an arbitrary object into a NeuronList, potentially in parallel.

PARAMETER DESCRIPTION
obj
            Sequence of anything readable by read_any_single or
            directory path(s).

TYPE: sequence

include_subdirs
            Whether to include subdirectories of a given
            directory.

TYPE: bool DEFAULT: DEFAULT_INCLUDE_SUBDIRS

parallel
            "auto" or True for n_cores // 2, otherwise int for
            number of jobs, or False for serial.

TYPE: str | bool | int | None DEFAULT: 'auto'

attrs
            Arbitrary attributes to include in each TreeNeuron
            of the NeuronList.

TYPE: dict or None DEFAULT: None

RETURNS DESCRIPTION
core.NeuronList
Source code in navis/io/base.py
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
def read_any_multi(
    self,
    objs,
    include_subdirs=DEFAULT_INCLUDE_SUBDIRS,
    parallel="auto",
    attrs: Optional[Dict[str, Any]] = None,
) -> "core.NeuronList":
    """Attempt to convert an arbitrary object into a NeuronList,
    potentially in parallel.

    Parameters
    ----------
    obj :               sequence
                        Sequence of anything readable by read_any_single or
                        directory path(s).
    include_subdirs :   bool
                        Whether to include subdirectories of a given
                        directory.
    parallel :          str | bool | int | None
                        "auto" or True for n_cores // 2, otherwise int for
                        number of jobs, or False for serial.
    attrs :             dict or None
                        Arbitrary attributes to include in each TreeNeuron
                        of the NeuronList.

    Returns
    -------
    core.NeuronList

    """
    if not utils.is_iterable(objs):
        objs = [objs]

    if not objs:
        logger.warning("No files found, returning empty NeuronList")
        return core.NeuronList([])

    new_objs = []
    for obj in objs:
        try:
            if os.path.isdir(os.path.expanduser(obj)):
                new_objs.extend(self.files_in_dir(obj, include_subdirs))
                continue
        except TypeError:
            pass
        new_objs.append(obj)

    if (
        isinstance(parallel, str)
        and parallel.lower() == "auto"
        and len(new_objs) < 200
    ):
        parallel = False

    read_fn = partial(self.read_any_single, attrs=attrs)
    neurons = parallel_read(read_fn, new_objs, parallel)
    return core.NeuronList(neurons)

Attempt to convert an arbitrary object into a neuron.

PARAMETER DESCRIPTION
obj
    Readable buffer, dataframe, path or URL to single file,
    or parsable string.

TYPE: typing.IO | pandas.DataFrame | str | os.PathLike

attrs
    Arbitrary attributes to include in the neuron.

TYPE: dict or None DEFAULT: None

RETURNS DESCRIPTION
core.BaseNeuron
Source code in navis/io/base.py
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
def read_any_single(
    self, obj, attrs: Optional[Dict[str, Any]] = None
) -> "core.BaseNeuron":
    """Attempt to convert an arbitrary object into a neuron.

    Parameters
    ----------
    obj :       typing.IO | pandas.DataFrame | str | os.PathLike
                Readable buffer, dataframe, path or URL to single file,
                or parsable string.
    attrs :     dict or None
                Arbitrary attributes to include in the neuron.

    Returns
    -------
    core.BaseNeuron
    """
    if hasattr(obj, "read"):
        return self.read_buffer(obj, attrs)
    if isinstance(obj, pd.DataFrame):
        return self.read_dataframe(obj, attrs)
    if isinstance(obj, os.PathLike):
        if str(obj).endswith(".zip"):
            return self.read_zip(obj, attrs=attrs)
        elif ".tar" in str(obj):
            return self.read_tar(obj, attrs=attrs)
        return self.read_file_path(obj, attrs)
    if isinstance(obj, str):
        # See if this might be a file (make sure to expand user)
        if os.path.isfile(os.path.expanduser(obj)):
            p = Path(obj).expanduser()
            if p.suffix == ".zip":
                return self.read_zip(p, attrs=attrs)
            return self.read_file_path(p, attrs)
        if obj.startswith("http://") or obj.startswith("https://"):
            return self.read_url(obj, attrs)
        if obj.startswith("ftp://"):
            return self.read_ftp(obj, attrs=attrs)
        return self.read_string(obj, attrs)
    if isinstance(obj, bytes):
        return self.read_bytes(obj, attrs)
    raise ValueError(f"Could not read neuron from object of type '{type(obj)}'")

Read buffer into a single neuron.

PARAMETER DESCRIPTION
f
    Readable buffer.

TYPE: IO

attrs
    Arbitrary attributes to include in the neuron.

TYPE: dict | None DEFAULT: None

RETURNS DESCRIPTION
core.NeuronObject
Source code in navis/io/base.py
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
def read_buffer(
    self, f: IO, attrs: Optional[Dict[str, Any]] = None
) -> "core.BaseNeuron":
    """Read buffer into a single neuron.

    Parameters
    ----------
    f :         IO
                Readable buffer.
    attrs :     dict | None
                Arbitrary attributes to include in the neuron.

    Returns
    -------
    core.NeuronObject
    """
    raise NotImplementedError(
        "Reading from buffer not implemented for " f"{type(self)}"
    )

Read bytes into a Neuron.

PARAMETER DESCRIPTION
s
    Bytes.

TYPE: bytes

attrs
    Arbitrary attributes to include in the neuron.

TYPE: dict or None DEFAULT: None

RETURNS DESCRIPTION
core.BaseNeuron
Source code in navis/io/base.py
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
def read_bytes(
    self, s: str, attrs: Optional[Dict[str, Any]] = None
) -> "core.BaseNeuron":
    """Read bytes into a Neuron.

    Parameters
    ----------
    s :         bytes
                Bytes.
    attrs :     dict or None
                Arbitrary attributes to include in the neuron.

    Returns
    -------
    core.BaseNeuron
    """
    sio = io.BytesIO(s)
    return self.read_buffer(
        sio, merge_dicts({"name": self.name_fallback, "origin": "string"}, attrs)
    )

Convert a DataFrame into a neuron.

PARAMETER DESCRIPTION
nodes

TYPE: pandas.DataFrame

attrs
    Arbitrary attributes to include in the neuron.

TYPE: dict or None DEFAULT: None

RETURNS DESCRIPTION
core.BaseNeuron
Source code in navis/io/base.py
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
def read_dataframe(
    self, nodes: pd.DataFrame, attrs: Optional[Dict[str, Any]] = None
) -> "core.BaseNeuron":
    """Convert a DataFrame into a neuron.

    Parameters
    ----------
    nodes :     pandas.DataFrame
    attrs :     dict or None
                Arbitrary attributes to include in the neuron.

    Returns
    -------
    core.BaseNeuron
    """
    raise NotImplementedError(
        "Reading DataFrames not implemented for " f"{type(self)}"
    )

Read directory of files into a NeuronList.

PARAMETER DESCRIPTION
fpath
            Path to directory containing files.

TYPE: str | os.PathLike

include_subdirs
            Whether to descend into subdirectories, default False.

TYPE: bool DEFAULT: DEFAULT_INCLUDE_SUBDIRS

parallel

TYPE: str | bool | "auto" DEFAULT: 'auto'

limit
            Limit the number of files read from this directory.

TYPE: int DEFAULT: None

attrs
            Arbitrary attributes to include in the TreeNeurons
            of the NeuronList

TYPE: dict or None DEFAULT: None

RETURNS DESCRIPTION
core.NeuronList
Source code in navis/io/base.py
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
def read_directory(
    self,
    path: os.PathLike,
    include_subdirs=DEFAULT_INCLUDE_SUBDIRS,
    parallel="auto",
    limit: Optional[int] = None,
    attrs: Optional[Dict[str, Any]] = None,
) -> "core.NeuronList":
    """Read directory of files into a NeuronList.

    Parameters
    ----------
    fpath :             str | os.PathLike
                        Path to directory containing files.
    include_subdirs :   bool, optional
                        Whether to descend into subdirectories, default False.
    parallel :          str | bool | "auto"
    limit :             int, optional
                        Limit the number of files read from this directory.
    attrs :             dict or None
                        Arbitrary attributes to include in the TreeNeurons
                        of the NeuronList

    Returns
    -------
    core.NeuronList
    """
    files = list(self.files_in_dir(Path(path), include_subdirs))

    if isinstance(limit, int):
        files = files[:limit]
    elif isinstance(limit, list):
        files = [f for f in files if f in limit]
    elif isinstance(limit, slice):
        files = files[limit]
    elif isinstance(limit, str):
        # Check if limit is a regex
        if rgx.search(limit):
            files = [f for f in files if re.search(limit, str(f.name))]
        else:
            files = [f for f in files if limit in str(f)]

    read_fn = partial(self.read_file_path, attrs=attrs)
    neurons = parallel_read(read_fn, files, parallel)
    return core.NeuronList(neurons)

Read single file from path into a neuron.

PARAMETER DESCRIPTION
fpath
    Path to files.

TYPE: str | os.PathLike

attrs
    Arbitrary attributes to include in the neuron.

TYPE: dict or None DEFAULT: None

RETURNS DESCRIPTION
core.BaseNeuron
Source code in navis/io/base.py
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
def read_file_path(
    self, fpath: os.PathLike, attrs: Optional[Dict[str, Any]] = None
) -> "core.BaseNeuron":
    """Read single file from path into a neuron.

    Parameters
    ----------
    fpath :     str | os.PathLike
                Path to files.
    attrs :     dict or None
                Arbitrary attributes to include in the neuron.

    Returns
    -------
    core.BaseNeuron
    """
    p = Path(fpath)
    with open(p, "rb" if self.read_binary else "r") as f:
        try:
            props = self.parse_filename(f.name)
            props["origin"] = str(p)
            return self.read_buffer(f, merge_dicts(props, attrs))
        except BaseException as e:
            raise ValueError(f"Error reading file {p}") from e

Read given files from an FTP server into a NeuronList.

Typically not used directly but via read_ftp() dispatcher.

PARAMETER DESCRIPTION
files
    Files inside the tar file to read.

TYPE: tarfile.TarInfo | list thereof

ftp
    The FTP client. This should already be connected, logged in
    and in the correct directory. If "GLOBAL", we will look for a
    `_FTP` global variable.

TYPE: ftplib.FTP | "GLOBAL"

attrs
    Arbitrary attributes to include in the TreeNeuron.

TYPE: dict or None DEFAULT: None

on_error
    What do do when error is encountered.

TYPE: 'ignore' | 'raise' DEFAULT: 'ignore'

RETURNS DESCRIPTION
core.NeuronList
Source code in navis/io/base.py
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
def read_from_ftp(
    self,
    files: Union[str, List[str]],
    ftp: FTP,
    attrs: Optional[Dict[str, Any]] = None,
    on_error: Union[Literal["ignore", Literal["raise"]]] = "ignore",
) -> "core.NeuronList":
    """Read given files from an FTP server into a NeuronList.

    Typically not used directly but via `read_ftp()` dispatcher.

    Parameters
    ----------
    files :     tarfile.TarInfo | list thereof
                Files inside the tar file to read.
    ftp :       ftplib.FTP | "GLOBAL"
                The FTP client. This should already be connected, logged in
                and in the correct directory. If "GLOBAL", we will look for a
                `_FTP` global variable.
    attrs :     dict or None
                Arbitrary attributes to include in the TreeNeuron.
    on_error :  'ignore' | 'raise'
                What do do when error is encountered.

    Returns
    -------
    core.NeuronList

    """
    # When reading in parallel, we expect there to be a global FTP connection
    # that was initialized once for each worker process.
    if ftp == "GLOBAL":
        if "_FTP" not in globals():
            raise ValueError("No global FTP connection found.")
        ftp = _FTP

    files = utils.make_iterable(files)

    neurons = []
    for file in files:
        # Read the file into a bytes
        with io.BytesIO() as f:
            ftp.retrbinary("RETR " + file, f.write)
            f.seek(0)
            props = self.parse_filename(file)
            props["origin"] = f"{ftp.host}:{ftp.port}{ftp.pwd()}/{file}"
            try:
                n = self.read_buffer(f, merge_dicts(props, attrs))
                neurons.append(n)
            except BaseException:
                if on_error == "ignore":
                    logger.warning(f'Failed to read "{file}" from FTP.')
                else:
                    raise

    return core.NeuronList(neurons)

Read given files from a tar into a NeuronList.

Typically not used directly but via read_tar() dispatcher.

PARAMETER DESCRIPTION
files
    Files inside the tar file to read.

TYPE: tarfile.TarInfo | list thereof

tarpath
    Path to tar file.

TYPE: str | os.PathLike

attrs
    Arbitrary attributes to include in the TreeNeuron.

TYPE: dict or None DEFAULT: None

on_error
    What do do when error is encountered.

TYPE: 'ignore' | 'raise' DEFAULT: 'ignore'

RETURNS DESCRIPTION
core.NeuronList
Source code in navis/io/base.py
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
def read_from_tar(
    self,
    files: Union[str, List[str]],
    tarpath: os.PathLike,
    attrs: Optional[Dict[str, Any]] = None,
    on_error: Union[Literal["ignore", Literal["raise"]]] = "ignore",
) -> "core.NeuronList":
    """Read given files from a tar into a NeuronList.

    Typically not used directly but via `read_tar()` dispatcher.

    Parameters
    ----------
    files :     tarfile.TarInfo | list thereof
                Files inside the tar file to read.
    tarpath :   str | os.PathLike
                Path to tar file.
    attrs :     dict or None
                Arbitrary attributes to include in the TreeNeuron.
    on_error :  'ignore' | 'raise'
                What do do when error is encountered.

    Returns
    -------
    core.NeuronList

    """
    p = Path(tarpath)
    files = utils.make_iterable(files)

    neurons = []
    with tarfile.open(p, "r") as tf:
        for file in files:
            # Note the `file` is of type tarfile.TarInfo here
            props = self.parse_filename(file.name.split("/")[-1])
            props["origin"] = str(p)
            try:
                n = self.read_bytes(
                    tf.extractfile(file).read(), merge_dicts(props, attrs)
                )
                neurons.append(n)
            except BaseException:
                if on_error == "ignore":
                    logger.warning(f'Failed to read "{file.filename}" from tar.')
                else:
                    raise

    return core.NeuronList(neurons)

Read given files from a zip into a NeuronList.

Typically not used directly but via read_zip() dispatcher.

PARAMETER DESCRIPTION
files
    Files inside the ZIP file to read.

TYPE: zipfile.ZipInfo | list thereof

zippath
    Path to zip file.

TYPE: str | os.PathLike

attrs
    Arbitrary attributes to include in the TreeNeuron.

TYPE: dict or None DEFAULT: None

on_error
    What do do when error is encountered.

TYPE: 'ignore' | 'raise' DEFAULT: 'ignore'

RETURNS DESCRIPTION
core.NeuronList
Source code in navis/io/base.py
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
def read_from_zip(
    self,
    files: Union[str, List[str]],
    zippath: os.PathLike,
    attrs: Optional[Dict[str, Any]] = None,
    on_error: Union[Literal["ignore", Literal["raise"]]] = "ignore",
) -> "core.NeuronList":
    """Read given files from a zip into a NeuronList.

    Typically not used directly but via `read_zip()` dispatcher.

    Parameters
    ----------
    files :     zipfile.ZipInfo | list thereof
                Files inside the ZIP file to read.
    zippath :   str | os.PathLike
                Path to zip file.
    attrs :     dict or None
                Arbitrary attributes to include in the TreeNeuron.
    on_error :  'ignore' | 'raise'
                What do do when error is encountered.

    Returns
    -------
    core.NeuronList

    """
    p = Path(zippath)
    files = utils.make_iterable(files)

    neurons = []
    with ZipFile(p, "r") as zip:
        for file in files:
            # Note the `file` is of type zipfile.ZipInfo here
            props = self.parse_filename(file.orig_filename)
            props["origin"] = str(p)
            try:
                n = self.read_bytes(zip.read(file), merge_dicts(props, attrs))
                neurons.append(n)
            except BaseException:
                if on_error == "ignore":
                    logger.warning(f'Failed to read "{file.filename}" from zip.')
                else:
                    raise

    return core.NeuronList(neurons)

Read files from an FTP server.

This is a dispatcher for .read_from_ftp.

PARAMETER DESCRIPTION
url
    Can be the path to a single file or a directory.

TYPE: str

limit
    Limit the number of files read from this directory.

TYPE: int DEFAULT: None

attrs
    Arbitrary attributes to include in the TreeNeuron.

TYPE: dict or None DEFAULT: None

on_error
    What do do when error is encountered.

TYPE: 'ignore' | 'raise' DEFAULT: 'ignore'

RETURNS DESCRIPTION
core.NeuronList
Source code in navis/io/base.py
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
def read_ftp(
    self,
    url,
    parallel="auto",
    limit: Optional[int] = None,
    attrs: Optional[Dict[str, Any]] = None,
    on_error: Union[Literal["ignore", Literal["raise"]]] = "ignore",
) -> "core.NeuronList":
    """Read files from an FTP server.

    This is a dispatcher for `.read_from_ftp`.

    Parameters
    ----------
    url :       str
                Can be the path to a single file or a directory.
    limit :     int, optional
                Limit the number of files read from this directory.
    attrs :     dict or None
                Arbitrary attributes to include in the TreeNeuron.
    on_error :  'ignore' | 'raise'
                What do do when error is encountered.

    Returns
    -------
    core.NeuronList

    """
    # Remove the ftp:// prefix
    url = url.replace("ftp://", "")

    # Split into server and path
    server, path = url.split("/", 1)

    # Check if server contains a port
    if ":" in server:
        server, port = server.split(":")
        port = int(port)
    else:
        port = 21  # default port

    read_fn = partial(self.read_from_ftp, attrs=attrs, on_error=on_error)
    neurons = parallel_read_ftp(
        read_fn=read_fn,
        server=server,
        port=port,
        path=path,
        file_ext=self.is_valid_file,
        limit=limit,
        parallel=parallel,
    )
    return core.NeuronList(neurons)

Read single string into a Neuron.

PARAMETER DESCRIPTION
s
    String.

TYPE: str

attrs
    Arbitrary attributes to include in the neuron.

TYPE: dict or None DEFAULT: None

RETURNS DESCRIPTION
core.BaseNeuron
Source code in navis/io/base.py
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
def read_string(
    self, s: str, attrs: Optional[Dict[str, Any]] = None
) -> "core.BaseNeuron":
    """Read single string into a Neuron.

    Parameters
    ----------
    s :         str
                String.
    attrs :     dict or None
                Arbitrary attributes to include in the neuron.

    Returns
    -------
    core.BaseNeuron
    """
    sio = io.StringIO(s)
    return self.read_buffer(
        sio, merge_dicts({"name": self.name_fallback, "origin": "string"}, attrs)
    )

Read files from a tar archive into a NeuronList.

This is a dispatcher for .read_from_tar.

PARAMETER DESCRIPTION
fpath
    Path to tar file.

TYPE: str | os.PathLike

limit
    Limit the number of files read from this directory.

TYPE: int DEFAULT: None

attrs
    Arbitrary attributes to include in the TreeNeuron.

TYPE: dict or None DEFAULT: None

on_error
    What do do when error is encountered.

TYPE: 'ignore' | 'raise' DEFAULT: 'ignore'

RETURNS DESCRIPTION
core.NeuronList
Source code in navis/io/base.py
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
def read_tar(
    self,
    fpath: os.PathLike,
    parallel="auto",
    limit: Optional[int] = None,
    attrs: Optional[Dict[str, Any]] = None,
    on_error: Union[Literal["ignore", Literal["raise"]]] = "ignore",
) -> "core.NeuronList":
    """Read files from a tar archive into a NeuronList.

    This is a dispatcher for `.read_from_tar`.

    Parameters
    ----------
    fpath :     str | os.PathLike
                Path to tar file.
    limit :     int, optional
                Limit the number of files read from this directory.
    attrs :     dict or None
                Arbitrary attributes to include in the TreeNeuron.
    on_error :  'ignore' | 'raise'
                What do do when error is encountered.

    Returns
    -------
    core.NeuronList

    """
    fpath = Path(fpath).expanduser()
    read_fn = partial(
        self.read_from_tar, tarpath=fpath, attrs=attrs, on_error=on_error
    )
    neurons = parallel_read_archive(
        read_fn=read_fn,
        fpath=fpath,
        file_ext=self.is_valid_file,
        limit=limit,
        parallel=parallel,
    )
    return core.NeuronList(neurons)

Read file from URL into a neuron.

PARAMETER DESCRIPTION
url
    URL to file.

TYPE: str

attrs
    Arbitrary attributes to include in the neuron.

TYPE: dict or None DEFAULT: None

RETURNS DESCRIPTION
core.BaseNeuron
Source code in navis/io/base.py
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
def read_url(
    self, url: str, attrs: Optional[Dict[str, Any]] = None
) -> "core.BaseNeuron":
    """Read file from URL into a neuron.

    Parameters
    ----------
    url :       str
                URL to file.
    attrs :     dict or None
                Arbitrary attributes to include in the neuron.

    Returns
    -------
    core.BaseNeuron
    """
    # Note: originally, we used stream=True and passed `r.raw` to the
    # read_buffer function but that caused issue when there was more
    # than one chunk which would require us to concatenate the chunks
    # `via r.raw.iter_content()`.
    # Instead, we will simply read the whole content, wrap it in a BytesIO
    # and pass that to the read_buffer function. This is not ideal as it
    # will load the whole file into memory while the streaming solution
    # may have raised an exception earlier if the file was corrupted or
    # the wrong format.
    with requests.get(url, stream=False) as r:
        r.raise_for_status()
        props = self.parse_filename(url.split("/")[-1])
        props["origin"] = url
        return self.read_buffer(io.BytesIO(r.content), merge_dicts(props, attrs))

Read files from a zip into a NeuronList.

This is a dispatcher for .read_from_zip.

PARAMETER DESCRIPTION
fpath
    Path to zip file.

TYPE: str | os.PathLike

limit
    Limit the number of files read from this directory.

TYPE: int DEFAULT: None

attrs
    Arbitrary attributes to include in the TreeNeuron.

TYPE: dict or None DEFAULT: None

on_error
    What do do when error is encountered.

TYPE: 'ignore' | 'raise' DEFAULT: 'ignore'

RETURNS DESCRIPTION
core.NeuronList
Source code in navis/io/base.py
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
def read_zip(
    self,
    fpath: os.PathLike,
    parallel="auto",
    limit: Optional[int] = None,
    attrs: Optional[Dict[str, Any]] = None,
    on_error: Union[Literal["ignore", Literal["raise"]]] = "ignore",
) -> "core.NeuronList":
    """Read files from a zip into a NeuronList.

    This is a dispatcher for `.read_from_zip`.

    Parameters
    ----------
    fpath :     str | os.PathLike
                Path to zip file.
    limit :     int, optional
                Limit the number of files read from this directory.
    attrs :     dict or None
                Arbitrary attributes to include in the TreeNeuron.
    on_error :  'ignore' | 'raise'
                What do do when error is encountered.

    Returns
    -------
    core.NeuronList

    """
    fpath = Path(fpath).expanduser()
    read_fn = partial(
        self.read_from_zip, zippath=fpath, attrs=attrs, on_error=on_error
    )
    neurons = parallel_read_archive(
        read_fn=read_fn,
        fpath=fpath,
        file_ext=self.is_valid_file,
        limit=limit,
        parallel=parallel,
    )
    return core.NeuronList(neurons)

Writer class that takes care of things like filenames, archives, etc.

PARAMETER DESCRIPTION
write_func
        Writer function to write a single file to disk. Must
        accept a `filepath` parameter.

TYPE: callable

ext
        File extension - e.g. '.swc'.

TYPE: str

Source code in navis/io/base.py
 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
116
117
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
class Writer:
    """Writer class that takes care of things like filenames, archives, etc.

    Parameters
    ----------
    write_func :    callable
                    Writer function to write a single file to disk. Must
                    accept a `filepath` parameter.
    ext :           str, optional
                    File extension - e.g. '.swc'.

    """

    def __init__(self, write_func, ext):
        assert callable(write_func)
        if ext:
            assert isinstance(ext, str) and ext.startswith(".")
        self.write_func = write_func
        self.ext = ext

    def write_single(self, x, filepath, **kwargs):
        """Write single object to file."""
        # try to str.format any path-like
        try:
            as_str = os.fspath(filepath)
        except TypeError:
            raise ValueError(
                f'`filepath` must be str or pathlib.Path, got "{type(filepath)}"'
            )

        # Format filename (e.g. "{neuron.name}.swc")
        formatted_str = as_str.format(neuron=x)

        # If it was formatted, make sure it has correct extension
        if self.ext and formatted_str != as_str and not as_str.endswith(self.ext):
            raise ValueError(f"Formattable filepaths must end with '{self.ext}'")

        filepath = Path(formatted_str)

        # Expand user - otherwise .exists() might fail
        filepath = filepath.expanduser()

        # If not specified, generate filename
        if self.ext and not str(filepath).endswith(self.ext):
            filepath = filepath / f"{x.id}{self.ext}"

        # Make sure the parent directory exists
        if not filepath.parent.exists():
            raise ValueError(f"Parent folder {filepath.parent} must exist.")

        # Track the path we put this (and presumably all other files in)
        self.path = Path(filepath)
        while not self.path.is_dir():
            self.path = self.path.parent

        return self.write_func(x, filepath=filepath, **kwargs)

    def write_many(self, x, filepath, **kwargs):
        """Write multiple files to folder."""
        if not utils.is_iterable(filepath):
            # Assume this is a folder if it doesn't end with e.g. '.swc'
            is_filename = str(filepath).endswith(self.ext) if self.ext else False
            is_single = len(x) == 1
            is_formattable = "{" in str(filepath) and "}" in str(filepath)
            if not is_filename or is_single or is_formattable:
                filepath = [filepath] * len(x)
            else:
                raise ValueError(
                    "`filepath` must either be a folder, a "
                    "formattable filepath or a list of filepaths"
                    "when saving multiple neurons."
                )

        if len(filepath) != len(x):
            raise ValueError(
                f"Got {len(filepath)} file names for " f"{len(x)} neurons."
            )

        # At this point filepath is iterable
        filepath: Iterable[str]
        for n, f in config.tqdm(
            zip(x, filepath),
            disable=config.pbar_hide,
            leave=config.pbar_leave,
            total=len(x),
            desc="Writing",
        ):
            self.write_single(n, filepath=f, **kwargs)

    def write_zip(self, x, filepath, **kwargs):
        """Write files to zip."""
        filepath = Path(filepath).expanduser()
        # Parse pattern, if given
        pattern = "{neuron.id}" + (self.ext if self.ext else "")
        if "@" in str(filepath):
            pattern, filename = filepath.name.split("@")
            filepath = filepath.parent / filename

        # Make sure we have an iterable
        x = core.NeuronList(x)

        with ZipFile(filepath, mode="w") as zf:
            # Context-manager will remove temporary directory and its contents
            with tempfile.TemporaryDirectory() as tempdir:
                for n in config.tqdm(
                    x,
                    disable=config.pbar_hide,
                    leave=config.pbar_leave,
                    total=len(x),
                    desc="Writing",
                ):
                    # Save to temporary file
                    f = None
                    try:
                        # Generate temporary filename
                        f = os.path.join(tempdir, pattern.format(neuron=n))
                        # Write to temporary file
                        self.write_single(n, filepath=f, **kwargs)
                        # Add file to zip
                        zf.write(
                            f,
                            arcname=pattern.format(neuron=n),
                            compress_type=compression,
                        )
                    except BaseException:
                        raise
                    finally:
                        # Remove temporary file - we do this inside the loop
                        # to avoid unnecessarily occupying space as we write
                        if f:
                            os.remove(f)

        # Set filepath to zipfile -> this overwrite filepath set in write_single
        # (which would be the temporary file)
        self.path = Path(filepath)

    def write_any(self, x, filepath, **kwargs):
        """Write any to file. Default entry point."""
        # If target is a zipfile
        if isinstance(filepath, (str, Path)) and str(filepath).endswith(".zip"):
            return self.write_zip(x, filepath=filepath, **kwargs)
        elif isinstance(x, core.NeuronList):
            return self.write_many(x, filepath=filepath, **kwargs)
        else:
            return self.write_single(x, filepath=filepath, **kwargs)

Write any to file. Default entry point.

Source code in navis/io/base.py
205
206
207
208
209
210
211
212
213
def write_any(self, x, filepath, **kwargs):
    """Write any to file. Default entry point."""
    # If target is a zipfile
    if isinstance(filepath, (str, Path)) and str(filepath).endswith(".zip"):
        return self.write_zip(x, filepath=filepath, **kwargs)
    elif isinstance(x, core.NeuronList):
        return self.write_many(x, filepath=filepath, **kwargs)
    else:
        return self.write_single(x, filepath=filepath, **kwargs)

Write multiple files to folder.

Source code in navis/io/base.py
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
def write_many(self, x, filepath, **kwargs):
    """Write multiple files to folder."""
    if not utils.is_iterable(filepath):
        # Assume this is a folder if it doesn't end with e.g. '.swc'
        is_filename = str(filepath).endswith(self.ext) if self.ext else False
        is_single = len(x) == 1
        is_formattable = "{" in str(filepath) and "}" in str(filepath)
        if not is_filename or is_single or is_formattable:
            filepath = [filepath] * len(x)
        else:
            raise ValueError(
                "`filepath` must either be a folder, a "
                "formattable filepath or a list of filepaths"
                "when saving multiple neurons."
            )

    if len(filepath) != len(x):
        raise ValueError(
            f"Got {len(filepath)} file names for " f"{len(x)} neurons."
        )

    # At this point filepath is iterable
    filepath: Iterable[str]
    for n, f in config.tqdm(
        zip(x, filepath),
        disable=config.pbar_hide,
        leave=config.pbar_leave,
        total=len(x),
        desc="Writing",
    ):
        self.write_single(n, filepath=f, **kwargs)

Write single object to file.

Source code in navis/io/base.py
 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
def write_single(self, x, filepath, **kwargs):
    """Write single object to file."""
    # try to str.format any path-like
    try:
        as_str = os.fspath(filepath)
    except TypeError:
        raise ValueError(
            f'`filepath` must be str or pathlib.Path, got "{type(filepath)}"'
        )

    # Format filename (e.g. "{neuron.name}.swc")
    formatted_str = as_str.format(neuron=x)

    # If it was formatted, make sure it has correct extension
    if self.ext and formatted_str != as_str and not as_str.endswith(self.ext):
        raise ValueError(f"Formattable filepaths must end with '{self.ext}'")

    filepath = Path(formatted_str)

    # Expand user - otherwise .exists() might fail
    filepath = filepath.expanduser()

    # If not specified, generate filename
    if self.ext and not str(filepath).endswith(self.ext):
        filepath = filepath / f"{x.id}{self.ext}"

    # Make sure the parent directory exists
    if not filepath.parent.exists():
        raise ValueError(f"Parent folder {filepath.parent} must exist.")

    # Track the path we put this (and presumably all other files in)
    self.path = Path(filepath)
    while not self.path.is_dir():
        self.path = self.path.parent

    return self.write_func(x, filepath=filepath, **kwargs)

Write files to zip.

Source code in navis/io/base.py
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
def write_zip(self, x, filepath, **kwargs):
    """Write files to zip."""
    filepath = Path(filepath).expanduser()
    # Parse pattern, if given
    pattern = "{neuron.id}" + (self.ext if self.ext else "")
    if "@" in str(filepath):
        pattern, filename = filepath.name.split("@")
        filepath = filepath.parent / filename

    # Make sure we have an iterable
    x = core.NeuronList(x)

    with ZipFile(filepath, mode="w") as zf:
        # Context-manager will remove temporary directory and its contents
        with tempfile.TemporaryDirectory() as tempdir:
            for n in config.tqdm(
                x,
                disable=config.pbar_hide,
                leave=config.pbar_leave,
                total=len(x),
                desc="Writing",
            ):
                # Save to temporary file
                f = None
                try:
                    # Generate temporary filename
                    f = os.path.join(tempdir, pattern.format(neuron=n))
                    # Write to temporary file
                    self.write_single(n, filepath=f, **kwargs)
                    # Add file to zip
                    zf.write(
                        f,
                        arcname=pattern.format(neuron=n),
                        compress_type=compression,
                    )
                except BaseException:
                    raise
                finally:
                    # Remove temporary file - we do this inside the loop
                    # to avoid unnecessarily occupying space as we write
                    if f:
                        os.remove(f)

    # Set filepath to zipfile -> this overwrite filepath set in write_single
    # (which would be the temporary file)
    self.path = Path(filepath)

Merge dicts and kwargs left to right.

Ignores None arguments.

Source code in navis/io/base.py
55
56
57
58
59
60
61
62
63
64
65
66
def merge_dicts(*dicts: Optional[Dict], **kwargs) -> Dict:
    """Merge dicts and kwargs left to right.

    Ignores None arguments.
    """
    # handles nones
    out = dict()
    for d in dicts:
        if d:
            out.update(d)
    out.update(kwargs)
    return out

Read neurons from some objects with the given reader function, potentially in parallel.

Reader function must be picklable.

PARAMETER DESCRIPTION
read_fn

TYPE: Callable

objs

TYPE: Iterable

parallel
        "auto" or True for `n_cores` // 2, otherwise int for number
        of jobs, or false for serial.

TYPE: str | bool | int DEFAULT: 'auto'

RETURNS DESCRIPTION
core.NeuronList
Source code in navis/io/base.py
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
def parallel_read(read_fn, objs, parallel="auto") -> List["core.NeuronList"]:
    """Read neurons from some objects with the given reader function,
    potentially in parallel.

    Reader function must be picklable.

    Parameters
    ----------
    read_fn :       Callable
    objs :          Iterable
    parallel :      str | bool | int
                    "auto" or True for `n_cores` // 2, otherwise int for number
                    of jobs, or false for serial.

    Returns
    -------
    core.NeuronList

    """
    try:
        length = len(objs)
    except TypeError:
        length = None

    prog = partial(
        config.tqdm,
        desc="Importing",
        total=length,
        disable=config.pbar_hide,
        leave=config.pbar_leave,
    )

    if (
        isinstance(parallel, str)
        and parallel.lower() == "auto"
        and not isinstance(length, type(None))
        and length < 200
    ):
        parallel = False

    if parallel:
        # Do not swap this as `isinstance(True, int)` returns `True`
        if isinstance(parallel, (bool, str)):
            n_cores = max(1, os.cpu_count() // 2)
        else:
            n_cores = int(parallel)

        with mp.Pool(processes=n_cores) as pool:
            results = pool.imap(read_fn, objs)
            neurons = list(prog(results))
    else:
        neurons = [read_fn(obj) for obj in prog(objs)]

    return neurons

Read neurons from a archive (zip or tar), potentially in parallel.

Reader function must be picklable.

PARAMETER DESCRIPTION
read_fn

TYPE: Callable

fpath

TYPE: str | Path

file_ext
        File extension to search for - e.g. ".swc". `None` or `''`
        are interpreted as looking for filenames without extension.
        To include all files use `'*'`. Can also be callable that
        accepts a filename and returns True or False depending on
        if it should be included.

TYPE: str | callable

limit
        Limit the number of files read from this directory.

TYPE: int DEFAULT: None

parallel
        "auto" or True for n_cores // 2, otherwise int for number of
        jobs, or false for serial.

TYPE: str | bool | int DEFAULT: 'auto'

ignore_hidden
        Archives zipped on OSX can end up containing a
        `__MACOSX` folder with files that mirror the name of other
        files. For example if there is a `123456.swc` in the archive
        you might also find a `__MACOSX/._123456.swc`. Reading the
        latter will result in an error. If ignore_hidden=True
        we will simply ignore all file that starts with "._".

TYPE: bool DEFAULT: True

RETURNS DESCRIPTION
core.NeuronList
Source code in navis/io/base.py
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
def parallel_read_archive(
    read_fn, fpath, file_ext, limit=None, parallel="auto", ignore_hidden=True
) -> List["core.NeuronList"]:
    """Read neurons from a archive (zip or tar), potentially in parallel.

    Reader function must be picklable.

    Parameters
    ----------
    read_fn :       Callable
    fpath :         str | Path
    file_ext :      str | callable
                    File extension to search for - e.g. ".swc". `None` or `''`
                    are interpreted as looking for filenames without extension.
                    To include all files use `'*'`. Can also be callable that
                    accepts a filename and returns True or False depending on
                    if it should be included.
    limit :         int, optional
                    Limit the number of files read from this directory.
    parallel :      str | bool | int
                    "auto" or True for n_cores // 2, otherwise int for number of
                    jobs, or false for serial.
    ignore_hidden : bool
                    Archives zipped on OSX can end up containing a
                    `__MACOSX` folder with files that mirror the name of other
                    files. For example if there is a `123456.swc` in the archive
                    you might also find a `__MACOSX/._123456.swc`. Reading the
                    latter will result in an error. If ignore_hidden=True
                    we will simply ignore all file that starts with "._".

    Returns
    -------
    core.NeuronList

    """
    # Check zip content
    p = Path(fpath)
    to_read = []

    if p.name.endswith(".zip"):
        with ZipFile(p, "r") as zip:
            for i, file in enumerate(zip.filelist):
                fname = file.filename.split("/")[-1]
                if ignore_hidden and fname.startswith("._"):
                    continue
                if callable(file_ext):
                    if file_ext(file):
                        to_read.append(file)
                elif file_ext == "*":
                    to_read.append(file)
                elif file_ext and fname.endswith(file_ext):
                    to_read.append(file)
                elif "." not in file.filename:
                    to_read.append(file)

                if isinstance(limit, int) and i >= limit:
                    break
    elif ".tar" in p.name:  # can be ".tar", "tar.gz" or "tar.bz"
        with tarfile.open(p, "r") as tf:
            for i, file in enumerate(tf):
                fname = file.name.split("/")[-1]
                if ignore_hidden and fname.startswith("._"):
                    continue
                if callable(file_ext):
                    if file_ext(file):
                        to_read.append(file)
                elif file_ext == "*":
                    to_read.append(file)
                elif file_ext and fname.endswith(file_ext):
                    to_read.append(file)
                elif "." not in file.filename:
                    to_read.append(file)

                if isinstance(limit, int) and i >= limit:
                    break

    if isinstance(limit, list):
        to_read = [f for f in to_read if f in limit]
    elif isinstance(limit, slice):
        to_read = to_read[limit]
    elif isinstance(limit, str):
        # Check if limit is a regex
        if rgx.search(limit):
            to_read = [f for f in to_read if re.search(limit, f)]
        else:
            to_read = [f for f in to_read if limit in f]

    prog = partial(
        config.tqdm,
        desc="Importing",
        total=len(to_read),
        disable=config.pbar_hide,
        leave=config.pbar_leave,
    )

    if isinstance(parallel, str) and parallel.lower() == "auto" and len(to_read) < 200:
        parallel = False

    if parallel:
        # Do not swap this as `isinstance(True, int)` returns `True`
        if isinstance(parallel, (bool, str)):
            n_cores = max(1, os.cpu_count() // 2)
        else:
            n_cores = int(parallel)

        with mp.Pool(processes=n_cores) as pool:
            results = pool.imap(read_fn, to_read)
            neurons = list(prog(results))
    else:
        neurons = [read_fn(obj) for obj in prog(to_read)]

    return neurons

Read neurons from an FTP server, potentially in parallel.

Reader function must be picklable.

PARAMETER DESCRIPTION
read_fn

TYPE: Callable

server
        FTP server address.

TYPE: str

port
        FTP server port.

TYPE: int

path
        Path to directory containing files or single file.

TYPE: str

file_ext
        File extension to search for - e.g. ".swc". `None` or `''`
        are interpreted as looking for filenames without extension.
        To include all files use `'*'`. Can also be callable that
        accepts a filename and returns True or False depending on
        if it should be included.

TYPE: str | callable

limit
        Limit the number of files read from this directory.

TYPE: int DEFAULT: None

parallel
        "auto" or True for n_cores // 2, otherwise int for number of
        jobs, or false for serial.

TYPE: str | bool | int DEFAULT: 'auto'

RETURNS DESCRIPTION
core.NeuronList
Source code in navis/io/base.py
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
def parallel_read_ftp(
    read_fn,
    server,
    port,
    path,
    file_ext,
    limit=None,
    parallel="auto",
) -> List["core.NeuronList"]:
    """Read neurons from an FTP server, potentially in parallel.

    Reader function must be picklable.

    Parameters
    ----------
    read_fn :       Callable
    server :        str
                    FTP server address.
    port :          int
                    FTP server port.
    path :          str
                    Path to directory containing files or single file.
    file_ext :      str | callable
                    File extension to search for - e.g. ".swc". `None` or `''`
                    are interpreted as looking for filenames without extension.
                    To include all files use `'*'`. Can also be callable that
                    accepts a filename and returns True or False depending on
                    if it should be included.
    limit :         int, optional
                    Limit the number of files read from this directory.
    parallel :      str | bool | int
                    "auto" or True for n_cores // 2, otherwise int for number of
                    jobs, or false for serial.

    Returns
    -------
    core.NeuronList

    """
    # Check if this is a single file
    is_single_file = False
    if "*" not in path:
        if isinstance(file_ext, str) and path.endswith(file_ext):
            is_single_file = True
        elif callable(file_ext) and file_ext(path.rsplit("/", 1)[1]):
            is_single_file = True

    if is_single_file:
        path, fname = path.rsplit("/", 1)
        to_read = [fname]
    else:
        pattern = ""
        # Check if path contains a "*." pattern - e.g. something like "*_raw.swc"
        if "*" in path:
            path, fname = path.rsplit("/", 1)
            pattern = fname

        # Remove leading /
        if path.startswith("/"):
            path = path[1:]

        # First check content
        with FTP() as ftp:
            ftp.connect(server, port)  # connect to server
            ftp.login()  # anonymous login
            ftp.cwd(path)  # change to path

            # Read content
            content = []
            ftp.retrlines(f"LIST {pattern}", content.append)

        # Parse content into filenames
        to_read = []
        for line in content:
            if not line:
                continue
            file = line.split()[-1].strip()

            if callable(file_ext):
                if file_ext(file):
                    to_read.append(file)
            elif file_ext == "*":
                to_read.append(file)
            elif file_ext and fname.endswith(file_ext):
                to_read.append(file)

    if isinstance(limit, int):
        to_read = to_read[:limit]
    elif isinstance(limit, list):
        to_read = [f for f in to_read if f in limit]
    elif isinstance(limit, slice):
        to_read = to_read[limit]
    elif isinstance(limit, str):
        # Check if limit is a regex
        if rgx.search(limit):
            to_read = [f for f in to_read if re.search(limit, f)]
        else:
            to_read = [f for f in to_read if limit in f]

    if not to_read:
        return []

    prog = partial(
        config.tqdm,
        desc="Loading",
        total=len(to_read),
        disable=config.pbar_hide,
        leave=config.pbar_leave,
    )

    if isinstance(parallel, str) and parallel.lower() == "auto" and len(to_read) < 200:
        parallel = False

    if parallel:
        # Do not swap this as `isinstance(True, int)` returns `True`
        if isinstance(parallel, (bool, str)):
            n_cores = max(1, os.cpu_count() // 2)
        else:
            n_cores = int(parallel)

        # We can't send the FTP object to the process (because its socket is not pickleable)
        # Instead, we need to initialize a new FTP connection in each process via a global variable
        with mp.Pool(
            processes=n_cores, initializer=_ftp_pool_init, initargs=(server, port, path)
        ) as pool:
            results = pool.imap(partial(read_fn, ftp="GLOBAL"), to_read)
            neurons = list(prog(results))
    else:
        with FTP() as ftp:
            ftp.connect(server, port)
            ftp.login()
            ftp.cwd(path)

            neurons = [read_fn(file, ftp=ftp) for file in prog(to_read)]

    return neurons

Convert bit width into int and float dtypes.

PARAMETER DESCRIPTION
precision

16, 32, 64, or None

TYPE: int

RETURNS DESCRIPTION
tuple

Integer numpy dtype, float numpy dtype

RAISES DESCRIPTION
ValueError

Unknown precision.

Source code in navis/io/base.py
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
def parse_precision(precision: Optional[int]):
    """Convert bit width into int and float dtypes.

    Parameters
    ----------
    precision : int
        16, 32, 64, or None

    Returns
    -------
    tuple
        Integer numpy dtype, float numpy dtype

    Raises
    ------
    ValueError
        Unknown precision.
    """
    INT_DTYPES = {16: np.int16, 32: np.int32, 64: np.int64, None: None}
    FLOAT_DTYPES = {16: np.float16, 32: np.float32, 64: np.float64, None: None}

    try:
        return (INT_DTYPES[precision], FLOAT_DTYPES[precision])
    except KeyError:
        raise ValueError(
            f"Unknown precision {precision}. Expected on of the following: 16, 32 (default), 64 or None"
        )