Commit d4bfa426 authored by Daniel Toyra's avatar Daniel Toyra
Browse files

Merging

parents 7b6c3c17 37f2715a
before_script:
- export CWD=$(pwd)
- export PYTHONPATH=$PYTHONPATH:$CWD
# - cd /finesse
# - rm kat
# - git reset --hard
# - git checkout develop
# - git pull
# - echo "Building Finesse..."
# - ./finesse.sh --build > /dev/null 2>&1
# - echo "Sucessfuly built Finesse"
- cd $CWD
python_3:
script:
- source /setup.sh
- echo $PYTHONIOENCODING
- kat -v
- which python3
- python3 --version
- cd test
- python3 run_tests.py
python_2:
script:
- source /setup.sh
- echo $PYTHONIOENCODING
- kat -v
- which python2.7
- python2.7 --version
- cd test
- python2.7 run_tests.py
\ No newline at end of file
......@@ -22,6 +22,10 @@ to print a warning message when "extra lines" are generated
Daniel Brown 17/12/14
--------------------------------------------------------------
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import pykat
from pykat.components import *
......@@ -34,13 +38,13 @@ s s1 1 n2 n3
m m2 0.9 0.1 0 n3 n4
""")
print "Before..."
print "".join(kat.generateKatScript())
print ("Before...")
print ("".join(kat.generateKatScript()))
kat.s1.remove()
print "After remove..."
print "".join(kat.generateKatScript())
print ("After remove...")
print ("".join(kat.generateKatScript()))
# Adding in with commands
kat.parseCommands("""
......@@ -49,8 +53,8 @@ m m3 0.9 0.1 0 n2a n3a
s s3 1 n3a n3
""")
print "After add with commands..."
print "".join(kat.generateKatScript())
print ("After add with commands...")
print ("".join(kat.generateKatScript()))
kat.s2.remove()
kat.s3.remove()
......@@ -61,5 +65,5 @@ kat.add(space("s2", "n2", "n2a", L=1))
kat.add(space("s3", "n3", "n3a", L=1))
kat.add(mirror("m3", "n2a", "n3a", R=0.9, T=0.1, phi=0))
print "After add with objects..."
print "".join(kat.generateKatScript())
print ("After add with objects...")
print ("".join(kat.generateKatScript()))
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
"""
Fabry-Perot cavity scan example.
......@@ -314,14 +318,14 @@ r = kat.run()
# output the raw FINESSE file that PyKat has generated
scriptList = kat.generateKatScript()
print ''.join(scriptList)
print (''.join(scriptList))
# calculate and print cavity finesse
r1r2 = np.sqrt(parameters['cavity']['itm']['reflectivity']['inner']) * np.sqrt(parameters['cavity']['etm']['reflectivity']['inner'])
finesse = np.pi / (2 * np.arcsin((1 - r1r2) / (2 * np.sqrt(r1r2))))
print "Cavity finesse: {0:.0f}".format(finesse)
print ("Cavity finesse: {0:.0f}".format(finesse))
# create plot
pl.plot(r.x, r.y)
......
......@@ -66,6 +66,7 @@ cav cavity M_ITM_HR n_ITM_OUT M_ETM_HR n_ETM_IN
##############################
# set up a mirror rotation signal
kat.signals.f = 1
kat.signals.apply(kat.M_ETM_HR.phi, 1, 180) # amplitude = 1, phase = 180 degrees
# manually add yaxis command, as this is not implemented yet as of PyKat 0.3.1
......
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from pykat.optics.ABCD import apply, mirror_trans
from pykat.optics.gaussian_beams import gauss_param
from pykat.optics.gaussian_beams import beam_param
nr1 = 1
nr2 = 1.44963098985906
q1 = gauss_param(q=5.96343 + 3.04713j)
q1 = beam_param(q=5.96343 + 3.04713j)
abcd = mirror_trans(nr1, nr2, float("inf"))
# into material
q2 = apply(abcd, q1, nr1, nr2)
q2 = apply(abcd, q1.q, nr1, nr2)
# and out again
q3 = apply(abcd, q2, nr2, nr1)
q3 = apply(abcd, q2.q, nr2, nr1)
print "q1 =", q1, " w0 =", q1.w0, " w =", q1.w, " z =", q1.z
print "q2 =", q2, " w0 =", q2.w0, " w =", q2.w, " z =", q2.z
print "q3 =", q3, " w0 =", q3.w0, " w =", q3.w, " z =", q3.z
print ("q1 =", q1, " w0 =", q1.w0, " w =", q1.w, " z =", q1.z)
print ("q2 =", q2, " w0 =", q2.w0, " w =", q2.w, " z =", q2.z)
print ("q3 =", q3, " w0 =", q3.w0, " w =", q3.w, " z =", q3.z)
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 10 14:18:17 2013
@author: Sean
"""
import sys
sys.path.append("../")
import pykat
from pykat.optics.gaussian_beams import gauss_param
import pykat.finesse as finesse
from pykat.commands import xaxis
import pylab as pl
import numpy as np
import math
code = """
%------------------------------------------------------------------------
% Finesse input file to plot the phase of light field reflected from a
% beam splitter to show the way lengths and positions are handled
% Andreas Freise 15.08.2009
%------------------------------------------------------------------------
l l1 1 0 n1 % laser with P=1W at the default frequency
s s1 1 1 n1 n2 % space of 1m length
bs b1 1 0 0 0 n2 n3 dump dump % beam splitter as `turning mirror'
s s2 1 1 n3 n4 % another space of 1m length
ad ad1 0 n4 % amplitude detector
% for the plot we perform two sequenctial runs of Finesse
% 1) first trace: change microscopic position of beamsplitter
xaxis b1 phi lin 0 180 100
% 2) second trace: change length of space s1
% xaxis s1 L lin 1 2 100
yaxis deg % plotting the phase of the results
"""
kat = finesse.kat()
kat.parseCommands(code)
maxtem = np.arange(0, 2, 2)
kat.trace = 17
for tem in maxtem:
print "Calculating maxtem ", tem, "..."
kat.maxtem = tem
r = kat.run()
pl.plot(r.x, r.y, label="maxtem={0}".format(tem))
pl.ylabel("Phase [deg]")
pl.xlabel("Tuning [deg]")
pl.legend()
pl.show()
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from pykat import finesse
from pykat.commands import *
import copy
import pylab as pl
from collections import namedtuple
from collections import OrderedDict
import pylab as pl
from pykat.utilities.plotting.tools import printPDF
import matplotlib
formatter = matplotlib.ticker.EngFormatter(unit='', places=0)
formatter.ENG_PREFIXES[-6] = 'u'
global fig_sagnac
import matplotlib.backends.backend_pdf
def printPDF(self, filename):
pdfp = matplotlib.backends.backend_pdf.PdfPages(filename)
pdfp.savefig(self,dpi=300,bbox_inches='tight')
pdfp.close()
def main():
print """
print("""
--------------------------------------------------------------
Example file for using PyKat to automate Finesse simulations
Finesse: http://www.gwoptics.org/finesse
......@@ -19,7 +35,7 @@ def main():
Andreas Freise 30.10.2014
--------------------------------------------------------------
"""
""")
# defining variables as global for debugging
global kat
global out
......@@ -43,18 +59,11 @@ def main():
result=OrderedDict()
legend = {}
# getting mass of the light mirror of cavity a
# getting mass of the light mirror of cavity a
global m
m = kat.M1a.mass.value
# getting the anle of incidence on end mirrors:
AoI2 = float(kat.constants['AoI2'].value) / 180.*np.pi
# fsig applied to a BS with AoI!=0 reduces the phase
# change for a given signal in meters. Thus to make the
# finesse results comaptible with the default SQL we need
# to scale the results with cos(AoI):
global AoIScale
AoIScale=np.cos(AoI2)
# setting frequency range
global f
f = namedtuple('f', ('start','stop','points','data'))
f.start=100
......@@ -63,34 +72,38 @@ def main():
kat.parseKatCode('xaxis sig1 f log {0} {1} {2}'.format(f.start, f.stop, f.points-1))
# Reading Haixing Miao's reference data:
datah1=np.loadtxt('QN_Sagnac_25ppm_loss.dat')
datah2=np.loadtxt('QN_Sagnac_lossless.dat')
datah1=np.loadtxt('QN_Sagnac_lossless.dat')
datah2=np.loadtxt('QN_Sagnac_25ppm_loss.dat')
# Reading Stefan D. example data:
data=np.loadtxt('Stefan_data.txt')
print "--------------------------------------------------------"
print " Run default file (no loss)"
print ("--------------------------------------------------------")
print (" Run default file (no loss)")
out = kat.run()
#f.data = np.logspace(np.log10(f.start), np.log10(f.stop), f.points)
f.data=out.x # getting frequency vector from Finesse instead
print "--------------------------------------------------------"
print " Computing SQL"
print ("--------------------------------------------------------")
print (" Computing SQL")
hbar=6.62606957E-34/(2.0 *np.pi)
SQL_x= np.sqrt( 4 * hbar / ( m * f.data**2 * 4 * np.pi * np.pi ))
legend['SQL']=mylegend('SQL','k')
result['SQL']=SQL_x
result['default']=out.y*AoIScale
legend['default']=mylegend('Finesse, no loss','m')
result['H1']=datah1[:,1]
legend['H1']=mylegend('Haixing, no loss','k')
legend['H1']=mylegend('Haixing, no loss','g')
legend['H1'].lt='--.'
legend['H1'].lw=2
print "--------------------------------------------------------"
print " Run file with loss (or transmission) on end mirrors"
L=12.5e-6
#L=0
#T=25e-6
T=0
result['default']=out.y*np.cos(AoI2)
legend['default']=mylegend('no loss','m')
print ("--------------------------------------------------------")
L=0
T=12.5e-6
R=1-T-L
kat.M2a.R=R
kat.M3a.R=R
......@@ -105,25 +118,37 @@ def main():
kat.M2b.L=L
kat.M3b.L=L
out=kat.run()
result['loss']=out.y*AoIScale
legend['loss']=mylegend('Finesse, 25ppm loss','b')
result['H2']=datah2[:,1]
legend['H2']=mylegend('Haixing, 25ppm loss','k')
legend['H2']=mylegend('Haixing, 25ppm loss','g')
legend['H2'].lt='-.'
legend['H2'].lw=5
result['loss']=out.y*np.cos(AoI2)
legend['loss']=mylegend('25ppm loss','b')
print "--------------------------------------------------------"
print " Additional imbalanced BS"
result['bs']=imbalanced_bs(kat)*AoIScale
legend['bs']=mylegend('Imbalanced BS 49:51','r')
#result['S_sym']=data[:,1]
#legend['S_sym']=mylegend('Stefan D, balanced','k')
#legend['S_sym'].lt='-.'
print ("--------------------------------------------------------")
print (" 3. Imbalanced BS")
#result['bs']=imbalanced_bs(kat)*np.cos(AoI2)
#legend['bs']=mylegend('Imbalanced BS 49:51','r')
#result['S_imb']=data[:,2]
#legend['S_imb']=mylegend('Stefan D, imbalanced','k')
#legend['S_imb'].lt='--.'
#print "--------------------------------------------------------"
#print " Mass asymmetry"
#result['mass']=mass(kat)*AoIScale
print ("--------------------------------------------------------")
print (" 3. Mass asymmetry")
#result['mass']=mass(kat)
#legend['mass']=mylegend('Mass asymmetry 10%','c')
print "--------------------------------------------------------"
print " Plotting results"
print ("--------------------------------------------------------")
print (" Plotting results")
plot_results(f, result, legend)
......@@ -180,7 +205,7 @@ def plot_results(f, result, legend):
pl.legend(loc=1)
pl.draw()
pl.show(block=0)
printPDF(fig, "speedmeter_plots.pdf")
#printPDF(fig, "speedmeter_plots.pdf")
if __name__ == '__main__':
......
......@@ -6,20 +6,20 @@
# Andreas Freise, 30.10.2014
#
# The parameters below don't necessarily match the current
# speedmeter design, instead they were chosen to fit an example
# file from Stefan Danilishin. However, you can easily change
# the parameters to an updated design without problem.
# speedmeter design, instead they were chosen to match Stefan
# Danilishin's Matlab example for comparison. However, you can
# easily change the parameters to an updated design without
# problem. No special tuning or so is required.
#################################################################
## general constants
const Pin 0.6 # double the power at the BS, which for this example is 0.3W
const MassM1 1m # Mass M1 in [kg]: 1 gramm
const MassM23 100 # Mass M2, M3: 100 gramm
const MassM23 100m # Mass M2, M3: 100 gramm
const T_ETM 0u # transmission of cavity end mirrors (cavity loss)
const L_ETM 0u # loss of cavity end mirrors (cavity loss)
const AoI 0 # angle of incidence on input mirror (4.4 deg)
const AoI2 0 # angle of incidence on end mirror (42.8 deg)
const AoI2 42.8
## lengths of some ray segments
const lrs2 0.250
......@@ -53,12 +53,10 @@ s rs7 $lrs7 nM6e nM7w
bs M7 1 0 0 49.39870535E0 nM7w nM7n dump dump
s rs8 $lrs8 nM7n nM1an
#attr M1a backscatter 0.6u
bs1 M1a 500u 0 0 $AoI nM1aw nM1an nM1ae nM1as
bs1 M1a 500u 0 0 4.4 nM1aw nM1an nM1ae nM1as
attr M1a Rc -7.91
attr M1a mass $MassM1
s rs12 0.6575 nM3an nM1ae
s rs12 1.315 nM3an nM1ae
bs1 M3a $T_ETM $L_ETM 0 $AoI2 nM3aw nM3an nM3aT1 nM3aT2
attr M3a mass $MassM23
s rs11 0.2 1. nM2an nM3aw
......@@ -81,8 +79,7 @@ s rs26 $lrs26 nM8n nM1bw
#################################################################
## Cavity b
#attr M1b backscatter 0.6u
bs1 M1b 500u 0 0 $AoI nM1bw nM1bn nM1be nM1bs
bs1 M1b 500u 0 0 4.4 nM1bw nM1bn nM1be nM1bs
attr M1b Rc -7.91
attr M1b mass $MassM1
s rs19 1.315 nM1be nM2bw
......@@ -115,11 +112,11 @@ s sl2 1n nl2 nl3
bs dHD .5 .5 0 0 nHD1 nout1 nout2 nl3
# homodyne detector, use 180 deg phase for normal use, i.e. output=nout1-nout2
qhdS sens 180 nout1 nout2
# re-scaling output to m/sqrt(Hz)
scale meter sens
#qhdS sens 180 nout1 nout2
# scale output to m/sqrt(Hz)
#scale meter sens
xaxis sig1 f log 100 100k 99
%xaxis sig1 f log 100 100k 99
yaxis log abs
maxtem off
......
......@@ -3,7 +3,7 @@ from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
__version__ = "1.0.4"
__version__ = "1.0.6"
# This flag is used to switch on the gui features in pkat at import time
USE_GUI = False
......
......@@ -9,15 +9,22 @@ if six.PY2:
import os, sys
def PrintError(message, exception):
size = 60
size = 62
print("\033[91m")
try:
from textwrap import wrap, fill
print ("-" * size)
for a in wrap(message, size): print(a)
for a in wrap(str(exception.msg), size): print(a)
for a in wrap(message, size):
print(a)
for a in wrap(str(exception.msg), size):
a = a.replace("*** ", "\n")
a = a.replace("** ", "\n")
print(a)
print ("-" * size)
finally:
print ("\033[0m")
......
......@@ -28,6 +28,7 @@ from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import codecs
import uuid
import sys
import os
......@@ -1503,7 +1504,7 @@ class kat(object):
try:
if time.time() < _start_kat + duration:
time.sleep(0.1)
fifo = open(pipe_name, "r")
fifo = codecs.open(pipe_name, "r", "utf-8")
self.__looking = False
else:
raise pkex.BasePyKatException("Could not connect to pykat pipe in {0} seconds. Ensure you are using Finesse >= v2.1 and Pykat >= v1.0.0.".format(duration))
......@@ -1515,8 +1516,8 @@ class kat(object):
for line in fifo:
if (sys.version_info < (3, 0)):
line = line.decode("utf8") # Make sure we're using unicode encoding
#if (sys.version_info < (3, 0)):
# line = line.decode("utf8") # Make sure we're using unicode encoding
v = line.split(u":", 1)
......@@ -1540,16 +1541,18 @@ class kat(object):
(stdout, stderr) = p.communicate()
r.stdout = stdout.decode('unicode_escape')
r.stderr = stderr.decode('unicode_escape')
r.stdout = stdout.decode('utf-8')
r.stderr = stderr.decode('utf-8')
for line in r.stdout[::-1]:
if line.lstrip().startswith('computation time:'):
try:
r.runtime = float(line.split(":")[1].replace("s",""))
except:
r.runtime = 0.0
k = r.stdout.rfind('computation time:')
if k > 0:
try:
line = r.stdout[k:]
r.runtime = float(line.split(":")[1].replace("s",""))
except:
r.runtime = 0.0
r.runDateTime = datetime.datetime.now()
# If Finesse returned an error, just print that and exit!
......
......@@ -20,11 +20,34 @@ from pykat.maths.hermite import *
from pykat.maths import newton_weights
from scipy.integrate import newton_cotes
from multiprocessing import Process, Queue, Array, Value, Event
from pykat.exceptions import BasePyKatException
EmpiricalInterpolant = collections.namedtuple('EmpiricalInterpolant', 'B nodes node_indices limits x worst_error')
ReducedBasis = collections.namedtuple('ReducedBasis', 'RB limits x')
ROMLimits = collections.namedtuple('ROMLimits', 'zmin zmax w0min w0max R mapSamples max_order')
def read_EI(filename, verbose=True):
import pickle
with open(filename, "rb") as file:
ei = pickle.load(file)
if verbose:
print("Map data this ROM was made for in one dimension:")
print(" Map separation dx = " + str(ei.x[1]-ei.x[0]))
print(" x range = -{0}m to {0}m".format(max(abs(ei.x))))
print(" Data points = " + str(ei.x.size * 2))
print("")
print("Parameter limits:")
print(" w0 = {0}m to {1}m".format(ei.limits.w0min, ei.limits.w0max))
print(" z = {0}m to {1}m".format(ei.limits.zmin, ei.limits.zmax))
print(" max order = {0}".format(ei.limits.max_order))
print("")
print("ROM contains {0} basis modes".format(ei.nodes.shape[0]))
return ei
class ROMWeights:
def __init__(self, w_ij_Q1, w_ij_Q2, w_ij_Q3, w_ij_Q4, EIx, EIy, nr1=1, nr2=1, direction="reflection_front"):
......@@ -566,6 +589,12 @@ def makeWeightsNew(smap, EIxFilename, EIyFilename=None, verbose=True, newtonCote
wy[ym == 0] = 0.5
W = np.outer(wx, wy)
if A_xy_Q1.shape != W.shape or \
A_xy_Q2.shape != W.shape or \
A_xy_Q3.shape != W.shape or \
A_xy_Q4.shape != W.shape:
raise BasePyKatException("Map data points do not overlap exactly with data points this EI was made for. Consider using the `intepolate=True` option.")
# make integration weights
Bx = EIx.B
By = EIy.B[:,::-1]
......
......@@ -217,7 +217,7 @@ class FinesseTestProcess(Thread):
shutil.rmtree(BUILD_PATH)
print "Checking out finesse base..."
utils.git(["clone","git://gitmaster.atlas.aei.uni-hannover.de/finesse/finesse.git", BUILD_PATH])
utils.git(["clone","https://gitlab.aei.uni-hannover.de/finesse/finesse.git", BUILD_PATH])
print "Checking out and building develop version of finesse " + self.git_commit
......
......@@ -32,7 +32,7 @@ def start(instance_path,port=5000, debug=True, ip="0.0.0.0", git_bin="/usr/bin/g
# need local copy of src
if not os.path.exists(os.path.join(app.instance_path,"finesse_src")):
print "finesse src folder didn't exist, cloning now..."
utils.git(["clone","git://gitmaster.atlas.aei.uni-hannover.de/finesse/finesse.git","finesse_src"])
utils.git(["clone","https://gitlab.aei.uni-hannover.de/finesse/finesse.git","finesse_src"])
else:
# get the latest version for logs etc.
utils.git("pull", cwd=os.path.join(app.instance_path,"finesse_src"))
......
import pykat
import traceback
import os
import sys
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'