## SVG to C data using python

So, we’ve been building a little servo mechanism to move a mirror to aim a laser (a super fast and hacky hot glue job on a 2×4, but dang dong if it don’t basically work) and I thought it’d be nice to write a little script that converts paths in svg files (which I can draw in inkscape)  into a C struct that we can just stick into an arduino file and read from. If anybody else needs this, you’ll need to modify some stuff. All the stuff is cobbled together from stackexchange replies. God, I love python. Checkout the nice little float regular expression.

from xml.dom import minidom

#Suggestion:python svgwrite.py mysvg >> outputfile
# append a bunch of images to file

import sys
if len(sys.argv) < 2:
print "***** USAGE: python svgparse.py filename *****"

svg_file = sys.argv[1]

doc = minidom.parse(svg_file)  # parseString also exists
path_strings = [path.getAttribute('d') for path
in doc.getElementsByTagName('path')]
#print path_strings

import re
posStrings = re.findall(r"[-+]?\d*\.\d+|\d+", path_strings[0])

x = []
y = []
for i in range(len(posStrings)):
if i % 2 == 0:
x.append(float(posStrings[i]))
else:
y.append(float(posStrings[i]))

'''
print "x"
print x
print "y"
print y
'''

# Insert math here. Normalization, centering, etc. precomputation of angles.

#print svg_file.split('.')[0]

print "float xpos[" + str(len(x)) + "] = {" + ", ".join(map(str,x)) + "};"
print "float ypos[" + str(len(y)) + "] = {" + ", ".join(map(str,y)) + "};"


## Avr-gcc and Arduino

I’m using an arduino nano.

Way easier than wiring up my own bullcrap, even though I’ve got some raw chips and a programmer on hand.

Here’s a short makefile that will get stuff to happen. You’ll need to replace /dev/tty0USB0 with wherever you’re device actually is.

TARGET=led

all: $(TARGET).c avr-gcc -Os -DF_CPU=16000000UL -mmcu=atmega328p -c -o$(TARGET).o $(TARGET).c avr-gcc -mmcu=atmega328p$(TARGET).o -o $(TARGET) avr-objcopy -O ihex -R .eeprom$(TARGET) $(TARGET).hex flash:$(TARGET).hex
avrdude -F -V -c arduino -p ATMEGA328P -P /dev/ttyUSB0 -b 57600  -U flash:w:\$(TARGET).hex

This was useful in figuring out how to make this makefile.

#include <avr/io.h>

int main(void)
{
// connect led to pin PC0
DDRB |= (1 << 0);
while(1)
{
PORTB ^= (0xFF << 0);    // toggles the led
}
}

This makes a fast switching program just to see what we can pump out. I measure 1.6Mhz

avr-objdump -m avr -D fastswitch.hex > assembly

Also

Adafruit Shield version 1 works on my chinese DK electornics board. Nice.

Got the thing to receive in my own python script. Pretty dang cool.

Now, some problems. The framerate variable makes no sense. My math must be wrong somewhere. Lower framerates devolve into industrial music.

Some good hiccups, had to convert from the default doubles to float32.

Using socket was pretty easy.

Declare variables global. I believe globals are supposed to be bad, but they sure are useful.

Tkinter is pretty good for quick stuff.

#rtl_tcp -s 2048000 -f 101140000
#-f 101140000 -g 40 -n 20480000

#rtl_sdr -f 101140000 -g 40 -n 20480000 ab120_10s.dat

from sys import argv
#This will allow a command line assignment of the filename
#script, filename = argv

import struct
import numpy as np
from scipy import signal
import matplotlib.pyplot as plt
import scipy as sp

import socket

TCP_IP = '127.0.0.1'
TCP_PORT = 1234
BUFFER_SIZE = 1024

import pyaudio

p = pyaudio.PyAudio()

# open stream (2)
framerate = 204800 #10000 # for industrial music
samplerate = 2048000

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
offset = -4.0e5
def callback(in_data, frame_count, time_info, status):
data = ""
#print frame_count
for i in range(frame_count * samplerate / framerate / BUFFER_SIZE * 2):
data = data + s.recv(BUFFER_SIZE)

rawdata = np.fromstring(data,dtype=np.uint8)
real = rawdata[0::2]-127.5
imag = rawdata[1::2]-127.5
vals = real + 1.j * imag
T = frame_count / float(framerate) #seconds
fshift = offset#-4.0e5 #-3.5e5
#print offset
vals = vals * np.exp ( 1.j *2 * np.pi * np.linspace(0, fshift * T  ,vals.size)) # number of cycles
vals = sp.signal.decimate(vals,10)
diff = vals[0:-1] * np.conj(vals[1:])
sig = np.arctan2(np.real(diff),np.imag(diff))
sig = sp.signal.resample(sig,frame_count)
return (np.float32(sig/np.pi), pyaudio.paContinue)
#return (sig/np.pi, pyaudio.paContinue)

stream = p.open(format=pyaudio.paFloat32,
channels=1,
rate=framerate,
output=True,
stream_callback=callback)

from matplotlib.widgets import Slider

import signal
import sys
def signal_handler(signal, frame):
print('You pressed Ctrl+C!')
s.close()
stream.stop_stream()
stream.close()

# close PyAudio (5)
p.terminate()
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
'''
axcolor = 'lightgoldenrodyellow'
axfreq = plt.axes([0.25, 0.1, 0.65, 0.03], axisbg=axcolor)

sfreq = Slider(axfreq, 'Freq', -5.e5, -3.e5, valinit=-4.e5)
def update(val):
offset = sfreq.val
sfreq.on_changed(update)
plt.ion()
plt.show()
'''

from Tkinter import *

def update(event):
global offset
offset = event.widget.get()
#print offset

master = Tk()
w = Scale(master, from_=-10e5, to=0)
w.pack()
w.set(-4e5)
w.bind('<ButtonRelease>', update)

#w = Scale(master, from_=0, to=200, orient=HORIZONTAL)
#w.pack()

master.mainloop()

signal.pause()


## Bootstrapping myself into RF

I’ve dreamed radio dreams for many years.

I think I’m closer than ever to being able to goof around in the RF.

Previously I’ve taken a too low level approach, trying to build my own oscillators and amplifiers. Certainly doable, but not the easiest, and not actually the thing I’m most interested in.

The revelation came when I saw this mit radar building guide. They’re using little blocks that I understand from microcircuits. I think that’s one of the easier ways into the high frequency regime.

So I went a huntin on ebay and bought anything that sounded reasonable. VCO, mixer, LNA. One tripping point was that I had no way to measure anything. My oscilloscope only goes up to 100Mhz.

So I bought a frequency Counter and Power Meter for real cheap.

The frequency counter works. Try wiggling between high and low mode and turning the filter off. It picked up my 2Mhz function generator signal and also the signal off the VCO I bought, which goes from 90Mhz to 190Mhz ish.

With the pin connector on the left the top is control, the two middle are ground and the bottom is power

## Folgertech Prusa update

Folgertech sent us free replacements for our broken thermistor and two new motor driver boards. Fast response, Fast delivery. Good on you, Folgertech.

So we got it a printin! For a while we were getting stringy garbage that seemed to not really match any problems we found. Problem turned out to be that the print head came preassembled with the gear set screw untightened. Kind of a wonder it was printing at all. Had noticed that manual extrusion was rather sporadic. Maybe should’ve suspected sooner, but I guess I assumed that repetier was being wonky.

The built in slic3r in repetier crashes on my mac for some reason, so I open up an independent instance and use that instead.

Also, SD card printing is preferable. We’ve killed a couple prints when my computer goes to sleep.

We’re using Onshape. It is pretty awesome. Ben whipped out some mounts for our lcd screen in like 10 minutes. Then we didn’t have enough M3 nuts, so we printed them. PLA is soft enough that it can be threaded by the screw. Needed to be 105% scaled in Slic3r.

Also press fit some spare 606Z bearings into a little cup. No scaling needed. Also press fit a little 6mm cylinder into the center. Not an insanely permanant tight press fit, but definitely needs so force to take out.

Made some cubes, some octopusi, a sloth.

Onwards and upwards!

## Problem 2: Schutz chap 5

1.

Redshift from gravity. Fire a photon up. Convert into mass and let mass drop. If energy conserved then you gain mgh of energy where $m = \hbar \omega'$, the freqeuncy at the top. Hence you have $\hbar \omega = m+mgh=\hbar \omega (1+gh)$.

The frequency at the top is reduced by (1+gh), i.e. it is redder.

2. Uniform gravity raises no tides? That’s odd. naively I would think that the water would flow towards the lowest energy configuration, which would be at the bottom of the external potential. On the total gravitational potential (+ centrifugal force) constant surface. Which does get distorted by an external field.

Oh. I see. Looking at the text, the earth would be freely falling as well.  Wow. That’s an important point. The earth is falling towards the moon at exactly the rate of free fall. It’s the differences of force that cause the tides. A little stronger on the front, a little weaker on the back. This is sort of the same thing as a draping cloth in a falling elevator.

7.

Can’t raise an lower $\Lambda$ using the metric. They are coordinate transformations. I believe upper indices are components of vectors and lower indices are components of 1-forms. $dx^\mu \partial_\mu$ and $\partial_\mu \phi$

$x = r\cos(\theta)$

$y = r\sin(\theta)$

This matrix will convert the gradient into new coordinates

$\begin{bmatrix} \cos{\theta} & -r\sin(\theta) \\ \sin(\theta) & r\cos(\theta) \end{bmatrix}$

$\theta = \arctan(\frac{y}{x})$

$r = \sqrt{x^2+y^2}$

This one will convert vectors into new coordinates

$\begin{bmatrix} x/r& y/r\\ -y/r^2 &x/r^2\end{bmatrix}$

Multiplying the two should give an identity matrix, since inner product should stay invariant under coordinate change. Quite miraculously they do. Try multiplying the two matrices. Nice.

## Problem 1: Free Particle

Let’s solve the free particle

I guess

Newton’s Law $F = ma$

$d^2 x / dt^2=0$

Hence $x = x_0 + vt$

At least that works. Not sure I derived it particularly. Or proved it unique.

Whatever. Lagrangian version

$L = T-V = \frac{1}{2}mv^2$

Euler Lagrange Equations

$\frac{d}{dt} \partial L / \partial \dot{q} = \partial_q L$

How do you get that? By varying the action with fixed endpoints it’s the one that minimizes the path.

$S = \int L dt = \int \partial/\partial\dot{q} L \delta \dot{q} + \partial_q L \delta q$

Nice.

$H = \frac{p^2}{2m}$

$\dot{p}=-\partial_x H=0$

$p = Const$

$\dot{x}=\partial_p H=\frac{p}{m}$

Okay. What about the quantum version?

Well $p = \frac{\hbar}{i}\partial_x$

How do I know that? In particular it’s hard to remember where the i goes. Well, I memorized it at some point. It follows that

$[x,p]=-\hbar/i$

But what is

$i \partial_t \psi = -\frac{\hbar^2}{2m}\nabla^2 \psi$

$E\psi =$

Whatever. I’m bored.

Maybe I’ll do the path integral some other day

## Folgertech Prusa i3 Printer

So we bought the Prusa i3 with the aluminum frame from folgertech about two weeks ago. Was tempted first to get a Chinese version off of aliexpress, but I’ve heard tales of long shipping times, plus possibly some kind of importing fee. WOuldn’t have saved much money anyhow. Definitely the way to go. It shipped pretty fast. Got it in about 3 days or so. Noice.

Box was surprisingly heavy and small.

There were some small problems, but nothing super major

The thermoresistor leads were overcrimped. The bot is totally unresponsive if it is freaking out about the thermoresistors (including motor control. Odd.) They should measure ~100k if they’re correct. We tried resoldering them, but too brittle. Hopefully getting a replacement from folgertech.

A little confusion about what the extra molex connector was for. For attaching to the thermistor

Missing 20mm screws

The 3d printed mounting piece for the extruder had its holes with poor spacing. We dremelled out some material in order to get both screws through.
The triple screw mounting of the Z-axis motor mounts torques the linear guide rails. We found just using the two upper screws to be better and leaving the third that goes into the vertical beam out.
We had a couple things that we changed in the firmware Configuration.h file  in order to get it working.
Our motors were only going one way until we disabled the max endstops. I guess it must have been registering nonexistant endstops as being hit.
#define X_HOME_DIR -1
#define INVERT_E0_DIR true
#define DISABLE_MAX_ENDSTOPS
There are no teeth in the stage belt connector (There probably should be some?)
Two of our motor drivers did not work. We were tearing our hair out over why the extruder motor wasn’t turning until we popped another one in.
Also a brief moment of panic when the entire board would not respond, but removing motor driver that had blown brought everything back up.
We also bought a lcd screen. I recommend it. Pretty nice.
Used repetier and slic3r on mac and grabbed some models from thingiverse.
I think the nozzle is 4mm, based on the folgertech website selling the extruder unit with 4mm attached. Not super sure how I’m gonna measure that.
http://reprap.org/wiki/Calibration
Maximum layer height of .4*.8 = .32
extrusion width <= .4
#define DEFAULT_AXIS_STEPS_PER_UNIT   {80,80,3840,90}
http://reprap.org/wiki/Triffid_Hunter’s_Calibration_Guide
// NEMA 17 motor with T2 belt and 20-tooth pulley:
(200 * 16) / (2 * 20) = 80.0
I wonder how much stretching will change this?
// NEMA 17 with standard pitch M5 threaded rod:
(200 * 16) / 0.8 = 4000
Hmm. 3840 in the stock firmware vs 4000 in Triffid’s guide?
“Personally I go for layer height of 0.2mm, and extrusion width of 0.5mm regardless of which nozzle I’m using.”
Tried 200C extruder temp
With painter tape on unheated bed. Seemed to be working until thermistor fix snapped
Triffid suggests printing at decremental temps
Also 65C bed for PLA.
Gotta try that.
So close.
So very close now.

Let’s try to give an explanation of superconductivity a go.

First off, there are at least two prongs, the microscopic and the macroscopic. This is ubiquitous under many topics. Hypothetically the two are linked, but in practice you don’t need one for the other. For example, the microscopics of magnets coming from the electron spins and why the spins like to align vs the forces felt by refrigerator magnets. Or why electrons respond to electric field in metals vs. circuits.

On the macroscopic level you have the London equations. They are essentially just telling what the response of the material is, kind of like ohm’s law for superconductors. You can derive the Meissner effect, the expulsion of magnetic field from inside the superconductor, from these guys.

On the microscopic level, you have BCS theory. The electrons are attracting each other, and they form bound states a little like a hydrogen atom called Cooper pairs.

In between the two, on what you might call the mesoscopic level, is Landau Ginzburg theory and Bogoliubov de Gennes. These more or less describe that the electron fluid is more or less moving as if the superconductor.

For bosons, the condensation is conceptually more straightforward. Bosons need to be in wavefunctions that are fully symmettric between the particles. If you flip any of the coordinates between particles, the wavefunction stays the same. $\psi=x_1 x_2$ for example or $\psi=e^{i k x_1 + i q x_2}+e^{i q x_1 + i k x_2}$.  It is possible for all the bosons to just be in the same wavefunction $\Psi=\psi(x_1)\psi(x_2)\psi(x_3)...$. Cool. Alright. This is a good variational wavefunction to try (the variational parameters being the entire single particle function $\psi$. Quite a lot of wiggle room! But also very constraining. Many particle physics Hilbert spaces are huge.). Maybe the bosons will like it, maybe they won’t. In what situations do they like this thing? Basically, attractive potentials. In He-4 this comes from van der Waal forces (dipole dipole forces).