Skip to content

Commit

Permalink
Add documentation + optimize and cleanup code
Browse files Browse the repository at this point in the history
  • Loading branch information
DolphinDream committed Dec 29, 2018
1 parent ad968de commit 321544a
Show file tree
Hide file tree
Showing 2 changed files with 178 additions and 50 deletions.
142 changes: 142 additions & 0 deletions docs/nodes/list_mutators/combinatorics.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
Combinatorics
=============

Functionality
-------------

Combinatorics node performs various combinatoric operations like: **Product**, **Permutations** and **Combinations**.


Inputs
------

The inputs to the node are a set of lists of any type and a set of control parameters.

The list inputs in combination to the control parameter inputs (Repeat / Length) are vectorized and the control parameters accept either single or multiple values for vectorization.

List inputs to the node:
- **A**
- **B** [1]
...
- **Z** [1]

Notes:
[1] : The multiple list inputs are available for the **Product** operation, all the other operations take one list input. For the **Product** operation as the last list input is connected a new empty input socket will appear to allow other lists to be connected.


Parameters
----------

The **Operation** parameter allows to select one of following operations: Product, Permutations and Combinations.

All parameters except **Operation** can be given as an external input.

+---------------+---------------+----------+--------------------------------------------+
| Param | Type | Default | Description |
+===============+===============+==========+============================================+
| **Operation** | Enum: | Product | See details in the Operations section. |
| | Product | | |
| | Permutations | | |
| | Combinations | | |
+---------------+---------------+----------+--------------------------------------------+
| **Repeat** | Int | 1 | Repeat the input lists this many times [1] |
+---------------+---------------+----------+--------------------------------------------+
| **Length** | Int | 1 | The number of the elements in the list to |
| | | | operate on [2] |
+---------------+---------------+----------+--------------------------------------------+
| **A** | List | | The list of elements to operate on. |
+---------------+---------------+----------+--------------------------------------------+
| **B..Z** | List | | Additional lists to operate on [3] |
+---------------+---------------+----------+--------------------------------------------+

Notes:
[1] : The Repeat parameter is only available for the **Product** operation.
[2] : The Length parameter is only available for the **Permutations** and **Combinations** operation.
[3] : Additional lists inputs are available only for the **Product** operation.

Operations
----------

**Product**

For this operation the node allows an arbitrary number of input lists to be product together as: A x B x .. x Z. The result of the product operation is a list of elements each of size equal to the number of input lists and has all the combinations of elements from the first list, followed by all elements in the second list etc.

e.g. for two connected list inputs:

A : ["X", "Y"]
B : [1, 2, 3]

The result A x B is:

["X", "Y"] x [1, 2, 3] => [ ["X", 1], ["X", 2], ["X", 3], ["Y", 1], ["Y", 2], ["Y", 3] ]

The value of the **Repeat** parameter makes the node compute the product of all the connected lists replicated this number of times.

e.g. for one connected input with repeat value of 2:

A : ["X", "Y"]
Repeat: 2

The result A x A is:

["X", "Y"] x ["X", "Y"] => [ ["X", "X"], ["X", "Y"], ["Y", "X"], ["Y", "Y"] ]


**Permutations**

For this operation the node take a single input list and generates the permutations of its elements. The **Length** parameter sets the number of elements in the list to be permutated.

Notes:
* If the **Length** is zero, the node will permute ALL elements in the list.
* The **Length** value is bounded between zero and the length of the input list, so any length values larger than the length of the input list is equivalent to permuting ALL elements in the list.

e.g. for a list of 3 (mixed) elements:

A: ["X", 3, (1,1,1)]
L: 3

The result is:

[
['X', 3, (1, 1, 1)],
['X', (1, 1, 1), 3],
[3, 'X', (1, 1, 1)],
[3, (1, 1, 1), 'X'],
[(1, 1, 1), 'X', 3],
[(1, 1, 1), 3, 'X']
]

**Combinations**

For this operation the node takes a single list as input and generates the combinations of its elements taking L number of elements given by the **Length** parameter.

Notes:
* If the **Length** is zero, the node will combine ALL elements in the list.
* The **Length** value is bounded between zero and the length of the input list, so any length values larger than the length of the input list is equivalent to combining ALL elements.

e.g. for a list of 4 elements taken 2 elements:

A : [1, 'X', (1, 2, 3), [1, 3]]
L : 2

The result is:

[
[1, 'X'],
[1, (1, 2, 3)],
[1, [1, 3]],
['X', (1, 2, 3)],
['X', [1, 3]],
[(1, 2, 3), [1, 3]]
]


Outputs
-------

**Result**
The list of product, permutations or combinations.

The results will be generated only when the **Result** output is connected.


86 changes: 36 additions & 50 deletions nodes/list_mutators/combinatorics.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,26 +17,29 @@
# ##### END GPL LICENSE BLOCK #####

import bpy
from bpy.props import BoolProperty, IntProperty, FloatProperty, EnumProperty
from bpy.props import IntProperty, EnumProperty

from sverchok.node_tree import SverchCustomTreeNode
from sverchok.data_structure import (match_long_repeat, updateNode)

from itertools import (product, permutations, combinations, compress)
from itertools import (product, permutations, combinations)

operationItems = {
("PRODUCT", "Product", "", 0),
("PERMUTATIONS", "Permutations", "", 1),
("COMBINATIONS", "Combinations", "", 2),
operations = {
"PRODUCT": (10, lambda s, r: product(*s, repeat=r)),
"PERMUTATIONS": (20, lambda s, l: permutations(s, l)),
"COMBINATIONS": (30, lambda s, l: combinations(s, l))
}

ABC = tuple('ABCDEFGHIJKLMNOPQRSTUVWXYZ') # input socket labels
operationItems = [(k, k.title(), "", s[0]) for k, s in sorted(operations.items(), key=lambda k: k[1][0])]

ABC = tuple('ABCDEFGHIJKLMNOPQRSTUVWXYZ') # input socket labels

multiple_input_operations = {"PRODUCT"}

multiple_input_operations = { "PRODUCT" }

class SvCombinatoricsNode(bpy.types.Node, SverchCustomTreeNode):
"""
Triggers: Product, Permutation, Combination
Triggers: Product, Permutations, Combinations
Tooltip: Generate various combinatoric operations
"""
bl_idname = 'SvCombinatoricsNode'
Expand All @@ -53,23 +56,22 @@ def update_operation(self, context):
update=update_operation)

repeat = IntProperty(
name='Repeat', description='Repeat the sequence',
name='Repeat', description='Repeat the list inputs this many times',
default=1, min=1, update=updateNode)

length = IntProperty(
name='Lenght', description='Lenght of the sequence',
default=1, min=1, update=updateNode)
name='Length', description='Limit the elements to operate on to this value',
default=1, min=0, update=updateNode)

def sv_init(self, context):
self.inputs.new('StringsSocket', "Repeat").prop_name = "repeat"
self.inputs.new('StringsSocket', "Length").prop_name = "length"
self.inputs.new('StringsSocket', "Selector")
self.inputs.new('StringsSocket', "A")
self.inputs.new('StringsSocket', "B")

self.outputs.new('StringsSocket', "Result")

self.operation = "PRODUCT"
self.update_operation(context)

def update(self):
''' Add/remove sockets as A-Z sockets are connected/disconnected '''
Expand All @@ -95,7 +97,7 @@ def update(self):
inputs_AZ.remove(s)

def update_sockets(self):
''' Update sockets based on current mode '''
''' Update sockets based on selected operation '''

inputs = self.inputs

Expand All @@ -104,18 +106,19 @@ def update_sockets(self):
if not "B" in inputs:
inputs.new("StringsSocket", "B")
else:
print("remove sockets")
for a in ABC[1:]: # remove all B-Z inputs (keep A)
if a in inputs:
inputs.remove(inputs[a])

# update the other sockets (operation specific)
if self.operation in { "PRODUCT" }:
inputs["Repeat"].hide_safe = False
# update the other sockets
if self.operation in {"PRODUCT"}:
if inputs["Repeat"].hide:
inputs["Repeat"].hide_safe = False
inputs["Length"].hide_safe = True
elif self.operation in { "COMBINATIONS", "PERMUTATIONS" }:
elif self.operation in {"COMBINATIONS", "PERMUTATIONS"}:
inputs["Repeat"].hide_safe = True
inputs["Length"].hide_safe = False
if inputs["Length"].hide:
inputs["Length"].hide_safe = False

def draw_buttons(self, context, layout):
layout.prop(self, "operation", text="")
Expand All @@ -126,49 +129,32 @@ def process(self):
if not any(s.is_linked for s in outputs):
return

# input values lists (single or multi value)
inputs = self.inputs

all_AZ_sockets = list(filter(lambda s: s.name in ABC, inputs))
connected_AZ_sockets = list(filter(lambda s: s.is_linked, all_AZ_sockets))

I = [] # list of all data inputs (single or multiple)

# collect the data inputs from all connected AZ sockets
for s in connected_AZ_sockets:
a = s.sv_get()[0]
I.append(a)

resultList = []
I = [s.sv_get()[0] for s in connected_AZ_sockets]

if self.operation == "PRODUCT":
R = inputs["Repeat"].sv_get()[0]
R = list(map(lambda x: max(1, int(x)), R))
parameters = match_long_repeat([[I], R])
for sequence, r in zip(*parameters):
result = product(*sequence, repeat=r)
result = [list(a) for a in result]
resultList.append(result)

elif self.operation == "PERMUTATIONS":
else: # PERMUTATIONS / COMBINATIONS
L = inputs["Length"].sv_get()[0]
L = list(map(lambda x: max(1, int(x)), L))
L = list(map(lambda x: max(0, int(x)), L))
parameters = match_long_repeat([I, L])
for sequence, l in zip(*parameters):
l = min(l, len(sequence))
result = permutations(sequence, l)
result = [list(a) for a in result]
resultList.append(result)

elif self.operation == "COMBINATIONS":
L = inputs["Length"].sv_get()[0]
L = list(map(lambda x: max(1, int(x)), L))
parameters = match_long_repeat([I, L])
for sequence, l in zip(*parameters):
l = min(l, len(sequence))
result = combinations(sequence, l)
result = [list(a) for a in result]
resultList.append(result)
function = operations[self.operation][1]

resultList = []
for sequence, v in zip(*parameters):
if self.operation in {"PERMUTATIONS", "COMBINATIONS"}:
if v == 0 or v > len(sequence):
v = len(sequence)
result = [list(a) for a in function(sequence, v)]
resultList.append(result)

outputs["Result"].sv_set(resultList)

Expand Down

0 comments on commit 321544a

Please sign in to comment.