1
2023-02-16T13:06:06: AttributeError: partially initialized module
'numpy' has no attribute 'ndarray' (most likely due to a circular import)

This error occurred while I was using dash app to plot some real-time charts. The specific line it refers to is:

go.Scatter( mode = 'lines',line = dict(dash = 'longdash'),x=xData,

Here 'go' refers to plotly.graph_objs.

The result of this error is that while the page is open, all I can see is a blank space with no charts on it.

The complete error is below:

 Traceback (most recent call last):
   File "/root/mudraksh-tools-v1/venv/lib/python3.8/site-packages/flask/app.py", line 2525, in wsgi_app
     response = self.full_dispatch_request()
   File "/root/mudraksh-tools-v1/venv/lib/python3.8/site-packages/flask/app.py", line 1822, in full_dispatch_request
     rv = self.handle_user_exception(e)
   File "/root/mudraksh-tools-v1/venv/lib/python3.8/site-packages/flask/app.py", line 1820, in full_dispatch_request
     rv = self.dispatch_request()
   File "/root/mudraksh-tools-v1/venv/lib/python3.8/site-packages/flask/app.py", line 1796, in dispatch_request
     return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)
   File "/root/mudraksh-tools-v1/venv/lib/python3.8/site-packages/dash/dash.py", line 1274, in dispatch
     ctx.run(
   File "/root/mudraksh-tools-v1/venv/lib/python3.8/site-packages/dash/_callback.py", line 440, in add_context
     output_value = func(*func_args, **func_kwargs)  # %% callback invoked %%
   File "/root/mudraksh-tools-v1/ToolsServer.py", line 103, in update_graph_scatter
     go.Scatter(mode ="lines",
   File "/root/mudraksh-tools-v1/venv/lib/python3.8/site-packages/plotly/graph_objs/_scatter.py", line 3354, in __init__
     self["x"] = _v
   File "/root/mudraksh-tools-v1/venv/lib/python3.8/site-packages/plotly/basedatatypes.py", line 4859, in __setitem__
     self._set_prop(prop, value)
   File "/root/mudraksh-tools-v1/venv/lib/python3.8/site-packages/plotly/basedatatypes.py", line 5198, in _set_prop
     val = validator.validate_coerce(val)
   File "/root/mudraksh-tools-v1/venv/lib/python3.8/site-packages/_plotly_utils/basevalidators.py", line 399, in validate_co
     elif is_homogeneous_array(v):
   File "/root/mudraksh-tools-v1/venv/lib/python3.8/site-packages/_plotly_utils/basevalidators.py", line 186, in is_homogene
     and isinstance(v, np.ndarray)
 AttributeError: partially initialized module 'numpy' has no attribute 'ndarray' (most likely due to a circular import)

I tried to refresh the code, I even rebooted the VMNode but I have no clue what's going on here. This particular program was running successfully for months with no changes done to it but suddenly today it just stops plotting and throws this error. I saw some similar questions answered, but the name of my program was dashToolsServer. I even changed it to ToolsServer. I have not imported numpy explicitly in the code though I think it is being used by plotly.

Edit: This is the complete code :

import dash
from dash import html,dcc
from dash.dependencies import Output, Input
import plotly
import random
import plotly.graph_objs as go
# from collections import deque
import datetime
from plotly.subplots import make_subplots
from pymongo import MongoClient
# from time import ctime
import time
from math import ceil
from configparser import ConfigParser
from waitress import serve

todays_date = str(datetime.datetime.today().date())

config = ConfigParser()
configfile = 'config.ini'
config.read(configfile)

try: 
    host = config['server']['host']
    port = int(config['server']['port'])
    mhost = config['mongo']['host']
    mport = int(config['mongo']['port'])
    muser = config['mongo']['user']
    mpass = config['mongo']['pass']
except Exception as e:
    print(f'Error in taking config values: {e}')


app = dash.Dash(__name__)

conn = MongoClient(host=mhost,port=mport,username=muser,password=mpass)

db = conn['GraphData']
collec = db[todays_date]

 
app = dash.Dash(__name__,title='IV Graphs',update_title='Plotting...') 
app.layout = html.Div( 
    [ 
        html.Div(children=html.Div(id='live-graph'), className='row'),
        dcc.Interval( 
            id = 'graph-update', 
            interval = 5000, 
            n_intervals = 0
        ), 
    ] 
) 

@app.callback( 
    Output('live-graph', 'children'), 
    [ Input('graph-update', 'n_intervals') ] 
) 

def update_graph_scatter(n): 
    colLimit = 2
    plotData = list(collec.find())#{'$and':[{'title':{'$ne':'AD BN'}},{'title':{'$ne':'AD N'}}]}))
    # print(plotData)
    titleList = []
    reqOrder = ['AD N','AD BN','NIFTY CALL WEEKLY IV', 'BANKNIFTY CALL WEEKLY IV',
                'NIFTY PUT WEEKLY IV', 'BANKNIFTY PUT WEEKLY IV',
                'NIFTY CALL MONTHLY IV', 'BANKNIFTY CALL MONTHLY IV',
                'NIFTY PUT MONTHLY IV', 'BANKNIFTY PUT MONTHLY IV', 'PCR CURRENT N',
                'PCR CURRENT BN','PCR NEXT N','PCR NEXT BN']


    for titleData in reqOrder:
        for dbData in plotData:
            if dbData['title'] == titleData:
                if titleData == 'AD BN' or titleData == 'AD N':
                    titleList.append(f"{dbData['title']}: {dbData['ratio']}  UP: {dbData['up']}  DOWN: {dbData['down']}")
                    break
                else:      
                    titleList.append(dbData['title'] + ": "+ str(round(float(dbData['yaxis'][-1]),2)))
    print(titleList)
    fig = make_subplots(rows=ceil(len(reqOrder)/colLimit), cols=colLimit,
                        subplot_titles=tuple(titleList), 
                        )

    colNum = 1
    rowNum = 1
    graphs = []
    LAYOUT = {
          'plot_bgcolor': 'white',
          'paper_bgcolor': 'white'
          }

    fig['layout'].update(LAYOUT)
    for algo in reqOrder:
        for dbData in plotData:
            if dbData['title'] == algo:
                xData = convertTimeStamps(dbData['xaxis'])
                yData = convertToFloat(dbData['yaxis'])
                if colNum>colLimit:
                    colNum = 1
                    rowNum+=1 
                # print([0 for i in plotData[dbData].keys()])   
                fig.add_trace(
                    go.Scatter(mode ="lines",
                                x=xData, y=yData),
                                row=rowNum, col=colNum
                                
                    )
                
                if dbData['title'] == 'AD BN' or dbData['title'] == 'AD N':
                    # fig.add_hline(y=0)
                    fig.add_trace(
                        go.Scatter( mode = 'lines',line = dict(dash = 'longdash'),x=xData,
                                    y=[0 for i in xData]),
                                    row=rowNum, col=colNum
                        )
                    fig.add_trace(
                        go.Scatter( mode = 'lines',line = dict(dash = 'longdash'),x=xData,
                                    y=[0 for i in xData]),
                                    row=rowNum, col=colNum
                        )
                    fig.add_trace(
                        go.Scatter( mode = 'lines',line = dict(dash = 'longdash'),x=xData,
                                    y=[2 for i in xData]),
                                    row=rowNum, col=colNum
                        )
                    fig.add_trace(
                        go.Scatter( mode = 'lines',line = dict(dash = 'longdash'),x=xData,
                                    y=[0.5 for i in xData]),
                                    row=rowNum, col=colNum
                        )
                colNum+=1
                # break
    fig.update_layout(
                        autosize = True
                    )

    print(fig)
    graphs.append(html.Div(style={
        'display': 'flex',
        'flex-flow': 'column',
        'background-color': 'green',
        'height': '200vh',
        'width': '100%'
    },children = [  dcc.Graph(
                        id='basic-interactions',
                        figure=fig,
                        style={'height': '100%'}
                    )]))
    
    return graphs

def convertTimeStamps(epochList):
    ans = []
    for timeStamp in epochList:
        ans.append(datetime.datetime.fromtimestamp(timeStamp))
    return ans

def convertToFloat(data):
    ans = []
    for p in data:
        ans.append(float(p))
    return ans

if __name__ == '__main__':
    app.run_server(host=host, port=port,debug = False)


7
  • Could you please add all your code because I am suspecting that you have an import problem? Commented Feb 16, 2023 at 8:06
  • Has your problem solved with the suggested link? Commented Feb 16, 2023 at 8:17
  • @Hamzah As you can see, im not importing numpy Commented Feb 16, 2023 at 8:46
  • This is your problem, you should import numpy at the first line before importing plotly, give it a try and tell me if that solves your problem. Commented Feb 16, 2023 at 8:48
  • 1
    @Hamzah I tried your suggestion, now the error has disappeared but I still cant see the charts rendering on the frontend. Do you have any suggestions as to what might be the issue ? Commented Feb 16, 2023 at 8:53

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.