dash icon indicating copy to clipboard operation
dash copied to clipboard

Global Variables - Update

Open nyan314sn opened this issue 9 years ago • 5 comments

I have about 50 csv files where each file contains data I want to plot using dash and pandas. There is a dropdown menu to let the user choose which file to plot and various kinds of plot will be displayed using one underlying file.

It is inefficient and takes a lot of time to read all the files ( about 5 GB) into memory at the beginning of the Dash application.

Here is the summary of what I got so far.

def prepare_chart_type_1(df):
    """
    return plotly figure of chart type 1
    """
    return F
   
def prepare_chart_type_2(df):
    """
    return plotly figure of Chart type 2
    """
    return F    
    
@app.callback(
    dash.dependencies.Output('plot-1', 'figure'),
    [dash.dependencies.Input('dropdown-menu-1', 'value') ])
def create_chart_1( var):   
    
    df=pd.read_csv( var)  
    return prepare_chart_type_1(df)
        
@app.callback(
    dash.dependencies.Output('plot-2', 'figure'),
    [dash.dependencies.Input('dropdown-menu-1', 'value') ])
def create_chart_1( var):   
    
    df=pd.read_csv( var)  
    return prepare_chart_type_2(df)

This is not efficient since I am reading the same csv file two times. Ideally, I like to read csv file one time and the resulting dataframe will be used at each callback.

How can I accomplish this ? Thanks.

nyan314sn avatar Aug 30 '17 23:08 nyan314sn

I think this is probably more of a general Python question rather than a Dash specific one, but here's one way I might go about doing this:

from collections import defaultdict
import pandas as pd

class keydefaultdict(defaultdict):
    """Subclasss defaultdict such that the default_factory method called for missing                                                                                          
    keys takes a single parameter https://stackoverflow.com/a/2912455/77533                                                                                                   
    """
    def __missing__(self, key):
        if self.default_factory is None:
            raise KeyError(key)
        else:
            ret = self[key] = self.default_factory(key)
            return ret


FILE_MAP = {
    'name1': 'file1.csv',
    'name2': 'file2.csv',
    'name3': 'file3.csv',
    #....                                                                                                                                                                     
}

DATA_FRAMES = keydefaultdict(lambda name: pd.read_csv(FILE_MAP[name]))

@app.callback(
    dash.dependencies.Output('plot-2', 'figure'),
    [dash.dependencies.Input('dropdown-menu-1', 'value') ])
def create_chart_1(name):
    df = DATA_FRAMES[name]
    return prepare_chart_type_2(df)

The idea is that you define your map of CSV identifiers (as used in the input elements) to corresponding path names of the CSV files in global FILE_MAP and you use the DATA_FRAMES global variable as your cache of loaded Pandas DataFrames. When you look up a file name in DATA_FRAM, if it hasn't been looked up before only then will it load a new Pandas data frame, otherwise it returns the existing DataFrame for that key. (We need to subclass defaultdict because the method that it invokes to create a new object when a key lookup fails takes no arguments, so we override it to take a single argument, the key whose look up failed.) The result is that your CSV files are only ever loaded when they are needed, and they persist across callback requests within the global variable DATA_FRAMES.

If you're trying to improve load times, I would also recommend storing your data using Feather, which uses the Apache Arrow binary columnar storage format. Pandas makes it super easy to convert to and read this format (eg DataFrame.to_feather()) essentially giving you a free speedup for load times.

ned2 avatar Sep 04 '17 06:09 ned2

@ned2 First of all, Thank you for taking the time to provide such an elegant answer. My python knowledge is definitely limited.

In your example, DATA_FRAMES object has "default_factory" function that reads the csv file, given a file name, we should never get the KeyError from if self.default_factory is None: raise KeyError(key) . If anything, we will get an "file_name" does not exist from "pd.read_csv." Am I correct?

Your solution, I think, is the most efficient one provided that all the csv files fit into DATA_FRAMES object.

In the worst case scenario that the user would go through all the csv files. Won't this solution break down if the total size of csv files is 20 GB and the ram of the computer is like 12 GB ?

nyan314sn avatar Sep 06 '17 16:09 nyan314sn

No worries :)

In your example, DATA_FRAMES object has "default_factory" function that reads the csv file, given a file name, we should never get the KeyError from if self.default_factory is None: raise KeyError(key). If anything, we will get an "file_name" does not exist from "pd.read_csv." Am I correct?

The keydefaultdict class came from a Stackoverflow answer and is intended to be a reusable class one might keep around in their own collection of utilities. You're right that as it's used in my code snippet, the default_factory is never going to be None, therefore a KeyError will never be raised. This is simply guarding against the situation where you instantiated a keydefaultdict with no argument. In this situation, default_factory has the value None and looking up a new key in this situation would then raise a NoneType object is not callable error, when it should raise a KeyError to be consistent with the behaviour of defaultdict.

If you're concerned about memory use, then you might need a slightly more intelligent solution than using a defaultdict. Perhaps the lru_cache decorator from from the functools module, which caches the result of the function it's applied to, might be used:

import functools
import pandas as pd

FILE_MAP = {
    'name1': 'file1.csv',
    'name2': 'file2.csv',
    'name3': 'file3.csv',
    #....                                                                                                                                                                     
}

@functools.lru_cache
def get_csv(name):
    return pd.read_csv(FILE_MAP[name])

I don't know whether that will give you enough control over the cache size, I haven't used it that much. There's other ways to go about caching though.

ned2 avatar Sep 07 '17 02:09 ned2

Combine charts in 1 div:

@app.callback(
    dash.dependencies.Output('plots', 'children'),
    [dash.dependencies.Input('dropdown-menu-1', 'value') ])

def create_charts( var):   
    df=pd.read_csv( var)  
    chart_1 = prepare_chart_type_1(df)
    chart_2 = prepare_chart_type_2(df)
    return html.Div([chart_1, chart_2])

OR, Create intermediate-value and use the same value in both callbacks.

peace899 avatar Sep 26 '17 20:09 peace899

I believe that this is covered by https://github.com/plotly/dash/issues/49#issuecomment-311511286 and the cross-process caching options in https://plot.ly/dash/performance. feel free to reopen or create a new issue if not!

chriddyp avatar Oct 04 '17 03:10 chriddyp