Python and Pattern CHOP: Difference between pages

From Derivative
(Difference between pages)
Jump to navigation Jump to search
mNo edit summary
 
No edit summary
 
Line 1: Line 1:
__TOC__
{{Summary
== Python In TouchDesigner ==
|opFilter=False
TouchDesigner uses [https://www.python.org/ Python] for scripting tasks. A custom Python build is included, with most of the features of a standard Python installation and a huge number of tools and utilities specific to working in the software.  
|long=The Pattern CHOP generates a sequence of samples in a channel. Unlike the [[Wave CHOP]] its purpose is generating arrays of samples that have no reference to time (seconds or frames).
* Quick Start: [[Introduction to Python Tutorial|Tutorial: Introduction to Python in TouchDesigner]].
* Common script examples: [[Python Tips]]
It is useful for curve generation like lookup tables, simple shapes that can be converted to SOPs, generating channels that are passed to the [[Geometry COMP]] to generate instances, and other non-time-based curve-generation, with as little need to make expressions in Python.
* List of [[Python Classes and Modules|TouchDesigner Python Classes and Modules]]  
* Index of all Python pages in this wiki: [[:Category:Python_Reference|Python Reference]]
All defaults are in samples, not seconds or frames (though like all CHOPs, it carries with it a sample rate). There is no start-end, just Length in samples.
'''Tip''': To display a CHOP viewer in the units of samples, make the [[Viewer Active]] and change [[Mouse Click|RMB]] -> Units to be Samples.
The Pattern CHOP optionally takes one input CHOP to match the length and sample rate, and, choosing via the Combine Channels menu, Appends or Inserts the new channel(s), Replaces the incoming channels, Adds to the incoming channels or Multiplies the incoming channels.
The Pattern CHOP defaults to one cycle of the curve over the length of the CHOP, no matter how many samples long.
'''Tip: Customizing each channel:''' The python object for the Pattern CHOP has a <code>chanIndex</code> member, so if Pattern generates three channels you can put something like <code>[1, 3, 7][me.chanIndex]</code> in any parameter to customize its value for each channel. For example, in the Type parameter, put the expression <code>['sin', 'cos', 'ramp'][me.chanIndex]</code> to get 3 different curve types.
|opLicense=Non-Commercial
|opClass=patternCHOP_Class
|opLabel=Pattern
|opFamily=CHOP
|opType=pattern
|short=The Pattern CHOP generates a sequence of samples in a channel.
|opCategories=
}}
{{ParameterPage
|opFamily=CHOP
|pageName=Pattern
|items={{Parameter
|parName=wavetype
|parItems={{ParameterItem
|itemName=const
|opFamily=CHOP
|parName=wavetype
|itemLabel=Constant
|itemSummary=(1)
}}<!--
-->{{ParameterItem
|itemName=sin
|opFamily=CHOP
|parName=wavetype
|itemLabel=Sine
|itemSummary=(-1 to 1)
}}<!--
-->{{ParameterItem
|itemName=cos
|opFamily=CHOP
|parName=wavetype
|itemLabel=Cosine
|itemSummary=(-1 to 1)
}}<!--
-->{{ParameterItem
|itemName=tri
|opFamily=CHOP
|parName=wavetype
|itemLabel=Triangle
|itemSummary=(-1 to 1)
}}<!--
-->{{ParameterItem
|itemName=ramp
|opFamily=CHOP
|parName=wavetype
|itemLabel=Ramp
|itemSummary=(0-1)
}}<!--
-->{{ParameterItem
|itemName=rampsamples
|opFamily=CHOP
|parName=wavetype
|itemLabel=Ramp Samples
|itemSummary=(0 to numSamples-1)
}}<!--
-->{{ParameterItem
|itemName=square
|opFamily=CHOP
|parName=wavetype
|itemLabel=Square
|itemSummary=(-1 to -1)
}}<!--
-->{{ParameterItem
|itemName=pulse
|opFamily=CHOP
|parName=wavetype
|itemLabel=Pulse
|itemSummary=(0-1)
}}<!--
-->{{ParameterItem
|itemName=random
|opFamily=CHOP
|parName=wavetype
|itemLabel=Random
|itemSummary=(0-1)
}}<!--
-->{{ParameterItem
|itemName=randomcycle
|opFamily=CHOP
|parName=wavetype
|itemLabel=Random per Cycle
|itemSummary=All samples in a cycle will have the same randomly generated value.
}}<!--
-->{{ParameterItem
|itemName=randomnonrepint
|opFamily=CHOP
|parName=wavetype
|itemLabel=Random Non-Repeating Integers
|itemSummary=This wave type is used in conjunction with the Randomize pulse. Between each Randomize pulse, the random values at each sample will be non-repeating. For example in the simplest case with a channel length of 1, each time Randomize is pulsed the random value of sample 1 after the pulse will be different than the random value before the pulse.
}}<!--
-->{{ParameterItem
|itemName=step
|opFamily=CHOP
|parName=wavetype
|itemLabel=Step
|itemSummary=(0 to 1) step function
}}<!--
-->{{ParameterItem
|itemName=rampcyclic
|opFamily=CHOP
|parName=wavetype
|itemLabel=Cyclic Ramp
|itemSummary=(0 to (numSamples -1) / numSamples). Same as 'Ramp' type, but on phase shifting the value never goes out of range.
}}
|parOrder=0
|parLabel=Type
|opFamily=CHOP
|opType=pattern
|parSummary=The shape of one cycle of the pattern.
|parType=Menu
|parReadOnly=
}}
{{Parameter
|parName=length
|parOrder=1
|parLabel=Length
|opFamily=CHOP
|opType=pattern
|parSummary=Set the number of samples for this CHOP.
|parType=Int
|parReadOnly=
|parItems=
}}
{{Parameter
|parName=numcycles
|parOrder=2
|parLabel=Number of Cycles
|opFamily=CHOP
|opType=pattern
|parSummary=Set the number of repeating cycles of the Type shapes over the Length, except for Random.
|parType=Float
|parReadOnly=
|parItems=
}}
{{Parameter
|opFamily=CHOP
|opType=patternCHOP
|parLabel=Step per Cycle
|parName=steppercycle
|parType=Float
|parReadOnly=
|parOrder=3
|parSummary=
|parItems=
}}
{{Parameter
|opFamily=CHOP
|opType=patternCHOP
|parLabel=Number of Steps
|parName=numsteps
|parType=Int
|parReadOnly=
|parOrder=4
|parSummary=
|parItems=
}}
{{Parameter
|parName=bias
|parOrder=5
|parLabel=Bias
|opFamily=CHOP
|opType=pattern
|parSummary=Makes Triangle type into a sawtooth wave, and sets the Square type variable-width.
|parType=Float
|parReadOnly=
|parItems=
}}
{{Parameter
|parName=seed
|parOrder=6
|parLabel=Seed
|opFamily=CHOP
|opType=pattern
|parSummary=The seed for the random Types.
|parType=Float
|parReadOnly=
|parItems=
}}
{{Parameter
|parName=phase
|parOrder=7
|parLabel=Phase
|opFamily=CHOP
|opType=pattern
|parSummary=Shifts the cycle.
|parType=Float
|parReadOnly=
|parItems=
}}
{{Parameter
|opFamily=CHOP
|opType=patternCHOP
|parLabel=Phase Step per Channel
|parName=phasestep
|parType=Float
|parReadOnly=
|parOrder=8
|parSummary=Increases the phase for each channel. A Phase Step of .25 when there are 2 channels will shift the second channel to be 1/4 cycle later phase than the first phase, where if the 2 channels are used for x and y, will draw a circle when passed to a CHOP to SOP.
|parItems=
}}
{{Parameter
|parName=taper
|parItems={{ParameterItem
|itemName=taper1
|opFamily=CHOP
|parName=taper
|itemLabel=""
|itemSummary=
}}<!--
-->{{ParameterItem
|itemName=taper2
|opFamily=CHOP
|parName=taper
|itemLabel=""
|itemSummary=
}}
|parOrder=9
|parLabel=Taper
|opFamily=CHOP
|opType=pattern
|parSummary=Two parameters to multiply by a line from <code>taper1</code> at the start to <code>taper2</code> at the end. The default of (<code>1 1</code>) has no effect.
|parType=Float
|parReadOnly=
}}
{{Parameter
|parName=taperdecay
|parOrder=10
|parLabel=Taper Decay Rate
|opFamily=CHOP
|opType=pattern
|parSummary=An exponent that is applied to the result of the taper.
|parType=Float
|parReadOnly=
|parItems=
}}
{{Parameter
|parName=amp
|parOrder=11
|parLabel=Amplitude
|opFamily=CHOP
|opType=pattern
|parSummary=See also the Range.
|parType=Float
|parReadOnly=
|parItems=
}}
{{Parameter
|parName=offset
|parOrder=12
|parLabel=Offset
|opFamily=CHOP
|opType=pattern
|parSummary=See also the Range.
|parType=Float
|parReadOnly=
|parItems=
}}
{{Parameter
|parName=fromrange
|parItems={{ParameterItem
|itemName=fromrange1
|opFamily=CHOP
|parName=fromrange
|itemLabel=""
|itemSummary=
}}<!--
-->{{ParameterItem
|itemName=fromrange2
|opFamily=CHOP
|parName=fromrange
|itemLabel=""
|itemSummary=
}}
|parOrder=13
|parLabel=From Range
|opFamily=CHOP
|opType=pattern
|parSummary=A value at each From Range will become its corresponding To Range value.
|parType=Float
|parReadOnly=
}}
{{Parameter
|parName=torange
|parItems={{ParameterItem
|itemName=torange1
|opFamily=CHOP
|parName=torange
|itemLabel=""
|itemSummary=
}}<!--
-->{{ParameterItem
|itemName=torange2
|opFamily=CHOP
|parName=torange
|itemLabel=""
|itemSummary=
}}
|parOrder=14
|parLabel=To Range
|opFamily=CHOP
|opType=pattern
|parSummary=A value at each From Range will become its corresponding To Range value.
|parType=Float
|parReadOnly=
}}
{{Parameter
|parName=integer
|parItems={{ParameterItem
|itemName=off
|opFamily=CHOP
|parName=integer
|itemLabel=Off
|itemSummary=
}}<!--
-->{{ParameterItem
|itemName=ceiling
|opFamily=CHOP
|parName=integer
|itemLabel=Ceiling
|itemSummary=
}}<!--
-->{{ParameterItem
|itemName=floor
|opFamily=CHOP
|parName=integer
|itemLabel=Floor
|itemSummary=
}}<!--
-->{{ParameterItem
|itemName=round
|opFamily=CHOP
|parName=integer
|itemLabel=Round
|itemSummary=
}}
|parOrder=15
|parLabel=Integer
|opFamily=CHOP
|opType=pattern
|parSummary=A round-off menu to convert all numbers to integers.
|parType=Menu
|parReadOnly=
}}
{{Parameter
|parName=reverse
|parOrder=16
|parLabel=Reverse
|opFamily=CHOP
|opType=pattern
|parSummary=Reverses the final order of the samples as in the [[Stretch CHOP]].
|parType=Toggle
|parReadOnly=
|parItems=
}}
{{Parameter
|parName=randomize
|parOrder=17
|parLabel=Randomize
|opFamily=CHOP
|opType=pattern
|parSummary=When the Type parameter above is set to Random Non-Repeating Integers, this trigger will randomize all the values.
|parType=Pulse
|parReadOnly=
|parItems=
}}
|pageSummary=
}}
{{ParameterPage
|opFamily=CHOP
|pageName=Channel
|items={{Parameter
|parName=channelname
|parOrder=0
|parLabel=Channel Names
|opFamily=CHOP
|opType=pattern
|parSummary=You can creates many channels with simple patterns like <code>chan[1-20]</code>, which generates 20 channels from <code>chan1</code> to <code>chan20</code>, or <code>t[xyz]</code> which generates <code>tx</code>, <code>ty</code> and <code>tz</code>. See the section, Common CHOP Parameters for a description of this and all Options. See [[CHOP Common Page#Scope|Scope and Channel Name Matching]] Options.
|parType=Str
|parReadOnly=
|parItems=
}}
{{Parameter
|parName=combine
|parItems={{ParameterItem
|itemName=off
|opFamily=CHOP
|parName=combine
|itemLabel=Off
|itemSummary=It only adopts the length and sample rate of the input.
}}<!--
-->{{ParameterItem
|itemName=append
|opFamily=CHOP
|parName=combine
|itemLabel=Append
|itemSummary=It appends the new Pattern CHOP channels after the last incoming channel.
}}<!--
-->{{ParameterItem
|itemName=insert
|opFamily=CHOP
|parName=combine
|itemLabel=Insert
|itemSummary=It inserts the new channels before the first incoming channel.
}}<!--
-->{{ParameterItem
|itemName=replace
|opFamily=CHOP
|parName=combine
|itemLabel=Replace
|itemSummary=It replaces the incoming channels using channel-name-matching.
}}<!--
-->{{ParameterItem
|itemName=add
|opFamily=CHOP
|parName=combine
|itemLabel=Add
|itemSummary=It adds incoming channels to the generated channels, matching by channel-name-matching.
}}<!--
-->{{ParameterItem
|itemName=multiply
|opFamily=CHOP
|parName=combine
|itemLabel=Multiply
|itemSummary=It multiplies incoming channels with the generated channels, matching by channel-name-matching.
}}
|parOrder=1
|parLabel=Combine Channels
|opFamily=CHOP
|opType=pattern
|parSummary=If an input CHOP is attached, it adopts the length and sample rate of the input CHOP, and
|parType=Menu
|parReadOnly=
}}
{{Parameter
|parName=rate
|parOrder=2
|parLabel=Sample Rate
|opFamily=CHOP
|opType=pattern
|parSummary=The sample rate of the channels, in samples per second.
|parType=Float
|parReadOnly=
|parItems=
}}
{{Parameter
|parName=left
|parItems={{ParameterItem
|itemName=hold
|opFamily=CHOP
|parName=left
|itemLabel=Hold
|itemSummary=Hold the current value of the channel.
}}<!--
-->{{ParameterItem
|itemName=slope
|opFamily=CHOP
|parName=left
|itemLabel=Slope
|itemSummary=Continue the slope before the start of the channel.
}}<!--
-->{{ParameterItem
|itemName=cycle
|opFamily=CHOP
|parName=left
|itemLabel=Cycle
|itemSummary=Cycle the channel repeatedly.
}}<!--
-->{{ParameterItem
|itemName=mirror
|opFamily=CHOP
|parName=left
|itemLabel=Mirror
|itemSummary=Cycle the channel repeatedly, mirroring every other cycle.
}}<!--
-->{{ParameterItem
|itemName=default
|opFamily=CHOP
|parName=left
|itemLabel=Default Value
|itemSummary=Use the constant value specified in the Default Value parameter.
}}
|parOrder=3
|parLabel=Extend Left
|opFamily=CHOP
|opType=pattern
|parSummary=The left right extend conditions (before/after range).
|parType=Menu
|parReadOnly=
}}
{{Parameter
|parName=right
|parItems={{ParameterItem
|itemName=hold
|opFamily=CHOP
|parName=right
|itemLabel=Hold
|itemSummary=Hold the current value of the channel.
}}<!--
-->{{ParameterItem
|itemName=slope
|opFamily=CHOP
|parName=right
|itemLabel=Slope
|itemSummary=Continue the slope after the end of the channel.
}}<!--
-->{{ParameterItem
|itemName=cycle
|opFamily=CHOP
|parName=right
|itemLabel=Cycle
|itemSummary=Cycle the channel repeatedly.
}}<!--
-->{{ParameterItem
|itemName=mirror
|opFamily=CHOP
|parName=right
|itemLabel=Mirror
|itemSummary=Cycle the channel repeatedly, mirroring every other cycle.
}}<!--
-->{{ParameterItem
|itemName=default
|opFamily=CHOP
|parName=right
|itemLabel=Default Value
|itemSummary=Use the constant value specified in the Default Value parameter.
}}
|parOrder=4
|parLabel=Extend Right
|opFamily=CHOP
|opType=pattern
|parSummary=The right extend conditions (before/after range).
|parType=Menu
|parReadOnly=
}}
{{Parameter
|parName=defval
|parOrder=5
|parLabel=Default Value
|opFamily=CHOP
|opType=pattern
|parSummary=The value used for the Default Value extend condition. 
|parType=Float
|parReadOnly=
|parItems=
}}
|pageSummary=
}}
{{:CHOP Generator Common Page}}
{{InputsPage
|opFamily=CHOP
|opInputs={{OPInput
|opFamily=CHOP
|inputIndex=0
|inputName=
|inputSummary=
}}
}}


In addition, selecting '''Help -> Python Examples''' in the TouchDesigner UI takes you to the <code>PythonExamples.toe</code> file with 100+ working examples.
{{InfoCHOPChannels
 
|opFamily=CHOP
== Learning Python ==
|opLabel=Pattern
If you don't know Python, here are some good resources for learning:
|infoChannels=}}
* [https://docs.python.org/3/tutorial/index.html The official Python tutorial]
{{History}}
* [https://docs.python-guide.org/intro/learning/ Python Learning Resources]
{{CHOPNavBox|opFamily=CHOP}}
* [https://www.pcworld.com/article/3287981/best-python-courses.html List of online Python courses]
{{#invoke:Category|list|CHOPs}}
* [http://www.codeacademy.com General programming courses at codeacademy.com]
* [http://overapi.com/python Python cheat sheet]
* [https://www.freecodecamp.org/news/freecodecamp-python-courses-ranked-from-best-to-worst/ Python at freeCodeCamp]
* alphamoonbase's tips and tricks: [https://derivative.ca/community-post/python-tipsntricks Part 1], [https://derivative.ca/community-post/python-tipsntricks-2 Part 2], [https://derivative.ca/community-post/python-tipsntricks-3 Part 3] - real-world python-in-TouchDesigner experience
 
== Python Classes and Modules Available in TouchDesigner ==
TouchDesigner includes all the modules in a [https://docs.python.org/3.11/library/ standard Python installation] plus the following:
=== <code>td</code>: TouchDesigner's Main Python Module ===
'''All [[Td Module|td module]] members and methods are available in scripts, expressions, and the textport.''' There is no need to import the module or its members explicitly. This is especially important in expressions, which don't allow import statements.
 
The following can be found in the <code>td</code> module:
* '''[[Td Module|Main TouchDesigner utilities]]''' - the most basic starting points for interacting with TouchDesigner, such as <code>me</code> and <code>op()</code>.
* '''[[Python Classes and Modules#Helper_Classes|TouchDesigner Python helper classes]]''' - important helper objects used to organize functions and information pertaining to a specific part of TouchDesigner.
* '''[[Python Classes and Modules#Operator_Related_Classes|Operator related classes]]''' - every [[Operator]] in TouchDesigner has an associated Python class in the  <code>td</code> module. Their wiki pages can be accessed by clicking on the Python Help button in their [[Parameter Dialog|parameter dialog]]. There are also a number of associated Python objects that are used when working with Operators.
* '''[[Python Classes and Modules#Standard_Python_Modules|Useful standard Python modules]]''' - the <code>td</code> module also automatically imports a number of helpful standard modules (e.g. <code>math</code>), allowing them to be accessed in expressions through their namespace.
 
=== TouchDesigner Utility Modules ===
TouchDesigner also contains utility modules for advanced Python programming. Utility modules are not imported into the <code>td</code> module automatically. Instructions for their use can be found on their wiki pages.
* '''[[Python Classes and Modules#TouchDesigner_Utility_Modules and Python Utilities|List of Python Utility Modules and Python Utilities]]'''.
 
=== 3rd Party Packages ===
TouchDesigner includes a number of 3rd party Python packages that are generally useful when working with the software. These are not included in the <code>td</code> module so must be imported explicitly.
* '''[[Python Classes and Modules#3rd_Party_Packages|List of 3rd party Python Packages]]'''.
 
=== Installing Custom Python Packages ===
Part of the great power of Python is its access to the countless number of modules that have been created. If you want to use modules that are not included in the above, use the following steps:
 
Note: When adding your own version for a package that is already shipped with TouchDesigner, you might encounter unexpected behaviors.
Many of our internal tools and palette components rely on NumPy and/or OpenCV. '''Loading different versions of Numpy and/or OpenCV is at your own risk.'''
Some other issue could be with the following: considering a Package A with a dependency B, if updating your sys.path cause a different version of dependency B to load first, it could cause issues with Package A.
 
==== Windows ====
#Install a parallel copy of the same version of Python to the hard disk. The current version of Python shipped with TouchDesigner is 3.11. It can be found [https://www.python.org/downloads/ here]. Use the most recent subversion of 3.11.
##Alternatively, you can use a Python package and environment manager, [https://derivative.ca/community-post/tutorial/anaconda-managing-python-environments-and-3rd-party-libraries-touchdesigner such as Anaconda].
#Install the package to the parallel python installation, following its normal installation procedure.
#Launch Python and import the module manually to make sure there are no errors outside of the TouchDesigner context.
 
Once the module is successfully installed, you can import it in TouchDesigner following those next steps:
 
Under the Edit->Preferences menu, tick "Add External Python to Search Path". You can add the search path by modifying the Preference labelled "Python 32/64 bit Module Path". Multiple paths are separated by semicolons (<code>;</code>).
 
Finally you can modify the search path directly by either modifying the system environment variable <code>PYTHONPATH</code> or by '''firing an [[Execute DAT]] onStart()''' with the code snippet below.
 
<syntaxhighlight lang=python>
import sys
mypath = "C:/Python311/Lib/site-packages" # use the correct path to your installation, sometimes in a user folder
if mypath not in sys.path:
sys.path = [mypath] + sys.path
</syntaxhighlight>
 
This script will prepend your custom Python install site-packages folder to your PATH. Prepending will make sure that your custom packages, when being imported, '''will have priority over any other package with a matching package name found''' in the path. If the package is not found in the custom path, but a package of the same name is found in the TouchDesigner Python site-packages folder then '''it will fall back on this package'''.
 
Users can also import packages from Python installations that weren't installed with the official Python installer but with alternative Python package and environment managers, [https://derivative.ca/community-post/tutorial/anaconda-managing-python-environments-and-3rd-party-libraries-touchdesigner such as Anaconda].
 
Examples of other useful Python modules are [http://wiki.python.org/moin/UsefulModules here].
Unofficial precompiled modules found on Christoph Gohlke's [http://www.lfd.uci.edu/~gohlke/pythonlibs/?q=cp33 website].
 
==== MacOS ====
 
On MacOS, use [https://brew.sh/ Homebrew] to manage your Python installations. Follow the instructions on Homebrew's website to get started.
 
When Homebrew is installed, you can use the command <syntaxhighlight lang="bash" inline=true>brew install python@3.11</syntaxhighlight> to install Python on your system. The <syntaxhighlight lang=python inline=true>@3.11</syntaxhighlight> after <syntaxhighlight lang="bash" inline=true>python</syntaxhighlight> sets the version, which must be the same as TouchDesigner's.
 
===== Intel Macs =====
 
On Intel's Macs, your default Homebrew path should be <syntaxhighlight inline=true>/usr/local/bin/brew</syntaxhighlight>
 
===== ARM Macs =====
 
On ARM's Macs, your Homebrew path should be <syntaxhighlight inline=true>/opt/homebrew/bin/brew</syntaxhighlight>, '''for the native ARM homebrew'''. That is, when using the default Homebrew install command.
 
'''NOTE:''' In some cases, you might want to run Homebrew Rosetta. It is required if you are using the non-native / Intel TouchDesigner build and require a Python version that is not available as an ARM installer on MacOS.
 
To install Homebrew Rosetta, use the following command: <syntaxhighlight inline=true>arch -x86_64 /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"</syntaxhighlight>.
Your Homebrew Rosetta path should be <syntaxhighlight inline=true>/usr/local/bin/brew</syntaxhighlight>.
 
If you have both Homebrew versions installed on your system, it is advised to add an alias for the Homebrew Rosetta installation.
Use the following command in your terminal <syntaxhighlight inline=true>alias ibrew="arch -x86_64 /usr/local/bin/brew"</syntaxhighlight> where <syntaxhighlight inline=true>ibrew</syntaxhighlight> stands for Intel Brew.
You can add this alias to your terminal profile so that it is persistent.
 
You can now use either <syntaxhighlight inline=true>brew install YOUR_APP_NAME</syntaxhighlight> or <syntaxhighlight inline=true>ibrew install YOUR_APP_NAME</syntaxhighlight> to install ARM or Intel formulas or casks respectively.
 
Continue with your python installation, matching TouchDesigner's Python, as described at the top of this MacOS section. Remember, if you followed the previous steps: when your are using the ARM native TouchDesigner build, use <syntaxhighlight inline=true>brew</syntaxhighlight>, if it's the Intel build running with Rosetta, use <syntaxhighlight inline=true>ibrew</syntaxhighlight>.
 
It can also be useful to add extra aliases, and precede them with an <syntaxhighlight inline=true>i</syntaxhighlight> when they are related to Intel / Rosetta, for Python itself, and pip:
<syntaxhighlight>
alias iPY311=/usr/local/opt/python@3.11/bin/python3
alias iPIP311=/usr/local/opt/python@3.11/bin/pip3
</syntaxhighlight>
 
Now, all you have to do is install your custom (Intel) Python 3.11 packages using <syntaxhighlight inline=true>iPIP311 install YOUR_PACKAGE_NAME</syntaxhighlight>.
 
Once the module is successfully installed, you can import it in TouchDesigner following these next steps:
 
Under the Edit->Preferences menu, tick "Add External Python to Search Path". You can add the search path by modifying the Preference labelled "Python 32/64 bit Module Path". Multiple paths are separated by semicolons (<code>;</code>). You can enter the path to your Python packages (usually <code><python install>/Lib/site-packages</code>)
 
If the preferences method doesn't work for you, there are a couple other methods: you can modify the Python search path directly by either modifying the '''system environment variable <code>PYTHONPATH</code>''' or by '''setting up an [[Execute DAT]] onStart()''' with the code snippet below.
 
<syntaxhighlight lang=python>
import sys
mypath = "/usr/local/lib/python3.11/site-packages" # TIP: This path is printed out in the terminal when installing this Python version with Homebrew
if mypath not in sys.path:
sys.path = [mypath] + sys.path
</syntaxhighlight>
 
This script will prepend your custom Python install site-packages folder to your PATH. Prepending will make sure that your custom packages, when being imported, '''will have priority over any other package with a matching package name found''' in the path. If the package is not found in the custom path, but a package of the same name is found in the TouchDesigner Python site-packages folder then '''it will fall back on this package'''.
 
==== I am getting the following ImportError, what should I do ? ImportError: DLL load failed while importing […] ====
For most cases, it is better to document your environment and to share the project and steps to reproduced with the Derivative team at forum.derivative.ca
 
If you feel adventurous, what is likely to happen is that there is a dependency conflict causing an issue between TouchDesigner and the Python library you are attempting to use.
 
You can use a tool such as [https://github.com/lucasg/Dependencies Dependencies] to get an idea of which libraries your package is depending on. You drag n drop your python package binary, pyd, to the tool and you can see what are the libraries it is depending on. Then you investigate further to find what library might already be used by TouchDesigner, going through the dependencies of dependencies. Tedious.
 
== Python Gotchas ==
There are a few things in standard Python that can trip you up in TouchDesigner. If you find anything that's not included here, post in the forum!
* Some TouchDesigner objects (especially parameters and CHOP channels) will try to act as the correct data type for their context. For example, a Float parameter object (<code>myOp.par.Float1</code>) will act like a floating point number ''in most cases'', but it is still a parameter object. For example <code>round(myOp.par.Float1)</code> will not work. To get the actual value of a parameter or channel, use its <code>.eval()</code> method. If you think you may be encountering this problem, you can tell the difference by using the <code>repr</code> function. For example <code>repr(myOp.par.Float1)</code> will show that this is a parameter and not a number.
* same goes with operator parameter types.  if a parameter is a path to a CHOP, <code>n.par.Chop</code> usually works, but to be safe, <code>n.par.Chop.eval()</code> always works.
* <code>subprocess.Popen</code> doesn't work with file-like objects. See [https://forum.derivative.ca/t/resolved-td-specific-stdoutcatcher-object-has-no-attribute-fileno/140106 this forum post] for details.
* Python threads don't have access to TouchDesigner objects. Search "threading" in the forum to see some workarounds.
 
== More In The Python Category ==

Latest revision as of 17:18, 24 January 2024

Summary
[edit]

The Pattern CHOP generates a sequence of samples in a channel. Unlike the Wave CHOP its purpose is generating arrays of samples that have no reference to time (seconds or frames).

It is useful for curve generation like lookup tables, simple shapes that can be converted to SOPs, generating channels that are passed to the Geometry COMP to generate instances, and other non-time-based curve-generation, with as little need to make expressions in Python.

All defaults are in samples, not seconds or frames (though like all CHOPs, it carries with it a sample rate). There is no start-end, just Length in samples.

Tip: To display a CHOP viewer in the units of samples, make the Viewer Active and change RMB -> Units to be Samples.

The Pattern CHOP optionally takes one input CHOP to match the length and sample rate, and, choosing via the Combine Channels menu, Appends or Inserts the new channel(s), Replaces the incoming channels, Adds to the incoming channels or Multiplies the incoming channels.

The Pattern CHOP defaults to one cycle of the curve over the length of the CHOP, no matter how many samples long.

Tip: Customizing each channel: The python object for the Pattern CHOP has a chanIndex member, so if Pattern generates three channels you can put something like [1, 3, 7][me.chanIndex] in any parameter to customize its value for each channel. For example, in the Type parameter, put the expression ['sin', 'cos', 'ramp'][me.chanIndex] to get 3 different curve types.

PythonIcon.pngpatternCHOP_Class


Parameters - Pattern Page

Type wavetype - - The shape of one cycle of the pattern.

  • Constant const - (1)
  • Sine sin - (-1 to 1)
  • Cosine cos - (-1 to 1)
  • Triangle tri - (-1 to 1)
  • Ramp ramp - (0-1)
  • Ramp Samples rampsamples - (0 to numSamples-1)
  • Square square - (-1 to -1)
  • Pulse pulse - (0-1)
  • Random random - (0-1)
  • Random per Cycle randomcycle - All samples in a cycle will have the same randomly generated value.
  • Random Non-Repeating Integers randomnonrepint - This wave type is used in conjunction with the Randomize pulse. Between each Randomize pulse, the random values at each sample will be non-repeating. For example in the simplest case with a channel length of 1, each time Randomize is pulsed the random value of sample 1 after the pulse will be different than the random value before the pulse.
  • Step step - (0 to 1) step function
  • Cyclic Ramp rampcyclic - (0 to (numSamples -1) / numSamples). Same as 'Ramp' type, but on phase shifting the value never goes out of range.

Length length - Set the number of samples for this CHOP.

Number of Cycles numcycles - Set the number of repeating cycles of the Type shapes over the Length, except for Random.

Step per Cycle steppercycle -

Number of Steps numsteps -

Bias bias - Makes Triangle type into a sawtooth wave, and sets the Square type variable-width.

Seed seed - The seed for the random Types.

Phase phase - Shifts the cycle.

Phase Step per Channel phasestep - Increases the phase for each channel. A Phase Step of .25 when there are 2 channels will shift the second channel to be 1/4 cycle later phase than the first phase, where if the 2 channels are used for x and y, will draw a circle when passed to a CHOP to SOP.

Taper taper - - Two parameters to multiply by a line from taper1 at the start to taper2 at the end. The default of (1 1) has no effect.

  • taper1 -
  • taper2 -

Taper Decay Rate taperdecay - An exponent that is applied to the result of the taper.

Amplitude amp - See also the Range.

Offset offset - See also the Range.

From Range fromrange - - A value at each From Range will become its corresponding To Range value.

  • fromrange1 -
  • fromrange2 -

To Range torange - - A value at each From Range will become its corresponding To Range value.

  • torange1 -
  • torange2 -

Integer integer - - A round-off menu to convert all numbers to integers.

  • Off off -
  • Ceiling ceiling -
  • Floor floor -
  • Round round -

Reverse reverse - Reverses the final order of the samples as in the Stretch CHOP.

Randomize randomize - When the Type parameter above is set to Random Non-Repeating Integers, this trigger will randomize all the values.


Parameters - Channel Page

Channel Names channelname - You can creates many channels with simple patterns like chan[1-20], which generates 20 channels from chan1 to chan20, or t[xyz] which generates tx, ty and tz. See the section, Common CHOP Parameters for a description of this and all Options. See Scope and Channel Name Matching Options.

Combine Channels combine - - If an input CHOP is attached, it adopts the length and sample rate of the input CHOP, and

  • Off off - It only adopts the length and sample rate of the input.
  • Append append - It appends the new Pattern CHOP channels after the last incoming channel.
  • Insert insert - It inserts the new channels before the first incoming channel.
  • Replace replace - It replaces the incoming channels using channel-name-matching.
  • Add add - It adds incoming channels to the generated channels, matching by channel-name-matching.
  • Multiply multiply - It multiplies incoming channels with the generated channels, matching by channel-name-matching.

Sample Rate rate - The sample rate of the channels, in samples per second.

Extend Left left - - The left right extend conditions (before/after range).

  • Hold hold - Hold the current value of the channel.
  • Slope slope - Continue the slope before the start of the channel.
  • Cycle cycle - Cycle the channel repeatedly.
  • Mirror mirror - Cycle the channel repeatedly, mirroring every other cycle.
  • Default Value default - Use the constant value specified in the Default Value parameter.

Extend Right right - - The right extend conditions (before/after range).

  • Hold hold - Hold the current value of the channel.
  • Slope slope - Continue the slope after the end of the channel.
  • Cycle cycle - Cycle the channel repeatedly.
  • Mirror mirror - Cycle the channel repeatedly, mirroring every other cycle.
  • Default Value default - Use the constant value specified in the Default Value parameter.

Default Value defval - The value used for the Default Value extend condition.


Parameters - Common Page

Time Slice timeslice - Turning this on forces the channels to be "Time Sliced". A Time Slice is the time between the last cook frame and the current cook frame.

Scope scope - To determine which channels get affected, some CHOPs use a Scope string on the Common page.

Sample Rate Match srselect - - Handle cases where multiple input CHOPs' sample rates are different. When Resampling occurs, the curves are interpolated according to the Interpolation Method Option, or "Linear" if the Interpolate Options are not available.

  • Resample At First Input's Rate first - Use rate of first input to resample others.
  • Resample At Maximum Rate max - Resample to the highest sample rate.
  • Resample At Minimum Rate min - Resample to the lowest sample rate.
  • Error If Rates Differ err - Doesn't accept conflicting sample rates.

Export Method exportmethod - - This will determine how to connect the CHOP channel to the parameter. Refer to the Export article for more information.

  • DAT Table by Index datindex - Uses the docked DAT table and references the channel via the index of the channel in the CHOP.
  • DAT Table by Name datname - Uses the docked DAT table and references the channel via the name of the channel in the CHOP.
  • Channel Name is Path:Parameter autoname - The channel is the full destination of where to export to, such has geo1/transform1:tx.

Export Root autoexportroot - This path points to the root node where all of the paths that exporting by Channel Name is Path:Parameter are relative to.

Export Table exporttable - The DAT used to hold the export information when using the DAT Table Export Methods (See above).


Operator Inputs

  • Input 0: -


Info CHOP Channels

Extra Information for the Pattern CHOP can be accessed via an Info CHOP.

Common CHOP Info Channels

  • start - Start of the CHOP interval in samples.
  • length - Number of samples in the CHOP.
  • sample_rate - The samplerate of the channels in frames per second.
  • num_channels - Number of channels in the CHOP.
  • time_slice - 1 if CHOP is Time Slice enabled, 0 otherwise.
  • export_sernum - A count of how often the export connections have been updated.

Common Operator Info Channels

  • total_cooks - Number of times the operator has cooked since the process started.
  • cook_time - Duration of the last cook in milliseconds.
  • cook_frame - Frame number when this operator was last cooked relative to the component timeline.
  • cook_abs_frame - Frame number when this operator was last cooked relative to the absolute time.
  • cook_start_time - Time in milliseconds at which the operator started cooking in the frame it was cooked.
  • cook_end_time - Time in milliseconds at which the operator finished cooking in the frame it was cooked.
  • cooked_this_frame - 1 if operator was cooked this frame.
  • warnings - Number of warnings in this operator if any.
  • errors - Number of errors in this operator if any.


TouchDesigner Build:

CHOPs
Ableton Link • Analyze • Angle • Attribute • Audio Band EQ • Audio Binaural • Audio Device In • Audio Device Out • Audio Dynamics • Audio File In • Audio File Out • Audio Filter • Audio Movie • Audio NDI • Audio Oscillator • Audio Para EQ • Audio Play • Audio Render • Audio Spectrum • Audio Stream In • Audio Stream Out • Audio VST • Audio Web Render • Beat • Bind • BlackTrax • Blend • Blob Track • Body Track • Bullet Solver • Clip Blender • Clip • Clock • Composite • Constant • Copy • Count • CPlusPlus • Cross • Cycle • DAT to • Delay • Delete • DMX In • DMX Out • Envelope • EtherDream • Event • Expression • Extend • Face Track • Fan • Feedback • File In • File Out • Filter • FreeD In • FreeD Out • Function • Gesture • Handle • Helios DAC • Hog • Hokuyo • Hold • Import Select • In • Info • Interpolate • Introduction To s Vid • Inverse Curve • Inverse Kin • Join • Joystick • Keyboard In • Keyframe • Kinect Azure • Kinect • Lag • Laser • Laser Device • Leap Motion • Leuze ROD4 • LFO • Limit • Logic • Lookup • LTC In • LTC Out • Math • Merge • MIDI In • MIDI In Map • MIDI Out • MoSys • Mouse In • Mouse Out • NatNet In • Ncam • Noise • Null • OAK Device • OAK Select • Object • Oculus Audio • Oculus Rift • OpenVR • OSC In • OSC Out • Out • Override • Panel • Pangolin • Parameter • Pattern • Perform • Phaser • Pipe In • Pipe Out • PosiStageNet • Pulse • RealSense • Record • Rename • Render Pick • RenderStream In • Reorder • Replace • Resample • S Curve • Scan • Script • Select • Sequencer • Serial • Shared Mem In • Shared Mem Out • Shift • Shuffle • Slope • SOP to • Sort • Speed • Splice • Spring • Stretch • Stype In • Stype Out • Switch • Sync In • Sync Out • Tablet • Time Slice • Timecode • Timeline • Timer • TOP to • Touch In • Touch Out • Trail • Transform • Transform XYZ • Trigger • Experimental:Trigger • Trim • Warp • Wave • WrnchAI • ZED