Presentation is loading. Please wait.

Presentation is loading. Please wait.

Ergo Developer Tutorial

Similar presentations


Presentation on theme: "Ergo Developer Tutorial"— Presentation transcript:

1 Ergo Developer Tutorial
NCSA, UIUC

2 Eclipse RCP installation

3 Eclipse RCP Installation
Objective To learn how to install Eclipse Rich Client Platform (RCP) Contents System Prerequisites Eclipse Download and Installation Updating Eclipse to latest release

4 System Prerequisites Operating System
Linux (just about any version) MacOSX (10.5 Leopard or higher) Windows (XP and higher) Java: Eclipse requires Oracle or IBM Java Need Java SDK Java 1.8 or higher Java 1.8 is the same as JDK 8.0 The GNU Java Compiler (GCJ), which comes standard on Linux, will not work. OpenJDK, distributed with some Linux distributions, comes closer to working, but should not be used

5 Eclipse Packages The current version of Eclipse (4.6) is also known as “Neon” Eclipse is available in a number of different packages for different kinds of development Click on Get Eclipse Neon installer to download the Eclipse installer and run it. For Ergo, we recommend the Eclipse for RCP and RAP Developers

6 Eclipse Installer (1) Imaginations unbound

7 Eclipse Installer (2) Imaginations unbound

8 Exercise Download the “Eclipse Installer” to your laptop
If your machine is Linux or Mac OS X, untar the file On Mac OS X you can just double-click in the Finder Run the installer executable. When it asks which package to install, select “Eclipse for RCP and RAP Developers” This creates an eclipse folder containing the executable as well as other support files and folders

9 Starting Eclipse Linux Mac OS X Windows
From a terminal window, enter “<eclipse_installation_path>/eclipse/eclipse &” Or, open the eclipse folder Double-click on the eclipse executable Mac OS X From Finder, open the eclipse folder where you installed Double-click on the Eclipse application Or from a terminal window Windows Open the eclipse folder

10 Specifying a Workspace
Eclipse prompts for a workspace location at startup time The workspace contains all user-defined data Projects and resources such as folders and files The default workspace location is fine for this tutorial

11 Eclipse Welcome Page Displayed when Eclipse is run for the first time
Select “Go to the Workbench”

12 Updating Eclipse RCP Eclipse releases two service packs per major release To check for updates, select Help > Check for Updates… If there are updates installed, Restart eclipse after installing Ergo can be updated in a similar way

13 Exercise Launch Eclipse RCP and select the default workspace
Go to Help > Check for Updates… Install GEF and Zest SDKs Install updates – if any

14 Eclipse RCP/Ergo Overview

15 Eclipse RCP/Ergo Overview
Objective To introduce the Eclipse RCP platform and Ergo Platform architecture Contents What is Eclipse RCP? What is Ergo?

16 The Eclipse Platform Integrated development environments(IDEs) for Java, C/C++, Fortran, etc Factor out the language independent parts (platform) Then, add in the language-specific pieces later (plug-ins) “The Eclipse platform itself is a sort of universal tool platform – it is an IDE for anything and nothing in particular.” – Eclipse Platform Overview

17 What is Eclipse? Universal platform for integrating development tools
Open, extensible architecture based on plug-ins Plug-ins are installed into Eclipse to add new behavior JDT is just a collection of plug-ins Java VM Eclipse Platform Java Dev Tools (JDT) Plug-in Dev. Env (PDE)

18 RCP Core

19 Eclipse Plug-in Architecture
OSGi is a specification describing a modular approach for Java applications Plug-in – smallest unit of Eclipse function Extension Point – named entity for collecting “contributions” Example: extension point for Ergo analysis Extension – a contribution Example: an Ergo analysis

20 Eclipse Plug-in Arch. (2)
Each plug-in Contributes to 1 or more extension points Optionally declares new extension points Depends on a set of other plug-ins Contains Java code libraries and other files May export Java-based APIs for downstream plug-ins Lives in its own plug-in subdirectory Details are defined in the plug-in manifest Manifest declares contributions Code implements contributions and provides API plugin.xml file in root of plug-in subdirectory

21 Eclipse Plug-in Arch. (3)
Plugin example Plug-in A Declares extension point P Declares interface I to go with P Plug-in B Implements interface I with its own class C Contributes class C to extension point P Plug-in A instantiates C and calls its I methods plug-in A plug-in B extension point P extension interface I class C

22 Core Technologies OSGI Provides plug-in based environment for Eclipse
Permits lazy-loading of plug-ins Permits multiple version of the same plugin/packages to co-exist Every Eclipse plug-in is an OSGi plug-in (or bundle) Every OSGi plug-in can be treated as a standard JAR outside of OSGi

23 Core Technologies (2) SWT – a platform independent widget toolkit that wraps native widgets offering a native look and feel across platforms JFace – provides Model-View-Controller wrapping for SWT widgets (e.g. TreeViewer, TableViewer, etc) Model – consists of application data, business rules, logic and functions View – visual representation of the data (e.g. chart, diagram) Controller – mediates input converting commands for the model or view

24 Eclipse Basics The workbench contains the menus, toolbars, editors, and views that make up the main Eclipse Window The workbench represents the desktop development environment Contains a set of tools for resource management Provides a common way to navigate through the resources Multiple workbenches can be opened simultaneously Only one workbench per workspace View View Editor View

25 Perspectives A Perspective is a visual container for a set of views/editors They are task oriented, i.e. they contain specific views for doing certain tasks Java Perspective – Java development C++ Perspective – C++ development

26 View A View is typically used to work on a set of data, might be hierarchical Example: Eclipse package explorer, Ergo Scenarios view Views can be freely positioned in the User Interface

27 Components of RCP App. Main program – a RCP main application class implements IApplication, synonymous to the main method for a standard Java application This class should be defined via extension point org.eclipse.core.runtime.application A Perspective – defines the layout of your application Declared via extension point org.eclipse.ui.perspective Workbench Advisor – controls the appearance of the application (menus, toolbars, perspectives, etc)

28 Ergo-EQ Architecture

29 Ergo Core Technologies
Eclipse RCP Geotools Visualization Toolkit JFreeChart Ktable Jasper Reports

30 More RCP Resources Eclipse RCP Tutorial Eclipse RCP Wiki
Eclipse RCP Wiki

31 Setup Ergo Development Environment

32 Setup Ergo Development Environment
Objective Checkout all required Ergo projects for development Content Step by step instructions to checkout each repository Adding projects to working sets Full instructions on Ergo wiki: Environment Setup Neon

33 Ergo Repositories One Git repositories make up Ergo and Ergo-EQ with package names specific to core, earthquake, gis, etc ergo If you check out the repository in different workspace; Delete the project (without deleting the content) Move the repository to desired location Switch to Git Repository Exploring Perspective Click on “Add existing local repository” Select the your Git repository Right-click on the git repo and select “import projects”

34 Checkout Ergo Repository
In Eclipse, go to File > Import > Git > Projects from Git Click Next Select Clone URI and Click Next Protocol: HTTPS: Copy and Paste into the URI field: If you have account on opensource.ncsa.illinois.edu: For u/p, enter your opensource credentials, click Next

35 Checkout Ergo Repository (2)
Select only master develop-v1 Click Next

36 Checkout Ergo Repository (3)
Assuming the default “workspace”, we recommend creating a git directory in the workspace and then checking out the repository to that directory eclipse_workspace/git/ergo Select Master as Initial branch Click Next

37 Checkout Ergo Repository (4)
It will take some time to clone the repository Select Import existing projects Click Next

38 Checkout Ergo Repository (5)
Select all projects Uncheck the box Search for nested projects Check Add project to working sets See next slide...

39 Checkout Ergo Repository (6)
To add the checked out files to a working set: Click Select Click New Select Java Click Next Where it says “Working set name” enter ergo-core Click Finish Check the box that says ergo-core Click OK See Next Slide

40 Checkout Ergo Repository (7)
Your Import Projects dialog should look similar to this Click Finish Projects will be checked out into workspace/git/ergo and added to the working set ergo-core

41 Show Working Sets Use dropdown menu to organize projects by Working Sets Select Top Level Elements – Working Sets

42 Exercise Checkout ergo git repository into working set ergo-core
In Package Explorer, select to show Working Sets

43 Set Target Platform - Neon
Find project edu.illinois.ncsa.ergo.eq.rcp Double click on ergo_neon.target to open it. Click Set as Target Platform Please wait for the compilation

44 Close Unused Projects (plugins)
Find a project, edu.illinois.ncsa.ergo.developertools Right click on the project title Select Close Project Do same operation for projects org.geotools.mappane.modified Imaginations unbound

45 Launch Ergo-EQ Find project edu.illinois.ncsa.ergo.eq.rcp
Double click on the file ergo-eq.product Under Testing click on Launch an Eclipse application If you see a dialog with the message “errors exist in org.geotools”, click Proceed

46 Analysis framework

47 Analysis Framework Objective Content Create a new Ergo Analysis
Create the Analysis description file (User Interface, XML) Create the Analysis Task (Java code) Register Analysis (description file) with newAnalyses extension point Register Analysis Task with ogreTasks extension point Launch Ergo-EQ with new analysis

48 Step 1. Analysis Description File
XML file specifying the inputs, outputs, and parameters for the new analysis Defines User Interface for New Analysis Put file in defining plug-ins descriptions folder

49 Create New Plug-in Create new eclipse plugin, File > New > Plug-in Project Project Name: edu.illinois.ncsa.ergo.eq.tutorial Leave rest as default Click Next

50 Create New Plug-in (2) Uncheck the box “This plug-in will make contributions to the UI” Leave rest as default Click Finish You can find your project under “Other Projects” working set

51 Create Descriptions Folder
Right click on the new project and select New > Folder Where it says “Folder Name:” enter descriptions Click Finish

52 Create Analysis Description File
Similar to the folder creation, right click on the descriptions folder and select New > File Where it says “File name” enter NewBuildingDamage.xml Click Finish

53 Exercise Create new Plug-in Project Create descriptions folder
Create empty file NewBuildingDamage.xml

54 Analysis Description Tag
id (required) – must match the id given to the analysis in the edu.illinois.ncsa.ergo.core.analysis.newAnalyses extension point (we will add the id later) help-context (optional) – assigns a help context id to this analysis Code: <analysis-description id="" help-context="">

55 Analysis Type Tag <analysis-type> Code:
type (required) - specifies analysis iteration type property (required) name – special keyword to identify which dataset is the dataset being iterated over value – dataset to iterate over Code: <analysis-type type="simpleIteration"> <property name="iteratingDatasetKey" value="buildings"/> </analysis-type>

56 Groups Tag <groups> Code:
Specify the grouping of User Interface Inputs and parameters Code: <groups> <group-name>Required</group-name> <group-name>Advanced</group-name> </groups>

57 Parameter Tag Attributes
group (unused) – string that must match a member of <groups> format – the format of whatever phylum parameter this is. For datasets, indicates type of dataset (mapping, shapefile, etc) phylum – type of parameter, currently supports string, dataset, or boolean cardinality – how many of this type, currently supports single or multiple key – name of property which will correspond to Analysis Task Setter (e.g. key = “building”, Analysis Task must have setBuilding) friendly-name – name that should be displayed in the User Interface optional – value of true denotes this parameter is not needed to perform the analysis advanced – a value of true denotes this is an advanced parameter and should be in that grouping. It is required, but this will hide it in the UI under Advanced grouping

58 Parameter Tag (2) Elements
<types> A list of types that are accepted by this <parameter>, this should match the tag field of the dataset type defined at edu.illinois.ncsa.ergo.gis.gisSchemas <description> A textual description of the parameter.  Primarily used to generate tooltips in the UI.

59 Result Name Code: <!-- Name of result dataset -->
<parameter format="resultName" phylum="string" cardinality="single" key="buildingDamagev4.resultName" friendly-name="Result Name"/>

60 Building Dataset Code: <!-- Building Dataset Input -->
<parameter phylum="dataset" cardinality="single" key="buildings" friendly-name="Buildings"> <types> <type>buildingv4</type> <type>buildingv5</type> </types> </parameter>

61 Hazard Dataset Code: <!-- Hazard Dataset Input -->
<parameter phylum="dataset" cardinality="multiple" key="hazard" friendly-name="Hazard"> <types> <type>hazardRaster</type> <type>deterministicHazardRaster</type> <type>hazard</type> </types> </parameter>

62 Fragility Dataset Code:
<!-- Building Fragility Dataset Input --> <parameter advanced="true" phylum="dataset" cardinality="single" key="fragilities" friendly-name="Fragilities"> <types> <type>buildingFragilities</type> </types> </parameter>

63 Output Tag <output> - two required properties Attributes
base-dataset-key – the key of the <parameter> which is the base for this new Dataset Schema – The id of the schema that this Dataset implements (see edu.illinois.ncsa.gis.gisSchemas extension point) Attributes format – the format of the parameter, currently supports string or dataset key – the name of the property for which value should be added. No spaces allowed friendly-name – name of property for which value should be added Elements property – additional properties required by output

64 Output Code: <!-- OUTPUTS -->
<output friendly-name="Building Damage" key="buildingDamagev4" phylum="dataset" format="shapefile" geom="buildings" guids="buildings"> <property name="buildings" type="base-dataset-key" value="buildings"/> <property name="schema" type="schema" value="edu.illinois.ncsa.ergo.eq.schemas.buildingDamageVer4.v1.0"/> </output>

65 Produced Types Tag <produced-types> - types produced by this analysis Elements <type> – should match the output type (e.g. the tag in the edu.illinois.ncsa.ergo.gis.gisSchemas extension Code: <produced-types> <type>buildingDamagev4</type> </produced-types>

66 Closing Tag Code: Ctrl-f to reformat the code Ctrl-s to save the file
</analysis-description>

67 Exercise Add the analysis description pieces for the new analysis

68 Step 2. Create Analysis Task
Java class performs the work Must implement the Analysis Task that corresponds to the <analysis-type> (e.g. SimpleFeatureTask) Keys given to each parameter must match set methods in this class Column names given to the outputs must match values given in the output schema type

69 Add Required Dependencies
Open project MANIFEST.MF under META-INF folder Select Dependencies tab Under Required Plug-ins, click Add edu.illinois.ncsa.ergo.core.analysis edu.illinois.ncsa.ergo.gis edu.illinois.ncsa.ergo.eq edu.illinois.ncsa.ergo.eq.hazard ncsa.tools.elf.core ncsa.tools.common ncsa.tools.ogrescript org.dom4j org.geotools Ctrl-s to save MANIFEST.MF

70 Create New Java Class Right click on the project, New > Class
Package: edu.illinois.ncsa.ergo.eq.tutorial.tasks Name: NewBuildingDamageTask Superclass: SimpleFeatureTask - edu.illinois.ncsa.ergo.core.analysis.ogrescript.tasks.core.SimpleFeatureTask Click Finish

71 Add Unimplemented Methods
If your eclipse already add the method, you don’t need to do this part. Click on the red x in the class and select add unimplemented methods Adds handleFeature method – each building is passed in 1 at a time, we will add our business logic here

72 Add Set Methods For key=buildings For key=hazard For key=fragilities
Nothing to set, this is our iterating dataset For key=hazard setHazard(List<RasterDataset> hazardList) For key=fragilities setFragilities(FragilityDataset fragilities) Note: if your eclipse complaints “can’t resolve a type”, ctrl+shift+o (it will import all classes you need) RasterDataset is the parent of HazardDataset for scenario eq

73 Hazard Input Add class variable Code: Add Set Method
When you import the classes with ctrl+shift+o, it will ask to choose which to import for List. Please choose Java.util.List private FragilityHazardSet hazardSet = new FragilityHazardSet(); public void setHazard(List<RasterDataset> hazardList) { hazardSet.setDatasets(hazardList); }

74 Fragility Input Add Class Variable Code: Add Set Method Code
private FragilityDataset fragilities; public void setFragilities(FragilityDataset fragilities) { this.fragilities = fragilities; }

75 Exercise Add class variable for fragility and Set Method
Add class variable for hazard and Set method

76 Implement handleFeature
Code: When you import the classes with ctrl+shift+o, it will ask to choose which to import for Point. Please choose Com.vividsolutions.jts.geom.Point Point location = (Point) feature.getAttribute(0); // Period of Demand Type double period = 0.0; // Demand Type for Fragility String demandHazardType = "PGA"; // Units of Demand for Fragility String demandHazardUnits = "g"; // Default int spectrumOverride = 0;

77 Implement handleFeature (2)
Get hazard that best matches the period, demand type and demand units. It will find the dataset that can best provide the hazard Code: //Find Hazard Value at Location double hazardVal = hazardSet.getHazardVal(location, period, demandHazardType, demandHazardUnits, spectrumOverride);

78 Implement handleFeature (3)
Get the first fragility set in the map and get the damage value for the first fragility curve in the set for the hazard value Store the result in the resultMap associated with the Task Code: FragilitySet randomFragility = fragilities.getFragilitySets().values().iterator().next(); double damage = randomFragility.getFragilities().get(0).getValueAtPoint(hazardVal); resultMap.put("meandamage", damage );

79 Exercise Implement handleFeature Get hazard value at building location
Get Fragility curve and corresponding damage for the hazard value Store damage as meandamage

80 Step 3. Register Analysis
Objective Register analysis with edu.illinois.ncsa.ergo.core.analysis.newAnalyses extension point Content How to register a new analysis

81 Analysis Extension Point
Inside the project edu.illinois.ncsa.ergo.eq.tutorial, open MANIFEST.MF Click on the Extensions tab Click Add Where it says Extension Point filter, search for edu.illinois.ncsa.ergo.core.analysis.newAnalyses Select the Extension Point and Click Finish

82 Create Analysis Extension
To create a new extension, right click on edu.illinois.ncsa.ergo.core.analysis.newAnalyses and select New > analysis Your eclipse may already add the new analysis for you, in this case, you don’t need to add another analysis This will create a blank analysis extension with the following attributes: id – This id must match the id given in the analysis description file, NewBuildingDamage.xml name – Friendly name of the analysis and should be i18n tag – This tag must match the tag in the ncsa.tools.ogrescript.ogreTasks extension. No spaces allowed descriptor – Location of the analysis description file category – The category to put the new analysis in, for display purposes description – brief description of the new analysis

83 Analysis Extension Details
Fill in the following for our new analysis id edu.illinois.ncsa.ergo.eq.tutorial.NewBuildingDamage name New Building Damage tag tutorialBuildingDamage descriptor descriptions/NewBuildingDamage.xml category Building description new building damage analysis Ctrl+s to save it

84 Update Analysis Description
Use the same ID for analysis description file Open NewBuildingDamage.xml Replace (line 1) With <analysis-description id="" help-context=""> <analysis-description id="edu.illinois.ncsa.ergo.eq.tutorial.NewBuildingDamage" help-context="">

85 Exercise Add Extension Point in MANIFEST.MF
Add Extension to Extension Point for new Analysis in MANIFEST.MF Update NewBuildingDamage.xml with analysis id

86 Step 4. Register Analysis Task
Objective Register new analysis task with ncsa.tools.ogrescript.ogreTasks extension point Content How to register a new analysis task

87 Analysis Task Extension Point
Inside the project edu.illinois.ncsa.ergo.eq.tutorial, open MANIFEST.MF Click on the Extensions tab Click Add Where it says Extension Point filter, search for ncsa.tools.ogrescript.ogreTasks Select the Extension Point and Click Finish

88 Create Analysis Task Extension
Similar to the newAnalyses extension, right click on ncsa.tools.ogrescript.ogreTasks and select New > ogreTasks This will create a blank analysis task extension with the following attributes: id – This id should match the fully qualified class name of the task (see class attribute) name – This is the friendly name of the Task and should be i18n tag – This tag must match the tag in the edu.illinois.ncsa.ergo.core.analysis.newAnalyses extension point class – This points to the implementing class we created previously

89 Analysis Task Extension Details
Fill in the following for our new analysis task id edu.illinois.ncsa.ergo.eq.tutorial.tasks.NewBuildingDamageTask name New Building Damage Task tag tutorialBuildingDamage Class Ctrl-s to save

90 Add Plug-in to Ergo Go to Run > Run Configurations…
Under Eclipse Applications select ergo-eq.product Select the Plug-ins tab Locate our plugin edu.illinois.ncsa.ergo.eq.tutorial and check the box to include it Click Run

91 Sync Repositories Click on Synchronize button to fetch defined repositories

92 Create New Scenario Select File > New Scenario
Where it says Name enter Tutorial Scenario Click Next

93 Create New Scenario (2) Where it says Country select United States of America Expand Tennessee and select Shelby county Click Next Click Finish

94 Execute Analysis Right Click on the new scenario and select Execute Analysis Expand Building and select New Building Damage Click Finish

95 New Building Damage Click on the New Building Damage box to build the User Interface Note: the analysis is currently red because not all input parameters are satisfied See next slide for inputs

96 New Building Damage (2) For Result Name, enter Building Damage
For Buildings, click Search and locate Shelby County RES3 For Hazard, click Search and locate Memphis 7.7M PGA For Fragilities, click Search and locate Default Building Fragilities 1.0 Click the Execute button that should now be enabled

97 Exercise Run the New Building Damage analysis
You may have some problem to run because of the library we are using is out dated.

98 Advanced Topics Add new Data Type

99 Add Dataset Type Objective Content Add new dataset type to Ergo-EQ
Creating a new dataset schema Adding schema extension to extension point Adding field-specific metadata

100 New Dataset Schema Create a folder in the root directory of your plugin called gisSchemas Create a new empty file called ergo-tutorialBuildingDamage_1.0.xsd in gisSchemas folder See ergo-buildingDamageVer4_1.0.xsd in plugin edu.illinois.ncsa.ergo.eq as an example

101 Sample Code for Schema <?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:gml=" xmlns:xsd=" targetNamespace=" xmlns:xlink=" xmlns:iwfs=" targetNamespaceOptional="true" xmlns=" elementFormDefault="qualified"> <xsd:import namespace=" schemaLocation=" <xsd:element name="TUTORIALBUILDINGDAMAGE" substitutionGroup="gml:_Feature" type="iwfs:TUTORIALBUILDINGDAMAGE"/> <xsd:complexType name="TUTORIALBUILDINGDAMAGE"> <xsd:complexContent> <xsd:extension base="gml:AbstractFeatureType"> <xsd:sequence> <xsd:element name="ergo.meandamage" minOccurs="0" nillable="true" type="xsd:double"/> </xsd:sequence> </xsd:extension> </xsd:complexContent> </xsd:complexType> </xsd:schema>

102 Add Schema Extension Point
Go to edu.illinois.ncsa.ergo.eq.tutorial project and open MANIFEST.MF Click on Extensions Click Add Add edu.illinois.ncsa.ergo.gis.gisSchemas

103 Add Schema Extension Right click on edu.illinois.ncsa.ergo.gis.gisSchemas and select New > gisSchema This will create a new extension with the following attributes id – The id of the schema name – A friendly name for the schema version A version identifier for the schema type – a short type name for the schema (used in analysis description to identify input types) description – a user-friendly description of the schema file – The schema file defined in the previous step format – The format of the schema. Predefined formats include shapefile, fragility, mapping, raster, and table requiredFields – The list of fields that are required as a minimum for this schema. These will be prompted to map during ingestion of data mapLayer – For shapefiles, the suggested smart layering position in the map. Should be between 1 and 100. A mapLayer of -1 indicates dataset should be invisible by default category – a category name for the schema. Categories determine what subfodlers the schemas appear in the repository

104 Schema Extension Details
Id - edu.illinois.ncsa.ergo.eq.tutorial.schemas.tutorialBuildingDamage.v1.0 name - Tutorial Building Damage version - 1.0 type - tutorialBuildingDamage description - Tutorial building damage output type file - gisSchemas/ergo-tutorialBuildingDamage_1.0.xsd format - shapefile requiredFields - meandamage mapLayer - 10 category – Buildings Ctrl-s to save

105 Field Specific Metadata
Create a folder in the root directory of your plugin called gisMetadata Create a file name corresponding to the schema xsd file name, but ending in .xml (e.g. ergo-tutorialBuildingDamage_1.0.xml) Ergo will automatically look for a file with the same prefix in gisMetadata when displaying fields in the User Interface

106 Metadata Attributes Column-id – The id to match the column id from the xsd file. Should not include the ergo. prefix Friendly-name Is-numeric Unit Field-length Importance Is-result Agg-type

107 Sample Metadata for Data Type
<?xml version="1.0" encoding="ISO "?> <table-metadata> <column-metadata column-id="meandamage" friendly-name="Mean Structural Damage" is-result="true" is-numeric="true" unit="decimal" importance="mainValue" agg-type="mean" field-length="10" /> </table-metadata>

108 Create custom iterator
Advanced Topics Create custom iterator

109 Create Custom Iterator
Objective Add new custom iterator Content What is a custom iterator Adding a custom iterator extension

110 Custom Iterators Simple Feature Iterator Table Iterator
Iterates over a feature dataset providing 1 feature per iteration to the analysis task Table Iterator Iterates over a table dataset providing 1 row per iteration to the analysis task Custom Iterator Handles special cases where simple iteration is not applicable (e.g. see Intersect Features analysis) Similar to simple/table iterator, except all datasets are provided to the task to handle iteration

111 Create Analysis Task Right click on the project edu.illinois.ncsa.ergo.eq.tutorial and select New > Class Package – edu.illinois.ncsa.ergo.eq.tutorial.tasks Name – CustomIteratorAnalysisTask Superclass – AnalysisBaseTask Click Finish

112 Implement Custom Analysis Task
Code private SimpleFeatureType resultType; private FeatureDataset myBuildings; private DefaultFeatureCollection resultBldg; public FeatureType getBldgResult() { return resultType; } public void setBldgResult(SimpleFeatureType resultType) { this.resultType = resultType; public void setMyBuildings(FeatureDataset myBuildings) { this.myBuildings = myBuildings;

113 Implement Custom Analysis Task (2)
Code @Override protected void wrappedExecute(IProgressMonitor monitor) throws ScriptExecutionException { try { generateBldgResult(); } catch (TaskException e) { e.printStackTrace(); }

114 Implement Custom Analysis Task (3)
Code private void generateBldgResult() throws TaskException { try { resultBldg = new DefaultFeatureCollection(); SimpleFeatureCollection fc = myBuildings.getFeatures(); SimpleFeatureType originalSchema = fc.getSchema(); String typeName = resultType.getTypeName(); SimpleFeatureTypeBuilder builder = FeatureUtils.prepareSimpleFeatureTypeBuilder( originalSchema, typeName); builder.add("meandamage", Double.class); SimpleFeatureType newSchema = builder.buildFeatureType(); SimpleFeatureIterator iter = fc.features(); while (iter.hasNext()) { List<Object> data = new LinkedList<Object>(); SimpleFeature f = iter.next(); List<Object> values = f.getAttributes(); for (Object obj : values) { data.add(obj); } SimpleFeature newf = SimpleFeatureBuilder.build(newSchema, data, null); resultBldg.add(newf); } finally { iter.close(); commitFeatures(resultBldg, createFeatureStore(newSchema, "feature.store.bldgResult")); } catch (IOException e) { error("IO problem", e); } catch (EnvironmentAccessException e) { error("Ogre Script Problem", e);

115 Implement Custom Analysis Task (4)
Code private SimpleFeatureStore createFeatureStore(SimpleFeatureType featureType, String featureStoreKey) throws IOException, MalformedURLException,EnvironmentAccessException { Path tempDir = Files.createTempDirectory("temp"); String tempFileName = tempDir.toString() + "/" + featureType.getTypeName() + ".shp"; File tempShapefile = new File(tempFileName); URL shapeURL = tempShapefile.toURI().toURL(); DataStore shapefileDatastore = new ShapefileDataStore(shapeURL); shapefileDatastore.createSchema(featureType); SimpleFeatureStore featureStore = (SimpleFeatureStore) shapefileDatastore.getFeatureSource(featureType.getTypeName()); environment.addOrSetEntry(featureStoreKey, featureStore, false); return featureStore; }

116 Implement Custom Analysis Task (5)
Code private void commitFeatures(DefaultFeatureCollection featureCollection, SimpleFeatureStore featureStore) throws IOException { DefaultTransaction transaction = new DefaultTransaction(); try { featureStore.setTransaction(transaction); featureStore.addFeatures(featureCollection); transaction.commit(); featureStore.setTransaction(Transaction.AUTO_COMMIT); } finally { featureCollection.clear(); transaction.close(); }

117 Exercise Create custom iterator class Implement iterator class
Create Analysis Task Implement Analysis Task

118 Custom Analysis Description
Right click on the descriptions folder and select New > File Where it says “File name” enter CustomIteratorBuildingDamage.xml Click Finish

119 Custom Analysis Description (2)
Code <analysis-description id="edu.illinois.ncsa.ergo.eq.tutorial.CustomBuildingDamage" help-context=""> <analysis-type type="noIteration" > </analysis-type> <!-- GROUPS input and parameter fields --> <groups> <group-name>Required</group-name> <group-name>Advanced</group-name> </groups> <!-- INPUTS --> <!-- Name of result dataset --> <parameter format="resultName" phylum="string" cardinality="single" key="bldgResult.resultName" friendly-name="Result Name"/> <!-- Building Dataset Input --> <parameter phylum="dataset" cardinality="single" key="myBuildings" friendly-name="Buildings"> <types> <type>buildingv4</type> <type>buildingv5</type> </types> </parameter> <!-- OUTPUTS --> <output friendly-name="Building Damage" key="bldgResult" phylum="dataset" format="shapefile" geom="myBuildings" guids="myBuildings"> <property name="myBuildings" type="base-dataset-key" value="myBuildings"/> <property name="schema" type="schema" value="edu.illinois.ncsa.ergo.eq.tutorial.schemas.tutorialBuildingDamage.v1.0"/> </output> </analysis-description>

120 Register Custom Analysis
Register at newAnalyses extension point id - edu.illinois.ncsa.ergo.eq.tutorial.CustomBuildingDamage name – Custom Building Damage tag - example descriptor – descriptions/CustomIteratorBuildingDamage.xml category - Building

121 Register Custom Analysis Task
Register at ogreTasks extension point id – edu.illinois.ncsa.ergo.eq.tutorial.tasks.CustomIteratorAnalysisTask name – Custom Building Damage tag - example class - edu.illinois.ncsa.ergo.eq.tutorial.tasks.CustomIteratorAnalysisTask

122 Run Custom Iterator To see your new analysis with custom iterator, re-launch Ergo-EQ Open a scenario and follow the previous steps for executing a new analysis, you should see Custom Building Damage in the Building category

123 Questions?

124 Resources User/Developer Documentation
Analysis Framework Developer’s Guide Adding Dataset Types Git e-book


Download ppt "Ergo Developer Tutorial"

Similar presentations


Ads by Google