Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add new Combinatorics node (WIP) #2346

Merged
merged 2 commits into from
Dec 29, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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.


1 change: 1 addition & 0 deletions index.md
Original file line number Diff line number Diff line change
Expand Up @@ -314,6 +314,7 @@
---
SvSpiralNode
SvExportGcodeNode
SvCombinatoricsNode

## Alpha Nodes
SvCurveViewerNode
Expand Down
167 changes: 167 additions & 0 deletions nodes/list_mutators/combinatorics.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,167 @@
# ##### BEGIN GPL LICENSE BLOCK #####
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# ##### END GPL LICENSE BLOCK #####

import bpy
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)

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))
}

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"}


class SvCombinatoricsNode(bpy.types.Node, SverchCustomTreeNode):
"""
Triggers: Product, Permutations, Combinations
Tooltip: Generate various combinatoric operations
"""
bl_idname = 'SvCombinatoricsNode'
bl_label = 'Combinatorics'

def update_operation(self, context):
self.label = self.operation.title()
self.update_sockets()
updateNode(self, context)

operation = EnumProperty(
name="Operation", items=operationItems,
description="Operation type", default="PRODUCT",
update=update_operation)

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

length = IntProperty(
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', "A")
self.inputs.new('StringsSocket', "B")

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

self.update_operation(context)

def update(self):
''' Add/remove sockets as A-Z sockets are connected/disconnected '''

# not a multiple quaternion operation ? => no need to update sockets
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

which quaternions?!

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

oops. cut and paste :)

if self.operation not in multiple_input_operations:
return

inputs = self.inputs

# get all existing A-Z sockets (connected or not)
inputs_AZ = list(filter(lambda s: s.name in ABC, inputs))

# last A-Z socket connected ? => add an empty A-Z socket at the end
if inputs_AZ[-1].links:
name = ABC[len(inputs_AZ)] # pick the next letter A to Z
inputs.new("StringsSocket", name)

else: # last input disconnected ? => remove all but last unconnected
while len(inputs_AZ) > 2 and not inputs_AZ[-2].links:
s = inputs_AZ[-1]
inputs.remove(s)
inputs_AZ.remove(s)

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

inputs = self.inputs

# update the A-Z input sockets
if self.operation in multiple_input_operations:
if not "B" in inputs:
inputs.new("StringsSocket", "B")
else:
for a in ABC[1:]: # remove all B-Z inputs (keep A)
if a in inputs:
inputs.remove(inputs[a])

# 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"}:
inputs["Repeat"].hide_safe = True
if inputs["Length"].hide:
inputs["Length"].hide_safe = False

def draw_buttons(self, context, layout):
layout.prop(self, "operation", text="")

def process(self):
outputs = self.outputs
# return if no outputs are connected
if not any(s.is_linked for s in outputs):
return

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))

# collect the data inputs from all connected AZ sockets
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])
else: # PERMUTATIONS / COMBINATIONS
L = inputs["Length"].sv_get()[0]
L = list(map(lambda x: max(0, int(x)), L))
parameters = match_long_repeat([I, L])

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)


def register():
bpy.utils.register_class(SvCombinatoricsNode)


def unregister():
bpy.utils.unregister_class(SvCombinatoricsNode)