Repository: aehrc/VariantSpark (language: python)

Issue:
Align python code formatting between pylind and inteliJ



Discussion / hints:

Fix patch:
diff --git a/python/docs/conf.py b/python/docs/conf.py
index fdd34320..406c532e 100644
--- a/python/docs/conf.py
+++ b/python/docs/conf.py
@@ -12,8 +12,8 @@
 # All configuration values have a default; values that are commented out
 # serve to show the default.
 
-import sys
 import os
+import sys
 
 # add python sources and dependecies to the list
 # This is need for read the docs to pickup the sources without instaalling the package.
@@ -25,12 +25,12 @@
 # If extensions (or modules to document with autodoc) are in another directory,
 # add these directories to sys.path here. If the directory is relative to the
 # documentation root, use os.path.abspath to make it absolute, like shown here.
-#sys.path.insert(0, os.path.abspath('.'))
+# sys.path.insert(0, os.path.abspath('.'))
 
 # -- General configuration ------------------------------------------------
 
 # If your documentation needs a minimal Sphinx version, state it here.
-#needs_sphinx = '1.0'
+# needs_sphinx = '1.0'
 
 # Add any Sphinx extension module names here, as strings. They can be
 # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
@@ -51,7 +51,7 @@
 source_suffix = '.rst'
 
 # The encoding of source files.
-#source_encoding = 'utf-8-sig'
+# source_encoding = 'utf-8-sig'
 
 # The master toctree document.
 master_doc = 'index'
@@ -79,9 +79,9 @@
 
 # There are two options for replacing |today|: either, you set today to some
 # non-false value, then it is used:
-#today = ''
+# today = ''
 # Else, today_fmt is used as the format for a strftime call.
-#today_fmt = '%B %d, %Y'
+# today_fmt = '%B %d, %Y'
 
 # List of patterns, relative to source directory, that match files and
 # directories to ignore when looking for source files.
@@ -89,32 +89,31 @@
 
 # The reST default role (used for this markup: `text`) to use for all
 # documents.
-#default_role = None
+# default_role = None
 
 # If true, '()' will be appended to :func: etc. cross-reference text.
-#add_function_parentheses = True
+# add_function_parentheses = True
 
 # If true, the current module name will be prepended to all description
 # unit titles (such as .. function::).
-#add_module_names = True
+# add_module_names = True
 
 # If true, sectionauthor and moduleauthor directives will be shown in the
 # output. They are ignored by default.
-#show_authors = False
+# show_authors = False
 
 # The name of the Pygments (syntax highlighting) style to use.
 pygments_style = 'sphinx'
 
 # A list of ignored prefixes for module index sorting.
-#modindex_common_prefix = []
+# modindex_common_prefix = []
 
 # If true, keep warnings as "system message" paragraphs in the built documents.
-#keep_warnings = False
+# keep_warnings = False
 
 # If true, `todo` and `todoList` produce output, else they produce nothing.
 todo_include_todos = False
 
-
 # -- Options for HTML output ----------------------------------------------
 
 # The theme to use for HTML and HTML Help pages.  See the documentation for
@@ -124,26 +123,26 @@
 # Theme options are theme-specific and customize the look and feel of a theme
 # further.  For a list of options available for each theme, see the
 # documentation.
-#html_theme_options = {}
+# html_theme_options = {}
 
 # Add any paths that contain custom themes here, relative to this directory.
-#html_theme_path = []
+# html_theme_path = []
 
 # The name for this set of Sphinx documents.  If None, it defaults to
 # "<project> v<release> documentation".
-#html_title = None
+# html_title = None
 
 # A shorter title for the navigation bar.  Default is the same as html_title.
-#html_short_title = None
+# html_short_title = None
 
 # The name of an image file (relative to this directory) to place at the top
 # of the sidebar.
-#html_logo = None
+# html_logo = None
 
 # The name of an image file (within the static path) to use as favicon of the
 # docs.  This file should be a Windows icon file (.ico) being 16x16 or 32x32
 # pixels large.
-#html_favicon = None
+# html_favicon = None
 
 # Add any paths that contain custom static files (such as style sheets) here,
 # relative to this directory. They are copied after the builtin static files,
@@ -153,62 +152,62 @@
 # Add any extra paths that contain custom files (such as robots.txt or
 # .htaccess) here, relative to this directory. These files are copied
 # directly to the root of the documentation.
-#html_extra_path = []
+# html_extra_path = []
 
 # If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
 # using the given strftime format.
-#html_last_updated_fmt = '%b %d, %Y'
+# html_last_updated_fmt = '%b %d, %Y'
 
 # If true, SmartyPants will be used to convert quotes and dashes to
 # typographically correct entities.
-#html_use_smartypants = True
+# html_use_smartypants = True
 
 # Custom sidebar templates, maps document names to template names.
-#html_sidebars = {}
+# html_sidebars = {}
 
 # Additional templates that should be rendered to pages, maps page names to
 # template names.
-#html_additional_pages = {}
+# html_additional_pages = {}
 
 # If false, no module index is generated.
-#html_domain_indices = True
+# html_domain_indices = True
 
 # If false, no index is generated.
-#html_use_index = True
+# html_use_index = True
 
 # If true, the index is split into individual pages for each letter.
-#html_split_index = False
+# html_split_index = False
 
 # If true, links to the reST sources are added to the pages.
-#html_show_sourcelink = True
+# html_show_sourcelink = True
 
 # If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
-#html_show_sphinx = True
+# html_show_sphinx = True
 
 # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
-#html_show_copyright = True
+# html_show_copyright = True
 
 # If true, an OpenSearch description file will be output, and all pages will
 # contain a <link> tag referring to it.  The value of this option must be the
 # base URL from which the finished HTML is served.
-#html_use_opensearch = ''
+# html_use_opensearch = ''
 
 # This is the file name suffix for HTML files (e.g. ".xhtml").
-#html_file_suffix = None
+# html_file_suffix = None
 
 # Language to be used for generating the HTML full-text search index.
 # Sphinx supports the following languages:
 #   'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja'
 #   'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr'
-#html_search_language = 'en'
+# html_search_language = 'en'
 
 # A dictionary with options for the search language support, empty by default.
 # Now only 'ja' uses this config value
-#html_search_options = {'type': 'default'}
+# html_search_options = {'type': 'default'}
 
 # The name of a javascript file (relative to the configuration directory) that
 # implements a search results scorer. If empty, the default will be used.
-#html_search_scorer = 'scorer.js'
+# html_search_scorer = 'scorer.js'
 
 # Output file base name for HTML help builder.
 htmlhelp_basename = 'VariantSdoc'
@@ -216,17 +215,17 @@
 # -- Options for LaTeX output ---------------------------------------------
 
 latex_elements = {
-# The paper size ('letterpaper' or 'a4paper').
-#'papersize': 'letterpaper',
+    # The paper size ('letterpaper' or 'a4paper').
+    # 'papersize': 'letterpaper',
 
-# The font size ('10pt', '11pt' or '12pt').
-#'pointsize': '10pt',
+    # The font size ('10pt', '11pt' or '12pt').
+    # 'pointsize': '10pt',
 
-# Additional stuff for the LaTeX preamble.
-#'preamble': '',
+    # Additional stuff for the LaTeX preamble.
+    # 'preamble': '',
 
-# Latex figure (float) alignment
-#'figure_align': 'htbp',
+    # Latex figure (float) alignment
+    # 'figure_align': 'htbp',
 }
 
 # Grouping the document tree into LaTeX files. List of tuples
@@ -239,23 +238,23 @@
 
 # The name of an image file (relative to this directory) to place at the top of
 # the title page.
-#latex_logo = None
+# latex_logo = None
 
 # For "manual" documents, if this is true, then toplevel headings are parts,
 # not chapters.
-#latex_use_parts = False
+# latex_use_parts = False
 
 # If true, show page references after internal links.
-#latex_show_pagerefs = False
+# latex_show_pagerefs = False
 
 # If true, show URL addresses after external links.
-#latex_show_urls = False
+# latex_show_urls = False
 
 # Documents to append as an appendix to all manuals.
-#latex_appendices = []
+# latex_appendices = []
 
 # If false, no module index is generated.
-#latex_domain_indices = True
+# latex_domain_indices = True
 
 
 # -- Options for manual page output ---------------------------------------
@@ -268,7 +267,7 @@
 ]
 
 # If true, show URL addresses after external links.
-#man_show_urls = False
+# man_show_urls = False
 
 
 # -- Options for Texinfo output -------------------------------------------
@@ -283,13 +282,13 @@
 ]
 
 # Documents to append as an appendix to all manuals.
-#texinfo_appendices = []
+# texinfo_appendices = []
 
 # If false, no module index is generated.
-#texinfo_domain_indices = True
+# texinfo_domain_indices = True
 
 # How to display URL addresses: 'footnote', 'no', or 'inline'.
-#texinfo_show_urls = 'footnote'
+# texinfo_show_urls = 'footnote'
 
 # If true, do not generate a @detailmenu in the "Top" node's menu.
-#texinfo_no_detailmenu = False
+# texinfo_no_detailmenu = False
diff --git a/python/docs/index.rst b/python/docs/index.rst
index 338b154d..331a3bef 100644
--- a/python/docs/index.rst
+++ b/python/docs/index.rst
@@ -1,7 +1,7 @@
 .. VariantS documentation master file, created by
-   sphinx-quickstart on Fri Nov 17 15:37:37 2017.
-   You can adapt this file completely to your liking, but it should at least
-   contain the root `toctree` directive.
+sphinx-quickstart on Fri Nov 17 15:37:37 2017.
+You can adapt this file completely to your liking, but it should at least
+contain the root `toctree` directive.
 
 =======================================
 Welcome to variant-spark documentation!
diff --git a/python/examples/chr21_GRCh38_hail.py b/python/examples/chr21_GRCh38_hail.py
index 6d969c70..f3620ef3 100755
--- a/python/examples/chr21_GRCh38_hail.py
+++ b/python/examples/chr21_GRCh38_hail.py
@@ -5,29 +5,31 @@
 @author: szu004
 '''
 import os
-import pkg_resources
+
 import hail as hl
-import varspark as vs
+
 import varspark.hail as vshl
-from pyspark.sql import SparkSession
 
-PROJECT_DIR=os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, os.pardir))
+PROJECT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, os.pardir))
+
 
 def main():
     vshl.init()
-    print("Version info:") 
-    for (k,v) in vshl.version_info().items():
-       print("%s=%s" % (k,v))
+    print("Version info:")
+    for (k, v) in vshl.version_info().items():
+        print("%s=%s" % (k, v))
 
-    data = hl.import_vcf(os.path.join(PROJECT_DIR, 'data/chr22_1000_GRCh38.vcf'), reference_genome='GRCh38')
-    labels = hl.import_table(os.path.join(PROJECT_DIR, 'data/chr22-labels-hail.csv'), delimiter=',', 
-            types={'x22_16050408':'float64'}).key_by('sample')
+    data = hl.import_vcf(os.path.join(PROJECT_DIR, 'data/chr22_1000_GRCh38.vcf'),
+                         reference_genome='GRCh38')
+    labels = hl.import_table(os.path.join(PROJECT_DIR, 'data/chr22-labels-hail.csv'), delimiter=',',
+                             types={'x22_16050408': 'float64'}).key_by('sample')
 
-    mt = data.annotate_cols(hipster = labels[data.s])
+    mt = data.annotate_cols(hipster=labels[data.s])
     print(mt.count())
-    
+
     rf_model = vshl.random_forest_model(y=mt.hipster.x22_16050408,
-                    x=mt.GT.n_alt_alleles(), seed = 13, mtry_fraction = 0.05, min_node_size = 5, max_depth = 10)
+                                        x=mt.GT.n_alt_alleles(), seed=13, mtry_fraction=0.05,
+                                        min_node_size=5, max_depth=10)
     rf_model.fit_trees(100, 50)
 
     print("OOB error: %s" % rf_model.oob_error())
@@ -38,6 +40,6 @@ def main():
 
     rf_model.release()
 
+
 if __name__ == '__main__':
     main()
-
diff --git a/python/examples/chr21_missing_hail.py b/python/examples/chr21_missing_hail.py
index 68501de5..408074fb 100755
--- a/python/examples/chr21_missing_hail.py
+++ b/python/examples/chr21_missing_hail.py
@@ -5,27 +5,27 @@
 @author: szu004
 '''
 import os
-import pkg_resources
+
 import hail as hl
-import varspark as vs
+
 import varspark.hail as vshl
-from pyspark.sql import SparkSession
 
-PROJECT_DIR=os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, os.pardir))
+PROJECT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, os.pardir))
+
 
 def main():
     vshl.init()
-    
+
     data = hl.import_vcf(os.path.join(PROJECT_DIR, 'data/chr22_1000_missing.vcf'))
-    labels = hl.import_table(os.path.join(PROJECT_DIR, 'data/chr22-labels-hail.csv'), delimiter=',', 
-            types={'x22_16050408':'float64'}).key_by('sample')
+    labels = hl.import_table(os.path.join(PROJECT_DIR, 'data/chr22-labels-hail.csv'), delimiter=',',
+                             types={'x22_16050408': 'float64'}).key_by('sample')
 
-    mt = data.annotate_cols(hipster = labels[data.s])
+    mt = data.annotate_cols(hipster=labels[data.s])
     print(mt.count())
-    
+
     rf_model = vshl.random_forest_model(y=mt.hipster.x22_16050408,
-                    x=mt.GT.n_alt_alleles(), seed = 13, mtry_fraction = 0.05,
-                    min_node_size = 5, max_depth = 10, imputation_type = "mode")
+                                        x=mt.GT.n_alt_alleles(), seed=13, mtry_fraction=0.05,
+                                        min_node_size=5, max_depth=10, imputation_type="mode")
     rf_model.fit_trees(100, 50)
 
     print("OOB error: %s" % rf_model.oob_error())
@@ -36,6 +36,6 @@ def main():
 
     rf_model.release()
 
+
 if __name__ == '__main__':
     main()
-
diff --git a/python/examples/hipster_index.py b/python/examples/hipster_index.py
index cd3ea6dd..105a1703 100644
--- a/python/examples/hipster_index.py
+++ b/python/examples/hipster_index.py
@@ -4,25 +4,28 @@
 @author: szu004
 '''
 import os
-from varspark import VariantsContext
+
 from pyspark.sql import SparkSession
 
-PROJECT_DIR=os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, os.pardir))
+from varspark import VariantsContext
+
+PROJECT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, os.pardir))
+
 
 def main():
     print(VariantsContext.spark_conf())
-    spark = SparkSession.builder\
+    spark = SparkSession.builder \
         .config(conf=VariantsContext.spark_conf()) \
         .appName("HipsterIndex") \
         .getOrCreate()
     vs = VariantsContext(spark)
     features = vs.import_vcf(os.path.join(PROJECT_DIR, 'data/chr22_1000.vcf'))
-    labels = vs.load_label(os.path.join(PROJECT_DIR,'data/chr22-labels.csv'), '22_16050408')
-    model  = features.importance_analysis(labels, mtry_fraction = 0.1, seed = 13, n_trees = 200)
+    labels = vs.load_label(os.path.join(PROJECT_DIR, 'data/chr22-labels.csv'), '22_16050408')
+    model = features.importance_analysis(labels, mtry_fraction=0.1, seed=13, n_trees=200)
     print("Oob = %s" % model.oob_error())
     for entry in model.important_variables(10):
         print(entry)
-        
+
+
 if __name__ == '__main__':
     main()
-
diff --git a/python/examples/hipster_index_hail.py b/python/examples/hipster_index_hail.py
index 5954f73e..403c66aa 100755
--- a/python/examples/hipster_index_hail.py
+++ b/python/examples/hipster_index_hail.py
@@ -7,6 +7,7 @@
 import os
 
 import hail as hl
+
 import varspark.hail as vshl
 
 PROJECT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, os.pardir))
diff --git a/python/setup.py b/python/setup.py
index 0993af28..1f963a84 100644
--- a/python/setup.py
+++ b/python/setup.py
@@ -1,21 +1,19 @@
 from __future__ import print_function
-from setuptools import setup, find_packages
-import sys
-import os
+
 import glob
+import os
+import sys
 
-if sys.version_info < (2, 7):
-    print("Python versions prior to 2.7 are not supported.", file=sys.stderr)
-    exit(-1)
+from setuptools import setup, find_packages
 
 HERE = os.path.dirname(__file__)
 ROOT_DIR = os.path.abspath(os.path.join(HERE, os.pardir))
 TEMP_PATH = "target"
 
 in_src = os.path.isfile(os.path.join(ROOT_DIR, "pom.xml"))
-        
+
 VERSION = '0.4.0dev1'
-    
+
 # Provide guidance about how to use setup.py
 incorrect_invocation_message = """
 If you are installing varspark from variant-spark source, you must first build variant-spark  and
@@ -28,18 +26,19 @@
       pip install dist/*.tar.gz"""
 
 
-
 def src_path(src_dir):
     return os.path.join(ROOT_DIR, src_dir)
 
+
 def dst_path(dst_dir):
     return os.path.join(TEMP_PATH, dst_dir)
 
+
 EXT_DIRS = [
     ('target', 'jars'),
     ('bin', 'bin'),
-    ('examples','examples'),    
-    ('data','data')    
+    ('examples', 'examples'),
+    ('data', 'data')
 ]
 
 if (in_src):
@@ -51,30 +50,30 @@ def dst_path(dst_dir):
               file=sys.stderr)
         exit(-1)
 
-
 try:
-        
+
     if (in_src):
         # Construct the symlink farm - this is necessary since we can't refer to the path above the
         # package root and we need to copy the jars and scripts which are up above the python root.
-        for (src_dir,dst_dir) in EXT_DIRS:
+        for (src_dir, dst_dir) in EXT_DIRS:
             os.symlink(src_path(src_dir), dst_path(dst_dir))
 
     setup(
         name='variant-spark',
-        version= VERSION,    
-        packages=find_packages(exclude=["*.test"]) + ['varspark.jars'], 
+        version=VERSION,
+        packages=find_packages(exclude=["*.test"]) + ['varspark.jars'],
+        python_requires=">=3.6",
         install_requires=[
             'typedecorator==0.0.5'
         ],
-        extras_require = {
-            'deps': [ 
+        extras_require={
+            'deps': [
                 'pandas>=0.25.0',
             ],
-            'spark': [ 
+            'spark': [
                 'pyspark>=2.4.1',
             ],
-            'test': [ 
+            'test': [
                 'pyspark>=2.4.1',
             ],
             'hail': [
@@ -88,12 +87,13 @@ def dst_path(dst_dir):
         package_data={
             'varspark.jars': ['*-all.jar'],
         },
-        data_files = [
-            ('share/variant-spark/examples', glob.glob(os.path.join(dst_path('examples'),'*'))),
-            ('share/variant-spark/data', [ p for p in glob.glob(os.path.join(dst_path('data'),'*')) if not os.path.isdir(p)]),
+        data_files=[
+            ('share/variant-spark/examples', glob.glob(os.path.join(dst_path('examples'), '*'))),
+            ('share/variant-spark/data',
+             [p for p in glob.glob(os.path.join(dst_path('data'), '*')) if not os.path.isdir(p)]),
         ],
-        scripts = [
-            'target/bin/variant-spark',                   
+        scripts=[
+            'target/bin/variant-spark',
             'target/bin/jvariant-spark',
             'target/bin/find-varspark-jar',
         ],
@@ -105,20 +105,20 @@ def dst_path(dst_dir):
         # metadata for upload to PyPI
         description='VariantSpark Python API',
         long_description=("variant-spark is a scalable toolkit for "
-                        "genome-wide association studies optimized for GWAS like datasets"),
+                          "genome-wide association studies optimized for GWAS like datasets"),
         author='Piotr Szul et. al',
         author_email='piotr.szul@csiro.au',
         license='CSIRO Non-Commercial Source Code Licence Agreement v1.0',
         keywords='gwas vcf random forest association studies variant',
         classifiers=[
             'Development Status :: 2 - Pre-Alpha',
-    
+
             'Intended Audience :: Science/Research',
             'Topic :: Scientific/Engineering :: Bio-Informatics',
-    
-            "Programming Language :: Python :: 2.7"
+
+            "Programming Language :: Python :: 3.6"
         ],
-        url='https://bioinformatics.csiro.au/variantspark',   # project home page, if any
+        url='https://bioinformatics.csiro.au/variantspark',  # project home page, if any
         project_urls={
             'Bug Tracker': 'https://github.com/aehrc/VariantSpark/issues',
             'Documentation': 'http://variantspark.readthedocs.io/en/latest',
@@ -130,6 +130,6 @@ def dst_path(dst_dir):
     # packaging.
     if (in_src):
         # Depending on cleaning up the symlink farm or copied version
-        for (src_dir,dst_dir) in EXT_DIRS:
+        for (src_dir, dst_dir) in EXT_DIRS:
             os.remove(dst_path(dst_dir))
         os.rmdir(TEMP_PATH)
diff --git a/python/varspark/__init__.py b/python/varspark/__init__.py
index a56c0237..0072c08c 100644
--- a/python/varspark/__init__.py
+++ b/python/varspark/__init__.py
@@ -1,4 +1,5 @@
 import os
+
 try:
     from varspark.core import VarsparkContext, VariantsContext
 except Exception:
diff --git a/python/varspark/cli.py b/python/varspark/cli.py
index ce7cd31c..57249e9d 100644
--- a/python/varspark/cli.py
+++ b/python/varspark/cli.py
@@ -1,16 +1,13 @@
-# Ensure backwards compatibility with Python 2
-from __future__ import (
-    absolute_import,
-    division,
-    print_function)
-
 import subprocess
 import sys
+
 from varspark import find_jar
 
+
 def varspark_jar():
     print(find_jar())
 
+
 def varspark_submit():
     args = ['spark-submit', '--jars', find_jar()] + sys.argv[1:]
-    sys.exit(subprocess.call(" ".join(["'%s'"%arg for arg in args]), shell=True))
+    sys.exit(subprocess.call(" ".join(["'%s'" % arg for arg in args]), shell=True))
diff --git a/python/varspark/core.py b/python/varspark/core.py
index f6b1cb37..ae8ee9ae 100644
--- a/python/varspark/core.py
+++ b/python/varspark/core.py
@@ -1,19 +1,12 @@
-# Ensure backwards compatibility with Python 2
-from __future__ import (
-    absolute_import,
-    division,
-    print_function)
-
 import sys
 from random import randint
-from typedecorator import params, Nullable, Union, setup_typecheck
+
 from pyspark import SparkConf
 from pyspark.sql import SQLContext
-from varspark.etc import find_jar
-from varspark import java
+from typedecorator import params, Nullable, setup_typecheck
 
-if sys.version_info > (3,):
-    long = int
+from varspark import java
+from varspark.etc import find_jar
 
 
 class VarsparkContext(object):
@@ -21,13 +14,13 @@ class VarsparkContext(object):
     """
 
     @classmethod
-    def spark_conf(cls, conf  = SparkConf()):
+    def spark_conf(cls, conf=SparkConf()):
         """ Adds the necessary option to the spark configuration.
         Note: In client mode these need to be setup up using --jars or --driver-class-path
         """
         return conf.set("spark.jars", find_jar())
 
-    def __init__(self, ss, silent = False):
+    def __init__(self, ss, silent=False):
         """The main entry point for VariantSpark functionality.
         :param ss: SparkSession
         :type ss: :class:`.pyspark.SparkSession`
@@ -48,7 +41,7 @@ def __init__(self, ss, silent = False):
             sys.stderr.write('Running on Apache Spark version {}\n'.format(self.sc.version))
             if self.sc._jsc.sc().uiWebUrl().isDefined():
                 sys.stderr.write('SparkUI available at {}\n'.format(
-                        self.sc._jsc.sc().uiWebUrl().get()))
+                    self.sc._jsc.sc().uiWebUrl().get()))
             sys.stderr.write(
                 'Welcome to\n'
                 ' _    __           _             __  _____                  __    \n'
@@ -63,8 +56,8 @@ def import_vcf(self, vcf_file_path, min_partitions=0):
         """ Import features from a VCF file.
         """
         return FeatureSource(self._jvm, self._vs_api,
-                            self._jsql, self.sql, self._jvsc.importVCF(vcf_file_path,
-                            min_partitions))
+                             self._jsql, self.sql, self._jvsc.importVCF(vcf_file_path,
+                                                                        min_partitions))
 
     @params(self=object, label_file_path=str, col_name=str)
     def load_label(self, label_file_path, col_name):
@@ -82,6 +75,7 @@ def stop(self):
         self.sc.stop()
         self.sc = None
 
+
 # Deprecated
 VariantsContext = VarsparkContext
 
@@ -96,7 +90,7 @@ def __init__(self, _jvm, _vs_api, _jsql, sql, _jfs):
         self.sql = sql
 
     @params(self=object, label_source=object, n_trees=Nullable(int), mtry_fraction=Nullable(float),
-            oob=Nullable(bool), seed=Nullable(Union(int, long)), batch_size=Nullable(int),
+            oob=Nullable(bool), seed=Nullable(int), batch_size=Nullable(int),
             var_ordinal_levels=Nullable(int), max_depth=int, min_node_size=int)
     def importance_analysis(self, label_source, n_trees=1000, mtry_fraction=None,
                             oob=True, seed=None, batch_size=100, var_ordinal_levels=3,
@@ -107,17 +101,25 @@ def importance_analysis(self, label_source, n_trees=1000, mtry_fraction=None,
         :param int n_trees: The number of trees to build in the forest.
         :param float mtry_fraction: The fraction of variables to try at each split.
         :param bool oob: Should OOB error be calculated.
-        :param long seed: Random seed to use.
+        :param int seed: Random seed to use.
         :param int batch_size: The number of trees to build in one batch.
         :param int var_ordinal_levels:
 
         :return: Importance analysis model.
         :rtype: :py:class:`ImportanceAnalysis`
         """
-        jrf_params = self._jvm.au.csiro.variantspark.algo.RandomForestParams(bool(oob),
-                                java.jfloat_or(mtry_fraction), True, java.NAN, True,
-                                java.jlong_or(seed, randint(java.MIN_LONG, java.MAX_LONG)),
-                                max_depth, min_node_size, False, 0)
+        vs_algo = self._jvm.au.csiro.variantspark.algo
+        jrf_params = vs_algo.RandomForestParams(bool(oob),
+                                                java.jfloat_or(
+                                                    mtry_fraction),
+                                                True, java.NAN, True,
+                                                java.jlong_or(seed,
+                                                              randint(
+                                                                  java.MIN_LONG,
+                                                                  java.MAX_LONG)),
+                                                max_depth,
+                                                min_node_size, False,
+                                                0)
         jia = self._vs_api.ImportanceAnalysis(self._jsql, self._jfs, label_source,
                                               jrf_params, n_trees, batch_size, var_ordinal_levels)
         return ImportanceAnalysis(jia, self.sql)
diff --git a/python/varspark/etc.py b/python/varspark/etc.py
index 95b7e39d..ac2d91a8 100644
--- a/python/varspark/etc.py
+++ b/python/varspark/etc.py
@@ -1,13 +1,9 @@
-# Ensure backwards compatibility with Python 2
-from __future__ import (
-    absolute_import,
-    division,
-    print_function)
-
 import glob
 import os
+
 import pkg_resources
 
+
 def find_jar():
     """Gets the path to the variant spark jar bundled with the
     python distribution
@@ -15,7 +11,9 @@ def find_jar():
     # try to find the distribution jars first
     jars_dir = pkg_resources.resource_filename(__name__, "jars")
     if not os.path.isdir(jars_dir):
-        #then it can be an develoment install
+        # then it can be an develoment install
         jars_dir = os.path.abspath(pkg_resources.resource_filename(__name__,
-                                            os.path.join(os.pardir, os.pardir, "target")))
+                                                                   os.path.join(os.pardir,
+                                                                                os.pardir,
+                                                                                "target")))
     return glob.glob(os.path.join(jars_dir, "*-all.jar"))[0]
diff --git a/python/varspark/hail/__init__.py b/python/varspark/hail/__init__.py
index 06fdd0d9..484869a4 100644
--- a/python/varspark/hail/__init__.py
+++ b/python/varspark/hail/__init__.py
@@ -1,14 +1,3 @@
-'''
-Created on 7 Nov 2017
-
-@author: szu004
-'''
-# Ensure backwards compatibility with Python 2
-from __future__ import (
-    absolute_import,
-    division,
-    print_function)
-
 from hail.backend.spark_backend import SparkBackend
 
 from .context import init, version_info, version
diff --git a/python/varspark/hail/hail.py b/python/varspark/hail/hail.py
index 5f95a7a0..3f464a89 100644
--- a/python/varspark/hail/hail.py
+++ b/python/varspark/hail/hail.py
@@ -1,18 +1,18 @@
 import os
 import sys
 
+import pkg_resources
+import pyspark
 from hail.backend.spark_backend import install_exception_handler, connect_logger, \
     __name__ as __hail_name__
 from hail.utils.java import scala_package_object
-import pkg_resources
-import pyspark
 
 
 #
 # This is a customised version of the constructor honoring spark.jars passed in
 # spark_config
 #
-#pylint: disable=C0415
+# pylint: disable=C0415
 
 def SparkBackend__init__(self, idempotent, sc, spark_conf, app_name, master,
                          local, log, quiet, append, min_block_size,
diff --git a/python/varspark/hail/methods.py b/python/varspark/hail/methods.py
index 872df9a2..822517b4 100644
--- a/python/varspark/hail/methods.py
+++ b/python/varspark/hail/methods.py
@@ -1,38 +1,22 @@
-'''
-Created on 7 Nov 2017
-
-@author: szu004
-'''
-# Ensure backwards compatibility with Python 2
-from __future__ import (
-    absolute_import,
-    division,
-    print_function)
-
-
-
-from typing import *
 from hail.expr.expressions import *
-from hail.expr.types import *
 from hail.typecheck import *
-from hail.ir import *
-from hail.table import Table
+
 from . import rf
 
-@typecheck(
-        y=expr_float64,
-        x=expr_int32,
-        covariates=sequenceof(expr_float64),
-        oob=bool,
-        mtry_fraction=nullable(float),
-        min_node_size=nullable(int),
-        max_depth=nullable(int),
-        seed=nullable(int),
-        imputation_type=nullable(str)
-        )
 
+@typecheck(
+    y=expr_float64,
+    x=expr_int32,
+    covariates=sequenceof(expr_float64),
+    oob=bool,
+    mtry_fraction=nullable(float),
+    min_node_size=nullable(int),
+    max_depth=nullable(int),
+    seed=nullable(int),
+    imputation_type=nullable(str)
+)
 def random_forest_model(y, x, covariates=(), oob=True, mtry_fraction=None,
-    min_node_size = None, max_depth=None, seed=None, imputation_type=None):
+                        min_node_size=None, max_depth=None, seed=None, imputation_type=None):
     """Creates an empty random forest classifier with specified parameters.
 
     :param Float64Expression y:  Column-indexed response expressions.
@@ -42,7 +26,7 @@ def random_forest_model(y, x, covariates=(), oob=True, mtry_fraction=None,
     :param float mtry_fraction: The fraction of variables to try at each split.
     :param int min_node_size: The minimum number of samples in a node to be consider for splitting.
     :param int max_depth: The maximum depth of the trees to build.
-    :param long seed: Random seed to use.
+    :param int seed: Random seed to use.
     :param string imputation_type: Imputation type to use. Currently only "mode" is supported which performs
         basic replacement of missing values with the mode of non missing values. If not provided and input containts
         missing data an error is reported.
@@ -53,13 +37,13 @@ def random_forest_model(y, x, covariates=(), oob=True, mtry_fraction=None,
     mt = matrix_table_source('random_forest_model/x', x)
     check_entry_indexed('random_forest_model/x', x)
     mts = mt._select_all(col_exprs=dict(y=y),
-                        row_exprs=dict(),
-                        col_key=[],
-                        entry_exprs=dict(e=x))
+                         row_exprs=dict(),
+                         col_key=[],
+                         entry_exprs=dict(e=x))
     return rf.RandomForestModel(mts._mir,
-                        oob = oob,
-                        mtry_fraction=mtry_fraction,
-                        min_node_size = min_node_size,
-                        max_depth = max_depth,
-                        seed = seed,
-                        imputation_type = imputation_type)
+                                oob=oob,
+                                mtry_fraction=mtry_fraction,
+                                min_node_size=min_node_size,
+                                max_depth=max_depth,
+                                seed=seed,
+                                imputation_type=imputation_type)
diff --git a/python/varspark/hail/plot.py b/python/varspark/hail/plot.py
index c189a94b..17885a10 100644
--- a/python/varspark/hail/plot.py
+++ b/python/varspark/hail/plot.py
@@ -1,27 +1,12 @@
-from typing import *
-import warnings
-import math
-
-import collections
-import numpy as np
-import pandas as pd
-import bokeh
-import bokeh.io
-from bokeh.models import HoverTool, ColorBar, LogTicker, LogColorMapper, LinearColorMapper, CategoricalColorMapper, \
-    ColumnDataSource, BasicTicker, Plot, ColorMapper, CDSView, GroupFilter, Legend, LegendItem, Renderer, CustomJS, \
-    Select, Column, Span, DataRange1d, Slope
-from bokeh.plotting import figure
-from bokeh.transform import transform
-from bokeh.layouts import gridplot
-
-import hail
 from hail.plot.plots import *
 from hail.plot.plots import _collect_scatter_plot_data, _get_scatter_plot_elements
 
 
 @typecheck(pvals=expr_float64, locus=nullable(expr_locus()), title=nullable(str),
-           size=int, hover_fields=nullable(dictof(str, expr_any)), collect_all=bool, n_divisions=int, significance_line=nullable(numeric))
-def manhattan_imp(pvals, locus=None, title=None, size=4, hover_fields=None, collect_all=False, n_divisions=500, significance_line=5e-8):
+           size=int, hover_fields=nullable(dictof(str, expr_any)), collect_all=bool,
+           n_divisions=int, significance_line=nullable(numeric))
+def manhattan_imp(pvals, locus=None, title=None, size=4, hover_fields=None, collect_all=False,
+                  n_divisions=500, significance_line=5e-8):
     """Create a Manhattan plot. (https://en.wikipedia.org/wiki/Manhattan_plot)
 
     Parameters
@@ -58,7 +43,7 @@ def manhattan_imp(pvals, locus=None, title=None, size=4, hover_fields=None, coll
 
     hover_fields['locus'] = hail.str(locus)
 
-    #pvals = -hail.log10(pvals)
+    # pvals = -hail.log10(pvals)
 
     source_pd = _collect_scatter_plot_data(
         ('_global_locus', locus.global_position()),
@@ -71,8 +56,11 @@ def manhattan_imp(pvals, locus=None, title=None, size=4, hover_fields=None, coll
 
     observed_contigs = set(source_pd['_contig'])
     observed_contigs = [contig for contig in ref.contigs.copy() if contig in observed_contigs]
-    contig_ticks = hail.eval([hail.locus(contig, int(ref.lengths[contig]/2)).global_position() for contig in observed_contigs])
-    color_mapper = CategoricalColorMapper(factors=ref.contigs, palette= palette[:2] * int((len(ref.contigs)+1)/2))
+    contig_ticks = hail.eval(
+        [hail.locus(contig, int(ref.lengths[contig] / 2)).global_position() for contig in
+         observed_contigs])
+    color_mapper = CategoricalColorMapper(factors=ref.contigs,
+                                          palette=palette[:2] * int((len(ref.contigs) + 1) / 2))
 
     p = figure(title=title, x_axis_label='Chromosome', y_axis_label='Importance (gini)', width=1000)
     p, _, legend, _, _, _ = _get_scatter_plot_elements(
@@ -83,7 +71,8 @@ def manhattan_imp(pvals, locus=None, title=None, size=4, hover_fields=None, coll
     legend.visible = False
     p.xaxis.ticker = contig_ticks
     p.xaxis.major_label_overrides = dict(zip(contig_ticks, observed_contigs))
-    p.select_one(HoverTool).tooltips = [t for t in p.select_one(HoverTool).tooltips if not t[0].startswith('_')]
+    p.select_one(HoverTool).tooltips = [t for t in p.select_one(HoverTool).tooltips if
+                                        not t[0].startswith('_')]
 
     if significance_line is not None:
         p.renderers.append(Span(location=-math.log10(significance_line),
diff --git a/python/varspark/hail/rf.py b/python/varspark/hail/rf.py
index 976efadd..3d6e5e98 100644
--- a/python/varspark/hail/rf.py
+++ b/python/varspark/hail/rf.py
@@ -1,22 +1,6 @@
-'''
-Created on 10 Nov 2017
-
-@author: szu004
-'''
-# Ensure backwards compatibility with Python 2
-from __future__ import (
-    absolute_import,
-    division,
-    print_function)
-
-from typing import *
-from hail.expr.expressions import *
-from hail.expr.types import *
-from hail.typecheck import *
 from hail.ir import *
 from hail.table import Table
-
-from hail.utils import java
+from hail.typecheck import *
 from hail.utils.java import Env
 
 
diff --git a/python/varspark/java.py b/python/varspark/java.py
index f4bbf841..614ee6ef 100644
--- a/python/varspark/java.py
+++ b/python/varspark/java.py
@@ -1,32 +1,19 @@
-'''
-Created on 20 Jun 2018
+MAX_LONG = 9223372036854775807
+MIN_LONG = -9223372036854775808
 
-@author: szu004
-'''
-
-# Ensure backwards compatibility with Python 2
-from __future__ import (
-    absolute_import,
-    division,
-    print_function)
-
-import sys
-if sys.version_info > (3,):
-    long = int
-
-MAX_LONG =  long(9223372036854775807)
-MIN_LONG = long(-9223372036854775808)
-
-MAX_INT =  2147483647
+MAX_INT = 2147483647
 MIN_INT = -2147483648
 
 NAN = float('nan')
 
+
 def jtype_or(t, v, def_v):
     return t(def_v) if v is None else t(v)
 
-def jfloat_or(v, def_v = NAN):
+
+def jfloat_or(v, def_v=NAN):
     return jtype_or(float, v, def_v)
 
-def jlong_or (v, def_v ):
-    return jtype_or(long, v, def_v)
+
+def jlong_or(v, def_v):
+    return jtype_or(int, v, def_v)
diff --git a/python/varspark/lang.py b/python/varspark/lang.py
index 2ab8f673..706e336b 100644
--- a/python/varspark/lang.py
+++ b/python/varspark/lang.py
@@ -1,22 +1,14 @@
-'''
-Created on 10 Nov 2017
-
-@author: szu004
-'''
-# Ensure backwards compatibility with Python 2
-from __future__ import (
-    absolute_import,
-    division,
-    print_function)
-
 import inspect
 
+
 def merge_inits(*inits):
     def call_inits(self, *args, **kwargs):
         for init in inits:
             init(self, *args, **kwargs)
+
     return call_inits
 
+
 def extend_cls(cls, mixin):
     for name, method in inspect.getmembers(mixin, predicate=inspect.ismethod):
         if name == '__init__':
diff --git a/python/varspark/utils.py b/python/varspark/utils.py
index c5824917..4daf873b 100644
--- a/python/varspark/utils.py
+++ b/python/varspark/utils.py
@@ -1,17 +1,7 @@
-'''
-Created on 6 Dec 2017
-
-@author: szu004
-'''
-# Ensure backwards compatibility with Python 2
-from __future__ import (
-    absolute_import,
-    division,
-    print_function)
-
 import numpy as np
-from pyspark.mllib.linalg.distributed import IndexedRowMatrix, RowMatrix
 import pandas as pd
+from pyspark.mllib.linalg.distributed import IndexedRowMatrix, RowMatrix
+
 
 def dist_mat_to_array(dist_mat):
     """ Converts a (small) distributed  matrix to dense numpy narray
@@ -26,7 +16,8 @@ def dist_mat_to_array(dist_mat):
     else:
         raise Exception("Cannot convert distributed matrix of type %s" % type(dist_mat))
 
-def array_to_dataframe(ndarray, labels = None):
+
+def array_to_dataframe(ndarray, labels=None):
     """ Converts a square numpy array to a pandas dataframe with index and column names
     from labels (if provided)
 
@@ -34,10 +25,11 @@ def array_to_dataframe(ndarray, labels = None):
     :param labels: labels to use for the index and for the column names
     :return: a pandas dataframe
     """
-    return pd.DataFrame(ndarray, columns = labels, index = labels)
+    return pd.DataFrame(ndarray, columns=labels, index=labels)
 
-def array_to_dataframe_coord(ndarray, labels = None, triangular = True, include_diagonal = True,
-                                row_name = 'row', col_name = 'col', value_name = 'value'):
+
+def array_to_dataframe_coord(ndarray, labels=None, triangular=True, include_diagonal=True,
+                             row_name='row', col_name='col', value_name='value'):
     """ Converts a square numpy array to a pandas dataframe in coordinate format
     that is `[row, column, value]`. Optionally only includes the lower triangular matrix with
     or without diagonal (to get only unique coordinates)
@@ -53,10 +45,10 @@ def array_to_dataframe_coord(ndarray, labels = None, triangular = True, include_
     pdist_mat = np.array(ndarray)
     if triangular:
         pdist_mat[np.triu_indices(pdist_mat.shape[0], 1 if include_diagonal else 0)] = np.nan
-    pdist_df = array_to_dataframe(pdist_mat, labels = labels)
+    pdist_df = array_to_dataframe(pdist_mat, labels=labels)
     pdist_df[row_name] = pdist_df.index
-    return pd.melt(pdist_df, id_vars = [row_name], var_name = col_name,
-                        value_name = value_name).dropna()
+    return pd.melt(pdist_df, id_vars=[row_name], var_name=col_name,
+                   value_name=value_name).dropna()
 
 
 def kinship_mat_to_dataframe(km):
@@ -66,7 +58,8 @@ def kinship_mat_to_dataframe(km):
     :param km: kinship matrix to convert
     :return: dataframe with the values from the kinship matrix
     """
-    return array_to_dataframe(dist_mat_to_array(km.matrix()), labels = km.sample_list())
+    return array_to_dataframe(dist_mat_to_array(km.matrix()), labels=km.sample_list())
+
 
 def kinship_mat_to_dataframe_coord(km, **kwargs):
     """Converts a hail KinshipMatrix to a pandas dataframe. Coordinate values are
@@ -77,4 +70,4 @@ def kinship_mat_to_dataframe_coord(km, **kwargs):
     :return: dataframe with the values from the kinship matrix in the coordinate form
     """
     return array_to_dataframe_coord(dist_mat_to_array(km.matrix()),
-                                    labels = km.sample_list(), **kwargs)
+                                    labels=km.sample_list(), **kwargs)


Test patch:
diff --git a/python/varspark/test/__init__.py b/python/varspark/test/__init__.py
index e543e40a..f515dc9c 100644
--- a/python/varspark/test/__init__.py
+++ b/python/varspark/test/__init__.py
@@ -1,16 +1,11 @@
-# Ensure backwards compatibility with Python 2
-from __future__ import (
-    absolute_import,
-    division,
-    print_function)
-
-import os
 import glob
+import os
 
 THIS_DIR = os.path.dirname(os.path.abspath(__file__))
 PROJECT_DIR = os.path.abspath(os.path.join(THIS_DIR, os.pardir, os.pardir, os.pardir))
 
+
 def find_variants_jar():
-    jar_candidates = glob.glob(os.path.join(PROJECT_DIR, 'target','variant-spark_*-all.jar'))
+    jar_candidates = glob.glob(os.path.join(PROJECT_DIR, 'target', 'variant-spark_*-all.jar'))
     assert len(jar_candidates) == 1, "Expecting one jar, but found: %s" % str(jar_candidates)
     return jar_candidates[0]
diff --git a/python/varspark/test/test_core.py b/python/varspark/test/test_core.py
index 9d3caa6e..01f516d1 100644
--- a/python/varspark/test/test_core.py
+++ b/python/varspark/test/test_core.py
@@ -1,33 +1,24 @@
-# Ensure backwards compatibility with Python 2
-from __future__ import (
-    absolute_import,
-    division,
-    print_function)
-
 import os
-import sys
 import unittest
-import pytest
 
+import pytest
 from pyspark import SparkConf
 from pyspark.sql import SparkSession
 
 from varspark import VariantsContext
 from varspark.test import find_variants_jar, PROJECT_DIR
 
-if sys.version_info > (3,):
-    long = int
-
 THIS_DIR = os.path.dirname(os.path.abspath(__file__))
 
+
 @pytest.mark.spark
 class VariantSparkPySparkTestCase(unittest.TestCase):
 
     @classmethod
     def setUpClass(self):
-        sconf = SparkConf(loadDefaults=False)\
+        sconf = SparkConf(loadDefaults=False) \
             .set("spark.driver.extraClassPath", find_variants_jar())
-        spark = SparkSession.builder.config(conf=sconf)\
+        spark = SparkSession.builder.config(conf=sconf) \
             .appName("test").master("local").getOrCreate()
         self.sc = spark.sparkContext
 
@@ -35,6 +26,7 @@ def setUpClass(self):
     def tearDownClass(self):
         pass
 
+
 class VariantSparkAPITestCase(VariantSparkPySparkTestCase):
 
     def setUp(self):
diff --git a/python/varspark/test/test_hail.py b/python/varspark/test/test_hail.py
index 7447112c..14ba6e41 100644
--- a/python/varspark/test/test_hail.py
+++ b/python/varspark/test/test_hail.py
@@ -1,18 +1,19 @@
 import filecmp
 import os
 import unittest
-import yaml
-import pytest
 
 import hail as hl
 import numpy.testing as npt
 import pandas as pd
 import pandas.testing as pdt
+import pytest
+import yaml
 from pyspark.sql.functions import *
 
 import varspark.hail as vshl
 from varspark.test import PROJECT_DIR
 
+
 #
 # TODO: Add test cases for GRCh38 and missing data imputation
 #