<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def Moran_BV_matrix(variables, w, permutations=0, varnames=None):
 """ Bivariate Moran Matrix Calculates bivariate Moran between all pairs of a set of variables. Parameters variables : array or pandas.DataFrame sequence of variables to be assessed w : W a spatial weights object permutations : int number of permutations varnames : list, optional if variables is an array Strings for variable names. Will add an attribute to `Moran_BV` objects in results needed for plotting in `splot` or `.plot()`. Default =None. Note: If variables is a `pandas.DataFrame` varnames will automatically be generated Returns ------- results : dictionary (i, j) is the key for the pair of variables, values are the Moran_BV objects. Examples -------- open dbf pull of selected variables from dbf and create numpy arrays for each create a contiguity matrix from an external gal file create an instance of Moran_BV_matrix check values 0.1936261 0.3770138 """

    try:
        # check if pandas is installed
        import pandas
        if isinstance(variables, pandas.DataFrame):
            # if yes use variables as df and convert to numpy_array
            varnames = pandas.Index.tolist(variables.columns)
            variables_n = []
            for var in varnames:
                variables_n.append(variables[str(var)].values)
        else:
            variables_n = variables
    except ImportError:
        variables_n = variables
    
    results = _Moran_BV_Matrix_array(variables=variables_n, w=w,
                                     permutations=permutations,
                                     varnames=varnames)
    return results