How to print numpy objects without line breaks - python

I am logging input arguments to a function using
logging.debug('Input to this function = %s',
inspect.getargvalues(inspect.currentframe())[3])
But I do not want the line breaks inserted within numpy objects. numpy.set_printoptions(linewidth=np.nan) removes some, but line breaks are still inserted in 2D objects such as
array([[ 0.84148239, 0.71467895, 0.00946744, 0.3471317 ],
[ 0.68041249, 0.20310698, 0.89486761, 0.97799646],
[ 0.22328803, 0.32401271, 0.96479887, 0.43404245]])
I want it to be like this:
array([[ 0.84148239, 0.71467895, 0.00946744, 0.3471317 ], [ 0.68041249, 0.20310698, 0.89486761, 0.97799646], [ 0.22328803, 0.32401271, 0.96479887, 0.43404245]])
How can I do this? Thanks.

Given an array x, you can print it without line breaks with,
import numpy as np
x_str = np.array_repr(x).replace('\n', '')
print(x_str)
or alternatively using the function np.array2string instead of np.array_repr.
I'm not sure if there is an easy way to remove newlines from the string representation or numpy arrays. However, it is always possible to remove them after the conversion took place,
input_args = inspect.getargvalues(inspect.currentframe())[3]
logging.debug('Input to this function = %s', repr(input_args).replace('\n', ''))

import numpy as np
np.set_printoptions(threshold=np.inf)
np.set_printoptions(linewidth=np.inf)
# Testing:
big_arr = np.ones([30,70])
print(big_arr)

Simple solution
import numpy as np
value = np.array([[1, 2, 3, 4, 5, 6, 7, 8], [1, 2, 3, 4, 5, 6, 7, 8], [1, 2, 3, 7, 8]])
value_str = str(value).replace('\n', '')
print("prints: " + value_str)
# prints: [[1, 2, 3, 4, 5, 6, 7, 8], [1, 2, 3, 4, 5, 6, 7, 8], [1, 2, 3, 7, 8]]

This solution also works:
myArray = np.array([[ 0.84148239, 0.71467895, 0.00946744, 0.3471317 ],
[ 0.68041249, 0.20310698, 0.89486761, 0.97799646],
[ 0.22328803, 0.32401271, 0.96479887, 0.43404245]])
print(np.array2string(myArray).replace('\n','').replace(' ',', '))
Output:
[[0.84148239, 0.71467895, 0.00946744, 0.3471317, ], [0.68041249, 0.20310698, 0.89486761, 0.97799646], [0.22328803, 0.32401271, 0.96479887, 0.43404245]]

Related

How to iterate random_path in the below code?

I want to print random_path in the below code. Can I show all random paths using list
random_path = nx.generate_random_paths(twitch_G,100, path_length = 5)
If I got your question right, you just need to put random_path inside list list( random_path )
gr = nx.gnp_random_graph(10, 0.6)
list( nx.generate_random_paths(gr, sample_size=2, path_length=4) )
result:
[[1, 9, 0, 4, 7], [6, 7, 3, 0, 5]]

How to make press the keyboard return random python list elements?

I have a python list with some numbers in it and I want to achieve that press keyboard can return a different number. This is my code.
import random
import os
a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
b = random.sample(a, 1)
while True:
print(b)
os.system('pause')
But everytime I press space the returned element is the same, how can I make it return a different number?
import random
import os
a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
while True:
b = random.sample(a, 1)
print(b)
os.system('pause')
A random sample has to be taken every iteration

Create a multiset from a Set X

in a Multiset it is allowed to have multiple elements
For Example. if X (normal set) = {0,2,4,7,10}, then ∆X (multiset) = {2,2,3,3,4,5,6,7,8,10}.
∆X denotes the multiset of all 􏰃(N 2) pairwise distances between points in X
How can i Write this in Python?
I have created a List X but i don't know how to put all differences in another list and order them.
I hope you can help me.
It is basically just one line.
import itertools
s = {0,2,4,7,10}
sorted([abs(a-b) for (a,b) in itertools.combinations(s,2)])
you can use itertools
import itertools
s = {0,2,4,7,10}
k = itertools.combinations(s,2)
distance = []
l = list(k)
for p in l:
distance.append(abs(p[1]-p[0]))
print(sorted(distance))
A simple way is to convert your set to a list, sort it, and then use a double for loop to compute the differences:
X = {0,2,4,7,10} # original set
sorted_X = sorted(list(X))
diffs = []
for i, a in enumerate(sorted_X):
for j, b in enumerate(sorted_X):
if j > i:
diffs.append(b-a)
print(diffs)
#[2, 4, 7, 10, 2, 5, 8, 3, 6, 3]
And if you want the diffs sorted as well:
print(sorted(diffs))
#[2, 2, 3, 3, 4, 5, 6, 7, 8, 10]
Another option that would work in this case is to use itertools.product:
from itertools import product
print(sorted([(y-x) for x,y in product(sorted_X, sorted_X) if y>x]))
#[2, 2, 3, 3, 4, 5, 6, 7, 8, 10]

Accesing a matrix within a .mat file with python

I'm translating matlab code to python. I have a few matrices within a .mat file called 'AK_1'. I only want to access the data in one of these matrices. The matlab code accesses it this way where .response1 is the desired matrix:
numtrials1 = subject_data1.response1(1,:);
I tried loading all the data into a dict so I could then loop through it to the desired matrice with this code but that did not produce a workable result.
subject_data1_dict = {}
subject_data1 = scipy.io.loadmat('./MAT_Data_Full_AAAD_V2/AK_1.mat', subject_data1_dict)
How can I access only the matrix 'response1' within the file AK_1.mat?
Say you have a myfile.mat with the following struct S:
S =
response1: [5x5 double]
response2: [5x5 double]
response3: [5x5 double]
And you want to access response1 from python. Then:
>>> from scipy.io import loadmat
>>> D = loadmat("myfile.mat", variable_names = ("S",) )
>>> D["S"]["response1"] # returns matlab's S.response1
If you wanted to select more variables contained in the file than just S, you just add them in the tuple, i.e. variable_names=("S","otherVar")
Obviously, if all you're interested in is the response1 array, you can bypass collecting the dictionary altogether, i.e.:
>>> response1 = loadmat("myfile.mat", variable_names = ("S",) )["S"]["response1"]
>>> response1
array([[ array([[ 9, 1, 2, 2, 7],
[10, 3, 10, 5, 1],
[ 2, 6, 10, 10, 9],
[10, 10, 5, 8, 10],
[ 7, 10, 9, 10, 7]], dtype=uint8)]], dtype=object)
create and save a structure containing 3 matrices in matlab:
a=1:5
b.aa=a
b.bb=a
b.cc=a
save(struct.mat,'b')
load .mat file in python
from scipy.io import loadmat
matfile = loadmat('d:/struct.mat')
you can now access for example b.aa and b.bb via:
matfile[('b')][0][0][0]
matfile[('b')][0][0][1]
Is that what you wanted?

What is the purpose of deepcopy's second parameter, memo?

from copy import*
a=[1,2,3,4]
c={'a':'aaa'}
print c
#{'a': 'aaa'}
b=deepcopy(a,c)
print b
print c
# print {'a': 'aaa', 10310992: 3, 10310980: 4, 10311016: 1, 11588784: [1, 2, 3, 4, [1, 2, 3, 4]], 11566456: [1, 2, 3, 4], 10311004: 2}
why c print that
Please try to use the code, rather than text, because my English is not very good, thank you
in django.utils.tree.py
def __deepcopy__(self, memodict):
"""
Utility method used by copy.deepcopy().
"""
obj = Node(connector=self.connector, negated=self.negated)
obj.__class__ = self.__class__
obj.children = deepcopy(self.children, memodict)
obj.subtree_parents = deepcopy(self.subtree_parents, memodict)
return obj
import copy
memo = {}
x1 = range(5)
x2=range(6,9)
x3=[2,3,4,11]
y1 = copy.deepcopy(x1, memo)
y2=copy.deepcopy(x2, memo)
y3=copy.deepcopy(x3,memo)
print memo
print id(y1),id(y2),id(y3)
y1[0]='www'
print y1,y2,y3
print memo
print :
{10310992: 3, 10310980: 4, 10311016: 1, 11588784: [0, 1, 2, 3, 4, [0, 1, 2, 3, 4]], 10311028: 0, 11566456: [0, 1, 2, 3, 4], 10311004: 2}
{11572448: [6, 7, 8], 10310992: 3, 10310980: 4, 10311016: 1, 11572368: [2, 3, 4, 11], 10310956: 6, 10310896: 11, 10310944: 7, 11588784: [0, 1, 2, 3, 4, [0, 1, 2, 3, 4], 6, 7, 8, [6, 7, 8], 11, [2, 3, 4, 11]], 10311028: 0, 11566456: [0, 1, 2, 3, 4], 10310932: 8, 10311004: 2}
11572408 11581280 11580960
['www', 1, 2, 3, 4] [6, 7, 8] [2, 3, 4, 11]
{11572448: [6, 7, 8], 10310992: 3, 10310980: 4, 10311016: 1, 11572368: [2, 3, 4, 11], 10310956: 6, 10310896: 11, 10310944: 7, 11588784: [0, 1, 2, 3, 4, [0, 1, 2, 3, 4], 6, 7, 8, [6, 7, 8], 11, [2, 3, 4, 11]], 10311028: 0, 11566456: ['www', 1, 2, 3, 4], 10310932: 8, 10311004: 2}
No one above gave a good example of how to use it.
Here's what I do:
def __deepcopy__(self, memo):
copy = type(self)()
memo[id(self)] = copy
copy._member1 = self._member1
copy._member2 = deepcopy(self._member2, memo)
return copy
Where member1 is an object not requiring deepcopy (like a string or integer), and member2 is one that does, like another custom type or a list or dict.
I've used the above code on highly tangled object graphs and it works very well.
If you also want to make your classes pickleable (for file save / load), there is not analogous memo param for getstate / setstate, in other words the pickle system somehow keeps track of already referenced objects, so you don't need to worry.
The above works on PyQt5 classes that you inherit from (as well as pickling - for instance I can deepcopy or pickle a custom QMainWindow, QWidget, QGraphicsItem, etc.)
If there is some initialization code in your constructor that creates new objects, for instance a CustomWidget(QWidget) that creates a new CustomScene(QGraphicsScene), but you'd like to pickle or copy the scene from one CustomWidget to a new one, then one way is to make a new=True parameter in your __init__ and say:
def __init__(..., new=True):
....
if new:
self._scene = CustomScene()
def __deepcopy__(self, memo):
copy = type(self)(..., new=False)
....
copy._scene = deepcopy(self._scene, memo)
....
That ensures you don't create a CustomScene (or some big class that does a lot of initializing) twice! You also should use the same setting (new=False) in your __setstate__ method, eg.:
def __setstate__(self, data):
self.__init__(...., new=False)
self._member1 = data['member 1']
.....
There are other ways to get around the above, but this is the one I converged to and use frequently.
Why did I talk about pickling as well? Because you will want both in any application typically, and you maintain them at the same time. If you add a member to your class, you add it to setstate, getstate, and deepcopy code. I would make it a rule that for any new class you make, you create the above three methods if you plan on doing copy / paste an file save / load in your app. Alternative is JSON and save / loading yourself, but then there's a lot more work for you to do including memoization.
So to support all the above, you need __deepcopy__, __setstate__, and __getstate__ methods and to import deepcopy:
from copy import deepcopy
, and when you write your pickle loader / saver functions (where you call pickle.load()/ pickle.dump() to load / save your object hierarchy / graph) do import _pickle as pickle for the best speeds (_pickle is some faster C impl which is usually compatible with your app requirements).
It's the memo dict, where id-to-object correspondence is kept to reconstruct complex object graphs perfectly. Hard to "use the code", but, let's try:
>>> import copy
>>> memo = {}
>>> x = range(5)
>>> y = copy.deepcopy(x, memo)
>>> memo
{399680: [0, 1, 2, 3, 4], 16790896: 3, 16790884: 4, 16790920: 1,
438608: [0, 1, 2, 3, 4, [0, 1, 2, 3, 4]], 16790932: 0, 16790908: 2}
>>>
and
>>> id(x)
399680
>>> for j in x: print j, id(j)
...
0 16790932
1 16790920
2 16790908
3 16790896
4 16790884
so as you see the IDs are exactly right. Also:
>>> for k, v in memo.items(): print k, id(v)
...
399680 435264
16790896 16790896
16790884 16790884
16790920 16790920
438608 435464
16790932 16790932
16790908 16790908
you see the identity for the (immutable) integers.
So here's a graph:
>>> z = [x, x]
>>> t = copy.deepcopy(z, memo)
>>> print id(t[0]), id(t[1]), id(y)
435264 435264 435264
so you see all the subcopies are the same objects as y (since we reused the memo).
You can read more by checking the Python online documentation:
http://docs.python.org/library/copy.html
The deepcopy() function is recursive, and it will work its way down through a deeply nested object. It uses a dictionary to detect objects it has seen before, to detect an infinite loop. You should just ignore this dictionary.
class A(object):
def __init__(self, *args):
self.lst = args
class B(object):
def __init__(self):
self.x = self
def my_deepcopy(arg):
try:
obj = type(arg)() # get new, empty instance of type arg
for key in arg.__dict__:
obj.__dict__[key] = my_deepcopy(arg.__dict__[key])
return obj
except AttributeError:
return type(arg)(arg) # return new instance of a simple type such as str
a = A(1, 2, 3)
b = B()
b.x is b # evaluates to True
c = my_deepcopy(a) # works fine
c = my_deepcopy(b) # stack overflow, recurses forever
from copy import deepcopy
c = deepcopy(b) # this works because of the second, hidden, dict argument
Just ignore the second, hidden, dict argument. Do not try to use it.
Here's a quick illustration I used for explaining this to myself:
a = [1,2,3]
memo = {}
b = copy.deepcopy(a,memo)
# now memo = {139907464678864: [1, 2, 3], 9357408: 1, 9357440: 2, 9357472: 3, 28258000: [1, 2, 3, [1, 2, 3]]}
key = 139907464678864
print(id(a) == key) #True
print(id(b) == key) #False
print(id(a) == id(memo[key])) #False
print(id(b) == id(memo[key])) #True
in other words:
memo[id_of_initial_object] = copy_of_initial_object

Categories