ASKSAGE: Sage Q&A Forum - RSS feedhttps://ask.sagemath.org/questions/Q&A Forum for SageenCopyright Sage, 2010. Some rights reserved under creative commons license.Tue, 12 Sep 2023 19:12:56 +0200NameError: name '...' is not definedhttps://ask.sagemath.org/question/63697/nameerror-name-is-not-defined/ I got the preparsed with sage --preparse command keflll.py file with the function invertibles() that returns the list of integers. It doesn't use any lambda expressions. I can call it in the code, but as long as I try to call it in parallel i get the error:
NameError: name 'invertibles' is not defined
The code is given below:
from keflll import invertibles
from sage.parallel.multiprocessing_sage import pyprocessing
p_iter = pyprocessing(4)
P = parallel(p_iter=p_iter)
def f(x):
return invertibles(x)
list( P(f)([(2,),(3,)]) )
How can I parallelize calls of the functions that are in custom made module or just depend on those?Alex KareninFri, 19 Aug 2022 12:10:33 +0200https://ask.sagemath.org/question/63697/import astropy in a sage notebook vhttps://ask.sagemath.org/question/73368/import-astropy-in-a-sage-notebook-v/ Hi Sagesse!
I'm wondering if there's an easy way to get a sage notebook (v8.7) to import the module astropy which is found /usr/lib/python3/dist-packages/astropy/ on my linux system.
I am guessing it would require doing an export SAGE_PATH= xxx and then a launch of my notebook as
sage --notebook in the usual fashion .
Right now I have the problem :
---
importError Traceback (most recent call last)
<ipython-input-1-7c3762fa282d> in <module>()
1 JD_ecl = RealNumber('2460059.34')
2 Period = RealNumber('1.195')
----> 3 from astropy.time import Time
4 times = ['1999-01-01T00:00:00.123456789', '2010-01-01T00:00:00']
5 t = Time(times, format='isot', scale='utc')
****ImportError: No module named astropy.time****
---
and when I check my path in the notebook, it references a directories in my sagepath which in fact don't exist at this point.
But maybe I can put a symlink there ....
Example:
---
import sys
print(sys.path)
['', '/home/patricia/SageMath/local/lib/python27.zip', '/home/patricia/SageMath/local/lib/python2.7', '/home/patricia/SageMath/local/lib/python2.7/plat-linux2', '/home/patricia/SageMath/local/lib/python2.7/lib-tk', '/home/patricia/SageMath/local/lib/python2.7/lib-old', '/home/patricia/SageMath/local/lib/python2.7/lib-dynload', '/home/patricia/SageMath/local/lib/python2.7/site-packages', '/home/patricia/SageMath/local/lib/python2.7/site-packages/IPython/extensions', '/home/patricia/.sage/ipython-5.0.0']
---
Qu'en pensez-vous ?
PatBTue, 12 Sep 2023 19:12:56 +0200https://ask.sagemath.org/question/73368/how to import a function in another filehttps://ask.sagemath.org/question/63770/how-to-import-a-function-in-another-file/In python it's easy to find how can I do:
from file import func1, func2, func3
But I couldn't do in jupyter notebook. It didn't read the file.
For example dag is an function in sample_code ;
import ipynb
from ipynb.fs.full.sample_code import dag
---------------------------------------------------------------------------
ModuleNotFoundError Traceback (most recent call last)
<ipython-input-3-cb32ddc8df9f> in <module>
----> 1 import ipynb
2 from ipynb.fs.full.sample_code import dag
ModuleNotFoundError: No module named 'ipynb'
Thanks for advance.SuleThu, 25 Aug 2022 13:26:40 +0200https://ask.sagemath.org/question/63770/import txt file contents to SageMath/Pythonhttps://ask.sagemath.org/question/60268/import-txt-file-contents-to-sagemathpython/I have a text file with contents like the following
[[1, 4], [2, 6], [5, 7]]
[[1, 4], [2, 7], [5, 8]]
I would like to import the contents to SageMath/Python, and assign L=[[[1, 4], [2, 6], [5, 7]], [[1, 4], [2, 7], [5, 8]]].
I tried to use the following
with open('somefile.txt', 'r') as fp:
L = [RDF(l.strip()) for l in fp.readlines()]
But there is some error: could not convert string to float: '[[1, 4], [2, 6], [5, 7]]'
How could I solve this problem? How to convert the values to integer (not float)? Thank you very much.lijr07Wed, 15 Dec 2021 09:40:10 +0100https://ask.sagemath.org/question/60268/I cannot import a python package that I can happily import using the same path within a python file run in IDLE.https://ask.sagemath.org/question/59677/i-cannot-import-a-python-package-that-i-can-happily-import-using-the-same-path-within-a-python-file-run-in-idle/ I am new to SageMath and to PreTeXt that I am using it with. I cannot import a python package that I can happily import using the same path within a python file run in IDLE. If I remove the "import sys ... import ternary" lines the PreTeXt code runs fine and I get the sin curve. The ternary module is Marc Harper's installed from GitHub using pip. But the module is not found when I run with the 3 lines added (so I have not bothered to add code that uses the module yet!). (To keep code to a minimum in the <interactive> ... </interactive> part I would ideally like to be able to import python code). Can anyone put me on the right track please? (PSWith a Karma of 1 I had to remove the links at the top of the code indoor to have the question accepted)
<book xml:id="prog1" xml:lang="en-US">
<title>prog1</title>
<chapter xml:id="my-chapter">
<interactive xml:id="simple-plot" platform="sage" width="100%" aspect="1:1">
<slate surface="sage">
plot(sin,(-5,5))
import sys
sys.path.append("/usr/local/lib/python3.8/site-packages/")
import ternary
</slate>
</interactive>
</chapter>
</book>
</pretext>aubreyWed, 10 Nov 2021 19:25:59 +0100https://ask.sagemath.org/question/59677/Save tensor in filehttps://ask.sagemath.org/question/59632/save-tensor-in-file/I define the following $3+1$ manifold and chart:
n = 3
M = Manifold(1+n, 'M', structure='Lorentzian')
X.<t,r,th,ph> = M.chart(r"t r:(0,+oo) th:(0,pi):\theta ph:(0,2*pi):\phi")
with a variable $eps$ and function $h$:
eps = var('eps')
h = function('h')(r,th)
The metric of this space is:
gdd = M.metric()
gdd[0,0] = -eps; gdd[1,1] = r; gdd[2,2] = h; gdd[3,3] = 1
With this metric, I calculate numerous tensors (Riemann, Ricci, ...), which take a long time to compute. Therefore, I would like to save those tensors in a single file and then import them back every time I need them. I have tried using
> np.save('file.npy', gdd)
but when I open file.npy I read the following:
> Error! /Users/.../file.npy is not UTF-8 encoded
Is there a way I can save various symbolic tensors (which depend on functions and variables, as the one shown above) in a file, and load them back separately?kekoSun, 07 Nov 2021 23:09:57 +0100https://ask.sagemath.org/question/59632/Circular importshttps://ask.sagemath.org/question/58119/circular-imports/Hello,
I'm writing two classes which depend on each other. They are very similar to Integer and Rational, so let's just take that example.
Rationals are constructed using instances of Integer.
But some operations on an Integer return a Rational (such as division).
Currently I have two files: integer.py and rational.py.
At the top of rational.py I do
from integer import Integer, Integers
And within a few specific methods of Integer (e.g. \_div\_()), I do
from rational import Rational
or
from rational import Rationals
This worked fine, but now that I am running the doctests using the SageMath doctesting framework:
./sage -t integer.py
I get errors. I traced these errors back to the following problem.
My parents Integers and Rationals are unique: they inherit from UniqueRepresentation.
When running the tests, two *different* instances of Integers are created. I think this is because I first create such an instance, then I perform for example a division, which imports from rational.py, which in turn imports integer.py, thereby redefining Integers. Hence a newly created instance of Integers is another one than the first one.
This causes my tests to break.
This problem does not arise when I work in the SageMath shell/console.
I read two little paragraphs in the SageMath documentation suggesting that I should do something like the following in the doctests of for example my division function in integer.py:
import __main__
__main__.Integers = Integers
But I got no success with this. Also I do not fully understand what this does.
I tried looking at the actual SageMath library files which implement integers/rational numbers. But there the files seem to me like they import from their C or Cython versions, which I have no experience with and do not use myself.
Does anybody know a clean way to get rid of this problem?MathéMon, 26 Jul 2021 16:31:29 +0200https://ask.sagemath.org/question/58119/Import specific functions in order to reduce the startup timehttps://ask.sagemath.org/question/54632/import-specific-functions-in-order-to-reduce-the-startup-time/# The context
Let's suppose I want to create a simple script which only prints the prime factorization of the number 100. The script would look like
from sage.all import *
print(factor(100))
# The problem
Executing that simple script takes a lot of time because there are plenty of modules that are expoted because of the `from ... import` statemnt.
I tried finding the file in which the function `factor` is defined and importing that specific module.
from sage.arith.misc import factor
print(factor(100))
However, this yields the following error.
Traceback (most recent call last):
File "/home/myusername/Experiments/factor-100.py", line 1, in <module>
from sage.arith.misc import factor
File "/usr/lib/python3.9/site-packages/sage/arith/misc.py", line 23, in <module>
from sage.libs.flint.arith import (bernoulli_number as flint_bernoulli,
File "sage/libs/flint/arith.pyx", line 1, in init sage.libs.flint.arith (build/cythonized/sage/libs/flint/arith.c:5015)
File "sage/rings/integer.pyx", line 1, in init sage.rings.integer (build/cythonized/sage/rings/integer.c:54202)
File "sage/rings/rational.pyx", line 95, in init sage.rings.rational (build/cythonized/sage/rings/rational.c:40423)
File "sage/rings/real_mpfr.pyx", line 1, in init sage.rings.real_mpfr (build/cythonized/sage/rings/real_mpfr.c:45462)
File "sage/libs/mpmath/utils.pyx", line 1, in init sage.libs.mpmath.utils (build/cythonized/sage/libs/mpmath/utils.c:9058)
File "sage/rings/complex_number.pyx", line 1, in init sage.rings.complex_number (build/cythonized/sage/rings/complex_number.c:26879)
File "sage/rings/complex_double.pyx", line 98, in init sage.rings.complex_double (build/cythonized/sage/rings/complex_double.c:25209)
ImportError: cannot import name complex_number
I can fix this problem by adding the following `import` rule.
from sage.misc.all import *
from sage.arith.misc import factor
print(factor(100))
However, this also loads a lot of modules.
# The question
Is it possible to import less modules than the last code block shown?
doltesThu, 10 Dec 2020 20:35:03 +0100https://ask.sagemath.org/question/54632/How to correctly import sage modules from python modehttps://ask.sagemath.org/question/53476/how-to-correctly-import-sage-modules-from-python-mode/I am writing a module for sage, and I want to import some sage objects cleanly, without calling the heavy `import sage.all`. But without it, I often get errors.
$ sage -python
Python 3.7.3 (default, May 21 2020, 07:31:27)
[GCC 9.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from sage.rings.integer import Integer
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "sage/rings/rational.pxd", line 8, in init sage.rings.integer (build/cythonized/sage/rings/integer.c:53202)
File "sage/rings/rational.pyx", line 95, in init sage.rings.rational (build/cythonized/sage/rings/rational.c:39849)
File "sage/rings/real_mpfr.pyx", line 1, in init sage.rings.real_mpfr (build/cythonized/sage/rings/real_mpfr.c:44200)
File "sage/rings/complex_number.pxd", line 6, in init sage.libs.mpmath.utils (build/cythonized/sage/libs/mpmath/utils.c:8637)
File "sage/rings/complex_double.pxd", line 7, in init sage.rings.complex_number (build/cythonized/sage/rings/complex_number.c:24172)
File "sage/rings/complex_double.pyx", line 96, in init sage.rings.complex_double (build/cythonized/sage/rings/complex_double.c:24325)
ImportError: cannot import name complex_number
>>> from sage.all import *
>>> from sage.rings.integer import Integer
>>>
$ sage
┌────────────────────────────────────────────────────────────────────┐
│ SageMath version 9.1, Release Date: 2020-05-20 │
│ Using Python 3.7.3. Type "help()" for help. │
└────────────────────────────────────────────────────────────────────┘
This is just an example.hellmanThu, 17 Sep 2020 09:58:04 +0200https://ask.sagemath.org/question/53476/Breaking code into multiple files on Windowshttps://ask.sagemath.org/question/52884/breaking-code-into-multiple-files-on-windows/In Jupyter on Windows, I create a Notebook "testa.ipynb" as follows:
def f():
return 3
I then create another Notebook "testb.ipynb" as follows:
import testa
testa.f()
Running this produces the error "No module named 'testa'". The files are in the same directory, which is the default "C:\Users\<user>".
How can I break my code into multiple files like this?kabaThu, 06 Aug 2020 02:08:35 +0200https://ask.sagemath.org/question/52884/importing .sage fileshttps://ask.sagemath.org/question/7867/importing-sage-files/What's the recommended approach for importing .sage scripts as a module, i.e. into their own namespace? I have a file with ~10k functions and it'd be much nicer to keep them filed tidily away.
I've written a hack sage_import wrapper which seems to work for my use case, but hopefully there's a better way. DSMThu, 13 Jan 2011 10:19:28 +0100https://ask.sagemath.org/question/7867/Having trouble importing the lazy_laurent_series modulehttps://ask.sagemath.org/question/48608/having-trouble-importing-the-lazy_laurent_series-module/I am trying to import and use lazy Laurent series rings in sage, documented here: (http://doc.sagemath.org/html/en/reference/power_series/sage/rings/lazy_laurent_series_ring.html). I have the latest version of sage installed, and yet when I attempt to import/install the package it is nowhere to be found.
from sage.rings.lazy_laurent_series_ring import LazyLaurentSeriesRing
---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
<ipython-input-1-db0f55e1138b> in <module>()
----> 1 from sage.rings.lazy_laurent_series_ring import LazyLaurentSeriesRing
ImportError: No module named lazy_laurent_series_ring
I then tried to download it, perhaps I am not downloading the correct package? Where is it hiding?
sage -i lazy_laurent_series
Error: package 'lazy_laurent_series' not found
Note: if it is an old-style package, use -p instead of -i to install ittzeentchTue, 05 Nov 2019 00:56:54 +0100https://ask.sagemath.org/question/48608/using cplex as a solver in sage - import error undefined symbol: CPXsetlogfilehttps://ask.sagemath.org/question/46606/using-cplex-as-a-solver-in-sage-import-error-undefined-symbol-cpxsetlogfile/Hi,
Ubuntu 18.04; Installed cplex_studio129.linux-x86-64.bin and then Sage 8.7 from source.
I chose source to allow me to "make" Sage again after linking the necessary CPLEX files as described at the very bottom of the page here:
doc.sagemath.org/html/en/thematic_tutorials/linear_programming
i.e. from
/home/klara/sage-8.7/local/lib
`ln -s /opt/ibm/ILOG/CPLEX_Studio129/cplex/lib/x86-64_linux/static_pic/libcplex.a .`
and from:
/home/klara/sage-8.7/local/include
`ln -s /opt/ibm/ILOG/CPLEX_Studio129/cplex/include/ilcplex/cplex.h .`
and finally, also from:
/home/klara/sage-8.7/local/include
`ln -s /opt/ibm/ILOG/CPLEX_Studio129/cplex/include/ilcplex/cpxconst.h .`
But now I get the following import error when running:
sage: p = MixedIntegerLinearProgram(solver='CPLEX')
ImportError: /home/klara/sage-8.7/local/lib/python2.7/site-packages/sage/numerical/backends/cplex_backend.so: undefined symbol: CPXsetlogfile
(By the way, after installing Sage but before linking and remaking I got the more basic import error:
`ImportError: No module named cplex_backend`)
Any hints as what to look into would be appreciated.
Thanks.
----------
Here is the Full Output of the error:
sage: p = MixedIntegerLinearProgram(solver='CPLEX')
---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
<ipython-input-1-d320ed52392f> in <module>()
----> 1 p = MixedIntegerLinearProgram(solver='CPLEX')
/home/klara/sage-8.7/local/lib/python2.7/site-packages/sage/misc/lazy_import.pyx in sage.misc.lazy_import.LazyImport.__call__ (build/cythonized/sage/misc/lazy_import.c:3690)()
352 True
353 """
--> 354 return self.get_object()(*args, **kwds)
355
356 def __repr__(self):
/home/klara/sage-8.7/local/lib/python2.7/site-packages/sage/numerical/mip.pyx in sage.numerical.mip.MixedIntegerLinearProgram.__init__ (build/cythonized/sage/numerical/mip.c:3931)()
449 self._first_variable_names = list(names)
450 from sage.numerical.backends.generic_backend import get_solver
--> 451 self._backend = get_solver(solver=solver,
452 constraint_generation=constraint_generation,
453 base_ring=base_ring)
/home/klara/sage-8.7/local/lib/python2.7/site-packages/sage/numerical/backends/generic_backend.pyx in sage.numerical.backends.generic_backend.get_solver (build/cythonized/sage/numerical/backends/generic_backend.c:20060)()
1647 raise ValueError("'solver' should be set to 'GLPK', 'Coin', 'CPLEX', 'CVXOPT', 'Gurobi', 'PPL', 'InteractiveLP', or None.")
1648
-> 1649 cpdef GenericBackend get_solver(constraint_generation = False, solver = None, base_ring = None):
1650 """
1651 Return a solver according to the given preferences
/home/klara/sage-8.7/local/lib/python2.7/site-packages/sage/numerical/backends/generic_backend.pyx in sage.numerical.backends.generic_backend.get_solver (build/cythonized/sage/numerical/backends/generic_backend.c:19611)()
1794
1795 elif solver == "Cplex":
-> 1796 from sage.numerical.backends.cplex_backend import CPLEXBackend
1797 return CPLEXBackend()
1798
ImportError: /home/klara/sage-8.7/local/lib/python2.7/site-packages/sage/numerical/backends/cplex_backend.so: undefined symbol: CPXsetlogfilebucks65Tue, 21 May 2019 13:36:42 +0200https://ask.sagemath.org/question/46606/"from __future__ import print_function" fails on Sage scriptshttps://ask.sagemath.org/question/46342/from-__future__-import-print_function-fails-on-sage-scripts/Hello, Sage Community.
I am trying to use the "print" function in a .sage script, so I have added the line
from __future__ import print_function
as the first line to be included in my .sage file. Unfortunately, when running `sage test.sage`, Sage preparses the document and creates an auxiliary file "test.sage.py", which makes an import, then predefines some constants, and finally adds my preparsed code. As a consequence, the `from __future__ import print_function` is not the first line, and I get the following error message:
File "test.sage.py", line 6
from __future__ import print_function
SyntaxError: from __future__ imports must occur at the beginning of the file
Here is a MWE. The file "test.sage" containing:
from __future__ import print_function
print(1+1)
is preparsed to "test.sage.py" containing:
# This file was *autogenerated* from the file test.sage
from sage.all_cmdline import * # import sage library
_sage_const_1 = Integer(1)
from __future__ import print_function
print(_sage_const_1 +_sage_const_1 )
Of course, I could manually add this line to the .sage.py file and then execute it, but this could be tedious in my case for two reasons: 1. I have a lot of files which I have to modify and rerun every 15 minutes. 2. I also need this process to be automatic to be able to execute it with automatically generated script and even sageTeX.
Thanks in advance for your answers!dsejasWed, 24 Apr 2019 19:14:49 +0200https://ask.sagemath.org/question/46342/How to import functions to program?https://ask.sagemath.org/question/44713/how-to-import-functions-to-program/Hello,
Sory for stupid question. Im new to sage and I would like to import a class/base that will allow me to use convergent() and numerator() functions. How could I do that?
I found class sage.rings.continued_fraction.ContinuedFraction_base
Bases: sage.structure.sage_object.SageObject
However when trying something like import, it doesn't work ..
trrrrrrWed, 19 Dec 2018 21:26:09 +0100https://ask.sagemath.org/question/44713/Load module from remote serverhttps://ask.sagemath.org/question/43778/load-module-from-remote-server/Hi, I am using a remote sage notebook public server (such as http://sage.math.canterbury.ac.nz/).
I would like to be able to load my own python modules, but I don't know how can I access local files, such as
import sys
sys.path.append('path-to-file-in-my-local-drive')
import module-name
Is there any way to do that?jllbThu, 27 Sep 2018 10:38:06 +0200https://ask.sagemath.org/question/43778/Importing Sage functions into Cython?https://ask.sagemath.org/question/42277/importing-sage-functions-into-cython/ I am trying to define variables in Cython part of my code like this
a,b,c = var('a,b,c')
But in this line I cant import var() function from Sage
from sage.calculus.var import var
I got this error:
$ sage -python real_sage.sage
Compiling ./real_sage.spyx...
Traceback (most recent call last):
File "real_sage.sage", line 6, in <module>
from real_sage import foo
File "real_sage.pyx", line 10, in init real_sage
File "sage/calculus/var.pyx", line 6, in init sage.calculus.var
File "/home/tunamustafakemal/sega/SageMath/local/lib/python2.7/site-packages/sage/symbolic/function_factory.py", line 15, in <module>
from sage.symbolic.function import SymbolicFunction, sfunctions_funcs, \
File "sage/rings/integer.pxd", line 7, in init sage.symbolic.function
File "sage/rings/rational.pxd", line 8, in init sage.rings.integer
File "sage/rings/rational.pyx", line 89, in init sage.rings.rational
File "sage/rings/real_mpfr.pyx", line 1, in init sage.rings.real_mpfr
File "sage/rings/complex_number.pxd", line 6, in init sage.libs.mpmath.utils
File "sage/rings/complex_double.pxd", line 10, in init sage.rings.complex_number
File "sage/rings/complex_double.pyx", line 94, in init sage.rings.complex_double
ImportError: cannot import name complex_number
Thanks for any support.tunaMon, 07 May 2018 06:14:53 +0200https://ask.sagemath.org/question/42277/Import Sage Worksheetshttps://ask.sagemath.org/question/41924/import-sage-worksheets/ Hello, I'm looking to be able to modulate my code in the Sage Math cloud. I've done some research on the topic and it seems that one could use the `attach` syntax to bring in the methods from another worksheet. Unfortunately I get the following error when I try to attach the sagews 'test' which is in the same folder as the worksheet I'm working in.
`File "/cocalc/lib/python2.7/site-packages/smc_sagews/sage_server.py", line 1013, in execute
exec compile(block+'\n', '', 'single') in namespace, locals
File "", line 1, in <module>
File "/cocalc/lib/python2.7/site-packages/smc_sagews/sage_salvus.py", line 3443, in attach
raise IOError('did not find file %r to attach' % fname)
IOError: did not find file 'test' to attach`
Can anyone help me with this issue?
Thanks,
Adam
ajmullinsMon, 09 Apr 2018 02:24:28 +0200https://ask.sagemath.org/question/41924/Making a collection of functionshttps://ask.sagemath.org/question/40811/making-a-collection-of-functions/I have a somewhat large collection of functions that I wrote myself to make some computations. They are all very much dependent on each other so if I ever want to use some subset of them, say when I'm working in some Jupyter notebook, I have to copy paste the whole bunch of them into a cell and evaluate it. This makes the notebook really bulky and ugly. Is there anyway I can make these functions into a package so that I can just import it in any jupyter notebook that's in the same folder to use those functions?r2d2Sat, 27 Jan 2018 20:25:00 +0100https://ask.sagemath.org/question/40811/Import just one function from .sage filehttps://ask.sagemath.org/question/39906/import-just-one-function-from-sage-file/I have a `.sage` file that has a single function I want to import. If it were a `.py` file, I would obviously use `from temp import myfun`, but as far as I know, `.sage` files have to be imported with either `load('temp.sage')` or `attach('temp.sage')` (or preparsed, but this gets tiresome). Is there a way to import just one function from a `.sage` file?jaebondSat, 02 Dec 2017 07:21:59 +0100https://ask.sagemath.org/question/39906/Error when trying to import without sage.allhttps://ask.sagemath.org/question/40116/error-when-trying-to-import-without-sageall/I am trying to import only the Sage functions needed as is done in the Sage source code, but I am running into issues. For example, (running `sage -python`),
>>> from sage.groups.group import Group
results in
...
from sage.rings.complex_double import CDF
File "sage/rings/real_double.pxd", line 8, in init sage.rings.complex_double (/export/pkgs/linux-rh6/sagemath-7.0/src/build/cythonized/sage/rings/complex_double.c:22654)
File "sage/rings/real_double.pyx", line 64, in init sage.rings.real_double (/export/pkgs/linux-rh6/sagemath-7.0/src/build/cythonized/sage/rings/real_double.c:25060)
ImportError: cannot import name ZZ
(I can post the full traceback if that would be helpful.) Similar things happen for almost any import I try. I was using the `import_statements` to determine what to import.
Am I missing something?
EDIT:
I think I get the picture a little better now. The Sage source files aren't meant to be imported in Python, they are meant to be imported into Sage, which presumably runs `import sage.all` when it starts.jaebondTue, 12 Dec 2017 04:06:39 +0100https://ask.sagemath.org/question/40116/Error importing ZZhttps://ask.sagemath.org/question/35522/error-importing-zz/I'm trying to switch to a more software-development-like approach for one of my projects. To this end I'll be writing several files, and I'll be trying to keep imports to a minimum to speed up module loading.
At first I started with a file `foo.sage` and a `Makefile` which preparses this using `sage -min -preparse foo.sage`. But the resulting `foo.sage.py` still starts with `from sage.all_cmdline import *`. I thought the point of the `-min` switch was to avoid just that. Am I missing something here?
Next I tried to write Python code instead. But there I got problems, apparently because I was loading modules in the wrong order. Take for example a file `foo.py` containing just the line `from sage.rings.integer_ring import ZZ`. My Sage 7.4 on Gentoo will print the following when running said file as `sage foo.py`:
Traceback (most recent call last):
File "foo.py", line 1, in <module>
from sage.rings.integer_ring import ZZ
File "sage/rings/integer.pxd", line 7, in init sage.rings.integer_ring (…/rings/integer_ring.c:14426)
File "sage/rings/rational.pxd", line 8, in init sage.rings.integer (…/rings/integer.c:49048)
File "sage/rings/fast_arith.pxd", line 3, in init sage.rings.rational (…/rings/rational.c:36533)
File "sage/libs/pari/gen.pxd", line 5, in init sage.rings.fast_arith (…/rings/fast_arith.c:8139)
File "sage/libs/pari/gen.pyx", line 91, in init sage.libs.pari.gen (…/libs/pari/gen.c:135191)
File "/usr/lib64/python2.7/site-packages/sage/rings/infinity.py", line 228, in <module>
from sage.rings.integer_ring import ZZ
ImportError: cannot import name ZZ
Is there a way to reasonably import things like this without too much experimentation, and without importing far more than I actually need here?MvGFri, 11 Nov 2016 11:40:15 +0100https://ask.sagemath.org/question/35522/File imports for polynomial rings in sagehttps://ask.sagemath.org/question/7584/file-imports-for-polynomial-rings-in-sage/If i type in the following
R.<z1,z2> = PolynomialRing(GF(5),2,"z")
direclty to Sage it accepts it as a polynomial ring.
But if i place this in a .py file and load it from this Sage
eg `sage my.py` it gives me a syntax error.
I guess i need a module loaded for it to be detected, but which module and hence which command do i need to make Sage accept this ring.aeThu, 19 Aug 2010 11:41:02 +0200https://ask.sagemath.org/question/7584/Importing user SAGE files "pythonically"https://ask.sagemath.org/question/40036/importing-user-sage-files-pythonically/Hello,
I'm wondering if there's a more "pythonic" way in which to import user-written SAGE modules.
For instance, I'm able to load in a SAGE file I've written using the `load` keyword.
load(path_to_sage_file)
That's all well and good, however, as I start to import more and more user SAGE files, where certain functions are coming from becomes less clear. It would be ideal to do something like
from name_of_sage_file import name_of_sage_function
However, this doesn't seem to work. Is there a more "pythonic" way in which to go about doing this? Thanks!Vincent RussoSat, 09 Dec 2017 16:15:19 +0100https://ask.sagemath.org/question/40036/import CSV in python using jupyter notebook on cocalc cloudhttps://ask.sagemath.org/question/38546/import-csv-in-python-using-jupyter-notebook-on-cocalc-cloud/I want to import this [CVS file](https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data) in my python script with the commands:
url = "https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data"
names = ['sepal-length', 'sepal-width', 'petal-length', 'petal-width', 'class']
dataset = pandas.read_csv(url, names=names)
The problem is that it returns this error message:
---------------------------------------------------------------------------
URLError Traceback (most recent call last)
<ipython-input-21-45b1e7974739> in <module>()
32 url = "https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data"
33 names = ['sepal-length', 'sepal-width', 'petal-length', 'petal-width', 'class']
---> 34 dataset = pandas.read_csv(url, names=names)
/projects/sage/sage-7.6/local/lib/python2.7/site-packages/pandas/io/parsers.py in parser_f(filepath_or_buffer, sep, delimiter, header, names, index_col, usecols, squeeze, prefix, mangle_dupe_cols, dtype, engine, converters, true_values, false_values, skipinitialspace, skiprows, nrows, na_values, keep_default_na, na_filter, verbose, skip_blank_lines, parse_dates, infer_datetime_format, keep_date_col, date_parser, dayfirst, iterator, chunksize, compression, thousands, decimal, lineterminator, quotechar, quoting, escapechar, comment, encoding, dialect, tupleize_cols, error_bad_lines, warn_bad_lines, skipfooter, skip_footer, doublequote, delim_whitespace, as_recarray, compact_ints, use_unsigned, low_memory, buffer_lines, memory_map, float_precision)
653 skip_blank_lines=skip_blank_lines)
654
--> 655 return _read(filepath_or_buffer, kwds)
656
657 parser_f.__name__ = name
/projects/sage/sage-7.6/local/lib/python2.7/site-packages/pandas/io/parsers.py in _read(filepath_or_buffer, kwds)
390 compression = _infer_compression(filepath_or_buffer, compression)
391 filepath_or_buffer, _, compression = get_filepath_or_buffer(
--> 392 filepath_or_buffer, encoding, compression)
393 kwds['compression'] = compression
394
/projects/sage/sage-7.6/local/lib/python2.7/site-packages/pandas/io/common.py in get_filepath_or_buffer(filepath_or_buffer, encoding, compression)
184 if _is_url(filepath_or_buffer):
185 url = str(filepath_or_buffer)
--> 186 req = _urlopen(url)
187 content_encoding = req.headers.get('Content-Encoding', None)
188 if content_encoding == 'gzip':
/projects/sage/sage-7.6/local/lib/python/urllib2.pyc in urlopen(url, data, timeout, cafile, capath, cadefault, context)
152 else:
153 opener = _opener
--> 154 return opener.open(url, data, timeout)
155
156 def install_opener(opener):
/projects/sage/sage-7.6/local/lib/python/urllib2.pyc in open(self, fullurl, data, timeout)
427 req = meth(req)
428
--> 429 response = self._open(req, data)
430
431 # post-process response
/projects/sage/sage-7.6/local/lib/python/urllib2.pyc in _open(self, req, data)
445 protocol = req.get_type()
446 result = self._call_chain(self.handle_open, protocol, protocol +
--> 447 '_open', req)
448 if result:
449 return result
/projects/sage/sage-7.6/local/lib/python/urllib2.pyc in _call_chain(self, chain, kind, meth_name, *args)
405 func = getattr(handler, meth_name)
406
--> 407 result = func(*args)
408 if result is not None:
409 return result
/projects/sage/sage-7.6/local/lib/python/urllib2.pyc in https_open(self, req)
1239 def https_open(self, req):
1240 return self.do_open(httplib.HTTPSConnection, req,
-> 1241 context=self._context)
1242
1243 https_request = AbstractHTTPHandler.do_request_
/projects/sage/sage-7.6/local/lib/python/urllib2.pyc in do_open(self, http_class, req, **http_conn_args)
1196 except socket.error, err: # XXX what error?
1197 h.close()
-> 1198 raise URLError(err)
1199 else:
1200 try:
URLError: <urlopen error [Errno 110] Connection timed out>
What's the problem?
How could I solve?
I use a free account on CoCalc.
If it takes time to upload and so not enough for my free account, how I can upload the file as worksheet and link it? What will be the link in the URL specification?
ThankspspWed, 16 Aug 2017 16:40:27 +0200https://ask.sagemath.org/question/38546/import print_function only works in one cell in linuxhttps://ask.sagemath.org/question/37776/import-print_function-only-works-in-one-cell-in-linux/I just installed Sage in Linux Mint, and the Import `print_function` only seems to work in one cell in the Notebook.
If I type this in the top cell it works fine:
from __future__ import print_function
print("all","good","dogs","eat","shoes",sep=" now ")
to print this:
all now good now dogs now eat now shoes
But if I do exactly the same print in the next cell, without the import, I get a syntax error.
However, the import does work for all cells in Sage for Windows.cybervigilanteSat, 03 Jun 2017 04:00:46 +0200https://ask.sagemath.org/question/37776/Import Text.txt file contents from a windows computer to sagecell.https://ask.sagemath.org/question/38185/import-texttxt-file-contents-from-a-windows-computer-to-sagecell/Hello,
The following code will work on my Linux computer if I use the "/usual path/" in Linux but I cannot get Sage to recognize
my Windows path. My code
with open('C:\Users\miram\OneDrive\Documents\Programming\Original.txt', 'r') as f:
L = f.readlines()
I have also tried the path
with open('C:\\Users\\miram\\OneDrive\\Documents\\Programming\\Original.txt', 'r') as f:
L = f.readlines()
I have also tried the path
with open('C:\\Text\\22.PE.Orig.List.txt', 'r') as f:
L = f.readlines()
and with one backslash.
I get the following error:
IOError: [Errno 2] No such file or directory: 'C:\\Text\\22.PE.Orig.List.txt'
What I want to do, as can be seen, is import a text file into SageMath so that I can work with the list created.
I am following: https://ask.sagemath.org/question/28765/turning-a-txt-file-into-a-list-in-sagemathpython/ and have followed the advice for my Linux machine and have not had a problem. I need to do it on my Windows computer, though.
I think my problem is that I am using a sagecell server. Is that true?happys5Thu, 06 Jul 2017 03:47:54 +0200https://ask.sagemath.org/question/38185/How to import numpyhttps://ask.sagemath.org/question/37959/how-to-import-numpy/ I am having problems importing numpy. I have sage 7.6 and am using terminal sessions on mac. Whenever I try "import numpy" I get an error message saying "Error importing numpy: you should not try to import numpy from its source directory; please exit the numpy source tree, and relaunch your python interpreter from there." I understand that this means some numpy software is not in the right file, but others, working on the same project as me, I know have not had to import any extra software for numpy to work. I'd really appreciate any help!TabethaFri, 16 Jun 2017 14:00:48 +0200https://ask.sagemath.org/question/37959/Import class using mathematicahttps://ask.sagemath.org/question/37229/import-class-using-mathematica/I have a class a in a file a.sage using the interface to mathematica. I want to use this class in another class b.
One way I found was to run first "mv a.sage a.py", which generates a python file. But then I get the error: "NameError: global name 'mathematica' is not defined" because you cannot use mathematica in python as you can use it with sage.
Is there a way importing a self-written class (a.sage) using mathematica in another self-written class (b.sage)?sageUserFri, 07 Apr 2017 19:34:45 +0200https://ask.sagemath.org/question/37229/How to import the print function from __future__ ?https://ask.sagemath.org/question/37014/how-to-import-the-print-function-from-__future__/I did `from __future__ import print_function`
print('text',end='\n')
But it shows error.screened00Tue, 21 Mar 2017 15:41:27 +0100https://ask.sagemath.org/question/37014/