<commit_before>import numpy as np
from RayTracePixels import *
from Model_objs import SIELens,ExternalShear,GaussSource
from SourceProfile import SourceProfile
import matplotlib.pyplot as pl
import matplotlib.cm as cm
from matplotlib.widgets import Slider,Button
from astropy.cosmology import get_current,set_current
set_current('WMAP9')
cosmo = get_current()

xim = np.arange(-2,2,.005)
yim = np.arange(-2,2,.005)
#xim = np.arange(4.0,8.0,0.015)
#yim = np.arange(-2.5,-6.5,-0.015)

xim,yim = np.meshgrid(xim,yim)

zLens,zSource = 0.8,5.656
xLens,yLens = 0.,0.
MLens,eLens,PALens = 2.87e11,0.54,180-96.4
xSource,ySource,FSource,sSource = 0.216,0.24,0.023,0.074
#xSource,ySource,FSource,sSource = 0.090,0.141,0.0185,0.111

#xSource,ySource = 0.203,0.289
#FSource,sSource = 0.01925,0.097
#xSblue,ySblue = 0.144,0.300
#FSblue,sSblue = 0.273e-3,0.148
#xSred,ySred = 0.051,0.182
#FSred,sSred = 0.176e-3, 0.097
#xSource,ySource, sSource = xSred,ySred,sSred

Lens = SIELens(zLens,xLens,yLens,MLens,eLens,PALens)
Source = GaussSource(zSource,True,xSource,ySource,FSource,sSource)
Shear = ExternalShear(0.0,0.)
Dd = cosmo.angular_diameter_distance(zLens).value
Ds = cosmo.angular_diameter_distance(zSource).value
Dds = cosmo.angular_diameter_distance_z1z2(zLens,zSource).value

xsource,ysource = LensRayTrace(xim,yim,Lens,Dd,Ds,Dds,shear=Shear)

imbg = SourceProfile(xim,yim,Source,Lens)
imlensed = SourceProfile(xsource,ysource,Source,Lens)
caustics = CausticsSIE(Lens,Dd,Ds,Dds,Shear)

f = pl.figure(figsize=(12,6))
ax = f.add_subplot(111,aspect='equal')
pl.subplots_adjust(right=0.48,top=0.97,bottom=0.03,left=0.05)

cmbg = cm.cool
cmbg._init()
cmbg._lut[0,-1] = 0.

cmlens = cm.gist_heat_r
cmlens._init()
cmlens._lut[0,-1] = 0.

ax.imshow(imbg,cmap=cmbg,extent=[xim.min(),xim.max(),yim.min(),yim.max()],origin='lower')
ax.imshow(imlensed,cmap=cmlens,extent=[xim.min(),xim.max(),yim.min(),yim.max()],origin='lower')

for i in range(caustics.shape[0]):
      ax.plot(caustics[i,0,:],caustics[i,1,:],'k-')

# Put in a bunch of sliders to control lensing parameters

axcolor='lightgoldenrodyellow'
ytop,ystep = 0.9,0.05
axzL = pl.axes([0.56,ytop,0.4,0.03],axisbg=axcolor)
axzS = pl.axes([0.56,ytop-ystep,0.4,0.03],axisbg=axcolor)
axxL = pl.axes([0.56,ytop-2*ystep,0.4,0.03],axisbg=axcolor)
axyL = pl.axes([0.56,ytop-3*ystep,0.4,0.03],axisbg=axcolor)
axML = pl.axes([0.56,ytop-4*ystep,0.4,0.03],axisbg=axcolor)
axeL = pl.axes([0.56,ytop-5*ystep,0.4,0.03],axisbg=axcolor)
axPAL= pl.axes([0.56,ytop-6*ystep,0.4,0.03],axisbg=axcolor)
axss = pl.axes([0.56,ytop-7*ystep,0.4,0.03],axisbg=axcolor)
axsa = pl.axes([0.56,ytop-8*ystep,0.4,0.03],axisbg=axcolor)
axxS = pl.axes([0.56,ytop-9*ystep,0.4,0.03],axisbg=axcolor)
axyS = pl.axes([0.56,ytop-10*ystep,0.4,0.03],axisbg=axcolor)
axFS = pl.axes([0.56,ytop-11*ystep,0.4,0.03],axisbg=axcolor)
axwS = pl.axes([0.56,ytop-12*ystep,0.4,0.03],axisbg=axcolor)

slzL = Slider(axzL,"z$_{Lens}$",0.01,3.0,valinit=zLens)
slzS = Slider(axzS,"z$_{Source}$",slzL.val,10.0,valinit=zSource)
slxL = Slider(axxL,"x$_{Lens}$",-1.5,1.5,valinit=xLens)
slyL = Slider(axyL,"y$_{Lens}$",-1.5,1.5,valinit=yLens)
slML = Slider(axML,"log(M$_{Lens}$)",10.,12.5,valinit=np.log10(MLens))
sleL = Slider(axeL,"e$_{Lens}$",0.,1.,valinit=eLens)
slPAL= Slider(axPAL,"PA$_{Lens}$",0.,180.,valinit=PALens)
slss = Slider(axss,"Shear",0.,1.,valinit=Shear.shear['value'])
slsa = Slider(axsa,"Angle",0.,180.,valinit=Shear.shearangle['value'])
slxs = Slider(axxS,"x$_{Source}$",-1.5,1.5,valinit=xSource)
slys = Slider(axyS,"y$_{Source}$",-1.5,1.5,valinit=ySource)
slFs = Slider(axFS,"S$_{Source}$",0.01,1.,valinit=FSource)
slws = Slider(axwS,"$\sigma_{Source}$",0.001,0.3,valinit=sSource)

def update(val):
      zL,zS = slzL.val,slzS.val
      xL,yL = slxL.val, slyL.val
      ML,eL,PAL = slML.val,sleL.val,slPAL.val
      sh,sha = slss.val,slsa.val
      xs,ys = slxs.val, slys.val
      Fs,ws = slFs.val, slws.val
      newDd = cosmo.angular_diameter_distance(zL).value
      newDs = cosmo.angular_diameter_distance(zS).value
      newDds= cosmo.angular_diameter_distance_z1z2(zL,zS).value
      newLens = SIELens(zLens,xL,yL,10**ML,eL,PAL)
      newShear = ExternalShear(sh,sha)
      newSource = GaussSource(zS,True,xs,ys,Fs,ws)
      xs,ys = LensRayTrace(xim,yim,newLens,newDd,newDs,newDds,newShear)
      imbg = SourceProfile(xim,yim,newSource,newLens)
      imlensed = SourceProfile(xs,ys,newSource,newLens)
      caustics = CausticsSIE(newLens,Dd,Ds,Dds,newShear)

      ax.cla()

      ax.imshow(imbg,cmap=cmbg,extent=[xim.min(),xim.max(),yim.min(),yim.max()],origin='lower')
      ax.imshow(imlensed,cmap=cmlens,extent=[xim.min(),xim.max(),yim.min(),yim.max()],origin='lower')

      for i in range(caustics.shape[0]):
            ax.plot(caustics[i,0,:],caustics[i,1,:],'k-')

      f.canvas.draw_idle()

slzL.on_changed(update); slzS.on_changed(update)
slxL.on_changed(update); slyL.on_changed(update)
slML.on_changed(update); sleL.on_changed(update); slPAL.on_changed(update)
slss.on_changed(update); slsa.on_changed(update)
slxs.on_changed(update); slys.on_changed(update)
slFs.on_changed(update); slws.on_changed(update)

resetax = pl.axes([0.56,ytop-14*ystep,0.08,0.04])
resbutton = Button(resetax,'Reset',color=axcolor,hovercolor='0.975')
def reset(event):
      slzL.reset(); slzS.reset()
      slxL.reset(); slyL.reset()
      slML.reset(); sleL.reset(); slPAL.reset()
      slss.reset(); slsa.reset()
      slxs.reset(); slys.reset()
      slFs.reset(); slws.reset()
resbutton.on_clicked(reset)

#spt0346ax = pl.axes([0.56,ytop-15*ystep,0.08,0.04])
#s0346button = Button(spt0346ax,'SPT0346-52',color=axcolor,hovercolor='0.975')

sptsources = {
      'SPT0346-52':{'zL':0.8,'zS':5.6556,'xL':0.,'yL':0.,'ML':np.log10(3.73e11),'eL':0.55,'PAL':83.5,
                    'ss':0.,'sa':0.,'xS':0.245,'yS':0.285,'FS':0.023,'ws':0.085}}

def switchsource(sd):
      slzL.set_val(sd['zL']); slzS.set_val(sd['zS'])
      slxL.set_val(sd['xL']); slyL.set_val(sd['yL'])
      slML.set_val(sd['ML']); sleL.set_val(sd['eL']); slPAL.set_val(sd['PAL'])
      slss.set_val(sd['ss']); slsa.set_val(sd['sa'])
      slxs.set_val(sd['xS']); slys.set_val(sd['yS'])
      slFs.set_val(sd['FS']); slws.set_val(sd['ws'])

#s0346button.on_clicked(switchsource(sptsources['SPT0346-52']))

pl.show()
<commit_msg>altered for new coord convention<commit_after>import numpy as np
from RayTracePixels import *
from Model_objs import *
from SourceProfile import SourceProfile
import matplotlib.pyplot as pl
import matplotlib.cm as cm
from matplotlib.widgets import Slider,Button
from astropy.cosmology import get_current,set_current
set_current('WMAP9')
cosmo = get_current()

xim = np.arange(-2,2,.005)
yim = np.arange(-2,2,.005)
#xim = np.arange(4.0,8.0,0.015)
#yim = np.arange(-2.5,-6.5,-0.015)

xim,yim = np.meshgrid(xim,yim)

zLens,zSource = 0.8,5.656
xLens,yLens = 0.,0.
MLens,eLens,PALens = 2.87e11,0.54,180-96.4
xSource,ySource,FSource,sSource = 0.216,0.24,0.023,0.074
#xSource,ySource,FSource,sSource = 0.090,0.141,0.0185,0.111

#xSource,ySource = 0.203,0.289
#FSource,sSource = 0.01925,0.097
#xSblue,ySblue = 0.144,0.300
#FSblue,sSblue = 0.273e-3,0.148
#xSred,ySred = 0.051,0.182
#FSred,sSred = 0.176e-3, 0.097
#xSource,ySource, sSource = xSred,ySred,sSred

Lens = SIELens(zLens,xLens,yLens,MLens,eLens,PALens)
Source = GaussSource(zSource,True,xSource,ySource,FSource,sSource)
Shear = ExternalShear(0.0,0.)
Dd = cosmo.angular_diameter_distance(zLens).value
Ds = cosmo.angular_diameter_distance(zSource).value
Dds = cosmo.angular_diameter_distance_z1z2(zLens,zSource).value

xsource,ysource = LensRayTrace(xim,yim,Lens,Dd,Ds,Dds,shear=Shear)

imbg = SourceProfile(xim,yim,Source,Lens)
imlensed = SourceProfile(xsource,ysource,Source,Lens)
caustics = CausticsSIE(Lens,Dd,Ds,Dds,Shear)

f = pl.figure(figsize=(12,6))
ax = f.add_subplot(111,aspect='equal')
pl.subplots_adjust(right=0.48,top=0.97,bottom=0.03,left=0.05)

cmbg = cm.cool
cmbg._init()
cmbg._lut[0,-1] = 0.

cmlens = cm.gist_heat_r
cmlens._init()
cmlens._lut[0,-1] = 0.

ax.imshow(imbg,cmap=cmbg,extent=[xim.min(),xim.max(),yim.min(),yim.max()],origin='lower')
ax.imshow(imlensed,cmap=cmlens,extent=[xim.min(),xim.max(),yim.min(),yim.max()],origin='lower')

for i in range(caustics.shape[0]):
      ax.plot(caustics[i,0,:],caustics[i,1,:],'k-')

# Put in a bunch of sliders to control lensing parameters

axcolor='lightgoldenrodyellow'
ytop,ystep = 0.9,0.05
axzL = pl.axes([0.56,ytop,0.4,0.03],axisbg=axcolor)
axzS = pl.axes([0.56,ytop-ystep,0.4,0.03],axisbg=axcolor)
axxL = pl.axes([0.56,ytop-2*ystep,0.4,0.03],axisbg=axcolor)
axyL = pl.axes([0.56,ytop-3*ystep,0.4,0.03],axisbg=axcolor)
axML = pl.axes([0.56,ytop-4*ystep,0.4,0.03],axisbg=axcolor)
axeL = pl.axes([0.56,ytop-5*ystep,0.4,0.03],axisbg=axcolor)
axPAL= pl.axes([0.56,ytop-6*ystep,0.4,0.03],axisbg=axcolor)
axss = pl.axes([0.56,ytop-7*ystep,0.4,0.03],axisbg=axcolor)
axsa = pl.axes([0.56,ytop-8*ystep,0.4,0.03],axisbg=axcolor)
axxS = pl.axes([0.56,ytop-9*ystep,0.4,0.03],axisbg=axcolor)
axyS = pl.axes([0.56,ytop-10*ystep,0.4,0.03],axisbg=axcolor)
axFS = pl.axes([0.56,ytop-11*ystep,0.4,0.03],axisbg=axcolor)
axwS = pl.axes([0.56,ytop-12*ystep,0.4,0.03],axisbg=axcolor)

slzL = Slider(axzL,"z$_{Lens}$",0.01,3.0,valinit=zLens)
slzS = Slider(axzS,"z$_{Source}$",slzL.val,10.0,valinit=zSource)
slxL = Slider(axxL,"x$_{Lens}$",-1.5,1.5,valinit=xLens)
slyL = Slider(axyL,"y$_{Lens}$",-1.5,1.5,valinit=yLens)
slML = Slider(axML,"log(M$_{Lens}$)",10.,12.5,valinit=np.log10(MLens))
sleL = Slider(axeL,"e$_{Lens}$",0.,1.,valinit=eLens)
slPAL= Slider(axPAL,"PA$_{Lens}$",0.,180.,valinit=PALens)
slss = Slider(axss,"Shear",0.,1.,valinit=Shear.shear['value'])
slsa = Slider(axsa,"Angle",0.,180.,valinit=Shear.shearangle['value'])
slxs = Slider(axxS,"x$_{Source}$",-1.5,1.5,valinit=xSource)
slys = Slider(axyS,"y$_{Source}$",-1.5,1.5,valinit=ySource)
slFs = Slider(axFS,"S$_{Source}$",0.01,1.,valinit=FSource)
slws = Slider(axwS,"$\sigma_{Source}$",0.001,0.3,valinit=sSource)

def update(val):
      zL,zS = slzL.val,slzS.val
      xL,yL = slxL.val, slyL.val
      ML,eL,PAL = slML.val,sleL.val,slPAL.val
      sh,sha = slss.val,slsa.val
      xs,ys = slxs.val, slys.val
      Fs,ws = slFs.val, slws.val
      newDd = cosmo.angular_diameter_distance(zL).value
      newDs = cosmo.angular_diameter_distance(zS).value
      newDds= cosmo.angular_diameter_distance_z1z2(zL,zS).value
      newLens = SIELens(zLens,xL,yL,10**ML,eL,PAL)
      newShear = ExternalShear(sh,sha)
      newSource = GaussSource(zS,True,xs,ys,Fs,ws)
      xs,ys = LensRayTrace(xim,yim,newLens,newDd,newDs,newDds,newShear)
      imbg = SourceProfile(xim,yim,newSource,newLens)
      imlensed = SourceProfile(xs,ys,newSource,newLens)
      caustics = CausticsSIE(newLens,Dd,Ds,Dds,newShear)

      ax.cla()

      ax.imshow(imbg,cmap=cmbg,extent=[xim.min(),xim.max(),yim.min(),yim.max()],origin='lower')
      ax.imshow(imlensed,cmap=cmlens,extent=[xim.min(),xim.max(),yim.min(),yim.max()],origin='lower')

      for i in range(caustics.shape[0]):
            ax.plot(caustics[i,0,:],caustics[i,1,:],'k-')

      f.canvas.draw_idle()

slzL.on_changed(update); slzS.on_changed(update)
slxL.on_changed(update); slyL.on_changed(update)
slML.on_changed(update); sleL.on_changed(update); slPAL.on_changed(update)
slss.on_changed(update); slsa.on_changed(update)
slxs.on_changed(update); slys.on_changed(update)
slFs.on_changed(update); slws.on_changed(update)

resetax = pl.axes([0.56,ytop-14*ystep,0.08,0.04])
resbutton = Button(resetax,'Reset',color=axcolor,hovercolor='0.975')
def reset(event):
      slzL.reset(); slzS.reset()
      slxL.reset(); slyL.reset()
      slML.reset(); sleL.reset(); slPAL.reset()
      slss.reset(); slsa.reset()
      slxs.reset(); slys.reset()
      slFs.reset(); slws.reset()
resbutton.on_clicked(reset)

#spt0346ax = pl.axes([0.56,ytop-15*ystep,0.08,0.04])
#s0346button = Button(spt0346ax,'SPT0346-52',color=axcolor,hovercolor='0.975')

sptsources = {
      'SPT0346-52':{'zL':0.8,'zS':5.6556,'xL':0.,'yL':0.,'ML':np.log10(3.73e11),'eL':0.55,'PAL':83.5,
                    'ss':0.,'sa':0.,'xS':0.245,'yS':0.285,'FS':0.023,'ws':0.085}}

def switchsource(sd):
      slzL.set_val(sd['zL']); slzS.set_val(sd['zS'])
      slxL.set_val(sd['xL']); slyL.set_val(sd['yL'])
      slML.set_val(sd['ML']); sleL.set_val(sd['eL']); slPAL.set_val(sd['PAL'])
      slss.set_val(sd['ss']); slsa.set_val(sd['sa'])
      slxs.set_val(sd['xS']); slys.set_val(sd['yS'])
      slFs.set_val(sd['FS']); slws.set_val(sd['ws'])

#s0346button.on_clicked(switchsource(sptsources['SPT0346-52']))

pl.show()
<|endoftext|>


<commit_before># -*- python -*-
#
# Git Version: @git@

#-----------------------------------------------------------------------
# XALT: A tool that tracks users jobs and environments on a cluster.
# Copyright (C) 2013-2014 University of Texas at Austin
# Copyright (C) 2013-2014 University of Tennessee
#
# This library is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as
# published by the Free Software Foundation; either version 2.1 of
# the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser  General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free
# Software Foundation, Inc., 59 Temple Place, Suite 330,
# Boston, MA 02111-1307 USA
#-----------------------------------------------------------------------

from __future__             import print_function
import os, sys

dirNm, execName = os.path.split(os.path.realpath(sys.argv[0]))
sys.path.insert(1,os.path.abspath(os.path.join(dirNm, "../libexec")))

from xalt_parse_mpirun_args import find_exec

ignoreT = {
  'env'              : True,
  'perf'             : True,
  'stat'             : True,
  'numactl'          : True,
  'tacc_affinity'    : True,
  'tacc_xrun'        : True,
  'time'             : True,
}

argT = {
  '-2'                        : 1,
  '-m'                        : 1,
  '-o'                        : 1,
  '-c'                        : 1,
}

npT = {
  '-n'                        : "tasks",
  '-np'                       : "tasks",
  }

def compute_ntasks(t):
  tasks = t.get("tasks")
  nodes = t.get("nodes")
  if (not tasks):
    if (not nodes):
      tasks = 1
    elif (not os.environ.get("SLURM_JOBID")):
      tasks = 1
    if (nodes == 1):
      tasks = 1
    else:
      nodes = nodes or 1
      tasks = os.environ.get("SLURM_CPUS_ON_NODE",1)*nodes
  return tasks

def main():
  """
  Find name of executable when using ibrun.
  """

  print(find_exec(ignoreT, argT, npT, "-c", sys.argv[1:]),
                  compute_ntasks=compute_ntasks))

if ( __name__ == '__main__'): main()
<commit_msg>typo )) -> )<commit_after># -*- python -*-
#
# Git Version: @git@

#-----------------------------------------------------------------------
# XALT: A tool that tracks users jobs and environments on a cluster.
# Copyright (C) 2013-2014 University of Texas at Austin
# Copyright (C) 2013-2014 University of Tennessee
#
# This library is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as
# published by the Free Software Foundation; either version 2.1 of
# the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser  General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free
# Software Foundation, Inc., 59 Temple Place, Suite 330,
# Boston, MA 02111-1307 USA
#-----------------------------------------------------------------------

from __future__             import print_function
import os, sys

dirNm, execName = os.path.split(os.path.realpath(sys.argv[0]))
sys.path.insert(1,os.path.abspath(os.path.join(dirNm, "../libexec")))

from xalt_parse_mpirun_args import find_exec

ignoreT = {
  'env'              : True,
  'perf'             : True,
  'stat'             : True,
  'numactl'          : True,
  'tacc_affinity'    : True,
  'tacc_xrun'        : True,
  'time'             : True,
}

argT = {
  '-2'                        : 1,
  '-m'                        : 1,
  '-o'                        : 1,
  '-c'                        : 1,
}

npT = {
  '-n'                        : "tasks",
  '-np'                       : "tasks",
  }

def compute_ntasks(t):
  tasks = t.get("tasks")
  nodes = t.get("nodes")
  if (not tasks):
    if (not nodes):
      tasks = 1
    elif (not os.environ.get("SLURM_JOBID")):
      tasks = 1
    if (nodes == 1):
      tasks = 1
    else:
      nodes = nodes or 1
      tasks = os.environ.get("SLURM_CPUS_ON_NODE",1)*nodes
  return tasks

def main():
  """
  Find name of executable when using ibrun.
  """

  print(find_exec(ignoreT, argT, npT, "-c", sys.argv[1:]),
                  compute_ntasks=compute_ntasks)

if ( __name__ == '__main__'): main()
<|endoftext|>


<commit_before># Copyright 2017 Google Inc. and Skytruth Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from __future__ import absolute_import, division
import argparse
import json
from . import abstract_models
from . import layers
from classification import utility
from classification.objectives import (
    TrainNetInfo, MultiClassificationObjectiveSmoothed, LogRegressionObjectiveMAE)
import logging
import math
import numpy as np
import os

import tensorflow as tf
import tensorflow.contrib.slim as slim
import tensorflow.contrib.metrics as metrics

class Model(abstract_models.MisconceptionModel):

    window_size = 3
    feature_depths = [48, 64, 96, 128, 192, 256, 384, 512, 768]
    strides = [2] * 9
    assert len(strides) == len(feature_depths)
    feature_sub_depths = 1024

    initial_learning_rate = 10e-5
    learning_decay_rate = 0.5
    decay_examples = 100000

    @property
    def number_of_steps(self):
        return 800000

    @property
    def max_window_duration_seconds(self):
        return 180 * 24 * 3600

    @property
    def window_max_points(self):
        nominal_max_points = (self.max_window_duration_seconds / (5 * 60)) / 4
        layer_reductions = np.prod(self.strides)
        final_size = int(round(nominal_max_points / layer_reductions))
        max_points = final_size * layer_reductions
        logging.info('Using %s points', max_points)
        return max_points

    @property
    def min_viable_timeslice_length(self):
        return 500

    def __init__(self, num_feature_dimensions, vessel_metadata, metrics):
        super(Model, self).__init__(num_feature_dimensions, vessel_metadata)

        class XOrNone:
            def __init__(self, key):
                self.key = key

            def __call__(self, mmsi):
                x = vessel_metadata.vessel_label(self.key, mmsi)
                if x == '':
                    return None
                return np.float32(x)

        self.training_objectives = [
            LogRegressionObjectiveMAE(
                'length',
                'Vessel-length',
                XOrNone('length'),
                metrics=metrics,
                loss_weight=0.1),
            LogRegressionObjectiveMAE(
                'tonnage',
                'Vessel-tonnage',
                XOrNone('tonnage'),
                metrics=metrics,
                loss_weight=0.1),
            LogRegressionObjectiveMAE(
                'engine_power',
                'Vessel-engine-Power',
                XOrNone('engine_power'),
                metrics=metrics,
                loss_weight=0.1),
            LogRegressionObjectiveMAE(
                'crew_size',
                'Vessel-Crew-Size',
                XOrNone('crew_size'),
                metrics=metrics,
                loss_weight=0.1),
            MultiClassificationObjectiveSmoothed(
                "Multiclass", "Vessel-class", vessel_metadata, metrics=metrics, loss_weight=1,
                smoothing_coefficient=0.01)
        ]

    def _build_model(self, features, timestamps, mmsis, is_training):
        outputs, _ = layers.misconception_model(
            features,
            self.window_size,
            self.feature_depths,
            self.strides,
            self.training_objectives,
            is_training,
            sub_count=self.feature_sub_depths,
            sub_layers=2)
        return outputs

    def build_training_net(self, features, timestamps, mmsis):
        self._build_model(features, timestamps, mmsis, is_training=True)

        trainers = []
        for i in range(len(self.training_objectives)):
            trainers.append(self.training_objectives[i].build_trainer(
                timestamps, mmsis))

        learning_rate = tf.train.exponential_decay(
            self.initial_learning_rate, slim.get_or_create_global_step(),
            self.decay_examples, self.learning_decay_rate)

        optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate)

        return TrainNetInfo(optimizer, trainers)

    def build_inference_net(self, features, timestamps, mmsis):
        self._build_model(features, timestamps, mmsis, is_training=False)

        evaluations = []
        for i in range(len(self.training_objectives)):
            to = self.training_objectives[i]
            evaluations.append(to.build_evaluation(timestamps, mmsis))

        return evaluations
<commit_msg>disable crew size<commit_after># Copyright 2017 Google Inc. and Skytruth Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from __future__ import absolute_import, division
import argparse
import json
from . import abstract_models
from . import layers
from classification import utility
from classification.objectives import (
    TrainNetInfo, MultiClassificationObjectiveSmoothed, LogRegressionObjectiveMAE)
import logging
import math
import numpy as np
import os

import tensorflow as tf
import tensorflow.contrib.slim as slim
import tensorflow.contrib.metrics as metrics

class Model(abstract_models.MisconceptionModel):

    window_size = 3
    feature_depths = [48, 64, 96, 128, 192, 256, 384, 512, 768]
    strides = [2] * 9
    assert len(strides) == len(feature_depths)
    feature_sub_depths = 1024

    initial_learning_rate = 10e-5
    learning_decay_rate = 0.5
    decay_examples = 100000

    @property
    def number_of_steps(self):
        return 800000

    @property
    def max_window_duration_seconds(self):
        return 180 * 24 * 3600

    @property
    def window_max_points(self):
        nominal_max_points = (self.max_window_duration_seconds / (5 * 60)) / 4
        layer_reductions = np.prod(self.strides)
        final_size = int(round(nominal_max_points / layer_reductions))
        max_points = final_size * layer_reductions
        logging.info('Using %s points', max_points)
        return max_points

    @property
    def min_viable_timeslice_length(self):
        return 500

    def __init__(self, num_feature_dimensions, vessel_metadata, metrics):
        super(Model, self).__init__(num_feature_dimensions, vessel_metadata)

        class XOrNone:
            def __init__(self, key):
                self.key = key

            def __call__(self, mmsi):
                x = vessel_metadata.vessel_label(self.key, mmsi)
                if x == '':
                    return None
                return np.float32(x)

        self.training_objectives = [
            LogRegressionObjectiveMAE(
                'length',
                'Vessel-length',
                XOrNone('length'),
                metrics=metrics,
                loss_weight=0.1),
            LogRegressionObjectiveMAE(
                'tonnage',
                'Vessel-tonnage',
                XOrNone('tonnage'),
                metrics=metrics,
                loss_weight=0.1),
            LogRegressionObjectiveMAE(
                'engine_power',
                'Vessel-engine-Power',
                XOrNone('engine_power'),
                metrics=metrics,
                loss_weight=0.1),
            # LogRegressionObjectiveMAE(
            #     'crew_size',
            #     'Vessel-Crew-Size',
            #     XOrNone('crew_size'),
            #     metrics=metrics,
            #     loss_weight=0.1),
            MultiClassificationObjectiveSmoothed(
                "Multiclass", "Vessel-class", vessel_metadata, metrics=metrics, loss_weight=1,
                smoothing_coefficient=0.01)
        ]

    def _build_model(self, features, timestamps, mmsis, is_training):
        outputs, _ = layers.misconception_model(
            features,
            self.window_size,
            self.feature_depths,
            self.strides,
            self.training_objectives,
            is_training,
            sub_count=self.feature_sub_depths,
            sub_layers=2)
        return outputs

    def build_training_net(self, features, timestamps, mmsis):
        self._build_model(features, timestamps, mmsis, is_training=True)

        trainers = []
        for i in range(len(self.training_objectives)):
            trainers.append(self.training_objectives[i].build_trainer(
                timestamps, mmsis))

        learning_rate = tf.train.exponential_decay(
            self.initial_learning_rate, slim.get_or_create_global_step(),
            self.decay_examples, self.learning_decay_rate)

        optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate)

        return TrainNetInfo(optimizer, trainers)

    def build_inference_net(self, features, timestamps, mmsis):
        self._build_model(features, timestamps, mmsis, is_training=False)

        evaluations = []
        for i in range(len(self.training_objectives)):
            to = self.training_objectives[i]
            evaluations.append(to.build_evaluation(timestamps, mmsis))

        return evaluations
<|endoftext|>


<commit_before>import numpy as np

from Interpolation import *

class LagrangeInterpolation(Interpolation):

    def __init__(self, x, y):
        Interpolation.__init__(self, x, y)

    def predict(self, x):
        if not isinstance(x, np.ndarray):
            raise TypeError("Type of Parameter should be 1 dimension numpy.ndarray")
        else:
            if len(x.shape) != 1:
                raise TypeError("Type of Parameter should be 1 dimension numpy.ndarray")

        y = []
        l = np.empty(self.size)
        li = np.empty(self.size - 1)
        for xi in x:
            lNume = np.linspace(xi, xi, self.size) - self.x[0]
            for i in range(self.size):
                lDeno = np.linspace(self.x[0][i], self.x[0][i], self.size) - self.x[0]
                li[ : i] = lNume[ : i] / lDeno[ : i]
                li[i : ] = lNume[i + 1 : ] / lDeno[i + 1 : ]
                l[i] = li.cumprod()[-1]

            l = l.reshape(len(l), 1)

            y.append(np.dot(self.y, l)[0][0])

        return np.array(y)

<commit_msg>Fix Bug<commit_after>import numpy as np

from Interpolation import *

class LagrangeInterpolation(Interpolation):

    def __init__(self, x, y):
        Interpolation.__init__(self, x, y)

    def predict(self, x):
        if not isinstance(x, np.ndarray):
            raise TypeError("Type of Parameter should be 1 dimension numpy.ndarray")
        else:
            if len(x.shape) != 1:
                raise TypeError("Type of Parameter should be 1 dimension numpy.ndarray")

        y = []
        l = np.empty(self.size)
        l = l.reshape(self.size, 1)
        li = np.empty(self.size - 1)
        for xi in x:
            lNume = np.linspace(xi, xi, self.size) - self.x[0]
            for i in range(self.size):
                lDeno = np.linspace(self.x[0][i], self.x[0][i], self.size) - self.x[0]
                li[ : i] = lNume[ : i] / lDeno[ : i]
                li[i : ] = lNume[i + 1 : ] / lDeno[i + 1 : ]
                l[i][0] = li.cumprod()[-1]

            y.append(np.dot(self.y, l)[0][0])

        return np.array(y)

<|endoftext|>


<commit_before>import numpy as np
import uncertainties.unumpy as unp
from uncertainties.unumpy import (nominal_values as noms, std_devs as stds)
import matplotlib.pyplot as plt
import matplotlib as mpl
from scipy.optimize import curve_fit
plt.rcParams['figure.figsize'] = (12, 8)
plt.rcParams['font.size'] = 13
plt.rcParams['lines.linewidth'] = 1
csfont = {'fontname': 'Times New Roman'}

R, U, I = np.genfromtxt('data2.txt', unpack=True , skip_header=2)

I /=1000   # in Ampere

def f(U, m, n):
    return m * U + n

params, covariance = curve_fit(f, U, I)

errors = np.sqrt(np.diag(covariance))

print('m =', params[0], '+-', errors[0])
print('n =', params[1], '+-', errors[1])

# m = 0.0626722441168 +- 0.001489792226
# n = -0.0571161417906 +- 0.00395286541757

x_plot = np.linspace(min(U), max(U))

plt.plot(x_plot, f(x_plot, *params), 'b-', label='linearer Fit')
plt.plot(U,I, 'rx', label='Messwerte')
plt.xlabel(r'$U \,\mathrm{V}$')
plt.ylabel(r'$I \,\mathrm{A}$')
plt.title('Messungen Gegenspannung')
plt.grid()
plt.legend()
plt.tight_layout()
plt.savefig('bilder/gegen.pdf')
plt.show()
<commit_msg>plt1 wie 2<commit_after>import numpy as np
import uncertainties.unumpy as unp
from uncertainties.unumpy import (nominal_values as noms, std_devs as stds)
import matplotlib.pyplot as plt
import matplotlib as mpl
from scipy.optimize import curve_fit
plt.rcParams['figure.figsize'] = (12, 8)
plt.rcParams['font.size'] = 13
plt.rcParams['lines.linewidth'] = 1
csfont = {'fontname': 'Times New Roman'}

R, U, I = np.genfromtxt('data2.txt', unpack=True , skip_header=2)

I /=1000   # in Ampere

def f(I, m, n):
    return m * I + n

params, covariance = curve_fit(f, I, U)

errors = np.sqrt(np.diag(covariance))

print('m =', params[0], '+-', errors[0])
print('n =', params[1], '+-', errors[1])

# m = 15.7865377557 +- 0.375264383097
# n = 0.929385148384 +- 0.0415200261762

x_plot = np.linspace(min(I), max(I))

plt.plot(x_plot, f(x_plot, *params), 'b-', label='linearer Fit')
plt.plot(I,U, 'rx', label='Messwerte')
plt.ylabel(r'$U \,\mathrm{V}$')
plt.xlabel(r'$I \,\mathrm{A}$')
# plt.title('Messungen Gegenspannung')
plt.grid()
plt.legend()
plt.tight_layout()
plt.savefig('bilder/gegen.pdf')
plt.show()
<|endoftext|>


<commit_before># Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from contextlib import contextmanager
from argparse import ArgumentParser, ArgumentTypeError
from fontmake import __version__
from fontmake.font_project import FontProject
from fontmake.errors import FontmakeError

class PyClassType(object):
    """ Callable object which returns a Python class defined in named module.
    It can be passed as type= argument to ArgumentParser.add_argument().
    """

    def __init__(self, class_name):
        self.class_name = class_name

    def __call__(self, module_name):
        import importlib
        import inspect

        try:
            mod = importlib.import_module(module_name)
        except ImportError:
            raise ArgumentTypeError("No module named %r" % module_name)

        try:
            klass = getattr(mod, self.class_name)
        except AttributeError as e:
            raise ArgumentTypeError("Module %r has no attribute %r"
                                    % (module_name, self.class_name))

        if not inspect.isclass(klass):
            raise ArgumentTypeError("%r is not a class: %r"
                                    % (self.class_name, type(klass)))
        return klass

def exclude_args(parser, args, excluded_args, target):
    msg = '"%s" option invalid for %s'
    for argname in excluded_args:
        if argname not in args:
            continue
        if args[argname]:
            optname = "--%s" % argname.replace("_", "-")
            parser.error(msg % (optname, target))
        del args[argname]

@contextmanager
def _make_tempdirs(parser, args):
    output = args["output"]
    tempdirs = []
    for dirname in ("master_dir", "instance_dir"):
        if args.get(dirname) == "{tmp}":
            if "ufo" in output:
                parser.error(
                    "Can't use temporary %s directory with 'ufo' output"
                    % dirname.replace("_dir", ""))
            import tempfile
            td = args[dirname] = tempfile.mkdtemp(prefix=dirname+"_")
            tempdirs.append(td)

    yield tempdirs

    if tempdirs:
        import shutil
        for td in tempdirs:
            shutil.rmtree(td)

def main(args=None):
    parser = ArgumentParser()
    parser.add_argument('--version', action='version', version=__version__)
    inputGroup = parser.add_argument_group(
        title='Input arguments',
        description='The following arguments are mutually exclusive.')
    xInputGroup = inputGroup.add_mutually_exclusive_group(required=True)
    xInputGroup.add_argument(
        '-g', '--glyphs-path', metavar='GLYPHS',
        help='Path to .glyphs source file')
    xInputGroup.add_argument(
        '-u', '--ufo-paths', nargs='+', metavar='UFO',
        help='One or more paths to UFO files')
    xInputGroup.add_argument(
        '-m', '--mm-designspace', metavar='DESIGNSPACE',
        help='Path to .designspace file')

    outputGroup = parser.add_argument_group(title='Output arguments')
    outputGroup.add_argument(
        '-o', '--output', nargs='+', default=('otf', 'ttf'), metavar="FORMAT",
        help='Output font formats. Choose between: %(choices)s. '
             'Default: otf, ttf',
        choices=('ufo', 'otf', 'ttf', 'ttf-interpolatable', 'variable'))
    outputSubGroup = outputGroup.add_mutually_exclusive_group()
    outputSubGroup.add_argument(
        '--output-path', default=None,
        help="Output font file path. Only valid when the output is a single "
        "file (e.g. input is a single UFO or output is variable font)")
    outputSubGroup.add_argument(
        '--output-dir', default=None,
        help="Output folder. By default, output folders are created in the "
        "current working directory, grouping output fonts by format.")
    outputGroup.add_argument(
        '-i', '--interpolate', nargs="?", default=False, const=True,
        metavar="INSTANCE_NAME",
        help='Interpolate masters and generate all the instances defined. '
             'To only interpolate a specific instance (or instances) that '
             'match a given "name" attribute, you can pass as argument '
             'the full instance name or a regular expression. '
             'E.g.: -i "Noto Sans Bold"; or -i ".* UI Condensed". '
             '(for Glyphs or MutatorMath sources only). ')
    outputGroup.add_argument(
        '-M', '--masters-as-instances', action='store_true',
        help='Output masters as instances')
    outputGroup.add_argument(
        '--family-name',
        help='Family name to use for masters, and to filter output instances')
    outputGroup.add_argument(
        '--round-instances', dest='round_instances', action='store_true',
        help='Apply integer rounding to all geometry when interpolating')
    outputGroup.add_argument(
        '--designspace-path', default=None,
        help='Path to output designspace file (for Glyphs sources only).')
    outputGroup.add_argument(
        '--master-dir', default=None,
        help='Directory where to write master UFO. Default: "./master_ufo". '
             'If value is "{tmp}", a temporary directory is created and '
             'removed at the end (for Glyphs sources only).')
    outputGroup.add_argument(
        '--instance-dir', default=None,
        help='Directory where to write instance UFOs. Default: '
             '"./instance_ufo". If value is "{tmp}", a temporary directory '
             'is created and removed at the end (for Glyphs sources only).')

    contourGroup = parser.add_argument_group(title='Handling of contours')
    contourGroup.add_argument(
        '--keep-overlaps', dest='remove_overlaps', action='store_false',
        help='Do not remove any overlap.')
    contourGroup.add_argument(
        '--keep-direction', dest='reverse_direction', action='store_false',
        help='Do not reverse contour direction when output is ttf or '
             'ttf-interpolatable')
    contourGroup.add_argument(
        '-e', '--conversion-error', type=float, default=None, metavar='ERROR',
        help='Maximum approximation error for cubic to quadratic conversion '
             'measured in EM')
    contourGroup.add_argument(
        '-a', '--autohint', nargs='?', const='',
        help='Run ttfautohint. Can provide arguments, quoted')

    layoutGroup = parser.add_argument_group(title='Handling of OpenType Layout')
    layoutGroup.add_argument(
        '--interpolate-binary-layout', nargs="?", default=False, const=True,
        metavar="MASTER_DIR",
        help='Interpolate layout tables from compiled master binaries. '
             'Requires Glyphs or MutatorMath source.')
    feaCompilerGroup = layoutGroup.add_mutually_exclusive_group(required=False)
    feaCompilerGroup.add_argument(
        '--use-afdko', action='store_true',
        help='Use makeOTF instead of feaLib to compile FEA.')
    feaCompilerGroup.add_argument(
        '--mti-source',
        help='Path to mtiLib .txt feature definitions (use instead of FEA)')

    glyphnamesGroup = parser.add_mutually_exclusive_group(required=False)
    glyphnamesGroup.add_argument(
        '--production-names', dest='use_production_names', action='store_true',
        help='Rename glyphs with production names if available otherwise use '
             'uninames.')
    glyphnamesGroup.add_argument(
        '--no-production-names', dest='use_production_names',
        action='store_false')

    subsetGroup = parser.add_mutually_exclusive_group(required=False)
    subsetGroup.add_argument(
        '--subset', dest='subset', action='store_true',
        help='Subset font using export flags set by glyphsLib')
    subsetGroup.add_argument(
        '--no-subset', dest='subset', action='store_false')

    subroutinizeGroup = parser.add_mutually_exclusive_group(required=False)
    subroutinizeGroup.add_argument(
        '-s', '--subroutinize', action='store_true',
        help='Optimize CFF table using compreffor (default)')
    subroutinizeGroup.add_argument(
        '-S', '--no-subroutinize', dest='subroutinize', action='store_false')

    parser.set_defaults(use_production_names=None, subset=None,
                        subroutinize=True)

    logGroup = parser.add_argument_group(title='Logging arguments')
    logGroup.add_argument(
        '--timing', action='store_true',
        help="Print the elapsed time for each steps")
    logGroup.add_argument(
        '--verbose', default='INFO', metavar='LEVEL',
        choices=('DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'),
        help='Configure the logger verbosity level. Choose between: '
             '%(choices)s. Default: INFO')
    args = vars(parser.parse_args(args))

    glyphs_path = args.pop('glyphs_path')
    ufo_paths = args.pop('ufo_paths')
    designspace_path = args.pop('mm_designspace')
    input_format = ("Glyphs" if glyphs_path else
                    "designspace" if designspace_path else
                    "UFO") + " source"

    if 'variable' in args['output']:
        if not (glyphs_path or designspace_path):
            parser.error(
                'Glyphs or designspace source required for variable font')
        exclude_args(parser, args,
                     ['interpolate', 'masters_as_instances',
                      'interpolate_binary_layout'],
                     "variable output")

    try:
        project = FontProject(timing=args.pop('timing'),
                              verbose=args.pop('verbose'))

        if glyphs_path:
            with _make_tempdirs(parser, args):
                project.run_from_glyphs(glyphs_path, **args)
            return

        exclude_args(parser, args,
                     ['family_name', 'mti_source', 'designspace_path',
                      'master_dir', 'instance_dir'],
                     input_format)
        if designspace_path:
            project.run_from_designspace(designspace_path, **args)
            return

        exclude_args(parser, args,
                     ['interpolate', 'interpolate_binary_layout',
                      'round_instances'],
                    input_format)
        project.run_from_ufos(
            ufo_paths, is_instance=args.pop('masters_as_instances'), **args)
    except FontmakeError as e:
        import sys
        sys.exit("fontmake: error: %s" % e)

if __name__ == '__main__':
    import sys
    sys.exit(main())
<commit_msg>main: add --cff-round-tolerance option to cli<commit_after># Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from contextlib import contextmanager
from argparse import ArgumentParser, ArgumentTypeError
from fontmake import __version__
from fontmake.font_project import FontProject
from fontmake.errors import FontmakeError

class PyClassType(object):
    """ Callable object which returns a Python class defined in named module.
    It can be passed as type= argument to ArgumentParser.add_argument().
    """

    def __init__(self, class_name):
        self.class_name = class_name

    def __call__(self, module_name):
        import importlib
        import inspect

        try:
            mod = importlib.import_module(module_name)
        except ImportError:
            raise ArgumentTypeError("No module named %r" % module_name)

        try:
            klass = getattr(mod, self.class_name)
        except AttributeError as e:
            raise ArgumentTypeError("Module %r has no attribute %r"
                                    % (module_name, self.class_name))

        if not inspect.isclass(klass):
            raise ArgumentTypeError("%r is not a class: %r"
                                    % (self.class_name, type(klass)))
        return klass

def exclude_args(parser, args, excluded_args, target):
    msg = '"%s" option invalid for %s'
    for argname in excluded_args:
        if argname not in args:
            continue
        if args[argname]:
            optname = "--%s" % argname.replace("_", "-")
            parser.error(msg % (optname, target))
        del args[argname]

@contextmanager
def _make_tempdirs(parser, args):
    output = args["output"]
    tempdirs = []
    for dirname in ("master_dir", "instance_dir"):
        if args.get(dirname) == "{tmp}":
            if "ufo" in output:
                parser.error(
                    "Can't use temporary %s directory with 'ufo' output"
                    % dirname.replace("_dir", ""))
            import tempfile
            td = args[dirname] = tempfile.mkdtemp(prefix=dirname+"_")
            tempdirs.append(td)

    yield tempdirs

    if tempdirs:
        import shutil
        for td in tempdirs:
            shutil.rmtree(td)

def main(args=None):
    parser = ArgumentParser()
    parser.add_argument('--version', action='version', version=__version__)
    inputGroup = parser.add_argument_group(
        title='Input arguments',
        description='The following arguments are mutually exclusive.')
    xInputGroup = inputGroup.add_mutually_exclusive_group(required=True)
    xInputGroup.add_argument(
        '-g', '--glyphs-path', metavar='GLYPHS',
        help='Path to .glyphs source file')
    xInputGroup.add_argument(
        '-u', '--ufo-paths', nargs='+', metavar='UFO',
        help='One or more paths to UFO files')
    xInputGroup.add_argument(
        '-m', '--mm-designspace', metavar='DESIGNSPACE',
        help='Path to .designspace file')

    outputGroup = parser.add_argument_group(title='Output arguments')
    outputGroup.add_argument(
        '-o', '--output', nargs='+', default=('otf', 'ttf'), metavar="FORMAT",
        help='Output font formats. Choose between: %(choices)s. '
             'Default: otf, ttf',
        choices=('ufo', 'otf', 'ttf', 'ttf-interpolatable', 'variable'))
    outputSubGroup = outputGroup.add_mutually_exclusive_group()
    outputSubGroup.add_argument(
        '--output-path', default=None,
        help="Output font file path. Only valid when the output is a single "
        "file (e.g. input is a single UFO or output is variable font)")
    outputSubGroup.add_argument(
        '--output-dir', default=None,
        help="Output folder. By default, output folders are created in the "
        "current working directory, grouping output fonts by format.")
    outputGroup.add_argument(
        '-i', '--interpolate', nargs="?", default=False, const=True,
        metavar="INSTANCE_NAME",
        help='Interpolate masters and generate all the instances defined. '
             'To only interpolate a specific instance (or instances) that '
             'match a given "name" attribute, you can pass as argument '
             'the full instance name or a regular expression. '
             'E.g.: -i "Noto Sans Bold"; or -i ".* UI Condensed". '
             '(for Glyphs or MutatorMath sources only). ')
    outputGroup.add_argument(
        '-M', '--masters-as-instances', action='store_true',
        help='Output masters as instances')
    outputGroup.add_argument(
        '--family-name',
        help='Family name to use for masters, and to filter output instances')
    outputGroup.add_argument(
        '--round-instances', dest='round_instances', action='store_true',
        help='Apply integer rounding to all geometry when interpolating')
    outputGroup.add_argument(
        '--designspace-path', default=None,
        help='Path to output designspace file (for Glyphs sources only).')
    outputGroup.add_argument(
        '--master-dir', default=None,
        help='Directory where to write master UFO. Default: "./master_ufo". '
             'If value is "{tmp}", a temporary directory is created and '
             'removed at the end (for Glyphs sources only).')
    outputGroup.add_argument(
        '--instance-dir', default=None,
        help='Directory where to write instance UFOs. Default: '
             '"./instance_ufo". If value is "{tmp}", a temporary directory '
             'is created and removed at the end (for Glyphs sources only).')

    contourGroup = parser.add_argument_group(title='Handling of contours')
    contourGroup.add_argument(
        '--keep-overlaps', dest='remove_overlaps', action='store_false',
        help='Do not remove any overlap.')
    contourGroup.add_argument(
        '--keep-direction', dest='reverse_direction', action='store_false',
        help='Do not reverse contour direction when output is ttf or '
             'ttf-interpolatable')
    contourGroup.add_argument(
        '-e', '--conversion-error', type=float, default=None, metavar='ERROR',
        help='Maximum approximation error for cubic to quadratic conversion '
             'measured in EM')
    contourGroup.add_argument(
        '-a', '--autohint', nargs='?', const='',
        help='Run ttfautohint. Can provide arguments, quoted')
    contourGroup.add_argument(
        '--cff-round-tolerance', type=float, default=None, metavar='FLOAT',
        help='Restrict rounding of point coordinates in CFF table to only '
             'those floats whose absolute difference from their integral part '
             'is less than or equal to the tolerance. By default, all floats '
             'are rounded to integer (tolerance 0.5); 0 disables rounding.'
    )

    layoutGroup = parser.add_argument_group(title='Handling of OpenType Layout')
    layoutGroup.add_argument(
        '--interpolate-binary-layout', nargs="?", default=False, const=True,
        metavar="MASTER_DIR",
        help='Interpolate layout tables from compiled master binaries. '
             'Requires Glyphs or MutatorMath source.')
    feaCompilerGroup = layoutGroup.add_mutually_exclusive_group(required=False)
    feaCompilerGroup.add_argument(
        '--use-afdko', action='store_true',
        help='Use makeOTF instead of feaLib to compile FEA.')
    feaCompilerGroup.add_argument(
        '--mti-source',
        help='Path to mtiLib .txt feature definitions (use instead of FEA)')

    glyphnamesGroup = parser.add_mutually_exclusive_group(required=False)
    glyphnamesGroup.add_argument(
        '--production-names', dest='use_production_names', action='store_true',
        help='Rename glyphs with production names if available otherwise use '
             'uninames.')
    glyphnamesGroup.add_argument(
        '--no-production-names', dest='use_production_names',
        action='store_false')

    subsetGroup = parser.add_mutually_exclusive_group(required=False)
    subsetGroup.add_argument(
        '--subset', dest='subset', action='store_true',
        help='Subset font using export flags set by glyphsLib')
    subsetGroup.add_argument(
        '--no-subset', dest='subset', action='store_false')

    subroutinizeGroup = parser.add_mutually_exclusive_group(required=False)
    subroutinizeGroup.add_argument(
        '-s', '--subroutinize', action='store_true',
        help='Optimize CFF table using compreffor (default)')
    subroutinizeGroup.add_argument(
        '-S', '--no-subroutinize', dest='subroutinize', action='store_false')

    parser.set_defaults(use_production_names=None, subset=None,
                        subroutinize=True)

    logGroup = parser.add_argument_group(title='Logging arguments')
    logGroup.add_argument(
        '--timing', action='store_true',
        help="Print the elapsed time for each steps")
    logGroup.add_argument(
        '--verbose', default='INFO', metavar='LEVEL',
        choices=('DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'),
        help='Configure the logger verbosity level. Choose between: '
             '%(choices)s. Default: INFO')
    args = vars(parser.parse_args(args))

    glyphs_path = args.pop('glyphs_path')
    ufo_paths = args.pop('ufo_paths')
    designspace_path = args.pop('mm_designspace')
    input_format = ("Glyphs" if glyphs_path else
                    "designspace" if designspace_path else
                    "UFO") + " source"

    if 'variable' in args['output']:
        if not (glyphs_path or designspace_path):
            parser.error(
                'Glyphs or designspace source required for variable font')
        exclude_args(parser, args,
                     ['interpolate', 'masters_as_instances',
                      'interpolate_binary_layout'],
                     "variable output")

    try:
        project = FontProject(timing=args.pop('timing'),
                              verbose=args.pop('verbose'))

        if glyphs_path:
            with _make_tempdirs(parser, args):
                project.run_from_glyphs(glyphs_path, **args)
            return

        exclude_args(parser, args,
                     ['family_name', 'mti_source', 'designspace_path',
                      'master_dir', 'instance_dir'],
                     input_format)
        if designspace_path:
            project.run_from_designspace(designspace_path, **args)
            return

        exclude_args(parser, args,
                     ['interpolate', 'interpolate_binary_layout',
                      'round_instances'],
                    input_format)
        project.run_from_ufos(
            ufo_paths, is_instance=args.pop('masters_as_instances'), **args)
    except FontmakeError as e:
        import sys
        sys.exit("fontmake: error: %s" % e)

if __name__ == '__main__':
    import sys
    sys.exit(main())
<|endoftext|>


<commit_before>#!/usr/bin/env python

# Copyright (c) 2013, Carnegie Mellon University
# All rights reserved.
# Authors: Michael Koval <mkoval@cs.cmu.edu>
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# - Redistributions of source code must retain the above copyright notice, this
#   list of conditions and the following disclaimer.
# - Redistributions in binary form must reproduce the above copyright notice,
#   this list of conditions and the following disclaimer in the documentation
#   and/or other materials provided with the distribution.
# - Neither the name of Carnegie Mellon University nor the names of its
#   contributors may be used to endorse or promote products derived from this
#   software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.

import numpy

class MobileBase(object):
    def __init__(self, sim, robot):
        self.simulated = sim
        self.robot = robot

    def CloneBindings(self, parent):
        pass

    def Forward(self, meters, timeout=None):
        """
        Drives the robot forward the desired distance
        Note: Only implemented in simulation. Derived robots should implement this method.
        @param meters the distance to drive the robot
        @param timout duration to wait for execution
        """
        if self.simulated:
            with self.robot.GetEnv():
                current_pose = self.robot.GetTransform().copy()
                current_pose[:3,3] = current_pose[:3,3] + meters*current_pose[:3,0]
                self.robot.SetTransform(current_pose)
        else:
            raise NotImplementedError('DriveForward is not implemented')

    def Rotate(self, angle_rad, timeout=None):
        """
        Rotates the robot the desired distance
        @param angle_rad the number of radians to rotate
        @param timeout duration to wait for execution
        """
        if self.simulated:
            with self.robot.GetEnv():
                current_pose_in_world = self.robot.GetTransform().copy()
                desired_pose_in_herb = numpy.array([[numpy.cos(angle_rad), -numpy.sin(angle_rad), 0, 0],
                                                    [numpy.sin(angle_rad), numpy.cos(angle_rad), 0, 0],
                                                    [0, 0, 1, 0],
                                                    [0, 0, 0, 1]])
                desired_pose_in_world = numpy.dot(current_pose_in_world, desired_pose_in_herb)
                self.robot.SetTransform(desired_pose_in_world)
        else:
            raise NotImplementedError('Rotate is not implemented')

    def DriveStraightUntilForce(robot, direction, velocity=0.1, force_threshold=3.0,
                                max_distance=None, timeout=None, left_arm=True, right_arm=True):
        """
        Drive the base in a direction until a force/torque sensor feels a force. The
        base first turns to face the desired direction, then drives forward at the
        specified velocity. The action terminates when max_distance is reached, the
        timeout is exceeded, or if a force is felt. The maximum distance and timeout
        can be disabled by setting the corresponding parameters to None.
        @param direction forward direction of motion in the world frame
        @param velocity desired forward velocity
        @param force_threshold threshold force in Newtons
        @param max_distance maximum distance in meters
        @param timeout maximum duration in seconds
        @param left_arm flag to use the left force/torque sensor
        @param right_arm flag to use the right force/torque sensor
        @return felt_force flag indicating whether the action felt a force
        """
        if self.simulated:
            raise NotImplementedError('DriveStraightUntilForce does not work in simulation')
        else:
            raise NotImplementedError('DriveStraightUntilForce is not implemented')
<commit_msg>fixed function signature in mobilebase<commit_after>#!/usr/bin/env python

# Copyright (c) 2013, Carnegie Mellon University
# All rights reserved.
# Authors: Michael Koval <mkoval@cs.cmu.edu>
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# - Redistributions of source code must retain the above copyright notice, this
#   list of conditions and the following disclaimer.
# - Redistributions in binary form must reproduce the above copyright notice,
#   this list of conditions and the following disclaimer in the documentation
#   and/or other materials provided with the distribution.
# - Neither the name of Carnegie Mellon University nor the names of its
#   contributors may be used to endorse or promote products derived from this
#   software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.

import numpy

class MobileBase(object):
    def __init__(self, sim, robot):
        self.simulated = sim
        self.robot = robot

    def CloneBindings(self, parent):
        pass

    def Forward(self, meters, timeout=None):
        """
        Drives the robot forward the desired distance
        Note: Only implemented in simulation. Derived robots should implement this method.
        @param meters the distance to drive the robot
        @param timout duration to wait for execution
        """
        if self.simulated:
            with self.robot.GetEnv():
                current_pose = self.robot.GetTransform().copy()
                current_pose[:3,3] = current_pose[:3,3] + meters*current_pose[:3,0]
                self.robot.SetTransform(current_pose)
        else:
            raise NotImplementedError('DriveForward is not implemented')

    def Rotate(self, angle_rad, timeout=None):
        """
        Rotates the robot the desired distance
        @param angle_rad the number of radians to rotate
        @param timeout duration to wait for execution
        """
        if self.simulated:
            with self.robot.GetEnv():
                current_pose_in_world = self.robot.GetTransform().copy()
                desired_pose_in_herb = numpy.array([[numpy.cos(angle_rad), -numpy.sin(angle_rad), 0, 0],
                                                    [numpy.sin(angle_rad), numpy.cos(angle_rad), 0, 0],
                                                    [0, 0, 1, 0],
                                                    [0, 0, 0, 1]])
                desired_pose_in_world = numpy.dot(current_pose_in_world, desired_pose_in_herb)
                self.robot.SetTransform(desired_pose_in_world)
        else:
            raise NotImplementedError('Rotate is not implemented')

    def DriveStraightUntilForce(self, direction, velocity=0.1, force_threshold=3.0,
                                max_distance=None, timeout=None, left_arm=True, right_arm=True):
        """
        Drive the base in a direction until a force/torque sensor feels a force. The
        base first turns to face the desired direction, then drives forward at the
        specified velocity. The action terminates when max_distance is reached, the
        timeout is exceeded, or if a force is felt. The maximum distance and timeout
        can be disabled by setting the corresponding parameters to None.
        @param direction forward direction of motion in the world frame
        @param velocity desired forward velocity
        @param force_threshold threshold force in Newtons
        @param max_distance maximum distance in meters
        @param timeout maximum duration in seconds
        @param left_arm flag to use the left force/torque sensor
        @param right_arm flag to use the right force/torque sensor
        @return felt_force flag indicating whether the action felt a force
        """
        if self.simulated:
            raise NotImplementedError('DriveStraightUntilForce does not work in simulation')
        else:
            raise NotImplementedError('DriveStraightUntilForce is not implemented')
<|endoftext|>


<commit_before>from woodpecker.io.generators.basegenerator import BaseGenerator

class HttpSequenceGenerator(BaseGenerator):
    def generate(self):
        pass
<commit_msg>Added core sequence generation method Timings and auto-assertions are still to be implemented<commit_after>import os
import copy
import six

from woodpecker.io.generators.basegenerator import BaseGenerator

class HttpSequenceGenerator(BaseGenerator):
    def generate(self, filename, sequence_name='NewSequence', **kwargs):
        self._generate_headers()
        self._generate_class_definition(sequence_name)
        self._generate_calls(**kwargs)

        with open(os.path.abspath(filename), 'w') as fp:
            fp.write(self._fix_code())

    def _generate_headers(self):
        self.buffer.write(
            'from woodpecker.sequences.httpsequence import HttpSequence'
        )
        self.buffer.write('\n\n')

    def _generate_class_definition(self, sequence_name):
        self.buffer.write(
            'class {classname}(HttpSequence):\n'.format(
                classname=sequence_name
            )
        )

    def _generate_calls(self,
                        group_resources=True,
                        auto_assert=True,
                        new_sequence_threshold=7.0,
                        async_request_threshold=0.1):
        # Generate steps call
        self.buffer.write('    def steps(self):\n')

        previous_entry = None
        for entry in six.viewvalues(self._parsed_entries):
            self._generate_single_entry(entry,
                                        previous_entry,
                                        group_resources,
                                        auto_assert,
                                        new_sequence_threshold,
                                        async_request_threshold,
                                        False)
            self.buffer.write('\n')
            previous_entry = copy.deepcopy(entry)
            if not group_resources and len(entry.resources) > 0:
                self.buffer.write('        self.start_async_pool()\n\n')
                for resource in entry.resources:
                    self._generate_single_entry(resource,
                                                previous_entry,
                                                group_resources,
                                                auto_assert,
                                                new_sequence_threshold,
                                                async_request_threshold,
                                                True)
                self.buffer.write('        self.end_async_pool()\n\n')

    def _generate_single_entry(self,
                               entry,
                               previous_entry,
                               group_resources,
                               auto_assert,
                               new_sequence_threshold,
                               async_request_threshold,
                               _async):
        # Write the call according to the method
        if entry.method.upper() in ('GET', 'POST', 'PUT', 'PATCH', 'DELETE'):
            self.buffer.write(
                '        self.{async}{method}('.format(
                    async='async_' if _async else '',
                    method=entry.method.lower()
                )
            )
            # Write the URL
            self.buffer.write("'{url}'\n".format(url=entry.url))
            self.buffer.write(', ')
        else:
            self.buffer.write(
                '        self.http_request('
            )
            # Write the URL
            self.buffer.write("'{url}'\n".format(url=entry.url))
            self.buffer.write(", method='{method}', ".format(
                method=entry.method.upper()
            ))

        # Check if URL is resource
        if entry.mime_type() in (
            'text/css',
            'application/javascript',
            'image/png'
            'image/jpeg'
            'image/gif',
            'image/tiff'
        ):
            self.buffer.write('is_resource=True, ')

        # If auto assert is true, perform some checks on the entry response
        # text to perform a semi-intelligent assert
        # TODO: add automatic assert feature

        # If group resources is true, group them in the with_resources clause
        if group_resources and len(entry.resources) > 0:
            self.buffer.write('with_resources=(')
            for resource in entry.resources:
                if resource.method == 'GET':
                    self.buffer.write("'{url}'".format(url=resource.url))
                else:
                    self.buffer.write("('{url}', '{method}')")
                self.buffer.write(',')
            self.buffer.write(')')

        # Close the method call
        self.buffer.write(')\n\n')
<|endoftext|>


<commit_before>from scipy.sparse import isspmatrix_csc, isspmatrix_csr, isspmatrix, spdiags
import _superlu

try:
    import umfpack
    isUmfpack = True
except:
    isUmfpack = False
useUmfpack = True

def _toCS_superLU( A ):
    if hasattr(A, 'tocsc') and not isspmatrix_csr( A ):
        mat = A.tocsc()
        csc = 1
    elif hasattr(A, 'tocsr'):
        mat = A.tocsr()
        csc = 0
    else:
        raise ValueError, "matrix cannot be converted to CSC/CSR"
    return mat, csc

def _toCS_umfpack( A ):
    if isspmatrix_csr( A ) or isspmatrix_csc( A ):
        mat = A
    else:
        if hasattr(A, 'tocsc'):
            mat = A.tocsc()
        elif hasattr(A, 'tocsr'):
            mat = A.tocsr()
        else:
            raise ValueError, "matrix cannot be converted to CSC/CSR"
    return mat

def spsolve(A, b, permc_spec=2):
    if not hasattr(A, 'tocsr') and not hasattr(A, 'tocsc'):
        raise ValueError, "sparse matrix must be able to return CSC format--"\
              "A.tocsc()--or CSR format--A.tocsr()"
    if not hasattr(A, 'shape'):
        raise ValueError, "sparse matrix must be able to return shape" \
                " (rows, cols) = A.shape"
    M, N = A.shape
    if (M != N):
        raise ValueError, "matrix must be square"

    if isUmfpack and useUmfpack:
        mat = _toCS_umfpack( A )

        if mat.dtype.char not in 'dD':
            raise ValueError, "convert matrix data to double, please, using"\
                  " .astype(), or set sparse.useUmfpack = False"

        family = {'d' : 'di', 'D' : 'zi'}
        umf = umfpack.UmfpackContext( family[mat.dtype.char] )
        return umf.linsolve( umfpack.UMFPACK_A, mat, b, autoTranspose = True )

    else:
        mat, csc = _toCS_superLU( A )
        ftype, lastel, data, index0, index1 = \
               mat.ftype, mat.nnz, mat.data, mat.rowind, mat.indptr
        gssv = eval('_superlu.' + ftype + 'gssv')
        print "data-ftype: %s compared to data %s" % (ftype, data.dtype.char)
        print "Calling _superlu.%sgssv" % ftype
        return gssv(N, lastel, data, index0, index1, b, csc, permc_spec)[0]

def splu(A, permc_spec=2, diag_pivot_thresh=1.0,
         drop_tol=0.0, relax=1, panel_size=10):
    M, N = A.shape
    if (M != N):
        raise ValueError, "can only factor square matrices"

##     if isUmfpack:
##         print "UMFPACK is present - try umfpack.numeric and umfpack.solve instead!"

    csc = A.tocsc()
    gstrf = eval('_superlu.' + csc.ftype + 'gstrf')
    return gstrf(N, csc.nnz, csc.data, csc.rowind, csc.indptr, permc_spec,
                 diag_pivot_thresh, drop_tol, relax, panel_size)

def _testme():
    from scipy.sparse import csc_matrix, dok_matrix
    from numpy import transpose, array, arange

    print "Inverting a sparse linear system:"
    print "The sparse matrix (constructed from diagonals):"
    a = spdiags([[1, 2, 3, 4, 5], [6, 5, 8, 9, 10]], [0, 1], 5, 5)
    b = array([1, 2, 3, 4, 5])
    print "Solve: single precision complex:"
    globals()['useUmfpack'] = False
    a = a.astype('F')
    x = spsolve(a, b)
    print x
    print "Error: ", a*x-b

    print "Solve: double precision complex:"
    globals()['useUmfpack'] = True
    a = a.astype('D')
    x = spsolve(a, b)
    print x
    print "Error: ", a*x-b

    print "Solve: double precision:"
    a = a.astype('d')
    x = spsolve(a, b)
    print x
    print "Error: ", a*x-b

    print "Solve: single precision:"
    globals()['useUmfpack'] = False
    a = a.astype('f')
    x = spsolve(a, b.astype('f'))
    print x
    print "Error: ", a*x-b

if __name__ == "__main__":
    _testme()
<commit_msg>Fixed linsolve.py docstring<commit_after>from scipy.sparse import isspmatrix_csc, isspmatrix_csr, isspmatrix, spdiags
import _superlu

try:
    import umfpack
    isUmfpack = True
except:
    isUmfpack = False
useUmfpack = True

def _toCS_superLU( A ):
    if hasattr(A, 'tocsc') and not isspmatrix_csr( A ):
        mat = A.tocsc()
        csc = 1
    elif hasattr(A, 'tocsr'):
        mat = A.tocsr()
        csc = 0
    else:
        raise ValueError, "matrix cannot be converted to CSC/CSR"
    return mat, csc

def _toCS_umfpack( A ):
    if isspmatrix_csr( A ) or isspmatrix_csc( A ):
        mat = A
    else:
        if hasattr(A, 'tocsc'):
            mat = A.tocsc()
        elif hasattr(A, 'tocsr'):
            mat = A.tocsr()
        else:
            raise ValueError, "matrix cannot be converted to CSC/CSR"
    return mat

def spsolve(A, b, permc_spec=2):
    if not hasattr(A, 'tocsr') and not hasattr(A, 'tocsc'):
        raise ValueError, "sparse matrix must be able to return CSC format--"\
              "A.tocsc()--or CSR format--A.tocsr()"
    if not hasattr(A, 'shape'):
        raise ValueError, "sparse matrix must be able to return shape" \
                " (rows, cols) = A.shape"
    M, N = A.shape
    if (M != N):
        raise ValueError, "matrix must be square"

    if isUmfpack and useUmfpack:
        mat = _toCS_umfpack( A )

        if mat.dtype.char not in 'dD':
            raise ValueError, "convert matrix data to double, please, using"\
                  " .astype(), or set linsolve.useUmfpack = False"

        family = {'d' : 'di', 'D' : 'zi'}
        umf = umfpack.UmfpackContext( family[mat.dtype.char] )
        return umf.linsolve( umfpack.UMFPACK_A, mat, b, autoTranspose = True )

    else:
        mat, csc = _toCS_superLU( A )
        ftype, lastel, data, index0, index1 = \
               mat.ftype, mat.nnz, mat.data, mat.rowind, mat.indptr
        gssv = eval('_superlu.' + ftype + 'gssv')
        print "data-ftype: %s compared to data %s" % (ftype, data.dtype.char)
        print "Calling _superlu.%sgssv" % ftype
        return gssv(N, lastel, data, index0, index1, b, csc, permc_spec)[0]

def splu(A, permc_spec=2, diag_pivot_thresh=1.0,
         drop_tol=0.0, relax=1, panel_size=10):
    M, N = A.shape
    if (M != N):
        raise ValueError, "can only factor square matrices"

##     if isUmfpack:
##         print "UMFPACK is present - try umfpack.numeric and umfpack.solve instead!"

    csc = A.tocsc()
    gstrf = eval('_superlu.' + csc.ftype + 'gstrf')
    return gstrf(N, csc.nnz, csc.data, csc.rowind, csc.indptr, permc_spec,
                 diag_pivot_thresh, drop_tol, relax, panel_size)

def _testme():
    from scipy.sparse import csc_matrix, dok_matrix
    from numpy import transpose, array, arange

    print "Inverting a sparse linear system:"
    print "The sparse matrix (constructed from diagonals):"
    a = spdiags([[1, 2, 3, 4, 5], [6, 5, 8, 9, 10]], [0, 1], 5, 5)
    b = array([1, 2, 3, 4, 5])
    print "Solve: single precision complex:"
    globals()['useUmfpack'] = False
    a = a.astype('F')
    x = spsolve(a, b)
    print x
    print "Error: ", a*x-b

    print "Solve: double precision complex:"
    globals()['useUmfpack'] = True
    a = a.astype('D')
    x = spsolve(a, b)
    print x
    print "Error: ", a*x-b

    print "Solve: double precision:"
    a = a.astype('d')
    x = spsolve(a, b)
    print x
    print "Error: ", a*x-b

    print "Solve: single precision:"
    globals()['useUmfpack'] = False
    a = a.astype('f')
    x = spsolve(a, b.astype('f'))
    print x
    print "Error: ", a*x-b

if __name__ == "__main__":
    _testme()
<|endoftext|>


<commit_before>import os, sys, zipfile

dbfarm = os.environ['GDK_DBFARM']
db = os.path.join(dbfarm, os.environ['TSTDB'])
archive = os.path.join(dbfarm, 'prevchainrel.zip')
rev = os.getenv('REVISION')

if not os.path.exists(db):
    print >> sys.stderr, 'database directory %s does not exist' % db
    sys.exit(1)

try:
    f = open(os.path.join(db, 'bat', 'BACKUP', 'SUBCOMMIT', 'BBP.dir'), 'rU')
except IOError:
    try:
        f = open(os.path.join(db, 'bat', 'BACKUP', 'BBP.dir'), 'rU')
    except IOError:
        f = open(os.path.join(db, 'bat', 'BBP.dir'), 'rU')
hdr = f.readline()
ptroid = f.readline()
ptr, oid, hge = ptroid.split()
f.close()

z = zipfile.ZipFile(archive)
comment = z.comment
z.close()

try:
    # try to create compressed zip file
    z = zipfile.ZipFile(os.path.join(dbfarm, 'newchainrel.zip'), 'w',
                        zipfile.ZIP_DEFLATED)
except RuntimeError:
    # if that fails, create uncompressed zip file
    z = zipfile.ZipFile(os.path.join(dbfarm, 'newchainrel.zip'), 'w')

if rev:
    revcomment = ' (hg id %s)' % rev
else:
    revcomment = ''
z.comment = comment + 'Chained on host %s%s.\n' % (os.getenv('HOSTNAME', 'unknown'), revcomment)

for root, dirs, files in os.walk(db):
    for f in files:
        ff = os.path.join(root, f)
        z.write(ff, ff[len(db) + len(os.sep):].replace(os.sep, '/'))

z.close()
<commit_msg>Add comment about largest integer size.<commit_after>import os, sys, zipfile

dbfarm = os.environ['GDK_DBFARM']
db = os.path.join(dbfarm, os.environ['TSTDB'])
archive = os.path.join(dbfarm, 'prevchainrel.zip')
rev = os.getenv('REVISION')

if not os.path.exists(db):
    print >> sys.stderr, 'database directory %s does not exist' % db
    sys.exit(1)

try:
    f = open(os.path.join(db, 'bat', 'BACKUP', 'SUBCOMMIT', 'BBP.dir'), 'rU')
except IOError:
    try:
        f = open(os.path.join(db, 'bat', 'BACKUP', 'BBP.dir'), 'rU')
    except IOError:
        f = open(os.path.join(db, 'bat', 'BBP.dir'), 'rU')
hdr = f.readline()
ptroid = f.readline()
ptr, oid, hge = ptroid.split()
f.close()

z = zipfile.ZipFile(archive)
comment = z.comment
z.close()

try:
    # try to create compressed zip file
    z = zipfile.ZipFile(os.path.join(dbfarm, 'newchainrel.zip'), 'w',
                        zipfile.ZIP_DEFLATED)
except RuntimeError:
    # if that fails, create uncompressed zip file
    z = zipfile.ZipFile(os.path.join(dbfarm, 'newchainrel.zip'), 'w')

if rev:
    revcomment = ' (hg id %s)' % rev
else:
    revcomment = ''
if hge == '16' and 'largest integer size 16' not in comment:
    revcomment = ' with largest integer size 16' + revcomment
z.comment = comment + 'Chained on host %s%s.\n' % (os.getenv('HOSTNAME', 'unknown'), revcomment)

for root, dirs, files in os.walk(db):
    for f in files:
        ff = os.path.join(root, f)
        z.write(ff, ff[len(db) + len(os.sep):].replace(os.sep, '/'))

z.close()
<|endoftext|>