SlideShare une entreprise Scribd logo
1  sur  18
When to use Python in FME
Dr. Jonathan Stanger
Senior Consultant – Spatial Partners Pty. Ltd.
FME is good for
Broad User Skill Levels
FME is good for
Maintainability
FME is good for
Portability
FME is good for
Rapid Modification
Why using Python is bad…
The FME transformer library is very extensive. FME does limit us, but with
good reason. It uses a simple data paradigm that aligns with most spatial
data, collections of features that each have a well defined set of attributes.
We perform operations discretely on a single feature at a time.
Sometimes this can be frustrating but remember:
Don’t reinvent the wheel! Try rephrasing the problem you are solving!
Where can Python be used?
● Start-up Scripts – Executes before FME transformers (even readers…)
● Shut-down Scripts – Executes after all FME transformers are finished
● Scripted Parameters – Executes on start-up and preserves the value
● PythonCreator – Has no input, Python defines all features outputted
● PythonCaller – Executes function once or calls input once per feature
Good examples for Python in FME
Smart Scripted Parameters
While the Workspace Runner is useful, in
trivial cases its not always ideal. If the
only requirement is glob style directory
search to provide file paths the workspace
runner leaves excess complexity for
deployment.
Solution: Script glob search into
parameter to return
import fme, fmeobjects, glob
# Get parameters set by user to initiate the glob
search
rootpath = fme.macroValues['rootPath']
# Glob search for file candidates
candidates = glob.glob(rootpath + '/**/data.TAB',
recursive = True)
# Return string that matches what FME expects
if candidates:
return '""' + '" "'.join(candidates) + '""'
else:
return ""
Example: Avoiding the workspace
runner
Front Stage File Manipulation
FME rightly treats the data schema of
some file formats quite strictly, unlike
users sometimes. This impacts MapInfo
and sometimes Excel files.
Solution: Rename/copy the file to a
standard filename
- Published Parameter (Target File)
- Private Parameter (Reader Target)
import fme, fmeobjects
from shutil import copy2
# Extract required info from macroValues
fmepath = fme.macroValues['FME_MF_DIR']
targetfile = fme.macroValues['fileName']
# Check parameter is assigned
if targetfile:
# Copy2 will automatically overwrite existing
# file. Set reader target to private parameter
# containing:
# $(FME_MF_DIR)Standard.xlsx
copy2(targetfile, fmepath + 'Standard.xlsx')
Example: File Formats playing badly
Inter-feature Dependant Operations
Assuming features have ID’s that are not
consecutive. If features have two
attributes, one representing the
component ahead and one the
component behind, how do we sort the
features?
Solution: Sort elements by matching
ahead ID to behind ID
Example: Paired Sorting
Sort Order 1
Behind
934AH9
Ahead
365U33
Sort Order 2
Behind
6433OE
Ahead
934AH9
Sort Order 3
Behind
18KW22
Ahead
6433OE
Sort Order 4
Behind
20554Z
Ahead
18KW22
Repeated(recursive) operations (N > 3 or N = ?)
FME was designed to work with tabular
not network/graph style data. As such,
recursive algorithms such as DFS or BFS
are nearly impossible to implement with
native transformers.
Solution: Gather all the data into Python
then process in memory
Think carefully about how you output!
Example: Trace network data
A
B
D E C
GFH
I
Non-standard Geometry Manipulation
FME offers well developed options for
direct geometry manipulation, scaling,
offsetting or rotating. Less typical
geometry manipulation can be tricky
though.
Solution: Implement custom geometry
transformation in Python
Example: Mirror around arbitrary plane
geom = feature.getGeometry()
points = line.getPoints()
x, y, z = point.getXYZ()
point.setXYZ(x, y, z)
Tedious Operations
For simple cases FME string manipulation
is more than sufficient. Building a string
conditionally based on 20+ attributes is
possible but very tedious and difficult to
maintain.
Solution: Python string manipulation to
efficiently build the string
import fme, fmeobjects
# Attribute to label lookup dictionary
attributeMap = {
'5_040': '5pr',
'50_040': '50pr',
'100_040': '100pr',
'200_040': '200pr',
'400_040': '400pr',
... x 25 more,
}
class FeatureProcessor(object):
def __init__(self):
pass
def input(self,feature):
# Use dictionary comprehension to conditionally build elements of label
attributes = {attributeMap[key]: feature.getAttribute(key)
for key in attributeMap.keys()
if feature.getAttribute(key) and feature.getAttribute(key) > 0}
# Join label elements to form a single string
label = ", ".join([str(int(attributes[key])) + "x" + key
for key in attributes.keys()])
feature.setAttribute('LABEL', label)
self.pyoutput(feature)
def close(self):
pass
Example: Build very complex string
General Rules for
Python use
● Recursion
● File Manipulation
● FME forums say its not possible
Hints for Python in FME
1. Logger rather than Print
2. Scripted Parameters are hard to Debug
3. Don’t import non-standard libraries
4. You can import FME libraries to external
python scripts
5. Don’t use copies of a PythonCaller
import fme
import fmeobjects
logger = fmeobjects.FMELogFile()
parameter = fme.macroValues['ParameterName']
logger.logMessageString("{Python Script} Parameter set: %s" % parameter)
# Template Class Interface:
# When using this class, make sure its name is set as the value
# of the 'Class or Function to Process Features' transformer parameter
class FeatureProcessor(object):
def __init__(self):
pass
def input(self, feature):
self.pyoutput(feature)
def close(self):
pass
Useful Pattern – FME Env. Dictionary
import fme
import fmeobjects
# Template Class Interface:
# When using this class, make sure its name is set as the value
# of the 'Class or Function to Process Features' transformer
# parameter
class FeatureProcessor(object):
def __init__(self):
self.featureList = []
def input(self, feature):
self.featureList.append(feature)
def close(self):
for feature in self.featureList:
self.pyoutput(feature)
Useful Pattern – Bulk Feature Manipulation
Example: Tiled Grid Viewports
PythonCaller: Consumes point and line geometry, coverts to points then divides space to provide
viewport polygons that will overlay every point in the set. Useful for creating AutoCAD viewports or
other pagination of your geometry.
Example: Procedural Tree Layout for Logical Networks
Start-up Python Script: Parses logical connectivity then builds GML file with generated geometry for export
via FME to other file formats such as AutoCAD to a database as a pre-calculated UI display geometry
THANK YOU!
Dr. Jonathan Stanger
jstanger@spatialpartners.com

Contenu connexe

Tendances

Model Driven Architecture (MDA): Motivations, Status & Future
Model Driven Architecture (MDA): Motivations, Status & FutureModel Driven Architecture (MDA): Motivations, Status & Future
Model Driven Architecture (MDA): Motivations, Status & Futureelliando dias
 
Flutter Online Study jam 10-7-2019
Flutter Online Study jam 10-7-2019Flutter Online Study jam 10-7-2019
Flutter Online Study jam 10-7-2019Ahmed Abu Eldahab
 
Git 101: Git and GitHub for Beginners
Git 101: Git and GitHub for Beginners Git 101: Git and GitHub for Beginners
Git 101: Git and GitHub for Beginners HubSpot
 
Understanding GIT and Version Control
Understanding GIT and Version ControlUnderstanding GIT and Version Control
Understanding GIT and Version ControlSourabh Sahu
 
Go Programming Language (Golang)
Go Programming Language (Golang)Go Programming Language (Golang)
Go Programming Language (Golang)Ishin Vin
 
Qt for Python
Qt for PythonQt for Python
Qt for PythonICS
 
Domain-Driven Design with ASP.NET MVC
Domain-Driven Design with ASP.NET MVCDomain-Driven Design with ASP.NET MVC
Domain-Driven Design with ASP.NET MVCSteven Smith
 
Domain Driven Design Introduction
Domain Driven Design IntroductionDomain Driven Design Introduction
Domain Driven Design Introductionwojtek_s
 
Introduction to GitHub, Open Source and Tech Article
Introduction to GitHub, Open Source and Tech ArticleIntroduction to GitHub, Open Source and Tech Article
Introduction to GitHub, Open Source and Tech ArticlePRIYATHAMDARISI
 
Git and Github slides.pdf
Git and Github slides.pdfGit and Github slides.pdf
Git and Github slides.pdfTilton2
 
Write microservice in golang
Write microservice in golangWrite microservice in golang
Write microservice in golangBo-Yi Wu
 
Powerpoint and promethean board
Powerpoint and promethean boardPowerpoint and promethean board
Powerpoint and promethean boardkevinbrace
 
Real Life Clean Architecture
Real Life Clean ArchitectureReal Life Clean Architecture
Real Life Clean ArchitectureMattia Battiston
 
Pivotal Tracker Overview
Pivotal Tracker OverviewPivotal Tracker Overview
Pivotal Tracker OverviewDan Podsedly
 

Tendances (20)

Model Driven Architecture (MDA): Motivations, Status & Future
Model Driven Architecture (MDA): Motivations, Status & FutureModel Driven Architecture (MDA): Motivations, Status & Future
Model Driven Architecture (MDA): Motivations, Status & Future
 
UI Programming with Qt-Quick and QML
UI Programming with Qt-Quick and QMLUI Programming with Qt-Quick and QML
UI Programming with Qt-Quick and QML
 
Flutter Online Study jam 10-7-2019
Flutter Online Study jam 10-7-2019Flutter Online Study jam 10-7-2019
Flutter Online Study jam 10-7-2019
 
Github basics
Github basicsGithub basics
Github basics
 
Git 101: Git and GitHub for Beginners
Git 101: Git and GitHub for Beginners Git 101: Git and GitHub for Beginners
Git 101: Git and GitHub for Beginners
 
Understanding GIT and Version Control
Understanding GIT and Version ControlUnderstanding GIT and Version Control
Understanding GIT and Version Control
 
Git l'essentiel
Git l'essentielGit l'essentiel
Git l'essentiel
 
Go Programming Language (Golang)
Go Programming Language (Golang)Go Programming Language (Golang)
Go Programming Language (Golang)
 
Dart
DartDart
Dart
 
ROS distributed architecture
ROS  distributed architectureROS  distributed architecture
ROS distributed architecture
 
Qt for Python
Qt for PythonQt for Python
Qt for Python
 
Domain-Driven Design with ASP.NET MVC
Domain-Driven Design with ASP.NET MVCDomain-Driven Design with ASP.NET MVC
Domain-Driven Design with ASP.NET MVC
 
Domain Driven Design Introduction
Domain Driven Design IntroductionDomain Driven Design Introduction
Domain Driven Design Introduction
 
Introduction to GitHub, Open Source and Tech Article
Introduction to GitHub, Open Source and Tech ArticleIntroduction to GitHub, Open Source and Tech Article
Introduction to GitHub, Open Source and Tech Article
 
Git and Github slides.pdf
Git and Github slides.pdfGit and Github slides.pdf
Git and Github slides.pdf
 
Write microservice in golang
Write microservice in golangWrite microservice in golang
Write microservice in golang
 
Powerpoint and promethean board
Powerpoint and promethean boardPowerpoint and promethean board
Powerpoint and promethean board
 
Real Life Clean Architecture
Real Life Clean ArchitectureReal Life Clean Architecture
Real Life Clean Architecture
 
Pivotal Tracker Overview
Pivotal Tracker OverviewPivotal Tracker Overview
Pivotal Tracker Overview
 
Domain Driven Design 101
Domain Driven Design 101Domain Driven Design 101
Domain Driven Design 101
 

Similaire à When to use python in FME

Functions2.pdf
Functions2.pdfFunctions2.pdf
Functions2.pdfprasnt1
 
Creating Custom Solutions with FME and Python
Creating Custom Solutions with FME and PythonCreating Custom Solutions with FME and Python
Creating Custom Solutions with FME and PythonSafe Software
 
python interview prep question , 52 questions
python interview prep question , 52 questionspython interview prep question , 52 questions
python interview prep question , 52 questionsgokul174578
 
Functions and Modules.pptx
Functions and Modules.pptxFunctions and Modules.pptx
Functions and Modules.pptxAshwini Raut
 
Dive into Python Functions Fundamental Concepts.pdf
Dive into Python Functions Fundamental Concepts.pdfDive into Python Functions Fundamental Concepts.pdf
Dive into Python Functions Fundamental Concepts.pdfSudhanshiBakre1
 
Functions and modules in python
Functions and modules in pythonFunctions and modules in python
Functions and modules in pythonKarin Lagesen
 
Python Modules, executing modules as script.pptx
Python Modules, executing modules as script.pptxPython Modules, executing modules as script.pptx
Python Modules, executing modules as script.pptxSingamvineela
 
Functions in Python Syntax and working .
Functions in Python Syntax and working .Functions in Python Syntax and working .
Functions in Python Syntax and working .tarunsharmaug23
 
Python Interview Questions For Experienced
Python Interview Questions For ExperiencedPython Interview Questions For Experienced
Python Interview Questions For Experiencedzynofustechnology
 
Beyond 49x Transformers: Don't be afraid of (the) Python!
Beyond 49x Transformers: Don't be afraid of (the) Python!Beyond 49x Transformers: Don't be afraid of (the) Python!
Beyond 49x Transformers: Don't be afraid of (the) Python!Safe Software
 

Similaire à When to use python in FME (20)

Terraform training 🎒 - Basic
Terraform training 🎒 - BasicTerraform training 🎒 - Basic
Terraform training 🎒 - Basic
 
Advance python
Advance pythonAdvance python
Advance python
 
Python master class 2
Python master class 2Python master class 2
Python master class 2
 
Php, mysq lpart3
Php, mysq lpart3Php, mysq lpart3
Php, mysq lpart3
 
Functions2.pdf
Functions2.pdfFunctions2.pdf
Functions2.pdf
 
Creating Custom Solutions with FME and Python
Creating Custom Solutions with FME and PythonCreating Custom Solutions with FME and Python
Creating Custom Solutions with FME and Python
 
python interview prep question , 52 questions
python interview prep question , 52 questionspython interview prep question , 52 questions
python interview prep question , 52 questions
 
Functions and Modules.pptx
Functions and Modules.pptxFunctions and Modules.pptx
Functions and Modules.pptx
 
Dive into Python Functions Fundamental Concepts.pdf
Dive into Python Functions Fundamental Concepts.pdfDive into Python Functions Fundamental Concepts.pdf
Dive into Python Functions Fundamental Concepts.pdf
 
Python and You Series
Python and You SeriesPython and You Series
Python and You Series
 
Symfony2 meets propel 1.5
Symfony2 meets propel 1.5Symfony2 meets propel 1.5
Symfony2 meets propel 1.5
 
Functions and modules in python
Functions and modules in pythonFunctions and modules in python
Functions and modules in python
 
Python Modules, executing modules as script.pptx
Python Modules, executing modules as script.pptxPython Modules, executing modules as script.pptx
Python Modules, executing modules as script.pptx
 
Functions in Python Syntax and working .
Functions in Python Syntax and working .Functions in Python Syntax and working .
Functions in Python Syntax and working .
 
Puppet quick start guide
Puppet quick start guidePuppet quick start guide
Puppet quick start guide
 
Python Interview Questions For Experienced
Python Interview Questions For ExperiencedPython Interview Questions For Experienced
Python Interview Questions For Experienced
 
Beyond 49x Transformers: Don't be afraid of (the) Python!
Beyond 49x Transformers: Don't be afraid of (the) Python!Beyond 49x Transformers: Don't be afraid of (the) Python!
Beyond 49x Transformers: Don't be afraid of (the) Python!
 
Functions
FunctionsFunctions
Functions
 
Dost.jar and fo.jar
Dost.jar and fo.jarDost.jar and fo.jar
Dost.jar and fo.jar
 
Functions
FunctionsFunctions
Functions
 

Plus de Daniela Perri

4.5 Powering infrastructure with fme
4.5 Powering infrastructure with fme4.5 Powering infrastructure with fme
4.5 Powering infrastructure with fmeDaniela Perri
 
FME Server as an Enterprise Service Bus
FME Server as an Enterprise Service BusFME Server as an Enterprise Service Bus
FME Server as an Enterprise Service BusDaniela Perri
 
Metadata in Local Government
Metadata in Local GovernmentMetadata in Local Government
Metadata in Local GovernmentDaniela Perri
 
Western power bushfire reponse process
Western power bushfire reponse processWestern power bushfire reponse process
Western power bushfire reponse processDaniela Perri
 

Plus de Daniela Perri (7)

4.5 Powering infrastructure with fme
4.5 Powering infrastructure with fme4.5 Powering infrastructure with fme
4.5 Powering infrastructure with fme
 
FME Server as an Enterprise Service Bus
FME Server as an Enterprise Service BusFME Server as an Enterprise Service Bus
FME Server as an Enterprise Service Bus
 
Metadata in Local Government
Metadata in Local GovernmentMetadata in Local Government
Metadata in Local Government
 
Hypsometric areas
Hypsometric areasHypsometric areas
Hypsometric areas
 
Index map
Index mapIndex map
Index map
 
Western power bushfire reponse process
Western power bushfire reponse processWestern power bushfire reponse process
Western power bushfire reponse process
 
Daniela CV Jan 2017
Daniela CV Jan 2017Daniela CV Jan 2017
Daniela CV Jan 2017
 

Dernier

Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfhans926745
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesBoston Institute of Analytics
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 

Dernier (20)

Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 

When to use python in FME

  • 1. When to use Python in FME Dr. Jonathan Stanger Senior Consultant – Spatial Partners Pty. Ltd.
  • 2. FME is good for Broad User Skill Levels FME is good for Maintainability FME is good for Portability FME is good for Rapid Modification
  • 3. Why using Python is bad… The FME transformer library is very extensive. FME does limit us, but with good reason. It uses a simple data paradigm that aligns with most spatial data, collections of features that each have a well defined set of attributes. We perform operations discretely on a single feature at a time. Sometimes this can be frustrating but remember: Don’t reinvent the wheel! Try rephrasing the problem you are solving!
  • 4. Where can Python be used? ● Start-up Scripts – Executes before FME transformers (even readers…) ● Shut-down Scripts – Executes after all FME transformers are finished ● Scripted Parameters – Executes on start-up and preserves the value ● PythonCreator – Has no input, Python defines all features outputted ● PythonCaller – Executes function once or calls input once per feature
  • 5. Good examples for Python in FME
  • 6. Smart Scripted Parameters While the Workspace Runner is useful, in trivial cases its not always ideal. If the only requirement is glob style directory search to provide file paths the workspace runner leaves excess complexity for deployment. Solution: Script glob search into parameter to return import fme, fmeobjects, glob # Get parameters set by user to initiate the glob search rootpath = fme.macroValues['rootPath'] # Glob search for file candidates candidates = glob.glob(rootpath + '/**/data.TAB', recursive = True) # Return string that matches what FME expects if candidates: return '""' + '" "'.join(candidates) + '""' else: return "" Example: Avoiding the workspace runner
  • 7. Front Stage File Manipulation FME rightly treats the data schema of some file formats quite strictly, unlike users sometimes. This impacts MapInfo and sometimes Excel files. Solution: Rename/copy the file to a standard filename - Published Parameter (Target File) - Private Parameter (Reader Target) import fme, fmeobjects from shutil import copy2 # Extract required info from macroValues fmepath = fme.macroValues['FME_MF_DIR'] targetfile = fme.macroValues['fileName'] # Check parameter is assigned if targetfile: # Copy2 will automatically overwrite existing # file. Set reader target to private parameter # containing: # $(FME_MF_DIR)Standard.xlsx copy2(targetfile, fmepath + 'Standard.xlsx') Example: File Formats playing badly
  • 8. Inter-feature Dependant Operations Assuming features have ID’s that are not consecutive. If features have two attributes, one representing the component ahead and one the component behind, how do we sort the features? Solution: Sort elements by matching ahead ID to behind ID Example: Paired Sorting Sort Order 1 Behind 934AH9 Ahead 365U33 Sort Order 2 Behind 6433OE Ahead 934AH9 Sort Order 3 Behind 18KW22 Ahead 6433OE Sort Order 4 Behind 20554Z Ahead 18KW22
  • 9. Repeated(recursive) operations (N > 3 or N = ?) FME was designed to work with tabular not network/graph style data. As such, recursive algorithms such as DFS or BFS are nearly impossible to implement with native transformers. Solution: Gather all the data into Python then process in memory Think carefully about how you output! Example: Trace network data A B D E C GFH I
  • 10. Non-standard Geometry Manipulation FME offers well developed options for direct geometry manipulation, scaling, offsetting or rotating. Less typical geometry manipulation can be tricky though. Solution: Implement custom geometry transformation in Python Example: Mirror around arbitrary plane geom = feature.getGeometry() points = line.getPoints() x, y, z = point.getXYZ() point.setXYZ(x, y, z)
  • 11. Tedious Operations For simple cases FME string manipulation is more than sufficient. Building a string conditionally based on 20+ attributes is possible but very tedious and difficult to maintain. Solution: Python string manipulation to efficiently build the string import fme, fmeobjects # Attribute to label lookup dictionary attributeMap = { '5_040': '5pr', '50_040': '50pr', '100_040': '100pr', '200_040': '200pr', '400_040': '400pr', ... x 25 more, } class FeatureProcessor(object): def __init__(self): pass def input(self,feature): # Use dictionary comprehension to conditionally build elements of label attributes = {attributeMap[key]: feature.getAttribute(key) for key in attributeMap.keys() if feature.getAttribute(key) and feature.getAttribute(key) > 0} # Join label elements to form a single string label = ", ".join([str(int(attributes[key])) + "x" + key for key in attributes.keys()]) feature.setAttribute('LABEL', label) self.pyoutput(feature) def close(self): pass Example: Build very complex string
  • 12. General Rules for Python use ● Recursion ● File Manipulation ● FME forums say its not possible
  • 13. Hints for Python in FME 1. Logger rather than Print 2. Scripted Parameters are hard to Debug 3. Don’t import non-standard libraries 4. You can import FME libraries to external python scripts 5. Don’t use copies of a PythonCaller
  • 14. import fme import fmeobjects logger = fmeobjects.FMELogFile() parameter = fme.macroValues['ParameterName'] logger.logMessageString("{Python Script} Parameter set: %s" % parameter) # Template Class Interface: # When using this class, make sure its name is set as the value # of the 'Class or Function to Process Features' transformer parameter class FeatureProcessor(object): def __init__(self): pass def input(self, feature): self.pyoutput(feature) def close(self): pass Useful Pattern – FME Env. Dictionary
  • 15. import fme import fmeobjects # Template Class Interface: # When using this class, make sure its name is set as the value # of the 'Class or Function to Process Features' transformer # parameter class FeatureProcessor(object): def __init__(self): self.featureList = [] def input(self, feature): self.featureList.append(feature) def close(self): for feature in self.featureList: self.pyoutput(feature) Useful Pattern – Bulk Feature Manipulation
  • 16. Example: Tiled Grid Viewports PythonCaller: Consumes point and line geometry, coverts to points then divides space to provide viewport polygons that will overlay every point in the set. Useful for creating AutoCAD viewports or other pagination of your geometry.
  • 17. Example: Procedural Tree Layout for Logical Networks Start-up Python Script: Parses logical connectivity then builds GML file with generated geometry for export via FME to other file formats such as AutoCAD to a database as a pre-calculated UI display geometry
  • 18. THANK YOU! Dr. Jonathan Stanger jstanger@spatialpartners.com