summaryrefslogtreecommitdiff
path: root/python-nanoset.spec
blob: 836d35473a8aa84bd5fd0463abd90645f006df1b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
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
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
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
%global _empty_manifest_terminate_build 0
Name:		python-nanoset
Version:	0.2.1
Release:	1
Summary:	A memory-optimized wrapper for Python sets likely to be empty.
License:	MIT
URL:		https://github.com/althonos/nanoset.py
Source0:	https://mirrors.aliyun.com/pypi/web/packages/0a/42/773b208c9c9eee249e6ccef5460b16874952c2838afdd9a7047e92cd042e/nanoset-0.2.1.tar.gz


%description
# `nanoset.py` [![starme](https://img.shields.io/github/stars/althonos/nanoset.py.svg?style=social&label=Star)](https://github.com/althonos/nanoset.py)

*A memory-optimized wrapper for Python sets likely to be empty.*

[![TravisCI](https://img.shields.io/travis/althonos/nanoset.py/master.svg?logo=travis&maxAge=600&style=flat-square)](https://travis-ci.org/althonos/nanoset.py/branches)
[![AppVeyor](https://img.shields.io/appveyor/ci/althonos/nanoset-py/master?logo=appveyor&style=flat-square&maxAge=600)](https://ci.appveyor.com/project/althonos/nanoset-py)
[![License](https://img.shields.io/badge/license-MIT-blue.svg?style=flat-square&maxAge=2678400)](https://choosealicense.com/licenses/mit/)
[![Source](https://img.shields.io/badge/source-GitHub-303030.svg?maxAge=2678400&style=flat-square)](https://github.com/althonos/nanoset.py/)
[![PyPI](https://img.shields.io/pypi/v/nanoset.svg?style=flat-square&maxAge=600)](https://pypi.org/project/nanoset)
[![Crates](https://img.shields.io/crates/v/nanoset-py?style=flat-square&maxAge=600)](https://crates.io/crates/nanoset-py)
[![Wheel](https://img.shields.io/pypi/wheel/nanoset.svg?style=flat-square&maxAge=3600)](https://pypi.org/project/nanoset/#files)
[![Python Versions](https://img.shields.io/pypi/pyversions/nanoset.svg?style=flat-square&maxAge=600)](https://pypi.org/project/nanoset/#files)
[![Python Implementations](https://img.shields.io/pypi/implementation/nanoset.svg?style=flat-square&maxAge=600)](https://pypi.org/project/nanoset/#files)
[![Changelog](https://img.shields.io/badge/keep%20a-changelog-8A0707.svg?maxAge=2678400&style=flat-square)](https://github.com/althonos/nanoset.py/blob/master/CHANGELOG.md)
[![GitHub issues](https://img.shields.io/github/issues/althonos/nanoset.py.svg?style=flat-square&maxAge=600)](https://github.com/althonos/nanoset.py/issues)

## ⏱️ TL;DR

Save up to 85% of the memory used by empty `set` instances in your code with
a single line of code:
```python
from nanoset import PicoSet as set
```

## 🚩 Table of Contents

- [Overview](#-overview)
  * [About Python memory usage](#-about-python-memory-usage)
  * [Simple example usecase](#-simple-example-usecase)
  * [Implementation](#-implementation)
  * [Statistics](#-statistics)
- [Installing](#-installing)
- [API Reference](#-api-reference)
- [License](#-license)


## πŸ—ΊοΈ Overview

### 🐏 About Python memory usage

Python is a great programming language (*fight me*), but sometimes you start
questioning why it does things in certain ways. Since Python 2.3, the standard
library provides the [`set`](https://docs.python.org/3.7/library/stdtypes.html#set)
collection, which is a specialized container for membership testing. On the
contrary to the ubiquitous [`list`](https://docs.python.org/3.7/library/stdtypes.html#list)
collection, `set` is not ordered (or, more accurately, *does not let you access
the order it stores the elements in*). The other feature of `set` is that just
like its mathematical counterpart, it does not allow duplicates, which is very
useful for some algorithms. However, **sets are memory-expensive**:
```python
>>> import sys
>>> sys.getsizeof(list())
56
>>> sys.getsizeof(set())
216
```

An empty set takes more than three times the memory of an empty list! For some
data structures or objects with a lot of `set` attributes, they can quickly
cause a very large part of the memory to be used for nothing. This is even more
sad when you are used to [Rust](https://www.rust-lang.org/), where most
[collections](https://doc.rust-lang.org/std/collections/) allocate lazily.
**This is where `nanoset` comes to the rescue:**
```python
>>> import nanoset
>>> sys.getsizeof(nanoset.NanoSet())
48
>>> sys.getsizeof(nanoset.PicoSet())
32
```

*Actually, that's a lie, but keep reading*.

### πŸ’‘ Simple example usecase

Let's imagine we are building an ordered graph data structure, where we may
want to store [taxonomic data](https://en.wikipedia.org/wiki/Taxonomic_database),
or any other kind of hierarchy. We can simply define the graphs and its nodes
with the two following classes:

```python
class Graph:
    root: Node
    nodes: Dict[str, Node]

class Node:
    neighbors: Set[node]
```

This makes adding an edge and querying for an edge existence between two nodes
an `O(1)` operation, and iterating over all the nodes an `O(n)` operation, which
is mot likely what we want here. We use `set` and not `list` because we want to
avoid storing an edge in duplicate, which is a sensible choice. But now let's
look at the [statistics](https://terminologies.gfbio.org/terminology/?ontology=NCBITAXON)
of the [NCBITaxon](https://www.ncbi.nlm.nih.gov/taxonomy) project, the
database for Organismal Classification developed by the US National Center for
Biotechnology Information:

```ignore
 Metrics
    Number of classes*: 1595237
    Number of individuals: 0
    Number of properties: 0
    Classes without definition: 1595237
    Classes without label: 0
    Average number of children: 12
    Classes with a single child: 40319
    Maximum number of children: 41761
    Classes with more than 25 children: 0
    Classes with more than 1 parent: 0
    Maximum depth: 38
    Number of leaves**: 1130671
```

According to these, we are going to have **1,130,671** leaves for a total of
**1,595,237** nodes, which means **70.8%** of empty sets. Now you may think:

> Ok, I got this. But in this case, I just need a special case for leaves, where
> instead of storing an empty set of `neighbors`, I store a reference to `None`
> when that set would be empty. I can then replace that reference with an actual
> set only when I want to add new edges from that node. Problem solved!

Well, glad we are on the same level: this is what **`nanoset`** does for you!


### πŸ”¨ Implementation

Actually, it's not magic at all. Just imagine a class `NanoSet` that works as
a [proxy](https://www.tutorialspoint.com/python_design_patterns/python_design_patterns_proxy.htm)
to an actual Python `set` it wraps, but which is only allocated when some data
actually needs to be stored:

```python
class NanoSet(collections.abc.Set):

    def __init__(self, iterable=None):
        self.inner = None if iterable is None else set(iterable)

    def add(self, element):
        if self.inner is None:
            self.inner = set()
        self.inner.add(element)

    # ... the rest of the `set` API ...
```

That's about it! However, doing it like so in Python would not be super
efficient, as the resulting object would be **48** bytes. Using
[slots](http://book.pythontips.com/en/latest/__slots__magic.html), this can be
reduced to **40** bytes, which is on par to what we get with **`NanoSet`**.

**Note that these values are only when the inner set is empty!** When actually
allocating the set to store our values, we allocate an additional **232** bytes
of data. This means that using **`NanoSet`** creates an overhead, since a
non-empty set will now weigh **264** bytes (**248** bytes for **`PicoSet`**).

> Well, I was way better off with my approach of storing `Optional[Set]`
> everywhere then, I don't want to pay any additional cost for nonempty sets!

Sure. But that would mean changing your whole code. And actually, you may not
gain that much memory from doing that compared to using `nanoset`, since the
only time the wrapper performs badly is when you have a load factor of more than
90%. Furthermore, just to give you some perspective, `sys.getsizeof(1)` is
**28** bytes.

> By the way, you didn't mention `PicoSet`. How did you manage to get that down
> to **32** bytes, when a slotted Python object can't be less that **40** bytes?

Easy: `PicoSet` is basically `NanoSet`, but without an implementation of the
[Garbage Collector protocol](https://docs.python.org/3/c-api/gcsupport.html).
This saves us **8** bytes of object memory, but comes with a drawback: the
garbage collector cannot see the set allocated *inside* the `PicoSet`. This
does not change anything for execution, but debugging with a memory profiler
will be harder. Here is an example where we allocate **1,000,000** singletons
first with `NanoSet`, then with `PicoSet`, using
[`guppy3`](https://pypi.org/project/guppy3/) to check the heap:

```python
>>> l = [nanoset.NanoSet({x}) for x in range(1000000)]
>>> guppy.hpy().heap()
Partition of a set of 3036763 objects. Total size = 304996526 bytes.
 Index  Count   %     Size    %   Cumulative %  Kind (class / dict of class)
     0 1000044  33 216105248  71  216105248  71 set
     1 1000000  33  48000000  16  264105248  87 nanoset.NanoSet
     ...
     3     113   0   8716880   3  300851404  99 list
     ...
```
```python
>>> l = [nanoset.PicoSet({x}) for x in range(1000000)]
>>> guppy.hpy().heap()
Partition of a set of 1036905 objects. Total size = 44998965 bytes.
 Index  Count   %     Size   %   Cumulative  %  Kind (class / dict of class)
     0 1000000  96 32000000  71   32000000   71 nanoset.PicoSet
     1      96   0  8712752  24   32712752   89 list
     ...
```

On the second run, we have about the same order of allocated memory, saving
**16 MB** (**16** bytes saved by switching from `NanoSet` to `PicoSet` times
**1,000,000** instances). However, the garbage collector has no idea where
some of the memory is, because `PicoSet` hides the sets it allocates (this is
fine: it will be deallocated along with the `PicoSet`).

As such, I'd advise avoiding using `PicoSet` when debugging, which can be done
easily with Python's `__debug__` flag:
```python
if __debug__:
    from nanoset import NanoSet as set
else:
    from nanoset import PicoSet as set
```
This will cause `PicoSet` to be used instead of `NanoSet` when running Python
with the `-O` flag.


### πŸ“ˆ Statistics

Okay, so let's do some maths. With `S = 232` the size of an allocated set,
`s` the size of the wrapper (`48` for `NanoSet`, `32` for `PicoSet`), the
`x` percentage of nonempty sets in our data structure, the relative size
of our sets is:

  * if we're using `set`: **S \* x / (S \* x) = 100%** (we use that as a reference)
  * if we're using `nanoset`: **((S + s) \* x + s \* (100 - x)) / (S \* x)**

This gives us the following graph, which shows how much memory you can save
depending of the ratio of empty sets you have at runtime:

![sizegraph](https://github.com/althonos/nanoset.py/raw/master/static/sizegraph.svg?sanitize=true)

If we get back to our NCBITaxon example, we have a total of **1,595,237** nodes
and **1,130,671** leaves, which means that by using sets we are allocating
**1,595,237 * 232 = 328.6 MiB** of memory simply for `set` after the whole
taxonomy is loaded. If we use `NanoSet` however, we
can reduce this to **168.7 MiB**, or even to **144.4 MiB** with `PicoSet`!
**We just saved about 45% memory just by using `NanoSet` in place of `set`.**


## πŸ”§ Installing

This module is implemented in Rust, but native [Python wheels](https://pythonwheels.com/)
are compiled for the following platforms:

* Windows x86-64: CPython 3.5, 3.6, 3.7, 3.8
* Linux x86-64: CPython 3.5, 3.6, 3.7, 3.8
* OSX x86-64: CPython 3.5, 3.6, 3.7, 3.8

If you platform is not among these, you will need a
[working Rust `nightly` toolchain](https://www.rust-lang.org/tools/install)
as well as the [`setuptools-rust`](https://pypi.org/project/setuptools-rust/)
library installed to build the extension module.

Then, simply install with `pip`:
```console
$ pip install --user nanoset
```

## πŸ“– API Reference

Well, this is a comprehensive wrapper for `set`, so you can just read the
[standard library documentation](https://docs.python.org/3.7/library/stdtypes.html#set-types-set-frozenset).
Except for some very particular edge-cases, `NanoSet` and `PicoSet` both pass the
[`set` test suite](https://github.com/python/cpython/blob/master/Lib/test/test_set.py)
of [CPython](https://github.com/python/cpython).

There are however things you *can't* do:
- Subclassing a `PicoSet` or a `NanoSet`.
- Weakrefing a `PicoSet` or a `NanoSet`.
- Checking for membership in a plain `set` or `frozenset` with implicit
  conversion to `frozenset`.
- Creating a `dict` from a `PicoSet` or a `NanoSet` without rehashing keys.

## πŸ“œ License

This library is provided under the open-source [MIT license](https://choosealicense.com/licenses/mit/).




%package -n python3-nanoset
Summary:	A memory-optimized wrapper for Python sets likely to be empty.
Provides:	python-nanoset
BuildRequires:	python3-devel
BuildRequires:	python3-setuptools
BuildRequires:	python3-pip
BuildRequires:	python3-cffi
BuildRequires:	gcc
BuildRequires:	gdb
%description -n python3-nanoset
# `nanoset.py` [![starme](https://img.shields.io/github/stars/althonos/nanoset.py.svg?style=social&label=Star)](https://github.com/althonos/nanoset.py)

*A memory-optimized wrapper for Python sets likely to be empty.*

[![TravisCI](https://img.shields.io/travis/althonos/nanoset.py/master.svg?logo=travis&maxAge=600&style=flat-square)](https://travis-ci.org/althonos/nanoset.py/branches)
[![AppVeyor](https://img.shields.io/appveyor/ci/althonos/nanoset-py/master?logo=appveyor&style=flat-square&maxAge=600)](https://ci.appveyor.com/project/althonos/nanoset-py)
[![License](https://img.shields.io/badge/license-MIT-blue.svg?style=flat-square&maxAge=2678400)](https://choosealicense.com/licenses/mit/)
[![Source](https://img.shields.io/badge/source-GitHub-303030.svg?maxAge=2678400&style=flat-square)](https://github.com/althonos/nanoset.py/)
[![PyPI](https://img.shields.io/pypi/v/nanoset.svg?style=flat-square&maxAge=600)](https://pypi.org/project/nanoset)
[![Crates](https://img.shields.io/crates/v/nanoset-py?style=flat-square&maxAge=600)](https://crates.io/crates/nanoset-py)
[![Wheel](https://img.shields.io/pypi/wheel/nanoset.svg?style=flat-square&maxAge=3600)](https://pypi.org/project/nanoset/#files)
[![Python Versions](https://img.shields.io/pypi/pyversions/nanoset.svg?style=flat-square&maxAge=600)](https://pypi.org/project/nanoset/#files)
[![Python Implementations](https://img.shields.io/pypi/implementation/nanoset.svg?style=flat-square&maxAge=600)](https://pypi.org/project/nanoset/#files)
[![Changelog](https://img.shields.io/badge/keep%20a-changelog-8A0707.svg?maxAge=2678400&style=flat-square)](https://github.com/althonos/nanoset.py/blob/master/CHANGELOG.md)
[![GitHub issues](https://img.shields.io/github/issues/althonos/nanoset.py.svg?style=flat-square&maxAge=600)](https://github.com/althonos/nanoset.py/issues)

## ⏱️ TL;DR

Save up to 85% of the memory used by empty `set` instances in your code with
a single line of code:
```python
from nanoset import PicoSet as set
```

## 🚩 Table of Contents

- [Overview](#-overview)
  * [About Python memory usage](#-about-python-memory-usage)
  * [Simple example usecase](#-simple-example-usecase)
  * [Implementation](#-implementation)
  * [Statistics](#-statistics)
- [Installing](#-installing)
- [API Reference](#-api-reference)
- [License](#-license)


## πŸ—ΊοΈ Overview

### 🐏 About Python memory usage

Python is a great programming language (*fight me*), but sometimes you start
questioning why it does things in certain ways. Since Python 2.3, the standard
library provides the [`set`](https://docs.python.org/3.7/library/stdtypes.html#set)
collection, which is a specialized container for membership testing. On the
contrary to the ubiquitous [`list`](https://docs.python.org/3.7/library/stdtypes.html#list)
collection, `set` is not ordered (or, more accurately, *does not let you access
the order it stores the elements in*). The other feature of `set` is that just
like its mathematical counterpart, it does not allow duplicates, which is very
useful for some algorithms. However, **sets are memory-expensive**:
```python
>>> import sys
>>> sys.getsizeof(list())
56
>>> sys.getsizeof(set())
216
```

An empty set takes more than three times the memory of an empty list! For some
data structures or objects with a lot of `set` attributes, they can quickly
cause a very large part of the memory to be used for nothing. This is even more
sad when you are used to [Rust](https://www.rust-lang.org/), where most
[collections](https://doc.rust-lang.org/std/collections/) allocate lazily.
**This is where `nanoset` comes to the rescue:**
```python
>>> import nanoset
>>> sys.getsizeof(nanoset.NanoSet())
48
>>> sys.getsizeof(nanoset.PicoSet())
32
```

*Actually, that's a lie, but keep reading*.

### πŸ’‘ Simple example usecase

Let's imagine we are building an ordered graph data structure, where we may
want to store [taxonomic data](https://en.wikipedia.org/wiki/Taxonomic_database),
or any other kind of hierarchy. We can simply define the graphs and its nodes
with the two following classes:

```python
class Graph:
    root: Node
    nodes: Dict[str, Node]

class Node:
    neighbors: Set[node]
```

This makes adding an edge and querying for an edge existence between two nodes
an `O(1)` operation, and iterating over all the nodes an `O(n)` operation, which
is mot likely what we want here. We use `set` and not `list` because we want to
avoid storing an edge in duplicate, which is a sensible choice. But now let's
look at the [statistics](https://terminologies.gfbio.org/terminology/?ontology=NCBITAXON)
of the [NCBITaxon](https://www.ncbi.nlm.nih.gov/taxonomy) project, the
database for Organismal Classification developed by the US National Center for
Biotechnology Information:

```ignore
 Metrics
    Number of classes*: 1595237
    Number of individuals: 0
    Number of properties: 0
    Classes without definition: 1595237
    Classes without label: 0
    Average number of children: 12
    Classes with a single child: 40319
    Maximum number of children: 41761
    Classes with more than 25 children: 0
    Classes with more than 1 parent: 0
    Maximum depth: 38
    Number of leaves**: 1130671
```

According to these, we are going to have **1,130,671** leaves for a total of
**1,595,237** nodes, which means **70.8%** of empty sets. Now you may think:

> Ok, I got this. But in this case, I just need a special case for leaves, where
> instead of storing an empty set of `neighbors`, I store a reference to `None`
> when that set would be empty. I can then replace that reference with an actual
> set only when I want to add new edges from that node. Problem solved!

Well, glad we are on the same level: this is what **`nanoset`** does for you!


### πŸ”¨ Implementation

Actually, it's not magic at all. Just imagine a class `NanoSet` that works as
a [proxy](https://www.tutorialspoint.com/python_design_patterns/python_design_patterns_proxy.htm)
to an actual Python `set` it wraps, but which is only allocated when some data
actually needs to be stored:

```python
class NanoSet(collections.abc.Set):

    def __init__(self, iterable=None):
        self.inner = None if iterable is None else set(iterable)

    def add(self, element):
        if self.inner is None:
            self.inner = set()
        self.inner.add(element)

    # ... the rest of the `set` API ...
```

That's about it! However, doing it like so in Python would not be super
efficient, as the resulting object would be **48** bytes. Using
[slots](http://book.pythontips.com/en/latest/__slots__magic.html), this can be
reduced to **40** bytes, which is on par to what we get with **`NanoSet`**.

**Note that these values are only when the inner set is empty!** When actually
allocating the set to store our values, we allocate an additional **232** bytes
of data. This means that using **`NanoSet`** creates an overhead, since a
non-empty set will now weigh **264** bytes (**248** bytes for **`PicoSet`**).

> Well, I was way better off with my approach of storing `Optional[Set]`
> everywhere then, I don't want to pay any additional cost for nonempty sets!

Sure. But that would mean changing your whole code. And actually, you may not
gain that much memory from doing that compared to using `nanoset`, since the
only time the wrapper performs badly is when you have a load factor of more than
90%. Furthermore, just to give you some perspective, `sys.getsizeof(1)` is
**28** bytes.

> By the way, you didn't mention `PicoSet`. How did you manage to get that down
> to **32** bytes, when a slotted Python object can't be less that **40** bytes?

Easy: `PicoSet` is basically `NanoSet`, but without an implementation of the
[Garbage Collector protocol](https://docs.python.org/3/c-api/gcsupport.html).
This saves us **8** bytes of object memory, but comes with a drawback: the
garbage collector cannot see the set allocated *inside* the `PicoSet`. This
does not change anything for execution, but debugging with a memory profiler
will be harder. Here is an example where we allocate **1,000,000** singletons
first with `NanoSet`, then with `PicoSet`, using
[`guppy3`](https://pypi.org/project/guppy3/) to check the heap:

```python
>>> l = [nanoset.NanoSet({x}) for x in range(1000000)]
>>> guppy.hpy().heap()
Partition of a set of 3036763 objects. Total size = 304996526 bytes.
 Index  Count   %     Size    %   Cumulative %  Kind (class / dict of class)
     0 1000044  33 216105248  71  216105248  71 set
     1 1000000  33  48000000  16  264105248  87 nanoset.NanoSet
     ...
     3     113   0   8716880   3  300851404  99 list
     ...
```
```python
>>> l = [nanoset.PicoSet({x}) for x in range(1000000)]
>>> guppy.hpy().heap()
Partition of a set of 1036905 objects. Total size = 44998965 bytes.
 Index  Count   %     Size   %   Cumulative  %  Kind (class / dict of class)
     0 1000000  96 32000000  71   32000000   71 nanoset.PicoSet
     1      96   0  8712752  24   32712752   89 list
     ...
```

On the second run, we have about the same order of allocated memory, saving
**16 MB** (**16** bytes saved by switching from `NanoSet` to `PicoSet` times
**1,000,000** instances). However, the garbage collector has no idea where
some of the memory is, because `PicoSet` hides the sets it allocates (this is
fine: it will be deallocated along with the `PicoSet`).

As such, I'd advise avoiding using `PicoSet` when debugging, which can be done
easily with Python's `__debug__` flag:
```python
if __debug__:
    from nanoset import NanoSet as set
else:
    from nanoset import PicoSet as set
```
This will cause `PicoSet` to be used instead of `NanoSet` when running Python
with the `-O` flag.


### πŸ“ˆ Statistics

Okay, so let's do some maths. With `S = 232` the size of an allocated set,
`s` the size of the wrapper (`48` for `NanoSet`, `32` for `PicoSet`), the
`x` percentage of nonempty sets in our data structure, the relative size
of our sets is:

  * if we're using `set`: **S \* x / (S \* x) = 100%** (we use that as a reference)
  * if we're using `nanoset`: **((S + s) \* x + s \* (100 - x)) / (S \* x)**

This gives us the following graph, which shows how much memory you can save
depending of the ratio of empty sets you have at runtime:

![sizegraph](https://github.com/althonos/nanoset.py/raw/master/static/sizegraph.svg?sanitize=true)

If we get back to our NCBITaxon example, we have a total of **1,595,237** nodes
and **1,130,671** leaves, which means that by using sets we are allocating
**1,595,237 * 232 = 328.6 MiB** of memory simply for `set` after the whole
taxonomy is loaded. If we use `NanoSet` however, we
can reduce this to **168.7 MiB**, or even to **144.4 MiB** with `PicoSet`!
**We just saved about 45% memory just by using `NanoSet` in place of `set`.**


## πŸ”§ Installing

This module is implemented in Rust, but native [Python wheels](https://pythonwheels.com/)
are compiled for the following platforms:

* Windows x86-64: CPython 3.5, 3.6, 3.7, 3.8
* Linux x86-64: CPython 3.5, 3.6, 3.7, 3.8
* OSX x86-64: CPython 3.5, 3.6, 3.7, 3.8

If you platform is not among these, you will need a
[working Rust `nightly` toolchain](https://www.rust-lang.org/tools/install)
as well as the [`setuptools-rust`](https://pypi.org/project/setuptools-rust/)
library installed to build the extension module.

Then, simply install with `pip`:
```console
$ pip install --user nanoset
```

## πŸ“– API Reference

Well, this is a comprehensive wrapper for `set`, so you can just read the
[standard library documentation](https://docs.python.org/3.7/library/stdtypes.html#set-types-set-frozenset).
Except for some very particular edge-cases, `NanoSet` and `PicoSet` both pass the
[`set` test suite](https://github.com/python/cpython/blob/master/Lib/test/test_set.py)
of [CPython](https://github.com/python/cpython).

There are however things you *can't* do:
- Subclassing a `PicoSet` or a `NanoSet`.
- Weakrefing a `PicoSet` or a `NanoSet`.
- Checking for membership in a plain `set` or `frozenset` with implicit
  conversion to `frozenset`.
- Creating a `dict` from a `PicoSet` or a `NanoSet` without rehashing keys.

## πŸ“œ License

This library is provided under the open-source [MIT license](https://choosealicense.com/licenses/mit/).




%package help
Summary:	Development documents and examples for nanoset
Provides:	python3-nanoset-doc
%description help
# `nanoset.py` [![starme](https://img.shields.io/github/stars/althonos/nanoset.py.svg?style=social&label=Star)](https://github.com/althonos/nanoset.py)

*A memory-optimized wrapper for Python sets likely to be empty.*

[![TravisCI](https://img.shields.io/travis/althonos/nanoset.py/master.svg?logo=travis&maxAge=600&style=flat-square)](https://travis-ci.org/althonos/nanoset.py/branches)
[![AppVeyor](https://img.shields.io/appveyor/ci/althonos/nanoset-py/master?logo=appveyor&style=flat-square&maxAge=600)](https://ci.appveyor.com/project/althonos/nanoset-py)
[![License](https://img.shields.io/badge/license-MIT-blue.svg?style=flat-square&maxAge=2678400)](https://choosealicense.com/licenses/mit/)
[![Source](https://img.shields.io/badge/source-GitHub-303030.svg?maxAge=2678400&style=flat-square)](https://github.com/althonos/nanoset.py/)
[![PyPI](https://img.shields.io/pypi/v/nanoset.svg?style=flat-square&maxAge=600)](https://pypi.org/project/nanoset)
[![Crates](https://img.shields.io/crates/v/nanoset-py?style=flat-square&maxAge=600)](https://crates.io/crates/nanoset-py)
[![Wheel](https://img.shields.io/pypi/wheel/nanoset.svg?style=flat-square&maxAge=3600)](https://pypi.org/project/nanoset/#files)
[![Python Versions](https://img.shields.io/pypi/pyversions/nanoset.svg?style=flat-square&maxAge=600)](https://pypi.org/project/nanoset/#files)
[![Python Implementations](https://img.shields.io/pypi/implementation/nanoset.svg?style=flat-square&maxAge=600)](https://pypi.org/project/nanoset/#files)
[![Changelog](https://img.shields.io/badge/keep%20a-changelog-8A0707.svg?maxAge=2678400&style=flat-square)](https://github.com/althonos/nanoset.py/blob/master/CHANGELOG.md)
[![GitHub issues](https://img.shields.io/github/issues/althonos/nanoset.py.svg?style=flat-square&maxAge=600)](https://github.com/althonos/nanoset.py/issues)

## ⏱️ TL;DR

Save up to 85% of the memory used by empty `set` instances in your code with
a single line of code:
```python
from nanoset import PicoSet as set
```

## 🚩 Table of Contents

- [Overview](#-overview)
  * [About Python memory usage](#-about-python-memory-usage)
  * [Simple example usecase](#-simple-example-usecase)
  * [Implementation](#-implementation)
  * [Statistics](#-statistics)
- [Installing](#-installing)
- [API Reference](#-api-reference)
- [License](#-license)


## πŸ—ΊοΈ Overview

### 🐏 About Python memory usage

Python is a great programming language (*fight me*), but sometimes you start
questioning why it does things in certain ways. Since Python 2.3, the standard
library provides the [`set`](https://docs.python.org/3.7/library/stdtypes.html#set)
collection, which is a specialized container for membership testing. On the
contrary to the ubiquitous [`list`](https://docs.python.org/3.7/library/stdtypes.html#list)
collection, `set` is not ordered (or, more accurately, *does not let you access
the order it stores the elements in*). The other feature of `set` is that just
like its mathematical counterpart, it does not allow duplicates, which is very
useful for some algorithms. However, **sets are memory-expensive**:
```python
>>> import sys
>>> sys.getsizeof(list())
56
>>> sys.getsizeof(set())
216
```

An empty set takes more than three times the memory of an empty list! For some
data structures or objects with a lot of `set` attributes, they can quickly
cause a very large part of the memory to be used for nothing. This is even more
sad when you are used to [Rust](https://www.rust-lang.org/), where most
[collections](https://doc.rust-lang.org/std/collections/) allocate lazily.
**This is where `nanoset` comes to the rescue:**
```python
>>> import nanoset
>>> sys.getsizeof(nanoset.NanoSet())
48
>>> sys.getsizeof(nanoset.PicoSet())
32
```

*Actually, that's a lie, but keep reading*.

### πŸ’‘ Simple example usecase

Let's imagine we are building an ordered graph data structure, where we may
want to store [taxonomic data](https://en.wikipedia.org/wiki/Taxonomic_database),
or any other kind of hierarchy. We can simply define the graphs and its nodes
with the two following classes:

```python
class Graph:
    root: Node
    nodes: Dict[str, Node]

class Node:
    neighbors: Set[node]
```

This makes adding an edge and querying for an edge existence between two nodes
an `O(1)` operation, and iterating over all the nodes an `O(n)` operation, which
is mot likely what we want here. We use `set` and not `list` because we want to
avoid storing an edge in duplicate, which is a sensible choice. But now let's
look at the [statistics](https://terminologies.gfbio.org/terminology/?ontology=NCBITAXON)
of the [NCBITaxon](https://www.ncbi.nlm.nih.gov/taxonomy) project, the
database for Organismal Classification developed by the US National Center for
Biotechnology Information:

```ignore
 Metrics
    Number of classes*: 1595237
    Number of individuals: 0
    Number of properties: 0
    Classes without definition: 1595237
    Classes without label: 0
    Average number of children: 12
    Classes with a single child: 40319
    Maximum number of children: 41761
    Classes with more than 25 children: 0
    Classes with more than 1 parent: 0
    Maximum depth: 38
    Number of leaves**: 1130671
```

According to these, we are going to have **1,130,671** leaves for a total of
**1,595,237** nodes, which means **70.8%** of empty sets. Now you may think:

> Ok, I got this. But in this case, I just need a special case for leaves, where
> instead of storing an empty set of `neighbors`, I store a reference to `None`
> when that set would be empty. I can then replace that reference with an actual
> set only when I want to add new edges from that node. Problem solved!

Well, glad we are on the same level: this is what **`nanoset`** does for you!


### πŸ”¨ Implementation

Actually, it's not magic at all. Just imagine a class `NanoSet` that works as
a [proxy](https://www.tutorialspoint.com/python_design_patterns/python_design_patterns_proxy.htm)
to an actual Python `set` it wraps, but which is only allocated when some data
actually needs to be stored:

```python
class NanoSet(collections.abc.Set):

    def __init__(self, iterable=None):
        self.inner = None if iterable is None else set(iterable)

    def add(self, element):
        if self.inner is None:
            self.inner = set()
        self.inner.add(element)

    # ... the rest of the `set` API ...
```

That's about it! However, doing it like so in Python would not be super
efficient, as the resulting object would be **48** bytes. Using
[slots](http://book.pythontips.com/en/latest/__slots__magic.html), this can be
reduced to **40** bytes, which is on par to what we get with **`NanoSet`**.

**Note that these values are only when the inner set is empty!** When actually
allocating the set to store our values, we allocate an additional **232** bytes
of data. This means that using **`NanoSet`** creates an overhead, since a
non-empty set will now weigh **264** bytes (**248** bytes for **`PicoSet`**).

> Well, I was way better off with my approach of storing `Optional[Set]`
> everywhere then, I don't want to pay any additional cost for nonempty sets!

Sure. But that would mean changing your whole code. And actually, you may not
gain that much memory from doing that compared to using `nanoset`, since the
only time the wrapper performs badly is when you have a load factor of more than
90%. Furthermore, just to give you some perspective, `sys.getsizeof(1)` is
**28** bytes.

> By the way, you didn't mention `PicoSet`. How did you manage to get that down
> to **32** bytes, when a slotted Python object can't be less that **40** bytes?

Easy: `PicoSet` is basically `NanoSet`, but without an implementation of the
[Garbage Collector protocol](https://docs.python.org/3/c-api/gcsupport.html).
This saves us **8** bytes of object memory, but comes with a drawback: the
garbage collector cannot see the set allocated *inside* the `PicoSet`. This
does not change anything for execution, but debugging with a memory profiler
will be harder. Here is an example where we allocate **1,000,000** singletons
first with `NanoSet`, then with `PicoSet`, using
[`guppy3`](https://pypi.org/project/guppy3/) to check the heap:

```python
>>> l = [nanoset.NanoSet({x}) for x in range(1000000)]
>>> guppy.hpy().heap()
Partition of a set of 3036763 objects. Total size = 304996526 bytes.
 Index  Count   %     Size    %   Cumulative %  Kind (class / dict of class)
     0 1000044  33 216105248  71  216105248  71 set
     1 1000000  33  48000000  16  264105248  87 nanoset.NanoSet
     ...
     3     113   0   8716880   3  300851404  99 list
     ...
```
```python
>>> l = [nanoset.PicoSet({x}) for x in range(1000000)]
>>> guppy.hpy().heap()
Partition of a set of 1036905 objects. Total size = 44998965 bytes.
 Index  Count   %     Size   %   Cumulative  %  Kind (class / dict of class)
     0 1000000  96 32000000  71   32000000   71 nanoset.PicoSet
     1      96   0  8712752  24   32712752   89 list
     ...
```

On the second run, we have about the same order of allocated memory, saving
**16 MB** (**16** bytes saved by switching from `NanoSet` to `PicoSet` times
**1,000,000** instances). However, the garbage collector has no idea where
some of the memory is, because `PicoSet` hides the sets it allocates (this is
fine: it will be deallocated along with the `PicoSet`).

As such, I'd advise avoiding using `PicoSet` when debugging, which can be done
easily with Python's `__debug__` flag:
```python
if __debug__:
    from nanoset import NanoSet as set
else:
    from nanoset import PicoSet as set
```
This will cause `PicoSet` to be used instead of `NanoSet` when running Python
with the `-O` flag.


### πŸ“ˆ Statistics

Okay, so let's do some maths. With `S = 232` the size of an allocated set,
`s` the size of the wrapper (`48` for `NanoSet`, `32` for `PicoSet`), the
`x` percentage of nonempty sets in our data structure, the relative size
of our sets is:

  * if we're using `set`: **S \* x / (S \* x) = 100%** (we use that as a reference)
  * if we're using `nanoset`: **((S + s) \* x + s \* (100 - x)) / (S \* x)**

This gives us the following graph, which shows how much memory you can save
depending of the ratio of empty sets you have at runtime:

![sizegraph](https://github.com/althonos/nanoset.py/raw/master/static/sizegraph.svg?sanitize=true)

If we get back to our NCBITaxon example, we have a total of **1,595,237** nodes
and **1,130,671** leaves, which means that by using sets we are allocating
**1,595,237 * 232 = 328.6 MiB** of memory simply for `set` after the whole
taxonomy is loaded. If we use `NanoSet` however, we
can reduce this to **168.7 MiB**, or even to **144.4 MiB** with `PicoSet`!
**We just saved about 45% memory just by using `NanoSet` in place of `set`.**


## πŸ”§ Installing

This module is implemented in Rust, but native [Python wheels](https://pythonwheels.com/)
are compiled for the following platforms:

* Windows x86-64: CPython 3.5, 3.6, 3.7, 3.8
* Linux x86-64: CPython 3.5, 3.6, 3.7, 3.8
* OSX x86-64: CPython 3.5, 3.6, 3.7, 3.8

If you platform is not among these, you will need a
[working Rust `nightly` toolchain](https://www.rust-lang.org/tools/install)
as well as the [`setuptools-rust`](https://pypi.org/project/setuptools-rust/)
library installed to build the extension module.

Then, simply install with `pip`:
```console
$ pip install --user nanoset
```

## πŸ“– API Reference

Well, this is a comprehensive wrapper for `set`, so you can just read the
[standard library documentation](https://docs.python.org/3.7/library/stdtypes.html#set-types-set-frozenset).
Except for some very particular edge-cases, `NanoSet` and `PicoSet` both pass the
[`set` test suite](https://github.com/python/cpython/blob/master/Lib/test/test_set.py)
of [CPython](https://github.com/python/cpython).

There are however things you *can't* do:
- Subclassing a `PicoSet` or a `NanoSet`.
- Weakrefing a `PicoSet` or a `NanoSet`.
- Checking for membership in a plain `set` or `frozenset` with implicit
  conversion to `frozenset`.
- Creating a `dict` from a `PicoSet` or a `NanoSet` without rehashing keys.

## πŸ“œ License

This library is provided under the open-source [MIT license](https://choosealicense.com/licenses/mit/).




%prep
%autosetup -n nanoset-0.2.1

%build
%py3_build

%install
%py3_install
install -d -m755 %{buildroot}/%{_pkgdocdir}
if [ -d doc ]; then cp -arf doc %{buildroot}/%{_pkgdocdir}; fi
if [ -d docs ]; then cp -arf docs %{buildroot}/%{_pkgdocdir}; fi
if [ -d example ]; then cp -arf example %{buildroot}/%{_pkgdocdir}; fi
if [ -d examples ]; then cp -arf examples %{buildroot}/%{_pkgdocdir}; fi
pushd %{buildroot}
if [ -d usr/lib ]; then
	find usr/lib -type f -printf "\"/%h/%f\"\n" >> filelist.lst
fi
if [ -d usr/lib64 ]; then
	find usr/lib64 -type f -printf "\"/%h/%f\"\n" >> filelist.lst
fi
if [ -d usr/bin ]; then
	find usr/bin -type f -printf "\"/%h/%f\"\n" >> filelist.lst
fi
if [ -d usr/sbin ]; then
	find usr/sbin -type f -printf "\"/%h/%f\"\n" >> filelist.lst
fi
touch doclist.lst
if [ -d usr/share/man ]; then
	find usr/share/man -type f -printf "\"/%h/%f.gz\"\n" >> doclist.lst
fi
popd
mv %{buildroot}/filelist.lst .
mv %{buildroot}/doclist.lst .

%files -n python3-nanoset -f filelist.lst
%dir %{python3_sitearch}/*

%files help -f doclist.lst
%{_docdir}/*

%changelog
* Fri Jun 09 2023 Python_Bot <Python_Bot@openeuler.org> - 0.2.1-1
- Package Spec generated