From c13800c91bdb75913a2c45d349da609ee6017c20 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Aur=C3=A9lien=20Lamercerie?=
 <aurelien.lamercerie@tetras-libre.fr>
Date: Wed, 1 Mar 2023 19:15:31 +0100
Subject: [PATCH] Development Init (amrbatch and tests packages, license,
 requirements)

---
 .gitignore                                    |   5 +
 LICENSE                                       |   5 +
 amrbatch/__init__.py                          |   9 +
 amrbatch/amr_analyzer.py                      | 289 ++++++
 amrbatch/amrld/.gitignore                     |   7 +
 amrbatch/amrld/LICENSE                        | 204 ++++
 amrbatch/amrld/README.md                      | 164 ++++
 amrbatch/amrld/amr-core-patterns.txt          |   3 +
 amrbatch/amrld/amr-core.txt                   |  52 +
 amrbatch/amrld/amr-ne.txt                     |  20 +
 amrbatch/amrld/amr_rdf2dot.py                 | 135 +++
 amrbatch/amrld/amr_to_jsonld.py               | 160 ++++
 amrbatch/amrld/amr_to_rdf.py                  | 432 +++++++++
 amrbatch/amrld/compare_smatch/__init__.py     |   0
 .../amrld/compare_smatch/amr_alignment.py     | 252 +++++
 amrbatch/amrld/compare_smatch/amr_metadata.py |  62 ++
 amrbatch/amrld/compare_smatch/smatch_graph.py | 210 +++++
 amrbatch/amrld/disagree_btwn_sents.py         | 293 ++++++
 amrbatch/amrld/requirements.txt               |   3 +
 amrbatch/amrld/simple-smatch-table.py         | 297 ++++++
 amrbatch/amrld/smatch/README.txt              | 103 ++
 amrbatch/amrld/smatch/__init__.py             |   0
 amrbatch/amrld/smatch/amr.py                  | 343 +++++++
 amrbatch/amrld/smatch/smatch-table.py         | 441 +++++++++
 amrbatch/amrld/smatch/smatch.py               | 863 +++++++++++++++++
 amrbatch/amrld/smatch/smatch2.py              | 887 ++++++++++++++++++
 amrbatch/amrld/test/bio_ras_0001_1.json       |  61 ++
 amrbatch/amrld/test/bio_ras_0001_1.rdf        |  39 +
 amrbatch/amrld/test/bio_ras_0001_1.txt        |  15 +
 amrbatch/amrld/test/pmid-11777939-32_amr.rdf  |  70 ++
 amrbatch/amrld/test/pmid-11777939-32_amr.txt  |  20 +
 amrbatch/amrld/test/test.amr.graph            |  12 +
 amrbatch/amrld/xref_namespaces.txt            |   3 +
 amrbatch/main.py                              |  55 ++
 amrbatch/propbank_analyzer.py                 | 254 +++++
 gpl-3.0.txt                                   | 674 +++++++++++++
 requirements.txt                              |   8 +
 tests/context.py                              |   8 +
 tests/input/SSC-ABSTRACT.txt                  |   1 +
 tests/input/test.txt                          |   1 +
 tests/test_amrbatch_main.py                   |  45 +
 41 files changed, 6505 insertions(+)
 create mode 100644 .gitignore
 create mode 100644 LICENSE
 create mode 100644 amrbatch/__init__.py
 create mode 100644 amrbatch/amr_analyzer.py
 create mode 100644 amrbatch/amrld/.gitignore
 create mode 100644 amrbatch/amrld/LICENSE
 create mode 100644 amrbatch/amrld/README.md
 create mode 100644 amrbatch/amrld/amr-core-patterns.txt
 create mode 100644 amrbatch/amrld/amr-core.txt
 create mode 100644 amrbatch/amrld/amr-ne.txt
 create mode 100644 amrbatch/amrld/amr_rdf2dot.py
 create mode 100644 amrbatch/amrld/amr_to_jsonld.py
 create mode 100644 amrbatch/amrld/amr_to_rdf.py
 create mode 100644 amrbatch/amrld/compare_smatch/__init__.py
 create mode 100644 amrbatch/amrld/compare_smatch/amr_alignment.py
 create mode 100644 amrbatch/amrld/compare_smatch/amr_metadata.py
 create mode 100644 amrbatch/amrld/compare_smatch/smatch_graph.py
 create mode 100755 amrbatch/amrld/disagree_btwn_sents.py
 create mode 100644 amrbatch/amrld/requirements.txt
 create mode 100755 amrbatch/amrld/simple-smatch-table.py
 create mode 100755 amrbatch/amrld/smatch/README.txt
 create mode 100644 amrbatch/amrld/smatch/__init__.py
 create mode 100755 amrbatch/amrld/smatch/amr.py
 create mode 100755 amrbatch/amrld/smatch/smatch-table.py
 create mode 100755 amrbatch/amrld/smatch/smatch.py
 create mode 100644 amrbatch/amrld/smatch/smatch2.py
 create mode 100644 amrbatch/amrld/test/bio_ras_0001_1.json
 create mode 100644 amrbatch/amrld/test/bio_ras_0001_1.rdf
 create mode 100644 amrbatch/amrld/test/bio_ras_0001_1.txt
 create mode 100644 amrbatch/amrld/test/pmid-11777939-32_amr.rdf
 create mode 100755 amrbatch/amrld/test/pmid-11777939-32_amr.txt
 create mode 100644 amrbatch/amrld/test/test.amr.graph
 create mode 100644 amrbatch/amrld/xref_namespaces.txt
 create mode 100644 amrbatch/main.py
 create mode 100644 amrbatch/propbank_analyzer.py
 create mode 100644 gpl-3.0.txt
 create mode 100644 requirements.txt
 create mode 100644 tests/context.py
 create mode 100644 tests/input/SSC-ABSTRACT.txt
 create mode 100644 tests/input/test.txt
 create mode 100644 tests/test_amrbatch_main.py

diff --git a/.gitignore b/.gitignore
new file mode 100644
index 00000000..954ce385
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,5 @@
+*.pyc
+__pycache__ 
+*.todo
+*.ttl.tbc
+*catalog-v001.xml
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 00000000..64725caa
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,5 @@
+AMR-Batch is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
+
+This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
diff --git a/amrbatch/__init__.py b/amrbatch/__init__.py
new file mode 100644
index 00000000..2bd3be3d
--- /dev/null
+++ b/amrbatch/__init__.py
@@ -0,0 +1,9 @@
+# -- Update System Path
+import os, sys
+LIB_PATH = os.path.dirname(os.path.abspath(__file__)) + '/'
+sys.path.insert(0, os.path.abspath(LIB_PATH))
+# print('Running in ' + LIB_PATH)
+# os.chdir(LIB_PATH)
+
+# -- Main Methods
+from main import parse_sentences_from_file 
diff --git a/amrbatch/amr_analyzer.py b/amrbatch/amr_analyzer.py
new file mode 100644
index 00000000..5785fd27
--- /dev/null
+++ b/amrbatch/amr_analyzer.py
@@ -0,0 +1,289 @@
+#!/usr/bin/python3.10
+# -*-coding:Utf-8 -*
+
+#==============================================================================
+# C.M. Tool: AMR Graph (penman) Analzer
+#------------------------------------------------------------------------------
+# Module to analyze AMR Graph in penman format
+#==============================================================================
+
+#==============================================================================
+# Importing required modules
+#==============================================================================
+
+import sys
+import glob
+import regex as re
+import propbank_analyzer
+
+from bs4 import BeautifulSoup
+
+
+#==============================================================================
+# Parameters
+#==============================================================================
+
+# Input/Output Directories
+INPUT_DIR = "../inputData/"
+OUTPUT_DIR = "../outputData/"
+
+# Regular expressions for AMR graph analysis
+AMR_PRED_RE = '[a-z]+-0\d'
+
+AMR_ARGOF_RE = ':ARG\d-of'
+
+AMR_ARG_RE = re.compile(r'''
+    \([^.]*\) (*SKIP)(*FAIL)  # match anything in parentheses and "throw it away"
+    |                          # or
+    :ARG\d                     # match :ARGi
+    ''', re.VERBOSE)
+
+
+
+#==============================================================================
+# Functions to find AMR predicate/argument relations
+#==============================================================================
+
+def find_pred_arg_relations(graph, relation_list):
+    """ Find all direct predicat/argument relations in a graph 
+        (argument as :ARGi), and add found relations in the input list.
+    """
+
+    for pred_match in re.finditer(AMR_PRED_RE, graph):
+        for arg_match in AMR_ARG_RE.finditer(graph[pred_match.end():]):
+            pred = pred_match.group()
+            arg = arg_match.group()
+            relation_list.append((pred, arg))
+            
+    return relation_list
+
+    
+def find_argof_pred_relations(graph, relation_list):
+    """ Find all undirect predicat/argument relations in a graph 
+        (argument as :ARGi-of), and add found relations in the input list.
+    """
+    
+    for arg_match in re.finditer(AMR_ARGOF_RE, graph):
+        pred_match = re.findall(AMR_PRED_RE, graph[arg_match.end():])
+        pred = pred_match[0]
+        arg = arg_match.group()
+        relation_list.append((pred, arg))
+        
+    return relation_list
+
+
+def find_all_pred_arg_relations(graph, relation_list):
+    """ Find all predicat/argument relations in a graph 
+        (argument as :ARGi or :ARGi-of), and add found relations 
+        in the input list.
+    """
+    
+    relation_list = find_pred_arg_relations(graph, relation_list)
+    relation_list = find_argof_pred_relations(graph, relation_list)
+    
+    return relation_list
+
+
+#==============================================================================
+# Functions to update relation list with probbank roles (from propbank frames)
+#==============================================================================
+
+def update_relation_list_with_propbank_role(old_relation_list):
+    
+    new_relation_list = []
+    
+    for (pred, orig_arg) in old_relation_list:
+        
+        orig_role = orig_arg[0:5]
+        new_role = propbank_analyzer.find_pb_role(pred, orig_role)
+        
+        if new_role is not None:
+            
+            new_arg = orig_arg[0:5] + '-' + new_role
+            if len(orig_arg) >= 8:
+                new_arg += orig_arg[5:8]
+                
+            new_relation_list.append((pred, orig_arg, new_arg))
+            
+        else:
+            print("*** relation (" + pred + ", " + orig_role + ") " +
+                  "no found in PropBank frames ***")
+            
+    return new_relation_list
+
+
+#==============================================================================
+# Functions to substitute arguments in AMR graph
+#==============================================================================
+
+def sub_betwenn_pos(text, start, end, new_str):
+    result = text[:start]
+    result += new_str
+    result += text[end:]
+    return result
+
+
+def substitute_pred_arg_relations(graph, relation_list):
+    """ Substitute direct predicat/argument relations in a given AMR graph.
+    """
+
+    for (pred, old_arg, new_arg) in relation_list:
+        
+        for pred_match in re.finditer(AMR_PRED_RE, graph):
+            
+            for arg_match in AMR_ARG_RE.finditer(graph[pred_match.end():]):
+                
+                start = pred_match.end() + arg_match.start()
+                end = pred_match.end() + arg_match.end()
+                
+                if ((pred == pred_match.group()) & 
+                    (arg_match.group() == old_arg)):
+                    
+                    graph = sub_betwenn_pos(graph, start, end, new_arg)
+            
+    return graph
+
+    
+def substitute_argof_pred_relations(graph, relation_list):
+    """ Substitute undirect predicat/argument relations in a given AMR graph.
+    """
+    
+    for (pred, old_arg, new_arg) in relation_list:
+        
+        for arg_match in re.finditer(AMR_ARGOF_RE, graph):
+            
+            pred_match = re.findall(AMR_PRED_RE, graph[arg_match.end():])
+            start = arg_match.start()
+            end = arg_match.end() 
+            
+            if ((pred == pred_match[0]) &
+                (arg_match.group() == old_arg)):
+                
+                graph = sub_betwenn_pos(graph, start, end, new_arg)
+        
+    return graph
+
+
+def substitute_all_pred_arg_relations(graph, relation_list):
+    """ Substitute all predicat/argument relations in a given AMR graph.
+    """
+    
+    graph = substitute_pred_arg_relations(graph, relation_list)
+    graph = substitute_argof_pred_relations(graph, relation_list)
+    
+    return graph
+
+
+#==============================================================================
+# Main Function(s)
+#==============================================================================
+
+def enrich_amr_graph_with_propbank_role(graph):
+    """
+    Enrich an AMR graph with PropBank roles.
+
+    Parameters
+    ----------
+    graph : STRING
+        AMR graph in PENMAN form.
+
+    Returns
+    -------
+    graph : STRING
+        AMR graph enriched with PropBank roles.
+
+    """
+    
+    relation_list = []
+    
+    relation_list = find_all_pred_arg_relations(graph, relation_list)
+    relation_list = update_relation_list_with_propbank_role(relation_list)
+    
+    graph = substitute_all_pred_arg_relations(graph, relation_list)
+    
+    return graph
+
+
+#==============================================================================
+# *** Dev Test ***
+#==============================================================================
+
+def dev_analyze(amr_graph_file):
+
+    print("\n" + "[CMT-Dev] AMR Graph Analyzer")
+    
+    print("\n-- Start data")
+    amr_graph_file = INPUT_DIR + amr_graph_file
+    print("----- Reading file " + amr_graph_file)
+    with open(amr_graph_file, 'r') as f:
+        amr_graph_1 = f.read()
+        amr_graph_2 = ''.join(amr_graph_1)
+    print("----- AMR Graph 1: \n" + amr_graph_1)
+    print("----- AMR Graph 2: \n" + amr_graph_2)
+    rel_list_1 = []
+    nb_relation_1 = len(rel_list_1)
+    print("----- Relation list 1 (init): " + str(rel_list_1))
+    print("----- Number of relations in list 1: " + str(nb_relation_1))
+    rel_list_2 = []
+    nb_relation_2 = len(rel_list_2)
+    print("----- Relation list 2 (init): " + str(rel_list_2))
+    print("----- Number of relations in list 2: " + str(nb_relation_2))
+    
+    print("\n-- Finding AMR predicate/argument relations (step-by-step)")
+    rel_list_1 = find_pred_arg_relations(amr_graph_1, rel_list_1)
+    if len(rel_list_1) > nb_relation_1:
+        nb_relation_1 = len(rel_list_1)
+        print("----- some relations found ")
+        print("----- Relation list (update): " + str(rel_list_1))
+        print("----- Number of relations in list 1: " + str(nb_relation_1))
+    else:
+        print("----- no relation found ")
+    rel_list_1 = find_argof_pred_relations(amr_graph_1, rel_list_1)
+    if len(rel_list_1) > nb_relation_1:
+        nb_relation_1 = len(rel_list_1)
+        print("----- some relations found ")
+        print("----- Relation list (update): " + str(rel_list_1))
+        print("----- Number of relations in list 1: " + str(nb_relation_1))
+    else:
+        print("----- no relation found ")
+        
+    print("\n-- Finding AMR predicate/argument relations (all-in)")
+    rel_list_2 = find_all_pred_arg_relations(amr_graph_1, rel_list_2)
+    if len(rel_list_2) > nb_relation_2:
+        nb_relation_2 = len(rel_list_2)
+        print("----- some relations found ")
+        print("----- Relation list (update): " + str(rel_list_2))
+        print("----- Number of relations: " + str(nb_relation_2))
+    else:
+        print("----- no relation found ")
+        
+    print("\n-- Update relation list with probbank roles (from propbank frames)")
+    rel_list_3 = update_relation_list_with_propbank_role(rel_list_2)
+    nb_relation_3 = len(rel_list_3)
+    if nb_relation_3 >= nb_relation_2:
+        print("----- All relation update (good!)")
+    else:
+        print("----- Update imperfect")
+    print("----- Relation list (update): " + str(rel_list_3))
+    print("----- Number of relations: " + str(nb_relation_3))
+       
+    print("\n-- Enrich AMR graph with PropBank roles (step-by-step)")
+    amr_graph_1 = substitute_pred_arg_relations(amr_graph_1, rel_list_3)
+    print("----- AMR Graph 1 (update after step 1): \n" + amr_graph_1)
+    amr_graph_1 = substitute_argof_pred_relations(amr_graph_1, rel_list_3)
+    print("----- AMR Graph 1 (update after step 2): \n" + amr_graph_1)
+       
+    print("\n-- Enrich AMR graph with PropBank roles (main function)")
+    amr_graph_2 = enrich_amr_graph_with_propbank_role(amr_graph_2)
+    print("----- AMR Graph 2 (update): \n" + amr_graph_2)
+    
+    print("\n" + "[SSC] Done")
+    
+
+def dev_test_1():
+    dev_analyze('test-amr-graph-1.penman')
+
+
+    
+    
+    
diff --git a/amrbatch/amrld/.gitignore b/amrbatch/amrld/.gitignore
new file mode 100644
index 00000000..ee142b2e
--- /dev/null
+++ b/amrbatch/amrld/.gitignore
@@ -0,0 +1,7 @@
+.project
+.pydevproject
+.history
+.settings
+*.pyc
+out.rdf
+.DS_Store
diff --git a/amrbatch/amrld/LICENSE b/amrbatch/amrld/LICENSE
new file mode 100644
index 00000000..088a6b8c
--- /dev/null
+++ b/amrbatch/amrld/LICENSE
@@ -0,0 +1,204 @@
+                                 Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
+
+   APPENDIX: How to apply the Apache License to your work.
+
+      To apply the Apache License to your work, attach the following
+      boilerplate notice, with the fields enclosed by brackets "{}"
+      replaced with your own identifying information. (Don't include
+      the brackets!)  The text should be enclosed in the appropriate
+      comment syntax for the file format. We also recommend that a
+      file or class name and description of purpose be included on the
+      same "printed page" as the copyright notice for easier
+      identification within third-party archives.
+
+   Copyright {yyyy} {name of copyright owner}
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
+
+
+
diff --git a/amrbatch/amrld/README.md b/amrbatch/amrld/README.md
new file mode 100644
index 00000000..146a5d5f
--- /dev/null
+++ b/amrbatch/amrld/README.md
@@ -0,0 +1,164 @@
+# AMR-LD (AMRs as Linked Data)
+
+## Advantages of AMR-LD
+
+- Sharable in standard W3C format
+
+- Some reasoning for free (using RDF/OWL tools):
+  - amr:ARG0-of owl:inverseOf amr:ARG0
+  - inheritance reasoning:
+  
+  ```
+    If :p rdf:type amr-ne:enzyme .
+       ame-ne:enzyme rdfs:subClassOf amr-ne:protein .
+    Then :p rdf:type amr-ne:protein
+  ```
+
+- Linked to well know identifiers/entities
+
+  ```
+    :e amr:xref up:RASH_HUMAN .
+    :e amr:xref pfam:PF00071 .
+  ```
+
+- Making semantic assertions of precise equivalence using `owl:sameAs` relations
+
+  ```
+    :e owl:sameAs up:RASH_HUMAN .
+  ```
+
+- Query tools for free (SPARQL)
+  - Names of proteins in a AMR repository
+
+  ```
+    select ?n
+    where  { ?p rdf:type amr-ne:protein .
+         ?p amr:name ?no .
+       ?no rdf:type amr-ne:name .
+       ?no :op1 ?n }
+  ```
+
+   - All propbank events (verbs) that have a protein as :ARG1
+
+  ```
+    select ?v
+    where { ?e rdf:type ?v .
+          ?e amr:ARG1 ?p .
+       ?p rdf:type amr-ne:protein .
+       ### we would get all the "amr-ne:enzyme"s if reasoning enabled
+       }
+  ```
+
+   - All propbank events (verbs) that have a protein as :ARG*
+
+  ```
+    select ?v
+    where { ?e rdf:type ?v .
+          ?e ?arg ?p .
+       ?p rdf:type amr-ne:protein .
+       ### we would get all the "amr-ne:enzyme"s if reasoning enabled
+       FILTER regex(?arg, "ARG", "i") }
+       }
+  ```
+## 2. AMR-LD example
+
+The cjconsensus Gold-Standard data set contains the following AMR (from a sentence in the results section of [Innocenti et al. 2002](http://www.ncbi.nlm.nih.gov/pubmed/11777939)):
+
+```
+# ::id pmid_1177_7939.53 ::date 2015-03-07T10:57:15 ::annotator SDL-AMR-09 ::preferred
+# ::snt Sos-1 has been shown to be part of a signaling complex with Grb2, which mediates the activation of Ras upon RTK stimulation.
+# ::save-date Fri Mar 13, 2015 ::file pmid_1177_7939_53.txt
+(s / show-01
+      :ARG1 (h / have-part-91
+            :ARG1 (m / macro-molecular-complex
+                  :ARG0-of (s2 / signal-07)
+                  :part (p2 / protein :name (n2 / name :op1 "Grb2")
+                        :ARG0-of (m2 / mediate-01
+                              :ARG1 (a / activate-01
+                                    :ARG1 (e / enzyme :name (n3 / name :op1 "Ras"))
+                                    :condition (s3 / stimulate-01
+                                          :ARG1 (e2 / enzyme :name (n4 / name :op1 "RTK")))))))
+            :ARG2 (p / protein :name (n / name :op1 "Sos-1"))))
+```
+
+Under our current rubric, this would then be translated to the following RDF TTL code, with a fairly simple one-to-one mapping from AMR elements to RDF elements.  
+
+```
+@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>.
+@prefix xsd: <http://www.w3.org/2001/XMLSchema#>.
+
+@prefix amr: <http://amr.isi.edu#>
+@prefix pb: <https://verbs.colorado.edu/propbank#>
+@prefix ontonotes: <https://catalog.ldc.upenn.edu/LDC2013T19#>
+@prefix amr-ne: <http://amr.isi.edu/entity-types#>
+
+@prefix up: <http://www.uniprot.org/uniprot/>
+@prefix pfam: <http://pfam.xfam.org/family/>
+
+
+### : is the default namespace
+
+:a1 rdf:type amr:AMR .
+:a1 amr:has-sentence "Sos-1 has been shown to be part of a signaling complex with Grb2, which mediates the activation of Ras upon RTK stimulation." .
+:a1 amr:has-id "pmid_1177_7939.53"
+:a1 amr:has-date "2015-03-07T10:57:15
+:a1 amr:has-annotator SDL-AMR-09
+:a1 amr:is-preferred "true"^^xsd:boolean
+:a1 amr:has-file "pmid_1177_7939_53.txt"
+
+:a1 amr:has-root :s .   ### or :a1 amr:has-root :pmid_1177_7939.53__s
+:s rdf:type pb:show-01 .
+:s amr:ARG1 :h .
+:h rdf:type pb:have-part-91 .
+:h amr:ARG1 :m .
+:m rdf:type amr-ne:macro-molecular-complex .
+:m amr:ARG0-of :s2 .
+:s2 rdf:type pb:signal-07 .
+:m amr:part :p2 .
+:p2 rdf:type amr-ne:protein .
+:p2 :name :n2 .
+:n2 rdf:type amr-ne:name .
+:n2 amr:op1 "Grb2" .
+:p2 amr:xref up:P62993 .
+:p2 amr:xref up:GRB2_HUMAN .
+:p2 amr:ARG0-of :m2 .
+:m2 rdf:type pb:mediate-01 .
+:m2 amr:ARG1 :a .
+:a rdf:type pb:activate-01 .
+:a amr:ARG1 :e .
+:e rdf:type amr-ne:enzyme .
+:e :name :n3 .
+:n3 rdf:type amr-ne:name .
+:n3 :op1 "Ras" .
+:e amr:xref up:RASH_HUMAN .     ### we could also do:   :e owl:sameAs up:RASH_HUMAN  
+:e amr:xref pfam:PF00071 .
+:a amr:condition :s3 .
+:s3 rdf:type pb:stimulate-01 .
+:s3 amr:ARG1 :e2 .
+:e2 rdf:type amr-ne:enzyme .
+:e2 amr:name :n4 .
+:n4 rdf:type amr-ne:name .
+:n4 :op1 "RTK" .
+:e2 amr:xref pfam:PF07714
+:h amr:ARG2 :p .
+:p rdf:type amr-ne:protein .
+:p amr:name :n .
+:n rdf:type amr:name .
+:n :op1 "Sos-1" .
+```
+## `amr_to_rdf.py`
+
+This is a simple script that reads the AMR using libraries from the [AMRICA](https://github.com/nsaphra/AMRICA) toolkit and then transposes the graph structure of the AMR into RDF using [rdflib](https://github.com/RDFLib/rdflib). We use simple heuristics to map namespaces and to generate valid RDF for the AMR as needed. 
+
+How to run the script:
+
+```
+$ python amr_to_rdf.py -i <input AMR file> -o <output RDF file> [-f <format>]
+```
+
+How to test the script:
+
+```
+$ python amr_to_rdf.py -i test/bio_ras_0001_1.txt -o out.rdf -f nt
+```
+
diff --git a/amrbatch/amrld/amr-core-patterns.txt b/amrbatch/amrld/amr-core-patterns.txt
new file mode 100644
index 00000000..d09b30b4
--- /dev/null
+++ b/amrbatch/amrld/amr-core-patterns.txt
@@ -0,0 +1,3 @@
+op(\d+)
+(\w+)-quantity 
+([\w\-]+)-entity 
diff --git a/amrbatch/amrld/amr-core.txt b/amrbatch/amrld/amr-core.txt
new file mode 100644
index 00000000..7ea44bc7
--- /dev/null
+++ b/amrbatch/amrld/amr-core.txt
@@ -0,0 +1,52 @@
+accompanier, age
+beneficiary
+compared-to, concession, condition, consist-of
+degree, destination, direction, domain, duration
+example, extent
+frequency
+instrument
+location
+manner, medium, mod, mode
+ord
+part, path, polarity, poss, purpose
+quant
+scale, source, subevent
+time, topic, unit
+value
+wiki
+calendar, century, day, dayperiod, decade, era, month, quarter, season, timezone, weekday, year, year2
+prep-against, prep-along-with, prep-amid, prep-among, prep-as, prep-at
+prep-by
+prep-for, prep-from
+prep-in, prep-in-addition-to, prep-into
+prep-on, prep-on-behalf-of, prep-out-of
+prep-to, prep-toward
+prep-under
+prep-with, prep-without
+conj-as-if
+location-of
+polarity
+degree
+mode 
+amr-unknown
+interrogative
+imperative
+expressive
+and
+or
+either
+neither
+after
+near
+between
+all
+no
+that
+more
+too
+most
+subset, subset-of
+wiki
+product-of, sum-of
+statistical-test
+date-entity, date-interval
\ No newline at end of file
diff --git a/amrbatch/amrld/amr-ne.txt b/amrbatch/amrld/amr-ne.txt
new file mode 100644
index 00000000..578d7046
--- /dev/null
+++ b/amrbatch/amrld/amr-ne.txt
@@ -0,0 +1,20 @@
+thing
+person, family, animal, language, nationality, ethnic-group, regional-group, religious-group
+organization, company, government-organization, military, criminal-organization, political-party
+school, university, research-institute
+team, league
+location, city, city-district, county, state, province, territory, country, local-region, country-region, world-region, continent
+ocean, sea, lake, river, gulf, bay, strait, canal
+peninsula, mountain, volcano, valley, canyon, island, desert, forest
+moon, planet, star, constellation
+facility, airport, station, port, tunnel, bridge, road, railway-line, canal 
+building, theater, museum, palace, hotel, worship-place, sports-facility 
+market, park, zoo, amusement-park
+event, incident, natural-disaster, earthquake, war, conference, game, festival
+product, vehicle, ship, aircraft, aircraft-type, spaceship, car-make
+work-of-art, picture, music, show, broadcast-program
+publication, book, newspaper, magazine, journal
+natural-object
+law, treaty, award, food-dish, music-key
+molecular-physical-entity, small-molecule, protein, protein-family, protein-segment, amino-acid, macro-molecular-complex, enzyme, rna
+pathway, gene, dna-sequence, cell, cell-line, organism, disease
\ No newline at end of file
diff --git a/amrbatch/amrld/amr_rdf2dot.py b/amrbatch/amrld/amr_rdf2dot.py
new file mode 100644
index 00000000..97eec8b6
--- /dev/null
+++ b/amrbatch/amrld/amr_rdf2dot.py
@@ -0,0 +1,135 @@
+"""
+A commandline tool for drawing RDF graphs in Graphviz DOT format
+
+You can draw the graph of an RDF file directly:
+
+.. code-block: bash
+
+   rdf2dot my_rdf_file.rdf | dot -Tpng | display
+
+"""
+
+import rdflib
+import rdflib.extras.cmdlineutils
+from rdflib.namespace import Namespace, NamespaceManager
+
+import sys
+import cgi
+import collections
+
+from rdflib import XSD
+
+LABEL_PROPERTIES = [rdflib.RDFS.label,
+                    rdflib.URIRef("http://purl.org/dc/elements/1.1/title"),
+                    rdflib.URIRef("http://xmlns.com/foaf/0.1/name"),
+                    rdflib.URIRef("http://www.w3.org/2006/vcard/ns#fn"),
+                    rdflib.URIRef("http://www.w3.org/2006/vcard/ns#org")
+                    ]
+
+XSDTERMS = [
+    XSD[x] for x in (
+        "anyURI", "base64Binary", "boolean", "byte", "date",
+        "dateTime", "decimal", "double", "duration", "float", "gDay", "gMonth",
+        "gMonthDay", "gYear", "gYearMonth", "hexBinary", "ID", "IDREF",
+        "IDREFS", "int", "integer", "language", "long", "Name", "NCName",
+        "negativeInteger", "NMTOKEN", "NMTOKENS", "nonNegativeInteger",
+        "nonPositiveInteger", "normalizedString", "positiveInteger", "QName",
+        "short", "string", "time", "token", "unsignedByte", "unsignedInt",
+        "unsignedLong", "unsignedShort")]
+
+EDGECOLOR = "blue"
+NODECOLOR = "black"
+ISACOLOR = "black"
+
+
+def rdf2dot(g, stream, opts={}):
+    """
+    Convert the RDF graph to DOT
+    writes the dot output to the stream
+    """
+
+    fields = collections.defaultdict(set)
+    nodes = {}
+    
+    def node(x):
+
+        if x not in nodes:
+            nodes[x] = "node%d" % len(nodes)
+        return nodes[x]
+
+    def label(x, g):
+
+        for labelProp in LABEL_PROPERTIES:
+            l = g.value(x, labelProp)
+            if l:
+                return l
+
+        try:
+            return g.namespace_manager.compute_qname(x)[2]
+        except:
+            return x
+
+    def formatliteral(l, g):
+        v = cgi.escape(l)
+        if l.datatype:
+            return u'&quot;%s&quot;^^%s' % (v, qname(l.datatype, g))
+        elif l.language:
+            return u'&quot;%s&quot;@%s' % (v, l.language)
+        return u'&quot;%s&quot;' % v
+
+    def qname(x, g):
+        try:
+            q = g.compute_qname(x)
+            return q[0] + ":" + q[2]
+        except:
+            return x
+
+    def color(p):
+        return "BLACK"
+
+    stream.write(u"digraph { \n node [ fontname=\"DejaVu Sans\" ] ; \n")
+
+    for s, p, o in g:
+        sn = node(s)
+        if p == rdflib.RDFS.label:
+            continue
+        if isinstance(o, (rdflib.URIRef, rdflib.BNode)):
+            on = node(o)
+            opstr = u"\t%s -> %s [ color=%s, label=< <font point-size='14' " + \
+                    u"color='#6666ff'>%s</font> > ] ;\n"
+            stream.write(opstr % (sn, on, color(p), qname(p, g)))
+        else:
+            fields[sn].add((qname(p, g), formatliteral(o, g)))
+
+    for u, n in nodes.items():
+        stream.write(u"# %s %s\n" % (u, n))
+        f = []
+        #f = [u"<tr><td align='left' width='40px'>%s</td><td align='left'>%s</td></tr>" %
+        #     x for x in sorted(fields[n])]
+        nn = g.compute_qname(u)
+        uu = nn[0] + u":" + nn[2]
+        opstr = u"%s [ shape=none, color=%s label=< <table color='#666666'" + \
+                u" cellborder='0' cellspacing='0' border='1'><tr>" + \
+                u"<td href='%s' bgcolor='#ffffff' colspan='2'>" + \
+                u"<font point-size='14' color='#000000'>%s</font></td>" + \
+                u"</tr>%s</table> > ] \n"
+        stream.write(opstr % (n, NODECOLOR, label(u, g), uu, u"".join(f)))
+
+    stream.write("}\n")
+
+
+def _help():
+    sys.stderr.write("""
+rdf2dot.py [-f <format>] files...
+Read RDF files given on STDOUT, writes a graph of the RDFS schema in DOT
+language to stdout
+-f specifies parser to use, if not given,
+
+""")
+
+
+def main():
+    rdflib.extras.cmdlineutils.main(rdf2dot, _help)
+
+if __name__ == '__main__':
+    main()
\ No newline at end of file
diff --git a/amrbatch/amrld/amr_to_jsonld.py b/amrbatch/amrld/amr_to_jsonld.py
new file mode 100644
index 00000000..72635c06
--- /dev/null
+++ b/amrbatch/amrld/amr_to_jsonld.py
@@ -0,0 +1,160 @@
+#!/usr/bin/env python
+"""
+amr_to_jsonld.py
+
+Note, this is derived from the source code to AMRICA's disagree_btwn_sents.py script by Naomi Saphra (nsaphra@jhu.edu)
+Copyright(c) 2015. All rights reserved.
+
+"""
+
+import argparse
+import argparse_config
+import codecs
+import os
+import re
+import json
+
+from compare_smatch import amr_metadata
+
+cur_sent_id = 0
+  
+def run_main(args):
+  try:
+    import rdflib
+  except ImportError:
+    raise ImportError('requires rdflib')
+
+  infile = codecs.open(args.infile, encoding='utf8')
+  outfile = open(args.outfile, 'w')
+  
+  json_obj = []
+  
+  # namespaces
+  amr_ns = rdflib.Namespace("http://amr.isi.edu/rdf/core-amr#")
+  pb_ns = rdflib.Namespace("https://verbs.colorado.edu/propbank#")
+  ontonotes_ns = rdflib.Namespace("https://catalog.ldc.upenn.edu/LDC2013T19#")
+  amr_ne_ns = rdflib.Namespace("http://amr.isi.edu/entity-types#")
+  up_ns = rdflib.Namespace("http://www.uniprot.org/uniprot/")
+  pfam_ns = rdflib.Namespace("http://pfam.xfam.org/family/")
+  
+  ns_lookup = {}
+  nelist = []
+  nefile = codecs.open("ne.txt", encoding='utf8')
+  for l in nefile:
+    for w in re.split(",\s*", l):
+        nelist.append( w )
+  for ne in nelist:
+      ns_lookup[ne] = amr_ne_ns  
+  
+  amrs_same_sent = []
+  cur_id = ""
+  while True:
+    (amr_line, comments) = amr_metadata.get_amr_line(infile)
+    cur_amr = None
+    if amr_line:
+      cur_amr = amr_metadata.AmrMeta.from_parse(amr_line, comments)
+      if not cur_id:
+        cur_id = cur_amr.metadata['id']
+
+    if cur_amr is None or cur_id != cur_amr.metadata['id']:
+      amr = amrs_same_sent[0]
+
+      (inst, rel1, rel2) = amr.get_triples2()
+
+      # lookup from original amr objects and simple python objects
+      lookup = {}
+      context = {}
+    
+
+      default = "http://amr.isi.edu/amr_data/" + amr.metadata['id'] + "#" 
+      temp_ns = rdflib.Namespace(default)  
+
+      a1 = {}
+      a1["@type"] = amr_ns.AMR.toPython()
+      json_obj.append(a1)
+
+      #:a1 amr:has-sentence "Sos-1 has been shown to be part of a signaling complex with Grb2, which mediates the activation of Ras upon RTK stimulation." .
+      a1['has-sentence'] = amr.metadata['snt']
+
+      #:a1 amr:has-id "pmid_1177_7939.53"
+      a1['@id'] = amr.metadata['id']
+      
+      #:a1 amr:has-date "2015-03-07T10:57:15
+      a1['has-date'] = amr.metadata['date']
+
+      #:a1 amr:has-annotator SDL-AMR-09
+      #:a1 amr:is-preferred "true"^^xsd:boolean
+      #:a1 amr:has-file "pmid_1177_7939_53.txt"
+      
+      amr_root = {}
+      lookup[amr.root] = amr_root 
+      a1['root'] = amr_root
+      context['root'] = amr_ns.root.toPython()
+      context['@base'] = default
+
+      for (p, s, o) in inst:
+        
+        if( ns_lookup.get(o,None) is not None ):
+            context[o] = amr_ne_ns[o].toPython()
+        elif( re.search('\-\d+$', o) is not None ):
+            context[o] = pb_ns[o].toPython()        
+        else: 
+            context[o] = amr_ns[o].toPython()
+            
+        if( lookup.get(s,None) is None ):
+           lookup[s] = {}
+        
+        s_obj = lookup[s]
+        s_obj["@id"] = s
+        s_obj["@type"] = o
+                
+      for (p, s, o) in rel2:
+          
+        if( lookup.get(s,None) is None ):
+           lookup[s] = {}
+
+        if( lookup.get(o,None) is None ):
+           lookup[o] = {}
+
+        s_obj = lookup[s]
+        o_obj = lookup[o]
+
+        if( s != o ):
+            s_obj[p] = o_obj
+        
+      for (p, s, l) in rel1:
+          
+        if( lookup.get(s,None) is None ):
+           lookup[s] = {}
+
+        s_obj = lookup[s]
+        o_obj = lookup[o]
+
+        s_obj[p] = l
+        
+      a1['@context'] = context 
+      
+      amrs_same_sent = []
+      if cur_amr is not None:
+        cur_id = cur_amr.metadata['id']
+      else:
+        break
+
+    amrs_same_sent.append(cur_amr)
+
+  json.dump( json_obj, outfile, indent=2 )
+  outfile.close()
+
+  infile.close()
+  
+ # gold_aligned_fh and gold_aligned_fh.close()
+
+if __name__ == '__main__':
+  parser = argparse.ArgumentParser()
+  parser.add_argument('-i', '--infile', help='amr input file')
+  parser.add_argument('-o', '--outfile', help='RDF output file')
+
+  args = parser.parse_args()
+  
+  run_main(args)
+
diff --git a/amrbatch/amrld/amr_to_rdf.py b/amrbatch/amrld/amr_to_rdf.py
new file mode 100644
index 00000000..0653ed8a
--- /dev/null
+++ b/amrbatch/amrld/amr_to_rdf.py
@@ -0,0 +1,432 @@
+#!/usr/bin/env python
+"""
+amr_to_rdf.py
+
+Note, this is derived from the source code to AMRICA's disagree_btwn_sents.py script by Naomi Saphra (nsaphra@jhu.edu)
+Copyright(c) 2015. All rights reserved.
+
+"""
+
+import argparse
+#import argparse_config
+import codecs
+import os
+import re
+import textwrap
+
+from compare_smatch import amr_metadata
+from rdflib.namespace import RDF
+from rdflib.namespace import RDFS
+from rdflib.plugins import sparql
+#from Carbon.QuickDraw import frame
+from numpy.f2py.auxfuncs import throw_error
+
+cur_sent_id = 0
+    
+def strip_word_alignments(str, patt):    
+    match = patt.match(str)
+    if match:
+        str = match.group(1)
+        
+    return str
+            
+def run_main(args): 
+
+    inPath = args.inPath
+    outPath = args.outPath
+
+    #
+    # If the path is a directory then loop over the directory contents,
+    # Else run the script on the file as described
+    #
+    if( os.path.isfile(inPath) ):
+        run_main_on_file(args)
+    else:
+        if not os.path.exists(outPath):
+            os.makedirs(outPath)
+        for fn in os.listdir(inPath):
+            if os.path.isfile(inPath+"/"+fn) and fn.endswith(".txt"):
+                args.inPath =inPath + "/" + fn
+                args.outPath = outPath + "/" + fn + ".rdf"
+                run_main_on_file(args)
+
+def run_main_on_file(args):
+    
+    try:
+        import rdflib
+    except ImportError:
+        raise ImportError('requires rdflib')
+                
+    infile = codecs.open(args.inPath, encoding='utf8')
+    outfile = open(args.outPath, 'w')
+    
+    pBankRoles = True
+    if( not(args.pbankRoles == u'1') ):
+        pBankRoles = False
+                                
+    xref_namespace_lookup = {}
+    with open('xref_namespaces.txt') as f:
+        xref_lines = f.readlines()
+    for l in xref_lines:
+        line = re.split("\t", l)
+        xref_namespace_lookup[line[0]] = line[1].rstrip('\r\n')
+                                
+    # create the basic RDF data structure
+    g = rdflib.Graph()
+    
+    # namespaces
+    amr_ns = rdflib.Namespace("http://amr.isi.edu/rdf/core-amr#")
+    amr_terms_ns = rdflib.Namespace("http://amr.isi.edu/rdf/amr-terms#")
+    amr_data = rdflib.Namespace("http://amr.isi.edu/amr_data#")
+    pb_ns = rdflib.Namespace("http://amr.isi.edu/frames/ld/v1.2.2/")
+    amr_ne_ns = rdflib.Namespace("http://amr.isi.edu/entity-types#")
+
+    up_ns = rdflib.Namespace("http://www.uniprot.org/uniprot/")
+    pfam_ns = rdflib.Namespace("http://pfam.xfam.org/family/")
+    ontonotes_ns = rdflib.Namespace("https://catalog.ldc.upenn.edu/LDC2013T19#")
+
+    g.namespace_manager.bind('propbank', pb_ns, replace=True)
+    g.namespace_manager.bind('amr-core', amr_ns, replace=True)
+    g.namespace_manager.bind('amr-terms', amr_terms_ns, replace=True)
+    g.namespace_manager.bind('entity-types', amr_ne_ns, replace=True)    
+    g.namespace_manager.bind('amr-data', amr_data, replace=True)    
+    
+    for k in xref_namespace_lookup.keys():
+        temp_ns = rdflib.Namespace(xref_namespace_lookup[k])
+        g.namespace_manager.bind(k, temp_ns, replace=True)    
+        xref_namespace_lookup[k] = temp_ns
+    
+    # Basic AMR Ontology consisting of 
+    #   1. concepts
+    #   2. roles 
+    #   3. strings (which are actually going to be Literal(string)s
+    conceptClass = amr_ns.Concept
+    neClass = amr_ns.NamedEntity
+    frameClass = amr_ns.Frame
+    roleClass = amr_ns.Role
+    frameRoleClass = pb_ns.FrameRole
+    
+    g.add( (conceptClass, rdflib.RDF.type, rdflib.RDFS.Class) )
+    g.add( (conceptClass, RDFS.label, rdflib.Literal("AMR-Concept") ) )
+    #g.add( (conceptClass, RDFS.comment, rdflib.Literal("Class of all concepts expressed in AMRs") ) )
+
+    g.add( (neClass, rdflib.RDF.type, conceptClass) )
+    g.add( (neClass, RDFS.label, rdflib.Literal("AMR-EntityType") ) )
+    #g.add( (neClass, RDFS.comment, rdflib.Literal("Class of all named entities expressed in AMRs") ) )
+
+    g.add( (neClass, rdflib.RDF.type, conceptClass) )
+    g.add( (neClass, RDFS.label, rdflib.Literal("AMR-Term") ) )
+    #g.add( (neClass, RDFS.comment, rdflib.Literal("Class of all named entities expressed in AMRs") ) )
+
+    g.add( (roleClass, rdflib.RDF.type, rdflib.RDFS.Class) )
+    g.add( (roleClass, RDFS.label, rdflib.Literal("AMR-Role") ) )
+    #g.add( (roleClass, RDFS.comment, rdflib.Literal("Class of all roles expressed in AMRs") ) )
+
+    g.add( (frameRoleClass, rdflib.RDF.type, roleClass) )
+    g.add( (frameRoleClass, RDFS.label, rdflib.Literal("AMR-PropBank-Role") ) )
+    #g.add( (frameRoleClass, RDFS.comment, rdflib.Literal("Class of all roles of PropBank frames") ) )
+
+    g.add( (frameClass, rdflib.RDF.type, conceptClass) )
+    g.add( (frameClass, RDFS.label, rdflib.Literal("AMR-PropBank-Frame") ) )
+    #g.add( (frameClass, RDFS.comment, rdflib.Literal("Class of all frames expressed in AMRs") ) )
+    
+    amr_count = 0
+    ns_lookup = {}
+    class_lookup = {}
+    nelist = []
+    corelist = []
+    pattlist = []
+    pmid_patt = re.compile('.*pmid_(\d+)_(\d+).*')
+    word_align_patt = re.compile('(.*)\~e\.(.+)')
+    propbank_patt = re.compile('^(.*)\-\d+$')
+    opN_patt = re.compile('op(\d+)')
+    arg_patt = re.compile('ARG\d+')
+
+    with open('amr-ne.txt') as f:
+        ne_lines = f.readlines()
+    for l in ne_lines:
+        for w in re.split(",\s*", l):
+            w = w.rstrip('\r\n')
+            nelist.append( w )
+    for ne in nelist:
+            ns_lookup[ne] = amr_ne_ns
+            class_lookup[ne] = neClass
+
+    with open('amr-core.txt') as f:
+        core_lines = f.readlines()
+    for l in core_lines:
+        for w in re.split(",\s*", l):
+            w = w.rstrip('\r\n')
+            corelist.append( w )
+    for c in corelist:
+            ns_lookup[c] = amr_ns    
+            class_lookup[c] = conceptClass
+            
+    pattfile = codecs.open("amr-core-patterns.txt", encoding='utf8')
+    for l in pattfile:
+        pattlist.append( w )
+    
+    amrs_same_sent = []
+    
+    cur_id = ""
+    while True:
+        (amr_line, comments) = amr_metadata.get_amr_line(infile)
+        cur_amr = None
+
+        vb_lookup = {}
+        label_lookup_table = {}
+        xref_variables = {}
+    
+        if amr_line:
+            cur_amr = amr_metadata.AmrMeta.from_parse(amr_line, comments)
+            if not cur_id:
+                cur_id = cur_amr.metadata['id']
+
+        if cur_amr is None or cur_id != cur_amr.metadata['id']:
+            amr = amrs_same_sent[0]
+
+            (inst, rel1, rel2) = amr.get_triples2()
+        
+            temp_ns = rdflib.Namespace("http://amr.isi.edu/amr_data/" + amr.metadata['id'] + "#")    
+            a1 = temp_ns.root01 # reserve term root01 
+            
+            # :a1 rdf:type amr:AMR .
+            g.add( (a1, 
+                    rdflib.RDF.type, 
+                    amr_ns.AMR) )
+
+            #:a1 amr:has-id "pmid_1177_7939.53"
+            amr_id = amr.metadata['id']
+            g.add( (a1, 
+                    amr_ns['has-id'], 
+                    rdflib.Literal(amr_id)))
+            
+            match = pmid_patt.match(amr_id)
+            if match:
+                    pmid = match.group(1) + match.group(2)
+                    g.add( (a1, 
+                            amr_ns['has-pmid'], 
+                            rdflib.Literal(pmid)))
+
+            #:a1 amr:has-sentence "Sos-1 has been shown to be part of a signaling complex with Grb2, which mediates the activation of Ras upon RTK stimulation." .
+            if( amr.metadata.get('snt', None) is not None):
+                    g.add( (a1, 
+                            amr_ns['has-sentence'], 
+                            rdflib.Literal(amr.metadata['snt']) )
+                          )
+
+            #:a1 amr:has-date "2015-03-07T10:57:15
+            if( amr.metadata.get('date', None) is not None):
+                    g.add( (a1, 
+                            amr_ns['has-date'], 
+                            rdflib.Literal(amr.metadata['date'])))
+
+            #:a1 amr:amr-annotator SDL-AMR-09
+            if( amr.metadata.get('amr-annotator', None) is not None):
+                    g.add( (a1,
+                            amr_ns['has-annotator'], 
+                            rdflib.Literal(amr.metadata['amr-annotator'])))
+                    
+            #:a1 amr:tok 
+            if( amr.metadata.get('tok', None) is not None):
+                    g.add( (a1, 
+                            amr_ns['has-tokens'], 
+                            rdflib.Literal(amr.metadata['tok'])))
+
+            #:a1 amr:alignments
+            if( amr.metadata.get('alignments', None) is not None):
+                    g.add( (a1, 
+                            amr_ns['has-alignments'], 
+                            rdflib.Literal(amr.metadata['alignments'])))
+            
+            g.add( (a1, amr_ns.root, temp_ns[amr.root]) )
+
+            # Add triples for setting types pointing to other resources
+            frames = {}
+            for (p, s, o) in inst:
+                    
+                o = strip_word_alignments(o,word_align_patt)
+                #if word_pos is not None:
+                #        g.add( (temp_ns[s], 
+                #                        amr_ns['has-word-pos'], 
+                #                        rdflib.Literal(word_pos)) )            
+                  
+                if( ns_lookup.get(o,None) is not None ):
+                    resolved_ns = ns_lookup.get(o,None)
+                    o_resolved = resolved_ns[o]
+                    if( class_lookup.get(o,None) is not None): 
+                        g.add( (o_resolved, rdflib.RDF.type, class_lookup.get(o,None)) )
+                    else:
+                        raise ValueError(o_resolved + ' does not have a class assigned.')
+                elif( re.search('\-\d+$', o) is not None ):
+                    #match = propbank_patt.match(o)
+                    #str = ""
+                    #if match:
+                    #    str = match.group(1)
+                    #o_resolved = pb_ns[str + ".html#" +o ]
+                    o_resolved = pb_ns[ o ]
+                    g.add( (o_resolved, rdflib.RDF.type, frameClass) ) 
+                elif( o == 'xref' and args.fixXref): 
+                    continue
+                elif( not(o == 'name') ): # ignore 'name' objects but add all others.
+                    o_resolved = amr_terms_ns[o]
+                    g.add( (o_resolved, rdflib.RDF.type, conceptClass) )
+                # identify xref variables in AMR, don't retain it as a part of the graph.
+                else: 
+                    continue
+                 
+                frames[s] = o
+                g.add( (temp_ns[s], RDF.type, o_resolved) )
+
+            # Add object properties for local links in the current AMR
+            for (p, s, o) in rel2:
+                
+                if( p == "TOP" ):
+                    continue
+                 
+                # Do not include word positions for predicates 
+                # (since they are more general and do not need to linked to everything).     
+                p = strip_word_alignments(p,word_align_patt)                
+                o = strip_word_alignments(o,word_align_patt)
+                                
+                # remember which objects have name objects 
+                if( p == 'name' ):
+                    label_lookup_table[o] = s 
+                    
+                # objects with value objects should also be in  
+                elif( p == 'xref' and args.fixXref):
+                    xref_variables[o] = s   
+               
+                elif( re.search('^ARG\d+$', p) is not None ):
+
+                    frameRole = frames[s] + "." + p
+                    if( not(pBankRoles) ): 
+                        frameRole = p
+
+                    g.add( (pb_ns[frameRole], rdflib.RDF.type, frameRoleClass) )
+                    g.add( (temp_ns[s], pb_ns[frameRole], temp_ns[o] ) )                    
+                    vb_lookup[s] = temp_ns[s]
+                    vb_lookup[frameRole] = pb_ns[frameRole]
+                    vb_lookup[o] = temp_ns[o]
+
+                elif( re.search('^ARG\d+\-of$', p) is not None ):
+                    
+                    frameRole = frames[o] + "." + p
+                    if( not(pBankRoles) ): 
+                        frameRole = p
+                        
+                    g.add( (pb_ns[frameRole], rdflib.RDF.type, frameRoleClass) )
+                    g.add( (temp_ns[s], pb_ns[frameRole], temp_ns[o] ) )        
+                    vb_lookup[s] = temp_ns[s]
+                    vb_lookup[frameRole] = pb_ns[frameRole]
+                    vb_lookup[o] = temp_ns[o]
+                
+                else:
+                
+                    g.add( (amr_terms_ns[p], rdflib.RDF.type, roleClass) )
+                    g.add( (temp_ns[s], amr_terms_ns[p], temp_ns[o]) )
+                    vb_lookup[s] = temp_ns[s]
+                    vb_lookup[p] = amr_terms_ns[p]
+                    vb_lookup[o] = temp_ns[o]
+    
+
+            # Add data properties in the current AMR
+            labels = {}
+            for (p, s, l) in rel1:
+
+                p = strip_word_alignments(p, word_align_patt)
+                l = strip_word_alignments(l, word_align_patt)
+                
+                #
+                # Build labels across multiple 'op1, op2, ... opN' links, 
+                #
+                opN_match = re.match(opN_patt, p)
+                if( opN_match is not None and
+                        label_lookup_table.get(s,None) is not None):
+                    opN = int(opN_match.group(1))
+                    ss = label_lookup_table[s]
+                    if( labels.get(ss, None) is None ):
+                        labels[ss] = []
+                    
+                    labels[ss].append( (opN, l) )
+
+                elif( xref_variables.get(s,None) is not None 
+                      and p == 'value'
+                      and args.fixXref):
+                    for k in xref_namespace_lookup.keys():
+                        if( l.startswith(k) ):
+                            l2 = l[-len(l)+len(k):]
+                            xref_vb = xref_variables.get(s,None)
+                            resolved_xref_vb = vb_lookup.get(xref_vb,None)
+                            g.add( (resolved_xref_vb, 
+                                    amr_ns['xref'], 
+                                    xref_namespace_lookup[k][l2]) )
+                            
+                # Special treatment for propbank roles.                 
+                elif( re.search('ARG\d+$', p) is not None ):
+                    
+                    frameRole = frames[s] + "." + p
+                    if( not(pBankRoles) ): 
+                        frameRole = p
+                    
+                    g.add( (pb_ns[frameRole], rdflib.RDF.type, frameRoleClass) )
+                    g.add( (temp_ns[s], pb_ns[frameRole], rdflib.Literal(l) ) )                    
+                
+                # Otherwise, it's just a literal 
+                else:
+                    g.add( (temp_ns[s], amr_terms_ns[p], rdflib.Literal(l) ) )
+            
+            # Add labels here
+            # ["\n".join([i.split(' ')[j] for j in range(5)]) for i in g.vs["id"]]
+            for key in labels.keys():
+                labelArray = [i[1] for i in sorted(labels[key])];
+                
+                label = " ".join( labelArray )
+                g.add( (temp_ns[key], 
+                        RDFS.label, 
+                        rdflib.Literal(label) ) )
+            
+            amrs_same_sent = []
+            if cur_amr is not None:
+                cur_id = cur_amr.metadata['id']
+            else:
+                break
+
+        amrs_same_sent.append(cur_amr)
+        amr_count = amr_count+1
+
+    # Additional processing to clean up. 
+    # 1. Add labels to AMR objects
+    #q = sparql.prepareQuery("select distinct ?s ?label " +
+    #                                                "where { " +
+    #                                                "?s <http://amr.isi.edu/rdf/core-amr#name> ?n . " +
+    #                                                "?n <http://amr.isi.edu/rdf/core-amr#op1> ?label " +
+    #                                                "}")
+    #qres = g.query(q)
+
+    #for row in qres:
+    #    print("%s type %s" % row)
+    print ("%d AMRs converted" % amr_count)
+    outfile.write( g.serialize(format=args.format) )
+    outfile.close()
+
+    infile.close()
+    
+ # gold_aligned_fh and gold_aligned_fh.close()
+
+if __name__ == '__main__':
+    parser = argparse.ArgumentParser()
+    
+    parser.add_argument('-i', '--inPath', help='AMR input file or directory')
+    parser.add_argument('-o', '--outPath', help='RDF output file or directory')
+
+    parser.add_argument('-pbr', '--pbankRoles', default='1', help='Do we include PropBank Roles?')
+    parser.add_argument('-kx', '--fixXref', default='1', help='Keep existing Xref formalism?')
+    parser.add_argument('-v', '--verbose', action='store_true')
+    parser.add_argument('-f', '--format', nargs='?', default='nt',
+                        help="RDF Format: xml, n3, nt, trix, rdfa")
+
+    args = parser.parse_args()
+    
+    run_main(args)
+
diff --git a/amrbatch/amrld/compare_smatch/__init__.py b/amrbatch/amrld/compare_smatch/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/amrbatch/amrld/compare_smatch/amr_alignment.py b/amrbatch/amrld/compare_smatch/amr_alignment.py
new file mode 100644
index 00000000..893c2bf0
--- /dev/null
+++ b/amrbatch/amrld/compare_smatch/amr_alignment.py
@@ -0,0 +1,252 @@
+"""
+amr_alignment.py
+
+Author: Naomi Saphra (nsaphra@jhu.edu)
+Copyright(c) 2014
+
+Builds a weighted mapping of tokens between parallel sentences for use in
+weighted cross-language Smatch alignment.
+Takes in an output file from GIZA++ (specified in construction functions).
+"""
+
+from collections import defaultdict
+from pynlpl.formats.giza import GizaSentenceAlignment
+import re
+
+class Amr2AmrAligner(object):
+  def __init__(self, num_best=5, num_best_in_file=-1, src2tgt_fh=None, tgt2src_fh=None):
+    if src2tgt_fh == None or tgt2src_fh == None:
+      self.is_default = True
+      self.node_weight_fn = self.dflt_node_weight_fn
+      self.edge_weight_fn = self.dflt_edge_weight_fn
+    else:
+      self.is_default = False
+      self.node_weight_fn = None
+      self.edge_weight_fn = self.xlang_edge_weight_fn
+    self.src2tgt_fh = src2tgt_fh
+    self.tgt2src_fh = tgt2src_fh
+    self.amr2amr = {}
+    self.num_best = num_best
+    self.num_best_in_file = num_best_in_file
+    self.last_nbest_line = {self.src2tgt_fh:None, self.tgt2src_fh:None}
+    if num_best_in_file < 0:
+      self.num_best_in_file = num_best
+    assert self.num_best_in_file >= self.num_best
+
+  def set_amrs(self, tgt_amr, src_amr):
+    if self.is_default:
+      return
+
+    self.tgt_toks = tgt_amr.metadata['tok'].strip().split()
+    self.src_toks = src_amr.metadata['tok'].strip().split()
+
+    sent2sent_union = align_sent2sent_union(self.tgt_toks, self.src_toks,
+      self.get_nbest_alignments(self.src2tgt_fh), self.get_nbest_alignments(self.tgt2src_fh))
+
+    if 'alignments' in tgt_amr.metadata:
+      amr2sent_tgt = align_amr2sent_jamr(tgt_amr, self.tgt_toks, tgt_amr.metadata['alignments'].strip().split())
+    else:
+      amr2sent_tgt = align_amr2sent_dflt(tgt_amr, self.tgt_toks)
+    if 'alignments' in src_amr.metadata:
+      amr2sent_src = align_amr2sent_jamr(src_amr, self.src_toks, src_amr.metadata['alignments'].strip().split())
+    else:
+      amr2sent_src = align_amr2sent_dflt(src_amr, self.src_toks)
+
+    self.amr2amr = defaultdict(float)
+    for (tgt_lbl, tgt_scores) in amr2sent_tgt.items():
+      for (src_lbl, src_scores) in amr2sent_src.items():
+        if src_lbl.lower() == tgt_lbl.lower():
+          self.amr2amr[(tgt_lbl, src_lbl)] += 1.0
+          continue
+        for (t, t_score) in enumerate(tgt_scores):
+          for (s, s_score) in enumerate(src_scores):
+            score = t_score * s_score * sent2sent_union[t][s]
+            if score > 0:
+              self.amr2amr[(tgt_lbl, src_lbl)] += score
+
+    self.node_weight_fn = lambda t,s : self.amr2amr[(t, s)]
+
+  def const_map_fn(self, const):
+    """ Get all const strings from source amr that could map to target const """
+    const_matches = [const]
+    for (t,s) in filter(lambda (t,s): t == const, self.amr2amr):
+      if self.node_weight_fn(t,s) > 0: # weight > 0
+        const_matches.append(s)
+    return sorted(const_matches, key=lambda x: self.node_weight_fn(const, x), reverse=True)
+
+  @staticmethod
+  def dflt_node_weight_fn(tgt_label, src_label):
+    return 1.0 if tgt_label.lower() == src_label.lower() else 0.0
+
+  @staticmethod
+  def dflt_edge_weight_fn(tgt_label, src_label):
+    return 1.0 if tgt_label.lower() == src_label.lower() else 0.0
+
+  def xlang_edge_weight_fn(self, tgt_label, src_label):
+    tgt = tgt_label.lower()
+    src = src_label.lower()
+    if tgt == src:
+      # operand edges are all equivalent
+      #TODO make this an RE instead?
+      return 1.0
+    if tgt.startswith("op") and src.startswith("op"):
+      return 0.9 # frumious hack to favor similar op edges
+    return 0.0
+
+  def get_nbest_alignments(self, fh):
+    """ Read an entry from the giza alignment .A3 NBEST file. """
+    aligns = []
+    curr_sent = -1
+    start_ind = 0
+    if self.last_nbest_line[fh]:
+      if self.num_best > 0:
+        aligns.append(self.last_nbest_line[fh])
+      start_ind = 1
+      curr_sent = self.last_nbest_line[fh][0].index
+      self.last_nbest_line[fh] = None
+
+    for ind in range(start_ind, self.num_best_in_file):
+      meta_line = fh.readline()
+      if meta_line == "":
+        if len(aligns) == 0:
+          return None
+        else:
+          break
+
+      meta = re.match("# Sentence pair \((\d+)\) "+
+        "source length (\d+) target length (\d+) "+
+        "alignment score : (.+)", meta_line)
+      if not meta:
+        raise Exception
+      sent = int(meta.group(1))
+      if curr_sent < 0:
+        curr_sent = sent
+      score = float(meta.group(4))
+
+      tgt_line = fh.readline()
+      src_line = fh.readline()
+      if sent != curr_sent:
+        self.last_nbest_line[fh] = (GizaSentenceAlignment(src_line, tgt_line, sent), score)
+        break
+      if ind < self.num_best:
+        aligns.append((GizaSentenceAlignment(src_line, tgt_line, sent), score))
+    return aligns
+
+default_aligner = Amr2AmrAligner()
+
+def get_all_labels(amr):
+  ret = [v for v in amr.var_values]
+  for l in amr.const_links:
+    ret += [v for (k,v) in l.items()]
+  return ret
+
+def align_amr2sent_dflt(amr, sent):
+  labels = get_all_labels(amr)
+  align = {l:[0.0 for tok in sent] for l in labels}
+  for label in labels:
+    lbl = label.lower()
+    # checking for multiwords / bad segmentation
+    # ('_' replaces ' ' in multiword quotes)
+    # TODO just fix AMR format parser to deal with spaces in quotes
+    possible_toks = lbl.split('_')
+    possible_toks.append(lbl)
+
+    matches = [t_ind for (t_ind, t) in enumerate(sent) if t.lower() in possible_toks]
+    for t_ind in matches:
+      align[label][t_ind] = 1.0 / len(matches)
+  return align
+
+def parse_jamr_alignment(chunk):
+  (tok_range, nodes_str) = chunk.split('|')
+  (start_tok, end_tok) = tok_range.split('-')
+  node_list = nodes_str.split('+')
+  return (int(start_tok), int(end_tok), node_list)
+
+def align_label2toks_en(label, sent, weights, toks_to_align):
+  """
+  label: node label to map
+  sent: token list to map label to
+  weights: list to be modified with new weights
+  default_full: set True to have the default distribution sum to 1 instead of 0
+  return list mapping token index to match weight
+  """
+  # TODO frumious hack. should set up actual stemmer sometime.
+
+  lbl = label.lower()
+  stem = lbl
+  wordnet = re.match("(.+)-\d\d", lbl)
+  if wordnet:
+    stem = wordnet.group(1)
+  if len(stem) > 4: # arbitrary
+    if len(stem) > 5:
+      stem = stem[:-2]
+    else:
+      stem = stem[:-1]
+
+  def is_match(tok):
+    return tok == lbl or \
+      (len(tok) >= len(stem) and tok[:len(stem)] == stem)
+
+  matches = [t_ind for t_ind in toks_to_align if is_match(sent[t_ind].lower())]
+  if len(matches) == 0:
+    matches = toks_to_align
+  for t_ind in matches:
+    weights[t_ind] += 1.0 / len(matches)
+  return weights
+
+def align_amr2sent_jamr(amr, sent, jamr_line):
+  """
+  amr: an amr to map nodes to sentence toks
+  sent: sentence array of toks
+  jamr_line: metadata field 'alignments', aligned with jamr
+  return dict mapping amr node labels to match weights for each tok in sent
+  """
+  labels = get_all_labels(amr)
+  labels_remain = {label:labels.count(label) for label in labels}
+  tokens_remain = set(range(len(sent)))
+  align = {l:[0.0 for tok in sent] for l in labels}
+
+  for chunk in jamr_line:
+    (start_tok, end_tok, node_list) = parse_jamr_alignment(chunk)
+    for node_path in node_list:
+      label = amr.path2label[node_path]
+      toks_to_align = range(start_tok, end_tok)
+      align[label] = align_label2toks_en(label, sent, align[label], toks_to_align)
+      labels_remain[label] -= 1
+      for t in toks_to_align:
+        tokens_remain.discard(t)
+
+  #TODO should really switch from a label-token-label alignment model to node-token-node
+  for label in labels_remain:
+    if labels_remain[label] > 0:
+      align[label] = align_label2toks_en(label, sent, align[label], tokens_remain)
+  for label in align:
+    z = sum(align[label])
+    if z == 0:
+      continue
+    align[label] = [w/z for w in align[label]]
+  return align
+
+def align_sent2sent(tgt_toks, src_toks, alignment_scores):
+  z = sum([s for (a,s) in alignment_scores])
+  tok_align = [[0.0 for s in src_toks] for t in tgt_toks]
+  for (align, score) in alignment_scores:
+    for srcind, tgtind in align.alignment:
+      if tgtind >= 0 and srcind >= 0:
+        tok_align[tgtind][srcind] += score
+
+  for targetind, targettok in enumerate(tgt_toks):
+    for sourceind, sourcetok in enumerate(src_toks):
+      tok_align[targetind][sourceind] /= z
+  return tok_align
+
+def align_sent2sent_union(tgt_toks, src_toks, src2tgt, tgt2src):
+  src2tgt_align = align_sent2sent(tgt_toks, src_toks, src2tgt)
+  tgt2src_align = align_sent2sent(src_toks, tgt_toks, tgt2src)
+
+  tok_align = [[0.0 for s in src_toks] for t in tgt_toks]
+  for tgtind, tgttok in enumerate(tgt_toks):
+    for srcind, srctok in enumerate(src_toks):
+      tok_align[tgtind][srcind] = \
+        (src2tgt_align[tgtind][srcind] + tgt2src_align[srcind][tgtind]) / 2.0
+  return tok_align
diff --git a/amrbatch/amrld/compare_smatch/amr_metadata.py b/amrbatch/amrld/compare_smatch/amr_metadata.py
new file mode 100644
index 00000000..85d13e1d
--- /dev/null
+++ b/amrbatch/amrld/compare_smatch/amr_metadata.py
@@ -0,0 +1,62 @@
+#!/usr/bin/env python
+"""
+amr_metadata.py
+
+Author: Naomi Saphra (nsaphra@jhu.edu)
+Copyright(c) 2014
+
+Read AMR file in while also processing metadata in comments
+"""
+
+import re
+
+from smatch.amr import AMR
+
+class AmrMeta(AMR):
+  def __init__(self, var_list=None, var_value_list=None,
+               link_list=None, const_link_list=None, path2label=None,
+               base_amr=None, metadata={}):
+    if base_amr is None:
+      super(AmrMeta, self).__init__(var_list, var_value_list, 
+                                    link_list, const_link_list, path2label)
+    else:
+      self.nodes = base_amr.nodes
+      self.root = base_amr.root
+      self.var_values = base_amr.var_values
+      self.links = base_amr.links
+      self.const_links = base_amr.const_links
+      self.path2label = base_amr.path2label
+
+    self.metadata = metadata
+
+  @classmethod
+  def from_parse(cls, annotation_line, comment_lines, xlang=False):
+    metadata = {}
+    for l in comment_lines:
+      matches = re.findall(r'::(\S+)\s(([^:]|:(?!:))+)', l)
+      for m in matches:
+        metadata[m[0]] = m[1].strip()
+
+    base_amr = AMR.parse_AMR_line(annotation_line, xlang=xlang)
+    return cls(base_amr=base_amr, metadata=metadata)
+
+
+def get_amr_line(infile):
+  """ Read an entry from the input file. AMRs are separated by blank lines. """
+  cur_comments = []
+  cur_amr = []
+  has_content = False
+  for line in infile:
+    if line[0] == "(" and len(cur_amr) != 0:
+      cur_amr = []
+    if line.strip() == "":
+      if not has_content:
+        continue
+      else:
+        break
+    elif line.strip().startswith("#"):
+      cur_comments.append(line.strip())
+    else:
+      has_content = True
+      cur_amr.append(line.strip())
+  return ("".join(cur_amr), cur_comments)
diff --git a/amrbatch/amrld/compare_smatch/smatch_graph.py b/amrbatch/amrld/compare_smatch/smatch_graph.py
new file mode 100644
index 00000000..35ac66d6
--- /dev/null
+++ b/amrbatch/amrld/compare_smatch/smatch_graph.py
@@ -0,0 +1,210 @@
+#!/usr/bin/env python
+"""
+smatch_graph.py
+
+Author: Naomi Saphra (nsaphra@jhu.edu)
+Copyright(c) 2014
+
+Describes a class for building graphs of AMRs with disagreements hilighted.
+"""
+
+import copy
+import networkx as nx
+import pygraphviz as pgz
+from pynlpl.formats.giza import GizaSentenceAlignment
+
+from amr_alignment import Amr2AmrAligner
+from amr_alignment import default_aligner
+import amr_metadata
+from smatch import smatch
+
+GOLD_COLOR = 'blue'
+TEST_COLOR = 'red'
+DFLT_COLOR = 'black'
+
+class SmatchGraph:
+  def __init__(self, inst, rel1, rel2, \
+    gold_inst_t, gold_rel1_t, gold_rel2_t, \
+    match, const_map_fn=default_aligner.const_map_fn):
+    """
+    TODO correct these params
+    Input:
+      (inst, rel1, rel2) from test amr.get_triples2()
+      (gold_inst_t, gold_rel1_t, gold_rel2_t) from gold amr2dict()
+      match from smatch
+      const_map_fn returns a sorted list of gold label matches for a test label
+    """
+    (self.inst, self.rel1, self.rel2) = (inst, rel1, rel2)
+    (self.gold_inst_t, self.gold_rel1_t, self.gold_rel2_t) = \
+      (gold_inst_t, gold_rel1_t, gold_rel2_t)
+    self.match = match # test var index -> gold var index
+    self.map_fn = const_map_fn
+
+    (self.unmatched_inst, self.unmatched_rel1, self.unmatched_rel2) = \
+      [copy.deepcopy(x) for x in (self.gold_inst_t, self.gold_rel1_t, self.gold_rel2_t)]
+    self.gold_ind = {} # test variable hash -> gold variable index
+    self.G = nx.MultiDiGraph()
+
+  def smatch2graph(self, node_weight_fn=None, edge_weight_fn=None):
+    """
+    Returns graph of test AMR / gold AMR union, with hilighted disagreements for
+    different labels on edges and nodes, unmatched nodes and edges.
+    """
+
+    for (ind, (i, v, instof)) in enumerate(self.inst):
+      self.add_inst(ind, v, instof)
+
+    for (reln, v, const) in self.rel1:
+      self.add_rel1(reln, v, const)
+
+    for (reln, v1, v2) in self.rel2:
+      self.add_rel2(reln, v1, v2)
+
+    if node_weight_fn and edge_weight_fn:
+      self.unmatch_dead_nodes(node_weight_fn, edge_weight_fn)
+
+    # Add gold standard elements not in test
+    test_ind = {v:k for (k,v) in self.gold_ind.items()} # reverse lookup from gold ind
+
+    for (ind, instof) in self.unmatched_inst.items():
+      test_ind[ind] = u'GOLD %s' % ind
+      self.add_node(test_ind[ind], '', instof, test_ind=-1, gold_ind=ind)
+
+    for ((ind, const), relns) in self.unmatched_rel1.items():
+      for reln in relns:
+        const_hash = test_ind[ind] + ' ' + const
+        if const_hash not in test_ind:
+          test_ind[const_hash] = const_hash
+          self.add_node(const_hash, '', const)
+        self.add_edge(test_ind[ind], test_ind[const_hash], '', reln)
+
+    for ((ind1, ind2), relns) in self.unmatched_rel2.items():
+      for reln in relns:
+        self.add_edge(test_ind[ind1], test_ind[ind2], '', reln)
+
+    return self.G
+
+  def get_text_alignments(self):
+    """ Return an array of variable ID mappings, including labels, that are human-readable.
+        Call only after smatch2graph(). """
+    align = []
+    for (v, attr) in self.G.nodes(data=True):
+      if attr['test_ind'] < 0 and attr['gold_ind'] < 0:
+        continue
+      align.append("%s\t%s\t-\t%s\t%s" % (attr['test_ind'], attr['test_label'], attr['gold_ind'], attr['gold_label']))
+    return align
+
+  def add_edge(self, v1, v2, test_lbl, gold_lbl):
+    assert(gold_lbl == '' or test_lbl == '' or gold_lbl == test_lbl)
+    if gold_lbl == '':
+      self.G.add_edge(v1, v2, label=test_lbl, test_label=test_lbl, gold_label=gold_lbl, color=TEST_COLOR)
+    elif test_lbl == '':
+      self.G.add_edge(v1, v2, label=gold_lbl, test_label=test_lbl, gold_label=gold_lbl, color=GOLD_COLOR)
+    elif test_lbl == gold_lbl:
+      self.G.add_edge(v1, v2, label=test_lbl, test_label=test_lbl, gold_label=gold_lbl, color=DFLT_COLOR)
+
+  def add_node(self, v, test_lbl, gold_lbl, test_ind=-1, gold_ind=-1):
+    assert(gold_lbl or test_lbl)
+    if gold_lbl == '':
+      self.G.add_node(v, label=u'%s / *' % test_lbl, test_label=test_lbl, gold_label=gold_lbl, \
+        test_ind=test_ind, gold_ind=gold_ind, color=TEST_COLOR)
+    elif test_lbl == '':
+      self.G.add_node(v, label=u'* / %s' % gold_lbl, test_label=test_lbl, gold_label=gold_lbl, \
+        test_ind=test_ind, gold_ind=gold_ind, color=GOLD_COLOR)
+    elif test_lbl == gold_lbl:
+      self.G.add_node(v, label=test_lbl, test_label=test_lbl, gold_label=gold_lbl, \
+        test_ind=test_ind, gold_ind=gold_ind, color=DFLT_COLOR)
+    else:
+      self.G.add_node(v, label=u'%s / %s' % (test_lbl, gold_lbl), test_label=test_lbl, gold_label=gold_lbl, \
+        test_ind=test_ind, gold_ind=gold_ind, color=DFLT_COLOR)
+
+  def add_inst(self, ind, var, instof):
+    self.gold_ind[var] = self.match[ind]
+    gold_lbl = ''
+    gold_ind = self.match[ind]
+    if gold_ind >= 0: # there's a gold match
+      gold_lbl = self.gold_inst_t[gold_ind]
+      if self.match[ind] in self.unmatched_inst:
+        del self.unmatched_inst[gold_ind]
+    self.add_node(var, instof, gold_lbl, test_ind=ind, gold_ind=gold_ind)
+
+  def add_rel1(self, reln, var, const):
+    const_matches = self.map_fn(const)
+    gold_edge_lbl = ''
+
+    # we match const to the highest-ranked match label from the var
+    gold_node_lbl = ''
+    node_hash = var+' '+const
+    for const_match in const_matches:
+      if (self.gold_ind[var], const_match) in self.gold_rel1_t:
+        gold_node_lbl = const_match
+        #TODO put the metatable editing in the helper fcns?
+        if reln not in self.gold_rel1_t[(self.gold_ind[var], const_match)]:
+          # relns between existing nodes should be in unmatched rel2
+          self.gold_ind[node_hash] = const_match
+          self.unmatched_rel2[(self.gold_ind[var], const_match)] = self.unmatched_rel1[(self.gold_ind[var], const_match)]
+          del self.unmatched_rel1[(self.gold_ind[var], const_match)]
+        else:
+          gold_edge_lbl = reln
+          self.unmatched_rel1[(self.gold_ind[var], const_match)].remove(reln)
+        break
+
+    self.add_node(node_hash, const, gold_node_lbl)
+    self.add_edge(var, node_hash, reln, gold_edge_lbl)
+
+  def add_rel2(self, reln, v1, v2):
+    gold_lbl = ''
+    if (self.gold_ind[v1], self.gold_ind[v2]) in self.gold_rel2_t:
+      if reln in self.gold_rel2_t[(self.gold_ind[v1], self.gold_ind[v2])]:
+        gold_lbl = reln
+        self.unmatched_rel2[(self.gold_ind[v1], self.gold_ind[v2])].remove(reln)
+    self.add_edge(v1, v2, reln, gold_lbl)
+
+  def unmatch_dead_nodes(self, node_weight_fn, edge_weight_fn):
+    """ Unmap node mappings that don't increase smatch score. """
+    node_is_live = {v:(gold == -1) for (v, gold) in self.gold_ind.items()}
+    for (v, attr) in self.G.nodes(data=True):
+      if node_weight_fn(attr['test_label'], attr['gold_label']) > 0:
+        node_is_live[v] = True
+    for (v1, links) in self.G.adjacency_iter():
+      for (v2, edges) in links.items():
+        if len(edges) > 1:
+          node_is_live[v2] = True
+          node_is_live[v1] = True
+          break
+        for (ind, attr) in edges.items():
+          if attr['test_label'] == attr['gold_label']:
+            node_is_live[v2] = True
+            node_is_live[v1] = True
+            break
+
+    for v in node_is_live.keys():
+      if not node_is_live[v]:
+        self.unmatched_inst[self.gold_ind[v]] = self.G.node[v]['gold_label']
+        self.G.node[v]['gold_label'] = ''
+        self.G.node[v]['label'] = u'%s / *' % self.G.node[v]['test_label']
+        self.G.node[v]['color'] = TEST_COLOR
+        del self.gold_ind[v]
+
+
+def amr2dict(inst, rel1, rel2):
+  """ Get tables of AMR data indexed by variable number """
+  node_inds = {}
+  inst_t = {}
+  for (ind, (i, v, label)) in enumerate(inst):
+    node_inds[v] = ind
+    inst_t[ind] = label
+
+  rel1_t = {}
+  for (label, v1, const) in rel1:
+    if (node_inds[v1], const) not in rel1_t:
+      rel1_t[(node_inds[v1], const)] = set()
+    rel1_t[(node_inds[v1], const)].add(label)
+
+  rel2_t = {}
+  for (label, v1, v2) in rel2:
+    if (node_inds[v1], node_inds[v2]) not in rel2_t:
+      rel2_t[(node_inds[v1], node_inds[v2])] = set()
+    rel2_t[(node_inds[v1], node_inds[v2])].add(label)
+
+  return (inst_t, rel1_t, rel2_t)
diff --git a/amrbatch/amrld/disagree_btwn_sents.py b/amrbatch/amrld/disagree_btwn_sents.py
new file mode 100755
index 00000000..f313dde2
--- /dev/null
+++ b/amrbatch/amrld/disagree_btwn_sents.py
@@ -0,0 +1,293 @@
+#!/usr/bin/env python
+"""
+disagree_btwn_sents.py
+(Derived from AMRICA/disagree.py)
+
+A tool for inspecting AMR data to id patterns of inter-annotator disagreement
+or semantic inequivalence.
+
+AMR input file expected in format where comments above each annotation indicate
+the sentence like so:
+
+# ::id DF-170-181103-888_2097.1 ::date 2013-09-16T07:15:31 ::annotator ANON-01 ::preferred
+# ::tok This is a sentence .
+(this / file
+  :is (an / AMR))
+
+For monolingual disagreement, all annotations of some sentence should occur
+consecutively in the monolingual annotation file. For bilingual, annotations
+should be in the same order of sentences between the two files.
+
+For bilingual disagreement, you can include a ::alignments field from jamr to help with
+AMR-sentence alignment.
+"""
+
+import argparse
+import argparse_config
+import codecs
+import networkx as nx
+from networkx.readwrite import json_graph
+import json
+import os
+import pygraphviz as pgz
+
+# internal libraries
+from compare_smatch import amr_metadata
+from compare_smatch import smatch_graph
+from compare_smatch.amr_alignment import Amr2AmrAligner
+from compare_smatch.amr_alignment import default_aligner
+from compare_smatch.smatch_graph import SmatchGraph
+from smatch import smatch
+
+cur_sent_id = 0
+
+def hilight_disagreement(test_amrs, gold_amr, iter_num, aligner=default_aligner, gold_aligned_fh=None):
+  """
+  Input:
+    gold_amr: gold AMR object
+    test_amrs: list of AMRs to compare to
+  Returns list of disagreement graphs for each gold-test AMR pair.
+  """
+
+  amr_graphs = []
+  smatchgraphs = []
+  gold_label=u'b'
+  gold_amr.rename_node(gold_label)
+  (gold_inst, gold_rel1, gold_rel2) = gold_amr.get_triples2()
+  (gold_inst_t, gold_rel1_t, gold_rel2_t) = smatch_graph.amr2dict(gold_inst, gold_rel1, gold_rel2)
+
+  for a in test_amrs:
+    aligner.set_amrs(a, gold_amr)
+    test_label=u'a'
+    a.rename_node(test_label)
+    (test_inst, test_rel1, test_rel2) = a.get_triples2()
+    if gold_aligned_fh:
+      best_match = get_next_gold_alignments(gold_aligned_fh)
+      best_match_num = -1.0
+    else:
+      (best_match, best_match_num) = smatch.get_fh(test_inst, test_rel1, test_rel2,
+        gold_inst, gold_rel1, gold_rel2,
+        test_label, gold_label,
+        node_weight_fn=aligner.node_weight_fn, edge_weight_fn=aligner.edge_weight_fn,
+        iter_num=iter_num)
+
+    disagreement = SmatchGraph(test_inst, test_rel1, test_rel2, \
+      gold_inst_t, gold_rel1_t, gold_rel2_t, \
+      best_match, const_map_fn=aligner.const_map_fn)
+    amr_graphs.append((disagreement.smatch2graph(node_weight_fn=aligner.node_weight_fn,
+                                                 edge_weight_fn=aligner.edge_weight_fn),
+      best_match_num))
+    smatchgraphs.append(disagreement)
+  return (amr_graphs, smatchgraphs)
+
+
+def open_output_files(args):
+  json_fh = None
+  if args.json_out:
+    json_fh = codecs.open(args.json_out, 'w', encoding='utf8')
+  align_fh = None
+  if args.align_out:
+    align_fh =  codecs.open(args.align_out, 'w', encoding='utf8')
+  return (json_fh, align_fh)
+
+
+def close_output_files(json_fh, align_fh):
+  json_fh and json_fh.close()
+  align_fh and align_fh.close()
+
+
+def get_next_gold_alignments(gold_aligned_fh):
+  match_hash = {}
+  line = gold_aligned_fh.readline().strip()
+  while (line):
+    if line.startswith('#'): # comment line
+      line = gold_aligned_fh.readline().strip()
+      continue
+    align = line.split('\t')
+    test_ind = int(align[0])
+    gold_ind = int(align[3])
+    if test_ind >= 0:
+      match_hash[test_ind] = gold_ind
+    line = gold_aligned_fh.readline().strip()
+
+  match = []
+  for (i, (k, v)) in enumerate(sorted(match_hash.items(), key=lambda x: x[0])):
+    assert i == k
+    match.append(v)
+  return match
+
+
+def get_sent_info(metadata, dflt_id=None):
+  """ Return ID, sentence if available, and change metadata to reflect """
+  (sent_id, sent) = (None, None)
+  if 'tok' in metadata:
+    sent = metadata['tok']
+  else:
+    sent = metadata['snt']
+
+  if 'id' in metadata:
+    sent_id = metadata['id']
+  elif dflt_id is not None:
+    sent_id = dflt_id
+  else:
+    sent_id = "%d" % cur_sent_id
+    cur_sent_id += 1
+
+  (metadata['id'], metadata['tok']) = \
+    (sent_id, sent)
+
+  return (sent_id, sent)
+
+
+def monolingual_main(args):
+  infile = codecs.open(args.infile, encoding='utf8')
+  gold_aligned_fh = None
+  if args.align_in:
+    gold_aligned_fh = codecs.open(args.align_in, encoding='utf8')
+  (json_fh, align_fh) = open_output_files(args)
+
+  amrs_same_sent = []
+  cur_id = ""
+  while True:
+    (amr_line, comments) = amr_metadata.get_amr_line(infile)
+    cur_amr = None
+    if amr_line:
+      cur_amr = amr_metadata.AmrMeta.from_parse(amr_line, comments)
+      get_sent_info(cur_amr.metadata)
+      if 'annotator' not in cur_amr.metadata:
+        cur_amr.metadata['annotator'] = ''
+      if not cur_id:
+        cur_id = cur_amr.metadata['id']
+
+    if cur_amr is None or cur_id != cur_amr.metadata['id']:
+      gold_amr = amrs_same_sent[0]
+      test_amrs = amrs_same_sent[1:]
+      if len(test_amrs) == 0:
+        test_amrs = [gold_amr] # single AMR view case
+        args.num_restarts = 1 # TODO make single AMR view more efficient
+      (amr_graphs, smatchgraphs) = hilight_disagreement(test_amrs, gold_amr, args.num_restarts)
+
+      gold_anno = gold_amr.metadata['annotator']
+      sent = gold_amr.metadata['tok']
+
+      if (args.verbose):
+        print("ID: %s\n Sentence: %s\n gold anno: %s" % (cur_id, sent, gold_anno))
+
+      for (a, (g, score)) in zip(test_amrs, amr_graphs):
+        test_anno = a.metadata['annotator']
+        if json_fh:
+          json_fh.write(json.dumps(g) + '\n')
+        if align_fh:
+          for sg in smatchgraphs:
+            align_fh.write("""# ::id %s\n# ::tok %s\n# ::gold_anno %s\n# ::test_anno %s""" % \
+              (cur_id, sent, gold_anno, test_anno))
+            align_fh.write('\n'.join(sg.get_text_alignments()) + '\n\n')
+        if (args.verbose):
+          print("  annotator %s score: %d" % (test_anno, score))
+
+        ag = nx.to_agraph(g)
+        ag.graph_attr['label'] = sent
+        ag.layout(prog=args.layout)
+        ag.draw('%s/%s_annotated_%s_%s.png' % (args.outdir, cur_id, gold_anno, test_anno))
+
+      amrs_same_sent = []
+      if cur_amr is not None:
+        cur_id = cur_amr.metadata['id']
+      else:
+        break
+
+    amrs_same_sent.append(cur_amr)
+
+  infile.close()
+  gold_aligned_fh and gold_aligned_fh.close()
+  close_output_files(json_fh, align_fh)
+
+
+def xlang_main(args):
+  """ Disagreement graphs for aligned cross-language language. """
+  src_amr_fh = codecs.open(args.src_amr, encoding='utf8')
+  tgt_amr_fh = codecs.open(args.tgt_amr, encoding='utf8')
+  gold_aligned_fh = None
+  if args.align_in:
+    gold_aligned_fh = codecs.open(args.align_in, encoding='utf8')
+  (json_fh, align_fh) = open_output_files(args)
+
+  amrs_same_sent = []
+  aligner = Amr2AmrAligner(num_best=args.num_align_read, num_best_in_file=args.num_aligned_in_file)
+  while True:
+    (src_amr_line, src_comments) = amr_metadata.get_amr_line(src_amr_fh)
+    if src_amr_line == "":
+      break
+    (tgt_amr_line, tgt_comments) = amr_metadata.get_amr_line(tgt_amr_fh)
+    src_amr = amr_metadata.AmrMeta.from_parse(src_amr_line, src_comments, xlang=True)
+    tgt_amr = amr_metadata.AmrMeta.from_parse(tgt_amr_line, tgt_comments, xlang=True)
+    (cur_id, src_sent) = get_sent_info(src_amr.metadata)
+    (tgt_id, tgt_sent) = get_sent_info(tgt_amr.metadata, dflt_id=cur_id)
+    assert cur_id == tgt_id
+
+    (amr_graphs, smatchgraphs) = hilight_disagreement([tgt_amr], src_amr, args.num_restarts, aligner=aligner, gold_aligned_fh=gold_aligned_fh)
+    if json_fh:
+      json_fh.write(json.dumps(amr_graphs[0]) + '\n')
+    if align_fh:
+      align_fh.write("""# ::id %s\n# ::src_snt %s\n# ::tgt_snt %s\n""" % (cur_id, src_sent, tgt_sent))
+      align_fh.write('\n'.join(smatchgraphs[0].get_text_alignments()) + '\n\n')
+    if (args.verbose):
+      print("ID: %s\n Sentence: %s\n Sentence: %s\n Score: %f" % (cur_id, src_sent, tgt_sent, amr_graphs[0][1]))
+    #raw_input("Press enter to continue: ")
+
+    ag = nx.to_agraph(amr_graphs[0][0])
+    ag.graph_attr['label'] = "%s\n%s" % (src_sent, tgt_sent)
+    ag.layout(prog=args.layout)
+    ag.draw('%s/%s.png' % (args.outdir, cur_id))
+
+  src_amr_fh.close()
+  tgt_amr_fh.close()
+  gold_aligned_fh and gold_aligned_fh.close()
+  close_output_files(json_fh, align_fh)
+
+
+if __name__ == '__main__':
+  parser = argparse.ArgumentParser()
+  parser.add_argument("-c", "--conf_file", help="Specify config file")
+  parser.add_argument('-i', '--infile', help='amr input file')
+  parser.add_argument('-o', '--outdir', help='image output directory')
+  parser.add_argument('-v', '--verbose', action='store_true')
+  parser.add_argument('-s', '--src_amr',
+    help='In bitext mode, source language AMR file.')
+  parser.add_argument('-t', '--tgt_amr',
+    help='In bitext mode, target language AMR file.')
+  parser.add_argument('--align_src2tgt',
+    help='In bitext mode, GIZA alignment .NBEST file (see GIZA++ -nbestalignments opt) with source as vcb1.')
+  parser.add_argument('--align_tgt2src',
+    help='In bitext mode, GIZA alignment .NBEST file (see GIZA++ -nbestalignments opt) with target as vcb1.')
+  parser.add_argument('--num_align_read', type=int,
+    help='N to read from GIZA NBEST file.')
+  parser.add_argument('--num_aligned_in_file', type=int, default=1,
+    help='N printed to GIZA NBEST file.')
+  parser.add_argument('-j', '--json_out',
+    help='File to dump json graphs to.')
+  parser.add_argument('--num_restarts', type=int, default=5,
+    help='Number of random restarts to execute during hill-climbing algorithm.')
+  parser.add_argument('--align_out',
+    help="Human-readable alignments output file")
+  parser.add_argument('--align_in',
+    help="Alignments from human-editable text file, as from align_out")
+  parser.add_argument('--layout', default='dot',
+    help='Graphviz output layout')
+  # TODO make interactive option and option to process a specific range
+
+  args_conf = parser.parse_args()
+  if args_conf.conf_file:
+    argparse_config.read_config_file(parser, args_conf.conf_file)
+
+  args = parser.parse_args()
+  if args.no_verbose:
+    args.verbose = False
+  if not args.num_align_read:
+    args.num_align_read = args.num_aligned_in_file
+
+  if not os.path.exists(args.outdir):
+    os.makedirs(args.outdir)
+
+  xlang_main(args)
+  
\ No newline at end of file
diff --git a/amrbatch/amrld/requirements.txt b/amrbatch/amrld/requirements.txt
new file mode 100644
index 00000000..d1128324
--- /dev/null
+++ b/amrbatch/amrld/requirements.txt
@@ -0,0 +1,3 @@
+argparse
+rdflib
+numpy
diff --git a/amrbatch/amrld/simple-smatch-table.py b/amrbatch/amrld/simple-smatch-table.py
new file mode 100755
index 00000000..557a5027
--- /dev/null
+++ b/amrbatch/amrld/simple-smatch-table.py
@@ -0,0 +1,297 @@
+#!/usr/bin/env python
+
+"""
+smatch-table.py
+
+This file is from the code for smatch, available at:
+
+http://amr.isi.edu/download/smatch-v1.0.tar.gz
+http://amr.isi.edu/smatch-13.pdf
+"""
+
+import sys
+import subprocess
+from smatch import amr
+from smatch import smatch
+import os
+import random
+import time
+
+from compare_smatch import amr_metadata
+#import optparse
+# import argparse #argparse only works for python 2.7. If you are using older versin of Python, you can use optparse instead.
+#import locale
+
+verbose = False  # global variable, verbose output control
+
+single_score = True  # global variable, single score output control
+
+pr_flag = False  # global variable, output precision and recall
+
+ERROR_LOG = sys.stderr
+
+match_num_dict = {}  # key: match number tuples    value: the matching number
+
+isi_dir_pre = "/nfs/web/isi.edu/cgi-bin/div3/mt/save-amr"
+
+def build_arg_parser():
+  """Build an argument parser using argparse"""
+  parser = argparse.ArgumentParser(
+      description="Smatch calculator -- arguments")
+  parser.add_argument(
+      '-f',
+      nargs=2,
+      required=True,
+      type=argparse.FileType('r'),
+      help='Two files containing AMR pairs. AMRs in each file are separated by a single blank line')
+  parser.add_argument(
+      '-o',
+      '--outfile',
+      help='Output')
+  parser.add_argument(
+      '-r',
+      type=int,
+      default=4,
+      help='Restart number (Default:4)')
+  parser.add_argument(
+      '-v',
+      action='store_true',
+      help='Verbose output (Default:False)')
+  parser.add_argument(
+      '--ms',
+      action='store_true',
+      default=False,
+      help='Output multiple scores (one AMR pair a score) instead of a single document-level smatch score (Default: False)')
+  parser.add_argument(
+      '--pr',
+      action='store_true',
+      default=False,
+      help="Output precision and recall as well as the f-score. Default: false")
+  return parser
+
+def build_arg_parser2():
+  """Build an argument parser using optparse"""
+  usage_str = "Smatch calculator -- arguments"
+  parser = optparse.OptionParser(usage=usage_str)
+  #parser.add_option("-h","--help",action="help",help="Smatch calculator -- arguments")
+  parser.add_option(
+      "-f",
+      "--files",
+      nargs=2,
+      dest="f",
+      type="string",
+      help='Two files containing AMR pairs. AMRs in each file are separated by a single blank line. This option is required.')
+  parser.add_option(
+      "-o",
+      "--outfile",
+      nargs=1,
+      dest="o",
+      type="string",
+      help='Output file.')
+  parser.add_option(
+      "-r",
+      "--restart",
+      dest="r",
+      type="int",
+      help='Restart number (Default: 4)')
+  parser.add_option(
+      "-v",
+      "--verbose",
+      action='store_true',
+      dest="v",
+      help='Verbose output (Default:False)')
+  parser.add_option(
+      "--ms",
+      "--multiple_score",
+      action='store_true',
+      dest="ms",
+      help='Output multiple scores (one AMR pair a score) instead of a single document-level smatch score (Default: False)')
+  parser.add_option(
+      '--pr',
+      "--precision_recall",
+      action='store_true',
+      dest="pr",
+      help="Output precision and recall as well as the f-score. Default: false")
+  parser.set_defaults(r=4, v=False, ms=False, pr=False)
+  return parser
+
+def main(args):
+  """Main function of the smatch calculation program"""
+  global verbose
+  global iter_num
+  global single_score
+  global pr_flag
+  global match_num_dict
+  # set the restart number
+  iter_num = args.r + 1
+  verbose = False
+  if args.ms:
+    single_score = False
+  if args.v:
+    verbose = True
+  if args.pr:
+    pr_flag = True
+  total_match_num = 0
+  total_test_num = 0
+  total_gold_num = 0
+  sent_num = 1
+  prev_amr1 = ""
+  outfile = open(args.outfile, 'w')
+  if not single_score:     
+    outfile.write("Sentence\tText")
+    if pr_flag:
+      outfile.write("\tPrecision\tRecall")
+    outfile.write("\tSmatch\n")
+    
+  while True:
+    cur_amr1 = smatch.get_amr_line(args.f[0])
+    (cur_amr2, comments) = amr_metadata.get_amr_line(args.f[1])
+    if cur_amr1 == "" and cur_amr2 == "":
+      break
+    if(cur_amr1 == ""):        
+      # GULLY CHANGED THIS. 
+      # IF WE RUN OUT OF AVAILABLE AMRS FROM FILE 1, 
+      # REUSE THE LAST AVAILABLE AMR
+      cur_amr1 = prev_amr1  
+      #print >> sys.stderr, "Error: File 1 has less AMRs than file 2"
+      #print >> sys.stderr, "Ignoring remaining AMRs"
+      #break
+      # print >> sys.stderr, "AMR 1 is empty"
+      # continue
+    if(cur_amr2 == ""):
+      print >> sys.stderr, "Error: File 2 has less AMRs than file 1"
+      print >> sys.stderr, "Ignoring remaining AMRs"
+      break
+    # print >> sys.stderr, "AMR 2 is empty"
+    # continue
+    prev_amr1 = cur_amr1
+    
+    amr1 = amr.AMR.parse_AMR_line(cur_amr1)
+    amr2 = amr.AMR.parse_AMR_line(cur_amr2)
+    
+    # We were getting screwy SMATCH scores from 
+    # using the amr_metadata construct
+    meta_enabled_amr = amr_metadata.AmrMeta.from_parse(cur_amr2, comments)
+    
+    test_label = "a"
+    gold_label = "b"
+    amr1.rename_node(test_label)
+    amr2.rename_node(gold_label)
+    (test_inst, test_rel1, test_rel2) = amr1.get_triples2()
+    (gold_inst, gold_rel1, gold_rel2) = amr2.get_triples2()
+    if verbose:
+      print "AMR pair", sent_num
+      print >> sys.stderr, "Instance triples of AMR 1:", len(test_inst)
+      print >> sys.stderr, test_inst
+  #   print >> sys.stderr,"Relation triples of AMR 1:",len(test_rel)
+      print >> sys.stderr, "Relation triples of AMR 1:", len(test_rel1) + len(test_rel2)
+      print >>sys.stderr, test_rel1
+      print >> sys.stderr, test_rel2
+  #   print >> sys.stderr, test_rel
+      print >> sys.stderr, "Instance triples of AMR 2:", len(gold_inst)
+      print >> sys.stderr, gold_inst
+  #   print >> sys.stderr,"Relation triples of file 2:",len(gold_rel)
+      print >> sys.stderr, "Relation triples of AMR 2:", len(
+          gold_rel1) + len(gold_rel2)
+      #print >> sys.stderr,"Relation triples of file 2:",len(gold_rel1)+len(gold_rel2)
+      print >> sys.stderr, gold_rel1
+      print >> sys.stderr, gold_rel2
+  #    print >> sys.stderr, gold_rel
+    if len(test_inst) < len(gold_inst):
+      (best_match,
+       best_match_num) = smatch.get_fh(test_inst,
+                                test_rel1,
+                                test_rel2,
+                                gold_inst,
+                                gold_rel1,
+                                gold_rel2,
+                                test_label,
+                                gold_label)
+      if verbose:
+        print >> sys.stderr, "AMR pair ", sent_num
+        print >> sys.stderr, "best match number", best_match_num
+        print >> sys.stderr, "best match", best_match
+    else:
+      (best_match,
+       best_match_num) = smatch.get_fh(gold_inst,
+                                gold_rel1,
+                                gold_rel2,
+                                test_inst,
+                                test_rel1,
+                                test_rel2,
+                                gold_label,
+                                test_label)
+      if verbose:
+        print >> sys.stderr, "Sent ", sent_num
+        print >> sys.stderr, "best match number", best_match_num
+        print >> sys.stderr, "best match", best_match
+    if not single_score:
+      #(precision,
+      # recall,
+      # best_f_score) = smatch.compute_f(best_match_num,
+      #                           len(test_rel1) + len(test_inst) + len(test_rel2),
+      #                           len(gold_rel1) + len(gold_inst) + len(gold_rel2))
+      outfile.write( str(meta_enabled_amr.metadata.get("tok", None)) )
+      #if pr_flag:
+      #  outfile.write( "\t%.2f" % precision )
+      #  outfile.write( "\t%.2f" % recall )
+      #outfile.write( "\t%.2f" % best_f_score )
+      print sent_num
+      outfile.write( "\n" )
+    total_match_num += best_match_num
+    total_test_num += len(test_rel1) + len(test_rel2) + len(test_inst)
+    total_gold_num += len(gold_rel1) + len(gold_rel2) + len(gold_inst)
+    match_num_dict.clear()
+    sent_num += 1  # print "F-score:",best_f_score
+  if verbose:
+    print >> sys.stderr, "Total match num"
+    print >> sys.stderr, total_match_num, total_test_num, total_gold_num
+  if single_score:
+    (precision, recall, best_f_score) = smatch.compute_f(
+        total_match_num, total_test_num, total_gold_num)
+    if pr_flag:
+      print "Precision: %.2f" % precision
+      print "Recall: %.2f" % recall
+    print "Document F-score: %.2f" % best_f_score
+  args.f[0].close()
+  args.f[1].close()
+  outfile.close()
+
+if __name__ == "__main__":
+  parser = None
+  args = None
+  if sys.version_info[:2] != (2, 7):
+    if sys.version_info[0] != 2 or sys.version_info[1] < 5:
+      print >> ERROR_LOG, "Smatch only supports python 2.5 or later"
+      exit(1)
+    import optparse
+    if len(sys.argv) == 1:
+      print >> ERROR_LOG, "No argument given. Please run smatch.py -h to see the argument descriptions."
+      exit(1)
+    # requires version >=2.3!
+    parser = build_arg_parser2()
+    (args, opts) = parser.parse_args()
+    # handling file errors
+    # if not len(args.f)<2:
+    #   print >> ERROR_LOG,"File number given is less than 2"
+    #   exit(1)
+    file_handle = []
+    if args.f is None:
+      print >> ERROR_LOG, "smatch.py requires -f option to indicate two files containing AMR as input. Please run smatch.py -h to see the argument descriptions."
+      exit(1)
+    if not os.path.exists(args.f[0]):
+      print >> ERROR_LOG, "Given file", args.f[0], "does not exist"
+      exit(1)
+    else:
+      file_handle.append(codecs.open(args.f[0], encoding='utf8'))
+    if not os.path.exists(args.f[1]):
+      print >> ERROR_LOG, "Given file", args.f[1], "does not exist"
+      exit(1)
+    else:
+      file_handle.append(codecs.open(args.f[1], encoding='utf8'))
+    args.f = tuple(file_handle)
+  else:  # version 2.7
+    import argparse
+    parser = build_arg_parser()
+    args = parser.parse_args()
+  main(args)
diff --git a/amrbatch/amrld/smatch/README.txt b/amrbatch/amrld/smatch/README.txt
new file mode 100755
index 00000000..2668f4c9
--- /dev/null
+++ b/amrbatch/amrld/smatch/README.txt
@@ -0,0 +1,103 @@
+There is also a pdf version of this documentation: smatch_guide.pdf (with the same content but in the same directory. 
+
+Smatch Tool Guideline
+
+Shu Cai 03/20/2013
+
+Smatch is a tool to evaluate the semantic overlap between semantic feature structures. It can be used to compute the inter agreements of AMRs, and the agreement between an automatic-generated AMR and a gold AMR. For multiple AMR pairs, the smatch tool can provide a weighted, overall score for all the AMR pairs. 
+
+I. Content and web demo pages
+
+The directory contains the Smatch code (mostly Python and some Perl) as well as a guide for Smatch.
+
+Smatch Webpages
+
+Smatch tool webpage: http://amr.isi.edu/eval/smatch/compare.html (A quick tutorial can be found on the page)
+- input: two AMRs. 
+- output: the smatch score and the matching/unmatching triples.
+
+Smatch table tool webpage: http://amr.isi.edu/eval/smatch/table.html
+- input: AMR IDs and users. 
+- output: a table which consists of the smatch scores of every pair of users.
+
+II. Installation
+
+Python (version 2.5 or later) is required to run smatch tool. Python 2.7 is recommended. No compilation is necessary. 
+
+If a user wants to run smatch tool outside the current locations, they can just copy the whole directory. Running the latest smatch tools requires the following files: amr.py (a library called by smatch.py), smatch.py, smatch-table.py. Running the old versions of smatch requires Perl installed, and  
+esem-format-check.pl,smatch-v0.x.py (x<5), smatch-table-v0.x.py (x<3).
+
+III. Usage
+
+Smatch tool consists of two program written in python.
+
+1. smatch.py: for computing the smatch score(s) for multiple AMRs created by two different groups.
+
+Input: two files which contain AMRs. Each file may contain multiple AMRs, and every two AMRs are separated by a blank line. AMRs can be one-per-line or have multiple lines, as long as there is no blank line in one AMR.  
+
+Input file format: see test_input1.txt, test_input2.txt in the smatch tool folder. AMRs are separated by one or more blank lines, so no blank lines are allowed inside an AMR. Lines starting with a hash (#) will be ignored.
+
+Output: Smatch score(s) computed 
+
+Usage: python smatch.py [-h] -f F F [-r R] [-v] [-ms]
+
+arguments:
+
+-h: help
+
+-f: two files which contain multiple AMRs. A blank line is used to separate two AMRs. Required arguments.
+
+-r: restart numer of the heuristic search during computation, optional. Default value: 4. This argument must be a positive integer. Large restart number will reduce the chance of search error, but also increase the running time. Small restart number will reduce the running time as well as increase the change of search error. The default value is by far the best trade-off. User can set a large number if the AMR length is long (search space is large) and user does not need very high speed.  
+
+-v: verbose output, optional. Default value: false. The verbose information includes the triples of each AMR, the matching triple number found for each iterations, and the best matching triple number. It is useful when you try to understand how the program works. User will not need this option most of the time. 
+ 
+--ms: multiple score, optional. Adding this option will result in a single smatch score for each AMR pair. Otherwise it will output one single weighted score based on all pairs of AMRs. AMRs are weighted according to their number of triples.
+Default value: false
+
+--pr: Output precision and recall as well as the f-score. Default:false
+
+A typical (and most common) example of running smatch.py: 
+
+python smatch.py -f test_input1.txt test_input2.txt
+
+The release includes sample files test_input1.txt and test_input2.txt, so you should be able to run the above command as is. The above command should about the following line:
+Document F-score: 0.81
+
+2. smatch-table.py: it calls the smatch library to compute the smatch scores for a group of users and multiple AMR IDs, and output a table to show the AMR score between each pair of users. 
+
+Input: AMR ID list and User list. AMR ID list can be stored in a file (-fl file) or given by the command line (-f AMR_ID1, AMR_ID2,...). User list are given by the command line (-p user1,user2,..). If no users are given, the program searches for all the users who annotates all AMRs we require. The user number should be at least 2. 
+
+Input file format: AMR ID list (see sample_file_list the smatch tool folder)
+
+Output: A table which shows the overall AMR score between every pair of users. 
+
+Usage: python smatch-table.py [-h] [--fl FL] [-f F [F ...]] [-p [P [P ...]]]
+                       [--fd FD] [-r R] [-v]
+
+optional arguments:
+
+-h, --help      show this help message and exit
+
+--fl FL         AMR ID list file (a file which contains one line of AMR IDs, separated by blank space)
+
+-f F [F ...]    AMR IDs (at least one). If we already have valid AMR ID list file, this option will be ignored.
+
+-p [P [P ...]]  User list (It can be unspecified. When the list is none, the program searches for all the users who annotates all AMRs we require) It is meaningless to give only one user since smatch-table computes agreement between each pair of users. So the number of P is at least 2.
+
+--fd FD         AMR File directory. Default=location on isi file system
+
+-r R            Restart number (Default:4), same as the -r option in smatch.py
+
+-v              Verbose output (Default:False), same as the -v option in smatch.py
+
+
+A typical example of running smatch-table.py: 
+
+python smatch-table.py --fd $amr_root_dir --fl sample_file_list -p ulf knight
+
+which will compare files
+$amr_root_dir/ulf/nw_wsj_0001_1.txt $amr_root_dir/knight/nw_wsj_0001_1.txt
+$amr_root_dir/ulf/nw_wsj_0001_2.txt $amr_root_dir/knight/nw_wsj_0001_2.txt
+etc.
+
+Note: smatch-table.py computes smatch scores for every pair of users, so its speed can be slow when the number of user is large or when -P option is not set (in this case we compute smatch scores for all users who annotates the AMRs we require).
diff --git a/amrbatch/amrld/smatch/__init__.py b/amrbatch/amrld/smatch/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/amrbatch/amrld/smatch/amr.py b/amrbatch/amrld/smatch/amr.py
new file mode 100755
index 00000000..85b2a740
--- /dev/null
+++ b/amrbatch/amrld/smatch/amr.py
@@ -0,0 +1,343 @@
+#!/usr/bin/env python
+
+"""
+amr.py
+
+This file is from the code for smatch, available at:
+
+http://amr.isi.edu/download/smatch-v1.0.tar.gz
+http://amr.isi.edu/smatch-13.pdf
+"""
+
+import sys
+from collections import defaultdict
+
+
+class AMR(object):
+
+  def __init__(
+          self,
+          var_list=None,
+          var_value_list=None,
+          link_list=None,
+          const_link_list=None,
+          path2label=None):
+    """
+    path2label: maps 0.1.0 to the label (inst or const) of the 0-indexed child
+      of the 1-indexed child of the 0th node (head)
+    """
+    if var_list is None:
+      self.nodes = []  # AMR variables
+      self.root = None
+    else:
+      self.nodes = var_list[:]
+      if len(var_list) != 0:
+        self.root = var_list[0]
+      else:
+        self.root = None
+    if var_value_list is None:
+      self.var_values = []
+    else:
+      self.var_values = var_value_list[:]
+    if link_list is None:
+      # connections between instances  #adjacent list representation
+      self.links = []
+    else:
+      self.links = link_list[:]
+    if const_link_list is None:
+      self.const_links = []
+    else:
+      self.const_links = const_link_list[:]
+    if path2label is None:
+      self.path2label = {}
+    else:
+      self.path2label = path2label
+
+  def add_node(self, node_value):
+    self.nodes.append(node_value)
+
+  def rename_node(self, prefix):
+    var_map_dict = {}
+    for i in range(0, len(self.nodes)):
+      var_map_dict[self.nodes[i]] = prefix + str(i)
+    for i, v in enumerate(self.nodes):
+      self.nodes[i] = var_map_dict[v]
+    for i, d in enumerate(self.links):
+      new_dict = {}
+      for k, v in d.items():
+        new_dict[var_map_dict[k]] = v
+      self.links[i] = new_dict
+
+  def get_triples(self):
+    """Get the triples in two list: instance_triple, relation_triple"""
+    instance_triple = []
+    relation_triple = []
+    for i in range(len(self.nodes)):
+      instance_triple.append(("instance", self.nodes[i], self.var_values[i]))
+      for k, v in self.links[i].items():
+        relation_triple.append((v, self.nodes[i], k))
+      for k2, v2 in self.const_links[i].items():
+        relation_triple.append((k2, self.nodes[i], v2))
+    return (instance_triple, relation_triple)
+
+  def get_triples2(self):
+    """Get the triples in three lists: instance_triple, relation (two variables) triple, and relation (one variable) triple"""
+    instance_triple = []
+    relation_triple1 = []
+    relation_triple2 = []
+    for i in range(len(self.nodes)):
+      instance_triple.append(("instance", self.nodes[i], self.var_values[i]))
+      for k, v in self.links[i].items():
+        relation_triple2.append((v, self.nodes[i], k))
+      for k2, v2 in self.const_links[i].items():
+        relation_triple1.append((k2, self.nodes[i], v2))
+    return (instance_triple, relation_triple1, relation_triple2)
+
+  def __str__(self):
+    """Output AMR string"""
+    for i in range(len(self.nodes)):
+      print("Variable", i, self.nodes[i])
+      print("Dependencies:")
+      for k, v in self.links[i].items():
+        print("Variable", k, " via ", v)
+      for k2, v2 in self.const_links[i].items():
+        print("Attribute:", k2, "value", v2)
+
+  def __repr__(self):
+    return self.__str__()
+
+  def out_amr(self):
+    self.__str__()
+
+  @staticmethod
+  def parse_AMR_line(line, xlang=False):
+    # set xlang True if you want consts represented as variable nodes with
+    # instance labels
+    # significant symbol just encountered: 1 for (, 2 for :, 3 for /
+    state = -1
+    stack = []  # variable stack
+    cur_charseq = []  # current processing char sequence
+    var_dict = {}  # key: var name value: var value
+    var_list = []  # variable name list (order: occurence of the variable
+    # key: var name:  value: list of (attribute name, other variable)
+    var_attr_dict1 = defaultdict(list)
+    # key:var name, value: list of (attribute name, const value)
+    var_attr_dict2 = defaultdict(list)
+    cur_attr_name = ""  # current attribute name
+    attr_list = []  # each entry is an attr dict
+    in_quote = False
+    curr_path = ['0']
+    path2label = {}
+    path_lookup = {}  # (var, reln, const) to path key
+
+    def remove_from_paths(path):
+      """ Adjust all paths in path2label by removing the node at path
+          (and any descdendants) """
+      node_ind = int(path[-1])
+      depth = len(path) - 1
+      prefix = '.'.join(path[:-1]) + '.'
+      # remove node from path2label keys
+      new_path2label = {}
+      for (k, v) in path2label.items():
+        if k.startswith(prefix):
+          k_arr = k.split('.')
+          curr_ind = int(k_arr[depth])
+          if curr_ind == node_ind:
+            continue  # deleting node
+          elif curr_ind > node_ind:
+            # node index moves down by 1 since middle node removed
+            k_arr[depth] = str(curr_ind - 1)
+            new_path2label['.'.join(k_arr)] = v
+            continue
+        new_path2label[k] = v
+      return new_path2label
+
+      # remove node from path_lookup vals
+      for (k, v) in path_lookup.items():
+        if v[:depth] == path[:depth]:
+          curr_ind = int(v[depth])
+          if curr_ind == node_ind:
+            del path_lookup[k]
+          if curr_ind > node_ind:
+            v[depth] = str(curr_ind - 1)
+
+    for i, c in enumerate(line.strip()):
+      if c == " ":
+        if in_quote:
+          cur_charseq.append('_')
+          continue
+        if state == 2:
+          cur_charseq.append(c)
+        continue
+      elif c == "\"":
+        if in_quote:
+          in_quote = False
+        else:
+          in_quote = True
+      elif c == "(":
+        if in_quote:
+          continue
+        if state == 2:
+          if cur_attr_name != "":
+            print("Format error when processing ", line[0:i + 1])
+            return None
+          cur_attr_name = "".join(cur_charseq).strip()
+          cur_charseq[:] = []
+        state = 1
+      elif c == ":":
+        if in_quote:
+          continue
+        if state == 3:  # (...:
+          var_value = "".join(cur_charseq)
+          cur_charseq[:] = []
+          cur_var_name = stack[-1]
+          var_dict[cur_var_name] = var_value
+          path2label['.'.join(curr_path)] = var_value
+          curr_path.append('0')
+        elif state == 2:  # : ...:
+          temp_attr_value = "".join(cur_charseq)
+          cur_charseq[:] = []
+          parts = temp_attr_value.split()
+          if len(parts) < 2:
+            print("Error in processing", line[0:i + 1])
+            return None
+          attr_name = parts[0].strip()
+          attr_value = parts[1].strip()
+          if len(stack) == 0:
+            print("Error in processing", line[:i], attr_name, attr_value)
+            return None
+          # TODO should all labels in quotes be consts?
+          if attr_value not in var_dict:
+            var_attr_dict2[stack[-1]].append((attr_name, attr_value))
+            path2label['.'.join(curr_path)] = attr_value
+            path_lookup[
+                (stack[-1], attr_name, attr_value)] = [i for i in curr_path]
+            curr_path[-1] = str(int(curr_path[-1]) + 1)
+          else:
+            var_attr_dict1[stack[-1]].append((attr_name, attr_value))
+        else:
+          curr_path[-1] = str(int(curr_path[-1]) + 1)
+        state = 2
+      elif c == "/":
+        if in_quote:
+          continue
+        if state == 1:
+          variable_name = "".join(cur_charseq)
+          cur_charseq[:] = []
+          if variable_name in var_dict:
+            print("Duplicate variable ", variable_name, " in parsing AMR")
+            return None
+          stack.append(variable_name)
+          var_list.append(variable_name)
+          if cur_attr_name != "":
+            if not cur_attr_name.endswith("-of"):
+              var_attr_dict1[stack[-2]].append((cur_attr_name, variable_name))
+            else:
+              var_attr_dict1[variable_name].append(
+                  (cur_attr_name[:-3], stack[-2]))
+            cur_attr_name = ""
+        else:
+          print("Error in parsing AMR", line[0:i + 1])
+          return None
+        state = 3
+      elif c == ")":
+        if in_quote:
+          continue
+        if len(stack) == 0:
+          print("Unmatched parathesis at position", i, 
+                "in processing", line[0:i + 1])
+          return None
+        if state == 2:
+          temp_attr_value = "".join(cur_charseq)
+          cur_charseq[:] = []
+          parts = temp_attr_value.split()
+          if len(parts) < 2:
+            print("Error processing", line[:i + 1], temp_attr_value)
+            return None
+          attr_name = parts[0].strip()
+          attr_value = parts[1].strip()
+          if cur_attr_name.endswith("-of"):
+            var_attr_dict1[variable_name].append(
+                (cur_attr_name[:-3], stack[-2]))
+          elif attr_value not in var_dict:
+            var_attr_dict2[stack[-1]].append((attr_name, attr_value))
+          else:
+            var_attr_dict1[stack[-1]].append((attr_name, attr_value))
+          path2label['.'.join(curr_path)] = attr_value
+          path_lookup[
+              (stack[-1], attr_name, attr_value)] = [i for i in curr_path]
+          curr_path.pop()
+        elif state == 3:
+          var_value = "".join(cur_charseq)
+          cur_charseq[:] = []
+          cur_var_name = stack[-1]
+          var_dict[cur_var_name] = var_value
+          path2label['.'.join(curr_path)] = var_value
+        else:
+          curr_path.pop()
+        stack.pop()
+        cur_attr_name = ""
+        state = 4
+      else:
+        cur_charseq.append(c)
+    # create var_list, link_list, attribute
+    # keep original variable name.
+    var_value_list = []
+    link_list = []
+    const_attr_list = []  # for monolingual mode
+
+    # xlang mode variables
+    const_cnt = 0
+    const_var_list = []
+    const_var_value_list = []
+    const_link_list = []
+
+    for v in var_list:
+      if v not in var_dict:
+        print("Error: variable value not found", v)
+        return None
+      else:
+        var_value_list.append(var_dict[v])
+      link_dict = {}
+      const_dict = {}
+      if v in var_attr_dict1:
+        for v1 in var_attr_dict1[v]:
+          link_dict[v1[1]] = v1[0]
+      if v in var_attr_dict2:
+        for v2 in var_attr_dict2[v]:
+          const_lbl = v2[1]
+          if v2[1][0] == "\"" and v2[1][-1] == "\"":
+            const_lbl = v2[1][1:-1]
+          elif v2[1] in var_dict:
+            # not the first occurrence of this child var
+            link_dict[v2[1]] = v2[0]
+            path2label = remove_from_paths(path_lookup[(v, v2[0], v2[1])])
+            continue
+
+          if xlang:
+            const_var = '_CONST_%d' % const_cnt
+            const_cnt += 1
+            var_dict[const_var] = const_lbl
+            const_var_list.append(const_var)
+            const_var_value_list.append(const_lbl)
+            const_link_list.append({})
+            link_dict[const_var] = v2[0]
+          else:
+            const_dict[v2[0]] = const_lbl
+
+      link_list.append(link_dict)
+      if not xlang:
+        const_attr_list.append(const_dict)
+      link_list[0][var_list[0]] = "TOP"
+    if xlang:
+      var_list += const_var_list
+      var_value_list += const_var_value_list
+      link_list += const_link_list
+      const_attr_list = [{} for v in var_list]
+    result_amr = AMR(
+        var_list,
+        var_value_list,
+        link_list,
+        const_attr_list,
+        path2label)
+    return result_amr
diff --git a/amrbatch/amrld/smatch/smatch-table.py b/amrbatch/amrld/smatch/smatch-table.py
new file mode 100755
index 00000000..11fdbdce
--- /dev/null
+++ b/amrbatch/amrld/smatch/smatch-table.py
@@ -0,0 +1,441 @@
+#!/usr/bin/env python
+
+"""
+smatch-table.py
+
+This file is from the code for smatch, available at:
+
+http://amr.isi.edu/download/smatch-v1.0.tar.gz
+http://amr.isi.edu/smatch-13.pdf
+"""
+
+import amr
+import sys
+import subprocess
+import smatch
+import os
+import random
+import time
+#import optparse
+# import argparse #argparse only works for python 2.7. If you are using older versin of Python, you can use optparse instead.
+#import locale
+
+ERROR_LOG = sys.stderr
+
+verbose = False
+
+isi_dir_pre = "/nfs/web/isi.edu/cgi-bin/div3/mt/save-amr"
+
+"""
+Get the annotator name list based on a list of files
+Args:
+   file_dir: AMR file folder
+   files: a list of AMR names, e.g. nw_wsj_0001_1
+Return:
+   a list of user names who annotate all the files
+"""
+
+
+def get_names(file_dir, files):
+  # for each user, check if they have files available
+  # return user name list
+  total_list = []
+  name_list = []
+  get_sub = False
+  for path, subdir, dir_files in os.walk(file_dir):
+    #      print path
+    if not get_sub:
+      total_list = subdir[:]
+      get_sub = True
+    else:
+      break
+  for user in total_list:
+    # print user
+    has_file = True
+    for file in files:
+      #  print file
+      file_path = file_dir + user + "/" + file + ".txt"
+#	  print file_path
+      if not os.path.exists(file_path):
+        has_file = False
+        break
+    if has_file:
+      name_list.append(user)
+   # print name_list
+  if len(name_list) == 0:
+    print >> ERROR_LOG, "********Error: Cannot find any user who completes the files*************"
+  return name_list
+"""
+Compute the smatch scores for a file list between two users
+Args:
+   user1: user 1 name
+   user2: user 2 name
+   file_list: file list
+   dir_pre: the file location prefix
+   start_num: the number of restarts in smatch
+Returns:
+   smatch f score.
+"""
+
+
+def compute_files(user1, user2, file_list, dir_pre, start_num):
+   # print file_list
+   # print user1, user2
+  match_total = 0
+  test_total = 0
+  gold_total = 0
+  for fi in file_list:
+    file1 = dir_pre + user1 + "/" + fi + ".txt"
+    file2 = dir_pre + user2 + "/" + fi + ".txt"
+    # print file1,file2
+    if not os.path.exists(file1):
+      print >> ERROR_LOG, "*********Error: ", file1, "does not exist*********"
+      return -1.00
+    if not os.path.exists(file2):
+      print >> ERROR_LOG, "*********Error: ", file2, "does not exist*********"
+      return -1.00
+    try:
+      file1_h = open(file1, "r")
+      file2_h = open(file2, "r")
+    except:
+      print >> ERROR_LOG, "Cannot open the files", file1, file2
+    cur_amr1 = smatch.get_amr_line(file1_h)
+    cur_amr2 = smatch.get_amr_line(file2_h)
+    if(cur_amr1 == ""):
+      print >> ERROR_LOG, "AMR 1 is empty"
+      continue
+    if(cur_amr2 == ""):
+      print >> ERROR_LOG, "AMR 2 is empty"
+      continue
+    amr1 = amr.AMR.parse_AMR_line(cur_amr1)
+    amr2 = amr.AMR.parse_AMR_line(cur_amr2)
+    test_label = "a"
+    gold_label = "b"
+    amr1.rename_node(test_label)
+    amr2.rename_node(gold_label)
+    (test_inst, test_rel1, test_rel2) = amr1.get_triples2()
+    (gold_inst, gold_rel1, gold_rel2) = amr2.get_triples2()
+    if verbose:
+      print >> ERROR_LOG, "Instance triples of file 1:", len(test_inst)
+      print >> ERROR_LOG, test_inst
+      print >> sys.stderr, "Relation triples of file 1:", len(
+          test_rel1) + len(test_rel2)
+      print >>sys.stderr, test_rel1
+      print >> sys.stderr, test_rel2
+      print >> ERROR_LOG, "Instance triples of file 2:", len(gold_inst)
+      print >> ERROR_LOG, gold_inst
+      print >> sys.stderr, "Relation triples of file 2:", len(
+          gold_rel1) + len(gold_rel2)
+      print >> sys.stderr, gold_rel1
+      print >> sys.stderr, gold_rel2
+    if len(test_inst) < len(gold_inst):
+      (best_match,
+       best_match_num) = smatch.get_fh(test_inst,
+                                       test_rel1,
+                                       test_rel2,
+                                       gold_inst,
+                                       gold_rel1,
+                                       gold_rel2,
+                                       test_label,
+                                       gold_label)
+      if verbose:
+        print >> ERROR_LOG, "best match number", best_match_num
+        print >>ERROR_LOG, "Best Match:", smatch.print_alignment(
+            best_match, test_inst, gold_inst)
+    else:
+      (best_match,
+       best_match_num) = smatch.get_fh(gold_inst,
+                                       gold_rel1,
+                                       gold_rel2,
+                                       test_inst,
+                                       test_rel1,
+                                       test_rel2,
+                                       gold_label,
+                                       test_label)
+      if verbose:
+        print >> ERROR_LOG, "best match number", best_match_num
+        print >>ERROR_LOG, "Best Match:", smatch.print_alignment(
+            best_match, gold_inst, test_inst, True)
+    #(match_num,test_num,gold_num)=smatch.get_match(tmp_filename1,tmp_filename2,start_num)
+    # print match_num,test_num,gold_num
+  # print best_match_num
+  # print len(test_inst)+len(test_rel1)+len(test_rel2)
+  # print len(gold_inst)+len(gold_rel1)+len(gold_rel2)
+    match_total += best_match_num
+    test_total += len(test_inst) + len(test_rel1) + len(test_rel2)
+    gold_total += len(gold_inst) + len(gold_rel1) + len(gold_rel2)
+    smatch.match_num_dict.clear()
+  (precision, recall, f_score) = smatch.compute_f(
+      match_total, test_total, gold_total)
+  return "%.2f" % f_score
+
+
+def get_max_width(table, index):
+  return max([len(str(row[index])) for row in table])
+"""
+Print a table
+"""
+
+
+def pprint_table(table):
+  col_paddings = []
+  for i in range(len(table[0])):
+    col_paddings.append(get_max_width(table, i))
+  for row in table:
+    print row[0].ljust(col_paddings[0] + 1),
+    for i in range(1, len(row)):
+      col = str(row[i]).rjust(col_paddings[i] + 2)
+      print col,
+    print "\n"
+
+
+def print_help():
+  print "Smatch Calculator Program Help"
+  print "This program prints the smatch score of the two files"
+  print "Command line arguments:"
+  print "-h: Show help (Other options won't work if you use -h)"
+  print "smatch-table.py -h"
+  print "Usage: smatch-table.py file_list (-f list_file) [ -p user_list ] [-r number of starts]"
+  print "File list is AMR file ids separated by a blank space"
+  print "Example: smatch-table.py nw_wsj_0001_1 nw_wsj_0001_2"
+  print "Or use -f list_file to indicate a file which contains one line of file names, separated by a blank space"
+  print "Example: smatch.py -f file"
+  print "-p: (Optional) user list to list the user name in the command line, after the file list. Otherwise the program automatically searches for the users who completes all AMRs you want."
+  print "Example: smatch.py -f file -p user1 user2"
+  print "Example: smatch.py nw_wsj_0001_1 nw_wsj_0001_2 -p user1 user2"
+  print "-r: (Optional) the number of random starts(higher number may results in higher accuracy and slower speed (default number of starts: 10)"
+  print "Example: smatch.py -f file -p user1 user2 -r 20"
+ # print "-d: detailed output, including alignment and triples of the two files"
+ # print "Example (if you want to use all options): smatch.py file1 file2
+ # -d -r 20"
+  print "Contact shucai@isi.edu for additional help"
+
+
+def build_arg_parser():
+  """Build an argument parser using argparse"""
+  parser = argparse.ArgumentParser(
+      description="Smatch table calculator -- arguments")
+  parser.add_argument(
+      "--fl",
+      type=argparse.FileType('r'),
+      help='AMR ID list file')
+  parser.add_argument('-f', nargs='+', help='AMR IDs (at least one)')
+  parser.add_argument("-p", nargs='*', help="User list (can be none)")
+  parser.add_argument(
+      "--fd",
+      default=isi_dir_pre,
+      help="AMR File directory. Default=location on isi machine")
+  #parser.add_argument("--cd",default=os.getcwd(),help="(Dependent) code directory. Default: current directory")
+  parser.add_argument(
+      '-r',
+      type=int,
+      default=4,
+      help='Restart number (Default:4)')
+  parser.add_argument(
+      '-v',
+      action='store_true',
+      help='Verbose output (Default:False)')
+  return parser
+"""
+Callback function to handle variable number of arguments in optparse
+"""
+
+
+def cb(option, opt_str, value, parser):
+  args = []
+  args.append(value)
+  for arg in parser.rargs:
+    if arg[0] != "-":
+      args.append(arg)
+    else:
+      del parser.rargs[:len(args)]
+      break
+  if getattr(parser.values, option.dest):
+    args.extend(getattr(parser.values, option.dest))
+  setattr(parser.values, option.dest, args)
+
+
+def build_arg_parser2():
+  """Build an argument parser using optparse"""
+  usage_str = "Smatch table calculator -- arguments"
+  parser = optparse.OptionParser(usage=usage_str)
+  parser.add_option("--fl", dest="fl", type="string", help='AMR ID list file')
+  parser.add_option(
+      "-f",
+      dest="f",
+      type="string",
+      action="callback",
+      callback=cb,
+      help="AMR IDs (at least one)")
+  parser.add_option(
+      "-p",
+      dest="p",
+      type="string",
+      action="callback",
+      callback=cb,
+      help="User list")
+  parser.add_option("--fd", dest="fd", type="string", help="file directory")
+  #parser.add_option("--cd",dest="cd",type="string",help="code directory")
+  parser.add_option(
+      "-r",
+      "--restart",
+      dest="r",
+      type="int",
+      help='Restart number (Default: 4)')
+  parser.add_option(
+      "-v",
+      "--verbose",
+      action='store_true',
+      dest="v",
+      help='Verbose output (Default:False)')
+  parser.set_defaults(r=4, v=False, ms=False, fd=isi_dir_pre)
+  return parser
+
+
+def check_args(args):
+  """Check if the arguments are valid"""
+  if not os.path.exists(args.fd):
+    print >> ERROR_LOG, "Not a valid path", args.fd
+    return ([], [], False)
+  # if not os.path.exists(args.cd):
+  #  print >> ERROR_LOG,"Not a valid path", args.cd
+  #  return ([],[],False)
+  amr_ids = []
+  if args.fl is not None:
+    # we already ensure the file can be opened and opened the file
+    file_line = args.fl.readline()
+    amr_ids = file_line.strip().split()
+  elif args.f is None:
+    print >> ERROR_LOG, "No AMR ID was given"
+    return ([], [], False)
+  else:
+    amr_ids = args.f
+  names = []
+  check_name = True
+  if args.p is None:
+    names = get_names(args.fd, amr_ids)
+    check_name = False  # no need to check names
+    if len(names) == 0:
+      print >> ERROR_LOG, "Cannot find any user who tagged these AMR"
+      return ([], [], False)
+  else:
+    names = args.p
+  if names == []:
+    print >> ERROR_LOG, "No user was given"
+    return ([], [], False)
+  if len(names) == 1:
+    print >> ERROR_LOG, "Only one user is given. Smatch calculation requires at least two users."
+    return ([], [], False)
+  if "consensus" in names:
+    con_index = names.index("consensus")
+    names.pop(con_index)
+    names.append("consensus")
+  # check if all the AMR_id and user combinations are valid
+  if check_name:
+    pop_name = []
+    for i, name in enumerate(names):
+      for amr in amr_ids:
+        amr_path = args.fd + name + "/" + amr + ".txt"
+        if not os.path.exists(amr_path):
+          print >> ERROR_LOG, "User", name, "fails to tag AMR", amr
+          pop_name.append(i)
+          break
+    if len(pop_name) != 0:
+      pop_num = 0
+      for p in pop_name:
+        print >> ERROR_LOG, "Deleting user", names[
+            p - pop_num], "from the name list"
+        names.pop(p - pop_num)
+        pop_num += 1
+    if len(names) < 2:
+      print >> ERROR_LOG, "Not enough users to evaluate. Smatch requires >2 users who tag all the AMRs"
+      return ("", "", False)
+  return (amr_ids, names, True)
+
+
+def main(args):
+  """Main Function"""
+  (ids, names, result) = check_args(args)
+  if args.v:
+    verbose = True
+  if not result:
+    return 0
+  acc_time = 0
+  len_name = len(names)
+  table = []
+  for i in range(0, len_name + 1):
+    table.append([])
+  table[0].append("")
+  for i in range(0, len_name):
+    table[0].append(names[i])
+  for i in range(0, len_name):
+    table[i + 1].append(names[i])
+    for j in range(0, len_name):
+      if i != j:
+        start = time.clock()
+        table[
+            i +
+            1].append(
+            compute_files(
+                names[i],
+                names[j],
+                ids,
+                args.fd,
+                args.r))
+        end = time.clock()
+        if table[i + 1][-1] != -1.0:
+          acc_time += end - start
+        # if table[i+1][-1]==-1.0:
+        #   sys.exit(1)
+      else:
+        table[i + 1].append("")
+  # check table
+  for i in range(0, len_name + 1):
+    for j in range(0, len_name + 1):
+      if i != j:
+        if table[i][j] != table[j][i]:
+          if table[i][j] > table[j][i]:
+            table[j][i] = table[i][j]
+          else:
+            table[i][j] = table[j][i]
+  pprint_table(table)
+  return acc_time
+
+
+if __name__ == "__main__":
+  # acc_time=0 #accumulated time
+  whole_start = time.clock()
+  parser = None
+  args = None
+  if sys.version_info[:2] != (2, 7):
+    # requires version >=2.3!
+    if sys.version_info[0] != 2 or sys.version_info[1] < 5:
+      print >> ERROR_LOG, "This prgram requires python 2.5 or later to run. "
+      exit(1)
+    import optparse
+    parser = build_arg_parser2()
+    (args, opts) = parser.parse_args()
+    file_handle = None
+    if args.fl is not None:
+      try:
+        file_handle = open(args.fl, "r")
+        args.fl = file_handle
+      except:
+        print >> ERROR_LOG, "The ID list file", args.fl, "does not exist"
+        args.fl = None
+#      print args
+  else:  # version 2.7
+    import argparse
+    parser = build_arg_parser()
+    args = parser.parse_args()
+  # Regularize fd and cd representation
+  if args.fd[-1] != "/":
+    args.fd = args.fd + "/"
+  # if args.cd[-1]!="/":
+  #   args.cd=args.cd+"/"
+  acc_time = main(args)
+  whole_end = time.clock()
+  whole_time = whole_end - whole_start
+#   print >> ERROR_LOG, "Accumulated time", acc_time
+#   print >> ERROR_LOG, "whole time", whole_time
+#   print >> ERROR_LOG, "Percentage", float(acc_time)/float(whole_time)
diff --git a/amrbatch/amrld/smatch/smatch.py b/amrbatch/amrld/smatch/smatch.py
new file mode 100755
index 00000000..ce654023
--- /dev/null
+++ b/amrbatch/amrld/smatch/smatch.py
@@ -0,0 +1,863 @@
+#!/usr/bin/env python
+# encoding: utf-8
+"""
+smatch.py
+
+Author: Shu Cai
+Copyright(c) 2012. All rights reserved.
+
+This file is from the code for smatch, available at:
+
+http://amr.isi.edu/download/smatch-v1.0.tar.gz
+http://amr.isi.edu/smatch-13.pdf
+"""
+import codecs
+import sys
+import os
+import time
+import random
+import amr
+#import optparse
+# import argparse #argparse only works for python 2.7. If you are using
+# older versin of Python, you can use optparse instead.
+
+verbose = False  # global variable, verbose output control
+
+single_score = True  # global variable, single score output control
+
+pr_flag = False  # global variable, output precision and recall
+
+ERROR_LOG = sys.stderr
+
+match_num_dict = {}  # key: match number tuples	value: the matching number
+
+
+def get_amr_line(input_f):
+  """Read the amr file. AMRs are separated by a blank line."""
+  cur_amr = []
+  has_content = False
+  for line in input_f:
+    if line[0] == "(" and len(cur_amr) != 0:
+      cur_amr = []
+    if line.strip() == "":
+      if not has_content:
+        continue
+      else:
+        break
+    elif line.strip().startswith("#"):
+      # omit the comment in the AMR file
+      continue
+    else:
+      has_content = True
+      cur_amr.append(line.strip())
+  return "".join(cur_amr)
+
+
+def build_arg_parser():
+  """Build an argument parser using argparse"""
+  parser = argparse.ArgumentParser(
+      description="Smatch calculator -- arguments")
+  parser.add_argument(
+      '-f',
+      nargs=2,
+      required=True,
+      type=argparse.FileType('r'),
+      help='Two files containing AMR pairs. AMRs in each file are separated by a single blank line')
+  parser.add_argument(
+      '-r',
+      type=int,
+      default=4,
+      help='Restart number (Default:4)')
+  parser.add_argument(
+      '-v',
+      action='store_true',
+      help='Verbose output (Default:False)')
+  parser.add_argument(
+      '--ms',
+      action='store_true',
+      default=False,
+      help='Output multiple scores (one AMR pair a score) instead of a single document-level smatch score (Default: False)')
+  parser.add_argument(
+      '--pr',
+      action='store_true',
+      default=False,
+      help="Output precision and recall as well as the f-score. Default: false")
+  return parser
+
+
+def build_arg_parser2():
+  """Build an argument parser using optparse"""
+  usage_str = "Smatch calculator -- arguments"
+  parser = optparse.OptionParser(usage=usage_str)
+  #parser.add_option("-h","--help",action="help",help="Smatch calculator -- arguments")
+  parser.add_option(
+      "-f",
+      "--files",
+      nargs=2,
+      dest="f",
+      type="string",
+      help='Two files containing AMR pairs. AMRs in each file are separated by a single blank line. This option is required.')
+  parser.add_option(
+      "-r",
+      "--restart",
+      dest="r",
+      type="int",
+      help='Restart number (Default: 4)')
+  parser.add_option(
+      "-v",
+      "--verbose",
+      action='store_true',
+      dest="v",
+      help='Verbose output (Default:False)')
+  parser.add_option(
+      "--ms",
+      "--multiple_score",
+      action='store_true',
+      dest="ms",
+      help='Output multiple scores (one AMR pair a score) instead of a single document-level smatch score (Default: False)')
+  parser.add_option(
+      '--pr',
+      "--precision_recall",
+      action='store_true',
+      dest="pr",
+      help="Output precision and recall as well as the f-score. Default: false")
+  parser.set_defaults(r=4, v=False, ms=False, pr=False)
+  return parser
+
+
+def dflt_label_weighter(test_label, gold_label):
+  """
+  Return score corresponding to the weight to add for matching
+  test_label and gold_label in the default Smatch setting.
+  """
+  if test_label.lower() == gold_label.lower():
+    return 1.0
+  else:
+    return 0.0
+
+
+def compute_pool(test_instance, test_relation1, test_relation2,
+    gold_instance, gold_relation1, gold_relation2,
+    test_label, gold_label,
+    node_weight_fn, edge_weight_fn):
+  """
+  compute the possible variable matching candidate (the match which may result in 1)
+  Args:
+    test_instance: instance triples in AMR 1
+    test_relation1: relation triples which contain only one variable in AMR 1
+    test_relation2: relation triples which contain two variables in AMR 1
+    gold_instance: instance triples in AMR 2
+    gold_relation1: relation triples which contain only one variable in AMR 2
+    gold_relations: relation triples which contain two variables in AMR 2
+    test_label: the prefix of the variable in AMR 1, e.g. a (variable a1, a2, a3...)
+    gold_label: the prefix of the variable in AMR 2, e.g. b (variable b1, b2, b3...)
+  Returns:
+    candidate_match: a list of candidate mapping variables. Each entry contains a set of the variables the variable can map to.
+    weight_dict: a dictionary which contains the matching triple number of every pair of variable mapping. """
+  len_test_inst = len(test_instance)
+  len_gold_inst = len(gold_instance)
+  len_test_rel1 = len(test_relation1)
+  len_gold_rel1 = len(gold_relation1)
+  len_test_rel2 = len(test_relation2)
+  len_gold_rel2 = len(gold_relation2)
+  candidate_match = []
+  weight_dict = {}
+  for i in range(0, len_test_inst):
+    candidate_match.append(set())
+  for i in range(0, len_test_inst):
+    for j in range(0, len_gold_inst):
+      if test_instance[i][0].lower() == gold_instance[j][0].lower():
+        w = node_weight_fn(test_instance[i][2], gold_instance[j][2])
+        var1_num = int(test_instance[i][1][len(test_label):])
+        var2_num = int(gold_instance[j][1][len(gold_label):])
+        candidate_match[var1_num].add(var2_num)
+        cur_k = (var1_num, var2_num)
+        if cur_k in weight_dict:
+          weight_dict[cur_k][-1] += w
+        else:
+          weight_dict[cur_k] = {}
+          weight_dict[cur_k][-1] = w
+  for i in range(0, len_test_rel1):
+    for j in range(0, len_gold_rel1):
+      if test_relation1[i][0].lower() == gold_relation1[j][0].lower():
+        w = node_weight_fn(test_relation1[i][2], gold_relation1[j][2])
+        var1_num = int(test_relation1[i][1][len(test_label):])
+        var2_num = int(gold_relation1[j][1][len(gold_label):])
+        candidate_match[var1_num].add(var2_num)
+        cur_k = (var1_num, var2_num)
+        if cur_k in weight_dict:
+          weight_dict[cur_k][-1] += w
+        else:
+          weight_dict[cur_k] = {}
+          weight_dict[cur_k][-1] = w
+
+  for i in range(0, len_test_rel2):
+    for j in range(0, len_gold_rel2):
+      w = edge_weight_fn(test_relation2[i][0], gold_relation2[j][0])
+      if w > 0:
+        var1_num_test = int(test_relation2[i][1][len(test_label):])
+        var1_num_gold = int(gold_relation2[j][1][len(gold_label):])
+        var2_num_test = int(test_relation2[i][2][len(test_label):])
+        var2_num_gold = int(gold_relation2[j][2][len(gold_label):])
+        candidate_match[var1_num_test].add(var1_num_gold)
+        candidate_match[var2_num_test].add(var2_num_gold)
+        cur_k1 = (var1_num_test, var1_num_gold)
+        cur_k2 = (var2_num_test, var2_num_gold)
+        if cur_k2 != cur_k1:
+          if cur_k1 in weight_dict:
+            if cur_k2 in weight_dict[cur_k1]:
+              weight_dict[cur_k1][cur_k2] += w
+            else:
+              weight_dict[cur_k1][cur_k2] = w
+          else:
+            weight_dict[cur_k1] = {}
+            weight_dict[cur_k1][-1] = 0
+            weight_dict[cur_k1][cur_k2] = w
+          if cur_k2 in weight_dict:
+            if cur_k1 in weight_dict[cur_k2]:
+              weight_dict[cur_k2][cur_k1] += w
+            else:
+              weight_dict[cur_k2][cur_k1] = w
+          else:
+            weight_dict[cur_k2] = {}
+            weight_dict[cur_k2][-1] = 0
+            weight_dict[cur_k2][cur_k1] = w
+        else:
+          # cycle
+          if cur_k1 in weight_dict:
+            weight_dict[cur_k1][-1] += w
+          else:
+            weight_dict[cur_k1] = {}
+            weight_dict[cur_k1][-1] = w
+  return (candidate_match, weight_dict)
+
+
+def init_match(candidate_match, test_instance, gold_instance, node_weight_fn):
+  """Initialize match based on the word match
+     Args:
+         candidate_match: candidate variable match list
+         test_instance: test instance
+         gold_instance: gold instance
+      Returns:
+         intialized match result"""
+  random.seed()
+  matched_dict = {}
+
+  num_test_matched = 0
+  matches_by_weight = []
+  result = [-1 for c in candidate_match]
+  for i, c in enumerate(candidate_match):
+    c2 = list(c)
+    if len(c2) == 0:
+      num_test_matched += 1
+      continue
+    # word in the test instance
+    test_word = test_instance[i][2]
+    for j, m_id in enumerate(c2):
+      gold_word = gold_instance[int(m_id)][2]
+      curr_score = node_weight_fn(gold_word, test_word)
+      matches_by_weight.append((int(m_id), i, curr_score))
+
+  matches_by_weight = sorted(matches_by_weight, key=lambda (x1,x2,x3) : x3, reverse=True)
+  for (gold, test, score) in matches_by_weight:
+    if len(matched_dict) == len(gold_instance) \
+        or num_test_matched == len(test_instance):
+      break
+    if result[test] != -1 or gold in matched_dict:
+      continue
+    result[test] = gold
+    matched_dict[gold] = 1
+    num_test_matched += 1
+
+  for (i, m) in enumerate(result):
+    if m != -1:
+      continue
+    c2 = list(candidate_match[i])
+    found = False
+    while len(c2) != 1:
+      rid = random.randint(0, len(c2) - 1)
+      if c2[rid] in matched_dict:
+        c2.pop(rid)
+      else:
+        matched_dict[c2[rid]] = 1
+        result[i] = c2[rid]
+        found = True
+        break
+    if not found:
+      if c2[0] not in matched_dict:
+        result[i] = c2[0]
+        matched_dict[c2[0]] = 1
+  return result
+
+
+def get_random_sol(candidate):
+  """
+  Generate a random variable mapping.
+  Args:
+      candidate:a list of set and each set contains the candidate match of a test instance
+  """
+  random.seed()
+  matched_dict = {}
+  result = []
+  for c in candidate:
+    c2 = list(c)
+    found = False
+    if len(c2) == 0:
+      result.append(-1)
+      continue
+    while len(c2) != 1:
+      rid = random.randint(0, len(c2) - 1)
+      if c2[rid] in matched_dict:
+        c2.pop(rid)
+      else:
+        matched_dict[c2[rid]] = 1
+        result.append(c2[rid])
+        found = True
+        break
+    if not found:
+      if c2[0] not in matched_dict:
+        result.append(c2[0])
+        matched_dict[c2[0]] = 1
+      else:
+        result.append(-1)
+  return result
+
+
+def compute_match(match, weight_dict):
+  """Given a variable match, compute match number based on weight_dict.
+     Args:
+         match: a list of number in gold set, len(match)= number of test instance
+     Returns:
+         matching triple number
+     Complexity: O(m*n) , m is the length of test instance, n is the length of gold instance"""
+  # remember matching number of the previous matching we investigated
+  if tuple(match) in match_num_dict:
+    return match_num_dict[tuple(match)]
+  match_num = 0
+  for i, m in enumerate(match):
+    if m == -1:
+      continue
+    cur_m = (i, m)
+    if cur_m not in weight_dict:
+      continue
+    match_num += weight_dict[cur_m][-1]
+    for k in weight_dict[cur_m]:
+      if k == -1:
+        continue
+      if k[0] < i:
+        continue
+      elif match[k[0]] == k[1]:
+        match_num += weight_dict[cur_m][k]
+  match_num_dict[tuple(match)] = match_num
+  return match_num
+
+
+def move_gain(match, i, m, nm, weight_dict, match_num):
+  """Compute the triple match number gain by the move operation
+     Args:
+         match: current match list
+         i: the remapped source variable
+         m: the original id
+         nm: new mapped id
+         weight_dict: weight dictionary
+         match_num: the original matching number
+      Returns:
+         the gain number (might be negative)"""
+  cur_m = (i, nm)
+  old_m = (i, m)
+  new_match = match[:]
+  new_match[i] = nm
+  if tuple(new_match) in match_num_dict:
+    return match_num_dict[tuple(new_match)] - match_num
+  gain = 0
+  if cur_m in weight_dict:
+    gain += weight_dict[cur_m][-1]
+    for k in weight_dict[cur_m]:
+      if k == -1:
+        continue
+      elif match[k[0]] == k[1]:
+        gain += weight_dict[cur_m][k]
+  if old_m in weight_dict:
+    gain -= weight_dict[old_m][-1]
+    for k in weight_dict[old_m]:
+      if k == -1:
+        continue
+      elif match[k[0]] == k[1]:
+        gain -= weight_dict[old_m][k]
+  match_num_dict[tuple(new_match)] = match_num + gain
+  return gain
+
+
+def swap_gain(match, i, m, j, m2, weight_dict, match_num):
+  """Compute the triple match number gain by the swap operation
+     Args:
+         match: current match list
+         i: the position 1
+         m: the original mapped variable of i
+         j: the position 2
+         m2: the original mapped variable of j
+         weight_dict: weight dictionary
+         match_num: the original matching number
+      Returns:
+         the gain number (might be negative)"""
+  new_match = match[:]
+  new_match[i] = m2
+  new_match[j] = m
+  gain = 0
+  cur_m = (i, m2)
+  cur_m2 = (j, m)
+  old_m = (i, m)
+  old_m2 = (j, m2)
+  if cur_m in weight_dict:
+    gain += weight_dict[cur_m][-1]
+    if cur_m2 in weight_dict[cur_m]:
+      gain += weight_dict[cur_m][cur_m2]
+    for k in weight_dict[cur_m]:
+      if k == -1:
+        continue
+      elif k[0] == j:
+        continue
+      elif match[k[0]] == k[1]:
+        gain += weight_dict[cur_m][k]
+  if cur_m2 in weight_dict:
+    gain += weight_dict[cur_m2][-1]
+    for k in weight_dict[cur_m2]:
+      if k == -1:
+        continue
+      elif k[0] == i:
+        continue
+      elif match[k[0]] == k[1]:
+        gain += weight_dict[cur_m2][k]
+  if old_m in weight_dict:
+    gain -= weight_dict[old_m][-1]
+    if old_m2 in weight_dict[old_m]:
+      gain -= weight_dict[old_m][old_m2]
+    for k in weight_dict[old_m]:
+      if k == -1:
+        continue
+      elif k[0] == j:
+        continue
+      elif match[k[0]] == k[1]:
+        gain -= weight_dict[old_m][k]
+  if old_m2 in weight_dict:
+    gain -= weight_dict[old_m2][-1]
+    for k in weight_dict[old_m2]:
+      if k == -1:
+        continue
+      elif k[0] == i:
+        continue
+      elif match[k[0]] == k[1]:
+        gain -= weight_dict[old_m2][k]
+  match_num_dict[tuple(new_match)] = match_num + gain
+  return gain
+
+
+def get_best_gain(
+    match,
+    candidate_match,
+    weight_dict,
+    gold_len,
+        start_match_num):
+  """ hill-climbing method to return the best gain swap/move can get
+    Args:
+        match: the initial variable mapping
+        candidate_match: the match candidates list
+        weight_dict: the weight dictionary
+        gold_len: the number of the variables in file 2
+        start_match_num: the initial match number
+    Returns:
+        the best gain we can get via swap/move operation"""
+  largest_gain = 0
+  largest_match_num = 0
+  swap = True  # True: using swap False: using move
+  change_list = []
+  # unmatched gold number
+  unmatched_gold = set(range(0, gold_len))
+  # O(gold_len)
+  for m in match:
+    if m in unmatched_gold:
+      unmatched_gold.remove(m)
+  unmatch_list = list(unmatched_gold)
+  for i, m in enumerate(match):
+    # remap i
+    for nm in unmatch_list:
+      if nm in candidate_match[i]:
+        #(i,m) -> (i,nm)
+        gain = move_gain(match, i, m, nm, weight_dict, start_match_num)
+        if verbose:
+          new_match = match[:]
+          new_match[i] = nm
+          new_m_num = compute_match(new_match, weight_dict)
+          if new_m_num != start_match_num + gain:
+            print >> sys.stderr, match, new_match
+            print >> sys.stderr, "Inconsistency in computing: move gain", start_match_num, gain, new_m_num
+        if gain > largest_gain:
+          largest_gain = gain
+          change_list = [i, nm]
+          swap = False
+          largest_match_num = start_match_num + gain
+  for i, m in enumerate(match):
+    for j, m2 in enumerate(match):
+      # swap i
+      if i == j:
+        continue
+      new_match = match[:]
+      new_match[i] = m2
+      new_match[j] = m
+      sw_gain = swap_gain(match, i, m, j, m2, weight_dict, start_match_num)
+      if verbose:
+        new_match = match[:]
+        new_match[i] = m2
+        new_match[j] = m
+        new_m_num = compute_match(new_match, weight_dict)
+        if new_m_num != start_match_num + sw_gain:
+          print >> sys.stderr, match, new_match
+          print >> sys.stderr, "Inconsistency in computing: swap gain", start_match_num, sw_gain, new_m_num
+      if sw_gain > largest_gain:
+        largest_gain = sw_gain
+        change_list = [i, j]
+        swap = True
+  cur_match = match[:]
+  largest_match_num = start_match_num + largest_gain
+  if change_list != []:
+    if swap:
+      temp = cur_match[change_list[0]]
+      cur_match[change_list[0]] = cur_match[change_list[1]]
+      cur_match[change_list[1]] = temp
+      # print >> sys.stderr,"swap gain"
+    else:
+      cur_match[change_list[0]] = change_list[1]
+      # print >> sys.stderr,"move gain"
+  return (largest_match_num, cur_match)
+
+
+def get_fh(test_instance, test_relation1, test_relation2,
+    gold_instance, gold_relation1, gold_relation2,
+    test_label, gold_label,
+    node_weight_fn=dflt_label_weighter, edge_weight_fn=dflt_label_weighter,
+    iter_num=5):
+  """Get the f-score given two sets of triples
+     Args:
+         iter_num: iteration number of heuristic search
+         test_instance: instance triples of AMR 1
+         test_relation1: relation triples of AMR 1 (one-variable)
+         test_relation2: relation triples of AMR 2 (two-variable)
+         gold_instance: instance triples of AMR 2
+         gold_relation1: relation triples of AMR 2 (one-variable)
+         gold_relation2: relation triples of AMR 2 (two-variable)
+         test_label: prefix label for AMRe 1
+         gold_label: prefix label for AMR 2
+      Returns:
+         best_match: the variable mapping which results in the best matching triple number
+         best_match_num: the highest matching number
+        """
+  # compute candidate pool
+  (candidate_match,
+   weight_dict) = compute_pool(test_instance, test_relation1, test_relation2,
+                               gold_instance, gold_relation1, gold_relation2,
+                               test_label, gold_label,
+                               node_weight_fn, edge_weight_fn)
+  best_match_num = 0
+  best_match = [-1] * len(test_instance)
+
+  # best lexical match
+  if iter_num == 0:
+    start_match = init_match(
+        candidate_match,
+        test_instance,
+        gold_instance,
+        node_weight_fn)
+    return(start_match, compute_match(start_match, weight_dict))
+
+  for i in range(0, iter_num):
+    if verbose:
+      print >> sys.stderr, "Iteration", i
+    if i == 0:
+      # smart initialization
+      start_match = init_match(
+          candidate_match,
+          test_instance,
+          gold_instance,
+          node_weight_fn)
+    else:
+      # random initialization
+      start_match = get_random_sol(candidate_match)
+    # first match_num, and store the match in memory
+    match_num = compute_match(start_match, weight_dict)
+   # match_num_dict[tuple(start_match)]=match_num
+    if verbose:
+      print >> sys.stderr, "starting point match num:", match_num
+      print >> sys.stderr, "start match", start_match
+    # hill-climbing
+    (largest_match_num,
+     cur_match) = get_best_gain(start_match,
+                                candidate_match,
+                                weight_dict,
+                                len(gold_instance),
+                                match_num)
+    if verbose:
+      print >> sys.stderr, "Largest match number after the hill-climbing", largest_match_num
+   # match_num=largest_match_num
+    # hill-climbing until there will be no gain if we generate a new variable
+    # mapping
+    while largest_match_num > match_num:
+      match_num = largest_match_num
+      (largest_match_num,
+       cur_match) = get_best_gain(cur_match,
+                                  candidate_match,
+                                  weight_dict,
+                                  len(gold_instance),
+                                  match_num)
+      if verbose:
+        print >> sys.stderr, "Largest match number after the hill-climbing", largest_match_num
+    if match_num > best_match_num:
+      best_match = cur_match[:]
+      best_match_num = match_num
+  return (best_match, best_match_num)
+
+# help of inst_list: record a0 location in the test_instance ...
+
+
+def print_alignment(match, test_instance, gold_instance, flip=False):
+  """ print the alignment based on a match
+  Args:
+      match: current match, denoted by a list
+      test_instance: instances of AMR 1
+      gold_instance: instances of AMR 2
+      filp: filp the test/gold or not"""
+  result = []
+  for i, m in enumerate(match):
+    if m == -1:
+      if not flip:
+        result.append(
+            test_instance[i][1] +
+            "(" +
+            test_instance[i][2] +
+            ")" +
+            "-Null")
+      else:
+        result.append(
+            "Null-" +
+            test_instance[i][1] +
+            "(" +
+            test_instance[i][2] +
+            ")")
+    else:
+      if not flip:
+        result.append(
+            test_instance[i][1] +
+            "(" +
+            test_instance[i][2] +
+            ")" +
+            "-" +
+            gold_instance[m][1] +
+            "(" +
+            gold_instance[m][2] +
+            ")")
+      else:
+        result.append(
+            gold_instance[m][1] +
+            "(" +
+            gold_instance[m][2] +
+            ")" +
+            "-" +
+            test_instance[i][1] +
+            "(" +
+            test_instance[i][2] +
+            ")")
+  return " ".join(result)
+
+
+def compute_f(match_num, test_num, gold_num):
+  """ Compute the f-score based on the matching triple number, triple number of the AMR set 1, triple number of AMR set 2
+      Args:
+         match_num: matching triple number
+         test_num:  triple number of AMR 1
+         gold_num:  triple number of AMR 2
+      Returns:
+         precision: match_num/test_num
+         recall: match_num/gold_num
+         f_score: 2*precision*recall/(precision+recall)"""
+  if test_num == 0 or gold_num == 0:
+    return (0.00, 0.00, 0.00)
+  precision = float(match_num) / float(test_num)
+  recall = float(match_num) / float(gold_num)
+  if (precision + recall) != 0:
+    f_score = 2 * precision * recall / (precision + recall)
+    if verbose:
+      print >> sys.stderr, "F-score:", f_score
+    return (precision, recall, f_score)
+  else:
+    if verbose:
+      print >> sys.stderr, "F-score:", "0.0"
+    return (precision, recall, 0.00)
+
+def main(args):
+  """Main function of the smatch calculation program"""
+  global verbose
+  global iter_num
+  global single_score
+  global pr_flag
+  global match_num_dict
+  # set the restart number
+  iter_num = args.r + 1
+  verbose = False
+  if args.ms:
+    single_score = False
+  if args.v:
+    verbose = True
+  if args.pr:
+    pr_flag = True
+  total_match_num = 0
+  total_test_num = 0
+  total_gold_num = 0
+  sent_num = 1
+  prev_amr1 = ""
+  while True:
+    cur_amr1 = get_amr_line(args.f[0])
+    cur_amr2 = get_amr_line(args.f[1])
+    if cur_amr1 == "" and cur_amr2 == "":
+      break
+    if(cur_amr1 == ""):        
+      # GULLY CHANGED THIS. 
+      # IF WE RUN OUT OF AVAILABLE AMRS FROM FILE 1, 
+      # REUSE THE LAST AVAILABLE AMR
+      cur_amr1 = prev_amr1  
+      #print >> sys.stderr, "Error: File 1 has less AMRs than file 2"
+      #print >> sys.stderr, "Ignoring remaining AMRs"
+      #break
+      # print >> sys.stderr, "AMR 1 is empty"
+      # continue
+    if(cur_amr2 == ""):
+      print >> sys.stderr, "Error: File 2 has less AMRs than file 1"
+      print >> sys.stderr, "Ignoring remaining AMRs"
+      break
+    # print >> sys.stderr, "AMR 2 is empty"
+    # continue
+    prev_amr1 = cur_amr1
+    amr1 = amr.AMR.parse_AMR_line(cur_amr1)
+    amr2 = amr.AMR.parse_AMR_line(cur_amr2)
+    test_label = "a"
+    gold_label = "b"
+    amr1.rename_node(test_label)
+    amr2.rename_node(gold_label)
+    (test_inst, test_rel1, test_rel2) = amr1.get_triples2()
+    (gold_inst, gold_rel1, gold_rel2) = amr2.get_triples2()
+    if verbose:
+      print "AMR pair", sent_num
+      print >> sys.stderr, "Instance triples of AMR 1:", len(test_inst)
+      print >> sys.stderr, test_inst
+  #   print >> sys.stderr,"Relation triples of AMR 1:",len(test_rel)
+      print >> sys.stderr, "Relation triples of AMR 1:", len(
+          test_rel1) + len(test_rel2)
+      print >>sys.stderr, test_rel1
+      print >> sys.stderr, test_rel2
+  #   print >> sys.stderr, test_rel
+      print >> sys.stderr, "Instance triples of AMR 2:", len(gold_inst)
+      print >> sys.stderr, gold_inst
+  #   print >> sys.stderr,"Relation triples of file 2:",len(gold_rel)
+      print >> sys.stderr, "Relation triples of AMR 2:", len(
+          gold_rel1) + len(gold_rel2)
+      #print >> sys.stderr,"Relation triples of file 2:",len(gold_rel1)+len(gold_rel2)
+      print >> sys.stderr, gold_rel1
+      print >> sys.stderr, gold_rel2
+  #    print >> sys.stderr, gold_rel
+    if len(test_inst) < len(gold_inst):
+      (best_match,
+       best_match_num) = get_fh(test_inst,
+                                test_rel1,
+                                test_rel2,
+                                gold_inst,
+                                gold_rel1,
+                                gold_rel2,
+                                test_label,
+                                gold_label)
+      if verbose:
+        print >> sys.stderr, "AMR pair ", sent_num
+        print >> sys.stderr, "best match number", best_match_num
+        print >> sys.stderr, "best match", best_match
+        print >>sys.stderr, "Best Match:", print_alignment(
+            best_match, test_inst, gold_inst)
+    else:
+      (best_match,
+       best_match_num) = get_fh(gold_inst,
+                                gold_rel1,
+                                gold_rel2,
+                                test_inst,
+                                test_rel1,
+                                test_rel2,
+                                gold_label,
+                                test_label)
+      if verbose:
+        print >> sys.stderr, "Sent ", sent_num
+        print >> sys.stderr, "best match number", best_match_num
+        print >> sys.stderr, "best match", best_match
+        print >>sys.stderr, "Best Match:", print_alignment(
+            best_match, gold_inst, test_inst, True)
+    if not single_score:
+      (precision,
+       recall,
+       best_f_score) = compute_f(best_match_num,
+                                 len(test_rel1) + len(test_inst) + len(test_rel2),
+                                 len(gold_rel1) + len(gold_inst) + len(gold_rel2))
+      print str(sent_num)
+      if pr_flag:
+        print "Precision: %.2f" % precision
+        print "Recall: %.2f" % recall
+      print "%.2f" % best_f_score
+    total_match_num += best_match_num
+    total_test_num += len(test_rel1) + len(test_rel2) + len(test_inst)
+    total_gold_num += len(gold_rel1) + len(gold_rel2) + len(gold_inst)
+    match_num_dict.clear()
+    sent_num += 1  # print "F-score:",best_f_score
+  if verbose:
+    print >> sys.stderr, "Total match num"
+    print >> sys.stderr, total_match_num, total_test_num, total_gold_num
+  if single_score:
+    (precision, recall, best_f_score) = compute_f(
+        total_match_num, total_test_num, total_gold_num)
+    if pr_flag:
+      print "Precision: %.2f" % precision
+      print "Recall: %.2f" % recall
+    print "Document F-score: %.2f" % best_f_score
+  args.f[0].close()
+  args.f[1].close()
+
+if __name__ == "__main__":
+  parser = None
+  args = None
+  if sys.version_info[:2] != (2, 7):
+    if sys.version_info[0] != 2 or sys.version_info[1] < 5:
+      print >> ERROR_LOG, "Smatch only supports python 2.5 or later"
+      exit(1)
+    import optparse
+    if len(sys.argv) == 1:
+      print >> ERROR_LOG, "No argument given. Please run smatch.py -h to see the argument descriptions."
+      exit(1)
+    # requires version >=2.3!
+    parser = build_arg_parser2()
+    (args, opts) = parser.parse_args()
+    # handling file errors
+    # if not len(args.f)<2:
+    #   print >> ERROR_LOG,"File number given is less than 2"
+    #   exit(1)
+    file_handle = []
+    if args.f is None:
+      print >> ERROR_LOG, "smatch.py requires -f option to indicate two files containing AMR as input. Please run smatch.py -h to see the argument descriptions."
+      exit(1)
+    if not os.path.exists(args.f[0]):
+      print >> ERROR_LOG, "Given file", args.f[0], "does not exist"
+      exit(1)
+    else:
+      file_handle.append(codecs.open(args.f[0], encoding='utf8'))
+    if not os.path.exists(args.f[1]):
+      print >> ERROR_LOG, "Given file", args.f[1], "does not exist"
+      exit(1)
+    else:
+      file_handle.append(codecs.open(args.f[1], encoding='utf8'))
+    args.f = tuple(file_handle)
+  else:  # version 2.7
+    import argparse
+    parser = build_arg_parser()
+    args = parser.parse_args()
+  main(args)
diff --git a/amrbatch/amrld/smatch/smatch2.py b/amrbatch/amrld/smatch/smatch2.py
new file mode 100644
index 00000000..da933767
--- /dev/null
+++ b/amrbatch/amrld/smatch/smatch2.py
@@ -0,0 +1,887 @@
+#!/usr/bin/env python
+# encoding: utf-8
+"""
+smatch.py
+
+Author: Shu Cai
+Copyright(c) 2012. All rights reserved.
+
+This file is from the code for smatch, available at:
+
+http://amr.isi.edu/download/smatch-v1.0.tar.gz
+http://amr.isi.edu/smatch-13.pdf
+"""
+import codecs
+import sys
+import os
+import time
+import random
+import amr
+#import optparse
+# import argparse #argparse only works for python 2.7. If you are using
+# older versin of Python, you can use optparse instead.
+
+verbose = False  # global variable, verbose output control
+
+single_score = True  # global variable, single score output control
+
+pr_flag = False  # global variable, output precision and recall
+
+ERROR_LOG = sys.stderr
+
+match_num_dict = {}  # key: match number tuples	value: the matching number
+
+
+def get_amr_line(input_f):
+  """Read the amr file. AMRs are separated by a blank line."""
+  cur_amr = []
+  has_content = False
+  for line in input_f:
+    if line[0] == "(" and len(cur_amr) != 0:
+      cur_amr = []
+    if line.strip() == "":
+      if not has_content:
+        continue
+      else:
+        break
+    elif line.strip().startswith("#"):
+      # omit the comment in the AMR file
+      continue
+    else:
+      has_content = True
+      cur_amr.append(line.strip())
+  return "".join(cur_amr)
+
+
+def build_arg_parser():
+  """Build an argument parser using argparse"""
+  parser = argparse.ArgumentParser(
+      description="Smatch calculator -- arguments")
+  parser.add_argument(
+      '-f',
+      nargs=2,
+      required=True,
+      type=argparse.FileType('r'),
+      help='Two files containing AMR pairs. AMRs in each file are separated by a single blank line')
+  parser.add_argument(
+      '-o',
+      '--outfile',
+      help='Output')
+  parser.add_argument(
+      '-r',
+      type=int,
+      default=4,
+      help='Restart number (Default:4)')
+  parser.add_argument(
+      '-v',
+      action='store_true',
+      help='Verbose output (Default:False)')
+  parser.add_argument(
+      '--ms',
+      action='store_true',
+      default=False,
+      help='Output multiple scores (one AMR pair a score) instead of a single document-level smatch score (Default: False)')
+  parser.add_argument(
+      '--pr',
+      action='store_true',
+      default=False,
+      help="Output precision and recall as well as the f-score. Default: false")
+  return parser
+
+
+def build_arg_parser2():
+  """Build an argument parser using optparse"""
+  usage_str = "Smatch calculator -- arguments"
+  parser = optparse.OptionParser(usage=usage_str)
+  #parser.add_option("-h","--help",action="help",help="Smatch calculator -- arguments")
+  parser.add_option(
+      "-f",
+      "--files",
+      nargs=2,
+      dest="f",
+      type="string",
+      help='Two files containing AMR pairs. AMRs in each file are separated by a single blank line. This option is required.')
+  parser.add_option(
+      "-o",
+      "--outfile",
+      nargs=1,
+      dest="o",
+      type="string",
+      help='Output file.')
+  parser.add_option(
+      "-r",
+      "--restart",
+      dest="r",
+      type="int",
+      help='Restart number (Default: 4)')
+  parser.add_option(
+      "-v",
+      "--verbose",
+      action='store_true',
+      dest="v",
+      help='Verbose output (Default:False)')
+  parser.add_option(
+      "--ms",
+      "--multiple_score",
+      action='store_true',
+      dest="ms",
+      help='Output multiple scores (one AMR pair a score) instead of a single document-level smatch score (Default: False)')
+  parser.add_option(
+      '--pr',
+      "--precision_recall",
+      action='store_true',
+      dest="pr",
+      help="Output precision and recall as well as the f-score. Default: false")
+  parser.set_defaults(r=4, v=False, ms=False, pr=False)
+  return parser
+
+
+def dflt_label_weighter(test_label, gold_label):
+  """
+  Return score corresponding to the weight to add for matching
+  test_label and gold_label in the default Smatch setting.
+  """
+  if test_label.lower() == gold_label.lower():
+    return 1.0
+  else:
+    return 0.0
+
+
+def compute_pool(test_instance, test_relation1, test_relation2,
+    gold_instance, gold_relation1, gold_relation2,
+    test_label, gold_label,
+    node_weight_fn, edge_weight_fn):
+  """
+  compute the possible variable matching candidate (the match which may result in 1)
+  Args:
+    test_instance: instance triples in AMR 1
+    test_relation1: relation triples which contain only one variable in AMR 1
+    test_relation2: relation triples which contain two variables in AMR 1
+    gold_instance: instance triples in AMR 2
+    gold_relation1: relation triples which contain only one variable in AMR 2
+    gold_relations: relation triples which contain two variables in AMR 2
+    test_label: the prefix of the variable in AMR 1, e.g. a (variable a1, a2, a3...)
+    gold_label: the prefix of the variable in AMR 2, e.g. b (variable b1, b2, b3...)
+  Returns:
+    candidate_match: a list of candidate mapping variables. Each entry contains a set of the variables the variable can map to.
+    weight_dict: a dictionary which contains the matching triple number of every pair of variable mapping. """
+  len_test_inst = len(test_instance)
+  len_gold_inst = len(gold_instance)
+  len_test_rel1 = len(test_relation1)
+  len_gold_rel1 = len(gold_relation1)
+  len_test_rel2 = len(test_relation2)
+  len_gold_rel2 = len(gold_relation2)
+  candidate_match = []
+  weight_dict = {}
+  for i in range(0, len_test_inst):
+    candidate_match.append(set())
+  for i in range(0, len_test_inst):
+    for j in range(0, len_gold_inst):
+      if test_instance[i][0].lower() == gold_instance[j][0].lower():
+        w = node_weight_fn(test_instance[i][2], gold_instance[j][2])
+        var1_num = int(test_instance[i][1][len(test_label):])
+        var2_num = int(gold_instance[j][1][len(gold_label):])
+        candidate_match[var1_num].add(var2_num)
+        cur_k = (var1_num, var2_num)
+        if cur_k in weight_dict:
+          weight_dict[cur_k][-1] += w
+        else:
+          weight_dict[cur_k] = {}
+          weight_dict[cur_k][-1] = w
+  for i in range(0, len_test_rel1):
+    for j in range(0, len_gold_rel1):
+      if test_relation1[i][0].lower() == gold_relation1[j][0].lower():
+        w = node_weight_fn(test_relation1[i][2], gold_relation1[j][2])
+        var1_num = int(test_relation1[i][1][len(test_label):])
+        var2_num = int(gold_relation1[j][1][len(gold_label):])
+        candidate_match[var1_num].add(var2_num)
+        cur_k = (var1_num, var2_num)
+        if cur_k in weight_dict:
+          weight_dict[cur_k][-1] += w
+        else:
+          weight_dict[cur_k] = {}
+          weight_dict[cur_k][-1] = w
+
+  for i in range(0, len_test_rel2):
+    for j in range(0, len_gold_rel2):
+      w = edge_weight_fn(test_relation2[i][0], gold_relation2[j][0])
+      if w > 0:
+        var1_num_test = int(test_relation2[i][1][len(test_label):])
+        var1_num_gold = int(gold_relation2[j][1][len(gold_label):])
+        var2_num_test = int(test_relation2[i][2][len(test_label):])
+        var2_num_gold = int(gold_relation2[j][2][len(gold_label):])
+        candidate_match[var1_num_test].add(var1_num_gold)
+        candidate_match[var2_num_test].add(var2_num_gold)
+        cur_k1 = (var1_num_test, var1_num_gold)
+        cur_k2 = (var2_num_test, var2_num_gold)
+        if cur_k2 != cur_k1:
+          if cur_k1 in weight_dict:
+            if cur_k2 in weight_dict[cur_k1]:
+              weight_dict[cur_k1][cur_k2] += w
+            else:
+              weight_dict[cur_k1][cur_k2] = w
+          else:
+            weight_dict[cur_k1] = {}
+            weight_dict[cur_k1][-1] = 0
+            weight_dict[cur_k1][cur_k2] = w
+          if cur_k2 in weight_dict:
+            if cur_k1 in weight_dict[cur_k2]:
+              weight_dict[cur_k2][cur_k1] += w
+            else:
+              weight_dict[cur_k2][cur_k1] = w
+          else:
+            weight_dict[cur_k2] = {}
+            weight_dict[cur_k2][-1] = 0
+            weight_dict[cur_k2][cur_k1] = w
+        else:
+          # cycle
+          if cur_k1 in weight_dict:
+            weight_dict[cur_k1][-1] += w
+          else:
+            weight_dict[cur_k1] = {}
+            weight_dict[cur_k1][-1] = w
+  return (candidate_match, weight_dict)
+
+
+def init_match(candidate_match, test_instance, gold_instance, node_weight_fn):
+  """Initialize match based on the word match
+     Args:
+         candidate_match: candidate variable match list
+         test_instance: test instance
+         gold_instance: gold instance
+      Returns:
+         intialized match result"""
+  random.seed()
+  matched_dict = {}
+
+  num_test_matched = 0
+  matches_by_weight = []
+  result = [-1 for c in candidate_match]
+  for i, c in enumerate(candidate_match):
+    c2 = list(c)
+    if len(c2) == 0:
+      num_test_matched += 1
+      continue
+    # word in the test instance
+    test_word = test_instance[i][2]
+    for j, m_id in enumerate(c2):
+      gold_word = gold_instance[int(m_id)][2]
+      curr_score = node_weight_fn(gold_word, test_word)
+      matches_by_weight.append((int(m_id), i, curr_score))
+
+  matches_by_weight = sorted(matches_by_weight, key=lambda (x1,x2,x3) : x3, reverse=True)
+  for (gold, test, score) in matches_by_weight:
+    if len(matched_dict) == len(gold_instance) \
+        or num_test_matched == len(test_instance):
+      break
+    if result[test] != -1 or gold in matched_dict:
+      continue
+    result[test] = gold
+    matched_dict[gold] = 1
+    num_test_matched += 1
+
+  for (i, m) in enumerate(result):
+    if m != -1:
+      continue
+    c2 = list(candidate_match[i])
+    found = False
+    while len(c2) != 1:
+      rid = random.randint(0, len(c2) - 1)
+      if c2[rid] in matched_dict:
+        c2.pop(rid)
+      else:
+        matched_dict[c2[rid]] = 1
+        result[i] = c2[rid]
+        found = True
+        break
+    if not found:
+      if c2[0] not in matched_dict:
+        result[i] = c2[0]
+        matched_dict[c2[0]] = 1
+  return result
+
+
+def get_random_sol(candidate):
+  """
+  Generate a random variable mapping.
+  Args:
+      candidate:a list of set and each set contains the candidate match of a test instance
+  """
+  random.seed()
+  matched_dict = {}
+  result = []
+  for c in candidate:
+    c2 = list(c)
+    found = False
+    if len(c2) == 0:
+      result.append(-1)
+      continue
+    while len(c2) != 1:
+      rid = random.randint(0, len(c2) - 1)
+      if c2[rid] in matched_dict:
+        c2.pop(rid)
+      else:
+        matched_dict[c2[rid]] = 1
+        result.append(c2[rid])
+        found = True
+        break
+    if not found:
+      if c2[0] not in matched_dict:
+        result.append(c2[0])
+        matched_dict[c2[0]] = 1
+      else:
+        result.append(-1)
+  return result
+
+
+def compute_match(match, weight_dict):
+  """Given a variable match, compute match number based on weight_dict.
+     Args:
+         match: a list of number in gold set, len(match)= number of test instance
+     Returns:
+         matching triple number
+     Complexity: O(m*n) , m is the length of test instance, n is the length of gold instance"""
+  # remember matching number of the previous matching we investigated
+  if tuple(match) in match_num_dict:
+    return match_num_dict[tuple(match)]
+  match_num = 0
+  for i, m in enumerate(match):
+    if m == -1:
+      continue
+    cur_m = (i, m)
+    if cur_m not in weight_dict:
+      continue
+    match_num += weight_dict[cur_m][-1]
+    for k in weight_dict[cur_m]:
+      if k == -1:
+        continue
+      if k[0] < i:
+        continue
+      elif match[k[0]] == k[1]:
+        match_num += weight_dict[cur_m][k]
+  match_num_dict[tuple(match)] = match_num
+  return match_num
+
+
+def move_gain(match, i, m, nm, weight_dict, match_num):
+  """Compute the triple match number gain by the move operation
+     Args:
+         match: current match list
+         i: the remapped source variable
+         m: the original id
+         nm: new mapped id
+         weight_dict: weight dictionary
+         match_num: the original matching number
+      Returns:
+         the gain number (might be negative)"""
+  cur_m = (i, nm)
+  old_m = (i, m)
+  new_match = match[:]
+  new_match[i] = nm
+  if tuple(new_match) in match_num_dict:
+    return match_num_dict[tuple(new_match)] - match_num
+  gain = 0
+  if cur_m in weight_dict:
+    gain += weight_dict[cur_m][-1]
+    for k in weight_dict[cur_m]:
+      if k == -1:
+        continue
+      elif match[k[0]] == k[1]:
+        gain += weight_dict[cur_m][k]
+  if old_m in weight_dict:
+    gain -= weight_dict[old_m][-1]
+    for k in weight_dict[old_m]:
+      if k == -1:
+        continue
+      elif match[k[0]] == k[1]:
+        gain -= weight_dict[old_m][k]
+  match_num_dict[tuple(new_match)] = match_num + gain
+  return gain
+
+
+def swap_gain(match, i, m, j, m2, weight_dict, match_num):
+  """Compute the triple match number gain by the swap operation
+     Args:
+         match: current match list
+         i: the position 1
+         m: the original mapped variable of i
+         j: the position 2
+         m2: the original mapped variable of j
+         weight_dict: weight dictionary
+         match_num: the original matching number
+      Returns:
+         the gain number (might be negative)"""
+  new_match = match[:]
+  new_match[i] = m2
+  new_match[j] = m
+  gain = 0
+  cur_m = (i, m2)
+  cur_m2 = (j, m)
+  old_m = (i, m)
+  old_m2 = (j, m2)
+  if cur_m in weight_dict:
+    gain += weight_dict[cur_m][-1]
+    if cur_m2 in weight_dict[cur_m]:
+      gain += weight_dict[cur_m][cur_m2]
+    for k in weight_dict[cur_m]:
+      if k == -1:
+        continue
+      elif k[0] == j:
+        continue
+      elif match[k[0]] == k[1]:
+        gain += weight_dict[cur_m][k]
+  if cur_m2 in weight_dict:
+    gain += weight_dict[cur_m2][-1]
+    for k in weight_dict[cur_m2]:
+      if k == -1:
+        continue
+      elif k[0] == i:
+        continue
+      elif match[k[0]] == k[1]:
+        gain += weight_dict[cur_m2][k]
+  if old_m in weight_dict:
+    gain -= weight_dict[old_m][-1]
+    if old_m2 in weight_dict[old_m]:
+      gain -= weight_dict[old_m][old_m2]
+    for k in weight_dict[old_m]:
+      if k == -1:
+        continue
+      elif k[0] == j:
+        continue
+      elif match[k[0]] == k[1]:
+        gain -= weight_dict[old_m][k]
+  if old_m2 in weight_dict:
+    gain -= weight_dict[old_m2][-1]
+    for k in weight_dict[old_m2]:
+      if k == -1:
+        continue
+      elif k[0] == i:
+        continue
+      elif match[k[0]] == k[1]:
+        gain -= weight_dict[old_m2][k]
+  match_num_dict[tuple(new_match)] = match_num + gain
+  return gain
+
+
+def get_best_gain(
+    match,
+    candidate_match,
+    weight_dict,
+    gold_len,
+        start_match_num):
+  """ hill-climbing method to return the best gain swap/move can get
+    Args:
+        match: the initial variable mapping
+        candidate_match: the match candidates list
+        weight_dict: the weight dictionary
+        gold_len: the number of the variables in file 2
+        start_match_num: the initial match number
+    Returns:
+        the best gain we can get via swap/move operation"""
+  largest_gain = 0
+  largest_match_num = 0
+  swap = True  # True: using swap False: using move
+  change_list = []
+  # unmatched gold number
+  unmatched_gold = set(range(0, gold_len))
+  # O(gold_len)
+  for m in match:
+    if m in unmatched_gold:
+      unmatched_gold.remove(m)
+  unmatch_list = list(unmatched_gold)
+  for i, m in enumerate(match):
+    # remap i
+    for nm in unmatch_list:
+      if nm in candidate_match[i]:
+        #(i,m) -> (i,nm)
+        gain = move_gain(match, i, m, nm, weight_dict, start_match_num)
+        if verbose:
+          new_match = match[:]
+          new_match[i] = nm
+          new_m_num = compute_match(new_match, weight_dict)
+          if new_m_num != start_match_num + gain:
+            print >> sys.stderr, match, new_match
+            print >> sys.stderr, "Inconsistency in computing: move gain", start_match_num, gain, new_m_num
+        if gain > largest_gain:
+          largest_gain = gain
+          change_list = [i, nm]
+          swap = False
+          largest_match_num = start_match_num + gain
+  for i, m in enumerate(match):
+    for j, m2 in enumerate(match):
+      # swap i
+      if i == j:
+        continue
+      new_match = match[:]
+      new_match[i] = m2
+      new_match[j] = m
+      sw_gain = swap_gain(match, i, m, j, m2, weight_dict, start_match_num)
+      if verbose:
+        new_match = match[:]
+        new_match[i] = m2
+        new_match[j] = m
+        new_m_num = compute_match(new_match, weight_dict)
+        if new_m_num != start_match_num + sw_gain:
+          print >> sys.stderr, match, new_match
+          print >> sys.stderr, "Inconsistency in computing: swap gain", start_match_num, sw_gain, new_m_num
+      if sw_gain > largest_gain:
+        largest_gain = sw_gain
+        change_list = [i, j]
+        swap = True
+  cur_match = match[:]
+  largest_match_num = start_match_num + largest_gain
+  if change_list != []:
+    if swap:
+      temp = cur_match[change_list[0]]
+      cur_match[change_list[0]] = cur_match[change_list[1]]
+      cur_match[change_list[1]] = temp
+      # print >> sys.stderr,"swap gain"
+    else:
+      cur_match[change_list[0]] = change_list[1]
+      # print >> sys.stderr,"move gain"
+  return (largest_match_num, cur_match)
+
+
+def get_fh(test_instance, test_relation1, test_relation2,
+    gold_instance, gold_relation1, gold_relation2,
+    test_label, gold_label,
+    node_weight_fn=dflt_label_weighter, edge_weight_fn=dflt_label_weighter,
+    iter_num=5):
+  """Get the f-score given two sets of triples
+     Args:
+         iter_num: iteration number of heuristic search
+         test_instance: instance triples of AMR 1
+         test_relation1: relation triples of AMR 1 (one-variable)
+         test_relation2: relation triples of AMR 2 (two-variable)
+         gold_instance: instance triples of AMR 2
+         gold_relation1: relation triples of AMR 2 (one-variable)
+         gold_relation2: relation triples of AMR 2 (two-variable)
+         test_label: prefix label for AMRe 1
+         gold_label: prefix label for AMR 2
+      Returns:
+         best_match: the variable mapping which results in the best matching triple number
+         best_match_num: the highest matching number
+        """
+  # compute candidate pool
+  (candidate_match,
+   weight_dict) = compute_pool(test_instance, test_relation1, test_relation2,
+                               gold_instance, gold_relation1, gold_relation2,
+                               test_label, gold_label,
+                               node_weight_fn, edge_weight_fn)
+  best_match_num = 0
+  best_match = [-1] * len(test_instance)
+
+  # best lexical match
+  if iter_num == 0:
+    start_match = init_match(
+        candidate_match,
+        test_instance,
+        gold_instance,
+        node_weight_fn)
+    return(start_match, compute_match(start_match, weight_dict))
+
+  for i in range(0, iter_num):
+    if verbose:
+      print >> sys.stderr, "Iteration", i
+    if i == 0:
+      # smart initialization
+      start_match = init_match(
+          candidate_match,
+          test_instance,
+          gold_instance,
+          node_weight_fn)
+    else:
+      # random initialization
+      start_match = get_random_sol(candidate_match)
+    # first match_num, and store the match in memory
+    match_num = compute_match(start_match, weight_dict)
+   # match_num_dict[tuple(start_match)]=match_num
+    if verbose:
+      print >> sys.stderr, "starting point match num:", match_num
+      print >> sys.stderr, "start match", start_match
+    # hill-climbing
+    (largest_match_num,
+     cur_match) = get_best_gain(start_match,
+                                candidate_match,
+                                weight_dict,
+                                len(gold_instance),
+                                match_num)
+    if verbose:
+      print >> sys.stderr, "Largest match number after the hill-climbing", largest_match_num
+   # match_num=largest_match_num
+    # hill-climbing until there will be no gain if we generate a new variable
+    # mapping
+    while largest_match_num > match_num:
+      match_num = largest_match_num
+      (largest_match_num,
+       cur_match) = get_best_gain(cur_match,
+                                  candidate_match,
+                                  weight_dict,
+                                  len(gold_instance),
+                                  match_num)
+      if verbose:
+        print >> sys.stderr, "Largest match number after the hill-climbing", largest_match_num
+    if match_num > best_match_num:
+      best_match = cur_match[:]
+      best_match_num = match_num
+  return (best_match, best_match_num)
+
+# help of inst_list: record a0 location in the test_instance ...
+
+
+def print_alignment(match, test_instance, gold_instance, flip=False):
+  """ print the alignment based on a match
+  Args:
+      match: current match, denoted by a list
+      test_instance: instances of AMR 1
+      gold_instance: instances of AMR 2
+      filp: filp the test/gold or not"""
+  result = []
+  for i, m in enumerate(match):
+    if m == -1:
+      if not flip:
+        result.append(
+            test_instance[i][1] +
+            "(" +
+            test_instance[i][2] +
+            ")" +
+            "-Null")
+      else:
+        result.append(
+            "Null-" +
+            test_instance[i][1] +
+            "(" +
+            test_instance[i][2] +
+            ")")
+    else:
+      if not flip:
+        result.append(
+            test_instance[i][1] +
+            "(" +
+            test_instance[i][2] +
+            ")" +
+            "-" +
+            gold_instance[m][1] +
+            "(" +
+            gold_instance[m][2] +
+            ")")
+      else:
+        result.append(
+            gold_instance[m][1] +
+            "(" +
+            gold_instance[m][2] +
+            ")" +
+            "-" +
+            test_instance[i][1] +
+            "(" +
+            test_instance[i][2] +
+            ")")
+  return " ".join(result)
+
+
+def compute_f(match_num, test_num, gold_num):
+  """ Compute the f-score based on the matching triple number, triple number of the AMR set 1, triple number of AMR set 2
+      Args:
+         match_num: matching triple number
+         test_num:  triple number of AMR 1
+         gold_num:  triple number of AMR 2
+      Returns:
+         precision: match_num/test_num
+         recall: match_num/gold_num
+         f_score: 2*precision*recall/(precision+recall)"""
+  if test_num == 0 or gold_num == 0:
+    return (0.00, 0.00, 0.00)
+  precision = float(match_num) / float(test_num)
+  recall = float(match_num) / float(gold_num)
+  if (precision + recall) != 0:
+    f_score = 2 * precision * recall / (precision + recall)
+    if verbose:
+      print >> sys.stderr, "F-score:", f_score
+    return (precision, recall, f_score)
+  else:
+    if verbose:
+      print >> sys.stderr, "F-score:", "0.0"
+    return (precision, recall, 0.00)
+
+def main(args):
+  """Main function of the smatch calculation program"""
+  global verbose
+  global iter_num
+  global single_score
+  global pr_flag
+  global match_num_dict
+  # set the restart number
+  iter_num = args.r + 1
+  verbose = False
+  if args.ms:
+    single_score = False
+  if args.v:
+    verbose = True
+  if args.pr:
+    pr_flag = True
+  total_match_num = 0
+  total_test_num = 0
+  total_gold_num = 0
+  sent_num = 1
+
+  prev_amr1 = ""
+  outfile = open(args.outfile, 'w')
+  if not single_score:     
+    outfile.write("Sentence")
+    if pr_flag:
+      outfile.write("\tPrecision\tRecall")
+    outfile.write("\tSmatch\n")
+    
+  while True:
+    cur_amr1 = get_amr_line(args.f[0])
+    cur_amr2 = get_amr_line(args.f[1])
+    if cur_amr1 == "" and cur_amr2 == "":
+      break
+    if(cur_amr1 == ""):        
+      # GULLY CHANGED THIS. 
+      # IF WE RUN OUT OF AVAILABLE AMRS FROM FILE 1, 
+      # REUSE THE LAST AVAILABLE AMR
+      cur_amr1 = prev_amr1  
+      #print >> sys.stderr, "Error: File 1 has less AMRs than file 2"
+      #print >> sys.stderr, "Ignoring remaining AMRs"
+      #break
+      # print >> sys.stderr, "AMR 1 is empty"
+      # continue
+    if(cur_amr2 == ""):
+      print >> sys.stderr, "Error: File 2 has less AMRs than file 1"
+      print >> sys.stderr, "Ignoring remaining AMRs"
+      break
+    # print >> sys.stderr, "AMR 2 is empty"
+    # continue
+    prev_amr1 = cur_amr1
+    amr1 = amr.AMR.parse_AMR_line(cur_amr1)
+    amr2 = amr.AMR.parse_AMR_line(cur_amr2)
+    test_label = "a"
+    gold_label = "b"
+    amr1.rename_node(test_label)
+    amr2.rename_node(gold_label)
+    (test_inst, test_rel1, test_rel2) = amr1.get_triples2()
+    (gold_inst, gold_rel1, gold_rel2) = amr2.get_triples2()
+    if verbose:
+      print "AMR pair", sent_num
+      print >> sys.stderr, "Instance triples of AMR 1:", len(test_inst)
+      print >> sys.stderr, test_inst
+  #   print >> sys.stderr,"Relation triples of AMR 1:",len(test_rel)
+      print >> sys.stderr, "Relation triples of AMR 1:", len(
+          test_rel1) + len(test_rel2)
+      print >>sys.stderr, test_rel1
+      print >> sys.stderr, test_rel2
+  #   print >> sys.stderr, test_rel
+      print >> sys.stderr, "Instance triples of AMR 2:", len(gold_inst)
+      print >> sys.stderr, gold_inst
+  #   print >> sys.stderr,"Relation triples of file 2:",len(gold_rel)
+      print >> sys.stderr, "Relation triples of AMR 2:", len(
+          gold_rel1) + len(gold_rel2)
+      #print >> sys.stderr,"Relation triples of file 2:",len(gold_rel1)+len(gold_rel2)
+      print >> sys.stderr, gold_rel1
+      print >> sys.stderr, gold_rel2
+  #    print >> sys.stderr, gold_rel
+    if len(test_inst) < len(gold_inst):
+      (best_match,
+       best_match_num) = get_fh(test_inst,
+                                test_rel1,
+                                test_rel2,
+                                gold_inst,
+                                gold_rel1,
+                                gold_rel2,
+                                test_label,
+                                gold_label)
+      if verbose:
+        print >> sys.stderr, "AMR pair ", sent_num
+        print >> sys.stderr, "best match number", best_match_num
+        print >> sys.stderr, "best match", best_match
+        print >>sys.stderr, "Best Match:", print_alignment(
+            best_match, test_inst, gold_inst)
+    else:
+      (best_match,
+       best_match_num) = get_fh(gold_inst,
+                                gold_rel1,
+                                gold_rel2,
+                                test_inst,
+                                test_rel1,
+                                test_rel2,
+                                gold_label,
+                                test_label)
+      if verbose:
+        print >> sys.stderr, "Sent ", sent_num
+        print >> sys.stderr, "best match number", best_match_num
+        print >> sys.stderr, "best match", best_match
+        print >>sys.stderr, "Best Match:", print_alignment(
+            best_match, gold_inst, test_inst, True)
+    if not single_score:
+      (precision,
+      recall,
+      best_f_score) = compute_f(best_match_num,
+                                 len(test_rel1) + len(test_inst) + len(test_rel2),
+                                 len(gold_rel1) + len(gold_inst) + len(gold_rel2))
+      if pr_flag:
+        outfile.write( "\t%.2f" % precision )
+        outfile.write( "\t%.2f" % recall )
+      outfile.write( "\t%.2f" % best_f_score )
+      outfile.write(str(sent_num))
+      outfile.write( "\n" )
+      print "%d" % sent_num + "\t" + "%.2f" % best_f_score
+      if pr_flag:
+        print "Precision: %.2f" % precision
+        print "Recall: %.2f" % recall 
+    total_match_num += best_match_num
+    total_test_num += len(test_rel1) + len(test_rel2) + len(test_inst)
+    total_gold_num += len(gold_rel1) + len(gold_rel2) + len(gold_inst)
+    match_num_dict.clear()
+    sent_num += 1  # print "F-score:",best_f_score
+  if verbose:
+    print >> sys.stderr, "Total match num"
+    print >> sys.stderr, total_match_num, total_test_num, total_gold_num
+  if single_score:
+    (precision, recall, best_f_score) = compute_f(
+        total_match_num, total_test_num, total_gold_num)
+    if pr_flag:
+      print "Precision: %.2f" % precision
+      print "Recall: %.2f" % recall
+    print "Document F-score: %.2f" % best_f_score
+  args.f[0].close()
+  args.f[1].close()
+
+if __name__ == "__main__":
+  parser = None
+  args = None
+  if sys.version_info[:2] != (2, 7):
+    if sys.version_info[0] != 2 or sys.version_info[1] < 5:
+      print >> ERROR_LOG, "Smatch only supports python 2.5 or later"
+      exit(1)
+    import optparse
+    if len(sys.argv) == 1:
+      print >> ERROR_LOG, "No argument given. Please run smatch.py -h to see the argument descriptions."
+      exit(1)
+    # requires version >=2.3!
+    parser = build_arg_parser2()
+    (args, opts) = parser.parse_args()
+    # handling file errors
+    # if not len(args.f)<2:
+    #   print >> ERROR_LOG,"File number given is less than 2"
+    #   exit(1)
+    file_handle = []
+    if args.f is None:
+      print >> ERROR_LOG, "smatch.py requires -f option to indicate two files containing AMR as input. Please run smatch.py -h to see the argument descriptions."
+      exit(1)
+    if not os.path.exists(args.f[0]):
+      print >> ERROR_LOG, "Given file", args.f[0], "does not exist"
+      exit(1)
+    else:
+      file_handle.append(codecs.open(args.f[0], encoding='utf8'))
+    if not os.path.exists(args.f[1]):
+      print >> ERROR_LOG, "Given file", args.f[1], "does not exist"
+      exit(1)
+    else:
+      file_handle.append(codecs.open(args.f[1], encoding='utf8'))
+    args.f = tuple(file_handle)
+  else:  # version 2.7
+    import argparse
+    parser = build_arg_parser()
+    args = parser.parse_args()
+  main(args)
diff --git a/amrbatch/amrld/test/bio_ras_0001_1.json b/amrbatch/amrld/test/bio_ras_0001_1.json
new file mode 100644
index 00000000..c790bd5f
--- /dev/null
+++ b/amrbatch/amrld/test/bio_ras_0001_1.json
@@ -0,0 +1,61 @@
+[
+  {
+    "root": {
+      "domain": {
+        "op1": {
+          "@id": "g", 
+          "@type": "gene", 
+          "name": {
+            "@id": "n", 
+            "@type": "name", 
+            "op1": "KRAS"
+          }
+        }, 
+        "@id": "a", 
+        "@type": "and", 
+        "op2": {
+          "@id": "g2", 
+          "@type": "gene", 
+          "name": {
+            "@id": "n2", 
+            "@type": "name", 
+            "op1": "PIK3CA"
+          }
+        }, 
+        "op3": {
+          "@id": "g3", 
+          "@type": "gene", 
+          "name": {
+            "@id": "n3", 
+            "@type": "name", 
+            "op1": "BRAF"
+          }
+        }
+      }, 
+      "@id": "o", 
+      "@type": "oncogene", 
+      "location": {
+        "@id": "c", 
+        "@type": "cancer"
+      }
+    }, 
+    "has-date": "2014-08-13T14:22:25", 
+    "@context": {
+      "and": "http://amr.isi.edu/rdf/core-amr#and", 
+      "oncogene": "http://amr.isi.edu/rdf/core-amr#oncogene", 
+      "kill-01": "https://verbs.colorado.edu/propbank#kill-01", 
+      "name": "http://amr.isi.edu/rdf/core-amr#name", 
+      "cancer": "http://amr.isi.edu/rdf/core-amr#cancer", 
+      "most": "http://amr.isi.edu/rdf/core-amr#most", 
+      "@base": "http://amr.isi.edu/amr_data/bio.ras_0001_1#", 
+      "human": "http://amr.isi.edu/rdf/core-amr#human", 
+      "gene": "http://amr.isi.edu/entity-types#gene", 
+      "root": "http://amr.isi.edu/rdf/core-amr#root", 
+      "frequent": "http://amr.isi.edu/rdf/core-amr#frequent", 
+      "mutate-01": "https://verbs.colorado.edu/propbank#mutate-01"
+    }, 
+    "@id": "bio.ras_0001_1", 
+    "@type": "http://amr.isi.edu/rdf/core-amr#AMR", 
+    "has-sentence": "The most frequently mutated oncogenes in the deadliest cancers responsible for human mortality are KRAS , PIK3CA and BRAF ."
+  }
+]
\ No newline at end of file
diff --git a/amrbatch/amrld/test/bio_ras_0001_1.rdf b/amrbatch/amrld/test/bio_ras_0001_1.rdf
new file mode 100644
index 00000000..642dab56
--- /dev/null
+++ b/amrbatch/amrld/test/bio_ras_0001_1.rdf
@@ -0,0 +1,39 @@
+<http://amr.isi.edu/amr_data/bio.ras_0001_1#k> <http://amr.isi.edu/rdf/core-amr#ARG1> <http://amr.isi.edu/amr_data/bio.ras_0001_1#h> .
+<http://amr.isi.edu/amr_data/bio.ras_0001_1#root01> <http://amr.isi.edu/rdf/core-amr#has-sentence> "The most frequently mutated oncogenes in the deadliest cancers responsible for human mortality are KRAS , PIK3CA and BRAF ." .
+<http://amr.isi.edu/amr_data/bio.ras_0001_1#f> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://amr.isi.edu/rdf/core-amr#frequent> .
+<http://amr.isi.edu/amr_data/bio.ras_0001_1#n> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://amr.isi.edu/rdf/core-amr#name> .
+<http://amr.isi.edu/amr_data/bio.ras_0001_1#g2> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://amr.isi.edu/entity-types#gene> .
+<http://amr.isi.edu/amr_data/bio.ras_0001_1#a> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://amr.isi.edu/rdf/core-amr#and> .
+<http://amr.isi.edu/amr_data/bio.ras_0001_1#o> <http://amr.isi.edu/rdf/core-amr#location> <http://amr.isi.edu/amr_data/bio.ras_0001_1#c> .
+<http://amr.isi.edu/amr_data/bio.ras_0001_1#root01> <http://amr.isi.edu/rdf/core-amr#has-id> "bio.ras_0001_1" .
+<http://amr.isi.edu/amr_data/bio.ras_0001_1#m> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://amr.isi.edu/rdf/core-amr#most> .
+<http://amr.isi.edu/amr_data/bio.ras_0001_1#f> <http://amr.isi.edu/rdf/core-amr#degree> <http://amr.isi.edu/amr_data/bio.ras_0001_1#m3> .
+<http://amr.isi.edu/amr_data/bio.ras_0001_1#n2> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://amr.isi.edu/rdf/core-amr#name> .
+<http://amr.isi.edu/amr_data/bio.ras_0001_1#n3> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://amr.isi.edu/rdf/core-amr#name> .
+<http://amr.isi.edu/amr_data/bio.ras_0001_1#root01> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://amr.isi.edu/rdf/core-amr#AMR> .
+<http://amr.isi.edu/amr_data/bio.ras_0001_1#a> <http://amr.isi.edu/rdf/core-amr#op3> <http://amr.isi.edu/amr_data/bio.ras_0001_1#g3> .
+<http://amr.isi.edu/amr_data/bio.ras_0001_1#k> <http://amr.isi.edu/rdf/core-amr#ARG0> <http://amr.isi.edu/amr_data/bio.ras_0001_1#c> .
+<http://amr.isi.edu/amr_data/bio.ras_0001_1#a> <http://amr.isi.edu/rdf/core-amr#op1> <http://amr.isi.edu/amr_data/bio.ras_0001_1#g> .
+<http://amr.isi.edu/amr_data/bio.ras_0001_1#n2> <http://amr.isi.edu/rdf/core-amr#op1> "PIK3CA" .
+<http://amr.isi.edu/amr_data/bio.ras_0001_1#g> <http://amr.isi.edu/rdf/core-amr#name> <http://amr.isi.edu/amr_data/bio.ras_0001_1#n> .
+<http://amr.isi.edu/amr_data/bio.ras_0001_1#m3> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://amr.isi.edu/rdf/core-amr#most> .
+<http://amr.isi.edu/amr_data/bio.ras_0001_1#o> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://amr.isi.edu/rdf/core-amr#oncogene> .
+<http://amr.isi.edu/amr_data/bio.ras_0001_1#m2> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <https://verbs.colorado.edu/propbank#mutate-01> .
+<http://amr.isi.edu/amr_data/bio.ras_0001_1#k> <http://amr.isi.edu/rdf/core-amr#degree> <http://amr.isi.edu/amr_data/bio.ras_0001_1#m> .
+<http://amr.isi.edu/amr_data/bio.ras_0001_1#m2> <http://amr.isi.edu/rdf/core-amr#frequency> <http://amr.isi.edu/amr_data/bio.ras_0001_1#f> .
+<http://amr.isi.edu/amr_data/bio.ras_0001_1#k> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <https://verbs.colorado.edu/propbank#kill-01> .
+<http://amr.isi.edu/amr_data/bio.ras_0001_1#h> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://amr.isi.edu/rdf/core-amr#human> .
+<http://amr.isi.edu/amr_data/bio.ras_0001_1#g3> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://amr.isi.edu/entity-types#gene> .
+<http://amr.isi.edu/amr_data/bio.ras_0001_1#root01> <http://amr.isi.edu/rdf/core-amr#root> <http://amr.isi.edu/amr_data/bio.ras_0001_1#o> .
+<http://amr.isi.edu/amr_data/bio.ras_0001_1#c> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://amr.isi.edu/rdf/core-amr#cancer> .
+<http://amr.isi.edu/amr_data/bio.ras_0001_1#n3> <http://amr.isi.edu/rdf/core-amr#op1> "BRAF" .
+<http://amr.isi.edu/amr_data/bio.ras_0001_1#o> <http://amr.isi.edu/rdf/core-amr#TOP> <http://amr.isi.edu/amr_data/bio.ras_0001_1#o> .
+<http://amr.isi.edu/amr_data/bio.ras_0001_1#o> <http://amr.isi.edu/rdf/core-amr#domain> <http://amr.isi.edu/amr_data/bio.ras_0001_1#a> .
+<http://amr.isi.edu/amr_data/bio.ras_0001_1#g2> <http://amr.isi.edu/rdf/core-amr#name> <http://amr.isi.edu/amr_data/bio.ras_0001_1#n2> .
+<http://amr.isi.edu/amr_data/bio.ras_0001_1#g> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://amr.isi.edu/entity-types#gene> .
+<http://amr.isi.edu/amr_data/bio.ras_0001_1#n> <http://amr.isi.edu/rdf/core-amr#op1> "KRAS" .
+<http://amr.isi.edu/amr_data/bio.ras_0001_1#m2> <http://amr.isi.edu/rdf/core-amr#ARG1> <http://amr.isi.edu/amr_data/bio.ras_0001_1#o> .
+<http://amr.isi.edu/amr_data/bio.ras_0001_1#g3> <http://amr.isi.edu/rdf/core-amr#name> <http://amr.isi.edu/amr_data/bio.ras_0001_1#n3> .
+<http://amr.isi.edu/amr_data/bio.ras_0001_1#root01> <http://amr.isi.edu/rdf/core-amr#has-date> "2014-08-13T14:22:25" .
+<http://amr.isi.edu/amr_data/bio.ras_0001_1#a> <http://amr.isi.edu/rdf/core-amr#op2> <http://amr.isi.edu/amr_data/bio.ras_0001_1#g2> .
+
diff --git a/amrbatch/amrld/test/bio_ras_0001_1.txt b/amrbatch/amrld/test/bio_ras_0001_1.txt
new file mode 100644
index 00000000..c79b0e4d
--- /dev/null
+++ b/amrbatch/amrld/test/bio_ras_0001_1.txt
@@ -0,0 +1,15 @@
+# ::id bio.ras_0001_1 ::date 2014-08-13T14:22:25
+# ::snt The most frequently mutated oncogenes in the deadliest cancers responsible for human mortality are KRAS , PIK3CA and BRAF .
+
+(o / oncogene
+      :domain (a / and
+            :op1 (g / gene :name (n / name :op1 "KRAS"))
+            :op2 (g2 / gene :name (n2 / name :op1 "PIK3CA"))
+            :op3 (g3 / gene :name (n3 / name :op1 "BRAF")))
+      :location (c / cancer
+            :ARG0-of (k / kill-01
+                  :ARG1 (h / human)
+                  :degree (m / most)))
+      :ARG1-of (m2 / mutate-01
+            :frequency (f / frequent
+                  :degree (m3 / most))))
diff --git a/amrbatch/amrld/test/pmid-11777939-32_amr.rdf b/amrbatch/amrld/test/pmid-11777939-32_amr.rdf
new file mode 100644
index 00000000..9c69ec8b
--- /dev/null
+++ b/amrbatch/amrld/test/pmid-11777939-32_amr.rdf
@@ -0,0 +1,70 @@
+@prefix ns1: <http://amr.isi.edu/rdf/core-amr#> .
+@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
+@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
+@prefix xml: <http://www.w3.org/XML/1998/namespace> .
+@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
+
+<http://amr.isi.edu/amr_data/pmid_1177_7939.32#root01> a ns1:AMR ;
+    ns1:has-date "2015-02-27T00:14:25" ;
+    ns1:has-id "pmid_1177_7939.32" ;
+    ns1:has-sentence "In previous studies, we showed that Sos-1, E3b1, and Eps8 could form a trimeric complex in vivo upon concomitant overexpression of the three proteins." ;
+    ns1:root <http://amr.isi.edu/amr_data/pmid_1177_7939.32#s> .
+
+<http://amr.isi.edu/amr_data/pmid_1177_7939.32#c> a ns1:concomitant .
+
+<http://amr.isi.edu/amr_data/pmid_1177_7939.32#e2> a <http://amr.isi.edu/entity-types#enzyme> ;
+    ns1:name <http://amr.isi.edu/amr_data/pmid_1177_7939.32#n3> .
+
+<http://amr.isi.edu/amr_data/pmid_1177_7939.32#f> a <https://verbs.colorado.edu/propbank#form-01> ;
+    ns1:ARG0 <http://amr.isi.edu/amr_data/pmid_1177_7939.32#a> ;
+    ns1:ARG1 <http://amr.isi.edu/amr_data/pmid_1177_7939.32#m> ;
+    ns1:condition <http://amr.isi.edu/amr_data/pmid_1177_7939.32#o> ;
+    ns1:manner <http://amr.isi.edu/amr_data/pmid_1177_7939.32#i> ;
+    ns1:mod <http://amr.isi.edu/amr_data/pmid_1177_7939.32#p> .
+
+<http://amr.isi.edu/amr_data/pmid_1177_7939.32#i> a ns1:in-vivo .
+
+<http://amr.isi.edu/amr_data/pmid_1177_7939.32#m> a <http://amr.isi.edu/entity-types#macro-molecular-complex> ;
+    ns1:mod <http://amr.isi.edu/amr_data/pmid_1177_7939.32#t> .
+
+<http://amr.isi.edu/amr_data/pmid_1177_7939.32#n> a ns1:name ;
+    ns1:op1 "Sos-1" .
+
+<http://amr.isi.edu/amr_data/pmid_1177_7939.32#n2> a ns1:name ;
+    ns1:op1 "E3b1" .
+
+<http://amr.isi.edu/amr_data/pmid_1177_7939.32#n3> a ns1:name ;
+    ns1:op1 "Eps8" .
+
+<http://amr.isi.edu/amr_data/pmid_1177_7939.32#o> a <https://verbs.colorado.edu/propbank#overexpress-00> ;
+    ns1:ARG2 <http://amr.isi.edu/amr_data/pmid_1177_7939.32#a> ;
+    ns1:manner <http://amr.isi.edu/amr_data/pmid_1177_7939.32#c> .
+
+<http://amr.isi.edu/amr_data/pmid_1177_7939.32#p> a ns1:possible .
+
+<http://amr.isi.edu/amr_data/pmid_1177_7939.32#p2> a <http://amr.isi.edu/entity-types#protein> ;
+    ns1:name <http://amr.isi.edu/amr_data/pmid_1177_7939.32#n> .
+
+<http://amr.isi.edu/amr_data/pmid_1177_7939.32#p3> a <http://amr.isi.edu/entity-types#protein> ;
+    ns1:name <http://amr.isi.edu/amr_data/pmid_1177_7939.32#n2> .
+
+<http://amr.isi.edu/amr_data/pmid_1177_7939.32#p5> a ns1:previous .
+
+<http://amr.isi.edu/amr_data/pmid_1177_7939.32#s2> a ns1:study ;
+    ns1:time <http://amr.isi.edu/amr_data/pmid_1177_7939.32#p5> .
+
+<http://amr.isi.edu/amr_data/pmid_1177_7939.32#t> a ns1:trimeric .
+
+<http://amr.isi.edu/amr_data/pmid_1177_7939.32#w> a ns1:we .
+
+<http://amr.isi.edu/amr_data/pmid_1177_7939.32#a> a ns1:and ;
+    ns1:op1 <http://amr.isi.edu/amr_data/pmid_1177_7939.32#p2> ;
+    ns1:op2 <http://amr.isi.edu/amr_data/pmid_1177_7939.32#p3> ;
+    ns1:op3 <http://amr.isi.edu/amr_data/pmid_1177_7939.32#e2> .
+
+<http://amr.isi.edu/amr_data/pmid_1177_7939.32#s> a <https://verbs.colorado.edu/propbank#show-01> ;
+    ns1:ARG0 <http://amr.isi.edu/amr_data/pmid_1177_7939.32#w> ;
+    ns1:ARG1 <http://amr.isi.edu/amr_data/pmid_1177_7939.32#f> ;
+    ns1:TOP <http://amr.isi.edu/amr_data/pmid_1177_7939.32#s> ;
+    ns1:medium <http://amr.isi.edu/amr_data/pmid_1177_7939.32#s2> .
+
diff --git a/amrbatch/amrld/test/pmid-11777939-32_amr.txt b/amrbatch/amrld/test/pmid-11777939-32_amr.txt
new file mode 100755
index 00000000..d53255b7
--- /dev/null
+++ b/amrbatch/amrld/test/pmid-11777939-32_amr.txt
@@ -0,0 +1,20 @@
+# ::id pmid_1177_7939.32 ::date 2015-02-27T00:14:25 ::authors mrizea
+# ::snt In previous studies, we showed that Sos-1, E3b1, and Eps8 could form a trimeric complex in vivo upon concomitant overexpression of the three proteins.
+# ::note Sentence+ loaded by script SntLoaderUlf1.7.pl
+# ::save-date Wed Apr 1, 2015 ::user bbadarau ::file pmid_1177_7939_32.txt
+(s / show-01
+      :ARG0 (w / we)
+      :ARG1 (f / form-01
+            :ARG0 (a / and
+                  :op1 (p2 / protein :name (n / name :op1 "Sos-1"))
+                  :op2 (p3 / protein :name (n2 / name :op1 "E3b1"))
+                  :op3 (e2 / enzyme :name (n3 / name :op1 "Eps8")))
+            :ARG1 (m / macro-molecular-complex
+                  :mod (t / trimeric))
+            :mod (p / possible)
+            :manner (i / in-vivo)
+            :condition (o / overexpress-00
+                  :ARG2 a
+                  :manner (c / concomitant)))
+      :medium (s2 / study
+            :time (p5 / previous)))
\ No newline at end of file
diff --git a/amrbatch/amrld/test/test.amr.graph b/amrbatch/amrld/test/test.amr.graph
new file mode 100644
index 00000000..d374bd90
--- /dev/null
+++ b/amrbatch/amrld/test/test.amr.graph
@@ -0,0 +1,12 @@
+# ::id test-1
+# ::snt The sun is a star.
+(s / star
+      :domain (s2 / sun))
+
+# ::id test-2
+# ::snt Earth is a planet.
+(p / planet
+      :domain p
+      :name (n / name
+            :op1 "Earth"))
+
diff --git a/amrbatch/amrld/xref_namespaces.txt b/amrbatch/amrld/xref_namespaces.txt
new file mode 100644
index 00000000..36e64247
--- /dev/null
+++ b/amrbatch/amrld/xref_namespaces.txt
@@ -0,0 +1,3 @@
+UNIPROT	http://www.uniprot.org/uniprot/
+PUBCHEM	https://pubchem.ncbi.nlm.nih.gov/compound/	
+GO	http://amigo.geneontology.org/amigo/term/GO:
\ No newline at end of file
diff --git a/amrbatch/main.py b/amrbatch/main.py
new file mode 100644
index 00000000..a60a622b
--- /dev/null
+++ b/amrbatch/main.py
@@ -0,0 +1,55 @@
+#!/usr/bin/python3.10
+# -*-coding:Utf-8 -*
+
+#==============================================================================
+# AMR Batch: main
+#------------------------------------------------------------------------------
+# Module providing the main method(s) of the amrBatch library.
+#==============================================================================
+
+import sys, os, glob
+import shutil
+from rdflib import Graph
+
+
+    
+   
+#==============================================================================
+# Steps
+#==============================================================================
+
+# TODO
+    
+
+#==============================================================================
+# AMR Main Methods 
+#==============================================================================
+
+def parse_sentences_from_file(input_file_path,  
+                              output_penman_file_path=None, 
+                              technical_dir_path=None):
+    """
+    Method to parse an input file containing natural language sentences and 
+    construct the corresponding AMR graphs (and their RDF serializations if required).
+    The method returns an AMR graph string in PENMAN format. AMR graphs are also 
+    serialized in RDF turtle format using the AMR-LD library if requested 
+    (by defining output_turtle_file_path as a parameter).
+    
+
+    Parameters
+    ----------
+    input_file_path: a path to a text file.
+    output_penman_file_path: a file path where the output graphs is written in PENMAN format if defined (the function still outputs the string). 
+    output_turtle_file_path: a file path where the output AMRLD representation is written in TURTLE format if defined. 
+    technical_dir_path: a dir path where some technical and log files are written if defined.
+
+    Returns
+    -------
+    AMR Graph String (in PENMAN format).
+
+    """
+    
+    pass
+    
+    return ''
+
diff --git a/amrbatch/propbank_analyzer.py b/amrbatch/propbank_analyzer.py
new file mode 100644
index 00000000..bb6fbe35
--- /dev/null
+++ b/amrbatch/propbank_analyzer.py
@@ -0,0 +1,254 @@
+#!/usr/bin/python3.10
+# -*-coding:Utf-8 -*
+
+#==============================================================================
+# C.M. Tool: PropBank Frame Analyzer
+#------------------------------------------------------------------------------
+# Module to analyze PropBank frames
+#==============================================================================
+
+#==============================================================================
+# Importing required modules
+#==============================================================================
+
+import sys
+import glob
+import re
+
+from bs4 import BeautifulSoup
+
+
+#==============================================================================
+# Parameters
+#==============================================================================
+
+# Input/Output Directories
+INPUT_DIR = "../inputData/"
+OUTPUT_DIR = "../outputData/"
+
+# Data
+PROPBANK_FRAMES_DIR = "../propbankFrames/"
+PBF_DIGITS = 2
+AMR_CORE_ROLE_FORM = [':ARG\d$', 'ARG\d$', '\d$']
+
+
+#==============================================================================
+# Functions to analyze and adapt the target description
+#==============================================================================
+
+def itemize_amr_predicate(amr_predicate):
+    ap_items = amr_predicate.split('-')
+    lemma = ap_items[0]
+    if len(ap_items) > 1:
+        roleset_number = int(ap_items[1])
+    else:
+        roleset_number = 1
+    return lemma, roleset_number
+
+
+def get_lemma_from_amr_predicate(amr_predicate):
+    lemma, _ = itemize_amr_predicate(amr_predicate)
+    return lemma
+    
+
+def get_role_ref_from_amr_predicate(amr_predicate):
+    _, roleset_number = itemize_amr_predicate(amr_predicate)
+    roleset_ref = str(roleset_number).rjust(PBF_DIGITS,"0")
+    return roleset_ref
+    
+    
+def get_roleset_id_from_amr_predicate(amr_predicate):
+    lemma = get_lemma_from_amr_predicate(amr_predicate)
+    roleset_ref = get_role_ref_from_amr_predicate(amr_predicate)
+    roleset_id = lemma + '.' + roleset_ref    
+    return roleset_id
+
+
+def get_number_from_amr_role(amr_role):
+    role_number = -1
+    for role_format in AMR_CORE_ROLE_FORM:
+        if re.match(role_format, amr_role):
+            role_number = int(amr_role[-1])
+    return role_number
+
+
+#==============================================================================
+# Functions to find the XML description corresponding to a roleset
+#==============================================================================
+
+def find_frame_of_lemma(lemma):
+    """ Find the Frame XML data corresponding to a given lemma
+    """
+    
+    target_file = PROPBANK_FRAMES_DIR + lemma + '.xml'
+    frame_filepath = glob.glob(target_file, recursive=True)
+    
+    if len(frame_filepath) >= 1:
+        frame_filepath = frame_filepath[0]
+        with open(frame_filepath, 'r') as f:
+            xml_data = f.read()
+            frame_data = BeautifulSoup(xml_data, 'xml')
+    else:
+        frame_filepath = ''
+        frame_data = None
+    
+    is_found = frame_data is not None
+    
+    return is_found, frame_filepath, frame_data
+
+
+#==============================================================================
+# Functions to analyze a frame data
+#==============================================================================
+
+def find_roleset_in_frame(frame_data, lemma, roleset_id):
+    """ Find the roleset corresponding to a lemma and an id in a frame data
+    """
+      
+    try:
+        lemma_data = frame_data.find('predicate', {'lemma':lemma})
+        roleset_data = lemma_data.find('roleset', {'id':roleset_id})
+    
+    except:
+        lemma_data = None
+        roleset_data = None
+         
+    is_found = (lemma_data is not None) & (roleset_data is not None)
+    
+    return is_found, roleset_data
+
+
+def find_role_in_roleset(roleset_data, role_number):
+    """ Find the role corresponding to a given number in a roleset data
+    """
+  
+    try:
+        role_data = roleset_data.find('role', {'n':role_number})
+
+    except:
+        role_data = None
+
+    is_found = (role_data is not None)
+
+    return is_found, role_data
+
+
+#==============================================================================
+# Main Function(s)
+#==============================================================================
+
+def find_pb_role(amr_predicate, amr_role):
+    """
+    Find the probbank role in PropBank frame corresponding to a given AMR
+    predicate and a given AMR role.
+
+    Parameters
+    ----------
+    amr_predicate : STRING
+        AMR predicate (example: 'include-01').
+    amr_role : STRING
+        AMR core role (example: ':ARG0').
+
+    Returns
+    -------
+    PropBank role (example: 'PAG').
+
+    """
+    
+    # -- Intialize result
+    result = None
+    
+    # -- Analyze and adapt the target description
+    lemma = get_lemma_from_amr_predicate(amr_predicate)
+    roleset_id = get_roleset_id_from_amr_predicate(amr_predicate)
+    role_number = get_number_from_amr_role(amr_role)
+    
+    # -- Find the Frame XML data corresponding to a given lemma
+    frame_found, frame_filepath, frame_data = find_frame_of_lemma(lemma)
+           
+    if frame_found:      
+        # -- Analyze frame data to find the target role
+        rs_found, rs_data = find_roleset_in_frame(frame_data, lemma, roleset_id)
+        nb_roles = -1
+        
+        if rs_found:
+            nb_roles = len(rs_data.find_all('role'))
+            if role_number in range(nb_roles):
+                r_found, role_data = find_role_in_roleset(rs_data, role_number)
+                if r_found:
+                    result = role_data.get('f')   
+    
+    return result
+    
+
+#==============================================================================
+# *** Dev Test ***
+#==============================================================================
+
+def dev_analyze(amr_predicate, amr_role):
+
+    print("\n" + "[CMT-Dev] PropBank Frame Analyzer")
+    
+    # -- Analyze and adapt the target description
+    print("-- Analyzing given data to specify the targetted data")
+    print("----- given data: " + amr_predicate + ', ' + amr_role)
+    lemma = get_lemma_from_amr_predicate(amr_predicate)
+    print("----- lemma: " + lemma)
+    roleset_id = get_roleset_id_from_amr_predicate(amr_predicate)
+    print("----- roleset id: " + roleset_id)
+    role_number = get_number_from_amr_role(amr_role)
+    print("----- role number: " + str(role_number))
+    
+    # -- Find the Frame XML data corresponding to a given lemma
+    print("-- Finding frame data")
+    frame_found, frame_filepath, frame_data = find_frame_of_lemma(lemma)
+    if frame_found:
+        print("----- frame xml file found: " + frame_filepath)
+    else:
+        print("----- frame xml file not found for lemma " + lemma)
+           
+    if frame_found:      
+        # -- Analyze frame data to get informations
+        print("-- Analyzing frame data")
+        rs_found, rs_data = find_roleset_in_frame(frame_data, lemma, roleset_id)
+        nb_roles = -1
+        
+        if rs_found:
+            print("----- roleset id: " + rs_data.get('id'))
+            print("----- roleset name: " + rs_data.get('name'))
+            nb_roles = len(rs_data.find_all('role'))
+            print("----- number of roles: " + str(nb_roles))
+            for n in range(nb_roles):
+                _, role_data = find_role_in_roleset(rs_data, n)
+                print("----- role " + str(n) + ': ' + role_data.get('f') + 
+                                                 ', ' + role_data.get('descr'))
+        else:
+            print("----- roleset " + roleset_id + " not found")
+        
+        # -- Analyze frame data to get informations
+        if rs_found & role_number in range(nb_roles):
+            print("-- Finding role")
+            print("----- role number: " + str(role_number))
+            r_found, role_data = find_role_in_roleset(rs_data, role_number)
+            if r_found:
+                print("----- role " + str(role_number) + " found: " + 
+                      role_data.get('f') + 
+                      ', ' + role_data.get('descr'))
+            else:
+                print("----- role " + str(role_number) + " not found")    
+    
+    # -- Test for main function(s)
+    print("-- Test for main function(s)")
+    pb_role = find_pb_role(amr_predicate, amr_role)
+    print("----- find_pb_role(amr_predicate, amr_role) = " + pb_role)
+    
+    # -- Ending print
+    print("\n" + "[SSC] Done")
+    
+def dev_test_1():
+    dev_analyze('include-01', ':ARG0')
+
+
+    
+    
+    
diff --git a/gpl-3.0.txt b/gpl-3.0.txt
new file mode 100644
index 00000000..f288702d
--- /dev/null
+++ b/gpl-3.0.txt
@@ -0,0 +1,674 @@
+                    GNU GENERAL PUBLIC LICENSE
+                       Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+                            Preamble
+
+  The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+  The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works.  By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users.  We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors.  You can apply it to
+your programs, too.
+
+  When we speak of free software, we are referring to freedom, not
+price.  Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+  To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights.  Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+  For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received.  You must make sure that they, too, receive
+or can get the source code.  And you must show them these terms so they
+know their rights.
+
+  Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+  For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software.  For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+  Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so.  This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software.  The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable.  Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products.  If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+  Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary.  To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+  The precise terms and conditions for copying, distribution and
+modification follow.
+
+                       TERMS AND CONDITIONS
+
+  0. Definitions.
+
+  "This License" refers to version 3 of the GNU General Public License.
+
+  "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+  "The Program" refers to any copyrightable work licensed under this
+License.  Each licensee is addressed as "you".  "Licensees" and
+"recipients" may be individuals or organizations.
+
+  To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy.  The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+  A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+  To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy.  Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+  To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies.  Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+  An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License.  If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+  1. Source Code.
+
+  The "source code" for a work means the preferred form of the work
+for making modifications to it.  "Object code" means any non-source
+form of a work.
+
+  A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+  The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form.  A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+  The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities.  However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work.  For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+  The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+  The Corresponding Source for a work in source code form is that
+same work.
+
+  2. Basic Permissions.
+
+  All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met.  This License explicitly affirms your unlimited
+permission to run the unmodified Program.  The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work.  This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+  You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force.  You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright.  Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+  Conveying under any other circumstances is permitted solely under
+the conditions stated below.  Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+  3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+  No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+  When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+  4. Conveying Verbatim Copies.
+
+  You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+  You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+  5. Conveying Modified Source Versions.
+
+  You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+    a) The work must carry prominent notices stating that you modified
+    it, and giving a relevant date.
+
+    b) The work must carry prominent notices stating that it is
+    released under this License and any conditions added under section
+    7.  This requirement modifies the requirement in section 4 to
+    "keep intact all notices".
+
+    c) You must license the entire work, as a whole, under this
+    License to anyone who comes into possession of a copy.  This
+    License will therefore apply, along with any applicable section 7
+    additional terms, to the whole of the work, and all its parts,
+    regardless of how they are packaged.  This License gives no
+    permission to license the work in any other way, but it does not
+    invalidate such permission if you have separately received it.
+
+    d) If the work has interactive user interfaces, each must display
+    Appropriate Legal Notices; however, if the Program has interactive
+    interfaces that do not display Appropriate Legal Notices, your
+    work need not make them do so.
+
+  A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit.  Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+  6. Conveying Non-Source Forms.
+
+  You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+    a) Convey the object code in, or embodied in, a physical product
+    (including a physical distribution medium), accompanied by the
+    Corresponding Source fixed on a durable physical medium
+    customarily used for software interchange.
+
+    b) Convey the object code in, or embodied in, a physical product
+    (including a physical distribution medium), accompanied by a
+    written offer, valid for at least three years and valid for as
+    long as you offer spare parts or customer support for that product
+    model, to give anyone who possesses the object code either (1) a
+    copy of the Corresponding Source for all the software in the
+    product that is covered by this License, on a durable physical
+    medium customarily used for software interchange, for a price no
+    more than your reasonable cost of physically performing this
+    conveying of source, or (2) access to copy the
+    Corresponding Source from a network server at no charge.
+
+    c) Convey individual copies of the object code with a copy of the
+    written offer to provide the Corresponding Source.  This
+    alternative is allowed only occasionally and noncommercially, and
+    only if you received the object code with such an offer, in accord
+    with subsection 6b.
+
+    d) Convey the object code by offering access from a designated
+    place (gratis or for a charge), and offer equivalent access to the
+    Corresponding Source in the same way through the same place at no
+    further charge.  You need not require recipients to copy the
+    Corresponding Source along with the object code.  If the place to
+    copy the object code is a network server, the Corresponding Source
+    may be on a different server (operated by you or a third party)
+    that supports equivalent copying facilities, provided you maintain
+    clear directions next to the object code saying where to find the
+    Corresponding Source.  Regardless of what server hosts the
+    Corresponding Source, you remain obligated to ensure that it is
+    available for as long as needed to satisfy these requirements.
+
+    e) Convey the object code using peer-to-peer transmission, provided
+    you inform other peers where the object code and Corresponding
+    Source of the work are being offered to the general public at no
+    charge under subsection 6d.
+
+  A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+  A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling.  In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage.  For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product.  A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+  "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source.  The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+  If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information.  But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+  The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed.  Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+  Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+  7. Additional Terms.
+
+  "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law.  If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+  When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it.  (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.)  You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+  Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+    a) Disclaiming warranty or limiting liability differently from the
+    terms of sections 15 and 16 of this License; or
+
+    b) Requiring preservation of specified reasonable legal notices or
+    author attributions in that material or in the Appropriate Legal
+    Notices displayed by works containing it; or
+
+    c) Prohibiting misrepresentation of the origin of that material, or
+    requiring that modified versions of such material be marked in
+    reasonable ways as different from the original version; or
+
+    d) Limiting the use for publicity purposes of names of licensors or
+    authors of the material; or
+
+    e) Declining to grant rights under trademark law for use of some
+    trade names, trademarks, or service marks; or
+
+    f) Requiring indemnification of licensors and authors of that
+    material by anyone who conveys the material (or modified versions of
+    it) with contractual assumptions of liability to the recipient, for
+    any liability that these contractual assumptions directly impose on
+    those licensors and authors.
+
+  All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10.  If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term.  If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+  If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+  Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+  8. Termination.
+
+  You may not propagate or modify a covered work except as expressly
+provided under this License.  Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+  However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+  Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+  Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License.  If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+  9. Acceptance Not Required for Having Copies.
+
+  You are not required to accept this License in order to receive or
+run a copy of the Program.  Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance.  However,
+nothing other than this License grants you permission to propagate or
+modify any covered work.  These actions infringe copyright if you do
+not accept this License.  Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+  10. Automatic Licensing of Downstream Recipients.
+
+  Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License.  You are not responsible
+for enforcing compliance by third parties with this License.
+
+  An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations.  If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+  You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License.  For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+  11. Patents.
+
+  A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based.  The
+work thus licensed is called the contributor's "contributor version".
+
+  A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version.  For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+  Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+  In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement).  To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+  If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients.  "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+  If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+  A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License.  You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+  Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+  12. No Surrender of Others' Freedom.
+
+  If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License.  If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all.  For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+  13. Use with the GNU Affero General Public License.
+
+  Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work.  The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+  14. Revised Versions of this License.
+
+  The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time.  Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+  Each version is given a distinguishing version number.  If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation.  If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+  If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+  Later license versions may give you additional or different
+permissions.  However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+  15. Disclaimer of Warranty.
+
+  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+  16. Limitation of Liability.
+
+  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+  17. Interpretation of Sections 15 and 16.
+
+  If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+                     END OF TERMS AND CONDITIONS
+
+            How to Apply These Terms to Your New Programs
+
+  If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+  To do so, attach the following notices to the program.  It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+    <one line to give the program's name and a brief idea of what it does.>
+    Copyright (C) <year>  <name of author>
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation, either version 3 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program.  If not, see <https://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+  If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+    <program>  Copyright (C) <year>  <name of author>
+    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+    This is free software, and you are welcome to redistribute it
+    under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License.  Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+  You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+<https://www.gnu.org/licenses/>.
+
+  The GNU General Public License does not permit incorporating your program
+into proprietary programs.  If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library.  If this is what you want to do, use the GNU Lesser General
+Public License instead of this License.  But first, please read
+<https://www.gnu.org/licenses/why-not-lgpl.html>.
diff --git a/requirements.txt b/requirements.txt
new file mode 100644
index 00000000..3d9c233e
--- /dev/null
+++ b/requirements.txt
@@ -0,0 +1,8 @@
+unidecode
+amrlib
+argparse
+numpy
+rdflib
+graphviz
+bs4
+lxml
diff --git a/tests/context.py b/tests/context.py
new file mode 100644
index 00000000..7af3af3f
--- /dev/null
+++ b/tests/context.py
@@ -0,0 +1,8 @@
+import os
+import sys
+LIB_PATH = f'{os.path.dirname(os.path.abspath(__file__))}/..'
+print(f'Test Context: {LIB_PATH}')
+sys.path.insert(0, os.path.abspath(LIB_PATH))
+
+import amrbatch
+ 
diff --git a/tests/input/SSC-ABSTRACT.txt b/tests/input/SSC-ABSTRACT.txt
new file mode 100644
index 00000000..a73909bc
--- /dev/null
+++ b/tests/input/SSC-ABSTRACT.txt
@@ -0,0 +1 @@
+The Solar System is the gravitationally bound system of the Sun and the objects that orbit it, either directly or indirectly. Of the objects that orbit the Sun directly, the largest are the eight planets, with the remainder being smaller objects, the dwarf planets and small Solar System bodies. Of the objects that orbit the Sun indirectly—the natural satellites—two are larger than the smallest planet, Mercury, and one more almost equals it in size. The Solar System formed 4.6 billion years ago from the gravitational collapse of a giant interstellar molecular cloud. The vast majority of the system's mass is in the Sun, with the majority of the remaining mass contained in Jupiter. The four smaller inner system planets, Mercury, Venus, Earth and Mars, are terrestrial planets, being primarily composed of rock and metal. The four outer system planets are giant planets, being substantially more massive than the terrestrials. The two largest planets, Jupiter and Saturn, are gas giants, being composed mainly of hydrogen and helium; the two outermost planets, Uranus and Neptune, are ice giants, being composed mostly of substances with relatively high melting points compared with hydrogen and helium, called volatiles, such as water, ammonia and methane. All eight planets have almost circular orbits that lie within a nearly flat disc called the ecliptic. The Solar System also contains smaller objects. The asteroid belt, which lies between the orbits of Mars and Jupiter, mostly contains objects composed, like the terrestrial planets, of rock and metal. Beyond Neptune's orbit lie the Kuiper belt and scattered disc, which are populations of trans-Neptunian objects composed mostly of ices, and beyond them a newly discovered population of sednoids. Within these populations, some objects are large enough to have rounded under their own gravity, though there is considerable debate as to how many there will prove to be. Such objects are categorized as dwarf planets. Astronomers generally accept at least nine objects as dwarf planets: the asteroid Ceres and the trans-Neptunian objects Pluto, Eris, Haumea, Makemake, Gonggong, Quaoar, Sedna, and Orcus. In addition to these two regions, various other small-body populations, including comets, centaurs and interplanetary dust clouds, freely travel between regions. Six of the planets, the six largest possible dwarf planets, and many of the smaller bodies are orbited by natural satellites, usually termed "moons" after the Moon. Each of the outer planets is encircled by planetary rings of dust and other small objects. The solar wind, a stream of charged particles flowing outwards from the Sun, creates a bubble-like region in the interstellar medium known as the heliosphere. The heliopause is the point at which pressure from the solar wind is equal to the opposing pressure of the interstellar medium; it extends out to the edge of the scattered disc. The Oort cloud, which is thought to be the source for long-period comets, may also exist at a distance roughly a thousand times further than the heliosphere. The Solar System is located 26,000 light-years from the center of the Milky Way galaxy in the Orion Arm, which contains most of the visible stars in the night sky. The nearest stars are within the so-called Local Bubble, with the closest, Proxima Centauri, at 4.25 light-years. (en)
diff --git a/tests/input/test.txt b/tests/input/test.txt
new file mode 100644
index 00000000..79bd7b50
--- /dev/null
+++ b/tests/input/test.txt
@@ -0,0 +1 @@
+The sun is a star. Earth is a planet.
diff --git a/tests/test_amrbatch_main.py b/tests/test_amrbatch_main.py
new file mode 100644
index 00000000..f5d67831
--- /dev/null
+++ b/tests/test_amrbatch_main.py
@@ -0,0 +1,45 @@
+#!/usr/bin/python3.10
+# -*-coding:Utf-8 -*
+
+#==============================================================================
+# AMR Batch: Main Test Running Script 
+#------------------------------------------------------------------------------
+# Script to run the document parsing for main test.
+#==============================================================================
+
+import subprocess, os
+from datetime import datetime
+
+FILE_PATH = f'{os.path.dirname(os.path.abspath(__file__))}'
+INPUT_DIR_PATH = f'{FILE_PATH}/input/'
+OUTPUT_DIR_PATH = f'{FILE_PATH}/output/'
+
+from context import amrbatch
+
+
+   
+#==============================================================================
+# Input / Output Data
+#==============================================================================
+
+# -- Input Data
+amrld_file_path = f'{INPUT_DIR_PATH}test.txt'
+
+
+# -- Output references
+base_output_name = f'Test'
+time_ref = f'{datetime.now().strftime("%Y%m%d")}'
+out_dir_path = f'{OUTPUT_DIR_PATH}{base_output_name}-{time_ref}/'
+os.makedirs(out_dir_path, exist_ok=True)
+penman_output_file = f'{base_output_name}.pnm'
+turtle_output_file = f'{base_output_name}.ttl'
+
+
+
+#==============================================================================
+# Parsing using amrbatch main method
+#==============================================================================
+
+# -- Parsing from a file
+amrbatch.parsing_sentences_from_file(
+    input_file_path, penman_output_file=None, turtle_output_file=None)
-- 
GitLab