When using sympy, why is a permutation group not a group? - python-3.x

I've run this code, pretty plainly expecting the result to be True and yet it's not. I'm not able to make heads or tails of the documentation regarding this behavior, so if someone could explain it to me I'd appreciate it.
from sympy.combinatorics.named_groups import SymmetricGroup
G = SymmetricGroup(3)
print(G.is_group())
[Edit: Weirdly, I tested this and it came out True:
from sympy.combinatorics import Permutation
from sympy.combinatorics.perm_groups import PermutationGroup
from sympy.combinatorics.named_groups import SymmetricGroup
G = SymmetricGroup(3)
H = PermutationGroup( Permutation(0,1,2) )
print(G.is_normal(H))
]

So I found the answer, it's that the "group", when created, only stores a generating set. To see this run the following code which only prints two elements.
from sympy.combinatorics.named_groups import SymmetricGroup
G = SymmetricGroup(3)
for i in G:
print(i)
However, I'm now left with the curious fact that this code prints True False for reasons I haven't been able to discover:
from sympy.combinatorics import Permutation
from sympy.combinatorics.perm_groups import PermutationGroup
from sympy.combinatorics.named_groups import SymmetricGroup
G = PermutationGroup(list(SymmetricGroup(3).generate()))
H = PermutationGroup( Permutation([0,1,2]) ) # This should just be the trivial
# subgroup and therefore normal
print(H.is_subgroup(G), H.is_normal(G))

Related

Make sense of a list in Python3

I'm running into a little bit of a snag and I can't seem to research my way out of this, so I'm hoping for some pointers.
I'm using an 3x MCP23017 chips and putting them to output so that I can control a few things. I'm using the Adafruit MCP23017 library on Github, and this works well with the following:
#!/usr/bin/env python
import time
import board
import busio
import RPi.GPIO as GPIO
from digitalio import Direction
from adafruit_mcp230xx.mcp23017 import MCP23017
GPIO.setmode(GPIO.BCM)
i2c = busio.I2C(board.SCL, board.SDA)
mcp1 = MCP23017(i2c, address=0x20)
mcp2 = MCP23017(i2c, address=0x24)
mcp3 = MCP23017(i2c, address=0x22)
#mcp1
one_port_pins = []
for pin in range(0, 15):
one_port_pins.append(mcp3.get_pin(pin))
for pin in one_port_pins:
pin.direction = Direction.OUTPUT
#mcp2
two_port_pins = []
for pin in range(0, 15):
two_port_pins.append(mcp2.get_pin(pin))
for pin in two_port_pins:
pin.direction = Direction.OUTPUT
#mcp3
three_port_pins = []
for pin in range(0, 15):
three_port_pins.append(mcp3.get_pin(pin))
for pin in three_port_pins:
pin.direction = Direction.OUTPUT
According to the example, I'm able to trigger them as such:
for pin in two_port_pins:
pin.value = True
time.sleep(0.2)
pin.value = False
time.sleep(0.2)
And this does trigger them and work great, however, at this stage, I would like to incorporate some of my other script, that would parse through some of the pin's need to be activated, although, I'm not quite sure how to match them.
Trying to print the lists one_port_pins, two_port_pins and three_port_pins gives me all sorts of data I'm not at all formiliar with when I try to print:
print(pin.__dict__)
>>> {'_pin': 0, '_mcp': <adafruit_mcp230xx.mcp23017.MCP23017 object at 0xb65d5230>}
>>> {'_pin': 1, '_mcp': <adafruit_mcp230xx.mcp23017.MCP23017 object at 0xb65d5230>}
>>> {'_pin': 2, '_mcp': <adafruit_mcp230xx.mcp23017.MCP23017 object at 0xb65d5230>}
Can someone tell me what I am looking at? How am I able to select a specific pin to activate?
Thank you!

Restarting an optimisation with Pymoo

I'm trying to restart an optimisation in pymoo.
I have a problem defined as:
class myOptProb(Problem):
"""my body goes here"""
algorithm = NSGA2(pop_size=24)
problem = myOptProblem(opt_obj=dp_ptr,
nvars=7,
nobj=4,
nconstr=0,
lb=0.3 * np.ones(7),
ub=0.7 * np.ones(7),
parallelization=('threads', cpu_count(),))
res = minimize(problem,
algorithm,
('n_gen', 100),
seed=1,
verbose=True)
During the optimisation I write the design vectors and results to a .csv file. An example of design_vectors.csv is:
5.000000000000000000e+00, 4.079711567060104183e-01, 6.583544872784267143e-01, 4.712364759485179189e-01, 6.859360188593541796e-01, 5.653765991273791425e-01, 5.486782880836487131e-01, 5.275405748345924906e-01,
7.000000000000000000e+00, 5.211287914743063521e-01, 6.368123569438421949e-01, 3.496693260479644128e-01, 4.116734716044557763e-01, 5.343037085833151068e-01, 6.878382993278697732e-01, 5.244120877022839800e-01,
9.000000000000000000e+00, 5.425317846613321171e-01, 5.275405748345924906e-01, 4.269449637288642574e-01, 6.954464617649794844e-01, 5.318980876983187001e-01, 4.520564690494201510e-01, 5.203792876471586837e-01,
1.100000000000000000e+01, 4.579502451694219545e-01, 6.853050113762846340e-01, 3.695822666721857441e-01, 3.505318077758549089e-01, 3.540316632186925050e-01, 5.022648662707586142e-01, 3.086099221096791911e-01,
3.000000000000000000e+00, 4.121775968257620493e-01, 6.157117313805953174e-01, 3.412904026310568106e-01, 4.791574104703620329e-01, 6.634382012372381787e-01, 4.174456593494717538e-01, 4.151101354345394512e-01,
The results.csv is:
5.000000000000000000e+00, 1.000000000000000000e+05, 1.000000000000000000e+05, 1.000000000000000000e+05, 1.000000000000000000e+05,
7.000000000000000000e+00, 1.041682833582066703e+00, 3.481167125962069189e-03, -5.235115318709097909e-02, 4.634480813876099177e-03,
9.000000000000000000e+00, 1.067730307802263967e+00, 2.194702810002167534e-02, -3.195892023664552717e-01, 1.841232582360878426e-03,
1.100000000000000000e+01, 8.986880344052742275e-01, 2.969022150977750681e-03, -4.346692726475211849e-02, 4.995468429444801205e-03,
3.000000000000000000e+00, 9.638770499257821589e-01, 1.859596479928402393e-02, -2.723230073142696162e-01, 1.600910928983005632e-03,
The first column is the index of the design vector - because I thread asynchronously, I specify the indices.
I see that it should be possible to restart the optimisation via the sampling parameter for pymoo.algorithms.nsga2.NSGA2 but I couldn't find a working example. The documentation for both population and individuals is also not clear. So how can I restart a simulation with the previous results?
Yes, you can initialize the algorithm object with a population instead of doing it randomly.
I have written a small tutorial for a biased initialization:
https://pymoo.org/customization/initialization.html
Because in your case the data already exists, in a CSV or in-memory file, you might want to create a dummy problem (I have called it Constant in my example) to set the attributes in the Population object. (In the population X, F, G, CV and feasible needs to be set). Another way would be setting the attributes directly...
The biased initialization with a dummy problem is shown below. If you already use pymoo to store the csv files, you can also just np.save the Population object directly and load it. Then all intermediate steps are not necessary.
I am planning to improve checkpoint implementation in the future. So if you have some more feedback and use case which are not possible yet please let me know.
import numpy as np
from pymoo.algorithms.nsga2 import NSGA2
from pymoo.algorithms.so_genetic_algorithm import GA
from pymoo.factory import get_problem, G1, Problem
from pymoo.model.evaluator import Evaluator
from pymoo.model.population import Population
from pymoo.optimize import minimize
class YourProblem(Problem):
def __init__(self, n_var=10):
super().__init__(n_var=n_var, n_obj=1, n_constr=0, xl=-0, xu=1, type_var=np.double)
def _evaluate(self, x, out, *args, **kwargs):
out["F"] = np.sum(np.square(x - 0.5), axis=1)
problem = YourProblem()
# create initial data and set to the population object - for your this is your file
N = 300
X = np.random.random((N, problem.n_var))
F = np.random.random((N, problem.n_obj))
G = np.random.random((N, problem.n_constr))
class Constant(YourProblem):
def _evaluate(self, x, out, *args, **kwargs):
out["F"] = F
out["G"] = G
pop = Population().new("X", X)
Evaluator().eval(Constant(), pop)
algorithm = GA(pop_size=100, sampling=pop)
minimize(problem,
algorithm,
('n_gen', 10),
seed=1,
verbose=True)

getting "none" as result and don't uderstand why

I am learning how to program in python 3 and today i was praticing until i start to struggle with this.
I was trying to make a function to get to know the total square meters of wood that i'll use in one project, but i keep get the none result and i don't know why, even reading almost every post about it that i found here.
Anyway, here's the code:
from math import pi
def acirc(r):
pi*r**2
def madeiratotal(r1,r2,r3,r4,r5):
a = acirc(r1)
b = acirc(r2)
c = acirc(r3)
d = acirc(r4)
e = acirc(r5)
print (a+b+c+d+e)
madeiratotal(0.15,0.09,0.175,0.1,0.115)
I already try defining the "acirc" function inside the "madeiratotal" function, try to print all numbers separated and them suming then... I just don't know what else to do please help
You need to return value from acirc function otherwise return type is None
def acirc(r):
return pi*r**2

Is there a way to move the camera of a 2d world in pyglet?

I'm testing pyglet, and it has everything(except for a good guide) but the only thing that i don't understand is: how do I move the camera to show hidden content?
As stated by Rabbid76, try pyglet.gl.glTranslatef(dx,dy,dz).
The first argument in glTranslatef changes the x-direction of a supposed "camera",
the second changes y, and the third changes z. Heres a quick code example that may also help:
import pyglet
from pyglet.window import key
from pyglet.gl import glTranslatef
def movement(keys):
if keys[key.I]:
glTranslatef(0,10,0)
if keys[key.K]:
glTranslatef(0,-10,0)
if keys[key.J]:
glTranslatef(-10,0,0)
if keys[key.L]:
glTranslatef(10,0,0)
def update(dt):
window.clear()
label.draw()
movement()
if __name__ == '__main__':
window = pyglet.window.Window(height=1000,width=1000)
keys = key.KeyStateHandler()
window.push_handlers(keys)
label = pyglet.text.Label('Hello, world',
font_size=36,
x=window.width//2, y=window.height//2)
pyglet.clock.schedule_interval(update,1/60)
pyglet.app.run()
In the above example, you would use the I, J, K, and L keys to move a label around your window. Hope this was helpful!
For anyone who comes since the pyglet 2 update, you can now use Window.view = Window.view.from_translation(pygmath.Vec3(xpos, ypos, zpos)).
Try using an offset. Fo/x, lets say x = 0, and camoffset = 5. You can render the x as x+camoffset. It works.

Numba #jit fails to speed up the performance of this function. Anyway to fix that?

I am quite new to the numba package in python. I am not sure if I am using the numba.jit correctly, but the code just runs too slow with 23.7s per loops over the line: Z1 = mmd(X,Y,20)
What is the correct way to optimize the code? I need your help guys. Thank you.
Here is my code:
import pandas as pd
import numba as nb
import numpy as np
#nb.jit
def mmd(array1, array2, n):
n1 = array1.shape[0]
MMD = np.empty(n1, dtype = 'float64')
for i in range(n-1,n1):
MMD[i] = np.average(abs(array1[i+1-n:i+1] - array2[i]))
return MMD
X = np.array([i**2 for i in range(1000000)])
Y = np.array([i for i in range(1000000)])
Z1 = mmd(X,Y,20)
EDIT: simplified the code even further
EDIT2: tried #nb.jit(nopython = True), then there is an error message:
KeyError: "<class 'numba.targets.cpu.CPUTargetOptions'> does not support option: 'nonpython'"
also tried:
#nb.jit(nb.float32[:](nb.float32[:],nb.float32[:],nb.int8))
To make Numba work well you need to use "nopython" mode, as you mentioned. To enable this, simply run the program with jit replaced by njit (or equivalently, jit(nopython=True), and fix the errors one by one:
np.empty() doesn't support the dtype='float64' argument in Numba. That's OK though, because float64 is the default. Just remove it.
np.average() is not supported in Numba. That's OK, since we are not passing any weights anyway, it's the same as np.mean(). Replace it.
The built-in abs() is not supported in Numba. Use np.abs() instead.
We end up with this:
#nb.njit
def mmd(array1, array2, n):
n1 = array1.shape[0]
MMD = np.empty(n1)
for i in range(n-1,n1):
MMD[i] = np.mean(np.abs(array1[i+1-n:i+1] - array2[i]))
return MMD
And it is 100x faster.
Bonus tips:
You can initialize your sample data more concisely and faster like this:
Y = np.arange(1000000)
X = Y * Y
The first n values in the result are uninitialized garbage. You might want to clean that up somehow.

Resources