I'm unable to run this code. When I run this it gives me an error which, from what I understand it means that it is unable to import cvxopt.base module.
If there is anyone who has encountered this error or knows the solution to this problem, please reach out.
I'm sharing the code & trace of Python interface below:
The Code:
#!/usr/bin/env python
import numpy as np
from numpy import linalg
from cvxopt import solvers
def Twin_plane_1(R,S,C1,Epsi1,regulz1):
StS = np.dot(S.T,S)
# for regularization we add identity matrix with wt. before inversion
StS = StS + regulz1*(np.identity(StS.shape[0]))
StSRt = linalg.solve(StS,R.T)
RtStSRt = np.dot(R,StSRt)
RtStSRt = (RtStSRt+(RtStSRt.T))/2
m2 = R.shape[0]
e2 = -np.ones((m2,1))
solvers.options['show_progress'] = False
vlb = np.zeros((m2,1))
vub = C1*(np.ones((m2,1)))
# x<=vub
# x>=vlb -> -x<=-vlb
# cdx<=vcd
cd = np.vstack((np.identity(m2),-np.identity(m2)))
vcd = np.vstack((vub,-vlb))
alpha = solvers.qp(matrix(RtStSRt,tc='d'),matrix(e2,tc='d'),matrix(cd,tc='d'),matrix(vcd,tc='d'))#,matrix(0.0,(1,m1)),matrix(0.0))#,None,matrix(x0))
alphasol = np.array(alpha['x'])
z = -np.dot(StSRt,alphasol)
w1 = z[:len(z)-1]
b1 = z[len(z)-1]
return [w1,b1]
The Trace:
Traceback (most recent call last): File
"C:\Users\sau\Downloads\Twin-SVM-master\Twin-SVM-master\TwinPlane1.py",
line 6, in
from cvxopt import solvers File "C:\Python35\lib\site-packages\cvxopt__init__.py", line 50, in
import cvxopt.base ImportError: DLL load failed: The specified module could not be found.
I was having the same issue...try this:
import os
os.environ['PATH'] += r';C:\\Users\\user\\AppData\\Local\\Continuum\\anaconda3\\Library\\mingw-
w64\\bin'
Related
I am trying to use python gdal to process a grib2 file into a geotiff file based on the following example:
https://geoexamples.com/d3-raster-tools-docs/code_samples/vardah.html
based on this I have the following code:
import gdal
import osr
ds = gdal.Open(r"/home/test/gfs.t12z.sfluxgrbf000.grib2",1)
gph = ds.GetRasterBand(84).ReadAsArray()
press = ds.GetRasterBand(54).ReadAsArray() / 100
temp = ds.GetRasterBand(52).ReadAsArray()
u = ds.GetRasterBand(50).ReadAsArray()
v = ds.GetRasterBand(51).ReadAsArray()
corr_press = press * (1 - (0.0065*gph/(0.0065*gph + temp + 273.15)))**-5.257
driver = gdal.GetDriverByName('GTiff')
outRaster = driver.Create("/home/test/vardah2.tiff", ds.RasterXSize, ds.RasterYSize, 4, gdal.GDT_Float32)
outRaster.SetGeoTransform(ds.GetGeoTransform())
outband = outRaster.GetRasterBand(1)
outband.WriteArray(corr_press)
outband.SetMetadata({'name': 'press'})
outRasterSRS = osr.SpatialReference()
outRasterSRS.ImportFromEPSG(4326)
outRaster.SetProjection(outRasterSRS.ExportToWkt())
outband.FlushCache()
I am attempting to do this on centos 7 and when I run the program I get the following error:
ERROR 6: The GRIB driver does not support update access to existing datasets.
Traceback (most recent call last):
File "ficky.py", line 4, in <module>
gph = ds.GetRasterBand(84).ReadAsArray()
AttributeError: 'NoneType' object has no attribute 'GetRasterBand'
How do I resolve this error to get a successful run of this script on a centos interface?
Change
ds = gdal.Open(r"/home/test/gfs.t12z.sfluxgrbf000.grib2",1)
to
ds = gdal.Open("/home/test/gfs.t12z.sfluxgrbf000.grib2")
or even better
ds = gdal.Open("/home/test/gfs.t12z.sfluxgrbf000.grib2", GA_ReadOnly)
Environment
{'qiskit-terra': '0.21.1', 'qiskit-aer': '0.10.4', 'qiskit-ignis': None, 'qiskit-ibmq-provider': '0.19.2', 'qiskit': '0.37.1', 'qiskit-nature': '0.4.2', 'qiskit-finance': '0.3.3', 'qiskit-optimization': '0.4.0', 'qiskit-machine-learning': '0.4.0'}
Python 3.8
IBM Quantum Lab and MacOS
What is happening?
When I try to send a pulse schedule to IBMQ Jakarta in IBM Quantum Lab. I get the following error
Traceback (most recent call last):
Input In [24] in <cell line: 1>
job2.result().get_counts()
File /opt/conda/lib/python3.8/site-packages/qiskit/providers/ibmq/job/ibmqjob.py:290 in result
raise IBMQJobFailureError(
IBMQJobFailureError: 'Unable to retrieve result for job 634c09e4d31ce7a982d82517. Job has failed: Waveform memory exceeds the maximum amount of memory currently available. Error code: 8018.'
How can we reproduce the issue?
import qiskit
qiskit.IBMQ.enable_account("KEY")
qiskit.IBMQ.providers()
backend = ibmq_provider.get_backend("ibmq_jakarta")
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from numpy import pi
qreg_cin = QuantumRegister(1, 'cin')
qreg_a = QuantumRegister(1, 'a')
qreg_b = QuantumRegister(1, 'b')
qreg_cout = QuantumRegister(1, 'cout')
creg_c = ClassicalRegister(2, 'c')
qc = QuantumCircuit(qreg_cin, qreg_a, qreg_b, qreg_cout, creg_c)
# set input states
qc.x(qreg_a[0])
# a = 1
qc.x(qreg_b[0])
# b = 1
# add a to b, storing result in b
qc.cx(qreg_a[0], qreg_b[0])
qc.cx(qreg_a[0], qreg_cin[0])
qc.ccx(qreg_cin[0], qreg_b[0], qreg_a[0])
qc.cx(qreg_a[0], qreg_cout[0])
qc.ccx(qreg_cin[0], qreg_b[0], qreg_a[0])
qc.cx(qreg_a[0], qreg_cin[0])
qc.cx(qreg_cin[0], qreg_b[0])
qc.measure(qreg_b[0], creg_c[0])
qc.measure(qreg_cout[0], creg_c[1])
from qiskit import transpile
transpiled_qc = qiskit.transpile(qc, backend=backend,optimization_level = 3)
pulse_schedule_standard = qiskit.schedule(transpiled_qc, backend)
job2 = qiskit.execute(pulse_schedule_standard, shots=8192, backend=backend)
job2.status()
job2.result().get_counts()
I am running the following script:
# STEP 1: import packages, declare tindexes
import pandas as pd
import yfinance as yf
import datetime as dt
bnpl_tindex = ["APT.AX","Z1P.AX","LFS.AX","SZL.AX","HUM.AX","SPT.AX","OPY.AX","IOU.AX","LBY.AX","DOU.AX"]
target_dates = pd.date_range(start=dt.date.today() - dt.timedelta(days=365), end=dt.date.today(), freq="M").strftime('%Y-%m-%d')
target_dates = target_dates.append(pd.Index([dt.date.today().strftime('%Y-%m-%d')]))
target_dates.sort_values()
#STEP 2: source functions
from collect_index_data import collect_index_data
#DELETE LATER... TESTING!
collect_index_data(bnpl_tindex, target_dates)
#
collect_index_data is as follows:
def collect_index_data(ticker_list,date_list):
if (bool(ticker_list) and all(isinstance(elem, str) for elem in ticker_list) )==False:
sys.exit('Input should be a list or a single string.')
else:
print("Components of Index: ")
#initialise dictionary
d = {}
#loop through ticker list
for x in ticker_list:
d["DF.{0}".format(x)] = yf.Ticker(x)
#testing
print(x)
#testing
print(d)
and I get the following error message
Components of Index:
Traceback (most recent call last):
File "C:\Users\thoma\Desktop\Files\Programming\Python\run_tindex_data.py", line 27, in <module>
collect_index_data(bnpl_tindex, target_dates)
File "C:\Users\thoma\Desktop\Files\Programming\Python\collect_index_data.py", line 12, in collect_index_data
d["DF.{0}".format(x)] = yf.Ticker("MSFT")
NameError: name 'yf' is not defined
My question is why is yfinance package not being recognised in my function?
I could import it inside the function, but I plan to run the function multiple times in a script - so this would be computationally wasteful.
thanks!
There is a module in helpers directory called helper_a.py.
It has all classes and functions defined here.
Now I want to call a function from here into another module (not in helpers directory) but one step (cd ..) behind. (init.py) is in helpers directory.
Code and error is as below :
from helpers.helper_a import *
import pandas as pd
query_train_data = "select * from train;"
df_train_dataset = pd.read_sql(query_train_data, con=engDps1000)
query_test_data = "select * from test;"
df_test_dataset = pd.read_sql(query_test_data, con=engDps1000)
df_train_data = df_train_dataset
df_test_data = df_test_dataset
data_prep_steps() # This function is defined in helpers_a
Error:
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-12-3c88b46f341a> in <module>
----> 1 data_prep_steps()
~\Desktop\Notebooks\helpers\helper_a.py in data_prep_steps()
---> 89 # STEP 1 : CONVERT REQUIRED COLS TO CATEGORIES
90 for df_name in [df_train_data, df_test_data]:
91 data_prep_class = data_prep(df_name)
NameError: name 'df_train_data' is not defined
Question is that the variable df_train data is defined in the current module and i want to use it in the function defined in helpers_a by calling it also in the current module, but why is it not recognizing this variable??
Note : Also tried assigning global variable status but it still doesnt solve the issue
There is a solution to create non existing attributes,methods or functions in other modules. It comes from unit testing.
from unittest.mock import patch, PropertyMock
from helpers.helper_a import *
import pandas as pd
query_train_data = "select * from train;"
df_train_dataset = pd.read_sql(query_train_data, con=engDps1000)
query_test_data = "select * from test;"
df_test_dataset = pd.read_sql(query_test_data, con=engDps1000)
df_train_data = df_train_dataset
df_test_data = df_test_dataset
with patch('helpers.helper_a.df_test_data',create=True,new_callable=PropertyMock) as df_test_data_mock: #Create tells to create attribute if it does not exist
with patch('helpers.helper_a.df_train_data', create=True, new_callable=PropertyMock) as df_train_data_mock: # PropertyMock is used to mock properties
df_test_data_mock.return_value = df_test_data
df_train_data_mock.return_value = df_train_data
data_prep_steps() # This function is defined in helpers_a
Although I agree with comments that passing those values would be way simpler. Also due to python dynamic nature you can just simply set those attributes on the module itself. This method is way simpler but you need to remember to clean up after your done which previous method does for you with context mananger.
import helpers.helper_a
import pandas as pd
query_train_data = "select * from train;"
df_train_dataset = pd.read_sql(query_train_data, con=engDps1000)
query_test_data = "select * from test;"
df_test_dataset = pd.read_sql(query_test_data, con=engDps1000)
helpers.helper_a.df_train_data = df_train_dataset
helpers.helper_a.df_test_data = df_test_dataset
helpers.helper_a.data_prep_steps() # This function is defined in helpers_a
I get the following output from the unit test below:
[[array([[-1.57079633]])]]
[[array([[0.+1.57079633j]])]]
<module 'numpy' from '/usr/local/lib/python2.7/dist-packages/numpy/__init__.pyc'>
E
======================================================================
ERROR: test_TestWECTrain_BasicEnv_SetupAndStepping (__main__.Test_exp)
----------------------------------------------------------------------
Traceback (most recent call last):
File "Test_exp.py", line 34, in test_TestWECTrain_BasicEnv_SetupAndStepping
expsigmatphase = np.exp(tmp)
AttributeError: exp
----------------------------------------------------------------------
Ran 1 test in 0.001s
FAILED (errors=1)
Here is the unit test
import unittest
import os
import scipy.io as sio
import numpy as np
from pprint import pprint
class Test_exp (unittest.TestCase):
def test_exp (self):
data_file = "test_buoysimoptions.mat"
buoysimoptions = sio.loadmat (data_file)
t = 0.0
phase = buoysimoptions['SeaParameters']['phase']
sigma = buoysimoptions['SeaParameters']['sigma']
sigmatminusphase = sigma * t - phase; print (sigmatminusphase)
tmp = -1.0j * sigmatminusphase; print (tmp)
print (np)
tmp = np.asarray(tmp)
expsigmatphase = np.exp(tmp)
if __name__ == '__main__':
unittest.main()
The input file (2.9kB) can be downloaded here: https://www.dropbox.com/s/psq1gq8xpjivrim/test_buoysimoptions.mat?dl=0
Why do I get the error AttributeError: exp?
Note this is identical to "AttributeError: exp" while using numpy.exp() on an apparently ordinary array but this question was never answered and provides no minimal example like I do.
This is in Python 2.7, In Python 3.5 I get:
[[array([[-1.57079633]])]]
[[array([[0.+1.57079633j]])]]
E
======================================================================
ERROR: test_exp (__main__.Test_exp)
----------------------------------------------------------------------
Traceback (most recent call last):
File "Test_exp.py", line 25, in test_exp
expsigmatphase = np.exp(tmp)
AttributeError: 'numpy.ndarray' object has no attribute 'exp'
----------------------------------------------------------------------
Ran 1 test in 0.002s
FAILED (errors=1)
Edit: some further information on the loaded data
I expected buoysimoptions['SeaParameters']['phase'] to just be a numpy array, but it seems not, see below, which ultimately causes the error
>>> phase = buoysimoptions['SeaParameters']['phase']
>>> phase
array([[array([[1.57079633]])]], dtype=object)
>>> phase = buoysimoptions['SeaParameters']['phase'][0]
>>> phase
array([array([[1.57079633]])], dtype=object)
>>> phase = buoysimoptions['SeaParameters']['phase'][0][0]
>>> phase
array([[1.57079633]])
do I need to index [0][0] always to just get the actual array? What is the right thing to do here? If I use the last one, the exp error goes away.
It turns out the answer is simple, these loaded variables were themselves oringinally matlab structures, and I was omitting the index when retrieving them, the correct thing to do is the following (note the extra [0,0]s when retrieving phase and sigma):
import unittest
import os
import scipy.io as sio
import numpy as np
from pprint import pprint
class Test_exp (unittest.TestCase):
def test_exp (self):
data_file = "test_buoysimoptions.mat"
buoysimoptions = sio.loadmat (data_file)
t = 0.0
phase = buoysimoptions['SeaParameters'][0,0]['phase']
sigma = buoysimoptions['SeaParameters'][0,0]['sigma']
sigmatminusphase = sigma * t - phase; print (sigmatminusphase)
tmp = -1.0j * sigmatminusphase; print (tmp)
print (np)
tmp = np.asarray(tmp)
expsigmatphase = np.exp(tmp)
if __name__ == '__main__':
unittest.main()