{"title":"West Health Data Science Blog","link":[{"@attributes":{"href":"https:\/\/WestHealth.github.io\/","rel":"alternate"}},{"@attributes":{"href":"https:\/\/WestHealth.github.io\/feeds\/all.atom.xml","rel":"self"}}],"id":"https:\/\/WestHealth.github.io\/","updated":"2021-03-22T10:47:00-07:00","subtitle":"Applied Data Science to Lower Healthcare Costs for Successful Aging","entry":[{"title":"Visualizations with Dash Leaflet Series Part 2 - Basics - Review of Dash, Geopandas and Dash-Leaflet","link":{"@attributes":{"href":"https:\/\/WestHealth.github.io\/visualizations-with-dash-leaflet-series-part-2-basics-review-of-dash-geopandas-and-dash-leaflet.html","rel":"alternate"}},"published":"2021-03-22T10:47:00-07:00","updated":"2021-03-22T10:47:00-07:00","author":{"name":"Haw-minn Lu"},"id":"tag:westhealth.github.io,2021-03-22:\/visualizations-with-dash-leaflet-series-part-2-basics-review-of-dash-geopandas-and-dash-leaflet.html","summary":"<h1>Overview<\/h1>\n<p>In this section, we discuss geographic data handling, a brief overview of <code>dash<\/code> and introduce <code>dash-leaflet<\/code> in greater detail.  <\/p>\n<h2>Geographic Data Handling<\/h2>\n<h3>Where to get geographic data<\/h3>\n<p>There are two types of geographic data that we use in this tutorial, map data, and geometries. Map data is the underlying \u2026<\/p>","content":"<h1>Overview<\/h1>\n<p>In this section, we discuss geographic data handling, a brief overview of <code>dash<\/code> and introduce <code>dash-leaflet<\/code> in greater detail.  <\/p>\n<h2>Geographic Data Handling<\/h2>\n<h3>Where to get geographic data<\/h3>\n<p>There are two types of geographic data that we use in this tutorial, map data, and geometries. Map data is the underlying map used by Leaflet. In the section below where we discuss <code>dash-leaflet<\/code> we will go into greater detail, but the vast majority of maps have a basis in the <a href=\"https:\/\/www.openstreetmap.org\">open street map project<\/a>. The other category of geographic data, we refer to as geometries. These describe objects as points or boundaries. For example, a city may be represented by a latitude and longitude though technically cities have municipal boundaries and actually may span area. For the purposes of this tutorial, we will use the <code>uscities.csv<\/code> file obtained from <a href=\"https:\/\/simplemaps.com\/data\/us-cities\">simplemaps.com<\/a>, distributed under the <a href=\"https:\/\/creativecommons.org\/licenses\/by\/4.0\/\">Creative Commons Attribution 4.0<\/a>. They have a number of other geographic files that are free and distributed under that license. <\/p>\n<p>Another good resource is the <a href=\"https:\/\/www.census.gov\">US Census Bureau<\/a> which has almost every imaginable boundary file for the US at this <a href=\"https:\/\/www.census.gov\/geographies\/mapping-files\/time-series\/geo\/carto-boundary-file.html\">link<\/a>. However, the Census Bureau frequently reorganizes their site so an on-line search can be used should the provided link fail. The files are distributed in geographic information system (GIS) shapefiles and keyhole markup language (KML) files all together in a single zip file. They offer several resolutions for these depending on the detail desired. These files from the Census Bureau are do not have a copyright and do not necessarily require attribution, though it is always a good idea to give credit where credit is due and give attribution. For the purposes of this tutorial we will use the <code>cb_2018_us_county_20m.zip<\/code> file for county boundaries and <code>zip cb_2019_us_state_20m.zip<\/code> for state boundaries. The lowest resolution shapes are selected to reduce the memory footprint and processing required. For higher quality, use the 500k version of the files.<\/p>\n<h3>GeoPandas and Data Formats<\/h3>\n<p>We've already mentioned GIS shapefiles and KML files.  Now we introduce two more GeoJSON and Geobuf.  We won't get into the fine details on either of these, but <code>leaflet<\/code> supports the use of both of these. <a href=\"https:\/\/geojson.org\">GeoJSON<\/a> is a JSON file format for encoding a variety of geographic data structures. <a href=\"https:\/\/github.com\/mapbox\/geobuf[\">Geobuf<\/a> is a binary file format for encoding a variety of geographic data structures. Beyond know what they are for the purposes here, that's all that is needed.<\/p>\n<p>Fortunately, <code>geopandas<\/code> can read most geographic data files automatically. It can even read the zip files provided by the US Census Bureau without unzipping it.  So let's start by loading the county census shape file and examine the <code>geopanda<\/code> dataframe. <\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kn\">import<\/span> <span class=\"nn\">geopandas<\/span> <span class=\"k\">as<\/span> <span class=\"nn\">gpd<\/span>\n<span class=\"n\">zipfile<\/span> <span class=\"o\">=<\/span> <span class=\"s2\">&quot;zip:\/\/cb_2019_us_county_20m.zip&quot;<\/span>\n<span class=\"n\">gdf<\/span> <span class=\"o\">=<\/span> <span class=\"n\">gpd<\/span><span class=\"o\">.<\/span><span class=\"n\">read_file<\/span><span class=\"p\">(<\/span><span class=\"n\">zipfile<\/span><span class=\"p\">)<\/span>\n<span class=\"n\">gdf<\/span>\n<\/code><\/pre><\/div>\n\n<p>This dataframe looks and feels like a <code>pandas<\/code> dataframe, but you should note that there is a <code>geometry<\/code> column, which as some strangely formatted object. It is in fact a <code>shapely.geometry<\/code> object. For the purposes here, no deep knowledge of <code>shapely<\/code> or <code>geopandas<\/code> is needed. Suffice it to say that a <code>GeoDataFrame<\/code> is essentially a <code>pandas<\/code> <code>DataFrame<\/code> with that has a <code>geometry<\/code> column. In all other respects it behaves like a <code>pandas<\/code> <code>DataFrame<\/code> and most methods and tools operate in the same fashion.<\/p>\n<p>Turning to the other data file, <code>uscities.csv<\/code>, which does not explicitly have a geometry column, we also would like also like to convert it to a <code>geopandas<\/code> <code>GeoDataFrame<\/code>.  Upon inspection of the <code>csv<\/code> file, there is a latitude and longitude columns, <code>lat<\/code> and <code>lng<\/code> respectively.  The following snippet of code can convert it to a <code>geopandas<\/code> <code>GeoDataFrame<\/code>.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kn\">import<\/span> <span class=\"nn\">geopandas<\/span> <span class=\"k\">as<\/span> <span class=\"nn\">gpd<\/span>\n<span class=\"kn\">import<\/span> <span class=\"nn\">pandas<\/span> <span class=\"k\">as<\/span> <span class=\"nn\">pd<\/span>\n<span class=\"n\">df<\/span> <span class=\"o\">=<\/span> <span class=\"n\">pd<\/span><span class=\"o\">.<\/span><span class=\"n\">read_csv<\/span><span class=\"p\">(<\/span><span class=\"s1\">&#39;uscities.csv&#39;<\/span><span class=\"p\">)<\/span>\n<span class=\"n\">gdf<\/span> <span class=\"o\">=<\/span> <span class=\"n\">gpd<\/span><span class=\"o\">.<\/span><span class=\"n\">GeoDataFrame<\/span><span class=\"p\">(<\/span><span class=\"n\">df<\/span><span class=\"p\">,<\/span> <span class=\"n\">geometry<\/span><span class=\"o\">=<\/span><span class=\"n\">gpd<\/span><span class=\"o\">.<\/span><span class=\"n\">points_from_xy<\/span><span class=\"p\">(<\/span><span class=\"n\">df<\/span><span class=\"o\">.<\/span><span class=\"n\">lat<\/span><span class=\"p\">,<\/span> <span class=\"n\">df<\/span><span class=\"o\">.<\/span><span class=\"n\">lng<\/span><span class=\"p\">))<\/span>\n<\/code><\/pre><\/div>\n\n<p>The last line basically creates a <code>GeoDataFrame<\/code> from a <code>DataFrame<\/code> by adding a column <code>geometry<\/code> which converts pairs of values into a <code>shapely<\/code> point using the function <code>points_from_xy<\/code>. <\/p>\n<p>The choice of using <code>GeoDataFrame<\/code> is that is allows a powerful set of geographic and geometric tools on top of <code>pandas<\/code>. As we progress to our examples, two particular operations <code>bounds<\/code> and <code>centroid<\/code> will be important. It should be noted that the <code>dash-leaflet<\/code> documentation elects to do any data manipulation in <code>pandas<\/code> then uses <code>dash-leaflet.express<\/code> helpers to convert the an extracted <code>dict<\/code> to GeoJSON. using the <code>dict_to_geojson<\/code> helper function. Using <code>geopandas<\/code> allows you to skip this as <code>geopandas<\/code> can directly generate GeoJSON formatted data.<\/p>\n<p>Another helper function in <code>dash-leaflet.express<\/code> is <code>geojson_to_geobuf<\/code> which can be used to encode a GeoJSON structure into a Geobuf. Geobuf has the advantage of being a much more space efficient format.<\/p>\n<h2>Dash Basics<\/h2>\n<p>Dash is framework to build web applications and is especially good for developing analytic applications. It is built on <code>Flask<\/code>, <code>Plotly.js<\/code> and <code>React.js<\/code>. <\/p>\n<p>This example taken from the <a href=\"https:\/\/dash.plotly.com\/\">Dash User Guide<\/a> demonstrates the basic anatomy of a Dash app.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kn\">import<\/span> <span class=\"nn\">dash_core_components<\/span> <span class=\"k\">as<\/span> <span class=\"nn\">dcc<\/span>\n<span class=\"kn\">import<\/span> <span class=\"nn\">dash_html_components<\/span> <span class=\"k\">as<\/span> <span class=\"nn\">html<\/span>\n<span class=\"kn\">from<\/span> <span class=\"nn\">dash.dependencies<\/span> <span class=\"kn\">import<\/span> <span class=\"n\">Input<\/span><span class=\"p\">,<\/span> <span class=\"n\">Output<\/span>\n\n\n<span class=\"n\">app<\/span> <span class=\"o\">=<\/span> <span class=\"n\">dash<\/span><span class=\"o\">.<\/span><span class=\"n\">Dash<\/span><span class=\"p\">(<\/span><span class=\"vm\">__name__<\/span><span class=\"p\">)<\/span>\n\n<span class=\"n\">app<\/span><span class=\"o\">.<\/span><span class=\"n\">layout<\/span> <span class=\"o\">=<\/span> <span class=\"n\">html<\/span><span class=\"o\">.<\/span><span class=\"n\">Div<\/span><span class=\"p\">([<\/span>\n    <span class=\"n\">html<\/span><span class=\"o\">.<\/span><span class=\"n\">H6<\/span><span class=\"p\">(<\/span><span class=\"s2\">&quot;Change the value in the text box to see callbacks in action!&quot;<\/span><span class=\"p\">),<\/span>\n    <span class=\"n\">html<\/span><span class=\"o\">.<\/span><span class=\"n\">Div<\/span><span class=\"p\">([<\/span><span class=\"s2\">&quot;Input: &quot;<\/span><span class=\"p\">,<\/span>\n              <span class=\"n\">dcc<\/span><span class=\"o\">.<\/span><span class=\"n\">Input<\/span><span class=\"p\">(<\/span><span class=\"nb\">id<\/span><span class=\"o\">=<\/span><span class=\"s1\">&#39;my-input&#39;<\/span><span class=\"p\">,<\/span> <span class=\"n\">value<\/span><span class=\"o\">=<\/span><span class=\"s1\">&#39;initial value&#39;<\/span><span class=\"p\">,<\/span> <span class=\"nb\">type<\/span><span class=\"o\">=<\/span><span class=\"s1\">&#39;text&#39;<\/span><span class=\"p\">)]),<\/span>\n    <span class=\"n\">html<\/span><span class=\"o\">.<\/span><span class=\"n\">Br<\/span><span class=\"p\">(),<\/span>\n    <span class=\"n\">html<\/span><span class=\"o\">.<\/span><span class=\"n\">Div<\/span><span class=\"p\">(<\/span><span class=\"nb\">id<\/span><span class=\"o\">=<\/span><span class=\"s1\">&#39;my-output&#39;<\/span><span class=\"p\">),<\/span>\n\n<span class=\"p\">])<\/span>\n\n<span class=\"nd\">@app<\/span><span class=\"o\">.<\/span><span class=\"n\">callback<\/span><span class=\"p\">(<\/span>\n    <span class=\"n\">Output<\/span><span class=\"p\">(<\/span><span class=\"n\">component_id<\/span><span class=\"o\">=<\/span><span class=\"s1\">&#39;my-output&#39;<\/span><span class=\"p\">,<\/span> <span class=\"n\">component_property<\/span><span class=\"o\">=<\/span><span class=\"s1\">&#39;children&#39;<\/span><span class=\"p\">),<\/span>\n    <span class=\"n\">Input<\/span><span class=\"p\">(<\/span><span class=\"n\">component_id<\/span><span class=\"o\">=<\/span><span class=\"s1\">&#39;my-input&#39;<\/span><span class=\"p\">,<\/span> <span class=\"n\">component_property<\/span><span class=\"o\">=<\/span><span class=\"s1\">&#39;value&#39;<\/span><span class=\"p\">)<\/span>\n<span class=\"p\">)<\/span>\n<span class=\"k\">def<\/span> <span class=\"nf\">update_output_div<\/span><span class=\"p\">(<\/span><span class=\"n\">input_value<\/span><span class=\"p\">):<\/span>\n    <span class=\"k\">return<\/span> <span class=\"s1\">&#39;Output: <\/span><span class=\"si\">{}<\/span><span class=\"s1\">&#39;<\/span><span class=\"o\">.<\/span><span class=\"n\">format<\/span><span class=\"p\">(<\/span><span class=\"n\">input_value<\/span><span class=\"p\">)<\/span>\n\n\n<span class=\"k\">if<\/span> <span class=\"vm\">__name__<\/span> <span class=\"o\">==<\/span> <span class=\"s1\">&#39;__main__&#39;<\/span><span class=\"p\">:<\/span>\n    <span class=\"n\">app<\/span><span class=\"o\">.<\/span><span class=\"n\">run_server<\/span><span class=\"p\">(<\/span><span class=\"n\">debug<\/span><span class=\"o\">=<\/span><span class=\"kc\">True<\/span><span class=\"p\">)<\/span>\n<\/code><\/pre><\/div>\n\n<p>This basic structure is all you will need for this tutorial. If you are interested in greater detail or other components, we encourage you to explore the documentation in greater detail.  The basic building blocks are components and for this tutorial, the <code>dash_core_components<\/code>, <code>dash_html_components<\/code> as well as <code>dash_leaflet<\/code> will provide the necessary components. The <code>app<\/code> instantiation of <code>Dash<\/code> is the core object which the app is built around. This is similar for those who build Flask app to the instantiation of <code>Flask<\/code>. The <code>layout<\/code> attribute of the <code>app<\/code> object defines the HTML layout of the app. As you can see, the components from <code>dash_html_components<\/code> mirror HTML tags. Pretty much any HTML tag has a corresponding Dash component in <code>dash_html_components<\/code>. The core components contain more of the interactive components, such as input, dropdown, and graph.<\/p>\n<p>The next block of code defines the interactivity. The <code>callback<\/code> decorator is passed input and output dependencies. In this case the <code>value<\/code> property of the <code>my-input<\/code> component triggers the callback which updates the <code>children<\/code> property of the <code>my-output<\/code> component.<\/p>\n<p>Finally, <code>app.run_server<\/code> starts the webserver. Dash can be run inline in Jupyter notebooks with the use of <code>JupyterDash<\/code> as mentioned in part 1. To use <code>JupyterDash<\/code>, assign your <code>app<\/code> to an instantiation of <code>JupyterDash<\/code> rather than <code>Dash<\/code>. Additionally, <code>run_server<\/code> also takes a <code>mode<\/code> argument and if set to <code>'inline'<\/code>will display the app inline in a Jupyter notebook. <\/p>\n<h2>Dash Leaflet<\/h2>\n<p>Dash-leaflet as mentioned in part 1 is a lightweight wrapper to <code>leaflet.js<\/code>.  It ports most <code>react<\/code>components in <code>leaflet<\/code> to dash. There are numerous components, but the three that will be of the most importance to us here are the <code>Map<\/code>, <code>TileLayer<\/code> and <code>GeoJSON<\/code> components.<\/p>\n<p>The <code>Map<\/code> component can be though of as the parent container which houses our visualizations. The <code>TileLayer<\/code> and <code>GeoJSON<\/code> components are layers within the <code>Map<\/code> component.  We have seen from our  <a href=\"https:\/\/github.com\/WestHealth\/tutorial-blog-material\/blob\/main\/leaflet-tutorial\/notebooks\/01-getting-started.ipynb\">Getting Started<\/a> example, where a <code>Map<\/code> component comprises a <code>TileLayer<\/code> as a child.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>app.layout = dl.Map(dl.TileLayer(), style={&#39;width&#39;: &#39;1000px&#39;, &#39;height&#39;: &#39;500px&#39;})\n<\/code><\/pre><\/div>\n\n<p>If you layer children in a <code>Map<\/code> component they are rendered from left to right with the last child rendered on the top. So you will want the <code>TileLayer<\/code> to be the bottom layer hence it should be first.  The <code>height<\/code> and <code>width<\/code> styling is supplied to make the map look good when deployed inline to a Jupyter notebook. These dimensions may change due to the aesthetic of your particular visualization.<\/p>\n<h3>The Map Component<\/h3>\n<p>The <code>Map<\/code> component as well as the other layer components has the standard <code>Dash<\/code> properties: <code>id<\/code>, <code>children<\/code>, <code>style<\/code> and <code>className<\/code>. It has a lot of other properties that aren't really documented but can be found in the source for <code>Map.react.js<\/code> at the <a href=\"https:\/\/github.com\/thedirtyfew\/dash-leaflet\/tree\/master\/src\/lib\/components\"><code>components<\/code> subdirectory<\/a> of the source file. They are two numerous to go into here, but a few useful properties include <code>click_lat_lng<\/code> which when used as an <code>Input<\/code> to a callback provide the location on the map of a mouse click and <code>dbl_click_lat_lng<\/code> which reports the location of a mouse double click. Aside from the styling properties of <code>style<\/code> and <code>className<\/code> the other property that is useful is <code>bounds<\/code> which functions like a bounding box how much of the map is to be rendered. Two other properties <code>center<\/code> and <code>zoom<\/code> are useful as well. The property <code>center<\/code> centers the map at a given latitude and longitude and <code>zoom<\/code> provides the zoom level to display the map. For example, to display the continental United States a setting of <code>center=[39, -98], zoom=4<\/code> yields nice results. This allows us to programatically change the view of the map presented to the user. <\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">app<\/span><span class=\"o\">.<\/span><span class=\"n\">layout<\/span> <span class=\"o\">=<\/span> <span class=\"n\">dl<\/span><span class=\"o\">.<\/span><span class=\"n\">Map<\/span><span class=\"p\">(<\/span><span class=\"n\">dl<\/span><span class=\"o\">.<\/span><span class=\"n\">TileLayer<\/span><span class=\"p\">(),<\/span>\n                    <span class=\"n\">center<\/span><span class=\"o\">=<\/span><span class=\"p\">[<\/span><span class=\"mi\">39<\/span><span class=\"p\">,<\/span> <span class=\"o\">-<\/span><span class=\"mi\">98<\/span><span class=\"p\">],<\/span>\n                    <span class=\"n\">zoom<\/span><span class=\"o\">=<\/span><span class=\"mi\">4<\/span><span class=\"p\">,<\/span>\n                    <span class=\"n\">style<\/span><span class=\"o\">=<\/span><span class=\"p\">{<\/span><span class=\"s1\">&#39;width&#39;<\/span><span class=\"p\">:<\/span> <span class=\"s1\">&#39;1000px&#39;<\/span><span class=\"p\">,<\/span> <span class=\"s1\">&#39;height&#39;<\/span><span class=\"p\">:<\/span> <span class=\"s1\">&#39;500px&#39;<\/span><span class=\"p\">})<\/span>\n<\/code><\/pre><\/div>\n\n<h3>The TileLayer component<\/h3>\n<p>The <code>TileLayer<\/code> is responsible for grabbing map tiles from tile server. There are a number of free servers as well as some servers which are commercial, but on a freemium model, but require incorporating an access key. Openstreetmaps is really the parent of all tileservers, even the commercial map servers use openstreetmaps as their underlying dataset. For a list of map servers, you can look at <a href=\"https:\/\/wiki.openstreetmap.org\/wiki\/Tile_servers\">openstreetmap's wiki article on tile servers<\/a>.<\/p>\n<p>The <code>TileLayer<\/code> component has the standard <code>Dash<\/code> properties mentioned above for the <code>Map<\/code> component. Two other important properties are the <code>url<\/code> property and the <code>attribution<\/code> property. The <code>url<\/code> property specifies the url for the tile server, by default openstreetmap is used. It has a corresponding url of <code>https:\/\/{s}.tile.openstreetmap.org\/{z}\/{x}\/{y}.png<\/code>. The <code>x<\/code>,<code>y<\/code>, <code>z<\/code> components clearly indicate tile position, the <code>s<\/code> indicates the server. In the case of openstreetmap, there are 3 servers indicated by <code>a<\/code>, <code>b<\/code>, <code>c<\/code>. Some tile servers take and <code>s<\/code> value some don't.  The <code>attribution<\/code> is an HTML string with links to properly give credit to the map server. This should be set in compliance with the terms of use of the underlying tile server, plus it is always the right thing to give credit where credit is due.<\/p>\n<h3>The GeoJSON component<\/h3>\n<p>The <code>GeoJSON<\/code> component is where most of the magic happens. In short it is the layer best equipped with infusing data into the maps. The properties of the <code>GeoJSON<\/code> play a large part in the customization of the map visualization and behavior described in this tutorial. As such these properties are described in greater detail in subsequent parts of this tutorial. Probably the most important property of the <code>GeoJSON<\/code> layer is the <code>data<\/code> property which supplies the layer with geographic data. The propezrty <code>format<\/code> specifies whether the data is formatted as a <code>'geojson'<\/code> or <code>'geobuf'<\/code> as be introduced at the beginning of this part of the tutorial. In a nutshell what the <code>GeoJSON<\/code> does is that it renders all point data in <code>data<\/code> as a marker (which we'll discuss later) and all polygonal data in <code>data<\/code> as an outline. Another property we'll need for our examples is <code>zoomToBounds<\/code> which if set to <code>True<\/code> zooms the map to the bounds of the <code>data<\/code> whenever it changes. For instance, if the <code>data<\/code> is an outline of a state, it will center and zoom the map to the state.<\/p>\n<h3>Some Simple Examples<\/h3>\n<p>To close out this section of the tutorial, we'll draw a few outlines on a map using the county and state US Census shape files. The full example is provided in this <a href=\"https:\/\/github.com\/WestHealth\/tutorial-blog-material\/blob\/main\/leaflet-tutorial\/notebooks\/02-simple-examples.ipynb\">notebook<\/a>. We will make an interactive map of the states and counties of Alaska (why Alaska? I will be clear in a moment.)<\/p>\n<p>First thing we do is to process the data appropriately.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">zipfile<\/span> <span class=\"o\">=<\/span> <span class=\"s2\">&quot;zip:\/\/cb_2019_us_state_20m.zip&quot;<\/span>\n<span class=\"n\">gdf<\/span> <span class=\"o\">=<\/span> <span class=\"n\">gpd<\/span><span class=\"o\">.<\/span><span class=\"n\">read_file<\/span><span class=\"p\">(<\/span><span class=\"n\">zipfile<\/span><span class=\"p\">)<\/span>\n<span class=\"n\">us_territories_geoids<\/span> <span class=\"o\">=<\/span> <span class=\"p\">[<\/span><span class=\"s1\">&#39;78&#39;<\/span><span class=\"p\">,<\/span><span class=\"s1\">&#39;69&#39;<\/span><span class=\"p\">,<\/span><span class=\"s1\">&#39;72&#39;<\/span><span class=\"p\">,<\/span><span class=\"s1\">&#39;60&#39;<\/span><span class=\"p\">,<\/span><span class=\"s1\">&#39;66&#39;<\/span><span class=\"p\">]<\/span>\n<span class=\"n\">alaska_hawaii_geoids<\/span> <span class=\"o\">=<\/span> <span class=\"p\">[<\/span><span class=\"s1\">&#39;02&#39;<\/span><span class=\"p\">,<\/span><span class=\"s1\">&#39;15&#39;<\/span><span class=\"p\">]<\/span>\n<span class=\"n\">continental_us_states<\/span><span class=\"o\">=<\/span><span class=\"n\">gdf<\/span><span class=\"p\">[<\/span><span class=\"o\">~<\/span><span class=\"n\">gdf<\/span><span class=\"p\">[<\/span><span class=\"s1\">&#39;GEOID&#39;<\/span><span class=\"p\">]<\/span><span class=\"o\">.<\/span><span class=\"n\">isin<\/span><span class=\"p\">(<\/span><span class=\"n\">us_territories_geoids<\/span><span class=\"o\">+<\/span><span class=\"n\">alaska_hawaii_geoids<\/span><span class=\"p\">)<\/span>\n<\/code><\/pre><\/div>\n\n<p>Besides reading the shape file, we also filter out US territories that are provided by the Census file. Additionally, to display the continental United States we filter out Alaska and Hawaii.<\/p>\n<p>Next the <code>GeoPandas<\/code> <code>DataFrame<\/code> is converted to a GeoJSON object. the <code>to_json<\/code> method converts the <code>DataFrame<\/code> to a JSON string which then needs to be loaded into a python dictionary. Then we create the layout for the app.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">geojson<\/span><span class=\"o\">=<\/span><span class=\"n\">json<\/span><span class=\"o\">.<\/span><span class=\"n\">loads<\/span><span class=\"p\">(<\/span><span class=\"n\">continental_us_states<\/span><span class=\"o\">.<\/span><span class=\"n\">to_json<\/span><span class=\"p\">())<\/span>\n<span class=\"n\">app<\/span><span class=\"o\">.<\/span><span class=\"n\">layout<\/span> <span class=\"o\">=<\/span> <span class=\"n\">dl<\/span><span class=\"o\">.<\/span><span class=\"n\">Map<\/span><span class=\"p\">([<\/span>\n    <span class=\"n\">dl<\/span><span class=\"o\">.<\/span><span class=\"n\">TileLayer<\/span><span class=\"p\">(),<\/span>\n    <span class=\"n\">dl<\/span><span class=\"o\">.<\/span><span class=\"n\">GeoJSON<\/span><span class=\"p\">(<\/span><span class=\"n\">data<\/span><span class=\"o\">=<\/span><span class=\"n\">geojson<\/span><span class=\"p\">,<\/span> <span class=\"n\">zoomToBounds<\/span><span class=\"o\">=<\/span><span class=\"kc\">True<\/span><span class=\"p\">,<\/span> <span class=\"n\">zoomToBoundsOnClick<\/span><span class=\"o\">=<\/span><span class=\"kc\">True<\/span><span class=\"p\">)<\/span>\n<span class=\"p\">],<\/span>\n                    <span class=\"n\">style<\/span><span class=\"o\">=<\/span><span class=\"p\">{<\/span>\n                        <span class=\"s1\">&#39;width&#39;<\/span><span class=\"p\">:<\/span> <span class=\"s1\">&#39;1000px&#39;<\/span><span class=\"p\">,<\/span>\n                        <span class=\"s1\">&#39;height&#39;<\/span><span class=\"p\">:<\/span> <span class=\"s1\">&#39;500px&#39;<\/span>\n                    <span class=\"p\">})<\/span>\n<\/code><\/pre><\/div>\n\n<p>The <code>zoomToBounds<\/code> property sets the bounds based on the supplied data so we don't need to supply the <code>center<\/code> or <code>zoom<\/code> properties to the map. The <code>zoomToBoundsOnClick<\/code> adds a little interactivity. If set to <code>True<\/code> clicking on a feature (i.e. state in our case) will set the zoom on the data associated with that feature. There many more customizations we can apply to this type of visualization which we will go into greater depth in the next section.<\/p>\n<h3>The Anti Meridian Problem<\/h3>\n<p>Suppose we decide to display the entire 50 states. Suddenly it seems the zoom level is out of whack. <\/p>\n<p><img alt=\"\" src=\"images\/dl-02-alaska.png\"><\/p>\n<p>To illustrate the problem further, we produce a similar visualization based on the counties of Alaska. To show the use of the <code>geobuf<\/code> type we convert the geojson to <code>geobuf<\/code> here. If <code>geobuf<\/code> is used the <code>format<\/code> property must be set to <code>'geobuf'<\/code>.  As for the data preprocessing we filter the <code>GeoDataFrame<\/code> read from the Census by filtering on the state Federal Information Processing Standards (FIPS) code for Alaska, <code>'02'<\/code>.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kn\">import<\/span> <span class=\"nn\">dash_leaflet.express<\/span> <span class=\"k\">as<\/span> <span class=\"nn\">dlx<\/span>\n<span class=\"n\">zipfile<\/span> <span class=\"o\">=<\/span> <span class=\"s2\">&quot;zip:\/\/cb_2019_us_county_20m.zip&quot;<\/span>\n<span class=\"n\">gdf<\/span> <span class=\"o\">=<\/span> <span class=\"n\">gpd<\/span><span class=\"o\">.<\/span><span class=\"n\">read_file<\/span><span class=\"p\">(<\/span><span class=\"n\">zipfile<\/span><span class=\"p\">)<\/span>\n<span class=\"n\">alaska<\/span> <span class=\"o\">=<\/span> <span class=\"n\">gdf<\/span><span class=\"p\">[<\/span><span class=\"n\">gdf<\/span><span class=\"p\">[<\/span><span class=\"s1\">&#39;STATEFP&#39;<\/span><span class=\"p\">]<\/span><span class=\"o\">==<\/span><span class=\"s1\">&#39;02&#39;<\/span><span class=\"p\">]<\/span>\n<span class=\"n\">geojson<\/span><span class=\"o\">=<\/span><span class=\"n\">json<\/span><span class=\"o\">.<\/span><span class=\"n\">loads<\/span><span class=\"p\">(<\/span><span class=\"n\">alaska<\/span><span class=\"o\">.<\/span><span class=\"n\">to_json<\/span><span class=\"p\">())<\/span>\n<span class=\"n\">geobuf<\/span> <span class=\"o\">=<\/span> <span class=\"n\">dlx<\/span><span class=\"o\">.<\/span><span class=\"n\">geojson_to_geobuf<\/span><span class=\"p\">(<\/span><span class=\"n\">geojson<\/span><span class=\"p\">)<\/span>\n<span class=\"n\">app<\/span><span class=\"o\">.<\/span><span class=\"n\">layout<\/span> <span class=\"o\">=<\/span> <span class=\"n\">dl<\/span><span class=\"o\">.<\/span><span class=\"n\">Map<\/span><span class=\"p\">([<\/span>\n    <span class=\"n\">dl<\/span><span class=\"o\">.<\/span><span class=\"n\">TileLayer<\/span><span class=\"p\">(),<\/span>\n    <span class=\"n\">dl<\/span><span class=\"o\">.<\/span><span class=\"n\">GeoJSON<\/span><span class=\"p\">(<\/span><span class=\"n\">data<\/span><span class=\"o\">=<\/span><span class=\"n\">geobuf<\/span><span class=\"p\">,<\/span> <span class=\"nb\">format<\/span><span class=\"o\">=<\/span><span class=\"s1\">&#39;geobuf&#39;<\/span><span class=\"p\">,<\/span> <span class=\"n\">zoomToBounds<\/span><span class=\"o\">=<\/span><span class=\"kc\">True<\/span><span class=\"p\">,<\/span> <span class=\"n\">zoomToBoundsOnClick<\/span><span class=\"o\">=<\/span><span class=\"kc\">True<\/span><span class=\"p\">)<\/span>\n<span class=\"p\">],<\/span>\n                    <span class=\"n\">style<\/span><span class=\"o\">=<\/span><span class=\"p\">{<\/span>\n                        <span class=\"s1\">&#39;width&#39;<\/span><span class=\"p\">:<\/span> <span class=\"s1\">&#39;1000px&#39;<\/span><span class=\"p\">,<\/span>\n                        <span class=\"s1\">&#39;height&#39;<\/span><span class=\"p\">:<\/span> <span class=\"s1\">&#39;500px&#39;<\/span>\n                    <span class=\"p\">})<\/span>\n<\/code><\/pre><\/div>\n\n<p>Again, we get that zoomed out view. If you click on the counties, the zoom in feature works as expected, until you click on the lower left Aleutian Islands. If you click on that you get that world view again. So what is wrong here? Both for this county Aleutians West and the outline for Alaska in our state maps, there are some polygons on the opposite side of the Anti Meridian (the 180 degrees longitude line). If you example the longitudes of the Aleutians West, some are listed as <code>-170<\/code>s and some in the <code>170<\/code>s. The other clue is that if you look at the extreme right you will see highlighted the western half of the county rendered in that part of the map.<\/p>\n<p>There are two solutions, one is to simply drop the polygons on the wrong side of the Anti Meridian. The other is to take the longitudes that are in the <code>170<\/code>s  and put them in the <code>-180<\/code>s. This is like instead of saying \"179 degrees West\" saying \"181 degrees East\" while not canonical, it is still accurate.<\/p>\n<p>To correct this, we used <code>shapely<\/code> and some fancy <code>pandas<\/code> coding which is beyond the scope of this tutorial. Nonetheless, it is presented here and in the sample notebook and can be adapted for other applications.<\/p>\n<p>First we extract the geometry of  Aleutians West<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">aleutians_west<\/span><span class=\"o\">=<\/span><span class=\"n\">alaska<\/span><span class=\"p\">[<\/span><span class=\"n\">alaska<\/span><span class=\"p\">[<\/span><span class=\"s1\">&#39;GEOID&#39;<\/span><span class=\"p\">]<\/span><span class=\"o\">==<\/span><span class=\"s1\">&#39;02016&#39;<\/span><span class=\"p\">]<\/span><span class=\"o\">.<\/span><span class=\"n\">geometry<\/span><span class=\"o\">.<\/span><span class=\"n\">to_list<\/span><span class=\"p\">()[<\/span><span class=\"mi\">0<\/span><span class=\"p\">]<\/span>\n<\/code><\/pre><\/div>\n\n<p>Next we find all points west of the Anti Meridian and shift it to an east value (basically subtracting 360 from it.)<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kn\">import<\/span> <span class=\"nn\">shapely<\/span>\n<span class=\"n\">corrected_poly<\/span><span class=\"o\">=<\/span><span class=\"p\">[]<\/span>\n<span class=\"k\">for<\/span> <span class=\"n\">each<\/span> <span class=\"ow\">in<\/span> <span class=\"n\">aleutians_west<\/span><span class=\"p\">:<\/span>\n    <span class=\"k\">if<\/span> <span class=\"n\">each<\/span><span class=\"o\">.<\/span><span class=\"n\">exterior<\/span><span class=\"o\">.<\/span><span class=\"n\">coords<\/span><span class=\"o\">.<\/span><span class=\"n\">xy<\/span><span class=\"p\">[<\/span><span class=\"mi\">0<\/span><span class=\"p\">][<\/span><span class=\"mi\">0<\/span><span class=\"p\">]<\/span><span class=\"o\">&gt;<\/span><span class=\"mi\">0<\/span><span class=\"p\">:<\/span>\n        <span class=\"n\">corrected_poly<\/span><span class=\"o\">.<\/span><span class=\"n\">append<\/span><span class=\"p\">(<\/span><span class=\"n\">shapely<\/span><span class=\"o\">.<\/span><span class=\"n\">affinity<\/span><span class=\"o\">.<\/span><span class=\"n\">translate<\/span><span class=\"p\">(<\/span><span class=\"n\">each<\/span><span class=\"p\">,<\/span><span class=\"o\">-<\/span><span class=\"mi\">360<\/span><span class=\"p\">,<\/span><span class=\"mi\">0<\/span><span class=\"p\">))<\/span>\n    <span class=\"k\">else<\/span><span class=\"p\">:<\/span>\n        <span class=\"n\">corrected_poly<\/span><span class=\"o\">.<\/span><span class=\"n\">append<\/span><span class=\"p\">(<\/span><span class=\"n\">each<\/span><span class=\"p\">),<\/span>\n<span class=\"n\">fixed_aleutian<\/span><span class=\"o\">=<\/span><span class=\"n\">shapely<\/span><span class=\"o\">.<\/span><span class=\"n\">geometry<\/span><span class=\"o\">.<\/span><span class=\"n\">multipolygon<\/span><span class=\"o\">.<\/span><span class=\"n\">MultiPolygon<\/span><span class=\"p\">(<\/span><span class=\"n\">corrected_poly<\/span><span class=\"p\">)<\/span>\n<\/code><\/pre><\/div>\n\n<p>It should be noted that we know that the geometry is a <code>MultiPolygon<\/code> if you were to adapt this to be general purpose, you need to account for the possibility that your shape is simply a <code>Polygon<\/code>.<\/p>\n<p>Finally we insert it back into the <code>GeoDataFrame<\/code>. The <code>at<\/code> mechanism was used since with trial and error it seems to be the one method that works.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">alaska<\/span><span class=\"o\">.<\/span><span class=\"n\">at<\/span><span class=\"p\">[<\/span><span class=\"n\">alaska<\/span><span class=\"p\">[<\/span><span class=\"n\">alaska<\/span><span class=\"p\">[<\/span><span class=\"s1\">&#39;GEOID&#39;<\/span><span class=\"p\">]<\/span><span class=\"o\">==<\/span><span class=\"s1\">&#39;02016&#39;<\/span><span class=\"p\">]<\/span><span class=\"o\">.<\/span><span class=\"n\">index<\/span><span class=\"p\">[<\/span><span class=\"mi\">0<\/span><span class=\"p\">],<\/span> <span class=\"s1\">&#39;geometry&#39;<\/span><span class=\"p\">]<\/span><span class=\"o\">=<\/span><span class=\"n\">fixed_aleutian<\/span>\n<\/code><\/pre><\/div>\n\n<p>Now if you repeat the code shown above, Alaska comes into view without being wrapped around the world.<\/p>\n<h2>Conclusion<\/h2>\n<p>In this installment, we showed the basics behind, working with geographic data files, Dash and Dash Leaflet. Demonstrated some basic visualizations with state and county boundaries. In the next installment, we will take the outline visualization shown here even further.<\/p>","category":[{"@attributes":{"term":"Visualizations"}},{"@attributes":{"term":"Dash"}},{"@attributes":{"term":"Leaflet"}},{"@attributes":{"term":"Python"}}]},{"title":"Exploring fillable forms with PDFrw","link":{"@attributes":{"href":"https:\/\/WestHealth.github.io\/exploring-fillable-forms-with-pdfrw.html","rel":"alternate"}},"published":"2021-03-01T11:22:00-08:00","updated":"2021-03-01T11:22:00-08:00","author":{"name":"Haw-minn Lu"},"id":"tag:westhealth.github.io,2021-03-01:\/exploring-fillable-forms-with-pdfrw.html","summary":"<h2>Introduction and Background<\/h2>\n<p>With the goal of providing a senior friendly vaccine experience, <a href=\"https:\/\/westpace.org\">Gary and Mary West PACE<\/a> which stood up a small senior oriented covid vaccine clinic desires to mitigate the amount of paperwork a frail senior is subjected to. Quite a lot of data is repeatedly asked for \u2026<\/p>","content":"<h2>Introduction and Background<\/h2>\n<p>With the goal of providing a senior friendly vaccine experience, <a href=\"https:\/\/westpace.org\">Gary and Mary West PACE<\/a> which stood up a small senior oriented covid vaccine clinic desires to mitigate the amount of paperwork a frail senior is subjected to. Quite a lot of data is repeatedly asked for to make appointments, on consent forms and in reminder cards. While the idea of using pre-populated fillable PDF forms is a simple one, implementation is full of challenges as many common programmatic PDF tools do not properly work with filled forms. To meet the challenges, PDF forms have repeated fields with same name, checkboxes and radio buttons are used. Furthermore, to make life easier for the staff, PDF forms for multiple patients needed to be consolidated into a single PDF.<\/p>\n<p>Programatically filling in PDF forms can be a quick and accurate way to disseminate forms. Bits and pieces can be found throughout the Internet and places like Stack Overflow. No single source provides a complete answer, however, this <a href=\"https:\/\/medium.com\/@vivsvaan\/filling-editable-pdf-in-python-76712c3ce99\">blog post in Medium by Vivsvaan Sharma<\/a> is a good starting place. The blog post is long on python practices and a bit short on PDF details. Another useful resource is the <a href=\"https:\/\/www.adobe.com\/content\/dam\/acom\/en\/devnet\/pdf\/pdfs\/PDF32000_2008.pdf\">PDF 1.7 specification<\/a>, but it is well over 750 pages!.<\/p>\n<p>The scope of this series applies to PDF 1.7 at this time no investigation as to whether techniques apply to PDF 2.0 or forms designed with Adobe LifeCycle. The forms are confirmed to work with Acrobat Reader, but not tested across the board with different readers.<\/p>\n<p>We will cover the basics of using PDFrw to explore fillable forms and look at basic data types within PDFrw. We will first look at text form fields and discuss how to access fields that are repeated. We will then look at checkboxes, radio buttons, combo boxes and lists. Finally, we'll offer a solution for consolidating multiple filled forms into a single PDF while preserving the filled forms (and maintain editability).<\/p>\n<h2>Finding Your Way Around PDFrw and fillable forms<\/h2>\n<p>If you search the internet, including the above mentioned <em>Medium<\/em> blog post, you will find a snippet of code which might look like the following:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">pdf<\/span> <span class=\"o\">=<\/span> <span class=\"n\">pdfrw<\/span><span class=\"o\">.<\/span><span class=\"n\">PdfReader<\/span><span class=\"p\">(<\/span><span class=\"n\">file_path<\/span><span class=\"p\">)<\/span>\n<span class=\"k\">for<\/span> <span class=\"n\">page<\/span> <span class=\"ow\">in<\/span> <span class=\"n\">pdf<\/span><span class=\"o\">.<\/span><span class=\"n\">pages<\/span><span class=\"p\">:<\/span>\n    <span class=\"n\">annotations<\/span> <span class=\"o\">=<\/span> <span class=\"n\">page<\/span><span class=\"p\">[<\/span><span class=\"s1\">&#39;\/Annots&#39;<\/span><span class=\"p\">]<\/span>\n    <span class=\"k\">if<\/span> <span class=\"n\">annotations<\/span> <span class=\"ow\">is<\/span> <span class=\"kc\">None<\/span><span class=\"p\">:<\/span>\n        <span class=\"k\">continue<\/span>\n\n    <span class=\"k\">for<\/span> <span class=\"n\">annotation<\/span> <span class=\"ow\">in<\/span> <span class=\"n\">annotations<\/span><span class=\"p\">:<\/span>\n        <span class=\"k\">if<\/span> <span class=\"n\">annotation<\/span><span class=\"p\">[<\/span><span class=\"s1\">&#39;\/Subtype&#39;<\/span><span class=\"p\">]<\/span><span class=\"o\">==<\/span><span class=\"s1\">&#39;\/Widget&#39;<\/span><span class=\"p\">:<\/span>\n            <span class=\"k\">if<\/span> <span class=\"n\">annotation<\/span><span class=\"p\">[<\/span><span class=\"s1\">&#39;\/T&#39;<\/span><span class=\"p\">]:<\/span>\n                <span class=\"n\">key<\/span> <span class=\"o\">=<\/span> <span class=\"n\">annotation<\/span><span class=\"p\">[<\/span><span class=\"s1\">&#39;\/T&#39;<\/span><span class=\"p\">]<\/span><span class=\"o\">.<\/span><span class=\"n\">to_unicode<\/span><span class=\"p\">()<\/span>\n                <span class=\"nb\">print<\/span> <span class=\"p\">(<\/span><span class=\"n\">key<\/span><span class=\"p\">)<\/span>\n<\/code><\/pre><\/div>\n\n<p>The type of <code>annotation['\/T']<\/code> is <code>pdfString<\/code> while some sources use [1:-1] to extract the string from <code>pdfString<\/code> the <code>.to_unicode()<\/code> method is the proper way to extract the string. According to the PDF 1.7 specification &sect; 12.5.6.19 all fillable forms use are widget annotation, so the check for the <code>annotation['\/SubType']<\/code> filters the annotation to only widget annotations.<\/p>\n<p>As an example take the file <code>sample_form1.pdf<\/code> located at here at github. It has a fields for a person to enter their name and address information, plus we added a checkbox for an called <code>opt in<\/code>. If we run the segment of code on this file, the output looks like:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>Name\nAddress\nCity\nState\nZip\nOpt in\n<\/code><\/pre><\/div>\n\n<p>So in this way we can figure out which <code>annotation<\/code> contains the fields  All we have to do is set the value.  Well almost as we'll explain below. To set the value, first we need to create a <code>PDFString<\/code> with our value with the <code>encode<\/code> method then update the <code>annotation<\/code> as shown in this code snippet.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">annotation<\/span><span class=\"o\">.<\/span><span class=\"n\">update<\/span><span class=\"p\">(<\/span><span class=\"n\">pdfrw<\/span><span class=\"o\">.<\/span><span class=\"n\">PdfDict<\/span><span class=\"p\">(<\/span><span class=\"n\">V<\/span><span class=\"o\">=<\/span><span class=\"n\">pdfrw<\/span><span class=\"o\">.<\/span><span class=\"n\">objects<\/span><span class=\"o\">.<\/span><span class=\"n\">pdfstring<\/span><span class=\"o\">.<\/span><span class=\"n\">PdfString<\/span><span class=\"o\">.<\/span><span class=\"n\">encode<\/span><span class=\"p\">(<\/span><span class=\"n\">value<\/span><span class=\"p\">)))<\/span>\n<\/code><\/pre><\/div>\n\n<p>This converts your <code>value<\/code> into a <code>PdfString<\/code> and updates the <code>annotation<\/code> creating a value for. <code>annotation['\/V'<\/code>].  <\/p>\n<p>As mentioned above, this won't quite do it. At the top level of your <code>PdfReader<\/code> object <code>pdf<\/code> you also need to set the <code>NeedAppearances<\/code> property in the interactive from dictionary, <code>AcroForm<\/code> (See &sect; 12.7,2). Without this, the fields are updated but will not necessarily display. In our example, the corresponding snippet of code is<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">pdf<\/span><span class=\"o\">.<\/span><span class=\"n\">Root<\/span><span class=\"o\">.<\/span><span class=\"n\">AcroForm<\/span><span class=\"o\">.<\/span><span class=\"n\">update<\/span><span class=\"p\">(<\/span><span class=\"n\">pdfrw<\/span><span class=\"o\">.<\/span><span class=\"n\">PdfDict<\/span><span class=\"p\">(<\/span><span class=\"n\">NeedAppearances<\/span><span class=\"o\">=<\/span><span class=\"n\">pdfrw<\/span><span class=\"o\">.<\/span><span class=\"n\">PdfObject<\/span><span class=\"p\">(<\/span><span class=\"s1\">&#39;true&#39;<\/span><span class=\"p\">)))<\/span>\n<\/code><\/pre><\/div>\n\n<p>To recap, we can write a simple form filler with the following block of code for text fields. We will discuss checkboxes below.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">def<\/span> <span class=\"nf\">form_filler<\/span><span class=\"p\">(<\/span><span class=\"n\">in_path<\/span><span class=\"p\">,<\/span> <span class=\"n\">data<\/span><span class=\"p\">,<\/span> <span class=\"n\">out_path<\/span><span class=\"p\">):<\/span>\n    <span class=\"n\">pdf<\/span> <span class=\"o\">=<\/span> <span class=\"n\">pdfrw<\/span><span class=\"o\">.<\/span><span class=\"n\">PdfReader<\/span><span class=\"p\">(<\/span><span class=\"n\">in_path<\/span><span class=\"p\">)<\/span>\n    <span class=\"k\">for<\/span> <span class=\"n\">page<\/span> <span class=\"ow\">in<\/span> <span class=\"n\">pdf<\/span><span class=\"o\">.<\/span><span class=\"n\">pages<\/span><span class=\"p\">:<\/span>\n        <span class=\"n\">annotations<\/span> <span class=\"o\">=<\/span> <span class=\"n\">page<\/span><span class=\"p\">[<\/span><span class=\"s1\">&#39;\/Annots&#39;<\/span><span class=\"p\">]<\/span>\n        <span class=\"k\">if<\/span> <span class=\"n\">annotations<\/span> <span class=\"ow\">is<\/span> <span class=\"kc\">None<\/span><span class=\"p\">:<\/span>\n            <span class=\"k\">continue<\/span>\n\n        <span class=\"k\">for<\/span> <span class=\"n\">annotation<\/span> <span class=\"ow\">in<\/span> <span class=\"n\">annotations<\/span><span class=\"p\">:<\/span>\n            <span class=\"k\">if<\/span> <span class=\"n\">annotation<\/span><span class=\"p\">[<\/span><span class=\"s1\">&#39;\/Subtype&#39;<\/span><span class=\"p\">]<\/span> <span class=\"o\">==<\/span> <span class=\"s1\">&#39;\/Widget&#39;<\/span><span class=\"p\">:<\/span>\n                <span class=\"n\">key<\/span> <span class=\"o\">=<\/span> <span class=\"n\">annotation<\/span><span class=\"p\">[<\/span><span class=\"s1\">&#39;\/T&#39;<\/span><span class=\"p\">]<\/span><span class=\"o\">.<\/span><span class=\"n\">to_unicode<\/span><span class=\"p\">()<\/span>\n                <span class=\"k\">if<\/span> <span class=\"n\">key<\/span> <span class=\"ow\">in<\/span> <span class=\"n\">data<\/span><span class=\"p\">:<\/span>\n                    <span class=\"n\">pdfstr<\/span> <span class=\"o\">=<\/span> <span class=\"n\">pdfrw<\/span><span class=\"o\">.<\/span><span class=\"n\">objects<\/span><span class=\"o\">.<\/span><span class=\"n\">pdfstring<\/span><span class=\"o\">.<\/span><span class=\"n\">PdfString<\/span><span class=\"o\">.<\/span><span class=\"n\">encode<\/span><span class=\"p\">(<\/span><span class=\"n\">data<\/span><span class=\"p\">[<\/span><span class=\"n\">key<\/span><span class=\"p\">])<\/span>\n                    <span class=\"n\">annotation<\/span><span class=\"o\">.<\/span><span class=\"n\">update<\/span><span class=\"p\">(<\/span><span class=\"n\">pdfrw<\/span><span class=\"o\">.<\/span><span class=\"n\">PdfDict<\/span><span class=\"p\">(<\/span><span class=\"n\">V<\/span><span class=\"o\">=<\/span><span class=\"n\">pdfstr<\/span><span class=\"p\">))<\/span>\n        <span class=\"n\">pdf<\/span><span class=\"o\">.<\/span><span class=\"n\">Root<\/span><span class=\"o\">.<\/span><span class=\"n\">AcroForm<\/span><span class=\"o\">.<\/span><span class=\"n\">update<\/span><span class=\"p\">(<\/span>\n            <span class=\"n\">pdfrw<\/span><span class=\"o\">.<\/span><span class=\"n\">PdfDict<\/span><span class=\"p\">(<\/span><span class=\"n\">NeedAppearances<\/span><span class=\"o\">=<\/span><span class=\"n\">pdfrw<\/span><span class=\"o\">.<\/span><span class=\"n\">PdfObject<\/span><span class=\"p\">(<\/span><span class=\"s1\">&#39;true&#39;<\/span><span class=\"p\">)))<\/span>\n        <span class=\"n\">pdfrw<\/span><span class=\"o\">.<\/span><span class=\"n\">PdfWriter<\/span><span class=\"p\">()<\/span><span class=\"o\">.<\/span><span class=\"n\">write<\/span><span class=\"p\">(<\/span><span class=\"n\">out_path<\/span><span class=\"p\">,<\/span> <span class=\"n\">pdf<\/span><span class=\"p\">)<\/span>\n<\/code><\/pre><\/div>\n\n<h3>Multiple Fields with Same Name<\/h3>\n<p>For text fields: Simple? Well not quite. Take a look at <code>sample_form2.pdf<\/code>. This form differs from <code>sample_form1.pdf<\/code> only in that the <code>Name<\/code> field appears twice. Once in the information block at the top where name and address information is filled out, but also at the bottom in the signature block. If we were to run the first code block to examine the annotations, we get the following:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>Address\nCity\nState\nZip\nOpt in\n<\/code><\/pre><\/div>\n\n<p>So what happened to the <code>Name<\/code> field. Turns out whenever the multiple fields occur with the same name the situation is more complicated. One way to deal with this is to simply rename the fields to be different such as <code>Name-1<\/code> and <code>Name-2<\/code>, which is fine if the sole use of the form is for automated form filling. However, if the form is also to be used for manual filling, this would require the user to enter the <code>Name<\/code> multiple times.<\/p>\n<p>With a little sleuthing and experimentation, you will see that there are some widget annotations without the <code>\/T<\/code> field but with a <code>\/Parent<\/code> field. As it turns out this <code>\/Parent<\/code> contains the field name <code>\\T<\/code> as well as the  default value <code>\\V<\/code>. So for our examples there is one <code>\\Parent<\/code> and two <code>\\Kids<\/code>. With a simple modification to our code by inserting the lines:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">if<\/span> <span class=\"ow\">not<\/span> <span class=\"n\">annotation<\/span><span class=\"p\">[<\/span><span class=\"s1\">&#39;\/T&#39;<\/span><span class=\"p\">]:<\/span>\n    <span class=\"n\">annotation<\/span><span class=\"o\">=<\/span><span class=\"n\">annotation<\/span><span class=\"p\">[<\/span><span class=\"s1\">&#39;\/Parent&#39;<\/span><span class=\"p\">]<\/span>\n<\/code><\/pre><\/div>\n\n<p>That can allow us to inspect and modify annotations that appear more than once. With this modification, the result of our inspection code yields:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">pdf<\/span> <span class=\"o\">=<\/span> <span class=\"n\">pdfrw<\/span><span class=\"o\">.<\/span><span class=\"n\">PdfReader<\/span><span class=\"p\">(<\/span><span class=\"n\">file_path<\/span><span class=\"p\">)<\/span>\n<span class=\"k\">for<\/span> <span class=\"n\">page<\/span> <span class=\"ow\">in<\/span> <span class=\"n\">pdf<\/span><span class=\"o\">.<\/span><span class=\"n\">pages<\/span><span class=\"p\">:<\/span>\n    <span class=\"n\">annotations<\/span> <span class=\"o\">=<\/span> <span class=\"n\">page<\/span><span class=\"p\">[<\/span><span class=\"s1\">&#39;\/Annots&#39;<\/span><span class=\"p\">]<\/span>\n    <span class=\"k\">if<\/span> <span class=\"n\">annotations<\/span> <span class=\"ow\">is<\/span> <span class=\"kc\">None<\/span><span class=\"p\">:<\/span>\n        <span class=\"k\">continue<\/span>\n\n    <span class=\"k\">for<\/span> <span class=\"n\">annotation<\/span> <span class=\"ow\">in<\/span> <span class=\"n\">annotations<\/span><span class=\"p\">:<\/span>\n        <span class=\"k\">if<\/span> <span class=\"n\">annotation<\/span><span class=\"p\">[<\/span><span class=\"s1\">&#39;\/Subtype&#39;<\/span><span class=\"p\">]<\/span><span class=\"o\">==<\/span><span class=\"s1\">&#39;\/Widget&#39;<\/span><span class=\"p\">:<\/span>\n            <span class=\"k\">if<\/span> <span class=\"ow\">not<\/span> <span class=\"n\">annotation<\/span><span class=\"p\">[<\/span><span class=\"s1\">&#39;\/T&#39;<\/span><span class=\"p\">]:<\/span>\n                <span class=\"n\">annotation<\/span><span class=\"o\">=<\/span><span class=\"n\">annotation<\/span><span class=\"p\">[<\/span><span class=\"s1\">&#39;\/Parent&#39;<\/span><span class=\"p\">]<\/span>\n            <span class=\"k\">if<\/span> <span class=\"n\">annotation<\/span><span class=\"p\">[<\/span><span class=\"s1\">&#39;\/T&#39;<\/span><span class=\"p\">]:<\/span>\n                <span class=\"n\">key<\/span> <span class=\"o\">=<\/span> <span class=\"n\">annotation<\/span><span class=\"p\">[<\/span><span class=\"s1\">&#39;\/T&#39;<\/span><span class=\"p\">]<\/span><span class=\"o\">.<\/span><span class=\"n\">to_unicode<\/span><span class=\"p\">()<\/span>\n                <span class=\"nb\">print<\/span> <span class=\"p\">(<\/span><span class=\"n\">key<\/span><span class=\"p\">)<\/span>\n<\/code><\/pre><\/div>\n\n<p>It should be noted that <code>Name<\/code> now appears twice, once for each instance, but they both point to the same <code>\/Parent<\/code>. With this modification, the form filler will actually fill the <code>\/Parent<\/code> value twice, but this has no impact since it is overwriting the default value with the same value while keeping the code simple.<\/p>\n<h2>Checkboxes<\/h2>\n<p>In accordance to &sect;12.7.4.2.3 the you can set the checkbox state as follows:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">def<\/span> <span class=\"nf\">checkbox<\/span><span class=\"p\">(<\/span><span class=\"n\">annotation<\/span><span class=\"p\">,<\/span> <span class=\"n\">value<\/span><span class=\"p\">):<\/span>\n    <span class=\"k\">if<\/span> <span class=\"n\">value<\/span><span class=\"p\">:<\/span>\n        <span class=\"n\">val_str<\/span> <span class=\"o\">=<\/span> <span class=\"n\">pdfrw<\/span><span class=\"o\">.<\/span><span class=\"n\">objects<\/span><span class=\"o\">.<\/span><span class=\"n\">pdfname<\/span><span class=\"o\">.<\/span><span class=\"n\">BasePdfName<\/span><span class=\"p\">(<\/span><span class=\"s1\">&#39;\/Yes&#39;<\/span><span class=\"p\">)<\/span>\n    <span class=\"k\">else<\/span><span class=\"p\">:<\/span>\n        <span class=\"n\">val_str<\/span> <span class=\"o\">=<\/span> <span class=\"n\">pdfrw<\/span><span class=\"o\">.<\/span><span class=\"n\">objects<\/span><span class=\"o\">.<\/span><span class=\"n\">pdfname<\/span><span class=\"o\">.<\/span><span class=\"n\">BasePdfName<\/span><span class=\"p\">(<\/span><span class=\"s1\">&#39;\/Off&#39;<\/span><span class=\"p\">)<\/span>\n    <span class=\"n\">annotation<\/span><span class=\"o\">.<\/span><span class=\"n\">update<\/span><span class=\"p\">(<\/span><span class=\"n\">pdfrw<\/span><span class=\"o\">.<\/span><span class=\"n\">PdfDict<\/span><span class=\"p\">(<\/span><span class=\"n\">V<\/span><span class=\"o\">=<\/span><span class=\"n\">val_str<\/span><span class=\"p\">))<\/span>\n<\/code><\/pre><\/div>\n\n<p>This will work especially when the export value of the checkbox is <code>Yes<\/code>, but doesn't need to be. The easiest solution if you designed the form or can use acrobat to edit the form is to ensure that the export value of the checkbox is <code>Yes<\/code> and the default state of the box is unchecked. In fact the recommendation in the specification is that it be set to <code>Yes<\/code>. However, you may not have the luxury and upon closer inspection of a form where the export value is not set to <code>Yes.<\/code> You will see that the <code>\/V<\/code> and <code>\/AS<\/code> fields are set to the export value not <code>Yes<\/code>.<\/p>\n<p>If you are using the form not only for automatic filling but also for manual filling you may wish the box to be checked as a default. In that case, while the code does work, we feel the the best solution is to delete the <code>\/V<\/code> as well as the <code>\/AS<\/code>field from the dictionary. If you do not have acrobat and can not find the export value, you can discover it by looking at appearance dictionary <code>\/AP<\/code> and specifically at the <code>\/N<\/code> field. Each annotation has up to 3 appearances in it's appearance dictionary <code>\/N<\/code>, <code>\/R<\/code>   and <code>\/D<\/code>, standing for <em>normal<\/em>, <em>rollover<\/em>, and <em>down<\/em> (&sect;12.5.5). The latter two has to do with appearance in interacting with the mouse, the normal appearance has to do with how the form is printed. You can find the export value by examining the normal appearance keys are set to the export value and <code>\/Off<\/code>. For example if you run,<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"nb\">print<\/span> <span class=\"p\">(<\/span><span class=\"n\">annotation<\/span><span class=\"p\">[<\/span><span class=\"s1\">&#39;\/AP&#39;<\/span><span class=\"p\">][<\/span><span class=\"s1\">&#39;\/N&#39;<\/span><span class=\"p\">]<\/span><span class=\"o\">.<\/span><span class=\"n\">keys<\/span><span class=\"p\">())<\/span>\n<\/code><\/pre><\/div>\n\n<p>you will get annotations something like<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"p\">[<\/span><span class=\"s1\">&#39;\/Export&#39;<\/span><span class=\"p\">,<\/span> <span class=\"s1\">&#39;\/Off&#39;<\/span><span class=\"p\">]<\/span>\n<\/code><\/pre><\/div>\n\n<p>where <code>Export<\/code> is the export value.  The resulting sophisticated version of function should be more this.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">def<\/span> <span class=\"nf\">checkbox<\/span><span class=\"p\">(<\/span><span class=\"n\">annotation<\/span><span class=\"p\">,<\/span> <span class=\"n\">value<\/span><span class=\"p\">,<\/span> <span class=\"n\">export<\/span><span class=\"o\">=<\/span><span class=\"kc\">None<\/span><span class=\"p\">):<\/span>\n    <span class=\"k\">if<\/span> <span class=\"n\">export<\/span><span class=\"p\">:<\/span>\n        <span class=\"n\">export<\/span> <span class=\"o\">=<\/span> <span class=\"s1\">&#39;\/&#39;<\/span> <span class=\"o\">+<\/span> <span class=\"n\">export<\/span>\n    <span class=\"k\">else<\/span><span class=\"p\">:<\/span>\n        <span class=\"n\">keys<\/span> <span class=\"o\">=<\/span> <span class=\"n\">annotation<\/span><span class=\"p\">[<\/span><span class=\"s1\">&#39;\/AP&#39;<\/span><span class=\"p\">][<\/span><span class=\"s1\">&#39;\/N&#39;<\/span><span class=\"p\">]<\/span><span class=\"o\">.<\/span><span class=\"n\">keys<\/span><span class=\"p\">()<\/span>\n        <span class=\"n\">keys<\/span><span class=\"o\">.<\/span><span class=\"n\">remove<\/span><span class=\"p\">(<\/span><span class=\"s1\">&#39;\/Off&#39;<\/span><span class=\"p\">)<\/span>\n        <span class=\"n\">export<\/span> <span class=\"o\">=<\/span> <span class=\"n\">keys<\/span><span class=\"p\">[<\/span><span class=\"mi\">0<\/span><span class=\"p\">]<\/span>\n    <span class=\"k\">if<\/span> <span class=\"n\">value<\/span><span class=\"p\">:<\/span>\n        <span class=\"n\">annotation<\/span><span class=\"o\">.<\/span><span class=\"n\">update<\/span><span class=\"p\">(<\/span><span class=\"n\">pdfrw<\/span><span class=\"o\">.<\/span><span class=\"n\">PdfDict<\/span><span class=\"p\">(<\/span><span class=\"n\">V<\/span><span class=\"o\">=<\/span><span class=\"n\">export<\/span><span class=\"p\">,<\/span> <span class=\"n\">AS<\/span><span class=\"o\">=<\/span><span class=\"n\">export<\/span><span class=\"p\">))<\/span>\n    <span class=\"k\">else<\/span><span class=\"p\">:<\/span>\n        <span class=\"k\">del<\/span> <span class=\"n\">annotation<\/span><span class=\"p\">[<\/span><span class=\"s1\">&#39;\/V&#39;<\/span><span class=\"p\">]<\/span>\n        <span class=\"k\">del<\/span> <span class=\"n\">annotation<\/span><span class=\"p\">[<\/span><span class=\"s1\">&#39;\/AS&#39;<\/span><span class=\"p\">]<\/span>\n<\/code><\/pre><\/div>\n\n<p>According to the PDF specification for checkboxes, the appearance stream <code>\/AS<\/code> should be set to the same value <code>\/V<\/code>. Failure to do so may mean in some circumstances the checkboxes do not appear. It should be noted that there isn't really strict enforcement within PDF readers, so it is best not to tempt fate and enter a value other than the export value for a checked value. Additionally, all these complicated machinations with the appearance dictionary come into play when dealing with more complex form elements.<\/p>\n<h2>More Complex Forms<\/h2>\n<p>For the purpose of the vaccine clinic application, filling text fields and checkboxes along with the discussion of consolidation files below are sufficient. However, in the interest of not leaving a partial solution. We'll take this topic further and address filling in all other form fields. <\/p>\n<h3>Radio Buttons<\/h3>\n<p>Radio buttons are by far the most complex of the form entries types. Each widget links to <code>\/Kids<\/code> which represent the other buttons in the radio group. But each widget in a radio group will link to the same 'kids'.  Much like the 'parents' for the repeated forms fields with the same name, you need only update each once, but it can't hurt to apply the same update multiple times if it simplifies your code.<\/p>\n<p>In a nutshell, the value <code>\/V<\/code> of each widget in a radio group needs to be set to the export value of the button selected. In each kid, the appearance stream <code>\/AS<\/code> should be set to <code>\/Off<\/code> except for the kid corresponding to the export value. In order to identify the kid with its corresponding export value, we need to look again to the <code>\/N<\/code> field of the appearance dictionary <code>\/AP<\/code> just as was done with the checkboxes.<\/p>\n<p>The resulting code could look like the following:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">def<\/span> <span class=\"nf\">radio_button<\/span><span class=\"p\">(<\/span><span class=\"n\">annotation<\/span><span class=\"p\">,<\/span> <span class=\"n\">value<\/span><span class=\"p\">):<\/span>\n    <span class=\"k\">for<\/span> <span class=\"n\">each<\/span> <span class=\"ow\">in<\/span> <span class=\"n\">annotation<\/span><span class=\"p\">[<\/span><span class=\"s1\">&#39;\/Kids&#39;<\/span><span class=\"p\">]:<\/span>\n        <span class=\"c1\"># determine the export value of each kid<\/span>\n        <span class=\"n\">keys<\/span> <span class=\"o\">=<\/span> <span class=\"n\">each<\/span><span class=\"p\">[<\/span><span class=\"s1\">&#39;\/AP&#39;<\/span><span class=\"p\">][<\/span><span class=\"s1\">&#39;\/N&#39;<\/span><span class=\"p\">]<\/span><span class=\"o\">.<\/span><span class=\"n\">keys<\/span><span class=\"p\">()<\/span>\n        <span class=\"n\">keys<\/span><span class=\"o\">.<\/span><span class=\"n\">remove<\/span><span class=\"p\">(<\/span><span class=\"s1\">&#39;\/Off&#39;<\/span><span class=\"p\">)<\/span>\n        <span class=\"n\">export<\/span> <span class=\"o\">=<\/span> <span class=\"n\">keys<\/span><span class=\"p\">[<\/span><span class=\"mi\">0<\/span><span class=\"p\">]<\/span>\n\n        <span class=\"k\">if<\/span> <span class=\"sa\">f<\/span><span class=\"s1\">&#39;\/<\/span><span class=\"si\">{<\/span><span class=\"n\">value<\/span><span class=\"si\">}<\/span><span class=\"s1\">&#39;<\/span> <span class=\"o\">==<\/span> <span class=\"n\">export<\/span><span class=\"p\">:<\/span>\n            <span class=\"n\">val_str<\/span> <span class=\"o\">=<\/span> <span class=\"n\">pdfrw<\/span><span class=\"o\">.<\/span><span class=\"n\">objects<\/span><span class=\"o\">.<\/span><span class=\"n\">pdfname<\/span><span class=\"o\">.<\/span><span class=\"n\">BasePdfName<\/span><span class=\"p\">(<\/span><span class=\"sa\">f<\/span><span class=\"s1\">&#39;\/<\/span><span class=\"si\">{<\/span><span class=\"n\">value<\/span><span class=\"si\">}<\/span><span class=\"s1\">&#39;<\/span><span class=\"p\">)<\/span>\n        <span class=\"k\">else<\/span><span class=\"p\">:<\/span>\n            <span class=\"n\">val_str<\/span> <span class=\"o\">=<\/span> <span class=\"n\">pdfrw<\/span><span class=\"o\">.<\/span><span class=\"n\">objects<\/span><span class=\"o\">.<\/span><span class=\"n\">pdfname<\/span><span class=\"o\">.<\/span><span class=\"n\">BasePdfName<\/span><span class=\"p\">(<\/span><span class=\"sa\">f<\/span><span class=\"s1\">&#39;\/Off&#39;<\/span><span class=\"p\">)<\/span>\n        <span class=\"n\">each<\/span><span class=\"o\">.<\/span><span class=\"n\">update<\/span><span class=\"p\">(<\/span><span class=\"n\">pdfrw<\/span><span class=\"o\">.<\/span><span class=\"n\">PdfDict<\/span><span class=\"p\">(<\/span><span class=\"n\">AS<\/span><span class=\"o\">=<\/span><span class=\"n\">val_str<\/span><span class=\"p\">))<\/span>\n\n    <span class=\"n\">annotation<\/span><span class=\"o\">.<\/span><span class=\"n\">update<\/span><span class=\"p\">(<\/span><span class=\"n\">pdfrw<\/span><span class=\"o\">.<\/span><span class=\"n\">PdfDict<\/span><span class=\"p\">(<\/span><span class=\"n\">V<\/span><span class=\"o\">=<\/span><span class=\"n\">pdfrw<\/span><span class=\"o\">.<\/span><span class=\"n\">objects<\/span><span class=\"o\">.<\/span><span class=\"n\">pdfname<\/span><span class=\"o\">.<\/span><span class=\"n\">BasePdfName<\/span><span class=\"p\">(<\/span><span class=\"sa\">f<\/span><span class=\"s1\">&#39;\/<\/span><span class=\"si\">{<\/span><span class=\"n\">value<\/span><span class=\"si\">}<\/span><span class=\"s1\">&#39;<\/span><span class=\"p\">)))<\/span>\n<\/code><\/pre><\/div>\n\n<h3>Combo Boxes and Lists<\/h3>\n<p>Both combo boxes and lists are forms of the choice form type. The combo boxes resemble drop down menus and lists are similar to list pickers in HTML. Functionally they are very similar as for form filling.\nThe value <code>\/V<\/code> and appearance stream <code>\/AS<\/code> need to be set to their exported values. The <code>\/Op<\/code> yields a list of lists associating the exported value with the value that appears in the widget. For example if you examine the <code>\/Opt<\/code> field of the gender form field in <code>sample-form3.pdf<\/code> you'll see:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"p\">[[<\/span><span class=\"s1\">&#39;(Male-Value)&#39;<\/span><span class=\"p\">,<\/span> <span class=\"s1\">&#39;(Male)&#39;<\/span><span class=\"p\">],<\/span> <span class=\"p\">[<\/span><span class=\"s1\">&#39;(Female-Value)&#39;<\/span><span class=\"p\">,<\/span> <span class=\"s1\">&#39;(Female)&#39;<\/span><span class=\"p\">]]<\/span>\n<\/code><\/pre><\/div>\n\n<p>where the exported values <code>Male-Value<\/code> and <code>Female-Value<\/code> are associated with the text <code>Male<\/code> and <code>Female<\/code>.<\/p>\n<p>To set the combo box, you simply need to set the value to the export value.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">def<\/span> <span class=\"nf\">combobox<\/span><span class=\"p\">(<\/span><span class=\"n\">annotation<\/span><span class=\"p\">,<\/span> <span class=\"n\">value<\/span><span class=\"p\">):<\/span>\n    <span class=\"n\">export<\/span><span class=\"o\">=<\/span><span class=\"kc\">None<\/span>\n    <span class=\"k\">for<\/span> <span class=\"n\">each<\/span> <span class=\"ow\">in<\/span> <span class=\"n\">annotation<\/span><span class=\"p\">[<\/span><span class=\"s1\">&#39;\/Opt&#39;<\/span><span class=\"p\">]:<\/span>\n        <span class=\"k\">if<\/span> <span class=\"n\">each<\/span><span class=\"p\">[<\/span><span class=\"mi\">1<\/span><span class=\"p\">]<\/span><span class=\"o\">.<\/span><span class=\"n\">to_unicode<\/span><span class=\"p\">()<\/span><span class=\"o\">==<\/span><span class=\"n\">value<\/span><span class=\"p\">:<\/span>\n            <span class=\"n\">export<\/span> <span class=\"o\">=<\/span> <span class=\"n\">each<\/span><span class=\"p\">[<\/span><span class=\"mi\">0<\/span><span class=\"p\">]<\/span><span class=\"o\">.<\/span><span class=\"n\">to_unicode<\/span><span class=\"p\">()<\/span>\n    <span class=\"k\">if<\/span> <span class=\"n\">export<\/span> <span class=\"ow\">is<\/span> <span class=\"kc\">None<\/span><span class=\"p\">:<\/span>\n        <span class=\"k\">raise<\/span> <span class=\"ne\">KeyError<\/span><span class=\"p\">(<\/span><span class=\"sa\">f<\/span><span class=\"s2\">&quot;Export Value: <\/span><span class=\"si\">{<\/span><span class=\"n\">value<\/span><span class=\"si\">}<\/span><span class=\"s2\"> Not Found&quot;<\/span><span class=\"p\">)<\/span>\n    <span class=\"n\">pdfstr<\/span> <span class=\"o\">=<\/span> <span class=\"n\">pdfrw<\/span><span class=\"o\">.<\/span><span class=\"n\">objects<\/span><span class=\"o\">.<\/span><span class=\"n\">pdfstring<\/span><span class=\"o\">.<\/span><span class=\"n\">PdfString<\/span><span class=\"o\">.<\/span><span class=\"n\">encode<\/span><span class=\"p\">(<\/span><span class=\"n\">export<\/span><span class=\"p\">)<\/span>\n    <span class=\"n\">annotation<\/span><span class=\"o\">.<\/span><span class=\"n\">update<\/span><span class=\"p\">(<\/span><span class=\"n\">pdfrw<\/span><span class=\"o\">.<\/span><span class=\"n\">PdfDict<\/span><span class=\"p\">(<\/span><span class=\"n\">V<\/span><span class=\"o\">=<\/span><span class=\"n\">pdfstr<\/span><span class=\"p\">,<\/span> <span class=\"n\">AS<\/span><span class=\"o\">=<\/span><span class=\"n\">pdfstr<\/span><span class=\"p\">))<\/span>\n<\/code><\/pre><\/div>\n\n<p>Lists are structurally very similar. The list of exported values can be found in the <code>\/Opt<\/code> field. The main difference is that lists based on their configuration can take multiple values. Multiple values can be set with Pdfrw by setting <code>\\V<\/code> and <code>\\AS<\/code> to a list of <code>PdfString<\/code>s. We write it as separate helpers, but of course, you could combine the code into one function.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">def<\/span> <span class=\"nf\">listbox<\/span><span class=\"p\">(<\/span><span class=\"n\">annotation<\/span><span class=\"p\">,<\/span> <span class=\"n\">values<\/span><span class=\"p\">):<\/span>\n    <span class=\"n\">pdfstrs<\/span><span class=\"o\">=<\/span><span class=\"p\">[]<\/span>\n    <span class=\"k\">for<\/span> <span class=\"n\">value<\/span> <span class=\"ow\">in<\/span> <span class=\"n\">values<\/span><span class=\"p\">:<\/span>\n        <span class=\"n\">export<\/span><span class=\"o\">=<\/span><span class=\"kc\">None<\/span>\n        <span class=\"k\">for<\/span> <span class=\"n\">each<\/span> <span class=\"ow\">in<\/span> <span class=\"n\">annotation<\/span><span class=\"p\">[<\/span><span class=\"s1\">&#39;\/Opt&#39;<\/span><span class=\"p\">]:<\/span>\n            <span class=\"k\">if<\/span> <span class=\"n\">each<\/span><span class=\"p\">[<\/span><span class=\"mi\">1<\/span><span class=\"p\">]<\/span><span class=\"o\">.<\/span><span class=\"n\">to_unicode<\/span><span class=\"p\">()<\/span><span class=\"o\">==<\/span><span class=\"n\">value<\/span><span class=\"p\">:<\/span>\n                <span class=\"n\">export<\/span> <span class=\"o\">=<\/span> <span class=\"n\">each<\/span><span class=\"p\">[<\/span><span class=\"mi\">0<\/span><span class=\"p\">]<\/span><span class=\"o\">.<\/span><span class=\"n\">to_unicode<\/span><span class=\"p\">()<\/span>\n        <span class=\"k\">if<\/span> <span class=\"n\">export<\/span> <span class=\"ow\">is<\/span> <span class=\"kc\">None<\/span><span class=\"p\">:<\/span>\n            <span class=\"k\">raise<\/span> <span class=\"ne\">KeyError<\/span><span class=\"p\">(<\/span><span class=\"sa\">f<\/span><span class=\"s2\">&quot;Export Value: <\/span><span class=\"si\">{<\/span><span class=\"n\">value<\/span><span class=\"si\">}<\/span><span class=\"s2\"> Not Found&quot;<\/span><span class=\"p\">)<\/span>\n        <span class=\"n\">pdfstrs<\/span><span class=\"o\">.<\/span><span class=\"n\">append<\/span><span class=\"p\">(<\/span><span class=\"n\">pdfrw<\/span><span class=\"o\">.<\/span><span class=\"n\">objects<\/span><span class=\"o\">.<\/span><span class=\"n\">pdfstring<\/span><span class=\"o\">.<\/span><span class=\"n\">PdfString<\/span><span class=\"o\">.<\/span><span class=\"n\">encode<\/span><span class=\"p\">(<\/span><span class=\"n\">export<\/span><span class=\"p\">))<\/span>\n    <span class=\"n\">annotation<\/span><span class=\"o\">.<\/span><span class=\"n\">update<\/span><span class=\"p\">(<\/span><span class=\"n\">pdfrw<\/span><span class=\"o\">.<\/span><span class=\"n\">PdfDict<\/span><span class=\"p\">(<\/span><span class=\"n\">V<\/span><span class=\"o\">=<\/span><span class=\"n\">pdfstrs<\/span><span class=\"p\">,<\/span> <span class=\"n\">AS<\/span><span class=\"o\">=<\/span><span class=\"n\">pdfstrs<\/span><span class=\"p\">))<\/span>\n<\/code><\/pre><\/div>\n\n<h3>Putting it all together<\/h3>\n<p>Now that we have shown how to fill in all the specific types of form elements in a PDF field. (With the exception of the signature form, which probably should not be filled programatically). Let's put this all together. If you have access to the forms themselves, you will know what type of form field each corresponds to each label. However, it would be nice to be able to determine the field type and work appropriately. <\/p>\n<h5>Determining Form Field Types Programmatically<\/h5>\n<p>To address the missing ingredient, it is important to understand that fillable forms fall into 4 form types, button (push button, checkboxes and radio buttons), text, choice (combo box and list box) and signature. They correspond to following values of the  <code>\/FT<\/code> form type field of our annotation, <code>\/Btn<\/code>, <code>\/Tx<\/code>, <code>\/Ch<\/code> and <code>\/Sig<\/code>, respectively. We will omit the signature type as we do not support filling in signature. Furthermore, the push button is a widget which can cause an action but is not fillable. <\/p>\n<p>To distinguish the types of buttons and choices, we can examine the form flags <code>\/Ff<\/code> field. For radio buttons, the 16th bit is set. For combo box the 18th bit is set. Please note that <code>annotation['\/Ff']<\/code> returns a <code>PdfObject<\/code> when returned and must be coerced into an <code>int<\/code> for bit testing.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">def<\/span> <span class=\"nf\">field_type<\/span><span class=\"p\">(<\/span><span class=\"n\">annotation<\/span><span class=\"p\">):<\/span>\n    <span class=\"n\">ft<\/span> <span class=\"o\">=<\/span> <span class=\"n\">annotation<\/span><span class=\"p\">[<\/span><span class=\"s1\">&#39;\/FT&#39;<\/span><span class=\"p\">]<\/span>\n    <span class=\"n\">ff<\/span> <span class=\"o\">=<\/span> <span class=\"n\">annotation<\/span><span class=\"p\">[<\/span><span class=\"s1\">&#39;\/Ff&#39;<\/span><span class=\"p\">]<\/span>\n\n    <span class=\"k\">if<\/span> <span class=\"n\">ft<\/span> <span class=\"o\">==<\/span> <span class=\"s1\">&#39;\/Tx&#39;<\/span><span class=\"p\">:<\/span>\n        <span class=\"k\">return<\/span> <span class=\"s1\">&#39;text&#39;<\/span>\n    <span class=\"k\">if<\/span> <span class=\"n\">ft<\/span> <span class=\"o\">==<\/span> <span class=\"s1\">&#39;\/Ch&#39;<\/span><span class=\"p\">:<\/span>\n        <span class=\"k\">if<\/span> <span class=\"n\">ff<\/span> <span class=\"ow\">and<\/span> <span class=\"nb\">int<\/span><span class=\"p\">(<\/span><span class=\"n\">ff<\/span><span class=\"p\">)<\/span> <span class=\"o\">&amp;<\/span> <span class=\"mi\">1<\/span> <span class=\"o\">&lt;&lt;<\/span> <span class=\"mi\">17<\/span><span class=\"p\">:<\/span>  <span class=\"c1\"># test 18th bit<\/span>\n            <span class=\"k\">return<\/span> <span class=\"s1\">&#39;combo&#39;<\/span>\n        <span class=\"k\">else<\/span><span class=\"p\">:<\/span>\n            <span class=\"k\">return<\/span> <span class=\"s1\">&#39;list&#39;<\/span>\n    <span class=\"k\">if<\/span> <span class=\"n\">ft<\/span> <span class=\"o\">==<\/span> <span class=\"s1\">&#39;\/Btn&#39;<\/span><span class=\"p\">:<\/span>\n        <span class=\"k\">if<\/span> <span class=\"n\">ff<\/span> <span class=\"ow\">and<\/span> <span class=\"nb\">int<\/span><span class=\"p\">(<\/span><span class=\"n\">ff<\/span><span class=\"p\">)<\/span> <span class=\"o\">&amp;<\/span> <span class=\"mi\">1<\/span> <span class=\"o\">&lt;&lt;<\/span> <span class=\"mi\">15<\/span><span class=\"p\">:<\/span>  <span class=\"c1\"># test 16th bit<\/span>\n            <span class=\"k\">return<\/span> <span class=\"s1\">&#39;radio&#39;<\/span>\n        <span class=\"k\">else<\/span><span class=\"p\">:<\/span>\n            <span class=\"k\">return<\/span> <span class=\"s1\">&#39;checkbox&#39;<\/span>\n<\/code><\/pre><\/div>\n\n<p>For completeness, we should present a text_form filler helper.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">def<\/span> <span class=\"nf\">text_form<\/span><span class=\"p\">(<\/span><span class=\"n\">annotation<\/span><span class=\"p\">,<\/span> <span class=\"n\">value<\/span><span class=\"p\">):<\/span>\n    <span class=\"n\">pdfstr<\/span> <span class=\"o\">=<\/span> <span class=\"n\">pdfrw<\/span><span class=\"o\">.<\/span><span class=\"n\">objects<\/span><span class=\"o\">.<\/span><span class=\"n\">pdfstring<\/span><span class=\"o\">.<\/span><span class=\"n\">PdfString<\/span><span class=\"o\">.<\/span><span class=\"n\">encode<\/span><span class=\"p\">(<\/span><span class=\"n\">value<\/span><span class=\"p\">)<\/span>\n    <span class=\"n\">annotation<\/span><span class=\"o\">.<\/span><span class=\"n\">update<\/span><span class=\"p\">(<\/span><span class=\"n\">pdfrw<\/span><span class=\"o\">.<\/span><span class=\"n\">PdfDict<\/span><span class=\"p\">(<\/span><span class=\"n\">V<\/span><span class=\"o\">=<\/span><span class=\"n\">pdfstr<\/span><span class=\"p\">,<\/span> <span class=\"n\">AS<\/span><span class=\"o\">=<\/span><span class=\"n\">pdfstr<\/span><span class=\"p\">))<\/span>\n<\/code><\/pre><\/div>\n\n<p>So now we have all the building blocks to put an automatic form filler together. The finished form filler can be found in our github repository at.<\/p>\n<h2>Consolidating Multiple Filled Forms<\/h2>\n<p>There are two problems with consolidating multiple filled forms. The first problem is that when two PDF files are merged matching names are associated with each other. For instance, if I had John Doe entered in one form and Jane Doe in the second, when I combine them John Doe will override the second form's name field and John Doe would appear in both forms. The second problem is that most simple command line or programmatic methods of combining two or more PDF files lose form data. One solution is to \"flatten\" the each PDF file. This is equivalent to printing the file to PDF. In effect, this bakes in the filled form values and does not permit the editing the fields. Going even further, one could render the PDFs as images if the only requirement is that the combined files be printable. However, at the surface tools like <code>ghostscript<\/code> and <code>imagemagick<\/code> don't do a good job of preserving form data. Other tools like PDFUnite don't solve any of these problems.<\/p>\n<h3>Form Field Name Collisions<\/h3>\n<p>In our use case of the vaccine clinic, we have the same form being filled out for multiple patients. So to combine a batch of these requires all form field names to be different. The solution is quite simple, in the process of filling out the form using the code above, we can also rename (set) the value of <code>\/T<\/code>. <\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">def<\/span> <span class=\"nf\">form_filler<\/span><span class=\"p\">(<\/span><span class=\"n\">in_path<\/span><span class=\"p\">,<\/span> <span class=\"n\">data<\/span><span class=\"p\">,<\/span> <span class=\"n\">out_path<\/span><span class=\"p\">,<\/span> <span class=\"n\">suffix<\/span><span class=\"p\">):<\/span>\n    <span class=\"n\">pdf<\/span> <span class=\"o\">=<\/span> <span class=\"n\">pdfrw<\/span><span class=\"o\">.<\/span><span class=\"n\">PdfReader<\/span><span class=\"p\">(<\/span><span class=\"n\">in_path<\/span><span class=\"p\">)<\/span>\n    <span class=\"k\">for<\/span> <span class=\"n\">page<\/span> <span class=\"ow\">in<\/span> <span class=\"n\">pdf<\/span><span class=\"o\">.<\/span><span class=\"n\">pages<\/span><span class=\"p\">:<\/span>\n        <span class=\"n\">annotations<\/span> <span class=\"o\">=<\/span> <span class=\"n\">page<\/span><span class=\"p\">[<\/span><span class=\"s1\">&#39;\/Annots&#39;<\/span><span class=\"p\">]<\/span>\n        <span class=\"k\">if<\/span> <span class=\"n\">annotations<\/span> <span class=\"ow\">is<\/span> <span class=\"kc\">None<\/span><span class=\"p\">:<\/span>\n            <span class=\"k\">continue<\/span>\n\n        <span class=\"k\">for<\/span> <span class=\"n\">annotation<\/span> <span class=\"ow\">in<\/span> <span class=\"n\">annotations<\/span><span class=\"p\">:<\/span>\n            <span class=\"k\">if<\/span> <span class=\"n\">annotation<\/span><span class=\"p\">[<\/span><span class=\"s1\">&#39;\/SubType&#39;<\/span><span class=\"p\">]<\/span> <span class=\"o\">==<\/span> <span class=\"s1\">&#39;\/Widget&#39;<\/span><span class=\"p\">:<\/span>\n                <span class=\"n\">key<\/span> <span class=\"o\">=<\/span> <span class=\"n\">annotation<\/span><span class=\"p\">[<\/span><span class=\"s1\">&#39;\/T&#39;<\/span><span class=\"p\">]<\/span><span class=\"o\">.<\/span><span class=\"n\">to_unicode<\/span><span class=\"p\">()<\/span>\n                <span class=\"k\">if<\/span> <span class=\"n\">key<\/span> <span class=\"ow\">in<\/span> <span class=\"n\">data<\/span><span class=\"p\">:<\/span>\n                    <span class=\"n\">pdfstr<\/span> <span class=\"o\">=<\/span> <span class=\"n\">pdfrw<\/span><span class=\"o\">.<\/span><span class=\"n\">objects<\/span><span class=\"o\">.<\/span><span class=\"n\">pdfstring<\/span><span class=\"o\">.<\/span><span class=\"n\">PdfString<\/span><span class=\"o\">.<\/span><span class=\"n\">encode<\/span><span class=\"p\">(<\/span><span class=\"n\">data<\/span><span class=\"p\">[<\/span><span class=\"n\">key<\/span><span class=\"p\">])<\/span>\n                    <span class=\"n\">new_key<\/span> <span class=\"o\">=<\/span> <span class=\"n\">key<\/span> <span class=\"o\">+<\/span> <span class=\"n\">suffix<\/span>\n                    <span class=\"n\">annotation<\/span><span class=\"o\">.<\/span><span class=\"n\">update<\/span><span class=\"p\">(<\/span><span class=\"n\">pdfrw<\/span><span class=\"o\">.<\/span><span class=\"n\">PdfDict<\/span><span class=\"p\">(<\/span><span class=\"n\">V<\/span><span class=\"o\">=<\/span><span class=\"n\">pdfstr<\/span><span class=\"p\">,<\/span> <span class=\"n\">T<\/span><span class=\"o\">=<\/span><span class=\"n\">new_key<\/span><span class=\"p\">))<\/span>\n        <span class=\"n\">pdf<\/span><span class=\"o\">.<\/span><span class=\"n\">Root<\/span><span class=\"o\">.<\/span><span class=\"n\">AcroForm<\/span><span class=\"o\">.<\/span><span class=\"n\">update<\/span><span class=\"p\">(<\/span>\n            <span class=\"n\">pdfrw<\/span><span class=\"o\">.<\/span><span class=\"n\">PdfDict<\/span><span class=\"p\">(<\/span><span class=\"n\">NeedAppearances<\/span><span class=\"o\">=<\/span><span class=\"n\">pdfrw<\/span><span class=\"o\">.<\/span><span class=\"n\">PdfObject<\/span><span class=\"p\">(<\/span><span class=\"s1\">&#39;true&#39;<\/span><span class=\"p\">)))<\/span>\n        <span class=\"n\">pdfrw<\/span><span class=\"o\">.<\/span><span class=\"n\">PdfWriter<\/span><span class=\"p\">()<\/span><span class=\"o\">.<\/span><span class=\"n\">write<\/span><span class=\"p\">(<\/span><span class=\"n\">out_path<\/span><span class=\"p\">,<\/span> <span class=\"n\">pdf<\/span><span class=\"p\">)<\/span>\n<\/code><\/pre><\/div>\n\n<p>So all you have to do is supply a unique suffix to each form. In our case, we simply number the batch so the suffix is just a sequential number.<\/p>\n<h3>Combining the files<\/h3>\n<p>If you search the internet for combine PDF files using pdfrw, you'll get a recipe like the following.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">writer<\/span> <span class=\"o\">=<\/span> <span class=\"n\">PdfWriter<\/span><span class=\"p\">()<\/span>\n<span class=\"k\">for<\/span> <span class=\"n\">fname<\/span> <span class=\"ow\">in<\/span> <span class=\"n\">files<\/span><span class=\"p\">:<\/span>\n    <span class=\"n\">r<\/span> <span class=\"o\">=<\/span> <span class=\"n\">PdfReader<\/span><span class=\"p\">(<\/span><span class=\"n\">fname<\/span><span class=\"p\">)<\/span>\n    <span class=\"n\">writer<\/span><span class=\"o\">.<\/span><span class=\"n\">addpages<\/span><span class=\"p\">(<\/span><span class=\"n\">r<\/span><span class=\"o\">.<\/span><span class=\"n\">pages<\/span><span class=\"p\">)<\/span>\n<span class=\"n\">writer<\/span><span class=\"o\">.<\/span><span class=\"n\">write<\/span><span class=\"p\">(<\/span><span class=\"s2\">&quot;output.pdf&quot;<\/span><span class=\"p\">)<\/span>\n<\/code><\/pre><\/div>\n\n<p>While you don't lose the form data per se, you lose rendering information and hence the combined PDF fails to show the fields. The problem comes from the fact that the written PDF does not have an interactive form dictionary (see &sect;12.7.2 of the PDF 1.7 specification). In particular the interactive forms dictionary contains the boolean <code>NeedAppearances<\/code> to be set in order for fields to be shown. If the forms being combined have different interactive form dictionaries, they will need to be merged. This is beyond the scope of this blog and the issues has not really been addressed though the <a href=\"https:\/\/stackoverflow.com\/questions\/57008782\/pypdf2-pdffilemerger-loosing-pdf-module-in-merged-file\">stackoverflow article<\/a>\nendeavors to make a first attempt. For our purposes since the source form is identical amongst the various copies, any <code>AcroForm<\/code> dictionary can be used. <\/p>\n<p>After obtaining the dictionary, from <code>pdf.Root.AcroForm<\/code> (assuming the reader is stored in <code>pdf<\/code>), it is not clear how to add it to the <code>PdfWriter<\/code> object. The clue comes from a simple recipe for copying a pdf file.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">pdf<\/span> <span class=\"o\">=<\/span> <span class=\"n\">PdfReader<\/span><span class=\"p\">(<\/span><span class=\"n\">in_file<\/span><span class=\"p\">)<\/span>\n<span class=\"n\">PdfWriter<\/span><span class=\"p\">()<\/span><span class=\"o\">.<\/span><span class=\"n\">write<\/span><span class=\"p\">(<\/span><span class=\"n\">out_file<\/span><span class=\"p\">,<\/span> <span class=\"n\">pdf<\/span><span class=\"p\">)<\/span>\n<\/code><\/pre><\/div>\n\n<p>If one examines, these source code, the second parameter is set to the attribute <code>trailer<\/code>, so assuming <code>acro_form<\/code> contains the  interactive forms <code>PdfDict<\/code> you can set it by <code>writer.trailer.Root.AcroForm = acro_form<\/code>.<\/p>\n<h3>Double Sided Printing<\/h3>\n<p>This issue is less about <code>pdfrw<\/code> than just making sure certain issues are taken into consideration. For example, in the clinic example, we wanted to pre-populate vaccination cards provided from a digital template from the CDC. Each card has a front and back but there are 6 cards per sheet. You must insure the information for the front of one card corresponds to the correct back of the card. In our case with 6 cards, if the front is arrayed like this:<\/p>\n<table>\n<thead>\n<tr>\n<th align=\"center\">1<\/th>\n<th align=\"center\">3<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td align=\"center\">3<\/td>\n<td align=\"center\">4<\/td>\n<\/tr>\n<tr>\n<td align=\"center\">5<\/td>\n<td align=\"center\">6<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>Then the back needs to be arranged as follows provided you are printing with the \"flip along the long side\" option which you should use unless the back is intentionally printed upside down relative to the front.<\/p>\n<table>\n<thead>\n<tr>\n<th align=\"center\">2<\/th>\n<th align=\"center\">1<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td align=\"center\">4<\/td>\n<td align=\"center\">3<\/td>\n<\/tr>\n<tr>\n<td align=\"center\">6<\/td>\n<td align=\"center\">5<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>Another consideration when printing double sided is that if you document has an odd number of pages you will need to insert a blank page somewhere to make the page count even. Otherwise, when you print a bundle, the first page of the second document will be on the back of last page of the first.<\/p>\n<h3>Blank Page<\/h3>\n<p>While the <code>pdfrw<\/code> library does not have a method for producing a blank page, but there is a simple recipe taken from this <a href=\"https:\/\/www.binpress.com\/pdfrw-python-pdf-library\/\">article<\/a>. <\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">def<\/span> <span class=\"nf\">blank_page<\/span><span class=\"p\">():<\/span>\n    <span class=\"n\">blank<\/span> <span class=\"o\">=<\/span> <span class=\"n\">pdfrw<\/span><span class=\"o\">.<\/span><span class=\"n\">PageMerge<\/span><span class=\"p\">()<\/span>\n    <span class=\"n\">blank<\/span><span class=\"o\">.<\/span><span class=\"n\">mbox<\/span> <span class=\"o\">=<\/span> <span class=\"p\">[<\/span><span class=\"mi\">0<\/span><span class=\"p\">,<\/span> <span class=\"mi\">0<\/span><span class=\"p\">,<\/span> <span class=\"mi\">612<\/span><span class=\"p\">,<\/span> <span class=\"mi\">792<\/span><span class=\"p\">]<\/span> <span class=\"c1\"># 8.5 x 11<\/span>\n    <span class=\"n\">blank<\/span> <span class=\"o\">=<\/span> <span class=\"n\">blank<\/span><span class=\"o\">.<\/span><span class=\"n\">render<\/span><span class=\"p\">()<\/span>\n    <span class=\"k\">return<\/span> <span class=\"n\">blank<\/span>\n<\/code><\/pre><\/div>\n\n<p>Please note that the mbox specifies the page dimensions in points. In our case, all documents are letter size. Of course, it is easy to turn <code>blank_page<\/code> into a function which takes page size as a parameter and generates a blank page. It should also be noted that the <code>pages<\/code> attribute of the <code>PdfReader<\/code> object returned by <code>PdfReader<\/code> is merely a list so it is easy to insert the blank page where desired. In our particular example, the last two pages were meant to be printed back to back so we needed to insert the blank page before the last two. The code ended up looking like the following<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">pages<\/span> <span class=\"o\">=<\/span> <span class=\"n\">PdfReader<\/span><span class=\"p\">(<\/span><span class=\"n\">doc_name<\/span><span class=\"p\">)<\/span><span class=\"o\">.<\/span><span class=\"n\">pages<\/span>\n<span class=\"k\">if<\/span> <span class=\"nb\">len<\/span><span class=\"p\">(<\/span><span class=\"n\">pages<\/span><span class=\"p\">)<\/span><span class=\"o\">%<\/span><span class=\"mi\">2<\/span><span class=\"o\">==<\/span><span class=\"mi\">1<\/span> <span class=\"ow\">and<\/span> <span class=\"n\">double_sided<\/span><span class=\"p\">:<\/span> <span class=\"c1\"># Odd number of pages<\/span>\n    <span class=\"n\">writer<\/span><span class=\"o\">.<\/span><span class=\"n\">addpages<\/span><span class=\"p\">(<\/span><span class=\"n\">pages<\/span><span class=\"p\">[<\/span><span class=\"mi\">0<\/span><span class=\"p\">:<\/span><span class=\"o\">-<\/span><span class=\"mi\">2<\/span><span class=\"p\">])<\/span>\n    <span class=\"n\">writer<\/span><span class=\"o\">.<\/span><span class=\"n\">addpage<\/span><span class=\"p\">(<\/span><span class=\"n\">blank_page<\/span><span class=\"p\">())<\/span>\n    <span class=\"n\">writer<\/span><span class=\"o\">.<\/span><span class=\"n\">addpages<\/span><span class=\"p\">(<\/span><span class=\"n\">pages<\/span><span class=\"p\">[<\/span><span class=\"o\">-<\/span><span class=\"mi\">2<\/span><span class=\"p\">:])<\/span>\n<\/code><\/pre><\/div>\n\n<p>where <code>double_sided<\/code> was a flag indicating whether we wanted to go into \"double sided mode.\"<\/p>\n<h2>Conclusion<\/h2>\n<p>A complete functional version of this PDF form filler can be found in our github repository. This process was able to produce large quantities of pre filled forms for seniors seeking Covid vaccinations relieving one of the bottlenecks that have plagued many other vaccine clinics. <\/p>\n<div class=\"highlight\"><pre><span><\/span><code>\n<\/code><\/pre><\/div>","category":[{"@attributes":{"term":"Algorithms"}},{"@attributes":{"term":"PDF"}},{"@attributes":{"term":"Fillable Forms"}},{"@attributes":{"term":"Python"}}]},{"title":"Visualizations with Dash Leaflet Series - Part 1: Setup and Configuration","link":{"@attributes":{"href":"https:\/\/WestHealth.github.io\/visualizations-with-dash-leaflet-series-part-1-setup-and-configuration.html","rel":"alternate"}},"published":"2021-02-16T09:37:00-08:00","updated":"2021-02-16T09:37:00-08:00","author":{"name":"Haw-minn Lu"},"id":"tag:westhealth.github.io,2021-02-16:\/visualizations-with-dash-leaflet-series-part-1-setup-and-configuration.html","summary":"<h1>Introduction<\/h1>\n<p>This tutorial series came about when the Data Science team here at the West Health Institute was asked to provide a highly interactive <a href=\"https:\/\/www.westhealth.org\/resource\/vaxmap-potential-covid-19-vaccine-locations\/\">map visualization<\/a> by the West Health Policy Center and the University of Pittsburg School of Pharmacy for their study: <em>Access to Potential COVID-19\nVaccine Administration Facilities \u2026<\/em><\/p>","content":"<h1>Introduction<\/h1>\n<p>This tutorial series came about when the Data Science team here at the West Health Institute was asked to provide a highly interactive <a href=\"https:\/\/www.westhealth.org\/resource\/vaxmap-potential-covid-19-vaccine-locations\/\">map visualization<\/a> by the West Health Policy Center and the University of Pittsburg School of Pharmacy for their study: <em>Access to Potential COVID-19\nVaccine Administration Facilities:\nA Geographic Information\nSystems Analysis<\/em>. We'll describe more about the visualization later.<\/p>\n<p>In the evaluation process Dash Leaflet prove to be a powerful though underdocumented library. As a result, many sources of documentation as well as some source code sleuthing were required to acquire sufficent expertise to implement the visualization. This tutorial series serves as a vessel to share this expertise with the community at large.<\/p>\n<h2>What is Dash Leaflet?<\/h2>\n<p>Dash leaflet is a lightweight wrapper around the popular <code>Leaflet.js<\/code> library but also includes <code>supercluster<\/code>, MapBox's open source clustering library. The wrapper presents the various React components of <code>Leaflet.js<\/code> as dash components that are easy to configure to those comfortable with the <code>dash<\/code> framework. <\/p>\n<h2>Why Dash Leaflet?<\/h2>\n<p>There are other map visualizations and pythonization of <code>Leaflet.js<\/code> available, so why pick Dash Leaflet amongst these choices. In our case, it came down to our requirements and Dash Leaflet was the only one which met them.<\/p>\n<p>At a minumum requirements were that it include a reasonably fast clustering solution, be able to handle data on the order of 80,000 features, be low cost or free and be deployable as a standalone app.<\/p>\n<p>MapBox was a leading candidate. MapBox provided map visualization capabilities and had a very fast clustering algorithm which runs client side and even has components in <code>dash<\/code>. However, MapBox works on a freemium model and could become too costly for a non-profit project such as the aforementioned study. Additionally, using MapBox would require key management to be incorporated. MapBox might have remained the option of choice had we not found Dash Leaflet.<\/p>\n<p>Jupyter's <code>ipyleaflet<\/code> was another potential candidate. In truth, like MapBox, it has a lot more customizations baked in (such as predefined marker shapes). The Achilles heel for <code>ipyleaflet<\/code> is that there was no standard deployment method as a standalone app. The documentation recommended the use of <code>voila<\/code> for deployment, but for our particular use case, this resulted in a startup time of up to 15 minutes <strong>per session<\/strong>, which simply wasn't acceptable.<\/p>\n<p>With all these benefits, Dash Leaflet is very barebones and does not include many of the conveniences of some other packages so some additional effort is required to perform customizations.<\/p>\n<h2>Resources<\/h2>\n<p><a href=\"https:\/\/dash-leaflet.herokuapp.com\/\">Documentation<\/a> is somewhat scant with Dash Leaflet. The bulk of the documentation are examples of usage with reference to the <a href=\"https:\/\/leafletjs.com\/reference-1.7.1.html\"><code>Leaflet.js<\/code> documentation<\/a>. Since much of the Dash Leaflet components mirror that of <code>Leaflet.js<\/code>, one can get a majority of the needed information. One deficiency  is that it is often unclear what properties are exposed to <code>dash<\/code>. Often to figure this out, a little sleuthing in the <a href=\"https:\/\/github.com\/thedirtyfew\/dash-leaflet\">source code<\/a> is necessary in particular in the <code>src\/lib\/components\/<\/code> directory. The code itself is sufficiently documented to make this determination.<\/p>\n<h1>An Complex Example<\/h1>\n<p>We use the aforementioned Covid Vaccination visualization as an example. The purpose to of this section is to give an overview of the custom features and explain at a high level how the features were implemented. If you are interested in the subject matter please refer to the study mentioned above.<\/p>\n<p>If this visualization takes some time to start up initially it is a consequence of our use of AWS Lambda functions to deploy the app not a consequence of the Dash Leaflet framework. You can deploy to a dedicated server if you want to avoid this issue.<\/p>\n<iframe style=\"width: 1600px; height: 1200px; overflow: hidden; border: none;\" src=\"https:\/\/9sawbccap0.execute-api.us-west-2.amazonaws.com\/test\" width=\"1600\" height=\"1200\" scrolling=\"no\">VaxMap 2.0<\/iframe>\n\n<p>The visualization has two active modes, the overview mode was described in the national view. After a state is selected the visualization enters a detail mode. The selection of various options can yield both a state or county view while in the detail mode.<\/p>\n<p>When the visualization is first shown a national view is presented, each state has a custom marker indicating the number of potential vaccination centers as projected by the study. Over each marker is a tooltip which breaks down the vaccination centers into four categories. These markers are precalculated at this level and do not use clusters. They are intended to give a similar look and feel as the clusters that are presented in the state and county views. To this end the markers are placed at the centroid of each state. Hovering over each state highlights it. Clicking on a state or selecting it from the drop down menus on the lower left selects the state and goes into a state view.<\/p>\n<p>Under the hood, clicking on a state triggers a callback which sets the state of the drop down menu. Because of this zooming is governed by the dropdown menu's callback so automatic zooming features built into <code>leaflet<\/code> can not be used.<\/p>\n<p>Once the state is selected, the visualization enters the detail mode. At this point the counties for the selected state are shown. For basic navigation, clicking on the county activates the dropdown menu's callback for each state. Hovering over any county displays an information box in the upper right corner with statistics about the county. Clicking on a neighboring state selects that state. At the detail level potential vaccine centers are clustered employing the <code>MapBox<\/code> <code>supercluster<\/code> library. An automatic feature of the library is that clicking on the cluster marker zooms in on the cluster until that cluster separates into smaller clusters or individual sites. A custom tooltip is created deriving from the contents of a given cluster.<\/p>\n<p>Finally, the individual potential vaccine sites have different symbols for markers. The marker legend is also a filter which activates the dropdown callback for facility type. <\/p>\n<p>All of these features and customizations will be explained in subsequent blog articles.<\/p>\n<h1>Getting Setup<\/h1>\n<p>Our <a href=\"https:\/\/github.com\/WestHealth\/tutorial-blog-material\/tree\/main\/leaflet-tutorial\">github repository<\/a> contains Jupyter Notebooks for all the articles.<\/p>\n<p>If you are skilled in python, Jupyter Notebooks is not required.<\/p>\n<h2>Prerequesites<\/h2>\n<p>For this tutorial series, it is expected that the reader be moderately skilled in programming in python and using <code>plotly dash<\/code> and is comfortable in the Jupyter environment. <\/p>\n<p>While not required, familiarity with pandas, geopandas and javascript is helpful.<\/p>\n<h2>Required Libraries<\/h2>\n<p>To run the notebooks, it is assumed that the following python packages be installed. <\/p>\n<ul>\n<li><code>dash<\/code><\/li>\n<li><code>jupyter-dash<\/code><\/li>\n<li><code>dash-leaflet<\/code><\/li>\n<li><code>pandas<\/code><\/li>\n<li><code>dash_extensions<\/code><\/li>\n<li><code>geopandas<\/code><\/li>\n<\/ul>\n<p>If you are using <code>conda<\/code> or <code>mamba<\/code>, please note that at the time of the writing of this article, <code>conda<\/code>'s dependencies have an issue when installing <code>jupyter-dash<\/code>. Dash must be installed with <code>conda<\/code> first before <code>jupyter-dash<\/code> or an obsolete version of <code>dash<\/code> will get installed.<\/p>\n<p>A <a href=\"https:\/\/raw.githubusercontent.com\/WestHealth\/tutorial-blog-material\/main\/leaflet-tutorial\/Dockerfile\"><code>Dockerfile<\/code><\/a> is provided as well which enables the reader to run the jupyter environment inside a docker container. If you use docker it is recommended that you install <code>jupyter-server-proxy<\/code>.<\/p>\n<h2>Getting Started<\/h2>\n<p>To insure your environment is properly set up. The <a href=\"https:\/\/github.com\/WestHealth\/tutorial-blog-material\/blob\/main\/leaflet-tutorial\/notebooks\/01-getting-started.ipynb\">notebook<\/a> contains the \"Getting Started\" example from the <code>Dash-Leaflet<\/code> documentation ported to the Jupyter environment. This notebooks is designed to be compatible with operating in the docker environment. If you are not running in the docker enviroment. The following line is not necessary and can be commented out:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>JupyterDash.infer_jupyter_proxy_config()\n<\/code><\/pre><\/div>\n\n<p>What this line does is it enables <code>JupyterDash<\/code> to use Jupyter Server Proxy to proxy all connections to a single exposed port. While <code>JupyterDash<\/code> is a wrapper that allows <code>dash<\/code> to run inside a notebook. <code>Dash<\/code> still opens a local flask server on a selected port.<\/p>\n<p>Additionally, <code>JupyterDash<\/code> replaces <code>Dash<\/code> in the creation of the <code>app<\/code>. The final change is that <code>JupyterDash<\/code>'s <code>app<\/code> takes an <code>mode<\/code> parameter. By setting, <code>mode<\/code> to <code>'inline'<\/code> the visualization will display inside the notebook.<\/p>\n<p>Finally, one might noticed that the port number is randomly selected. This is to permit the running of simultaneous <code>dash<\/code> apps within any container. Remember while <code>JupyterDash<\/code> inlines <code>dash<\/code> it still uses a port even if it is internal to the container. By randomly selecting a port, it is unlikely you will have a port number conflict.<\/p>\n<h1>Outline<\/h1>\n<p>The following parts are tentatively scheduled for this blog series. This section will be update as the series is published.<\/p>\n<ul>\n<li>Part 2 - Basics - Review of Dash, Geopandas and Dash-Leaflet<\/li>\n<li>Part 3 - Feature Outline Maps<\/li>\n<li>Part 4 - Scatter Plot Maps<\/li>\n<li>Part 5 - Cluster Maps<\/li>\n<li>Part 6 - Complex Visualizations Using Multiple Layers<\/li>\n<li>Part 7 - Special Tricks and Hacks<\/li>\n<\/ul>","category":[{"@attributes":{"term":"Visualizations"}},{"@attributes":{"term":"Dash"}},{"@attributes":{"term":"Leaflet"}},{"@attributes":{"term":"Python"}}]},{"title":"Metamorphic Truth","link":{"@attributes":{"href":"https:\/\/WestHealth.github.io\/metamorphic-truth.html","rel":"alternate"}},"published":"2020-02-25T11:36:00-08:00","updated":"2020-02-25T11:36:00-08:00","author":{"name":"Haw-minn Lu"},"id":"tag:westhealth.github.io,2020-02-25:\/metamorphic-truth.html","summary":"<h2>What is Metamorphic Truth?<\/h2>\n<p>Metamorphic truth is a method of training an Artificial Neural Network (ANN)\nwhere the \"truth\" supplied during training is not fixed and may depend on the\nprediction made by the ANN. More specifically during training a truth\nmetamorphism is defined as a function of the prediction \u2026<\/p>","content":"<h2>What is Metamorphic Truth?<\/h2>\n<p>Metamorphic truth is a method of training an Artificial Neural Network (ANN)\nwhere the \"truth\" supplied during training is not fixed and may depend on the\nprediction made by the ANN. More specifically during training a truth\nmetamorphism is defined as a function of the prediction, the ground truth, and\nperhaps additional metadata.<\/p>\n<h2>History and Concept<\/h2>\n<p>The concept arose when building a denoising autoencoder with missing data.  The\nobvious approach of filling in the missing data with dummy data may work well\nbut could also ultimately distort the loss function.  By viewing ANN training\nas a feedback system, it became clear that the loss function should somehow\nignore the dummy filled-in data and thus remove the downstream bias from these\nterms.  Then, the  mean square error (MSE) error would look like<\/p>\n<div class=\"math\">$$\\sum_{i\\in S_{\\mathrm{notmissing}}} |y_i - \\tilde y_i|^2,$$<\/div>\n<p>\nwhere <span class=\"math\">\\(S_{\\mathrm{notmissing}}\\)<\/span> is the set of indexes for which <span class=\"math\">\\(y_i\\)<\/span> is not\nmissing and <span class=\"math\">\\({\\tilde{\\mathbf{y}}}\\)<\/span> is the predicted value.<\/p>\n<p>From the perspective of a feedback system, any prediction the autoencoder makes\nis acceptable, or, in lay terms, \"your guess is as good as mine.\" Detailed\ndiscussion of this type of autoencoder can be found in <a href=\"https:\/\/arxiv.org\/abs\/2002.08338\">our\npaper<\/a>. <\/p>\n<p>Unfortunately, there are several practical problems. In our missing data\nproblem, the attributes <span class=\"math\">\\(\\{y_i\\}\\)<\/span> that are missing may change based on the\npresent sample so the loss function would be specific to which sample is being\nused to train the autoencoder. Most machine learning packages do not allow\nsample by sample customization of the loss function.<\/p>\n<p>As a practical consideration, rather than dismantling the structure of\nestablished machine learning libraries or contriving a complex loss function,\nit was much simpler to alter the so-called \"ground truth\" that is fed back into\nthe autoencoder during learning using a standard MSE loss function:<\/p>\n<div class=\"math\">$$\\sum_{i=1}^N |\\bar y_i - \\tilde y_i|^2,$$<\/div>\n<p>where <span class=\"math\">\\(N\\)<\/span> is the dimension of the output vector and <span class=\"math\">\\(\\bar y_i\\)<\/span> is given by the\nfollowing:<\/p>\n<div class=\"math\">$$\\bar y_i=\\begin{cases}\n  \\tilde y_i &amp; \\text{if $y_i$ is missing} \\\\\n  y_i &amp; \\text{otherwise}\n\\end{cases}$$<\/div>\n<p>This mapping cancels the dummy <span class=\"math\">\\(y_i\\)<\/span> values in the loss function, thus removing\nits effects.  This mapping is defined as a <em>truth metamorphism<\/em>.<\/p>\n<h3>Learning Implications<\/h3>\n<p>What started out as a \"hack\" for implementing a desired mathematical\ncalculation has much broader implications to learning. From one perspective,\nrigid ground truths can be thought of as another form of overtraining. In\npractice, there may be ambiguous labels and by enforcing a fixed ground truth for\neach output in training, you may be preventing the network from exploring \nother potential minima consistent with the label-ambiguity. <\/p>\n<p>For example, human learning with feedback tailored to an individual's current\nunderstanding usually works better. Learning from a books is like the rigid\nground truth model, whereas learning from a live teacher is like the\nmetamorphic truth model. When learning from the book, the \"truth\" doesn't\nchange no matter how many times you read it, though your understanding might\nimproved each time. When learning from a live teacher, one might get an\nindication that the answer is close enough to the answer the\nteacher originally wanted.  <\/p>\n<h2>Formalizing the Concept<\/h2>\n<p>Despite the variety of architectures, ANNs that implement the\nmultilayer perceptron have a common output layer that \ncomputes the following:<\/p>\n<div class=\"math\">$$\\tilde y_i = \\sum_{j=0}^{L_\\mathrm{output}} w_{i,j} x_{j},$$<\/div>\n<p>where <span class=\"math\">\\(w_{i,j}\\)<\/span> are the weights from the output layer, <span class=\"math\">\\(x_{j}\\)<\/span> are the outputs\nfrom the last hidden layer and <span class=\"math\">\\(L_\\mathrm{output}\\)<\/span> is the number of units in\nthe output layer.  For the mean square error, the loss function is defined as:<\/p>\n<div class=\"math\">$$E(\\mathbf{w}) = \\frac{1}{N}\\sum_{i} (y_i - \\tilde y_i)^2.$$<\/div>\n<p>Typical gradient descent algorithms start by calculating the derivative of the\nerror with respect to the weights and apply it first to the output layer and then \nthe the hidden layers via the chain-rule, <\/p>\n<div class=\"math\">$$\\frac{\\partial E}{\\partial w_{j,i}} =  \\frac{\\partial E}{\\partial \\tilde y_i} \\frac{\\partial \\tilde y_i}{\\partial w_{j,i}}.$$<\/div>\n<p>Using the MSE this becomes<\/p>\n<div class=\"math\">$$\\frac{\\partial E}{\\partial w_{j,i}} =  \\frac{2}{N}\\sum_{i} (y_i - \\tilde{y_i}) \\frac{\\partial \\tilde y_i}{\\partial w_{j,i}}.$$<\/div>\n<p>To train using metamorphic truth, we define a truth metamorphism:\n<span class=\"math\">\\(\\bar{\\mathbf{y}}=\\cal{M}(\\mathbf{y}, \\mathbf{\\tilde {y}})\\)<\/span> and we define the\nloss function of <span class=\"math\">\\(\\mathbf{\\bar y}\\)<\/span> as opposed to the ground truth\n<span class=\"math\">\\(\\mathbf{y}\\)<\/span>.  Treating the metamorphism as a function just gives a more\ncomplex loss function. What separates a metamorphism from simply another loss\nfunction is that we define the following,<\/p>\n<div class=\"math\">$$\\frac{\\partial \\cal{M}}{\\partial w_{j,i}}\\triangleq 0.$$<\/div>\n<p>where we have extrapolated <span class=\"math\">\\({\\partial \\bar{y_i}}\/{\\partial w_{j,i}} = 0\\)<\/span> from\n<span class=\"math\">\\({\\partial {y_i}}\/{\\partial w_{j,i}} = 0\\)<\/span>. In non-mathematical terms, the truth\nmetamorph is treated <em>exactly<\/em> like the ground truth. The result is that all the\nlearning algorithms can proceed unchanged once the truth metamorph is\nsubstituted for the ground truth.<\/p>\n<h3>Potential Mathematical Implications<\/h3>\n<p>No doubt a lot of question arises by this \"hacking\" of the mathematics. In\nessence, what has been done is the error surface for which a gradient descent\nalgorithm changes during the learning process making it possibly a moving\ntarget for the ANN model which may result in oscillations that make the minima\nharder to find.  Practically speaking, it is too early to tell if this is a\npotential problem. However, should it proved to be a problem, a lesson from\nfeedback systems can be applied. Whenever a system is in danger of instability,\na dampening agent of some sort is imposed. In fact, in modern stocastic\ngradient descent elements of dampening are introduced already (e.g.,\nbatch-learning, momentum).   Our one practical application of metamorphic truth\nfor data imputation does not suffer these issues.<\/p>\n<h2>Examples of Situations to Use Metamorphic Truth<\/h2>\n<p>The following are some examples of where metamorphic truth might be applicable.\nWe have not had detailed case study on any of these except the \"Don't Care\"\nexample which has been incorporated into an autoencoder for imputation as\nmentioned above.<\/p>\n<h3>Don't Care<\/h3>\n<p>In some models there are cases where the output is irrelevant.  For example,\ncertain states in logic design are ignored\n<a href=\"https:\/\/en.wikipedia.org\/wiki\/Don%27t-care_term\">(see here)<\/a>. The imputation\n<a href=\"https:\/\/arxiv.org\/abs\/2002.08338\">example<\/a> is \na situation where the predicted value from \na missing data element is irrelevant. <\/p>\n<p>As another example, consider a model that predicts medical conditions and\ngender. If the output is a gender-specific condition (such as pregnancy), one\nmight choose to ignore the corresponding gender output as a postprocessing step\nHence, in these cases you don't care what the prediction is and metamorphic\ntruth allows you to train a model in this way if desired.<\/p>\n<p>In this example, the metamorphism is similar to the one given above:<\/p>\n<div class=\"math\">$$\\cal{M}(\\mathbf{y}, \\mathbf{\\tilde y})_i=\\begin{cases}\n  \\tilde y_i &amp; \\text{if you don't care what $y_i$ is} \\\\\n  y_i &amp; \\text{otherwise}\n\\end{cases}$$<\/div>\n<h3>Multiple Answers<\/h3>\n<p>Consider the following digits from the MNIST database:<\/p>\n<p><img alt=\"\" src=\"images\/ml-02-metamorphic-truth-image.png\"><\/p>\n<p>These are three ambiguous numerals. Without disclosing the truth value in the\nMNIST database, one could probably make the case that the first number is a <code>2<\/code>\nor an incomplete <code>3<\/code>. The second number could be a <code>2<\/code> or a <code>7<\/code> and the third a\n<code>7<\/code> and a <code>9<\/code>.<\/p>\n<p>Suppose the middle number was labelled as a <code>7<\/code> one could make the case that\nthis was labelled incorrectly or the person labelling the samples was taught to\nwrite numbers a little differently so that what seems like it should be a <code>2<\/code>\nin your eyes could be a <code>7<\/code> in the labeller's eyes. Perhaps the entire dataset\nis labeled by multiple people. There could be a lack of\nconsistency in the way the numbers are labeled. Even if the person who labeled\nthe digit is the actual person who wrote it, it may very well be that the way\nthey wrote the number <code>7<\/code> is outside the norm of how the digit is drawn.<\/p>\n<p>For all of the above reasons, it is possible that these cases could adversely\nbias an ANN's learning. For this reason, one might want to say that both <code>2<\/code>\nand <code>3<\/code> are acceptable answers to the first classification and <code>2<\/code> and <code>7<\/code> are\nacceptible answers to the second classification etc.<\/p>\n<p>One can implement this kind of training by putting multiple values for each\n<span class=\"math\">\\(\\bf y\\)<\/span>. The metamorphism takes the predicted values and returns the closest\ncorrect answer to the prediction. <\/p>\n<h3>Confidence Labels<\/h3>\n<p>In some situations, there may be a small subset of impeccably labeled data and\na larger set of less reliable data that you want to incorporate into learning.\nYou could define a metamorphism<\/p>\n<div class=\"math\">$$\\cal{M}(\\mathbf{y}, \\mathbf{\\tilde y})_i= (1-\\alpha)\\tilde y_i + \\alpha y_i,$$<\/div>\n<p>\nwhere <span class=\"math\">\\(\\alpha\\)<\/span> is a confidence value in the truth for that particular sample and attribute. This metamorphism gives more or less weight to a truth value based on the confidence and inversely weights the contribution of the prediciton<\/p>\n<h2>Implementational Issues<\/h2>\n<p>While originally developed for a multiple imputation autoencoder using\n<code>tensorflow<\/code>, it is unclear how to implement metamorphic truth with other\npopular machine learning packages.  The following is a high level description\nof how to implement it in <code>tensorflow.<\/code> The <code>metamorphism<\/code> function takes the\npredicted output, the ground truth output, and a sample index as input.  The\nsample index is used to access metadata when necessary. For example in the\nimputation problem the attributes that are missing vary from sample to sample,\nso the index keeps track of which sample is transformed by the\nmetamorphism.<\/p>\n<p>The basic idea is to append the index of the training sample to the training\noutput to retain the order if the samples are scrambled.  This index is then\nstripped off in the loss function when the metamorphism \nis applied.<\/p>\n<p>When you <code>compile<\/code> a Tensorflow model, you  specify a customized loss function.\nThe loss function will first <code>split<\/code> the index from the truth value (recall we\nappended the index to it), leaving the truth value without the index. The truth\nvalue, predicted value and index are fed into the metamorphism. <\/p>\n<p>For <code>tensorflow<\/code> you must turn the output of the metamorphism into a constant\nwith respect to the model as <code>tensorflow<\/code> will build a computation graph and\ntry to compute the gradient of the metamorphism (which may have complicated\ndiscontinuities). To compensate for this, we construct a custom function\n<code>zero_derivative,<\/code> as follows<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"nd\">@tf<\/span><span class=\"o\">.<\/span><span class=\"n\">custom_gradient<\/span>\n<span class=\"k\">def<\/span> <span class=\"nf\">zero_derivative<\/span><span class=\"p\">(<\/span><span class=\"n\">x<\/span><span class=\"p\">):<\/span>\n    <span class=\"k\">def<\/span> <span class=\"nf\">grad<\/span><span class=\"p\">(<\/span><span class=\"n\">dy<\/span><span class=\"p\">):<\/span>\n    <span class=\"k\">return<\/span> <span class=\"n\">tf<\/span><span class=\"o\">.<\/span><span class=\"n\">zeros_like<\/span><span class=\"p\">(<\/span><span class=\"n\">dy<\/span><span class=\"p\">)<\/span>\n    <span class=\"k\">return<\/span> <span class=\"n\">x<\/span><span class=\"p\">,<\/span> <span class=\"n\">grad<\/span>\n<\/code><\/pre><\/div>\n\n<p>This 'function' is the identity function with a zero derivative. In effect, it\nturns the operand <code>x<\/code> into a constant.  Finally, when you run <code>fit<\/code> you supply\nas the training output, the original training output with the index appended to\neach sample.<\/p>\n<h2>Conclusion<\/h2>\n<p>Metamorphic truth expands the use cases for deep learning networks to\nsituations with ambiguous labeling or in situations with outputs that are\nirrelevant. Real applications for metamorphic truth are limited to date and the\ntheoretical and practical implementation study metamorphic truth is just\nbeginning. <\/p>\n<script type=\"text\/javascript\">if (!document.getElementById('mathjaxscript_pelican_#%@#$@#')) {\n    var align = \"center\",\n        indent = \"0em\",\n        linebreak = \"false\";\n\n    if (false) {\n        align = (screen.width < 768) ? \"left\" : align;\n        indent = (screen.width < 768) ? \"0em\" : indent;\n        linebreak = (screen.width < 768) ? 'true' : linebreak;\n    }\n\n    var mathjaxscript = document.createElement('script');\n    mathjaxscript.id = 'mathjaxscript_pelican_#%@#$@#';\n    mathjaxscript.type = 'text\/javascript';\n    mathjaxscript.src = 'https:\/\/cdnjs.cloudflare.com\/ajax\/libs\/mathjax\/2.7.3\/latest.js?config=TeX-AMS-MML_HTMLorMML';\n\n    var configscript = document.createElement('script');\n    configscript.type = 'text\/x-mathjax-config';\n    configscript[(window.opera ? \"innerHTML\" : \"text\")] =\n        \"MathJax.Hub.Config({\" +\n        \"    config: ['MMLorHTML.js'],\" +\n        \"    TeX: { extensions: ['AMSmath.js','AMSsymbols.js','noErrors.js','noUndefined.js'], equationNumbers: { autoNumber: 'none' } },\" +\n        \"    jax: ['input\/TeX','input\/MathML','output\/HTML-CSS'],\" +\n        \"    extensions: ['tex2jax.js','mml2jax.js','MathMenu.js','MathZoom.js'],\" +\n        \"    displayAlign: '\"+ align +\"',\" +\n        \"    displayIndent: '\"+ indent +\"',\" +\n        \"    showMathMenu: true,\" +\n        \"    messageStyle: 'normal',\" +\n        \"    tex2jax: { \" +\n        \"        inlineMath: [ ['\\\\\\\\(','\\\\\\\\)'] ], \" +\n        \"        displayMath: [ ['$$','$$'] ],\" +\n        \"        processEscapes: true,\" +\n        \"        preview: 'TeX',\" +\n        \"    }, \" +\n        \"    'HTML-CSS': { \" +\n        \"        availableFonts: ['STIX', 'TeX'],\" +\n        \"        preferredFont: 'STIX',\" +\n        \"        styles: { '.MathJax_Display, .MathJax .mo, .MathJax .mi, .MathJax .mn': {color: 'inherit ! important'} },\" +\n        \"        linebreaks: { automatic: \"+ linebreak +\", width: '90% container' },\" +\n        \"    }, \" +\n        \"}); \" +\n        \"if ('default' !== 'default') {\" +\n            \"MathJax.Hub.Register.StartupHook('HTML-CSS Jax Ready',function () {\" +\n                \"var VARIANT = MathJax.OutputJax['HTML-CSS'].FONTDATA.VARIANT;\" +\n                \"VARIANT['normal'].fonts.unshift('MathJax_default');\" +\n                \"VARIANT['bold'].fonts.unshift('MathJax_default-bold');\" +\n                \"VARIANT['italic'].fonts.unshift('MathJax_default-italic');\" +\n                \"VARIANT['-tex-mathit'].fonts.unshift('MathJax_default-italic');\" +\n            \"});\" +\n            \"MathJax.Hub.Register.StartupHook('SVG Jax Ready',function () {\" +\n                \"var VARIANT = MathJax.OutputJax.SVG.FONTDATA.VARIANT;\" +\n                \"VARIANT['normal'].fonts.unshift('MathJax_default');\" +\n                \"VARIANT['bold'].fonts.unshift('MathJax_default-bold');\" +\n                \"VARIANT['italic'].fonts.unshift('MathJax_default-italic');\" +\n                \"VARIANT['-tex-mathit'].fonts.unshift('MathJax_default-italic');\" +\n            \"});\" +\n        \"}\";\n\n    (document.body || document.getElementsByTagName('head')[0]).appendChild(configscript);\n    (document.body || document.getElementsByTagName('head')[0]).appendChild(mathjaxscript);\n}\n<\/script>","category":[{"@attributes":{"term":"Machine Learning"}},{"@attributes":{"term":"Machine Learning"}},{"@attributes":{"term":"Deep Learning"}}]},{"title":"Quasiorthonormal Encoding","link":{"@attributes":{"href":"https:\/\/WestHealth.github.io\/quasiorthonormal-encoding.html","rel":"alternate"}},"published":"2020-02-21T16:00:00-08:00","updated":"2020-02-21T16:00:00-08:00","author":{"name":"Haw-minn Lu"},"id":"tag:westhealth.github.io,2020-02-21:\/quasiorthonormal-encoding.html","summary":"<h2>Introduction<\/h2>\n<p>Quasiorthonormal encoding (QOE) is a generalization of the one-hot encoding and\nexploits the fact that in high dimensional vector spaces, two random vectors\nare almost always orthogonal. The concept originated with <a href=\"https:\/\/ieeexplore.ieee.org\/document\/549073\">K\u016frkov\u00e1 and\nKainen<\/a> almost 25 years ago. The\nprinciple is the same as one-hot encoding when you view \u2026<\/p>","content":"<h2>Introduction<\/h2>\n<p>Quasiorthonormal encoding (QOE) is a generalization of the one-hot encoding and\nexploits the fact that in high dimensional vector spaces, two random vectors\nare almost always orthogonal. The concept originated with <a href=\"https:\/\/ieeexplore.ieee.org\/document\/549073\">K\u016frkov\u00e1 and\nKainen<\/a> almost 25 years ago. The\nprinciple is the same as one-hot encoding when you view the encoded values as\nunit vectors as shown:<\/p>\n<table>\n<thead>\n<tr>\n<th>Make<\/th>\n<th align=\"center\">Ordinal<\/th>\n<th align=\"center\">One-Hot<\/th>\n<th align=\"center\">QOE<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>Toyota<\/td>\n<td align=\"center\">1<\/td>\n<td align=\"center\"><span class=\"math\">\\(\\mathbf{u}_1\\)<\/span><\/td>\n<td align=\"center\"><span class=\"math\">\\(\\mathbf{q}_1\\)<\/span><\/td>\n<\/tr>\n<tr>\n<td>Honda<\/td>\n<td align=\"center\">2<\/td>\n<td align=\"center\"><span class=\"math\">\\(\\mathbf{u}_2\\)<\/span><\/td>\n<td align=\"center\"><span class=\"math\">\\(\\mathbf{q}_2\\)<\/span><\/td>\n<\/tr>\n<tr>\n<td>Subaru<\/td>\n<td align=\"center\">3<\/td>\n<td align=\"center\"><span class=\"math\">\\(\\mathbf{u}_3\\)<\/span><\/td>\n<td align=\"center\"><span class=\"math\">\\(\\mathbf{q}_3\\)<\/span><\/td>\n<\/tr>\n<tr>\n<td>Nissan<\/td>\n<td align=\"center\">4<\/td>\n<td align=\"center\"><span class=\"math\">\\(\\mathbf{u}_4\\)<\/span><\/td>\n<td align=\"center\"><span class=\"math\">\\(\\mathbf{q}_4\\)<\/span><\/td>\n<\/tr>\n<tr>\n<td>Mitsubishi<\/td>\n<td align=\"center\">5<\/td>\n<td align=\"center\"><span class=\"math\">\\(\\mathbf{u}_5\\)<\/span><\/td>\n<td align=\"center\"><span class=\"math\">\\(\\mathbf{q}_5\\)<\/span><\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>where <span class=\"math\">\\(\\mathbf{u}_i\\)<\/span> are unit vectors in <span class=\"math\">\\(\\mathbb{R}^5\\)<\/span> and <span class=\"math\">\\({\\mathbf{q}_i}\\)<\/span>\nare a set of quasiorthogonal vectors in a dimension less than 5. The set\n<span class=\"math\">\\({\\mathbf{q}_i}\\)<\/span> is quasiorthonormal if each <span class=\"math\">\\(\\mathbf{q}_i\\)<\/span> is normal\n(<span class=\"math\">\\(||\\mathbf{q}_i||=1\\)<\/span>) and <span class=\"math\">\\(|\\mathbf{q}_i\\cdot \\mathbf{q}_j|&lt;\\epsilon\\)<\/span> for some\nsmall <span class=\"math\">\\(\\epsilon\\)<\/span> value and for <span class=\"math\">\\(i\\ne j\\)<\/span>. In otherwords, if <span class=\"math\">\\(i\\)<\/span> and <span class=\"math\">\\(j\\)<\/span> are\ndistinct <span class=\"math\">\\(\\mathbf{q}_i\\)<\/span> and <span class=\"math\">\\(\\mathbf{q}_j\\)<\/span> are almost perpendicular.<\/p>\n<p>By relaxing the condition that the encoded values be orthogonal many more codes\ncan be used in a smaller number of dimensions. A similar principle to this is\nused in areas such as Code Division Multiple Access (CDMA) that is used in\nmobile telephony.  In lay terms, if you allow for almost orthogonal vectors\nrather than strictly orthogonal, you can fit more vectors into the same\nvector space.<\/p>\n<p>Some advantages to QOE include a reduction of dimensionality over that of using\none-hot encoding thus limiting effects of the \"curse of dimensionality\" or the\nproblem of high dimension low sample size (HDLSS). The advantage over other\nencodings such as binary, hash, etc. is that it does not induce artificial\ngeometric relationships that can cause downlstream bias in the results because\neach label in a category remains mathematically orthogonal to the other\nlabels.<\/p>\n<p>While K\u016frkov\u00e1 and Kainen proposed this type of encoding almost 25 years ago,\nmachine learning has advanced since then so we include a short recap of the \nrelevant issues next.<\/p>\n<h4>One Hot Encoding Recap<\/h4>\n<p>In machine learning, the typical aspects of one hot encoding maps a variable\nwith <span class=\"math\">\\(n\\)<\/span> categories into a set of unit vectors in a <span class=\"math\">\\(n\\)<\/span>-dimensional space:\n<span class=\"math\">\\(L=\\{l_i\\}\\)<\/span> for <span class=\"math\">\\(i=1\\ldots n\\)<\/span>, then the one hot encoding <span class=\"math\">\\(\\mathbb{1}_L:L\n\\mapsto \\mathbb{R}^n\\)<\/span> given by <span class=\"math\">\\(l_i \\mapsto \\mathbf{u}_i\\)<\/span> where <span class=\"math\">\\(\\mathbf{u}_i\\)<\/span>\nis an orthonormal basis in <span class=\"math\">\\(\\mathbb{R}^n\\)<\/span>. The simplest basis used is\n<span class=\"math\">\\(\\mathbf{u}_i = (0,0,\\ldots, 1, 0,\\ldots, 0)\\)<\/span> where the <span class=\"math\">\\(1\\)<\/span> is in the <span class=\"math\">\\(i\\)<\/span>th\nposition which is know as the <em>standard basis<\/em> for <span class=\"math\">\\(\\mathbb{R}^n\\)<\/span>. <\/p>\n<p>Mapping of a vector back to the original category uses the <em>argmax<\/em> function,\nso for a vector <span class=\"math\">\\(\\mathbf{z}\\)<\/span>, <span class=\"math\">\\(\\mathrm{argmax}(\\mathbf{z}) = i\\)<\/span> where <span class=\"math\">\\(z_i&gt;z_j\\)<\/span>\nfor all <span class=\"math\">\\(j\\ne i\\)<\/span> and the vector <span class=\"math\">\\(\\mathbf{z}\\)<\/span> decodes to\n<span class=\"math\">\\(l_{\\mathrm{argmax}(\\mathbf{z})}\\)<\/span>. Of course, the argmax function is not\neasily differentiable which presents problems in ML learning algorithms that require\nderivatives. To fix this, a <em>softer<\/em> version is used called the <em>softargmax<\/em>\nor now as simply <em>softmax<\/em> and is defined as follows:<\/p>\n<div class=\"math\">$$\\mathrm{softmax}(\\mathbf{z})_i={e^{z_i}\\over \\sum_{j=1}^n e^{z_j}}$$<\/div>\n<p>for <span class=\"math\">\\(i=1,2,\\ldots,n\\)<\/span> and <span class=\"math\">\\({\\bf z}=(z_1, z_2,\\ldots, z_n) \\in \\mathbb{R}^n\\)<\/span>\nwhere <span class=\"math\">\\(\\mathbf{z}\\)<\/span> is the vector being decoded.  The softmax function decodes a\none-hot encoded vector into a probability density function which enables\napplication of negative log likelihood loss functions or cross entropy losses.<\/p>\n<p>We can generalize the one-hot encoding formulation to use an arbitrary\northonormal basis <span class=\"math\">\\({\\mathbf{u}_i}\\)<\/span>. To decode a one-hot encoded value in this\nframework, we would take <span class=\"math\">\\(i =\n\\mathrm{argmax}(\\mathbf{z}\\cdot\\mathbf{u}_1,\\mathbf{z}\\cdot\\mathbf{u}_2,\\ldots,\\mathbf{z}\\cdot\\mathbf{u}_n)\\)<\/span>.\nThis reduces to <span class=\"math\">\\(\\mathrm{argmax}(\\mathbf{z})\\)<\/span> for the standard basis.\nThus, the softmax function can be expressed as  the following,<\/p>\n<div class=\"math\">$$\\mathrm{softmax}({\\bf z})_i={e^{{\\bf z}\\cdot {\\bf u}_i}\\over \\sum_{j=1}^n e^{{\\bf z}\\cdot {\\bf u}_j}}.$$<\/div>\n<h2>Quasiorthogonality<\/h2>\n<p>Given an <span class=\"math\">\\(\\epsilon\\)<\/span> two vectors <span class=\"math\">\\({\\bf x}\\)<\/span> and <span class=\"math\">\\({\\bf y}\\)<\/span>\nare said to be <em>quasiorthogonal<\/em> if <span class=\"math\">\\({|{\\bf x}\\cdot {\\bf y}|\\over \\|{\\bf x}\\|\n\\|{\\bf y}\\|}&lt;\\epsilon\\)<\/span>. This extends the orthogonality principle by\nallowing the inner product to not exactly equal zero.\nAs an extension, we can define a quasiorthonormal <em>basis<\/em> by a set of normal\nvectors <span class=\"math\">\\(\\{{\\bf q}_i\\}\\)<\/span> for <span class=\"math\">\\(i=1,\\ldots,K\\)<\/span> such that <span class=\"math\">\\(|{\\bf q}_i\\cdot {\\bf\nq}_j|&lt; \\epsilon $ and $||{\\bf q}_i||=1\\)<\/span>, for all  <span class=\"math\">\\(i,j\\in\\{1,\\ldots,K\\}\\)<\/span>, where\nin principle for large enough <span class=\"math\">\\(n\\)<\/span>, <span class=\"math\">\\(K\\gg n\\)<\/span>.\n<a href=\"https:\/\/www.cs.cas.cz\/~vera\/publications\/books\/C1.pdf\">Kainen and K\u016frkov\u00e1<\/a> derived a lower bound for <span class=\"math\">\\(K\\)<\/span> as a function of <span class=\"math\">\\(\\epsilon\\)<\/span> and <span class=\"math\">\\(n\\)<\/span>. Namely, <\/p>\n<div class=\"math\">$$K \\ge e^{n\\epsilon^2}.$$<\/div>\n<h2>Quasiorthonormal Encoding<\/h2>\n<p>Briefly, quasiorthonormal encoding simply substitutes a quasiorthonormal basis\n<span class=\"math\">\\(\\{{\\bf q}_i\\}\\)<\/span> for the orthonormal basis <span class=\"math\">\\(\\{{\\bf u}_i\\}\\)<\/span> used above. So more\nformally, given a quasiorthonormal basis, we can define a QOE for a set\n<span class=\"math\">\\(L=\\{l_i\\}\\)<\/span> by <span class=\"math\">\\({\\mathbb q}(l_i)= {\\bf q}_i\\)<\/span>. Decoding under QOE would use the\nfollowing formula for decoding <span class=\"math\">\\(\\mathbf{z}\\)<\/span>: <\/p>\n<div class=\"math\">$$i =\n\\mathrm{argmax}(\\mathbf{z}\\cdot\\mathbf{q}_1,\\mathbf{z}\\cdot\\mathbf{q}_2,\\ldots,\\mathbf{z}\\cdot\\mathbf{q}_n)$$<\/div>\n<p>The analogous softmax function, let's call it <em>qsoftmax<\/em>, would be expressed as\n<\/p>\n<div class=\"math\">$$\\mathrm{qsoftmax}({\\bf z})_i={e^{{\\bf z}\\cdot {\\bf q}_i}\\over \\sum_{j=1}^K\ne^{{\\bf z}\\cdot {\\bf q}_j}}$$<\/div>\n<p>The only real difference in the formulation is that while still operating in\n<span class=\"math\">\\({\\mathbb R}^n\\)<\/span> we are encoding <span class=\"math\">\\(K&gt;n\\)<\/span> labels.<\/p>\n<h4>Implementation<\/h4>\n<p>To facilitate modern vectorized computation packages such as <code>numpy<\/code> and\n<code>tensorflow<\/code>, we define the following <span class=\"math\">\\(n\\times K\\)<\/span> <em>change of coordinates<\/em> matrix <\/p>\n<div class=\"math\">$$\\mathbf{Q}=  \\left[\\begin{matrix} \n\\bigg| &amp; \\bigg| &amp; &amp;\\bigg | \\\\ \n\\mathbf{q}_1 &amp; \\mathbf{q}_2 &amp; \\cdots &amp; \\mathbf{q}_K \\\\\n\\bigg| &amp; \\bigg| &amp; &amp;\\bigg | \\end{matrix}\\right].$$<\/div>\n<p>that transforms between the QOE space and the one hot encoding space. So given\na argmax or softmax function, we can express the quasiorthonormal variant as\nfollows <\/p>\n<div class=\"math\">$$\\mathrm{qargmax}(\\mathbf{z}) = \\mathrm{argmax}(\\mathbf{Qz})$$<\/div>\n<p> and\n<\/p>\n<div class=\"math\">$$\\mathrm{qsoftmax}(\\mathbf{z}) = \\mathrm{softmax}(\\mathbf{Qz}).$$<\/div>\n<p>This facilitates the use of optimized functions such as <code>softmax<\/code> in libraries\nlike <code>tensorflow<\/code> and using the above matrix enables quick implementation of\nQOE into these packages.  In the examples below, we use <code>tensorflow<\/code> to test\nthe effectiveness of using QOE over one-hot encoding. <\/p>\n<h2>Construction of an Quasiorthonormal set<\/h2>\n<p>It is difficult find explicit constructions of quasiorthonormal sets in the\nliterature. Several methods are mentioned by\n<a href=\"https:\/\/www.researchgate.net\/publication\/303520147\">Kainen<\/a>, but these\nconstructions are somewhat theoretical and hard for the lay person to follow.\nThere are a number of combinatorial problems related such as spherical codes\nand Steiner Triple Systems, which strive to find optimal solutions. As a\npractical matter, we only need to find fast suboptimal solutions so we can use\n<a href=\"http:\/\/neilsloane.com\/packings\/index.html\">spherical codes<\/a>.  Spherical codes\ntry to find a set of points on the <span class=\"math\">\\(n\\)<\/span>-dimensional hypersphere such that the\nminimum distance between two points is maximized. In most constructions of\nspherical codes, a given point's antipodal point is also in that code set.\nSo in order to get a quasiorthogonal set, for each pair of antipodal points,\nonly one element of the pair is selected.<\/p>\n<h2>Experiment and Demonstration<\/h2>\n<p>As an initial experiment, we applied QOE to classification of the MNIST\nhandwriting dataset, using the 60000 training examples with 10000 test\nexamples. As there are 10 categories, we needed sets of\nquasiorthonormal bases with 10 elements. We took the spherical code for 24\npoints in 4-dimensions, giving us 12 quasi-orthogonal vectors. The maximum\npairwise dot product was 0.5 leading to an angle of 60<span class=\"math\">\\(^\\circ\\)<\/span>. We also took the\nspherical code for 56 points in 7-dimensions, giving 28 quasi-orthogonal\nvectors. The maximum pairwise dot product was .33 leading to an angle of a\nlittle over 70<span class=\"math\">\\(^\\circ\\)<\/span><\/p>\n<p>We used a hidden layer with 64 units with a ReLU activation function. Next\nthere is a 20% dropout layer to mitigate overtraining, then an output layer\nwhose width depends on the encoding used.<\/p>\n<p>As a preliminary, we define a <code>qsoftmax<\/code> metafunction:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">def<\/span> <span class=\"nf\">qsoftmax<\/span><span class=\"p\">(<\/span><span class=\"n\">basis<\/span><span class=\"p\">):<\/span>\n    <span class=\"k\">def<\/span> <span class=\"nf\">func<\/span><span class=\"p\">(<\/span><span class=\"n\">x<\/span><span class=\"p\">):<\/span>\n        <span class=\"n\">qx<\/span> <span class=\"o\">=<\/span> <span class=\"n\">tf<\/span><span class=\"o\">.<\/span><span class=\"n\">matmul<\/span><span class=\"p\">(<\/span><span class=\"n\">tf<\/span><span class=\"o\">.<\/span><span class=\"n\">constant<\/span><span class=\"p\">(<\/span><span class=\"n\">basis<\/span><span class=\"p\">),<\/span><span class=\"n\">x<\/span><span class=\"p\">,<\/span><span class=\"n\">transpose_b<\/span><span class=\"o\">=<\/span><span class=\"kc\">True<\/span><span class=\"p\">)<\/span>        \n        <span class=\"k\">return<\/span> <span class=\"n\">tf<\/span><span class=\"o\">.<\/span><span class=\"n\">nn<\/span><span class=\"o\">.<\/span><span class=\"n\">softmax<\/span><span class=\"p\">(<\/span><span class=\"n\">tf<\/span><span class=\"o\">.<\/span><span class=\"n\">transpose<\/span><span class=\"p\">(<\/span><span class=\"n\">qx<\/span><span class=\"p\">))<\/span>\n    <span class=\"k\">return<\/span> <span class=\"n\">func<\/span>\n<\/code><\/pre><\/div>\n\n<p>which takes a quasiorthogonal basis and returns the quasiorthogonal softmax\nfunction based on the basis. The various transpose operations are necessary to\nconform the inputs and outputs to the shape provided and required by the\ntensorflow model.<\/p>\n<p>For <code>tensorflow<\/code> and <code>keras<\/code>, the base network is the following,<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">normal_model<\/span> <span class=\"o\">=<\/span> <span class=\"n\">tf<\/span><span class=\"o\">.<\/span><span class=\"n\">keras<\/span><span class=\"o\">.<\/span><span class=\"n\">models<\/span><span class=\"o\">.<\/span><span class=\"n\">Sequential<\/span><span class=\"p\">([<\/span>\n  <span class=\"n\">tf<\/span><span class=\"o\">.<\/span><span class=\"n\">keras<\/span><span class=\"o\">.<\/span><span class=\"n\">layers<\/span><span class=\"o\">.<\/span><span class=\"n\">Flatten<\/span><span class=\"p\">(<\/span><span class=\"n\">input_shape<\/span><span class=\"o\">=<\/span><span class=\"p\">(<\/span><span class=\"mi\">28<\/span><span class=\"p\">,<\/span> <span class=\"mi\">28<\/span><span class=\"p\">)),<\/span>\n  <span class=\"n\">tf<\/span><span class=\"o\">.<\/span><span class=\"n\">keras<\/span><span class=\"o\">.<\/span><span class=\"n\">layers<\/span><span class=\"o\">.<\/span><span class=\"n\">Dense<\/span><span class=\"p\">(<\/span><span class=\"mi\">64<\/span><span class=\"p\">,<\/span> <span class=\"n\">activation<\/span><span class=\"o\">=<\/span><span class=\"n\">tf<\/span><span class=\"o\">.<\/span><span class=\"n\">nn<\/span><span class=\"o\">.<\/span><span class=\"n\">relu<\/span><span class=\"p\">),<\/span>\n  <span class=\"n\">tf<\/span><span class=\"o\">.<\/span><span class=\"n\">keras<\/span><span class=\"o\">.<\/span><span class=\"n\">layers<\/span><span class=\"o\">.<\/span><span class=\"n\">Dropout<\/span><span class=\"p\">(<\/span><span class=\"mf\">0.2<\/span><span class=\"p\">),<\/span>\n  <span class=\"n\">tf<\/span><span class=\"o\">.<\/span><span class=\"n\">keras<\/span><span class=\"o\">.<\/span><span class=\"n\">layers<\/span><span class=\"o\">.<\/span><span class=\"n\">Dense<\/span><span class=\"p\">(<\/span><span class=\"mi\">10<\/span><span class=\"p\">)<\/span>\n  <span class=\"n\">tf<\/span><span class=\"o\">.<\/span><span class=\"n\">keras<\/span><span class=\"o\">.<\/span><span class=\"n\">layers<\/span><span class=\"o\">.<\/span><span class=\"n\">Activation<\/span><span class=\"p\">(<\/span><span class=\"n\">tf<\/span><span class=\"o\">.<\/span><span class=\"n\">nn<\/span><span class=\"o\">.<\/span><span class=\"n\">softmax<\/span><span class=\"p\">)<\/span>\n<span class=\"p\">])<\/span>\n<\/code><\/pre><\/div>\n\n<p>We used a separate <code>Activation<\/code> layer to make the\n<code>qsoftmax<\/code> clearer.<\/p>\n<p>As a sanity test, you can implement the following:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">sanity_model<\/span> <span class=\"o\">=<\/span> <span class=\"n\">tf<\/span><span class=\"o\">.<\/span><span class=\"n\">keras<\/span><span class=\"o\">.<\/span><span class=\"n\">models<\/span><span class=\"o\">.<\/span><span class=\"n\">Sequential<\/span><span class=\"p\">([<\/span>\n  <span class=\"n\">tf<\/span><span class=\"o\">.<\/span><span class=\"n\">keras<\/span><span class=\"o\">.<\/span><span class=\"n\">layers<\/span><span class=\"o\">.<\/span><span class=\"n\">Flatten<\/span><span class=\"p\">(<\/span><span class=\"n\">input_shape<\/span><span class=\"o\">=<\/span><span class=\"p\">(<\/span><span class=\"mi\">28<\/span><span class=\"p\">,<\/span> <span class=\"mi\">28<\/span><span class=\"p\">)),<\/span>\n  <span class=\"n\">tf<\/span><span class=\"o\">.<\/span><span class=\"n\">keras<\/span><span class=\"o\">.<\/span><span class=\"n\">layers<\/span><span class=\"o\">.<\/span><span class=\"n\">Dense<\/span><span class=\"p\">(<\/span><span class=\"mi\">64<\/span><span class=\"p\">,<\/span> <span class=\"n\">activation<\/span><span class=\"o\">=<\/span><span class=\"n\">tf<\/span><span class=\"o\">.<\/span><span class=\"n\">nn<\/span><span class=\"o\">.<\/span><span class=\"n\">relu<\/span><span class=\"p\">),<\/span>\n  <span class=\"n\">tf<\/span><span class=\"o\">.<\/span><span class=\"n\">keras<\/span><span class=\"o\">.<\/span><span class=\"n\">layers<\/span><span class=\"o\">.<\/span><span class=\"n\">Dropout<\/span><span class=\"p\">(<\/span><span class=\"mf\">0.2<\/span><span class=\"p\">),<\/span>\n  <span class=\"n\">tf<\/span><span class=\"o\">.<\/span><span class=\"n\">keras<\/span><span class=\"o\">.<\/span><span class=\"n\">layers<\/span><span class=\"o\">.<\/span><span class=\"n\">Dense<\/span><span class=\"p\">(<\/span><span class=\"mi\">10<\/span><span class=\"p\">)<\/span>\n  <span class=\"n\">tf<\/span><span class=\"o\">.<\/span><span class=\"n\">keras<\/span><span class=\"o\">.<\/span><span class=\"n\">layers<\/span><span class=\"o\">.<\/span><span class=\"n\">Lambda<\/span><span class=\"p\">(<\/span><span class=\"n\">qsoftmax<\/span><span class=\"p\">(<\/span><span class=\"n\">numpy<\/span><span class=\"o\">.<\/span><span class=\"n\">identity<\/span><span class=\"p\">(<\/span><span class=\"mi\">10<\/span><span class=\"p\">,<\/span><span class=\"n\">dtype<\/span><span class=\"o\">=<\/span><span class=\"n\">numpy<\/span><span class=\"o\">.<\/span><span class=\"n\">float32<\/span><span class=\"p\">)))<\/span>\n<span class=\"p\">])<\/span>\n<\/code><\/pre><\/div>\n\n<p>This should function identically as the reference model because it tests that\nthe qsoftmax function operates as expected (which it does for us) since\napplying the identity matrix to <code>qsoftmax<\/code> merely converts it to the standard\n<code>softmax<\/code> function. This is useful for troubleshooting if you have difficulty.<\/p>\n<p>For the two QOE experiments we labeled the bases for the two quasiorthonormal\nsets <code>base4<\/code> and <code>base7<\/code> and only took the first 10 vectors.\nWe used the following additional test models<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">basis4_model<\/span> <span class=\"o\">=<\/span> <span class=\"n\">tf<\/span><span class=\"o\">.<\/span><span class=\"n\">keras<\/span><span class=\"o\">.<\/span><span class=\"n\">models<\/span><span class=\"o\">.<\/span><span class=\"n\">Sequential<\/span><span class=\"p\">([<\/span>\n  <span class=\"n\">tf<\/span><span class=\"o\">.<\/span><span class=\"n\">keras<\/span><span class=\"o\">.<\/span><span class=\"n\">layers<\/span><span class=\"o\">.<\/span><span class=\"n\">Flatten<\/span><span class=\"p\">(<\/span><span class=\"n\">input_shape<\/span><span class=\"o\">=<\/span><span class=\"p\">(<\/span><span class=\"mi\">28<\/span><span class=\"p\">,<\/span> <span class=\"mi\">28<\/span><span class=\"p\">)),<\/span>\n  <span class=\"n\">tf<\/span><span class=\"o\">.<\/span><span class=\"n\">keras<\/span><span class=\"o\">.<\/span><span class=\"n\">layers<\/span><span class=\"o\">.<\/span><span class=\"n\">Dense<\/span><span class=\"p\">(<\/span><span class=\"mi\">64<\/span><span class=\"p\">,<\/span> <span class=\"n\">activation<\/span><span class=\"o\">=<\/span><span class=\"n\">tf<\/span><span class=\"o\">.<\/span><span class=\"n\">nn<\/span><span class=\"o\">.<\/span><span class=\"n\">relu<\/span><span class=\"p\">),<\/span>\n  <span class=\"n\">tf<\/span><span class=\"o\">.<\/span><span class=\"n\">keras<\/span><span class=\"o\">.<\/span><span class=\"n\">layers<\/span><span class=\"o\">.<\/span><span class=\"n\">Dropout<\/span><span class=\"p\">(<\/span><span class=\"mf\">0.2<\/span><span class=\"p\">),<\/span>\n  <span class=\"n\">tf<\/span><span class=\"o\">.<\/span><span class=\"n\">keras<\/span><span class=\"o\">.<\/span><span class=\"n\">layers<\/span><span class=\"o\">.<\/span><span class=\"n\">Dense<\/span><span class=\"p\">(<\/span><span class=\"mi\">4<\/span><span class=\"p\">),<\/span>\n  <span class=\"n\">tf<\/span><span class=\"o\">.<\/span><span class=\"n\">keras<\/span><span class=\"o\">.<\/span><span class=\"n\">layers<\/span><span class=\"o\">.<\/span><span class=\"n\">Lambda<\/span><span class=\"p\">(<\/span><span class=\"n\">qsoftmax<\/span><span class=\"p\">(<\/span><span class=\"n\">basis4<\/span><span class=\"p\">))<\/span>\n<span class=\"p\">])<\/span>\n<span class=\"n\">basis7_model<\/span> <span class=\"o\">=<\/span> <span class=\"n\">tf<\/span><span class=\"o\">.<\/span><span class=\"n\">keras<\/span><span class=\"o\">.<\/span><span class=\"n\">models<\/span><span class=\"o\">.<\/span><span class=\"n\">Sequential<\/span><span class=\"p\">([<\/span>\n  <span class=\"n\">tf<\/span><span class=\"o\">.<\/span><span class=\"n\">keras<\/span><span class=\"o\">.<\/span><span class=\"n\">layers<\/span><span class=\"o\">.<\/span><span class=\"n\">Flatten<\/span><span class=\"p\">(<\/span><span class=\"n\">input_shape<\/span><span class=\"o\">=<\/span><span class=\"p\">(<\/span><span class=\"mi\">28<\/span><span class=\"p\">,<\/span> <span class=\"mi\">28<\/span><span class=\"p\">)),<\/span>\n  <span class=\"n\">tf<\/span><span class=\"o\">.<\/span><span class=\"n\">keras<\/span><span class=\"o\">.<\/span><span class=\"n\">layers<\/span><span class=\"o\">.<\/span><span class=\"n\">Dense<\/span><span class=\"p\">(<\/span><span class=\"mi\">64<\/span><span class=\"p\">,<\/span> <span class=\"n\">activation<\/span><span class=\"o\">=<\/span><span class=\"n\">tf<\/span><span class=\"o\">.<\/span><span class=\"n\">nn<\/span><span class=\"o\">.<\/span><span class=\"n\">relu<\/span><span class=\"p\">),<\/span>\n  <span class=\"n\">tf<\/span><span class=\"o\">.<\/span><span class=\"n\">keras<\/span><span class=\"o\">.<\/span><span class=\"n\">layers<\/span><span class=\"o\">.<\/span><span class=\"n\">Dropout<\/span><span class=\"p\">(<\/span><span class=\"mf\">0.2<\/span><span class=\"p\">),<\/span>\n  <span class=\"n\">tf<\/span><span class=\"o\">.<\/span><span class=\"n\">keras<\/span><span class=\"o\">.<\/span><span class=\"n\">layers<\/span><span class=\"o\">.<\/span><span class=\"n\">Dense<\/span><span class=\"p\">(<\/span><span class=\"mi\">7<\/span><span class=\"p\">),<\/span>\n  <span class=\"n\">tf<\/span><span class=\"o\">.<\/span><span class=\"n\">keras<\/span><span class=\"o\">.<\/span><span class=\"n\">layers<\/span><span class=\"o\">.<\/span><span class=\"n\">Lambda<\/span><span class=\"p\">(<\/span><span class=\"n\">qsoftmax<\/span><span class=\"p\">(<\/span><span class=\"n\">basis7<\/span><span class=\"p\">))<\/span>\n<span class=\"p\">])<\/span>\n<\/code><\/pre><\/div>\n\n<p>The following table is the mean of the accuracy over three training runs of the\nvalidation data with training data in parentheses<\/p>\n<table>\n<thead>\n<tr>\n<th align=\"center\">Number of Epochs<\/th>\n<th align=\"center\">One Hot Encoding<\/th>\n<th align=\"center\">7-Dimensional QO<\/th>\n<th align=\"center\">4-Dimensional QO<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td align=\"center\">10<\/td>\n<td align=\"center\">97.53% (97.30%)<\/td>\n<td align=\"center\">97.24% (96.94%)<\/td>\n<td align=\"center\">95.65% (95.15%)<\/td>\n<\/tr>\n<tr>\n<td align=\"center\">20<\/td>\n<td align=\"center\">97.68% (98.02%)<\/td>\n<td align=\"center\">97.49% (97.75%)<\/td>\n<td align=\"center\">95.94% (96.15%)<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>The seven dimensional quasiorthogonal basis (at 70<span class=\"math\">\\(^\\circ\\)<\/span>), performs nearly as\nwell as the one-hot encoded version whereas the four dimensional quasiorthogonal\nbasis (at 60<span class=\"math\">\\(^\\circ\\)<\/span>) case did not perform as well. Though 95\\% vs 98\\%\npercent may not seem significant, for the MNIST handwriting dataset, this \nrelatively small change in performance is how these \nclassification algorithms are judged.<\/p>\n<h2>Spherical Encoding<\/h2>\n<p>One key to the effectiveness of an encoding method is how well categorical\nvalues can be decoded in an noisy environment. Orthogonality provides excellent\ndecodability especially using the softmax function, but this comes at the cost\nof the number of dimensions used for the encoding. Quasiorthoganility with the\nQO softmax function performs less effectively at decoding than orthogonality\nwith the softmax, but reduces dimensionality.<\/p>\n<p>A curious observation is that if you examine the effect of the softmax function\non negative values along one of the basis vectors, the softmax function\nseverely attenuates it. Therefore, one can construct an orthogonal code using\nboth the 1 and -1 values so for standard unit vectors, you could encode\ncategorical values to <span class=\"math\">\\(\\{\\mathbf{u}_i, -\\mathbf{u}_i,\\}\\)<\/span>, reducing the\ndimensionality by half. Of course nothing comes for free, if a prediction gets\nconfused between two antipodal unit vectors, the result could be that they\ncancel out and allow the noise to dictate the resulting category. By contrast,\nfor one-hot encoding, the result would get decoded \nas one of the two possible values.<\/p>\n<p>With this risk in mind, we can further extend the idea to a quasiorthogonal\nbasis by adding the antipodal vectors for each vector in the basis. The result\nnot only doubles the number of vectors that can be used for encoding, it\nreduces the problem of finding a basis to that of finding spherical codes.<\/p>\n<p>Finally, we tested how effective this types of coding is by using an orthogonal\nbasis in 5 dimensions and adding the antipodal unit vector to produce a set of\n10 vectors. <\/p>\n<p>The model tested becomes:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">basis5_model<\/span> <span class=\"o\">=<\/span> <span class=\"n\">tf<\/span><span class=\"o\">.<\/span><span class=\"n\">keras<\/span><span class=\"o\">.<\/span><span class=\"n\">models<\/span><span class=\"o\">.<\/span><span class=\"n\">Sequential<\/span><span class=\"p\">([<\/span>\n  <span class=\"n\">tf<\/span><span class=\"o\">.<\/span><span class=\"n\">keras<\/span><span class=\"o\">.<\/span><span class=\"n\">layers<\/span><span class=\"o\">.<\/span><span class=\"n\">Flatten<\/span><span class=\"p\">(<\/span><span class=\"n\">input_shape<\/span><span class=\"o\">=<\/span><span class=\"p\">(<\/span><span class=\"mi\">28<\/span><span class=\"p\">,<\/span> <span class=\"mi\">28<\/span><span class=\"p\">)),<\/span>\n  <span class=\"n\">tf<\/span><span class=\"o\">.<\/span><span class=\"n\">keras<\/span><span class=\"o\">.<\/span><span class=\"n\">layers<\/span><span class=\"o\">.<\/span><span class=\"n\">Dense<\/span><span class=\"p\">(<\/span><span class=\"mi\">64<\/span><span class=\"p\">,<\/span> <span class=\"n\">activation<\/span><span class=\"o\">=<\/span><span class=\"n\">tf<\/span><span class=\"o\">.<\/span><span class=\"n\">nn<\/span><span class=\"o\">.<\/span><span class=\"n\">relu<\/span><span class=\"p\">),<\/span>\n  <span class=\"n\">tf<\/span><span class=\"o\">.<\/span><span class=\"n\">keras<\/span><span class=\"o\">.<\/span><span class=\"n\">layers<\/span><span class=\"o\">.<\/span><span class=\"n\">Dropout<\/span><span class=\"p\">(<\/span><span class=\"mf\">0.2<\/span><span class=\"p\">),<\/span>\n  <span class=\"n\">tf<\/span><span class=\"o\">.<\/span><span class=\"n\">keras<\/span><span class=\"o\">.<\/span><span class=\"n\">layers<\/span><span class=\"o\">.<\/span><span class=\"n\">Dense<\/span><span class=\"p\">(<\/span><span class=\"mi\">5<\/span><span class=\"p\">),<\/span>\n  <span class=\"n\">tf<\/span><span class=\"o\">.<\/span><span class=\"n\">keras<\/span><span class=\"o\">.<\/span><span class=\"n\">layers<\/span><span class=\"o\">.<\/span><span class=\"n\">Lambda<\/span><span class=\"p\">(<\/span><span class=\"n\">qsoftmax<\/span><span class=\"p\">(<\/span><span class=\"n\">basis5<\/span><span class=\"p\">))<\/span>\n<span class=\"p\">])<\/span>\n<\/code><\/pre><\/div>\n\n<p>In addition, we ran a test using the 3 dimension 10 vector spherical code\nprovided <a href=\"http:\/\/neilsloane.com\/packings\/index.html\">here<\/a>. The accuracy is\nshown in the following table with training accuracy in parentheses.<\/p>\n<table>\n<thead>\n<tr>\n<th align=\"center\">Number of Epochs<\/th>\n<th align=\"center\">One Hot Encoding<\/th>\n<th align=\"center\">5-Dimensional SC<\/th>\n<th align=\"center\">3-Dimensional SC<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td align=\"center\">10<\/td>\n<td align=\"center\">97.53% (97.30%)<\/td>\n<td align=\"center\">96.51% (96.26%)<\/td>\n<td align=\"center\">95.37% (94.83%)<\/td>\n<\/tr>\n<tr>\n<td align=\"center\">20<\/td>\n<td align=\"center\">97.68% (98.02%)<\/td>\n<td align=\"center\">96.82% (97.11%)<\/td>\n<td align=\"center\">95.74% (95.83%)<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>In this case, the 5-dimensional spherical codes performed close to the one-hot\nencoding by not as closely as the 7-dimension QO codes. The 3-dimensional\nspherical codes performed on par with the 4-dimensional QO codes.<\/p>\n<h3>Conclusion<\/h3>\n<p>While the extreme dimensionality reduction from 10 to 4 or 10 to 3 did not\nyield comparable performance to one-hot encoding. More modest reductions such\nas 10 to 7 and 10 to 5 did. It is worth considering that quasiorthogonal or\nspherical codes are much harder to find in low dimensions. One should note\nthat, though we went from 10 to 7 dimensions, we did not fully exploit the space\nspanned by the quasiorthogonal vector set. Otherwise, we would likely have had the similar\nresults if the categorical labels had a cardinality of 28 rather than 10.\nFurthermore, as the target encoded space approaches 20 or 30 dimensions, we\nhave the ability to encode 100,000 or even a million labels.  So for high\ncardinality categories, QO encoding and spherical encoding provide an efficient\ncategorical encoding while controlling the curse of dimensionality.<\/p>\n<script type=\"text\/javascript\">if (!document.getElementById('mathjaxscript_pelican_#%@#$@#')) {\n    var align = \"center\",\n        indent = \"0em\",\n        linebreak = \"false\";\n\n    if (false) {\n        align = (screen.width < 768) ? \"left\" : align;\n        indent = (screen.width < 768) ? \"0em\" : indent;\n        linebreak = (screen.width < 768) ? 'true' : linebreak;\n    }\n\n    var mathjaxscript = document.createElement('script');\n    mathjaxscript.id = 'mathjaxscript_pelican_#%@#$@#';\n    mathjaxscript.type = 'text\/javascript';\n    mathjaxscript.src = 'https:\/\/cdnjs.cloudflare.com\/ajax\/libs\/mathjax\/2.7.3\/latest.js?config=TeX-AMS-MML_HTMLorMML';\n\n    var configscript = document.createElement('script');\n    configscript.type = 'text\/x-mathjax-config';\n    configscript[(window.opera ? \"innerHTML\" : \"text\")] =\n        \"MathJax.Hub.Config({\" +\n        \"    config: ['MMLorHTML.js'],\" +\n        \"    TeX: { extensions: ['AMSmath.js','AMSsymbols.js','noErrors.js','noUndefined.js'], equationNumbers: { autoNumber: 'none' } },\" +\n        \"    jax: ['input\/TeX','input\/MathML','output\/HTML-CSS'],\" +\n        \"    extensions: ['tex2jax.js','mml2jax.js','MathMenu.js','MathZoom.js'],\" +\n        \"    displayAlign: '\"+ align +\"',\" +\n        \"    displayIndent: '\"+ indent +\"',\" +\n        \"    showMathMenu: true,\" +\n        \"    messageStyle: 'normal',\" +\n        \"    tex2jax: { \" +\n        \"        inlineMath: [ ['\\\\\\\\(','\\\\\\\\)'] ], \" +\n        \"        displayMath: [ ['$$','$$'] ],\" +\n        \"        processEscapes: true,\" +\n        \"        preview: 'TeX',\" +\n        \"    }, \" +\n        \"    'HTML-CSS': { \" +\n        \"        availableFonts: ['STIX', 'TeX'],\" +\n        \"        preferredFont: 'STIX',\" +\n        \"        styles: { '.MathJax_Display, .MathJax .mo, .MathJax .mi, .MathJax .mn': {color: 'inherit ! important'} },\" +\n        \"        linebreaks: { automatic: \"+ linebreak +\", width: '90% container' },\" +\n        \"    }, \" +\n        \"}); \" +\n        \"if ('default' !== 'default') {\" +\n            \"MathJax.Hub.Register.StartupHook('HTML-CSS Jax Ready',function () {\" +\n                \"var VARIANT = MathJax.OutputJax['HTML-CSS'].FONTDATA.VARIANT;\" +\n                \"VARIANT['normal'].fonts.unshift('MathJax_default');\" +\n                \"VARIANT['bold'].fonts.unshift('MathJax_default-bold');\" +\n                \"VARIANT['italic'].fonts.unshift('MathJax_default-italic');\" +\n                \"VARIANT['-tex-mathit'].fonts.unshift('MathJax_default-italic');\" +\n            \"});\" +\n            \"MathJax.Hub.Register.StartupHook('SVG Jax Ready',function () {\" +\n                \"var VARIANT = MathJax.OutputJax.SVG.FONTDATA.VARIANT;\" +\n                \"VARIANT['normal'].fonts.unshift('MathJax_default');\" +\n                \"VARIANT['bold'].fonts.unshift('MathJax_default-bold');\" +\n                \"VARIANT['italic'].fonts.unshift('MathJax_default-italic');\" +\n                \"VARIANT['-tex-mathit'].fonts.unshift('MathJax_default-italic');\" +\n            \"});\" +\n        \"}\";\n\n    (document.body || document.getElementsByTagName('head')[0]).appendChild(configscript);\n    (document.body || document.getElementsByTagName('head')[0]).appendChild(mathjaxscript);\n}\n<\/script>","category":[{"@attributes":{"term":"Machine Learning"}},{"@attributes":{"term":"Machine Learning"}},{"@attributes":{"term":"Imputation"}},{"@attributes":{"term":"Deep Learning"}}]},{"title":"Categorial Encodings","link":{"@attributes":{"href":"https:\/\/WestHealth.github.io\/categorial-encodings.html","rel":"alternate"}},"published":"2020-02-21T14:50:00-08:00","updated":"2020-02-21T14:50:00-08:00","author":{"name":"Haw-minn Lu"},"id":"tag:westhealth.github.io,2020-02-21:\/categorial-encodings.html","summary":"<h1>Introduction<\/h1>\n<p>While most popular machine learning methods such as deep learning require\nnumerical data as input, categorical  data is very common practice. For\nexample, a person's vitals could be a combination of both, they could include\nheight, weight (numerical) and gender, race (categorical). The challenge is to\nconvert the categorical \u2026<\/p>","content":"<h1>Introduction<\/h1>\n<p>While most popular machine learning methods such as deep learning require\nnumerical data as input, categorical  data is very common practice. For\nexample, a person's vitals could be a combination of both, they could include\nheight, weight (numerical) and gender, race (categorical). The challenge is to\nconvert the categorical data into a vector of some sort. There is a good\noverview of most encoding techniques at this <a href=\"https:\/\/towardsdatascience.com\/smarter-ways-to-encode-categorical-data-for-machine-learning-part-1-of-3-6dca2f71b159\">blog\npost<\/a>.\nHe further categorizes the coding techniques as <em>classic<\/em>, <em>contrast<\/em>, and\n<em>Bayesian<\/em>. Notably, <em>word embeddings<\/em> are not mentioned. Both contrast\nencoding and Bayesian encoding use the\nstatistics of the data to facilitate encoding. These two categories may be of\nuse when more statistical analysis is required, however there has not been widespread adoption of these emcoding techniques for machine learning. These encoding techiques can be found as\npart of the <code>scikit-learn<\/code> category <a href=\"https:\/\/contrib.scikit-learn.org\/categorical-encoding\/index.html\">encoding\npackage<\/a>.<\/p>\n<p>Though we will pursue a discussion of classic encodings and modern derivatives,\nword embeddings deserve special mention. Word embeddings are used to represent\nwords, phrases or even entire documents as a vector. Their goal is that similar\nmeaning or concepts get mapped to vectors that are close in the target vector\nspace. Additionally, it is adapted for encoding a large categorical feature\n(i.e., words) into a relatively lower dimensional space.<\/p>\n<h3>Ordinal Encoding<\/h3>\n<p>To begin our overview of fundamental encoding methods, we start with Ordinal (Label)\nEncoding.  Ordinal encoding is the\nsimplest and perhaps most naive approach encoding a categorical feature --- one simply assigns a number to each member of a category. This is\noften how data from surveys are encoded into spreadsheets for easy storage and\ncalculation of basic statistics. An associated data dictionary is used to\nconvert the values back and forth between a number and a category. Take for\nexample the case of gender, male could be encoded as 1 and female as 2, with a\ndata dictionary as follows: <code>{'male': 1, 'female': 2}<\/code><\/p>\n<p>Suppose we have three categories of ethnic groups: White, Black, and Asian.\nUnder ordinal encoding, suppose What is encoded as 1, Black is encoded as 2 and\nAsian is encoded as 3. If a machine learning classification is somehow confused\nbetween Asian and White and decides to split the difference and report the\nin-between value (2) which encodes Black.  The issue is that arbitrary \ngradation between 1 and 3 introduces a natural interpolation (2) that may\nbe nonsense. Thus, the natural ordering of the numbers imposes an ordered \ngeometrical relationship between the categories that does not apply.<\/p>\n<p>Nonetheless there are situations where ordinal encoding makes sense. For\nexample, a 'rate your satisfaction' survey typically encodes five levels (1)\nterrible, (2) acceptable (3) mediocre, (4) good, (5) excellent.<\/p>\n<h3>One Hot Encoding<\/h3>\n<p>This is the most common encoding used in machine learning.  One hot encoding\ntakes a category with cardinality <span class=\"math\">\\(N\\)<\/span> and encodes each categorical value with\nan <span class=\"math\">\\(N\\)<\/span>-dimensional vector with a single '1' and the remainder '0's. Take as an\nexample encoding 5 makes of Japanese Cars: Toyota, Honda, Subaru, Nissan,\nMitsubishi. The following table shows a comparison of coding between ordinal\nand one-hot:<\/p>\n<table>\n<thead>\n<tr>\n<th>Make<\/th>\n<th align=\"center\">Ordinal<\/th>\n<th>One-Hot<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>Toyota<\/td>\n<td align=\"center\">1<\/td>\n<td>(1,0,0,0,0)<\/td>\n<\/tr>\n<tr>\n<td>Honda<\/td>\n<td align=\"center\">2<\/td>\n<td>(0,1,0,0,0)<\/td>\n<\/tr>\n<tr>\n<td>Subaru<\/td>\n<td align=\"center\">3<\/td>\n<td>(0,0,1,0,0)<\/td>\n<\/tr>\n<tr>\n<td>Nissan<\/td>\n<td align=\"center\">4<\/td>\n<td>(0,0,0,1,0)<\/td>\n<\/tr>\n<tr>\n<td>Mitsubishi<\/td>\n<td align=\"center\">5<\/td>\n<td>(0,0,0,0,1)<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>The advantage is that one hot encoding doesn't induce an implicit ordering or\nbetween categories. The primary disadvantage is that \nthe dimensionality of the problem has increased with \ncorresponding increases in complexity and computation (see <a href=\"https:\/\/en.wikipedia.org\/wiki\/Curse_of_dimensionality\">curse of\ndimensionality<\/a>)\nThis easily leads to the high dimensionality low sample size (HDLSS) situation,\nwhich is a problem for most machine learning methods.<\/p>\n<h3>Binary Encoding, Hash Encoding, BaseN Encoding<\/h3>\n<p>Somewhere in between these two are <em>binary encoding<\/em>, <em>hash encoding<\/em>, and\n<em>baseN<\/em> encoding. Binary encoding simply labels each category with a unique\nbinary code and converts the binary code to a vector. Using the previous\nexample of the Japanese car makes: <\/p>\n<table>\n<thead>\n<tr>\n<th>Make<\/th>\n<th align=\"center\">Ordinal<\/th>\n<th align=\"center\">as Binary<\/th>\n<th align=\"center\">Binary Code<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>Toyota<\/td>\n<td align=\"center\">1<\/td>\n<td align=\"center\">001<\/td>\n<td align=\"center\">(0,0,1)<\/td>\n<\/tr>\n<tr>\n<td>Honda<\/td>\n<td align=\"center\">2<\/td>\n<td align=\"center\">010<\/td>\n<td align=\"center\">(0,1,0)<\/td>\n<\/tr>\n<tr>\n<td>Subaru<\/td>\n<td align=\"center\">3<\/td>\n<td align=\"center\">011<\/td>\n<td align=\"center\">(0,1,1)<\/td>\n<\/tr>\n<tr>\n<td>Nissan<\/td>\n<td align=\"center\">4<\/td>\n<td align=\"center\">100<\/td>\n<td align=\"center\">(1,0,0)<\/td>\n<\/tr>\n<tr>\n<td>Mitsubishi<\/td>\n<td align=\"center\">5<\/td>\n<td align=\"center\">101<\/td>\n<td align=\"center\">(1,0,1)<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>Hash encoding assigns each category an ordinal value that is then converted\ninto a binary hash value that is encoded as an <span class=\"math\">\\(n\\)<\/span>-tuple in the same fashion as\nthe binary encoding. You can view hash encoding as binary encoding applied to\nthe hashed ordinal value. Hash encoding has several advantages. First, it is\nopen ended so new categories can be added later. Second, the resultant\ndimensionality can be much lower than one-hot encoding. The chief disadvantage\nis that categories can collide if two categories accidentally map into the same\nhash value. This is a <em>hash collision<\/em> and must be fixed separately using a\nresolution mechanism.  A good treatment of hash coding can be found\n<a href=\"https:\/\/booking.ai\/dont-be-tricked-by-the-hashing-trick-192a6aae3087\">here<\/a><\/p>\n<p>Finally, baseN encoding is a generalization of binary encoding  that uses a\nnumber base other than 2 (binary). Below is an example of the Japanese car\nmakes using base 3,<\/p>\n<table>\n<thead>\n<tr>\n<th>Make<\/th>\n<th align=\"center\">Ordinal<\/th>\n<th align=\"center\">as Ternary<\/th>\n<th align=\"center\">Ternary Code<\/th>\n<th align=\"center\">Balanced Ternary Code<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>Toyota<\/td>\n<td align=\"center\">1<\/td>\n<td align=\"center\">01<\/td>\n<td align=\"center\">(0,1)<\/td>\n<td align=\"center\">(0,1)<\/td>\n<\/tr>\n<tr>\n<td>Honda<\/td>\n<td align=\"center\">2<\/td>\n<td align=\"center\">02<\/td>\n<td align=\"center\">(0,2)<\/td>\n<td align=\"center\">(0,-1)<\/td>\n<\/tr>\n<tr>\n<td>Subaru<\/td>\n<td align=\"center\">3<\/td>\n<td align=\"center\">10<\/td>\n<td align=\"center\">(1,0)<\/td>\n<td align=\"center\">(1,0)<\/td>\n<\/tr>\n<tr>\n<td>Nissan<\/td>\n<td align=\"center\">4<\/td>\n<td align=\"center\">11<\/td>\n<td align=\"center\">(1,1)<\/td>\n<td align=\"center\">(1,1)<\/td>\n<\/tr>\n<tr>\n<td>Mitsubishi<\/td>\n<td align=\"center\">5<\/td>\n<td align=\"center\">12<\/td>\n<td align=\"center\">(1,2)<\/td>\n<td align=\"center\">(1,-1)<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>A disadvantage of all three of these techniques is that while it does reduce the\ndimension of the encoded feature, artificial geometric relationships \nmay creep in between unrelated categories.  For example, \n<code>(0.7,0.7)<\/code> may be confusion between Toyota and Honda or a weak Subaru result, \nalthough this is still better than ordinal encoding. <\/p>\n<h3>Quasiorthonormal Encoding<\/h3>\n<p>Quasiorthonormal encoding (QOE) is a generalization of the one-hot encoding and\nexploits the fact that in high-dimensional vector spaces, two random vectors\nare generally almost orthogonal. The concept originated with <a href=\"https:\/\/ieeexplore.ieee.org\/document\/549073\">K\u016frkov\u00e1 and\nKainen<\/a> almost 25 years ago. The\nprinciple is the same as one-hot encoding when you view the encoded values as\nunit vectors as shown:<\/p>\n<table>\n<thead>\n<tr>\n<th>Make<\/th>\n<th align=\"center\">Ordinal<\/th>\n<th align=\"center\">One-Hot<\/th>\n<th align=\"center\">QOE<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>Toyota<\/td>\n<td align=\"center\">1<\/td>\n<td align=\"center\"><span class=\"math\">\\(\\mathbf{u}_1\\)<\/span><\/td>\n<td align=\"center\"><span class=\"math\">\\(\\mathbf{q}_1\\)<\/span><\/td>\n<\/tr>\n<tr>\n<td>Honda<\/td>\n<td align=\"center\">2<\/td>\n<td align=\"center\"><span class=\"math\">\\(\\mathbf{u}_2\\)<\/span><\/td>\n<td align=\"center\"><span class=\"math\">\\(\\mathbf{q}_2\\)<\/span><\/td>\n<\/tr>\n<tr>\n<td>Subaru<\/td>\n<td align=\"center\">3<\/td>\n<td align=\"center\"><span class=\"math\">\\(\\mathbf{u}_3\\)<\/span><\/td>\n<td align=\"center\"><span class=\"math\">\\(\\mathbf{q}_3\\)<\/span><\/td>\n<\/tr>\n<tr>\n<td>Nissan<\/td>\n<td align=\"center\">4<\/td>\n<td align=\"center\"><span class=\"math\">\\(\\mathbf{u}_4\\)<\/span><\/td>\n<td align=\"center\"><span class=\"math\">\\(\\mathbf{q}_4\\)<\/span><\/td>\n<\/tr>\n<tr>\n<td>Mitsubishi<\/td>\n<td align=\"center\">5<\/td>\n<td align=\"center\"><span class=\"math\">\\(\\mathbf{u}_5\\)<\/span><\/td>\n<td align=\"center\"><span class=\"math\">\\(\\mathbf{q}_5\\)<\/span><\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>where <span class=\"math\">\\(\\mathbf{u}_i\\)<\/span> are unit vectors in <span class=\"math\">\\(\\mathbb{R}^5\\)<\/span> and <span class=\"math\">\\({\\mathbf{q}_i}\\)<\/span>\nare a set of quasiorthogonal vectors in a dimension less than 5. The set\n<span class=\"math\">\\({\\mathbf{q}_i}\\)<\/span> is quasiorthonormal if each <span class=\"math\">\\(\\mathbf{q}_i\\)<\/span> is normal\n(<span class=\"math\">\\(||\\mathbf{q}_i||=1\\)<\/span>) and <span class=\"math\">\\(|\\mathbf{q}_i\\cdot \\mathbf{q}_j|&lt;\\epsilon\\)<\/span> for some\nsmall <span class=\"math\">\\(\\epsilon\\)<\/span> value and for <span class=\"math\">\\(i\\ne j\\)<\/span>. In otherwords, if <span class=\"math\">\\(i\\)<\/span> and <span class=\"math\">\\(j\\)<\/span> are\ndistinct <span class=\"math\">\\(\\mathbf{q}_i\\)<\/span> and <span class=\"math\">\\(\\mathbf{q}_j\\)<\/span> are almost perpendicular.<\/p>\n<p>We will explore more about QOE in the next article.<\/p>\n<h3>Summary<\/h3>\n<p>Although most machine learning methods require numerical data, categorical data \nis very common in certain areas, such as medical data science or survey analysis. \nWe reviewed the most popular encoding methods to make this kind of data \ntractable for machine learning, but each of them has drawbacks in computation or \ninterpretation that can lead to confusing downstream results, if not handled correctly \nat the outset.<\/p>\n<script type=\"text\/javascript\">if (!document.getElementById('mathjaxscript_pelican_#%@#$@#')) {\n    var align = \"center\",\n        indent = \"0em\",\n        linebreak = \"false\";\n\n    if (false) {\n        align = (screen.width < 768) ? \"left\" : align;\n        indent = (screen.width < 768) ? \"0em\" : indent;\n        linebreak = (screen.width < 768) ? 'true' : linebreak;\n    }\n\n    var mathjaxscript = document.createElement('script');\n    mathjaxscript.id = 'mathjaxscript_pelican_#%@#$@#';\n    mathjaxscript.type = 'text\/javascript';\n    mathjaxscript.src = 'https:\/\/cdnjs.cloudflare.com\/ajax\/libs\/mathjax\/2.7.3\/latest.js?config=TeX-AMS-MML_HTMLorMML';\n\n    var configscript = document.createElement('script');\n    configscript.type = 'text\/x-mathjax-config';\n    configscript[(window.opera ? \"innerHTML\" : \"text\")] =\n        \"MathJax.Hub.Config({\" +\n        \"    config: ['MMLorHTML.js'],\" +\n        \"    TeX: { extensions: ['AMSmath.js','AMSsymbols.js','noErrors.js','noUndefined.js'], equationNumbers: { autoNumber: 'none' } },\" +\n        \"    jax: ['input\/TeX','input\/MathML','output\/HTML-CSS'],\" +\n        \"    extensions: ['tex2jax.js','mml2jax.js','MathMenu.js','MathZoom.js'],\" +\n        \"    displayAlign: '\"+ align +\"',\" +\n        \"    displayIndent: '\"+ indent +\"',\" +\n        \"    showMathMenu: true,\" +\n        \"    messageStyle: 'normal',\" +\n        \"    tex2jax: { \" +\n        \"        inlineMath: [ ['\\\\\\\\(','\\\\\\\\)'] ], \" +\n        \"        displayMath: [ ['$$','$$'] ],\" +\n        \"        processEscapes: true,\" +\n        \"        preview: 'TeX',\" +\n        \"    }, \" +\n        \"    'HTML-CSS': { \" +\n        \"        availableFonts: ['STIX', 'TeX'],\" +\n        \"        preferredFont: 'STIX',\" +\n        \"        styles: { '.MathJax_Display, .MathJax .mo, .MathJax .mi, .MathJax .mn': {color: 'inherit ! important'} },\" +\n        \"        linebreaks: { automatic: \"+ linebreak +\", width: '90% container' },\" +\n        \"    }, \" +\n        \"}); \" +\n        \"if ('default' !== 'default') {\" +\n            \"MathJax.Hub.Register.StartupHook('HTML-CSS Jax Ready',function () {\" +\n                \"var VARIANT = MathJax.OutputJax['HTML-CSS'].FONTDATA.VARIANT;\" +\n                \"VARIANT['normal'].fonts.unshift('MathJax_default');\" +\n                \"VARIANT['bold'].fonts.unshift('MathJax_default-bold');\" +\n                \"VARIANT['italic'].fonts.unshift('MathJax_default-italic');\" +\n                \"VARIANT['-tex-mathit'].fonts.unshift('MathJax_default-italic');\" +\n            \"});\" +\n            \"MathJax.Hub.Register.StartupHook('SVG Jax Ready',function () {\" +\n                \"var VARIANT = MathJax.OutputJax.SVG.FONTDATA.VARIANT;\" +\n                \"VARIANT['normal'].fonts.unshift('MathJax_default');\" +\n                \"VARIANT['bold'].fonts.unshift('MathJax_default-bold');\" +\n                \"VARIANT['italic'].fonts.unshift('MathJax_default-italic');\" +\n                \"VARIANT['-tex-mathit'].fonts.unshift('MathJax_default-italic');\" +\n            \"});\" +\n        \"}\";\n\n    (document.body || document.getElementsByTagName('head')[0]).appendChild(configscript);\n    (document.body || document.getElementsByTagName('head')[0]).appendChild(mathjaxscript);\n}\n<\/script>","category":[{"@attributes":{"term":"Machine Learning"}},{"@attributes":{"term":"Machine Learning"}},{"@attributes":{"term":"Deep Learning"}}]},{"title":"Interactive Spotify networks with Pyvis","link":{"@attributes":{"href":"https:\/\/WestHealth.github.io\/pyvis_spotify_network.html","rel":"alternate"}},"published":"2020-02-10T00:00:00-08:00","updated":"2020-02-10T00:00:00-08:00","author":{"name":"Giancarlo Perrone"},"id":"tag:westhealth.github.io,2020-02-10:\/pyvis_spotify_network.html","summary":"<p>Successful Data Science pivots upon discovering meaningful relationships in data using intuitive visualizations. Representing relationships using a network graph is a common approach, but generating an interactive and fluid graph visualization can be a challenge, especially with large datasets. In this blog post we introduce Pyvis, a python module based upon the mature VisJS JavaScript library, enabling fluid and interactive visualizations of complex network graphs.<\/p>","content":"<h2>Interactive network graphs with Pyvis<\/h2>\n<p>Successful Data Science pivots upon discovering meaningful relationships in data using intuitive visualizations. Representing relationships using a network graph is a common approach, but generating an interactive and fluid graph visualization can be a challenge, especially with large datasets. In this blog post we introduce Pyvis, a python module based upon the mature VisJS JavaScript library, enabling fluid and interactive visualizations of complex network graphs.<\/p>\n<p>It is recommended to also check out the standalone JavaScript library, <strong><em>visjs<\/em><\/strong> to see even more examples of the capabilities. Documentation can be found <a href=\"https:\/\/visjs.github.io\/vis-network\/docs\/network\/\">here.<\/a><\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kn\">from<\/span> <span class=\"nn\">IPython.display<\/span> <span class=\"kn\">import<\/span> <span class=\"n\">HTML<\/span>\n<span class=\"n\">HTML<\/span><span class=\"p\">(<\/span><span class=\"s1\">&#39;&lt;img src=&quot;extra\/showcase.gif&quot; height=500px width=500px&gt;&#39;<\/span><span class=\"p\">)<\/span>\n<\/code><\/pre><\/div>\n\n<h2>Installation<\/h2>\n<p>To install pyvis simply invoke<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>pip install pyvis\n<\/code><\/pre><\/div>\n\n<p>in a terminal<\/p>\n<p>You can verify that pyvis was installed correctly by importing it:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kn\">import<\/span> <span class=\"nn\">pyvis<\/span>\n<\/code><\/pre><\/div>\n\n<h2>Getting started<\/h2>\n<p>The standard way to import pyvis' Network interface is to import it as<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kn\">from<\/span> <span class=\"nn\">pyvis.network<\/span> <span class=\"kn\">import<\/span> <span class=\"n\">Network<\/span>\n<\/code><\/pre><\/div>\n\n<h4>Use a Network instance to create your first graph<\/h4>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">g<\/span> <span class=\"o\">=<\/span> <span class=\"n\">Network<\/span><span class=\"p\">()<\/span>\n<\/code><\/pre><\/div>\n\n<p>This blog post is written in Jupyter Notebook, pyvis supports experimentation within jupyter.\nTo use pyvis from a notebook persepective, pass the notebook indicator upon instantiation:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">g<\/span> <span class=\"o\">=<\/span> <span class=\"n\">Network<\/span><span class=\"p\">(<\/span><span class=\"n\">notebook<\/span><span class=\"o\">=<\/span><span class=\"kc\">True<\/span><span class=\"p\">)<\/span>\n<\/code><\/pre><\/div>\n\n<h2>Dataset exploration<\/h2>\n<p>To demonstrate a practical example of building intuitive relational visualizations, I am choosing to explore Spotify data for artists and their related artists. I have already aggregated and stored the data as a csv, so let's begin to explore what we're working with. <\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kn\">from<\/span> <span class=\"nn\">pyvis.network<\/span> <span class=\"kn\">import<\/span> <span class=\"n\">Network<\/span>\n<span class=\"kn\">import<\/span> <span class=\"nn\">pandas<\/span> <span class=\"k\">as<\/span> <span class=\"nn\">pd<\/span>\n<span class=\"n\">df<\/span> <span class=\"o\">=<\/span> <span class=\"n\">pd<\/span><span class=\"o\">.<\/span><span class=\"n\">read_csv<\/span><span class=\"p\">(<\/span><span class=\"s2\">&quot;..\/spotify_graph.csv&quot;<\/span><span class=\"p\">,<\/span> <span class=\"n\">index_col<\/span><span class=\"o\">=<\/span><span class=\"mi\">0<\/span><span class=\"p\">)<\/span>\n<\/code><\/pre><\/div>\n\n<p>Our dataframe is as basic as it gets. Each unique artist in the <code>artist<\/code> column is in the top 20 listened to artists for this particular user. The corresponding artist in the <code>related<\/code> column specifies a link or relationship between these two artists.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">df<\/span><span class=\"o\">.<\/span><span class=\"n\">head<\/span><span class=\"p\">()<\/span>\n<\/code><\/pre><\/div>\n\n<p>Now, let's create our graph:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">g<\/span> <span class=\"o\">=<\/span> <span class=\"n\">Network<\/span><span class=\"p\">(<\/span><span class=\"n\">notebook<\/span><span class=\"o\">=<\/span><span class=\"kc\">True<\/span><span class=\"p\">,<\/span> <span class=\"n\">width<\/span><span class=\"o\">=<\/span><span class=\"mi\">750<\/span><span class=\"p\">,<\/span> <span class=\"n\">height<\/span><span class=\"o\">=<\/span><span class=\"mi\">800<\/span><span class=\"p\">,<\/span> <span class=\"n\">bgcolor<\/span><span class=\"o\">=<\/span><span class=\"s2\">&quot;#3c4647&quot;<\/span><span class=\"p\">,<\/span> <span class=\"n\">font_color<\/span><span class=\"o\">=<\/span><span class=\"s2\">&quot;white&quot;<\/span><span class=\"p\">)<\/span>\n<span class=\"n\">g<\/span>\n<\/code><\/pre><\/div>\n\n<p>At this point, we can add the individual nodes in each column<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">for<\/span> <span class=\"n\">artist<\/span> <span class=\"ow\">in<\/span> <span class=\"n\">df<\/span><span class=\"o\">.<\/span><span class=\"n\">artist<\/span><span class=\"p\">:<\/span>\n    <span class=\"n\">g<\/span><span class=\"o\">.<\/span><span class=\"n\">add_node<\/span><span class=\"p\">(<\/span><span class=\"n\">artist<\/span><span class=\"p\">,<\/span> <span class=\"n\">label<\/span><span class=\"o\">=<\/span><span class=\"n\">artist<\/span><span class=\"p\">,<\/span> <span class=\"n\">color<\/span><span class=\"o\">=<\/span><span class=\"s2\">&quot;#26d18f&quot;<\/span><span class=\"p\">)<\/span>\n<span class=\"k\">for<\/span> <span class=\"n\">related<\/span> <span class=\"ow\">in<\/span> <span class=\"n\">df<\/span><span class=\"o\">.<\/span><span class=\"n\">related<\/span><span class=\"p\">:<\/span>\n    <span class=\"n\">g<\/span><span class=\"o\">.<\/span><span class=\"n\">add_node<\/span><span class=\"p\">(<\/span><span class=\"n\">related<\/span><span class=\"p\">,<\/span> <span class=\"n\">label<\/span><span class=\"o\">=<\/span><span class=\"n\">related<\/span><span class=\"p\">,<\/span> <span class=\"n\">color<\/span><span class=\"o\">=<\/span><span class=\"s2\">&quot;#8965c7&quot;<\/span><span class=\"p\">)<\/span>\n<span class=\"n\">g<\/span>\n<\/code><\/pre><\/div>\n\n<p>To display our results, we use the <code>show()<\/code> method and provide a name for the html output<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">g<\/span><span class=\"o\">.<\/span><span class=\"n\">show<\/span><span class=\"p\">(<\/span><span class=\"s2\">&quot;extra\/snodes.html&quot;<\/span><span class=\"p\">)<\/span>\n<\/code><\/pre><\/div>\n\n<p>The above graph doesn't really tell us anything of value, but we can easily distinguish between our <span style=\"color:#26d18f\">source nodes<\/span> and <span style=\"color:#8965c7\">destination nodes<\/span>.<\/p>\n<p>Let's add the edges to see how the top 20 artists link to their related artists.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">g<\/span><span class=\"o\">.<\/span><span class=\"n\">add_edges<\/span><span class=\"p\">(<\/span><span class=\"nb\">list<\/span><span class=\"p\">(<\/span><span class=\"nb\">zip<\/span><span class=\"p\">(<\/span><span class=\"n\">df<\/span><span class=\"o\">.<\/span><span class=\"n\">artist<\/span><span class=\"p\">,<\/span> <span class=\"n\">df<\/span><span class=\"o\">.<\/span><span class=\"n\">related<\/span><span class=\"p\">)))<\/span>\n<\/code><\/pre><\/div>\n\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">g<\/span><span class=\"o\">.<\/span><span class=\"n\">show<\/span><span class=\"p\">(<\/span><span class=\"s2\">&quot;extra\/sconnect_init.html&quot;<\/span><span class=\"p\">)<\/span>\n<\/code><\/pre><\/div>\n\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">g<\/span>\n<\/code><\/pre><\/div>\n\n<p>Now our network is connected! It is easy to identify the clusters our data creates. Again, noticing the the <strong><span style=\"color:#26d18f\">central<\/span><\/strong> and <strong><span style=\"color:#8965c7\">outgoing<\/span><\/strong> nodes. Here, we can zoom in to the network to click on and drag nodes to navigate the data. In this network, you will notice that there are certain clusters that are interconnected, as well as some disconnected islands. The islands make up the <code>outliers<\/code> of the listening pattern as their links are not aligned with the majority of the data. <\/p>\n<p>The interconnectivity is not exactly obvious to notice at first. For example, the <strong><em>King Krule<\/em><\/strong> and <strong><em>Tame Impala<\/em><\/strong> clusters contain multiple edges, meaning that particular artist appears several times in the <code>related<\/code> set of artists.<\/p>\n<p>Looking back at our DataFrame we can delve into the <code>related<\/code> columns to see how many times each related artist appears as a result of having a relationship with another top artist.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">counts<\/span> <span class=\"o\">=<\/span> <span class=\"n\">df<\/span><span class=\"o\">.<\/span><span class=\"n\">related<\/span><span class=\"o\">.<\/span><span class=\"n\">value_counts<\/span><span class=\"p\">()<\/span> \n<span class=\"n\">counts<\/span>\n<\/code><\/pre><\/div>\n\n<p>Using the above data we can modify our nodes to adapt to the frequencies in which the node appears, as well as provide that frequency in the node metadata.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">for<\/span> <span class=\"n\">node<\/span> <span class=\"ow\">in<\/span> <span class=\"n\">g<\/span><span class=\"o\">.<\/span><span class=\"n\">nodes<\/span><span class=\"p\">:<\/span>\n    <span class=\"n\">freq<\/span> <span class=\"o\">=<\/span> <span class=\"nb\">str<\/span><span class=\"p\">(<\/span><span class=\"n\">counts<\/span><span class=\"o\">.<\/span><span class=\"n\">get<\/span><span class=\"p\">(<\/span><span class=\"n\">node<\/span><span class=\"p\">[<\/span><span class=\"s1\">&#39;id&#39;<\/span><span class=\"p\">],<\/span> <span class=\"mi\">1<\/span><span class=\"p\">))<\/span>\n    <span class=\"c1\"># nodes with a value will scale their size<\/span>\n    <span class=\"c1\"># nodes with a title will include a hover tooltip on the node<\/span>\n    <span class=\"n\">node<\/span><span class=\"o\">.<\/span><span class=\"n\">update<\/span><span class=\"p\">({<\/span><span class=\"s2\">&quot;value&quot;<\/span><span class=\"p\">:<\/span> <span class=\"n\">freq<\/span><span class=\"p\">,<\/span> <span class=\"s2\">&quot;title&quot;<\/span><span class=\"p\">:<\/span> <span class=\"sa\">f<\/span><span class=\"s2\">&quot;Frequency: <\/span><span class=\"si\">{<\/span><span class=\"n\">freq<\/span><span class=\"si\">}<\/span><span class=\"s2\">&quot;<\/span><span class=\"p\">})<\/span>\n<span class=\"n\">g<\/span><span class=\"o\">.<\/span><span class=\"n\">nodes<\/span><span class=\"p\">[<\/span><span class=\"mi\">0<\/span><span class=\"p\">]<\/span>\n<\/code><\/pre><\/div>\n\n<p>We can also tweak the colors of the edges. Default pyvis behavior is to color the edges the based on the color of the source node. By configuring our <code>Network<\/code> to inherit edge colors from the destination nodes we can benefit from seeing how our source artists relate to the related artists:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">g<\/span><span class=\"o\">.<\/span><span class=\"n\">inherit_edge_colors<\/span><span class=\"p\">(<\/span><span class=\"s2\">&quot;to&quot;<\/span><span class=\"p\">)<\/span>\n<\/code><\/pre><\/div>\n\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">g<\/span><span class=\"o\">.<\/span><span class=\"n\">show<\/span><span class=\"p\">(<\/span><span class=\"s2\">&quot;extra\/smodded.html&quot;<\/span><span class=\"p\">)<\/span>\n<\/code><\/pre><\/div>\n\n<h2>Edge metadata<\/h2>\n<p>Just how we demonstrated adding labels to the nodes on hover, we can also add labels to edges in the same manner. Just like nodes, the <code>title<\/code> attribute of the edges can be supplied to render a hoverable tooltip to display edge information: <\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">for<\/span> <span class=\"n\">e<\/span> <span class=\"ow\">in<\/span> <span class=\"n\">g<\/span><span class=\"o\">.<\/span><span class=\"n\">edges<\/span><span class=\"p\">:<\/span>\n    <span class=\"n\">edge_label<\/span> <span class=\"o\">=<\/span> <span class=\"sa\">f<\/span><span class=\"s1\">&#39;<\/span><span class=\"si\">{<\/span><span class=\"n\">e<\/span><span class=\"p\">[<\/span><span class=\"s2\">&quot;from&quot;<\/span><span class=\"p\">]<\/span><span class=\"si\">}<\/span><span class=\"s1\"> ---&gt; <\/span><span class=\"si\">{<\/span><span class=\"n\">e<\/span><span class=\"p\">[<\/span><span class=\"s2\">&quot;to&quot;<\/span><span class=\"p\">]<\/span><span class=\"si\">}<\/span><span class=\"s1\">&#39;<\/span>\n    <span class=\"n\">e<\/span><span class=\"o\">.<\/span><span class=\"n\">update<\/span><span class=\"p\">({<\/span><span class=\"s2\">&quot;title&quot;<\/span><span class=\"p\">:<\/span> <span class=\"n\">edge_label<\/span><span class=\"p\">})<\/span>\n<span class=\"n\">g<\/span><span class=\"o\">.<\/span><span class=\"n\">edges<\/span><span class=\"p\">[<\/span><span class=\"mi\">0<\/span><span class=\"p\">]<\/span>\n<\/code><\/pre><\/div>\n\n<p>Try <strong>hovering<\/strong> over an edge below to see the effect!<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">g<\/span><span class=\"o\">.<\/span><span class=\"n\">show<\/span><span class=\"p\">(<\/span><span class=\"s2\">&quot;extra\/sedgetitles.html&quot;<\/span><span class=\"p\">)<\/span>\n<\/code><\/pre><\/div>\n\n<p>Now it is much easier to tell which artists contribute to the listening pattern displayed. The bigger the node, the more it appears as a related artist to the top listened. Furthermore, nodes with <span style=\"color:#26d18f\">green<\/span> edges between them, indicate that they each appear in each other's related artists list.<\/p>\n<h2>Layout<\/h2>\n<p>Due to pyvis' default physics settings, initial network graphs may contain undesirable features. For example, our graph so far has adapted well to spacing out clusters and drawing them nicely. However, the more dense clusters contain overlapping nodes. Internal physics parameters can be tweaked to result in desired layout, and pyvis offers a sandbox-like approach to generating layout parameters.<\/p>\n<p>Achieve this with the <code>show_buttons()<\/code> method, which will attach a set of tweakable options to the graph in order to adjust settings in a live setting. Use the scroll wheel on the resulting graph to access and tweak the modifiers.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">g<\/span><span class=\"o\">.<\/span><span class=\"n\">show_buttons<\/span><span class=\"p\">(<\/span><span class=\"n\">filter_<\/span><span class=\"o\">=<\/span><span class=\"s2\">&quot;physics&quot;<\/span><span class=\"p\">)<\/span> <span class=\"c1\"># only show physics options<\/span>\n<span class=\"n\">g<\/span><span class=\"o\">.<\/span><span class=\"n\">show<\/span><span class=\"p\">(<\/span><span class=\"s2\">&quot;extra\/sbuttons.html&quot;<\/span><span class=\"p\">)<\/span>\n<\/code><\/pre><\/div>\n\n<p>We need to tweak the Network's options. Examining the options member we see the following:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">g<\/span><span class=\"o\">.<\/span><span class=\"n\">options<\/span>\n<\/code><\/pre><\/div>\n\n<p>So, using the settings UI to adjust parameters until satisfied with the layout, you can copy and paste the output from the <code>generate options<\/code> button to update the Network's internal options dict. I found the <code>barnesHut<\/code> solver to be best with the below settings:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">g<\/span><span class=\"o\">.<\/span><span class=\"n\">options<\/span><span class=\"o\">.<\/span><span class=\"vm\">__dict__<\/span><span class=\"o\">.<\/span><span class=\"n\">update<\/span><span class=\"p\">({<\/span>\n  <span class=\"s2\">&quot;physics&quot;<\/span><span class=\"p\">:<\/span> <span class=\"p\">{<\/span>\n    <span class=\"s2\">&quot;barnesHut&quot;<\/span><span class=\"p\">:<\/span> <span class=\"p\">{<\/span>\n      <span class=\"s2\">&quot;gravitationalConstant&quot;<\/span><span class=\"p\">:<\/span> <span class=\"o\">-<\/span><span class=\"mi\">8500<\/span><span class=\"p\">,<\/span>\n      <span class=\"s2\">&quot;centralGravity&quot;<\/span><span class=\"p\">:<\/span> <span class=\"mf\">0.95<\/span><span class=\"p\">,<\/span>\n      <span class=\"s2\">&quot;springLength&quot;<\/span><span class=\"p\">:<\/span> <span class=\"mi\">195<\/span>\n    <span class=\"p\">},<\/span>\n    <span class=\"s2\">&quot;minVelocity&quot;<\/span><span class=\"p\">:<\/span> <span class=\"mf\">0.75<\/span>\n  <span class=\"p\">}<\/span>\n<span class=\"p\">})<\/span>\n<\/code><\/pre><\/div>\n\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">g<\/span><span class=\"o\">.<\/span><span class=\"n\">options<\/span>\n<\/code><\/pre><\/div>\n\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">g<\/span><span class=\"o\">.<\/span><span class=\"n\">conf<\/span> <span class=\"o\">=<\/span> <span class=\"kc\">False<\/span> <span class=\"c1\"># this is needed at the moment when reverting from a show_buttons call<\/span>\n<span class=\"n\">g<\/span><span class=\"o\">.<\/span><span class=\"n\">options<\/span><span class=\"o\">.<\/span><span class=\"vm\">__dict__<\/span><span class=\"o\">.<\/span><span class=\"n\">update<\/span><span class=\"p\">({<\/span>\n    <span class=\"s2\">&quot;configure&quot;<\/span><span class=\"p\">:<\/span> <span class=\"p\">{<\/span>\n        <span class=\"s2\">&quot;enabled&quot;<\/span><span class=\"p\">:<\/span> <span class=\"kc\">False<\/span>\n    <span class=\"p\">}<\/span>\n<span class=\"p\">})<\/span>\n\n<span class=\"n\">g<\/span><span class=\"o\">.<\/span><span class=\"n\">show<\/span><span class=\"p\">(<\/span><span class=\"s2\">&quot;extra\/sfinal.html&quot;<\/span><span class=\"p\">)<\/span>\n<\/code><\/pre><\/div>\n\n<h2>Conclusion<\/h2>\n<p>Pyvis is a powerful tool to incorporate in any data analysis task dealing with relationships between data points or topological structures. With a familiar approach to building our data Network data structures, you have seen that visualization of the results is quick and easy. Additional customization is supported to accomodate specific layout needs as well -- all supported within a Jupyter Notebook environment. <\/p>\n<p>Pyvis is open source, additional feedback\/feature requests and contribution is welcome! Check out pyvis on <a href=\"https:\/\/github.com\/WestHealth\/pyvis\">github<\/a>, or check out the documentation on <a href=\"https:\/\/pyvis.readthedocs.io\/en\/latest\/\">readthedocs<\/a>.<\/p>","category":[{"@attributes":{"term":"Network"}},{"@attributes":{"term":"pyvis"}},{"@attributes":{"term":"spotify"}},{"@attributes":{"term":"graphs"}},{"@attributes":{"term":"visualization"}}]},{"title":"Heatmap Test","link":{"@attributes":{"href":"https:\/\/WestHealth.github.io\/heatmap-test.html","rel":"alternate"}},"published":"2019-11-22T11:35:00-08:00","updated":"2019-11-22T11:35:00-08:00","author":{"name":"Haw-minn Lu"},"id":"tag:westhealth.github.io,2019-11-22:\/heatmap-test.html","summary":"<p>Heat map code from https:\/\/stackoverflow.com\/questions\/33282368\/plotting-a-2d-heatmap-with-matplotlib<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kn\">import<\/span> <span class=\"nn\">matplotlib.pyplot<\/span> <span class=\"k\">as<\/span> <span class=\"nn\">plt<\/span>\n<span class=\"kn\">import<\/span> <span class=\"nn\">numpy<\/span> <span class=\"k\">as<\/span> <span class=\"nn\">np<\/span>\n<\/code><\/pre><\/div>\n\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"o\">%<\/span><span class=\"n\">matplotlib<\/span> <span class=\"n\">inline<\/span>\n<\/code><\/pre><\/div>\n\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"c1\"># generate 2 2d grids for the x &amp; y bounds<\/span>\n<span class=\"n\">y<\/span><span class=\"p\">,<\/span> <span class=\"n\">x<\/span> <span class=\"o\">=<\/span> <span class=\"n\">np<\/span><span class=\"o\">.<\/span><span class=\"n\">meshgrid<\/span><span class=\"p\">(<\/span><span class=\"n\">np<\/span><span class=\"o\">.<\/span><span class=\"n\">linspace<\/span><span class=\"p\">(<\/span><span class=\"o\">-<\/span><span class=\"mi\">3<\/span><span class=\"p\">,<\/span> <span class=\"mi\">3<\/span><span class=\"p\">,<\/span> <span class=\"mi\">100<\/span><span class=\"p\">),<\/span> <span class=\"n\">np<\/span><span class=\"o\">.<\/span><span class=\"n\">linspace<\/span><span class=\"p\">(<\/span><span class=\"o\">-<\/span><span class=\"mi\">3<\/span><span class=\"p\">,<\/span> <span class=\"mi\">3<\/span><span class=\"p\">,<\/span> <span class=\"mi\">100<\/span><span class=\"p\">))<\/span>\n\n<span class=\"n\">z<\/span> <span class=\"o\">=<\/span> <span class=\"p\">(<\/span><span class=\"mi\">1<\/span> <span class=\"o\">-<\/span> <span class=\"n\">x<\/span> <span class=\"o\">\/<\/span> <span class=\"mf\">2.<\/span> <span class=\"o\">+<\/span> <span class=\"n\">x<\/span> <span class=\"o\">**<\/span> <span class=\"mi\">5 \u2026<\/span><\/code><\/pre><\/div>","content":"<p>Heat map code from https:\/\/stackoverflow.com\/questions\/33282368\/plotting-a-2d-heatmap-with-matplotlib<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kn\">import<\/span> <span class=\"nn\">matplotlib.pyplot<\/span> <span class=\"k\">as<\/span> <span class=\"nn\">plt<\/span>\n<span class=\"kn\">import<\/span> <span class=\"nn\">numpy<\/span> <span class=\"k\">as<\/span> <span class=\"nn\">np<\/span>\n<\/code><\/pre><\/div>\n\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"o\">%<\/span><span class=\"n\">matplotlib<\/span> <span class=\"n\">inline<\/span>\n<\/code><\/pre><\/div>\n\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"c1\"># generate 2 2d grids for the x &amp; y bounds<\/span>\n<span class=\"n\">y<\/span><span class=\"p\">,<\/span> <span class=\"n\">x<\/span> <span class=\"o\">=<\/span> <span class=\"n\">np<\/span><span class=\"o\">.<\/span><span class=\"n\">meshgrid<\/span><span class=\"p\">(<\/span><span class=\"n\">np<\/span><span class=\"o\">.<\/span><span class=\"n\">linspace<\/span><span class=\"p\">(<\/span><span class=\"o\">-<\/span><span class=\"mi\">3<\/span><span class=\"p\">,<\/span> <span class=\"mi\">3<\/span><span class=\"p\">,<\/span> <span class=\"mi\">100<\/span><span class=\"p\">),<\/span> <span class=\"n\">np<\/span><span class=\"o\">.<\/span><span class=\"n\">linspace<\/span><span class=\"p\">(<\/span><span class=\"o\">-<\/span><span class=\"mi\">3<\/span><span class=\"p\">,<\/span> <span class=\"mi\">3<\/span><span class=\"p\">,<\/span> <span class=\"mi\">100<\/span><span class=\"p\">))<\/span>\n\n<span class=\"n\">z<\/span> <span class=\"o\">=<\/span> <span class=\"p\">(<\/span><span class=\"mi\">1<\/span> <span class=\"o\">-<\/span> <span class=\"n\">x<\/span> <span class=\"o\">\/<\/span> <span class=\"mf\">2.<\/span> <span class=\"o\">+<\/span> <span class=\"n\">x<\/span> <span class=\"o\">**<\/span> <span class=\"mi\">5<\/span> <span class=\"o\">+<\/span> <span class=\"n\">y<\/span> <span class=\"o\">**<\/span> <span class=\"mi\">3<\/span><span class=\"p\">)<\/span> <span class=\"o\">*<\/span> <span class=\"n\">np<\/span><span class=\"o\">.<\/span><span class=\"n\">exp<\/span><span class=\"p\">(<\/span><span class=\"o\">-<\/span><span class=\"n\">x<\/span> <span class=\"o\">**<\/span> <span class=\"mi\">2<\/span> <span class=\"o\">-<\/span> <span class=\"n\">y<\/span> <span class=\"o\">**<\/span> <span class=\"mi\">2<\/span><span class=\"p\">)<\/span>\n<span class=\"c1\"># x and y are bounds, so z should be the value *inside* those bounds.<\/span>\n<span class=\"c1\"># Therefore, remove the last value from the z array.<\/span>\n<span class=\"n\">z<\/span> <span class=\"o\">=<\/span> <span class=\"n\">z<\/span><span class=\"p\">[:<\/span><span class=\"o\">-<\/span><span class=\"mi\">1<\/span><span class=\"p\">,<\/span> <span class=\"p\">:<\/span><span class=\"o\">-<\/span><span class=\"mi\">1<\/span><span class=\"p\">]<\/span>\n<span class=\"n\">z_min<\/span><span class=\"p\">,<\/span> <span class=\"n\">z_max<\/span> <span class=\"o\">=<\/span> <span class=\"o\">-<\/span><span class=\"n\">np<\/span><span class=\"o\">.<\/span><span class=\"n\">abs<\/span><span class=\"p\">(<\/span><span class=\"n\">z<\/span><span class=\"p\">)<\/span><span class=\"o\">.<\/span><span class=\"n\">max<\/span><span class=\"p\">(),<\/span> <span class=\"n\">np<\/span><span class=\"o\">.<\/span><span class=\"n\">abs<\/span><span class=\"p\">(<\/span><span class=\"n\">z<\/span><span class=\"p\">)<\/span><span class=\"o\">.<\/span><span class=\"n\">max<\/span><span class=\"p\">()<\/span>\n\n<span class=\"n\">fig<\/span><span class=\"p\">,<\/span> <span class=\"n\">ax<\/span> <span class=\"o\">=<\/span> <span class=\"n\">plt<\/span><span class=\"o\">.<\/span><span class=\"n\">subplots<\/span><span class=\"p\">()<\/span>\n\n<span class=\"n\">c<\/span> <span class=\"o\">=<\/span> <span class=\"n\">ax<\/span><span class=\"o\">.<\/span><span class=\"n\">pcolormesh<\/span><span class=\"p\">(<\/span><span class=\"n\">x<\/span><span class=\"p\">,<\/span> <span class=\"n\">y<\/span><span class=\"p\">,<\/span> <span class=\"n\">z<\/span><span class=\"p\">,<\/span> <span class=\"n\">cmap<\/span><span class=\"o\">=<\/span><span class=\"s1\">&#39;RdBu&#39;<\/span><span class=\"p\">,<\/span> <span class=\"n\">vmin<\/span><span class=\"o\">=<\/span><span class=\"n\">z_min<\/span><span class=\"p\">,<\/span> <span class=\"n\">vmax<\/span><span class=\"o\">=<\/span><span class=\"n\">z_max<\/span><span class=\"p\">)<\/span>\n<span class=\"n\">ax<\/span><span class=\"o\">.<\/span><span class=\"n\">set_title<\/span><span class=\"p\">(<\/span><span class=\"s1\">&#39;pcolormesh&#39;<\/span><span class=\"p\">)<\/span>\n<span class=\"c1\"># set the limits of the plot to the limits of the data<\/span>\n<span class=\"n\">ax<\/span><span class=\"o\">.<\/span><span class=\"n\">axis<\/span><span class=\"p\">([<\/span><span class=\"n\">x<\/span><span class=\"o\">.<\/span><span class=\"n\">min<\/span><span class=\"p\">(),<\/span> <span class=\"n\">x<\/span><span class=\"o\">.<\/span><span class=\"n\">max<\/span><span class=\"p\">(),<\/span> <span class=\"n\">y<\/span><span class=\"o\">.<\/span><span class=\"n\">min<\/span><span class=\"p\">(),<\/span> <span class=\"n\">y<\/span><span class=\"o\">.<\/span><span class=\"n\">max<\/span><span class=\"p\">()])<\/span>\n<span class=\"n\">fig<\/span><span class=\"o\">.<\/span><span class=\"n\">colorbar<\/span><span class=\"p\">(<\/span><span class=\"n\">c<\/span><span class=\"p\">,<\/span> <span class=\"n\">ax<\/span><span class=\"o\">=<\/span><span class=\"n\">ax<\/span><span class=\"p\">)<\/span>\n\n<span class=\"n\">plt<\/span><span class=\"o\">.<\/span><span class=\"n\">show<\/span><span class=\"p\">()<\/span>\n<\/code><\/pre><\/div>\n\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">z<\/span><span class=\"o\">.<\/span><span class=\"n\">shape<\/span>\n<\/code><\/pre><\/div>\n\n<div class=\"highlight\"><pre><span><\/span><code>\n<\/code><\/pre><\/div>","category":[{"@attributes":{"term":"Machine Learning"}},{"@attributes":{"term":"Machine Learning"}},{"@attributes":{"term":"Deep Learning"}}]},{"title":"Welcome to West Health Machine Learning and Analytics Blog","link":{"@attributes":{"href":"https:\/\/WestHealth.github.io\/welcome-to-west-health-machine-learning-and-analytics-blog.html","rel":"alternate"}},"published":"2019-11-22T11:35:00-08:00","updated":"2019-11-22T11:35:00-08:00","author":{"name":"Haw-minn Lu"},"id":"tag:westhealth.github.io,2019-11-22:\/welcome-to-west-health-machine-learning-and-analytics-blog.html","summary":"<h3>Who we are and what we do<\/h3>\n<p>The mission of West Health Institute is to lower healthcare costs to enable\nseniors to successfully age in place, with access to high-quality, affordable\nhealth and support services that preserve and protect their dignity, quality of\nlife and independence. Data Science is fundamental \u2026<\/p>","content":"<h3>Who we are and what we do<\/h3>\n<p>The mission of West Health Institute is to lower healthcare costs to enable\nseniors to successfully age in place, with access to high-quality, affordable\nhealth and support services that preserve and protect their dignity, quality of\nlife and independence. Data Science is fundamental to this mission because data\ninforms the institutional policy decisions for both private and public\norganizations.<\/p>\n<p>The West Health Institute has developed substantial in-house,\nmulti-disciplinary expertise in data-driven methods for decision-making through\nits Data Science Engineering team. Bringing together access to major\nhealthcare-related databases with core skills and resources, capabilities\ninclude everything from database administration to economic analysis to\nstatistics to data visualization for quantitative insights tailored to research\ngoals. The Data Science team extracts, transforms, merges, and loads data\nsources to create descriptive and predictive models of care for all aspects of\naging-related research through customized HIPAA-compliant private cloud on\nrunning Amazon Web Services (AWS).<\/p>\n<h3>What to expect on this blog<\/h3>\n<p>Articles in this blog will be of three types. <\/p>\n<ul>\n<li>Sharing of our novel Data Science methods.<\/li>\n<\/ul>\n<p>For example, we are currently developing techniques for quasiorthonormal \n  encoding for outlier and cluster analysis on anonymized data along \n  with customized activation functions for Tensorflow\/Pytorch. Stay tuned!<\/p>\n<ul>\n<li>\n<p>General discussion of aspects of machine learning principles as applied to medical data. \n  For example, what are the principles and pitfalls of doing machine learning \n  on private data.<\/p>\n<\/li>\n<li>\n<p>Implementation methods for deploying high-quality, reliable, Data Science products. \n  For example, how do you scale and deploy Data Science products derived from \n  private data sources.<\/p>\n<\/li>\n<\/ul>","category":[{"@attributes":{"term":"Machine Learning"}},{"@attributes":{"term":"Machine Learning"}},{"@attributes":{"term":"Deep Learning"}}]},{"title":"Serverless HIPAA Implementation Series: Part 1 Introduction and Authentication Flow","link":{"@attributes":{"href":"https:\/\/WestHealth.github.io\/serverless-hipaa-implementation-series-part-1-introduction-and-authentication-flow.html","rel":"alternate"}},"published":"2019-10-23T10:37:00-07:00","updated":"2019-10-23T10:37:00-07:00","author":{"name":"Michael Scherer"},"id":"tag:westhealth.github.io,2019-10-23:\/serverless-hipaa-implementation-series-part-1-introduction-and-authentication-flow.html","summary":"<p>These posts reveal serverless methods for designing and testing our internal\nsystems, as I iterated over different configurations and components.  AWS\nprovided the initial JavaScript-based design for API with authentication but I\nupdated it for Python. I only used HIPAA eligible services because of \nour sensitive private data sources.<\/p>\n<h2>How \u2026<\/h2>","content":"<p>These posts reveal serverless methods for designing and testing our internal\nsystems, as I iterated over different configurations and components.  AWS\nprovided the initial JavaScript-based design for API with authentication but I\nupdated it for Python. I only used HIPAA eligible services because of \nour sensitive private data sources.<\/p>\n<h2>How is Authentication handled?<\/h2>\n<p><span><img class=\"image-fit-container\"  src=\"\/images\/customAuthorizations.png\"\/><\/span><\/p>\n<h3>SAML tokens<\/h3>\n<p>We use OKTA organizationally for our third party authentication, which is\nrelatively inexpensive for us, as a non-profit. OKTA provides a central\nlocation to authenticate users and determine their attributes.  AWS Cognito\ndoes something similar but with fewer authentication methods. When using OKTA\nyou have two options for authentication: OAUTH and SAML. We picked SAML because\nwe have used it on other systems and it facilitates encrypting and signing the\npayload with a private key. This did make a little more\ndifficult as usually OAUTH is a little more popular and has more authentication \nlibraries. <\/p>\n<h3>Trading a SAML token for a JWT Token<\/h3>\n<p>One issue is that SAML can take time to calculate and validate, especially if\nyou have to decrypt it every time. More importantly, it may create a security\nrisk to store the SAML token in the browser to cache the user's session. Thus,\nwe used an intermediate API end-point to trade the SAML token for a JWT token\nfor use over a limited time. We used a JWT signed with a private key and cached\nin a database for the lifetime of the token. This technique has two primary\nconsequences:<\/p>\n<ul>\n<li>You need the private key to sign the token.<\/li>\n<li>Users who authenticated with a valid key that is <em>not<\/em> in the database are denied.<\/li>\n<\/ul>\n<p>One key advantage of the cache database is that we can control the user\nauthentication in the database itself which makes it harder for an attacker to\nspoof or steal the signing key.  The authorizer checks this key against the\ncache and allows the user only if it is valid. <\/p>\n<h3>API Gateway Custom Authorizer<\/h3>\n<p><span><img class=\"image-fit-container\"  src=\"\/images\/custom-auth-workflow.png\"\/><\/span>\nhttps:\/\/docs.aws.amazon.com\/apigateway\/latest\/developerguide\/apigateway-use-lambda-authorizer.html<\/p>\n<p>Once we have the authentication established we can use the AWS API Gateway\ncustom Lambda authorizer to authenticate users against the endpoints. The\nclient performs the authentication via OKTA to get a SAML token, and then\nredirects the POST response to the <code>\/SAML<\/code> endpoint, which then authenticates the\ntoken returning a JWT.  The JWT is then used through the API Gateway authorizer\nto establish a policy for which endpoints the user has access to. The\nauthorizer is tied to every lambda except the SAML endpoint. This means the\nroute lambda does not need to know how to handle authentication.<\/p>\n<p>The next issue is to determine which endpoints the user can access.\nBecause a single authorizer is tied to multiple endpoints, it is\ncalled for each of the different endpoints.  If you had a different authorizer\nper endpoint though that authorizer is called for that endpoint and the \ncache is kept per endpoint. <\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"p\">{<\/span>\n    <span class=\"nt\">&quot;principalId&quot;<\/span><span class=\"p\">:<\/span> <span class=\"s2\">&quot;This should be the username or ID of the user accessing the endpoint&quot;<\/span><span class=\"p\">,<\/span>\n    <span class=\"nt\">&quot;policyDocument&quot;<\/span><span class=\"p\">:<\/span> <span class=\"p\">{<\/span>\n        <span class=\"nt\">&quot;Version&quot;<\/span><span class=\"p\">:<\/span> <span class=\"s2\">&quot;2012-10-17&quot;<\/span><span class=\"p\">,<\/span>\n        <span class=\"nt\">&quot;Statement&quot;<\/span><span class=\"p\">:<\/span> \n            <span class=\"p\">{<\/span>\n                <span class=\"nt\">&quot;Action&quot;<\/span><span class=\"p\">:<\/span> <span class=\"p\">[<\/span>\n                    <span class=\"s2\">&quot;execute-api:Invoke&quot;<\/span>\n                <span class=\"p\">],<\/span>\n                <span class=\"nt\">&quot;Effect&quot;<\/span><span class=\"p\">:<\/span> <span class=\"s2\">&quot;Allow&quot;<\/span><span class=\"p\">,<\/span>\n                <span class=\"nt\">&quot;Resource&quot;<\/span><span class=\"p\">:<\/span> <span class=\"p\">[<\/span>\n                    <span class=\"s2\">&quot;\/full\/api\/endpoint\/end&quot;<\/span>\n                <span class=\"p\">]<\/span>\n            <span class=\"p\">}<\/span>\n    <span class=\"p\">}<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<h3>API Gateway resource policy<\/h3>\n<p>The API Gateway resource policy can be added to your API Gateway to allow\nadditional security options onto all of that gateway's resources. It could be\nthings like a whitelist or blacklist, but it works weird in specific cases with authorizer\npolicies and you need to be EXTREMELY careful when using the resource policy.<\/p>\n<h4>Authorizer and Resource Policy<\/h4>\n<p><span><img class=\"image-fit-container\"  src=\"\/images\/20191101114610.png\"\/><\/span>\nhttps:\/\/docs.aws.amazon.com\/apigateway\/latest\/developerguide\/apigateway-authorization-flow.html<\/p>\n<p>This table is at the bottom of the page in the link above and represents how the two interacts. This can act a little funky when as it\nis not one overrides the other, it's one interacts with the other. If you are for instance doing a whitelist and allow\nonly from an IP address, and the authorizer only builds a policy that allows the endpoints they are allowed to access, \nbut doesn't explicitly deny the other endpoints, you get in a position where they are allowed into the other endpoint\nsince the whitelist allowed you, but the authorizer didn't allow or deny you. You can fix this by only specifying denies\nin the resource policy or only allow on public endpoints(endpoints without an authorizer) so that anything it \nevaluates will not accidentally allow something. Or by explicitly denying \naccess to the endpoints that they are not allowed to access. In our situation we wanted to IP block on one endpoint for \ntesting. So we whitelisted the token redemtion to our IP so there is no way to gain an authentication token \nfor the other endpoints, and there is nothing else in the resource policy that could accept a user. <\/p>","category":[{"@attributes":{"term":"Architecture"}},{"@attributes":{"term":"HIPAA"}},{"@attributes":{"term":"Serverless"}},{"@attributes":{"term":"Implementation"}}]},{"title":"Network","link":{"@attributes":{"href":"https:\/\/WestHealth.github.io\/network.html","rel":"alternate"}},"published":"2019-07-30T08:28:00-07:00","updated":"2019-07-30T20:14:00-07:00","author":{"name":"Giancarlo Perrone"},"id":"tag:westhealth.github.io,2019-07-30:\/network.html","summary":"Pyvis demo","content":"\n<div>\n<div id=\"mynetwork\"><\/div>\n<link rel=\"stylesheet\" href=\"https:\/\/cdnjs.cloudflare.com\/ajax\/libs\/vis\/4.16.1\/vis.css\" type=\"text\/css\" \/>\n<script type=\"text\/javascript\" src=\"https:\/\/cdnjs.cloudflare.com\/ajax\/libs\/vis\/4.16.1\/vis-network.min.js\"> <\/script>\n<style type=\"text\/css\">\n\n        #mynetwork {\n            width: 500px;\n            height: 500px;\n            background-color: #ffffff;\n            border: 1px solid lightgray;\n            position: relative;\n        }\n     \n<\/style>\n<script type=\"text\/javascript\">\n\n    \/\/ initialize global variables.\n    var edges;\n    var nodes;\n    var network; \n    var container;\n    var options, data;\n\n    \n    \/\/ This method is responsible for drawing the graph, returns the drawn network\n    function drawGraph() {\n        var container = document.getElementById('mynetwork');\n        \n        \n\n        \/\/ parsing and collecting nodes and edges from the python\n        nodes = new vis.DataSet([{\"id\": \"Acciaiuoli\", \"label\": \"Acciaiuoli\", \"shape\": \"dot\", \"title\": \"Acciaiuoli\"}, {\"id\": \"Medici\", \"label\": \"Medici\", \"shape\": \"dot\", \"title\": \"Medici\"}, {\"id\": \"Barbadori\", \"label\": \"Barbadori\", \"shape\": \"dot\", \"title\": \"Barbadori\"}, {\"id\": \"Ridolfi\", \"label\": \"Ridolfi\", \"shape\": \"dot\", \"title\": \"Ridolfi\"}, {\"id\": \"Tornabuoni\", \"label\": \"Tornabuoni\", \"shape\": \"dot\", \"title\": \"Tornabuoni\"}, {\"id\": \"Albizzi\", \"label\": \"Albizzi\", \"shape\": \"dot\", \"title\": \"Albizzi\"}, {\"id\": \"Salviati\", \"label\": \"Salviati\", \"shape\": \"dot\", \"title\": \"Salviati\"}, {\"id\": \"Castellani\", \"label\": \"Castellani\", \"shape\": \"dot\", \"title\": \"Castellani\"}, {\"id\": \"Peruzzi\", \"label\": \"Peruzzi\", \"shape\": \"dot\", \"title\": \"Peruzzi\"}, {\"id\": \"Strozzi\", \"label\": \"Strozzi\", \"shape\": \"dot\", \"title\": \"Strozzi\"}, {\"id\": \"Bischeri\", \"label\": \"Bischeri\", \"shape\": \"dot\", \"title\": \"Bischeri\"}, {\"id\": \"Guadagni\", \"label\": \"Guadagni\", \"shape\": \"dot\", \"title\": \"Guadagni\"}, {\"id\": \"Ginori\", \"label\": \"Ginori\", \"shape\": \"dot\", \"title\": \"Ginori\"}, {\"id\": \"Pazzi\", \"label\": \"Pazzi\", \"shape\": \"dot\", \"title\": \"Pazzi\"}, {\"id\": \"Lamberteschi\", \"label\": \"Lamberteschi\", \"shape\": \"dot\", \"title\": \"Lamberteschi\"}]);\n        edges = new vis.DataSet([{\"from\": \"Acciaiuoli\", \"to\": \"Medici\"}, {\"from\": \"Medici\", \"to\": \"Barbadori\"}, {\"from\": \"Medici\", \"to\": \"Ridolfi\"}, {\"from\": \"Medici\", \"to\": \"Tornabuoni\"}, {\"from\": \"Medici\", \"to\": \"Albizzi\"}, {\"from\": \"Medici\", \"to\": \"Salviati\"}, {\"from\": \"Castellani\", \"to\": \"Peruzzi\"}, {\"from\": \"Castellani\", \"to\": \"Strozzi\"}, {\"from\": \"Castellani\", \"to\": \"Barbadori\"}, {\"from\": \"Peruzzi\", \"to\": \"Strozzi\"}, {\"from\": \"Peruzzi\", \"to\": \"Bischeri\"}, {\"from\": \"Strozzi\", \"to\": \"Ridolfi\"}, {\"from\": \"Strozzi\", \"to\": \"Bischeri\"}, {\"from\": \"Ridolfi\", \"to\": \"Tornabuoni\"}, {\"from\": \"Tornabuoni\", \"to\": \"Guadagni\"}, {\"from\": \"Albizzi\", \"to\": \"Ginori\"}, {\"from\": \"Albizzi\", \"to\": \"Guadagni\"}, {\"from\": \"Salviati\", \"to\": \"Pazzi\"}, {\"from\": \"Bischeri\", \"to\": \"Guadagni\"}, {\"from\": \"Guadagni\", \"to\": \"Lamberteschi\"}]);\n\n        \/\/ adding nodes and edges to the graph\n        data = {nodes: nodes, edges: edges};\n\n        var options = {\"nodes\": {\"borderWidth\": 4, \"color\": {\"background\": \"rgba(252,39,99,1)\", \"highlight\": {\"border\": \"rgba(129,11,233,1)\"}}}};\n        \n        \n\n        \n\n        network = new vis.Network(container, data, options);\n\n        \n\n\n        \n\n        return network;\n\n    }\n\n    drawGraph();\n\n<\/script>\n<\/div>\n<\/br>\n","category":[{"@attributes":{"term":"Network"}},{"@attributes":{"term":"Graphics"}},{"@attributes":{"term":"Network"}}]},{"title":"Elder Poverty Graphic","link":{"@attributes":{"href":"https:\/\/WestHealth.github.io\/elder-poverty-graphic.html","rel":"alternate"}},"published":"2019-05-22T10:37:00-07:00","updated":"2019-05-22T10:37:00-07:00","author":{"name":"Michael Scherer"},"id":"tag:westhealth.github.io,2019-05-22:\/elder-poverty-graphic.html","content":"<h1>Elder Poverty Graphic<\/h1>\n<p><link rel=\"stylesheet\" href=\"https:\/\/cdn.pydata.org\/bokeh\/release\/bokeh-0.12.2.min.css\" type=\"text\/css\" \/>\n<link rel=\"stylesheet\" href=\"https:\/\/cdn.pydata.org\/bokeh\/release\/bokeh-widgets-0.12.2.min.css\" type=\"text\/css\" \/>\n<link rel=\"stylesheet\" href=\"https:\/\/webmedia.whidsc.net\/Poverty\/ion\/css\/ion.rangeSlider.css\" type=\"text\/css\" \/>\n<link rel=\"stylesheet\" href=\"https:\/\/webmedia.whidsc.net\/Poverty\/ion\/css\/ion.rangeSlider.skinFlat.css\" type=\"text\/css\" \/>\n<link rel=\"stylesheet\" href=\"https:\/\/webmedia.whidsc.net\/Poverty\/national-4.css\" type=\"text\/css\" \/><\/p>\n<div class=\"national\">\n<div class=\"bk-root\">\n<div class=\"plotdiv\" id=\"d18c8a44-80e8-4e34-b4d4-8e8b7774e824\"><\/div>\n<\/div>\n<\/div>\n<script type=\"text\/javascript\" src=\"https:\/\/cdn.pydata.org\/bokeh\/release\/bokeh-0.12.2.min.js\"><\/script>\n<script type=\"text\/javascript\" src=\"https:\/\/cdn.pydata.org\/bokeh\/release\/bokeh-widgets-0.12.2.min.js\"><\/script>\n<script type=\"text\/javascript\" src=\"https:\/\/cdn.pydata.org\/bokeh\/release\/bokeh-compiler-0.12.2.min.js\"><\/script>\n<script type=\"text\/javascript\" src=\"https:\/\/webmedia.whidsc.net\/Poverty\/ion\/js\/bokeh-jquery-shim.js\"><\/script>\n<script type=\"text\/javascript\" src=\"https:\/\/webmedia.whidsc.net\/Poverty\/ion\/js\/ion.rangeSlider.min.js\"><\/script>\n<script type=\"text\/javascript\" src=\"https:\/\/webmedia.whidsc.net\/Poverty\/national-4.js\"><\/script>\n\n<p>This was a graphic that we created for the WestHealth main website. <\/p>","category":{"@attributes":{"term":"Post"}}}]}